Repository navigation
fix(terminal): truthful handle liveness + no forked resume tabs for hidden restorable panes - #12574
Conversation
…en PTY absence leaf.connected mirrors the renderer graph (ptyId !== null), so a restored surface whose PTY died with a prior process was listed connected/writable forever with empty title/lastOutputAt/preview — the exact signature automation saw on run6 workspaces after a restart. listTerminals now threads the controller inventory it already fetches into buildTerminalSummary and demotes only on proven absence, only for locally-scoped ids; unknown liveness and SSH/remote scopes never demote, and no session or pane is retired.
…resume tabs paneWillConnectOnActivation still assumed the pre-keep-alive mount model, but every non-parked tab of the active worktree mounts and connects hidden at 0x0. Activation therefore appended a replacement resume tab per non-group-active agent pane and handed it the sleeping record, stranding the hidden pane as a bare shell — or forking two live surfaces onto one provider session when the old PTY survived in the daemon. The predicate now answers "will mount and connect": any non-web-mirror tab of the active worktree qualifies; non-active worktrees still answer false so background wake keeps its append-based resume. Contract change: reverses the hidden-tab expectation from #6800, whose premise (hidden panes never connect) no longer holds; that test is updated in place.
📝 WalkthroughWalkthroughThe runtime now tracks aggregate live PTY IDs and marks proven-absent local PTYs as disconnected and non-writable. Unknown, remote, and SSH PTYs retain their existing state. Renderer activation treats non-web terminal panes as reconnecting and supports in-place cold restoration. Per-tab cold parking preserves tabs associated with sleeping-agent sessions in the current worktree. Tests cover PTY liveness, pane replacement, repeated activation, and sleeping-session retention. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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
🧹 Nitpick comments (2)
src/renderer/src/lib/worktree-reactivation-preserved-pane-replacement.test.ts (1)
173-227: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCover the web-terminal exception.
Current cases use
HUSK_TAB_ID, so they only cover local terminal tabs. Add a focused case with a web-terminal surface tab ID. Assert that an otherwise restorable record is not claimed for local in-place recovery. This protects the exception insrc/renderer/src/lib/sleeping-agent-pane-ownership.tsLine 120.src/main/runtime/terminal-list-stale-leaf-liveness.test.ts (1)
6-12: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReduce this comment to one test invariant.
The comment repeats the test setup and expected behavior. Keep one concise statement of the required liveness contract.
Proposed change
-// STA repro (run6-review-pr-11959 incident): a renderer-published leaf whose -// ptyId no PTY provider owns anymore (e.g. a persisted surface restored after a -// restart, or a pane that never completed its initial attach) must not be -// reported connected/writable to external automation. `leaf.connected` mirrors -// `ptyId !== null` from the graph, so without consulting the controller -// inventory the CLI reports connected=true, writable=true with empty -// title/lastOutputAt/preview forever — the exact incident signature. +// A locally absent PTY must not be reported connected or writable.As per coding guidelines, comments must be concise, non-obvious, and preferably one line.
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 560f6f1b-0e45-4d5d-8508-64fafe7dfe53
📒 Files selected for processing (5)
src/main/runtime/orca-runtime.tssrc/main/runtime/terminal-list-stale-leaf-liveness.test.tssrc/renderer/src/lib/resume-sleeping-agent-session.test.tssrc/renderer/src/lib/sleeping-agent-pane-ownership.tssrc/renderer/src/lib/worktree-reactivation-preserved-pane-replacement.test.ts
…ership exception CodeRabbit flagged both exclusions as untested: a remote-runtime-scoped leaf absent from the local inventory must stay connected (its inventory lives on the remote host), and a web-mirror tab must not own sleeping-session recovery (it never mounts a local pane), so the appended replacement remains its correct resume path.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 82d2ea16-4b48-4f3f-80ec-3d3fbdbaa027
📒 Files selected for processing (2)
src/main/runtime/terminal-list-stale-leaf-liveness.test.tssrc/renderer/src/lib/worktree-reactivation-preserved-pane-replacement.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/main/runtime/terminal-list-stale-leaf-liveness.test.ts
… panes owning sleeping records Review (GPT verifier) confirmed two gaps: - listTerminals demoted a live just-spawned PTY when listProcesses snapshotted before session registration (the sweep's hasPty rescue is leaf-gated), and federation reads one connected:false as exited. The summary's proven-absence check now also consults the provider's sync hasPty. - Ordinary per-tab cold parking (30s hidden) kept a non-group-active pane unmounted, so a sleeping record it owns under the new ownership predicate could not cold-restore until the user revealed the tab. Per-tab parks now exempt panes owning a sleeping-session record; worktree-level parks are untouched (they clear on activation).
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.test.ts (1)
262-272: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCover the pane-key fallback.
The hook also derives the tab ID from
paneKeywhentabIdis absent. Add a same-worktree case withouttabIdand verify thattab-2remains unparked. This protects persisted legacy records.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: ccf1e326-e952-46bf-b4b0-7c77e6dcdc30
📒 Files selected for processing (4)
src/main/runtime/orca-runtime.tssrc/main/runtime/terminal-list-stale-leaf-liveness.test.tssrc/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.test.tssrc/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/main/runtime/orca-runtime.ts
… the park exemption to consumable records Round-2 review confirmed two holes in the round-1 fixes: - DaemonPtyAdapter.hasPty is cached activeSessionIds membership, and a successful listSessions never removed ids the authoritative inventory omitted — an exit missed while the socket was down kept hasPty true forever, and the new spawn/list-race rescue would trust it, reopening connected-forever for that pty. listProcesses now drops pre-request cached ids the inventory does not list alive (ids spawned mid-flight are snapshot- protected). - The park exemption covered records a pane can never consume (automaticResumeBlockedBy, passive-completed evidence), pinning hidden panes mounted indefinitely. The exemption now lives in sleeping-record-park-exemption.ts and requires a consumable record. Also pins the web-mirror replacement's resume claim and startup command (CodeRabbit round-2).
There was a problem hiding this comment.
Actionable comments posted: 3
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: a03b94e9-5494-4b86-9bd4-56e2c9d9730d
📒 Files selected for processing (6)
src/main/daemon/daemon-pty-adapter.test.tssrc/main/daemon/daemon-pty-adapter.tssrc/renderer/src/components/terminal-pane/sleeping-record-park-exemption.tssrc/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.test.tssrc/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.tssrc/renderer/src/lib/worktree-reactivation-preserved-pane-replacement.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- src/renderer/src/lib/worktree-reactivation-preserved-pane-replacement.test.ts
- src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.test.ts
- src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.ts
| // Why: snapshotted before the request so ids spawned mid-flight can never | ||
| // be reconciled away below. | ||
| const preRequestActiveIds = new Set(this.activeSessionIds) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🔴 Critical | 🏗️ Heavy lift
Protect replacements that reuse a session ID.
preRequestActiveIds stores only IDs. If an old session exits and a new session reuses the same ID while listSessions is in flight, the inventory can omit that ID during the transition. The ID remains in preRequestActiveIds, so this cleanup deletes the replacement from activeSessionIds. hasPty() can then report false for a live PTY.
Track a per-session generation or incarnation in the snapshot. Delete an ID only when its current generation still matches the snapshot. Add a regression test for same-ID replacement during an in-flight inventory.
Also applies to: 1420-1427
| for (const id of preRequestActiveIds) { | ||
| if (!aliveSessionIds.has(id)) { | ||
| this.activeSessionIds.delete(id) | ||
| } | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
Clear checkpoint bookkeeping for sessions proven absent.
This loop removes only activeSessionIds. If an omitted session has a dirtySessionVersions entry and another session remains active, checkpointDirtySessions() filters the ID out of its work set but leaves it in dirtySessionVersions. stopCheckpointTimerIfIdle() then keeps the five-second checkpoint timer running.
After the generation check, clear dirtySessionVersions and related checkpoint state for the omitted ID. Use a shared cleanup path if recovery-specific state also requires handling.
| if (record.automaticResumeBlockedBy || isPassiveCompletedHibernationEvidence(record)) { | ||
| continue | ||
| } | ||
| const tabId = record.tabId ?? record.paneKey.slice(0, record.paneKey.indexOf(':')) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rg -n -C 4 '\bpaneKey\b' src --glob '*.{ts,tsx}'Repository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Target file context:"
sed -n '1,80p' src/renderer/src/components/terminal-pane/sleeping-record-park-exemption.ts
echo
echo "Type definitions / helpers for paneKey across tracked source (excl tests):"
rg -n "paneKey:|makePaneKey|function makePaneKey|const makePaneKey|new PaneKey|PaneKey|sleepingAgentSessionsByPaneKey|sleepingAgentSession" src/renderer/src --glob '!**/*.test.{ts,tsx}' || true
echo
echo "Filenames containing pane key factory or sleeping session:"
git ls-files src/renderer/src --exclude='**/*.test.{ts,tsx}' | rg -i 'pane|sleep|session|terminal|tab' || trueRepository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "stable pane-id implementation:"
sed -n '1,260p' shared/stable-pane-id.ts
echo
echo "Target exemption file:"
sed -n '1,80p' src/renderer/src/components/terminal-pane/sleeping-record-park-exemption.ts
echo
echo "Sleeping record type/usages without full matches:"
rg -n "sleepingAgentSessionsByPaneKey|sleeping.*Session|Sleeping.*Record|makeSleepingRecord|recordTerminal" src/renderer/src --glob '!**/*.test.{ts,tsx}' --glob '!**/*.test.tsx' | head -n 200
echo
echo "Precise non-test source files where sleepingAgentSessionsByPaneKey is read/written:"
rg -l "sleepingAgentSessionsByPaneKey" src/renderer/src --glob '!**/*.test.{ts,tsx}' | sort
echo
echo "Programmatic delimiter check from source implementations:"
python3 - <<'PY'
from pathlib import Path
paths = [Path('shared/stable-pane-id.ts'), Path('src/renderer/src/components/terminal-pane/sleeping-record-park-exemption.ts')]
for path in paths:
text = path.read_text()
print(path, 'contains makePaneKey' in text, 'contains parsePaneKey' in text, 'contains indexOf' in text, 'contains slice(0,' in text)
PYRepository: stablyai/orca
Length of output: 250
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Find pane-id file:"
fd -a 'stable-pane-id' . || true
echo
echo "Find pane-key factory/import locations:"
rg -n "makePaneKey|parsePaneKey|function makePaneKey|export .*makePaneKey|String\\(pane\\)|\\${pane}" . --glob '!**/.git/**' | head -n 240
echo
echo "Find target exemption file exact path:"
fd -a 'sleeping-record-park-exemption' . || trueRepository: stablyai/orca
Length of output: 425
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "stable-pane-id implementation:"
sed -n '1,260p' src/shared/stable-pane-id.ts
echo
echo "mint-stable-pane-id implementation:"
sed -n '1,260p' src/renderer/src/lib/pane-manager/mint-stable-pane-id.ts
echo
echo "Target exemption file:"
sed -n '1,80p' src/renderer/src/components/terminal-pane/sleeping-record-park-exemption.ts
echo
echo "Programmatic delimiter shape check:"
python3 - <<'PY'
from pathlib import Path
files = [
Path('src/shared/stable-pane-id.ts'),
Path('src/renderer/src/lib/pane-manager/mint-stable-pane-id.ts'),
Path('src/renderer/src/components/terminal-pane/sleeping-record-park-exemption.ts'),
]
for p in files:
text = p.read_text()
print(f"{p}: contains makePaneKey={any(x in text for x in ['makePaneKey','String(paneKey)'])}, contains parsePaneKey={'parsePaneKey' in text}, contains indexOf={text.find(\"indexOf(':\")!=-1}, contains slice(0,={text.find('slice(0,')!=-1}")
PYRepository: stablyai/orca
Length of output: 5334
🏁 Script executed:
#!/bin/bash
set -euo pipefail
python3 - <<'PY'
from pathlib import Path
files = [
Path('src/shared/stable-pane-id.ts'),
Path('src/renderer/src/lib/pane-manager/mint-stable-pane-id.ts'),
Path('src/renderer/src/components/terminal-pane/sleeping-record-park-exemption.ts'),
]
for p in files:
text = p.read_text()
print(f"{p}: factory={('makePaneKey' in text)}, parse={('parsePaneKey' in text)}, indexOf={('indexOf' in text)}, slice={('slice(0' in text)}")
PY
echo
echo "SleepingAgentSessionRecord type:"
rg -n -A 80 "export type SleepingAgentSessionRecord|interface SleepingAgentSessionRecord|type SleepingAgentSessionRecord" src --glob '!**/*.test.{ts,tsx}' | head -n 180
echo
echo "Non-test files writing/constructing sleepingAgentSessionsByPaneKey:"
rg -n "sleepingAgentSessionsByPaneKey|setSleepingAgentSession|SleepingAgentSessionRecord|paneKey:" src --glob '!**/*.test.{ts,tsx}' | sed -n '1,200p'Repository: stablyai/orca
Length of output: 32962
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "workspace-session-sleeping-agents schema around paneKey:"
sed -n '1,170p' src/shared/workspace-session-sleeping-agents.ts
echo
echo "Agent hibernation planner creation path around sleeping records:"
sed -n '240,320p' src/renderer/src/lib/agent-hibernation-planner.ts
echo
echo "Wake sleeping agents record id extraction:"
sed -n '60,90p' src/renderer/src/lib/wake-sleeping-agents-in-background.ts
echo
echo "Agent status slice collection around getSleepingRecordTabId / candidate id:"
sed -n '222,290p' src/renderer/src/lib/agent-status-connection-ownership.ts
rg -n "getSleepingRecordTabId|candidateIdFor|setSleepingAgentSession|new \\{" src/renderer/src/lib src/shared --glob '!**/*.test.{ts,tsx}' | head -n 200
echo
echo "All create/serialize literal usages of SleepingAgentSessionRecord in source:"
rg -n "tabId\\??:|paneKey: makePaneKey\\(|sleepingAgentSessionsByPaneKey\\[paneKey\\]|sleepingAgentSessionsByPaneKey\\['|makeSleepingRecord|recordPaneIsOwned" src/renderer/src src/shared --glob '!**/*.test.{ts,tsx}' | head -n 250Repository: stablyai/orca
Length of output: 32819
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Agent hibernation planner relevant ranges:"
sed -n '130,240p' src/renderer/src/lib/agent-hibernation-planner.ts
echo
sed -n '290,315p' src/renderer/src/lib/agent-hibernation-planner.ts
echo
echo "Sleeping record extraction ranges:"
sed -n '630,675p' src/renderer/src/store/slices/agent-status.ts
echo
sed -n '20,35p' src/renderer/src/lib/sleeping-agent-pane-ownership.ts
echo
sed -n '35,80p' src/renderer/src/hooks/useIpcEvents.ts
echo
echo "Other tab id derivation helpers:"
sed -n '350,405p' src/renderer/src/store/slices/agent-status.ts
echo
echo "Read-only behavioral probe of `makePaneKey` / parser and fallback output:"
python3 - <<'PY'
from pathlib import Path
src = Path('src/shared/stable-pane-id.ts').read_text()
needles = ['function makePaneKey(tabId: string, stableLeafId: string): PaneKey', 'function parsePaneKey', 'indexOf(']
checks = {needle: src.find(needle) != -1 for needle in needles}
print(checks)
PYRepository: stablyai/orca
Length of output: 11581
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Agent status slice range around `tabI` and sleeping record carry:"
sed -n '880,915p' src/renderer/src/store/slices/agent-status.ts
echo
sed -n '1828,1872p' src/renderer/src/store/slices/agent-status.ts
echo
echo "Search for SleepingAgentSessionRecord construction in non-test source:"
rg -n "return \\{|tabId:.*getTabIdFromPaneKey|paneKey: makePaneKey|tabId:.*entry|tabId:.*paneKey|sleepingAgentSessionsByPaneKey\\[paneKey\\] =" src/renderer/src src/shared --glob '!**/*.test.{ts,tsx}' | head -n 220
echo
echo "Focused IPC payload normalization for paneKey around terminal events:"
sed -n '3672,3718p' src/renderer/src/hooks/useIpcEvents.tsRepository: stablyai/orca
Length of output: 21421
Add a safe delimiter guard for paneKey.
paneKey supports legacy numeric forms and hypphenated/unknown forms, so indexOf(':') can be non-positive. For paneKey === 'tab-1', the fallback returns tab- and can add the wrong tab as a cold-park exemption. Use parsePaneKey/parseLegacyNumericPaneKey or check index > 0 before slicing.
main's stablyai#12574 grew use-terminal-tab-cold-parking.ts alongside this branch, so the merge crossed the 300-line budget. Move the last gate between a candidate and an unmounted pane — watcher coverage and the verdict-flip pin — into its own module rather than ratcheting the limit.
…esktop promotion (#12666) STA-1716 reported that a packaged `orca serve` could become the single-instance owner after the desktop app exits, leaving Dock/Finder unable to restore a window — and that forcing a reopen made the headless process hydrate a renderer that interrupted and DUPLICATED live agent sessions. Verification against main found every criterion already fixed (#8646 for desktop promotion and the fail-closed CLI, #12212 for duplicate serve activation, #12574 + #9729 for the resume/ownership guards). The genuine gap was criterion 6: the ticket's own automated regression never existed. An existing reliability gate asserted PTY identity survives promotion, but nothing asserted what the incident was actually about — how many agents the promoted renderer resumes. This adds that coverage: a unit/service-level journey that drives the real single-instance lock, activation gate, settle and focus paths, then runs the real resume logic against a store seeded as a renderer freshly mounted inside the serve process, asserting zero duplicate resumes. `settleServeDesktopActivation` moved from `index.ts` into its own module with identical semantics, so the test drives the real decision rather than re-implementing it — the earlier repro had to mirror that logic locally, which is the "test passes without running the scenario" failure mode. Proven to be a real oracle: breaking each guard individually turns it red, and reverting the pre-#12574 pane form reproduces the incident exactly (two duplicate `codex resume` tabs).
…idden restorable panes (stablyai#12574) * fix(runtime): report terminal handles disconnected on controller-proven PTY absence leaf.connected mirrors the renderer graph (ptyId !== null), so a restored surface whose PTY died with a prior process was listed connected/writable forever with empty title/lastOutputAt/preview — the exact signature automation saw on run6 workspaces after a restart. listTerminals now threads the controller inventory it already fetches into buildTerminalSummary and demotes only on proven absence, only for locally-scoped ids; unknown liveness and SSH/remote scopes never demote, and no session or pane is retired. * fix(terminal): stop forking hidden restorable panes into replacement resume tabs paneWillConnectOnActivation still assumed the pre-keep-alive mount model, but every non-parked tab of the active worktree mounts and connects hidden at 0x0. Activation therefore appended a replacement resume tab per non-group-active agent pane and handed it the sleeping record, stranding the hidden pane as a bare shell — or forking two live surfaces onto one provider session when the old PTY survived in the daemon. The predicate now answers "will mount and connect": any non-web-mirror tab of the active worktree qualifies; non-active worktrees still answer false so background wake keeps its append-based resume. Contract change: reverses the hidden-tab expectation from stablyai#6800, whose premise (hidden panes never connect) no longer holds; that test is updated in place. * test(terminal): pin the remote-scope exemption and the web-mirror ownership exception CodeRabbit flagged both exclusions as untested: a remote-runtime-scoped leaf absent from the local inventory must stay connected (its inventory lives on the remote host), and a web-mirror tab must not own sleeping-session recovery (it never mounts a local pane), so the appended replacement remains its correct resume path. * fix(terminal): rescue just-spawned ptys from absence demotion; unpark panes owning sleeping records Review (GPT verifier) confirmed two gaps: - listTerminals demoted a live just-spawned PTY when listProcesses snapshotted before session registration (the sweep's hasPty rescue is leaf-gated), and federation reads one connected:false as exited. The summary's proven-absence check now also consults the provider's sync hasPty. - Ordinary per-tab cold parking (30s hidden) kept a non-group-active pane unmounted, so a sleeping record it owns under the new ownership predicate could not cold-restore until the user revealed the tab. Per-tab parks now exempt panes owning a sleeping-session record; worktree-level parks are untouched (they clear on activation). * fix(terminal): reconcile the daemon session cache on inventory; scope the park exemption to consumable records Round-2 review confirmed two holes in the round-1 fixes: - DaemonPtyAdapter.hasPty is cached activeSessionIds membership, and a successful listSessions never removed ids the authoritative inventory omitted — an exit missed while the socket was down kept hasPty true forever, and the new spawn/list-race rescue would trust it, reopening connected-forever for that pty. listProcesses now drops pre-request cached ids the inventory does not list alive (ids spawned mid-flight are snapshot- protected). - The park exemption covered records a pane can never consume (automaticResumeBlockedBy, passive-completed evidence), pinning hidden panes mounted indefinitely. The exemption now lives in sleeping-record-park-exemption.ts and requires a consumable record. Also pins the web-mirror replacement's resume claim and startup command (CodeRabbit round-2). --------- Co-authored-by: OrcaWin <[email protected]>
…esktop promotion (stablyai#12666) STA-1716 reported that a packaged `orca serve` could become the single-instance owner after the desktop app exits, leaving Dock/Finder unable to restore a window — and that forcing a reopen made the headless process hydrate a renderer that interrupted and DUPLICATED live agent sessions. Verification against main found every criterion already fixed (stablyai#8646 for desktop promotion and the fail-closed CLI, stablyai#12212 for duplicate serve activation, stablyai#12574 + stablyai#9729 for the resume/ownership guards). The genuine gap was criterion 6: the ticket's own automated regression never existed. An existing reliability gate asserted PTY identity survives promotion, but nothing asserted what the incident was actually about — how many agents the promoted renderer resumes. This adds that coverage: a unit/service-level journey that drives the real single-instance lock, activation gate, settle and focus paths, then runs the real resume logic against a store seeded as a renderer freshly mounted inside the serve process, asserting zero duplicate resumes. `settleServeDesktopActivation` moved from `index.ts` into its own module with identical semantics, so the test drives the real decision rather than re-implementing it — the earlier repro had to mirror that logic locally, which is the "test passes without running the scenario" failure mode. Proven to be a real oracle: breaking each guard individually turns it red, and reverting the pre-stablyai#12574 pane form reproduces the incident exactly (two duplicate `codex resume` tabs).
Summary
Root-cause fixes for the run6 autonomous-workspace terminal incident (workspace
run6-review-pr-11959; reproduced live on untouchedrun6-review-pr-12042). The rc.3→v1.4.168 upgrade was chronology, not cause — the 6-commit tag delta touches only relay/SSH, and the PTY daemon survives app restarts by design.Fix 1 —
orca-runtime.ts: report only proven liveness.leaf.connectedmirrors the renderer graph (ptyId !== null), so restored surfaces whose PTY died with a prior process were listedconnected: true / writable: trueforever, with empty title/lastOutputAt/preview (that signature means "zero bytes crossed this process").listTerminalsnow threads the controller inventory it already fetches intobuildTerminalSummaryand demotes only on proven absence, only for locally-scoped ids. Unknown liveness and SSH/remote:scopes never demote; nothing is retired or destroyed (consistent with #12393's proven-absence rule, applied to reporting).Fix 2 —
sleeping-agent-pane-ownership.ts: stop forking hidden restorable panes.paneWillConnectOnActivationstill assumed the pre-keep-alive mount model, but every non-parked tab of the active worktree mounts and connects hidden at 0×0 (TerminalPaneOverlayLayer.tsx,pty-connection.ts:4544-4557). Activation therefore appended a replacement resume tab per non-group-active agent pane and handed it the sleeping record — stranding the hidden pane as a bare shell, or running two live surfaces on one provider session when the old PTY survived in the daemon. Background-created agent tabs 2..N never hold the group-active slot, so autonomous workspaces forked one replacement per extra agent tab on first click. The predicate now answers "will mount and connect"; non-active worktrees still answer false, so background wake keeps its append-based resume.Test plan
src/main/runtime/terminal-list-stale-leaf-liveness.test.ts(4): proven-absent demotion, live kept, unknown-never-demotes, SSH scope excluded — the first case fails without Fix 1.src/renderer/src/lib/worktree-reactivation-preserved-pane-replacement.test.ts(4): husk append + repeat-activation stability, live-pane no-fork, in-place-restore no-append, non-group-active no-fork — the last fails without Fix 2.resume-sleeping-agent-session.test.tshidden-tab case to the corrected contract.orca-runtime.test.ts1022 ✅; 13 sleeping-session/activation suites 130 ✅; adjacent orphan/graph-sync/banner suites 46 ✅;tscnode+web ✅;oxlint✅.Not addressed here (documented for follow-up): silent-accept writes to stale handles, and reattach snapshot never seeding preview/title (both confirmed with repro chains).