Skip to content

fix(web): usage and account switching come from the paired server - #27135

Merged
OrcaWin merged 1 commit into
mainfrom
OrcaWin/d4-d4-s6a
Oct 10, 2026
Merged

OrcaWin merged 1 commit into
mainfrom
OrcaWin/d4-d4-s6a

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Oct 10, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​288 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​288
Prod 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​243 $\color{#cf222e}{\Huge{\mathbf{−}}}$​35 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​208

ELI5

In the browser version of Orca, the bottom bar never showed how much Claude or Codex quota you had used, and picking a different account did nothing. The server always knew these numbers; the web page just never asked. Now it asks the server, shows the same usage bars as the desktop app, and account switches happen on the server.

What Changed

Before: in the paired web client the status bar had no usage bars, the Usage menu was empty, and the Claude/Codex account lists were empty, so switching did nothing. Clicking "Add account" looked like it worked and then showed an empty list.

After: the web client shows the server's usage per provider, keeps it current as the server publishes changes, refreshes on demand, and lists, switches and removes the server's Claude and Codex accounts. "Add account" and "Sign in again" now show a message saying this has to be done in the desktop app on the machine running Orca, instead of quietly emptying the list.

Mechanism: the web client talks to its one paired server directly, so the app reads usage and accounts through the web page's own bridge (window.api.rateLimits, window.api.claudeAccounts, window.api.codexAccounts). On the web, those bridges returned fixed empty values. This PR connects them to calls the server already offers to paired clients:

Bridge Now calls
rateLimits.get accounts.list { refreshUsage: false } → rateLimits from that snapshot
rateLimits.refresh, the per-target refreshes, fetchInactive*Accounts accounts.list { refreshUsage: true }. Calls made at the same time share one request.
rateLimits.onUpdate one shared accounts.subscribe stream. It starts with the first listener, stops with the last, and reconnects 5s after it drops.
claudeAccounts / codexAccounts list, select, remove accounts.list, accounts.selectClaude / selectCodex / selectCodexForTarget (WSL), accounts.removeClaude / removeCodex

Safety details:

  • If a refresh times out or the server can't be reached, the last usage the server sent is kept, so the bars don't go blank.
  • A server whose snapshot has no usage sends nothing, so the bars stay hidden instead of showing zeros.
  • Choosing a Codex account for a WSL lane uses the server's WSL-specific call, so the host lane is left alone. There is no WSL-specific Claude call, so switching a WSL lane back to "system default" is refused with a reason, because otherwise it would reset the host lane.
  • If the server can't be reached, the account list shows an error instead of an empty roster that looks like "no accounts".

Why

The server already sends all of this data. These are the same calls the mobile app uses for the same screens, paired clients are already allowed to make them, and nothing changes on the server or in the protocol. Fixing it in the web bridge means every screen that shows this data (status bar, usage list, account switcher, Accounts settings) keeps working unchanged and simply gets real data on the web. The alternative was to treat the web client as a "remote server is selected" desktop, which would have changed unrelated behavior across the app.

Adding an account on a remote host needs a sign-in-link flow. That is planned as separate follow-up work, so for now add and sign-in-again fail with a clear reason instead of pretending to work.

The approach and most of the tests come from #25133 by @gustavobragac (credited as co-author). Changes from that PR: the last usage is kept when a refresh fails, simultaneous refreshes share one request, add and sign-in-again are refused with a reason, and the extra refresh after each switch is dropped because the server already pushes updated usage when the selection changes.

Linked Issue

Fixes #25132

Visual Proof

N/A. This environment can't launch the app. The behavior is covered by web-preload-api-rate-limits.test.ts, which talks to a stubbed paired server through the real web bridge.

Testing

  • New src/renderer/src/web/web-preload-api-rate-limits.test.ts (13 tests). On origin/main, 9 of the original 10 failed: usage came back empty, nothing subscribed, and select/remove never reached the server. All 13 pass with this change.

  • pnpm tc:web, oxlint, check:code-quality:changed, and localization catalog verification all pass. The existing web preload composition and agent-provider tests pass.

  • I manually tested these changes locally

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

Review

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Web client only. Desktop and mobile are unchanged. SSH: no change, because the paired server owns its accounts. Backward compatibility: only methods older servers already expose are used, and a server without rateLimits in its snapshot publishes nothing.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • 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)

