Skip to content

fix(terminal): retire sessions when tabs close - #8628

Merged
brennanb2025 merged 9 commits into
mainfrom
brennanb2025/pty-exhaustion-session-leak
Jul 14, 2026
Merged

brennanb2025 merged 9 commits into
mainfrom
brennanb2025/pty-exhaustion-session-leak

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • plans retirement from all six tab ownership sources before state deletion;
  • routes local, daemon, WSL, and SSH IDs through pty.kill, ordinary runtime handles through terminal.close, and paired web tabs through host tab ownership;
  • preserves PTYs and pending snapshots still referenced by another live terminal surface;
  • distinguishes explicit user/cleanup retirement from natural pty-exit reconciliation;
  • revokes tab- and pane-scoped agent resume authority, reconnect state, and parked observers on explicit close while preserving detach, park, sleep, and reload semantics;
  • closes local, SSH, and runtime sessions whose asynchronous background spawn resolves after its owner was closed;
  • routes unified-only and bulk tab actions through the same destructive lifecycle boundary;
  • revalidates remaining ownership after bulk-close yields so newly created, moved, or detached survivors cannot be killed from stale plans;
  • keeps failed pre-mutation closes as live non-target owners and deduplicates provider teardown across runtime aliases and replans;
  • requires positively verified PTY ownership for first pane-authority transfer, does not persist trust across restart, and safely re-verifies restored aliases on reattach;
  • rejects malformed/runtime-prefixed IDs at the main PTY-kill boundary before local provider fallback;
  • documents the lifecycle contract, regression history, open-source prior art, and bounded follow-ups.

Screenshots

No visual change.

Testing

  • pnpm lint
  • pnpm typecheck
  • Full supported-runtime suite under Node 24: 2,775 files passed, 7 skipped; 29,344 tests passed, 40 skipped
  • Registered reliability manifest: 40 gates passed
  • Max-lines ratchet passed with no new bypasses
  • Fresh-build Electron regression gate: pnpm 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 total
  • Native Windows 11/ConPTY regression gate at 51334b3fa10f105ba24b4d3a2f3c4005636830da: exact PTY listed before close, preserved while parked, removed after close, and no test Electron/daemon process leaked; later commits are test-harness-only
  • Native Windows Node 24 PTY suite on exact final SHA e3a9791f3805a1a2b0c7dac5bcb80f2d0d09beff: 273 passed, 12 skipped, clean worktree
  • Focused main/renderer lifecycle, authority, provider, persistence, and bulk-close suites passed, including full PTY and hook-server files
  • Desktop/web/E2E builds passed; no UI asset or native ABI change

Focused 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:

  • expanded retirement ownership from three sources to six;
  • separated runtime and paired-host teardown from local PTY kill;
  • protected shared PTYs and their cold-restore/snapshot state;
  • separated natural exit from explicit retirement;
  • closed direct background-spawn races;
  • added pane-scoped retirement and late-event tombstones;
  • added yield-time ownership replanning, failure-safe sibling accounting, and canonical teardown reservation;
  • made first pane-authority transfer require live ownership proof, bounded IPC inputs, non-persisted authority provenance, restart re-verification, and verified-alias preference;
  • made the Electron reliability command shell-neutral and corrected its evidence and complexity claims.

Final confirmation verdicts:

  • lifecycle lane: CLEAN, 58/58 focused tests;
  • security lane at exact HEAD 8dd2da0647e15189f5b4507457a06bfd8227d4ed: CLEAN, 695/695 focused tests;
  • restart/reliability lane at exact HEAD: CLEAN, 394 authority/persistence tests plus 230 full hook-server 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

  • No new command construction, credentials, dependencies, auth flows, filesystem paths, or user-controlled executable arguments are introduced.
  • Malformed remote: IDs fail closed in the renderer and main process and never reach local pty.kill provider routing.
  • Pane-authority IPC validates bounded pane/PTY identifiers and requires authoritative physical or current-owner PTY proof before minting transferable authority.
  • Authority proof is process-local and is not trusted merely because an alias was restored from disk.
  • Logs contain tab identifiers and aggregate failure counts, not commands, provider credentials, environment variables, or secrets.
  • Explicit close removes resume authority, reducing unattended privileged-agent resurrection after a user closes a tab.

