Files
FinalToken/tests/FinalToken.Core.Tests/StorageTests.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

193 lines
12 KiB
C#

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