Skip to content

fix(rate-limits): show why an inactive Claude account has no usage instead of a blank row - #18736

Closed
Tauri-EPO wants to merge 5 commits into
stablyai:mainfrom
Tauri-EPO:Tauri-EPO/claude-inactive-usage-error-rows
Closed

Tauri-EPO wants to merge 5 commits into
stablyai:mainfrom
Tauri-EPO:Tauri-EPO/claude-inactive-usage-error-rows

Conversation

@Tauri-EPO

@Tauri-EPO Tauri-EPO commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #18732 — merge that first. This PR's diff includes its commit until then; the change specific to this PR is the second commit.

ELI5

When a saved Claude account could not report its usage, the account switcher showed nothing at all: no bars, no error. A blocked login, a throttled endpoint, and a network blip all looked identical to "no data". Now each saved account says what happened: "Sign in to see usage" when the login is dead, "Usage temporarily unavailable" when Anthropic throttled us, "Usage unavailable" otherwise, and the last known bars stay on screen through a transient failure.

What Changed

  • oauth-refresh.ts: refreshClaudeOauthCredentialsWithOutcome reports why a refresh failed (no-refresh-token / invalid-grant / rate-limited / rejected / network). refreshClaudeOauthCredentials keeps its string | null contract on top of it.
  • claude-managed-account-usage.ts (inactive accounts): a refresh token that is missing (no-refresh-token) or rejected (invalid_grant) returns a reauth-required error row without spending a usage call; both need a new login, so neither reaches the transient-failure map. A failed usage GET returns a classified error row through the same classifyClaudeOAuthUsageError + makeClaudeUsageClassificationError the active account already uses (stale-token, rate-limited with retryAtMs, server, network), instead of throwing. A transient refresh failure on an already-expired token is reported by kind instead of being sent to the usage endpoint; inside the refresh buffer the stored token is still tried once.
  • service/service-inactive-accounts.ts: the per-account catch writes an error row through applyStalePolicy instead of leaving the cache untouched, so last-known windows survive a transient failure and a hard failure still produces a row. It evicts the cache only when the account has left the resolver list, so a generation bump mid-flight no longer blanks a row the account switch just seeded.
  • InlineProviderUsage.tsx: the empty-error label is chosen by failureKind. Auth kinds keep "Sign in to see usage"; rate-limited reads "Usage temporarily unavailable"; anything else "Usage unavailable". Two new English strings.
  • rate-limit-types.ts: new failureKind value reauth-required (optional string field; old clients ignore it).

Why

Points 3 and 5 of #14833: the inactive path threw on any OAuth failure and the service swallowed it, so Switch to could not distinguish a dead login from a throttle from a bug. #18732 fixes the refresh itself; this PR makes the remaining failures visible and actionable. The existing classification and result builders cover every case, so this reuses them rather than adding a parallel path.

Linked Issue

Part of #14833 (does not close it: fetch triggers, persistence, and roster rows follow in separate PRs).
Depends on #18716 / #18732.

Visual Proof

N/A for screenshots: the change is a text label inside the account switcher rows. The live run below shows the rows the switcher receives.

Testing

Platforms: Windows 11 (local). Not run on macOS/Linux/SSH; main-process plus one renderer label, platform-neutral.

  • Live, real fetchInactiveClaudeAccountUsage from this branch (Electron stubbed for app.getPath), against two managed accounts on my machine. No credential file was rewritten:

    <dead refresh token>  {"status":"error","error":"Sign in to this account again","failureKind":"reauth-required","session":null,"weekly":null,"credentialsRewritten":false}
    <valid account>       {"status":"ok","error":null,"session":0,"weekly":0,"credentialsRewritten":false}
    
  • vitest run --config config/vitest.config.ts over src/main/claude-accounts, the Claude fetcher suites, service-inactive-account-previews, service-live-claude-usage, claude-usage-error-classification, inline-usage-bars, codex-status-sign-in: 32 files, 283 tests, 282 passed. New tests: 5 refresh-outcome cases, 4 inactive-path cases (401 to stale-token row, 429 to rate-limited with retryAtMs, invalid_grant to reauth-required with no usage call, transient refresh failure still tries the stored token), 2 service cases (thrown fetch produces an error row; last-known windows kept), 1 label case.

  • The single failure is pre-existing on Windows and unrelated: service-inactive-account-previews > allows usage-panel Fable supplements expects allowUsagePanelSupplement: true, which is darwin/linux-only (fails identically on clean main).

  • Full typecheck (run-typecheck-projects-in-parallel.mjs): clean. oxlint and oxfmt --check on changed files: clean. verify-localization-catalog, verify-localization-extraction, audit-localization-coverage --check, runtime catalog generator: all exit 0, no generated diff.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

