Skip to content

fix(terminal): ask before closing the window when a terminal probe could not answer - #17044

Closed
brennanb2025 wants to merge 18 commits into
brennanb2025/probe-liveness-coercion-r1from
brennanb2025/window-close-guard-r1
Closed

brennanb2025 wants to merge 18 commits into
brennanb2025/probe-liveness-coercion-r1from
brennanb2025/window-close-guard-r1

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​685 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​683
Prod 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​247 $\color{#cf222e}{\Huge{\mathbf{−}}}$​101 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​146

ELI5

Before closing the window, Orca asks each local terminal "is something still running in you?"
If any says yes, you get "There are local terminals with running processes. Close the window anyway?"

The problem: the terminal could only answer yes or no — it had no way to say "I couldn't check."
When the check failed, it said no. So the window closed, silently, on work that was still running.

This PR lets the terminal say "I couldn't check", and treats that the same as "yes": ask the user.

User-facing before / after

Before: with a live agent or command running in a local pane, if the process probe degraded, the
window closed with no warning at all. No dialog, no chance to cancel — running work was killed and
unsaved terminal state went with it. On screen it was indistinguishable from closing an idle window.

After: the same degraded probe raises the confirmation. The user sees the running-processes
warning and can Cancel. A terminal that was positively observed idle still closes silently,
exactly as today.

What was actually wrong

Terminal.tsx:560 called window.api.pty.hasChildProcesses(id). That IPC returns a bare boolean:

// src/main/providers/local-pty-provider.ts
async hasChildProcesses(id: string): Promise<boolean> {
  const proc = ptyProcesses.get(id)
  if (!proc) return false
  try {
    const foreground = proc.process     // node-pty's foreground title
    const shell = ptyShellName.get(id)
    if (!shell) return true
    return foreground !== shell
  } catch {
    return false                        // <- a failed probe reads as "nothing running"
  }
}

Two real degraded reads both land on false:

  1. The native title read throws — swallowed by the bare catch.
  2. node-pty's POSIX title read silently falls back to the spawned shell name when the native read
    fails, so foreground === shell with an agent very much alive. This is the exact case
    classifyLocalPtyChildProcesses calls "pty title matches the shell while the foreground scan is
    degraded"
    .

The guard then ran results.some(Boolean) → false → confirmNativeWindowClose(). No dialog.

That is the neighbouring shape from #17024: the host answered, its probes failed, and it published
the deliberate legacy collapse (foregroundProcess = the stable-cache shell name,
hasChildProcesses: false) — byte-identical to a genuinely idle shell unless you read
processEvidence. An unavailable check would not have caught it; that flag is for an unroutable
handle, not a failed probe.

The fix

Read through readPtyProcessInspectionEvidence — the same route #17024 adopted, no second way to ask —
and block on anything that is not a positively observed exited:

result.status === 'rejected'
  ? true
  : readPtyProcessInspectionEvidence(result.value).children.verdict !== 'exited'

Strictly more conservative than what it replaces: the host collapses hasChildProcesses to
children.verdict === 'live', so every case that blocked before still blocks, plus unverifiable
and a rejected probe. Loss of contact is unchanged — an unroutable handle publishes no evidence, so
the legacy fields stay the only answer and the window still closes.

The probe, the decision and the dialog move out of Terminal.tsx into
components/terminal/window-close-running-process-prompt.tsx as a pure move, so the decision is only
reachable through the surface the user sees — and so the test can assert on that dialog in a real DOM.

Failing-first proof

src/renderer/src/components/terminal/window-close-running-process-prompt.test.tsx mounts the real
hook and the real Radix dialog in happy-dom, drives the real proceedToNativeWindowClose, and asserts
on the warning text in document.body and on whether confirmWindowClose() fired — never on an
intermediate boolean. The degraded fixture is built through the real collapse function
(buildPtyProcessInspectionWireResult) so it cannot drift from the producer, and the window.api.pty
double publishes both the evidence and the legacy hasChildProcesses derived from the same answer,
so the pre-fix predicate is exercisable rather than merely untestable. The boundary modelled is a
swallowing one: the host resolves with a degraded answer, it does not throw.

Ablation table

Each production hunk reverted individually, test file re-run:

# Hunk reverted to Result Reddened
A the pre-fix guard verbatim: Promise.all(ptyIds.map(id => window.api.pty.hasChildProcesses(id))).then(r => r.some(Boolean)) 3 failed / 3 passed degraded probe; raised inspection; malformed foreign evidence
B children.verdict !== 'exited' → result.value.hasChildProcesses 2 failed / 4 passed degraded probe; malformed foreign evidence
C rejected probe → false instead of true 1 failed / 5 passed raised inspection
— restored 6 passed —

Row A is the important one: it is the code on the PR's base, and the degraded case goes green-closes.

What I did NOT verify

  • No packaged-app or live Electron run. The degraded read needs a real native title-read failure,
    which I could not induce on this machine; the confirmation is from source plus the unit-level DOM.
  • Windows and Linux untested. The reasoning covers both (the Windows job-read path produces
    unverifiable through the same classifier), but nothing ran there.
  • The SSH/relay path is out of scope by construction — this guard filters to local PTYs only
    (getConnectionId(worktreeId) === null and !isRemoteRuntimePtyId).
  • A load-related worker-start timeout hit one unrelated renderer file in the 441-file sweep
    (remote-runtime-pty-latched-pane-retention.test.ts); it passes on its own re-run.

…uld not answer

The window-close guard asked `pty:hasChildProcesses`, whose local answer is a
bare boolean: `LocalPtyProvider.hasChildProcesses` reads node-pty's foreground
title and returns `false` both when the native read throws (a bare `catch`) and
when it silently degrades to the spawned shell name. `results.some(Boolean)` was
then false, so `confirmNativeWindowClose()` fired with no dialog and the window
closed on live work the user was never asked about.

Route the guard through `readPtyProcessInspectionEvidence` — the same reader
#17024 adopted — and block on anything that is not a positively observed
`exited`. A rejected inspection now asks too; the `Promise.all` it replaced had
no catch, so a rejection left the window neither closed nor prompting.

The prompt (probe, decision and dialog) moves out of Terminal.tsx unchanged so
the decision is only reachable through the surface the user actually sees, and
so the regression test can assert on that dialog in a real DOM.
…w file

The confirmNativeWindowClose block moved out of Terminal.tsx with the rest of
the prompt; the source-text pin followed it, with an indent anchor so a nested
copy cannot satisfy it.
pty:inspectProcess answers `unavailable: true` for an id it cannot route,
and inspectPtyProviderProcessForRenderer answers it on terminal_gone — both
alongside the legacy idle collapse (null/false) and no processEvidence. The
evidence read then fabricated `exited` out of fields nothing observed, so the
window closed with no prompt. probeTerminalLiveness already fences this shape
on the cleanup path; this consumer is strictly more destructive.

Also pins Terminal.tsx as the guard's only entry point: swapping the
registered handler's call for a direct confirmWindowClose() left every
suite, tsc and oxlint green.
…ot wedge the close

The guard awaited Promise.allSettled with no deadline. A local inspect is an IPC
round trip into a process-table scan and can stall indefinitely, and this path has
no backstop: main arms its renderer-ack timer only when isQuitting, which is exactly
the branch that never probes. A stalled probe therefore left the window neither
closed nor prompting — the silent death this guard exists to remove, reached through
a stall instead of a wrong verdict.

Bound it with the deadline the tab-close and pane-close paths already use
(RUNNING_CLOSE_PROBE_TIMEOUT_MS, #10142) rather than a second constant, and keep the
posture those paths set: unanswered asks, never closes.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review round 1 — patched, not superseded

Reviewed 4946978057; head is now 2c3ba200fd. The shape is what we'd write from scratch: probe, decision and dialog live in one unit so the decision is only reachable through the surface the user sees, the evidence predicate is a separate leaf, and it reuses readPtyProcessInspectionEvidence / inspectRuntimeTerminalProcess rather than re-deriving anything. Three defects found and fixed.

1. unavailable: true was flattened into exited and closed the window silently.
The predicate went straight to the evidence read, skipping the unavailable marker on the same return type. Two producers publish it with the legacy idle collapse and no processEvidence, so the reader took the legacy branch and hasChildProcesses: false became exited. Critically, DegradedDaemonPtyProvider.hasPty is a route lookup, not host evidence — a daemon whose session routing is lost answers false for a pane that is still running, and that becomes terminal_gone → unavailable. That is ssh-execution-boundary.md rule 2: loss of contact is unverifiable, never exited. The sibling consumer of the same evidence (probeTerminalLiveness) already fenced this shape; the window-close guard is the strictly more destructive of the two and was the less conservative one. Now fenced ahead of the evidence read — strictly additive, no existing gate weakened.

2. The guard's only entry point was unpinned.
Swapping proceedToNativeWindowClose(isQuitting) in the registered handler for a direct window.api.ui.confirmWindowClose() — the exact regression this PR fixes — left 22 suites / 237 tests, tsc and oxlint all green. Pinned now with two source-text assertions in the guard's own test file, anchored on the effect's indent.

3. The probe had no deadline.
Promise.allSettled was awaited unbounded. A local inspect is an IPC round trip into a process-table scan and can stall indefinitely, and this path has no backstop anywhere: main arms its renderer-ack timer only when isQuitting, which is exactly the branch that never probes. A stalled probe left the window neither closed nor prompting — the same silent death this guard exists to remove, reached through a stall rather than a wrong verdict. Now bounded by the deadline the tab-close and pane-close paths already use (RUNNING_CLOSE_PROBE_TIMEOUT_MS, #10142) rather than a second constant, keeping their posture: unanswered asks, never closes.

Gate-level ablation (each arm reverted alone):

Gate Reverted alone Tests red
Promise.allSettled + rejected ⇒ blocking → Promise.all 1
verdict !== 'exited' → === 'live' 2
verdict arm → always false 3
verdict arm → always true 1
unavailable fence (added) deleted 1
probe deadline (added) withTimeout deleted 2 (one hangs to the 30s limit)
STA-5505 pin repoint 1

No gate is only jointly pinned. Attacks: relocating the dialog out of the JSX is compile-gated (TS6133); the early-return attack on proceedToNativeWindowClose reddens 6 tests. One honest limitation — an early return planted above the entry-point call still passes, because a source-text pin proves the call is written there, not that control reaches it; closing that needs mounting a 2800-line component.

Not verified: macOS only, no Windows or Linux run, no packaged build, and the unavailable reachability is traced through the providers rather than observed on a live degraded daemon. Nothing below this PR in the stack was judged or touched.

Still open (not fixed here): on the blocking-but-unverified path the dialog still says "There are local terminals with running processes", which asserts as fact the thing the guard just established it could not determine. Worth distinct copy in a follow-up.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Correction to my earlier comment — the unavailable fence over-blocks

My previous comment endorsed fencing unavailable: true as blocking without qualification. That is too broad, and a follow-up pass found it introduces a spurious prompt. Correcting the record.

unavailable: true has two producers with opposite epistemic status, and the wire shape makes them byte-identical:

  1. Loss of contact — genuinely unverifiable. DegradedDaemonPtyProvider.hasPty is a map/route lookup, so a daemon that has lost session routing answers false for a pane that is still running. Blocking here is right, and it is the defect the fence was written for.
  2. Authoritative local exit — genuinely exited. inspectPtyProviderProcessForRenderer also produces unavailable by catching terminal_gone, thrown when provider.hasPty(id) === false. For LocalPtyProvider that is ptyProcesses.has(id) (local-pty-provider.ts:1104), and clearPtyState → ptyProcesses.delete runs inside the natural-exit handler (:226, :1055). Main is the execution host for a local pane, so this is positive evidence of absence — not "we could not ask".

Reachability is closed, and it is not a race. Terminal.tsx defers the exit-close for a parked multi-leaf tab; collapseParkedExitedLeaf rewrites only the layout via setTabLayout, which never writes ptyIdsByTabId. The dead id therefore survives in exactly the map the window-close guard collects, so closing the window shows "There are local terminals with running processes" for a process main has confirmed is gone.

There is also a polarity split. guardRunningTerminalClose requires unavailable !== true to count a PTY busy (running-terminal-close-guard.ts:138), so tab close closes on the same evidence the window path now blocks on.

Severity is modest — one extra click, the window still closes — but the cost is a false statement on a confirmation dialog, and a guard that cries wolf is the failure mode this feature exists to avoid.

Not fixed here, deliberately. The two producers are only separable on the main side (pty-process-inspection.ts / the pty:inspectProcess handler), which is territory owned by the PRs below this one in the stack, and this PR must not reach into them. Note the pre-fix behaviour was not correct either — it closed silently on both producers, which is wrong for the lost-route case. Neither polarity is right while the shapes stay conflated, so the real fix is for the stack owner to have the local provider publish processEvidence with children: { verdict: 'exited' } rather than collapsing to a bare unavailable.

Flagging for a decision: separate the producers in the stack, or accept the false prompt and the polarity split for now.

@greptile-apps

greptile-apps Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR makes native window closing conservative when local terminal process inspection is degraded and consolidates the probe, decision, and confirmation dialog into one hook.

  • Reads structured PTY inspection evidence and prompts unless child-process exit was positively observed.
  • Bounds stalled inspections and treats rejected, unavailable, or unverifiable results as blocking.
  • Adds shared close-request generation fencing so superseded or cancelled probes cannot act.
  • Adds DOM-level coverage for degraded evidence, timeouts, overlapping requests, cancellations, guard vetoes, and dirty-file deferrals.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Important Files Changed

Filename Overview
src/renderer/src/components/terminal/window-close-running-process-prompt.tsx Centralizes terminal inspection and close confirmation while correctly fencing stale probe completions and dialog cancellation.
src/renderer/src/components/window-close-request-coordinator.ts Adds a shared generation that advances before close guards, invalidating work from superseded attempts across all request branches.
src/renderer/src/components/terminal/window-close-running-process-evidence.ts Conservatively interprets structured PTY evidence and bounds inspections that reject, become unavailable, or never settle.
src/renderer/src/components/Terminal.tsx Replaces the inline legacy boolean probe and dialog with the consolidated close-running-process hook.
src/renderer/src/components/terminal/window-close-running-process-prompt.test.tsx Exercises the real coordinator and dialog across degraded evidence, timeout, cancellation, stale-probe, veto, and deferred-close scenarios.

Sequence Diagram

sequenceDiagram
  participant U as User
  participant C as Close coordinator
  participant P as Terminal close prompt
  participant H as PTY inspection host
  participant W as Native window
  U->>C: Request window close
  C->>C: Advance request generation
  C->>P: Proceed with current request
  P->>H: Inspect local PTYs
  H-->>P: Process evidence
  alt Request was superseded
    P->>P: Discard stale result
  else Any result is not positively exited
    P-->>U: Show confirmation dialog
    alt User cancels
      P->>C: Abandon current request
    else User confirms
      P->>W: Run checkpoint and confirm close
    end
  else Every PTY is positively exited
    P->>W: Run checkpoint and confirm close
  end
Loading

Reviews (13): Last reviewed commit: "Merge commit 'fc6519a3ab8b4a330a76770f69..." | Re-trigger Greptile

Main re-sends window:close-requested on every close attempt — the native `close`
handler previews and re-sends with a fresh requestId, and the renderer-drawn X
routes through window:request-close and sends again. Nothing downstream fences the
probe: the coordinator releases closeInFlight before it calls the handler, and
Terminal's re-entrancy ref only trips when dirty editors queued the close. So a
second attempt while the first probe is outstanding starts another one, and both
`.then` callbacks act.

macOS keeps native traffic lights under titleBarStyle 'hiddenInset', so the second
attempt is reachable by mouse with the dialog already up. The older probe then
decides on a process table it read before the dialog existed: an idle answer calls
confirmNativeWindowClose() and closes the window the user just chose to keep, and a
blocking one reopens the warning they dismissed.

A per-request generation makes the decision belong to the newest attempt only. The
verdict handling is untouched — unanswered still blocks, and `exited` is still the
only verdict that closes with no prompt.
The newest attempt is not the newest intent. The per-attempt generation added in
0a896a9 drops an answer from a *superseded* attempt, but a probe belonging to
the current attempt still decides even after the user has dismissed the warning:
press the traffic light again while the prompt is up, then choose Cancel, and the
second attempt's probe lands on an idle table and calls
confirmNativeWindowClose() — the window closes over running work the user just
chose to keep. Reachable because nothing serialises native close requests (main
re-sends on every attempt, the coordinator releases closeInFlight before calling
the handler, and the prompt is a renderer modal that cannot stop Cmd+Q or the
macOS traffic lights under titleBarStyle 'hiddenInset').

Route every dismissal — Cancel, Escape/outside-click, and the confirming Close —
through one helper that bumps the same generation, so dismissing ends the attempt
the way a newer request does.

Verdict handling is untouched: rejected and unavailable still block, unanswered
still blocks at the 4s bound, and `exited` is still the only verdict that closes
with no prompt.

Also pins the per-attempt bump on its own. Both existing overlap tests cancel
before the stale answer lands, so the dismissal fence alone satisfies them —
without a case that never cancels, deleting the per-attempt bump left the whole
suite green.
…uest

The per-attempt generation was bumped inside the probe branch, so the close
paths that never probe — a quit, or a request that finds no local PTYs — left
an earlier probe still current. When such a request was vetoed by its shutdown
checkpoint the window stayed open, and the older probe went on to reopen the
warning or drive the close sequence a second time.

Bumped at the entry instead, where no branch can skip it.
…t today's producers

Measured, not assumed: instrumenting the predicate across 14,788 tests shows it
evaluated 41 times, reaching `unavailable: true` twice, and the absence-action
reader answered the same way in 41 of 41 — so deleting the fence reddens nothing
while forcing its excluded case reddens 2. All five `unavailable: true` producers
publish no `processEvidence`, which is why the two agree. Keep the fence for the
unvalidated peer JSON both routes into this result actually are, and say so, so it
is not read as independent coverage.
…e probe

A close request that never reaches proceedToNativeWindowClose still supersedes
the attempt before it: a pre-close guard can veto one in the coordinator, and
Terminal defers one behind the unsaved-changes dialog. Counting attempts inside
the hook left an older probe current across all of those exits, so cancelling
the deferred close still let the stale probe close the window.

Move the generation to the coordinator and advance it once, at the single point
every request passes through, above every branch.
brennanb2025 added a commit that referenced this pull request Aug 29, 2026
The generation moved from the hook's own ref to the coordinator, above every
branch, because most close requests never reach proceedToNativeWindowClose. The
pending affordance's timer is armed per attempt and those same requests cannot
cancel it either, so it now reads the one rule too.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Superseded by #18593.

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.

1 participant