Repository navigation
fix(relay): mint PTY ids that carry the relay incarnation instead of a restarting counter - #16901
Conversation
📝 WalkthroughWalkthroughPtyHandler now generates Merge Risk: 🟠 High · up to After a terminal is successfully reattached, a previously scheduled cleanup timer can still force-kill that live terminal several seconds later. This can terminate the user's shell or running work, so the PR is not merge-ready until the timer is canceled or otherwise prevented from reaping restored terminals. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Description checkExplanation The description is detailed, focused, and explains the problem, solution, scope, compatibility, tests, and verification. It mentions issue STA-5698 and explains that there is no visible behavior change, although it does not reproduce every template heading or checklist item.
✨ 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 |
…tions The epoch escaping had no test: dropping encodeURIComponent left the whole relay suite green. Pin the three-field id shape against an epoch that carries both separators, and cover a colon-bearing relay id through the unchanged app-side SSH id wrapper. subprocess.test.ts had traded `pty-1`/`pty-2` for `expect.any(String)`, which discarded the invariant those two cases exist to prove: an early node-pty load failure burns no sequence, a late spawn failure burns one.
The harness built the expected id without the encodeURIComponent production applies at the mint site. A test epoch carrying a reserved character would diverge silently across ~40 assertions in 11 files.
Review loop — round 1Reviewed at head VerdictPatched, not superseded. The design is what I would write from scratch: it mirrors the in-repo precedent in Is this redundant once #16894 and #16895 land?No — and the relationship runs the other way. Those two prevent orphan processes; this one prevents identifier reuse, which bites with zero orphans present. A client holding a durable binding to Three specifics:
This is also the only one of the three that helps on Linux, where a Live A/B on a real remote Linux hostBuilt this branch's relay and the currently shipped relay, ran both against the real
The shipped relay reproduces the collision verbatim — identical id strings naming different shells. This branch cannot. Defects found and fixed
Ablation
CompatibilityRule 3 of Blast radius is SSH-remote only — Gates
Not verified
|
CI follow-up — the one red check is not this PR, but it will block the mergeHead is now Why this is not a regression from this change
Why it appeared only nowThe earlier green run of this job at What this means for mergingThe lane will be red on this PR, and on any future PR that touches SSH source, until that spec is fixed. The fix is to drop the inline duplicate and call the shared Stated plainly so it is not mistaken for verified: I diagnosed this from the diff, the job logs, and the two connect implementations. I did not run the spec against |
Correction — the two local test failures are environmental, not platform-specificIn my first comment I called Both fail because the shell running the suite is itself an Orca agent pane, so ambient So they are not a defect on Two further notes from the review, neither merge-blocking and neither acted on:
|
Greptile SummaryThe PR namespaces newly minted relay PTY IDs by relay-handler incarnation while preserving legacy and foreign-epoch IDs during revival.
Confidence Score: 5/5The PR appears safe to merge. No blocking failure remains.
|
| Filename | Overview |
|---|---|
| src/relay/pty-handler.ts | Introduces an encoded, per-handler mint epoch for fresh PTY IDs while retaining collision checks and legacy revival behavior. |
| src/relay/pty-handler-test-harness.ts | Provides deterministic epoch-scoped IDs and handler construction for tests. |
| src/relay/pty-handler-spawn-admission.test.ts | Covers cross-lifetime uniqueness, separator escaping, legacy revival, and foreign-epoch revival. |
| src/shared/ssh-pty-id.test.ts | Confirms the new colon-bearing relay IDs survive SSH wrapping and routing unchanged. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart LR
A[Relay handler starts] --> B[Generate random mint epoch]
B --> C[Spawn PTY]
C --> D["Mint pty2:<epoch>:<sequence>"]
D --> E[Persist and route ID as opaque string]
F[Relay replacement] --> G[Generate different epoch]
G --> H[New PTY cannot reuse old incarnation ID]
I[Revive serialized PTY] --> J{Legacy pty-N?}
J -->|Yes| K[Preserve ID and advance legacy sequence]
J -->|No| L[Preserve foreign ID opaquely]
Reviews (2): Last reviewed commit: "Merge branch 'main' into brennanb2025/st..." | Re-trigger Greptile
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/relay/pty-handler.ts (1)
1839-1845: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winCancel the pending reap sweep after a successful reattach.
shutdown()armsmanaged.reapTimerbefore issuing the kill. If the PTY survives and the client reattaches before the 6-second sweep, this block restores the pane surface but leaves the timer active. The sweep then sees a live PID and callsrequestForceKill, terminating the reattached PTY.Clear
managed.reapTimerwhen the attach is accepted, or make the sweep stop when the pane surface is restored.Proposed fix
if (attachedPaneKey) { this.retiredPaneSurfaces.restore(attachedPaneKey) + if (managed.reapTimer) { + clearTimeout(managed.reapTimer) + managed.reapTimer = undefined + } }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: c10e2cb8-6525-4cb1-8757-5aadd39bf027
📒 Files selected for processing (1)
src/relay/pty-handler.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.
…a restarting counter (stablyai#16901) * fix(relay): scope PTY ids to mint epochs * test(relay): treat minted PTY ids as opaque * test(relay): pin mint-epoch id shape and restore spawn-sequence assertions The epoch escaping had no test: dropping encodeURIComponent left the whole relay suite green. Pin the three-field id shape against an epoch that carries both separators, and cover a colon-bearing relay id through the unchanged app-side SSH id wrapper. subprocess.test.ts had traded `pty-1`/`pty-2` for `expect.any(String)`, which discarded the invariant those two cases exist to prove: an early node-pty load failure burns no sequence, a late spawn failure burns one. * test(relay): mirror production epoch escaping in testPtyId The harness built the expected id without the encodeURIComponent production applies at the mint site. A test epoch carrying a reserved character would diverge silently across ~40 assertions in 11 files.
In plain terms
Every terminal on a remote machine gets a name from the helper program that manages it — and the names were just
terminal-1,terminal-2,terminal-3, counting up.The problem: the counter restarted from 1 every time the helper restarted. So
terminal-2today andterminal-2yesterday could be two completely different terminals. Orca remembers those names to reconnect you to your work, so after a helper restart it could ask forterminal-2and get something that had nothing to do with what you left open.Orca papered over this with a pile of guesswork — extra checks trying to work out whether a name still meant what it used to, and a fallback that quietly assumed "probably fine" when it couldn't tell.
Now each name includes a unique tag for that particular helper lifetime. A name from an old helper can never be mistaken for a new one, because a new helper can't produce that name at all.
What you'll notice: nothing directly. This removes a whole class of "Orca reconnected me to the wrong thing" confusion at the root, rather than guarding against it after the fact.
How the three PRs fit together
The original report (STA-5698) was: after the remote helper restarts, Orca might start your AI agent a second time while the first one is still running — two agents editing the same files at once.
That needs two ingredients:
These three PRs remove both ingredients rather than trying to detect the collision afterwards:
Each stands alone and they can land in any order.
Why not just detect the collision? That was the first attempt (#16843, now closed). It tried to work out "has the helper been replaced?" by comparing how long it had been running against when Orca last saw the terminal. It couldn't tell a helper restart apart from the whole machine having rebooted — and after a reboot nothing survives, so there's nothing to protect against. It would have refused to restore your agent in a case that was completely safe. A live reproduction also failed to produce the collision at all on Linux: killing the helper took the agent down with it in 0.3 seconds.
So: prevent the leftovers, fix the names, and the problem doesn't arise instead of being guessed at.
The defect
src/relay/pty-handler.tsmints PTY ids from a per-process counter:That records a position, not an identity. When a relay restarts with nothing to revive, it starts again at
pty-1— so a client's durable binding topty-2can name a different shell in a later relay lifetime.Scope, precisely: the mint is a
do/whilethat skips ids already taken, and the revive path advances the counter past whatever it parsed. So ids restart only when the new relay revives nothing — which is exactly the case a client reconnecting to a replaced relay hits.Several things in the tree exist only to compensate for this:
attachIdentityMismatches, whose own comment says it "Rejects cross-relay-generation id collisions (a reset relay reusespty-N)" — and which is permissive when identity is absentexpectedPaneKey/expectedTabIdon every attachSSH_PTY_IDENTITY_MISMATCHThe change
Mint ids that carry the relay incarnation, following the convention #16691 just established for the same problem class one layer up (
src/shared/worktree/identity.ts,wt2:${executionHostId}:${instanceId}):An id minted by a dead incarnation can no longer be minted by a live one.
Backward compatible by construction. The only structural parse of a PTY id anywhere outside tests is the revive path, and it stays legacy-only: old
pty-Nids still revive and still advance the counter exactly as before, while new-shaped ids revive opaquely without importing a foreign epoch's sequence. Ids cross the wire as opaque strings —parseAppSshPtyIdsplits on@@and takes the remainder, so the added colons are safe — and the one place an id reaches the filesystem hashes it first.Deliberately not in scope
No client-side behaviour changes, no resume guard, no change to the SSH absence fallback. This is identity hygiene only.
Tests
New coverage proves cross-lifetime uniqueness, legacy revival and counter advancement, foreign new-shape revival, and same-epoch collision freedom. The cross-lifetime assertion was confirmed red before the change (expected
pty2, receivedpty-1).Sibling suites that asserted the old minted shape were updated to treat the id as opaque rather than to hardcode the new literal — the differential harness now indexes callbacks by the actual spawned id, and the subprocess repair assertions require an id string without coupling to any mint format. Hardcoding
pty2:…would have recreated the same coupling one format later.Verification
pnpm test src/relay/(the whole directory, not a single file — a single-file run is what hid the sibling breakage in the first place) shows no failures beyond the three that fail identically onorigin/main:pty-handler-spawn-environment,pty-handler-startup-command-delivery, and a ~35s timing flake insubprocess. The last of these never callspty.spawn, so the new mint path is unreachable from it.pnpm tc,npx oxlint,pnpm oxfmt, andpnpm build:relayall pass, including when merged together with #16894 and #16895.