feat: add FinalToken v1 for Claude and Codex usage (#2)

FinalToken v1: a NativeAOT tray app for Windows 11 and CachyOS that tracks
Claude Code and Codex usage and limits through their CLIs only, with no
provider sign-in and no tokens (R1-R7, D1-D11).

- Core: incremental collectors for Claude transcripts and Codex
  rollouts, limit probes through `claude -p /usage` and
  `codex app-server`, a journaled history store, the refresh engine,
  pace and popup decisions, and the snapshot.json contract.
- App (Avalonia): stats panel with limit bars, pace, projections, token
  totals, charts, limit history and breakdowns; tray, settings,
  non-activating pace popups, single-instance activation, start with
  the OS, and the Off/Ask/Automatic Stream Deck plugin install.
- Stream Deck plugin (SDK v2, NativeAOT) for Elgato and OpenDeck.
- finaltoken-cli, tools/publish.py, the documentation check and the
  agent review workflow.

Closes #1
This commit was merged in pull request #2.
This commit is contained in:
2026-10-14 22:11:19 +02:00
parent 6d67f157a5
commit f8afd11679
106 changed files with 6583 additions and 0 deletions
+7
View File
@@ -0,0 +1,7 @@
# 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.
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 PNG screenshots outside
the repo at ../runs/shots/app. FINALTOKEN_SCREENSHOT_DIR overrides that path.
Popup expiry uses an injected TimeProvider; fire timers and pump the dispatcher instead of sleeping.
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<IsTestProject>true</IsTestProject>
<UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner>
<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>
</Project>
@@ -0,0 +1,71 @@
using System.Globalization;
using Xunit;
namespace FinalToken.App.Tests;
public sealed class FormattingTests
{
[Fact]
public void DailyChartLabelAndTooltipUseTheBucketsLocalDate()
{
var zone = TimeZoneInfo.CreateCustomTimeZone("Fixture+02", TimeSpan.FromHours(2), "Fixture", "Fixture");
var day = FinalToken.Core.CalendarDays.Start(new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero), zone);
Assert.Equal("10-14", Display.ChartDateLabel(day, TimeSpan.FromDays(1)));
Assert.Equal(day.DateTime.ToString("g"), Display.ChartTimestamp(day, TimeSpan.FromDays(1)));
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("custom-config")]
public void LinuxAutostartHonorsConfigHome(string? configHome)
{
var home = Path.Combine(Path.GetTempPath(), "fixture-home");
var config = string.IsNullOrEmpty(configHome) ? null : Path.Combine(Path.GetTempPath(), configHome);
Assert.Equal(Path.Combine(config ?? Path.Combine(home, ".config"), "autostart", "finaltoken.desktop"), OsStartup.LinuxAutostartPath(config, home));
}
[Theory]
[InlineData("de-DE")]
[InlineData("en-US")]
public void FutureProjectionIncludesLocalDateInUsersCulture(string culture)
{
var clock = new FixedClock();
var projection = new DateTimeOffset(2026, 10, 16, 6, 24, 0, TimeSpan.Zero);
var userCulture = CultureInfo.GetCultureInfo(culture);
Assert.Equal(new DateTime(2026, 10, 16, 8, 24, 0).ToString("g", userCulture), Display.Projection(projection, clock, userCulture));
}
[Fact]
public void TodaysProjectionUsesLocalTimeOnly()
{
Assert.Equal("23:24", Display.Projection(new(2026, 10, 14, 21, 24, 0, TimeSpan.Zero), new FixedClock(), CultureInfo.GetCultureInfo("de-DE")));
}
[Fact]
public void ProjectionDateChangesAtLocalMidnight()
{
Assert.Equal("15.10.2026 00:24", Display.Projection(new(2026, 10, 14, 22, 24, 0, TimeSpan.Zero), new FixedClock(), CultureInfo.GetCultureInfo("de-DE")));
}
[Theory]
[InlineData(0, new double[] { 0 })]
[InlineData(1, new double[] { 0, 1 })]
[InlineData(2, new double[] { 0, 1, 2 })]
[InlineData(3, new double[] { 0, 1, 2, 3 })]
public void SmallChartTicksAreDistinctIntegers(double maximum, double[] expected)
=> Assert.Equal(expected, UsageChart.AxisTicks(maximum));
[Theory]
[InlineData(5, new double[] { 0, 2, 4, 6 })]
[InlineData(17, new double[] { 0, 5, 10, 15, 20 })]
[InlineData(123456, new double[] { 0, 50000, 100000, 150000 })]
public void LargerChartTicksUseRoundedStepsAndCoverMaximum(double maximum, double[] expected)
=> Assert.Equal(expected, UsageChart.AxisTicks(maximum));
[Fact]
public void PercentTicksKeepQuarterMarksAndEmptyPercentChartHasOnlyZero()
{
Assert.Equal([0d, 25, 50, 75, 100], UsageChart.AxisTicks(3, true));
Assert.Equal([0d], UsageChart.AxisTicks(0, true));
}
private sealed class FixedClock : TimeProvider
{
public override DateTimeOffset GetUtcNow() => new(2026, 10, 14, 18, 0, 0, TimeSpan.Zero);
public override TimeZoneInfo LocalTimeZone { get; } = TimeZoneInfo.CreateCustomTimeZone("Fixture+02", TimeSpan.FromHours(2), "Fixture", "Fixture");
}
}
+144
View File
@@ -0,0 +1,144 @@
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", "app");
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.Equal($"FinalToken {typeof(Program).Assembly.GetName().Version!.ToString(3)}", panel.Title);
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Claude");
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Tokens per day");
var filters = panel.GetVisualDescendants().OfType<ComboBox>().ToArray();
filters[0].SelectedIndex = 4; filters[1].SelectedIndex = 2;
Assert.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);
var popupClock = new PopupClock();
using var stack = new PopupStack(() => { }, popupClock);
var first = PopupWindow.Pace(new(Provider.Claude, "a", "Session", PaceState.Ahead, 20, null), () => { });
var second = PopupWindow.Pace(new(Provider.Codex, "b", "Week", PaceState.Behind, -20, null), () => { });
stack.Show(first); stack.Show(second); Assert.True(second.Position.Y < first.Position.Y);
var chart = new UsageChart { Values = [new(DateTimeOffset.UtcNow, "Exact", 123456)] };
var chartWindow = new Window { Content = chart, Width = 400, Height = 180 };
chartWindow.Show();
using (chartWindow.CaptureRenderedFrame()) { }
chartWindow.MouseMove(new Point(65, 80));
Assert.Contains(123456.ToString("N0"), ToolTip.GetTip(chart)?.ToString()); chartWindow.Close();
var polishShots = shots;
Directory.CreateDirectory(polishShots);
var emptyChart = new Window { Content = Ui.Card(Ui.Stack(Ui.Text("Tokens per hour", 19), new UsageChart())), Width = 620, Height = 260,
RequestedThemeVariant = ThemeVariant.Light };
emptyChart.Show(); Save(emptyChart, "chart-empty.png", polishShots); emptyChart.Close();
var time = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
var smallChart = new Window { Content = Ui.Card(Ui.Stack(Ui.Text("Tokens per hour", 19), new UsageChart
{ Values = [new(time, "Claude", 1), new(time.AddHours(1), "Claude", 2), new(time.AddHours(2), "Claude", 3)] })),
Width = 620, Height = 260, RequestedThemeVariant = ThemeVariant.Light };
smallChart.Show(); Save(smallChart, "chart-max-3.png", polishShots); smallChart.Close();
var day = new DateTimeOffset(2026, 10, 14, 0, 0, 0, TimeSpan.FromHours(2));
var daily = new UsageChart { Interval = TimeSpan.FromDays(1), Values = [new(day, "Claude", 3), new(day.AddDays(1), "Claude", 2)] };
var dailyWindow = new Window { Content = Ui.Card(Ui.Stack(Ui.Text("Tokens per day", 19), daily)),
Width = 620, Height = 260, RequestedThemeVariant = ThemeVariant.Light };
dailyWindow.Show(); Save(dailyWindow, "chart-local-day.png");
dailyWindow.MouseMove(new Point(90, 150));
Assert.Contains(day.DateTime.ToString("g"), ToolTip.GetTip(daily)?.ToString()); dailyWindow.Close();
popupClock.Fire(); Dispatcher.UIThread.RunJobs();
Assert.False(first.IsVisible); Assert.False(second.IsVisible);
Assert.All(popupClock.Timers, timer => Assert.True(timer.Disposed));
completion.SetResult();
void Save(Window window, string name, string? destination = null)
{
Dispatcher.UIThread.RunJobs();
using var bitmap = window.CaptureRenderedFrame(); Assert.NotNull(bitmap);
using var output = File.Create(Path.Combine(destination ?? shots, name)); bitmap.Save(output, PngBitmapEncoderOptions.Default);
Assert.True(output.Length > 2000);
}
}
catch (Exception e) { completion.SetException(e); }
});
if (OperatingSystem.IsWindows()) thread.SetApartmentState(ApartmentState.STA);
thread.Start(); await completion.Task; thread.Join();
}
public sealed class TestApplication : Application
{ public override void Initialize() => Styles.Add(new FluentTheme()); }
private sealed class PopupClock : TimeProvider
{
public List<PopupTimer> Timers { get; } = [];
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
{
Assert.Equal(TimeSpan.FromSeconds(8), dueTime);
Assert.Equal(Timeout.InfiniteTimeSpan, period);
var timer = new PopupTimer(callback, state); Timers.Add(timer); return timer;
}
public void Fire() { foreach (var timer in Timers.Where(t => !t.Disposed)) timer.Fire(); }
}
private sealed class PopupTimer(TimerCallback callback, object? state) : ITimer
{
public bool Disposed { get; private set; }
public void Fire() => callback(state);
public bool Change(TimeSpan dueTime, TimeSpan period) => throw new NotSupportedException();
public void Dispose() => Disposed = true;
public ValueTask DisposeAsync() { Dispose(); return ValueTask.CompletedTask; }
}
}
@@ -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.")] };
}
}
+4
View File
@@ -0,0 +1,4 @@
# Cli tests
Hand-written fixtures only. xUnit v3 AOT with Microsoft.Testing.Platform.
Run `dotnet test --project tests/FinalToken.Cli.Tests -c Release` from the root.
Cover behavior and failure boundaries, not implementation details.
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
+122
View File
@@ -0,0 +1,122 @@
using FinalToken.Cli;
using FinalToken.Core;
using Xunit;
namespace FinalToken.Cli.Tests;
public class CliTests
{
[Fact]
public async Task UnexpectedRefreshFailureReturnsOneWithoutExceptionText()
{
var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N"));
try
{
using var output = new StringWriter(); using var error = new StringWriter();
Assert.Equal(1, await CliApplication.RunAsync(["status"], output, error, directory,
_ => throw new System.Text.Json.JsonException("synthetic private input"), TestContext.Current.CancellationToken));
Assert.Contains("could not complete", error.ToString()); Assert.DoesNotContain("synthetic private", error.ToString());
}
finally { if (Directory.Exists(directory)) Directory.Delete(directory, true); }
}
[Theory]
[InlineData("")]
[InlineData("unknown")]
[InlineData("status --unknown")]
[InlineData("status --json --json")]
public async Task InvalidUsageExitsTwo(string command)
{
using var output = new StringWriter();
using var error = new StringWriter();
Assert.Equal(2, await CliApplication.RunAsync(command.Split(' ', StringSplitOptions.RemoveEmptyEntries), output, error, cancellationToken: TestContext.Current.CancellationToken));
Assert.Contains("Usage: finaltoken-cli status", error.ToString());
}
[Fact]
public async Task BusyStoreReadsExistingSnapshotAndDoesNotRefresh()
{
var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(directory);
try
{
using var storeLock = StoreLock.TryAcquire(directory);
await SnapshotFile.WriteAsync(directory, new Snapshot { MadeAt = DateTimeOffset.UtcNow, RefreshInterval = TimeSpan.FromSeconds(60), Providers = [] }, TestContext.Current.CancellationToken);
using var output = new StringWriter();
using var error = new StringWriter();
Assert.Equal(0, await CliApplication.RunAsync(["status", "--json"], output, error, directory,
_ => throw new InvalidOperationException("Must not create a writing engine."), TestContext.Current.CancellationToken));
Assert.Contains("\"v\":1", output.ToString());
Assert.Contains("Store is in use", error.ToString());
}
finally { Directory.Delete(directory, true); }
}
[Fact]
public async Task StatusNoProbeWritesSnapshotAndText()
{
var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(directory);
try
{
using var output = new StringWriter();
using var error = new StringWriter();
Assert.Equal(0, await CliApplication.RunAsync(["status", "--no-probe"], output, error, directory,
path => new(path, claudeDirectory: path, codexDirectory: path, cliDiscovery: (_, _) => new(null, "Fixture CLI missing.")), TestContext.Current.CancellationToken));
Assert.Contains("Tokens today: 0", output.ToString());
Assert.NotNull(SnapshotFile.Read(directory).Snapshot);
}
finally { Directory.Delete(directory, true); }
}
[Fact]
public async Task BusyStoreWithoutSnapshotExitsOne()
{
var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(directory);
try
{
using var storeLock = StoreLock.TryAcquire(directory);
using var output = new StringWriter();
using var error = new StringWriter();
Assert.Equal(1, await CliApplication.RunAsync(["status"], output, error, directory, cancellationToken: TestContext.Current.CancellationToken));
}
finally { Directory.Delete(directory, true); }
}
[Fact]
public async Task PrintsFoldedDiagnosticCountAndLastTime()
{
var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(directory);
try
{
using var output = new StringWriter();
using var error = new StringWriter();
var result = await CliApplication.RunAsync(["status", "--no-probe"], output, error, directory, path =>
{
var engine = new RefreshEngine(path, claudeDirectory: path, codexDirectory: path,
cliDiscovery: (_, _) => new(null, "Fixture CLI missing."));
for (var i = 0; i < 20; i++) engine.Diagnostics.Add(Provider.Claude, "fixture-parse", "Malformed usage.");
return engine;
}, TestContext.Current.CancellationToken);
Assert.Equal(0, result);
Assert.Contains("fixture-parse (x20, last ", error.ToString());
Assert.Equal(1, error.ToString().Split('\n').Count(line => line.StartsWith("fixture-parse", StringComparison.Ordinal)));
}
finally { Directory.Delete(directory, true); }
}
[Fact]
public async Task StatusKeepsExistingDesktopPath()
{
var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(directory);
try
{
await SnapshotFile.WriteAsync(directory, new Snapshot { MadeAt = DateTimeOffset.UtcNow,
RefreshInterval = TimeSpan.FromMinutes(1), Providers = [], AppPath = "desktop.exe" }, TestContext.Current.CancellationToken);
using var output = new StringWriter();
using var error = new StringWriter();
Assert.Equal(0, await CliApplication.RunAsync(["status", "--no-probe"], output, error, directory,
path => new(path, claudeDirectory: path, codexDirectory: path, cliDiscovery: (_, _) => new(null, "Fixture CLI missing.")),
TestContext.Current.CancellationToken));
Assert.Equal("desktop.exe", SnapshotFile.Read(directory).Snapshot!.AppPath);
}
finally { Directory.Delete(directory, true); }
}
}
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<IsTestProject>true</IsTestProject>
<UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner>
<TestingPlatformDotnetTestSupport>true</TestingPlatformDotnetTestSupport>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="xunit.v3.aot.mtp-v2" />
<ProjectReference Include="../../src/FinalToken.Cli/FinalToken.Cli.csproj" />
</ItemGroup>
</Project>
+4
View File
@@ -0,0 +1,4 @@
# Core tests
Hand-written fixtures only. xUnit v3 AOT with Microsoft.Testing.Platform.
Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root.
Cover behavior and failure boundaries, not implementation details.
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
@@ -0,0 +1,88 @@
using FinalToken.Core.Processes;
using FinalToken.Core.StreamDeck;
using Xunit;
namespace FinalToken.Core.Tests;
public class DiscoveryAndPolicyTests
{
[Fact]
public void WindowsClaudeNpmShimResolvesInstalledNativeBinary()
{
using var directory = new TestDirectory(); directory.Write("claude.cmd", "fixture");
var binary = directory.Write("node_modules/@anthropic-ai/claude-code/bin/claude.exe", "fixture native");
Assert.Equal(binary, CliDiscovery.Find(Provider.Claude, searchPath: directory.Path, windows: true).Command?.FileName);
}
[Fact]
public void WindowsClaudeNpmShimFallsBackToLegacyCliScriptWithoutShell()
{
using var directory = new TestDirectory(); directory.Write("claude.cmd", "fixture");
var script = directory.Write("node_modules/@anthropic-ai/claude-code/cli.js", "fixture script");
var node = directory.Write("node.exe", "fixture node");
var command = CliDiscovery.Find(Provider.Claude, searchPath: directory.Path, windows: true).Command;
Assert.NotNull(command); Assert.Equal(node, command.FileName); Assert.Equal([script], command.PrefixArguments);
}
[Fact]
public void FindsNativeWindowsAndHonorsOverride()
{
using var directory = new TestDirectory();
var path = directory.Write("claude.exe", "fixture");
Assert.Equal(path, CliDiscovery.Find(Provider.Claude, searchPath: directory.Path, windows: true).Command!.FileName);
Assert.Null(CliDiscovery.Find(Provider.Claude, Path.Combine(directory.Path, "missing.exe"), windows: true).Command);
}
[Fact]
public void ResolvesWindowsCodexNpmNativeBinaryWithoutShell()
{
using var directory = new TestDirectory();
directory.Write("codex.cmd", "fixture");
var binary = directory.Write("node_modules/@openai/codex/node_modules/@openai/codex-win32-x64/vendor/x86_64-pc-windows-msvc/bin/codex.exe", "fixture");
Assert.Equal(binary, CliDiscovery.Find(Provider.Codex, searchPath: directory.Path, windows: true).Command!.FileName);
}
[Fact]
public void ResolvesWindowsNpmNodeFallback()
{
using var directory = new TestDirectory();
directory.Write("codex.cmd", "fixture");
var script = directory.Write("node_modules/@openai/codex/bin/codex.js", "fixture");
var node = directory.Write("node.exe", "fixture");
var command = CliDiscovery.Find(Provider.Codex, searchPath: directory.Path, windows: true).Command;
Assert.NotNull(command);
Assert.Equal(node, command.FileName);
Assert.Equal(script, Assert.Single(command.PrefixArguments));
}
[Fact]
public void LinuxNativeAndNodeShebangWork()
{
using var directory = new TestDirectory();
var binary = directory.Write("codex", "ELF fixture");
Assert.Equal(binary, CliDiscovery.Find(Provider.Codex, overridePath: binary, searchPath: directory.Path, windows: false).Command!.FileName);
directory.Write("codex", "#!/usr/bin/env node\nfixture");
var node = directory.Write("node", "fixture");
var command = CliDiscovery.Find(Provider.Codex, overridePath: binary, searchPath: directory.Path, windows: false).Command;
Assert.Equal(node, command!.FileName);
Assert.Equal(binary, Assert.Single(command.PrefixArguments));
}
[Fact]
public void MissingCliAndUnsupportedWrapperAreUnavailable()
{
using var directory = new TestDirectory();
Assert.Null(CliDiscovery.Find(Provider.Claude, searchPath: directory.Path, windows: true).Command);
directory.Write("codex.cmd", "fixture");
Assert.Null(CliDiscovery.Find(Provider.Codex, searchPath: directory.Path, windows: true).Command);
}
[Fact]
public void InvalidOverrideBecomesUnavailableInsteadOfStoppingRefresh()
{
Assert.Null(CliDiscovery.Find(Provider.Claude, "invalid\0path", windows: true).Command);
}
[Theory]
[InlineData(InstallMode.Off, PluginInstallState.NotInstalled, InstallAction.Nothing)]
[InlineData(InstallMode.Ask, PluginInstallState.NotInstalled, InstallAction.Ask)]
[InlineData(InstallMode.Automatic, PluginInstallState.Outdated, InstallAction.Install)]
[InlineData(InstallMode.Automatic, PluginInstallState.NoHostFound, InstallAction.Nothing)]
[InlineData(InstallMode.Automatic, PluginInstallState.NoShippedPlugin, InstallAction.Nothing)]
[InlineData(InstallMode.Automatic, PluginInstallState.UpToDate, InstallAction.Nothing)]
public void InstallPolicyHonorsModeAndStatus(InstallMode mode, PluginInstallState state, InstallAction expected) =>
Assert.Equal(expected, InstallPolicy.Decide(mode, new(state, "1.0", "0.9"), null));
[Fact] public void AskHonorsDismissedVersion() => Assert.Equal(InstallAction.Nothing, InstallPolicy.Decide(InstallMode.Ask, new(PluginInstallState.Outdated, "1.0"), "1.0"));
}
+160
View File
@@ -0,0 +1,160 @@
using FinalToken.Core.Collectors;
using FinalToken.Core.Processes;
using Xunit;
namespace FinalToken.Core.Tests;
public class EngineTests
{
private static RefreshEngine Engine(TestDirectory directory, TestClock clock, FakeRunner runner) =>
new(directory.Path, clock, runner, Path.Combine(directory.Path, "claude"), Path.Combine(directory.Path, "codex"),
(_, _) => new(new("fixture.exe", []), null));
[Fact]
public async Task SchedulerDebouncesChangesAndRunsPeriodicScansWithoutOverprobing()
{
using var directory = new TestDirectory();
var clock = new TestClock();
var runner = new FakeRunner();
await using var engine = Engine(directory, clock, runner);
var snapshots = 0;
engine.SnapshotChanged += _ => snapshots++;
await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(2, runner.Requests.Count);
engine.NotifySourceChanged();
clock.Advance(TimeSpan.FromSeconds(1));
await engine.TickAsync(TestContext.Current.CancellationToken);
Assert.Equal(1, snapshots);
engine.NotifySourceChanged();
clock.Advance(TimeSpan.FromSeconds(1));
await engine.TickAsync(TestContext.Current.CancellationToken);
Assert.Equal(1, snapshots);
clock.Advance(TimeSpan.FromSeconds(1));
await engine.TickAsync(TestContext.Current.CancellationToken);
Assert.Equal(2, snapshots);
Assert.Equal(2, runner.Requests.Count);
clock.Advance(TimeSpan.FromMinutes(1));
await engine.TickAsync(TestContext.Current.CancellationToken);
Assert.Equal(3, snapshots);
clock.Advance(TimeSpan.FromMinutes(4));
await engine.TickAsync(TestContext.Current.CancellationToken);
Assert.Equal(4, runner.Requests.Count);
}
[Fact]
public async Task TokensTriggerProbeWithOneMinuteThrottlePerProvider()
{
using var directory = new TestDirectory();
var clock = new TestClock();
var runner = new FakeRunner();
await using var engine = Engine(directory, clock, runner);
await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
var path = directory.Write("claude/projects/p/a.jsonl", Fixtures.Claude());
clock.Advance(TimeSpan.FromSeconds(30));
await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(2, runner.Requests.Count);
await File.AppendAllTextAsync(path, Fixtures.Claude("b"), TestContext.Current.CancellationToken);
clock.Advance(TimeSpan.FromSeconds(30));
await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(3, runner.Requests.Count);
Assert.False(runner.Requests[^1].CodexRpc);
}
[Fact]
public async Task ThrottledTokenProbeRemainsPendingWithoutAnotherTokenEvent()
{
using var directory = new TestDirectory();
var clock = new TestClock();
var runner = new FakeRunner();
await using var engine = Engine(directory, clock, runner);
await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
directory.Write("claude/projects/p/a.jsonl", Fixtures.Claude());
clock.Advance(TimeSpan.FromSeconds(30));
await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(2, runner.Requests.Count);
clock.Advance(TimeSpan.FromSeconds(30));
await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(3, runner.Requests.Count);
}
[Fact]
public async Task FailedProbeKeepsLastGoodSampleWithItsAge()
{
using var directory = new TestDirectory();
var clock = new TestClock();
var runner = new FakeRunner();
await using var engine = Engine(directory, clock, runner);
await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
var original = engine.CurrentSnapshot!.Providers[0].Windows[0].Window;
runner.Handler = (_, _) => Task.FromResult(new ProcessResult(-1, "", TimedOut: true));
clock.Advance(TimeSpan.FromMinutes(5));
var snapshot = await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(original, snapshot.Providers[0].Windows[0].Window);
Assert.Equal(TimeSpan.FromMinutes(5), snapshot.Providers[0].Windows[0].Age(clock.GetUtcNow()));
Assert.Equal(ProviderStatus.Unavailable, snapshot.Providers[0].Status);
Assert.Contains(engine.RecentDiagnostics, d => d.Code == "probe-timeout");
}
[Fact]
public async Task StopCancelsAndWaitsForRunningProbe()
{
using var directory = new TestDirectory();
var clock = new TestClock();
var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var stopped = false;
var runner = new FakeRunner { Handler = async (_, token) =>
{
started.SetResult();
try { await Task.Delay(Timeout.InfiniteTimeSpan, token); }
finally { stopped = true; }
return new(0, "");
} };
await using var engine = Engine(directory, clock, runner);
await engine.StartAsync(TestContext.Current.CancellationToken);
await started.Task.WaitAsync(TestContext.Current.CancellationToken);
await engine.StopAsync();
Assert.True(stopped);
Assert.Null(engine.CurrentSnapshot);
}
[Fact]
public async Task NoProbeAndDisabledProvidersNeverStartProcesses()
{
using var directory = new TestDirectory();
var clock = new TestClock();
var runner = new FakeRunner();
await using var engine = Engine(directory, clock, runner);
await engine.RefreshNowAsync(true, TestContext.Current.CancellationToken);
Assert.Empty(runner.Requests);
await engine.UpdateSettingsAsync(new Settings { Claude = new() { Enabled = false }, Codex = new() { Enabled = false } }, TestContext.Current.CancellationToken);
var snapshot = await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
Assert.Empty(runner.Requests);
Assert.All(snapshot.Providers, p => Assert.Equal(ProviderStatus.Disabled, p.Status));
}
[Fact]
public async Task ActivationIsRaisedOncePerRequestAndEventsRunOffCallerContext()
{
using var directory = new TestDirectory();
await using var engine = Engine(directory, new(), new());
var activations = 0;
var context = new SynchronizationContext();
var previousContext = SynchronizationContext.Current;
try
{
SynchronizationContext.SetSynchronizationContext(context);
engine.ActivationRequested += () => { Assert.NotSame(context, SynchronizationContext.Current); activations++; };
await ActivationFile.RequestAsync(directory.Path, TestContext.Current.CancellationToken);
await engine.TickAsync(TestContext.Current.CancellationToken);
await engine.TickAsync(TestContext.Current.CancellationToken);
Assert.Equal(1, activations);
}
finally { SynchronizationContext.SetSynchronizationContext(previousContext); }
}
[Fact]
public async Task ProbeUsesExactClaudeArgumentsWorkingDirectoryAndTimeout()
{
using var directory = new TestDirectory();
var runner = new FakeRunner();
var probe = new LimitProbe(runner, new(), directory.Path);
var result = await probe.RunAsync(Provider.Claude, new("fixture", []), new TestClock().GetUtcNow(), TestContext.Current.CancellationToken);
Assert.True(result.Success);
var request = Assert.Single(runner.Requests);
Assert.Equal(["-p", "/usage", "--output-format", "json", "--no-session-persistence"], request.Arguments);
Assert.Equal(directory.Path, request.WorkingDirectory);
Assert.Equal(TimeSpan.FromSeconds(60), request.Timeout);
}
}
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<IsTestProject>true</IsTestProject>
<UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner>
<TestingPlatformDotnetTestSupport>true</TestingPlatformDotnetTestSupport>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="xunit.v3.aot.mtp-v2" />
<ProjectReference Include="../../src/FinalToken.Core/FinalToken.Core.csproj" />
<ProjectReference Include="../FinalToken.ProcessHost/FinalToken.ProcessHost.csproj" ReferenceOutputAssembly="false" />
</ItemGroup>
<Target Name="CopyProcessHost" AfterTargets="Build">
<ItemGroup>
<ProcessHostFiles Include="$(MSBuildThisFileDirectory)../../artifacts/bin/FinalToken.ProcessHost/$(Configuration)/$(TargetFramework)/*" />
</ItemGroup>
<Copy SourceFiles="@(ProcessHostFiles)" DestinationFolder="$(OutDir)ProcessHost" SkipUnchangedFiles="true" />
</Target>
</Project>
@@ -0,0 +1,121 @@
using System.Diagnostics;
using System.Text.Json;
using FinalToken.Core.Collectors;
using Xunit;
namespace FinalToken.Core.Tests;
public class IntegrationTests
{
[Fact]
public async Task GuiHostProbeReceivesValidStandardHandlesWithoutConsole()
=> await RunGuiProbe("--handles-probe");
[Fact]
public async Task GuiHostDecodesUtf8ProviderJsonWithoutConsoleCodePage()
=> await RunGuiProbe("--utf8-probe");
private static async Task RunGuiProbe(string mode)
{
if (!OperatingSystem.IsWindows()) return;
using var directory = new TestDirectory();
var reportPath = Path.Combine(directory.Path, "report.json");
using var process = new Process { StartInfo = new()
{
FileName = Path.Combine(AppContext.BaseDirectory, "ProcessHost", "FinalToken.ProcessHost.exe"),
UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = directory.Path
} };
process.StartInfo.ArgumentList.Add(mode);
process.StartInfo.ArgumentList.Add(reportPath);
process.Start();
try
{
await process.WaitForExitAsync(TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(90), TestContext.Current.CancellationToken);
using var report = JsonDocument.Parse(File.ReadAllText(reportPath));
Assert.False(report.RootElement.GetProperty("HostHasConsole").GetBoolean());
Assert.False(report.RootElement.GetProperty("HostInputValid").GetBoolean());
Assert.Equal(0, process.ExitCode);
}
finally { if (!process.HasExited) process.Kill(true); }
}
[Fact]
public void UsageProseAndContributingSectionAreSilent()
{
const string text = """
You are currently using your subscription to power your Claude Code usage
Current session: 4% used · resets Oct 14, 11:30pm (Europe/Berlin)
Current week (all models): 67% used · resets Oct 18, 8pm (Europe/Berlin)
Current week (Fable): 0% used · resets Oct 18, 8pm (Europe/Berlin)
What's contributing to your limits usage?
Usage across Claude Code and Claude contributes to your limits.
Sessions and conversations share your subscription allowance.
Learn more about how usage is calculated.
Current example: this prose is not a limit window
""";
var log = new DiagnosticLog();
Assert.Equal(3, ClaudeUsageParser.ParseText(text, new(2026, 10, 14, 18, 0, 0, TimeSpan.Zero), log).Count);
Assert.Empty(log.Recent);
}
[Fact]
public async Task MissingSnapshotAppPathDoesNotDefaultToReadersExecutable()
{
using var directory = new TestDirectory();
directory.Write("snapshot.json", """{"v":1,"madeAt":"2026-10-14T16:00:00Z","refreshInterval":"00:01:00","providers":[]}""");
Assert.Null(SnapshotFile.Read(directory.Path).Snapshot!.AppPath);
await using var engine = new RefreshEngine(directory.Path, claudeDirectory: directory.Path, codexDirectory: directory.Path,
cliDiscovery: (_, _) => new(null, "Fixture CLI missing."));
Assert.Null((await engine.RefreshNowAsync(true, TestContext.Current.CancellationToken)).AppPath);
}
[Fact]
public async Task UnspecifiedHostAppPathPreservesExistingDesktopPath()
{
using var directory = new TestDirectory();
await SnapshotFile.WriteAsync(directory.Path, new Snapshot { AppPath = "desktop.exe", MadeAt = DateTimeOffset.UtcNow,
RefreshInterval = TimeSpan.FromMinutes(1), Providers = [] }, TestContext.Current.CancellationToken);
await using var engine = new RefreshEngine(directory.Path, claudeDirectory: directory.Path, codexDirectory: directory.Path,
cliDiscovery: (_, _) => new(null, "Fixture CLI missing."));
Assert.Equal("desktop.exe", (await engine.RefreshNowAsync(true, TestContext.Current.CancellationToken)).AppPath);
}
[Fact]
public void DaysFollowLocalCalendarInsteadOfUtcMidnight()
{
using var directory = new TestDirectory();
var store = new HistoryStore(directory.Path, new());
var first = new DateTimeOffset(2026, 10, 14, 23, 0, 0, TimeSpan.Zero);
store.Add(new(Provider.Codex, first, "model", "project", new(Total: 10), "one"));
store.Add(new(Provider.Codex, first.AddHours(1), "model", "project", new(Total: 20), "two"));
var zone = TimeZoneInfo.CreateCustomTimeZone("Fixture +02", TimeSpan.FromHours(2), "Fixture", "Fixture");
var day = Assert.Single(store.TokenSeries(Provider.Codex, first, first.AddHours(2), SeriesInterval.Day, zone));
Assert.Equal(30, day.Counts.Total);
Assert.Equal(new DateTimeOffset(2026, 10, 15, 0, 0, 0, TimeSpan.FromHours(2)), day.Time);
}
[Theory]
[InlineData("2026-03-29", 23)]
[InlineData("2026-10-25", 25)]
public void LocalDaySeriesIncludesEveryHourAcrossDst(string localDate, int hours)
{
using var directory = new TestDirectory();
var store = new HistoryStore(directory.Path, new());
var zone = TimeZoneInfo.FindSystemTimeZoneById("Europe/Berlin");
var date = DateTime.ParseExact(localDate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
var start = new DateTimeOffset(date, zone.GetUtcOffset(date));
var end = CalendarDays.NextStart(start, zone);
Assert.Equal(TimeSpan.FromHours(hours), end - start);
for (var i = 0; i < hours; i++)
store.Add(new(Provider.Codex, start.AddHours(i), "model", "project", new(Total: 1), "hour-" + i));
var day = Assert.Single(store.TokenSeries(Provider.Codex, start, end, SeriesInterval.Day, zone));
Assert.Equal(hours, day.Counts.Total);
Assert.Equal(start, day.Time);
Assert.Equal(hours, store.TokenSeries(Provider.Codex, start, end, SeriesInterval.Hour, zone).Count);
}
[Fact]
public async Task ExplicitDesktopPathOverridesPriorSnapshotPath()
{
using var directory = new TestDirectory();
await SnapshotFile.WriteAsync(directory.Path, new Snapshot { AppPath = "old.exe", MadeAt = DateTimeOffset.UtcNow,
RefreshInterval = TimeSpan.FromMinutes(1), Providers = [] }, TestContext.Current.CancellationToken);
await using var engine = new RefreshEngine(directory.Path, claudeDirectory: directory.Path, codexDirectory: directory.Path,
cliDiscovery: (_, _) => new(null, "Fixture CLI missing."), appPath: "desktop.exe");
Assert.Equal("desktop.exe", (await engine.RefreshNowAsync(true, TestContext.Current.CancellationToken)).AppPath);
}
}
+73
View File
@@ -0,0 +1,73 @@
using Xunit;
namespace FinalToken.Core.Tests;
public class PaceTests
{
private static readonly DateTimeOffset Now = new(2026, 10, 14, 16, 0, 0, TimeSpan.Zero);
private static LimitWindow Window(double used, double elapsed = 0.5) => new(Provider.Claude, "session", "Session",
used, Now + TimeSpan.FromHours(5 * (1 - elapsed)), TimeSpan.FromHours(5), Now, "fixture");
[Theory]
[InlineData(0, 0, PaceState.OnTrack)]
[InlineData(0, 0.5, PaceState.Behind)]
[InlineData(60, 0.5, PaceState.Ahead)]
[InlineData(50, 0.5, PaceState.OnTrack)]
[InlineData(10, 0.4, PaceState.OnTrack)]
[InlineData(0, 1.2, PaceState.Behind)]
public void CalculatesStates(double used, double elapsed, PaceState expected) =>
Assert.Equal(expected, Pace.Calculate(Window(used, elapsed), Now).State);
[Fact] public void ClampsElapsedAfterReset() => Assert.Equal(1, Pace.Calculate(Window(50, 2), Now).ElapsedFraction);
[Fact] public void MissingLengthIsUnknown() => Assert.Equal(PaceState.Unknown, Pace.Calculate(Window(40) with { Length = null }, Now).State);
[Fact] public void MissingResetIsUnknown() => Assert.Equal(PaceState.Unknown, Pace.Calculate(Window(40) with { ResetsAt = null }, Now).State);
[Fact] public void AheadProjectionPrecedesReset()
{
var window = Window(80);
Assert.Equal(Now.AddMinutes(37.5), Pace.Calculate(window, Now).Projection);
Assert.True(Pace.Calculate(window, Now).Projection < window.ResetsAt);
}
[Fact] public void ProjectionAfterResetIsHidden() => Assert.Null(Pace.Calculate(Window(10), Now).Projection);
[Fact] public void ZeroElapsedDoesNotProject() => Assert.Null(Pace.Calculate(Window(50, 0), Now).Projection);
[Fact] public void ZeroUsageDoesNotProject() => Assert.Null(Pace.Calculate(Window(0), Now).Projection);
[Fact]
public void PopupHysteresisPreventsFlappingAndRearmsAfterClear()
{
var machine = new PopupDecider();
var settings = new Settings();
Assert.NotNull(machine.Observe(Window(60), Pace.Calculate(Window(60), Now), settings));
Assert.Null(machine.Observe(Window(59), Pace.Calculate(Window(59), Now), settings));
Assert.Null(machine.Observe(Window(60), Pace.Calculate(Window(60), Now), settings));
Assert.Null(machine.Observe(Window(57), Pace.Calculate(Window(57), Now), settings));
Assert.NotNull(machine.Observe(Window(60), Pace.Calculate(Window(60), Now), settings));
}
[Fact]
public void BehindHasHysteresisAndIndependentProviderState()
{
var machine = new PopupDecider();
var settings = new Settings();
Assert.NotNull(machine.Observe(Window(40), Pace.Calculate(Window(40), Now), settings));
Assert.Null(machine.Observe(Window(41), Pace.Calculate(Window(41), Now), settings));
Assert.NotNull(machine.Observe(Window(40) with { Provider = Provider.Codex }, Pace.Calculate(Window(40), Now), settings));
Assert.Null(machine.Observe(Window(43), Pace.Calculate(Window(43), Now), settings));
Assert.NotNull(machine.Observe(Window(40), Pace.Calculate(Window(40), Now), settings));
}
[Fact]
public void PopupHonorsProviderAndStateSettings()
{
var window = Window(60);
Assert.Null(new PopupDecider().Observe(window, Pace.Calculate(window, Now), new Settings { PopupAhead = false }));
Assert.Null(new PopupDecider().Observe(window, Pace.Calculate(window, Now), new Settings { Claude = new() { PopupsEnabled = false } }));
Assert.Null(new PopupDecider().Observe(window, Pace.Calculate(window, Now), new Settings { Claude = new() { Enabled = false } }));
Assert.Null(new PopupDecider().Observe(Window(40), Pace.Calculate(Window(40), Now), new Settings { PopupBehind = false }));
}
[Fact]
public void ProviderStateTogglesDoNotDisableOtherProviders()
{
var settings = new Settings { Claude = new() { PopupAhead = false, PopupBehind = false } };
var machine = new PopupDecider();
Assert.Null(machine.Observe(Window(60), Pace.Calculate(Window(60), Now), settings));
Assert.Null(machine.Observe(Window(40), Pace.Calculate(Window(40), Now), settings));
Assert.NotNull(machine.Observe(Window(60) with { Provider = Provider.Codex }, Pace.Calculate(Window(60), Now), settings));
}
}
+107
View File
@@ -0,0 +1,107 @@
using FinalToken.Core.Collectors;
using Xunit;
namespace FinalToken.Core.Tests;
public class ParserTests
{
private static readonly DateTimeOffset Now = new(2026, 10, 14, 16, 0, 0, TimeSpan.Zero);
[Fact]
public void TranscriptReturnsOnlyMetadataAndCorrectCacheTotal()
{
var usage = TranscriptParser.Parse(Fixtures.Claude(), new());
Assert.NotNull(usage);
Assert.Equal(new TokenCounts(10, 3, 4, 2, 0, 19), usage.Counts);
Assert.Equal("fixture-model", usage.Model);
Assert.Equal("/project", usage.Project);
}
[Theory]
[InlineData("{")]
[InlineData("[]")]
[InlineData("null")]
[InlineData("{\"type\":\"assistant\",\"message\":{\"usage\":{\"input_tokens\":-1}}}")]
public void TranscriptMalformedInputDoesNotThrow(string line) => Assert.Null(TranscriptParser.Parse(line, new()));
[Fact]
public void TranscriptMalformedUsageReportsDiagnostic()
{
var diagnostics = new DiagnosticLog();
Assert.Null(TranscriptParser.Parse(Fixtures.Claude().Replace("\"input_tokens\":10", "\"input_tokens\":-1"), diagnostics));
Assert.Single(diagnostics.Recent);
}
[Theory]
[InlineData("Current session: 28% used · resets Oct 14, 7:30pm (Europe/Berlin)", 5, 17, 30)]
[InlineData("Current week (all models): 66% used · resets Oct 18, 8pm (Europe/Berlin)", 168, 18, 0)]
[InlineData("Current week (Fable): 0% used • resets Oct 18, 8:00pm (Europe/Berlin)", 168, 18, 0)]
public void ClaudeUsageParsesKnownFormatsAndIanaZone(string line, int hours, int resetHour, int resetMinute)
{
var window = Assert.Single(ClaudeUsageParser.ParseText(line, Now, new()));
Assert.Equal(TimeSpan.FromHours(hours), window.Length);
Assert.Equal(resetHour, window.ResetsAt!.Value.Hour);
Assert.Equal(resetMinute, window.ResetsAt.Value.Minute);
}
[Fact]
public void ClaudeInfersNewYearWithinWindow()
{
var windows = ClaudeUsageParser.ParseText("Current week (all models): 10% used · resets Jan 2, 8pm (Europe/Berlin)",
new(2026, 12, 31, 16, 0, 0, TimeSpan.Zero), new());
Assert.Equal(2027, Assert.Single(windows).ResetsAt!.Value.Year);
}
[Theory]
[InlineData("Current session: 101% used · resets Oct 14, 7:30pm (Europe/Berlin)")]
[InlineData("Current session: 10% used · resets Oct 14, 7:30pm (Unknown/Zone)")]
[InlineData("Current session: 10% used · resets Oct 18, 8pm (Europe/Berlin)")]
[InlineData("Current session: 10% used · resets Oct 14, 3pm (Europe/Berlin)")]
[InlineData("Current session: unknown format")]
public void ClaudeUnknownFormatsBecomeDiagnostics(string line)
{
var diagnostics = new DiagnosticLog();
Assert.Empty(ClaudeUsageParser.ParseText(line, Now, diagnostics));
Assert.Single(diagnostics.Recent);
}
[Fact] public void ClaudeEnvelopeIsLocalAndZeroTurns() => Assert.Equal(2, ClaudeUsageParser.ParseEnvelope(Fixtures.ClaudeEnvelope, Now, new()).Count);
[Theory]
[InlineData("{")]
[InlineData("{\"is_error\":true}")]
[InlineData("{\"local_command\":\"usage\",\"num_turns\":1,\"is_error\":false,\"result\":\"x\"}")]
public void ClaudeRejectsInvalidEnvelope(string json) => Assert.Empty(ClaudeUsageParser.ParseEnvelope(json, Now, new()));
[Fact]
public void RolloutTracksModelAndProjectAndCumulativeCounts()
{
var cursor = new ScanCursor();
foreach (var line in Fixtures.Meta.Split('\n', StringSplitOptions.RemoveEmptyEntries)) RolloutParser.Parse(line, cursor, Now, new());
var entry = RolloutParser.Parse(Fixtures.Codex(10), cursor, Now, new());
Assert.Equal("session-1", cursor.SessionId);
Assert.Equal("fixture-model", entry.CumulativeUsage!.Model);
Assert.Equal(12, entry.CumulativeUsage.Counts.Total);
Assert.Equal("codex:primary", Assert.Single(entry.Limits).Id);
}
[Theory]
[InlineData("{")]
[InlineData("null")]
[InlineData("[]")]
[InlineData("{\"type\":\"event_msg\",\"payload\":{\"type\":\"token_count\"}}")]
public void RolloutMalformedInputIsTotal(string line) => Assert.Null(RolloutParser.Parse(line, new(), Now, new()).CumulativeUsage);
[Fact]
public void CodexReadsSchemaCamelCaseResponse()
{
var window = Assert.Single(CodexLimitsParser.ParseResponse(Fixtures.CodexResponse, Now, new()));
Assert.Equal(24, window.UsedPercent);
Assert.Equal(TimeSpan.FromDays(7), window.Length);
}
[Fact]
public void CodexReadsMultipleBuckets()
{
var json = "{\"result\":{\"rateLimitsByLimitId\":{\"a\":{\"limitId\":\"a\",\"primary\":{\"usedPercent\":1}},\"b\":{\"limitId\":\"b\",\"secondary\":{\"usedPercent\":2}}}}}";
var windows = CodexLimitsParser.ParseResponse(json, Now, new());
Assert.Equal(2, windows.Count);
Assert.All(windows, w => Assert.Null(w.Length));
}
[Fact] public void CodexRejectsInvalidWindow() => Assert.Empty(CodexLimitsParser.ParseResponse(Fixtures.CodexResponse.Replace("\"usedPercent\":24", "\"usedPercent\":-1"), Now, new()));
[Fact] public void DiagnosticsAreBoundedAndExcludeInput()
{
var diagnostics = new DiagnosticLog(capacity: 2);
for (var i = 0; i < 4; i++) TranscriptParser.Parse("private fixture text", diagnostics);
Assert.Equal(4, Assert.Single(diagnostics.Recent).Count);
Assert.All(diagnostics.Recent, d => Assert.DoesNotContain("private fixture", d.Summary));
}
}
@@ -0,0 +1,95 @@
using System.Text.Json;
using Xunit;
namespace FinalToken.Core.Tests;
public sealed class PartialSettingsTests
{
[Theory]
[InlineData("{}")]
[InlineData("{\"refreshInterval\":\"00:00:30\"}")]
[InlineData("{\"claude\":{\"enabled\":false},\"codex\":{\"cliPath\":\"fixture\"}}")]
[InlineData("{\"claude\":{},\"codex\":{\"popupBehind\":false}}")]
[InlineData("{\"refreshInterval\":\"00:00:30\",\"future\":123,\"claude\":{\"popupAhead\":false,\"future\":{}}}")]
public void PartialFilesKeepValuesAndDefaultAbsentProperties(string json)
{
using var directory = new TestDirectory();
directory.Write("settings.json", json);
var diagnostics = new DiagnosticLog();
var settings = SettingsFile.Load(directory.Path, diagnostics);
var expected = new Settings();
using var doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("refreshInterval", out _)) expected = expected with { RefreshInterval = TimeSpan.FromSeconds(30) };
if (json.Contains("\"enabled\":false")) expected = expected with { Claude = expected.Claude with { Enabled = false } };
if (json.Contains("\"cliPath\"")) expected = expected with { Codex = expected.Codex with { CliPath = "fixture" } };
if (json.Contains("\"popupAhead\":false")) expected = expected with { Claude = expected.Claude with { PopupAhead = false } };
if (json.Contains("\"popupBehind\":false")) expected = expected with { Codex = expected.Codex with { PopupBehind = false } };
Assert.Equal(expected, settings);
Assert.Empty(diagnostics.Recent);
}
[Theory]
[InlineData("\"Automatic\"", InstallMode.Automatic)]
[InlineData("\"Ask\"", InstallMode.Ask)]
[InlineData("\"Off\"", InstallMode.Off)]
[InlineData("2", InstallMode.Automatic)]
public void InstallModeAcceptsNamesAndExistingNumericFiles(string value, InstallMode expected)
{
using var directory = new TestDirectory();
directory.Write("settings.json", "{\"streamDeckInstallMode\":" + value + "}");
var diagnostics = new DiagnosticLog();
Assert.Equal(new Settings { StreamDeckInstallMode = expected }, SettingsFile.Load(directory.Path, diagnostics));
Assert.Empty(diagnostics.Recent);
}
[Theory]
[InlineData("\"probeInterval\":\"00:00:10\"")]
[InlineData("\"paceThreshold\":0")]
[InlineData("\"probeInterval\":\"invalid\"")]
[InlineData("\"streamDeckInstallMode\":99")]
[InlineData("\"streamDeckInstallMode\":\"Unknown\"")]
[InlineData("\"claude\":null")]
[InlineData("\"codex\":{\"enabled\":\"invalid\"}")]
public void OneInvalidPropertyStillFallsBackForWholeFile(string invalid)
{
using var directory = new TestDirectory();
directory.Write("settings.json", "{\"refreshInterval\":\"00:00:30\"," + invalid + "}");
var diagnostics = new DiagnosticLog();
Assert.Equal(new Settings(), SettingsFile.Load(directory.Path, diagnostics));
Assert.Equal("settings-defaults", Assert.Single(diagnostics.Recent).Code);
}
[Fact]
public void SnapshotKeepsOptionalVersionInitializer()
{
using var directory = new TestDirectory();
directory.Write("snapshot.json", """{"madeAt":"2026-10-14T16:00:00Z","refreshInterval":"00:01:00","providers":[]}""");
var snapshot = SnapshotFile.Read(directory.Path).Snapshot;
Assert.NotNull(snapshot); Assert.Equal(1, snapshot.V); Assert.Null(snapshot.AppPath);
}
[Theory]
[InlineData("{\"v\":1,\"refreshInterval\":\"00:01:00\",\"providers\":[]}")]
[InlineData("{\"v\":1,\"madeAt\":\"2026-10-14T16:00:00Z\",\"providers\":[]}")]
[InlineData("{\"v\":1,\"madeAt\":\"2026-10-14T16:00:00Z\",\"refreshInterval\":\"00:01:00\"}")]
public void SnapshotStillRejectsMissingRequiredFields(string json)
{
using var directory = new TestDirectory();
directory.Write("snapshot.json", json);
Assert.Null(SnapshotFile.Read(directory.Path).Snapshot);
}
[Fact]
public void HistoryTypesKeepDefaultsForAbsentProperties()
{
var state = JsonSerializer.Deserialize("{\"sequence\":2}", CoreJsonContext.Default.HistoryState)!;
Assert.Equal(1, state.V); Assert.Equal(2, state.Sequence);
Assert.Empty(state.ClaudeKeys); Assert.Empty(state.CodexTotals); Assert.Empty(state.CodexTimes);
Assert.Empty(state.Cursors); Assert.Empty(state.LatestWindows); Assert.Empty(state.LastSamples);
var partition = JsonSerializer.Deserialize("{}", CoreJsonContext.Default.HistoryPartition)!;
Assert.Equal(1, partition.V); Assert.Empty(partition.Buckets); Assert.Empty(partition.Limits);
var transaction = JsonSerializer.Deserialize("{\"sequence\":3}", CoreJsonContext.Default.HistoryTransaction)!;
Assert.Equal(1, transaction.V); Assert.Equal(3, transaction.Sequence);
Assert.Empty(transaction.Buckets); Assert.Empty(transaction.Limits); Assert.Empty(transaction.ClaudeKeys);
Assert.Empty(transaction.ExpiredClaudeKeys); Assert.Empty(transaction.CodexTotals); Assert.Empty(transaction.CodexTimes);
Assert.Empty(transaction.Cursors); Assert.Empty(transaction.LatestWindows); Assert.Empty(transaction.LastSamples);
state = JsonSerializer.Deserialize("{\"cursors\":{\"fixture\":{\"model\":\"fixture\"}}}", CoreJsonContext.Default.HistoryState)!;
Assert.Equal(-1, state.Cursors["fixture"].ObservedLength); Assert.Equal("", state.Cursors["fixture"].PrefixHash);
Assert.Empty(state.Cursors["fixture"].LatestLimits);
}
}
@@ -0,0 +1,39 @@
using FinalToken.Core.Processes;
using Xunit;
namespace FinalToken.Core.Tests;
public class ProcessTests
{
private static ProcessRequest LongProcess(string directory) => OperatingSystem.IsWindows()
? new(new(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "ping.exe"), []), ["-n", "30", "127.0.0.1"], directory, TimeSpan.FromSeconds(60))
: new(new("sleep", []), ["30"], directory, TimeSpan.FromSeconds(60));
[Fact]
public async Task FakeClockTimeoutTerminatesChild()
{
using var directory = new TestDirectory();
var clock = new TestClock();
var task = new ProcessRunner(clock).RunAsync(LongProcess(directory.Path), TestContext.Current.CancellationToken);
clock.Advance(TimeSpan.FromSeconds(61));
Assert.True((await task).TimedOut);
}
[Fact]
public async Task CancellationTerminatesAndWaitsForChild()
{
using var directory = new TestDirectory();
using var cancelled = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
var task = new ProcessRunner().RunAsync(LongProcess(directory.Path), cancelled.Token);
await cancelled.CancelAsync();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => task);
}
[Fact]
public async Task CaptureIsBoundedWithoutBlockingTheChild()
{
using var directory = new TestDirectory();
var result = await new ProcessRunner().RunAsync(new(new("dotnet", []), ["--info"], directory.Path,
TimeSpan.FromSeconds(60), OutputLimit: 50), TestContext.Current.CancellationToken);
Assert.Equal(0, result.ExitCode);
Assert.Equal(50, result.Output.Length);
Assert.True(result.OutputTruncated);
}
}
@@ -0,0 +1,141 @@
using System.Text.Json;
using System.Threading.Channels;
using FinalToken.Core.Collectors;
using FinalToken.Core.Processes;
using Xunit;
namespace FinalToken.Core.Tests;
public sealed class ReviewRegressionTests
{
private static CliCommand Child(string mode) => new(Path.Combine(AppContext.BaseDirectory, "ProcessHost",
OperatingSystem.IsWindows() ? "FinalToken.ProcessHost.exe" : "FinalToken.ProcessHost"), [mode]);
[Theory]
[InlineData("--rpc-success", true)]
[InlineData("--rpc-error", false)]
[InlineData("--rpc-init-error", false)]
[InlineData("--rpc-eof", false)]
[InlineData("--rpc-garbage", false)]
[InlineData("--rpc-shape", false)]
[InlineData("--rpc-bound", false)]
public async Task RpcChildFailuresBecomeFailedProbes(string mode, bool success)
{
using var directory = new TestDirectory();
var log = new DiagnosticLog();
var probe = new LimitProbe(new ProcessRunner(), log, directory.Path);
var result = await probe.RunAsync(Provider.Codex, Child(mode), new TestClock().GetUtcNow(), TestContext.Current.CancellationToken);
Assert.Equal(success, result.Success);
if (!success) { Assert.Empty(result.Windows); Assert.NotNull(result.Reason); Assert.NotEmpty(log.Recent); }
else Assert.Single(result.Windows);
}
[Theory]
[InlineData("--rpc-error", false)]
[InlineData("--rpc-eof", false)]
[InlineData("--rpc-garbage", false)]
[InlineData("--rpc-error", true)]
public async Task EngineKeepsUpdatingClaudeWhenCodexFails(string mode, bool fallback)
{
using var directory = new TestDirectory();
var clock = new TestClock();
var runner = new FakeRunner { Handler = (request, token) => request.CodexRpc
? new ProcessRunner().RunAsync(request, token) : Task.FromResult(new ProcessResult(0, Fixtures.ClaudeEnvelope)) };
if (fallback) directory.Write("codex/sessions/rollout-fixture.jsonl", Fixtures.Meta + Fixtures.Codex(10));
await using var engine = new RefreshEngine(directory.Path, clock, runner, Path.Combine(directory.Path, "claude"),
Path.Combine(directory.Path, "codex"), (provider, _) => new(provider == Provider.Codex ? Child(mode) : new("fixture", []), null));
var snapshots = Channel.CreateUnbounded<Snapshot>(); engine.SnapshotChanged += value => snapshots.Writer.TryWrite(value);
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
deadline.CancelAfter(TimeSpan.FromSeconds(15));
await engine.StartAsync(deadline.Token);
var initial = await snapshots.Reader.ReadAsync(deadline.Token);
var first = initial.Providers.Single(p => p.Provider == Provider.Claude).Windows[0].Window.SampleTime;
clock.Advance(TimeSpan.FromMinutes(5));
var snapshot = await snapshots.Reader.ReadAsync(deadline.Token);
var claude = snapshot.Providers.Single(p => p.Provider == Provider.Claude);
Assert.Equal(ProviderStatus.Available, claude.Status); Assert.True(claude.Windows[0].Window.SampleTime > first);
var codex = snapshot.Providers.Single(p => p.Provider == Provider.Codex);
Assert.Equal(fallback ? ProviderStatus.Available : ProviderStatus.Unavailable, codex.Status);
if (fallback) Assert.Contains("rollout", codex.Reason); else Assert.Empty(codex.Windows);
await engine.StopAsync();
}
[Fact]
public async Task BackgroundLoopRecoversAfterCorruptMonthAndStopsCleanly()
{
using var directory = new TestDirectory();
var bad = directory.Write("history/2026-10.json", "{");
var clock = new TestClock();
await using var engine = new RefreshEngine(directory.Path, clock, new FakeRunner(), directory.Path, directory.Path, (_, _) => new(new("fixture", []), null));
var snapshots = Channel.CreateUnbounded<Snapshot>();
engine.SnapshotChanged += value => snapshots.Writer.TryWrite(value);
await engine.StartAsync(TestContext.Current.CancellationToken);
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
deadline.CancelAfter(TimeSpan.FromSeconds(15));
while (!engine.RecentDiagnostics.Any(d => d.Code == "refresh-failed")) await Task.Delay(10, deadline.Token);
await File.WriteAllTextAsync(bad, "{\"v\":1,\"buckets\":[],\"limits\":[]}", deadline.Token);
clock.Advance(TimeSpan.FromSeconds(1));
var first = await snapshots.Reader.ReadAsync(deadline.Token);
clock.Advance(TimeSpan.FromMinutes(5));
var second = await snapshots.Reader.ReadAsync(deadline.Token);
Assert.True(second.MadeAt > first.MadeAt);
await engine.StopAsync();
}
[Fact]
public async Task ProbeDoesNotSwallowShutdownCancellation()
{
using var directory = new TestDirectory();
using var stop = new CancellationTokenSource(); stop.Cancel();
var runner = new FakeRunner { Handler = (_, token) => Task.FromCanceled<ProcessResult>(token) };
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => new LimitProbe(runner, new(), directory.Path)
.RunAsync(Provider.Codex, Child("--rpc-error"), DateTimeOffset.UtcNow, stop.Token));
}
[Fact]
public async Task ShutdownWinsWhenAProcessFailureRacesCancellation()
{
using var directory = new TestDirectory();
using var stop = new CancellationTokenSource();
var runner = new FakeRunner { Handler = (_, _) => { stop.Cancel(); throw new InvalidDataException("synthetic failure during shutdown"); } };
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => new LimitProbe(runner, new(), directory.Path)
.RunAsync(Provider.Codex, Child("--rpc-error"), DateTimeOffset.UtcNow, stop.Token));
}
[Theory]
[InlineData("Africa/Cairo", "2026-04-24")]
[InlineData("America/Santiago", "2026-09-06")]
[InlineData("Asia/Beirut", "2026-03-29")]
public void TotalsSurviveMissingLocalMidnight(string zoneId, string dateText)
{
var zone = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
var date = DateTime.ParseExact(dateText, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
Assert.True(zone.IsInvalidTime(date));
VerifyTotals(zone, date);
}
[Fact]
public void WeekCanStartOnAMondayWithNoMidnight()
{
var rule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new(2026, 1, 1), new(2026, 12, 31), TimeSpan.FromHours(1),
TimeZoneInfo.TransitionTime.CreateFixedDateRule(new(1, 1, 1), 3, 30),
TimeZoneInfo.TransitionTime.CreateFixedDateRule(new(1, 1, 1), 10, 1));
var zone = TimeZoneInfo.CreateCustomTimeZone("Monday gap", TimeSpan.Zero, "Monday gap", "standard", "summer", [rule]);
VerifyTotals(zone, new(2026, 3, 30));
using var directory = new TestDirectory();
var store = new HistoryStore(directory.Path, new());
var monday = new DateTimeOffset(2026, 3, 30, 1, 0, 0, TimeSpan.FromHours(1));
store.Add(new(Provider.Codex, monday.AddHours(-1), null, null, new(Total: 7), "before-week"));
store.Add(new(Provider.Codex, monday, null, null, new(Total: 11), "in-week"));
var wednesday = new DateTimeOffset(2026, 4, 1, 12, 0, 0, TimeSpan.FromHours(1));
store.Add(new(Provider.Codex, wednesday.AddHours(-1), null, null, new(Total: 13), "today"));
var totals = store.Totals(Provider.Codex, wednesday, null, zone);
Assert.Equal(13, totals.Today.Total); Assert.Equal(24, totals.Week.Total);
}
private static void VerifyTotals(TimeZoneInfo zone, DateTime date)
{
using var directory = new TestDirectory();
var store = new HistoryStore(directory.Path, new());
var first = new DateTimeOffset(date.AddHours(1), zone.GetUtcOffset(date.AddHours(1)));
var now = first.AddHours(10);
store.Add(new(Provider.Codex, first.AddHours(-1), null, null, new(Total: 7), "before"));
store.Add(new(Provider.Codex, first, null, null, new(Total: 11), "inside"));
var totals = store.Totals(Provider.Codex, now, null, zone);
Assert.Equal(11, totals.Today.Total);
Assert.Equal(date.DayOfWeek == DayOfWeek.Monday ? 11 : 18, totals.Week.Total);
}
}
+265
View File
@@ -0,0 +1,265 @@
using FinalToken.Core.Collectors;
using Xunit;
namespace FinalToken.Core.Tests;
public class ReworkTests
{
[Theory]
[InlineData("<synthetic>", 10)]
[InlineData("fixture-model", 0)]
public void SyntheticAndUnrequestedZeroUsageAreSilent(string model, int input)
{
var line = """{"type":"assistant","message":{"model":"@model","usage":{"input_tokens":@input,"output_tokens":0}}}"""
.Replace("@model", model).Replace("@input", input.ToString(System.Globalization.CultureInfo.InvariantCulture));
var log = new DiagnosticLog();
Assert.Null(TranscriptParser.Parse(line, log));
Assert.Empty(log.Recent);
}
[Fact]
public async Task IdleSaveDoesNotRewriteAnyHistoryFile()
{
using var directory = new TestDirectory();
var store = new HistoryStore(directory.Path, new());
store.Add(new(Provider.Claude, DateTimeOffset.UtcNow, "model", "project", new(Total: 10), "key"));
await store.SaveAsync(TestContext.Current.CancellationToken);
var before = Directory.GetFiles(directory.Path, "*", SearchOption.AllDirectories)
.ToDictionary(p => p, p => (File.GetLastWriteTimeUtc(p), new FileInfo(p).Length));
await store.SaveAsync(TestContext.Current.CancellationToken);
Assert.All(before, p => Assert.Equal(p.Value, (File.GetLastWriteTimeUtc(p.Key), new FileInfo(p.Key).Length)));
}
[Fact]
public void UnchangedLimitsAreSampledAtMostHourly()
{
using var directory = new TestDirectory();
var store = new HistoryStore(directory.Path, new());
var now = DateTimeOffset.UtcNow;
var window = new LimitWindow(Provider.Claude, "session", "Session", 10, now.AddHours(3), TimeSpan.FromHours(5), now, "fixture");
store.AddLimits([window]);
store.AddLimits([window with { SampleTime = now.AddMinutes(5) }]);
store.AddLimits([window with { SampleTime = now.AddHours(1) }]);
Assert.Equal(2, store.LimitSamples(Provider.Claude, "session", now.AddSeconds(-1), now.AddHours(2)).Count);
store.AddLimits([window with { UsedPercent = 11, SampleTime = now.AddHours(1).AddMinutes(1) }]);
Assert.Equal(3, store.LimitSamples(Provider.Claude, "session", now.AddSeconds(-1), now.AddHours(2)).Count);
}
[Fact]
public async Task AtomicReplaceSucceedsWhileDeleteSharingReaderRemainsOpen()
{
using var directory = new TestDirectory();
var path = directory.Write("shared.json", "old");
using var reader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
await AtomicFile.WriteAsync(path, "new", TestContext.Current.CancellationToken);
Assert.Equal("new", File.ReadAllText(path));
}
[Fact]
public async Task SharingViolationRetriesAndFailsWithinBound()
{
if (!OperatingSystem.IsWindows()) return;
using var directory = new TestDirectory();
var path = directory.Write("blocked.json", "old");
using var reader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var clock = new TestClock();
var write = AtomicFile.WriteAsync(path, "new", TestContext.Current.CancellationToken, clock);
for (var attempt = 0; attempt < 10; attempt++)
{
Assert.Equal(TimeSpan.FromMilliseconds(50), await clock.NextTimerAsync(TestContext.Current.CancellationToken));
Assert.False(write.IsCompleted);
clock.Advance(TimeSpan.FromMilliseconds(50));
}
await Assert.ThrowsAsync<IOException>(() => write);
Assert.Equal("old", File.ReadAllText(path));
Assert.Empty(Directory.GetFiles(directory.Path, "*.tmp"));
}
[Fact]
public void FoldedDiagnosticPreservesOtherProblemsAndTracksLastOccurrence()
{
var clock = new TestClock();
var log = new DiagnosticLog(clock, 2);
log.Add(Provider.Claude, "parse", "Malformed usage.");
log.Add(Provider.Codex, "timeout", "Probe timed out.");
clock.Advance(TimeSpan.FromMinutes(1));
for (var i = 0; i < 20; i++) log.Add(Provider.Claude, "parse", "Malformed usage.");
Assert.Equal(2, log.Recent.Count);
var folded = Assert.Single(log.Recent, d => d.Provider == Provider.Claude);
Assert.Equal(21, folded.Count);
Assert.Equal(clock.GetUtcNow(), folded.Time);
}
[Fact]
public async Task UnchangedSourceIsNotOpenedEvenAfterRestart()
{
using var directory = new TestDirectory();
var source = directory.Write("claude/projects/p/a.jsonl", Fixtures.Claude());
var log = new DiagnosticLog();
var store = new HistoryStore(directory.Path, log);
var scanner = new IncrementalScanner(store, log, Path.Combine(directory.Path, "claude"), directory.Path);
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
await store.SaveAsync(TestContext.Current.CancellationToken);
store = new(directory.Path, log);
scanner = new(store, log, Path.Combine(directory.Path, "claude"), directory.Path);
using var exclusive = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.None);
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
Assert.Empty(log.Recent);
}
[Fact]
public async Task TornJournalTailIsIgnoredAndRepairedBeforeNextAppend()
{
using var directory = new TestDirectory();
var now = DateTimeOffset.UtcNow;
var store = new HistoryStore(directory.Path, new());
store.Add(new(Provider.Claude, now, "m", "p", new(Total: 10), "one"));
await store.SaveAsync(TestContext.Current.CancellationToken);
var path = Path.Combine(directory.Path, "history.journal.jsonl");
await File.AppendAllTextAsync(path, "{\"v\":1,\"sequence\":2", TestContext.Current.CancellationToken);
store = new(directory.Path, new());
Assert.Equal(10, store.Total(Provider.Claude, now.AddHours(-1), now.AddHours(1)).Total);
store.Add(new(Provider.Claude, now, "m", "p", new(Total: 7), "two"));
await store.SaveAsync(TestContext.Current.CancellationToken);
store = new(directory.Path, new());
Assert.Equal(17, store.Total(Provider.Claude, now.AddHours(-1), now.AddHours(1)).Total);
}
[Fact]
public async Task CompactionAndReplayPreserveBucketsKeysAndLimitSets()
{
using var directory = new TestDirectory();
var now = DateTimeOffset.UtcNow;
var store = new HistoryStore(directory.Path, new());
var usage = new UsageEvent(Provider.Claude, now, "m", "p", new(Total: 10), "one");
store.Add(usage);
store.AddLimits([new(Provider.Claude, "session", "Session", 10, now.AddHours(1), TimeSpan.FromHours(5), now, "fixture")]);
await store.SaveAsync(TestContext.Current.CancellationToken);
var committed = File.ReadAllText(Path.Combine(directory.Path, "history.journal.jsonl"));
await store.CompactAsync(TestContext.Current.CancellationToken);
// Simulate interruption after checkpoint replacement but before journal reset.
directory.Write("history.journal.jsonl", committed);
store = new(directory.Path, new());
Assert.False(store.Add(usage));
Assert.Equal(10, store.Total(Provider.Claude, now.AddHours(-1), now.AddHours(1)).Total);
Assert.Single(store.LimitSamples(Provider.Claude, "session", now.AddHours(-1), now.AddHours(1)));
store.Add(usage with { DedupeKey = "two", Counts = new(Total: 7) });
await store.SaveAsync(TestContext.Current.CancellationToken);
store = new(directory.Path, new());
Assert.Equal(17, store.Total(Provider.Claude, now.AddHours(-1), now.AddHours(1)).Total);
}
[Fact]
public async Task ExpiredClaudeKeysCannotRecountOldResumedEntries()
{
using var directory = new TestDirectory();
var clock = new TestClock();
var now = clock.GetUtcNow();
var store = new HistoryStore(directory.Path, new(), clock);
var usage = new UsageEvent(Provider.Claude, now, "m", "p", new(Total: 10), "key");
Assert.True(store.Add(usage));
await store.SaveAsync(TestContext.Current.CancellationToken);
clock.Advance(TimeSpan.FromDays(61));
store = new(directory.Path, new(), clock);
Assert.False(store.Add(usage));
await store.SaveAsync(TestContext.Current.CancellationToken);
await store.CompactAsync(TestContext.Current.CancellationToken);
var stateJson = File.ReadAllText(Path.Combine(directory.Path, "history.state.json"));
Assert.Contains("\"claudeKeys\":{}", stateJson);
Assert.Equal(10, store.Total(Provider.Claude, now.AddHours(-1), now.AddHours(1)).Total);
}
[Fact]
public async Task SmallUpdateAppendsOnlyItsChanges()
{
using var directory = new TestDirectory();
var now = DateTimeOffset.UtcNow;
var store = new HistoryStore(directory.Path, new());
for (var i = 0; i < 1000; i++) store.Add(new(Provider.Claude, now, "m", "p", new(Total: 1), "key-" + i));
await store.SaveAsync(TestContext.Current.CancellationToken);
var path = Path.Combine(directory.Path, "history.journal.jsonl");
var before = new FileInfo(path).Length;
store.Add(new(Provider.Claude, now, "m", "p", new(Total: 1), "new-key"));
await store.SaveAsync(TestContext.Current.CancellationToken);
var increase = new FileInfo(path).Length - before;
Assert.InRange(increase, 1, 2048);
Assert.True(increase < before / 10);
}
[Fact]
public async Task UnchangedProbeRefreshesSnapshotAgeWithoutWritingHistoryBeforeHourlySample()
{
using var directory = new TestDirectory();
var now = DateTimeOffset.UtcNow;
var store = new HistoryStore(directory.Path, new());
var window = new LimitWindow(Provider.Claude, "session", "Session", 10, now.AddHours(3), TimeSpan.FromHours(5), now, "usage");
store.AddLimits([window]);
await store.SaveAsync(TestContext.Current.CancellationToken);
var journal = new FileInfo(Path.Combine(directory.Path, "history.journal.jsonl"));
var length = journal.Length;
var time = journal.LastWriteTimeUtc;
store.AddLimits([window with { SampleTime = now.AddMinutes(5) }]);
await store.SaveAsync(TestContext.Current.CancellationToken);
journal.Refresh();
Assert.Equal(length, journal.Length);
Assert.Equal(time, journal.LastWriteTimeUtc);
Assert.Equal(now.AddMinutes(5), Assert.Single(store.LatestLimits(Provider.Claude)).SampleTime);
}
[Fact]
public async Task SharingViolationRetriesUntilReaderReleasesItsHandle()
{
if (!OperatingSystem.IsWindows()) return;
using var directory = new TestDirectory();
var path = directory.Write("briefly-blocked.json", "old");
using var reader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var clock = new TestClock();
var write = AtomicFile.WriteAsync(path, "new", TestContext.Current.CancellationToken, clock);
Assert.Equal(TimeSpan.FromMilliseconds(50), await clock.NextTimerAsync(TestContext.Current.CancellationToken));
Assert.False(write.IsCompleted);
reader.Dispose();
clock.Advance(TimeSpan.FromMilliseconds(50));
await write;
Assert.Equal("new", File.ReadAllText(path));
}
[Fact]
public async Task PartiallyWrittenCompactionReplaysAbsoluteBucketUpserts()
{
using var directory = new TestDirectory();
var now = DateTimeOffset.UtcNow;
var hour = new DateTimeOffset(now.UtcTicks - now.UtcTicks % TimeSpan.TicksPerHour, TimeSpan.Zero);
var store = new HistoryStore(directory.Path, new());
var usage = new UsageEvent(Provider.Claude, now, "m", "p", new(Total: 10), "one");
store.Add(usage);
await store.CompactAsync(TestContext.Current.CancellationToken);
store.Add(usage with { DedupeKey = "two", Counts = new(Total: 7) });
await store.SaveAsync(TestContext.Current.CancellationToken);
var month = now.UtcDateTime.ToString("yyyy-MM", System.Globalization.CultureInfo.InvariantCulture);
var partition = new HistoryPartition { Buckets = [new(Provider.Claude, hour, "m", "p", new(Total: 17))] };
directory.Write("history/" + month + ".json", System.Text.Json.JsonSerializer.Serialize(partition, CoreJsonContext.Default.HistoryPartition));
store = new(directory.Path, new());
Assert.Equal(17, store.Total(Provider.Claude, now.AddHours(-1), now.AddHours(1)).Total);
Assert.False(store.Add(usage with { DedupeKey = "two" }));
}
[Fact]
public void CompletedCorruptJournalRecordIsRejected()
{
using var directory = new TestDirectory();
directory.Write("history.journal.jsonl", "{\n");
Assert.Throws<InvalidDataException>(() => new HistoryStore(directory.Path, new()));
Assert.Equal("{\n", File.ReadAllText(Path.Combine(directory.Path, "history.journal.jsonl")));
}
[Fact]
public void LateHistoricalLimitSamplesAreNotLostBehindNewerWindows()
{
using var directory = new TestDirectory();
var store = new HistoryStore(directory.Path, new());
var now = DateTimeOffset.UtcNow;
var window = new LimitWindow(Provider.Codex, "primary", "Session", 10, now.AddHours(5), TimeSpan.FromHours(5), now, "rollout");
store.AddLimits([window with { UsedPercent = 30, SampleTime = now.AddHours(3) }]);
store.AddLimits([window]);
store.AddLimits([window with { SampleTime = now.AddMinutes(5) }]);
store.AddLimits([window with { SampleTime = now.AddHours(1) }]);
Assert.Equal(3, store.LimitSamples(Provider.Codex, "primary", now.AddSeconds(-1), now.AddHours(4)).Count);
Assert.Equal(30, Assert.Single(store.LatestLimits(Provider.Codex)).UsedPercent);
}
[Fact]
public void LateUnchangedSampleCannotDuplicateHourlyPointAcrossMonthBoundary()
{
using var directory = new TestDirectory();
var store = new HistoryStore(directory.Path, new());
var now = new DateTimeOffset(2026, 10, 1, 0, 10, 0, TimeSpan.Zero);
var window = new LimitWindow(Provider.Codex, "primary", "Week", 10, now.AddDays(5), TimeSpan.FromDays(7), now, "rollout");
store.AddLimits([window]);
store.AddLimits([window with { SampleTime = now.AddMinutes(-30) }]);
Assert.Single(store.LimitSamples(Provider.Codex, "primary", now.AddHours(-1), now.AddHours(1)));
}
}
+192
View File
@@ -0,0 +1,192 @@
using FinalToken.Core.Collectors;
using Xunit;
namespace FinalToken.Core.Tests;
public class StorageTests
{
[Fact]
public async Task TranscriptAppendShrinkReplaceAndRestartDoNotDoubleCount()
{
using var directory = new TestDirectory();
var source = directory.Write("claude/projects/p/session.jsonl", Fixtures.Claude());
var history = new HistoryStore(directory.Path, new());
var scanner = new IncrementalScanner(history, new(), Path.Combine(directory.Path, "claude"), Path.Combine(directory.Path, "codex"));
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
await File.AppendAllTextAsync(source, Fixtures.Claude("b"), cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
await history.SaveAsync(TestContext.Current.CancellationToken);
history = new(directory.Path, new());
scanner = new(history, new(), Path.Combine(directory.Path, "claude"), Path.Combine(directory.Path, "codex"));
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
await File.WriteAllTextAsync(source, Fixtures.Claude(), cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
var previousWrite = File.GetLastWriteTimeUtc(source);
await File.WriteAllTextAsync(source, Fixtures.Claude("c"), cancellationToken: TestContext.Current.CancellationToken);
File.SetLastWriteTimeUtc(source, previousWrite.AddSeconds(1));
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
directory.Write("claude/projects/other/copied.jsonl", Fixtures.Claude("b"));
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
Assert.Equal(57, history.Total(Provider.Claude, DateTimeOffset.MinValue, DateTimeOffset.MaxValue).Total);
}
[Fact]
public async Task IncompleteLineIsReadOnlyWhenCompleted()
{
using var directory = new TestDirectory();
var fixture = Fixtures.Claude();
var source = directory.Write("claude/projects/p/session.jsonl", fixture[..30]);
var history = new HistoryStore(directory.Path, new());
var scanner = new IncrementalScanner(history, new(), Path.Combine(directory.Path, "claude"), directory.Path);
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
await File.AppendAllTextAsync(source, fixture[30..], cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
}
[Fact]
public async Task CodexCountsIncreasesAndDeduplicatesArchivedCopyAcrossRestart()
{
using var directory = new TestDirectory();
var first = Fixtures.Meta + Fixtures.Codex(10);
var source = directory.Write("codex/sessions/rollout-a.jsonl", first);
var history = new HistoryStore(directory.Path, new());
var scanner = new IncrementalScanner(history, new(), directory.Path, Path.Combine(directory.Path, "codex"));
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
await File.AppendAllTextAsync(source, Fixtures.Codex(10, "2026-10-14T16:01:00Z") + Fixtures.Codex(20, "2026-10-14T16:02:00Z"), cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
Assert.Equal(22, history.Total(Provider.Codex, DateTimeOffset.MinValue, DateTimeOffset.MaxValue).Total);
await history.SaveAsync(TestContext.Current.CancellationToken);
history = new(directory.Path, new());
scanner = new(history, new(), directory.Path, Path.Combine(directory.Path, "codex"));
directory.Write("codex/archived_sessions/rollout-a.jsonl", await File.ReadAllTextAsync(source, cancellationToken: TestContext.Current.CancellationToken));
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
Assert.Single((await scanner.ScanAsync(TestContext.Current.CancellationToken)).CodexFallback);
Assert.Equal(22, history.Total(Provider.Codex, DateTimeOffset.MinValue, DateTimeOffset.MaxValue).Total);
}
[Fact]
public async Task CodexHandlesCumulativeCounterResetWithoutLosingLaterIncrease()
{
using var directory = new TestDirectory();
directory.Write("codex/sessions/rollout-a.jsonl", Fixtures.Meta + Fixtures.Codex(100) +
Fixtures.Codex(10, "2026-10-14T16:01:00Z") + Fixtures.Codex(20, "2026-10-14T16:02:00Z"));
var history = new HistoryStore(directory.Path, new());
var scanner = new IncrementalScanner(history, new(), directory.Path, Path.Combine(directory.Path, "codex"));
await scanner.ScanAsync(TestContext.Current.CancellationToken);
Assert.Equal(112, history.Total(Provider.Codex, DateTimeOffset.MinValue, DateTimeOffset.MaxValue).Total);
}
[Fact]
public async Task MalformedLineDoesNotStopValidLaterEntry()
{
using var directory = new TestDirectory();
directory.Write("claude/projects/p/a.jsonl", "{\n" + Fixtures.Claude());
var log = new DiagnosticLog();
var scanner = new IncrementalScanner(new(directory.Path, log), log, Path.Combine(directory.Path, "claude"), directory.Path);
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
Assert.Single(log.Recent);
}
[Fact]
public async Task LargeValidEntryStillCountsUsage()
{
using var directory = new TestDirectory();
var line = Fixtures.Claude().Replace("{\"type\"", "{\"padding\":\"" + new string('x', 4 * 1024 * 1024) + "\",\"type\"");
directory.Write("claude/projects/p/large.jsonl", line);
var scanner = new IncrementalScanner(new(directory.Path, new()), new(), Path.Combine(directory.Path, "claude"), directory.Path);
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
}
[Fact]
public void LockIsExclusiveAndCanBeReacquired()
{
using var directory = new TestDirectory();
using (var first = StoreLock.TryAcquire(directory.Path))
{
Assert.NotNull(first);
Assert.Null(StoreLock.TryAcquire(directory.Path));
}
using var second = StoreLock.TryAcquire(directory.Path);
Assert.NotNull(second);
}
[Fact]
public async Task AtomicWritesReplaceAndCancellationPreservesPriorVersion()
{
using var directory = new TestDirectory();
var path = directory.Write("a.json", "old");
await AtomicFile.WriteAsync(path, "new", cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal("new", await File.ReadAllTextAsync(path, cancellationToken: TestContext.Current.CancellationToken));
using var cancellation = new CancellationTokenSource();
cancellation.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => AtomicFile.WriteAsync(path, "lost", cancellation.Token));
Assert.Equal("new", await File.ReadAllTextAsync(path, cancellationToken: TestContext.Current.CancellationToken));
Assert.Empty(Directory.GetFiles(directory.Path, "*.tmp"));
}
[Fact]
public async Task SettingsRoundTripAndInvalidFallback()
{
using var directory = new TestDirectory();
var log = new DiagnosticLog();
Assert.Equal(new Settings(), SettingsFile.Load(directory.Path, log));
Assert.Single(log.Recent);
var settings = new Settings { StreamDeckInstallMode = InstallMode.Automatic, Claude = new() { Enabled = false } };
await SettingsFile.SaveAsync(directory.Path, settings, cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(settings, SettingsFile.Load(directory.Path, new()));
directory.Write("settings.json", "{\"probeInterval\":\"00:00:10\"}");
Assert.Equal(new Settings(), SettingsFile.Load(directory.Path, new()));
directory.Write("settings.json", "{");
Assert.Equal(new Settings(), SettingsFile.Load(directory.Path, new()));
}
[Fact]
public async Task SnapshotRoundTripAndThreeIntervalStaleness()
{
using var directory = new TestDirectory();
var now = DateTimeOffset.UtcNow;
var snapshot = new Snapshot { MadeAt = now, RefreshInterval = TimeSpan.FromSeconds(60), Providers = [] };
await SnapshotFile.WriteAsync(directory.Path, snapshot, cancellationToken: TestContext.Current.CancellationToken);
var fresh = SnapshotFile.Read(directory.Path, now.AddSeconds(180));
Assert.False(fresh.IsStale);
Assert.Equal(now, fresh.Snapshot!.MadeAt);
Assert.Null(fresh.Snapshot.AppPath);
Assert.True(SnapshotFile.Read(directory.Path, now.AddSeconds(181)).IsStale);
directory.Write("snapshot.json", "{\"v\":2}");
Assert.Null(SnapshotFile.Read(directory.Path).Snapshot);
}
[Fact]
public void CorruptHistoryIsNotSilentlyOverwritten()
{
using var directory = new TestDirectory();
var path = directory.Write("history.state.json", "{");
Assert.Throws<InvalidDataException>(() => new HistoryStore(directory.Path, new()));
Assert.Equal("{", File.ReadAllText(path));
}
[Fact]
public void QueriesAggregateByHourDayModelProjectAndLimitWindow()
{
using var directory = new TestDirectory();
var history = new HistoryStore(directory.Path, new());
var now = new DateTimeOffset(2026, 10, 14, 16, 30, 0, TimeSpan.Zero);
history.Add(new(Provider.Claude, now.AddHours(-1), "a", "/one", new(Total: 10), "a"));
history.Add(new(Provider.Claude, now, "b", "/two", new(Total: 20), "b"));
history.Add(new(Provider.Codex, now, "b", "/two", new(Total: 99), "c"));
var window = new LimitWindow(Provider.Claude, "session", "Session", 20, now.AddHours(1), TimeSpan.FromHours(5), now, "fixture");
history.AddLimits([window]);
Assert.Equal(2, history.TokenSeries(Provider.Claude, now.AddHours(-2), now.AddHours(1), SeriesInterval.Hour).Count);
Assert.Equal(30, Assert.Single(history.TokenSeries(Provider.Claude, now.AddHours(-2), now.AddHours(1), SeriesInterval.Day)).Counts.Total);
Assert.Equal("b", history.ByModel(Provider.Claude, now.AddHours(-2), now.AddHours(1))[0].Name);
Assert.Equal("/two", history.ByProject(Provider.Claude, now.AddHours(-2), now.AddHours(1))[0].Name);
Assert.Single(history.LimitSamples(Provider.Claude, "session", now, now.AddHours(1)));
var totals = history.Totals(Provider.Claude, now, window, TimeZoneInfo.Utc);
Assert.Equal(30, totals.Today.Total);
Assert.Equal(30, totals.Session!.Value.Total);
Assert.Equal(30, totals.Week.Total);
}
[Fact]
public void LatestLimitSetDoesNotRetainWindowsRemovedByProvider()
{
using var directory = new TestDirectory();
var history = new HistoryStore(directory.Path, new());
var now = DateTimeOffset.UtcNow;
history.AddLimits([new(Provider.Codex, "codex:primary", "Session", 10, now.AddHours(1), TimeSpan.FromHours(5), now, "rollout"),
new(Provider.Codex, "codex:secondary", "Week", 20, now.AddDays(1), TimeSpan.FromDays(7), now, "rollout")]);
history.AddLimits([new(Provider.Codex, "codex:primary", "Week", 24, now.AddDays(5), TimeSpan.FromDays(7), now.AddMinutes(1), "app-server")]);
Assert.Single(history.LatestLimits(Provider.Codex));
Assert.Equal(2, history.LimitSamples(Provider.Codex, "codex:primary", now.AddMinutes(-1), now.AddMinutes(2)).Count);
}
}
@@ -0,0 +1,129 @@
using FinalToken.Core.StreamDeck;
using Xunit;
namespace FinalToken.Core.Tests.StreamDeck;
public sealed class InstallerTests : IDisposable
{
private readonly string root = Path.Combine(Path.GetTempPath(), "finaltoken-installer-" + Guid.NewGuid().ToString("N"));
private string Shipped => Path.Combine(root, "shipped");
private string Plugins => Path.Combine(root, "plugins");
private string Installed => Path.Combine(Plugins, PluginInstaller.FolderName);
public InstallerTests() => Write(Shipped, "1.0.0.0", "new");
[Fact]
public async Task ReleasePluginReportsOldDevelopmentCopyAsOutdated()
{
var shipped = Environment.GetEnvironmentVariable("FINALTOKEN_TEST_SHIPPED_PLUGIN");
if (shipped is null)
{
Write(Shipped, typeof(PluginInstaller).Assembly.GetName().Version!.ToString(), "new");
shipped = Shipped;
}
Write(Installed, "1.0.0.1", "old development copy");
var process = new FakeProcesses();
var installer = new PluginInstaller(shipped, new(Plugins, "fake", "fake"), process);
var status = await installer.GetStatusAsync(TestContext.Current.CancellationToken);
Assert.Equal(PluginInstallState.Outdated, status.State);
Assert.Equal(typeof(PluginInstaller).Assembly.GetName().Version!.ToString(), status.ShippedVersion);
Assert.Equal("1.0.0.1", status.InstalledVersion);
Assert.Equal(0, process.Stops); Assert.Equal(0, process.Starts);
}
[Fact]
public async Task FreshInstallDoesNotStartStoppedHost()
{
var process = new FakeProcesses();
var installer = Create(process);
Assert.Equal(PluginInstallState.NotInstalled, (await installer.GetStatusAsync(TestContext.Current.CancellationToken)).State);
await installer.InstallOrUpdateAsync(TestContext.Current.CancellationToken);
Assert.Equal("new", File.ReadAllText(Path.Combine(Installed, "binary")));
Assert.Equal(PluginInstallState.UpToDate, (await installer.GetStatusAsync(TestContext.Current.CancellationToken)).State);
Assert.Equal(0, process.Stops); Assert.Equal(0, process.Starts);
}
[Fact]
public async Task UpdateStopsAndRestartsRunningHost()
{
Write(Installed, "0.9.0.0", "old");
var process = new FakeProcesses { Running = true };
var installer = Create(process);
var outcomes = new List<InstallOutcome>(); installer.Outcome += outcomes.Add;
Assert.Equal(PluginInstallState.Outdated, (await installer.GetStatusAsync(TestContext.Current.CancellationToken)).State);
await installer.InstallOrUpdateAsync(TestContext.Current.CancellationToken);
Assert.Equal("new", File.ReadAllText(Path.Combine(Installed, "binary")));
Assert.Equal(1, process.Stops); Assert.Equal(1, process.Starts);
Assert.Contains(InstallOutcome.Updated, outcomes);
Assert.Single(Directory.GetDirectories(Plugins));
}
[Fact]
public async Task CurrentAndNewerVersionsAreNotReplaced()
{
Write(Installed, "2.0.0.0", "newer");
var process = new FakeProcesses { Running = true };
await Create(process).InstallOrUpdateAsync(TestContext.Current.CancellationToken);
Assert.Equal("newer", File.ReadAllText(Path.Combine(Installed, "binary")));
Assert.Equal(0, process.Stops);
}
[Fact]
public async Task RestartFailureRollsBackAndRestartsOldPlugin()
{
Write(Installed, "0.9.0.0", "old");
var process = new FakeProcesses { Running = true, FailFirstStart = true };
var installer = Create(process);
var outcomes = new List<InstallOutcome>(); installer.Outcome += outcomes.Add;
await Assert.ThrowsAsync<IOException>(() => installer.InstallOrUpdateAsync(TestContext.Current.CancellationToken));
Assert.Equal("old", File.ReadAllText(Path.Combine(Installed, "binary")));
Assert.Equal(2, process.Starts);
Assert.Contains(InstallOutcome.RolledBack, outcomes);
Assert.Single(Directory.GetDirectories(Plugins));
}
[Fact]
public async Task NoHostAndMissingShippedPluginHaveExplicitStatus()
{
var installer = new PluginInstaller(Shipped, null);
Assert.Equal(PluginInstallState.NoHostFound, (await installer.GetStatusAsync(TestContext.Current.CancellationToken)).State);
await installer.InstallOrUpdateAsync(TestContext.Current.CancellationToken);
var missing = new PluginInstaller(Path.Combine(root, "missing"), new(Plugins, "fake", "fake"));
Assert.Equal(PluginInstallState.NoShippedPlugin, (await missing.GetStatusAsync(TestContext.Current.CancellationToken)).State);
await Assert.ThrowsAsync<InvalidOperationException>(() => missing.InstallOrUpdateAsync(TestContext.Current.CancellationToken));
}
[Fact]
public async Task StopFailureKeepsOldFolderAndAttemptsRestart()
{
Write(Installed, "0.9.0.0", "old");
var process = new FakeProcesses { Running = true, FailStop = true };
await Assert.ThrowsAsync<IOException>(() => Create(process).InstallOrUpdateAsync(TestContext.Current.CancellationToken));
Assert.Equal("old", File.ReadAllText(Path.Combine(Installed, "binary")));
Assert.Equal(1, process.Starts);
}
[Theory]
[InlineData(InstallMode.Off, InstallAction.Nothing)]
[InlineData(InstallMode.Ask, InstallAction.Ask)]
[InlineData(InstallMode.Automatic, InstallAction.Install)]
public void PolicyHonorsInstallMode(InstallMode mode, InstallAction expected) =>
Assert.Equal(expected, InstallPolicy.Decide(mode, new(PluginInstallState.NotInstalled, "1"), null));
[Fact]
public void PolicyHonorsDismissedVersionAndUnavailableHost()
{
Assert.Equal(InstallAction.Nothing, InstallPolicy.Decide(InstallMode.Ask, new(PluginInstallState.Outdated, "1"), "1"));
Assert.Equal(InstallAction.Nothing, InstallPolicy.Decide(InstallMode.Automatic, new(PluginInstallState.NoHostFound), null));
}
private PluginInstaller Create(FakeProcesses process) => new(Shipped, new(Plugins, "fake", "fake"), process);
private static void Write(string directory, string version, string binary)
{
Directory.CreateDirectory(directory);
File.WriteAllText(Path.Combine(directory, "manifest.json"), "{\"Version\":\"" + version + "\"}");
File.WriteAllText(Path.Combine(directory, "binary"), binary);
}
public void Dispose() { if (Directory.Exists(root)) Directory.Delete(root, true); }
private sealed class FakeProcesses : IHostProcesses
{
public bool Running { get; init; }
public bool FailFirstStart { get; init; }
public bool FailStop { get; init; }
public int Stops { get; private set; }
public int Starts { get; private set; }
public Task<bool> IsRunningAsync(PluginHost host, CancellationToken ct) => Task.FromResult(Running);
public Task StopAsync(PluginHost host, CancellationToken ct) { Stops++; if (FailStop) throw new IOException("stop failed"); return Task.CompletedTask; }
public Task StartAsync(PluginHost host, CancellationToken ct) { Starts++; if (FailFirstStart && Starts == 1) throw new IOException("start failed"); return Task.CompletedTask; }
}
}
@@ -0,0 +1,95 @@
using FinalToken.Core.Processes;
using System.Threading.Channels;
namespace FinalToken.Core.Tests;
public sealed class TestDirectory : IDisposable
{
public string Path { get; } = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "finaltoken-test-" + Guid.NewGuid().ToString("N"));
public TestDirectory() => Directory.CreateDirectory(Path);
public string Write(string relative, string contents)
{
var path = System.IO.Path.GetFullPath(System.IO.Path.Combine(Path, relative));
Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path)!);
File.WriteAllText(path, contents);
return path;
}
public void Dispose() => Directory.Delete(Path, true);
}
public sealed class TestClock : TimeProvider
{
private readonly Channel<TimeSpan> scheduled = Channel.CreateUnbounded<TimeSpan>();
public ValueTask<TimeSpan> NextTimerAsync(CancellationToken cancellationToken) => scheduled.Reader.ReadAsync(cancellationToken);
private readonly Lock gate = new();
private DateTimeOffset now = new(2026, 10, 14, 16, 0, 0, TimeSpan.Zero);
private readonly List<TestTimer> timers = [];
public override DateTimeOffset GetUtcNow() { lock (gate) return now; }
public void Advance(TimeSpan amount)
{
List<TestTimer> due;
lock (gate)
{
now += amount;
due = timers.Where(t => t.Next <= now && !t.Disposed).ToList();
foreach (var timer in due) timer.Next = timer.Period > TimeSpan.Zero ? now + timer.Period : DateTimeOffset.MaxValue;
}
foreach (var timer in due) timer.Callback(timer.State);
}
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
{
lock (gate)
{
var timer = new TestTimer(this, callback, state, period);
timer.Change(dueTime, period);
timers.Add(timer);
scheduled.Writer.TryWrite(dueTime);
return timer;
}
}
private sealed class TestTimer(TestClock owner, TimerCallback callback, object? state, TimeSpan period) : ITimer
{
public TimerCallback Callback { get; } = callback;
public object? State { get; } = state;
public TimeSpan Period { get; private set; } = period;
public DateTimeOffset Next { get; set; }
public bool Disposed { get; private set; }
public bool Change(TimeSpan dueTime, TimeSpan newPeriod)
{
lock (owner.gate)
{
if (Disposed) return false;
Period = newPeriod;
Next = dueTime == Timeout.InfiniteTimeSpan ? DateTimeOffset.MaxValue : owner.now + dueTime;
return true;
}
}
public void Dispose() { lock (owner.gate) Disposed = true; }
public ValueTask DisposeAsync() { Dispose(); return ValueTask.CompletedTask; }
}
}
public sealed class FakeRunner : IProcessRunner
{
public List<ProcessRequest> Requests { get; } = [];
public Func<ProcessRequest, CancellationToken, Task<ProcessResult>>? Handler { get; set; }
public Task<ProcessResult> RunAsync(ProcessRequest request, CancellationToken cancellationToken)
{
Requests.Add(request);
return Handler?.Invoke(request, cancellationToken) ?? Task.FromResult(new ProcessResult(0,
request.CodexRpc ? Fixtures.CodexResponse : Fixtures.ClaudeEnvelope));
}
}
internal static class Fixtures
{
public const string ClaudeEnvelope = "{\"local_command\":\"usage\",\"num_turns\":0,\"is_error\":false,\"result\":\"Current session: 28% used · resets Oct 14, 7:30pm (Europe/Berlin)\\nCurrent week (all models): 66% used · resets Oct 18, 8pm (Europe/Berlin)\"}";
public const string CodexResponse = "{\"id\":2,\"result\":{\"rateLimits\":{\"limitId\":\"codex\",\"primary\":{\"usedPercent\":24,\"windowDurationMins\":10080,\"resetsAt\":1792479531},\"secondary\":null}}}";
public static string Claude(string id = "a", string request = "r", int input = 10, string time = "2026-10-14T16:00:00Z") =>
"""{"type":"assistant","timestamp":"@time","cwd":"/project","requestId":"@request","message":{"id":"@id","model":"fixture-model","usage":{"input_tokens":@input,"output_tokens":2,"cache_read_input_tokens":3,"cache_creation_input_tokens":4}}}"""
.Replace("@time", time).Replace("@request", request).Replace("@id", id).Replace("@input", input.ToString(System.Globalization.CultureInfo.InvariantCulture)) + "\n";
public const string Meta = "{\"type\":\"session_meta\",\"payload\":{\"id\":\"session-1\",\"cwd\":\"/project\"}}\n{\"type\":\"turn_context\",\"payload\":{\"model\":\"fixture-model\"}}\n";
public static string Codex(int input, string time = "2026-10-14T16:00:00Z") =>
"""{"type":"event_msg","timestamp":"@time","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":@input,"cached_input_tokens":0,"output_tokens":2,"reasoning_output_tokens":1,"total_tokens":@total}},"rate_limits":{"limit_id":"codex","primary":{"used_percent":24,"window_minutes":10080,"resets_at":1792479531},"secondary":null}}}"""
.Replace("@time", time).Replace("@input", input.ToString(System.Globalization.CultureInfo.InvariantCulture)).Replace("@total", (input + 2).ToString(System.Globalization.CultureInfo.InvariantCulture)) + "\n";
}
+8
View File
@@ -0,0 +1,8 @@
# Process probe host
Windows GUI-subsystem regression helper for D6. It deliberately has no console or standard
handles, then runs Core's ProcessRunner. Child modes check handles and synthetic UTF-8 JSON. The optional
live Claude mode keeps provider output in memory and writes only diagnostic metadata.
No provider text or real transcript fixtures belong here. JSON uses source generation.
Built with Core tests; run `dotnet test --project tests/FinalToken.Core.Tests -c Release`.
Portable `--rpc-*` modes provide synthetic app-server exchanges, errors, EOF and malformed output.
The `app-server` mode returns an RPC error for published-CLI checks; it never contacts a provider.
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
@@ -0,0 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup><ProjectReference Include="../../src/FinalToken.Core/FinalToken.Core.csproj" /></ItemGroup>
</Project>
+104
View File
@@ -0,0 +1,104 @@
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using FinalToken.Core;
using FinalToken.Core.Collectors;
using FinalToken.Core.Processes;
namespace FinalToken.ProcessHost;
public static class Program
{
public static async Task<int> Main(string[] args)
{
if (args.FirstOrDefault() is { } mode && (mode.StartsWith("--rpc-", StringComparison.Ordinal) || mode == "app-server"))
return await RpcAsync(mode == "app-server" ? "--rpc-error" : mode);
if (!OperatingSystem.IsWindows()) return 0;
if (args is ["--handles"])
return new[] { -10, -11, -12 }.All(id => Native.GetFileType(Native.GetStdHandle(id)) != 0) ? 0 : 17;
if (args is ["--utf8"])
{
await Console.OpenStandardOutput().WriteAsync(System.Text.Encoding.UTF8.GetBytes("{\"marker\":\"· •\"}"));
return 0;
}
if (args.Length < 2) return 2;
Native.FreeConsole();
foreach (var id in new[] { -10, -11, -12 }) Native.SetStdHandle(id, 0);
var report = new ProbeReport { HostHasConsole = Native.GetConsoleWindow() != 0,
HostInputValid = Native.GetFileType(Native.GetStdHandle(-10)) != 0, OutputCodePage = Console.OutputEncoding.CodePage };
var live = args[0] == "--claude";
var utf8 = args[0] == "--utf8-probe";
var cli = live ? CliDiscovery.Find(Provider.Claude).Command : new CliCommand(Environment.ProcessPath!, []);
if (cli is null) return 3;
var result = await new ProcessRunner().RunAsync(new(cli, live
? ["-p", "/usage", "--output-format", "json", "--no-session-persistence"] : utf8 ? ["--utf8"] : ["--handles"],
Path.GetDirectoryName(Path.GetFullPath(args[1]))!, TimeSpan.FromSeconds(60)), CancellationToken.None);
report = report with { ExitCode = result.ExitCode, TimedOut = result.TimedOut,
Utf8Matched = utf8 && result.Output == "{\"marker\":\"· •\"}" };
if (live)
{
var diagnostics = new DiagnosticLog();
var windows = ClaudeUsageParser.ParseEnvelope(result.Output, DateTimeOffset.UtcNow, diagnostics);
report = report with { WindowCount = windows.Count, DiagnosticCodes = diagnostics.Recent.Select(d => d.Code).ToArray() };
}
await AtomicFile.WriteAsync(args[1], JsonSerializer.Serialize(report, ProbeJsonContext.Default.ProbeReport));
return live ? report.WindowCount > 0 ? 0 : 18 : utf8 ? report.Utf8Matched ? 0 : 19 : result.ExitCode;
}
private static async Task<int> RpcAsync(string mode)
{
Console.InputEncoding = System.Text.Encoding.UTF8;
Console.OutputEncoding = new System.Text.UTF8Encoding(false);
if (mode == "--rpc-eof") return 0;
var initialize = await Console.In.ReadLineAsync();
using var first = JsonDocument.Parse(initialize ?? "null");
if (first.RootElement.GetProperty("method").GetString() != "initialize") return 20;
if (mode == "--rpc-init-error") { await Console.Out.WriteLineAsync("{\"id\":1,\"error\":{\"code\":-1,\"message\":\"synthetic error\"}}"); return 0; }
await Console.Out.WriteLineAsync("{\"id\":1,\"result\":{}}");
using var initialized = JsonDocument.Parse(await Console.In.ReadLineAsync() ?? "null");
using var request = JsonDocument.Parse(await Console.In.ReadLineAsync() ?? "null");
if (initialized.RootElement.GetProperty("method").GetString() != "initialized" ||
request.RootElement.GetProperty("method").GetString() != "account/rateLimits/read") return 21;
await Console.Out.WriteLineAsync("{\"method\":\"syntheticNotification\"}");
var response = mode switch
{
"--rpc-error" => "{\"id\":2,\"error\":{\"code\":-1,\"message\":\"synthetic error\"}}",
"--rpc-garbage" => "not JSON",
"--rpc-shape" => "[]",
"--rpc-bound" => new string('x', 1024 * 1024 + 1),
_ => "{\"id\":2,\"result\":{\"rateLimits\":{\"limitId\":\"codex\",\"primary\":{\"usedPercent\":24,\"windowDurationMins\":10080,\"resetsAt\":1792479531}}}}"
};
await Console.Out.WriteLineAsync(response);
return 0;
}
}
public sealed record ProbeReport
{
public bool HostHasConsole { get; init; }
public bool HostInputValid { get; init; }
public int ExitCode { get; init; }
public bool TimedOut { get; init; }
public int WindowCount { get; init; }
public int OutputCodePage { get; init; }
public bool Utf8Matched { get; init; }
public string[] DiagnosticCodes { get; init; } = [];
}
[JsonSerializable(typeof(ProbeReport))]
internal partial class ProbeJsonContext : JsonSerializerContext;
internal static partial class Native
{
[LibraryImport("kernel32.dll")]
internal static partial nint GetStdHandle(int id);
[LibraryImport("kernel32.dll")]
internal static partial uint GetFileType(nint handle);
[LibraryImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static partial bool SetStdHandle(int id, nint handle);
[LibraryImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static partial bool FreeConsole();
[LibraryImport("kernel32.dll")]
internal static partial nint GetConsoleWindow();
}
@@ -0,0 +1,5 @@
# StreamDeck tests
Hand-written fixtures only. xUnit v3 AOT with Microsoft.Testing.Platform.
Run `dotnet test --project tests/FinalToken.StreamDeck.Tests -c Release` from the root.
Use fake sockets and synthetic snapshots for protocol, settings and key rendering checks.
Manifest tests read the copied plugin assets. Never require a running Stream Deck host.
@@ -0,0 +1 @@
@AGENTS.md
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<IsTestProject>true</IsTestProject>
<UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner>
<TestingPlatformDotnetTestSupport>true</TestingPlatformDotnetTestSupport>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="xunit.v3.aot.mtp-v2" />
<ProjectReference Include="../../src/FinalToken.StreamDeck/FinalToken.StreamDeck.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,165 @@
using System.Text.Json;
using System.Xml.Linq;
using FinalToken.Core;
using Xunit;
namespace FinalToken.StreamDeck.Tests;
public sealed class PluginTests
{
[Fact]
public async Task InvalidHostFrameEndsConnectionWithoutLoggingFrameText()
{
var socket = new FakeSocket { ReceiveFailure = new InvalidDataException("synthetic private frame") };
var session = new PluginSession(socket, _ => Task.FromResult(false));
Assert.Null(await session.ReceiveAsync(TestContext.Current.CancellationToken));
Assert.Equal("connection-ended", session.ConnectionEndCode);
}
[Theory]
[InlineData("{}", "Claude", "SessionPercent", "")]
[InlineData("{\"provider\":\"Codex\"}", "Codex", "SessionPercent", "")]
[InlineData("{\"metric\":\"TokensToday\",\"future\":1}", "Claude", "TokensToday", "")]
public void PartialStatSettingsKeepConstructorDefaults(string json, string provider, string metric, string window)
{
var settings = JsonSerializer.Deserialize(json, PluginJsonContext.Default.StatSettings)!;
Assert.Equal(new StatSettings(provider, metric, window), settings);
Assert.True(settings.IsValid);
}
private static readonly DateTimeOffset Now = new(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
private static Snapshot Snapshot(PaceState state = PaceState.Ahead) => new()
{
MadeAt = Now, RefreshInterval = TimeSpan.FromMinutes(1), AppPath = "app.exe",
Providers = [new(Provider.Claude, ProviderStatus.Available, null,
[new(new(Provider.Claude, "session", "Session", 65, Now.AddHours(2), TimeSpan.FromHours(5), Now, "test"), new(state, .6, 5)),
new(new(Provider.Claude, "week", "Week", 42, Now.AddDays(2), TimeSpan.FromDays(7), Now, "test"), new(state, .5, -8))],
new(Total: 12345), null, new(Total: 2345678))]
};
[Fact]
public async Task RegistersAndSettingsRoundTripWithDeduplicatedDrawing()
{
var socket = new FakeSocket();
var session = new PluginSession(socket, _ => Task.FromResult(true));
await session.RegisterAsync(new(1234, "registration-id", "registerPlugin"), TestContext.Current.CancellationToken);
Assert.Equal("registerPlugin", Read(socket.Sent[0], "event"));
Assert.Equal("registration-id", Read(socket.Sent[0], "uuid"));
await session.UpdateAsync(new(Snapshot(), false, null), Now, TestContext.Current.CancellationToken);
await session.HandleAsync("""{"event":"willAppear","action":"de.finalfactory.finaltoken.stat","context":"key","payload":{"settings":{}}}""", Now, TestContext.Current.CancellationToken);
var count = socket.Sent.Count;
await session.UpdateAsync(new(Snapshot(), false, null), Now, TestContext.Current.CancellationToken);
Assert.Equal(count, socket.Sent.Count);
await session.HandleAsync("""{"event":"sendToPlugin","context":"key","payload":{"settings":{"provider":"Claude","metric":"TokensWeek","window":"week"}}}""", Now, TestContext.Current.CancellationToken);
using var settings = JsonDocument.Parse(socket.Sent.Single(s => Read(s, "event") == "setSettings"));
Assert.Equal("TokensWeek", settings.RootElement.GetProperty("payload").GetProperty("metric").GetString());
Assert.Equal("sendToPropertyInspector", Read(socket.Sent[^1], "event"));
await session.HandleAsync("""{"event":"willDisappear","context":"key"}""", Now, TestContext.Current.CancellationToken);
count = socket.Sent.Count;
await session.UpdateAsync(new(null, true, null), Now, TestContext.Current.CancellationToken);
Assert.Equal(count, socket.Sent.Count);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task KeyPressLaunchesSnapshotAppAndAlertsFailure(bool success)
{
string? path = null;
var socket = new FakeSocket();
var session = new PluginSession(socket, value => { path = value; return Task.FromResult(success); });
await session.UpdateAsync(new(Snapshot(), false, null), Now, TestContext.Current.CancellationToken);
await session.HandleAsync("""{"event":"keyDown","context":"key"}""", Now, TestContext.Current.CancellationToken);
Assert.Equal("app.exe", path);
Assert.Equal(success ? 0 : 1, socket.Sent.Count);
if (!success) Assert.Equal("showAlert", Read(socket.Sent[0], "event"));
}
[Theory]
[InlineData("SessionPercent", "65%")]
[InlineData("WeekPercent", "42%")]
[InlineData("PaceDelta", "+5pp")]
[InlineData("TimeToReset", "2h 0m")]
[InlineData("TokensToday", "12.3k")]
[InlineData("TokensWeek", "2.3M")]
public void RendersEveryMetric(string metric, string value)
{
var svg = StatRenderer.Render(new(Snapshot(), false, null), new(Metric: metric), Now);
Assert.Contains(value, svg);
Assert.Equal("svg", XDocument.Parse(svg).Root!.Name.LocalName);
}
[Theory]
[InlineData(PaceState.Ahead, "#ef6461")]
[InlineData(PaceState.Behind, "#69a7ff")]
[InlineData(PaceState.OnTrack, "#58d6a0")]
[InlineData(PaceState.Unknown, "#a0a7b4")]
public void RendersPaceColorAndMarker(PaceState state, string color)
{
var svg = StatRenderer.Render(new(Snapshot(state), false, null), new(), Now);
Assert.Contains(color, svg);
Assert.Contains("M42 56v11", svg);
}
[Fact]
public void StaleMissingAndUnknownWindowAreExplicit()
{
Assert.Contains("offline", StatRenderer.Render(new(Snapshot(), true, null), new(), Now));
Assert.Contains("offline", StatRenderer.Render(new(null, true, null), new(), Now));
Assert.Contains("—", StatRenderer.Render(new(Snapshot(), false, null), new(Window: "removed"), Now));
}
[Fact]
public void NullNestedSnapshotContentShowsOffline()
{
var snapshot = Snapshot() with { Providers = [new(Provider.Claude, ProviderStatus.Available, null, null!, new(), null, new())] };
Assert.Contains("offline", StatRenderer.Render(new(snapshot, false, null), new(), Now));
}
[Fact]
public void PaceAndResetUseAvailableWeekWhenNoSessionExists()
{
var provider = Snapshot().Providers[0];
provider = provider with { Windows = [provider.Windows[1]] };
Assert.Equal("week", StatRenderer.SelectWindow(provider, new(Metric: "PaceDelta"))?.Window.Id);
Assert.Equal("week", StatRenderer.SelectWindow(provider, new(Metric: "TimeToReset"))?.Window.Id);
Assert.Null(StatRenderer.SelectWindow(provider, new()));
}
[Fact]
public async Task MalformedAndInvalidSettingsDoNotChangeKeys()
{
var socket = new FakeSocket();
var session = new PluginSession(socket, _ => Task.FromResult(false));
foreach (var json in new[] { "{", "[]", "null", """{"event":"willAppear","context":"key","payload":{"settings":{"provider":"Unknown"}}}""" })
await session.HandleAsync(json, Now, TestContext.Current.CancellationToken);
Assert.Empty(socket.Sent);
}
[Fact]
public void RegistrationValidatesArguments()
{
Assert.NotNull(Registration.Parse(["-port", "1234", "-pluginUUID", "x", "-registerEvent", "registerPlugin", "-info", "{}"]));
Assert.Null(Registration.Parse(["-port", "0"]));
}
[Fact]
public void ManifestHasExpectedContractAndLocalAssets()
{
var folder = Path.Combine(AppContext.BaseDirectory, "plugin");
using var manifest = JsonDocument.Parse(File.ReadAllText(Path.Combine(folder, "manifest.json")));
var root = manifest.RootElement;
Assert.Equal(2, root.GetProperty("SDKVersion").GetInt32());
Assert.Equal("de.finalfactory.finaltoken", root.GetProperty("UUID").GetString());
Assert.Equal("FinalToken.StreamDeck.exe", root.GetProperty("CodePathWin").GetString());
Assert.Equal("FinalToken.StreamDeck", root.GetProperty("CodePathLin").GetString());
Assert.True(Version.TryParse(root.GetProperty("Version").GetString(), out _));
Assert.Single(root.GetProperty("Actions").EnumerateArray());
Assert.Equal(PluginSession.Action, root.GetProperty("Actions")[0].GetProperty("UUID").GetString());
Assert.True(File.Exists(Path.Combine(folder, root.GetProperty("PropertyInspectorPath").GetString()!)));
Assert.True(File.Exists(Path.Combine(folder, root.GetProperty("Icon").GetString()! + ".svg")));
}
private static string? Read(string json, string property)
{
using var doc = JsonDocument.Parse(json);
return doc.RootElement.GetProperty(property).GetString();
}
private sealed class FakeSocket : IPluginSocket
{
public Exception? ReceiveFailure { get; init; }
public List<string> Sent { get; } = [];
public Task SendAsync(string json, CancellationToken cancellationToken) { Sent.Add(json); return Task.CompletedTask; }
public Task<string?> ReceiveAsync(CancellationToken cancellationToken) => ReceiveFailure is { } error
? Task.FromException<string?>(error) : Task.FromResult<string?>(null);
}
}