Skip to content

fix(terminal): apply the running-process close confirmation to every tab close path (#10142) - #12272

Merged
nwparker merged 6 commits into
mainfrom
nwparker/fix-10142-tab-close-confirm-all-paths
Aug 4, 2026
Merged

nwparker merged 6 commits into
mainfrom
nwparker/fix-10142-tab-close-confirm-all-paths

Conversation

@nwparker

@nwparker nwparker commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Description

closeTerminalTab() guarded only pinned tabs — it never probed for running child processes. The running-process confirmation ("Stop running command?") lived exclusively in the pane-level keyboard path (TerminalPane.handleRequestClosePane → inspectRuntimeTerminalProcess), which only Cmd+W / Ctrl+W reached.

Every mouse path bypassed it entirely:

  • Tab X button → SortableTab onClick → onClose → handleCloseTab → closeTerminalTab(tabId)
  • Middle-click → SortableTab onAuxClick → same chokepoint

So Cmd+W on a tab running npm run dev asked first, but clicking the X on the same tab killed it silently.

This PR moves the decision into closeTerminalTab itself, so every interactive close path — X button, middle-click, tab context menu, tab groups, floating panel — inherits the exact same confirmation, with no per-call-site duplication.

  • running-terminal-close-guard.ts (new) — shouldConfirmRunningTerminalClose() decides whether a close is an interactive user close (excludes force, rejectPinned, reason: 'cleanup' | 'pty-exit', hostCloseReason: 'pty-exit', lifecyclePtyId), and guardRunningTerminalClose() probes the tab's live PTYs and either closes or raises the dialog.
  • running-terminal-close-confirm.ts (new) — standalone zustand store mirroring pinned-tab-close-confirm's semantics (single visible request, FIFO queue, 350 ms double-activation guard, dedupe by tab id).
  • RunningTerminalCloseDialog.tsx (new, mounted once in App.tsx) — renders the existing CloseTerminalDialog. Zero new user-visible strings, so no i18n keys and no locale-catalog churn; wording and styling are byte-identical to what Cmd+W already showed, which is the whole point of the issue.
  • The guard sits after the pinned block and before the web-runtime branch, so paired/remote host-backed tabs are covered too. Pinned still wins (one dialog, never two).
  • TerminalPane's last-pane close now delegates to closeTerminalTab instead of running its own probe — that removes a duplicate inspectProcess round trip and makes a double prompt structurally impossible.
  • Every caller that cannot wait on a modal is explicitly opted out via skipRunningProcessConfirm: CLI/RPC close (useIpcEvents), the CLI pane-close fallback, and the paired-runtime bulk closes.
  • Drive-by: useTabGroupWorkspaceModel moved leaveWorktreeIfEmpty() into onClosed — it was already wrong for the deferred pinned path.

Fixes #10142

ELI5

Imagine you have a terminal running a long job. If you pressed Cmd+W to close it, Orca asked "hey, something's still running — really close?". But if you clicked the little x on the tab, or middle-clicked it, Orca just closed it and killed your job without a word. Same tab, same job, two different answers depending on how you closed it.

The check was written into the keyboard shortcut instead of into "closing a tab". This PR moves the check down to the one place all closing goes through, so it doesn't matter how you close the tab — you get the same warning either way. Nothing new to learn, no new buttons, and the existing "Don't ask again" checkbox now works for the mouse too.

Fix proof

Test file: src/renderer/src/components/terminal/terminal-close-confirm-keyboard-vs-mouse.test.ts
(the independently adjudicated repro, committed at a92d8e0b0d as repro-10142-close-confirm-keyboard-vs-mouse.test.ts; renamed only — git diff -M a92d8e0b0d HEAD shows the assertions are byte-identical apart from a header comment and prettier reflow).

BEFORE — run at the repro commit a92d8e0b0d (parent = base f3e087ec06), materialized into a scratch tree:

$ npx vitest run --config config/vitest.config.ts \
    src/renderer/src/components/terminal/repro-10142-close-confirm-keyboard-vs-mouse.test.ts

 FAIL  ... > mouse close (X button / middle-click) consults the running-process probe
AssertionError: expected "inspectRuntimeTerminalProcess" to be called at least once
 ❯ repro-10142-close-confirm-keyboard-vs-mouse.test.ts:123:47
    123|     expect(inspectRuntimeTerminalProcessMock).toHaveBeenCalled()

 FAIL  ... > mouse close (X button / middle-click) does not drop a busy tab without confirmation
AssertionError: expected "vi.fn()" to not be called at all, but actually been called 1 times
  1st vi.fn() call: Array [ "tab-busy" ]
 ❯ repro-10142-close-confirm-keyboard-vs-mouse.test.ts:130:26
    130|     expect(closeTab).not.toHaveBeenCalled()

 Test Files  1 failed (1)
      Tests  2 failed | 2 passed (4)

AFTER — this branch:

$ npx vitest run --config config/vitest.config.ts \
    src/renderer/src/components/terminal/terminal-close-confirm-keyboard-vs-mouse.test.ts

 Test Files  1 passed (1)
      Tests  4 passed (4)
   Duration  335ms

The two tests that already passed at base (the source assertion on handleRequestClosePane, and the pinned-tab control) still pass — so the fix adds the mouse path rather than moving the keyboard one.

Not tautological: re-verified during review by disabling the guard on this branch — the repro goes red again.

E2E, against real Electron (4/4 passing):

  • tests/e2e/terminal-tab-close-running-confirm.spec.ts — middle-click prompts + Cancel keeps the tab; Cmd+W raises exactly one dialog (the anti-double-prompt assertion).
  • tests/e2e/terminal-tab-close-running-confirm-mouse.spec.ts — X applies the same confirmation as Cmd+W; confirming "Stop and Close" actually closes it.

Plus 69 new unit tests across running-terminal-close-guard.test.ts, terminal-tab-close-running-confirm.test.ts, running-terminal-close-confirm.test.ts, terminal-close-copy-kind.test.ts, RunningTerminalCloseDialog.test.tsx.

Visual proof

Both sides ran the identical Playwright script in the same electron-headless project at the same 1920×1170 viewport. BEFORE is a scratch build of a92d8e0b0d (pre-fix); AFTER is this branch. The script starts a tab, runs sleep 300, polls window.api.pty.inspectProcess() until foregroundProcess === 'sleep', then closes the tab and dumps DOM state.

Machine-read DOM state (printed by the run, not hand-written):

close path BEFORE AFTER
Cmd+W (control) confirmDialogVisible: true, renderedTabCount: 1 confirmDialogVisible: true, renderedTabCount: 1
X button confirmDialogVisible: false, renderedTabCount: 0 confirmDialogVisible: true, renderedTabCount: 1
middle-click confirmDialogVisible: false, renderedTabCount: 0 confirmDialogVisible: true, renderedTabCount: 1

The Cmd+W row is identical on both builds, which is what makes the other two rows meaningful: the keyboard path did not change, the mouse paths did.

X button — busy tab → BEFORE (gone, no prompt) → AFTER (prompt, tab kept)

combined-x-button-setup-before-after.png

Middle-click — same three panels

combined-middle-click-setup-before-after.png

Control: Cmd+W unchanged before and after

combined-keyboard-cmdw-control.png

BEFORE — clicking X kills the busy tab silently:

before-x-button-closes-silently.webm

AFTER — clicking X raises the same prompt Cmd+W does:

after-x-button-shows-confirm.webm

AFTER — confirming really does stop the process and close the tab. This one is assertion-backed: it is the shipped spec tests/e2e/terminal-tab-close-running-confirm-mouse.spec.ts › "confirming the X-button prompt closes the busy tab", recorded over 3/3 passing runs (the recorder refuses to keep a failing run):

after-x-button-confirm-and-close.webm
Raw unpaired frames (same viewport both sides)

Busy tab, X hovered — BEFORE / AFTER:
before-2a
after-2a

After X click — BEFORE (tab gone) / AFTER (dialog):
before-2
after-2

After middle-click — BEFORE / AFTER:
before-3
after-3

After Cmd+W (control) — BEFORE / AFTER:
before-1
after-1

Regressions & trade-offs

Test evidence (no regressions found)

Command Result
vitest run src/renderer/ (whole renderer) 19,196 passed / 4 skipped, 0 failed (2,085 files)
vitest run src/shared/ 3,691 passed / 15 skipped, 0 failed
Touched-area sweep (terminal, terminal-pane, tab-bar, floating-terminal, tab-group, store, useIpcEvents) 5,561 passed, 0 failed
pnpm run typecheck (node + cli + web) 0 errors — verified non-incremental (7,743 files) and proven live by injecting a deliberate TS2322
oxlint, audit:code-quality:native, audit:code-quality:type-aware --deny-warnings, lint:react-doctor:changed pass
check:max-lines-ratchet pass — "352 grandfathered suppression(s), no new bypasses". No max-lines disable or bump added.
check:reliability-gates (62 gates) pass
verify:localization-{catalog,extraction,coverage} pass — no new strings introduced
E2E terminal-panes.spec.ts 31/31
E2E golden-core-flows.spec.ts 2/2
E2E terminal-tab-close-restart-persistence + daemon-generation-legacy-close-safety 2/2

Two e2e specs flaked (terminal-shortcuts.spec.ts, terminal-pane-close-layout-consistency.spec.ts), plus a helpers/orca-app.ts:372 fixture flake ("seeded e2e worktrees did not load"). All three were reproduced at base f3e087ec06 at an equal or higher rate — terminal-shortcuts failed 2/4 base runs vs 1/3 here, on the same test. helpers/orca-app.ts is untouched by this diff.

Disclosed behavior changes

  1. Closing a tab with the mouse is no longer synchronous. When a tab has live PTY ids, the close waits for one inspectProcess round trip. Measured locally over 60 samples: p50 0.4 ms, p95 4.3 ms, max 20.2 ms; end-to-end X-button close 79–119 ms, dominated by input dispatch, not the probe. No perceptible local regression. On remote/SSH runtimes the probe crosses the relay, so a wedged link makes the X button appear dead for up to 4 s (RUNNING_CLOSE_PROBE_TIMEOUT_MS) before showing the dialog. Cmd+W already had this exposure; a mouse-only shorter timeout was deliberately rejected because it would recreate the very keyboard/mouse asymmetry this PR removes.

  2. Timeout asks rather than closes. If the probe does not answer within 4 s, we raise the dialog instead of silently closing. Unanswered ≠ idle — this was changed during review, since performing the destructive close on timeout would have reintroduced the bug on exactly the path this PR reroutes.

  3. Fail-open on probe failure. A rejected probe (or unavailable: true) is treated as idle and the tab closes without a prompt. This matches the pre-existing Cmd+W behavior verbatim; failing closed would make the X button do nothing at all, which is worse.

  4. Spurious prompt on a brand-new tab (macOS, pre-existing). For roughly the first ~0.5 s of a tab's life the daemon reports foregroundProcess: 'login' → hasChildProcesses: true, so Cmd+T then immediately X shows "Stop running command?" on an idle shell (reproduced 4/4). This is existing probe behavior, but this PR promotes it onto the highest-frequency close path. A login/wrapper exclusion in isShellProcess would remove it — filed as follow-up, not fixed here to keep the diff on-issue.

  5. Bulk closes intentionally keep today's silent behavior. Close Others / Close to Right / Close to Left / Kill All / CLI orca terminal close still drop running tabs without asking — prompting per tab would be a modal storm, and an aggregate "N terminals are running" dialog is a separate feature.

  6. Pinned still supersedes running. A pinned busy tab shows only "Close pinned tab?" — exactly one dialog, preserving today's documented precedence, but the user is not told a command is running.

  7. No probe dedupe. Six rapid X-clicks issue six concurrent probes (measured). The dialog is deduped by tab id, so the user sees one prompt; the extra probes are harmless locally but wasteful on a slow relay. An in-flight Map would collapse them — follow-up.

  8. Two dialog hosts remain. TerminalPane's pane-level pendingCloseConfirmation still handles closing one pane of a split; the new store-driven host handles whole-tab closes. Both render the same CloseTerminalDialog, and the skipRunningProcessConfirm handoff guarantees only one can open per user action.

Known follow-up flagged by the release scan (not fixed here)

useTabGroupWorkspaceModel.closeGroup calls closeItem(id, { skipEmptyCheck: true }), which is the one bulk caller not given skipRunningProcessConfirm. With busy terminals in the group, "close split pane" can now show one dialog per busy tab, and closeEmptyGroup/leaveWorktreeIfEmpty run before those closes land. This is disclosed rather than hidden; it wants a one-line flag plus a "bulk paths never prompt" regression test. Happy to fold it into this PR if a reviewer prefers that to a follow-up.

Perf

Verdict: MINOR. No render fan-out, no polling, no new FS/git/network work, no new synchronous IPC.

  • check:zustand-selector-fanout (--check, exit 0): 2,500 subscribers × 2,000 unrelated writes = 5,000,000 selector runs, median 32.98 ms, 0 render invalidations. The always-mounted RunningTerminalCloseDialog and the new store add zero invalidations — all four subscriptions are narrow scalar/action reads with no object literals in selectors.
  • Probe IPC RTT (headless Electron, 60 samples, local daemon PTY): min 0.20 / p50 0.40 / p95 4.30 / max 20.2 ms.
  • End-to-end idle-tab close via the real X button: 79, 86, 94, 98, 119 ms — dominated by Playwright input dispatch.
  • Net −1 IPC on Cmd+W: TerminalPane no longer probes separately for the last-pane close.
  • handleRequestClosePane's dep array shrank (dropped worktreeId, tabId), so fewer callback recreations.
  • Every setTimeout has a matching clearTimeout on both the .then and .catch arms; a decided latch prevents double-resolution.
  • All 20 closeTerminalTab call sites enumerated — no surviving guarded one is a loop or background path.

Costs are items 1 and 7 above.

Release scan

Verdict: PASS-WITH-NOTES. No P0.

Cleared explicitly:

  • Cannot close a tab that shouldn't close — the guard re-enters closeTerminalTab after confirmation rather than continuing inline, so pin/route/precomputed state is revalidated against fresh state after an arbitrarily long dialog.
  • Cannot block closing forever — three independent escapes (Promise.allSettled never rejects; the 4 s probe timeout; a .catch that force-closes if raising the dialog throws), all arbitrated by one decided latch.
  • No orphan requests — RunningTerminalCloseDialog is mounted in App.tsx, which is the render root for both the Electron renderer and the paired-web root, so no surface can raise a request with no dialog to answer it.
  • Main-process / RPC paths cannot wedge on a modal — CLI/RPC closes stay synchronous via skipRunningProcessConfirm / rejectPinned.
  • Backward compat — no persisted-state shape change, reuses the existing skipCloseTerminalWithRunningProcessConfirm setting, no migration, rollback-safe.
  • Security — no new deps, no lockfile/native-binary changes, no shell/exec/eval, no new logging, no network sinks.
  • Cross-platform — no metaKey hardcoding introduced; the Cmd+W chord still resolves through terminal-shortcut-policy.ts with an explicit platform argument, and the e2e spec branches on process.platform. No path handling added. Folder workspaces are safe (the guard keys only off ptyIdsByTabId and the unified tab model, never git-worktree state). Nothing provider-specific touched.

P1/P2 notes are the tab-group closeGroup gap and the latency/false-prompt items already listed under Regressions & trade-offs, plus one narrow divergence: the guard treats unavailable: true (daemon protocol < 11) as idle while TerminalPane treats it as busy — the two should read it the same way.

Review loop

Reviewed 2 times until clean — verdict: "Merge-ready. The repro's assertions are provably unmodified, and I confirmed the repro still fails when the guard is disabled, so it is not tautological. The fix routes every interactive close path through one shared guard in closeTerminalTab while explicitly opting out every caller that cannot wait on a modal (CLI/RPC, lifecycle echoes, bulk closes), and it removes the duplicate probe from TerminalPane's last-pane path rather than leaving two competing policies. All 4 e2e specs pass against real Electron, 69 new unit tests pass, ~6,500 tests across the touched areas pass, and typecheck, oxlint, the max-lines ratchet, and all three localization gates are clean. No new user-visible strings were added, so there is no i18n gap. Remaining items are UX/coverage follow-ups, not merge blockers."

Round 1 raised 2 blocking issues, both fixed in f2cf1cbd35 / 14092a02e5: the probe timeout performed the destructive close (now it asks), and the e2e spec wrote screenshots to a hardcoded scratch dir with a stale "bug is unfixed" docblock.

Credits

Cross-referenced against #10167 by @innocarpe, which independently solved the same
issue and reached the same core design: move the decision into closeTerminalTab so every
close path shares one policy, raise it through a store-driven dialog reusing
CloseTerminalDialog, and have TerminalPane delegate its last-pane close instead of
probing twice. That convergence is a good sign for the approach.

Two things #10167 got right that this branch did not, now adopted in 47c02a3489:

  1. 350 ms double-activation guard on the queue (running-terminal-close-confirm.ts) —
    a queued request replaces the visible one in place, so the second click of a double-click
    aimed at one tab would land on the next tab's prompt and kill a running process the user
    never saw asked about. fix(terminal): confirm running process on tab X / middle-click close #10167 mirrored the sibling pinned-tab-close-confirm slice here;
    this branch had the guard in its description but not in its code.
  2. Layout bindings in the PTY lookup (running-terminal-close-guard.ts) — a mounting
    pane is bound into terminalLayoutsByTabId before ptyIdsByTabId catches up. fix(terminal): confirm running process on tab X / middle-click close #10167
    fell back to the layout when the map was empty; this branch now unions both, matching
    the store's own collectPtyIdsForTab teardown collector. Reading only the map let a
    close slip through that window with no prompt.

Where this PR goes further, and why it is the one being merged:

  • Non-interactive callers are excluded. fix(terminal): confirm running process on tab X / middle-click close #10167 guards on reason !== 'pty-exit' && !force,
    so reason: 'cleanup' teardowns, rejectPinned CLI closes, hostCloseReason echoes,
    lifecyclePtyId closes and bulk "Close Others" would each raise a modal — several from
    callers that are answered synchronously and cannot wait on one. shouldConfirmRunningTerminalClose
    enumerates and tests all seven.
  • A wedged probe asks instead of hanging or killing. A remote inspect can hang for its
    full 15 s RPC timeout; the 4 s bound raises the prompt rather than leaving the X button
    looking dead.
  • unavailable remote handles fail open, and copy resolution is scoped to the PTYs that
    actually reported a child, so an idle agent pane in a split cannot mis-word the prompt.
  • Pinned + running interaction: with confirmClosePinnedTab off the pin prompt says
    nothing, so a busy pinned tab still gets asked rather than silently closing.
  • e2e coverage against real Electron for X, middle-click, and single-dialog Cmd+W.

Closing #10167 in favour of this PR — thanks @innocarpe for the analysis and for the two
fixes adopted here.

Made with Orca 🐋

nwparker and others added 5 commits August 2, 2026 21:36
…confirmation

Unit repro: closeTerminalTab (the X-button/middle-click entry) never consults inspectRuntimeTerminalProcess and drops a tab with a live child.
E2E repro: Cmd+W shows 'Stop running command?' for a tab running sleep 300; cancelling then clicking the tab X closes it silently.

Co-authored-by: Orca <[email protected]>
…10142)

