Skip to content

perf(terminal): release hidden parked workspaces' terminals and layouts so memory stays flat - #45956

Merged
brennanb2025 merged 45 commits into
mainfrom
brennanb2025/workspace-surface-release
Nov 24, 2026
Merged

brennanb2025 merged 45 commits into
mainfrom
brennanb2025/workspace-surface-release

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Every workspace you opened stayed fully loaded in the background for the rest of the session, even when you couldn't see it. So the more workspaces you visited, the more memory Orca used. Now a hidden workspace whose terminals are already asleep also puts away its tab bars and layout, and rebuilds them when you come back. Your running commands keep running, and the terminal output, unsent drafts and tab positions are all there when you return.

Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​256 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​256
Prod 39 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​864 $\color{#cf222e}{\Huge{\mathbf{−}}}$​129 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​735

What Changed

Before: each visited workspace kept its terminal views (an xterm each, with ~270 listeners) and its whole tab-group layout mounted for the session. Terminal parking existed but never applied to restored terminals, so it didn't help.

After: a hidden workspace that has been ordinarily parked releases its terminal views and its tab-group layout. On return (or hover prewarm) the layout remounts from store state and terminals restore from their parking snapshot. PTYs are never touched.

Mechanism:

  1. Restored terminals can park. The restore flag pendingActivationSpawn is kept as sort metadata after a reattach, and parking read it as "spawn still pending". A tab now counts as settled once every pane has a live PTY (isTerminalActivationSpawnSettled). Manual and automatic parking share the rule. Terminals shown as chat keep their previous behavior.
  2. A stale capability answer no longer blocks parking. The startup capability ask runs before restored sessions revive, so it answers "no" and that answer was cached. When a pane binds the revived session, Orca now asks again for just those ids, one request at a time with bounded retries. If the answer still doesn't come, the id settles back to its earlier "no" (no new timer).
  3. Idle warm-up no longer mounts tabs that can never park. These are restored tabs with no PTY and nothing queued to start. They now mount when shown, as Activating a worktree respawns the agent command in every dead tab, without a limit; hitting the container PID limit then kills the terminal daemon with no log #39166 intended.
  4. Parked layouts are released. WorktreeSplitSurface unmounts TabGroupSplitLayout and the session drop target only when the workspace is hidden and ordinarily parked, has no browser pages or simulator tabs, and every group's active tab is a terminal, structured chat or room (all drawn outside the layout). An active editor or an empty group's landing picker keeps the layout mounted. Terminal and chat overlays stay mounted, so watchers, bells, titles, exits and chat state are unchanged.
  5. An open quick-command editor keeps its layout. Its unsaved text lives in the tab strip, so the workspace isn't released while the dialog is open.
  6. Returning restores the tab strip. Per-group state that outlived the mounted strip on main now lives in one per-tab-group store, cleared when its group or workspace is removed: the tab-strip scroll offset, the shell-capability answer a returning strip reuses (only on the same host; a different host takes the normal cache expiry), and the hosts agent detection already checked (so a remount doesn't force another host scan).
  7. Hidden overlays match main once warm-up is done. When the only deferred tabs left are restored tabs with no PTY, warm-up counts as finished, so a hidden workspace keeps its simulator and browser overlays mounted as it does on main.

Why

Per-workspace renderer state should not grow with how many workspaces you visited in a session. Releasing what is off screen and rebuilding it from store state keeps memory bounded. The alternative was a fixed number of recent workspaces mounted. That still pays for terminals and layouts nobody is looking at, and it duplicates the parking policy that already decides which hidden terminals can sleep safely. This PR reuses that policy, so only workspaces that parking already considers safe are released.

Linked Issue

Internal (app memory: flat renderer as workspaces are visited).

Visual Proof

N/A. Nothing on screen changes; a returning workspace looks the same. Proof is the memory and restore benchmark below.

Testing

Benchmark on the fleet profile on Linux (1,800 worktrees + 100 folders, 1,800 chats, 200 terminals). It visits 150 workspaces one at a time with 2 streamed chat turns each, then runs return probes. Measured after GC. Main is the base 2284cb2; the head build's source tree is identical to the PR head.

At 150 visited workspaces main this PR
Mounted xterms (10 → 150 visits) 1 → 30 0 → 0
Mounted workspace layouts (10 → 150) 11 → 150 6 → 5
DOM listeners (10 → 150) 1,884 → 17,578 1,569 → 7,995
Renderer JS heap (10 → 150) 150 → 871 MB 147 → 758 MB
Renderer PSS (10 → 150) 671 → 3,165 MB 629 → 2,913 MB
Switch back to an early workspace, median of 10 1,004 ms 205 ms (131–211 ms across 6 runs of this branch)

What still grows here is chat views: on this branch every visited chat stays mounted (150 at the end). The separate chat-view cap (#45916) bounds those. The two together are what make the renderer flat.

Restore checks on a released workspace:

  • A shell loop printing every 10 s kept running while released. On return all 213 lines were present and the terminal was ready in 590 ms.
  • An unsent chat draft was kept.

Unit tests: settled-activation-spawn.test.ts (restored splits park only when every pane is live), terminal-provider-snapshot-capability.test.ts (a revived session becomes parkable), tab-group-scoped-state.test.ts (per-group state is disposed with its group or workspace), windows-terminal-capabilities.test.ts (a released strip's host answer survives cache expiry and the owner cap) and released-layout-eligibility.test.ts (an open quick-command dialog keeps its unsaved text). Platforms: Linux end to end. macOS, Windows and SSH/paired hosts by code review of the platform-specific paths: Windows shell capabilities, remote parking capture, paired-runtime gates.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below
  • Every added test fails without this change and avoids the test anti-patterns

Performance

Reduces work: hidden parked workspaces drop their xterms, layout subscriptions and listeners.

  • Release check: recomputed only when that workspace's tab membership or groups change. Title updates don't trigger it.
  • Revived capability re-ask: event-driven, in batches of 512, with at most 8 rounds per cohort. It adds no steady-idle timer.
  • Per-group state (strip offsets, held capability answers, observed agent hosts): bounded by open groups and cleared on removal. Its one store subscription visits only the workspaces a groups write addressed.
  • Shell-capability probes: a strip returning on the same host adds none.

A fresh perf scan on the head is in the comments.

Risk

Level: Medium. The riskiest part is restoring a released workspace. If a view that lives inside the layout were wrongly released, a user would see it rebuilt on return and lose its in-view state (for example an editor's scroll). The allowlist keeps editors, browsers, simulators and empty groups mounted. Back out with a plain revert; no saved data or protocol changes.

Visible behavior changes, intended:

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

Cross-platform: renderer-only; Windows shell-capability probing keeps its existing owners. Remote/SSH: remote parking keeps its capture and paired-runtime gates. Mobile: unaffected. Folder workspaces: same path as worktrees.

@brennanb2025 brennanb2025 changed the title perf(terminal): release parked hidden workspace layouts perf(terminal): park hidden workspaces' terminals and release their layouts so memory stays flat Nov 21, 2026
@brennanb2025
brennanb2025 force-pushed the brennanb2025/workspace-surface-release branch from a3ec07d to 5913a8c Compare November 23, 2026 10:38
…ies, index settled and release checks, keep strip scroll through hidden prewarm
…-ask and keep tab-strip offsets until their group closes
… offsets of closed groups, cap capability reuse at the re-probe ceiling
… shared capability answer, as a retained strip did
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan (fresh perf reviewer) on a3ef93a

Performance scan complete; no introduced P0/P1 findings.

Findings

None. Static verdict: clean. The change releases eligible hidden layouts without adding recurring idle polling or fleet-wide expensive derivation on status updates.

Compared 2284cb2d04f0de86c695f1f5aa584d5c48ee1f18 with verified head a3ef93a14554d0617067bdd14ccb6e0d26c7e83a. Read all 24 changed runtime files, both added tests, relevant unchanged consumers, and the requested perf-scan/perf skills. No files were edited; no builds, typechecks, tests, or runtime benchmarks were run. Counts below are source-derived, not timing or heap measurements.

Coverage: trigger, population, bound

Notation: W = workspaces; M = mounted workspace shells; Tᵥ/Gᵥ/Pᵥ = tabs/groups/panes in one workspace; R = revived PTYs awaiting an answer; S = accepted app-store writes/second. Examined W = 1,900 and 10× = 19,000. Actual S was not measured; examples use S = 2, consistent with the supplied hook workload exceeding 1/s.

Changed work Trigger and owner Population, work and bound
Layout release: TerminalWorktreeSplitSurface.tsx, released-layout-eligibility.ts, WorkspacePaneOverlayLayers.tsx Renderer render; memo invalidates on release gate, local tab count or local groups Selector performs two keyed lookups, without walking tabs. Eligibility builds one local tab index and checks groups: O(Tᵥ + Gᵥ). It runs after the hidden/ordinary-park/no-browser gates. Visible, measuring, force-parked, simulator and active editor/landing layouts retain their existing surface. Structured chat remains mounted outside the released layout.
Scroll retention: TabBar.tsx, tab-strip-scroll-memory.ts Strip mount, scroll, resize while awaiting restoration, and unmount One added passive scroll listener per strip with a key; callback reads one scrollLeft. Cleanup checks only that workspace’s groups: O(Gᵥ). At most one temporary ResizeObserver per pending restoration; it disconnects when restoration completes or the strip unmounts. Saved records are capped at 8,192, unchanged at 10× fleet.
Returning-strip capability behavior: use-tab-bar-runtime-model.ts, windows-terminal-capabilities.ts Enabled capability-hook mount or owner change Returning strips reuse an existing owner answer without a TTL probe. New strips retain base’s 30-second TTL load. Cache misses still load, with pending-request sharing by owner; owner cache remains capped at 32. No work is tied to workspace-status frequency.
Settled activation: settled-activation-spawn.ts, terminal-hidden-view-parking.ts, manual eligibility/lifecycle, cold-parking lifecycle, parking-pass candidates Manual park or an addressed parking reconsideration Only tabs still carrying pending activation metadata need the added check. It builds a set of that tab’s live PTYs and checks its saved leaf bindings: O(Ptab). Worktree candidate collection can call eligibility twice for one dirty workspace. No global workspace lookup is added per tab. Chat leaves and incomplete spawn bindings remain ineligible.
Newly reachable ordinary parking Eligible restored terminal becomes hidden and passes existing retention/coverage gates Existing capture, watcher registration and pane teardown operate on the affected tabs/panes. Local ordinary parking skips scrollback capture. Remote captures preserve output, run per parking episode, and retain the existing 512-KiB-per-leaf session limit. Capture serialization still initially visits configured scrollback; the byte cap is not a CPU cap. This is required recovery work before releasing that owner.
Bind notification: ipc-pty-connect.ts, pty-transport.ts Spawn result or attachment binds a PTY Constant map/set operations. Spawn can reach the notification twice, but the first removal of cached false makes the second re-ask admission a no-op. Existing gone-session marking is preserved.
Revived capability re-ask: terminal-provider-snapshot-revived-reask.ts, terminal-provider-snapshot-capability.ts Binding an inventory PTY whose cached answer is false One renderer-wide coordinator, deduplicated IDs, batches of 512, sequential awaited batches. For a fixed cohort, at most 8 rounds, with delays 0/1/2/4/8/16/30/30 seconds. At R = 1,900: ≤32 batch requests; at R = 19,000: ≤304. Successful answers remove retry debt; unresolved IDs settle back to false. New bindings can extend a cohort, so this is a fixed-cohort bound, not a process-lifetime request cap.
Capability bookkeeping Inventory membership change, answer, or reset The added live-ID set is O(live PTYs), replaced on synchronization and cleared on reset. Answer recording visits returned IDs and existing unknown-retry entries. Publications carry changed PTY IDs. No new store subscription is introduced here.
Deferred admission: use-activation-deferred-tab-admission.ts, unbound-restored-terminal-tab.ts Existing idle admission after activation/revision change Maps and filters only the active workspace’s tabs, checking saved leaf IDs where necessary. Plans permit at most four deferred admissions; an empty warmable set schedules no successor itself. Hidden unbound restored tabs now avoid empty xterm mounts.
Inventory extraction: terminal-provider-snapshot-pty-inventory.ts, bound-ID type import, startup hydration, degraded recovery, account switching Startup, degraded startup recovery, or explicit account move Collector logic is moved unchanged: O(tabs + bindings + saved leaves + reconnect entries), deduplicated by PTY ID. All three production callers were traced. No new migration, storage operation, startup await, or hot-path caller is added.

The newly reached main-process capability handler, src/main/ipc/pty/ipc/inspect.ts:54, validates at most 512 IDs, waits on the existing provider-startup promise, and asks provider-owned capability state. The inspected daemon implementation checks protocol support and session membership; this path does not read scrollback, scan history, query SQLite, list sessions, or spawn a process.

Listener and selector census

Layout selector

The added selector at TerminalWorktreeSplitSurface.tsx:51 has one production consumer: each WorktreeSplitSurface, created by unchanged TerminalSplitWorkspaceSurfaces.tsx.

  • Quiet store: 0 callbacks/s.
  • With writes: M × S selector evaluations/s, two keyed reads each.
  • At M = 1,900, S = 2: 3,800 evaluations and 7,600 keyed reads/s.
  • At 10× M: 38,000 evaluations and 76,000 keyed reads/s.

useShallow compares two values; unchanged results prevent render and eligibility-map construction. This is useful constant work per retained shell, replacing substantially more subscription work: useTabBarRuntimeModel alone contains 23 direct app-store subscriptions per mounted strip, before counting its nested hooks and panel children. Releasing 1,900 one-group layouts removes at least 43,700 such subscriptions while adding 1,900 shell subscriptions. At S = 2, that is at least 87,400 removed selector evaluations/s versus 3,800 added.

Scroll and resize listeners

useTabStripScrollMemory is called only by TabBar. Production TabBar hosts are unchanged TabGroupPanel, TerminalTitlebarTabs, and FloatingTerminalPanelSurface; missing strip keys skip registration.

Every consumer of the strip’s restored/native scroll event at head is:

Consumer Listener count per applicable strip
New scroll-memory callback 1
Existing overflow navigation 1
Existing TabStripScrollIndicator scrolling-state callback 1
Existing indicator thumb synchronization Up to 1, when its track exists
Existing windowed-strip callback 1 when tab count ≥100

Thus 3–5 scroll callbacks per event, local to the scrolled strip. The new callback adds one property read, no store write. Restoration dispatches at most one synthetic scroll event per saved offset; a native scroll event may also follow. Windowing coalesces its update through one pending animation frame.

The existing shared resize subscribers are the windowed-strip range and indicator thumb. Existing strip ResizeObserver/MutationObserver registrations, the new pending-restoration observer, and scroll listeners all disconnect on teardown. Idle and unrelated status updates cause 0 scroll callbacks/s.

Windows capability subscribers

All production hook-call sites at head, including unchanged files:

  • use-tab-bar-runtime-model.ts
  • hooks/skills/runtime/useActiveProjectSkillRuntime.ts
  • onboarding/WindowsTerminalStep.tsx
  • settings/page/use-settings-terminal-model.ts
  • settings/navigation/useSettingsNavigationMetadata.ts
  • settings/cli/install/WslCliRegistration.tsx
  • status-bar/accounts/use-codex-switcher-controller.ts
  • status-bar/accounts/ClaudeSwitcherForOwner.tsx
  • agent/AgentSettingsDialog.tsx, through useLocalWindowsTerminalCapabilities
  • A second call in use-settings-terminal-model.ts, through that local wrapper

Each enabled instance registers one callback in its host-owner bucket. Disabled instances register none. Cleanup removes the exact callback and deletes empty buckets. Hook/status store writes produce 0 capability publications/s; a completed capability load publishes once to that owner’s enabled consumers.

The existing reprobe runner is shared by owner, with one shared window-focus listener. Releasing one strip does not stop surviving consumers.

I verified the requested base comparison: a returning strip previously remained mounted and retained the shared answer. Reusing cached answers on return preserves that behavior; new mounts retain base’s TTL semantics.

Capability publications and parking subscribers

The new publication route reaches all these unchanged consumers:

  • One capability-revision subscriber, in useTerminalProviderSnapshotCapability, called by use-terminal-workspace-projection.ts.
  • Two addressed parking subscribers, through useTerminalParkingWorkspaceChanges: use-terminal-parking-pass.ts and use-terminal-watcher-effects.ts.
  • Two workspace-keyed parking subscribers per cold-parking overlay: its direct input subscription and watcher-synchronization subscription.

PTY reverse indexes select affected workspace buckets. A publication for one PTY does not broadcast a parking invalidation to all 1,900 workspaces. Ordinary status writes that change no parking input produce 0 parking notifications; changed capability answers notify their addressed owners.

The unchanged bound-PTY store selector has one production owner. It runs on store writes, uses addressed record transitions, and preserves array identity when PTY membership is unchanged; a type-import relocation does not change this behavior.

Watchers newly reached through parking

  • Fact consumers: mounted pty-connection/output/pane-side-effect-facts.ts and parked parked-terminal-byte-watcher.ts. The registry retains one current consumer per PTY and shares one upstream channel.
  • Byte sidecars: parked byte watcher, agent-draft-readiness.ts, and claude-model-switch-confirmation.ts. Only byte-mode parked watchers add the parking sidecar; main/remote fact authority bypasses it.
  • Exit sidecar: terminal-parked-pty-watcher.ts, one per watched local PTY.
  • Geometry: TabGroupPanel owns body registration/grid observation; RetainedPaneHost is the sole geometry-subscription implementation consumer. Hidden fallback hosts do not subscribe for geometry unless explicitly measuring.
  • Manual parking retains its existing single window-event listener.
  • AiVaultSessionDropLayer registers seven window listeners only when enabled; hidden instances already registered none.

At idle these event-driven watchers receive 0 events/s. Under load, work follows the addressed PTY’s facts, bytes or exit—not W × event rate. Reveal/close/exit disposes registrations; replacement registration prevents duplicate parked byte watchers.

Timers and idle wakeups

Timer or newly reachable timer work Before → after steady-idle wakeups/s
New revived re-ask coordinator 0 → 0 after answer or exhaustion. A fixed cohort has ≤8 transient timer firings over approximately 91 seconds plus request time.
Existing 1-second batch deadline, newly used by re-ask 0 → 0 after completion; cleared when each request settles. A timeout does not cancel its underlying IPC, so “one in flight” describes awaited batches, not guaranteed cancellation of timed-out requests.
Existing general capability retry Base-false cohort 0 → 0 after revived settlement. Answers/settlement delete retry deadlines. An already scheduled synchronization timeout can wake once and then stop. Truly unknown base entries retain their existing five-minute re-ask.
Existing Windows reprobe No new recurring cadence: settled answer 0 → 0; unchanged unsettled owner eventually 1/300 → 1/300 while consumed. No owner-count multiplication from strips.
Scroll indicator, fit retries, fact handoff and watcher notifications Event/lifecycle-triggered one-shots; 0 → 0 once settled. Cleanup cancels owned timers; none becomes an interval.

Base cached false had no timed recovery path. Returning unresolved revived IDs to that same mounted, settled-false state therefore loses no base recovery mechanism. Originally unknown IDs retain their existing recovery path.

Regression classes touched

Class Disposition
Per-row derivation / broad selectors Matched and disproved: two keyed selector reads; local collection derivation stays behind memoized release gates. Subscription population decreases substantially.
Fixed-cadence retries / new idle wakeups Matched and disproved: finite revived cohort, explicit terminal settlement, retry-debt deletion; 0 additional steady-idle wakeups/s.
Expensive work newly reachable past a gate Reviewed: settled restored tabs can now park. Capability requests read bounded metadata; captures preserve necessary remote output; watchers replace mounted policy owners.
Hidden owners keep working / per-instance loading Improved: layout and strip owners disappear. Returning strips reuse capability answers; menus retain their existing open-menu admission gates.
Per-entity state outlives entity Matched and bounded: live capability inventory is pruned/reset; strip memory capped at 8,192; observers/listeners have cleanup.
Unbounded fanout / abandoned requests No introduced fanout: revived batches await sequentially; fixed-cohort attempts stop. Existing timeout-versus-cancellation limitation remains.
No-op publications / whole snapshots New publications carry changed PTY IDs and occur on meaningful authoritative transitions. No new whole-store snapshot publication.
Re-reading unchanged input / subprocess-per-instance Returning cached capability loads avoid reprobes; new mounts preserve base TTL/deduplication. No new per-PTY subprocess.
Eager startup imports Inventory extraction adds no heavy dependency or startup work; startup call order is unchanged.
Persistence / whole-file writes No changed persistence cadence or migration. Existing local-only remote parking captures retain their durability role.

Pre-existing aggregate work remains: usePendingStartupParkPresence checks every tab in each mounted overlay on store writes—S × total overlay tabs presence lookups—and runtime grid measurement enumerates mounted group bodies on geometry events. Neither population nor trigger cadence is increased by this span; layout release reduces the latter’s DOM population.

Six questions

Question Disposition
1. Work before skip gates? Reviewed. Selector cost counted upstream; tab indexing follows the release gate. Agent-menu inventory remains gated on menu opening.
2. Ownership multiplies work? Reviewed. Complete affected-consumer census above; capability requests/reprobes share owners, parked policy replaces mounted policy, and released strips retire subscriptions.
3. Which thread/storage pays? Renderer performs local eligibility, restoration and capture. Main capability handling reads provider metadata. No newly reached synchronous filesystem, SQLite or history scan found.
4. Growth and retry progress? Reviewed at 1,900/19,000 workspaces. Local collection sizes are explicit; revived answers remove IDs and fixed cohorts terminate. Admission stops when no warmable tab remains.
5. Execution-host effects? Inspected local daemon, degraded provider, Windows, SSH and environment capability routing. Existing host keys, TTL sharing and remote durability gates remain. No live Windows/SSH performance measurement was performed.
6. Obsolete work stops? Reviewed teardown and replacement paths for strips, observers, capability subscribers, parked watchers, retry debt and caches. No introduced perpetual idle owner found.

Residual validation limits: actual renderer CPU, switching frame gaps, xterm disposal, post-GC memory, and adverse-host IPC timings were not measured under the requested read-only restriction. The added tests were inspected only; they cover settled split eligibility and successful revived capability recovery, not fleet-scale timing.

@brennanb2025 brennanb2025 changed the title perf(terminal): park hidden workspaces' terminals and release their layouts so memory stays flat perf(terminal): release hidden parked workspaces' terminals and layouts so memory stays flat Nov 23, 2026
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan (fresh perf reviewer) on c0a7453

Review complete; one P1 blocks this head.

Findings

P1 — The returning-strip cache exception survives a host change

Introduced at windows-terminal-capabilities.ts:243, with the flag latched at use-tab-bar-runtime-model.ts:149.

returningStrip is initialized once and remains true for the component’s lifetime. The capability effect reruns when its owner changes, but continues bypassing the TTL whenever that new owner already has a cached answer.

A reachable sequence is:

  1. A released strip returns, initializing returningStrip=true.
  2. The user selects another host’s copy of the same workspace ID. Selection explicitly supports this through activeWorkspaceExecutionHostId; workspace surfaces and their React keys remain keyed by bare workspace ID.
  3. The new host has an answer older than 30 seconds, retained by another subscriber or released strip.
  4. Head reuses that answer without loading capabilities. Base reruns loadWindowsTerminalCapabilities for the changed owner and refreshes the expired answer.

For a remote owner, no local re-probe runner repairs this. A previously unavailable shell can therefore remain missing until another consumer explicitly reloads that host.

Trigger / population / bound: One owner transition on a previously returned strip; potentially every such strip among 1,900 workspaces, or 19,000 at the growth target. Base performs one deduplicated TTL load for the new owner; head performs zero and can retain stale output indefinitely. This is P1 for a user-visible freshness regression, not a measured CPU regression.

Source evidence: set-active-worktree.ts:134 treats a changed host selection as a state change; resolve-owner.ts uses that selection; TerminalSplitWorkspaceSurfaces.tsx:60 keys the surface without the host. The changed capability effect includes owner dependencies but applies the return exception on every execution.

Required correction: Tie the exception to the specific owner whose strip was released, and preserve normal TTL loading when that owner changes.

Proving check, not executed: Mount a returning strip for host A; retain an expired negative answer for remote host B; change the strip’s owner to B. Assert one deduplicated B load and publication of its current answer. Control: returning to unchanged host A should reuse its answer without a TTL load.

Coverage and work accounting

Compared 2284cb2d04f0de86c695f1f5aa584d5c48ee1f18 with verified head c0a7453c4f2f30a4005752a419bf580fa98c4044. Read-only source review; no edits, builds, typechecks, test suites, or runtime measurements.

Notation: N mounted workspace surfaces; T/G/L tabs, groups, and terminal leaves in an affected workspace; P inventory PTYs; R revived negative-capability IDs; H capability host owners; W root-store publications/second.

Changed work and files Trigger and population Work, lifetime, bound
Startup inventory extraction: use-app-startup-hydration.ts, startup-degraded-recovery.ts, terminal-provider-snapshot-pty-inventory.ts; account-switch import and bound-selector type import Startup, eligible degraded recovery, account switch Inventory algorithm is moved unchanged: visits saved tabs, bindings, reconnect IDs, and layout bindings. O(Total tabs + bindings), deduplicated IDs. Startup’s existing awaited capability step and reconnect ordering remain. No added migration, disk write, or startup RPC.
Capability synchronization: terminal-provider-snapshot-capability.ts Inventory membership change, explicit refresh, existing unknown-retry deadline Adds a live-ID set, epoch, and settlement operations. Retention O(P), replaced/pruned with inventory. Existing identity/deadline gates remain before inventory scans. New answer settlement clears retry debt.
Revived recovery: terminal-provider-snapshot-revived-reask.ts, ipc-pty-connect.ts, pty-transport.ts Successful spawn/attach/bind of an inventoried ID cached false Bind gate uses constant-time membership checks. One shared scheduled pass, serial batches of ≤512 IDs, eight attempts per admitted ID. Duplicate binds while awaiting do not reset its allowance. Answers/removal/exhaustion retire IDs; epochs reject reset-era results.
Settled-spawn eligibility: manual hook, cold-parking hook, manual eligibility, settled-activation-spawn.ts, terminal-hidden-view-parking.ts, parking-pass candidates Manual park request; addressed parking-input change; existing visibility/parking deadlines Only flagged local activation-spawn tabs invoke the new check. O(live PTYs + tree leaves + saved bindings) per checked tab. Workspace candidate collection remains restricted to dirty workspaces; it can check eligibility twice. Pending startup, missing bindings, chat leaves, visibility, portal, measurement, and restore-policy gates remain.
Layout release: split surface, overlay layers, released-layout-eligibility.ts Park verdict, local tab count, group reference, browser eligibility One workspace-local O(T+G) eligibility projection after the release gate. Removes its layout subtree; keeps overlay-owned chats outside that subtree. Editors, landing views, simulators, browser pages, force-park cases, and open quick-command editors prevent release as applicable. Return remounts that workspace’s groups, not all workspaces.
Scroll preservation: TabBar.tsx, tab-strip-scroll-memory.ts Strip mount/unmount, native scroll, pending restore resize One passive scroll listener per mounted strip; at most one temporary ResizeObserver. Scroll handling stores one number. Cleanup removes both. Saved entries capped at 8,192; restoration deletes the entry. Group-open checks scan that workspace’s groups.
Quick-command protection: button and editor-presence module Editor open/close and component teardown One count per workspace with an open editor; constant-time increment/decrement, idempotent cleanup. No timer, subscription, publication, or root-store write.
Windows capability retention: runtime model, capability hook, holds module Strip release/return; capability load/publication; owner transition One hold per released group and one count per held owner. Add checks its workspace plus one rotating workspace for closed groups. Cache pruning/trimming scans H owners per load/publication, not per hook-status event. Ordinary same-owner returns avoid added probes; new mounts retain TTL loading. Owner-transition exception is the finding above.
Deferred admission: hook and unbound-restored predicate Existing activation/plan/mount-revision idle admission Adds filtering of the active workspace’s tabs and saved bindings. Admission still requires a peak deferred count ≤4 and admits one tab per pass. No warmable tab means no revision increment or self-reschedule. Unbound saved terminals wait for visibility.

The newly reached main capability inspection validates at most 512 IDs and queries provider metadata. The daemon authority check uses protocol support and activeSessionIds.has(id); it does not read scrollback, enumerate all sessions, spawn a process, or synchronously access SQLite/filesystem storage.

For a simultaneous cohort, revived recovery sends at most 8 × ceil(R/512) batches: 32 for R=1,900, 304 for R=19,000. With 300/3,000 revived terminals, the bounds are 8/48 batches. These are finite recovery costs, not status-event costs.

Listener and selector census

Rates below are source-derived. Actual W was not measured. Hook status arriving more than once/second does not establish one root-store write per event: accepted updates can be batched, and title updates can add writes.

Subscription/listener Every production consumer at head Idle and load rate
New layout selector WorktreeSplitSurface, instantiated by TerminalSplitWorkspaceSurfaces N subscriptions, including released surfaces. N×W constant-size evaluations/second; no fleet scan inside the selector. At N=1,900 and W=2/20: 3,800/38,000 evaluations/s; at 10N: 38,000/380,000. Unrelated hook-status/title writes preserve selected values and do not rerun layout eligibility. Quiescent W=0 gives zero callbacks.
Capability revision publication Sole direct subscriber: useTerminalProviderSnapshotCapability, through useTerminalWorkspaceProjection. Returned revision feeds useTerminalParkingPass and useTerminalWatcherEffects One global subscription per workbench. No publication from ordinary status events. Revived publication occurs only for newly authoritative answers, at most once per admitted ID before another invalidation. Addressed PTYs feed the parking reverse indexes; they do not request unconditional all-workspace invalidation.
Parking input publication downstream Two keyed subscriptions per mounted terminal overlay: useTerminalTabColdParking and its useParkedTerminalWatcherSynchronization; two addressed workbench subscriptions through parking-pass and watcher effects A changed PTY notifies its owning workspace buckets plus the two addressed consumers. Ordinary unrelated hook-status updates do not become fleet-wide capability invalidations. Closed subscriptions remove their buckets.
Bound-PTY selector, unchanged implementation useTerminalProviderSnapshotCapability One root-store selector per workbench, evaluated W times/second. Unchanged source references take the fast path. Addressed transitions update affected contributions; unknown transitions rebuild inventory. Membership changes sort P IDs; title-only replacement preserves the returned inventory identity.
Windows capability subscribers WindowsTerminalStep; WslCliRegistration; useSettingsNavigationMetadata; useSettingsTerminalModel’s host hook and local wrapper; AgentSettingsDialog’s local wrapper; useTabBarRuntimeModel; useCodexSwitcherController; ClaudeSwitcherForOwner; useActiveProjectSkillRuntime Ten hook call sites, with multiplicity from their mounted owners. Each enabled instance subscribes to one owner bucket. Hook-status writes do not themselves publish capabilities. A host load notifies its mounted consumers; released strips retain holds, not callbacks. Cleanup unsubscribes and releases reprobe ownership.
Local reprobe focus listener, unchanged Shared runner started by enabled local instances of the capability hook At most one global focus listener while runners exist; one runner per owner. Settled WSL answers schedule no probe. Unsettled answers back off to 300 seconds. On Windows, App → SkillFreshnessNudge → useActiveProjectSkillRuntime keeps a local consumer independently of parked strips, preserving local recovery.
New strip scroll/resize listeners Only TabBar → useTabStripScrollMemory One scroll listener per mounted strip; resize observer only while a saved restore awaits a usable box. Zero autonomous idle cadence. Under interaction: one O(1) assignment per scroll event; restore dispatches one synthetic scroll event. Both disconnect on teardown.
Manual parking listener, changed callback useManualTerminalWorktreeParking, through useTerminalParkingFoundation Existing single workbench event listener. Zero calls without requests; each request examines only its target workspace.
Quick-command presence and capability holds Presence: quick-command button writes, layout eligibility reads. Holds: tab-bar runtime writes/takes; capability pruning/trimming reads No listeners, selectors, or scheduled work of their own.

useSettingsNavigationMetadata also serves the workspace palette. useActiveProjectSkillRuntime serves the persistent freshness nudge and its settings/setup/onboarding consumers; these remain consumers of the same shared capability owner rather than introducing separate probe loops.

Pre-existing amplification: useTabBarRuntimeModel alone contains 23 direct root-store subscriptions per strip; the group workspace model contains six more, including broad layout/open-file dependencies. Before release, these selectors run on every root-store publication across retained strips. The change removes those owners for released layouts while retaining the one new surface selector. It does not eliminate all per-workspace subscription cost.

Timer accounting

Timer Before → after steady-idle wakeups/s per process Transitional bound
New revived re-ask scheduler Renderer 0 → 0 after answers or exhaustion; main/daemon 0 → 0 periodic wakeups attributable to this scheduler Isolated cohort: at most eight passes, delays 0,1,2,4,8,16,30,30 seconds. New IDs do not extend old IDs’ attempt allowance.
Existing one-second resolution timeout, newly used by revived batches Renderer 0 → 0 after recovery; main/daemon 0 → 0 periodic wakeups One timeout per sequential batch; cleared on an earlier answer. Timeout does not cancel underlying RPC work. No more than eight batch inclusions per revived ID per admission.
Existing inventory unknown-retry timer For base-settled false IDs: 0 → 0 after revived settlement Clearing retry maps can leave an already armed callback; its next synchronization sees no retry debt and stops. Genuine startup-unknown IDs retain their existing slow recovery path.
Existing local Windows re-probe Unchanged: settled owner 0 → 0; unsettled owner at ceiling 1/300 → 1/300 Shared ownership and cleanup remain.
Existing deferred-admission idle callback/timeout fallback 0 → 0 after admission settles ≤4 admissions per eligible plan; an unbound-only remainder does not keep rescheduling itself.

Verified against base: restored IDs answered false had no timer or automatic re-ask. Exhausted revived IDs return to that same parking result and quiet state. The change does not remove base recovery for genuine unknown IDs.

Regression classes touched

Class Disposition
Broad subscriptions / per-row derivation Matched; new selector is constant-size and workspace-keyed. N×W cost recorded above; no new collection walk per status event. Nonblocking overhead under this round’s bar.
Expensive work newly reached past a gate Matched; restored terminals now reach existing capture/parking/restore paths. Work is limited to affected terminals and their lifecycle transitions; no new per-chunk inventory.
Polling / new steady-idle wakeups Matched and bounded: revived retry stops per ID; steady idle remains zero for formerly settled-false IDs.
Publication/version amplification Matched; revived true answers publish changed PTY IDs. No publication for unchanged/null/settled-false revived answers.
Per-instance loading / remount work Matched; local subtree remount and subscription setup repeat on return. Ordinary capability returns avoid added TTL probes. Owner-change freshness is P1.
Cache ownership and invalidation Finding: return exception is not restricted to the held owner.
Entity retention / resource cleanup Matched; editor counts clean up, scroll memory has a cap, retry entries retire, holds drain closed groups opportunistically. Removed layout owners release their component subscriptions and listeners.
Fanout / pending work Matched; serial ≤512-ID batches and eight attempts bound each admission. Underlying timed-out RPC cancellation is unchanged; no claim of actual I/O cancellation.
Hot-path rescans Matched; new leaf walks are local parking-eligibility work. Hold cleanup checks at most two workspaces per add, rather than sweeping N.
Startup imports / storage Inventory extraction is a move. No added SDK, migration, whole-state persistence, subprocess, or synchronous storage operation.

Nonblocking notes: the 8,192-entry scroll cap can evict an older live strip’s remembered offset at the 10× population. Hold cleanup is opportunistic, so deleted released groups may retain small records until later additions. Neither is claimed as immediate teardown.

Six scan questions

  1. Unused work before skip gates — reviewed. Capability bind admission precedes scheduling; layout eligibility follows the parking/browser gate. The new N×W selector overhead remains explicit.
  2. Ownership multiplying work — reviewed. One revived scheduler; owner-shared capability loads/reprobes; one added selector per retained surface. Complete affected consumer census above.
  3. Thread and storage payer — reviewed statically. Renderer pays projections, leaf walks, restore/remount work, and retry bookkeeping. Newly reached main inspection reads metadata. Timing, CPU, heap, and frame-delay impact were not measured.
  4. Growth and progress — reviewed. Eight attempts per revived ID, 512-ID batches, addressed parking candidates, capped scroll memory, and finite deferred admission. No source-proven unbounded retry loop.
  5. Execution host — reviewed; P1 remains. Local, SSH, paired-runtime, Windows, macOS/Linux renderer gates, and web-owner call sites inspected. Same-owner cached return matches base; changed-owner TTL bypass does not.
  6. Obsolete work stopping — reviewed. Scroll observers/listeners disconnect; component subscriptions retire; retry maps drain and epochs reject stale results. Timed-out RPCs are not canceled, and closed capability holds drain opportunistically.

The four added test files were inspected, not executed. No runtime speed, memory reduction, or platform-QA result is asserted. The referenced terminal-session-reliability skill was unavailable at the supplied sibling location; terminal correctness controls were traced directly in source.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status for c0a7453

Problem: every visited workspace stayed mounted for the session (xterms, listeners, tab-group layout), so renderer memory grew with workspaces visited.

User-facing change: none on screen. Hidden workspaces whose terminals are parked release their terminal views and layout, and come back in the same state on return.

Reviews on this head

  • Blinded regression audit (Codex): SAFE. It also confirmed in base code that a terminal's Find query is already lost whenever a terminal parks on main. That is pre-existing; this change only widens which terminals can park.
  • Fresh Claude review: PASS.
  • Fresh perf reviewer (full perf-scan): blocked by one P1, see the report above. It is the latest form of the shell-capability point below and needs a decision from Brennan.

Open: shell-capability reuse on a returning tab strip (perf P1, both sides)

  • Finding: a strip that returned from a released layout keeps its "returning" flag for its lifetime. If that strip later switches to another host's copy of the same workspace, it reuses that host's cached answer even when it is older than the 30 s TTL. Main would reload it.
  • Other side: this needs a returning strip, then a host switch within that same strip, and a cached answer kept alive by another consumer. The answer is still the latest one published for that host, so it is not invented data. Ordinary returns now make zero probes, which matches a retained strip on main.
  • Fix if wanted: clear the flag when the owner key changes.

Fixed in the last rounds: an open quick-command dialog's unsaved text kept the layout from being released (data loss); revived capability re-asks are now counted per id; live capability owners are never trimmed.

Notes (below the blocker bar)

  • A workspace left on an editor tab, or holding a never-opened restored tab, still stays mounted.
  • Restored tabs with no PTY are no longer idle-warmed in the active workspace.
  • Manual park now refuses a restored chat-view terminal or a partly spawned split.

Verified
Benchmark: head=c0a7453c4f2f30a4005752a419bf580fa98c4044 gate=PASS name=workspace-unmount-soak corpus=fleet seed (1,800 worktrees + 100 folders, 1,800 chats, 200 terminals), Linux, 150 visits x 2 streamed turns, GC'd. main 2284cb2 vs head. xterms 30 -> 0, mounted layouts 150 -> 5, DOM listeners 17,578 -> 7,997, renderer heap 871 -> 753 MB, renderer PSS 3,165 -> 2,896 MB, early-workspace switch-back median 1,004 -> 416 ms. Mounted listeners measured: workspace surfaces, tab strips, chat overlays.

Restore on a released workspace: the running shell loop kept all 215 lines (ready in 486 ms), and the unsent chat draft was kept. remote-check (pnpm check:changed, related tests) passes on this head, as do the 4 changed test files (8 tests).

…eep agent detection's observed hosts across a remount
…e's simulator and browser overlays unmounted
…mulator and browser overlays unmounted

Replaces the per-store-write tab scan: admission marks its restriction drained when only unbound restored tabs remain, so over-cap restrictions keep base behaviour.
…ly on the same host; tidy observed-host and hold lifetimes

- Comparing the held owner key keeps a host-changed return on the normal TTL load.
- Agent detection resolves its group's observed-host set once per group, not per render.
- A capability hold left by a dependency change on a still-mounted strip is dropped when probing turns off.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Findings

No blocking regression found in 2284cb2d04f0de86c695f1f5aa584d5c48ee1f18..3ad9999e879a4c1c0da028a14ce4e6c9fda7ac0b, using this round’s grading bar.

The previous different-host capability finding is resolved. The returning strip compares its held owner with its current owner in use-tab-bar-runtime-model.ts:

  • Same owner: reuse the shared cached answer, matching base’s continuously mounted strip.
  • Different owner: use the normal loader, including its 30-second TTL and pending-request deduplication.
  • Subsequent owner change while mounted: clear the reuse exemption in windows-terminal-capabilities.ts.
  • New strip: retain base’s mount-time TTL load.

Nonblocking notes:

  • Released layouts leave their outer workspace surfaces mounted. Consequently, the new local selector still executes once per surface per store write.
  • Unannotated group replacements still make the shared retirement subscriber inspect every remembered workspace. The ordinary tab-activation writer is addressed; status-only writes do not take this fallback.
  • Capability-cache trimming can now visit live host owners beyond the former 32-entry cap. Those entries preserve answers for open strips; they do not accumulate independently of their owners.

Coverage and work bounds

Evidence is source inspection and base/head comparison, not runtime measurement. HEAD was verified. No files were edited, and no builds, typechecks or test suites were run. The added test assertions were inspected, not executed.

Population notation:

  • W: workspace surfaces, evaluated at 1,900 and 19,000.
  • G: open tab groups; gᵥ, tᵥ, pᵥ: groups, tabs and pane bindings in one workspace.
  • P: distinct saved/live PTY IDs.
  • H: distinct capability owners.
  • R: total app-store writes/second. At an illustrative R=2, the new workspace selector receives 3,800 evaluations/second at W=1,900; hook traffic above one write/second produces more than 1,900/second. Actual R was not measured.

All changed runtime work is in the renderer unless otherwise identified.

Changed work Trigger and population Bound and disposition
Startup hydration, degraded recovery and account-switch inventory imports Startup/recovery or explicit account switch; saved workspaces, tabs and bindings Collector implementation is moved unchanged. Existing full inventory traversal and deduplication remain; no added startup wait or per-status inventory. Covers startup-migration.
Snapshot inventory selector’s type import Existing selector execution on store writes Runtime implementation unchanged. Addressed changes update affected contributions; membership changes rebuild/sort the PTY array; unannotated input uses the existing full resync.
Revived-session admission in IPC connect/bind Successful spawn, restore or bind; one PTY ID Constant membership checks. Only an inventory ID with a cached false enters re-ask work; duplicate bind calls while it is unknown do not renew its allowance.
Revived-capability re-asks Eligible IDs admitted since startup’s negative answer One scheduled retry owner and one renderer-side request chain; batches of at most 512; eight attempts per ID. A simultaneous 1,900-ID cohort requires at most 32 batch calls; 19,000 requires 304. Arrivals can produce smaller batches, but each ID retains its own attempt limit.
Capability answers and revisions Actual parking-authority changes True answers publish affected IDs; false/unknown answers do not publish a redundant parking change. A batch publishes once. Reverse indexes invalidate affected workspace owners. Covers publish/version-bump.
Settled activation-spawn eligibility Manual parking, existing tab-parking effect or dirty-workspace parking pass Walks only the candidate tab’s pane topology/bindings, O(pᵥ). Called only behind the pending-spawn predicate. No new subscription or periodic sweep.
Layout release eligibility Parking/visibility change, local group identity or tab-count change, dialog-presence transition O(tᵥ + gᵥ) for that workspace, memoized. Unrelated title/status writes retain the memo inputs. Visible, measuring, force-parked, browser-containing, simulator-containing and unsafe active-content layouts retain their gates.
Layout/drop-layer release and restoration Eligible hidden workspace parks; user returns Releases that workspace’s layout and drop layer. Existing terminal parking captures buffers before unmount; cleanup detaches retained sessions and destroys pane managers/disposables. Return rebuilds the visited workspace, not all saved workspaces.
Group-scoped state Strip mount/unmount, group removal or workspace removal Exactly three production registries: capability holds, scroll memory and observed agent targets. At most one entry per open group per registry; removal disposes entries. Observed-target set contents scale with distinct targets seen by that group, as base’s mount-lived set did.
Capability holds/cache retention Strip cleanup, return and cache loads/publications Constant owner-count updates; group existence check visits gᵥ. Cache retains live mounted/held owners plus the ordinary unheld cache budget. Pruning/trimming is O(H + 32) on loads/publications, not store writes.
Agent observation persistence Group launch surface mounts or changes target One group lookup per owner change; set membership thereafter. Prevents remount-driven repeat refreshes of already observed hosts. Existing explicit refresh, re-pair and reconnect recovery remain.
Tab-strip scroll memory Strip mount, native scroll and cleanup One passive listener per mounted strip; constant work per scroll. A temporary ResizeObserver waits for measurable width, then disconnects. One saved offset per released open group.
Activation admission Active workspace’s deferred plan/revision changes Existing peak limit of four deferred tabs remains. Each admission scans only that workspace’s tabs/bindings. Warmable tabs advance; unbound restored tabs remain deferred until shown.
Drained restriction propagation and overlay gates Admission exhausts warmable tabs; restriction is widened/pruned; surface renders WeakSet membership/addition is constant work. One revision change on first drain; replacements carry the mark without a new global subscription.

The newly reached main-process capability handler validates at most 512 IDs and checks provider metadata. The daemon adapter’s authority check reads protocol support and activeSessionIds.has(id); this route does not add per-ID filesystem reads, subprocesses, snapshots or daemon RPCs.

Listener and selector census at head

Counts below include unchanged production consumers of the changed hooks.

Subscription/listener Every production consumer Idle and loaded rate
Shared group-state store subscription heldOwnerKeyByGroup, offsetByGroup, observedTargetsByGroup One subscription total, after first use. R callbacks/second. Status-only writes perform one group-map reference comparison.
New workspace-local app selector WorktreeSplitSurface, instantiated by TerminalSplitWorkspaceSurfaces W subscriptions; W × R evaluations/second. At R=2: 3,800 / 38,000 at N/10N. Each evaluates local tab length, local groups reference and shallow equality; no eligibility scan on unchanged results.
Quick-command presence Subscriber: WorktreeSplitSurface. Producer: TabBarQuickCommandsButton One listener per mounted workspace surface. Zero notifications from store/status writes. First dialog open/last close notifies only that workspace’s listener bucket. Dialog and surface cleanup remove counts/listeners.
Scroll/resize observation TabBar through useTabStripScrollMemory One scroll listener per mounted strip; at most one temporary ResizeObserver per pending restore. No timer or store-write callback. Both disconnect on cleanup.
Windows capability publication useTabBarRuntimeModel, useActiveProjectSkillRuntime, WindowsTerminalStep, WslCliRegistration, useSettingsNavigationMetadata, useSettingsTerminalModel, useCodexSwitcherController, ClaudeSwitcherForOwner; local-wrapper consumers: AgentSettingsDialog and useSettingsTerminalModel One subscriber per enabled mounted hook, partitioned by owner. Publications notify that owner’s consumers only. Released strips retain holds rather than listeners. Ordinary store writes do not notify this registry.
Shared Windows reprobe/focus listener All local, non-SSH consumers of that capability hook One runner per owner and at most one global focus listener. Final consumer cleanup stops its timer; held answers alone start no runner.
Agent detection selectors Direct consumers: runtime-target-selection, AgentLaunchSettingsCatalog, OrchestrationSkillAgentCoverage; bridge: useAgentMenuObservation Each mounted detector retains seven app-state selectors and one host-entry selector. App selectors follow R; host-entry observation follows that host’s publications. Released group menus unsubscribe. Existing pairing selector searches runtime environments, not workspaces.
Agent-menu bridge consumers useTabBarCreateMenuController, AgentMenuItems, split-pane-landing-agents, useBotAgentChoices, AgentSessionContinuationDialog, SourceControlActionAgentPicker, useRepositoryActionPickerInputs, NewWorkspaceComposerModal, AutomationAgentLaunchPicker, useSourceControlActionAgentChoice, useChecksPanelCommentResolution Only the tab-bar caller supplies the new observation-group identity. Other consumers retain mount-scoped observation semantics. Existing shown/open acquisition gates remain.
Snapshot bound-ID selector and capability revision One useTerminalProviderSnapshotCapability in useTerminalWorkspaceProjection One app-store selector and one revision listener per terminal controller, not per workspace. Revision changes feed the parking and watcher effects; both use addressed dirty owners and return when none are dirty.
Manual parking event useManualTerminalWorktreeParking, called by useTerminalParkingFoundation One existing window listener per controller. Changed handler visits requested workspace tabs only; zero calls without a request.

For genuine quiescence, subscription callbacks are zero/second. If existing background activity writes the store at Rᵢ, app-store subscribers run at the formulas above; this change introduces no timer to generate those writes.

Group-state retirement and unannotated writers

At tab-group-scoped-state.ts:25:

  • Unchanged groupsByWorktree: one comparison.
  • Addressed tab activation: inspect the named workspace, build its open-group set and retire entries in three registries. Cost is O(gᵥ), independent of 1,900 versus 19,000 unrelated workspaces.
  • Full resync/unannotated replacement: collect at most three remembered-workspace lists, deduplicate, compare workspace group arrays, and inspect groups only where arrays changed.

Production fallback writers found:

  1. Full and scoped hydrateTabsSession, explicitly marked hydration.
  2. buildLayoutFrameStorePatch, explicitly marked host-mirror-frame when group content changes.
  3. Web-session mirror applyWorktreeRecordUpdates → withWorktreeEntry/writableWebSessionTabsRecord, which copies group records without addressed annotations.

Initial empty state is also unannotated. Normal focus, create, close, move, split, drag-preview, rename, reconciliation, editor-owner and teardown writers use addressed replacements/drafts. Mirror sameGroups equality excludes ordinary status/title changes from creating a new group record.

The fallback is a bounded structural-update cost, not a new all-workspace traversal on every hook-status update.

Overlay retention against base

For plans within the four-tab admission limit, base eventually admitted unbound restored tabs and drained the restriction. Head avoids mounting those empty terminals but marks the restriction drained, restoring the same hidden browser/emulator overlay admission. Pruning/widening preserves that mark.

For over-cap plans, admission still exits before marking drained. Their hidden overlay restrictions remain as on base. The new gate therefore does not retain additional simulator/browser overlays for those workspaces.

Timers and idle wakeups

Timer Base → head steady-idle wakeups/second, per process Transient bound
New revived-capability retry timer Renderer 0 → 0 after answer/exhaustion; no added steady main/daemon RPC cadence Immediate first pass, then 1/2/4/8/16/30/30-second waits, eight attempts per ID. Later IDs cannot extend older IDs’ allowance.
One-second capability-request timeout, reused by revived path Renderer 0 → 0 after requests settle One timeout per awaited batch; cleared on completion. Timeout does not cancel an already dispatched IPC, but retries remain finite.
Existing unknown-capability synchronization Unchanged: genuine unresolved IDs eventually retry at roughly 1/300 s⁻¹ per synchronization chain Revived IDs that exhaust their allowance settle false and have retry-deadline entries removed. An already armed synchronization timer may perform one final check.
Existing local Windows reprobe Settled owner: 0 → 0. Unsettled mounted owner: existing backoff, eventually approximately 1/300 s⁻¹ Shared per owner. Releasing its final consumer stops it; returning can re-arm it. No per-strip idle multiplier.
Existing admission/deadline timers 0 → 0 after admission/parking settles Admission advances a tab or marks drained; existing cancellation remains.

Base’s startup false answer was permanently settled. Head’s exhausted revived path returns to that same state: mounted, no continuing retry and no continuing capability RPC. It preserves startup unknown-answer recovery, explicit refresh/degraded recovery, and permits another re-ask on a later attach.

Regression classes touched

Class Disposition
Broad subscriptions / per-row collection derivation New workspace selector reads addressed local values. Its W × R cheap evaluations are disclosed above; full eligibility work is memoized.
No-op identity/publication churn Drain marks change once; false capability answers do not bump parking authority; existing group equality prevents status-driven group replacements.
Fixed polling / new idle wakeups Revived retry is finite per ID; steady-idle delta is zero after settlement. Existing unknown/reprobe polling is identified separately.
Hidden/per-instance work Layout listeners and terminal resources release; quick-command presence is workspace-addressed. Remaining outer-surface subscriptions are counted.
Expensive work newly reachable beyond a gate Capability re-ask handler performs bounded metadata checks. Newly parkable terminals use existing capture/restore and watcher safety gates.
Whole-snapshot publication / version bumps Changed PTY IDs invalidate their owners; one global revision listener does not imply one subscriber per workspace.
Entity-state retention Three static registries retire entries with groups/workspaces; scroll observers and presence listeners clean up; restriction marks use weak identity.
Hot-path scans Group retirement is addressed on activation; local eligibility and pane topology scans have local bounds. Capability owner scans occur on loads/publications.
Queues/retries Eight attempts per ID, 512-ID batches, one revived request chain; no allowance renewal from unrelated arrivals.
Cache identity / host correctness Same-owner return reuse confirmed; different-owner and new-mount TTL loading confirmed.
Startup imports / migration Collector extraction preserves startup work and contains no newly eager SDK or adapter initialization.

Six questions

  1. Unused work before the skip gate? — Reviewed. Workspace selectors still execute, but expensive eligibility, host probing and inventory work remain behind their relevant gates.
  2. Does ownership multiply work? — Reviewed. One shared retirement subscription, owner-shared capability loads/reprobe, workspace-addressed dialog notifications, and one capability-revision subscriber.
  3. Which thread/storage layer pays? — Reviewed. Renderer pays local derivations and lifecycle capture/restore. Added main capability calls inspect bounded provider metadata; no new disk/SQLite or subprocess path.
  4. What grows, and does progress advance? — Reviewed. Registries follow open owners; admission advances or drains; each revived ID exhausts independently. Existing unknown resync and observed-target growth are distinguished from new work.
  5. What changes by host? — Reviewed statically. Local, Windows/WSL, SSH and paired-runtime routing preserve owner identity. No runtime latency or cross-platform execution claim is made.
  6. Does obsolete work stop? — Reviewed. Released strips unsubscribe; scroll observers disconnect; closed groups retire state; late capability answers are checked against inventory/epoch; retries settle.

Runtime frame latency, retained heap and native host behavior remain unmeasured under the requested read-only scope. No source-proven blocking amplification remains unresolved.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status for 9ed2ec7

Problem: every visited workspace stayed mounted for the session (xterms, listeners, tab-group layout), so renderer memory grew with workspaces visited.

User-facing change: none on screen. Hidden workspaces whose terminals are parked release their terminal views and layout, and come back in the same state on return.

Reviews on the final code (3ad9999e879a; the head adds only a ratchet baseline row)

  • Blinded regression audit (Codex): SAFE. It again confirmed that a terminal's Find query is already lost whenever a terminal parks on main, so that point is pre-existing.
  • Fresh perf reviewer (full perf-scan): clean, see the report above.
  • Fresh Claude review: PASS (no P0/P1).
  • remote-check (pnpm check:changed, related tests) passes on the head.

Fixed since the last status

  • Released strips' capability holds, tab-strip scroll offsets and agent detection's observed hosts now live in one per-tab-group store that is cleared when the group or workspace is removed. Its store subscription visits only the workspaces a write addressed.
  • A remounted tab bar no longer forces a fresh agent-host scan, and a returning strip reuses its held shell-capability answer only on the same host (a different host takes the normal TTL load).
  • A hidden workspace whose only deferred tabs are unbound restored tabs keeps its simulator and browser overlays mounted, as main does once warm-up drains. Every write to the deferred-mount restriction carries that state (a reviewer enumerated all of them).
  • Closing a quick-command dialog now re-checks release for its hidden workspace.

Mount effects in TabBar / TabGroupPanel, decided one by one

  • Survive a remount: shell capabilities (held answer), agent detection (observed hosts per group), strip scroll offset.
  • DOM-local with cleanup, cheap to redo: overflow navigation, drag-scroll, pointer activation, hover card, scroll indicator, menu fit, sortable rename, focus return, context-menu listeners, item-actions layout.
  • Shared store or IPC subscriptions, cheap: chat names (shared observer), recent-tab switcher listener, quick-commands shortcut.
  • Gated off while hidden: runtime file list (menu open or landing page only), auto-close preference (open only), naming-failure probe (only with a naming failure), session drop layer (visible only). Landing pages are never released.

Intended, recorded with reviewers' agreement

  • Manual "Park terminals" refuses a restored chat-view terminal (it would lose its reader position) and a restored split with an unbound pane (nothing to park). Reviewer: AGREE.
  • Hovering a released workspace remounts its tab bars for the prewarm lease, which is how main runs all the time. Keeping it released would move that mount onto the reveal frame. Claude reviewer: AGREE to ship and track it as a follow-up (cover sweeping the pointer across many released rows).
  • Restored tabs with no PTY start their shell when opened instead of in idle warm-up (Activating a worktree respawns the agent command in every dead tab, without a limit; hitting the container PID limit then kills the terminal daemon with no log #39166).
  • Claude suggested deleting released-layout-eligibility.test.ts as a UI test. It is kept: it guards the open quick-command dialog's unsaved text (data loss), which the test rules allow.

Notes (below the blocker bar)

  • A keyboard switch to a released workspace mounts its tab bars on the reveal frame (no hover prewarm). The switch-back measurement below includes that.
  • A workspace left on an editor tab, or holding a never-opened restored tab, still stays mounted.

Verified
Benchmark: head=3ad9999e879a4c1c0da028a14ce4e6c9fda7ac0b gate=PASS name=workspace-unmount-soak corpus=fleet seed (1,800 worktrees + 100 folders, 1,800 chats, 200 terminals), Linux, 150 visits x 2 streamed turns, GC'd. main 2284cb2 vs head, build tree identical to the head's. xterms 30 -> 0, mounted layouts 150 -> 5, DOM listeners 17,578 -> 7,997, renderer heap 871 -> 757 MB, renderer PSS 3,165 -> 2,947 MB, early-workspace switch-back median 1,004 -> 197 ms (recent workspaces 193 ms).

Restore on a released workspace: the running shell loop kept all 213 lines (ready in 494 ms), and the unsent chat draft was kept. An earlier variant that kept the tab-group chrome mounted and released only terminal views kept about a third of the heap and PSS saving, so the layout release stays.

…he registry doesn't import it (dependency cycle)
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Findings

No must-fix regression found against 2284cb2d04f0de86c695f1f5aa584d5c48ee1f18 at head 2298323fd96acb442ed542eb539abff2751b4c1d.

Confirmed:

  • Same-owner returning strips reuse their held capability answer. Different-owner returns use the normal mount-time TTL load.
  • Revived terminal capability requests settle after success or eight attempts. After settlement, their steady-idle timer and RPC rates match base: zero.
  • Group-state retirement subscribes once through the store’s observer installers. Ordinary tab activation addresses its workspace; unrelated status writes do not enumerate remembered workspaces.
  • Quick-command presence notifications stay within the affected workspace.
  • Drained admission preserves hidden browser/emulator overlays without widening admission for over-cap workspaces.

Evidence is source inspection and base/head comparison. No files were edited; no builds, typechecks, tests, benchmarks, or app launches were run. Timing, CPU, heap reduction, and rendered restoration were not measured.

Coverage and work accounting

All 37 runtime files in the requested marker, the five added test files, and the compiler-baseline deletion were inspected. The test assertions were read, not executed.

Notation: W = workspaces, M = mounted workspace surfaces, G = open groups, gᵢ/tᵢ/pᵢ = one workspace’s groups/tabs/panes, T = inventory PTY IDs, R = revived IDs awaiting answers, H = capability owners. Fleet accounting uses W=1,900, with 19,000 as the growth case; terminals and hosts scale independently.

Changed work Trigger and population Work and bound
Startup/degraded recovery inventory extraction; account-switch inventory Startup, degraded reconnect, explicit account move Same collector and ordering as base, moved into terminal-provider-snapshot-pty-inventory.ts. One traversal of terminal tabs, bindings, layouts and reconnect IDs: O(inventory). No new per-write inventory or startup wait.
Capability synchronization and retained live-ID set PTY membership change or existing unknown-capability deadline Adds one O(T) retained set during an already O(T) synchronization. Removes answered retry debt. Stable inventory with no retry debt still returns before scanning.
Revived capability re-ask Spawn/attach of an inventory ID whose cached answer is false Two O(1) admission checks; one shared retry owner; batches of at most 512 IDs, serially awaited; eight attempts per admitted ID. Later arrivals do not reset older IDs’ allowances.
Capability publication/version bump Newly authoritative revived answers Publishes only when at least one awaited ID becomes true. Carries changed IDs into parking invalidation. False, null and already-answered entries do not produce a new capability revision here.
Settled activation-spawn checks Manual park or existing automatic workspace/tab parking evaluation Only flagged, non-remote activation-spawn candidates reach the new check. O(pᵢ) live-ID/binding/tree validation; missing panes and restored terminal-chat readers remain ineligible. Workspace passes retain their dirty-workspace gate.
Layout release eligibility Park/reveal, local membership/group changes, dialog presence Selector reads two addressed values. The memoized eligibility walk is O(tᵢ+gᵢ), behind the release gate. Unrelated title/status changes do not rerun that walk.
Layout and drop-layer release Hidden, ordinarily parked, eligible workspace Removes that workspace’s group layout, strips and drop layer. Force-parked surfaces, browser-bearing layouts, simulators, active editor views and empty landing groups retain their gates. Terminal/chat overlays remain separate owners.
Scroll memory Strip mount, scroll, resize while restoration is pending, unmount O(1) offset bookkeeping per scroll. At most one pending resize observer per strip. Saved offset/tab ID is bounded by open groups; listener and observer disconnect on unmount.
Capability holds/cache retention Strip cleanup, return, group removal, capability load/publication One owner-key hold per released group, shared owner counts, constant-time lookups. Cache pruning/trimming visits cached owners only on loads/publications; no store-write scan or new timer.
Agent observation memory Group’s launch surface first observes a host; layout remount Reuses the group’s observed-host set. Group lookup occurs through memoization, not every render. Prevents remount-triggered remote refreshes. Three production group registries total.
Quick-command editor presence First dialog opens / last closes in one workspace O(1) count update plus that workspace’s listeners. Intermediate split-dialog opens/closes do not notify. Counts and listeners disappear on cleanup.
Deferred admission and overlay gates Active workspace’s existing idle-admission pass Filters that workspace’s tabs, including O(pᵢ) binding checks where needed. At most four admitted deferred siblings plus a terminal drained pass for a fixed eligible plan. Over-cap plans fail the existing eligibility gate before this work.
Drained restriction propagation Restriction widening/pruning; workspace render One WeakSet lookup/add per replacement, one lookup per rendered surface. No store subscription; obsolete restriction identities are weakly held.

The parking safety chain remains intact: settled-spawn status alone does not authorize unmounting. Existing pane coverage, restore-policy, provider capability, capture, portal, measurement and cooldown gates still apply.

Listener census and rates

Let S be actual store writes/second. It cannot be measured under the requested read-only scope. The examples below use S=2/s to represent hook status arriving more than once per second, and S=100/s as a burst illustration—not a claimed production rate.

Listener/selector Every head consumer and multiplicity Idle and loaded rate
New layout-membership selector WorktreeSplitSurface, once per mounted workspace surface: M At quiet S=0: zero callbacks. At M=1,900: 3,800 selector evaluations/s at S=2, 190,000 at S=100; 10× population gives 38,000 and 1.9M. Each performs two keyed reads and a shallow comparison, with no collection walk or IPC.
New quick-command presence subscription WorktreeSplitSurface, M listeners partitioned by workspace. Producer: TabBarQuickCommandsButton per mounted group Zero notifications from store/status writes. First-open/last-close notifies only that workspace’s surface listeners—normally one—not all 1,900.
New group-retirement subscription One store observer serving scroll memory, Windows capability holds and observed agent targets At S=2: two reference checks/s total; at S=100: 100. Unchanged group-map identity exits immediately. Addressed activation visits only named workspaces and their remembered groups.
New scroll listener / conditional ResizeObserver TabBar through useTabStripScrollMemory, once per mounted strip Zero autonomous idle callbacks. One constant-time assignment per delivered scroll event; resize callbacks only while a saved offset waits for nonzero width. Both clean up. Released strips have neither.
Windows capability subscription Eight direct production call sites plus two local-wrapper call sites, listed below; one registration per enabled mounted invocation No app-store/status-write notification. Publications notify only subscribers of that owner. Released strips replace subscriptions with holds. Local reprobes remain shared per owner.
Agent detection selectors Seven app-state selectors plus one host-entry subscription per mounted useDetectedAgents invocation; consumers listed below Seven selector checks × D × S, where D is mounted invocations; host-entry callbacks follow that host’s changes. These selectors predate the span. Releasing strips removes their invocations; the retained host set adds no subscription.
Provider capability revision One production hook consumer: useTerminalWorkspaceProjection → useTerminalProviderSnapshotCapability One revision listener per terminal controller, not per terminal/workspace. New revived publications occur on real true answers, not hook-status writes.
Parking invalidation downstream of capability publication One addressed listener in useTerminalParkingWorkspaceChanges; two workspace-scoped registrations per terminal overlay through cold parking and watcher synchronization Changed PTYs route through existing reverse indexes to their affected workspaces. No newly added all-workspace listener. Existing parking subscriptions remain after layout release.
Manual parking event Existing single listener in useManualTerminalWorktreeParking, called by useTerminalParkingFoundation Zero at idle; one addressed workspace evaluation per manual request. The listener count is unchanged.

Windows capability consumers at head are useTabBarRuntimeModel, useActiveProjectSkillRuntime, WindowsTerminalStep, WslCliRegistration, useSettingsNavigationMetadata, useSettingsTerminalModel, useCodexSwitcherController, and ClaudeSwitcherForOwner; local-wrapper consumers are AgentSettingsDialog and the second capability invocation in useSettingsTerminalModel. Multiplicity includes every mounted use of those hooks; it is not ten global singleton listeners.

Agent detection’s non-menu consumers are runtime-target-selection, OrchestrationSkillAgentCoverage, and AgentLaunchSettingsCatalog. Menu consumers are:

  • useTabBarCreateMenuController, AgentMenuItems, useBotAgentChoices, and SplitPaneLandingAgents through useNewTabAgentMenuRows.
  • AgentSessionContinuationDialog, NewWorkspaceComposerModal, SourceControlActionAgentPicker, useRepositoryActionPickerInputs, useChecksPanelCommentResolution, useSourceControlActionAgentChoice, and AutomationAgentLaunchPicker through useAgentMenuObservation.

Only the tab-bar controller supplies the new persistent observation group. Other consumers retain mount-local behavior.

The new surface selector is measurable subscription overhead, but its body does not scale with inventory size. Conversely, released layouts remove their existing per-group subtree subscriptions and DOM observers. No measured net CPU claim is made.

Group retirement and writer provenance

Retirement’s reference gate and addressed traversal are installed once by the store-creation loop. Registry creation does not install additional subscriptions, and the module no longer imports the store.

For one local tab activation, tabActivationPatch uses replaceRecordEntries. Added retirement work is O(gᵢ + remembered entries in that workspace’s three registries), independent of 1,900 versus 19,000 other workspaces.

Writers without addressed group provenance are:

  • Initial empty/bootstrap state.
  • Full and scoped session hydration, explicitly marked hydration.
  • Imported workspace-layout frames, explicitly marked host-mirror-frame.
  • Host session snapshot application: withWorktreeEntry builds an unaddressed record, then the production store-patch funnel marks it host-mirror-frame.
  • Arbitrary replacement/reset writes, which correctly take the unknown fallback.

Local create, close, focus, move, drop, split, label, reconciliation, rename, teardown and editor-owner migration paths inspected use addressed replacements/drafts.

A full-resync fallback enumerates up to three remembered-workspace lists and compares the union’s buckets: at most 5,700 enumerated keys plus 1,900 bucket checks in the stated case; 57,000 plus 19,000 at 10×. Only changed buckets undergo group retirement. This is a bounded note: host mirrors can exercise it on real group changes, but equal groups preserve identity, so ordinary hook-status frames do not trigger it.

Timers and recovery comparison

The revived retry owner adds the only new timer mechanism.

Timer/path Base steady idle Head steady idle Transient bound
Revived re-ask scheduler, renderer 0 wakeups/s 0 wakeups/s after answer/exhaustion Eight scheduled passes for a fixed unresolved cohort; delays 0, 1, 2, 4, 8, 16, 30, 30 seconds, plus request time.
Existing one-second batch timeout, newly used by re-ask 0 for settled-false IDs 0 after settlement At most 8 × ceil(R/512) requests/timeouts for a fixed cohort. Successful requests cancel their timeout.
Main/daemon periodic timer from this change 0 0 None added. Main receives transient capability IPCs.
Existing admission idle callback / timeout fallback 0 after admission 0 after admission Finite admission/drained passes; no permanent loop.
Existing local Windows reprobe Settled usable answer: 0; unsettled owner eventually 1/300 s Same policy for remaining consumers Shared owner runner; last consumer leaving cancels it. Returning may restart bounded backoff if no other consumer retained the runner.

For 300 revived IDs, the fixed-cohort maximum is eight capability RPCs; for 3,000, 48. A 1,900-ID stress cohort needs at most 32; 19,000 IDs need at most 304. These are transient totals, not recurring rates.

Base’s cached false answer has no retry/recovery timer. Head’s exhaustion restores that same false state and deletes retry debt. Originally unknown IDs retain base’s slow recovery path. Explicit refresh remains available, and a later attach can re-ask a settled-false revived ID. No recovery path that base possessed was found removed. An already-armed synchronization timeout can perform a final no-op check after settlement; it cannot sustain periodic wakeups once retry debt is empty.

Returning strips and hidden overlays

The held-owner comparison compares the saved owner key with the newly resolved owner before enabling reuse. The hook also clears reuse after an owner change. Therefore:

  • Same owner: shared cached answer, matching base’s continuously mounted strip.
  • Different owner or new strip: ordinary 30-second TTL/in-flight-deduplicated load.
  • Shared publications still update mounted consumers. Holds prevent eviction of released strips’ answers.

Cache storage can exceed 32 for live subscribers/holds. Holds retire with groups; unused cached answers are pruned/trimmed on subsequent loads/publications. Owner-cache traversal is bounded lifecycle work, not status-write work.

Admission’s drained mark lets browser/emulator gates recognize completed warming even when unbound restored tabs remain deferred. Pruning/widening carries the mark; a fresh activation plan gets a fresh identity. Over-cap plans never reach the marking callback. Browser paint retention remains an independent override. The added per-render gate is one WeakSet lookup; no per-write traversal was added.

Regression classes touched

Class Disposition
No-op identities / unchanged publication Reviewed: equal presence does not notify; drained identity marks once; revived publication requires true changes.
Broad subscriptions / per-row collection derivation Reviewed: new selector uses addressed reads; eligibility walks occur outside the selector and are memoized. Existing retained-subtree subscriptions remain a pre-existing cost.
Polling / new idle wakeups Disproved for the new retry owner: finite attempts and zero settled wakeups/RPCs.
Expensive work past a gate Reviewed: newly eligible terminals still require existing restoration/coverage gates. Main capability inspection uses provider lookup and session-set membership, not session listing, filesystem or SQL.
Hidden/per-instance work Improved: released strips stop their listeners/probes; host observations survive remount. Over-cap overlay admission remains restricted.
Whole snapshot / notification amplification New answers publish addressed PTY IDs. Existing global capability revision has one controller consumer; existing inventory rebuilds remain lifecycle-triggered.
Entity state outliving owner Three module-level registries, entries retired with groups/workspaces; DOM listeners clean up; restriction marks are weak. Observed-host history matches base’s group-lifetime observation behavior.
Hot-path rescans No new fleet inventory walk on title/status events. Full-resync retirement and capability-cache traversal are bounded notes above.
Fan-out / retry queues Shared re-ask pass, 512-ID batches, eight attempts per ID; no per-pane retry timer. Timeout races do not cancel the underlying request, as in base’s helper.
Eager startup imports Collector extraction and observer relocation inspected; no new SDK/native adapter startup dependency. The import cycle is removed.
Capture/persistence amplification Existing capture episodes are reused for newly parkable terminals; no new periodic serialization or full-state persistence mechanism.

Six questions

  1. Unused work before the skip gate? Reviewed. Ordinary status writes reach constant-time selector/reference checks; layout inventories, pane validation and capability requests retain specific admission gates.
  2. Ownership multiplying work? Reviewed. Three registries share one retirement listener; quick-command notifications are workspace-local; Windows loads/reprobes share host ownership; capability revision has one controller consumer.
  3. Which thread/storage pays? Renderer pays projections, pane checks and bookkeeping. Main capability IPC performs bounded provider/session lookups. No new synchronous filesystem/SQLite path was found.
  4. What grows, and does retry advance? State follows open groups, distinct observed hosts and PTY inventory/cohorts. Attempts advance per ID and exhaust independently; admission advances one eligible sibling or marks its restriction drained.
  5. What changes by host? Windows/local, environment, SSH and web routes were traced statically. Different-owner returns retain TTL loading; web false answers settle; exact remote parking-policy gates remain. Native/transport timings were not assessed.
  6. Does obsolete work stop? Reviewed cleanup for released strips, group removal, quick-command dialogs, restriction identities and retry settlement. Actual post-GC resource release and visible restoration remain unmeasured.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status for 2298323

Problem: every visited workspace stayed mounted for the session (xterms, listeners, tab-group layout), so renderer memory grew with workspaces visited.

User-facing change: none on screen. Hidden workspaces whose terminals are parked release their terminal views and layout, and come back in the same state on return.

Reviews on the final code (3ad9999e879a; the head adds only a ratchet baseline row)

  • Blinded regression audit (Codex): SAFE. It again confirmed that a terminal's Find query is already lost whenever a terminal parks on main, so that point is pre-existing.
  • Fresh perf reviewer (full perf-scan): clean, see the report above.
  • Fresh Claude review: PASS (no P0/P1).
  • remote-check (pnpm check:changed, related tests) and GitHub CI pass on the head.

Fixed since the last status

  • Released strips' capability holds, tab-strip scroll offsets and agent detection's observed hosts now live in one per-tab-group store that is cleared when the group or workspace is removed. Its store subscription visits only the workspaces a write addressed.
  • A remounted tab bar no longer forces a fresh agent-host scan, and a returning strip reuses its held shell-capability answer only on the same host (a different host takes the normal TTL load).
  • A hidden workspace whose only deferred tabs are unbound restored tabs keeps its simulator and browser overlays mounted, as main does once warm-up drains. Every write to the deferred-mount restriction carries that state (a reviewer enumerated all of them).
  • Closing a quick-command dialog now re-checks release for its hidden workspace.
  • The per-group store's cleanup subscription is installed by the store at creation, which removes an import cycle CI caught.

Mount effects in TabBar / TabGroupPanel, decided one by one

  • Survive a remount: shell capabilities (held answer), agent detection (observed hosts per group), strip scroll offset.
  • DOM-local with cleanup, cheap to redo: overflow navigation, drag-scroll, pointer activation, hover card, scroll indicator, menu fit, sortable rename, focus return, context-menu listeners, item-actions layout.
  • Shared store or IPC subscriptions, cheap: chat names (shared observer), recent-tab switcher listener, quick-commands shortcut.
  • Gated off while hidden: runtime file list (menu open or landing page only), auto-close preference (open only), naming-failure probe (only with a naming failure), session drop layer (visible only). Landing pages are never released.

Intended, recorded with reviewers' agreement

  • Manual "Park terminals" refuses a restored chat-view terminal (it would lose its reader position) and a restored split with an unbound pane (nothing to park). Reviewer: AGREE.
  • Hovering a released workspace remounts its tab bars for the prewarm lease, which is how main runs all the time. Keeping it released would move that mount onto the reveal frame. Claude reviewer: AGREE to ship and track it as a follow-up (cover sweeping the pointer across many released rows).
  • Restored tabs with no PTY start their shell when opened instead of in idle warm-up (Activating a worktree respawns the agent command in every dead tab, without a limit; hitting the container PID limit then kills the terminal daemon with no log #39166).
  • Claude suggested deleting released-layout-eligibility.test.ts as a UI test. It is kept: it guards the open quick-command dialog's unsaved text (data loss), which the test rules allow.

Notes (below the blocker bar)

  • A keyboard switch to a released workspace mounts its tab bars on the reveal frame (no hover prewarm). The switch-back measurement below includes that.
  • A workspace left on an editor tab, or holding a never-opened restored tab, still stays mounted.

Verified
Benchmark: head=2298323fd96acb442ed542eb539abff2751b4c1d gate=PASS name=workspace-unmount-soak corpus=fleet seed (1,800 worktrees + 100 folders, 1,800 chats, 200 terminals), Linux, 150 visits x 2 streamed turns, GC'd. main 2284cb2 vs head, build tree identical to the head's. xterms 30 -> 0, mounted layouts 150 -> 5, DOM listeners 17,578 -> 7,995, renderer heap 871 -> 758 MB, renderer PSS 3,165 -> 2,913 MB, early-workspace switch-back median 1,004 -> 205 ms (recent workspaces 204 ms).

Restore on a released workspace: the running shell loop kept all 213 lines (ready in 590 ms), and the unsent chat draft was kept. An earlier variant that kept the tab-group chrome mounted and released only terminal views kept about a third of the heap and PSS saving, so the layout release stays.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Findings

No must-fix regression found in 2284cb2d04f0de86c695f1f5aa584d5c48ee1f18..2298323fd96acb442ed542eb539abff2751b4c1d under this round’s bar.

The previous different-host capability finding is resolved. Same-owner returns reuse the shared answer; different-owner returns use the normal TTL load. The latest commit installs group-state retirement once through the store’s installer list without changing its retirement algorithm.

This is a source-based review. No files were edited, and no builds, typechecks, tests, benchmarks, or application runs were performed. Counts below are derived from production code, not measured CPU, latency, or heap results.

Coverage and workload

Reviewed all 43 changed files, including test assertions and compiler-baseline changes, plus unchanged consumers, publishers, store writers, parking watchers, capability readers, and main-process capability handlers.

For pricing:

  • W = 1,900 workspaces; growth case 19,000.
  • M ≤ W mounted workspace surfaces; G open groups; B mounted strips.
  • R accepted app-store writes/s. Examples use R = 2 and 20; actual runtime cadence was not measured. Hook updates above 1/s contribute to R.
  • P live PTY IDs; Tᵢ tabs and Gᵢ groups in the affected workspace; Q pending unknown capability IDs.
Changed work Trigger and population Work, ownership, and bound
Layout release and restore: TerminalWorktreeSplitSurface, released-layout-eligibility, WorkspacePaneOverlayLayers Parking/visibility changes, this workspace’s tab count or groups, first dialog open/last close Renderer: two keyed store reads per selector evaluation. Eligibility builds a local tab index and visits local groups: O(Tᵢ + Gᵢ), memoized outside the selector and behind the parking gate. Release removes the layout and drop layer; return reconstructs that workspace’s groups. No fleet scan inside each selector.
Settled restored-terminal eligibility: settled-activation-spawn, automatic/manual/tab parking callers Existing dirty-workspace parking passes, tab parking effects, explicit manual park Only tabs with applicable pending-spawn metadata inspect live bindings and tree leaves. O(PTYsᵢ + leavesᵢ) per evaluated tab; no RPC or global inventory. Workspace eligibility can evaluate it twice per pass. Missing bindings, pending startup, restore policy, and watcher coverage still prevent unsafe parking.
Activation admission and restriction propagation One active workspace’s eligible deferral plan Existing admission cap remains four deferred tabs. Each pass adds local filtering, including saved leaf bindings for candidate unbound tabs. At most four admissions plus a drain-detection pass for a stable plan.
Overlay drain state Admission discovers only unbound restored tabs; restriction widening/pruning; surface render WeakSet operations are O(1) per changed restriction/rendered surface. New plans get new identities. Marks retain no restriction themselves. No store subscription or timer added here.
Group-scoped state Strip mount/unmount, host observation, group/workspace removal Exactly three production registries: capability holds, scroll offsets, observed agent targets. At most one value per open group per registry. set checks only that workspace’s groups. Removal retires owned entries synchronously.
Scroll memory Strip scroll, remount, pending hidden-prewarm resize, cleanup One scalar offset update per scroll event; one restore per saved offset. Pending ResizeObserver disconnects after application or cleanup. No frame loop, polling, or store write on scrolling.
Agent observation persistence Tab-bar launch surface observes a host or remounts One memoized group-state lookup, then Set membership/addition. Existing inventories, owner keys, explicit refresh, reconnect and pairing recovery remain. Remount no longer counts as a fresh launch surface. Other callers retain mount-local sets.
Windows capability holds/cache Enabled consumer mount, owner transition, capability publication, strip release/return Cache/in-flight sharing remains per owner. Same-owner return performs no mount load when a cached answer exists. Different-owner/new mounts retain the 30-second TTL load. Cache pruning/trim visits cached owners on loads/publications, not on hook-status writes. Protected owners are bounded by enabled consumers and released open groups; remaining cache allowance is 32.
Revived capability re-ask Successful spawn/bind of an inventory ID previously settled false Ordinary binds add constant Map/Set checks. Eligible IDs join one renderer queue, with sequential batches of 512 and eight attempts per ID. Later binds do not replenish another ID’s attempts. Queue size is bounded by outstanding eligible inventory IDs.
Capability bookkeeping/publication Capability answer, inventory synchronization, reset One additional live-ID Set of O(P); reset advances one scalar epoch. Revived answers process their returned batch and refresh the existing unknown deadline minimum, O(Q). Only newly authoritative IDs publish; false/unknown answers do not bump the revision.
Startup/recovery inventory extraction Startup, degraded reconnect, explicit account switch The collector’s traversal and startup ordering are unchanged: O(W + tabs + bindings) and deduplicated IDs. Moving it into the inventory module adds no migration, persistence, or per-write scan.
IPC binding wrappers Successful spawn/connect/bind Replace the existing bound-session call with a wrapper that preserves it and conditionally requests recovery. No PTY-output, input, or status-event RPC added.
Observer installation Store module initialization One installer-list entry, called once by store/index.ts:183. The registry now imports the store type only; registry creation and set no longer install listeners.
Compiler baseline/type options Compilation/module import One bailout-baseline entry removed; observation options are type-only. No runtime loop or heavy startup dependency introduced.

The newly reached main-process capability handler validates at most 512 IDs and returns metadata. It does not capture scrollback, list every session, read history, or spawn a child process. Local authority ultimately checks adapter capability plus active-session membership (src/main/ipc/pty/ipc/inspect.ts:54, src/main/daemon/providers/adapter/daemon-pty-runtime-state.ts:270).

Subscription, selector, and listener census

Path and every production consumer at head Listener population Idle and load rate
Quick-command presence → WorktreeSplitSurface, created only by TerminalSplitWorkspaceSurfaces Exactly one external-store listener per mounted workspace surface: M, including released layouts. Sole producer: TabBarQuickCommandsButton, rendered by TabGroupPanel. Zero notifications/s without first-open/last-close transitions. Hook/status/store writes notify zero presence listeners. Each relevant transition notifies only listeners for that workspace—normally one, not M. At M=1,900 or 19,000, unrelated writes still cause zero notifications.
Group-state retirement → the three registries listed above One app-store subscription, not one per registry/group/workspace R callbacks/s; zero self-generated wakeups. Unchanged group-map identity costs one comparison. At R=2/20, two/twenty comparisons/s regardless of 1,900 or 19,000 workspaces. Addressed activation examines one workspace, its Gᵢ groups, and three registries.
New workspace release selector → WorktreeSplitSurface One Zustand selector per mounted surface: M M×R evaluations/s: 3,800/38,000 at 1,900 surfaces and R=2/20; 38,000/380,000 at 19,000. Each performs keyed reads and shallow comparison of two fields. Unrelated status writes cause no eligibility scan or resulting render. Released group trees remove their existing strip/panel subscriptions.
Scroll listener/ResizeObserver → TabBar One passive scroll listener per mounted strip with a group and element; at most one observer per pending saved-offset restore Zero callbacks at stable idle or merely because the app store writes. Load follows actual scrolling/resizing of those elements. Both listeners and observers are removed on cleanup. Production strip hosts are TabGroupPanel, TerminalTitlebarTabs, and FloatingTerminalPanelSurface.
Windows capability subscription One subscriber per enabled hook instance, bucketed by owner Publication visits only that owner’s subscribers. No callback on unrelated app-store writes. Released strips unsubscribe and leave scalar owner holds. Existing local reprobe runners remain shared per owner, with one shared focus listener.

Windows-hook census, including unchanged consumers: use-tab-bar-runtime-model, useActiveProjectSkillRuntime, WindowsTerminalStep, WslCliRegistration, useSettingsNavigationMetadata, use-settings-terminal-model, use-codex-switcher-controller, and ClaudeSwitcherForOwner; the local wrapper is additionally consumed by use-settings-terminal-model and AgentSettingsDialog. That is ten production call sites, with multiplicity determined by mounted components.

useDetectedAgents retains seven app-view store selectors and one host-status selector per mounted hook; this change adds no selector. Direct consumers are runtime-target-selection, OrchestrationSkillAgentCoverage, AgentLaunchSettingsCatalog, and useAgentMenuObservation. The latter is reached through:

  • The tab-bar controller, AgentMenuItems, split landing agents, and bot agent choices.
  • New-workspace composer and session-continuation dialogs.
  • Source-control settings, repository action picker, sidebar action picker, and checks-comment resolution.
  • Automation authoring.

Their existing selector cadence remains store/status driven. Only the tab-bar controller supplies the persistent observation group. Hidden acquisition remains gated, and released strips remove their hook instances.

Capability-publication census: subscribeTerminalProviderSnapshotCapability has one production hook consumer, useTerminalProviderSnapshotCapability, called once by the terminal workspace projection. Its revision reaches the existing parking and watcher effects. Before that notification, addressed invalidation resolves changed PTYs to affected workspaces. Those workspaces have two parking-input subscriptions per mounted terminal overlay, and the terminal controller has two addressed listeners—parking and watcher effects. A revived batch publishes once only when it makes IDs authoritative; no per-status revision bump was introduced.

Group-map writers and retirement pricing

The addressed path is verified in tabs-focus-actions.ts:52: ordinary activation uses replaceRecordEntries. Create, close, move, drop, split, label, preview, reconciliation, rename and teardown paths similarly use addressed replacements/drafts.

The non-addressed/full-resync producers found are:

Producer Why retirement falls back Cadence/bound
Full/scoped hydrateTabsSession Explicit hydration resync Startup or explicit hydration
buildLayoutFrameStorePatch Explicit host-mirror-frame resync Imported structural frames; main-layout-owner path remains gated
Web-session snapshot application withWorktreeEntry copies the record; the publication funnel marks a host-mirror resync Only when group content changes; sameGroups compares ownership, selection, order and MRU, so status-only snapshots preserve identity
Initial state, arbitrary raw replacement/reset No addressed predecessor Bootstrap/reset or externally supplied replacement
Provenance reorder/unknown-chain fallback Conservative reader fallback Exceptional transition; chain traversal is capped at 64

A resync enumerates remembered workspace keys from three registries: at most 3W inputs, deduplicated to W workspace comparisons, then group retirement only where the workspace group-array identity changed. At 1,900 remembered workspaces that is up to 5,700 collected keys and 1,900 comparisons; at 19,000, 57,000 and 19,000. This fallback does not occur on ordinary tab activation or hook-status writes.

The latest installation move preserves those counts and disposal callbacks. Production has one installer invocation; the exported function is not independently idempotent, but no second production caller exists.

Timers and idle wakeups

Timer/path Base steady idle, per process Head steady idle, per process Transient work
New revived re-ask timer Renderer: 0/s for settled-false IDs Renderer: 0/s after answer or exhaustion Initial immediate pass, then 1/2/4/8/16/30/30-second delays: eight attempts per ID, about 91 seconds of delays plus request time
Capability request timeout, reused by revived requests No requests for settled-false IDs 0/s after settlement Existing one-second timeout per attempted batch; cleared on completion
Existing ordinary unknown-capability retry After its grace, approximately 1/300 callback/s when unknown IDs remain Same recovery schedule for originally unknown IDs Revived settlement removes its deadlines; an already armed ordinary timer can make one final no-op visit
Existing local Windows reprobe 0/s for settled answers; approximately 1/300 timer wakeup/s per unsettled owner after backoff Same while an enabled consumer remains; final unsubscribe stops its runner Return can restart a runner if no consumer remained; no new polling mechanism
Existing activation idle admission 0/s after a plan drains 0/s after a plan drains At most four admissions plus drain detection; no recurring idle schedule

For a simultaneous cohort of P revived IDs, the new runner performs at most 8×ceil(P/512) batch calls: 32 at 1,900 IDs, 304 at 19,000. Per-ID attempts bound staggered cohorts as well; later arrivals cannot keep older IDs retrying indefinitely. Logical requests are serialized. The existing timeout does not cancel underlying IPC, so it is not proof of transport cancellation.

Both requested base comparisons hold:

  1. Originally false IDs return to zero steady-idle timers/RPCs after recovery ends.
  2. Originally unknown IDs retain base’s slow recovery path. Exhausting a formerly false ID returns it to base’s own mounted, settled-false state; a later attach can try again.

Retention and behavior controls

  • Same-owner capability reuse is guarded by the saved owner comparison in windows-terminal-capability-holds.ts:34 and the mount decision in use-tab-bar-runtime-model.ts:148. An owner change also clears reuse within the hook. Different-owner and new mounts retain TTL loading.
  • Drained restrictions allow emulator/browser overlay retention where base’s completed admission removed the restriction. Pruning/widening carries the mark; a new plan does not. Over-cap plans remain ineligible for admission and retain base’s hidden-overlay gate. Visible workspaces and browser guests requiring paint retain their existing exceptions.
  • Layout eligibility excludes simulator tabs, active editor/non-overlay views, empty groups, quick-command editors and force-parked surfaces. Structured-chat overlays remain mounted.
  • Restored parking still requires complete bindings and watcher coverage. Pending restored terminal-as-chat layouts remain exempt, preserving reader state.
  • Scalar group state retires with group/workspace removal. Observed-host sets retain the same distinct-host history that base’s session-long mounted strips retained.

Regression classes touched

Class Disposition
Broad selectors / per-row derivation per write Matched and bounded: new selector is keyed and constant work; local eligibility scanning is outside it
Publication/version churn Matched and disproved: revived publication requires newly authoritative IDs and names those IDs
Whole snapshot / notification amplification Matched and bounded: batches ≤512, one capability publication per changed batch, addressed parking invalidation
Fixed retries / steady-idle wakeups Matched and disproved as a permanent regression: per-ID exhaustion returns to zero; original unknown recovery remains
Hidden-owner/per-instance work Improved: released strips lose subscriptions/listeners; remount avoids duplicate host acquisition
Per-entity lifetime leaks Matched and bounded by open groups; observers/listeners clean up; drain marks use WeakSet
Hot-path rescans Matched and bounded: ordinary retirement visits addressed workspaces; capability inventory selector keeps its existing incremental route
Cache identity/freshness Previous finding resolved; same-owner reuse and different-owner TTL paths verified
Fan-out/queues and cancellation Eight attempts per ID, batches of 512, serialized logical requests; underlying IPC cancellation remains pre-existing
Expensive work newly reachable past a gate Newly reached capability query is bounded metadata lookup; parking retains restore/coverage gates
Eager startup imports No heavy SDK/native/storage dependency added; extracted inventory module is pure
Store identity/no-op writes Drain revision advances only on first marking; restriction propagation adds no app-store write

Pre-existing costs retained in this span include Zustand’s selector dispatch per accepted store write, whole-inventory synchronization on membership/retry work, deadline-minimum scans, and conservative full-resync retirement. None becomes a new fleet scan on each hook-status update.

Six scan questions

  1. Unused work before the gate — reviewed. Eligibility scanning follows the release gate; presence notifications are workspace addressed; agent acquisition remains activity gated.
  2. Ownership multiplication — reviewed. Three registries share one retirement listener; host loads remain owner shared; released strips unsubscribe.
  3. Thread/storage cost — reviewed. New derivations run in renderer; newly called main capability handling reads bounded metadata. No new filesystem, SQLite, history serialization, or subprocess path.
  4. Growth and progress — reviewed. Group values track open owners; admission advances or marks drained; revived attempts expire independently. Resync costs are explicitly priced above.
  5. Execution-host differences — reviewed statically. Local, Windows/WSL, SSH, paired-runtime and web routes were traced. Different-owner TTL behavior is restored. No platform execution or latency evidence was collected.
  6. Obsolete-work cleanup — reviewed. Strip listeners/observers unsubscribe, group values retire, drain marks are weak, retries settle, and retained overlays preserve base gates.

Residual validation gaps are runtime switch-frame latency, actual heap/xterm release, native Windows/SSH timing, and rendered restore behavior. Added test assertions were inspected but not executed. The referenced terminal-session-reliability skill was unavailable in the searched skill roots; relevant binding, capture, coverage and retention code was inspected directly.

@brennanb2025

brennanb2025 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Review status for 2298323

Problem: every visited workspace stayed mounted for the session (xterms, listeners, tab-group layout), so renderer memory grew with workspaces visited.

User-facing change: none on screen. Hidden workspaces whose terminals are parked release their terminal views and layout, and come back in the same state on return.

Reviews on the final code (3ad9999e879a; the head adds only a ratchet baseline row)

  • Blinded regression audit (Codex): SAFE. It again confirmed that a terminal's Find query is already lost whenever a terminal parks on main, so that point is pre-existing.
  • Fresh perf reviewer (full perf-scan): clean, see the latest report above (it covers the subscribe surface too).
  • Fresh Claude review: PASS (no P0/P1).
  • remote-check (pnpm check:changed, related tests) and GitHub CI pass on the head.

Fixed since the last status

  • Released strips' capability holds, tab-strip scroll offsets and agent detection's observed hosts now live in one per-tab-group store that is cleared when the group or workspace is removed. Its store subscription visits only the workspaces a write addressed.
  • A remounted tab bar no longer forces a fresh agent-host scan, and a returning strip reuses its held shell-capability answer only on the same host (a different host takes the normal TTL load).
  • A hidden workspace whose only deferred tabs are unbound restored tabs keeps its simulator and browser overlays mounted, as main does once warm-up drains. Every write to the deferred-mount restriction carries that state (a reviewer enumerated all of them).
  • Closing a quick-command dialog now re-checks release for its hidden workspace.
  • The per-group store's cleanup subscription is installed by the store at creation, which removes an import cycle CI caught.

Mount effects in TabBar / TabGroupPanel, decided one by one

  • Survive a remount: shell capabilities (held answer), agent detection (observed hosts per group), strip scroll offset.
  • DOM-local with cleanup, cheap to redo: overflow navigation, drag-scroll, pointer activation, hover card, scroll indicator, menu fit, sortable rename, focus return, context-menu listeners, item-actions layout.
  • Shared store or IPC subscriptions, cheap: chat names (shared observer), recent-tab switcher listener, quick-commands shortcut.
  • Gated off while hidden: runtime file list (menu open or landing page only), auto-close preference (open only), naming-failure probe (only with a naming failure), session drop layer (visible only). Landing pages are never released.

Intended, recorded with reviewers' agreement

  • Manual "Park terminals" refuses a restored chat-view terminal (it would lose its reader position) and a restored split with an unbound pane (nothing to park). Reviewer: AGREE.
  • Hovering a released workspace remounts its tab bars for the prewarm lease, which is how main runs all the time. Keeping it released would move that mount onto the reveal frame. Claude reviewer: AGREE to ship and track it as a follow-up (cover sweeping the pointer across many released rows).
  • Restored tabs with no PTY start their shell when opened instead of in idle warm-up (Activating a worktree respawns the agent command in every dead tab, without a limit; hitting the container PID limit then kills the terminal daemon with no log #39166).
  • Claude suggested deleting released-layout-eligibility.test.ts as a UI test. It is kept: it guards the open quick-command dialog's unsaved text (data loss), which the test rules allow.

Notes (below the blocker bar)

  • A keyboard switch to a released workspace mounts its tab bars on the reveal frame (no hover prewarm). The switch-back measurement below includes that.
  • A workspace left on an editor tab, or holding a never-opened restored tab, still stays mounted.

Verified
Benchmark: head=2298323fd96acb442ed542eb539abff2751b4c1d gate=PASS name=workspace-unmount-soak corpus=fleet seed (1,800 worktrees + 100 folders, 1,800 chats, 200 terminals), Linux, 150 visits x 2 streamed turns, GC'd. main 2284cb2 vs head, build tree identical to the head's. xterms 30 -> 0, mounted layouts 150 -> 5, DOM listeners 17,578 -> 7,995, renderer heap 871 -> 758 MB, renderer PSS 3,165 -> 2,913 MB, early-workspace switch-back median 1,004 -> 205 ms (recent workspaces 204 ms).

Restore on a released workspace: the running shell loop kept all 213 lines (ready in 590 ms), and the unsent chat draft was kept. An earlier variant that kept the tab-group chrome mounted and released only terminal views kept about a third of the heap and PSS saving, so the layout release stays.

…e-surface-release

# Conflicts:
#	src/renderer/src/components/tab-bar/TabBar.tsx
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Findings

No P0/P1 regression found against 38a9a02bbaf64f3cf126b74a30162e35f9b6c8cb at head 4ff05ce42dd28d70a631d2759c7ee2e3e9eebdcb, under this round’s blocking bar.

This is a source-based assessment. No files were edited; no builds, typechecks, test suites, or runtime profiling were run. Counts below are derived from production code, not measured CPU, latency, or heap results.

Coverage and work bounds

Population notation: W = mounted workspace surfaces, G = open groups, Tᵥ/Lᵥ = tabs/pane bindings in the affected workspace, P = inventoried PTYs, H = capability host owners, S = actual store writes/second. The requested large case uses W = 1,900; growth case W = 19,000. Terminal and host populations are scaled separately.

Changed work Trigger → population Bound and disposition
Release hidden layout and drop layer Parking verdict, relevant group/count change, or dialog presence → affected workspace TerminalWorktreeSplitSurface.tsx:55 adds a constant-size selector. Eligibility scans Tᵥ tabs and groups only after the release gate opens and memo inputs change. No fleet scan on hook-status writes. Browser pages, simulator tabs, empty landing groups, unsupported active views, force parks, and open quick-command editors prevent release.
Recognize completed restored spawns Existing manual/automatic parking evaluation → candidate terminal tabs settled-activation-spawn.ts:5 visits that tab’s live IDs, topology leaves, and saved bindings: O(Lᵥ), only when pending-spawn metadata otherwise prevents parking. Every pane must be bound and live; terminal-as-chat remains mounted. Dirty-workspace parking and existing retention deadlines remain the owners.
Re-ask revived snapshot capability Spawn/attach → a live inventory ID previously answered false O(1) admission; shared retry owner; batches ≤512 IDs; eight attempts per admitted ID. For P=300/3,000 simultaneous IDs: ≤8/48 batch calls across eight fully unanswered passes. Adversarial P=1,900/19,000: ≤32/304. Separate binds cannot extend an older ID’s attempt allowance.
Publish capability changes A revived answer becomes authoritative → changed PTY owners Boolean false and unanswered exhaustion publish no capability gain. True answers publish changed IDs once per answer batch. Indexed invalidation addresses their workspaces; the existing revision channel additionally notifies one terminal controller.
Startup/degraded recovery inventory Startup, degraded recovery, account-switch inventory → saved terminal catalog Inventory implementation was moved unchanged. It visits saved tabs, live bindings, reconnect IDs, and layout bindings once per existing caller. No new startup await, migration, persistence write, or recurring inventory was added. The bound-PTY selector’s change is type-import routing.
Preserve strip capability ownership Strip unmount/remount → one group and its host Hold lookup/count changes are O(1); storing checks that workspace’s open groups. Holds retire with groups. Cache capacity is ordinary entries plus live held/subscribed owners; host count, rather than workspace count, determines retained capability answers. Cache maintenance is O(H) per load/publication, not per store/status write.
Preserve agent observations Launch-surface acquisition/remount → group and encountered remote targets Existing per-mount observed-host set becomes per-open-group state. Same-group return does not become a new remote observation/probe. Unknown inventory, reconnect/contact changes, re-pair, and explicit refresh retain their existing recovery paths.
Deferred admission and overlay gates Active-workspace admission/revision → its deferred plan Admission remains capped at four deferred tabs. Each pass scans that workspace’s tabs/bindings; it admits one warmable tab or marks the restriction drained. The mark changes revision once; a subsequent confirming pass stops. No permanent polling.
Scroll restoration and condensing Strip remount, scroll, or hidden-prewarm resize → mounted group One saved offset/active ID per group; one new constant-time scroll handler. Pending restoration has at most one ResizeObserver and disconnects after application or unmount. Remount replanning is O(tabs in that strip), with no host probe or fleet inventory.

The added lastSynchronizedLivePtyIdSet retains O(P) IDs and is replaced on synchronization/reset. It does not accumulate visited-workspace snapshots.

Subscription, selector, and listener census

Rates are source-derived. A quiet store has S=0; background status can make S>0 even when the user is idle. Since runtime sampling was prohibited, actual S is not claimed. At S=2 writes/s—a concrete load above one status update/s—the following multiplications apply.

Channel Every production consumer at head Idle/load rate and lifetime
Quick-command presence One subscription per mounted WorktreeSplitSurface, including released layouts. Sole reader hook call: TerminalWorktreeSplitSurface.tsx:64. Producer: each TabBarQuickCommandsButton; imperative eligibility also reads presence without subscribing. W listeners: 1,900/19,000. Zero calls per store write or hook-status event. First open and last close notify only that workspace’s bucket, ordinarily one listener. Additional split-group dialogs only change the count. Cleanup removes empty buckets and editor counts.
Group-state retirement One store subscription, shared by exactly three production registries: strip offsets, Windows capability holds, and observed agent targets S callbacks/s: 2 at S=2, independent of W. Unchanged groups cost a reference comparison. Addressed activation visits one workspace: its group IDs plus at most three registries’ saved entries there. Retained entries are bounded by open groups, not historical visits.
Surface eligibility selector One useShallow subscription per mounted WorktreeSplitSurface W×S constant-size selector evaluations: 3,800/s at W=1,900, S=2; 38,000/s at 10× W. Unrelated writes return equal projections: no eligibility tab walk or component commit from this selector.
Snapshot capability revision and PTY selector useTerminalWorkspaceProjection → useTerminalProviderSnapshotCapability: one revision listener and one bound-PTY selector per terminal controller No capability notification from status-only writes. Real capability batches notify the controller once. Its existing parent projection can visit mounted surfaces; this publication fanout predates the span. PTY-selector membership work remains addressed/cached as on base.
Parking invalidation downstream Two existing global addressed listeners per terminal controller: parking pass and watcher effects. Two existing workspace listeners per terminal overlay: cold-parking inputs and watcher synchronization A changed PTY batch invalidates only indexed affected workspaces. For D affected mounted overlays, approximately 2D workspace callbacks plus two addressed callbacks per dirty workspace; no new W-wide workspace-listener broadcast.
Windows capability publication Direct hook consumers: tab-bar runtime model, WindowsTerminalStep, WslCliRegistration, settings navigation metadata, settings terminal model, Codex switcher controller, ClaudeSwitcherForOwner, and useActiveProjectSkillRuntime. Local-wrapper consumers: AgentSettingsDialog and settings terminal model One listener per enabled hook instance, bucketed by owner. No callbacks on unrelated store/status writes. Publication rate is that owner’s existing mount/TTL/refresh/reprobe rate × its mounted consumers. Released strips unsubscribe and retain a hold instead. One existing global focus listener serves reprobe runners; last-consumer cleanup removes it.
Agent-detection projections Direct callers: runtime-target selection, orchestration coverage, launch-settings catalog, and agent-menu observation. Menu callers: tab-bar create controller, split landing, AgentMenuItems, bot choices, continuation dialog, new-workspace composer, automation picker, global/repository/sidebar source-control pickers, and checks-comment resolution Existing seven app-state projections and one runtime-host-status projection per hook instance; the view-active read is contextual. No subscriptions were added by the observation-group change. Released layouts remove their mounted instances. Existing host/contact and inventory gates control acquisition.
Strip DOM/resize listeners New memory hook; existing overflow navigation, WindowedTabStrip, TabStripScrollIndicator, and condense hook New handler: one local assignment per scroll. Existing scroll consumers are navigation, indicator activity, optional indicator geometry, and windowing above its threshold. No cross-workspace dispatch. Restore emits one synthetic scroll; native scroll may follow. Resize observers are event-driven and disconnect on teardown.

store-observer-installers.ts:14 lists retirement once; store/index.ts:184 invokes that installer list once during singleton store creation. Moving installation removes the store value import from the registry module and preserves its retirement behavior.

Addressed versus resync group writes

Ordinary activation uses replaceRecordEntries in tabs-focus-actions.ts:52. Create, close, move, drop, drag-preview, label, group, reconciliation, lifecycle-removal, terminal-creation, and restored-editor updates likewise use addressed replacements/drafts.

The non-addressed production funnels are:

  • Full/scoped hydrateTabsSession: explicitly marked hydration.
  • Main layout-frame imports through buildLayoutFrameStorePatch: explicitly marked host-mirror-frame.
  • Legacy host-session mirror group writes through withWorktreeEntry/batch mutable copies; the mirror funnel marks full resync.
  • Initial store construction and arbitrary unannotated state replacement.

For resync, retirement collects at most three registries’ remembered workspace keys—≤5,700 at W=1,900, ≤57,000 at 10×—deduplicates them, then skips unchanged group-array references. Actual changed workspaces visit their saved group entries. Status-only mirror updates preserve group identity through group equality and do not trigger this scan.

Timers and idle wakeups

Timer or newly reached timer Before → after steady-idle wakeups/s per process Finite transition work
New revived re-ask timer Renderer 0 → 0 after answers/exhaustion One shared scheduled timer; eight attempts per ID. A simultaneous unanswered cohort schedules passes near 0/1/3/7/15/31/61/91 seconds, plus request duration. New arrivals do not reset older IDs.
Existing 1-second capability deadline, now also used by revived requests Renderer 0 → 0 One deadline per sequential batch; cancelled on completion. Timeout does not cancel underlying IPC, so “one in flight” bounds awaited requests, not necessarily already timed-out operations. Admission/attempt limits still bound this cohort’s total calls.
Existing activation idle callback / timeout fallback 0 → 0 Finite capped admission and drain confirmation; cancelled on effect cleanup.
Existing scroll-indicator 800 ms timeout and windowing rAF, reachable from restoration scroll Renderer 0 → 0 Local debounce/frame work after restoration, then stops.
Existing Windows reprobe runner No added steady-idle timer Existing local-owner backoff begins at 30 seconds and reaches 300 seconds: 0.0333 → 0.00333 wakeups/s while unsettled; settled answers stop scheduling. Released consumers unregister. No new main/daemon timer was introduced.

Base’s startup false remains permanently settled, mounted, with no retry. Head reopens only that negative answer after binding and eventually returns an unanswered ID to false, clearing retry metadata. It therefore adds finite recovery work without losing a base recovery route or adding a permanent five-minute retry for those IDs.

Windows owner fix and merged condensing

windows-terminal-capability-holds.ts:35 compares the held owner with the resolved owner. Same-owner returning strips reuse the shared answer; a different owner follows the normal TTL/in-flight load. New mounts also retain the 30-second TTL behavior. A mounted owner change clears reuse eligibility. The previous owner-mismatch finding is resolved.

Both scroll memory and condensing remain in TabBar.tsx. Offset restoration follows navigation’s mount reveal and waits for a nonzero box during hidden prewarm. Condensing recalculates membership/width and keeps the active tab represented.

Note, not blocker: the condense sliding-window ref is not preserved across release, so neighboring icons can differ after return. Base also replans when a hidden strip measures zero width; it does not guarantee unchanged neighboring membership across that transition. I found no lost active tab or new persistent work. Visual timing/flicker remains unmeasured.

Drained restriction identity uses a WeakSet. Pruning/widening replacements carry the mark; fresh plans do not inherit it. Small plans containing only unbound restored tabs regain browser/emulator overlay eligibility as base did after draining. Over-cap plans never receive this mark, preserving base’s restricted hidden-overlay behavior. Browser paint demand still overrides its mount gate; simulator tabs prevent layout release.

Regression classes touched

Class Disposition
Broad selectors / per-row derivation Constant-size workspace projection; expensive eligibility outside the selector and memoized. No new per-status fleet derivation.
No-op writes / unnecessary publication Drained revision changes once per restriction; presence publishes only first-open/last-close; revived publication requires a real authoritative gain.
Polls / new steady-idle wakeups New retry sequence terminates; steady-idle delta is zero.
Hidden/per-instance work Eligible strips and drop layers unmount; return avoids repeating same-owner host acquisition. Necessary terminal watchers and chat/browser retention remain.
Per-entity state outliving owners Three shared registries retire on group/workspace removal; presence listeners clean up; restriction marks are weak.
Hot-path rescans Addressed activation remains workspace-local. Full-resync fallback and O(H) cache maintenance are explicitly counted above.
Fanout / queues Revived batches ≤512, per-ID attempts ≤8; timed-out IPC cancellation limitation noted above.
Startup imports / migration / persistence Inventory extraction preserves implementation and call ordering; no new SDK, migration, serialization, or storage path.
Subprocess / synchronous main work Capability re-ask reaches bounded provider registry/Set checks in ipc/pty/ipc/inspect.ts:54; no per-ID subprocess, filesystem scan, or SQLite call.

Six scan questions

  1. Unused work before a skip gate? Reviewed. Release eligibility follows parking/browser/dialog gates; unrelated store writes do not scan tabs. Startup inventory remains existing one-shot work.
  2. Ownership multiplying work? Reviewed. Presence is workspace-local; retirement is singleton; capability loads share owner caches/in-flight promises; observation state survives group remount.
  3. Which thread/storage pays? Renderer pays selectors, local scans, and remount layout. Main performs bounded capability lookups. No new storage work; timings were not measured.
  4. Growth and forward progress? Reviewed at W=1,900/19,000 with P and H independent. Group state retires, admission progresses/stops, revived retries exhaust per ID.
  5. Execution-host effects? Local, SSH, paired-runtime/web, Windows, macOS/Linux routing branches inspected. Owner identity and parking capability gates remain intact. No live host validation was performed.
  6. Obsolete work releases its budget? Reviewed. Listener/observer cleanup, registry retirement, retry settlement/epoch handling, and existing parked-pane ownership were traced. Actual retained heap/GPU counts require runtime evidence.

@brennanb2025

brennanb2025 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Review status for aaba360 (main merged)

Main merged into the branch as 4ff05ce42dd2. The only textual conflict was TabBar.tsx: the branch's tab-strip scroll memory and main's new tab-strip condensing (overflow chip) were both kept. Condensing keeps the strip from overflowing, so restoring a saved offset is a harmless no-op there. The other files both sides changed (use-tab-bar-create-menu-controller.ts, a ratchet baseline row) auto-merged; the create menu still passes the per-group agent-detection setting.

Reviews on the merge

  • Delta blinded audit (Codex) of the merge: found one must-fix. Main's folded Pane Actions menu opens the quick-command editor through its own owner, which didn't register with the branch's open-dialog guard, so a parked workspace could release its layout and drop the dialog's unsaved text. Fixed in aaba3605e96f by registering that editor too; a delta re-audit of the fix (listing every editor owner) is SAFE. Nit: a standalone chat's editor also notifies the release check (one render per open/close).
  • Fresh perf reviewer (full perf-scan) on 4ff05ce42dd2: clean, report above.
  • Fresh Claude review of the merge resolution and the fix: PASS. One P2: main's condensed strip re-centres its visible window on the active tab on every mount, and returning to a parked workspace is now a remount, so a strip the user had shifted comes back re-centred (the active tab stays visible). Fix if wanted: keep the window start per group alongside the scroll offset.
  • remote-check (pnpm check:changed, related tests) passes on the head.

QA: neither the conflict nor the fix touches parking or the release/remount logic, so the soak on 2298323fd96a stands (qa_head). Soak there: heap 871 -> 758 MB, PSS 3,165 -> 2,913 MB, listeners 17,578 -> 7,995, xterms 30 -> 0, layouts 150 -> 5, early switch-back 1,004 -> 205 ms; terminal and draft restore pass.

@brennanb2025
brennanb2025 merged commit 16cf21e into main Nov 24, 2026
55 checks passed
Jinwoo-H pushed a commit that referenced this pull request Nov 24, 2026
…ts so memory stays flat (#45956)

* perf(terminal): release hidden parked workspace surfaces

* perf(terminal): keep chat overlays mounted when releasing a parked workspace

* perf(terminal): keep workspaces with plugin editor frames mounted

* perf(terminal): release only layouts whose active tabs draw outside them

* perf(terminal): derive release eligibility from identity-stable tab selections

* chore: drop unrelated lockfile churn

* fix(terminal): park restored hidden terminals once every pane has a live PTY

* fix(terminal): re-ask snapshot capability when a restored session revives under its id

* fix(terminal): keep idle admission from mounting unbound restored tabs that can never park

* fix(terminal): keep restored chat-view terminals unparked and drop superseded capability retries

* fix(terminal): coalesce revived-session capability re-asks and keep empty split panes mounted

* fix(terminal): stop the revived re-ask once its own sessions are answered

* fix(tab-bar): keep each group's tab-strip scroll across a released layout

* perf(terminal): ask only revived ids once at a time with bounded retries, index settled and release checks, keep strip scroll through hidden prewarm

* fix(terminal): keep unanswered revived ids on the inventory's slow re-ask and keep tab-strip offsets until their group closes

* fix(terminal): hand unanswered revived ids to the inventory loop and wake it

* fix(terminal): settle unanswered revived ids back to their cached answer instead of polling

* fix(tab-bar): remember a tab strip scrolled to its start

* fix(terminal): clear an id's unknown retry when its revived answer settles

* fix(tab-bar): sync strip navigation with a restored offset before its resize pass

* perf(terminal): skip backoff for answered capability ids and reuse the live local re-probe on tab-strip remount

* docs(terminal): unbound restored tabs now wait until shown

* perf(terminal): key release eligibility on tab membership, drop strip offsets of closed groups, cap capability reuse at the re-probe ceiling

* refactor(terminal): move released-layout eligibility into its own module

* fix(terminal): reuse a recent capability answer only for tab strips returning from a released layout

* fix(terminal): a tab strip returning from a released layout reads the shared capability answer, as a retained strip did

* fix(terminal): settle restored splits by every layout leaf; returning strips reload after a failed capability probe

* perf(terminal): keep a host's shell-capability answer while a released tab strip holds it

* perf(terminal): released strips' hosts survive the capability cache cap; holds are scoped to live groups

* fix(terminal): keep layouts with an open quick-command editor, count revived re-asks per id, never trim live capability owners

* fix(terminal): a returning strip reuses the cached capability answer only for the host it returned with

* fix(terminal): dispose released strips' state with their tab group; keep agent detection's observed hosts across a remount

* test(terminal): hoist the capability read mock so the store import can't initialise it first

* fix(terminal): unbound restored tabs no longer hold a hidden workspace's simulator and browser overlays unmounted

* fix(terminal): a drained activation admission stops holding hidden simulator and browser overlays unmounted

Replaces the per-store-write tab scan: admission marks its restriction drained when only unbound restored tabs remain, so over-cap restrictions keep base behaviour.

* fix(terminal): pruning a closed tab keeps a drained admission's restriction drained

* fix(terminal): a targeted background mount keeps a drained admission's restriction drained

* fix(terminal): a partial reveal keeps a drained admission's restriction drained

* perf(terminal): retire tab-group state only for the workspaces a groups write addressed

* fix(terminal): closing a quick-command dialog re-checks its hidden workspace's layout release

* fix(terminal): a returning strip reuses its held capability answer only on the same host; tidy observed-host and hold lifetimes

- Comparing the held owner key keeps a host-changed return on the normal TTL load.
- Agent detection resolves its group's observed-host set once per group, not per render.
- A capability hold left by a dependency change on a still-mounted strip is dropped when probing turns off.

* chore(terminal): record useDetectedAgents' react-compiler bailouts dropping to 0

* fix(terminal): install tab-group state retirement from the store so the registry doesn't import it (dependency cycle)

* fix(terminal): the folded pane-actions quick-command editor also keeps its workspace's layout mounted while open
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.

1 participant