Skip to content

fix(status-bar): source rate-limit badges from the Active Server that owns usage - #15880

Closed
nwparker wants to merge 4 commits into
mainfrom
nwparker/rate-limit-badge-remote-source
Closed

nwparker wants to merge 4 commits into
mainfrom
nwparker/rate-limit-badge-remote-source

Conversation

@nwparker

@nwparker nwparker commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

🛑 HELD — do not merge

Held by maintainer decision (2026-08-22). CI is green and the branch merges clean; this is not a technical blocker.
Converted to draft and labelled wip so it cannot be merged by accident.
Superseded fork PR #15804 (@yzxcj797) is still open and should stay open while this is held.


Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​628 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​628
Prod 7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​445 $\color{#cf222e}{\Huge{\mathbf{−}}}$​20 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​425

Supersedes #15804 by @yzxcj797 — carried over so it can run full CI (fork PRs only run track-community-pr in this repo). Original authorship preserved in the commit: 5adafcc is authored by them, and my follow-up commit credits them with Co-authored-by.

ELI5

If your "Active Server" is a remote machine, that machine is the one running Claude/Codex — so the usage percentages in the status bar should be its numbers. Today they are the numbers from the laptop you're looking at, which usually runs no agents at all. Worst case that laptop happens to be signed in too, so the badge shows a perfectly believable percentage that describes the wrong computer. This makes the badges read from the server that actually owns the accounts, show nothing (not stale local numbers) while the first answer is on its way, and say "cannot reach <server>" when the server has gone quiet instead of spinning forever. It also stops hiding the server's bars just because the laptop you are looking at has none of those agent CLIs installed — which is the whole point of a thin client.

What Changed

  • New src/renderer/src/components/status-bar/remote-usage-rate-limits.ts — useRemoteUsageRateLimits(settings). Subscribes to the provider-accounts snapshot of whichever runtime owns accounts, stamps every snapshot with the owner id it came from, and exposes an owner-keyed refresh().
  • Rewritten usage-rate-limits-source.ts — resolveStatusBarUsageRateLimits(local, remoteUsage) takes an explicit RemoteUsageState (local | remote-pending | remote-unverifiable | remote) instead of a boolean plus a nullable snapshot. remote-unverifiable carries a reason (unreachable | usage-not-published) and the last snapshot the owner vouched for.
  • StatusBar.tsx badges, usageSettings durability flags, and the manual Refresh button now go through the resolved state.
  • StatusBar.tsx no longer gates the usage bars (or their context-menu toggles) on this machine's agent-CLI PATH detection while a remote server owns usage. detectedAgentIds describes the viewer only, so on the thin client this PR is written for it hid every one of the server's bars.
  • usage-error-copy.ts — an unverifiable owner is labelled Usage unavailable instead of the provider-classified Refresh failed. The badge's inline label is the string Usage / rate-limit badges are not environment-aware: rateLimits.refresh*ForTarget only accepts host / wsl, so a client with a remote Active Server shows local usage #15798 complains about; without this the new copy only appeared once the user opened the popover. The marker is a new renderer-only optional usageMetadata.unverifiableUsageOwner flag (hosts never set it).
  • createPendingProviderSnapshot is exported from status-bar-provider-visibility.ts so the pending and unreachable snapshots come from the same factory the rest of the status bar uses.
  • Two new English catalog keys: auto.components.status.bar.usage.remoteOwnerUnreachable and …usage.remoteOwnerNoUsage.

No wire change. ProviderAccountsSnapshot.rateLimits has carried the host's full RateLimitState since #1467 (2026-05-05), so this needs no new RPC method and no new stream opcode. rateLimits is typed RateLimitState | null, so a host that publishes an accounts snapshot without it is possible; that case is now an explicit verdict (Usage unavailable — <server> does not report usage) rather than a permanent silent spinner — see below.

Why

Root cause, in two parts.

1. The badges read the wrong store slice. StatusBarInner destructured providers straight out of the local rateLimits zustand slice, which is fed by the renderer's local poll. The accounts roster right next to it was already environment-aware ("Showing accounts managed by <server>"), so the two surfaces disagreed. #15798 calls the valid-looking-local-numbers case "arguably worse than an error state, because it looks correct".

2. The first version of the degrade did not actually degrade. #15804 replaced only status on the local Claude/Codex snapshot while a remote snapshot was in flight. getTightestUsageSection(p) still found the preserved session/weekly windows, so StatusBar.tsx's "Fetching with no prior data" branch never fired and the local percentage bar kept rendering. It only looked fixed because the test fixture used session: null, weekly: null. It also covered claude and codex only, so gemini, opencodeGo, kimi, antigravity, minimax and grok leaked local numbers permanently. Both are fixed by replacing every provider key with a genuinely empty snapshot, driven by a Record<UsageProviderKey, …> derived from RateLimitState so a newly added provider is a compile error, not a silent leak.

Beyond the reported symptom, five more problems are fixed on this branch:

  • A host that answers without usage spun the badge forever. watchProviderAccounts marks its first-snapshot timeout as satisfied as soon as any snapshot object arrives, so a snapshot with rateLimits: null disarmed the 15s guard and its onClose error — and the hook then discarded it. The result was the pulsing ··· placeholder with no error path and no recovery. It now resolves to remote-unverifiable with reason: 'usage-not-published', whose copy does not claim the server is unreachable: it answered, it just publishes no usage.
  • Swallowed watcher errors. watchProviderAccounts raises a 15s first-snapshot timeout, "Remote provider account subscription closed.", and RuntimeRpcCallError — all through one onError. fix(status-bar): show the Active Server's usage in the rate-limit badges #15804 console.error'd them, leaving the badge on ··· and the roster on "Loading usage…" indefinitely. That collapses loss of contact into in progress, which docs/reference/ssh-execution-boundary.md exists to prevent. Errors now resolve to remote-unverifiable and render Usage unavailable — cannot reach <server> (an error status — never 0%, never a permanent spinner), cleared by the next successful snapshot. Losing contact also keeps the last snapshot the owner vouched for (blanked, carrying the verdict) so its bars stay in place instead of silently disappearing on a viewer that has none of those providers configured locally. Only providers someone had actually set up get that verdict (the server's own last snapshot when there was one, the viewer's otherwise): an error status reads as configured to isProviderConfigured, so stamping the null/unavailable slots too would pin MiniMax and OpenCode Go bars on users who never set them up and swallow the usage setup CTA. Those slots pass through untouched — they carry no numbers to leak and are no evidence the server has them set up.
  • Server A → server B leaked A's numbers. The cached snapshot was cleared only on the remote → local transition, so on an A → B switch the badges showed A's usage under B's label. The hook now stamps each snapshot with its owner id and ignores anything whose owner does not match the active one, which also drops late in-flight callbacks from the closed watcher.
  • Stale useCallback deps. handleRefresh read remoteUsageOwner/activeRuntimeEnvironmentId without listing them; npx oxlint flagged it at StatusBar.tsx:2137, and exhaustive-deps is only warn in .oxlintrc.json, so CI would not have caught it. Because the other deps are stable store selectors, the closure was never rebuilt — clicking Refresh after switching to a remote server still ran the local refresh. The hook's owner-keyed refresh is now in the dep array.
  • The Refresh button lied. fetchProviderAccountsSnapshot resolves off the subscribe-time ready frame, which the host emits before refreshIfStale() runs, so the spinner stopped before any newer data could exist. Background polling does not cover this either: shouldBackgroundPoll() requires the host window to be visible, non-minimized and focused, which a machine acting as a server never is. The refresh now holds until the persistent watcher delivers a snapshot newer than the one held at click time, capped at 8s so a throttled host still releases the button.

Durability flags (minimaxCookieConfigured / grokAuthConfigured) take the host's value when it sends one and fall back to the local value when it does not — a host predating those providers omits them entirely, and reading them raw would make a configured bar silently vanish (docs/reference/remote-wire-compatibility.md: what the host publishes reaches old clients).

Linked Issue

Fixes #15798

Visual Proof

Not attached — I have no paired remote Orca server in this environment and will not fabricate screenshots. This is a UI change, so here is exactly what a reviewer should look at:

  1. Pair a remote server and set it as the Active Server. The status-bar Claude/Codex percentages should match the server's usage, not the viewer's. Cross-check against the "Showing accounts managed by <server>" roster right beside them — they must now agree.
  2. Immediately after switching, before the first snapshot lands, the badges must show the pulsing ··· placeholder — not the local machine's percentages. This is the case the original patch got wrong, so it is the one worth watching.
  3. Stop or kill the remote server and wait ~15s. Badges must show the warning triangle, the inline label Usage unavailable (not Refresh failed), and Usage unavailable — cannot reach <server name> in the popover — never 0%, never an endless spinner. The bars the server had vouched for stay in place carrying that verdict.
  4. Switch from server A to server B. B's badges must go blank first; A's numbers must never appear under B's name.
  5. On a client with no agent CLIs installed (the thin-client case the issue describes), the server's bars must still appear — before this they were hidden by local PATH detection.
  6. Against a remote Orca old enough not to publish rateLimits, the badges must read Usage unavailable — <server> does not report usage instead of spinning.
  7. With a local Active Server (no remote), nothing changes at all — the local PATH gate, the local numbers and the local refresh are all untouched.

Testing

Run on macOS only (Darwin 25.3.0). Everything below passed; no pre-existing unrelated failures were observed in the files touched.

npx vitest run --config config/vitest.config.ts \
  src/renderer/src/components/status-bar/usage-rate-limits-source.test.ts \
  src/renderer/src/components/status-bar/remote-usage-rate-limits.test.ts
  -> 2 files, 26 tests passed

npx vitest run --config config/vitest.config.ts src/renderer/src/components/status-bar/
  -> 44 files, 310 tests passed

npx vitest run --config config/vitest.config.ts src/renderer/src/app-startup-routing.test.ts
  -> 23 tests passed

npx oxlint <changed source/test files>                                 -> 0 warnings, exit 0
npx oxlint --config config/oxlint-code-quality-native-plugins.json \
  <changed source files> --deny-warnings                               -> exit 0
npx oxfmt --check <changed files>                                      -> clean
node config/scripts/check-max-lines-ratchet.mjs                        -> OK, no new bypasses
node config/scripts/check-reliability-gates.mjs                        -> 87 gates pass
node config/scripts/verify-localization-catalog.mjs                    -> pass
node config/scripts/verify-localization-extraction.mjs                 -> pass
node config/scripts/audit-localization-coverage.mjs --check            -> pass

Project-wide pnpm typecheck / pnpm lint were deliberately not run locally; CI covers them.

Regression evidence — every behaviour change is pinned by a test that fails without it. Each product line was reverted in isolation and the suite re-run:

revert usage-error-copy's unverifiable branch
  FAIL labels an unverifiable owner as unavailable rather than "Refresh failed"
       expected 'Refresh failed' to be 'Usage unavailable'

revert the hook's "snapshot without rateLimits" branch, and lastKnown on failure
  FAIL does not spin forever when the owner answers without usage (older host)
  FAIL keeps the last snapshot the owner vouched for when contact is lost

revert `base = remoteUsage.lastKnown ?? localRateLimits`, and the StatusBar PATH gate
  FAIL keeps the bars the unreachable server vouched for, blanked (#15798)
  FAIL does not hide the owning server's bars behind this laptop's PATH detection

The earlier round of the same exercise (reverting the degrade so it preserved the local session/weekly windows, and pointing StatusBar back at rateLimits) still fails 4 tests, including never renders local percentages while the first remote snapshot is in flight — the proof that the original patch did not fix the reported symptom.

Coverage added: usage-rate-limits-source.test.ts (local passthrough, remote adoption, pre-flag-host fallback, all eight providers blanked while pending, both unverifiable reasons' copy, the Usage unavailable inline label, last-known bars kept on contact loss, never inventing bars for unconfigured providers, usage setup CTA left reachable, latestUsageUpdatedAt) and remote-usage-rate-limits.test.ts (no watcher without a remote owner, pending → remote, watcher error → unverifiable → recovery, usage-less snapshot → unverifiable, usage-less manual refresh, last-known retention, generic label fallback, A → B never shows A's numbers including a late callback, refresh held open until newer data, refresh failure → unverifiable). Three of the resolver tests are source-level pins on StatusBar.tsx, following the existing worktree-jump-palette-source-context-boundary.test.ts pattern — the resolver is pure, so without them a revert of the wiring lines would leave the whole suite green.

  • I manually tested these changes locally — no, and I am not ticking this. There is no paired remote server in this environment; verification here is automated only. The manual steps are listed under Visual Proof.
  • Automated tests added/updated, or explained why not below

Review

  • Malicious-code scan of the contributor diff: performed explicitly because @yzxcj797 is not a stablyai member. The full patch (3 files, +152/-5, renderer-only) was read hunk by hunk. No fetch/XMLHttpRequest/WebSocket, no new URL or RPC method, no eval/new Function/child_process/dynamic import(), no process.env, no credential/keychain/~/.claude reads, no writes to disk or settings, no obfuscated or non-ASCII payloads (only em-dashes in English prose), and no edits to AGENTS.md/CLAUDE.md/docs//.claude/ or anything an agent later reads as instructions. RateLimitState carries usage percentages and error strings only — no tokens. Clean. The problems fixed above are ordinary correctness bugs, not hostile behavior.
  • Cross-platform: pure renderer state. No fs, no path, no argv, no shell, no line-ending handling, no keyboard shortcuts. Nothing to branch on for macOS/Linux/Windows.
  • SSH / remote: this is the core of the change. The execution host owns usage data; the client now renders the host's snapshot and never substitutes its own. Loss of contact maps to a distinct remote-unverifiable verdict with copy naming the owner, and it is kept separate from a reachable host that simply publishes no usage — no synonym for "healthy", no 0%, no permanent spinner, per docs/reference/ssh-execution-boundary.md.
  • Remote wire compatibility: no new wire field, method or opcode (usageMetadata.unverifiableUsageOwner is renderer-synthesized and never published by a host). The consumed payload (ProviderAccountsSnapshot.rateLimits) has been on the wire since feat(mobile): account switcher and rate-limit usage on mobile #1467. Optional fields an older host may omit (minimaxCookieConfigured, grokAuthConfigured, claudeTarget, codexTarget, the inactive-account arrays) are normalized instead of read raw, so a new client against an old host degrades rather than blanking bars.
  • Agent / integration compatibility: no agent, git, or provider-hosting surface touched. The Git 2.25 baseline and GitHub/GitLab neutrality are not implicated. Folder workspaces vs. git worktrees is not implicated either — usage is per runtime environment, not per repo. Mobile is unaffected; accounts.subscribe behavior on the host is unchanged.
  • Performance: one accounts.subscribe while a remote server is active, closed on owner change and on unmount. The refresh path still shares fetchProviderAccountsSnapshot's existing in-flight dedupe. The 8s settle cap is a setTimeout cleared on settle. Nothing new runs when the Active Server is local.
  • UI quality: the pending state reuses the existing ··· placeholder and the unreachable state reuses the existing error treatment (warning triangle plus popover message); no new visual vocabulary, no new tokens, sizes or colors. Both new strings are in en.json and interpolated, so the other four locales fall back to English until a localization pass. The unverifiable inline label reuses the existing Usage unavailable key.
  • Security: no new capability, no credential handling, no new network sink. The only user-controlled string that reaches the UI is the runtime environment's own name, rendered as React text.

Known limitations / follow-ups (deliberately out of scope)

  • Settings → Appearance's status-bar toggle list (useAvailableStatusBarToggles) still filters on local PATH detection, so a thin client can toggle the server's usage bars from the status-bar context menu but not from that Settings pane. Same root cause as the gate fixed here; threading remote ownership into that hook reaches a different pane and its tests.
  • The visibility gate's settings fallback is still the viewer's. When a provider has no snapshot from the server, hasUsageProviderSettingsForProvider reads the local GlobalSettings, so e.g. a viewer with Gemini CLI OAuth enabled locally can see a -- Gemini slot for a server that has no Gemini. Only the durability flags the host publishes (minimaxCookieConfigured, grokAuthConfigured) are owner-scoped today.
  • Switcher popovers — see below.

Known follow-up (deliberately out of scope)

ClaudeSwitcherMenu / CodexSwitcherMenu still read inactiveClaudeAccounts / inactiveCodexAccounts / claudeTarget / codexTarget from the local store, so the inactive-account rows and the host/WSL chip inside the popover still describe the viewer's machine while the active row above them describes the server. The remote snapshot already carries that data. Threading it through means changing both switcher components' props and is a larger diff than this fix warrants; happy to file it as a follow-up issue, or fold it in here if a reviewer prefers.

Agent skill upstream boundary

  • Not applicable — no skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation touched.

Notes

Renderer-only, in-memory state — nothing persisted, so there is no settings migration or backward-compat risk.

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) — targeted lint, tests and typecheck run locally (see Testing); the full project runs are left to CI

yzxcj797 and others added 2 commits August 21, 2026 22:57
With a remote Active Server, the usage badges kept polling the local
device: the accounts roster next to them was already environment-aware
('Showing accounts managed by <server>'), but the numbers came from the
local rate-limits slice, so the badges sat on 'Refresh failed' forever —
or worse, showed valid-looking numbers describing a machine that runs
no agents (#15798).

The provider-accounts snapshot the roster already consumes carries the
server's full RateLimitState; the status bar now watches that snapshot
when a remote environment owns accounts and renders its numbers. The
manual refresh re-fetches the snapshot instead of the local poll. Until
the first snapshot lands, Claude/Codex rows degrade to a fetching state
rather than flashing local numbers; without a remote owner nothing
changes.
Blank every provider while the owning server's first snapshot is in
flight. Overwriting only `status` left the local session/weekly windows
in place, so getTightestUsageSection() still returned data and the badge
kept rendering the viewer's percentages under the server's name — the
exact "looks correct, is wrong" symptom #15798 reports. The degrade also
skipped gemini/opencodeGo/kimi/antigravity/minimax/grok; it is now driven
by a compile-forced map over RateLimitState's provider keys.

Surface watcher failures instead of console.error: a first-snapshot
timeout, a closed subscription or an RPC error now resolve to
"Usage unavailable — cannot reach <server>". Per
docs/reference/ssh-execution-boundary.md, loss of contact with the
execution host is its own verdict and must not render as a spinner.

Scope the cached snapshot to its owner so switching server A -> B cannot
show A's numbers under B, keep the MiniMax/Grok durability flags local
when the host is too old to publish them, and hold the refresh spinner
until data newer than the click arrives rather than clearing on the
subscribe-time `ready` frame.

The subscription moved out of StatusBar.tsx into useRemoteUsageRateLimits
so the owner-switch and unreachable paths are unit-testable.

Co-authored-by: yzxcj797 <[email protected]>
@nwparker
nwparker requested a review from brennanb2025 as a code owner August 22, 2026 06:14
@coderabbitai

coderabbitai Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The status bar now supports usage snapshots owned by remote provider accounts. New state resolution distinguishes local, pending, verified remote, and unverifiable usage. Remote snapshots are watched, refreshed, retained when contact is lost, and isolated when servers change. Effective rate limits now control provider metadata, visibility, context-menu entries, and refresh behavior. New tests cover snapshot lifecycle, resolution, failures, server switching, and status-bar wiring.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 13.64% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 22 functions across 8 files. (1 skipped: 1 unsupported.) Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR addresses #15798 by using the Active Server's usage data, preventing stale local values, and reporting clear unavailable states.
Out of Scope Changes check ✅ Passed The changes remain focused on remote-aware status-bar usage resolution, compatibility, error handling, refresh behavior, localization, and related tests.
Title check ✅ Passed The title clearly and concisely describes sourcing status-bar rate-limit badges from the Active Server that owns usage.
Description check ✅ Passed The description is detailed, relevant, and covers the template sections, implementation, rationale, testing, compatibility, limitations, and linked issue.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

…der bars

A remote-unreachable owner stamped every provider snapshot 'error', which
isProviderConfigured reads as "configured" — pinning MiniMax/OpenCode Go bars
on users who never set them up and swallowing the usage setup CTA. Only blank
providers that carried local usage; leave null/'unavailable' slots untouched.
…face

Three gaps left the remote-owned badges wrong for the thin-client case #15798
is actually about:

- A host that answers without `rateLimits` (any Orca older than the version
  that started publishing it) disarmed the watcher's first-snapshot timeout and
  was then dropped, pinning every bar on the pulsing placeholder forever with
  no error path. It is now its own verdict, with copy that does not falsely
  claim the server is unreachable.
- The inline badge label still read "Refresh failed" - the exact string the
  issue complains about - because the provider-classified copy never saw the
  new error. Unverifiable snapshots carry a marker so the label reads
  "Usage unavailable"; no fetch failed, and no retry will help.
- Bar visibility was still gated on this laptop's PATH detection, so a viewer
  with no agent CLIs installed saw none of the server's bars. Detection
  describes the local machine only, so it no longer gates bars a remote owner
  provides.

Losing contact also keeps the last snapshot the server vouched for (blanked,
carrying the verdict) instead of making its bars disappear.

@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

🧹 Nitpick comments (2)
src/renderer/src/components/status-bar/remote-usage-rate-limits.ts (1)

158-169: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Optional: discard refresh results that land after the owner changes.

refresh captures ownerId in its closure. If the user switches the Active Server while fetchProviderAccountsSnapshot is in flight, the resolution still calls applyOwned with the previous ownerId. That write lands in ownedRef.current and owned.

The rendered state is not wrong, because the state memo discards snapshots whose ownerId does not match. The write is still redundant, and it briefly replaces the ref content that lastKnownFor reads.

A small guard keeps the ref consistent with the active owner.

♻️ Proposed guard
     timer = window.setTimeout(entry.settle, REMOTE_USAGE_REFRESH_SETTLE_TIMEOUT_MS)
     pendingRefreshRef.current?.settle()
     pendingRefreshRef.current = entry
+    const isCurrentOwner = (): boolean => pendingRefreshRef.current === entry || true
     try {
       const snapshot = await fetchProviderAccountsSnapshot({ activeRuntimeEnvironmentId: ownerId })

A simpler form is to compare against a ref that the watcher effect keeps in sync with the active ownerId, and to skip both applyOwned calls when the ids differ.

src/renderer/src/components/status-bar/remote-usage-rate-limits.test.ts (1)

257-287: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a test for the 8-second refresh timeout.

The hook documents REMOTE_USAGE_REFRESH_SETTLE_TIMEOUT_MS as the escape hatch that releases the refresh button when the owner sends no newer data. No test covers it. A regression that removes the timer would only surface as a permanently disabled refresh button in production.

Use vi.useFakeTimers() and advance past the timeout after a refresh that returns identical updatedAt values.

🧪 Sketch
+  it('releases the refresh promise after the settle timeout', async () => {
+    vi.useFakeTimers()
+    try {
+      const { result } = renderHook(() =>
+        useRemoteUsageRateLimits({ activeRuntimeEnvironmentId: 'env-a' })
+      )
+      act(() => {
+        latestWatcher().onSnapshot({ rateLimits: rateLimits(71, 5_000) })
+      })
+      mocks.fetchSnapshot.mockResolvedValue({ rateLimits: rateLimits(71, 5_000) })
+
+      let settled = false
+      await act(async () => {
+        const pending = result.current.refresh!().then(() => {
+          settled = true
+        })
+        await vi.advanceTimersByTimeAsync(8_000)
+        await pending
+      })
+      expect(settled).toBe(true)
+    } finally {
+      vi.useRealTimers()
+    }
+  })

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: abda9750-cc06-4dfd-bd1e-2dba738fb37e

📥 Commits

Reviewing files that changed from the base of the PR and between 2b1254d and a5021e1.

📒 Files selected for processing (9)
  • src/renderer/src/components/status-bar/StatusBar.tsx
  • src/renderer/src/components/status-bar/remote-usage-rate-limits.test.ts
  • src/renderer/src/components/status-bar/remote-usage-rate-limits.ts
  • src/renderer/src/components/status-bar/status-bar-provider-visibility.ts
  • src/renderer/src/components/status-bar/usage-error-copy.ts
  • src/renderer/src/components/status-bar/usage-rate-limits-source.test.ts
  • src/renderer/src/components/status-bar/usage-rate-limits-source.ts
  • 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; 1 remains after this review.

Comment on lines +132 to +150
function adoptRemoteRateLimits(local: RateLimitState, remote: RateLimitState): RateLimitState {
const partial = remote as PartialRemoteRateLimitState
return {
...remote,
// Why: MiniMax/Grok sign-in lives on disk, so a host older than those
// providers omits the flags entirely; falling back to the local value keeps
// a configured bar visible instead of making it disappear on the first
// remote snapshot.
minimaxCookieConfigured: normalizeFlag(
partial.minimaxCookieConfigured,
local.minimaxCookieConfigured
),
grokAuthConfigured: normalizeFlag(partial.grokAuthConfigured, local.grokAuthConfigured),
claudeTarget: partial.claudeTarget ?? local.claudeTarget,
codexTarget: partial.codexTarget ?? local.codexTarget,
inactiveClaudeAccounts: partial.inactiveClaudeAccounts ?? [],
inactiveCodexAccounts: partial.inactiveCodexAccounts ?? []
}
}

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Inspect definition and downstream usage of inactiveClaudeAccounts/inactiveCodexAccounts
# to confirm whether omission on older hosts should fall back to local state.
set -euo pipefail

echo "--- rate-limit-types.ts definition ---"
rg -n -B2 -A2 'inactiveClaudeAccounts|inactiveCodexAccounts' src/shared/rate-limit-types.ts

echo "--- Usages across renderer ---"
rg -n -C3 'inactiveClaudeAccounts|inactiveCodexAccounts' src/renderer

Repository: stablyai/orca

Length of output: 10001


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "--- rate-limit types ---"
sed -n '110,155p' src/shared/rate-limit-types.ts

echo "--- source implementation and tests ---"
sed -n '1,220p' src/renderer/src/components/status-bar/usage-rate-limits-source.ts
sed -n '1,260p' src/renderer/src/components/status-bar/usage-rate-limits-source.test.ts

echo "--- producers and hydration paths ---"
rg -n -C4 'inactiveClaudeAccounts|inactiveCodexAccounts|adoptRemoteRateLimits|PartialRemoteRateLimitState|RemoteUsageState' src/renderer src/shared src/main

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "--- remote usage transport and merge call sites ---"
rg -n -C8 'resolveStatusBarUsageRateLimits|kind: .remote.|rateLimits.*remote|remoteUsage' \
  src/renderer/src src/shared --glob '*.{ts,tsx}'

echo "--- inactive-account consumers ---"
sed -n '890,920p' src/renderer/src/components/status-bar/StatusBar.tsx
sed -n '1780,1810p' src/renderer/src/components/status-bar/StatusBar.tsx

echo "--- relevant source tests after the existing remote compatibility test ---"
rg -n -C8 'preFlagHost|older|optional|inactiveClaudeAccounts|inactiveCodexAccounts' \
  src/renderer/src/components/status-bar/usage-rate-limits-source.test.ts

echo "--- changed-file summary ---"
git diff --stat -- src/renderer/src/components/status-bar/usage-rate-limits-source.ts \
  src/renderer/src/components/status-bar/usage-rate-limits-source.test.ts \
  src/shared/rate-limit-types.ts

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "--- remote snapshot shape and callback ---"
sed -n '1,135p' src/renderer/src/components/status-bar/remote-usage-rate-limits.ts
rg -n -C6 'watchProviderAccounts|OwnedUsageSnapshot|rateLimits:' \
  src/renderer/src/components/status-bar/remote-usage-rate-limits.ts \
  src/renderer/src/components/status-bar/remote-usage-rate-limits.test.ts

echo "--- inactive-account type and account registries ---"
rg -n -C5 'type InactiveAccountUsage|interface InactiveAccountUsage|InactiveClaudeAccountInfo|InactiveCodexAccountInfo|inactive.*Accounts' \
  src/shared src/main src/renderer/src \
  --glob '*.{ts,tsx}' \
  | head -n 400

echo "--- file change summary ---"
git diff --stat

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "--- provider-account snapshot types and serialization ---"
rg -n -C8 'ProviderAccountsSnapshot|rateLimits.*RateLimitState|getAccountsSnapshot|accounts\.subscribe|accounts\.list' \
  src/main src/renderer/src src/shared --glob '*.{ts,tsx}' \
  | head -n 500

echo "--- account IDs used by the status bar ---"
sed -n '880,925p' src/renderer/src/components/status-bar/StatusBar.tsx
sed -n '1770,1810p' src/renderer/src/components/status-bar/StatusBar.tsx

echo "--- local account resolver wiring ---"
rg -n -C10 'setInactiveClaudeAccountsResolver|setInactiveCodexAccountsResolver|InactiveClaudeAccountInfo|InactiveCodexAccountInfo' \
  src/main --glob '*.{ts,tsx}' \
  | head -n 500

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

node - <<'JS'
const local = {
  inactiveClaudeAccounts: [
    { accountId: 'local-claude', rateLimits: { status: 'unavailable' } }
  ],
  inactiveCodexAccounts: [
    { accountId: 'local-codex', rateLimits: { status: 'unavailable' } }
  ]
}

const remote = { ...local }
delete remote.inactiveClaudeAccounts
delete remote.inactiveCodexAccounts

const current = {
  ...remote,
  inactiveClaudeAccounts: remote.inactiveClaudeAccounts ?? [],
  inactiveCodexAccounts: remote.inactiveCodexAccounts ?? []
}

const proposed = {
  ...remote,
  inactiveClaudeAccounts: remote.inactiveClaudeAccounts ?? local.inactiveClaudeAccounts,
  inactiveCodexAccounts: remote.inactiveCodexAccounts ?? local.inactiveCodexAccounts
}

const currentClaude = current.inactiveClaudeAccounts.find(
  (account) => account.accountId === 'local-claude'
)
const currentCodex = current.inactiveCodexAccounts.find(
  (account) => account.accountId === 'local-codex'
)

if (currentClaude !== undefined || currentCodex !== undefined) {
  throw new Error('The current fallback did not reset omitted arrays')
}
if (proposed.inactiveClaudeAccounts[0].accountId !== 'local-claude') {
  throw new Error('The proposed Claude fallback did not preserve local state')
}
if (proposed.inactiveCodexAccounts[0].accountId !== 'local-codex') {
  throw new Error('The proposed Codex fallback did not preserve local state')
}

console.log(JSON.stringify({
  current: {
    inactiveClaudeAccounts: current.inactiveClaudeAccounts,
    inactiveCodexAccounts: current.inactiveCodexAccounts,
    downstreamClaudeMatch: currentClaude ?? null,
    downstreamCodexMatch: currentCodex ?? null
  },
  proposed: {
    inactiveClaudeAccounts: proposed.inactiveClaudeAccounts,
    inactiveCodexAccounts: proposed.inactiveCodexAccounts
  }
}, null, 2))
JS

Repository: stablyai/orca

Length of output: 647


Preserve inactive-account state for older remote hosts.

When the remote snapshot omits inactiveClaudeAccounts or inactiveCodexAccounts, falling back to [] removes local entries used by the status bar for account usage and sign-in state. Use the local arrays as the compatibility fallback.

🐛 Proposed fix
-    inactiveClaudeAccounts: partial.inactiveClaudeAccounts ?? [],
-    inactiveCodexAccounts: partial.inactiveCodexAccounts ?? []
+    inactiveClaudeAccounts: partial.inactiveClaudeAccounts ?? local.inactiveClaudeAccounts,
+    inactiveCodexAccounts: partial.inactiveCodexAccounts ?? local.inactiveCodexAccounts
📝 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
function adoptRemoteRateLimits(local: RateLimitState, remote: RateLimitState): RateLimitState {
const partial = remote as PartialRemoteRateLimitState
return {
...remote,
// Why: MiniMax/Grok sign-in lives on disk, so a host older than those
// providers omits the flags entirely; falling back to the local value keeps
// a configured bar visible instead of making it disappear on the first
// remote snapshot.
minimaxCookieConfigured: normalizeFlag(
partial.minimaxCookieConfigured,
local.minimaxCookieConfigured
),
grokAuthConfigured: normalizeFlag(partial.grokAuthConfigured, local.grokAuthConfigured),
claudeTarget: partial.claudeTarget ?? local.claudeTarget,
codexTarget: partial.codexTarget ?? local.codexTarget,
inactiveClaudeAccounts: partial.inactiveClaudeAccounts ?? [],
inactiveCodexAccounts: partial.inactiveCodexAccounts ?? []
}
}
function adoptRemoteRateLimits(local: RateLimitState, remote: RateLimitState): RateLimitState {
const partial = remote as PartialRemoteRateLimitState
return {
...remote,
// Why: MiniMax/Grok sign-in lives on disk, so a host older than those
// providers omits the flags entirely; falling back to the local value keeps
// a configured bar visible instead of making it disappear on the first
// remote snapshot.
minimaxCookieConfigured: normalizeFlag(
partial.minimaxCookieConfigured,
local.minimaxCookieConfigured
),
grokAuthConfigured: normalizeFlag(partial.grokAuthConfigured, local.grokAuthConfigured),
claudeTarget: partial.claudeTarget ?? local.claudeTarget,
codexTarget: partial.codexTarget ?? local.codexTarget,
inactiveClaudeAccounts: partial.inactiveClaudeAccounts ?? local.inactiveClaudeAccounts,
inactiveCodexAccounts: partial.inactiveCodexAccounts ?? local.inactiveCodexAccounts
}
}

@nwparker
nwparker marked this pull request as draft August 23, 2026 04:28
@nwparker

Copy link
Copy Markdown
Contributor Author

Holding this one per maintainer decision — converted to draft and labelled wip. CI is green and it merges clean, so this is a scheduling/scope hold rather than a defect. Leaving #15804 open while this sits.

@Tonic-Jin

Copy link
Copy Markdown

Reproduced the underlying problem on a third pairing shape: Windows 11 viewer (1.4.197) + Linux orca serve (1.4.197), details in #15798. The host publishes rateLimits in the accounts snapshot and the viewer never consumes it; two things follow that make this PR matter more on Windows:

Is there anything contributors can do to move the hold along (rebase onto the post-#17244/#17277/#17286 layout, split into smaller PRs, more test coverage)? I can test the branch on the Windows + Linux orca serve pairing.

@mmarabel

Copy link
Copy Markdown
Contributor

Field corroboration (2026-09-11, related: #20118 / #20120): desktop Orca on macOS with a paired Hetzner VPS environment as the workspace runtime. The desktop's rateLimits.claude targets the Mac host (credentialSource: 'none' — Mac Keychain entry exists but tokens emptied) while the VPS holds a valid native ~/.claude/.credentials.json (Pro tier). So the meter reflects the wrong machine's empty store although the machine running the sessions could report usage. This PR is the architectural fix for the host side; #20120 only makes the desktop-side failure visible instead of silent.

@nwparker

Copy link
Copy Markdown
Contributor Author

Superseded by #29430, which reimplements this approach on the current status bar (including the newer Cursor and ZCode meters) and is merged. Closing.

@nwparker nwparker closed this Oct 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

wip Actively being worked on

Projects

None yet

4 participants