Repository navigation
Fix native PTY I/O failures disabling session termination - #19523
Conversation
I/O failures on write or resize were incorrectly treated as exit evidence, which disabled further termination attempts and producer flow control. Separate ioFailed state from dead state; I/O errors suppress operations but keep kill, forceKill, and signal available. Publish physical exit before notifying listeners to prevent reentrant cleanup attempts from accessing the retired native process.
|
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 (2)
🚧 Files skipped from review as they are similar to previous changes (2)
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review. 📝 WalkthroughWalkthroughThe subprocess handle now tracks PTY I/O failure separately from physical process exit. Failed write, resize, and clear operations stop without disabling termination. Exit handling marks the process dead and suppresses reentrant termination before notifying listeners. New tests cover macOS, Linux, and Windows mocks, repeated cleanup cycles, ConPTY ownership, and native POSIX process and descriptor cleanup. A reliability gate documents the invariant, test commands, evidence, budgets, and known gaps. Merge Risk: ⚪ Minimal · up to This change separates PTY I/O failure handling from process-exit state so failed I/O no longer prevents termination and cleanup. No actionable merge-blocking risk remains in the supplied change context. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description explains the problem, solution, scope, testing, and lack of UI changes. However, the required Linked Issue field is incomplete because it contains only Full details: Docstring CoverageExplanation Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 3 functions across 3 files. (1 skipped: 1 unsupported.)
✨ 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.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 78385c77-6532-4574-8c10-e2193c90d76e
📒 Files selected for processing (4)
config/reliability-gates.jsoncsrc/main/daemon/pty-subprocess-io-failure-cleanup.test.tssrc/main/daemon/pty-subprocess-io-failure-native.test.tssrc/main/daemon/pty-subprocess/subprocess-handle.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
There was a problem hiding this comment.
Caution
This PR breaks pnpm lint: the new reliability gate was inserted inside the previous gate object, leaving config/reliability-gates.jsonc as invalid JSONC.
Reviewed changes
ioFailed/deadsplit —src/main/daemon/pty-subprocess/subprocess-handle.tsnow tracks I/O failure separately from process exit, sowrite/resize/clearare suppressed after a native error whilekill/forceKill/signalstay available until the process actually exits.- Exit-listener reentrancy fence — the merged
onExithandler now marksdead, neutralizesnativeProc.kill(non-Windows), andmarkDead()s the foreground tracker beforeacceptExitnotifies listeners, so a listener re-enteringkill/forceKill/signalcan no longer signal a retired PID. - Two new test suites — a fault-injected suite (write/resize failures across simulated platforms, 32-cycle reap loop, reentrancy) and a native POSIX suite (real shells, ESRCH + EBADF assertions).
- Reliability gate — a new
terminal-session.io-failure-cleanupexperimental gate documents the contract.
The core handle change is correct and well-tested; the only blocking issue is the malformed gate manifest below.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
- Fixed missing closing brace and comma in reliability-gates.jsonc - Added clear() operation to PTY mock fixture and test coverage - Enhanced assertions to verify operation suppression during I/O failures - Improved kill operation error handling with better promise-chain assertions - Updated test result summaries in reliability gate documentation
…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]>

Problem
When a native PTY I/O operation (write or resize) fails, the subprocess handle sets a
deadflag that blocks all subsequent operations—including termination. This prevents killing or force-killing the session until the process naturally exits.Solution
Separate I/O failure handling from process exit:
ioFailedflag: Suppresses further I/O ops after transient errors, but keeps termination and producer flow control availabledeadflag: Only set after the process actually exits, blocks reentrant signals from exit listenersWhat Changed
src/main/daemon/pty-subprocess/subprocess-handle.ts: SplitioFailedfromdead; neutralize kill before exit eventssrc/main/daemon/pty-subprocess-io-failure-cleanup.test.ts: 24 tests covering write/resize failures across platforms, exit-listener reentrancy, and 32 failed-I/O create/close cyclessrc/main/daemon/pty-subprocess-io-failure-native.test.ts: 4 native POSIX tests with real shells verifying PID reaping and fd closureconfig/reliability-gates.jsonc: Reliability gate documenting coverage, invariants, and test commandsWhy
I/O failures are transient communication issues, not evidence of process exit. Termination must remain available regardless. The fix ensures graceful and forced shutdown work until the process genuinely exits.
Linked Issue
Fixes #
Visual Proof
N/A — no UI change.
Testing
AI Disclosure
Review
Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
Ensure no issues in: Security, Cross-platoform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)