Skip to content

fix(terminal): don't resume an agent whose spawned PTY is still live - #24386

Closed
Minidoracat wants to merge 2 commits into
stablyai:mainfrom
Minidoracat:fix/resume-dedupe-live-pty
Closed

Minidoracat wants to merge 2 commits into
stablyai:mainfrom
Minidoracat:fix/resume-dedupe-live-pty

Conversation

@Minidoracat

@Minidoracat Minidoracat commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

When you open a workspace, Orca restarts agents it thinks were interrupted. If another Orca you paired with started an agent in that workspace, this desktop could not tell that the agent was still running. So every time you opened the workspace, or opened it from your phone, Orca started another copy in a new tab, and both copies wrote into the same conversation. With this change, the terminal host remembers which pane each terminal was started for, so the desktop can see that the agent is already running and leaves it alone.

What Changed

  • The terminal daemon and the SSH relay both report the ORCA_PANE_KEY each PTY was spawned with, as paneKey in their session listings. The daemon records it once when it creates the session. The relay already kept it on the managed PTY. Reattaching a PTY from another pane does not change it.
  • The value passes through the process-list admission and pty:listSessions as an optional field, PtyListedSession.paneKey.
  • liveSleepingAgentClaims in the activation gate now also claims a sleeping record when a live PTY was spawned for that record's pane. Before this change, a record could only be claimed through this renderer's own layout or tab binding. That check still runs first.
  • The phone-triggered background wake (wakeSleepingAgentsForWorktreeInBackground) is the sweep's other caller. It skipped only the in-place wake claims and never looked at the PTY census. It now reads the same census claims through readLiveSleepingAgentClaimKeys before its resume step and merges them into skipClaimKeys. A workspace owned by a paired runtime has no client census, so it keeps its existing host-mirror checks. If the census fails for any other reason, the wake skips its resume step, just as the activation gate refuses to act on an unreadable census.

Before: a paired client launches an agent in a host's local worktree, and the agent reports from the client's pane. The host's sleeping record therefore names a pane the host desktop has no layout for. On activation:

  1. The host adopts the unowned PTY onto a new tab, and the record stays unclaimed.
  2. The blocked check skips the PTY, because a fresh launch has no agent-session owner claim (agentOwnership: 'absent').
  3. The sweep launches --resume of the same session in yet another tab.

This repeats on every later activation.

After: the census row for that PTY carries the pane key the agent reports from. The record is claimed, the PTY counts as accounted for, and nothing is resumed.

Why

The census already proves which PTYs are alive, but nothing tied a live PTY to the pane an agent reports from. Every existing link goes through renderer state: the layout leaf, ptyIdsByTabId, or status rows. That state is exactly what is missing for a pane another client opened. The spawn pane key is fixed for the life of the PTY, and it is the same key the agent's hooks use.

Alternatives considered:

  • Skip records whose pane has no layout while any live PTY is unclaimed. My first version did this. Review showed it also suppresses legitimate recovery: closeTab(reason: 'pty-exit') keeps the sleeping record but drops the layout, so a crashed agent would stay down while any plain shell was open.
  • Treat absent PTYs as possible owners in the blocked check. That blocks resuming any dead agent whenever a plain shell is open (see resumes a dead agent when the workspace only has a non-agent PTY).
  • Match on terminal handle or provider-session id. The OMP hook does not send a terminal handle, and the census has no provider-session id.

The daemon keeps the key in a side table in terminal-host-session-listing.ts instead of on Session. The listing is the only reader, and Session is at its max-lines cap.

Linked Issue

Fixes #24385

Refs #13716. Activations with startup work (hasActivationWork) still skip the gate and resume without a census. Every caller that passes startup, setup, default tabs, or an issue command is a worktree-creation flow. A sleeping record can exist there only if the new workspace's own startup agent reports before activation finishes; that path is unchanged here.

Visual Proof

N/A. There is no UI change; the visible effect is that no duplicate tab appears. The seam test runs the full activation path.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

New end-to-end test in worktree-agent-activation-seam.test.ts: does not fork an agent from a pane this renderer never had onto its adopted PTY. It goes through activateAndRevealWorktree and the real resume sweep, with:

  • a sleeping OMP record for a pane this renderer has no tab for;
  • a live PTY that lists as absent, whose spawn pane key is that pane;
  • a host that reports the PTY as unowned.

