Repository navigation
fix(rate-limits): respect Claude usage Retry-After across accounts - #26589
Noah-TaeHwan wants to merge 1 commit into
Conversation
계정별 서버 대기와 마지막 사용량을 기존 내구성 writer로 저장하고 강제 갱신과 계정 전환에서도 대기를 지킵니다. 모의 HTTP 회귀 테스트로 수정 전 실패와 수정 후 통과를 검증했습니다. 전체 lint의 기존 모바일 순환 경고와 네이티브 패키징 실패는 별도 증거에 기록했습니다.
📝 WalkthroughWalkthroughClaude 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 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)
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: Advanced
- Run ID:
2c7b43ab-a0ae-48f6-a7e7-99ec641cd349
📒 Files selected for processing (10)
src/main/rate-limits/claude-active-usage-fetch.tssrc/main/rate-limits/claude-oauth-usage-error.test.tssrc/main/rate-limits/claude-oauth-usage-error.tssrc/main/rate-limits/claude-profile-usage.test.tssrc/main/rate-limits/claude-usage-cache.tssrc/main/rate-limits/service-claude-retry-after.test.tssrc/main/rate-limits/service-window-activation.test.tssrc/main/rate-limits/service/service-fetch-queue.tssrc/main/rate-limits/service/service-full-cycle-preparation.tssrc/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.
| 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 |
There was a problem hiding this comment.
🎯 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.tsRepository: 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-limitsRepository: 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.
| 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 |
| 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 |
There was a problem hiding this comment.
🩺 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.tsRepository: 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.
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
blockedUntiland 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.force: true; force still bypasses normal refresh intervals.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.logandtests-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 transientEBUSYon 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.7316356349:corepack pnpm test:node src/main/rate-limits/service-claude-retry-after.test.ts -t 'retries a transient cache read failure' --reporter=verboseexpected "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.logTest Files 1 passed (1);Tests 1 passed | 12 skipped (13); exit 0;fix-round2-green.logcorepack 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=2Test Files 5 passed (5);Tests 67 passed (67); exit 0;fix-round2-suites.logcorepack pnpm typecheck$ node config/scripts/run-typecheck-projects-in-parallel.mjs; exit 0; no diagnostics;fix-round2-typecheck.logoxfmt --checkon both round 2 filesAll matched files use the correct format.; exit 0corepack pnpm run check:code-quality:changedChanged-code quality gate passed since 7c50009ca494.; zero new findings; exit 0;fix-round2-quality.logEarlier validation below predates round 2 and is retained as historical evidence.
7c50009ca494Test Files 1 failed (1);Tests 12 failed (12); exit 1pnpm test src/main/rate-limits/service-claude-retry-after.test.ts --reporter=verboseTest Files 1 passed (1);Tests 12 passed (12); exit 0pnpm test src/main/rate-limits --maxWorkers=2Test Files 56 passed | 1 skipped (57);Tests 785 passed | 1 skipped (786); exit 0pnpm 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=2Test Files 3 passed (3);Tests 31 passed (31); exit 0pnpm typecheckpnpm run check:code-quality:changedChanged-code quality gate passed since 7c50009ca494.; zero new findings across 10 files; exit 0pnpm lintafter mobile dependency installationimport(no-cycle)warnings; identical clean-main failure reproduced inlint-main.logpnpm buildlipo: no eligible inputs found; seebuild.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, andmobile/src/terminal/document/fit-scale.ts:1,9. These files are unchanged; the clean-main reproduction confirms the same failure.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
Notes
lipo. Native/build-script inputs are unchanged from main; a separate clean-main native replay was not performed.Checklist