Repository navigation
fix(terminal): retire sessions when tabs close - #8628
Conversation
📝 WalkthroughWalkthroughThe change defines explicit terminal retirement semantics independent of React view mounting, adds PTY ownership planning and provider teardown, propagates close reasons, and protects asynchronous launches from recreating closed tabs. It also adds pane-authority transfer and retirement across renderer, main, preload, persistence, and hook ingestion paths. Bulk terminal cleanup now coordinates daemon results with exact PTY teardown, while tests, reliability gates, and Electron helpers cover parked-tab closure, late spawns, authority races, and stable repository/worktree selection. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 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: 3
🧹 Nitpick comments (4)
pty-exhaustion-agent-session-leak.md (1)
164-164: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winAdd rollback instructions for the PTY limit tweak.
kern.tty.ptmx_max=999is the macOS ceiling, so this only buys temporary headroom. Document how to revert the sysctl and remove any persistent/etc/sysctl.confoverride.src/renderer/src/lib/retire-unowned-background-terminal.ts (1)
22-38: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winSilent best-effort teardown hides future leaks.
The catch block swallows every failure from
terminal.close/pty.killwith no logging. Given this module exists specifically to close the PTY-exhaustion leak, a failed retirement (e.g. IPC timeout, dead runtime) will now fail exactly as silently as the original leak did, with no signal for detection/alerting.♻️ Suggested minimal observability addition
} catch { - // Best-effort provider teardown; the retired tab must not be recreated. + // Best-effort provider teardown; the retired tab must not be recreated. + console.warn('[terminal-retirement] Failed to retire provider resource', args) }src/renderer/src/components/terminal/close-local-terminal-tab-state.ts (1)
12-16: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueSimplify optional parameter passing.
Since
state.closeTabaccepts an optionaloptionsobject, you can pass it directly without conditionally checking its properties.♻️ Proposed refactor
- if (options?.reason || options?.remoteCloseOwnedByHost) { - state.closeTab(terminalTabId, options) - } else { - state.closeTab(terminalTabId) - } + state.closeTab(terminalTabId, options)src/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.tsx (1)
65-65: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the unused
closeTabprop.If you apply the fix to use
closeTerminalTabinonPtyExit, thecloseTabprop injected from the store will no longer be needed in this component and can be safely removed.♻️ Proposed refactor
- closeTab: (tabId: string, options?: { reason?: TerminalTabCloseReason }) => void
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: ce911c74-e3dd-4354-84bd-89cc2ef3120a
📒 Files selected for processing (21)
docs/reference/terminal-session-lifecycle.mdpty-exhaustion-agent-session-leak.mdsrc/renderer/src/components/Terminal.tsxsrc/renderer/src/components/floating-terminal/FloatingTerminalPanel.test.tsxsrc/renderer/src/components/floating-terminal/FloatingTerminalPanel.tsxsrc/renderer/src/components/onboarding/OnboardingInlineCommandTerminal.tsxsrc/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.tsxsrc/renderer/src/components/terminal-pane/terminal-parked-watcher-registry.tssrc/renderer/src/components/terminal/close-local-terminal-tab-state.tssrc/renderer/src/components/terminal/terminal-tab-actions.test.tssrc/renderer/src/components/terminal/terminal-tab-actions.tssrc/renderer/src/lib/agent-background-draft-delivery.tssrc/renderer/src/lib/launch-agent-background-session.test.tssrc/renderer/src/lib/launch-agent-background-session.tssrc/renderer/src/lib/launch-worktree-background-terminals.test.tssrc/renderer/src/lib/launch-worktree-background-terminals.tssrc/renderer/src/lib/retire-unowned-background-terminal.tssrc/renderer/src/store/slices/terminal-tab-retirement-store.test.tssrc/renderer/src/store/slices/terminal-tab-retirement.test.tssrc/renderer/src/store/slices/terminal-tab-retirement.tssrc/renderer/src/store/slices/terminals.ts
| return | ||
| } | ||
| closeTab(terminalTabId) | ||
| closeTab(terminalTabId, { reason: 'pty-exit' }) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win
Use closeTerminalTab to ensure proper remote closure and active tab fallback.
By calling the raw store closeTab directly, this handler bypasses the teardown logic inside closeTerminalTab, skipping remote closure sync for web runtime sessions and active tab fallback selection.
To ensure consistent teardown across the application, replace closeTab with closeTerminalTab (which is already imported and used below in onCloseTab).
🐛 Proposed fix
- closeTab(terminalTabId, { reason: 'pty-exit' })
+ closeTerminalTab(terminalTabId, { reason: 'pty-exit' })📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| closeTab(terminalTabId, { reason: 'pty-exit' }) | |
| closeTerminalTab(terminalTabId, { reason: 'pty-exit' }) |
| if ( | ||
| await retireUnownedTerminal({ | ||
| tabId: tab.id, | ||
| ptyId, | ||
| runtimeTarget: { kind: 'local' } | ||
| }) | ||
| ) { | ||
| throw new Error('The terminal tab was closed before its session finished starting.') | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Guard the setup-tab launch paths against retirement failures. The new throw in createBackgroundTab is only handled inside the defaultLaunches loop; the shouldSplitSetup primary-tab fallback and the args.setup fallback/final createBackgroundTab call still await it directly, so a closed tab can now reject the whole launchWorktreeBackgroundTerminals flow. Wrap those call sites the same way as the loop or return early on a null tab.
| for (const terminal of retirementPlan.runtimeTerminals) { | ||
| const environmentId = terminal.environmentId ?? fallbackRuntimeEnvironmentId | ||
| retirementTasks.push( | ||
| callRuntimeRpc( | ||
| environmentId ? { kind: 'environment', environmentId } : { kind: 'local' }, | ||
| 'terminal.close', | ||
| { terminal: terminal.handle } | ||
| ) | ||
| ) | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Missing timeout on terminal.close RPC.
Every other callRuntimeRpc call in this file passes { timeoutMs: 15_000 } (terminal.stop, terminal.stopExact). This new terminal.close call omits it, so a hung/unresponsive runtime environment leaves the retirement promise unresolved forever — the Promise.allSettled warning callback will never fire, and the fire-and-forget teardown task leaks silently.
🔧 Proposed fix
retirementTasks.push(
callRuntimeRpc(
environmentId ? { kind: 'environment', environmentId } : { kind: 'local' },
'terminal.close',
- { terminal: terminal.handle }
+ { terminal: terminal.handle },
+ { timeoutMs: 15_000 }
)
)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| for (const terminal of retirementPlan.runtimeTerminals) { | |
| const environmentId = terminal.environmentId ?? fallbackRuntimeEnvironmentId | |
| retirementTasks.push( | |
| callRuntimeRpc( | |
| environmentId ? { kind: 'environment', environmentId } : { kind: 'local' }, | |
| 'terminal.close', | |
| { terminal: terminal.handle } | |
| ) | |
| ) | |
| } | |
| for (const terminal of retirementPlan.runtimeTerminals) { | |
| const environmentId = terminal.environmentId ?? fallbackRuntimeEnvironmentId | |
| retirementTasks.push( | |
| callRuntimeRpc( | |
| environmentId ? { kind: 'environment', environmentId } : { kind: 'local' }, | |
| 'terminal.close', | |
| { terminal: terminal.handle }, | |
| { timeoutMs: 15_000 } | |
| ) | |
| ) | |
| } |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/renderer/src/components/terminal/close-local-terminal-tab-state.ts (1)
16-39: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winUse
closeUnifiedTabfor unified terminals here
closeTabdoesn’t clearunifiedTabsByWorktree, so this path can leave a stale unified-tab entry behind.
♻️ Duplicate comments (1)
src/renderer/src/store/slices/terminals.ts (1)
1225-1244: 🩺 Stability & Availability | 🟠 MajorMissing timeout on
terminal.closeRPC (unresolved from prior review).Every other
callRuntimeRpccall in this file passes{ timeoutMs: 15_000 }(terminal.stop,terminal.stopExact). Thisterminal.closecall still omits it, so a hung/unresponsive remote runtime environment leaves the retirement promise unresolved forever — thePromise.allSettledwarning callback never fires and the fire-and-forget teardown task leaks silently.🔧 Proposed fix
retirementTasks.push( callRuntimeRpc( environmentId ? { kind: 'environment', environmentId } : { kind: 'local' }, 'terminal.close', - { terminal: terminal.handle } + { terminal: terminal.handle }, + { timeoutMs: 15_000 } ) )
🧹 Nitpick comments (2)
config/reliability-gates.jsonc (1)
499-513: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winProvider naming inconsistent with the rest of the manifest.
This new gate uses
"runtime"inproviders/coveredProviders. Every other gate in this file (terminal-session.kill-all-surface-cleanup,terminal-input.guarded-agent-send-authorization,terminal-input.agent-prompt-injection, etc.) spells this provider"remote-runtime". If any tooling validates these arrays against a canonical provider enum,"runtime"won't match.📝 Proposed fix
"providers": [ "local", "daemon", "ssh", - "runtime" + "remote-runtime" ],and the matching
coveredProvidersentry at line 512.src/renderer/src/store/slices/agent-status.ts (1)
882-901: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winPreserve reference identity when nothing is being retired.
boundRecentlyRetiredAgentStatusPaneKeysalways allocates a fresh object, even whenpaneKeysis empty (the common case — most tab closes retire zero pane aliases). This is called unconditionally fromdropAgentStatusByTabPrefixon every tab close, sorecentlyRetiredAgentStatusPaneKeysgets a new reference every time regardless of whether anything changed — the exact pattern this file otherwise guards against everywhere else (removePaneKeys,movePaneKeyedRecord, and the explicit "skip writing X when the reference is unchanged" comments throughoutcloseTab/dropAgentStatus*).♻️ Proposed fix
function boundRecentlyRetiredAgentStatusPaneKeys( existing: Record<string, true>, paneKeys: readonly string[] ): Record<string, true> { + if (paneKeys.length === 0) { + return existing + } const additions = new Set(paneKeys)
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 22b8ac5b-74ec-47a2-a915-1a32aab04eb1
📒 Files selected for processing (35)
config/reliability-gates.jsoncdocs/reference/terminal-session-lifecycle.mdsrc/main/agent-hooks/server-pane-authority.test.tssrc/main/agent-hooks/server.tssrc/main/ipc/agent-hooks.test.tssrc/main/ipc/agent-hooks.tssrc/main/ipc/agent-pane-authority-ipc.tssrc/main/ipc/pty-management.test.tssrc/main/ipc/pty-management.tssrc/main/persistence.test.tssrc/main/persistence.tssrc/preload/api-types.tssrc/preload/index.tssrc/renderer/src/components/shared/kill-all-terminal-surfaces.test.tssrc/renderer/src/components/shared/kill-all-terminal-surfaces.tssrc/renderer/src/components/terminal-pane/pty-connection.test.tssrc/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.tssrc/renderer/src/components/terminal/close-local-terminal-tab-state.tssrc/renderer/src/components/terminal/terminal-tab-actions-kill-all.test.tssrc/renderer/src/components/terminal/terminal-tab-actions.test.tssrc/renderer/src/components/terminal/terminal-tab-actions.tssrc/renderer/src/hooks/useIpcEvents.tssrc/renderer/src/store/slices/agent-pane-authority.test.tssrc/renderer/src/store/slices/agent-pane-authority.tssrc/renderer/src/store/slices/agent-status.tssrc/renderer/src/store/slices/tabs.tssrc/renderer/src/store/slices/terminal-pane-detach-agent-identity.test.tssrc/renderer/src/store/slices/terminal-tab-retirement-store.test.tssrc/renderer/src/store/slices/terminal-tab-retirement.test.tssrc/renderer/src/store/slices/terminal-tab-retirement.tssrc/renderer/src/store/slices/terminals.tssrc/renderer/src/web/web-preload-api.tssrc/shared/agent-hook-listener.tssrc/shared/types.tstests/e2e/terminal-parked-close-retirement.spec.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- src/renderer/src/store/slices/terminal-tab-retirement-store.test.ts
- docs/reference/terminal-session-lifecycle.md
- src/renderer/src/store/slices/terminal-tab-retirement.ts
- src/renderer/src/components/terminal/terminal-tab-actions.ts
| const reportedTabId = | ||
| event.tabId !== undefined && event.tabId.trim().length > 0 ? event.tabId.trim() : undefined | ||
| if (tabId !== undefined && tabId !== parsedPaneKey.tabId) { | ||
| if ( | ||
| paneKey === physicalPaneKey && | ||
| reportedTabId !== undefined && | ||
| reportedTabId !== parsedPaneKey.tabId | ||
| ) { | ||
| return | ||
| } | ||
| const tabId = paneKey !== physicalPaneKey ? parsedPaneKey.tabId : reportedTabId |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Find callers of ingestTerminalStatus / ingestRemote to check whether tabId
# is always supplied.
rg -n -B2 -A6 '\.ingestTerminalStatus\(' --type=ts -g '!**/*.test.ts'
rg -n -B2 -A10 '\.ingestRemote\(' --type=ts -g '!**/*.test.ts'Repository: stablyai/orca
Length of output: 151
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Locate the relevant function definitions and all call sites.
rg -n -B4 -A12 'function ingestTerminalStatus|const ingestTerminalStatus|ingestTerminalStatus\s*=' src/main/agent-hooks/server.ts
rg -n -B4 -A12 'function ingestRemote|const ingestRemote|ingestRemote\s*=' src/main/agent-hooks/server.ts
# Find call sites across the repo.
rg -n -B3 -A8 '\.ingestTerminalStatus\(' src
rg -n -B3 -A10 '\.ingestRemote\(' src
# Find any obvious envelope/tabId shaping near callers.
rg -n -B3 -A8 'tabId\s*:' src/main src/renderer src/sharedRepository: stablyai/orca
Length of output: 151
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Map the relevant files and inspect the function definitions/call sites.
git ls-files 'src/main/agent-hooks/*' 'src/**/*pty*' 'src/**/*terminal*' | sed -n '1,200p'
echo '--- server.ts matches ---'
rg -n -B3 -A10 'ingestTerminalStatus|ingestRemote|tabId\s*:' src/main/agent-hooks/server.ts
echo '--- repo call sites ---'
rg -n -B3 -A8 'ingestTerminalStatus\s*\(' src
rg -n -B3 -A8 'ingestRemote\s*\(' src
echo '--- pty/terminal callers mentioning event.tabId or envelope.tabId ---'
rg -n -B3 -A8 'event\.tabId|envelope\.tabId|tabId\s*:' src/main src/sharedRepository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the relevant regions in server.ts.
sed -n '1125,1295p' src/main/agent-hooks/server.ts
echo '--- usages inside server.ts ---'
rg -n -B4 -A8 'ingestTerminalStatus|ingestRemote' src/main/agent-hooks/server.ts
echo '--- repo-wide callsites ---'
rg -n -B3 -A10 'this\.ingestTerminalStatus\(|ingestTerminalStatus\(' src/main src/shared
rg -n -B3 -A10 'this\.ingestRemote\(|ingestRemote\(' src/main src/shared
echo '--- caller shapes likely relevant to tabId ---'
rg -n -B3 -A10 'event\.tabId|envelope\.tabId|tabId:\s*undefined|tabId\s*\?' src/main src/sharedRepository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the event type/source for terminal agent status and remote envelopes.
rg -n -B4 -A16 'onTerminalAgentStatus|TerminalAgentStatus|type .*AgentStatus|interface .*AgentStatus|AgentStatusPayload|normalizeHookPayload|readStringField' src/main src/shared
echo '--- main index hook wiring ---'
sed -n '1760,1820p' src/main/index.ts
echo '--- agent hook server tests around omitted tabId cases ---'
rg -n -B3 -A8 "tabId: undefined|tabId\\s*\\?\\:" src/main/agent-hooks/server.test.ts src/main/persistence.test.ts src/main/agent-hooks/*.test.tsRepository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Find where terminal agent status events are produced and whether tabId is included.
rg -n -B4 -A16 'onTerminalAgentStatus|terminalAgentStatus|emit.*AgentStatus|agent status' src/main/runtime src/main/index.ts src/main/agent-hooks/server.ts
echo '--- runtime file around agent status emission ---'
rg -n 'onTerminalAgentStatus|agentStatus' src/main/runtime/orca-runtime.ts src/main/runtime/**/*.ts
# Narrow inspection around likely emitter sites if found.
sed -n '1,260p' src/main/runtime/orca-runtime.ts | tail -n 120Repository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the emitter to determine whether tabId is always present on the event.
sed -n '6379,6445p' src/main/runtime/orca-runtime.ts
echo '--- event type definition ---'
rg -n -B3 -A8 'type RuntimeTerminalAgentStatusEvent|interface RuntimeTerminalAgentStatusEvent' src/main/runtime/orca-runtime.ts src/main/runtime/**/*.tsRepository: stablyai/orca
Length of output: 2655
Preserve derived tabId on the non-aliased path
tabId can be undefined here, because runtime agent-status events make it optional. Fall back to parsedPaneKey.tabId when reportedTabId is missing, and keep the mismatch return only for explicit conflicts.
src/main/agent-hooks/server.ts:1165-1174, 1275-1286
| let remainingOriginalCount = initialCount | ||
| let remainingOriginalIds = initialIds | ||
| for (let attempt = 0; attempt < MAX_POLL_ATTEMPTS; attempt += 1) { | ||
| await sleep(POLL_INTERVAL_MS) | ||
| const current = await collectSessions(adapters) | ||
| remainingOriginalCount = current.reduce( | ||
| (count, s) => (initialIds.has(s.sessionId) ? count + 1 : count), | ||
| 0 | ||
| remainingOriginalIds = new Set( | ||
| current | ||
| .filter((session) => initialIds.has(session.sessionId)) | ||
| .map((session) => session.sessionId) | ||
| ) | ||
| remainingOriginalCount = remainingOriginalIds.size | ||
| if (remainingOriginalCount === 0) { | ||
| break | ||
| } | ||
| } | ||
|
|
||
| const killedCount = initialCount - remainingOriginalCount | ||
| return { killedCount, remainingCount: remainingOriginalCount } | ||
| return { | ||
| killedCount, | ||
| remainingCount: remainingOriginalCount, | ||
| killedSessionIds: [...initialIds].filter( | ||
| (sessionId) => !remainingOriginalIds.has(sessionId) | ||
| ) | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Confirm collectSessions' failure-swallowing behavior and whether any
# adapter-level retry/backoff exists that would mitigate transient drops.
rg -n -B3 -A15 'async function collectSessions' src/main/ipc/pty-management.tsRepository: stablyai/orca
Length of output: 885
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the kill-all flow and downstream use of killedSessionIds.
rg -n -B4 -A20 'killedSessionIds|kill-all-terminal-surfaces|killPty|daemonKilledSessionIds' src/main src -g '!**/dist/**'
# Read the relevant files/sections with line numbers.
for f in src/main/ipc/pty-management.ts src/main/kill-all-terminal-surfaces.ts; do
if [ -f "$f" ]; then
echo "\n### $f"
wc -l "$f"
sed -n '1,260p' "$f" | cat -n
fi
doneRepository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Check whether the daemon kill-all tests exercise listSessions failures and
# whether any failure-aware bookkeeping exists in pty-management.ts.
rg -n -A20 -B5 'listSessions.*reject|reject.*listSessions|collectSessions\(|Promise.allSettled' src/main/ipc/pty-management.test.ts src/main/ipc/pty-management.tsRepository: stablyai/orca
Length of output: 13036
Transient adapter failures can misreport live sessions as killed. collectSessions() drops any adapter whose listSessions() rejects, so a single poll can erase still-running IDs from remainingOriginalIds. That can produce a false killedSessionIds set, and kill-all-terminal-surfaces.ts will then skip the exact killPty() retry for those PTYs. Carry adapter failures through the poll result, or only treat an ID as dead when its adapter responded in that iteration.
There was a problem hiding this comment.
🧹 Nitpick comments (2)
src/renderer/src/components/Terminal.tsx (1)
1367-1377: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract shared helper for paired-host-aware bulk-close routing. All three sites implement the identical decision — terminal contentType closes via
closeTerminalTab(entityId), other content types close viacloseWebRuntimeSessionTab— copy-pasted with only comment wording differing. A shared helper (e.g.closeUnifiedItemForBulkClose(state, item, runtimeEnvironmentId)) would keep this paired-host bulk-close contract consistent as it evolves instead of requiring synchronized edits in three places.
src/renderer/src/components/Terminal.tsx#L1367-L1377: replace this branch with a call to the shared helper.src/renderer/src/components/Terminal.tsx#L1432-L1442: replace this branch with a call to the shared helper.src/renderer/src/components/tab-group/useTabGroupWorkspaceModel.ts#L316-L321: replace this branch with a call to the shared helper.src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts (1)
456-465: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winTrim now-unused parameters from
shouldDetachPaneTransportOnUnmount.
tabStillExistsandworktreeTabs(andtabId) are no longer read by the function body — the implementation is justBoolean(args.ptyId). Keeping them in the signature suggests tab-existence/shared-ownership are still considered here, when that responsibility has moved to the retirement planner. Simplifying the signature to{ ptyId: string | null }would make the current (correct) contract explicit and prevent future confusion.♻️ Proposed signature simplification
-export function shouldDetachPaneTransportOnUnmount(args: { - tabStillExists: boolean - tabId: string - ptyId: string | null - worktreeTabs: readonly TerminalTab[] | undefined -}): boolean { +export function shouldDetachPaneTransportOnUnmount(args: { ptyId: string | null }): boolean { // Why: mounted transport teardown is renderer-only; closeTab or the pane-close // action already owns provider shutdown. Destroy only pending, ID-less spawns. return Boolean(args.ptyId) }#!/bin/bash rg -n -B2 -A8 'shouldDetachPaneTransportOnUnmount\(' src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: b97768bd-0a00-49e3-b7b2-fe3ca34167a7
📒 Files selected for processing (24)
config/reliability-gates.jsoncsrc/main/agent-hooks/server-pane-authority.test.tssrc/main/agent-hooks/server.tssrc/main/ipc/agent-hooks.test.tssrc/main/ipc/agent-hooks.tssrc/main/ipc/agent-pane-authority-ipc.tssrc/main/ipc/agent-pane-authority-ownership.test.tssrc/main/ipc/agent-pane-authority-ownership.tssrc/main/ipc/agent-status-ipc-boundary.tssrc/main/ipc/register-core-handlers.test.tssrc/main/ipc/register-core-handlers.tssrc/renderer/src/components/Terminal.tsxsrc/renderer/src/components/shared/kill-all-terminal-surfaces.test.tssrc/renderer/src/components/shared/kill-all-terminal-surfaces.tssrc/renderer/src/components/tab-group/useTabGroupWorkspaceModel.focus.test.tssrc/renderer/src/components/tab-group/useTabGroupWorkspaceModel.tssrc/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.tssrc/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.tssrc/renderer/src/components/terminal/close-local-terminal-tab-state.tssrc/renderer/src/components/terminal/terminal-close-target.tssrc/renderer/src/components/terminal/terminal-tab-actions.tssrc/renderer/src/store/slices/terminal-tab-retirement.test.tssrc/renderer/src/store/slices/terminal-tab-retirement.tssrc/renderer/src/store/slices/terminals.ts
🚧 Files skipped from review as they are similar to previous changes (9)
- src/renderer/src/components/terminal/close-local-terminal-tab-state.ts
- src/main/ipc/agent-hooks.test.ts
- config/reliability-gates.jsonc
- src/renderer/src/store/slices/terminal-tab-retirement.test.ts
- src/renderer/src/components/shared/kill-all-terminal-surfaces.ts
- src/renderer/src/components/terminal/terminal-tab-actions.ts
- src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts
- src/main/agent-hooks/server.ts
- src/renderer/src/store/slices/terminals.ts
|
Windows validation — ACTIONABLE FINDINGS
Verdict: ACTIONABLE FINDINGS (not CLEAN). Fix the POSIX test assumptions and E2E argument/path handling, then rerun Windows validation. |
|
Windows rerun requested at exact SHA This head addresses every actionable item from the prior Windows run:
Please rerun the same Node 24 focused suite and:
Please report the exact full SHA, command results, whether the native ConPTY test reached and passed the exact parked-PTY disappearance assertion, and final |
|
@coderabbitai review |
✅ Action performedReview finished.
|
|
Windows validation — ACTIONABLE FINDINGS Exact target
Environment
Command results
Electron / native Windows ConPTY lifecycle evidence
Final git status --short: empty Verdict: ACTIONABLE FINDINGS |
|
Windows follow-up requested at exact SHA The only change since the clean native ConPTY run is the reported unit-test harness correction: the simulated Linux expected shim path now uses Please rerun at minimum:
Confirm the full exact SHA, passing test count, empty |
|
Windows follow-up — ACTIONABLE FINDINGS
First useful stack: Classification: test-harness portability failure; no new product or Electron lifecycle failure was exercised. The latest change updates the assertion's expected shim path to posix.join, but the mocked ensureLinuxTerminalOrcaCliShimDir at src/main/ipc/pty.test.ts:174–176 still returns host node:path.join. The code under test also retains the node:path delimiter imported on the Windows host. Overriding process.platform to 'linux' does not switch Node's path implementation, so the simulated Linux PATH still mixes Windows-host and POSIX path dialects. Final git status --short: empty Verdict: ACTIONABLE FINDINGS (not CLEAN) |
|
Windows final targeted rerun requested at exact SHA The simulated Linux test now keeps its synthetic PATH, split delimiter, expected shim path, and mocked shim path on the same host Please rerun:
Report the full SHA, counts, empty |
|
Windows targeted PTY follow-up — CLEAN
Verdict: CLEAN |
…into background run tabs Automation dispatch created the hidden run tab (and persisted its layout) before the agent PTY spawn resolved. When the target worktree was already mounted — the common case for existing-workspace automations — Terminal.tsx mounted a TerminalPane for the new empty tab immediately, and its fresh-spawn path bound a default shell to the run tab. The agent PTY then lost the binding race and kept running detached, so 'View run' opened a blank shell prompt while the agent was only reachable from the sessions list. Mirror the CLI terminal path instead: spawn the PTY first against a pre-allocated tab id, then create the inactive tab with initialPtyId and bind the layout in one synchronous block, leaving no window for the fresh-spawn race. Rebased onto stablyai#8628's session retirement work. Its retireUnownedTerminal guard does not apply once the tab is created after the spawn — the tab cannot be closed mid-spawn because it does not exist yet, so the check would retire every launch. The invariant it protects still holds here: the worktree can disappear across the spawn await, so the launch now retires the provider terminal and skips tab adoption in that case, and its two regression tests were rebuilt around that trigger. Fixes stablyai#2989 Co-Authored-By: Claude Fable 5 <[email protected]>
* fix(terminal): retire sessions when tabs close * fix(terminal): close remaining session lifecycle gaps * fix(terminal): close review-discovered lifecycle gaps * fix(terminal): revalidate bulk session retirement * fix(terminal): harden retirement review edges * fix(agent): reverify restored pane authority * test: make terminal retirement gate portable on Windows * test: use POSIX join in Linux PATH assertion * test: keep simulated Linux PATH host-consistent
Summary
Closing a terminal tab now permanently retires every exclusively owned terminal session and agent-resume record, even when the tab is cold-parked and has no mounted React pane.
This fixes a P0 PTY-exhaustion regression where closing parked agent tabs forgot their PTY IDs without terminating the persistent daemon, SSH, or runtime session, and later resume capture could resurrect deliberately closed agents in bulk.
The change:
pty.kill, ordinary runtime handles throughterminal.close, and paired web tabs through host tab ownership;pty-exitreconciliation;Screenshots
No visual change.
Testing
pnpm lintpnpm typecheckpnpm run test:e2e -- tests/e2e/terminal-parked-close-retirement.spec.ts --workers=1— 1/1 passed on the final review-fix code; three local passes total51334b3fa10f105ba24b4d3a2f3c4005636830da: exact PTY listed before close, preserved while parked, removed after close, and no test Electron/daemon process leaked; later commits are test-harness-onlye3a9791f3805a1a2b0c7dac5bcb80f2d0d09beff: 273 passed, 12 skipped, clean worktreeFocused regression coverage includes active and parked tabs, split PTY unions, all six ownership sources, shared-owner snapshot preservation, disconnected/deferred SSH IDs, ordinary and paired runtime ownership, malformed runtime IDs, duplicate close, provider rejection, natural exit, resume-record cleanup, local/SSH/runtime late spawns, late setup splits, pane detach chains, restart alias re-verification, pre-mutation close failure, yield-time survivor creation/move, canonical runtime alias dedupe, and a real 100-tab Zustand fixture.
AI Review Report
Multiple independent read-only review waves audited the design and implementation for lifecycle architecture, provider ownership, renderer/main trust boundaries, async races, bulk-close reliability, cross-platform behavior, and test quality.
Review findings materially changed the implementation:
Final confirmation verdicts:
8dd2da0647e15189f5b4507457a06bfd8227d4ed: CLEAN, 695/695 focused tests;No reviewer modified files.
Cross-platform scope
The implementation uses existing provider abstractions for macOS/Linux local PTYs, Windows ConPTY/WSL, SSH app-scoped IDs, disconnected relay state, and runtime terminals. No platform-specific paths, shortcuts, shell interpolation, or POSIX-only reliability commands were added.
Live macOS and native Windows 11/ConPTY Electron evidence proves exact parked-session disappearance. Linux Wayland CI and focused WSL routing tests are green. Live WSL and live SSH process-absence evidence remain explicitly conditional; deterministic unit/main tests cover their routing and ownership contracts.
Security Audit
remote:IDs fail closed in the renderer and main process and never reach localpty.killprovider routing.Notes
/usr/local/bin/orca-dev; Electron/desktop/web build outputs and the regression gate complete without that install.