Over two activations it asserts the outcome adopted, a single tab bound to the live PTY, and the record left intact. The second activation finds the PTY already bound to the adopted tab. On main the test fails with resumed.

Second end-to-end test in the same file: does not fork that agent when a phone opens the workspace. It seeds the same state, then runs the real background wake and sweep, and asserts that no tab is created and the record is left intact. Without the wake change, the sweep opens a resume tab. A unit test, wakes hibernated panes but resumes nothing when the PTY census fails, covers the failure case.

Boundary tests:

  • New gate test does not claim a dead agent through a shell spawned for another pane of its tab. The match must be exact: when an agent's tab closed on PTY exit, a shell in a sibling pane must not stop that agent from resuming. This is the regression the earlier design had.
  • Existing tests still cover the rest: a record with no live PTY resumes (preserves a sleeping OMP session until its execution host can answer), and a dead agent next to a plain shell resumes (resumes a dead agent when the workspace only has a non-agent PTY).

Daemon test in terminal-host.test.ts: lists the pane key a session was spawned for, not the pane that reattaches it. Reattaching from another pane keeps the spawn pane key. After the PTY exits and is respawned under the same id, the new key is reported. The fix depends on that behavior, and the seam test cannot see it.

Run locally on Windows:

  • 106 test files, 1,128 tests passing: the daemon, provider, relay, and pty IPC suites, plus the renderer activation, resume, sleeping-agent, background-wake, and host-mirror suites. One existing test fails the same way on a clean main checkout, because a named pipe it needs is missing on this machine (ENOENT): daemon-pty-adapter-daemon-recovery.test.ts › joins a request-path respawn instead of forking a second daemon.
  • Typecheck (all projects), oxlint, oxfmt --check, audit:anti-slop, the code-quality native and type-aware configs, check:code-quality:changed, and check:max-lines-ratchet on the changed files.

Not done: a manual end-to-end check. Reproducing it needs two paired desktops and a build of this branch. Field evidence is in the linked issue.

AI Disclosure

Written with AI assistance: OMP coding agent with Claude Opus 5.5 did the investigation, fix, and tests, and Claude- and GPT-based review agents did independent review passes. I checked the diff and the test results myself.

Review

AI code review summary. Two independent review agents, one Claude-based and one GPT-based, reviewed this in two rounds. In round one both found the regression in the earlier skip-based design, which led to the design in this PR. In round two neither found a correctness problem. They asked for:

  • the daemon lifecycle test and the exact-pane boundary test, both now included;
  • the SSH relay field, now included;
  • notes on the hasActivationWork bypass and the daemon-replacement caveat, now under Linked Issue and Notes;
  • covering the phone-triggered background wake, now included.

A third round reviewed the background-wake change. One reviewer approved it. The other asked that a failed census not authorize a resume, and that errors from the now-async wake be caught and logged; both are done.

Each area checked explicitly:

  • Cross-platform: the key is a plain string taken from the spawn env on every OS. No paths or shell behavior change.
  • SSH, remote, and local: local daemon PTYs and SSH relay PTYs both carry the field. The in-process local provider does not, but it already reports unknown ownership, which blocks resume. Paired-runtime-owned workspaces still block before any of this runs.
  • Agents and integrations: provider-neutral. Every Orca agent integration reports from ORCA_PANE_KEY.
  • Performance: one small map built per activation-gate run, plus one optional string per listed PTY.
  • UI: no change.
  • Security: no new input surface. The pane key is already exported into every Orca PTY and sent by hooks. It now also reaches the renderer on the same machine.
  • Wire compatibility: the new field is optional end to end, as in Rule 1 of docs/reference/remote-wire-compatibility.md. Older daemons and relays omit it, and the gate falls back to the existing claims.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Mobile: the background wake also skips sessions that a live PTY still owns. The wake is now async: its in-place wake and background mounts still run synchronously, and only the resume step waits for the census.
  • Backwards compatibility: no persisted-state change, and the protocol change is optional and additive.
  • Rollout: the daemon protocol version is not bumped, so an updated desktop keeps using a running daemon that still has live sessions. PTYs only gain the field once a daemon built from this change creates them. Whether a bump is worth an extra daemon process is the maintainers' call.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred). I ran the targeted suites and checks listed above; CI covers the full suite and the build.

