Repository navigation
fix(terminal): a remounted new SSH tab keeps the shell its old pane was still spawning - #22578
Conversation
…r'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.
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. Important Review skippedReview was skipped as selected files did not have any reviewable changes. ⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
📝 WalkthroughWalkthroughThe IPC PTY transport now uses a callback to decide whether to retain a fresh PTY that resolves after its pane is destroyed. The callback checks deletion state, tab presence, and layout membership. Disposed connections can retain an eligible PTY for a successor, while refused PTY IDs are still retired. Tests cover retention decisions, late spawn handling, and a successor receiving the same PTY ID. Priority: ➖ Normal Merge Risk: 🔵 Low · up to A refused cold-restore session may leave a PTY running without an owner. The issue is localized, but should be fixed or explicitly accepted before merging. Security Architecture ReviewSecurity architecture risk: 🟡 Moderate · up to The change prevents a remount from killing a shell that its replacement still needs. Refused spawns are still terminated, but it is unclear who cleans up a preserved shell if no replacement takes ownership and the tab later closes. Retained concerns
Security review detailsSecurity Blast Radius
Security Findings and Attack Paths
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Docstring CoverageExplanation Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 24 functions across 22 files. (1 skipped: 1 unsupported.) ✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
ℹ️ No critical issues — the core fix is sound and its regression tests genuinely fail without it (I neutered the
retainDisposedSpawnline and watched the repro plus the handoff test go red). Two defects in the new diagnostic/guard code are inline.
Reviewed changes
- Disposed-spawn retention (
ipc-pty-connect.ts,pty-connection/disposed-spawn-retention.ts,pty-connection/pty-input-recovery.ts):retireFreshSpawnnow takes adisposed | refusedpath. Only thedisposedpath consults the new store-backedretainDisposedSpawn()and may keep a PTY that main's pane-spawn reservation handed to a remounted successor; therefusedpath still kills unconditionally for #11003. Wired only for real panes (remote-runtime transport unchanged, no wire/RPC change). - Lifecycle breadcrumbs (
lib/terminal-tab-lifecycle-breadcrumbs.ts): rate-limited crumbs forterminal_tab_pty_exit,terminal_fresh_spawn_retired, andterminal_active_tab_auto_move, with hashed tab ids and redacted PTY ids. - Shared pty-exit handler (
components/terminal/terminal-tab-pty-exit.ts): replaces the two copy-pasted overlay/close handlers. - FNV hash extraction (
lib/crash-breadcrumb-id-hash.ts) and orphan-sweep crumb (store/terminals/terminal-tab-creation.ts), plus thessh-reconnect-source-recovery.mdRESOLVED section.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 8b4c5c4e-f424-459f-97e6-e94ab27f333a
📒 Files selected for processing (7)
docs/reference/ssh-reconnect-source-recovery.mdsrc/renderer/src/components/terminal-pane/ipc-pty-connect.tssrc/renderer/src/components/terminal-pane/pty-connection-fresh-spawn-guards.test.tssrc/renderer/src/components/terminal-pane/pty-connection/disposed-spawn-retention.test.tssrc/renderer/src/components/terminal-pane/pty-connection/disposed-spawn-retention.tssrc/renderer/src/components/terminal-pane/pty-connection/pty-input-recovery.tssrc/renderer/src/components/terminal-pane/pty-transport-types.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- docs/reference/ssh-reconnect-source-recovery.md
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.
| !spawnResult.coldRestore && | ||
| !context.ownsPtyId(spawnResult.id) | ||
| ) { | ||
| if (spawnResult.isReattach || spawnResult.coldRestore || context.ownsPtyId(spawnResult.id)) { |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
# Locate coldRestore producers and inspect their PTY allocation paths.
rg -n -C 6 --glob '*.ts' 'coldRestore\s*:' srcRepository: stablyai/orca
Length of output: 41199
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- daemon producer ---'
cat -n src/main/daemon/daemon-pty-spawn-result.ts | sed -n '1,180p'
printf '%s\n' '--- connect admission and retirement ---'
cat -n src/renderer/src/components/terminal-pane/ipc-pty-connect.ts | sed -n '1,145p'Repository: stablyai/orca
Length of output: 17323
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- cold-restore producer continuation ---'
cat -n src/main/daemon/daemon-pty-spawn-result.ts | sed -n '174,245p'
printf '%s\n' '--- createOrAttachSpawn declarations and implementations ---'
rg -n -C 5 --glob '*.ts' 'createOrAttachSpawn\s*\(' src/main
printf '%s\n' '--- coldRestore cache writes ---'
rg -n -C 5 --glob '*.ts' 'coldRestoreCache|buildColdRestorePayload|historySeeded' src/main/daemonRepository: stablyai/orca
Length of output: 40070
Retire refused cold-restore PTYs.
When admitPtyId rejects a newly created cold-restore session, retireFreshSpawn skips window.api.pty.kill because spawnResult.coldRestore is set. The connection returns without binding the PTY, so the PTY can remain running without an owner.
Keep the isReattach exemption for existing sessions, but remove the unconditional coldRestore exemption.
Suggested fix
- if (spawnResult.isReattach || spawnResult.coldRestore || context.ownsPtyId(spawnResult.id)) {
+ if (spawnResult.isReattach || context.ownsPtyId(spawnResult.id)) {📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if (spawnResult.isReattach || spawnResult.coldRestore || context.ownsPtyId(spawnResult.id)) { | |
| if (spawnResult.isReattach || context.ownsPtyId(spawnResult.id)) { |
There was a problem hiding this comment.
ℹ️ No critical issues — minor suggestions inline. The host-scoping change lands cleanly: I verified the new host-qualified assertions genuinely fail if the lookup is reduced back to a raw id, and the prior two review threads are now addressed.
Reviewed changes
Delta since the prior pullfrog review at a59ffb3b0c (head 8e7694a):
- Host-scoped disposed-spawn retention (
pty-connection/disposed-spawn-retention.ts,pty-connection/pty-input-recovery.ts): the delete-state lookup now tries the host-qualified key first, falls back to the raw id only for legacy entries, and honors a legacy entry only when its recordedexecutionHostIdmatches the pane's — so an SSH worktree removal is detected rather than missed. Assertions coverlocal,ssh:target, andruntime:paired. - Auxiliary diagnostics and the shared pty-exit handler were dropped (
terminal-tab-lifecycle-breadcrumbs.ts,crash-breadcrumb-id-hash.ts,terminal-tab-pty-exit.ts, the active-terminal-repair crumb, checks-panel/replay-guard hash extraction, orphan-sweep crumb), leaving the PR as the retention fix plus its tests and docs. No dangling references remain. - Refreshed against
main(mergec7a4725b6).
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| const deleteState = | ||
| (executionHostId | ||
| ? state.deleteStateByWorktreeId?.[composeWorktreeHostIdentity(executionHostId, worktreeId)] | ||
| : undefined) ?? state.deleteStateByWorktreeId?.[worktreeId] |
There was a problem hiding this comment.
This host-qualified-then-legacy delete-state resolution duplicates getDeleteStateForWorktreeHost (src/renderer/src/components/sidebar/worktree-delete-state-host-match.ts:5), which already performs the same qualified lookup with the same host scoping. Consider extracting that helper to a shared module and calling it with { id: worktreeId, hostId: executionHostId }, so the two copies cannot drift.
Technical details
# Duplicated delete-state host resolution
## Affected sites
- `src/renderer/src/components/terminal-pane/pty-connection/disposed-spawn-retention.ts:14-20` — hand-rolled qualified-then-raw lookup plus `executionHostId` match guard.
- `src/renderer/src/components/sidebar/worktree-delete-state-host-match.ts:5` — existing `getDeleteStateForWorktreeHost`, same semantics (verified equivalent for the qualified hit, the legacy hit, host-mismatch, and null-`executionHostId` cases).
## Required outcome
- One implementation of the host-qualified delete-state lookup; the retention predicate calls it rather than re-deriving the key.
## Suggested approach
- Move `getDeleteStateForWorktreeHost` to a shared (non-sidebar) module and call it from both sites, or add a sibling that takes `(worktreeId, executionHostId)` directly. AGENTS.md: "Reuse Before Reimplementing".
## Open questions for the human
- If the cross-feature import is the reason it was not reused, is a shared extraction worth the extra diff in this PR or a follow-up?
ELI5
Opening a terminal tab can kill its new shell if the screen is rebuilt while the shell starts. The discarded screen now leaves that shell for its replacement.
What Changed
Before, a disposed pane killed a newly spawned PTY even when main's spawn reservation had handed the same PTY to the replacement pane. That could close the new SSH tab and return the user to the first tab.
Now disposal checks the current tab, layout leaf and workspace deletion state on the pane's execution host before retiring the shell. A live pane that explicitly refuses the PTY still retires it. Host-qualified deletion entries also keep same-ID workspaces on different hosts separate.
Why
Disposal does not prove the shell is unwanted. The existing spawn reservation intentionally shares it with a replacement pane. Checking current ownership preserves that behavior while cleaning up shells whose tabs or leaves were removed. This covers local, WSL, SSH and folder workspaces without changing RPCs or remote wire formats.
Linked Issue
Supersedes #19386, which identified the same race. Report: https://stablygroup.slack.com/archives/C0B4PDCMPPT/p1790183212868609.
Visual Proof
N/A — process-lifetime race; before/after regression tests exercise both transports receiving the same PTY.
Testing
Refreshed against current main and tested on macOS with
ORCA_BACKGROUND_LAUNCH=1and two workers:ssh-conn@@pty-7; the fix passes.pnpm tc:web, changed-file oxlint, formatting andpnpm run check:code-quality:changedpassed.Review
Independent review found no remaining blockers in the reduced diff.
Agent skill upstream boundary
Notes
The trigger that rebuilds the pane in the field report is still unknown, and the separate report of focus switching while both tabs survive remains unexplained. A retained shell can outlive its tab if the tab closes before any replacement binds it; preserving possibly owned remote work is safer than killing it. No new diagnostics or UI refactors are included. No manual SSH or Windows run was performed; full CI must pass before merge.
Checklist