AI Disclosure

Implementation and tests by Claude (Fable 5.1) via Claude Code, driven and verified by me; the live run above was executed on my machine.

Review

Agent code-review summary:

  • Cross-platform: no platform branches. macOS keychain reads go through the same readClaudeManagedCredentialsJson; a keychain failure now surfaces as an unknown-kind error row ("Usage unavailable") instead of a gap.
  • SSH / remote: rows are produced on the host that owns the credentials, as before. Remote snapshots carry the same ProviderRateLimits shape.
  • Wire compatibility: reauth-required is a new value of an existing optional string field. Old desktop and mobile clients fall into their generic error handling; no new opcode or required field.
  • Agents / integrations: Claude only. Codex inactive rows unchanged (they already use InlineUsageSignInAction).
  • Performance: invalid_grant short-circuits before the usage GET, one fewer call per dead account per switcher open. No new polling.
  • UI: label only, existing text-[10px] text-muted-foreground style. No inline "Sign in" button in the Claude switcher yet; the Accounts pane has re-auth, and an inline action like the Codex one is a natural follow-up.
  • Security: error strings carry HTTP status and message, never tokens. The refresh outcome reads only the token endpoint's JSON error field.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Review follow-ups (68b17b4): intent-named localization IDs (components.status.bar.inlineUsage.*), 'unknown' for failures that escape the fetcher, no usage call with an already-expired token after a transient refresh failure, and unsupported-proxy as its own refresh outcome. Rebased on the updated #18732.

pnpm build:desktop did not run on this worktree: the native windows-process-tree rebuild fails on this path length (MAX_PATH) and pnpm 12 refuses to run scripts until the install completes. The sibling branch #18732 built cleanly with the same toolchain minutes earlier, and this diff is TypeScript-only with the full typecheck clean, so CI covers the build.

Follow-ups for #14833, each its own PR: fetch inactive accounts on Usage popover open and on Refresh; persist last-known per account with validity until resetsAt; per-account rows in the Usage popover (#10688 keeps the Accounts pane).

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

Author

X: @EnricoPin

…ectron net

The token endpoint answers 429 to Chromium's network stack while the same
refresh_token grant from Node succeeds, so every Orca-owned refresh failed
silently: inactive managed accounts never got a new token and their usage
rows stayed blank, and the launch-time refresh only worked because the
claude CLI refreshed on its own afterwards.

Route the POST through undici's fetch. Proxy resolution mirrors what child
processes get: Orca's configured proxy wins over the shell's and its bypass
list replaces NO_PROXY; SOCKS proxies fall back to a direct connection with a
warning since undici only tunnels through HTTP proxies. The usage fetch keeps
using net.fetch, which the usage endpoint accepts.

Fixes stablyai#18716

@pullfrog pullfrog 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.

ℹ️ No critical issues — minor suggestions inline.

Reviewed changes

