diff --git a/AGENTS.md b/AGENTS.md index 6e80630..8147740 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,7 +28,7 @@ the decision, why and gives-up format, and carries the `type/decision` label. |---|---| | `src/FinalToken.Core` | No UI. Domain model, pace (D7), collectors (D3, D4), history store (D5), refresh scheduler (D6), snapshot contract (D9), settings, plugin installer (D11) | | `src/FinalToken.App` | Avalonia desktop app (D8): stats panel, tray, settings, popups | -| `src/FinalToken.Cli` | `finaltoken` console: runs a refresh and prints the snapshot, for scripts and checks | +| `src/FinalToken.Cli` | `finaltoken-cli` console: runs a refresh and prints the snapshot, for scripts and checks | | `src/FinalToken.StreamDeck` | Stream Deck plugin executable and its `.sdPlugin` assets (D10) | | `tests/*` | One test project per tested project, named `.Tests` | | `tools/` | Repository tools, listed under [Tools](#tools) | @@ -123,6 +123,8 @@ a screenshot of each changed view: compiling is not working. - `tools/gitea.sh`: calls the Gitea API with the stored git credential or `GITEA_TOKEN`. - `tools/agent-review.sh`: posts an agent review and sets the `agent-review` status; see `docs/agents/review.md`. +- `tools/publish.py`: publishes the app, `finaltoken-cli` and Stream Deck plugin with NativeAOT + into an empty output directory and creates a ZIP beside it. Run on the target OS. ## Writing diff --git a/FinalToken.slnx b/FinalToken.slnx index 530ee06..e9adc4d 100644 --- a/FinalToken.slnx +++ b/FinalToken.slnx @@ -6,6 +6,7 @@ + diff --git a/README.md b/README.md index 882ad03..f987c29 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,57 @@ # FinalToken +FinalToken is a tray app for Claude Code and Codex usage. It shows token history, provider limits, +and pace, warns when usage runs ahead of or behind a limit, and puts selected stats on Stream Deck +keys. Starting the app opens the stats panel; closing it keeps the tray app running by default. + +FinalToken does not sign in to a provider, handle API keys or OAuth tokens, or read credential +files. It reads the installed CLIs' usage files and runs their local commands. It never calls a +provider's HTTP API itself. Missing or logged-out CLIs show as unavailable. + +## Requirements + +- Claude Code and/or Codex CLI installed and logged in through the CLI. Their paths can be + overridden in Settings. +- Windows 11, or Linux with X11 or XWayland. CachyOS with KDE Plasma uses XWayland. +- For keys: Stream Deck 7 on Windows, or OpenDeck on Linux. These are optional. + +## Install and use + +Extract the published ZIP to a folder and run `FinalToken.exe` on Windows or `FinalToken` on +Linux. Keep the `streamdeck` folder beside the app. Open, Refresh, Settings and Quit are in the +tray menu. Start with the OS is opt-in. + +Data lives in `%LOCALAPPDATA%\FinalToken` on Windows and `~/.local/share/FinalToken` on Linux. +`FINALTOKEN_DATA_DIR` overrides it. FinalToken keeps its own history after the CLIs remove their +files. A fresh install imports Claude entries from the last 60 days. `snapshot.json` is the +shared output for the plugin and CLI. + +Settings has three Stream Deck install modes: **Off**, **Ask** (default), and **Automatic**. +Ask offers Install or Update and Not now. Automatic installs or updates the shipped plugin when +a host is found; it stops and restarts a running host. Off installs nothing. +Add the plugin's **Stat** action to a key, then select a provider and metric in its inspector. +Pressing the key opens the app's panel; missing or stale data shows offline. + +## CLI + +Run `finaltoken-cli status [--json] [--no-probe]`. Use `./finaltoken-cli` on Linux or +`.\finaltoken-cli.exe` in PowerShell when running from the extracted folder. +It scans, probes limits and prints a snapshot. `--no-probe` reads usage files only. +When the app holds the store lock, the CLI reads its existing snapshot without refreshing. +Exit codes are 0 for success, 1 for failure and 2 for bad arguments. + +## Build from source + +Use .NET SDK 10.0.100 or newer within .NET 10, Python 3, and the target OS's NativeAOT C++ +toolchain. Run from the repository root, as described in [AGENTS.md](AGENTS.md): + +```text +dotnet build FinalToken.slnx -c Release +dotnet test --solution FinalToken.slnx -c Release +python -B tools/docs/check_docs.py +python -B tools/publish.py win-x64 --out artifacts/package-win-x64 +``` + +The publish directory must be empty. The tool bundles all three executables and plugin assets, +then creates a ZIP beside the directory. Publish `win-x64` on Windows and `linux-x64` on Linux. + diff --git a/src/FinalToken.App/AGENTS.md b/src/FinalToken.App/AGENTS.md index 045f37b..6db63a2 100644 --- a/src/FinalToken.App/AGENTS.md +++ b/src/FinalToken.App/AGENTS.md @@ -2,7 +2,9 @@ Avalonia 12 Fluent host (D8). Views are built in C# without reflection bindings. View-model properties use CommunityToolkit.Mvvm source generators. Custom charts use DrawingContext. Program owns StoreLock for the engine lifetime. DesktopApp marshals Core events to the UI; +Program passes its executable path to RefreshEngine for desktop activation through D9 snapshots. history queries run on worker threads and discard superseded results. Keep all writes atomic (D5). +Daily charts use local calendar boundaries; never assume a day lasts 24 hours. Stream Deck policy and the real installer come through IPluginInstaller (D11). UsePlatformDetect selects X11 on Linux in the pinned Avalonia version. Keep XWayland support. Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root. diff --git a/src/FinalToken.App/PanelViewModel.cs b/src/FinalToken.App/PanelViewModel.cs index b4a7c30..a8271bc 100644 --- a/src/FinalToken.App/PanelViewModel.cs +++ b/src/FinalToken.App/PanelViewModel.cs @@ -49,7 +49,7 @@ public partial class PanelViewModel : ObservableObject : ModelsAtPoint(p.Provider, point.Time, interval))).ToArray(); IEnumerable ModelsAtPoint(Provider provider, DateTimeOffset time, SeriesInterval interval) { - var end = time.Add(interval == SeriesInterval.Hour ? TimeSpan.FromHours(1) : TimeSpan.FromDays(1)); + var end = interval == SeriesInterval.Hour ? time.AddHours(1) : CalendarDays.NextStart(time); return store.ByModel(provider, time < from ? from : time, end > now ? now : end) .Select(m => new ChartValue(time, m.Name ?? "Unknown model", m.Counts.Total)); } diff --git a/src/FinalToken.App/PanelWindow.cs b/src/FinalToken.App/PanelWindow.cs index c09a45c..b4008fd 100644 --- a/src/FinalToken.App/PanelWindow.cs +++ b/src/FinalToken.App/PanelWindow.cs @@ -79,7 +79,7 @@ public sealed class PanelWindow : Window } var h = model.History; body.Children.Add(Ui.Card(Ui.Stack(Ui.Text("Tokens per hour", 19), Legend(h.Hourly), new UsageChart { Values = h.Hourly }))); - body.Children.Add(Ui.Card(Ui.Stack(Ui.Text("Tokens per day · UTC days", 19), Legend(h.Daily), new UsageChart { Values = h.Daily, Interval = TimeSpan.FromDays(1) }))); + body.Children.Add(Ui.Card(Ui.Stack(Ui.Text("Tokens per day", 19), Legend(h.Daily), new UsageChart { Values = h.Daily, Interval = TimeSpan.FromDays(1) }))); foreach (var limit in h.Limits) body.Children.Add(Ui.Card(Ui.Stack(Ui.Text(limit.Label, 19), Ui.Text("Blue: used · dashed green: expected pace · gaps: window reset", 11), new UsageChart { Values = limit.Values, Percent = true }))); body.Children.Add(Breakdown("By model", h.Models)); diff --git a/src/FinalToken.App/Program.cs b/src/FinalToken.App/Program.cs index d3bf046..91f0d56 100644 --- a/src/FinalToken.App/Program.cs +++ b/src/FinalToken.App/Program.cs @@ -20,7 +20,7 @@ public static class Program if (OperatingSystem.IsWindows()) WindowsActivation.AllowRunningInstance(); ActivationFile.RequestAsync(directory).GetAwaiter().GetResult(); return 0; } - try { Engine = new RefreshEngine(directory); } + try { Engine = new RefreshEngine(directory, appPath: Environment.ProcessPath); } catch (InvalidDataException e) { StartupError = e.Message; } BuildAvaloniaApp().StartWithClassicDesktopLifetime(args); return StartupError is null ? 0 : 1; diff --git a/src/FinalToken.Cli/AGENTS.md b/src/FinalToken.Cli/AGENTS.md index 4d7979a..8ceefc3 100644 --- a/src/FinalToken.Cli/AGENTS.md +++ b/src/FinalToken.Cli/AGENTS.md @@ -1,4 +1,6 @@ # CLI NativeAOT console host for D1, D5, D6 and D9. Exit codes: success 0, failure 1, usage 2. +Assembly/executable name is `finaltoken-cli` on every platform, beside the `FinalToken` app. A busy store is read-only. Keep argument parsing in CliApplication for tests. +Pass no app path to RefreshEngine; preserve the desktop path from an existing snapshot. Run `dotnet test --project tests/FinalToken.Cli.Tests -c Release` from the root. diff --git a/src/FinalToken.Cli/CliApplication.cs b/src/FinalToken.Cli/CliApplication.cs index 797dc15..4915e6b 100644 --- a/src/FinalToken.Cli/CliApplication.cs +++ b/src/FinalToken.Cli/CliApplication.cs @@ -11,7 +11,7 @@ public static class CliApplication { if (args.Length == 0 || args[0] != "status" || args.Skip(1).Any(a => a is not ("--json" or "--no-probe")) || args.Skip(1).Distinct().Count() != args.Length - 1) - { await error.WriteLineAsync("Usage: finaltoken status [--json] [--no-probe]"); return 2; } + { await error.WriteLineAsync("Usage: finaltoken-cli status [--json] [--no-probe]"); return 2; } try { var directory = dataDirectory ?? DataPaths.DataDirectory; diff --git a/src/FinalToken.Cli/FinalToken.Cli.csproj b/src/FinalToken.Cli/FinalToken.Cli.csproj index 6b008f4..df2c537 100644 --- a/src/FinalToken.Cli/FinalToken.Cli.csproj +++ b/src/FinalToken.Cli/FinalToken.Cli.csproj @@ -1,7 +1,7 @@ Exe - finaltoken + finaltoken-cli true diff --git a/src/FinalToken.Core/AGENTS.md b/src/FinalToken.Core/AGENTS.md index c2402f9..daef42e 100644 --- a/src/FinalToken.Core/AGENTS.md +++ b/src/FinalToken.Core/AGENTS.md @@ -10,10 +10,14 @@ Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root `ActivationFile.RequestAsync` and exits; a busy CLI uses `SnapshotFile.Read`. - Construct `RefreshEngine`, subscribe to `SnapshotChanged`, `PopupRequested` and `ActivationRequested`, then `StartAsync`. `StopAsync` cancels and waits. Dispose asynchronously. + The desktop host passes `appPath: Environment.ProcessPath`. Other hosts omit it to keep the + previous snapshot's desktop path. A missing path stays null in readers and writers (D9). - Use `CurrentSnapshot`, `Settings`, `UpdateSettingsAsync`, `RefreshNowAsync` and `RecentDiagnostics`. `History` offers token series, model/project breakdowns and limit samples. - Snapshot provider totals use local today and Monday-based calendar week. Session totals use the reset and length of a known short limit. Hourly storage includes whole boundary hours (D5). + Day series use local calendar days, including DST. Tests can supply a zone to `TokenSeries`. + Use `CalendarDays.NextStart` for daily query ends; adding 24 hours is wrong on DST days. - `SnapshotFile.Read` returns a DTO, staleness and a metadata-only error. Serialize with `CoreJsonContext.Default.Snapshot`. `WindowSnapshot.Window` holds the limit; `.Pace` holds D7. - W3 owns `StreamDeck/`: `IPluginInstaller`, `PluginInstallStatus`, `InstallPolicy` and its stub. @@ -34,7 +38,6 @@ Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root session. Queries load only overlapping months and preserve their existing public signatures. - Claude imports and response keys have a 60-day horizon, twice the default 30-day cleanup. Keys expire daily; entries older than the horizon are ignored even after a key expires. - Legacy stores keep their recorded buckets and retain old keys for 60 days after migration. Codex replay protection uses the last session timestamp and cumulative counts, with no per-event dedupe keys. A later counter reset still permits subsequent increases. - Store changed percent/reset samples and at most one unchanged sample per window per hour. @@ -50,3 +53,8 @@ Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root use `File.Replace` for existing targets and retry Windows sharing failures for at most 500 ms. - Diagnostics fold by provider/code; `Count` is additive and `Time` is the latest occurrence. Synthetic Claude entries are silent. No message text appears in a diagnostic or journal. +- ProcessRunner redirects all three handles, closes non-interactive stdin and sets explicit + UTF-8 encodings. A WinExe's default console encoding corrupts UTF-8 provider JSON (D3, D6). + `tests/FinalToken.ProcessHost` reproduces the missing-console case without a provider login. +- Claude usage prose is silent. Diagnose only malformed `Current ...` lines before the + contributing section, where parsing stops. No legacy development-store migration is supported. diff --git a/src/FinalToken.Core/CalendarDays.cs b/src/FinalToken.Core/CalendarDays.cs new file mode 100644 index 0000000..82840bc --- /dev/null +++ b/src/FinalToken.Core/CalendarDays.cs @@ -0,0 +1,23 @@ +namespace FinalToken.Core; + +/// Local calendar boundaries, including 23/25-hour days. Midnight overlaps choose +/// the earlier instant; midnight gaps start at the first valid local minute. +public static class CalendarDays +{ + public static DateTimeOffset Start(DateTimeOffset instant, TimeZoneInfo? zone = null) + { + zone ??= TimeZoneInfo.Local; + return AtStart(TimeZoneInfo.ConvertTime(instant, zone).Date, zone); + } + public static DateTimeOffset NextStart(DateTimeOffset instant, TimeZoneInfo? zone = null) + { + zone ??= TimeZoneInfo.Local; + return AtStart(TimeZoneInfo.ConvertTime(instant, zone).Date.AddDays(1), zone); + } + private static DateTimeOffset AtStart(DateTime date, TimeZoneInfo zone) + { + while (zone.IsInvalidTime(date)) date = date.AddMinutes(1); + var offset = zone.IsAmbiguousTime(date) ? zone.GetAmbiguousTimeOffsets(date).Max() : zone.GetUtcOffset(date); + return new(date, offset); + } +} diff --git a/src/FinalToken.Core/Collectors/ClaudeUsageParser.cs b/src/FinalToken.Core/Collectors/ClaudeUsageParser.cs index beaade7..442d328 100644 --- a/src/FinalToken.Core/Collectors/ClaudeUsageParser.cs +++ b/src/FinalToken.Core/Collectors/ClaudeUsageParser.cs @@ -28,8 +28,8 @@ public static partial class ClaudeUsageParser foreach (var raw in text.Split('\n')) { var line = raw.Trim(); - if (line.Length == 0 || line == "You are currently using your subscription to power your Claude Code usage" || - line == "What's contributing to your limits usage?") continue; + if (line.StartsWith("What's contributing to your limits usage?", StringComparison.Ordinal)) break; + if (!line.StartsWith("Current ", StringComparison.Ordinal)) continue; var match = UsageLine().Match(line); if (!match.Success) { diagnostics.Add(Provider.Claude, "claude-usage-line", "Unknown usage line skipped."); continue; } diff --git a/src/FinalToken.Core/HistoryStore.cs b/src/FinalToken.Core/HistoryStore.cs index 0359d4f..b6d3b43 100644 --- a/src/FinalToken.Core/HistoryStore.cs +++ b/src/FinalToken.Core/HistoryStore.cs @@ -23,17 +23,6 @@ public sealed class ScanCursor public long LastWriteTicks { get; set; } } -// Retained for source compatibility and one-time migration of 14223b0 stores. -public sealed class HistoryData -{ - public int V { get; set; } = 1; - public List Buckets { get; set; } = []; - public List Limits { get; set; } = []; - public HashSet DedupeKeys { get; set; } = []; - public Dictionary CodexTotals { get; set; } = []; - public Dictionary Cursors { get; set; } = []; -} - /// UTC hourly storage; queries use [from,to), including whole boundary hours (D5). /// Data partitions load on demand with a three-month cache; journal replay is bounded by compaction. /// Claude imports and dedupe keys have a 60-day horizon, longer than the CLI's default 30-day cleanup. @@ -77,7 +66,6 @@ public sealed class HistoryStore months.Add(month); } journalBytes = HistoryJournal.Read(JournalPath, ApplyTransaction); - if (state.Sequence == 0 && File.Exists(Path.Combine(directory, "history.json"))) MigrateLegacy(); PruneKeys(); } catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException) @@ -223,13 +211,16 @@ public sealed class HistoryStore .OrderBy(w => w.SampleTime).ToArray(); } public IReadOnlyList TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval) + => TokenSeries(provider, from, to, interval, TimeZoneInfo.Local); + public IReadOnlyList TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval, + TimeZoneInfo? zone) { lock (gate) { Dictionary points = []; foreach (var bucket in Range(provider, from, to)) { - var key = interval == SeriesInterval.Hour ? bucket.Hour : new DateTimeOffset(bucket.Hour.UtcDateTime.Date, TimeSpan.Zero); + var key = interval == SeriesInterval.Hour ? bucket.Hour : CalendarDays.Start(bucket.Hour, zone); points[key] = points.GetValueOrDefault(key) + bucket.Counts; } return points.OrderBy(p => p.Key).Select(p => new TokenPoint(p.Key, p.Value)).ToArray(); @@ -378,38 +369,4 @@ public sealed class HistoryStore if (value.V != 1 || value.Sequence < 0 || value.ClaudeKeys is null || value.CodexTotals is null || value.CodexTimes is null || value.Cursors is null || value.LatestWindows is null || value.LastSamples is null) throw new JsonException(); } - private void MigrateLegacy() - { - var legacy = JsonSerializer.Deserialize(SharedFile.ReadAllText(Path.Combine(directory, "history.json")), - CoreJsonContext.Default.HistoryData) ?? throw new JsonException(); - if (legacy.V != 1 || legacy.Buckets is null || legacy.Limits is null || legacy.DedupeKeys is null || - legacy.CodexTotals is null || legacy.Cursors is null) throw new JsonException(); - foreach (var bucket in legacy.Buckets) PendingPartition(Month(bucket.Hour)).Buckets[BucketKey.For(bucket)] = bucket; - foreach (var group in legacy.Limits.OrderBy(w => w.SampleTime).GroupBy(w => (w.Provider, w.SampleTime))) AddLimits(group); - foreach (var key in legacy.DedupeKeys) - { - if (!key.StartsWith("codex:", StringComparison.Ordinal)) - state.ClaudeKeys[key] = pending.ClaudeKeys[key] = clock.GetUtcNow(); - else - { - var last = key.LastIndexOf(':'); - var timeStart = key.LastIndexOf(':', last - 1); - if (timeStart > 6 && long.TryParse(key.AsSpan(timeStart + 1, last - timeStart - 1), out var ticks)) - { - var session = key[6..timeStart]; - var time = new DateTimeOffset(ticks, TimeSpan.Zero); - if (time > state.CodexTimes.GetValueOrDefault(session)) - state.CodexTimes[session] = pending.CodexTimes[session] = time; - } - } - } - foreach (var (session, counts) in legacy.CodexTotals) state.CodexTotals[session] = pending.CodexTotals[session] = counts; - foreach (var (path, cursor) in legacy.Cursors) - { - state.Cursors[path] = cursor; - pending.Cursors[path] = CloneCursor(cursor); - } - cache.Clear(); - cacheOrder.Clear(); - } } diff --git a/src/FinalToken.Core/Processes/ProcessRunner.cs b/src/FinalToken.Core/Processes/ProcessRunner.cs index fbbfcef..eb2d619 100644 --- a/src/FinalToken.Core/Processes/ProcessRunner.cs +++ b/src/FinalToken.Core/Processes/ProcessRunner.cs @@ -24,10 +24,17 @@ public sealed class ProcessRunner(TimeProvider? timeProvider = null) : IProcessR { FileName = request.Command.FileName, WorkingDirectory = request.WorkingDirectory, UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, - RedirectStandardError = true, RedirectStandardInput = request.CodexRpc + RedirectStandardError = true, RedirectStandardInput = true, + // CLI JSON is UTF-8. A GUI host has no console code page; using its default + // encoding corrupts Unicode delimiters in Claude's local /usage result (D3). + StandardOutputEncoding = new UTF8Encoding(false), StandardErrorEncoding = new UTF8Encoding(false), + StandardInputEncoding = new UTF8Encoding(false) } }; foreach (var argument in request.Command.PrefixArguments.Concat(request.Arguments)) process.StartInfo.ArgumentList.Add(argument); process.Start(); + // D6: a WinExe host can have no standard input handle. Give every child a valid + // pipe; non-interactive probes get EOF, while app-server keeps its RPC input open. + if (!request.CodexRpc) process.StandardInput.Close(); var stderr = CaptureAsync(process.StandardError, request.OutputLimit, token); Task<(string Output, bool Truncated)>? stdout = null; try diff --git a/src/FinalToken.Core/RefreshEngine.cs b/src/FinalToken.Core/RefreshEngine.cs index 1657dd2..6fdbbf6 100644 --- a/src/FinalToken.Core/RefreshEngine.cs +++ b/src/FinalToken.Core/RefreshEngine.cs @@ -12,6 +12,7 @@ public sealed class RefreshEngine : IAsyncDisposable private readonly SemaphoreSlim lifecycleGate = new(1, 1); private readonly string directory; private readonly TimeProvider clock; + private readonly string? appPath; private readonly IncrementalScanner scanner; private readonly LimitProbe probe; private readonly Func discover; @@ -30,7 +31,7 @@ public sealed class RefreshEngine : IAsyncDisposable public RefreshEngine(string? dataDirectory = null, TimeProvider? timeProvider = null, IProcessRunner? processRunner = null, string? claudeDirectory = null, string? codexDirectory = null, - Func? cliDiscovery = null) + Func? cliDiscovery = null, string? appPath = null) { directory = dataDirectory ?? DataPaths.DataDirectory; Directory.CreateDirectory(directory); @@ -44,6 +45,7 @@ public sealed class RefreshEngine : IAsyncDisposable probe = new(processRunner ?? new ProcessRunner(clock), Diagnostics, directory); discover = cliDiscovery ?? ((provider, path) => CliDiscovery.Find(provider, path)); current = SnapshotFile.Read(directory, clock.GetUtcNow()).Snapshot; + this.appPath = appPath ?? current?.AppPath; activation = ActivationFile.ReadRequest(directory); } public string DataDirectory => directory; @@ -203,7 +205,8 @@ public sealed class RefreshEngine : IAsyncDisposable if (state.Status == ProviderStatus.Available && popups.Observe(window.Window, window.Pace, config) is { } alert) alerts.Add(alert); } - var snapshot = new Snapshot { MadeAt = clock.GetUtcNow(), RefreshInterval = config.RefreshInterval, Providers = providers }; + var snapshot = new Snapshot { MadeAt = clock.GetUtcNow(), RefreshInterval = config.RefreshInterval, + Providers = providers, AppPath = appPath }; await History.SaveAsync(token); await SnapshotFile.WriteAsync(directory, snapshot, token); Volatile.Write(ref current, snapshot); diff --git a/src/FinalToken.Core/Snapshot.cs b/src/FinalToken.Core/Snapshot.cs index 91f132a..093e147 100644 --- a/src/FinalToken.Core/Snapshot.cs +++ b/src/FinalToken.Core/Snapshot.cs @@ -14,7 +14,7 @@ public sealed record Snapshot public int V { get; init; } = 1; public required DateTimeOffset MadeAt { get; init; } public required TimeSpan RefreshInterval { get; init; } - public string? AppPath { get; init; } = Environment.ProcessPath; + public string? AppPath { get; init; } public required IReadOnlyList Providers { get; init; } } public sealed record SnapshotReadResult(Snapshot? Snapshot, bool IsStale, string? Error); @@ -42,7 +42,6 @@ public static class SnapshotFile [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, WriteIndented = false)] [JsonSerializable(typeof(Snapshot))] [JsonSerializable(typeof(Settings))] -[JsonSerializable(typeof(HistoryData))] [JsonSerializable(typeof(HistoryState))] [JsonSerializable(typeof(HistoryPartition))] [JsonSerializable(typeof(HistoryTransaction))] diff --git a/src/FinalToken.StreamDeck/README.md b/src/FinalToken.StreamDeck/README.md index 667451e..3fc564c 100644 --- a/src/FinalToken.StreamDeck/README.md +++ b/src/FinalToken.StreamDeck/README.md @@ -30,6 +30,6 @@ Deployment stages in a sibling folder, swaps with a backup and rolls back on fai The interface and install policy remain compatible with the original Core contract. `python -B tools/publish.py win-x64` builds the app, CLI and plugin into one folder and ZIP. -The Windows CLI is named `finaltoken-cli.exe` to avoid colliding with `FinalToken.exe`. -Use `--skip-app` while the desktop project is being replaced. Publish a Linux RID on Linux; +The CLI is named `finaltoken-cli` on every platform (`finaltoken-cli.exe` on Windows), +beside the desktop app. Publish a Linux RID on Linux; the .NET NativeAOT toolchain does not support cross-OS compilation. diff --git a/tests/FinalToken.App.Tests/HeadlessTests.cs b/tests/FinalToken.App.Tests/HeadlessTests.cs index c26dd6a..4de1027 100644 --- a/tests/FinalToken.App.Tests/HeadlessTests.cs +++ b/tests/FinalToken.App.Tests/HeadlessTests.cs @@ -32,6 +32,7 @@ public sealed class HeadlessTests var panel = new PanelWindow(model, () => { }, () => { }, () => { }, () => { }) { Height = 2450 }; panel.RequestedThemeVariant = ThemeVariant.Light; panel.Show(); Save(panel, "panel-light.png"); Assert.Contains(panel.GetVisualDescendants().OfType(), t => t.Text == "Claude"); + Assert.Contains(panel.GetVisualDescendants().OfType(), t => t.Text == "Tokens per day"); var filters = panel.GetVisualDescendants().OfType().ToArray(); filters[0].SelectedIndex = 4; filters[1].SelectedIndex = 2; Assert.Equal(HistoryRange.All, model.Range); Assert.Equal(Provider.Codex, model.ProviderFilter); diff --git a/tests/FinalToken.Cli.Tests/CliTests.cs b/tests/FinalToken.Cli.Tests/CliTests.cs index 4ce23e8..1d4ef61 100644 --- a/tests/FinalToken.Cli.Tests/CliTests.cs +++ b/tests/FinalToken.Cli.Tests/CliTests.cs @@ -16,7 +16,7 @@ public class CliTests using var output = new StringWriter(); using var error = new StringWriter(); Assert.Equal(2, await CliApplication.RunAsync(command.Split(' ', StringSplitOptions.RemoveEmptyEntries), output, error, cancellationToken: TestContext.Current.CancellationToken)); - Assert.Contains("Usage:", error.ToString()); + Assert.Contains("Usage: finaltoken-cli status", error.ToString()); } [Fact] public async Task BusyStoreReadsExistingSnapshotAndDoesNotRefresh() @@ -88,4 +88,22 @@ public class CliTests } finally { Directory.Delete(directory, true); } } + [Fact] + public async Task StatusKeepsExistingDesktopPath() + { + var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + try + { + await SnapshotFile.WriteAsync(directory, new Snapshot { MadeAt = DateTimeOffset.UtcNow, + RefreshInterval = TimeSpan.FromMinutes(1), Providers = [], AppPath = "desktop.exe" }, TestContext.Current.CancellationToken); + using var output = new StringWriter(); + using var error = new StringWriter(); + Assert.Equal(0, await CliApplication.RunAsync(["status", "--no-probe"], output, error, directory, + path => new(path, claudeDirectory: path, codexDirectory: path, cliDiscovery: (_, _) => new(null, "Fixture CLI missing.")), + TestContext.Current.CancellationToken)); + Assert.Equal("desktop.exe", SnapshotFile.Read(directory).Snapshot!.AppPath); + } + finally { Directory.Delete(directory, true); } + } } diff --git a/tests/FinalToken.Core.Tests/FinalToken.Core.Tests.csproj b/tests/FinalToken.Core.Tests/FinalToken.Core.Tests.csproj index f60fcd2..986ed05 100644 --- a/tests/FinalToken.Core.Tests/FinalToken.Core.Tests.csproj +++ b/tests/FinalToken.Core.Tests/FinalToken.Core.Tests.csproj @@ -8,5 +8,12 @@ + + + + + + + diff --git a/tests/FinalToken.Core.Tests/IntegrationTests.cs b/tests/FinalToken.Core.Tests/IntegrationTests.cs new file mode 100644 index 0000000..1b0015b --- /dev/null +++ b/tests/FinalToken.Core.Tests/IntegrationTests.cs @@ -0,0 +1,121 @@ +using System.Diagnostics; +using System.Text.Json; +using FinalToken.Core.Collectors; +using Xunit; + +namespace FinalToken.Core.Tests; + +public class IntegrationTests +{ + [Fact] + public async Task GuiHostProbeReceivesValidStandardHandlesWithoutConsole() + => await RunGuiProbe("--handles-probe"); + [Fact] + public async Task GuiHostDecodesUtf8ProviderJsonWithoutConsoleCodePage() + => await RunGuiProbe("--utf8-probe"); + private static async Task RunGuiProbe(string mode) + { + if (!OperatingSystem.IsWindows()) return; + using var directory = new TestDirectory(); + var reportPath = Path.Combine(directory.Path, "report.json"); + using var process = new Process { StartInfo = new() + { + FileName = Path.Combine(AppContext.BaseDirectory, "ProcessHost", "FinalToken.ProcessHost.exe"), + UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = directory.Path + } }; + process.StartInfo.ArgumentList.Add(mode); + process.StartInfo.ArgumentList.Add(reportPath); + process.Start(); + try + { + await process.WaitForExitAsync(TestContext.Current.CancellationToken); + using var report = JsonDocument.Parse(File.ReadAllText(reportPath)); + Assert.False(report.RootElement.GetProperty("HostHasConsole").GetBoolean()); + Assert.False(report.RootElement.GetProperty("HostInputValid").GetBoolean()); + Assert.Equal(0, process.ExitCode); + } + finally { if (!process.HasExited) process.Kill(true); } + } + [Fact] + public void UsageProseAndContributingSectionAreSilent() + { + const string text = """ + You are currently using your subscription to power your Claude Code usage + + Current session: 4% used · resets Oct 14, 11:30pm (Europe/Berlin) + Current week (all models): 67% used · resets Oct 18, 8pm (Europe/Berlin) + Current week (Fable): 0% used · resets Oct 18, 8pm (Europe/Berlin) + + What's contributing to your limits usage? + Usage across Claude Code and Claude contributes to your limits. + Sessions and conversations share your subscription allowance. + Learn more about how usage is calculated. + Current example: this prose is not a limit window + """; + var log = new DiagnosticLog(); + Assert.Equal(3, ClaudeUsageParser.ParseText(text, new(2026, 10, 14, 18, 0, 0, TimeSpan.Zero), log).Count); + Assert.Empty(log.Recent); + } + [Fact] + public async Task MissingSnapshotAppPathDoesNotDefaultToReadersExecutable() + { + using var directory = new TestDirectory(); + directory.Write("snapshot.json", """{"v":1,"madeAt":"2026-10-14T16:00:00Z","refreshInterval":"00:01:00","providers":[]}"""); + Assert.Null(SnapshotFile.Read(directory.Path).Snapshot!.AppPath); + await using var engine = new RefreshEngine(directory.Path, claudeDirectory: directory.Path, codexDirectory: directory.Path, + cliDiscovery: (_, _) => new(null, "Fixture CLI missing.")); + Assert.Null((await engine.RefreshNowAsync(true, TestContext.Current.CancellationToken)).AppPath); + } + [Fact] + public async Task UnspecifiedHostAppPathPreservesExistingDesktopPath() + { + using var directory = new TestDirectory(); + await SnapshotFile.WriteAsync(directory.Path, new Snapshot { AppPath = "desktop.exe", MadeAt = DateTimeOffset.UtcNow, + RefreshInterval = TimeSpan.FromMinutes(1), Providers = [] }, TestContext.Current.CancellationToken); + await using var engine = new RefreshEngine(directory.Path, claudeDirectory: directory.Path, codexDirectory: directory.Path, + cliDiscovery: (_, _) => new(null, "Fixture CLI missing.")); + Assert.Equal("desktop.exe", (await engine.RefreshNowAsync(true, TestContext.Current.CancellationToken)).AppPath); + } + [Fact] + public void DaysFollowLocalCalendarInsteadOfUtcMidnight() + { + using var directory = new TestDirectory(); + var store = new HistoryStore(directory.Path, new()); + var first = new DateTimeOffset(2026, 10, 14, 23, 0, 0, TimeSpan.Zero); + store.Add(new(Provider.Codex, first, "model", "project", new(Total: 10), "one")); + store.Add(new(Provider.Codex, first.AddHours(1), "model", "project", new(Total: 20), "two")); + var zone = TimeZoneInfo.CreateCustomTimeZone("Fixture +02", TimeSpan.FromHours(2), "Fixture", "Fixture"); + var day = Assert.Single(store.TokenSeries(Provider.Codex, first, first.AddHours(2), SeriesInterval.Day, zone)); + Assert.Equal(30, day.Counts.Total); + Assert.Equal(new DateTimeOffset(2026, 10, 15, 0, 0, 0, TimeSpan.FromHours(2)), day.Time); + } + [Theory] + [InlineData("2026-03-29", 23)] + [InlineData("2026-10-25", 25)] + public void LocalDaySeriesIncludesEveryHourAcrossDst(string localDate, int hours) + { + using var directory = new TestDirectory(); + var store = new HistoryStore(directory.Path, new()); + var zone = TimeZoneInfo.FindSystemTimeZoneById("Europe/Berlin"); + var date = DateTime.ParseExact(localDate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); + var start = new DateTimeOffset(date, zone.GetUtcOffset(date)); + var end = CalendarDays.NextStart(start, zone); + Assert.Equal(TimeSpan.FromHours(hours), end - start); + for (var i = 0; i < hours; i++) + store.Add(new(Provider.Codex, start.AddHours(i), "model", "project", new(Total: 1), "hour-" + i)); + var day = Assert.Single(store.TokenSeries(Provider.Codex, start, end, SeriesInterval.Day, zone)); + Assert.Equal(hours, day.Counts.Total); + Assert.Equal(start, day.Time); + Assert.Equal(hours, store.TokenSeries(Provider.Codex, start, end, SeriesInterval.Hour, zone).Count); + } + [Fact] + public async Task ExplicitDesktopPathOverridesPriorSnapshotPath() + { + using var directory = new TestDirectory(); + await SnapshotFile.WriteAsync(directory.Path, new Snapshot { AppPath = "old.exe", MadeAt = DateTimeOffset.UtcNow, + RefreshInterval = TimeSpan.FromMinutes(1), Providers = [] }, TestContext.Current.CancellationToken); + await using var engine = new RefreshEngine(directory.Path, claudeDirectory: directory.Path, codexDirectory: directory.Path, + cliDiscovery: (_, _) => new(null, "Fixture CLI missing."), appPath: "desktop.exe"); + Assert.Equal("desktop.exe", (await engine.RefreshNowAsync(true, TestContext.Current.CancellationToken)).AppPath); + } +} diff --git a/tests/FinalToken.Core.Tests/ParserTests.cs b/tests/FinalToken.Core.Tests/ParserTests.cs index fc6190d..a657563 100644 --- a/tests/FinalToken.Core.Tests/ParserTests.cs +++ b/tests/FinalToken.Core.Tests/ParserTests.cs @@ -51,7 +51,7 @@ public class ParserTests [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")] + [InlineData("Current session: unknown format")] public void ClaudeUnknownFormatsBecomeDiagnostics(string line) { var diagnostics = new DiagnosticLog(); diff --git a/tests/FinalToken.Core.Tests/ReworkTests.cs b/tests/FinalToken.Core.Tests/ReworkTests.cs index e5840ba..bdc0a00 100644 --- a/tests/FinalToken.Core.Tests/ReworkTests.cs +++ b/tests/FinalToken.Core.Tests/ReworkTests.cs @@ -190,30 +190,6 @@ public class ReworkTests Assert.Equal(now.AddMinutes(5), Assert.Single(store.LatestLimits(Provider.Claude)).SampleTime); } [Fact] - public async Task LegacyMigrationPreservesTotalsAndDedupeWithoutCodexEventKeys() - { - using var directory = new TestDirectory(); - var now = DateTimeOffset.UtcNow; - var usage = TranscriptParser.Parse(Fixtures.Claude(time: now.ToString("O")), new())!; - var hour = new DateTimeOffset(now.UtcTicks - now.UtcTicks % TimeSpan.TicksPerHour, TimeSpan.Zero); - var legacy = new HistoryData - { - Buckets = [new(Provider.Claude, hour, usage.Model, usage.Project, usage.Counts)], - DedupeKeys = [usage.DedupeKey, $"codex:session-1:{now.UtcTicks}:12"], - CodexTotals = new() { ["session-1"] = new(Input: 10, Output: 2, Total: 12) } - }; - directory.Write("history.json", System.Text.Json.JsonSerializer.Serialize(legacy, CoreJsonContext.Default.HistoryData)); - var store = new HistoryStore(directory.Path, new()); - Assert.False(store.Add(usage)); - Assert.Equal(19, store.Total(Provider.Claude, now.AddHours(-1), now.AddHours(1)).Total); - await store.CompactAsync(TestContext.Current.CancellationToken); - store = new(directory.Path, new()); - Assert.False(store.Add(usage)); - var stateJson = File.ReadAllText(Path.Combine(directory.Path, "history.state.json")); - Assert.DoesNotContain("codex:session-1:", stateJson); - Assert.Contains("\"codexTotals\":{\"session-1\":", stateJson); - } - [Fact] public async Task SharingViolationRetriesUntilReaderReleasesItsHandle() { if (!OperatingSystem.IsWindows()) return; diff --git a/tests/FinalToken.Core.Tests/StorageTests.cs b/tests/FinalToken.Core.Tests/StorageTests.cs index 72f761e..2fc4a5f 100644 --- a/tests/FinalToken.Core.Tests/StorageTests.cs +++ b/tests/FinalToken.Core.Tests/StorageTests.cs @@ -142,7 +142,7 @@ public class StorageTests 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.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); @@ -151,7 +151,7 @@ public class StorageTests public void CorruptHistoryIsNotSilentlyOverwritten() { using var directory = new TestDirectory(); - var path = directory.Write("history.json", "{"); + var path = directory.Write("history.state.json", "{"); Assert.Throws(() => new HistoryStore(directory.Path, new())); Assert.Equal("{", File.ReadAllText(path)); } diff --git a/tests/FinalToken.ProcessHost/AGENTS.md b/tests/FinalToken.ProcessHost/AGENTS.md new file mode 100644 index 0000000..1afe49a --- /dev/null +++ b/tests/FinalToken.ProcessHost/AGENTS.md @@ -0,0 +1,6 @@ +# Process probe host +Windows GUI-subsystem regression helper for D6. It deliberately has no console or standard +handles, then runs Core's ProcessRunner. Child modes check handles and synthetic UTF-8 JSON. The optional +live Claude mode keeps provider output in memory and writes only diagnostic metadata. +No provider text or real transcript fixtures belong here. JSON uses source generation. +Built with Core tests; run `dotnet test --project tests/FinalToken.Core.Tests -c Release`. diff --git a/tests/FinalToken.ProcessHost/CLAUDE.md b/tests/FinalToken.ProcessHost/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/tests/FinalToken.ProcessHost/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/tests/FinalToken.ProcessHost/FinalToken.ProcessHost.csproj b/tests/FinalToken.ProcessHost/FinalToken.ProcessHost.csproj new file mode 100644 index 0000000..6c4d14d --- /dev/null +++ b/tests/FinalToken.ProcessHost/FinalToken.ProcessHost.csproj @@ -0,0 +1,7 @@ + + + WinExe + true + + + diff --git a/tests/FinalToken.ProcessHost/Program.cs b/tests/FinalToken.ProcessHost/Program.cs new file mode 100644 index 0000000..746cc19 --- /dev/null +++ b/tests/FinalToken.ProcessHost/Program.cs @@ -0,0 +1,76 @@ +using System.Runtime.InteropServices; +using System.Text.Json; +using System.Text.Json.Serialization; +using FinalToken.Core; +using FinalToken.Core.Collectors; +using FinalToken.Core.Processes; + +namespace FinalToken.ProcessHost; + +public static class Program +{ + public static async Task Main(string[] args) + { + if (!OperatingSystem.IsWindows()) return 0; + if (args is ["--handles"]) + return new[] { -10, -11, -12 }.All(id => Native.GetFileType(Native.GetStdHandle(id)) != 0) ? 0 : 17; + if (args is ["--utf8"]) + { + await Console.OpenStandardOutput().WriteAsync(System.Text.Encoding.UTF8.GetBytes("{\"marker\":\"· •\"}")); + return 0; + } + if (args.Length < 2) return 2; + Native.FreeConsole(); + foreach (var id in new[] { -10, -11, -12 }) Native.SetStdHandle(id, 0); + var report = new ProbeReport { HostHasConsole = Native.GetConsoleWindow() != 0, + HostInputValid = Native.GetFileType(Native.GetStdHandle(-10)) != 0, OutputCodePage = Console.OutputEncoding.CodePage }; + var live = args[0] == "--claude"; + var utf8 = args[0] == "--utf8-probe"; + var cli = live ? CliDiscovery.Find(Provider.Claude).Command : new CliCommand(Environment.ProcessPath!, []); + if (cli is null) return 3; + var result = await new ProcessRunner().RunAsync(new(cli, live + ? ["-p", "/usage", "--output-format", "json", "--no-session-persistence"] : utf8 ? ["--utf8"] : ["--handles"], + Path.GetDirectoryName(Path.GetFullPath(args[1]))!, TimeSpan.FromSeconds(60)), CancellationToken.None); + report = report with { ExitCode = result.ExitCode, TimedOut = result.TimedOut, + Utf8Matched = utf8 && result.Output == "{\"marker\":\"· •\"}" }; + if (live) + { + var diagnostics = new DiagnosticLog(); + var windows = ClaudeUsageParser.ParseEnvelope(result.Output, DateTimeOffset.UtcNow, diagnostics); + report = report with { WindowCount = windows.Count, DiagnosticCodes = diagnostics.Recent.Select(d => d.Code).ToArray() }; + } + await AtomicFile.WriteAsync(args[1], JsonSerializer.Serialize(report, ProbeJsonContext.Default.ProbeReport)); + return live ? report.WindowCount > 0 ? 0 : 18 : utf8 ? report.Utf8Matched ? 0 : 19 : result.ExitCode; + } +} + +public sealed record ProbeReport +{ + public bool HostHasConsole { get; init; } + public bool HostInputValid { get; init; } + public int ExitCode { get; init; } + public bool TimedOut { get; init; } + public int WindowCount { get; init; } + public int OutputCodePage { get; init; } + public bool Utf8Matched { get; init; } + public string[] DiagnosticCodes { get; init; } = []; +} + +[JsonSerializable(typeof(ProbeReport))] +internal partial class ProbeJsonContext : JsonSerializerContext; + +internal static partial class Native +{ + [LibraryImport("kernel32.dll")] + internal static partial nint GetStdHandle(int id); + [LibraryImport("kernel32.dll")] + internal static partial uint GetFileType(nint handle); + [LibraryImport("kernel32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool SetStdHandle(int id, nint handle); + [LibraryImport("kernel32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool FreeConsole(); + [LibraryImport("kernel32.dll")] + internal static partial nint GetConsoleWindow(); +} diff --git a/tools/publish.py b/tools/publish.py index 81ab5d0..03817e7 100755 --- a/tools/publish.py +++ b/tools/publish.py @@ -34,10 +34,7 @@ def main(): for file in stage.iterdir(): if file.suffix in ['.pdb', '.dbg']: continue - # Windows paths ignore case: FinalToken.exe (app) and finaltoken.exe (CLI) - # cannot share a folder. Keep the desktop activation path stable. - filename = 'finaltoken-cli.exe' if name == 'Cli' and file.name == 'finaltoken.exe' else file.name - target = destination / filename + target = destination / file.name if target.exists(): if file.is_file() and target.is_file() and file.read_bytes() == target.read_bytes(): continue