From fd30dfcea4e525bf77f6790ddd05da04c31df8a2 Mon Sep 17 00:00:00 2001 From: Florian Schmidt Date: Wed, 14 Oct 2026 21:50:09 +0200 Subject: [PATCH] fix: address the first agent review of PR #2 Blocking findings: 1. A Codex RPC error or early exit threw past LimitProbe and stopped the refresh loop, so Claude stopped updating too (D2). Every probe failure is now a failed probe result, the loop records an unexpected tick failure and keeps ticking, shutdown cancellation still propagates, the app reports failed operations, and the CLI exits 1 instead of crashing. Fake app-server modes in the GUI process host test errors, EOF and garbage. 2. Totals converted local midnight directly and threw where midnight does not exist (Cairo, Santiago, Beirut). Today and the week start through CalendarDays now. 3. Daily chart labels used UTC dates for local-day buckets; labels and tooltips now share the local date. Review notes fixed as well: Claude Code installed with npm on Windows is found through its native binary or cli.js; the plugin ends cleanly on a bad host frame; Linux autostart honours XDG_CONFIG_HOME; the unused stub installer and the worker names in docs are gone. Refs #1 --- src/FinalToken.App/Charts.cs | 9 +- src/FinalToken.App/DesktopApp.cs | 7 +- src/FinalToken.App/OsStartup.cs | 5 +- src/FinalToken.App/PanelViewModel.cs | 6 + src/FinalToken.Cli/CliApplication.cs | 2 +- src/FinalToken.Core/AGENTS.md | 4 +- src/FinalToken.Core/CalendarDays.cs | 3 + src/FinalToken.Core/Collectors/LimitProbe.cs | 8 +- src/FinalToken.Core/HistoryStore.cs | 4 +- src/FinalToken.Core/Processes/CliDiscovery.cs | 9 ++ src/FinalToken.Core/RefreshEngine.cs | 6 +- src/FinalToken.Core/StreamDeck/Installer.cs | 8 - src/FinalToken.StreamDeck/Program.cs | 6 +- src/FinalToken.StreamDeck/Protocol.cs | 6 + tests/FinalToken.App.Tests/AGENTS.md | 4 +- tests/FinalToken.App.Tests/FormattingTests.cs | 18 +++ tests/FinalToken.App.Tests/HeadlessTests.cs | 11 +- tests/FinalToken.Cli.Tests/CliTests.cs | 13 ++ .../DiscoveryAndPolicyTests.cs | 16 ++ .../ReviewRegressionTests.cs | 141 ++++++++++++++++++ tests/FinalToken.ProcessHost/AGENTS.md | 2 + tests/FinalToken.ProcessHost/Program.cs | 28 ++++ .../PluginTests.cs | 12 +- 23 files changed, 296 insertions(+), 32 deletions(-) create mode 100644 tests/FinalToken.Core.Tests/ReviewRegressionTests.cs diff --git a/src/FinalToken.App/Charts.cs b/src/FinalToken.App/Charts.cs index c9d8a3f..dc6d9e2 100644 --- a/src/FinalToken.App/Charts.cs +++ b/src/FinalToken.App/Charts.cs @@ -68,7 +68,7 @@ public sealed class UsageChart : Control context.DrawLine(new Pen(Palette[2], 1, new DashStyle([4, 3], 0)), Position(p, pe), Position(value, expected)); } context.DrawEllipse(Palette[0], null, point, 3, 3); - hits.Add((new(point.X - 8, point.Y - 10, 16, 20), $"{value.Time.LocalDateTime:g} · {value.Value:0.##}% · expected {(value.Expected is { } e ? $"{e:0.##}%" : "unknown")}")); + hits.Add((new(point.X - 8, point.Y - 10, 16, 20), $"{Display.ChartTimestamp(value.Time, Interval)} · {value.Value:0.##}% · expected {(value.Expected is { } e ? $"{e:0.##}%" : "unknown")}")); previous = value; } } @@ -85,14 +85,13 @@ public sealed class UsageChart : Control var x = plot.Left + (groups[i].Key - groups[0].Key).TotalSeconds / duration * plot.Width; var rect = new Rect(x + Math.Min(1, width / 8), bottom - height, Math.Max(0.5, width - Math.Min(2, width / 4)), height); context.DrawRectangle(Palette[Array.IndexOf(series, value.Series) % Palette.Length], null, rect); - hits.Add((rect, $"{value.Time.LocalDateTime:g} · {value.Series}: {value.Value:N0} tokens")); + hits.Add((rect, $"{Display.ChartTimestamp(value.Time, Interval)} · {value.Series}: {value.Value:N0} tokens")); bottom -= height; } } } - string DateLabel(DateTimeOffset time) => Interval >= TimeSpan.FromDays(1) ? time.UtcDateTime.ToString("MM-dd") : time.LocalDateTime.ToString("MM-dd HH:mm"); - Text(context, DateLabel(groups[0].Key), new(plot.Left, plot.Bottom + 8), ink); - Text(context, DateLabel(groups[^1].Key), new(Math.Max(plot.Left, plot.Right - 110), plot.Bottom + 8), ink); + Text(context, Display.ChartDateLabel(groups[0].Key, Interval), new(plot.Left, plot.Bottom + 8), ink); + Text(context, Display.ChartDateLabel(groups[^1].Key, Interval), new(Math.Max(plot.Left, plot.Right - 110), plot.Bottom + 8), ink); ToolTip.SetShowDelay(this, 0); } private static void Text(DrawingContext context, string text, Point point, IBrush brush) => context.DrawText( diff --git a/src/FinalToken.App/DesktopApp.cs b/src/FinalToken.App/DesktopApp.cs index d782198..26a30e1 100644 --- a/src/FinalToken.App/DesktopApp.cs +++ b/src/FinalToken.App/DesktopApp.cs @@ -178,7 +178,10 @@ public sealed class DesktopApp : Application { try { await work(); } catch (OperationCanceledException) { } - catch (Exception e) when (e is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException) - { model.Message = "Operation failed: " + e.Message; } + catch (Exception) + { + engine?.Diagnostics.Add(null, "host-operation", "A desktop operation failed."); + model.Message = "Operation failed. See diagnostics."; + } } } diff --git a/src/FinalToken.App/OsStartup.cs b/src/FinalToken.App/OsStartup.cs index 64617fe..7ed2f6e 100644 --- a/src/FinalToken.App/OsStartup.cs +++ b/src/FinalToken.App/OsStartup.cs @@ -6,12 +6,15 @@ namespace FinalToken.App; public static class OsStartup { + public static string LinuxAutostartPath(string? configHome, string userHome) + => Path.Combine(string.IsNullOrEmpty(configHome) ? Path.Combine(userHome, ".config") : configHome, "autostart", "finaltoken.desktop"); public static async Task ApplyAsync(bool enabled, string? executable = null) { executable ??= Environment.ProcessPath ?? throw new InvalidOperationException("Executable path is unavailable."); if (OperatingSystem.IsWindows()) { ApplyWindows(enabled, executable); return; } if (!OperatingSystem.IsLinux()) return; - var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".config", "autostart", "finaltoken.desktop"); + var path = LinuxAutostartPath(Environment.GetEnvironmentVariable("XDG_CONFIG_HOME"), + Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); if (!enabled) { if (File.Exists(path)) File.Delete(path); return; } await AtomicFile.WriteAsync(path, DesktopEntry(executable)); } diff --git a/src/FinalToken.App/PanelViewModel.cs b/src/FinalToken.App/PanelViewModel.cs index a0cca1b..78bb63c 100644 --- a/src/FinalToken.App/PanelViewModel.cs +++ b/src/FinalToken.App/PanelViewModel.cs @@ -66,6 +66,12 @@ public partial class PanelViewModel : ObservableObject public static class Display { + public static string ChartDateLabel(DateTimeOffset time, TimeSpan interval) + => ChartTime(time, interval).ToString(interval >= TimeSpan.FromDays(1) ? "MM-dd" : "MM-dd HH:mm"); + public static string ChartTimestamp(DateTimeOffset time, TimeSpan interval) + => ChartTime(time, interval).ToString("g"); + private static DateTime ChartTime(DateTimeOffset time, TimeSpan interval) + => interval >= TimeSpan.FromDays(1) ? time.DateTime : time.LocalDateTime; public static string Projection(DateTimeOffset projection, TimeProvider? clock = null, System.Globalization.CultureInfo? culture = null) { clock ??= TimeProvider.System; diff --git a/src/FinalToken.Cli/CliApplication.cs b/src/FinalToken.Cli/CliApplication.cs index 4915e6b..0b3f380 100644 --- a/src/FinalToken.Cli/CliApplication.cs +++ b/src/FinalToken.Cli/CliApplication.cs @@ -46,7 +46,7 @@ public static class CliApplication } return 0; } - catch (Exception e) when (e is IOException or UnauthorizedAccessException or OperationCanceledException) + catch (Exception) { await error.WriteLineAsync("FinalToken could not complete the refresh or read the snapshot."); return 1; } } } diff --git a/src/FinalToken.Core/AGENTS.md b/src/FinalToken.Core/AGENTS.md index 929b58f..11efa66 100644 --- a/src/FinalToken.Core/AGENTS.md +++ b/src/FinalToken.Core/AGENTS.md @@ -14,6 +14,8 @@ Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root `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). +- Probes return a failed `ProbeResult` for process or protocol failures; shutdown cancellation + propagates. The background engine records other tick failures and retries without faulting its loop. - 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 @@ -22,7 +24,7 @@ Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root 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. +- `StreamDeck/` contains `IPluginInstaller`, `PluginInstallStatus`, `InstallPolicy` and platform deployment. No shipped production dependency is needed in Core. Source parsers use temporary memory for one complete line; memory usage therefore scales with the largest transcript entry. diff --git a/src/FinalToken.Core/CalendarDays.cs b/src/FinalToken.Core/CalendarDays.cs index 82840bc..0e1dd93 100644 --- a/src/FinalToken.Core/CalendarDays.cs +++ b/src/FinalToken.Core/CalendarDays.cs @@ -4,6 +4,9 @@ namespace FinalToken.Core; /// the earlier instant; midnight gaps start at the first valid local minute. public static class CalendarDays { + /// Start of a specified local calendar date; midnight gaps and overlaps follow the same policy as Start(instant). + public static DateTimeOffset Start(DateTime date, TimeZoneInfo? zone = null) + => AtStart(DateTime.SpecifyKind(date.Date, DateTimeKind.Unspecified), zone ?? TimeZoneInfo.Local); public static DateTimeOffset Start(DateTimeOffset instant, TimeZoneInfo? zone = null) { zone ??= TimeZoneInfo.Local; diff --git a/src/FinalToken.Core/Collectors/LimitProbe.cs b/src/FinalToken.Core/Collectors/LimitProbe.cs index 8f9a19d..208373c 100644 --- a/src/FinalToken.Core/Collectors/LimitProbe.cs +++ b/src/FinalToken.Core/Collectors/LimitProbe.cs @@ -24,7 +24,11 @@ public sealed class LimitProbe(IProcessRunner runner, DiagnosticLog diagnostics, diagnostics.Add(provider, "probe-no-limits", "No usable limit windows returned; CLI may be logged out."); return new(false, [], "No usable limits returned; CLI may be logged out."); } - catch (Exception e) when (e is IOException or UnauthorizedAccessException or System.ComponentModel.Win32Exception or InvalidOperationException) - { diagnostics.Add(provider, "probe-start", "CLI probe could not run."); return new(false, [], "CLI probe could not run."); } + catch (Exception) when (cancellationToken.IsCancellationRequested) + { throw new OperationCanceledException(cancellationToken); } + // D2: a provider's process/protocol failure must not interrupt the other provider. + // Exception messages can contain child output; expose only fixed metadata. + catch (Exception) + { diagnostics.Add(provider, "probe-failed", "CLI probe could not complete."); return new(false, [], "CLI probe could not complete."); } } } diff --git a/src/FinalToken.Core/HistoryStore.cs b/src/FinalToken.Core/HistoryStore.cs index b6d3b43..3247a4f 100644 --- a/src/FinalToken.Core/HistoryStore.cs +++ b/src/FinalToken.Core/HistoryStore.cs @@ -242,8 +242,8 @@ public sealed class HistoryStore var local = TimeZoneInfo.ConvertTime(now, zone); var today = local.Date; var week = today.AddDays(-(((int)today.DayOfWeek + 6) % 7)); - var todayUtc = new DateTimeOffset(TimeZoneInfo.ConvertTimeToUtc(today, zone)); - var weekUtc = new DateTimeOffset(TimeZoneInfo.ConvertTimeToUtc(week, zone)); + var todayUtc = CalendarDays.Start(today, zone); + var weekUtc = CalendarDays.Start(week, zone); return (Total(provider, todayUtc, now), session is { ResetsAt: { } reset, Length: { } length } && reset > now ? Total(provider, reset - length, now) : null, Total(provider, weekUtc, now)); } diff --git a/src/FinalToken.Core/Processes/CliDiscovery.cs b/src/FinalToken.Core/Processes/CliDiscovery.cs index 024acc7..4393442 100644 --- a/src/FinalToken.Core/Processes/CliDiscovery.cs +++ b/src/FinalToken.Core/Processes/CliDiscovery.cs @@ -38,6 +38,15 @@ public static class CliDiscovery if (!File.Exists(path)) return new(null, "Configured CLI does not exist."); var directory = Path.GetDirectoryName(path)!; if (windows && Path.GetExtension(path).Equals(".exe", StringComparison.OrdinalIgnoreCase)) return new(new(path, []), null); + if (provider == Provider.Claude && windows) + { + var package = Path.Combine(directory, "node_modules", "@anthropic-ai", "claude-code"); + // Current npm installs copy the platform binary here; older releases use cli.js. + var binary = Path.Combine(package, "bin", "claude.exe"); + if (File.Exists(binary)) return new(new(binary, []), null); + var script = Path.Combine(package, "cli.js"); + if (File.Exists(script) && FindNode(directory, searchPath, true) is { } node) return new(new(node, [script]), null); + } if (provider == Provider.Codex) { var package = Path.Combine(directory, "node_modules", "@openai", "codex"); diff --git a/src/FinalToken.Core/RefreshEngine.cs b/src/FinalToken.Core/RefreshEngine.cs index 6fdbbf6..d932a9a 100644 --- a/src/FinalToken.Core/RefreshEngine.cs +++ b/src/FinalToken.Core/RefreshEngine.cs @@ -145,8 +145,10 @@ public sealed class RefreshEngine : IAsyncDisposable do { try { await TickAsync(token); } - catch (Exception e) when (e is IOException or UnauthorizedAccessException) - { Diagnostics.Add(null, "refresh-write", "Refresh could not persist files."); } + catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; } + // D6: isolate a failed tick, including a malformed stored partition, and retry. + catch (Exception) + { Diagnostics.Add(null, "refresh-failed", "Refresh failed; the scheduler will retry."); } } while (await timer.WaitForNextTickAsync(token)); } private async Task RefreshAsync(bool noProbe, CancellationToken token) diff --git a/src/FinalToken.Core/StreamDeck/Installer.cs b/src/FinalToken.Core/StreamDeck/Installer.cs index fba20ec..1949f17 100644 --- a/src/FinalToken.Core/StreamDeck/Installer.cs +++ b/src/FinalToken.Core/StreamDeck/Installer.cs @@ -7,14 +7,6 @@ public interface IPluginInstaller Task GetStatusAsync(CancellationToken cancellationToken = default); Task InstallOrUpdateAsync(CancellationToken cancellationToken = default); } -/// W3 replaces this with platform host detection and atomic plugin deployment (D11). -public sealed class StubPluginInstaller : IPluginInstaller -{ - public Task GetStatusAsync(CancellationToken cancellationToken = default) => - Task.FromResult(new PluginInstallStatus(PluginInstallState.NoHostFound)); - public Task InstallOrUpdateAsync(CancellationToken cancellationToken = default) => - Task.FromException(new InvalidOperationException("No Stream Deck host found.")); -} public enum InstallAction { Nothing, Ask, Install } public static class InstallPolicy { diff --git a/src/FinalToken.StreamDeck/Program.cs b/src/FinalToken.StreamDeck/Program.cs index 850a9d8..5ea3043 100644 --- a/src/FinalToken.StreamDeck/Program.cs +++ b/src/FinalToken.StreamDeck/Program.cs @@ -22,7 +22,7 @@ try do { updates.Writer.TryWrite(SnapshotFile.Read(DataPaths.DataDirectory)); } while (await timer.WaitForNextTickAsync(stop.Token)); }); - var incoming = transport.ReceiveAsync(stop.Token); + var incoming = session.ReceiveAsync(stop.Token); var update = updates.Reader.ReadAsync(stop.Token).AsTask(); try { @@ -34,7 +34,7 @@ try var json = await incoming; if (json is null) break; await session.HandleAsync(json, DateTimeOffset.UtcNow, stop.Token); - incoming = transport.ReceiveAsync(stop.Token); + incoming = session.ReceiveAsync(stop.Token); } else { @@ -51,7 +51,7 @@ try } if (socket.State == WebSocketState.CloseReceived) await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); - await RollingLog.WriteAsync("host-closed"); + await RollingLog.WriteAsync(session.ConnectionEndCode); return 0; } catch (Exception e) when (e is WebSocketException or IOException or OperationCanceledException or UnauthorizedAccessException) diff --git a/src/FinalToken.StreamDeck/Protocol.cs b/src/FinalToken.StreamDeck/Protocol.cs index 9e9dd33..7ec33f1 100644 --- a/src/FinalToken.StreamDeck/Protocol.cs +++ b/src/FinalToken.StreamDeck/Protocol.cs @@ -58,6 +58,12 @@ public sealed class PluginSocket(ClientWebSocket socket) : IPluginSocket public sealed class PluginSession(IPluginSocket socket, Func> launch) { + public string ConnectionEndCode { get; private set; } = "host-closed"; + public async Task ReceiveAsync(CancellationToken cancellationToken) + { + try { return await socket.ReceiveAsync(cancellationToken); } + catch (InvalidDataException) { ConnectionEndCode = "connection-ended"; return null; } + } public const string Action = "de.finalfactory.finaltoken.stat"; private readonly Dictionary keys = []; private readonly Dictionary images = []; diff --git a/tests/FinalToken.App.Tests/AGENTS.md b/tests/FinalToken.App.Tests/AGENTS.md index e35e03f..e89e9d4 100644 --- a/tests/FinalToken.App.Tests/AGENTS.md +++ b/tests/FinalToken.App.Tests/AGENTS.md @@ -2,6 +2,6 @@ Hand-written fixtures only. xUnit v3 AOT with Microsoft.Testing.Platform. Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root. View-model tests use public Core queries. Headless tests run on a dedicated UI thread with -Skia and HarfBuzz, exercise settings and popup actions, and save seven PNG screenshots outside -the repo at ../runs/shots/w2. FINALTOKEN_SCREENSHOT_DIR overrides that path. +Skia and HarfBuzz, exercise settings and popup actions, and save PNG screenshots outside +the repo at ../runs/shots/app. FINALTOKEN_SCREENSHOT_DIR overrides that path. Popup expiry uses an injected TimeProvider; fire timers and pump the dispatcher instead of sleeping. diff --git a/tests/FinalToken.App.Tests/FormattingTests.cs b/tests/FinalToken.App.Tests/FormattingTests.cs index 863e478..ac343fd 100644 --- a/tests/FinalToken.App.Tests/FormattingTests.cs +++ b/tests/FinalToken.App.Tests/FormattingTests.cs @@ -5,6 +5,24 @@ namespace FinalToken.App.Tests; public sealed class FormattingTests { + [Fact] + public void DailyChartLabelAndTooltipUseTheBucketsLocalDate() + { + var zone = TimeZoneInfo.CreateCustomTimeZone("Fixture+02", TimeSpan.FromHours(2), "Fixture", "Fixture"); + var day = FinalToken.Core.CalendarDays.Start(new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero), zone); + Assert.Equal("10-14", Display.ChartDateLabel(day, TimeSpan.FromDays(1))); + Assert.Equal(day.DateTime.ToString("g"), Display.ChartTimestamp(day, TimeSpan.FromDays(1))); + } + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("custom-config")] + public void LinuxAutostartHonorsConfigHome(string? configHome) + { + var home = Path.Combine(Path.GetTempPath(), "fixture-home"); + var config = string.IsNullOrEmpty(configHome) ? null : Path.Combine(Path.GetTempPath(), configHome); + Assert.Equal(Path.Combine(config ?? Path.Combine(home, ".config"), "autostart", "finaltoken.desktop"), OsStartup.LinuxAutostartPath(config, home)); + } [Theory] [InlineData("de-DE")] [InlineData("en-US")] diff --git a/tests/FinalToken.App.Tests/HeadlessTests.cs b/tests/FinalToken.App.Tests/HeadlessTests.cs index becd9d7..cf5de2f 100644 --- a/tests/FinalToken.App.Tests/HeadlessTests.cs +++ b/tests/FinalToken.App.Tests/HeadlessTests.cs @@ -26,7 +26,7 @@ public sealed class HeadlessTests AppBuilder.Configure().UseSkia().UseHarfBuzz().UseHeadless(new() { UseHeadlessDrawing = false }).SetupWithoutStarting(); var root = new DirectoryInfo(AppContext.BaseDirectory); while (root.Parent is not null && !File.Exists(Path.Combine(root.FullName, "FinalToken.slnx"))) root = root.Parent; - var shots = Environment.GetEnvironmentVariable("FINALTOKEN_SCREENSHOT_DIR") ?? Path.Combine(root.Parent!.FullName, "runs", "shots", "w2"); + var shots = Environment.GetEnvironmentVariable("FINALTOKEN_SCREENSHOT_DIR") ?? Path.Combine(root.Parent!.FullName, "runs", "shots", "app"); Directory.CreateDirectory(shots); var model = FakeData.Model(); var panel = new PanelWindow(model, () => { }, () => { }, () => { }, () => { }) { Height = 2450 }; @@ -86,7 +86,7 @@ public sealed class HeadlessTests using (chartWindow.CaptureRenderedFrame()) { } chartWindow.MouseMove(new Point(65, 80)); Assert.Contains(123456.ToString("N0"), ToolTip.GetTip(chart)?.ToString()); chartWindow.Close(); - var polishShots = Path.Combine(root.Parent!.FullName, "runs", "shots", "w1"); + var polishShots = shots; Directory.CreateDirectory(polishShots); var emptyChart = new Window { Content = Ui.Card(Ui.Stack(Ui.Text("Tokens per hour", 19), new UsageChart())), Width = 620, Height = 260, RequestedThemeVariant = ThemeVariant.Light }; @@ -96,6 +96,13 @@ public sealed class HeadlessTests { Values = [new(time, "Claude", 1), new(time.AddHours(1), "Claude", 2), new(time.AddHours(2), "Claude", 3)] })), Width = 620, Height = 260, RequestedThemeVariant = ThemeVariant.Light }; smallChart.Show(); Save(smallChart, "chart-max-3.png", polishShots); smallChart.Close(); + var day = new DateTimeOffset(2026, 10, 14, 0, 0, 0, TimeSpan.FromHours(2)); + var daily = new UsageChart { Interval = TimeSpan.FromDays(1), Values = [new(day, "Claude", 3), new(day.AddDays(1), "Claude", 2)] }; + var dailyWindow = new Window { Content = Ui.Card(Ui.Stack(Ui.Text("Tokens per day", 19), daily)), + Width = 620, Height = 260, RequestedThemeVariant = ThemeVariant.Light }; + dailyWindow.Show(); Save(dailyWindow, "chart-local-day.png"); + dailyWindow.MouseMove(new Point(90, 150)); + Assert.Contains(day.DateTime.ToString("g"), ToolTip.GetTip(daily)?.ToString()); dailyWindow.Close(); popupClock.Fire(); Dispatcher.UIThread.RunJobs(); Assert.False(first.IsVisible); Assert.False(second.IsVisible); Assert.All(popupClock.Timers, timer => Assert.True(timer.Disposed)); diff --git a/tests/FinalToken.Cli.Tests/CliTests.cs b/tests/FinalToken.Cli.Tests/CliTests.cs index 1d4ef61..e6e641a 100644 --- a/tests/FinalToken.Cli.Tests/CliTests.cs +++ b/tests/FinalToken.Cli.Tests/CliTests.cs @@ -6,6 +6,19 @@ namespace FinalToken.Cli.Tests; public class CliTests { + [Fact] + public async Task UnexpectedRefreshFailureReturnsOneWithoutExceptionText() + { + var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N")); + try + { + using var output = new StringWriter(); using var error = new StringWriter(); + Assert.Equal(1, await CliApplication.RunAsync(["status"], output, error, directory, + _ => throw new System.Text.Json.JsonException("synthetic private input"), TestContext.Current.CancellationToken)); + Assert.Contains("could not complete", error.ToString()); Assert.DoesNotContain("synthetic private", error.ToString()); + } + finally { if (Directory.Exists(directory)) Directory.Delete(directory, true); } + } [Theory] [InlineData("")] [InlineData("unknown")] diff --git a/tests/FinalToken.Core.Tests/DiscoveryAndPolicyTests.cs b/tests/FinalToken.Core.Tests/DiscoveryAndPolicyTests.cs index 4ecce82..16e16c0 100644 --- a/tests/FinalToken.Core.Tests/DiscoveryAndPolicyTests.cs +++ b/tests/FinalToken.Core.Tests/DiscoveryAndPolicyTests.cs @@ -6,6 +6,22 @@ namespace FinalToken.Core.Tests; public class DiscoveryAndPolicyTests { + [Fact] + public void WindowsClaudeNpmShimResolvesInstalledNativeBinary() + { + using var directory = new TestDirectory(); directory.Write("claude.cmd", "fixture"); + var binary = directory.Write("node_modules/@anthropic-ai/claude-code/bin/claude.exe", "fixture native"); + Assert.Equal(binary, CliDiscovery.Find(Provider.Claude, searchPath: directory.Path, windows: true).Command?.FileName); + } + [Fact] + public void WindowsClaudeNpmShimFallsBackToLegacyCliScriptWithoutShell() + { + using var directory = new TestDirectory(); directory.Write("claude.cmd", "fixture"); + var script = directory.Write("node_modules/@anthropic-ai/claude-code/cli.js", "fixture script"); + var node = directory.Write("node.exe", "fixture node"); + var command = CliDiscovery.Find(Provider.Claude, searchPath: directory.Path, windows: true).Command; + Assert.NotNull(command); Assert.Equal(node, command.FileName); Assert.Equal([script], command.PrefixArguments); + } [Fact] public void FindsNativeWindowsAndHonorsOverride() { diff --git a/tests/FinalToken.Core.Tests/ReviewRegressionTests.cs b/tests/FinalToken.Core.Tests/ReviewRegressionTests.cs new file mode 100644 index 0000000..b87fab2 --- /dev/null +++ b/tests/FinalToken.Core.Tests/ReviewRegressionTests.cs @@ -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(); 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(); + 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(token) }; + await Assert.ThrowsAnyAsync(() => 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(() => 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); + } +} diff --git a/tests/FinalToken.ProcessHost/AGENTS.md b/tests/FinalToken.ProcessHost/AGENTS.md index 1afe49a..9247569 100644 --- a/tests/FinalToken.ProcessHost/AGENTS.md +++ b/tests/FinalToken.ProcessHost/AGENTS.md @@ -4,3 +4,5 @@ handles, then runs Core's ProcessRunner. Child modes check handles and synthetic 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`. +Portable `--rpc-*` modes provide synthetic app-server exchanges, errors, EOF and malformed output. +The `app-server` mode returns an RPC error for published-CLI checks; it never contacts a provider. diff --git a/tests/FinalToken.ProcessHost/Program.cs b/tests/FinalToken.ProcessHost/Program.cs index 746cc19..43de577 100644 --- a/tests/FinalToken.ProcessHost/Program.cs +++ b/tests/FinalToken.ProcessHost/Program.cs @@ -11,6 +11,8 @@ public static class Program { public static async Task Main(string[] args) { + if (args.FirstOrDefault() is { } mode && (mode.StartsWith("--rpc-", StringComparison.Ordinal) || mode == "app-server")) + return await RpcAsync(mode == "app-server" ? "--rpc-error" : mode); if (!OperatingSystem.IsWindows()) return 0; if (args is ["--handles"]) return new[] { -10, -11, -12 }.All(id => Native.GetFileType(Native.GetStdHandle(id)) != 0) ? 0 : 17; @@ -42,6 +44,32 @@ public static class Program 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; } + private static async Task RpcAsync(string mode) + { + Console.InputEncoding = System.Text.Encoding.UTF8; + Console.OutputEncoding = new System.Text.UTF8Encoding(false); + if (mode == "--rpc-eof") return 0; + var initialize = await Console.In.ReadLineAsync(); + using var first = JsonDocument.Parse(initialize ?? "null"); + if (first.RootElement.GetProperty("method").GetString() != "initialize") return 20; + if (mode == "--rpc-init-error") { await Console.Out.WriteLineAsync("{\"id\":1,\"error\":{\"code\":-1,\"message\":\"synthetic error\"}}"); return 0; } + await Console.Out.WriteLineAsync("{\"id\":1,\"result\":{}}"); + using var initialized = JsonDocument.Parse(await Console.In.ReadLineAsync() ?? "null"); + using var request = JsonDocument.Parse(await Console.In.ReadLineAsync() ?? "null"); + if (initialized.RootElement.GetProperty("method").GetString() != "initialized" || + request.RootElement.GetProperty("method").GetString() != "account/rateLimits/read") return 21; + await Console.Out.WriteLineAsync("{\"method\":\"syntheticNotification\"}"); + var response = mode switch + { + "--rpc-error" => "{\"id\":2,\"error\":{\"code\":-1,\"message\":\"synthetic error\"}}", + "--rpc-garbage" => "not JSON", + "--rpc-shape" => "[]", + "--rpc-bound" => new string('x', 1024 * 1024 + 1), + _ => "{\"id\":2,\"result\":{\"rateLimits\":{\"limitId\":\"codex\",\"primary\":{\"usedPercent\":24,\"windowDurationMins\":10080,\"resetsAt\":1792479531}}}}" + }; + await Console.Out.WriteLineAsync(response); + return 0; + } } public sealed record ProbeReport diff --git a/tests/FinalToken.StreamDeck.Tests/PluginTests.cs b/tests/FinalToken.StreamDeck.Tests/PluginTests.cs index bd2ac2d..d6bfd2e 100644 --- a/tests/FinalToken.StreamDeck.Tests/PluginTests.cs +++ b/tests/FinalToken.StreamDeck.Tests/PluginTests.cs @@ -7,6 +7,14 @@ namespace FinalToken.StreamDeck.Tests; public sealed class PluginTests { + [Fact] + public async Task InvalidHostFrameEndsConnectionWithoutLoggingFrameText() + { + var socket = new FakeSocket { ReceiveFailure = new InvalidDataException("synthetic private frame") }; + var session = new PluginSession(socket, _ => Task.FromResult(false)); + Assert.Null(await session.ReceiveAsync(TestContext.Current.CancellationToken)); + Assert.Equal("connection-ended", session.ConnectionEndCode); + } [Theory] [InlineData("{}", "Claude", "SessionPercent", "")] [InlineData("{\"provider\":\"Codex\"}", "Codex", "SessionPercent", "")] @@ -146,9 +154,11 @@ public sealed class PluginTests } private sealed class FakeSocket : IPluginSocket { + public Exception? ReceiveFailure { get; init; } public List Sent { get; } = []; public Task SendAsync(string json, CancellationToken cancellationToken) { Sent.Add(json); return Task.CompletedTask; } - public Task ReceiveAsync(CancellationToken cancellationToken) => Task.FromResult(null); + public Task ReceiveAsync(CancellationToken cancellationToken) => ReceiveFailure is { } error + ? Task.FromException(error) : Task.FromResult(null); } }