Skip to content

fix(window): bound the ordinary window-close wait on a wedged renderer - #15294

Closed
OrcaWin wants to merge 2 commits into
mainfrom
OrcaWin/window-close-unbounded-wait
Closed

OrcaWin wants to merge 2 commits into
mainfrom
OrcaWin/window-close-unbounded-wait

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Aug 18, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​477 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​476
Prod 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​221 $\color{#cf222e}{\Huge{\mathbf{−}}}$​35 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​186

Bound the ordinary window-close wait on a wedged renderer

The bug

Triage of 28 Orca 1.4.184 crash reports found 7 where the whole process tree was force-killed externally (exit code 1, TerminateProcess — Task Manager "End task" / taskkill /T /F), by 6 different users within ~17 hours. All 7 relaunched within 5–23 seconds, so these were force-restarts, not shutdowns. One user did it 5 times in 19 minutes.

Root cause

mainWindow.on('close') preventDefault()s the close, sends window:close-requested to the renderer, and waits for the renderer to reply. Only the app-wide quit path armed a deadline on that wait:

// createMainWindow.ts (before)
e.preventDefault()
const isQuitting = opts?.getIsQuitting?.() ?? false
const requestId = ++closeRequestSequence
if (isQuitting) {
  armQuitRendererAckTimer(requestId)   // <-- ONLY on the quit path
}
mainWindow.webContents.send('window:close-requested', { isQuitting, requestId })

On an ordinary close (Alt+F4, native X) isQuitting is false, so the main process waited forever. window-close-decision.ts said so in its own doc comment: "App-wide quit separately bounds failure to acknowledge that request; ordinary window close does not."

The renderer-drawn X was worse. onRequestClose sent { isQuitting: false } with no requestId at all, so onCloseRequestReceived could never match its ack and no deadline could ever be armed on that path — even in principle.

Why this bites hardest on Windows: autoHideMenuBar: true + titleBarStyle: 'hidden' make the X renderer-drawn, and File → Exit (the only bounded path, role: 'quit') has no accelerator and is hidden behind Alt. With a blocked renderer main thread: the X does nothing, Alt+F4 does nothing, Task Manager is the only exit.

What the ack deadline actually measures

The key insight that makes this fix cheap and safe: the existing timer does not bound "the renderer finished deciding". Preload sends the ack synchronously, before any app logic:

// preload/index.ts
const listener = (_event, data) => {
  ipcRenderer.send('window:close-request-received', data?.requestId)  // first
  callback({ isQuitting: data?.isQuitting ?? false })                 // then app logic
}

So a wedged main thread never acks, while a healthy-but-thinking renderer acks in one tick and the (correct) unbounded wait for the user's answer resumes. That is exactly the right liveness probe — it was just wired to one of three close paths.

The fix

  1. Every close path allocates a requestId and arms the deadline (sendWindowCloseRequest), including the renderer-drawn X.
  2. The deadline branches on what firing means:
    • isQuitting → unchanged (destroy; will-quit is blocked and the app is going away anyway).
    • ordinary close → a native main-process dialog.showMessageBox.
  3. Wait re-sends a fresh close request and re-arms on the new id, with backoff. Critical on Windows: the renderer-drawn X is itself dead while the renderer is wedged, so a one-shot prompt the user dismisses would strand them again with no way to re-trigger. It must be a new request, not a re-arm of the expired one — preload only acks a message it actually receives, so a deadline armed on an already-consumed requestId is one a recovered renderer can never clear. Acks are also recorded independently of the armed timer, so an ack that lands while the dialog is open counts as recovery and stops the probing entirely. Each Wait doubles the next probe (10s → 20s → 40s, capped at 60s) so a renderer that is legitimately busy for minutes is not shown a destructive button on a fixed 10s beat.

How #5787's guarantee is preserved

resolveWindowCloseAction is untouched — an unresponsive-but-alive renderer still resolves to 'request-confirmation', so the save/running-process guard still runs.

What #5787 forbids is main silently bypassing that guard for a merely-hung renderer. This change never does: the main process's only new power is the power to ask. The decision to end sessions belongs to a human looking at a dialog that spells out the cost, with Wait as both defaultId and cancelId so a reflexive Enter or Escape can never be the answer that discards work.

Unsaved state on "Close Window": that window's terminal sessions end and its unsaved editor changes are lost — stated in the dialog. Strictly better than today's taskkill /T /F, which takes the entire process tree.

Fix evidence — real Windows app, real wedged renderer

Reproduced on Windows 11 by wedging the renderer main thread via CDP immediately after asking main to close, i.e. the exact renderer-drawn-X path that previously had neither a requestId nor a timer:

window.api.ui.requestClose()
const end = Date.now() + 300000
while (Date.now() < end) { /* wedge the renderer main thread */ }

1. The bound fires (main-process log — this line did not and could not exist before):

[window] Renderer did not acknowledge close; prompting to close unresponsive window

2. A real native dialog renders while the renderer is hard-blocked (top-level window enumeration + PrintWindow capture):

34060   Orca isn't responding      <-- new native top-level window
34060   Orca
+---------------------------------------------------------------+
| Orca isn't responding                                       X |
+---------------------------------------------------------------+
|  !   This Orca window didn't respond to the close request.     |
|                                                                |
|      Wait keeps the window open in case it recovers. Close     |
|      Window ends this window's terminal sessions and discards  |
|      unsaved editor changes in it.                             |
|                                                                |
|                                  [ Wait ]   [ Close Window ]   |
+---------------------------------------------------------------+

3. The escape actually works. Clicked Close Window with ~4 minutes of wedge still remaining (no WEDGE_DONE in the harness log — the renderer was still hard-blocked). Main destroyed the window and the app exited cleanly:

[window] Renderer did not acknowledge close; prompting to close unresponsive window
[window] User chose to close unresponsive window; destroying it

4. Late acknowledgement is safe. In a separate run the wedge expired after the deadline had fired and the dialog was up. The renderer woke, processed the queued close request, confirmed, and the window closed normally — no crash, no double-close, no error in the log.

ELI5

The window's X button doesn't close the window by itself. It taps the app on the shoulder and asks "okay to close? you might have unsaved work." Then it waits for an answer.

If the app has frozen, that answer never comes — and nobody had set a timer. The X would wait politely, forever. On Windows the X is drawn by the frozen part, so it couldn't even light up. Alt+F4 asked the same frozen thing and got the same silence. The only thing left was Task Manager, which kills everything at once — every window, every terminal, all of it.

Now the tap on the shoulder comes with a 10-second timer. If there's no answer, a plain Windows box appears — drawn by the part of Orca that isn't frozen — and asks you: keep waiting, or close this window? You decide. The app never decides to throw away your work on its own.

Trade-offs and risks

Closing a window whose renderer was merely slow, not dead. This is the real risk, and it is bounded three ways:

  • The deadline measures IPC receipt, not work completion. A renderer busy restoring a huge session still acks in its listener before doing that work. Only a blocked main thread misses it.
  • The deadline never closes anything. It shows a dialog whose default and cancel are both Wait.
  • If the renderer wakes mid-dialog it just closes normally (validated live, evidence Add Ctrl+Click to open links in terminal #4). If the user picked "Close Window" while it was hung, that explicit choice is honored, guarded by isDestroyed().

Residual risk: a user who reflexively clicks "Close Window" on a renderer that was 11 seconds slow loses that window's unsaved editor state. That is a deliberate trade against 7 confirmed taskkill /T /F events that lost the entire process tree.

Platform scope: all three, no branch. The defect is in the close handshake, not the chrome — the chrome only changes how often users hit it. macOS's native X routes through the same preventDefault()ed handler and is equally unbounded, and role: 'quit' has no default accelerator on Linux either. A win32-only branch would leave two platforms with Force Quit as the only exit, and leave the new path uncompiled and untested where it isn't used.

Not done: a "Reload Window" button. Arguably what these users actually wanted (all 7 relaunched within 5–23s). Reloading a wedged renderer needs forcefullyCrashRenderer(), which entangles crash-report classification, the expected-teardown state, and the renderer-recovery circuit breaker. Worth a follow-up; deliberately out of scope here.

Bound value. 10s, matching the shipped quit deadline, as a separate constant (WINDOW_CLOSE_RENDERER_ACK_TIMEOUT_MS) so it can be tuned independently. Long enough to sit out a bad GC pause; the user is staring at a dead X for those 10 seconds.

Edge cases covered by tests: rapid repeated close attempts (one timer, one dialog — no stacking); an in-flight quit escalating a pending ordinary deadline back to destroy (will-quit stays blocked, so a dialog nobody can get past would be wrong); a late ack after the bound; a window destroyed before the deadline fires.

Tests

src/main/window/createMainWindow-unresponsive-close-prompt.test.ts (16 cases) and src/main/window/unresponsive-window-close-prompt.test.ts (6 cases), covering: the bound fires on a renderer that never acks; a healthy close is unaffected (no dialog, no destroy, request still sent synchronously); the renderer-drawn X now arms a timer; a late ack does not double-close or crash; Wait re-sends a NEW request; an ack for the re-sent request stops the probing; an ack that lands while the dialog is open stops it too; the backoff widens and is capped; a rejected dialog is treated as Wait and stays bounded; a quit gets its own full 10s even when an ordinary deadline is nearly expired; repeated ordinary closes cannot defer the bound; quit escalation; Wait is both default and cancel.

The six regression cases added in review all fail against the pre-review commit of this branch and pass after it (verified by checking out the old createMainWindow.ts under the new tests).

$ npx vitest run --config config/vitest.config.ts src/main/window src/renderer/src/i18n
Test Files  55 passed | 1 skipped (56)
     Tests  495 passed | 1 skipped (496)

pnpm run typecheck, pnpm exec oxlint, pnpm run check:max-lines-ratchet (188 grandfathered suppressions, no new bypasses) and the full pnpm run lint — including the two localization gates that were red on the first push — are green. The branch was also rebased onto origin/main to resolve an en.json conflict with a newly landed quickOpen key; that conflict had left the PR mergeable_state: dirty, which is why GitHub was not creating CI runs for the review commit at all. No max-lines disable or baseline bump was added; the dialog lives in its own module, unresponsive-window-close-prompt.ts.

Limitations

What this does not fix

  • The bound only detects failure to acknowledge receipt. A renderer that acks in one tick and then wedges inside its own close-confirmation flow clears the timer and is still an unbounded wait with no escape. That is the deliberate design — the ack is a liveness probe, not a decision timer — but it means this covers "wedged before the ack", not "wedged after".
  • Stale isQuitting is an unfixed hole, unchanged from main. isQuitting is only reset from will-prevent-unload. A Cmd+Q that the renderer cancels in its own confirmation dialog sends nothing back to main, so getIsQuitting() stays true; a later ordinary X on a wedged renderer then takes the quit branch and destroys the window after 10s with no dialog. The doc comment in window-close-decision.ts was corrected in review to stop claiming the ordinary-close deadline always asks.
  • A permanently wedged renderer is still prompted forever, just on a widening schedule (10s, 20s, 40s, then every 60s). There is no total cap and no "stop asking" button; the exits remain Close Window, a recovery, or killing the app.
  • Destroy loses more than the dialog names. PTY cleanup is deliberately deferred to will-quit "so the renderer captures scrollback before PTY-exit events unmount TerminalPane"; destroying the renderer skips that capture, so terminal scrollback is lost on top of the sessions and unsaved editor changes the dialog does mention. Still strictly better than the taskkill /T /F this replaces.
  • The original close intent can still be misattributed. Closing during early startup, before the App root subscribes to window:close-requested, produces an "Orca isn't responding" dialog after 10s for a renderer that is merely still loading. The re-probe does now reach a listener that mounts later (main re-sends), but the first prompt's wording still blames the wrong thing.
  • Not fixed: a "Reload Window" option, which is arguably what these users wanted. Out of scope, as described above.

Not verified

  • The Windows field evidence above was captured against the first version of this fix, before the review changes (re-send, backoff, quit-grace, dialog-rejection handling). Those four changes are covered by unit tests only. No reviewer, and not this pass, launched the real app after them.
  • macOS behavior of the new destroy is unverified. shouldQuitWhenAllWindowsClosed returns false on darwin when not quitting, so "Close Window" leaves the app alive with no window and PTYs still owned by main until a later sweep. Whether the dialog's "ends this window's terminal sessions" is accurate there — and what a later dock activation restores — was not tested.
  • Dialog parenting is decided once, from isVisible(). How that reads for a minimized window per platform is unconfirmed; if it reports visible, the dialog becomes a sheet/child of a window the user cannot see, and unresponsiveClosePromptOpen then suppresses every further prompt for as long as that invisible dialog is open.
  • What Electron does to an open window-modal dialog whose parent is destroy()ed mid-quit (the ordinary-prompt-open + quit-escalation race) was not exercised on a real build.
  • rendererAckTimer.unref?.() means neither deadline keeps the event loop alive — matching the pre-existing quit timer — so on an otherwise idle main process the prompt can be delayed. Not measured.
  • Whether 10s is the right bound is asserted, not measured; it simply matches the shipped quit deadline.
  • The es/ja/ko/zh translations added for the five new keys were written in this pass, not by a human translator or the project's normal translation flow. English en.json values are the authoritative fallbacks.
  • Interactions with the sibling crash-triage PRs (fix(git): back off host probes a wedged runtime never answers #15293, fix(git): scope capability state to the distro that runs git #15297) were not evaluated. This branch touches only src/main/window and src/renderer/src/i18n/locales.

Residual risk

  • A user who reflexively clicks "Close Window" on a renderer that was 11 seconds slow loses that window's unsaved editor state and scrollback. Deliberate trade against 7 confirmed taskkill /T /F events that lost the entire process tree; mitigated by Wait being both defaultId and cancelId.
  • When a wedged renderer finally drains several queued close requests, it dispatches each of them. The in-app running-process dialog is a boolean state flag so it does not stack, and main's onConfirmClose/close() are guarded by isDestroyed(), but the renderer-side close flow can run more than once in that window.

Adversarial review

Three independent reviewers went over this branch after it was written; none saw the others' notes, and none of them wrote the code. Their lenses were, respectively: the #5787 data-loss guarantee and the close handshake's state machine; the repo's required CI gates and AGENTS.md rules run against a clean worktree of the branch; and field-incident realism — whether the fix reintroduces the "session restored problem infinitly repeat" shape it was triaged from. All three worked from code reading plus throwaway vitest scenarios against the branch; none launched the real app.

They returned 10 blocking findings (2 blocker, 4 major, 4 minor), which collapse to 5 distinct defects — the re-arm loop was found independently by all three, and the missing localization keys by three. None was rejected; all five are fixed in this branch.

  1. (blocker, found 3×) The re-arm after Wait could never be answered. The deadline nulls rendererAckRequestId, so an ack arriving while the dialog was open was discarded — and the Wait branch then re-armed on that same, already-consumed requestId without re-sending anything. A renderer that recovered mid-dialog was re-accused of not responding every 10 seconds, forever, on a window-modal dialog whose second button destroys sessions. Two reviewers reproduced it (6 prompts in 50 simulated seconds, 1 close request ever sent); the branch's own "survives a late acknowledgement" test missed it because it answers the dialog with Close Window rather than Wait. Fixed by re-sending a fresh request instead of re-arming, plus recording acks independently of the armed timer so a mid-dialog ack ends the probing outright.
  2. (blocker, found 3×) The five new window.unresponsiveClose.* keys were never added to en.json, so verify:localization-catalog and verify:localization-extraction — separate required steps in .github/workflows/pr.yml — were both red. This was the actual cause of the failing static analysis and verify checks on the first push. Fixed via sync:localization-catalog; es/ja/ko/zh were also filled in, since all 46 other translateMain keys in the repo are translated in every locale and these five were the only gap.
  3. (major) A quit arriving late in an unacked ordinary close inherited that deadline's remaining time, cutting the 10s quit grace to as little as ~0ms — a regression against main, where an ordinary close armed no timer at all and a quit always started fresh. Reproduced at 100ms. Fixed by re-arming on the ordinary→quit escalation only; repeated ordinary closes still cannot defer the bound (both directions now have tests).
  4. (minor) Wait was a fixed 10-second snooze with no backoff and no cap — 20 prompts in 200 simulated seconds on a renderer that was legitimately busy, which is the same shape as the incident that motivated the sibling backoff PR. Fixed with doubling backoff capped at 60s.
  5. (minor, found 2×) A rejected dialog.showMessageBox skipped the re-arm entirely — no catch on the awaited call and void-ed at the call site — silently restoring the unbounded wait this PR exists to remove, while filing the rejection as a fatal main-process error in the very crash telemetry this effort is triaging. Fixed by treating a failed dialog as Wait (log, then re-probe) and attaching a .catch() at the call site.

Reviewers also confirmed several things came back clean: resolveWindowCloseAction is untouched and an unresponsive-but-alive renderer still resolves to request-confirmation; the only destroy() on the ordinary path requires an explicit response === 1; late acks cannot double-close; createMainWindow has one call site so there is no multi-window interaction; every real quit path still takes the destroy branch and never shows the new dialog; freezeBoundsOnQuit() before destroy() suppresses a spurious renderer-crash report; the renderer-drawn-X hole is genuinely closed (one sender, ack echoed by preload before any app logic); and check:max-lines-ratchet passes with no new bypass.

@coderabbitai

coderabbitai Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3b99372f-5a04-4f58-899b-940a47b1432e

📥 Commits

Reviewing files that changed from the base of the PR and between 2e09be06ee368c1bafee5ad60b6faa7139065b2a and d77a6cf.

📒 Files selected for processing (1)
  • src/renderer/src/i18n/locales/en.json
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/i18n/locales/en.json

Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review.


📝 Walkthrough

Walkthrough

The main process now tracks renderer close acknowledgements for ordinary closes and quits. Close requests include numeric request IDs and use a shared timeout mechanism. Ordinary-close timeouts display a localized native prompt with Wait and Close Window actions. Quit timeouts destroy unresponsive windows. Tests cover prompt behavior, timeout handling, retries, request IDs, late acknowledgements, and cleanup.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.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 identifies the primary fix for unbounded ordinary window-close waits.
Description check ✅ Passed The description thoroughly covers the bug, implementation, rationale, evidence, testing, limitations, and risks.

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

🧹 Nitpick comments (1)
src/main/window/createMainWindow.ts (1)

1033-1045: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Note the duration coupling when a quit escalates an armed ordinary deadline.

If a timer is already armed, this function upgrades rendererAckDeadlineIsQuitting but keeps the original duration. The escalation currently fires at the ordinary bound because both constants are 10_000. If either constant changes later, a quit that arrives after an ordinary close will destroy the window at the ordinary interval instead of the quit interval. Consider restarting the timer with the quit duration when the flag transitions to quitting.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8ab7abc7-3ac1-4329-837c-8b3136693d15

📥 Commits

Reviewing files that changed from the base of the PR and between 4b2c901 and 1891643.

📒 Files selected for processing (7)
  • src/main/window/createMainWindow-test-harness.ts
  • src/main/window/createMainWindow-tray-minimize-close.test.ts
  • src/main/window/createMainWindow-unresponsive-close-prompt.test.ts
  • src/main/window/createMainWindow.ts
  • src/main/window/unresponsive-window-close-prompt.test.ts
  • src/main/window/unresponsive-window-close-prompt.ts
  • src/main/window/window-close-decision.ts

Included review availability: Your plan includes up to 10 reviews per rolling hour; 5 remain after this review.

Comment thread src/main/window/createMainWindow.ts Resolved
OrcaWin and others added 2 commits August 18, 2026 14:39
An ordinary close (Alt+F4, native X, renderer-drawn X) was preventDefault()ed,
an IPC was sent to the renderer, and the main process then waited with no
timeout at all. Only the app-wide quit path armed the 10s ack deadline, so a
wedged renderer left the X and Alt+F4 doing nothing and Task Manager as the
only exit. The renderer-drawn X was worse: it sent no requestId, so its ack
could never be matched and no deadline could ever be armed on that path.

Every close path now allocates a requestId and arms the ack deadline. The quit
path keeps its existing destroy. An ordinary close instead shows a native
main-process dialog — Wait (default and cancel) or Close Window — because the
renderer that would draw an in-app one is the thing that is wedged.

#5787 is preserved: resolveWindowCloseAction still routes an unresponsive but
alive renderer to 'request-confirmation'. What #5787 forbids is main SILENTLY
bypassing the renderer's save guard; an explicit user choice in a dialog that
states the cost is not silent. Main only decides to ask.
…grace

Adversarial review of the ordinary-close deadline found four defects in the
first cut.

Re-arming after Wait reused a requestId main had already sent and the deadline
had already consumed. Preload only acks a message it receives, so a renderer
that recovered while the dialog was open could never clear that deadline: it
was re-accused of not responding every 10s, forever, with a destructive button
on screen each time. Re-SEND instead, and record every ack independently of the
armed id — an ack that lands while the prompt is up now counts as recovery and
stops the probing outright.

Wait also had no backoff, so a renderer legitimately busy for minutes drew a
modal on a fixed 10s beat. Each Wait now doubles the next probe up to a minute.

A quit arriving late in an unacked ordinary close inherited that deadline's
remaining time, so Cmd+Q could destroy the window milliseconds later where main
has always granted a full 10s. Only the ordinary->quit escalation re-arms;
repeated Alt+F4 still cannot defer the bound.

A rejected showMessageBox skipped the re-arm entirely and silently restored the
unbounded wait this fix exists to remove. A failed dialog is now treated as
Wait.

Also adds the five window.unresponsiveClose.* keys to en.json (two required CI
gates were red without them) plus es/ja/ko/zh, so the one dialog carrying the
data-loss warning is not English-only, and corrects window-close-decision.ts's
doc comment: the quit deadline still destroys, including for a close main still
believes belongs to a quit.
@nwparker

Copy link
Copy Markdown
Contributor

Closing per maintainer decision. Also CONFLICTING/DIRTY against current main and untouched since 2026-08-18.

@nwparker nwparker closed this Aug 26, 2026
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