Repository navigation
fix(ssh): decline an agent resume when the answering relay never minted the pane's PTY (STA-5698) - #18010
fix(ssh): decline an agent resume when the answering relay never minted the pane's PTY (STA-5698)#18010brennanb2025 wants to merge 4 commits into
Conversation
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Epoch gate core — new
relay-pty-mint-epoch.tsparses thepty2:<mintEpoch>:<seq>id, reads the answering relay'srelay.status.ptyIdMintEpoch(per-provider cached, 2s timeout), compares, and strips resume options when a known-different epoch answers. Theread ?? Promise.resolve(undefined)fallback is live, not dead — the trailing.thenshort-circuits toundefinedwhenrequestHostRpcis absent. - Retired-owner retention — SSH reconnect records the epoch-bearing owner (keyed
connectionId \0 paneKey, bounded at 256) before clearing an absent PTY, andspawnForStablePaneconsumes it only when the live owner is gone and explicit resume identity (resumeProviderSession/agentSessionEnsure) is present. - Reply/state propagation —
agentResumeUnavailablethreads fromPtySpawnResultthrough both IPC and runtime commit paths andrelay.status; the renderer cancels the pending resume and shows theresume-unavailablebanner. - Tests & validation — 46 targeted tests with exact (not truthiness) assertions plus an E2E validation report demonstrating real relay replacement declines the resume and a same-epoch relay resumes.
I traced the two invariants the whole mechanism depends on and both hold: the SshPtyProvider is recreated per reconnect (new SshPtyProvider + a fresh allocateSshPtyProviderGeneration), so the WeakMap epoch cache is never stale across a relay replacement; and the retired-owner key is produced by makePaneKey(tabId, leafId) on both the retire and spawn sides. The ...ctx.result widening in commitRuntimePtySpawn is benign because the final reply is field-whitelisted by toRuntimeSpawnReply.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
📝 WalkthroughWalkthroughThe change adds relay PTY mint-epoch tracking and retired-owner storage. Stable-pane spawning compares relay epochs and declines agent resume for stale ownership. Spawn contracts propagate the unavailable-resume marker through IPC, runtime, terminal creation, and renderer transport. Commit paths suppress agent-launch side effects for declined resumes. Renderer flows clear pending startup state and launch metadata. Tests and validation records cover epoch matching, relay recovery, reconnects, and resume cleanup. Merge Risk: 🟡 Moderate · up to The PR adds relay-lifetime checks to prevent automatic agent duplication, but several current paths can still resume on a different relay, bind a fresh shell to stale session state, or retain authority for a surviving old agent. Those cases can cause concurrent agents to edit the same worktree or route status to the wrong pane, so merge should wait for the affected paths to be corrected or explicitly accepted by the owner. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Description checkExplanation The description clearly explains the problem, solution, decision rules, root cause, linked issue, testing evidence, scope, and known limitations. It does not use every template heading and lacks an explicit Visual Proof section and checklist completion, but the description is substantially complete and reviewable. Full details: Docstring CoverageExplanation Docstring coverage is 7.69% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 26 functions across 30 files. (1 skipped: 1 unsupported.)
✨ 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 (2)
src/main/ipc/pty/runtime/spawn-execute.ts (1)
63-84: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy liftApply the relay-epoch gate to
agentSessionEnsurespawns.When
args.agentSessionEnsureis set, this branch bypassesspawnForStablePaneand sends unmodifiedctx.spawnOptionsto the provider. It does not read the retired owner or compare its relay epoch. A runtime SSH resume can therefore continue on a newly answering relay that did not mint the prior PTY.Derive the epoch-aware options before
agentSessionOwners.ensure, use them for the provider spawn, and propagateagentResumeUnavailablewhen the gate declines the resume.src/main/runtime/orca-runtime-create-terminal.ts (1)
213-217: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winGate structured-session binding for declined resumes.
When
deriveStablePaneFreshSpawnOptionsdeclines a resume, it removes the resume and agent-launch options, so the provider creates a fresh shell.ensureAgentSessionstill passesstructuredAgentSessionId, and this block binds that fresh shell to the structured session. Later writes can target the replacement shell. Add!agentResumeDeclinedto the condition.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 9ce2e61f-c108-4ea9-adb1-bf866c6f63a0
⛔ Files ignored due to path filters (5)
validation-artifacts/sta5698-task01-final-20260829T010120Z/test1-relay-replaced-pass.pngis excluded by!**/*.pngvalidation-artifacts/sta5698-task01-final-20260829T010120Z/test1-stub-launches.logis excluded by!**/*.logvalidation-artifacts/sta5698-task01-final-20260829T010120Z/test1-working-shell-pass.pngis excluded by!**/*.pngvalidation-artifacts/sta5698-task01-final-20260829T010120Z/test2-same-relay-resume-pass.pngis excluded by!**/*.pngvalidation-artifacts/sta5698-task01-final-20260829T010120Z/test2-stub-launches.logis excluded by!**/*.log
📒 Files selected for processing (31)
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-create-terminal.tssrc/main/runtime/runtime-pty-controller-contract.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.tsvalidation-artifacts/sta5698-task01-final-20260829T010120Z/report.md
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.
| } | ||
| } | ||
| const result = await args.provider.spawn(args.spawnOptions) | ||
| const retiredRelayOwnerPtyId = takeRetiredRelayEpochOwner(args.connectionId, args.paneKey) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Keep retired ownership when the fresh spawn fails.
takeRetiredRelayEpochOwner deletes the retired owner before provider.spawn() completes. If the spawn rejects, a retry has no owner PTY ID to compare. The retry can then retain automatic agent-resume options for a different relay epoch.
Remove this record only after a successful spawn, or restore it in the error path. Add a regression test for a failed fresh spawn followed by a retry.
|
STA-5698 runtime evidence rerun on the current PR head ( Test 1 (relay replaced → must not resume): FAIL. Initial Test 2 (same relay → must resume): FAIL, over-declining. Relay PID Screenshots and full logs are in |
|
Marking draft. Both runtime tests fail on the current head, so this is not mergeable as it stands. Note the earlier passing end-to-end run was against pre-rebase code. Between then and now the branch was rebased onto current main and the retired-owner map was bounded. One of those regressed it, and the passing evidence does not transfer. Two things stand out for whoever picks this up:
Full evidence is in |
|
SSH still works: Orca connects to the host over SSH and routes workspace operations through the managed remote Orca server (orcad). These merges remove the legacy SSH relay, not SSH support. Closing as obsolete after the merged SSH relay retirement in #27214 and #27215. This PR concerns the SSH relay PTY attach, recovery, replay, or lease lifecycle. #27214 removed the desktop relay connection/fallback path; #27215 deleted the SSH relay server, deployment assets, and relay-only tests. SSH hosts now use the managed Orca server (orcad), and unsupported hosts fail explicitly, so this relay-specific work is no longer planned. This closes the proposed relay implementation; it does not claim that any independent local, WSL, or managed-server behavior was fixed. |
|
Thanks @brennanb2025 — the relay itself is gone, but the idea behind this (don't auto-resume an agent when the host's "terminal not found" was never observed as a real exit) still applies to managed hosts and paired runtimes. I've captured it on #13716 with credit to this PR; this one stays closed since its mechanism was relay-specific. |

Fixes STA-5698.
In plain terms
You have an AI agent running in a terminal on a remote machine. The connection drops, or the helper process over there restarts. Orca reconnects, finds your terminal gone, opens a fresh one, and automatically restarts your agent where it left off — without ever checking whether the old one is still running.
If it is, you now have two agents editing the same files.
This makes Orca check. When the terminal's name shows it was created by a different helper lifetime than the one now answering, Orca still gives you a working shell but does not restart the agent, and says so.
What you'll notice: almost always nothing. Measured across five ordinary flows — idle, disconnect/reconnect, a 49s network pause, a 90s sleep, and a full app quit and relaunch — the helper was never replaced, so the resume path is untouched. It only declines when the helper genuinely was replaced, which in testing meant the old terminal was already gone anyway.
How it decides
Terminal ids now carry the minting helper's identity (
pty2:<mintEpoch>:<seq>, from #16901). On a post-absence fresh spawn:resume-unavailablebannerThat last row is deliberate. Declining on "don't know" would break the common absence case (the PTY died while the helper stayed up, which must keep auto-resuming), and the residual risk needs a legacy id and a helper replacement and a surviving agent at once. The tradeoff is commented at the decision site rather than left implicit.
Polarity follows the repo's own rule, stated in
src/relay/pty-shell-utils.ts:183-193: only positive proof authorises the automatic path.Root cause of the first failed attempt
An earlier revision passed unit tests but failed end-to-end: the relay was replaced, the epoch demonstrably changed, and Orca still relaunched with
--resume.Instrumentation on a real SSH host proved why, and it was none of the obvious candidates.
relay.statuswas called zero times — the read never failed or timed out.spawnForStablePaneran withowner === null, because relay recovery cleared the stable owner before the renderer requested its cold resume. The gate was skipped entirely rather than answered wrongly.The fix retains the epoch-bearing owner across that retirement, keyed by connection and pane, and consumes it at the fresh-spawn point when the live owner is gone and there is explicit persisted resume identity.
Review
Reviewed to clean by two independent models. One finding was seeded from my own read and fixed here: the retired-owner map was module-level with its only deletion inside
take(), so any retirement not followed by a fresh spawn — closed tab, removed connection — leaked an entry for the life of the process. It is now bounded at 256 with insertion-order eviction and delete-then-set recency, with regression tests.Deployment review was explicit, after a sibling PR was closed for exactly this class of defect: this change depends only on the existing
pty2id string and therelay.statuscontract — no patched-only native symbols, nothing absent from the relay's remotely-installed dependencies.Honest limits
setsid'd grandchild that outlives its shell is invisible to it.Related
Builds on #16901 (id format) and #16894 (relay reaps its PTYs on a fatal exit), both merged. #16843 was the first attempt and was closed — it inferred replacement from process age and would have refused a resume after an ordinary host reboot.