core: plan the daily budget per day, start forecasts at 2 % and follow the limit week (#15)

The developer's feedback of 2026-10-18 named four problems at the top
of the panel: late forecasts, a daily budget that shrank with every use,
unequal Claude and Codex tiles, and an unclear "This week".

- Core: forecasts start at 2 % of a window (D7). Each day of a long
  instance has a share, an even pace and a budget. Today's budget starts
  from the use at the start of the day and stays put while today is
  spent. An estimated start-of-day use counts only the whole hours before
  the first sample's hour, so later samples and tokens do not move it.
  Week token totals follow the provider's limit week, with the calendar
  week as the named fallback; the snapshot carries `weekStart` and
  `weekWindow` (D9).
- App: tiles of one window kind show the same rows, with muted
  placeholders that say why (D8). The stale warning sits in the Used row.
  Week charts draw even pace and budget as steps per day, mark the
  instance start and reset, and label full-day rates. Token tiles say
  since when.
- CLI: prints which week it uses and since when.

Closes #13
This commit was merged in pull request #15.
This commit is contained in:
2026-10-18 10:53:00 +02:00
parent d5ad3ecee9
commit 0a08b508a2
23 changed files with 629 additions and 87 deletions
+46 -18
View File
@@ -154,18 +154,27 @@ probe.
`t + (100 − u) · e·W / u`, is shown; it always comes before `r`. A second forecast uses the `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 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 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 2 % of the window has passed (6 min of a session, about 3 h 22 min of a week), or as soon as
window is ahead. Before either, one hour at 1 % already "reaches" 100 % within days, which is the window is ahead. Before either, a few minutes of use already "reach" 100 % within days,
noise. Until forecasts start, the tile and the window chart say when they will. 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 - **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 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 %. "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 - **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 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. 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 A day's share is the time of that day inside the instance. A 7-day instance that resets at
left until `r`. A 7-day instance that resets at another time than midnight touches 8 local another time than midnight touches 8 local dates; the first and the last have shorter shares,
dates; the first and the last are partial days and both are shown. 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. An estimated `u₀` takes `k` from the first sample at or after `s`, not
the newest, and counts only the whole hours before that sample's hour, so later samples and
tokens do not move it. Without `u₀` there is no budget.
- **Estimates from tokens.** Where samples do not cover a span, its use is estimated from the - **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, 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, output 5, cache write 1.25, cache read 0.1; Codex uncached input 1, cached input 0.1,
@@ -192,19 +201,29 @@ 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 **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 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 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). 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; the token hour that holds the first sample keeps growing after it.
Measured samples alone left the day chart empty until the app had run for a whole week, while the 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 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 of the instance by construction (developer feedback, 2026-10-15). A window that is ahead early is
its first 10 % is no noise: a Codex week at 39 % ten hours after its reset reaches 100 % within no noise: a Codex week at 39 % ten hours after its reset reaches 100 % within a day, and that is
a day, and that is the warning the user needs (developer feedback, 2026-10-15). 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 **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 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 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 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, and overstates `u₀` by the use in that sample's hour before the sample.
## D8 — Desktop app ## D8 — Desktop app
@@ -221,8 +240,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 running in the tray. Starting the app opens the stats panel (R4). Start with the OS is an
opt-in setting. opt-in setting.
- **Panel (R4).** It leads with one tile per limit window: used percent, pace, the forecasts of - **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 [D7](#d7--pace) and, for windows longer than a day, today's use and the daily budget. Tiles of
follow the per-day use of the long windows, token totals and charts, one window chart per limit 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 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 "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 percent as a line (measured, or estimated before the first sample), the even-pace diagonal
@@ -251,15 +275,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 ([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 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 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 and its token totals for today, the current session window and the current week, with the
their source-generated JSON context live in `FinalToken.Core`, shared by the app, the CLI and the week's start and the id of the limit window it follows (`weekStart`, `weekWindow`). The week is
Stream Deck plugin. Nothing listens on a socket or runs an HTTP server. A reader treats a 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 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 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. 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 **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. **Gives up.** Updates faster than the reader's poll interval.
+3 -2
View File
@@ -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`; Slots in order: dark `#3987e5 #d95926 #199e70 #c98500 #d55181 #9085e9`;
light `#2a78d6 #eb6834 #1baf7a #eda100 #e87ba4 #6250d6`. Other is muted. light `#2a78d6 #eb6834 #1baf7a #eda100 #e87ba4 #6250d6`. Other is muted.
- Status chips always have icon and label: `#0ca30c` ✓ On track, `#ec835a` ▲ Ahead, - 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 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 …" 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. 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 - 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 write use full/65%/40% provider colour. Reasoning is part of output; Codex cache read is part
of input. Never add either subset twice. 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 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). 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; Use `LimitAnalysis.SameInstance` for reset membership, history gaps and previous-window lookup;
+45 -17
View File
@@ -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<DataTooltip> Tip)> hits = []; private readonly List<(Rect Rect, Func<DataTooltip> Tip)> hits = [];
public DailyLimitChart() : this(new([], [], null, 0, null), Provider.Claude) { } public DailyLimitChart() : this(new([], [], null, 0, null), Provider.Claude) { }
public IReadOnlyList<string> 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() 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()); PointerMoved += (_, e) => ToolTip.SetTip(this, hits.LastOrDefault(h => h.Rect.Contains(e.GetPosition(this))).Tip?.Invoke());
} }
public override void Render(DrawingContext context) public override void Render(DrawingContext context)
{ {
base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size)); hits.Clear(); 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 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 plot = new Rect(40, 24, Math.Max(1, Bounds.Width - 174), Math.Max(1, Bounds.Height - 76));
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 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]); var ticks = UsageChart.AxisTicks(maximum * 1.15); var max = Math.Max(1, ticks[^1]);
double Y(double value) => plot.Bottom - value / max * plot.Height; double Y(double value) => plot.Bottom - value / max * plot.Height;
foreach (var tick in ticks) 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); ChartText.Draw(context, $"{tick:0.#}%", new(0, Y(tick) - 7), ink);
} }
var width = plot.Width / Math.Max(1, days.Current.Count); var width = plot.Width / Math.Max(1, days.Current.Count);
var labels = AxisLabels;
for (var i = 0; i < days.Current.Count; i++) for (var i = 0; i < days.Current.Count; i++)
{ {
var day = days.Current[i]; var x = plot.Left + i * width; var day = days.Current[i]; var x = plot.Left + i * width;
if (i < days.Previous.Count && days.Previous[i].Used is { } prior) 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) 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))); 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); 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); 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 + 30), () => DataTooltip.Day(day))); 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); if (days.Current.Count == 0) return;
var budgetLabel = days.DailyBudget is { } b ? Math.Clamp(Y(b) - 7, plot.Top, plot.Bottom - 14) : 0; if (days.Reset is { } reset && reset != CalendarDays.Start(reset, clock.LocalTimeZone))
if (days.DailyBudget is { } budget && Math.Abs(evenLabel - budgetLabel) < 18) {
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); var middle = Math.Clamp((evenLabel + budgetLabel) / 2, plot.Top + 9, plot.Bottom - 23);
evenLabel = middle + (budget >= days.EvenPace ? 9 : -9); evenLabel = middle + (value >= even ? 9 : -9);
budgetLabel = middle + (budget >= days.EvenPace ? -9 : 9); budgetLabel = middle + (value >= even ? -9 : 9);
} }
Reference(days.EvenPace, $"Even {days.EvenPace:0.#}%/day", ink, evenLabel, true); // Labels name the full-day rates of the tile's plan row; partial days draw their share of it.
if (days.DailyBudget is { } dailyBudget) Reference(dailyBudget, $"Budget {dailyBudget:0.#}%/day", Ui.Colour("Secondary", dark), budgetLabel, false); Reference(d => d.EvenPace, $"Even {days.EvenPace:0.#}%/day", ink, evenLabel, true);
void Reference(double value, string label, IBrush brush, double labelY, bool dashed) 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<LimitDay, double?> 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))); var pen = new Pen(brush, 1, dashed ? new DashStyle([4, 4], 0) : null);
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)); 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); ChartText.Draw(context, label, new(plot.Right + 8, labelY), brush);
} }
} }
+3
View File
@@ -40,6 +40,9 @@ public sealed class DataTooltip : Border
var rows = new List<TooltipRow> { new("Use", day.IsFuture ? "Future day" : day.Used is { } use ? $"{use:0.##} % of the week" : "Collecting history") }; var rows = new List<TooltipRow> { 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.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.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()); 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)); public override string ToString() => Title + "\n" + string.Join('\n', Rows.Select(r => r.Label + ": " + r.Value));
+2
View File
@@ -112,6 +112,8 @@ public static class Display
return local.ToString(local.Date == clock.GetLocalNow().Date ? "t" : "g", return local.ToString(local.Date == clock.GetLocalNow().Date ? "t" : "g",
culture ?? System.Globalization.CultureInfo.CurrentCulture); 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 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"; ? $"{(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"; public static string Span(TimeSpan span) => span.TotalHours >= 1 ? $"{span.TotalHours:0.#} h" : $"{span.TotalMinutes:0} min";
+35 -22
View File
@@ -120,7 +120,7 @@ public sealed class PanelWindow : Window
if (index < 0) index = 0; 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(); 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) 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"); : 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 chart = new Border { Child = DayView(entries[index]) };
var title = Ui.Text(group.Key + " · " + labels[index], 15); var title = Ui.Text(group.Key + " · " + labels[index], 15);
@@ -154,9 +154,11 @@ public sealed class PanelWindow : Window
var totals = providers.Select(p => var totals = providers.Select(p =>
{ {
var row = new WrapPanel(); var row = new WrapPanel();
row.Children.Add(TokenTile(p, "Today", p.Today)); row.Children.Add(TokenTile(p, "Today", "since 00:00", 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)); 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, "This week", p.Week)); 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)); return (Control)Ui.Card(Ui.Stack(Ui.Text(p.Provider.ToString(), 15), row));
}); });
content.Add(Ui.Columns(totals, wide)); content.Add(Ui.Columns(totals, wide));
@@ -191,48 +193,59 @@ public sealed class PanelWindow : Window
{ {
var w = window.Window; var pace = window.Pace; var w = window.Window; var pace = window.Pace;
var detail = model.History.Details.FirstOrDefault(d => d.Provider == w.Provider && d.Id == w.Id); 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) }; 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)); 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 }); var card = Ui.Stack(title);
card.Children.Add(Ui.Text(w.ResetsAt is { } reset ? $"Resets in {Display.Duration(reset - now)} · {Display.Projection(reset, clock)}" : "Reset unknown", 13, "Secondary")); 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(now - w.SampleTime > model.ProbeInterval * 2
? $"used · ⚠ sample {Display.Duration(now - w.SampleTime)} old" : "used", 12, "Muted"));
Row("Pace", new PaceBar(window, now) { Height = 10 });
Row("Reset", Ui.Text(w.ResetsAt is { } reset ? $"Resets in {Display.Duration(reset - now)} · {Display.Projection(reset, clock)}" : "Reset unknown", 13, "Secondary"));
if (pace.Projection is { } projection) if (pace.Projection is { } projection)
{ {
var caption = Display.Forecast(projection, pace.State, clock) + $" ({Display.Duration(w.ResetsAt!.Value - projection)} before reset)"; var caption = Display.Forecast(projection, pace.State, clock) + $" ({Display.Duration(w.ResetsAt!.Value - projection)} before reset)";
if (pace.State == PaceState.Ahead) if (pace.State == PaceState.Ahead)
{ {
var line = new DockPanel(); var mark = Ui.Mark("⚠ ", Brush.Parse("#d03b3b"), 13); 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) else if (LimitAnalysis.AverageUseAtReset(w, now, pace) is { } average)
card.Children.Add(Ui.Text($"≈ {average:0.#} % at reset", 13, "Secondary")); Row("Forecast", Ui.Text($"≈ {average:0.#} % at reset", 13, "Secondary"));
else if (Display.ForecastWaiting(window, now, clock) is { } waiting) else Row("Forecast", Ui.Text(Display.ForecastWaiting(window, now, clock) ?? "No forecast: pace unknown", 13, "Muted"));
card.Children.Add(Ui.Text(waiting, 13, "Muted"));
if (detail?.Recent is { } recent) 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"); 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 var days = detail?.Days;
? $"Today ≈ +{today:0.#} % of the week (estimated)" : $"Today +{today:0.#} % of the week" : "Today · collecting a day baseline", 15)); var estimated = days?.TodayOrigin == UseOrigin.Estimated || days?.BudgetOrigin == UseOrigin.Estimated;
card.Children.Add(Ui.Text($"Even pace {days.EvenPace:0.#} %/day", 13, "Secondary")); Row("Today", Ui.Text(days?.Today is { } today
if (days.DailyBudget is { } budget) card.Children.Add(Ui.Text($"Budget {budget:0.#} %/day for {Display.Duration(w.ResetsAt!.Value - now)}", 15)); ? $"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"));
var tile = Ui.Card(card); tile.Name = $"LimitTile-{w.Provider}-{w.Id}"; 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.##} %"), 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; 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), 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); 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() private Control CompositionLegend()
{ {
+2
View File
@@ -40,6 +40,8 @@ public static class CliApplication
{ {
await output.WriteLineAsync($"{provider.Provider}: {provider.Status} {provider.Reason}"); 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($" 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) 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}")); 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}"));
} }
+2 -1
View File
@@ -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. propagates. The background engine records other tick failures and retries without faulting its loop.
- Use `CurrentSnapshot`, `Settings`, `UpdateSettingsAsync`, `RefreshNowAsync` and - Use `CurrentSnapshot`, `Settings`, `UpdateSettingsAsync`, `RefreshNowAsync` and
`RecentDiagnostics`. `History` offers token series, model/project breakdowns and limit samples. `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). 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`. 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. Use `CalendarDays.NextStart` for daily query ends; adding 24 hours is wrong on DST days.
+5 -4
View File
@@ -245,17 +245,18 @@ public sealed class HistoryStore
} }
public TokenCounts Total(Provider provider, DateTimeOffset from, DateTimeOffset to) public TokenCounts Total(Provider provider, DateTimeOffset from, DateTimeOffset to)
{ lock (gate) return Sum(Range(provider, from, to).Select(b => b.Counts)); } { lock (gate) return Sum(Range(provider, from, to).Select(b => b.Counts)); }
public (TokenCounts Today, TokenCounts? Session, TokenCounts Week) Totals(Provider provider, DateTimeOffset now, public (TokenCounts Today, TokenCounts? Session, TokenCounts Week, DateTimeOffset WeekStart, string? WeekWindow) Totals(Provider provider, DateTimeOffset now,
LimitWindow? session, TimeZoneInfo? zone = null) LimitWindow? session, TimeZoneInfo? zone = null, LimitWindow? weekWindow = null)
{ {
zone ??= TimeZoneInfo.Local; zone ??= TimeZoneInfo.Local;
var local = TimeZoneInfo.ConvertTime(now, zone); var local = TimeZoneInfo.ConvertTime(now, zone);
var today = local.Date; var today = local.Date;
var week = today.AddDays(-(((int)today.DayOfWeek + 6) % 7)); var week = today.AddDays(-(((int)today.DayOfWeek + 6) % 7));
var todayUtc = CalendarDays.Start(today, zone); 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 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<TokenBucket> Range(Provider provider, DateTimeOffset from, DateTimeOffset to) => private IEnumerable<TokenBucket> Range(Provider provider, DateTimeOffset from, DateTimeOffset to) =>
SelectMonths(from, to).SelectMany(m => GetPartition(m).Buckets.Values) SelectMonths(from, to).SelectMany(m => GetPartition(m).Buckets.Values)
+4 -2
View File
@@ -3,9 +3,11 @@ namespace FinalToken.Core;
public sealed record RateForecast(double PercentPerDay, double UseAtReset, DateTimeOffset? ReachesLimit, public sealed record RateForecast(double PercentPerDay, double UseAtReset, DateTimeOffset? ReachesLimit,
double Increase = 0, TimeSpan Span = default); double Increase = 0, TimeSpan Span = default);
public sealed record LimitDay(DateTimeOffset Start, DateTimeOffset End, double? Used, double? Cumulative, 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<LimitDay> Current, IReadOnlyList<LimitDay> Previous, public sealed record WindowDays(IReadOnlyList<LimitDay> Current, IReadOnlyList<LimitDay> 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);
/// <summary>Pure D7 calculations. Missing baselines use marked token estimates when calibration is available.</summary> /// <summary>Pure D7 calculations. Missing baselines use marked token estimates when calibration is available.</summary>
public static partial class LimitAnalysis public static partial class LimitAnalysis
+60
View File
@@ -0,0 +1,60 @@
namespace FinalToken.Core;
public static partial class LimitAnalysis
{
private static double WeightedTokens(IReadOnlyList<(DateTimeOffset Time, double Weight)> weighted,
DateTimeOffset start, DateTimeOffset end, DateTimeOffset from, DateTimeOffset to)
{
var hour = Hour(from < start ? start : from);
var exclusiveEnd = Hour(end);
return weighted.Where(p => p.Time >= hour && p.Time < to && p.Time < exclusiveEnd).Sum(p => p.Weight);
}
// D7: plan from the day baseline; spending within that plan does not take from later days.
private static WindowDays PlanDays(LimitWindow window, LimitInstance current, LimitInstance? previous,
LimitDay? today, IReadOnlyList<LimitWindow> observations, IReadOnlyList<(DateTimeOffset Time, double Weight)> weighted,
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 (Instance(window, observations).FirstOrDefault(s => s.SampleTime >= start) is { } first)
{
// D7: use only completed hours before the first sample; its own hour can still grow.
var sampleHour = Hour(first.SampleTime);
var baselineEnd = start < sampleHour ? start : sampleHour;
var denominator = WeightedTokens(weighted, current.Start, current.End, current.Start, sampleHour);
if (denominator > 0)
{
baseline = first.UsedPercent * WeightedTokens(weighted, current.Start, current.End, current.Start, baselineEnd) / denominator;
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);
}
}
+2 -5
View File
@@ -66,8 +66,7 @@ public static partial class LimitAnalysis
if (length > TimeSpan.FromDays(1)) if (length > TimeSpan.FromDays(1))
{ {
var today = current.Days.FirstOrDefault(d => d.IsToday); var today = current.Days.FirstOrDefault(d => d.IsToday);
days = new(current.Days, past.FirstOrDefault()?.Days ?? [], today?.Used, 100 / length.TotalDays, days = PlanDays(window, current, past.FirstOrDefault(), today, observations, weighted, now, zone);
reset > now ? (100 - window.UsedPercent) / (reset - now).TotalDays : null, today?.Origin ?? UseOrigin.Measured);
} }
return new(current, past, days); return new(current, past, days);
@@ -76,9 +75,7 @@ public static partial class LimitAnalysis
{ {
double Weight(DateTimeOffset from, DateTimeOffset to) double Weight(DateTimeOffset from, DateTimeOffset to)
{ {
var hour = Hour(from < start ? start : from); return WeightedTokens(weighted, start, end, from, to);
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) 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(); .GroupBy(s => s.SampleTime).Select(g => g.Last()).OrderBy(s => s.SampleTime).ToArray();
+2 -2
View File
@@ -2,10 +2,10 @@ namespace FinalToken.Core;
public static class Pace 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) => public static DateTimeOffset? ForecastStartsAt(LimitWindow window) =>
window.Length is { Ticks: > 0 } length && window.ResetsAt is { } reset 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) => public static bool CanForecast(LimitWindow window, DateTimeOffset now, double threshold = 10) =>
CanForecast(window, now, Calculate(window, now, threshold)); CanForecast(window, now, Calculate(window, now, threshold));
+5 -2
View File
@@ -199,10 +199,13 @@ public sealed class RefreshEngine : IAsyncDisposable
var windows = History.LatestLimits(provider); var windows = History.LatestLimits(provider);
// Session totals follow an explicitly short limit window, never a week mislabeled primary. // 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 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 state = statuses[provider];
var snapshots = windows.Select(w => new WindowSnapshot(w, Pace.Calculate(w, now, config.PaceThreshold))).ToArray(); 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) foreach (var window in snapshots)
if (state.Status == ProviderStatus.Available && popups.Observe(window.Window, window.Pace, config) is { } alert) if (state.Status == ProviderStatus.Available && popups.Observe(window.Window, window.Pace, config) is { } alert)
alerts.Add(alert); alerts.Add(alert);
+2 -1
View File
@@ -8,7 +8,8 @@ public sealed record WindowSnapshot(LimitWindow Window, PaceResult Pace)
public TimeSpan Age(DateTimeOffset now) => now - Window.SampleTime; public TimeSpan Age(DateTimeOffset now) => now - Window.SampleTime;
} }
public sealed record ProviderSnapshot(Provider Provider, ProviderStatus Status, string? Reason, public sealed record ProviderSnapshot(Provider Provider, ProviderStatus Status, string? Reason,
IReadOnlyList<WindowSnapshot> Windows, TokenCounts Today, TokenCounts? Session, TokenCounts Week); IReadOnlyList<WindowSnapshot> Windows, TokenCounts Today, TokenCounts? Session, TokenCounts Week, DateTimeOffset WeekStart = default,
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? WeekWindow = null);
public sealed record Snapshot public sealed record Snapshot
{ {
// Keep this initializer for omitted properties in source-generated JSON (D9). // Keep this initializer for omitted properties in source-generated JSON (D9).
+71 -1
View File
@@ -146,6 +146,76 @@ public sealed class HeadlessTests
model.Snapshot = model.Snapshot! with { MadeAt = clock.GetUtcNow() }; Dispatcher.UIThread.RunJobs(); model.Snapshot = model.Snapshot! with { MadeAt = clock.GetUtcNow() }; Dispatcher.UIThread.RunJobs();
Assert.Equal(prior, viewport.Offset); 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<Border>()
.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<TextBlock>(), t => t.Text == "Limit week");
Assert.Contains(budgetPanel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Calendar week");
Assert.Contains(budgetPanel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "since Mon 00:00");
var tokenTiles = budgetPanel.GetVisualDescendants().OfType<StackPanel>().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<TextBlock>(), t => t.Text == "since " + TimeZoneInfo.ConvertTime(budgetSnapshot.Providers[0].WeekStart, budgetClock.LocalTimeZone).ToString("ddd HH:mm"));
Assert.Contains("Limit week", Assert.IsType<DataTooltip>(ToolTip.GetTip(limitTokens)).Title);
Assert.Contains("since ", Assert.IsType<DataTooltip>(ToolTip.GetTip(limitTokens)).Title);
foreach (var dayChart in budgetPanel.GetVisualDescendants().OfType<DailyLimitChart>())
{
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<ScrollViewer>().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<TextBlock>().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.Snapshot = budgetSnapshot with { Providers = budgetSnapshot.Providers.Select(p => p.Provider == Provider.Codex
? p with { Windows = p.Windows.Select(w => w with { Window = w.Window with { SampleTime = budgetClock.GetUtcNow().AddMinutes(-15) } }).ToArray() }
: p).ToArray() };
Dispatcher.UIThread.RunJobs();
Assert.Equal(longRows, Rows(Provider.Claude)); Assert.Equal(longRows, Rows(Provider.Codex));
var staleWeek = budgetPanel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-week");
var freshWeek = budgetPanel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Claude-week");
var staleUsed = staleWeek.GetVisualDescendants().OfType<TextBlock>().Single(t => t.Name == "Used");
Assert.Equal("used · ⚠ sample 15 min old", staleUsed.Text);
Assert.Equal(12, staleUsed.FontSize); Assert.Equal("#ff898781", staleUsed.Foreground?.ToString());
Assert.Equal("used", freshWeek.GetVisualDescendants().OfType<TextBlock>().Single(t => t.Name == "Used").Text);
budgetPanel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = default;
SaveThemes(budgetPanel, "budget-stale-1280x1000");
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<TextBlock>(), t => t.Text == "No forecast: pace unknown");
Assert.Contains(budgetPanel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Recent rate needs 3 h of samples");
Assert.Contains(budgetPanel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.StartsWith("Recent rate from ", StringComparison.Ordinal) == true);
Assert.Contains(budgetPanel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Today · collecting a day baseline");
budgetPanel.Close();
var forecastModel = FakeData.ForecastModel(); var forecastModel = FakeData.ForecastModel();
var forecastClock = new FixedClock(forecastModel.Snapshot!.MadeAt); var forecastClock = new FixedClock(forecastModel.Snapshot!.MadeAt);
var forecastPanel = new PanelWindow(forecastModel, () => { }, () => { }, () => { }, () => { }, forecastClock); var forecastPanel = new PanelWindow(forecastModel, () => { }, () => { }, () => { }, () => { }, forecastClock);
@@ -239,7 +309,7 @@ public sealed class HeadlessTests
("future-day", future), ("future-day", future),
("project", DataTooltip.Tokens("D:/Projects/Customer/Workspace/Project-with-a-long-name", new(100000000, 1900000000, 10000000, 53670717, 1234567, 2063670717))), ("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<Border>().First(b => b.Name == "LimitTile-Claude-week"))!), ("tile", (DataTooltip)ToolTip.GetTip(panel.GetVisualDescendants().OfType<Border>().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"); 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)); CaptureChartTip("burnup", new BurnUpChart(limit, clock), new Point(240, 100));
+22 -3
View File
@@ -10,7 +10,7 @@ public sealed class ViewModelTests
[InlineData(40, false)] [InlineData(40, false)]
public void HistoryForecastsUseTheSnapshotsConfiguredPace(double threshold, bool eligible) 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.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); 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 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 now = new DateTimeOffset(2026, 10, 15, 16, 45, 0, TimeSpan.Zero);
var ahead = new LimitWindow(Provider.Codex, "primary", "Week", 39, var ahead = new LimitWindow(Provider.Codex, "primary", "Week", 39,
new(2026, 10, 22, 6, 18, 0, TimeSpan.Zero), TimeSpan.FromDays(7), now, "fixture"); 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)); 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, store.AddLimits([ahead with { SampleTime = now.AddHours(-4), UsedPercent = 20 }, ahead,
early with { SampleTime = now.AddHours(-1), UsedPercent = 0 }, early]); 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) 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)); } { 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() public static PanelViewModel EarlyResetModel()
{ {
var now = new FixedClock().GetUtcNow(); var now = new FixedClock().GetUtcNow();
+18
View File
@@ -61,11 +61,29 @@ public class CliTests
Assert.Equal(0, await CliApplication.RunAsync(["status", "--no-probe"], output, error, directory, 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)); 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("Tokens today: 0", output.ToString());
Assert.Contains("Calendar week: since ", output.ToString());
Assert.NotNull(SnapshotFile.Read(directory).Snapshot); Assert.NotNull(SnapshotFile.Read(directory).Snapshot);
} }
finally { Directory.Delete(directory, true); } finally { Directory.Delete(directory, true); }
} }
[Fact] [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() public async Task BusyStoreWithoutSnapshotExitsOne()
{ {
var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N")); var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N"));
@@ -0,0 +1,225 @@
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 FirstSampleKeepsEstimatedBudgetStableWhenLaterUseHasNoLocalTokens()
{
var day = CalendarDays.Start(Start.AddDays(3), Zone);
var first = Week(day.AddHours(2), 20);
var newest = Week(day.AddHours(12), 22);
ModelTokenPoint[] tokens = [new(day.AddHours(-1), "fixture", new(Input: 100)), new(day.AddHours(1), "fixture", new(Input: 100))];
var initial = LimitAnalysis.Analyze(first, [], tokens, first.SampleTime, Zone)!.Days!;
var later = LimitAnalysis.Analyze(newest, [first], tokens, newest.SampleTime, Zone)!.Days!;
var remainingDays = (first.ResetsAt!.Value - day).TotalDays;
var expectedBudget = 90 / remainingDays;
Assert.Equal(18.202247191, expectedBudget, 8);
Assert.Equal(10, initial.Today); Assert.Equal(11, later.Today);
foreach (var days in new[] { initial, later })
{
Assert.Equal(10, 100 - days.TodayBudget!.Value * remainingDays, 8);
Assert.Equal(expectedBudget, days.TodayBudget.Value, 8);
Assert.Equal(expectedBudget, days.LaterBudget!.Value, 8);
Assert.Equal(UseOrigin.Estimated, days.BudgetOrigin);
Assert.Equal(UseOrigin.Estimated, days.TodayOrigin);
Assert.True(days.Today < days.TodayBudget);
Assert.All(days.Current.Where(d => d.IsToday || d.IsFuture), d => Assert.Equal(UseOrigin.Estimated, d.BudgetOrigin));
}
Assert.Equal(initial.Current.Select(d => d.Budget), later.Current.Select(d => d.Budget));
}
[Fact] public void TokensAddedInFirstSampleHourDoNotMoveEstimatedBudgets()
{
var day = CalendarDays.Start(Start.AddDays(3), Zone);
var first = Week(day.AddHours(2).AddMinutes(5), 20);
var newest = Week(day.AddHours(2).AddMinutes(30), 22);
// Hourly buckets for 100 input tokens at 23:30 and 02:01 local.
ModelTokenPoint[] tokens = [new(day.AddHours(-1), "fixture", new(Input: 100)), new(day.AddHours(2), "fixture", new(Input: 100))];
var initial = LimitAnalysis.Analyze(first, [], tokens, first.SampleTime, Zone)!.Days!;
ModelTokenPoint[] moreTokens = [.. tokens, new(day.AddHours(2), "fixture", new(Input: 100))];
var later = LimitAnalysis.Analyze(newest, [first], moreTokens, newest.SampleTime, Zone)!.Days!;
var remainingDays = (first.ResetsAt!.Value - day).TotalDays;
var expectedBudget = 80 / remainingDays;
Assert.Equal(10, initial.Today); Assert.Equal(22d * 200 / 300, later.Today!.Value, 8);
foreach (var days in new[] { initial, later })
{
Assert.Equal(20, 100 - days.TodayBudget!.Value * remainingDays, 8);
Assert.Equal(expectedBudget, days.TodayBudget.Value, 8);
Assert.Equal(expectedBudget, days.LaterBudget!.Value, 8);
Assert.Equal(UseOrigin.Estimated, days.BudgetOrigin);
Assert.Equal(UseOrigin.Estimated, days.TodayOrigin);
Assert.True(days.Today < days.TodayBudget);
Assert.All(days.Current.Where(d => d.IsToday || d.IsFuture), d => Assert.Equal(UseOrigin.Estimated, d.BudgetOrigin));
}
Assert.Equal(initial.TodayBudget, later.TodayBudget);
Assert.Equal(initial.LaterBudget, later.LaterBudget);
Assert.Equal(initial.Current.Select(d => d.Budget), later.Current.Select(d => d.Budget));
}
[Fact] public void FirstSampleInFirstHourUsesItsPercentAsEstimatedBaseline()
{
var day = CalendarDays.Start(Start.AddDays(3), Zone);
var first = Week(day.AddMinutes(5), 20);
ModelTokenPoint[] tokens = [new(day.AddHours(-1), "fixture", new(Input: 100)), new(day, "fixture", new(Input: 100))];
var days = LimitAnalysis.Analyze(first, [], tokens, first.SampleTime, Zone)!.Days!;
var remainingDays = (first.ResetsAt!.Value - day).TotalDays;
Assert.Equal(first.UsedPercent, 100 - days.TodayBudget!.Value * remainingDays, 8);
Assert.Equal(80 / remainingDays, days.TodayBudget.Value, 8);
Assert.Equal(80 / remainingDays, days.LaterBudget!.Value, 8);
Assert.Equal(UseOrigin.Estimated, days.BudgetOrigin);
}
[Fact] public void HalfHourZoneExcludesTheUtcHourContainingMidnightFromEstimatedBaseline()
{
var zone = TimeZoneInfo.CreateCustomTimeZone("Fixture+0530", TimeSpan.FromHours(5.5), "Fixture", "Fixture");
var day = CalendarDays.Start(new DateTime(2026, 10, 13), zone);
var firstHour = day.AddMinutes(-30);
var first = Week(day.AddMinutes(5), 20);
var newest = Week(day.AddMinutes(15), 22);
ModelTokenPoint[] tokens = [new(firstHour.AddHours(-1), "fixture", new(Input: 100)), new(firstHour, "fixture", new(Input: 100))];
var initial = LimitAnalysis.Analyze(first, [], tokens, first.SampleTime, zone)!.Days!;
ModelTokenPoint[] moreTokens = [.. tokens, new(firstHour, "fixture", new(Input: 100))];
var later = LimitAnalysis.Analyze(newest, [first], moreTokens, newest.SampleTime, zone)!.Days!;
var remainingDays = (first.ResetsAt!.Value - day).TotalDays;
foreach (var days in new[] { initial, later })
{
Assert.Equal(first.UsedPercent, 100 - days.TodayBudget!.Value * remainingDays, 8);
Assert.Equal(80 / remainingDays, days.TodayBudget.Value, 8);
Assert.Equal(80 / remainingDays, days.LaterBudget!.Value, 8);
Assert.Equal(UseOrigin.Estimated, days.BudgetOrigin);
}
Assert.Equal(initial.TodayBudget, later.TodayBudget);
Assert.Equal(initial.LaterBudget, later.LaterBudget);
Assert.Equal(initial.Current.Select(d => d.Budget), later.Current.Select(d => d.Budget));
}
[Fact] public void NoWholeHourTokensBeforeFirstSampleLeavesBudgetUnknown()
{
var day = CalendarDays.Start(Start.AddDays(3), Zone);
var first = Week(day.AddHours(2).AddMinutes(5), 20);
var newest = Week(day.AddHours(2).AddMinutes(30), 22);
ModelTokenPoint[] tokens = [new(day.AddHours(2), "fixture", new(Input: 100))];
var days = LimitAnalysis.Analyze(newest, [first], tokens, newest.SampleTime, Zone)!.Days!;
Assert.NotNull(days.Today);
Assert.Null(days.TodayBudget); Assert.Null(days.LaterBudget); Assert.Null(days.BudgetOrigin);
Assert.All(days.Current, d => { Assert.Null(d.Budget); Assert.Null(d.BudgetOrigin); });
}
[Fact] public void FirstSampleWithoutTokensCannotCalibrateABudgetFromLaterTokens()
{
var day = CalendarDays.Start(Start.AddDays(3), Zone);
var first = Week(day.AddHours(2), 20);
var newest = Week(day.AddHours(12), 22);
ModelTokenPoint[] tokens = [new(day.AddHours(3), "fixture", new(Input: 100))];
var days = LimitAnalysis.Analyze(newest, [first], tokens, newest.SampleTime, Zone)!.Days!;
Assert.NotNull(days.Today);
Assert.Null(days.TodayBudget); Assert.Null(days.LaterBudget); Assert.Null(days.BudgetOrigin);
Assert.All(days.Current, d => { Assert.Null(d.Budget); Assert.Null(d.BudgetOrigin); });
}
[Theory]
[InlineData(-1)]
[InlineData(0)]
public void MeasuredBaselineWinsOverFirstSampleTokenCalibration(int minutes)
{
var day = CalendarDays.Start(Start.AddDays(3), Zone);
var baseline = Week(day.AddMinutes(minutes), 25);
var first = Week(day.AddHours(2), 26);
var newest = Week(day.AddHours(12), 30);
ModelTokenPoint[] tokens = [new(day.AddHours(-1), "fixture", new(Input: 100)), new(day.AddHours(1), "fixture", new(Input: 100))];
var days = LimitAnalysis.Analyze(newest, [first, baseline, baseline with { SampleTime = day.AddHours(-1), UsedPercent = 20 }],
tokens, newest.SampleTime, Zone)!.Days!;
var expected = 75 / (newest.ResetsAt!.Value - day).TotalDays;
Assert.Equal(expected, days.TodayBudget!.Value, 8);
Assert.Equal(expected, days.LaterBudget!.Value, 8);
Assert.Equal(UseOrigin.Measured, days.BudgetOrigin);
Assert.Equal(UseOrigin.Measured, days.TodayOrigin);
Assert.Equal(5, days.Today);
}
[Fact] public void LastDayHasOnlyItsRemainingBudget()
{
var now = Start.AddDays(7).AddHours(-2);
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));
}
}
@@ -8,7 +8,7 @@ public class EarlyForecastTests
private static LimitWindow Week(double used = 39) => new(Provider.Codex, "primary", "Week", used, 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"); 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); var window = Week(); var pace = Pace.Calculate(window, Now);
Assert.Equal(PaceState.Ahead, pace.State); Assert.Equal(PaceState.Ahead, pace.State);
@@ -48,7 +48,7 @@ public class EarlyForecastTests
[InlineData(40, false)] [InlineData(40, false)]
public void AllForecastsFollowConfiguredThreshold(double threshold, bool eligible) 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.State == PaceState.Ahead);
Assert.Equal(eligible, Pace.CanForecast(window, Now, threshold)); Assert.Equal(eligible, Pace.CanForecast(window, Now, threshold));
Assert.Equal(eligible, pace.Projection is not null); 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)); 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); 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 { Length = null }));
Assert.Null(Pace.ForecastStartsAt(window with { ResetsAt = null })); Assert.Null(Pace.ForecastStartsAt(window with { ResetsAt = null }));
Assert.Null(Pace.ForecastStartsAt(window with { Length = TimeSpan.Zero })); Assert.Null(Pace.ForecastStartsAt(window with { Length = TimeSpan.Zero }));
@@ -126,7 +126,7 @@ public sealed class LimitAnalysisTests
{ {
var w = Window(); var w = Window();
var days = LimitAnalysis.Days(w, [w with { SampleTime = Now.AddHours(-14), UsedPercent = 51 }], Now, TimeZoneInfo.Utc)!; 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.IsFuture && d.Used is null);
Assert.Contains(days.Current, d => d.Start == Now.AddHours(-36) && 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); Assert.Null(LimitAnalysis.Days(w, [], Now, TimeZoneInfo.Utc)!.Today);
@@ -134,10 +134,10 @@ public sealed class TokenEstimateTests
[Theory] [Theory]
[InlineData(5)] [InlineData(5)]
[InlineData(168)] [InlineData(168)]
public void ForecastsBeginAtExactlyTenPercentWithoutChangingState(int hours) public void ForecastsBeginAtExactlyTwoPercentWithoutChangingState(int hours)
{ {
var start = Start; var length = TimeSpan.FromHours(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 before = atThreshold.AddTicks(-1);
var window = Window with { ResetsAt = start + length, Length = length, SampleTime = before, UsedPercent = 11 }; var window = Window with { ResetsAt = start + length, Length = length, SampleTime = before, UsedPercent = 11 };
Assert.Equal(PaceState.OnTrack, Pace.Calculate(window, before).State); Assert.Equal(PaceState.OnTrack, Pace.Calculate(window, before).State);
@@ -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;
}
}