diff --git a/CHANGELOG.md b/CHANGELOG.md index d1b7db9..2e8827c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,19 +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)) +- 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)) - 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 +- 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/AccountUsageTests.cs b/CodexUsageDock.Tests/AccountUsageTests.cs new file mode 100644 index 0000000..3dce9a8 --- /dev/null +++ b/CodexUsageDock.Tests/AccountUsageTests.cs @@ -0,0 +1,277 @@ +using System.Text.Json; +using Xunit; + +namespace CodexUsageDock.Tests; + +public sealed class AccountUsageTests +{ + private static readonly DateTimeOffset Now = new(2026, 9, 9, 12, 0, 0, TimeSpan.Zero); + + [Fact] + public void ParsesServerCalendarDaysAndNullableSummaryWithoutInventingValues() + { + var result = Parse(""" + { + "summary": { + "lifetimeTokens": 123456, + "peakDailyTokens": 0, + "longestRunningTurnSec": 3600, + "currentStreakDays": null, + "longestStreakDays": 12 + }, + "dailyUsageBuckets": [ + { "startDate": "2026-09-09", "tokens": 2000 }, + { "startDate": "2026-09-07", "tokens": 0 } + ] + } + """); + + Assert.Equal(AccountUsageStatus.Available, result.Status); + Assert.Equal("synthetic-hash", result.AccountKey); + Assert.Equal(Now, result.UpdatedAt); + Assert.Equal(123456, result.LifetimeTokens); + Assert.Equal(0, result.PeakDailyTokens); + Assert.Equal(3600, result.LongestRunningTurnSeconds); + Assert.Null(result.CurrentStreakDays); + Assert.Equal(12, result.LongestStreakDays); + Assert.Collection(result.Days, + day => Assert.Equal(new DailyTokenUsage(new DateOnly(2026, 9, 7), 0), day), + day => Assert.Equal(new DailyTokenUsage(new DateOnly(2026, 9, 9), 2000), day)); + } + + [Fact] + public void InvalidDatesNegativeTokensOverflowAndDuplicatesYieldPartialData() + { + var result = Parse(""" + { + "summary": { "lifetimeTokens": -1, "peakDailyTokens": 9223372036854775808, "currentStreakDays": "10" }, + "dailyUsageBuckets": [ + { "startDate": "2026-09-09", "tokens": 100 }, + { "startDate": "2026-09-09", "tokens": 200 }, + { "startDate": "2026-02-30", "tokens": 100 }, + { "startDate": "2026-9-8", "tokens": 100 }, + { "startDate": "2026-09-08T00:00:00Z", "tokens": 100 }, + { "startDate": "2026-09-08", "tokens": -1 }, + { "startDate": "2026-09-07", "tokens": 9223372036854775808 }, + { "startDate": "2026-09-06", "tokens": "100" }, + null + ] + } + """); + + Assert.Equal(AccountUsageStatus.Partial, result.Status); + Assert.Equal(100, Assert.Single(result.Days).TotalTokens); + Assert.Null(result.LifetimeTokens); + Assert.Null(result.PeakDailyTokens); + Assert.Null(result.CurrentStreakDays); + } + + [Fact] + public void RetainsAtMost366LatestServerDaysAndMarksTruncation() + { + var start = new DateOnly(2024, 1, 1); + var daily = Enumerable.Range(0, 370).Select(index => new + { + startDate = start.AddDays(index).ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture), + tokens = index, + }); + + var result = Parse(JsonSerializer.Serialize(new { dailyUsageBuckets = daily })); + + Assert.Equal(AccountUsageStatus.Partial, result.Status); + Assert.Equal(AccountUsageParser.MaximumDays, result.Days.Count); + Assert.Equal(start.AddDays(4), result.Days[0].Date); + Assert.Equal(start.AddDays(369), result.Days[^1].Date); + } + + [Theory] + [InlineData("{}")] + [InlineData("null")] + [InlineData("[]")] + [InlineData("{\"summary\":{\"lifetimeTokens\":null},\"dailyUsageBuckets\":null}")] + public void MissingDataIsUnavailableRatherThanZero(string json) + { + var result = Parse(json); + + Assert.Equal(AccountUsageStatus.Unavailable, result.Status); + Assert.Empty(result.Days); + Assert.Null(result.LifetimeTokens); + Assert.Null(result.AccountKey); + } + + [Fact] + public void SummaryWithoutDailyDataIsPartialAndConfirmedEmptyRowsRemainAvailable() + { + var summaryOnly = Parse("""{"summary":{"lifetimeTokens":0},"dailyUsageBuckets":null}"""); + var emptyDays = Parse("""{"summary":{"lifetimeTokens":null},"dailyUsageBuckets":[]}"""); + + Assert.Equal(AccountUsageStatus.Partial, summaryOnly.Status); + Assert.Equal(0, summaryOnly.LifetimeTokens); + Assert.Equal(AccountUsageStatus.Available, emptyDays.Status); + Assert.Empty(emptyDays.Days); + Assert.Null(emptyDays.LifetimeTokens); + } + + [Fact] + public async Task ActivityIsReadBetweenMatchingAccountChecks() + { + var requests = new List<(string Method, int Id)>(); + var result = await CodexAppServerReader.ReadAccountUsageSequenceAsync((method, id, _) => + { + requests.Add((method, id)); + return Task.FromResult(JsonDocument.Parse(method == "account/usage/read" + ? """{"result":{"dailyUsageBuckets":[{"startDate":"2026-09-09","tokens":100}]}}""" + : """{"result":{"accountId":"synthetic-account"}}""")); + }); + + Assert.Equal(new[] { ("account/rateLimits/read", 2), ("account/usage/read", 3), ("account/rateLimits/read", 4) }, requests); + Assert.Equal(AccountUsageStatus.Available, result.Status); + Assert.Equal(100, Assert.Single(result.Days).TotalTokens); + Assert.Equal(64, result.AccountKey!.Length); + Assert.DoesNotContain("synthetic-account", JsonSerializer.Serialize(result), StringComparison.Ordinal); + } + + [Fact] + public async Task AccountChangeDiscardsEveryUsageValue() + { + var result = await CodexAppServerReader.ReadAccountUsageSequenceAsync((method, id, _) => + Task.FromResult(JsonDocument.Parse(id switch + { + 2 => """{"result":{"accountId":"synthetic-account-A"}}""", + 3 => """{"result":{"summary":{"lifetimeTokens":123},"dailyUsageBuckets":[{"startDate":"2026-09-09","tokens":100}]}}""", + _ => """{"result":{"accountId":"synthetic-account-B"}}""", + }))); + + Assert.Equal(AccountUsageStatus.Unavailable, result.Status); + Assert.Empty(result.Days); + Assert.Null(result.AccountKey); + Assert.Null(result.LifetimeTokens); + } + + [Fact] + public async Task MissingInitialIdentitySkipsTheAccountUsageRequest() + { + var count = 0; + var result = await CodexAppServerReader.ReadAccountUsageSequenceAsync((_, _, _) => + { + count++; + return Task.FromResult(JsonDocument.Parse("""{"result":{"accountId":null}}""")); + }); + + Assert.Equal(1, count); + Assert.Equal(AccountUsageStatus.Unavailable, result.Status); + } + + [Theory] + [InlineData("{\"result\":{\"accountId\":null}}")] + [InlineData("{\"error\":{\"code\":-1,\"message\":\"private details\"}}")] + public async Task MissingFinalIdentityDiscardsActivity(string finalResponse) + { + var result = await CodexAppServerReader.ReadAccountUsageSequenceAsync((_, id, _) => + Task.FromResult(JsonDocument.Parse(id switch + { + 2 => """{"result":{"accountId":"synthetic-account"}}""", + 3 => """{"result":{"dailyUsageBuckets":[]}}""", + _ => finalResponse, + }))); + + Assert.Equal(AccountUsageStatus.Unavailable, result.Status); + Assert.Null(result.AccountKey); + Assert.DoesNotContain("private", JsonSerializer.Serialize(result), StringComparison.Ordinal); + } + + [Fact] + public async Task MethodNotFoundIsUnsupportedWithoutReadingOrExposingErrorText() + { + var requests = 0; + var result = await CodexAppServerReader.ReadAccountUsageSequenceAsync((_, id, _) => + { + requests++; + return Task.FromResult(JsonDocument.Parse(id == 2 + ? """{"result":{"accountId":"synthetic-account"}}""" + : """{"error":{"code":-32601,"message":"private path or credential"}}""")); + }); + + Assert.Equal(AccountUsageStatus.Unsupported, result.Status); + Assert.Equal(2, requests); + Assert.Empty(result.Days); + Assert.DoesNotContain("private", JsonSerializer.Serialize(result), StringComparison.Ordinal); + } + + [Fact] + public async Task PreCanceledActivityReadDoesNotStartARequest() + { + await Assert.ThrowsAsync(() => + CodexAppServerReader.ReadAccountUsageSequenceAsync((_, _, _) => throw new InvalidOperationException("Must not run"), + new CancellationToken(canceled: true))); + } + + [Fact] + public async Task ResponseReaderIgnoresUnrelatedMalformedIdentifiers() + { + using var reader = new StringReader(""" + [] + {"id":"2","result":{}} + {"id":2,"result":{}} + """); + + var responses = await CodexAppServerReader.ReadResponsesAsync(reader, CancellationToken.None, 2); + using var response = responses[2]; + Assert.Equal(2, response.RootElement.GetProperty("id").GetInt32()); + } + + [Fact] + public async Task ResponseReaderRejectsOversizedMessagesWithABoundedError() + { + using var reader = new StringReader(new string('x', 1_048_577)); + + var error = await Assert.ThrowsAsync(() => + CodexAppServerReader.ReadResponsesAsync(reader, CancellationToken.None, 2)); + + Assert.Equal("Codex app-server returned an oversized response.", error.Message); + } + + [Fact] + public void ConfiguredSourceUsesProcessArgumentsAndAnEnvironmentVariable() + { + var executable = Path.Combine(Path.GetTempPath(), "synthetic cli", "codex.exe"); + var home = Path.Combine(Path.GetTempPath(), "synthetic profile & account"); + + var info = CodexAppServerReader.CreateStartInfo(new CodexSourceOptions(executable, home)); + + Assert.Equal(executable, info.FileName); + Assert.Collection(info.ArgumentList, + argument => Assert.Equal("app-server", argument), + argument => Assert.Equal("--stdio", argument)); + Assert.Equal(home, info.Environment["CODEX_HOME"]); + Assert.Equal(Path.GetDirectoryName(executable), info.WorkingDirectory); + Assert.False(info.UseShellExecute); + Assert.True(info.CreateNoWindow); + Assert.Empty(info.Arguments); + } + + [Fact] + public void ActivityPageShowsAtMost30ServerDatesAndNeverAccountIdentifiers() + { + var start = new DateOnly(2026, 8, 1); + var snapshot = new AccountUsageSnapshot("sensitive-account-key", Now, + Enumerable.Range(0, 40).Select(index => new DailyTokenUsage(start.AddDays(index), index)).ToArray(), + AccountUsageStatus.Partial, LifetimeTokens: 0); + + var text = CodexAccountActivityPage.FormatActivity(snapshot); + + Assert.Contains("Partial data", text, StringComparison.Ordinal); + Assert.Contains("Their time zone is not specified", text, StringComparison.Ordinal); + Assert.Contains("**Lifetime tokens:** 0", text, StringComparison.Ordinal); + Assert.Contains("**Peak daily tokens:** Not reported", text, StringComparison.Ordinal); + Assert.Equal(30, text.Split('\n').Count(line => line.StartsWith("| 2026-", StringComparison.Ordinal))); + Assert.DoesNotContain("sensitive-account-key", text, StringComparison.Ordinal); + Assert.DoesNotContain("| 2026-08-01", text, StringComparison.Ordinal); + } + + private static AccountUsageSnapshot Parse(string json) + { + using var document = JsonDocument.Parse(json); + return AccountUsageParser.Parse(document.RootElement, "synthetic-hash", Now); + } +} 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/HistoryIntegrationTests.cs b/CodexUsageDock.Tests/HistoryIntegrationTests.cs new file mode 100644 index 0000000..4cd6965 --- /dev/null +++ b/CodexUsageDock.Tests/HistoryIntegrationTests.cs @@ -0,0 +1,201 @@ +using System.Text.Json; +using Microsoft.CommandPalette.Extensions.Toolkit; +using Xunit; + +namespace CodexUsageDock.Tests; + +public sealed class HistoryIntegrationTests : IDisposable +{ + private static readonly DateTimeOffset Now = new(2026, 9, 9, 12, 0, 0, TimeSpan.Zero); + private readonly TestEnvironment _environment = new(); + + public void Dispose() => _environment.Dispose(); + + [Fact] + public void RetentionPreferencesRoundTripAndExposeSafeDefaults() + { + var first = _environment.CreateSettings(); + + SubmitSettings(first, new Dictionary + { + ["historyRetentionDays"] = "90", + }); + + Assert.Equal(90, first.HistoryRetentionDays); + + var restarted = _environment.CreateSettings(); + Assert.Equal(90, restarted.HistoryRetentionDays); + + File.Delete(_environment.PathFor("settings.json")); + var defaults = _environment.CreateSettings(); + Assert.Equal(0, defaults.HistoryRetentionDays); + } + + [Fact] + public void InvalidRetentionPreferencesUseSafeDefaults() + { + File.WriteAllText(_environment.PathFor("settings.json"), JsonSerializer.Serialize( + new Dictionary + { + ["historyRetentionDays"] = "365", + })); + + var settings = _environment.CreateSettings(); + + Assert.Equal(0, settings.HistoryRetentionDays); + } + + [Fact] + public void AggregateRetentionIsOptInAndPausingDoesNotAppend() + { + var now = Now; + using var service = CreateService(() => now); + + service.RecordHistory(Snapshot("account-a", "default", 80, now), now); + var paused = service.GetAggregateHistory(); + Assert.Equal(0, paused.RetentionDays); + Assert.True(paused.Identified); + Assert.Empty(paused.Points); + + service.SetAggregateRetentionDays(30); + now = Now.AddMinutes(6); + service.RecordHistory(Snapshot("account-a", "default", 70, now), now); + var enabled = service.GetAggregateHistory(); + Assert.Equal(30, enabled.RetentionDays); + Assert.Equal(70, Assert.Single(enabled.Points).PrimaryRemainingPercent); + + service.SetAggregateRetentionDays(0); + now = Now.AddMinutes(12); + service.RecordHistory(Snapshot("account-a", "default", 60, now), now); + var pausedAgain = service.GetAggregateHistory(); + Assert.Equal(0, pausedAgain.RetentionDays); + var retained = Assert.Single(pausedAgain.Points); + Assert.Equal(70, retained.PrimaryRemainingPercent); + } + + [Fact] + public void AggregateHistoryIsSeparatedByAccountAndCategory() + { + var now = Now; + using var service = CreateService(() => now); + service.SetAggregateRetentionDays(30); + + service.RecordHistory(Snapshot("account-a", "default", 80, now), now); + Assert.Equal(80, Assert.Single(service.GetAggregateHistory().Points).PrimaryRemainingPercent); + + now = Now.AddMinutes(6); + service.RecordHistory(Snapshot("account-b", "default", 20, now), now); + Assert.Equal(20, Assert.Single(service.GetAggregateHistory().Points).PrimaryRemainingPercent); + + now = Now.AddMinutes(12); + service.RecordHistory(Snapshot("account-a", "review", 50, now), now); + Assert.Equal(50, Assert.Single(service.GetAggregateHistory().Points).PrimaryRemainingPercent); + + // Revisit the original scope with its original measurement. The store + // must reload account-a/default rather than exposing the review or b data. + service.RecordHistory(Snapshot("account-a", "default", 80, Now), Now); + var restored = service.GetAggregateHistory(); + Assert.Equal(80, Assert.Single(restored.Points).PrimaryRemainingPercent); + Assert.True(restored.Identified); + } + + [Fact] + public void ExplicitExportIsScopedAndContainsNoIdentifiers() + { + var now = Now; + using var service = CreateService(() => now); + service.SetAggregateRetentionDays(30); + + service.RecordHistory(Snapshot("account-a", "default", 80, now), now); + now = Now.AddMinutes(6); + service.RecordHistory(Snapshot("account-b", "default", 20, now), now); + + var result = service.ExportAggregateHistory(csv: false); + const string prefix = "Export saved to "; + Assert.StartsWith(prefix, result, StringComparison.Ordinal); + var exportPath = result[prefix.Length..]; + Assert.True(File.Exists(exportPath)); + + var content = File.ReadAllText(exportPath); + using var document = JsonDocument.Parse(content); + var observations = document.RootElement.GetProperty("observations"); + var observation = Assert.Single(observations.EnumerateArray()); + Assert.Equal(20, observation.GetProperty("primaryRemainingPercent").GetDouble()); + Assert.DoesNotContain("account-a", content, StringComparison.Ordinal); + Assert.DoesNotContain("account-b", content, StringComparison.Ordinal); + Assert.DoesNotContain("default", content, StringComparison.Ordinal); + Assert.DoesNotContain("accountKey", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("bucketId", content, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void ContextGuardsKeepTheCurrentAccountHistoryAndBlockStaleActions() + { + var now = Now; + using var service = CreateService(() => now); + service.SetAggregateRetentionDays(30); + + service.RecordHistory(Snapshot("account-a", "default", 80, now), now); + var accountA = service.GetAggregateHistory(); + Assert.NotNull(accountA.Context); + + now = Now.AddMinutes(6); + service.RecordHistory(Snapshot("account-b", "default", 20, now), now); + var accountB = service.GetAggregateHistory(); + Assert.NotEqual(accountA.Context, accountB.Context); + Assert.Equal(20, Assert.Single(accountB.Points).PrimaryRemainingPercent); + + Assert.False(service.ClearAggregateHistory(accountA.Context)); + var exportDirectory = Path.Combine( + Path.GetDirectoryName(_environment.PathFor("aggregates.json"))!, + "exports"); + Assert.False(Directory.Exists(exportDirectory)); + + var staleExport = service.ExportAggregateHistory(csv: false, expectedContext: accountA.Context); + Assert.Contains("changed", staleExport, StringComparison.OrdinalIgnoreCase); + Assert.False(Directory.Exists(exportDirectory)); + + var preserved = service.GetAggregateHistory(); + Assert.Equal(accountB.Context, preserved.Context); + Assert.Equal(20, Assert.Single(preserved.Points).PrimaryRemainingPercent); + } + + private CodexUsageService CreateService(Func clock) => _environment.CreateService( + _ => Task.FromResult(CodexUsageSnapshot.Loading), + () => CodexUsageSnapshot.Loading, + clock: clock); + + private static CodexUsageSnapshot Snapshot( + string account, + string category, + double remaining, + DateTimeOffset updatedAt) => new( + new RateLimitWindow(100 - remaining, 300, updatedAt.AddHours(4)), + new RateLimitWindow(100 - remaining, 10080, updatedAt.AddDays(6)), + "pro", + null, + null, + updatedAt, + UsageDataSource.AppServer, + null, + AccountKey: account, + DefaultBucketId: category); + + private static void SubmitSettings( + CodexUsageDockSettingsPage page, + IReadOnlyDictionary values) + { + var payload = new Dictionary + { + ["historyRetentionDays"] = "0", + }; + + foreach (var pair in values) + { + payload[pair.Key] = pair.Value; + } + + var form = page.GetContent().OfType().Last(); + form.SubmitForm(JsonSerializer.Serialize(payload), "{}"); + } +} diff --git a/CodexUsageDock.Tests/OptionalActionServiceTests.cs b/CodexUsageDock.Tests/OptionalActionServiceTests.cs new file mode 100644 index 0000000..97786d7 --- /dev/null +++ b/CodexUsageDock.Tests/OptionalActionServiceTests.cs @@ -0,0 +1,376 @@ +using System.Collections.Concurrent; +using System.Text.Json; +using Xunit; + +namespace CodexUsageDock.Tests; + +public sealed class OptionalActionServiceTests : IDisposable +{ + private const string AccountA = "synthetic-account-a"; + private const string AccountB = "synthetic-account-b"; + private static readonly DateTimeOffset Now = new(2026, 9, 9, 12, 0, 0, TimeSpan.Zero); + private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + private readonly TestEnvironment _environment = new(); + + public void Dispose() => _environment.Dispose(); + + private string JournalPath => _environment.PathFor("optional-reset.json"); + + [Fact] + public async Task AmbiguousResetSurvivesRestartAndRetriesTheSameKeyWithoutAnotherReportedCredit() + { + string? firstKey = null; + using (var first = CreateService(() => Quota(AccountA, 1), reset: (_, _, key, _) => + { + firstKey = key; + return Task.FromResult(new ResetCreditResult(ResetCreditOutcome.Ambiguous, Now)); + })) + { + await first.RefreshAsync().WaitAsync(Timeout); + await first.ConsumeEarnedResetAsync(AccountA).WaitAsync(Timeout); + Assert.NotNull(firstKey); + Assert.Equal(firstKey, ReadPendingKey(AccountA)); + } + + string? retriedKey = null; + using var restarted = CreateService(() => Quota(AccountA, 0), reset: (_, _, key, _) => + { + retriedKey = key; + return Task.FromResult(new ResetCreditResult(ResetCreditOutcome.AlreadyRedeemed, Now)); + }); + await restarted.RefreshAsync().WaitAsync(Timeout); + await restarted.ConsumeEarnedResetAsync(AccountA).WaitAsync(Timeout); + + Assert.Equal(firstKey, retriedKey); + Assert.Null(ReadPendingKey(AccountA)); + Assert.Contains("No second reset", restarted.ResetActionStatus, StringComparison.Ordinal); + } + + [Fact] + public async Task FailedRetryPreflightRetainsAnEarlierAmbiguousKey() + { + var keys = new List(); + var call = 0; + var quota = Quota(AccountA, 1); + using var service = CreateService(() => quota, reset: (_, _, key, _) => + { + keys.Add(key); + var outcome = ++call switch + { + 1 => ResetCreditOutcome.Ambiguous, + 2 => ResetCreditOutcome.Unavailable, + _ => ResetCreditOutcome.AlreadyRedeemed, + }; + return Task.FromResult(new ResetCreditResult(outcome, Now)); + }); + await service.RefreshAsync().WaitAsync(Timeout); + await service.ConsumeEarnedResetAsync(AccountA).WaitAsync(Timeout); + var original = ReadPendingKey(AccountA); + + quota = Quota(AccountA, null); + await service.RefreshAsync().WaitAsync(Timeout); + await service.ConsumeEarnedResetAsync(AccountA).WaitAsync(Timeout); + Assert.Equal(original, ReadPendingKey(AccountA)); + await service.ConsumeEarnedResetAsync(AccountA).WaitAsync(Timeout); + + Assert.Equal(3, keys.Count); + Assert.All(keys, key => Assert.Equal(original, key)); + Assert.Null(ReadPendingKey(AccountA)); + } + + [Fact] + public async Task ConcurrentResetRequestsShareOneCallAndOneSavedKey() + { + var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var result = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var calls = 0; + using var service = CreateService(() => Quota(AccountA, 2), reset: (_, _, _, _) => + { + Interlocked.Increment(ref calls); + started.TrySetResult(); + return result.Task; + }); + await service.RefreshAsync().WaitAsync(Timeout); + var first = service.ConsumeEarnedResetAsync(AccountA); + await started.Task.WaitAsync(Timeout); + var second = service.ConsumeEarnedResetAsync(AccountA); + var third = service.ConsumeEarnedResetAsync(AccountA); + Assert.Same(first, second); + Assert.Same(first, third); + Assert.NotNull(ReadPendingKey(AccountA)); + + result.SetResult(new(ResetCreditOutcome.Reset, Now)); + await Task.WhenAll(first, second, third).WaitAsync(Timeout); + Assert.Equal(1, calls); + Assert.Null(ReadPendingKey(AccountA)); + } + + [Theory] + [InlineData(null)] + [InlineData(0)] + public async Task UnknownOrZeroCreditsDoNotCreateANewResetAttempt(int? available) + { + var calls = 0; + using var service = CreateService(() => Quota(AccountA, available), reset: (_, _, _, _) => + { + calls++; + return Task.FromResult(new ResetCreditResult(ResetCreditOutcome.Reset, Now)); + }); + await service.RefreshAsync().WaitAsync(Timeout); + await service.ConsumeEarnedResetAsync(AccountA).WaitAsync(Timeout); + + Assert.Equal(0, calls); + Assert.Null(ReadPendingKey(AccountA)); + Assert.False(File.Exists(LocalStorage.ContextPath(JournalPath, AccountA))); + } + + [Theory] + [InlineData(null)] + [InlineData(0)] + public async Task PendingResetCanBeRetriedWhenNoCreditCountIsAvailable(int? available) + { + var original = Guid.Parse("12345678-abcd-4321-abcd-1234567890ab").ToString("N"); + Assert.True(new ResetAttemptJournal(JournalPath).Save(AccountA, original)); + string? sentKey = null; + using var service = CreateService(() => Quota(AccountA, available), reset: (_, _, key, _) => + { + sentKey = key; + return Task.FromResult(new ResetCreditResult(ResetCreditOutcome.AlreadyRedeemed, Now)); + }); + await service.RefreshAsync().WaitAsync(Timeout); + await service.ConsumeEarnedResetAsync(AccountA).WaitAsync(Timeout); + + Assert.Equal(original, sentKey); + Assert.Null(ReadPendingKey(AccountA)); + } + + [Fact] + public async Task ExistingOpaqueKeyKeepsItsExactCasingDuringRetry() + { + var original = Guid.Parse("abcdef12-abcd-4321-abcd-1234567890ab").ToString("N").ToUpperInvariant(); + Assert.True(new ResetAttemptJournal(JournalPath).Save(AccountA, original)); + string? sentKey = null; + using var service = CreateService(() => Quota(AccountA, 0), reset: (_, _, key, _) => + { + sentKey = key; + return Task.FromResult(new ResetCreditResult(ResetCreditOutcome.Ambiguous, Now)); + }); + await service.RefreshAsync().WaitAsync(Timeout); + await service.ConsumeEarnedResetAsync(AccountA).WaitAsync(Timeout); + + Assert.Equal(original, sentKey); + Assert.Equal(original, ReadPendingKey(AccountA)); + } + + [Fact] + public async Task PendingKeyIsDurablySavedBeforeTheConsumerIsCalled() + { + string? sentKey = null; + string? savedAtCall = null; + var recordReadableAtCall = false; + using var service = CreateService(() => Quota(AccountA, 1), reset: (_, account, key, _) => + { + sentKey = key; + recordReadableAtCall = new ResetAttemptJournal(JournalPath).TryRead(account, out savedAtCall); + return Task.FromResult(new ResetCreditResult(ResetCreditOutcome.Ambiguous, Now)); + }); + await service.RefreshAsync().WaitAsync(Timeout); + await service.ConsumeEarnedResetAsync(AccountA).WaitAsync(Timeout); + + Assert.True(recordReadableAtCall); + Assert.NotNull(sentKey); + Assert.Equal(sentKey, savedAtCall); + Assert.Equal(sentKey, ReadPendingKey(AccountA)); + } + + [Theory] + [InlineData("invalid-json")] + [InlineData("[]")] + [InlineData("{\"schemaVersion\":\"1\",\"pendingKey\":null}")] + [InlineData("{\"schemaVersion\":2,\"pendingKey\":null}")] + [InlineData("{\"schemaVersion\":1,\"pendingKey\":\"invalid-key\"}")] + public async Task InvalidJournalBlocksTheActionWithoutOverwritingRecoveryData(string contents) + { + var path = LocalStorage.ContextPath(JournalPath, AccountA); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, contents); + var calls = 0; + using var service = CreateService(() => Quota(AccountA, 1), reset: (_, _, _, _) => + { + calls++; + return Task.FromResult(new ResetCreditResult(ResetCreditOutcome.Reset, Now)); + }); + await service.RefreshAsync().WaitAsync(Timeout); + await service.ConsumeEarnedResetAsync(AccountA).WaitAsync(Timeout); + + Assert.Equal(0, calls); + Assert.Equal(contents, File.ReadAllText(path)); + Assert.Contains("No reset request was sent", service.ResetActionStatus, StringComparison.Ordinal); + } + + [Fact] + public async Task JournalWriteFailurePreventsTheConsumerFromRunning() + { + Directory.CreateDirectory(LocalStorage.ContextPath(JournalPath, AccountA)); + var calls = 0; + using var service = CreateService(() => Quota(AccountA, 1), reset: (_, _, _, _) => + { + calls++; + return Task.FromResult(new ResetCreditResult(ResetCreditOutcome.Reset, Now)); + }); + await service.RefreshAsync().WaitAsync(Timeout); + await service.ConsumeEarnedResetAsync(AccountA).WaitAsync(Timeout); + + Assert.Equal(0, calls); + Assert.Contains("could not be saved", service.ResetActionStatus, StringComparison.Ordinal); + } + + [Fact] + public async Task LateResetResultDoesNotReplaceTheNewAccountStatus() + { + var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var pending = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var quota = Quota(AccountA, 1); + using var service = CreateService(() => quota, reset: (_, _, _, _) => + { + started.TrySetResult(); + return pending.Task; + }); + await service.RefreshAsync().WaitAsync(Timeout); + var action = service.ConsumeEarnedResetAsync(AccountA); + await started.Task.WaitAsync(Timeout); + quota = Quota(AccountB, 1); + await service.RefreshAsync().WaitAsync(Timeout); + var newAccountStatus = service.ResetActionStatus; + pending.SetResult(new(ResetCreditOutcome.Reset, Now)); + await action.WaitAsync(Timeout); + + Assert.Equal(AccountB, service.Current.AccountKey); + Assert.Equal(newAccountStatus, service.ResetActionStatus); + Assert.Null(ReadPendingKey(AccountA)); + Assert.Null(ReadPendingKey(AccountB)); + } + + [Fact] + public async Task LateTaskResultIsDiscardedAfterAnAccountChange() + { + var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var pending = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var quota = Quota(AccountA, 1); + using var service = CreateService(() => quota, thread: (_, _, _, _) => + { + started.TrySetResult(); + return pending.Task; + }); + await service.RefreshAsync().WaitAsync(Timeout); + var action = service.ReadTaskUsageAsync("task-a"); + await started.Task.WaitAsync(Timeout); + quota = Quota(AccountB, 1); + await service.RefreshAsync().WaitAsync(Timeout); + var newAccountStatus = service.ThreadActionStatus; + pending.SetResult(TaskResult("task-a", AccountA)); + await action.WaitAsync(Timeout); + + Assert.Null(service.CurrentThreadUsage); + Assert.Equal(newAccountStatus, service.ThreadActionStatus); + } + + [Fact] + public async Task LatestRequestedTaskIsQueuedAndAnOlderTaskIsNeverPublishedAsItsResult() + { + var firstStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var secondStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var firstResult = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var secondResult = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var published = new ConcurrentQueue(); + var calls = new ConcurrentQueue(); + using var service = CreateService(() => Quota(AccountA, 1), thread: (_, id, _, _) => + { + calls.Enqueue(id); + if (id == "task-a") + { + firstStarted.TrySetResult(); + return firstResult.Task; + } + secondStarted.TrySetResult(); + return secondResult.Task; + }); + service.Updated += (_, _) => + { + if (service.CurrentThreadUsage?.ThreadId is { } id) published.Enqueue(id); + }; + await service.RefreshAsync().WaitAsync(Timeout); + var first = service.ReadTaskUsageAsync("task-a"); + await firstStarted.Task.WaitAsync(Timeout); + var second = service.ReadTaskUsageAsync("task-b"); + firstResult.SetResult(TaskResult("task-a", AccountA)); + await secondStarted.Task.WaitAsync(Timeout); + Assert.Null(service.CurrentThreadUsage); + Assert.DoesNotContain("task-a", published); + secondResult.SetResult(TaskResult("task-b", AccountA)); + await Task.WhenAll(first, second).WaitAsync(Timeout); + + Assert.Collection(calls, id => Assert.Equal("task-a", id), id => Assert.Equal("task-b", id)); + Assert.Equal("task-b", service.CurrentThreadUsage!.ThreadId); + Assert.DoesNotContain("task-a", published); + } + + [Theory] + [InlineData(null, "task-a")] + [InlineData(AccountB, "task-a")] + [InlineData(AccountA, "foreign-task")] + public async Task TaskResponsesWithoutMatchingAccountAndTaskAreNotUsed(string? responseAccount, string responseTask) + { + using var service = CreateService(() => Quota(AccountA, 1), thread: (_, _, _, _) => + Task.FromResult(TaskResult(responseTask, responseAccount))); + await service.RefreshAsync().WaitAsync(Timeout); + await service.ReadTaskUsageAsync("task-a").WaitAsync(Timeout); + + Assert.Null(service.CurrentThreadUsage); + Assert.DoesNotContain("estimate reported", service.ThreadActionStatus, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task StaleOrUnidentifiedUsageDoesNotAuthorizeResetOrTaskRequests() + { + var calls = 0; + var quota = Quota(null, 1); + using var service = CreateService(() => quota, + reset: (_, _, _, _) => { calls++; return Task.FromResult(new ResetCreditResult(ResetCreditOutcome.Reset, Now)); }, + thread: (_, id, account, _) => { calls++; return Task.FromResult(TaskResult(id, account)); }); + await service.RefreshAsync().WaitAsync(Timeout); + await service.ConsumeEarnedResetAsync(AccountA).WaitAsync(Timeout); + await service.ReadTaskUsageAsync("task-a").WaitAsync(Timeout); + quota = Quota(AccountA, 1) with { UpdatedAt = Now.AddHours(-1) }; + await service.RefreshAsync().WaitAsync(Timeout); + await service.ConsumeEarnedResetAsync(AccountA).WaitAsync(Timeout); + await service.ReadTaskUsageAsync("task-a").WaitAsync(Timeout); + + Assert.Equal(0, calls); + Assert.Null(service.CurrentThreadUsage); + Assert.Null(ReadPendingKey(AccountA)); + } + + private CodexUsageService CreateService(Func quota, + Func>? reset = null, + Func>? thread = null) + { + var service = _environment.CreateService(_ => Task.FromResult(quota()), () => quota(), clock: () => Now); + service.InitializeOptionalFeatures(_environment.PathFor("optional-aggregates.json"), JournalPath, reset, thread); + return service; + } + + private string? ReadPendingKey(string account) + { + Assert.True(new ResetAttemptJournal(JournalPath).TryRead(account, out var key)); + return key; + } + + private static CodexUsageSnapshot Quota(string? account, int? resets) => new( + null, new RateLimitWindow(20, 10080, Now.AddDays(3)), null, null, + resets is { } count ? new RateLimitResetCredits(count, null) : null, + Now, UsageDataSource.AppServer, null, AccountKey: account, DefaultBucketId: "codex"); + + private static ThreadUsageSnapshot TaskResult(string id, string? account) => + new(id, account, Now, ThreadUsageStatus.Available, EstimatedUsageCreditsMicros: 100, Groups: []); +} diff --git a/CodexUsageDock.Tests/ProviderDockTests.cs b/CodexUsageDock.Tests/ProviderDockTests.cs new file mode 100644 index 0000000..de41742 --- /dev/null +++ b/CodexUsageDock.Tests/ProviderDockTests.cs @@ -0,0 +1,382 @@ +using System.Text.Json; +using Microsoft.CommandPalette.Extensions; +using Microsoft.CommandPalette.Extensions.Toolkit; +using Xunit; + +namespace CodexUsageDock.Tests; + +public sealed class ProviderDockTests : IDisposable +{ + private readonly TestEnvironment _environment = new(); + public void Dispose() => _environment.Dispose(); + + [Fact] + public async Task TogglingAlertsOffAndOnWithoutARefreshEstablishesANewBaseline() + { + File.WriteAllText(_environment.PathFor("settings.json"), """{"enableUsageAlerts":"true"}"""); + var now = new DateTimeOffset(2026, 9, 9, 12, 0, 0, TimeSpan.Zero); + var reset = now.AddHours(4); + var remaining = 40.0; + CodexUsageSnapshot Snapshot() => new(new(100 - remaining, 300, reset), null, null, null, null, + now, UsageDataSource.AppServer, null, AccountKey: "a", DefaultBucketId: "codex"); + using var service = _environment.CreateService(_ => Task.FromResult(Snapshot()), Snapshot, clock: () => now); + var settings = _environment.CreateSettings(); + var messages = new List(); + using var provider = new CodexUsageDockCommandsProvider(service, settings, messages.Add, () => now); + await service.RefreshAsync(); + settings.GetContent().OfType().Last().SubmitForm("""{"enableUsageAlerts":"false"}""", "{}"); + settings.GetContent().OfType().Last().SubmitForm("""{"enableUsageAlerts":"true"}""", "{}"); + remaining = 5; + now = now.AddMinutes(1); + await service.RefreshAsync(); + Assert.Empty(messages); + remaining = 30; + now = now.AddMinutes(1); + await service.RefreshAsync(); + remaining = 8; + now = now.AddMinutes(1); + await service.RefreshAsync(); + Assert.Single(messages); + } + + [Fact] + public void SeparateDockBandsHaveStableRestorableIdentities() + { + File.WriteAllText(_environment.PathFor("settings.json"), """{"separateDockItems":"true"}"""); + using var service = _environment.CreateService(); + using var provider = new CodexUsageDockCommandsProvider(service, _environment.CreateSettings(), _ => { }); + var bands = provider.GetDockBands()!; + Assert.Equal(3, bands.Length); + Assert.Equal(3, bands.Select(item => item.Command.Id).Distinct(StringComparer.Ordinal).Count()); + foreach (var band in bands) + { + Assert.Single(Assert.IsAssignableFrom(band.Command).GetItems()); + Assert.Same(band, provider.GetCommandItem(band.Command.Id)); + } + Assert.Null(provider.GetCommandItem("unknown")); + Assert.Null(provider.GetCommandItem(string.Empty)); + 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/SourceAndActivityServiceTests.cs b/CodexUsageDock.Tests/SourceAndActivityServiceTests.cs new file mode 100644 index 0000000..636e2d6 --- /dev/null +++ b/CodexUsageDock.Tests/SourceAndActivityServiceTests.cs @@ -0,0 +1,121 @@ +using Xunit; + +namespace CodexUsageDock.Tests; + +public sealed class SourceAndActivityServiceTests : IDisposable +{ + private static readonly DateTimeOffset Now = new(2026, 9, 9, 12, 0, 0, TimeSpan.Zero); + private readonly TestEnvironment _environment = new(); + public void Dispose() => _environment.Dispose(); + + private static CodexUsageSnapshot Quota(string account) => new(null, new(20, 10080, Now.AddDays(3)), + null, null, null, Now, UsageDataSource.AppServer, null, AccountKey: account, DefaultBucketId: "codex"); + + [Fact] + public void SourcePathsAreExplicitAndErrorsDoNotExposeTheirValues() + { + var home = _environment.PathFor("profile"); + Directory.CreateDirectory(home); + var executable = _environment.PathFor("codex.exe"); + File.WriteAllText(executable, "synthetic fixture; never executed"); + Assert.True(CodexSourceOptions.TryCreate(executable, home, out var options, out var error)); + Assert.Null(error); + Assert.Equal(executable, options.ExecutablePath); + Assert.Equal(home, options.HomePath); + Assert.False(CodexSourceOptions.TryCreate("private-relative-path", null, out _, out error)); + Assert.DoesNotContain("private-relative-path", error!, StringComparison.Ordinal); + Assert.False(CodexSourceOptions.TryCreate(executable + " --argument", home, out _, out _)); + } + + [Fact] + public async Task InvalidSourceConfigurationFailsClosedWithoutReadingAnotherProfile() + { + var calls = 0; + using var service = _environment.CreateService(_ => { calls++; return Task.FromResult(Quota("a")); }, + () => { calls++; return Quota("b"); }, clock: () => Now); + service.ConfigureSource(CodexSourceOptions.Default, "Invalid source configuration."); + await service.RefreshAsync(); + Assert.Equal(0, calls); + Assert.Equal(UsageDataSource.Unavailable, service.Current.Source); + } + + [Fact] + public async Task SlowAccountActivityDoesNotBlockQuotasOrPublishForAnotherAccount() + { + var pending = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var snapshot = Quota("a"); + using var service = _environment.CreateService(_ => Task.FromResult(snapshot), () => snapshot, + clock: () => Now, accountUsageReader: _ => pending.Task); + await service.RefreshAsync(); + var activityTask = service.AccountUsageRefreshTask; + Assert.Equal("a", service.Current.AccountKey); + Assert.False(activityTask.IsCompleted); + snapshot = Quota("b"); + await service.RefreshAsync(); + pending.SetResult(new("a", Now, [new(DateOnly.FromDateTime(Now.Date), 123)], AccountUsageStatus.Available)); + await activityTask.WaitAsync(TimeSpan.FromSeconds(10)); + Assert.Equal(AccountUsageStatus.Unavailable, service.CurrentAccountUsage.Status); + Assert.Equal("b", service.Current.AccountKey); + } + + [Fact] + public async Task AccountUsageCanBeDisabledAndUnsupportedReadsAreThrottled() + { + var now = Now; + var calls = 0; + using var service = _environment.CreateService(_ => Task.FromResult(Quota("a")), () => Quota("a"), + clock: () => now, accountUsageReader: _ => + { + calls++; + return Task.FromResult(AccountUsageSnapshot.Unavailable with { Status = AccountUsageStatus.Unsupported }); + }); + service.SetAccountActivityEnabled(false); + await service.RefreshAsync(); + Assert.Equal(0, calls); + service.SetAccountActivityEnabled(true); + await service.RefreshAsync(); + await service.AccountUsageRefreshTask.WaitAsync(TimeSpan.FromSeconds(10)); + now = Now.AddMinutes(6); + await service.RefreshAsync(); + Assert.Equal(1, calls); + now = Now.AddMinutes(31); + await service.RefreshAsync(); + await service.AccountUsageRefreshTask.WaitAsync(TimeSpan.FromSeconds(10)); + Assert.Equal(2, calls); + } + + [Fact] + public async Task DisablingActivityAndSwitchingSourcePublishClearedStateImmediately() + { + using var service = _environment.CreateService(_ => Task.FromResult(Quota("a")), () => Quota("a"), + clock: () => Now, accountUsageReader: _ => Task.FromResult(new AccountUsageSnapshot("a", Now, [], AccountUsageStatus.Available))); + await service.RefreshAsync(); + await service.AccountUsageRefreshTask.WaitAsync(TimeSpan.FromSeconds(10)); + Assert.Equal(AccountUsageStatus.Available, service.CurrentAccountUsage.Status); + var updates = 0; + service.Updated += (_, _) => updates++; + service.SetAccountActivityEnabled(false); + Assert.Equal(1, updates); + Assert.Equal(AccountUsageStatus.Unavailable, service.CurrentAccountUsage.Status); + service.ConfigureSource(new(HomePath: _environment.PathFor("new-profile"))); + Assert.Equal(2, updates); + Assert.Equal(UsageDataSource.Initializing, service.Current.Source); + Assert.Empty(service.WeeklyHistory); + } + + [Fact] + public async Task SourceSwitchDiscardsTheOldInFlightQuotaResponse() + { + var pending = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var calls = 0; + using var service = _environment.CreateService(_ => ++calls == 1 ? pending.Task : Task.FromResult(Quota("b")), + () => Quota("fallback"), clock: () => Now); + var first = service.RefreshAsync(); + service.ConfigureSource(new(HomePath: _environment.PathFor("profile"))); + pending.SetResult(Quota("a")); + await first.WaitAsync(TimeSpan.FromSeconds(10)); + await service.RefreshAsync().WaitAsync(TimeSpan.FromSeconds(10)); + Assert.Equal("b", service.Current.AccountKey); + Assert.Equal(80, Assert.Single(service.WeeklyHistory).RemainingPercent); + } +} diff --git a/CodexUsageDock.Tests/TaskAndResetProtocolTests.cs b/CodexUsageDock.Tests/TaskAndResetProtocolTests.cs new file mode 100644 index 0000000..aa6c029 --- /dev/null +++ b/CodexUsageDock.Tests/TaskAndResetProtocolTests.cs @@ -0,0 +1,331 @@ +using System.Text.Json; +using Xunit; + +namespace CodexUsageDock.Tests; + +public sealed class TaskAndResetProtocolTests +{ + private static readonly DateTimeOffset Now = new(2026, 9, 9, 12, 0, 0, TimeSpan.Zero); + private static readonly string AccountKey = AccountScope("synthetic-account"); + private const string TaskId = "synthetic-thread-123"; + private const string ResetKey = "3d2054c5-d593-401d-84e4-bd8f733341cf"; + private const string AccountResponse = """{"result":{"accountId":"synthetic-account"}}"""; + private const string TaskResponse = """ + {"result":{"threadUsage":{"threadId":"synthetic-thread-123","estimatedUsageCreditsMicros":123456,"estimatedUsageUsdMicros":null,"groups":[]}}} + """; + + [Fact] + public void TaskUsagePreservesEstimatesAndNullableTokenClasses() + { + var snapshot = ParseThread(""" + { + "threadUsage": { + "threadId": "synthetic-thread-123", + "estimatedUsageCreditsMicros": 1234567, + "estimatedUsageUsdMicros": 12000, + "groups": [{ + "model": "synthetic-model", "reasoningEffort": "high", "speed": "fast", + "estimatedUsageCreditsMicros": 1234567, + "netNewInputTokens": 100, "cachedInputTokens": null, + "inputTokens": 150, "outputTokens": 20, "totalTokens": 170 + }] + } + } + """); + + Assert.Equal(ThreadUsageStatus.Available, snapshot.Status); + Assert.Equal(TaskId, snapshot.ThreadId); + Assert.Equal(AccountKey, snapshot.AccountKey); + Assert.Equal(1234567, snapshot.EstimatedUsageCreditsMicros); + Assert.Equal(12000, snapshot.EstimatedUsageUsdMicros); + var group = Assert.Single(snapshot.Groups!); + Assert.Equal("synthetic-model", group.Model); + Assert.Equal("high", group.ReasoningEffort); + Assert.Equal("fast", group.Speed); + Assert.Equal(100, group.NetNewInputTokens); + Assert.Null(group.CachedInputTokens); + Assert.Equal(150, group.InputTokens); + Assert.Equal(20, group.OutputTokens); + Assert.Equal(170, group.TotalTokens); + } + + [Fact] + public void InvalidTaskValuesAreUnknownAndLabelsAreSanitized() + { + var snapshot = ParseThread(""" + {"threadUsage": { + "threadId":"synthetic-thread-123", "estimatedUsageCreditsMicros":-1, "estimatedUsageUsdMicros":9223372036854775808, + "groups":[null,{}, {"model":" Model\n one ","reasoningEffort":[],"speed":"fast\tmode", + "estimatedUsageCreditsMicros":"100","netNewInputTokens":-2,"inputTokens":0,"outputTokens":null}] + }} + """); + + Assert.Equal(ThreadUsageStatus.Partial, snapshot.Status); + Assert.Null(snapshot.EstimatedUsageCreditsMicros); + Assert.Null(snapshot.EstimatedUsageUsdMicros); + var group = Assert.Single(snapshot.Groups!); + Assert.Equal("Model one", group.Model); + Assert.Null(group.ReasoningEffort); + Assert.Equal("fast mode", group.Speed); + Assert.Null(group.EstimatedUsageCreditsMicros); + Assert.Null(group.NetNewInputTokens); + Assert.Equal(0, group.InputTokens); + Assert.Null(group.TotalTokens); + } + + [Fact] + public void TaskGroupsAndLabelsAreBounded() + { + var snapshot = ParseThread(JsonSerializer.Serialize(new + { + threadUsage = new + { + threadId = TaskId, + estimatedUsageCreditsMicros = 0, + groups = Enumerable.Range(0, 70).Select(index => new + { + model = new string('m', 100) + index, + reasoningEffort = new string('e', 50), + speed = new string('s', 50), + totalTokens = index, + }), + }, + })); + + Assert.Equal(ThreadUsageStatus.Partial, snapshot.Status); + Assert.Equal(64, snapshot.Groups!.Count); + Assert.All(snapshot.Groups, group => + { + Assert.Equal(80, group.Model!.Length); + Assert.Equal(32, group.ReasoningEffort!.Length); + Assert.Equal(32, group.Speed!.Length); + }); + } + + [Theory] + [InlineData("{}")] + [InlineData("{\"threadUsage\":null}")] + [InlineData("{\"threadUsage\":{\"threadId\":\"foreign-thread\",\"estimatedUsageCreditsMicros\":100,\"groups\":[]}}")] + [InlineData("{\"threadUsage\":{\"threadId\":\"synthetic-thread-123\",\"estimatedUsageCreditsMicros\":null,\"groups\":[]}}")] + public void MissingOrForeignTaskUsageDoesNotProduceAnEstimate(string json) + { + var snapshot = ParseThread(json); + Assert.Equal(ThreadUsageStatus.Unavailable, snapshot.Status); + Assert.Null(snapshot.EstimatedUsageCreditsMicros); + Assert.Null(snapshot.Groups); + } + + [Fact] + public async Task TaskReadSendsTheSelectedIdBetweenMatchingAccountChecks() + { + var calls = new List(); + var result = await CodexAppServerReader.ReadThreadUsageSequenceAsync((method, id, parameters, _) => + { + calls.Add(CodexAppServerReader.CreateRequestJson(method, id, parameters)); + return Task.FromResult(JsonDocument.Parse(method == "account/usage/read" ? TaskResponse : AccountResponse)); + }, TaskId, AccountKey); + + Assert.Equal(3, calls.Count); + using var before = JsonDocument.Parse(calls[0]); + using var usage = JsonDocument.Parse(calls[1]); + using var after = JsonDocument.Parse(calls[2]); + Assert.Equal("account/rateLimits/read", before.RootElement.GetProperty("method").GetString()); + Assert.Equal("account/usage/read", usage.RootElement.GetProperty("method").GetString()); + Assert.Equal(TaskId, usage.RootElement.GetProperty("params").GetProperty("threadId").GetString()); + Assert.Equal("account/rateLimits/read", after.RootElement.GetProperty("method").GetString()); + Assert.Equal(ThreadUsageStatus.Available, result.Status); + Assert.Equal(123456, result.EstimatedUsageCreditsMicros); + } + + [Fact] + public async Task TaskReadRejectsAnAccountChangeBeforeOrAfterTheUsageRequest() + { + var beforeCalls = 0; + var beforeMismatch = await CodexAppServerReader.ReadThreadUsageSequenceAsync((_, _, _, _) => + { + beforeCalls++; + return Task.FromResult(JsonDocument.Parse(AccountResponse)); + }, TaskId, AccountScope("other-account")); + Assert.Equal(1, beforeCalls); + Assert.Equal(ThreadUsageStatus.AccountMismatch, beforeMismatch.Status); + + var afterMismatch = await CodexAppServerReader.ReadThreadUsageSequenceAsync((_, id, _, _) => + Task.FromResult(JsonDocument.Parse(id switch + { + 2 => AccountResponse, + 3 => TaskResponse, + _ => """{"result":{"accountId":"other-account"}}""", + })), TaskId, AccountKey); + Assert.Equal(ThreadUsageStatus.AccountMismatch, afterMismatch.Status); + Assert.Null(afterMismatch.EstimatedUsageCreditsMicros); + Assert.Null(afterMismatch.AccountKey); + } + + [Fact] + public async Task UnsupportedTaskMethodRemainsDistinctFromUnavailableUsage() + { + var result = await CodexAppServerReader.ReadThreadUsageSequenceAsync((_, id, _, _) => + Task.FromResult(JsonDocument.Parse(id == 2 ? AccountResponse + : """{"error":{"code":-32601,"message":"private error data"}}""")), TaskId, AccountKey); + Assert.Equal(ThreadUsageStatus.Unsupported, result.Status); + Assert.DoesNotContain("private", JsonSerializer.Serialize(result), StringComparison.Ordinal); + } + + [Theory] + [InlineData("")] + [InlineData("thread\nrequest")] + [InlineData("thread with spaces")] + public async Task InvalidTaskIdsDoNotSendRequests(string id) + { + var result = await CodexAppServerReader.ReadThreadUsageSequenceAsync((_, _, _, _) => + throw new InvalidOperationException("Must not send"), id, AccountKey); + Assert.Equal(ThreadUsageStatus.Unavailable, result.Status); + } + + [Theory] + [InlineData("reset", (int)ResetCreditOutcome.Reset)] + [InlineData("alreadyRedeemed", (int)ResetCreditOutcome.AlreadyRedeemed)] + [InlineData("nothingToReset", (int)ResetCreditOutcome.NothingToReset)] + [InlineData("noCredit", (int)ResetCreditOutcome.NoCredit)] + [InlineData("unknown-outcome", (int)ResetCreditOutcome.Ambiguous)] + public void ResetParserPreservesTerminalServerOutcomes(string value, int expected) + { + using var document = JsonDocument.Parse(JsonSerializer.Serialize(new { result = new { outcome = value } })); + var result = ResetCreditParser.Parse(document.RootElement, Now); + Assert.Equal((ResetCreditOutcome)expected, result.Outcome); + Assert.Equal(Now, result.AttemptedAt); + } + + [Theory] + [InlineData("null")] + [InlineData("{}")] + [InlineData("{\"result\":{\"outcome\":null}}")] + [InlineData("{\"error\":{\"code\":-32603,\"message\":\"private details\"}}")] + [InlineData("{\"error\":{\"code\":-32601},\"result\":{\"outcome\":\"reset\"}}")] + public void UncertainResetRepliesRemainAmbiguous(string json) + { + using var document = JsonDocument.Parse(json); + var result = ResetCreditParser.Parse(document.RootElement, Now); + Assert.Equal(ResetCreditOutcome.Ambiguous, result.Outcome); + Assert.DoesNotContain("private", JsonSerializer.Serialize(result), StringComparison.Ordinal); + } + + [Fact] + public async Task ResetChecksTheExpectedAccountBeforeSendingTheCallerKey() + { + var requests = new List(); + var result = await CodexAppServerReader.ConsumeResetCreditSequenceAsync((method, id, parameters, _) => + { + requests.Add(CodexAppServerReader.CreateRequestJson(method, id, parameters)); + return Task.FromResult(JsonDocument.Parse(id == 2 ? AccountResponse : """{"result":{"outcome":"reset"}}""")); + }, AccountKey, ResetKey); + + Assert.Equal(2, requests.Count); + using var before = JsonDocument.Parse(requests[0]); + using var consume = JsonDocument.Parse(requests[1]); + Assert.Equal("account/rateLimits/read", before.RootElement.GetProperty("method").GetString()); + Assert.Equal("account/rateLimitResetCredit/consume", consume.RootElement.GetProperty("method").GetString()); + Assert.Equal(ResetKey, consume.RootElement.GetProperty("params").GetProperty("idempotencyKey").GetString()); + Assert.False(consume.RootElement.GetProperty("params").TryGetProperty("creditId", out _)); + Assert.Equal(ResetCreditOutcome.Reset, result.Outcome); + } + + [Fact] + public async Task ResetAccountMismatchPreventsTheMutation() + { + var calls = 0; + var result = await CodexAppServerReader.ConsumeResetCreditSequenceAsync((_, _, _, _) => + { + calls++; + return Task.FromResult(JsonDocument.Parse(AccountResponse)); + }, AccountScope("other-account"), ResetKey); + Assert.Equal(1, calls); + Assert.Equal(ResetCreditOutcome.AccountMismatch, result.Outcome); + + var unverified = await CodexAppServerReader.ConsumeResetCreditSequenceAsync((_, _, _, _) => + throw new InvalidOperationException("Must not send"), "unverified", ResetKey); + Assert.Equal(ResetCreditOutcome.AccountMismatch, unverified.Outcome); + } + + [Fact] + public async Task FailedPreflightIsSafeButFailureAfterConsumeRemainsAmbiguousAndKeepsTheKey() + { + var unavailable = await CodexAppServerReader.ConsumeResetCreditSequenceAsync((_, _, _, _) => + Task.FromException(new IOException("before consume")), AccountKey, ResetKey); + Assert.Equal(ResetCreditOutcome.Unavailable, unavailable.Outcome); + + var keys = new List(); + var failed = await Attempt(throwAfterSend: true); + Assert.Equal(ResetCreditOutcome.Ambiguous, failed.Outcome); + Assert.Single(keys); + var retried = await Attempt(throwAfterSend: false); + Assert.Equal(ResetCreditOutcome.AlreadyRedeemed, retried.Outcome); + Assert.Equal(new[] { ResetKey, ResetKey }, keys); + + Task Attempt(bool throwAfterSend) => + CodexAppServerReader.ConsumeResetCreditSequenceAsync((method, id, parameters, _) => + { + if (id == 2) return Task.FromResult(JsonDocument.Parse(AccountResponse)); + using var request = JsonDocument.Parse(CodexAppServerReader.CreateRequestJson(method, id, parameters)); + keys.Add(request.RootElement.GetProperty("params").GetProperty("idempotencyKey").GetString()!); + return throwAfterSend + ? Task.FromException(new IOException("after possible send")) + : Task.FromResult(JsonDocument.Parse("""{"result":{"outcome":"alreadyRedeemed"}}""")); + }, AccountKey, ResetKey); + } + + [Fact] + public async Task CancellationAfterConsumeBeginsIsAmbiguous() + { + using var cancellation = new CancellationTokenSource(); + var result = await CodexAppServerReader.ConsumeResetCreditSequenceAsync((_, id, _, _) => + { + if (id == 2) return Task.FromResult(JsonDocument.Parse(AccountResponse)); + cancellation.Cancel(); + return Task.FromException(new OperationCanceledException(cancellation.Token)); + }, AccountKey, ResetKey, cancellation.Token); + Assert.Equal(ResetCreditOutcome.Ambiguous, result.Outcome); + } + + [Fact] + public async Task UnsupportedResetAndCancellationBeforeConsumeDoNotClaimAmbiguousConsumption() + { + var unsupported = await CodexAppServerReader.ConsumeResetCreditSequenceAsync((_, id, _, _) => + Task.FromResult(JsonDocument.Parse(id == 2 ? AccountResponse : """{"error":{"code":-32601}}""")), AccountKey, ResetKey); + Assert.Equal(ResetCreditOutcome.Unsupported, unsupported.Outcome); + + using var cancellation = new CancellationTokenSource(); + var calls = 0; + var canceled = await CodexAppServerReader.ConsumeResetCreditSequenceAsync((_, _, _, _) => + { + calls++; + cancellation.Cancel(); + return Task.FromResult(JsonDocument.Parse(AccountResponse)); + }, AccountKey, ResetKey, cancellation.Token); + Assert.Equal(1, calls); + Assert.Equal(ResetCreditOutcome.Unavailable, canceled.Outcome); + } + + [Theory] + [InlineData("")] + [InlineData("key\nwith-control")] + [InlineData("key with space")] + public async Task InvalidIdempotencyKeysFailBeforeAnyRequest(string key) + { + await Assert.ThrowsAsync(() => + CodexAppServerReader.ConsumeResetCreditSequenceAsync((_, _, _, _) => + throw new InvalidOperationException("Must not send"), AccountKey, key)); + } + + private static ThreadUsageSnapshot ParseThread(string json) + { + using var document = JsonDocument.Parse(json); + return ThreadUsageParser.Parse(document.RootElement, TaskId, AccountKey, Now); + } + + private static string AccountScope(string accountId) + { + using var result = JsonDocument.Parse(JsonSerializer.Serialize(new { rateLimits = new { }, accountId })); + return CodexAppServerReader.ParseSnapshot(result.RootElement, default, Now).AccountKey!; + } +} diff --git a/CodexUsageDock.Tests/TestEnvironment.cs b/CodexUsageDock.Tests/TestEnvironment.cs index 5ab4830..9057230 100644 --- a/CodexUsageDock.Tests/TestEnvironment.cs +++ b/CodexUsageDock.Tests/TestEnvironment.cs @@ -21,11 +21,16 @@ internal CodexUsageService CreateService( WeeklyUsageHistoryStore? weeklyHistoryStore = null, AdaptiveWeeklyUsageStore? adaptiveWeeklyUsageStore = null, Func>? localTokenUsageReader = null, - Func? clock = null) => - new(appServerReader, localSessionReader, + Func? clock = null, + Func>? accountUsageReader = null) + { + var service = new CodexUsageService(appServerReader, localSessionReader, weeklyHistoryStore ?? new WeeklyUsageHistoryStore(PathFor("weekly.json")), adaptiveWeeklyUsageStore ?? new AdaptiveWeeklyUsageStore(PathFor("adaptive.json")), - localTokenUsageReader, clock); + localTokenUsageReader, clock, accountUsageReader); + service.InitializeOptionalFeatures(PathFor("aggregates.json"), PathFor("reset-attempt.json")); + return service; + } internal CodexUsageService CreateService( Func> appServerReader, @@ -33,8 +38,9 @@ internal CodexUsageService CreateService( WeeklyUsageHistoryStore? weeklyHistoryStore = null, AdaptiveWeeklyUsageStore? adaptiveWeeklyUsageStore = null, Func>? localTokenUsageReader = null, - Func? clock = null) => - CreateService(appServerReader, _ => localSessionReader(), weeklyHistoryStore, adaptiveWeeklyUsageStore, localTokenUsageReader, clock); + Func? clock = null, + Func>? accountUsageReader = null) => + CreateService(appServerReader, _ => localSessionReader(), weeklyHistoryStore, adaptiveWeeklyUsageStore, localTokenUsageReader, clock, accountUsageReader); public void Dispose() { diff --git a/CodexUsageDock.Tests/UsageAggregateStoreTests.cs b/CodexUsageDock.Tests/UsageAggregateStoreTests.cs new file mode 100644 index 0000000..68145bf --- /dev/null +++ b/CodexUsageDock.Tests/UsageAggregateStoreTests.cs @@ -0,0 +1,258 @@ +using System.Text.Json; +using Xunit; + +namespace CodexUsageDock.Tests; + +public sealed class UsageAggregateStoreTests : IDisposable +{ + private static readonly DateTimeOffset Now = new(2026, 9, 9, 12, 0, 0, TimeSpan.Zero); + private readonly TestEnvironment _environment = new(); + + public void Dispose() => _environment.Dispose(); + + [Fact] + public void RetentionCanBeChangedAndIsAppliedToReloadedData() + { + var path = _environment.PathFor("usage-aggregates.json"); + var store = new UsageAggregateStore(path, 30, () => Now); + + Assert.True(store.Record(Point(Now.AddDays(-20)), Now, out var firstError), firstError); + Assert.True(store.Record(Point(Now.AddDays(-6)), Now, out var secondError), secondError); + Assert.Equal(2, store.Snapshot.Count); + + Assert.True(store.SetRetentionDays(7, Now, out var retentionError), retentionError); + Assert.Single(store.Snapshot); + Assert.Equal(Now.AddDays(-6), store.Snapshot[0].RecordedAt); + + var reloaded = new UsageAggregateStore(path, 7, () => Now); + Assert.Equal(7, reloaded.RetentionDays); + Assert.Single(reloaded.Snapshot); + Assert.Equal(Now.AddDays(-6), reloaded.Snapshot[0].RecordedAt); + } + + [Fact] + public void SameBucketAndResetReplacesTheLatestPoint() + { + var path = _environment.PathFor("usage-aggregates.json"); + var store = new UsageAggregateStore(path, 30, () => Now); + var reset = Now.AddDays(1); + + Assert.True(store.Record(Point(Now.AddMinutes(1), 80, reset), Now.AddMinutes(1))); + Assert.True(store.Record(Point(Now.AddMinutes(4), 70, reset), Now.AddMinutes(4))); + + var replaced = Assert.Single(store.Snapshot); + Assert.Equal(70, replaced.PrimaryRemainingPercent); + Assert.Equal(Now.AddMinutes(4), replaced.RecordedAt); + } + + [Fact] + public void AResetChangeWithinTheSameBucketIsPreserved() + { + var path = _environment.PathFor("usage-aggregates.json"); + var store = new UsageAggregateStore(path, 30, () => Now); + + Assert.True(store.Record(Point(Now.AddMinutes(1), 80, Now.AddDays(1)), Now.AddMinutes(1))); + Assert.True(store.Record(Point(Now.AddMinutes(4), 70, Now.AddDays(2)), Now.AddMinutes(4))); + + Assert.Equal(2, store.Snapshot.Count); + Assert.Equal( + [80d, 70d], + store.Snapshot.Select(observation => observation.PrimaryRemainingPercent!.Value).ToArray()); + } + + [Fact] + public void LiveFactoryRequiresKnownFreshAppServerData() + { + var reset = Now.AddHours(4); + var snapshot = new CodexUsageSnapshot( + new RateLimitWindow(20, 300, reset), + null, + "pro", + null, + null, + Now.AddMinutes(-1), + UsageDataSource.AppServer, + null, + AccountKey: "already-hashed-account-key", + DefaultBucketId: "default"); + + Assert.True(UsageAggregateStore.TryCreateLivePoint(snapshot, Now, TimeSpan.FromMinutes(1), out var point)); + Assert.NotNull(point); + Assert.Equal(UsageDataSource.AppServer, point!.Source); + Assert.Equal(80, point.PrimaryRemainingPercent); + Assert.Equal(reset, point.PrimaryResetsAt); + Assert.DoesNotContain("already-hashed-account-key", JsonSerializer.Serialize(point), StringComparison.Ordinal); + + Assert.False(UsageAggregateStore.TryCreateLivePoint( + snapshot with { AccountKey = null }, Now, TimeSpan.FromMinutes(1), out _)); + Assert.False(UsageAggregateStore.TryCreateLivePoint( + snapshot with { Source = UsageDataSource.LocalSession }, Now, TimeSpan.FromMinutes(1), out _)); + Assert.False(UsageAggregateStore.TryCreateLivePoint( + snapshot with { UpdatedAt = Now.AddMinutes(-6) }, Now, TimeSpan.FromMinutes(1), out _)); + Assert.False(UsageAggregateStore.TryCreateLivePoint( + snapshot with { UpdatedAt = Now.AddMinutes(1) }, Now, TimeSpan.FromMinutes(1), out _)); + } + + [Fact] + public void InvalidDirectObservationIsRejectedWithGenericError() + { + var store = new UsageAggregateStore(_environment.PathFor("usage-aggregates.json"), 30, () => Now); + var invalid = new UsageAggregatePoint( + Now, + double.NaN, + null, + Now.AddHours(1), + null, + UsageDataSource.AppServer); + + Assert.False(store.Record(invalid, Now, out var error)); + Assert.Equal("The usage observation was invalid and was not saved.", error); + Assert.Empty(store.Snapshot); + } + + [Fact] + public void MalformedNullAndOversizedDocumentsAreBoundedSafely() + { + var path = _environment.PathFor("usage-aggregates.json"); + File.WriteAllText(path, "null"); + + var malformed = new UsageAggregateStore(path, 30, () => Now); + Assert.Empty(malformed.Snapshot); + Assert.Contains("could not be read", malformed.StorageError, StringComparison.Ordinal); + + var points = Enumerable.Range(0, UsageAggregateStore.MaximumEntries + 5) + .Select(index => Point( + Now.AddMinutes(-index * 2), + 20 + index % 70, + Now.AddMinutes(-index * 2).AddDays(1))) + .ToArray(); + var document = new UsageAggregateStoreDocument(UsageAggregateStore.SchemaVersion, 90, points); + File.WriteAllText(path, JsonSerializer.Serialize(document)); + + var capped = new UsageAggregateStore(path, 90, () => Now); + Assert.Equal(UsageAggregateStore.MaximumEntries, capped.Snapshot.Count); + Assert.Equal(Now, capped.Snapshot[^1].RecordedAt); + Assert.Equal(Now.AddMinutes(-2 * (UsageAggregateStore.MaximumEntries - 1)), capped.Snapshot[0].RecordedAt); + } + + [Fact] + public void InvalidEntriesAndNullItemsAreIgnoredDuringReload() + { + var path = _environment.PathFor("usage-aggregates.json"); + var invalidDocument = new + { + SchemaVersion = UsageAggregateStore.SchemaVersion, + RetentionDays = 30, + Observations = new object?[] + { + null, + new + { + RecordedAt = Now, + PrimaryRemainingPercent = 101d, + WeeklyRemainingPercent = (double?)null, + PrimaryResetsAt = Now.AddHours(1), + WeeklyResetsAt = (DateTimeOffset?)null, + Source = UsageDataSource.AppServer, + }, + new + { + RecordedAt = Now.AddMinutes(1), + PrimaryRemainingPercent = 20d, + WeeklyRemainingPercent = (double?)null, + PrimaryResetsAt = Now.AddHours(1), + WeeklyResetsAt = (DateTimeOffset?)null, + Source = UsageDataSource.LocalSession, + }, + }, + }; + File.WriteAllText(path, JsonSerializer.Serialize(invalidDocument)); + + var store = new UsageAggregateStore(path, 30, () => Now); + + Assert.Empty(store.Snapshot); + } + + [Fact] + public void ExportsAreDeterministicInvariantAndPrivacyBounded() + { + var path = _environment.PathFor("usage-aggregates.json"); + var store = new UsageAggregateStore(path, 30, () => Now); + Assert.True(store.Record( + Point(Now.AddMinutes(-1), 87.5, Now.AddHours(4), weeklyRemaining: 12.25, weeklyReset: Now.AddDays(6)), + Now)); + + var json = store.ExportJson(Now); + var repeatedJson = store.ExportJson(Now); + var csv = store.ExportCsv(Now); + + Assert.Equal(json, repeatedJson); + using var parsed = JsonDocument.Parse(json); + Assert.Equal(UsageAggregateStore.SchemaVersion, parsed.RootElement.GetProperty("schemaVersion").GetInt32()); + Assert.Equal("UTC ISO 8601", parsed.RootElement.GetProperty("units").GetProperty("timestamps").GetString()); + Assert.Contains("percent (0-100)", json, StringComparison.Ordinal); + Assert.Contains("87.5", json, StringComparison.Ordinal); + Assert.Contains("12.25", json, StringComparison.Ordinal); + Assert.Contains("2026-09-09T11:59:00.0000000Z", json, StringComparison.Ordinal); + Assert.Contains("schemaVersion=1", csv, StringComparison.Ordinal); + Assert.Contains("recordedAtUtc,primaryRemainingPercent,weeklyRemainingPercent", csv, StringComparison.Ordinal); + Assert.Contains("87.5", csv, StringComparison.Ordinal); + Assert.DoesNotContain("87,5", csv, StringComparison.Ordinal); + Assert.DoesNotContain("\"tokens\"", json, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("\"cost\"", json, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("\"account\"", json, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("\"session\"", json, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void ContextStoresAreIsolatedAndDoNotPersistContextText() + { + var path = _environment.PathFor("usage-aggregates.json"); + var baseStore = new UsageAggregateStore(path, 30, () => Now); + var accountStore = baseStore.ForContext("account-id|default-category"); + + Assert.True(accountStore.Record(Point(Now.AddMinutes(-1)), Now)); + Assert.Single(accountStore.Snapshot); + Assert.Empty(baseStore.Snapshot); + + foreach (var file in Directory.EnumerateFiles( + Path.GetDirectoryName(path)!, + "*", + SearchOption.AllDirectories)) + { + Assert.DoesNotContain("account-id", file, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("default-category", file, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("account-id", File.ReadAllText(file), StringComparison.Ordinal); + Assert.DoesNotContain("default-category", File.ReadAllText(file), StringComparison.Ordinal); + } + } + + [Fact] + public void ClearOnlyRemovesTheCurrentStore() + { + var path = _environment.PathFor("usage-aggregates.json"); + var baseStore = new UsageAggregateStore(path, 30, () => Now); + var contextStore = baseStore.ForContext("known-account|default"); + + Assert.True(baseStore.Record(Point(Now.AddMinutes(-2)), Now)); + Assert.True(contextStore.Record(Point(Now.AddMinutes(-1)), Now)); + Assert.True(contextStore.Clear(out var error), error); + + Assert.Single(baseStore.Snapshot); + Assert.Empty(contextStore.Snapshot); + Assert.Single(new UsageAggregateStore(path, 30, () => Now).Snapshot); + } + + private static UsageAggregatePoint Point( + DateTimeOffset recordedAt, + double primaryRemaining = 80, + DateTimeOffset? primaryReset = null, + double? weeklyRemaining = null, + DateTimeOffset? weeklyReset = null) => new( + recordedAt, + primaryRemaining, + weeklyRemaining, + primaryReset ?? recordedAt.AddHours(1), + weeklyReset, + UsageDataSource.AppServer); +} diff --git a/CodexUsageDock.Tests/UsageAlertTests.cs b/CodexUsageDock.Tests/UsageAlertTests.cs new file mode 100644 index 0000000..75443f7 --- /dev/null +++ b/CodexUsageDock.Tests/UsageAlertTests.cs @@ -0,0 +1,368 @@ +using Xunit; + +namespace CodexUsageDock.Tests; + +public sealed class UsageAlertTests +{ + private static readonly DateTimeOffset Now = new(2026, 9, 9, 12, 0, 0, TimeSpan.Zero); + private static readonly TimeSpan RefreshInterval = TimeSpan.FromMinutes(1); + private static readonly UsageAlertOptions EnabledOptions = new(true); + + [Fact] + public void EnablingUsesTheFirstFreshMeasurementAsBaselineThenAlertsOnCrossing() + { + var evaluator = new UsageAlertEvaluator(); + + Assert.Empty(Evaluate(evaluator, Presentation(primaryRemaining: 50))); + + var crossing = Evaluate(evaluator, Presentation(primaryRemaining: 9)); + var alert = Assert.Single(crossing); + Assert.StartsWith("low:", alert.Key, StringComparison.Ordinal); + Assert.Contains("5-hour window", alert.Message, StringComparison.Ordinal); + Assert.Empty(Evaluate(evaluator, Presentation(primaryRemaining: 9))); + } + + [Fact] + public void LowAlertRearmsOnlyAfterARecoveryAboveThresholdPlusFive() + { + var evaluator = new UsageAlertEvaluator(); + + Assert.Empty(Evaluate(evaluator, Presentation(primaryRemaining: 50))); + Assert.Single(Evaluate(evaluator, Presentation(primaryRemaining: 9))); + Assert.Empty(Evaluate(evaluator, Presentation(primaryRemaining: 12))); + Assert.Empty(Evaluate(evaluator, Presentation(primaryRemaining: 15))); + Assert.Empty(Evaluate(evaluator, Presentation(primaryRemaining: 16))); + Assert.Single(Evaluate(evaluator, Presentation(primaryRemaining: 9))); + } + + [Fact] + public void ResetTimestampJitterWithinOneMinuteStaysInTheSameCycle() + { + var evaluator = new UsageAlertEvaluator(); + var reset = Now.AddHours(4); + + Assert.Empty(Evaluate(evaluator, Presentation(primaryRemaining: 50, primaryReset: reset))); + Assert.Single(Evaluate(evaluator, Presentation( + primaryRemaining: 9, + primaryReset: reset.AddSeconds(5)))); + Assert.Empty(Evaluate(evaluator, Presentation( + primaryRemaining: 9, + primaryReset: reset.AddSeconds(10)))); + } + + [Fact] + public void NewCycleAndAccountSwitchStartCleanBaselines() + { + var evaluator = new UsageAlertEvaluator(); + var firstReset = Now.AddHours(4); + var nextReset = firstReset.AddMinutes(2); + + Assert.Empty(Evaluate(evaluator, Presentation(primaryRemaining: 50, primaryReset: firstReset))); + Assert.Single(Evaluate(evaluator, Presentation(primaryRemaining: 9, primaryReset: firstReset))); + Assert.Empty(Evaluate(evaluator, Presentation(primaryRemaining: 9, primaryReset: nextReset))); + Assert.Empty(Evaluate(evaluator, Presentation(primaryRemaining: 50, primaryReset: nextReset))); + Assert.Single(Evaluate(evaluator, Presentation(primaryRemaining: 9, primaryReset: nextReset))); + + Assert.Empty(Evaluate(evaluator, Presentation(primaryRemaining: 50, accountKey: "account-a"))); + Assert.Single(Evaluate(evaluator, Presentation(primaryRemaining: 9, accountKey: "account-a"))); + Assert.Empty(Evaluate(evaluator, Presentation(primaryRemaining: 9, accountKey: "account-b"))); + Assert.Empty(Evaluate(evaluator, Presentation(primaryRemaining: 50, accountKey: "account-b"))); + Assert.Single(Evaluate(evaluator, Presentation(primaryRemaining: 9, accountKey: "account-b"))); + } + + [Fact] + public void CategorySwitchStartsACleanBaseline() + { + var evaluator = new UsageAlertEvaluator(); + + Assert.Empty(Evaluate(evaluator, Presentation(primaryRemaining: 50, defaultBucketId: "codex"))); + Assert.Single(Evaluate(evaluator, Presentation(primaryRemaining: 9, defaultBucketId: "codex"))); + Assert.Empty(Evaluate(evaluator, Presentation(primaryRemaining: 9, defaultBucketId: "review"))); + Assert.Empty(Evaluate(evaluator, Presentation(primaryRemaining: 50, defaultBucketId: "review"))); + Assert.Single(Evaluate(evaluator, Presentation(primaryRemaining: 9, defaultBucketId: "review"))); + } + + [Fact] + public void IneligibleSnapshotsNeverProduceAlerts() + { + var cases = new[] + { + Presentation(primaryRemaining: 9, updatedAt: Now.AddMinutes(-6)), + Presentation(primaryRemaining: 9, updatedAt: Now.AddMinutes(1)), + Presentation(primaryRemaining: 9, source: UsageDataSource.LastConfirmed), + Presentation(primaryRemaining: 9, source: UsageDataSource.Unavailable), + Presentation(primaryRemaining: 9, isLoading: true), + Presentation(primaryRemaining: 9, accountKey: null), + }; + + foreach (var presentation in cases) + { + Assert.Empty(Evaluate(new UsageAlertEvaluator(), presentation)); + } + } + + [Fact] + public void ExpiredOrInvalidWindowsAreIgnored() + { + var expired = Presentation(primaryRemaining: 9, primaryReset: Now.AddMinutes(-1)); + var invalid = Presentation(primaryRemaining: 9) with + { + Usage = Presentation(primaryRemaining: null).Usage with + { + Primary = new RateLimitWindow(double.NaN, 300, Now.AddHours(4)), + }, + }; + + Assert.Empty(Evaluate(new UsageAlertEvaluator(), expired)); + Assert.Empty(Evaluate(new UsageAlertEvaluator(), invalid)); + } + + [Fact] + public void AdditionalCategoriesStaySeparateAndLabelsAreSanitized() + { + var longName = new string('x', 100) + "\nraw account label"; + var highBuckets = new[] + { + new RateLimitBucket("coding", longName, new RateLimitWindow(50, 60, Now.AddHours(1)), null), + new RateLimitBucket("review", "Review", new RateLimitWindow(50, 60, Now.AddHours(1)), null), + }; + var lowBuckets = new[] + { + new RateLimitBucket("coding", longName, new RateLimitWindow(95, 60, Now.AddHours(1)), null), + new RateLimitBucket("review", "Review", new RateLimitWindow(95, 60, Now.AddHours(1)), null), + }; + var evaluator = new UsageAlertEvaluator(); + + Assert.Empty(Evaluate(evaluator, Presentation( + primaryRemaining: null, + secondaryRemaining: null, + buckets: highBuckets))); + var alerts = Evaluate(evaluator, Presentation( + primaryRemaining: null, + secondaryRemaining: null, + buckets: lowBuckets)); + + Assert.Equal(2, alerts.Count); + Assert.Contains(alerts, alert => alert.Message.Contains("Review", StringComparison.Ordinal)); + Assert.Contains(alerts, alert => alert.Message.Contains(new string('x', 70), StringComparison.Ordinal)); + Assert.DoesNotContain(new string('x', 71), alerts[0].Message, StringComparison.Ordinal); + Assert.DoesNotContain("raw account label", alerts[1].Message, StringComparison.Ordinal); + Assert.DoesNotContain("account-a", string.Join(" ", alerts.Select(alert => alert.Message)), StringComparison.Ordinal); + } + + [Fact] + public void DefaultBucketExtraDurationIsTrackedSeparately() + { + var evaluator = new UsageAlertEvaluator(); + var high = new[] + { + new RateLimitBucket( + "codex", + "Default", + new RateLimitWindow(50, 60, Now.AddHours(1)), + null), + }; + var low = new[] + { + new RateLimitBucket( + "codex", + "Default", + new RateLimitWindow(95, 60, Now.AddHours(1)), + null), + }; + + Assert.Empty(Evaluate(evaluator, Presentation( + primaryRemaining: 50, + secondaryRemaining: null, + buckets: high, + defaultBucketId: "codex"))); + var alerts = Evaluate(evaluator, Presentation( + primaryRemaining: 50, + secondaryRemaining: null, + buckets: low, + defaultBucketId: "codex")); + + var alert = Assert.Single(alerts); + Assert.Contains("1-hour window", alert.Message, StringComparison.Ordinal); + } + + [Fact] + public void WindowTrackingIsBounded() + { + var highBuckets = Enumerable.Range(0, 40) + .Select(index => new RateLimitBucket( + $"bucket-{index}", + $"Bucket {index}", + new RateLimitWindow(50, 60, Now.AddHours(1)), + null)) + .ToArray(); + var lowBuckets = highBuckets + .Select(bucket => bucket with { Primary = bucket.Primary! with { UsedPercent = 95 } }) + .ToArray(); + var evaluator = new UsageAlertEvaluator(); + + Assert.Empty(Evaluate(evaluator, Presentation(primaryRemaining: null, secondaryRemaining: null, buckets: highBuckets))); + var alerts = Evaluate(evaluator, Presentation(primaryRemaining: null, secondaryRemaining: null, buckets: lowBuckets)); + + Assert.Equal(32, alerts.Count); + } + + [Fact] + public void DisablingOrChangingOptionsClearsTheBaseline() + { + var evaluator = new UsageAlertEvaluator(); + var disabled = new UsageAlertOptions(false); + var changed = new UsageAlertOptions(true, LowRemainingPercent: 20); + + Assert.Empty(Evaluate(evaluator, Presentation(primaryRemaining: 50), options: EnabledOptions)); + Assert.Empty(Evaluate(evaluator, Presentation(primaryRemaining: 9), options: disabled)); + Assert.Empty(Evaluate(evaluator, Presentation(primaryRemaining: 9), options: EnabledOptions)); + Assert.Empty(Evaluate(evaluator, Presentation(primaryRemaining: 50), options: EnabledOptions)); + Assert.Single(Evaluate(evaluator, Presentation(primaryRemaining: 9), options: EnabledOptions)); + + Assert.Empty(Evaluate(evaluator, Presentation(primaryRemaining: 19), options: changed)); + Assert.Empty(Evaluate(evaluator, Presentation(primaryRemaining: 10), options: changed)); + Assert.Empty(Evaluate(evaluator, Presentation(primaryRemaining: 30), options: changed)); + Assert.Single(Evaluate(evaluator, Presentation(primaryRemaining: 19), options: changed)); + } + + [Fact] + public void ResetExpiryWarnsOnEntryWithinTwentyFourHoursAndDeduplicatesByExpiry() + { + var evaluator = new UsageAlertEvaluator(); + var expiry = Now.AddHours(25); + var outside = new RateLimitResetCredits(1, [new RateLimitResetCredit("First title", null, expiry)]); + var inside = new RateLimitResetCredits(1, [new RateLimitResetCredit("Second title", "available", expiry)]); + + Assert.Empty(Evaluate(evaluator, Presentation( + primaryRemaining: null, + secondaryRemaining: null, + resetCredits: outside), now: Now)); + Assert.Empty(Evaluate(evaluator, Presentation( + primaryRemaining: null, + secondaryRemaining: null, + resetCredits: inside, + updatedAt: Now), now: Now.AddHours(2))); + var transition = Evaluate(evaluator, Presentation( + primaryRemaining: null, + secondaryRemaining: null, + resetCredits: inside, + updatedAt: Now.AddHours(2)), now: Now.AddHours(2)); + Assert.Single(transition); + Assert.StartsWith("reset-expiry:", transition[0].Key, StringComparison.Ordinal); + Assert.DoesNotContain("First title", transition[0].Message, StringComparison.Ordinal); + Assert.DoesNotContain("Second title", transition[0].Message, StringComparison.Ordinal); + + Assert.Empty(Evaluate(evaluator, Presentation( + primaryRemaining: null, + secondaryRemaining: null, + resetCredits: new RateLimitResetCredits(1, [new RateLimitResetCredit("Changed title", "available", expiry)]), + updatedAt: Now.AddHours(2)), now: Now.AddHours(2))); + Assert.Empty(Evaluate(evaluator, Presentation( + primaryRemaining: null, + secondaryRemaining: null, + resetCredits: new RateLimitResetCredits(1, [new RateLimitResetCredit("Used", "used", expiry)]), + updatedAt: Now.AddHours(2)), now: Now.AddHours(2))); + } + + [Fact] + public void ForecastWarningUsesMatchingFreshHistoryAndBaselinesPredictiveRisk() + { + var evaluator = new UsageAlertEvaluator(); + var reset = Now.AddHours(4); + UsageHistoryEntry[] firstHistory = + [ + new(Now, 40), + ]; + UsageHistoryEntry[] secondHistory = + [ + new(Now.AddMinutes(-10), 100), + new(Now.AddMinutes(1), 35), + ]; + + Assert.Empty(Evaluate(evaluator, Presentation( + primaryRemaining: 40, + secondaryRemaining: null, + primaryReset: reset, + primaryHistory: firstHistory), now: Now)); + var warning = Evaluate(evaluator, Presentation( + primaryRemaining: 35, + secondaryRemaining: null, + primaryReset: reset, + updatedAt: Now.AddMinutes(1), + primaryHistory: secondHistory), now: Now.AddMinutes(1)); + + var alert = Assert.Single(warning); + Assert.StartsWith("forecast:", alert.Key, StringComparison.Ordinal); + Assert.Contains("forecast may reach", alert.Message, StringComparison.Ordinal); + Assert.Empty(Evaluate(evaluator, Presentation( + primaryRemaining: 35, + secondaryRemaining: null, + primaryReset: reset, + updatedAt: Now.AddMinutes(1), + primaryHistory: secondHistory), now: Now.AddMinutes(1))); + + var predictiveBaselineEvaluator = new UsageAlertEvaluator(); + Assert.Empty(Evaluate(predictiveBaselineEvaluator, Presentation( + primaryRemaining: 40, + secondaryRemaining: null, + primaryReset: reset, + primaryHistory: secondHistory), now: Now.AddMinutes(1))); + Assert.Empty(Evaluate(predictiveBaselineEvaluator, Presentation( + primaryRemaining: 40, + secondaryRemaining: null, + primaryReset: reset, + primaryHistory: secondHistory), now: Now.AddMinutes(1))); + } + + private static IReadOnlyList Evaluate( + UsageAlertEvaluator evaluator, + UsagePresentation presentation, + DateTimeOffset? now = null, + UsageAlertOptions? options = null) => + evaluator.Evaluate(presentation, now ?? Now, RefreshInterval, options ?? EnabledOptions); + + 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, + string? defaultBucketId = "codex", + IReadOnlyList? buckets = null, + RateLimitResetCredits? resetCredits = null, + IReadOnlyList? primaryHistory = null, + IReadOnlyList? weeklyHistory = 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, + resetCredits, + updatedAt ?? Now, + source, + null, + Buckets: buckets, + AccountKey: accountKey, + DefaultBucketId: defaultBucketId); + return new UsagePresentation( + snapshot, + primaryHistory ?? Array.Empty(), + weeklyHistory ?? Array.Empty(), + new AdaptiveWeeklyUsageHistory([], null), + LocalTokenUsageSnapshot.Unavailable, + isLoading); + } +} 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/UsagePreferenceTests.cs b/CodexUsageDock.Tests/UsagePreferenceTests.cs new file mode 100644 index 0000000..737f1be --- /dev/null +++ b/CodexUsageDock.Tests/UsagePreferenceTests.cs @@ -0,0 +1,157 @@ +using System.Text.Json; +using Microsoft.CommandPalette.Extensions.Toolkit; +using Xunit; + +namespace CodexUsageDock.Tests; + +public sealed class UsagePreferenceTests : IDisposable +{ + private readonly TestEnvironment _environment = new(); + + public void Dispose() => _environment.Dispose(); + + [Fact] + public void NewPreferencesUseSafeDefaults() + { + var settings = _environment.CreateSettings(); + + Assert.False(settings.EnableUsageAlerts); + Assert.False(settings.CompactDock); + Assert.False(settings.SeparateDockItems); + Assert.True(settings.ShowAccountActivity); + } + + [Fact] + public void UsagePreferencesPersistAcrossNewPages() + { + var first = _environment.CreateSettings(); + SubmitSettings(first, new Dictionary + { + ["enableUsageAlerts"] = "true", + ["compactDock"] = "true", + ["separateDockItems"] = "true", + ["showAccountActivity"] = "false", + }); + + Assert.True(first.EnableUsageAlerts); + Assert.True(first.CompactDock); + Assert.True(first.SeparateDockItems); + Assert.False(first.ShowAccountActivity); + + var restarted = _environment.CreateSettings(); + + Assert.True(restarted.EnableUsageAlerts); + Assert.True(restarted.CompactDock); + Assert.True(restarted.SeparateDockItems); + Assert.False(restarted.ShowAccountActivity); + } + + [Fact] + public void SettingsLoadKeepsValidValuesAndRejectsInvalidChoices() + { + File.WriteAllText(_environment.PathFor("settings.json"), JsonSerializer.Serialize( + new Dictionary + { + ["enableUsageAlerts"] = "true", + ["compactDock"] = "true", + ["separateDockItems"] = "not-a-boolean", + ["showAccountActivity"] = "false", + })); + + var settings = _environment.CreateSettings(); + + Assert.True(settings.EnableUsageAlerts); + Assert.True(settings.CompactDock); + Assert.False(settings.SeparateDockItems); + Assert.False(settings.ShowAccountActivity); + } + + [Theory] + [InlineData("FiveHour", 47, false, "5h 47%")] + [InlineData("Weekly", 86, false, "Week 86%")] + [InlineData("FiveHour", 47, true, "5h47%")] + [InlineData("Weekly", 86, true, "W86%")] + public void FormatQuotaTitleSupportsFullAndCompactModes( + string kindName, + double remainingPercent, + bool compact, + string expected) + { + var kind = Enum.Parse(kindName); + Assert.Equal(expected, UsageDockItem.FormatQuotaTitle(kind, remainingPercent, compact)); + } + + [Fact] + public async Task NonCompactModeKeepsResetTimeAndFreshnessWarning() + { + var now = DateTimeOffset.Now; + var snapshot = new CodexUsageSnapshot( + new RateLimitWindow(53, 300, now.AddHours(4)), + null, + "pro", + null, + null, + now.AddMinutes(-10), + UsageDataSource.AppServer, + null); + + using var service = _environment.CreateService(_ => Task.FromResult(snapshot), () => snapshot); + var settings = _environment.CreateSettings(); + using var details = new CodexUsageDockPage(service, settings); + using var item = new UsageDockItem(service, UsageDockItemKind.FiveHour, details, settings); + + await service.RefreshAsync(); + + Assert.Equal("5h 47%", item.Title); + Assert.Contains("Stale", item.Subtitle, StringComparison.Ordinal); + Assert.Contains("reset", item.Subtitle, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task CompactModeUsesShortTitleAndOmitsResetTimeButKeepsFreshnessWarning() + { + var now = DateTimeOffset.Now; + var snapshot = new CodexUsageSnapshot( + new RateLimitWindow(53, 300, now.AddHours(4)), + null, + "pro", + null, + null, + now.AddMinutes(-10), + UsageDataSource.AppServer, + null); + + using var service = _environment.CreateService(_ => Task.FromResult(snapshot), () => snapshot); + var settings = _environment.CreateSettings(); + SubmitSettings(settings, new Dictionary { ["compactDock"] = "true" }); + using var details = new CodexUsageDockPage(service, settings); + using var item = new UsageDockItem(service, UsageDockItemKind.FiveHour, details, settings); + + await service.RefreshAsync(); + + Assert.Equal("5h47%", item.Title); + Assert.Contains("Stale", item.Subtitle, StringComparison.Ordinal); + Assert.DoesNotContain("reset", item.Subtitle, StringComparison.OrdinalIgnoreCase); + } + + private static void SubmitSettings(CodexUsageDockSettingsPage page, IReadOnlyDictionary values) + { + var payload = new Dictionary + { + ["showFiveHourLimit"] = "true", + ["showWeeklyLimit"] = "true", + ["showResetsAndCredits"] = "true", + ["showResetTime"] = "true", + ["useAdaptiveWeeklyForecast"] = "true", + ["refreshInterval"] = "1", + }; + + foreach (var pair in values) + { + payload[pair.Key] = pair.Value; + } + + var form = page.GetContent().OfType().Last(); + form.SubmitForm(JsonSerializer.Serialize(payload), "{}"); + } +} diff --git a/CodexUsageDock/AccountUsageData.cs b/CodexUsageDock/AccountUsageData.cs new file mode 100644 index 0000000..fdd9913 --- /dev/null +++ b/CodexUsageDock/AccountUsageData.cs @@ -0,0 +1,129 @@ +using System.Globalization; +using System.Text.Json; + +namespace CodexUsageDock; + +internal enum AccountUsageStatus +{ + Available, + Partial, + Unsupported, + Unavailable, +} + +internal sealed record AccountUsageSnapshot( + string? AccountKey, + DateTimeOffset UpdatedAt, + IReadOnlyList Days, + AccountUsageStatus Status, + long? LifetimeTokens = null, + long? PeakDailyTokens = null, + long? LongestRunningTurnSeconds = null, + long? CurrentStreakDays = null, + long? LongestStreakDays = null) +{ + internal static AccountUsageSnapshot Unavailable { get; } = new(null, DateTimeOffset.MinValue, [], AccountUsageStatus.Unavailable); +} + +internal static class AccountUsageParser +{ + internal const int MaximumDays = 366; + private const int MaximumInputDays = 4096; + + internal static AccountUsageSnapshot Parse(JsonElement result, string accountKey, DateTimeOffset now) + { + if (result.ValueKind != JsonValueKind.Object || string.IsNullOrWhiteSpace(accountKey)) + { + return AccountUsageSnapshot.Unavailable with { UpdatedAt = now }; + } + + var partial = false; + var daysAvailable = false; + var days = new SortedDictionary(); + if (result.TryGetProperty("dailyUsageBuckets", out var daily)) + { + if (daily.ValueKind == JsonValueKind.Array) + { + daysAvailable = true; + var inputCount = 0; + foreach (var entry in daily.EnumerateArray()) + { + if (++inputCount > MaximumInputDays) + { + partial = true; + break; + } + + if (entry.ValueKind != JsonValueKind.Object + || !entry.TryGetProperty("startDate", out var dateValue) + || dateValue.ValueKind != JsonValueKind.String + || !DateOnly.TryParseExact(dateValue.GetString(), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date) + || !entry.TryGetProperty("tokens", out var tokensValue) + || tokensValue.ValueKind != JsonValueKind.Number + || !tokensValue.TryGetInt64(out var tokens) + || tokens < 0 + || !days.TryAdd(date, tokens)) + { + partial = true; + continue; + } + + if (days.Count > MaximumDays) + { + days.Remove(days.First().Key); + partial = true; + } + } + } + else if (daily.ValueKind != JsonValueKind.Null) + { + partial = true; + } + } + + var summary = default(JsonElement); + if (result.TryGetProperty("summary", out var summaryValue)) + { + if (summaryValue.ValueKind == JsonValueKind.Object) + { + summary = summaryValue; + } + else if (summaryValue.ValueKind != JsonValueKind.Null) + { + partial = true; + } + } + + var lifetime = ReadNonnegative(summary, "lifetimeTokens", ref partial); + var peak = ReadNonnegative(summary, "peakDailyTokens", ref partial); + var longest = ReadNonnegative(summary, "longestRunningTurnSec", ref partial); + var currentStreak = ReadNonnegative(summary, "currentStreakDays", ref partial); + var longestStreak = ReadNonnegative(summary, "longestStreakDays", ref partial); + if (!daysAvailable && lifetime is null && peak is null && longest is null && currentStreak is null && longestStreak is null) + { + return AccountUsageSnapshot.Unavailable with { UpdatedAt = now }; + } + + return new AccountUsageSnapshot(accountKey, now, + days.Select(day => new DailyTokenUsage(day.Key, day.Value)).ToArray(), + partial || !daysAvailable ? AccountUsageStatus.Partial : AccountUsageStatus.Available, + lifetime, peak, longest, currentStreak, longestStreak); + } + + private static long? ReadNonnegative(JsonElement summary, string name, ref bool partial) + { + if (summary.ValueKind != JsonValueKind.Object || !summary.TryGetProperty(name, out var value) + || value.ValueKind == JsonValueKind.Null) + { + return null; + } + + if (value.ValueKind == JsonValueKind.Number && value.TryGetInt64(out var number) && number >= 0) + { + return number; + } + + partial = true; + return null; + } +} 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/CodexAppServerReader.cs b/CodexUsageDock/CodexAppServerReader.cs index 7918867..1359b06 100644 --- a/CodexUsageDock/CodexAppServerReader.cs +++ b/CodexUsageDock/CodexAppServerReader.cs @@ -10,10 +10,255 @@ internal static class CodexAppServerReader { private const int MaximumBucketCount = 32; - internal static async Task ReadAsync(CancellationToken cancellationToken = default) + internal static Task ReadAsync(CancellationToken cancellationToken = default) => + ReadAsync(CodexSourceOptions.Default, cancellationToken); + + internal static Task ReadAsync(CodexSourceOptions options, CancellationToken cancellationToken) => + WithAppServerAsync(options, static async (process, token) => + { + await SendAsync(process, "account/rateLimits/read", 2, null, token).ConfigureAwait(false); + await SendAsync( + process, + "account/read", + 3, + static writer => + { + writer.WritePropertyName("params"); + writer.WriteStartObject(); + writer.WriteBoolean("refreshToken", false); + writer.WriteEndObject(); + }, + token).ConfigureAwait(false); + + var responses = await ReadResponsesAsync(process.StandardOutput, token, 2, 3).ConfigureAwait(false); + using var rateResponse = responses[2]; + using var accountResponse = responses[3]; + ThrowIfError(rateResponse.RootElement); + return ParseSnapshot(rateResponse.RootElement.GetProperty("result"), accountResponse.RootElement, DateTimeOffset.Now); + }, cancellationToken); + + internal static async Task ReadAccountUsageAsync(CodexSourceOptions options, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + try + { + return await WithAppServerAsync(options, static (process, token) => + ReadAccountUsageSequenceAsync((method, id, requestToken) => RequestAsync(process, method, id, requestToken), token), + cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } + catch (Exception error) when (error is IOException or InvalidOperationException or JsonException + or OperationCanceledException or System.ComponentModel.Win32Exception or UnauthorizedAccessException) + { + return AccountUsageSnapshot.Unavailable with { UpdatedAt = DateTimeOffset.Now }; + } + } + + internal static async Task ReadAccountUsageSequenceAsync( + Func> request, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + using var before = await request("account/rateLimits/read", 2, cancellationToken).ConfigureAwait(false); + var beforeKey = GetResponseAccountKey(before.RootElement); + if (beforeKey is null) + { + return AccountUsageSnapshot.Unavailable with { UpdatedAt = DateTimeOffset.Now }; + } + + using var usage = await request("account/usage/read", 3, cancellationToken).ConfigureAwait(false); + if (IsMethodNotFound(usage.RootElement)) + { + return new AccountUsageSnapshot(beforeKey, DateTimeOffset.Now, [], AccountUsageStatus.Unsupported); + } + + if (HasError(usage.RootElement)) + { + return AccountUsageSnapshot.Unavailable with { UpdatedAt = DateTimeOffset.Now }; + } + + using var after = await request("account/rateLimits/read", 4, cancellationToken).ConfigureAwait(false); + var afterKey = GetResponseAccountKey(after.RootElement); + if (!string.Equals(beforeKey, afterKey, StringComparison.Ordinal)) + { + return AccountUsageSnapshot.Unavailable with { UpdatedAt = DateTimeOffset.Now }; + } + + return TryGetObject(usage.RootElement, "result", out var result) + ? AccountUsageParser.Parse(result, beforeKey, DateTimeOffset.Now) + : AccountUsageSnapshot.Unavailable with { UpdatedAt = DateTimeOffset.Now }; + } + + internal static async Task ReadThreadUsageAsync( + CodexSourceOptions options, string threadId, string expectedAccountKey, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + if (!ThreadUsageParser.IsValidThreadId(threadId)) return EmptyThreadUsage(ThreadUsageStatus.Unavailable); + if (!IsValidAccountKey(expectedAccountKey)) return EmptyThreadUsage(ThreadUsageStatus.AccountMismatch); + try + { + return await WithAppServerAsync(options, (process, token) => + ReadThreadUsageSequenceAsync((method, id, parameters, requestToken) => + RequestAsync(process, method, id, parameters, requestToken), threadId, expectedAccountKey, token), + cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } + catch (Exception error) when (error is IOException or InvalidOperationException or JsonException + or OperationCanceledException or System.ComponentModel.Win32Exception or UnauthorizedAccessException) + { + return EmptyThreadUsage(ThreadUsageStatus.Unavailable); + } + } + + internal static async Task ReadThreadUsageSequenceAsync( + Func?, CancellationToken, Task> request, + string threadId, string expectedAccountKey, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + if (!ThreadUsageParser.IsValidThreadId(threadId)) return EmptyThreadUsage(ThreadUsageStatus.Unavailable); + if (!IsValidAccountKey(expectedAccountKey)) return EmptyThreadUsage(ThreadUsageStatus.AccountMismatch); + + using var before = await request("account/rateLimits/read", 2, null, cancellationToken).ConfigureAwait(false); + if (IsMethodNotFound(before.RootElement)) return EmptyThreadUsage(ThreadUsageStatus.Unsupported); + if (HasError(before.RootElement)) return EmptyThreadUsage(ThreadUsageStatus.Unavailable); + var beforeKey = GetResponseAccountKey(before.RootElement); + if (!string.Equals(expectedAccountKey, beforeKey, StringComparison.OrdinalIgnoreCase)) + return EmptyThreadUsage(ThreadUsageStatus.AccountMismatch); + + using var usage = await request("account/usage/read", 3, + writer => WriteStringParameter(writer, "threadId", threadId), cancellationToken).ConfigureAwait(false); + if (IsMethodNotFound(usage.RootElement)) return EmptyThreadUsage(ThreadUsageStatus.Unsupported); + if (HasError(usage.RootElement)) return EmptyThreadUsage(ThreadUsageStatus.Unavailable); + + using var after = await request("account/rateLimits/read", 4, null, cancellationToken).ConfigureAwait(false); + if (HasError(after.RootElement)) return EmptyThreadUsage(ThreadUsageStatus.Unavailable); + if (!string.Equals(beforeKey, GetResponseAccountKey(after.RootElement), StringComparison.Ordinal)) + return EmptyThreadUsage(ThreadUsageStatus.AccountMismatch); + + return TryGetObject(usage.RootElement, "result", out var result) + ? ThreadUsageParser.Parse(result, threadId, beforeKey!, DateTimeOffset.Now) + : EmptyThreadUsage(ThreadUsageStatus.Unavailable); + } + + internal static async Task ConsumeResetCreditAsync( + CodexSourceOptions options, string expectedAccountKey, string idempotencyKey, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using var process = StartAppServer(); + ValidateIdempotencyKey(idempotencyKey); + if (!IsValidAccountKey(expectedAccountKey)) return new(ResetCreditOutcome.AccountMismatch, DateTimeOffset.Now); + + var consumeStarted = false; + ResetCreditResult? completed = null; + try + { + return await WithAppServerAsync(options, async (process, token) => + { + var result = await ConsumeResetCreditSequenceAsync((method, id, parameters, requestToken) => + { + if (method == "account/rateLimitResetCredit/consume") consumeStarted = true; + return RequestAsync(process, method, id, parameters, requestToken); + }, expectedAccountKey, idempotencyKey, token).ConfigureAwait(false); + completed = result; + return result; + }, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + // Cleanup can fail after the server has replied. Keep a known result; + // otherwise never describe a possibly dispatched reset as safe to replace. + return completed ?? new(consumeStarted ? ResetCreditOutcome.Ambiguous : ResetCreditOutcome.Unavailable, DateTimeOffset.Now); + } + } + + internal static async Task ConsumeResetCreditSequenceAsync( + Func?, CancellationToken, Task> request, + string expectedAccountKey, string idempotencyKey, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + ValidateIdempotencyKey(idempotencyKey); + var attemptedAt = DateTimeOffset.Now; + if (!IsValidAccountKey(expectedAccountKey)) return new(ResetCreditOutcome.AccountMismatch, attemptedAt); + + var consumeStarted = false; + try + { + using var before = await request("account/rateLimits/read", 2, null, cancellationToken).ConfigureAwait(false); + if (IsMethodNotFound(before.RootElement)) return new(ResetCreditOutcome.Unsupported, attemptedAt); + if (HasError(before.RootElement)) return new(ResetCreditOutcome.Unavailable, attemptedAt); + if (!string.Equals(expectedAccountKey, GetResponseAccountKey(before.RootElement), StringComparison.OrdinalIgnoreCase)) + return new(ResetCreditOutcome.AccountMismatch, attemptedAt); + + cancellationToken.ThrowIfCancellationRequested(); + attemptedAt = DateTimeOffset.Now; + consumeStarted = true; + using var response = await request("account/rateLimitResetCredit/consume", 3, + writer => WriteStringParameter(writer, "idempotencyKey", idempotencyKey), cancellationToken).ConfigureAwait(false); + return ResetCreditParser.Parse(response.RootElement, attemptedAt); + } + catch (Exception) + { + return new(consumeStarted ? ResetCreditOutcome.Ambiguous : ResetCreditOutcome.Unavailable, attemptedAt); + } + } + + private static ThreadUsageSnapshot EmptyThreadUsage(ThreadUsageStatus status) => + ThreadUsageSnapshot.Unavailable with { Status = status, UpdatedAt = DateTimeOffset.Now }; + + private static bool IsValidAccountKey(string? value) => value is { Length: 64 } && value.All(char.IsAsciiHexDigit); + + private static void ValidateIdempotencyKey(string value) + { + if (!ResetCreditParser.IsValidIdempotencyKey(value)) + throw new ArgumentException("A bounded, nonempty idempotency key is required.", nameof(value)); + } + + private static void WriteStringParameter(Utf8JsonWriter writer, string name, string value) + { + writer.WritePropertyName("params"); + writer.WriteStartObject(); + writer.WriteString(name, value); + writer.WriteEndObject(); + } + + private static string? GetResponseAccountKey(JsonElement response) => + !HasError(response) && TryGetObject(response, "result", out var result) ? ParseAccountKey(result) : null; + + internal static bool IsMethodNotFound(JsonElement response) => + TryGetObject(response, "error", out var error) + && error.TryGetProperty("code", out var code) + && code.ValueKind == JsonValueKind.Number + && code.TryGetInt32(out var number) + && number == -32601; + + private static Task RequestAsync(Process process, string method, int id, CancellationToken cancellationToken) => + RequestAsync(process, method, id, method == "account/usage/read" ? static writer => + { + writer.WritePropertyName("params"); + writer.WriteStartObject(); + writer.WriteEndObject(); + } : null, cancellationToken); + + private static async Task RequestAsync(Process process, string method, int id, + Action? parameters, CancellationToken cancellationToken) + { + await SendAsync(process, method, id, parameters, cancellationToken).ConfigureAwait(false); + var responses = await ReadResponsesAsync(process.StandardOutput, cancellationToken, id).ConfigureAwait(false); + return responses[id]; + } + + private static async Task WithAppServerAsync( + CodexSourceOptions options, + Func> operation, + CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + using var process = StartAppServer(options); var standardErrorDrain = DrainAsync(process.StandardError); using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); timeout.CancelAfter(TimeSpan.FromSeconds(20)); @@ -43,27 +288,7 @@ await SendAsync( ThrowIfError(initializationResponse.RootElement); await SendAsync(process, "initialized", null, null, readCancellationToken).ConfigureAwait(false); - await SendAsync(process, "account/rateLimits/read", 2, null, readCancellationToken).ConfigureAwait(false); - await SendAsync( - process, - "account/read", - 3, - static writer => - { - writer.WritePropertyName("params"); - writer.WriteStartObject(); - writer.WriteBoolean("refreshToken", false); - writer.WriteEndObject(); - }, - readCancellationToken).ConfigureAwait(false); - - var responses = await ReadResponsesAsync(process.StandardOutput, readCancellationToken, 2, 3).ConfigureAwait(false); - using var rateResponse = responses[2]; - using var accountResponse = responses[3]; - - ThrowIfError(rateResponse.RootElement); - var rateResult = rateResponse.RootElement.GetProperty("result"); - return ParseSnapshot(rateResult, accountResponse.RootElement, DateTimeOffset.Now); + return await operation(process, readCancellationToken).ConfigureAwait(false); } finally { @@ -239,8 +464,15 @@ internal static async Task> ReadResponsesAsync(Tex throw new InvalidOperationException("Codex app-server stopped unexpectedly."); } - var document = JsonDocument.Parse(line); - if (document.RootElement.TryGetProperty("id", out var id) + if (line.Length > 1_048_576) + { + throw new InvalidOperationException("Codex app-server returned an oversized response."); + } + + var document = JsonDocument.Parse(line, new JsonDocumentOptions { MaxDepth = 32 }); + if (document.RootElement.ValueKind == JsonValueKind.Object + && document.RootElement.TryGetProperty("id", out var id) + && id.ValueKind == JsonValueKind.Number && id.TryGetInt32(out var value) && pendingIds.Remove(value)) { @@ -355,13 +587,15 @@ internal static async Task> ReadResponsesAsync(Tex return new RateLimitResetCredits(availableCount, parsed); } - private static Process StartAppServer() + private static Process StartAppServer(CodexSourceOptions options) => + Process.Start(CreateStartInfo(options)) ?? throw new InvalidOperationException("Codex app-server could not be started."); + + internal static ProcessStartInfo CreateStartInfo(CodexSourceOptions options) { - var executable = FindCodexExecutable(); + var executable = options.ExecutablePath ?? FindCodexExecutable(); var startInfo = new ProcessStartInfo { FileName = executable, - Arguments = "app-server --stdio", WorkingDirectory = GetSafeWorkingDirectory(executable), UseShellExecute = false, RedirectStandardInput = true, @@ -369,7 +603,13 @@ private static Process StartAppServer() RedirectStandardError = true, CreateNoWindow = true, }; - return Process.Start(startInfo) ?? throw new InvalidOperationException("Codex app-server could not be started."); + startInfo.ArgumentList.Add("app-server"); + startInfo.ArgumentList.Add("--stdio"); + if (options.HomePath is not null) + { + startInfo.Environment["CODEX_HOME"] = options.HomePath; + } + return startInfo; } private static string FindCodexExecutable() @@ -497,12 +737,15 @@ private static async Task ObserveProcessExitAsync(Process process, Task standard private static void ThrowIfError(JsonElement response) { - if (response.TryGetProperty("error", out var error)) + if (HasError(response)) { - throw new InvalidOperationException(error.GetRawText()); + throw new InvalidOperationException("Codex app-server returned an error."); } } + private static bool HasError(JsonElement response) => response.ValueKind == JsonValueKind.Object + && response.TryGetProperty("error", out _); + private static string? ParsePlan(JsonElement accountResponse) { if (!TryGetObject(accountResponse, "result", out var result) diff --git a/CodexUsageDock/CodexSourceOptions.cs b/CodexUsageDock/CodexSourceOptions.cs new file mode 100644 index 0000000..c6516c8 --- /dev/null +++ b/CodexUsageDock/CodexSourceOptions.cs @@ -0,0 +1,47 @@ +namespace CodexUsageDock; + +internal sealed record CodexSourceOptions(string? ExecutablePath = null, string? HomePath = null) +{ + internal static CodexSourceOptions Default { get; } = new(); + + internal static bool TryCreate(string? executablePath, string? homePath, out CodexSourceOptions options, out string? error) + { + options = Default; + error = null; + try + { + var executable = Normalize(executablePath); + var home = Normalize(homePath); + if (executable is not null && (!File.Exists(executable) + || !(Path.GetFileName(executable).Equals("codex.exe", StringComparison.OrdinalIgnoreCase) + || Path.GetFileName(executable).Equals("codex.cmd", StringComparison.OrdinalIgnoreCase)) + || CodexAppServerReader.IsWindowsAppsPath(executable))) + { + error = "Choose an existing standalone codex.exe or codex.cmd outside WindowsApps."; + return false; + } + if (home is not null && !Directory.Exists(home)) + { + error = "The selected Codex home directory is unavailable. Check the path and its access permissions."; + return false; + } + options = new(executable, home); + return true; + } + catch (Exception exception) when (exception is ArgumentException or NotSupportedException or IOException or UnauthorizedAccessException) + { + error = "Source paths must be complete, accessible Windows paths without arguments or control characters."; + return false; + } + } + + private static string? Normalize(string? value) + { + if (string.IsNullOrWhiteSpace(value)) return null; + if (value.Length > 1024 || value.Any(char.IsControl) || !Path.IsPathFullyQualified(value)) + { + throw new ArgumentException("Invalid source path."); + } + return Path.TrimEndingDirectorySeparator(Path.GetFullPath(value.Trim())); + } +} diff --git a/CodexUsageDock/CodexUsageDockCommandsProvider.cs b/CodexUsageDock/CodexUsageDockCommandsProvider.cs index 7fb2d06..0d8dcd7 100644 --- a/CodexUsageDock/CodexUsageDockCommandsProvider.cs +++ b/CodexUsageDock/CodexUsageDockCommandsProvider.cs @@ -13,6 +13,23 @@ public partial class CodexUsageDockCommandsProvider : CommandProvider private readonly ICommandItem[] _commands; private readonly CodexUsageDockPage _details; private readonly CodexUsageDiagnosticsPage _diagnostics; + private readonly CodexAccountActivityPage _accountActivity; + 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; + private bool _lastAlertsEnabled; + 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() @@ -20,21 +37,39 @@ public CodexUsageDockCommandsProvider() { } - internal CodexUsageDockCommandsProvider(CodexUsageService usage, CodexUsageDockSettingsPage settings) + internal CodexUsageDockCommandsProvider(CodexUsageService usage, CodexUsageDockSettingsPage settings, + Action? notify = null, Func? clock = null) { _usage = usage; _settings = settings; + _settings.Id = "nl.mathijs.codexusage.settings"; + _notify = notify ?? (message => new ToastStatusMessage(message).Show()); + _clock = clock ?? (() => DateTimeOffset.Now); + _lastAlertsEnabled = _settings.EnableUsageAlerts; DisplayName = "Codex Usage"; Id = "nl.mathijs.codexusage"; Icon = new IconInfo("\uE943"); _usage.SetRefreshInterval(_settings.RefreshInterval); _usage.SetAdaptiveWeeklyForecastEnabled(_settings.UseAdaptiveWeeklyForecast); + _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); + _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 = [ @@ -54,29 +89,50 @@ internal CodexUsageDockCommandsProvider(CodexUsageService usage, CodexUsageDockS Title = "Codex Usage diagnostics", Subtitle = "Source, freshness, supported fields, and safe troubleshooting details", }, + new CommandItem(_accountActivity) + { + Title = "Codex account activity", + Subtitle = "Account-wide daily tokens reported by Codex", + }, + 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; + return _commands.Concat(Volatile.Read(ref _dockBands)).FirstOrDefault(item => item.Command.Id == id); + } private void OnSettingsChanged(object? sender, EventArgs e) { + if (_lastAlertsEnabled != _settings.EnableUsageAlerts) + { + _alerts.Reset(); + _lastAlertsEnabled = _settings.EnableUsageAlerts; + } _usage.SetRefreshInterval(_settings.RefreshInterval); _usage.SetAdaptiveWeeklyForecastEnabled(_settings.UseAdaptiveWeeklyForecast); + _usage.SetAccountActivityEnabled(_settings.ShowAccountActivity); + _usage.SetAggregateRetentionDays(_settings.HistoryRetentionDays); _fiveHour.Refresh(); _weekly.Refresh(); _details.Refresh(); - RebuildDockBands(); - RaiseItemsChanged(); + _history.Refresh(); + UpdateDockLayout(); } private void OnClearAdaptiveHistoryRequested(object? sender, EventArgs e) @@ -99,17 +155,44 @@ 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) + { + var message = string.Join(" · ", alerts.Take(3).Select(alert => alert.Message)); + if (alerts.Count > 3) message += $" · {alerts.Count - 3} more usage alerts"; + _notify(message); + } } - private void RebuildDockBands() + private void UpdateDockLayout() { - var items = GetVisibleDockItems(); - var dockBand = items.Length == 0 - ? null - : new WrappedDockItem(items, "nl.mathijs.codexusage.dock", DisplayName); - _dockBands = dockBand is null ? [] : [dockBand]; + var changedBands = new List(); + bool catalogChanged; + lock (_dockLayoutLock) + { + 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); + } } private IListItem[] GetVisibleDockItems() @@ -143,6 +226,10 @@ public override void Dispose() _resetsAndCredits.Dispose(); _details.Dispose(); _diagnostics.Dispose(); + _accountActivity.Dispose(); + _history.Dispose(); + _actions.Dispose(); + _textUsage.Dispose(); _usage.Dispose(); base.Dispose(); GC.SuppressFinalize(this); diff --git a/CodexUsageDock/CodexUsageService.AccountActivity.cs b/CodexUsageDock/CodexUsageService.AccountActivity.cs new file mode 100644 index 0000000..6e535d1 --- /dev/null +++ b/CodexUsageDock/CodexUsageService.AccountActivity.cs @@ -0,0 +1,94 @@ +namespace CodexUsageDock; + +internal sealed partial class CodexUsageService +{ + private readonly Func>? _accountUsageReader; + private Task? _accountReadTask; + private Task _accountRefreshTask = Task.CompletedTask; + private DateTimeOffset _accountReadAfter; + private bool _accountActivityEnabled = true; + + internal AccountUsageSnapshot CurrentAccountUsage { get; private set; } = AccountUsageSnapshot.Unavailable; + + internal Task AccountUsageRefreshTask + { + get { lock (_refreshStateLock) { return _accountRefreshTask; } } + } + + internal void RequestAccountUsageRefresh() + { + lock (_refreshStateLock) { _accountReadAfter = DateTimeOffset.MinValue; } + } + + internal void SetAccountActivityEnabled(bool enabled) + { + lock (_refreshStateLock) + { + if (_accountActivityEnabled == enabled) return; + _accountActivityEnabled = enabled; + _accountReadAfter = DateTimeOffset.MinValue; + if (!enabled) CurrentAccountUsage = AccountUsageSnapshot.Unavailable; + } + RaiseUpdated(); + } + + private void StartAccountUsageRefresh(CodexUsageSnapshot snapshot) + { + lock (_refreshStateLock) + { + if (_disposed || !ReferenceEquals(Current, snapshot) || !_accountActivityEnabled || (!_usesConfiguredSources && _accountUsageReader is null) + || snapshot.Source != UsageDataSource.AppServer || snapshot.AccountKey is null + || _accountReadTask is { IsCompleted: false } || _clock() < _accountReadAfter) + { + return; + } + + var cancellation = CancellationTokenSource.CreateLinkedTokenSource(_lifetimeCancellation.Token); + cancellation.CancelAfter(TimeSpan.FromSeconds(25)); + var sourceGeneration = _sourceGeneration; + var options = _sourceOptions; + var account = snapshot.AccountKey; + _accountReadAfter = _clock().AddMinutes(5); + var read = _accountReadTask = Task.Run(() => _usesConfiguredSources + ? CodexAppServerReader.ReadAccountUsageAsync(options, cancellation.Token) + : _accountUsageReader!(cancellation.Token)); + _accountRefreshTask = Task.Run(() => ObserveAccountUsageAsync(read, cancellation, sourceGeneration, account)); + } + } + + private async Task ObserveAccountUsageAsync(Task read, CancellationTokenSource cancellation, + long sourceGeneration, string account) + { + try + { + var result = await read.WaitAsync(cancellation.Token).ConfigureAwait(false); + lock (_refreshStateLock) + { + if (_disposed || !_accountActivityEnabled || sourceGeneration != _sourceGeneration + || !string.Equals(Current.AccountKey, account, StringComparison.Ordinal)) return; + if (result.Status is AccountUsageStatus.Available or AccountUsageStatus.Partial + && !string.Equals(result.AccountKey, account, StringComparison.Ordinal)) return; + + CurrentAccountUsage = result; + if (result.Status == AccountUsageStatus.Unsupported) _accountReadAfter = _clock().AddMinutes(30); + } + RaiseUpdated(); + } + catch (OperationCanceledException) + { + } + catch (Exception exception) + { + LocalStorage.TraceFailure("read account activity", exception); + } + finally + { + if (read.IsCompleted) cancellation.Dispose(); + else _ = read.ContinueWith(task => + { + _ = task.Exception; + cancellation.Dispose(); + }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + } + } +} diff --git a/CodexUsageDock/CodexUsageService.Actions.cs b/CodexUsageDock/CodexUsageService.Actions.cs new file mode 100644 index 0000000..ae6a220 --- /dev/null +++ b/CodexUsageDock/CodexUsageService.Actions.cs @@ -0,0 +1,191 @@ +namespace CodexUsageDock; + +internal sealed partial class CodexUsageService +{ + private ResetAttemptJournal? _resetJournal; + private Func>? _resetCreditConsumer; + private Func>? _threadUsageReader; + private Task? _resetActionTask; + private Task? _threadActionTask; + private PendingTaskRead? _pendingTaskRead; + private long _taskRequestVersion; + private sealed record PendingTaskRead(CodexSourceOptions Options, string ThreadId, string Account, + long SourceGeneration, long RequestVersion); + internal string ResetActionStatus { get; private set; } = "Only an explicit, confirmed action can use an existing earned reset."; + internal ThreadUsageSnapshot? CurrentThreadUsage { get; private set; } + internal string ThreadActionStatus { get; private set; } = "Enter a Codex task ID to request its reported usage estimate."; + + internal (CodexUsageSnapshot Usage, ThreadUsageSnapshot? Task, string TaskStatus, string ResetStatus) GetActionPresentation() + { + lock (_refreshStateLock) { return (Current, CurrentThreadUsage, ThreadActionStatus, ResetActionStatus); } + } + + internal void InitializeOptionalFeatures(string aggregatePath, string resetJournalPath, + Func>? resetConsumer = null, + Func>? threadReader = null) + { + if (_started) throw new InvalidOperationException("Optional storage must be configured before monitoring starts."); + _aggregatePath = Path.GetFullPath(aggregatePath); + _resetJournal = new ResetAttemptJournal(Path.GetFullPath(resetJournalPath)); + _resetCreditConsumer = resetConsumer ?? (_usesConfiguredSources ? CodexAppServerReader.ConsumeResetCreditAsync : null); + _threadUsageReader = threadReader ?? (_usesConfiguredSources ? CodexAppServerReader.ReadThreadUsageAsync : null); + } + + internal Task ConsumeEarnedResetAsync(string expectedAccountKey) + { + Task task; + lock (_refreshStateLock) + { + if (_resetActionTask is { IsCompleted: false }) return _resetActionTask; + if (_disposed || _resetJournal is null || _resetCreditConsumer is null + || !IsFreshAccount(expectedAccountKey)) + { + ResetActionStatus = "Refresh a live, identified Codex account before using a reset."; + task = Task.FromResult(ResetActionStatus); + } + else + { + var options = _sourceOptions; + var generation = _sourceGeneration; + var available = Current.ResetCredits?.AvailableCount; + ResetActionStatus = "Checking the existing reset attempt…"; + task = _resetActionTask = Task.Run(() => RunResetAsync(options, expectedAccountKey, available, generation)); + } + } + RaiseUpdated(); + return task; + } + + private async Task RunResetAsync(CodexSourceOptions options, string account, int? available, long generation) + { + string message; + if (!_resetJournal!.TryRead(account, out var key)) + message = "The pending reset record could not be read safely. No reset request was sent."; + else if (key is null && available is not > 0) + message = "No available earned reset is currently reported. No reset request was sent."; + else + { + key ??= Guid.NewGuid().ToString("N"); + if (!_resetJournal.Save(account, key)) + message = "The reset request ID could not be saved. No reset request was sent."; + else + { + ResetCreditResult result; + try + { + result = await _resetCreditConsumer!(options, account, key, _lifetimeCancellation.Token).ConfigureAwait(false); + } + catch (Exception error) + { + LocalStorage.TraceFailure("request earned reset", error); + result = new(ResetCreditOutcome.Ambiguous, _clock()); + } + message = DescribeResetOutcome(result.Outcome); + // Any unresolved attempt, including a retry whose preflight failed, keeps its original key. + if (result.Outcome is ResetCreditOutcome.Reset or ResetCreditOutcome.AlreadyRedeemed + or ResetCreditOutcome.NothingToReset or ResetCreditOutcome.NoCredit) + { + if (!_resetJournal.Save(account, null)) + message += " The recovery record could not be cleared; a retry will reuse the same request ID."; + } + await RefreshAsync().ConfigureAwait(false); + } + } + lock (_refreshStateLock) + { + if (!_disposed && generation == _sourceGeneration && Current.AccountKey == account) + ResetActionStatus = message; + } + RaiseUpdated(); + return message; + } + + internal static string DescribeResetOutcome(ResetCreditOutcome outcome) => outcome switch + { + ResetCreditOutcome.Reset => "An earned reset was applied. Usage limits have been requested again.", + ResetCreditOutcome.AlreadyRedeemed => "This request had already redeemed its reset. No second reset was used.", + ResetCreditOutcome.NothingToReset => "The service reports nothing to reset. No reset was applied.", + ResetCreditOutcome.NoCredit => "The service reports no eligible earned reset. No reset was applied.", + ResetCreditOutcome.Unsupported => "This Codex CLI does not support earned resets. The request ID is retained for a safe retry.", + ResetCreditOutcome.AccountMismatch => "The Codex account changed before the request. No reset was sent to the changed account.", + ResetCreditOutcome.Unavailable => "The service could not be checked before sending the reset. The request ID is retained.", + _ => "The reset outcome is unknown. Confirm a retry to reuse the same request ID, including after restarting the extension.", + }; + + private bool IsFreshAccount(string expectedAccountKey) => !string.IsNullOrWhiteSpace(expectedAccountKey) + && Current.AccountKey == expectedAccountKey && Current.Source == UsageDataSource.AppServer + && !_isLoading && UsageFreshness.IsFresh(Current.UpdatedAt, _clock(), RefreshInterval); + + internal Task ReadTaskUsageAsync(string threadId) + { + Task task; + lock (_refreshStateLock) + { + if (_disposed || _threadUsageReader is null || Current.AccountKey is not { } account || !IsFreshAccount(account)) + { + ThreadActionStatus = "Refresh a live, identified account before requesting task usage."; + CurrentThreadUsage = null; + task = Task.CompletedTask; + } + else if (!ThreadUsageParser.IsValidThreadId(threadId?.Trim())) + { + ThreadActionStatus = "Enter a task ID of at most 128 letters, digits, hyphens, or underscores."; + CurrentThreadUsage = null; + task = Task.CompletedTask; + } + else + { + _pendingTaskRead = new(_sourceOptions, threadId!.Trim(), account, _sourceGeneration, ++_taskRequestVersion); + ThreadActionStatus = "Reading the latest requested task estimate…"; + CurrentThreadUsage = null; + task = _threadActionTask is { IsCompleted: false } active ? active + : _threadActionTask = Task.Run(RunTaskReadsAsync); + } + } + RaiseUpdated(); + return task; + } + + private async Task RunTaskReadsAsync() + { + while (true) + { + PendingTaskRead request; + lock (_refreshStateLock) + { + if (_disposed || _pendingTaskRead is null) { _threadActionTask = null; return; } + request = _pendingTaskRead; + _pendingTaskRead = null; + } + ThreadUsageSnapshot? result = null; + try { result = await _threadUsageReader!(request.Options, request.ThreadId, request.Account, _lifetimeCancellation.Token).ConfigureAwait(false); } + catch (Exception error) { LocalStorage.TraceFailure("read task usage", error); } + lock (_refreshStateLock) + { + if (_disposed || request.SourceGeneration != _sourceGeneration || Current.AccountKey != request.Account + || request.RequestVersion != _taskRequestVersion) continue; + var usable = result?.AccountKey == request.Account && result.ThreadId == request.ThreadId + && result.Status is ThreadUsageStatus.Available or ThreadUsageStatus.Partial; + CurrentThreadUsage = usable ? result : null; + ThreadActionStatus = result?.Status switch + { + ThreadUsageStatus.Available when usable => "Task usage estimate reported by Codex.", + ThreadUsageStatus.Partial when usable => "Partial task estimate; missing values are not zero.", + ThreadUsageStatus.Unsupported => "This Codex CLI does not support task usage estimates.", + ThreadUsageStatus.AccountMismatch => "The account changed during the read. The result was discarded.", + _ => "Task usage is unavailable. Check the task ID and try again.", + }; + } + RaiseUpdated(); + } + } + + private void ClearActionPresentation() + { + CurrentThreadUsage = null; + _pendingTaskRead = null; + _taskRequestVersion++; + ThreadActionStatus = "Enter a Codex task ID to request its reported usage estimate."; + ResetActionStatus = "Only an explicit, confirmed action can use an existing earned reset."; + } +} diff --git a/CodexUsageDock/CodexUsageService.Aggregates.cs b/CodexUsageDock/CodexUsageService.Aggregates.cs new file mode 100644 index 0000000..22af2f8 --- /dev/null +++ b/CodexUsageDock/CodexUsageService.Aggregates.cs @@ -0,0 +1,68 @@ +namespace CodexUsageDock; + +internal sealed partial class CodexUsageService +{ + private string? _aggregatePath; + private UsageAggregateStore? _aggregateStore; + private int _aggregateRetentionDays; + + internal void SetAggregateRetentionDays(int days) + { + if (days is not (0 or 7 or 30 or 90)) throw new ArgumentOutOfRangeException(nameof(days)); + lock (_historyLock) + { + if (_aggregateRetentionDays == days) return; + _aggregateRetentionDays = days; + OpenAggregateStore(); + if (days != 0) _aggregateStore?.SetRetentionDays(days, _clock()); + } + RaiseUpdated(); + } + + private void OpenAggregateStore() => _aggregateStore = _aggregatePath is not null && _historyContext is not null + ? new UsageAggregateStore(LocalStorage.ContextPath(_aggregatePath, _historyContext), + _aggregateRetentionDays == 0 ? 90 : _aggregateRetentionDays, _clock) + : null; + + private void RecordAggregate(CodexUsageSnapshot snapshot, DateTimeOffset now) + { + if (_aggregateRetentionDays == 0 || _aggregateStore is null) return; + if (UsageAggregateStore.TryCreateLivePoint(snapshot, now, RefreshInterval, out var point)) + _aggregateStore.Record(point!, now); + } + + internal (IReadOnlyList Points, int RetentionDays, string? Error, bool Identified, string? Context) GetAggregateHistory() + { + lock (_historyLock) + { + return (_aggregateStore?.Snapshot ?? [], _aggregateRetentionDays, _aggregateStore?.StorageError, _historyContext is not null, _historyContext); + } + } + + internal bool ClearAggregateHistory(string? expectedContext = null) + { + bool cleared; + lock (_historyLock) + { + if (expectedContext is not null && expectedContext != _historyContext) return false; + cleared = _aggregateStore?.Clear() ?? _historyContext is not null; + } + RaiseUpdated(); + return cleared; + } + + internal string ExportAggregateHistory(bool csv, string? expectedContext = null) + { + lock (_historyLock) + { + if (expectedContext is not null && expectedContext != _historyContext) + return "The account or quota category changed. Open its history and request the export again."; + if (_aggregateStore is null || _aggregatePath is null) + return "Identify the current Codex account before exporting its history."; + var content = csv ? _aggregateStore.ExportCsv(_clock()) : _aggregateStore.ExportJson(_clock()); + var file = $"codex-usage-{_clock():yyyyMMdd-HHmmss}-{Guid.NewGuid():N}.{(csv ? "csv" : "json")}"; + var destination = Path.Combine(Path.GetDirectoryName(_aggregatePath)!, "exports", file); + return LocalStorage.TryWrite(destination, content) ? $"Export saved to {destination}" : "The export could not be saved."; + } + } +} diff --git a/CodexUsageDock/CodexUsageService.cs b/CodexUsageDock/CodexUsageService.cs index 2432fa0..46476ea 100644 --- a/CodexUsageDock/CodexUsageService.cs +++ b/CodexUsageDock/CodexUsageService.cs @@ -23,7 +23,12 @@ internal sealed partial class CodexUsageService : IDisposable private readonly Func _clock; private readonly Func> _appServerReader; private readonly Func _localSessionReader; - private readonly Func>? _localTokenUsageReader; + private Func>? _localTokenUsageReader; + private readonly bool _usesConfiguredSources; + private CachedCodexSessionReader? _configuredSessionReader; + private CodexSourceOptions _sourceOptions = CodexSourceOptions.Default; + private long _sourceGeneration; + private string? _sourceConfigurationError; private Task? _refreshTask; private Task? _tokenReadTask; private Task _tokenRefreshTask = Task.CompletedTask; @@ -42,6 +47,9 @@ public CodexUsageService() AdaptiveWeeklyUsageStore.CreateDefault(), localTokenUsageReader: new LocalCodexTokenUsageReader().ReadAsync) { + _usesConfiguredSources = true; + _configuredSessionReader = new CachedCodexSessionReader(); + InitializeOptionalFeatures(LocalStorage.GetPath("aggregates.json"), LocalStorage.GetPath("reset-attempt.json")); } internal CodexUsageService( @@ -50,12 +58,14 @@ internal CodexUsageService( WeeklyUsageHistoryStore weeklyHistoryStore, AdaptiveWeeklyUsageStore adaptiveWeeklyUsageStore, Func>? localTokenUsageReader = null, - Func? clock = null) + Func? clock = null, + Func>? accountUsageReader = null) { _appServerReader = appServerReader; _localSessionReader = localSessionReader; _localTokenUsageReader = localTokenUsageReader; _clock = clock ?? (() => DateTimeOffset.Now); + _accountUsageReader = accountUsageReader; _weeklyHistoryStore = _baseWeeklyHistoryStore = weeklyHistoryStore; _adaptiveWeeklyUsageStore = _baseAdaptiveWeeklyUsageStore = adaptiveWeeklyUsageStore; // Legacy files have no account identity. They must never seed a verified account. @@ -67,8 +77,9 @@ internal CodexUsageService( WeeklyUsageHistoryStore weeklyHistoryStore, AdaptiveWeeklyUsageStore adaptiveWeeklyUsageStore, Func>? localTokenUsageReader = null, - Func? clock = null) - : this(appServerReader, _ => localSessionReader(), weeklyHistoryStore, adaptiveWeeklyUsageStore, localTokenUsageReader, clock) + Func? clock = null, + Func>? accountUsageReader = null) + : this(appServerReader, _ => localSessionReader(), weeklyHistoryStore, adaptiveWeeklyUsageStore, localTokenUsageReader, clock, accountUsageReader) { } @@ -148,6 +159,39 @@ public AdaptiveWeeklyUsageHistory AdaptiveWeeklyHistory public event EventHandler? Updated; + internal bool ConfigureSource(CodexSourceOptions options, string? error = null) + { + lock (_refreshStateLock) + { + if (_sourceOptions == options && _sourceConfigurationError == error) return false; + _sourceOptions = options; + _sourceConfigurationError = error; + _sourceGeneration++; + _tokenGeneration++; + _lastConfirmed = null; + Current = CodexUsageSnapshot.Loading; + CurrentTokenUsage = LocalTokenUsageSnapshot.Unavailable; + CurrentAccountUsage = AccountUsageSnapshot.Unavailable; + ClearActionPresentation(); + _accountReadAfter = DateTimeOffset.MinValue; + if (_usesConfiguredSources) + { + _localTokenUsageReader = new LocalCodexTokenUsageReader(options.HomePath).ReadAsync; + _configuredSessionReader = new CachedCodexSessionReader(options.HomePath); + } + lock (_historyLock) + { + _memoryHistoryContext = null; + _historyContext = null; + _primaryHistory.Clear(); + _weeklyHistory.Clear(); + _aggregateStore = null; + } + } + RaiseUpdated(); + return true; + } + public void Start() { lock (_refreshStateLock) @@ -219,6 +263,8 @@ public Task RefreshAsync() { TaskCompletionSource completion; CancellationToken cancellationToken; + CodexSourceOptions options; + long generation; lock (_refreshStateLock) { if (_disposed) @@ -235,10 +281,12 @@ public Task RefreshAsync() completion = new(TaskCreationOptions.RunContinuationsAsynchronously); _refreshTask = completion.Task; cancellationToken = _lifetimeCancellation.Token; + options = _sourceOptions; + generation = _sourceGeneration; } RaiseUpdated(); - _ = ExecuteRefreshAsync(completion, cancellationToken); + _ = ExecuteRefreshAsync(completion, options, generation, cancellationToken); return completion.Task; } @@ -273,8 +321,11 @@ internal void RecordHistory(CodexUsageSnapshot snapshot, DateTimeOffset? recorde // A returning account may have been observed while learning was paused. // Resume at this measurement rather than replaying another context's gap. _adaptiveWeeklyForecastNeedsBaseline = _adaptiveWeeklyForecastEnabled; + OpenAggregateStore(); } + RecordAggregate(snapshot, now); + RecordWindowHistory(_primaryHistory, snapshot.Primary, snapshot.UpdatedAt, now, now - TimeSpan.FromHours(5)); var weeklyHistoryChanged = RecordWindowHistory(_weeklyHistory, snapshot.Secondary, snapshot.UpdatedAt, now, now - TimeSpan.FromDays(7)); if (weeklyHistoryChanged && context is not null) @@ -329,13 +380,13 @@ private static bool RecordWindowHistory( private TimeSpan GetAdaptiveMaximumGap() => UsageTrendHistory.MaximumGap(RefreshInterval); - private async Task ExecuteRefreshAsync(TaskCompletionSource completion, CancellationToken cancellationToken) + private async Task ExecuteRefreshAsync(TaskCompletionSource completion, CodexSourceOptions options, long generation, CancellationToken cancellationToken) { CodexUsageSnapshot? tokenSnapshot = null; try { - var snapshot = await ReadSnapshotAsync(cancellationToken).ConfigureAwait(false); - if (!cancellationToken.IsCancellationRequested && TryPublish(snapshot)) + var snapshot = await ReadSnapshotAsync(options, generation, cancellationToken).ConfigureAwait(false); + if (!cancellationToken.IsCancellationRequested && TryPublish(snapshot, generation)) { tokenSnapshot = snapshot; } @@ -346,8 +397,8 @@ private async Task ExecuteRefreshAsync(TaskCompletionSource completion, Cancella catch (Exception error) { TraceFailure("unexpected refresh", error); - var unavailable = _lastConfirmed is null ? CreateUnavailableSnapshot() : LastConfirmedSnapshot(_clock()); - _ = TryPublish(unavailable); + var unavailable = FailureSnapshot(_clock()); + _ = TryPublish(unavailable, generation); } finally { @@ -360,20 +411,37 @@ private async Task ExecuteRefreshAsync(TaskCompletionSource completion, Cancella if (tokenSnapshot is not null) { StartTokenRefresh(tokenSnapshot); + StartAccountUsageRefresh(tokenSnapshot); } completion.TrySetResult(); + if (generation != _sourceGeneration && !cancellationToken.IsCancellationRequested) + { + _ = RefreshAsync(); + } } } - private async Task ReadSnapshotAsync(CancellationToken cancellationToken) + private async Task ReadSnapshotAsync(CodexSourceOptions options, long generation, CancellationToken cancellationToken) { var attemptedAt = _clock(); + CachedCodexSessionReader? localCache; + lock (_refreshStateLock) + { + if (_sourceConfigurationError is not null || generation != _sourceGeneration) + return CreateUnavailableSnapshot() with { LastAttemptAt = attemptedAt }; + localCache = _configuredSessionReader; + } try { - var live = await _appServerReader(cancellationToken).ConfigureAwait(false); - if (live.Source == UsageDataSource.AppServer) + var live = await (_usesConfiguredSources + ? CodexAppServerReader.ReadAsync(options, cancellationToken) + : _appServerReader(cancellationToken)).ConfigureAwait(false); + lock (_refreshStateLock) { - _lastConfirmed = live; + if (live.Source == UsageDataSource.AppServer && generation == _sourceGeneration) + { + _lastConfirmed = live; + } } return live with { LastAttemptAt = attemptedAt }; } @@ -386,16 +454,24 @@ private async Task ReadSnapshotAsync(CancellationToken cance TraceFailure("live usage read", error); try { - var fallback = await Task.Run(() => _localSessionReader(cancellationToken), cancellationToken).ConfigureAwait(false); + var fallback = await Task.Run(() => _usesConfiguredSources + ? 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. if (_lastConfirmed is { } confirmed && (fallback.UpdatedAt <= confirmed.UpdatedAt || (confirmed.AccountKey is not null && fallback.AccountKey != confirmed.AccountKey))) { - return LastConfirmedSnapshot(attemptedAt); + 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) { @@ -404,14 +480,22 @@ private async Task ReadSnapshotAsync(CancellationToken cance catch (Exception fallbackError) { TraceFailure("local session fallback", fallbackError); - return _lastConfirmed is null - ? CreateUnavailableSnapshot() with { LastAttemptAt = attemptedAt } - : LastConfirmedSnapshot(attemptedAt); + return FailureSnapshot(attemptedAt); } } } - private CodexUsageSnapshot LastConfirmedSnapshot(DateTimeOffset attemptedAt) => _lastConfirmed! with + private CodexUsageSnapshot FailureSnapshot(DateTimeOffset attemptedAt) + { + lock (_refreshStateLock) + { + return _lastConfirmed is { } confirmed + ? LastConfirmedSnapshot(confirmed, attemptedAt) + : CreateUnavailableSnapshot() with { LastAttemptAt = attemptedAt }; + } + } + + private static CodexUsageSnapshot LastConfirmedSnapshot(CodexUsageSnapshot confirmed, DateTimeOffset attemptedAt) => confirmed with { Source = UsageDataSource.LastConfirmed, LastAttemptAt = attemptedAt, @@ -420,6 +504,7 @@ private CodexUsageSnapshot LastConfirmedSnapshot(DateTimeOffset attemptedAt) => private async Task ReadTokenUsageAsync( CodexUsageSnapshot snapshot, + Func> reader, CancellationToken cancellationToken) { if (snapshot.Secondary is not { WindowMinutes: > 0 } weekly) @@ -432,7 +517,7 @@ private async Task ReadTokenUsageAsync( var windowEnd = now < weekly.ResetsAt ? now : weekly.ResetsAt; try { - return await _localTokenUsageReader!(windowStart, windowEnd, TimeZoneInfo.Local, cancellationToken).ConfigureAwait(false); + return await reader(windowStart, windowEnd, TimeZoneInfo.Local, cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { @@ -449,7 +534,7 @@ private void StartTokenRefresh(CodexUsageSnapshot snapshot) { lock (_refreshStateLock) { - if (_disposed || _localTokenUsageReader is null || snapshot.Secondary is null + if (_disposed || !ReferenceEquals(Current, snapshot) || _localTokenUsageReader is null || snapshot.Secondary is null || snapshot.Source is UsageDataSource.LastConfirmed or UsageDataSource.Unavailable or UsageDataSource.Initializing || _tokenReadTask is { IsCompleted: false }) { @@ -461,7 +546,8 @@ private void StartTokenRefresh(CodexUsageSnapshot snapshot) // Keep the actual read task, even after a timeout, so a non-cooperative // file read cannot cause overlapping scans of the reader's mutable cache. var generation = _tokenGeneration; - var read = _tokenReadTask = Task.Run(() => ReadTokenUsageAsync(snapshot, cancellation.Token)); + var reader = _localTokenUsageReader; + var read = _tokenReadTask = Task.Run(() => ReadTokenUsageAsync(snapshot, reader, cancellation.Token)); // Notifications must run outside the state lock, even if the read finishes immediately. _tokenRefreshTask = Task.Run(() => ObserveTokenRefreshAsync(read, cancellation, generation)); } @@ -508,11 +594,11 @@ private async Task ObserveTokenRefreshAsync(Task read, } } - private bool TryPublish(CodexUsageSnapshot snapshot) + private bool TryPublish(CodexUsageSnapshot snapshot, long generation) { lock (_refreshStateLock) { - if (_disposed) + if (_disposed || generation != _sourceGeneration) { return false; } @@ -523,6 +609,12 @@ private bool TryPublish(CodexUsageSnapshot snapshot) || snapshot.Source == UsageDataSource.Unavailable) { CurrentTokenUsage = LocalTokenUsageSnapshot.Unavailable; + if (Current.AccountKey != snapshot.AccountKey) + { + ClearActionPresentation(); + CurrentAccountUsage = AccountUsageSnapshot.Unavailable; + _accountReadAfter = DateTimeOffset.MinValue; + } } Current = snapshot; @@ -590,7 +682,8 @@ public void Dispose() } _disposed = true; - refreshTask = Task.WhenAll(_refreshTask ?? Task.CompletedTask, _tokenRefreshTask); + refreshTask = Task.WhenAll(_refreshTask ?? Task.CompletedTask, _tokenRefreshTask, _accountRefreshTask, + (Task?)_resetActionTask ?? Task.CompletedTask, _threadActionTask ?? Task.CompletedTask); } _timer.Stop(); 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/CodexAccountActivityPage.cs b/CodexUsageDock/Pages/CodexAccountActivityPage.cs new file mode 100644 index 0000000..7473022 --- /dev/null +++ b/CodexUsageDock/Pages/CodexAccountActivityPage.cs @@ -0,0 +1,131 @@ +using System.Globalization; +using System.Text; +using Microsoft.CommandPalette.Extensions; +using Microsoft.CommandPalette.Extensions.Toolkit; + +namespace CodexUsageDock; + +internal sealed partial class CodexAccountActivityPage : ContentPage, IDisposable +{ + private readonly object _presentationLock = new(); + private readonly CodexUsageService _service; + private MarkdownContent _content = new(string.Empty); + private bool _disposed; + + internal CodexAccountActivityPage(CodexUsageService service) + { + _service = service; + Id = "nl.mathijs.codexusage.account-activity"; + Name = "Open"; + Title = "Codex account activity"; + Icon = new IconInfo("\uE9D9"); + _service.Updated += OnUpdated; + UpdatePresentation(); + } + + public override IContent[] GetContent() + { + lock (_presentationLock) + { + return [_content]; + } + } + + internal static string FormatActivity(AccountUsageSnapshot snapshot) + { + var body = new StringBuilder("# Codex account activity\n\n"); + if (snapshot.Status == AccountUsageStatus.Unsupported) + { + body.Append("This Codex CLI does not provide account activity. An update may add support.\n"); + return body.ToString(); + } + + if (snapshot.Status == AccountUsageStatus.Unavailable) + { + body.Append("Account activity is unavailable. Enable account activity in settings and refresh to request it. The account must remain identified throughout the read.\n"); + return body.ToString(); + } + + body.Append("Token totals reported by the Codex account service. These figures do not measure your remaining quota.\n\n"); + if (snapshot.Status == AccountUsageStatus.Partial) + { + body.Append("**Partial data:** some server information is missing, invalid, duplicated, or outside the retained history.\n\n"); + } + + body.Append("Last read: ").Append(snapshot.UpdatedAt.ToLocalTime().ToString("yyyy-MM-dd HH:mm zzz", CultureInfo.InvariantCulture)).Append(".\n\n"); + AppendSummary(body, "Lifetime tokens", snapshot.LifetimeTokens); + AppendSummary(body, "Peak daily tokens", snapshot.PeakDailyTokens); + AppendSummary(body, "Longest running turn (seconds)", snapshot.LongestRunningTurnSeconds); + AppendSummary(body, "Current streak (days)", snapshot.CurrentStreakDays); + AppendSummary(body, "Longest streak (days)", snapshot.LongestStreakDays); + + body.Append("\n## Daily activity\n\nDates are calendar dates supplied by the server. Their time zone is not specified. Up to 30 recent reported days are shown.\n\n"); + if (snapshot.Days.Count == 0) + { + body.Append("No readable daily rows were returned. Missing days are not treated as zero usage.\n"); + return body.ToString(); + } + + body.Append("| Server date | Tokens |\n| --- | ---: |\n"); + foreach (var day in snapshot.Days.OrderByDescending(day => day.Date).Take(30)) + { + 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 AppendSummary(StringBuilder body, string label, long? value) => + body.Append("- **").Append(label).Append(":** ") + .Append(value?.ToString("N0", CultureInfo.InvariantCulture) ?? "Not reported").Append('\n'); + + private void UpdatePresentation() + { + var body = FormatActivity(_service.CurrentAccountUsage); + lock (_presentationLock) + { + if (_disposed) + { + return; + } + + _content = new MarkdownContent(body); + Commands = + [ + new CommandContextItem(new RefreshUsageCommand(_service, refreshAccountActivity: true)) { Title = "Refresh now" }, + new CommandContextItem(new CopyTextCommand(body)) { Title = "Copy activity summary" }, + ]; + } + } + + private void OnUpdated(object? sender, EventArgs e) + { + UpdatePresentation(); + lock (_presentationLock) + { + if (_disposed) + { + return; + } + } + + RaiseItemsChanged(0); + } + + public void Dispose() + { + lock (_presentationLock) + { + if (_disposed) + { + return; + } + + _disposed = true; + _service.Updated -= OnUpdated; + } + + GC.SuppressFinalize(this); + } +} diff --git a/CodexUsageDock/Pages/CodexActionsPage.cs b/CodexUsageDock/Pages/CodexActionsPage.cs new file mode 100644 index 0000000..a5ec9ad --- /dev/null +++ b/CodexUsageDock/Pages/CodexActionsPage.cs @@ -0,0 +1,111 @@ +using System.Globalization; +using System.Text; +using System.Text.Json; +using Microsoft.CommandPalette.Extensions; +using Microsoft.CommandPalette.Extensions.Toolkit; +using Microsoft.CmdPal.Common.Commands; + +namespace CodexUsageDock; + +internal sealed partial class CodexActionsPage : ContentPage, IDisposable +{ + private readonly CodexUsageService _service; + private readonly TaskUsageForm _form; + private readonly object _gate = new(); + private MarkdownContent _content = new(string.Empty); + private bool _disposed; + + internal CodexActionsPage(CodexUsageService service) + { + _service = service; + _form = new TaskUsageForm(service); + Id = "nl.mathijs.codexusage.actions"; + Name = "Open"; + Title = "Codex task usage and earned resets"; + Icon = new IconInfo("\uE945"); + service.Updated += OnUpdated; + Refresh(); + } + + public override IContent[] GetContent() { lock (_gate) { return [_form, _content]; } } + + private void Refresh() + { + 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(); + } + RaiseItemsChanged(0); + } + + internal static string FormatTask(ThreadUsageSnapshot task) + { + if (task.Status is not (ThreadUsageStatus.Available or ThreadUsageStatus.Partial)) return string.Empty; + var body = new StringBuilder("Task: ").Append(UsageText.EscapeMarkdown(task.ThreadId ?? "Unknown")) + .Append(".\n\n**Server estimate, not a bill or quota percentage.** Last read: ") + .Append(task.UpdatedAt.ToString("yyyy-MM-dd HH:mm zzz", CultureInfo.InvariantCulture)).Append(".\n\n") + .Append("Estimated credits: ").Append(Micro(task.EstimatedUsageCreditsMicros)) + .Append("; estimated USD: ").Append(Micro(task.EstimatedUsageUsdMicros)).Append(".\n\n") + .Append("| Model / effort / speed | Input | Cached input | Net new input | Output | Total | Estimated credits |\n") + .Append("| --- | ---: | ---: | ---: | ---: | ---: | ---: |\n"); + foreach (var group in task.Groups ?? []) + body.Append("| ").Append(UsageText.EscapeMarkdown(string.Join(" / ", group.Model ?? "Unknown model", group.ReasoningEffort ?? "Unknown effort", group.Speed ?? "Unknown speed"))) + .Append(" | ").Append(Tokens(group.InputTokens)).Append(" | ").Append(Tokens(group.CachedInputTokens)) + .Append(" | ").Append(Tokens(group.NetNewInputTokens)).Append(" | ").Append(Tokens(group.OutputTokens)) + .Append(" | ").Append(Tokens(group.TotalTokens)).Append(" | ").Append(Micro(group.EstimatedUsageCreditsMicros)).Append(" |\n"); + return body.Append("\nCached and net-new input are components of input; do not add them to input again. Missing values are not zero.\n").ToString(); + } + + private static string Micro(long? value) => value is { } amount ? (amount / 1_000_000m).ToString("0.######", CultureInfo.InvariantCulture) : "Not reported"; + private static string Tokens(long? value) => value?.ToString("N0", CultureInfo.InvariantCulture) ?? "Not reported"; + private void OnUpdated(object? sender, EventArgs args) => Refresh(); + public void Dispose() { lock (_gate) { _disposed = true; _service.Updated -= OnUpdated; } } +} + +internal sealed partial class TaskUsageForm : FormContent +{ + private readonly CodexUsageService _service; + internal TaskUsageForm(CodexUsageService service) + { + _service = service; + TemplateJson = """ + {"type":"AdaptiveCard","version":"1.5","body":[{"type":"Input.Text","id":"threadId","label":"Codex task ID","placeholder":"Paste the task ID","maxLength":128,"isRequired":true}],"actions":[{"type":"Action.Submit","title":"Read task estimate"}]} + """; + } + + public override CommandResult SubmitForm(string payload) + { + try + { + if (string.IsNullOrEmpty(payload) || payload.Length > 4096) return CommandResult.KeepOpen(); + using var doc = JsonDocument.Parse(payload, new JsonDocumentOptions { MaxDepth = 8 }); + if (doc.RootElement.ValueKind == JsonValueKind.Object && doc.RootElement.TryGetProperty("threadId", out var id) + && id.ValueKind == JsonValueKind.String) _ = _service.ReadTaskUsageAsync(id.GetString()!); + } + catch (JsonException) { } + return CommandResult.KeepOpen(); + } +} diff --git a/CodexUsageDock/Pages/CodexHistoryPage.cs b/CodexUsageDock/Pages/CodexHistoryPage.cs new file mode 100644 index 0000000..122d179 --- /dev/null +++ b/CodexUsageDock/Pages/CodexHistoryPage.cs @@ -0,0 +1,68 @@ +using System.Globalization; +using System.Text; +using Microsoft.CommandPalette.Extensions; +using Microsoft.CommandPalette.Extensions.Toolkit; +using Microsoft.CmdPal.Common.Commands; + +namespace CodexUsageDock; + +internal sealed partial class CodexHistoryPage : ContentPage, IDisposable +{ + private readonly CodexUsageService _service; + private readonly object _gate = new(); + private MarkdownContent _content = new(string.Empty); + private string? _operation; + private bool _disposed; + + internal CodexHistoryPage(CodexUsageService service) + { + _service = service; + Id = "nl.mathijs.codexusage.history"; + Name = "Open"; + Title = "Codex usage history"; + Icon = new IconInfo("\uE81C"); + service.Updated += OnUpdated; + Refresh(); + } + + public override IContent[] GetContent() { lock (_gate) { return [_content]; } } + + private void Export(bool csv, string context) { _operation = _service.ExportAggregateHistory(csv, context); Refresh(); } + private void Clear(string context) { _operation = _service.ClearAggregateHistory(context) ? "Retained observations deleted." : "Retained observations could not be deleted, or the account/category changed."; Refresh(); } + + internal void Refresh() + { + 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 ? [] : + [ + new CommandContextItem(new AnonymousCommand(() => Export(true, context)) { Result = CommandResult.KeepOpen() }) { Title = "Export CSV file" }, + new CommandContextItem(new AnonymousCommand(() => Export(false, context)) { Result = CommandResult.KeepOpen() }) { Title = "Export JSON file" }, + new CommandContextItem(new ConfirmableCommand(new AnonymousCommand(() => Clear(context)) { Result = CommandResult.KeepOpen() }, + "Delete retained usage observations?", "Delete this account and quota category's retained observations. Existing exports and learned forecasts are kept.", () => true) + { Name = "Delete retained observations" }) { Title = "Delete retained observations" }, + ]; + } + RaiseItemsChanged(0); + } + + private static string Percent(double? value) => value?.ToString("0.#", CultureInfo.InvariantCulture) is { } text ? text + "%" : "Not reported"; + 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 7db332a..6a0f6e7 100644 --- a/CodexUsageDock/Pages/CodexUsageDockSettingsPage.cs +++ b/CodexUsageDock/Pages/CodexUsageDockSettingsPage.cs @@ -14,6 +14,11 @@ internal sealed partial class CodexUsageDockSettingsPage : ContentPage private const string ShowResetTimeKey = "showResetTime"; private const string RefreshIntervalKey = "refreshInterval"; private const string UseAdaptiveWeeklyForecastKey = "useAdaptiveWeeklyForecast"; + private const string EnableUsageAlertsKey = "enableUsageAlerts"; + private const string CompactDockKey = "compactDock"; + private const string SeparateDockItemsKey = "separateDockItems"; + private const string ShowAccountActivityKey = "showAccountActivity"; + private const string HistoryRetentionKey = "historyRetentionDays"; private readonly Settings _settings = new(); private readonly string _path; private readonly FormContent _statusContent = new() @@ -60,6 +65,26 @@ internal CodexUsageDockSettingsPage(string path) Label = "Use adaptive weekly forecast", Description = "Blend the current pace with up to eight local weekly cycles. Turning this off pauses learning and keeps saved history.", }); + _settings.Add(new ToggleSetting(EnableUsageAlertsKey, false) + { + Label = "Enable usage alerts", + Description = "Show a quiet notification when the usage status changes.", + }); + _settings.Add(new ToggleSetting(CompactDockKey, false) + { + Label = "Compact Dock", + Description = "Use shorter usage labels and hide reset times in the Dock.", + }); + _settings.Add(new ToggleSetting(SeparateDockItemsKey, false) + { + Label = "Separate Dock items", + 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 ChoiceSetSetting( RefreshIntervalKey, [ @@ -71,6 +96,12 @@ internal CodexUsageDockSettingsPage(string path) Label = "Refresh interval", Description = "How often the extension refreshes local Codex usage data.", }); + _settings.Add(new ChoiceSetSetting(HistoryRetentionKey, + [new("Collection paused", "0"), new("7 days", "7"), new("30 days", "30"), new("90 days", "90")]) + { + Label = "Retain usage observations", + Description = "Optional local quota history for export. Pausing keeps saved data; use History to delete it.", + }); var clearHistory = new ConfirmableCommand( new AnonymousCommand(() => ClearAdaptiveHistoryRequested?.Invoke(this, EventArgs.Empty)) { @@ -107,8 +138,19 @@ internal CodexUsageDockSettingsPage(string path) public bool UseAdaptiveWeeklyForecast => _settings.GetSetting(UseAdaptiveWeeklyForecastKey); + public bool EnableUsageAlerts => _settings.GetSetting(EnableUsageAlertsKey); + + public bool CompactDock => _settings.GetSetting(CompactDockKey); + + public bool SeparateDockItems => _settings.GetSetting(SeparateDockItemsKey); + + public bool ShowAccountActivity => _settings.GetSetting(ShowAccountActivityKey); + public TimeSpan RefreshInterval => ParseRefreshInterval(_settings.GetSetting(RefreshIntervalKey)); + internal int HistoryRetentionDays => _settings.GetSetting(HistoryRetentionKey) switch + { "7" => 7, "30" => 30, "90" => 90, _ => 0 }; + internal string? StatusMessage { get; private set; } public override IContent[] GetContent() => StatusMessage is null @@ -147,6 +189,13 @@ private void Load() var valid = new JsonObject(); foreach (var property in document.RootElement.EnumerateObject()) { + if (property.Value.ValueKind is JsonValueKind.True or JsonValueKind.False + && IsBooleanSetting(property.Name)) + { + valid[property.Name] = property.Value.GetBoolean() ? "true" : "false"; + continue; + } + if (property.Value.ValueKind != JsonValueKind.String) { continue; @@ -157,8 +206,11 @@ private void Load() { valid[property.Name] = value; } - else if (property.Name is ShowFiveHourLimitKey or ShowWeeklyLimitKey or ShowResetsAndCreditsKey or ShowResetTimeKey or UseAdaptiveWeeklyForecastKey - && bool.TryParse(value, out var enabled)) + else if (property.Name == HistoryRetentionKey && value is "0" or "7" or "30" or "90") + { + valid[property.Name] = value; + } + else if (IsBooleanSetting(property.Name) && bool.TryParse(value, out var enabled)) { valid[property.Name] = enabled ? "true" : "false"; } @@ -173,6 +225,11 @@ private void Load() } } + private static bool IsBooleanSetting(string name) => name is + ShowFiveHourLimitKey or ShowWeeklyLimitKey or ShowResetsAndCreditsKey or ShowResetTimeKey or + UseAdaptiveWeeklyForecastKey or EnableUsageAlertsKey or CompactDockKey or SeparateDockItemsKey or + ShowAccountActivityKey; + 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/RefreshUsageCommand.cs b/CodexUsageDock/RefreshUsageCommand.cs index 867c71f..ec7bde1 100644 --- a/CodexUsageDock/RefreshUsageCommand.cs +++ b/CodexUsageDock/RefreshUsageCommand.cs @@ -3,12 +3,13 @@ namespace CodexUsageDock; -internal sealed partial class RefreshUsageCommand(CodexUsageService usage) : InvokableCommand +internal sealed partial class RefreshUsageCommand(CodexUsageService usage, bool refreshAccountActivity = false) : InvokableCommand { public override string Name => "Refresh Codex usage"; public override ICommandResult Invoke() { + if (refreshAccountActivity) usage.RequestAccountUsageRefresh(); _ = usage.RefreshAsync(); return CommandResult.KeepOpen(); } diff --git a/CodexUsageDock/ResetAttemptJournal.cs b/CodexUsageDock/ResetAttemptJournal.cs new file mode 100644 index 0000000..e983c97 --- /dev/null +++ b/CodexUsageDock/ResetAttemptJournal.cs @@ -0,0 +1,36 @@ +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace CodexUsageDock; + +// Persist before sending a mutation so a lost response or restart cannot create a second redemption. +internal sealed class ResetAttemptJournal(string path) +{ + internal bool TryRead(string accountKey, out string? key) + { + key = null; + try + { + var scoped = LocalStorage.ContextPath(path, accountKey); + if (!File.Exists(scoped)) return true; + if (new FileInfo(scoped).Length > 4096) return false; + using var document = JsonDocument.Parse(File.ReadAllText(scoped), new JsonDocumentOptions { MaxDepth = 4 }); + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object + || !root.TryGetProperty("schemaVersion", out var version) || !version.TryGetInt32(out var value) || value != 1 + || !root.TryGetProperty("pendingKey", out var pending)) return false; + if (pending.ValueKind == JsonValueKind.Null) return true; + if (pending.ValueKind != JsonValueKind.String || !Guid.TryParseExact(pending.GetString(), "N", out _)) return false; + key = pending.GetString(); + return true; + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException or JsonException or InvalidOperationException) + { + LocalStorage.TraceFailure("read pending reset", error); + return false; + } + } + + internal bool Save(string accountKey, string? key) => LocalStorage.TryWrite( + LocalStorage.ContextPath(path, accountKey), new JsonObject { ["schemaVersion"] = 1, ["pendingKey"] = key }.ToJsonString()); +} diff --git a/CodexUsageDock/ResetCreditData.cs b/CodexUsageDock/ResetCreditData.cs new file mode 100644 index 0000000..42cbb24 --- /dev/null +++ b/CodexUsageDock/ResetCreditData.cs @@ -0,0 +1,49 @@ +using System.Text.Json; + +namespace CodexUsageDock; + +internal enum ResetCreditOutcome +{ + Reset, + AlreadyRedeemed, + NothingToReset, + NoCredit, + Unsupported, + AccountMismatch, + // The consume request was not started; no credit could have been consumed. + Unavailable, + // A retry must use the original idempotency key. + Ambiguous, +} + +internal sealed record ResetCreditResult(ResetCreditOutcome Outcome, DateTimeOffset AttemptedAt); + +internal static class ResetCreditParser +{ + internal static bool IsValidIdempotencyKey(string? value) => value is { Length: > 0 and <= 128 } + && value.All(character => char.IsAsciiLetterOrDigit(character) || character is '-' or '_'); + + internal static ResetCreditResult Parse(JsonElement response, DateTimeOffset attemptedAt) + { + if (response.ValueKind == JsonValueKind.Object && response.TryGetProperty("error", out _) + && response.TryGetProperty("result", out _)) return new(ResetCreditOutcome.Ambiguous, attemptedAt); + if (CodexAppServerReader.IsMethodNotFound(response)) return new(ResetCreditOutcome.Unsupported, attemptedAt); + if (response.ValueKind != JsonValueKind.Object + || response.TryGetProperty("error", out _) + || !response.TryGetProperty("result", out var result) || result.ValueKind != JsonValueKind.Object + || !result.TryGetProperty("outcome", out var value) || value.ValueKind != JsonValueKind.String) + { + return new(ResetCreditOutcome.Ambiguous, attemptedAt); + } + + var outcome = value.GetString() switch + { + "reset" => ResetCreditOutcome.Reset, + "alreadyRedeemed" => ResetCreditOutcome.AlreadyRedeemed, + "nothingToReset" => ResetCreditOutcome.NothingToReset, + "noCredit" => ResetCreditOutcome.NoCredit, + _ => ResetCreditOutcome.Ambiguous, + }; + return new(outcome, attemptedAt); + } +} diff --git a/CodexUsageDock/TaskUsageData.cs b/CodexUsageDock/TaskUsageData.cs new file mode 100644 index 0000000..eca9865 --- /dev/null +++ b/CodexUsageDock/TaskUsageData.cs @@ -0,0 +1,130 @@ +using System.Text.Json; + +namespace CodexUsageDock; + +internal enum ThreadUsageStatus +{ + Available, + Partial, + Unsupported, + Unavailable, + AccountMismatch, +} + +internal sealed record ThreadUsageGroup( + string? Model, + string? ReasoningEffort, + string? Speed, + long? EstimatedUsageCreditsMicros, + long? NetNewInputTokens, + long? CachedInputTokens, + long? InputTokens, + long? OutputTokens, + long? TotalTokens); + +internal sealed record ThreadUsageSnapshot( + string? ThreadId, + string? AccountKey, + DateTimeOffset UpdatedAt, + ThreadUsageStatus Status, + long? EstimatedUsageCreditsMicros = null, + long? EstimatedUsageUsdMicros = null, + IReadOnlyList? Groups = null) +{ + internal static ThreadUsageSnapshot Unavailable { get; } = new(null, null, DateTimeOffset.MinValue, ThreadUsageStatus.Unavailable); +} + +internal static class ThreadUsageParser +{ + internal const int MaximumGroups = 64; + + internal static bool IsValidThreadId(string? value) => value is { Length: > 0 and <= 128 } + && value.All(character => char.IsAsciiLetterOrDigit(character) || character is '-' or '_'); + + internal static ThreadUsageSnapshot Parse(JsonElement result, string expectedThreadId, string accountKey, DateTimeOffset now) + { + if (!IsValidThreadId(expectedThreadId) || string.IsNullOrWhiteSpace(accountKey) || result.ValueKind != JsonValueKind.Object + || !result.TryGetProperty("threadUsage", out var usage) || usage.ValueKind != JsonValueKind.Object + || !usage.TryGetProperty("threadId", out var thread) || thread.ValueKind != JsonValueKind.String + || !string.Equals(thread.GetString(), expectedThreadId, StringComparison.Ordinal)) + { + return ThreadUsageSnapshot.Unavailable with { UpdatedAt = now }; + } + + var partial = false; + var credits = ReadNonnegative(usage, "estimatedUsageCreditsMicros", ref partial); + var usd = ReadNonnegative(usage, "estimatedUsageUsdMicros", ref partial); + var groups = new List(); + if (usage.TryGetProperty("groups", out var groupValues) && groupValues.ValueKind == JsonValueKind.Array) + { + var count = 0; + foreach (var group in groupValues.EnumerateArray()) + { + if (++count > MaximumGroups) + { + partial = true; + break; + } + if (group.ValueKind != JsonValueKind.Object) + { + partial = true; + continue; + } + + var parsed = new ThreadUsageGroup( + ReadLabel(group, "model", 80, ref partial), + ReadLabel(group, "reasoningEffort", 32, ref partial), + ReadLabel(group, "speed", 32, ref partial), + ReadNonnegative(group, "estimatedUsageCreditsMicros", ref partial), + ReadNonnegative(group, "netNewInputTokens", ref partial), + ReadNonnegative(group, "cachedInputTokens", ref partial), + ReadNonnegative(group, "inputTokens", ref partial), + ReadNonnegative(group, "outputTokens", ref partial), + ReadNonnegative(group, "totalTokens", ref partial)); + if (parsed is { Model: null, ReasoningEffort: null, Speed: null, EstimatedUsageCreditsMicros: null, + NetNewInputTokens: null, CachedInputTokens: null, InputTokens: null, OutputTokens: null, TotalTokens: null }) + { + partial = true; + continue; + } + + groups.Add(parsed); + } + } + else + { + partial = true; + } + + if (credits is null && usd is null && groups.Count == 0) + { + return ThreadUsageSnapshot.Unavailable with { UpdatedAt = now }; + } + + return new(expectedThreadId, accountKey, now, partial ? ThreadUsageStatus.Partial : ThreadUsageStatus.Available, + credits, usd, groups.ToArray()); + } + + private static string? ReadLabel(JsonElement element, string name, int maximumLength, ref bool partial) + { + if (!element.TryGetProperty(name, out var value) || value.ValueKind == JsonValueKind.Null) return null; + if (value.ValueKind == JsonValueKind.String) + { + var original = value.GetString(); + var safe = UsageText.SanitizeExternal(original, maximumLength); + if (!string.Equals(original, safe, StringComparison.Ordinal)) partial = true; + return safe; + } + + partial = true; + return null; + } + + private static long? ReadNonnegative(JsonElement element, string name, ref bool partial) + { + if (!element.TryGetProperty(name, out var value) || value.ValueKind == JsonValueKind.Null) return null; + if (value.ValueKind == JsonValueKind.Number && value.TryGetInt64(out var number) && number >= 0) return number; + partial = true; + return null; + } +} diff --git a/CodexUsageDock/UsageAggregateStore.cs b/CodexUsageDock/UsageAggregateStore.cs new file mode 100644 index 0000000..d385d01 --- /dev/null +++ b/CodexUsageDock/UsageAggregateStore.cs @@ -0,0 +1,624 @@ +using System.Globalization; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace CodexUsageDock; + +internal sealed record UsageAggregatePoint( + DateTimeOffset RecordedAt, + double? PrimaryRemainingPercent, + double? WeeklyRemainingPercent, + DateTimeOffset? PrimaryResetsAt, + DateTimeOffset? WeeklyResetsAt, + UsageDataSource Source); + +internal sealed record UsageAggregateStoreDocument( + int SchemaVersion, + int RetentionDays, + UsageAggregatePoint?[]? Observations); + +internal sealed class UsageAggregateStore +{ + internal const int SchemaVersion = 1; + internal const int MaximumEntries = 27_000; + internal const int DefaultRetentionDays = 30; + internal const int MaximumDocumentBytes = 16 * 1024 * 1024; + + private static readonly TimeSpan ObservationBucket = TimeSpan.FromMinutes(5); + private const string FileName = "usage-aggregates.json"; + private const string LoadErrorMessage = "Saved usage observations could not be read. A new history will be collected."; + private const string SaveErrorMessage = "Usage observations could not be saved. They may be lost after restarting."; + private const string InvalidObservationMessage = "The usage observation was invalid and was not saved."; + private const string InvalidRetentionMessage = "Retention must be 7, 30, or 90 days."; + private const string ClearErrorMessage = "Usage observations could not be cleared."; + private const string ExportCaveat = "Local quota observations only; no tokens, costs, account identifiers, or session content."; + private readonly object _gate = new(); + private readonly string _path; + private readonly Func _clock; + private List _observations; + private int _retentionDays; + private string? _storageError; + + internal UsageAggregateStore( + string path, + int retentionDays = DefaultRetentionDays, + Func? clock = null) + { + _path = Path.GetFullPath(path); + _retentionDays = NormalizeRetentionDays(retentionDays); + _clock = clock ?? (() => DateTimeOffset.UtcNow); + _observations = Load(); + } + + internal static UsageAggregateStore CreateDefault() => new(LocalStorage.GetPath(FileName)); + + internal UsageAggregateStore ForContext(string context) => + new(LocalStorage.ContextPath(_path, context), _retentionDays, _clock); + + internal int RetentionDays + { + get + { + lock (_gate) + { + return _retentionDays; + } + } + } + + internal string? StorageError + { + get + { + lock (_gate) + { + return _storageError; + } + } + } + + internal IReadOnlyList Snapshot + { + get + { + lock (_gate) + { + return _observations.ToArray(); + } + } + } + + internal IReadOnlyList Read(DateTimeOffset now) + { + lock (_gate) + { + if (!TryNormalizeNow(now, out var normalizedNow)) + { + return _observations.ToArray(); + } + + var normalized = Normalize(_observations, normalizedNow, _retentionDays, out var changed); + if (changed) + { + var previous = _observations; + if (TrySave(normalized, out _)) + { + _observations = normalized; + } + else + { + _observations = previous; + } + } + + return _observations.ToArray(); + } + } + + internal bool SetRetentionDays(int retentionDays, DateTimeOffset now) => + SetRetentionDays(retentionDays, now, out _); + + internal bool SetRetentionDays(int retentionDays, DateTimeOffset now, out string? error) + { + error = null; + if (!TryGetSupportedRetention(retentionDays, out var normalizedRetention)) + { + error = InvalidRetentionMessage; + SetStorageError(error); + return false; + } + + if (!TryNormalizeNow(now, out var normalizedNow)) + { + error = InvalidObservationMessage; + SetStorageError(error); + return false; + } + + lock (_gate) + { + var previousRetention = _retentionDays; + var previousObservations = _observations; + _retentionDays = normalizedRetention; + var normalized = Normalize(_observations, normalizedNow, _retentionDays, out _); + if (!TrySave(normalized, out error)) + { + _retentionDays = previousRetention; + _observations = previousObservations; + return false; + } + + _observations = normalized; + return true; + } + } + + internal bool Record(UsageAggregatePoint point) => + Record(point, _clock(), out _); + + internal bool Record(UsageAggregatePoint point, out string? error) => + Record(point, _clock(), out error); + + internal bool Record(UsageAggregatePoint point, DateTimeOffset now) => + Record(point, now, out _); + + internal bool Record(UsageAggregatePoint point, DateTimeOffset now, out string? error) + { + error = null; + if (!TryNormalizeNow(now, out var normalizedNow) + || !TryNormalizePoint(point, normalizedNow, out var normalizedPoint)) + { + error = InvalidObservationMessage; + SetStorageError(error); + return false; + } + + lock (_gate) + { + var previous = _observations; + var updated = new List(previous); + var key = GetObservationKey(normalizedPoint); + var existingIndex = FindLastIndex(updated, key); + if (existingIndex >= 0) + { + if (updated[existingIndex].RecordedAt > normalizedPoint.RecordedAt) + { + return true; + } + + updated[existingIndex] = normalizedPoint; + } + else + { + updated.Add(normalizedPoint); + } + + updated = Normalize(updated, normalizedNow, _retentionDays, out _); + if (!TrySave(updated, out error)) + { + _observations = previous; + return false; + } + + _observations = updated; + return true; + } + } + + internal bool Clear() => Clear(out _); + + internal bool Clear(out string? error) + { + error = null; + lock (_gate) + { + var previous = _observations; + if (!TrySave([], out error)) + { + _observations = previous; + error ??= ClearErrorMessage; + return false; + } + + _observations = []; + return true; + } + } + + internal string ExportJson() => ExportJson(_clock()); + + internal string ExportJson(DateTimeOffset now) + { + var observations = Read(now); + var output = new StringBuilder(Math.Min(1_000_000, observations.Count * 180 + 512)); + output.Append("{\n"); + output.Append(" \"schemaVersion\": 1,\n"); + output.Append(" \"units\": {\n"); + output.Append(" \"timestamps\": \"UTC ISO 8601\",\n"); + output.Append(" \"remainingPercent\": \"percent (0-100)\"\n"); + output.Append(" },\n"); + output.Append(" \"caveat\": ").Append(Quote(ExportCaveat)).Append(",\n"); + output.Append(" \"observations\": ["); + for (var index = 0; index < observations.Count; index++) + { + if (index == 0) + { + output.Append('\n'); + } + else + { + output.Append(",\n"); + } + + AppendJsonObservation(output, observations[index]); + } + + if (observations.Count > 0) + { + output.Append('\n'); + } + + output.Append(" ]\n"); + output.Append('}'); + return output.ToString(); + } + + internal string ExportCsv() => ExportCsv(_clock()); + + internal string ExportCsv(DateTimeOffset now) + { + var observations = Read(now); + var output = new StringBuilder(Math.Min(1_000_000, observations.Count * 160 + 512)); + output.Append("# schemaVersion=1\n"); + output.Append("# units=recordedAtUtc and reset timestamps are UTC ISO 8601; remainingPercent fields are percent from 0 to 100\n"); + output.Append("# caveat=Local quota observations only; no tokens, costs, account identifiers, or session content\n"); + output.Append("recordedAtUtc,primaryRemainingPercent,weeklyRemainingPercent,primaryResetsAtUtc,weeklyResetsAtUtc,source\n"); + foreach (var observation in observations) + { + output.Append(FormatUtc(observation.RecordedAt)).Append(','); + AppendCsvNumber(output, observation.PrimaryRemainingPercent).Append(','); + AppendCsvNumber(output, observation.WeeklyRemainingPercent).Append(','); + AppendCsvTimestamp(output, observation.PrimaryResetsAt).Append(','); + AppendCsvTimestamp(output, observation.WeeklyResetsAt).Append(','); + output.Append(observation.Source.ToString()).Append('\n'); + } + + return output.ToString(); + } + + internal static bool TryCreateLivePoint( + CodexUsageSnapshot? snapshot, + DateTimeOffset now, + TimeSpan refreshInterval, + out UsageAggregatePoint? point) + { + point = null; + if (snapshot is null + || snapshot.Source != UsageDataSource.AppServer + || string.IsNullOrWhiteSpace(snapshot.AccountKey) + || !TryNormalizeNow(now, out var normalizedNow) + || snapshot.UpdatedAt > normalizedNow + || !UsageFreshness.IsFresh(snapshot.UpdatedAt, normalizedNow, refreshInterval)) + { + return false; + } + + var primary = TryGetWindowValues(snapshot.Primary, normalizedNow); + var weekly = TryGetWindowValues(snapshot.Secondary, normalizedNow); + if (primary is null && weekly is null) + { + return false; + } + + point = new UsageAggregatePoint( + snapshot.UpdatedAt.ToUniversalTime(), + primary?.RemainingPercent, + weekly?.RemainingPercent, + primary?.ResetsAt, + weekly?.ResetsAt, + UsageDataSource.AppServer); + return true; + } + + private List Load() + { + try + { + if (!File.Exists(_path)) + { + return []; + } + + var fileInfo = new FileInfo(_path); + if (fileInfo.Length > MaximumDocumentBytes) + { + SetStorageError(LoadErrorMessage); + return []; + } + + var document = JsonSerializer.Deserialize( + File.ReadAllText(_path), + UsageAggregateStoreJsonContext.Default.UsageAggregateStoreDocument); + if (document is null + || document.SchemaVersion != SchemaVersion + || document.Observations is null + || !TryNormalizeNow(_clock(), out var now)) + { + SetStorageError(LoadErrorMessage); + return []; + } + + var normalized = Normalize(document.Observations, now, _retentionDays, out var changed); + if (changed) + { + _ = TrySave(normalized, out _); + } + + return normalized; + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException or JsonException or NotSupportedException or InvalidOperationException) + { + LocalStorage.TraceFailure("load usage observations", error); + SetStorageError(LoadErrorMessage); + return []; + } + } + + private bool TrySave(IReadOnlyList observations, out string? error) + { + error = null; + try + { + var document = new UsageAggregateStoreDocument( + SchemaVersion, + _retentionDays, + observations.ToArray()); + var json = JsonSerializer.Serialize( + document, + UsageAggregateStoreJsonContext.Default.UsageAggregateStoreDocument); + if (!LocalStorage.TryWrite(_path, json)) + { + error = SaveErrorMessage; + SetStorageError(error); + return false; + } + + SetStorageError(null); + return true; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException or NotSupportedException or InvalidOperationException or ArgumentException) + { + LocalStorage.TraceFailure("save usage observations", exception); + error = SaveErrorMessage; + SetStorageError(error); + return false; + } + } + + private static List Normalize( + IEnumerable observations, + DateTimeOffset now, + int retentionDays, + out bool changed) + { + var original = observations.ToArray(); + var accepted = new List(); + foreach (var observation in original) + { + if (observation is null || !TryNormalizePoint(observation, now, out var normalized)) + { + continue; + } + + if (!IsWithinRetention(normalized.RecordedAt, now, retentionDays)) + { + continue; + } + + accepted.Add(normalized); + } + + accepted.Sort(static (left, right) => left.RecordedAt.CompareTo(right.RecordedAt)); + var deduplicated = new List(Math.Min(accepted.Count, MaximumEntries)); + var indexes = new Dictionary(); + foreach (var observation in accepted) + { + var key = GetObservationKey(observation); + if (indexes.TryGetValue(key, out var index)) + { + deduplicated[index] = observation; + } + else + { + indexes[key] = deduplicated.Count; + deduplicated.Add(observation); + } + } + + if (deduplicated.Count > MaximumEntries) + { + deduplicated = deduplicated.TakeLast(MaximumEntries).ToList(); + } + + changed = accepted.Count != original.Length + || deduplicated.Count != accepted.Count + || !deduplicated.SequenceEqual(original.Where(observation => observation is not null)!.Cast()); + return deduplicated; + } + + private static bool IsWithinRetention(DateTimeOffset recordedAt, DateTimeOffset now, int retentionDays) + { + try + { + var age = now - recordedAt; + return age >= TimeSpan.Zero && age <= TimeSpan.FromDays(retentionDays); + } + catch (ArgumentOutOfRangeException) + { + return false; + } + } + + private static bool TryNormalizePoint( + UsageAggregatePoint point, + DateTimeOffset now, + out UsageAggregatePoint normalized) + { + normalized = point; + if (point.Source != UsageDataSource.AppServer + || !IsValidTimestamp(point.RecordedAt) + || point.RecordedAt > now + || !IsValidPercent(point.PrimaryRemainingPercent) + || !IsValidPercent(point.WeeklyRemainingPercent)) + { + return false; + } + + if (point.PrimaryRemainingPercent is null && point.WeeklyRemainingPercent is null) + { + return false; + } + + if (!TryNormalizeReset(point.PrimaryResetsAt, point.RecordedAt, out var primaryReset) + || !TryNormalizeReset(point.WeeklyResetsAt, point.RecordedAt, out var weeklyReset)) + { + return false; + } + + normalized = new UsageAggregatePoint( + point.RecordedAt.ToUniversalTime(), + point.PrimaryRemainingPercent, + point.WeeklyRemainingPercent, + point.PrimaryRemainingPercent is null ? null : primaryReset, + point.WeeklyRemainingPercent is null ? null : weeklyReset, + UsageDataSource.AppServer); + return true; + } + + private static bool TryNormalizeReset( + DateTimeOffset? reset, + DateTimeOffset recordedAt, + out DateTimeOffset? normalized) + { + normalized = null; + if (reset is not { } value) + { + return true; + } + + if (!IsValidTimestamp(value) || value < recordedAt) + { + return false; + } + + normalized = value.ToUniversalTime(); + return true; + } + + private static (double RemainingPercent, DateTimeOffset ResetsAt)? TryGetWindowValues( + RateLimitWindow? window, + DateTimeOffset now) + { + if (!UsageFreshness.IsValidWindow(window, now) + || !IsValidTimestamp(window!.ResetsAt)) + { + return null; + } + + return (window!.RemainingPercent, window.ResetsAt.ToUniversalTime()); + } + + private static bool IsValidPercent(double? value) => + value is null || double.IsFinite(value.Value) && value.Value is >= 0 and <= 100; + + private static bool IsValidTimestamp(DateTimeOffset value) => + value > DateTimeOffset.MinValue && value < DateTimeOffset.MaxValue; + + private static bool TryNormalizeNow(DateTimeOffset now, out DateTimeOffset normalized) + { + normalized = now.ToUniversalTime(); + return IsValidTimestamp(normalized); + } + + private static int NormalizeRetentionDays(int retentionDays) => + TryGetSupportedRetention(retentionDays, out var normalized) ? normalized : DefaultRetentionDays; + + private static bool TryGetSupportedRetention(int retentionDays, out int normalized) + { + normalized = retentionDays switch + { + 7 or 30 or 90 => retentionDays, + _ => 0, + }; + return normalized != 0; + } + + private static int FindLastIndex(List observations, ObservationKey key) + { + for (var index = observations.Count - 1; index >= 0; index--) + { + if (GetObservationKey(observations[index]) == key) + { + return index; + } + } + + return -1; + } + + private static ObservationKey GetObservationKey(UsageAggregatePoint observation) => new( + observation.RecordedAt.UtcTicks / ObservationBucket.Ticks, + observation.PrimaryResetsAt?.UtcTicks, + observation.WeeklyResetsAt?.UtcTicks); + + private static void AppendJsonObservation(StringBuilder output, UsageAggregatePoint observation) + { + output.Append(" {\"recordedAtUtc\": ") + .Append(Quote(FormatUtc(observation.RecordedAt))) + .Append(", \"primaryRemainingPercent\": "); + AppendJsonNumber(output, observation.PrimaryRemainingPercent); + output.Append(", \"weeklyRemainingPercent\": "); + AppendJsonNumber(output, observation.WeeklyRemainingPercent); + output.Append(", \"primaryResetsAtUtc\": "); + AppendJsonTimestamp(output, observation.PrimaryResetsAt); + output.Append(", \"weeklyResetsAtUtc\": "); + AppendJsonTimestamp(output, observation.WeeklyResetsAt); + output.Append(", \"source\": ").Append(Quote(observation.Source.ToString())).Append('}'); + } + + private static void AppendJsonNumber(StringBuilder output, double? value) => + output.Append(value is { } number ? number.ToString("R", CultureInfo.InvariantCulture) : "null"); + + private static void AppendJsonTimestamp(StringBuilder output, DateTimeOffset? value) => + output.Append(value is { } timestamp ? Quote(FormatUtc(timestamp)) : "null"); + + private static StringBuilder AppendCsvNumber(StringBuilder output, double? value) => + output.Append(value is { } number ? number.ToString("R", CultureInfo.InvariantCulture) : string.Empty); + + private static StringBuilder AppendCsvTimestamp(StringBuilder output, DateTimeOffset? value) => + output.Append(value is { } timestamp ? FormatUtc(timestamp) : string.Empty); + + private static string FormatUtc(DateTimeOffset value) => + value.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.fffffff'Z'", CultureInfo.InvariantCulture); + + private static string Quote(string value) => + "\"" + JsonEncodedText.Encode(value).ToString() + "\""; + + private void SetStorageError(string? error) + { + lock (_gate) + { + _storageError = error; + } + } + + private readonly record struct ObservationKey(long Bucket, long? PrimaryResetTicks, long? WeeklyResetTicks); +} + +[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true)] +[JsonSerializable(typeof(UsageAggregateStoreDocument))] +[JsonSerializable(typeof(UsageAggregatePoint))] +internal sealed partial class UsageAggregateStoreJsonContext : JsonSerializerContext +{ +} diff --git a/CodexUsageDock/UsageAlerts.cs b/CodexUsageDock/UsageAlerts.cs new file mode 100644 index 0000000..7510613 --- /dev/null +++ b/CodexUsageDock/UsageAlerts.cs @@ -0,0 +1,478 @@ +using System.Globalization; + +namespace CodexUsageDock; + +internal sealed record UsageAlertOptions( + bool Enabled = false, + int LowRemainingPercent = 10, + bool ForecastWarnings = true, + bool ResetExpiryWarnings = true); + +internal sealed record UsageAlert(string Key, string Message); + +internal sealed class UsageAlertEvaluator +{ + private const int MaximumTrackedWindows = 32; + private const int MaximumTrackedResetExpiries = 32; + private static readonly TimeSpan WindowCycleTolerance = TimeSpan.FromMinutes(1); + private static readonly TimeSpan ForecastWarningHorizon = TimeSpan.FromMinutes(60); + private static readonly TimeSpan ResetExpiryWarningHorizon = TimeSpan.FromHours(24); + private readonly object _stateLock = new(); + private UsageAlertOptions? _lastOptions; + private string? _activeAccountKey; + private AccountAlertState? _state; + + internal IReadOnlyList Evaluate( + UsagePresentation presentation, + DateTimeOffset now, + TimeSpan refreshInterval, + UsageAlertOptions options) + { + ArgumentNullException.ThrowIfNull(presentation); + ArgumentNullException.ThrowIfNull(options); + + lock (_stateLock) + { + if (!options.Enabled) + { + ClearState(); + _lastOptions = options; + return []; + } + + if (_lastOptions is null || !_lastOptions.Equals(options)) + { + ClearState(); + _lastOptions = options; + } + + var snapshot = presentation.Usage; + if (!IsEligible(presentation, now, refreshInterval, snapshot)) + { + return []; + } + + var accountKey = snapshot.AccountKey!.Trim(); + if (!string.Equals(_activeAccountKey, accountKey, StringComparison.Ordinal)) + { + ClearState(); + _activeAccountKey = accountKey; + } + + var category = GetDefaultCategory(snapshot); + if (_state is null || !string.Equals(_state.DefaultCategory, category, StringComparison.Ordinal)) + { + _state = new AccountAlertState(category); + } + + var alerts = new List(); + var observations = CollectWindowObservations(snapshot, now); + var currentWindowKeys = new HashSet(StringComparer.Ordinal); + foreach (var observation in observations) + { + var key = GetWindowKey(observation); + currentWindowKeys.Add(key); + var windowState = GetWindowState(observation); + + EvaluateLowRemaining(observation, windowState, options, alerts); + } + + foreach (var key in _state.Windows.Keys.Where(key => !currentWindowKeys.Contains(key)).ToArray()) + { + _state.Windows.Remove(key); + } + + if (options.ForecastWarnings) + { + EvaluateForecastWarning( + observations, + snapshot.Primary, + presentation.PrimaryHistory, + now, + refreshInterval, + alerts); + EvaluateForecastWarning( + observations, + snapshot.Secondary, + presentation.WeeklyHistory, + now, + refreshInterval, + alerts); + } + + if (options.ResetExpiryWarnings) + { + EvaluateResetExpiry(snapshot.ResetCredits, now, alerts); + } + else + { + _state.ResetExpiries.Clear(); + } + + return alerts; + } + } + + internal void Reset() + { + lock (_stateLock) + { + ClearState(); + _lastOptions = null; + } + } + + private static bool IsEligible( + UsagePresentation presentation, + DateTimeOffset now, + TimeSpan refreshInterval, + CodexUsageSnapshot snapshot) => + !presentation.IsLoading + && snapshot.Source == UsageDataSource.AppServer + && !string.IsNullOrWhiteSpace(snapshot.AccountKey) + && UsageFreshness.IsFresh(snapshot.UpdatedAt, now, refreshInterval); + + private static string GetDefaultCategory(CodexUsageSnapshot snapshot) => + string.IsNullOrWhiteSpace(snapshot.DefaultBucketId) ? "default" : snapshot.DefaultBucketId!; + + private static List CollectWindowObservations( + CodexUsageSnapshot snapshot, + DateTimeOffset now) + { + var observations = new List(MaximumTrackedWindows); + var seen = new HashSet(StringComparer.Ordinal); + var defaultCategory = GetDefaultCategory(snapshot); + AddObservation(observations, seen, defaultCategory, "default", "primary", snapshot.Primary, now, isDefault: true, knownDefaultWindow: null); + AddObservation(observations, seen, defaultCategory, "default", "secondary", snapshot.Secondary, now, isDefault: true, knownDefaultWindow: null); + + if (snapshot.Buckets is not { Count: > 0 } buckets) + { + return observations; + } + + for (var index = 0; index < buckets.Count && observations.Count < MaximumTrackedWindows; index++) + { + var bucket = buckets[index]; + if (bucket is null) + { + continue; + } + + var isDefaultBucket = string.Equals(bucket.Id, snapshot.DefaultBucketId, StringComparison.Ordinal); + var category = isDefaultBucket + ? defaultCategory + : string.IsNullOrWhiteSpace(bucket.Id) ? $"bucket-{index + 1}" : bucket.Id; + var label = isDefaultBucket + ? "default" + : UsageText.SanitizeExternal(bucket.Name, 70) + ?? UsageText.SanitizeExternal(bucket.Id, 70) + ?? $"Additional quota {index + 1}"; + AddObservation( + observations, + seen, + category, + label, + "primary", + bucket.Primary, + now, + isDefault: isDefaultBucket, + knownDefaultWindow: snapshot.Primary); + AddObservation( + observations, + seen, + category, + label, + "secondary", + bucket.Secondary, + now, + isDefault: isDefaultBucket, + knownDefaultWindow: snapshot.Secondary); + } + + return observations; + } + + private static void AddObservation( + List observations, + HashSet seen, + string category, + string label, + string role, + RateLimitWindow? window, + DateTimeOffset now, + bool isDefault, + RateLimitWindow? knownDefaultWindow) + { + if (window is null + || observations.Count >= MaximumTrackedWindows + || isDefault && window == knownDefaultWindow + || !UsageFreshness.IsValidWindow(window, now)) + { + return; + } + + var observationKey = $"{category}|{role}|{window.WindowMinutes}|{window.ResetsAt.UtcTicks}|{window.UsedPercent.ToString("R", CultureInfo.InvariantCulture)}"; + if (!seen.Add(observationKey)) + { + return; + } + + var identityKey = $"{category}|{role}|{window.WindowMinutes}"; + observations.Add(new WindowObservation(category, label, role, window, isDefault, identityKey)); + } + + private WindowAlertState GetWindowState(WindowObservation observation) + { + var key = GetWindowKey(observation); + if (_state!.Windows.TryGetValue(key, out var state)) + { + var delta = state.CycleResetAt >= observation.Window.ResetsAt + ? state.CycleResetAt - observation.Window.ResetsAt + : observation.Window.ResetsAt - state.CycleResetAt; + if (delta <= WindowCycleTolerance) + { + state.CycleResetAt = observation.Window.ResetsAt; + return state; + } + } + + state = new WindowAlertState(observation.Window.ResetsAt); + _state.Windows[key] = state; + return state; + } + + private static void EvaluateLowRemaining( + WindowObservation observation, + WindowAlertState state, + UsageAlertOptions options, + List alerts) + { + var remaining = observation.Window.RemainingPercent; + var threshold = Math.Clamp(options.LowRemainingPercent, 0, 100); + if (!state.HasMeasurement) + { + state.HasMeasurement = true; + state.LastRemaining = remaining; + state.Rearmed = remaining > threshold; + return; + } + + var crossedDown = state.Rearmed + && state.LastRemaining > threshold + && remaining <= threshold; + if (crossedDown) + { + alerts.Add(new UsageAlert( + $"low:{GetWindowKey(observation)}:{state.CycleKey}", + $"{FormatWindowName(observation)} is at {FormatPercent(remaining)}% remaining.")); + state.Rearmed = false; + } + + if (remaining > threshold + 5) + { + state.Rearmed = true; + } + + state.LastRemaining = remaining; + } + + private void EvaluateForecastWarning( + IReadOnlyList observations, + RateLimitWindow? targetWindow, + IReadOnlyList history, + DateTimeOffset now, + TimeSpan refreshInterval, + List alerts) + { + if (targetWindow is null) + { + return; + } + + var observation = observations.FirstOrDefault(candidate => + candidate.IsDefault && candidate.Window == targetWindow); + if (observation is null || !_state!.Windows.TryGetValue(GetWindowKey(observation), out var state)) + { + return; + } + + UsageTrendForecast? forecast = null; + try + { + var windowStart = targetWindow.ResetsAt - TimeSpan.FromMinutes(targetWindow.WindowMinutes); + forecast = UsageTrendAnalyzer.Analyze( + history, + windowStart, + targetWindow.ResetsAt, + now, + dataAvailable: true, + UsageFreshness.MaximumAge(refreshInterval)).Forecast; + } + catch (ArgumentException) + { + } + catch (InvalidOperationException) + { + } + catch (OverflowException) + { + } + + var atRisk = forecast is { ReachesLimitBeforeReset: true } candidate + && candidate.EndsAt >= now + && candidate.EndsAt < targetWindow.ResetsAt + && candidate.EndsAt - now <= ForecastWarningHorizon; + if (!state.ForecastInitialized) + { + state.ForecastInitialized = true; + state.ForecastAtRisk = atRisk; + return; + } + + if (atRisk && !state.ForecastAtRisk && !state.ForecastWarningIssued) + { + var minutes = Math.Max(1, (int)Math.Ceiling((forecast!.EndsAt - now).TotalMinutes)); + alerts.Add(new UsageAlert( + $"forecast:{GetWindowKey(observation)}:{state.CycleKey}", + $"{FormatWindowName(observation)} forecast may reach its limit within {minutes.ToString(CultureInfo.InvariantCulture)} minutes.")); + state.ForecastWarningIssued = true; + } + + state.ForecastAtRisk = atRisk; + } + + private void EvaluateResetExpiry( + RateLimitResetCredits? resets, + DateTimeOffset now, + List alerts) + { + if (resets is not { AvailableCount: > 0, Credits: { Count: > 0 } credits }) + { + _state!.ResetExpiries.Clear(); + return; + } + + var eligible = credits + .Where(credit => credit is not null + && credit.ExpiresAt is { } expiry + && expiry > now + && IsAvailableStatus(credit.Status)) + .Select(credit => credit.ExpiresAt!.Value) + .GroupBy(expiry => expiry.UtcTicks) + .OrderBy(group => group.Key) + .Take(MaximumTrackedResetExpiries) + .Select(group => group.First()) + .ToArray(); + var currentKeys = new HashSet(); + foreach (var expiry in eligible) + { + var key = expiry.UtcTicks; + currentKeys.Add(key); + var withinWarningWindow = expiry - now <= ResetExpiryWarningHorizon; + if (!_state!.ResetExpiries.TryGetValue(key, out var state)) + { + _state.ResetExpiries[key] = new ResetExpiryState(withinWarningWindow); + continue; + } + + if (withinWarningWindow && !state.WithinWarningWindow) + { + alerts.Add(new UsageAlert( + $"reset-expiry:{key.ToString(CultureInfo.InvariantCulture)}", + $"A reset credit expires within 24 hours at {expiry.ToUniversalTime():yyyy-MM-dd HH:mm} UTC.")); + } + + state.WithinWarningWindow = withinWarningWindow; + } + + foreach (var key in _state!.ResetExpiries.Keys.Where(key => !currentKeys.Contains(key)).ToArray()) + { + _state.ResetExpiries.Remove(key); + } + } + + private static bool IsAvailableStatus(string? status) => + status is null || string.Equals(status.Trim(), "available", StringComparison.OrdinalIgnoreCase); + + private static string GetWindowKey(WindowObservation observation) => observation.Key; + + private static string FormatWindowName(WindowObservation observation) + { + var duration = FormatWindowDuration(observation.Window.WindowMinutes); + return observation.IsDefault + ? $"{duration} window" + : $"{observation.Label} {observation.Role} window ({duration})"; + } + + 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 FormatPercent(double remaining) => + remaining.ToString("0", CultureInfo.InvariantCulture); + + private void ClearState() + { + _activeAccountKey = null; + _state = null; + } + + private sealed record WindowObservation( + string Category, + string Label, + string Role, + RateLimitWindow Window, + bool IsDefault, + string Key); + + private sealed class WindowAlertState + { + internal WindowAlertState(DateTimeOffset cycleResetAt) + { + CycleResetAt = cycleResetAt; + CycleKey = cycleResetAt.UtcTicks.ToString(CultureInfo.InvariantCulture); + } + + internal DateTimeOffset CycleResetAt { get; set; } + internal string CycleKey { get; } + internal bool HasMeasurement { get; set; } + internal double LastRemaining { get; set; } + internal bool Rearmed { get; set; } + internal bool ForecastAtRisk { get; set; } + internal bool ForecastInitialized { get; set; } + internal bool ForecastWarningIssued { get; set; } + } + + private sealed class ResetExpiryState(bool withinWarningWindow) + { + internal bool WithinWarningWindow { get; set; } = withinWarningWindow; + } + + private sealed class AccountAlertState(string defaultCategory) + { + internal string DefaultCategory { get; } = defaultCategory; + internal Dictionary Windows { get; } = new(StringComparer.Ordinal); + internal Dictionary ResetExpiries { get; } = []; + } +} 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 36c1a51..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; @@ -35,7 +35,7 @@ private void UpdateText() var window = _kind == UsageDockItemKind.FiveHour ? snapshot.Primary : snapshot.Secondary; if (snapshot.Source == UsageDataSource.Unavailable) { - (Title, Subtitle) = FormatUnavailable(_kind); + (Title, Subtitle) = FormatUnavailable(_kind, _settings?.CompactDock == true); Icon = new IconInfo("\uE783"); return; } @@ -43,14 +43,17 @@ private void UpdateText() if (_kind == UsageDockItemKind.ResetsAndCredits) { Title = FormatResetsAndCredits(snapshot); - Subtitle = CombineStatusAndDetail( - FormatSourceFreshness(snapshot, now, _usage.RefreshInterval), - FormatResetExpiry(snapshot.ResetCredits, now)); + Subtitle = FormatLiveDetailOrStatus( + snapshot, + now, + _usage.RefreshInterval, + _settings?.CompactDock == true ? string.Empty : FormatResetExpiry(snapshot.ResetCredits, now)); Icon = new IconInfo("\uE777"); return; } - var label = _kind == UsageDockItemKind.FiveHour ? "5h" : "Week"; + var compact = _settings?.CompactDock == true; + var label = _kind == UsageDockItemKind.FiveHour ? "5h" : compact ? "W" : "Week"; if (window is null) { var dataWasLoaded = snapshot.Primary is not null || snapshot.Secondary is not null; @@ -72,9 +75,15 @@ private void UpdateText() return; } - Title = $"{label} {window.RemainingPercent:0}%"; - var reset = _settings?.ShowResetTime == false ? string.Empty : $"reset {FormatReset(window.ResetsAt)}"; - Subtitle = CombineStatusAndDetail(FormatSourceFreshness(snapshot, now, _usage.RefreshInterval), reset); + Title = FormatQuotaTitle(_kind, window.RemainingPercent, compact); + 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"); } @@ -103,6 +112,20 @@ internal static string FormatFallbackAge(CodexUsageSnapshot snapshot, DateTimeOf : $"Fallback · {(int)age.TotalDays} days old"; } + internal static string FormatQuotaTitle(UsageDockItemKind kind, double remainingPercent, bool compact) + { + var label = kind switch + { + UsageDockItemKind.FiveHour => "5h", + UsageDockItemKind.Weekly => compact ? "W" : "Week", + _ => throw new ArgumentOutOfRangeException(nameof(kind), kind, "The resets and credits item has no quota percentage."), + }; + + return compact + ? $"{label}{remainingPercent:0}%" + : $"{label} {remainingPercent:0}%"; + } + internal static string FormatSourceFreshness( CodexUsageSnapshot snapshot, DateTimeOffset now, @@ -174,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}"; @@ -205,31 +253,20 @@ 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) => + internal static (string Title, string Subtitle) FormatUnavailable(UsageDockItemKind kind, bool compact = false) => (kind switch { UsageDockItemKind.FiveHour => "5h --", - UsageDockItemKind.Weekly => "Week --", + UsageDockItemKind.Weekly => compact ? "W --" : "Week --", _ => "-- 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/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 787feda..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,12 +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 only display, refresh, 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. +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. +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 9501f54..ab7dc91 100644 --- a/README.md +++ b/README.md @@ -46,10 +46,14 @@ 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 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. + Open Command Palette and select **Codex Usage settings** to choose which usage entries appear in the Dock. You can independently show or hide the five-hour limit, weekly limit, and resets and credits, choose whether usage entries show their reset time, set the local data refresh interval to 1, 5, or 15 minutes, and enable or pause the adaptive weekly forecast. Pausing the forecast keeps its learned local history and excludes measurements collected while it is paused; **Delete learned forecast history** asks for confirmation before permanently clearing it. The extension saves these choices in `CodexUsageDock/settings.json` under the current user's Windows local application data directory and restores them before refreshing after a restart. If saving fails, the page explains that the choices apply only to the running session and lets you save again. Deleting learned history confirms success only after the cleared state is saved. History read/write failures also appear in Details. Choices lost by older versions cannot be recovered; set them once again after updating. @@ -58,6 +62,26 @@ The extension saves these choices in `CodexUsageDock/settings.json` under the cu Microsoft Store installs updates automatically. You can also check for updates from **Microsoft Store > Library**. +## Sources and account activity + +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. + +**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. + +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. + +The same page offers **Use or retry an earned reset**, which always asks for confirmation. It only uses an existing earned reset, never purchases one, and verifies the expected account before the mutation. A request ID is saved locally before sending. Unknown outcomes retain that exact ID across retries and extension restarts; concurrent clicks share the same attempt. An unreadable or unwritable recovery record stops the request. Only an unambiguous server outcome clears the pending record, and limits are refreshed afterward. This feature has synthetic protocol and service tests; no real credit was consumed while developing it. + ## Uninstall Remove **Codex Usage Dock** from **Windows Settings > Apps > Installed apps**. @@ -90,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 98bce0d..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 | Planned | -| 3 | `codex/sprint-3-history-planning` | Retained aggregates and export, workday planning, forecast explanation and validation, supported task analysis, explicit earned-reset action | Planned | -| 4 | `codex/sprint-4-provider-pilot` | Optional Claude statusline bridge, explicit local profiles/WSL paths, efficient fallback reads, accessible text alternatives | Planned | +| 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; 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. @@ -25,3 +27,23 @@ Gemini/Cursor/Copilot expansion, a standalone tray app, cloud sync, team dashboa ### Sprint 1 verification Native ARM64 tests passed (186/186); application builds have no warnings. Existing test-name analyzer warnings remain unchanged. The x64 .NET 10 test runtime is unavailable locally, so x64 test execution belongs to PR CI. The integration preflight passed manifest, COM identity, generated-output freshness, self-contained runtime, and asset checks. Package registration and AppExtension discovery were unavailable in this test context; Command Palette reload, visual behavior, Store installation, and real-account compatibility were not verified. Tests use isolated synthetic data and do not consume actual reset credits. + +The final sprint 1 head also passed [GitHub Actions](https://github.com/TheBeems/CodexUsageDock/actions/runs/34379840746), including x64 tests, both architecture builds, and Store-package validation. + +### Sprint 2 verification + +The x64 and ARM64 application code compiles without warnings. Local ARM64 test execution was blocked while loading the assembly by Windows Application Control (`0x800711C7`), including a retry with elevated execution. No Windows security policy was changed. [GitHub validation](https://github.com/TheBeems/CodexUsageDock/actions/runs/34383095096) passed all 235 tests, both architecture builds, and package checks on head `d067295`. Live account activity, notifications, individual pinning, and configuration changes still require Command Palette verification after an authorized installation. + +### 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 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.