Repository navigation
feat(agent-session): let the host own a chat's tab id and let a create reserve it - #22616
Conversation
…e reserve it A structured chat's tab id was derived from its session id by every layer that needed one: the renderer, the host snapshot and the status address each built their own spelling. The join between a conversation and the tab that shows it must be a pointer the host owns, not a derivation each client repeats. The session record now carries surfaceTabId. A create pins it: the tab half of the pane agent.launch reserved, an optional tabId on agentSession.create, or a host-minted UUID. Records written before the field existed are backfilled at open with the string clients derived, in memory at once and on disk with the store's first transaction, so nothing keyed by it (read state, notification ids, worker rows) moves on upgrade. A second record under a held id is refused. Only the record and the two create wires change here. The snapshot still publishes agent-session:<sid> and the renderer still derives its local id; those move in the next two changes. agentSession.create is a strict object, so the field is advertised as a capability a client checks before sending it.
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review. 📝 WalkthroughWalkthroughStructured-session creation now carries an optional tab ID from the launch pane key into the create request and its fingerprint. The host validates and reserves the ID, or derives one from the session ID when the caller does not provide it. Session records store the ID, and store loading backfills it for legacy records. The attach result and structured launch outcome include the ID when available. A runtime capability identifies hosts that accept the create parameter. Priority: ⬇️ Low Merge Risk: 🟡 Moderate · up to A retry requesting a different tab can silently return the first tab’s reservation. A tab collision can also be reported as a taken session. Resolve the retry behavior before merging. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description gives a detailed explanation of the behavior, rationale, compatibility, visual proof, and testing. However, it does not provide the required linked issue, and it omits the AI Disclosure, Agent skill upstream boundary, and Checklist sections from the repository template. Resolution Add a valid linked issue after "Fixes #". Include the AI Disclosure, Agent skill upstream boundary, and Checklist sections, with applicable checkboxes selected and any required explanations. Retain "N/A" only where the section is not applicable.
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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: 3
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 8de107a8-b9ca-4710-a434-3b3b1bbb2042
📒 Files selected for processing (25)
src/main/agent-launch/agent-launch-executor.tssrc/main/agent-launch/agent-launch-surface-factories.tssrc/main/native-chat/agent-session-wire/structured-agent-session-acquisition-options.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.tssrc/main/native-chat/agent-session-wire/structured-agent-session-attach.tssrc/main/runtime/agent-session-record-store-file.tssrc/main/runtime/agent-session-record-store-surface-tab-id.test.tssrc/main/runtime/agent-session-record-store.tssrc/main/runtime/agent-session-reservation-admission.tssrc/main/runtime/agent-session-store-transaction-queue.tssrc/main/runtime/rpc/methods/agent-launch-session-reservation.test.tssrc/main/runtime/rpc/methods/agent-launch-surfaces.tssrc/main/runtime/rpc/methods/structured-agent-session-create.tssrc/main/runtime/rpc/methods/structured-agent-session.test.tssrc/main/runtime/rpc/methods/structured-agent-session.tssrc/shared/agent-launch-intent.tssrc/shared/agent-session-launch-args.tssrc/shared/agent-session-record.tssrc/shared/agent-session-surface-tab-id.tssrc/shared/agent-session-wire.tssrc/shared/protocol-version.tssrc/shared/rpc-contract/structured-agent-session-params.tssrc/shared/structured-agent-session-create.test.tssrc/shared/structured-agent-session-create.tssrc/shared/structured-agent-session-mutation.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.
| for (const record of state.records.values()) { | ||
| if (record.sessionId !== request.sessionId && record.surfaceTabId === request.surfaceTabId) { | ||
| throw new Error('agent_session_conflict') | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
# Confirm how store errors become refusal codes on the attach path.
rg -nP -C10 'function classifyStoreFailure' src/main/native-chat
rg -nP -C3 "agent_session_conflict" src/main/runtime/rpc/methods src/main/agent-launchRepository: stablyai/orca
Length of output: 4207
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- reservation admission ---'
sed -n '210,285p' src/main/runtime/agent-session-reservation-admission.ts
printf '%s\n' '--- launch surface refusal handling ---'
sed -n '55,105p' src/main/runtime/rpc/methods/agent-launch-surfaces.ts
printf '%s\n' '--- classifier and refusal-code declaration ---'
sed -n '1,90p' src/main/native-chat/agent-session-wire/structured-agent-session-attach.ts
sed -n '345,375p' src/main/native-chat/agent-session-wire/structured-agent-session-attach.ts
rg -n -C4 'AGENT_SESSION_WIRE_REFUSAL_CODES|AgentSessionWireRefusalCode|reserveAgentSession|assertSurfaceTabIdUnheld|surfaceTabId' src/main/runtime src/main/native-chatRepository: stablyai/orca
Length of output: 41705
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- refusal code declaration ---'
rg -n -C12 'AGENT_SESSION_WIRE_REFUSAL_CODES' src/main/shared src/shared src/main 2>/dev/null | head -120
printf '%s\n' '--- refusal message mapping ---'
rg -n -C8 'structuredAgentSessionRefusalMessage|agent_session_conflict' src/main/native-chat/agent-session-wire src/shared src/main/shared 2>/dev/null | head -160
printf '%s\n' '--- classifier call sites ---'
rg -n -C5 'classifyStoreFailure\(' src/main/native-chat src/main/runtimeRepository: stablyai/orca
Length of output: 36227
Use a distinct refusal code for surface-tab conflicts.
When a requested session reuses a surfaceTabId held by another session, the reservation throws agent_session_conflict. agent-launch-surfaces.ts maps that code to AgentLaunchSessionAlreadyExistsError, so the launch reports that the requested session already exists even when only the surface tab is occupied.
Use a distinct code, such as agent_session_surface_tab_conflict, and add it to AGENT_SESSION_WIRE_REFUSAL_CODES.
🐛 Suggested fix
- throw new Error('agent_session_conflict')
+ throw new Error('agent_session_surface_tab_conflict') 'agent_session_conflict',
+ 'agent_session_surface_tab_conflict',| // they are the session's initial state, not its identity, so a retry that re-resolves them | ||
| // must replay rather than conflict. | ||
| ...(args.options ? { options: args.options } : {}), | ||
| ...(args.tabId ? { surfaceTabId: args.tabId } : {}), |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
# Confirm which fingerprint the operation ledger stores for create-by-intent.
rg -nP -C8 'function admitAttachOrRefuse|function attachFingerprintFields' src/main/native-chat
rg -nP -C4 'surfaceTabId' src/main/native-chat/agent-session-wireRepository: stablyai/orca
Length of output: 12498
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- attach admission ---'
sed -n '104,185p' src/main/native-chat/agent-session-wire/structured-agent-session-attach.ts
printf '%s\n' '--- ledger symbols ---'
rg -n -P -C8 'reserveRequestFor|payloadFingerprint|hostFingerprint|clientOperationId|operation row|replay|conflict' src/main/native-chat src/main/runtime/rpc/methods/structured-agent-session-create.ts
printf '%s\n' '--- create path ---'
sed -n '1,210p' src/main/runtime/rpc/methods/structured-agent-session-create.ts
printf '%s\n' '--- create intent and operation handling ---'
rg -n -P -C10 'create-intent|CreateIntentParams|structuredAgentSessionCreateIntentFingerprint|reserveRequestFor|admitAttachOrRefuse' src/main/runtime/rpc src/main/native-chat/agent-session-wireRepository: stablyai/orca
Length of output: 45531
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- create conflict boundary ---'
sed -n '130,185p' src/main/runtime/rpc/methods/structured-agent-session.ts
printf '%s\n' '--- attach admission and reservation ---'
sed -n '120,145p' src/main/native-chat/agent-session-wire/structured-agent-session-attach.ts
sed -n '305,340p' src/main/native-chat/agent-session-wire/structured-agent-session-attach.ts
sed -n '80,145p' src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts
printf '%s\n' '--- reserveOwner declarations and implementation ---'
rg -n -P -C12 'reserveOwner\s*[:(]' src/main/runtime src/main/native-chat
printf '%s\n' '--- operation result types and replay handling ---'
rg -n -P -C10 'type .*Reserve|reserveOwner|replayed|fingerprint.*conflict|operation_conflict|operation_replay' src/main/runtime/agent-session-record-store* src/main/native-chat/agent-session-wireRepository: stablyai/orca
Length of output: 45545
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- files declaring reserveOwner ---'
rg -l 'reserveOwner' src/main --glob '*.ts' | sort
printf '%s\n' '--- exact declarations ---'
rg -n 'reserveOwner' src/main/runtime/agent-session-record-store.ts src/main/runtime/agent-session-record-store 2>/dev/null || true
printf '%s\n' '--- store files ---'
fd -t f 'agent-session-record-store' src/mainRepository: stablyai/orca
Length of output: 2493
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- reserveOwner implementation ---'
sed -n '130,265p' src/main/runtime/agent-session-record-store.ts
printf '%s\n' '--- reserve types ---'
rg -n -P -C8 'AgentSessionReserve(Request|Result)|reserveOwner' src/main/shared src/shared src/main/runtime/agent-session-record-store.ts 2>/dev/null || true
printf '%s\n' '--- conflict helper ---'
rg -n -P -C8 'function agentSessionFingerprintConflict|agentSessionFingerprintConflict' src/main/runtime/rpc src/main/shared src/shared 2>/dev/null || trueRepository: stablyai/orca
Length of output: 18399
🏁 Script executed:
#!/bin/bash
set -e
sed -n '1,280p' src/main/runtime/agent-session-reservation-admission.ts
printf '%s\n' '--- ledger admission definitions ---'
rg -n -P -C12 'admitAgentSessionMutation|AgentSessionOperationDecision|operationLedger|operationId|fingerprint' src/shared/agent-session-mutation-envelope.ts src/shared/agent-session-operation-ledger.ts src/main/runtime/agent-session-reservation-admission.tsRepository: stablyai/orca
Length of output: 41754
🏁 Script executed:
#!/bin/bash
set -e
sed -n '147,185p' src/main/runtime/rpc/methods/structured-agent-session.tsRepository: stablyai/orca
Length of output: 1544
Include tabId in the durable create-operation identity.
The RPC check only compares the client fingerprint with the host fingerprint for the same payload. Preparation then computes the ledger fingerprint from attachFingerprintFields, which excludes surfaceTabId, and adds surfaceTabId afterward. Therefore, a retry from the same caller with the same operation ID but a different tabId has the same ledger fingerprint. The ledger replays the first record and returns its original tab ID instead of refusing the changed request.
Include tabId in the create-path ledger fingerprint. Alternatively, document that the first reservation wins and require clients to use value.tabId as the authoritative tab ID.
There was a problem hiding this comment.
ℹ️ No critical issues — one validation gap and one phase-2 migration question.
Reviewed changes
- Host-owned
surfaceTabId—AgentSessionRecordgains an optional, colon-free, length-bounded tab id; legacy records are backfilled in memory withstructured-agent-session-<sessionId>at load and reach disk on the first transaction, not at open. - Reservation pins and refuses — a create pins the reserved id on the new record, a second record under a held id is refused with
agent_session_conflict, and a colon-bearing id is refused asagent_session_operation_invalid. agentSession.creategains an optionaltabId— on the create-intent payload, part of the create fingerprint on both the client builder and the host recompute, and gated by the newagentSession.create.tab-id.v1capability because the create schema is strict.agent.launchreserves the tab half ofpaneKey— a launch that settles as a structured chat records the pane's tab id as the chat'stabId, and the structured outcome reports the host's recorded id back.- Two extractions —
isAgentSessionLaunchArgsand the create-intent fingerprint moved to new homes to stay under the line cap; both are behaviour-preserving.
ℹ️ New chats record an opaque id while every reader still derives the old string
The backfill keeps pre-existing chats working by filling the derived string, but a chat created after this lands records a random UUID (params.surfaceTabId ?? randomUUID()) while every current reader still derives structured-agent-session-<sessionId>. Nothing reads record.surfaceTabId for tab snapshots, the status address, worker keys, or read/unread state yet, so phase 1 behaves identically — but when those readers switch to the recorded id, the interim chats' state (written under the derived prefix) would be the ones orphaned, which is the exact class of loss the backfill exists to prevent. Worth confirming the next change migrates those chats, or that a new record keeps the derived spelling until readers switch.
Technical details
# The recorded id and the ids readers still use diverge for new chats
## Affected sites
- `src/main/native-chat/agent-session-wire/structured-agent-session-attach.ts:320` — a plain create (desktop renderer, mobile, orchestration worker) reserves no `tabId`, so the record gets a random UUID.
- `src/main/runtime/agent-session-record-store-file.ts:85` — `backfillAgentSessionSurfaceTabIds` fills legacy records with `structuredAgentSessionTabId(sessionId)`, the string readers derive.
- `src/shared/structured-agent-session-projection.ts:223` and callers (`structured-agent-session-provisional-tab.ts:25`, `runtime/web-session-tabs-sync/terminal-surfaces.ts:104`, `lib/structured-agent-session-launch-draft.ts:17`) — every reader derives the tab id from the session id.
- `src/main/persistence/restoring-sessions/pane-key-remapping.ts:19` — read/acknowledgement keys are `<tabId>:<leaf>` and the remapper preserves the tab prefix, so a prefix change orphans them with no repair.
## Required outcome
- Decide and document: chats created between now and the reader switch either keep the derived spelling on their record, or the switch to `record.surfaceTabId` carries a migration for state written under the derived prefix during the interim.
## Open questions
- Does the planned phase-2 change migrate read/unread state for chats created after this PR, or does it rely only on the load-time backfill (which covers pre-existing records only)?ℹ️ Nitpicks
structuredAgentSessionCreateIntentFingerprint(host recompute) andstructuredAgentSessionCreateFingerprint(client builder) independently list the same field set and method name. AddingtabIdto one and forgetting the other would refuse every create; a single shared field-list helper would remove the drift risk.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
A create that reserved no tab minted a random UUID that no reader uses: the renderer, status address, worker rows and host-shared read state all still key by structured-agent-session-<sid>. Persisted, that id would move every chat created before readers switch to the recorded one, orphaning its read state and worker rows the way the backfill exists to prevent. An unreserved create now records the derived id, the same rule the backfill applies, so the record always matches the prefix every existing key uses; an opaque mint belongs with the change that moves the last reader. Also: - a chat tab id must be a host tab id on the record, the create wire and in admission, matching what agent.launch already requires of paneKey; a web-surface id would decode as another tab - the stored launch-result guard checks the structured outcome's tabId - comments no longer claim a retry naming another tab conflicts; replay keys on the attach fingerprint and answers with the recorded id (now pinned) - the wire refusal test used a non-hex digest, so the schema refused it for that reason; it now reaches the tab id rule - pin that the reload path refills the id without forcing a save
There was a problem hiding this comment.
ℹ️ No critical issues — the new commit cleanly resolves the prior feedback; one description nit.
Reviewed changes
- Unreserved creates now record the derived id —
reserveRequestForfalls back tostructuredAgentSessionTabId(sessionId)instead of minting a random UUID, so a new record always matches the prefix every current reader derives. - Chat tab ids must be host tab ids —
isAgentSessionSurfaceTabIdnow composesisValidHostTerminalTabId, andagentSession.create'stabIduses that refine, so aweb-terminal-…or colon-bearing id is refused at the wire rather than persisted. isAgentLaunchOutcomevalidates the structuredtabId— the stored-launch guard rejects a non-string, mirroring the terminal arm'spaneKey, with a matching test.- Reload refill is pinned — a new record-store test shows an external rewrite refills the id in memory without forcing a save.
ℹ️ Nitpicks
- The PR description still describes the removed behaviour: "What Changed" §3 says the attach layer "mints a UUID" for a plain create, and the Why section says "only chats created after the upgrade get an opaque id". The commit now records the derived id for every unreserved create, so both should be updated to match.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
🟡 Minor · Propagate the recorded tab ID through publication and… · structured-agent-session-create.ts:130-140
src/main/runtime/rpc/methods/structured-agent-session-create.ts:130-140
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winPropagate the recorded tab ID through publication and lifecycle operations.
When a create supplies an explicit
tabId, the host persists it and returns it asresult.value.tabId. The commit then publishesagent-session:${sessionId}instead. The snapshot and renderer close path can therefore address a different tab than the returned host-owned ID.Suggested fix
diff --git a/src/main/runtime/rpc/methods/structured-agent-session-create.ts b/src/main/runtime/rpc/methods/structured-agent-session-create.ts @@ workspaceId: prepared.tab.workspaceId, sessionId: result.value.sessionId, agent: prepared.tab.agent, + ...(result.value.tabId ? { tabId: result.value.tabId } : {}), activate: args.activate }) diff --git a/src/main/runtime/orca-runtime-restore-structured-agent-session-tabs-once.ts b/src/main/runtime/orca-runtime-restore-structured-agent-session-tabs-once.ts @@ workspaceId: string sessionId: string agent: 'claude' | 'codex' + tabId?: string activate: boolean @@ - const id = `agent-session:${input.sessionId}` + const id = input.tabId ?? `agent-session:${input.sessionId}` diff --git a/src/main/runtime/orca-runtime-close-mobile-session-tab.ts b/src/main/runtime/orca-runtime-close-mobile-session-tab.ts @@ await this.notifier.closeSessionTab( - structuredAgentSessionTabId(tab.sessionId), + tab.id, worktreeId ) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-handoff-types.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-handoff-types.ts @@ workspaceId: string sessionId: string + tabId?: string agent?: 'claude' | 'codex' diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-handoff-reverse.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-handoff-reverse.ts @@ workspaceId: record.location.workspaceId, sessionId, + ...(record.surfaceTabId ? { tabId: record.surfaceTabId } : {}), agent: record.provider, diff --git a/src/main/runtime/orca-runtime-get-worktree-ps.ts b/src/main/runtime/orca-runtime-get-worktree-ps.ts @@ - revealNativeSession: async ({ workspaceId, sessionId, agent = 'codex', adoptedTerminal }) => { + revealNativeSession: async ({ + workspaceId, + sessionId, + tabId, + agent = 'codex', + adoptedTerminal + }) => { @@ workspaceId, sessionId, + ...(tabId ? { tabId } : {}), agent, activate: false }) - this.notifier?.focusEditorTab?.(structuredAgentSessionTabId(sessionId), workspaceId) + this.notifier?.focusEditorTab?.(tabId ?? structuredAgentSessionTabId(sessionId), workspaceId)This is a minor functional integration defect in the explicit-tab workflow. The correction is localized and preserves the derived-ID fallback for older callers.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 08950d29-7ef6-4d20-9720-79495acea34e
📒 Files selected for processing (14)
src/main/agent-launch/agent-launch-surface-factories.tssrc/main/native-chat/agent-session-wire/structured-agent-session-acquisition-options.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-attach.tssrc/main/runtime/agent-session-record-store-file.tssrc/main/runtime/agent-session-record-store-surface-tab-id.test.tssrc/main/runtime/rpc/methods/agent-launch-terminal-identity.test.tssrc/main/runtime/rpc/methods/structured-agent-session-create.tssrc/main/runtime/rpc/methods/structured-agent-session.test.tssrc/shared/agent-launch-intent.tssrc/shared/agent-session-record.tssrc/shared/agent-session-surface-tab-id.tssrc/shared/rpc-contract/agent-launch-params.tssrc/shared/rpc-contract/structured-agent-session-params.tssrc/shared/structured-agent-session-mutation.ts
🚧 Files skipped from review as they are similar to previous changes (7)
- src/shared/agent-session-surface-tab-id.ts
- src/main/runtime/agent-session-record-store-file.ts
- src/main/runtime/rpc/methods/structured-agent-session-create.ts
- src/shared/structured-agent-session-mutation.ts
- src/main/agent-launch/agent-launch-surface-factories.ts
- src/shared/rpc-contract/structured-agent-session-params.ts
- src/shared/agent-session-record.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.
Review status: ready to merge, all checks green at
|
stablyai#22616 (f0b3f44) added src/shared/agent-session-launch-args.ts and src/shared/agent-session-surface-tab-id.ts, which the session route reaches through the agent-session wire modules. Main measures 4221; the fork line is identical here (both trees built and compared). The pin's own comment already records this class of drift: a src/shared-only change never runs this suite, because the job's path filter covers only mobile/** and the builder scripts.
…fresh Review round two, from CodeRabbit and Pullfrog. - Credential precedence returned the first token that parsed, so an expired keychain token in front of a fresh Cursor IDE session reported "sign-in expired" on every poll while a usable session sat one source below. A live session now wins; the expired one is returned only when nothing live exists, so the actionable message still appears in that case. - The usage schema took `.optional()` where the route sends `null` for an absent sub-object, so one null pool failed the parse for the whole body and threw away valid pools and the billing cycle with it. - Cursor usage could survive an account switch: a failed refresh for account B kept account A's figures beside B's name in Accounts. The snapshot now carries a hashed account fingerprint, and a known-and-changed identity clears the previous reading. A refresh that names no account still keeps its own. - The Accounts section rendered nothing at all when a signed-in account's fetch failed, and could repaint an older account when two status reads overlapped. It now states the failure — beside the numbers when a stale snapshot remains — and ignores superseded reads. - A web client claimed "not signed in" for a host it cannot read, contradicting the meter beside it; it now says the detail is host-only. - Signed-out copy named `cursor-agent login` as the only way in, though an IDE sign-in works just as well. - The census comment ended at 4219 after the pacer squash without naming the two modules #22616 added; recorded them, re-measured on a clean origin/main. - Narrowed the docs claim: Cursor documents all-plan APIs, but no individual usage endpoint.
…d holds The host's tab snapshot named a structured chat by agent-session:<sessionId>, a spelling no pane key can carry and every client re-derived. The snapshot now publishes the id the session record holds (#22616), so every client copies one id and keys read state, notification ids and worker rows by it. The status address and orchestration worker key prefix move with it, because their readers correlate them with the snapshot; existing records were backfilled with the old string, so nothing persisted moves. A /clear replacement keeps its tab: the source hands its tab id to the replacement it declared, and the admission check admits exactly that. Paired clients that predate this still see agent-session:<sessionId>, projected per client behind session.tabs.chat-tab-id.v1 across every id-bearing snapshot field, and a chat named by that spelling on activate, close or move is resolved through the session it names. The desktop renderer is in-process and keeps deriving its own local id until it adopts the host's; the two IPC calls that address it keep the derived spelling for that reason, pinned by a ratchet.
…fresh Review round two, from CodeRabbit and Pullfrog. - Credential precedence returned the first token that parsed, so an expired keychain token in front of a fresh Cursor IDE session reported "sign-in expired" on every poll while a usable session sat one source below. A live session now wins; the expired one is returned only when nothing live exists, so the actionable message still appears in that case. - The usage schema took `.optional()` where the route sends `null` for an absent sub-object, so one null pool failed the parse for the whole body and threw away valid pools and the billing cycle with it. - Cursor usage could survive an account switch: a failed refresh for account B kept account A's figures beside B's name in Accounts. The snapshot now carries a hashed account fingerprint, and a known-and-changed identity clears the previous reading. A refresh that names no account still keeps its own. - The Accounts section rendered nothing at all when a signed-in account's fetch failed, and could repaint an older account when two status reads overlapped. It now states the failure — beside the numbers when a stale snapshot remains — and ignores superseded reads. - A web client claimed "not signed in" for a host it cannot read, contradicting the meter beside it; it now says the detail is host-only. - Signed-out copy named `cursor-agent login` as the only way in, though an IDE sign-in works just as well. - The census comment ended at 4219 after the pacer squash without naming the two modules #22616 added; recorded them, re-measured on a clean origin/main. - Narrowed the docs claim: Cursor documents all-plan APIs, but no individual usage endpoint.
* feat(rate-limits): add Cursor usage tracking ## ELI5 If you use Cursor, Orca now shows how much of your monthly Cursor plan you have used, next to the Claude, Codex and Grok meters, and in Settings → Accounts. It reads the sign-in Cursor already saved on this computer and never changes it. ## What changed Cursor becomes a rate-limit provider like Grok: a status-bar meter (default-on, with its own toggle), a row in the usage roster, and a Settings → Accounts section naming the signed-in account. The credential is read from whichever of three stores has it, first match wins, all read-only: - the macOS login keychain item `cursor-access-token` / `cursor-user`, which is where `cursor-agent` 2026.06+ keeps the session; - `~/.cursor/auth.json` and its platform variants, used by older CLIs; - the Cursor IDE's `state.vscdb` (`cursorAuth/accessToken`), for people who never run the CLI. The keychain entry is the one current CLIs use, and reading only `auth.json` finds nothing on an up-to-date macOS install. A locked keychain cannot mask a readable `auth.json`, and a locked `state.vscdb` cannot mask either. `~/.cursor/cli-config.json` supplies the account's email and display name; it never holds a token. Usage comes from the dashboard route the Cursor web dashboard itself reads, because Cursor documents no individual-user usage API — every documented API is team- or Enterprise-scoped. Per Cursor's pricing docs an individual plan has two pools, Cursor Models and Other Models, both resetting with the billing cycle, plus optional on-demand spend; each becomes a named bucket. The headline percentage prefers `used / limit` over the sibling percentage fields, which are pre-rounded for the dashboard's own copy. Because the route is undocumented the mapping is defensive: an unrecognised payload resolves to `unavailable` and hides the bar rather than publishing a zero that reads as "no usage". Orca never runs `cursor-agent login` and never writes, refreshes or rotates a Cursor credential. An expired token short-circuits to an actionable "run cursor-agent login" instead of spending a request that can only 401 — not a rare case, since `cursor-agent status` still reports `isAuthenticated: true` against a token that expired months ago. ## Why this shape Six open PRs implement this feature and none reads the keychain, so each finds nothing for a large share of users; this takes the auth layer further and keeps what those PRs verified live. The bar is not gated on `cursor-agent` being on PATH, unlike other CLI providers, because an IDE-only session is real usage with no CLI to detect. `readKeychainPassword` moved out of the Claude keychain reader into `src/main/macos-keychain/generic-password.ts` so both providers share one `security(1)` wrapper. It is a byte-for-byte relocation, so Claude's credential path is unchanged; the two child_process allowlists move the entry with it and neither ratchet count changes. Co-authored-by: Preschian Febryantara <[email protected]> Co-authored-by: Qwesdy <[email protected]> Co-authored-by: ivo922 <[email protected]> Co-authored-by: Mihail Vratchanski <[email protected]> Co-authored-by: Tauri-EPO <[email protected]> Co-authored-by: Raajik <[email protected]> * test(rate-limits): name the JWT helper's segment type in the Cursor tests The anti-slop gate rejects a bare `object` parameter; the fixtures build a claims record, so say that. * fix(rate-limits): render Cursor's pools and keep its plan total visible Review of the first commit found the meter effectively blank for a healthy account, which the screenshots missed because the only Cursor session on hand had expired and never reached the success path. - The verbose status-bar segment filtered buckets through an allowlist written for Gemini's experimental models, so both Cursor pools were dropped and the fallback needed a `session` window Cursor never reports. A signed-in account rendered an icon and no number. The allowlist now admits Cursor's pools, and the fallback accepts a monthly window. - `getWindowSections` dropped `monthly` whenever buckets existed. Cursor puts the plan total there and its sub-pools in buckets, so a plan at 92% showed as 50% in the roster, the tooltip, and the tightest-usage pick. - A plan reporting `enabled: false` still published its 0% pools, painting a healthy meter for a pool the account does not own and skipping the request-quota fallback. - `redirect: 'error'` turned the dashboard's bounce to /login into a generic network failure, hiding the actionable sign-in message. - A busy `state.vscdb` (the IDE holds it open) surfaced as a provider error, which would pin an alert bar on Cursor IDE users who never set Cursor up in Orca. It falls through to "no credential" instead. - Refreshing the Accounts section read the keychain twice for one update. * fix(rate-limits): pin the platform in the Cursor keychain tests Review caught three cases that assumed macOS: the keychain source is behind an explicit `process.platform` check, so on the Linux CI runner the mocked read was never reached and the tests read the CLI file instead. They now set the platform they mean, and two new cases assert the off-macOS fall-through. Also track the credentials reference doc (docs/** is ignored by default, so a new reference needs its own allowlist entry) and give the visibility fixtures their own provider id instead of Grok's. * fix(rate-limits): prefer a live Cursor session and report a failed refresh Review round two, from CodeRabbit and Pullfrog. - Credential precedence returned the first token that parsed, so an expired keychain token in front of a fresh Cursor IDE session reported "sign-in expired" on every poll while a usable session sat one source below. A live session now wins; the expired one is returned only when nothing live exists, so the actionable message still appears in that case. - The usage schema took `.optional()` where the route sends `null` for an absent sub-object, so one null pool failed the parse for the whole body and threw away valid pools and the billing cycle with it. - Cursor usage could survive an account switch: a failed refresh for account B kept account A's figures beside B's name in Accounts. The snapshot now carries a hashed account fingerprint, and a known-and-changed identity clears the previous reading. A refresh that names no account still keeps its own. - The Accounts section rendered nothing at all when a signed-in account's fetch failed, and could repaint an older account when two status reads overlapped. It now states the failure — beside the numbers when a stale snapshot remains — and ignores superseded reads. - A web client claimed "not signed in" for a host it cannot read, contradicting the meter beside it; it now says the detail is host-only. - Signed-out copy named `cursor-agent login` as the only way in, though an IDE sign-in works just as well. - The census comment ended at 4219 after the pacer squash without naming the two modules #22616 added; recorded them, re-measured on a clean origin/main. - Narrowed the docs claim: Cursor documents all-plan APIs, but no individual usage endpoint. * fix(i18n): localize the web client's Cursor host-only notice It reaches the Accounts pane like any other string, so the coverage gate is right to want it in the catalog rather than allowlisted. * fix(rate-limits): name the Cursor account on failed refreshes, and ship the reworded copy Review round three. Both findings say an earlier fix did not actually take. - The account-switch guard reads `authProvenance` off the fresh result, but the fetcher stamped it only on success and network failures. The `stale-token`, 429, 5xx and parse results omitted it, and so did the expired-session branch — so a switch whose first refresh failed, which is precisely the case the guard exists for, still rendered the previous account's figures under the new name. Every failure holding a readable session now names its account; a missing or unreadable credential still names none. The service test also fed a result shape the fetcher never produces, so it proved nothing; it now uses the real stale-token shape, and the fetcher test asserts provenance across 401/429/5xx and expiry. - The reworded signed-out copy never rendered: a present catalog value beats the `translate()` fallback, and `sync:localization-catalog` only adds missing keys rather than updating changed defaults. Updated both strings in en.json, which also prunes them from the runtime-required catalog now that they match. * docs: keep the Cursor credentials reference out of the tree Its content lives in the PR description instead; docs/** stays ignored rather than gaining an allowlist entry for this branch. * test(mobile): drop the census note main no longer pins main removed `SESSION_ROUTE_MODULES` and re-pinned this lane on a different count, so the paragraph this branch added documents a number series that is gone. The branch touches nothing in this file now. --------- Co-authored-by: Preschian Febryantara <[email protected]> Co-authored-by: Qwesdy <[email protected]> Co-authored-by: ivo922 <[email protected]> Co-authored-by: Mihail Vratchanski <[email protected]> Co-authored-by: Tauri-EPO <[email protected]> Co-authored-by: Raajik <[email protected]>

