From a8785fa453391130e18cca9e00f4431024d02abc Mon Sep 17 00:00:00 2001 From: Florian Schmidt Date: Sun, 18 Oct 2026 09:37:00 +0200 Subject: [PATCH 01/14] 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 3ab1ce4f95951659174832a54735fe3f6ce51b64 Mon Sep 17 00:00:00 2001 From: Florian Schmidt Date: Sun, 18 Oct 2026 09:37:21 +0200 Subject: [PATCH 02/14] docs: record the reset history, API value at list prices and window series The developer asked for figures per reset, with wastage, API value and the gift of early resets (D12, D13). Codex moves its week between slots, so analyses follow a window series (D7). The reset hour before a gap goes to the ending instance (#9). Refs #14 --- docs/decisions.md | 70 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 67 insertions(+), 3 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index 8678a77..6660872 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -179,12 +179,20 @@ probe. is reached stops use, so an estimate that would pass it shows "limit reached (estimated)" at the time it crosses. No tokens in the instance means no estimate. Instance boundaries come from resets: an instance starts at its reset minus its length, and ends at its reset or at the next - instance's start, whichever comes first (Codex can start a new window early). Spans between - instances (a session window opens only with the next message) belong to none. A past instance + instance's start, whichever comes first (Codex can start a new window early). Tokens are + hourly (D5): an hour that holds a boundary goes to the instance that starts in it, or, when + none does, to the instance that ends in it. Other spans between instances (a session window + opens only with the next message) belong to none. A sample whose reset contradicts a later + instance's start is stale and is ignored. A past instance with samples is always the real one; an instance is only inferred where no samples exist, by stepping back one window length, and never overlaps a real one. Windows of a day or shorter are never inferred, since a session starts with whatever message comes next. Past instances are labelled with their real start and end. +- **Window series.** The samples of one limit share the provider, the limit name and the + length. The limit name is the window id without a Codex slot suffix (`:primary`, + `:secondary`): Codex moves a limit between its slots when another limit appears or goes, as + its week did on 2026-09-13 when its 5 h limit went away. Every analysis of a window reads its + series, never a window of another length under the same id. A window without a known length or reset has no pace; FinalToken never guesses one; an estimate is a marked calculation from measured tokens, not a guess. @@ -223,7 +231,8 @@ an instance and any weighting the provider applies beyond the price ratios. - **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 - window, and the top entries by model and by project, with the rest folded into an expandable + window, the reset history of each long window ([D12](#d12--reset-history)), 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 from 0 % to 100 %, the forecast to the reset and the previous instance faintly behind, with no @@ -295,3 +304,58 @@ setting says so and nothing happens. **Why.** R7. **Gives up.** Elgato's double-click `.streamDeckPlugin` installer, which always asks. + +## D12 — Reset history + +**Decision.** For each limit window longer than a day, the panel lists the instances of its +window series ([D7](#d7--pace)) that have samples and overlap the panel's range, newest first, +with totals over them. Inferred instances are left out, because their resets were not observed. + +- **End.** An instance ends at its reset or at the next instance's start (D7). One that ends + more than 15 minutes before its reset **reset early**, and the time from its end to its reset + is **skipped**. The running instance is marked as running and has no end figures yet. +- **Figures.** Start, end, duration and reset; peak and final use (the last point of its D7 + burn-up, marked when estimated); when it reached 100 % and how long it stayed there; tokens by + kind and by model in its hours (the window's model family only, boundary hours as in D7); and + their API value ([D13](#d13--api-value-at-list-prices)). +- **Unused.** A finished instance leaves `100 − final use` percent of its limit unused. +- **Gift.** An early reset hands out a fresh limit ahead of schedule: its gift is + `100 · skipped / W` percent of a limit. Over many windows, that is how many extra limits the + provider gave. +- **Value of a percent.** Unused and gift percent become tokens and money at the instance's own + tokens and API value per percent point when its final use is at least 5 %; otherwise at the + median of the series' instances that qualify. Without one, only the percent is shown. +- **Totals** over the listed instances: their number, early resets, tokens, API value, unused + and gift (in limits and value), and how often and how long 100 % was reached. +- **Timeline.** Each series shows its instances on one time axis without joining their lines, + marks each reset and the skipped time of early resets, and counts its early resets by local + hour and weekday. + +**Why.** R4. The developer asked for figures per reset, including wastage, API value and what +early resets give (developer feedback, 2026-10-18). Codex resets early often: 11 of its 12 week +instances from 2026-09-21 to 2026-10-17 ended early, some after 10 hours. + +**Gives up.** Resets FinalToken never saw: before its first sample, and instances without any +sample. Token figures at a boundary are only as fine as an hour. The gift assumes the provider +would have kept its schedule. Unused and gift values assume the instance's model mix. A drop in +use without a new reset is not a reset. + +## D13 — API value at list prices + +**Decision.** FinalToken estimates what tokens would cost at the providers' public API list +prices. A table compiled into Core gives, per model, US dollars per million tokens for input, +output, cache write and cache read (Claude) or input, cached input and output (Codex), with the +day it was checked and its source pages. A model id matches its entry exactly or with a +trailing date suffix (`claude-haiku-4-5-20251001`). A model without an entry has no value; its +tokens are counted and shown as unpriced. Claude cache writes use the 5-minute price. Reasoning +is part of output and Codex cached input part of input, as in [D7](#d7--pace). Values are +shown with "≈" as "at API list prices". + +**Why.** The developer asked what each window would cost at API prices (developer feedback, +2026-10-18). [D2](#d2--the-clis-are-the-only-interface-to-a-provider) rules out asking a +provider; a dated table can be checked by hand and is updated with a release. + +**Gives up.** Price changes after the check until a release updates the table. Long-context +prices (OpenAI above 272K input tokens, Claude Haiku 5.5 above 100K), because hourly buckets do +not keep request sizes. The 1-hour cache write price, fast and batch prices, and models not in +the table. -- 2.54.0 From f9027e8a27aab8739e458bda4d6fc5b2c725e613 Mon Sep 17 00:00:00 2001 From: Florian Schmidt Date: Sun, 18 Oct 2026 09:37:35 +0200 Subject: [PATCH 03/14] docs: say which samples D7 ignores as stale Refs #14 --- docs/decisions.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index 6660872..aca6951 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -182,8 +182,8 @@ probe. instance's start, whichever comes first (Codex can start a new window early). Tokens are hourly (D5): an hour that holds a boundary goes to the instance that starts in it, or, when none does, to the instance that ends in it. Other spans between instances (a session window - opens only with the next message) belong to none. A sample whose reset contradicts a later - instance's start is stale and is ignored. A past instance + opens only with the next message) belong to none. A sample that would place its instance + after an instance sampled later is stale and is ignored. A past instance with samples is always the real one; an instance is only inferred where no samples exist, by stepping back one window length, and never overlaps a real one. Windows of a day or shorter are never inferred, since a session starts with whatever message comes next. Past instances are -- 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 04/14] 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 05/14] 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 1c3f857a2c03e35720bd19acfe1b36f84dbca6c2 Mon Sep 17 00:00:00 2001 From: Florian Schmidt Date: Sun, 18 Oct 2026 10:07:40 +0200 Subject: [PATCH 06/14] core: add the reset history, API list prices and window series The developer wants figures for every reset: how long an instance lasted, its tokens, its final use, its API value, what it left unused and what an early reset handed out (D12, D13). Instances come from one window series, so a Codex limit that moves between the primary and secondary slot stays one history (D7). Building the spans once also fixes two D7 cases: the hour in which one instance ends and the next starts goes to the new instance instead of being lost, and a late sample of an old instance no longer places it after a newer one. Refs #14 Refs #9 --- src/FinalToken.Core/AGENTS.md | 15 +- src/FinalToken.Core/ApiPrices.cs | 65 +++++++ src/FinalToken.Core/HistoryStore.cs | 8 + src/FinalToken.Core/LimitAnalysis.cs | 2 +- src/FinalToken.Core/LimitEstimates.cs | 164 ++++++++-------- src/FinalToken.Core/LimitSpans.cs | 58 ++++++ src/FinalToken.Core/ResetHistory.cs | 109 +++++++++++ src/FinalToken.Core/WindowSeries.cs | 15 ++ .../ResetBoundaryTests.cs | 32 ++++ .../ResetHistoryTests.cs | 176 ++++++++++++++++++ 10 files changed, 554 insertions(+), 90 deletions(-) create mode 100644 src/FinalToken.Core/ApiPrices.cs create mode 100644 src/FinalToken.Core/LimitSpans.cs create mode 100644 src/FinalToken.Core/ResetHistory.cs create mode 100644 src/FinalToken.Core/WindowSeries.cs create mode 100644 tests/FinalToken.Core.Tests/ResetBoundaryTests.cs create mode 100644 tests/FinalToken.Core.Tests/ResetHistoryTests.cs diff --git a/src/FinalToken.Core/AGENTS.md b/src/FinalToken.Core/AGENTS.md index 4c23995..be6b081 100644 --- a/src/FinalToken.Core/AGENTS.md +++ b/src/FinalToken.Core/AGENTS.md @@ -1,5 +1,5 @@ # Core -UI-free domain and file/CLI integration. Implements D1–D7, D9 and the D11 installer contract. +UI-free domain and file/CLI integration. Implements D1–D7, D9 and D11–D13. Keep parsers total. Only metadata leaves them. JSON uses CoreJsonContext. Hosts own StoreLock. Persisted defaults use settable properties: source-generated init-only property factories can overwrite initializers for missing JSON members. Treat settings as values; update them with `with`. @@ -28,6 +28,19 @@ Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root No shipped production dependency is needed in Core. Source parsers use temporary memory for one complete line; memory usage therefore scales with the largest transcript entry. +## Limit analysis + +- Use `WindowSeries` (provider, name, length) for all sample queries and instance membership (D7). + Codex `:primary` and `:secondary` suffixes identify slots, not limits. Read across ids with + `HistoryStore.LimitSamples(window, from, to)`; the original id query remains available. +- `LimitAnalysis` shares real spans and burn-up construction between `Analyze` and `Resets`. + Keep the current instance, ignore stale samples and leave gaps unassigned. A boundary hour + belongs to its starting instance, else to its ending instance (D7). +- Reset history lists only real instances overlapping the range, with whole-instance values (D12). + Percent values use the instance at final ≥ 5 %, else the qualifying listed-instance median. +- `ApiPrices` is the dated D13 list-price table. Match exact ids or a valid trailing date. + Unknown models remain unpriced; never infer a price from a family or count token subsets twice. + ## Store persistence and scaling - Refresh changes append as one durable, newline-terminated transaction to diff --git a/src/FinalToken.Core/ApiPrices.cs b/src/FinalToken.Core/ApiPrices.cs new file mode 100644 index 0000000..1f0ff45 --- /dev/null +++ b/src/FinalToken.Core/ApiPrices.cs @@ -0,0 +1,65 @@ +using System.Globalization; + +namespace FinalToken.Core; + +public sealed record ApiPrice(decimal Input, decimal CacheWrite, decimal CacheRead, decimal Output); + +/// D13: USD per million tokens, checked 2026-10-18. Standard short-context prices. +/// https://platform.claude.com/docs/en/about-claude/pricing +/// https://developers.openai.com/api/docs/pricing +/// Claude writes use the 5-minute price; Haiku 5.5 assumes prompts up to 100K. +public static class ApiPrices +{ + public static DateOnly CheckedOn => new(2026, 10, 18); + private static readonly Dictionary Claude = new(StringComparer.Ordinal) + { + ["claude-fable-5-1"] = new(10, 12.50m, .25m, 50), + ["claude-fable-5"] = new(10, 12.50m, 1, 50), + ["claude-opus-5-5"] = new(4, 5, .20m, 20), + ["claude-opus-5"] = new(5, 6.25m, .50m, 25), + ["claude-opus-4-8"] = new(5, 6.25m, .50m, 25), + ["claude-opus-4-7"] = new(5, 6.25m, .50m, 25), + ["claude-opus-4-6"] = new(5, 6.25m, .50m, 25), + ["claude-opus-4-5"] = new(5, 6.25m, .50m, 25), + ["claude-sonnet-5-5"] = new(2, 2.50m, .10m, 10), + ["claude-sonnet-5"] = new(2, 2.50m, .20m, 10), + ["claude-sonnet-4-6"] = new(3, 3.75m, .30m, 15), + ["claude-sonnet-4-5"] = new(3, 3.75m, .30m, 15), + ["claude-haiku-5-5"] = new(.10m, .125m, .01m, .50m), + ["claude-haiku-4-5"] = new(1, 1.25m, .10m, 5) + }; + private static readonly Dictionary Codex = new(StringComparer.Ordinal) + { + ["gpt-6-astra"] = new(10, 0, 1, 50), + ["gpt-6.1-sol"] = new(2, 0, .10m, 10), + ["gpt-6-sol"] = new(2, 0, .20m, 10), + ["gpt-6-luna"] = new(.10m, 0, .01m, .50m), + ["gpt-5.6-sol"] = new(4, 0, .40m, 20), + ["gpt-5.6-terra"] = new(2, 0, .20m, 12), + ["gpt-5.6-luna"] = new(.20m, 0, .02m, 1.20m), + ["gpt-5.5"] = new(5, 0, .50m, 30), + ["gpt-5.4"] = new(2.50m, 0, .25m, 15), + ["gpt-5.4-mini"] = new(.75m, 0, .075m, 4.50m), + ["gpt-5.3-codex"] = new(1.75m, 0, .175m, 14), + ["gpt-5.2"] = new(1.75m, 0, .175m, 14), + ["gpt-5.1"] = new(1.25m, 0, .125m, 10), + ["gpt-5"] = new(1.25m, 0, .125m, 10) + }; + public static ApiPrice? Find(Provider provider, string? model) + { + if (model is null) return null; + var prices = provider == Provider.Claude ? Claude : Codex; + if (prices.TryGetValue(model, out var price)) return price; + return model.Length > 9 && model[^9] == '-' && + DateOnly.TryParseExact(model[^8..], "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out _) && + prices.TryGetValue(model[..^9], out price) ? price : null; + } + public static decimal? Value(Provider provider, string? model, TokenCounts counts) + { + if (Find(provider, model) is not { } p) return null; + var input = provider == Provider.Claude ? Math.Max(0, counts.Input) : Math.Max(0, counts.Input - counts.CacheRead); + return (input * p.Input + Math.Max(0, counts.CacheRead) * p.CacheRead + + (provider == Provider.Claude ? Math.Max(0, counts.CacheWrite) * p.CacheWrite : 0) + + Math.Max(0, counts.Output) * p.Output) / 1_000_000; + } +} diff --git a/src/FinalToken.Core/HistoryStore.cs b/src/FinalToken.Core/HistoryStore.cs index 991a85b..9376244 100644 --- a/src/FinalToken.Core/HistoryStore.cs +++ b/src/FinalToken.Core/HistoryStore.cs @@ -212,6 +212,14 @@ public sealed class HistoryStore .Where(w => w.Provider == provider && w.Id == windowId && w.SampleTime >= from && w.SampleTime < to) .OrderBy(w => w.SampleTime).ToArray(); } + public IReadOnlyList LimitSamples(Provider provider, DateTimeOffset from, DateTimeOffset to) + { + lock (gate) return SelectMonths(from, to).SelectMany(m => GetPartition(m).Limits) + .Where(w => w.Provider == provider && w.SampleTime >= from && w.SampleTime < to) + .OrderBy(w => w.SampleTime).ToArray(); + } + public IReadOnlyList LimitSamples(LimitWindow window, DateTimeOffset from, DateTimeOffset to) => + LimitSamples(window.Provider, from, to).Where(WindowSeries.For(window).Matches).ToArray(); public IReadOnlyList TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval) => TokenSeries(provider, from, to, interval, TimeZoneInfo.Local); public IReadOnlyList TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval, diff --git a/src/FinalToken.Core/LimitAnalysis.cs b/src/FinalToken.Core/LimitAnalysis.cs index d4cd7f8..4a8c776 100644 --- a/src/FinalToken.Core/LimitAnalysis.cs +++ b/src/FinalToken.Core/LimitAnalysis.cs @@ -12,7 +12,7 @@ public static partial class LimitAnalysis { /// D7: minute-rounded probe resets may drift within 15 minutes in either direction. public static bool SameInstance(LimitWindow first, LimitWindow second) => - first.Provider == second.Provider && first.Id == second.Id && + WindowSeries.For(first) == WindowSeries.For(second) && first.ResetsAt is { } firstReset && second.ResetsAt is { } secondReset && (firstReset - secondReset).Duration() <= TimeSpan.FromMinutes(15); diff --git a/src/FinalToken.Core/LimitEstimates.cs b/src/FinalToken.Core/LimitEstimates.cs index 7fc0e0d..d64e0b5 100644 --- a/src/FinalToken.Core/LimitEstimates.cs +++ b/src/FinalToken.Core/LimitEstimates.cs @@ -24,26 +24,12 @@ public static partial class LimitAnalysis { if (window.ResetsAt is not { } reset || window.Length is not { Ticks: > 0 } length || Pace.Calculate(window, now).State == PaceState.Unknown) return null; zone ??= TimeZoneInfo.Local; - var observations = samples.Append(window).Where(s => s.Provider == window.Provider && s.Id == window.Id && - s.ResetsAt is not null && s.Length is { Ticks: > 0 } && s.SampleTime <= now && double.IsFinite(s.UsedPercent) && s.UsedPercent is >= 0 and <= 100).OrderBy(s => s.SampleTime).ToArray(); - var weighted = tokens.Where(p => TokenWeights.Matches(window, p.Model)).GroupBy(p => p.Time) - .Select(g => (Time: g.Key, Weight: g.Sum(p => TokenWeights.Weighted(window.Provider, p.Counts)))).OrderBy(p => p.Time).ToArray(); - // D7: samples identify real instances; resets and lengths define their boundaries. - var groups = new List> { new() { window } }; - foreach (var observation in observations) - { - var group = groups.FirstOrDefault(g => SameInstance(g[0], observation)); - if (group is null) groups.Add([observation]); else group.Add(observation); - } - var spans = groups.Select(g => - { - var anchor = SameInstance(g[0], window) ? window : g[^1]; - return (Anchor: anchor, Start: anchor.ResetsAt!.Value - anchor.Length!.Value, End: anchor.ResetsAt.Value); - }).OrderBy(g => g.Start).ToArray(); - for (var i = 0; i + 1 < spans.Length; i++) - if (spans[i + 1].Start < spans[i].End) spans[i].End = spans[i + 1].Start; + var spans = RealSpans(window, samples, now); + var observations = spans.SelectMany(s => s.Samples).ToArray(); + var weighted = WeightedTokens(window, tokens); var currentSpan = spans.Single(g => SameInstance(g.Anchor, window)); - var current = Build(window, currentSpan.Start, currentSpan.End, now < currentSpan.End ? now : currentSpan.End, null); + var current = BuildInstance(window, observations, weighted, currentSpan.Start, currentSpan.End, + now < currentSpan.End ? now : currentSpan.End, null, TokenEnd(currentSpan.End, spans), now, zone); var realPast = spans.Where(g => g.Start < currentSpan.Start).OrderByDescending(g => g.Start).ToArray(); var past = new List(); var realIndex = 0; @@ -57,8 +43,9 @@ public static partial class LimitAnalysis // A shorter gap stays unassigned. Sessions never produce inferred candidates. var span = realIndex < realPast.Length && (!canInfer || realPast[realIndex].End > inferredStart) ? realPast[realIndex++] - : (Anchor: window with { ResetsAt = cursor }, Start: inferredStart, End: cursor); - var instance = Build(span.Anchor, span.Start, span.End, span.End < now ? span.End : now, current.Scale); + : new InstanceSpan(window with { ResetsAt = cursor }, [], inferredStart, cursor); + var instance = BuildInstance(span.Anchor, observations, weighted, span.Start, span.End, + span.End < now ? span.End : now, current.Scale, TokenEnd(span.End, spans), now, zone); if (instance.HasData) past.Add(instance); cursor = span.Start; } @@ -70,75 +57,76 @@ public static partial class LimitAnalysis reset > now ? (100 - window.UsedPercent) / (reset - now).TotalDays : null, today?.Origin ?? UseOrigin.Measured); } return new(current, past, days); + } - LimitInstance Build(LimitWindow anchor, DateTimeOffset start, DateTimeOffset end, DateTimeOffset until, - double? fallback) + private static LimitInstance BuildInstance(LimitWindow anchor, IReadOnlyList observations, + (DateTimeOffset Time, double Weight)[] weighted, DateTimeOffset start, DateTimeOffset end, DateTimeOffset until, + double? fallback, DateTimeOffset tokenEnd, DateTimeOffset now, TimeZoneInfo zone) + { + double Weight(DateTimeOffset from, DateTimeOffset to) { - 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); - } - 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(); - var last = measured.LastOrDefault(); - var denominator = last is null ? 0 : Weight(start, last.SampleTime); - var total = Weight(start, until); - double? scale = total <= 0 ? null : last is not null ? denominator > 0 ? last.UsedPercent / denominator : null : fallback; - var points = new SortedDictionary { [start] = new(start, 0, UseOrigin.Measured) }; - if (scale is { } k) - { - foreach (var time in weighted.Where(p => p.Time >= Hour(start) && p.Time < until && p.Time < Hour(end)).SelectMany(p => new[] { p.Time, p.Time.AddHours(1) }).Append(until).Distinct()) - { - var cutoff = time < until ? time : until; - if (cutoff <= start) continue; - // Samples own the measured span; tokens fill before the first sample and after the last. - if (measured.Length == 0 || cutoff < measured[0].SampleTime) - points[cutoff] = new(cutoff, k * Weight(start, cutoff), UseOrigin.Estimated); - else if (last is not null && cutoff > last.SampleTime) - points[cutoff] = new(cutoff, last.UsedPercent + k * (Weight(start, cutoff) - Weight(start, last.SampleTime)), UseOrigin.Estimated); - } - } - foreach (var sample in measured) points[sample.SampleTime] = new(sample.SampleTime, sample.UsedPercent, UseOrigin.Measured); - DateTimeOffset? reached = null; UseOrigin? reachedOrigin = null; - var raw = points.Values.OrderBy(p => p.Time).ToArray(); - for (var i = 1; i < raw.Length; i++) - { - var point = raw[i]; var prior = raw[i - 1]; - if (reached is null && point.Used >= 100) - { - reached = point.Origin == UseOrigin.Measured || point.Used <= prior.Used ? point.Time - : prior.Time.AddTicks((long)((point.Time - prior.Time).Ticks * Math.Clamp((100 - prior.Used) / (point.Used - prior.Used), 0, 1))); - reachedOrigin = point.Origin; - if (point.Origin == UseOrigin.Estimated) points[reached.Value] = new(reached.Value, 100, UseOrigin.Estimated); - } - if (point.Origin == UseOrigin.Estimated) - points[point.Time] = point with { Used = reached is not null ? 100 : Math.Min(100, point.Used) }; - } - double EstimatedAt(DateTimeOffset time, double factor) => reachedOrigin == UseOrigin.Estimated && time >= reached - ? 100 : Math.Min(100, factor * Weight(start, time)); - var daily = new List(); - for (var day = CalendarDays.Start(start, zone); day < end; day = CalendarDays.NextStart(day, zone)) - { - var next = CalendarDays.NextStart(day, zone); var dayEnd = next < end ? next : end; - var cutoff = dayEnd < until ? dayEnd : until; var future = day > until; - var baseline = day <= start ? 0 : Last(day); - var cumulative = cutoff >= start ? Last(cutoff) : null; - if (last is not null && scale is not null && cutoff > last.SampleTime && Weight(start, cutoff) > Weight(start, last.SampleTime)) cumulative = null; - double? use = !future && baseline is { } b && cumulative is { } c ? Math.Max(0, c - b) : null; - var origin = UseOrigin.Measured; - if (!future && use is null && scale is { } factor) - { - use = Math.Max(0, EstimatedAt(cutoff, factor) - (day > start ? EstimatedAt(day, factor) : 0)); origin = UseOrigin.Estimated; - cumulative ??= EstimatedAt(cutoff, factor); - } - daily.Add(new(day, dayEnd, use, future ? null : cumulative, day == CalendarDays.Start(now, zone), future, origin)); - } - var series = points.Values.OrderBy(p => p.Time).ToArray(); - double? peak = series.Length > 1 ? series.Max(p => p.Used) : null; - return new(start, anchor.ResetsAt!.Value, series, daily, scale, peak, reached, end, reachedOrigin); - double? Last(DateTimeOffset time) => measured.LastOrDefault(s => s.SampleTime <= time)?.UsedPercent; + var hour = Hour(from < start ? start : from); + var exclusiveEnd = tokenEnd; + return weighted.Where(p => p.Time >= hour && p.Time < to && p.Time < exclusiveEnd).Sum(p => p.Weight); } + 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(); + var last = measured.LastOrDefault(); + var denominator = last is null ? 0 : Weight(start, last.SampleTime); + var total = Weight(start, until); + double? scale = total <= 0 ? null : last is not null ? denominator > 0 ? last.UsedPercent / denominator : null : fallback; + var points = new SortedDictionary { [start] = new(start, 0, UseOrigin.Measured) }; + if (scale is { } k) + { + foreach (var time in weighted.Where(p => p.Time >= Hour(start) && p.Time < until && p.Time < tokenEnd).SelectMany(p => new[] { p.Time, p.Time.AddHours(1) }).Append(until).Distinct()) + { + var cutoff = time < until ? time : until; + if (cutoff <= start) continue; + // Samples own the measured span; tokens fill before the first sample and after the last. + if (measured.Length == 0 || cutoff < measured[0].SampleTime) + points[cutoff] = new(cutoff, k * Weight(start, cutoff), UseOrigin.Estimated); + else if (last is not null && cutoff > last.SampleTime) + points[cutoff] = new(cutoff, last.UsedPercent + k * (Weight(start, cutoff) - Weight(start, last.SampleTime)), UseOrigin.Estimated); + } + } + foreach (var sample in measured) points[sample.SampleTime] = new(sample.SampleTime, sample.UsedPercent, UseOrigin.Measured); + DateTimeOffset? reached = null; UseOrigin? reachedOrigin = null; + var raw = points.Values.OrderBy(p => p.Time).ToArray(); + for (var i = 1; i < raw.Length; i++) + { + var point = raw[i]; var prior = raw[i - 1]; + if (reached is null && point.Used >= 100) + { + reached = point.Origin == UseOrigin.Measured || point.Used <= prior.Used ? point.Time + : prior.Time.AddTicks((long)((point.Time - prior.Time).Ticks * Math.Clamp((100 - prior.Used) / (point.Used - prior.Used), 0, 1))); + reachedOrigin = point.Origin; + if (point.Origin == UseOrigin.Estimated) points[reached.Value] = new(reached.Value, 100, UseOrigin.Estimated); + } + if (point.Origin == UseOrigin.Estimated) + points[point.Time] = point with { Used = reached is not null ? 100 : Math.Min(100, point.Used) }; + } + double EstimatedAt(DateTimeOffset time, double factor) => reachedOrigin == UseOrigin.Estimated && time >= reached + ? 100 : Math.Min(100, factor * Weight(start, time)); + var daily = new List(); + for (var day = CalendarDays.Start(start, zone); day < end; day = CalendarDays.NextStart(day, zone)) + { + var next = CalendarDays.NextStart(day, zone); var dayEnd = next < end ? next : end; + var cutoff = dayEnd < until ? dayEnd : until; var future = day > until; + var baseline = day <= start ? 0 : Last(day); + var cumulative = cutoff >= start ? Last(cutoff) : null; + if (last is not null && scale is not null && cutoff > last.SampleTime && Weight(start, cutoff) > Weight(start, last.SampleTime)) cumulative = null; + double? use = !future && baseline is { } b && cumulative is { } c ? Math.Max(0, c - b) : null; + var origin = UseOrigin.Measured; + if (!future && use is null && scale is { } factor) + { + use = Math.Max(0, EstimatedAt(cutoff, factor) - (day > start ? EstimatedAt(day, factor) : 0)); origin = UseOrigin.Estimated; + cumulative ??= EstimatedAt(cutoff, factor); + } + daily.Add(new(day, dayEnd, use, future ? null : cumulative, day == CalendarDays.Start(now, zone), future, origin)); + } + var series = points.Values.OrderBy(p => p.Time).ToArray(); + double? peak = series.Length > 1 ? series.Max(p => p.Used) : null; + return new(start, anchor.ResetsAt!.Value, series, daily, scale, peak, reached, end, reachedOrigin); + double? Last(DateTimeOffset time) => measured.LastOrDefault(s => s.SampleTime <= time)?.UsedPercent; } } diff --git a/src/FinalToken.Core/LimitSpans.cs b/src/FinalToken.Core/LimitSpans.cs new file mode 100644 index 0000000..3c29c56 --- /dev/null +++ b/src/FinalToken.Core/LimitSpans.cs @@ -0,0 +1,58 @@ +namespace FinalToken.Core; + +public static partial class LimitAnalysis +{ + private sealed record InstanceSpan(LimitWindow Anchor, IReadOnlyList Samples, + DateTimeOffset Start, DateTimeOffset End); + + private static InstanceSpan[] RealSpans(LimitWindow window, IEnumerable samples, DateTimeOffset now) + { + var key = WindowSeries.For(window); + var observations = samples.Append(window).Where(s => key.Matches(s) && s.ResetsAt is not null && + s.Length is { Ticks: > 0 } && s.SampleTime <= now && double.IsFinite(s.UsedPercent) && + s.UsedPercent is >= 0 and <= 100).Distinct().OrderByDescending(s => s.SampleTime).ToArray(); + var groups = new List> { new() { window } }; + foreach (var sample in observations) + { + var group = groups.FirstOrDefault(g => SameInstance(g[0], sample)); + if (group is null) groups.Add([sample]); else group.Add(sample); + } + var candidates = groups.Select(g => + { + var anchor = SameInstance(g[0], window) ? window : g.MaxBy(s => s.SampleTime)!; + return new InstanceSpan(anchor, g.Distinct().OrderBy(s => s.SampleTime).ToArray(), + anchor.ResetsAt!.Value - anchor.Length!.Value, anchor.ResetsAt.Value); + }).ToArray(); + var current = candidates[0]; + var accepted = new List { current }; + var latestStart = current.Start; + // D7 / #9: earlier observations cannot put an instance after a later observed instance. + // Order by first observation so an interleaved late rollout cannot reorder real resets. + foreach (var span in candidates.Skip(1).OrderByDescending(s => s.Samples.Min(p => p.SampleTime))) + { + if (span.Start > latestStart) continue; + accepted.Add(span); latestStart = span.Start; + } + var result = accepted.OrderBy(s => s.Start).ToArray(); + for (var i = 0; i + 1 < result.Length; i++) + if (result[i + 1].Start < result[i].End) result[i] = result[i] with { End = result[i + 1].Start }; + // A late sample of the old instance after an early reset is stale too. + result = result.Select(s => + { + var valid = s.Samples.Where(p => p.SampleTime <= s.End).ToArray(); + var anchor = SameInstance(s.Anchor, window) ? window : valid.LastOrDefault() ?? s.Anchor; + return new InstanceSpan(anchor, valid, anchor.ResetsAt!.Value - anchor.Length!.Value, anchor.ResetsAt.Value); + }).Where(s => s.Samples.Count > 0 || SameInstance(s.Anchor, window)).OrderBy(s => s.Start).ToArray(); + for (var i = 0; i + 1 < result.Length; i++) + if (result[i + 1].Start < result[i].End) result[i] = result[i] with { End = result[i + 1].Start }; + return result.Select(s => s with { Samples = s.Samples.Where(p => p.SampleTime <= s.End).ToArray() }).ToArray(); + } + + private static DateTimeOffset TokenEnd(DateTimeOffset end, IReadOnlyList spans) => + end == Hour(end) || spans.Any(s => s.Start >= end && Hour(s.Start) == Hour(end)) ? Hour(end) : Hour(end).AddHours(1); + + private static (DateTimeOffset Time, double Weight)[] WeightedTokens(LimitWindow window, IReadOnlyList tokens) => + tokens.Where(p => TokenWeights.Matches(window, p.Model)).GroupBy(p => p.Time) + .Select(g => (Time: g.Key, Weight: g.Sum(p => TokenWeights.Weighted(window.Provider, p.Counts)))) + .OrderBy(p => p.Time).ToArray(); +} diff --git a/src/FinalToken.Core/ResetHistory.cs b/src/FinalToken.Core/ResetHistory.cs new file mode 100644 index 0000000..c36996b --- /dev/null +++ b/src/FinalToken.Core/ResetHistory.cs @@ -0,0 +1,109 @@ +namespace FinalToken.Core; + +public enum PercentBasis { OwnInstance, SeriesMedian } +public sealed record PercentRate(double Tokens, decimal? ApiValue, PercentBasis Basis); +public sealed record ResetValue(double Percent, double? Tokens, decimal? ApiValue); +public sealed record ResetModel(string? Model, TokenCounts Tokens, decimal? ApiValue); +public sealed record ResetInstance(LimitInstance BurnUp, DateTimeOffset End, bool Running, bool Early, + TimeSpan Skipped, TokenCounts Tokens, IReadOnlyList Models, decimal? ApiValue, long UnpricedTokens, + PercentRate? ValuePerPercent = null, ResetValue? Unused = null, ResetValue? Gift = null) +{ + public DateTimeOffset Start => BurnUp.Start; + public DateTimeOffset Reset => BurnUp.Reset; + public TimeSpan Duration => End - Start; + public LimitPoint Final => BurnUp.Points[^1]; + public double? Peak => BurnUp.Peak; + public UseOrigin PeakOrigin => BurnUp.Points.Any(p => p.Used == Peak && p.Origin == UseOrigin.Measured) + ? UseOrigin.Measured : UseOrigin.Estimated; + public DateTimeOffset? ReachedLimit => BurnUp.ReachedLimit; + public TimeSpan TimeAtLimit => ReachedLimit is { } time && End > time ? End - time : TimeSpan.Zero; +} +public sealed record ResetTotals(int Instances, int Finished, int Early, TokenCounts Tokens, decimal? ApiValue, + long UnpricedTokens, ResetValue Unused, ResetValue Gift, TimeSpan Skipped, int ReachedLimit, TimeSpan TimeAtLimit); +public sealed record ResetHistory(LimitWindow Window, IReadOnlyList Instances, ResetTotals Totals, + IReadOnlyList EarlyByHour, IReadOnlyList EarlyByWeekday, TimeSpan? MedianDuration, DateTimeOffset FirstSample); + +public static partial class LimitAnalysis +{ + /// D12: only observed real instances; values cover whole overlapping instances, not a clipped range. + public static ResetHistory Resets(LimitWindow window, IEnumerable samples, + IReadOnlyList tokens, DateTimeOffset from, DateTimeOffset now, TimeZoneInfo? zone = null) + { + zone ??= TimeZoneInfo.Local; + var rows = new List(); + var hours = new int[24]; var weekdays = new int[7]; + var firstSample = window.SampleTime; + if (window.ResetsAt is not null && window.Length is { } length && length > TimeSpan.FromDays(1) && + Pace.Calculate(window, now).State != PaceState.Unknown) + { + var spans = RealSpans(window, samples, now); + firstSample = spans.SelectMany(s => s.Samples).Select(s => s.SampleTime).DefaultIfEmpty(window.SampleTime).Min(); + var weighted = WeightedTokens(window, tokens); + foreach (var span in spans.Where(s => s.Samples.Count > 0 && s.End > from && s.Start <= now).Reverse()) + { + var running = span.End > now; + var end = running ? now : span.End; + var burn = BuildInstance(span.Anchor, span.Samples, weighted, span.Start, span.End, end, + null, TokenEnd(span.End, spans), now, zone); + var models = tokens.Where(p => p.Time >= Hour(span.Start) && p.Time < end && + p.Time < TokenEnd(span.End, spans) && TokenWeights.Matches(window, p.Model)) + .GroupBy(p => p.Model).Select(g => + { + var counts = g.Aggregate(new TokenCounts(), (sum, p) => sum + p.Counts); + return new ResetModel(g.Key, counts, ApiPrices.Value(window.Provider, g.Key, counts)); + }).OrderByDescending(m => m.Tokens.Total).ToArray(); + var early = !running && span.Anchor.ResetsAt!.Value - end > TimeSpan.FromMinutes(15); + rows.Add(new(burn, end, running, early, early ? span.Anchor.ResetsAt!.Value - end : TimeSpan.Zero, + models.Aggregate(new TokenCounts(), (sum, m) => sum + m.Tokens), models, + SumMoney(models.Select(m => m.ApiValue)), models.Where(m => m.ApiValue is null).Sum(m => m.Tokens.Total))); + if (early) + { + var local = TimeZoneInfo.ConvertTime(end, zone); + hours[local.Hour]++; weekdays[((int)local.DayOfWeek + 6) % 7]++; + } + } + var qualifying = rows.Where(r => r.Final.Used >= 5).ToArray(); + var medianTokens = Median(qualifying.Select(r => r.Tokens.Total / r.Final.Used)); + var medianMoney = MedianMoney(qualifying.Where(r => r.ApiValue is not null).Select(r => r.ApiValue!.Value / (decimal)r.Final.Used)); + for (var i = 0; i < rows.Count; i++) + { + var row = rows[i]; + var rate = row.Final.Used >= 5 ? new PercentRate(row.Tokens.Total / row.Final.Used, + row.ApiValue / (decimal)row.Final.Used, PercentBasis.OwnInstance) : medianTokens is { } median + ? new PercentRate(median, medianMoney, PercentBasis.SeriesMedian) : null; + ResetValue Value(double percent) => new(percent, rate?.Tokens * percent, rate?.ApiValue * (decimal)percent); + rows[i] = row with { ValuePerPercent = rate, Unused = row.Running ? null : Value(100 - row.Final.Used), + Gift = row.Early ? Value(100 * row.Skipped.TotalSeconds / length.TotalSeconds) : null }; + } + } + ResetValue TotalValue(IEnumerable source) + { + var values = source.OfType().ToArray(); + return new(values.Sum(v => v.Percent), values.All(v => v.Tokens is not null) ? values.Sum(v => v.Tokens) : null, + values.All(v => v.ApiValue is not null) ? values.Sum(v => v.ApiValue) : null); + } + var totals = new ResetTotals(rows.Count, rows.Count(r => !r.Running), rows.Count(r => r.Early), + rows.Aggregate(new TokenCounts(), (sum, r) => sum + r.Tokens), SumMoney(rows.Select(r => r.ApiValue)), + rows.Sum(r => r.UnpricedTokens), TotalValue(rows.Select(r => r.Unused)), TotalValue(rows.Select(r => r.Gift)), + TimeSpan.FromTicks(rows.Sum(r => r.Skipped.Ticks)), rows.Count(r => r.ReachedLimit is not null), + TimeSpan.FromTicks(rows.Sum(r => r.TimeAtLimit.Ticks))); + return new(window, rows, totals, hours, weekdays, + Median(rows.Select(r => (double)r.Duration.Ticks)) is { } ticks ? TimeSpan.FromTicks((long)ticks) : null, firstSample); + } + + private static decimal? SumMoney(IEnumerable values) + { + var known = values.OfType().ToArray(); + return known.Length == 0 ? null : known.Sum(); + } + private static double? Median(IEnumerable source) + { + var sorted = source.Order().ToArray(); var n = sorted.Length; + return n == 0 ? null : (sorted[(n - 1) / 2] + sorted[n / 2]) / 2; + } + private static decimal? MedianMoney(IEnumerable source) + { + var sorted = source.Order().ToArray(); var n = sorted.Length; + return n == 0 ? null : (sorted[(n - 1) / 2] + sorted[n / 2]) / 2; + } +} diff --git a/src/FinalToken.Core/WindowSeries.cs b/src/FinalToken.Core/WindowSeries.cs new file mode 100644 index 0000000..daa85d7 --- /dev/null +++ b/src/FinalToken.Core/WindowSeries.cs @@ -0,0 +1,15 @@ +namespace FinalToken.Core; + +/// D7: Codex slots can change; a limit's name and length identify its series. +public readonly record struct WindowSeries(Provider Provider, string Name, TimeSpan? Length) +{ + public static WindowSeries For(LimitWindow window) + { + var name = window.Id; + if (window.Provider == Provider.Codex) + foreach (var suffix in new[] { ":primary", ":secondary" }) + if (name.EndsWith(suffix, StringComparison.Ordinal)) { name = name[..^suffix.Length]; break; } + return new(window.Provider, name, window.Length); + } + public bool Matches(LimitWindow window) => this == For(window); +} diff --git a/tests/FinalToken.Core.Tests/ResetBoundaryTests.cs b/tests/FinalToken.Core.Tests/ResetBoundaryTests.cs new file mode 100644 index 0000000..e12d501 --- /dev/null +++ b/tests/FinalToken.Core.Tests/ResetBoundaryTests.cs @@ -0,0 +1,32 @@ +using Xunit; + +namespace FinalToken.Core.Tests; + +public sealed class ResetBoundaryTests +{ + private static readonly DateTimeOffset Day = new(2026, 10, 15, 0, 0, 0, TimeSpan.Zero); + private static LimitWindow Window(DateTimeOffset start, DateTimeOffset sample, double used) => + new(Provider.Codex, "codex:primary", "Session", used, start.AddHours(5), TimeSpan.FromHours(5), sample, "fixture"); + + [Fact] public void ResetHourBeforeAGapBelongsToTheEndingInstance() + { + var previous = Window(Day.AddHours(10).AddMinutes(13), Day.AddHours(14), 50); + var current = Window(Day.AddHours(20), Day.AddHours(21), 10); + ModelTokenPoint[] tokens = [new(Day.AddHours(10), "model", new(Input: 100, Total: 100)), + new(Day.AddHours(15), "model", new(Input: 50, Total: 50))]; + var past = Assert.Single(LimitAnalysis.Analyze(current, [previous], tokens, current.SampleTime, TimeZoneInfo.Utc)!.Past); + Assert.Equal(75, past.Points.Last().Used); + Assert.Equal(UseOrigin.Estimated, past.Points.Last().Origin); + Assert.Equal(previous.ResetsAt, past.Points.Last().Time); + } + + [Fact] public void EarlierSampleCannotPutAnInstanceAfterTheCurrentWindow() + { + var current = Window(Day.AddHours(10), Day.AddHours(12), 10); + var stale = Window(Day.AddHours(11), Day.AddHours(11.5), 90); + var result = LimitAnalysis.Analyze(current, [stale], [], current.SampleTime, TimeZoneInfo.Utc)!; + Assert.Equal(current.ResetsAt, result.Current.End); + Assert.Equal(10, result.Current.Peak); + Assert.Empty(result.Past); + } +} diff --git a/tests/FinalToken.Core.Tests/ResetHistoryTests.cs b/tests/FinalToken.Core.Tests/ResetHistoryTests.cs new file mode 100644 index 0000000..0fe43e7 --- /dev/null +++ b/tests/FinalToken.Core.Tests/ResetHistoryTests.cs @@ -0,0 +1,176 @@ +using Xunit; + +namespace FinalToken.Core.Tests; + +public sealed class ResetHistoryTests +{ + private static readonly DateTimeOffset Day = new(2026, 10, 1, 0, 0, 0, TimeSpan.Zero); + private static readonly TimeSpan Week = TimeSpan.FromDays(7); + private static LimitWindow Window(DateTimeOffset start, double used = 50, double sampleHour = 1) => + new(Provider.Codex, "codex:primary", "Week", used, start + Week, Week, start.AddHours(sampleHour), "fixture"); + private static ModelTokenPoint Token(DateTimeOffset time, long input = 1_000_000, string model = "gpt-6.1-sol") => + new(time, model, new(Input: input, Total: input)); + private static ResetHistory History(LimitWindow current, LimitWindow[] samples, ModelTokenPoint[] tokens, + DateTimeOffset? from = null, DateTimeOffset? now = null, TimeZoneInfo? zone = null) => + LimitAnalysis.Resets(current, samples, tokens, from ?? DateTimeOffset.MinValue, now ?? current.SampleTime, zone ?? TimeZoneInfo.Utc); + + [Fact] public void SeriesMergesCodexSlotsButSeparatesLengthsNamesAndProviders() + { + var week = Window(Day); + Assert.True(LimitAnalysis.SameInstance(week, week with { Id = "codex:secondary" })); + Assert.False(LimitAnalysis.SameInstance(week, week with { Length = TimeSpan.FromHours(5) })); + Assert.False(LimitAnalysis.SameInstance(week, week with { Id = "codex_bengalfox:primary" })); + Assert.False(LimitAnalysis.SameInstance(week, week with { Provider = Provider.Claude })); + var previous = Window(Day - Week, 30) with { Id = "codex:secondary" }; + var wrong = previous with { Id = week.Id, Length = TimeSpan.FromHours(5), UsedPercent = 99 }; + var other = previous with { Id = "codex_bengalfox:secondary", UsedPercent = 98 }; + var analysis = LimitAnalysis.Analyze(week, [previous, wrong, other], [], week.SampleTime, TimeZoneInfo.Utc)!; + Assert.Equal(30, Assert.Single(analysis.Past).Peak); + Assert.Equal(30, History(week, [previous, wrong, other], []).Instances[1].Final.Used); + Assert.Null(LimitAnalysis.Recent(week, [week with { Length = TimeSpan.FromHours(5), UsedPercent = 0, SampleTime = week.SampleTime.AddHours(-4) }], week.SampleTime)); + } + + [Fact] public void StoreSeriesQueryKeepsTheOriginalIdQueryWorking() + { + using var directory = new TestDirectory(); + var store = new HistoryStore(directory.Path, new()); + var week = Window(Day); + var moved = week with { Id = "codex:secondary", SampleTime = week.SampleTime.AddHours(-1) }; + var shortWindow = week with { Length = TimeSpan.FromHours(5) }; + store.AddLimits([moved, shortWindow, week]); + Assert.Equal(3, store.LimitSamples(Provider.Codex, Day, Day.AddDays(1)).Count); + Assert.Equal(2, store.LimitSamples(week, Day, Day.AddDays(1)).Count); + Assert.Equal(2, store.LimitSamples(Provider.Codex, week.Id, Day, Day.AddDays(1)).Count); + } + + [Theory] + [InlineData("claude-haiku-4-5")] + [InlineData("claude-haiku-4-5-20251001")] + public void PriceMatchesExactAndDatedModel(string model) => Assert.Equal(1, ApiPrices.Find(Provider.Claude, model)!.Input); + + [Theory] + [InlineData("codex-auto-review")] + [InlineData("gpt-6.1-sol-latest")] + [InlineData("gpt-6.1-sol-20261301")] + [InlineData("gpt-6.1-sol-20261018-extra")] + [InlineData(null)] + public void UnknownModelHasNoValue(string? model) => Assert.Null(ApiPrices.Value(Provider.Codex, model, new(Input: 100))); + + [Fact] public void ProviderValuesDoNotDoubleCountTokenSubsets() + { + var counts = new TokenCounts(1_000_000, 400_000, 200_000, 100_000, 80_000); + Assert.Equal(17.6m, ApiPrices.Value(Provider.Claude, "claude-fable-5-1", counts)); + Assert.Equal(2.24m, ApiPrices.Value(Provider.Codex, "gpt-6.1-sol", counts)); + Assert.Null(ApiPrices.Find(Provider.Claude, "gpt-6.1-sol")); + } + + [Fact] public void OnTimeEarlyAndRunningInstancesHaveOwnValuesAndTotals() + { + var first = Window(Day, 40); + var second = Window(Day + Week, 50); + var current = Window(Day.AddDays(9), 20); + var history = History(current, [first, second], [Token(Day), Token(second.ResetsAt!.Value - Week), Token(Day.AddDays(9))]); + Assert.Equal(3, history.Instances.Count); + var running = history.Instances[0]; var early = history.Instances[1]; var onTime = history.Instances[2]; + Assert.True(running.Running); Assert.Null(running.Unused); Assert.Null(running.Gift); + Assert.Equal(TimeSpan.FromHours(1), running.Duration); Assert.Equal(current.SampleTime, running.End); + Assert.False(onTime.Early); Assert.Equal(Week, onTime.Duration); Assert.Equal(60, onTime.Unused!.Percent); + Assert.True(early.Early); Assert.Equal(TimeSpan.FromDays(2), early.Duration); Assert.Equal(TimeSpan.FromDays(5), early.Skipped); + Assert.Equal(100d * 5 / 7, early.Gift!.Percent, 8); Assert.Equal(50, early.Unused!.Percent); + Assert.Equal(20_000, early.ValuePerPercent!.Tokens); Assert.Equal(.04m, early.ValuePerPercent.ApiValue); + Assert.Equal(PercentBasis.OwnInstance, early.ValuePerPercent.Basis); + Assert.Equal(1_000_000, early.Unused.Tokens); Assert.Equal(2m, early.Unused.ApiValue); + Assert.Equal(3, history.Totals.Instances); Assert.Equal(2, history.Totals.Finished); Assert.Equal(1, history.Totals.Early); + Assert.Equal(3_000_000, history.Totals.Tokens.Total); Assert.Equal(6m, history.Totals.ApiValue); + Assert.Equal(110, history.Totals.Unused.Percent); Assert.Equal(TimeSpan.FromDays(2), history.MedianDuration); + Assert.Equal(TimeSpan.FromDays(5), history.Totals.Skipped); + } + + [Fact] public void LowUseUsesMedianOfQualifyingListedInstances() + { + var first = Window(Day, 50); var second = Window(Day + Week, 25); var current = Window(Day + Week * 2, 4); + var result = History(current, [first, second], [Token(Day), Token(Day + Week), Token(Day + Week * 2)]); + var rate = result.Instances[0].ValuePerPercent!; + Assert.Equal(30_000, rate.Tokens); Assert.Equal(.06m, rate.ApiValue); Assert.Equal(PercentBasis.SeriesMedian, rate.Basis); + var onlyLow = History(current, [first, second], [Token(Day + Week * 2)], from: current.ResetsAt!.Value - Week); + Assert.Null(Assert.Single(onlyLow.Instances).ValuePerPercent); + } + + [Fact] public void NoQualifyingInstanceKeepsOnlyUnusedAndGiftPercent() + { + var old = Window(Day, 4); var current = Window(Day.AddDays(2), 0); + var row = History(current, [old], []).Instances[1]; + Assert.Null(row.ValuePerPercent); Assert.Equal(96, row.Unused!.Percent); + Assert.Null(row.Unused.Tokens); Assert.Null(row.Unused.ApiValue); Assert.Null(row.Gift!.Tokens); + } + + [Fact] public void ReachedLimitAndTimeAtLimitReuseTheBurnUpIncludingEstimates() + { + var old = Window(Day, 50); var current = Window(Day + Week, 20); + var tokens = new[] { Token(Day), Token(Day.AddHours(2), 2_000_000), Token(Day + Week) }; + var row = History(current, [old], tokens).Instances[1]; + var analysis = LimitAnalysis.Analyze(current, [old], tokens, current.SampleTime, TimeZoneInfo.Utc)!; + Assert.Equal(analysis.Past[0].Points, row.BurnUp.Points); + Assert.Equal(100, row.Peak); Assert.Equal(100, row.Final.Used); Assert.Equal(UseOrigin.Estimated, row.Final.Origin); + Assert.Equal(Day.AddHours(2.5), row.ReachedLimit); + Assert.Equal(Week - TimeSpan.FromHours(2.5), row.TimeAtLimit); + Assert.Equal(0, row.Unused!.Percent); + var measured = History(current, [old with { UsedPercent = 100 }], [Token(Day), Token(Day + Week)]).Instances[1]; + Assert.Equal(old.SampleTime, measured.ReachedLimit); Assert.Equal(UseOrigin.Measured, measured.BurnUp.ReachedOrigin); + } + + [Fact] public void FamilyFilterAndUnpricedModelsAreExplicit() + { + var current = Window(Day, 20) with { Provider = Provider.Claude, Id = "fable", Label = "Week (Fable)" }; + var row = Assert.Single(History(current, [], [Token(Day, 100, "claude-fable-5"), Token(Day, 200, "claude-fable-new"), + Token(Day, 10_000, "claude-sonnet-5")]).Instances); + Assert.Equal(300, row.Tokens.Total); Assert.Equal(200, row.UnpricedTokens); Assert.Equal(.001m, row.ApiValue); + Assert.Equal(2, row.Models.Count); + var zero = Assert.Single(History(current with { UsedPercent = 0 }, [], [Token(Day, 100, "claude-sonnet-5")]).Instances); + Assert.Equal(0, zero.Tokens.Total); Assert.Null(zero.ApiValue); Assert.Null(zero.ValuePerPercent); + } + + [Fact] public void RangeIncludesWholeOverlappingRealInstanceAndLeavesInferredOnesOut() + { + var old = Window(Day, 30); var current = Window(Day + Week * 2, 20); + var result = History(current, [old], [Token(Day), Token(Day + Week), Token(Day + Week * 2)], from: Day.AddDays(3)); + Assert.Equal(2, result.Instances.Count); Assert.Equal(Day, result.Instances[1].Start); + Assert.Equal(1_000_000, result.Instances[1].Tokens.Total); + Assert.Single(History(current, [old], [], from: Day + Week).Instances); + Assert.Equal(old.SampleTime, result.FirstSample); + } + + [Fact] public void JitterAndInterleavedOldRolloutAfterEarlyResetDoNotCreateAnotherInstance() + { + var transition = Day.AddHours(10).AddMinutes(48).AddSeconds(56); + var old = Window(Day.AddDays(-2), 90); + var current = Window(transition, 2); + var newFirst = current with { SampleTime = transition, UsedPercent = 0, ResetsAt = current.ResetsAt!.Value.AddSeconds(-11) }; + var stale = old with { SampleTime = transition.AddSeconds(4), UsedPercent = 98, ResetsAt = old.ResetsAt!.Value.AddSeconds(9) }; + var jitter = old with { SampleTime = old.SampleTime.AddHours(1), UsedPercent = 95, ResetsAt = old.ResetsAt.Value.AddSeconds(11) }; + var result = History(current, [old, jitter, newFirst, stale], [Token(Day.AddDays(-2)), Token(Day.AddHours(10))]); + Assert.Equal(2, result.Instances.Count); Assert.Equal(95, result.Instances[1].Final.Used); + Assert.Equal(transition, result.Instances[1].End); Assert.Equal(1_000_000, result.Instances[0].Tokens.Total); + Assert.Equal(jitter.ResetsAt, result.Instances[1].Reset); + Assert.Equal(1_000_000, result.Instances[1].Tokens.Total); + Assert.DoesNotContain(result.Instances[1].BurnUp.Points, p => p.Used == 98); + } + + [Fact] public void HistogramsUseLocalEndHourAndMondayBasedWeekday() + { + var zone = TimeZoneInfo.CreateCustomTimeZone("Fixture +03", TimeSpan.FromHours(3), "Fixture", "Fixture"); + var old = Window(Day); var transition = Day.AddDays(1).AddHours(22); // Saturday locally. + var result = History(Window(transition), [old], [], zone: zone); + Assert.Equal(1, result.EarlyByHour[1]); Assert.Equal(1, result.EarlyByHour.Sum()); + Assert.Equal(1, result.EarlyByWeekday[5]); Assert.Equal(1, result.EarlyByWeekday.Sum()); + } + + [Theory] + [InlineData(15, false)] + [InlineData(16, true)] + public void EarlyThresholdIsStrictlyMoreThanFifteenMinutes(int minutes, bool early) + { + var old = Window(Day); var next = Window(Day + Week - TimeSpan.FromMinutes(minutes)); + Assert.Equal(early, History(next, [old], []).Instances[1].Early); + } +} -- 2.54.0 From e39a244751e019c380134e24a0c28fc1b2c59bd7 Mon Sep 17 00:00:00 2001 From: Florian Schmidt Date: Sun, 18 Oct 2026 10:07:40 +0200 Subject: [PATCH 07/14] app: show the reset history of each long limit window A Resets section after the window charts gives, per provider, totals for the listed instances, a timeline with each burn-up and the skipped time, early resets by local hour and weekday, and a sortable instance table with a detailed tooltip per row (D8, D12). The breakdown and reset tables share their sorting, header and expander code. Refs #14 --- src/FinalToken.App/AGENTS.md | 9 +- src/FinalToken.App/BreakdownTable.cs | 25 ++-- src/FinalToken.App/DataTooltip.cs | 2 +- src/FinalToken.App/DetailTable.cs | 43 +++++++ src/FinalToken.App/PanelViewModel.cs | 27 ++++- src/FinalToken.App/PanelWindow.cs | 34 ++++++ src/FinalToken.App/ResetCard.cs | 51 ++++++++ src/FinalToken.App/ResetCharts.cs | 126 ++++++++++++++++++++ src/FinalToken.App/ResetTable.cs | 65 ++++++++++ src/FinalToken.App/ResetTooltip.cs | 53 ++++++++ tests/FinalToken.App.Tests/HeadlessTests.cs | 1 + tests/FinalToken.App.Tests/ResetTests.cs | 94 +++++++++++++++ tests/FinalToken.App.Tests/ResetViews.cs | 107 +++++++++++++++++ 13 files changed, 612 insertions(+), 25 deletions(-) create mode 100644 src/FinalToken.App/DetailTable.cs create mode 100644 src/FinalToken.App/ResetCard.cs create mode 100644 src/FinalToken.App/ResetCharts.cs create mode 100644 src/FinalToken.App/ResetTable.cs create mode 100644 src/FinalToken.App/ResetTooltip.cs create mode 100644 tests/FinalToken.App.Tests/ResetTests.cs create mode 100644 tests/FinalToken.App.Tests/ResetViews.cs diff --git a/src/FinalToken.App/AGENTS.md b/src/FinalToken.App/AGENTS.md index 524869f..f85c1ba 100644 --- a/src/FinalToken.App/AGENTS.md +++ b/src/FinalToken.App/AGENTS.md @@ -13,7 +13,8 @@ Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root. ## Panel and visual rules - Keep this order: fixed 56 px header; Limits; Week use per day; Tokens (totals, hourly and daily - charts); Window charts (current-instance burn-up and past peaks); Breakdown by model and project; collapsed Diagnostics, hidden when empty. + charts); Window charts (current-instance burn-up and past peaks); Resets (one full-width card per + provider); Breakdown by model and project; collapsed Diagnostics, hidden when empty. Preserve scroll offset on snapshots. Sections have two columns from 1200 px content width; limit tiles have three from 1400 px. Cards align at the top and size to their content. - Follow the OS light/dark theme through `Ui.Theme` and `Ui.NeutralTheme`. Selection never uses @@ -50,7 +51,8 @@ Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root. have a 2 px surface gap; below 6 px width remove gaps and snap shared edges to physical pixels. Breakdowns show eight rows plus expandable Other; keep every detail column sortable and right-aligned. - Estimated day bars use provider outlines and 45-degree hatching; measured days stay solid. Align past - days by index and burn-ups by elapsed time. Never join different resets on one time axis. + days by index and burn-ups by elapsed time. The Resets timeline puts real instances side by side + on one time axis without joining their lines; hatch skipped time and mark observed resets (D12). Burn-ups use solid measured and lighter dashed estimated lines, with no point markers. - Use DataTooltip for every data hover: bold title, two-column label/value grid, exact and compact counts, optional series swatches. Future days have no cumulative value. Share one date formatter @@ -62,3 +64,6 @@ Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root. Instances start at reset minus length and end at reset or the next start. Keep gaps unassigned; never infer short windows or overlap a sampled window with an inferred one (D7). Label real dates. Page wheel events must never change a selection: WindowSelector bubbles them to the scroll view. +- Resets use the shared detail-table sorting, headers, row placement and expansion. Preserve + the selected window, sort and expansion on renders. Money is invariant USD at API list prices; + unknown models stay unpriced, and percent-derived values and token estimates carry `≈` (D13). diff --git a/src/FinalToken.App/BreakdownTable.cs b/src/FinalToken.App/BreakdownTable.cs index 76e8bc5..5fe7d2d 100644 --- a/src/FinalToken.App/BreakdownTable.cs +++ b/src/FinalToken.App/BreakdownTable.cs @@ -8,12 +8,7 @@ using FinalToken.Core; namespace FinalToken.App; public enum BreakdownColumn { Name, Total, Share, Input, Output, CacheWrite, CacheRead, Reasoning } -public sealed class BreakdownState -{ - public bool Expanded { get; set; } - public BreakdownColumn Sort { get; set; } = BreakdownColumn.Total; - public bool Descending { get; set; } = true; -} +public sealed class BreakdownState() : TableState(BreakdownColumn.Total); public sealed class BreakdownTable : StackPanel { @@ -29,21 +24,21 @@ public sealed class BreakdownTable : StackPanel } public static IReadOnlyList SortRows(IEnumerable rows, BreakdownColumn column, bool descending) { - if (column == BreakdownColumn.Name) return (descending ? rows.OrderByDescending(r => r.Name, StringComparer.OrdinalIgnoreCase) : rows.OrderBy(r => r.Name, StringComparer.OrdinalIgnoreCase)).ToArray(); + if (column == BreakdownColumn.Name) return DetailTable.Sort(rows, r => r.Name, descending, StringComparer.OrdinalIgnoreCase).ToArray(); double Key(BreakdownRow r) => column switch { BreakdownColumn.Total => r.Counts.Total, BreakdownColumn.Share => r.Share, BreakdownColumn.Input => r.Counts.Input, BreakdownColumn.Output => r.Counts.Output, BreakdownColumn.CacheWrite => r.Counts.CacheWrite, BreakdownColumn.CacheRead => r.Counts.CacheRead, _ => r.Counts.ReasoningOutput }; - return (descending ? rows.OrderByDescending(Key) : rows.OrderBy(Key)).ThenBy(r => r.Name, StringComparer.OrdinalIgnoreCase).ToArray(); + return DetailTable.Sort(rows, Key, descending).ThenBy(r => r.Name, StringComparer.OrdinalIgnoreCase).ToArray(); } private void RenderTable() { Children.Clear(); var header = new DockPanel(); if (rows.Count > 8) { - var expand = Ui.Button(state.Expanded ? "Show top 8" : $"Show all {rows.Count}", () => { state.Expanded = !state.Expanded; RenderTable(); }); + var expand = DetailTable.Expansion(rows.Count, state, RenderTable); DockPanel.SetDock(expand, Dock.Right); header.Children.Add(expand); } header.Children.Add(Ui.Text(title, 15)); Children.Add(header); @@ -61,12 +56,7 @@ public sealed class BreakdownTable : StackPanel for (var c = 0; c < (reasoning ? 8 : 7); c++) { var column = (BreakdownColumn)c; - var button = Ui.Button(headers[c] + (state.Sort == column ? state.Descending ? " ↓" : " ↑" : ""), () => - { - state.Descending = state.Sort != column || !state.Descending; state.Sort = column; RenderTable(); - }); - button.Name = title.Replace(" ", "") + "Sort" + column; - button.Padding = new Thickness(0, 4); button.HorizontalAlignment = c == 0 ? HorizontalAlignment.Left : HorizontalAlignment.Right; + var button = DetailTable.Header(headers[c], column, state, RenderTable, title.Replace(" ", "") + "Sort" + column, c == 0); Add(button, 0, c); } var names = projects ? PanelWindow.ShortProjectNames(visible.Select(r => r.Name).ToArray()) : visible.Select(r => r.Name).ToArray(); @@ -105,12 +95,11 @@ public sealed class BreakdownTable : StackPanel ToolTip.SetTip(value, DataTooltip.Tokens(row.Name, counts)); Add(value, i + 1, c); } } - Children.Add(new ScrollViewer { Content = grid, HorizontalScrollBarVisibility = ScrollBarVisibility.Auto, VerticalScrollBarVisibility = ScrollBarVisibility.Disabled }); + Children.Add(DetailTable.Scroll(grid)); if (rows.Count == 0) Children.Add(Ui.Text("No tokens in this range.", 12, "Muted")); void Add(Control control, int row, int column) { - while (grid.RowDefinitions.Count <= row) grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto)); - Grid.SetRow(control, row); Grid.SetColumn(control, column); grid.Children.Add(control); + DetailTable.Add(grid, control, row, column); } } } diff --git a/src/FinalToken.App/DataTooltip.cs b/src/FinalToken.App/DataTooltip.cs index f08fb68..89323dc 100644 --- a/src/FinalToken.App/DataTooltip.cs +++ b/src/FinalToken.App/DataTooltip.cs @@ -9,7 +9,7 @@ namespace FinalToken.App; public sealed record TooltipRow(string Label, string Value, IBrush? Swatch = null); /// D8: every data tooltip uses the same title and aligned label/value layout. -public sealed class DataTooltip : Border +public sealed partial class DataTooltip : Border { public string Title { get; } public IReadOnlyList Rows { get; } diff --git a/src/FinalToken.App/DetailTable.cs b/src/FinalToken.App/DetailTable.cs new file mode 100644 index 0000000..37c1d07 --- /dev/null +++ b/src/FinalToken.App/DetailTable.cs @@ -0,0 +1,43 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.Primitives; +using Avalonia.Layout; + +namespace FinalToken.App; + +public class TableState(TColumn sort) where TColumn : struct, Enum +{ + public bool Expanded { get; set; } + public TColumn Sort { get; set; } = sort; + public bool Descending { get; set; } = true; +} + +/// Shared sorting, headers, row placement and expansion for detail tables. +public static class DetailTable +{ + public static IOrderedEnumerable Sort(IEnumerable rows, Func key, + bool descending, IComparer? comparer = null) => + descending ? rows.OrderByDescending(key, comparer) : rows.OrderBy(key, comparer); + + public static Button Header(string label, TColumn column, TableState state, + Action render, string name, bool first = false) where TColumn : struct, Enum + { + var button = Ui.Button(label + (state.Sort.Equals(column) ? state.Descending ? " ↓" : " ↑" : ""), () => + { + state.Descending = !state.Sort.Equals(column) || !state.Descending; state.Sort = column; render(); + }); + button.Name = name; button.Padding = new Thickness(0, 4); + button.HorizontalAlignment = first ? HorizontalAlignment.Left : HorizontalAlignment.Right; + return button; + } + public static Button Expansion(int count, TableState state, Action render) where TColumn : struct, Enum => + Ui.Button(state.Expanded ? "Show top 8" : $"Show all {count}", () => { state.Expanded = !state.Expanded; render(); }); + + public static void Add(Grid grid, Control control, int row, int column) + { + while (grid.RowDefinitions.Count <= row) grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto)); + Grid.SetRow(control, row); Grid.SetColumn(control, column); grid.Children.Add(control); + } + public static ScrollViewer Scroll(Grid grid) => new() { Content = grid, + HorizontalScrollBarVisibility = ScrollBarVisibility.Auto, VerticalScrollBarVisibility = ScrollBarVisibility.Disabled }; +} diff --git a/src/FinalToken.App/PanelViewModel.cs b/src/FinalToken.App/PanelViewModel.cs index 1002e8f..5f9f8fa 100644 --- a/src/FinalToken.App/PanelViewModel.cs +++ b/src/FinalToken.App/PanelViewModel.cs @@ -14,6 +14,7 @@ public sealed record HistoryView(IReadOnlyList Hourly, IReadOnlyList IReadOnlyList Limits, IReadOnlyList Models, IReadOnlyList Projects) { public IReadOnlyList Details { get; init; } = []; + public IReadOnlyList Resets { get; init; } = []; } public partial class PanelViewModel : ObservableObject @@ -50,14 +51,25 @@ public partial class PanelViewModel : ObservableObject var hourly = Series(SeriesInterval.Hour); var daily = Series(SeriesInterval.Day); var details = new List(); + var resets = new List(); var limits = providers.SelectMany(p => p.Windows.Select(w => { - var samples = store.LimitSamples(p.Provider, w.Window.Id, from, now); - var instanceSamples = store.LimitSamples(p.Provider, w.Window.Id, - w.Window.ResetsAt is { } r && w.Window.Length is { } l ? r - l * 9 - TimeSpan.FromMinutes(15) : now.AddDays(-14), now); + var instanceFrom = w.Window.ResetsAt is { } r && w.Window.Length is { } l + ? r - l * 9 - TimeSpan.FromMinutes(15) : now.AddDays(-14); + var resetFrom = from == DateTimeOffset.MinValue ? from : from - (w.Window.Length ?? TimeSpan.Zero) - TimeSpan.FromMinutes(15); + var series = store.LimitSamples(w.Window, resetFrom < instanceFrom ? resetFrom : instanceFrom, now); + var samples = series.Where(s => s.SampleTime >= from).ToArray(); + var instanceSamples = series.Where(s => s.SampleTime >= instanceFrom).ToArray(); var tokens = w.Window.ResetsAt is { } tokenReset && w.Window.Length is { } tokenLength ? store.TokenSeriesByModel(p.Provider, tokenReset - tokenLength * 9 - TimeSpan.FromMinutes(15), now, SeriesInterval.Hour) : []; var analysis = LimitAnalysis.Analyze(w.Window, instanceSamples, tokens, now); + if (w.Window.Length > TimeSpan.FromDays(1)) + { + var tokenFrom = series.Where(s => s.ResetsAt is not null).Select(s => s.ResetsAt!.Value - s.Length!.Value) + .Append(w.Window.ResetsAt is { } resetAt ? resetAt - w.Window.Length.Value : now).Min(); + resets.Add(LimitAnalysis.Resets(w.Window, series, + store.TokenSeriesByModel(p.Provider, tokenFrom, now, SeriesInterval.Hour), from, now)); + } details.Add(new(p.Provider, w.Window.Id, LimitAnalysis.Recent(w.Window, instanceSamples, now, w.Pace), analysis?.Days, instanceSamples.Where(s => LimitAnalysis.SameInstance(s, w.Window)).Select(s => s.SampleTime).DefaultIfEmpty(w.Window.SampleTime).Min())); @@ -71,7 +83,7 @@ public partial class PanelViewModel : ObservableObject new(now, p.Provider.ToString(), w.Window.UsedPercent), analysis, w, now); })).ToArray(); var models = Breakdown(true); var projects = Breakdown(false); - return new(hourly, daily, limits, models, projects) { Details = details }; + return new(hourly, daily, limits, models, projects) { Details = details, Resets = resets }; IReadOnlyList Series(SeriesInterval interval) { @@ -135,4 +147,11 @@ public static class Display public static string Forecast(DateTimeOffset date, PaceState state, TimeProvider? clock = null) => (state == PaceState.Ahead ? "⚠ " : "At this pace ") + "100 % on " + Projection(date, clock); public static string State(PaceState state) => state switch { PaceState.OnTrack => "✓ On track", PaceState.Ahead => "▲ Ahead", PaceState.Behind => "▼ Behind", _ => "? Pace unknown" }; + public static string Money(decimal? value) => value is { } dollars + ? "≈ $" + dollars.ToString(dollars >= 100 ? "N0" : "N2", System.Globalization.CultureInfo.InvariantCulture) : "Unpriced"; + public static string Limits(double percent) => "≈ " + (percent / 100).ToString("0.0", System.Globalization.CultureInfo.InvariantCulture) + " limits"; + public static string ResetPercent(double percent, UseOrigin origin) => (origin == UseOrigin.Estimated ? "≈ " : "") + + percent.ToString("0.#", System.Globalization.CultureInfo.InvariantCulture) + " %"; + public static string ResetDate(DateTimeOffset time, TimeProvider clock) => TimeZoneInfo.ConvertTime(time, clock.LocalTimeZone).ToString("MM-dd HH:mm"); + public static string ResetDuration(TimeSpan span) => span <= TimeSpan.Zero ? "0 min" : Duration(span); } diff --git a/src/FinalToken.App/PanelWindow.cs b/src/FinalToken.App/PanelWindow.cs index c345c63..8fff243 100644 --- a/src/FinalToken.App/PanelWindow.cs +++ b/src/FinalToken.App/PanelWindow.cs @@ -21,6 +21,8 @@ public sealed class PanelWindow : Window private bool wide; private int limitColumns; private readonly Dictionary selectedDailyWindow = []; + private readonly Dictionary selectedResetWindow = []; + private readonly Dictionary> resetTables = []; private readonly BreakdownState modelBreakdown = new(), projectBreakdown = new(); public PanelWindow(PanelViewModel model, Action refresh, Action settings, Action quit, Action reload, TimeProvider? clock = null) @@ -175,6 +177,38 @@ public sealed class PanelWindow : Window Ui.Text("Measured · dashed: estimated · faint: previous · dotted: forecast", 12, "Muted"), new BurnUpChart(limit with { Now = now }, clock), Ui.Text("Past instances · peak use", 12, "Muted"), new InstancePeaks(limit.Analysis!.Past, limit.Provider, clock)))), wide)); } + var resetHistories = h.Resets.Where(r => model.ProviderFilter is null || r.Window.Provider == model.ProviderFilter).ToArray(); + if (resetHistories.Length > 0) + { + content.Add(Ui.Text("Resets", 20)); + foreach (var group in resetHistories.GroupBy(r => r.Window.Provider)) + { + var entries = group.ToArray(); + var index = Array.FindIndex(entries, r => WindowSeries.For(r.Window) == selectedResetWindow.GetValueOrDefault(group.Key)); + if (index < 0) index = 0; + var title = Ui.Text(group.Key + " · " + entries[index].Window.Label, 15); + Control View(ResetHistory history) + { + var key = WindowSeries.For(history.Window); + if (!resetTables.TryGetValue(key, out var state)) resetTables[key] = state = new(ResetColumn.Start); + return new ResetCard(history, state, clock); + } + var view = new Border { Child = View(entries[index]) }; + var stack = Ui.Stack(title); + if (entries.Length > 1) + { + var selector = new WindowSelector { Name = "ResetWindowSelector", ItemsSource = entries.Select(r => r.Window.Label).ToArray(), SelectedIndex = index }; + selector.SelectionChanged += (_, _) => + { + if (selector.SelectedIndex < 0) return; + var history = entries[selector.SelectedIndex]; selectedResetWindow[group.Key] = WindowSeries.For(history.Window); + title.Text = group.Key + " · " + history.Window.Label; view.Child = View(history); + }; + stack.Children.Add(selector); + } + stack.Children.Add(view); content.Add(Ui.Card(stack)); + } + } content.Add(Ui.Text("Breakdown", 20)); content.Add(Ui.Card(new BreakdownTable("By model", h.Models, false, model.ProviderFilter, modelBreakdown))); content.Add(Ui.Card(new BreakdownTable("By project", h.Projects, true, model.ProviderFilter, projectBreakdown))); diff --git a/src/FinalToken.App/ResetCard.cs b/src/FinalToken.App/ResetCard.cs new file mode 100644 index 0000000..c9e9598 --- /dev/null +++ b/src/FinalToken.App/ResetCard.cs @@ -0,0 +1,51 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.Primitives; +using Avalonia.Layout; +using FinalToken.Core; + +namespace FinalToken.App; + +public sealed class ResetCard : StackPanel +{ + public ResetCard(ResetHistory history, TableState state, TimeProvider clock) + { + Spacing = 16; + var totals = history.Totals; + if (totals.Finished == 0) + Children.Add(Ui.Text("No reset observed since " + Display.Projection(history.FirstSample, clock), 12, "Muted")); + if (history.Instances.Count == 0) return; + var stats = new UniformGrid { Columns = 6, Rows = 1 }; + void Stat(string label, string value, string caption, DataTooltip tooltip) + { + var tile = Ui.Stack(Ui.Text(label, 12, "Secondary"), Ui.Text(value, 24), Ui.Text(caption, 12, "Muted")); + tile.Margin = new Thickness(0, 0, 12, 0); ToolTip.SetTip(tile, tooltip); stats.Children.Add(tile); + } + DataTooltip ValueTip(string title, ResetValue value) => new(title, new("Limits", Display.Limits(value.Percent)), + new("Percent", $"{value.Percent:N2} %"), new("Estimated tokens", value.Tokens is { } tokens ? "≈ " + tokens.ToString("N0") : "No qualifying instance"), + new("Estimated API value", Display.Money(value.ApiValue)), new("Basis", "Own instance ≥ 5 %, else series median"), + new("Coverage", "Whole listed instances; hourly boundary tokens")); + string ValueCaption(ResetValue value) => (value.Tokens is { } tokens ? "≈ " + Display.Compact(tokens) + " tokens · " : "") + Display.Money(value.ApiValue); + Stat("Resets", totals.Instances.ToString(), $"{totals.Early} early", new DataTooltip("Listed instances", + new("Total", totals.Instances.ToString()), new("Finished", totals.Finished.ToString()), new("Early", totals.Early.ToString()), + new("Running", (totals.Instances - totals.Finished).ToString()))); + Stat("Tokens", Display.Compact(totals.Tokens.Total), "in listed instances", DataTooltip.Tokens("Reset history tokens", totals.Tokens)); + Stat("API value", Display.Money(totals.ApiValue), "at API list prices", new DataTooltip("API value at list prices", + new("Value", Display.Money(totals.ApiValue)), new("Unpriced tokens", DataTooltip.Count(totals.UnpricedTokens)), + new("Prices checked", ApiPrices.CheckedOn.ToString("yyyy-MM-dd")))); + Stat("Unused", Display.Limits(totals.Unused.Percent), ValueCaption(totals.Unused), ValueTip("Unused limit · estimated value", totals.Unused)); + Stat("Gift", Display.Limits(totals.Gift.Percent), ValueCaption(totals.Gift) + " · " + Display.ResetDuration(totals.Skipped) + " skipped", ValueTip("Early-reset gift · estimated value", totals.Gift)); + Stat("100 % reached", totals.ReachedLimit + "×", Display.ResetDuration(totals.TimeAtLimit) + " at 100 %", new DataTooltip("100 % reached", + new("Instances", totals.ReachedLimit.ToString()), new("Total time", Display.ResetDuration(totals.TimeAtLimit)), + new("Source", history.Instances.Any(r => r.BurnUp.ReachedOrigin == UseOrigin.Estimated) ? "Includes token estimates" : "Measured"))); + Children.Add(stats); + Children.Add(Ui.Text("Measured · dashed: estimated · vertical: reset · hatched: skipped · top band: time at 100 %", 12, "Muted")); + Children.Add(new ResetTimeline(history, clock)); + Children.Add(Ui.Columns([ + Ui.Stack(Ui.Text("Early resets by hour · local time", 13, "Secondary"), new ResetHistogram(history.EarlyByHour, history.Window.Provider, false)), + Ui.Stack(Ui.Text("Early resets by weekday · local time", 13, "Secondary"), new ResetHistogram(history.EarlyByWeekday, history.Window.Provider, true))], true)); + Children.Add(Ui.Text("Median instance " + (history.MedianDuration is { } median ? Display.ResetDuration(median) : "—") + + $" · early resets {totals.Early} of {totals.Instances}", 12, "Secondary")); + Children.Add(new ResetTable(history, state, clock)); + } +} diff --git a/src/FinalToken.App/ResetCharts.cs b/src/FinalToken.App/ResetCharts.cs new file mode 100644 index 0000000..406da38 --- /dev/null +++ b/src/FinalToken.App/ResetCharts.cs @@ -0,0 +1,126 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Media; +using FinalToken.Core; + +namespace FinalToken.App; + +/// D12: real instances share a time axis; their burn-ups are never connected. +public sealed class ResetTimeline(ResetHistory history, TimeProvider clock) : Control +{ + private Rect plot; + private DateTimeOffset from, to; + private readonly List<(Rect Bounds, ResetInstance Instance)> hits = []; + protected override void OnInitialized() + { + base.OnInitialized(); Height = 210; ToolTip.SetShowDelay(this, 0); + PointerMoved += (_, e) => + { + var point = e.GetPosition(this); + if (!plot.Contains(point) || to <= from) { ToolTip.SetTip(this, null); return; } + var time = from.AddTicks((long)((to - from).Ticks * (point.X - plot.Left) / plot.Width)); + var instance = hits.Where(h => h.Bounds.Contains(point)).OrderBy(h => Math.Abs(h.Bounds.Center.X - point.X)) + .Select(h => h.Instance).FirstOrDefault() ?? + history.Instances.FirstOrDefault(r => r.Early && r.End <= time && r.Reset >= time); + ToolTip.SetTip(this, instance is null ? null : DataTooltip.Reset(instance, clock)); + }; + PointerExited += (_, _) => ToolTip.SetTip(this, null); + } + public override void Render(DrawingContext context) + { + base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size)); hits.Clear(); + if (history.Instances.Count == 0) return; + var dark = Ui.Dark(this); var colour = Ui.ProviderColour(history.Window.Provider, dark); var muted = Ui.Colour("Muted", dark); + plot = new Rect(42, 12, Math.Max(1, Bounds.Width - 58), Math.Max(1, Bounds.Height - 48)); + from = history.Instances.Min(r => r.Start); + to = history.Instances.Max(r => r.Early ? r.Reset : r.End); + if (to <= from) to = from.AddHours(1); + double X(DateTimeOffset time) => plot.Left + (time - from).TotalSeconds / (to - from).TotalSeconds * plot.Width; + double Y(double used) => plot.Bottom - used / 100 * plot.Height; + foreach (var tick in new[] { 0, 25, 50, 75, 100 }) + { + context.DrawLine(new Pen(Ui.Colour("Grid", dark)), new(plot.Left, Y(tick)), new(plot.Right, Y(tick))); + ChartText.Draw(context, tick + "%", new(0, Y(tick) - 7), muted); + } + using (context.PushClip(plot)) + { + foreach (var row in history.Instances.Where(r => r.Early)) + { + var band = new Rect(X(row.End), plot.Top, Math.Max(0, X(row.Reset) - X(row.End)), plot.Height); + using (context.PushClip(band)) + { + using (context.PushOpacity(.035)) context.DrawRectangle(colour, null, band); + using (context.PushOpacity(.14)) + for (var x = band.Left - band.Height; x < band.Right; x += 8) + context.DrawLine(new Pen(colour), new(x, band.Bottom), new(x + band.Height, band.Top)); + } + } + foreach (var row in history.Instances.Reverse()) + { + var hitWidth = Math.Max(8, X(row.End) - X(row.Start)); + hits.Add((new Rect((X(row.Start) + X(row.End) - hitWidth) / 2, plot.Top, hitWidth, plot.Height), row)); + if (!row.Running) + context.DrawLine(new Pen(Ui.Colour("Axis", dark)), new(X(row.End), plot.Top), new(X(row.End), plot.Bottom)); + if (row.ReachedLimit is { } reached) + { + using (context.PushOpacity(.16)) context.DrawRectangle(colour, null, + new Rect(X(reached), plot.Top, Math.Max(1, X(row.End) - X(reached)), 7)); + context.DrawLine(new Pen(colour, 3), new(X(reached), plot.Top + 1), new(X(row.End), plot.Top + 1)); + } + var points = row.BurnUp.Points; + for (var i = 1; i < points.Count; i++) + { + var a = points[i - 1]; var b = points[i]; + if (i == 1 && a.Time == row.Start && row.BurnUp.Scale is null && b.Origin == UseOrigin.Measured && b.Time > row.Start) continue; + var estimated = a.Origin == UseOrigin.Estimated || b.Origin == UseOrigin.Estimated; + using (context.PushOpacity(estimated ? .55 : 1)) + context.DrawLine(new Pen(colour, 2, estimated ? new DashStyle([4, 3], 0) : null), new(X(a.Time), Y(a.Used)), new(X(b.Time), Y(b.Used))); + } + } + } + for (var i = 0; i < 5; i++) + { + var time = from.AddTicks((to - from).Ticks * i / 4); + ChartText.Draw(context, Display.ResetDate(time, clock), new(Math.Clamp(X(time) - 36, plot.Left, Math.Max(plot.Left, plot.Right - 86)), plot.Bottom + 12), muted); + } + } +} + +public sealed class ResetHistogram(IReadOnlyList counts, Provider provider, bool weekdays) : Control +{ + private readonly List<(Rect Bounds, int Index)> hits = []; + private static readonly string[] Weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; + protected override void OnInitialized() + { + base.OnInitialized(); Height = 104; ToolTip.SetShowDelay(this, 0); + PointerMoved += (_, e) => + { + var hit = hits.Where(h => h.Bounds.Contains(e.GetPosition(this))).Select(h => (int?)h.Index).FirstOrDefault(); + ToolTip.SetTip(this, hit is { } index ? new DataTooltip(weekdays ? Weekdays[index] : $"{index:00}:00–{index:00}:59 local", + new TooltipRow("Early resets", counts[index].ToString())) : null); + }; + PointerExited += (_, _) => ToolTip.SetTip(this, null); + } + public override void Render(DrawingContext context) + { + base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size)); hits.Clear(); + if (counts.Count == 0) return; + var dark = Ui.Dark(this); var colour = Ui.ProviderColour(provider, dark); var muted = Ui.Colour("Muted", dark); + var plot = new Rect(26, 10, Math.Max(1, Bounds.Width - 34), Math.Max(1, Bounds.Height - 34)); + var maximum = Math.Max(1, counts.Max()); var width = plot.Width / counts.Count; + ChartText.Draw(context, maximum.ToString(), new(0, plot.Top - 6), muted); + ChartText.Draw(context, "0", new(8, plot.Bottom - 6), muted); + context.DrawLine(new Pen(Ui.Colour("Grid", dark)), plot.TopLeft, plot.TopRight); + context.DrawLine(new Pen(Ui.Colour("Axis", dark)), plot.BottomLeft, plot.BottomRight); + for (var i = 0; i < counts.Count; i++) + { + var height = plot.Height * counts[i] / maximum; + var left = plot.Left + i * width; + var bar = UsageChart.BarBounds(left, plot.Bottom, width, height, TopLevel.GetTopLevel(this)?.RenderScaling ?? 1); + if (height > 0) context.DrawRectangle(colour, null, bar); + hits.Add((new(left, plot.Top, Math.Max(8, width), plot.Height), i)); + if (weekdays || i % 3 == 0) + ChartText.Draw(context, weekdays ? Weekdays[i] : i.ToString("00"), new(left + width / 2 - (weekdays ? 10 : 6), plot.Bottom + 8), muted, 11); + } + } +} diff --git a/src/FinalToken.App/ResetTable.cs b/src/FinalToken.App/ResetTable.cs new file mode 100644 index 0000000..73d09ae --- /dev/null +++ b/src/FinalToken.App/ResetTable.cs @@ -0,0 +1,65 @@ +using Avalonia.Controls; +using Avalonia.Layout; +using FinalToken.Core; + +namespace FinalToken.App; + +public enum ResetColumn { Start, End, Lasted, Reset, Final, Reached, Tokens, ApiValue, Unused, Gift } + +public sealed class ResetTable : StackPanel +{ + private readonly ResetHistory history; + private readonly TableState state; + private readonly TimeProvider clock; + public ResetTable(ResetHistory history, TableState state, TimeProvider clock) + { + this.history = history; this.state = state; this.clock = clock; Spacing = 8; + AttachedToVisualTree += (_, _) => RenderTable(); + } + public static IReadOnlyList SortRows(IEnumerable rows, ResetColumn column, bool descending) + { + double Key(ResetInstance row) => column switch + { + ResetColumn.Start => row.Start.UtcTicks, ResetColumn.End => row.End.UtcTicks, + ResetColumn.Lasted => row.Duration.Ticks, ResetColumn.Reset => row.Skipped.Ticks, + ResetColumn.Final => row.Final.Used, ResetColumn.Reached => row.ReachedLimit?.UtcTicks ?? double.MinValue, + ResetColumn.Tokens => row.Tokens.Total, ResetColumn.ApiValue => (double?)row.ApiValue ?? double.MinValue, + ResetColumn.Unused => row.Unused?.Percent ?? double.MinValue, _ => row.Gift?.Percent ?? double.MinValue + }; + return DetailTable.Sort(rows, Key, descending).ThenByDescending(r => r.Start).ToArray(); + } + private void RenderTable() + { + Children.Clear(); + var heading = new DockPanel(); + if (history.Instances.Count > 8) + { + var expand = DetailTable.Expansion(history.Instances.Count, state, RenderTable); + expand.Name = "ResetExpand"; DockPanel.SetDock(expand, Dock.Right); heading.Children.Add(expand); + } + heading.Children.Add(Ui.Text(state.Sort == ResetColumn.Start && state.Descending ? "Instances · newest first" : "Instances", 13, "Secondary")); Children.Add(heading); + var grid = new Grid { Name = "ResetRows", ColumnDefinitions = new ColumnDefinitions("100,100,90,150,110,110,80,90,100,100"), + ColumnSpacing = 12, RowSpacing = 8, MinWidth = 1138 }; + string[] headers = ["Start", "End", "Lasted", "Reset", "Final (peak)", "100 % at", "Tokens", "API value", "Unused", "Gift"]; + for (var c = 0; c < headers.Length; c++) + DetailTable.Add(grid, DetailTable.Header(headers[c], (ResetColumn)c, state, RenderTable, "ResetSort" + (ResetColumn)c, c == 0), 0, c); + var sorted = SortRows(history.Instances, state.Sort, state.Descending); + var visible = state.Expanded ? sorted : sorted.Take(8).ToArray(); + for (var r = 0; r < visible.Count; r++) + { + var row = visible[r]; + string Value(ResetValue? value) => value is null ? "—" : Display.ResetPercent(value.Percent, UseOrigin.Estimated); + string[] cells = [Display.ResetDate(row.Start, clock), row.Running ? "Running" : Display.ResetDate(row.End, clock), Display.ResetDuration(row.Duration), + row.Running ? "Running" : row.Early ? "Early by " + Display.ResetDuration(row.Skipped) : "On time", + Display.ResetPercent(row.Final.Used, row.Final.Origin) + (row.Peak is { } peak ? " (" + Display.ResetPercent(peak, row.PeakOrigin) + ")" : ""), + row.ReachedLimit is { } reached ? (row.BurnUp.ReachedOrigin == UseOrigin.Estimated ? "≈ " : "") + Display.ResetDate(reached, clock) : "—", + Display.Compact(row.Tokens.Total), Display.Money(row.ApiValue), Value(row.Unused), Value(row.Gift)]; + for (var c = 0; c < cells.Length; c++) + { + var text = Ui.TableNumber(cells[c], 12); text.HorizontalAlignment = c == 0 ? HorizontalAlignment.Left : HorizontalAlignment.Right; + ToolTip.SetTip(text, DataTooltip.Reset(row, clock)); DetailTable.Add(grid, text, r + 1, c); + } + } + Children.Add(DetailTable.Scroll(grid)); + } +} diff --git a/src/FinalToken.App/ResetTooltip.cs b/src/FinalToken.App/ResetTooltip.cs new file mode 100644 index 0000000..471a5d2 --- /dev/null +++ b/src/FinalToken.App/ResetTooltip.cs @@ -0,0 +1,53 @@ +using FinalToken.Core; + +namespace FinalToken.App; + +public sealed partial class DataTooltip +{ + public static DataTooltip Reset(ResetInstance row, TimeProvider clock) + { + var rows = new List + { + new("Start", Display.Projection(row.Start, clock)), + new(row.Running ? "As of" : "End", Display.Projection(row.End, clock)), + new("Nominal reset", Display.Projection(row.Reset, clock)), + new("Lasted", Display.ResetDuration(row.Duration)), + new("Final use", Display.ResetPercent(row.Final.Used, row.Final.Origin)), + new("Peak", row.Peak is { } peak ? Display.ResetPercent(peak, row.PeakOrigin) : "Collecting history"), + new("100 % reached", row.ReachedLimit is { } reached ? + (row.BurnUp.ReachedOrigin == UseOrigin.Estimated ? "≈ " : "") + Display.Projection(reached, clock) : "Not reached"), + new("Time at 100 %", Display.ResetDuration(row.TimeAtLimit)), + new("Total tokens", Count(row.Tokens.Total)), new("Input", Count(row.Tokens.Input)), + new("Cache read", Count(row.Tokens.CacheRead)), new("Cache write", Count(row.Tokens.CacheWrite)), + new("Output", Count(row.Tokens.Output)), new("Reasoning (in output)", Count(row.Tokens.ReasoningOutput)), + new("API list value", Display.Money(row.ApiValue)), new("Unpriced tokens", Count(row.UnpricedTokens)) + }; + foreach (var model in row.Models.Take(5)) + rows.Add(new(model.Model ?? "Unknown model", Count(model.Tokens.Total) + " · " + Display.Money(model.ApiValue))); + if (row.Models.Count > 5) rows.Add(new("Other models", (row.Models.Count - 5).ToString())); + rows.Add(new("Tokens per percent", row.ValuePerPercent is { } rate ? "≈ " + Display.Compact(rate.Tokens) + + " · " + rate.Tokens.ToString("N2") : "No qualifying instance")); + rows.Add(new("API value per percent", Display.Money(row.ValuePerPercent?.ApiValue))); + rows.Add(new("Value basis", row.ValuePerPercent?.Basis switch + { + PercentBasis.OwnInstance => "Own instance (final ≥ 5 %)", + PercentBasis.SeriesMedian => "Median of qualifying listed instances", + _ => "No instance with final ≥ 5 %" + })); + if (row.Unused is { } unused) AddValue("Unused", unused); + if (row.Gift is { } gift) { AddValue("Gift", gift); rows.Add(new("Skipped", Display.ResetDuration(row.Skipped))); } + var estimates = new List(); + if (row.Final.Origin == UseOrigin.Estimated) estimates.Add("final"); + if (row.PeakOrigin == UseOrigin.Estimated) estimates.Add("peak"); + if (row.BurnUp.ReachedOrigin == UseOrigin.Estimated) estimates.Add("100 % time"); + if (row.Unused is not null) estimates.Add("unused value"); + if (row.Gift is not null) estimates.Add("gift value"); + rows.Add(new("Estimated figures", estimates.Count == 0 ? "API list value" : string.Join(", ", estimates) + ", API list value")); + rows.Add(new("Prices checked", ApiPrices.CheckedOn.ToString("yyyy-MM-dd") + " · hourly boundary tokens")); + return new(row.Running ? "Running instance" : row.Early ? "Early reset" : "On-time reset", rows.ToArray()); + + void AddValue(string label, ResetValue value) => rows.Add(new(label, + Display.ResetPercent(value.Percent, UseOrigin.Estimated) + " · " + + (value.Tokens is { } count ? "≈ " + Display.Compact(count) + " tokens · " : "") + Display.Money(value.ApiValue))); + } +} diff --git a/tests/FinalToken.App.Tests/HeadlessTests.cs b/tests/FinalToken.App.Tests/HeadlessTests.cs index e5ac3f6..96d8950 100644 --- a/tests/FinalToken.App.Tests/HeadlessTests.cs +++ b/tests/FinalToken.App.Tests/HeadlessTests.cs @@ -364,6 +364,7 @@ public sealed class HeadlessTests popupClock.Fire(); Dispatcher.UIThread.RunJobs(); Assert.False(first.IsVisible); Assert.False(second.IsVisible); Assert.All(popupClock.Timers, timer => Assert.True(timer.Disposed)); + ResetViews.Verify((window, name) => Save(window, name)); completion.SetResult(); void SaveThemes(Window window, string stem) { diff --git a/tests/FinalToken.App.Tests/ResetTests.cs b/tests/FinalToken.App.Tests/ResetTests.cs new file mode 100644 index 0000000..2de9492 --- /dev/null +++ b/tests/FinalToken.App.Tests/ResetTests.cs @@ -0,0 +1,94 @@ +using System.Globalization; +using FinalToken.Core; +using Xunit; + +namespace FinalToken.App.Tests; + +public sealed class ResetTests +{ + [Fact] public void HistoryQueriesOnlyLongWindowsAndFollowsProviderAndRange() + { + var fixture = ResetFixture.Create(); + var all = PanelViewModel.QueryHistory(fixture.Store, fixture.Snapshot, HistoryRange.All, null, fixture.Now); + Assert.Equal(3, all.Resets.Count); + Assert.All(all.Resets, r => Assert.True(r.Window.Length > TimeSpan.FromDays(1))); + var filtered = PanelViewModel.QueryHistory(fixture.Store, fixture.Snapshot, HistoryRange.All, Provider.Codex, fixture.Now); + Assert.Equal(2, filtered.Resets.Count); Assert.All(filtered.Resets, r => Assert.Equal(Provider.Codex, r.Window.Provider)); + var recent = PanelViewModel.QueryHistory(fixture.Store, fixture.Snapshot, HistoryRange.Hours24, Provider.Codex, fixture.Now); + var week = recent.Resets.Single(r => r.Window.Id == "codex:primary"); + Assert.True(week.Instances.Count < filtered.Resets[0].Instances.Count); + Assert.Contains(week.Instances, r => r.Start < fixture.Now.AddHours(-24) && r.End > fixture.Now.AddHours(-24)); + Assert.Equal(10, filtered.Resets[0].Instances.Count); + } + + [Fact] public void BurnUpQueriesReadTheSeriesAcrossCodexSlotsAndExcludeShortWindows() + { + var fixture = ResetFixture.Create(); + var history = PanelViewModel.QueryHistory(fixture.Store, fixture.Snapshot, HistoryRange.All, Provider.Codex, fixture.Now); + var week = history.Limits.Single(l => l.Window!.Window.Id == "codex:primary" && l.Window.Window.Length > TimeSpan.FromDays(1)); + Assert.DoesNotContain(week.Values, v => v.Value == 99); + Assert.True(week.Values.Count > 10); + Assert.Equal(8, week.Analysis!.Past.Count); + } + + [Fact] public void MoneyAndLimitsStayInvariantOnAGermanDesktop() + { + var previous = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("de-DE"); + Assert.Equal("≈ $1,234", Display.Money(1234)); Assert.Equal("≈ $99.25", Display.Money(99.25m)); + Assert.Equal("Unpriced", Display.Money(null)); Assert.Equal("≈ 3.1 limits", Display.Limits(310)); + Assert.Equal("0 min", Display.ResetDuration(TimeSpan.Zero)); + } + finally { CultureInfo.CurrentCulture = previous; } + } + + [Fact] public void EveryInstanceColumnSortsByItsUnderlyingValue() + { + var fixture = ResetFixture.Create(); + var rows = fixture.History.Resets[0].Instances; + Assert.Equal(rows.OrderBy(r => r.Start), ResetTable.SortRows(rows, ResetColumn.Start, false)); + Assert.Equal(rows.Max(r => r.Final.Used), ResetTable.SortRows(rows, ResetColumn.Final, true)[0].Final.Used); + Assert.Equal(rows.Max(r => r.Skipped), ResetTable.SortRows(rows, ResetColumn.Reset, true)[0].Skipped); + Assert.Equal(rows.Max(r => r.Duration), ResetTable.SortRows(rows, ResetColumn.Lasted, true)[0].Duration); + foreach (var column in Enum.GetValues()) + { + var ascending = ResetTable.SortRows(rows, column, false); var descending = ResetTable.SortRows(rows, column, true); + Assert.Equal(rows.Count, ascending.Count); Assert.Equal(rows.Count, descending.Count); + } + } +} + +internal sealed record ResetFixture(HistoryStore Store, Snapshot Snapshot, DateTimeOffset Now, HistoryView History) +{ + public static ResetFixture Create() + { + var start = new DateTimeOffset(2026, 9, 12, 6, 0, 0, TimeSpan.Zero); + int[] durations = [7, 1, 2, 7, 1, 2, 1, 1, 2]; + var now = start.AddDays(durations.Sum()).AddHours(12); + var store = new HistoryStore(Path.Combine(Path.GetTempPath(), "finaltoken-resets", Guid.NewGuid().ToString("N")), new(), new FixedClock(now)); + var currentStart = start; LimitWindow current = null!; + for (var i = 0; i <= durations.Length; i++) + { + var used = i == 2 ? 100 : i == 4 ? 4 : 20 + i * 7; + current = new(Provider.Codex, i < 4 ? "codex:secondary" : "codex:primary", "Week", used, + currentStart.AddDays(7), TimeSpan.FromDays(7), currentStart.AddHours(6), "fixture"); + store.AddLimits([current with { SampleTime = currentStart.AddHours(1), UsedPercent = used / 2.0 }, current]); + store.AddLimits([current with { Id = "codex_bengalfox:secondary", Label = "Week (Bengalfox)", UsedPercent = 0 }]); + store.Add(new(Provider.Codex, currentStart.AddMinutes(30), "gpt-6.1-sol", "Fixture", new(10_000_000, 4_000_000, 0, 2_000_000, 300_000, 12_000_000), "a" + i)); + store.Add(new(Provider.Codex, currentStart.AddHours(2), "gpt-6-astra", "Fixture", new(1_000_000, 200_000, 0, 2_000_000, 300_000, 3_000_000), "b" + i)); + store.Add(new(Provider.Codex, currentStart.AddHours(2), "codex-auto-review", "Fixture", new(Input: 100_000, Total: 100_000), "c" + i)); + if (i < durations.Length) currentStart = currentStart.AddDays(durations[i]); + } + var shortWindow = current with { Id = "codex:primary", Length = TimeSpan.FromHours(5), ResetsAt = now.AddHours(2), UsedPercent = 99, SampleTime = now.AddMinutes(-1), Label = "Session" }; + store.AddLimits([shortWindow]); + var claude = current with { Provider = Provider.Claude, Id = "week", Label = "Week (all models)" }; + var alternate = current with { Id = "codex_bengalfox:primary", Label = "Week (Bengalfox)", UsedPercent = 0 }; + var snapshot = FakeData.Snapshot(now) with { Providers = + [new(Provider.Codex, ProviderStatus.Available, null, [new(current, Pace.Calculate(current, now)), new(alternate, Pace.Calculate(alternate, now)), + new(shortWindow, Pace.Calculate(shortWindow, now))], new(), new(), new()), + new(Provider.Claude, ProviderStatus.Available, null, [new(claude, Pace.Calculate(claude, now))], new(), null, new())] }; + return new(store, snapshot, now, PanelViewModel.QueryHistory(store, snapshot, HistoryRange.All, null, now)); + } +} diff --git a/tests/FinalToken.App.Tests/ResetViews.cs b/tests/FinalToken.App.Tests/ResetViews.cs new file mode 100644 index 0000000..1e48f37 --- /dev/null +++ b/tests/FinalToken.App.Tests/ResetViews.cs @@ -0,0 +1,107 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Headless; +using Avalonia.Interactivity; +using Avalonia.Styling; +using Avalonia.Threading; +using Avalonia.VisualTree; +using FinalToken.Core; +using Xunit; + +namespace FinalToken.App.Tests; + +internal static class ResetViews +{ + public static void Verify(Action save) + { + var fixture = ResetFixture.Create(); + var clock = new FixedClock(fixture.Now); + var model = new PanelViewModel { Snapshot = fixture.Snapshot, History = fixture.History, Range = HistoryRange.All }; + var panel = new PanelWindow(model, () => { }, () => { }, () => { }, () => { }, clock); + panel.Show(); Dispatcher.UIThread.RunJobs(); + var headings = panel.GetVisualDescendants().OfType().Where(t => t.FontSize == 20).Select(t => t.Text).ToArray(); + Assert.True(Array.IndexOf(headings, "Window charts") < Array.IndexOf(headings, "Resets")); + Assert.True(Array.IndexOf(headings, "Resets") < Array.IndexOf(headings, "Breakdown")); + var selector = panel.GetVisualDescendants().OfType().Single(c => c.Name == "ResetWindowSelector"); + selector.SelectedIndex = 1; + Assert.Contains(panel.GetVisualDescendants().OfType(), t => t.Text == "Codex · Week (Bengalfox)"); + model.Snapshot = model.Snapshot with { MadeAt = fixture.Now.AddMinutes(-1) }; Dispatcher.UIThread.RunJobs(); + Assert.Equal(1, panel.GetVisualDescendants().OfType().Single(c => c.Name == "ResetWindowSelector").SelectedIndex); + panel.GetVisualDescendants().OfType().Single(c => c.Name == "ResetWindowSelector").SelectedIndex = 0; + Dispatcher.UIThread.RunJobs(); + using (panel.CaptureRenderedFrame()) { } + var card = panel.GetVisualDescendants().OfType().First(); + var table = card.GetVisualDescendants().OfType().Single(); + Grid Rows() + { + Dispatcher.UIThread.RunJobs(); + using (panel.CaptureRenderedFrame()) { } + return table.GetVisualDescendants().OfType().Single(g => g.Name == "ResetRows"); + } + void Click(string name) + { + Dispatcher.UIThread.RunJobs(); + using (panel.CaptureRenderedFrame()) { } + table.GetVisualDescendants().OfType