Notes

  • Intentional worktree sleep, renderer reload, tab parking, pane detach/move, and warm app reattach preserve their documented sessions.
  • Provider shutdown remains best-effort when an SSH or runtime host is disconnected. Durable relay kill-on-reconnect and daemon ownership leases remain bounded follow-ups.
  • The local CLI install step in the full packaging build may require elevated permission to replace /usr/local/bin/orca-dev; Electron/desktop/web build outputs and the regression gate complete without that install.
  • X/Twitter: @brennanb2025

@coderabbitai

coderabbitai Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

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

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.79% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title is concise and accurately summarizes the main change: retiring terminal sessions when tabs close.
Description check ✅ Passed The description follows the required template and includes complete Summary, Screenshots, Testing, AI Review Report, Security Audit, and Notes sections.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (4)
pty-exhaustion-agent-session-leak.md (1)

164-164: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Add rollback instructions for the PTY limit tweak.

kern.tty.ptmx_max=999 is the macOS ceiling, so this only buys temporary headroom. Document how to revert the sysctl and remove any persistent /etc/sysctl.conf override.

src/renderer/src/lib/retire-unowned-background-terminal.ts (1)

22-38: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Silent best-effort teardown hides future leaks.

The catch block swallows every failure from terminal.close/pty.kill with 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 value

Simplify optional parameter passing.

Since state.closeTab accepts an optional options object, 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 value

Remove the unused closeTab prop.

If you apply the fix to use closeTerminalTab in onPtyExit, the closeTab prop 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

📥 Commits

Reviewing files that changed from the base of the PR and between 83588b4 and 097708b.

📒 Files selected for processing (21)
  • docs/reference/terminal-session-lifecycle.md
  • pty-exhaustion-agent-session-leak.md
  • src/renderer/src/components/Terminal.tsx
  • src/renderer/src/components/floating-terminal/FloatingTerminalPanel.test.tsx
  • src/renderer/src/components/floating-terminal/FloatingTerminalPanel.tsx
  • src/renderer/src/components/onboarding/OnboardingInlineCommandTerminal.tsx
  • src/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.tsx
  • src/renderer/src/components/terminal-pane/terminal-parked-watcher-registry.ts
  • src/renderer/src/components/terminal/close-local-terminal-tab-state.ts
  • src/renderer/src/components/terminal/terminal-tab-actions.test.ts
  • src/renderer/src/components/terminal/terminal-tab-actions.ts
  • src/renderer/src/lib/agent-background-draft-delivery.ts
  • src/renderer/src/lib/launch-agent-background-session.test.ts
  • src/renderer/src/lib/launch-agent-background-session.ts
  • src/renderer/src/lib/launch-worktree-background-terminals.test.ts
  • src/renderer/src/lib/launch-worktree-background-terminals.ts
  • src/renderer/src/lib/retire-unowned-background-terminal.ts
  • src/renderer/src/store/slices/terminal-tab-retirement-store.test.ts
  • src/renderer/src/store/slices/terminal-tab-retirement.test.ts
  • src/renderer/src/store/slices/terminal-tab-retirement.ts
  • src/renderer/src/store/slices/terminals.ts

return
}
closeTab(terminalTabId)
closeTab(terminalTabId, { reason: 'pty-exit' })

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🔴 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.

Suggested change
closeTab(terminalTabId, { reason: 'pty-exit' })
closeTerminalTab(terminalTabId, { reason: 'pty-exit' })

Comment on lines +184 to +192
if (
await retireUnownedTerminal({
tabId: tab.id,
ptyId,
runtimeTarget: { kind: 'local' }
})
) {
throw new Error('The terminal tab was closed before its session finished starting.')
}

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.

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

Comment on lines +1233 to +1242
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 }
)
)
}

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.

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

Suggested change
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 }
)
)
}

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 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 win

Use closeUnifiedTab for unified terminals here
closeTab doesn’t clear unifiedTabsByWorktree, 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 | 🟠 Major

Missing timeout on terminal.close RPC (unresolved from prior review).

Every other callRuntimeRpc call in this file passes { timeoutMs: 15_000 } (terminal.stop, terminal.stopExact). This terminal.close call still omits it, so a hung/unresponsive remote runtime environment leaves the retirement promise unresolved forever — the Promise.allSettled warning 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 win

Provider naming inconsistent with the rest of the manifest.

This new gate uses "runtime" in providers/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 coveredProviders entry at line 512.

