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:
@@ -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.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.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) |
|
| `src/FinalToken.StreamDeck` | Stream Deck plugin executable and its `.sdPlugin` assets (D10) |
|
||||||
| `tests/*` | One test project per tested project, named `<Project>.Tests` |
|
| `tests/*` | One test project per tested project, named `<Project>.Tests` |
|
||||||
| `tools/` | Repository tools, listed under [Tools](#tools) |
|
| `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/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
|
- `tools/agent-review.sh`: posts an agent review and sets the `agent-review` status; see
|
||||||
`docs/agents/review.md`.
|
`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
|
## Writing
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
<Project Path="src/FinalToken.StreamDeck/FinalToken.StreamDeck.csproj" />
|
<Project Path="src/FinalToken.StreamDeck/FinalToken.StreamDeck.csproj" />
|
||||||
</Folder>
|
</Folder>
|
||||||
<Folder Name="/tests/">
|
<Folder Name="/tests/">
|
||||||
|
<Project Path="tests/FinalToken.ProcessHost/FinalToken.ProcessHost.csproj" />
|
||||||
<Project Path="tests/FinalToken.Core.Tests/FinalToken.Core.Tests.csproj" />
|
<Project Path="tests/FinalToken.Core.Tests/FinalToken.Core.Tests.csproj" />
|
||||||
<Project Path="tests/FinalToken.Cli.Tests/FinalToken.Cli.Tests.csproj" />
|
<Project Path="tests/FinalToken.Cli.Tests/FinalToken.Cli.Tests.csproj" />
|
||||||
<Project Path="tests/FinalToken.App.Tests/FinalToken.App.Tests.csproj" />
|
<Project Path="tests/FinalToken.App.Tests/FinalToken.App.Tests.csproj" />
|
||||||
|
|||||||
@@ -1,2 +1,57 @@
|
|||||||
# FinalToken
|
# 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.
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,9 @@
|
|||||||
Avalonia 12 Fluent host (D8). Views are built in C# without reflection bindings. View-model
|
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.
|
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 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).
|
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).
|
Stream Deck policy and the real installer come through IPluginInstaller (D11).
|
||||||
UsePlatformDetect selects X11 on Linux in the pinned Avalonia version. Keep XWayland support.
|
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.
|
Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root.
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ public partial class PanelViewModel : ObservableObject
|
|||||||
: ModelsAtPoint(p.Provider, point.Time, interval))).ToArray();
|
: ModelsAtPoint(p.Provider, point.Time, interval))).ToArray();
|
||||||
IEnumerable<ChartValue> ModelsAtPoint(Provider provider, DateTimeOffset time, SeriesInterval interval)
|
IEnumerable<ChartValue> 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)
|
return store.ByModel(provider, time < from ? from : time, end > now ? now : end)
|
||||||
.Select(m => new ChartValue(time, m.Name ?? "Unknown model", m.Counts.Total));
|
.Select(m => new ChartValue(time, m.Name ?? "Unknown model", m.Counts.Total));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ public sealed class PanelWindow : Window
|
|||||||
}
|
}
|
||||||
var h = model.History;
|
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 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)
|
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(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));
|
body.Children.Add(Breakdown("By model", h.Models));
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ public static class Program
|
|||||||
if (OperatingSystem.IsWindows()) WindowsActivation.AllowRunningInstance();
|
if (OperatingSystem.IsWindows()) WindowsActivation.AllowRunningInstance();
|
||||||
ActivationFile.RequestAsync(directory).GetAwaiter().GetResult(); return 0;
|
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; }
|
catch (InvalidDataException e) { StartupError = e.Message; }
|
||||||
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
|
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
|
||||||
return StartupError is null ? 0 : 1;
|
return StartupError is null ? 0 : 1;
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
# CLI
|
# CLI
|
||||||
NativeAOT console host for D1, D5, D6 and D9. Exit codes: success 0, failure 1, usage 2.
|
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.
|
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.
|
Run `dotnet test --project tests/FinalToken.Cli.Tests -c Release` from the root.
|
||||||
|
|||||||
@@ -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")) ||
|
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)
|
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
|
try
|
||||||
{
|
{
|
||||||
var directory = dataDirectory ?? DataPaths.DataDirectory;
|
var directory = dataDirectory ?? DataPaths.DataDirectory;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<OutputType>Exe</OutputType>
|
<OutputType>Exe</OutputType>
|
||||||
<AssemblyName>finaltoken</AssemblyName>
|
<AssemblyName>finaltoken-cli</AssemblyName>
|
||||||
<PublishAot>true</PublishAot>
|
<PublishAot>true</PublishAot>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
<ItemGroup><ProjectReference Include="../FinalToken.Core/FinalToken.Core.csproj" /></ItemGroup>
|
<ItemGroup><ProjectReference Include="../FinalToken.Core/FinalToken.Core.csproj" /></ItemGroup>
|
||||||
|
|||||||
@@ -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`.
|
`ActivationFile.RequestAsync` and exits; a busy CLI uses `SnapshotFile.Read`.
|
||||||
- Construct `RefreshEngine`, subscribe to `SnapshotChanged`, `PopupRequested` and
|
- Construct `RefreshEngine`, subscribe to `SnapshotChanged`, `PopupRequested` and
|
||||||
`ActivationRequested`, then `StartAsync`. `StopAsync` cancels and waits. Dispose asynchronously.
|
`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
|
- Use `CurrentSnapshot`, `Settings`, `UpdateSettingsAsync`, `RefreshNowAsync` and
|
||||||
`RecentDiagnostics`. `History` offers token series, model/project breakdowns and limit samples.
|
`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
|
- 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).
|
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
|
- `SnapshotFile.Read` returns a DTO, staleness and a metadata-only error. Serialize with
|
||||||
`CoreJsonContext.Default.Snapshot`. `WindowSnapshot.Window` holds the limit; `.Pace` holds D7.
|
`CoreJsonContext.Default.Snapshot`. `WindowSnapshot.Window` holds the limit; `.Pace` holds D7.
|
||||||
- W3 owns `StreamDeck/`: `IPluginInstaller`, `PluginInstallStatus`, `InstallPolicy` and its stub.
|
- 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.
|
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.
|
- 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.
|
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
|
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.
|
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.
|
- 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.
|
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.
|
- 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.
|
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.
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
namespace FinalToken.Core;
|
||||||
|
|
||||||
|
/// <summary>Local calendar boundaries, including 23/25-hour days. Midnight overlaps choose
|
||||||
|
/// the earlier instant; midnight gaps start at the first valid local minute.</summary>
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -28,8 +28,8 @@ public static partial class ClaudeUsageParser
|
|||||||
foreach (var raw in text.Split('\n'))
|
foreach (var raw in text.Split('\n'))
|
||||||
{
|
{
|
||||||
var line = raw.Trim();
|
var line = raw.Trim();
|
||||||
if (line.Length == 0 || line == "You are currently using your subscription to power your Claude Code usage" ||
|
if (line.StartsWith("What's contributing to your limits usage?", StringComparison.Ordinal)) break;
|
||||||
line == "What's contributing to your limits usage?") continue;
|
if (!line.StartsWith("Current ", StringComparison.Ordinal)) continue;
|
||||||
var match = UsageLine().Match(line);
|
var match = UsageLine().Match(line);
|
||||||
if (!match.Success)
|
if (!match.Success)
|
||||||
{ diagnostics.Add(Provider.Claude, "claude-usage-line", "Unknown usage line skipped."); continue; }
|
{ diagnostics.Add(Provider.Claude, "claude-usage-line", "Unknown usage line skipped."); continue; }
|
||||||
|
|||||||
@@ -23,17 +23,6 @@ public sealed class ScanCursor
|
|||||||
public long LastWriteTicks { get; set; }
|
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<TokenBucket> Buckets { get; set; } = [];
|
|
||||||
public List<LimitWindow> Limits { get; set; } = [];
|
|
||||||
public HashSet<string> DedupeKeys { get; set; } = [];
|
|
||||||
public Dictionary<string, TokenCounts> CodexTotals { get; set; } = [];
|
|
||||||
public Dictionary<string, ScanCursor> Cursors { get; set; } = [];
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>UTC hourly storage; queries use [from,to), including whole boundary hours (D5).
|
/// <summary>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.
|
/// 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.
|
/// 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);
|
months.Add(month);
|
||||||
}
|
}
|
||||||
journalBytes = HistoryJournal.Read(JournalPath, ApplyTransaction);
|
journalBytes = HistoryJournal.Read(JournalPath, ApplyTransaction);
|
||||||
if (state.Sequence == 0 && File.Exists(Path.Combine(directory, "history.json"))) MigrateLegacy();
|
|
||||||
PruneKeys();
|
PruneKeys();
|
||||||
}
|
}
|
||||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException)
|
catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException)
|
||||||
@@ -223,13 +211,16 @@ public sealed class HistoryStore
|
|||||||
.OrderBy(w => w.SampleTime).ToArray();
|
.OrderBy(w => w.SampleTime).ToArray();
|
||||||
}
|
}
|
||||||
public IReadOnlyList<TokenPoint> TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval)
|
public IReadOnlyList<TokenPoint> TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval)
|
||||||
|
=> TokenSeries(provider, from, to, interval, TimeZoneInfo.Local);
|
||||||
|
public IReadOnlyList<TokenPoint> TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval,
|
||||||
|
TimeZoneInfo? zone)
|
||||||
{
|
{
|
||||||
lock (gate)
|
lock (gate)
|
||||||
{
|
{
|
||||||
Dictionary<DateTimeOffset, TokenCounts> points = [];
|
Dictionary<DateTimeOffset, TokenCounts> points = [];
|
||||||
foreach (var bucket in Range(provider, from, to))
|
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;
|
points[key] = points.GetValueOrDefault(key) + bucket.Counts;
|
||||||
}
|
}
|
||||||
return points.OrderBy(p => p.Key).Select(p => new TokenPoint(p.Key, p.Value)).ToArray();
|
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 ||
|
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();
|
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();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,10 +24,17 @@ public sealed class ProcessRunner(TimeProvider? timeProvider = null) : IProcessR
|
|||||||
{
|
{
|
||||||
FileName = request.Command.FileName, WorkingDirectory = request.WorkingDirectory,
|
FileName = request.Command.FileName, WorkingDirectory = request.WorkingDirectory,
|
||||||
UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true,
|
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);
|
foreach (var argument in request.Command.PrefixArguments.Concat(request.Arguments)) process.StartInfo.ArgumentList.Add(argument);
|
||||||
process.Start();
|
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);
|
var stderr = CaptureAsync(process.StandardError, request.OutputLimit, token);
|
||||||
Task<(string Output, bool Truncated)>? stdout = null;
|
Task<(string Output, bool Truncated)>? stdout = null;
|
||||||
try
|
try
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ public sealed class RefreshEngine : IAsyncDisposable
|
|||||||
private readonly SemaphoreSlim lifecycleGate = new(1, 1);
|
private readonly SemaphoreSlim lifecycleGate = new(1, 1);
|
||||||
private readonly string directory;
|
private readonly string directory;
|
||||||
private readonly TimeProvider clock;
|
private readonly TimeProvider clock;
|
||||||
|
private readonly string? appPath;
|
||||||
private readonly IncrementalScanner scanner;
|
private readonly IncrementalScanner scanner;
|
||||||
private readonly LimitProbe probe;
|
private readonly LimitProbe probe;
|
||||||
private readonly Func<Provider, string?, CliDiscoveryResult> discover;
|
private readonly Func<Provider, string?, CliDiscoveryResult> discover;
|
||||||
@@ -30,7 +31,7 @@ public sealed class RefreshEngine : IAsyncDisposable
|
|||||||
|
|
||||||
public RefreshEngine(string? dataDirectory = null, TimeProvider? timeProvider = null, IProcessRunner? processRunner = null,
|
public RefreshEngine(string? dataDirectory = null, TimeProvider? timeProvider = null, IProcessRunner? processRunner = null,
|
||||||
string? claudeDirectory = null, string? codexDirectory = null,
|
string? claudeDirectory = null, string? codexDirectory = null,
|
||||||
Func<Provider, string?, CliDiscoveryResult>? cliDiscovery = null)
|
Func<Provider, string?, CliDiscoveryResult>? cliDiscovery = null, string? appPath = null)
|
||||||
{
|
{
|
||||||
directory = dataDirectory ?? DataPaths.DataDirectory;
|
directory = dataDirectory ?? DataPaths.DataDirectory;
|
||||||
Directory.CreateDirectory(directory);
|
Directory.CreateDirectory(directory);
|
||||||
@@ -44,6 +45,7 @@ public sealed class RefreshEngine : IAsyncDisposable
|
|||||||
probe = new(processRunner ?? new ProcessRunner(clock), Diagnostics, directory);
|
probe = new(processRunner ?? new ProcessRunner(clock), Diagnostics, directory);
|
||||||
discover = cliDiscovery ?? ((provider, path) => CliDiscovery.Find(provider, path));
|
discover = cliDiscovery ?? ((provider, path) => CliDiscovery.Find(provider, path));
|
||||||
current = SnapshotFile.Read(directory, clock.GetUtcNow()).Snapshot;
|
current = SnapshotFile.Read(directory, clock.GetUtcNow()).Snapshot;
|
||||||
|
this.appPath = appPath ?? current?.AppPath;
|
||||||
activation = ActivationFile.ReadRequest(directory);
|
activation = ActivationFile.ReadRequest(directory);
|
||||||
}
|
}
|
||||||
public string DataDirectory => 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)
|
if (state.Status == ProviderStatus.Available && popups.Observe(window.Window, window.Pace, config) is { } alert)
|
||||||
alerts.Add(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 History.SaveAsync(token);
|
||||||
await SnapshotFile.WriteAsync(directory, snapshot, token);
|
await SnapshotFile.WriteAsync(directory, snapshot, token);
|
||||||
Volatile.Write(ref current, snapshot);
|
Volatile.Write(ref current, snapshot);
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ public sealed record Snapshot
|
|||||||
public int V { get; init; } = 1;
|
public int V { get; init; } = 1;
|
||||||
public required DateTimeOffset MadeAt { get; init; }
|
public required DateTimeOffset MadeAt { get; init; }
|
||||||
public required TimeSpan RefreshInterval { get; init; }
|
public required TimeSpan RefreshInterval { get; init; }
|
||||||
public string? AppPath { get; init; } = Environment.ProcessPath;
|
public string? AppPath { get; init; }
|
||||||
public required IReadOnlyList<ProviderSnapshot> Providers { get; init; }
|
public required IReadOnlyList<ProviderSnapshot> Providers { get; init; }
|
||||||
}
|
}
|
||||||
public sealed record SnapshotReadResult(Snapshot? Snapshot, bool IsStale, string? Error);
|
public sealed record SnapshotReadResult(Snapshot? Snapshot, bool IsStale, string? Error);
|
||||||
@@ -42,7 +42,6 @@ public static class SnapshotFile
|
|||||||
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, WriteIndented = false)]
|
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, WriteIndented = false)]
|
||||||
[JsonSerializable(typeof(Snapshot))]
|
[JsonSerializable(typeof(Snapshot))]
|
||||||
[JsonSerializable(typeof(Settings))]
|
[JsonSerializable(typeof(Settings))]
|
||||||
[JsonSerializable(typeof(HistoryData))]
|
|
||||||
[JsonSerializable(typeof(HistoryState))]
|
[JsonSerializable(typeof(HistoryState))]
|
||||||
[JsonSerializable(typeof(HistoryPartition))]
|
[JsonSerializable(typeof(HistoryPartition))]
|
||||||
[JsonSerializable(typeof(HistoryTransaction))]
|
[JsonSerializable(typeof(HistoryTransaction))]
|
||||||
|
|||||||
@@ -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.
|
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.
|
`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`.
|
The CLI is named `finaltoken-cli` on every platform (`finaltoken-cli.exe` on Windows),
|
||||||
Use `--skip-app` while the desktop project is being replaced. Publish a Linux RID on Linux;
|
beside the desktop app. Publish a Linux RID on Linux;
|
||||||
the .NET NativeAOT toolchain does not support cross-OS compilation.
|
the .NET NativeAOT toolchain does not support cross-OS compilation.
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ public sealed class HeadlessTests
|
|||||||
var panel = new PanelWindow(model, () => { }, () => { }, () => { }, () => { }) { Height = 2450 };
|
var panel = new PanelWindow(model, () => { }, () => { }, () => { }, () => { }) { Height = 2450 };
|
||||||
panel.RequestedThemeVariant = ThemeVariant.Light; panel.Show(); Save(panel, "panel-light.png");
|
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 == "Claude");
|
||||||
|
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Tokens per day");
|
||||||
var filters = panel.GetVisualDescendants().OfType<ComboBox>().ToArray();
|
var filters = panel.GetVisualDescendants().OfType<ComboBox>().ToArray();
|
||||||
filters[0].SelectedIndex = 4; filters[1].SelectedIndex = 2;
|
filters[0].SelectedIndex = 4; filters[1].SelectedIndex = 2;
|
||||||
Assert.Equal(HistoryRange.All, model.Range); Assert.Equal(Provider.Codex, model.ProviderFilter);
|
Assert.Equal(HistoryRange.All, model.Range); Assert.Equal(Provider.Codex, model.ProviderFilter);
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ public class CliTests
|
|||||||
using var output = new StringWriter();
|
using var output = new StringWriter();
|
||||||
using var error = new StringWriter();
|
using var error = new StringWriter();
|
||||||
Assert.Equal(2, await CliApplication.RunAsync(command.Split(' ', StringSplitOptions.RemoveEmptyEntries), output, error, cancellationToken: TestContext.Current.CancellationToken));
|
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]
|
[Fact]
|
||||||
public async Task BusyStoreReadsExistingSnapshotAndDoesNotRefresh()
|
public async Task BusyStoreReadsExistingSnapshotAndDoesNotRefresh()
|
||||||
@@ -88,4 +88,22 @@ public class CliTests
|
|||||||
}
|
}
|
||||||
finally { Directory.Delete(directory, true); }
|
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>
|
<ItemGroup>
|
||||||
<PackageReference Include="xunit.v3.aot.mtp-v2" />
|
<PackageReference Include="xunit.v3.aot.mtp-v2" />
|
||||||
<ProjectReference Include="../../src/FinalToken.Core/FinalToken.Core.csproj" />
|
<ProjectReference Include="../../src/FinalToken.Core/FinalToken.Core.csproj" />
|
||||||
|
<ProjectReference Include="../FinalToken.ProcessHost/FinalToken.ProcessHost.csproj" ReferenceOutputAssembly="false" />
|
||||||
</ItemGroup>
|
</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>
|
</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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 14, 7:30pm (Unknown/Zone)")]
|
||||||
[InlineData("Current session: 10% used · resets Oct 18, 8pm (Europe/Berlin)")]
|
[InlineData("Current session: 10% used · resets Oct 18, 8pm (Europe/Berlin)")]
|
||||||
[InlineData("Current session: 10% used · resets Oct 14, 3pm (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)
|
public void ClaudeUnknownFormatsBecomeDiagnostics(string line)
|
||||||
{
|
{
|
||||||
var diagnostics = new DiagnosticLog();
|
var diagnostics = new DiagnosticLog();
|
||||||
|
|||||||
@@ -190,30 +190,6 @@ public class ReworkTests
|
|||||||
Assert.Equal(now.AddMinutes(5), Assert.Single(store.LatestLimits(Provider.Claude)).SampleTime);
|
Assert.Equal(now.AddMinutes(5), Assert.Single(store.LatestLimits(Provider.Claude)).SampleTime);
|
||||||
}
|
}
|
||||||
[Fact]
|
[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()
|
public async Task SharingViolationRetriesUntilReaderReleasesItsHandle()
|
||||||
{
|
{
|
||||||
if (!OperatingSystem.IsWindows()) return;
|
if (!OperatingSystem.IsWindows()) return;
|
||||||
|
|||||||
@@ -142,7 +142,7 @@ public class StorageTests
|
|||||||
var fresh = SnapshotFile.Read(directory.Path, now.AddSeconds(180));
|
var fresh = SnapshotFile.Read(directory.Path, now.AddSeconds(180));
|
||||||
Assert.False(fresh.IsStale);
|
Assert.False(fresh.IsStale);
|
||||||
Assert.Equal(now, fresh.Snapshot!.MadeAt);
|
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);
|
Assert.True(SnapshotFile.Read(directory.Path, now.AddSeconds(181)).IsStale);
|
||||||
directory.Write("snapshot.json", "{\"v\":2}");
|
directory.Write("snapshot.json", "{\"v\":2}");
|
||||||
Assert.Null(SnapshotFile.Read(directory.Path).Snapshot);
|
Assert.Null(SnapshotFile.Read(directory.Path).Snapshot);
|
||||||
@@ -151,7 +151,7 @@ public class StorageTests
|
|||||||
public void CorruptHistoryIsNotSilentlyOverwritten()
|
public void CorruptHistoryIsNotSilentlyOverwritten()
|
||||||
{
|
{
|
||||||
using var directory = new TestDirectory();
|
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.Throws<InvalidDataException>(() => new HistoryStore(directory.Path, new()));
|
||||||
Assert.Equal("{", File.ReadAllText(path));
|
Assert.Equal("{", File.ReadAllText(path));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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`.
|
||||||
@@ -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>
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
+1
-4
@@ -34,10 +34,7 @@ def main():
|
|||||||
for file in stage.iterdir():
|
for file in stage.iterdir():
|
||||||
if file.suffix in ['.pdb', '.dbg']:
|
if file.suffix in ['.pdb', '.dbg']:
|
||||||
continue
|
continue
|
||||||
# Windows paths ignore case: FinalToken.exe (app) and finaltoken.exe (CLI)
|
target = destination / file.name
|
||||||
# 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
|
|
||||||
if target.exists():
|
if target.exists():
|
||||||
if file.is_file() and target.is_file() and file.read_bytes() == target.read_bytes():
|
if file.is_file() and target.is_file() and file.read_bytes() == target.read_bytes():
|
||||||
continue
|
continue
|
||||||
|
|||||||
Reference in New Issue
Block a user