Repository navigation
fix(terminal): remove host-retired ghost panes in paired remote splits (#17770) - #19365
Conversation
Fixes #17770 When a pane of a split terminal in a paired remote-server workspace has its process exit, the host retires that leaf and republishes a one-leaf layout. The client's host-authoritative live-layout reconciler planned insertions only, so the retired leaf's pane stayed mounted forever as a blank, dead ghost. Add a removal planner (planTerminalLiveLayoutRemovals / trackRetiredLeafIds / selectRetiredPaneIds) that closes a mounted pane once the host has dropped its leaf AND the pane's transport PTY has cleared - never removing the last pane and never a pane whose PTY is still live. The reconciler effect also re-runs on transport recovery-state changes so a pane whose PTY is still ending is removed once it clears.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (5)
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review. 📝 WalkthroughWalkthroughThe change adds helpers that track host-retired terminal leaves and select panes for removal after their PTY ends. The reconciliation effect stores host layout state, plans removals, closes eligible panes, and reruns on PTY recovery changes. Unit tests cover the helper behavior and retirement sequence. A new end-to-end test verifies that exiting one pane in a paired remote split leaves the other pane active. Fixed issue severity: Medium Priority: ➖ Normal — Impact reflects medium issue severity. Severity of issue fixed: Medium Merge Risk: ⚪ Minimal · up to Remote split terminals now remove host-retired panes only after teardown while preserving the remaining shell. The targeted ghost-pane behavior is covered with helper tests and an end-to-end paired-client scenario, with no active merge risk identified. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
planTerminalLiveLayoutRemovals/trackRetiredLeafIds— a pure removal/retirement-tracking side for host-authoritative layouts: a mounted leaf is only removable after the host has both named it in a prior layout and dropped it from the current one.selectRetiredPaneIds— the boundary-safety guard that closes a retired pane only once its transport PTY has cleared (getPtyId() === null) and never the last pane, soexecuteClosePanecan never kill a still-live remote terminal.useTerminalPaneReconciliationwiring — retires/forgets leaves across runs via refs, closes confirmed ghosts through the existingexecuteClosePanepath, and addsptyRecoveryStatesByPaneIdto the effect deps so a pane whose PTY clears after the layout shrinks is still removed.- Tests — 25 unit tests over the three pure functions (each guard mutation-tested per the PR body) plus a paired host + paired client e2e repro that quits a split shell and asserts the DOM settles on the single surviving pane.
I traced the safety model against the surrounding code and it holds. The close is gated on getPtyId() === null, so closeWebRuntimeTerminal receives null and the host's PTY is never touched from this path (safe direction is leak, not kill). The host only prunes a leaf from its authoritative parentLayout.root on a real onPtyExit (retireLeavesFromTerminalLayout), and the client store root is reconciled from that pruned tree in chooseRemoteTerminalLayout, so a shrinking collectLeafIds(restoredLayout.root) is genuine retirement evidence rather than a transient/partition artifact. Because the effect reads the already-pruned restoredLayout.root for both insertions and removals, there is no re-insertion loop after a pane is closed. The e2e test's assertions (store layout at one leaf while DOM had kept the ghost pre-fix) are a real refutation, not theatre.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
The host-retired leaf tracking added two `useRef`s to useTerminalPaneReconciliation (last host layout leaf set and retired leaf set), which flattens to 209 render hooks. Order is otherwise unchanged; the new hash was captured from the flattened order and diffed against main (only the two useRef entries were inserted).
|
Review follow-up: the CI-red blocker ( Cause: the two Mutation control: swapping one Re-ran the repro instrument on the same branch: |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Hook-order parity repin —
terminal-pane-hook-order-parity.test.tsrepins the flattened render-hook count from 207 to 209 and the corresponding SHA-256 hash to account for the twouseRefs (hostLayoutLeafIdsRef,retiredLeafIdsRef) that the already-reviewed removal side added touseTerminalPaneReconciliation.
I verified the repin against the current sources: the two useRef declarations sit in use-terminal-pane-reconciliation.ts:42 exactly where the new changelog comment describes them, the useMemo count is unchanged at 8, and the test passes locally against this tree. The parity test remains a real guard — it still pins the full flattened order via the hash plus the exact hook count, so any future accidental reorder or stray hook still fails it; the repin reflects a genuine, already-approved hook addition rather than masking a regression.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…uld not be killed (upstream ports) (#370) * perf(terminal): skip the partial-escape-tail walk on ESC-free PTY chunks (#18748) `advancePartialEscapeTail` runs once per PTY chunk, on the main thread, for every terminal — visible, hidden or parked — inside `HeadlessEmulator`'s write path. It unconditionally concatenated the pending tail with the whole chunk and then walked the result one code unit at a time through a VT500 state machine. `extractPartialEscapeTail` only leaves `ground` on an ESC byte, so with no pending tail and no ESC in the chunk the answer is always ''. Taking that case up front skips both the full-chunk concat and the walk. `String.prototype.includes` is a native scan, so the gate costs essentially nothing on the chunks it does not short-circuit. This is the same gate its two neighbours on the very same ingest path already apply — `TerminalOscCwdTitleScanner.scan` and `TerminalMouseModeMirror.scan`, both carrying a comment citing their measured share of a 2.2x ingest regression. This call was simply missed. Measured by `pnpm bench:terminal-partial-escape-tail` over 640 x 16 KB chunks (10 MB), median of 7 rounds: | stream shape | before | after | | | --- | --- | --- | --- | | ESC-free (build logs, `cat`, piped output) | 40.3 ms | 0.19 ms | 213x | | SGR-coloured output (gate does not apply) | 30.6 ms | 32.1 ms | 1.0x | The benchmark proves equivalence over a 226-case corpus before timing, and a new unit test pairs every pending-tail state the scanner can be left in against every chunk shape, asserting the gate is indistinguishable from the unconditional fold. (cherry picked from commit c36dd5f) * fix(terminal): fold-safe CAN/SUB and double-ESC handling in partial-escape tail (#19521) `extractPartialEscapeTail` broke its own fold invariant (extract(a + b) === extract(extract(a) + b)) in the oscEsc/stringEsc states, so a PTY read that split there produced a different pending tail than the same bytes delivered whole — the tail snapshots append after a restore. Two causes, both in the "ESC did not terminate the string" branch: - CAN/SUB were routed through `stateAfterEscByte`, which maps them back to `esc` instead of aborting to ground. `extractPartialEscapeTail('\x1bPx\x1b\x18X0abc')` returned '\x1b\x18X0abc'; the chunk-split fold returned ''. - A second ESC opened its new sequence at `i - 1` rather than at itself. `extractPartialEscapeTail('\x1b] \x1b\x1b^')` returned '\x1b\x1b^' whole but '\x1b^' folded. The fold was right — xterm starts the sequence at the second ESC. The existing fuzz only asserted the fold as `advance(extract(pending), chunk)`, which is a tautology because every PENDINGS entry is already a tail. Replaced with a sweep that re-splits the combined stream at every code-unit boundary, and extended the alphabet (NUL, 0x20 intermediate, CJK) and SEQUENCES with CAN/SUB and doubled-ESC-inside-string cases. A 1.25M-split fold fuzz over a VT alphabet goes from 421 failures to 0. (cherry picked from commit ed88188) * fix(pty): un fallo de I/O no es evidencia de exit (upstream #19523) Port de stablyai/orca#19523. Un throw en `write` o `resize` ponia `dead = true` —el mismo flag que pone un exit real— y con eso quedaban deshabilitados `kill`, `forceKill`, `signal` y el flow control del productor: la sesion ya no se podia terminar nunca. Nuestras dos lineas del bug eran identicas a las que upstream borra (`pty-subprocess.ts` 1175 y 1188). Separa `ioFailed` de `dead`, con las mismas tres guardas que upstream (`write`, `resize`, `pause`); `resume` queda sin tocar, igual que alla. Los tests de upstream no se pueden portar: reciben un `pty.IPty` ya creado porque alla extrajeron `createDaemonPtySubprocessHandle` a un modulo aparte, y nuestro `createPtySubprocess` spawnea el proceso el mismo. Se escriben tres contra nuestro seam, con el harness que ya existe. Dos de los tres se verificaron fallando al revertir el arreglo. * fix(terminal): quitar los panes fantasma que el host ya retiro (upstream #19365) Port de stablyai/orca#19365. Al reconciliador de layout host-autoritativo le faltaba el camino de REMOCION: solo materializaba panes que el host nombraba, nunca desmontaba uno que el host dejo de nombrar. Un pane cuyo PTY termino queda de fantasma —no renderiza nada y, cuando es el ultimo, se come el siguiente cierre de la pestaña. Es el sintoma de "pestañas espejadas que se duplican o desincronizan" en un split remoto. Los tres helpers (`planTerminalLiveLayoutRemovals`, `selectRetiredPaneIds`, `trackRetiredLeafIds`) entran tal cual. Lo que hubo que portar es el cableado: upstream lo consume desde `use-terminal-pane-reconciliation.ts`, un hook que extrajo despues de nuestra divergencia y que aca no existe, asi que va en el mismo effect de `TerminalPane.tsx` que ya aplicaba las inserciones. Sus dos archivos propios se descartan por eso. Un leaf solo cuenta como retirado contra el layout que el host nombro ANTES, asi que los dos refs del hook (`hostLayoutLeafIdsRef`, `retiredLeafIdsRef`) van junto a los otros refs de pane. `ptyRecoveryStatesByPaneId` entra a las deps porque es lo que re-corre el effect cuando el PTY de un pane retirado termina de cerrarse. 25 tests del reconciliador y 4317 de terminal-pane en verde. El warning de react-doctor en ese archivo es previo: verificado con stash sobre main. * test(e2e): traer el fixture que el spec de panes fantasma importa El spec e2e de #19365 importa `paired-browser-placement-fixture`, que upstream agrego despues de nuestra divergencia: sin el, `playwright --list` falla con "Cannot find module" y tumba el job de static analysis entero — no solo ese spec. Se trae del upstream tal cual. Sus tres dependencias (`orca-app`, `headless-paired-runtime-host`, `paired-electron-client`) ya existen aca, asi que no arrastra nada mas. Verificado: `playwright --list` vuelve a resolver los 591 tests. * test(e2e): declarar el spec de panes fantasma en el ratchet de conteo El spec que trae upstream #19365 sube el conteo de electron-headless de 590 a 591, y el ratchet exige declararlo a proposito. Es el unico spec que agrega la tanda. --------- Co-authored-by: Neil <[email protected]>

Fixes #17770
ELI5
When you have a terminal split into two panes on a "remote server" (paired) workspace and you type
exitin one of them, that pane's shell dies. The remote host notices, removes that half from the layout, and tells your app "this tab now has one pane." But your app only knew how to add panes to match the host's layout — it never learned how to remove one. So the dead pane just sat there: a blank rectangle you couldn't type into, with no "process exited" message and no restart button. Worse, if you then closed the still-working pane, the tab was left showing only the dead one — so it looked like closing one pane killed your whole split session.This PR teaches the layout reconciler to remove a pane once the host has dropped its leaf and that pane's connection is confirmed gone — so the ghost disappears and the tab settles on the pane that's actually alive.
The bug (#17770)
In a paired remote-server workspace, the host owns the pane layout. When a split pane's process exits,
OrcaRuntimeService.onPtyExitretires that leaf and republishes a one-leaf layout. On the client,useTerminalPaneReconciliationranplanTerminalLiveLayoutInsertionsand returned early when there were no insertions — there was no removal path. The retired leaf's pane stayed mounted forever as a blank, unresponsive ghost with no exit overlay and no restart control.This is exclusively a paired-runtime/web defect: the reconciler branch is gated by
isHostAuthoritativeLayout, which only admits web clients orremote:-prefixed PTYs. Direct-SSH tabs (ssh:…@@pty2:…) never take this branch, which is why local splits and "Add SSH host" tabs were unaffected.A subtlety this fix accounts for: for a paired (web-surface) tab, the per-pane transport treats its own stream ending as unverifiable (attachment loss, per the SSH execution boundary) and deliberately keeps the pane — it cannot tell retirement from a partition. Only the host's authoritative layout knows the leaf was truly retired, so removal must be driven from the layout reconciler, not the per-pane exit path.
The fix
terminal-live-layout-reconciliation.tsgains a removal side:trackRetiredLeafIds— a leaf counts as retired only if the host named it in a prior layout and has since dropped it while its pane is still mounted. A leaf the host never named (a pane the client is still spawning) is never treated as retired; a leaf the host names again is forgotten.planTerminalLiveLayoutRemovals— mounted leaves the current layout no longer names and that are in the retired set.selectRetiredPaneIds— closes a retired pane only once its transport PTY has cleared (getPtyId() === null), and never the last pane on the tab. This is the boundary-safety guard: a pane whose PTY is still live is left alone, soexecuteClosePanecan never kill a still-running remote terminal.use-terminal-pane-reconciliation.tswires these in and closes retired panes throughexecuteClosePane(the same cleanup a user close runs). Because a retired pane's PTY often clears just after the layout shrinks, the reconciliation effect now also re-runs on transport recovery-state changes (ptyRecoveryStatesByPaneId), so a pane whose PTY is still ending is removed on the next run once it clears.Boundary / wire notes
Reproduction & before/after proof
Added
tests/e2e/paired-remote-split-pane-host-retired-ghost.spec.ts: a headless paired runtime host + a paired desktop client. The host splits a terminal into two login-shell leaves; the second shell is quit withexit. The test asserts the host-authoritative layout the client holds shrinks to one leaf (confirming retirement) and that the client's DOM then settles at exactly the surviving pane.Verified on that instrument (
electron-headless):Error: paired client kept the retired pane mounted as a dead ghost … Expected: 1 Received: 2. This is the exact refutation-proof shape (store = 1 leaf, DOM = 2 panes).getPtyId()was still non-null, so the safety guard correctly skipped it — and nothing re-ran the effect once the PTY cleared. This is what motivated theptyRecoveryStatesByPaneIddependency.1 passed— the retired pane is removed and the tab settles on the live pane. Green across 3 consecutive runs (12–17s each).This resolves every observed symptom in #17770: the ghost after
exit(a); its survival across workspace switches (b, moot once removed); and "closing one pane terminates the whole split session" (c) — the ghost never becomes the sole pane. The click-close path on a live pane (d) is unaffected, and local splits / unsplit remote tabs (e) don't regress (gated byisHostAuthoritativeLayoutand the never-last-pane guard).Unit coverage & mutation testing
terminal-live-layout-reconciliation.test.tscovers the three new pure functions (25 tests pass). Each guard was mutation-tested by reverting the specific behavior it protects:getPtyId() === nullguard → "keeps a pane still bound to a PTY…" fails;<= 1→< 1) → "never removes the last pane" fails;The recovery-state re-trigger is proven by the e2e differential above (removal planner alone fails; adding the dependency passes).
Review follow-up (CI-red blocker)
test / tests node 24 6/8failed oncf2839ewithterminal-pane-hook-order-parity.test.ts:expected [ Array(209) ] to have a length of 207. The twouseRefs this PR adds touseTerminalPaneReconciliation(last host layout leaf set, retired leaf set) are render hooks and shift the flattened count from 207 to 209. No hook order changed otherwise -- the flattened order was diffed againstmainand only the twouseRefentries were inserted (useTerminalPaneController>useTerminalPaneReconciliation>useRefx2). Resolved in5f81ca2by repinning the count/hash with a changelog comment matching the file's convention.Mutation control on the repin: replacing one
useRefwith a plain{ current }object makes the test fail withExpected 209, Received 208; restoring it passes.Visual Proof
Captured with an assertion-free variant of the shipped e2e (
paired-remote-split-pane-host-retired-ghost-visual.spec.ts, not committed to this branch — it drops the pane-count assertions and adds screenshotting so the same script runs to completion on both trees; happy to push it if a reviewer wants to re-run the capture). Instrument:electron-headless, a headless paired Orca runtime host plus a paired Electron client, window pinned to 1440×900, identical steps, and an identical 20 s settle window on both sides.use-terminal-pane-reconciliation.tsreverted tomain(single-file revert; the planners stay, only the wiring is removed).5f81ca2, unmodified.Annotations are drawn by the harness: red frame = the leaf the host retired, green frame = the leaf the host still names. Both shells are switched to a neutral
orca-demo$prompt before the first capture, so the frames carry no capturing-machineuser@host.1. Split, both panes live
Both trees are identical here: two panes, two remote PTYs, host layout names two leaves.
2. The host retires one leaf (
exitin the lower shell)Also identical, and that is correct: at the instant the layout shrinks the retired pane's PTY has not cleared yet, so
selectRetiredPaneIdsdeliberately declines to close it. Look at the host layout, not the DOM — it is already down to one leaf in both. Store = 1 leaf, DOM = 2 panes on both sides.3. After the settle window — this is the difference
BEFORE keeps the ghost: the red-framed pane is still mounted, showing the dead shell's
exitecho, with no exit overlay and no restart control. Store = 1 leaf, DOM = 2 panes (ghostStillMounted: true). AFTER has removed it and the surviving pane fills the tab (ghostStillMounted: false).4. The surviving pane is still usable — the tab was not killed
echo ORCA_PANE_ALIVE_<ts>is sent to the first terminal and its output is read back out of that pane's xterm buffer. It succeeds on both sides, which is the point: the fix removes a dead pane without touching the live one. BEFORE still carries the ghost underneath — that is the state where #17770 (c) bites, because closing the live pane then leaves the ghost as the only pane.The harness also writes machine-readable per-step facts (pane ids, PTY ids, host leaves,
ghostStillMounted) tofacts.jsonbeside the screenshots; those are the numbers quoted above.Root cause or symptom?
The removal side is a genuine repair, not a sweep.
useTerminalPaneReconciliation's contract is to make mounted panes match the host-authoritative layout; it only ever implemented insertions. The host is behaving correctly —OrcaRuntimeService.onPtyExitretires the leaf and republishes. So "why is a retired pane still mounted at all?" answers to "the client reconciler has no removal path", and adding one completes the contract. The decision rule is also boundary-correct: removal needs positive host evidence (the host named the leaf, then dropped it) and a locally confirmed-cleared PTY, and never touches the last pane, so the safe direction stays leak-not-kill.The retry scheduling is the soft spot.
selectRetiredPaneIdscorrectly defers when the ghost's PTY is still bound, and the deferred retry is scheduled offptyRecoveryStatesByPaneId— a state whose actual job is driving the reconnect overlay, and whose updater is deliberately identity-stable:updateTerminalRemoteRuntimeRecoveryUiStatereturnspreviousunchanged when the phase is not one ofrecovering/backoff/disconnectedand the pane has no prior entry. So the effect only re-runs if the ghost passes through a visible recovery phase.On the paired path it always does, and the reason is worth writing down because nothing in these files says it:
web-terminal--prefixed tab id (web-session-tabs-sync/terminal-build.ts:73), so every tab that can reach the removal branch satisfiesisWebTerminalSurfaceTabId.RemoteRuntimePtyTransport'sonEndtakes its first branch unconditionally for such tabs (remote-runtime-pty-transport.ts:2052) — it treats the stream end as attachment loss, keeps the PTY, and schedules a resubscribe → phaserecovering.'ended') deletes it. Two identity changes, two re-runs, and the ghost is removed on one of them.That is measured, not inferred. Driving the transport directly and recording every
onRecoveryStateChange:getPtyId()afterweb-terminal-…verdict: 'exited'recoveringtab-1verdict: 'exited'endedA is the load-bearing one: on a paired tab even a certified exit keeps the PTY and routes through a visible phase, so the retry trigger always fires. B shows the no-visible-phase clear is real at transport level — it is simply unreachable from the removal branch, because every host-published layout is keyed
web-terminal-…(point 1 above), so a tab in state B never takes that branch.The other candidate —
handleRemoteTerminalError→isRemoteTerminalGoneMessage→retireRemoteTerminalId()(remote-runtime-pty-transport.ts:1678), which clears the PTY straight fromconnected— is gated too: it hangs off theterminal.sendRPC failing, andsendUnacknowledgedInput(:1446) only falls back to that RPC when no multiplexed stream is live. With a live stream the write never reaches it (measured: the RPC is not called), and a closed stream is exactly the state that has already emittedrecovering.So this is hardening, not a live gap. But the protection is three independent structural gates in three modules, none of which states the dependency — and
isHostAuthoritativeLayout's own doc comment describes a desktop, non-web-terminal-case as in scope. A future change that gives a normal-tab-id remote-runtime tab a host-published layout reopens the ghost with no failing test.Assessment: correct fix, fragile trigger. The durable version drives the retry off the PTY-exit signal the transport already emits on every clearing path (
onPtyExit, called atremote-runtime-pty-transport.ts:1568,:2077,:2538) rather than off recovery-phase object identity, which also drops the coupling to an unrelated overlay state. I did not make that change here — it is a real refactor of the effect's trigger and belongs in review, not in a silent amend. Flagging it as the follow-up this PR should not ship without a decision on.Relationship to #18387 (community PR)
@ylcn91 opened #18387 for this same issue on 2026-09-03, four days before this PR. The two are not independent work: two of the three shared files are byte-identical between the branches (blob
814ca8d974fforterminal-live-layout-reconciliation.test.ts, blob859f6c97168forterminal-live-layout-reconciliation.ts). The design —trackRetiredLeafIds/planTerminalLiveLayoutRemovals/selectRetiredPaneIds, the retired-set gate, thegetPtyId() === nullguard, the never-last-pane guard, and their unit tests — is @ylcn91's.Same root cause? Identical. Both identify that the host-authoritative reconciler planned insertions only.
Do they conflict? Yes — same three files, same functions. They cannot both merge.
What this PR adds (the complete delta):
ptyRecoveryStatesByPaneIdin the reconciliation effect's dependency array.tests/e2e/paired-remote-split-pane-host-retired-ghost.spec.ts— end-to-end reproduction against a real paired host and client.terminal-pane-hook-order-parity.test.tsrepin (207 → 209).Does #18387 miss a case? One, and it is load-bearing. Its comment states that a removal skipped while the transport still held its PTY "is retried after the exit … once the exit lands and rewrites the layout bindings". That rewrite does not happen:
clearExitedPanePtyLayoutBindingForLeaf(use-terminal-pane-layout-bindings.ts:104) early-returns whenexistingBindings[leafId] !== exitedPtyId, and the host already dropped that leaf's binding when it shrank the layout. Nothing re-runs the effect, so on the ordering where the layout shrink arrives before the PTY clears, the ghost stays. This is not theoretical — the e2e in this PR fails with #18387's planners and wiring alone.#18387 is also CI-red, latently. It adds the same two
useRefs touseTerminalPaneReconciliationwithout repinning the hook-order parity test, which then failsexpected [ Array(209) ] to have a length of 207. Reproduced locally by running that test atmain's expectations against this branch's hook file. #18387 has no check runs at all (fork workflows were never approved), so nothing ever reported it.Does this PR miss anything #18387 catches? No — this branch is a strict superset of #18387's changes.
Recommendation. This PR is #18387 plus the one missing re-trigger and the CI repin, so on merits it is the more complete change — but the substance is @ylcn91's and the delta is four lines plus tests. The cleanest outcome is to push that delta onto #18387 and land their branch, closing this one; that gets the better fix and the right authorship in one move. If this branch lands instead, it should carry
Co-authored-by: ylcn91, and #18387 should be closed with a comment that credits the diagnosis and links here. Either way #18387 should not simply be closed as superseded.DO NOT MERGE without explicit approval.