fix(ssh): stop terminal tabs disappearing after reconnect
Summary
Fixes #11791.
- Preserve every tracked SSH terminal session when a target disconnects, allowing all tabs to reattach after reconnect.
- Keep launched agent rows visible while terminal titles and hooks are still rehydrating.
- Restrict the
launchAgentfallback to single-pane tabs so blank split panes are not misclassified as duplicate agents. - Avoid unnecessary Zustand publications when disconnect cleanup produces no state changes.
- Extend the Docker SSH reconnect test to cover multiple agent tabs, restored terminal execution, and sidebar agent-count parity.
Screenshots
No visual change.
Testing
- [x]
pnpm lint - [x]
pnpm typecheck - [x]
pnpm test - [x]
pnpm build - [x] Added or updated high-quality tests that would catch regressions, or explained why tests were not needed.
Focused checks completed
- Focused Vitest suites: 4 files and 51 tests passed.
pnpm run typecheck:nodepnpm run typecheck:web- Focused
oxlint --deny-warnings - Focused
oxfmt --check pnpm run check:max-lines-ratchetpnpm exec electron-vite build --mode e2e- The targeted Playwright spec compiles and registers successfully.
The Docker-backed test body could not execute locally because this host is Windows and the Docker Desktop daemon was unavailable.
AI Review Report
Reviewed the implementation against #11791 and the automated PR feedback.
The review checked:
- Whether disconnect cleanup preserves live and last-known relay PTY IDs for every affected SSH tab.
- Whether tracked PTY IDs correctly take precedence over stale
lastKnownIDs. - Whether filtered reconnect state can cause unnecessary Zustand publications.
- Whether blank reconnect titles can hide explicitly launched OMP or Codex agents.
- Whether tab-level
launchAgentmetadata can incorrectly attribute blank split panes. - Multi-tab reconnect behavior, folder workspaces, SSH routing, and Electron renderer state boundaries.
The no-op publication feedback was valid and has been fixed with focused regression coverage.
idle: The derived row state remains idle for sidebar presentation.
Cross-platform behavior was reviewed for macOS, Linux, and Windows. This change does not introduce platform-specific shortcuts, labels, paths, shell commands, or Electron execution-world changes. The production changes remain platform-neutral; only the Docker SSH E2E fixture is POSIX-gated.
Security Audit
- No new dependencies, IPC channels, authentication flows, or secret handling were introduced.
- No production shell commands or user-controlled command construction were added.
- Reconnect session IDs remain scoped to the affected SSH target and existing provider authority.
- No local-only filesystem assumptions were introduced.
- The E2E commands use the existing shell-quoting helper for generated markers and temporary remote proof paths.
No security follow-up is currently required.
Notes
The PR now contains three commits:
- Seed deferred reattach IDs when an SSH target disconnects.
- Preserve launched agent rows while reconnect titles are blank.
- Harden no-op handling, split-pane attribution, and multi-tab reconnect coverage.
📝 Walkthrough
Walkthrough
The change preserves deferred SSH relay session IDs during direct SSH binding cleanup, stale-binding invalidation, and target-scoped state updates. Reconnect gating can reattach deferred sessions when the target is already connected. Title-derived agent rows now use launch metadata to create idle rows for blank-title terminal tabs, while split-pane siblings and plain-shell tabs remain without inferred rows. Regression tests cover reconnect recovery, agent-row behavior, and two-tab end-to-end recovery.
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Docstring Coverage | ⚠️ Warning | Docstring coverage is 33.33% 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 | The changes address issue #11791 by restoring deferred SSH sessions, preserving agent rows, and testing multiple terminals after reconnect. |
| Out of Scope Changes check | ✅ Passed | The code and tests remain focused on SSH terminal recovery, launch-agent row correctness, and sidebar parity for issue #11791. |
| Title check | ✅ Passed | The title clearly summarizes the primary SSH reconnect fix that prevents terminal tabs from disappearing. |
| Description check | ✅ Passed | The description covers the required summary, screenshots, testing, AI review, security audit, and notes sections with relevant details. |
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 @coderabbitai help to get the list of available commands.
Greptile Summary
This PR fixes a terminal session restore bug (#11791) where SSH terminals would spawn a blank shell after disconnect/reconnect instead of reattaching to their previous session. It seeds deferredSshSessionIdsByTabId during disconnect cleanup so remounted panes can find their relay session, and adds a launchAgent fallback in the sidebar row builder to keep agent rows visible when the tab title is transiently blank during the reconnect window.
direct-ssh-terminal-recovery.ts: AddsresolveDirectSshReconnectSessionIdto prefer the live PTY id overlastKnownRelayPtyIdByTabId, and seedsdeferredSessionIdsByTabIdinclearDirectSshTerminalBindingsbefore nulling out tab bindings so the session id is captured while it is still alive.terminals.ts: AppliesmergeDeferredSshSessionIdsForTargetafter every binding-clear to push the seeds into store state, with a target-id filter to prevent foreign-connection entries from leaking across targets.worktree-title-derived-agent-rows.ts: Adds alaunchAgentfallback path (guarded byallowLaunchAgentFallback, which is onlytruefor single-pane tabs) so agent sidebar rows remain visible when the tab title arrives blank.
Confidence Score: 5/5
Safe to merge — the change is a targeted fix that adds a deferred-reattach seed during disconnect cleanup and a blank-title fallback in the sidebar, both well-guarded against multi-pane and foreign-target edge cases.
The disconnect-to-reattach path is clearly correct: session ids are captured before bindings are cleared, foreign-connection ids are filtered out by target, and Zustand state updates are skipped when nothing actually changes. The launchAgent fallback in the sidebar is gated to single-leaf tabs and falls through cleanly for splits. Unit tests cover the priority ordering, foreign-session no-op, second-clear re-seed, and split-sibling attribution guard. The E2E test exercises the full two-tab reconnect flow with sidebar row verification.
Files Needing Attention: No files require special attention.
Important Files Changed
| Filename | Overview |
|---|---|
| src/renderer/src/store/slices/direct-ssh-terminal-recovery.ts | Adds resolveDirectSshReconnectSessionId and seeds deferredSessionIdsByTabId before clearing bindings; logic and priority order (ptyId → ptyIdsByTabId[0] → lastKnown) are correct. |
| src/renderer/src/store/slices/terminals.ts | clearDirectSshTargetPtyBindings and invalidateStaleDirectSshTargetPtyBindings now merge deferred session ids with proper early-return guards; foreign-target filtering via mergeDeferredSshSessionIdsForTarget is correct. |
| src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts | allowLaunchAgentFallback correctly guards the launchAgent fallback to single-leaf tabs only; isTerminalLeafId check is correctly moved to an early-exit position. |
| src/renderer/src/store/slices/direct-ssh-terminal-recovery-types.ts | Adds deferredSessionIdsByTabId field to DirectSshTerminalBindingClearResult with clear documentation; backward-compatible addition. |
| tests/e2e/ssh-docker-relay-perf.spec.ts | E2E test expanded from 1 to 2 agent tabs, adds sidebar row count assertion, and simplifies the recovery script; changes are appropriate and reduce flakiness risk. |
Sequence Diagram
sequenceDiagram
participant SSH as SSH Target
participant Store as Zustand Store
participant Recovery as clearDirectSshTerminalBindings
participant Deferred as deferredSshSessionIdsByTabId
participant Gate as resolveSshPaneConnectGate
participant Pane as Terminal Pane
SSH->>Store: disconnect event
Store->>Recovery: clearDirectSshTargetPtyBindings(targetId)
Recovery->>Recovery: resolveDirectSshReconnectSessionId(state, tab)
Recovery-->>Store: "{ patch, deferredSessionIdsByTabId }"
Store->>Store: mergeDeferredSshSessionIdsForTarget(current, seeds, targetId)
Store->>Deferred: "write deferredSshSessionIdsByTabId[tabId] = sessionId"
Note over Store: tab.ptyId is now null
SSH->>Store: reconnect event
Store->>Pane: remount terminal pane
Pane->>Gate: "resolveSshPaneConnectGate({ sshStatus: connected, deferredTabSessionId })"
Gate-->>Pane: "{ pendingSessionId, enterDeferredFlow: true }"
Pane->>SSH: reattach to existing relay session
Reviews (2): Last reviewed commit: "fix(ssh): harden reconnect recovery edge..." | Re-trigger Greptile
Thanks @siddqamar for the fix and the extended Docker reconnect test. #11791 was closed as fixed, and since then the SSH relay has been removed: SSH terminals now live on Orca's managed remote server and reattach to it on reconnect. Closing; if tabs still go missing after a reconnect on a current build, please open a new issue with details.