Skip to content

fix(rate-limits): respect Claude usage Retry-After across accounts - #26589

Open
Noah-TaeHwan wants to merge 1 commit into
stablyai:mainfrom
Noah-TaeHwan:fix/claude-usage-retry-after
Open

Noah-TaeHwan wants to merge 1 commit into
stablyai:mainfrom
Noah-TaeHwan:fix/claude-usage-retry-after

Conversation

@Noah-TaeHwan

Copy link
Copy Markdown

Fixes #26588

ELI5

After a usage request returns 429, opening the account list, pressing Refresh, or switching back to that account must wait until the server allows another request. The app now remembers that wait for each profile and keeps the last usage values and their original timestamp. Other profiles can still refresh.

What Changed

  • Add an account-specific blockedUntil and last successful quota snapshot beside the existing usage caches, using the canonical host data directory and existing durable usage writer. The key hashes the actual profile folder, so token replacement does not reset the wait and different runtime folders stay separate.
  • Enforce the wait in the shared active/inactive fetcher before reading credentials or making a request. Keep the active/full-cycle Retry-After gates binding even with force: true; force still bypasses normal refresh intervals.
  • Reuse Retry-After parsing, its 24-hour cap, the existing 30-second polling floor and 15-minute default cadence when a 429 header is unusable. Coalesce overlapping reads for the same profile.
  • Validate and persist only quota fields and timestamps. No tokens, raw responses, profile paths, or authentication metadata are saved. Retain the existing live-usage feed behavior.

Why

The 60-second inactive-list debounce cannot protect a longer server wait, and a user refresh must not override a 429. Applying the gate where all profile reads converge avoids a separate retry policy in every caller. A small sidecar reuses the existing persistence machinery without rewriting the analytics history on every quota read.

Linked Issue

Addresses the usage-429 retry behavior reported in #9616; related to per-account retention in #14833. Builds on the Retry-After/live-feed work in #9617. Open #18746 adds refreshes on popover open and Refresh; this change is complementary — whichever trigger fires, each account's Retry-After wait is honored. It does not claim to cover the broader scope of #18736.

Visual Proof

Before/after desktop screenshots or a recording have not been captured. This changes refresh behavior, so interaction proof remains pending. Mocked request-count evidence is available in tests-before-final.log and tests-after.log.

Testing

Environment: macOS, Node 24.21.0, pnpm 12.8.1, Bun 1.4.2. Root and separate mobile dependencies installed with pnpm install --frozen-lockfile; manifests and lockfiles are unchanged. All test requests use mocks.

Fix round 2 (Node 24.21.0 at /opt/homebrew/opt/node@24/bin, ORCA_BACKGROUND_LAUNCH=1): a transient EBUSY on the first cache read is retried on the next Refresh. Rejected reads are discarded; successfully loaded account waits remain cached. All usage/profile requests are mocked.

Round 2 check Raw output / result
New test against 7316356349: corepack pnpm test:node src/main/rate-limits/service-claude-retry-after.test.ts -t 'retries a transient cache read failure' --reporter=verbose expected "vi.fn()" to be called 2 times, but got 1 times; Test Files 1 failed (1); Tests 1 failed | 12 skipped (13); exit 1; fix-round2-red.log
Same new test after the fix Test Files 1 passed (1); Tests 1 passed | 12 skipped (13); exit 0; fix-round2-green.log
corepack pnpm test:node src/main/rate-limits/service-claude-retry-after.test.ts src/main/rate-limits/claude-profile-usage.test.ts src/main/rate-limits/claude-oauth-usage-error.test.ts src/main/rate-limits/service-window-activation.test.ts src/main/rate-limits/service-refresh-orchestration.test.ts --maxWorkers=2 Test Files 5 passed (5); Tests 67 passed (67); exit 0; fix-round2-suites.log
corepack pnpm typecheck $ node config/scripts/run-typecheck-projects-in-parallel.mjs; exit 0; no diagnostics; fix-round2-typecheck.log
oxfmt --check on both round 2 files All matched files use the correct format.; exit 0
corepack pnpm run check:code-quality:changed Changed-code quality gate passed since 7c50009ca494.; zero new findings; exit 0; fix-round2-quality.log

Earlier validation below predates round 2 and is retained as historical evidence.

