Skip to content

fix(terminal): ghost panes, escape-tail correctness and a PTY that could not be killed (upstream ports) - #370

Merged
fabolivark merged 6 commits into
mainfrom
feat/upstream-terminal-stability
Sep 9, 2026
Merged

fabolivark merged 6 commits into
mainfrom
feat/upstream-terminal-stability

Conversation

@fabolivark

@fabolivark fabolivark commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 6 +970 −2 +968
Prod 7 +300 −19 +281

Third slice of the upstream batch. #368 carries the six that applied cleanly, #369 the serve tab cap. These four are the highest-value items from a sweep of what upstream has already merged since our merge-base (8b04e060fa, 2026-08-15) — 1873 commits, 601 of them in our paths.

2e19342c12 — host-retired ghost panes in paired remote splits

The host-authoritative layout reconciler only ever materialized panes the host named; it never unmounted one the host stopped naming. A pane whose PTY ended stays mounted as a ghost — it renders nothing and, once it is the last pane, absorbs the tab's next close.

This is the "mirrored tabs duplicate or desync" symptom in a remote split. Verified missing here before porting: planRetiredPaneRemoval matched nothing in the tree.

The three helpers land as-is. The wiring is the port: upstream consumes them from use-terminal-pane-reconciliation.ts, a hook it extracted after our divergence, so the removal goes in the same TerminalPane.tsx effect that already applied insertions. Its two own files are dropped for that reason.

A leaf only counts as retired against the layout the host named before this one, so the hook's two refs move next to the other pane refs. ptyRecoveryStatesByPaneId joins the deps because it is what re-runs the effect once a retired pane's PTY finishes ending — that is how a pane whose PTY is still closing gets removed on the next pass instead of being killed early.

31b84cc71f — an I/O failure is not exit evidence

A throw from write or resize set dead = true — the same flag a real exit sets — which disabled kill, forceKill, signal and the producer's flow control. The session could never be terminated again. Our two bug lines were byte-identical to the two upstream deletes (pty-subprocess.ts:1175, :1188).

Separates ioFailed from dead with the same three guards upstream applies (write, resize, pause); resume is left alone, as there.

Upstream's tests cannot be ported: they take an already-created pty.IPty because upstream extracted createDaemonPtySubprocessHandle into its own module, while our createPtySubprocess spawns the process itself. Three tests written against our seam using the harness that already exists — two of the three verified failing with the fix reverted.

ed881889c4 — fold-safe partial escape tail

extractPartialEscapeTail broke its own fold invariant in the oscEsc/stringEsc states: a PTY read split at the wrong byte produced a different tail than the same bytes delivered whole, so the tail appended after a restore was corrupt. Non-deterministic by nature — it depends on where the chunk splits. Upstream's fuzz over 1.25 M splits went 421 failures → 0, and that fuzz file comes with it.

Its only conflict was config/reliability-gates.jsonc: the commit edits a gate entry (terminal-session.shell-owned-mode-recovery) this tree does not have at all, so there is nothing for the edit to land on. Registry still validates — 82 gates.

c36dd5f4c7 — skip the tail walk on ESC-free chunks

advancePartialEscapeTail runs once per PTY chunk, on the main thread, for every terminal — visible, hidden or parked — and concatenated the pending tail with the whole chunk to walk it code unit by code unit. With no pending tail and no ESC the answer is always ''. ESC-free streams (build logs, cat, piped output): 40.3 ms → 0.19 ms over 10 MB. It is the same gate its two neighbours in that ingest path already apply; this call was missed.

Only package.json conflicted, over bench entries. Took only the one whose benchmark file this commit brings; upstream's other two point at files added after our merge-base and would be dead commands here.

Tests

4317 terminal-pane, 25 reconciler, 16 escape-tail (fuzz included), 3 new PTY I/O. Gates: max-lines OK, check:test-case-deletion OK (61791 cases, none lost), reliability-gates OK. The no-adjust-state-on-prop-change warning in TerminalPane.tsx is pre-existing — verified by stashing against main.

nwparker and others added 6 commits September 9, 2026 10:49
…nks (#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)
…scape 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)
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.
…eam #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.
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.
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.
@fabolivark
fabolivark merged commit 74fa4e0 into main Sep 9, 2026
46 checks passed
@fabolivark
fabolivark deleted the feat/upstream-terminal-stability branch September 9, 2026 16:35
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.

2 participants