Skip to content

fix(ssh): stop terminal tabs disappearing after reconnect - #11892

Closed
siddqamar wants to merge 3 commits into
stablyai:mainfrom
siddqamar:fix/terminal-session-restore
Closed

siddqamar wants to merge 3 commits into
stablyai:mainfrom
siddqamar:fix/terminal-session-restore

Conversation

@siddqamar

@siddqamar siddqamar commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

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 launchAgent fallback 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

  • pnpm lint
  • pnpm typecheck
  • pnpm test
  • pnpm build
  • 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:node
  • pnpm run typecheck:web
  • Focused oxlint --deny-warnings
  • Focused oxfmt --check
  • pnpm run check:max-lines-ratchet
  • pnpm 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 lastKnown IDs.
  • Whether filtered reconnect state can cause unnecessary Zustand publications.
  • Whether blank reconnect titles can hide explicitly launched OMP or Codex agents.
  • Whether tab-level launchAgent metadata 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:

  1. Seed deferred reattach IDs when an SSH target disconnects.
  2. Preserve launched agent rows while reconnect titles are blank.
  3. Harden no-op handling, split-pane attribution, and multi-tab reconnect coverage.

…1791)

After laptop sleep, clearDirectSshTargetPtyBindings nulls tab.ptyId/ptyIds
but left lastKnown unused by pty-connection. Remounts with SSH already
connected then spawned blank shells instead of reattaching.

- Seed deferredSshSessionIdsByTabId from live/lastKnown session ids
- Merge seeds on clear and stale-invalidate paths for the target
- Cover disconnect clear, invalidate, and connected+deferred gate
…blyai#11791)

After SSH reconnect, agent hooks and OSC titles lag while PTYs are already
live. Blank titles dropped OMP/Codex tabs from the worktree card so the
sidebar showed fewer agents than open tabs.

- Fall back to tab.launchAgent for live PTYs with non-classifiable titles
- Leave plain shell tabs without launchAgent hidden
@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@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

🧹 Nitpick comments (1)
src/renderer/src/store/slices/direct-ssh-terminal-recovery.test.ts (1)

112-128: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add tracked PTY fallback coverage.

This test covers live-tab and last-known IDs. It does not cover ptyIdsByTabId[tab.id]?.[0].

Add a tab with ptyId: null, a tracked PTY ID, and a different last-known ID. Assert that the tracked PTY ID wins.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 58311eb5-878a-4cd3-8518-882a189837b5

📥 Commits

Reviewing files that changed from the base of the PR and between 340faaa and a394976.

📒 Files selected for processing (8)
  • src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts
  • src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts
  • src/renderer/src/components/terminal-pane/ssh-pane-connect-gate.test.ts
  • src/renderer/src/store/slices/direct-ssh-terminal-recovery-types.ts
  • src/renderer/src/store/slices/direct-ssh-terminal-recovery.test.ts
  • src/renderer/src/store/slices/direct-ssh-terminal-recovery.ts
  • src/renderer/src/store/slices/direct-ssh-terminal-retry.test.ts
  • src/renderer/src/store/slices/terminals.ts

@greptile-apps

greptile-apps Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

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: Adds resolveDirectSshReconnectSessionId to prefer the live PTY id over lastKnownRelayPtyIdByTabId, and seeds deferredSessionIdsByTabId in clearDirectSshTerminalBindings before nulling out tab bindings so the session id is captured while it is still alive.
  • terminals.ts: Applies mergeDeferredSshSessionIdsForTarget after 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 a launchAgent fallback path (guarded by allowLaunchAgentFallback, which is only true for 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
Loading

Reviews (2): Last reviewed commit: "fix(ssh): harden reconnect recovery edge..." | Re-trigger Greptile

Comment on lines +153 to +173
const entry: AgentStatusEntry = {
paneKey,
state: 'working',
prompt: rowLabel,
updatedAt: args.now,
stateStartedAt: args.now,
stateHistory: [],
agentType,
terminalTitle: title,
lastAssistantMessage: 'Idle',
...(orchestration ? { orchestration } : {})
}
return {
paneKey,
entry,
tab: args.tab,
agentType,
rowSource: 'live',
state: 'idle',
startedAt: 0
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Fallback entry has state: 'working' while the row has state: 'idle'

The synthesised AgentStatusEntry sets state: 'working' while the outer DashboardAgentRow sets state: 'idle'. This matches the existing non-fallback idle path (where entryState is always 'working' even for idle rows), but any consumer that inspects entry.state directly—rather than row.state—will see the agent as actively working during the reconnect window. If any badge or notification logic uses entry.state, it could surface a spurious "working" indicator until the real title arrives.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Avoid no-op disconnect publications, keep launch-agent fallback tab-scoped for split panes, and cover multi-tab SSH reconnect sidebar parity.
@siddqamar siddqamar changed the title Fix/terminal session restore fix(ssh): stop terminal tabs disappearing after reconnect Aug 1, 2026
@AmethystLiang
AmethystLiang requested a review from OrcaWin August 3, 2026 18:39
@nwparker nwparker removed the P1 label Aug 19, 2026
@OrcaWin

OrcaWin commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator

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.

@OrcaWin OrcaWin closed this Oct 11, 2026
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] Reconnecting to the remote machine doesn't load all terminals properly

4 participants