This PR makes the inactive Claude account switcher rows report why usage is missing instead of a blank row, reusing the active account's existing failure classification rather than adding a parallel path.

  • OAuth refresh outcome — refreshClaudeOauthCredentialsWithOutcome reports why a refresh failed (no-refresh-token, invalid-grant, rate-limited, rejected, network) on top of the existing string | null contract.
  • Inactive-account classification — a dead refresh token becomes a reauth-required row without spending a usage call; a failed usage GET becomes a classified error row (stale-token, rate-limited with retryAtMs, server, network) through the shared classifyClaudeOAuthUsageError / makeClaudeUsageClassificationError.
  • Service error row — the per-account catch writes an error row through applyStalePolicy, so last-known windows survive a transient failure and a hard failure still produces a row.
  • Switcher label — unavailableUsageLabel maps auth kinds to "Sign in to see usage", rate-limited to "Usage temporarily unavailable", and everything else to "Usage unavailable".
  • Type + i18n — new reauth-required UsageRateLimitFailureKind value and two English strings.

ℹ️ Nitpicks

  • reauth-required is not handled by the Claude switches in usage-error-copy.ts (getProviderUsageStatusLabel / getProviderUsageErrorMessage), so it degrades to the generic "Refresh failed" copy. It isn't reachable today — only the inactive path emits it, and those rows use unavailableUsageLabel — but the roster follow-up (#10688) will surface it.
  • AUTH_FAILURE_KINDS is typed ReadonlySet<string>; ReadonlySet<UsageRateLimitFailureKind> would let the compiler catch a misspelled auth-kind entry.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@coderabbitai

coderabbitai Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: fe0b79af-f059-48dc-8d89-5ec9cdab6586

📥 Commits

Reviewing files that changed from the base of the PR and between 68b17b4 and edf8dd2.

📒 Files selected for processing (6)
  • src/main/rate-limits/claude-fetcher-managed-account-usage.test.ts
  • src/main/rate-limits/claude-managed-account-usage.ts
  • src/main/rate-limits/rate-limit-service-test-harness.ts
  • src/main/rate-limits/service-inactive-account-previews.test.ts
  • src/main/rate-limits/service/service-inactive-accounts.ts
  • src/shared/rate-limit-types.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/main/rate-limits/service-inactive-account-previews.test.ts
  • src/shared/rate-limit-types.ts
  • src/main/rate-limits/claude-managed-account-usage.ts
  • src/main/rate-limits/service/service-inactive-accounts.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.


📝 Walkthrough

Walkthrough

The OAuth refresh flow now uses Node’s undici fetch with HTTP proxy support and structured failure outcomes. Managed-account usage classifies refresh and usage errors, preserves stored tokens for transient failures, and requires reauthentication for invalid grants. Inactive-account loading records network failures while applying stale-data policy. Inline usage labels now distinguish authentication, rate-limit, and general failures. Tests cover the new transport, classifications, cache behavior, and labels.

Merge Risk: ⚪ Minimal · up to edf8d

This change replaces blank inactive-account usage rows with classified authentication, rate-limit, network, and general error states while preserving usable cached usage data during transient failures. The covered failure paths do not show an outstanding merge-blocking risk.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 21 functions across 10 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the primary change: showing the reason inactive Claude accounts have no usage instead of displaying a blank row.
Description check ✅ Passed The description is complete and relevant. It includes the required explanation, changes, rationale, linked issues, visual-proof statement, testing details, AI disclosure, compatibility notes, and chec…
  • Fix all pre-merge checks with AI

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: Team

Run ID: 5c41a927-228a-4bee-8c5c-ff76bdcdacb6

📥 Commits

Reviewing files that changed from the base of the PR and between 8064d1f and 786a06b0377e3ff0a0db33be16308337a8e6caf6.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (11)
  • package.json
  • src/main/claude-accounts/oauth-refresh.test.ts
  • src/main/claude-accounts/oauth-refresh.ts
  • src/main/rate-limits/claude-fetcher-managed-account-usage.test.ts
  • src/main/rate-limits/claude-managed-account-usage.ts
  • src/main/rate-limits/service-inactive-account-previews.test.ts
  • src/main/rate-limits/service/service-inactive-accounts.ts
  • src/renderer/src/components/status-bar/InlineProviderUsage.tsx
  • src/renderer/src/components/status-bar/inline-usage-bars.test.tsx
  • src/renderer/src/i18n/locales/en.json
  • src/shared/rate-limit-types.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.

…a SOCKS proxy in the refresh

Review follow-ups on stablyai#18732: the refresh request now aborts with the
caller's signal instead of waiting out its own timeout, and a configured
SOCKS proxy (which undici cannot tunnel through) skips the refresh with a
warning instead of connecting directly around the configured egress route.
…stead of a blank row

The inactive-account usage path threw on any OAuth failure and the service
swallowed it without writing a row, so a 401, a 429, or a dead refresh token
all looked like "no data" in the account switcher. The active-account path
already classifies these failures; reuse that classification for inactive
accounts and give the switcher a label for each case.

- OAuth refresh reports why it failed (invalid_grant, rate-limited, rejected,
  network); a dead refresh token becomes a `reauth-required` row without
  spending a usage call.
- The usage GET failure becomes a classified error row (stale-token,
  rate-limited with retry-at, server, network) instead of a throw.
- The service still catches thrown failures, but writes an error row and
  keeps last-known windows through the existing stale policy.
- Inline usage bars say "Sign in to see usage" only for auth failures; a
  throttle reads "Usage temporarily unavailable" and anything else "Usage
  unavailable".

Part of stablyai#14833 (points 3 and 5). Stacked on stablyai#18732.
… rows

- Name the two new switcher strings with intent IDs under
  components.status.bar.inlineUsage instead of hash-based auto keys.
- Classify a failure that escapes the fetcher as 'unknown', since network
  and HTTP failures are already classified inside it.
- After a transient refresh failure, do not send an already-expired token to
  the usage endpoint; report the refresh failure kind instead. Inside the
  refresh buffer the stored token is still tried once.
- Surface an unsupported (SOCKS) proxy as its own refresh outcome.
@Tauri-EPO
Tauri-EPO force-pushed the Tauri-EPO/claude-inactive-usage-error-rows branch from 786a06b to 68b17b4 Compare September 5, 2026 01:31

@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: Team

Run ID: 3ef2014a-9536-42e2-a344-28c6fdc5fcba

📥 Commits

Reviewing files that changed from the base of the PR and between 786a06b0377e3ff0a0db33be16308337a8e6caf6 and 68b17b4.

📒 Files selected for processing (8)
  • src/main/claude-accounts/oauth-refresh.test.ts
  • src/main/claude-accounts/oauth-refresh.ts
  • src/main/rate-limits/claude-fetcher-managed-account-usage.test.ts
  • src/main/rate-limits/claude-managed-account-usage.ts
  • src/main/rate-limits/service-inactive-account-previews.test.ts
  • src/main/rate-limits/service/service-inactive-accounts.ts
  • src/renderer/src/components/status-bar/InlineProviderUsage.tsx
  • src/renderer/src/i18n/locales/en.json
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/i18n/locales/en.json

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.

@pullfrog pullfrog 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.

ℹ️ No critical issues — one minor metadata nit inline.

Reviewed changes

Since the prior review (786a06b), the branch was rebased onto an updated #18732 and a review-follow-ups commit landed.

  • Expired-token refresh failure — added isOauthTokenExpired plus refreshFailedResult/REFRESH_FAILURE_KINDS so a stored token already past expiry reports a classified error row instead of sending a token doomed to 401.
  • SOCKS proxy refusal — resolveRefreshRoute now refuses (rather than silently bypasses) a SOCKS proxy, returning a new unsupported-proxy failure kind.
  • Caller cancellation — the refresh forwards the caller signal through AbortSignal.any so the inactive fetch settles promptly on abort.
  • Service failure kind — the per-account catch now writes failureKind: 'unknown', addressing the prior review's network-mislabel note.
  • i18n keys — the two new labels moved from auto-hash keys to an explicit inlineUsage.* namespace.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

A stored blob with no refresh token was mapped to
'refreshable-credentials-without-token', which claims the opposite: that the
account is refreshable and the UI should say "Refreshing sign-in". Nothing can
refresh it, so the row promised a recovery that never arrived, and the
inactive-account stale policy kept serving the old windows instead of the
"Sign in to see usage" row.

