diff --git a/Directory.Packages.props b/Directory.Packages.props
index 8afd472..1aee77d 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -3,6 +3,10 @@
true
+
+
+
+
diff --git a/src/FinalToken.App/AGENTS.md b/src/FinalToken.App/AGENTS.md
index 6f572b6..045f37b 100644
--- a/src/FinalToken.App/AGENTS.md
+++ b/src/FinalToken.App/AGENTS.md
@@ -1,4 +1,8 @@
# App
-Buildable placeholder only. W2 replaces Program.cs and this guidance with the Avalonia host (D8).
-Use RefreshEngine and source-generated snapshot DTOs from Core. Marshal Core events to the UI.
+Avalonia 12 Fluent host (D8). Views are built in C# without reflection bindings. View-model
+properties use CommunityToolkit.Mvvm source generators. Custom charts use DrawingContext.
+Program owns StoreLock for the engine lifetime. DesktopApp marshals Core events to the UI;
+history queries run on worker threads and discard superseded results. Keep all writes atomic (D5).
+Stream Deck policy and the real installer come through IPluginInstaller (D11).
+UsePlatformDetect selects X11 on Linux in the pinned Avalonia version. Keep XWayland support.
Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root.
diff --git a/src/FinalToken.App/Charts.cs b/src/FinalToken.App/Charts.cs
new file mode 100644
index 0000000..ea56d6e
--- /dev/null
+++ b/src/FinalToken.App/Charts.cs
@@ -0,0 +1,103 @@
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Media;
+using Avalonia.Styling;
+using FinalToken.Core;
+using System.Globalization;
+
+namespace FinalToken.App;
+
+public sealed class UsageChart : Control
+{
+ private static readonly IBrush[] Palette = [Brush.Parse("#3878D4"), Brush.Parse("#B377D1"), Brush.Parse("#249A88"), Brush.Parse("#C98926")];
+ public static IBrush SeriesColour(int index) => Palette[index % Palette.Length];
+ public IReadOnlyList Values { get; init; } = [];
+ public bool Percent { get; init; }
+ public TimeSpan Interval { get; init; } = TimeSpan.FromHours(1);
+ private readonly List<(Rect Rect, string Text)> hits = [];
+ public UsageChart()
+ {
+ Height = 180;
+ PointerMoved += (_, e) => ToolTip.SetTip(this, hits.LastOrDefault(h => h.Rect.Contains(e.GetPosition(this))).Text);
+ PointerExited += (_, _) => ToolTip.SetTip(this, null);
+ }
+ public override void Render(DrawingContext context)
+ {
+ base.Render(context);
+ hits.Clear();
+ var ink = ActualThemeVariant == ThemeVariant.Dark ? Brushes.WhiteSmoke : Brushes.DarkSlateGray;
+ var plot = new Rect(58, 12, Math.Max(1, Bounds.Width - 74), Math.Max(1, Bounds.Height - 46));
+ var groups = Values.GroupBy(v => v.Time).OrderBy(g => g.Key).ToArray();
+ var max = Percent ? 100 : Math.Max(1, groups.Select(g => g.Sum(v => v.Value)).DefaultIfEmpty().Max());
+ for (var i = 0; i <= 4; i++)
+ {
+ var y = plot.Bottom - plot.Height * i / 4;
+ context.DrawLine(new Pen(ActualThemeVariant == ThemeVariant.Dark ? Brush.Parse("#354052") : Brush.Parse("#DFE5EE")), new(plot.Left, y), new(plot.Right, y));
+ var tick = max * i / 4;
+ var label = Percent ? $"{tick:0}%" : tick >= 1e9 ? $"{tick / 1e9:0.#}B" : tick >= 1e6 ? $"{tick / 1e6:0.#}M" : tick >= 1000 ? $"{tick / 1000:0.#}K" : $"{tick:0}";
+ Text(context, label, new(0, y - 8), ink);
+ }
+ if (groups.Length == 0) { Text(context, "No samples in this range", new(plot.Left + 12, plot.Top + 32), ink); return; }
+ var series = Values.Select(v => v.Series).Distinct().ToArray();
+ if (Percent)
+ {
+ ChartValue? previous = null;
+ var minTime = groups[0].Key;
+ var timeSpan = Math.Max(1, (groups[^1].Key - minTime).TotalSeconds);
+ Point Position(ChartValue v, double value) => new(plot.Left + (v.Time - minTime).TotalSeconds / timeSpan * plot.Width, plot.Bottom - Math.Clamp(value, 0, 100) / 100 * plot.Height);
+ foreach (var value in Values.OrderBy(v => v.Time))
+ {
+ var point = Position(value, value.Value);
+ if (previous is { } p && !value.BreakBefore)
+ {
+ context.DrawLine(new Pen(Palette[0], 2), Position(p, p.Value), point);
+ if (p.Expected is { } pe && value.Expected is { } expected)
+ context.DrawLine(new Pen(Palette[2], 1, new DashStyle([4, 3], 0)), Position(p, pe), Position(value, expected));
+ }
+ context.DrawEllipse(Palette[0], null, point, 3, 3);
+ hits.Add((new(point.X - 8, point.Y - 10, 16, 20), $"{value.Time.LocalDateTime:g} · {value.Value:0.##}% · expected {(value.Expected is { } e ? $"{e:0.##}%" : "unknown")}"));
+ previous = value;
+ }
+ }
+ else
+ {
+ var duration = Math.Max(Interval.TotalSeconds, (groups[^1].Key - groups[0].Key).TotalSeconds + Interval.TotalSeconds);
+ var width = plot.Width * Interval.TotalSeconds / duration;
+ for (var i = 0; i < groups.Length; i++)
+ {
+ var bottom = plot.Bottom;
+ foreach (var value in groups[i])
+ {
+ var height = value.Value / max * plot.Height;
+ var x = plot.Left + (groups[i].Key - groups[0].Key).TotalSeconds / duration * plot.Width;
+ var rect = new Rect(x + Math.Min(1, width / 8), bottom - height, Math.Max(0.5, width - Math.Min(2, width / 4)), height);
+ context.DrawRectangle(Palette[Array.IndexOf(series, value.Series) % Palette.Length], null, rect);
+ hits.Add((rect, $"{value.Time.LocalDateTime:g} · {value.Series}: {value.Value:N0} tokens"));
+ bottom -= height;
+ }
+ }
+ }
+ string DateLabel(DateTimeOffset time) => Interval >= TimeSpan.FromDays(1) ? time.UtcDateTime.ToString("MM-dd") : time.LocalDateTime.ToString("MM-dd HH:mm");
+ Text(context, DateLabel(groups[0].Key), new(plot.Left, plot.Bottom + 8), ink);
+ Text(context, DateLabel(groups[^1].Key), new(Math.Max(plot.Left, plot.Right - 110), plot.Bottom + 8), ink);
+ ToolTip.SetShowDelay(this, 0);
+ }
+ private static void Text(DrawingContext context, string text, Point point, IBrush brush) => context.DrawText(
+ new FormattedText(text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, Typeface.Default, 11, brush), point);
+}
+
+public sealed class PaceBar(WindowSnapshot window) : Control
+{
+ public static IBrush Colour(PaceState state) => Brush.Parse(state switch
+ { PaceState.Ahead => "#D98236", PaceState.Behind => "#3A8CCB", PaceState.OnTrack => "#279884", _ => "#8C95A3" });
+ public override void Render(DrawingContext context)
+ {
+ base.Render(context);
+ context.DrawRectangle(Brush.Parse("#338795A5"), null, new Rect(Bounds.Size), 4, 4);
+ context.DrawRectangle(Colour(window.Pace.State), null, new Rect(0, 0, Bounds.Width * Math.Clamp(window.Window.UsedPercent / 100, 0, 1), Bounds.Height), 4, 4);
+ if (window.Pace.ElapsedFraction is { } elapsed)
+ context.DrawLine(new Pen(ActualThemeVariant == ThemeVariant.Dark ? Brushes.White : Brushes.Black, 2), new(Bounds.Width * elapsed, 0), new(Bounds.Width * elapsed, Bounds.Height));
+ ToolTip.SetTip(this, $"Used {window.Window.UsedPercent:0.##}% · expected {window.Pace.ElapsedFraction * 100:0.##}%");
+ }
+}
diff --git a/src/FinalToken.App/DesktopApp.cs b/src/FinalToken.App/DesktopApp.cs
new file mode 100644
index 0000000..d782198
--- /dev/null
+++ b/src/FinalToken.App/DesktopApp.cs
@@ -0,0 +1,184 @@
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Controls.ApplicationLifetimes;
+using Avalonia.Media;
+using Avalonia.Media.Imaging;
+using Avalonia.Themes.Fluent;
+using Avalonia.Threading;
+using FinalToken.Core;
+using FinalToken.Core.StreamDeck;
+
+namespace FinalToken.App;
+
+public sealed class DesktopApp : Application
+{
+ private readonly PanelViewModel model = new();
+ private IClassicDesktopStyleApplicationLifetime? desktop;
+ private PanelWindow? panel;
+ private PopupStack? popups;
+ private TrayIcon? tray;
+ private DispatcherTimer? ageTimer;
+ private SettingsWindow? settingsWindow;
+ private Task settingsSave = Task.CompletedTask;
+ private PopupWindow? pluginAsk;
+ private RefreshEngine? engine;
+ private readonly SemaphoreSlim pluginGate = new(1, 1);
+ private int historyRequest;
+ private bool quitting;
+ private PluginInstallStatus pluginStatus = new(PluginInstallState.NoHostFound);
+ public IPluginInstaller PluginInstaller { get; set; } = FinalToken.Core.StreamDeck.PluginInstaller.CreateDefault();
+ public override void Initialize() => Styles.Add(new FluentTheme());
+ public override void OnFrameworkInitializationCompleted()
+ {
+ if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime lifetime)
+ {
+ desktop = lifetime; desktop.ShutdownMode = ShutdownMode.OnExplicitShutdown;
+ engine = Program.Engine;
+ if (Program.StartupError is { } error)
+ {
+ var window = new Window { Title = "FinalToken — history error", Width = 560, Height = 240,
+ Content = Ui.Card(Ui.Stack(Ui.Text("History cannot be loaded", 22), Ui.Text(error), Ui.Button("Quit", () => desktop.Shutdown(1)))) };
+ desktop.MainWindow = window; window.Show();
+ window.Closed += (_, _) => desktop.Shutdown(1);
+ }
+ else
+ {
+ panel = new PanelWindow(model, () => Run(Refresh), OpenSettings, () => Run(Quit), () => Run(LoadHistory));
+ desktop.MainWindow = panel; popups = new(OpenPanel);
+ panel.Closing += (_, e) => { if (!quitting && engine?.Settings.CloseToTray != false) { e.Cancel = true; panel.Hide(); } else if (!quitting) { e.Cancel = true; Run(Quit); } };
+ CreateTray(); panel.Show();
+ if (engine is not null)
+ {
+ engine.SnapshotChanged += snapshot => Dispatcher.UIThread.Post(() => { model.Snapshot = snapshot; model.Diagnostics = engine.RecentDiagnostics; model.Message = "Updated " + snapshot.MadeAt.LocalDateTime.ToString("g"); Run(LoadHistory); });
+ engine.PopupRequested += alert => Dispatcher.UIThread.Post(() => { if (!quitting) popups.Pace(alert); });
+ engine.ActivationRequested += () => Dispatcher.UIThread.Post(OpenPanel);
+ model.Snapshot = engine.CurrentSnapshot;
+ ageTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(30) };
+ ageTimer.Tick += (_, _) => { if (panel.IsVisible) model.Diagnostics = engine.RecentDiagnostics; };
+ ageTimer.Start();
+ Run(Start);
+ }
+ }
+ desktop.ShutdownRequested += (_, e) => { if (!quitting && engine is not null) { e.Cancel = true; Run(Quit); } };
+ }
+ base.OnFrameworkInitializationCompleted();
+ }
+ private async Task Start()
+ {
+ await engine!.StartAsync();
+ if (engine.Settings.StartWithOs) await OsStartup.ApplyAsync(true);
+ await CheckPlugin();
+ }
+ private void CreateTray()
+ {
+ var menu = new NativeMenu();
+ foreach (var (label, action) in new (string, Action)[] { ("Open", OpenPanel), ("Refresh now", () => Run(Refresh)), ("Settings", OpenSettings), ("Quit", () => Run(Quit)) })
+ { var item = new NativeMenuItem(label); item.Click += (_, _) => action(); menu.Items.Add(item); }
+ using var bitmap = new RenderTargetBitmap(new PixelSize(32, 32));
+ using (var context = bitmap.CreateDrawingContext())
+ { context.DrawRectangle(Brush.Parse("#3878D4"), null, new Rect(0, 0, 32, 32), 7, 7); context.DrawLine(new Pen(Brushes.White, 4), new(9, 9), new(23, 9)); context.DrawLine(new Pen(Brushes.White, 4), new(16, 9), new(16, 25)); }
+ using var stream = new MemoryStream(); bitmap.Save(stream, PngBitmapEncoderOptions.Default); stream.Position = 0;
+ tray = new TrayIcon { Icon = new WindowIcon(stream), ToolTipText = "FinalToken", Menu = menu, IsVisible = true };
+ tray.Clicked += (_, _) => OpenPanel();
+ TrayIcon.SetIcons(this, [tray]);
+ }
+ private void OpenPanel()
+ {
+ if (panel is null || quitting) return;
+ panel.Show(); panel.WindowState = WindowState.Normal; panel.Activate();
+ if (OperatingSystem.IsWindows()) WindowsActivation.Activate(panel);
+ }
+ private Task Refresh() => engine is null ? Task.CompletedTask : engine.RefreshNowAsync();
+ private async Task LoadHistory()
+ {
+ if (engine is null || model.Snapshot is not { } snapshot || quitting) return;
+ var request = ++historyRequest; var range = model.Range; var filter = model.ProviderFilter;
+ var history = await Task.Run(() => PanelViewModel.QueryHistory(engine.History, snapshot, range, filter, DateTimeOffset.UtcNow));
+ if (request == historyRequest && !quitting) model.History = history;
+ }
+ private void OpenSettings()
+ {
+ if (engine is null) return;
+ if (settingsWindow is not null) { settingsWindow.Activate(); return; }
+ settingsWindow = new SettingsWindow(engine.Settings, pluginStatus, value => settingsSave = SaveSettings(value));
+ settingsWindow.Closed += (_, _) => settingsWindow = null;
+ settingsWindow.Show();
+ }
+ private async Task SaveSettings(Settings value)
+ {
+ if (engine is null || quitting) return;
+ var previous = engine.Settings;
+ await OsStartup.ApplyAsync(value.StartWithOs);
+ if (quitting) { await OsStartup.ApplyAsync(previous.StartWithOs); return; }
+ try { await engine.UpdateSettingsAsync(value); }
+ catch { await OsStartup.ApplyAsync(previous.StartWithOs); throw; }
+ if (quitting) return;
+ await CheckPlugin();
+ if (!quitting) await engine.RefreshNowAsync();
+ }
+ private async Task CheckPlugin()
+ {
+ if (engine is null || quitting) return;
+ await pluginGate.WaitAsync();
+ try
+ {
+ if (quitting) return;
+ pluginAsk?.Close(); pluginAsk = null;
+ pluginStatus = await PluginInstaller.GetStatusAsync();
+ var action = InstallPolicy.Decide(engine.Settings.StreamDeckInstallMode, pluginStatus, engine.Settings.DismissedPluginVersion);
+ if (action == InstallAction.Install) await InstallPlugin();
+ else if (action == InstallAction.Ask)
+ {
+ var version = pluginStatus.ShippedVersion;
+ pluginAsk = new PopupWindow("Stream Deck plugin", $"Version {version} is ready.", OpenPanel,
+ pluginStatus.State == PluginInstallState.Outdated ? "Update" : "Install", () => Run(() => AcceptPlugin(version)),
+ () => Run(() => DismissPlugin(version)));
+ popups!.Show(pluginAsk);
+ }
+ }
+ finally { pluginGate.Release(); }
+ }
+ private async Task DismissPlugin(string? version)
+ {
+ await pluginGate.WaitAsync();
+ try { if (!quitting && engine is not null) await engine.UpdateSettingsAsync(engine.Settings with { DismissedPluginVersion = version }); }
+ finally { pluginGate.Release(); }
+ }
+ private async Task AcceptPlugin(string? version)
+ {
+ await pluginGate.WaitAsync();
+ try
+ {
+ if (quitting || engine?.Settings.StreamDeckInstallMode == InstallMode.Off) return;
+ var current = await PluginInstaller.GetStatusAsync();
+ if (current.ShippedVersion == version && current.State is PluginInstallState.NotInstalled or PluginInstallState.Outdated)
+ await InstallPlugin();
+ }
+ finally { pluginGate.Release(); }
+ }
+ private async Task InstallPlugin()
+ {
+ try { await PluginInstaller.InstallOrUpdateAsync(); pluginStatus = await PluginInstaller.GetStatusAsync(); if (!quitting) popups!.Show(new PopupWindow("Stream Deck", pluginStatus.State == PluginInstallState.UpToDate ? "Plugin installed successfully." : $"Plugin status: {pluginStatus.State}", OpenPanel)); }
+ catch (Exception e) when (e is IOException or UnauthorizedAccessException or InvalidOperationException)
+ { if (!quitting) popups!.Show(new PopupWindow("Stream Deck", "Install failed: " + e.Message, OpenPanel)); }
+ }
+ private async Task Quit()
+ {
+ if (quitting) return; quitting = true;
+ ageTimer?.Stop(); tray?.Dispose(); popups?.Dispose(); settingsWindow?.Close();
+ var stopping = engine?.StopAsync() ?? Task.CompletedTask;
+ await pluginGate.WaitAsync(); pluginGate.Release();
+ try { await settingsSave; }
+ catch (Exception e) when (e is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or OperationCanceledException)
+ { engine?.Diagnostics.Add(null, "settings-shutdown", "Settings could not finish applying before shutdown."); }
+ await stopping;
+ desktop?.Shutdown();
+ }
+ private async void Run(Func work)
+ {
+ try { await work(); }
+ catch (OperationCanceledException) { }
+ catch (Exception e) when (e is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException)
+ { model.Message = "Operation failed: " + e.Message; }
+ }
+}
diff --git a/src/FinalToken.App/FinalToken.App.csproj b/src/FinalToken.App/FinalToken.App.csproj
index 9dda08d..9704ede 100644
--- a/src/FinalToken.App/FinalToken.App.csproj
+++ b/src/FinalToken.App/FinalToken.App.csproj
@@ -1,8 +1,15 @@
- Exe
+ WinExe
FinalToken
true
+ true
+ true
+
+
+
+
+
diff --git a/src/FinalToken.App/OsStartup.cs b/src/FinalToken.App/OsStartup.cs
new file mode 100644
index 0000000..64617fe
--- /dev/null
+++ b/src/FinalToken.App/OsStartup.cs
@@ -0,0 +1,32 @@
+using System.Runtime.Versioning;
+using FinalToken.Core;
+using Microsoft.Win32;
+
+namespace FinalToken.App;
+
+public static class OsStartup
+{
+ public static async Task ApplyAsync(bool enabled, string? executable = null)
+ {
+ executable ??= Environment.ProcessPath ?? throw new InvalidOperationException("Executable path is unavailable.");
+ if (OperatingSystem.IsWindows()) { ApplyWindows(enabled, executable); return; }
+ if (!OperatingSystem.IsLinux()) return;
+ var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".config", "autostart", "finaltoken.desktop");
+ if (!enabled) { if (File.Exists(path)) File.Delete(path); return; }
+ await AtomicFile.WriteAsync(path, DesktopEntry(executable));
+ }
+ public static string DesktopEntry(string executable)
+ {
+ if (executable.IndexOfAny(['\r', '\n', '\0']) >= 0) throw new ArgumentException("Executable path contains invalid characters.", nameof(executable));
+ var quoted = executable.Replace("\\", "\\\\", StringComparison.Ordinal).Replace("\"", "\\\"", StringComparison.Ordinal)
+ .Replace("`", "\\`", StringComparison.Ordinal).Replace("$", "\\$", StringComparison.Ordinal).Replace("%", "%%", StringComparison.Ordinal);
+ var escaped = quoted.Replace("\\", "\\\\", StringComparison.Ordinal);
+ return $"[Desktop Entry]\nType=Application\nName=FinalToken\nExec=\"{escaped}\"\nTerminal=false\nX-GNOME-Autostart-enabled=true\n";
+ }
+ [SupportedOSPlatform("windows")]
+ private static void ApplyWindows(bool enabled, string executable)
+ {
+ using var key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
+ if (enabled) key.SetValue("FinalToken", "\"" + executable + "\""); else key.DeleteValue("FinalToken", false);
+ }
+}
diff --git a/src/FinalToken.App/PanelViewModel.cs b/src/FinalToken.App/PanelViewModel.cs
new file mode 100644
index 0000000..b4a7c30
--- /dev/null
+++ b/src/FinalToken.App/PanelViewModel.cs
@@ -0,0 +1,75 @@
+using CommunityToolkit.Mvvm.ComponentModel;
+using FinalToken.Core;
+
+namespace FinalToken.App;
+
+public enum HistoryRange { Hours24, Days7, Days30, Days90, All }
+public sealed record ChartValue(DateTimeOffset Time, string Series, double Value, double? Expected = null, bool BreakBefore = false);
+public sealed record BreakdownRow(string Name, TokenCounts Counts, double Share);
+public sealed record LimitChart(string Label, IReadOnlyList Values);
+public sealed record HistoryView(IReadOnlyList Hourly, IReadOnlyList Daily,
+ IReadOnlyList Limits, IReadOnlyList Models, IReadOnlyList Projects);
+
+public partial class PanelViewModel : ObservableObject
+{
+ [ObservableProperty] private Snapshot? snapshot;
+ [ObservableProperty] private HistoryRange range = HistoryRange.Days7;
+ [ObservableProperty] private Provider? providerFilter;
+ [ObservableProperty] private HistoryView history = new([], [], [], [], []);
+ [ObservableProperty] private IReadOnlyList diagnostics = [];
+ [ObservableProperty] private string message = "Reading local CLI data…";
+
+ public static DateTimeOffset RangeStart(HistoryRange range, DateTimeOffset now) => range switch
+ {
+ HistoryRange.Hours24 => now.AddHours(-24), HistoryRange.Days7 => now.AddDays(-7),
+ HistoryRange.Days30 => now.AddDays(-30), HistoryRange.Days90 => now.AddDays(-90),
+ _ => DateTimeOffset.MinValue
+ };
+
+ // D5: queries return copies; the caller runs this on a worker thread.
+ public static HistoryView QueryHistory(HistoryStore store, Snapshot snapshot, HistoryRange range, Provider? filter, DateTimeOffset now)
+ {
+ var from = RangeStart(range, now);
+ var providers = snapshot.Providers.Where(p => filter is null || p.Provider == filter).ToArray();
+ var hourly = Series(SeriesInterval.Hour);
+ var daily = Series(SeriesInterval.Day);
+ var limits = providers.SelectMany(p => p.Windows.Select(w =>
+ {
+ var samples = store.LimitSamples(p.Provider, w.Window.Id, from, now);
+ return new LimitChart($"{p.Provider} · {w.Window.Label}", samples.Select((s, i) =>
+ new ChartValue(s.SampleTime, w.Window.Label, s.UsedPercent,
+ Pace.Calculate(s, s.SampleTime).ElapsedFraction * 100,
+ i > 0 && s.ResetsAt != samples[i - 1].ResetsAt)).ToArray());
+ })).ToArray();
+ return new(hourly, daily, limits, Breakdown(true), Breakdown(false));
+
+ IReadOnlyList Series(SeriesInterval interval) => providers.SelectMany(p =>
+ store.TokenSeries(p.Provider, from, now, interval).SelectMany(point => filter is null
+ ? new[] { new ChartValue(point.Time, p.Provider.ToString(), point.Counts.Total) }
+ : ModelsAtPoint(p.Provider, point.Time, interval))).ToArray();
+ IEnumerable ModelsAtPoint(Provider provider, DateTimeOffset time, SeriesInterval interval)
+ {
+ var end = time.Add(interval == SeriesInterval.Hour ? TimeSpan.FromHours(1) : TimeSpan.FromDays(1));
+ return store.ByModel(provider, time < from ? from : time, end > now ? now : end)
+ .Select(m => new ChartValue(time, m.Name ?? "Unknown model", m.Counts.Total));
+ }
+ IReadOnlyList Breakdown(bool models)
+ {
+ var rows = providers.SelectMany(p => models ? store.ByModel(p.Provider, from, now) : store.ByProject(p.Provider, from, now))
+ .GroupBy(r => r.Name ?? "Unknown").Select(g => new TokenBreakdown(g.Key,
+ g.Aggregate(new TokenCounts(), (sum, r) => sum + r.Counts))).OrderByDescending(r => r.Counts.Total).ToArray();
+ var total = rows.Sum(r => (double)r.Counts.Total);
+ return rows.Select(r => new BreakdownRow(r.Name!, r.Counts, total == 0 ? 0 : r.Counts.Total / total)).ToArray();
+ }
+ }
+}
+
+public static class Display
+{
+ public static string Duration(TimeSpan span) => span <= TimeSpan.Zero ? "now" : span.TotalDays >= 1
+ ? $"{span.TotalDays:0.0} d" : span.TotalHours >= 1 ? $"{span.TotalHours:0.0} h" : $"{Math.Ceiling(span.TotalMinutes):0} min";
+ public static string Tokens(TokenCounts? counts) => counts is { } c
+ ? $"{c.Total:N0} total · input {c.Input:N0} · cache read {c.CacheRead:N0} · cache write {c.CacheWrite:N0} · output {c.Output:N0} · reasoning {c.ReasoningOutput:N0}"
+ : "Unavailable — no known session window";
+ public static string State(PaceState state) => state switch { PaceState.OnTrack => "On track", PaceState.Unknown => "Pace unknown", _ => state.ToString() };
+}
diff --git a/src/FinalToken.App/PanelWindow.cs b/src/FinalToken.App/PanelWindow.cs
new file mode 100644
index 0000000..c09a45c
--- /dev/null
+++ b/src/FinalToken.App/PanelWindow.cs
@@ -0,0 +1,130 @@
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Layout;
+using Avalonia.Media;
+using FinalToken.Core;
+
+namespace FinalToken.App;
+
+public static class Ui
+{
+ public static TextBlock Text(string text, double size = 13) => new() { Text = text, FontSize = size, TextWrapping = TextWrapping.Wrap };
+ public static StackPanel Stack(params Control[] children)
+ {
+ var stack = new StackPanel { Spacing = 10 };
+ foreach (var child in children) stack.Children.Add(child);
+ return stack;
+ }
+ public static Border Card(Control content) => new() { Child = content, Padding = new Thickness(18), CornerRadius = new CornerRadius(9), BorderThickness = new Thickness(1), BorderBrush = Brush.Parse("#558795A5") };
+ public static Button Button(string text, Action action)
+ {
+ var button = new Button { Content = text };
+ button.Click += (_, _) => action();
+ return button;
+ }
+}
+
+public sealed class PanelWindow : Window
+{
+ private readonly PanelViewModel model;
+ private readonly StackPanel body = new() { Spacing = 16, Margin = new Thickness(24) };
+ public PanelWindow(PanelViewModel model, Action refresh, Action settings, Action quit, Action reload)
+ {
+ this.model = model;
+ Title = "FinalToken"; Width = 1160; Height = 920; MinWidth = 720; MinHeight = 500;
+ var header = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12 };
+ header.Children.Add(Ui.Text("FinalToken", 28));
+ header.Children.Add(Ui.Button("Refresh now", refresh));
+ header.Children.Add(Ui.Button("Settings", settings));
+ header.Children.Add(Ui.Button("Quit", quit));
+ var range = new ComboBox { ItemsSource = new[] { "24 hours", "7 days", "30 days", "90 days", "All history" }, SelectedIndex = (int)model.Range, MinWidth = 150 };
+ range.SelectionChanged += (_, _) => { model.Range = (HistoryRange)range.SelectedIndex; reload(); };
+ var providers = new ComboBox { ItemsSource = new[] { "All providers", "Claude", "Codex" }, SelectedIndex = 0, MinWidth = 150 };
+ providers.SelectionChanged += (_, _) => { model.ProviderFilter = providers.SelectedIndex == 0 ? null : (Provider)(providers.SelectedIndex - 1); reload(); };
+ var filters = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12 };
+ filters.Children.Add(range); filters.Children.Add(providers);
+ var dock = new DockPanel { Margin = new Thickness(0, 18, 0, 0) };
+ var top = Ui.Stack(header, filters); top.Margin = new Thickness(24, 0, 24, 0);
+ DockPanel.SetDock(top, Dock.Top); dock.Children.Add(top);
+ dock.Children.Add(new ScrollViewer { Content = body }); Content = dock;
+ model.PropertyChanged += (_, _) => RenderModel();
+ RenderModel();
+ }
+ public void RenderModel()
+ {
+ body.Children.Clear();
+ body.Children.Add(Ui.Text(model.Message));
+ if (model.Snapshot is { } snapshot)
+ {
+ foreach (var provider in snapshot.Providers.Where(p => model.ProviderFilter is null || p.Provider == model.ProviderFilter))
+ {
+ var card = Ui.Stack(Ui.Text(provider.Provider.ToString(), 22), Ui.Text($"{provider.Status} {provider.Reason}"));
+ foreach (var window in provider.Windows)
+ {
+ var w = window.Window; var pace = window.Pace;
+ var title = Ui.Text($"{w.Label} {w.UsedPercent:0.##}% {Display.State(pace.State)} {(pace.Delta is { } d ? $"{d:+0.0;-0.0;0} points" : "")}", 15);
+ title.Foreground = PaceBar.Colour(pace.State);
+ card.Children.Add(title);
+ card.Children.Add(new PaceBar(window) { Height = 14 });
+ card.Children.Add(Ui.Text($"Reset: {(w.ResetsAt is { } reset ? Display.Duration(reset - DateTimeOffset.UtcNow) + " · " + reset.LocalDateTime.ToString("g") : "unknown")} Sample age: {Display.Duration(DateTimeOffset.UtcNow - w.SampleTime)}" +
+ (pace.Projection is { } projection ? $" Reaches 100%: {projection.LocalDateTime:g}" : "")));
+ }
+ card.Children.Add(Ui.Text("Tokens · provider totals", 15));
+ card.Children.Add(Ui.Text("Today " + Display.Tokens(provider.Today)));
+ card.Children.Add(Ui.Text("Session " + Display.Tokens(provider.Session)));
+ card.Children.Add(Ui.Text("Week " + Display.Tokens(provider.Week)));
+ card.Children.Add(Ui.Text("Cache read is included in Codex input; reasoning is included in output.", 11));
+ body.Children.Add(Ui.Card(card));
+ }
+ }
+ var h = model.History;
+ body.Children.Add(Ui.Card(Ui.Stack(Ui.Text("Tokens per hour", 19), Legend(h.Hourly), new UsageChart { Values = h.Hourly })));
+ body.Children.Add(Ui.Card(Ui.Stack(Ui.Text("Tokens per day · UTC days", 19), Legend(h.Daily), new UsageChart { Values = h.Daily, Interval = TimeSpan.FromDays(1) })));
+ foreach (var limit in h.Limits)
+ body.Children.Add(Ui.Card(Ui.Stack(Ui.Text(limit.Label, 19), Ui.Text("Blue: used · dashed green: expected pace · gaps: window reset", 11), new UsageChart { Values = limit.Values, Percent = true })));
+ body.Children.Add(Breakdown("By model", h.Models));
+ body.Children.Add(Breakdown("By project", h.Projects));
+ var diagnostics = Ui.Stack(Ui.Text("Recent diagnostics", 19));
+ foreach (var d in model.Diagnostics) diagnostics.Children.Add(Ui.Text($"{d.Time.LocalDateTime:g} · {d.Provider} · {d.Code} · {d.Summary}"));
+ if (model.Diagnostics.Count == 0) diagnostics.Children.Add(Ui.Text("No recent problems."));
+ body.Children.Add(Ui.Card(diagnostics));
+ }
+ private static Control Legend(IReadOnlyList values)
+ {
+ var legend = new WrapPanel { Orientation = Orientation.Horizontal };
+ var index = 0;
+ foreach (var series in values.Select(v => v.Series).Distinct())
+ {
+ var label = Ui.Text("● " + series, 12); label.Foreground = UsageChart.SeriesColour(index++);
+ label.Margin = new Thickness(0, 0, 14, 0); legend.Children.Add(label);
+ }
+ return legend;
+ }
+ private static Border Breakdown(string title, IReadOnlyList rows)
+ {
+ var table = Ui.Stack(Ui.Text(title, 19));
+ var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("3*,1*,1*,1*,1*,1*,1*,1*"), MinWidth = 900 };
+ var headers = new[] { "Name", "Total", "Share", "Input", "Cache read", "Cache write", "Output", "Reasoning" };
+ AddRow(headers, 0);
+ var index = 1;
+ foreach (var row in rows)
+ {
+ var c = row.Counts;
+ AddRow([row.Name, c.Total.ToString("N0"), row.Share.ToString("P1"), c.Input.ToString("N0"), c.CacheRead.ToString("N0"),
+ c.CacheWrite.ToString("N0"), c.Output.ToString("N0"), c.ReasoningOutput.ToString("N0")], index++);
+ }
+ table.Children.Add(new ScrollViewer { Content = grid, HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
+ VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled });
+ if (rows.Count == 0) table.Children.Add(Ui.Text("No tokens in this range."));
+ return Ui.Card(table);
+ void AddRow(string[] values, int row)
+ {
+ grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
+ for (var column = 0; column < values.Length; column++)
+ {
+ var text = Ui.Text(values[column], 11); text.Margin = new Thickness(0, 4, 8, 4);
+ Grid.SetRow(text, row); Grid.SetColumn(text, column); grid.Children.Add(text);
+ }
+ }
+ }
+}
diff --git a/src/FinalToken.App/Popups.cs b/src/FinalToken.App/Popups.cs
new file mode 100644
index 0000000..ba245f6
--- /dev/null
+++ b/src/FinalToken.App/Popups.cs
@@ -0,0 +1,70 @@
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Layout;
+using Avalonia.Media;
+using Avalonia.Threading;
+using Avalonia.Styling;
+using Avalonia.VisualTree;
+using FinalToken.Core;
+
+namespace FinalToken.App;
+
+public sealed class PopupWindow : Window
+{
+ public PopupWindow(string title, string message, Action open, string? installLabel = null, Action? install = null, Action? dismiss = null, IBrush? accent = null)
+ {
+ Width = 380; Height = install is null ? 145 : 180;
+ RequestedThemeVariant = ThemeVariant.Dark;
+ WindowDecorations = WindowDecorations.None; CanResize = false; Topmost = true; ShowInTaskbar = false; ShowActivated = false;
+ var body = Ui.Stack(Ui.Text(title, 19), Ui.Text(message));
+ if (install is not null)
+ {
+ var actions = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12 };
+ actions.Children.Add(Ui.Button(installLabel ?? "Install", () => { install(); Close(); }));
+ actions.Children.Add(Ui.Button("Not now", () => { dismiss?.Invoke(); Close(); }));
+ body.Children.Add(actions);
+ }
+ var card = Ui.Card(body); card.Background = Brush.Parse("#202C40");
+ body.Resources["TextControlForeground"] = Brushes.WhiteSmoke;
+ foreach (var text in body.Children.OfType()) text.Foreground = Brushes.WhiteSmoke;
+ ((TextBlock)body.Children[0]).Foreground = accent ?? Brushes.WhiteSmoke;
+ Content = card;
+ PointerPressed += (_, e) =>
+ {
+ var source = e.Source as Control;
+ if (source is not Button && source?.FindAncestorOfType