src/renderer/src/store/slices/agent-status.ts (1)

882-901: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Preserve reference identity when nothing is being retired.

boundRecentlyRetiredAgentStatusPaneKeys always allocates a fresh object, even when paneKeys is empty (the common case — most tab closes retire zero pane aliases). This is called unconditionally from dropAgentStatusByTabPrefix on every tab close, so recentlyRetiredAgentStatusPaneKeys gets 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 throughout closeTab/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

📥 Commits

Reviewing files that changed from the base of the PR and between 097708b and c47fd1a.

📒 Files selected for processing (35)
  • config/reliability-gates.jsonc
  • docs/reference/terminal-session-lifecycle.md
  • src/main/agent-hooks/server-pane-authority.test.ts
  • src/main/agent-hooks/server.ts
  • src/main/ipc/agent-hooks.test.ts
  • src/main/ipc/agent-hooks.ts
  • src/main/ipc/agent-pane-authority-ipc.ts
  • src/main/ipc/pty-management.test.ts
  • src/main/ipc/pty-management.ts
  • src/main/persistence.test.ts
  • src/main/persistence.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts
  • src/renderer/src/components/shared/kill-all-terminal-surfaces.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts
  • src/renderer/src/components/terminal/close-local-terminal-tab-state.ts
  • src/renderer/src/components/terminal/terminal-tab-actions-kill-all.test.ts
  • src/renderer/src/components/terminal/terminal-tab-actions.test.ts
  • src/renderer/src/components/terminal/terminal-tab-actions.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/store/slices/agent-pane-authority.test.ts
  • src/renderer/src/store/slices/agent-pane-authority.ts
  • src/renderer/src/store/slices/agent-status.ts
  • src/renderer/src/store/slices/tabs.ts
  • src/renderer/src/store/slices/terminal-pane-detach-agent-identity.test.ts
  • src/renderer/src/store/slices/terminal-tab-retirement-store.test.ts
  • src/renderer/src/store/slices/terminal-tab-retirement.test.ts
  • src/renderer/src/store/slices/terminal-tab-retirement.ts
  • src/renderer/src/store/slices/terminals.ts
  • src/renderer/src/web/web-preload-api.ts
  • src/shared/agent-hook-listener.ts
  • src/shared/types.ts
  • tests/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

Comment on lines +1165 to +1174
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 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/shared

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

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

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

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

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

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

Comment on lines 131 to +154
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)
)
}

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.

🗄️ 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.ts

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

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

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
src/renderer/src/components/Terminal.tsx (1)

1367-1377: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract 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 via closeWebRuntimeSessionTab — 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 win

Trim now-unused parameters from shouldDetachPaneTransportOnUnmount.

