Files
FinalToken/tests/FinalToken.App.Tests/HeadlessTests.cs
T
schmidt.florian 82fece85f5 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
2026-10-18 11:12:38 +02:00

488 lines
42 KiB
C#

using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Headless;
using Avalonia.Interactivity;
using Avalonia.Media.Imaging;
using Avalonia.Styling;
using Avalonia.Themes.Fluent;
using Avalonia.Threading;
using Avalonia.VisualTree;
using FinalToken.Core;
using FinalToken.Core.StreamDeck;
using Xunit;
namespace FinalToken.App.Tests;
public sealed class HeadlessTests
{
[Fact]
public async Task ViewsRenderAndInteractionsApplySettingsAndPopupActions()
{
var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var thread = new Thread(() =>
{
try
{
AppBuilder.Configure<TestApplication>().UseSkia().UseHarfBuzz().UseHeadless(new() { UseHeadlessDrawing = false }).SetupWithoutStarting();
var root = new DirectoryInfo(AppContext.BaseDirectory);
while (root.Parent is not null && !File.Exists(Path.Combine(root.FullName, "FinalToken.slnx"))) root = root.Parent;
var shots = Environment.GetEnvironmentVariable("FINALTOKEN_SCREENSHOT_DIR") ?? Path.Combine(root.Parent!.FullName, "runs", "shots", "app");
Directory.CreateDirectory(shots);
var model = FakeData.Model();
var clock = new FixedClock(model.Snapshot!.MadeAt);
var panel = new PanelWindow(model, () => { }, () => { }, () => { }, () => { }, clock);
panel.Resources["SystemAccentColor"] = Avalonia.Media.Colors.Red;
panel.RequestedThemeVariant = ThemeVariant.Light; panel.Show(); Save(panel, "panel-light.png");
Assert.Equal($"FinalToken {typeof(Program).Assembly.GetName().Version!.ToString(3)}", panel.Title);
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Claude");
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Tokens per day");
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "●" && t.Foreground?.ToString() == "#ffeb6834");
Assert.All(panel.GetVisualDescendants().OfType<ProgressBar>(), bar => Assert.True(bar.Bounds.Width <= 140, $"Share bar width {bar.Bounds.Width}"));
Assert.Single(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Current session");
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.StartsWith("At this pace 100 % on ", StringComparison.Ordinal) == true);
Assert.Single(panel.GetVisualDescendants().OfType<WrapPanel>(), p => p.Name == "CompositionLegend");
var codexTile = panel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-secondary");
Assert.DoesNotContain(codexTile.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.Contains('⚠') == true || t.Foreground?.ToString() == "#ffd03b3b");
var withCache = panel.GetVisualDescendants().OfType<UsageChart>().Where(c => !c.Percent).Sum(c => c.Values.Sum(v => v.Value));
panel.GetVisualDescendants().OfType<CheckBox>().Single(c => c.Content as string == "Include cache reads").IsChecked = false;
Dispatcher.UIThread.RunJobs();
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == Display.Compact(61000000));
Assert.True(panel.GetVisualDescendants().OfType<UsageChart>().Where(c => !c.Percent).Sum(c => c.Values.Sum(v => v.Value)) < withCache);
model.IncludeCacheReads = true; Dispatcher.UIThread.RunJobs();
var originalSnapshot = model.Snapshot!;
var originalHistory = model.History;
var claude = originalSnapshot.Providers.Single(p => p.Provider == Provider.Claude);
var week = claude.Windows.Single(w => w.Window.Id == "week");
model.Snapshot = originalSnapshot with { Providers = originalSnapshot.Providers.Select(p => p.Provider == Provider.Claude
? p with { Windows = p.Windows.Append(week with { Window = week.Window with { Id = "fable", Label = "Week · Fable" } }).ToArray() } : p).ToArray() };
model.History = originalHistory with { Details = originalHistory.Details.Append(originalHistory.Details.Single(d => d.Provider == Provider.Claude && d.Id == "week") with { Id = "fable" }).ToArray() };
Dispatcher.UIThread.RunJobs();
panel.GetVisualDescendants().OfType<ComboBox>().Single().SelectedIndex = 1;
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Claude · Week · Fable");
var wheelSelector = panel.GetVisualDescendants().OfType<ComboBox>().Single();
var wheelViewport = panel.GetVisualDescendants().OfType<ScrollViewer>().First();
Dispatcher.UIThread.RunJobs(); using (panel.CaptureRenderedFrame()) { }
var maximumOffset = wheelViewport.Extent.Height - wheelViewport.Viewport.Height;
const double scrollRoom = 80;
Assert.True(maximumOffset > scrollRoom * 2);
var selectorTop = wheelSelector.TranslatePoint(default, wheelViewport)!.Value.Y + wheelViewport.Offset.Y;
// BringIntoView can leave offset zero with Linux fonts. Centre the selector with room both ways.
var centredOffset = selectorTop - (wheelViewport.Viewport.Height - wheelSelector.Bounds.Height) / 2;
wheelViewport.Offset = new Vector(0, Math.Clamp(centredOffset, scrollRoom, maximumOffset - scrollRoom));
Dispatcher.UIThread.RunJobs(); wheelSelector.Focus();
foreach (var direction in new[] { 1, -1 })
{
using (panel.CaptureRenderedFrame()) { }
var selectorY = wheelSelector.TranslatePoint(default, wheelViewport)!.Value.Y;
Assert.InRange(selectorY, 0, wheelViewport.Viewport.Height - wheelSelector.Bounds.Height);
var beforeWheel = wheelViewport.Offset.Y;
Assert.InRange(beforeWheel, 1, maximumOffset - 1);
panel.MouseWheel(wheelSelector.TranslatePoint(new Point(20, 16), panel)!.Value, new Vector(0, direction));
Dispatcher.UIThread.RunJobs();
Assert.Equal(1, wheelSelector.SelectedIndex);
Assert.True(direction > 0 ? wheelViewport.Offset.Y < beforeWheel : wheelViewport.Offset.Y > beforeWheel,
$"Wheel {direction}: before={beforeWheel}, after={wheelViewport.Offset.Y}");
}
foreach (var segment in panel.GetVisualDescendants().OfType<ToggleButton>().Where(b => b.Classes.Contains("segment")))
{
segment.Focus(); var rangeBefore = model.Range; var providerBefore = model.ProviderFilter;
panel.MouseWheel(segment.TranslatePoint(new Point(8, 8), panel)!.Value, new Vector(0, -1));
Assert.Equal(rangeBefore, model.Range); Assert.Equal(providerBefore, model.ProviderFilter);
}
wheelViewport.Offset = default;
model.History = originalHistory;
model.Snapshot = originalSnapshot with { Providers = originalSnapshot.Providers.Select(p => p.Provider == Provider.Claude ? p with { Windows = [] } : p).ToArray() };
Dispatcher.UIThread.RunJobs();
Assert.Single(panel.GetVisualDescendants().OfType<DailyLimitChart>());
model.Snapshot = originalSnapshot; Dispatcher.UIThread.RunJobs();
var filters = panel.GetVisualDescendants().OfType<ToggleButton>().Where(b => b is not CheckBox).ToArray();
filters[4].IsChecked = true; filters[7].IsChecked = true;
Assert.Equal(HistoryRange.All, model.Range); Assert.Equal(Provider.Codex, model.ProviderFilter);
filters[1].IsChecked = true; filters[5].IsChecked = true;
panel.RequestedThemeVariant = ThemeVariant.Dark; Save(panel, "panel-dark.png");
foreach (var (width, height) in new[] { (1280, 900), (1500, 1000) })
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
panel.Width = width; panel.Height = height; panel.RequestedThemeVariant = theme;
var stem = $"panel-{width}x{height}-{theme.ToString().ToLowerInvariant()}";
var viewport = panel.GetVisualDescendants().OfType<ScrollViewer>().First();
viewport.Offset = default; Save(panel, stem + "-limits.png");
var selected = panel.GetVisualDescendants().OfType<ToggleButton>().First(b => b.Classes.Contains("segment") && b.IsChecked == true);
Assert.Equal(theme == ThemeVariant.Dark ? "#ff383835" : "#ffe1e0d9", selected.Background?.ToString());
Assert.Equal(Avalonia.Media.FontWeight.SemiBold, selected.FontWeight);
selected.Focus(Avalonia.Input.NavigationMethod.Tab); Dispatcher.UIThread.RunJobs();
Assert.Equal(theme == ThemeVariant.Dark ? "#fff0efec" : "#ff0b0b0b", selected.BorderBrush?.ToString());
var neutralCheck = panel.GetVisualDescendants().OfType<NeutralCheckBox>().Single();
neutralCheck.Focus(Avalonia.Input.NavigationMethod.Tab); Dispatcher.UIThread.RunJobs();
Assert.Equal(theme == ThemeVariant.Dark ? "#fff0efec" : "#ff0b0b0b", neutralCheck.BorderBrush?.ToString());
Assert.True(neutralCheck.MarkVisible);
var glyph = panel.GetVisualDescendants().OfType<TextBlock>().Single(t => t.Name == "NeutralCheckGlyph");
Assert.Equal(theme == ThemeVariant.Dark ? "#fff0efec" : "#ff0b0b0b", glyph.Foreground?.ToString());
Assert.Equal(56, panel.GetVisualDescendants().OfType<Grid>().Single(g => g.Name == "PanelHeader").Bounds.Height);
if (width == 1500)
{
var sessionTile = panel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Claude-session");
var weekTile = panel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Claude-week");
var codexLimit = panel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-secondary");
Assert.Equal(sessionTile.Bounds.Y, weekTile.Bounds.Y); Assert.Equal(weekTile.Bounds.Y, codexLimit.Bounds.Y);
Assert.True(sessionTile.Bounds.Height < weekTile.Bounds.Height);
}
foreach (var (name, target) in new[] { ("week", "Week use per day"), ("tokens", "Tokens"), ("windows", "Window charts"), ("breakdown", "Breakdown") })
{
var text = panel.GetVisualDescendants().OfType<TextBlock>().First(t => t.Text == target);
var position = text.TranslatePoint(default, viewport)!.Value;
viewport.Offset = new Vector(0, viewport.Offset.Y + position.Y - 16);
Save(panel, stem + "-" + name + ".png");
if (name == "breakdown")
{
panel.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == "Show all 110").RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
Save(panel, stem + "-breakdown-expanded.png");
Assert.Contains(panel.GetVisualDescendants().OfType<Button>(), b => b.Content as string == "Show top 8");
panel.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == "Show top 8").RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
}
}
var prior = viewport.Offset;
model.Snapshot = model.Snapshot! with { MadeAt = clock.GetUtcNow() }; Dispatcher.UIThread.RunJobs();
Assert.Equal(prior, viewport.Offset);
}
var budgetModel = FakeData.BudgetModel();
var budgetSnapshot = budgetModel.Snapshot!;
var budgetClock = new FixedClock(budgetSnapshot.MadeAt);
var budgetPanel = new PanelWindow(budgetModel, () => { }, () => { }, () => { }, () => { }, budgetClock) { Width = 1280, Height = 1000 };
budgetPanel.Show(); Dispatcher.UIThread.RunJobs();
string[] Rows(Provider provider, string id = "week") => ((StackPanel)budgetPanel.GetVisualDescendants().OfType<Border>()
.Single(b => b.Name == $"LimitTile-{provider}-{id}").Child!).Children.Select(c => c.Name!).ToArray();
string[] longRows = ["Title", "Percent", "Used", "Pace", "Reset", "Forecast", "Recent", "Today", "Plan"];
Assert.Equal(longRows, Rows(Provider.Claude)); Assert.Equal(longRows, Rows(Provider.Codex));
Assert.Contains(budgetPanel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Limit week");
Assert.Contains(budgetPanel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Calendar week");
Assert.Contains(budgetPanel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "since Mon 00:00");
var tokenTiles = budgetPanel.GetVisualDescendants().OfType<StackPanel>().Where(p => p.Name?.StartsWith("TokenTile-", StringComparison.Ordinal) == true).ToArray();
Assert.All(tokenTiles, tile => Assert.Equal(tokenTiles[0].Bounds.Height, tile.Bounds.Height));
var limitTokens = tokenTiles.Single(t => t.Name == "TokenTile-Claude-Limit-week");
Assert.Contains(limitTokens.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "since " + TimeZoneInfo.ConvertTime(budgetSnapshot.Providers[0].WeekStart, budgetClock.LocalTimeZone).ToString("ddd HH:mm"));
Assert.Contains("Limit week", Assert.IsType<DataTooltip>(ToolTip.GetTip(limitTokens)).Title);
Assert.Contains("since ", Assert.IsType<DataTooltip>(ToolTip.GetTip(limitTokens)).Title);
foreach (var dayChart in budgetPanel.GetVisualDescendants().OfType<DailyLimitChart>())
{
Assert.Contains("from " + Display.Time(budgetSnapshot.Providers[0].WeekStart, budgetClock), dayChart.AxisLabels[0]);
Assert.Contains("reset " + Display.Time(budgetSnapshot.Providers[0].WeekStart.AddDays(7), budgetClock), dayChart.AxisLabels[^1]);
}
var partialDay = budgetModel.History.Details[0].Days!.Current[0];
var partialTip = DataTooltip.Day(partialDay);
Assert.Contains(partialTip.Rows, r => r.Label == "Share");
Assert.Contains(partialTip.Rows, r => r.Label == "Even pace");
Assert.Contains(partialTip.Rows, r => r.Label == "Budget");
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
budgetPanel.RequestedThemeVariant = theme;
var viewport = budgetPanel.GetVisualDescendants().OfType<ScrollViewer>().First(); viewport.Offset = default;
Save(budgetPanel, $"budget-1280x1000-{theme}-limits.png");
foreach (var (name, target) in new[] { ("week", "Week use per day"), ("tokens", "Tokens") })
{
var heading = budgetPanel.GetVisualDescendants().OfType<TextBlock>().First(t => t.Text == target);
viewport.Offset = new Vector(0, viewport.Offset.Y + heading.TranslatePoint(default, viewport)!.Value.Y - 16);
Save(budgetPanel, $"budget-1280x1000-{theme}-{name}.png");
}
}
budgetModel.Snapshot = budgetSnapshot with { Providers = budgetSnapshot.Providers.Select(p => p.Provider == Provider.Codex
? p with { Windows = p.Windows.Select(w => w with { Window = w.Window with { SampleTime = budgetClock.GetUtcNow().AddMinutes(-15) } }).ToArray() }
: p).ToArray() };
Dispatcher.UIThread.RunJobs();
Assert.Equal(longRows, Rows(Provider.Claude)); Assert.Equal(longRows, Rows(Provider.Codex));
var staleWeek = budgetPanel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-week");
var freshWeek = budgetPanel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Claude-week");
var staleUsed = staleWeek.GetVisualDescendants().OfType<TextBlock>().Single(t => t.Name == "Used");
Assert.Equal("used · ⚠ sample 15 min old", staleUsed.Text);
Assert.Equal(12, staleUsed.FontSize); Assert.Equal("#ff898781", staleUsed.Foreground?.ToString());
Assert.Equal("used", freshWeek.GetVisualDescendants().OfType<TextBlock>().Single(t => t.Name == "Used").Text);
budgetPanel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = default;
SaveThemes(budgetPanel, "budget-stale-1280x1000");
budgetModel.History = new([], [], [], [], []);
budgetModel.Snapshot = budgetSnapshot with { Providers = budgetSnapshot.Providers.Select(p =>
{
var w = p.Windows[0].Window with { UsedPercent = 1, ResetsAt = p.Provider == Provider.Claude ? budgetClock.GetUtcNow().AddDays(7).AddHours(-1) : null };
var shortWindow = w with { Id = "session", Label = "Session", Length = TimeSpan.FromHours(5),
ResetsAt = p.Provider == Provider.Claude ? budgetClock.GetUtcNow().AddHours(5).AddMinutes(-1) : null };
return p with { Windows = [new(w, Pace.Calculate(w, budgetClock.GetUtcNow())), new(shortWindow, Pace.Calculate(shortWindow, budgetClock.GetUtcNow()))] };
}).ToArray() };
Dispatcher.UIThread.RunJobs();
Assert.Equal(longRows, Rows(Provider.Claude)); Assert.Equal(longRows, Rows(Provider.Codex));
Assert.Equal(longRows.Take(7), Rows(Provider.Claude, "session"));
Assert.Equal(Rows(Provider.Claude, "session"), Rows(Provider.Codex, "session"));
Assert.Contains(budgetPanel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "No forecast: pace unknown");
Assert.Contains(budgetPanel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Recent rate needs 3 h of samples");
Assert.Contains(budgetPanel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.StartsWith("Recent rate from ", StringComparison.Ordinal) == true);
Assert.Contains(budgetPanel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Today · collecting a day baseline");
budgetPanel.Close();
var forecastModel = FakeData.ForecastModel();
var forecastClock = new FixedClock(forecastModel.Snapshot!.MadeAt);
var forecastPanel = new PanelWindow(forecastModel, () => { }, () => { }, () => { }, () => { }, forecastClock);
forecastPanel.Show(); Dispatcher.UIThread.RunJobs();
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 == "⚠ ");
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 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));
var aheadWindow = forecastModel.Snapshot!.Providers[0].Windows[0];
var earlyAlert = new PopupDecider().Observe(aheadWindow.Window, aheadWindow.Pace, new Settings());
Assert.NotNull(earlyAlert);
var earlyPopup = PopupWindow.Pace(earlyAlert, () => { }); earlyPopup.Show();
Assert.Contains(earlyPopup.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.Contains("⚠ 100 % on ") == true);
earlyPopup.Close();
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
forecastPanel.Width = 1280; forecastPanel.Height = 900; forecastPanel.RequestedThemeVariant = theme;
var viewport = forecastPanel.GetVisualDescendants().OfType<ScrollViewer>().First(); viewport.Offset = default;
Save(forecastPanel, $"forecast-1280x900-{theme}-limits.png");
var heading = forecastPanel.GetVisualDescendants().OfType<TextBlock>().First(t => t.Text == "Window charts");
viewport.Offset = new Vector(0, viewport.Offset.Y + heading.TranslatePoint(default, viewport)!.Value.Y - 16);
Save(forecastPanel, $"forecast-1280x900-{theme}-windows.png");
var charts = forecastPanel.GetVisualDescendants().OfType<BurnUpChart>().ToArray();
Assert.Equal(2, charts.Length);
Assert.True(DrawsForecast(charts[0])); Assert.False(DrawsForecast(charts[1]));
}
forecastPanel.Close();
var earlyModel = FakeData.EarlyResetModel();
var earlyPanel = new PanelWindow(earlyModel, () => { }, () => { }, () => { }, () => { }, new FixedClock(earlyModel.Snapshot!.MadeAt));
earlyPanel.Show();
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.Null(Assert.Single(earlyModel.History.Limits).Forecast);
Assert.All(Assert.Single(earlyModel.History.Limits).Analysis!.Past, instance => Assert.True(instance.End <= earlyModel.Snapshot!.MadeAt));
foreach (var (width, height) in new[] { (1280, 900), (1500, 1000) })
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
earlyPanel.Width = width; earlyPanel.Height = height; earlyPanel.RequestedThemeVariant = theme;
var viewport = earlyPanel.GetVisualDescendants().OfType<ScrollViewer>().First(); viewport.Offset = default;
Save(earlyPanel, $"panel-{width}x{height}-{theme}-early-limits.png");
var heading = earlyPanel.GetVisualDescendants().OfType<TextBlock>().First(t => t.Text == "Window charts");
viewport.Offset = new Vector(0, viewport.Offset.Y + heading.TranslatePoint(default, viewport)!.Value.Y - 16);
Save(earlyPanel, $"panel-{width}x{height}-{theme}-early-windows.png");
}
earlyPanel.Close();
panel.Width = 1000; panel.Height = 900;
panel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = default; Save(panel, "panel-1000x900-light.png");
panel.Width = 1500; panel.Height = 1000;
model.History = originalHistory with { Details = originalHistory.Details.Select(d => d.Provider == Provider.Claude && d.Days is { } days
? d with { Days = days with { Current = days.Current.Select(day => day with { Used = null }).ToArray(), Today = null } } : d).ToArray() };
Dispatcher.UIThread.RunJobs(); Assert.Single(panel.GetVisualDescendants().OfType<DailyLimitChart>());
foreach (var (width, height) in new[] { (1280, 900), (1500, 1000) })
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
panel.Width = width; panel.Height = height; panel.RequestedThemeVariant = theme; Dispatcher.UIThread.RunJobs();
var viewport = panel.GetVisualDescendants().OfType<ScrollViewer>().First();
var heading = panel.GetVisualDescendants().OfType<TextBlock>().First(t => t.Text == "Week use per day");
viewport.Offset = new Vector(0, viewport.Offset.Y + heading.TranslatePoint(default, viewport)!.Value.Y - 16);
Save(panel, $"panel-{width}x{height}-{theme}-collecting-days.png");
}
model.History = originalHistory;
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
var weekData = originalHistory.Details.Single(d => d.Provider == Provider.Claude && d.Id == "week").Days!;
Assert.Contains(weekData.Current, d => d.Origin == UseOrigin.Estimated);
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");
var types = new (string Name, DataTooltip Tip)[]
{
("day-estimated", DataTooltip.Day(weekData.Current.First(d => d.Origin == UseOrigin.Estimated))),
("day-measured", DataTooltip.Day(weekData.Current.Last(d => d.Used is not null && d.Origin == UseOrigin.Measured))),
("future-day", future),
("project", DataTooltip.Tokens("D:/Projects/Customer/Workspace/Project-with-a-long-name", new(100000000, 1900000000, 10000000, 53670717, 1234567, 2063670717))),
("tile", (DataTooltip)ToolTip.GetTip(panel.GetVisualDescendants().OfType<Border>().First(b => b.Name == "LimitTile-Claude-week"))!),
("tokens", DataTooltip.Tokens("Claude - Calendar week", originalSnapshot.Providers[0].Week)),
};
var limit = originalHistory.Limits.Single(l => l.Provider == Provider.Claude && l.Window!.Window.Id == "week");
CaptureChartTip("burnup", new BurnUpChart(limit, clock), new Point(240, 100));
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, clock), new Point(600, 30));
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("composition", new CompositionBar(originalSnapshot.Providers[0].Week, Provider.Claude, true) { Height = 8 }, new Point(100, 4));
void CaptureChartTip(string name, Control chartControl, Point hover)
{
var window = new Window { Width = 740, Height = 600, RequestedThemeVariant = theme }; Ui.Theme(window);
var content = Ui.Stack(Ui.Text(name, 20), chartControl); content.Margin = new Thickness(24); window.Content = content;
window.Show(); Dispatcher.UIThread.RunJobs(); using (window.CaptureRenderedFrame()) { }
window.MouseMove(chartControl.TranslatePoint(hover, window)!.Value);
var actualTip = Assert.IsType<DataTooltip>(ToolTip.GetTip(chartControl));
window.MouseMove(new Point(0, 0)); ToolTip.SetIsOpen(chartControl, false);
content.Children.Add(new DataTooltip(actualTip.Title, actualTip.Rows.ToArray()));
Save(window, $"tooltip-{name}-{theme}.png"); window.Close();
}
foreach (var (name, tip) in types)
{
var tooltipWindow = new Window { Width = 620, Height = 300, RequestedThemeVariant = theme };
Ui.Theme(tooltipWindow); tooltipWindow.Content = new Border { Child = tip, Padding = new Thickness(24), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
tooltipWindow.Show(); Save(tooltipWindow, $"tooltip-{name}-{theme}.png"); tooltipWindow.Close();
}
}
model.Snapshot = FakeData.Snapshot(clock.GetUtcNow(), true);
Dispatcher.UIThread.RunJobs(); panel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = default;
Save(panel, "panel-unavailable.png");
foreach (var (width, height) in new[] { (1280, 900), (1500, 1000) })
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
panel.Width = width; panel.Height = height; panel.RequestedThemeVariant = theme;
panel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = default;
Save(panel, $"panel-{width}x{height}-{theme}-unavailable.png");
}
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();
expander.BringIntoView(); Save(panel, "panel-diagnostics-collapsed.png");
expander.IsExpanded = true; panel.UpdateLayout();
panel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = new Vector(0, 100000);
Save(panel, "panel-diagnostics-expanded.png"); panel.Close();
string? folder = null; var quitCalls = 0; var saveCalls = 0;
var actions = new SettingsWindow(new(), new(PluginInstallState.NoHostFound), _ => { saveCalls++; return Task.CompletedTask; }, () => quitCalls++, path => folder = path);
actions.Show();
void ClickSettings(string text) => actions.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == text).RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
ClickSettings("Open folder"); Assert.Equal(DataPaths.DataDirectory, folder);
ClickSettings("Quit FinalToken"); Assert.Equal(1, quitCalls);
ClickSettings("Cancel"); Assert.False(actions.IsVisible); Assert.Equal(0, saveCalls);
Settings? saved = null;
var initial = new Settings { StartWithOs = true, StreamDeckInstallMode = InstallMode.Automatic, DismissedPluginVersion = "0.9" };
var settings = new SettingsWindow(initial, new(PluginInstallState.Outdated, "1.0", "0.9"), value => { saved = value; return Task.CompletedTask; }, () => { });
settings.Show(); Save(settings, "settings.png");
var providerNames = settings.GetVisualDescendants().OfType<CheckBox>().Select(c => c.Name).ToArray();
Assert.Equal(providerNames.Length, providerNames.Distinct().Count());
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
settings.RequestedThemeVariant = theme;
var viewport = settings.GetVisualDescendants().OfType<ScrollViewer>().First();
viewport.Offset = default; Save(settings, $"settings-{theme}-general.png");
viewport.Offset = new Vector(0, 10000); Save(settings, $"settings-{theme}-providers.png");
}
var refresh = settings.GetVisualDescendants().OfType<NumericUpDown>().First(); refresh.Value = 25;
settings.GetVisualDescendants().OfType<CheckBox>().Single(c => c.Content as string == "Ahead popups").IsChecked = false;
settings.GetVisualDescendants().OfType<TextBox>().Single(t => t.Name == "ClaudeCliPath").Text = "claude-fixture";
settings.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == "Save").RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
Assert.NotNull(saved); Assert.Equal(TimeSpan.FromSeconds(25), saved.RefreshInterval); Assert.True(saved.StartWithOs);
Assert.Equal(initial.Claude with { CliPath = "claude-fixture" }, saved.Claude); Assert.False(saved.PopupAhead); Assert.Equal("0.9", saved.DismissedPluginVersion);
Exception? cancellationFailure = null;
void CatchCancellation(object? sender, DispatcherUnhandledExceptionEventArgs e)
{ cancellationFailure = e.Exception; e.Handled = true; }
Dispatcher.UIThread.UnhandledException += CatchCancellation;
var cancelled = new SettingsWindow(new(), new(PluginInstallState.NoHostFound), _ => Task.FromException(new OperationCanceledException()));
cancelled.Show();
cancelled.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == "Save").RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
Dispatcher.UIThread.RunJobs();
Dispatcher.UIThread.UnhandledException -= CatchCancellation;
Assert.Null(cancellationFailure);
Assert.Contains(cancelled.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Settings save was cancelled."); cancelled.Close();
var opened = 0;
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.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), () => { });
behind.Show(); SaveThemes(behind, "popup-behind"); behind.Close();
var installed = 0; var dismissed = 0;
var ask = new PopupWindow("Stream Deck plugin", "Version 1.0 is ready.", () => { }, "Install", () => installed++, () => dismissed++);
ask.Show(); SaveThemes(ask, "popup-streamdeck-ask");
ask.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == "Not now").RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
Assert.Equal(0, installed); Assert.Equal(1, dismissed);
var install = new PopupWindow("Stream Deck plugin", "Update ready", () => { }, "Update", () => installed++);
install.Show(); install.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == "Update").RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
Assert.Equal(1, installed);
var popupClock = new PopupClock();
using var stack = new PopupStack(() => { }, popupClock);
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), () => { });
stack.Show(first); stack.Show(second); Assert.True(second.Position.Y < first.Position.Y);
var chart = new UsageChart { Values = [new(clock.GetUtcNow(), "Exact", 123456)] };
var chartWindow = new Window { Content = chart, Width = 400, Height = 180 };
chartWindow.Show();
using (chartWindow.CaptureRenderedFrame()) { }
chartWindow.MouseMove(new Point(200, 100));
Assert.Contains(123456.ToString("N0"), ToolTip.GetTip(chart)?.ToString()); chartWindow.Close();
var polishShots = shots;
Directory.CreateDirectory(polishShots);
var emptyChart = new Window { Content = Ui.Card(Ui.Stack(Ui.Text("Tokens per hour", 19), new UsageChart())), Width = 620, Height = 260,
RequestedThemeVariant = ThemeVariant.Light };
emptyChart.Show(); Save(emptyChart, "chart-empty.png", polishShots); emptyChart.Close();
var time = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
var smallChart = new Window { Content = Ui.Card(Ui.Stack(Ui.Text("Tokens per hour", 19), new UsageChart
{ Values = [new(time, "Claude", 1), new(time.AddHours(1), "Claude", 2), new(time.AddHours(2), "Claude", 3)] })),
Width = 620, Height = 260, RequestedThemeVariant = ThemeVariant.Light };
smallChart.Show(); Save(smallChart, "chart-max-3.png", polishShots); smallChart.Close();
var day = new DateTimeOffset(2026, 10, 14, 0, 0, 0, TimeSpan.FromHours(2));
var daily = new UsageChart { Interval = TimeSpan.FromDays(1), Values = [new(day, "Claude", 3), new(day.AddDays(1), "Claude", 2)] };
var dailyWindow = new Window { Content = Ui.Card(Ui.Stack(Ui.Text("Tokens per day", 19), daily)),
Width = 620, Height = 260, RequestedThemeVariant = ThemeVariant.Light };
dailyWindow.Show(); Save(dailyWindow, "chart-local-day.png");
dailyWindow.MouseMove(new Point(90, 150));
Assert.Contains(day.DateTime.ToString("d"), ToolTip.GetTip(daily)?.ToString()); dailyWindow.Close();
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)
{
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{ window.RequestedThemeVariant = theme; Save(window, stem + "-" + theme + ".png"); }
}
bool DrawsForecast(BurnUpChart chart)
{
var drawing = new Avalonia.Media.DrawingGroup();
using (var context = drawing.Open()) chart.Render(context);
return HasForecast(drawing);
static bool HasForecast(Avalonia.Media.DrawingGroup group) => group.Children.Any(d =>
d is Avalonia.Media.GeometryDrawing { Pen.DashStyle.Dashes: { } dashes } && dashes.SequenceEqual(new double[] { 1, 3 }) ||
d is Avalonia.Media.DrawingGroup nested && HasForecast(nested));
}
void Save(Window window, string name, string? destination = null)
{
Dispatcher.UIThread.RunJobs();
using var bitmap = window.CaptureRenderedFrame(); Assert.NotNull(bitmap);
using var output = File.Create(Path.Combine(destination ?? shots, name)); bitmap.Save(output, PngBitmapEncoderOptions.Default);
Assert.True(output.Length > 2000);
}
}
catch (Exception e) { completion.SetException(e); }
});
if (OperatingSystem.IsWindows()) thread.SetApartmentState(ApartmentState.STA);
thread.Start(); await completion.Task; thread.Join();
}
public sealed class TestApplication : Application
{ public override void Initialize() => Styles.Add(Ui.NeutralTheme()); }
private sealed class PopupClock : TimeProvider
{
public List<PopupTimer> Timers { get; } = [];
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
{
Assert.Equal(TimeSpan.FromSeconds(8), dueTime);
Assert.Equal(Timeout.InfiniteTimeSpan, period);
var timer = new PopupTimer(callback, state); Timers.Add(timer); return timer;
}
public void Fire() { foreach (var timer in Timers.Where(t => !t.Disposed)) timer.Fire(); }
}
private sealed class PopupTimer(TimerCallback callback, object? state) : ITimer
{
public bool Disposed { get; private set; }
public void Fire() => callback(state);
public bool Change(TimeSpan dueTime, TimeSpan period) => throw new NotSupportedException();
public void Dispose() => Disposed = true;
public ValueTask DisposeAsync() { Dispose(); return ValueTask.CompletedTask; }
}
}