The web client's usage and Claude/Codex account bridges were stubs, so the
status-bar usage bars never appeared and switching accounts did nothing.
Back them with the server's existing accounts.list / accounts.subscribe
snapshot (which already carries rate limits) and its select/remove RPCs.
Adding or re-signing accounts now fails with a reason instead of silently
returning an empty roster.

Harvests the approach and tests from #25133 by @gustavobragac.

Co-authored-by: gustavobragac <[email protected]>
@OrcaWin
OrcaWin requested a review from brennanb2025 as a code owner October 10, 2026 04:20
@coderabbitai

coderabbitai Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →Review in Change Stack →

📝 Walkthrough

Walkthrough

The web preload account APIs now read Claude and Codex account snapshots and route supported removal and selection actions through server RPCs. Adding or reauthenticating an account rejects with a desktop-only message. Rate-limit reads and updates now use account snapshots and subscriptions. Tests cover account operations, usage refreshes, stream updates, retries, and cleanup.


Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🔵 Low · up to 8c7b9

After switching or disconnecting a paired server, the web client can briefly show usage from the previous server. Scope cached and pending usage requests to the active server before merging, or explicitly accept this limited risk.

Pre-merge checks | Passed 4 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 21 functions across 3 files. (1 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check Passed The title clearly summarizes the main change: paired web usage and account switching now use the server.
Description check Passed The description is detailed and covers the required sections, including user impact, mechanism, rationale, linked issue, visual proof, testing, scope, and checklist status. It clearly reports that man…
Linked Issues check Passed Issue #25132 requires paired web usage display and Claude/Codex account switching. web-rate-limits-api.ts reads accounts.list, publishes rateLimits, subscribes to accounts.subscribe, retains t…
Out of Scope Changes check Passed The reviewed production changes are limited to web preload bridges and related localization messages. The added tests exercise the same usage and account behaviors. The host-only add and re-authentica…

Full details: Docstring Coverage

Explanation

Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 21 functions across 3 files. (1 skipped: 1 unsupported.)


  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

  • Autofix · 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: 4a5c9147-1f0f-4662-ab31-28d5deb1c530
📥 Commits

Reviewing files that changed from the base of the PR and between 7bd3928 and 8c7b9fc.

📒 Files selected for processing (4)
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/web/preload-api/web-agent-accounts-api.ts
  • src/renderer/src/web/preload-api/web-rate-limits-api.ts
  • src/renderer/src/web/web-preload-api-rate-limits.test.ts

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

Comment on lines +23 to +142
const listeners = new Set<(state: RateLimitState) => void>()
let stream: { unsubscribe: () => void } | null = null
let streamStarting = false
let resubscribeTimer: ReturnType<typeof setTimeout> | null = null
let lastState: RateLimitState | null = null

function publishRateLimits(state: RateLimitState): void {
lastState = state
for (const listener of listeners) {
listener(state)
}
}

function readSnapshotRateLimits(result: unknown): RateLimitState | null {
if (typeof result !== 'object' || result === null || !('snapshot' in result)) {
return null
}
const { snapshot } = result
if (typeof snapshot !== 'object' || snapshot === null || !('rateLimits' in snapshot)) {
return null
}
return isRateLimitState(snapshot.rateLimits) ? snapshot.rateLimits : null
}

function isRateLimitState(value: unknown): value is RateLimitState {
return typeof value === 'object' && value !== null && 'claude' in value && 'codex' in value
}

function scheduleResubscribe(): void {
stream = null
if (resubscribeTimer || listeners.size === 0) {
return
}
resubscribeTimer = setTimeout(() => {
resubscribeTimer = null
startStream()
}, RESUBSCRIBE_DELAY_MS)
}

function startStream(): void {
if (stream || streamStarting || listeners.size === 0) {
return
}
const environment = requireActiveEnvironmentOrNull()
if (!environment) {
scheduleResubscribe()
return
}
streamStarting = true
let handle: { unsubscribe: () => void } | null = null
// Why: getClientForEnvironment throws synchronously while manually disconnected;
// starting inside the chain always resets streamStarting so a reconnect can resubscribe.
void Promise.resolve()
.then(() =>
getClientForEnvironment(environment).subscribe('accounts.subscribe', null, {
onResponse: (response) => {
const state = response.ok ? readSnapshotRateLimits(response.result) : null
// Why: a server whose snapshot predates usage publishes nothing, not empty bars.
if (state) {
publishRateLimits(state)
}
},
onError: () => {
if (stream === handle) {
scheduleResubscribe()
}
},
onClose: () => {
if (stream === handle) {
scheduleResubscribe()
}
}
})
)
.then((subscription) => {
handle = subscription
stream = subscription
if (listeners.size === 0) {
stopStream()
}
})
.catch(() => scheduleResubscribe())
.finally(() => {
streamStarting = false
})
}

function stopStream(): void {
if (resubscribeTimer) {
clearTimeout(resubscribeTimer)
resubscribeTimer = null
}
const current = stream
stream = null
current?.unsubscribe()
}

async function readRateLimits(refreshUsage: boolean): Promise<RateLimitState> {
try {
const snapshot = await fetchAccountsSnapshot(refreshUsage)
if (snapshot.rateLimits) {
publishRateLimits(snapshot.rateLimits)
return snapshot.rateLimits
}
} catch {
// Why: a slow or unreachable server must not blank bars the stream already filled.
}
return lastState ?? createEmptyRateLimitState()
}

let pendingRefresh: Promise<RateLimitState> | null = null

// Why shared: a forced refresh can hold a call slot until provider fetches finish on the
// server, and the Accounts pane fires several at once.
function refreshRateLimits(): Promise<RateLimitState> {
pendingRefresh ??= readRateLimits(true).finally(() => {
pendingRefresh = null
})
return pendingRefresh
}

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:

sed -n '1,180p' src/renderer/src/web/preload-api/web-rate-limits-api.ts
rg -n 'createRateLimitsApi|activeEnvironment|onUpdate' src/renderer/src/web/preload-api src/renderer/src/web/web-preload-api* | head -100

Repository: stablyai/orca

Length of output: 11364


🏁 Script executed:

printf '%s\n' '--- web-runtime-environments-api.ts ---'
nl -ba src/renderer/src/web/preload-api/web-runtime-environments-api.ts | sed -n '1,230p'
printf '%s\n' '--- web-runtime-session.ts ---'
nl -ba src/renderer/src/web/preload-api/web-runtime-session.ts | sed -n '1,250p'
printf '%s\n' '--- runtime client bindings ---'
rg -n -F --glob '*.ts' -- 'getClientForEnvironment' src/renderer/src/web
rg -n -F --glob '*.ts' -- 'disconnect' src/renderer/src/web/preload-api src/renderer/src/web | head -120
rg -n -F --glob '*.ts' -- 'stopStream' src/renderer/src/web
printf '%s\n' '--- rate-limit lifecycle tests ---'
nl -ba src/renderer/src/web/web-preload-api-rate-limits.test.ts | sed -n '1,340p'

Repository: stablyai/orca

Length of output: 42124


🏁 Script executed:

printf '%s\n' '--- web-runtime-client.ts ---'
nl -ba src/renderer/src/web/web-runtime-client.ts | sed -n '1,300p'
printf '%s\n' '--- client subscription/transport close bindings ---'
rg -n -F --glob '*.ts' -- 'onClose' src/renderer/src/web | head -160
rg -n -F --glob '*.ts' -- 'close()' src/renderer/src/web/web-runtime-client.ts src/renderer/src/web/web-runtime-*.ts
printf '%s\n' '--- environment switch/disconnect tests ---'
nl -ba src/renderer/src/web/web-preload-api-runtime-environment.test.ts | sed -n '130,360p'
printf '%s\n' '--- all rate-limit environment references ---'
rg -n -F --glob '*.ts' -- 'rateLimits' src/renderer/src/web | head -160

Repository: stablyai/orca

Length of output: 30267


🏁 Script executed:

printf '%s\n' '--- web-runtime-calls.ts ---'
nl -ba src/renderer/src/web/preload-api/web-runtime-calls.ts | sed -n '1,120p'
printf '%s\n' '--- subscription registry ---'
nl -ba src/renderer/src/web/web-runtime-subscription-registry.ts | sed -n '1,100p'
printf '%s\n' '--- transport close path ---'
nl -ba src/renderer/src/web/web-runtime-connection-transport.ts | sed -n '70,220p'
printf '%s\n' '--- frame router close path ---'
nl -ba src/renderer/src/web/web-runtime-connection-frame-router.ts | sed -n '110,150p'

Repository: stablyai/orca

Length of output: 16034


Scope the cached usage to the active environment.

disconnect and environment replacement close the old client, but they do not clear lastState. After environment A publishes usage, a failed or incomplete accounts.list for environment B returns that cached state. A manual disconnect also catches the runtime_manually_disconnected error and returns A's usage. This can show the prior environment's limits as the current environment's limits.

Suggested fix
-import { getClientForEnvironment, requireActiveEnvironmentOrNull } from './web-runtime-session'
+import {
+  getClientForEnvironment,
+  manuallyDisconnectedEnvironmentIds,
+  requireActiveEnvironmentOrNull
+} from './web-runtime-session'
...
-let lastState: RateLimitState | null = null
+let lastState: { environmentId: string; state: RateLimitState } | null = null
 
-function publishRateLimits(state: RateLimitState): void {
-  lastState = state
+function publishRateLimits(state: RateLimitState, environmentId: string): void {
+  lastState = { environmentId, state }
...
-            publishRateLimits(state)
+            if (
+              requireActiveEnvironmentOrNull()?.id === environment.id &&
+              !manuallyDisconnectedEnvironmentIds.has(environment.id)
+            ) {
+              publishRateLimits(state, environment.id)
+            }
...
 async function readRateLimits(refreshUsage: boolean): Promise<RateLimitState> {
+  const environment = requireActiveEnvironmentOrNull()
   try {
     const snapshot = await fetchAccountsSnapshot(refreshUsage)
-    if (snapshot.rateLimits) {
-      publishRateLimits(snapshot.rateLimits)
+    if (
+      snapshot.rateLimits &&
+      environment &&
+      requireActiveEnvironmentOrNull()?.id === environment.id &&
+      !manuallyDisconnectedEnvironmentIds.has(environment.id)
+    ) {
+      publishRateLimits(snapshot.rateLimits, environment.id)
       return snapshot.rateLimits
     }
...
-  return lastState ?? createEmptyRateLimitState()
+  const currentEnvironment = requireActiveEnvironmentOrNull()
+  return currentEnvironment &&
+    !manuallyDisconnectedEnvironmentIds.has(currentEnvironment.id) &&
+    lastState?.environmentId === currentEnvironment.id
+    ? lastState.state
+    : createEmptyRateLimitState()
 }

Comment on lines +128 to +142
// Why: a slow or unreachable server must not blank bars the stream already filled.
}
return lastState ?? createEmptyRateLimitState()
}

let pendingRefresh: Promise<RateLimitState> | null = null

// Why shared: a forced refresh can hold a call slot until provider fetches finish on the
// server, and the Accounts pane fires several at once.
function refreshRateLimits(): Promise<RateLimitState> {
pendingRefresh ??= readRateLimits(true).finally(() => {
pendingRefresh = null
})
return pendingRefresh
}

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:

sed -n '115,175p' src/renderer/src/web/preload-api/web-rate-limits-api.ts
sed -n '35,90p' src/renderer/src/web/preload-api/web-runtime-environments-api.ts
rg -n 'pendingRefresh|refreshUsage|refreshAll' src/renderer/src/web/web-preload-api-rate-limits.test.ts src/renderer/src/web/preload-api/web-rate-limits-api.ts

Repository: stablyai/orca

Length of output: 5658


🏁 Script executed:

set -eu
printf '%s\n' '--- web-rate-limits-api.ts ---'
nl -ba src/renderer/src/web/preload-api/web-rate-limits-api.ts | sed -n '1,180p'
printf '%s\n' '--- environment lifecycle and active-environment helpers ---'
rg -n -F --glob '*.ts' -- 'activeEnvironment|closeActiveRuntimeClients|disconnectActiveRuntimeEnvironment|requireActiveEnvironmentOrNull' src/renderer/src/web/preload-api src/renderer/src/web | sed -n '1,220p'
printf '%s\n' '--- account and rate-limit callers ---'
rg -n -F --glob '*.ts' -- 'refreshClaudeForTarget|refreshCodexForTarget|refreshMiniMax|refreshGrok|fetchInactiveClaudeAccounts|fetchInactiveCodexAccounts|rateLimits.refresh|rateLimits.get' src/renderer/src/web src/renderer/src | sed -n '1,240p'
printf '%s\n' '--- focused tests ---'
nl -ba src/renderer/src/web/web-preload-api-rate-limits.test.ts | sed -n '1,240p'

Repository: stablyai/orca

Length of output: 17628


Scope the pending refresh to the active environment.

pendingRefresh is module-global. If environment A starts a forced refresh and the active environment changes to B before it completes, B reuses A's promise. B can receive A's successful rate-limit snapshot without sending an accounts.list request for B. Scoping lastState and guarding publication does not change the value returned by this shared promise.

Suggested fix
-let pendingRefresh: Promise<RateLimitState> | null = null
+let pendingRefresh: {
+  environment: ReturnType<typeof requireActiveEnvironmentOrNull>
+  promise: Promise<RateLimitState>
+} | null = null

 // Why shared: a forced refresh can hold a call slot until provider fetches finish on the
 // server, and the Accounts pane fires several at once.
 function refreshRateLimits(): Promise<RateLimitState> {
-  pendingRefresh ??= readRateLimits(true).finally(() => {
-    pendingRefresh = null
-  })
-  return pendingRefresh
+  const environment = requireActiveEnvironmentOrNull()
+  if (pendingRefresh?.environment === environment) {
+    return pendingRefresh.promise
+  }
+  const promise = readRateLimits(true).finally(() => {
+    if (pendingRefresh?.promise === promise) {
+      pendingRefresh = null
+    }
+  })
+  pendingRefresh = { environment, promise }
+  return promise
 }
📝 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
// Why: a slow or unreachable server must not blank bars the stream already filled.
}
return lastState ?? createEmptyRateLimitState()
}
let pendingRefresh: Promise<RateLimitState> | null = null
// Why shared: a forced refresh can hold a call slot until provider fetches finish on the
// server, and the Accounts pane fires several at once.
function refreshRateLimits(): Promise<RateLimitState> {
pendingRefresh ??= readRateLimits(true).finally(() => {
pendingRefresh = null
})
return pendingRefresh
}
// Why: a slow or unreachable server must not blank bars the stream already filled.
}
return lastState ?? createEmptyRateLimitState()
}
let pendingRefresh: {
environment: ReturnType<typeof requireActiveEnvironmentOrNull>
promise: Promise<RateLimitState>
} | null = null
// Why shared: a forced refresh can hold a call slot until provider fetches finish on the
// server, and the Accounts pane fires several at once.
function refreshRateLimits(): Promise<RateLimitState> {
const environment = requireActiveEnvironmentOrNull()
if (pendingRefresh?.environment === environment) {
return pendingRefresh.promise
}
const promise = readRateLimits(true).finally(() => {
if (pendingRefresh?.promise === promise) {
pendingRefresh = null
}
})
pendingRefresh = { environment, promise }
return promise
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Web client shows no usage and can't switch Claude/Codex accounts

1 participant