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:
@@ -1,4 +1,6 @@
|
||||
# App tests
|
||||
Hand-written fixtures only. xUnit v3 AOT with Microsoft.Testing.Platform.
|
||||
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>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Avalonia.Headless" />
|
||||
<PackageReference Include="xunit.v3.aot.mtp-v2" />
|
||||
<ProjectReference Include="../../src/FinalToken.App/FinalToken.App.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -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.")] };
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user