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:
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user