Repository navigation
fix(rate-limits): unstick Claude "Limited" usage — respect Retry-After and feed live usage from session statuslines - #9617
Conversation
…from session statuslines The OAuth usage endpoint's 429 Retry-After (~50 min) was ignored, so the 30s-15min automated retry lanes kept landing inside the throttle window and the status bar stayed on a bare "Limited" indefinitely while Claude itself worked fine. - Respect Retry-After on 429: carry it through usageMetadata.retryAtMs and gate automated refetches (activation lane, poll cycles) until it expires; user-directed refreshes still bypass. - Keep the last-known usage snapshot visible through rate-limited windows (24h) instead of dropping it after the generic 30-minute stale threshold. - Add a managed Claude statusLine command that forwards each session's rate_limits (Claude Code >=2.1.80) to a new /statusline/claude loopback route, feeding live usage windows with zero usage-endpoint calls; OAuth polling pauses while the live feed is fresh. User-owned statusLine settings are never overwritten. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
📝 WalkthroughWalkthroughAdds Claude statusline payload parsing, platform-specific managed scripts, configuration lifecycle handling, and an HTTP endpoint that forwards parsed events. Wires forwarded events into rate-limit state with attribution, deduplication, live-feed freshness gating, and account-change handling. Extends OAuth 429 errors with parsed 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: ab7eb77b-da60-4a0f-84d5-f37aa161c28a
📒 Files selected for processing (20)
config/tsconfig.cli.jsonsrc/main/agent-hooks/managed-hook-stdin-lifecycle.test.tssrc/main/agent-hooks/managed-hook-timeout.test.tssrc/main/agent-hooks/server-claude-statusline.test.tssrc/main/agent-hooks/server.tssrc/main/claude/hook-service.test.tssrc/main/claude/hook-service.tssrc/main/claude/hook-settings.tssrc/main/claude/statusline-script.tssrc/main/index.tssrc/main/rate-limits/claude-fetcher.test.tssrc/main/rate-limits/claude-fetcher.tssrc/main/rate-limits/claude-oauth-usage-error.test.tssrc/main/rate-limits/claude-oauth-usage-error.tssrc/main/rate-limits/claude-usage-window.tssrc/main/rate-limits/service.test.tssrc/main/rate-limits/service.tssrc/shared/claude-statusline-rate-limits.test.tssrc/shared/claude-statusline-rate-limits.tssrc/shared/rate-limit-types.ts
…es only one Statusline payloads may report five_hour and seven_day independently; a partial post must not wipe the other bar to null. Also document the seconds-vs-ms epoch heuristic. Addresses CodeRabbit review on stablyai#9617. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
The OAuth polling endpoint is rate-limited; Claude's status often shows "Limited" until the next poll cycle, even when quota remains. Live posts from the statusline command update usage within 100ms, eliminating false "Limited" displays during active sessions. Manages install lifecycle via marker to respect user deletions. Handles Windows payload buffering and guards before curl spawn. Protects against live-post/OAuth-fetch races and cross-attribution during account switches. Gracefully tolerates schema drift in statusline parsing.
…e-limited' into dbachko/fix-claude-usage-limited # Conflicts: # src/main/rate-limits/service.ts
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 8fd9ef1c-c4df-4cad-9fca-ca04a9dcd7d1
📒 Files selected for processing (10)
src/main/agent-hooks/hook-stdin-contract.tssrc/main/claude/hook-service.test.tssrc/main/claude/hook-service.tssrc/main/claude/hook-settings.tssrc/main/claude/statusline-script.test.tssrc/main/claude/statusline-script.tssrc/main/rate-limits/service.test.tssrc/main/rate-limits/service.tssrc/shared/claude-statusline-rate-limits.test.tssrc/shared/claude-statusline-rate-limits.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/main/claude/statusline-script.ts
- src/main/rate-limits/service.ts
Capture usedPercent before ingesting and assert it remains unchanged, rather than checking for a specific value. This is more precise and less brittle when testing session switch isolation.
…r and feed live usage from session statuslines (stablyai#9617) * fix(rate-limits): unstick Claude "Limited" usage and feed live usage from session statuslines The OAuth usage endpoint's 429 Retry-After (~50 min) was ignored, so the 30s-15min automated retry lanes kept landing inside the throttle window and the status bar stayed on a bare "Limited" indefinitely while Claude itself worked fine. - Respect Retry-After on 429: carry it through usageMetadata.retryAtMs and gate automated refetches (activation lane, poll cycles) until it expires; user-directed refreshes still bypass. - Keep the last-known usage snapshot visible through rate-limited windows (24h) instead of dropping it after the generic 30-minute stale threshold. - Add a managed Claude statusLine command that forwards each session's rate_limits (Claude Code >=2.1.80) to a new /statusline/claude loopback route, feeding live usage windows with zero usage-endpoint calls; OAuth polling pauses while the live feed is fresh. User-owned statusLine settings are never overwritten. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(rate-limits): keep last-known window when a statusline post carries only one Statusline payloads may report five_hour and seven_day independently; a partial post must not wipe the other bar to null. Also document the seconds-vs-ms epoch heuristic. Addresses CodeRabbit review on stablyai#9617. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(rate-limits): unstick Claude usage with live statusline feed The OAuth polling endpoint is rate-limited; Claude's status often shows "Limited" until the next poll cycle, even when quota remains. Live posts from the statusline command update usage within 100ms, eliminating false "Limited" displays during active sessions. Manages install lifecycle via marker to respect user deletions. Handles Windows payload buffering and guards before curl spawn. Protects against live-post/OAuth-fetch races and cross-attribution during account switches. Gracefully tolerates schema drift in statusline parsing. * test(rate-limits): assert stale outgoing post doesn't affect incoming Capture usedPercent before ingesting and assert it remains unchanged, rather than checking for a specific value. This is more precise and less brittle when testing session switch isolation. --------- Co-authored-by: Dzmitry Bachko <[email protected]> Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Jinjing <[email protected]>
Summary
Fixes #9616
Claude usage in the status bar could get stuck on a bare "Limited — Claude usage is rate limited right now." indefinitely while Claude Code itself worked fine in every terminal. Root cause (confirmed with a live probe): the OAuth usage endpoint returns
429withretry-after: ~3000s, Orca discards that header, and the 30s→15min automated retry lanes keep landing inside the throttle window — a self-sustaining 429 loop. On top of that, the generic 30-minute stale policy drops the last good snapshot before the ~50-minute throttle can clear, leaving no usage bars at all.This PR fixes the loop and adds a zero-cost live usage source:
Retry-Afteron 429 (claude-oauth-usage-error.ts): parsed (seconds or HTTP-date, capped at 24h) and carried throughusageMetadata.retryAtMs. Automated refetches — the activation-retry lane ingetActiveWindowRefreshPlanand both fetch cycles — now wait it out; the status-bar refresh button still forces a real attempt.applyStalePolicyretains the previous snapshot for up to 24h when the fresh failure israte-limited(quota display is informational; a stale bar beats a bare "Limited"). The existing renderer already shows stale windows + the error note, so no UI changes were needed.rate_limits(5h/7dused_percentage+resets_at) to thestatusLinecommand on every turn, piggybacked on Messages API responses. A new managed statusline script (installed alongside the existing managed hooks, locally and on SSH remotes) forwards it to a new/statusline/claudeloopback route →RateLimitService.ingestLiveClaudeRateLimits(). Live posts clear stuck error states, are attributed to the selected account by comparing the session'sCLAUDE_CONFIG_DIRagainst a snapshot captured during fetch cycles (no per-post auth sync), and are deduped (30s) so streaming sessions don't spam renderer pushes. While the live feed is fresh (<5 min), automated OAuth polling is skipped entirely — which also removes the polling pressure that caused the 429s in the first place. A user-ownedstatusLinecommand is never overwritten (single settings slot; managed-command matcher, same sweep semantics as hooks), and the managed script emits no stdout so the in-terminal status line stays visually unchanged.Screenshots
Before — status bar and popover stuck on "Limited" with no usage data, while Claude's own in-terminal statusline showed correct 5h/weekly usage the whole time:
After: no new UI surfaces — the existing status-bar states just behave correctly: usage bars stay visible (with the stale-warning icon + "Limited" note) through a 429 window, and live sessions update the bars on every turn.
Testing
pnpm lint— passes except 2 pre-existingswitch-exhaustiveness-checkerrors insrc/renderer/src/components/skills/skill-freshness-group.tsxandsrc/main/daemon/daemon-server.ts; both files are untouched by this PR and byte-identical toorigin/mainpnpm typecheckpnpm test— 32,871 passed; the only failures are in files byte-identical toorigin/main(src/main/ipc/pty.test.tsshell-ready-marker timing — the same pre-existing set noted in fix(pr-comments): let users mark comment authors as bots for the Humans/Bots filter #7598 — plus environment-flaky relay/daemon/ssh suites that pass or fail nondeterministically across runs in this environment); every suite touched by this PR passespnpm buildclaude-oauth-usage-error.test.ts(new): Retry-After parsing — numeric, HTTP-date, 24h cap, invalid/non-positive, non-429claude-fetcher.test.ts: 429 results carryretryAtMs; absent header ⇒ no gateservice.test.ts: automated refetches wait out Retry-After then recover; manual refresh bypasses; rate-limited windows keep last-known usage past the 30-min threshold; statusline ingest clears errors and pauses OAuth polling while fresh; posts dropped before attribution is known or on config-dir mismatch; identical-post dedupeclaude-statusline-rate-limits.test.ts(new): payload parser incl. malformed bodiesserver-claude-statusline.test.ts(new): real HTTP round-trip — token rejection, fail-open on junk, listener dispatchhook-service.test.ts: managed statusLine install (local + remote script/settings shape), user-owned statusLine preserved on install and remove, managed statusLine removed on remove, OpenClaude excludedstatusLine(schema has notimeoutfield)retry-after: 3037) with the exact headers Orca sends before writing the fixAI Review Report
Reviewed the full diff against the repo checklist:
.shand Windows.cmd(fully-qualified%SystemRoot%\System32\curl.exe, shared stdin-drain epilogue, endpoint-file refresh) — and settings commands use the existingwrapWindowsGitBashHookCommand/wrapPosixHookCommandwrappers. The.cmdvariant skips the client-siderate_limitspre-check (payload substring checks are impractical in batch); the server validates payloads regardless. No shortcuts, labels, or path joins added outside existing helpers.installRemoteships the POSIX statusline script + settings to SSH remotes. Flagged: relay-hosted hook receivers (SSH relay, WSL guest relay) do not forward/statusline/claudeyet — those posts 404 fail-open and remote sessions simply keep the OAuth path (now Retry-After-gated). Local sessions on all three OSes get the live feed. Follow-up noted below.retryAtMsis only ever set by the Claude OAuth path; the plan-level gate is a safe no-op for providers that never set it).rate_limits; ingest uses a cached auth snapshot (no per-post keychain/auth sync, which is serialized and side-effectful) and dedupes identical windows within 30s soupdateState/renderer pushes don't churn. Gated cycles skip the Claude network fetch entirely, reducing total API traffic versus main.shouldApplyClaudeexcludes gated passthroughs); account/target switches clear the attribution snapshot so mid-switch posts from the outgoing account are dropped; the deferred-by-live-session and CLI-fallback paths are unchanged.Security Audit
/statusline/clauderides the existing loopback-only (127.0.0.1) hook server behind the per-instance random-UUID token header, checked before any body parsing; slowloris timeout and body-size cap come from the sharedreadRequestBody. Malformed input fails open with 204 and no state change.JSON.parsed inside try/catch with strict shape validation (typeof/Number.isFiniteon every consumed field);configDiris only compared for equality against Orca's own captured value — never used as a path, command, or interpolated string.Retry-Afteris clamped to 24h so a hostile/corrupt header can't disable usage refresh for days.payload@-, never argv), token via env,curl.exefully qualified on Windows to prevent repo-local binary hijack.writeHooksJson; only the managed statusLine slot (matched by the managed-script needle) is ever created/removed — user statusLine commands are preserved on install and remove, covered by tests.Notes
statusLinesetting itself is long-supported and older CLIs just omitrate_limits./statusline/claudethrough the SSH/WSL relay envelope so remote sessions also feed live usage (currently they fail open to OAuth polling); consider the same Retry-After plumbing for other providers if their endpoints start throttling.X: @dbachko
Generated with Devin