Skip to content

fix(rate-limits): unstick Claude "Limited" usage — respect Retry-After and feed live usage from session statuslines - #9617

Merged
AmethystLiang merged 5 commits into
stablyai:mainfrom
dbachko:dbachko/fix-claude-usage-limited
Jul 21, 2026
Merged

AmethystLiang merged 5 commits into
stablyai:mainfrom
dbachko:dbachko/fix-claude-usage-limited

Conversation

@dbachko

@dbachko dbachko commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

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 429 with retry-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:

  • Respect Retry-After on 429 (claude-oauth-usage-error.ts): parsed (seconds or HTTP-date, capped at 24h) and carried through usageMetadata.retryAtMs. Automated refetches — the activation-retry lane in getActiveWindowRefreshPlan and both fetch cycles — now wait it out; the status-bar refresh button still forces a real attempt.
  • Keep last-known usage through rate-limited windows: applyStalePolicy retains the previous snapshot for up to 24h when the fresh failure is rate-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.
  • Live usage from session statuslines: Claude Code ≥ 2.1.80 pipes rate_limits (5h/7d used_percentage + resets_at) to the statusLine command 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/claude loopback route → RateLimitService.ingestLiveClaudeRateLimits(). Live posts clear stuck error states, are attributed to the selected account by comparing the session's CLAUDE_CONFIG_DIR against 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-owned statusLine command 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:

