Skip to content

fix(renderer): prevent restored terminal spawn storms - #15742

Closed
Jinwoo-H wants to merge 1 commit into
mainfrom
sta4953-mount-gate-takeover
Closed

Jinwoo-H wants to merge 1 commit into
mainfrom
sta4953-mount-gate-takeover

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​998 $\color{#cf222e}{\Huge{\mathbf{−}}}$​7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​991
Prod 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​480 $\color{#cf222e}{\Huge{\mathbf{−}}}$​17 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​463

Summary

STA-4953 was reported and diagnosed by Revofusion in #15624.

Opening a paired-runtime workspace could mount restored PTY-less terminal rows before the current connection received an authoritative session.tabs answer. Every affected mount took the fresh-spawn path and created a new host shell.

Now that #15644 is merged, this PR consumes its canonical, generation-scoped hasHostSessionMirrorHydrated evidence. It does not add another answer or connection latch. This PR owns only the mount policy.

Mount policy

  • Hold only cold-restored, non-mirrored rows that would fresh-spawn: no tab PTY, no tracked pane PTY, and no surviving layout-leaf PTY.
  • Scope each wait to the environment id plus that environment connection generation, and accept only evidence that landed in the store. A full inventory speaks for every covered worktree; a single-worktree frame speaks only for that worktree.
  • Never withhold the active or remembered-active tab, group actives, activity portals, pending-startup tabs, live tabs, or rows an earlier pass already mounted.
  • Keep rows proven dead by an accepted empty snapshot unmounted until the user explicitly activates them; that click intentionally creates a new shell.
  • Fail open into mounting after 20 seconds for an unanswered host epoch, with a 60-second total ceiling across reconnects and host moves.
  • Keep allowed/deferred Set identities stable when membership is unchanged, avoiding memoized worktree-surface rerenders.
  • Request browser-automation bootstrap with tabIds: [], so it mounts only the surface. Do not whole-worktree mount an unparseable sleeping record that no pane matcher can consume.
  • Make no IPC, RPC, stream, or host-publication change. Local, direct-SSH, and folder workspaces remain outside the gate.

Red-first evidence

  • The bug was reproduced on clean main at the rendered Terminal seam: restored PTY-less rows mounted before host evidence and reached the fresh-spawn class.
  • With only the shipping applyRestoredTerminalSpawnHold call removed, all 21 rendered scenarios fail; with it restored, all 21 pass.
  • Targeted mutations kill the group-active mapping, activity-portal carve-out, environment/connection epoch checks, settled-verdict reset on host move, 60-second ceiling, and stable-Set identity tests.

Verification

  • Mount policy and rendered seam: 2 files, 43/43 tests passed.
  • fix(terminal): stop orphaning live agent terminals across host restarts and graph syncs #15644 hydration evidence and session-tabs consumers: 6 files, 61/61 tests passed.
  • Broader renderer sweep after rebase: 1,077 files, 9,853 tests passed, 2 skipped.
  • pnpm run typecheck:web
  • pnpm run check:code-quality:changed
  • pnpm run check:react-doctor:changed
  • pnpm run check:reliability-gates
  • git diff --check, formatting, raw control-byte scan, and binary diff scan
  • Independent OpenCode reviews found and drove fixes for host-environment epoch identity and stable set references. A final read-only review found no blocker after its kill-switch and untargetable-wake concerns were independently traced and rejected as intentional or unrecoverable.

Known tradeoffs and gaps

  • A host that does not answer within 20 seconds can still spawn the restored rows when the gate fails open. This is deliberate: a mount gate must not leave a workspace blank forever.
  • A dead restored row remains visible but unmounted after an accepted empty snapshot; explicitly activating it starts a new shell.
  • The spawn-safety hold is intentionally independent of the watcher-deferral kill switch. Disabling watcher deferral must not reopen the spawn storm.
  • Coverage is deterministic renderer/hydration evidence on macOS. There is not yet a live headed or headless paired-runtime test counting host terminal.create calls, nor Linux, Windows, or live SSH execution for this gate.

@Jinwoo-H
Jinwoo-H marked this pull request as ready for review August 21, 2026 17:46
@coderabbitai

coderabbitai Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 6f0e15fd-c0fb-420b-bd18-6536c8f4f3f7

📥 Commits

Reviewing files that changed from the base of the PR and between f7033e0 and 7a696c6.

📒 Files selected for processing (11)
  • config/reliability-gates.jsonc
  • src/renderer/src/components/Terminal.tsx
  • src/renderer/src/components/terminal/restored-terminal-spawn-hold.render.test.tsx
  • src/renderer/src/components/terminal/restored-terminal-spawn-hold.test.ts
  • src/renderer/src/components/terminal/restored-terminal-spawn-hold.ts
  • src/renderer/src/hooks/ipc-events/browser-automation-bootstrap-lease.test.ts
  • src/renderer/src/hooks/ipc-events/browser-automation-bootstrap-lease.ts
  • src/renderer/src/hooks/useIpcEvents-browser-tab-create.test.ts
  • src/renderer/src/lib/wake-sleeping-agents-in-background.test.ts
  • src/renderer/src/lib/wake-sleeping-agents-in-background.ts
  • src/renderer/src/runtime/web-session-tabs-sync.ts
🚧 Files skipped from review as they are similar to previous changes (9)
  • src/renderer/src/hooks/useIpcEvents-browser-tab-create.test.ts
  • src/renderer/src/lib/wake-sleeping-agents-in-background.test.ts
  • src/renderer/src/lib/wake-sleeping-agents-in-background.ts
  • src/renderer/src/components/terminal/restored-terminal-spawn-hold.test.ts
  • src/renderer/src/components/Terminal.tsx
  • src/renderer/src/components/terminal/restored-terminal-spawn-hold.ts
  • src/renderer/src/components/terminal/restored-terminal-spawn-hold.render.test.tsx
  • config/reliability-gates.jsonc
  • src/renderer/src/runtime/web-session-tabs-sync.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.


📝 Walkthrough

Walkthrough

The terminal activation path now resolves runtime environments and holds restored pty-less rows that could spawn host terminals. Holds use worktree- and connection-scoped session-tab evidence, bounded timers, and mount restrictions. Unit and render tests cover activation, exclusions, reconnects, stale evidence, timeouts, and lifecycle behavior. Background mount requests now target explicit tab IDs. Session-tab RPC paths share a 15-second timeout constant. A reliability gate documents the behavior and validation criteria.

Merge Risk: ⚪ Minimal · up to 7a696

This localized renderer change prevents restored terminal rows from spawning shells before host state is known, with targeted and broad checks reported as passing; no actionable merge-blocking risk remains beyond normal checks and review.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description clearly explains the problem, mount policy, scope, verification results, and known tradeoffs. However, it omits the required Visual Proof section or an explicit N/A explanation, and it… Add the required Linked Issue section with a Fixes #<issue> reference. Add before-and-after visual proof for the behavior change, or state N/A with a brief reason. Complete the applicable Testing, Review, Notes, Agent skill upstream bou…
Docstring Coverage ⚠️ Warning Docstring coverage is 40.38% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 52 functions across 18 files. (1 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: preventing restored terminals from spawning excessive host shells.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description clearly explains the problem, mount policy, scope, verification results, and known tradeoffs. However, it omits the required Visual Proof section or an explicit N/A explanation, and it does not provide the required Linked Issue entry in the template format.

Resolution

Add the required Linked Issue section with a Fixes #&lt;issue&gt; reference. Add before-and-after visual proof for the behavior change, or state N/A with a brief reason. Complete the applicable Testing, Review, Notes, Agent skill upstream boundary, and Checklist sections, including platform coverage and command results if available.

Full details: Docstring Coverage

Explanation

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

✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Jinwoo-H
Jinwoo-H marked this pull request as draft August 22, 2026 00:43
@Jinwoo-H
Jinwoo-H force-pushed the sta4953-mount-gate-takeover branch from 9451bf5 to 79c4393 Compare August 22, 2026 01:39
@Jinwoo-H
Jinwoo-H marked this pull request as ready for review August 24, 2026 03:56

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
config/reliability-gates.jsonc (1)

3-3: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Update updatedAt to cover the newest recorded evidence.

The new gate terminal-session.restored-spawn-hold records evidence runs dated 2026-08-21, but updatedAt stays at 2026-08-20. Set updatedAt to the latest change date so the manifest freshness stamp matches its content.

📝 Proposed fix
-  "updatedAt": "2026-08-20",
+  "updatedAt": "2026-08-21",
🧹 Nitpick comments (2)
src/renderer/src/components/terminal/restored-terminal-spawn-hold.test.ts (1)

189-207: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a case for a partial release.

The suite covers a full release through environmentId: null and through the deadline. It does not cover the re-filter path at restored-terminal-spawn-hold.ts Lines 211-223, where one held row stops being holdable while others stay held.

That path is the only producer of a non-empty releasedTabIds alongside a non-empty heldTabIds. Callers use releasedTabIds to re-allow mounting. If that difference regresses, the affected row stays unmounted for the rest of the hold.

💚 Proposed test
+  it('reports only the row it let go while the rest stay held', () => {
+    const holdByWorktreeId = new Map<string, RestoredSpawnHoldEntry>()
+    plan({ holdByWorktreeId })
+    const partial = plan({
+      holdByWorktreeId,
+      isColdActivationPass: false,
+      nowMs: 2_000,
+      immediateTabIds: new Set(['row-1'])
+    })
+    expect([...partial.heldTabIds]).toEqual(['row-2'])
+    expect([...partial.releasedTabIds]).toEqual(['row-1'])
+  })
src/renderer/src/runtime/web-session-tabs-sync.ts (1)

576-585: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Shorten the two doc blocks.

Both blocks run ten lines and restate the decision logic in prose. Keep the non-obvious rule (a rejection settles only when the store already holds an equal-or-newer accepted view) and drop the walkthrough.

As per coding guidelines: "Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code."

Also applies to: 3661-3670

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: da9eecf7-d0d2-45d1-8a03-d2b3fb1bf1d6

📥 Commits

Reviewing files that changed from the base of the PR and between 9451bf5 and 79c4393.

📒 Files selected for processing (7)
  • config/reliability-gates.jsonc
  • src/renderer/src/components/Terminal.tsx
  • src/renderer/src/components/terminal/restored-terminal-spawn-hold.render.test.tsx
  • src/renderer/src/components/terminal/restored-terminal-spawn-hold.test.ts
  • src/renderer/src/components/terminal/restored-terminal-spawn-hold.ts
  • src/renderer/src/lib/wake-sleeping-agents-in-background.ts
  • src/renderer/src/runtime/web-session-tabs-sync.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.

…A-4953)

Opening a paired-runtime workspace mounted every persisted terminal row before
the first authoritative session.tabs snapshot for the current connection. A row
with no pty left anywhere can never be watcher-covered
(terminal-parked-tab-watchers requires a non-null ptyId), so cold activation
mounted it immediately and pty-connection took its FRESH SPAWN branch -- one new
remote shell per restored row.

Hold that class -- non-mirrored rows with no ptyId and no surviving layout-leaf
pty -- until the host answers for the worktree, reading the canonical evidence
merged #15644 already owns: host-session-mirror-hydration's generation-scoped
latch, settled only from landed web-session-tabs store patches, plus the store's
runtime connection generation. No parallel answer bookkeeping.

The hold epoch is the host, not just the number: generations count per
environment, so it carries environmentId too and a workspace that moves hosts
starts a fresh window and inherits no verdict -- still under the same ceiling,
still never re-holding a mounted row.

Never held: the active tab, group actives (unified-tab id mapped to its terminal
entityId), activity portals, pendingStartupByTabId rows, live tabs, and anything
an earlier pass already mounted (no retroactive unmount). Local, SSH and folder
workspaces resolve no environment and are never held.

Unlike the resume/spawn gate, this one releases into *mounting*, where failing
open is safe, so it is bounded: a 20s per-connection window (session.tabs RPC
timeout + 5s) and a 60s ceiling across reconnects. A blank workspace cannot wedge.

The allowed/deferred sets keep their identity while membership is unchanged; a
settled hold runs on every render, and a fresh Set each time is a new prop
identity for the memoized worktree surface tree.

Also closes two untargeted background-mount paths that fanned the same rows into
host spawns: the bootstrap mount in useIpcEvents now requests the surface only,
and wake-sleeping-agents no longer falls back to a whole-worktree mount for a
passive record whose tab id cannot be resolved.

Registers the invariant as terminal-session.restored-spawn-hold in
config/reliability-gates.jsonc (experimental/partial, macOS-only evidence).
@Jinwoo-H
Jinwoo-H force-pushed the sta4953-mount-gate-takeover branch from 79c4393 to 7a696c6 Compare August 25, 2026 04:56
@Jinwoo-H
Jinwoo-H marked this pull request as ready for review August 25, 2026 07:59
@coderabbitai

coderabbitai Bot commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@nwparker

nwparker commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

#40289 fixes the dead-tab respawn wave from #39166 without depending on this PR. Saved tabs that have no PTY anywhere wait until they are shown, on local, SSH and paired workspaces. This PR's separate concern still stands: holding rows on a paired host until its first session.tabs answer arrives. It would need a rebase onto current main.

@nwparker

nwparker commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

Thanks @Jinwoo-H for this work and for the careful diagnosis of the restored-terminal spawn storm, and thanks to Revofusion for the original report in #15624. The core problem is now fixed on main by #40289: when a worktree opens, saved tabs with no live PTY are held until the user opens them, and the visible and active tabs still start immediately. Your mount-policy design (never holding the active, group-active, pending-startup or activity-portal tabs, and mounting once a PTY binds) shaped that approach. This branch has drifted a long way from main, so I'm closing it in favor of #40289. If the paired-host gating before the first session.tabs answer still covers a case #40289 misses, please open an issue and link it here.

@nwparker nwparker closed this Nov 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants