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