Command / state Actual output / result
New regression suite against original main sources at 7c50009ca494 Test Files 1 failed (1); Tests 12 failed (12); exit 1
pnpm test src/main/rate-limits/service-claude-retry-after.test.ts --reporter=verbose Test Files 1 passed (1); Tests 12 passed (12); exit 0
pnpm test src/main/rate-limits --maxWorkers=2 Test Files 56 passed | 1 skipped (57); Tests 785 passed | 1 skipped (786); exit 0
pnpm test:node src/main/rate-limits/service-claude-retry-after.test.ts src/main/rate-limits/claude-profile-usage.test.ts src/main/rate-limits/claude-oauth-usage-error.test.ts --maxWorkers=2 Test Files 3 passed (3); Tests 31 passed (31); exit 0
pnpm typecheck exit 0; no diagnostics
pnpm run check:code-quality:changed Changed-code quality gate passed since 7c50009ca494.; zero new findings across 10 files; exit 0
pnpm lint after mobile dependency installation exit 1: five existing import(no-cycle) warnings; identical clean-main failure reproduced in lint-main.log
pnpm build exit 1: desktop/web/mobile stages completed, then native packaging failed with lipo: no eligible inputs found; see build.log.

The final new tests were run against the original main implementation, then all owned fix files were restored byte-for-byte before passing runs. Coverage includes inactive reopening past its debounce, manual refresh, account switching, exact expiry, default waits, live usage, overlapping inactive/active reads, corrupt-cache handling, module restart, token replacement, quota retention, and credential exclusion.

The full test suite was not run. There are 11,887 test files under the root source/config/test trees; a full run was expected to exceed the ten-minute budget, so the relevant quota suites were selected. No claim is made that a full run was timed. The skipped quota test requires a real CLI and remains intentionally unexecuted.

Full lint's five warnings are at mobile/src/transport/client-context.tsx:45, mobile/src/transport/host-client-hooks.ts:6, mobile/src/terminal/document/mouse-report-cell.ts:2, and mobile/src/terminal/document/fit-scale.ts:1,9. These files are unchanged; the clean-main reproduction confirms the same failure.

  • I manually tested these changes locally
  • Automated tests added/updated

AI Disclosure

AI-assisted implementation and automated verification using GPT-6 via Codex. A separate review session (also GPT-6 via Codex) requested one change — a transient cache-read failure was memoized and blocked later refreshes; fixed with a regression test and re-reviewed (approve).

Review

Independent review is pending. Implementation uses the existing platform-aware filesystem writer and execution-host data directory; the changes stay in quota polling and its tests, using existing IPC fields and credential readers. Mocked tests ran on macOS under Bun and Node. Linux/Windows, SSH/WSL, and real desktop behavior remain unverified. The reviewer should examine profile-folder identity, stale/live-data retention, persistence failures and in-flight switching; test results are not product acceptance.

Agent skill upstream boundary

  • Not applicable: no upstream skill source or registry is copied into the app.

Notes

  • Corrupt/unreadable cache state stops quota requests rather than resetting an unknown wait. Later access retries the read; valid cache state is required before requests resume. Successfully loaded waits are retained.
  • A disk-write failure is logged and retains the in-memory wait; persistence across restart is then not guaranteed.
  • Full build remains blocked by missing native binary inputs to lipo. Native/build-script inputs are unchanged from main; a separate clean-main native replay was not performed.
  • No fork, push, issue/PR creation, comments, publication, or usage/profile endpoint calls were made.

Checklist

  • Scope and before/after behavior explained
  • Automated before/after evidence supplied
  • Desktop screenshots or recording supplied
  • Independent correctness/security/performance review completed
  • Cross-platform and SSH/WSL runtime behavior verified
  • Full lint, full test suite, and build all pass

계정별 서버 대기와 마지막 사용량을 기존 내구성 writer로 저장하고 강제 갱신과 계정 전환에서도 대기를 지킵니다.

모의 HTTP 회귀 테스트로 수정 전 실패와 수정 후 통과를 검증했습니다. 전체 lint의 기존 모바일 순환 경고와 네이티브 패키징 실패는 별도 증거에 기록했습니다.
@coderabbitai

coderabbitai Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

📝 Walkthrough

Walkthrough