The tab-strip X button, middle-click and the tab context menu closed a
terminal with a live child process without asking, while Cmd+W raised
"Stop running command?" for the same tab. The probe lived only in
TerminalPane's pane-level close handler; every mouse entry point reaches
closeTerminalTab(), which guarded pinned tabs and nothing else.

Move the decision into closeTerminalTab, above the web-runtime branch so
paired/remote host-backed tabs are covered too, and give the last-pane
keyboard close back to it instead of probing twice:

- running-terminal-close-guard.ts probes every live PTY of the tab and
  fails open on a rejected probe or a stale remote handle, matching what
  Cmd+W already did. No live PTY ids => fully synchronous close, so idle,
  parked and hibernated tabs keep today's behavior.
- shouldConfirmRunningTerminalClose keeps lifecycle echoes, bulk closes,
  CLI/RPC closes and the post-confirmation re-entry off the modal path.
- A standalone confirm store drives RunningTerminalCloseDialog, which
  reuses the existing CloseTerminalDialog (no new user-visible strings).
  The request carries the tab label because a tab-strip close can target
  a tab the user is not looking at, and dedupes by tab id.
- TerminalPane.handleRequestClosePane now delegates the last pane to
  closeTerminalTab. Its transport ptyId is nullable by design, so the old
  path silently skipped the prompt mid-reattach; the pane keeps its own
  probe only for closing one pane of a split.
