Repository navigation
fix(terminal): don't resume an agent whose spawned PTY is still live - #24386
Minidoracat wants to merge 2 commits into
Conversation
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.
|
| const livePtyId = | ||
| persistedPtyId && livePtyIds.has(persistedPtyId) | ||
| ? persistedPtyId | ||
| : livePtyIdBySpawnPaneKey.get(record.paneKey) | ||
| if (livePtyId) { | ||
| claimedPtyIds.add(livePtyId) | ||
| keys.add(getProviderSessionClaimKey(record)) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Spawn pane key reaches the census — the daemon records the
ORCA_PANE_KEYa session was spawned with in aWeakMap(reattach never rewrites it) and the SSH relay publishes its existingmanaged.paneKey; both surface as optionalpaneKeythroughPtyProcessInfo/SessionInfo/PtyListedSession, byte-accounted inpty-process-list-admission.ts. - Activation gate claims by spawn pane key —
liveSleepingAgentClaimsnow 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.DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
|
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 configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (6)
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review. 📝 WalkthroughWalkthroughPTY 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 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 ReviewSecurity architecture risk: 🔵 Low · up to 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 Security review detailsSecurity Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Out of Scope Changes checkExplanation The PR changes the excluded mobile/runtime wake path.
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 |
…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.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Phone-triggered background wake now reads the PTY census —
wakeSleepingAgentsForWorktreeInBackgroundawaitsreadLiveSleepingAgentClaimKeysafter its in-place wake and background-mount steps and merges those claims intoskipClaimKeys, 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
readLiveSleepingAgentClaimKeysreturnsnullwhenlistActivationPtySessionsthrows, 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 —
liveSessionsInWorkspaceand 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
skipClaimKeyscarries both in-place and live-PTY claims, andawaitadded to the displaced frame-ordering test. Re-ran the wake, live-done, gate (49 tests) and seam (12 tests) suites on39d30b8; all green.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
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]>
|
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. |
…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]>

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
ORCA_PANE_KEYeach PTY was spawned with, aspaneKeyin 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.pty:listSessionsas an optional field,PtyListedSession.paneKey.liveSleepingAgentClaimsin 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.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 throughreadLiveSleepingAgentClaimKeysbefore its resume step and merges them intoskipClaimKeys. 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:
blockedcheck skips the PTY, because a fresh launch has no agent-session owner claim (agentOwnership: 'absent').--resumeof 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:
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.absentPTYs as possible owners in theblockedcheck. That blocks resuming any dead agent whenever a plain shell is open (seeresumes a dead agent when the workspace only has a non-agent PTY).The daemon keeps the key in a side table in
terminal-host-session-listing.tsinstead of onSession. The listing is the only reader, andSessionis 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
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 throughactivateAndRevealWorktreeand the real resume sweep, with:absent, whose spawn pane key is that pane;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. Onmainthe test fails withresumed.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:
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.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:
maincheckout, 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.oxlint,oxfmt --check,audit:anti-slop, the code-quality native and type-aware configs,check:code-quality:changed, andcheck:max-lines-ratcheton 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:
hasActivationWorkbypass and the daemon-replacement caveat, now under Linked Issue and Notes;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:
unknownownership, which blocks resume. Paired-runtime-owned workspaces still block before any of this runs.ORCA_PANE_KEY.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
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred). I ran the targeted suites and checks listed above; CI covers the full suite and the build.