diff --git a/CHANGELOG.md b/CHANGELOG.md index c8132f6..2e8827c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,26 +10,35 @@ Each entry links to the commit or pull request that introduced the change. ### Added +- A text alternative for Codex quota, reset, trend, and local token data. ([PR #21](https://github.com/TheBeems/CodexUsageDock/pull/21)) - Optional account-scoped quota history with 7/30/90-day retention, explicit CSV/JSON exports, and confirmed deletion. ([PR #20](https://github.com/TheBeems/CodexUsageDock/pull/20)) -- A workday planner with per-day and per-hour quota budgets, measurement evidence, and held-out recent-pace checks. ([PR #20](https://github.com/TheBeems/CodexUsageDock/pull/20)) - Task-level server usage estimates and explicitly confirmed earned resets with account verification and persistent request IDs for safe retries. ([PR #20](https://github.com/TheBeems/CodexUsageDock/pull/20)) - Optional quiet usage alerts from fresh, identified accounts, compact Dock labels, and separate pinnable quota and credit entries with stable identifiers. ([PR #19](https://github.com/TheBeems/CodexUsageDock/pull/19)) - Account-wide daily token activity on compatible Codex versions, with independent refresh and account-identity verification. ([PR #19](https://github.com/TheBeems/CodexUsageDock/pull/19)) -- Explicit executable and Codex home settings, with invalid-source errors and protection against results from a previous profile. ([PR #19](https://github.com/TheBeems/CodexUsageDock/pull/19)) - Separate quota categories and arbitrary window durations from modern Codex responses, while preserving legacy five-hour and weekly limits. ([PR #18](https://github.com/TheBeems/CodexUsageDock/pull/18)) - Safe diagnostics with running-build version, source, freshness, refresh attempts, and reset-field availability. ([PR #18](https://github.com/TheBeems/CodexUsageDock/pull/18)) ### Fixed -- Calculate planner workday budgets from reset and current dates in the same local time zone. ([PR #20](https://github.com/TheBeems/CodexUsageDock/pull/20)) +- Use the regional calendar consistently for the day and month in Dock reset and expiry dates. ([PR #23](https://github.com/TheBeems/CodexUsageDock/pull/23)) +- Switching Dock modes or hiding a metric no longer restores inactive saved bands. Existing band objects are retained, and usage refreshes update their items without reloading the whole provider. ([PR #22](https://github.com/TheBeems/CodexUsageDock/pull/22)) +- Skip inaccessible session subdirectories during local fallback discovery. ([PR #21](https://github.com/TheBeems/CodexUsageDock/pull/21)) +- Serialize source-sensitive presentation changes so delayed updates cannot restore old account values. ([PR #21](https://github.com/TheBeems/CodexUsageDock/pull/21)) - Keep the last confirmed live measurement during outages, without resetting its age or continuing projections and learning. ([PR #18](https://github.com/TheBeems/CodexUsageDock/pull/18)) - Apply one freshness policy across the Dock, details, and forecasts, and keep account/category history isolated. Unidentified legacy history is no longer imported into verified accounts. ([PR #18](https://github.com/TheBeems/CodexUsageDock/pull/18)) ### Changed +- Show the local reset date and next earned-reset expiry directly in fresh Dock subtitles, with short regional month names and minute-precise times. ([PR #23](https://github.com/TheBeems/CodexUsageDock/pull/23)) +- Cache local quota fallback read positions with bounded content reads and memory, while reporting incomplete scans and preserving event-time selection. ([PR #21](https://github.com/TheBeems/CodexUsageDock/pull/21)) - Expanded the release skill to cover scoped commit/push, Store submission, resumable certification tracking, and verified installation, with a repository-local Codex entry point. ([commit e54709c](https://github.com/TheBeems/CodexUsageDock/commit/e54709ce6e26b9aaa072d6f88625a9a3aa067494)) - Distinguish source releases, the running extension build, and Microsoft Store rollout in installation guidance. ([PR #18](https://github.com/TheBeems/CodexUsageDock/pull/18)) +### Removed + +- Remove the workday planner and its workday-end and remaining-workdays settings. Existing planner preferences are ignored and dropped on the next settings save; usage displays, reset times, forecasts, and history remain available. ([commit 263c22a](https://github.com/TheBeems/CodexUsageDock/commit/263c22a650f2b7062515f94e983023e337dc7610)) +- Remove the experimental Claude integration and capture script, manual Codex path settings, and source profiles to keep the extension focused on automatically detected Codex usage. Older source preferences are ignored while other saved Codex choices are preserved. ([commit 39bf74c](https://github.com/TheBeems/CodexUsageDock/commit/39bf74cd476920441146f37737ad1216a9c0b8ad)) + ## [0.6.1] - 2026-09-09 ### Fixed diff --git a/CodexUsageDock.Tests/CachedSessionReaderTests.cs b/CodexUsageDock.Tests/CachedSessionReaderTests.cs new file mode 100644 index 0000000..08ec044 --- /dev/null +++ b/CodexUsageDock.Tests/CachedSessionReaderTests.cs @@ -0,0 +1,419 @@ +using System.Security.AccessControl; +using System.Security.Principal; +using System.Text; +using System.Text.Json; +using Xunit; + +namespace CodexUsageDock.Tests; + +public sealed class CachedSessionReaderTests : IDisposable +{ + private static readonly DateTimeOffset Now = new(2026, 9, 9, 12, 0, 0, TimeSpan.Zero); + private readonly TestEnvironment _environment = new(); + + private string HomePath => _environment.PathFor("cached-codex-home"); + + public void Dispose() => _environment.Dispose(); + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void InaccessibleSubdirectoryDoesNotHideLaterReadableSessions(bool archived) + { + var root = Path.Combine(HomePath, archived ? "archived_sessions" : "sessions"); + var blocked = Directory.CreateDirectory(Path.Combine(root, "000-blocked")); + var readable = Directory.CreateDirectory(Path.Combine(root, "zzz-readable")); + File.WriteAllText(Path.Combine(readable.FullName, "rollout-valid.jsonl"), QuotaLine(Now, 25)); + var originalAccess = blocked.GetAccessControl(); + var deniedAccess = blocked.GetAccessControl(); + using var identity = WindowsIdentity.GetCurrent(); + deniedAccess.AddAccessRule(new FileSystemAccessRule(identity.User!, FileSystemRights.ListDirectory, AccessControlType.Deny)); + try + { + blocked.SetAccessControl(deniedAccess); + Assert.Throws(() => Directory.GetFiles(blocked.FullName)); + var reader = CreateReader(); + + Assert.Equal(25, reader.ReadLatest().Primary!.UsedPercent); + Assert.Equal(25, reader.ReadLatest().Primary!.UsedPercent); + Assert.Equal(0, reader.BytesReadLastScan); + } + finally + { + deniedAccess.SetSecurityDescriptorBinaryForm(originalAccess.GetSecurityDescriptorBinaryForm(), AccessControlSections.Access); + blocked.SetAccessControl(deniedAccess); + } + } + + [Fact] + public void SelectionUsesEventTimeAcrossActiveAndArchivedFilesAndClearsInactiveWindows() + { + WriteSession("rollout-active.jsonl", QuotaLine(Now.AddHours(-2), 70, 40)); + var archived = WriteSession("rollout-archived.jsonl", + QuotaLine(Now.AddMinutes(-10), null, null) + QuotaLine(Now.AddHours(-3), 80, 60), archived: true); + File.SetLastWriteTimeUtc(archived, Now.AddDays(-10).UtcDateTime); + var reader = CreateReader(); + + var result = reader.ReadLatest(); + + Assert.Equal(Now.AddMinutes(-10), result.UpdatedAt); + Assert.Null(result.Primary); + Assert.Null(result.Secondary); + Assert.Null(result.AccountKey); + Assert.Equal(UsageDataSource.LocalSession, result.Source); + Assert.True(reader.LastScanComplete); + Assert.Equal(2, reader.CachedFileCount); + } + + [Fact] + public void UnchangedCachedFilesReadZeroContentBytesEvenWhenTheirContentCannotBeOpened() + { + var path = WriteSession("rollout-one.jsonl", QuotaLine(Now, 25)); + var reader = CreateReader(); + var first = reader.ReadLatest(); + Assert.Equal(new FileInfo(path).Length, reader.BytesReadLastScan); + using var held = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None); + + var unchanged = reader.ReadLatest(); + + Assert.Equal(first, unchanged); + Assert.Equal(0, reader.BytesReadLastScan); + Assert.True(reader.LastScanComplete); + } + + [Fact] + public void AppendingReadsOnlyTheNewBytesAndPreservesTheMeasurementTimestamp() + { + var path = WriteSession("rollout-one.jsonl", QuotaLine(Now.AddHours(-1), 25)); + var reader = CreateReader(); + reader.ReadLatest(); + var appended = QuotaLine(Now.AddMinutes(-5), 45); + File.AppendAllText(path, appended); + + var result = reader.ReadLatest(); + + Assert.Equal(Encoding.UTF8.GetByteCount(appended), reader.BytesReadLastScan); + Assert.Equal(Now.AddMinutes(-5), result.UpdatedAt); + Assert.Equal(45, result.Primary!.UsedPercent); + Assert.True(reader.LastScanComplete); + reader.ReadLatest(); + Assert.Equal(0, reader.BytesReadLastScan); + } + + [Fact] + public void ACompleteJsonObjectWithoutItsNewlineIsNotPublishedUntilTheLineCompletes() + { + var path = WriteSession("rollout-one.jsonl", QuotaLine(Now.AddHours(-1), 25)); + var reader = CreateReader(); + reader.ReadLatest(); + var appended = QuotaLine(Now, 45).TrimEnd('\n'); + File.AppendAllText(path, appended); + + var unfinished = reader.ReadLatest(); + + Assert.Equal(25, unfinished.Primary!.UsedPercent); + Assert.False(reader.LastScanComplete); + Assert.Contains("scan incomplete", unfinished.Error, StringComparison.Ordinal); + reader.ReadLatest(); + Assert.Equal(0, reader.BytesReadLastScan); + File.AppendAllText(path, "\n"); + + var completed = reader.ReadLatest(); + + Assert.Equal(1, reader.BytesReadLastScan); + Assert.Equal(45, completed.Primary!.UsedPercent); + Assert.True(reader.LastScanComplete); + Assert.Null(completed.Error); + } + + [Fact] + public void Utf8CharactersSplitAcrossAppendsAreParsedOnlyAfterTheRecordCompletes() + { + var path = WriteSession("rollout-one.jsonl", QuotaLine(Now.AddHours(-1), 25)); + var reader = CreateReader(); + reader.ReadLatest(); + var appended = Encoding.UTF8.GetBytes(QuotaLine(Now, 40).Replace("\"pro\"", "\"café\"", StringComparison.Ordinal)); + var split = Array.IndexOf(appended, (byte)0xC3) + 1; + Assert.True(split > 0); + using (var stream = new FileStream(path, FileMode.Append, FileAccess.Write)) stream.Write(appended.AsSpan(0, split)); + Assert.Equal(25, reader.ReadLatest().Primary!.UsedPercent); + using (var stream = new FileStream(path, FileMode.Append, FileAccess.Write)) stream.Write(appended.AsSpan(split)); + + var completed = reader.ReadLatest(); + + Assert.Equal("café", completed.PlanType); + Assert.Equal(appended.Length - split, reader.BytesReadLastScan); + Assert.True(reader.LastScanComplete); + } + + [Fact] + public void TruncatingAFileInvalidatesItsPreviousMeasurementAndPartialLine() + { + var path = WriteSession("rollout-one.jsonl", QuotaLine(Now, 95) + new string('x', 4096)); + var reader = CreateReader(); + Assert.Equal(95, reader.ReadLatest().Primary!.UsedPercent); + var replacement = QuotaLine(Now.AddHours(-1), 10); + File.WriteAllText(path, replacement); + + var result = reader.ReadLatest(); + + Assert.Equal(10, result.Primary!.UsedPercent); + Assert.Equal(Now.AddHours(-1), result.UpdatedAt); + Assert.Equal(Encoding.UTF8.GetByteCount(replacement), reader.BytesReadLastScan); + Assert.True(reader.LastScanComplete); + } + + [Fact] + public void RewritingTheSameLengthWithANewModificationTimeInvalidatesTheCheckpoint() + { + var initial = QuotaLine(Now, 95); + var replacement = QuotaLine(Now, 10); + Assert.Equal(initial.Length, replacement.Length); + var path = WriteSession("rollout-one.jsonl", initial); + var reader = CreateReader(); + reader.ReadLatest(); + File.WriteAllText(path, replacement); + File.SetLastWriteTimeUtc(path, Now.AddMinutes(1).UtcDateTime); + + var result = reader.ReadLatest(); + + Assert.Equal(10, result.Primary!.UsedPercent); + Assert.Equal(Encoding.UTF8.GetByteCount(replacement), reader.BytesReadLastScan); + } + + [Fact] + public void AChangedCreationTimeInvalidatesAReplacedFileEvenWhenItGrew() + { + var path = WriteSession("rollout-one.jsonl", QuotaLine(Now, 95)); + File.SetCreationTimeUtc(path, Now.AddDays(-2).UtcDateTime); + var reader = CreateReader(); + reader.ReadLatest(); + var replacement = QuotaLine(Now.AddHours(-1), 10) + "{\"message\":\"replacement\"}\n"; + File.WriteAllText(path, replacement); + File.SetCreationTimeUtc(path, Now.AddDays(-1).UtcDateTime); + + var result = reader.ReadLatest(); + + Assert.Equal(10, result.Primary!.UsedPercent); + Assert.Equal(Now.AddHours(-1), result.UpdatedAt); + Assert.Equal(Encoding.UTF8.GetByteCount(replacement), reader.BytesReadLastScan); + } + + [Fact] + public void DeletingTheLatestFileFallsBackToAnotherCachedMeasurementWithoutRereadingIt() + { + WriteSession("rollout-older.jsonl", QuotaLine(Now.AddHours(-1), 25)); + var newest = WriteSession("rollout-newest.jsonl", QuotaLine(Now, 45)); + var reader = CreateReader(); + Assert.Equal(45, reader.ReadLatest().Primary!.UsedPercent); + File.Delete(newest); + + var result = reader.ReadLatest(); + + Assert.Equal(25, result.Primary!.UsedPercent); + Assert.Equal(0, reader.BytesReadLastScan); + Assert.Equal(1, reader.CachedFileCount); + Assert.True(reader.LastScanComplete); + } + + [Fact] + public void UnreadableFilesAreRetriedAndMalformedOrFutureRecordsDoNotReplaceValidUsage() + { + WriteSession("rollout-readable.jsonl", QuotaLine(Now.AddHours(-1), 25) + + "[\"rate_limits\"]\n{\"rate_limits\":invalid}\n" + QuotaLine(Now.AddHours(1), 99)); + var locked = WriteSession("rollout-locked.jsonl", QuotaLine(Now, 45)); + var reader = CreateReader(); + using (var held = new FileStream(locked, FileMode.Open, FileAccess.Read, FileShare.None)) + { + var result = reader.ReadLatest(); + Assert.Equal(25, result.Primary!.UsedPercent); + Assert.False(reader.LastScanComplete); + Assert.Contains("scan incomplete", result.Error, StringComparison.Ordinal); + } + + var recovered = reader.ReadLatest(); + + Assert.Equal(45, recovered.Primary!.UsedPercent); + Assert.Equal(new FileInfo(locked).Length, reader.BytesReadLastScan); + Assert.True(reader.LastScanComplete); + } + + [Fact] + public void InitialBudgetExhaustionReturnsObservedUsageAndContinuesFromItsCheckpoint() + { + const int budget = 512; + var path = WriteSession("rollout-large.jsonl", QuotaLine(Now.AddHours(-1), 25) + + new string('x', 4096) + "\n" + QuotaLine(Now, 45)); + var reader = CreateReader(maxBytesPerScan: budget, maxLineBytes: 1024, fileReadQuantum: 256); + + var result = reader.ReadLatest(); + long totalBytes = reader.BytesReadLastScan; + + Assert.Equal(25, result.Primary!.UsedPercent); + Assert.Equal(budget, reader.BytesReadLastScan); + Assert.False(reader.LastScanComplete); + Assert.Contains("scan incomplete", result.Error, StringComparison.Ordinal); + for (var scan = 0; scan < 20 && !reader.LastScanComplete; scan++) + { + result = reader.ReadLatest(); + Assert.InRange(reader.BytesReadLastScan, 0, budget); + totalBytes += reader.BytesReadLastScan; + } + Assert.True(reader.LastScanComplete); + Assert.Equal(45, result.Primary!.UsedPercent); + Assert.Equal(new FileInfo(path).Length, totalBytes); + Assert.Null(result.Error); + } + + [Fact] + public void ANewFileReceivesAReadTurnWhileAnOlderLargeFileIsStillPending() + { + WriteSession("rollout-large.jsonl", QuotaLine(Now.AddHours(-1), 25) + new string('x', 50_000) + "\n"); + var reader = CreateReader(maxBytesPerScan: 1024, fileReadQuantum: 512); + Assert.Equal(25, reader.ReadLatest().Primary!.UsedPercent); + WriteSession("rollout-newest.jsonl", QuotaLine(Now, 45)); + + var result = reader.ReadLatest(); + + Assert.Equal(45, result.Primary!.UsedPercent); + Assert.False(reader.LastScanComplete); + Assert.InRange(reader.BytesReadLastScan, 0, 1024); + } + + [Fact] + public void CacheOverflowRotatesFilesAndKeepsTheNewestObservedEventWhenItsCheckpointIsEvicted() + { + for (var index = 0; index < 5; index++) + WriteSession($"rollout-{index}.jsonl", QuotaLine(Now.AddMinutes(index - 5), 20 + index)); + var reader = CreateReader(maxCachedFiles: 2); + CodexUsageSnapshot? result = null; + for (var scan = 0; scan < 8; scan++) + { + result = reader.ReadLatest(); + Assert.InRange(reader.CachedFileCount, 1, 2); + Assert.False(reader.LastScanComplete); + } + + Assert.Equal(24, result!.Primary!.UsedPercent); + Assert.Contains("scan incomplete", result.Error, StringComparison.Ordinal); + Assert.Null(result.AccountKey); + } + + [Fact] + public void OverflowDoesNotEvictEveryPartialRecordBeforeAnyRecordCanFinish() + { + for (var index = 0; index < 3; index++) + WriteSession($"rollout-{index}.jsonl", QuotaLine(Now.AddMinutes(index - 3), 20 + index)); + var reader = CreateReader(maxBytesPerScan: 128, maxCachedFiles: 2, fileReadQuantum: 128); + CodexUsageSnapshot? result = null; + for (var scan = 0; scan < 30; scan++) + { + try { result = reader.ReadLatest(); } + catch (InvalidOperationException) { /* The first complete measurement may require multiple bounded reads. */ } + Assert.InRange(reader.CachedFileCount, 1, 2); + Assert.InRange(reader.BytesReadLastScan, 0, 128); + } + + Assert.NotNull(result); + Assert.Equal(22, result.Primary!.UsedPercent); + } + + [Fact] + public void AnOversizedUnfinishedLineIsDiscardedAndTheNextCompleteRecordCanStillBeRead() + { + var path = WriteSession("rollout-one.jsonl", QuotaLine(Now.AddHours(-1), 25)); + var reader = CreateReader(maxLineBytes: 1024); + reader.ReadLatest(); + File.AppendAllText(path, new string('x', 50_000)); + var unfinished = reader.ReadLatest(); + Assert.Equal(25, unfinished.Primary!.UsedPercent); + Assert.False(reader.LastScanComplete); + File.AppendAllText(path, "\n" + QuotaLine(Now, 45)); + + var result = reader.ReadLatest(); + + Assert.Equal(45, result.Primary!.UsedPercent); + Assert.True(reader.LastScanComplete); + } + + [Fact] + public void PreCancelledReadDoesNotTouchContentOrLoseAnExistingCheckpoint() + { + var path = WriteSession("rollout-one.jsonl", QuotaLine(Now.AddHours(-1), 25)); + var reader = CreateReader(); + reader.ReadLatest(); + var appended = QuotaLine(Now, 45); + File.AppendAllText(path, appended); + + Assert.Throws(() => reader.ReadLatest(new CancellationToken(canceled: true))); + Assert.Equal(0, reader.BytesReadLastScan); + Assert.False(reader.LastScanComplete); + + var result = reader.ReadLatest(); + + Assert.Equal(45, result.Primary!.UsedPercent); + Assert.Equal(Encoding.UTF8.GetByteCount(appended), reader.BytesReadLastScan); + } + + [Fact] + public void CancellationDuringDiscoveryStopsBeforeContentReadsAndCanBeRetried() + { + WriteSession("rollout-one.jsonl", QuotaLine(Now, 25)); + using var cancellation = new CancellationTokenSource(); + var cancelAtClock = true; + var reader = new CachedCodexSessionReader(HomePath, clock: () => + { + if (cancelAtClock) cancellation.Cancel(); + return Now; + }); + + Assert.Throws(() => reader.ReadLatest(cancellation.Token)); + Assert.Equal(0, reader.BytesReadLastScan); + Assert.Equal(0, reader.CachedFileCount); + cancelAtClock = false; + + Assert.Equal(25, reader.ReadLatest().Primary!.UsedPercent); + Assert.True(reader.LastScanComplete); + } + + [Fact] + public void MissingSourcesRemainUnavailableWithoutCreatingAnyDirectories() + { + var reader = CreateReader(); + + Assert.Throws(() => reader.ReadLatest()); + + Assert.False(Directory.Exists(HomePath)); + Assert.Equal(0, reader.BytesReadLastScan); + Assert.Equal(0, reader.CachedFileCount); + } + + private CachedCodexSessionReader CreateReader(long maxBytesPerScan = 8 * 1024 * 1024, + int maxCachedFiles = 512, int maxLineBytes = 128 * 1024, int fileReadQuantum = 64 * 1024) => + new(HomePath, maxBytesPerScan, maxCachedFiles, maxLineBytes, fileReadQuantum, () => Now); + + private string WriteSession(string name, string content, bool archived = false) + { + var directory = Path.Combine(HomePath, archived ? "archived_sessions" : "sessions", "2026", "09", "09"); + Directory.CreateDirectory(directory); + var path = Path.Combine(directory, name); + File.WriteAllText(path, content); + File.SetLastWriteTimeUtc(path, Now.UtcDateTime); + return path; + } + + private static string QuotaLine(DateTimeOffset recordedAt, int? primary, int? secondary = 40) => + JsonSerializer.Serialize(new + { + timestamp = recordedAt, + payload = new + { + rate_limits = new + { + primary = primary is { } shortUsed ? new { used_percent = shortUsed, window_minutes = 300, resets_at = Now.AddHours(4).ToUnixTimeSeconds() } : null, + secondary = secondary is { } weeklyUsed ? new { used_percent = weeklyUsed, window_minutes = 10080, resets_at = Now.AddDays(3).ToUnixTimeSeconds() } : null, + plan_type = "pro", + }, + }, + }) + "\n"; +} diff --git a/CodexUsageDock.Tests/CodexOnlySettingsTests.cs b/CodexUsageDock.Tests/CodexOnlySettingsTests.cs new file mode 100644 index 0000000..5d6cdd0 --- /dev/null +++ b/CodexUsageDock.Tests/CodexOnlySettingsTests.cs @@ -0,0 +1,110 @@ +using System.Text.Json; +using Microsoft.CommandPalette.Extensions; +using Microsoft.CommandPalette.Extensions.Toolkit; +using Xunit; + +namespace CodexUsageDock.Tests; + +public sealed class CodexOnlySettingsTests : IDisposable +{ + private readonly TestEnvironment _environment = new(); + + public void Dispose() => _environment.Dispose(); + + [Theory] + [InlineData("codexExecutablePath")] + [InlineData("codexHomePath")] + [InlineData("sourceLabel")] + [InlineData("enableClaude")] + [InlineData("claudeBridgePath")] + [InlineData("workdayEnd")] + [InlineData("remainingWorkdays")] + public void SettingsDoNotOfferRemovedControls(string key) + { + var settings = _environment.CreateSettings(); + var content = string.Join("\n", settings.GetContent().OfType() + .Select(form => form.TemplateJson + form.DataJson)); + + Assert.DoesNotContain(key, content, StringComparison.Ordinal); + } + + [Fact] + public void SavingLegacySettingsKeepsCodexChoicesAndDropsRemovedPreferences() + { + var legacy = LegacySettings(); + File.WriteAllText(_environment.PathFor("settings.json"), JsonSerializer.Serialize(legacy)); + var settings = _environment.CreateSettings(); + + Assert.False(settings.ShowFiveHourLimit); + Assert.True(settings.CompactDock); + Assert.Equal(TimeSpan.FromMinutes(5), settings.RefreshInterval); + Assert.Null(settings.StatusMessage); + + legacy["refreshInterval"] = "15"; + settings.GetContent().OfType().Last().SubmitForm(JsonSerializer.Serialize(legacy), "{}"); + + using var saved = JsonDocument.Parse(File.ReadAllText(_environment.PathFor("settings.json"))); + foreach (var key in new[] { "codexExecutablePath", "codexHomePath", "sourceLabel", "enableClaude", "claudeBridgePath", "workdayEnd", "remainingWorkdays" }) + { + Assert.False(saved.RootElement.TryGetProperty(key, out _), key); + } + + var restarted = _environment.CreateSettings(); + Assert.False(restarted.ShowFiveHourLimit); + Assert.True(restarted.CompactDock); + Assert.Equal(TimeSpan.FromMinutes(15), restarted.RefreshInterval); + Assert.Null(restarted.StatusMessage); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task LegacyPreferencesDoNotBlockCodexOrRestoreRemovedCommands(bool separate) + { + var legacy = LegacySettings(); + legacy["separateDockItems"] = separate ? "true" : "false"; + File.WriteAllText(_environment.PathFor("settings.json"), JsonSerializer.Serialize(legacy)); + var now = new DateTimeOffset(2026, 9, 13, 12, 0, 0, TimeSpan.Zero); + var quota = new CodexUsageSnapshot(new(25, 300, now.AddHours(4)), new(40, 10080, now.AddDays(3)), + null, null, null, now, UsageDataSource.AppServer, null, AccountKey: "account-a"); + using var service = _environment.CreateService(_ => Task.FromResult(quota), () => CodexUsageSnapshot.Loading, + clock: () => now); + var settings = _environment.CreateSettings(); + using var provider = new CodexUsageDockCommandsProvider(service, settings, _ => { }, () => now); + + await service.RefreshAsync().WaitAsync(TimeSpan.FromSeconds(5)); + + Assert.Equal(UsageDataSource.AppServer, service.Current.Source); + Assert.Equal(quota.AccountKey, service.Current.AccountKey); + Assert.Equal(quota.Primary, service.Current.Primary); + Assert.Equal(quota.Secondary, service.Current.Secondary); + Assert.Null(settings.StatusMessage); + var removedIds = new[] { "nl.mathijs.codexusage.dock.claude", "nl.mathijs.codexusage.claude", "nl.mathijs.codexusage.profiles", "nl.mathijs.codexusage.planner" }; + foreach (var id in removedIds) + { + Assert.Null(provider.GetCommandItem(id)); + Assert.DoesNotContain(provider.TopLevelCommands(), item => item.Command.Id == id); + } + + var expectedIds = separate + ? new[] { "nl.mathijs.codexusage.dock.weekly", "nl.mathijs.codexusage.dock.credits" } + : ["nl.mathijs.codexusage.dock"]; + Assert.Equal(expectedIds, provider.GetDockBands()!.Select(item => item.Command.Id)); + Assert.Contains(provider.TopLevelCommands(), item => item.Command.Id == "nl.mathijs.codexusage.table"); + Assert.All(provider.GetDockBands()!, item => Assert.IsAssignableFrom(item.Command)); + } + + private static Dictionary LegacySettings() => new() + { + ["showFiveHourLimit"] = "false", + ["compactDock"] = "true", + ["refreshInterval"] = "5", + ["codexExecutablePath"] = "removed-invalid-executable-path", + ["codexHomePath"] = "removed-invalid-home-path", + ["sourceLabel"] = "Old source", + ["enableClaude"] = "true", + ["claudeBridgePath"] = "removed-invalid-capture-path", + ["workdayEnd"] = "18:30", + ["remainingWorkdays"] = "5", + }; +} diff --git a/CodexUsageDock.Tests/CodexUsageTableTests.cs b/CodexUsageDock.Tests/CodexUsageTableTests.cs new file mode 100644 index 0000000..2ebf050 --- /dev/null +++ b/CodexUsageDock.Tests/CodexUsageTableTests.cs @@ -0,0 +1,24 @@ +using Xunit; + +namespace CodexUsageDock.Tests; + +public sealed class CodexUsageTableTests +{ + [Fact] + public void TextViewKeepsUnknownZeroExpiredAndUnconfirmedStatesDistinct() + { + var now = new DateTimeOffset(2026, 9, 9, 12, 0, 0, TimeSpan.Zero); + var quota = new CodexUsageSnapshot(new(100, 300, now.AddHours(-1)), null, null, null, new(0, null), + now.AddHours(-2), UsageDataSource.LastConfirmed, null, + [new("extra", "Extra | quota", new(0, 60, now.AddHours(1)), null)], DefaultBucketId: "codex"); + var view = new UsagePresentation(quota, [], [], new([], null), LocalTokenUsageSnapshot.Unavailable, false); + var body = CodexUsageTablePage.Format(view, now, TimeSpan.FromMinutes(1)); + Assert.Contains("LastConfirmed", body, StringComparison.Ordinal); + Assert.Contains("Reset passed; refresh required", body, StringComparison.Ordinal); + Assert.Contains("Not reported", body, StringComparison.Ordinal); + Assert.Contains("0%", body, StringComparison.Ordinal); + Assert.Contains("100%", body, StringComparison.Ordinal); + Assert.Contains("Extra \\| quota", body, StringComparison.Ordinal); + Assert.DoesNotContain("![", body, StringComparison.Ordinal); + } +} diff --git a/CodexUsageDock.Tests/DockDateSubtitleTests.cs b/CodexUsageDock.Tests/DockDateSubtitleTests.cs new file mode 100644 index 0000000..7a5c880 --- /dev/null +++ b/CodexUsageDock.Tests/DockDateSubtitleTests.cs @@ -0,0 +1,62 @@ +using System.Globalization; +using Xunit; + +namespace CodexUsageDock.Tests; + +public sealed class DockDateSubtitleTests +{ + [Theory] + [InlineData("ar-SA")] + [InlineData("fa-IR")] + public void DatesUseTheRegionalCalendarForBothDayAndMonth(string cultureName) + { + var culture = CultureInfo.GetCultureInfo(cultureName); + var local = new DateTimeOffset(2026, 9, 15, 12, 56, 0, TimeSpan.FromHours(2)); + var calendarDay = culture.DateTimeFormat.Calendar.GetDayOfMonth(local.DateTime); + Assert.NotEqual(local.Day, calendarDay); + var expected = $"{calendarDay.ToString(culture)} {local.ToString("MMM", culture).TrimEnd('.')} 12:56"; + + Assert.Equal(expected, UsageDockItem.FormatLocalDateTime(local, culture)); + } + + [Theory] + [InlineData(9, 15, 12, 56, "15 sept 12:56")] + [InlineData(10, 4, 4, 0, "4 okt 4:00")] + [InlineData(1, 1, 0, 5, "1 jan 0:05")] + public void DutchDatesUseAbbreviatedMonthsAndUnpaddedHours(int month, int day, int hour, int minute, string expected) + { + var local = new DateTimeOffset(2026, month, day, hour, minute, 0, TimeSpan.FromHours(2)); + Assert.Equal(expected, UsageDockItem.FormatLocalDateTime(local, CultureInfo.GetCultureInfo("nl-NL"))); + } + + [Theory] + [InlineData("Reset - 15 sept 12:56")] + [InlineData("Expires - 4 okt 4:00")] + public void FreshLiveSubtitleShowsOnlyTheDateDetail(string detail) + { + var now = DateTimeOffset.UnixEpoch.AddDays(1); + var snapshot = CodexUsageSnapshot.Loading with { Source = UsageDataSource.AppServer, UpdatedAt = now.AddMinutes(-10) }; + Assert.Equal(detail, UsageDockItem.FormatLiveDetailOrStatus(snapshot, now, TimeSpan.FromMinutes(15), detail)); + } + + [Fact] + public void StaleAndFallbackSubtitlesRetainTheirWarning() + { + var now = DateTimeOffset.UnixEpoch.AddDays(1); + var stale = CodexUsageSnapshot.Loading with { Source = UsageDataSource.AppServer, UpdatedAt = now.AddHours(-1) }; + Assert.StartsWith("Stale", UsageDockItem.FormatLiveDetailOrStatus(stale, now, TimeSpan.FromMinutes(1), "Reset - 2 jan 4:00")); + var fallback = stale with { Source = UsageDataSource.LastConfirmed }; + Assert.StartsWith("Last confirmed", UsageDockItem.FormatLiveDetailOrStatus(fallback, now, TimeSpan.FromMinutes(1), "Expires - 2 jan 4:00")); + var local = stale with { Source = UsageDataSource.LocalSession, UpdatedAt = now }; + Assert.StartsWith("Fallback", UsageDockItem.FormatLiveDetailOrStatus(local, now, TimeSpan.FromMinutes(1), "Reset - 2 jan 4:00")); + } + + [Fact] + public void HiddenDateRetainsExistingStatusText() + { + var now = DateTimeOffset.UnixEpoch; + var snapshot = CodexUsageSnapshot.Loading with { Source = UsageDataSource.AppServer, UpdatedAt = now }; + Assert.Equal(UsageDockItem.FormatSourceFreshness(snapshot, now), + UsageDockItem.FormatLiveDetailOrStatus(snapshot, now, TimeSpan.FromMinutes(1), string.Empty)); + } +} diff --git a/CodexUsageDock.Tests/PlanningHistoryIntegrationTests.cs b/CodexUsageDock.Tests/HistoryIntegrationTests.cs similarity index 89% rename from CodexUsageDock.Tests/PlanningHistoryIntegrationTests.cs rename to CodexUsageDock.Tests/HistoryIntegrationTests.cs index b560819..4cd6965 100644 --- a/CodexUsageDock.Tests/PlanningHistoryIntegrationTests.cs +++ b/CodexUsageDock.Tests/HistoryIntegrationTests.cs @@ -4,7 +4,7 @@ namespace CodexUsageDock.Tests; -public sealed class PlanningHistoryIntegrationTests : IDisposable +public sealed class HistoryIntegrationTests : IDisposable { private static readonly DateTimeOffset Now = new(2026, 9, 9, 12, 0, 0, TimeSpan.Zero); private readonly TestEnvironment _environment = new(); @@ -12,49 +12,37 @@ public sealed class PlanningHistoryIntegrationTests : IDisposable public void Dispose() => _environment.Dispose(); [Fact] - public void PlanningPreferencesRoundTripAndExposeSafeDefaults() + public void RetentionPreferencesRoundTripAndExposeSafeDefaults() { var first = _environment.CreateSettings(); SubmitSettings(first, new Dictionary { ["historyRetentionDays"] = "90", - ["workdayEnd"] = "18:30", - ["remainingWorkdays"] = "5", }); Assert.Equal(90, first.HistoryRetentionDays); - Assert.Equal(new TimeOnly(18, 30), first.WorkdayEnd); - Assert.Equal(5, first.RemainingWorkdays); var restarted = _environment.CreateSettings(); Assert.Equal(90, restarted.HistoryRetentionDays); - Assert.Equal(new TimeOnly(18, 30), restarted.WorkdayEnd); - Assert.Equal(5, restarted.RemainingWorkdays); File.Delete(_environment.PathFor("settings.json")); var defaults = _environment.CreateSettings(); Assert.Equal(0, defaults.HistoryRetentionDays); - Assert.Equal(new TimeOnly(17, 0), defaults.WorkdayEnd); - Assert.Equal(1, defaults.RemainingWorkdays); } [Fact] - public void InvalidPlanningPreferencesUseSafeDefaults() + public void InvalidRetentionPreferencesUseSafeDefaults() { File.WriteAllText(_environment.PathFor("settings.json"), JsonSerializer.Serialize( new Dictionary { ["historyRetentionDays"] = "365", - ["workdayEnd"] = "25:61", - ["remainingWorkdays"] = "0", })); var settings = _environment.CreateSettings(); Assert.Equal(0, settings.HistoryRetentionDays); - Assert.Equal(new TimeOnly(17, 0), settings.WorkdayEnd); - Assert.Equal(1, settings.RemainingWorkdays); } [Fact] @@ -200,8 +188,6 @@ private static void SubmitSettings( var payload = new Dictionary { ["historyRetentionDays"] = "0", - ["workdayEnd"] = "17:00", - ["remainingWorkdays"] = "1", }; foreach (var pair in values) diff --git a/CodexUsageDock.Tests/ProviderDockTests.cs b/CodexUsageDock.Tests/ProviderDockTests.cs index 6fdea69..de41742 100644 --- a/CodexUsageDock.Tests/ProviderDockTests.cs +++ b/CodexUsageDock.Tests/ProviderDockTests.cs @@ -1,3 +1,4 @@ +using System.Text.Json; using Microsoft.CommandPalette.Extensions; using Microsoft.CommandPalette.Extensions.Toolkit; using Xunit; @@ -50,11 +51,332 @@ public void SeparateDockBandsHaveStableRestorableIdentities() foreach (var band in bands) { Assert.Single(Assert.IsAssignableFrom(band.Command).GetItems()); - Assert.Equal(band.Command.Id, provider.GetCommandItem(band.Command.Id)!.Command.Id); + Assert.Same(band, provider.GetCommandItem(band.Command.Id)); } Assert.Null(provider.GetCommandItem("unknown")); Assert.Null(provider.GetCommandItem(string.Empty)); - var combined = provider.GetCommandItem("nl.mathijs.codexusage.dock"); - Assert.Equal(3, Assert.IsAssignableFrom(combined!.Command).GetItems().Length); + Assert.Null(provider.GetCommandItem(CombinedDockId)); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void DockModeTransitionsKeepStableBandObjectsAndPersist(bool initiallySeparate) + { + File.WriteAllText( + _environment.PathFor("settings.json"), + JsonSerializer.Serialize(new Dictionary + { + [SeparateDockItemsKey] = initiallySeparate.ToString().ToLowerInvariant(), + })); + + var initialId = initiallySeparate ? FiveHourDockId : CombinedDockId; + var settings = _environment.CreateSettings(); + using (var service = _environment.CreateService()) + using (var provider = new CodexUsageDockCommandsProvider(service, settings, _ => { })) + { + var initialBand = FindBand(provider, initialId); + Assert.Same(initialBand, provider.GetCommandItem(initialId)); + + SubmitSettings(settings, + (SeparateDockItemsKey, (!initiallySeparate).ToString().ToLowerInvariant())); + Assert.Equal(initiallySeparate ? 1 : 3, provider.GetDockBands()!.Length); + + SubmitSettings(settings, + (SeparateDockItemsKey, initiallySeparate.ToString().ToLowerInvariant())); + Assert.Same(initialBand, FindBand(provider, initialId)); + Assert.Same(initialBand, provider.GetCommandItem(initialId)); + } + + using var restartedService = _environment.CreateService(); + using var restartedProvider = new CodexUsageDockCommandsProvider( + restartedService, + _environment.CreateSettings(), + _ => { }); + Assert.Equal(initiallySeparate ? 3 : 1, restartedProvider.GetDockBands()!.Length); + Assert.Same( + FindBand(restartedProvider, initialId), + restartedProvider.GetCommandItem(initialId)); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void DockModeSwitchPersistsTheOppositeModeAcrossRestart(bool initiallySeparate) + { + File.WriteAllText( + _environment.PathFor("settings.json"), + JsonSerializer.Serialize(new Dictionary + { + [SeparateDockItemsKey] = initiallySeparate.ToString().ToLowerInvariant(), + })); + + var settings = _environment.CreateSettings(); + var oldIds = initiallySeparate + ? new[] { FiveHourDockId, WeeklyDockId, CreditsDockId } + : new[] { CombinedDockId }; + var newIds = initiallySeparate + ? new[] { CombinedDockId } + : new[] { FiveHourDockId, WeeklyDockId, CreditsDockId }; + using (var service = _environment.CreateService()) + using (var provider = new CodexUsageDockCommandsProvider(service, settings, _ => { })) + { + SubmitSettings(settings, (SeparateDockItemsKey, (!initiallySeparate).ToString().ToLowerInvariant())); + foreach (var id in oldIds) + { + Assert.Null(provider.GetCommandItem(id)); + } + } + + using var restartedService = _environment.CreateService(); + using var restartedProvider = new CodexUsageDockCommandsProvider( + restartedService, + _environment.CreateSettings(), + _ => { }); + Assert.Equal(newIds, restartedProvider.GetDockBands()!.Select(band => band.Command.Id)); + foreach (var id in oldIds) + { + Assert.Null(restartedProvider.GetCommandItem(id)); + } + foreach (var id in newIds) + { + Assert.Same(FindBand(restartedProvider, id), restartedProvider.GetCommandItem(id)); + } + } + + [Fact] + public void RestorableLookupUsesOnlyTheActiveDockSelection() + { + File.WriteAllText(_environment.PathFor("settings.json"), $"{{\"{SeparateDockItemsKey}\":\"true\"}}"); + using var service = _environment.CreateService(); + var settings = _environment.CreateSettings(); + using var provider = new CodexUsageDockCommandsProvider(service, settings, _ => { }); + + foreach (var band in provider.GetDockBands()!) + { + Assert.Same(band, provider.GetCommandItem(band.Command.Id)); + } + + Assert.Null(provider.GetCommandItem(CombinedDockId)); + SubmitSettings(settings, (SeparateDockItemsKey, "false")); + + var combined = FindBand(provider, CombinedDockId); + Assert.Same(combined, provider.GetCommandItem(CombinedDockId)); + Assert.Null(provider.GetCommandItem(FiveHourDockId)); + Assert.Null(provider.GetCommandItem(WeeklyDockId)); + Assert.Null(provider.GetCommandItem(CreditsDockId)); + } + + [Fact] + public void HiddenAndDisabledDockIdsAreNotRestorableInBothModes() + { + using var service = _environment.CreateService(); + var settings = _environment.CreateSettings(); + using var provider = new CodexUsageDockCommandsProvider(service, settings, _ => { }); + + Assert.NotNull(provider.GetCommandItem(CombinedDockId)); + Assert.Null(provider.GetCommandItem(FiveHourDockId)); + Assert.Null(provider.GetCommandItem(ClaudeDockId)); + + SubmitSettings(settings, (ShowFiveHourLimitKey, "false")); + Assert.Null(provider.GetCommandItem(FiveHourDockId)); + Assert.Equal(2, Assert.IsAssignableFrom(FindBand(provider, CombinedDockId).Command).GetItems().Length); + + SubmitSettings(settings, + (ShowWeeklyLimitKey, "false"), + (ShowResetsAndCreditsKey, "false")); + Assert.Empty(provider.GetDockBands()!); + foreach (var id in AllDockIds) + { + Assert.Null(provider.GetCommandItem(id)); + } + + SubmitSettings(settings, (SeparateDockItemsKey, "true"), (ShowWeeklyLimitKey, "true")); + Assert.Single(provider.GetDockBands()!); + Assert.Null(provider.GetCommandItem(CombinedDockId)); + Assert.Null(provider.GetCommandItem(FiveHourDockId)); + Assert.Same( + FindBand(provider, WeeklyDockId), + provider.GetCommandItem(WeeklyDockId)); + Assert.Null(provider.GetCommandItem(CreditsDockId)); + Assert.Null(provider.GetCommandItem(ClaudeDockId)); + Assert.Null(provider.GetCommandItem("testhost-owned-pin")); + + SubmitSettings(settings, (ShowWeeklyLimitKey, "false")); + Assert.Empty(provider.GetDockBands()!); + Assert.Null(provider.GetCommandItem(WeeklyDockId)); + } + + [Fact] + public void RetainedBandPagesAreClearedWhenTheirBandBecomesInactive() + { + using var service = _environment.CreateService(); + var settings = _environment.CreateSettings(); + using var provider = new CodexUsageDockCommandsProvider(service, settings, _ => { }); + + var combinedBand = FindBand(provider, CombinedDockId); + var combinedPage = Assert.IsAssignableFrom(combinedBand.Command); + Assert.Equal(3, combinedPage.GetItems().Length); + var combinedEmptyNotifications = 0; + combinedPage.ItemsChanged += (_, _) => + { + if (combinedPage.GetItems().Length == 0) + { + combinedEmptyNotifications++; + } + }; + + SubmitSettings(settings, + (ShowFiveHourLimitKey, "false"), + (ShowWeeklyLimitKey, "false"), + (ShowResetsAndCreditsKey, "false")); + Assert.Empty(combinedPage.GetItems()); + Assert.True(combinedEmptyNotifications > 0); + Assert.Empty(provider.GetDockBands()!); + + SubmitSettings(settings, (ShowWeeklyLimitKey, "true")); + Assert.Same(combinedBand, FindBand(provider, CombinedDockId)); + Assert.Single(combinedPage.GetItems()); + + var emptyNotificationsBeforeSeparate = combinedEmptyNotifications; + SubmitSettings(settings, (SeparateDockItemsKey, "true")); + Assert.Empty(combinedPage.GetItems()); + Assert.True(combinedEmptyNotifications > emptyNotificationsBeforeSeparate); + var weeklyBand = FindBand(provider, WeeklyDockId); + var weeklyPage = Assert.IsAssignableFrom(weeklyBand.Command); + Assert.Single(weeklyPage.GetItems()); + var weeklyEmptyNotifications = 0; + weeklyPage.ItemsChanged += (_, _) => + { + if (weeklyPage.GetItems().Length == 0) + { + weeklyEmptyNotifications++; + } + }; + + SubmitSettings(settings, (ShowWeeklyLimitKey, "false")); + Assert.Empty(weeklyPage.GetItems()); + Assert.True(weeklyEmptyNotifications > 0); + Assert.Empty(provider.GetDockBands()!); + } + + [Fact] + public async Task QuotaRefreshKeepsBandIdentityAndNotifiesOnlyItsBandList() + { + var now = new DateTimeOffset(2026, 9, 9, 12, 0, 0, TimeSpan.Zero); + var pending = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var snapshot = CodexUsageSnapshot.Loading with + { + Primary = new RateLimitWindow(25, 300, now.AddHours(4)), + Secondary = new RateLimitWindow(40, 10080, now.AddDays(5)), + UpdatedAt = now, + Source = UsageDataSource.AppServer, + Error = null, + AccountKey = "test-account", + DefaultBucketId = "codex", + }; + using var service = _environment.CreateService( + _ => pending.Task, + () => CodexUsageSnapshot.Loading, + clock: () => now); + using var provider = new CodexUsageDockCommandsProvider( + service, + _environment.CreateSettings(), + _ => { }, + () => now); + var band = FindBand(provider, CombinedDockId); + var list = Assert.IsAssignableFrom(band.Command); + var providerInvalidations = 0; + var bandInvalidations = 0; + provider.ItemsChanged += (_, _) => providerInvalidations++; + list.ItemsChanged += (_, _) => bandInvalidations++; + + var refresh = service.RefreshAsync(); + pending.SetResult(snapshot); + await refresh.WaitAsync(TimeSpan.FromSeconds(5)); + + Assert.Same(band, FindBand(provider, CombinedDockId)); + Assert.Same(band, provider.GetCommandItem(CombinedDockId)); + Assert.Equal(0, providerInvalidations); + Assert.True(bandInvalidations > 0); + } + + [Fact] + public async Task RepeatedCompletedQuotaRefreshNotifiesAPreviouslyReadItem() + { + var now = new DateTimeOffset(2026, 9, 9, 12, 0, 0, TimeSpan.Zero); + var firstRead = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var secondRead = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var readNumber = 0; + var snapshot = CodexUsageSnapshot.Loading with + { + Primary = new RateLimitWindow(25, 300, now.AddHours(4)), + Secondary = new RateLimitWindow(40, 10080, now.AddDays(5)), + UpdatedAt = now, + Source = UsageDataSource.AppServer, + Error = null, + AccountKey = "test-account", + DefaultBucketId = "codex", + ResetCredits = new RateLimitResetCredits(2, null), + }; + Task Read(CancellationToken _) => + Interlocked.Increment(ref readNumber) == 1 ? firstRead.Task : secondRead.Task; + using var service = _environment.CreateService( + Read, + () => CodexUsageSnapshot.Loading, + clock: () => now); + using var provider = new CodexUsageDockCommandsProvider( + service, + _environment.CreateSettings(), + _ => { }, + () => now); + + var band = FindBand(provider, CombinedDockId); + // Reset-credit text is independent of the real-time window validity clock. + var item = Assert.IsAssignableFrom(band.Command).GetItems()[2]; + var cachedTitle = item.Title; + var firstRefresh = service.RefreshAsync(); + firstRead.SetResult(snapshot); + await firstRefresh.WaitAsync(TimeSpan.FromSeconds(5)); + + Assert.NotEqual(item.Title, cachedTitle); + item.PropChanged += (_, args) => + { + if (args.PropertyName == nameof(ICommandItem.Title)) cachedTitle = item.Title; + }; + + var secondRefresh = service.RefreshAsync(); + secondRead.SetResult(snapshot); + await secondRefresh.WaitAsync(TimeSpan.FromSeconds(5)); + + Assert.Equal(item.Title, cachedTitle); + } + + private const string CombinedDockId = "nl.mathijs.codexusage.dock"; + private const string FiveHourDockId = "nl.mathijs.codexusage.dock.five-hour"; + private const string WeeklyDockId = "nl.mathijs.codexusage.dock.weekly"; + private const string CreditsDockId = "nl.mathijs.codexusage.dock.credits"; + private const string ClaudeDockId = "nl.mathijs.codexusage.dock.claude"; + private const string SeparateDockItemsKey = "separateDockItems"; + private const string ShowFiveHourLimitKey = "showFiveHourLimit"; + private const string ShowWeeklyLimitKey = "showWeeklyLimit"; + private const string ShowResetsAndCreditsKey = "showResetsAndCredits"; + private static readonly string[] AllDockIds = [ + CombinedDockId, + FiveHourDockId, + WeeklyDockId, + CreditsDockId, + ClaudeDockId, + ]; + + private static ICommandItem FindBand(CodexUsageDockCommandsProvider provider, string id) => + Assert.Single(provider.GetDockBands() ?? Array.Empty(), item => item.Command.Id == id); + + private static void SubmitSettings( + CodexUsageDockSettingsPage page, + params (string Key, string Value)[] values) + { + var payload = values.ToDictionary(pair => pair.Key, pair => pair.Value); + page.GetContent().OfType().Last().SubmitForm(JsonSerializer.Serialize(payload), "{}"); } } diff --git a/CodexUsageDock.Tests/UsageDataTests.cs b/CodexUsageDock.Tests/UsageDataTests.cs index 66598a2..26bef81 100644 --- a/CodexUsageDock.Tests/UsageDataTests.cs +++ b/CodexUsageDock.Tests/UsageDataTests.cs @@ -445,7 +445,7 @@ public async Task DetailsPageRefreshUpdatesMainContentAndDetailsPane() } [Fact] - public async Task CompletedRefreshRebuildsAndInvalidatesDockBands() + public async Task CompletedRefreshUpdatesExistingDockBandWithoutReloadingProvider() { var now = DateTimeOffset.Now; var result = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); @@ -457,6 +457,10 @@ public async Task CompletedRefreshRebuildsAndInvalidatesDockBands() { var invalidationCount = 0; provider.ItemsChanged += (_, _) => invalidationCount++; + var band = Assert.Single(provider.GetDockBands()!); + var list = Assert.IsAssignableFrom(band.Command); + var bandInvalidations = 0; + list.ItemsChanged += (_, _) => bandInvalidations++; var refresh = service.RefreshAsync(); result.SetResult(CodexUsageSnapshot.Loading with @@ -468,9 +472,9 @@ public async Task CompletedRefreshRebuildsAndInvalidatesDockBands() }); await refresh.WaitAsync(AsyncTestTimeout); - Assert.Equal(1, invalidationCount); - var band = Assert.Single(provider.GetDockBands()!); - var list = Assert.IsAssignableFrom(band.Command); + Assert.Equal(0, invalidationCount); + Assert.True(bandInvalidations > 0); + Assert.Same(band, Assert.Single(provider.GetDockBands()!)); Assert.Contains(list.GetItems(), item => item.Title == "5h 75%"); } finally @@ -1366,7 +1370,7 @@ public void UnavailableDockItemsUseConsistentStatus(string kindName, string expe } [Fact] - public void ResetExpiryUsesTheNextFutureExpiryRoundedUpToWholeDays() + public void ResetExpiryUsesTheNextFutureExpiryDate() { var now = new DateTimeOffset(2026, 7, 16, 12, 0, 0, TimeSpan.Zero); var resets = new RateLimitResetCredits( @@ -1377,24 +1381,24 @@ public void ResetExpiryUsesTheNextFutureExpiryRoundedUpToWholeDays() new RateLimitResetCredit("Expired reset", "available", now.AddDays(-1)), ]); - Assert.Equal("expires in 13 days", UsageDockItem.FormatResetExpiry(resets, now)); + Assert.Equal($"Expires - {UsageDockItem.FormatLocalDateTime(now.AddDays(12).AddHours(1).ToLocalTime(), System.Globalization.CultureInfo.CurrentCulture)}", UsageDockItem.FormatResetExpiry(resets, now)); } [Fact] public void ResetExpiryReportsUnavailableWhenNoFutureExpiryIsKnown() { - Assert.Equal("expiration unavailable", UsageDockItem.FormatResetExpiry(null, DateTimeOffset.Now)); + Assert.Equal("Expires - unavailable", UsageDockItem.FormatResetExpiry(null, DateTimeOffset.UnixEpoch)); } [Fact] - public void ResetExpiryUsesWholeHoursWhenLessThanOneDayRemains() + public void ResetExpiryIncludesDateAndMinutesForSameDayExpiry() { var now = new DateTimeOffset(2026, 7, 16, 12, 0, 0, TimeSpan.Zero); var resets = new RateLimitResetCredits( 1, [new RateLimitResetCredit("Next reset", "available", now.AddHours(12).AddMinutes(1))]); - Assert.Equal("expires in 13 hours", UsageDockItem.FormatResetExpiry(resets, now)); + Assert.Equal($"Expires - {UsageDockItem.FormatLocalDateTime(now.AddHours(12).AddMinutes(1).ToLocalTime(), System.Globalization.CultureInfo.CurrentCulture)}", UsageDockItem.FormatResetExpiry(resets, now)); } [Fact] diff --git a/CodexUsageDock.Tests/UsagePlanningTests.cs b/CodexUsageDock.Tests/UsagePlanningTests.cs deleted file mode 100644 index 10fdcde..0000000 --- a/CodexUsageDock.Tests/UsagePlanningTests.cs +++ /dev/null @@ -1,345 +0,0 @@ -using Xunit; - -namespace CodexUsageDock.Tests; - -public sealed class UsagePlanningTests -{ - private static readonly DateTimeOffset Now = new(2026, 9, 9, 12, 0, 0, TimeSpan.Zero); - private static readonly TimeSpan RefreshInterval = TimeSpan.FromMinutes(1); - - [Fact] - public void FreshPlanReportsRemainingQuotaAndRatesUntilTheEarlierBoundary() - { - var desiredEnd = Now.AddHours(5); - var plan = UsagePlanner.Plan( - Presentation( - primaryRemaining: 50, - secondaryRemaining: 80, - primaryReset: Now.AddHours(2), - secondaryReset: Now.AddDays(4)), - Now, - RefreshInterval, - desiredEnd, - remainingWorkdays: 3); - - Assert.True(plan.IsAvailable); - Assert.Equal(50, plan.Primary!.RemainingPercent); - Assert.Equal(TimeSpan.FromHours(2), plan.Primary.Horizon); - Assert.Equal(Now.AddHours(2), plan.Primary.HorizonEnd); - Assert.True(plan.Primary.ResetsBeforeDesiredEnd); - Assert.Equal(1, plan.Primary.Workdays); - Assert.Equal(25, plan.Primary.AvailablePointsPerHour, precision: 8); - Assert.Equal(50, plan.Primary.AvailablePointsPerWorkday, precision: 8); - Assert.Contains("resets before the desired end", plan.Primary.HorizonMessage, StringComparison.Ordinal); - - Assert.Equal(80, plan.Weekly!.RemainingPercent); - Assert.Equal(TimeSpan.FromHours(5), plan.Weekly.Horizon); - Assert.False(plan.Weekly.ResetsBeforeDesiredEnd); - Assert.Equal(3, plan.Weekly.Workdays); - Assert.Equal(80 / 3d / 5d, plan.Weekly.AvailablePointsPerHour, precision: 8); - Assert.Contains("not a guarantee", plan.Disclaimer, StringComparison.Ordinal); - Assert.Contains("not a guarantee", plan.Status, StringComparison.Ordinal); - } - - [Fact] - public void WeeklyWorkdayAssumptionAffectsDailyAndHourlyBudget() - { - var desiredEnd = Now.AddHours(5); - var fiveDayPlan = UsagePlanner.Plan( - Presentation(primaryRemaining: null, secondaryRemaining: 50, secondaryReset: Now.AddDays(7)), - Now, - RefreshInterval, - desiredEnd, - remainingWorkdays: 5); - var oneDayPlan = UsagePlanner.Plan( - Presentation(primaryRemaining: null, secondaryRemaining: 50, secondaryReset: Now.AddDays(7)), - Now, - RefreshInterval, - desiredEnd, - remainingWorkdays: 1); - - Assert.Equal(10, fiveDayPlan.Weekly!.AvailablePointsPerWorkday, precision: 8); - Assert.Equal(2, fiveDayPlan.Weekly.AvailablePointsPerHour, precision: 8); - Assert.Equal(50, oneDayPlan.Weekly!.AvailablePointsPerWorkday, precision: 8); - Assert.Equal(10, oneDayPlan.Weekly.AvailablePointsPerHour, precision: 8); - } - - [Theory] - [InlineData(2, 23, 3)] - [InlineData(-7, 1, 1)] - public void WeeklyBudgetCapsWorkdaysUsingLocalCalendarDates(int offsetHours, int resetHour, int expectedDays) - { - var timeZone = TimeZoneInfo.CreateCustomTimeZone("Planning test", TimeSpan.FromHours(offsetHours), "Planning test", "Planning test"); - var reset = new DateTimeOffset(2026, 9, 11, resetHour, 0, 0, TimeSpan.Zero); - var presentation = Presentation(primaryRemaining: null, secondaryRemaining: 60, secondaryReset: reset); - - var plan = UsagePlanner.Plan(presentation, Now, RefreshInterval, Now.AddHours(5), 7, timeZone); - var equivalentOffsetPlan = UsagePlanner.Plan( - presentation, Now.ToOffset(TimeSpan.FromHours(14)), RefreshInterval, Now.AddHours(5), 7, timeZone); - - Assert.Equal(expectedDays, plan.Weekly!.Workdays); - Assert.Equal(60d / expectedDays, plan.Weekly.AvailablePointsPerWorkday, precision: 8); - Assert.Equal(60d / expectedDays / 5, plan.Weekly.AvailablePointsPerHour, precision: 8); - Assert.Equal(plan.Weekly.Workdays, equivalentOffsetPlan.Weekly!.Workdays); - } - - [Fact] - public void InvalidEndOrWorkdayCountReturnsAnExplanation() - { - var presentation = Presentation(); - - var now = UsagePlanner.Plan(presentation, Now, RefreshInterval, Now); - var zeroDays = UsagePlanner.Plan(presentation, Now, RefreshInterval, Now.AddHours(1), 0); - var eightDays = UsagePlanner.Plan(presentation, Now, RefreshInterval, Now.AddHours(1), 8); - - Assert.False(now.IsAvailable); - Assert.Contains("desired end must be after now", now.Status, StringComparison.Ordinal); - Assert.False(zeroDays.IsAvailable); - Assert.Contains("between 1 and 7", zeroDays.Status, StringComparison.Ordinal); - Assert.False(eightDays.IsAvailable); - Assert.Contains("between 1 and 7", eightDays.Status, StringComparison.Ordinal); - } - - [Fact] - public void StaleFutureUnattributedAndBlockedDataPausePlanning() - { - var desiredEnd = Now.AddHours(2); - var cases = new[] - { - (Presentation(updatedAt: Now.AddMinutes(-6)), "usage data is stale"), - (Presentation(updatedAt: Now.AddMinutes(1)), "timestamp is in the future"), - (Presentation(accountKey: null), "account identity is unavailable"), - (Presentation(ordinaryUsageAllowed: false), "ordinary usage is currently blocked"), - }; - - foreach (var (presentation, expected) in cases) - { - var plan = UsagePlanner.Plan(presentation, Now, RefreshInterval, desiredEnd); - Assert.False(plan.IsAvailable); - Assert.Contains(expected, plan.Status, StringComparison.Ordinal); - Assert.Empty(plan.Windows); - } - } - - [Fact] - public void LastConfirmedAndLoadingDataAreNotTreatedAsFreshPlans() - { - var desiredEnd = Now.AddHours(2); - var lastConfirmed = UsagePlanner.Plan( - Presentation(source: UsageDataSource.LastConfirmed), - Now, - RefreshInterval, - desiredEnd); - var loading = UsagePlanner.Plan( - Presentation(isLoading: true), - Now, - RefreshInterval, - desiredEnd); - - Assert.False(lastConfirmed.IsAvailable); - Assert.Contains("last confirmed", lastConfirmed.Status, StringComparison.Ordinal); - Assert.False(loading.IsAvailable); - Assert.Contains("loading", loading.Status, StringComparison.Ordinal); - } - - [Fact] - public void ExpiredPrimaryCanLeaveAValidWeeklyPlanAndExpiredBothPause() - { - var desiredEnd = Now.AddDays(1); - var primaryExpired = UsagePlanner.Plan( - Presentation(primaryReset: Now.AddMinutes(-1), secondaryReset: Now.AddDays(4)), - Now, - RefreshInterval, - desiredEnd); - var bothExpired = UsagePlanner.Plan( - Presentation(primaryReset: Now.AddMinutes(-1), secondaryReset: Now.AddMinutes(-1)), - Now, - RefreshInterval, - desiredEnd); - - Assert.True(primaryExpired.IsAvailable); - Assert.Null(primaryExpired.Primary); - Assert.NotNull(primaryExpired.Weekly); - Assert.False(bothExpired.IsAvailable); - Assert.Contains("no valid", bothExpired.Status, StringComparison.Ordinal); - } - - [Fact] - public void ForecastUsesOnlyAUsableCurrentPaceAndReportsUnavailableEvidenceWhenInsufficient() - { - var reset = Now.AddHours(4); - UsageHistoryEntry[] history = - [ - new(Now.AddMinutes(-10), 100), - new(Now, 50), - ]; - var plan = UsagePlanner.Plan( - Presentation( - primaryRemaining: 50, - secondaryRemaining: null, - primaryReset: reset, - primaryHistory: history), - Now, - RefreshInterval, - Now.AddHours(1)); - - Assert.True(plan.IsAvailable); - Assert.True(plan.Primary!.Forecast.IsAvailable); - Assert.True(plan.Primary.Forecast.ReachesLimitBeforeReset); - Assert.Contains("current pace", plan.Primary.Forecast.Status, StringComparison.Ordinal); - Assert.Equal(2, plan.Primary.Evidence.MeasurementCount); - Assert.Equal(2, plan.Primary.Evidence.SegmentMeasurementCount); - Assert.False(plan.Primary.Backtest.IsAvailable); - - var insufficient = UsagePlanner.Plan( - Presentation( - primaryRemaining: 50, - secondaryRemaining: null, - primaryReset: reset, - primaryHistory: [new(Now, 50)]), - Now, - RefreshInterval, - Now.AddHours(1)); - Assert.False(insufficient.Primary!.Forecast.IsAvailable); - Assert.Contains("another measurement", insufficient.Primary.Forecast.Status, StringComparison.Ordinal); - } - - [Fact] - public void GapsBreakTheContinuousSegmentAndPauseForecast() - { - UsageHistoryEntry[] history = - [ - new(Now.AddMinutes(-40), 100), - new(Now.AddMinutes(-20), 90), - new(Now, 80), - ]; - var plan = UsagePlanner.Plan( - Presentation( - primaryRemaining: 80, - secondaryRemaining: null, - primaryHistory: history), - Now, - RefreshInterval, - Now.AddHours(1)); - - Assert.Equal(3, plan.Primary!.Evidence.MeasurementCount); - Assert.Equal(1, plan.Primary.Evidence.SegmentMeasurementCount); - Assert.False(plan.Primary.Forecast.IsAvailable); - Assert.Contains("another measurement", plan.Primary.Forecast.Status, StringComparison.Ordinal); - Assert.False(plan.Primary.Backtest.IsAvailable); - } - - [Fact] - public void EvidenceDescribesMeasurementsSegmentsAdaptiveCyclesAndItsLimit() - { - UsageHistoryEntry[] history = - [ - new(Now.AddMinutes(-20), 100), - new(Now.AddMinutes(-10), 90), - new(Now, 80), - ]; - var adaptive = new AdaptiveWeeklyUsageHistory( - [new AdaptiveWeeklyUsageCycle(Now.AddDays(-7), 10080, 60, 10, [])], - new AdaptiveWeeklyUsageCycle(Now.AddDays(7), 10080, 60, 10, [])); - var plan = UsagePlanner.Plan( - Presentation( - primaryRemaining: null, - secondaryRemaining: 80, - weeklyHistory: history, - adaptiveHistory: adaptive), - Now, - RefreshInterval, - Now.AddHours(1)); - - var evidence = plan.Weekly!.Evidence; - Assert.Equal(3, evidence.MeasurementCount); - Assert.Equal(TimeSpan.FromMinutes(20), evidence.MeasurementSpan); - Assert.Equal(3, evidence.SegmentMeasurementCount); - Assert.Equal(TimeSpan.FromMinutes(20), evidence.SegmentSpan); - Assert.Equal(2, evidence.AdaptiveCycleCount); - Assert.Contains("3 measurements", evidence.Summary, StringComparison.Ordinal); - Assert.Contains("continuous segment", evidence.Summary, StringComparison.Ordinal); - Assert.Contains("adaptive weekly cycles: 2", evidence.Summary, StringComparison.Ordinal); - Assert.Contains("not a calibrated reliability probability", evidence.Summary, StringComparison.Ordinal); - } - - [Fact] - public void BacktestHoldsOutTheLatestMeasurementAndDoesNotTrainOnIt() - { - UsageHistoryEntry[] firstHistory = - [ - new(Now.AddMinutes(-20), 100), - new(Now.AddMinutes(-10), 90), - new(Now, 70), - ]; - UsageHistoryEntry[] changedHoldout = - [ - new(Now.AddMinutes(-20), 100), - new(Now.AddMinutes(-10), 90), - new(Now, 60), - ]; - var first = UsagePlanner.Plan( - Presentation(primaryRemaining: 70, secondaryRemaining: null, primaryHistory: firstHistory), - Now, - RefreshInterval, - Now.AddHours(1)).Primary!.Backtest; - var second = UsagePlanner.Plan( - Presentation(primaryRemaining: 60, secondaryRemaining: null, primaryHistory: changedHoldout), - Now, - RefreshInterval, - Now.AddHours(1)).Primary!.Backtest; - - Assert.True(first.IsAvailable); - Assert.Equal(2, first.TrainingSampleCount); - Assert.Equal(Now, first.HeldOutAt); - Assert.Equal(80, first.PredictedRemainingPercent!.Value, precision: 8); - Assert.Equal(70, first.ActualRemainingPercent!.Value, precision: 8); - Assert.Equal(10, first.AbsoluteErrorPercentagePoints!.Value, precision: 8); - Assert.Equal(first.PredictedRemainingPercent, second.PredictedRemainingPercent); - Assert.Equal(20, second.AbsoluteErrorPercentagePoints!.Value, precision: 8); - Assert.Contains("excluded from the preceding-pace calculation", first.Status, StringComparison.Ordinal); - } - - private static UsagePresentation Presentation( - double? primaryRemaining = 80, - double? secondaryRemaining = 80, - int primaryMinutes = 300, - int secondaryMinutes = 10080, - DateTimeOffset? primaryReset = null, - DateTimeOffset? secondaryReset = null, - DateTimeOffset? updatedAt = null, - UsageDataSource source = UsageDataSource.AppServer, - string? accountKey = "account-a", - bool isLoading = false, - bool? ordinaryUsageAllowed = null, - IReadOnlyList? primaryHistory = null, - IReadOnlyList? weeklyHistory = null, - AdaptiveWeeklyUsageHistory? adaptiveHistory = null) - { - var primary = primaryRemaining is { } primaryValue - ? new RateLimitWindow(100 - primaryValue, primaryMinutes, primaryReset ?? Now.AddHours(4)) - : null; - var secondary = secondaryRemaining is { } secondaryValue - ? new RateLimitWindow(100 - secondaryValue, secondaryMinutes, secondaryReset ?? Now.AddDays(6)) - : null; - var snapshot = new CodexUsageSnapshot( - primary, - secondary, - "pro", - null, - null, - updatedAt ?? Now, - source, - null, - AccountKey: accountKey, - OrdinaryUsageAllowed: ordinaryUsageAllowed, - DefaultBucketId: "codex"); - return new UsagePresentation( - snapshot, - primaryHistory ?? Array.Empty(), - weeklyHistory ?? Array.Empty(), - adaptiveHistory ?? new AdaptiveWeeklyUsageHistory([], null), - LocalTokenUsageSnapshot.Unavailable, - isLoading); - } -} diff --git a/CodexUsageDock.Tests/UsagePreferenceTests.cs b/CodexUsageDock.Tests/UsagePreferenceTests.cs index 214a71c..737f1be 100644 --- a/CodexUsageDock.Tests/UsagePreferenceTests.cs +++ b/CodexUsageDock.Tests/UsagePreferenceTests.cs @@ -19,8 +19,6 @@ public void NewPreferencesUseSafeDefaults() Assert.False(settings.CompactDock); Assert.False(settings.SeparateDockItems); Assert.True(settings.ShowAccountActivity); - Assert.Equal(string.Empty, settings.CodexExecutablePath); - Assert.Equal(string.Empty, settings.CodexHomePath); } [Fact] @@ -33,16 +31,12 @@ public void UsagePreferencesPersistAcrossNewPages() ["compactDock"] = "true", ["separateDockItems"] = "true", ["showAccountActivity"] = "false", - ["codexExecutablePath"] = "C:/Tools/codex.cmd", - ["codexHomePath"] = "C:/Users/test/.codex", }); Assert.True(first.EnableUsageAlerts); Assert.True(first.CompactDock); Assert.True(first.SeparateDockItems); Assert.False(first.ShowAccountActivity); - Assert.Equal("C:/Tools/codex.cmd", first.CodexExecutablePath); - Assert.Equal("C:/Users/test/.codex", first.CodexHomePath); var restarted = _environment.CreateSettings(); @@ -50,14 +44,11 @@ public void UsagePreferencesPersistAcrossNewPages() Assert.True(restarted.CompactDock); Assert.True(restarted.SeparateDockItems); Assert.False(restarted.ShowAccountActivity); - Assert.Equal("C:/Tools/codex.cmd", restarted.CodexExecutablePath); - Assert.Equal("C:/Users/test/.codex", restarted.CodexHomePath); } [Fact] - public void SettingsLoadKeepsValidValuesAndRejectsUnsafePathValues() + public void SettingsLoadKeepsValidValuesAndRejectsInvalidChoices() { - var validBoundaryPath = new string('a', 1024); File.WriteAllText(_environment.PathFor("settings.json"), JsonSerializer.Serialize( new Dictionary { @@ -65,8 +56,6 @@ public void SettingsLoadKeepsValidValuesAndRejectsUnsafePathValues() ["compactDock"] = "true", ["separateDockItems"] = "not-a-boolean", ["showAccountActivity"] = "false", - ["codexExecutablePath"] = validBoundaryPath, - ["codexHomePath"] = new string('b', 1025), })); var settings = _environment.CreateSettings(); @@ -75,20 +64,6 @@ public void SettingsLoadKeepsValidValuesAndRejectsUnsafePathValues() Assert.True(settings.CompactDock); Assert.False(settings.SeparateDockItems); Assert.False(settings.ShowAccountActivity); - Assert.Equal(validBoundaryPath, settings.CodexExecutablePath); - Assert.Contains("Invalid source path", settings.CodexHomePath, StringComparison.Ordinal); - - File.WriteAllText(_environment.PathFor("settings.json"), JsonSerializer.Serialize( - new Dictionary - { - ["codexExecutablePath"] = "C:/Codex\u0001/codex.exe", - ["codexHomePath"] = "C:/Users/test/.codex", - })); - - var controlCharacterSettings = _environment.CreateSettings(); - - Assert.Contains("Invalid source path", controlCharacterSettings.CodexExecutablePath, StringComparison.Ordinal); - Assert.Equal("C:/Users/test/.codex", controlCharacterSettings.CodexHomePath); } [Theory] diff --git a/CodexUsageDock/CachedCodexSessionReader.cs b/CodexUsageDock/CachedCodexSessionReader.cs new file mode 100644 index 0000000..2b9fb7c --- /dev/null +++ b/CodexUsageDock/CachedCodexSessionReader.cs @@ -0,0 +1,330 @@ +using System.Text.Json; + +namespace CodexUsageDock; + +internal sealed class CachedCodexSessionReader +{ + private readonly string _homePath; + private readonly long _maxBytesPerScan; + private readonly int _maxCachedFiles; + private readonly int _maxLineBytes; + private readonly int _fileReadQuantum; + private readonly Func _clock; + private readonly object _sync = new(); + private readonly Dictionary _files = new(StringComparer.OrdinalIgnoreCase); + private readonly LinkedList _pending = new(); + private FileObservation? _latest; + private string? _discoveryAfter; + private long _scan; + private long _visit; + + internal CachedCodexSessionReader( + string? homePath = null, + long maxBytesPerScan = 8 * 1024 * 1024, + int maxCachedFiles = 512, + int maxLineBytes = 128 * 1024, + int fileReadQuantum = 64 * 1024, + Func? clock = null) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxBytesPerScan); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxCachedFiles); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxLineBytes); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(fileReadQuantum); + _homePath = Path.GetFullPath(homePath ?? LocalStorage.GetCodexHome()); + _maxBytesPerScan = maxBytesPerScan; + _maxCachedFiles = maxCachedFiles; + _maxLineBytes = maxLineBytes; + _fileReadQuantum = fileReadQuantum; + _clock = clock ?? (() => DateTimeOffset.UtcNow); + } + + internal long BytesReadLastScan { get; private set; } + internal int CachedFileCount => _files.Count; + internal bool LastScanComplete { get; private set; } + + internal CodexUsageSnapshot ReadLatest(CancellationToken cancellationToken = default) + { + lock (_sync) + { + BytesReadLastScan = 0; + LastScanComplete = false; + cancellationToken.ThrowIfCancellationRequested(); + _scan++; + var now = _clock(); + var inventoryComplete = DiscoverFiles(cancellationToken); + var buffer = new byte[Math.Min(16 * 1024, _fileReadQuantum)]; + var readFailed = false; + while (_pending.First is { } next && BytesReadLastScan < _maxBytesPerScan) + { + cancellationToken.ThrowIfCancellationRequested(); + var file = next.Value; + _pending.RemoveFirst(); + file.QueueNode = null; + file.LastVisit = ++_visit; + if (!ReadFile(file, buffer, now, cancellationToken)) + { + // Retry failed files on the next refresh, rather than spinning without consuming the budget. + readFailed = true; + continue; + } + QueueIfNeeded(file); + } + + foreach (var file in _files.Values) + { + RememberLatest(file); + } + cancellationToken.ThrowIfCancellationRequested(); + LastScanComplete = inventoryComplete && !readFailed && _pending.Count == 0 + && _files.Values.All(file => file.PartialLength == 0 && !file.DiscardingLine); + var latest = _latest?.Snapshot ?? throw new InvalidOperationException("No usable Codex usage measurement was found."); + return latest with { Error = LastScanComplete ? null : "Local session scan incomplete." }; + } + } + + private bool DiscoverFiles(CancellationToken cancellationToken) + { + var comparer = new DiscoveryOrder(_discoveryAfter); + var candidates = new SortedSet(comparer); + var complete = true; + var found = 0; + var latestSeen = false; + foreach (var directory in new[] { Path.Combine(_homePath, "sessions"), Path.Combine(_homePath, "archived_sessions") }) + { + cancellationToken.ThrowIfCancellationRequested(); + if (!Directory.Exists(directory)) continue; + var options = new EnumerationOptions + { + RecurseSubdirectories = true, + IgnoreInaccessible = true, + AttributesToSkip = FileAttributes.ReparsePoint, + }; + try + { + foreach (var path in Directory.EnumerateFiles(directory, "rollout-*.jsonl", options)) + { + cancellationToken.ThrowIfCancellationRequested(); + found++; + if (_files.TryGetValue(path, out var file)) file.SeenAt = _scan; + if (StringComparer.OrdinalIgnoreCase.Equals(_latest?.Stamp.Path, path)) latestSeen = true; + FileStamp stamp; + try { stamp = ReadStamp(path); } + catch (Exception error) when (error is IOException or UnauthorizedAccessException) + { + LocalStorage.TraceFailure("inspect fallback session", error); + complete = false; + continue; + } + if (_latest is { } latest && StringComparer.OrdinalIgnoreCase.Equals(latest.Stamp.Path, path)) + _latest = NeedsReset(latest.Stamp, stamp, latest.Offset) ? null : latest with { Stamp = stamp }; + if (file is not null) + { + Observe(file, stamp); + QueueIfNeeded(file); + } + else + { + candidates.Add(stamp); + if (candidates.Count > _maxCachedFiles) candidates.Remove(candidates.Max!); + } + } + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException) + { + LocalStorage.TraceFailure("enumerate fallback sessions", error); + complete = false; + } + } + + if (complete) + { + foreach (var file in _files.Values.Where(file => file.SeenAt != _scan).ToArray()) Remove(file); + if (!latestSeen) _latest = null; + } + var evictedPending = false; + foreach (var stamp in candidates) + { + cancellationToken.ThrowIfCancellationRequested(); + if (_files.Count == _maxCachedFiles) + { + var eligible = _files.Values.Where(file => file.AddedAt != _scan); + var evicted = eligible.Where(file => file.QueueNode is null).MinBy(file => file.LastVisit); + if (evicted is null && !evictedPending) + { + evicted = eligible.Where(file => file.LastVisit > 0 && file.PartialLength == 0).MinBy(file => file.LastVisit); + evictedPending = evicted is not null; + } + if (evicted is null) break; + RememberLatest(evicted); + Remove(evicted); + } + var added = new FileState(stamp, _scan); + _files.Add(stamp.Path, added); + QueueIfNeeded(added); + _discoveryAfter = stamp.Path; + } + // An overflow can require rereading evicted checkpoints; never label that bounded view a complete inventory. + return complete && found <= _maxCachedFiles; + } + + private bool ReadFile(FileState file, byte[] buffer, DateTimeOffset now, CancellationToken cancellationToken) + { + try + { + Observe(file, ReadStamp(file.Stamp.Path)); + using var stream = new FileStream(file.Stamp.Path, FileMode.Open, FileAccess.Read, + FileShare.ReadWrite | FileShare.Delete, bufferSize: 1); + if (stream.Length < file.Stamp.Length) + { + Reset(file); + file.Stamp = file.Stamp with { Length = stream.Length }; + } + stream.Position = file.Offset; + var remaining = Math.Min(Math.Min(_fileReadQuantum, _maxBytesPerScan - BytesReadLastScan), file.Stamp.Length - file.Offset); + while (remaining > 0) + { + cancellationToken.ThrowIfCancellationRequested(); + var read = stream.Read(buffer, 0, (int)Math.Min(buffer.Length, remaining)); + if (read == 0) return false; + ProcessBytes(file, buffer.AsSpan(0, read), now); + file.Offset += read; + BytesReadLastScan += read; + remaining -= read; + RememberLatest(file); + } + return true; + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException) + { + LocalStorage.TraceFailure("read fallback session", error); + return false; + } + } + + private void ProcessBytes(FileState file, ReadOnlySpan bytes, DateTimeOffset now) + { + while (!bytes.IsEmpty) + { + var newline = bytes.IndexOf((byte)'\n'); + var count = newline < 0 ? bytes.Length : newline; + if (!file.DiscardingLine) + { + if (count > _maxLineBytes - file.PartialLength) + { + file.ClearPartial(); + file.DiscardingLine = true; + } + else + { + var needed = file.PartialLength + count; + if (needed > file.Partial.Length) + Array.Resize(ref file.Partial, Math.Min(_maxLineBytes, Math.Max(needed, 1024))); + bytes[..count].CopyTo(file.Partial.AsSpan(file.PartialLength)); + file.PartialLength = needed; + } + } + if (newline < 0) break; + if (!file.DiscardingLine) ParseLine(file, now); + file.ClearPartial(); + file.DiscardingLine = false; + bytes = bytes[(newline + 1)..]; + } + } + + private static void ParseLine(FileState file, DateTimeOffset now) + { + var line = file.Partial.AsMemory(0, file.PartialLength); + if (line.Span.IndexOf("\"rate_limits\""u8) < 0) return; + if (line.Span.StartsWith("\uFEFF"u8)) line = line[3..]; + try + { + using var document = JsonDocument.Parse(line, new JsonDocumentOptions { MaxDepth = 32 }); + var snapshot = LocalCodexSessionReader.ParseSnapshot(document.RootElement, now); + if (snapshot is not null && (file.Latest is null || snapshot.UpdatedAt >= file.Latest.UpdatedAt)) + file.Latest = snapshot; + } + catch (JsonException) + { + // Malformed complete records are ignored; an unfinished record remains bounded until its newline arrives. + } + } + + private void Observe(FileState file, FileStamp stamp) + { + if (NeedsReset(file.Stamp, stamp, file.Offset)) Reset(file); + file.Stamp = stamp; + } + + private static bool NeedsReset(FileStamp previous, FileStamp current, long offset) => previous.CreatedAt != current.CreatedAt + || current.Length < previous.Length || current.Length < offset + || (current.Length == previous.Length && current.WrittenAt != previous.WrittenAt); + + private void Reset(FileState file) + { + if (StringComparer.OrdinalIgnoreCase.Equals(_latest?.Stamp.Path, file.Stamp.Path)) _latest = null; + file.Offset = 0; + file.Latest = null; + file.ClearPartial(); + file.DiscardingLine = false; + } + + private void RememberLatest(FileState file) + { + if (file.Latest is { } snapshot && (_latest is null || snapshot.UpdatedAt > _latest.Snapshot.UpdatedAt)) + _latest = new(file.Stamp, file.Offset, snapshot); + } + + private void QueueIfNeeded(FileState file) + { + if (file.QueueNode is null && file.Offset < file.Stamp.Length) file.QueueNode = _pending.AddLast(file); + } + + private void Remove(FileState file) + { + if (file.QueueNode is { } node) _pending.Remove(node); + file.ClearPartial(); + _files.Remove(file.Stamp.Path); + } + + private static FileStamp ReadStamp(string path) + { + var info = new FileInfo(path); + return new(path, info.Length, info.LastWriteTimeUtc, info.CreationTimeUtc); + } + + private sealed record FileStamp(string Path, long Length, DateTime WrittenAt, DateTime CreatedAt); + private sealed record FileObservation(FileStamp Stamp, long Offset, CodexUsageSnapshot Snapshot); + + private sealed class FileState(FileStamp stamp, long scan) + { + internal FileStamp Stamp = stamp; + internal long Offset; + internal long SeenAt = scan; + internal long AddedAt = scan; + internal long LastVisit; + internal byte[] Partial = []; + internal int PartialLength; + internal bool DiscardingLine; + internal CodexUsageSnapshot? Latest; + internal LinkedListNode? QueueNode; + + internal void ClearPartial() + { + Partial.AsSpan(0, PartialLength).Clear(); + PartialLength = 0; + } + } + + private sealed class DiscoveryOrder(string? after) : IComparer + { + public int Compare(FileStamp? left, FileStamp? right) + { + if (ReferenceEquals(left, right)) return 0; + if (left is null) return -1; + if (right is null) return 1; + var leftAfter = after is null || StringComparer.OrdinalIgnoreCase.Compare(left.Path, after) > 0; + var rightAfter = after is null || StringComparer.OrdinalIgnoreCase.Compare(right.Path, after) > 0; + return leftAfter == rightAfter ? StringComparer.OrdinalIgnoreCase.Compare(left.Path, right.Path) : leftAfter ? -1 : 1; + } + } +} diff --git a/CodexUsageDock/CodexUsageDockCommandsProvider.cs b/CodexUsageDock/CodexUsageDockCommandsProvider.cs index 5fe42e5..0d8dcd7 100644 --- a/CodexUsageDock/CodexUsageDockCommandsProvider.cs +++ b/CodexUsageDock/CodexUsageDockCommandsProvider.cs @@ -14,9 +14,9 @@ public partial class CodexUsageDockCommandsProvider : CommandProvider private readonly CodexUsageDockPage _details; private readonly CodexUsageDiagnosticsPage _diagnostics; private readonly CodexAccountActivityPage _accountActivity; - private readonly CodexPlanningPage _planner; private readonly CodexHistoryPage _history; private readonly CodexActionsPage _actions; + private readonly CodexUsageTablePage _textUsage; private readonly UsageAlertEvaluator _alerts = new(); private readonly Action _notify; private readonly Func _clock; @@ -24,6 +24,12 @@ public partial class CodexUsageDockCommandsProvider : CommandProvider private const string FiveHourDockId = "nl.mathijs.codexusage.dock.five-hour"; private const string WeeklyDockId = "nl.mathijs.codexusage.dock.weekly"; private const string CreditsDockId = "nl.mathijs.codexusage.dock.credits"; + private readonly object _dockLayoutLock = new(); + private readonly UsageDockBand _combinedBand; + private readonly UsageDockBand _fiveHourBand; + private readonly UsageDockBand _weeklyBand; + private readonly UsageDockBand _creditsBand; + private readonly UsageDockBand[] _allDockBands; private ICommandItem[] _dockBands = []; public CodexUsageDockCommandsProvider() @@ -46,19 +52,24 @@ internal CodexUsageDockCommandsProvider(CodexUsageService usage, CodexUsageDockS _usage.SetRefreshInterval(_settings.RefreshInterval); _usage.SetAdaptiveWeeklyForecastEnabled(_settings.UseAdaptiveWeeklyForecast); - ApplySourceSettings(); _usage.SetAccountActivityEnabled(_settings.ShowAccountActivity); _usage.SetAggregateRetentionDays(_settings.HistoryRetentionDays); var details = _details = new CodexUsageDockPage(_usage, _settings); _diagnostics = new CodexUsageDiagnosticsPage(_usage); _diagnostics.Id = "nl.mathijs.codexusage.diagnostics"; _accountActivity = new CodexAccountActivityPage(_usage); - _planner = new CodexPlanningPage(_usage, _settings, _clock); _history = new CodexHistoryPage(_usage); _actions = new CodexActionsPage(_usage); + _textUsage = new CodexUsageTablePage(_usage, _clock); + _details.Commands = [.. _details.Commands, new CommandContextItem(_textUsage) { Title = "Read usage in text" }]; _fiveHour = new UsageDockItem(_usage, UsageDockItemKind.FiveHour, details, _settings); _weekly = new UsageDockItem(_usage, UsageDockItemKind.Weekly, details, _settings); _resetsAndCredits = new UsageDockItem(_usage, UsageDockItemKind.ResetsAndCredits, details); + _combinedBand = new("nl.mathijs.codexusage.dock", DisplayName); + _fiveHourBand = new(FiveHourDockId, "Codex five-hour usage"); + _weeklyBand = new(WeeklyDockId, "Codex weekly usage"); + _creditsBand = new(CreditsDockId, "Codex resets and credits"); + _allDockBands = [_combinedBand, _fiveHourBand, _weeklyBand, _creditsBand]; _commands = [ @@ -83,36 +94,27 @@ internal CodexUsageDockCommandsProvider(CodexUsageService usage, CodexUsageDockS Title = "Codex account activity", Subtitle = "Account-wide daily tokens reported by Codex", }, - new CommandItem(_planner) { Title = "Codex workday planner", Subtitle = "Daily quota budget, recent pace, and forecast evidence" }, new CommandItem(_history) { Title = "Codex usage history", Subtitle = "Retained quota observations, CSV/JSON export, and deletion" }, new CommandItem(_actions) { Title = "Codex task usage and earned resets", Subtitle = "Request a task estimate or explicitly use an earned reset" }, + new CommandItem(_textUsage) { Title = "Codex usage in text", Subtitle = "Quota tables and measured values without charts or color cues" }, ]; _settings.Changed += OnSettingsChanged; _settings.ClearAdaptiveHistoryRequested += OnClearAdaptiveHistoryRequested; _usage.Updated += OnUsageUpdated; - RebuildDockBands(); + UpdateDockLayout(); _usage.Start(); } public override ICommandItem[] TopLevelCommands() => _commands; - public override ICommandItem[]? GetDockBands() => _dockBands; + public override ICommandItem[]? GetDockBands() => [.. Volatile.Read(ref _dockBands)]; public override ICommandItem? GetCommandItem(string id) { if (string.IsNullOrWhiteSpace(id)) return null; - var known = _commands.Concat(_dockBands).FirstOrDefault(item => item.Command.Id == id); - if (known is not null) return known; - return id switch - { - "nl.mathijs.codexusage.dock" => new WrappedDockItem(GetVisibleDockItems(), "nl.mathijs.codexusage.dock", DisplayName), - FiveHourDockId => new WrappedDockItem([_fiveHour], FiveHourDockId, "Codex five-hour usage"), - WeeklyDockId => new WrappedDockItem([_weekly], WeeklyDockId, "Codex weekly usage"), - CreditsDockId => new WrappedDockItem([_resetsAndCredits], CreditsDockId, "Codex resets and credits"), - _ => null, - }; + return _commands.Concat(Volatile.Read(ref _dockBands)).FirstOrDefault(item => item.Command.Id == id); } private void OnSettingsChanged(object? sender, EventArgs e) @@ -124,24 +126,13 @@ private void OnSettingsChanged(object? sender, EventArgs e) } _usage.SetRefreshInterval(_settings.RefreshInterval); _usage.SetAdaptiveWeeklyForecastEnabled(_settings.UseAdaptiveWeeklyForecast); - var sourceChanged = ApplySourceSettings(); _usage.SetAccountActivityEnabled(_settings.ShowAccountActivity); _usage.SetAggregateRetentionDays(_settings.HistoryRetentionDays); _fiveHour.Refresh(); _weekly.Refresh(); _details.Refresh(); - _planner.Refresh(); _history.Refresh(); - RebuildDockBands(); - RaiseItemsChanged(); - if (sourceChanged) _ = _usage.RefreshAsync(); - } - - private bool ApplySourceSettings() - { - _ = CodexSourceOptions.TryCreate(_settings.CodexExecutablePath, _settings.CodexHomePath, out var options, out var error); - if (error is not null) _settings.ShowOperationStatus(error); - return _usage.ConfigureSource(options, error); + UpdateDockLayout(); } private void OnClearAdaptiveHistoryRequested(object? sender, EventArgs e) @@ -164,8 +155,10 @@ private void OnUsageUpdated(object? sender, EventArgs e) return; } - RebuildDockBands(); - RaiseItemsChanged(); + foreach (var band in Volatile.Read(ref _dockBands).OfType()) + { + band.NotifyItemsChanged(); + } var alerts = _alerts.Evaluate(_usage.GetPresentation(), _clock(), _usage.RefreshInterval, new UsageAlertOptions(Enabled: _settings.EnableUsageAlerts)); if (alerts.Count > 0) @@ -176,21 +169,30 @@ private void OnUsageUpdated(object? sender, EventArgs e) } } - private void RebuildDockBands() + private void UpdateDockLayout() { - var items = GetVisibleDockItems(); - if (_settings.SeparateDockItems) + var changedBands = new List(); + bool catalogChanged; + lock (_dockLayoutLock) { - _dockBands = items.Select(item => new WrappedDockItem([item], - ReferenceEquals(item, _fiveHour) ? FiveHourDockId : ReferenceEquals(item, _weekly) ? WeeklyDockId : CreditsDockId, - ReferenceEquals(item, _fiveHour) ? "Codex five-hour usage" : ReferenceEquals(item, _weekly) ? "Codex weekly usage" : "Codex resets and credits")) - .Cast().ToArray(); - return; + var separate = _settings.SeparateDockItems; + Publish(_combinedBand, separate ? [] : GetVisibleDockItems()); + Publish(_fiveHourBand, separate && _settings.ShowFiveHourLimit ? [_fiveHour] : []); + Publish(_weeklyBand, separate && _settings.ShowWeeklyLimit ? [_weekly] : []); + Publish(_creditsBand, separate && _settings.ShowResetsAndCredits ? [_resetsAndCredits] : []); + ICommandItem[] bands = _allDockBands.Where(band => band.HasItems).ToArray(); + catalogChanged = !Volatile.Read(ref _dockBands).SequenceEqual(bands); + Volatile.Write(ref _dockBands, bands); + } + + // No host callback may run while the layout lock is held. + foreach (var band in changedBands) band.NotifyItemsChanged(); + if (catalogChanged) RaiseItemsChanged(); + + void Publish(UsageDockBand band, IListItem[] items) + { + if (band.PublishItems(items)) changedBands.Add(band); } - var dockBand = items.Length == 0 - ? null - : new WrappedDockItem(items, "nl.mathijs.codexusage.dock", DisplayName); - _dockBands = dockBand is null ? [] : [dockBand]; } private IListItem[] GetVisibleDockItems() @@ -225,9 +227,9 @@ public override void Dispose() _details.Dispose(); _diagnostics.Dispose(); _accountActivity.Dispose(); - _planner.Dispose(); _history.Dispose(); _actions.Dispose(); + _textUsage.Dispose(); _usage.Dispose(); base.Dispose(); GC.SuppressFinalize(this); diff --git a/CodexUsageDock/CodexUsageService.cs b/CodexUsageDock/CodexUsageService.cs index 56deedd..46476ea 100644 --- a/CodexUsageDock/CodexUsageService.cs +++ b/CodexUsageDock/CodexUsageService.cs @@ -25,6 +25,7 @@ internal sealed partial class CodexUsageService : IDisposable private readonly Func _localSessionReader; private Func>? _localTokenUsageReader; private readonly bool _usesConfiguredSources; + private CachedCodexSessionReader? _configuredSessionReader; private CodexSourceOptions _sourceOptions = CodexSourceOptions.Default; private long _sourceGeneration; private string? _sourceConfigurationError; @@ -47,6 +48,7 @@ public CodexUsageService() localTokenUsageReader: new LocalCodexTokenUsageReader().ReadAsync) { _usesConfiguredSources = true; + _configuredSessionReader = new CachedCodexSessionReader(); InitializeOptionalFeatures(LocalStorage.GetPath("aggregates.json"), LocalStorage.GetPath("reset-attempt.json")); } @@ -175,6 +177,7 @@ internal bool ConfigureSource(CodexSourceOptions options, string? error = null) if (_usesConfiguredSources) { _localTokenUsageReader = new LocalCodexTokenUsageReader(options.HomePath).ReadAsync; + _configuredSessionReader = new CachedCodexSessionReader(options.HomePath); } lock (_historyLock) { @@ -421,10 +424,12 @@ private async Task ExecuteRefreshAsync(TaskCompletionSource completion, CodexSou private async Task ReadSnapshotAsync(CodexSourceOptions options, long generation, CancellationToken cancellationToken) { var attemptedAt = _clock(); + CachedCodexSessionReader? localCache; lock (_refreshStateLock) { - if (_sourceConfigurationError is not null) + if (_sourceConfigurationError is not null || generation != _sourceGeneration) return CreateUnavailableSnapshot() with { LastAttemptAt = attemptedAt }; + localCache = _configuredSessionReader; } try { @@ -450,7 +455,7 @@ private async Task ReadSnapshotAsync(CodexSourceOptions opti try { var fallback = await Task.Run(() => _usesConfiguredSources - ? LocalCodexSessionReader.ReadLatest(options.HomePath ?? LocalStorage.GetCodexHome(), _clock(), cancellationToken) + ? localCache!.ReadLatest(cancellationToken) : _localSessionReader(cancellationToken), cancellationToken).ConfigureAwait(false); // Session logs do not normally identify the signed-in account. A newer // unverified log must not replace a confirmed, account-scoped measurement. @@ -460,7 +465,13 @@ private async Task ReadSnapshotAsync(CodexSourceOptions opti { return LastConfirmedSnapshot(confirmed, attemptedAt); } - return fallback with { Error = LiveDataUnavailableMessage, LastAttemptAt = attemptedAt }; + return fallback with + { + Error = localCache is { LastScanComplete: false } + ? LiveDataUnavailableMessage + " The local session scan is incomplete; more data will be checked on the next refresh." + : LiveDataUnavailableMessage, + LastAttemptAt = attemptedAt, + }; } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { diff --git a/CodexUsageDock/LocalCodexSessionReader.cs b/CodexUsageDock/LocalCodexSessionReader.cs index e80c882..14f8b84 100644 --- a/CodexUsageDock/LocalCodexSessionReader.cs +++ b/CodexUsageDock/LocalCodexSessionReader.cs @@ -62,32 +62,10 @@ internal static CodexUsageSnapshot ReadLatest(string codexHome, DateTimeOffset n try { using var document = JsonDocument.Parse(line); - var root = document.RootElement; - if (root.ValueKind != JsonValueKind.Object - || !root.TryGetProperty("timestamp", out var timestamp) - || timestamp.ValueKind != JsonValueKind.String - || !DateTimeOffset.TryParse(timestamp.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var recordedAt) - || recordedAt > now - || !root.TryGetProperty("payload", out var payload) || payload.ValueKind != JsonValueKind.Object - || !payload.TryGetProperty("rate_limits", out var limits) || limits.ValueKind != JsonValueKind.Object - || !TryReadWindow(limits, "primary", out var primary) - || !TryReadWindow(limits, "secondary", out var secondary) - || (!limits.TryGetProperty("primary", out _) && !limits.TryGetProperty("secondary", out _))) + var snapshot = ParseSnapshot(document.RootElement, now); + if (snapshot is not null && (latest is null || snapshot.UpdatedAt >= latest.UpdatedAt)) { - continue; - } - - var windows = RateLimitWindowParser.Classify(primary, secondary); - if ((primary is not null || secondary is not null) && windows.FiveHour is null && windows.Weekly is null) - { - continue; - } - - var plan = limits.TryGetProperty("plan_type", out var planType) && planType.ValueKind == JsonValueKind.String - ? UsageText.SanitizeExternal(planType.GetString(), 32) : null; - if (latest is null || recordedAt >= latest.UpdatedAt) - { - latest = new CodexUsageSnapshot(windows.FiveHour, windows.Weekly, plan, null, null, recordedAt, UsageDataSource.LocalSession, null); + latest = snapshot; } } catch (JsonException) @@ -104,9 +82,36 @@ internal static CodexUsageSnapshot ReadLatest(string codexHome, DateTimeOffset n return latest; } + internal static CodexUsageSnapshot? ParseSnapshot(JsonElement root, DateTimeOffset now) + { + if (root.ValueKind != JsonValueKind.Object + || !root.TryGetProperty("timestamp", out var timestamp) + || timestamp.ValueKind != JsonValueKind.String + || !DateTimeOffset.TryParse(timestamp.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var recordedAt) + || recordedAt > now + || !root.TryGetProperty("payload", out var payload) || payload.ValueKind != JsonValueKind.Object + || !payload.TryGetProperty("rate_limits", out var limits) || limits.ValueKind != JsonValueKind.Object + || !TryReadWindow(limits, "primary", out var primary) + || !TryReadWindow(limits, "secondary", out var secondary) + || (!limits.TryGetProperty("primary", out _) && !limits.TryGetProperty("secondary", out _))) + { + return null; + } + + var windows = RateLimitWindowParser.Classify(primary, secondary); + if ((primary is not null || secondary is not null) && windows.FiveHour is null && windows.Weekly is null) + { + return null; + } + + var plan = limits.TryGetProperty("plan_type", out var planType) && planType.ValueKind == JsonValueKind.String + ? UsageText.SanitizeExternal(planType.GetString(), 32) : null; + return new CodexUsageSnapshot(windows.FiveHour, windows.Weekly, plan, null, null, recordedAt, UsageDataSource.LocalSession, null); + } + private static bool TryReadWindow(JsonElement limits, string name, out RateLimitWindow? window) { window = RateLimitWindowParser.TryParse(limits, name, "used_percent", "window_minutes", "resets_at"); return window is not null || !limits.TryGetProperty(name, out var value) || value.ValueKind == JsonValueKind.Null; } -} \ No newline at end of file +} diff --git a/CodexUsageDock/Pages/CodexActionsPage.cs b/CodexUsageDock/Pages/CodexActionsPage.cs index dc204bc..a5ec9ad 100644 --- a/CodexUsageDock/Pages/CodexActionsPage.cs +++ b/CodexUsageDock/Pages/CodexActionsPage.cs @@ -31,30 +31,30 @@ internal CodexActionsPage(CodexUsageService service) private void Refresh() { - var presentation = _service.GetActionPresentation(); - var body = new StringBuilder("# Task usage\n\n").Append(presentation.TaskStatus).Append("\n\n"); - if (presentation.Task is { } task) body.Append(FormatTask(task)); - body.Append("\n# Earned resets\n\nReported available: ") - .Append(presentation.Usage.ResetCredits?.AvailableCount.ToString(CultureInfo.InvariantCulture) ?? "Unknown") - .Append(".\n\n").Append(presentation.ResetStatus) - .Append("\n\nUse the confirmed reset action only when you want to redeem one existing earned reset. ") - .Append("After an unknown outcome, retrying uses the same saved request ID. The backend decides eligibility.\n"); - var expectedAccount = presentation.Usage.AccountKey; - var commands = new List - { - new CommandContextItem(new RefreshUsageCommand(_service)) { Title = "Refresh usage" }, - }; - if (expectedAccount is not null) - { - commands.Add(new CommandContextItem(new ConfirmableCommand( - new AnonymousCommand(() => { _ = _service.ConsumeEarnedResetAsync(expectedAccount); }) { Result = CommandResult.KeepOpen() }, - "Use or retry an earned reset?", - "Redeem one existing earned reset for the currently identified Codex account. A retry of an uncertain request reuses its saved ID. No reset is purchased.", - () => true) { Name = "Use or retry an earned reset" }) { Title = "Use or retry an earned reset" }); - } lock (_gate) { if (_disposed) return; + var presentation = _service.GetActionPresentation(); + var body = new StringBuilder("# Task usage\n\n").Append(presentation.TaskStatus).Append("\n\n"); + if (presentation.Task is { } task) body.Append(FormatTask(task)); + body.Append("\n# Earned resets\n\nReported available: ") + .Append(presentation.Usage.ResetCredits?.AvailableCount.ToString(CultureInfo.InvariantCulture) ?? "Unknown") + .Append(".\n\n").Append(presentation.ResetStatus) + .Append("\n\nUse the confirmed reset action only when you want to redeem one existing earned reset. ") + .Append("After an unknown outcome, retrying uses the same saved request ID. The backend decides eligibility.\n"); + var expectedAccount = presentation.Usage.AccountKey; + var commands = new List + { + new CommandContextItem(new RefreshUsageCommand(_service)) { Title = "Refresh usage" }, + }; + if (expectedAccount is not null) + { + commands.Add(new CommandContextItem(new ConfirmableCommand( + new AnonymousCommand(() => { _ = _service.ConsumeEarnedResetAsync(expectedAccount); }) { Result = CommandResult.KeepOpen() }, + "Use or retry an earned reset?", + "Redeem one existing earned reset for the currently identified Codex account. A retry of an uncertain request reuses its saved ID. No reset is purchased.", + () => true) { Name = "Use or retry an earned reset" }) { Title = "Use or retry an earned reset" }); + } _content = new MarkdownContent(body.ToString()); Commands = commands.ToArray(); } diff --git a/CodexUsageDock/Pages/CodexHistoryPage.cs b/CodexUsageDock/Pages/CodexHistoryPage.cs index 27029cf..122d179 100644 --- a/CodexUsageDock/Pages/CodexHistoryPage.cs +++ b/CodexUsageDock/Pages/CodexHistoryPage.cs @@ -32,23 +32,23 @@ internal CodexHistoryPage(CodexUsageService service) internal void Refresh() { - var history = _service.GetAggregateHistory(); - var body = new StringBuilder("# Usage history\n\n"); - if (_operation is not null) body.Append(UsageText.EscapeMarkdown(_operation)).Append("\n\n"); - if (!history.Identified) body.Append("Waiting for an identified account. Histories are separated by account and quota category.\n\n"); - body.Append(history.RetentionDays == 0 ? "Collection paused. Choose 7, 30, or 90 days in settings to retain observations." - : $"Retention: {history.RetentionDays} days. Up to one observation per five minutes, with separate reset transitions.") - .Append("\n\n").Append(history.Points.Count.ToString(CultureInfo.InvariantCulture)).Append(" retained observations. ") - .Append("Exports contain UTC quota percentages and reset times, without account IDs, conversation content, tokens, or costs.\n\n"); - if (history.Error is not null) body.Append(history.Error).Append("\n\n"); - body.Append("The most recent 30 observations are shown. The exports include all retained rows for this context.\n\n") - .Append("| Observed UTC | Five-hour remaining | Weekly remaining |\n| --- | ---: | ---: |\n"); - foreach (var point in history.Points.TakeLast(30).Reverse()) - body.Append("| ").Append(point.RecordedAt.UtcDateTime.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture)).Append(" | ") - .Append(Percent(point.PrimaryRemainingPercent)).Append(" | ").Append(Percent(point.WeeklyRemainingPercent)).Append(" |\n"); lock (_gate) { if (_disposed) return; + var history = _service.GetAggregateHistory(); + var body = new StringBuilder("# Usage history\n\n"); + if (_operation is not null) body.Append(UsageText.EscapeMarkdown(_operation)).Append("\n\n"); + if (!history.Identified) body.Append("Waiting for an identified account. Histories are separated by account and quota category.\n\n"); + body.Append(history.RetentionDays == 0 ? "Collection paused. Choose 7, 30, or 90 days in settings to retain observations." + : $"Retention: {history.RetentionDays} days. Up to one observation per five minutes, with separate reset transitions.") + .Append("\n\n").Append(history.Points.Count.ToString(CultureInfo.InvariantCulture)).Append(" retained observations. ") + .Append("Exports contain UTC quota percentages and reset times, without account IDs, conversation content, tokens, or costs.\n\n"); + if (history.Error is not null) body.Append(history.Error).Append("\n\n"); + body.Append("The most recent 30 observations are shown. The exports include all retained rows for this context.\n\n") + .Append("| Observed UTC | Five-hour remaining | Weekly remaining |\n| --- | ---: | ---: |\n"); + foreach (var point in history.Points.TakeLast(30).Reverse()) + body.Append("| ").Append(point.RecordedAt.UtcDateTime.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture)).Append(" | ") + .Append(Percent(point.PrimaryRemainingPercent)).Append(" | ").Append(Percent(point.WeeklyRemainingPercent)).Append(" |\n"); _content = new MarkdownContent(body.ToString()); Commands = history.Context is not { } context ? [] : [ diff --git a/CodexUsageDock/Pages/CodexPlanningPage.cs b/CodexUsageDock/Pages/CodexPlanningPage.cs deleted file mode 100644 index a340e18..0000000 --- a/CodexUsageDock/Pages/CodexPlanningPage.cs +++ /dev/null @@ -1,77 +0,0 @@ -using System.Globalization; -using System.Text; -using Microsoft.CommandPalette.Extensions; -using Microsoft.CommandPalette.Extensions.Toolkit; - -namespace CodexUsageDock; - -internal sealed partial class CodexPlanningPage : ContentPage, IDisposable -{ - private readonly CodexUsageService _service; - private readonly CodexUsageDockSettingsPage _settings; - private readonly Func _clock; - private readonly object _gate = new(); - private MarkdownContent _content = new(string.Empty); - private bool _disposed; - - internal CodexPlanningPage(CodexUsageService service, CodexUsageDockSettingsPage settings, Func? clock = null) - { - _service = service; - _settings = settings; - _clock = clock ?? (() => DateTimeOffset.Now); - Id = "nl.mathijs.codexusage.planner"; - Name = "Open"; - Title = "Codex workday planner"; - Icon = new IconInfo("\uE787"); - service.Updated += OnUpdated; - Refresh(); - } - - public override IContent[] GetContent() { lock (_gate) { return [_content]; } } - - internal void Refresh() - { - var now = _clock(); - var localEnd = now.LocalDateTime.Date.Add(_settings.WorkdayEnd.ToTimeSpan()); - var body = TimeZoneInfo.Local.IsInvalidTime(localEnd) - ? "The selected workday end does not exist in today's local time zone. Choose another time in settings." - : FormatPlan(UsagePlanner.Plan(_service.GetPresentation(), now, _service.RefreshInterval, - new DateTimeOffset(localEnd, TimeZoneInfo.Local.GetUtcOffset(localEnd)), _settings.RemainingWorkdays)); - lock (_gate) - { - if (_disposed) return; - _content = new MarkdownContent(body); - Commands = [new CommandContextItem(new RefreshUsageCommand(_service)) { Title = "Refresh usage" }, - new CommandContextItem(_settings) { Title = "Change planning assumptions" }, - new CommandContextItem(new CopyTextCommand(body)) { Title = "Copy plan" }]; - } - RaiseItemsChanged(0); - } - - internal static string FormatPlan(UsagePlanningResult plan) - { - var text = new StringBuilder("# Workday planner\n\n").Append(plan.Status).Append("\n\n"); - text.Append("Target today: ").Append(plan.DesiredEnd.ToString("yyyy-MM-dd HH:mm zzz", CultureInfo.InvariantCulture)) - .Append(". Remaining workdays before weekly reset: ").Append(plan.RequestedWorkdays?.ToString(CultureInfo.InvariantCulture) ?? "1") - .Append(". Change these assumptions in settings.\n\n"); - foreach (var window in plan.Windows) - { - text.Append("## ").Append(window.Label).Append(" allowance\n\n") - .Append(window.RemainingPercent.ToString("0.#", CultureInfo.InvariantCulture)).Append("% remaining; budget ") - .Append(window.AvailablePointsPerWorkday.ToString("0.#", CultureInfo.InvariantCulture)).Append(" quota percentage points per workday, or ") - .Append(window.AvailablePointsPerHour.ToString("0.#", CultureInfo.InvariantCulture)).Append(" points per hour today.\n\n") - .Append(window.HorizonMessage).Append("\n\n") - .Append("**Recent pace:** ").Append(window.Forecast.Status).Append("\n\n") - .Append("**Evidence:** ").Append(window.Evidence.Summary).Append("\n\n") - .Append("**Last observation check:** ").Append(window.Backtest.Status).Append("\n\n"); - if (window.Backtest.AbsoluteErrorPercentagePoints is { } error) - text.Append("Held-out prediction error: ").Append(error.ToString("0.##", CultureInfo.InvariantCulture)) - .Append(" percentage points. One held-out observation does not establish long-term accuracy.\n\n"); - } - return text.Append("Quota points are not tokens, money, or a guaranteed number of tasks. Both windows apply independently. ") - .Append("This planner uses recent pace; the dashboard may additionally use its optional learned weekly pattern.").ToString(); - } - - private void OnUpdated(object? sender, EventArgs args) => Refresh(); - public void Dispose() { lock (_gate) { _disposed = true; _service.Updated -= OnUpdated; } } -} diff --git a/CodexUsageDock/Pages/CodexUsageDockSettingsPage.cs b/CodexUsageDock/Pages/CodexUsageDockSettingsPage.cs index 9dd522a..6a0f6e7 100644 --- a/CodexUsageDock/Pages/CodexUsageDockSettingsPage.cs +++ b/CodexUsageDock/Pages/CodexUsageDockSettingsPage.cs @@ -8,7 +8,6 @@ namespace CodexUsageDock; internal sealed partial class CodexUsageDockSettingsPage : ContentPage { - private const string InvalidSourcePath = "Invalid source path: re-enter or clear this field"; private const string ShowFiveHourLimitKey = "showFiveHourLimit"; private const string ShowWeeklyLimitKey = "showWeeklyLimit"; private const string ShowResetsAndCreditsKey = "showResetsAndCredits"; @@ -19,12 +18,7 @@ internal sealed partial class CodexUsageDockSettingsPage : ContentPage private const string CompactDockKey = "compactDock"; private const string SeparateDockItemsKey = "separateDockItems"; private const string ShowAccountActivityKey = "showAccountActivity"; - private const string CodexExecutablePathKey = "codexExecutablePath"; - private const string CodexHomePathKey = "codexHomePath"; - private const int MaximumPathLength = 1024; private const string HistoryRetentionKey = "historyRetentionDays"; - private const string WorkdayEndKey = "workdayEnd"; - private const string RemainingWorkdaysKey = "remainingWorkdays"; private readonly Settings _settings = new(); private readonly string _path; private readonly FormContent _statusContent = new() @@ -84,27 +78,13 @@ internal CodexUsageDockSettingsPage(string path) _settings.Add(new ToggleSetting(SeparateDockItemsKey, false) { Label = "Separate Dock items", - Description = "Show each usage item as its own Dock entry.", + Description = "Offer separate metric bands instead of the combined band. Other-mode pins are hidden. After switching, add the desired bands through Dock customization if needed.", }); _settings.Add(new ToggleSetting(ShowAccountActivityKey, true) { Label = "Show account activity", Description = "Read account-wide daily tokens from the Codex service after quotas load. Older CLI versions may not support this.", }); - _settings.Add(new TextSetting(CodexExecutablePathKey, string.Empty) - { - Label = "Codex executable path", - Description = "Optional explicit path to codex.exe or codex.cmd.", - Placeholder = @"C:\Path\to\codex.exe", - Multiline = false, - }); - _settings.Add(new TextSetting(CodexHomePathKey, string.Empty) - { - Label = "Codex home path", - Description = "Optional Codex home directory. It may be a Windows-accessible WSL directory; this extension does not launch WSL or modify Codex configuration.", - Placeholder = @"C:\Users\you\.codex", - Multiline = false, - }); _settings.Add(new ChoiceSetSetting( RefreshIntervalKey, [ @@ -122,19 +102,6 @@ internal CodexUsageDockSettingsPage(string path) Label = "Retain usage observations", Description = "Optional local quota history for export. Pausing keeps saved data; use History to delete it.", }); - _settings.Add(new TextSetting(WorkdayEndKey, "17:00") - { - Label = "Workday end (HH:mm)", - Description = "Local time used by the planner for today. After this time, planning pauses until the next day.", - Multiline = false, - }); - _settings.Add(new ChoiceSetSetting(RemainingWorkdaysKey, - [new("1 workday", "1"), new("2 workdays", "2"), new("3 workdays", "3"), new("4 workdays", "4"), - new("5 workdays", "5"), new("6 workdays", "6"), new("7 workdays", "7")]) - { - Label = "Workdays remaining before weekly reset", - Description = "Your planning assumption, including today. The extension does not infer your calendar.", - }); var clearHistory = new ConfirmableCommand( new AnonymousCommand(() => ClearAdaptiveHistoryRequested?.Invoke(this, EventArgs.Empty)) { @@ -179,18 +146,10 @@ internal CodexUsageDockSettingsPage(string path) public bool ShowAccountActivity => _settings.GetSetting(ShowAccountActivityKey); - public string CodexExecutablePath => GetPathSetting(CodexExecutablePathKey); - - public string CodexHomePath => GetPathSetting(CodexHomePathKey); - public TimeSpan RefreshInterval => ParseRefreshInterval(_settings.GetSetting(RefreshIntervalKey)); internal int HistoryRetentionDays => _settings.GetSetting(HistoryRetentionKey) switch { "7" => 7, "30" => 30, "90" => 90, _ => 0 }; - internal TimeOnly WorkdayEnd => TimeOnly.TryParseExact(_settings.GetSetting(WorkdayEndKey), "HH:mm", - System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var time) ? time : new(17, 0); - internal int RemainingWorkdays => int.TryParse(_settings.GetSetting(RemainingWorkdaysKey), out var days) - && days is >= 1 and <= 7 ? days : 1; internal string? StatusMessage { get; private set; } @@ -230,12 +189,6 @@ private void Load() var valid = new JsonObject(); foreach (var property in document.RootElement.EnumerateObject()) { - if (property.Name is CodexExecutablePathKey or CodexHomePathKey) - { - valid[property.Name] = property.Value.ValueKind == JsonValueKind.String && IsValidPathSetting(property.Value.GetString()) - ? property.Value.GetString() : InvalidSourcePath; - continue; - } if (property.Value.ValueKind is JsonValueKind.True or JsonValueKind.False && IsBooleanSetting(property.Name)) { @@ -253,10 +206,7 @@ private void Load() { valid[property.Name] = value; } - else if (property.Name == HistoryRetentionKey && value is "0" or "7" or "30" or "90" - || property.Name == RemainingWorkdaysKey && value is "1" or "2" or "3" or "4" or "5" or "6" or "7" - || property.Name == WorkdayEndKey && TimeOnly.TryParseExact(value, "HH:mm", - System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out _)) + else if (property.Name == HistoryRetentionKey && value is "0" or "7" or "30" or "90") { valid[property.Name] = value; } @@ -280,30 +230,6 @@ ShowFiveHourLimitKey or ShowWeeklyLimitKey or ShowResetsAndCreditsKey or ShowRes UseAdaptiveWeeklyForecastKey or EnableUsageAlertsKey or CompactDockKey or SeparateDockItemsKey or ShowAccountActivityKey; - private static bool IsValidPathSetting(string? value) - { - if (value is null || value.Length > MaximumPathLength) - { - return false; - } - - foreach (var character in value) - { - if (char.IsControl(character)) - { - return false; - } - } - - return true; - } - - private string GetPathSetting(string key) - { - var value = _settings.GetSetting(key); - return IsValidPathSetting(value) ? value! : InvalidSourcePath; - } - private void OnSettingsChanged(object sender, Settings args) { var saved = LocalStorage.TryWrite(_path, _settings.ToJson()); diff --git a/CodexUsageDock/Pages/CodexUsageTablePage.cs b/CodexUsageDock/Pages/CodexUsageTablePage.cs new file mode 100644 index 0000000..1b39943 --- /dev/null +++ b/CodexUsageDock/Pages/CodexUsageTablePage.cs @@ -0,0 +1,88 @@ +using System.Globalization; +using System.Text; +using Microsoft.CommandPalette.Extensions; +using Microsoft.CommandPalette.Extensions.Toolkit; + +namespace CodexUsageDock; + +internal sealed partial class CodexUsageTablePage : ContentPage, IDisposable +{ + private readonly CodexUsageService _service; + private readonly Func _clock; + private readonly object _gate = new(); + private MarkdownContent _content = new(string.Empty); + private bool _disposed; + + internal CodexUsageTablePage(CodexUsageService service, Func? clock = null) + { + _service = service; + _clock = clock ?? (() => DateTimeOffset.Now); + Id = "nl.mathijs.codexusage.table"; + Name = "Open"; + Title = "Codex usage in text"; + Icon = new IconInfo("\uE8A5"); + service.Updated += OnUpdated; + Refresh(); + } + + public override IContent[] GetContent() { lock (_gate) { return [_content]; } } + + internal static string Format(UsagePresentation view, DateTimeOffset now, TimeSpan interval) + { + var snapshot = view.Usage; + var freshness = snapshot.Source is UsageDataSource.Initializing or UsageDataSource.Unavailable + ? "Unavailable" : UsageFreshness.Classify(snapshot.UpdatedAt, now, interval, snapshot.Source == UsageDataSource.LastConfirmed).ToString(); + var body = new StringBuilder("# Codex usage in text\n\nA text alternative to the dashboard charts.\n\n") + .Append("Status: ").Append(freshness).Append(view.IsLoading ? "; refreshing" : string.Empty) + .Append(". Source: ").Append(snapshot.SourceDisplayName).Append(".\n\n"); + if (snapshot.Source is not (UsageDataSource.Initializing or UsageDataSource.Unavailable)) + body.Append("Observed UTC: ").Append(Utc(snapshot.UpdatedAt)).Append(". Percentages below describe that observation.\n\n"); + if (snapshot.OrdinaryUsageAllowed == false) body.Append("**Ordinary usage was reported blocked.**\n\n"); + body.Append("| Quota category / window | Remaining at observation | Reset UTC | Window state now |\n| --- | ---: | --- | --- |\n"); + AppendWindow(body, "Default five-hour", snapshot.Primary, now); + AppendWindow(body, "Default weekly", snapshot.Secondary, now); + foreach (var bucket in snapshot.Buckets?.Take(32) ?? []) + { + var label = UsageText.SanitizeExternal(bucket.Name, 70) ?? UsageText.SanitizeExternal(bucket.Id, 70) ?? "Additional category"; + if (bucket.Id != snapshot.DefaultBucketId || bucket.Primary != snapshot.Primary) AppendWindow(body, label + " primary", bucket.Primary, now); + if (bucket.Id != snapshot.DefaultBucketId || bucket.Secondary != snapshot.Secondary) AppendWindow(body, label + " secondary", bucket.Secondary, now); + } + body.Append("\nAvailable earned resets at observation: ").Append(snapshot.ResetCredits?.AvailableCount.ToString(CultureInfo.InvariantCulture) ?? "Not reported") + .Append(".\n\n## Recent weekly observations\n\nUp to 20 measured points, without projected values.\n\n| Observed UTC | Remaining |\n| --- | ---: |\n"); + foreach (var point in view.WeeklyHistory.TakeLast(20)) + body.Append("| ").Append(Utc(point.RecordedAt)).Append(" | ").Append(point.RemainingPercent.ToString("0.#", CultureInfo.InvariantCulture)).Append("% |\n"); + body.Append("\n## Locally observed daily tokens\n\nThese are local activity totals, not account-wide billing or quota percentages.\n\n"); + body.Append("Availability: ").Append(view.TokenUsage.Status).Append(".\n\n| Local calendar date | Tokens |\n| --- | ---: |\n"); + foreach (var day in view.TokenUsage.Days.TakeLast(8)) + body.Append("| ").Append(day.Date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)).Append(" | ") + .Append(day.TotalTokens.ToString("N0", CultureInfo.InvariantCulture)).Append(" |\n"); + return body.ToString(); + } + + private static void AppendWindow(StringBuilder body, string label, RateLimitWindow? window, DateTimeOffset now) + { + body.Append("| ").Append(UsageText.EscapeMarkdown(label)); + if (window is null) { body.Append(" | Not reported | Not reported | Unknown |\n"); return; } + var valid = double.IsFinite(window.UsedPercent) && window.UsedPercent is >= 0 and <= 100 && window.WindowMinutes > 0; + body.Append(" (").Append(window.WindowMinutes.ToString(CultureInfo.InvariantCulture)).Append(" minutes) | ") + .Append(valid ? window.RemainingPercent.ToString("0.#", CultureInfo.InvariantCulture) + "%" : "Invalid") + .Append(" | ").Append(Utc(window.ResetsAt)).Append(" | ") + .Append(!valid ? "Invalid" : window.ResetsAt <= now ? "Reset passed; refresh required" : "Active window").Append(" |\n"); + } + + private static string Utc(DateTimeOffset time) => time.UtcDateTime.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture); + private void Refresh() + { + lock (_gate) + { + if (_disposed) return; + var body = Format(_service.GetPresentation(), _clock(), _service.RefreshInterval); + _content = new MarkdownContent(body); + Commands = [new CommandContextItem(new RefreshUsageCommand(_service)) { Title = "Refresh usage" }, + new CommandContextItem(new CopyTextCommand(body)) { Title = "Copy usage text" }]; + } + RaiseItemsChanged(0); + } + private void OnUpdated(object? sender, EventArgs args) => Refresh(); + public void Dispose() { lock (_gate) { _disposed = true; _service.Updated -= OnUpdated; } } +} diff --git a/CodexUsageDock/UsageDockBand.cs b/CodexUsageDock/UsageDockBand.cs new file mode 100644 index 0000000..867d57d --- /dev/null +++ b/CodexUsageDock/UsageDockBand.cs @@ -0,0 +1,48 @@ +using Microsoft.CommandPalette.Extensions; +using Microsoft.CommandPalette.Extensions.Toolkit; + +namespace CodexUsageDock; + +internal sealed partial class UsageDockBand : CommandItem +{ + private readonly DockBandPage _page; + + internal UsageDockBand(string id, string title) : this(new DockBandPage(id, title)) { } + + private UsageDockBand(DockBandPage page) : base(page) => _page = page; + + internal bool HasItems => _page.HasItems; + internal bool PublishItems(IListItem[] items) => _page.PublishItems(items); + internal void NotifyItemsChanged() => _page.NotifyItemsChanged(); + + private sealed partial class DockBandPage : ListPage + { + private IListItem[] _items = []; + + internal DockBandPage(string id, string title) + { + Id = id; + Name = title; + Title = title; + } + + internal bool HasItems => Volatile.Read(ref _items).Length > 0; + public override IListItem[] GetItems() => [.. Volatile.Read(ref _items)]; + + // The host synchronously calls GetItems from ItemsChanged. Publish the + // complete layout before notifying, including newly inactive bands. + internal bool PublishItems(IListItem[] items) + { + if (Volatile.Read(ref _items).SequenceEqual(items)) return false; + Volatile.Write(ref _items, items); + return true; + } + + internal void NotifyItemsChanged() + { + var items = Volatile.Read(ref _items); + foreach (var item in items.OfType()) item.NotifyDisplayPropertiesChanged(); + RaiseItemsChanged(Volatile.Read(ref _items).Length); + } + } +} diff --git a/CodexUsageDock/UsageDockItem.cs b/CodexUsageDock/UsageDockItem.cs index 9a03271..2c02dd4 100644 --- a/CodexUsageDock/UsageDockItem.cs +++ b/CodexUsageDock/UsageDockItem.cs @@ -10,7 +10,7 @@ internal enum UsageDockItemKind ResetsAndCredits, } -internal sealed partial class UsageDockItem : ListItem, IDisposable +internal sealed partial class UsageDockItem : UsageDockListItem, IDisposable { private readonly CodexUsageService _usage; private readonly UsageDockItemKind _kind; @@ -43,8 +43,10 @@ private void UpdateText() if (_kind == UsageDockItemKind.ResetsAndCredits) { Title = FormatResetsAndCredits(snapshot); - Subtitle = CombineStatusAndDetail( - FormatSourceFreshness(snapshot, now, _usage.RefreshInterval), + Subtitle = FormatLiveDetailOrStatus( + snapshot, + now, + _usage.RefreshInterval, _settings?.CompactDock == true ? string.Empty : FormatResetExpiry(snapshot.ResetCredits, now)); Icon = new IconInfo("\uE777"); return; @@ -74,8 +76,14 @@ private void UpdateText() } Title = FormatQuotaTitle(_kind, window.RemainingPercent, compact); - var reset = compact || _settings?.ShowResetTime == false ? string.Empty : $"reset {FormatReset(window.ResetsAt)}"; - Subtitle = CombineStatusAndDetail(FormatSourceFreshness(snapshot, now, _usage.RefreshInterval), reset); + var reset = compact || _settings?.ShowResetTime == false + ? string.Empty + : $"Reset - {FormatLocalDateTime(window.ResetsAt.ToLocalTime(), CultureInfo.CurrentCulture)}"; + Subtitle = FormatLiveDetailOrStatus( + snapshot, + now, + _usage.RefreshInterval, + reset); Icon = new IconInfo(window.RemainingPercent <= 10 ? "\uE7BA" : "\uE916"); } @@ -189,6 +197,31 @@ private static string FormatAge(DateTimeOffset timestamp, DateTimeOffset now) private static string FormatLocalTime(DateTimeOffset value) => value.ToLocalTime().ToString("HH:mm", CultureInfo.CurrentCulture); + internal static string FormatLocalDateTime(DateTimeOffset local, CultureInfo culture) + { + var month = local.ToString("MMM", culture).TrimEnd('.'); + // Windows globalization data can abbreviate Dutch September as "sep". + if (culture.TwoLetterISOLanguageName == "nl" && local.Month == 9) month = "sept"; + return $"{local.ToString("%d", culture)} {month} {local.ToString("H:mm", culture)}"; + } + + internal static string FormatLiveDetailOrStatus( + CodexUsageSnapshot snapshot, + DateTimeOffset now, + TimeSpan refreshInterval, + string detail) + { + var state = UsageFreshness.Classify( + snapshot.UpdatedAt, + now, + refreshInterval); + return snapshot.Source == UsageDataSource.AppServer + && state == UsageFreshnessState.Fresh + && detail.Length > 0 + ? detail + : CombineStatusAndDetail(FormatSourceFreshness(snapshot, now, refreshInterval), detail); + } + private static string CombineStatusAndDetail(string status, string detail) => detail.Length == 0 ? status : $"{status} · {detail}"; @@ -220,13 +253,10 @@ internal static string FormatResetExpiry(RateLimitResetCredits? resets, DateTime if (nextExpiry is not { } expiry) { - return "expiration unavailable"; + return "Expires - unavailable"; } - var remaining = expiry - now; - return remaining < TimeSpan.FromHours(24) - ? $"expires in {(int)Math.Ceiling(remaining.TotalHours)} hours" - : $"expires in {(int)Math.Ceiling(remaining.TotalDays)} days"; + return $"Expires - {FormatLocalDateTime(expiry.ToLocalTime(), CultureInfo.CurrentCulture)}"; } internal static (string Title, string Subtitle) FormatUnavailable(UsageDockItemKind kind, bool compact = false) => @@ -237,14 +267,6 @@ internal static (string Title, string Subtitle) FormatUnavailable(UsageDockItemK _ => "-- resets", }, "Codex usage unavailable"); - private static string FormatReset(DateTimeOffset reset) - { - var local = reset.ToLocalTime(); - return local.Date == DateTime.Today - ? local.ToString("HH:mm", CultureInfo.CurrentCulture) - : local.ToString("ddd HH:mm", CultureInfo.CurrentCulture); - } - public void Dispose() { _usage.Updated -= OnUpdated; diff --git a/CodexUsageDock/UsageDockListItem.cs b/CodexUsageDock/UsageDockListItem.cs new file mode 100644 index 0000000..9771c52 --- /dev/null +++ b/CodexUsageDock/UsageDockListItem.cs @@ -0,0 +1,16 @@ +using Microsoft.CommandPalette.Extensions; +using Microsoft.CommandPalette.Extensions.Toolkit; + +namespace CodexUsageDock; + +internal partial class UsageDockListItem(ICommand command) : ListItem(command) +{ + internal void NotifyDisplayPropertiesChanged() + { + // A host can subscribe after reading the initial values and miss an + // intervening update. Refresh even unchanged values on the next read. + OnPropertyChanged(nameof(Title)); + OnPropertyChanged(nameof(Subtitle)); + OnPropertyChanged(nameof(Icon)); + } +} diff --git a/CodexUsageDock/UsagePlanning.cs b/CodexUsageDock/UsagePlanning.cs deleted file mode 100644 index 70fad83..0000000 --- a/CodexUsageDock/UsagePlanning.cs +++ /dev/null @@ -1,600 +0,0 @@ -using System.Globalization; - -namespace CodexUsageDock; - -internal static class UsagePlanner -{ - internal const string Disclaimer = "Planning guidance only; it is not a guarantee."; - - internal static UsagePlanningResult Plan( - UsagePresentation presentation, - DateTimeOffset now, - TimeSpan refreshInterval, - DateTimeOffset desiredEnd, - int? remainingWorkdays = null, - TimeZoneInfo? timeZone = null) - { - ArgumentNullException.ThrowIfNull(presentation); - - if (desiredEnd <= now) - { - return Unavailable(desiredEnd, "Planning unavailable: the desired end must be after now.", remainingWorkdays); - } - - if (remainingWorkdays is < 1 or > 7) - { - return Unavailable( - desiredEnd, - "Planning unavailable: remaining workdays must be between 1 and 7.", - remainingWorkdays); - } - - var snapshot = presentation.Usage; - if (presentation.IsLoading) - { - return Unavailable(desiredEnd, "Planning paused while fresh usage data is loading.", remainingWorkdays); - } - - if (snapshot.Source != UsageDataSource.AppServer) - { - var sourceMessage = snapshot.Source switch - { - UsageDataSource.LastConfirmed => "Planning paused: only last confirmed usage is available; refresh live usage first.", - UsageDataSource.Unavailable => "Planning paused: live usage is unavailable.", - UsageDataSource.LocalSession => "Planning paused: local session usage is not a verified live app-server measurement.", - _ => "Planning paused until fresh live app-server usage is available.", - }; - return Unavailable(desiredEnd, sourceMessage, remainingWorkdays); - } - - if (string.IsNullOrWhiteSpace(snapshot.AccountKey)) - { - return Unavailable(desiredEnd, "Planning paused: the verified account identity is unavailable.", remainingWorkdays); - } - - var freshness = UsageFreshness.Classify(snapshot.UpdatedAt, now, refreshInterval); - if (freshness != UsageFreshnessState.Fresh) - { - var freshnessMessage = freshness switch - { - UsageFreshnessState.Stale => "Planning paused: usage data is stale; refresh before planning.", - UsageFreshnessState.Future => "Planning paused: the usage timestamp is in the future.", - UsageFreshnessState.Unknown => "Planning paused: usage freshness is unknown.", - _ => "Planning paused until fresh usage data is available.", - }; - return Unavailable(desiredEnd, freshnessMessage, remainingWorkdays); - } - - if (snapshot.OrdinaryUsageAllowed == false) - { - return Unavailable(desiredEnd, "Planning paused: ordinary usage is currently blocked.", remainingWorkdays); - } - - try - { - var maximumSampleAge = UsageFreshness.MaximumAge(refreshInterval); - var primary = CreateWindowPlan( - snapshot.Primary, - presentation.PrimaryHistory, - now, - desiredEnd, - remainingWorkdays, - maximumSampleAge, - adaptiveCycleCount: 0, - isPrimary: true, - timeZone ?? TimeZoneInfo.Local); - var weekly = CreateWindowPlan( - snapshot.Secondary, - presentation.WeeklyHistory, - now, - desiredEnd, - remainingWorkdays, - maximumSampleAge, - CountAdaptiveCycles(presentation), - isPrimary: false, - timeZone ?? TimeZoneInfo.Local); - - if (primary is null && weekly is null) - { - return Unavailable( - desiredEnd, - "Planning paused: no valid 5-hour or weekly allowance window is available.", - remainingWorkdays); - } - - var windows = new[] { primary, weekly }.Where(window => window is not null).Cast().ToArray(); - var status = windows.Length == 2 - ? $"Planning available for both allowance windows. {Disclaimer}" - : $"Planning available for one allowance window. {Disclaimer}"; - return new UsagePlanningResult( - true, - status, - desiredEnd, - remainingWorkdays, - primary, - weekly, - Disclaimer); - } - catch (ArgumentOutOfRangeException) - { - return Unavailable(desiredEnd, "Planning paused: the usage window timestamps are out of range.", remainingWorkdays); - } - catch (OverflowException) - { - return Unavailable(desiredEnd, "Planning paused: the usage window duration is out of range.", remainingWorkdays); - } - } - - private static UsagePlanningWindow? CreateWindowPlan( - RateLimitWindow? window, - IReadOnlyList history, - DateTimeOffset now, - DateTimeOffset desiredEnd, - int? requestedWorkdays, - TimeSpan maximumSampleAge, - int adaptiveCycleCount, - bool isPrimary, - TimeZoneInfo timeZone) - { - if (!UsageFreshness.IsValidWindow(window, now)) - { - return null; - } - - var validWindow = window!; - var horizonEnd = validWindow.ResetsAt < desiredEnd ? validWindow.ResetsAt : desiredEnd; - var horizon = horizonEnd - now; - if (horizon <= TimeSpan.Zero) - { - return null; - } - - var workdays = isPrimary - ? 1 - : Math.Max(1, Math.Min(requestedWorkdays ?? 1, CalendarDaysUntilReset(validWindow.ResetsAt, now, timeZone))); - var remaining = validWindow.RemainingPercent; - var pointsPerWorkday = remaining / workdays; - var pointsPerHour = pointsPerWorkday / horizon.TotalHours; - var displayLabel = FormatWindowDuration(validWindow.WindowMinutes); - var resetsBeforeDesiredEnd = validWindow.ResetsAt < desiredEnd; - var horizonMessage = resetsBeforeDesiredEnd - ? $"This {displayLabel} window resets before the desired end at {FormatUtc(validWindow.ResetsAt)}; planning stops at that reset." - : $"Planning runs until {FormatUtc(horizonEnd)}."; - - var forecast = CreateForecast( - validWindow, - history, - now, - maximumSampleAge); - var evidence = CreateEvidence( - validWindow, - history, - now, - maximumSampleAge, - adaptiveCycleCount); - var backtest = CreateBacktest( - validWindow, - history, - now, - maximumSampleAge); - - return new UsagePlanningWindow( - displayLabel, - remaining, - validWindow.WindowMinutes, - validWindow.ResetsAt, - horizonEnd, - workdays, - horizon, - pointsPerWorkday, - pointsPerHour, - resetsBeforeDesiredEnd, - horizonMessage, - forecast, - evidence, - backtest); - } - - private static UsagePlanningForecast CreateForecast( - RateLimitWindow window, - IReadOnlyList history, - DateTimeOffset now, - TimeSpan maximumSampleAge) - { - if (!TryGetWindowStart(window, out var windowStart)) - { - return UsagePlanningForecast.Unavailable("Forecast unavailable: the window duration is out of range."); - } - - try - { - var analysis = UsageTrendAnalyzer.Analyze( - history ?? Array.Empty(), - windowStart, - window.ResetsAt, - now, - dataAvailable: true, - maximumSampleAge, - adaptiveWeeklyForecastEnabled: false, - adaptiveWeeklyHistory: null); - if (analysis.Forecast is null) - { - return UsagePlanningForecast.Unavailable(analysis.ForecastStatus); - } - - return new UsagePlanningForecast(true, analysis.Forecast, analysis.ForecastStatus); - } - catch (ArgumentException) - { - return UsagePlanningForecast.Unavailable("Forecast unavailable: the measurements are not usable."); - } - catch (InvalidOperationException) - { - return UsagePlanningForecast.Unavailable("Forecast unavailable: the measurements are not usable."); - } - catch (OverflowException) - { - return UsagePlanningForecast.Unavailable("Forecast unavailable: the timestamps are out of range."); - } - } - - private static UsagePlanningEvidence CreateEvidence( - RateLimitWindow window, - IReadOnlyList history, - DateTimeOffset now, - TimeSpan maximumSampleAge, - int adaptiveCycleCount) - { - var samples = GetWindowSamples(history, window, now); - var segment = GetLatestSegment(history, window, now, maximumSampleAge); - var measurementSpan = GetSpan(samples); - var segmentSpan = GetSpan(segment); - var summary = $"{samples.Length.ToString(CultureInfo.InvariantCulture)} measurements over {FormatDuration(measurementSpan)}; " - + $"latest continuous segment: {segment.Length.ToString(CultureInfo.InvariantCulture)} measurements over {FormatDuration(segmentSpan)}; " - + $"adaptive weekly cycles: {adaptiveCycleCount.ToString(CultureInfo.InvariantCulture)}. " - + "This is descriptive evidence, not a calibrated reliability probability."; - return new UsagePlanningEvidence( - samples.Length, - measurementSpan, - segment.Length, - segmentSpan, - adaptiveCycleCount, - summary); - } - - private static UsagePlanningBacktest CreateBacktest( - RateLimitWindow window, - IReadOnlyList history, - DateTimeOffset now, - TimeSpan maximumSampleAge) - { - var segment = GetLatestSegment(history, window, now, maximumSampleAge); - if (segment.Length < 3) - { - return UsagePlanningBacktest.Unavailable( - "Backtest unavailable: at least three continuous measurements are required to hold out the latest one."); - } - - var heldOut = segment[^1]; - var training = segment[..^1]; - var first = training[0]; - var last = training[^1]; - var trainingSpan = last.RecordedAt - first.RecordedAt; - var holdoutInterval = heldOut.RecordedAt - last.RecordedAt; - if (training.Length < 2 - || trainingSpan <= TimeSpan.Zero - || holdoutInterval <= TimeSpan.Zero - || holdoutInterval > MaximumGap(maximumSampleAge)) - { - return UsagePlanningBacktest.Unavailable( - "Backtest unavailable: the held-out measurement does not follow a meaningful continuous pace."); - } - - var consumed = first.RemainingPercent - last.RemainingPercent; - var rate = consumed / trainingSpan.TotalMinutes; - if (!double.IsFinite(rate) || rate <= 0) - { - return UsagePlanningBacktest.Unavailable( - "Backtest unavailable: preceding measurements do not show a usable downward pace."); - } - - var predicted = Math.Clamp( - last.RemainingPercent - rate * holdoutInterval.TotalMinutes, - 0, - 100); - var error = Math.Abs(predicted - heldOut.RemainingPercent); - var status = $"Holdout at {FormatUtc(heldOut.RecordedAt)}: predicted {FormatPercent(predicted)}%, " - + $"actual {FormatPercent(heldOut.RemainingPercent)}%, absolute error {FormatPercent(error)} percentage points; " - + "the latest measurement was excluded from the preceding-pace calculation."; - return new UsagePlanningBacktest( - true, - training.Length, - heldOut.RecordedAt, - predicted, - heldOut.RemainingPercent, - error, - status); - } - - private static UsageHistoryEntry[] GetLatestSegment( - IReadOnlyList history, - RateLimitWindow window, - DateTimeOffset now, - TimeSpan maximumSampleAge) - { - if (!TryGetWindowStart(window, out var windowStart)) - { - return []; - } - - try - { - return UsageTrendHistory.LatestSegment( - history ?? Array.Empty(), - windowStart, - window.ResetsAt, - now, - MaximumGap(maximumSampleAge)); - } - catch (ArgumentException) - { - return []; - } - catch (InvalidOperationException) - { - return []; - } - catch (OverflowException) - { - return []; - } - } - - private static UsageHistoryEntry[] GetWindowSamples( - IReadOnlyList history, - RateLimitWindow window, - DateTimeOffset now) - { - if (!TryGetWindowStart(window, out var windowStart) || history is null) - { - return []; - } - - try - { - return history - .Where(sample => sample is not null - && double.IsFinite(sample.RemainingPercent) - && sample.RemainingPercent is >= 0 and <= 100 - && sample.RecordedAt >= windowStart - && sample.RecordedAt <= window.ResetsAt - && sample.RecordedAt <= now) - .OrderBy(sample => sample.RecordedAt) - .GroupBy(sample => sample.RecordedAt) - .Select(group => group.Last()) - .ToArray(); - } - catch (ArgumentException) - { - return []; - } - catch (InvalidOperationException) - { - return []; - } - catch (OverflowException) - { - return []; - } - } - - private static TimeSpan? GetSpan(UsageHistoryEntry[] samples) - { - if (samples.Length < 2) - { - return null; - } - - try - { - return samples[^1].RecordedAt - samples[0].RecordedAt; - } - catch (ArgumentOutOfRangeException) - { - return null; - } - } - - private static int CountAdaptiveCycles(UsagePresentation presentation) - { - var history = presentation.AdaptiveWeeklyHistory; - if (history is null) - { - return 0; - } - - var completed = history.CompletedCycles?.Count(cycle => cycle is not null) ?? 0; - return completed + (history.ActiveCycle is null ? 0 : 1); - } - - private static int CalendarDaysUntilReset(DateTimeOffset resetsAt, DateTimeOffset now, TimeZoneInfo timeZone) - { - var days = (TimeZoneInfo.ConvertTime(resetsAt, timeZone).Date - TimeZoneInfo.ConvertTime(now, timeZone).Date).Days; - if (days <= 1) - { - return 1; - } - - return days; - } - - private static TimeSpan MaximumGap(TimeSpan maximumSampleAge) - { - if (maximumSampleAge <= TimeSpan.Zero) - { - return TimeSpan.FromMinutes(15); - } - - return maximumSampleAge.Ticks > TimeSpan.MaxValue.Ticks / 3 - ? TimeSpan.MaxValue - : TimeSpan.FromTicks(maximumSampleAge.Ticks * 3); - } - - private static bool TryGetWindowStart(RateLimitWindow window, out DateTimeOffset start) - { - try - { - start = window.ResetsAt - TimeSpan.FromMinutes(window.WindowMinutes); - return true; - } - catch (ArgumentOutOfRangeException) - { - start = default; - return false; - } - catch (OverflowException) - { - start = default; - return false; - } - } - - private static string FormatDuration(TimeSpan? duration) - { - if (duration is not { } value) - { - return "unknown span"; - } - - if (value.TotalMinutes < 1) - { - return $"{Math.Max(1, (int)Math.Round(value.TotalSeconds))} seconds"; - } - - if (value.TotalHours < 1) - { - return $"{Math.Round(value.TotalMinutes, 1).ToString("0.#", CultureInfo.InvariantCulture)} minutes"; - } - - if (value.TotalDays < 1) - { - return $"{Math.Round(value.TotalHours, 1).ToString("0.#", CultureInfo.InvariantCulture)} hours"; - } - - return $"{Math.Round(value.TotalDays, 1).ToString("0.#", CultureInfo.InvariantCulture)} days"; - } - - private static string FormatPercent(double value) => value.ToString("0.##", CultureInfo.InvariantCulture); - - private static string FormatWindowDuration(int minutes) - { - if (minutes == (int)TimeSpan.FromHours(5).TotalMinutes) - { - return "5-hour"; - } - - if (minutes == (int)TimeSpan.FromDays(7).TotalMinutes) - { - return "weekly"; - } - - if (minutes > 0 && minutes % (int)TimeSpan.FromDays(1).TotalMinutes == 0) - { - return $"{minutes / (int)TimeSpan.FromDays(1).TotalMinutes}-day"; - } - - if (minutes > 0 && minutes % 60 == 0) - { - return $"{minutes / 60}-hour"; - } - - return $"{minutes}-minute"; - } - - private static string FormatUtc(DateTimeOffset value) => - value.ToUniversalTime().ToString("yyyy-MM-dd HH:mm 'UTC'", CultureInfo.InvariantCulture); - - private static UsagePlanningResult Unavailable( - DateTimeOffset desiredEnd, - string status, - int? remainingWorkdays) => - new(false, status, desiredEnd, remainingWorkdays, null, null, Disclaimer); -} - -internal sealed record UsagePlanningResult( - bool IsAvailable, - string Status, - DateTimeOffset DesiredEnd, - int? RequestedWorkdays, - UsagePlanningWindow? Primary, - UsagePlanningWindow? Weekly, - string Disclaimer) -{ - internal UsagePlanningWindow? FiveHour => Primary; - - internal IReadOnlyList Windows => - new[] { Primary, Weekly }.Where(window => window is not null).Cast().ToArray(); - - internal IReadOnlyList Evidence => - Windows.Select(window => window.Evidence).ToArray(); - - internal IReadOnlyList Backtests => - Windows.Select(window => window.Backtest).ToArray(); -} - -internal sealed record UsagePlanningWindow( - string Label, - double RemainingPercent, - int WindowMinutes, - DateTimeOffset ResetsAt, - DateTimeOffset HorizonEnd, - int Workdays, - TimeSpan Horizon, - double AvailablePointsPerWorkday, - double AvailablePointsPerHour, - bool ResetsBeforeDesiredEnd, - string HorizonMessage, - UsagePlanningForecast Forecast, - UsagePlanningEvidence Evidence, - UsagePlanningBacktest Backtest) -{ - internal double Remaining => RemainingPercent; - internal double QuotaPointsPerWorkday => AvailablePointsPerWorkday; - internal double QuotaPointsPerHour => AvailablePointsPerHour; -} - -internal sealed record UsagePlanningForecast( - bool IsAvailable, - UsageTrendForecast? Projection, - string Status) -{ - internal UsageTrendForecast? Forecast => Projection; - internal DateTimeOffset? EndsAt => Projection?.EndsAt; - internal bool ReachesLimitBeforeReset => Projection?.ReachesLimitBeforeReset ?? false; - - internal static UsagePlanningForecast Unavailable(string status) => new(false, null, status); -} - -internal sealed record UsagePlanningEvidence( - int MeasurementCount, - TimeSpan? MeasurementSpan, - int SegmentMeasurementCount, - TimeSpan? SegmentSpan, - int AdaptiveCycleCount, - string Summary) -{ - internal string Description => Summary; -} - -internal sealed record UsagePlanningBacktest( - bool IsAvailable, - int TrainingSampleCount, - DateTimeOffset? HeldOutAt, - double? PredictedRemainingPercent, - double? ActualRemainingPercent, - double? AbsoluteErrorPercentagePoints, - string Status) -{ - internal string Message => Status; - internal static UsagePlanningBacktest Unavailable(string status) => new(false, 0, null, null, null, null, status); -} diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index f780b24..206a746 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -99,6 +99,8 @@ Store install, update, and uninstall behavior must be tested with a Store-signed For settings and storage changes, also restart Command Palette and Windows in the isolated test environment and verify all saved choices, including the first refresh interval. Make the test settings/history file unwritable, verify a visible failure, restore write access, and retry. A failed learned-history deletion must preserve the saved history; a successful deletion must remain cleared after restart. With a large synthetic session directory, verify that limits appear before token analysis completes and that text and chart projections both pause after a measurement gap. +When upgrading from a development build with manual source paths or the Claude pilot, verify that those fields and the source-profile and Claude commands are absent. Old saved values must not prevent automatic Codex detection, and saved Claude Dock pins must not restore a band. Saving another preference must preserve the remaining Codex choices and omit the obsolete settings fields. Existing profile files and external capture scripts or files are not removed by this upgrade. + ## Build the Microsoft Store package The package artwork is generated from one canonical visual mark. Treat `scripts/generate-assets.ps1` as its source instead of editing individual PNG files. The release builder compares decoded artwork with a small rendering tolerance, because PNG encoding and anti-aliasing can differ between supported build hosts without changing the design: diff --git a/PRIVACY.md b/PRIVACY.md index ac7cd4b..244ea7a 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -1,6 +1,6 @@ # Privacy Policy -Last updated: September 9, 2026 +Last updated: September 13, 2026 Codex Usage Dock is a local Windows extension for PowerToys Command Palette. It displays Codex usage limits, earned resets, reset expiry times, and available credits in the Command Palette Dock. @@ -16,18 +16,22 @@ Communication initiated by the extension is limited to the local Codex app-serve ## Data storage -Settings are saved explicitly in `CodexUsageDock/settings.json` under the current Windows user's local application data directory, alongside the local history files. This file contains display, refresh, planning, retention, forecasting, and explicit source preferences. Failed writes are reported without logging file contents, personal paths, or credentials. Learned-history deletion is confirmed only after its empty state has been saved successfully. +Settings are saved explicitly in `CodexUsageDock/settings.json` under the current Windows user's local application data directory, alongside the local history files. This file contains display, refresh, retention, and forecasting preferences. Failed writes are reported without logging file contents, personal paths, or credentials. Learned-history deletion is confirmed only after its empty state has been saved successfully. The extension does not create an external user account or remote database. Settings and temporary runtime state remain on the user's Windows device. Daily token totals and per-file read positions are kept only in memory and are rebuilt from the current weekly window after a restart. To keep the weekly usage trend available after Command Palette restarts, it stores a rolling maximum of seven days of local timestamps and remaining weekly-percentage measurements. When the adaptive weekly forecast is enabled, it also stores at most eight aggregated quota-cycle profiles: total observed duration and consumption, plus six-hour usage buckets relative to the reset. These files contain no account, session, prompt, or message content and are never transmitted. Users can pause learning while keeping those profiles; measurements collected while paused are not added later. Users can also delete the learned profiles from Codex Usage settings. Account-scoped history uses a one-way hash of the account identity supplied by Codex, combined with the default quota category, as an opaque local directory name. Raw account identifiers and email addresses are not stored or shown in diagnostics. Legacy history without account attribution is not imported into a verified account; unverified observations remain in memory and do not train saved forecasts. The last confirmed usage snapshot is retained only in memory during an outage, with its original timestamp. Diagnostics exposes field availability and bounded status messages, not raw service errors, credentials, or personal paths. -Optional source preferences store the user-selected executable and Codex home paths locally in settings. These paths are not included in diagnostic reports or logs. Account activity requests travel through the local Codex app-server and retain only aggregate daily token counts and optional totals in memory. Identity is checked before and after each request. Optional usage notifications contain a quota label and bounded status text, without account identifiers; their deduplication state remains in memory. Disabling account activity clears the visible account activity state and stops new optional reads. +Account activity requests travel through the local Codex app-server and retain only aggregate daily token counts and optional totals in memory. Identity is checked before and after each request. Optional usage notifications contain a quota label and bounded status text, without account identifiers; their deduplication state remains in memory. Disabling account activity clears the visible account activity state and stops new optional reads. Optional retained history stores at most 27,000 aggregate quota observations with UTC timestamps and reset times, separated by hashed account/category context. The selected retention is 7, 30, or 90 days; collection starts only after opting in. Explicit CSV/JSON exports create local files without account IDs or conversation content. Users control deletion of retained observations and exported copies separately. Neither retained observations nor exports contain prompts or task contents. An explicitly requested task-usage read passes the user-entered task ID through the local Codex app-server and keeps the resulting aggregate estimates only in memory. A confirmed earned-reset action sends a mutation through that server. Before sending, the extension stores a random request ID in the account's hashed local context. An unresolved ID is retained across restarts so a retry cannot accidentally become a separate redemption. Recovery records contain no authentication credentials or raw account identifiers and are separate from history deletion. +The quota fallback keeps bounded file metadata, read positions, partial lines, and its latest parsed quota event only in memory. + +Source-path, source-label, and Claude preferences from earlier development builds are ignored and omitted on the next settings save. The extension no longer reads saved source-profile or Claude capture files. Existing profile files and externally configured capture scripts or files remain under the user's control and are not deleted or modified by the extension. + ## Permissions The Windows `runFullTrust` capability is required to run the packaged Command Palette COM server and to communicate with the locally installed Codex process. It is not used to bypass Windows security controls or access unrelated user data. diff --git a/README.md b/README.md index a333e1c..ab7dc91 100644 --- a/README.md +++ b/README.md @@ -46,11 +46,11 @@ Codex Usage Dock is activated inside PowerToys Command Palette and intentionally 5. Choose **Add command** (`+`) in the section where you want the widget. 6. Search for **Codex Usage** and select its Dock band. -The Dock will show entries similar to `5h 47%`, `Week 86%`, and `2 resets · 10.00`. The percentages represent the amount remaining. The final entry shows available earned resets, the time until the next reset credit expires in whole hours or days, and, when available, the credits balance. Select an entry to see reset expiry details or refresh the data manually. +The Dock will show entries similar to `5h 47%`, `Week 86%`, and `2 resets · 10.00`. The percentages represent the amount remaining. Quota subtitles show the next reset, such as `Reset - 15 sept 12:56`. The final entry shows available earned resets, the next credit expiry as `Expires - 4 okt 4:00`, and, when available, the credits balance. Dates use your local time zone and abbreviated month names from your regional settings. Stale or fallback data retains its source warning. Select an entry to see reset expiry details or refresh the data manually. ## Customize the Dock -**Compact Dock** shortens quota labels to forms such as `5h47%` and `W86%` and hides reset times while retaining stale/source warnings. **Separate Dock items** offers each metric as a separate pinnable band; existing combined-band and individual pin identifiers remain resolvable after changing modes. +**Compact Dock** shortens quota labels to forms such as `5h47%` and `W86%` and hides reset times while retaining stale/source warnings. **Separate Dock items** offers each visible metric as a separate pinnable band. Turning it off offers the combined band. Pins belonging to the inactive mode and hidden metrics stop displaying items and are not restored as active bands after a reload. Command Palette keeps its saved pins: switching modes does not move or convert them. Add the desired bands through Dock customization if they were not already pinned; switching back makes matching saved pins available again. **Enable usage alerts** is off by default. When enabled, fresh, identified account data can notify on a downward crossing of 10% remaining, a new projected limit within one hour, or a reset credit entering its last 24 hours. The first measurement establishes a baseline. Duplicate refreshes do not repeat alerts, small reset-time fluctuations stay in the same cycle, and account/category changes start a new baseline. Multiple simultaneous alerts are combined into one host notification. Delivery depends on the Command Palette host. @@ -64,15 +64,19 @@ Microsoft Store installs updates automatically. You can also check for updates f ## Sources and account activity -Settings accepts an optional full path to a standalone `codex.exe` or `codex.cmd` and an optional Codex home directory. Empty fields retain environment-based discovery. An explicit directory can be a Windows-accessible WSL path; the extension reads that directory and passes it to the Windows CLI as `CODEX_HOME`, without starting WSL or changing Codex configuration. Inaccessible or invalid explicit paths stop source reads and show a settings error. A profile change clears the displayed context and discards results from the previous in-flight read. +Codex is detected automatically using the existing environment configuration described in [Requirements](#requirements). Local session readers use `CODEX_HOME` when set, otherwise the current user's `.codex` directory. The extension has no path fields or source-profile selection in its settings. + +Saved source paths, source labels, and Claude preferences from earlier development builds are ignored. Other Codex preferences are preserved, and obsolete fields are omitted the next time settings are saved. Old source-profile files and externally configured capture scripts or files are not deleted or modified by the extension. **Codex account activity** shows account-wide token summaries and up to 30 recent server-calendar days when `account/usage/read` is supported. It updates independently after quota data, at most every five minutes automatically; unsupported versions retry after 30 minutes. **Refresh now** on that page requests an immediate retry. Disable **Show account activity** to stop these optional reads. Account identity must match before and after the request. Missing days and fields are not zero usage, and the server's unspecified calendar time zone is kept separate from local calendar-day chart bars. No account activity is written to disk by this feature. -## History, planning, and optional account actions +**Codex usage in text**, also available from Details, provides quota tables, reset times, recent measured weekly points, and local daily token totals without relying on charts or color. Missing values, reported zero, expired windows, and last-confirmed observations have distinct text labels. + +## History and optional account actions **Codex usage history** retains quota observations only when **Retain usage observations** is set to 7, 30, or 90 days. Observations are scoped to the identified account and default quota category, sampled in five-minute buckets, and capped at 27,000 rows. Reset changes within a bucket remain separate observations. Pausing collection keeps retained data; the history page offers confirmed deletion for the selected context. CSV and JSON export actions write files to the extension's local application data `exports` folder and show the resulting path. Exports contain quota percentages and UTC observation/reset times, without account IDs or conversation content. Exported copies are not deleted when retained history is cleared. -**Codex workday planner** uses today's local **Workday end** and your chosen **Workdays remaining before weekly reset**. It divides remaining weekly allowance across those days and today's remaining hours; the five-hour allowance is budgeted independently. Planning stops at an earlier reset and pauses after today's chosen end. It requires fresh, identified live data. The page explains the measurement span, continuous segment, learned-cycle count, and a held-out latest-observation check where sufficient data exists. This is descriptive evidence, not a calibrated confidence percentage or a guarantee. Its recent-pace estimate is separate from the dashboard's optional adaptive weekly forecast. +The workday planner and its end-time and remaining-workdays settings have been removed. Forecasts use observed usage without requiring a work schedule. Saved planner preferences from earlier development builds are ignored and omitted the next time settings are saved; other preferences and usage history are preserved. **Codex task usage and earned resets** accepts an explicit task ID for `account/usage/read` on compatible CLI versions. It shows server-estimated credits and optional USD, plus model/effort/speed and available input/cached/output token groups. These estimates are not invoices or conversions of quota percentages. Task reads verify account identity before and after, keep the most recently requested task, and retain results only in memory. @@ -110,6 +114,8 @@ Freshness uses the greater of five minutes and the configured refresh interval t When Codex supplies an account identity, weekly history and learned profiles are stored separately for that account and default quota category using opaque hashed directory names. History appears only after the account is identified. Older history files have no identity and are not imported into an account. Without a verified account identity, recent observations remain in memory and adaptive learning is paused. +The local quota fallback caches read positions and the latest valid quota event in memory. Unchanged files still in its cache are not reread for content; appended, replaced, truncated, and deleted files are handled on later refreshes. Each scan reads at most 8 MiB of file content, tracks up to 512 files, and bounds partial lines to 128 KiB. It still enumerates session file metadata and skips inaccessible subdirectories; these limits do not promise constant scan time for large directories. Incomplete scans are reported, and later refreshes continue discovery. No session payload or read-position cache is saved to disk by this quota fallback. + ## Development Build, test, Store packaging, and release instructions are in [DEVELOPMENT.md](DEVELOPMENT.md). diff --git a/SPRINTS.md b/SPRINTS.md index f8ad822..60e1765 100644 --- a/SPRINTS.md +++ b/SPRINTS.md @@ -1,13 +1,15 @@ # Usage assistant implementation -This series implements the recommended Codex-first roadmap, followed by a small, optional Claude pilot. Source work uses separate feature branches and pull requests. Merge, Store publication, and installation are separate steps. +This series implements a Codex-only usage roadmap. Source work uses separate feature branches and pull requests. Merge, Store publication, and installation are separate steps. + +The sprint records below describe the original PRs and their historical verification. The current implementation removes the Claude pilot, manual source-path settings, named source profiles, and workday planner, while retaining automatic Codex detection, bounded fallback reads, accessible text views, and usage-based forecasts. See [CHANGELOG.md](CHANGELOG.md) for the current scope. | Sprint | Feature branch | Scope | Status | | --- | --- | --- | --- | | 1 | `codex/sprint-1-reliable-usage` | Modern quota categories, consistent freshness, last confirmed data, account-scoped history, safe diagnostics, version communication | [PR #18](https://github.com/TheBeems/CodexUsageDock/pull/18); 186 native ARM64 tests passed; x64/ARM64 Debug builds passed | | 2 | `codex/sprint-2-attention-controls` | Quiet alerts, compact and individually pinnable Dock entries, account activity where supported, explicit source configuration | [PR #19](https://github.com/TheBeems/CodexUsageDock/pull/19); 235 x64 tests, both architecture builds, and package validation passed in CI | -| 3 | `codex/sprint-3-history-planning` | Retained aggregates and export, workday planning, forecast explanation and validation, supported task analysis, explicit earned-reset action | [PR #20](https://github.com/TheBeems/CodexUsageDock/pull/20); 314 native ARM64 tests and both architecture builds passed | -| 4 | `codex/sprint-4-provider-pilot` | Optional Claude statusline bridge, explicit local profiles/WSL paths, efficient fallback reads, accessible text alternatives | Planned | +| 3 | `codex/sprint-3-history-planning` | Retained aggregates and export, workday planning, forecast explanation and validation, supported task analysis, explicit earned-reset action | [PR #20](https://github.com/TheBeems/CodexUsageDock/pull/20); 314 native ARM64 tests; x64 tests, both builds, and package validation passed in CI | +| 4 | `codex/sprint-4-provider-pilot` | Optional Claude statusline bridge, explicit local profiles/WSL paths, efficient fallback reads, accessible text alternatives | [PR #21](https://github.com/TheBeems/CodexUsageDock/pull/21); 360 native ARM64 tests and both architecture builds passed; final GitHub validation recorded in the PR | Later sprints build on the previous feature branch so each PR can show only its own increment. Merge in sprint order and retarget dependent PRs to `main` after their base is merged. No merge is performed as part of this implementation request. @@ -34,6 +36,14 @@ The x64 and ARM64 application code compiles without warnings. Local ARM64 test e ### Sprint 3 verification -Native ARM64 test execution was available again and passed 314 tests. Both application architecture builds passed without warnings. Tests cover retention/export scope, planner assumptions and held-out observations, optional protocol support, task-request ordering, and persistent reset idempotency across ambiguous results and restarts. No real reset was redeemed. Command Palette forms, confirmations, and real-account compatibility still need live verification after an authorized installation. The GitHub workflow validates the pushed branch separately. +Native ARM64 test execution was available again and passed 314 tests. Both application architecture builds passed without warnings. Tests cover retention/export scope, planner assumptions and held-out observations, optional protocol support, task-request ordering, and persistent reset idempotency across ambiguous results and restarts. No real reset was redeemed. Command Palette forms, confirmations, and real-account compatibility still need live verification after an authorized installation. The final head `ebe7efe` passed all 314 x64 tests, both builds, and package validation in [GitHub Actions](https://github.com/TheBeems/CodexUsageDock/actions/runs/34385299160). Both integration preflights passed source/generated manifest, identity, asset, and self-contained runtime checks. The registered ARM64 Store package was healthy and discoverable, but its process and registration do not point at the new Debug builds. These expected mismatches leave live verification of the new code open; no registration or installation was changed. + +### Sprint 4 scope + +The pilot uses only an explicit local Claude capture and keeps its two quota windows and refresh state independent of Codex. The optional script preserves a formatter's input or displays a standalone quota line; setup is manual and described in README. Profiles save at most eight names and validated source paths, including Windows-accessible WSL directories, without copying credentials or launching WSL. Text views expose measured values without chart or color dependence. The quota fallback has bounded content reads and caches read positions; filesystem metadata enumeration remains proportional to the session inventory. + +Execution used separate protocol/integration and implementation agents, with Luna at max effort for the bounded implementation tasks. Review covered provider concurrency and profile changes. Tests use synthetic local data; no real Claude configuration, account authentication, or reset redemption is part of verification. + +All 360 native ARM64 tests passed, including script execution on synthetic stdin, profile persistence and invalid input, independent provider refresh, and bounded incremental session reads. Both application builds passed with zero warnings. Only the pre-existing test-name analyzer warnings remain. The two integration preflights passed source/generated manifest, COM identity, asset, output-freshness, and self-contained runtime checks. Registration and process matching failed as expected because Command Palette runs the installed ARM64 Store package rather than either new Debug build; the x64 preflight also reports the installed architecture mismatch. No package was registered or installed. Live forms, accessibility, Dock pinning, and real-provider compatibility remain unverified; GitHub validation is recorded in the sprint PR.