- Agent panes win the dialog copy when a split has both an agent and a
  plain command busy, instead of depending on PTY spawn order.
- Tab-group closeItem ran leaveWorktreeIfEmpty synchronously after a close
  that can now defer; it moves to onClosed and still honors skipEmptyCheck.

Co-authored-by: Orca <[email protected]>
…ath (#10142)

Follow-up hardening on the tab-close confirmation, from review of the first
pass:

- A pinned tab with `confirmClosePinnedTab` off never got the running-process
  prompt on any path, including Cmd+W, which is a regression against the old
  pane-level behavior: the pinned branch short-circuited on pinned-ness alone
  and re-entered with `force`, which the running guard excludes. The pin prompt
  now supersedes only when it will actually appear; with the setting off the
  close falls through to the running guard.
- The probe chain had no `.catch`, so a throw in the decision (a copy-kind
  lookup on a tab id makePaneKey rejects, a store subscriber) left the tab
  silently unclosed with no user feedback. It now fails open, as the pane path
  it replaced did.
- A wedged remote inspect RPC could leave the X button looking dead for its
  full 15s timeout. The probe is now bounded; every close path shares the
  bound, so keyboard and mouse still behave identically.
- The agent-vs-command copy had two resolvers on exactly the keyboard/mouse
  seam this issue is about. terminal-close-copy-kind.ts is now the single
  policy; TerminalPane and the tab-strip guard both call it.
- The running queue is async while the pinned queue is synchronous, so both
  could be pending at once and stack two modal overlays. The running dialog now
  waits for a visible pinned confirmation.
- Deduping a repeat close request dropped the second caller's callbacks; it now
  folds them in, so both closes resolve from one prompt. Ticking "don't ask
  again" also drains queued prompts instead of showing one the user just opted
  out of, and a queued prompt no longer inherits the previous tab's tick.

closeTerminalTab drops its private pinned predicate for the shared
isUnifiedTabPinned, whose only consumer the previous commit had removed.
…0142)