Claude usage popover stuck on Limited with no usage bars

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-existing switch-exhaustiveness-check errors in src/renderer/src/components/skills/skill-freshness-group.tsx and src/main/daemon/daemon-server.ts; both files are untouched by this PR and byte-identical to origin/main
  • pnpm typecheck
  • pnpm test — 32,871 passed; the only failures are in files byte-identical to origin/main (src/main/ipc/pty.test.ts shell-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 passes
  • pnpm build
  • Added or updated high-quality tests that would catch regressions:
    • claude-oauth-usage-error.test.ts (new): Retry-After parsing — numeric, HTTP-date, 24h cap, invalid/non-positive, non-429
    • claude-fetcher.test.ts: 429 results carry retryAtMs; absent header ⇒ no gate
    • service.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 dedupe
    • claude-statusline-rate-limits.test.ts (new): payload parser incl. malformed bodies
    • server-claude-statusline.test.ts (new): real HTTP round-trip — token rejection, fail-open on junk, listener dispatch
    • hook-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 excluded
    • Updated contract suites: stdin-lifecycle now executes the statusline script too; timeout contract exempts statusLine (schema has no timeout field)
  • Manual: reproduced the live 429 (retry-after: 3037) with the exact headers Orca sends before writing the fix

AI Review Report

Reviewed the full diff against the repo checklist:

  • Cross-platform (macOS/Linux/Windows): statusline script ships both variants — POSIX .sh and Windows .cmd (fully-qualified %SystemRoot%\System32\curl.exe, shared stdin-drain epilogue, endpoint-file refresh) — and settings commands use the existing wrapWindowsGitBashHookCommand/wrapPosixHookCommand wrappers. The .cmd variant skips the client-side rate_limits pre-check (payload substring checks are impractical in batch); the server validates payloads regardless. No shortcuts, labels, or path joins added outside existing helpers.
  • SSH/remote/local: installRemote ships the POSIX statusline script + settings to SSH remotes. Flagged: relay-hosted hook receivers (SSH relay, WSL guest relay) do not forward /statusline/claude yet — 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.
  • Agent/integration neutrality: Claude-only by design; OpenClaude is explicitly excluded from the statusLine install so its sessions can't misattribute usage to the Claude provider. Other providers' retry lanes are unaffected (retryAtMs is only ever set by the Claude OAuth path; the plan-level gate is a safe no-op for providers that never set it).
  • Performance: statusline invocations run ≤ every 300ms during streaming — the POSIX script exits before spawning curl when the payload has no 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 so updateState/renderer pushes don't churn. Gated cycles skip the Claude network fetch entirely, reducing total API traffic versus main.
  • Behavior risks checked: gated full cycles don't grow the failure streak or reset stale-policy clocks (shouldApplyClaude excludes 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

  • Endpoint exposure: /statusline/claude rides 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 shared readRequestBody. Malformed input fails open with 204 and no state change.
  • Input handling: the payload is JSON.parsed inside try/catch with strict shape validation (typeof/Number.isFinite on every consumed field); configDir is only compared for equality against Orca's own captured value — never used as a path, command, or interpolated string. Retry-After is clamped to 24h so a hostile/corrupt header can't disable usage refresh for days.
  • Command execution: the managed scripts reuse the audited hook-script patterns — payload piped to curl via stdin (payload@-, never argv), token via env, curl.exe fully qualified on Windows to prevent repo-local binary hijack.
  • Settings writes: atomic temp-file + rename via the existing 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.
  • Secrets/deps: no new dependencies; no secrets logged or persisted (the hook token already lived in the endpoint file; unchanged).

Notes

  • The statusline feed requires managed agent status hooks to be enabled (it installs alongside them) and Claude Code ≥ 2.1.80 with a Claude.ai subscriber session; anything older/API-key simply never posts and the OAuth path (now Retry-After-aware) covers it. No version gating needed — the statusLine setting itself is long-supported and older CLIs just omit rate_limits.
  • The Fable scoped weekly window is not present in statusline payloads; the last OAuth-provided value is carried through live updates and refreshes on manual refresh or once the live feed goes idle.
  • Follow-up: forward /statusline/claude through 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.
  • Related open issues in the same "stuck usage state" class that this does not fully close but should improve (live posts now clear stale Claude error states): Usage panel stuck on "Waiting for Claude session" after the last live Claude terminal exits #9324, [Bug]: (Does not affect normal use) Claude Code usage status stuck on "Refreshing sign-in" and does not update #8974.

X: @dbachko

Generated with Devin

…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>
@coderabbitai

coderabbitai Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds 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 Retry-After timestamps, updates automated and forced refresh behavior, preserves rate-limited snapshots, and centralizes Claude usage-window mapping. Adds tests for parsing, installation, endpoint behavior, retry handling, polling, and live ingestion.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.51% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is specific, concise, and matches the main change set.
Description check ✅ Passed The description follows the template with all required sections filled in.
Linked Issues check ✅ Passed The changes address #9616 by honoring Retry-After, preserving stale usage, and ingesting live statusline data.
Out of Scope Changes check ✅ Passed The diff stays focused on Claude rate-limit handling, statusline ingestion, and related tests.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: ab7eb77b-da60-4a0f-84d5-f37aa161c28a

📥 Commits

Reviewing files that changed from the base of the PR and between e218dfb and f44acf0.

📒 Files selected for processing (20)
  • config/tsconfig.cli.json
  • src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts
  • src/main/agent-hooks/managed-hook-timeout.test.ts
  • src/main/agent-hooks/server-claude-statusline.test.ts
  • src/main/agent-hooks/server.ts
  • src/main/claude/hook-service.test.ts
  • src/main/claude/hook-service.ts
  • src/main/claude/hook-settings.ts
  • src/main/claude/statusline-script.ts
  • src/main/index.ts
  • src/main/rate-limits/claude-fetcher.test.ts
  • src/main/rate-limits/claude-fetcher.ts
  • src/main/rate-limits/claude-oauth-usage-error.test.ts
  • src/main/rate-limits/claude-oauth-usage-error.ts
  • src/main/rate-limits/claude-usage-window.ts
  • src/main/rate-limits/service.test.ts
  • src/main/rate-limits/service.ts
  • src/shared/claude-statusline-rate-limits.test.ts
  • src/shared/claude-statusline-rate-limits.ts
  • src/shared/rate-limit-types.ts

Comment thread src/main/rate-limits/service.ts Resolved
dbachko and others added 3 commits July 20, 2026 22:12
…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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 8fd9ef1c-c4df-4cad-9fca-ca04a9dcd7d1

📥 Commits

Reviewing files that changed from the base of the PR and between 229106c and ed26f26.

📒 Files selected for processing (10)
  • src/main/agent-hooks/hook-stdin-contract.ts
  • src/main/claude/hook-service.test.ts
  • src/main/claude/hook-service.ts
  • src/main/claude/hook-settings.ts
  • src/main/claude/statusline-script.test.ts
  • src/main/claude/statusline-script.ts
  • src/main/rate-limits/service.test.ts
  • src/main/rate-limits/service.ts
  • src/shared/claude-statusline-rate-limits.test.ts
  • src/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

Comment thread src/main/rate-limits/service.test.ts Resolved
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.
@AmethystLiang
AmethystLiang merged commit c24ebca into stablyai:main Jul 21, 2026
2 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Claude usage stuck on "Limited" — usage-endpoint 429 Retry-After ignored, retries keep the throttle alive

2 participants