ELI5
A native chat shows up in a tab. Until now, every part of Orca that needed that tab's id made one up from the chat's session id, each in its own spelling: the desktop app, the host's tab list, and the status address. That works only while everyone derives the same thing, and it means the id can never be anything but a copy of the session id.
This change makes the host own the id. It is stored on the chat's session record, and a launcher can reserve it up front. When nobody reserves one — which is every chat today, new or old — the stored id is exactly the string everyone was deriving, so nothing a user has (read/unread state, notification ids, running workers) moves.
Nothing on screen changes. The host's tab list still publishes the old spelling and the desktop app still derives its local id; those are the next two changes. This is the durable half they build on.
What Changed
1.
AgentSessionRecord.surfaceTabId(optional). The id must be a host tab id — colon-free (a colon can never prefix a pane key), not a web-surface id (aweb-terminal-…id would decode as another tab), and at most 512 characters — the same ruleagent.launchalready applies topaneKey. The rule is enforced at the create wire, in reservation admission, and by the record validator; a persisted record that breaks it is quarantined like any other invalid row.2. Backfill for records written before the field. At
AgentSessionRecordStore.open, every record without the field getsstructured-agent-session-<sessionId>, the string clients derived. It is filled in memory at once, so every reader of the record sees one, and reaches disk with the store's first transaction rather than a write at open: a rewrite at open would read as an external change to any other holder of the file mid-restart, and would persist leases this instance had not yet adjudicated. A later open finds nothing to fill and writes nothing. When another holder rewrites the file, the reload refills memory the same way and forces no save.3. A create pins it. The reservation request carries
surfaceTabId; a new record stores it; a reservation against an existing record keeps the record's own. A second record under a held id is refused withagent_session_conflict. On the create path (null fence), the attach layer fills it from the caller's reservation, or with the derivedstructured-agent-session-<sessionId>when nothing was reserved.4.
agentSession.createaccepts an optionaltabIdon the create-intent payload. It is covered by the declared payload fingerprint, on both the client builder and the host recompute, so a payload whose declared digest omits thetabIdit carries is refused as malformed. Replay, though, keys on the host's attach fingerprint, which the tab id is not part of: a retry that names a different tab replays the original create and is answered with the id the record holds — the host owns the id. The attach result gainstabIdso the caller learns what the host recorded.5.
agent.launchreserves it frompaneKey. The structured route hands the tab half of the reserved pane to the structured create, so one reservation serves either route the host settles on. The structured outcome gainstabId, and the stored launch-result validator checks it when a recorded launch is read back.6. Capability
agentSession.create.tab-id.v1. The create-intent schema is a strict object, so an older host refuses a payload carryingtabIdrather than ignoring it. A client sends the field only to a host advertising this.Two extractions to stay under the line cap, no behaviour change:
isAgentSessionLaunchArgsmoves toagent-session-launch-args.ts, and the create-intent fingerprint moves intostructured-agent-session-create.tsasstructuredAgentSessionCreateIntentFingerprint.Why
Why the host owns it. A tab and the conversation it shows are different things. Deriving one's id from the other forced every layer to agree on a spelling, gave the host's own spelling a colon that no pane key can carry, and left nothing durable to publish. A host-owned id on the session record is what the tab snapshot can publish and what every client can copy.
Why existing records get the legacy string, not a fresh id. Read/unread state is host-shared and keyed by
<tabId>:<leaf>. Worker rows in the orchestration store carry that prefix. The load-time key remapper skips any well-formed pane key, so a changed prefix would orphan all of it with no repair. Filling the old string makes the upgrade a no-op for every existing chat.Why an unreserved create records the derived string too. Every reader still keys by
structured-agent-session-<sessionId>: the desktop app's tab id, the host-shared read state, the status address, and the worker rows. An opaque id minted at create would orphan all of that for every chat created before those readers move to the recorded id — the exact breakage the backfill exists to prevent. So an unreserved create records the derived string, the same rule the backfill applies; only a creator that reserves a tab gets a different id, and no client reserves one yet. The opaque host mint lands with the change that moves the last reader.Why not persist at open. The record store is opened by more than one instance across a restart, and each instance treats a file it did not write as an external change. See §2.
Why the tab id is in the declared digest but not in replay. The declared fingerprint must span the payload, so a digest that omits a field the payload carries is refused rather than admitted as the blank create it looks like. But which tab shows a chat is not which conversation it attaches to: replay keys on the attach fingerprint, the tab id stays out of it, and a retry naming another tab is answered with the recorded id rather than refused. Only a second record under a held id conflicts.
Why a capability. Rule 1 of the wire doc says a new optional field is safe only while every reader treats it as optional; a strict schema does not. The capability lets the client know before sending.
Linked Issue
Part of the chat-tab identity series that precedes moving desktop launches onto
agent.launch. No separate issue.Visual Proof
A manual upgrade test on macOS against an isolated dev profile. Phase A built
origin/main(1985c1b), created a Claude chat, and read it. Phase B relaunched the same profile on the PR build (f7af79a; the only later change is a one-line test comment). Nothing on screen differs between the builds — that is the point. Every check passed:surfaceTabId: structured-agent-session-<sid>.structured-agent-session-<its sid>as both its tab id and its stored id.Before (main build):
Chat created and answered
Chat read
After (PR build, same profile):
Same chat restored after the upgrade
Second message in the old chat
New chat
Both chats after another restart
Testing
pnpm tcclean,oxlintclean on every changed file,check:code-quality:changed0 new findings, the cross-version agent-session wire suite 14/14 run alone, lockfile identical toorigin/main.agent-session-record-store-surface-tab-id.test.ts): a reservation's id is persisted; a second record under it is refused; an id that could not prefix a pane key is refused; a record saved without the field loads with the legacy id in memory, is not written at open, reaches disk on the first transaction, and a later open writes nothing; after another holder rewrites the file the id is refilled in memory without forcing a save; a persisted colon-bearing id is quarantined.structured-agent-session-acquisition-options.test.ts): a create with a reserved id pins it on the record and answers with it; a create without one records the derived id and answers with it; a retry naming another tab is answered with the recorded one.agentSession.create(structured-agent-session.test.ts): a reservedtabIdreaches the attach params assurfaceTabId; a payload whose declared fingerprint omits thetabIdit carries is refused as an operation conflict; a colon-bearing or web-surfacetabIdis refused at the wire.agent.launch(agent-launch-session-reservation.test.ts): the tab half ofpaneKeyreaches the structured create; no tab when no pane; the outcome reports the host'stabId; notabIdfrom a host older than the field.structured-agent-session-create.test.ts):tabIdrides the params and the fingerprint; the pre-existing pinned literal for a blank create is unchanged; the capability is advertised.agent-launch-terminal-identity.test.ts): a recorded structured launch'stabIdis checked when present, and a row written before the field still reads.Ablation, run at the final head. Each production change was deleted one at a time, the named suites re-run, then restored from the commit:
tabIdtabIdin host intent fingerprinttabIdtabIdin client fingerprinttabIdtabIdNotes
Wire compatibility.
agentSession.creategains an optionaltabId(strict schema, hence the capability) and its result gains an optionaltabId;agent.launch's structured outcome gains an optionaltabId. No stream opcode, no published content change. Old client → new host: unchanged. New client → old host: the client must not sendtabIdwithout the capability; the result simply lacks the field.Sequencing for the next changes. No client should reserve a tab until the status address and the tab snapshot copy the recorded id — a reserved id would disagree with the keys those readers still derive. And because an unreserved chat's recorded id equals the derived string, tests for the reader moves must use a reserved, non-derived id; against a derived one, a reader that still derives would pass.
Known, accepted. The CLI's
agent.launchstructuredhandlestill returns the derived spelling; it becomes the recorded tab id when the snapshot publishes it. The host status address and worker key prefix still derive; they move together with the snapshot in the next change, because their readers correlate the two.Cross-platform and SSH. No platform-specific code; the record store is host-local on every host kind.