feat: add FinalToken v1 for Claude and Codex usage #2
@@ -0,0 +1,16 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
indent_style = space
|
||||
indent_size = 4
|
||||
|
||||
[*.{json,xml,csproj,props,slnx}]
|
||||
indent_size = 2
|
||||
|
||||
[*.cs]
|
||||
csharp_style_namespace_declarations = file_scoped:warning
|
||||
dotnet_sort_system_directives_first = true
|
||||
@@ -0,0 +1,8 @@
|
||||
artifacts/
|
||||
**/bin/
|
||||
**/obj/
|
||||
.vs/
|
||||
.idea/
|
||||
*.user
|
||||
*.suo
|
||||
TestResults/
|
||||
@@ -0,0 +1,17 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<LangVersion>14</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||
<Deterministic>true</Deterministic>
|
||||
<IsAotCompatible>true</IsAotCompatible>
|
||||
<EnableTrimAnalyzer>true</EnableTrimAnalyzer>
|
||||
<EnableAotAnalyzer>true</EnableAotAnalyzer>
|
||||
<JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault>
|
||||
<!-- D1: artifacts stay inside this worktree. -->
|
||||
<BaseOutputPath>$(MSBuildThisFileDirectory)artifacts/bin/$(MSBuildProjectName)/</BaseOutputPath>
|
||||
<BaseIntermediateOutputPath>$(MSBuildThisFileDirectory)artifacts/obj/$(MSBuildProjectName)/</BaseIntermediateOutputPath>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,8 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageVersion Include="xunit.v3.aot.mtp-v2" Version="4.0.2" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,14 @@
|
||||
<Solution>
|
||||
<Folder Name="/src/">
|
||||
<Project Path="src/FinalToken.Core/FinalToken.Core.csproj" />
|
||||
<Project Path="src/FinalToken.Cli/FinalToken.Cli.csproj" />
|
||||
<Project Path="src/FinalToken.App/FinalToken.App.csproj" />
|
||||
<Project Path="src/FinalToken.StreamDeck/FinalToken.StreamDeck.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/tests/">
|
||||
<Project Path="tests/FinalToken.Core.Tests/FinalToken.Core.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.StreamDeck.Tests/FinalToken.StreamDeck.Tests.csproj" />
|
||||
</Folder>
|
||||
</Solution>
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"sdk": { "version": "10.0.100", "rollForward": "latestFeature" },
|
||||
"test": { "runner": "Microsoft.Testing.Platform" }
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
# App
|
||||
Buildable placeholder only. W2 replaces Program.cs and this guidance with the Avalonia host (D8).
|
||||
Use RefreshEngine and source-generated snapshot DTOs from Core. Marshal Core events to the UI.
|
||||
Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root.
|
||||
@@ -0,0 +1 @@
|
||||
@AGENTS.md
|
||||
@@ -0,0 +1,8 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<AssemblyName>FinalToken</AssemblyName>
|
||||
<PublishAot>true</PublishAot>
|
||||
</PropertyGroup>
|
||||
<ItemGroup><ProjectReference Include="../FinalToken.Core/FinalToken.Core.csproj" /></ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1 @@
|
||||
Console.WriteLine("FinalToken app placeholder; W2 supplies the Avalonia host.");
|
||||
@@ -0,0 +1,4 @@
|
||||
# CLI
|
||||
NativeAOT console host for D1, D5, D6 and D9. Exit codes: success 0, failure 1, usage 2.
|
||||
A busy store is read-only. Keep argument parsing in CliApplication for tests.
|
||||
Run `dotnet test --project tests/FinalToken.Cli.Tests -c Release` from the root.
|
||||
@@ -0,0 +1 @@
|
||||
@AGENTS.md
|
||||
@@ -0,0 +1,52 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using FinalToken.Core;
|
||||
|
||||
namespace FinalToken.Cli;
|
||||
|
||||
public static class CliApplication
|
||||
{
|
||||
public static async Task<int> RunAsync(string[] args, TextWriter output, TextWriter error,
|
||||
string? dataDirectory = null, Func<string, RefreshEngine>? engineFactory = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (args.Length == 0 || args[0] != "status" || args.Skip(1).Any(a => a is not ("--json" or "--no-probe")) ||
|
||||
args.Skip(1).Distinct().Count() != args.Length - 1)
|
||||
{ await error.WriteLineAsync("Usage: finaltoken status [--json] [--no-probe]"); return 2; }
|
||||
try
|
||||
{
|
||||
var directory = dataDirectory ?? DataPaths.DataDirectory;
|
||||
using var storeLock = StoreLock.TryAcquire(directory);
|
||||
Snapshot snapshot;
|
||||
if (storeLock is null)
|
||||
{
|
||||
await error.WriteLineAsync("Store is in use; reading the existing snapshot without refreshing.");
|
||||
var result = SnapshotFile.Read(directory);
|
||||
if (result.Snapshot is not { } existing) { await error.WriteLineAsync(result.Error); return 1; }
|
||||
if (result.IsStale) await error.WriteLineAsync("Snapshot is stale.");
|
||||
snapshot = existing;
|
||||
}
|
||||
else
|
||||
{
|
||||
await using var engine = engineFactory?.Invoke(directory) ?? new RefreshEngine(directory);
|
||||
snapshot = await engine.RefreshNowAsync(args.Contains("--no-probe"), cancellationToken);
|
||||
foreach (var diagnostic in engine.RecentDiagnostics)
|
||||
await error.WriteLineAsync($"{diagnostic.Code}: {diagnostic.Summary}");
|
||||
}
|
||||
if (args.Contains("--json")) await output.WriteLineAsync(JsonSerializer.Serialize(snapshot, CoreJsonContext.Default.Snapshot));
|
||||
else
|
||||
{
|
||||
await output.WriteLineAsync($"FinalToken {snapshot.MadeAt:O}");
|
||||
foreach (var provider in snapshot.Providers)
|
||||
{
|
||||
await output.WriteLineAsync($"{provider.Provider}: {provider.Status} {provider.Reason}");
|
||||
await output.WriteLineAsync($" Tokens today: {provider.Today.Total}; session: {provider.Session?.Total.ToString(CultureInfo.InvariantCulture) ?? "unknown"}; week: {provider.Week.Total}");
|
||||
foreach (var window in provider.Windows)
|
||||
await output.WriteLineAsync(FormattableString.Invariant($" {window.Window.Label}: {window.Window.UsedPercent:0.##}% used; resets {window.Window.ResetsAt:O}; {window.Pace.State}; delta {window.Pace.Delta:0.##}; sampled {window.Window.SampleTime:O}"));
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException or OperationCanceledException)
|
||||
{ await error.WriteLineAsync("FinalToken could not complete the refresh or read the snapshot."); return 1; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<AssemblyName>finaltoken</AssemblyName>
|
||||
<PublishAot>true</PublishAot>
|
||||
</PropertyGroup>
|
||||
<ItemGroup><ProjectReference Include="../FinalToken.Core/FinalToken.Core.csproj" /></ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,3 @@
|
||||
using FinalToken.Cli;
|
||||
|
||||
return await CliApplication.RunAsync(args, Console.Out, Console.Error);
|
||||
@@ -0,0 +1,21 @@
|
||||
# Core
|
||||
UI-free domain and file/CLI integration. Implements D1–D7, D9 and the D11 installer contract.
|
||||
Keep parsers total. Only metadata leaves them. JSON uses CoreJsonContext. Hosts own StoreLock.
|
||||
Events from RefreshEngine run on a worker thread; UI hosts must marshal them.
|
||||
Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root.
|
||||
|
||||
## Host contract
|
||||
|
||||
- Acquire `StoreLock.TryAcquire(dataDirectory)` before creating a writing engine. A busy app calls
|
||||
`ActivationFile.RequestAsync` and exits; a busy CLI uses `SnapshotFile.Read`.
|
||||
- Construct `RefreshEngine`, subscribe to `SnapshotChanged`, `PopupRequested` and
|
||||
`ActivationRequested`, then `StartAsync`. `StopAsync` cancels and waits. Dispose asynchronously.
|
||||
- Use `CurrentSnapshot`, `Settings`, `UpdateSettingsAsync`, `RefreshNowAsync` and
|
||||
`RecentDiagnostics`. `History` offers token series, model/project breakdowns and limit samples.
|
||||
- Snapshot provider totals use local today and Monday-based calendar week. Session totals use the
|
||||
reset and length of a known short limit. Hourly storage includes whole boundary hours (D5).
|
||||
- `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.
|
||||
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.
|
||||
@@ -0,0 +1,51 @@
|
||||
using System.Text;
|
||||
|
||||
namespace FinalToken.Core;
|
||||
|
||||
public static class AtomicFile
|
||||
{
|
||||
// D5: same-directory rename; a reader sees either complete version.
|
||||
public static async Task WriteAsync(string path, string contents, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);
|
||||
var temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp";
|
||||
try
|
||||
{
|
||||
await using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None,
|
||||
4096, FileOptions.Asynchronous | FileOptions.WriteThrough))
|
||||
{
|
||||
await stream.WriteAsync(Encoding.UTF8.GetBytes(contents), cancellationToken);
|
||||
await stream.FlushAsync(cancellationToken);
|
||||
stream.Flush(true);
|
||||
}
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
File.Move(temporary, path, true);
|
||||
}
|
||||
finally { if (File.Exists(temporary)) File.Delete(temporary); }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The host must hold this for the entire lifetime of a writing HistoryStore/RefreshEngine (D5).</summary>
|
||||
public sealed class StoreLock : IDisposable
|
||||
{
|
||||
private readonly FileStream stream;
|
||||
private StoreLock(FileStream stream) => this.stream = stream;
|
||||
public static StoreLock? TryAcquire(string directory)
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
try { return new(new FileStream(Path.Combine(directory, "store.lock"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)); }
|
||||
catch (IOException) { return null; }
|
||||
}
|
||||
public void Dispose() => stream.Dispose();
|
||||
}
|
||||
|
||||
public static class ActivationFile
|
||||
{
|
||||
public static Task RequestAsync(string directory, CancellationToken cancellationToken = default) =>
|
||||
AtomicFile.WriteAsync(Path.Combine(directory, "activate.request"), Guid.NewGuid().ToString("N"), cancellationToken);
|
||||
public static string? ReadRequest(string directory)
|
||||
{
|
||||
try { return File.ReadAllText(Path.Combine(directory, "activate.request")); }
|
||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException) { return null; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
@AGENTS.md
|
||||
@@ -0,0 +1,61 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace FinalToken.Core.Collectors;
|
||||
|
||||
public static partial class ClaudeUsageParser
|
||||
{
|
||||
[GeneratedRegex(@"^Current (?<label>session|week \([^)]+\)): (?<used>\d+(?:\.\d+)?)% used\s*[·•]\s*resets (?<date>[A-Za-z]{3} \d{1,2}), (?<clock>\d{1,2}(?::\d{2})?[ap]m) \((?<zone>[^)]+)\)$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex UsageLine();
|
||||
|
||||
public static IReadOnlyList<LimitWindow> ParseEnvelope(string json, DateTimeOffset sampleTime, DiagnosticLog diagnostics)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(json);
|
||||
var root = document.RootElement;
|
||||
if (root.Field("is_error").ValueKind != JsonValueKind.False || root.Field("num_turns").Integer() != 0 ||
|
||||
root.Text("local_command") != "usage" || root.Text("result") is not { } text)
|
||||
{ diagnostics.Add(Provider.Claude, "claude-envelope", "Usage command did not return a successful local result."); return []; }
|
||||
return ParseText(text, sampleTime, diagnostics);
|
||||
}
|
||||
catch (JsonException) { diagnostics.Add(Provider.Claude, "claude-envelope", "Malformed usage response."); return []; }
|
||||
}
|
||||
public static IReadOnlyList<LimitWindow> ParseText(string text, DateTimeOffset sampleTime, DiagnosticLog diagnostics)
|
||||
{
|
||||
List<LimitWindow> windows = [];
|
||||
foreach (var raw in text.Split('\n'))
|
||||
{
|
||||
var line = raw.Trim();
|
||||
if (line.Length == 0 || line == "You are currently using your subscription to power your Claude Code usage" ||
|
||||
line == "What's contributing to your limits usage?") continue;
|
||||
var match = UsageLine().Match(line);
|
||||
if (!match.Success)
|
||||
{ diagnostics.Add(Provider.Claude, "claude-usage-line", "Unknown usage line skipped."); continue; }
|
||||
try
|
||||
{
|
||||
var used = double.Parse(match.Groups["used"].Value, CultureInfo.InvariantCulture);
|
||||
if (used is < 0 or > 100) throw new FormatException();
|
||||
var label = match.Groups["label"].Value;
|
||||
var length = label == "session" ? TimeSpan.FromHours(5) : TimeSpan.FromDays(7);
|
||||
var zone = TimeZoneInfo.FindSystemTimeZoneById(match.Groups["zone"].Value);
|
||||
var local = TimeZoneInfo.ConvertTime(sampleTime, zone);
|
||||
DateTimeOffset? reset = null;
|
||||
foreach (var year in new[] { local.Year, local.Year + 1 })
|
||||
{
|
||||
var date = DateTime.ParseExact($"{year} {match.Groups["date"].Value}, {match.Groups["clock"].Value}",
|
||||
["yyyy MMM d, h:mmtt", "yyyy MMM d, htt"], CultureInfo.InvariantCulture, DateTimeStyles.None);
|
||||
if (zone.IsInvalidTime(date) || zone.IsAmbiguousTime(date)) continue;
|
||||
var candidate = new DateTimeOffset(TimeZoneInfo.ConvertTimeToUtc(date, zone));
|
||||
if (candidate > sampleTime && candidate - sampleTime <= length) { reset = candidate; break; }
|
||||
}
|
||||
if (reset is null) throw new FormatException();
|
||||
windows.Add(new(Provider.Claude, label.ToLowerInvariant(), "Current " + label, used, reset, length, sampleTime, "usage"));
|
||||
}
|
||||
catch (Exception e) when (e is FormatException or TimeZoneNotFoundException or InvalidTimeZoneException or ArgumentException)
|
||||
{ diagnostics.Add(Provider.Claude, "claude-reset-parse", "Unknown or invalid usage reset skipped."); }
|
||||
}
|
||||
return windows;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace FinalToken.Core.Collectors;
|
||||
|
||||
public sealed record ScanResult(int AddedEvents, IReadOnlyList<LimitWindow> CodexFallback,
|
||||
int ClaudeAdded = 0, int CodexAdded = 0);
|
||||
|
||||
/// <summary>Only opens transcript/rollout jsonl paths. Offsets advance through complete lines only.
|
||||
/// Prefix and consumed-tail fingerprints detect replacements without rereading whole files.</summary>
|
||||
public sealed class IncrementalScanner(HistoryStore history, DiagnosticLog diagnostics,
|
||||
string claudeDirectory, string codexDirectory)
|
||||
{
|
||||
private static readonly UTF8Encoding StrictUtf8 = new(false, true);
|
||||
public async Task<ScanResult> ScanAsync(CancellationToken cancellationToken = default,
|
||||
bool claudeEnabled = true, bool codexEnabled = true)
|
||||
{
|
||||
var added = 0;
|
||||
var claudeFiles = claudeEnabled ? FindFiles(Path.Combine(claudeDirectory, "projects"), "*.jsonl", Provider.Claude) : [];
|
||||
foreach (var path in claudeFiles)
|
||||
added += await ScanFileAsync(path, Provider.Claude, [], cancellationToken);
|
||||
var claudeAdded = added;
|
||||
var codexFiles = !codexEnabled ? [] : FindFiles(Path.Combine(codexDirectory, "sessions"), "rollout-*.jsonl", Provider.Codex)
|
||||
.Concat(FindFiles(Path.Combine(codexDirectory, "archived_sessions"), "rollout-*.jsonl", Provider.Codex))
|
||||
.OrderBy(File.GetLastWriteTimeUtc).ToArray();
|
||||
// D4 fallback belongs to the newest rollout, even when it had no appended bytes this time.
|
||||
var latest = codexFiles.LastOrDefault();
|
||||
List<LimitWindow> fallback = [];
|
||||
foreach (var path in codexFiles)
|
||||
{
|
||||
List<LimitWindow> limits = [];
|
||||
added += await ScanFileAsync(path, Provider.Codex, limits, cancellationToken);
|
||||
if (path == latest && limits.Count > 0) fallback = limits;
|
||||
}
|
||||
if (latest is not null && fallback.Count == 0) fallback = history.Cursor(latest).LatestLimits;
|
||||
return new(added, fallback, claudeAdded, added - claudeAdded);
|
||||
}
|
||||
private IReadOnlyList<string> FindFiles(string directory, string pattern, Provider provider)
|
||||
{
|
||||
try { return Directory.Exists(directory) ? Directory.GetFiles(directory, pattern, SearchOption.AllDirectories) : []; }
|
||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException)
|
||||
{ diagnostics.Add(provider, "scan-directory", "Source directory cannot be enumerated."); return []; }
|
||||
}
|
||||
private async Task<int> ScanFileAsync(string path, Provider provider, List<LimitWindow> latestLimits, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete,
|
||||
65536, FileOptions.Asynchronous | FileOptions.SequentialScan);
|
||||
var cursor = history.Cursor(path);
|
||||
var creation = File.GetCreationTimeUtc(path).Ticks;
|
||||
if (stream.Length < cursor.Offset || cursor.CreationTicks != creation ||
|
||||
cursor.PrefixHash != Fingerprint(stream, 0, cursor.PrefixLength) ||
|
||||
cursor.TailHash != Fingerprint(stream, Math.Max(0, cursor.Offset - 256), (int)Math.Min(256, cursor.Offset)))
|
||||
{
|
||||
cursor.Offset = 0;
|
||||
cursor.SessionId = Path.GetFileNameWithoutExtension(path);
|
||||
cursor.Model = null;
|
||||
cursor.Project = null;
|
||||
cursor.LatestLimits = [];
|
||||
}
|
||||
var added = 0;
|
||||
stream.Position = cursor.Offset;
|
||||
var readBuffer = new byte[65536];
|
||||
using var line = new MemoryStream();
|
||||
var consumed = cursor.Offset;
|
||||
int read;
|
||||
while ((read = await stream.ReadAsync(readBuffer, cancellationToken)) > 0)
|
||||
{
|
||||
for (var i = 0; i < read; i++)
|
||||
{
|
||||
consumed++;
|
||||
if (readBuffer[i] != (byte)'\n')
|
||||
{
|
||||
line.WriteByte(readBuffer[i]);
|
||||
continue;
|
||||
}
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
// Source entries can contain large tool results. An output-capture bound
|
||||
// belongs to child processes, not to valid transcript records (D3).
|
||||
{
|
||||
try
|
||||
{
|
||||
var text = StrictUtf8.GetString(line.GetBuffer(), 0, (int)line.Length).TrimEnd('\r');
|
||||
if (text.Length > 0 && provider == Provider.Claude)
|
||||
{
|
||||
if (TranscriptParser.Parse(text, diagnostics) is { } usage && history.Add(usage)) added++;
|
||||
}
|
||||
else if (text.Length > 0)
|
||||
{
|
||||
var entry = RolloutParser.Parse(text, cursor, DateTimeOffset.UtcNow, diagnostics);
|
||||
if (entry.CumulativeUsage is { } usage && history.AddCodex(cursor.SessionId!, usage)) added++;
|
||||
if (entry.Limits.Count > 0)
|
||||
{
|
||||
latestLimits.Clear(); latestLimits.AddRange(entry.Limits);
|
||||
cursor.LatestLimits = entry.Limits.ToList();
|
||||
}
|
||||
history.AddLimits(entry.Limits);
|
||||
}
|
||||
}
|
||||
catch (DecoderFallbackException) { diagnostics.Add(provider, "scan-encoding", "Invalid UTF-8 source line skipped."); }
|
||||
}
|
||||
cursor.Offset = consumed;
|
||||
line.SetLength(0);
|
||||
}
|
||||
}
|
||||
cursor.CreationTicks = creation;
|
||||
cursor.PrefixLength = (int)Math.Min(256, cursor.Offset);
|
||||
cursor.PrefixHash = Fingerprint(stream, 0, cursor.PrefixLength);
|
||||
cursor.TailHash = Fingerprint(stream, Math.Max(0, cursor.Offset - 256), (int)Math.Min(256, cursor.Offset));
|
||||
return added;
|
||||
}
|
||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException)
|
||||
{ diagnostics.Add(provider, "scan-file", "Source file cannot be read."); return 0; }
|
||||
}
|
||||
private static string Fingerprint(FileStream stream, long offset, int length)
|
||||
{
|
||||
if (length == 0) return "";
|
||||
stream.Position = offset;
|
||||
var bytes = new byte[length];
|
||||
var count = stream.ReadAtLeast(bytes, length, false);
|
||||
return Convert.ToHexString(SHA256.HashData(bytes.AsSpan(0, count)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace FinalToken.Core.Collectors;
|
||||
|
||||
internal static class JsonFields
|
||||
{
|
||||
public static JsonElement Field(this JsonElement element, string name) =>
|
||||
element.ValueKind == JsonValueKind.Object && element.TryGetProperty(name, out var value) ? value : default;
|
||||
public static string? Text(this JsonElement element) => element.ValueKind == JsonValueKind.String ? element.GetString() : null;
|
||||
public static string? Text(this JsonElement element, string name) => element.Field(name).Text();
|
||||
public static long? Integer(this JsonElement element) => element.ValueKind == JsonValueKind.Number && element.TryGetInt64(out var value) ? value : null;
|
||||
public static double? Number(this JsonElement element) => element.ValueKind == JsonValueKind.Number && element.TryGetDouble(out var value) && double.IsFinite(value) ? value : null;
|
||||
public static DateTimeOffset? Timestamp(this JsonElement element) => element.Text() is { } text &&
|
||||
DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var time) ? time.ToUniversalTime() : null;
|
||||
public static long Count(this JsonElement element, string name, bool required = false)
|
||||
{
|
||||
var field = element.Field(name);
|
||||
if (!required && field.ValueKind == JsonValueKind.Undefined) return 0;
|
||||
if (field.Integer() is not { } count || count is < 0 or > 1_000_000_000_000_000) throw new FormatException();
|
||||
return count;
|
||||
}
|
||||
public static TokenCounts Counts(JsonElement usage, bool claude)
|
||||
{
|
||||
var input = usage.Count("input_tokens", true);
|
||||
var output = usage.Count("output_tokens", true);
|
||||
var read = usage.Count(claude ? "cache_read_input_tokens" : "cached_input_tokens");
|
||||
var write = usage.Count(claude ? "cache_creation_input_tokens" : "cache_write_input_tokens");
|
||||
var reasoning = claude ? 0 : usage.Count("reasoning_output_tokens");
|
||||
return new(input, read, write, output, reasoning,
|
||||
claude ? checked(input + output + read + write) : usage.Count("total_tokens", true));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using FinalToken.Core.Processes;
|
||||
|
||||
namespace FinalToken.Core.Collectors;
|
||||
|
||||
public sealed record ProbeResult(bool Success, IReadOnlyList<LimitWindow> Windows, string? Reason);
|
||||
public sealed class LimitProbe(IProcessRunner runner, DiagnosticLog diagnostics, string dataDirectory)
|
||||
{
|
||||
public async Task<ProbeResult> RunAsync(Provider provider, CliCommand command, DateTimeOffset sampleTime, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await runner.RunAsync(new(command, provider == Provider.Claude
|
||||
? ["-p", "/usage", "--output-format", "json", "--no-session-persistence"] : ["app-server"],
|
||||
dataDirectory, TimeSpan.FromSeconds(60), provider == Provider.Codex), cancellationToken);
|
||||
if (result.TimedOut || result.ExitCode != 0 || result.OutputTruncated)
|
||||
{
|
||||
var reason = result.TimedOut ? "Limit probe timed out." : "Limit probe failed or exceeded its output bound.";
|
||||
diagnostics.Add(provider, result.TimedOut ? "probe-timeout" : "probe-failed", reason);
|
||||
return new(false, [], reason);
|
||||
}
|
||||
var windows = provider == Provider.Claude ? ClaudeUsageParser.ParseEnvelope(result.Output, sampleTime, diagnostics)
|
||||
: CodexLimitsParser.ParseResponse(result.Output, sampleTime, diagnostics);
|
||||
if (windows.Count > 0) return new(true, windows, null);
|
||||
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."); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace FinalToken.Core.Collectors;
|
||||
|
||||
public sealed record RolloutEntry(UsageEvent? CumulativeUsage, IReadOnlyList<LimitWindow> Limits);
|
||||
|
||||
public static class RolloutParser
|
||||
{
|
||||
public static RolloutEntry Parse(string line, ScanCursor cursor, DateTimeOffset sampleTime, DiagnosticLog diagnostics)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(line);
|
||||
var root = document.RootElement;
|
||||
var payload = root.Field("payload");
|
||||
switch (root.Text("type"))
|
||||
{
|
||||
case "session_meta":
|
||||
cursor.SessionId = payload.Text("id") ?? cursor.SessionId;
|
||||
cursor.Project = payload.Text("cwd") ?? cursor.Project;
|
||||
return new(null, []);
|
||||
case "turn_context":
|
||||
cursor.Model = payload.Text("model");
|
||||
cursor.Project = payload.Text("cwd") ?? cursor.Project;
|
||||
return new(null, []);
|
||||
case "event_msg" when payload.Text("type") == "token_count":
|
||||
if (root.Field("timestamp").Timestamp() is not { } time) throw new FormatException();
|
||||
var limits = CodexLimitsParser.Parse(payload.Field("rate_limits"), time, "rollout", diagnostics);
|
||||
if (payload.Field("info").ValueKind == JsonValueKind.Null) return new(null, limits);
|
||||
var counts = JsonFields.Counts(payload.Field("info").Field("total_token_usage"), false);
|
||||
return new(new(Provider.Codex, time, cursor.Model, cursor.Project, counts,
|
||||
$"codex:{cursor.SessionId}:{counts.Total}"), limits);
|
||||
default: return new(null, []);
|
||||
}
|
||||
}
|
||||
catch (Exception e) when (e is JsonException or FormatException or OverflowException)
|
||||
{ diagnostics.Add(Provider.Codex, "rollout-parse", "Malformed token count entry skipped."); return new(null, []); }
|
||||
}
|
||||
}
|
||||
|
||||
public static class CodexLimitsParser
|
||||
{
|
||||
public static IReadOnlyList<LimitWindow> Parse(JsonElement value, DateTimeOffset sampleTime, string source, DiagnosticLog diagnostics)
|
||||
{
|
||||
if (value.ValueKind is JsonValueKind.Null or JsonValueKind.Undefined) return [];
|
||||
List<LimitWindow> windows = [];
|
||||
var camel = source == "app-server";
|
||||
var id = value.Text(camel ? "limitId" : "limit_id") ?? "codex";
|
||||
foreach (var name in new[] { "primary", "secondary" })
|
||||
{
|
||||
var window = value.Field(name);
|
||||
if (window.ValueKind is JsonValueKind.Null or JsonValueKind.Undefined) continue;
|
||||
var used = window.Field(camel ? "usedPercent" : "used_percent").Number();
|
||||
var minutesField = window.Field(camel ? "windowDurationMins" : "window_minutes");
|
||||
var resetField = window.Field(camel ? "resetsAt" : "resets_at");
|
||||
var minutes = minutesField.Integer();
|
||||
var reset = resetField.Integer();
|
||||
try
|
||||
{
|
||||
if (used is not (>= 0 and <= 100) || minutes is <= 0 or > 525600 ||
|
||||
(minutesField.ValueKind is not (JsonValueKind.Null or JsonValueKind.Undefined) && minutes is null) ||
|
||||
(resetField.ValueKind is not (JsonValueKind.Null or JsonValueKind.Undefined) && reset is null)) throw new FormatException();
|
||||
var length = minutes is { } m ? TimeSpan.FromMinutes(m) : (TimeSpan?)null;
|
||||
var resetsAt = reset is { } r ? DateTimeOffset.FromUnixTimeSeconds(r) : (DateTimeOffset?)null;
|
||||
windows.Add(new(Provider.Codex, id + ":" + name,
|
||||
length <= TimeSpan.FromHours(5) ? "Session" : length >= TimeSpan.FromDays(7) ? "Week" : name,
|
||||
used.Value, resetsAt, length, sampleTime, source));
|
||||
}
|
||||
catch (Exception e) when (e is FormatException or ArgumentOutOfRangeException)
|
||||
{ diagnostics.Add(Provider.Codex, "codex-limit-parse", "Malformed limit window skipped."); }
|
||||
}
|
||||
return windows;
|
||||
}
|
||||
|
||||
public static IReadOnlyList<LimitWindow> ParseResponse(string line, DateTimeOffset sampleTime, DiagnosticLog diagnostics)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(line);
|
||||
var result = document.RootElement.Field("result");
|
||||
var buckets = result.Field("rateLimitsByLimitId");
|
||||
if (buckets.ValueKind == JsonValueKind.Object)
|
||||
return buckets.EnumerateObject().SelectMany(b => Parse(b.Value, sampleTime, "app-server", diagnostics)).ToArray();
|
||||
return Parse(result.Field("rateLimits"), sampleTime, "app-server", diagnostics);
|
||||
}
|
||||
catch (JsonException) { diagnostics.Add(Provider.Codex, "codex-rpc-parse", "Malformed rate limit response."); return []; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace FinalToken.Core.Collectors;
|
||||
|
||||
public static class TranscriptParser
|
||||
{
|
||||
public static UsageEvent? Parse(string line, DiagnosticLog diagnostics)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(line);
|
||||
var root = document.RootElement;
|
||||
if (root.Text("type") != "assistant") return null;
|
||||
var message = root.Field("message");
|
||||
if (message.Field("usage").ValueKind is JsonValueKind.Undefined or JsonValueKind.Null) return null;
|
||||
if (message.Text("id") is not { Length: > 0 } id || root.Text("requestId") is not { Length: > 0 } request ||
|
||||
root.Field("timestamp").Timestamp() is not { } time) throw new FormatException();
|
||||
// Length prefixes avoid collisions between ids that contain separators (D3).
|
||||
return new(Provider.Claude, time, message.Text("model"), root.Text("cwd"),
|
||||
JsonFields.Counts(message.Field("usage"), true), $"claude:{id.Length}:{id}{request.Length}:{request}");
|
||||
}
|
||||
catch (Exception e) when (e is JsonException or FormatException or OverflowException)
|
||||
{ diagnostics.Add(Provider.Claude, "transcript-parse", "Malformed assistant usage entry skipped."); return null; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk" />
|
||||
@@ -0,0 +1,160 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace FinalToken.Core;
|
||||
|
||||
public sealed record TokenBucket(Provider Provider, DateTimeOffset Hour, string? Model, string? Project, TokenCounts Counts);
|
||||
public sealed record TokenPoint(DateTimeOffset Time, TokenCounts Counts);
|
||||
public sealed record TokenBreakdown(string? Name, TokenCounts Counts);
|
||||
public enum SeriesInterval { Hour, Day }
|
||||
|
||||
public sealed class ScanCursor
|
||||
{
|
||||
public long Offset { get; set; }
|
||||
public long CreationTicks { get; set; }
|
||||
public string PrefixHash { get; set; } = "";
|
||||
public int PrefixLength { get; set; }
|
||||
public string TailHash { get; set; } = "";
|
||||
public string? SessionId { get; set; }
|
||||
public string? Model { get; set; }
|
||||
public string? Project { get; set; }
|
||||
public List<LimitWindow> LatestLimits { get; set; } = [];
|
||||
}
|
||||
|
||||
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>D5: UTC hourly storage; queries use [from,to). Day series uses UTC days.
|
||||
/// Totals use the selected local zone for today and Monday-based calendar week.
|
||||
/// Boundary hours are included as a whole; finer history is deliberately unavailable.</summary>
|
||||
public sealed class HistoryStore
|
||||
{
|
||||
private readonly Lock gate = new();
|
||||
private readonly string directory;
|
||||
private readonly HistoryData data;
|
||||
public HistoryStore(string directory, DiagnosticLog diagnostics)
|
||||
{
|
||||
this.directory = directory;
|
||||
var path = Path.Combine(directory, "history.json");
|
||||
if (!File.Exists(path)) { data = new(); return; }
|
||||
try
|
||||
{
|
||||
data = JsonSerializer.Deserialize(File.ReadAllText(path), CoreJsonContext.Default.HistoryData)
|
||||
?? throw new JsonException();
|
||||
if (data.V != 1 || data.Buckets is null || data.Limits is null || data.Cursors is null ||
|
||||
data.CodexTotals is null || data.DedupeKeys is null) throw new JsonException();
|
||||
}
|
||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException)
|
||||
{
|
||||
diagnostics.Add(null, "history-invalid", "History cannot be loaded; refusing to overwrite it.");
|
||||
throw new InvalidDataException("History cannot be loaded; restore or move the invalid history file.");
|
||||
}
|
||||
}
|
||||
internal ScanCursor Cursor(string path)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
if (!data.Cursors.TryGetValue(path, out var cursor)) data.Cursors[path] = cursor = new();
|
||||
return cursor;
|
||||
}
|
||||
}
|
||||
public bool Add(UsageEvent usage)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
if (data.DedupeKeys.Contains(usage.DedupeKey)) return false;
|
||||
AddBucket(usage);
|
||||
data.DedupeKeys.Add(usage.DedupeKey);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
internal bool AddCodex(string session, UsageEvent cumulative)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
var key = $"codex:{session}:{cumulative.Time.UtcTicks}:{cumulative.Counts.Total}";
|
||||
if (data.DedupeKeys.Contains(key)) return false;
|
||||
var previous = data.CodexTotals.GetValueOrDefault(session);
|
||||
var delta = cumulative.Counts.IncreaseFrom(previous);
|
||||
if (delta.Total > 0) AddBucket(cumulative with { Counts = delta });
|
||||
data.CodexTotals[session] = cumulative.Counts;
|
||||
data.DedupeKeys.Add(key);
|
||||
return delta.Total > 0;
|
||||
}
|
||||
}
|
||||
private void AddBucket(UsageEvent usage)
|
||||
{
|
||||
var hour = FloorHour(usage.Time);
|
||||
var index = data.Buckets.FindIndex(b => b.Provider == usage.Provider && b.Hour == hour &&
|
||||
b.Model == usage.Model && b.Project == usage.Project);
|
||||
if (index < 0) data.Buckets.Add(new(usage.Provider, hour, usage.Model, usage.Project, usage.Counts));
|
||||
else data.Buckets[index] = data.Buckets[index] with { Counts = data.Buckets[index].Counts + usage.Counts };
|
||||
}
|
||||
public void AddLimits(IEnumerable<LimitWindow> windows)
|
||||
{
|
||||
lock (gate)
|
||||
foreach (var window in windows)
|
||||
if (!data.Limits.Contains(window)) data.Limits.Add(window);
|
||||
}
|
||||
public IReadOnlyList<LimitWindow> LatestLimits(Provider provider)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
var samples = data.Limits.Where(w => w.Provider == provider).ToArray();
|
||||
if (samples.Length == 0) return [];
|
||||
var newest = samples.Max(w => w.SampleTime);
|
||||
return samples.Where(w => w.SampleTime == newest).GroupBy(w => w.Id)
|
||||
.Select(g => g.Last()).OrderBy(w => w.Length).ToArray();
|
||||
}
|
||||
}
|
||||
public IReadOnlyList<LimitWindow> LimitSamples(Provider provider, string windowId, DateTimeOffset from, DateTimeOffset to)
|
||||
{
|
||||
lock (gate) return data.Limits.Where(w => w.Provider == provider && w.Id == windowId &&
|
||||
w.SampleTime >= from && w.SampleTime < to).OrderBy(w => w.SampleTime).ToArray();
|
||||
}
|
||||
public IReadOnlyList<TokenPoint> TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval)
|
||||
{
|
||||
lock (gate) return Range(provider, from, to).GroupBy(b => interval == SeriesInterval.Hour ? b.Hour :
|
||||
new DateTimeOffset(b.Hour.UtcDateTime.Date, TimeSpan.Zero)).OrderBy(g => g.Key)
|
||||
.Select(g => new TokenPoint(g.Key, Sum(g.Select(b => b.Counts)))).ToArray();
|
||||
}
|
||||
public IReadOnlyList<TokenBreakdown> ByModel(Provider provider, DateTimeOffset from, DateTimeOffset to) =>
|
||||
Breakdown(provider, from, to, true);
|
||||
public IReadOnlyList<TokenBreakdown> ByProject(Provider provider, DateTimeOffset from, DateTimeOffset to) =>
|
||||
Breakdown(provider, from, to, false);
|
||||
private IReadOnlyList<TokenBreakdown> Breakdown(Provider provider, DateTimeOffset from, DateTimeOffset to, bool model)
|
||||
{
|
||||
lock (gate) return Range(provider, from, to).GroupBy(b => model ? b.Model : b.Project)
|
||||
.Select(g => new TokenBreakdown(g.Key, Sum(g.Select(b => b.Counts)))).OrderByDescending(b => b.Counts.Total).ToArray();
|
||||
}
|
||||
public TokenCounts Total(Provider provider, DateTimeOffset from, DateTimeOffset to)
|
||||
{ lock (gate) return Sum(Range(provider, from, to).Select(b => b.Counts)); }
|
||||
public (TokenCounts Today, TokenCounts? Session, TokenCounts Week) Totals(Provider provider, DateTimeOffset now,
|
||||
LimitWindow? session, TimeZoneInfo? zone = null)
|
||||
{
|
||||
zone ??= TimeZoneInfo.Local;
|
||||
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));
|
||||
return (Total(provider, todayUtc, now), session is { ResetsAt: { } reset, Length: { } length } && reset > now
|
||||
? Total(provider, reset - length, now) : null, Total(provider, weekUtc, now));
|
||||
}
|
||||
private IEnumerable<TokenBucket> Range(Provider provider, DateTimeOffset from, DateTimeOffset to) =>
|
||||
to <= from ? [] : data.Buckets.Where(b => b.Provider == provider && b.Hour >= FloorHour(from) && b.Hour < to);
|
||||
private static DateTimeOffset FloorHour(DateTimeOffset time) => new(time.UtcTicks - time.UtcTicks % TimeSpan.TicksPerHour, TimeSpan.Zero);
|
||||
private static TokenCounts Sum(IEnumerable<TokenCounts> values) => values.Aggregate(new TokenCounts(), (a, b) => a + b);
|
||||
public Task SaveAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
string json;
|
||||
lock (gate) json = JsonSerializer.Serialize(data, CoreJsonContext.Default.HistoryData);
|
||||
return AtomicFile.WriteAsync(Path.Combine(directory, "history.json"), json, cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace FinalToken.Core;
|
||||
|
||||
[JsonConverter(typeof(JsonStringEnumConverter<Provider>))]
|
||||
public enum Provider { Claude, Codex }
|
||||
[JsonConverter(typeof(JsonStringEnumConverter<ProviderStatus>))]
|
||||
public enum ProviderStatus { Available, Unavailable, Disabled }
|
||||
[JsonConverter(typeof(JsonStringEnumConverter<PaceState>))]
|
||||
public enum PaceState { Unknown, OnTrack, Ahead, Behind }
|
||||
[JsonConverter(typeof(JsonStringEnumConverter<InstallMode>))]
|
||||
public enum InstallMode { Off, Ask, Automatic }
|
||||
|
||||
/// <summary>Cache read is a subset of input for Codex, but separate for Claude.
|
||||
/// Reasoning is a subset of output. Total is provider-reported or computed by its parser.</summary>
|
||||
public readonly record struct TokenCounts(long Input = 0, long CacheRead = 0, long CacheWrite = 0,
|
||||
long Output = 0, long ReasoningOutput = 0, long Total = 0)
|
||||
{
|
||||
public static TokenCounts operator +(TokenCounts a, TokenCounts b) => new(
|
||||
checked(a.Input + b.Input), checked(a.CacheRead + b.CacheRead), checked(a.CacheWrite + b.CacheWrite),
|
||||
checked(a.Output + b.Output), checked(a.ReasoningOutput + b.ReasoningOutput), checked(a.Total + b.Total));
|
||||
public TokenCounts IncreaseFrom(TokenCounts previous) => new(
|
||||
Math.Max(0, Input - previous.Input), Math.Max(0, CacheRead - previous.CacheRead),
|
||||
Math.Max(0, CacheWrite - previous.CacheWrite), Math.Max(0, Output - previous.Output),
|
||||
Math.Max(0, ReasoningOutput - previous.ReasoningOutput), Math.Max(0, Total - previous.Total));
|
||||
}
|
||||
|
||||
public sealed record UsageEvent(Provider Provider, DateTimeOffset Time, string? Model, string? Project,
|
||||
TokenCounts Counts, string DedupeKey);
|
||||
public sealed record LimitWindow(Provider Provider, string Id, string Label, double UsedPercent,
|
||||
DateTimeOffset? ResetsAt, TimeSpan? Length, DateTimeOffset SampleTime, string Source);
|
||||
public sealed record PaceResult(PaceState State, double? ElapsedFraction = null, double? Delta = null,
|
||||
DateTimeOffset? Projection = null);
|
||||
public sealed record PopupEvent(Provider Provider, string WindowId, string Label, PaceState State,
|
||||
double Delta, DateTimeOffset? Projection);
|
||||
public sealed record Diagnostic(DateTimeOffset Time, Provider? Provider, string Code, string Summary);
|
||||
|
||||
/// <summary>Bounded metadata-only diagnostics. Never pass parser input or process output here (D2).</summary>
|
||||
public sealed class DiagnosticLog(TimeProvider? timeProvider = null, int capacity = 100)
|
||||
{
|
||||
private readonly Lock gate = new();
|
||||
private readonly Queue<Diagnostic> entries = new();
|
||||
public void Add(Provider? provider, string code, string summary)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
entries.Enqueue(new((timeProvider ?? TimeProvider.System).GetUtcNow(), provider, code, summary));
|
||||
while (entries.Count > Math.Max(1, capacity)) entries.Dequeue();
|
||||
}
|
||||
}
|
||||
public IReadOnlyList<Diagnostic> Recent { get { lock (gate) return entries.ToArray(); } }
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
namespace FinalToken.Core;
|
||||
|
||||
public static class Pace
|
||||
{
|
||||
// D7. A reset in the past clamps elapsed to one; it never has a future projection.
|
||||
public static PaceResult Calculate(LimitWindow window, DateTimeOffset now, double threshold = 10)
|
||||
{
|
||||
if (window.Length is not { Ticks: > 0 } length || window.ResetsAt is not { } reset ||
|
||||
!double.IsFinite(window.UsedPercent) || window.UsedPercent is < 0 or > 100 ||
|
||||
!double.IsFinite(threshold) || threshold <= 0)
|
||||
return new(PaceState.Unknown);
|
||||
var elapsed = Math.Clamp(1 - (reset - now).TotalSeconds / length.TotalSeconds, 0, 1);
|
||||
var delta = window.UsedPercent - 100 * elapsed;
|
||||
var state = delta >= threshold ? PaceState.Ahead :
|
||||
delta <= -threshold && elapsed >= 0.5 ? PaceState.Behind : PaceState.OnTrack;
|
||||
DateTimeOffset? projection = null;
|
||||
if (state == PaceState.Ahead && window.UsedPercent > 0 && elapsed > 0)
|
||||
{
|
||||
var seconds = (100 - window.UsedPercent) * elapsed * length.TotalSeconds / window.UsedPercent;
|
||||
if (seconds >= 0 && seconds < (reset - now).TotalSeconds) projection = now.AddSeconds(seconds);
|
||||
}
|
||||
return new(state, elapsed, delta, projection);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>D8: retains an alert until it clears its threshold by two points.
|
||||
/// Observe is deterministic and has no side effects beyond its own state.</summary>
|
||||
public sealed class PopupDecider
|
||||
{
|
||||
private readonly Dictionary<(Provider, string), PaceState> states = [];
|
||||
public PopupEvent? Observe(LimitWindow window, PaceResult pace, Settings settings)
|
||||
{
|
||||
var key = (window.Provider, window.Id);
|
||||
var previous = states.GetValueOrDefault(key, PaceState.Unknown);
|
||||
var next = pace.State;
|
||||
if (pace.Delta is { } delta && pace.State != PaceState.Unknown)
|
||||
{
|
||||
if (previous == PaceState.Ahead && delta > settings.PaceThreshold - 2) next = PaceState.Ahead;
|
||||
if (previous == PaceState.Behind && delta < -settings.PaceThreshold + 2 && pace.ElapsedFraction >= 0.5)
|
||||
next = PaceState.Behind;
|
||||
}
|
||||
states[key] = next;
|
||||
if (previous == next || next is not (PaceState.Ahead or PaceState.Behind) ||
|
||||
!settings.For(window.Provider).Enabled || !settings.For(window.Provider).PopupsEnabled ||
|
||||
(next == PaceState.Ahead ? !settings.PopupAhead || !settings.For(window.Provider).PopupAhead :
|
||||
!settings.PopupBehind || !settings.For(window.Provider).PopupBehind)) return null;
|
||||
return new(window.Provider, window.Id, window.Label, next, pace.Delta!.Value, pace.Projection);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
namespace FinalToken.Core.Processes;
|
||||
|
||||
public sealed record CliCommand(string FileName, IReadOnlyList<string> PrefixArguments);
|
||||
public sealed record CliDiscoveryResult(CliCommand? Command, string? Reason);
|
||||
|
||||
public static class CliDiscovery
|
||||
{
|
||||
public static CliDiscoveryResult Find(Provider provider, string? overridePath = null,
|
||||
string? searchPath = null, bool? windows = null)
|
||||
{
|
||||
try { return FindCore(provider, overridePath, searchPath, windows); }
|
||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
|
||||
{ return new(null, "CLI path is invalid or cannot be inspected."); }
|
||||
}
|
||||
private static CliDiscoveryResult FindCore(Provider provider, string? overridePath,
|
||||
string? searchPath, bool? windows)
|
||||
{
|
||||
var isWindows = windows ?? OperatingSystem.IsWindows();
|
||||
var name = provider == Provider.Claude ? "claude" : "codex";
|
||||
if (!string.IsNullOrWhiteSpace(overridePath)) return Resolve(Path.GetFullPath(overridePath), provider, isWindows, searchPath);
|
||||
foreach (var directory in (searchPath ?? Environment.GetEnvironmentVariable("PATH") ?? "")
|
||||
.Split(isWindows ? ';' : ':', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
foreach (var suffix in isWindows ? new[] { ".exe", ".cmd", ".ps1", "" } : new[] { "" })
|
||||
{
|
||||
var candidate = Path.Combine(directory.Trim('"'), name + suffix);
|
||||
if (File.Exists(candidate))
|
||||
{
|
||||
var resolved = Resolve(candidate, provider, isWindows, searchPath);
|
||||
if (resolved.Command is not null) return resolved;
|
||||
}
|
||||
}
|
||||
}
|
||||
return new(null, $"{name} CLI was not found.");
|
||||
}
|
||||
private static CliDiscoveryResult Resolve(string path, Provider provider, bool windows, string? searchPath)
|
||||
{
|
||||
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.Codex)
|
||||
{
|
||||
var package = Path.Combine(directory, "node_modules", "@openai", "codex");
|
||||
// Unix npm bin symlinks point into the package; resolve before looking for vendor/node.
|
||||
var target = File.ResolveLinkTarget(path, true)?.FullName;
|
||||
if (target is not null && Path.GetFileName(target) == "codex.js") package = Path.GetDirectoryName(Path.GetDirectoryName(target))!;
|
||||
foreach (var vendorRoot in new[] { Path.Combine(package, "node_modules", "@openai", "codex-win32-x64", "vendor"), Path.Combine(package, "vendor") })
|
||||
{
|
||||
var binary = Path.Combine(vendorRoot, windows ? "x86_64-pc-windows-msvc" : "x86_64-unknown-linux-musl", "bin", windows ? "codex.exe" : "codex");
|
||||
if (File.Exists(binary)) return new(new(binary, []), null);
|
||||
}
|
||||
var script = Path.Combine(package, "bin", "codex.js");
|
||||
if (File.Exists(script) && FindNode(directory, searchPath, windows) is { } node) return new(new(node, [script]), null);
|
||||
}
|
||||
if (!windows)
|
||||
{
|
||||
using var file = File.OpenRead(path);
|
||||
var bytes = new byte[128];
|
||||
var count = file.Read(bytes);
|
||||
var first = System.Text.Encoding.UTF8.GetString(bytes, 0, count).Split('\n')[0];
|
||||
if (!first.StartsWith("#!", StringComparison.Ordinal)) return new(new(path, []), null);
|
||||
if ((first == "#!/usr/bin/env node" || first == "#!/usr/bin/node") && FindNode(directory, searchPath, false) is { } node)
|
||||
return new(new(node, [path]), null);
|
||||
}
|
||||
return new(null, "CLI wrapper has no supported native binary or Node runtime.");
|
||||
}
|
||||
private static string? FindNode(string directory, string? searchPath, bool windows)
|
||||
{
|
||||
foreach (var candidateDirectory in new[] { directory }.Concat((searchPath ?? Environment.GetEnvironmentVariable("PATH") ?? "")
|
||||
.Split(windows ? ';' : ':', StringSplitOptions.RemoveEmptyEntries)))
|
||||
{
|
||||
var path = Path.Combine(candidateDirectory.Trim('"'), windows ? "node.exe" : "node");
|
||||
if (File.Exists(path)) return path;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace FinalToken.Core.Processes;
|
||||
|
||||
public sealed record ProcessRequest(CliCommand Command, IReadOnlyList<string> Arguments, string WorkingDirectory,
|
||||
TimeSpan Timeout, bool CodexRpc = false, int OutputLimit = 1024 * 1024);
|
||||
public sealed record ProcessResult(int ExitCode, string Output, bool TimedOut = false, bool OutputTruncated = false);
|
||||
public interface IProcessRunner
|
||||
{
|
||||
Task<ProcessResult> RunAsync(ProcessRequest request, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>No shell; bounded capture; cancellation/timeout kills and waits for the whole child tree (D6).</summary>
|
||||
public sealed class ProcessRunner(TimeProvider? timeProvider = null) : IProcessRunner
|
||||
{
|
||||
public async Task<ProcessResult> RunAsync(ProcessRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(request.Timeout, timeProvider ?? TimeProvider.System);
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeout.Token);
|
||||
var token = linked.Token;
|
||||
using var process = new Process { StartInfo = new()
|
||||
{
|
||||
FileName = request.Command.FileName, WorkingDirectory = request.WorkingDirectory,
|
||||
UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true,
|
||||
RedirectStandardError = true, RedirectStandardInput = request.CodexRpc
|
||||
} };
|
||||
foreach (var argument in request.Command.PrefixArguments.Concat(request.Arguments)) process.StartInfo.ArgumentList.Add(argument);
|
||||
process.Start();
|
||||
var stderr = CaptureAsync(process.StandardError, request.OutputLimit, token);
|
||||
Task<(string Output, bool Truncated)>? stdout = null;
|
||||
try
|
||||
{
|
||||
if (request.CodexRpc)
|
||||
{
|
||||
await process.StandardInput.WriteLineAsync("{\"id\":1,\"method\":\"initialize\",\"params\":{\"clientInfo\":{\"name\":\"finaltoken\",\"version\":\"1.0.0\"},\"capabilities\":{\"experimentalApi\":false,\"explicitGatewayOauth\":true}}}".AsMemory(), token);
|
||||
await ReadResponseAsync(process.StandardOutput, 1, request.OutputLimit, token);
|
||||
await process.StandardInput.WriteLineAsync("{\"method\":\"initialized\"}".AsMemory(), token);
|
||||
await process.StandardInput.WriteLineAsync("{\"id\":2,\"method\":\"account/rateLimits/read\",\"params\":null}".AsMemory(), token);
|
||||
var output = await ReadResponseAsync(process.StandardOutput, 2, request.OutputLimit, token);
|
||||
Kill(process);
|
||||
await process.WaitForExitAsync(CancellationToken.None);
|
||||
await stderr;
|
||||
return new(0, output);
|
||||
}
|
||||
stdout = CaptureAsync(process.StandardOutput, request.OutputLimit, token);
|
||||
await process.WaitForExitAsync(token);
|
||||
var captured = await stdout;
|
||||
await stderr;
|
||||
return new(process.ExitCode, captured.Output, false, captured.Truncated);
|
||||
}
|
||||
catch (OperationCanceledException) when (timeout.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
|
||||
{ return new(-1, "", true); }
|
||||
finally
|
||||
{
|
||||
Kill(process);
|
||||
await process.WaitForExitAsync(CancellationToken.None);
|
||||
// Observe capture cancellation/failure; process output is never logged.
|
||||
try { await stderr; } catch (OperationCanceledException) { }
|
||||
if (stdout is not null)
|
||||
try { await stdout; } catch (OperationCanceledException) { }
|
||||
}
|
||||
}
|
||||
private static void Kill(Process process)
|
||||
{
|
||||
try { if (!process.HasExited) process.Kill(true); }
|
||||
catch (InvalidOperationException) { }
|
||||
}
|
||||
private static async Task<(string Output, bool Truncated)> CaptureAsync(StreamReader reader, int limit, CancellationToken token)
|
||||
{
|
||||
var output = new StringBuilder();
|
||||
var buffer = new char[4096];
|
||||
var truncated = false;
|
||||
int read;
|
||||
while ((read = await reader.ReadAsync(buffer, token)) > 0)
|
||||
{
|
||||
var keep = Math.Min(read, Math.Max(0, limit - output.Length));
|
||||
output.Append(buffer, 0, keep);
|
||||
truncated |= keep < read;
|
||||
}
|
||||
return (output.ToString(), truncated);
|
||||
}
|
||||
private static async Task<string> ReadResponseAsync(StreamReader reader, int id, int limit, CancellationToken token)
|
||||
{
|
||||
// Bound each line and total traffic, including unrelated notifications.
|
||||
var line = new StringBuilder();
|
||||
var one = new char[1];
|
||||
var total = 0;
|
||||
while (await reader.ReadAsync(one, token) > 0)
|
||||
{
|
||||
if (++total > limit) throw new InvalidDataException("RPC output exceeded its bound.");
|
||||
if (one[0] != '\n') { line.Append(one[0]); continue; }
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(line.ToString());
|
||||
if (document.RootElement.TryGetProperty("id", out var value) && value.TryGetInt32(out var responseId) && responseId == id)
|
||||
{
|
||||
if (document.RootElement.TryGetProperty("error", out _)) throw new InvalidDataException("RPC request failed.");
|
||||
return line.ToString();
|
||||
}
|
||||
}
|
||||
catch (JsonException) { }
|
||||
line.Clear();
|
||||
}
|
||||
throw new InvalidDataException("RPC response was not returned.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
using FinalToken.Core.Collectors;
|
||||
using FinalToken.Core.Processes;
|
||||
|
||||
namespace FinalToken.Core;
|
||||
|
||||
/// <summary>Shared app/CLI host (D6). Caller holds StoreLock. SnapshotChanged, PopupRequested,
|
||||
/// ActivationRequested run on worker threads, never the caller's UI synchronization context.
|
||||
/// UI hosts must marshal events. History query results are safe copies.</summary>
|
||||
public sealed class RefreshEngine : IAsyncDisposable
|
||||
{
|
||||
private readonly SemaphoreSlim refreshGate = new(1, 1);
|
||||
private readonly SemaphoreSlim lifecycleGate = new(1, 1);
|
||||
private readonly string directory;
|
||||
private readonly TimeProvider clock;
|
||||
private readonly IncrementalScanner scanner;
|
||||
private readonly LimitProbe probe;
|
||||
private readonly Func<Provider, string?, CliDiscoveryResult> discover;
|
||||
private readonly PopupDecider popups = new();
|
||||
private readonly Dictionary<Provider, DateTimeOffset> lastProbe = [];
|
||||
private readonly Dictionary<Provider, (ProviderStatus Status, string? Reason)> statuses = [];
|
||||
private readonly HashSet<Provider> pendingProbe = [];
|
||||
private readonly List<FileSystemWatcher> watchers = [];
|
||||
private CancellationTokenSource? lifetime = new();
|
||||
private Task? loop;
|
||||
private Snapshot? current;
|
||||
private Settings settings;
|
||||
private long changedTicks;
|
||||
private DateTimeOffset lastRefresh = DateTimeOffset.MinValue;
|
||||
private string? activation;
|
||||
|
||||
public RefreshEngine(string? dataDirectory = null, TimeProvider? timeProvider = null, IProcessRunner? processRunner = null,
|
||||
string? claudeDirectory = null, string? codexDirectory = null,
|
||||
Func<Provider, string?, CliDiscoveryResult>? cliDiscovery = null)
|
||||
{
|
||||
directory = dataDirectory ?? DataPaths.DataDirectory;
|
||||
Directory.CreateDirectory(directory);
|
||||
clock = timeProvider ?? TimeProvider.System;
|
||||
Diagnostics = new(clock);
|
||||
settings = SettingsFile.Load(directory, Diagnostics);
|
||||
History = new(directory, Diagnostics);
|
||||
ClaudeDirectory = claudeDirectory ?? DataPaths.ClaudeDirectory;
|
||||
CodexDirectory = codexDirectory ?? DataPaths.CodexDirectory;
|
||||
scanner = new(History, Diagnostics, ClaudeDirectory, CodexDirectory);
|
||||
probe = new(processRunner ?? new ProcessRunner(clock), Diagnostics, directory);
|
||||
discover = cliDiscovery ?? ((provider, path) => CliDiscovery.Find(provider, path));
|
||||
current = SnapshotFile.Read(directory, clock.GetUtcNow()).Snapshot;
|
||||
activation = ActivationFile.ReadRequest(directory);
|
||||
}
|
||||
public string DataDirectory => directory;
|
||||
public string ClaudeDirectory { get; }
|
||||
public string CodexDirectory { get; }
|
||||
public Snapshot? CurrentSnapshot => Volatile.Read(ref current);
|
||||
public Settings Settings => Volatile.Read(ref settings);
|
||||
public HistoryStore History { get; }
|
||||
public DiagnosticLog Diagnostics { get; }
|
||||
public IReadOnlyList<Diagnostic> RecentDiagnostics => Diagnostics.Recent;
|
||||
public event Action<Snapshot>? SnapshotChanged;
|
||||
public event Action<PopupEvent>? PopupRequested;
|
||||
public event Action? ActivationRequested;
|
||||
|
||||
public Task UpdateSettingsAsync(Settings value, CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||||
{
|
||||
await refreshGate.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
await SettingsFile.SaveAsync(directory, value, cancellationToken);
|
||||
Volatile.Write(ref settings, value);
|
||||
}
|
||||
finally { refreshGate.Release(); }
|
||||
}, cancellationToken);
|
||||
|
||||
public async Task StartAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
await lifecycleGate.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
if (loop is not null) return;
|
||||
lifetime ??= new();
|
||||
foreach (var path in new[] { Path.Combine(ClaudeDirectory, "projects"), Path.Combine(CodexDirectory, "sessions"), Path.Combine(CodexDirectory, "archived_sessions") })
|
||||
{
|
||||
if (!Directory.Exists(path)) continue;
|
||||
var watcher = new FileSystemWatcher(path, "*.jsonl") { IncludeSubdirectories = true };
|
||||
watcher.Changed += (_, _) => NotifySourceChanged();
|
||||
watcher.Created += (_, _) => NotifySourceChanged();
|
||||
watcher.Deleted += (_, _) => NotifySourceChanged();
|
||||
watcher.Renamed += (_, _) => NotifySourceChanged();
|
||||
watcher.Error += (_, _) => { Diagnostics.Add(null, "watcher", "File watcher failed; periodic scans continue."); NotifySourceChanged(); };
|
||||
watcher.EnableRaisingEvents = true;
|
||||
watchers.Add(watcher);
|
||||
}
|
||||
loop = Task.Run(() => RunLoopAsync(lifetime.Token), CancellationToken.None);
|
||||
}
|
||||
finally { lifecycleGate.Release(); }
|
||||
}
|
||||
public async Task StopAsync()
|
||||
{
|
||||
await lifecycleGate.WaitAsync();
|
||||
try
|
||||
{
|
||||
foreach (var watcher in watchers) watcher.Dispose();
|
||||
watchers.Clear();
|
||||
if (lifetime is not null) await lifetime.CancelAsync();
|
||||
if (loop is not null)
|
||||
try { await loop; } catch (OperationCanceledException) { }
|
||||
// Also wait for any manually requested refresh, which shares the lifetime token.
|
||||
await refreshGate.WaitAsync();
|
||||
refreshGate.Release();
|
||||
lifetime?.Dispose();
|
||||
lifetime = null;
|
||||
loop = null;
|
||||
}
|
||||
finally { lifecycleGate.Release(); }
|
||||
}
|
||||
public void NotifySourceChanged() => Interlocked.Exchange(ref changedTicks, clock.GetUtcNow().UtcTicks);
|
||||
|
||||
public Task<Snapshot> RefreshNowAsync(bool noProbe = false, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var shutdown = lifetime?.Token ?? CancellationToken.None;
|
||||
return Task.Run(async () =>
|
||||
{
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, shutdown);
|
||||
return await RefreshAsync(noProbe, linked.Token);
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>One scheduler tick, also usable with a fake TimeProvider. Changes debounce for two seconds.</summary>
|
||||
public Task TickAsync(CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||||
{
|
||||
var request = ActivationFile.ReadRequest(directory);
|
||||
if (request is not null && request != activation) { activation = request; Dispatch(ActivationRequested); }
|
||||
var now = clock.GetUtcNow();
|
||||
var changes = Interlocked.Read(ref changedTicks);
|
||||
if (now - lastRefresh >= Settings.RefreshInterval || changes > 0 && now.UtcTicks - changes >= TimeSpan.FromSeconds(2).Ticks)
|
||||
{
|
||||
Interlocked.CompareExchange(ref changedTicks, 0, changes);
|
||||
await RefreshAsync(false, cancellationToken);
|
||||
}
|
||||
}, cancellationToken);
|
||||
|
||||
private async Task RunLoopAsync(CancellationToken token)
|
||||
{
|
||||
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1), clock);
|
||||
do
|
||||
{
|
||||
try { await TickAsync(token); }
|
||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException)
|
||||
{ Diagnostics.Add(null, "refresh-write", "Refresh could not persist files."); }
|
||||
} while (await timer.WaitForNextTickAsync(token));
|
||||
}
|
||||
private async Task<Snapshot> RefreshAsync(bool noProbe, CancellationToken token)
|
||||
{
|
||||
await refreshGate.WaitAsync(token);
|
||||
try
|
||||
{
|
||||
var config = Settings;
|
||||
var scan = await scanner.ScanAsync(token, config.Claude.Enabled, config.Codex.Enabled);
|
||||
if (scan.ClaudeAdded > 0) pendingProbe.Add(Provider.Claude);
|
||||
if (scan.CodexAdded > 0) pendingProbe.Add(Provider.Codex);
|
||||
var now = clock.GetUtcNow();
|
||||
List<ProviderSnapshot> providers = [];
|
||||
List<PopupEvent> alerts = [];
|
||||
foreach (var provider in new[] { Provider.Claude, Provider.Codex })
|
||||
{
|
||||
var providerSettings = config.For(provider);
|
||||
if (!providerSettings.Enabled) statuses[provider] = (ProviderStatus.Disabled, "Disabled in settings.");
|
||||
else
|
||||
{
|
||||
var cli = discover(provider, providerSettings.CliPath);
|
||||
if (cli.Command is null) statuses[provider] = (ProviderStatus.Unavailable, cli.Reason);
|
||||
else
|
||||
{
|
||||
if (!statuses.ContainsKey(provider) || statuses[provider].Status == ProviderStatus.Disabled)
|
||||
statuses[provider] = (ProviderStatus.Available, null);
|
||||
var previousProbe = lastProbe.GetValueOrDefault(provider, DateTimeOffset.MinValue);
|
||||
var since = now - previousProbe;
|
||||
if (!noProbe && since >= TimeSpan.FromMinutes(1) && (since >= config.ProbeInterval || pendingProbe.Contains(provider)))
|
||||
{
|
||||
lastProbe[provider] = now;
|
||||
pendingProbe.Remove(provider);
|
||||
var result = await probe.RunAsync(provider, cli.Command, now, token);
|
||||
if (result.Success)
|
||||
{
|
||||
History.AddLimits(result.Windows);
|
||||
statuses[provider] = (ProviderStatus.Available, null);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (provider == Provider.Codex && scan.CodexFallback.Count > 0)
|
||||
statuses[provider] = (ProviderStatus.Available, "Probe failed; using rollout limits.");
|
||||
else statuses[provider] = (ProviderStatus.Unavailable, result.Reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
var windows = History.LatestLimits(provider);
|
||||
// Session totals follow an explicitly short limit window, never a week mislabeled primary.
|
||||
var session = windows.FirstOrDefault(w => w.Length is { } length && length <= TimeSpan.FromHours(5));
|
||||
var totals = History.Totals(provider, now, session);
|
||||
var state = statuses[provider];
|
||||
var snapshots = windows.Select(w => new WindowSnapshot(w, Pace.Calculate(w, now, config.PaceThreshold))).ToArray();
|
||||
providers.Add(new(provider, state.Status, state.Reason, snapshots, totals.Today, totals.Session, totals.Week));
|
||||
foreach (var window in snapshots)
|
||||
if (state.Status == ProviderStatus.Available && popups.Observe(window.Window, window.Pace, config) is { } alert)
|
||||
alerts.Add(alert);
|
||||
}
|
||||
var snapshot = new Snapshot { MadeAt = clock.GetUtcNow(), RefreshInterval = config.RefreshInterval, Providers = providers };
|
||||
await History.SaveAsync(token);
|
||||
await SnapshotFile.WriteAsync(directory, snapshot, token);
|
||||
Volatile.Write(ref current, snapshot);
|
||||
lastRefresh = clock.GetUtcNow();
|
||||
Dispatch(SnapshotChanged, snapshot);
|
||||
foreach (var alert in alerts) Dispatch(PopupRequested, alert);
|
||||
return snapshot;
|
||||
}
|
||||
finally { refreshGate.Release(); }
|
||||
}
|
||||
private void Dispatch<T>(Action<T>? handlers, T value)
|
||||
{
|
||||
if (handlers is null) return;
|
||||
foreach (var handler in handlers.GetInvocationList().Cast<Action<T>>())
|
||||
try { handler(value); } catch (Exception) { Diagnostics.Add(null, "event-handler", "A host event handler failed."); }
|
||||
}
|
||||
private void Dispatch(Action? handlers)
|
||||
{
|
||||
if (handlers is null) return;
|
||||
foreach (var handler in handlers.GetInvocationList().Cast<Action>())
|
||||
try { handler(); } catch (Exception) { Diagnostics.Add(null, "event-handler", "A host event handler failed."); }
|
||||
}
|
||||
public async ValueTask DisposeAsync() => await StopAsync();
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace FinalToken.Core;
|
||||
|
||||
public sealed record ProviderSettings
|
||||
{
|
||||
public bool Enabled { get; init; } = true;
|
||||
public bool PopupsEnabled { get; init; } = true;
|
||||
public bool PopupAhead { get; init; } = true;
|
||||
public bool PopupBehind { get; init; } = true;
|
||||
public string? CliPath { get; init; }
|
||||
}
|
||||
|
||||
public sealed record Settings
|
||||
{
|
||||
public TimeSpan RefreshInterval { get; init; } = TimeSpan.FromSeconds(60);
|
||||
public TimeSpan ProbeInterval { get; init; } = TimeSpan.FromMinutes(5);
|
||||
public double PaceThreshold { get; init; } = 10;
|
||||
public bool PopupAhead { get; init; } = true;
|
||||
public bool PopupBehind { get; init; } = true;
|
||||
public InstallMode StreamDeckInstallMode { get; init; } = InstallMode.Ask;
|
||||
public string? DismissedPluginVersion { get; init; }
|
||||
public bool StartWithOs { get; init; }
|
||||
public bool CloseToTray { get; init; } = true;
|
||||
public ProviderSettings Claude { get; init; } = new();
|
||||
public ProviderSettings Codex { get; init; } = new();
|
||||
public ProviderSettings For(Provider provider) => provider == Provider.Claude ? Claude : Codex;
|
||||
[System.Text.Json.Serialization.JsonIgnore]
|
||||
public bool IsValid => RefreshInterval > TimeSpan.Zero && RefreshInterval <= TimeSpan.FromSeconds(60) &&
|
||||
ProbeInterval >= TimeSpan.FromMinutes(1) && ProbeInterval <= TimeSpan.FromMinutes(60) &&
|
||||
double.IsFinite(PaceThreshold) && PaceThreshold is > 0 and <= 100 && Claude is not null && Codex is not null &&
|
||||
Enum.IsDefined(StreamDeckInstallMode);
|
||||
}
|
||||
|
||||
public static class DataPaths
|
||||
{
|
||||
public static string DataDirectory => Environment.GetEnvironmentVariable("FINALTOKEN_DATA_DIR") is { Length: > 0 } path
|
||||
? Path.GetFullPath(path) : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "FinalToken");
|
||||
public static string ClaudeDirectory => Environment.GetEnvironmentVariable("CLAUDE_CONFIG_DIR") is { Length: > 0 } path
|
||||
? Path.GetFullPath(path) : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".claude");
|
||||
public static string CodexDirectory => Environment.GetEnvironmentVariable("CODEX_HOME") is { Length: > 0 } path
|
||||
? Path.GetFullPath(path) : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".codex");
|
||||
}
|
||||
|
||||
public static class SettingsFile
|
||||
{
|
||||
public static Settings Load(string directory, DiagnosticLog diagnostics)
|
||||
{
|
||||
try
|
||||
{
|
||||
var value = JsonSerializer.Deserialize(File.ReadAllText(Path.Combine(directory, "settings.json")), CoreJsonContext.Default.Settings);
|
||||
if (value is { IsValid: true }) return value;
|
||||
}
|
||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException) { }
|
||||
diagnostics.Add(null, "settings-defaults", "Settings missing or invalid; using defaults.");
|
||||
return new();
|
||||
}
|
||||
public static Task SaveAsync(string directory, Settings settings, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!settings.IsValid) throw new ArgumentException("Invalid settings.", nameof(settings));
|
||||
return AtomicFile.WriteAsync(Path.Combine(directory, "settings.json"),
|
||||
JsonSerializer.Serialize(settings, CoreJsonContext.Default.Settings), cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace FinalToken.Core;
|
||||
|
||||
public sealed record WindowSnapshot(LimitWindow Window, PaceResult Pace)
|
||||
{
|
||||
public TimeSpan Age(DateTimeOffset now) => now - Window.SampleTime;
|
||||
}
|
||||
public sealed record ProviderSnapshot(Provider Provider, ProviderStatus Status, string? Reason,
|
||||
IReadOnlyList<WindowSnapshot> Windows, TokenCounts Today, TokenCounts? Session, TokenCounts Week);
|
||||
public sealed record Snapshot
|
||||
{
|
||||
public int V { get; init; } = 1;
|
||||
public required DateTimeOffset MadeAt { get; init; }
|
||||
public required TimeSpan RefreshInterval { get; init; }
|
||||
public string? AppPath { get; init; } = Environment.ProcessPath;
|
||||
public required IReadOnlyList<ProviderSnapshot> Providers { get; init; }
|
||||
}
|
||||
public sealed record SnapshotReadResult(Snapshot? Snapshot, bool IsStale, string? Error);
|
||||
|
||||
public static class SnapshotFile
|
||||
{
|
||||
public static Task WriteAsync(string directory, Snapshot snapshot, CancellationToken cancellationToken = default) =>
|
||||
AtomicFile.WriteAsync(Path.Combine(directory, "snapshot.json"),
|
||||
JsonSerializer.Serialize(snapshot, CoreJsonContext.Default.Snapshot), cancellationToken);
|
||||
public static SnapshotReadResult Read(string directory, DateTimeOffset? now = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var snapshot = JsonSerializer.Deserialize(File.ReadAllText(Path.Combine(directory, "snapshot.json")), CoreJsonContext.Default.Snapshot);
|
||||
if (snapshot is null || snapshot.V != 1 || snapshot.RefreshInterval <= TimeSpan.Zero || snapshot.Providers is null)
|
||||
return new(null, true, "Snapshot schema is invalid or unsupported.");
|
||||
var age = (now ?? DateTimeOffset.UtcNow) - snapshot.MadeAt;
|
||||
return new(snapshot, age.TotalSeconds > snapshot.RefreshInterval.TotalSeconds * 3, null);
|
||||
}
|
||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException)
|
||||
{ return new(null, true, "Snapshot is missing or invalid."); }
|
||||
}
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, WriteIndented = false)]
|
||||
[JsonSerializable(typeof(Snapshot))]
|
||||
[JsonSerializable(typeof(Settings))]
|
||||
[JsonSerializable(typeof(HistoryData))]
|
||||
public partial class CoreJsonContext : JsonSerializerContext;
|
||||
@@ -0,0 +1,29 @@
|
||||
namespace FinalToken.Core.StreamDeck;
|
||||
|
||||
public enum PluginInstallState { NoHostFound, NotInstalled, Outdated, UpToDate, NoShippedPlugin }
|
||||
public sealed record PluginInstallStatus(PluginInstallState State, string? ShippedVersion = null, string? InstalledVersion = null);
|
||||
public interface IPluginInstaller
|
||||
{
|
||||
Task<PluginInstallStatus> GetStatusAsync(CancellationToken cancellationToken = default);
|
||||
Task InstallOrUpdateAsync(CancellationToken cancellationToken = default);
|
||||
}
|
||||
/// <summary>W3 replaces this with platform host detection and atomic plugin deployment (D11).</summary>
|
||||
public sealed class StubPluginInstaller : IPluginInstaller
|
||||
{
|
||||
public Task<PluginInstallStatus> 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
|
||||
{
|
||||
public static InstallAction Decide(InstallMode mode, PluginInstallStatus status, string? dismissedVersion) =>
|
||||
status.State is not (PluginInstallState.NotInstalled or PluginInstallState.Outdated) || status.ShippedVersion is null
|
||||
? InstallAction.Nothing : mode switch
|
||||
{
|
||||
InstallMode.Automatic => InstallAction.Install,
|
||||
InstallMode.Ask when status.ShippedVersion != dismissedVersion => InstallAction.Ask,
|
||||
_ => InstallAction.Nothing
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
# Stream Deck
|
||||
Buildable placeholder only. W3 replaces Program.cs and this guidance with the D10 plugin.
|
||||
W3 also owns Core/StreamDeck. Read snapshots using SnapshotFile (D9); use Core DTOs.
|
||||
Run `dotnet test --project tests/FinalToken.StreamDeck.Tests -c Release` from the root.
|
||||
@@ -0,0 +1 @@
|
||||
@AGENTS.md
|
||||
@@ -0,0 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<PublishAot>true</PublishAot>
|
||||
</PropertyGroup>
|
||||
<ItemGroup><ProjectReference Include="../FinalToken.Core/FinalToken.Core.csproj" /></ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1 @@
|
||||
Console.WriteLine("FinalToken Stream Deck placeholder; W3 supplies the plugin host.");
|
||||
@@ -0,0 +1,4 @@
|
||||
# App tests
|
||||
Hand-written fixtures only. xUnit v3 AOT with Microsoft.Testing.Platform.
|
||||
Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root.
|
||||
Placeholder test; owning worker replaces it.
|
||||
@@ -0,0 +1 @@
|
||||
@AGENTS.md
|
||||
@@ -0,0 +1,12 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
<UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner>
|
||||
<TestingPlatformDotnetTestSupport>true</TestingPlatformDotnetTestSupport>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="xunit.v3.aot.mtp-v2" />
|
||||
<ProjectReference Include="../../src/FinalToken.App/FinalToken.App.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,3 @@
|
||||
using Xunit;
|
||||
namespace FinalToken.App.Tests;
|
||||
public class PlaceholderTests { [Fact] public void FoundationBuilds() => Assert.True(true); }
|
||||
@@ -0,0 +1,4 @@
|
||||
# Cli tests
|
||||
Hand-written fixtures only. xUnit v3 AOT with Microsoft.Testing.Platform.
|
||||
Run `dotnet test --project tests/FinalToken.Cli.Tests -c Release` from the root.
|
||||
Cover behavior and failure boundaries, not implementation details.
|
||||
@@ -0,0 +1 @@
|
||||
@AGENTS.md
|
||||
@@ -0,0 +1,69 @@
|
||||
using FinalToken.Cli;
|
||||
using FinalToken.Core;
|
||||
using Xunit;
|
||||
|
||||
namespace FinalToken.Cli.Tests;
|
||||
|
||||
public class CliTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData("unknown")]
|
||||
[InlineData("status --unknown")]
|
||||
[InlineData("status --json --json")]
|
||||
public async Task InvalidUsageExitsTwo(string command)
|
||||
{
|
||||
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());
|
||||
}
|
||||
[Fact]
|
||||
public async Task BusyStoreReadsExistingSnapshotAndDoesNotRefresh()
|
||||
{
|
||||
var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(directory);
|
||||
try
|
||||
{
|
||||
using var storeLock = StoreLock.TryAcquire(directory);
|
||||
await SnapshotFile.WriteAsync(directory, new Snapshot { MadeAt = DateTimeOffset.UtcNow, RefreshInterval = TimeSpan.FromSeconds(60), Providers = [] }, TestContext.Current.CancellationToken);
|
||||
using var output = new StringWriter();
|
||||
using var error = new StringWriter();
|
||||
Assert.Equal(0, await CliApplication.RunAsync(["status", "--json"], output, error, directory,
|
||||
_ => throw new InvalidOperationException("Must not create a writing engine."), TestContext.Current.CancellationToken));
|
||||
Assert.Contains("\"v\":1", output.ToString());
|
||||
Assert.Contains("Store is in use", error.ToString());
|
||||
}
|
||||
finally { Directory.Delete(directory, true); }
|
||||
}
|
||||
[Fact]
|
||||
public async Task StatusNoProbeWritesSnapshotAndText()
|
||||
{
|
||||
var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(directory);
|
||||
try
|
||||
{
|
||||
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.Contains("Tokens today: 0", output.ToString());
|
||||
Assert.NotNull(SnapshotFile.Read(directory).Snapshot);
|
||||
}
|
||||
finally { Directory.Delete(directory, true); }
|
||||
}
|
||||
[Fact]
|
||||
public async Task BusyStoreWithoutSnapshotExitsOne()
|
||||
{
|
||||
var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(directory);
|
||||
try
|
||||
{
|
||||
using var storeLock = StoreLock.TryAcquire(directory);
|
||||
using var output = new StringWriter();
|
||||
using var error = new StringWriter();
|
||||
Assert.Equal(1, await CliApplication.RunAsync(["status"], output, error, directory, cancellationToken: TestContext.Current.CancellationToken));
|
||||
}
|
||||
finally { Directory.Delete(directory, true); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
<UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner>
|
||||
<TestingPlatformDotnetTestSupport>true</TestingPlatformDotnetTestSupport>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="xunit.v3.aot.mtp-v2" />
|
||||
<ProjectReference Include="../../src/FinalToken.Cli/FinalToken.Cli.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,4 @@
|
||||
# Core tests
|
||||
Hand-written fixtures only. xUnit v3 AOT with Microsoft.Testing.Platform.
|
||||
Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root.
|
||||
Cover behavior and failure boundaries, not implementation details.
|
||||
@@ -0,0 +1 @@
|
||||
@AGENTS.md
|
||||
@@ -0,0 +1,72 @@
|
||||
using FinalToken.Core.Processes;
|
||||
using FinalToken.Core.StreamDeck;
|
||||
using Xunit;
|
||||
|
||||
namespace FinalToken.Core.Tests;
|
||||
|
||||
public class DiscoveryAndPolicyTests
|
||||
{
|
||||
[Fact]
|
||||
public void FindsNativeWindowsAndHonorsOverride()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
var path = directory.Write("claude.exe", "fixture");
|
||||
Assert.Equal(path, CliDiscovery.Find(Provider.Claude, searchPath: directory.Path, windows: true).Command!.FileName);
|
||||
Assert.Null(CliDiscovery.Find(Provider.Claude, Path.Combine(directory.Path, "missing.exe"), windows: true).Command);
|
||||
}
|
||||
[Fact]
|
||||
public void ResolvesWindowsCodexNpmNativeBinaryWithoutShell()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
directory.Write("codex.cmd", "fixture");
|
||||
var binary = directory.Write("node_modules/@openai/codex/node_modules/@openai/codex-win32-x64/vendor/x86_64-pc-windows-msvc/bin/codex.exe", "fixture");
|
||||
Assert.Equal(binary, CliDiscovery.Find(Provider.Codex, searchPath: directory.Path, windows: true).Command!.FileName);
|
||||
}
|
||||
[Fact]
|
||||
public void ResolvesWindowsNpmNodeFallback()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
directory.Write("codex.cmd", "fixture");
|
||||
var script = directory.Write("node_modules/@openai/codex/bin/codex.js", "fixture");
|
||||
var node = directory.Write("node.exe", "fixture");
|
||||
var command = CliDiscovery.Find(Provider.Codex, searchPath: directory.Path, windows: true).Command;
|
||||
Assert.NotNull(command);
|
||||
Assert.Equal(node, command.FileName);
|
||||
Assert.Equal(script, Assert.Single(command.PrefixArguments));
|
||||
}
|
||||
[Fact]
|
||||
public void LinuxNativeAndNodeShebangWork()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
var binary = directory.Write("codex", "ELF fixture");
|
||||
Assert.Equal(binary, CliDiscovery.Find(Provider.Codex, overridePath: binary, searchPath: directory.Path, windows: false).Command!.FileName);
|
||||
directory.Write("codex", "#!/usr/bin/env node\nfixture");
|
||||
var node = directory.Write("node", "fixture");
|
||||
var command = CliDiscovery.Find(Provider.Codex, overridePath: binary, searchPath: directory.Path, windows: false).Command;
|
||||
Assert.Equal(node, command!.FileName);
|
||||
Assert.Equal(binary, Assert.Single(command.PrefixArguments));
|
||||
}
|
||||
[Fact]
|
||||
public void MissingCliAndUnsupportedWrapperAreUnavailable()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
Assert.Null(CliDiscovery.Find(Provider.Claude, searchPath: directory.Path, windows: true).Command);
|
||||
directory.Write("codex.cmd", "fixture");
|
||||
Assert.Null(CliDiscovery.Find(Provider.Codex, searchPath: directory.Path, windows: true).Command);
|
||||
}
|
||||
[Fact]
|
||||
public void InvalidOverrideBecomesUnavailableInsteadOfStoppingRefresh()
|
||||
{
|
||||
Assert.Null(CliDiscovery.Find(Provider.Claude, "invalid\0path", windows: true).Command);
|
||||
}
|
||||
[Theory]
|
||||
[InlineData(InstallMode.Off, PluginInstallState.NotInstalled, InstallAction.Nothing)]
|
||||
[InlineData(InstallMode.Ask, PluginInstallState.NotInstalled, InstallAction.Ask)]
|
||||
[InlineData(InstallMode.Automatic, PluginInstallState.Outdated, InstallAction.Install)]
|
||||
[InlineData(InstallMode.Automatic, PluginInstallState.NoHostFound, InstallAction.Nothing)]
|
||||
[InlineData(InstallMode.Automatic, PluginInstallState.NoShippedPlugin, InstallAction.Nothing)]
|
||||
[InlineData(InstallMode.Automatic, PluginInstallState.UpToDate, InstallAction.Nothing)]
|
||||
public void InstallPolicyHonorsModeAndStatus(InstallMode mode, PluginInstallState state, InstallAction expected) =>
|
||||
Assert.Equal(expected, InstallPolicy.Decide(mode, new(state, "1.0", "0.9"), null));
|
||||
[Fact] public void AskHonorsDismissedVersion() => Assert.Equal(InstallAction.Nothing, InstallPolicy.Decide(InstallMode.Ask, new(PluginInstallState.Outdated, "1.0"), "1.0"));
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
using FinalToken.Core.Collectors;
|
||||
using FinalToken.Core.Processes;
|
||||
using Xunit;
|
||||
|
||||
namespace FinalToken.Core.Tests;
|
||||
|
||||
public class EngineTests
|
||||
{
|
||||
private static RefreshEngine Engine(TestDirectory directory, TestClock clock, FakeRunner runner) =>
|
||||
new(directory.Path, clock, runner, Path.Combine(directory.Path, "claude"), Path.Combine(directory.Path, "codex"),
|
||||
(_, _) => new(new("fixture.exe", []), null));
|
||||
[Fact]
|
||||
public async Task SchedulerDebouncesChangesAndRunsPeriodicScansWithoutOverprobing()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
var clock = new TestClock();
|
||||
var runner = new FakeRunner();
|
||||
await using var engine = Engine(directory, clock, runner);
|
||||
var snapshots = 0;
|
||||
engine.SnapshotChanged += _ => snapshots++;
|
||||
await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||
Assert.Equal(2, runner.Requests.Count);
|
||||
engine.NotifySourceChanged();
|
||||
clock.Advance(TimeSpan.FromSeconds(1));
|
||||
await engine.TickAsync(TestContext.Current.CancellationToken);
|
||||
Assert.Equal(1, snapshots);
|
||||
engine.NotifySourceChanged();
|
||||
clock.Advance(TimeSpan.FromSeconds(1));
|
||||
await engine.TickAsync(TestContext.Current.CancellationToken);
|
||||
Assert.Equal(1, snapshots);
|
||||
clock.Advance(TimeSpan.FromSeconds(1));
|
||||
await engine.TickAsync(TestContext.Current.CancellationToken);
|
||||
Assert.Equal(2, snapshots);
|
||||
Assert.Equal(2, runner.Requests.Count);
|
||||
clock.Advance(TimeSpan.FromMinutes(1));
|
||||
await engine.TickAsync(TestContext.Current.CancellationToken);
|
||||
Assert.Equal(3, snapshots);
|
||||
clock.Advance(TimeSpan.FromMinutes(4));
|
||||
await engine.TickAsync(TestContext.Current.CancellationToken);
|
||||
Assert.Equal(4, runner.Requests.Count);
|
||||
}
|
||||
[Fact]
|
||||
public async Task TokensTriggerProbeWithOneMinuteThrottlePerProvider()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
var clock = new TestClock();
|
||||
var runner = new FakeRunner();
|
||||
await using var engine = Engine(directory, clock, runner);
|
||||
await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||
var path = directory.Write("claude/projects/p/a.jsonl", Fixtures.Claude());
|
||||
clock.Advance(TimeSpan.FromSeconds(30));
|
||||
await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||
Assert.Equal(2, runner.Requests.Count);
|
||||
await File.AppendAllTextAsync(path, Fixtures.Claude("b"), TestContext.Current.CancellationToken);
|
||||
clock.Advance(TimeSpan.FromSeconds(30));
|
||||
await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||
Assert.Equal(3, runner.Requests.Count);
|
||||
Assert.False(runner.Requests[^1].CodexRpc);
|
||||
}
|
||||
[Fact]
|
||||
public async Task ThrottledTokenProbeRemainsPendingWithoutAnotherTokenEvent()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
var clock = new TestClock();
|
||||
var runner = new FakeRunner();
|
||||
await using var engine = Engine(directory, clock, runner);
|
||||
await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||
directory.Write("claude/projects/p/a.jsonl", Fixtures.Claude());
|
||||
clock.Advance(TimeSpan.FromSeconds(30));
|
||||
await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||
Assert.Equal(2, runner.Requests.Count);
|
||||
clock.Advance(TimeSpan.FromSeconds(30));
|
||||
await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||
Assert.Equal(3, runner.Requests.Count);
|
||||
}
|
||||
[Fact]
|
||||
public async Task FailedProbeKeepsLastGoodSampleWithItsAge()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
var clock = new TestClock();
|
||||
var runner = new FakeRunner();
|
||||
await using var engine = Engine(directory, clock, runner);
|
||||
await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||
var original = engine.CurrentSnapshot!.Providers[0].Windows[0].Window;
|
||||
runner.Handler = (_, _) => Task.FromResult(new ProcessResult(-1, "", TimedOut: true));
|
||||
clock.Advance(TimeSpan.FromMinutes(5));
|
||||
var snapshot = await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||
Assert.Equal(original, snapshot.Providers[0].Windows[0].Window);
|
||||
Assert.Equal(TimeSpan.FromMinutes(5), snapshot.Providers[0].Windows[0].Age(clock.GetUtcNow()));
|
||||
Assert.Equal(ProviderStatus.Unavailable, snapshot.Providers[0].Status);
|
||||
Assert.Contains(engine.RecentDiagnostics, d => d.Code == "probe-timeout");
|
||||
}
|
||||
[Fact]
|
||||
public async Task StopCancelsAndWaitsForRunningProbe()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
var clock = new TestClock();
|
||||
var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var stopped = false;
|
||||
var runner = new FakeRunner { Handler = async (_, token) =>
|
||||
{
|
||||
started.SetResult();
|
||||
try { await Task.Delay(Timeout.InfiniteTimeSpan, token); }
|
||||
finally { stopped = true; }
|
||||
return new(0, "");
|
||||
} };
|
||||
await using var engine = Engine(directory, clock, runner);
|
||||
await engine.StartAsync(TestContext.Current.CancellationToken);
|
||||
await started.Task.WaitAsync(TestContext.Current.CancellationToken);
|
||||
await engine.StopAsync();
|
||||
Assert.True(stopped);
|
||||
Assert.Null(engine.CurrentSnapshot);
|
||||
}
|
||||
[Fact]
|
||||
public async Task NoProbeAndDisabledProvidersNeverStartProcesses()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
var clock = new TestClock();
|
||||
var runner = new FakeRunner();
|
||||
await using var engine = Engine(directory, clock, runner);
|
||||
await engine.RefreshNowAsync(true, TestContext.Current.CancellationToken);
|
||||
Assert.Empty(runner.Requests);
|
||||
await engine.UpdateSettingsAsync(new Settings { Claude = new() { Enabled = false }, Codex = new() { Enabled = false } }, TestContext.Current.CancellationToken);
|
||||
var snapshot = await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||
Assert.Empty(runner.Requests);
|
||||
Assert.All(snapshot.Providers, p => Assert.Equal(ProviderStatus.Disabled, p.Status));
|
||||
}
|
||||
[Fact]
|
||||
public async Task ActivationIsRaisedOncePerRequestAndEventsRunOffCallerContext()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
await using var engine = Engine(directory, new(), new());
|
||||
var activations = 0;
|
||||
var context = new SynchronizationContext();
|
||||
var previousContext = SynchronizationContext.Current;
|
||||
try
|
||||
{
|
||||
SynchronizationContext.SetSynchronizationContext(context);
|
||||
engine.ActivationRequested += () => { Assert.NotSame(context, SynchronizationContext.Current); activations++; };
|
||||
await ActivationFile.RequestAsync(directory.Path, TestContext.Current.CancellationToken);
|
||||
await engine.TickAsync(TestContext.Current.CancellationToken);
|
||||
await engine.TickAsync(TestContext.Current.CancellationToken);
|
||||
Assert.Equal(1, activations);
|
||||
}
|
||||
finally { SynchronizationContext.SetSynchronizationContext(previousContext); }
|
||||
}
|
||||
[Fact]
|
||||
public async Task ProbeUsesExactClaudeArgumentsWorkingDirectoryAndTimeout()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
var runner = new FakeRunner();
|
||||
var probe = new LimitProbe(runner, new(), directory.Path);
|
||||
var result = await probe.RunAsync(Provider.Claude, new("fixture", []), new TestClock().GetUtcNow(), TestContext.Current.CancellationToken);
|
||||
Assert.True(result.Success);
|
||||
var request = Assert.Single(runner.Requests);
|
||||
Assert.Equal(["-p", "/usage", "--output-format", "json", "--no-session-persistence"], request.Arguments);
|
||||
Assert.Equal(directory.Path, request.WorkingDirectory);
|
||||
Assert.Equal(TimeSpan.FromSeconds(60), request.Timeout);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
<UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner>
|
||||
<TestingPlatformDotnetTestSupport>true</TestingPlatformDotnetTestSupport>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="xunit.v3.aot.mtp-v2" />
|
||||
<ProjectReference Include="../../src/FinalToken.Core/FinalToken.Core.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,73 @@
|
||||
using Xunit;
|
||||
|
||||
namespace FinalToken.Core.Tests;
|
||||
|
||||
public class PaceTests
|
||||
{
|
||||
private static readonly DateTimeOffset Now = new(2026, 10, 14, 16, 0, 0, TimeSpan.Zero);
|
||||
private static LimitWindow Window(double used, double elapsed = 0.5) => new(Provider.Claude, "session", "Session",
|
||||
used, Now + TimeSpan.FromHours(5 * (1 - elapsed)), TimeSpan.FromHours(5), Now, "fixture");
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 0, PaceState.OnTrack)]
|
||||
[InlineData(0, 0.5, PaceState.Behind)]
|
||||
[InlineData(60, 0.5, PaceState.Ahead)]
|
||||
[InlineData(50, 0.5, PaceState.OnTrack)]
|
||||
[InlineData(10, 0.4, PaceState.OnTrack)]
|
||||
[InlineData(0, 1.2, PaceState.Behind)]
|
||||
public void CalculatesStates(double used, double elapsed, PaceState expected) =>
|
||||
Assert.Equal(expected, Pace.Calculate(Window(used, elapsed), Now).State);
|
||||
[Fact] public void ClampsElapsedAfterReset() => Assert.Equal(1, Pace.Calculate(Window(50, 2), Now).ElapsedFraction);
|
||||
[Fact] public void MissingLengthIsUnknown() => Assert.Equal(PaceState.Unknown, Pace.Calculate(Window(40) with { Length = null }, Now).State);
|
||||
[Fact] public void MissingResetIsUnknown() => Assert.Equal(PaceState.Unknown, Pace.Calculate(Window(40) with { ResetsAt = null }, Now).State);
|
||||
[Fact] public void AheadProjectionPrecedesReset()
|
||||
{
|
||||
var window = Window(80);
|
||||
Assert.Equal(Now.AddMinutes(37.5), Pace.Calculate(window, Now).Projection);
|
||||
Assert.True(Pace.Calculate(window, Now).Projection < window.ResetsAt);
|
||||
}
|
||||
[Fact] public void ProjectionAfterResetIsHidden() => Assert.Null(Pace.Calculate(Window(10), Now).Projection);
|
||||
[Fact] public void ZeroElapsedDoesNotProject() => Assert.Null(Pace.Calculate(Window(50, 0), Now).Projection);
|
||||
[Fact] public void ZeroUsageDoesNotProject() => Assert.Null(Pace.Calculate(Window(0), Now).Projection);
|
||||
|
||||
[Fact]
|
||||
public void PopupHysteresisPreventsFlappingAndRearmsAfterClear()
|
||||
{
|
||||
var machine = new PopupDecider();
|
||||
var settings = new Settings();
|
||||
Assert.NotNull(machine.Observe(Window(60), Pace.Calculate(Window(60), Now), settings));
|
||||
Assert.Null(machine.Observe(Window(59), Pace.Calculate(Window(59), Now), settings));
|
||||
Assert.Null(machine.Observe(Window(60), Pace.Calculate(Window(60), Now), settings));
|
||||
Assert.Null(machine.Observe(Window(57), Pace.Calculate(Window(57), Now), settings));
|
||||
Assert.NotNull(machine.Observe(Window(60), Pace.Calculate(Window(60), Now), settings));
|
||||
}
|
||||
[Fact]
|
||||
public void BehindHasHysteresisAndIndependentProviderState()
|
||||
{
|
||||
var machine = new PopupDecider();
|
||||
var settings = new Settings();
|
||||
Assert.NotNull(machine.Observe(Window(40), Pace.Calculate(Window(40), Now), settings));
|
||||
Assert.Null(machine.Observe(Window(41), Pace.Calculate(Window(41), Now), settings));
|
||||
Assert.NotNull(machine.Observe(Window(40) with { Provider = Provider.Codex }, Pace.Calculate(Window(40), Now), settings));
|
||||
Assert.Null(machine.Observe(Window(43), Pace.Calculate(Window(43), Now), settings));
|
||||
Assert.NotNull(machine.Observe(Window(40), Pace.Calculate(Window(40), Now), settings));
|
||||
}
|
||||
[Fact]
|
||||
public void PopupHonorsProviderAndStateSettings()
|
||||
{
|
||||
var window = Window(60);
|
||||
Assert.Null(new PopupDecider().Observe(window, Pace.Calculate(window, Now), new Settings { PopupAhead = false }));
|
||||
Assert.Null(new PopupDecider().Observe(window, Pace.Calculate(window, Now), new Settings { Claude = new() { PopupsEnabled = false } }));
|
||||
Assert.Null(new PopupDecider().Observe(window, Pace.Calculate(window, Now), new Settings { Claude = new() { Enabled = false } }));
|
||||
Assert.Null(new PopupDecider().Observe(Window(40), Pace.Calculate(Window(40), Now), new Settings { PopupBehind = false }));
|
||||
}
|
||||
[Fact]
|
||||
public void ProviderStateTogglesDoNotDisableOtherProviders()
|
||||
{
|
||||
var settings = new Settings { Claude = new() { PopupAhead = false, PopupBehind = false } };
|
||||
var machine = new PopupDecider();
|
||||
Assert.Null(machine.Observe(Window(60), Pace.Calculate(Window(60), Now), settings));
|
||||
Assert.Null(machine.Observe(Window(40), Pace.Calculate(Window(40), Now), settings));
|
||||
Assert.NotNull(machine.Observe(Window(60) with { Provider = Provider.Codex }, Pace.Calculate(Window(60), Now), settings));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
using FinalToken.Core.Collectors;
|
||||
using Xunit;
|
||||
|
||||
namespace FinalToken.Core.Tests;
|
||||
|
||||
public class ParserTests
|
||||
{
|
||||
private static readonly DateTimeOffset Now = new(2026, 10, 14, 16, 0, 0, TimeSpan.Zero);
|
||||
[Fact]
|
||||
public void TranscriptReturnsOnlyMetadataAndCorrectCacheTotal()
|
||||
{
|
||||
var usage = TranscriptParser.Parse(Fixtures.Claude(), new());
|
||||
Assert.NotNull(usage);
|
||||
Assert.Equal(new TokenCounts(10, 3, 4, 2, 0, 19), usage.Counts);
|
||||
Assert.Equal("fixture-model", usage.Model);
|
||||
Assert.Equal("/project", usage.Project);
|
||||
}
|
||||
[Theory]
|
||||
[InlineData("{")]
|
||||
[InlineData("[]")]
|
||||
[InlineData("null")]
|
||||
[InlineData("{\"type\":\"assistant\",\"message\":{\"usage\":{\"input_tokens\":-1}}}")]
|
||||
public void TranscriptMalformedInputDoesNotThrow(string line) => Assert.Null(TranscriptParser.Parse(line, new()));
|
||||
[Fact]
|
||||
public void TranscriptMalformedUsageReportsDiagnostic()
|
||||
{
|
||||
var diagnostics = new DiagnosticLog();
|
||||
Assert.Null(TranscriptParser.Parse(Fixtures.Claude().Replace("\"input_tokens\":10", "\"input_tokens\":-1"), diagnostics));
|
||||
Assert.Single(diagnostics.Recent);
|
||||
}
|
||||
[Theory]
|
||||
[InlineData("Current session: 28% used · resets Oct 14, 7:30pm (Europe/Berlin)", 5, 17, 30)]
|
||||
[InlineData("Current week (all models): 66% used · resets Oct 18, 8pm (Europe/Berlin)", 168, 18, 0)]
|
||||
[InlineData("Current week (Fable): 0% used • resets Oct 18, 8:00pm (Europe/Berlin)", 168, 18, 0)]
|
||||
public void ClaudeUsageParsesKnownFormatsAndIanaZone(string line, int hours, int resetHour, int resetMinute)
|
||||
{
|
||||
var window = Assert.Single(ClaudeUsageParser.ParseText(line, Now, new()));
|
||||
Assert.Equal(TimeSpan.FromHours(hours), window.Length);
|
||||
Assert.Equal(resetHour, window.ResetsAt!.Value.Hour);
|
||||
Assert.Equal(resetMinute, window.ResetsAt.Value.Minute);
|
||||
}
|
||||
[Fact]
|
||||
public void ClaudeInfersNewYearWithinWindow()
|
||||
{
|
||||
var windows = ClaudeUsageParser.ParseText("Current week (all models): 10% used · resets Jan 2, 8pm (Europe/Berlin)",
|
||||
new(2026, 12, 31, 16, 0, 0, TimeSpan.Zero), new());
|
||||
Assert.Equal(2027, Assert.Single(windows).ResetsAt!.Value.Year);
|
||||
}
|
||||
[Theory]
|
||||
[InlineData("Current session: 101% used · resets Oct 14, 7:30pm (Europe/Berlin)")]
|
||||
[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")]
|
||||
public void ClaudeUnknownFormatsBecomeDiagnostics(string line)
|
||||
{
|
||||
var diagnostics = new DiagnosticLog();
|
||||
Assert.Empty(ClaudeUsageParser.ParseText(line, Now, diagnostics));
|
||||
Assert.Single(diagnostics.Recent);
|
||||
}
|
||||
[Fact] public void ClaudeEnvelopeIsLocalAndZeroTurns() => Assert.Equal(2, ClaudeUsageParser.ParseEnvelope(Fixtures.ClaudeEnvelope, Now, new()).Count);
|
||||
[Theory]
|
||||
[InlineData("{")]
|
||||
[InlineData("{\"is_error\":true}")]
|
||||
[InlineData("{\"local_command\":\"usage\",\"num_turns\":1,\"is_error\":false,\"result\":\"x\"}")]
|
||||
public void ClaudeRejectsInvalidEnvelope(string json) => Assert.Empty(ClaudeUsageParser.ParseEnvelope(json, Now, new()));
|
||||
[Fact]
|
||||
public void RolloutTracksModelAndProjectAndCumulativeCounts()
|
||||
{
|
||||
var cursor = new ScanCursor();
|
||||
foreach (var line in Fixtures.Meta.Split('\n', StringSplitOptions.RemoveEmptyEntries)) RolloutParser.Parse(line, cursor, Now, new());
|
||||
var entry = RolloutParser.Parse(Fixtures.Codex(10), cursor, Now, new());
|
||||
Assert.Equal("session-1", cursor.SessionId);
|
||||
Assert.Equal("fixture-model", entry.CumulativeUsage!.Model);
|
||||
Assert.Equal(12, entry.CumulativeUsage.Counts.Total);
|
||||
Assert.Equal("codex:primary", Assert.Single(entry.Limits).Id);
|
||||
}
|
||||
[Theory]
|
||||
[InlineData("{")]
|
||||
[InlineData("null")]
|
||||
[InlineData("[]")]
|
||||
[InlineData("{\"type\":\"event_msg\",\"payload\":{\"type\":\"token_count\"}}")]
|
||||
public void RolloutMalformedInputIsTotal(string line) => Assert.Null(RolloutParser.Parse(line, new(), Now, new()).CumulativeUsage);
|
||||
[Fact]
|
||||
public void CodexReadsSchemaCamelCaseResponse()
|
||||
{
|
||||
var window = Assert.Single(CodexLimitsParser.ParseResponse(Fixtures.CodexResponse, Now, new()));
|
||||
Assert.Equal(24, window.UsedPercent);
|
||||
Assert.Equal(TimeSpan.FromDays(7), window.Length);
|
||||
}
|
||||
[Fact]
|
||||
public void CodexReadsMultipleBuckets()
|
||||
{
|
||||
var json = "{\"result\":{\"rateLimitsByLimitId\":{\"a\":{\"limitId\":\"a\",\"primary\":{\"usedPercent\":1}},\"b\":{\"limitId\":\"b\",\"secondary\":{\"usedPercent\":2}}}}}";
|
||||
var windows = CodexLimitsParser.ParseResponse(json, Now, new());
|
||||
Assert.Equal(2, windows.Count);
|
||||
Assert.All(windows, w => Assert.Null(w.Length));
|
||||
}
|
||||
[Fact] public void CodexRejectsInvalidWindow() => Assert.Empty(CodexLimitsParser.ParseResponse(Fixtures.CodexResponse.Replace("\"usedPercent\":24", "\"usedPercent\":-1"), Now, new()));
|
||||
[Fact] public void DiagnosticsAreBoundedAndExcludeInput()
|
||||
{
|
||||
var diagnostics = new DiagnosticLog(capacity: 2);
|
||||
for (var i = 0; i < 4; i++) TranscriptParser.Parse("private fixture text", diagnostics);
|
||||
Assert.Equal(2, diagnostics.Recent.Count);
|
||||
Assert.All(diagnostics.Recent, d => Assert.DoesNotContain("private fixture", d.Summary));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
using FinalToken.Core.Processes;
|
||||
using Xunit;
|
||||
|
||||
namespace FinalToken.Core.Tests;
|
||||
|
||||
public class ProcessTests
|
||||
{
|
||||
private static ProcessRequest LongProcess(string directory) => OperatingSystem.IsWindows()
|
||||
? new(new(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "ping.exe"), []), ["-n", "30", "127.0.0.1"], directory, TimeSpan.FromSeconds(60))
|
||||
: new(new("sleep", []), ["30"], directory, TimeSpan.FromSeconds(60));
|
||||
[Fact]
|
||||
public async Task FakeClockTimeoutTerminatesChild()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
var clock = new TestClock();
|
||||
var task = new ProcessRunner(clock).RunAsync(LongProcess(directory.Path), TestContext.Current.CancellationToken);
|
||||
clock.Advance(TimeSpan.FromSeconds(61));
|
||||
Assert.True((await task).TimedOut);
|
||||
}
|
||||
[Fact]
|
||||
public async Task CancellationTerminatesAndWaitsForChild()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
using var cancelled = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
|
||||
var task = new ProcessRunner().RunAsync(LongProcess(directory.Path), cancelled.Token);
|
||||
await cancelled.CancelAsync();
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => task);
|
||||
}
|
||||
[Fact]
|
||||
public async Task CaptureIsBoundedWithoutBlockingTheChild()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
var result = await new ProcessRunner().RunAsync(new(new("dotnet", []), ["--info"], directory.Path,
|
||||
TimeSpan.FromSeconds(10), OutputLimit: 50), TestContext.Current.CancellationToken);
|
||||
Assert.Equal(0, result.ExitCode);
|
||||
Assert.Equal(50, result.Output.Length);
|
||||
Assert.True(result.OutputTruncated);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
using FinalToken.Core.Collectors;
|
||||
using Xunit;
|
||||
|
||||
namespace FinalToken.Core.Tests;
|
||||
|
||||
public class StorageTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task TranscriptAppendShrinkReplaceAndRestartDoNotDoubleCount()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
var source = directory.Write("claude/projects/p/session.jsonl", Fixtures.Claude());
|
||||
var history = new HistoryStore(directory.Path, new());
|
||||
var scanner = new IncrementalScanner(history, new(), Path.Combine(directory.Path, "claude"), Path.Combine(directory.Path, "codex"));
|
||||
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||
await File.AppendAllTextAsync(source, Fixtures.Claude("b"), cancellationToken: TestContext.Current.CancellationToken);
|
||||
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||
await history.SaveAsync(TestContext.Current.CancellationToken);
|
||||
history = new(directory.Path, new());
|
||||
scanner = new(history, new(), Path.Combine(directory.Path, "claude"), Path.Combine(directory.Path, "codex"));
|
||||
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||
await File.WriteAllTextAsync(source, Fixtures.Claude(), cancellationToken: TestContext.Current.CancellationToken);
|
||||
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||
await File.WriteAllTextAsync(source, Fixtures.Claude("c"), cancellationToken: TestContext.Current.CancellationToken);
|
||||
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||
directory.Write("claude/projects/other/copied.jsonl", Fixtures.Claude("b"));
|
||||
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||
Assert.Equal(57, history.Total(Provider.Claude, DateTimeOffset.MinValue, DateTimeOffset.MaxValue).Total);
|
||||
}
|
||||
[Fact]
|
||||
public async Task IncompleteLineIsReadOnlyWhenCompleted()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
var fixture = Fixtures.Claude();
|
||||
var source = directory.Write("claude/projects/p/session.jsonl", fixture[..30]);
|
||||
var history = new HistoryStore(directory.Path, new());
|
||||
var scanner = new IncrementalScanner(history, new(), Path.Combine(directory.Path, "claude"), directory.Path);
|
||||
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||
await File.AppendAllTextAsync(source, fixture[30..], cancellationToken: TestContext.Current.CancellationToken);
|
||||
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||
}
|
||||
[Fact]
|
||||
public async Task CodexCountsIncreasesAndDeduplicatesArchivedCopyAcrossRestart()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
var first = Fixtures.Meta + Fixtures.Codex(10);
|
||||
var source = directory.Write("codex/sessions/rollout-a.jsonl", first);
|
||||
var history = new HistoryStore(directory.Path, new());
|
||||
var scanner = new IncrementalScanner(history, new(), directory.Path, Path.Combine(directory.Path, "codex"));
|
||||
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||
await File.AppendAllTextAsync(source, Fixtures.Codex(10, "2026-10-14T16:01:00Z") + Fixtures.Codex(20, "2026-10-14T16:02:00Z"), cancellationToken: TestContext.Current.CancellationToken);
|
||||
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||
Assert.Equal(22, history.Total(Provider.Codex, DateTimeOffset.MinValue, DateTimeOffset.MaxValue).Total);
|
||||
await history.SaveAsync(TestContext.Current.CancellationToken);
|
||||
history = new(directory.Path, new());
|
||||
scanner = new(history, new(), directory.Path, Path.Combine(directory.Path, "codex"));
|
||||
directory.Write("codex/archived_sessions/rollout-a.jsonl", await File.ReadAllTextAsync(source, cancellationToken: TestContext.Current.CancellationToken));
|
||||
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||
Assert.Single((await scanner.ScanAsync(TestContext.Current.CancellationToken)).CodexFallback);
|
||||
Assert.Equal(22, history.Total(Provider.Codex, DateTimeOffset.MinValue, DateTimeOffset.MaxValue).Total);
|
||||
}
|
||||
[Fact]
|
||||
public async Task CodexHandlesCumulativeCounterResetWithoutLosingLaterIncrease()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
directory.Write("codex/sessions/rollout-a.jsonl", Fixtures.Meta + Fixtures.Codex(100) +
|
||||
Fixtures.Codex(10, "2026-10-14T16:01:00Z") + Fixtures.Codex(20, "2026-10-14T16:02:00Z"));
|
||||
var history = new HistoryStore(directory.Path, new());
|
||||
var scanner = new IncrementalScanner(history, new(), directory.Path, Path.Combine(directory.Path, "codex"));
|
||||
await scanner.ScanAsync(TestContext.Current.CancellationToken);
|
||||
Assert.Equal(112, history.Total(Provider.Codex, DateTimeOffset.MinValue, DateTimeOffset.MaxValue).Total);
|
||||
}
|
||||
[Fact]
|
||||
public async Task MalformedLineDoesNotStopValidLaterEntry()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
directory.Write("claude/projects/p/a.jsonl", "{\n" + Fixtures.Claude());
|
||||
var log = new DiagnosticLog();
|
||||
var scanner = new IncrementalScanner(new(directory.Path, log), log, Path.Combine(directory.Path, "claude"), directory.Path);
|
||||
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||
Assert.Single(log.Recent);
|
||||
}
|
||||
[Fact]
|
||||
public async Task LargeValidEntryStillCountsUsage()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
var line = Fixtures.Claude().Replace("{\"type\"", "{\"padding\":\"" + new string('x', 4 * 1024 * 1024) + "\",\"type\"");
|
||||
directory.Write("claude/projects/p/large.jsonl", line);
|
||||
var scanner = new IncrementalScanner(new(directory.Path, new()), new(), Path.Combine(directory.Path, "claude"), directory.Path);
|
||||
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||
}
|
||||
[Fact]
|
||||
public void LockIsExclusiveAndCanBeReacquired()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
using (var first = StoreLock.TryAcquire(directory.Path))
|
||||
{
|
||||
Assert.NotNull(first);
|
||||
Assert.Null(StoreLock.TryAcquire(directory.Path));
|
||||
}
|
||||
using var second = StoreLock.TryAcquire(directory.Path);
|
||||
Assert.NotNull(second);
|
||||
}
|
||||
[Fact]
|
||||
public async Task AtomicWritesReplaceAndCancellationPreservesPriorVersion()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
var path = directory.Write("a.json", "old");
|
||||
await AtomicFile.WriteAsync(path, "new", cancellationToken: TestContext.Current.CancellationToken);
|
||||
Assert.Equal("new", await File.ReadAllTextAsync(path, cancellationToken: TestContext.Current.CancellationToken));
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
cancellation.Cancel();
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => AtomicFile.WriteAsync(path, "lost", cancellation.Token));
|
||||
Assert.Equal("new", await File.ReadAllTextAsync(path, cancellationToken: TestContext.Current.CancellationToken));
|
||||
Assert.Empty(Directory.GetFiles(directory.Path, "*.tmp"));
|
||||
}
|
||||
[Fact]
|
||||
public async Task SettingsRoundTripAndInvalidFallback()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
var log = new DiagnosticLog();
|
||||
Assert.Equal(new Settings(), SettingsFile.Load(directory.Path, log));
|
||||
Assert.Single(log.Recent);
|
||||
var settings = new Settings { StreamDeckInstallMode = InstallMode.Automatic, Claude = new() { Enabled = false } };
|
||||
await SettingsFile.SaveAsync(directory.Path, settings, cancellationToken: TestContext.Current.CancellationToken);
|
||||
Assert.Equal(settings, SettingsFile.Load(directory.Path, new()));
|
||||
directory.Write("settings.json", "{\"probeInterval\":\"00:00:10\"}");
|
||||
Assert.Equal(new Settings(), SettingsFile.Load(directory.Path, new()));
|
||||
directory.Write("settings.json", "{");
|
||||
Assert.Equal(new Settings(), SettingsFile.Load(directory.Path, new()));
|
||||
}
|
||||
[Fact]
|
||||
public async Task SnapshotRoundTripAndThreeIntervalStaleness()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var snapshot = new Snapshot { MadeAt = now, RefreshInterval = TimeSpan.FromSeconds(60), Providers = [] };
|
||||
await SnapshotFile.WriteAsync(directory.Path, snapshot, cancellationToken: TestContext.Current.CancellationToken);
|
||||
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.True(SnapshotFile.Read(directory.Path, now.AddSeconds(181)).IsStale);
|
||||
directory.Write("snapshot.json", "{\"v\":2}");
|
||||
Assert.Null(SnapshotFile.Read(directory.Path).Snapshot);
|
||||
}
|
||||
[Fact]
|
||||
public void CorruptHistoryIsNotSilentlyOverwritten()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
var path = directory.Write("history.json", "{");
|
||||
Assert.Throws<InvalidDataException>(() => new HistoryStore(directory.Path, new()));
|
||||
Assert.Equal("{", File.ReadAllText(path));
|
||||
}
|
||||
[Fact]
|
||||
public void QueriesAggregateByHourDayModelProjectAndLimitWindow()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
var history = new HistoryStore(directory.Path, new());
|
||||
var now = new DateTimeOffset(2026, 10, 14, 16, 30, 0, TimeSpan.Zero);
|
||||
history.Add(new(Provider.Claude, now.AddHours(-1), "a", "/one", new(Total: 10), "a"));
|
||||
history.Add(new(Provider.Claude, now, "b", "/two", new(Total: 20), "b"));
|
||||
history.Add(new(Provider.Codex, now, "b", "/two", new(Total: 99), "c"));
|
||||
var window = new LimitWindow(Provider.Claude, "session", "Session", 20, now.AddHours(1), TimeSpan.FromHours(5), now, "fixture");
|
||||
history.AddLimits([window]);
|
||||
Assert.Equal(2, history.TokenSeries(Provider.Claude, now.AddHours(-2), now.AddHours(1), SeriesInterval.Hour).Count);
|
||||
Assert.Equal(30, Assert.Single(history.TokenSeries(Provider.Claude, now.AddHours(-2), now.AddHours(1), SeriesInterval.Day)).Counts.Total);
|
||||
Assert.Equal("b", history.ByModel(Provider.Claude, now.AddHours(-2), now.AddHours(1))[0].Name);
|
||||
Assert.Equal("/two", history.ByProject(Provider.Claude, now.AddHours(-2), now.AddHours(1))[0].Name);
|
||||
Assert.Single(history.LimitSamples(Provider.Claude, "session", now, now.AddHours(1)));
|
||||
var totals = history.Totals(Provider.Claude, now, window, TimeZoneInfo.Utc);
|
||||
Assert.Equal(30, totals.Today.Total);
|
||||
Assert.Equal(30, totals.Session!.Value.Total);
|
||||
Assert.Equal(30, totals.Week.Total);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LatestLimitSetDoesNotRetainWindowsRemovedByProvider()
|
||||
{
|
||||
using var directory = new TestDirectory();
|
||||
var history = new HistoryStore(directory.Path, new());
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
history.AddLimits([new(Provider.Codex, "codex:primary", "Session", 10, now.AddHours(1), TimeSpan.FromHours(5), now, "rollout"),
|
||||
new(Provider.Codex, "codex:secondary", "Week", 20, now.AddDays(1), TimeSpan.FromDays(7), now, "rollout")]);
|
||||
history.AddLimits([new(Provider.Codex, "codex:primary", "Week", 24, now.AddDays(5), TimeSpan.FromDays(7), now.AddMinutes(1), "app-server")]);
|
||||
Assert.Single(history.LatestLimits(Provider.Codex));
|
||||
Assert.Equal(2, history.LimitSamples(Provider.Codex, "codex:primary", now.AddMinutes(-1), now.AddMinutes(2)).Count);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
using FinalToken.Core.Processes;
|
||||
|
||||
namespace FinalToken.Core.Tests;
|
||||
|
||||
public sealed class TestDirectory : IDisposable
|
||||
{
|
||||
public string Path { get; } = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "finaltoken-test-" + Guid.NewGuid().ToString("N"));
|
||||
public TestDirectory() => Directory.CreateDirectory(Path);
|
||||
public string Write(string relative, string contents)
|
||||
{
|
||||
var path = System.IO.Path.GetFullPath(System.IO.Path.Combine(Path, relative));
|
||||
Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path)!);
|
||||
File.WriteAllText(path, contents);
|
||||
return path;
|
||||
}
|
||||
public void Dispose() => Directory.Delete(Path, true);
|
||||
}
|
||||
|
||||
public sealed class TestClock : TimeProvider
|
||||
{
|
||||
private readonly Lock gate = new();
|
||||
private DateTimeOffset now = new(2026, 10, 14, 16, 0, 0, TimeSpan.Zero);
|
||||
private readonly List<TestTimer> timers = [];
|
||||
public override DateTimeOffset GetUtcNow() { lock (gate) return now; }
|
||||
public void Advance(TimeSpan amount)
|
||||
{
|
||||
List<TestTimer> due;
|
||||
lock (gate)
|
||||
{
|
||||
now += amount;
|
||||
due = timers.Where(t => t.Next <= now && !t.Disposed).ToList();
|
||||
foreach (var timer in due) timer.Next = timer.Period > TimeSpan.Zero ? now + timer.Period : DateTimeOffset.MaxValue;
|
||||
}
|
||||
foreach (var timer in due) timer.Callback(timer.State);
|
||||
}
|
||||
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
var timer = new TestTimer(this, callback, state, period);
|
||||
timer.Change(dueTime, period);
|
||||
timers.Add(timer);
|
||||
return timer;
|
||||
}
|
||||
}
|
||||
private sealed class TestTimer(TestClock owner, TimerCallback callback, object? state, TimeSpan period) : ITimer
|
||||
{
|
||||
public TimerCallback Callback { get; } = callback;
|
||||
public object? State { get; } = state;
|
||||
public TimeSpan Period { get; private set; } = period;
|
||||
public DateTimeOffset Next { get; set; }
|
||||
public bool Disposed { get; private set; }
|
||||
public bool Change(TimeSpan dueTime, TimeSpan newPeriod)
|
||||
{
|
||||
lock (owner.gate)
|
||||
{
|
||||
if (Disposed) return false;
|
||||
Period = newPeriod;
|
||||
Next = dueTime == Timeout.InfiniteTimeSpan ? DateTimeOffset.MaxValue : owner.now + dueTime;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
public void Dispose() { lock (owner.gate) Disposed = true; }
|
||||
public ValueTask DisposeAsync() { Dispose(); return ValueTask.CompletedTask; }
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class FakeRunner : IProcessRunner
|
||||
{
|
||||
public List<ProcessRequest> Requests { get; } = [];
|
||||
public Func<ProcessRequest, CancellationToken, Task<ProcessResult>>? Handler { get; set; }
|
||||
public Task<ProcessResult> RunAsync(ProcessRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
Requests.Add(request);
|
||||
return Handler?.Invoke(request, cancellationToken) ?? Task.FromResult(new ProcessResult(0,
|
||||
request.CodexRpc ? Fixtures.CodexResponse : Fixtures.ClaudeEnvelope));
|
||||
}
|
||||
}
|
||||
|
||||
internal static class Fixtures
|
||||
{
|
||||
public const string ClaudeEnvelope = "{\"local_command\":\"usage\",\"num_turns\":0,\"is_error\":false,\"result\":\"Current session: 28% used · resets Oct 14, 7:30pm (Europe/Berlin)\\nCurrent week (all models): 66% used · resets Oct 18, 8pm (Europe/Berlin)\"}";
|
||||
public const string CodexResponse = "{\"id\":2,\"result\":{\"rateLimits\":{\"limitId\":\"codex\",\"primary\":{\"usedPercent\":24,\"windowDurationMins\":10080,\"resetsAt\":1792479531},\"secondary\":null}}}";
|
||||
public static string Claude(string id = "a", string request = "r", int input = 10, string time = "2026-10-14T16:00:00Z") =>
|
||||
"""{"type":"assistant","timestamp":"@time","cwd":"/project","requestId":"@request","message":{"id":"@id","model":"fixture-model","usage":{"input_tokens":@input,"output_tokens":2,"cache_read_input_tokens":3,"cache_creation_input_tokens":4}}}"""
|
||||
.Replace("@time", time).Replace("@request", request).Replace("@id", id).Replace("@input", input.ToString(System.Globalization.CultureInfo.InvariantCulture)) + "\n";
|
||||
public const string Meta = "{\"type\":\"session_meta\",\"payload\":{\"id\":\"session-1\",\"cwd\":\"/project\"}}\n{\"type\":\"turn_context\",\"payload\":{\"model\":\"fixture-model\"}}\n";
|
||||
public static string Codex(int input, string time = "2026-10-14T16:00:00Z") =>
|
||||
"""{"type":"event_msg","timestamp":"@time","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":@input,"cached_input_tokens":0,"output_tokens":2,"reasoning_output_tokens":1,"total_tokens":@total}},"rate_limits":{"limit_id":"codex","primary":{"used_percent":24,"window_minutes":10080,"resets_at":1792479531},"secondary":null}}}"""
|
||||
.Replace("@time", time).Replace("@input", input.ToString(System.Globalization.CultureInfo.InvariantCulture)).Replace("@total", (input + 2).ToString(System.Globalization.CultureInfo.InvariantCulture)) + "\n";
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
# StreamDeck tests
|
||||
Hand-written fixtures only. xUnit v3 AOT with Microsoft.Testing.Platform.
|
||||
Run `dotnet test --project tests/FinalToken.StreamDeck.Tests -c Release` from the root.
|
||||
Placeholder test; owning worker replaces it.
|
||||
@@ -0,0 +1 @@
|
||||
@AGENTS.md
|
||||
@@ -0,0 +1,12 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
<UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner>
|
||||
<TestingPlatformDotnetTestSupport>true</TestingPlatformDotnetTestSupport>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="xunit.v3.aot.mtp-v2" />
|
||||
<ProjectReference Include="../../src/FinalToken.StreamDeck/FinalToken.StreamDeck.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,3 @@
|
||||
using Xunit;
|
||||
namespace FinalToken.StreamDeck.Tests;
|
||||
public class PlaceholderTests { [Fact] public void FoundationBuilds() => Assert.True(true); }
|
||||
Reference in New Issue
Block a user