app: render the panel with an injected clock so tests do not depend on the date #12

Merged
schmidt.florian merged 2 commits from 11-panel-clock into master 2026-10-17 09:28:16 +02:00
12 changed files with 90 additions and 65 deletions
+1
View File
@@ -4,6 +4,7 @@ properties use CommunityToolkit.Mvvm source generators. Custom charts use Drawin
Program owns StoreLock for the engine lifetime. DesktopApp marshals Core events to the UI; Program owns StoreLock for the engine lifetime. DesktopApp marshals Core events to the UI;
Program passes its executable path to RefreshEngine for desktop activation through D9 snapshots. Program passes its executable path to RefreshEngine for desktop activation through D9 snapshots.
history queries run on worker threads and discard superseded results. Keep all writes atomic (D5). history queries run on worker threads and discard superseded results. Keep all writes atomic (D5).
Panel rendering and child views take time from the panel's TimeProvider; never read the system clock directly.
Daily charts use local calendar boundaries; never assume a day lasts 24 hours. Daily charts use local calendar boundaries; never assume a day lasts 24 hours.
Stream Deck policy and the real installer come through IPluginInstaller (D11). Stream Deck policy and the real installer come through IPluginInstaller (D11).
UsePlatformDetect selects X11 on Linux in the pinned Avalonia version. Keep XWayland support. UsePlatformDetect selects X11 on Linux in the pinned Avalonia version. Keep XWayland support.
+10 -10
View File
@@ -5,7 +5,7 @@ using FinalToken.Core;
namespace FinalToken.App; namespace FinalToken.App;
public sealed class BurnUpChart(LimitChart chart) : Decorator public sealed class BurnUpChart(LimitChart chart, TimeProvider? clock = null) : Decorator
{ {
private Rect plot; private Rect plot;
private double? crosshair; private double? crosshair;
@@ -13,7 +13,7 @@ public sealed class BurnUpChart(LimitChart chart) : Decorator
protected override void OnInitialized() protected override void OnInitialized()
{ {
base.OnInitialized(); Height = 240; ToolTip.SetShowDelay(this, 0); base.OnInitialized(); Height = 240; ToolTip.SetShowDelay(this, 0);
if (chart.Window is { } snapshot && Display.ForecastWaiting(snapshot, chart.Now) is { } waiting) if (chart.Window is { } snapshot && Display.ForecastWaiting(snapshot, chart.Now, clock) is { } waiting)
Child = new TextBlock { Text = waiting, FontSize = 12, Foreground = Ui.Colour("Muted", Ui.Dark(this)), Child = new TextBlock { Text = waiting, FontSize = 12, Foreground = Ui.Colour("Muted", Ui.Dark(this)),
HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center,
VerticalAlignment = Avalonia.Layout.VerticalAlignment.Top, Margin = new Thickness(42, 40, 16, 0) }; VerticalAlignment = Avalonia.Layout.VerticalAlignment.Top, Margin = new Thickness(42, 40, 16, 0) };
@@ -45,7 +45,7 @@ public sealed class BurnUpChart(LimitChart chart) : Decorator
if (before.Origin == UseOrigin.Estimated || after.Origin == UseOrigin.Estimated) source = "Estimated from tokens"; if (before.Origin == UseOrigin.Estimated || after.Origin == UseOrigin.Estimated) source = "Estimated from tokens";
} }
var expected = 100 * (time - current.Start).TotalSeconds / (current.Reset - current.Start).TotalSeconds; var expected = 100 * (time - current.Start).TotalSeconds / (current.Reset - current.Start).TotalSeconds;
ToolTip.SetTip(this, new DataTooltip(Display.Projection(time), new("Used", used is { } use ? $"{use:0.##} %" : "Collecting history", Ui.ProviderColour(chart.Provider, Ui.Dark(this))), ToolTip.SetTip(this, new DataTooltip(Display.Projection(time, clock), new("Used", used is { } use ? $"{use:0.##} %" : "Collecting history", Ui.ProviderColour(chart.Provider, Ui.Dark(this))),
new("Expected", $"{expected:0.##} %"), new("Delta", used is { } value ? $"{value - expected:+0.##;-0.##;0} points" : "Unknown"), new("Expected", $"{expected:0.##} %"), new("Delta", used is { } value ? $"{value - expected:+0.##;-0.##;0} points" : "Unknown"),
new("Source", used is null ? "No baseline" : source))); new("Source", used is null ? "No baseline" : source)));
InvalidateVisual(); InvalidateVisual();
@@ -82,16 +82,16 @@ public sealed class BurnUpChart(LimitChart chart) : Decorator
{ {
var x = X(crossing); var mark = snapshot.Pace.State == PaceState.Ahead ? Brush.Parse("#d03b3b") : colour; var x = X(crossing); var mark = snapshot.Pace.State == PaceState.Ahead ? Brush.Parse("#d03b3b") : colour;
context.DrawLine(new Pen(mark, 2), new(x, plot.Top - 5), new(x, plot.Top + 5)); context.DrawLine(new Pen(mark, 2), new(x, plot.Top - 5), new(x, plot.Top + 5));
ChartText.Draw(context, "100 % " + Display.Projection(crossing), new(Math.Clamp(x - 80, plot.Left, Math.Max(plot.Left, plot.Right - 175)), 0), Ui.Colour("Secondary", dark)); ChartText.Draw(context, "100 % " + Display.Projection(crossing, clock), new(Math.Clamp(x - 80, plot.Left, Math.Max(plot.Left, plot.Right - 175)), 0), Ui.Colour("Secondary", dark));
} }
if (instance.ReachedLimit is { } reached && instance.ReachedOrigin == UseOrigin.Estimated) if (instance.ReachedLimit is { } reached && instance.ReachedOrigin == UseOrigin.Estimated)
{ {
var labelX = Math.Clamp(X(reached) - 80, plot.Left, Math.Max(plot.Left, plot.Right - 260)); var labelX = Math.Clamp(X(reached) - 80, plot.Left, Math.Max(plot.Left, plot.Right - 260));
context.DrawLine(new Pen(colour, 2), new(X(reached), plot.Top - 5), new(X(reached), plot.Top + 5)); context.DrawLine(new Pen(colour, 2), new(X(reached), plot.Top - 5), new(X(reached), plot.Top + 5));
ChartText.Draw(context, "Limit reached (estimated) " + Display.Projection(reached), new(labelX, 0), Ui.Colour("Secondary", dark)); ChartText.Draw(context, "Limit reached (estimated) " + Display.Projection(reached, clock), new(labelX, 0), Ui.Colour("Secondary", dark));
} }
ChartText.Draw(context, Display.Projection(instance.Start), new(plot.Left, plot.Bottom + 12), muted); ChartText.Draw(context, Display.Projection(instance.Start, clock), new(plot.Left, plot.Bottom + 12), muted);
ChartText.Draw(context, Display.Projection(instance.Reset), new(Math.Max(plot.Left, plot.Right - 120), plot.Bottom + 12), muted); ChartText.Draw(context, Display.Projection(instance.Reset, clock), new(Math.Max(plot.Left, plot.Right - 120), plot.Bottom + 12), muted);
var tickX = X(chart.Now); var tickX = X(chart.Now);
if (tickX > plot.Left + 160 && tickX < plot.Right - 160) ChartText.Draw(context, "now", new(tickX - 10, plot.Bottom + 12), Ui.Colour("Secondary", dark)); if (tickX > plot.Left + 160 && tickX < plot.Right - 160) ChartText.Draw(context, "now", new(tickX - 10, plot.Bottom + 12), Ui.Colour("Secondary", dark));
@@ -110,7 +110,7 @@ public sealed class BurnUpChart(LimitChart chart) : Decorator
} }
} }
public sealed class InstancePeaks(IReadOnlyList<LimitInstance> instances, Provider provider) : Control public sealed class InstancePeaks(IReadOnlyList<LimitInstance> instances, Provider provider, TimeProvider? clock = null) : Control
{ {
private readonly List<(Rect Bounds, LimitInstance Instance)> hits = []; private readonly List<(Rect Bounds, LimitInstance Instance)> hits = [];
protected override void OnInitialized() protected override void OnInitialized()
@@ -119,9 +119,9 @@ public sealed class InstancePeaks(IReadOnlyList<LimitInstance> instances, Provid
PointerMoved += (_, e) => PointerMoved += (_, e) =>
{ {
var instance = hits.FirstOrDefault(h => h.Bounds.Contains(e.GetPosition(this))).Instance; var instance = hits.FirstOrDefault(h => h.Bounds.Contains(e.GetPosition(this))).Instance;
ToolTip.SetTip(this, instance is null ? null : new DataTooltip(Display.Projection(instance.Start) + " — " + Display.Projection(instance.End), ToolTip.SetTip(this, instance is null ? null : new DataTooltip(Display.Projection(instance.Start, clock) + " — " + Display.Projection(instance.End, clock),
new("Peak", $"{instance.Peak:0.##} %", Ui.ProviderColour(provider, Ui.Dark(this))), new("Peak", $"{instance.Peak:0.##} %", Ui.ProviderColour(provider, Ui.Dark(this))),
new(instance.ReachedOrigin == UseOrigin.Estimated ? "Limit reached (estimated)" : "100 % reached", instance.ReachedLimit is { } time ? "⚠ " + Display.Projection(time) : "Not reached"), new(instance.ReachedOrigin == UseOrigin.Estimated ? "Limit reached (estimated)" : "100 % reached", instance.ReachedLimit is { } time ? "⚠ " + Display.Projection(time, clock) : "Not reached"),
new("Source", instance.Points.Any(p => p.Origin == UseOrigin.Estimated) ? "Includes token estimates" : "Measured"))); new("Source", instance.Points.Any(p => p.Origin == UseOrigin.Estimated) ? "Includes token estimates" : "Measured")));
}; };
} }
+4 -3
View File
@@ -40,6 +40,7 @@ public sealed class UsageChart : Control
} }
public IReadOnlyList<ChartValue> Values { get; init; } = []; public IReadOnlyList<ChartValue> Values { get; init; } = [];
public IReadOnlyList<string> SeriesNames { get; init; } = []; public IReadOnlyList<string> SeriesNames { get; init; } = [];
public TimeProvider Clock { get; init; } = TimeProvider.System;
public bool Percent { get; init; } public bool Percent { get; init; }
public Provider LimitProvider { get; init; } public Provider LimitProvider { get; init; }
public ChartValue? Forecast { get; init; } public ChartValue? Forecast { get; init; }
@@ -94,7 +95,7 @@ public sealed class UsageChart : Control
{ {
var start = ForecastStart ?? tail; var start = ForecastStart ?? tail;
context.DrawLine(new Pen(colour, 2, new DashStyle([1, 3], 0)), Position(start, start.Value), Position(forecast, forecast.Value)); context.DrawLine(new Pen(colour, 2, new DashStyle([1, 3], 0)), Position(start, start.Value), Position(forecast, forecast.Value));
hits.Add((new Rect(Position(forecast, forecast.Value) - new Vector(8, 8), new Size(16, 16)), () => new DataTooltip("Average forecast", new("Time", Display.Projection(forecast.Time)), new("Use", $"{forecast.Value:0.#} %")))); hits.Add((new Rect(Position(forecast, forecast.Value) - new Vector(8, 8), new Size(16, 16)), () => new DataTooltip("Average forecast", new("Time", Display.Projection(forecast.Time, Clock)), new("Use", $"{forecast.Value:0.#} %"))));
} }
} }
else else
@@ -140,7 +141,7 @@ internal static class ChartText
} }
} }
public sealed class PaceBar(WindowSnapshot window) : Control public sealed class PaceBar(WindowSnapshot window, DateTimeOffset now) : Control
{ {
public static IBrush Colour(PaceState state) => Brush.Parse(state switch public static IBrush Colour(PaceState state) => Brush.Parse(state switch
{ PaceState.Ahead => "#ec835a", PaceState.Behind => "#fab219", PaceState.OnTrack => "#0ca30c", _ => "#898781" }); { PaceState.Ahead => "#ec835a", PaceState.Behind => "#fab219", PaceState.OnTrack => "#0ca30c", _ => "#898781" });
@@ -150,7 +151,7 @@ public sealed class PaceBar(WindowSnapshot window) : Control
var dark = Ui.Dark(this); var colour = Ui.ProviderColour(window.Window.Provider, dark); var dark = Ui.Dark(this); var colour = Ui.ProviderColour(window.Window.Provider, dark);
context.DrawRectangle(Ui.Colour("Grid", dark), null, new Rect(Bounds.Size), 3, 3); context.DrawRectangle(Ui.Colour("Grid", dark), null, new Rect(Bounds.Size), 3, 3);
var used = Bounds.Width * Math.Clamp(window.Window.UsedPercent / 100, 0, 1); var used = Bounds.Width * Math.Clamp(window.Window.UsedPercent / 100, 0, 1);
if (LimitAnalysis.AverageUseAtReset(window.Window, DateTimeOffset.UtcNow, window.Pace) is { } forecast && forecast > window.Window.UsedPercent) if (LimitAnalysis.AverageUseAtReset(window.Window, now, window.Pace) is { } forecast && forecast > window.Window.UsedPercent)
{ {
using (context.PushOpacity(0.25)) context.DrawRectangle(colour, null, new Rect(used, 0, Math.Max(0, Bounds.Width * Math.Min(1, forecast / 100) - used), Bounds.Height), 3, 3); using (context.PushOpacity(0.25)) context.DrawRectangle(colour, null, new Rect(used, 0, Math.Max(0, Bounds.Width * Math.Min(1, forecast / 100) - used), Bounds.Height), 3, 3);
if (forecast > 100) context.DrawLine(new Pen(window.Pace.State == PaceState.Ahead ? Brush.Parse("#d03b3b") : Ui.Colour("Secondary", dark), 3), new(Bounds.Width - 2, 0), new(Bounds.Width - 2, Bounds.Height)); if (forecast > 100) context.DrawLine(new Pen(window.Pace.State == PaceState.Ahead ? Brush.Parse("#d03b3b") : Ui.Colour("Secondary", dark), 3), new(Bounds.Width - 2, 0), new(Bounds.Width - 2, Bounds.Height));
+4 -4
View File
@@ -96,9 +96,9 @@ public partial class PanelViewModel : ObservableObject
public static class Display public static class Display
{ {
public static string? ForecastWaiting(WindowSnapshot window, DateTimeOffset now) => public static string? ForecastWaiting(WindowSnapshot window, DateTimeOffset now, TimeProvider? clock = null) =>
window.Pace.State != PaceState.Unknown && !Pace.CanForecast(window.Window, now, window.Pace) && window.Pace.State != PaceState.Unknown && !Pace.CanForecast(window.Window, now, window.Pace) &&
Pace.ForecastStartsAt(window.Window) is { } start && start > now ? "Forecast from " + Projection(start) : null; Pace.ForecastStartsAt(window.Window) is { } start && start > now ? "Forecast from " + Projection(start, clock) : null;
public static string ChartDateLabel(DateTimeOffset time, TimeSpan interval) public static string ChartDateLabel(DateTimeOffset time, TimeSpan interval)
=> ChartTime(time, interval).ToString(interval >= TimeSpan.FromDays(1) ? "MM-dd" : "MM-dd HH:mm"); => ChartTime(time, interval).ToString(interval >= TimeSpan.FromDays(1) ? "MM-dd" : "MM-dd HH:mm");
public static string ChartTimestamp(DateTimeOffset time, TimeSpan interval) public static string ChartTimestamp(DateTimeOffset time, TimeSpan interval)
@@ -132,7 +132,7 @@ public static class Display
var format = trimTrailingZeros ? decimals == 0 ? "0" : "0." + new string('#', decimals) : "F" + decimals; var format = trimTrailingZeros ? decimals == 0 ? "0" : "0." + new string('#', decimals) : "F" + decimals;
return value.ToString(format) + new[] { "", " K", " M", " B" }[unit]; return value.ToString(format) + new[] { "", " K", " M", " B" }[unit];
} }
public static string Forecast(DateTimeOffset date, PaceState state) => public static string Forecast(DateTimeOffset date, PaceState state, TimeProvider? clock = null) =>
(state == PaceState.Ahead ? "⚠ " : "At this pace ") + "100 % on " + Projection(date); (state == PaceState.Ahead ? "⚠ " : "At this pace ") + "100 % on " + Projection(date, clock);
public static string State(PaceState state) => state switch { PaceState.OnTrack => "✓ On track", PaceState.Ahead => "▲ Ahead", PaceState.Behind => "▼ Behind", _ => "? Pace unknown" }; public static string State(PaceState state) => state switch { PaceState.OnTrack => "✓ On track", PaceState.Ahead => "▲ Ahead", PaceState.Behind => "▼ Behind", _ => "? Pace unknown" };
} }
+13 -11
View File
@@ -11,6 +11,7 @@ namespace FinalToken.App;
public sealed class PanelWindow : Window public sealed class PanelWindow : Window
{ {
private readonly PanelViewModel model; private readonly PanelViewModel model;
private readonly TimeProvider clock;
private readonly StackPanel body = new() { Spacing = 24, Margin = new Thickness(24) }; private readonly StackPanel body = new() { Spacing = 24, Margin = new Thickness(24) };
private readonly StackPanel statuses = new() { Orientation = Orientation.Horizontal, Spacing = 8 }; private readonly StackPanel statuses = new() { Orientation = Orientation.Horizontal, Spacing = 8 };
private readonly TextBlock updated = Ui.Text("", 12, "Muted"); private readonly TextBlock updated = Ui.Text("", 12, "Muted");
@@ -22,9 +23,10 @@ public sealed class PanelWindow : Window
private readonly Dictionary<Provider, string> selectedDailyWindow = []; private readonly Dictionary<Provider, string> selectedDailyWindow = [];
private readonly BreakdownState modelBreakdown = new(), projectBreakdown = new(); private readonly BreakdownState modelBreakdown = new(), projectBreakdown = new();
public PanelWindow(PanelViewModel model, Action refresh, Action settings, Action quit, Action reload) public PanelWindow(PanelViewModel model, Action refresh, Action settings, Action quit, Action reload, TimeProvider? clock = null)
{ {
this.model = model; this.model = model;
this.clock = clock ?? TimeProvider.System;
Title = $"FinalToken {typeof(Program).Assembly.GetName().Version?.ToString(3)}"; Title = $"FinalToken {typeof(Program).Assembly.GetName().Version?.ToString(3)}";
Width = 1280; Height = 900; MinWidth = 960; MinHeight = 500; Ui.Theme(this); Width = 1280; Height = 900; MinWidth = 960; MinHeight = 500; Ui.Theme(this);
var brand = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center }; var brand = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center };
@@ -83,7 +85,7 @@ public sealed class PanelWindow : Window
limitColumns = LimitColumnCount((Bounds.Width > 0 ? Bounds.Width : Width) - 48); limitColumns = LimitColumnCount((Bounds.Width > 0 ? Bounds.Width : Width) - 48);
var content = new List<Control>(); var content = new List<Control>();
statuses.Children.Clear(); refreshButton.IsEnabled = !model.Refreshing; statuses.Children.Clear(); refreshButton.IsEnabled = !model.Refreshing;
var now = DateTimeOffset.UtcNow; var now = clock.GetUtcNow();
updated.Text = model.Snapshot is { } s ? "Updated " + (now - s.MadeAt < TimeSpan.FromMinutes(1) ? "just now" : Display.Duration(now - s.MadeAt) + " ago") : model.Message; updated.Text = model.Snapshot is { } s ? "Updated " + (now - s.MadeAt < TimeSpan.FromMinutes(1) ? "just now" : Display.Duration(now - s.MadeAt) + " ago") : model.Message;
ToolTip.SetTip(updated, model.Snapshot?.MadeAt.LocalDateTime.ToString("F")); ToolTip.SetTip(updated, model.Snapshot?.MadeAt.LocalDateTime.ToString("F"));
if (model.Snapshot is { } snapshot) if (model.Snapshot is { } snapshot)
@@ -163,15 +165,15 @@ public sealed class PanelWindow : Window
var seriesNames = h.Hourly.Concat(h.Daily).Select(v => v.Series).Distinct().Order(StringComparer.Ordinal).ToArray(); var seriesNames = h.Hourly.Concat(h.Daily).Select(v => v.Series).Distinct().Order(StringComparer.Ordinal).ToArray();
Control TokenChart(string title, IReadOnlyList<ChartValue> values, bool daily) => Ui.Card(Ui.Stack(Ui.Text(title, 15), Control TokenChart(string title, IReadOnlyList<ChartValue> values, bool daily) => Ui.Card(Ui.Stack(Ui.Text(title, 15),
Legend(seriesNames), new UsageChart { Values = values.Select(v => v with { Value = Math.Max(0, v.Value - (model.IncludeCacheReads ? 0 : v.CacheRead)) }).ToArray(), Legend(seriesNames), new UsageChart { Values = values.Select(v => v with { Value = Math.Max(0, v.Value - (model.IncludeCacheReads ? 0 : v.CacheRead)) }).ToArray(),
SeriesNames = seriesNames, Interval = daily ? TimeSpan.FromDays(1) : TimeSpan.FromHours(1) })); Clock = clock, SeriesNames = seriesNames, Interval = daily ? TimeSpan.FromDays(1) : TimeSpan.FromHours(1) }));
content.Add(Ui.Columns([TokenChart("Tokens per hour", h.Hourly, false), TokenChart("Tokens per day", h.Daily, true)], wide)); content.Add(Ui.Columns([TokenChart("Tokens per hour", h.Hourly, false), TokenChart("Tokens per day", h.Daily, true)], wide));
var windows = h.Limits.Where(l => l.Analysis?.Current.HasData == true).ToArray(); var windows = h.Limits.Where(l => l.Analysis?.Current.HasData == true).ToArray();
if (windows.Length > 0) if (windows.Length > 0)
{ {
content.Add(Ui.Text("Window charts", 20)); content.Add(Ui.Text("Window charts", 20));
content.Add(Ui.Columns(windows.Select(limit => Ui.Card(Ui.Stack(Ui.Text(limit.Label, 15), content.Add(Ui.Columns(windows.Select(limit => Ui.Card(Ui.Stack(Ui.Text(limit.Label, 15),
Ui.Text("Measured · dashed: estimated · faint: previous · dotted: forecast", 12, "Muted"), new BurnUpChart(limit), Ui.Text("Measured · dashed: estimated · faint: previous · dotted: forecast", 12, "Muted"), new BurnUpChart(limit with { Now = now }, clock),
Ui.Text("Past instances · peak use", 12, "Muted"), new InstancePeaks(limit.Analysis!.Past, limit.Provider)))), wide)); Ui.Text("Past instances · peak use", 12, "Muted"), new InstancePeaks(limit.Analysis!.Past, limit.Provider, clock)))), wide));
} }
content.Add(Ui.Text("Breakdown", 20)); content.Add(Ui.Text("Breakdown", 20));
content.Add(Ui.Card(new BreakdownTable("By model", h.Models, false, model.ProviderFilter, modelBreakdown))); content.Add(Ui.Card(new BreakdownTable("By model", h.Models, false, model.ProviderFilter, modelBreakdown)));
@@ -192,11 +194,11 @@ public sealed class PanelWindow : Window
var title = new DockPanel(); var title = new DockPanel();
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) { Height = 10 }); 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)}" : "Reset unknown", 13, "Secondary")); card.Children.Add(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) + $" ({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);
@@ -206,11 +208,11 @@ public sealed class PanelWindow : Window
} }
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")); card.Children.Add(Ui.Text($"≈ {average:0.#} % at reset", 13, "Secondary"));
else if (Display.ForecastWaiting(window, now) is { } waiting) else if (Display.ForecastWaiting(window, now, clock) is { } waiting)
card.Children.Add(Ui.Text(waiting, 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)}" : $" · ≈ {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)))); card.Children.Add(line);
} }
if (detail?.Days is { } days) if (detail?.Days is { } days)
@@ -223,7 +225,7 @@ public sealed class PanelWindow : Window
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) 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) : "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, TokenCounts counts)
{ {
+1
View File
@@ -5,3 +5,4 @@ View-model tests use public Core queries. Headless tests run on a dedicated UI t
Skia and HarfBuzz, exercise settings and popup actions, and save PNG screenshots outside Skia and HarfBuzz, exercise settings and popup actions, and save PNG screenshots outside
the repo at ../runs/shots/app. FINALTOKEN_SCREENSHOT_DIR overrides that path. the repo at ../runs/shots/app. FINALTOKEN_SCREENSHOT_DIR overrides that path.
Popup expiry uses an injected TimeProvider; fire timers and pump the dispatcher instead of sleeping. Popup expiry uses an injected TimeProvider; fire timers and pump the dispatcher instead of sleeping.
Pin panel clocks and HistoryStore retention clocks to fixture time. Reuse FixedClock for fixed-date tests.
@@ -43,7 +43,7 @@ public sealed class FormattingTests
[InlineData(FinalToken.Core.PaceState.Unknown, false)] [InlineData(FinalToken.Core.PaceState.Unknown, false)]
public void ForecastWarningFollowsState(FinalToken.Core.PaceState state, bool warning) public void ForecastWarningFollowsState(FinalToken.Core.PaceState state, bool warning)
{ {
var text = Display.Forecast(new(2026, 10, 18, 14, 43, 0, TimeSpan.Zero), state); var text = Display.Forecast(new(2026, 10, 18, 14, 43, 0, TimeSpan.Zero), state, new FixedClock());
Assert.Equal(warning, text.Contains('⚠')); Assert.Equal(warning, text.Contains('⚠'));
Assert.StartsWith(warning ? "⚠ 100 % on " : "At this pace 100 % on ", text); Assert.StartsWith(warning ? "⚠ 100 % on " : "At this pace 100 % on ", text);
} }
@@ -117,9 +117,11 @@ public sealed class FormattingTests
Assert.Equal([0d], UsageChart.AxisTicks(0, true)); Assert.Equal([0d], UsageChart.AxisTicks(0, true));
} }
private sealed class FixedClock : TimeProvider }
internal sealed class FixedClock(DateTimeOffset? now = null) : TimeProvider
{ {
public override DateTimeOffset GetUtcNow() => new(2026, 10, 14, 18, 0, 0, TimeSpan.Zero); public DateTimeOffset UtcNow { get; set; } = now ?? new(2026, 10, 14, 18, 0, 0, TimeSpan.Zero);
public override DateTimeOffset GetUtcNow() => UtcNow;
public override TimeZoneInfo LocalTimeZone { get; } = TimeZoneInfo.CreateCustomTimeZone("Fixture+02", TimeSpan.FromHours(2), "Fixture", "Fixture"); public override TimeZoneInfo LocalTimeZone { get; } = TimeZoneInfo.CreateCustomTimeZone("Fixture+02", TimeSpan.FromHours(2), "Fixture", "Fixture");
} }
}
+30 -12
View File
@@ -30,7 +30,8 @@ public sealed class HeadlessTests
var shots = Environment.GetEnvironmentVariable("FINALTOKEN_SCREENSHOT_DIR") ?? Path.Combine(root.Parent!.FullName, "runs", "shots", "app"); var shots = Environment.GetEnvironmentVariable("FINALTOKEN_SCREENSHOT_DIR") ?? Path.Combine(root.Parent!.FullName, "runs", "shots", "app");
Directory.CreateDirectory(shots); Directory.CreateDirectory(shots);
var model = FakeData.Model(); var model = FakeData.Model();
var panel = new PanelWindow(model, () => { }, () => { }, () => { }, () => { }); var clock = new FixedClock(model.Snapshot!.MadeAt);
var panel = new PanelWindow(model, () => { }, () => { }, () => { }, () => { }, clock);
panel.Resources["SystemAccentColor"] = Avalonia.Media.Colors.Red; panel.Resources["SystemAccentColor"] = Avalonia.Media.Colors.Red;
panel.RequestedThemeVariant = ThemeVariant.Light; panel.Show(); Save(panel, "panel-light.png"); panel.RequestedThemeVariant = ThemeVariant.Light; panel.Show(); Save(panel, "panel-light.png");
Assert.Equal($"FinalToken {typeof(Program).Assembly.GetName().Version!.ToString(3)}", panel.Title); Assert.Equal($"FinalToken {typeof(Program).Assembly.GetName().Version!.ToString(3)}", panel.Title);
@@ -142,16 +143,33 @@ public sealed class HeadlessTests
} }
} }
var prior = viewport.Offset; var prior = viewport.Offset;
model.Snapshot = model.Snapshot! with { MadeAt = DateTimeOffset.UtcNow }; 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 forecastModel = FakeData.ForecastModel(); var forecastModel = FakeData.ForecastModel();
var forecastPanel = new PanelWindow(forecastModel, () => { }, () => { }, () => { }, () => { }); var forecastClock = new FixedClock(forecastModel.Snapshot!.MadeAt);
var forecastPanel = new PanelWindow(forecastModel, () => { }, () => { }, () => { }, () => { }, forecastClock);
forecastPanel.Show(); Dispatcher.UIThread.RunJobs(); forecastPanel.Show(); Dispatcher.UIThread.RunJobs();
var aheadTile = forecastPanel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-primary"); var aheadTile = forecastPanel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-primary");
Assert.Contains(aheadTile.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.StartsWith("100 % on ") == true); Assert.Contains(aheadTile.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.StartsWith("100 % on ") == true);
Assert.Contains(aheadTile.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "⚠ "); Assert.Contains(aheadTile.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "⚠ ");
Assert.NotNull(forecastModel.History.Limits.Single(l => l.Window!.Window.Id == "primary").Forecast); Assert.NotNull(forecastModel.History.Limits.Single(l => l.Window!.Window.Id == "primary").Forecast);
var secondary = forecastModel.Snapshot!.Providers[0].Windows.Single(w => w.Window.Id == "secondary");
var forecastStart = Pace.ForecastStartsAt(secondary.Window)!.Value;
foreach (var (renderTime, waiting) in new[] { (forecastStart.AddTicks(-1), true), (forecastStart, false),
(forecastStart.AddTicks(1), false), (secondary.Window.ResetsAt!.Value, false), (secondary.Window.ResetsAt.Value.AddDays(365), false) })
{
forecastClock.UtcNow = renderTime;
forecastPanel.RenderModel(); Dispatcher.UIThread.RunJobs();
var tile = forecastPanel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-secondary");
Assert.Equal(waiting, tile.GetVisualDescendants().OfType<TextBlock>().Any(t => t.Text?.StartsWith("Forecast from ") == true));
var reset = Display.Projection(secondary.Window.ResetsAt!.Value, forecastClock);
Assert.Contains(tile.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.StartsWith("Resets in ") == true && t.Text.EndsWith(reset, StringComparison.Ordinal));
var burnUp = forecastPanel.GetVisualDescendants().OfType<BurnUpChart>().Last();
Assert.Equal(waiting, burnUp.GetVisualDescendants().OfType<TextBlock>().Any(t => t.Text?.StartsWith("Forecast from ") == true));
}
forecastClock.UtcNow = forecastModel.Snapshot.MadeAt;
forecastPanel.RenderModel(); Dispatcher.UIThread.RunJobs();
var waitingTile = forecastPanel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-secondary"); var waitingTile = forecastPanel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-secondary");
var note = Assert.Single(waitingTile.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.StartsWith("Forecast from ") == true).Text; var note = Assert.Single(waitingTile.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.StartsWith("Forecast from ") == true).Text;
Assert.Contains(forecastPanel.GetVisualDescendants().OfType<BurnUpChart>(), c => c.GetVisualDescendants().OfType<TextBlock>().Any(t => t.Text == note)); Assert.Contains(forecastPanel.GetVisualDescendants().OfType<BurnUpChart>(), c => c.GetVisualDescendants().OfType<TextBlock>().Any(t => t.Text == note));
@@ -175,7 +193,7 @@ public sealed class HeadlessTests
} }
forecastPanel.Close(); forecastPanel.Close();
var earlyModel = FakeData.EarlyResetModel(); var earlyModel = FakeData.EarlyResetModel();
var earlyPanel = new PanelWindow(earlyModel, () => { }, () => { }, () => { }, () => { }); var earlyPanel = new PanelWindow(earlyModel, () => { }, () => { }, () => { }, () => { }, new FixedClock(earlyModel.Snapshot!.MadeAt));
earlyPanel.Show(); earlyPanel.Show();
var earlyTile = earlyPanel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-secondary"); var earlyTile = earlyPanel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-secondary");
Assert.DoesNotContain(earlyTile.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.Contains("at reset") == true || t.Text?.Contains("100 % on") == true || t.Text?.StartsWith("Last ") == true); Assert.DoesNotContain(earlyTile.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.Contains("at reset") == true || t.Text?.Contains("100 % on") == true || t.Text?.StartsWith("Last ") == true);
@@ -212,7 +230,7 @@ public sealed class HeadlessTests
{ {
var weekData = originalHistory.Details.Single(d => d.Provider == Provider.Claude && d.Id == "week").Days!; var weekData = originalHistory.Details.Single(d => d.Provider == Provider.Claude && d.Id == "week").Days!;
Assert.Contains(weekData.Current, d => d.Origin == UseOrigin.Estimated); Assert.Contains(weekData.Current, d => d.Origin == UseOrigin.Estimated);
var future = DataTooltip.Day(new(DateTimeOffset.Now.AddDays(1), DateTimeOffset.Now.AddDays(2), null, 42, false, true)); var future = DataTooltip.Day(new(clock.GetLocalNow().AddDays(1), clock.GetLocalNow().AddDays(2), null, 42, false, true));
Assert.DoesNotContain(future.Rows, row => row.Label == "Cumulative"); Assert.DoesNotContain(future.Rows, row => row.Label == "Cumulative");
var types = new (string Name, DataTooltip Tip)[] var types = new (string Name, DataTooltip Tip)[]
{ {
@@ -224,9 +242,9 @@ public sealed class HeadlessTests
("tokens", DataTooltip.Tokens("Claude - This week", originalSnapshot.Providers[0].Week)), ("tokens", DataTooltip.Tokens("Claude - This 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), new Point(240, 100)); CaptureChartTip("burnup", new BurnUpChart(limit, clock), new Point(240, 100));
CaptureChartTip("past-instance", new InstancePeaks(limit.Analysis!.Past, Provider.Claude), new Point(30, 30)); CaptureChartTip("past-instance", new InstancePeaks(limit.Analysis!.Past, Provider.Claude, clock), new Point(30, 30));
CaptureChartTip("past-limit-reached", new InstancePeaks(limit.Analysis!.Past, Provider.Claude), new Point(600, 30)); CaptureChartTip("past-limit-reached", new InstancePeaks(limit.Analysis!.Past, Provider.Claude, clock), new Point(600, 30));
CaptureChartTip("hourly", new UsageChart { Values = originalHistory.Hourly }, new Point(60, 170)); CaptureChartTip("hourly", new UsageChart { Values = originalHistory.Hourly }, new Point(60, 170));
CaptureChartTip("daily", new UsageChart { Values = originalHistory.Daily, Interval = TimeSpan.FromDays(1) }, new Point(60, 170)); CaptureChartTip("daily", new UsageChart { Values = originalHistory.Daily, Interval = TimeSpan.FromDays(1) }, new Point(60, 170));
CaptureChartTip("composition", new CompositionBar(originalSnapshot.Providers[0].Week, Provider.Claude, true) { Height = 8 }, new Point(100, 4)); CaptureChartTip("composition", new CompositionBar(originalSnapshot.Providers[0].Week, Provider.Claude, true) { Height = 8 }, new Point(100, 4));
@@ -248,7 +266,7 @@ public sealed class HeadlessTests
tooltipWindow.Show(); Save(tooltipWindow, $"tooltip-{name}-{theme}.png"); tooltipWindow.Close(); tooltipWindow.Show(); Save(tooltipWindow, $"tooltip-{name}-{theme}.png"); tooltipWindow.Close();
} }
} }
model.Snapshot = FakeData.Snapshot(DateTimeOffset.UtcNow, true); model.Snapshot = FakeData.Snapshot(clock.GetUtcNow(), true);
Dispatcher.UIThread.RunJobs(); panel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = default; Dispatcher.UIThread.RunJobs(); panel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = default;
Save(panel, "panel-unavailable.png"); Save(panel, "panel-unavailable.png");
foreach (var (width, height) in new[] { (1280, 900), (1500, 1000) }) foreach (var (width, height) in new[] { (1280, 900), (1500, 1000) })
@@ -258,7 +276,7 @@ public sealed class HeadlessTests
panel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = default; panel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = default;
Save(panel, $"panel-{width}x{height}-{theme}-unavailable.png"); Save(panel, $"panel-{width}x{height}-{theme}-unavailable.png");
} }
model.Diagnostics = [new(DateTimeOffset.UtcNow, Provider.Claude, "fixture", "Probe timed out. Last good sample retained.")]; model.Diagnostics = [new(clock.GetUtcNow(), Provider.Claude, "fixture", "Probe timed out. Last good sample retained.")];
Dispatcher.UIThread.RunJobs(); var expander = panel.GetVisualDescendants().OfType<Expander>().Single(); Dispatcher.UIThread.RunJobs(); var expander = panel.GetVisualDescendants().OfType<Expander>().Single();
expander.BringIntoView(); Save(panel, "panel-diagnostics-collapsed.png"); expander.BringIntoView(); Save(panel, "panel-diagnostics-collapsed.png");
expander.IsExpanded = true; panel.UpdateLayout(); expander.IsExpanded = true; panel.UpdateLayout();
@@ -302,7 +320,7 @@ public sealed class HeadlessTests
Assert.Null(cancellationFailure); Assert.Null(cancellationFailure);
Assert.Contains(cancelled.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Settings save was cancelled."); cancelled.Close(); Assert.Contains(cancelled.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Settings save was cancelled."); cancelled.Close();
var opened = 0; var opened = 0;
var ahead = PopupWindow.Pace(new(Provider.Claude, "session", "Session", PaceState.Ahead, 22, DateTimeOffset.UtcNow.AddHours(1)), () => opened++); var ahead = PopupWindow.Pace(new(Provider.Claude, "session", "Session", PaceState.Ahead, 22, clock.GetUtcNow().AddHours(1)), () => opened++);
ahead.Show(); SaveThemes(ahead, "popup-ahead"); Assert.False(ahead.ShowActivated); ahead.Show(); SaveThemes(ahead, "popup-ahead"); Assert.False(ahead.ShowActivated);
ahead.MouseDown(new Point(100, 60), Avalonia.Input.MouseButton.Left); Assert.Equal(1, opened); Assert.False(ahead.IsVisible); ahead.MouseDown(new Point(100, 60), Avalonia.Input.MouseButton.Left); Assert.Equal(1, opened); Assert.False(ahead.IsVisible);
var behind = PopupWindow.Pace(new(Provider.Codex, "primary", "Primary", PaceState.Behind, -18, null), () => { }); var behind = PopupWindow.Pace(new(Provider.Codex, "primary", "Primary", PaceState.Behind, -18, null), () => { });
@@ -320,7 +338,7 @@ public sealed class HeadlessTests
var first = PopupWindow.Pace(new(Provider.Claude, "a", "Session", PaceState.Ahead, 20, null), () => { }); var first = PopupWindow.Pace(new(Provider.Claude, "a", "Session", PaceState.Ahead, 20, null), () => { });
var second = PopupWindow.Pace(new(Provider.Codex, "b", "Week", PaceState.Behind, -20, null), () => { }); var second = PopupWindow.Pace(new(Provider.Codex, "b", "Week", PaceState.Behind, -20, null), () => { });
stack.Show(first); stack.Show(second); Assert.True(second.Position.Y < first.Position.Y); stack.Show(first); stack.Show(second); Assert.True(second.Position.Y < first.Position.Y);
var chart = new UsageChart { Values = [new(DateTimeOffset.UtcNow, "Exact", 123456)] }; var chart = new UsageChart { Values = [new(clock.GetUtcNow(), "Exact", 123456)] };
var chartWindow = new Window { Content = chart, Width = 400, Height = 180 }; var chartWindow = new Window { Content = chart, Width = 400, Height = 180 };
chartWindow.Show(); chartWindow.Show();
using (chartWindow.CaptureRenderedFrame()) { } using (chartWindow.CaptureRenderedFrame()) { }
+10 -10
View File
@@ -51,7 +51,7 @@ public sealed class ViewModelTests
public void ResetDriftKeepsChartContinuousAndRealResetAddsGap(int minutes) public void ResetDriftKeepsChartContinuousAndRealResetAddsGap(int minutes)
{ {
var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero); var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog()); var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog(), new FixedClock(now));
var window = new LimitWindow(Provider.Claude, "week", "Week", 60, now.AddDays(4), TimeSpan.FromDays(7), now.AddMinutes(-1), "fixture"); var window = new LimitWindow(Provider.Claude, "week", "Week", 60, now.AddDays(4), TimeSpan.FromDays(7), now.AddMinutes(-1), "fixture");
var first = window with { SampleTime = CalendarDays.Start(now).AddHours(-1), UsedPercent = 40, ResetsAt = window.ResetsAt!.Value.AddMinutes(minutes) }; var first = window with { SampleTime = CalendarDays.Start(now).AddHours(-1), UsedPercent = 40, ResetsAt = window.ResetsAt!.Value.AddMinutes(minutes) };
store.AddLimits([first]); store.AddLimits([first]);
@@ -108,7 +108,7 @@ public sealed class ViewModelTests
[Fact] public void SelectedProviderDailySeriesRespectsPartialDays() [Fact] public void SelectedProviderDailySeriesRespectsPartialDays()
{ {
var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero); var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog()); var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog(), new FixedClock(now));
store.Add(new(Provider.Claude, now.AddHours(-26), "outside", "p", new(Total: 300), "outside")); store.Add(new(Provider.Claude, now.AddHours(-26), "outside", "p", new(Total: 300), "outside"));
store.Add(new(Provider.Claude, now.AddHours(-22), "inside", "p", new(Total: 100), "inside")); store.Add(new(Provider.Claude, now.AddHours(-22), "inside", "p", new(Total: 100), "inside"));
store.Add(new(Provider.Claude, now.AddHours(-3), "inside", "p", new(Total: 50), "today")); store.Add(new(Provider.Claude, now.AddHours(-3), "inside", "p", new(Total: 50), "today"));
@@ -122,7 +122,7 @@ public sealed class ViewModelTests
[Fact] public void BreakdownQueryReturnsEveryRowAndItsShareWithoutPrebuildingOther() [Fact] public void BreakdownQueryReturnsEveryRowAndItsShareWithoutPrebuildingOther()
{ {
var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero); var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog()); var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog(), new FixedClock(now));
for (var i = 0; i < 110; i++) store.Add(new(Provider.Claude, now.AddHours(-1), "model", $"project-{i}", new(Total: i + 1), $"{i}")); for (var i = 0; i < 110; i++) store.Add(new(Provider.Claude, now.AddHours(-1), "model", $"project-{i}", new(Total: i + 1), $"{i}"));
var view = PanelViewModel.QueryHistory(store, FakeData.Snapshot(now), HistoryRange.Days7, null, now); var view = PanelViewModel.QueryHistory(store, FakeData.Snapshot(now), HistoryRange.Days7, null, now);
Assert.Equal(110, view.Projects.Count); Assert.Equal("project-109", view.Projects[0].Name); Assert.Equal(110, view.Projects.Count); Assert.Equal("project-109", view.Projects[0].Name);
@@ -132,7 +132,7 @@ public sealed class ViewModelTests
[Fact] public void FilteredModelSeriesUseSixAlphabeticSlotsAndOther() [Fact] public void FilteredModelSeriesUseSixAlphabeticSlotsAndOther()
{ {
var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero); var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog()); var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog(), new FixedClock(now));
for (var i = 9; i >= 0; i--) store.Add(new(Provider.Claude, now.AddHours(-1), $"model-{i}", "p", new(CacheRead: 2, Total: 10), $"{i}")); for (var i = 9; i >= 0; i--) store.Add(new(Provider.Claude, now.AddHours(-1), $"model-{i}", "p", new(CacheRead: 2, Total: 10), $"{i}"));
var view = PanelViewModel.QueryHistory(store, FakeData.Snapshot(now), HistoryRange.Days7, Provider.Claude, now); var view = PanelViewModel.QueryHistory(store, FakeData.Snapshot(now), HistoryRange.Days7, Provider.Claude, now);
Assert.Equal(7, view.Hourly.Count); Assert.Equal(40, view.Hourly.Single(p => p.Series == "Other").Value); Assert.Equal(7, view.Hourly.Count); Assert.Equal(40, view.Hourly.Single(p => p.Series == "Other").Value);
@@ -148,7 +148,7 @@ public sealed class ViewModelTests
[Fact] public void ModelBreakdownKeepsActualProviderIdentityForDots() [Fact] public void ModelBreakdownKeepsActualProviderIdentityForDots()
{ {
var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero); var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog()); var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog(), new FixedClock(now));
store.Add(new(Provider.Claude, now.AddHours(-1), "arbitrary-name", "p", new(Total: 10), "a")); store.Add(new(Provider.Claude, now.AddHours(-1), "arbitrary-name", "p", new(Total: 10), "a"));
store.Add(new(Provider.Codex, now.AddHours(-1), "shared-name", "p", new(Total: 20), "b")); store.Add(new(Provider.Codex, now.AddHours(-1), "shared-name", "p", new(Total: 20), "b"));
store.Add(new(Provider.Claude, now.AddHours(-1), "shared-name", "p", new(Total: 30), "c")); store.Add(new(Provider.Claude, now.AddHours(-1), "shared-name", "p", new(Total: 30), "c"));
@@ -172,7 +172,7 @@ internal static class FakeData
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) }; var early = ahead with { Id = "secondary", 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()); 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]);
var snapshot = Snapshot(now) with { Providers = [Snapshot(now).Providers[1] with var snapshot = Snapshot(now) with { Providers = [Snapshot(now).Providers[1] with
@@ -192,9 +192,9 @@ internal static class FakeData
{ 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 EarlyResetModel() public static PanelViewModel EarlyResetModel()
{ {
var now = DateTimeOffset.UtcNow; var now = new FixedClock().GetUtcNow();
var transition = now.AddHours(-1); var transition = now.AddHours(-1);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), "finaltoken-early", Guid.NewGuid().ToString("N")), new DiagnosticLog()); var store = new HistoryStore(Path.Combine(Path.GetTempPath(), "finaltoken-early", Guid.NewGuid().ToString("N")), new DiagnosticLog(), new FixedClock(now));
var snapshot = Snapshot(now); var snapshot = Snapshot(now);
var codex = snapshot.Providers.Single(p => p.Provider == Provider.Codex); var codex = snapshot.Providers.Single(p => p.Provider == Provider.Codex);
var window = codex.Windows[0].Window with { UsedPercent = 2, ResetsAt = transition.AddDays(7), SampleTime = now }; var window = codex.Windows[0].Window with { UsedPercent = 2, ResetsAt = transition.AddDays(7), SampleTime = now };
@@ -208,8 +208,8 @@ internal static class FakeData
} }
public static PanelViewModel Model(bool unavailable = false) public static PanelViewModel Model(bool unavailable = false)
{ {
var now = DateTimeOffset.UtcNow; var now = new FixedClock().GetUtcNow();
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), "finaltoken-fake", Guid.NewGuid().ToString("N")), new DiagnosticLog()); var store = new HistoryStore(Path.Combine(Path.GetTempPath(), "finaltoken-fake", Guid.NewGuid().ToString("N")), new DiagnosticLog(), new FixedClock(now));
var snapshot = Snapshot(now, unavailable); var snapshot = Snapshot(now, unavailable);
foreach (var provider in snapshot.Providers) foreach (var provider in snapshot.Providers)
{ {
@@ -156,7 +156,7 @@ public sealed class LimitAnalysisTests
[Fact] public void ModelSeriesGroupsInOnePassAndMatchesTotals() [Fact] public void ModelSeriesGroupsInOnePassAndMatchesTotals()
{ {
using var directory = new TestDirectory(); using var directory = new TestDirectory();
var store = new HistoryStore(directory.Path, new DiagnosticLog()); var store = new HistoryStore(directory.Path, new DiagnosticLog(), new TestClock());
store.Add(new(Provider.Claude, Now.AddHours(-2), "a", "p", new(Total: 20), "a")); store.Add(new(Provider.Claude, Now.AddHours(-2), "a", "p", new(Total: 20), "a"));
store.Add(new(Provider.Claude, Now.AddHours(-2), "b", "p", new(Total: 30), "b")); store.Add(new(Provider.Claude, Now.AddHours(-2), "b", "p", new(Total: 30), "b"));
store.Add(new(Provider.Claude, Now.AddHours(-1), "a", "p", new(Total: 40), "c")); store.Add(new(Provider.Claude, Now.AddHours(-1), "a", "p", new(Total: 40), "c"));
+2 -2
View File
@@ -90,11 +90,11 @@ public class ReworkTests
using var directory = new TestDirectory(); using var directory = new TestDirectory();
var source = directory.Write("claude/projects/p/a.jsonl", Fixtures.Claude()); var source = directory.Write("claude/projects/p/a.jsonl", Fixtures.Claude());
var log = new DiagnosticLog(); var log = new DiagnosticLog();
var store = new HistoryStore(directory.Path, log); var store = new HistoryStore(directory.Path, log, new TestClock());
var scanner = new IncrementalScanner(store, log, Path.Combine(directory.Path, "claude"), directory.Path); var scanner = new IncrementalScanner(store, log, Path.Combine(directory.Path, "claude"), directory.Path);
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents); Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
await store.SaveAsync(TestContext.Current.CancellationToken); await store.SaveAsync(TestContext.Current.CancellationToken);
store = new(directory.Path, log); store = new(directory.Path, log, new TestClock());
scanner = new(store, log, Path.Combine(directory.Path, "claude"), directory.Path); scanner = new(store, log, Path.Combine(directory.Path, "claude"), directory.Path);
using var exclusive = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.None); using var exclusive = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.None);
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents); Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
+6 -6
View File
@@ -10,14 +10,14 @@ public class StorageTests
{ {
using var directory = new TestDirectory(); using var directory = new TestDirectory();
var source = directory.Write("claude/projects/p/session.jsonl", Fixtures.Claude()); var source = directory.Write("claude/projects/p/session.jsonl", Fixtures.Claude());
var history = new HistoryStore(directory.Path, new()); var history = new HistoryStore(directory.Path, new(), new TestClock());
var scanner = new IncrementalScanner(history, new(), Path.Combine(directory.Path, "claude"), Path.Combine(directory.Path, "codex")); var scanner = new IncrementalScanner(history, new(), Path.Combine(directory.Path, "claude"), Path.Combine(directory.Path, "codex"));
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents); Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents); Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
await File.AppendAllTextAsync(source, Fixtures.Claude("b"), cancellationToken: TestContext.Current.CancellationToken); await File.AppendAllTextAsync(source, Fixtures.Claude("b"), cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents); Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
await history.SaveAsync(TestContext.Current.CancellationToken); await history.SaveAsync(TestContext.Current.CancellationToken);
history = new(directory.Path, new()); history = new(directory.Path, new(), new TestClock());
scanner = new(history, new(), Path.Combine(directory.Path, "claude"), Path.Combine(directory.Path, "codex")); scanner = new(history, new(), Path.Combine(directory.Path, "claude"), Path.Combine(directory.Path, "codex"));
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents); Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
await File.WriteAllTextAsync(source, Fixtures.Claude(), cancellationToken: TestContext.Current.CancellationToken); await File.WriteAllTextAsync(source, Fixtures.Claude(), cancellationToken: TestContext.Current.CancellationToken);
@@ -36,7 +36,7 @@ public class StorageTests
using var directory = new TestDirectory(); using var directory = new TestDirectory();
var fixture = Fixtures.Claude(); var fixture = Fixtures.Claude();
var source = directory.Write("claude/projects/p/session.jsonl", fixture[..30]); var source = directory.Write("claude/projects/p/session.jsonl", fixture[..30]);
var history = new HistoryStore(directory.Path, new()); var history = new HistoryStore(directory.Path, new(), new TestClock());
var scanner = new IncrementalScanner(history, new(), Path.Combine(directory.Path, "claude"), directory.Path); var scanner = new IncrementalScanner(history, new(), Path.Combine(directory.Path, "claude"), directory.Path);
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents); Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
await File.AppendAllTextAsync(source, fixture[30..], cancellationToken: TestContext.Current.CancellationToken); await File.AppendAllTextAsync(source, fixture[30..], cancellationToken: TestContext.Current.CancellationToken);
@@ -79,7 +79,7 @@ public class StorageTests
using var directory = new TestDirectory(); using var directory = new TestDirectory();
directory.Write("claude/projects/p/a.jsonl", "{\n" + Fixtures.Claude()); directory.Write("claude/projects/p/a.jsonl", "{\n" + Fixtures.Claude());
var log = new DiagnosticLog(); var log = new DiagnosticLog();
var scanner = new IncrementalScanner(new(directory.Path, log), log, Path.Combine(directory.Path, "claude"), directory.Path); var scanner = new IncrementalScanner(new(directory.Path, log, new TestClock()), log, Path.Combine(directory.Path, "claude"), directory.Path);
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents); Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
Assert.Single(log.Recent); Assert.Single(log.Recent);
} }
@@ -89,7 +89,7 @@ public class StorageTests
using var directory = new TestDirectory(); using var directory = new TestDirectory();
var line = Fixtures.Claude().Replace("{\"type\"", "{\"padding\":\"" + new string('x', 4 * 1024 * 1024) + "\",\"type\""); var line = Fixtures.Claude().Replace("{\"type\"", "{\"padding\":\"" + new string('x', 4 * 1024 * 1024) + "\",\"type\"");
directory.Write("claude/projects/p/large.jsonl", line); directory.Write("claude/projects/p/large.jsonl", line);
var scanner = new IncrementalScanner(new(directory.Path, new()), new(), Path.Combine(directory.Path, "claude"), directory.Path); var scanner = new IncrementalScanner(new(directory.Path, new(), new TestClock()), new(), Path.Combine(directory.Path, "claude"), directory.Path);
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents); Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
} }
[Fact] [Fact]
@@ -159,7 +159,7 @@ public class StorageTests
public void QueriesAggregateByHourDayModelProjectAndLimitWindow() public void QueriesAggregateByHourDayModelProjectAndLimitWindow()
{ {
using var directory = new TestDirectory(); using var directory = new TestDirectory();
var history = new HistoryStore(directory.Path, new()); var history = new HistoryStore(directory.Path, new(), new TestClock());
var now = new DateTimeOffset(2026, 10, 14, 16, 30, 0, TimeSpan.Zero); var now = new DateTimeOffset(2026, 10, 14, 16, 30, 0, TimeSpan.Zero);
history.Add(new(Provider.Claude, now.AddHours(-1), "a", "/one", new(Total: 10), "a")); history.Add(new(Provider.Claude, now.AddHours(-1), "a", "/one", new(Total: 10), "a"));
history.Add(new(Provider.Claude, now, "b", "/two", new(Total: 20), "b")); history.Add(new(Provider.Claude, now, "b", "/two", new(Total: 20), "b"));