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

The developer asked for a detailed breakdown of every reset (feedback of
2026-10-18). Limits do not only reset at the end of their week: most Codex
weeks in the local history ended early.

- Core: a limit's samples form a window series (provider, limit name and
  length), so the history follows Codex's week across slots (D7). Instance
  spans are built once. One backward walk gives each instance, real or
  inferred, the start of the instance after it. The hour that holds a
  boundary goes to the instance that starts in it, or else to the one that
  ends in it (#9). A stale sample that would put its instance after a later
  one is ignored. The reset history lists the real instances with their
  figures, totals and early-reset hours (D12). API value uses a dated list
  price table; unknown models stay unpriced (D13).
- App: a Resets section per long window with totals, a timeline of
  burn-ups side by side with skipped time in lanes below, early resets by
  hour and weekday, and a sortable table (D8). The reset tooltip lists
  every model with its tokens and API value. Tall tooltips open beside the
  pointer, and Fluent's 320 px tooltip cap no longer wraps data values.
- Docs: D12 and D13 are new; D7 and D8 cover window series, boundary
  hours and the Resets section.

Closes #14
Closes #9
This commit was merged in pull request #16.
This commit is contained in:
2026-10-18 11:12:38 +02:00
parent 0a08b508a2
commit 82fece85f5
29 changed files with 1570 additions and 137 deletions
@@ -434,6 +434,7 @@ public sealed class HeadlessTests
popupClock.Fire(); Dispatcher.UIThread.RunJobs();
Assert.False(first.IsVisible); Assert.False(second.IsVisible);
Assert.All(popupClock.Timers, timer => Assert.True(timer.Disposed));
ResetViews.Verify((window, name) => Save(window, name));
completion.SetResult();
void SaveThemes(Window window, string stem)
{
+171
View File
@@ -0,0 +1,171 @@
using System.Globalization;
using FinalToken.Core;
using Xunit;
namespace FinalToken.App.Tests;
public sealed class ResetTests
{
[Fact] public void HistoryQueriesOnlyLongWindowsAndFollowsProviderAndRange()
{
var fixture = ResetFixture.Create();
var all = PanelViewModel.QueryHistory(fixture.Store, fixture.Snapshot, HistoryRange.All, null, fixture.Now);
Assert.Equal(3, all.Resets.Count);
Assert.All(all.Resets, r => Assert.True(r.Window.Length > TimeSpan.FromDays(1)));
var filtered = PanelViewModel.QueryHistory(fixture.Store, fixture.Snapshot, HistoryRange.All, Provider.Codex, fixture.Now);
Assert.Equal(2, filtered.Resets.Count); Assert.All(filtered.Resets, r => Assert.Equal(Provider.Codex, r.Window.Provider));
var recent = PanelViewModel.QueryHistory(fixture.Store, fixture.Snapshot, HistoryRange.Hours24, Provider.Codex, fixture.Now);
var week = recent.Resets.Single(r => r.Window.Id == "codex:primary");
Assert.True(week.Instances.Count < filtered.Resets[0].Instances.Count);
Assert.Contains(week.Instances, r => r.Start < fixture.Now.AddHours(-24) && r.End > fixture.Now.AddHours(-24));
Assert.Equal(10, filtered.Resets[0].Instances.Count);
}
[Fact] public void BurnUpQueriesReadTheSeriesAcrossCodexSlotsAndExcludeShortWindows()
{
var fixture = ResetFixture.Create();
var history = PanelViewModel.QueryHistory(fixture.Store, fixture.Snapshot, HistoryRange.All, Provider.Codex, fixture.Now);
var week = history.Limits.Single(l => l.Window!.Window.Id == "codex:primary" && l.Window.Window.Length > TimeSpan.FromDays(1));
Assert.DoesNotContain(week.Values, v => v.Value == 99);
Assert.True(week.Values.Count > 10);
Assert.Equal(8, week.Analysis!.Past.Count);
}
[Theory]
[InlineData("de-DE", "≈ 4,5 limits", "≈ 94,1 %")]
[InlineData("en-US", "≈ 4.5 limits", "≈ 94.1 %")]
public void ResetFiguresFollowTheUsersCultureExceptUsd(string culture, string limits, string percent)
{
var previous = CultureInfo.CurrentCulture;
try
{
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture);
Assert.Equal("≈ $1,234", Display.Money(1234)); Assert.Equal("≈ $99.25", Display.Money(99.25m));
Assert.Equal("Unpriced", Display.Money(null)); Assert.Equal(limits, Display.Limits(450));
Assert.Equal(percent, Display.ResetPercent(94.1, UseOrigin.Estimated));
Assert.Equal(percent[2..], Display.ResetPercent(94.1, UseOrigin.Measured));
}
finally { CultureInfo.CurrentCulture = previous; }
}
[Fact] public void ResetDurationsCannotWrapInsideTheFigure()
{
Assert.Equal("0\u00a0min", Display.ResetDuration(TimeSpan.Zero));
Assert.Equal("39\u00a0d\u00a00\u00a0h", Display.ResetDuration(TimeSpan.FromDays(39)));
Assert.Equal("≈\u00a015,1\u00a0M\u00a0tokens", Display.ResetFigure("≈ 15,1 M tokens"));
}
[Fact] public void OverlappingSkippedSpansGetSeparateLanesInTimeOrder()
{
var fixture = ResetFixture.Overlapping();
var history = fixture.History.Resets[0];
var layout = ResetTimeline.CalculateLayout(history, fixture.Now);
Assert.Equal(5, history.Totals.Early);
Assert.True(history.Instances.Max(r => r.Start) - history.Instances.Min(r => r.Start) < TimeSpan.FromDays(10));
Assert.Equal(5, layout.LaneCount);
Assert.Equal([0, 1, 2, 3, 4], layout.Skipped.Select(s => s.Lane));
Assert.Equal(history.Instances.Where(r => r.Early).OrderBy(r => r.End), layout.Skipped.Select(s => s.Instance));
}
[Fact] public void SkippedSpansReuseTheFirstLaneAsSoonAsItIsFree()
{
var fixture = ResetFixture.Create();
var layout = ResetTimeline.CalculateLayout(fixture.History.Resets[0], fixture.Now);
Assert.Equal(4, layout.LaneCount);
Assert.Equal([0, 1, 0, 1, 2, 3, 0], layout.Skipped.Select(s => s.Lane));
Assert.Equal(layout.Skipped[2].Instance.Reset, layout.Skipped[^1].Instance.End);
foreach (var lane in layout.Skipped.GroupBy(s => s.Lane))
{
var rows = lane.Select(s => s.Instance).ToArray();
for (var i = 1; i < rows.Length; i++) Assert.True(rows[i - 1].Reset <= rows[i].End);
}
}
[Fact] public void TimelineEndsAtNowOrTheLastEarlyNominalResetAndExcludesTheRunningReset()
{
var running = ResetFixture.RunningOnly();
var history = running.History.Resets[0];
var layout = ResetTimeline.CalculateLayout(history, running.Now);
Assert.Equal(history.Instances[0].Start, layout.From);
Assert.Equal(running.Now, layout.To); Assert.Empty(layout.Skipped);
Assert.True(layout.To < history.Instances[0].Reset);
var early = ResetFixture.Overlapping();
history = early.History.Resets[0];
layout = ResetTimeline.CalculateLayout(history, early.Now);
Assert.Equal(history.Instances.Min(r => r.Start), layout.From);
Assert.Equal(history.Instances.Where(r => r.Early).Max(r => r.Reset), layout.To);
Assert.True(layout.To > early.Now); Assert.True(layout.To < history.Instances[0].Reset);
var later = early.Now.AddDays(30);
Assert.Equal(later, ResetTimeline.CalculateLayout(history, later).To);
var onTime = ResetFixture.OnTimeOnly();
history = onTime.History.Resets[0];
history = history with { Instances = history.Instances.Where(r => !r.Running).ToArray() };
Assert.Equal(onTime.Now, ResetTimeline.CalculateLayout(history, onTime.Now).To);
}
[Fact] public void EveryInstanceColumnSortsByItsUnderlyingValue()
{
var fixture = ResetFixture.Create();
var rows = fixture.History.Resets[0].Instances;
Assert.Equal(rows.OrderBy(r => r.Start), ResetTable.SortRows(rows, ResetColumn.Start, false));
Assert.Equal(rows.Max(r => r.Final.Used), ResetTable.SortRows(rows, ResetColumn.Final, true)[0].Final.Used);
Assert.Equal(rows.Max(r => r.Skipped), ResetTable.SortRows(rows, ResetColumn.Reset, true)[0].Skipped);
Assert.Equal(rows.Max(r => r.Duration), ResetTable.SortRows(rows, ResetColumn.Lasted, true)[0].Duration);
foreach (var column in Enum.GetValues<ResetColumn>())
{
var ascending = ResetTable.SortRows(rows, column, false); var descending = ResetTable.SortRows(rows, column, true);
Assert.Equal(rows.Count, ascending.Count); Assert.Equal(rows.Count, descending.Count);
}
}
}
internal sealed record ResetFixture(HistoryStore Store, Snapshot Snapshot, DateTimeOffset Now, HistoryView History)
{
public static ResetFixture Create()
=> Create([7, 1, 2, 7, 1, 2, 1, 1, 2]);
public static ResetFixture RunningOnly() => Create([]);
public static ResetFixture OnTimeOnly() => Create([7, 7]);
public static ResetFixture Overlapping() => Create([1, 1, 1, 1, 1]);
public static ResetFixture ManyModels()
{
var fixture = OnTimeOnly();
var start = fixture.History.Resets[0].Instances[1].Start;
string[] models = ["gpt-6-sol", "gpt-6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-5.4-mini"];
for (var i = 0; i < models.Length; i++)
{
var count = 2_000_123 - i * 200_001;
fixture.Store.Add(new(Provider.Codex, start.AddHours(2), models[i], "Fixture", new(Input: count, Total: count), "extra" + i));
}
return fixture with { History = PanelViewModel.QueryHistory(fixture.Store, fixture.Snapshot, HistoryRange.All, null, fixture.Now) };
}
private static ResetFixture Create(int[] durations)
{
var start = new DateTimeOffset(2026, 9, 12, 6, 0, 0, TimeSpan.Zero);
var now = start.AddDays(durations.Sum()).AddHours(12);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), "finaltoken-resets", Guid.NewGuid().ToString("N")), new(), new FixedClock(now));
var currentStart = start; LimitWindow current = null!;
for (var i = 0; i <= durations.Length; i++)
{
var used = i == 2 ? 100 : i == 4 ? 4 : 20 + i * 7;
current = new(Provider.Codex, i < 4 ? "codex:secondary" : "codex:primary", "Week", used,
currentStart.AddDays(7), TimeSpan.FromDays(7), currentStart.AddHours(6), "fixture");
store.AddLimits([current with { SampleTime = currentStart.AddHours(1), UsedPercent = used / 2.0 }, current]);
store.AddLimits([current with { Id = "codex_bengalfox:secondary", Label = "Week (Bengalfox)", UsedPercent = 0 }]);
store.Add(new(Provider.Codex, currentStart.AddMinutes(30), "gpt-6.1-sol", "Fixture", new(10_000_000, 4_000_000, 0, 2_000_000, 300_000, 12_000_000), "a" + i));
store.Add(new(Provider.Codex, currentStart.AddHours(2), "gpt-6-astra", "Fixture", new(1_000_000, 200_000, 0, 2_000_000, 300_000, 3_000_000), "b" + i));
store.Add(new(Provider.Codex, currentStart.AddHours(2), "codex-auto-review", "Fixture", new(Input: 100_000, Total: 100_000), "c" + i));
if (i < durations.Length) currentStart = currentStart.AddDays(durations[i]);
}
var shortWindow = current with { Id = "codex:primary", Length = TimeSpan.FromHours(5), ResetsAt = now.AddHours(2), UsedPercent = 99, SampleTime = now.AddMinutes(-1), Label = "Session" };
store.AddLimits([shortWindow]);
var claude = current with { Provider = Provider.Claude, Id = "week", Label = "Week (all models)" };
var alternate = current with { Id = "codex_bengalfox:primary", Label = "Week (Bengalfox)", UsedPercent = 0 };
var snapshot = FakeData.Snapshot(now) with { Providers =
[new(Provider.Codex, ProviderStatus.Available, null, [new(current, Pace.Calculate(current, now)), new(alternate, Pace.Calculate(alternate, now)),
new(shortWindow, Pace.Calculate(shortWindow, now))], new(), new(), new()),
new(Provider.Claude, ProviderStatus.Available, null, [new(claude, Pace.Calculate(claude, now))], new(), null, new())] };
return new(store, snapshot, now, PanelViewModel.QueryHistory(store, snapshot, HistoryRange.All, null, now));
}
}
+214
View File
@@ -0,0 +1,214 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Headless;
using Avalonia.Interactivity;
using Avalonia.Styling;
using Avalonia.Threading;
using Avalonia.VisualTree;
using FinalToken.Core;
using Xunit;
namespace FinalToken.App.Tests;
internal static class ResetViews
{
public static void Verify(Action<Window, string> save)
{
VerifyEveryModelsTokensAndValue(save);
VerifyScenarios(save);
var fixture = ResetFixture.Create();
var clock = new FixedClock(fixture.Now);
var model = new PanelViewModel { Snapshot = fixture.Snapshot, History = fixture.History, Range = HistoryRange.All };
var panel = new PanelWindow(model, () => { }, () => { }, () => { }, () => { }, clock);
panel.Show(); Dispatcher.UIThread.RunJobs();
var headings = panel.GetVisualDescendants().OfType<TextBlock>().Where(t => t.FontSize == 20).Select(t => t.Text).ToArray();
Assert.True(Array.IndexOf(headings, "Window charts") < Array.IndexOf(headings, "Resets"));
Assert.True(Array.IndexOf(headings, "Resets") < Array.IndexOf(headings, "Breakdown"));
var selector = panel.GetVisualDescendants().OfType<ComboBox>().Single(c => c.Name == "ResetWindowSelector");
selector.SelectedIndex = 1;
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Codex · Week (Bengalfox)");
model.Snapshot = model.Snapshot with { MadeAt = fixture.Now.AddMinutes(-1) }; Dispatcher.UIThread.RunJobs();
Assert.Equal(1, panel.GetVisualDescendants().OfType<ComboBox>().Single(c => c.Name == "ResetWindowSelector").SelectedIndex);
panel.GetVisualDescendants().OfType<ComboBox>().Single(c => c.Name == "ResetWindowSelector").SelectedIndex = 0;
Dispatcher.UIThread.RunJobs();
using (panel.CaptureRenderedFrame()) { }
var card = panel.GetVisualDescendants().OfType<ResetCard>().First();
var table = card.GetVisualDescendants().OfType<ResetTable>().Single();
Grid Rows()
{
Dispatcher.UIThread.RunJobs();
using (panel.CaptureRenderedFrame()) { }
return table.GetVisualDescendants().OfType<Grid>().Single(g => g.Name == "ResetRows");
}
void Click(string name)
{
Dispatcher.UIThread.RunJobs();
using (panel.CaptureRenderedFrame()) { }
table.GetVisualDescendants().OfType<Button>().Single(b => b.Name == name).RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
Dispatcher.UIThread.RunJobs();
using (panel.CaptureRenderedFrame()) { }
}
Assert.Equal(9, Rows().RowDefinitions.Count); // Header plus eight rows.
var cells = Rows().Children.OfType<TextBlock>().ToArray();
Assert.All(cells, text => Assert.IsType<DataTooltip>(ToolTip.GetTip(text)));
Assert.Contains(cells, t => t.Text == "Running");
Assert.Contains(cells, t => t.Text?.StartsWith("Early by ", StringComparison.Ordinal) == true);
Assert.Contains(cells, t => t.Text?.Contains("100 %", StringComparison.Ordinal) == true);
Click("ResetSortFinal");
Assert.StartsWith("≈ 100 %", Rows().Children.OfType<TextBlock>().Single(t => Grid.GetRow(t) == 1 && Grid.GetColumn(t) == 4).Text);
Click("ResetExpand");
Assert.Equal(11, Rows().RowDefinitions.Count);
Assert.Contains(Rows().Children.OfType<TextBlock>(), t => t.Text == "On time");
model.Snapshot = model.Snapshot with { MadeAt = fixture.Now }; Dispatcher.UIThread.RunJobs();
table = panel.GetVisualDescendants().OfType<ResetCard>().First().GetVisualDescendants().OfType<ResetTable>().Single();
Assert.Equal(11, Rows().RowDefinitions.Count);
Assert.Contains(table.GetVisualDescendants().OfType<Button>(), b => b.Content as string == "Final (peak) ↓");
Click("ResetExpand");
Click("ResetSortStart");
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
panel.RequestedThemeVariant = theme; Dispatcher.UIThread.RunJobs();
var viewport = panel.GetVisualDescendants().OfType<ScrollViewer>().First();
var heading = panel.GetVisualDescendants().OfType<TextBlock>().Single(t => t.Text == "Resets" && t.FontSize == 20);
viewport.Offset = new Vector(0, viewport.Offset.Y + heading.TranslatePoint(default, viewport)!.Value.Y - 16);
save(panel, $"resets-panel-{theme}.png");
}
panel.Close();
var history = fixture.History.Resets[0];
foreach (var width in new[] { 1280, 1500 })
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
var content = new ResetCard(history, new(ResetColumn.Start), clock);
var window = new Window { Width = width, Height = 1030, Content = new Border { Padding = new Thickness(24),
Child = Ui.Stack(Ui.Text("Resets", 20), Ui.Card(Ui.Stack(Ui.Text("Codex · Week", 15), content))) }, RequestedThemeVariant = theme };
Ui.Theme(window); window.Show();
save(window, $"resets-{width}-{theme}.png");
var timeline = content.GetVisualDescendants().OfType<ResetTimeline>().Single();
window.MouseMove(timeline.TranslatePoint(new Point(timeline.Bounds.Width / 2, 80), window)!.Value);
Assert.IsType<DataTooltip>(ToolTip.GetTip(timeline));
var histogram = content.GetVisualDescendants().OfType<ResetHistogram>().First();
window.MouseMove(histogram.TranslatePoint(new Point(40, 40), window)!.Value);
Assert.IsType<DataTooltip>(ToolTip.GetTip(histogram));
var tableTip = content.GetVisualDescendants().OfType<ResetTable>().Single().GetVisualDescendants().OfType<TextBlock>()
.Select(t => ToolTip.GetTip(t)).OfType<DataTooltip>().First();
Assert.Contains(tableTip.Rows, r => r.Label == "Unpriced tokens");
Assert.Contains(tableTip.Rows, r => r.Label == "Tokens per percent");
Assert.Contains(tableTip.Rows, r => r.Label == "Estimated figures");
var oldest = history.Instances[^1];
Assert.False(oldest.Early); Assert.False(oldest.Running);
window.Close();
}
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
var tip = DataTooltip.Reset(history.Instances[1], clock);
var window = new Window { Width = 580, Height = 1120, Content = new Border { Child = tip, Padding = new Thickness(16) }, RequestedThemeVariant = theme };
Ui.Theme(window); window.Show(); save(window, $"resets-tooltip-{theme}.png"); window.Close();
}
}
private static void VerifyEveryModelsTokensAndValue(Action<Window, string> save)
{
var fixture = ResetFixture.ManyModels();
var history = fixture.History.Resets[0];
var row = history.Instances[1];
Assert.False(row.Running); Assert.Equal(9, row.Models.Count);
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
var card = new ResetCard(history, new(ResetColumn.Start), new FixedClock(fixture.Now));
var window = new Window { Width = 1280, Height = 1030, RequestedThemeVariant = theme,
Content = new Border { Padding = new Thickness(24), Child = Ui.Card(Ui.Stack(Ui.Text("Codex · Week", 15), card)) } };
Ui.Theme(window); window.Show(); Dispatcher.UIThread.RunJobs();
using (window.CaptureRenderedFrame()) { }
var cell = card.GetVisualDescendants().OfType<Grid>().Single(g => g.Name == "ResetRows")
.Children.OfType<TextBlock>().Single(t => Grid.GetRow(t) == 2 && Grid.GetColumn(t) == 0);
var tip = Assert.IsType<DataTooltip>(ToolTip.GetTip(cell));
foreach (var model in row.Models)
{
var detail = Assert.Single(tip.Rows, r => r.Label == model.Model);
Assert.Equal(DataTooltip.Count(model.Tokens.Total) + " · " + Display.Money(model.ApiValue), detail.Value);
}
Assert.Equal(row.Models.Select(m => m.Model), tip.Rows.Where(r => row.Models.Any(m => m.Model == r.Label)).Select(r => r.Label));
Assert.DoesNotContain(tip.Rows, r => r.Label == "Other models");
var pointer = cell.TranslatePoint(new Point(12, cell.Bounds.Height / 2), window)!.Value;
window.MouseMove(pointer); ToolTip.SetIsOpen(cell, true); Dispatcher.UIThread.RunJobs();
using (window.CaptureRenderedFrame()) { }
Assert.True(ToolTip.GetIsOpen(cell)); Assert.True(tip.Bounds.Width > 320);
var bounds = new PixelRect(tip.PointToScreen(default), PixelSize.FromSize(tip.Bounds.Size, 1));
Assert.False(bounds.Contains(window.PointToScreen(pointer)));
Assert.True(window.Screens.ScreenFromWindow(window)!.WorkingArea.Contains(bounds), $"tooltip {bounds}");
save(window, $"resets-many-models-hover-{theme}.png");
ToolTip.SetIsOpen(cell, false); window.Close();
}
}
private static void VerifyScenarios(Action<Window, string> save)
{
foreach (var (name, fixture) in new[] { ("running-only", ResetFixture.RunningOnly()),
("on-time", ResetFixture.OnTimeOnly()), ("overlapping", ResetFixture.Overlapping()) })
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
var history = fixture.History.Resets[0];
var card = new ResetCard(history, new(ResetColumn.Start), new FixedClock(fixture.Now));
var window = new Window { Width = 1280, Height = 950, RequestedThemeVariant = theme,
Content = new Border { Padding = new Thickness(24), Child = Ui.Card(Ui.Stack(Ui.Text("Codex · Week", 15), card)) } };
Ui.Theme(window); window.Show(); Dispatcher.UIThread.RunJobs();
using (window.CaptureRenderedFrame()) { }
save(window, $"resets-{name}-{theme}.png");
TextBlock[] TileBlocks(string label) => card.GetVisualDescendants().OfType<StackPanel>()
.Select(s => s.Children.OfType<TextBlock>().ToArray())
.Single(blocks => blocks.Length == 3 && blocks[0].Text == label);
string[] Tile(string label) => TileBlocks(label).Select(t => t.Text!).ToArray();
Assert.Equal(history.Totals.Finished.ToString(), Tile("Resets")[1]);
var caption = history.Totals.Finished == 0 ? "none yet" : history.Totals.Early + "\u00a0early";
Assert.Equal(caption + " · 1\u00a0running", Tile("Resets")[2]);
var texts = card.GetVisualDescendants().OfType<TextBlock>().Select(t => t.Text).ToArray();
Assert.Contains("early resets " + history.Totals.Early + " of " + history.Totals.Finished,
texts.Single(t => t?.StartsWith("Median instance ", StringComparison.Ordinal) == true || t?.StartsWith("No finished instance yet", StringComparison.Ordinal) == true));
if (history.Totals.Finished == 0)
{
Assert.Equal(["Unused", "—", "no finished instance"], Tile("Unused"));
Assert.Equal(Ui.Colour("Muted", theme == ThemeVariant.Dark).ToString(), TileBlocks("Unused")[1].Foreground?.ToString());
Assert.Contains(texts, text => text?.StartsWith("No finished instance yet", StringComparison.Ordinal) == true);
}
if (history.Totals.Early == 0)
{
Assert.Equal(["Gift", "—", "no early reset"], Tile("Gift"));
Assert.Equal(Ui.Colour("Muted", theme == ThemeVariant.Dark).ToString(), TileBlocks("Gift")[1].Foreground?.ToString());
Assert.Contains("No early resets in this range", texts);
Assert.Empty(card.GetVisualDescendants().OfType<ResetHistogram>());
}
else
{
Assert.Equal(2, card.GetVisualDescendants().OfType<ResetHistogram>().Count());
Assert.Contains(Display.ResetDuration(history.Totals.Skipped) + " skipped", Tile("Gift")[2]);
Assert.DoesNotContain("≈ ", Tile("Gift")[2]);
var timeline = card.GetVisualDescendants().OfType<ResetTimeline>().Single();
var layout = ResetTimeline.CalculateLayout(history, fixture.Now);
foreach (var skipped in layout.Skipped)
{
ToolTip.SetIsOpen(timeline, false);
window.MouseMove(new Point(4, 4)); Dispatcher.UIThread.RunJobs();
var mid = skipped.Instance.End + skipped.Instance.Skipped / 2;
var x = 42 + (mid - layout.From).TotalSeconds / (layout.To - layout.From).TotalSeconds * (timeline.Bounds.Width - 58);
var pointer = timeline.TranslatePoint(new Point(x, 181 + skipped.Lane * 10), window)!.Value;
window.MouseMove(pointer);
Assert.True(ToolTip.GetTip(timeline) is DataTooltip, $"{name} {theme}, lane {skipped.Lane}, timeline {timeline.Bounds}");
var tooltip = Assert.IsType<DataTooltip>(ToolTip.GetTip(timeline));
// The tall tooltip opens beside the pointer; over it, it would take the pointer from the timeline.
Assert.True(ToolTip.GetIsOpen(timeline));
Assert.True(tooltip.Bounds.Width > 320, $"tooltip width {tooltip.Bounds.Width}");
var tipBounds = new PixelRect(tooltip.PointToScreen(default), PixelSize.FromSize(tooltip.Bounds.Size, 1));
Assert.False(tipBounds.Contains(window.PointToScreen(pointer)), $"{name} {theme}, lane {skipped.Lane}, tooltip {tipBounds}, pointer {window.PointToScreen(pointer)}, placement {ToolTip.GetPlacement(timeline)}");
if (skipped == layout.Skipped[0] || skipped == layout.Skipped[^1]) save(window, $"resets-{name}-hover-lane{skipped.Lane}-{theme}.png");
Assert.Contains(tooltip.Rows, r => r.Label == "End" && r.Value == Display.Projection(skipped.Instance.End, new FixedClock(fixture.Now)));
}
ToolTip.SetIsOpen(timeline, false);
window.MouseMove(timeline.TranslatePoint(new Point(timeline.Bounds.Width - 10, 80), window)!.Value);
Assert.Null(ToolTip.GetTip(timeline));
window.MouseMove(new Point(4, 4));
}
window.Close();
}
}
}
@@ -99,6 +99,17 @@ public sealed class LimitInstanceTests
AssertNoOverlap(result);
}
[Fact] public void AdjacentInferredWeeksAssignTheBoundaryHourOnlyToTheStartingWeek()
{
var start = Day.AddMinutes(13);
var current = Window(start, TimeSpan.FromDays(7), start.AddHours(2), 20);
var result = Analyze(current, [], [Token(Day, 100), Token(Day.AddDays(-7), 100)], current.SampleTime);
var past = Assert.Single(result.Past);
Assert.Equal(start.AddDays(-7), past.Start); Assert.Equal(20, past.Peak);
Assert.DoesNotContain(result.Past, p => p.Start == start.AddDays(-14));
AssertNoOverlap(result);
}
[Theory]
[InlineData(5)]
[InlineData(24)]
@@ -0,0 +1,32 @@
using Xunit;
namespace FinalToken.Core.Tests;
public sealed class ResetBoundaryTests
{
private static readonly DateTimeOffset Day = new(2026, 10, 15, 0, 0, 0, TimeSpan.Zero);
private static LimitWindow Window(DateTimeOffset start, DateTimeOffset sample, double used) =>
new(Provider.Codex, "codex:primary", "Session", used, start.AddHours(5), TimeSpan.FromHours(5), sample, "fixture");
[Fact] public void ResetHourBeforeAGapBelongsToTheEndingInstance()
{
var previous = Window(Day.AddHours(10).AddMinutes(13), Day.AddHours(14), 50);
var current = Window(Day.AddHours(20), Day.AddHours(21), 10);
ModelTokenPoint[] tokens = [new(Day.AddHours(10), "model", new(Input: 100, Total: 100)),
new(Day.AddHours(15), "model", new(Input: 50, Total: 50))];
var past = Assert.Single(LimitAnalysis.Analyze(current, [previous], tokens, current.SampleTime, TimeZoneInfo.Utc)!.Past);
Assert.Equal(75, past.Points.Last().Used);
Assert.Equal(UseOrigin.Estimated, past.Points.Last().Origin);
Assert.Equal(previous.ResetsAt, past.Points.Last().Time);
}
[Fact] public void EarlierSampleCannotPutAnInstanceAfterTheCurrentWindow()
{
var current = Window(Day.AddHours(10), Day.AddHours(12), 10);
var stale = Window(Day.AddHours(11), Day.AddHours(11.5), 90);
var result = LimitAnalysis.Analyze(current, [stale], [], current.SampleTime, TimeZoneInfo.Utc)!;
Assert.Equal(current.ResetsAt, result.Current.End);
Assert.Equal(10, result.Current.Peak);
Assert.Empty(result.Past);
}
}
@@ -0,0 +1,232 @@
using Xunit;
namespace FinalToken.Core.Tests;
public sealed class ResetHistoryTests
{
private static readonly DateTimeOffset Day = new(2026, 10, 1, 0, 0, 0, TimeSpan.Zero);
private static readonly TimeSpan Week = TimeSpan.FromDays(7);
private static LimitWindow Window(DateTimeOffset start, double used = 50, double sampleHour = 1) =>
new(Provider.Codex, "codex:primary", "Week", used, start + Week, Week, start.AddHours(sampleHour), "fixture");
private static ModelTokenPoint Token(DateTimeOffset time, long input = 1_000_000, string model = "gpt-6.1-sol") =>
new(time, model, new(Input: input, Total: input));
private static ResetHistory History(LimitWindow current, LimitWindow[] samples, ModelTokenPoint[] tokens,
DateTimeOffset? from = null, DateTimeOffset? now = null, TimeZoneInfo? zone = null) =>
LimitAnalysis.Resets(current, samples, tokens, from ?? DateTimeOffset.MinValue, now ?? current.SampleTime, zone ?? TimeZoneInfo.Utc);
[Fact] public void SeriesMergesCodexSlotsButSeparatesLengthsNamesAndProviders()
{
var week = Window(Day);
Assert.True(LimitAnalysis.SameInstance(week, week with { Id = "codex:secondary" }));
Assert.False(LimitAnalysis.SameInstance(week, week with { Length = TimeSpan.FromHours(5) }));
Assert.False(LimitAnalysis.SameInstance(week, week with { Id = "codex_bengalfox:primary" }));
Assert.False(LimitAnalysis.SameInstance(week, week with { Provider = Provider.Claude }));
var previous = Window(Day - Week, 30) with { Id = "codex:secondary" };
var wrong = previous with { Id = week.Id, Length = TimeSpan.FromHours(5), UsedPercent = 99 };
var other = previous with { Id = "codex_bengalfox:secondary", UsedPercent = 98 };
var analysis = LimitAnalysis.Analyze(week, [previous, wrong, other], [], week.SampleTime, TimeZoneInfo.Utc)!;
Assert.Equal(30, Assert.Single(analysis.Past).Peak);
Assert.Equal(30, History(week, [previous, wrong, other], []).Instances[1].Final.Used);
Assert.Null(LimitAnalysis.Recent(week, [week with { Length = TimeSpan.FromHours(5), UsedPercent = 0, SampleTime = week.SampleTime.AddHours(-4) }], week.SampleTime));
}
[Fact] public void StoreSeriesQueryKeepsTheOriginalIdQueryWorking()
{
using var directory = new TestDirectory();
var store = new HistoryStore(directory.Path, new());
var week = Window(Day);
var moved = week with { Id = "codex:secondary", SampleTime = week.SampleTime.AddHours(-1) };
var shortWindow = week with { Length = TimeSpan.FromHours(5) };
store.AddLimits([moved, shortWindow, week]);
Assert.Equal(3, store.LimitSamples(Provider.Codex, Day, Day.AddDays(1)).Count);
Assert.Equal(2, store.LimitSamples(week, Day, Day.AddDays(1)).Count);
Assert.Equal(2, store.LimitSamples(Provider.Codex, week.Id, Day, Day.AddDays(1)).Count);
}
[Theory]
[InlineData("claude-haiku-4-5")]
[InlineData("claude-haiku-4-5-20251001")]
public void PriceMatchesExactAndDatedModel(string model) => Assert.Equal(1, ApiPrices.Find(Provider.Claude, model)!.Input);
[Theory]
[InlineData("codex-auto-review")]
[InlineData("gpt-6.1-sol-latest")]
[InlineData("gpt-6.1-sol-20261301")]
[InlineData("gpt-6.1-sol-20261018-extra")]
[InlineData(null)]
public void UnknownModelHasNoValue(string? model) => Assert.Null(ApiPrices.Value(Provider.Codex, model, new(Input: 100)));
[Fact] public void ProviderValuesDoNotDoubleCountTokenSubsets()
{
var counts = new TokenCounts(1_000_000, 400_000, 200_000, 100_000, 80_000);
Assert.Equal(17.6m, ApiPrices.Value(Provider.Claude, "claude-fable-5-1", counts));
Assert.Equal(2.24m, ApiPrices.Value(Provider.Codex, "gpt-6.1-sol", counts));
Assert.Null(ApiPrices.Find(Provider.Claude, "gpt-6.1-sol"));
}
[Fact] public void OnTimeEarlyAndRunningInstancesHaveOwnValuesAndTotals()
{
var first = Window(Day, 40);
var second = Window(Day + Week, 50);
var current = Window(Day.AddDays(9), 20);
var history = History(current, [first, second], [Token(Day), Token(second.ResetsAt!.Value - Week), Token(Day.AddDays(9))]);
Assert.Equal(3, history.Instances.Count);
var running = history.Instances[0]; var early = history.Instances[1]; var onTime = history.Instances[2];
Assert.True(running.Running); Assert.Null(running.Unused); Assert.Null(running.Gift);
Assert.Equal(TimeSpan.FromHours(1), running.Duration); Assert.Equal(current.SampleTime, running.End);
Assert.False(onTime.Early); Assert.Equal(Week, onTime.Duration); Assert.Equal(60, onTime.Unused!.Percent);
Assert.True(early.Early); Assert.Equal(TimeSpan.FromDays(2), early.Duration); Assert.Equal(TimeSpan.FromDays(5), early.Skipped);
Assert.Equal(100d * 5 / 7, early.Gift!.Percent, 8); Assert.Equal(50, early.Unused!.Percent);
Assert.Equal(20_000, early.ValuePerPercent!.Tokens); Assert.Equal(.04m, early.ValuePerPercent.ApiValue);
Assert.Equal(PercentBasis.OwnInstance, early.ValuePerPercent.Basis);
Assert.Equal(1_000_000, early.Unused.Tokens); Assert.Equal(2m, early.Unused.ApiValue);
Assert.Equal(3, history.Totals.Instances); Assert.Equal(2, history.Totals.Finished); Assert.Equal(1, history.Totals.Early);
Assert.Equal(3_000_000, history.Totals.Tokens.Total); Assert.Equal(6m, history.Totals.ApiValue);
Assert.Equal(110, history.Totals.Unused.Percent); Assert.Equal(TimeSpan.FromDays(4.5), history.MedianDuration);
Assert.Equal(TimeSpan.FromDays(5), history.Totals.Skipped);
}
[Fact] public void RunningInstanceHasNoFinishedDurationOrResetValues()
{
var history = History(Window(Day), [], []);
Assert.True(Assert.Single(history.Instances).Running);
Assert.Equal(0, history.Totals.Finished); Assert.Equal(0, history.Totals.Early);
Assert.Null(history.MedianDuration);
Assert.Null(history.Instances[0].Unused); Assert.Null(history.Instances[0].Gift);
Assert.All(history.EarlyByHour, count => Assert.Equal(0, count));
Assert.All(history.EarlyByWeekday, count => Assert.Equal(0, count));
}
[Fact] public void OnTimeFinishedInstancesHaveNoEarlyResetAndExcludeRunningDurationFromMedian()
{
var history = History(Window(Day + Week * 2), [Window(Day), Window(Day + Week)], []);
Assert.Equal(2, history.Totals.Finished); Assert.Equal(0, history.Totals.Early);
Assert.Equal(Week, history.MedianDuration);
Assert.All(history.Instances.Where(r => !r.Running), row => Assert.NotNull(row.Unused));
Assert.All(history.Instances, row => Assert.Null(row.Gift));
Assert.All(history.EarlyByHour, count => Assert.Equal(0, count));
Assert.All(history.EarlyByWeekday, count => Assert.Equal(0, count));
}
[Fact] public void LowUseUsesMedianOfQualifyingListedInstances()
{
var first = Window(Day, 50); var second = Window(Day + Week, 25); var current = Window(Day + Week * 2, 4);
var result = History(current, [first, second], [Token(Day), Token(Day + Week), Token(Day + Week * 2)]);
var rate = result.Instances[0].ValuePerPercent!;
Assert.Equal(30_000, rate.Tokens); Assert.Equal(.06m, rate.ApiValue); Assert.Equal(PercentBasis.SeriesMedian, rate.Basis);
var onlyLow = History(current, [first, second], [Token(Day + Week * 2)], from: current.ResetsAt!.Value - Week);
Assert.Null(Assert.Single(onlyLow.Instances).ValuePerPercent);
}
[Fact] public void NoQualifyingInstanceKeepsOnlyUnusedAndGiftPercent()
{
var old = Window(Day, 4); var current = Window(Day.AddDays(2), 0);
var row = History(current, [old], []).Instances[1];
Assert.Null(row.ValuePerPercent); Assert.Equal(96, row.Unused!.Percent);
Assert.Null(row.Unused.Tokens); Assert.Null(row.Unused.ApiValue); Assert.Null(row.Gift!.Tokens);
}
[Fact] public void ReachedLimitAndTimeAtLimitReuseTheBurnUpIncludingEstimates()
{
var old = Window(Day, 50); var current = Window(Day + Week, 20);
var tokens = new[] { Token(Day), Token(Day.AddHours(2), 2_000_000), Token(Day + Week) };
var row = History(current, [old], tokens).Instances[1];
var analysis = LimitAnalysis.Analyze(current, [old], tokens, current.SampleTime, TimeZoneInfo.Utc)!;
Assert.Equal(analysis.Past[0].Points, row.BurnUp.Points);
Assert.Equal(100, row.Peak); Assert.Equal(100, row.Final.Used); Assert.Equal(UseOrigin.Estimated, row.Final.Origin);
Assert.Equal(Day.AddHours(2.5), row.ReachedLimit);
Assert.Equal(Week - TimeSpan.FromHours(2.5), row.TimeAtLimit);
Assert.Equal(0, row.Unused!.Percent);
var measured = History(current, [old with { UsedPercent = 100 }], [Token(Day), Token(Day + Week)]).Instances[1];
Assert.Equal(old.SampleTime, measured.ReachedLimit); Assert.Equal(UseOrigin.Measured, measured.BurnUp.ReachedOrigin);
}
[Theory]
[InlineData(0, false)]
[InlineData(20, false)]
[InlineData(50, true)]
public void RealWeekKeepsItsEndHourOnlyWhenTheInferredSuccessorStartsInALaterHour(int gapMinutes, bool ownsEndHour)
{
var start = Day.AddMinutes(13);
var previous = Window(start);
var currentStart = start + Week * 2 + TimeSpan.FromMinutes(gapMinutes);
var current = Window(currentStart, 20, 2);
ModelTokenPoint[] tokens = [Token(Day, 100), Token(Day + Week, 50), Token(currentStart.AddMinutes(-currentStart.Minute), 100)];
var analysis = LimitAnalysis.Analyze(current, [previous], tokens, current.SampleTime, TimeZoneInfo.Utc)!;
var past = Assert.Single(analysis.Past, p => p.Start == start);
Assert.Equal(ownsEndHour ? 75 : 50, past.Points[^1].Used);
var history = History(current, [previous], tokens);
var row = Assert.Single(history.Instances, r => r.Start == start);
Assert.Equal(past.Points, row.BurnUp.Points);
Assert.Equal(ownsEndHour ? 150 : 100, row.Tokens.Total);
Assert.Equal(row.Tokens, Assert.Single(row.Models).Tokens);
Assert.Equal(previous.ResetsAt, row.End); Assert.False(row.Early);
Assert.Equal(2, history.Instances.Count);
}
[Fact] public void ResetHistoryUsesInferredSuccessorsBeyondTheEightPastChartInstances()
{
var start = Day.AddMinutes(13);
var previous = Window(start);
var current = Window(start + Week * 11, 20, 2);
ModelTokenPoint[] tokens = [Token(Day, 100), Token(Day + Week, 50), Token(Day + Week * 11, 100)];
var row = Assert.Single(History(current, [previous], tokens).Instances, r => r.Start == start);
Assert.Equal(100, row.Tokens.Total); Assert.Equal(50, row.Final.Used);
Assert.Equal(2, History(current, [previous], tokens).Instances.Count);
}
[Fact] public void FamilyFilterAndUnpricedModelsAreExplicit()
{
var current = Window(Day, 20) with { Provider = Provider.Claude, Id = "fable", Label = "Week (Fable)" };
var row = Assert.Single(History(current, [], [Token(Day, 100, "claude-fable-5"), Token(Day, 200, "claude-fable-new"),
Token(Day, 10_000, "claude-sonnet-5")]).Instances);
Assert.Equal(300, row.Tokens.Total); Assert.Equal(200, row.UnpricedTokens); Assert.Equal(.001m, row.ApiValue);
Assert.Equal(2, row.Models.Count);
var zero = Assert.Single(History(current with { UsedPercent = 0 }, [], [Token(Day, 100, "claude-sonnet-5")]).Instances);
Assert.Equal(0, zero.Tokens.Total); Assert.Null(zero.ApiValue); Assert.Null(zero.ValuePerPercent);
}
[Fact] public void RangeIncludesWholeOverlappingRealInstanceAndLeavesInferredOnesOut()
{
var old = Window(Day, 30); var current = Window(Day + Week * 2, 20);
var result = History(current, [old], [Token(Day), Token(Day + Week), Token(Day + Week * 2)], from: Day.AddDays(3));
Assert.Equal(2, result.Instances.Count); Assert.Equal(Day, result.Instances[1].Start);
Assert.Equal(1_000_000, result.Instances[1].Tokens.Total);
Assert.Single(History(current, [old], [], from: Day + Week).Instances);
Assert.Equal(old.SampleTime, result.FirstSample);
}
[Fact] public void JitterAndInterleavedOldRolloutAfterEarlyResetDoNotCreateAnotherInstance()
{
var transition = Day.AddHours(10).AddMinutes(48).AddSeconds(56);
var old = Window(Day.AddDays(-2), 90);
var current = Window(transition, 2);
var newFirst = current with { SampleTime = transition, UsedPercent = 0, ResetsAt = current.ResetsAt!.Value.AddSeconds(-11) };
var stale = old with { SampleTime = transition.AddSeconds(4), UsedPercent = 98, ResetsAt = old.ResetsAt!.Value.AddSeconds(9) };
var jitter = old with { SampleTime = old.SampleTime.AddHours(1), UsedPercent = 95, ResetsAt = old.ResetsAt.Value.AddSeconds(11) };
var result = History(current, [old, jitter, newFirst, stale], [Token(Day.AddDays(-2)), Token(Day.AddHours(10))]);
Assert.Equal(2, result.Instances.Count); Assert.Equal(95, result.Instances[1].Final.Used);
Assert.Equal(transition, result.Instances[1].End); Assert.Equal(1_000_000, result.Instances[0].Tokens.Total);
Assert.Equal(jitter.ResetsAt, result.Instances[1].Reset);
Assert.Equal(1_000_000, result.Instances[1].Tokens.Total);
Assert.DoesNotContain(result.Instances[1].BurnUp.Points, p => p.Used == 98);
}
[Fact] public void HistogramsUseLocalEndHourAndMondayBasedWeekday()
{
var zone = TimeZoneInfo.CreateCustomTimeZone("Fixture +03", TimeSpan.FromHours(3), "Fixture", "Fixture");
var old = Window(Day); var transition = Day.AddDays(1).AddHours(22); // Saturday locally.
var result = History(Window(transition), [old], [], zone: zone);
Assert.Equal(1, result.EarlyByHour[1]); Assert.Equal(1, result.EarlyByHour.Sum());
Assert.Equal(1, result.EarlyByWeekday[5]); Assert.Equal(1, result.EarlyByWeekday.Sum());
}
[Theory]
[InlineData(15, false)]
[InlineData(16, true)]
public void EarlyThresholdIsStrictlyMoreThanFifteenMinutes(int minutes, bool early)
{
var old = Window(Day); var next = Window(Day + Week - TimeSpan.FromMinutes(minutes));
Assert.Equal(early, History(next, [old], []).Instances[1].Early);
}
}