Skip to content

fix(ssh): contain reattach to existing panes, quarantine orphans - #12743

Closed
AmethystLiang wants to merge 4 commits into
mainfrom
sta-3077-narrow-ssh-reattach-containment
Closed

AmethystLiang wants to merge 4 commits into
mainfrom
sta-3077-narrow-ssh-reattach-containment

Conversation

@AmethystLiang

Copy link
Copy Markdown
Contributor

Summary

SSH reattach now validates each remote PTY lease against durable pane state before restoring it, preventing cross-wiring to wrong panes or creating phantom entries. Unverified leases are quarantined to prevent revival on reconnect.

Changes

  • New resolveExistingSshPtyBinding(): Searches both SSH target and local partitions for durable pane bindings, preferring target partition when both exist
  • New quarantineSshRemotePtyLeasesAsync(): Marks orphaned leases as expired in one batched write per reattach pass
  • Modified persistPtyBinding(): Added mayCreate: false option to refuse creating panes during reattach; compare-and-set with expectedBinding detects post-attach races
  • New ssh-remote-pty-lease-selection.ts: Coalesces duplicate remote PTY identities and selects winner lease for reattach
  • SSH relay session: Validates each lease's durable pane before attach; batches quarantine writes; clears provider state for blocked PTYs

Fixes

STA-3077: Reattach no longer cross-wires to wrong panes or creates orphaned entries. Resolves incomplete legacy leases to pane identity before reattach. Prevents duplicate remote PTY identities from interfering with active sessions.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test — added comprehensive tests for lease coalescing, partition-aware pane resolution, quarantine rollback on failure, compare-and-set races, legacy lease resolution, and duplicate blocking across reconnects
  • pnpm build

Notes

  • Reattach is now read-only: cannot create or grow topology
  • Binds back to the partition the pane was resolved from, respecting SSH partition isolation and folder workspace cases
  • Quarantine deferred to batched write to avoid synchronous I/O per pane

