From a8785fa453391130e18cca9e00f4431024d02abc Mon Sep 17 00:00:00 2001 From: Florian Schmidt Date: Sun, 18 Oct 2026 09:37:00 +0200 Subject: [PATCH 1/6] docs: start forecasts at 2 %, plan the daily budget from the day start, follow the limit week The developer wants forecasts earlier, a daily budget that today's use does not shrink, and week totals that follow the limit week (D7, D8, D9). Refs #13 --- docs/decisions.md | 56 +++++++++++++++++++++++++++++++++-------------- 1 file changed, 39 insertions(+), 17 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index 8678a77..d46d897 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -154,18 +154,25 @@ probe. `t + (100 − u) · e·W / u`, is shown; it always comes before `r`. A second forecast uses the recent rate: the rise of `u` over the window's samples from the last 24 h, when they span at least 3 h. It is shown beside the average forecast, never instead of it. Forecasts start once - 10 % of the window has passed (30 min of a session, about 17 h of a week), or as soon as the - window is ahead. Before either, one hour at 1 % already "reaches" 100 % within days, which is - noise. Until forecasts start, the tile and the window chart say when they will. + 2 % of the window has passed (6 min of a session, about 3 h 22 min of a week), or as soon as + the window is ahead. Before either, a few minutes of use already "reach" 100 % within days, + which is noise. Early forecasts are rough and firm up as the window goes on. Until forecasts + start, the tile and the window chart say when they will. - **Window instance.** The samples of one window whose reset times lie within 15 minutes of each other. Claude reports resets to the minute and drifts by a minute between probes ("8pm", then "7:59pm"), so exact equality would split one week. A reset starts a new instance at 0 %. - **Days of a long window.** For a window longer than a day: today's use is `u` now minus `u` at the local start of today (the last sample of the same instance at or before it, or 0 when the instance began today). The use of each local day of the instance is computed the same way. - The even pace per day is `100 · 1 d / W`. The daily budget is `(100 − u)` divided by the days - left until `r`. A 7-day instance that resets at another time than midnight touches 8 local - dates; the first and the last are partial days and both are shown. + A day's share is the time of that day inside the instance. A 7-day instance that resets at + another time than midnight touches 8 local dates; the first and the last have shorter shares, + and both are shown. The even pace of a day is `100 · share / W`. The daily budget plans the + rest of the instance from the start of today. With `s` the local start of today, or the + instance start when that is later, and `u₀` the use at `s`, today's budget is + `(100 − u₀) · today's share / (r − s)`; use during the day does not change it. A later day's + budget is `(100 − max(u, u₀ + today's budget)) · its share / (r − end of today)`, so later days + lose budget only once today's use passes today's budget. `u₀` is measured, or estimated as + below and then marked; without it there is no budget. - **Estimates from tokens.** Where samples do not cover a span, its use is estimated from the token history. Tokens are weighted by the provider's API price ratios: Claude input 1, output 5, cache write 1.25, cache read 0.1; Codex uncached input 1, cached input 0.1, @@ -192,15 +199,21 @@ is a marked calculation from measured tokens, not a guess. **Why.** R5. A straight line from the window's start to its reset is a pace the user can check by hand. A user over pace by less than the threshold still runs out before the reset, so the date shows from the first point over pace. The day figures answer "how much of the week did I -use today" and "how much may I use per day from now on" (developer feedback, 2026-10-14). +use today" and "how much may I use per day from now on" (developer feedback, 2026-10-14). A +budget computed from `u` and the time now fell with every use, even within the day's plan, and +held a partial first day to a full day's pace; a budget set at the start of the day can be +compared with the day's bar (developer feedback, 2026-10-18). Measured samples alone left the day chart empty until the app had run for a whole week, while the token history already covers it; the estimate fills it at once and agrees with the measured use -of the instance by construction (developer feedback, 2026-10-15). A window that is ahead in -its first 10 % is no noise: a Codex week at 39 % ten hours after its reset reaches 100 % within -a day, and that is the warning the user needs (developer feedback, 2026-10-15). +of the instance by construction (developer feedback, 2026-10-15). A window that is ahead early is +no noise: a Codex week at 39 % ten hours after its reset reaches 100 % within a day, and that is +the warning the user needs (developer feedback, 2026-10-15). Starting at 10 % hid every forecast +for the first 17 h of a week, and Codex weeks that reset early spent much of their time there; +the developer prefers a rough forecast that firms up with data (developer feedback, 2026-10-18). **Gives up.** Weekday and working-hour patterns. Forecasts assume a constant rate; early in a -window, a burst that puts it ahead gives a reach date that a quiet hour moves out again. +window, a burst that puts it ahead gives a reach date that a quiet hour moves out again, and in +the first hours a forecast can move by days. Measured day figures are only as fine as the samples (D5 keeps one per hour while the value stands still). Estimates miss use from other devices and from claude.ai or the web, which counts against the limit but leaves no local tokens; they also miss changes in model mix within @@ -221,8 +234,13 @@ an instance and any weighting the provider applies beyond the price ratios. running in the tray. Starting the app opens the stats panel (R4). Start with the OS is an opt-in setting. - **Panel (R4).** It leads with one tile per limit window: used percent, pace, the forecasts of - [D7](#d7--pace) and, for windows longer than a day, today's use and the daily budget. Then - follow the per-day use of the long windows, token totals and charts, one window chart per limit + [D7](#d7--pace) and, for windows longer than a day, today's use and the daily budget. Tiles of + one window kind show the same rows in the same order; a value that is not known yet shows a + muted placeholder that says why or from when. Then follow the per-day use of the long + windows, with each day's even pace and budget for its share and the instance start and reset + marked on the first and last day; token totals for today, the current session and the week of + [D9](#d9--the-snapshot-file-is-the-apps-only-output-to-other-processes), each saying since + when; charts, one window chart per limit window, and the top entries by model and by project, with the rest folded into an expandable "Other". A window chart is a burn-up of one instance from its start to its reset: the used percent as a line (measured, or estimated before the first sample), the even-pace diagonal @@ -251,15 +269,19 @@ chart library would add reflection and size for three chart types. ([D5](#d5--own-history-store)). It carries a schema version `v` (1 to begin with), the time it was made, the refresh interval, the path of the app's executable and, per provider, its status and reason, its limit windows (used percent, reset, length, pace state, delta and projection) -and its token totals for today, the current session window and the current week. The DTOs and -their source-generated JSON context live in `FinalToken.Core`, shared by the app, the CLI and the -Stream Deck plugin. Nothing listens on a socket or runs an HTTP server. A reader treats a +and its token totals for today, the current session window and the current week, with the +week's start and the id of the limit window it follows (`weekStart`, `weekWindow`). The week is +the current instance of the provider's weekly limit: its longest window over a day whose label +names no model family. Without one, it is the local calendar week from Monday, and `weekWindow` +is absent. The DTOs and their source-generated JSON context live in `FinalToken.Core`, shared by +the app, the CLI and the Stream Deck plugin. Nothing listens on a socket or runs an HTTP server. A reader treats a snapshot older than three refresh intervals as stale. The app gives the engine its own path; a CLI refresh keeps the path already in the snapshot, and a snapshot without one has none, so a reader never mistakes its own path for the app's. **Why.** R6 needs the stats outside the app. A file has no network surface, and it survives a -restart of either side. +restart of either side. Beside the limit tiles, "this week" reads as the limit's week, not the +calendar week (developer feedback, 2026-10-18). **Gives up.** Updates faster than the reader's poll interval. -- 2.54.0 From 941a597680bd891e5ba7137b5b0ebb6ca2958a41 Mon Sep 17 00:00:00 2001 From: Florian Schmidt Date: Sun, 18 Oct 2026 09:55:41 +0200 Subject: [PATCH 2/6] core: plan the daily budget per day, start forecasts at 2 % and follow the limit week The budget was the rest of the week over the time left, so each use today lowered it and a partial first day was held to a full day. Now each day of the instance has its share, its even pace and its budget. Today's budget starts from the use at the day start and does not move with today's use (D7). Forecasts start at 2 % of a window, so an early reset no longer hides them for most of a day. Limit tiles of one kind show the same rows, with placeholders that say why a value is missing. The week chart draws per-day steps and marks the instance start and reset (D8). Week token totals follow the provider's limit week and say since when, with the calendar week as fallback (D9). Refs #13 --- src/FinalToken.App/AGENTS.md | 5 +- src/FinalToken.App/Charts.cs | 62 ++++++++---- src/FinalToken.App/DataTooltip.cs | 3 + src/FinalToken.App/PanelViewModel.cs | 2 + src/FinalToken.App/PanelWindow.cs | 56 ++++++----- src/FinalToken.Cli/CliApplication.cs | 2 + src/FinalToken.Core/AGENTS.md | 3 +- src/FinalToken.Core/HistoryStore.cs | 9 +- src/FinalToken.Core/LimitAnalysis.cs | 6 +- src/FinalToken.Core/LimitDays.cs | 41 ++++++++ src/FinalToken.Core/LimitEstimates.cs | 3 +- src/FinalToken.Core/Pace.cs | 4 +- src/FinalToken.Core/RefreshEngine.cs | 7 +- src/FinalToken.Core/Snapshot.cs | 3 +- tests/FinalToken.App.Tests/HeadlessTests.cs | 59 ++++++++++- tests/FinalToken.App.Tests/ViewModelTests.cs | 25 ++++- tests/FinalToken.Cli.Tests/CliTests.cs | 18 ++++ tests/FinalToken.Core.Tests/DayBudgetTests.cs | 98 +++++++++++++++++++ .../EarlyForecastTests.cs | 17 +++- .../LimitAnalysisTests.cs | 2 +- .../TokenEstimateTests.cs | 4 +- .../FinalToken.Core.Tests/WeekTotalsTests.cs | 59 +++++++++++ 22 files changed, 422 insertions(+), 66 deletions(-) create mode 100644 src/FinalToken.Core/LimitDays.cs create mode 100644 tests/FinalToken.Core.Tests/DayBudgetTests.cs create mode 100644 tests/FinalToken.Core.Tests/WeekTotalsTests.cs diff --git a/src/FinalToken.App/AGENTS.md b/src/FinalToken.App/AGENTS.md index 524869f..85beac7 100644 --- a/src/FinalToken.App/AGENTS.md +++ b/src/FinalToken.App/AGENTS.md @@ -30,7 +30,7 @@ Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root. Slots in order: dark `#3987e5 #d95926 #199e70 #c98500 #d55181 #9085e9`; light `#2a78d6 #eb6834 #1baf7a #eda100 #e87ba4 #6250d6`. Other is muted. - Status chips always have icon and label: `#0ca30c` ✓ On track, `#ec835a` ▲ Ahead, - `#fab219` ▼ Behind. Forecasts start at 10% elapsed or as soon as Ahead, using the configured pace (D7); + `#fab219` ▼ Behind. Forecasts start at 2% elapsed or as soon as Ahead, using the configured pace (D7); until then, tiles and window charts show the Core forecast start time. Dates remain visible for every positive pace delta, but only Ahead gets the critical `#d03b3b` mark and ⚠. Other states say "At this pace 100 % on …" in secondary ink. Text paragraphs stay in ink colours; colour belongs to marks and meters. @@ -41,7 +41,8 @@ Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root. - Show one composition legend in the Tokens header. Cache reads are neutral; input/output/cache write use full/65%/40% provider colour. Reasoning is part of output; Codex cache read is part of input. Never add either subset twice. -- Week charts show dashed muted even pace and thin solid secondary budget, with labels beside +- Week charts show per-day steps: dashed muted even pace, and thin solid secondary budget from + today onward. Mark partial start and reset times. Keep labels beside their own right endpoints and separated when close. No known day values means a collecting message. Use CalendarDays, including partial dates at both ends of a window (D7). Use `LimitAnalysis.SameInstance` for reset membership, history gaps and previous-window lookup; diff --git a/src/FinalToken.App/Charts.cs b/src/FinalToken.App/Charts.cs index 9ca53c5..403d1b3 100644 --- a/src/FinalToken.App/Charts.cs +++ b/src/FinalToken.App/Charts.cs @@ -183,21 +183,25 @@ public sealed class CompositionBar(TokenCounts counts, Provider provider, bool i } } -public sealed class DailyLimitChart(WindowDays days, Provider provider) : Control +public sealed class DailyLimitChart(WindowDays days, Provider provider, TimeProvider? clock = null) : Control { + private readonly TimeProvider clock = clock ?? TimeProvider.System; private readonly List<(Rect Rect, Func Tip)> hits = []; public DailyLimitChart() : this(new([], [], null, 0, null), Provider.Claude) { } + public IReadOnlyList AxisLabels => days.Current.Select((day, i) => day.Start.DateTime.ToString("ddd") + + (i == 0 && days.InstanceStart is { } start && start != CalendarDays.Start(start, clock.LocalTimeZone) ? "\nfrom " + Display.Time(start, clock) : "") + + (i == days.Current.Count - 1 && days.Reset is { } reset && reset != CalendarDays.Start(reset, clock.LocalTimeZone) ? "\nreset " + Display.Time(reset, clock) : "")).ToArray(); protected override void OnInitialized() { - base.OnInitialized(); Height = 248; ToolTip.SetShowDelay(this, 0); + base.OnInitialized(); Height = 264; ToolTip.SetShowDelay(this, 0); PointerMoved += (_, e) => ToolTip.SetTip(this, hits.LastOrDefault(h => h.Rect.Contains(e.GetPosition(this))).Tip?.Invoke()); } public override void Render(DrawingContext context) { base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size)); hits.Clear(); var dark = Ui.Dark(this); var ink = Ui.Colour("Muted", dark); var colour = Ui.ProviderColour(provider, dark); - var plot = new Rect(40, 24, Math.Max(1, Bounds.Width - 174), Math.Max(1, Bounds.Height - 60)); - var maximum = Math.Max(days.EvenPace, Math.Max(days.DailyBudget ?? 0, days.Current.Concat(days.Previous).Select(d => d.Used ?? 0).DefaultIfEmpty(0).Max())); + var plot = new Rect(40, 24, Math.Max(1, Bounds.Width - 174), Math.Max(1, Bounds.Height - 76)); + var maximum = days.Current.Concat(days.Previous).Select(d => Math.Max(d.Used ?? 0, Math.Max(d.EvenPace, d.Budget ?? 0))).DefaultIfEmpty(0).Max(); var ticks = UsageChart.AxisTicks(maximum * 1.15); var max = Math.Max(1, ticks[^1]); double Y(double value) => plot.Bottom - value / max * plot.Height; foreach (var tick in ticks) @@ -206,11 +210,12 @@ public sealed class DailyLimitChart(WindowDays days, Provider provider) : Contro ChartText.Draw(context, $"{tick:0.#}%", new(0, Y(tick) - 7), ink); } var width = plot.Width / Math.Max(1, days.Current.Count); + var labels = AxisLabels; for (var i = 0; i < days.Current.Count; i++) { var day = days.Current[i]; var x = plot.Left + i * width; if (i < days.Previous.Count && days.Previous[i].Used is { } prior) - using (context.PushOpacity(.18)) context.DrawRectangle(null, new Pen(colour, 2), new Rect(x + 4, Y(prior), width - 8, plot.Bottom - Y(prior)), 3, 3); + using (context.PushOpacity(.18)) context.DrawRectangle(null, new Pen(colour, 2), new Rect(x + 4, Y(prior), Math.Max(1, width - 8), plot.Bottom - Y(prior)), 3, 3); if (day.Used is { } use) { var rect = new Rect(x + 8, Y(use), Math.Max(1, width - 16), Math.Max(0, plot.Bottom - Y(use))); @@ -227,23 +232,46 @@ public sealed class DailyLimitChart(WindowDays days, Provider provider) : Contro } if (day.IsToday) ChartText.Draw(context, $"{use:0.#}%", new(x + 8, Y(use) - 18), Ui.Colour("Ink", dark), 12); } - ChartText.Draw(context, day.Start.DateTime.ToString("ddd"), new(x + 8, plot.Bottom + 8), day.IsToday ? Ui.Colour("Ink", dark) : ink); - hits.Add((new Rect(x, plot.Top, width, plot.Height + 30), () => DataTooltip.Day(day))); + ChartText.Draw(context, labels[i], new(x + 4, plot.Bottom + 8), day.IsToday ? Ui.Colour("Ink", dark) : ink); + hits.Add((new Rect(x, plot.Top, width, plot.Height + 48), () => DataTooltip.Day(day))); } - var evenLabel = Math.Clamp(Y(days.EvenPace) - 7, plot.Top, plot.Bottom - 14); - var budgetLabel = days.DailyBudget is { } b ? Math.Clamp(Y(b) - 7, plot.Top, plot.Bottom - 14) : 0; - if (days.DailyBudget is { } budget && Math.Abs(evenLabel - budgetLabel) < 18) + if (days.Current.Count == 0) return; + if (days.Reset is { } reset && reset != CalendarDays.Start(reset, clock.LocalTimeZone)) + { + var start = CalendarDays.Start(reset, clock.LocalTimeZone); + var fraction = (reset - start).TotalSeconds / (CalendarDays.NextStart(start, clock.LocalTimeZone) - start).TotalSeconds; + var x = plot.Left + (days.Current.Count - 1 + fraction) * width; + context.DrawLine(new Pen(ink, 1, new DashStyle([3, 3], 0)), new(x, plot.Top), new(x, plot.Bottom)); + } + var even = days.Current[^1].EvenPace; var budget = days.Current[^1].Budget; + var evenLabel = Math.Clamp(Y(even) - 7, plot.Top, plot.Bottom - 14); + var budgetLabel = budget is { } b ? Math.Clamp(Y(b) - 7, plot.Top, plot.Bottom - 14) : 0; + if (budget is { } value && Math.Abs(evenLabel - budgetLabel) < 18) { var middle = Math.Clamp((evenLabel + budgetLabel) / 2, plot.Top + 9, plot.Bottom - 23); - evenLabel = middle + (budget >= days.EvenPace ? 9 : -9); - budgetLabel = middle + (budget >= days.EvenPace ? -9 : 9); + evenLabel = middle + (value >= even ? 9 : -9); + budgetLabel = middle + (value >= even ? -9 : 9); } - Reference(days.EvenPace, $"Even {days.EvenPace:0.#}%/day", ink, evenLabel, true); - if (days.DailyBudget is { } dailyBudget) Reference(dailyBudget, $"Budget {dailyBudget:0.#}%/day", Ui.Colour("Secondary", dark), budgetLabel, false); - void Reference(double value, string label, IBrush brush, double labelY, bool dashed) + // Labels name the full-day rates of the tile's plan row; partial days draw their share of it. + Reference(d => d.EvenPace, $"Even {days.EvenPace:0.#}%/day", ink, evenLabel, true); + if (budget is { } lastBudget) Reference(d => d.Budget, days.LaterBudget is { } later ? $"Budget {later:0.#}%/day" : $"Budget {lastBudget:0.#}%", + Ui.Colour("Secondary", dark), budgetLabel, false); + void Reference(Func select, string label, IBrush brush, double labelY, bool dashed) { - context.DrawLine(new Pen(brush, 1, dashed ? new DashStyle([4, 4], 0) : null), new(plot.Left, Y(value)), new(plot.Right, Y(value))); - if (Math.Abs(labelY + 7 - Y(value)) > 3) context.DrawLine(new Pen(brush, 1), new(plot.Right, Y(value)), new(plot.Right + 6, labelY + 7)); + var pen = new Pen(brush, 1, dashed ? new DashStyle([4, 4], 0) : null); + double? prior = null; + for (var i = 0; i < days.Current.Count; i++) + { + var current = select(days.Current[i]); var x = plot.Left + i * width; + if (current is { } v) + { + if (prior is { } p) context.DrawLine(pen, new(x, Y(p)), new(x, Y(v))); + context.DrawLine(pen, new(x, Y(v)), new(x + width, Y(v))); + } + prior = current; + } + if (prior is { } end && Math.Abs(labelY + 7 - Y(end)) > 3) + context.DrawLine(new Pen(brush, 1), new(plot.Right, Y(end)), new(plot.Right + 6, labelY + 7)); ChartText.Draw(context, label, new(plot.Right + 8, labelY), brush); } } diff --git a/src/FinalToken.App/DataTooltip.cs b/src/FinalToken.App/DataTooltip.cs index f08fb68..6641133 100644 --- a/src/FinalToken.App/DataTooltip.cs +++ b/src/FinalToken.App/DataTooltip.cs @@ -40,6 +40,9 @@ public sealed class DataTooltip : Border var rows = new List { new("Use", day.IsFuture ? "Future day" : day.Used is { } use ? $"{use:0.##} % of the week" : "Collecting history") }; if (!day.IsFuture && day.Used is not null) rows.Add(new("Source", day.Origin == UseOrigin.Estimated ? "Estimated from tokens" : "Measured")); if (!day.IsFuture && day.Cumulative is { } cumulative) rows.Add(new("Cumulative", $"{cumulative:0.##} %")); + if (day.IsPartial) rows.Add(new("Share", $"{day.Share.TotalHours:0.##} h")); + rows.Add(new("Even pace", $"{day.EvenPace:0.##} %")); + rows.Add(new("Budget", day.Budget is { } budget ? $"{budget:0.##} %" + (day.BudgetOrigin == UseOrigin.Estimated ? " (estimated)" : "") : "Unavailable")); return new(day.Start.DateTime.ToString("D"), rows.ToArray()); } public override string ToString() => Title + "\n" + string.Join('\n', Rows.Select(r => r.Label + ": " + r.Value)); diff --git a/src/FinalToken.App/PanelViewModel.cs b/src/FinalToken.App/PanelViewModel.cs index 1002e8f..089f7f5 100644 --- a/src/FinalToken.App/PanelViewModel.cs +++ b/src/FinalToken.App/PanelViewModel.cs @@ -112,6 +112,8 @@ public static class Display return local.ToString(local.Date == clock.GetLocalNow().Date ? "t" : "g", culture ?? System.Globalization.CultureInfo.CurrentCulture); } + public static string Time(DateTimeOffset time, TimeProvider? clock = null) => + TimeZoneInfo.ConvertTime(time, (clock ?? TimeProvider.System).LocalTimeZone).ToString("t"); public static string Duration(TimeSpan span) => span <= TimeSpan.Zero ? "now" : span.TotalDays >= 1 ? $"{(int)span.TotalDays} d {span.Hours} h" : span.TotalHours >= 1 ? $"{(int)span.TotalHours} h {span.Minutes} min" : $"{Math.Ceiling(span.TotalMinutes):0} min"; public static string Span(TimeSpan span) => span.TotalHours >= 1 ? $"{span.TotalHours:0.#} h" : $"{span.TotalMinutes:0} min"; diff --git a/src/FinalToken.App/PanelWindow.cs b/src/FinalToken.App/PanelWindow.cs index c345c63..9898759 100644 --- a/src/FinalToken.App/PanelWindow.cs +++ b/src/FinalToken.App/PanelWindow.cs @@ -120,7 +120,7 @@ public sealed class PanelWindow : Window if (index < 0) index = 0; var labels = entries.Select(d => providers.SelectMany(p => p.Windows).First(w => w.Window.Provider == d.Provider && w.Window.Id == d.Id).Window.Label).ToArray(); Control DayView(LimitDetail item) => item.Days!.Current.Any(d => d.Used is not null) - ? new DailyLimitChart(item.Days, item.Provider) + ? new DailyLimitChart(item.Days, item.Provider, clock) : Ui.Text($"Collecting history since {(item.Since ?? providers.SelectMany(p => p.Windows).First(w => w.Window.Provider == item.Provider && w.Window.Id == item.Id).Window.SampleTime).LocalDateTime:dd.MM. HH:mm}", 12, "Muted"); var chart = new Border { Child = DayView(entries[index]) }; var title = Ui.Text(group.Key + " · " + labels[index], 15); @@ -154,9 +154,11 @@ public sealed class PanelWindow : Window var totals = providers.Select(p => { var row = new WrapPanel(); - row.Children.Add(TokenTile(p, "Today", p.Today)); - if (p.Session is { } session && p.Windows.Any(w => w.Window.Length <= TimeSpan.FromDays(1))) row.Children.Add(TokenTile(p, "Current session", session)); - row.Children.Add(TokenTile(p, "This week", p.Week)); + row.Children.Add(TokenTile(p, "Today", "since 00:00", p.Today)); + if (p.Session is { } session && p.Windows.FirstOrDefault(w => w.Window.Length <= TimeSpan.FromHours(5) && w.Window.ResetsAt > now) is { Window: { ResetsAt: { } reset, Length: { } length } }) + row.Children.Add(TokenTile(p, "Current session", "since " + Display.Time(reset - length, clock), session)); + row.Children.Add(TokenTile(p, p.WeekWindow is not null ? "Limit week" : "Calendar week", + p.WeekWindow is not null ? "since " + TimeZoneInfo.ConvertTime(p.WeekStart, clock.LocalTimeZone).ToString("ddd HH:mm") : "since Mon 00:00", p.Week)); return (Control)Ui.Card(Ui.Stack(Ui.Text(p.Provider.ToString(), 15), row)); }); content.Add(Ui.Columns(totals, wide)); @@ -191,48 +193,58 @@ public sealed class PanelWindow : Window { var w = window.Window; var pace = window.Pace; var detail = model.History.Details.FirstOrDefault(d => d.Provider == w.Provider && d.Id == w.Id); - var title = new DockPanel(); + var title = new DockPanel { Name = "Title" }; var chip = new Border { Child = Ui.Mark(Display.State(pace.State), Brush.Parse("#0b0b0b")), Background = PaceBar.Colour(pace.State), CornerRadius = new CornerRadius(6), Padding = new Thickness(8, 4) }; DockPanel.SetDock(chip, Dock.Right); title.Children.Add(chip); title.Children.Add(Ui.Text(w.Provider + " · " + w.Label, 15)); - var card = Ui.Stack(title, Ui.Text($"{w.UsedPercent:0.#} %", 36), Ui.Text("used", 12, "Muted"), new PaceBar(window, now) { Height = 10 }); - card.Children.Add(Ui.Text(w.ResetsAt is { } reset ? $"Resets in {Display.Duration(reset - now)} · {Display.Projection(reset, clock)}" : "Reset unknown", 13, "Secondary")); + var card = Ui.Stack(title); + void Row(string name, Control control) { control.Name = name; card.Children.Add(control); } + Row("Percent", Ui.Text($"{w.UsedPercent:0.#} %", 36)); Row("Used", Ui.Text("used", 12, "Muted")); + Row("Pace", new PaceBar(window, now) { Height = 10 }); + Row("Reset", Ui.Text(w.ResetsAt is { } reset ? $"Resets in {Display.Duration(reset - now)} · {Display.Projection(reset, clock)}" : "Reset unknown", 13, "Secondary")); if (pace.Projection is { } projection) { var caption = Display.Forecast(projection, pace.State, clock) + $" ({Display.Duration(w.ResetsAt!.Value - projection)} before reset)"; if (pace.State == PaceState.Ahead) { var line = new DockPanel(); var mark = Ui.Mark("⚠ ", Brush.Parse("#d03b3b"), 13); - DockPanel.SetDock(mark, Dock.Left); line.Children.Add(mark); line.Children.Add(Ui.Text(caption[2..], 13, "Secondary")); card.Children.Add(line); + DockPanel.SetDock(mark, Dock.Left); line.Children.Add(mark); line.Children.Add(Ui.Text(caption[2..], 13, "Secondary")); Row("Forecast", line); } - else card.Children.Add(Ui.Text(caption, 13, "Secondary")); + else Row("Forecast", Ui.Text(caption, 13, "Secondary")); } else if (LimitAnalysis.AverageUseAtReset(w, now, pace) is { } average) - card.Children.Add(Ui.Text($"≈ {average:0.#} % at reset", 13, "Secondary")); - else if (Display.ForecastWaiting(window, now, clock) is { } waiting) - card.Children.Add(Ui.Text(waiting, 13, "Muted")); + Row("Forecast", Ui.Text($"≈ {average:0.#} % at reset", 13, "Secondary")); + else Row("Forecast", Ui.Text(Display.ForecastWaiting(window, now, clock) ?? "No forecast: pace unknown", 13, "Muted")); if (detail?.Recent is { } recent) { var line = Ui.Text($"Last {Display.Span(recent.Span)}: +{recent.Increase:0.#} %" + (recent.ReachesLimit is { } date ? $" · 100 % on {Display.Projection(date, clock)}" : $" · ≈ {recent.UseAtReset:0.#} % at reset"), 13, "Secondary"); - ToolTip.SetTip(line, new DataTooltip("Recent rate", new("Rate", $"{recent.PercentPerDay:0.##} %/day"), new("Observed span", Display.Duration(recent.Span)))); card.Children.Add(line); + ToolTip.SetTip(line, new DataTooltip("Recent rate", new("Rate", $"{recent.PercentPerDay:0.##} %/day"), new("Observed span", Display.Duration(recent.Span)))); Row("Recent", line); } - if (detail?.Days is { } days) + else Row("Recent", Ui.Text(Display.ForecastWaiting(window, now, clock) is not null && Pace.ForecastStartsAt(w) is { } forecastStart + ? "Recent rate from " + Display.Projection(forecastStart, clock) : "Recent rate needs 3 h of samples", 13, "Muted")); + if (w.Length > TimeSpan.FromDays(1)) { - card.Children.Add(Ui.Text(days.Today is { } today ? days.TodayOrigin == UseOrigin.Estimated - ? $"Today ≈ +{today:0.#} % of the week (estimated)" : $"Today +{today:0.#} % of the week" : "Today · collecting a day baseline", 15)); - card.Children.Add(Ui.Text($"Even pace {days.EvenPace:0.#} %/day", 13, "Secondary")); - if (days.DailyBudget is { } budget) card.Children.Add(Ui.Text($"Budget {budget:0.#} %/day for {Display.Duration(w.ResetsAt!.Value - now)}", 15)); + var days = detail?.Days; + var estimated = days?.TodayOrigin == UseOrigin.Estimated || days?.BudgetOrigin == UseOrigin.Estimated; + Row("Today", Ui.Text(days?.Today is { } today + ? $"Today {(estimated ? "≈ " : "")}+{today:0.#} %" + (days.TodayBudget is { } budget ? $" of {budget:0.#} % budget" : " of the week") + (estimated ? " (estimated)" : "") + : "Today · collecting a day baseline", 15, days?.Today is null ? "Muted" : "Ink")); + var plan = $"Even pace {days?.EvenPace ?? 100 / w.Length.Value.TotalDays:0.#} %/day"; + if (days?.LaterBudget is { } later) plan += $" · from tomorrow {later:0.#} %/day"; + else if (days?.TodayBudget is not null && w.ResetsAt is { } lastReset) plan += " · last day, resets " + Display.Time(lastReset, clock); + Row("Plan", Ui.Text(plan, 13, "Secondary")); } - if (now - w.SampleTime > model.ProbeInterval * 2) card.Children.Add(Ui.Text($"⚠ sample {Display.Duration(now - w.SampleTime)} old", 12, "Muted")); + if (now - w.SampleTime > model.ProbeInterval * 2) Row("Stale", Ui.Text($"⚠ sample {Display.Duration(now - w.SampleTime)} old", 12, "Muted")); var tile = Ui.Card(card); tile.Name = $"LimitTile-{w.Provider}-{w.Id}"; ToolTip.SetTip(tile, new DataTooltip(w.Provider + " · " + w.Label, new("Used", $"{w.UsedPercent:0.##} %"), new("Expected", $"{pace.ElapsedFraction * 100:0.##} %"), new("State", Display.State(pace.State)), new("Reset", w.ResetsAt is { } r ? Display.Projection(r, clock) : "Unknown"), new("Sample", w.SampleTime.LocalDateTime.ToString("g")))); return tile; } - private Control TokenTile(ProviderSnapshot provider, string label, TokenCounts counts) + private Control TokenTile(ProviderSnapshot provider, string label, string caption, TokenCounts counts) { var tile = Ui.Stack(Ui.Text(label, 12, "Secondary"), Ui.Text(Display.Compact(Math.Max(0, counts.Total - (model.IncludeCacheReads ? 0 : counts.CacheRead))), 32), - new CompositionBar(counts, provider.Provider, model.IncludeCacheReads) { Height = 6 }); + new CompositionBar(counts, provider.Provider, model.IncludeCacheReads) { Height = 6 }, Ui.Text(caption, 12, "Muted")); + tile.Name = $"TokenTile-{provider.Provider}-{label.Replace(' ', '-')}"; tile.Width = wide ? 164 : 188; tile.Margin = new Thickness(0, 8, 16, 0); - ToolTip.SetTip(tile, DataTooltip.Tokens(provider.Provider + " · " + label, counts)); return tile; + ToolTip.SetTip(tile, DataTooltip.Tokens(provider.Provider + " · " + label + " · " + caption, counts)); return tile; } private Control CompositionLegend() { diff --git a/src/FinalToken.Cli/CliApplication.cs b/src/FinalToken.Cli/CliApplication.cs index 0b3f380..ba112c5 100644 --- a/src/FinalToken.Cli/CliApplication.cs +++ b/src/FinalToken.Cli/CliApplication.cs @@ -40,6 +40,8 @@ public static class CliApplication { await output.WriteLineAsync($"{provider.Provider}: {provider.Status} {provider.Reason}"); await output.WriteLineAsync($" Tokens today: {provider.Today.Total}; session: {provider.Session?.Total.ToString(CultureInfo.InvariantCulture) ?? "unknown"}; week: {provider.Week.Total}"); + await output.WriteLineAsync($" {(provider.WeekWindow is null ? "Calendar week" : "Limit week")}: since {provider.WeekStart:O}" + + (provider.WeekWindow is { } weekWindow ? $" ({weekWindow})" : "")); foreach (var window in provider.Windows) await output.WriteLineAsync(FormattableString.Invariant($" {window.Window.Label}: {window.Window.UsedPercent:0.##}% used; resets {window.Window.ResetsAt:O}; {window.Pace.State}; delta {window.Pace.Delta:0.##}; sampled {window.Window.SampleTime:O}")); } diff --git a/src/FinalToken.Core/AGENTS.md b/src/FinalToken.Core/AGENTS.md index 4c23995..d46af09 100644 --- a/src/FinalToken.Core/AGENTS.md +++ b/src/FinalToken.Core/AGENTS.md @@ -18,7 +18,8 @@ Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root propagates. The background engine records other tick failures and retries without faulting its loop. - Use `CurrentSnapshot`, `Settings`, `UpdateSettingsAsync`, `RefreshNowAsync` and `RecentDiagnostics`. `History` offers token series, model/project breakdowns and limit samples. -- Snapshot provider totals use local today and Monday-based calendar week. Session totals use the +- Snapshot provider totals use local today and the current provider-wide limit week, falling back + to the Monday-based local calendar week (D9). Session totals use the reset and length of a known short limit. Hourly storage includes whole boundary hours (D5). Day series use local calendar days, including DST. Tests can supply a zone to `TokenSeries`. Use `CalendarDays.NextStart` for daily query ends; adding 24 hours is wrong on DST days. diff --git a/src/FinalToken.Core/HistoryStore.cs b/src/FinalToken.Core/HistoryStore.cs index 991a85b..1e536dd 100644 --- a/src/FinalToken.Core/HistoryStore.cs +++ b/src/FinalToken.Core/HistoryStore.cs @@ -245,17 +245,18 @@ public sealed class HistoryStore } public TokenCounts Total(Provider provider, DateTimeOffset from, DateTimeOffset to) { lock (gate) return Sum(Range(provider, from, to).Select(b => b.Counts)); } - public (TokenCounts Today, TokenCounts? Session, TokenCounts Week) Totals(Provider provider, DateTimeOffset now, - LimitWindow? session, TimeZoneInfo? zone = null) + public (TokenCounts Today, TokenCounts? Session, TokenCounts Week, DateTimeOffset WeekStart, string? WeekWindow) Totals(Provider provider, DateTimeOffset now, + LimitWindow? session, TimeZoneInfo? zone = null, LimitWindow? weekWindow = null) { zone ??= TimeZoneInfo.Local; var local = TimeZoneInfo.ConvertTime(now, zone); var today = local.Date; var week = today.AddDays(-(((int)today.DayOfWeek + 6) % 7)); var todayUtc = CalendarDays.Start(today, zone); - var weekUtc = CalendarDays.Start(week, zone); + var followsLimit = weekWindow is { ResetsAt: { } r, Length: { Ticks: > 0 } l } && r > now; + var weekUtc = followsLimit ? weekWindow!.ResetsAt!.Value - weekWindow.Length!.Value : CalendarDays.Start(week, zone); return (Total(provider, todayUtc, now), session is { ResetsAt: { } reset, Length: { } length } && reset > now - ? Total(provider, reset - length, now) : null, Total(provider, weekUtc, now)); + ? Total(provider, reset - length, now) : null, Total(provider, weekUtc, now), weekUtc, followsLimit ? weekWindow!.Id : null); } private IEnumerable Range(Provider provider, DateTimeOffset from, DateTimeOffset to) => SelectMonths(from, to).SelectMany(m => GetPartition(m).Buckets.Values) diff --git a/src/FinalToken.Core/LimitAnalysis.cs b/src/FinalToken.Core/LimitAnalysis.cs index d4cd7f8..8d905e7 100644 --- a/src/FinalToken.Core/LimitAnalysis.cs +++ b/src/FinalToken.Core/LimitAnalysis.cs @@ -3,9 +3,11 @@ namespace FinalToken.Core; public sealed record RateForecast(double PercentPerDay, double UseAtReset, DateTimeOffset? ReachesLimit, double Increase = 0, TimeSpan Span = default); public sealed record LimitDay(DateTimeOffset Start, DateTimeOffset End, double? Used, double? Cumulative, - bool IsToday, bool IsFuture, UseOrigin Origin = UseOrigin.Measured); + bool IsToday, bool IsFuture, UseOrigin Origin = UseOrigin.Measured, TimeSpan Share = default, double EvenPace = 0, double? Budget = null, + bool IsPartial = false, UseOrigin? BudgetOrigin = null); public sealed record WindowDays(IReadOnlyList Current, IReadOnlyList Previous, - double? Today, double EvenPace, double? DailyBudget, UseOrigin TodayOrigin = UseOrigin.Measured); + double? Today, double EvenPace, double? TodayBudget, double? LaterBudget = null, UseOrigin TodayOrigin = UseOrigin.Measured, + UseOrigin? BudgetOrigin = null, DateTimeOffset? InstanceStart = null, DateTimeOffset? Reset = null); /// Pure D7 calculations. Missing baselines use marked token estimates when calibration is available. public static partial class LimitAnalysis diff --git a/src/FinalToken.Core/LimitDays.cs b/src/FinalToken.Core/LimitDays.cs new file mode 100644 index 0000000..4f0744b --- /dev/null +++ b/src/FinalToken.Core/LimitDays.cs @@ -0,0 +1,41 @@ +namespace FinalToken.Core; + +public static partial class LimitAnalysis +{ + // D7: plan from the day baseline; spending within that plan does not take from later days. + private static WindowDays PlanDays(LimitWindow window, LimitInstance current, LimitInstance? previous, + LimitDay? today, IReadOnlyList observations, DateTimeOffset now, TimeZoneInfo zone) + { + var length = window.Length!.Value; + double? baseline = null; UseOrigin? origin = null; + double? todayBudget = null, laterBudget = null; + if (today is not null && current.Start <= now && current.Reset > now) + { + var start = today.Start > current.Start ? today.Start : current.Start; + if (start == current.Start) { baseline = 0; origin = UseOrigin.Measured; } + else if (Instance(window, observations).LastOrDefault(s => s.SampleTime >= current.Start && s.SampleTime <= start) is { } sample) + { baseline = sample.UsedPercent; origin = UseOrigin.Measured; } + else if (today is { Origin: UseOrigin.Estimated, Cumulative: { } cumulative, Used: { } use }) + { baseline = Math.Max(0, cumulative - use); origin = UseOrigin.Estimated; } + if (baseline is { } used) + { + todayBudget = Math.Max(0, 100 - used) * (today.End - start).TotalDays / (current.Reset - start).TotalDays; + if (today.End < current.Reset) + laterBudget = Math.Max(0, 100 - Math.Max(window.UsedPercent, used + todayBudget.Value)) / (current.Reset - today.End).TotalDays; + } + } + LimitDay Plan(LimitDay day, bool isCurrent) + { + var instance = isCurrent ? current : previous!; + var start = day.Start > instance.Start ? day.Start : instance.Start; + var share = day.End - start; + return day with { Share = share, EvenPace = 100 * share.TotalDays / (instance.Reset - instance.Start).TotalDays, + Budget = !isCurrent ? null : day.IsToday ? todayBudget : day.IsFuture ? laterBudget * share.TotalDays : null, + IsPartial = share != CalendarDays.NextStart(day.Start, zone) - day.Start, + BudgetOrigin = isCurrent && (day.IsToday || day.IsFuture) ? origin : null }; + } + return new(current.Days.Select(d => Plan(d, true)).ToArray(), previous?.Days.Select(d => Plan(d, false)).ToArray() ?? [], + today?.Used, 100 / length.TotalDays, todayBudget, laterBudget, today?.Origin ?? UseOrigin.Measured, + origin, current.Start, current.Reset); + } +} diff --git a/src/FinalToken.Core/LimitEstimates.cs b/src/FinalToken.Core/LimitEstimates.cs index 7fc0e0d..6e60ab4 100644 --- a/src/FinalToken.Core/LimitEstimates.cs +++ b/src/FinalToken.Core/LimitEstimates.cs @@ -66,8 +66,7 @@ public static partial class LimitAnalysis if (length > TimeSpan.FromDays(1)) { var today = current.Days.FirstOrDefault(d => d.IsToday); - days = new(current.Days, past.FirstOrDefault()?.Days ?? [], today?.Used, 100 / length.TotalDays, - reset > now ? (100 - window.UsedPercent) / (reset - now).TotalDays : null, today?.Origin ?? UseOrigin.Measured); + days = PlanDays(window, current, past.FirstOrDefault(), today, observations, now, zone); } return new(current, past, days); diff --git a/src/FinalToken.Core/Pace.cs b/src/FinalToken.Core/Pace.cs index 7fc5d96..65ff05d 100644 --- a/src/FinalToken.Core/Pace.cs +++ b/src/FinalToken.Core/Pace.cs @@ -2,10 +2,10 @@ namespace FinalToken.Core; public static class Pace { - // D7: use ticks at the boundary so exactly 10% is eligible despite floating-point rounding. + // D7: use ticks at the boundary so exactly 2% is eligible despite floating-point rounding. public static DateTimeOffset? ForecastStartsAt(LimitWindow window) => window.Length is { Ticks: > 0 } length && window.ResetsAt is { } reset - ? reset - TimeSpan.FromTicks(length.Ticks - length.Ticks / 10) : null; + ? reset - TimeSpan.FromTicks(length.Ticks - length.Ticks / 50) : null; public static bool CanForecast(LimitWindow window, DateTimeOffset now, double threshold = 10) => CanForecast(window, now, Calculate(window, now, threshold)); diff --git a/src/FinalToken.Core/RefreshEngine.cs b/src/FinalToken.Core/RefreshEngine.cs index d932a9a..c1eb2be 100644 --- a/src/FinalToken.Core/RefreshEngine.cs +++ b/src/FinalToken.Core/RefreshEngine.cs @@ -199,10 +199,13 @@ public sealed class RefreshEngine : IAsyncDisposable var windows = History.LatestLimits(provider); // Session totals follow an explicitly short limit window, never a week mislabeled primary. var session = windows.FirstOrDefault(w => w.Length is { } length && length <= TimeSpan.FromHours(5)); - var totals = History.Totals(provider, now, session); + // D9: the longest provider-wide limit defines the week; family limits do not. + var week = windows.Where(w => w.Length > TimeSpan.FromDays(1) && TokenWeights.Family(w) is null) + .OrderByDescending(w => w.Length).FirstOrDefault(); + var totals = History.Totals(provider, now, session, clock.LocalTimeZone, week); var state = statuses[provider]; var snapshots = windows.Select(w => new WindowSnapshot(w, Pace.Calculate(w, now, config.PaceThreshold))).ToArray(); - providers.Add(new(provider, state.Status, state.Reason, snapshots, totals.Today, totals.Session, totals.Week)); + providers.Add(new(provider, state.Status, state.Reason, snapshots, totals.Today, totals.Session, totals.Week, totals.WeekStart, totals.WeekWindow)); foreach (var window in snapshots) if (state.Status == ProviderStatus.Available && popups.Observe(window.Window, window.Pace, config) is { } alert) alerts.Add(alert); diff --git a/src/FinalToken.Core/Snapshot.cs b/src/FinalToken.Core/Snapshot.cs index 3e7f93f..20bcfc1 100644 --- a/src/FinalToken.Core/Snapshot.cs +++ b/src/FinalToken.Core/Snapshot.cs @@ -8,7 +8,8 @@ public sealed record WindowSnapshot(LimitWindow Window, PaceResult Pace) public TimeSpan Age(DateTimeOffset now) => now - Window.SampleTime; } public sealed record ProviderSnapshot(Provider Provider, ProviderStatus Status, string? Reason, - IReadOnlyList Windows, TokenCounts Today, TokenCounts? Session, TokenCounts Week); + IReadOnlyList Windows, TokenCounts Today, TokenCounts? Session, TokenCounts Week, DateTimeOffset WeekStart = default, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? WeekWindow = null); public sealed record Snapshot { // Keep this initializer for omitted properties in source-generated JSON (D9). diff --git a/tests/FinalToken.App.Tests/HeadlessTests.cs b/tests/FinalToken.App.Tests/HeadlessTests.cs index e5ac3f6..a9a5775 100644 --- a/tests/FinalToken.App.Tests/HeadlessTests.cs +++ b/tests/FinalToken.App.Tests/HeadlessTests.cs @@ -146,6 +146,63 @@ public sealed class HeadlessTests model.Snapshot = model.Snapshot! with { MadeAt = clock.GetUtcNow() }; Dispatcher.UIThread.RunJobs(); Assert.Equal(prior, viewport.Offset); } + var budgetModel = FakeData.BudgetModel(); + var budgetSnapshot = budgetModel.Snapshot!; + var budgetClock = new FixedClock(budgetSnapshot.MadeAt); + var budgetPanel = new PanelWindow(budgetModel, () => { }, () => { }, () => { }, () => { }, budgetClock) { Width = 1280, Height = 1000 }; + budgetPanel.Show(); Dispatcher.UIThread.RunJobs(); + string[] Rows(Provider provider, string id = "week") => ((StackPanel)budgetPanel.GetVisualDescendants().OfType() + .Single(b => b.Name == $"LimitTile-{provider}-{id}").Child!).Children.Select(c => c.Name!).ToArray(); + string[] longRows = ["Title", "Percent", "Used", "Pace", "Reset", "Forecast", "Recent", "Today", "Plan"]; + Assert.Equal(longRows, Rows(Provider.Claude)); Assert.Equal(longRows, Rows(Provider.Codex)); + Assert.Contains(budgetPanel.GetVisualDescendants().OfType(), t => t.Text == "Limit week"); + Assert.Contains(budgetPanel.GetVisualDescendants().OfType(), t => t.Text == "Calendar week"); + Assert.Contains(budgetPanel.GetVisualDescendants().OfType(), t => t.Text == "since Mon 00:00"); + var tokenTiles = budgetPanel.GetVisualDescendants().OfType().Where(p => p.Name?.StartsWith("TokenTile-", StringComparison.Ordinal) == true).ToArray(); + Assert.All(tokenTiles, tile => Assert.Equal(tokenTiles[0].Bounds.Height, tile.Bounds.Height)); + var limitTokens = tokenTiles.Single(t => t.Name == "TokenTile-Claude-Limit-week"); + Assert.Contains(limitTokens.GetVisualDescendants().OfType(), t => t.Text == "since " + TimeZoneInfo.ConvertTime(budgetSnapshot.Providers[0].WeekStart, budgetClock.LocalTimeZone).ToString("ddd HH:mm")); + Assert.Contains("Limit week", Assert.IsType(ToolTip.GetTip(limitTokens)).Title); + Assert.Contains("since ", Assert.IsType(ToolTip.GetTip(limitTokens)).Title); + foreach (var dayChart in budgetPanel.GetVisualDescendants().OfType()) + { + Assert.Contains("from " + Display.Time(budgetSnapshot.Providers[0].WeekStart, budgetClock), dayChart.AxisLabels[0]); + Assert.Contains("reset " + Display.Time(budgetSnapshot.Providers[0].WeekStart.AddDays(7), budgetClock), dayChart.AxisLabels[^1]); + } + var partialDay = budgetModel.History.Details[0].Days!.Current[0]; + var partialTip = DataTooltip.Day(partialDay); + Assert.Contains(partialTip.Rows, r => r.Label == "Share"); + Assert.Contains(partialTip.Rows, r => r.Label == "Even pace"); + Assert.Contains(partialTip.Rows, r => r.Label == "Budget"); + foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light }) + { + budgetPanel.RequestedThemeVariant = theme; + var viewport = budgetPanel.GetVisualDescendants().OfType().First(); viewport.Offset = default; + Save(budgetPanel, $"budget-1280x1000-{theme}-limits.png"); + foreach (var (name, target) in new[] { ("week", "Week use per day"), ("tokens", "Tokens") }) + { + var heading = budgetPanel.GetVisualDescendants().OfType().First(t => t.Text == target); + viewport.Offset = new Vector(0, viewport.Offset.Y + heading.TranslatePoint(default, viewport)!.Value.Y - 16); + Save(budgetPanel, $"budget-1280x1000-{theme}-{name}.png"); + } + } + budgetModel.History = new([], [], [], [], []); + budgetModel.Snapshot = budgetSnapshot with { Providers = budgetSnapshot.Providers.Select(p => + { + var w = p.Windows[0].Window with { UsedPercent = 1, ResetsAt = p.Provider == Provider.Claude ? budgetClock.GetUtcNow().AddDays(7).AddHours(-1) : null }; + var shortWindow = w with { Id = "session", Label = "Session", Length = TimeSpan.FromHours(5), + ResetsAt = p.Provider == Provider.Claude ? budgetClock.GetUtcNow().AddHours(5).AddMinutes(-1) : null }; + return p with { Windows = [new(w, Pace.Calculate(w, budgetClock.GetUtcNow())), new(shortWindow, Pace.Calculate(shortWindow, budgetClock.GetUtcNow()))] }; + }).ToArray() }; + Dispatcher.UIThread.RunJobs(); + Assert.Equal(longRows, Rows(Provider.Claude)); Assert.Equal(longRows, Rows(Provider.Codex)); + Assert.Equal(longRows.Take(7), Rows(Provider.Claude, "session")); + Assert.Equal(Rows(Provider.Claude, "session"), Rows(Provider.Codex, "session")); + Assert.Contains(budgetPanel.GetVisualDescendants().OfType(), t => t.Text == "No forecast: pace unknown"); + Assert.Contains(budgetPanel.GetVisualDescendants().OfType(), t => t.Text == "Recent rate needs 3 h of samples"); + Assert.Contains(budgetPanel.GetVisualDescendants().OfType(), t => t.Text?.StartsWith("Recent rate from ", StringComparison.Ordinal) == true); + Assert.Contains(budgetPanel.GetVisualDescendants().OfType(), t => t.Text == "Today · collecting a day baseline"); + budgetPanel.Close(); var forecastModel = FakeData.ForecastModel(); var forecastClock = new FixedClock(forecastModel.Snapshot!.MadeAt); var forecastPanel = new PanelWindow(forecastModel, () => { }, () => { }, () => { }, () => { }, forecastClock); @@ -239,7 +296,7 @@ public sealed class HeadlessTests ("future-day", future), ("project", DataTooltip.Tokens("D:/Projects/Customer/Workspace/Project-with-a-long-name", new(100000000, 1900000000, 10000000, 53670717, 1234567, 2063670717))), ("tile", (DataTooltip)ToolTip.GetTip(panel.GetVisualDescendants().OfType().First(b => b.Name == "LimitTile-Claude-week"))!), - ("tokens", DataTooltip.Tokens("Claude - This week", originalSnapshot.Providers[0].Week)), + ("tokens", DataTooltip.Tokens("Claude - Calendar week", originalSnapshot.Providers[0].Week)), }; var limit = originalHistory.Limits.Single(l => l.Provider == Provider.Claude && l.Window!.Window.Id == "week"); CaptureChartTip("burnup", new BurnUpChart(limit, clock), new Point(240, 100)); diff --git a/tests/FinalToken.App.Tests/ViewModelTests.cs b/tests/FinalToken.App.Tests/ViewModelTests.cs index f999e5f..9462c97 100644 --- a/tests/FinalToken.App.Tests/ViewModelTests.cs +++ b/tests/FinalToken.App.Tests/ViewModelTests.cs @@ -10,7 +10,7 @@ public sealed class ViewModelTests [InlineData(40, false)] public void HistoryForecastsUseTheSnapshotsConfiguredPace(double threshold, bool eligible) { - var model = FakeData.ForecastModel(threshold); + var model = FakeData.ForecastModel(threshold, beforeStart: true); Assert.Equal(eligible, model.History.Limits.Single(l => l.Window!.Window.Id == "primary").Forecast is not null); Assert.Equal(eligible, model.History.Details.Single(d => d.Id == "primary").Recent is not null); } @@ -166,12 +166,13 @@ public sealed class ViewModelTests internal static class FakeData { - public static PanelViewModel ForecastModel(double threshold = 10) + public static PanelViewModel ForecastModel(double threshold = 10, bool beforeStart = false) { var now = new DateTimeOffset(2026, 10, 15, 16, 45, 0, TimeSpan.Zero); var ahead = new LimitWindow(Provider.Codex, "primary", "Week", 39, new(2026, 10, 22, 6, 18, 0, TimeSpan.Zero), TimeSpan.FromDays(7), now, "fixture"); - var early = ahead with { Id = "secondary", Label = "Week · early on track", UsedPercent = 1, ResetsAt = now.AddDays(7).AddHours(-1) }; + if (beforeStart) ahead = ahead with { Length = TimeSpan.FromDays(28), ResetsAt = now.AddDays(28).AddHours(-4) }; + var early = ahead with { Id = "secondary", Length = TimeSpan.FromDays(7), Label = "Week · early on track", UsedPercent = 1, ResetsAt = now.AddDays(7).AddHours(-1) }; var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog(), new FixedClock(now)); store.AddLimits([ahead with { SampleTime = now.AddHours(-4), UsedPercent = 20 }, ahead, early with { SampleTime = now.AddHours(-1), UsedPercent = 0 }, early]); @@ -190,6 +191,24 @@ internal static class FakeData }; private static WindowSnapshot Window(Provider provider, string id, string label, double percent, DateTimeOffset now, int hours, int resetHours) { var w = new LimitWindow(provider, id, label, percent, now.AddHours(resetHours), TimeSpan.FromHours(hours), now.AddMinutes(-3), "fixture"); return new(w, Pace.Calculate(w, now)); } + public static PanelViewModel BudgetModel() + { + var now = new FixedClock().GetUtcNow(); + var clock = new FixedClock(now); + var start = new DateTimeOffset(2026, 10, 10, 22, 40, 0, clock.LocalTimeZone.BaseUtcOffset); + var store = new HistoryStore(Path.Combine(Path.GetTempPath(), "finaltoken-budget", Guid.NewGuid().ToString("N")), new DiagnosticLog(), clock); + var snapshot = Snapshot(now); + snapshot = snapshot with { Providers = snapshot.Providers.Select(p => + { + var w = new LimitWindow(p.Provider, "week", "Week", p.Provider == Provider.Claude ? 40 : 32, start.AddDays(7), TimeSpan.FromDays(7), now, "fixture"); + store.AddLimits([w with { SampleTime = CalendarDays.Start(now, clock.LocalTimeZone), UsedPercent = 30 }, w]); + for (var i = 0; i < 4; i++) + store.Add(new(p.Provider, start.AddDays(i), "fixture", "Fixture/Project", new(Input: 100, Total: 100), $"{p.Provider}-{i}")); + return p with { Windows = [new(w, Pace.Calculate(w, now))], Session = null, + WeekStart = start, WeekWindow = p.Provider == Provider.Claude ? "week" : null }; + }).ToArray() }; + return new() { Snapshot = snapshot, History = PanelViewModel.QueryHistory(store, snapshot, HistoryRange.Days7, null, now) }; + } public static PanelViewModel EarlyResetModel() { var now = new FixedClock().GetUtcNow(); diff --git a/tests/FinalToken.Cli.Tests/CliTests.cs b/tests/FinalToken.Cli.Tests/CliTests.cs index e6e641a..0448135 100644 --- a/tests/FinalToken.Cli.Tests/CliTests.cs +++ b/tests/FinalToken.Cli.Tests/CliTests.cs @@ -61,11 +61,29 @@ public class CliTests Assert.Equal(0, await CliApplication.RunAsync(["status", "--no-probe"], output, error, directory, path => new(path, claudeDirectory: path, codexDirectory: path, cliDiscovery: (_, _) => new(null, "Fixture CLI missing.")), TestContext.Current.CancellationToken)); Assert.Contains("Tokens today: 0", output.ToString()); + Assert.Contains("Calendar week: since ", output.ToString()); Assert.NotNull(SnapshotFile.Read(directory).Snapshot); } finally { Directory.Delete(directory, true); } } [Fact] + public async Task TextNamesLimitWeekAndItsStart() + { + var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + try + { + using var storeLock = StoreLock.TryAcquire(directory); + var start = new DateTimeOffset(2026, 10, 10, 22, 40, 0, TimeSpan.Zero); + await SnapshotFile.WriteAsync(directory, new Snapshot { MadeAt = DateTimeOffset.UtcNow, RefreshInterval = TimeSpan.FromMinutes(1), + Providers = [new(Provider.Codex, ProviderStatus.Available, null, [], new(), null, new(Total: 30), start, "week")] }, TestContext.Current.CancellationToken); + using var output = new StringWriter(); using var error = new StringWriter(); + Assert.Equal(0, await CliApplication.RunAsync(["status"], output, error, directory, cancellationToken: TestContext.Current.CancellationToken)); + Assert.Contains($"Limit week: since {start:O} (week)", output.ToString()); + } + finally { Directory.Delete(directory, true); } + } + [Fact] public async Task BusyStoreWithoutSnapshotExitsOne() { var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N")); diff --git a/tests/FinalToken.Core.Tests/DayBudgetTests.cs b/tests/FinalToken.Core.Tests/DayBudgetTests.cs new file mode 100644 index 0000000..464fcf6 --- /dev/null +++ b/tests/FinalToken.Core.Tests/DayBudgetTests.cs @@ -0,0 +1,98 @@ +using Xunit; + +namespace FinalToken.Core.Tests; + +public sealed class DayBudgetTests +{ + private static readonly TimeZoneInfo Zone = TimeZoneInfo.CreateCustomTimeZone("Fixture+02", TimeSpan.FromHours(2), "Fixture", "Fixture"); + private static readonly DateTimeOffset Start = new(2026, 10, 10, 22, 40, 0, TimeSpan.FromHours(2)); + private static LimitWindow Week(DateTimeOffset now, double used = 30) => new(Provider.Codex, "week", "Week", used, + Start.AddDays(7), TimeSpan.FromDays(7), now, "fixture"); + private static WindowDays Days(DateTimeOffset now, double used, params LimitWindow[] samples) => + LimitAnalysis.Days(Week(now, used), samples, now, Zone)!; + + [Fact] public void EightDatesHaveRealPartialSharesAndEvenPace() + { + var days = Days(Start.AddMinutes(20), 1); + Assert.Equal(8, days.Current.Count); + Assert.Equal(TimeSpan.FromMinutes(80), days.Current[0].Share); + Assert.Equal(TimeSpan.FromHours(22).Add(TimeSpan.FromMinutes(40)), days.Current[^1].Share); + Assert.Equal(TimeSpan.FromDays(7).Ticks, days.Current.Sum(d => d.Share.Ticks)); + Assert.Equal(100, days.Current.Sum(d => d.EvenPace), 8); + Assert.Equal(100d * 80 / (7 * 24 * 60), days.Current[0].EvenPace, 8); + Assert.All(days.Current.Skip(1).SkipLast(1), d => Assert.Equal(TimeSpan.FromDays(1), d.Share)); + } + [Theory] + [InlineData(3, 29, 23)] + [InlineData(10, 25, 25)] + public void DaylightSavingSharesUseActualHours(int month, int date, int hours) + { + var zone = TimeZoneInfo.FindSystemTimeZoneById("Europe/Berlin"); + var day = CalendarDays.Start(new DateTime(2026, month, date), zone); + var now = day.AddHours(12); + var window = Week(now) with { ResetsAt = day.AddDays(3) }; + var days = LimitAnalysis.Days(window, [window with { SampleTime = day, UsedPercent = 20 }], now, zone)!; + var today = Assert.Single(days.Current, d => d.IsToday); + Assert.Equal(hours, today.Share.TotalHours); + Assert.Equal(100d * hours / 168, today.EvenPace, 8); + Assert.Equal(80d * hours / 72, today.Budget!.Value, 8); + } + [Fact] public void FirstPartialDayBudgetHoldsWhileSpending() + { + var first = Days(Start.AddMinutes(10), .2); + var later = Days(Start.AddMinutes(50), .7); + Assert.Equal(first.Current[0].EvenPace, first.TodayBudget); + Assert.Equal(first.TodayBudget, later.TodayBudget); + Assert.Equal(first.LaterBudget, later.LaterBudget); + Assert.Equal(UseOrigin.Measured, first.BudgetOrigin); + Assert.Equal(100, first.Current.Sum(d => d.Budget ?? 0), 8); + } + [Fact] public void MeasuredBaselineKeepsTodayAndLaterPlanUntilTodayExceedsBudget() + { + var day = CalendarDays.Start(Start.AddDays(3), Zone); + var baseline = Week(day, 25); + var first = Days(day.AddHours(2), 26, baseline); + var within = Days(day.AddHours(12), 30, baseline); + var exceeded = Days(day.AddHours(16), 60, baseline); + var expected = 75 / (Start.AddDays(7) - day).TotalDays; + Assert.Equal(expected, first.TodayBudget!.Value, 8); + Assert.Equal(first.TodayBudget, within.TodayBudget); + Assert.Equal(first.TodayBudget, exceeded.TodayBudget); + Assert.Equal(first.LaterBudget, within.LaterBudget); + Assert.True(exceeded.LaterBudget < first.LaterBudget); + Assert.Equal(UseOrigin.Measured, within.BudgetOrigin); + Assert.All(within.Current.Where(d => !d.IsToday && !d.IsFuture), d => Assert.Null(d.Budget)); + Assert.Equal(within.TodayBudget, Assert.Single(within.Current, d => d.IsToday).Budget); + Assert.Equal(100 - 25, within.Current.Sum(d => d.Budget ?? 0), 8); + Assert.Equal(0, Days(day.AddHours(17), 100, baseline).LaterBudget); + } + [Fact] public void TokenBaselineIsMarkedEstimated() + { + var day = CalendarDays.Start(Start.AddDays(3), Zone); + var now = day.AddHours(12); var window = Week(now, 40); + ModelTokenPoint[] tokens = [new(Start, "fixture", new(Input: 100)), new(day, "fixture", new(Input: 100))]; + var days = LimitAnalysis.Analyze(window, [], tokens, now, Zone)!.Days!; + Assert.Equal(UseOrigin.Estimated, days.BudgetOrigin); + Assert.Equal(80 / (window.ResetsAt!.Value - day).TotalDays, days.TodayBudget!.Value, 8); + } + [Fact] public void LastDayHasOnlyItsRemainingBudget() + { + var now = Start.AddDays(7).AddHours(-2); + var baseline = Week(CalendarDays.Start(now, Zone), 80); + var days = Days(now, 90, baseline); + Assert.Equal(20, days.TodayBudget); + Assert.Null(days.LaterBudget); + Assert.Equal(20, days.Current[^1].Budget); + Assert.DoesNotContain(days.Current, d => d.IsFuture); + } + [Fact] public void MissingBaselineAndExpiredResetHaveNoBudget() + { + var now = Start.AddDays(3); + var unknown = Days(now, 30); + Assert.Null(unknown.TodayBudget); Assert.Null(unknown.LaterBudget); Assert.Null(unknown.BudgetOrigin); + Assert.All(unknown.Current, d => Assert.Null(d.Budget)); + var expired = Days(Start.AddDays(7), 90, Week(Start.AddDays(6), 80)); + Assert.Null(expired.TodayBudget); Assert.Null(expired.LaterBudget); + Assert.All(expired.Current, d => Assert.Null(d.Budget)); + } +} diff --git a/tests/FinalToken.Core.Tests/EarlyForecastTests.cs b/tests/FinalToken.Core.Tests/EarlyForecastTests.cs index 5bcfbe3..35fdf7e 100644 --- a/tests/FinalToken.Core.Tests/EarlyForecastTests.cs +++ b/tests/FinalToken.Core.Tests/EarlyForecastTests.cs @@ -8,7 +8,7 @@ public class EarlyForecastTests private static LimitWindow Week(double used = 39) => new(Provider.Codex, "primary", "Week", used, new(2026, 10, 22, 6, 18, 0, TimeSpan.Zero), TimeSpan.FromDays(7), Now, "fixture"); - [Fact] public void AheadCodexWeekProjectsBeforeTenPercent() + [Fact] public void AheadCodexWeekProjectsEarly() { var window = Week(); var pace = Pace.Calculate(window, Now); Assert.Equal(PaceState.Ahead, pace.State); @@ -48,7 +48,7 @@ public class EarlyForecastTests [InlineData(40, false)] public void AllForecastsFollowConfiguredThreshold(double threshold, bool eligible) { - var window = Week(); var pace = Pace.Calculate(window, Now, threshold); + var window = Week() with { Length = TimeSpan.FromDays(28), ResetsAt = Now.AddDays(28).AddHours(-4) }; var pace = Pace.Calculate(window, Now, threshold); Assert.Equal(eligible, pace.State == PaceState.Ahead); Assert.Equal(eligible, Pace.CanForecast(window, Now, threshold)); Assert.Equal(eligible, pace.Projection is not null); @@ -67,10 +67,19 @@ public class EarlyForecastTests Assert.NotNull(LimitAnalysis.Recent(window, [window with { SampleTime = Now.AddHours(-4), UsedPercent = 20 }], Now, pace)); } - [Fact] public void ForecastStartIsTenPercentIntoWindow() + [Fact] public void UnderPaceCodexAtSixPointFourPercentShowsUseAtReset() + { + var window = Week(4) with { ResetsAt = Now + TimeSpan.FromTicks(TimeSpan.FromDays(7).Ticks * 936 / 1000) }; + var pace = Pace.Calculate(window, Now); + Assert.Equal(PaceState.OnTrack, pace.State); + Assert.Null(pace.Projection); + Assert.Equal(62.5, LimitAnalysis.AverageUseAtReset(window, Now)!.Value, 8); + } + + [Fact] public void ForecastStartIsTwoPercentIntoWindow() { var window = Week(1); - Assert.Equal(window.ResetsAt - TimeSpan.FromDays(6.3), Pace.ForecastStartsAt(window)); + Assert.Equal(window.ResetsAt - TimeSpan.FromTicks(TimeSpan.FromDays(7).Ticks * 49 / 50), Pace.ForecastStartsAt(window)); Assert.Null(Pace.ForecastStartsAt(window with { Length = null })); Assert.Null(Pace.ForecastStartsAt(window with { ResetsAt = null })); Assert.Null(Pace.ForecastStartsAt(window with { Length = TimeSpan.Zero })); diff --git a/tests/FinalToken.Core.Tests/LimitAnalysisTests.cs b/tests/FinalToken.Core.Tests/LimitAnalysisTests.cs index b88d450..bcddf6b 100644 --- a/tests/FinalToken.Core.Tests/LimitAnalysisTests.cs +++ b/tests/FinalToken.Core.Tests/LimitAnalysisTests.cs @@ -126,7 +126,7 @@ public sealed class LimitAnalysisTests { var w = Window(); var days = LimitAnalysis.Days(w, [w with { SampleTime = Now.AddHours(-14), UsedPercent = 51 }], Now, TimeZoneInfo.Utc)!; - Assert.Equal(9, days.Today); Assert.Equal(100d / 7, days.EvenPace); Assert.Equal(40 / 3.5, days.DailyBudget); + Assert.Equal(9, days.Today); Assert.Equal(100d / 7, days.EvenPace); Assert.Equal(49d / 4, days.TodayBudget); Assert.Contains(days.Current, d => d.IsFuture && d.Used is null); Assert.Contains(days.Current, d => d.Start == Now.AddHours(-36) && d.Used is null); Assert.Null(LimitAnalysis.Days(w, [], Now, TimeZoneInfo.Utc)!.Today); diff --git a/tests/FinalToken.Core.Tests/TokenEstimateTests.cs b/tests/FinalToken.Core.Tests/TokenEstimateTests.cs index 145f8e7..2af55c7 100644 --- a/tests/FinalToken.Core.Tests/TokenEstimateTests.cs +++ b/tests/FinalToken.Core.Tests/TokenEstimateTests.cs @@ -134,10 +134,10 @@ public sealed class TokenEstimateTests [Theory] [InlineData(5)] [InlineData(168)] - public void ForecastsBeginAtExactlyTenPercentWithoutChangingState(int hours) + public void ForecastsBeginAtExactlyTwoPercentWithoutChangingState(int hours) { var start = Start; var length = TimeSpan.FromHours(hours); - var atThreshold = start + TimeSpan.FromTicks(length.Ticks / 10); + var atThreshold = start + TimeSpan.FromTicks(length.Ticks / 50); var before = atThreshold.AddTicks(-1); var window = Window with { ResetsAt = start + length, Length = length, SampleTime = before, UsedPercent = 11 }; Assert.Equal(PaceState.OnTrack, Pace.Calculate(window, before).State); diff --git a/tests/FinalToken.Core.Tests/WeekTotalsTests.cs b/tests/FinalToken.Core.Tests/WeekTotalsTests.cs new file mode 100644 index 0000000..777513e --- /dev/null +++ b/tests/FinalToken.Core.Tests/WeekTotalsTests.cs @@ -0,0 +1,59 @@ +using System.Text.Json; +using Xunit; + +namespace FinalToken.Core.Tests; + +public sealed class WeekTotalsTests +{ + [Theory] + [InlineData("limit", true)] + [InlineData("family", false)] + [InlineData("expired", false)] + [InlineData("missing", false)] + [InlineData("mixed", true)] + public async Task EngineSelectsProviderWeekOrCalendarFallback(string kind, bool limit) + { + using var directory = new TestDirectory(); + var clock = new WeekClock(); var now = clock.GetUtcNow(); + await using var engine = new RefreshEngine(directory.Path, clock, claudeDirectory: directory.Path, codexDirectory: directory.Path, + cliDiscovery: (_, _) => new(null, "Fixture CLI missing.")); + var start = new DateTimeOffset(2026, 10, 10, 22, 40, 0, TimeSpan.Zero); + var week = new LimitWindow(Provider.Codex, "week", "Week", 30, start.AddDays(7), TimeSpan.FromDays(7), now, "fixture"); + var family = week with { Id = "family", Label = "Week (Fable)", Length = TimeSpan.FromDays(8) }; + engine.History.AddLimits(kind switch + { + "limit" => [week], "family" => [family], "expired" => [week with { ResetsAt = now.AddHours(-1) }], + "mixed" => [family, week, week with { Id = "short", Length = TimeSpan.FromDays(2) }], _ => [] + }); + foreach (var (time, count) in new[] { (now.AddDays(-5), 10), (now.AddDays(-3), 20), (now.AddDays(-1), 30) }) + engine.History.Add(new(Provider.Codex, time, "fixture", "fixture", new(Total: count), count.ToString())); + var snapshot = await engine.RefreshNowAsync(true, TestContext.Current.CancellationToken); + var provider = snapshot.Providers.Single(p => p.Provider == Provider.Codex); + Assert.Equal(limit ? 50 : 30, provider.Week.Total); + Assert.Equal(limit ? start : new DateTimeOffset(2026, 10, 12, 0, 0, 0, TimeSpan.Zero), provider.WeekStart); + Assert.Equal(limit ? "week" : null, provider.WeekWindow); + } + [Theory] + [InlineData(true)] + [InlineData(false)] + public void SourceGeneratedJsonReadsNewAndLegacyWeekFields(bool limit) + { + var start = new DateTimeOffset(2026, 10, 10, 22, 40, 0, TimeSpan.Zero); + var snapshot = new Snapshot { MadeAt = start.AddDays(2), RefreshInterval = TimeSpan.FromMinutes(1), + Providers = [new(Provider.Codex, ProviderStatus.Available, null, [], new(), null, new(Total: 30), start, limit ? "week" : null)] }; + var json = JsonSerializer.Serialize(snapshot, CoreJsonContext.Default.Snapshot); + Assert.Contains("\"weekStart\"", json); + Assert.Equal(limit, json.Contains("\"weekWindow\"", StringComparison.Ordinal)); + var provider = Assert.Single(JsonSerializer.Deserialize(json, CoreJsonContext.Default.Snapshot)!.Providers); + Assert.Equal(start, provider.WeekStart); Assert.Equal(limit ? "week" : null, provider.WeekWindow); + const string old = """{"v":1,"madeAt":"2026-10-14T16:00:00Z","refreshInterval":"00:01:00","providers":[{"provider":1,"status":0,"windows":[],"today":{},"session":null,"week":{"total":30}}]}"""; + var legacy = JsonSerializer.Deserialize(old, CoreJsonContext.Default.Snapshot)!; + Assert.Equal(1, legacy.V); Assert.Equal(30, legacy.Providers[0].Week.Total); + Assert.Equal(default, legacy.Providers[0].WeekStart); Assert.Null(legacy.Providers[0].WeekWindow); + } + private sealed class WeekClock : TimeProvider + { + public override DateTimeOffset GetUtcNow() => new(2026, 10, 14, 16, 0, 0, TimeSpan.Zero); + public override TimeZoneInfo LocalTimeZone => TimeZoneInfo.Utc; + } +} -- 2.54.0 From 158572c2ba9a13d23ab92be149fd20e370974546 Mon Sep 17 00:00:00 2001 From: Florian Schmidt Date: Sun, 18 Oct 2026 10:02:02 +0200 Subject: [PATCH 3/6] docs: take an estimated day baseline's scale from the day's first sample With the newest sample's scale, use from the web or another device moved an estimated day baseline, and the daily budget moved with it while today stayed within its plan (review of #15). Refs #13 --- docs/decisions.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index d46d897..287a564 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -172,7 +172,8 @@ probe. `(100 − u₀) · today's share / (r − s)`; use during the day does not change it. A later day's budget is `(100 − max(u, u₀ + today's budget)) · its share / (r − end of today)`, so later days lose budget only once today's use passes today's budget. `u₀` is measured, or estimated as - below and then marked; without it there is no budget. + below and then marked. An estimated `u₀` takes `k` from the first sample at or after `s`, not + the newest, so later samples do not move it. Without `u₀` there is no budget. - **Estimates from tokens.** Where samples do not cover a span, its use is estimated from the token history. Tokens are weighted by the provider's API price ratios: Claude input 1, output 5, cache write 1.25, cache read 0.1; Codex uncached input 1, cached input 0.1, @@ -202,7 +203,9 @@ date shows from the first point over pace. The day figures answer "how much of t use today" and "how much may I use per day from now on" (developer feedback, 2026-10-14). A budget computed from `u` and the time now fell with every use, even within the day's plan, and held a partial first day to a full day's pace; a budget set at the start of the day can be -compared with the day's bar (developer feedback, 2026-10-18). +compared with the day's bar (developer feedback, 2026-10-18). An estimated `u₀` with the newest +`k` moved whenever use from the web or another device changed the scale, and the budget moved +with it. Measured samples alone left the day chart empty until the app had run for a whole week, while the token history already covers it; the estimate fills it at once and agrees with the measured use of the instance by construction (developer feedback, 2026-10-15). A window that is ahead early is @@ -217,7 +220,9 @@ the first hours a forecast can move by days. Measured day figures are only as fine as the samples (D5 keeps one per hour while the value stands still). Estimates miss use from other devices and from claude.ai or the web, which counts against the limit but leaves no local tokens; they also miss changes in model mix within -an instance and any weighting the provider applies beyond the price ratios. +an instance and any weighting the provider applies beyond the price ratios. An estimated `u₀` +keeps the first sample's scale for the whole day, even when later samples would estimate it +better. ## D8 — Desktop app -- 2.54.0 From 09f7633eb5dfdfdddbb0861930379df014b7273b Mon Sep 17 00:00:00 2001 From: Florian Schmidt Date: Sun, 18 Oct 2026 10:08:59 +0200 Subject: [PATCH 4/6] core: keep an estimated day baseline fixed and the tile rows equal An estimated day baseline took its scale from the newest sample, so use from the web lowered the budget while today stayed within it. It now takes the scale from the first sample at or after the day start (D7). The stale sample warning moves into the "used" caption, so tiles of one kind keep the same rows (D8). Both answer the first review of #15. Refs #13 --- src/FinalToken.App/PanelWindow.cs | 5 +- src/FinalToken.Core/LimitDays.cs | 23 ++++++-- src/FinalToken.Core/LimitEstimates.cs | 6 +-- tests/FinalToken.App.Tests/HeadlessTests.cs | 13 +++++ tests/FinalToken.Core.Tests/DayBudgetTests.cs | 54 +++++++++++++++++++ 5 files changed, 92 insertions(+), 9 deletions(-) diff --git a/src/FinalToken.App/PanelWindow.cs b/src/FinalToken.App/PanelWindow.cs index 9898759..5c9e85b 100644 --- a/src/FinalToken.App/PanelWindow.cs +++ b/src/FinalToken.App/PanelWindow.cs @@ -198,7 +198,9 @@ public sealed class PanelWindow : Window DockPanel.SetDock(chip, Dock.Right); title.Children.Add(chip); title.Children.Add(Ui.Text(w.Provider + " · " + w.Label, 15)); var card = Ui.Stack(title); void Row(string name, Control control) { control.Name = name; card.Children.Add(control); } - Row("Percent", Ui.Text($"{w.UsedPercent:0.#} %", 36)); Row("Used", Ui.Text("used", 12, "Muted")); + Row("Percent", Ui.Text($"{w.UsedPercent:0.#} %", 36)); + Row("Used", Ui.Text(now - w.SampleTime > model.ProbeInterval * 2 + ? $"used · ⚠ sample {Display.Duration(now - w.SampleTime)} old" : "used", 12, "Muted")); Row("Pace", new PaceBar(window, now) { Height = 10 }); Row("Reset", Ui.Text(w.ResetsAt is { } reset ? $"Resets in {Display.Duration(reset - now)} · {Display.Projection(reset, clock)}" : "Reset unknown", 13, "Secondary")); if (pace.Projection is { } projection) @@ -233,7 +235,6 @@ public sealed class PanelWindow : Window else if (days?.TodayBudget is not null && w.ResetsAt is { } lastReset) plan += " · last day, resets " + Display.Time(lastReset, clock); Row("Plan", Ui.Text(plan, 13, "Secondary")); } - if (now - w.SampleTime > model.ProbeInterval * 2) Row("Stale", Ui.Text($"⚠ sample {Display.Duration(now - w.SampleTime)} old", 12, "Muted")); var tile = Ui.Card(card); tile.Name = $"LimitTile-{w.Provider}-{w.Id}"; ToolTip.SetTip(tile, new DataTooltip(w.Provider + " · " + w.Label, new("Used", $"{w.UsedPercent:0.##} %"), new("Expected", $"{pace.ElapsedFraction * 100:0.##} %"), new("State", Display.State(pace.State)), new("Reset", w.ResetsAt is { } r ? Display.Projection(r, clock) : "Unknown"), new("Sample", w.SampleTime.LocalDateTime.ToString("g")))); return tile; diff --git a/src/FinalToken.Core/LimitDays.cs b/src/FinalToken.Core/LimitDays.cs index 4f0744b..a3d218e 100644 --- a/src/FinalToken.Core/LimitDays.cs +++ b/src/FinalToken.Core/LimitDays.cs @@ -2,9 +2,18 @@ namespace FinalToken.Core; public static partial class LimitAnalysis { + private static double WeightedTokens(IReadOnlyList<(DateTimeOffset Time, double Weight)> weighted, + DateTimeOffset start, DateTimeOffset end, DateTimeOffset from, DateTimeOffset to) + { + var hour = Hour(from < start ? start : from); + var exclusiveEnd = Hour(end); + return weighted.Where(p => p.Time >= hour && p.Time < to && p.Time < exclusiveEnd).Sum(p => p.Weight); + } + // D7: plan from the day baseline; spending within that plan does not take from later days. private static WindowDays PlanDays(LimitWindow window, LimitInstance current, LimitInstance? previous, - LimitDay? today, IReadOnlyList observations, DateTimeOffset now, TimeZoneInfo zone) + LimitDay? today, IReadOnlyList observations, IReadOnlyList<(DateTimeOffset Time, double Weight)> weighted, + DateTimeOffset now, TimeZoneInfo zone) { var length = window.Length!.Value; double? baseline = null; UseOrigin? origin = null; @@ -15,8 +24,16 @@ public static partial class LimitAnalysis if (start == current.Start) { baseline = 0; origin = UseOrigin.Measured; } else if (Instance(window, observations).LastOrDefault(s => s.SampleTime >= current.Start && s.SampleTime <= start) is { } sample) { baseline = sample.UsedPercent; origin = UseOrigin.Measured; } - else if (today is { Origin: UseOrigin.Estimated, Cumulative: { } cumulative, Used: { } use }) - { baseline = Math.Max(0, cumulative - use); origin = UseOrigin.Estimated; } + else if (Instance(window, observations).FirstOrDefault(s => s.SampleTime >= start) is { } first) + { + // D7: only the first observation after day start calibrates the budget baseline. + var denominator = WeightedTokens(weighted, current.Start, current.End, current.Start, first.SampleTime); + if (denominator > 0) + { + baseline = first.UsedPercent / denominator * WeightedTokens(weighted, current.Start, current.End, current.Start, start); + origin = UseOrigin.Estimated; + } + } if (baseline is { } used) { todayBudget = Math.Max(0, 100 - used) * (today.End - start).TotalDays / (current.Reset - start).TotalDays; diff --git a/src/FinalToken.Core/LimitEstimates.cs b/src/FinalToken.Core/LimitEstimates.cs index 6e60ab4..e91656f 100644 --- a/src/FinalToken.Core/LimitEstimates.cs +++ b/src/FinalToken.Core/LimitEstimates.cs @@ -66,7 +66,7 @@ public static partial class LimitAnalysis if (length > TimeSpan.FromDays(1)) { var today = current.Days.FirstOrDefault(d => d.IsToday); - days = PlanDays(window, current, past.FirstOrDefault(), today, observations, now, zone); + days = PlanDays(window, current, past.FirstOrDefault(), today, observations, weighted, now, zone); } return new(current, past, days); @@ -75,9 +75,7 @@ public static partial class LimitAnalysis { double Weight(DateTimeOffset from, DateTimeOffset to) { - var hour = Hour(from < start ? start : from); - var exclusiveEnd = Hour(end); - return weighted.Where(p => p.Time >= hour && p.Time < to && p.Time < exclusiveEnd).Sum(p => p.Weight); + return WeightedTokens(weighted, start, end, from, to); } var measured = Instance(anchor, observations).Where(s => s.SampleTime >= start - TimeSpan.FromMinutes(15) && s.SampleTime <= until) .GroupBy(s => s.SampleTime).Select(g => g.Last()).OrderBy(s => s.SampleTime).ToArray(); diff --git a/tests/FinalToken.App.Tests/HeadlessTests.cs b/tests/FinalToken.App.Tests/HeadlessTests.cs index a9a5775..b0e0e49 100644 --- a/tests/FinalToken.App.Tests/HeadlessTests.cs +++ b/tests/FinalToken.App.Tests/HeadlessTests.cs @@ -186,6 +186,19 @@ public sealed class HeadlessTests Save(budgetPanel, $"budget-1280x1000-{theme}-{name}.png"); } } + budgetModel.Snapshot = budgetSnapshot with { Providers = budgetSnapshot.Providers.Select(p => p.Provider == Provider.Codex + ? p with { Windows = p.Windows.Select(w => w with { Window = w.Window with { SampleTime = budgetClock.GetUtcNow().AddMinutes(-15) } }).ToArray() } + : p).ToArray() }; + Dispatcher.UIThread.RunJobs(); + Assert.Equal(longRows, Rows(Provider.Claude)); Assert.Equal(longRows, Rows(Provider.Codex)); + var staleWeek = budgetPanel.GetVisualDescendants().OfType().Single(b => b.Name == "LimitTile-Codex-week"); + var freshWeek = budgetPanel.GetVisualDescendants().OfType().Single(b => b.Name == "LimitTile-Claude-week"); + var staleUsed = staleWeek.GetVisualDescendants().OfType().Single(t => t.Name == "Used"); + Assert.Equal("used · ⚠ sample 15 min old", staleUsed.Text); + Assert.Equal(12, staleUsed.FontSize); Assert.Equal("#ff898781", staleUsed.Foreground?.ToString()); + Assert.Equal("used", freshWeek.GetVisualDescendants().OfType().Single(t => t.Name == "Used").Text); + budgetPanel.GetVisualDescendants().OfType().First().Offset = default; + SaveThemes(budgetPanel, "budget-stale-1280x1000"); budgetModel.History = new([], [], [], [], []); budgetModel.Snapshot = budgetSnapshot with { Providers = budgetSnapshot.Providers.Select(p => { diff --git a/tests/FinalToken.Core.Tests/DayBudgetTests.cs b/tests/FinalToken.Core.Tests/DayBudgetTests.cs index 464fcf6..88321f0 100644 --- a/tests/FinalToken.Core.Tests/DayBudgetTests.cs +++ b/tests/FinalToken.Core.Tests/DayBudgetTests.cs @@ -75,6 +75,60 @@ public sealed class DayBudgetTests Assert.Equal(UseOrigin.Estimated, days.BudgetOrigin); Assert.Equal(80 / (window.ResetsAt!.Value - day).TotalDays, days.TodayBudget!.Value, 8); } + [Fact] public void FirstSampleKeepsEstimatedBudgetStableWhenLaterUseHasNoLocalTokens() + { + var day = CalendarDays.Start(Start.AddDays(3), Zone); + var first = Week(day.AddHours(2), 20); + var newest = Week(day.AddHours(12), 22); + ModelTokenPoint[] tokens = [new(day.AddHours(-1), "fixture", new(Input: 100)), new(day.AddHours(1), "fixture", new(Input: 100))]; + var initial = LimitAnalysis.Analyze(first, [], tokens, first.SampleTime, Zone)!.Days!; + var later = LimitAnalysis.Analyze(newest, [first], tokens, newest.SampleTime, Zone)!.Days!; + var remainingDays = (first.ResetsAt!.Value - day).TotalDays; + var expectedBudget = 90 / remainingDays; + Assert.Equal(18.202247191, expectedBudget, 8); + Assert.Equal(10, initial.Today); Assert.Equal(11, later.Today); + foreach (var days in new[] { initial, later }) + { + Assert.Equal(10, 100 - days.TodayBudget!.Value * remainingDays, 8); + Assert.Equal(expectedBudget, days.TodayBudget.Value, 8); + Assert.Equal(expectedBudget, days.LaterBudget!.Value, 8); + Assert.Equal(UseOrigin.Estimated, days.BudgetOrigin); + Assert.Equal(UseOrigin.Estimated, days.TodayOrigin); + Assert.True(days.Today < days.TodayBudget); + Assert.All(days.Current.Where(d => d.IsToday || d.IsFuture), d => Assert.Equal(UseOrigin.Estimated, d.BudgetOrigin)); + } + Assert.Equal(initial.Current.Select(d => d.Budget), later.Current.Select(d => d.Budget)); + } + [Fact] public void FirstSampleWithoutTokensCannotCalibrateABudgetFromLaterTokens() + { + var day = CalendarDays.Start(Start.AddDays(3), Zone); + var first = Week(day.AddHours(2), 20); + var newest = Week(day.AddHours(12), 22); + ModelTokenPoint[] tokens = [new(day.AddHours(3), "fixture", new(Input: 100))]; + var days = LimitAnalysis.Analyze(newest, [first], tokens, newest.SampleTime, Zone)!.Days!; + Assert.NotNull(days.Today); + Assert.Null(days.TodayBudget); Assert.Null(days.LaterBudget); Assert.Null(days.BudgetOrigin); + Assert.All(days.Current, d => { Assert.Null(d.Budget); Assert.Null(d.BudgetOrigin); }); + } + [Theory] + [InlineData(-1)] + [InlineData(0)] + public void MeasuredBaselineWinsOverFirstSampleTokenCalibration(int minutes) + { + var day = CalendarDays.Start(Start.AddDays(3), Zone); + var baseline = Week(day.AddMinutes(minutes), 25); + var first = Week(day.AddHours(2), 26); + var newest = Week(day.AddHours(12), 30); + ModelTokenPoint[] tokens = [new(day.AddHours(-1), "fixture", new(Input: 100)), new(day.AddHours(1), "fixture", new(Input: 100))]; + var days = LimitAnalysis.Analyze(newest, [first, baseline, baseline with { SampleTime = day.AddHours(-1), UsedPercent = 20 }], + tokens, newest.SampleTime, Zone)!.Days!; + var expected = 75 / (newest.ResetsAt!.Value - day).TotalDays; + Assert.Equal(expected, days.TodayBudget!.Value, 8); + Assert.Equal(expected, days.LaterBudget!.Value, 8); + Assert.Equal(UseOrigin.Measured, days.BudgetOrigin); + Assert.Equal(UseOrigin.Measured, days.TodayOrigin); + Assert.Equal(5, days.Today); + } [Fact] public void LastDayHasOnlyItsRemainingBudget() { var now = Start.AddDays(7).AddHours(-2); -- 2.54.0 From d2cf2c282a9109f2a37535d915779b113d584879 Mon Sep 17 00:00:00 2001 From: Florian Schmidt Date: Sun, 18 Oct 2026 10:23:32 +0200 Subject: [PATCH 5/6] docs: count only whole hours before the first sample for an estimated baseline Token history is kept per hour, and the hour that holds the day's first sample keeps growing after it, so use in that hour still moved the budget (second review of #15). The developer chose another round with this rule on 2026-10-18. Refs #13 --- docs/decisions.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index 287a564..8b32bff 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -173,7 +173,8 @@ probe. budget is `(100 − max(u, u₀ + today's budget)) · its share / (r − end of today)`, so later days lose budget only once today's use passes today's budget. `u₀` is measured, or estimated as below and then marked. An estimated `u₀` takes `k` from the first sample at or after `s`, not - the newest, so later samples do not move it. Without `u₀` there is no budget. + the newest, and counts only the whole hours before that sample's hour, so later samples and + tokens do not move it. Without `u₀` there is no budget. - **Estimates from tokens.** Where samples do not cover a span, its use is estimated from the token history. Tokens are weighted by the provider's API price ratios: Claude input 1, output 5, cache write 1.25, cache read 0.1; Codex uncached input 1, cached input 0.1, @@ -205,7 +206,7 @@ budget computed from `u` and the time now fell with every use, even within the d held a partial first day to a full day's pace; a budget set at the start of the day can be compared with the day's bar (developer feedback, 2026-10-18). An estimated `u₀` with the newest `k` moved whenever use from the web or another device changed the scale, and the budget moved -with it. +with it; the token hour that holds the first sample keeps growing after it. Measured samples alone left the day chart empty until the app had run for a whole week, while the token history already covers it; the estimate fills it at once and agrees with the measured use of the instance by construction (developer feedback, 2026-10-15). A window that is ahead early is @@ -222,7 +223,7 @@ stands still). Estimates miss use from other devices and from claude.ai or the w counts against the limit but leaves no local tokens; they also miss changes in model mix within an instance and any weighting the provider applies beyond the price ratios. An estimated `u₀` keeps the first sample's scale for the whole day, even when later samples would estimate it -better. +better, and overstates `u₀` by the use in that sample's hour before the sample. ## D8 — Desktop app -- 2.54.0 From 8bde2a3b0eb6ca761763a4d78de3e1e57f894126 Mon Sep 17 00:00:00 2001 From: Florian Schmidt Date: Sun, 18 Oct 2026 10:38:22 +0200 Subject: [PATCH 6/6] core: estimate the day baseline from whole hours before the first sample The second review found that the hour bucket holding the first sample keeps growing after it, so use later in that hour still moved the estimated baseline and both budgets. Following D7, the estimate now counts only the whole hours before that sample's hour. No counted bucket can grow after the sample, so later samples and tokens no longer move it. Refs #13 --- src/FinalToken.Core/LimitDays.cs | 8 +- tests/FinalToken.Core.Tests/DayBudgetTests.cs | 73 +++++++++++++++++++ 2 files changed, 78 insertions(+), 3 deletions(-) diff --git a/src/FinalToken.Core/LimitDays.cs b/src/FinalToken.Core/LimitDays.cs index a3d218e..ee97ec1 100644 --- a/src/FinalToken.Core/LimitDays.cs +++ b/src/FinalToken.Core/LimitDays.cs @@ -26,11 +26,13 @@ public static partial class LimitAnalysis { baseline = sample.UsedPercent; origin = UseOrigin.Measured; } else if (Instance(window, observations).FirstOrDefault(s => s.SampleTime >= start) is { } first) { - // D7: only the first observation after day start calibrates the budget baseline. - var denominator = WeightedTokens(weighted, current.Start, current.End, current.Start, first.SampleTime); + // D7: use only completed hours before the first sample; its own hour can still grow. + var sampleHour = Hour(first.SampleTime); + var baselineEnd = start < sampleHour ? start : sampleHour; + var denominator = WeightedTokens(weighted, current.Start, current.End, current.Start, sampleHour); if (denominator > 0) { - baseline = first.UsedPercent / denominator * WeightedTokens(weighted, current.Start, current.End, current.Start, start); + baseline = first.UsedPercent * WeightedTokens(weighted, current.Start, current.End, current.Start, baselineEnd) / denominator; origin = UseOrigin.Estimated; } } diff --git a/tests/FinalToken.Core.Tests/DayBudgetTests.cs b/tests/FinalToken.Core.Tests/DayBudgetTests.cs index 88321f0..d94be07 100644 --- a/tests/FinalToken.Core.Tests/DayBudgetTests.cs +++ b/tests/FinalToken.Core.Tests/DayBudgetTests.cs @@ -99,6 +99,79 @@ public sealed class DayBudgetTests } Assert.Equal(initial.Current.Select(d => d.Budget), later.Current.Select(d => d.Budget)); } + [Fact] public void TokensAddedInFirstSampleHourDoNotMoveEstimatedBudgets() + { + var day = CalendarDays.Start(Start.AddDays(3), Zone); + var first = Week(day.AddHours(2).AddMinutes(5), 20); + var newest = Week(day.AddHours(2).AddMinutes(30), 22); + // Hourly buckets for 100 input tokens at 23:30 and 02:01 local. + ModelTokenPoint[] tokens = [new(day.AddHours(-1), "fixture", new(Input: 100)), new(day.AddHours(2), "fixture", new(Input: 100))]; + var initial = LimitAnalysis.Analyze(first, [], tokens, first.SampleTime, Zone)!.Days!; + ModelTokenPoint[] moreTokens = [.. tokens, new(day.AddHours(2), "fixture", new(Input: 100))]; + var later = LimitAnalysis.Analyze(newest, [first], moreTokens, newest.SampleTime, Zone)!.Days!; + var remainingDays = (first.ResetsAt!.Value - day).TotalDays; + var expectedBudget = 80 / remainingDays; + Assert.Equal(10, initial.Today); Assert.Equal(22d * 200 / 300, later.Today!.Value, 8); + foreach (var days in new[] { initial, later }) + { + Assert.Equal(20, 100 - days.TodayBudget!.Value * remainingDays, 8); + Assert.Equal(expectedBudget, days.TodayBudget.Value, 8); + Assert.Equal(expectedBudget, days.LaterBudget!.Value, 8); + Assert.Equal(UseOrigin.Estimated, days.BudgetOrigin); + Assert.Equal(UseOrigin.Estimated, days.TodayOrigin); + Assert.True(days.Today < days.TodayBudget); + Assert.All(days.Current.Where(d => d.IsToday || d.IsFuture), d => Assert.Equal(UseOrigin.Estimated, d.BudgetOrigin)); + } + Assert.Equal(initial.TodayBudget, later.TodayBudget); + Assert.Equal(initial.LaterBudget, later.LaterBudget); + Assert.Equal(initial.Current.Select(d => d.Budget), later.Current.Select(d => d.Budget)); + } + [Fact] public void FirstSampleInFirstHourUsesItsPercentAsEstimatedBaseline() + { + var day = CalendarDays.Start(Start.AddDays(3), Zone); + var first = Week(day.AddMinutes(5), 20); + ModelTokenPoint[] tokens = [new(day.AddHours(-1), "fixture", new(Input: 100)), new(day, "fixture", new(Input: 100))]; + var days = LimitAnalysis.Analyze(first, [], tokens, first.SampleTime, Zone)!.Days!; + var remainingDays = (first.ResetsAt!.Value - day).TotalDays; + Assert.Equal(first.UsedPercent, 100 - days.TodayBudget!.Value * remainingDays, 8); + Assert.Equal(80 / remainingDays, days.TodayBudget.Value, 8); + Assert.Equal(80 / remainingDays, days.LaterBudget!.Value, 8); + Assert.Equal(UseOrigin.Estimated, days.BudgetOrigin); + } + [Fact] public void HalfHourZoneExcludesTheUtcHourContainingMidnightFromEstimatedBaseline() + { + var zone = TimeZoneInfo.CreateCustomTimeZone("Fixture+0530", TimeSpan.FromHours(5.5), "Fixture", "Fixture"); + var day = CalendarDays.Start(new DateTime(2026, 10, 13), zone); + var firstHour = day.AddMinutes(-30); + var first = Week(day.AddMinutes(5), 20); + var newest = Week(day.AddMinutes(15), 22); + ModelTokenPoint[] tokens = [new(firstHour.AddHours(-1), "fixture", new(Input: 100)), new(firstHour, "fixture", new(Input: 100))]; + var initial = LimitAnalysis.Analyze(first, [], tokens, first.SampleTime, zone)!.Days!; + ModelTokenPoint[] moreTokens = [.. tokens, new(firstHour, "fixture", new(Input: 100))]; + var later = LimitAnalysis.Analyze(newest, [first], moreTokens, newest.SampleTime, zone)!.Days!; + var remainingDays = (first.ResetsAt!.Value - day).TotalDays; + foreach (var days in new[] { initial, later }) + { + Assert.Equal(first.UsedPercent, 100 - days.TodayBudget!.Value * remainingDays, 8); + Assert.Equal(80 / remainingDays, days.TodayBudget.Value, 8); + Assert.Equal(80 / remainingDays, days.LaterBudget!.Value, 8); + Assert.Equal(UseOrigin.Estimated, days.BudgetOrigin); + } + Assert.Equal(initial.TodayBudget, later.TodayBudget); + Assert.Equal(initial.LaterBudget, later.LaterBudget); + Assert.Equal(initial.Current.Select(d => d.Budget), later.Current.Select(d => d.Budget)); + } + [Fact] public void NoWholeHourTokensBeforeFirstSampleLeavesBudgetUnknown() + { + var day = CalendarDays.Start(Start.AddDays(3), Zone); + var first = Week(day.AddHours(2).AddMinutes(5), 20); + var newest = Week(day.AddHours(2).AddMinutes(30), 22); + ModelTokenPoint[] tokens = [new(day.AddHours(2), "fixture", new(Input: 100))]; + var days = LimitAnalysis.Analyze(newest, [first], tokens, newest.SampleTime, Zone)!.Days!; + Assert.NotNull(days.Today); + Assert.Null(days.TodayBudget); Assert.Null(days.LaterBudget); Assert.Null(days.BudgetOrigin); + Assert.All(days.Current, d => { Assert.Null(d.Budget); Assert.Null(d.BudgetOrigin); }); + } [Fact] public void FirstSampleWithoutTokensCannotCalibrateABudgetFromLaterTokens() { var day = CalendarDays.Start(Start.AddDays(3), Zone); -- 2.54.0