Repository navigation
perf(renderer): keep remote snapshot batches linear - #13676
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughSession-tab snapshot reconciliation now supports shared state mutation across snapshot batches. Host session-tab mappings use environment and worktree indexes for targeted cleanup. Agent-pane indexes and cloned records are reused during batch updates. Single-snapshot behavior remains available through the public wrapper. Tests cover empty batches, mixed and duplicate-worktree snapshots, sequential equivalence, immutability, and per-worktree cleanup. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ 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.
🧹 Nitpick comments (1)
src/renderer/src/runtime/web-session-tabs-sync.ts (1)
1630-1650: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winBind
withWorktreeEntryto the record key type.
recordKeyis typed as the fullWebSessionTabsBatchRecordKeyunion whileTis inferred only fromvalue. The twoas Record<string, T>casts then erase the relation between the key and the record's element type. A mismatched pair, for example'tabBarOrderByWorktree'with aTabGroup[]value, compiles. In batch mode the helper mutates the shared working state, so such a mismatch would write a wrong value into renderer state instead of failing type checking.Make the helper generic over the key so the compiler enforces the pairing.
♻️ Proposed typing change
-function withWorktreeEntry<T>( - state: WebSessionTabsSyncState, - recordKey: WebSessionTabsBatchRecordKey, - key: string, - value: T | null, - equal: (a: T | undefined, b: T | null) => boolean, - batchContext?: WebSessionTabsBatchContext, - deleteNull = true -): Record<string, T> { - const record = (state[recordKey] ?? {}) as Record<string, T> +function withWorktreeEntry< + K extends WebSessionTabsBatchRecordKey, + T = NonNullable<WebSessionTabsSyncState[K]>[string] +>( + state: WebSessionTabsSyncState, + recordKey: K, + key: string, + value: T | null, + equal: (a: T | undefined, b: T | null) => boolean, + batchContext?: WebSessionTabsBatchContext, + deleteNull = true +): Record<string, T> { + const record = (state[recordKey] ?? {}) as Record<string, T>
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: d23096bf-48b1-4f0f-9025-06e29faea710
📒 Files selected for processing (2)
src/renderer/src/runtime/web-session-tabs-sync.test.tssrc/renderer/src/runtime/web-session-tabs-sync.ts
The sibling-mapping test used a worktree id that shares no prefix with WT, so it passed against the prefix-scan it was meant to pin. Use an id prefixed by WT's and drain the new mapping index in the leak counters. Co-authored-by: Orca <[email protected]>
* perf(renderer): keep remote snapshot batches linear * test(renderer): cover the prefix-colliding sibling worktree The sibling-mapping test used a worktree id that shares no prefix with WT, so it passed against the prefix-scan it was meant to pin. Use an id prefixed by WT's and drain the new mapping index in the leak counters. Co-authored-by: Orca <[email protected]> --------- Co-authored-by: Orca <[email protected]>
The one-sentence version
When a remote host sends updates for 1,200 workspaces at once, Orca used to photocopy the entire filing cabinet 1,200 times — once per workspace. Now it photocopies it once, writes all 1,200 updates into that copy, and files it. 52× faster at 1,200 workspaces.
Start here: what is actually happening
A remote Orca host tells your client about its workspaces through
session.tabssnapshots — one per workspace, describing that workspace's terminals, browser pages, editors, and agent panes.On reconnect or replay, the host does not send these one at a time. It sends a batch: every workspace at once.
The renderer stores these in maps keyed by workspace. Those maps are immutable — the standard React/Zustand rule that you never edit state in place, you make a modified copy. Reconciling one snapshot means copying the map, changing one entry, and swapping the copy in.
That rule is correct. Applying it once per workspace inside a batch is what was expensive.
flowchart TB subgraph BEFORE["Before — one full copy per workspace"] direction TB B1["Snapshot 1 arrives"] --> B2["Copy ALL maps (1,200 entries)"] --> B3["Edit entry 1"] --> B4["Swap in"] B4 --> B5["Snapshot 2 arrives"] --> B6["Copy ALL maps again"] --> B7["Edit entry 2"] --> B8["Swap in"] B8 --> B9["... ×1,200"] end subgraph AFTER["After — one copy for the whole batch"] direction TB A1["Batch of 1,200 arrives"] --> A2["Copy ALL maps ONCE (a draft)"] A2 --> A3["Edit entry 1 in the draft"] --> A4["Edit entry 2 in the draft"] --> A5["... edit entry 1,200"] A5 --> A6["Swap the finished draft in ONCE"] endThe cost of the old shape is quadratic: copying an N-entry map N times is N² work. That is why the numbers get dramatically worse as workspace count grows rather than just proportionally worse.
Measured
Synthetic reconnect fixture, one ready remote terminal and one working agent per workspace, prior sequential reducer vs. the batch path on the same machine:
Note the shape: workspaces triple, old cost grows ~9×, new cost grows ~2×. Quadratic became linear.
811 ms is a visibly frozen window. That is a single reconnect to one busy host.
The second change is related: looking up "which agent panes belong to this tab?" used to scan every agent pane in the app, once per workspace. Those are now indexed by owner, so an agent-heavy batch stops re-scanning globally.
Where this runs in production
session.tabs.listAllwhen you connect to a remote host.snapshotsstream event — i.e. every remote reconnect and replay, for every paired runtime environment.Reconnects are exactly when a user is already waiting.
The behavior change you should actually review
Everything above is a pure speedup. This part is not, and it deserves a decision.
updateHostSessionTabIdMappingsruns on every snapshot apply. It clears the local→host tab id mappings belonging to a worktree. Previously it did that by string prefix match:Worktree ids are built as
${repoId}::${absolutePath}(src/shared/pty-session-id-format.ts:15). On POSIX, absolute paths may legally contain a colon.So consider two sibling worktrees:
repo::/wenv:repo::/w:<tabId>repo::/w:2env:repo::/w:2:<tabId>Every key belonging to B also starts with the prefix computed for A. So whenever worktree A published a snapshot, it silently wiped worktree B's tab mappings.
What that looked like to a user: a wiped mapping makes tab close fall back to
toHostSessionTabId(terminalTabId). The comment already interminal-tab-actions.ts:136describes the symptom — close "silently fell back to a local-only prune and the host's next snapshot re-added the tab." In other words: you close a tab, and it comes back. Reordering and moving tabs hit the same fallback (web-runtime-session.ts:768).This PR replaces the prefix scan with an exact
(environmentId, worktreeId)index, so only the worktree that actually published gets cleared.This is a bug fix, not a regression — but it is a real behavior change and it should be merged as one, not waved through as "pure perf." Less reachable on Windows, where colons are not legal inside path components.
Compatibility
src/renderer/src/runtime/.hostSessionTabIdByLocalKeyis purely client-side bookkeeping.Correctness argument for the batch rewrite
The risk in a copy-on-write draft is a read seeing a value that a later write in the same batch was supposed to produce, or vice versa. This was checked explicitly:
writableWebSessionTabsRecord(state, k, undefined)returns{...(state[k] ?? {})}— identical to the inline spreads it replaces, so the single-snapshot path is provably unchanged.agentPaneKeysByTabIdindex is built before the first mutation ofagentStatusByPaneKey, and is kept in sync on every add and delete.One invariant is load-bearing and worth naming:
writableWebSessionTabsRecordmutates itsstateargument when a batch context is present. That is safe only becauseapplyWebSessionTabsSnapshotshands it a shallow copy{ ...state }and every read precedes its write. If someone later passes the real store state, this breaks quietly. A guard test for that invariant would be a reasonable follow-up.activeGroupIdByWorktreenow routes through a value-equality gate, so a patch that changed identity but not value is no longer emitted. Content is the same; one redundant notification disappears.Testing
pnpm lintpnpm typecheckORCA_CROSS_VERSION_BASELINE_REF=v1.4.177 pnpm test— 4,603 files passed, 15 skipped; 49,334 tests passed, 97 skippedpnpm buildThe regression test compares the final batch result against repeated immutable single-snapshot reconciliation across terminal, agent-status, browser, editor, removal/replacement, and provisional-handoff cases — i.e. it asserts the fast path and the slow path agree, rather than asserting the fast path's own output. Also covered: input immutability, empty-batch identity, and selective same-environment mapping teardown.
The baseline ref is pinned because an unrelated repository tag named
v799currently outranks the intended release tag during automatic baseline selection.The temporary benchmark harness used for the table above was removed from the diff.