Skip to content

fix(ssh): stop respawning panes on client-side-only absence evidence - #17957

Merged
nwparker merged 3 commits into
mainfrom
fix/respawn-gates-host-attested
Sep 3, 2026
Merged

nwparker merged 3 commits into
mainfrom
fix/respawn-gates-host-attested

Conversation

@nwparker

@nwparker nwparker commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​315 $\color{#cf222e}{\Huge{\mathbf{−}}}$​21 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​294
Prod 14 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​190 $\color{#cf222e}{\Huge{\mathbf{−}}}$​7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​183

Stacked on #17951 (fix/duplicate-agent-respawn-gate) — review that first. Closes the three remaining respawn gates that #17951's review found but did not touch.

ELI5

A pane may only restart a shell when the host says the shell is gone. These three gates restarted shells on evidence the client made up by itself. Restarting a live agent pane means two claude --resume on one transcript — the corruption #17951 and #11006/#9034 already fixed elsewhere.

The three gates are independently separable if you'd rather land them as three PRs; say the word.

Gate 1 — ipc-pty-connect.ts:186 — fixed, and this was the worst of the three

SSH_PTY_CONNECTION_MISMATCH_MARKER is minted by a pure string compare in ssh-pty-id.ts:51,64, before the relay is ever contacted. It reports that an id isn't addressable through this connection — never that a process died. It still returned sessionExpired: true, which routes to startFreshColdRestoreAgentResume: fresh PTY plus agent resume.

The corruption case is real, not theoretical: ssh-target-id-migration.ts exists because target ids get renumbered on re-adoption. A carrier the migration sweep misses arrives at connect holding an old-target ptyId and a new-target connectionId on the same machine — so the resume lands on the transcript the surviving PTY still owns.

No host exists to attest here, so it now routes to unverifiable: returns undefined, landing on recoverUnverifiableDirectSshReattach (remount + reattach, no shell restart). #7661's original no-toast outcome is preserved and still pinned.

Gate 3 — ssh-reconnect-pane-retry.ts:15 — fixed

!args.tabPtyId read tab.ptyId, which terminal-pty-bindings.ts:103 documents as "the single-pane fallback for legacy attach" — not the record of what's running. Two deterministic divergences (not races):

  • workspace-terminal-reconnect.ts fills ptyIdsByTabId from the leaf map but writes tab.ptyId only when a tab-level id survives, so a split SSH tab exits reconnect with live leaf PTYs and a null fallback field.
  • clearTransientTerminalState nulls tab.ptyId on every hydrated row unconditionally, and finalizeHydratedTerminalPanes runs the retry immediately after.

Now consults the real records (ptyIdsByTabId + layout leaf map), read from working so bindings the invalidation step just retired don't block a legitimate retry. This is a store reducer, so the host snapshot genuinely isn't in scope — noted in-comment.

Gate 2 — recoverTerminalPane — hardened, but the branch is inert. Do not read this as a live duplicate-spawn fix.

Leases are stored in relay form (toStoredPtyId → toRelaySshPtyId). getRecentExpiredSshLease compares that raw against the runtime's app-form pty.ptyId, so 'pty-3' === 'ssh:target@@pty-3' never holds and recoverTerminalPane always throws terminal_not_recoverable for a real SSH pane. toComparablePtyId sits unused right beside it. The existing line-358 test passes only because its fixture uses one non-SSH id on both sides.

This PR does not switch that path on — turning on a never-run spawn path is the opposite of this task. Filed separately, and it must land with an expired-semantics fix or it enables the duplicate spawns.

Kept (safe, enables nothing): recoverTerminalPane now also requires the liveness verdict to be neither live nor unverifiable; and ssh-relay-session.ts:2705 calls markPtyLivenessLive before its expired write, because that line sits below attachResult — pty.attach had just succeeded, so the host had proved the shell alive and we were discarding it.

Two findings that contradict earlier analysis in this sweep

The spawn-execute twins are correct as written. I changed both from the SSH_SESSION_EXPIRED substring match to an error-class check and backed it out — it broke 3 tests, including pty-runtime-ssh-binding-persistence.test.ts for runtime-owned/remote-paired SSH. Per AGENTS.md's remote-wire rules an error class does not survive that boundary; the message is the only carrier. The two twins are byte-identical in this logic and neither is defective.

Gating on terminated would be wrong, on three counts: it is also the operator-close state (ssh:terminateSessions), so it inverts the pinned test "does not recover a pane whose authoritative SSH lease was terminated" and would resurrect panes the user deliberately closed; finishPtyShutdown writes it without reliable attestation by its own comment; and nothing writes it for relay restart/renumber, the most common genuine-loss case, so those panes would never recover. Across all 8 expired writers, zero mean exit — the vocabulary is already split correctly. recoverTerminalPane just reads the wrong side.

User-facing regressions

None expected. Every gate has a negative control asserting the legitimate case still works:

  • Gate 1: a relay-attested SSH_SESSION_EXPIRED still yields sessionExpired: true, so a genuinely dead PTY still respawns.
  • Gate 3: a tab with no PTY in any record, and one whose records are empty slots, both still retry.
  • Gate 2: an SSH pane with hostExitConfirmed: true still recovers.

Testing

src/main/ssh + src/main/ipc/pty + src/main/providers: 3243 passed, 27 skipped. Renderer terminal-pane/slices/hooks + src/main/runtime: 14081 passed, 9 skipped. tc:node and tc:web clean; check:code-quality:changed 0 new findings across 17 files. Each gate has verbatim before/after in the commit.

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

Important

One finding worth addressing before merge: Gate 3's leafPtyIds reads a map the invalidation step never clears, so a genuinely-dead split tab after a relay renumber can be stranded instead of recovered. Everything else checks out.

Reviewed changes

  • Gate 1 — ipc-pty-connect.ts: splits the client-side belongs to SSH connection mismatch marker out of the sessionExpired branch; it now returns undefined, routing the pane to recoverUnverifiableDirectSshReattach (remount + reattach, no shell restart) while the relay-attested SSH_SESSION_EXPIRED still yields sessionExpired: true. I traced the undefined result through reattach-result-handler.ts and the deferred-attach flows — the no-pty-id branch correctly reaches recoverUnverifiableDirectSshReattach for a fresh, unbound transport.
  • Gate 2 — orca-runtime-resolve-terminal-pane.ts + ssh-relay-session.ts: recoverTerminalPane now refuses to spawn when the liveness verdict is live or unverifiable (host-confirmed exit leaves no verdict and still recovers), and ssh-relay-session.ts records markPtyLivenessLive before its expired write since the attach had just proven the shell alive. I checked the other getPtyLivenessVerdict consumers (stop-explicitly-closed-tab-ptys, unstopped-pty-verification); the live verdict is handled correctly there.
  • Gate 3 — ssh-reconnect-pane-retry.ts + direct-ssh-pane-retry-ledger.ts: the retry decision now consults ptyIdsByTabId and the layout leaf map rather than only the legacy tab.ptyId fallback, with negative controls covering split tabs and hydrated tabs whose tab.ptyId was nulled.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@greptile-apps

greptile-apps Bot commented Sep 2, 2026 •

Copy link
Copy Markdown

Too many files changed for review (917 files, 100 file limit).

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

✅ No new issues found.

Reviewed changes

  • Gate 3 — relay's own absence answer — main's handlePtyReattachFailure now publishes livenessVerdict: 'exited' on its not-found branch (the one place a reachable relay answered for the exact id and reported it absent), so host-attested absence is no longer collapsed into the -1 loss-of-contact sentinel. code stays -1, keeping isProvenProcessExit false and every existing reader untouched.
  • Renderer recording — a new pty-liveness-verdict-ipc-bridge records hostAttestedAbsentPtyIds from pty:exit verdicts independently of pane mount, so the reconnect gate has the host's answer even while no pane is mounted.
  • Gate 3 predicate — shouldRetryPaneSpawnOnSshReconnect now consults isPtyBindingStillAddressable, so an id the host disowned no longer counts as a bound PTY. This resolves the prior review's stale-leaf-map finding: a dead split tab after a relay renumber now respawns instead of being stranded by pre-restart leaf ids.
  • Settlement — updateTabPtyId omits the id (and its replacement) from the absence record when a PTY answers to it again, guarding against a stale record surviving a redeployed relay's renumber-from-pty-1.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker force-pushed the fix/duplicate-agent-respawn-gate branch from 89b32e0 to 5f259a7 Compare September 3, 2026 03:38
@nwparker
nwparker force-pushed the fix/respawn-gates-host-attested branch from cee0f16 to e3007b9 Compare September 3, 2026 03:38

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

✅ No new issues found.

Reviewed changes

  • Relay-disowned signal renamed for disownership, not exit — the pty:exit verdict on the not-found branch changed from livenessVerdict: 'exited' to ptySourceDisowned: true, the renderer record from hostAttestedAbsentPtyIds to disownedPtyIds, and markHostAttestedPtyAbsence to markPtySourceDisowned. Runtime behavior is unchanged (code stays -1; the flag drives the same reconnect gate via isPtyBindingStillAddressable), and the rename is complete and self-consistent — no stale livenessVerdict/hostAttestedAbsentPtyIds references survive.
  • Rebased onto fix/duplicate-agent-respawn-gate (#17951) — the SSH_PTY_SOURCE_RESTORE_REQUIRED retry-loop work now lives in the base, so this PR's diff is exactly the three respawn gates. I confirmed Gate 1's isSshSessionGoneError (now from the base) still excludes the identity-mismatch suffix, and a SSH_PTY_SOURCE_RESTORE_REQUIRED message cannot match it, so a live-PTY source restore never reads as session expiry.
  • Strengthened a negative test — ssh-relay-session.test.ts now asserts the relay-not-found-for-a-live-reattach path publishes no pty:exit for that id at all (objectContaining({ id })), guarding against the new flag spuriously reaching a path that must stay silent.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker changed the base branch from fix/duplicate-agent-respawn-gate to main September 3, 2026 04:05
Three respawn gates acted on evidence weaker than host-attested exit.
Per docs/reference/ssh-execution-boundary.md, loss of contact, a failed
reattach, an identity mismatch and absence from a client map are all
`unverifiable`, never `exited`.

Gate 1 (ipc-pty-connect.ts): "belongs to SSH connection" is minted by the
id router from a pure client-side string compare, before any relay is
asked, and still returned `sessionExpired: true` -> fresh PTY + agent
resume. After an SSH target re-adoption the "other" connection is the
same machine, so that puts a second `claude --resume` on the transcript
the surviving PTY still owns. Now returns undefined with no error, which
routes the pane to recoverUnverifiableDirectSshReattach (remount +
reattach, no shell restart) and keeps #7661's no-red-toast outcome.

Gate 3 (ssh-reconnect-pane-retry.ts): `!tabPtyId` read `tab.ptyId`, which
is only the single-pane fallback for legacy attach. It diverges from the
real records deterministically: workspace-terminal-reconnect fills
ptyIdsByTabId from the leaf map but writes tab.ptyId only when a
tab-level id survives, and clearTransientTerminalState nulls tab.ptyId on
every hydrated row. Both leave live leaf PTYs with a null fallback field,
arming a generation bump onto the fresh-spawn path. Now consults
ptyIdsByTabId and the layout leaf map too; a tab with no PTY in any
record still retries.

Gate 2 (recoverTerminalPane): an `expired` lease plus `!pty.connected`
authorized createTerminal. Every writer of `expired` records that the
CLIENT lost its route, not that the shell died. Now also requires the
runtime's own liveness verdict to be neither `live` nor `unverifiable`,
and ssh-relay-session records markPtyLivenessLive at the persistPtyBinding
refusal, which is reached only after pty.attach succeeded. See the report
for why this branch is currently unreachable for SSH panes.
Gate 3 refused to respawn a pane whose records still named a PTY, which is
right for a transport drop and wrong for a killed relay: after the relay is
SIGKILLed and comes back, the leaf map still holds `pty2:<dead-epoch>:1` while
the new relay answers that it has no such id. #18017's "replaces the pane only
when the host proves the session is gone" regressed on exactly that.

The gap was not the predicate, it was its inputs. `handlePtyReattachFailure`
already distinguishes the three reattach outcomes and only its not-found branch
publishes anything — a lost link and an identity mismatch send nothing. But it
published `pty:exit { code: -1 }`, and `-1` is the sentinel every reader
resolves to `stop_unverified`, so the one branch holding positive host evidence
of absence arrived looking exactly like loss of contact. The renderer had no
host answer at all, which the gate's own comment conceded.

The exit now carries `livenessVerdict: 'exited'` beside the unchanged `-1`, so
the code keeps meaning "no provable status" for every existing reader while the
verdict rides its own field. A store bridge records those ids in
`hostAttestedAbsentPtyIds` regardless of whether a pane is mounted to hear it —
during reconnect none is — and the gate stops counting a recorded id the host
has disowned. Settled when a PTY answers to that id again, because a redeployed
relay renumbers from pty-1.

This narrows #17963, which pinned the same exit as unverified on the grounds
that not-found cannot separate "verified the pid is dead" from "my session map
never had this id". Everything #17963 protects is untouched: `-1` still fails
isProvenProcessExit, so the tab is not closed, the pane's leaf binding is not
dropped on exit, and markUnverifiedPtyLoss still fires. Only the reconnect
respawn gate reads the new field, and only for an id whose sole channel — the
relay that answered — has disowned it, which no client can reach again under
any verdict. That is the reading ssh-pty-relay-absence-verdict.test.ts already
pins for the spawn path; the reconnect path now agrees with it.

Rejected: parsing the relay's mint epoch out of `pty2:<epoch>:<n>`. It needs the
current epoch on the wire (a capability-negotiated relay change), it has no
answer for legacy `pty-N` ids, and a relay that comes back with zero PTYs gives
the client no epoch to compare against. Rejected: clearing the leaf record
outright, because the remote workspace snapshot re-hydrates those ids after the
clear and the gate would refuse again.
@nwparker
nwparker force-pushed the fix/respawn-gates-host-attested branch from e3007b9 to 3b63dd8 Compare September 3, 2026 04:08
@coderabbitai

coderabbitai Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change distinguishes relay-confirmed PTY disownership from process termination. Relay exit events now carry an optional disowned-source marker through preload and renderer IPC into terminal store state. Terminal recovery uses PTY liveness verdicts before creating replacement shells. SSH reconnect retry logic evaluates tab and leaf PTY bindings against recorded disowned ids. Rebinding a PTY clears its disowned marker. Tests cover relay events, liveness-gated recovery, IPC registration, and reconnect retry decisions.

Merge Risk: 🟡 Moderate · up to 3b63d

SSH panes whose remote process has been confirmed exited may fail to recover and remain unavailable because their PTY identifier is not normalized before lease lookup. This should be corrected before merge.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 41.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 22 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: preventing pane respawns based only on client-side absence evidence.
Description check ✅ Passed The description is detailed, focused, and includes the problem, implementation scope, rationale, regression behavior, and test results. It does not follow every template heading, and it omits a dedica…
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.
Full details: Description check

Explanation

The description is detailed, focused, and includes the problem, implementation scope, rationale, regression behavior, and test results. It does not follow every template heading, and it omits a dedicated Linked Issue section and required visual proof or an explicit N/A statement.

  • Fix all pre-merge checks with AI
✨ 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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/main/runtime/orca-runtime-resolve-terminal-pane.ts (1)

81-82: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Normalize the PTY identifier before the lease lookup.

Line 81 passes the app-form PTY id to getRecentExpiredSshLease, but SSH leases use relay-form ids. Real SSH panes therefore cannot find their expired lease. Recovery rejects with terminal_not_recoverable even after a host-confirmed exit, so the replacement-shell path cannot run. Normalize the ID at the lookup boundary.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 068ab4f2-3e1f-4ad2-91fe-53700290d98f

📥 Commits

Reviewing files that changed from the base of the PR and between 76836b3 and 3b63dd8.

📒 Files selected for processing (22)
  • src/main/runtime/orca-runtime-resolve-terminal-pane.ts
  • src/main/runtime/orca-runtime-tests/terminal-handles.spec.ts
  • src/main/ssh/ssh-relay-orphan-abandon-paths.test.ts
  • src/main/ssh/ssh-relay-session.test.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/preload/api/pty-api.ts
  • src/preload/api/pty-bridge-stream-and-serialization.ts
  • src/renderer/src/components/terminal-pane/ipc-pty-connect.ts
  • src/renderer/src/components/terminal-pane/pty-connection/ssh-session-gone-verdict.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport-spawn-errors.test.ts
  • src/renderer/src/hooks/ipc-events/app-lifetime-ipc-bridge.ts
  • src/renderer/src/hooks/ipc-events/pty-source-disowned-ipc-bridge.ts
  • src/renderer/src/hooks/ssh-reconnect-pane-retry.test.ts
  • src/renderer/src/hooks/ssh-reconnect-pane-retry.ts
  • src/renderer/src/hooks/useIpcEvents-lifecycle.test.ts
  • src/renderer/src/store/slices/direct-ssh-pane-retry-ledger.ts
  • src/renderer/src/store/slices/direct-ssh-terminal-retry.test.ts
  • src/renderer/src/store/slices/terminals.ts
  • src/renderer/src/store/terminals/terminal-actions.ts
  • src/renderer/src/store/terminals/terminal-disowned-pty-sources.ts
  • src/renderer/src/store/terminals/terminal-pty-bindings.ts
  • src/renderer/src/store/terminals/terminal-state.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.

@nwparker
nwparker merged commit 64dac75 into main Sep 3, 2026
32 checks passed
nwparker added a commit that referenced this pull request Sep 3, 2026
… the pane

`expired` never means the remote shell exited. Every writer records that the
CLIENT lost its route — a superseded sibling, a recycled relay id, a
persistPtyBinding refusal made *after* pty.attach proved the shell alive, a
failed reattach indistinguishable from a relay restart, a relay reset whose
kill may not have landed. docs/reference/ssh-execution-boundary.md grades all
of those `unverifiable`.

Three readers treated it as death, and together they made the pane unable to
reach a process that is still running:

- `isRestorablePtyBinding` / `hasRestorableSshRemotePtyLease` refused to replay
  a durable binding a renderer snapshot had omitted.
- `markSshRemotePtyLease(s)` wiped the persisted pane->pty binding, which is
  what makes `resolvePersistedStablePaneOwner` return null, `adoptStablePane`
  give up, and `createTerminal` cold-spawn a replacement. The user's terminal
  comes back empty and the running job is orphaned and invisible.

Only `terminated` now withdraws a binding: it is the operator-close state
(`ssh:terminateSessions`) and the one written after a host-acknowledged stop.

This authorizes a reattach ATTEMPT, never a respawn, so #17957's gates are
untouched and in fact fire less often — where the pane previously went straight
to a fresh spawn it now attaches first. A genuinely dead shell still converges:
`attachStablePaneOwner` retires the binding on `isPtyAlreadyGoneError` (the
relay's own absence answer, not a message match) and falls through to a fresh
spawn, so no pane retries forever.

Supersession keeps its own binding scrub in `supersedeSiblingLeasesForPane`,
where a NEWER lease for the same pane is the evidence — the 2 -> 19 -> 20
reattach fan-out stays fixed.
nwparker added a commit that referenced this pull request Sep 3, 2026
…ng it (#17965)

* fix(ssh): let an expired lease permit a reattach instead of unbinding the pane

`expired` never means the remote shell exited. Every writer records that the
CLIENT lost its route — a superseded sibling, a recycled relay id, a
persistPtyBinding refusal made *after* pty.attach proved the shell alive, a
failed reattach indistinguishable from a relay restart, a relay reset whose
kill may not have landed. docs/reference/ssh-execution-boundary.md grades all
of those `unverifiable`.

Three readers treated it as death, and together they made the pane unable to
reach a process that is still running:

- `isRestorablePtyBinding` / `hasRestorableSshRemotePtyLease` refused to replay
  a durable binding a renderer snapshot had omitted.
- `markSshRemotePtyLease(s)` wiped the persisted pane->pty binding, which is
  what makes `resolvePersistedStablePaneOwner` return null, `adoptStablePane`
  give up, and `createTerminal` cold-spawn a replacement. The user's terminal
  comes back empty and the running job is orphaned and invisible.

Only `terminated` now withdraws a binding: it is the operator-close state
(`ssh:terminateSessions`) and the one written after a host-acknowledged stop.

This authorizes a reattach ATTEMPT, never a respawn, so #17957's gates are
untouched and in fact fire less often — where the pane previously went straight
to a fresh spawn it now attaches first. A genuinely dead shell still converges:
`attachStablePaneOwner` retires the binding on `isPtyAlreadyGoneError` (the
relay's own absence answer, not a message match) and falls through to a fresh
spawn, so no pane retries forever.

Supersession keeps its own binding scrub in `supersedeSiblingLeasesForPane`,
where a NEWER lease for the same pane is the evidence — the 2 -> 19 -> 20
reattach fan-out stays fixed.

* test(persistence): split SSH remote PTY binding partition cases into their own file
nwparker added a commit that referenced this pull request Sep 3, 2026
`getRecentExpiredSshLease` compared the stored lease ptyId (relay form,
written through `toStoredPtyId` -> `toRelaySshPtyId`) raw against the
runtime's app-form `pty.ptyId`, so `'pty-3' === 'ssh:target@@pty-3'` never
held and `recoverTerminalPane` refused every real SSH pane. Normalize with
the same tolerant helper the binding reader already uses, now shared as
`toComparableRelaySshPtyId`.

Switching the path on is only safe on top of #17957 (respawn gated on the
runtime liveness verdict), #17965 (`expired` no longer withdraws bindings)
and #17966 (supersession and id recycling carry their own marks).
`recoverTerminalPane` additionally refuses a lease those marks disqualify,
so it acts only on an `expired` lease that means "reattach gave up".

The path's outcome is a reattach, not a respawn: `createTerminal` calls
`adoptStablePane` first, which attaches attach-only to the retained
binding and only falls through to a fresh shell once the host itself
answers that the PTY is absent.
nwparker added a commit that referenced this pull request Sep 3, 2026
…17969)

`getRecentExpiredSshLease` compared the stored lease ptyId (relay form,
written through `toStoredPtyId` -> `toRelaySshPtyId`) raw against the
runtime's app-form `pty.ptyId`, so `'pty-3' === 'ssh:target@@pty-3'` never
held and `recoverTerminalPane` refused every real SSH pane. Normalize with
the same tolerant helper the binding reader already uses, now shared as
`toComparableRelaySshPtyId`.

Switching the path on is only safe on top of #17957 (respawn gated on the
runtime liveness verdict), #17965 (`expired` no longer withdraws bindings)
and #17966 (supersession and id recycling carry their own marks).
`recoverTerminalPane` additionally refuses a lease those marks disqualify,
so it acts only on an `expired` lease that means "reattach gave up".

The path's outcome is a reattach, not a respawn: `createTerminal` calls
`adoptStablePane` first, which attaches attach-only to the retained
binding and only falls through to a fresh shell once the host itself
answers that the PTY is absent.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…tablyai#17957)

* fix(ssh): stop respawning panes on client-side-only absence evidence

Three respawn gates acted on evidence weaker than host-attested exit.
Per docs/reference/ssh-execution-boundary.md, loss of contact, a failed
reattach, an identity mismatch and absence from a client map are all
`unverifiable`, never `exited`.

Gate 1 (ipc-pty-connect.ts): "belongs to SSH connection" is minted by the
id router from a pure client-side string compare, before any relay is
asked, and still returned `sessionExpired: true` -> fresh PTY + agent
resume. After an SSH target re-adoption the "other" connection is the
same machine, so that puts a second `claude --resume` on the transcript
the surviving PTY still owns. Now returns undefined with no error, which
routes the pane to recoverUnverifiableDirectSshReattach (remount +
reattach, no shell restart) and keeps stablyai#7661's no-red-toast outcome.

Gate 3 (ssh-reconnect-pane-retry.ts): `!tabPtyId` read `tab.ptyId`, which
is only the single-pane fallback for legacy attach. It diverges from the
real records deterministically: workspace-terminal-reconnect fills
ptyIdsByTabId from the leaf map but writes tab.ptyId only when a
tab-level id survives, and clearTransientTerminalState nulls tab.ptyId on
every hydrated row. Both leave live leaf PTYs with a null fallback field,
arming a generation bump onto the fresh-spawn path. Now consults
ptyIdsByTabId and the layout leaf map too; a tab with no PTY in any
record still retries.

Gate 2 (recoverTerminalPane): an `expired` lease plus `!pty.connected`
authorized createTerminal. Every writer of `expired` records that the
CLIENT lost its route, not that the shell died. Now also requires the
runtime's own liveness verdict to be neither `live` nor `unverifiable`,
and ssh-relay-session records markPtyLivenessLive at the persistPtyBinding
refusal, which is reached only after pty.attach succeeded. See the report
for why this branch is currently unreachable for SSH panes.

* fix(ssh): let the respawn gate see the relay's own absence answer

Gate 3 refused to respawn a pane whose records still named a PTY, which is
right for a transport drop and wrong for a killed relay: after the relay is
SIGKILLed and comes back, the leaf map still holds `pty2:<dead-epoch>:1` while
the new relay answers that it has no such id. stablyai#18017's "replaces the pane only
when the host proves the session is gone" regressed on exactly that.

The gap was not the predicate, it was its inputs. `handlePtyReattachFailure`
already distinguishes the three reattach outcomes and only its not-found branch
publishes anything — a lost link and an identity mismatch send nothing. But it
published `pty:exit { code: -1 }`, and `-1` is the sentinel every reader
resolves to `stop_unverified`, so the one branch holding positive host evidence
of absence arrived looking exactly like loss of contact. The renderer had no
host answer at all, which the gate's own comment conceded.

The exit now carries `livenessVerdict: 'exited'` beside the unchanged `-1`, so
the code keeps meaning "no provable status" for every existing reader while the
verdict rides its own field. A store bridge records those ids in
`hostAttestedAbsentPtyIds` regardless of whether a pane is mounted to hear it —
during reconnect none is — and the gate stops counting a recorded id the host
has disowned. Settled when a PTY answers to that id again, because a redeployed
relay renumbers from pty-1.

This narrows stablyai#17963, which pinned the same exit as unverified on the grounds
that not-found cannot separate "verified the pid is dead" from "my session map
never had this id". Everything stablyai#17963 protects is untouched: `-1` still fails
isProvenProcessExit, so the tab is not closed, the pane's leaf binding is not
dropped on exit, and markUnverifiedPtyLoss still fires. Only the reconnect
respawn gate reads the new field, and only for an id whose sole channel — the
relay that answered — has disowned it, which no client can reach again under
any verdict. That is the reading ssh-pty-relay-absence-verdict.test.ts already
pins for the spawn path; the reconnect path now agrees with it.

Rejected: parsing the relay's mint epoch out of `pty2:<epoch>:<n>`. It needs the
current epoch on the wire (a capability-negotiated relay change), it has no
answer for legacy `pty-N` ids, and a relay that comes back with zero PTYs gives
the client no epoch to compare against. Rejected: clearing the leaf record
outright, because the remote workspace snapshot re-hydrates those ids after the
clear and the gate would refuse again.

* refactor(ssh): name the relay-disowned signal for disownership, not exit
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…ng it (stablyai#17965)

* fix(ssh): let an expired lease permit a reattach instead of unbinding the pane

`expired` never means the remote shell exited. Every writer records that the
CLIENT lost its route — a superseded sibling, a recycled relay id, a
persistPtyBinding refusal made *after* pty.attach proved the shell alive, a
failed reattach indistinguishable from a relay restart, a relay reset whose
kill may not have landed. docs/reference/ssh-execution-boundary.md grades all
of those `unverifiable`.

Three readers treated it as death, and together they made the pane unable to
reach a process that is still running:

- `isRestorablePtyBinding` / `hasRestorableSshRemotePtyLease` refused to replay
  a durable binding a renderer snapshot had omitted.
- `markSshRemotePtyLease(s)` wiped the persisted pane->pty binding, which is
  what makes `resolvePersistedStablePaneOwner` return null, `adoptStablePane`
  give up, and `createTerminal` cold-spawn a replacement. The user's terminal
  comes back empty and the running job is orphaned and invisible.

Only `terminated` now withdraws a binding: it is the operator-close state
(`ssh:terminateSessions`) and the one written after a host-acknowledged stop.

This authorizes a reattach ATTEMPT, never a respawn, so stablyai#17957's gates are
untouched and in fact fire less often — where the pane previously went straight
to a fresh spawn it now attaches first. A genuinely dead shell still converges:
`attachStablePaneOwner` retires the binding on `isPtyAlreadyGoneError` (the
relay's own absence answer, not a message match) and falls through to a fresh
spawn, so no pane retries forever.

Supersession keeps its own binding scrub in `supersedeSiblingLeasesForPane`,
where a NEWER lease for the same pane is the evidence — the 2 -> 19 -> 20
reattach fan-out stays fixed.

* test(persistence): split SSH remote PTY binding partition cases into their own file
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…tablyai#17969)

`getRecentExpiredSshLease` compared the stored lease ptyId (relay form,
written through `toStoredPtyId` -> `toRelaySshPtyId`) raw against the
runtime's app-form `pty.ptyId`, so `'pty-3' === 'ssh:target@@pty-3'` never
held and `recoverTerminalPane` refused every real SSH pane. Normalize with
the same tolerant helper the binding reader already uses, now shared as
`toComparableRelaySshPtyId`.

Switching the path on is only safe on top of stablyai#17957 (respawn gated on the
runtime liveness verdict), stablyai#17965 (`expired` no longer withdraws bindings)
and stablyai#17966 (supersession and id recycling carry their own marks).
`recoverTerminalPane` additionally refuses a lease those marks disqualify,
so it acts only on an `expired` lease that means "reattach gave up".

The path's outcome is a reattach, not a respawn: `createTerminal` calls
`adoptStablePane` first, which attaches attach-only to the retained
binding and only falls through to a fresh shell once the host itself
answers that the PTY is absent.
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.

1 participant