Skip to content

fix(runtime): skip unchanged worktrees when publishing mobile session snapshots - #12207

Merged
brennanb2025 merged 4 commits into
mainfrom
neil/oom-remote-session-partition
Aug 3, 2026
Merged

brennanb2025 merged 4 commits into
mainfrom
neil/oom-remote-session-partition

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Aug 3, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes a renderer OOM on always-on runtime hosts with paired clients.

Defect

buildMobileSessionTabSnapshots rebuilt per-worktree content for every worktree on every publication, and consulted its per-worktree cache only after the content was built:

const content = { ...three Maps + group projection + full tab array... }
const cached = mobileSessionSnapshotCacheByWorktree.get(worktreeId)
if (cached && jsonContentEquals(cached.content, content)) { ... }   // too late

The cache suppressed fanout and one allocation. It saved none of the work. Publication is triggered by a sync key including agentStatusByPaneKey, so this ran on every agent-status tick.

An agent tick legitimately changes exactly one worktree's snapshot. Pre-fix the renderer rebuilt all 222 to discover that — 221 of 222 rebuilds were redundant.

Fix

Two commits, reviewable independently.

68a7017c36 — refactor: make inputs explicit. Introduces MobileSessionWorktreeInputs (24 fields) built once per worktree and threaded through the seven per-worktree builders, replacing wholesale AppState. Pure refactor, no behavior change. This is the enabling step: with AppState out of those signatures the compiler proves the input set is complete, which is what makes the skip safe.

9180807746 — fix: skip unchanged worktrees. Reference-compares those explicit inputs and skips before building any intermediates. jsonContentEquals retained as a backstop on the non-skipped path.

Measured — buildMobileSessionTabSnapshots in isolation, N=222, 897 tabs, 54 live agent statuses

Median of 3 runs, before 922268af10 vs after 9180807746:

metric before after delta
republish, nothing changed 11.99 / 12.42 / 15.30 ms 1.31 / 1.75 / 2.02 ms ~7x faster
worktrees rebuilt on one agent tick 220 of 220 1 of 220 221 -> 1
allocation per republish 1.96 / 1.97 MB 0.54 / 0.55 MB 3.6x less
snapshots actually changed 1 of 220 1 of 220 unchanged
cold build 26.9 / 29.4 / 29.9 ms 29.5 / 31.9 / 43.0 ms slightly worse

Scope of these numbers. The benchmark calls buildMobileSessionTabSnapshots directly. It does NOT run syncRuntimeGraph, so the 787-tab flatten, the whole-graph rebuild, and the structured clone over IPC are absent from both columns. These figures are publication-content-build cost, not end-to-end publication cost.

Output is preserved: exactly 1 of 220 snapshots differs before and after. The fix removes work, not results.

At a realistic 20-30 pub/s this path drops from 24-36% of one core to 3.5-5.3%. At the 16 ms coalescing ceiling (~62.5 pub/s) gross allocation drops from ~7.2 GB/min to ~2.0 GB/min.

Field impact

Always-on Windows runtime host, 4 paired clients. Four renderer OOMs in two days across v1.4.163 and v1.4.164-rc.3. Renderer store at the OOM: tabsByWorktree 222, unifiedTabsByWorktree 224, terminalLayoutsByTabId 787, agentStatusByPaneKey 54.

Pre-crash usedHeapMB oscillated 3795 -> 3858 against a 4,192 MB limit — 91-92% occupancy for the final 8 minutes. That is allocation outrunning GC, not retention: ~95% of the churn is reclaimed, leaving a slow net climb that parks the heap near its ceiling, where near-continuous mark-compact on V8's GC threads converts allocation pressure into >100% of one core. The reported lag is those GC pauses.