Route 'no-refresh-token' to 'reauth-required' once the access token is expired,
and drop it from the transient-failure map by type so the inverted mapping
cannot come back. Inside the refresh buffer the still-valid access token is
tried as before.

Also stop the inactive-Claude catch from evicting the cache of an account that
is still listed. A generation bump alone now leaves the snapshot in place;
refreshForClaudeAccountChange seeds the outgoing account's row and nothing
refetches it on the spot, so the eviction blanked the row it had just filled.
pruneInactiveClaudeState already removes accounts that left the list.
@Tauri-EPO

Copy link
Copy Markdown
Contributor Author

Pushed edf8dd280d (was 68b17b49f5), addressing the two open review threads.

  • no-refresh-token was mapped to the opposite meaning. It went to refreshable-credentials-without-token, which asserts the account is refreshable and renders as "Refreshing sign-in" — a promise nothing could keep, since that failure means the stored blob has no refresh token at all. It now returns reauth-required once the access token is expired, and it is excluded from REFRESH_FAILURE_KINDS by type, so the transient map cannot claim it again. Inside the refresh buffer the still-valid access token is tried as before. This also unblocks fix(rate-limits): keep an inactive Claude account's last-known usage until its window resets #18753, where LOGIN_REQUIRED_FAILURE_KINDS covers reauth-required but not refreshable-credentials-without-token.
  • Inactive-Claude cache eviction on a thrown fetch. The catch deleted the cache on a generation bump even when the account was still listed, which blanked the row refreshForClaudeAccountChange() had just seeded (that path does not refetch inactive accounts, it only clears the on-open debounce). It now deletes only when the account has left the resolver list, matching the two guard blocks above it; pruneInactiveClaudeState() already handles removals.

Tests: asks for a new login when the stored blob has no refresh token at all (claude-fetcher-managed-account-usage.test.ts) and keeps the switch-time snapshot when a stale same-id fetch throws (service-inactive-account-previews.test.ts). Also gave the shared deferred() test helper a reject.

Gates on Windows 11 / Node 24, edf8dd280d:

tsc --noEmit -p config/tsconfig.node.json      -> exit 0
tsc --noEmit -p config/tsconfig.tc.web.json    -> exit 0
check-changed-code-quality.mjs                 -> 0 new findings across 10 changed files (exit 0)
vitest src/main/rate-limits src/main/claude-accounts
  before: Test Files 4 failed | 64 passed (68)   Tests 9 failed | 644 passed (653)
  after:  Test Files 4 failed | 65 passed (69)   Tests 9 failed | 646 passed (655)

The 9 failures are pre-existing on this machine, not from this stack — the same 9 fail on the base commit 9008fb70a6 with the branch checked out clean (Test Files 4 failed (4), Tests 9 failed | 63 passed (72) over those four files).

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

Since the prior review (68b17b4), one follow-up commit landed that corrects the no-refresh-token mapping and preserves switch-time snapshots.

  • Missing refresh token → reauth-required — a stored blob with no refresh token and an already-expired access token now yields a reauth-required row (Sign in to this account again) instead of the inverted refreshable-credentials-without-token mapping, addressing the prior review's note.
  • Type-narrowed transient map — REFRESH_FAILURE_KINDS is now Record<TransientRefreshFailure, UsageRateLimitFailureKind> (excluding invalid-grant and no-refresh-token by type), so a non-refreshable account can no longer be asserted refreshable.
  • Snapshot survives a stale fetch — the inactive catch's stale/aborted branch deletes the cache only when the account is no longer current, so refreshForClaudeAccountChange's switch-time snapshot isn't wiped by an in-flight same-id fetch that later rejects.
  • Regression tests — added a no-refresh-token case (no token call, no usage call) and a switch-time-snapshot case; the deferred test helper gained reject.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker

Copy link
Copy Markdown
Contributor

Thanks @Tauri-EPO! Closing — the usage code this targets has since been rewritten on main, so this change no longer applies.

@nwparker nwparker closed this Oct 26, 2026
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.

2 participants