Repository navigation
fix(pty): do not re-run an agent resume against a relay that never held the PTY (STA-5698) - #17471
brennanb2025 wants to merge 9 commits into
Conversation
Greptile SummaryThe PR prevents automatic agent resume when a replacement SSH relay did not own the previous PTY.
Confidence Score: 5/5The PR appears safe to merge. No blocking failure remains.
|
| Filename | Overview |
|---|---|
| src/main/ipc/pty/pane/relay-pty-mint-epoch.ts | Introduces relay-epoch comparison, resume-option stripping, and bounded one-shot retired-owner bookkeeping. |
| src/main/ipc/pty/pane/stable-owner.ts | Applies the epoch verdict before the fresh-spawn fallback and annotates declined resumes. |
| src/main/ssh/ssh-relay-session.ts | Preserves the prior epoch-bearing PTY identity when reconnect recovery retires an owner. |
| src/main/ipc/pty/ipc/spawn-commit.ts | Prevents declined resumes from installing launch authority, aliases, telemetry, or launch configuration. |
| src/main/runtime/orca-runtime.ts | Propagates declined-resume state while clearing agent launch metadata from replacement shells. |
| src/renderer/src/components/terminal-pane/pty-connection/declined-agent-resume.ts | Cancels pending startup delivery and clears stale renderer-side agent identity after a decline. |
| src/relay/relay-daemon.ts | Exposes the relay PTY mint epoch through relay.status for recovery comparison. |
Sequence Diagram
sequenceDiagram
participant UI as Terminal pane
participant Main as Main PTY recovery
participant Relay as Answering SSH relay
UI->>Main: Restore pane and resume agent
Main->>Relay: Attach previous PTY
Relay-->>Main: PTY absent
Main->>Relay: relay.status
Relay-->>Main: Current PTY mint epoch
alt Epoch matches previous PTY
Main->>Relay: Spawn with resume intent
Relay-->>UI: Resumed agent PTY
else Epoch differs
Main->>Relay: Spawn shell without resume intent
Relay-->>UI: Fresh shell + resume unavailable
else Epoch unavailable
Main->>Relay: Preserve compatibility resume behavior
Relay-->>UI: Existing recovery behavior
end
Reviews (6): Last reviewed commit: "fix(pty): suppress reminted authority on..." | Re-trigger Greptile
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (29)
🚧 Files skipped from review as they are similar to previous changes (28)
Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review. 📝 WalkthroughWalkthroughThe change adds relay PTY mint-epoch tracking for stable-pane recovery. A resume request from a retired owner in a different relay epoch is stripped of agent fields and marked unavailable. The marker propagates through IPC, runtime, and renderer contracts. Declined resumes skip spawn side effects and startup delivery. Renderer launch state, timers, and foreground-agent state are cleared. Tests cover epoch comparison, recovery, propagation, and cleanup. Merge Risk: 🟡 Moderate · up to The PR changes recovery to avoid restarting an agent against a replacement relay, but several current edge cases can still bypass that protection or suppress a requested fresh launch. These bounded correctness issues should be fixed or explicitly accepted before merge. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Description checkExplanation The description is detailed, relevant, and covers the change, rationale, linked issue, testing, validation, performance, and trade-offs. It omits several template headings, including Visual Proof, but the core required information is present. Full details: Docstring CoverageExplanation Docstring coverage is 7.14% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 28 functions across 28 files. (1 skipped: 1 too large.) ✨ Finishing Touches 💡 2📝 Generate docstrings 💡
🛠️ Fix failing CI checks 💡
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
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/ipc/pty/runtime/spawn-execute.ts (1)
63-84: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy liftApply the relay-epoch gate before structured agent-session spawning.
When
args.agentSessionEnsureis present, this branch bypassesspawnForStablePaneand sendsctx.spawnOptionsdirectly toctx.provider.spawn. A cold resume on a replacement relay can therefore retainagentSessionEnsure,resumeProviderSession, launch fields, and the launch token. Run the same retired-owner epoch evaluation before this branch creates or adopts an owner. ReturnagentResumeUnavailablewhen that evaluation declines the resume.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 901b4b6e-8c54-4152-bc2f-20728b78a44b
📒 Files selected for processing (29)
src/main/ipc/pty/ipc/spawn-commit-persist.tssrc/main/ipc/pty/ipc/spawn-commit.tssrc/main/ipc/pty/ipc/spawn-execute.tssrc/main/ipc/pty/ipc/spawn-options.tssrc/main/ipc/pty/pane/relay-pty-mint-epoch.tssrc/main/ipc/pty/pane/stable-owner-relay-epoch.test.tssrc/main/ipc/pty/pane/stable-owner.tssrc/main/ipc/pty/runtime/spawn-commit.tssrc/main/ipc/pty/runtime/spawn-execute.tssrc/main/ipc/pty/runtime/spawn-options.tssrc/main/ipc/pty/runtime/spawn.tssrc/main/providers/pty-provider-contract.tssrc/main/providers/pty-spawn-result.tssrc/main/runtime/orca-runtime.tssrc/main/ssh/ssh-relay-session.test.tssrc/main/ssh/ssh-relay-session.tssrc/relay/pty-handler.tssrc/relay/relay-daemon.tssrc/relay/subprocess.test.tssrc/renderer/src/components/terminal-pane/pty-connection-cold-restore-agent-resume.test.tssrc/renderer/src/components/terminal-pane/pty-connection/apply-reattach-payload.tssrc/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty-session.tssrc/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty.tssrc/renderer/src/components/terminal-pane/pty-connection/declined-agent-resume.tssrc/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.tssrc/renderer/src/components/terminal-pane/pty-connection/pane-serializer-settle.tssrc/renderer/src/components/terminal-pane/pty-connection/reattach-payload-session.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-transport.tssrc/shared/runtime-terminal-contracts.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.
| .catch(() => undefined) | ||
| const result = read ?? Promise.resolve(undefined) | ||
| relayMintEpochByProvider.set(provider, result) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Do not cache a failed relay-status read.
Line 39 converts a transient RPC failure into undefined, and Lines 40-41 cache that result for the provider lifetime. Every later resume on the same provider then receives an unknown verdict and bypasses the epoch gate. Remove the cache entry after rejection or timeout. Cache successful status responses, including a confirmed legacy response without an epoch.
Review found retiredRelayOwnerByPane had no teardown path, so entries for closed panes accumulated for the process lifetime. Adds a pane-keyed reverse index so teardown clears in O(1), and records the retired owner after the PTY teardown listeners run so the one-shot entry survives stale-reattach cleanup.
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/main/ipc/pty/pane/relay-pty-mint-epoch.ts (1)
121-137: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winRemove
codexHomePathOverridewhen declining agent resume.When the relay epoch differs,
stripAgentResumeOptionsremoves resume intent but preservescodexHomePathOverride. The local provider gives this override precedence over fresh Codex-home selection and exports it asCODEX_HOMEandORCA_CODEX_HOME. The fresh shell can therefore retain the resume-specific Codex home.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 3a6c3a10-9e6c-413f-b68b-f52fc74dc511
📒 Files selected for processing (3)
src/main/ipc/pty/pane/relay-pty-mint-epoch.tssrc/main/ipc/pty/pane/stable-owner-relay-epoch.test.tssrc/main/ssh/ssh-relay-session.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.
There was a problem hiding this comment.
Important
Two resume-decision gaps remain in the epoch gate: a fresh agent launch can be wrongly declined, and the agentSessionEnsure claim-resume path bypasses the gate entirely.
Reviewed changes
- Relay mint-epoch gate —
spawnForStablePanenow compares thepty2:<epoch>:<seq>epoch embedded in the pane's bound PTY id against the answering relay'srelay.status.ptyIdMintEpoch, stripping agent resume options and flaggingagentResumeUnavailablewhen they differ. - Retired-owner retention — SSH reattach failure remembers the pane's epoch-bearing PTY id, and
spawnForStablePaneconsults it when the stable owner was already retired, fixing the cold-resume path the first E2E run exposed. - Declined-resume propagation —
agentResumeUnavailableis threaded from main through the IPC and runtime replies into the renderer, which cancels pending startup delivery and shows the existingresume-unavailablebanner. - Side-effect gating — codex-pane accounting, launch authority, telemetry, and launch-config publication are skipped when a resume is declined.
ℹ️ Nitpicks
retiredRelayOwnerByPaneinrelay-pty-mint-epoch.tsis only ever removed bytakeRetiredRelayEpochOwner; a pane retired on reattach failure and then closed without a cold-restore leaves its entry behind for the process lifetime.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| }) | ||
| : 'unknown' | ||
| const hasAgentResumeIntent = Boolean( | ||
| args.spawnOptions.launchAgent || |
There was a problem hiding this comment.
Counting a bare launchAgent as resume intent over-declines. A fresh (non-resume) agent launch in a pane whose previous PTY died on a replaced relay carries launchAgent but no resumeProviderSession/agentSessionEnsure, yet spawnForStablePane uses args.owner.ptyId unconditionally (stable-owner.ts:297), so verdict === 'different' strips the launch and the user gets a plain shell plus the "resume unavailable" banner for a launch that was not a resume. The retired-owner path (stable-owner.ts:298) correctly requires resumeProviderSession || agentSessionEnsure — the owner-non-null path should apply the same guard.
Technical details
# Fresh agent launch wrongly declined after relay replacement
## Affected sites
- src/main/ipc/pty/pane/relay-pty-mint-epoch.ts:127 — `hasAgentResumeIntent` treats a bare `launchAgent` as resume intent
- src/main/ipc/pty/pane/stable-owner.ts:297 — `relayEpochOwnerPtyId` uses `args.owner?.ptyId` without checking resume intent
## Required outcome
- A fresh agent launch (`launchAgent`, no `resumeProviderSession`/`agentSessionEnsure`) must not be declined on either the owner-non-null or retired-owner path.
- A resume (`resumeProviderSession`/`agentSessionEnsure`) in a pane whose relay epoch differs must still be declined.
## Open questions for the human
- Is any `pty2:` resume expressed solely via `launchAgent` + `command` with no `resumeProviderSession`? If not, dropping `launchAgent` from `hasAgentResumeIntent` is sufficient.| const hasAgentResumeIntent = Boolean( | ||
| args.spawnOptions.launchAgent || | ||
| args.spawnOptions.resumeProviderSession || | ||
| args.spawnOptions.agentSessionEnsure |
There was a problem hiding this comment.
agentSessionEnsure is effectively dead code here. The host-authority claim resume (args.agentSessionEnsure) is routed through agentSessionOwners.ensure in runtime/spawn-execute.ts:63, which calls ctx.provider.spawn directly and never reaches spawnForStablePane, so the epoch gate is never consulted. A claim-based resume after a relay replacement therefore spawns against the new relay with no epoch check — the same double-agent failure this PR prevents on the resumeProviderSession path.
Technical details
# agentSessionEnsure claim resume bypasses the epoch gate
## Affected sites
- src/main/ipc/pty/runtime/spawn-execute.ts:63 — the `args.agentSessionEnsure` branch calls `agentSessionOwners.ensure(...)` → `ctx.provider.spawn` directly, never `spawnForStablePane`
- src/main/ipc/pty/pane/relay-pty-mint-epoch.ts:130 — `agentSessionEnsure` is listed in `hasAgentResumeIntent`, but no claim-resume flow reaches it
## Required outcome
- A claim-based resume must not spawn against a relay that never held the PTY without the epoch check, or the PR body must explicitly document this path as out of scope.
## Open questions for the human
- Is `agentSessionEnsure` used for SSH terminal resumes, or only daemon/headless hosts? `spawn-preflight.ts` selects `SshPtyProvider` for non-null `connectionId`, and `SshPtyProvider.spawn` handles `agentSessionEnsure`.There was a problem hiding this comment.
ℹ️ Incremental review of the two new commits — no new issues found; the changes resolve the leak nitpick from my prior review.
Reviewed changes (since b07ae7f)
- Pane-teardown cleanup for retired owners —
retiredRelayOwnerKeysByPanereverse-indexes retired owners by paneKey, andclearRetiredRelayEpochOwnersForPane(registered as a pane teardown listener) drops them when the pane closes. The reorder inhandlePtyReattachFailure—rememberRetiredRelayEpochOwnernow runs afterclearProviderPtyState— is necessary and correct, because the teardown listener fires insideclearProviderPtyState; recording after it lets the one-shot owner survive this stale-reattach cleanup while a genuine pane close still clears it. - Test type cleanup —
EpochAwareSpawnOptions/EpochAwareSpawnResultnow aliasPtySpawnOptions/PtySpawnResultdirectly and theunknown | Errorunion is dropped tounknown, plus a new test asserting teardown clears the retired owner.
The two [!IMPORTANT] findings from my prior review remain open: the fresh-agent-launch over-decline on the owner-non-null path, and the agentSessionEnsure claim resume bypassing the epoch gate.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
Validation update for PR #17471 (head
Screenshots (full Electron window): Focused epoch/SSH/renderer tests pass (47 tests), typecheck and changed-code quality pass. Residual evidence gap: same-epoch |
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: ae809824-4280-429e-9c3b-de04f1d00ea4
📒 Files selected for processing (1)
src/main/ipc/pty/pane/relay-pty-mint-epoch.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review.
| } | ||
| const key = retiredRelayOwnerKey(connectionId, paneKey) | ||
| const ownerPtyId = retiredRelayOwnerByPane.get(key) | ||
| forgetRetiredRelayOwnerKey(key, paneKey) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- repository conventions and learnings ---'
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -maxdepth 2 -type f -name '*.md' -print
printf '%s\n' '--- target source ---'
sed -n '1,150p' src/main/ipc/pty/pane/relay-pty-mint-epoch.ts
printf '%s\n' '--- direct bindings and callers ---'
rg -n -C 4 'takeRetiredRelayEpochOwner|forgetRetiredRelayOwnerKey|deriveStablePaneFreshSpawnOptions|provider\.spawn|stable-pane' src/main/ipc/ptyRepository: stablyai/orca
Length of output: 26107
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- PTY conventions ---'
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions/src-main-pty.md 2>/dev/null || true
printf '%s\n' '--- stable-owner fresh-spawn flow ---'
sed -n '150,335p' src/main/ipc/pty/pane/stable-owner.ts
printf '%s\n' '--- epoch option derivation ---'
sed -n '150,260p' src/main/ipc/pty/pane/relay-pty-mint-epoch.ts
printf '%s\n' '--- focused regression tests ---'
sed -n '1,290p' src/main/ipc/pty/pane/stable-owner-relay-epoch.test.tsRepository: stablyai/orca
Length of output: 15688
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- all spawnForStablePane call sites ---'
rg -n -C 12 'spawnForStablePane\(' src/main
printf '%s\n' '--- stable-pane retry and error handling identifiers ---'
rg -n -C 8 'stablePane|terminal_pane|retry|provider\.spawn' src/main/ipc/pty/pane src/main/ipc/pty/runtime src/main/ipc/pty/ipc | head -400Repository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- relay-absence retry scenario ---'
sed -n '1,220p' src/main/ipc/pty/pane/stable-pane-relay-absence-respawn.test.ts
printf '%s\n' '--- spawn execution around stable-pane resolution ---'
sed -n '1,180p' src/main/ipc/pty/runtime/spawn-execute.ts
printf '%s\n' '--- IPC spawn execution around stable-pane resolution ---'
sed -n '1,130p' src/main/ipc/pty/ipc/spawn-execute.tsRepository: stablyai/orca
Length of output: 20334
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- retired-owner producers and retry entry points ---'
rg -n -C 10 'rememberRetiredRelayEpochOwner|clearRetiredRelayEpochOwnersForPane|executePtyIpcSpawn|executeRuntimePtySpawn' src/main/ipc/pty
printf '%s\n' '--- request-level retry handling ---'
rg -n -C 8 'terminal_pane_owner_changed|SSH_SESSION_EXPIRED_ERROR|SshPtyAbsentFromRelayError|spawn.*retry|retry.*spawn' src/main/ipc src/main/providersRepository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- exact retired-owner producer bindings ---'
rg -n -C 12 'rememberRetiredRelayEpochOwner' src --glob '!*.test.ts'
printf '%s\n' '--- spawn request lifecycle and reservation cleanup ---'
sed -n '1,145p' src/main/ipc/pty/ipc/spawn-run.ts
sed -n '70,145p' src/main/ipc/pty/runtime/spawn.tsRepository: stablyai/orca
Length of output: 11365
Retain the retired owner until the fresh spawn succeeds.
If provider.spawn fails after takeRetiredRelayEpochOwner removes the record, a subsequent spawnForStablePane call can receive owner: null. The epoch check then sees no retired pty2 owner and preserves agent-resume options. Peek first and remove the record after success, or restore it on failure. Add a regression test for a failed spawn followed by a retry.
There was a problem hiding this comment.
ℹ️ Incremental review of
666b14e— no new issues found; the change correctly bounds the retired-owner retention map.
Reviewed changes (since 06bcd89868)
- Bounded retired-owner retention —
rememberRetiredRelayEpochOwnernow evicts the oldest entry onceretiredRelayOwnerByPaneexceedsMAX_RETIRED_RELAY_OWNERS(1,024), and the newforgetRetiredRelayOwnerKeyhelper centralizes forward-map plus reverse-index cleanup for both the eviction path andtakeRetiredRelayEpochOwner.
The two [!IMPORTANT] findings from the prior review remain open and are unchanged by this commit: the fresh-agent-launch over-decline on the owner-non-null path, and the agentSessionEnsure claim resume bypassing the epoch gate.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…resume-epoch-gate # Conflicts: # src/main/ipc/pty/ipc/spawn-commit.ts
…h-gate' into brennanb2025/sta5698-resume-epoch-gate
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
There was a problem hiding this comment.
Important
The reminted-authority suppression in c6fe03e is a clean, well-tested fix — but the two must-address findings from earlier reviews remain open and unchanged by this commit, so this is not an approval.
Reviewed changes (since 666b14e)
- Suppressed reminted pane authority on declined resume —
commitPtyIpcSpawnnow guards theopaqueRemintedSpawnPaneKey→ validated pane-key alias registration with!agentResumeDeclined, matching the guards already on the legacy-spawn-key and validated-key branches. A declined resume no longer installs a spawn-physical$$token as an authority-verified alias for the canonical pane. - Added a regression test — the new case simulates a declined resume via a provider returning
agentResumeUnavailable: trueand asserts the reminted alias is not registered while the pane still registers under the metadata-derived stable key. It is a genuine red-green test: without the guard,registerPaneKeyAliasis invoked and the assertion fails.
The two open [!IMPORTANT] findings from prior reviews are untouched by this delta and still block merge: the fresh-agent-launch over-decline on the owner-non-null path (relay-pty-mint-epoch.ts hasAgentResumeIntent counting a bare launchAgent, combined with stable-owner.ts:297 using args.owner?.ptyId unconditionally), and the agentSessionEnsure claim-resume path bypassing the epoch gate entirely via runtime/spawn-execute.ts:63.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Holding this — the root-cause fix supersedes itFiled STA-6198: Orca can displace a relay that is still alive, orphaning its PTYs and their agents. Eleven paths decide on evidence that does not prove the old relay is dead — most sharply, an unconditional That is the cause. This PR is the seatbelt. Why holding rather than merging. This gate fires on "the epoch differs", but that covers two very different situations:
Today those are indistinguishable, so declining is defensible. Once STA-6198 lands, displacement-while-alive largely stops, and what remains in the epoch-differs bucket is mostly genuine deaths — the cases where declining is unnecessary. The fix does not just reduce this PR's value, it inverts it. And the root-cause fix enables a strictly better trigger. The displacement code knows when it forcibly displaces a live relay, because it made that decision. The better gate is "we knowingly displaced a live relay, so its agents may still be running" — precise, never fires on an ordinary crash, and only buildable once STA-6198 exists. A residual will still want covering: deliberate coexistence (versioned-install upgrades, forcibly displacing a wedged relay so the user is not stuck) and Windows, where named pipes cannot be unlinked and coexistence is structural. What is preserved from this work, so none of it is lost:
Branch stays at |



Closes STA-5698.
ELI5
You have an AI agent running in a terminal on a remote machine. The connection drops, or the helper program Orca runs over there gets replaced. Orca reconnects, finds your terminal gone, and automatically restarts your agent where it left off.
That's usually right. But if the helper was replaced, the terminal Orca is restoring belonged to the previous helper — and if anything from it survived, restarting the agent gives you two agents editing the same files.
Until now Orca never checked. This makes it check: if the terminal was created by a different helper than the one now answering, Orca still opens a shell, but does not restart the agent, and says so.
What you'll notice: after a helper crash, a terminal with a note that the previous session wasn't restored — instead of two agents quietly fighting over your worktree. In ordinary use you'll notice nothing, because the helper isn't replaced in ordinary use (measured below).
The change
spawnForStablePane's post-absence fresh spawn compares the mint epoch carried by the pane's bound PTY id (pty2:<epoch>:<seq>, from #16901) against the epoch the answering relay reports onrelay.status.launchAgent/command/resumeProviderSession/agentSessionEnsure, markagentResumeUnavailable"Anything else" is deliberate and commented at the decision site: legacy
pty-Nids, a relay too old to report an epoch, an RPC failure or timeout, and non-SSH panes all produce no verdict. Declining them would break the common absence case — the PTY died while the relay stayed up, which must keep auto-resuming — and the residual needs a legacy id and a relay replacement and a surviving orphan at once.No new user-facing surface:
agentResumeUnavailableand theresume-unavailablebanner already existed.Why a gate rather than a liveness probe
The alternative was recording the PTY child's pid and asking the new relay whether it is still alive. It was rejected because its errors point the wrong way: the recorded pid is the shell's, but the thing being relaunched is the agent, which can outlive its shell. A probe would then read "shell dead → safe" and start a second agent — the exact bug. This gate's errors are all in the cost direction: at worst a banner and one manual resume.
Measured, not assumed
Relay replacement is rare. Across five ordinary flows on a real SSH target — idle, disconnect/reconnect, 49s network pause, 90s sleep analogue, full app quit and relaunch — the relay was replaced 0 times and the PTY survived every time. Only a SIGKILL control replaced it, and there the old PTY was gone in 2s. So the gate's only cost is paid almost never.
The seam was proved by runtime experiment, not by reading: the post-absence spawn is
stable-owner.ts, confirmed under instrumentation on a Docker SSH rig.End-to-end validation
Run twice against a real remote Linux host with a stub agent that logs its argv.
First run caught a real bug. Test 1 failed: the epoch changed (
29aca451…→9a92cb81…) and Orca still relaunched with--resume. Every unit test passed — they proved the gate declines when handed a different epoch, never that the real flow reaches it.Root cause, proved by instrumentation:
spawnForStablePaneexecuted withowner === null. Relay recovery had already cleared the stable owner before the renderer asked for the cold resume, and the gate only ran when an owner remained — so it was never consulted. (relay.statuswas called zero times; the deployed relay was publishing the field correctly, so neither a timeout nor a cache was involved.) Fixed by retaining the epoch-bearing owner across owner retirement, one-shot and connection-scoped.Second run, after the fix — both arms pass:
--resume, "previous session unavailable, started fresh" banner, working shell--resumeThe second arm matters as much as the first: it proves the gate is not disabling resume everywhere.
Tests
The regression test was confirmed red pre-fix (
expected requestHostRpc to be called once, received zero calls). Coverage: different epoch after a retired owner declines; same epoch after a retired owner preserves; an ordinary new agent launch is not converted into a resume decision; SSH reconnect retirement records the correct connection/pane-scoped owner.pnpm tcclean ·oxlintclean ·pnpm test src/main/ipc/pty/ src/relay/→ 152 files, 1552 passed.Known limit
This declines when the relay was replaced. It does not detect an orphan directly, so a
setsid'd grandchild that outlives its shell is invisible to it — as it is to every design evaluated, including the probe. Sibling PR #16894 (merged) removes that orphan at the source on the crash path.Performance Measurement
This is a safety gate, not a speed optimization, so no latency or speedup claim is made. Stable-pane recovery with an epoch-bearing owner performs at most one cached
relay.statusrequest per provider object or connection generation, then constant-time epoch parsing and comparison; no-owner, legacypty-N, non-SSH, and fresh spawns without an owner avoid that RPC. Retired-owner bookkeeping is bounded at 1,024 entries, and pane teardown removes entries through the reverse index. The documented real-target exercise observed relay replacement 0/5 times and PTY survival 5/5; the SIGKILL control replaced the relay and the old PTY was gone in 2 s. These are bounded observations, not a latency benchmark.User-Facing Trade-offs
A known different epoch intentionally declines automatic agent resume: the shell opens and the existing banner requests manual recovery, avoiding duplicate agents. An epoch or status RPC timeout can add up to the bounded 2-s check on recovery; unknown or failing status, legacy IDs, same epochs, non-SSH panes, and ordinary PTY loss retain prior resume behavior. The 1,024-entry cap may evict very old records, which then fall back to prior behavior. No new controls are added, and the additive fields remain SSH/folder/local compatible.