An agent launched for another client's pane reports that pane key, so the host desktop holds a sleeping record for a pane it has no layout for. Activation adopted the live PTY onto a new tab, could not claim the record, and resumed the same session in another tab, leaving two writers on one transcript. The daemon and SSH relay now list the ORCA_PANE_KEY each PTY was spawned with, and the activation gate claims a record whose pane a live PTY was spawned for.
@greptile-apps

greptile-apps Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 5/5

[Medium risk] Tracks which pane spawned each terminal session.

The latest changes introduce no established blocking issue, though the existing same-pane shell recovery concern remains.

Findings

  1. P2 Shell can claim dead agent ▶

Summary

The PR carries PTY spawn pane keys through session listings and uses them to avoid resuming agents whose PTYs are still live. The latest changes extend that check to phone-triggered background wakes and skip resumption when their census fails.

Reviews (2) · Last reviewed commit: "fix(terminal): skip live agents in the p..."

Comment on lines +140 to 146
const livePtyId =
persistedPtyId && livePtyIds.has(persistedPtyId)
? persistedPtyId
: livePtyIdBySpawnPaneKey.get(record.paneKey)
if (livePtyId) {
claimedPtyIds.add(livePtyId)
keys.add(getProviderSessionClaimKey(record))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Shell can claim dead agent

If an agent’s PTY exits and a plain shell starts in the same pane while the sleeping record remains, this fallback treats the shell’s matching pane key as proof that the agent is still running. The resume sweep then skips the record, leaving the agent unrestored. The new boundary test covers a shell in a sibling pane, but not one with the record’s exact key; please cover that case and distinguish the shell from the live agent before skipping recovery.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks. This case is the trade Orca already makes when it matches by layout, so I left it as is.

If the agent exits and its shell keeps running in the same pane, the record's pane still has a live PTY. In this renderer, the existing layout claim (persistedPtyId && livePtyIds.has(persistedPtyId), line 158) already takes that branch and skips the resume. The spawn-pane-key fallback (line 160) only runs when this renderer has no layout binding for the pane, which means the pane belongs to another client. When it matches, the decision is the same one the layout claim makes: a live PTY in the record's pane counts as owning the session.

The trade is deliberate and documented in resume-sleeping-agent-session.ts:121-127. A live shell can't be told apart from an agent idling at its prompt. Forking the transcript can't be undone, but declining to auto-resume can: the record stays, and the user can resume by hand. Doing better would take provider-session identity in the census, and the census has none today.

The sibling-pane test pins the opposite direction, the regression this design must not reintroduce: a crashed agent must still resume even when other shells in the workspace stay open.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

That clarification addresses the concern. The fallback only applies when this renderer has no binding, while an exact live PTY in the record’s pane is intentionally treated as ownership regardless of whether the process is an agent or shell—the same conservative trade already used by the layout claim. Given that forking a transcript is irreversible and manual resume remains available, I agree this is deliberate behavior rather than a regression. The sibling-pane test covers the important opposite case where unrelated shells must not suppress recovery; no change is needed.

Tip: You can customize Greptile's behavior for this repo with .greptile/rules.md and .greptile/config.json.

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

✅ No new issues found.

Reviewed changes

  • Spawn pane key reaches the census — the daemon records the ORCA_PANE_KEY a session was spawned with in a WeakMap (reattach never rewrites it) and the SSH relay publishes its existing managed.paneKey; both surface as optional paneKey through PtyProcessInfo / SessionInfo / PtyListedSession, byte-accounted in pty-process-list-admission.ts.
  • Activation gate claims by spawn pane key — liveSleepingAgentClaims now takes the listed sessions and, when the persisted layout PTY is not live, claims a sleeping record via the live PTY spawned for that record's pane, so an agent another client launched is no longer resumed onto a second tab.
  • Regression and boundary coverage — an end-to-end seam test over activateAndRevealWorktree (adopts, single tab, record intact), an exact-pane boundary test (a sibling-pane shell must not claim a dead agent), and a daemon lifecycle test (reattach keeps the spawn key; respawn under the same id reports the new key).

Verified locally: gate (34), seam (11), and daemon terminal-host suites pass (78 tests, 3 files). I traced the key end to end for both the daemon and the SSH relay (mapSshPtyProcessList spreads ...session, so paneKey survives), and the gate's exact-string match against record.paneKey is the right discriminator — the layout/tab fallback already covered the same-pane case, so the added fallback only fires where the leaf is gone.

ℹ️ Daemon protocol version is not bumped, so the fix only reaches PTYs created after the daemon is rebuilt

The daemon-protocol line is unchanged, so a desktop updated over an already-running daemon keeps talking to it and existing live sessions never gain paneKey. On Windows especially, the daemon can outlive an app update, so the exact PTY that triggers #24385 (a still-running agent) will not be claimed until it is respawned — the fix does not retroactively apply to the state that produced the report. This is a deliberate call the author flagged for maintainers; recording it here so the tradeoff is explicit before merge.

Technical details
# Daemon protocol version is not bumped

## Affected sites
- `src/main/daemon/terminal-host-session-listing.ts` — `paneKey` is only populated for sessions spawned after this build; it is not part of a versioned handshake.
- `src/main/daemon/types.ts` — `SessionInfo.paneKey` is additive/optional; old daemons omit it and the gate falls back to prior claims.

## Required outcome
- Decide whether the fix must apply to a live agent PTY that already exists on an older daemon generation, or whether "applies to the next spawn" is acceptable. If the former, the daemon needs a version bump or a migration trigger so a running daemon is replaced.

## Open questions for the human
- Is the intent to close #24385 for currently-affected users, or only to stop new occurrences? The PR text currently says `Fixes #24385`, which reads as the former.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai

coderabbitai Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 6696f936-2f36-46f8-8ac5-683ef9c98d27

📥 Commits

Reviewing files that changed from the base of the PR and between 127afa3 and 39d30b8.

📒 Files selected for processing (6)
  • src/renderer/src/lib/wake-sleeping-agents-in-background.test.ts
  • src/renderer/src/lib/wake-sleeping-agents-in-background.ts
  • src/renderer/src/lib/wake-sleeping-agents-live-done.test.ts
  • src/renderer/src/lib/worktree-agent-activation-gate.ts
  • src/renderer/src/lib/worktree-agent-activation-seam.test.ts
  • src/renderer/src/runtime/host-session-mirror-hydration-frame-ordering.test.tsx

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.


📝 Walkthrough

Walkthrough

PTY sessions now retain the pane key used at spawn and expose it through process listings. The activation gate matches sleeping agent records to live sessions by persisted PTY ID or spawn pane key. Background wake checks live PTY claims before resuming sessions and stops generic resume when the claim census fails. Tests cover spawn-key retention, activation matching, and background wake behavior.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to 39d30

The change protects still-running agents from duplicate resumes and preserves passive wake behavior when the live-session check fails. No actionable merge-blocking issue is established; merge after normal checks pass.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 39d30

The change reduces duplicate agent restarts and preserves existing ownership checks. No introduced security finding was established, but reconnect, identity uniqueness and mixed-version recovery assumptions remain incompletely verified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The newly affected decision is automatic resume suppression for sleeping records within the selected execution provider and worktree. Incorrect correlation could defer recovery or misclassify a live claim, but the inspected consumers do not turn paneKey into additional kill, write or credential authority.

Trust Boundaries and Controls

  • observed — The desktop spawn path normalizes pane identity from validated spawn metadata and removes pane environment values when forwarding is not permitted or no stable identity is available. The relay captures the supplied environment key and returns it through its existing listing operation. Its endpoint handshake rejects credential mismatches when an endpoint credential is configured; unconditional credential provisioning was not verified.

Resilience and Maintainability Implications

  • observed — Automatic activation requests one explicitly selected provider rather than aggregate diagnostic inventory. Provider failures propagate for scoped listings, and malformed or over-capacity rows cause admission to throw. These controls prevent the inspected IPC path from presenting a silently truncated census as successful evidence of absence.
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The PR changes the excluded mobile/runtime wake path. wakeSleepingAgentsForWorktreeInBackground now performs a PTY census, skips live-PTY claims, and stops on census failure. The seam test also adds… Remove the mobile/runtime wake behavior and its related tests from this PR, or move them to a separately scoped issue and pull request. Keep the host worktree activation changes required by #24385.
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 15 functions across 17 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR satisfies the coding requirements in #24385. Terminal-daemon, SSH-relay, IPC, and PTY listings preserve the PTY spawn-time paneKey. The activation gate matches that key to the live PTY and cl…
Title check ✅ Passed The title clearly and concisely describes the main change: preventing resume of an agent whose spawned PTY is still live.
Description check ✅ Passed The description follows the required template and covers the user impact, implementation, rationale, linked issue, testing, known test limitation, compatibility, review notes, and checklist. It also s…
Full details: Out of Scope Changes check

Explanation

The PR changes the excluded mobile/runtime wake path. wakeSleepingAgentsForWorktreeInBackground now performs a PTY census, skips live-PTY claims, and stops on census failure. The seam test also adds phone-wake behavior. #24385 explicitly excludes activateManagedWorktree mobile/runtime wake work, so these are unrelated product changes rather than support for the host activation fix.

  • Fix all pre-merge checks with AI
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


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.

…e too

The background wake that runs when a phone opens a worktree was the other caller of the resume sweep, and it never consulted the PTY census, so it could still fork an agent another client launched. It now reads the same census claims as the activation gate. A workspace owned by a paired runtime has no client census and keeps its host-mirror checks; any other census failure skips the resume step.

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

✅ No new issues found.

Reviewed changes

  • Phone-triggered background wake now reads the PTY census — wakeSleepingAgentsForWorktreeInBackground awaits readLiveSleepingAgentClaimKeys after its in-place wake and background-mount steps and merges those claims into skipClaimKeys, so a phone opening the workspace no longer forks an agent another client launched. The function is now async; the dispatcher awaits-and-catches it and logs failures instead of firing and forgetting.
  • Fail-closed on an unreadable census — the new readLiveSleepingAgentClaimKeys returns null when listActivationPtySessions throws, and the wake then skips only its resume step; steps (a) and (b) still run. A paired-runtime-owned workspace yields an empty set and keeps the existing host-mirror handling in the resume sweep.
  • Gate helpers extracted for reuse — liveSessionsInWorkspace and the spawn-pane-key claim logic are now shared by the activation gate and the new census reader, so both paths claim on identical evidence.
  • Coverage — a phone-triggered end-to-end seam test, a unit test for the census-failure skip, a unit test asserting skipClaimKeys carries both in-place and live-PTY claims, and await added to the displaced frame-ordering test. Re-ran the wake, live-done, gate (49 tests) and seam (12 tests) suites on 39d30b8; all green.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

nwparker added a commit that referenced this pull request Oct 25, 2026
The terminal daemon now lists the ORCA_PANE_KEY each PTY was spawned with,
and the activation gate (also used by the phone wake) claims a sleeping
record through that key when this renderer's layout no longer links the
record's pane to the live PTY. Covers a host that re-keyed the live PTY onto
a new tab and an agent a paired client launched for its own pane; both
previously forked a second `claude --resume` onto the live transcript.

Rewritten on current main from #24386 (the phone wake already routes
through the gate since #29431; the SSH relay it also touched is gone).

Co-authored-by: Minidoracat <[email protected]>
@nwparker

Copy link
Copy Markdown
Contributor

Thanks @Minidoracat! Your approach landed via #33380 (credited with Co-authored-by): the daemon reports each terminal's spawn pane key and the activation gate uses it to find the live agent PTY. The phone-wake and relay parts are no longer needed on main (#29431 routes phone wake through the gate; the relay was removed). Closing as superseded.

nwparker added a commit that referenced this pull request Oct 25, 2026
…33380)

The daemon records each terminal's spawn pane key and reports it in session listings; the sleeping-agent activation gate uses it as an exact-match fallback to find a live agent PTY after the host re-keys its tab, so paired clients and phone wake no longer start a duplicate `claude --resume`. Fixes #21235, #24385. Supersedes #24386.

Co-authored-by: Minidoracat <[email protected]>
@nwparker nwparker closed this Oct 25, 2026
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.

[Bug]: Activation resumes an agent a paired client launched while it is still running, forking it onto a second tab

2 participants