Skip to content

fix(ssh): keep a mid-spawn PTY alive for the pane that was remounted onto it - #19386

Closed
nwparker wants to merge 4 commits into
mainfrom
fix/ssh-reconnect-new-tab-disposed-spawn-kill
Closed

nwparker wants to merge 4 commits into
mainfrom
fix/ssh-reconnect-new-tab-disposed-spawn-kill

Conversation

@nwparker

@nwparker nwparker commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​288 $\color{#cf222e}{\Huge{\mathbf{−}}}$​12 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​276
Prod 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​120 $\color{#cf222e}{\Huge{\mathbf{−}}}$​7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​113

ELI5

When Orca reconnects to an SSH host and you open a new terminal right afterwards, the new terminal sometimes came up dead: either the tab vanished a moment later, or it showed a prompt but ignored everything you typed. Two things were racing over the same shell — the reconnect asked the fresh pane to "try again", and the first attempt, on its way out, killed the shell the retry had just been handed. This change stops the first attempt from killing a shell that the tab still owns.

Which shapes this covers. #17692 was triaged into two shapes: (a) the new tab deleted from tabsByWorktree, (b) the tab surviving with a bound PTY and a painted prompt but dead to input. Both are covered here, because both are the same pty.kill on the successor's PTY — (a) when the relay reports a proven exit and handlePtyExit closes the tab, (b) when only the synthetic -1 arrives. The e2e spec asserts them separately per round (survives / binds / answers echo). What this does not cover: a persistent state where every new terminal on a long-lived connection is blank until Orca restarts, with no reconnect involved — see the #17047 note under Linked Issue.

What Changed

  • src/renderer/src/components/terminal-pane/ipc-pty-connect.ts — the "spawn resolved after the transport was destroyed" branch used to kill the PTY unconditionally. It now asks the transport's retainDisposedSpawn callback first and only kills when the answer is not true. The two retirements are now separate closures: retireDisposedSpawn (transport destroyed mid-spawn; consults retention, because a remounted successor may hold the same id via main's pane-spawn reservation) and killFreshSpawn (a live transport refusing the id via admitPtyId; kills unconditionally, because that transport is the pane's only one and nothing else can own the PTY — the feat: bound direct SSH reconnect fan-out and recovery #11003 behaviour). The first revision of this PR routed both through one guard, which would have leaked every refused direct-SSH retry PTY in production.
  • src/renderer/src/components/terminal-pane/pty-connection/disposed-spawn-retention.ts (new) — shouldRetainDisposedPaneSpawn(state, worktreeId, tabId, leafId): keep the PTY while the worktree is not being deleted, the tab still exists in tabsByWorktree, and, if a layout exists, it still names the leaf. Otherwise the PTY is genuinely ownerless and the existing kill stands. The worktree-deletion exclusion is there because shutdownWorktreeTerminals kills from the bound-id ledger, which never learns an in-flight spawn's id.
  • src/renderer/src/components/terminal-pane/pty-connection/pty-input-recovery.ts — wires the callback into every IPC transport a pane creates, reading the live store at decision time.
  • src/renderer/src/components/terminal-pane/pty-transport-types.ts — the optional retainDisposedSpawn transport option.
  • tests/e2e/ssh-reconnect-new-tab-liveness.spec.ts (new, registered in config/scripts/run-ssh-docker-e2e.mjs) — six rounds of reconnect → open tab → assert survives, binds, and answers echo.
  • tests/e2e/ssh-reconnect-tab-destruction.spec.ts — the "not asserted" note now records what was measured on this fix for the preserved tab (see Testing): still not deterministic, and a different shape, so the assertion stays out.
  • docs/reference/ssh-reconnect-source-recovery.md — the section is marked resolved for the one measured cause (a newly opened tab), and the preserved-tab shape the section originally recorded is kept open with the sharper measurement.
  • pty-transport-reattach-admission.test.ts — the two "retires a rejected fresh fallback" tests now build the transport the way installPtyInputRecovery does (with retainDisposedSpawn supplied and answering true), so they fail on the first revision of this PR's guard and pass on this one.

Why

The cause, measured

The clustered hypothesis pointed at the direct-SSH snapshot apply window (remote-workspace-snapshot-apply.ts) and the merge's host-unknown branch. That is not where the loss happens. Instrumenting the store, pty.kill, and pty:exit on the Docker-SSH lane showed:

  1. A tab opened right after a reconnect has no PTY yet, so the reconnect's pane-retry ledger (retryDirectSshTerminalPanes) bumps its generation and the pane remounts while its first pty:spawn is still in flight.
  2. Main's pane-spawn reservation (spawn-begin.ts) sees the same (worktree, connection, paneKey) and hands the remounted pane the SAME PTY the first spawn is about to receive.
  3. The first transport is now destroyed, so when its spawn resolves, retireFreshSpawn in ipc-pty-connect.ts calls pty.kill(id) on the id the successor is bound to.

One kill, two symptoms. When the relay reported a proven exit (code 0), handlePtyExit closed the tab (closeTab reason=pty-exit) — the "tabs close immediately" shape of #17692. When only the synthetic -1 arrived, the tab stayed bound to a dead PTY with a painted prompt that never answered — #17692's second shape, which also looks like #17047's symptom but was only ever reproduced here with a reconnect.

It needs no second reconnect and no snapshot apply. It reproduces with one reconnect and one new tab, at 40-50% per attempt.

Why this fix and not another

  • The kill in retireFreshSpawn exists to reclaim a genuinely orphaned PTY (pane closed mid-spawn). That case is preserved: no tab, or no leaf in the layout, still kills.
  • Comparable products' terminal hosts shut down a process created for an already-disposed instance unconditionally, which is exactly the behaviour that is wrong here — because Orca deliberately hands the successor the same PTY through the reservation. The decision has to be made by the surface owner, not the disposed transport, so it is a callback the pane supplies rather than logic in the transport.
  • The alternative of making the retry ledger skip tabs with a spawn in flight would fix this path but leave every other mid-spawn remount (recovery remounts, activation bumps) able to kill a successor's shell the same way.
  • Direction is leak-over-kill per docs/reference/ssh-execution-boundary.md: the worst case of a wrong "retain" is a PTY the relay's idle sweep reclaims later; the worst case of a wrong "kill" is the user's shell.

Boundaries

  • Wire compatibility: no wire change. Renderer-internal; falls under Rule 1 trivially (no new field on any RPC or stream).
  • Execution boundary: no verdict is produced or changed; the change only refrains from a kill.
  • Folder workspaces / worktrees: tabsByWorktree is keyed by workspace key for both; the leaf check reads terminalLayoutsByTabId, which is workspace-agnostic.
  • Platforms: renderer-only, no path or shell logic.
  • Local terminals: the same retireDisposedSpawn runs for local spawns. Local panes are remounted mid-spawn far less often, but the same reasoning applies and the same retention rule is correct there.
  • Scope: retainDisposedSpawn is consumed only by createIpcPtyTransport (local IPC and direct SSH). createRemoteRuntimePtyTransport has no disposed-spawn kill to guard and ignores the option.

Linked Issue

Fixes #17692

This PR does not close #17047, and must not. The link is inferred, not measured: neither reporter mentions a reconnect, the repro here requires one, and the bound-but-dead shape #17047 describes was never observed on this mechanism. The closer candidate is the preserved-tab gap recorded under Testing (live shell on the host, empty pane), which this PR does not fix. The first commit's message still carries a Fixes #17047 line; merge with an explicit squash body (gh pr merge --squash --subject … --body …) so that line never reaches the auto-close parser.

Related: #17047 — deliberately not claimed. That report is a persistent state on a long-lived connection (every new terminal blank until Orca restarts, no reconnect mentioned). Nobody has reproduced it, and the only mechanism measured here requires a reconnect to overlap the tab's first spawn. The symptom of shape (b) is identical, so #17047 may share the cause if the user's connection was silently dropping and reconnecting, but that is a hypothesis, not a reproduction. The docs note records it as open.

Visual Proof

N/A — terminal liveness across an SSH reconnect; the evidence is the per-round table below, not a screenshot.

Testing

All measurements on the Docker-SSH lane (tests/e2e/fixtures/docker-ssh-relay, ORCA_E2E_SSH_DOCKER=1), macOS host, headless Electron. Each round: reconnect, immediately open a tab, then assert the tab survives, binds a PTY, and a written echo MARKER produces output.

Before (main at 2265fce, one reconnect + one new tab per round):

run rounds tab deleted bound but dead live
1 6 3 1 2
2 10 1 6 3
3 10 2 3 5
4 10 0 4 6
5 10 4 4 2

Both symptom shapes appeared in the same runs, from the same pty.kill on the successor's PTY. Controls: waiting for the reconnected pane to rebind before opening the tab was 8/8 live, i.e. the bug needs the tab's spawn to overlap the reconnect.

After (this branch):

mode rounds tab deleted bound but dead live
one reconnect, open immediately 20 0 0 20
two reconnects (issue's shape) 10 0 0 10
new spec, 6 rounds 6 0 0 6
existing ssh-reconnect-tab-destruction.spec.ts 1 pass

Re-verified after review changes (7e6def8, fresh worktree, fresh electron-vite build --mode e2e, same Docker-SSH lane):

run result
new spec (with the distinct-tab assertion) 6/6 rounds live, 25.7s
new spec + ssh-reconnect-tab-destruction, --repeat-each=2 4/4 pass
negative control: guard replaced by true, rebuilt, new spec rerun fails round 2: survived: false, ptyId: null (shape (a) on the instrument)

Same new spec with only the guard disabled (retainDisposedSpawn?.() !== true → true), rebuilt and rerun: fails in round 2 (the new tab never bound a PTY) — reproduced independently in the re-verification above. Six rounds is enough to separate the fix from a lucky run.

Per-regression mutation testing (each mutation against the one assertion written for it, all four caught):

mutation test that fails
drop the retainDisposedSpawn guard from the kill pty-transport-detach-attach-handoff.test.ts › keeps a fresh spawn that resolves after destroy when the pane surface still owns it
retention ignores the leaf check (always true once the tab exists) disposed-spawn-retention.test.ts › kills the PTY when the leaf was removed from a split layout
retention ignores tab presence disposed-spawn-retention.test.ts › kills the PTY when the tab is gone from every worktree
drop the wiring in pty-input-recovery.ts pty-connection-fresh-spawn-guards.test.ts › lets a disposed spawn survive while the pane surface still exists in the store
wiring passes pane.id instead of deps.tabId pty-connection-fresh-spawn-guards.test.ts › lets a disposed spawn survive while the pane surface still exists in the store

All five re-run at 7e6def8; each mutation fails exactly the named test and nothing else (30 → 29 pass). The e2e spec's distinct-tab assertion (CodeRabbit) is a guard on the probe itself: without it a round could measure the prior, already-live tab.

pnpm tc, pnpm run check:code-quality:changed, oxfmt clean. pr-e2e-gate-contract.test.mjs passes with the new spec claimed by run-ssh-docker-e2e.mjs.

Remediation round (independent verifier's findings; fresh worktree, fresh electron-vite build --mode e2e):

check result
unit: the 4 touched test files (48 tests) pass
unit: src/renderer/src/components/terminal-pane (442 files, 4231 tests) pass
pnpm tc (all projects), check:code-quality:changed, oxfmt --check clean
Docker-SSH: ssh-reconnect-new-tab-liveness 6/6 rounds x 3 runs, all live
Docker-SSH: ssh-reconnect-tab-destruction (as committed) 3/3 pass
real host (ssh openclaw, Ubuntu 24.04, scratch probe = the new spec's loop pointed at the user's ssh-config host) 4/4 rounds live; ids pty2:…:2 through :5

Per-regression mutation controls on the remediation (each against the assertion written for it):

mutation test that fails
PR-head guard restored (refusal path consults retention) — the P1 pty-transport-reattach-admission.test.ts › retires a rejected fresh fallback… and › surfaces rejected fresh fallback retirement… (2 fail, 15 pass)
refusal path re-routed through retireDisposedSpawn same two
retention guard dropped entirely (if (true)) pty-transport-detach-attach-handoff.test.ts › keeps a fresh spawn that resolves after destroy… (1 fail, 26 pass)
isDeleting exclusion dropped from the predicate disposed-spawn-retention.test.ts › kills the PTY when the worktree is being deleted… and pty-connection-fresh-spawn-guards.test.ts › lets a disposed spawn survive…
wiring passes tabId as worktreeId pty-connection-fresh-spawn-guards.test.ts › lets a disposed spawn survive…

Preserved-tab liveness (verifier P2, docs) — measured rather than asserted. A probe that selects the preserved tab after the second reconnect and writes echo MARKER | tee /tmp/MARKER failed 2 of 5 and 1 of 6 on this fix. The miss is a different shape from the one fixed here: the pane binds a PTY, the shell is alive on the host (the tee file exists with the marker), and the pane's xterm holds zero bytes before and after the write — an output-delivery gap, not a killed shell. Selecting the tab first does not recover it. So the assertion stays out of the spec, the section stays open for that shape in the docs, and it is the closer candidate for #17047's "live connection, blank new pane" report.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Review changes in 7e6def8: the e2e spec now records the active tab before openTerminalTabInActiveGroup and asserts the id changed (CodeRabbit's finding); the #17047 claim is dropped for lack of a reproduction; the docs note says which shape stays open.

The clustering note asked for the two shapes to be treated as two assertions. They are: the e2e spec asserts survival, binding, and liveness separately per round, and the before table records them separately. The snapshot-apply TOCTOU lead (merged built from a stale state) was checked and is real as a code smell, but it is not on the path this bug takes — the deletion trace goes through pty-exit → closeTab, never through hydrateTabsSession. Left alone to keep this PR to one cause.

Residual, not attributed to this PR: on the PR head, splitting a tab immediately after opening it right after a reconnect lost the split ({panes: 1, bound: 1}) in about 2 of 18 review rounds; a control passed. Same reconnect-remount window, no layout code touched here. Recorded in the docs note; worth its own issue.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

…onto it

A tab opened right after an SSH reconnect has no PTY yet, so the reconnect's
pane-retry ledger bumps its generation and remounts the pane while its first
spawn is still in flight. Main's pane-spawn reservation hands the remounted
pane the same PTY, and the disposed first transport then killed it as an
orphan. A proven exit closed the tab; a synthetic exit left it bound to a
dead shell that never answered input.

The disposed-spawn kill now asks the pane surface first and skips the kill
while the tab still exists and its layout still names the leaf. A genuinely
ownerless PTY is still killed.

Measured on the Docker-SSH lane: 4-5 failures in 10 rounds before, 0 in 36
after. The new e2e spec runs six rounds and fails in round 2 with only the
guard removed.

Fixes #17692
Fixes #17047
@coderabbitai

coderabbitai Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 8524ae47-6731-4a52-bd5b-c39f7e126d26

📥 Commits

Reviewing files that changed from the base of the PR and between ea102a9 and 7769814.

📒 Files selected for processing (12)
  • config/scripts/run-ssh-docker-e2e.mjs
  • docs/reference/ssh-reconnect-source-recovery.md
  • src/renderer/src/components/terminal-pane/ipc-pty-connect.ts
  • src/renderer/src/components/terminal-pane/pty-connection-fresh-spawn-guards.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/disposed-spawn-retention.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/disposed-spawn-retention.ts
  • src/renderer/src/components/terminal-pane/pty-connection/pty-input-recovery.ts
  • src/renderer/src/components/terminal-pane/pty-transport-detach-attach-handoff.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport-reattach-admission.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport-types.ts
  • tests/e2e/ssh-reconnect-new-tab-liveness.spec.ts
  • tests/e2e/ssh-reconnect-tab-destruction.spec.ts
🚧 Files skipped from review as they are similar to previous changes (12)
  • src/renderer/src/components/terminal-pane/pty-connection-fresh-spawn-guards.test.ts
  • src/renderer/src/components/terminal-pane/ipc-pty-connect.ts
  • tests/e2e/ssh-reconnect-tab-destruction.spec.ts
  • src/renderer/src/components/terminal-pane/pty-connection/pty-input-recovery.ts
  • config/scripts/run-ssh-docker-e2e.mjs
  • tests/e2e/ssh-reconnect-new-tab-liveness.spec.ts
  • src/renderer/src/components/terminal-pane/pty-transport-reattach-admission.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport-detach-attach-handoff.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/disposed-spawn-retention.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/disposed-spawn-retention.ts
  • src/renderer/src/components/terminal-pane/pty-transport-types.ts
  • docs/reference/ssh-reconnect-source-recovery.md

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


📝 Walkthrough

Walkthrough

The change adds worktree-aware retention for disposed PTY spawns during pane remounts. Transport cleanup retains eligible spawns and kills rejected or ownerless spawns. Tests cover retention state, delayed spawn resolution, and admission failures. A six-round Docker SSH E2E test verifies live shells in newly opened tabs after reconnects. Documentation records resolved and unresolved cases.

Priority: ➖ Normal — Impact reflects medium issue severity.

Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to 77698

This change retains eligible PTY spawns during SSH reconnect remounts to keep newly opened terminal tabs live while continuing to clean up ownerless or rejected PTYs. No current merge-blocking risk is established.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The changes address the reconnect-related new-terminal failure in #17692 with code fixes, unit tests, and SSH end-to-end coverage. The persistent blank-terminal behavior in #17047 remains unresolved a… Either unlink #17047 from this PR or provide an implementation and evidence that resolve its persistent blank-terminal behavior. Keep #17692 as the directly addressed issue if #17047 remains out of scope.
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 11 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 identifies the SSH mid-spawn PTY retention fix and matches the primary change.
Description check ✅ Passed The description is complete and follows the repository template. It explains the problem, implementation, scope, linked issue, testing, residual behavior, and checklist status.
Out of Scope Changes check ✅ Passed The production changes, tests, documentation, and E2E runner update all support the SSH reconnect PTY-liveness fix. The preserved-tab limitation and split-loss observation are documented without intro…
Full details: Linked Issues check

Explanation

The changes address the reconnect-related new-terminal failure in #17692 with code fixes, unit tests, and SSH end-to-end coverage. The persistent blank-terminal behavior in #17047 remains unresolved and is explicitly not claimed by this PR.

Full details: Docstring Coverage

Explanation

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

  • Fix all pre-merge checks with AI
✨ 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 2d0be2ea-a612-484e-aae7-c26ceac49ba4

📥 Commits

Reviewing files that changed from the base of the PR and between 2265fce and 1cc6a79.

📒 Files selected for processing (11)
  • config/scripts/run-ssh-docker-e2e.mjs
  • docs/reference/ssh-reconnect-source-recovery.md
  • src/renderer/src/components/terminal-pane/ipc-pty-connect.ts
  • src/renderer/src/components/terminal-pane/pty-connection-fresh-spawn-guards.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/disposed-spawn-retention.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/disposed-spawn-retention.ts
  • src/renderer/src/components/terminal-pane/pty-connection/pty-input-recovery.ts
  • src/renderer/src/components/terminal-pane/pty-transport-detach-attach-handoff.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport-types.ts
  • tests/e2e/ssh-reconnect-new-tab-liveness.spec.ts
  • tests/e2e/ssh-reconnect-tab-destruction.spec.ts

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

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

A fix for the "tab opened right after an SSH reconnect comes up dead" class of bugs (#17692 tab closes immediately, #17047 blank shell). The disposed first transport's orphan-kill in retireFreshSpawn was landing on the PTY that main's pane-spawn reservation had already handed to the remounted successor. The kill now consults a retainDisposedSpawn callback supplied by the pane, which decides from the live store whether the pane surface still exists.

  • ipc-pty-connect.ts — retireFreshSpawn gates its PTY kill on retainDisposedSpawn?.() !== true (absent/false keeps the existing kill; backwards-compatible).
  • disposed-spawn-retention.ts (new) — shouldRetainDisposedPaneSpawn: retain iff the tab still exists in tabsByWorktree and (when a layout exists) the layout still names the leaf; otherwise the PTY is genuinely orphaned and is killed.
  • pty-input-recovery.ts — wires the callback into every pane's transport options, reading useAppStore.getState() at decision time.
  • pty-transport-types.ts — the optional retainDisposedSpawn transport option.
  • tests/e2e/ssh-reconnect-new-tab-liveness.spec.ts (new) — six rounds of reconnect → open tab → assert survival, binding, and echo liveness; registered in run-ssh-docker-e2e.mjs.

Verified the core claim against the main-side reservation (spawn.ts / spawn-options.ts): the reservation hands the same PTY only when the (worktree, connection, paneKey) owner key matches, which implies an identical leafId — so the retention predicate's use of the disposed session's leafId is consistent with the case the fix targets, and a divergent leafId correctly falls through to the existing kill. Triage found no parallel disposed-spawn orphan-kill path (the remote-runtime transport has its own recovery lifecycle and never calls connectIpcPty), so there is no uncovered sibling of this bug. The unit tests assert exact outcomes (toBe(true)/toBe(false)/not.toHaveBeenCalled()) and the documented mutation testing shows each is a real tripwire, not theatre.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

nwparker and others added 2 commits September 7, 2026 21:55
The round captured activeTabId after opening; if the open ever left the prior
(already live) tab active, the PTY and echo checks would pass against it. Record
the prior id and assert the new one differs.

Scope the resolved note to the measured cause: the disposed-spawn kill. The
persistent no-reconnect state in #17047 was not reproduced on it and stays open.
The retention guard was applied to every caller of the shared retirement
closure, including the one where a live transport refuses the id it was
handed (admitPtyId, the direct-SSH retry admission). That transport is the
pane's only one, so nothing else can own the PTY, and the guard always
answered "retain" there because the pane doing the refusing is live. Every
refused retry PTY would have leaked — the case #11003 added the kill for.

Split the two retirements: retireDisposedSpawn consults the pane surface,
killFreshSpawn does not. The admission tests now build the transport with
retainDisposedSpawn supplied, as installPtyInputRecovery does, so they fail
on the previous guard.

Exclude a worktree being deleted from retention: its tabs are still in the
store, but the teardown kills from the bound-id ledger, which never learned
an in-flight spawn's id.

Measured the preserved tab in ssh-reconnect-tab-destruction rather than
asserting it: 2 misses in 5 and 1 in 6 on this fix, with a live shell on the
host and an empty pane — a different shape, recorded as still open. The new
spec's loop pointed at a real Ubuntu host (ssh openclaw) was 4/4 live.

@pullfrog pullfrog 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.

ℹ️ No critical issues — the P1 split is correct and well-tested; one minor observation inline about the worktree-deletion exclusion.

Reviewed changes

Since the prior Pullfrog review (1cc6a79):

  • Split the disposed-spawn retirement into two closures. retireFreshSpawn became killFreshSpawn (the original #11003 kill, unconditional) plus retireDisposedSpawn (consults retainDisposedSpawn). The admitPtyId refusal path now calls killFreshSpawn, so a live transport that refuses its own fresh-fallback id is still killed — closing the P1 where the first revision would have leaked every refused direct-SSH retry PTY.
  • Added a worktree-deletion exclusion. shouldRetainDisposedPaneSpawn now takes a worktreeId and returns false while deleteStateByWorktreeId[worktreeId].isDeleting, so a PTY spawned during teardown isn't retained.
  • Hardened the refusal-path tests. The two reattach-admission tests build the transport the way installPtyInputRecovery does (retainDisposedSpawn: () => true) and still assert the refusal kills — they fail on the first revision's merged guard.
  • Made the liveness probe assert a new tab (records the active tab id before opening and asserts it changed) and dropped the un-reproduced #17047 claim in favor of a docs note.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

tabId: string,
leafId: string
): boolean {
if (state.deleteStateByWorktreeId?.[worktreeId]?.isDeleting) {

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.

The isDeleting exclusion keys by the bare worktree id, but deleteStateByWorktreeId is keyed host-qualified (hostId|id) for any deleted target carrying a hostId — every SSH/remote worktree (markWorktreesDeleting → getDeleteStateTargetKey, fed target.hostId ? target : target.id from worktree-delete-execution.ts). For a remote worktree the lookup misses, so the exclusion silently no-ops and a mid-spawn PTY is retained (leaked) rather than killed during teardown. Still leak-over-kill and reclaimable — not blocking — but the exclusion's stated purpose isn't met for SSH.

Technical details
# isDeleting exclusion no-ops for host-qualified (SSH/remote) worktrees

## Affected sites
- src/renderer/src/components/terminal-pane/pty-connection/disposed-spawn-retention.ts:24 — `deleteStateByWorktreeId?.[worktreeId]` uses the bare `session.deps.worktreeId`.
- src/renderer/src/store/slices/worktrees/teardown/worktree-delete-state.ts:17 — `getDeleteStateTargetKey` returns `getWorktreeHostIdentity(target)` when `target.hostId` is set.

## Required outcome
- The exclusion must also fire for an SSH/remote worktree being deleted, or the reason it is intentionally local-only must be documented.

## Suggested approach (optional)
- Look up both the host-qualified key and the legacy bare key (mirroring `getDeleteStateForWorktreeHost`), using the host id already available on the session.

## Open questions for the human (optional)
- Does the runtime `terminal.stop` teardown already reclaim remote PTYs, making the renderer-side exclusion unnecessary for SSH?

@coderabbitai

coderabbitai Bot commented Sep 8, 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.

@OrcaWin

OrcaWin commented Sep 24, 2026

Copy link
Copy Markdown
Collaborator

Superseded by #22578. It ports this PR's disposed-spawn retention fix and its unit tests onto current main, with credit to this PR. It came from a crash scan 22 user report of new SSH tabs getting killed, and it also adds tab-lifecycle breadcrumbs. The Docker SSH e2e specs from this PR were not ported. Thanks @nwparker for the original diagnosis and fix.

OrcaWin added a commit that referenced this pull request Sep 26, 2026
…as still spawning (#22578)

* fix(terminal): a pane disposed mid-spawn no longer kills its successor's shell

A new terminal tab whose pane remounts while its first pty:spawn is in flight
is handed the SAME PTY by main's pane-spawn reservation. The disposed first
transport then killed that PTY as an orphan, so the tab closed on pty-exit
(focus fell back to tab 1) or stayed bound to a dead shell. Reported on SSH
worktrees (scan 22).

A transport destroyed mid-spawn now asks the pane surface first and keeps the
PTY while the tab exists, the worktree is not being deleted, and any layout
still names the leaf (leak-over-kill). A live transport refusing the id via
admitPtyId still kills unconditionally (#11003).

Adds rate-limited, id-hashed crash breadcrumbs for the next report:
terminal_fresh_spawn_retired (killed vs retained), terminal_tab_pty_exit
(host kind, ms since spawn, synthetic), terminal_active_tab_auto_move
(active-terminal repair, createTab orphan sweep). The two duplicated tab
pty-exit handlers now share handleTerminalTabPtyExit, and the FNV id hash
used by two crumbs moves to crash-breadcrumb-id-hash.ts.

Ports and supersedes #19386 (disposed-spawn-retention and its unit tests,
credit to its author); its Docker SSH e2e specs are not included.

* fix(terminal): scope spawn retention to its host and keep the PR focused

---------

Co-authored-by: m4air <[email protected]>
@OrcaWin

OrcaWin commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator

Closing as fixed: #22578 landed this fix (a remounted new SSH tab keeps the shell its old pane was still spawning).

@OrcaWin OrcaWin closed this Oct 11, 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.

[Bug] Terminal does not open during an SSH connection. [Bug] SSH terminals stop opening after a while — new terminals only show a blinking cursor

2 participants