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
+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";
}