diff --git a/CHANGELOG.md b/CHANGELOG.md index 51baab2..9035e87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,17 @@ - The AI quotas load on networks that announce IPv6 but don't route it. The quota requests try the IPv4 addresses first, then the others, within one 10-second connect budget. Before, the Claude quota failed with "Socket is not connected" (#105, [sateesh2020](https://github.com/sateesh2020)). +- The Claude quota check spends fewer of Anthropic's rate-limited requests and shows fewer errors: + - a restart (an update) or a second agent on the computer uses a reading under 3 minutes old, and still waits + out a `429`'s Retry-After, instead of asking again; + - an expired token is not sent, and a token Anthropic refused (`401`) is tried again only after 30 minutes; the + token Claude Code renews is used within a minute, instead of after a back-off of up to 15 minutes; + - when the network isn't back yet (after sleep), the last reading stays without an error and the check is + retried after 30 seconds, up to three times; + - a reply PhoneBox doesn't recognize (a captive portal, a changed format) keeps the last reading instead of + emptying the card. +- The Codex quota skips a reading cut off mid-write for the complete one before it, instead of showing a JSON error, + and a session log that is busy for a moment keeps the last reading. ## 0.9.11 — 2026-11-16 diff --git a/PRIVACY.md b/PRIVACY.md index b114a1b..187674b 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -12,7 +12,9 @@ Last updated: 2026-11-15 (PhoneBox 0.9.6). `~/Library/Application Support/PhoneBox` (macOS), plus `data.json` (pushed values and notifications) next to it. On macOS and Linux these files are readable only by your user (0600). - **Last Claude quota reading**: `claude-quota.json` next to the log (usage percentages and reset times, no token), - so the panel can show the last values after a restart. + so the panel can show the last values after a restart, and `claude-quota-schedule.json` (when the next check may + run, the last error message and, after Anthropic refused a token, a 16-character hash of that token, never the token + itself), so a restart doesn't ask Anthropic again sooner than it should. - **Log**: `agent.log` in `%LOCALAPPDATA%\PhoneBox` (Windows), `~/.local/share/PhoneBox` (Linux) or `~/Library/Application Support/PhoneBox` (macOS). - **Phone app**: caches (weather, rates, widget state) in its own app storage. The app asks for two permissions only: diff --git a/agent/PhoneBox.Agent.Tests/ClaudeQuotaScheduleTests.cs b/agent/PhoneBox.Agent.Tests/ClaudeQuotaScheduleTests.cs new file mode 100644 index 0000000..f61a245 --- /dev/null +++ b/agent/PhoneBox.Agent.Tests/ClaudeQuotaScheduleTests.cs @@ -0,0 +1,421 @@ +using System.Net; +using System.Text; +using Microsoft.Extensions.Logging.Abstractions; +using PhoneBox.Agent; +using Xunit; + +/// +/// The Claude quota check through its seams: a fake HTTP handler and a credentials file of the test's own, so nothing +/// here reads the real token or reaches api.anthropic.com. The usage endpoint is rate limited per account and shared +/// with Claude Code, so these tests count the requests PhoneBox would send. +/// +public sealed class ClaudeQuotaScheduleTests : IDisposable +{ + private const long Minute = 60_000; + private readonly string _dir = Directory.CreateTempSubdirectory("phonebox-claude-schedule-").FullName; + private readonly FakeAnthropic _api = new(); + private readonly long _t0 = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + + public void Dispose() + { + try { Directory.Delete(_dir, recursive: true); } catch (IOException) { } + } + + private string Creds => Path.Combine(_dir, "credentials.json"); + + private QuotaMonitor Agent() => new(NullLogger.Instance) + { + ClaudeCachePath = Path.Combine(_dir, "claude-quota.json"), + CredentialsPath = Creds, + HttpHandler = _api, + }; + + private void SignIn(string token, long expiresAt) => File.WriteAllText(Creds, + $$$"""{"claudeAiOauth":{"accessToken":"{{{token}}}","expiresAt":{{{expiresAt}}},"subscriptionType":"max","rateLimitTier":"default_claude_max_20x"}}"""); + + private const string Usage = """{"limits":[{"kind":"session","percent":42,"resets_at":"2099-01-01T00:00:00Z","severity":"normal"}]}"""; + + private static QuotaProvider Claude(QuotaMonitor agent) => Assert.Single(agent.Snapshot(), p => p.Id == "claude"); + + [Fact] + public async Task AFreshReadingIsNotFetchedAgainWhenTheAgentRestarts() + { + SignIn("token-1", _t0 + 3_600_000); + _api.Respond(HttpStatusCode.OK, Usage); + await Agent().ClaudeTickAsync(_t0, default); + Assert.Equal(1, _api.Calls); + + var restarted = Agent(); + restarted.LoadClaudeCache(_t0 + Minute); + await restarted.ClaudeTickAsync(_t0 + Minute, default); + Assert.Equal(1, _api.Calls); // the reading is a minute old: no request + Assert.Equal(42, Assert.Single(Claude(restarted).Limits).Percent); + + await restarted.ClaudeTickAsync(_t0 + 3 * Minute + 1, default); + Assert.Equal(2, _api.Calls); + } + + [Fact] + public async Task ARunningAgentUsesTheReadingAnotherOneJustFetched() + { + SignIn("token-1", _t0 + 3_600_000); + _api.Respond(HttpStatusCode.OK, Usage); + var first = Agent(); + var second = Agent(); + await first.ClaudeTickAsync(_t0, default); + await second.ClaudeTickAsync(_t0 + 10_000, default); + Assert.Equal(1, _api.Calls); + Assert.Equal(42, Assert.Single(Claude(second).Limits).Percent); + } + + [Fact] + public async Task ARetryAfterIsKeptAcrossARestart() + { + SignIn("token-1", _t0 + 3_600_000); + _api.Respond(HttpStatusCode.TooManyRequests, "{}", retryAfterSeconds: 230); + await Agent().ClaudeTickAsync(_t0, default); + + var restarted = Agent(); + restarted.LoadClaudeCache(_t0 + Minute); + await restarted.ClaudeTickAsync(_t0 + Minute, default); + await restarted.ClaudeTickAsync(_t0 + 3 * Minute, default); + Assert.Equal(1, _api.Calls); // the server asked for 230 s + Assert.Contains("limiting", Claude(restarted).Error); + + _api.Respond(HttpStatusCode.OK, Usage); + await restarted.ClaudeTickAsync(_t0 + 236_000, default); + Assert.Equal(2, _api.Calls); + Assert.Null(Claude(restarted).Error); + } + + [Fact] + public async Task ARenewedTokenIsUsedOnTheNextPassAfterAnExpiredOne() + { + SignIn("old", _t0 - Minute); + _api.Respond(HttpStatusCode.OK, Usage); + var agent = Agent(); + for (var t = _t0; t <= _t0 + 4 * Minute; t += 30_000) await agent.ClaudeTickAsync(t, default); + Assert.Equal(0, _api.Calls); // no request with an expired token + Assert.Contains("expired", Claude(agent).Error); + + SignIn("new", _t0 + 3_600_000); // Claude Code renewed it + await agent.ClaudeTickAsync(_t0 + 4 * Minute + 30_000, default); + await agent.ClaudeTickAsync(_t0 + 5 * Minute, default); + Assert.Equal(1, _api.Calls); // used within a minute + Assert.Null(Claude(agent).Error); + } + + [Fact] + public async Task ATokenThatExpiresWithinAMinuteIsNotSent() + { + SignIn("almost", _t0 + 20_000); + await Agent().ClaudeTickAsync(_t0, default); + Assert.Equal(0, _api.Calls); + } + + [Fact] + public async Task ARefusedTokenIsNotSentAgainUntilClaudeCodeRenewsIt() + { + SignIn("revoked", _t0 + 7_200_000); + _api.Respond(HttpStatusCode.Unauthorized, """{"error":"invalid token"}"""); + var agent = Agent(); + for (var t = _t0; t < _t0 + 30 * Minute; t += 30_000) await agent.ClaudeTickAsync(t, default); + Assert.Equal(1, _api.Calls); + Assert.NotNull(Claude(agent).Error); + + SignIn("renewed", _t0 + 7_200_000); + _api.Respond(HttpStatusCode.OK, Usage); + await agent.ClaudeTickAsync(_t0 + 30 * Minute, default); + Assert.Equal(2, _api.Calls); + Assert.Null(Claude(agent).Error); + } + + [Fact] + public async Task ARefusalIsNotPermanent() + { + // a 401 from a proxy or an outage: the same token is tried again after half an hour + SignIn("token-1", _t0 + 7_200_000); + _api.Respond(HttpStatusCode.Unauthorized, ""); + var agent = Agent(); + for (var t = _t0; t <= _t0 + 61 * Minute; t += 30_000) await agent.ClaudeTickAsync(t, default); + Assert.Equal(3, _api.Calls); // at 0, 30 and 60 minutes + } + + [Fact] + public async Task AForbiddenReplyBacksOffLikeOtherErrors() + { + SignIn("token-1", _t0 + 7_200_000); + _api.Respond(HttpStatusCode.Forbidden, "challenge"); + var agent = Agent(); + for (var t = _t0; t <= _t0 + 8 * Minute; t += 30_000) await agent.ClaudeTickAsync(t, default); + Assert.Equal(4, _api.Calls); // at 0, 1, 3 and 7 minutes + Assert.Contains("403", Claude(agent).Error); + } + + [Fact] + public async Task AClockSetBackDoesNotStopTheChecks() + { + SignIn("token-1", _t0 + 7_200_000); + _api.Respond(HttpStatusCode.OK, Usage); + var agent = Agent(); + await agent.ClaudeTickAsync(_t0, default); + + // the clock was a day ahead and NTP corrected it + var back = _t0 - 24 * 60 * Minute; + var t = back; + while (_api.Calls < 2 && t < back + 3 * 60 * Minute) { t += 30_000; await agent.ClaudeTickAsync(t, default); } + Assert.Equal(2, _api.Calls); + Assert.InRange(t - back, 0, 3_605_000 + 60_000); // the longest wait, plus the 30 s passes on either side + + // and from then on the normal 3 minutes, with no leftover from the old schedule + for (var u = t + 30_000; u <= t + 3 * Minute + 30_000; u += 30_000) await agent.ClaudeTickAsync(u, default); + Assert.Equal(3, _api.Calls); + } + + [Fact] + public async Task AnUnreachableNetworkIsRetriedSoonWithoutShowingAnError() + { + SignIn("token-1", _t0 + 3_600_000); + _api.Respond(HttpStatusCode.OK, Usage); + var agent = Agent(); + await agent.ClaudeTickAsync(_t0, default); + + // the computer woke up and the network is not back yet + _api.Fail(new HttpRequestException(HttpRequestError.ConnectionError, "No route to host")); + await agent.ClaudeTickAsync(_t0 + 3 * Minute, default); + Assert.Null(Claude(agent).Error); + Assert.Equal(42, Assert.Single(Claude(agent).Limits).Percent); + + _api.Respond(HttpStatusCode.OK, Usage); + await agent.ClaudeTickAsync(_t0 + 3 * Minute + 30_000, default); + Assert.Equal(3, _api.Calls); + Assert.Null(Claude(agent).Error); + } + + [Fact] + public async Task ANetworkThatStaysDownIsReportedAndBacksOff() + { + SignIn("token-1", _t0 + 3_600_000); + _api.Fail(new HttpRequestException(HttpRequestError.NameResolutionError, "No such host is known")); + var agent = Agent(); + for (var t = _t0; t <= _t0 + 10 * Minute; t += 30_000) await agent.ClaudeTickAsync(t, default); + Assert.NotNull(Claude(agent).Error); + // three quick retries 30 s apart, then the back-off (1, 2, 4 … minutes) + Assert.InRange(_api.Calls, 5, 7); + } + + [Fact] + public async Task AReplyWithoutLimitsKeepsTheLastReadingAndTheCache() + { + SignIn("token-1", _t0 + 3_600_000); + _api.Respond(HttpStatusCode.OK, Usage); + var agent = Agent(); + await agent.ClaudeTickAsync(_t0, default); + + _api.Respond(HttpStatusCode.OK, """{"something":"new"}"""); + await agent.ClaudeTickAsync(_t0 + 3 * Minute, default); + Assert.Equal(42, Assert.Single(Claude(agent).Limits).Percent); + Assert.NotNull(Claude(agent).Error); + + var restarted = Agent(); + restarted.LoadClaudeCache(_t0 + 4 * Minute); + Assert.Equal(42, Assert.Single(Claude(restarted).Limits).Percent); + + // an unknown reply format won't change by asking again soon + for (var t = _t0 + 3 * Minute + 30_000; t < _t0 + 18 * Minute; t += 30_000) await agent.ClaudeTickAsync(t, default); + Assert.Equal(2, _api.Calls); + } + + [Fact] + public async Task AHtmlErrorPageWithStatus200KeepsTheLastReading() + { + SignIn("token-1", _t0 + 3_600_000); + _api.Respond(HttpStatusCode.OK, Usage); + var agent = Agent(); + await agent.ClaudeTickAsync(_t0, default); + + _api.Respond(HttpStatusCode.OK, "captive portal"); + await agent.ClaudeTickAsync(_t0 + 3 * Minute, default); + Assert.Equal(42, Assert.Single(Claude(agent).Limits).Percent); + } + + [Fact] + public async Task AConnectFailureOfTheRealHandlerIsAConnectionError() + { + // the quick retry relies on SocketsHttpHandler reporting a failed connect (through the IPv4-first callback) + // as HttpRequestError.ConnectionError + var free = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0); + free.Start(); + var port = ((IPEndPoint)free.LocalEndpoint).Port; + free.Stop(); + using var http = new HttpClient(new SocketsHttpHandler { ConnectCallback = (ctx, ct) => QuotaMonitor.ConnectIpv4First(ctx.DnsEndPoint, ct) }); + var ex = await Assert.ThrowsAsync(() => http.GetAsync($"http://127.0.0.1:{port}/")); + Assert.Equal(HttpRequestError.ConnectionError, ex.HttpRequestError); + } + + [Theory] + [InlineData("null")] + [InlineData("\"2026-11-16T10:00:00Z\"")] + [InlineData("1.5e300")] + public async Task AnExpiryThatIsNotAWholeNumberDoesNotEndTheChecks(string expiresAt) + { + // JsonElement.TryGetInt64 throws on a non-number; that used to end the whole usage loop + File.WriteAllText(Creds, $$$"""{"claudeAiOauth":{"accessToken":"token-1","expiresAt":{{{expiresAt}}}}}"""); + _api.Respond(HttpStatusCode.OK, Usage); + var agent = Agent(); + await agent.ClaudeTickAsync(_t0, default); + Assert.Equal(1, _api.Calls); // an unknown expiry is left to the server + Assert.Null(Claude(agent).Error); + } + + [Fact] + public async Task ARefusedTokenStaysRefusedAcrossARestart() + { + SignIn("revoked", _t0 + 7_200_000); + _api.Respond(HttpStatusCode.Unauthorized, ""); + await Agent().ClaudeTickAsync(_t0, default); + + var restarted = Agent(); + for (var t = _t0 + 2 * Minute; t < _t0 + 30 * Minute; t += 30_000) await restarted.ClaudeTickAsync(t, default); + Assert.Equal(1, _api.Calls); + Assert.NotNull(Claude(restarted).Error); + + SignIn("renewed", _t0 + 7_200_000); + _api.Respond(HttpStatusCode.OK, Usage); + await restarted.ClaudeTickAsync(_t0 + 31 * Minute, default); + Assert.Equal(2, _api.Calls); + } + + [Fact] + public async Task ALongerWaitAnotherAgentGotMeanwhileIsKept() + { + SignIn("token-1", _t0 + 7_200_000); + _api.Respond(HttpStatusCode.OK, Usage); + var agent = Agent(); + // while this request runs, another agent on the computer gets a 429 that asks for 230 s + _api.OnSend = () => File.WriteAllText(agent.ClaudeSchedulePath, + $$"""{"nextAt":{{_t0 + 230_000}},"failures":1,"error":"Anthropic is limiting quota checks"}"""); + await agent.ClaudeTickAsync(_t0, default); + _api.OnSend = null; + await agent.ClaudeTickAsync(_t0 + 200_000, default); + Assert.Equal(1, _api.Calls); + await agent.ClaudeTickAsync(_t0 + 231_000, default); + Assert.Equal(2, _api.Calls); + } + + [Fact] + public async Task ARetryAfterCountsFromTheAnswer() + { + SignIn("token-1", _t0 + 7_200_000); + _api.Respond(HttpStatusCode.TooManyRequests, "{}", retryAfterSeconds: 120); + var agent = Agent(); + _api.OnSend = () => Thread.Sleep(2_000); // a slow answer + await agent.ClaudeTickAsync(_t0, default); + _api.OnSend = null; + await agent.ClaudeTickAsync(_t0 + 125_500, default); // 120 + 5 s after the request went out, not after the answer + Assert.Equal(1, _api.Calls); + await agent.ClaudeTickAsync(_t0 + 128_000, default); + Assert.Equal(2, _api.Calls); + } + + [Fact] + public async Task ARefusalAnotherAgentGotMeanwhileIsNotOverwritten() + { + SignIn("revoked", _t0 + 7_200_000); + _api.Respond(HttpStatusCode.ServiceUnavailable, ""); + var agent = Agent(); + // while this request runs, another agent sends the same token and gets a 401 + var print = Print("revoked"); + _api.OnSend = () => File.WriteAllText(agent.ClaudeSchedulePath, + $$"""{"nextAt":{{_t0 + 60_000}},"failures":0,"refused":"{{print}}","refusedAt":{{_t0}}}"""); + await agent.ClaudeTickAsync(_t0, default); + _api.OnSend = null; + + var restarted = Agent(); + for (var t = _t0 + 10 * Minute; t < _t0 + 30 * Minute; t += 30_000) await restarted.ClaudeTickAsync(t, default); + Assert.Equal(1, _api.Calls); + } + + private static string Print(string token) => + Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(Encoding.UTF8.GetBytes(token)))[..16]; + + [Fact] + public async Task AnHourLongWaitAnotherAgentGotIsKeptAfterASlowAnswer() + { + SignIn("token-1", _t0 + 7_200_000); + _api.Respond(HttpStatusCode.OK, Usage); + var agent = Agent(); + _api.OnSend = () => + { + // a second into this pass another agent is told to wait an hour (+5 s); this answer then takes 2 s + File.WriteAllText(agent.ClaudeSchedulePath, $$"""{"nextAt":{{_t0 + 1_000 + 3_605_000}},"failures":1}"""); + Thread.Sleep(2_000); + }; + await agent.ClaudeTickAsync(_t0, default); + _api.OnSend = null; + await agent.ClaudeTickAsync(_t0 + 10 * Minute, default); + Assert.Equal(1, _api.Calls); + } + + [Fact] + public async Task ANewerRefusalOfTheSameTokenIsKept() + { + SignIn("revoked", _t0 + 7_200_000); + _api.Respond(HttpStatusCode.Unauthorized, ""); + var agent = Agent(); + await agent.ClaudeTickAsync(_t0, default); + + // half an hour later this agent tries the token again; meanwhile another agent gets a fresh 401 for it + _api.Respond(HttpStatusCode.ServiceUnavailable, ""); + _api.OnSend = () => File.WriteAllText(agent.ClaudeSchedulePath, + $$"""{"nextAt":{{_t0 + 31 * Minute}},"failures":0,"refused":"{{Print("revoked")}}","refusedAt":{{_t0 + 30 * Minute}}}"""); + await agent.ClaudeTickAsync(_t0 + 30 * Minute, default); + _api.OnSend = null; + Assert.Equal(2, _api.Calls); + + var restarted = Agent(); + for (var t = _t0 + 36 * Minute; t < _t0 + 60 * Minute; t += 30_000) await restarted.ClaudeTickAsync(t, default); + Assert.Equal(2, _api.Calls); + } + + [Fact] + public async Task ARestartKeepsTheBackOffGoing() + { + SignIn("token-1", _t0 + 7_200_000); + _api.Respond(HttpStatusCode.Forbidden, ""); + var agent = Agent(); + await agent.ClaudeTickAsync(_t0, default); + await agent.ClaudeTickAsync(_t0 + Minute, default); // second failure: next at 3 minutes + + var restarted = Agent(); + await restarted.ClaudeTickAsync(_t0 + 3 * Minute, default); // third failure: the next one waits 4 minutes + await restarted.ClaudeTickAsync(_t0 + 5 * Minute, default); + Assert.Equal(3, _api.Calls); + await restarted.ClaudeTickAsync(_t0 + 7 * Minute, default); + Assert.Equal(4, _api.Calls); + } + + private sealed class FakeAnthropic : HttpMessageHandler + { + private Func _next = () => new HttpResponseMessage(HttpStatusCode.InternalServerError); + public int Calls { get; private set; } + public Action? OnSend { get; set; } + + public void Respond(HttpStatusCode status, string body, int? retryAfterSeconds = null) => _next = () => + { + var res = new HttpResponseMessage(status) { Content = new StringContent(body, Encoding.UTF8, "application/json") }; + if (retryAfterSeconds is { } s) res.Headers.RetryAfter = new System.Net.Http.Headers.RetryConditionHeaderValue(TimeSpan.FromSeconds(s)); + return res; + }; + + public void Fail(Exception ex) => _next = () => throw ex; + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + Calls++; + OnSend?.Invoke(); + Assert.Equal("https://api.anthropic.com/api/oauth/usage", request.RequestUri!.ToString()); + return Task.FromResult(_next()); + } + } +} diff --git a/agent/PhoneBox.Agent.Tests/CodexQuotaTests.cs b/agent/PhoneBox.Agent.Tests/CodexQuotaTests.cs new file mode 100644 index 0000000..d4778bb --- /dev/null +++ b/agent/PhoneBox.Agent.Tests/CodexQuotaTests.cs @@ -0,0 +1,65 @@ +using Microsoft.Extensions.Logging.Abstractions; +using PhoneBox.Agent; +using Xunit; + +/// The Codex reading from a session log of the test's own, never the real ~/.codex. +public sealed class CodexQuotaTests : IDisposable +{ + private readonly string _root = Directory.CreateTempSubdirectory("phonebox-codex-").FullName; + + public void Dispose() + { + try { Directory.Delete(_root, recursive: true); } catch (IOException) { } + } + + private QuotaMonitor Agent() => new(NullLogger.Instance) { CodexSessionsRoot = _root }; + + private static string Reading(int percent) => + """{"timestamp":"2026-11-16T10:00:00Z","type":"event_msg","payload":{"type":"token_count","rate_limits":{"primary":{"used_percent":""" + + percent + ""","window_minutes":300,"resets_at":4102444800},"secondary":{"used_percent":3,"window_minutes":10080,"resets_at":4102444800}}}}"""; + + private string Log(params string[] lines) + { + var dir = Path.Combine(_root, "2026", "11", "16"); + Directory.CreateDirectory(dir); + var path = Path.Combine(dir, "rollout-2026-11-16T10-00-00-test.jsonl"); + File.WriteAllText(path, string.Join("\n", lines)); + return path; + } + + private static QuotaProvider Codex(QuotaMonitor agent) => Assert.Single(agent.Snapshot(), p => p.Id == "codex"); + + [Fact] + public void ACompleteLastReadingIsUsed() + { + Log("{\"type\":\"session_meta\"}", Reading(12) + "\n"); + var agent = Agent(); + agent.CodexTick(); + Assert.Null(Codex(agent).Error); + Assert.Equal(12, Codex(agent).Limits[0].Percent); + } + + [Fact] + public void ALastLineCutOffMidWriteFallsBackToTheReadingBeforeIt() + { + // Codex was stopped, or PhoneBox read the file, while the newest reading was half written + var torn = Reading(55); + Log("{\"type\":\"session_meta\"}", Reading(12), torn[..(torn.Length / 2 + 40)]); + var agent = Agent(); + agent.CodexTick(); + Assert.Null(Codex(agent).Error); + Assert.Equal(12, Codex(agent).Limits[0].Percent); + } + + [Fact] + public void ALockedLogKeepsTheLastReading() + { + if (!OperatingSystem.IsWindows()) return; // FileShare.None only locks other readers on Windows + var path = Log("{\"type\":\"session_meta\"}", Reading(12) + "\n"); + var agent = Agent(); + agent.CodexTick(); + using (new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) + agent.CodexTick(); + Assert.Equal(12, Codex(agent).Limits[0].Percent); + } +} diff --git a/agent/PhoneBox.Agent/QuotaMonitor.Antigravity.cs b/agent/PhoneBox.Agent/QuotaMonitor.Antigravity.cs index 145c434..4eb30f4 100644 --- a/agent/PhoneBox.Agent/QuotaMonitor.Antigravity.cs +++ b/agent/PhoneBox.Agent/QuotaMonitor.Antigravity.cs @@ -23,7 +23,7 @@ public sealed partial class QuotaMonitor private async Task RefreshAntigravity(CancellationToken ct) { var endpoints = FindAntigravityEndpoints().Distinct().Take(8).ToArray(); - var provider = endpoints.Length > 0 ? await ReadAntigravityAsync(_http, endpoints, ct) : null; + var provider = endpoints.Length > 0 ? await ReadAntigravityAsync(Http, endpoints, ct) : null; var cli = FindAntigravityCli(); if (provider is null && cli is not null) { diff --git a/agent/PhoneBox.Agent/QuotaMonitor.cs b/agent/PhoneBox.Agent/QuotaMonitor.cs index 720afc9..9b22009 100644 --- a/agent/PhoneBox.Agent/QuotaMonitor.cs +++ b/agent/PhoneBox.Agent/QuotaMonitor.cs @@ -37,10 +37,24 @@ internal QuotaMonitor(ILogger log) : this(null!, log) { } private static readonly string Home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); // IPv4 first: on networks where IPv6 is advertised but not routable, the default connect fails with // "Socket is not connected" instead of falling back, which breaks the quota checks. - private readonly HttpClient _http = new(new SocketsHttpHandler { ConnectCallback = (ctx, ct) => ConnectIpv4First(ctx.DnsEndPoint, ct) }) + private HttpClient? _httpClient; + private HttpClient Http => _httpClient ??= NewHttpClient(HttpHandler + ?? new SocketsHttpHandler { ConnectCallback = (ctx, ct) => ConnectIpv4First(ctx.DnsEndPoint, ct) }); + + /// For tests: a fake handler instead of the network. + internal HttpMessageHandler? HttpHandler { get; init; } + + private static HttpClient NewHttpClient(HttpMessageHandler handler) { - Timeout = TimeSpan.FromSeconds(15), - }; + var http = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(15) }; + http.DefaultRequestHeaders.UserAgent.ParseAdd("PhoneBox/" + AppPaths.Version); + return http; + } + + private static readonly string DefaultCredentialsPath = Path.Combine(Home, ".claude", ".credentials.json"); + + /// Claude Code's credentials file (read only). Tests point it at a file of their own. + internal string CredentialsPath { get; init; } = DefaultCredentialsPath; /// The addresses in the order to try them: IPv4 first, each family keeping its resolver order. internal static IEnumerable Ipv4First(IEnumerable addresses) => @@ -98,9 +112,8 @@ internal static async ValueTask ConnectInOrder(IReadOnlyCollection _external = []; @@ -155,7 +168,6 @@ private static QuotaProvider Rolled(QuotaProvider p, long now) /// protected override async Task ExecuteAsync(CancellationToken ct) { - _http.DefaultRequestHeaders.UserAgent.ParseAdd("PhoneBox/" + AppPaths.Version); await Task.WhenAll(RunUsageLoopAsync(ct), RunOverviewLoopAsync(ct)); } @@ -217,35 +229,28 @@ internal async Task RefreshOverviewOnceAsync(Func findTool, /// A cached reading older than this is not shown any more. private const long ClaudeCacheMaxAgeMs = 7L * 24 * 3600 * 1000; - internal void LoadClaudeCache(long nowMs) + internal void LoadClaudeCache(long nowMs) => + _claude ??= ReadClaudeCache(nowMs); // limits whose reset has passed are shown as reset (see Snapshot) + + /// The cached reading, without an error, or null when there is none, it's broken or it's too old. + private QuotaProvider? ReadClaudeCache(long nowMs) { try { - if (!File.Exists(ClaudeCachePath)) return; + if (!File.Exists(ClaudeCachePath)) return null; var cached = JsonSerializer.Deserialize(File.ReadAllText(ClaudeCachePath), ConfigStore.WriteOpts); - if (cached is not { Id: "claude", Limits.Count: > 0, UpdatedAt: { } at } || nowMs - at > ClaudeCacheMaxAgeMs) return; - _claude ??= cached with { Error = null }; // limits whose reset has passed are shown as reset (see Snapshot) + if (cached is not { Id: "claude", Limits.Count: > 0, UpdatedAt: { } at } || nowMs - at > ClaudeCacheMaxAgeMs) return null; + return cached with { Error = null }; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException or NotSupportedException) { log.LogDebug("claude quota cache: {Msg}", ex.Message); + return null; } } - internal void SaveClaudeCache(QuotaProvider reading) - { - try - { - Directory.CreateDirectory(Path.GetDirectoryName(ClaudeCachePath)!); - var tmp = ClaudeCachePath + ".tmp"; - AppPaths.WriteAllTextPrivate(tmp, JsonSerializer.Serialize(reading, ConfigStore.WriteOpts)); - File.Move(tmp, ClaudeCachePath, overwrite: true); - } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) - { - log.LogDebug("claude quota cache: {Msg}", ex.Message); - } - } + internal void SaveClaudeCache(QuotaProvider reading) => + WriteShared(ClaudeCachePath, JsonSerializer.Serialize(reading, ConfigStore.WriteOpts)); private async Task RunUsageLoopAsync(CancellationToken ct) { @@ -275,8 +280,7 @@ private async Task RunUsageLoopAsync(CancellationToken ct) _nextCodexBar = Environment.TickCount64 + 60_000; } } - try { _codex = ReadCodex(); } - catch (Exception ex) { _codex = Fail("codex", "Codex", ex.Message); } + CodexTick(); if (Environment.TickCount64 >= _nextAntigravity) { @@ -284,82 +288,292 @@ private async Task RunUsageLoopAsync(CancellationToken ct) _nextAntigravity = Environment.TickCount64 + (ok ? 60_000 : 30_000); } - if (Environment.TickCount64 >= _nextClaude) - { - // Every 3 minutes when healthy; on errors back off, and never ask again sooner than a 429 says. - var ok = await RefreshClaude(ct); - _claudeFailures = ok ? 0 : _claudeFailures + 1; - _nextClaude = Environment.TickCount64 + (long)ClaudeDelay(ok, _claudeFailures, _claudeRetryAfter).TotalMilliseconds; - _claudeRetryAfter = null; - } + try { await ClaudeTickAsync(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), ct); } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; } + catch (Exception ex) { log.LogWarning("claude quota: {Msg}", ex.Message); } // never end the loop for Codex and Antigravity await Wake.Delay(TimeSpan.FromSeconds(30), ct); } } // ------------------------------------------------------------------ Claude - private async Task RefreshClaude(CancellationToken ct) + // The usage endpoint is rate limited per account and shared with Claude Code, so every request counts: + // - an expired, missing or refused token is waited out locally (the sign-in is read once a minute), never sent; + // - the schedule and the last reading are shared through files, so a restart (an update) or a second agent on + // this computer doesn't ask again before the 3 minutes or a Retry-After are over; + // - a token the server refused (401) is sent again only after 30 minutes; a renewed one is used within a minute. + + internal const long ClaudeHealthyMs = 180_000; + private const long ClaudeMaxWaitMs = 3_605_000; // the longest wait ClaudeDelay can ask for + private const long ClaudeTokenMarginMs = 60_000; // a token this close to expiry would be refused on the way + internal const int ClaudeOfflineRetries = 3; // quick retries while the network is not reachable + internal const long ClaudeOfflineRetryMs = 30_000; + private const long ClaudeUnrecognizedMs = 900_000; + private const long ClaudeTokenRecheckMs = 60_000; + private const long ClaudeRefusedRetryMs = 1_800_000; // a refusal may be a passing one (a proxy, an outage) + + private int _claudeOffline; // consecutive requests that could not reach the server + private string? _claudeRefused; // fingerprint of the token the server refused (never the token itself) + private long _claudeRefusedAt; + private bool _claudeAwaitingToken; // expired, missing or refused: only the sign-in is read until it changes + private long _claudeCredsReadAt; + + /// The shared schedule: when the next request may go out, and the message to show until then. + /// Fingerprint (a hash prefix, not the token) of the token Anthropic refused, and when. + private sealed record ClaudeSchedule(long NextAt, int Failures, string? Error, string? Refused = null, long RefusedAt = 0); + + internal string ClaudeSchedulePath => + Path.Combine(Path.GetDirectoryName(ClaudeCachePath)!, Path.GetFileNameWithoutExtension(ClaudeCachePath) + "-schedule.json"); + + private enum ClaudeResult { Ok, Limited, Refused, Offline, Unrecognized, Failed } + + /// One pass of the usage loop for Claude, at wall-clock time . + internal async Task ClaudeTickAsync(long nowMs, CancellationToken ct) { - var path = Path.Combine(Home, ".claude", ".credentials.json"); + // The sign-in is read when a request is due, and once a minute while waiting for Claude Code to renew an + // expired or refused token (on macOS each read starts the `security` tool). + // The schedule is wall-clock time, shared with other agents through a file. A clock set back (an NTP correction, + // a resumed VM) would otherwise hold it up for as long as it moved: no wait is longer than ClaudeMaxWaitMs. + if (_claudeNextAt - nowMs > ClaudeMaxWaitMs) _claudeNextAt = nowMs + ClaudeMaxWaitMs; + if (_claudeCredsReadAt > nowMs) _claudeCredsReadAt = 0; + if (_claudeAwaitingToken ? nowMs - _claudeCredsReadAt < ClaudeTokenRecheckMs : nowMs < _claudeNextAt) return; + _claudeCredsReadAt = nowMs; + var clock = System.Diagnostics.Stopwatch.StartNew(); // the reads below (the Keychain, the shared files) take time too + + // Claude Code may be rewriting the file right now: try again on the next pass string? json = null; - // Claude Code may be rewriting the file right now: try again on the next round instead of ending the service - try { if (File.Exists(path)) json = await File.ReadAllTextAsync(path, ct); } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { return false; } + try { if (File.Exists(CredentialsPath)) json = await File.ReadAllTextAsync(CredentialsPath, ct); } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { return; } #if !WINDOWS // macOS: Claude Code stores the credentials in the login Keychain instead of a file (read-only access). - if (json is null && OperatingSystem.IsMacOS()) json = Sh.Run("security", "find-generic-password", "-s", "Claude Code-credentials", "-w")?.Trim(); + if (json is null && OperatingSystem.IsMacOS() && CredentialsPath == DefaultCredentialsPath) + json = Sh.Run("security", "find-generic-password", "-s", "Claude Code-credentials", "-w")?.Trim(); #endif - if (string.IsNullOrEmpty(json)) { _claude = null; return true; } + if (string.IsNullOrEmpty(json)) + { + // Claude Code is not set up here + _claude = null; + _claudeAwaitingToken = false; + _claudeNextAt = nowMs + ClaudeHealthyMs; + return; + } - string plan = "Claude"; + string plan, token; + long expires; try { using var creds = JsonDocument.Parse(json); - var o = creds.RootElement.GetProperty("claudeAiOauth"); - plan = PlanLabel(Str(o, "subscriptionType"), Str(o, "rateLimitTier")); - var token = Str(o, "accessToken"); - var expires = o.TryGetProperty("expiresAt", out var e) && e.TryGetInt64(out var ms) ? ms : 0; - - if (string.IsNullOrEmpty(token)) { _claude = Keep(plan, "Not signed in to Claude Code"); return false; } - if (expires > 0 && expires < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()) + if (creds.RootElement.ValueKind != JsonValueKind.Object + || !creds.RootElement.TryGetProperty("claudeAiOauth", out var o) || o.ValueKind != JsonValueKind.Object) { - _claude = Keep(plan, "Token expired; it will refresh when Claude Code runs"); - return false; + _claude = Keep("Claude", "Not signed in to Claude Code"); + _claudeAwaitingToken = true; + return; } + plan = PlanLabel(Str(o, "subscriptionType"), Str(o, "rateLimitTier")); + token = Str(o, "accessToken") ?? ""; + // TryGetInt64 throws on a non-number; an unknown expiry is left to the server to judge + expires = o.TryGetProperty("expiresAt", out var e) && e.ValueKind == JsonValueKind.Number && e.TryGetInt64(out var ms) ? ms : 0; + } + catch (JsonException) + { + return; // read mid-write; the next pass reads the whole file + } + var print = token.Length == 0 ? "" : Fingerprint(token); + var wait = token.Length == 0 ? "Not signed in to Claude Code" + : expires > 0 && expires - nowMs < ClaudeTokenMarginMs ? "Token expired; it will refresh when Claude Code runs" + : print == _claudeRefused && nowMs - _claudeRefusedAt is >= 0 and < ClaudeRefusedRetryMs ? RefusedMessage : null; + _claudeAwaitingToken = wait is not null; + if (wait is not null) + { + _claude = Keep(plan, wait); + return; + } + + if (nowMs < _claudeNextAt) return; + if (AdoptShared(plan, print, nowMs) || nowMs < _claudeNextAt) return; + + var (result, retryAfter) = await FetchClaude(plan, token, nowMs, ct); + var answeredMs = nowMs + clock.ElapsedMilliseconds; + long next; + switch (result) + { + case ClaudeResult.Ok: + _claudeFailures = _claudeOffline = 0; + next = nowMs + ClaudeHealthyMs; + break; + case ClaudeResult.Refused: + _claudeRefused = print; + _claudeRefusedAt = nowMs; + _claudeAwaitingToken = true; + next = nowMs + ClaudeTokenRecheckMs; + break; + case ClaudeResult.Offline when _claudeOffline <= ClaudeOfflineRetries: + // usually a computer that just woke up: keep the reading (its age is shown) and look again soon + next = nowMs + ClaudeOfflineRetryMs; + break; + case ClaudeResult.Unrecognized: + _claudeOffline = 0; + next = nowMs + Math.Max(ClaudeUnrecognizedMs, (long)ClaudeDelay(false, ++_claudeFailures, null).TotalMilliseconds); + break; + default: + if (result != ClaudeResult.Offline) _claudeOffline = 0; + // a Retry-After counts from the answer, not from when the request went out + next = (retryAfter is null ? nowMs : answeredMs) + (long)ClaudeDelay(false, ++_claudeFailures, retryAfter).TotalMilliseconds; + if (result == ClaudeResult.Limited) + _claude = Keep(plan, $"Anthropic is limiting quota checks; trying again at {DateTimeOffset.FromUnixTimeMilliseconds(next).ToLocalTime():HH:mm}"); + break; + } + // Another agent may have written the schedule while this request ran: keep a longer wait it was given, and a + // refusal it got, unless this request just showed that very token works. + var error = _claude?.Error; + var (refused, refusedAt) = (_claudeRefused, _claudeRefusedAt); + if (ReadClaudeSchedule() is { } other) + { + if (other.NextAt > next && other.NextAt - answeredMs <= ClaudeMaxWaitMs) + (next, error) = (other.NextAt, other.Error ?? error); + if (other.Refused is { } theirs && (theirs != refused || other.RefusedAt > refusedAt) + && answeredMs - other.RefusedAt is >= 0 and < ClaudeRefusedRetryMs + && !(result == ClaudeResult.Ok && theirs == print)) + (refused, refusedAt) = (theirs, other.RefusedAt); + } + _claudeNextAt = next; + SaveClaudeSchedule(new ClaudeSchedule(next, _claudeFailures, error, refused, refusedAt)); + } + + private const string RefusedMessage = "Anthropic did not accept the sign-in; it will refresh when Claude Code runs"; + + /// Sends the one request and sets from its answer. + private async Task<(ClaudeResult, TimeSpan?)> FetchClaude(string plan, string token, long nowMs, CancellationToken ct) + { + try + { using var req = new HttpRequestMessage(HttpMethod.Get, "https://api.anthropic.com/api/oauth/usage"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); req.Headers.Add("anthropic-beta", "oauth-2025-04-20"); - using var res = await _http.SendAsync(req, ct); - if (res.StatusCode is System.Net.HttpStatusCode.TooManyRequests or System.Net.HttpStatusCode.ServiceUnavailable) + using var res = await Http.SendAsync(req, ct); + _claudeOffline = 0; + if (res.StatusCode is HttpStatusCode.TooManyRequests or HttpStatusCode.ServiceUnavailable) + // Asking again before Retry-After only keeps the limit in place, so wait at least that long. + return (ClaudeResult.Limited, RetryAfter(res.Headers.RetryAfter) ?? TimeSpan.FromMinutes(5)); + if (res.StatusCode == HttpStatusCode.Unauthorized) { - // The usage endpoint is rate limited per account (Claude Code and other tools use it too). Asking again - // before Retry-After only keeps the limit in place, so wait at least that long. - _claudeRetryAfter = RetryAfter(res.Headers.RetryAfter) ?? TimeSpan.FromMinutes(5); - var at = DateTime.Now + ClaudeDelay(false, _claudeFailures + 1, _claudeRetryAfter); - _claude = Keep(plan, $"Anthropic is limiting quota checks; trying again at {at:HH:mm}"); - return false; + _claude = Keep(plan, RefusedMessage); + return (ClaudeResult.Refused, null); } if (!res.IsSuccessStatusCode) { _claude = Keep(plan, $"Could not fetch quota (HTTP {(int)res.StatusCode})"); - return false; + return (ClaudeResult.Failed, null); + } + var body = await res.Content.ReadAsStringAsync(ct); + List limits = []; + string? extra = null; + try + { + using var doc = JsonDocument.Parse(body); + if (doc.RootElement.ValueKind == JsonValueKind.Object) + { + limits = ParseClaudeLimits(doc.RootElement); + extra = ClaudeExtra(doc.RootElement); + } + } + catch (JsonException) { } + if (limits.Count == 0) + { + // a captive portal, or a reply format this version doesn't know: keep the last reading and the cache + log.LogDebug("claude quota: unrecognized reply ({Length} bytes)", body.Length); + _claude = Keep(plan, "Anthropic sent a quota reply this version doesn't recognize"); + return (ClaudeResult.Unrecognized, null); } - using var doc = JsonDocument.Parse(await res.Content.ReadAsStringAsync(ct)); - _claude = new QuotaProvider("claude", "Claude", plan, ParseClaudeLimits(doc.RootElement), - ClaudeExtra(doc.RootElement), DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), null); + _claude = new QuotaProvider("claude", "Claude", plan, limits, extra, nowMs, null); SaveClaudeCache(_claude); - return true; + return (ClaudeResult.Ok, null); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } + catch (HttpRequestException ex) when (ex.HttpRequestError is HttpRequestError.ConnectionError or HttpRequestError.NameResolutionError) + { + // the request never reached the server: show it only once the quick retries are used up, or when there is + // no reading to show instead + log.LogDebug("claude quota: {Msg}", ex.Message); + if (++_claudeOffline > ClaudeOfflineRetries || _claude is not { Limits.Count: > 0 }) + _claude = Keep(plan, "Could not reach Anthropic: " + ex.Message); + return (ClaudeResult.Offline, null); + } catch (Exception ex) { log.LogDebug("claude quota: {Msg}", ex.Message); _claude = Keep(plan, "Could not fetch quota: " + ex.Message); - return false; + return (ClaudeResult.Failed, null); + } + } + + /// + /// Takes over what another agent on this computer (or this one before a restart) already knows: a newer reading, + /// and the time the next request may go out. + /// + /// True when the token was refused before (by another agent, or before a restart): don't send it. + private bool AdoptShared(string plan, string print, long nowMs) + { + if (ReadClaudeCache(nowMs) is { UpdatedAt: { } at } cached && at > (_claude?.UpdatedAt ?? 0) && at <= nowMs) + _claude = cached with { Plan = plan }; + if (_claude?.UpdatedAt is { } updated && updated <= nowMs && nowMs - updated < ClaudeHealthyMs) + _claudeNextAt = Math.Max(_claudeNextAt, updated + ClaudeHealthyMs); + + var shared = ReadClaudeSchedule(); + if (shared is { Refused: { } refused } && refused == print && nowMs - shared.RefusedAt is >= 0 and < ClaudeRefusedRetryMs) + { + (_claudeRefused, _claudeRefusedAt, _claudeAwaitingToken) = (refused, shared.RefusedAt, true); + _claude = Keep(plan, RefusedMessage); + return true; + } + // A schedule further ahead than any wait was written before the clock was set back: it no longer applies. One + // that ran out recently still carries the failure count, so a restart doesn't reset the back-off. + if (shared is null || shared.NextAt - nowMs > ClaudeMaxWaitMs || nowMs - shared.NextAt > ClaudeMaxWaitMs) return false; + _claudeFailures = Math.Max(_claudeFailures, shared.Failures); + if (shared.NextAt <= nowMs) return false; + _claudeNextAt = Math.Max(_claudeNextAt, shared.NextAt); + if (shared.Error is { Length: > 0 } error) _claude = Keep(plan, error); + return false; + } + + private static string Fingerprint(string token) => + Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(Encoding.UTF8.GetBytes(token)))[..16]; + + private ClaudeSchedule? ReadClaudeSchedule() + { + try + { + return File.Exists(ClaudeSchedulePath) + ? JsonSerializer.Deserialize(File.ReadAllText(ClaudeSchedulePath), ConfigStore.WriteOpts) : null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException or NotSupportedException) + { + log.LogDebug("claude quota schedule: {Msg}", ex.Message); + return null; + } + } + + private void SaveClaudeSchedule(ClaudeSchedule schedule) => + WriteShared(ClaudeSchedulePath, JsonSerializer.Serialize(schedule, ConfigStore.WriteOpts)); + + /// Atomic replace through a temporary file of this writer's own, so two agents can't trip over each other. + private void WriteShared(string path, string text) + { + var tmp = $"{path}.{Guid.NewGuid():N}.tmp"; + try + { + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + AppPaths.WriteAllTextPrivate(tmp, text); + File.Move(tmp, path, overwrite: true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + log.LogDebug("claude quota files: {Msg}", ex.Message); + try { File.Delete(tmp); } catch (Exception e) when (e is IOException or UnauthorizedAccessException) { } } } - /// On errors, keeps the last good values and attaches the error. /// /// When to check the Claude quota next: 3 minutes after a success; after a failure 1, 2, 4 … minutes (at most 15), /// and never sooner than a Retry-After (at most an hour). @@ -378,6 +592,7 @@ internal static TimeSpan ClaudeDelay(bool ok, int failures, TimeSpan? retryAfter : header?.Date is { } date ? (date - DateTimeOffset.UtcNow is var left && left > TimeSpan.Zero ? left : TimeSpan.Zero) : null; + /// On errors, keeps the last good values and attaches the error. private QuotaProvider Keep(string plan, string error) => _claude is { Limits.Count: > 0 } prev ? prev with { Plan = plan, Error = error } : new QuotaProvider("claude", "Claude", plan, [], null, null, error); @@ -432,9 +647,23 @@ private static string PlanLabel(string? sub, string? tier) private static partial Regex MaxTier(); // ------------------------------------------------------------------ Codex - private static QuotaProvider? ReadCodex() + /// Codex's session logs (read only). Tests point it at a folder of their own. + internal string CodexSessionsRoot { get; init; } = Path.Combine(Home, ".codex", "sessions"); + + /// One pass of the usage loop for Codex. + internal void CodexTick() { - var root = Path.Combine(Home, ".codex", "sessions"); + try { _codex = ReadCodex(); } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException && _codex is { Limits.Count: > 0 }) + { + log.LogDebug("codex quota: {Msg}", ex.Message); // the log is busy for a moment; it's read again in 30 s + } + catch (Exception ex) { _codex = Fail("codex", "Codex", ex.Message); } + } + + private QuotaProvider? ReadCodex() + { + var root = CodexSessionsRoot; if (!Directory.Exists(root)) return null; var files = new DirectoryInfo(root).EnumerateFiles("rollout-*.jsonl", SearchOption.AllDirectories); @@ -521,7 +750,10 @@ private static string PlanLabel(string? sub, string? tier) Long(last, "input_tokens"), Long(last, "output_tokens"), Long(token, "model_context_window"), updatedAt); } - /// Reads the last 1 MB of a file and returns the last line containing the given text. + /// + /// Reads the last 1 MB of a file and returns the last complete JSON line containing the given text. A line cut off + /// mid-write (Codex stopped, or the file read while it appends) is skipped for the one before it. + /// private static string? LastLineWith(string path, string needle) { using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); @@ -531,7 +763,15 @@ private static string PlanLabel(string? sub, string? tier) fs.ReadExactly(buf); var lines = Encoding.UTF8.GetString(buf).Split('\n'); for (var i = lines.Length - 1; i >= 1; i--) // the first line may be partial - if (lines[i].Contains(needle) && lines[i].Contains("\"primary\"")) return lines[i]; + { + if (!lines[i].Contains(needle) || !lines[i].Contains("\"primary\"")) continue; + try + { + using var _ = JsonDocument.Parse(lines[i]); + return lines[i]; + } + catch (JsonException) { } + } return null; } diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 7f58660..a69f43e 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -246,6 +246,9 @@ switchable ports). The panel keeps running over Wi-Fi while the USB power is off - **Claude quota:** read with the OAuth token Claude Code stores in `~/.claude/.credentials.json`, sent only to `api.anthropic.com/api/oauth/usage` (the endpoint behind Claude Code's `/usage`). The token is read-only: PhoneBox never refreshes it, so it can't interfere with Claude Code. This endpoint is undocumented and may change. + It is rate limited per account and shared with Claude Code, so PhoneBox asks at most every 3 minutes, and waits + longer after errors and as long as a `429` asks for, across restarts too. An expired or refused token is not sent: + PhoneBox waits until Claude Code renews it. - **Codex quota and sessions** are read from local files in `~/.codex/sessions`; Claude Code sessions from `~/.claude/sessions`. - **Native Antigravity quota:** the agent reads the running Antigravity server's port and CSRF token from its