app: redesign the stats panel and settings (D8)
agent-review agent review: pass

The panel is now a dashboard: a one-row header with range and provider
controls, a tile per limit window with pace, forecasts, today's share
of the week and the daily budget, per-day week charts with even-pace and
budget lines, token stat tiles with one composition legend, hourly and
daily charts side by side, limit history, and top-8 breakdowns. Colours
follow fixed provider and status tokens instead of the OS accent;
numbers are compact to three significant digits. Settings are grouped
into cards with a sticky footer. Developer feedback on v1.

Refs #5
This commit is contained in:
Florian Schmidt
2026-10-14 22:59:24 +02:00
parent a20d0ab9dc
commit 73f79eb6ac
11 changed files with 1013 additions and 226 deletions
+55 -1
View File
@@ -5,13 +5,67 @@ namespace FinalToken.App.Tests;
public sealed class FormattingTests
{
[Theory]
[InlineData(6000000000, "6 B")]
[InlineData(2000000000, "2 B")]
[InlineData(1500000000, "1,5 B")]
[InlineData(600000000, "600 M")]
[InlineData(82500, "82,5 K")]
[InlineData(0, "0")]
public void AxisNumbersDropTrailingZerosWithoutChangingCompactValues(double value, string expected)
{
var previous = CultureInfo.CurrentCulture;
try
{
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("de-DE");
Assert.Equal(expected, Display.Axis(value));
Assert.Equal("2,00 B", Display.Compact(2000000000));
}
finally { CultureInfo.CurrentCulture = previous; }
}
[Theory]
[InlineData(292950000, "293 M")]
[InlineData(2300000000, "2,30 B")]
[InlineData(966690000, "967 M")]
[InlineData(82500, "82,5 K")]
[InlineData(999950, "1,00 M")]
[InlineData(0, "0")]
public void CompactNumbersUseThreeSignificantDigits(double value, string expected)
{
var previous = CultureInfo.CurrentCulture;
try { CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("de-DE"); Assert.Equal(expected, Display.Compact(value)); }
finally { CultureInfo.CurrentCulture = previous; }
}
[Theory]
[InlineData(FinalToken.Core.PaceState.Ahead, true)]
[InlineData(FinalToken.Core.PaceState.OnTrack, false)]
[InlineData(FinalToken.Core.PaceState.Behind, false)]
[InlineData(FinalToken.Core.PaceState.Unknown, false)]
public void ForecastWarningFollowsState(FinalToken.Core.PaceState state, bool warning)
{
var text = Display.Forecast(new(2026, 10, 18, 14, 43, 0, TimeSpan.Zero), state);
Assert.Equal(warning, text.Contains('⚠'));
Assert.StartsWith(warning ? "⚠ 100 % on " : "At this pace 100 % on ", text);
}
[Theory]
[InlineData(1)]
[InlineData(1.25)]
[InlineData(2)]
public void DenseBarEdgesMeetOnPhysicalPixelsWithoutGaps(double scaling)
{
var first = UsageChart.BarBounds(50.13, 100, 3.17, 40, scaling);
var next = UsageChart.BarBounds(53.30, 100, 3.17, 40, scaling);
Assert.Equal(first.Right, next.Left, 6);
Assert.Equal(Math.Round(first.Left * scaling), first.Left * scaling, 6);
Assert.Equal(Math.Round(first.Right * scaling), first.Right * scaling, 6);
}
[Fact]
public void DailyChartLabelAndTooltipUseTheBucketsLocalDate()
{
var zone = TimeZoneInfo.CreateCustomTimeZone("Fixture+02", TimeSpan.FromHours(2), "Fixture", "Fixture");
var day = FinalToken.Core.CalendarDays.Start(new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero), zone);
Assert.Equal("10-14", Display.ChartDateLabel(day, TimeSpan.FromDays(1)));
Assert.Equal(day.DateTime.ToString("g"), Display.ChartTimestamp(day, TimeSpan.FromDays(1)));
Assert.Equal(day.DateTime.ToString("d"), Display.ChartTimestamp(day, TimeSpan.FromDays(1)));
}
[Theory]
[InlineData(null)]
+117 -12
View File
@@ -1,5 +1,6 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Headless;
using Avalonia.Interactivity;
using Avalonia.Media.Imaging;
@@ -29,23 +30,122 @@ public sealed class HeadlessTests
var shots = Environment.GetEnvironmentVariable("FINALTOKEN_SCREENSHOT_DIR") ?? Path.Combine(root.Parent!.FullName, "runs", "shots", "app");
Directory.CreateDirectory(shots);
var model = FakeData.Model();
var panel = new PanelWindow(model, () => { }, () => { }, () => { }, () => { }) { Height = 2450 };
var panel = new PanelWindow(model, () => { }, () => { }, () => { }, () => { });
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");
var filters = panel.GetVisualDescendants().OfType<ComboBox>().ToArray();
filters[0].SelectedIndex = 4; filters[1].SelectedIndex = 2;
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");
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[0].SelectedIndex = 1; filters[1].SelectedIndex = 0;
filters[1].IsChecked = true; filters[5].IsChecked = true;
panel.RequestedThemeVariant = ThemeVariant.Dark; Save(panel, "panel-dark.png");
model.Snapshot = FakeData.Snapshot(DateTimeOffset.UtcNow, true); Save(panel, "panel-unavailable.png"); panel.Close();
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);
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"), ("history", "Limit history"), ("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");
}
var prior = viewport.Offset;
model.Snapshot = model.Snapshot! with { MadeAt = DateTimeOffset.UtcNow }; Dispatcher.UIThread.RunJobs();
Assert.Equal(prior, viewport.Offset);
}
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;
model.Snapshot = FakeData.Snapshot(DateTimeOffset.UtcNow, 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(DateTimeOffset.UtcNow, 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();
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; }) { Height = 1600 };
var settings = new SettingsWindow(initial, new(PluginInstallState.Outdated, "1.0", "0.9"), value => { saved = value; return Task.CompletedTask; }, () => { });
settings.Show(); Save(settings, "settings.png");
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>().First().IsChecked = false;
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);
@@ -63,13 +163,13 @@ public sealed class HeadlessTests
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, DateTimeOffset.UtcNow.AddHours(1)), () => opened++);
ahead.Show(); Save(ahead, "popup-ahead.png"); 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);
var behind = PopupWindow.Pace(new(Provider.Codex, "primary", "Primary", PaceState.Behind, -18, null), () => { });
behind.Show(); Save(behind, "popup-behind.png"); behind.Close();
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(); Save(ask, "popup-streamdeck-ask.png");
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++);
@@ -102,11 +202,16 @@ public sealed class HeadlessTests
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("g"), ToolTip.GetTip(daily)?.ToString()); dailyWindow.Close();
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));
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"); }
}
void Save(Window window, string name, string? destination = null)
{
Dispatcher.UIThread.RunJobs();
@@ -121,7 +226,7 @@ public sealed class HeadlessTests
thread.Start(); await completion.Task; thread.Join();
}
public sealed class TestApplication : Application
{ public override void Initialize() => Styles.Add(new FluentTheme()); }
{ public override void Initialize() => Styles.Add(Ui.NeutralTheme()); }
private sealed class PopupClock : TimeProvider
{
public List<PopupTimer> Timers { get; } = [];
+86 -10
View File
@@ -5,6 +5,30 @@ namespace FinalToken.App.Tests;
public sealed class ViewModelTests
{
[Theory]
[InlineData(-1)]
[InlineData(1)]
public void ResetDriftKeepsChartContinuousAndRealResetAddsGap(int minutes)
{
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 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) };
store.AddLimits([first]);
store.AddLimits([window with { SampleTime = now.AddHours(-3), UsedPercent = 50, ResetsAt = window.ResetsAt!.Value.AddMinutes(-minutes) }]);
store.AddLimits([window]);
Snapshot SnapshotFor(LimitWindow w, DateTimeOffset time) => new() { MadeAt = time, RefreshInterval = TimeSpan.FromMinutes(1),
Providers = [new(Provider.Claude, ProviderStatus.Available, null, [new(w, Pace.Calculate(w, time))], new(), null, new())] };
var view = PanelViewModel.QueryHistory(store, SnapshotFor(window, now), HistoryRange.All, null, now);
Assert.All(Assert.Single(view.Limits).Values, v => Assert.False(v.BreakBefore));
var detail = Assert.Single(view.Details);
Assert.Equal(first.SampleTime, detail.Since); Assert.Equal(20, detail.Days!.Today); Assert.NotNull(detail.Recent);
var next = window with { ResetsAt = window.ResetsAt!.Value.AddDays(7), SampleTime = now.AddDays(7).AddMinutes(-1), UsedPercent = 5 };
store.AddLimits([next]);
var nextView = PanelViewModel.QueryHistory(store, SnapshotFor(next, now.AddDays(7)), HistoryRange.All, null, now.AddDays(7));
Assert.Equal(1, Assert.Single(nextView.Limits).Values.Count(v => v.BreakBefore));
Assert.True(Assert.Single(nextView.Limits).Values[^1].BreakBefore);
}
[Theory]
[InlineData(HistoryRange.Hours24, 1)]
[InlineData(HistoryRange.Days7, 7)]
@@ -55,6 +79,43 @@ public sealed class ViewModelTests
}
[Fact] public void DesktopEntryQuotesExecutableAndEscapesFieldCodes()
{ var text = OsStartup.DesktopEntry("/opt/Final Token/100%/app"); Assert.Contains("Exec=\"/opt/Final Token/100%%/app\"", text); Assert.Contains("Terminal=false", text); }
[Fact] public void BreakdownKeepsTopEightAndOtherWithoutLosingCounts()
{
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());
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);
Assert.Equal(9, view.Projects.Count); Assert.Equal("project-109", view.Projects[0].Name);
Assert.Equal("Other (102)", view.Projects[^1].Name); Assert.Equal(6105, view.Projects.Sum(r => r.Counts.Total));
Assert.Equal(1, view.Projects.Sum(r => r.Share), 8);
}
[Fact] public void FilteredModelSeriesUseSixAlphabeticSlotsAndOther()
{
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());
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);
Assert.Equal(7, view.Hourly.Count); Assert.Equal(40, view.Hourly.Single(p => p.Series == "Other").Value);
Assert.Equal(100, view.Hourly.Sum(p => p.Value)); Assert.Equal(20, view.Hourly.Sum(p => p.CacheRead));
Assert.Equal(view.Hourly.Select(p => p.Series).Order(), view.Daily.Select(p => p.Series).Order());
Assert.DoesNotContain(view.Hourly, p => p.Series == "model-6");
}
[Fact] public void ProjectNamesKeepTwoSegmentsAndDisambiguateCollisions()
{
var names = PanelWindow.ShortProjectNames(["D:/First/Shared/App", "D:/Second/Shared/App", "/work/Only/App", "Unknown"]);
Assert.Equal(["First/Shared/App", "Second/Shared/App", "Only/App", "Unknown"], names);
}
[Fact] public void ModelBreakdownKeepsActualProviderIdentityForDots()
{
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());
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.Claude, now.AddHours(-1), "shared-name", "p", new(Total: 30), "c"));
var view = PanelViewModel.QueryHistory(store, FakeData.Snapshot(now), HistoryRange.Days7, null, now);
Assert.Equal([Provider.Claude], view.Models.Single(r => r.Name == "arbitrary-name").Providers);
Assert.Equal([Provider.Claude, Provider.Codex], view.Models.Single(r => r.Name == "shared-name").Providers);
}
[Fact] public void DesktopEntryRejectsInjectedLine() => Assert.Throws<ArgumentException>(() => OsStartup.DesktopEntry("/app\nExec=other"));
[Fact] public void DesktopEntryEscapesCommandCharactersAtBothParsingLevels()
{
@@ -68,22 +129,37 @@ internal static class FakeData
public static Snapshot Snapshot(DateTimeOffset now, bool unavailable = false) => new()
{
MadeAt = now, RefreshInterval = TimeSpan.FromSeconds(60), Providers =
[new(Provider.Claude, ProviderStatus.Available, null, [Window(Provider.Claude, "session", "Current session", 68, now, 5, 3), Window(Provider.Claude, "week", "Current week", 32, now, 168, 48)],
new(12000, 18000, 2000, 4200, 0, 36200), new(4000, 6000, 1000, 1600, 0, 12600), new(85000, 92000, 16000, 28000, 0, 221000)),
[new(Provider.Claude, ProviderStatus.Available, null, [Window(Provider.Claude, "session", "Session · 5 h", 12, now, 5, 1), Window(Provider.Claude, "week", "Week · all models", 70, now, 168, 84)],
new(12000000, 218000000, 2000000, 47000000, 0, 279000000), new(4000000, 6000000, 1000000, 1600000, 0, 12600000), new(85000000, 1920000000, 16000000, 259000000, 0, 2280000000)),
new(Provider.Codex, unavailable ? ProviderStatus.Unavailable : ProviderStatus.Available, unavailable ? "CLI is not installed. Token history remains available." : null,
[Window(Provider.Codex, "primary", "Primary · 5 hours", 12, now, 5, 1), Window(Provider.Codex, "secondary", "Secondary · 7 days", 62, now, 168, 80)],
new(72000, 42000, 0, 8400, 2100, 80400), new(23000, 10000, 0, 3200, 700, 26200), new(340000, 150000, 0, 38000, 11000, 378000))]
[Window(Provider.Codex, "secondary", "Week", 86, now, 168, 24)],
new(72000000, 42000000, 0, 8400000, 2100000, 80400000), null, new(340000000, 150000000, 0, 38000000, 11000000, 378000000))]
};
private static WindowSnapshot Window(Provider provider, string id, string label, double percent, DateTimeOffset now, int hours, int resetHours)
{ var w = new LimitWindow(provider, id, label, percent, now.AddHours(resetHours), TimeSpan.FromHours(hours), now.AddMinutes(-3), "fixture"); return new(w, Pace.Calculate(w, now)); }
public static PanelViewModel Model(bool unavailable = false)
{
var now = DateTimeOffset.UtcNow;
var hourly = Enumerable.Range(0, 24).SelectMany(i => new[] { new ChartValue(now.AddHours(-24 + i), "Claude", 1000 + i * 210), new ChartValue(now.AddHours(-24 + i), "Codex", 2000 + (i % 5) * 800) }).ToArray();
var daily = Enumerable.Range(0, 7).SelectMany(i => new[] { new ChartValue(now.AddDays(-7 + i), "Claude", 20000 + i * 2000), new ChartValue(now.AddDays(-7 + i), "Codex", 30000 + i * 5000) }).ToArray();
return new() { Snapshot = Snapshot(now, unavailable), Message = "Updated just now · local CLI data", History = new(hourly, daily,
[new("Claude · Current session", Enumerable.Range(0, 8).Select(i => new ChartValue(now.AddMinutes(-140 + i * 20), "session", i * 8 + 12, i * 6)).ToArray())],
[new("claude-sonnet", new(Total: 221000), 0.37), new("gpt-6.1-sol", new(Total: 378000), 0.63)], [new("FinalToken", new(Total: 599000), 1)]),
Diagnostics = [new(now.AddMinutes(-4), Provider.Claude, "sample-age", "Latest limit sample is three minutes old.")] };
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), "finaltoken-fake", Guid.NewGuid().ToString("N")), new DiagnosticLog());
var snapshot = Snapshot(now, unavailable);
foreach (var provider in snapshot.Providers)
{
for (var i = 0; i < 168; i++)
{
var input = 1000000 + i * 10000; var cache = input * 8;
store.Add(new(provider.Provider, now.AddHours(-168 + i), provider.Provider == Provider.Claude ? "claude-fable" : "gpt-6.1-sol",
$"D:/Projects/Customer-{i % 110}/Workspace/Project-{i % 110}",
provider.Provider == Provider.Claude ? new(input, cache, 200000, 500000, 0, input + cache + 700000) : new(input + cache, cache, 0, 500000, 100000, input + cache + 500000), $"{provider.Provider}-{i}"));
}
foreach (var ws in provider.Windows.Where(w => w.Window.Length > TimeSpan.FromDays(1)))
{
var w = ws.Window; var start = w.ResetsAt!.Value - w.Length!.Value;
for (var i = 0; i <= (int)(now - start).TotalHours; i += 3)
store.AddLimits([w with { SampleTime = start.AddHours(i), UsedPercent = w.UsedPercent * i / (now - start).TotalHours }]);
for (var i = 0; i < 168; i += 6)
store.AddLimits([w with { ResetsAt = w.ResetsAt.Value.AddDays(-7), SampleTime = start.AddDays(-7).AddHours(i), UsedPercent = i * .5 }]);
}
}
return new() { Snapshot = snapshot, Message = "Updated just now", History = PanelViewModel.QueryHistory(store, snapshot, HistoryRange.Days7, null, now) };
}
}