Skip to content

fix(terminal): a restarted relay must not hand a new tab a dead PTY's exit - #16970

Merged
nwparker merged 1 commit into
mainfrom
nwparker/relay-restart-recycled-pty-exit
Aug 28, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/relay-restart-recycled-pty-exit

Conversation

@nwparker

@nwparker nwparker commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​51 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​51
Prod 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​64 $\color{#cf222e}{\Huge{\mathbf{−}}}$​6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​58

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:

Error: Active terminal pane did not receive a PTY binding
    at waitForActivePanePtyId (tests/e2e/helpers/terminal.ts:70:3)
    at createRemoteTerminalTab (tests/e2e/helpers/docker-ssh-relay-terminal-tabs.ts:23:3)
    at runResurrectionCycles (tests/e2e/ssh-lost-kill-tab-resurrection.spec.ts:124:7)

Reproduced locally against real Docker (pnpm test:e2e:ssh-docker) and confirmed red in CI, on this branch's merge-base and on main. Its sibling at :190 passed, 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:24 keeps a process-global map of PTY exits that arrived with no registered pane handler, keyed on the PTY id alone:

const preHandlerPtyExit = new Map<string, number>()

PTY ids are not unique over time. A redeployed SSH relay renumbers from pty-1. So:

  1. A tab closed while the transport is down leaves an exit for ssh:<target>@@pty-2 buffered — its pane is already unmounted, so nothing consumes it.
  2. The relay daemon dies and Orca redeploys it. The counter restarts at pty-1.
  3. The user opens a new tab. The restarted relay mints a genuinely new shell and hands it the recycled id ssh:<target>@@pty-2.
  4. src/renderer/src/components/terminal-pane/ipc-pty-connect.ts:95 does handlers.registerExit(spawnResult.id), which finds the dead previous incarnation's buffered exit and returns exitedBeforeAttach: true.
  5. The pane treats the brand-new, live shell as already dead. data-pty-id is 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:

946     1 node  relay.js --detached --grace-time 60 ...
1177  946 bash  /bin/bash --rcfile /root/.orca-relay/shell-ready/bash/rcfile
1192  946 bash  /bin/bash --rcfile /root/.orca-relay/shell-ready/bash/rcfile

Main resolved the spawn normally:

[orca-diag] pty:spawn IN  tab=874c4d79-… leaf=0e054bd9-… session=undefined conn=ssh-…
[orca-diag] spawnFreshSshPty resolved relayId=pty-2 appId=ssh:…@@pty-2 tab=874c4d79-…
[orca-diag] pty:spawn OUT tab=874c4d79-… id=ssh:…@@pty-2

The renderer threw that live shell away:

pane=1 tab=874c4d79-… SPAWN RESOLVED raw={"id":"ssh:…@@pty-2","exitedBeforeAttach":true} genMatch=true

…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.disconnect never 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 a sequence; new currentPreHandlerPtySequence() and discardPreHandlerPtyStateFromPriorIncarnation(ptyId, fenceSequence).
  • ipc-pty-connect.ts:76 reads the fence before the spawn request leaves the renderer; :99 applies 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 tc clean · oxlint clean 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)

=== RUN 1 ===
  ✓  1 [electron-headless] › tests/e2e/ssh-lost-kill-tab-resurrection.spec.ts:178:7 › SSH lost kill tab resurrection › does not resurrect tabs whose kill was lost to a killed relay daemon (40.5s)
  ✓  2 [electron-headless] › tests/e2e/ssh-lost-kill-tab-resurrection.spec.ts:190:7 › SSH lost kill tab resurrection › does not resurrect tabs closed while the host is disconnected (41.2s)
  2 passed (1.5m)

=== RUN 2 ===
  ✓  1 [electron-headless] › tests/e2e/ssh-lost-kill-tab-resurrection.spec.ts:178:7 › SSH lost kill tab resurrection › does not resurrect tabs whose kill was lost to a killed relay daemon (39.9s)
  ✓  2 [electron-headless] › tests/e2e/ssh-lost-kill-tab-resurrection.spec.ts:190:7 › SSH lost kill tab resurrection › does not resurrect tabs closed while the host is disconnected (38.6s)
  2 passed (1.5m)

=== RUN 3 ===
  ✓  1 [electron-headless] › tests/e2e/ssh-lost-kill-tab-resurrection.spec.ts:178:7 › SSH lost kill tab resurrection › does not resurrect tabs whose kill was lost to a killed relay daemon (40.0s)
  ✓  2 [electron-headless] › tests/e2e/ssh-lost-kill-tab-resurrection.spec.ts:190:7 › SSH lost kill tab resurrection › does not resurrect tabs closed while the host is disconnected (40.7s)
  2 passed (1.5m)

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 incarnationId through the pty:exit IPC. Larger change, deliberately not taken on release day. The observed failure records the stale exit during the reconnect, well before the next tab exists.

… 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.
@coderabbitai

coderabbitai Bot commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The 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. connectIpcPty records a fence before spawning and applies cleanup only to fresh spawns. Tests cover stale-state removal, newer-event retention, and exit re-admission.

Merge Risk: 🟡 Moderate · up to 5dfce

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)

Check name Status Explanation Resolution
Description check ⚠️ Warning 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 expl… 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, an…
Docstring Coverage ⚠️ Warning Docstring coverage is 12.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 8 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely identifies the terminal bug caused by a restarted relay handing a new tab a stale PTY exit.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

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.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between b1fe907 and 5dfcebb.

📒 Files selected for processing (3)
  • src/renderer/src/components/terminal-pane/ipc-pty-connect.ts
  • src/renderer/src/components/terminal-pane/pty-pre-handler-buffer.test.ts
  • src/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.

Comment on lines +14 to +15
/** Sequence of the newest chunk, used to fence state left by a prior incarnation of a reused id. */
sequence: number

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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

@nwparker
nwparker merged commit f5fb60b into main Aug 28, 2026
29 checks passed
nwparker added a commit that referenced this pull request Aug 28, 2026
…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.
nwparker added a commit that referenced this pull request Aug 28, 2026
… 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.
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 30, 2026
… 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)
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 30, 2026
… 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)
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
… 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.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
… 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.
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