Files
FinalToken/tests/FinalToken.ProcessHost/Program.cs
T
Florian Schmidt fd30dfcea4
agent-review agent review: pass
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
2026-10-14 21:50:09 +02:00

105 lines
5.2 KiB
C#

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<int> 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;
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;
}
private static async Task<int> 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
{
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();
}