Skip to content

fix(terminal): a remounted new SSH tab keeps the shell its old pane was still spawning - #22578

Merged
OrcaWin merged 4 commits into
mainfrom
fix/scan22-ssh-second-tab
Sep 26, 2026
Merged

OrcaWin merged 4 commits into
mainfrom
fix/scan22-ssh-second-tab

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​253 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​251
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​69 $\color{#cf222e}{\Huge{\mathbf{−}}}$​11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​58

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

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

Refreshed against current main and tested on macOS with ORCA_BACKGROUND_LAUNCH=1 and two workers:

  • Main's original connect implementation fails the shared-PTY regression by killing ssh-conn@@pty-7; the fix passes.
  • Five host-deletion regression assertions fail before the host-qualified guard and pass afterward.
  • Five core suites: 54 tests passed. Eight adjacent disposal, reconnect, resume and attachment suites: 86 tests passed.
  • pnpm tc:web, changed-file oxlint, formatting and pnpm run check:code-quality:changed passed.

Review

Independent review found no remaining blockers in the reduced diff.

Agent skill upstream boundary

  • Not applicable; no upstream skill code or resources copied.

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

  • This PR is small and focused
  • I explained what changed and why
  • Visual proof provided, or N/A with reason
  • Self-reviewed for correctness, security and performance
  • Cross-platform, SSH/remote and path/shortcut impact considered
  • Full CI passes; targeted tests and checks passed locally

…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.
@coderabbitai

coderabbitai Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 18f802bc-18ba-43c2-b1d1-4c14663ef071

📥 Commits

Reviewing files that changed from the base of the PR and between 8e7694a and 978dd45.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The 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 8e769

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 Review

Security architecture risk: 🟡 Moderate · up to 8e769

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

  • Medium · security · inferred: A disposed pane can preserve a fresh PTY before binding or publishing it. If no successor adopts it and the tab subsequently closes, cleanup of that process is not established; an SSH shell or its commands may remain running beyond the tab’s lifetime.
Security review details

Security Blast Radius

  • inferred — The plausible exposure is an already-authorized terminal process, including an SSH-hosted process, surviving beyond its visible tab. The evidence does not establish a new unauthenticated entrypoint or cross-tenant authority.

Security Findings and Attack Paths

  • inferred — If a retained spawn is not adopted and its tab later closes, it may remain an unbound running shell; provider-side or tab-close cleanup for that sequence has not been verified. The sequence requires an existing authorized spawn and a disposal or remount race.

Trust Boundaries and Controls

  • observed — Explicit-close handling, reattach and current-owner checks precede retention. Admission refusal cannot use the new callback to preserve its PTY.

Resilience and Maintainability Implications

  • observed — A successor can adopt the earlier spawn’s PTY ID, and the predecessor’s late completion does not kill that owned ID. This addresses the reported remount failure without relaxing the refusal path.

Hardening Proposals

  • proposed — Give a retained, unbound PTY an explicit, incarnation-safe owner or cancellable handoff lease, and verify retirement when the tab closes without adoption on both local and SSH paths.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning 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:… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly identifies the terminal race and the affected remounted SSH tab. It is specific and aligned with the primary change.
Description check ✅ Passed The description is complete and explains the user impact, implementation, rationale, linked issue, testing, limitations, and checklist status. It clearly notes that manual SSH or Windows testing and f…
Full details: Docstring Coverage

Explanation

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 💡
  • Commit to this branch
  • Create a new PR

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.

@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 core fix is sound and its regression tests genuinely fail without it (I neutered the retainDisposedSpawn line 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): retireFreshSpawn now takes a disposed | refused path. Only the disposed path consults the new store-backed retainDisposedSpawn() and may keep a PTY that main's pane-spawn reservation handed to a remounted successor; the refused path 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 for terminal_tab_pty_exit, terminal_fresh_spawn_retired, and terminal_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 the ssh-reconnect-source-recovery.md RESOLVED section.

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

@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: Advanced

Run ID: 8b4c5c4e-f424-459f-97e6-e94ab27f333a

📥 Commits

Reviewing files that changed from the base of the PR and between a59ffb3 and 8e7694a.

📒 Files selected for processing (7)
  • 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-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)) {

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.

🩺 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*:' src

Repository: 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/daemon

Repository: 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.

Suggested change
if (spawnResult.isReattach || spawnResult.coldRestore || context.ownsPtyId(spawnResult.id)) {
if (spawnResult.isReattach || context.ownsPtyId(spawnResult.id)) {

@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 — 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 recorded executionHostId matches the pane's — so an SSH worktree removal is detected rather than missed. Assertions cover local, ssh:target, and runtime: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 (merge c7a4725b6).

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

Comment on lines +14 to +17
const deleteState =
(executionHostId
? state.deleteStateByWorktreeId?.[composeWorktreeHostIdentity(executionHostId, worktreeId)]
: undefined) ?? state.deleteStateByWorktreeId?.[worktreeId]

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.

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?

@OrcaWin
OrcaWin merged commit d9bc757 into main Sep 26, 2026
29 of 30 checks passed
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