The running-process close specs polled `hasChildProcesses` to decide the tab
was busy, but macOS starts the shell under `login`, so an initialising terminal
already reports a child before `sleep 300` runs. Both specs could therefore
press close against a shell that never started the command: the probe correctly
saw an idle terminal and closed without asking, and the adjudicated repro failed
against a correct fix.

Wait for `foregroundProcess === 'sleep'` instead. Assertions are unchanged, and
the repro still fails at the pre-fix baseline (a92d8e0).
…10142)

Round-1 review follow-ups.

- The 4s probe bound closed the tab outright, but `inspectRuntimeTerminalProcess`
  gives remote runtimes a 15s RPC timeout: any probe taking 4-15s silently killed
  a running remote command that Cmd+W used to prompt about, and the pane path now
  delegates its last-pane close to this guard. An unanswered probe is unknown, not
  idle, so the timeout raises the confirmation with every pty treated as a
  candidate. Failing open still applies to an *answered* probe (rejection, stale
  remote handle), which is the pre-existing pane behavior.
- The split-pane Cmd+W probe had no bound at all; it now shares the same one, so
  the two paths give the same answer to the same question.
- The renamed regression spec dropped its repro scaffolding: the hardcoded
  /tmp screenshot directory (also a cross-platform path violation) and the
  title/docblock that still described the bug as open.
