feat: add FinalToken v1 for Claude and Codex usage #2

Merged
schmidt.florian merged 16 commits from 1-finaltoken-v1 into master 2026-10-14 22:11:22 +02:00
5 changed files with 127 additions and 17 deletions
Showing only changes of commit 9f33dd8896 - Show all commits
+2
View File
@@ -1,6 +1,8 @@
# Core # Core
UI-free domain and file/CLI integration. Implements D1–D7, D9 and the D11 installer contract. 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. Keep parsers total. Only metadata leaves them. JSON uses CoreJsonContext. Hosts own StoreLock.
Persisted defaults use settable properties: source-generated init-only property factories can
overwrite initializers for missing JSON members. Treat settings as values; update them with `with`.
Events from RefreshEngine run on a worker thread; UI hosts must marshal them. 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. Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root.
+18 -16
View File
@@ -4,26 +4,28 @@ namespace FinalToken.Core;
public sealed record ProviderSettings public sealed record ProviderSettings
{ {
public bool Enabled { get; init; } = true; // Setters let source-generated JSON construct defaults before assigning present properties.
public bool PopupsEnabled { get; init; } = true; public bool Enabled { get; set; } = true;
public bool PopupAhead { get; init; } = true; public bool PopupsEnabled { get; set; } = true;
public bool PopupBehind { get; init; } = true; public bool PopupAhead { get; set; } = true;
public string? CliPath { get; init; } public bool PopupBehind { get; set; } = true;
public string? CliPath { get; set; }
} }
public sealed record Settings public sealed record Settings
{ {
public TimeSpan RefreshInterval { get; init; } = TimeSpan.FromSeconds(60); // Preserve initializers when an older file lacks newly added properties (D5).
public TimeSpan ProbeInterval { get; init; } = TimeSpan.FromMinutes(5); public TimeSpan RefreshInterval { get; set; } = TimeSpan.FromSeconds(60);
public double PaceThreshold { get; init; } = 10; public TimeSpan ProbeInterval { get; set; } = TimeSpan.FromMinutes(5);
public bool PopupAhead { get; init; } = true; public double PaceThreshold { get; set; } = 10;
public bool PopupBehind { get; init; } = true; public bool PopupAhead { get; set; } = true;
public InstallMode StreamDeckInstallMode { get; init; } = InstallMode.Ask; public bool PopupBehind { get; set; } = true;
public string? DismissedPluginVersion { get; init; } public InstallMode StreamDeckInstallMode { get; set; } = InstallMode.Ask;
public bool StartWithOs { get; init; } public string? DismissedPluginVersion { get; set; }
public bool CloseToTray { get; init; } = true; public bool StartWithOs { get; set; }
public ProviderSettings Claude { get; init; } = new(); public bool CloseToTray { get; set; } = true;
public ProviderSettings Codex { get; init; } = new(); public ProviderSettings Claude { get; set; } = new();
public ProviderSettings Codex { get; set; } = new();
public ProviderSettings For(Provider provider) => provider == Provider.Claude ? Claude : Codex; public ProviderSettings For(Provider provider) => provider == Provider.Claude ? Claude : Codex;
[System.Text.Json.Serialization.JsonIgnore] [System.Text.Json.Serialization.JsonIgnore]
public bool IsValid => RefreshInterval > TimeSpan.Zero && RefreshInterval <= TimeSpan.FromSeconds(60) && public bool IsValid => RefreshInterval > TimeSpan.Zero && RefreshInterval <= TimeSpan.FromSeconds(60) &&
+2 -1
View File
@@ -11,7 +11,8 @@ public sealed record ProviderSnapshot(Provider Provider, ProviderStatus Status,
IReadOnlyList<WindowSnapshot> Windows, TokenCounts Today, TokenCounts? Session, TokenCounts Week); IReadOnlyList<WindowSnapshot> Windows, TokenCounts Today, TokenCounts? Session, TokenCounts Week);
public sealed record Snapshot public sealed record Snapshot
{ {
public int V { get; init; } = 1; // Keep this initializer for omitted properties in source-generated JSON (D9).
public int V { get; set; } = 1;
public required DateTimeOffset MadeAt { get; init; } public required DateTimeOffset MadeAt { get; init; }
public required TimeSpan RefreshInterval { get; init; } public required TimeSpan RefreshInterval { get; init; }
public string? AppPath { get; init; } public string? AppPath { get; init; }
@@ -0,0 +1,95 @@
using System.Text.Json;
using Xunit;
namespace FinalToken.Core.Tests;
public sealed class PartialSettingsTests
{
[Theory]
[InlineData("{}")]
[InlineData("{\"refreshInterval\":\"00:00:30\"}")]
[InlineData("{\"claude\":{\"enabled\":false},\"codex\":{\"cliPath\":\"fixture\"}}")]
[InlineData("{\"claude\":{},\"codex\":{\"popupBehind\":false}}")]
[InlineData("{\"refreshInterval\":\"00:00:30\",\"future\":123,\"claude\":{\"popupAhead\":false,\"future\":{}}}")]
public void PartialFilesKeepValuesAndDefaultAbsentProperties(string json)
{
using var directory = new TestDirectory();
directory.Write("settings.json", json);
var diagnostics = new DiagnosticLog();
var settings = SettingsFile.Load(directory.Path, diagnostics);
var expected = new Settings();
using var doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("refreshInterval", out _)) expected = expected with { RefreshInterval = TimeSpan.FromSeconds(30) };
if (json.Contains("\"enabled\":false")) expected = expected with { Claude = expected.Claude with { Enabled = false } };
if (json.Contains("\"cliPath\"")) expected = expected with { Codex = expected.Codex with { CliPath = "fixture" } };
if (json.Contains("\"popupAhead\":false")) expected = expected with { Claude = expected.Claude with { PopupAhead = false } };
if (json.Contains("\"popupBehind\":false")) expected = expected with { Codex = expected.Codex with { PopupBehind = false } };
Assert.Equal(expected, settings);
Assert.Empty(diagnostics.Recent);
}
[Theory]
[InlineData("\"Automatic\"", InstallMode.Automatic)]
[InlineData("\"Ask\"", InstallMode.Ask)]
[InlineData("\"Off\"", InstallMode.Off)]
[InlineData("2", InstallMode.Automatic)]
public void InstallModeAcceptsNamesAndExistingNumericFiles(string value, InstallMode expected)
{
using var directory = new TestDirectory();
directory.Write("settings.json", "{\"streamDeckInstallMode\":" + value + "}");
var diagnostics = new DiagnosticLog();
Assert.Equal(new Settings { StreamDeckInstallMode = expected }, SettingsFile.Load(directory.Path, diagnostics));
Assert.Empty(diagnostics.Recent);
}
[Theory]
[InlineData("\"probeInterval\":\"00:00:10\"")]
[InlineData("\"paceThreshold\":0")]
[InlineData("\"probeInterval\":\"invalid\"")]
[InlineData("\"streamDeckInstallMode\":99")]
[InlineData("\"streamDeckInstallMode\":\"Unknown\"")]
[InlineData("\"claude\":null")]
[InlineData("\"codex\":{\"enabled\":\"invalid\"}")]
public void OneInvalidPropertyStillFallsBackForWholeFile(string invalid)
{
using var directory = new TestDirectory();
directory.Write("settings.json", "{\"refreshInterval\":\"00:00:30\"," + invalid + "}");
var diagnostics = new DiagnosticLog();
Assert.Equal(new Settings(), SettingsFile.Load(directory.Path, diagnostics));
Assert.Equal("settings-defaults", Assert.Single(diagnostics.Recent).Code);
}
[Fact]
public void SnapshotKeepsOptionalVersionInitializer()
{
using var directory = new TestDirectory();
directory.Write("snapshot.json", """{"madeAt":"2026-10-14T16:00:00Z","refreshInterval":"00:01:00","providers":[]}""");
var snapshot = SnapshotFile.Read(directory.Path).Snapshot;
Assert.NotNull(snapshot); Assert.Equal(1, snapshot.V); Assert.Null(snapshot.AppPath);
}
[Theory]
[InlineData("{\"v\":1,\"refreshInterval\":\"00:01:00\",\"providers\":[]}")]
[InlineData("{\"v\":1,\"madeAt\":\"2026-10-14T16:00:00Z\",\"providers\":[]}")]
[InlineData("{\"v\":1,\"madeAt\":\"2026-10-14T16:00:00Z\",\"refreshInterval\":\"00:01:00\"}")]
public void SnapshotStillRejectsMissingRequiredFields(string json)
{
using var directory = new TestDirectory();
directory.Write("snapshot.json", json);
Assert.Null(SnapshotFile.Read(directory.Path).Snapshot);
}
[Fact]
public void HistoryTypesKeepDefaultsForAbsentProperties()
{
var state = JsonSerializer.Deserialize("{\"sequence\":2}", CoreJsonContext.Default.HistoryState)!;
Assert.Equal(1, state.V); Assert.Equal(2, state.Sequence);
Assert.Empty(state.ClaudeKeys); Assert.Empty(state.CodexTotals); Assert.Empty(state.CodexTimes);
Assert.Empty(state.Cursors); Assert.Empty(state.LatestWindows); Assert.Empty(state.LastSamples);
var partition = JsonSerializer.Deserialize("{}", CoreJsonContext.Default.HistoryPartition)!;
Assert.Equal(1, partition.V); Assert.Empty(partition.Buckets); Assert.Empty(partition.Limits);
var transaction = JsonSerializer.Deserialize("{\"sequence\":3}", CoreJsonContext.Default.HistoryTransaction)!;
Assert.Equal(1, transaction.V); Assert.Equal(3, transaction.Sequence);
Assert.Empty(transaction.Buckets); Assert.Empty(transaction.Limits); Assert.Empty(transaction.ClaudeKeys);
Assert.Empty(transaction.ExpiredClaudeKeys); Assert.Empty(transaction.CodexTotals); Assert.Empty(transaction.CodexTimes);
Assert.Empty(transaction.Cursors); Assert.Empty(transaction.LatestWindows); Assert.Empty(transaction.LastSamples);
state = JsonSerializer.Deserialize("{\"cursors\":{\"fixture\":{\"model\":\"fixture\"}}}", CoreJsonContext.Default.HistoryState)!;
Assert.Equal(-1, state.Cursors["fixture"].ObservedLength); Assert.Equal("", state.Cursors["fixture"].PrefixHash);
Assert.Empty(state.Cursors["fixture"].LatestLimits);
}
}
@@ -7,6 +7,16 @@ namespace FinalToken.StreamDeck.Tests;
public sealed class PluginTests public sealed class PluginTests
{ {
[Theory]
[InlineData("{}", "Claude", "SessionPercent", "")]
[InlineData("{\"provider\":\"Codex\"}", "Codex", "SessionPercent", "")]
[InlineData("{\"metric\":\"TokensToday\",\"future\":1}", "Claude", "TokensToday", "")]
public void PartialStatSettingsKeepConstructorDefaults(string json, string provider, string metric, string window)
{
var settings = JsonSerializer.Deserialize(json, PluginJsonContext.Default.StatSettings)!;
Assert.Equal(new StatSettings(provider, metric, window), settings);
Assert.True(settings.IsValid);
}
private static readonly DateTimeOffset Now = new(2026, 10, 14, 12, 0, 0, TimeSpan.Zero); private static readonly DateTimeOffset Now = new(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
private static Snapshot Snapshot(PaceState state = PaceState.Ahead) => new() private static Snapshot Snapshot(PaceState state = PaceState.Ahead) => new()
{ {