Claude usage fetching now uses a persistent cache keyed by the resolved configuration directory. The cache retains usage snapshots and account-specific Retry-After windows, and shares overlapping requests for the same account. Missing or invalid 429 retry headers now receive a 15-minute delay, with a 30-second minimum for short delays. Service fetch paths honor active retry windows even during forced refreshes.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🟡 Moderate · up to a4efe

A damaged cache can prevent Claude usage updates for every account until it is repaired manually. An overlapping refresh can also be skipped after another request is cancelled. Fix cache recovery before merging.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: Claude usage Retry-After handling across accounts. It is concise and specific.
Description check ✅ Passed The description is detailed and covers the required change, rationale, linked issues, testing, limitations, AI disclosure, and checklist. It also documents pending visual proof, independent review, cr…
Linked Issues check ✅ Passed Direct issue #26588 requires a persisted, profile-specific Claude 429 wait for all usage paths. The PR adds fetchCachedClaudeUsage with canonical-host persistence, SHA-256 keys from resolved profile…
Out of Scope Changes check ✅ Passed The changed source files remain within Claude usage rate-limit fetching, Retry-After handling, persistence, and related service behavior. The changed tests verify those paths. The service comment upda…
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 8 functions across 10 files.
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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: Advanced
  • Run ID: 2c7b43ab-a0ae-48f6-a7e7-99ec641cd349
📥 Commits

Reviewing files that changed from the base of the PR and between 89ba968 and a4efe25.

📒 Files selected for processing (10)
  • src/main/rate-limits/claude-active-usage-fetch.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-profile-usage.test.ts
  • src/main/rate-limits/claude-usage-cache.ts
  • src/main/rate-limits/service-claude-retry-after.test.ts
  • src/main/rate-limits/service-window-activation.test.ts
  • src/main/rate-limits/service/service-fetch-queue.ts
  • src/main/rate-limits/service/service-full-cycle-preparation.ts
  • src/main/rate-limits/service/service-provider-cycles.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Comment on lines +85 to +97