@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a queued dialog for terminal tabs with running processes. Adds PTY inspection with timeout and confirmation handling. Integrates the guard with tab, pane, bulk, lifecycle, IPC, and web-runtime close paths. Adds agent-specific and command-specific dialog copy resolution. Adds unit, component, regression, and end-to-end coverage.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% 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 clearly and concisely describes applying running-process confirmation to all terminal tab close paths.
Description check ✅ Passed The description provides the user-visible summary, visual evidence, extensive testing results, AI review, security audit, cross-platform checks, and known follow-up notes.
✨ Finishing Touches 💡 1
📝 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.

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/tab-group/useTabGroupWorkspaceModel.ts (1)

473-483: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Reconcile closeGroup cleanup with deferred terminal closing.

closeGroup calls closeItem(item.id, { skipEmptyCheck: true }), then immediately runs closeEmptyGroup(worktreeId, groupId) and leaveWorktreeIfEmpty(). Terminal items receive no closeTerminalTab options with this path, so a running process uses closeTerminalTab’s running-process confirmation instead of closing synchronously. If any terminal in the group remains open until after that confirmation, the emptiness cleanup happens too early and is not re-ran, which can leave an empty tab-group shell and keep the worktree active. Thread confirmation-appropriate options through and make the final cleanup wait for deferred closes, or make closeEmptyGroup/leaveWorktreeIfEmpty self-correct afterward.

🧹 Nitpick comments (4)
src/renderer/src/components/terminal-pane/TerminalPane.tsx (1)

1332-1335: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Align the unavailable check with the tab-level guard.

guardRunningTerminalClose treats a probe result as busy only when hasChildProcesses is true and unavailable !== true (running-terminal-close-guard.ts lines 108-115). This pane path checks only process.hasChildProcesses.

inspectRuntimeTerminalProcess currently returns hasChildProcesses: false alongside unavailable: true, so the two paths agree today. If that contract changes, Cmd+W on a split pane will prompt while the tab-strip X closes silently. Mirror the guard's condition to keep the two decisions identical.

♻️ Proposed consistency fix
             if (
-              !process.hasChildProcesses ||
+              !process.hasChildProcesses ||
+              process.unavailable === true ||
               settings?.skipCloseTerminalWithRunningProcessConfirm
             ) {
src/renderer/src/components/terminal/running-terminal-close-guard.test.ts (2)

49-53: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Make settleProbe resilient to microtask-depth changes.

settleProbe awaits a fixed count of three microtask ticks. The count is tied to the current promise depth of Promise.allSettled(...).then(...) in guardRunningTerminalClose.

If the guard adds one more await in that chain, these tests will stop settling the probe. Several assertions are negative (for example expect(onClose).not.toHaveBeenCalled() at line 208), so they would still pass while no longer testing the intended path. Wait on the observable outcome instead of a tick count.

♻️ Proposed condition-based settle helper
-async function settleProbe(): Promise<void> {
-  await Promise.resolve()
-  await Promise.resolve()
-  await Promise.resolve()
-}
+// Why: waiting on a fixed tick count silently breaks if the guard's promise depth changes.
+async function settleProbe(): Promise<void> {
+  await vi.waitFor(() => {
+    expect(
+      visibleRequest() !== null || inspectRuntimeTerminalProcessMock.mock.settledResults.length > 0
+    ).toBe(true)
+  })
+}

Alternatively, keep the tick loop but bound it by a settled condition supplied per test.


86-91: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Restore real timers in afterEach.

Four tests call vi.useFakeTimers() in the test body and vi.useRealTimers() before their assertions (lines 300-316, 318-334, 336-352, 354-371). If guard() or advanceTimersByTime throws, useRealTimers() never runs and fake timers leak into the next test.

Add the reset to the existing afterEach so cleanup does not depend on the happy path.

♻️ Proposed cleanup
   afterEach(() => {
+    vi.useRealTimers()
     const store = useRunningTerminalCloseConfirmStore.getState()
     while (visibleRequest()) {
       store.dismissRunningTerminalClose()
     }
   })
src/renderer/src/components/terminal/terminal-tab-actions.ts (1)

105-118: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider renaming resolvePinnedTabLabel for its new generic use.

Line 111 calls resolvePinnedTabLabel to compute the tab label for the running-process dialog. This label resolver does not depend on pin state and is now used for any tab, pinned or not. The name is misleading at this call site.

Rename the shared helper to something pin-agnostic, such as resolveUnifiedCloseTabLabel, and update both call sites (terminal-tab-actions.ts and pinned-tab-close-guard.ts).


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: bae860b9-dfd8-4841-85fd-6b86495e4696

📥 Commits

Reviewing files that changed from the base of the PR and between 173abf8 and f2cf1cb.

📒 Files selected for processing (22)
  • src/renderer/src/App.tsx
  • src/renderer/src/components/Terminal.tsx
  • src/renderer/src/components/tab-group/useTabGroupWorkspaceModel.ts
  • src/renderer/src/components/terminal-pane/CloseTerminalDialog.tsx
  • src/renderer/src/components/terminal-pane/RunningTerminalCloseDialog.test.tsx
  • src/renderer/src/components/terminal-pane/RunningTerminalCloseDialog.tsx
  • src/renderer/src/components/terminal-pane/TerminalPane.tsx
  • src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts
  • src/renderer/src/components/terminal/running-terminal-close-guard.test.ts
  • src/renderer/src/components/terminal/running-terminal-close-guard.ts
  • src/renderer/src/components/terminal/terminal-close-confirm-keyboard-vs-mouse.test.ts
  • src/renderer/src/components/terminal/terminal-close-copy-kind.test.ts
  • src/renderer/src/components/terminal/terminal-close-copy-kind.ts
  • src/renderer/src/components/terminal/terminal-tab-actions.ts
  • src/renderer/src/components/terminal/terminal-tab-close-running-confirm.test.ts
  • src/renderer/src/hooks/useIpcEvents.test.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/store/pinned-tab-close-guard.ts
  • src/renderer/src/store/running-terminal-close-confirm.test.ts
  • src/renderer/src/store/running-terminal-close-confirm.ts
  • tests/e2e/terminal-tab-close-running-confirm-mouse.spec.ts
  • tests/e2e/terminal-tab-close-running-confirm.spec.ts

…p from #10167 (#10142)

Cross-referenced against @innocarpe's #10167, which solved the same issue.
Two things it got right that this branch did not:

- Queue actions now hold off for 350ms after a queued request replaces the
  visible one, matching the sibling pinned-tab confirmation. Without it the
  second click of a double-click aimed at one tab lands on the next tab's
  prompt and kills a running process the user never saw asked about — the
  exact bug class this PR exists to close.
- The pty lookup unions the layout bindings with ptyIdsByTabId. A mounting
  pane is bound into the layout before the liveness map catches up, and the
  store's own teardown collector unions both for that reason, so reading only
  the map let a close slip through that window with no prompt.

Also replaces the render-time ref write that failed React Doctor's
"Ref mutated during render" rule: the queued-request checkbox reset now goes
through CloseTerminalDialog's existing subject-change reset instead of
remounting via key, which keeps the exit animation on one element.

Co-authored-by: Orca <[email protected]>
@nwparker
nwparker merged commit ba83a71 into main Aug 4, 2026
45 checks passed
@nwparker
nwparker deleted the nwparker/fix-10142-tab-close-confirm-all-paths branch August 4, 2026 05:48
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…tab close path (stablyai#10142) (stablyai#12272)

* test(repro): demonstrate stablyai#10142 tab X close bypasses running-process confirmation

Unit repro: closeTerminalTab (the X-button/middle-click entry) never consults inspectRuntimeTerminalProcess and drops a tab with a live child.
E2E repro: Cmd+W shows 'Stop running command?' for a tab running sleep 300; cancelling then clicking the tab X closes it silently.

Co-authored-by: Orca <[email protected]>

* fix(terminal): confirm running-process close on every tab close path (stablyai#10142)

The tab-strip X button, middle-click and the tab context menu closed a
terminal with a live child process without asking, while Cmd+W raised
"Stop running command?" for the same tab. The probe lived only in
TerminalPane's pane-level close handler; every mouse entry point reaches
closeTerminalTab(), which guarded pinned tabs and nothing else.

Move the decision into closeTerminalTab, above the web-runtime branch so
paired/remote host-backed tabs are covered too, and give the last-pane
keyboard close back to it instead of probing twice:

- running-terminal-close-guard.ts probes every live PTY of the tab and
  fails open on a rejected probe or a stale remote handle, matching what
  Cmd+W already did. No live PTY ids => fully synchronous close, so idle,
  parked and hibernated tabs keep today's behavior.
- shouldConfirmRunningTerminalClose keeps lifecycle echoes, bulk closes,
  CLI/RPC closes and the post-confirmation re-entry off the modal path.
- A standalone confirm store drives RunningTerminalCloseDialog, which
  reuses the existing CloseTerminalDialog (no new user-visible strings).
  The request carries the tab label because a tab-strip close can target
  a tab the user is not looking at, and dedupes by tab id.
- TerminalPane.handleRequestClosePane now delegates the last pane to
  closeTerminalTab. Its transport ptyId is nullable by design, so the old
  path silently skipped the prompt mid-reattach; the pane keeps its own
  probe only for closing one pane of a split.
- Agent panes win the dialog copy when a split has both an agent and a
  plain command busy, instead of depending on PTY spawn order.
- Tab-group closeItem ran leaveWorktreeIfEmpty synchronously after a close
  that can now defer; it moves to onClosed and still honors skipEmptyCheck.

Co-authored-by: Orca <[email protected]>

* fix(terminal): close the running-process confirmation gaps on every path (stablyai#10142)

Follow-up hardening on the tab-close confirmation, from review of the first
pass:

- A pinned tab with `confirmClosePinnedTab` off never got the running-process
  prompt on any path, including Cmd+W, which is a regression against the old
  pane-level behavior: the pinned branch short-circuited on pinned-ness alone
  and re-entered with `force`, which the running guard excludes. The pin prompt
  now supersedes only when it will actually appear; with the setting off the
  close falls through to the running guard.
- The probe chain had no `.catch`, so a throw in the decision (a copy-kind
  lookup on a tab id makePaneKey rejects, a store subscriber) left the tab
  silently unclosed with no user feedback. It now fails open, as the pane path
  it replaced did.
- A wedged remote inspect RPC could leave the X button looking dead for its
  full 15s timeout. The probe is now bounded; every close path shares the
  bound, so keyboard and mouse still behave identically.
- The agent-vs-command copy had two resolvers on exactly the keyboard/mouse
  seam this issue is about. terminal-close-copy-kind.ts is now the single
  policy; TerminalPane and the tab-strip guard both call it.
- The running queue is async while the pinned queue is synchronous, so both
  could be pending at once and stack two modal overlays. The running dialog now
  waits for a visible pinned confirmation.
- Deduping a repeat close request dropped the second caller's callbacks; it now
  folds them in, so both closes resolve from one prompt. Ticking "don't ask
  again" also drains queued prompts instead of showing one the user just opted
  out of, and a queued prompt no longer inherits the previous tab's tick.

closeTerminalTab drops its private pinned predicate for the shared
isUnifiedTabPinned, whose only consumer the previous commit had removed.

* test(e2e): wait for `sleep` to own the terminal before closing it (stablyai#10142)

The running-process close specs polled `hasChildProcesses` to decide the tab
was busy, but macOS starts the shell under `login`, so an initialising terminal
already reports a child before `sleep 300` runs. Both specs could therefore
press close against a shell that never started the command: the probe correctly
saw an idle terminal and closed without asking, and the adjudicated repro failed
against a correct fix.

Wait for `foregroundProcess === 'sleep'` instead. Assertions are unchanged, and
the repro still fails at the pre-fix baseline (a92d8e0).

* fix(terminal): ask instead of closing when the close probe times out (stablyai#10142)

Round-1 review follow-ups.

- The 4s probe bound closed the tab outright, but `inspectRuntimeTerminalProcess`
  gives remote runtimes a 15s RPC timeout: any probe taking 4-15s silently killed
  a running remote command that Cmd+W used to prompt about, and the pane path now
  delegates its last-pane close to this guard. An unanswered probe is unknown, not
  idle, so the timeout raises the confirmation with every pty treated as a
  candidate. Failing open still applies to an *answered* probe (rejection, stale
  remote handle), which is the pre-existing pane behavior.
- The split-pane Cmd+W probe had no bound at all; it now shares the same one, so
  the two paths give the same answer to the same question.
- The renamed regression spec dropped its repro scaffolding: the hardcoded
  /tmp screenshot directory (also a cross-platform path violation) and the
  title/docblock that still described the bug as open.

* fix(terminal): adopt the double-activation guard and layout pty lookup from stablyai#10167 (stablyai#10142)

Cross-referenced against @innocarpe's stablyai#10167, which solved the same issue.
Two things it got right that this branch did not:

- Queue actions now hold off for 350ms after a queued request replaces the
  visible one, matching the sibling pinned-tab confirmation. Without it the
  second click of a double-click aimed at one tab lands on the next tab's
  prompt and kills a running process the user never saw asked about — the
  exact bug class this PR exists to close.
- The pty lookup unions the layout bindings with ptyIdsByTabId. A mounting
  pane is bound into the layout before the liveness map catches up, and the
  store's own teardown collector unions both for that reason, so reading only
  the map let a close slip through that window with no prompt.

Also replaces the render-time ref write that failed React Doctor's
"Ref mutated during render" rule: the queued-request checkbox reset now goes
through CloseTerminalDialog's existing subject-change reset instead of
remounting via key, which keeps the exit animation on one element.

Co-authored-by: Orca <[email protected]>

---------

Co-authored-by: Orca <[email protected]>
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.

[Bug]: Tab close confirmation is bypassed when using the close button or middle-click

1 participant