tabStillExists and worktreeTabs (and tabId) are no longer read by the function body — the implementation is just Boolean(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

📥 Commits

Reviewing files that changed from the base of the PR and between c47fd1a and 3d0b7fd.

📒 Files selected for processing (24)
  • config/reliability-gates.jsonc
  • src/main/agent-hooks/server-pane-authority.test.ts
  • src/main/agent-hooks/server.ts
  • src/main/ipc/agent-hooks.test.ts
  • src/main/ipc/agent-hooks.ts
  • src/main/ipc/agent-pane-authority-ipc.ts
  • src/main/ipc/agent-pane-authority-ownership.test.ts
  • src/main/ipc/agent-pane-authority-ownership.ts
  • src/main/ipc/agent-status-ipc-boundary.ts
  • src/main/ipc/register-core-handlers.test.ts
  • src/main/ipc/register-core-handlers.ts
  • src/renderer/src/components/Terminal.tsx
  • src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts
  • src/renderer/src/components/shared/kill-all-terminal-surfaces.ts
  • src/renderer/src/components/tab-group/useTabGroupWorkspaceModel.focus.test.ts
  • src/renderer/src/components/tab-group/useTabGroupWorkspaceModel.ts
  • src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts
  • src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts
  • src/renderer/src/components/terminal/close-local-terminal-tab-state.ts
  • src/renderer/src/components/terminal/terminal-close-target.ts
  • src/renderer/src/components/terminal/terminal-tab-actions.ts
  • src/renderer/src/store/slices/terminal-tab-retirement.test.ts
  • src/renderer/src/store/slices/terminal-tab-retirement.ts
  • src/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

@OrcaWin

OrcaWin commented Jul 14, 2026

Copy link
Copy Markdown
Collaborator

Windows validation — ACTIONABLE FINDINGS

  • Exact SHA: c8dcb2b
  • Environment: Microsoft Windows 11 Pro 10.0.26200 (build 26200), PowerShell 7.6.3, Node v24.18.0, pnpm 10.24.0
  • pnpm typecheck: exit 0. All 3 configured TypeScript checks passed.
  • pnpm lint: exit 0. 26 warnings, 0 errors; reliability, max-lines, localization catalog, and localization coverage gates passed.
  • Focused Node 24 Vitest: exit 1. Test files: 10 passed, 1 failed (11 total). Tests: 706 passed, 2 failed, 12 skipped (720 total).
    • First useful stack: src/main/ipc/pty.test.ts:1704 — expected shim index 0 to be less than /usr/bin index -1. The Linux-PATH test splits with the native Windows path.delimiter (';'), so '/usr/local/bin:/usr/bin' remains one entry.
    • Second failure: src/main/ipc/pty.test.ts:6756 — expected ORCA_ORIG_ZDOTDIR to equal process.env.HOME (undefined on this Windows host), but received an empty string.
  • Requested pnpm run test:e2e command: exit 1, 0 tests collected. Playwright 1.59 consumed the appended spec path as another value for the variadic '--project electron-headless' option: Project(s) "tests/e2e/terminal-parked-close-retirement.spec.ts" not found.
  • Supplemental corrected invocation using '--project=electron-headless': exit 1. Tests: 0 passed, 1 failed (1 total). It reached Electron, but failed in fixture setup before spawning a PTY: the store did not match the exact Windows repo path within 30s, at tests/e2e/helpers/orca-app.ts:300:5. The UI snapshot showed the repo by name, suggesting Windows path canonicalization/equality in the fixture.
  • WSL: Ubuntu is configured. The focused WSL runtime-routing tests passed.
  • Remote-ID safety: the focused test rejecting 'remote:env-1@@Terminal-1' before unowned local-provider routing passed, and the kill-all surface tests passed. No focused evidence showed a remote runtime ID reaching local PTY kill.
  • Native ConPTY / parked close: not behaviorally validated because the corrected E2E failed during repo fixture setup before terminal creation; therefore the exact parked PTY disappearance assertion was not reached.
  • Final worktree check: HEAD unchanged; git status --short empty.

Verdict: ACTIONABLE FINDINGS (not CLEAN). Fix the POSIX test assumptions and E2E argument/path handling, then rerun Windows validation.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Windows rerun requested at exact SHA 51334b3fa.

This head addresses every actionable item from the prior Windows run:

  • simulated Linux/POSIX tests no longer use host-native PATH/HOME assumptions;
  • the Playwright project flag now uses the portable --project=electron-headless form;
  • Electron repo/worktree setup uses the provider-returned repo ID instead of raw path equality, including restart setup;
  • the restart fixture now polls through the concurrent repo-refresh generation race.

Please rerun the same Node 24 focused suite and:

pnpm run test:e2e -- tests/e2e/terminal-parked-close-retirement.spec.ts --workers=1

Please report the exact full SHA, command results, whether the native ConPTY test reached and passed the exact parked-PTY disappearance assertion, and final git status --short.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@OrcaWin

OrcaWin commented Jul 14, 2026

Copy link
Copy Markdown
Collaborator

Windows validation — ACTIONABLE FINDINGS

Exact target

  • Branch: brennanb2025/pty-exhaustion-session-leak
  • Full SHA: 51334b3
  • Initial and final git status --short: empty

Environment

  • Microsoft Windows 11 Pro 10.0.26200 (build 26200)
  • PowerShell 7.6.3
  • Node v24.18.0
  • pnpm 10.24.0
  • WSL available: Ubuntu

Command results

  1. pnpm typecheck — exit 0; all 3 configured TypeScript projects passed.
  2. pnpm lint — exit 0; 26 warnings, 0 errors. Reliability (40 gates), max-lines ratchet, localization catalog/parity, and localization coverage passed.
  3. Focused Node 24 Vitest suite — exit 1.
    • Files: 10 passed, 1 failed (11 total).
    • Tests: 708 passed, 1 failed, 12 skipped (721 total).
    • Sole failure:
      AssertionError: expected -1 to be greater than or equal to 0
      at src/main/ipc/pty.test.ts:1703:44
    • Classification: test-harness portability failure, not an observed product failure. The test now splits with posix.delimiter but still builds expected shimDir with host node:path.join, producing a Windows-style expected path while the Linux PATH contains a POSIX path. Use posix.join for the expected shim path.
    • All focused WSL runtime-routing tests passed.
    • The runtime-ID guard and kill-surface tests passed: remote:env-1@@Terminal-1 is rejected before local-provider shutdown, and remote runtime IDs do not reach the local PTY-kill API.
  4. pnpm run test:e2e -- tests/e2e/terminal-parked-close-retirement.spec.ts --workers=1 — exit 0.
    • Playwright metadata: passed; no failed test IDs.
    • Explicit collection check: exactly 1 test in 1 file under electron-headless:
      closing a parked terminal tab retires its exact PTY session

Electron / native Windows ConPTY lifecycle evidence

  • The seeded E2E repository was created, loaded by the fixture, and cleaned up.
  • The native Windows Electron app reached terminal creation and bound a local PTY; the long-lived Node child printed its unique ready marker. On the native Windows local PTY provider this is the node-pty ConPTY path.
  • The captured exact PTY ID was present in window.api.pty.listSessions() before close.
  • Parking was observed by the target tab's pane manager disappearing while that same exact PTY ID remained in listSessions().
  • Closing the parked tab through window.__store.getState().closeTab(tabId) caused that exact PTY ID to disappear from listSessions().
  • The tab locator count reached zero after close, confirming removal from the rendered/store-backed tab model.
  • No unhandled teardown error was reported; Playwright exited 0 and .last-run.json reports passed.
  • Post-run process audit found no Electron or terminal-daemon process created by this run. Older unrelated processes discovered by the broad scan predated validation (July 9–12).

Final git status --short: empty

Verdict: ACTIONABLE FINDINGS
The product-level Electron/ConPTY retirement gate is clean. The remaining action is the Windows portability bug in the Linux PATH unit-test expectation at src/main/ipc/pty.test.ts:1700–1703.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Windows follow-up requested at exact SHA 8ecc8ad03.

The only change since the clean native ConPTY run is the reported unit-test harness correction: the simulated Linux expected shim path now uses posix.join as well as posix.delimiter. No product or Electron lifecycle code changed.

Please rerun at minimum:

pnpm dlx node@24 ./node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/ipc/pty.test.ts

Confirm the full exact SHA, passing test count, empty git status --short, and post a final CLEAN verdict if it passes.

@OrcaWin

OrcaWin commented Jul 14, 2026

Copy link
Copy Markdown
Collaborator

Windows follow-up — ACTIONABLE FINDINGS

  • Full SHA tested: 8ecc8ad
  • Command: pnpm dlx node@24 ./node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/ipc/pty.test.ts
  • Exit code: 1
  • Test files: 1 failed (1 total)
  • Tests: 272 passed, 1 failed, 12 skipped (285 total)

First useful stack:
AssertionError: expected -1 to be greater than or equal to 0
at src/main/ipc/pty.test.ts:1703:44

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)

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Windows final targeted rerun requested at exact SHA e3a9791f3.

The simulated Linux test now keeps its synthetic PATH, split delimiter, expected shim path, and mocked shim path on the same host node:path dialect. This is necessary because overriding process.platform does not rebind already-imported node:path; real Linux CI still exercises the POSIX dialect. Product code remains unchanged.

Please rerun:

pnpm dlx node@24 ./node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/ipc/pty.test.ts

Report the full SHA, counts, empty git status --short, and CLEAN if green.

@OrcaWin

OrcaWin commented Jul 14, 2026

Copy link
Copy Markdown
Collaborator

Windows targeted PTY follow-up — CLEAN

  • Full SHA tested: e3a9791
  • Command: pnpm dlx node@24 ./node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/ipc/pty.test.ts
  • Exit code: 0
  • Test files: 1 passed (1 total)
  • Tests: 273 passed, 12 skipped (285 total)
  • Final git status --short: empty

Verdict: CLEAN

@brennanb2025
brennanb2025 merged commit 36cd8a3 into main Jul 14, 2026
4 checks passed
MaxZarev added a commit to MaxZarev/orca that referenced this pull request Jul 21, 2026
…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]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* 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
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.

2 participants