Replace dry-run persistPtyBinding with explicit resolveExistingSshPtyBinding to validate pane identity exists and is unique. Support resolving incomplete legacy leases by matching against durable terminal layout state. Properly quarantine and block duplicates by deleting ownership records.
The renderer partitions SSH worktrees by hostId but collapses repo-only ownership
onto the local partition. When resolving panes for reattach, search both the target
and local partitions and bind each pane back to the partition where it was found.
Batch quarantine writes per reattach pass to avoid per-pane I/O overhead.
- Add compare-and-set validation to persistPtyBinding for stale detection
- Refuse reattach when pane was replaced or reassigned during resolution
- Reject conflicting pane copies across host partitions
- Coalesce duplicate remote PTY identities
- Make quarantine async and transactional with rollback
@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This change updates SSH PTY reattach and reconnect handling. The store now coalesces remote PTY leases by identity, enforces monotonic lease finality, resolves durable pane bindings across host partitions, and supports guarded persistPtyBinding writes that return 'bound' or 'refused'. Relay-session reattach now selects valid lease candidates, resolves existing bindings before attach, quarantines refused or duplicate leases, and defers durable quarantine writes until worker completion. The PR also adds extensive tests for binding containment, lease arbitration, reconnect races, legacy lease recovery, and quarantine failure handling.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description includes summary, testing, and notes, but omits the required Screenshots, AI Review Report, and Security Audit sections; the build check is also incomplete. Add all required template sections, state whether there is visual change, document the AI review and security audit, and complete or explain the build check.
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 (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: restricting SSH reattach to existing panes and quarantining orphaned leases.
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.
✨ Finishing Touches 💡 1
📝 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.

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

🧹 Nitpick comments (3)
src/main/persistence.ts (1)

6648-6661: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Extract the resolved-binding shape into a named type.

The same six-field object shape is declared inline at Line 6654 and again at Line 6698. src/main/ssh/ssh-relay-session.ts then derives ResolvedSshPtyBinding from ReturnType<Store['resolveExistingSshPtyBinding']>. A named exported type keeps the public and private shapes from drifting apart.

♻️ Proposed refactor
+export type ResolvedSshPtyBinding = {
+  worktreeId: string
+  tabId: string
+  leafId: string
+  hostId: ExecutionHostId
+  ptyId: string
+  incarnationId?: string
+}
+
   resolveExistingSshPtyBinding(args: {
     targetId: string
     ptyId: string
     worktreeId?: string
     tabId?: string
     leafId?: string
-  }): {
-    worktreeId: string
-    tabId: string
-    leafId: string
-    hostId: ExecutionHostId
-    ptyId: string
-    incarnationId?: string
-  } | null {
+  }): ResolvedSshPtyBinding | null {
src/main/ssh/ssh-relay-session.ts (1)

2342-2348: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Treating a thrown persistPtyBinding as 'bound' bypasses the containment guarantee.

When persistPtyBinding throws, the compare-and-set result is unknown. This code then continues as if the guarded bind succeeded, registers runtime state at Line 2351, and the caller sets PTY ownership at Line 2237. That is the cross-wiring case this change is meant to prevent.

The opposite choice also has a cost: a transient write failure would quarantine a pane whose remote shell is still running. If the current behavior is the intended trade-off, add a short Why comment stating it, because the surrounding code refuses every other unverified path.

src/main/ssh/ssh-relay-session-test-fixtures.ts (1)

30-40: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

The binding mock cannot detect a wrong PTY id form.

The mock echoes binding.ptyId back in the result. It accepts both the relay-form id (pty-live) and the app-form id (ssh:target-1@@pty-live). Production code calls this resolver with both forms, so the mock hides an id-form mismatch. Make the mock resolve only the app-form id, so a caller that passes a relay-form id gets null.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 814e8b84-2bfe-4a9b-bb07-4dbac9b92040

📥 Commits

Reviewing files that changed from the base of the PR and between eea0bb6 and bb1f41e.

📒 Files selected for processing (9)
  • src/main/persistence-ssh-reattach-containment.test.ts
  • src/main/persistence.ts
  • src/main/ssh/ssh-relay-session-reattach-quarantine.test.ts
  • src/main/ssh/ssh-relay-session-reconnect-incarnation.test.ts
  • src/main/ssh/ssh-relay-session-test-fixtures.ts
  • src/main/ssh/ssh-relay-session.test.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/main/ssh/ssh-remote-pty-lease-selection.test.ts
  • src/main/ssh/ssh-remote-pty-lease-selection.ts

@AmethystLiang

Copy link
Copy Markdown
Contributor Author

@coderabbitai Fixing. Will be in the next commit

@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@AmethystLiang Acknowledged. I will verify the fix after the next commit.

You are interacting with an AI system.

@nwparker

nwparker commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

Heads up — I've opened #13111 against the same defect, and I want to be upfront about the overlap rather than have two branches drift.

Your design caught a bug in mine. I was arbitrating duplicate leases by recency alone. Your prefers the durable pane binding over a newer unbound lease and leaves pane duplicates active until durable binding can arbitrate reattach describe the case I got wrong: when a newer lease exists that no pane is bound to, picking by recency retires the lease the pane is actually attached to and detaches a live terminal. I've adopted the deferral approach — supersession now leaves a bound predecessor alone and lets reattach arbitrate once the binding is available.

mayCreate: false is likewise the right shape, and I've used it. Every creating branch already sets terminalMembershipChanged, so refusing is a check rather than a new path.

What's different in #13111: it's rebased on current main (this branch is ~116 behind), it's ~180 production lines, and it also fixes the duplicate-agent family (#12448 etc.) — restoreRequired was being reported as SSH_SESSION_EXPIRED, and the reattach handler treated every error as proof of death, so a transient fault respawned a shell that resumed the same agent session.

What you have that I don't: host-partition resolution (target vs local spill, and conflicting copies across partitions), and rollback when a durable write fails mid-quarantine. Those are real gaps in mine.

Happy to go either way — fold your partition/rollback coverage into #13111, or rebase this one and close mine. Your call as the author; I'd rather not duplicate the work.

@OrcaWin

OrcaWin commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator

SSH still works: Orca connects to the host over SSH and routes workspace operations through the managed remote Orca server (orcad). These merges remove the legacy SSH relay, not SSH support.

Closing as obsolete after the merged SSH relay retirement in #27214 and #27215. This PR concerns the SSH relay PTY attach, recovery, replay, or lease lifecycle. #27214 removed the desktop relay connection/fallback path; #27215 deleted the SSH relay server, deployment assets, and relay-only tests. SSH hosts now use the managed Orca server (orcad), and unsupported hosts fail explicitly, so this relay-specific work is no longer planned. This closes the proposed relay implementation; it does not claim that any independent local, WSL, or managed-server behavior was fixed.

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

3 participants