Repository navigation
fix(terminal): stop the orphan sweep from deleting reconnecting terminals (#9911) - #10155
Merged
Merged
Conversation
…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.
Contributor
📝 WalkthroughWalkthroughTerminal 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)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 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 |
This was referenced Jul 27, 2026
enrick-dev
pushed a commit
to enrick-dev/orca
that referenced
this pull request
Oct 15, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 onlyptyIdsByTabId+ the tab-rowptyId. After hydration or an SSH-relay drop, a tab's rowptyId/ptyIdsByTabIdare 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— newterminalTabHasReconnectablePtypredicate: a tab is live if it hasptyIdsByTabId, a rowptyId, or an entry in any of the three reconnect maps.getOrphanTerminalIdsuses it, so a reconnecting tab is never swept. (It deliberately does not trust persistedterminalLayoutsByTabIdleaf bindings, which can outlive their session.)tabs.ts— thereconcileWorktreeTabModellegacy-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 clearspendingReconnect+deferredSshfor its tabs (previously left stale), so the predicate can't keep a genuinely dead tab alive after target removal.terminals.tsclearTabPtyIdnow 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).reconnectPersistedTerminalsno 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 existinglastKnownRelayomission.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 stashof the source-only change → test fails → restore → passes):buildTerminalTabRetirementPlanterminal-orphan-helpers.test.tsreconcileWorktreeTabModel+ re-migrates into the unified modeltabs.test.tsterminal-orphan-helpers.test.tspendingReconnectssh.test.tsstore-cascades.test.tsterminals-hydration.test.tsbulk-worktree-purge-terminal-maps-leak.test.tsTesting
pnpm typecheck(node + cli + web) — cleanpnpm test— full renderer store-slice suite 1917 tests / 120 files pass; renderer runtime 491 pass; targeted slot-consumer suites passoxlinton all changed files — cleanpnpm buildAI 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:terminalLayoutsByTabIdleaf 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.pendingReconnectnot cleared on SSH-target removal (gpt R2): a hydration-race window left a stale entry → dead tab kept. Fixed inssh-target-cleanup.ts.clearTabPtyId.deferredSshentry that survives a failed reconnect → dead tab kept. Fixed with a guarded skip inreconnectPersistedTerminals.Both reviewers independently verified: no import cycle, type-clean, genuine-death tabs still swept (every exact-clear site pairs
clearTabPtyIdwithclearExitedPanePtyLayoutBinding, 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
parseAppSshPtyIdhelper. No Electron main/preload surface changed.