diff --git a/src/FinalToken.Core/AGENTS.md b/src/FinalToken.Core/AGENTS.md index daef42e..929b58f 100644 --- a/src/FinalToken.Core/AGENTS.md +++ b/src/FinalToken.Core/AGENTS.md @@ -1,6 +1,8 @@ # 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. +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. Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root. diff --git a/src/FinalToken.Core/Settings.cs b/src/FinalToken.Core/Settings.cs index fb422fa..c4f2d97 100644 --- a/src/FinalToken.Core/Settings.cs +++ b/src/FinalToken.Core/Settings.cs @@ -4,26 +4,28 @@ 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; } + // Setters let source-generated JSON construct defaults before assigning present properties. + public bool Enabled { get; set; } = true; + public bool PopupsEnabled { get; set; } = true; + public bool PopupAhead { get; set; } = true; + public bool PopupBehind { get; set; } = true; + public string? CliPath { get; set; } } 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(); + // Preserve initializers when an older file lacks newly added properties (D5). + public TimeSpan RefreshInterval { get; set; } = TimeSpan.FromSeconds(60); + public TimeSpan ProbeInterval { get; set; } = TimeSpan.FromMinutes(5); + public double PaceThreshold { get; set; } = 10; + public bool PopupAhead { get; set; } = true; + public bool PopupBehind { get; set; } = true; + public InstallMode StreamDeckInstallMode { get; set; } = InstallMode.Ask; + public string? DismissedPluginVersion { get; set; } + public bool StartWithOs { get; set; } + public bool CloseToTray { get; set; } = true; + public ProviderSettings Claude { get; set; } = new(); + public ProviderSettings Codex { get; set; } = 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) && diff --git a/src/FinalToken.Core/Snapshot.cs b/src/FinalToken.Core/Snapshot.cs index 093e147..3e7f93f 100644 --- a/src/FinalToken.Core/Snapshot.cs +++ b/src/FinalToken.Core/Snapshot.cs @@ -11,7 +11,8 @@ public sealed record ProviderSnapshot(Provider Provider, ProviderStatus Status, IReadOnlyList Windows, TokenCounts Today, TokenCounts? Session, TokenCounts Week); 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 TimeSpan RefreshInterval { get; init; } public string? AppPath { get; init; } diff --git a/tests/FinalToken.Core.Tests/PartialSettingsTests.cs b/tests/FinalToken.Core.Tests/PartialSettingsTests.cs new file mode 100644 index 0000000..b39473e --- /dev/null +++ b/tests/FinalToken.Core.Tests/PartialSettingsTests.cs @@ -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); + } +} diff --git a/tests/FinalToken.StreamDeck.Tests/PluginTests.cs b/tests/FinalToken.StreamDeck.Tests/PluginTests.cs index dbdeb97..bd2ac2d 100644 --- a/tests/FinalToken.StreamDeck.Tests/PluginTests.cs +++ b/tests/FinalToken.StreamDeck.Tests/PluginTests.cs @@ -7,6 +7,16 @@ namespace FinalToken.StreamDeck.Tests; 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 Snapshot Snapshot(PaceState state = PaceState.Ahead) => new() {