What this does NOT claim

  • The heap-occupancy improvement is inferred, not measured. A node harness has a different heap limit and no comparable retained set, so any occupancy figure from it would be an artifact. Confirming it requires running the fixed build under a real workload and sampling usedHeapMB / heapLimitMB from the renderer_memory breadcrumb.
  • Not the full 106% CPU. pr_refresh_queue (~100 coalesced events/min, main-process) is an independent contributor this does not touch.
  • End-to-end improvement is ~1.8x, not 7x. The 7x is the content build in isolation. Measured end-to-end through the real syncRuntimeGraph with a structuredClone-backed IPC mock, same scale, 3 runs: 21.3 ms -> 12.0 ms. The split after this PR is ~2 ms content build and ~4-7.5 ms structured clone of a 374-906 KB payload (see below) that is byte-identical before and after — this PR reuses cached snapshot objects but does not shrink what gets published. So the payload, not the build, is now the bottleneck; there is almost no headroom left inside this function. At 20-30 pub/s the path goes from 43-64% of one core to 24-36%.
  • The remaining cost is the payload clone, on timing rather than allocation-rate grounds. Two independent harnesses measured the graph payload at 374 KB and 906 KB; the gap is snapshot content density (the larger models agentStatus with a 20-entry stateHistory and a lastAssistantMessage the code notes can reach ~8 KB), and the larger is the more realistic. At the coalescer ceiling of 62.5 pub/s that is ~23-57 MB/s, i.e. ~1.4-3.4 GB/min — smaller than the ~7 GB/min this PR removes from the build side, so the payload is not the larger allocation contributor. The case for the follow-up rests on the end-to-end timing instead: after this PR the clone is 4.1 ms of a ~12 ms publication, and Electron pays it on both serialize and deserialize. A follow-up PR (perf(runtime): withhold unchanged mobile snapshots from the graph payload #12245) withholds unchanged snapshots, cutting an unchanged republish from 374 KB / 5.08 ms to 3.4 KB / 0.02 ms. It depends on this one — the partition is an object-identity check that only works once unchanged worktrees return reference-identical snapshots, and merging it first would silently degrade to "everything always changed". Note a graph-level equality check would NOT help: the sync-key gate at App.tsx:1213-1241 already suppresses no-op publications, and on an agent tick the graph genuinely differs by 1 of 220.
  • Cold build regresses slightly (~29 -> ~32 ms, once per module lifetime) from building the explicit input keys.

Known fallback

A worktree with a mounted TerminalPane always rebuilds: buildMobileTerminalSurfaceTabs reads live PaneManager/DOM state that no store reference can witness. canReuseMobileSessionSnapshot refuses to skip when either the previous or current publication saw a registered tab for that worktree (the previous half covers unmount). Only a handful are mounted at real scale. The benchmark fixture registers none, so the measured post-fix figure is mildly optimistic.

Correctness notes for review

  • agentStatusByPaneKey is read inside the build loop (buildMobileTerminalSurfaceTabs, via a local paneKey), so it is a genuine per-worktree input and is bucketed through a tabId -> worktreeId index. A grep for the bare identifier misses this site. Skipping on it would have pinned stale agent statuses on paired clients silently.
  • Absent slices previously resolved to a fresh [] per worktree, which would have defeated reference equality and produced a ~0% skip rate. Now shared EMPTY_WORKTREE_* constants.
  • Two invariants relied on and commented in code, flagged for reviewer judgement: browser workspaces stored under browserTabsByWorktree[K] have worktreeId === K; and an agentStatusByPaneKey key rejected by parsePaneKey can never be looked up, since every lookup key is makePaneKey output.

Tests

sync-runtime-graph-publication-cost.test.ts counts per-worktree work via a slice read once per worktree; .fails markers removed. Note that metric is satisfied by the refactor alone, so the fix commit adds tests counting tab.title reads, which observe content builds directly: at 300 worktrees, unchanged republish 1200 -> 0 build units, one worktree changed 1200 -> 4. Both verified failing without the skip.

Validation

  • runtime directory: 57 files / 558 tests PASS
  • 8 out-of-directory importers of this module: 775 tests PASS
  • typecheck:web, typecheck:node, oxlint PASS

Note: the pnpm test wrapper cannot run in this environment (windows-native-registry node-gyp rebuild needs Visual Studio); pnpm exec vitest run --config config/vitest.config.ts is the repo-correct direct invocation.

Final merge-readiness review — 2026-08-03

Reviewed exact head 27d470c2ac645cbcd4cf75c087ce6b3dc771a49d. The final independent review returned CLEAN. GitHub reports a clean merge state and 42 completed checks with zero failures, including Windows packaging.

Review fix

27d470c2 corrected the publication-cost regression so it mutates one real agentStatusByPaneKey entry and proves exactly one of 300 worktree snapshots changes identity. The earlier test only changed the top-level map identity and therefore did not exercise the claimed behavior. The temporary incident document was also removed from the PR.

Statistical benchmark

Identical SHA-256-verified uncommitted harness at baseline 3658165119, this PR 27d470c2ac, and the combined stack through #12245 at 5081a12ac2. Each target used three independently started, rotated rounds with 50 warmups and 150 measured samples per round: 450 measured samples per target per metric. Values are median / p95 [bootstrap 95% CI for median].

Metric Baseline #12207 Combined with #12245
Direct snapshot build 1.382 / 2.053 ms [1.341, 1.421] 0.135 / 0.189 ms [0.1348, 0.1360] 0.138 / 0.218 ms [0.1373, 0.1399]
Scheduled publication, excluding the deliberate 16 ms coalescing delay 2.913 / 3.929 ms [2.860, 2.967] 1.581 / 1.851 ms [1.575, 1.588] 0.277 / 0.379 ms [0.2758, 0.2792]
structuredClone 1.369 / 1.873 ms [1.363, 1.381] 1.329 / 1.436 ms [1.327, 1.332] 0.0466 / 0.0529 ms [0.0465, 0.0468]
Payload bytes 933,388 933,386 49,631

This PR reduces median direct-build time 90.2% versus baseline. The combined stack reduces median scheduled-publication time 90.5% and payload size 94.7% versus baseline; compared with this PR alone, #12245 reduces scheduled time 82.5%, clone time 96.5%, and payload 94.7%. Its 0.003 ms direct-build bookkeeping overhead is dwarfed by the transport reduction.

Every measured iteration changed exactly one status. Baseline and this PR published all 222 snapshots; the combined stack published the changed worktree and withheld the other 221. Payload content preserved the changed status, and there were zero measured publication failures.

Raw local artifacts remain uncommitted in the dedicated benchmark worktree under .benchmarks/mobile-session-publication/ (report.md, summary.json, execution.json, and raw/*.json). Absolute wall times should be treated cautiously because an unrelated two-day-old Node/Vite repro remained at approximately one logical CPU throughout; rotated commit order, independent processes, warmups, and confidence intervals reduce but cannot eliminate that host-load noise. The relative effects are large and consistent.

Validation gaps and merge order

OrcaWin added 3 commits August 2, 2026 21:58
buildMobileSessionTabSnapshots consults its per-worktree cache after building
the content, so a republish saves the fanout but none of the work. With 300
worktrees, an unchanged republish still does 601 units of per-worktree work,
and a single changed worktree does 602.

Publication is keyed on agentStatusByPaneKey/agentStatusEpoch, so this runs on
every agent status tick. On a multi-client runtime host with 381 worktrees this
allocated ~350 MB/min and rode the renderer into repeated 4 GB OOMs.

Tests are marked it.fails so the branch stays green; drop .fails when the build
loop skips worktrees whose inputs are unchanged.
…orktree

Every per-worktree builder in buildMobileSessionTabSnapshots took the whole
AppState, so a worktree's real input set was the transitive closure of seven
helpers and could not be memoized safely. Introduce MobileSessionWorktreeInputs
— built once per worktree — and thread it through the group projection and the
terminal/markdown/file/browser tab builders so the compiler proves the input
set. Tab- and pane-keyed slices are narrowed to this worktree's tab ids, file
ids, browser workspace/page ids, and pane keys; agent statuses are bucketed per
worktree once per publication via a tab-id index.

No behavior change. Dropping AppState from the projection path also removes the
second per-worktree read of browserTabsByWorktree, so the publication-cost
counter falls from 601 to 1 per publication and its two cases now pass.
… content

buildMobileSessionTabSnapshots consulted its per-worktree cache only after
building that worktree's three Maps, group projection, and full tab array, so
the cache suppressed the fanout but none of the computation. Every agent-status
tick therefore rebuilt every worktree, which drove sustained 4 GB renderer
working sets on a host holding 381 worktrees.

Cache MobileSessionWorktreeInputs alongside each snapshot and reuse the snapshot
when every input field is reference-equal, before any intermediate structure is
allocated. Worktrees with a mounted TerminalPane always rebuild: their live
DOM/PaneManager state is invisible to store references. Absent per-worktree
slices now resolve to shared empty values so an empty worktree can compare equal
to its last publication. jsonContentEquals stays as the backstop on the rebuild
path for inputs that churn by reference without changing output.

With 300 worktrees, per-worktree content builds go from 300 to 0 on an unchanged
republish and from 300 to 1 when one worktree changes.
@OrcaWin OrcaWin changed the title test(runtime): prove mobile session publication rebuilds every worktree (renderer OOM on multi-client hosts) fix(runtime): skip unchanged worktrees when publishing mobile session snapshots Aug 3, 2026
@brennanb2025
brennanb2025 marked this pull request as ready for review August 3, 2026 18:41
@coderabbitai

coderabbitai Bot commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Mobile session snapshot generation now prepares scoped per-worktree inputs instead of passing global AppState through builders. The runtime caches themes, narrowed maps, worktree inputs, snapshot content, and stable versions. Terminal, editor, markdown, file, browser, and group builders consume scoped inputs. Snapshot publication reuses unchanged worktrees and rebuilds changed worktrees. Tests verify read and rebuild counts across large worktree sets.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the defect, fix, tests, benchmarks, risks, and validation, but omits several required template sections and information. Add the required Screenshots, AI Review Report, Security Audit, and Notes sections, and complete the Testing checklist with the required platform-review confirmation.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly states that unchanged worktrees are skipped during mobile session snapshot publication, matching the primary change.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
📝 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.

@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 (1)
src/renderer/src/runtime/sync-runtime-graph.ts (1)

997-1038: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Make the exhaustiveness claim compiler-enforced, or correct the docstring.

The && chain covers all 24 fields of MobileSessionWorktreeInputs today, so there is no current defect. But the docstring states that a missed input is a compile error. Nothing enforces that. A field added to MobileSessionWorktreeInputs later compiles cleanly here and publishes a stale snapshot to paired clients.

Key the comparison by field so the type system rejects an omission.

♻️ Proposed refactor for compiler-enforced field coverage
 function canReuseMobileSessionSnapshot(
   previous: MobileSessionWorktreeInputs,
   next: MobileSessionWorktreeInputs
 ): boolean {
-  return (
-    // Why: live DOM/PaneManager state is invisible to store references, so a mounted surface always rebuilds.
-    !previous.hasMountedTerminalSurface &&
-    !next.hasMountedTerminalSurface &&
-    previous.worktreeId === next.worktreeId &&
-    previous.terminalTabs === next.terminalTabs &&
-    previous.browserWorkspaces === next.browserWorkspaces &&
-    previous.unifiedTabs === next.unifiedTabs &&
-    previous.groups === next.groups &&
-    previous.tabBarOrder === next.tabBarOrder &&
-    previous.activeGroupId === next.activeGroupId &&
-    previous.tabGroupLayout === next.tabGroupLayout &&
-    previous.openFilesById === next.openFilesById &&
-    previous.openFileIds === next.openFileIds &&
-    previous.activeEditorFileId === next.activeEditorFileId &&
-    previous.activeEditorTabType === next.activeEditorTabType &&
-    previous.activeTerminalTabId === next.activeTerminalTabId &&
-    previous.activeBrowserWorkspaceId === next.activeBrowserWorkspaceId &&
-    previous.generatedTitlesEnabled === next.generatedTitlesEnabled &&
-    previous.terminalTheme === next.terminalTheme &&
-    narrowedEntriesEqual(previous.terminalLayoutByTabId, next.terminalLayoutByTabId) &&
-    narrowedEntriesEqual(previous.paneTitlesByTabId, next.paneTitlesByTabId) &&
-    narrowedEntriesEqual(previous.launchDraftByTabId, next.launchDraftByTabId) &&
-    narrowedEntriesEqual(previous.agentStatusByPaneKey, next.agentStatusByPaneKey) &&
-    narrowedEntriesEqual(previous.editorDraftVersionByFileId, next.editorDraftVersionByFileId) &&
-    narrowedEntriesEqual(previous.pagesByBrowserWorkspaceId, next.pagesByBrowserWorkspaceId) &&
-    narrowedEntriesEqual(
-      previous.certificateFailureByBrowserPageId,
-      next.certificateFailureByBrowserPageId
-    )
-  )
+  // A missing key here is a compile error, so a new input cannot silently reuse a stale snapshot.
+  const equalByField: Record<keyof MobileSessionWorktreeInputs, boolean> = {
+    // Why: live DOM/PaneManager state is invisible to store references, so a mounted surface always rebuilds.
+    hasMountedTerminalSurface: !previous.hasMountedTerminalSurface && !next.hasMountedTerminalSurface,
+    worktreeId: previous.worktreeId === next.worktreeId,
+    terminalTabs: previous.terminalTabs === next.terminalTabs,
+    browserWorkspaces: previous.browserWorkspaces === next.browserWorkspaces,
+    unifiedTabs: previous.unifiedTabs === next.unifiedTabs,
+    groups: previous.groups === next.groups,
+    tabBarOrder: previous.tabBarOrder === next.tabBarOrder,
+    activeGroupId: previous.activeGroupId === next.activeGroupId,
+    tabGroupLayout: previous.tabGroupLayout === next.tabGroupLayout,
+    openFilesById: previous.openFilesById === next.openFilesById,
+    openFileIds: previous.openFileIds === next.openFileIds,
+    activeEditorFileId: previous.activeEditorFileId === next.activeEditorFileId,
+    activeEditorTabType: previous.activeEditorTabType === next.activeEditorTabType,
+    activeTerminalTabId: previous.activeTerminalTabId === next.activeTerminalTabId,
+    activeBrowserWorkspaceId: previous.activeBrowserWorkspaceId === next.activeBrowserWorkspaceId,
+    generatedTitlesEnabled: previous.generatedTitlesEnabled === next.generatedTitlesEnabled,
+    terminalTheme: previous.terminalTheme === next.terminalTheme,
+    terminalLayoutByTabId: narrowedEntriesEqual(
+      previous.terminalLayoutByTabId,
+      next.terminalLayoutByTabId
+    ),
+    paneTitlesByTabId: narrowedEntriesEqual(previous.paneTitlesByTabId, next.paneTitlesByTabId),
+    launchDraftByTabId: narrowedEntriesEqual(previous.launchDraftByTabId, next.launchDraftByTabId),
+    agentStatusByPaneKey: narrowedEntriesEqual(
+      previous.agentStatusByPaneKey,
+      next.agentStatusByPaneKey
+    ),
+    editorDraftVersionByFileId: narrowedEntriesEqual(
+      previous.editorDraftVersionByFileId,
+      next.editorDraftVersionByFileId
+    ),
+    pagesByBrowserWorkspaceId: narrowedEntriesEqual(
+      previous.pagesByBrowserWorkspaceId,
+      next.pagesByBrowserWorkspaceId
+    ),
+    certificateFailureByBrowserPageId: narrowedEntriesEqual(
+      previous.certificateFailureByBrowserPageId,
+      next.certificateFailureByBrowserPageId
+    )
+  }
+  return Object.values(equalByField).every(Boolean)
 }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4ce81134-24dd-407c-9532-cde591bd4906

📥 Commits

Reviewing files that changed from the base of the PR and between c9a37f5 and 27d470c.

📒 Files selected for processing (2)
  • src/renderer/src/runtime/sync-runtime-graph-publication-cost.test.ts
  • src/renderer/src/runtime/sync-runtime-graph.ts

Comment on lines +146 to +169
it('rebuilds only the worktrees whose inputs changed', () => {
const WORKTREES = 300
const { state, reads, resetReads } = makeCountingState(WORKTREES)

buildMobileSessionTabSnapshots(state)
resetReads()

// One worktree's tabs change — the other 299 are untouched.
const next = {
...state,
tabsByWorktree: {
...state.tabsByWorktree,
'repo::/wt-7': [
{ id: 'term-7', title: 'Agent 7 (done)', customTitle: null, type: 'terminal' }
]
},
get browserTabsByWorktree() {
return (state as unknown as { browserTabsByWorktree: unknown }).browserTabsByWorktree
}
} as unknown as AppState

buildMobileSessionTabSnapshots(next)

expect(reads()).toBeLessThan(WORKTREES / 10)

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

Measure tab-change rebuilds directly.

browserTabsByWorktree is read once before the worktree loop. Line 169 therefore passes even if a tab change rebuilds all 300 worktree snapshots.

Add a per-tab content-read counter and snapshot-reference assertions, as in the agent-status test. Verify that only repo::/wt-7 rebuilds after the tab change.

@brennanb2025
brennanb2025 merged commit 34291f0 into main Aug 3, 2026
125 of 127 checks passed
brennanb2025 added a commit that referenced this pull request Aug 4, 2026
#12383)

The per-worktree rebuild memo from #12207 refused to skip any worktree
with a registered TerminalPane, because builders read live PaneManager/DOM
state the memo could not witness. Hidden worktrees stay mounted (8 parked
+ 12 retained by default, unbounded with terminalHiddenViewParking off),
so that set rebuilt on every publication — on the always-on hosts the memo
targeted, ~20 worktrees paid the full content build plus the new inputs
build and deep compare every tick.

Capture the live reads instead: snapshot pane leaf ids, the live active
leaf, the serialized pane tree, and per-pane numeric/pty bindings once per
publication into MountedTerminalSurfaceCapture, compare captures by value
in the memo, and have the builders read only the capture. Live state
outside the capture is now unrepresentable in a builder, so the skip stays
provably complete — and a mounted worktree whose panes did not change
reuses its snapshot like any other.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
… snapshots (stablyai#12207)

* test(runtime): prove mobile session publication rebuilds every worktree

buildMobileSessionTabSnapshots consults its per-worktree cache after building
the content, so a republish saves the fanout but none of the work. With 300
worktrees, an unchanged republish still does 601 units of per-worktree work,
and a single changed worktree does 602.

Publication is keyed on agentStatusByPaneKey/agentStatusEpoch, so this runs on
every agent status tick. On a multi-client runtime host with 381 worktrees this
allocated ~350 MB/min and rode the renderer into repeated 4 GB OOMs.

Tests are marked it.fails so the branch stays green; drop .fails when the build
loop skips worktrees whose inputs are unchanged.

* refactor(runtime): make mobile session snapshot inputs explicit per worktree

Every per-worktree builder in buildMobileSessionTabSnapshots took the whole
AppState, so a worktree's real input set was the transitive closure of seven
helpers and could not be memoized safely. Introduce MobileSessionWorktreeInputs
— built once per worktree — and thread it through the group projection and the
terminal/markdown/file/browser tab builders so the compiler proves the input
set. Tab- and pane-keyed slices are narrowed to this worktree's tab ids, file
ids, browser workspace/page ids, and pane keys; agent statuses are bucketed per
worktree once per publication via a tab-id index.

No behavior change. Dropping AppState from the projection path also removes the
second per-worktree read of browserTabsByWorktree, so the publication-cost
counter falls from 601 to 1 per publication and its two cases now pass.

* fix(runtime): skip unchanged worktrees before building mobile session content

buildMobileSessionTabSnapshots consulted its per-worktree cache only after
building that worktree's three Maps, group projection, and full tab array, so
the cache suppressed the fanout but none of the computation. Every agent-status
tick therefore rebuilt every worktree, which drove sustained 4 GB renderer
working sets on a host holding 381 worktrees.

Cache MobileSessionWorktreeInputs alongside each snapshot and reuse the snapshot
when every input field is reference-equal, before any intermediate structure is
allocated. Worktrees with a mounted TerminalPane always rebuild: their live
DOM/PaneManager state is invisible to store references. Absent per-worktree
slices now resolve to shared empty values so an empty worktree can compare equal
to its last publication. jsonContentEquals stays as the backstop on the rebuild
path for inputs that churn by reference without changing output.

With 300 worktrees, per-worktree content builds go from 300 to 0 on an unchanged
republish and from 300 to 1 when one worktree changes.

* test(runtime): cover agent status publication cost

---------

Co-authored-by: Brennan Benson <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
stablyai#12383)

The per-worktree rebuild memo from stablyai#12207 refused to skip any worktree
with a registered TerminalPane, because builders read live PaneManager/DOM
state the memo could not witness. Hidden worktrees stay mounted (8 parked
+ 12 retained by default, unbounded with terminalHiddenViewParking off),
so that set rebuilt on every publication — on the always-on hosts the memo
targeted, ~20 worktrees paid the full content build plus the new inputs
build and deep compare every tick.

Capture the live reads instead: snapshot pane leaf ids, the live active
leaf, the serialized pane tree, and per-pane numeric/pty bindings once per
publication into MountedTerminalSurfaceCapture, compare captures by value
in the memo, and have the builders read only the capture. Live state
outside the capture is now unrepresentable in a builder, so the skip stays
provably complete — and a mounted worktree whose panes did not change
reuses its snapshot like any other.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants