orca icon indicating copy to clipboard operation
orca copied to clipboard

fix(terminal): retire sessions when tabs close

Open brennanb2025 opened this issue 4 months ago • 1 comments

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/runtime sessions, then later resume capture resurrected those 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 session.tabs.close ownership;
  • preserves PTYs still referenced by another live terminal surface;
  • distinguishes explicit user/cleanup retirement from natural pty-exit reconciliation;
  • revokes sleeping-agent records and reconnect/parked-watcher state on explicit close;
  • closes local/SSH/runtime sessions whose asynchronous background spawn resolves after the owning tab was closed;
  • documents the lifecycle contract, regression history, open-source prior art, and bounded follow-ups.

Screenshots

No visual change.

Testing

  • [x] pnpm lint
  • [x] pnpm typecheck
  • [x] pnpm test — full supported-runtime suite under Node 24: 29,316 passed, 42 skipped
  • [x] pnpm build
  • [x] Added or updated high-quality tests that would catch regressions

Focused lifecycle coverage includes active and parked tabs, split PTY unions, all six ownership sources, shared-owner exclusion, 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, and a late setup split spawn.

AI Review Report

Three independent read-only reviewers audited the design and original implementation plan for:

  • lifecycle architecture and destructive-close boundaries;
  • local, daemon, macOS/Linux/Windows/WSL, SSH, disconnected relay, runtime, and paired-web ownership;
  • direct call sites, natural-exit behavior, async spawn races, kill-all idempotency/performance, and regression coverage.

Their findings materially changed the implementation: the retirement union expanded from three to six sources; runtime and host-paired teardown were separated from local PTY kill; shared ownership was excluded; natural exit gained an explicit reason; whole parked-tab state is disposed synchronously; and both direct background launchers gained post-await owner checks.

An exact-PR review loop is being run after opening this PR. Its findings and any resulting fixes will be added here before merge handoff.

Cross-platform review explicitly checked macOS/Linux local PTYs, Windows ConPTY/WSL routing through the existing provider abstraction, SSH app-scoped IDs and disconnected relay behavior, runtime host ownership, path/shortcut neutrality, and Electron renderer/main boundaries. No new platform-specific shell commands, paths, labels, or shortcuts are introduced.

Security Audit

  • No new command construction, shell interpolation, credentials, dependencies, auth flows, filesystem paths, or user-controlled executable arguments are introduced.
  • Provider routing is derived from structured PTY IDs; malformed remote: IDs fail closed and are never passed to local pty.kill.
  • Logs contain tab identifiers and aggregate failure counts, not command contents, resume credentials, provider session IDs, environment variables, or secrets.
  • Explicit close removes resume authority, reducing the risk of unattended privileged agent resumes after a user closes a tab.
  • Remote and SSH teardown remains best-effort when the owning host is disconnected; durable relay kill-on-reconnect and daemon ownership leases remain documented follow-ups.

Notes

  • The branch is rebased on current origin/main.
  • Intentional worktree sleep, renderer reload, tab parking, pane detach/move, and warm app reattach continue to preserve their documented sessions.
  • Origin-aware defensive expiry, exact pane-scoped resume tombstones, disconnected SSH kill-on-reconnect, and daemon ownership leases are follow-ups; they are not required for the explicit tab-close incident fix.
  • The local CLI install step in pnpm build could not replace /usr/local/bin/orca-dev without sudo, but the build continued and completed successfully.
  • X/Twitter: @brennanb2025

brennanb2025 avatar Jul 14 '26 00:07 brennanb2025

📝 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[bot] avatar Jul 14 '26 00:07 coderabbitai[bot]

Windows validation — ACTIONABLE FINDINGS

  • Exact SHA: c8dcb2b6b4e2d7019496f636f880d074d75857f4
  • 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.

OrcaWin avatar Jul 14 '26 03:07 OrcaWin

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 avatar Jul 14 '26 05:07 brennanb2025

@coderabbitai review

brennanb2025 avatar Jul 14 '26 05:07 brennanb2025

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

coderabbitai[bot] avatar Jul 14 '26 05:07 coderabbitai[bot]

Windows validation — ACTIONABLE FINDINGS

Exact target

  • Branch: brennanb2025/pty-exhaustion-session-leak
  • Full SHA: 51334b3fa10f105ba24b4d3a2f3c4005636830da
  • 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.

OrcaWin avatar Jul 14 '26 06:07 OrcaWin

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.

brennanb2025 avatar Jul 14 '26 06:07 brennanb2025

Windows follow-up — ACTIONABLE FINDINGS

  • Full SHA tested: 8ecc8ad0363871b696323236f4d54129ce08f8b8
  • 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)

OrcaWin avatar Jul 14 '26 06:07 OrcaWin

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.

brennanb2025 avatar Jul 14 '26 06:07 brennanb2025

Windows targeted PTY follow-up — CLEAN

  • Full SHA tested: e3a9791f3805a1a2b0c7dac5bcb80f2d0d09beff
  • 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

OrcaWin avatar Jul 14 '26 06:07 OrcaWin