core: add the solution, Core engine, CLI and tests

Core implements the CLI-only collectors for Claude and Codex (D2 to D4),
the history store (D5), the refresh engine (D6), pace and popup
decisions (D7, D8), the snapshot contract (D9) and the Stream Deck
installer contract (D11). finaltoken status runs one refresh and prints
the snapshot. The app and plugin projects are placeholders so the
solution file is complete before they are built in parallel.

Refs #1
This commit is contained in:
Florian Schmidt
2026-10-14 19:09:54 +02:00
parent db890c5f68
commit 14223b05df
60 changed files with 2287 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,72 @@
using FinalToken.Core.Processes;
using FinalToken.Core.StreamDeck;
using Xunit;
namespace FinalToken.Core.Tests;
public class DiscoveryAndPolicyTests
{
[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,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.Core/FinalToken.Core.csproj" />
</ItemGroup>
</Project>
+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("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(2, diagnostics.Recent.Count);
Assert.All(diagnostics.Recent, d => Assert.DoesNotContain("private fixture", d.Summary));
}
}
@@ -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(10), OutputLimit: 50), TestContext.Current.CancellationToken);
Assert.Equal(0, result.ExitCode);
Assert.Equal(50, result.Output.Length);
Assert.True(result.OutputTruncated);
}
}
+190
View File
@@ -0,0 +1,190 @@
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);
await File.WriteAllTextAsync(source, Fixtures.Claude("c"), cancellationToken: TestContext.Current.CancellationToken);
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.Equal(Environment.ProcessPath, 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.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,91 @@
using FinalToken.Core.Processes;
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 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);
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";
}