app: add the Avalonia desktop app

Opening the app shows the stats panel: per-provider limit bars with the
pace marker, delta, reset and projection, token totals, hourly and daily
charts, limit history with its pace line, model and project tables and
recent diagnostics (R4, D8). Pace popups stack at the bottom right
without taking focus (R5). The tray, settings, single-instance
activation, start with the OS and the Stream Deck install policy (D11)
are wired to the Core engine. Avalonia 12.1.4 and
CommunityToolkit.Mvvm 8.4.2 are the new packages D8 calls for.

Refs #1
This commit is contained in:
Florian Schmidt
2026-10-14 20:08:11 +02:00
parent 3692cbd85b
commit 183247bab5
17 changed files with 959 additions and 8 deletions
+4
View File
@@ -3,6 +3,10 @@
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally> <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageVersion Include="Avalonia.Desktop" Version="12.1.4" />
<PackageVersion Include="Avalonia.Themes.Fluent" Version="12.1.4" />
<PackageVersion Include="Avalonia.Headless" Version="12.1.4" />
<PackageVersion Include="CommunityToolkit.Mvvm" Version="8.4.2" />
<PackageVersion Include="xunit.v3.aot.mtp-v2" Version="4.0.2" /> <PackageVersion Include="xunit.v3.aot.mtp-v2" Version="4.0.2" />
</ItemGroup> </ItemGroup>
</Project> </Project>
+6 -2
View File
@@ -1,4 +1,8 @@
# App # App
Buildable placeholder only. W2 replaces Program.cs and this guidance with the Avalonia host (D8). Avalonia 12 Fluent host (D8). Views are built in C# without reflection bindings. View-model
Use RefreshEngine and source-generated snapshot DTOs from Core. Marshal Core events to the UI. 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. Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root.
+103
View File
@@ -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<ChartValue> 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.##}%");
}
}
+184
View File
@@ -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<Task> 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; }
}
}
+8 -1
View File
@@ -1,8 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>WinExe</OutputType>
<AssemblyName>FinalToken</AssemblyName> <AssemblyName>FinalToken</AssemblyName>
<PublishAot>true</PublishAot> <PublishAot>true</PublishAot>
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup> </PropertyGroup>
<ItemGroup><ProjectReference Include="../FinalToken.Core/FinalToken.Core.csproj" /></ItemGroup> <ItemGroup><ProjectReference Include="../FinalToken.Core/FinalToken.Core.csproj" /></ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Desktop" />
<PackageReference Include="Avalonia.Themes.Fluent" />
<PackageReference Include="CommunityToolkit.Mvvm" />
</ItemGroup>
</Project> </Project>
+32
View File
@@ -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);
}
}
+75
View File
@@ -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<ChartValue> Values);
public sealed record HistoryView(IReadOnlyList<ChartValue> Hourly, IReadOnlyList<ChartValue> Daily,
IReadOnlyList<LimitChart> Limits, IReadOnlyList<BreakdownRow> Models, IReadOnlyList<BreakdownRow> 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<Diagnostic> 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<ChartValue> 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<ChartValue> 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<BreakdownRow> 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() };
}
+130
View File
@@ -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<ChartValue> 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<BreakdownRow> 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);
}
}
}
}
+70
View File
@@ -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<TextBlock>()) 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<Button>() is null)
{ open(); Close(); e.Handled = true; }
};
}
public static PopupWindow Pace(PopupEvent alert, Action open) => new($"{alert.Provider} · {Display.State(alert.State)}",
$"{alert.Label}: {alert.Delta:+0.0;-0.0;0} points from pace." +
(alert.Projection is { } projection ? $" At this rate: 100% at {projection.LocalDateTime:t}." : ""), open, accent: PaceBar.Colour(alert.State));
}
public sealed class PopupStack(Action open) : IDisposable
{
private readonly List<PopupWindow> windows = [];
public void Pace(PopupEvent alert) => Show(PopupWindow.Pace(alert, open));
public void Show(PopupWindow window)
{
windows.Add(window);
window.Closed += (_, _) => { windows.Remove(window); Position(); };
window.Show(); Position();
var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(8) };
timer.Tick += (_, _) => { timer.Stop(); window.Close(); };
window.Closed += (_, _) => timer.Stop(); timer.Start();
}
private void Position()
{
var bottom = 0;
foreach (var window in windows)
{
var screen = window.Screens.Primary;
if (screen is null) continue;
var area = screen.WorkingArea; var scale = screen.Scaling;
bottom += (int)(window.Height * scale) + 12;
window.Position = new PixelPoint(area.Right - (int)(window.Width * scale) - 16, area.Bottom - bottom - 4);
}
}
public void Dispose() { foreach (var window in windows.ToArray()) window.Close(); }
}
+37 -1
View File
@@ -1 +1,37 @@
Console.WriteLine("FinalToken app placeholder; W2 supplies the Avalonia host."); using Avalonia;
using FinalToken.Core;
namespace FinalToken.App;
public static class Program
{
internal static RefreshEngine? Engine { get; private set; }
internal static string? StartupError { get; private set; }
[STAThread]
public static int Main(string[] args)
{
StoreLock? storeLock = null;
try
{
var directory = DataPaths.DataDirectory;
storeLock = StoreLock.TryAcquire(directory);
if (storeLock is null)
{
if (OperatingSystem.IsWindows()) WindowsActivation.AllowRunningInstance();
ActivationFile.RequestAsync(directory).GetAwaiter().GetResult(); return 0;
}
try { Engine = new RefreshEngine(directory); }
catch (InvalidDataException e) { StartupError = e.Message; }
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
return StartupError is null ? 0 : 1;
}
finally
{
Engine?.DisposeAsync().AsTask().GetAwaiter().GetResult();
storeLock?.Dispose();
}
}
// D8: Avalonia 12.1.4's platform detection selects X11 on Linux (XWayland).
public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure<DesktopApp>().UsePlatformDetect()
.With(new X11PlatformOptions()).LogToTrace();
}
+58
View File
@@ -0,0 +1,58 @@
using Avalonia;
using Avalonia.Controls;
using FinalToken.Core;
using FinalToken.Core.StreamDeck;
namespace FinalToken.App;
public sealed class SettingsWindow : Window
{
public SettingsWindow(Settings initial, PluginInstallStatus status, Func<Settings, Task> save)
{
Title = "FinalToken settings"; Width = 620; Height = 800;
var body = Ui.Stack(Ui.Text("Settings", 26)); body.Margin = new Thickness(24);
var refresh = Number("Token refresh (seconds, 1–60)", (decimal)initial.RefreshInterval.TotalSeconds, 1, 60);
var probe = Number("Limit probe (minutes, 1–60)", (decimal)initial.ProbeInterval.TotalMinutes, 1, 60);
var threshold = Number("Pace threshold (points)", (decimal)initial.PaceThreshold, 0.1m, 100);
var ahead = Check("Ahead popups", initial.PopupAhead); var behind = Check("Behind popups", initial.PopupBehind);
var startup = Check("Start with the OS", initial.StartWithOs); var tray = Check("Close to tray", initial.CloseToTray);
var claude = ProviderControls("Claude", initial.Claude); var codex = ProviderControls("Codex", initial.Codex);
body.Children.Add(Ui.Text("Stream Deck", 19));
body.Children.Add(Ui.Text($"{status.State} · shipped {status.ShippedVersion ?? "none"} · installed {status.InstalledVersion ?? "none"}"));
var mode = new ComboBox { ItemsSource = new[] { "Off", "Ask", "Automatic" }, SelectedIndex = (int)initial.StreamDeckInstallMode };
body.Children.Add(mode);
body.Children.Add(Ui.Text("Dismissed plugin version (clear to ask again)"));
var dismissed = new TextBox { Text = initial.DismissedPluginVersion ?? "" }; body.Children.Add(dismissed);
var error = Ui.Text(""); body.Children.Add(error);
var button = new Button { Content = "Save", HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Right };
button.Click += async (_, _) =>
{
var value = initial with { RefreshInterval = TimeSpan.FromSeconds((double)(refresh.Value ?? 0)), ProbeInterval = TimeSpan.FromMinutes((double)(probe.Value ?? 0)),
PaceThreshold = (double)(threshold.Value ?? 0), PopupAhead = ahead.IsChecked == true, PopupBehind = behind.IsChecked == true,
StartWithOs = startup.IsChecked == true, CloseToTray = tray.IsChecked == true, Claude = claude(), Codex = codex(),
StreamDeckInstallMode = (InstallMode)mode.SelectedIndex, DismissedPluginVersion = string.IsNullOrWhiteSpace(dismissed.Text) ? null : dismissed.Text.Trim() };
if (!value.IsValid) { error.Text = "Check the intervals and pace threshold."; return; }
button.IsEnabled = false;
try { await save(value); Close(); }
catch (OperationCanceledException) { error.Text = "Settings save was cancelled."; button.IsEnabled = true; }
catch (Exception e) when (e is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException)
{ error.Text = "Could not apply settings: " + e.Message; button.IsEnabled = true; }
};
body.Children.Add(button); Content = new ScrollViewer { Content = body };
NumericUpDown Number(string label, decimal value, decimal min, decimal max)
{ body.Children.Add(Ui.Text(label)); var c = new NumericUpDown { Value = value, Minimum = min, Maximum = max }; body.Children.Add(c); return c; }
CheckBox Check(string label, bool value)
{ var c = new CheckBox { Content = label, IsChecked = value }; body.Children.Add(c); return c; }
Func<ProviderSettings> ProviderControls(string name, ProviderSettings config)
{
body.Children.Add(Ui.Text(name, 19));
var enabled = Check("Enabled", config.Enabled); var popups = Check("Popups enabled", config.PopupsEnabled);
var pa = Check("Ahead", config.PopupAhead); var pb = Check("Behind", config.PopupBehind);
body.Children.Add(Ui.Text("CLI path (empty uses PATH)"));
var path = new TextBox { Name = name + "CliPath", Text = config.CliPath ?? "" }; body.Children.Add(path);
return () => config with { Enabled = enabled.IsChecked == true, PopupsEnabled = popups.IsChecked == true, PopupAhead = pa.IsChecked == true,
PopupBehind = pb.IsChecked == true, CliPath = string.IsNullOrWhiteSpace(path.Text) ? null : path.Text.Trim() };
}
}
}
+55
View File
@@ -0,0 +1,55 @@
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Avalonia.Controls;
namespace FinalToken.App;
[SupportedOSPlatform("windows")]
internal static partial class WindowsActivation
{
public static void Activate(Window window)
{
if (window.TryGetPlatformHandle() is not { } platform) return;
var handle = platform.Handle;
if (SetForegroundWindow(handle) != 0) return;
var foreground = GetForegroundWindow();
if (foreground == 0) return;
var foregroundThread = GetWindowThreadProcessId(foreground, out _);
var ownThread = GetCurrentThreadId();
if (foregroundThread == ownThread || AttachThreadInput(ownThread, foregroundThread, 1) == 0) return;
try { SetForegroundWindow(handle); }
finally { AttachThreadInput(ownThread, foregroundThread, 0); }
}
// D8: a launcher transfers its foreground permission before the running app activates.
public static void AllowRunningInstance()
{
using var current = Process.GetCurrentProcess();
foreach (var candidate in Process.GetProcessesByName(current.ProcessName))
{
using (candidate)
{
try
{
if (candidate.Id != current.Id && candidate.SessionId == current.SessionId &&
string.Equals(candidate.MainModule?.FileName, Environment.ProcessPath, StringComparison.OrdinalIgnoreCase))
AllowSetForegroundWindow(candidate.Id);
}
catch (Exception e) when (e is Win32Exception or InvalidOperationException) { }
}
}
}
[LibraryImport("user32.dll")]
private static partial int AllowSetForegroundWindow(int processId);
[LibraryImport("user32.dll")]
private static partial int SetForegroundWindow(nint window);
[LibraryImport("user32.dll")]
private static partial nint GetForegroundWindow();
[LibraryImport("user32.dll")]
private static partial uint GetWindowThreadProcessId(nint window, out uint processId);
[LibraryImport("kernel32.dll")]
private static partial uint GetCurrentThreadId();
[LibraryImport("user32.dll")]
private static partial int AttachThreadInput(uint first, uint second, int attach);
}
+3 -1
View File
@@ -1,4 +1,6 @@
# App tests # App tests
Hand-written fixtures only. xUnit v3 AOT with Microsoft.Testing.Platform. Hand-written fixtures only. xUnit v3 AOT with Microsoft.Testing.Platform.
Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root. Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root.
Placeholder test; owning worker replaces it. View-model tests use public Core queries. Headless tests run on a dedicated UI thread with
Skia and HarfBuzz, exercise settings and popup actions, and save seven PNG screenshots outside
the repo at ../runs/shots/w2. FINALTOKEN_SCREENSHOT_DIR overrides that path.
@@ -6,6 +6,7 @@
<TestingPlatformDotnetTestSupport>true</TestingPlatformDotnetTestSupport> <TestingPlatformDotnetTestSupport>true</TestingPlatformDotnetTestSupport>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Avalonia.Headless" />
<PackageReference Include="xunit.v3.aot.mtp-v2" /> <PackageReference Include="xunit.v3.aot.mtp-v2" />
<ProjectReference Include="../../src/FinalToken.App/FinalToken.App.csproj" /> <ProjectReference Include="../../src/FinalToken.App/FinalToken.App.csproj" />
</ItemGroup> </ItemGroup>
+104
View File
@@ -0,0 +1,104 @@
using Avalonia;
using Avalonia.Controls;
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", "w2");
Directory.CreateDirectory(shots);
var model = FakeData.Model();
var panel = new PanelWindow(model, () => { }, () => { }, () => { }, () => { }) { Height = 2450 };
panel.RequestedThemeVariant = ThemeVariant.Light; panel.Show(); Save(panel, "panel-light.png");
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Claude");
var filters = panel.GetVisualDescendants().OfType<ComboBox>().ToArray();
filters[0].SelectedIndex = 4; filters[1].SelectedIndex = 2;
Assert.Equal(HistoryRange.All, model.Range); Assert.Equal(Provider.Codex, model.ProviderFilter);
filters[0].SelectedIndex = 1; filters[1].SelectedIndex = 0;
panel.RequestedThemeVariant = ThemeVariant.Dark; Save(panel, "panel-dark.png");
model.Snapshot = FakeData.Snapshot(DateTimeOffset.UtcNow, true); Save(panel, "panel-unavailable.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 };
settings.Show(); Save(settings, "settings.png");
var refresh = settings.GetVisualDescendants().OfType<NumericUpDown>().First(); refresh.Value = 25;
settings.GetVisualDescendants().OfType<CheckBox>().First().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, DateTimeOffset.UtcNow.AddHours(1)), () => opened++);
ahead.Show(); Save(ahead, "popup-ahead.png"); 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();
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.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);
using var stack = new PopupStack(() => { });
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(DateTimeOffset.UtcNow, "Exact", 123456)] };
var chartWindow = new Window { Content = chart, Width = 400, Height = 180 };
chartWindow.Show();
using (chartWindow.CaptureRenderedFrame()) { }
chartWindow.MouseMove(new Point(65, 30));
Assert.Contains(123456.ToString("N0"), ToolTip.GetTip(chart)?.ToString()); chartWindow.Close();
Thread.Sleep(8200); Dispatcher.UIThread.RunJobs();
Assert.False(first.IsVisible); Assert.False(second.IsVisible);
completion.SetResult();
void Save(Window window, string name)
{
Dispatcher.UIThread.RunJobs();
using var bitmap = window.CaptureRenderedFrame(); Assert.NotNull(bitmap);
using var output = File.Create(Path.Combine(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(new FluentTheme()); }
}
@@ -1,3 +0,0 @@
using Xunit;
namespace FinalToken.App.Tests;
public class PlaceholderTests { [Fact] public void FoundationBuilds() => Assert.True(true); }
@@ -0,0 +1,89 @@
using FinalToken.Core;
using Xunit;
namespace FinalToken.App.Tests;
public sealed class ViewModelTests
{
[Theory]
[InlineData(HistoryRange.Hours24, 1)]
[InlineData(HistoryRange.Days7, 7)]
[InlineData(HistoryRange.Days30, 30)]
[InlineData(HistoryRange.Days90, 90)]
public void RangeUsesRequestedDuration(HistoryRange range, int days)
{ var now = DateTimeOffset.UtcNow; Assert.Equal(now.AddDays(-days), PanelViewModel.RangeStart(range, now)); }
[Fact] public void AllRangeIncludesOldHistory() => Assert.Equal(DateTimeOffset.MinValue, PanelViewModel.RangeStart(HistoryRange.All, DateTimeOffset.UtcNow));
[Fact] public void UnknownSessionIsNotDisplayedAsZero() => Assert.Contains("Unavailable", Display.Tokens(null));
[Fact] public void PropertiesNotify()
{
var vm = new PanelViewModel(); var notified = new List<string?>(); vm.PropertyChanged += (_, e) => notified.Add(e.PropertyName);
vm.ProviderFilter = Provider.Codex; vm.Range = HistoryRange.Days30;
Assert.Contains(nameof(vm.ProviderFilter), notified); Assert.Contains(nameof(vm.Range), notified);
}
[Fact] public void HistoryFiltersProvidersAndGroupsModelsWithoutDoubleCounting()
{
var directory = Path.Combine(Path.GetTempPath(), "finaltoken-app-tests", Guid.NewGuid().ToString("N"));
var store = new HistoryStore(directory, new DiagnosticLog()); var now = DateTimeOffset.UtcNow;
store.Add(new(Provider.Claude, now.AddHours(-2), "a", "project", new(Total: 30), "1"));
store.Add(new(Provider.Claude, now.AddHours(-2), "b", "project", new(Total: 70), "2"));
store.Add(new(Provider.Codex, now.AddHours(-2), "b", "other", new(Total: 100), "3"));
var snapshot = FakeData.Snapshot(now);
var all = PanelViewModel.QueryHistory(store, snapshot, HistoryRange.Days7, null, now);
Assert.Equal(200, all.Hourly.Sum(p => p.Value)); Assert.Equal(200, all.Daily.Sum(p => p.Value));
Assert.Equal(1, all.Models.Sum(m => m.Share), 6);
var filtered = PanelViewModel.QueryHistory(store, snapshot, HistoryRange.Days7, Provider.Claude, now);
Assert.Equal(100, filtered.Hourly.Sum(p => p.Value)); Assert.Equal(2, filtered.Hourly.Count);
Assert.Single(filtered.Projects); Assert.Equal(1, filtered.Projects[0].Share);
}
[Fact] public void EmptyHistoryHasNoInventedData()
{
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog());
var history = PanelViewModel.QueryHistory(store, FakeData.Snapshot(DateTimeOffset.UtcNow), HistoryRange.All, null, DateTimeOffset.UtcNow);
Assert.Empty(history.Hourly); Assert.Empty(history.Models); Assert.Empty(history.Projects);
}
[Fact] public void SelectedProviderDailySeriesRespectsPartialDays()
{
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(-26), "outside", "p", new(Total: 300), "outside"));
store.Add(new(Provider.Claude, now.AddHours(-22), "inside", "p", new(Total: 100), "inside"));
store.Add(new(Provider.Claude, now.AddHours(-3), "inside", "p", new(Total: 50), "today"));
var view = PanelViewModel.QueryHistory(store, FakeData.Snapshot(now), HistoryRange.Hours24, Provider.Claude, now);
Assert.Equal(150, view.Hourly.Sum(v => v.Value));
Assert.Equal(150, view.Daily.Sum(v => v.Value));
Assert.DoesNotContain(view.Daily, v => v.Series == "outside");
}
[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 DesktopEntryRejectsInjectedLine() => Assert.Throws<ArgumentException>(() => OsStartup.DesktopEntry("/app\nExec=other"));
[Fact] public void DesktopEntryEscapesCommandCharactersAtBothParsingLevels()
{
var entry = OsStartup.DesktopEntry("/opt/a\"$`\\file");
Assert.Contains("a\\\\\"\\\\$\\\\`\\\\\\\\file", entry);
}
}
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.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))]
};
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.")] };
}
}