fix: probe Claude from the GUI app and close integration gaps

- A GUI-subsystem host has no console code page, so .NET decoded the
  probes' UTF-8 output with code page 0 and Claude's /usage separators
  never matched: Claude showed as unavailable in the app but not in the
  CLI. Probe output is now decoded as UTF-8 and every probe gets valid
  standard handles, with stdin closed unless it is the Codex RPC. A
  GUI-subsystem test host reproduces it.
- The /usage parser stops at the contributing section and only reports
  lines that start like a limit line.
- snapshot.json no longer defaults appPath to the reader's own path. The
  app passes its path to the engine and a CLI refresh keeps it, so a
  Stream Deck key always starts the app (D9, D10).
- The CLI is finaltoken-cli on every platform: FinalToken.exe and
  finaltoken.exe cannot share a folder on Windows.
- Day series follow the local calendar day, as Today does.
- The dev-only migration from the first store format is gone.
- README.md is a short user guide.

Refs #1
This commit is contained in:
Florian Schmidt
2026-10-14 20:39:53 +02:00
parent 183247bab5
commit 50ac2aad3a
30 changed files with 364 additions and 95 deletions
@@ -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<TextBlock>(), t => t.Text == "Claude");
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Tokens per day");
var filters = panel.GetVisualDescendants().OfType<ComboBox>().ToArray();
filters[0].SelectedIndex = 4; filters[1].SelectedIndex = 2;
Assert.Equal(HistoryRange.All, model.Range); Assert.Equal(Provider.Codex, model.ProviderFilter);
+19 -1
View File
@@ -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); }
}
}
@@ -8,5 +8,12 @@
<ItemGroup>
<PackageReference Include="xunit.v3.aot.mtp-v2" />
<ProjectReference Include="../../src/FinalToken.Core/FinalToken.Core.csproj" />
<ProjectReference Include="../FinalToken.ProcessHost/FinalToken.ProcessHost.csproj" ReferenceOutputAssembly="false" />
</ItemGroup>
<Target Name="CopyProcessHost" AfterTargets="Build">
<ItemGroup>
<ProcessHostFiles Include="$(MSBuildThisFileDirectory)../../artifacts/bin/FinalToken.ProcessHost/$(Configuration)/$(TargetFramework)/*" />
</ItemGroup>
<Copy SourceFiles="@(ProcessHostFiles)" DestinationFolder="$(OutDir)ProcessHost" SkipUnchangedFiles="true" />
</Target>
</Project>
@@ -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);
}
}
+1 -1
View File
@@ -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();
@@ -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;
+2 -2
View File
@@ -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<InvalidDataException>(() => new HistoryStore(directory.Path, new()));
Assert.Equal("{", File.ReadAllText(path));
}
+6
View File
@@ -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`.
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
@@ -0,0 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup><ProjectReference Include="../../src/FinalToken.Core/FinalToken.Core.csproj" /></ItemGroup>
</Project>
+76
View File
@@ -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<int> 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();
}