Repository navigation
fix(terminal): a restarted relay must not hand a new tab a dead PTY's exit - #16970
Conversation
… exit A redeployed SSH relay renumbers its PTY ids from pty-1, so a freshly spawned PTY can be handed an id a dead one used to own. The renderer's pre-handler buffer is keyed on that id alone, so `registerExit` found the dead PTY's buffered exit and reported the brand-new shell as `exitedBeforeAttach` — the pane never bound a PTY and the tab came up blank forever. Date every buffered record with a monotonic sequence and fence a fresh spawn against it: state recorded before the spawn request left the renderer belongs to the id's earlier owner. State recorded after it is kept, so the real pre-attach race (a shell that dies instantly, or writes before the pane registers its handler) still works. Makes ssh-lost-kill-tab-resurrection.spec.ts:178 pass; it failed in SETUP.
📝 WalkthroughWalkthroughThe PTY pre-handler buffer now assigns monotonic sequences to buffered data and exits. It exposes a sequence fence and removes state recorded before or at the fence for reused PTY IDs. Newer events remain available, and consumed-exit suppression resets for the new incarnation. Merge Risk: 🟡 Moderate · up to The change prevents previously buffered PTY state from being reused in the common relay-restart case, but mixed buffered output and delayed events for recycled PTY IDs can still be assigned to a newly opened terminal. That could show stale terminal data or incorrectly make a live shell appear dead, so the remaining ownership race should be fixed or explicitly accepted before merge. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description provides detailed ELI5, root-cause, change, rationale, issue, risk, and verification information. However, it omits several required template sections, including Visual Proof, the explicit Linked Issue section with a Fixes reference, Review, Agent skill upstream boundary, Notes, and Checklist. Resolution Add the missing template sections. For Visual Proof, write N/A with a reason if no visual change exists. Add the required issue reference in the Linked Issue section. Include the testing checkboxes and the required compatibility, review, and checklist information.
✨ 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: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: f9c7eebd-1ef5-4dd9-ae0a-fe9256738b5e
📒 Files selected for processing (3)
src/renderer/src/components/terminal-pane/ipc-pty-connect.tssrc/renderer/src/components/terminal-pane/pty-pre-handler-buffer.test.tssrc/renderer/src/components/terminal-pane/pty-pre-handler-buffer.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.
| /** Sequence of the newest chunk, used to fence state left by a prior incarnation of a reused id. */ | ||
| sequence: number |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Track the sequence for each buffered chunk.
state.sequence is overwritten for each append. If stale data exists before the fence and startup data arrives after it, Line 161 retains both chunks and drains stale output into the new pane. Filter chunks by their own sequence when applying the fence.
Also applies to: 76-79, 160-162
…ust the check
Review caught a swallowed exit. Keying only the comparison on the incarnation
while the storage stayed one slot per pty id left the two races this buffer
exists for able to cancel each other out:
1. the freshly spawned shell dies before the pane attaches -> its exit (X) is
buffered;
2. the relay flushes the previous owner's exit for the same recycled id (W),
which OVERWRITES X in the single slot;
3. the spawn reply names X, so the identity discard drops W -- the only
record left.
registerExit then finds nothing and the pane binds to a PTY that is dead and
will never be reported dead: a hang instead of the blank tab #16970 fixed.
Store one record per lifetime, capped at 4 per id, so W can never evict X. A
duplicate exit for a lifetime replaces that lifetime's record rather than
crowding out another's; drain still delivers the newest survivor, preserving
the last-write-wins behaviour a single slot always had.
… sequence fence (#17010) * fix(pty): key buffered pre-attach exits on the PTY incarnation, not a clock A restarted SSH relay renumbers PTYs from pty-1, so a fresh spawn is routinely handed an id whose previous shell is still emitting a late exit. #16970 stopped that exit blanking the new tab by dating every buffered record and dropping anything older than the spawn request. That fence is a clock, so it cannot judge a stale exit that arrives AFTER the request left — the residual risk #16970 documented. Thread the incarnation main already puts on the pty:exit payload (and the pty:spawn reply) through preload to the pre-handler buffer, so a buffered exit names which lifetime of the id died. An exit disagreeing with the incarnation now attaching is discarded whenever it arrived. Only a positive disagreement discards: absence stays "unknown", never a mismatch, so hosts that predate the field keep #16970's behaviour exactly. The fence is retained for the two cases with no incarnation to compare — buffered bytes (pty:data carries none) and unnamed exits. No wire change: incarnationId was already published on the relay's pty.exit notification and pty.spawn reply, and already forwarded over the in-process pty:exit / pty:spawn IPC. Only the preload types and the renderer read it now. * fix(pty): read the incarnation through the shared guard, not truthiness A malformed incarnation is evidence of nothing, so it must read as "unknown" rather than as a value that disagrees with every well-formed one — otherwise a non-string on the payload would discard the very exits the buffer exists to deliver. Route both the record and the comparison through the existing isPtyIncarnationId guard. * refactor(pty): name the bounded-map helper after what it does It evicts the oldest entry when the map is full and the id is new; it reserves nothing. Rename only — no behaviour change. * fix(pty): key the buffered-exit STORAGE on the incarnation too, not just the check Review caught a swallowed exit. Keying only the comparison on the incarnation while the storage stayed one slot per pty id left the two races this buffer exists for able to cancel each other out: 1. the freshly spawned shell dies before the pane attaches -> its exit (X) is buffered; 2. the relay flushes the previous owner's exit for the same recycled id (W), which OVERWRITES X in the single slot; 3. the spawn reply names X, so the identity discard drops W -- the only record left. registerExit then finds nothing and the pane binds to a PTY that is dead and will never be reported dead: a hang instead of the blank tab #16970 fixed. Store one record per lifetime, capped at 4 per id, so W can never evict X. A duplicate exit for a lifetime replaces that lifetime's record rather than crowding out another's; drain still delivers the newest survivor, preserving the last-write-wins behaviour a single slot always had. * fix(pty): filter buffered exits by lifetime inside the buffer, not at call sites Review found the identity was enforced only where connectIpcPty calls the discard, while preHandlerPtyExit has several other consumers. The severe one is registerEagerPtyBuffer: both background launchers spawn directly and then drain whatever is buffered for the returned id, so a relay-recycled id holding the previous owner's exit tore a freshly launched agent session down seconds after it started -- no fence, no admitPtyId, no identity check at all. Move the rule into the buffer: every read goes through admissiblePreHandlerPtyExits, so a record proven to belong to another lifetime is unreachable by construction rather than because each caller remembered to discard first. hasPreHandlerPtyExit/drainPreHandlerPtyExit take the asking lifetime; registerEagerPtyBuffer and registerExit thread it through, and both background launchers pass the incarnation their own spawn returned. A reader that cannot name an incarnation still sees everything, which is the honest answer -- it holds no evidence to discriminate with. That keeps the pre-spawn fast path in connectIpcPty behaving exactly as it does today; see the PR for the consumers this still does not cover. * chore: drop unrelated formatter churn in reliability-gates.jsonc Repo-wide oxfmt reindented pre-existing entries in a file this change never touches. Keep the diff to the PTY incarnation work.
… exit (stablyai#16970) A redeployed SSH relay renumbers its PTY ids from pty-1, so a freshly spawned PTY can be handed an id a dead one used to own. The renderer's pre-handler buffer is keyed on that id alone, so `registerExit` found the dead PTY's buffered exit and reported the brand-new shell as `exitedBeforeAttach` — the pane never bound a PTY and the tab came up blank forever. Date every buffered record with a monotonic sequence and fence a fresh spawn against it: state recorded before the spawn request left the renderer belongs to the id's earlier owner. State recorded after it is kept, so the real pre-attach race (a shell that dies instantly, or writes before the pane registers its handler) still works. Makes ssh-lost-kill-tab-resurrection.spec.ts:178 pass; it failed in SETUP. (cherry picked from commit f5fb60b)
… sequence fence (stablyai#17010) * fix(pty): key buffered pre-attach exits on the PTY incarnation, not a clock A restarted SSH relay renumbers PTYs from pty-1, so a fresh spawn is routinely handed an id whose previous shell is still emitting a late exit. stablyai#16970 stopped that exit blanking the new tab by dating every buffered record and dropping anything older than the spawn request. That fence is a clock, so it cannot judge a stale exit that arrives AFTER the request left — the residual risk stablyai#16970 documented. Thread the incarnation main already puts on the pty:exit payload (and the pty:spawn reply) through preload to the pre-handler buffer, so a buffered exit names which lifetime of the id died. An exit disagreeing with the incarnation now attaching is discarded whenever it arrived. Only a positive disagreement discards: absence stays "unknown", never a mismatch, so hosts that predate the field keep stablyai#16970's behaviour exactly. The fence is retained for the two cases with no incarnation to compare — buffered bytes (pty:data carries none) and unnamed exits. No wire change: incarnationId was already published on the relay's pty.exit notification and pty.spawn reply, and already forwarded over the in-process pty:exit / pty:spawn IPC. Only the preload types and the renderer read it now. * fix(pty): read the incarnation through the shared guard, not truthiness A malformed incarnation is evidence of nothing, so it must read as "unknown" rather than as a value that disagrees with every well-formed one — otherwise a non-string on the payload would discard the very exits the buffer exists to deliver. Route both the record and the comparison through the existing isPtyIncarnationId guard. * refactor(pty): name the bounded-map helper after what it does It evicts the oldest entry when the map is full and the id is new; it reserves nothing. Rename only — no behaviour change. * fix(pty): key the buffered-exit STORAGE on the incarnation too, not just the check Review caught a swallowed exit. Keying only the comparison on the incarnation while the storage stayed one slot per pty id left the two races this buffer exists for able to cancel each other out: 1. the freshly spawned shell dies before the pane attaches -> its exit (X) is buffered; 2. the relay flushes the previous owner's exit for the same recycled id (W), which OVERWRITES X in the single slot; 3. the spawn reply names X, so the identity discard drops W -- the only record left. registerExit then finds nothing and the pane binds to a PTY that is dead and will never be reported dead: a hang instead of the blank tab stablyai#16970 fixed. Store one record per lifetime, capped at 4 per id, so W can never evict X. A duplicate exit for a lifetime replaces that lifetime's record rather than crowding out another's; drain still delivers the newest survivor, preserving the last-write-wins behaviour a single slot always had. * fix(pty): filter buffered exits by lifetime inside the buffer, not at call sites Review found the identity was enforced only where connectIpcPty calls the discard, while preHandlerPtyExit has several other consumers. The severe one is registerEagerPtyBuffer: both background launchers spawn directly and then drain whatever is buffered for the returned id, so a relay-recycled id holding the previous owner's exit tore a freshly launched agent session down seconds after it started -- no fence, no admitPtyId, no identity check at all. Move the rule into the buffer: every read goes through admissiblePreHandlerPtyExits, so a record proven to belong to another lifetime is unreachable by construction rather than because each caller remembered to discard first. hasPreHandlerPtyExit/drainPreHandlerPtyExit take the asking lifetime; registerEagerPtyBuffer and registerExit thread it through, and both background launchers pass the incarnation their own spawn returned. A reader that cannot name an incarnation still sees everything, which is the honest answer -- it holds no evidence to discriminate with. That keeps the pre-spawn fast path in connectIpcPty behaving exactly as it does today; see the PR for the consumers this still does not cover. * chore: drop unrelated formatter churn in reliability-gates.jsonc Repo-wide oxfmt reindented pre-existing entries in a file this change never touches. Keep the diff to the PTY incarnation work. (cherry picked from commit a907dd2)
… exit (stablyai#16970) A redeployed SSH relay renumbers its PTY ids from pty-1, so a freshly spawned PTY can be handed an id a dead one used to own. The renderer's pre-handler buffer is keyed on that id alone, so `registerExit` found the dead PTY's buffered exit and reported the brand-new shell as `exitedBeforeAttach` — the pane never bound a PTY and the tab came up blank forever. Date every buffered record with a monotonic sequence and fence a fresh spawn against it: state recorded before the spawn request left the renderer belongs to the id's earlier owner. State recorded after it is kept, so the real pre-attach race (a shell that dies instantly, or writes before the pane registers its handler) still works. Makes ssh-lost-kill-tab-resurrection.spec.ts:178 pass; it failed in SETUP.
… sequence fence (stablyai#17010) * fix(pty): key buffered pre-attach exits on the PTY incarnation, not a clock A restarted SSH relay renumbers PTYs from pty-1, so a fresh spawn is routinely handed an id whose previous shell is still emitting a late exit. stablyai#16970 stopped that exit blanking the new tab by dating every buffered record and dropping anything older than the spawn request. That fence is a clock, so it cannot judge a stale exit that arrives AFTER the request left — the residual risk stablyai#16970 documented. Thread the incarnation main already puts on the pty:exit payload (and the pty:spawn reply) through preload to the pre-handler buffer, so a buffered exit names which lifetime of the id died. An exit disagreeing with the incarnation now attaching is discarded whenever it arrived. Only a positive disagreement discards: absence stays "unknown", never a mismatch, so hosts that predate the field keep stablyai#16970's behaviour exactly. The fence is retained for the two cases with no incarnation to compare — buffered bytes (pty:data carries none) and unnamed exits. No wire change: incarnationId was already published on the relay's pty.exit notification and pty.spawn reply, and already forwarded over the in-process pty:exit / pty:spawn IPC. Only the preload types and the renderer read it now. * fix(pty): read the incarnation through the shared guard, not truthiness A malformed incarnation is evidence of nothing, so it must read as "unknown" rather than as a value that disagrees with every well-formed one — otherwise a non-string on the payload would discard the very exits the buffer exists to deliver. Route both the record and the comparison through the existing isPtyIncarnationId guard. * refactor(pty): name the bounded-map helper after what it does It evicts the oldest entry when the map is full and the id is new; it reserves nothing. Rename only — no behaviour change. * fix(pty): key the buffered-exit STORAGE on the incarnation too, not just the check Review caught a swallowed exit. Keying only the comparison on the incarnation while the storage stayed one slot per pty id left the two races this buffer exists for able to cancel each other out: 1. the freshly spawned shell dies before the pane attaches -> its exit (X) is buffered; 2. the relay flushes the previous owner's exit for the same recycled id (W), which OVERWRITES X in the single slot; 3. the spawn reply names X, so the identity discard drops W -- the only record left. registerExit then finds nothing and the pane binds to a PTY that is dead and will never be reported dead: a hang instead of the blank tab stablyai#16970 fixed. Store one record per lifetime, capped at 4 per id, so W can never evict X. A duplicate exit for a lifetime replaces that lifetime's record rather than crowding out another's; drain still delivers the newest survivor, preserving the last-write-wins behaviour a single slot always had. * fix(pty): filter buffered exits by lifetime inside the buffer, not at call sites Review found the identity was enforced only where connectIpcPty calls the discard, while preHandlerPtyExit has several other consumers. The severe one is registerEagerPtyBuffer: both background launchers spawn directly and then drain whatever is buffered for the returned id, so a relay-recycled id holding the previous owner's exit tore a freshly launched agent session down seconds after it started -- no fence, no admitPtyId, no identity check at all. Move the rule into the buffer: every read goes through admissiblePreHandlerPtyExits, so a record proven to belong to another lifetime is unreachable by construction rather than because each caller remembered to discard first. hasPreHandlerPtyExit/drainPreHandlerPtyExit take the asking lifetime; registerEagerPtyBuffer and registerExit thread it through, and both background launchers pass the incarnation their own spawn returned. A reader that cannot name an incarnation still sees everything, which is the honest answer -- it holds no evidence to discriminate with. That keeps the pre-spawn fast path in connectIpcPty behaving exactly as it does today; see the PR for the consumers this still does not cover. * chore: drop unrelated formatter churn in reliability-gates.jsonc Repo-wide oxfmt reindented pre-existing entries in a file this change never touches. Keep the diff to the PTY incarnation work.
What was red
tests/e2e/ssh-lost-kill-tab-resurrection.spec.ts:178— "does not resurrect tabs whose kill was lost to a killed relay daemon" — the end-to-end oracle for the headline user report ("every day I come back to my SSH session there are more tabs", STA-4658 / #16752).It failed in SETUP, never reaching a resurrection assertion:
Reproduced locally against real Docker (
pnpm test:e2e:ssh-docker) and confirmed red in CI, on this branch's merge-base and onmain. Its sibling at:190passed, so the harness itself was fine.Root cause — this was a PRODUCT bug, not a test problem
src/renderer/src/components/terminal-pane/pty-pre-handler-buffer.ts:24keeps a process-global map of PTY exits that arrived with no registered pane handler, keyed on the PTY id alone:PTY ids are not unique over time. A redeployed SSH relay renumbers from
pty-1. So:ssh:<target>@@pty-2buffered — its pane is already unmounted, so nothing consumes it.pty-1.ssh:<target>@@pty-2.src/renderer/src/components/terminal-pane/ipc-pty-connect.ts:95doeshandlers.registerExit(spawnResult.id), which finds the dead previous incarnation's buffered exit and returnsexitedBeforeAttach: true.data-pty-idis never set. The tab is blank forever.Evidence (instrumented Docker run)
The host really did create the shell — the relay had a live child for it:
Main resolved the spawn normally:
The renderer threw that live shell away:
…while the SSH target reported
status: "connected". Nothing was down, nothing was racing — the client misattributed a dead PTY's exit to a live one.Why the sibling test passes: an orderly
ssh.disconnectnever kills the remote relay, so ids are never renumbered and never collide.User-facing impact
Kill or crash the relay daemon (host reboot, network partition, laptop sleep, relay crash) and close a tab in that window — the next terminal tab you open on that host comes up permanently dead. Silent: no error, just a blank pane. The same stale-id reuse also let a dead PTY's buffered bytes paint into the new pane.
The fix
Date every buffered record with a monotonic sequence, and fence a fresh spawn against it.
pty-pre-handler-buffer.ts: buffered exits and buffered data now carry asequence; newcurrentPreHandlerPtySequence()anddiscardPreHandlerPtyStateFromPriorIncarnation(ptyId, fenceSequence).ipc-pty-connect.ts:76reads the fence before the spawn request leaves the renderer;:99applies it once the id comes back, for fresh spawns only.State recorded at or below the fence was recorded when this PTY did not yet exist, so it belongs to the id's earlier owner and is dropped. State recorded after the fence is kept — that is the genuine pre-attach race (a shell that dies instantly, or writes before the pane registers its handler), and losing it would blank a legitimate pane. Reattach and cold-restore are untouched: they deliberately re-own an id that already existed, so their buffered exit is the real thing.
Renderer-local only — no IPC shape change, no relay protocol change, nothing persisted, so no remote wire-compatibility surface.
ELI5
Terminals on a remote machine get numbered tickets: shell #1, shell #2. When the remote helper program restarts, it forgets everything and starts handing out tickets from #1 again.
Orca had a lost-and-found box for "this shell died" notes, filed by ticket number. An old note saying "shell #2 died" was still sitting in the box. Then you opened a new terminal, the restarted helper gave it ticket #2, Orca checked the box, found the old note, and concluded your brand-new terminal was already dead. So it showed you an empty black rectangle — even though a perfectly good shell was running on the other end, waiting.
The fix stamps every note with a timestamp. When a new terminal is created, Orca ignores any note written before it asked for that terminal, because a note about something that didn't exist yet cannot be about it. Notes written after — like a shell that really did crash a split second after starting — still count.
Verification
pnpm tcclean ·oxlintclean on changed files ·pnpm test src/renderer/src/components/terminal-pane/→ 403 files, 3899 tests passed · 3 new unit tests covering drop-before-fence, keep-after-fence, and consumed-mark re-admission.Three consecutive Docker E2E runs (literal output)
Both tests in the file, three times, no retries. The oracle for the tab-accumulation fix now actually runs — and its resurrection assertions pass, so #16752's fix is confirmed end-to-end rather than merely assumed.
Residual risk
The fence catches stale state recorded before the spawn request. It would not catch a stale exit for a recycled id that arrives after the request was dispatched — a delayed duplicate crossing the spawn. Closing that window exactly needs the buffer keyed on PTY incarnation id, which means threading
incarnationIdthrough thepty:exitIPC. Larger change, deliberately not taken on release day. The observed failure records the stale exit during the reconnect, well before the next tab exists.