Skip to content

fix shiny app window becoming unclosable and orphaned - #17920

Merged
kevinushey merged 4 commits into
mainfrom
bugfix/shiny-window-orphaned
Jun 10, 2026
Merged

kevinushey merged 4 commits into
mainfrom
bugfix/shiny-window-orphaned

Conversation

@kevinushey

Copy link
Copy Markdown
Collaborator

Problem

With Run App > Run in Window, the Shiny app window could become impossible to close: clicking X grayed the window out (the app was stopped) but the window stayed open, never refreshed on subsequent runs, and could only be removed by quitting RStudio.

Root cause: when a page registers a beforeunload handler that prevents unload (e.g. window.onbeforeunload = function() { return 'Your changes will be lost!'; }, as the app in #17502 does), Chromium cancels the window close. A regular browser shows a "Leave site?" confirmation in this situation, but RStudio Desktop had no will-prevent-unload handler, so the close was cancelled silently -- every time, with no way to override it.

A second bug then orphaned the window permanently: SatelliteWindow.closeEvent() unregistered the window from GwtCallback during the close attempt, so once a close was cancelled, the still-live window could no longer make desktop callbacks. This is the Received callback desktop_allow_navigation from unknown window error in the reporter's logs, and why the window stayed gray and could not display a re-run app.

Fix

  • Handle will-prevent-unload in DesktopBrowserWindow: show a native "Leave page?" confirmation mirroring browser behavior, and force the close if the user chooses Leave. (Chromium does not expose the page's custom beforeunload message, so a generic message is the best we can do.) Strings are localized (en/fr).
  • Unregister satellite windows from GwtCallback only on the closed event (window actually destroyed), so a cancelled close no longer orphans the window. This also fixes premature unregistration on the source-window close path when the user cancels an unsaved-changes prompt.
  • RSTUDIO_DESKTOP_IGNORE_BEFOREUNLOAD=1 skips the dialog and forces the close; the e2e harness sets it since automation cannot dismiss native modals.

Tests

  • New desktop unit tests for the will-prevent-unload choices (leave/stay/env bypass) and for unregister-only-on-destroy.
  • New e2e suite e2e/rstudio/tests/shiny/shiny-app-window-close.test.ts (@desktop_only) covering: window closes when the app is stopped, when closed while running, and -- the regression -- when the app's iframe registers a close-preventing beforeunload handler. The third test fails without this fix.

Note: if the user chooses "Stay", the app will typically already have been stopped, since the satellite close notification (which stops the app) is sent before Chromium runs beforeunload. The window remains open and closable; reordering that is a deeper change to the satellite close protocol left out of scope here.

Fixes #17439.
Fixes #17502.

When a page hosted in a desktop window registers a beforeunload handler
that prevents unload (e.g. a Shiny app warning that state will be lost),
Chromium cancelled the window close with no UI at all, leaving the
window seemingly impossible to close. Worse, the satellite had already
unregistered itself from GwtCallback during the close attempt, so the
still-open window could no longer make desktop callbacks ("Received
callback desktop_allow_navigation from unknown window") and stayed
orphaned in a grayed-out state across subsequent app runs.

Now handle 'will-prevent-unload' by showing a "Leave page?"
confirmation (mirroring browser behavior) and forcing the close when
the user confirms, and only unregister satellite windows once they are
actually destroyed. RSTUDIO_DESKTOP_IGNORE_BEFOREUNLOAD=1 skips the
dialog for automation; the e2e harness sets it.

Addresses #17439, #17502
@kevinushey kevinushey added this to the Blue Plumbago milestone Jun 10, 2026
@kevinushey kevinushey self-assigned this Jun 10, 2026
@kevinushey
kevinushey requested a review from gtritchie June 10, 2026 03:24
@github-actions

github-actions Bot commented Jun 10, 2026 •

Copy link
Copy Markdown

🍎 macOS Desktop E2E · ARM64

✅ All tests passed!

████████████████████ 100% pass rate

✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
340 0 9 0
📥 Download Playwright report

⬇️ playwright-report.zip — extract and open index.html

Includes screenshots, traces, and step-by-step details for every test. Expires in 15 days.


2 shards · macos-26 ARM64 · commit bef6c0bbf9baf1282ff08cf7ccda3c0d84711f2d · Run #194

@gtritchie

Copy link
Copy Markdown
Member

Review summary

Four specialized agents reviewed the diff (code quality, tests, error handling, comments), and I independently adjudicated the one finding where they disagreed. The two source-code fixes are correct and well-reasoned — the Electron will-prevent-unload semantics, the window lifecycle, and the absence of an orphaning regression all check out. All actionable concerns live in the test and comment layers, not the fix itself.

Critical issues

None. No correctness, security, or silent-failure defect in the fix. The Leave/Stay/env-bypass branches map correctly to preventDefault(), and moving unregisterOwner to the closed event resolves the orphaning without introducing a leak or double-unregister.

Important issues

1. The third e2e test's "fails without this fix" claim — most likely TRUE (one agent thought otherwise; worth confirming). e2e/rstudio/tests/shiny/shiny-app-window-close.test.ts:111
The test-analyzer agent flagged this as a potential false-pass — that the test would pass even with both fixes reverted, because the fixture sets RSTUDIO_DESKTOP_IGNORE_BEFOREUNLOAD=1. I believe that conclusion is incorrect: the env var is read inside the new handler (desktop-browser-window.ts:337), so reverting the fix removes both the handler and the bypass. Per documented Electron 41 behavior, with no handler the prevent-unload defaults to cancel with no dialog → waitForEvent('close', {timeout: 15000}) times out → the test fails. So the test does guard the fix.

  • Residual caveat (worth ~5 minutes to settle): this reasoning is from the Electron docs, not an empirical run, and the test's own comment claims a "CDP dialog still surfaces" (:100). If such a dialog surfaced pre-fix and Playwright's dialog.accept() closed the window, that's the one way the test could pass without the fix. Recommend confirming by reverting both source changes and running the third test — it settles the ambiguity the comment introduces.

2. The orphaning symptom (fix #2) is not asserted end-to-end. e2e/rstudio/tests/shiny/shiny-app-window-close.test.ts:140-144
With the env var set, the window actually closes, so the cancelled-close → live-but-unregistered path that fix #2 addresses is never exercised in e2e. The e2e tests assert only that the window closes — none relaunch and verify that the next "Run in Window" produces a functional, registered window (the distinctive #17439 symptom). Fix #2 is currently guarded only by the satellite unit test.

3. The source-window cancel path — which the PR description explicitly claims to fix — has no test coverage. satellite-window.ts:92-95, satellite-window.test.ts:49
The PR notes it fixes "premature unregistration on the source-window close path when the user cancels an unsaved-changes prompt," but the only satellite unit test uses a non-source window name. A cheap, high-value addition: construct a SatelliteWindow whose name starts with _rstudio_satellite_source_window_, stub executeJavaScript so rstudioReadyToClose resolves false, call closeEvent, and assert unregisterOwner is not called (window stays live) — then that it is called once on closed. This is the path most prone to a future regression.

Suggestions

  • Soften the e2e comment that overclaims the CDP dialog as certain (shiny-app-window-close.test.ts:100) — "the beforeunload confirmation still surfaces as a CDP dialog" presents a version-dependent maybe as a fact; "can still surface" is more accurate (the handler is correctly defensive either way).
  • Comment/code API mismatch (shiny-app-window-close.test.ts:85) — comment says "e.g. via window.onbeforeunload" but the test installs the handler via addEventListener('beforeunload', …). Functionally equivalent; align the wording.
  • Add debug logging to the will-prevent-unload handler (desktop-browser-window.ts:336) — the rest of the file leaves logging breadcrumbs; the dialog-shown / user-choice path currently logs nothing.
  • Pre-existing (out of scope, noted only): the rstudioReadyToClose rejection path leaves closeStage stuck in CloseStagePending (satellite-window.ts:87-98). This predates the PR (the .catch was already there). Not a blocker.

Recommended action

  1. Confirm finding Clone fail-Permission denied (publickey) #1 empirically (revert both source changes, run the third e2e test).
  2. Close the two real coverage gaps: assert the orphaning/relaunch symptom in e2e (Autocompletion of delimiters #2), and add the source-window-cancel unit test (Allow for homebrew's version of libboost #3).
  3. Apply the minor comment/logging polish.
  4. Run npm run typecheck && npm run lint && npm test in src/node/desktop before merge.

Verdict: the fix is merge-quality; the remaining work is hardening the tests around it (gaps #2 and #3) and the quick empirical check on #1.

@gtritchie gtritchie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM, usual fit & finish suggestions on comments, tests, etc.

- add unit test for the source-window cancel path (window stays
  registered when the user cancels the close)
- destroy test windows before clearing the app singleton so the
  satellite 'closed' handler doesn't crash mocha teardown
- add debug logging to the will-prevent-unload handler
- clarify e2e comments (CDP dialog is version-dependent; cite the
  onbeforeunload example from #17502)
@kevinushey

Copy link
Copy Markdown
Collaborator Author

Thanks for the thorough review! Evaluated each finding; resolution in 9944a7f:

Finding #1 (does the third e2e test really fail pre-fix?) -- confirmed empirically. Reverted both source files to their pre-fix state and ran the third test against the dev build: it fails with page.waitForEvent('close'): Timeout 15000ms exceeded -- the close is silently cancelled, and no CDP dialog surfaces to rescue it. So the env-var bypass does not create a false pass (it only exists inside the new handler), and the test genuinely guards the fix. The "still surfaces as a CDP dialog" comment was indeed overclaiming; softened to "can still surface".

Finding #2 (orphaning symptom not asserted e2e) -- accurate as a gap description, but the proposed relaunch assertion can't actually catch a fix-#2-only regression: with RSTUDIO_DESKTOP_IGNORE_BEFOREUNLOAD=1 the window always truly closes in e2e, so an early unregister followed by a successful close leaves nothing orphaned, and the relaunch would succeed anyway. The cancelled-close-then-orphan path requires a user choosing "Stay" in a native modal, which automation can't drive -- the unit-test layer is the right guard here. Declining this one.

Finding #3 (source-window cancel path untested) -- agreed; added the suggested unit test: source-prefixed window name, rstudioReadyToClose resolving false, asserting preventDefault fired, rstudioCloseSourceWindow() invoked, closeStage reverted, and unregisterOwner deferred until closed.

Suggestions -- all applied: comment softening, aligned the onbeforeunload wording (now cites the #17502 example), and debug logging in the will-prevent-unload handler. Agreed the closeStage-stuck-on-rejection path is pre-existing and out of scope.

Bonus goblin the review's "run npm test before merge" advice flushed out: npm test was crashing at mocha teardown on the committed branch -- the first satellite unit test never destroys its window, so the new closed handler fired after afterEach had cleared the application singleton and appState() threw. Fixed by destroying all windows in afterEach before clearing the singleton (verified the crash at baseline and its absence after).

npm run typecheck, npm run lint, and npm test (405 passing) are all green.

The GWT SatelliteManager in the main window learns that a satellite has
closed from the satellite's own JS unload handler, but that notification
can lose the race with window destruction (and window proxies can report
as open even after close; see case 4436). A stale entry makes the next
open of a same-named satellite "reactivate" the dead window instead of
creating a new one -- e.g. re-running a Shiny app shortly after stopping
it could leave R busy serving an app with no window at all, as seen in
the shiny-app-window-close e2e failure on CI.

Now the Electron main process authoritatively calls
unregisterDesktopChildWindow in the main window once the satellite
window is actually destroyed; the 'closed' event never fires for a
cancelled close, so this cannot reintroduce the eager-unregister bug
fixed previously on this branch.
On CI, the interruptR in the first test could land while shiny was
servicing a request; shiny's error handling swallows the interrupt,
bouncing the websocket (so the window still closes and the test passes)
without stopping runApp(). R then stays busy forever, the next test's
runApp sits queued behind it, no satellite ever opens, and the client
escalates to a blocking "Terminate R" dialog. Ensure the console
actually returns to idle after the window closes, re-requesting the
interrupt if needed.

Also absorb two unrelated CI flake sources observed in the same runs:
wait out a main-window reload left in flight by a preceding spec before
driving prefs (and make setPref/clearPref wait for the bridge like
executeCommand already does), and disable startup update checks in the
e2e sandbox since runners have no route to the update server.
@kevinushey
kevinushey merged commit 9a471bb into main Jun 10, 2026
10 checks passed
@kevinushey
kevinushey deleted the bugfix/shiny-window-orphaned branch June 10, 2026 22:57
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.

Shiny app window doesn't fully close when terminated on the console, or closed manually Shiny app window orphaned

2 participants