Skip to content

fix(terminal): stop the orphan sweep from deleting reconnecting terminals (#9911) - #10155

Merged
nwparker merged 1 commit into
mainfrom
nwparker/claude-gone
Jul 23, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/claude-gone

Conversation

@nwparker

@nwparker nwparker commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #9911 — "Terminal window auto-closing. Unable to recover." A terminal running Claude Code (or any agent) would suddenly vanish from the UI with no way to get it back, even though the underlying PTY was still alive in the background.

Root cause: two modules disagreed about what counts as a live PTY. The terminal retirement planner (collectPtyIdsForTab) treats a tab's reconnect maps — pendingReconnectPtyIdByTabId, lastKnownRelayPtyIdByTabId, deferredSshSessionIdsByTabId — as live PTY ownership (it will tear those sessions down when you close the tab). But the orphan sweep (getOrphanTerminalIds) judged liveness from only ptyIdsByTabId + the tab-row ptyId. After hydration or an SSH-relay drop, a tab's row ptyId/ptyIdsByTabId are cleared while the still-live session survives in a reconnect map. The sweep then classified that live tab as a dead orphan and hard-deleted it (tab + layout + scrollback) before reconnect could rebind it — irrecoverable, with the agent still running headless. This is the local, non-remote core of the bug (SSH/remote just widen the window).

The fix makes the orphan sweep and the legacy→unified migration filter judge liveness from the same "attached-or-reconnecting" definition the retirement planner uses, and closes the surrounding lifecycle gaps that could otherwise strand a stale reconnect entry (which would flip the fix into keeping a dead tab).

What changed

  • terminal-orphan-helpers.ts — new terminalTabHasReconnectablePty predicate: a tab is live if it has ptyIdsByTabId, a row ptyId, or an entry in any of the three reconnect maps. getOrphanTerminalIds uses it, so a reconnecting tab is never swept. (It deliberately does not trust persisted terminalLayoutsByTabId leaf bindings, which can outlive their session.)
  • tabs.ts — the reconcileWorktreeTabModel legacy-tab migration filter uses the same predicate, so a reconnecting tab whose unified entry is transiently missing is re-migrated into its group (renders + reconnects) instead of lingering invisibly.
  • ssh-target-cleanup.ts — removing an SSH target now also clears pendingReconnect + deferredSsh for its tabs (previously left stale), so the predicate can't keep a genuinely dead tab alive after target removal.
  • terminals.ts
    • clearTabPtyId now promotes a surviving pane into the single per-tab relay slot when the slot-owning pane exits (instead of clearing it) — otherwise a split tab's surviving live pane could be visible only in the layout leaf map and get swept on the next relay drop (data loss).
    • reconnectPersistedTerminals no longer defers a persisted session whose SSH target is known-absent (authoritative target list loaded and doesn't list it), so a removed-out-of-band target can't strand a reconnect entry.
  • worktrees.ts — bulk worktree purge omits the two reconnect maps too (they're now liveness-authoritative), matching the existing lastKnownRelay omission.

ELI5

Every terminal tab has a little "is this alive?" checker. When you're on a flaky/SSH connection, a tab briefly loses its direct phone line but keeps a "call me back on this number" sticky note. One part of the app (the tab-closer) knew that sticky note means "still alive — reconnecting." But the cleanup crew that removes dead tabs didn't read the sticky note, so it saw "no phone line = dead" and threw the whole tab in the trash — deleting your still-running Claude session with no undo.

This PR makes the cleanup crew read the same sticky notes the tab-closer reads, so a tab that's just reconnecting is never thrown away. It also tidies the sticky notes when they're genuinely stale (target removed, split-pane closed) so we don't keep a truly-dead tab around by mistake.

Proof of fix

Every fix ships a regression test that was verified to fail on the pre-fix code and pass after (git stash of the source-only change → test fails → restore → passes):

Scenario Test
Reconnecting tab (session only in a reconnect map) not swept; sweep still agrees with buildTerminalTabRetirementPlan terminal-orphan-helpers.test.ts
End-to-end: reconnecting tab survives reconcileWorktreeTabModel + re-migrates into the unified model tabs.test.ts
Stale layout-leaf-only tab is still swept (guards the deliberate exclusion) terminal-orphan-helpers.test.ts
SSH-target removal clears pendingReconnect ssh.test.ts
Split-pane relay-slot promotes a survivor → not orphaned after a relay drop store-cascades.test.ts
Known-absent SSH target no longer defers (present target still defers) terminals-hydration.test.ts
Bulk purge evicts the two reconnect maps bulk-worktree-purge-terminal-maps-leak.test.ts

Testing

  • pnpm typecheck (node + cli + web) — clean
  • pnpm test — full renderer store-slice suite 1917 tests / 120 files pass; renderer runtime 491 pass; targeted slot-consumer suites pass
  • oxlint on all changed files — clean
  • Added high-quality regression tests, each mutation-verified (fails without its fix)
  • pnpm build

AI Review Report

Ran a 6-round adversarial review loop with two independent frontier models (GPT-5.6-Sol at xhigh reasoning, and Claude Fable 5), each instructed to refute the fix — hunting correctness bugs, regressions, and edge cases, and to trace every cleanup path that could keep a tab row alive with a stale liveness signal. The loop converged on a CLEAN (converged) verdict from both reviewers, with a final round in which both reviewers additionally traced the component-level pane-mount reconnect paths (pty-connection.ts) and cross-checked each other's assumptions, finding nothing new. It caught four real edge cases that were fixed before merge:

  1. Persisted-layout leaves as false liveness (fable R1): an earlier draft trusted terminalLayoutsByTabId leaf bindings, which SSH-target removal leaves stale → would resurrect a dead tab. Fixed by excluding layout leaves from the predicate; added a regression test that a stale-layout-leaf-only tab is still swept.
  2. pendingReconnect not cleared on SSH-target removal (gpt R2): a hydration-race window left a stale entry → dead tab kept. Fixed in ssh-target-cleanup.ts.
  3. Split-pane relay-slot data loss (gpt R3): the single per-tab relay slot wasn't promoting a survivor when the slot-owning pane exited → a live pane could be swept on the next relay drop. Fixed in clearTabPtyId.
  4. Absent-target defer stranding (gpt R4): a target removed out-of-band could strand a deferredSsh entry that survives a failed reconnect → dead tab kept. Fixed with a guarded skip in reconnectPersistedTerminals.

Both reviewers independently verified: no import cycle, type-clean, genuine-death tabs still swept (every exact-clear site pairs clearTabPtyId with clearExitedPanePtyLayoutBinding, so a cleared PTY is always genuinely dead and the survivor logic keeps row/slot on a live sibling), no false-drop of legitimate reconnects, and every regression test fails on the pre-fix code (mutation-checked). Cross-platform compatibility was explicitly reviewed — the change is platform-agnostic renderer store logic with no shortcuts, labels, filesystem paths, shell behavior, or Electron main/preload surface touched; SSH id handling uses existing shared helpers.

Two non-defects were noted and confirmed out of scope (both pre-existing, neither introduced here): the ptyIdsByTabId: [''] length-check edge (no production producer creates it), and the absent-target "ghost tab" — which is intended, user-closable ghost-workspace UX (a tab left visible), the opposite failure mode from #9911's silent deletion.

Security Audit

No new input handling, command execution, path handling, auth, secrets, IPC surface, or dependencies. The change is pure renderer store-state reconciliation logic (Zustand slices) operating on already-trusted in-process session state — no external input is parsed or executed. SSH session ids are only compared for membership/scoping, never executed or used to construct commands. No security-relevant risk identified.

Notes

  • Cross-platform: no platform-specific code paths, keyboard shortcuts, labels, or filesystem paths are touched. Logic is identical on macOS/Linux/Windows; SSH id parsing uses the existing parseAppSshPtyId helper. No Electron main/preload surface changed.
  • Severity ordering of the fixes: the predicate + split-pane fixes prevent live-session data loss (the reported bug). The SSH-target-cleanup, absent-target-defer, and purge changes prevent the inverse — keeping a dead tab alive — which the broader predicate would otherwise risk.
  • The change is deliberately scoped to the orphan-sweep / reconnect-liveness contract; the broader terminal-session-management rewrite discussed in the issue thread is out of scope here.

…nals (#9911)

The orphan sweep judged tab liveness from ptyIdsByTabId + row ptyId only,
while the retirement planner treats the reconnect maps (pendingReconnect,
lastKnownRelay, deferredSsh) as live ownership. After hydration or an SSH
relay drop a live session survives only in a reconnect map, so the sweep
deleted the still-live tab (plus its layout and scrollback) before reconnect
could rebind it — the agent kept running headless with no way to recover.

Make orphan detection and the legacy->unified migration filter judge liveness
from the same attached-or-reconnecting definition (deliberately excluding
persisted layout-leaf bindings, which can outlive their session), and close
the lifecycle gaps that could otherwise strand a stale reconnect entry:

- clearTabPtyId promotes a surviving pane into the single per-tab relay slot
  on pane exit instead of clearing it (a split tab's live pane could otherwise
  survive only in the layout leaf map and be swept on the next relay drop)
- SSH-target removal clears pendingReconnect/deferredSsh for its tabs
- reconnectPersistedTerminals does not re-defer a session whose SSH target is
  known-absent (authoritative list loaded and no longer lists it)
- bulk worktree purge omits the reconnect maps too

Each fix ships a regression test verified to fail on the pre-fix code.
@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Terminal liveness detection now recognizes active and reconnect-related PTY mappings during orphan cleanup and tab reconciliation. Relay PTY clearing promotes a surviving PTY when available. SSH-target cleanup removes deferred and pending reconnect entries, while hydration skips sessions for absent targets. Bulk worktree purging removes the same reconnect maps for deleted tabs. Regression tests cover these behaviors and preserve state for surviving tabs.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. 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 is concise and accurately summarizes the main change: preventing orphan sweep from deleting reconnecting terminals.
Description check ✅ Passed The description is mostly complete and matches the template well; only the Screenshots section is missing.
✨ Finishing Touches
📝 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.

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] Remote - Terminal window auto-closing. Unable to recover

1 participant