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

The headless forecast test failed from 2026-10-16 on because the panel
read the real clock while its fixture fixes the time.

- App: PanelWindow takes an optional TimeProvider (the system clock by
  default) and passes it to the pace bar, burn-up, peak and usage charts
  and every forecast label. The burn-up chart uses the panel's render
  time as now.
- Tests: headless panels run on a fixed clock at fixture time, with a
  check before, at and after the forecast start. App and Core tests
  with fixed-date Claude events pin HistoryStore's clock, so the 60-day
  retention cannot drop them later.

Closes #11
This commit was merged in pull request #12.
This commit is contained in:
2026-10-17 09:28:15 +02:00
parent adb8f5b88d
commit d5ad3ecee9
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 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).
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.
Stream Deck policy and the real installer come through IPluginInstaller (D11).
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;
public sealed class BurnUpChart(LimitChart chart) : Decorator
public sealed class BurnUpChart(LimitChart chart, TimeProvider? clock = null) : Decorator
{
private Rect plot;
private double? crosshair;
@@ -13,7 +13,7 @@ public sealed class BurnUpChart(LimitChart chart) : Decorator
protected override void OnInitialized()
{
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)),
HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center,
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";
}
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("Source", used is null ? "No baseline" : source)));
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;
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)
{
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));
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.Reset), new(Math.Max(plot.Left, plot.Right - 120), 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, clock), new(Math.Max(plot.Left, plot.Right - 120), plot.Bottom + 12), muted);
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));
@@ -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 = [];
protected override void OnInitialized()
@@ -119,9 +119,9 @@ public sealed class InstancePeaks(IReadOnlyList<LimitInstance> instances, Provid
PointerMoved += (_, e) =>
{
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(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")));
};
}
+4 -3
View File
@@ -40,6 +40,7 @@ public sealed class UsageChart : Control
}
public IReadOnlyList<ChartValue> Values { get; init; } = [];
public IReadOnlyList<string> SeriesNames { get; init; } = [];
public TimeProvider Clock { get; init; } = TimeProvider.System;
public bool Percent { get; init; }
public Provider LimitProvider { get; init; }
public ChartValue? Forecast { get; init; }
@@ -94,7 +95,7 @@ public sealed class UsageChart : Control
{
var start = ForecastStart ?? tail;
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
@@ -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
{ 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);
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);
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);
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 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) &&
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)
=> ChartTime(time, interval).ToString(interval >= TimeSpan.FromDays(1) ? "MM-dd" : "MM-dd HH:mm");
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;
return value.ToString(format) + new[] { "", " K", " M", " B" }[unit];
}
public static string Forecast(DateTimeOffset date, PaceState state) =>
(state == PaceState.Ahead ? "⚠ " : "At this pace ") + "100 % on " + Projection(date);
public static string Forecast(DateTimeOffset date, PaceState state, TimeProvider? clock = null) =>
(state == PaceState.Ahead ? "⚠ " : "At this pace ") + "100 % on " + Projection(date, clock);
public static string State(PaceState state) => state switch { PaceState.OnTrack => "✓ On track", PaceState.Ahead => "▲ Ahead", PaceState.Behind => "▼ Behind", _ => "? Pace unknown" };
}
+13 -11
View File
@@ -11,6 +11,7 @@ namespace FinalToken.App;
public sealed class PanelWindow : Window
{
private readonly PanelViewModel model;
private readonly TimeProvider clock;
private readonly StackPanel body = new() { Spacing = 24, Margin = new Thickness(24) };
private readonly StackPanel statuses = new() { Orientation = Orientation.Horizontal, Spacing = 8 };
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 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.clock = clock ?? TimeProvider.System;
Title = $"FinalToken {typeof(Program).Assembly.GetName().Version?.ToString(3)}";
Width = 1280; Height = 900; MinWidth = 960; MinHeight = 500; Ui.Theme(this);
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);
var content = new List<Control>();
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;
ToolTip.SetTip(updated, model.Snapshot?.MadeAt.LocalDateTime.ToString("F"));
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();
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(),
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));
var windows = h.Limits.Where(l => l.Analysis?.Current.HasData == true).ToArray();
if (windows.Length > 0)
{
content.Add(Ui.Text("Window charts", 20));
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("Past instances · peak use", 12, "Muted"), new InstancePeaks(limit.Analysis!.Past, limit.Provider)))), wide));
Ui.Text("Measured · dashed: estimated · faint: previous · dotted: forecast", 12, "Muted"), new BurnUpChart(limit with { Now = now }, clock),
Ui.Text("Past instances · peak use", 12, "Muted"), new InstancePeaks(limit.Analysis!.Past, limit.Provider, clock)))), wide));
}
content.Add(Ui.Text("Breakdown", 20));
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 chip = new Border { Child = Ui.Mark(Display.State(pace.State), Brush.Parse("#0b0b0b")), Background = PaceBar.Colour(pace.State), CornerRadius = new CornerRadius(6), Padding = new Thickness(8, 4) };
DockPanel.SetDock(chip, Dock.Right); title.Children.Add(chip); title.Children.Add(Ui.Text(w.Provider + " · " + w.Label, 15));
var card = Ui.Stack(title, Ui.Text($"{w.UsedPercent:0.#} %", 36), Ui.Text("used", 12, "Muted"), new PaceBar(window) { Height = 10 });
card.Children.Add(Ui.Text(w.ResetsAt is { } reset ? $"Resets in {Display.Duration(reset - now)} · {Display.Projection(reset)}" : "Reset unknown", 13, "Secondary"));
var card = Ui.Stack(title, Ui.Text($"{w.UsedPercent:0.#} %", 36), Ui.Text("used", 12, "Muted"), new PaceBar(window, now) { Height = 10 });
card.Children.Add(Ui.Text(w.ResetsAt is { } reset ? $"Resets in {Display.Duration(reset - now)} · {Display.Projection(reset, clock)}" : "Reset unknown", 13, "Secondary"));
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)
{
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)
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"));
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);
}
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"));
var tile = Ui.Card(card); tile.Name = $"LimitTile-{w.Provider}-{w.Id}";
ToolTip.SetTip(tile, new DataTooltip(w.Provider + " · " + w.Label, new("Used", $"{w.UsedPercent:0.##} %"), new("Expected", $"{pace.ElapsedFraction * 100:0.##} %"),
new("State", Display.State(pace.State)), new("Reset", w.ResetsAt is { } r ? Display.Projection(r) : "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)
{