app: show the reset history of each long limit window #16

Merged
schmidt.florian merged 16 commits from 14-reset-history into master 2026-10-18 11:12:40 +02:00
22 changed files with 422 additions and 66 deletions
Showing only changes of commit 941a597680 - Show all commits
+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`;
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;
+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 = [];
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()
{
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<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)));
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);
}
}
+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") };
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));
+2
View File
@@ -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";
+34 -22
View File
@@ -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()
{
+2
View File
@@ -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}"));
}
+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.
- 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.
+5 -4
View File
@@ -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<TokenBucket> Range(Provider provider, DateTimeOffset from, DateTimeOffset to) =>
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,
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<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>
public static partial class LimitAnalysis
+41
View File
@@ -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<LimitWindow> 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);
}
}
+1 -2
View File
@@ -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);
+2 -2
View File
@@ -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));
+5 -2
View File
@@ -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);
+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 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
{
// Keep this initializer for omitted properties in source-generated JSON (D9).
+58 -1
View File
@@ -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<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.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 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<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");
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)]
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();
+18
View File
@@ -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"));
@@ -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));
}
}
@@ -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 }));
@@ -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);
@@ -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);
@@ -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;
}
}