Files
FinalToken/tests/FinalToken.Core.Tests/EngineTests.cs
T
schmidt.florian f8afd11679 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
2026-10-14 22:11:19 +02:00

161 lines
8.0 KiB
C#

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);
}
}