fetch(
configDir: string,
fetchUsage: () => Promise<ProviderRateLimits>
): Promise<ProviderRateLimits> {
// 폴더는 토큰 교체 후에도 같고, WSL·SSH 프로필은 각 호스트의 실제 경로로 분리된다.
const key = createHash('sha256').update(resolve(configDir)).digest('hex')
const existing = this.pending.get(key)
if (existing) {
return existing
}
const operation = this.readUsage(key, fetchUsage).finally(() => this.pending.delete(key))
this.pending.set(key, operation)
return operation

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

set -eu
printf '%s\n' '--- cache ---'
nl -ba src/main/rate-limits/claude-usage-cache.ts | sed -n '1,180p'
printf '%s\n' '--- active fetch ---'
nl -ba src/main/rate-limits/claude-active-usage-fetch.ts | sed -n '1,130p'
printf '%s\n' '--- service callers ---'
nl -ba src/main/rate-limits/service/service-provider-cycles.ts | sed -n '70,135p'
nl -ba src/main/rate-limits/service/service-inactive-accounts.ts | sed -n '1,75p'
nl -ba src/main/rate-limits/claude-managed-account-usage.ts | sed -n '1,75p'
printf '%s\n' '--- abort/result definitions and references ---'
rg -n -F --glob '*.ts' -- 'abortedClaudeRateLimitResult' src/main/rate-limits
rg -n -F --glob '*.ts' -- 'fetchCachedClaudeUsage' src/main
printf '%s\n' '--- relevant tests ---'
rg -n -F --glob '*.test.ts' -- 'aborted|AbortController|fetchCachedClaudeUsage|refresh|inactive' src/main/rate-limits src/main/runtime | head -160
printf '%s\n' '--- base-to-head diff for implicated files ---'
git diff --unified=35 7c50009ca4946cf7384495f542d0b5856308b70c a4efe25b3d107d6638044cc6f2526ba23bd06895 -- src/main/rate-limits/claude-usage-cache.ts src/main/rate-limits/claude-active-usage-fetch.ts src/main/rate-limits/service/service-provider-cycles.ts src/main/rate-limits/service/service-inactive-accounts.ts src/main/rate-limits/claude-managed-account-usage.ts

Repository: stablyai/orca

Length of output: 35072


🏁 Script executed:

set -eu
nl -ba src/main/rate-limits/claude-usage-cache.ts | sed -n '70,115p'
nl -ba src/main/rate-limits/claude-active-usage-fetch.ts | sed -n '1,75p'
rg -n -F --glob '*.ts' -- 'abortedClaudeRateLimitResult' src/main/rate-limits
rg -n -F --glob '*.test.ts' -- 'abortedClaudeRateLimitResult|aborted|fetchCachedClaudeUsage' src/main/rate-limits

Repository: stablyai/orca

Length of output: 6186


🏁 Script executed:

set -eu
printf '%s\n' '--- aborted result and provider type ---'
nl -ba src/main/rate-limits/claude-usage-result.ts | sed -n '1,90p'
rg -n -F --glob '*.ts' -- 'export type ProviderRateLimits' src shared
nl -ba src/shared/rate-limit-types.ts | sed -n '1,130p'
printf '%s\n' '--- OAuth request checkpoints ---'
nl -ba src/main/rate-limits/claude-oauth-usage-request.ts | sed -n '45,120p'
printf '%s\n' '--- active result handling ---'
nl -ba src/main/rate-limits/service/service-provider-cycles.ts | sed -n '116,175p'

Repository: stablyai/orca

Length of output: 1524


Do not share an aborted result with a new caller.

ClaudeUsageCache.fetch returns the first caller’s pending promise. If that caller aborts while readUsage awaits the cache file, the shared callback returns abortedClaudeRateLimitResult(). A later active or inactive caller can then receive Rate-limit fetch aborted without invoking its own fetchUsage.

Retry with the current caller’s fetchUsage when the shared result is the aborted result. Continue sharing other results.

Suggested fix
     const existing = this.pending.get(key)
     if (existing) {
-      return existing
+      return existing.then((result) =>
+        result.error === 'Rate-limit fetch aborted' ? this.fetch(configDir, fetchUsage) : result
+      )
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
fetch(
configDir: string,
fetchUsage: () => Promise<ProviderRateLimits>
): Promise<ProviderRateLimits> {
// 폴더는 토큰 교체 후에도 같고, WSL·SSH 프로필은 각 호스트의 실제 경로로 분리된다.
const key = createHash('sha256').update(resolve(configDir)).digest('hex')
const existing = this.pending.get(key)
if (existing) {
return existing
}
const operation = this.readUsage(key, fetchUsage).finally(() => this.pending.delete(key))
this.pending.set(key, operation)
return operation
fetch(
configDir: string,
fetchUsage: () => Promise<ProviderRateLimits>
): Promise<ProviderRateLimits> {
// 폴더는 토큰 교체 후에도 같고, WSL·SSH 프로필은 각 호스트의 실제 경로로 분리된다.
const key = createHash('sha256').update(resolve(configDir)).digest('hex')
const existing = this.pending.get(key)
if (existing) {
return existing.then((result) =>
result.error === 'Rate-limit fetch aborted' ? this.fetch(configDir, fetchUsage) : result
)
}
const operation = this.readUsage(key, fetchUsage).finally(() => this.pending.delete(key))
this.pending.set(key, operation)
return operation

Comment on lines +109 to +123
this.entries ??= readFile(this.file, 'utf8')
.then(
(raw) => cacheSchema.parse(JSON.parse(raw)),
(error: unknown) => {
if (isDefinitiveAbsence(error)) {
return {}
}
throw error
}
)
.catch((error: unknown) => {
this.entries = null
throw error
})
const entries = await this.entries

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.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

sed -n '1,210p' src/main/rate-limits/claude-usage-cache.ts
sed -n '236,260p' src/main/rate-limits/service-claude-retry-after.test.ts

Repository: stablyai/orca

Length of output: 6669


Corrupt cache files can block Claude usage requests for all accounts.

When cacheSchema.parse(JSON.parse(raw)) fails, ClaudeUsageCache.readUsage rejects before it reads the account entry or calls fetchUsage. The rejection clears this.entries, so every later request retries the same invalid file and fails again. The active and inactive Claude usage paths share fetchCachedClaudeUsage, so this affects all accounts until the file is removed or repaired manually.

Keep the fail-closed behavior for an unreadable cache, but quarantine invalid JSON or schema data and reset the cache to an empty state. Do not assign a global wait. Preserve each account’s existing blockedUntil and snapshot values when the cache is valid, so Retry-After waits remain account-specific.

This branch has not been deployed

No deployments
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.

Claude usage retries bypass account-specific 429 waits

1 participant