Skip to content

fix(pty): do not re-run an agent resume against a relay that never held the PTY (STA-5698) - #17471

Closed
brennanb2025 wants to merge 9 commits into
mainfrom
brennanb2025/sta5698-resume-epoch-gate
Closed

brennanb2025 wants to merge 9 commits into
mainfrom
brennanb2025/sta5698-resume-epoch-gate

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​321 $\color{#cf222e}{\Huge{\mathbf{−}}}$​7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​314
Prod 25 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​368 $\color{#cf222e}{\Huge{\mathbf{−}}}$​67 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​301

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 on relay.status.

Verdict Behaviour
epochs known and different strip launchAgent / command / resumeProviderSession / agentSessionEnsure, mark agentResumeUnavailable
epochs known and same unchanged — resume as today
anything else unchanged — resume as today

"Anything else" is deliberate and commented at the decision site: legacy pty-N ids, 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: agentResumeUnavailable and the resume-unavailable banner 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: spawnForStablePane executed with owner === 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.status was 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:

Scenario Result
Relay replaced, different epoch PASS — stub launched exactly once, no --resume, "previous session unavailable, started fresh" banner, working shell
Relay alive, same epoch PASS — relaunched with --resume

The 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 tc clean · oxlint clean · 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.status request per provider object or connection generation, then constant-time epoch parsing and comparison; no-owner, legacy pty-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.

@greptile-apps

greptile-apps Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

Greptile Summary

The PR prevents automatic agent resume when a replacement SSH relay did not own the previous PTY.

  • Adds relay PTY mint epochs to status responses and compares them during stable-pane recovery.
  • Retains one-shot epoch-bearing ownership after failed reconnect retirement.
  • Strips resume intent and clears launch metadata when relay epochs differ.
  • Propagates the resume-unavailable result through main, runtime, transport, and renderer paths.
  • Adds recovery, propagation, cleanup, and regression coverage.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Important Files Changed

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
Loading

Reviews (6): Last reviewed commit: "fix(pty): suppress reminted authority on..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3d741114-c0b1-4fb2-b3fd-e9d27284d392

📥 Commits

Reviewing files that changed from the base of the PR and between 68bb227 and d1ee508.

📒 Files selected for processing (29)
  • src/main/ipc/pty/ipc/spawn-commit-persist.ts
  • src/main/ipc/pty/ipc/spawn-commit.ts
  • src/main/ipc/pty/ipc/spawn-execute.ts
  • src/main/ipc/pty/ipc/spawn-options.ts
  • src/main/ipc/pty/pane/relay-pty-mint-epoch.ts
  • src/main/ipc/pty/pane/stable-owner-relay-epoch.test.ts
  • src/main/ipc/pty/pane/stable-owner.ts
  • src/main/ipc/pty/runtime/spawn-commit.ts
  • src/main/ipc/pty/runtime/spawn-execute.ts
  • src/main/ipc/pty/runtime/spawn-options.ts
  • src/main/ipc/pty/runtime/spawn.ts
  • src/main/providers/pty-provider-contract.ts
  • src/main/providers/pty-spawn-result.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/ssh/ssh-relay-session.test.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/relay/pty-handler.ts
  • src/relay/relay-daemon.ts
  • src/relay/subprocess.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection-cold-restore-agent-resume.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/apply-reattach-payload.ts
  • src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty-session.ts
  • src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty.ts
  • src/renderer/src/components/terminal-pane/pty-connection/declined-agent-resume.ts
  • src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts
  • src/renderer/src/components/terminal-pane/pty-connection/pane-serializer-settle.ts
  • src/renderer/src/components/terminal-pane/pty-connection/reattach-payload-session.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
  • src/shared/runtime-terminal-contracts.ts
🚧 Files skipped from review as they are similar to previous changes (28)
  • src/main/ipc/pty/ipc/spawn-execute.ts
  • src/main/providers/pty-spawn-result.ts
  • src/main/ipc/pty/runtime/spawn-options.ts
  • src/main/ipc/pty/runtime/spawn-execute.ts
  • src/main/ipc/pty/pane/stable-owner-relay-epoch.test.ts
  • src/relay/subprocess.test.ts
  • src/main/ipc/pty/ipc/spawn-options.ts
  • src/main/ipc/pty/runtime/spawn-commit.ts
  • src/shared/runtime-terminal-contracts.ts
  • src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty-session.ts
  • src/renderer/src/components/terminal-pane/pty-connection/apply-reattach-payload.ts
  • src/renderer/src/components/terminal-pane/pty-connection-cold-restore-agent-resume.test.ts
  • src/relay/pty-handler.ts
  • src/relay/relay-daemon.ts
  • src/renderer/src/components/terminal-pane/pty-connection/declined-agent-resume.ts
  • src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts
  • src/main/ipc/pty/ipc/spawn-commit-persist.ts
  • src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty.ts
  • src/renderer/src/components/terminal-pane/pty-connection/reattach-payload-session.ts
  • src/renderer/src/components/terminal-pane/pty-connection/pane-serializer-settle.ts
  • src/main/providers/pty-provider-contract.ts
  • src/main/ipc/pty/ipc/spawn-commit.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/ipc/pty/runtime/spawn.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/main/ssh/ssh-relay-session.test.ts
  • src/main/ipc/pty/pane/stable-owner.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review.


📝 Walkthrough

Walkthrough

The 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 d1ee5

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning 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: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary fix: preventing agent resume against a relay that did not own the PTY.
Description check ✅ Passed 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…
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 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 Coverage

Explanation

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 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • 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

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 lift

Apply the relay-epoch gate before structured agent-session spawning.

When args.agentSessionEnsure is present, this branch bypasses spawnForStablePane and sends ctx.spawnOptions directly to ctx.provider.spawn. A cold resume on a replacement relay can therefore retain agentSessionEnsure, resumeProviderSession, launch fields, and the launch token. Run the same retired-owner epoch evaluation before this branch creates or adopts an owner. Return agentResumeUnavailable when 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

📥 Commits

Reviewing files that changed from the base of the PR and between f23d0b1 and b07ae7f.

📒 Files selected for processing (29)
  • src/main/ipc/pty/ipc/spawn-commit-persist.ts
  • src/main/ipc/pty/ipc/spawn-commit.ts
  • src/main/ipc/pty/ipc/spawn-execute.ts
  • src/main/ipc/pty/ipc/spawn-options.ts
  • src/main/ipc/pty/pane/relay-pty-mint-epoch.ts
  • src/main/ipc/pty/pane/stable-owner-relay-epoch.test.ts
  • src/main/ipc/pty/pane/stable-owner.ts
  • src/main/ipc/pty/runtime/spawn-commit.ts
  • src/main/ipc/pty/runtime/spawn-execute.ts
  • src/main/ipc/pty/runtime/spawn-options.ts
  • src/main/ipc/pty/runtime/spawn.ts
  • src/main/providers/pty-provider-contract.ts
  • src/main/providers/pty-spawn-result.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/ssh/ssh-relay-session.test.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/relay/pty-handler.ts
  • src/relay/relay-daemon.ts
  • src/relay/subprocess.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection-cold-restore-agent-resume.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/apply-reattach-payload.ts
  • src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty-session.ts
  • src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty.ts
  • src/renderer/src/components/terminal-pane/pty-connection/declined-agent-resume.ts
  • src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts
  • src/renderer/src/components/terminal-pane/pty-connection/pane-serializer-settle.ts
  • src/renderer/src/components/terminal-pane/pty-connection/reattach-payload-session.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
  • src/shared/runtime-terminal-contracts.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.

Comment on lines +39 to +41
.catch(() => undefined)
const result = read ?? Promise.resolve(undefined)
relayMintEpochByProvider.set(provider, result)

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 | 🟠 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.

Merge Sim added 2 commits August 30, 2026 15:06
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.

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

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 win

Remove codexHomePathOverride when declining agent resume.

When the relay epoch differs, stripAgentResumeOptions removes resume intent but preserves codexHomePathOverride. The local provider gives this override precedence over fresh Codex-home selection and exports it as CODEX_HOME and ORCA_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

📥 Commits

Reviewing files that changed from the base of the PR and between f3eb12d and 06bcd89.

📒 Files selected for processing (3)
  • src/main/ipc/pty/pane/relay-pty-mint-epoch.ts
  • src/main/ipc/pty/pane/stable-owner-relay-epoch.test.ts
  • src/main/ssh/ssh-relay-session.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.

@pullfrog pullfrog 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.

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 — spawnForStablePane now compares the pty2:<epoch>:<seq> epoch embedded in the pane's bound PTY id against the answering relay's relay.status.ptyIdMintEpoch, stripping agent resume options and flagging agentResumeUnavailable when they differ.
  • Retired-owner retention — SSH reattach failure remembers the pane's epoch-bearing PTY id, and spawnForStablePane consults it when the stable owner was already retired, fixing the cold-resume path the first E2E run exposed.
  • Declined-resume propagation — agentResumeUnavailable is threaded from main through the IPC and runtime replies into the renderer, which cancels pending startup delivery and shows the existing resume-unavailable banner.
  • Side-effect gating — codex-pane accounting, launch authority, telemetry, and launch-config publication are skipped when a resume is declined.

ℹ️ Nitpicks

  • retiredRelayOwnerByPane in relay-pty-mint-epoch.ts is only ever removed by takeRetiredRelayEpochOwner; a pane retired on reattach failure and then closed without a cold-restore leaves its entry behind for the process lifetime.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

})
: 'unknown'
const hasAgentResumeIntent = Boolean(
args.spawnOptions.launchAgent ||

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.

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

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.

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`.

@pullfrog pullfrog 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.

ℹ️ 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 — retiredRelayOwnerKeysByPane reverse-indexes retired owners by paneKey, and clearRetiredRelayEpochOwnersForPane (registered as a pane teardown listener) drops them when the pane closes. The reorder in handlePtyReattachFailure — rememberRetiredRelayEpochOwner now runs after clearProviderPtyState — is necessary and correct, because the teardown listener fires inside clearProviderPtyState; 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/EpochAwareSpawnResult now alias PtySpawnOptions/PtySpawnResult directly and the unknown | Error union is dropped to unknown, 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.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Validation update for PR #17471 (head 666b14e170):

  • Real Linux SSH validation on shared openclaw host with isolated Electron profile/CDP and relay build.
  • Relay replacement / different mint epoch: PASS — cold restore opened a working shell, exactly one stub launch with no --resume, and showed --- previous session unavailable, started fresh ---.
  • Same relay epoch / pane shell death: PASS — fresh spawn kept the same relay mint epoch and stub argv was exactly --resume pr17471-744252ba; no agentResumeUnavailable verdict.
  • Closing readiness checklist: no proven P0/P1 issues. The retired-owner retention path was additionally bounded to 1,024 entries and covered by tests (commit 666b14e170).

Screenshots (full Electron window):

Different epoch — unavailable banner
Same epoch — resume arm

Focused epoch/SSH/renderer tests pass (47 tests), typecheck and changed-code quality pass. Residual evidence gap: same-epoch --resume was proven through the live SSH provider and stub argv; that replacement PTY was not rebound into the visible xterm buffer during this run.

@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: ae809824-4280-429e-9c3b-de04f1d00ea4

📥 Commits

Reviewing files that changed from the base of the PR and between 06bcd89 and 666b14e.

📒 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)

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 | 🟠 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/pty

Repository: 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.ts

Repository: 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 -400

Repository: 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.ts

Repository: 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/providers

Repository: 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.ts

Repository: 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.

@pullfrog pullfrog 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.

ℹ️ 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 — rememberRetiredRelayEpochOwner now evicts the oldest entry once retiredRelayOwnerByPane exceeds MAX_RETIRED_RELAY_OWNERS (1,024), and the new forgetRetiredRelayOwnerKey helper centralizes forward-map plus reverse-index cleanup for both the eviction path and takeRetiredRelayEpochOwner.

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.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Merge Sim added 2 commits August 30, 2026 19:50
…resume-epoch-gate

# Conflicts:
#	src/main/ipc/pty/ipc/spawn-commit.ts
…h-gate' into brennanb2025/sta5698-resume-epoch-gate
@coderabbitai

coderabbitai Bot commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

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.

@pullfrog pullfrog 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.

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 — commitPtyIpcSpawn now guards the opaqueRemintedSpawnPaneKey → 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: true and 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, registerPaneKeyAlias is 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.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Holding this — the root-cause fix supersedes it

Filed 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 rm -f on any --connect failure (ssh-relay-deploy.ts:1423-1462), a test -S check the code itself notes is only an inode check, and a version-mismatch reply that is positive proof the old relay answered us landing in the same branch that unlinks its socket.

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:

Situation Old agent alive? Declining is
Relay displaced while alive (STA-6198) yes correct — the harm
Relay genuinely died (crash, OOM, reboot) no — SIGHUP kills it, and #16894 reaps it wrong — a safe resume refused

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:

  • The seam is proved by runtime experiment: the post-absence fresh spawn is stable-owner.ts, and fix(ssh): a relay that reports a PTY absent must authorise a fresh spawn #16763 makes it the live path.
  • Relay replacement is rare — measured 0 of 5 ordinary flows (idle, reconnect, 49s network pause, 90s sleep, full app restart); only a SIGKILL control replaced it, and there the PTY was gone in 2s. So the window being left unprotected is small.
  • The renderer half (agentResumeUnavailable → the resume-unavailable banner) already exists in the tree and needs no new plumbing.
  • Three defects were found and fixed along the way: two unbounded-map retention paths and a wrong merge resolution that would have registered agent-hook authority (authorityVerified: true) for a pane whose agent had just been declined.

Branch stays at c6fe03e9b5 for reference. Reopen or supersede as part of STA-6198.

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