Skip to content

fix(ssh): a reattach may bind a pane but never create one - #16751

Merged
nwparker merged 1 commit into
mainfrom
nwparker/ssh-05-reattach-fence
Aug 28, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/ssh-05-reattach-fence

Conversation

@nwparker

@nwparker nwparker commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​376 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​376
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​172 $\color{#cf222e}{\Huge{\mathbf{−}}}$​4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​168

Stack: 5 of 6 — based on #16750.

Read this first: this restores a mechanism that landed and was reverted twice. The revert chain is summarised below, and the one thing both prior attempts lacked is the second bullet of the fix.

Symptom

An SSH reconnect rewrites deleted pane state from stale leases: tabs the user closed are grafted back, close tombstones are erased, and duplicate pane leases accumulate. Canceled ticket STA-4268 (P0) states the mechanism exactly:

"Leases have no pane incarnation and upsert only by target/PTY. Every nonterminal lease is reattached; frozen coordinates are passed to persistPtyBinding, which creates and flushes missing tabs and layout leaves."

Root cause

reattachKnownPtys treats every non-terminated lease as live and calls persistPtyBinding, which had no way to say "bind only". Two of its branches then rebuild UI nobody asked for:

  • src/main/persistence/loading-store/pty-binding-persistence.ts:133-143 — if (args.incarnationId) unconditionally deletes the pane's close tombstone.
  • :145-160 — on a tab-not-found it mints one via createMinimalPersistedTerminalTab. The in-code comment names its only intended caller: "pty:spawn can beat the debounced writer." Spawn. There was no guard, so reattach took the same branch.

Separately, upsertSshRemotePtyLease matched (targetId, ptyId) alone (src/main/persistence/leasing-ssh-ptys/ssh-pty-lease-operations.ts:34-36), so a new relay pty id on the second reattach minted a SECOND lease instead of updating the first, leaving the predecessor non-terminated with nothing to retire it.

Revert history — please read before reviewing. #13326 landed this; #14361 reverted it (−23,088, 165 files); #14384 re-applied it (+23,281); #14395 reverted again — opened and merged nine seconds apart, empty commit body. Five readiness tickets filed against that revert (STA-4268, STA-4272, STA-4357, STA-4446, STA-4661) were all canceled while automated counsel re-proved the defect on three consecutive dailies; STA-4661 went through 4-seat counsel and was classified "release-blocking, revert-class." grep -rn "mayCreate" src/ returns nothing on main — the mechanism is genuinely out of the tree. #13324/#13325 are attempt three, untouched since 08-09.

The fix, and why this shape

+160 production lines across 5 files.

  1. mayCreate, default true. When false, one pre-mutation check mirrors all four creating branches (mint a tab, mint a root leaf, split the root and graft a leaf, mint a layout) and returns false without mutating, so a refusal leaves nothing half-written.

  2. The authority gate — the part both prior attempts lacked, and probably why both were reverted. mayCreate: false alone refuses in two situations: "the user closed it" and "the renderer has not published its layout yet". The second is routine on disconnect→reconnect and is almost certainly the revert(ssh): back out #13326 and #13928 — reconnect loses every tab #14361 tab-loss mechanism. The fence was not wrong; it was UNCONDITIONED. It is now passed only when hasHostAuthoritativeTerminalMembership() says the persisted membership speaks for this worktree — reusing the function already guarding the same question at orca-runtime.ts:8608. Losing a tab is worse than keeping a duplicate, so an unauthoritative session still gets the creating write.

    Authority is read from the local partition because that is the partition this write lands in — it is local's absence being interpreted. But a pane the ssh:<target> partition still holds is not gone, so it keeps its creating write; refusing there would strand a live pane behind a binding reattach can no longer reach. (This is the GH SSH host session partitions are written but never read — tab lists round-trip as empty and remote sync permanently deletes them #12721/Renderer and runtime disagree on which partition owns SSH worktree session state #12723 / STA-3980 partition split-brain. This PR does not fix it; it refuses to judge from one side of it.)

  3. findTerminalTabIdForLeaf — bind resolves the tab from the live layout instead of the lease's frozen tabId. Only the leaf half of a pane key is remint-stable: detachTerminalPaneToTab moves a live pane into a new tab, so a stored tabId names the tab the pane left. Identity vs location.

  4. Pane-keyed supersession — retires siblings on (targetId, worktreeId, leafId) to expired, guarded by the durable binding, which reads local then ssh:<target> so it is correct whichever partition the binding landed in.

On refusal the lease goes expired, never terminated, and the remote shell is left running. expired records that this shell has no surface to reach it through; terminated would assert an exit nothing here observed, which docs/reference/ssh-execution-boundary.md forbids.

Evidence

A/B on this tree: disable the authority gate (mayCreate = true) and the supersession call by hand.

 × does not resurrect a tab whose closing pty.kill failed with a transport error
 × refuses to graft a second leaf into a tab the reattach does not already own
 × treats a raised topology revision as the authority that makes absence a close
 × retires the predecessor when a pane re-leases under a new relay pty id
 × marks the superseded lease expired rather than terminated
 × holds the live lease count flat across ten reconnects of one pane
     AssertionError: expected [ 'pty-0', 'pty-1', 'pty-2', …(7) ] to deeply equal [ 'pty-9' ]
 × supersedes across a tab change, because the leaf is the pane identity
 × does not supersede a different pane in the same worktree

 Test Files  1 failed (1)
      Tests  8 failed | 4 passed (12)

That [ 'pty-0' … 7 more ] vs [ 'pty-9' ] is the lease-accumulation mechanism in miniature. The 4 that pass both ways are the over-refusal tripwires, which is the point of having them.

Restored:

 Test Files  1 passed (1)      Tests  12 passed (12)
 Test Files 178 passed | 2 skipped (180)
      Tests  2439 passed | 14 skipped (2453)   # src/main/ssh, src/main/persistence, src/main/runtime/workspace-session

$ pnpm tc → clean
$ pnpm run check:code-quality:changed → 0 new findings across 30 changed files

Honesty about scope — this is NOT the fix for the daily tab growth

The deterministic e2e repro (ssh-lost-kill-tab-resurrection.spec.ts, PR 6 of this stack) is byte-identical before and after this change — not a partial improvement, no change at all. Instrumentation shows why: in that scenario restoreReattachedPtyRuntime is never called (CREATING TAB 9 hits, reattach gate 0, BYPASS 0). The fence is on a path that bug does not take. Build provenance was verified positively, not by mtime: mayCreate appears 3× in out/main/index.js for the fenced build and 0× for every control run.

This is a real, separately-provable defect with an A/B control behind it. It must not be claimed as the fix for the user report, and this PR does not claim it. PR 6 is the one that closes that.

Deliberately NOT done

Still unfixed, carried forward

attachIdentityMismatches (src/relay/pty-handler.ts:399) still compares tabId, and expectedIdentityForLease (ssh-relay-session.ts:197) composes its paneKey from the frozen tabId. That refusal maps to SSH_SESSION_EXPIRED, which authorises a respawn onto a shell just proved alive. #14384 fixed it; eb22e49 reverted it; it never came back. It needs its own PR.

The revert-class risk changes shape rather than disappearing

Both prior reverts (#14361, #14395) were for tab loss. The authority gate is what stops that
recurrence, and four of the twelve tests are over-refusal tripwires.

But a wrong refusal here has a different signature, and a reviewer should weigh it deliberately
rather than assume the old one is the only one: refusing to bind leaves the lease expired and the
remote shell still running with no surface to reach it through — an orphaned remote writer, the
thread <uuid> already has an active writer shape #16752's own body cites from a user report. The
user does not lose a tab; they lose the ability to reattach to work that is still alive, and a later
reattach can collide with the orphan.

That is why refusal is gated on hasHostAuthoritativeTerminalMembership and on the pane being
absent from both partitions, and why the lease goes expired rather than terminated — the remote
process is deliberately left running so it remains recoverable.

Risk / blast radius

Main-process, SSH reattach path only. mayCreate defaults true, so every genuine-create caller (pty:spawn, stable-pane adoption, runtime spawn-commit) is unchanged by construction — enumerated below. Given the revert history, the specific risk to weigh is over-refusal losing a user's tab, which is what the authority gate exists to prevent and what four of the twelve tests assert directly.

Path Entry Fenced?
Relay bulk reattach reattachKnownPtys → restoreReattachedPtyRuntime (:2247/:2548) yes, now
Targeted single-PTY recovery reattachRejectedPty (:1960) yes — same function
Renderer pane-retry / cold spawn pty:spawn → reattachSshPtySession → pty.attach genuine create, default true
Stable-pane adoption attachStablePaneOwner genuine create, default true
Runtime/headless spawn-commit runtime/spawn-commit.ts:163 genuine create, default true

There is no separate wake-sweep binder; sleep/wake re-enters via reattachKnownPtys.

How to verify

pnpm test src/main/ssh-reattach-pane-cardinality.test.ts

To reproduce the defect: set mayCreate to true in ssh-relay-session.ts and comment out the supersedeSiblingLeasesForPane(operations, next, now) call in ssh-pty-lease-operations.ts:139, then re-run — 8 of 12 fail.


End-to-end verification

Specs this PR routes to

$ git diff --name-only nwparker/ssh-04-host-authority-seeding..nwparker/ssh-05-reattach-fence \
    | node config/scripts/pr-e2e-source-routing.mjs
["tests/e2e/pty-input-write-queue-ssh.spec.ts",
 "tests/e2e/ssh-cold-activation-restore.spec.ts",
 "tests/e2e/ssh-docker-reconnect-pane-restore.spec.ts",
 "tests/e2e/ssh-port-forward-lifecycle.spec.ts",
 "tests/e2e/ssh-reconnect-tab-destruction.spec.ts",
 "tests/e2e/ssh-startup-exec-readiness.spec.ts",
 "tests/e2e/ssh-terminal-window-wake-stale-grid-repro.spec.ts"]

$ … | node config/scripts/pr-e2e-source-routing.mjs --ssh-source
true

Seven specs — the widest of the stack, because this is the only level touching src/main/ssh/. Under main's router it routed to 5; #16746 adds ssh-port-forward-lifecycle and ssh-reconnect-tab-destruction.

ssh-port-forward-lifecycle failed in the full lane and was cleared — it passes on main and passes at this stack tip in isolation (59.6s, same build); it is flaky only inside the full lane. See the verdict table below. Note the routing change is what put it in front of this PR at all: under main's router this level would never have run it.

Given this PR restores a twice-reverted mechanism, breadth here matters more than anywhere else in the stack. The reverts were both for tab loss, so the specs that matter most are the reconnect/restore ones — ssh-docker-reconnect-pane-restore, ssh-reconnect-tab-destruction, ssh-cold-activation-restore.

Lane result

Covered by the full Docker-SSH lane at the stack tip (below). The routed subset for this level can also be run directly:

pnpm test:e2e:ssh-docker -- tests/e2e/pty-input-write-queue-ssh.spec.ts \
                            tests/e2e/ssh-cold-activation-restore.spec.ts \
                            tests/e2e/ssh-docker-reconnect-pane-restore.spec.ts \
                            tests/e2e/ssh-port-forward-lifecycle.spec.ts \
                            tests/e2e/ssh-reconnect-tab-destruction.spec.ts \
                            tests/e2e/ssh-startup-exec-readiness.spec.ts \
                            tests/e2e/ssh-terminal-window-wake-stale-grid-repro.spec.ts
$ pnpm test:e2e:ssh-docker
BUILD_SHA=49bb96e0b4c135ce305a2f4dfe2d4b52e0b19cde   DIRTY=0
14 specs / 20 tests → 17 passed, 2 failed, 1 skipped (10.7m)

The two lane failures, resolved — and one is now exempted:

Spec main tip (isolated) tip (full lane) Outcome
ssh-docker-bulk-open-freeze-repro FAILED — harness TypeError: … reading 'workerIndex' at docker-ssh-relay-target.ts:226 — FAILED Not a flake — a 100% failure, and three further arity bugs behind it. Now exempted from the lane; repair tracked in #16764
ssh-port-forward-lifecycle PASSED PASSED (59.6s) FAILED at ssh-port-forward-lifecycle-evidence.ts:159 waiting on getByText('Ports') Flaky in-lane, not a regression

Port-forward was re-run at the same commit and build and passed in 59.6s. It is green on main, green at the tip in isolation, and red only inside the full lane — it is the set's one @headful spec and runs last. Called flaky in-lane rather than "unrelated": a real lane-ordering problem, pre-existing, and worth tracking.

Note on the recorded run: the 14-spec result above predates the bulk-open exemption. The lane now runs 13 specs; bulk-open is not among them. The other 13 results are unaffected — nothing about that spec's failure changes another's outcome, since the runner passes them all to one Playwright invocation with --workers=1 and each spec owns its own fixture container.

Build provenance

mayCreate is a new identifier — 0 occurrences in main's source, which is the positive check that the fence is in the build. It lands in the main bundle:

$ grep -c mayCreate out/main/index.js
3

This count is load-bearing for the honesty section below: every red run cited in this campaign was verified at mayCreate = 0, establishing those runs were against a build without this fence. A green claim made against a bundle showing 0 would be meaningless.

Measured on the lane build:

BUILD_SHA=49bb96e0b4c135ce305a2f4dfe2d4b52e0b19cde   DIRTY=0
tombstone=13   hasLocalTabsRow=2   hostAuthority=4   mayCreate=3

mayCreate=3 is this level's symbol; the other three prove the rest of the stack is in the same build.

Provenance trap, reproduced on this tree. Do not grep a single renderer chunk. grep -c <sym> out/renderer/assets/store-*.js | head -1 matched store-DtDSfs7_.js and reported 0 for a symbol present 13 times across store-uJWnDUOY.js, App-CZkf3Bu7.js and quick-commands-menu-events-SBDd6cXN.js. Always use cat out/renderer/assets/*.js | grep -c <sym>.

Also: renderer console.warn never reaches the app log. Only main-process stdio is forwarded by ORCA_E2E_FORWARD_APP_LOGS=1.

What is NOT covered — read this before approving

  • This does NOT close the daily tab growth, and the e2e proves it. ssh-lost-kill-tab-resurrection.spec.ts (in fix(terminal): a close the host never heard must survive the reconnect #16752) is byte-identical before and after this change — not a partial improvement, no change at all. Instrumentation shows why: in that scenario restoreReattachedPtyRuntime is never called (CREATING TAB 9 hits, reattach gate 0, BYPASS 0). The fence is on a path that bug does not take. This PR does not claim otherwise; fix(terminal): a close the host never heard must survive the reconnect #16752 is the fix for the user report.
  • No e2e spec drives the fenced path. The seven routed specs exercise SSH reconnect and pane restore broadly, so they are the right regression guard for the over-refusal risk that caused both previous reverts — but none constructs a stale lease pointing at a closed pane. The direct proof is the 12-test A/B unit suite.
  • Lease COLLISION is not handled, only divergence. A collision guard for upsertSshRemotePtyLease was built, tested, and removed — its own test passed with the guard disabled, i.e. vacuous. Distinguishing "same lease" from "recycled id on a different shell" needs a relay-start identity, which would be a twelfth per-tab identity concept. Left as an in-code NOTE.
  • The partition split-brain is not fixed (SSH host session partitions are written but never read — tab lists round-trip as empty and remote sync permanently deletes them #12721/Renderer and runtime disagree on which partition owns SSH worktree session state #12723, STA-3980, STA-5068). This PR refuses to judge from one side of it — reading both local and ssh:<target> before deciding a pane is gone — but the two owner maps still disagree.
  • attachIdentityMismatches still compares tabId (src/relay/pty-handler.ts:399), and expectedIdentityForLease still composes its paneKey from the frozen tabId (ssh-relay-session.ts:197). That refusal maps to SSH_SESSION_EXPIRED, which authorises a respawn onto a shell just proved alive. fix(ssh): reapply the reattach-identity work and stop the fallback fence stranding moved panes #14384 fixed it; eb22e49 reverted it; it never came back. Needs its own PR.
  • The SSH_SESSION_EXPIRED error class is lossy one layer up, and that is a separate defect from the one above: ssh-pty-session-reattach.ts:227-231 rewrites the relay's PTY "pty-1" not found into a bare SSH_SESSION_EXPIRED, so isPtyAlreadyGoneError's /PTY ".+" not found/ cannot match and attachStablePaneOwner:242's already-correct fallback never runs. Owned by nwparker/ssh-07-absent-from-relay, stacked after this one. Not fixed here.
  • The tombstone half of the guard is unreachable, not merely unexercised. sanitizeWorkspaceSessionTerminalRetirements applies every tombstone then clears the map on every session write, so terminalSurfaceTombstonesByPaneKey is structurally always empty at pty-binding-persistence.ts:163. Guarding it would have been inert; recorded rather than shipped as dead code.

Failing-first test

Yes — an A/B control on this tree rather than a revert, because the two halves interact.

 × does not resurrect a tab whose closing pty.kill failed with a transport error
 × refuses to graft a second leaf into a tab the reattach does not already own
 × treats a raised topology revision as the authority that makes absence a close
 × retires the predecessor when a pane re-leases under a new relay pty id
 × marks the superseded lease expired rather than terminated
 × holds the live lease count flat across ten reconnects of one pane
     AssertionError: expected [ 'pty-0', 'pty-1', 'pty-2', …(7) ] to deeply equal [ 'pty-9' ]
 × supersedes across a tab change, because the leaf is the pane identity
 × does not supersede a different pane in the same worktree
      Tests  8 failed | 4 passed (12)

Reproduce: set mayCreate to true in ssh-relay-session.ts and comment out supersedeSiblingLeasesForPane(operations, next, now) at ssh-pty-lease-operations.ts:139. Restored: 12 passed. The 4 that pass both ways are the over-refusal tripwires.

@nwparker
nwparker force-pushed the nwparker/ssh-04-host-authority-seeding branch from 395a238 to fdc407c Compare August 27, 2026 09:49
@nwparker
nwparker force-pushed the nwparker/ssh-05-reattach-fence branch from 546005d to 20db4da Compare August 27, 2026 09:49
@nwparker
nwparker force-pushed the nwparker/ssh-04-host-authority-seeding branch from fdc407c to d82475f Compare August 27, 2026 09:53
@nwparker
nwparker force-pushed the nwparker/ssh-05-reattach-fence branch from 20db4da to e9afc48 Compare August 27, 2026 09:53
@nwparker
nwparker force-pushed the nwparker/ssh-04-host-authority-seeding branch from d82475f to e302d3b Compare August 27, 2026 10:07
@nwparker
nwparker force-pushed the nwparker/ssh-05-reattach-fence branch from e9afc48 to 562a6ce Compare August 27, 2026 10:07
@nwparker
nwparker force-pushed the nwparker/ssh-04-host-authority-seeding branch from e302d3b to 9cc5bac Compare August 27, 2026 10:10
@nwparker
nwparker force-pushed the nwparker/ssh-05-reattach-fence branch from 562a6ce to c65bd84 Compare August 27, 2026 10:10
@nwparker
nwparker force-pushed the nwparker/ssh-04-host-authority-seeding branch from 9cc5bac to a7c18c3 Compare August 28, 2026 02:44
`reattachKnownPtys` treats every non-terminated lease as live and calls
`persistPtyBinding`, which had no way to say "bind only". Two of its branches
then rebuild UI the user is not asking for:

- `pty-binding-persistence.ts:133-143` -- `if (args.incarnationId)`
  unconditionally deletes the pane's close tombstone.
- `:145-160` -- on a tab-not-found it mints one via
  `createMinimalPersistedTerminalTab`. The in-code comment names its only
  intended caller: "pty:spawn can beat the debounced writer." Spawn. Reattach
  took the same branch.

This is the mechanism canceled ticket STA-4268 described: "Leases have no pane
incarnation and upsert only by target/PTY. Every nonterminal lease is reattached;
frozen coordinates are passed to persistPtyBinding, which creates and flushes
missing tabs and layout leaves." It was fixed in #13326, reverted by #14361,
re-applied by #14384, and reverted again by #14395 (opened and merged nine
seconds apart, empty commit body). `grep -rn "mayCreate" src/` returns nothing on
main -- the mechanism is genuinely out of the tree.

Four parts:

1. `mayCreate` (default true). When false, one pre-mutation check mirrors all
   four creating branches and returns `false` without mutating, so a refusal
   leaves nothing half-written.

2. The authority gate -- the part both prior attempts lacked, and probably why
   both were reverted. `mayCreate: false` alone refuses in two situations: "the
   user closed it" AND "the renderer has not published its layout yet". The
   second is routine on disconnect->reconnect and is almost certainly the #14361
   tab-loss mechanism. The fence was not wrong; it was UNCONDITIONED. It is now
   passed only when `hasHostAuthoritativeTerminalMembership()` says the persisted
   membership speaks for this worktree, reusing the function already guarding the
   same question at `orca-runtime.ts:8608`. Losing a tab is worse than keeping a
   duplicate, so an unauthoritative session still gets the creating write.

   Authority is read from `local` because that is the partition the write lands
   in -- it is local's absence being interpreted. But a pane the `ssh:<target>`
   partition still holds is not gone, so it keeps its creating write; refusing
   there would strand a live pane behind a binding reattach can no longer reach.
   (SSH spawns bind into `ssh:<target>` while this reattach binds into `local` --
   GH #12721/#12723, STA-3980. This does not fix that split; it refuses to judge
   from one side of it.)

3. `findTerminalTabIdForLeaf` -- bind resolves the tab from the live layout
   instead of the lease's frozen `tabId`. Only the leaf half of a pane key is
   remint-stable: `detachTerminalPaneToTab` moves a live pane into a new tab, so
   a stored tabId names the tab the pane left. Identity vs location.

4. Pane-keyed supersession -- retires siblings on `(targetId, worktreeId,
   leafId)` to `expired`, guarded by the durable binding, which reads `local`
   then `ssh:<target>` so it is correct whichever partition the binding landed
   in. `upsertSshRemotePtyLease` matched `(targetId, ptyId)` alone
   (`ssh-pty-lease-operations.ts:34-36`), so a new relay pty id on reattach minted
   a SECOND lease instead of updating the first, leaving the predecessor
   non-terminated with nothing to retire it.

On refusal the lease goes `expired`, never `terminated` -- `expired` records that
this shell has no surface to reach it through; `terminated` would assert an exit
nothing here observed, which `docs/reference/ssh-execution-boundary.md` forbids.
The remote process is left running.

Deliberately NOT done:
- A collision guard for `upsertSshRemotePtyLease`. Built, tested, and REMOVED --
  its own test passed with the guard disabled, i.e. vacuous. Telling "same lease"
  from "recycled id on a different shell" needs a relay-start identity, which
  would be a twelfth per-tab identity concept; the codebase already carries
  eleven (784 refs) that SSH-v3 Phase 3 deletes. Left as an in-code NOTE. This
  handles lease DIVERGENCE, not COLLISION.
- A port of #13324. Its own authors deleted its load fold and reverted its
  local-only reader in #13326 ("a headless-owned pane still gets a vote before
  its lease is retired"); porting it ships a state-destroying migration they
  removed.
- `bindPaneShell` from #13325. Its purpose is making `isSupersededPtyId` live,
  and that fence does not exist in main. It would have been a refactor plus a
  silently-ignored `mayCreate` -- TS drops excess props through spreads
  (verified), which is why `mayCreate` is passed as a conditional spread here.

Honesty about scope: this does NOT close the daily-tab-growth report. The
deterministic e2e repro (`ssh-lost-kill-tab-resurrection.spec.ts`, later in this
stack) is byte-identical before and after, and instrumentation shows why -- in
that scenario `restoreReattachedPtyRuntime` is never called at all
(`CREATING TAB` 9 hits, `reattach gate` 0, `BYPASS` 0). The fence is on a path
that bug does not take. It is a real, separately-provable defect; it is not the
headline fix, and must not be claimed as one.

Evidence, A/B on this tree. Disabling the authority gate (`mayCreate = true`) and
the supersession call by hand: **8 of 12 fail**, including "does not resurrect a
tab whose closing pty.kill failed with a transport error" and "holds the live
lease count flat across ten reconnects of one pane"
(`[ 'pty-0', 'pty-1', 'pty-2', …(7) ]` vs `[ 'pty-9' ]`). The 4 that pass both
ways are the over-refusal tripwires, which is the point of having them. Restored:
12 passed; 2,439 passed across `src/main/ssh`, `src/main/persistence` and
`src/main/runtime/workspace-session`.
@nwparker
nwparker force-pushed the nwparker/ssh-05-reattach-fence branch from c65bd84 to 1a69ed3 Compare August 28, 2026 02:45
@nwparker
nwparker changed the base branch from nwparker/ssh-04-host-authority-seeding to main August 28, 2026 02:45
@nwparker
nwparker merged commit a7b1da9 into main Aug 28, 2026
2 of 19 checks passed
@coderabbitai

coderabbitai Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4d54b545-2500-45bc-80e0-1658888456d6

📥 Commits

Reviewing files that changed from the base of the PR and between e06a866 and 1a69ed3.

📒 Files selected for processing (6)
  • src/main/persistence/leasing-ssh-ptys/ssh-pty-lease-operations.ts
  • src/main/persistence/loading-store/pty-binding-persistence.ts
  • src/main/persistence/loading-store/ssh-lease-recovery-operations.ts
  • src/main/runtime/workspace-session-terminal-membership-authority.ts
  • src/main/ssh-reattach-pane-cardinality.test.ts
  • src/main/ssh/ssh-relay-session.ts

📝 Walkthrough

Walkthrough

The change updates SSH PTY lease recovery and reattachment. Lease operations compare relay PTY identities, find durable pane bindings, and expire stale sibling leases. Binding persistence can reject creation of missing terminal topology. Reattach recovery resolves tabs from current workspace layouts and expires leases when authoritative membership rejects a binding. New tests cover tab movement, topology authority, lease cardinality, pane isolation, and partial lease updates.

✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
📝 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.

paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 30, 2026
…yai#16751)

`reattachKnownPtys` treats every non-terminated lease as live and calls
`persistPtyBinding`, which had no way to say "bind only". Two of its branches
then rebuild UI the user is not asking for:

- `pty-binding-persistence.ts:133-143` -- `if (args.incarnationId)`
  unconditionally deletes the pane's close tombstone.
- `:145-160` -- on a tab-not-found it mints one via
  `createMinimalPersistedTerminalTab`. The in-code comment names its only
  intended caller: "pty:spawn can beat the debounced writer." Spawn. Reattach
  took the same branch.

This is the mechanism canceled ticket STA-4268 described: "Leases have no pane
incarnation and upsert only by target/PTY. Every nonterminal lease is reattached;
frozen coordinates are passed to persistPtyBinding, which creates and flushes
missing tabs and layout leaves." It was fixed in stablyai#13326, reverted by stablyai#14361,
re-applied by stablyai#14384, and reverted again by stablyai#14395 (opened and merged nine
seconds apart, empty commit body). `grep -rn "mayCreate" src/` returns nothing on
main -- the mechanism is genuinely out of the tree.

Four parts:

1. `mayCreate` (default true). When false, one pre-mutation check mirrors all
   four creating branches and returns `false` without mutating, so a refusal
   leaves nothing half-written.

2. The authority gate -- the part both prior attempts lacked, and probably why
   both were reverted. `mayCreate: false` alone refuses in two situations: "the
   user closed it" AND "the renderer has not published its layout yet". The
   second is routine on disconnect->reconnect and is almost certainly the stablyai#14361
   tab-loss mechanism. The fence was not wrong; it was UNCONDITIONED. It is now
   passed only when `hasHostAuthoritativeTerminalMembership()` says the persisted
   membership speaks for this worktree, reusing the function already guarding the
   same question at `orca-runtime.ts:8608`. Losing a tab is worse than keeping a
   duplicate, so an unauthoritative session still gets the creating write.

   Authority is read from `local` because that is the partition the write lands
   in -- it is local's absence being interpreted. But a pane the `ssh:<target>`
   partition still holds is not gone, so it keeps its creating write; refusing
   there would strand a live pane behind a binding reattach can no longer reach.
   (SSH spawns bind into `ssh:<target>` while this reattach binds into `local` --
   GH stablyai#12721/stablyai#12723, STA-3980. This does not fix that split; it refuses to judge
   from one side of it.)

3. `findTerminalTabIdForLeaf` -- bind resolves the tab from the live layout
   instead of the lease's frozen `tabId`. Only the leaf half of a pane key is
   remint-stable: `detachTerminalPaneToTab` moves a live pane into a new tab, so
   a stored tabId names the tab the pane left. Identity vs location.

4. Pane-keyed supersession -- retires siblings on `(targetId, worktreeId,
   leafId)` to `expired`, guarded by the durable binding, which reads `local`
   then `ssh:<target>` so it is correct whichever partition the binding landed
   in. `upsertSshRemotePtyLease` matched `(targetId, ptyId)` alone
   (`ssh-pty-lease-operations.ts:34-36`), so a new relay pty id on reattach minted
   a SECOND lease instead of updating the first, leaving the predecessor
   non-terminated with nothing to retire it.

On refusal the lease goes `expired`, never `terminated` -- `expired` records that
this shell has no surface to reach it through; `terminated` would assert an exit
nothing here observed, which `docs/reference/ssh-execution-boundary.md` forbids.
The remote process is left running.

Deliberately NOT done:
- A collision guard for `upsertSshRemotePtyLease`. Built, tested, and REMOVED --
  its own test passed with the guard disabled, i.e. vacuous. Telling "same lease"
  from "recycled id on a different shell" needs a relay-start identity, which
  would be a twelfth per-tab identity concept; the codebase already carries
  eleven (784 refs) that SSH-v3 Phase 3 deletes. Left as an in-code NOTE. This
  handles lease DIVERGENCE, not COLLISION.
- A port of stablyai#13324. Its own authors deleted its load fold and reverted its
  local-only reader in stablyai#13326 ("a headless-owned pane still gets a vote before
  its lease is retired"); porting it ships a state-destroying migration they
  removed.
- `bindPaneShell` from stablyai#13325. Its purpose is making `isSupersededPtyId` live,
  and that fence does not exist in main. It would have been a refactor plus a
  silently-ignored `mayCreate` -- TS drops excess props through spreads
  (verified), which is why `mayCreate` is passed as a conditional spread here.

Honesty about scope: this does NOT close the daily-tab-growth report. The
deterministic e2e repro (`ssh-lost-kill-tab-resurrection.spec.ts`, later in this
stack) is byte-identical before and after, and instrumentation shows why -- in
that scenario `restoreReattachedPtyRuntime` is never called at all
(`CREATING TAB` 9 hits, `reattach gate` 0, `BYPASS` 0). The fence is on a path
that bug does not take. It is a real, separately-provable defect; it is not the
headline fix, and must not be claimed as one.

Evidence, A/B on this tree. Disabling the authority gate (`mayCreate = true`) and
the supersession call by hand: **8 of 12 fail**, including "does not resurrect a
tab whose closing pty.kill failed with a transport error" and "holds the live
lease count flat across ten reconnects of one pane"
(`[ 'pty-0', 'pty-1', 'pty-2', …(7) ]` vs `[ 'pty-9' ]`). The 4 that pass both
ways are the over-refusal tripwires, which is the point of having them. Restored:
12 passed; 2,439 passed across `src/main/ssh`, `src/main/persistence` and
`src/main/runtime/workspace-session`.

(cherry picked from commit a7b1da9)
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…yai#16751)

`reattachKnownPtys` treats every non-terminated lease as live and calls
`persistPtyBinding`, which had no way to say "bind only". Two of its branches
then rebuild UI the user is not asking for:

- `pty-binding-persistence.ts:133-143` -- `if (args.incarnationId)`
  unconditionally deletes the pane's close tombstone.
- `:145-160` -- on a tab-not-found it mints one via
  `createMinimalPersistedTerminalTab`. The in-code comment names its only
  intended caller: "pty:spawn can beat the debounced writer." Spawn. Reattach
  took the same branch.

This is the mechanism canceled ticket STA-4268 described: "Leases have no pane
incarnation and upsert only by target/PTY. Every nonterminal lease is reattached;
frozen coordinates are passed to persistPtyBinding, which creates and flushes
missing tabs and layout leaves." It was fixed in stablyai#13326, reverted by stablyai#14361,
re-applied by stablyai#14384, and reverted again by stablyai#14395 (opened and merged nine
seconds apart, empty commit body). `grep -rn "mayCreate" src/` returns nothing on
main -- the mechanism is genuinely out of the tree.

Four parts:

1. `mayCreate` (default true). When false, one pre-mutation check mirrors all
   four creating branches and returns `false` without mutating, so a refusal
   leaves nothing half-written.

2. The authority gate -- the part both prior attempts lacked, and probably why
   both were reverted. `mayCreate: false` alone refuses in two situations: "the
   user closed it" AND "the renderer has not published its layout yet". The
   second is routine on disconnect->reconnect and is almost certainly the stablyai#14361
   tab-loss mechanism. The fence was not wrong; it was UNCONDITIONED. It is now
   passed only when `hasHostAuthoritativeTerminalMembership()` says the persisted
   membership speaks for this worktree, reusing the function already guarding the
   same question at `orca-runtime.ts:8608`. Losing a tab is worse than keeping a
   duplicate, so an unauthoritative session still gets the creating write.

   Authority is read from `local` because that is the partition the write lands
   in -- it is local's absence being interpreted. But a pane the `ssh:<target>`
   partition still holds is not gone, so it keeps its creating write; refusing
   there would strand a live pane behind a binding reattach can no longer reach.
   (SSH spawns bind into `ssh:<target>` while this reattach binds into `local` --
   GH stablyai#12721/stablyai#12723, STA-3980. This does not fix that split; it refuses to judge
   from one side of it.)

3. `findTerminalTabIdForLeaf` -- bind resolves the tab from the live layout
   instead of the lease's frozen `tabId`. Only the leaf half of a pane key is
   remint-stable: `detachTerminalPaneToTab` moves a live pane into a new tab, so
   a stored tabId names the tab the pane left. Identity vs location.

4. Pane-keyed supersession -- retires siblings on `(targetId, worktreeId,
   leafId)` to `expired`, guarded by the durable binding, which reads `local`
   then `ssh:<target>` so it is correct whichever partition the binding landed
   in. `upsertSshRemotePtyLease` matched `(targetId, ptyId)` alone
   (`ssh-pty-lease-operations.ts:34-36`), so a new relay pty id on reattach minted
   a SECOND lease instead of updating the first, leaving the predecessor
   non-terminated with nothing to retire it.

On refusal the lease goes `expired`, never `terminated` -- `expired` records that
this shell has no surface to reach it through; `terminated` would assert an exit
nothing here observed, which `docs/reference/ssh-execution-boundary.md` forbids.
The remote process is left running.

Deliberately NOT done:
- A collision guard for `upsertSshRemotePtyLease`. Built, tested, and REMOVED --
  its own test passed with the guard disabled, i.e. vacuous. Telling "same lease"
  from "recycled id on a different shell" needs a relay-start identity, which
  would be a twelfth per-tab identity concept; the codebase already carries
  eleven (784 refs) that SSH-v3 Phase 3 deletes. Left as an in-code NOTE. This
  handles lease DIVERGENCE, not COLLISION.
- A port of stablyai#13324. Its own authors deleted its load fold and reverted its
  local-only reader in stablyai#13326 ("a headless-owned pane still gets a vote before
  its lease is retired"); porting it ships a state-destroying migration they
  removed.
- `bindPaneShell` from stablyai#13325. Its purpose is making `isSupersededPtyId` live,
  and that fence does not exist in main. It would have been a refactor plus a
  silently-ignored `mayCreate` -- TS drops excess props through spreads
  (verified), which is why `mayCreate` is passed as a conditional spread here.

Honesty about scope: this does NOT close the daily-tab-growth report. The
deterministic e2e repro (`ssh-lost-kill-tab-resurrection.spec.ts`, later in this
stack) is byte-identical before and after, and instrumentation shows why -- in
that scenario `restoreReattachedPtyRuntime` is never called at all
(`CREATING TAB` 9 hits, `reattach gate` 0, `BYPASS` 0). The fence is on a path
that bug does not take. It is a real, separately-provable defect; it is not the
headline fix, and must not be claimed as one.

Evidence, A/B on this tree. Disabling the authority gate (`mayCreate = true`) and
the supersession call by hand: **8 of 12 fail**, including "does not resurrect a
tab whose closing pty.kill failed with a transport error" and "holds the live
lease count flat across ten reconnects of one pane"
(`[ 'pty-0', 'pty-1', 'pty-2', …(7) ]` vs `[ 'pty-9' ]`). The 4 that pass both
ways are the over-refusal tripwires, which is the point of having them. Restored:
12 passed; 2,439 passed across `src/main/ssh`, `src/main/persistence` and
`src/main/runtime/workspace-session`.
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