Skip to content

Fall back to DOM renderer on terminal WebGL context loss - #18405

Merged
gtritchie merged 4 commits into
mainfrom
bugfix/terminal-webgl-context-loss
Jul 30, 2026
Merged

gtritchie merged 4 commits into
mainfrom
bugfix/terminal-webgl-context-loss

Conversation

@gtritchie

Copy link
Copy Markdown
Member

Fixes #18393.

Since the xterm.js 6.0 upgrade (#16820), the default "canvas" value of the terminal_renderer preference maps to the xterm.js WebGL addon, but RStudio never subscribed to WebglAddon.onContextLoss. When a terminal's WebGL context was lost (GPU process crash, graphics driver reset, or the browser reclaiming a context when too many were live), the addon stayed loaded with a dead context: input still reached the shell, but nothing painted, so the terminal appeared hung until it was closed or the IDE reloaded.

Changes

  • XTermNative.onWebGLContextLoss() subscribes to the addon's onContextLoss event, which fires once the addon has given up waiting (~3s) for the browser to restore a lost context; losses the browser restores within that window recover silently inside the addon. At most one handler is installed per loaded addon, guarding against the two concurrent enableWebGL() calls made at terminal startup (the startup enable plus the pref binding).
  • XTermWidget.enableWebGL() registers a handler that disposes the addon and reverts to the DOM renderer via disableWebGL(), so the terminal keeps rendering — the recovery pattern the xterm.js API documents for this event.
  • unloadWebGLAddon() clears the handler-installed flag so a handler is registered again when the addon is reloaded (e.g. toggling the renderer preference back on after a fallback).

Test

New Playwright test in e2e/rstudio/tests/panes/terminal/terminal.test.ts ("terminal keeps rendering after WebGL context loss"):

  • Forces a real context loss with the WEBGL_lose_context extension on the addon's webgl2 render canvas, then asserts that the output of a subsequently typed command appears in the terminal's rendered DOM rows (.xterm-rows, which only exists under the DOM renderer). The output marker is split across shell quotes so the echoed command line cannot satisfy the assertion, and rstudioapi::terminalBuffer() is deliberately not used — the server-side buffer keeps receiving output while client rendering is broken, which is the bug being tested.
  • The command is typed during the addon's ~3s dead window, so the assertion also proves already-buffered content is repainted after the fallback.
  • A second round toggles the renderer preference dom → canvas and loses the context again, covering handler re-subscription on an addon reload (verified by mutation testing: removing the flag clear in unloadWebGLAddon fails this round).
  • Skips only when the environment cannot create WebGL2 contexts at all (probed on a detached canvas). If the environment is capable but the addon's render canvas never attaches, the test fails rather than skips, so a broken addon load reads as a regression instead of an environment limitation.

The test fails without the fix and passes with it; the full terminal suite passes on macOS Desktop.

Since the xterm.js 6.0 upgrade the default "canvas" terminal renderer
maps to the WebGL addon, but RStudio never subscribed to
WebglAddon.onContextLoss. When the context was lost (GPU crash, driver
reset, browser reclaiming a context), the addon stayed loaded with a
dead context and the terminal stopped painting for the rest of its
life. Subscribe to onContextLoss and dispose the addon when it fires,
reverting to the DOM renderer so the terminal keeps rendering.

Addresses #18393
Test changes:
- Skip only when the environment cannot create WebGL2 contexts (probed
  on a detached canvas); if the environment is capable but the addon
  render canvas never attaches, fail instead of skipping, so a broken
  addon load reads as a regression rather than an environment limit.
- Add a second loss round after toggling the renderer pref dom ->
  canvas, covering the handler re-subscription that depends on
  unloadWebGLAddon clearing its handler-installed flag (verified by
  mutation: removing the clear fails this round).
- Assert with toContain on the rendered text for self-diagnosing
  failures, skip 2D canvases before probing for webgl2, restore the
  terminal_renderer pref in a finally block, and use TIMEOUTS constants
  throughout.

Comment corrections: the addon recovers on its own when the browser
restores a lost context within its ~3s window; onContextLoss fires only
once it has given up. Reword the XTermNative Javadoc and XTermWidget
comment, which implied every context loss permanently falls back.

Addresses #18393
@gtritchie gtritchie added this to the 2026.08 (Yellow Yarrow) milestone Jul 30, 2026
@gtritchie
gtritchie requested a review from kevinushey July 30, 2026 16:58
@posit-snyk-bot

posit-snyk-bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

✅ Snyk checks have passed. No issues have been found so far.

Status Scan Engine Critical High Medium Low Total (0)
✅ Open Source Security 0 0 0 0 0 issues
✅ Licenses 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

@github-actions

github-actions Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

All tests passed!

#################### 100% pass rate

Passed Failed Skipped Flaky
1908 0 356 6
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ desktop-linux 474 0 89 0
✅ desktop-macos 478 0 84 2
✅ desktop-windows 477 0 89 3
✅ server-linux 459 0 94 1
✅ setup 20 0 0 0
View / download the full report

View report online -- opens in the browser, no download needed. Available for 14 days.

Download playwright-report.zip -- extract and open index.html

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


All platforms - commit 026b78afdb4ec7dc8e0c7a0e8c5ed9ece2bbbf88 - Run #397

@gtritchie
gtritchie merged commit 2ed3623 into main Jul 30, 2026
27 checks passed
@gtritchie
gtritchie deleted the bugfix/terminal-webgl-context-loss branch July 30, 2026 21:29

@kevinushey kevinushey left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Correctness

I verified the fix against the actual code paths and the bundled addon, and it holds up:

  • All load paths install the handler. loadWebGLAddon() is only called from enableWebGL(), and the handler is installed synchronously in the same loader callback that performs the load, so there is no gap in which the addon exists unhandled. The early-return in enableWebGL() (addon already loaded) is safe because whichever call loaded the addon already subscribed.
  • The double-enable at startup is handled. TerminalSession calls enableWebGL() twice when the pref is "canvas" (the pref binding plus the explicit startup call). The second loadWebGLAddon() returns true ("already loaded") and would have re-subscribed on every such call; the !this.rstudioWebGLContextLossHandler_ guard prevents that.
  • Re-subscription after reload works. unloadWebGLAddon() nulls the flag, so toggling the pref dom -> canvas gets a new handler. The e2e test's second round covers exactly this (and was mutation-tested against removing the flag clear).
  • Disposal semantics are sound. The registration is never explicitly .dispose()d, but WebglAddon.dispose() tears down its emitters, and disposing the addon from inside its own onContextLoss handler is the addon's documented usage. Even a hypothetical zombie listener firing later is harmless: disableWebGL() no-ops when isWebGLAddonLoaded() is false.
  • No fallback loop. After fallback the pref still reads "canvas" but nothing auto-retries WebGL on that terminal, so a flaky GPU can't cause a crash/reload cycle. New terminals will try WebGL again, which seems like the right balance.
  • Claims in comments check out. The bundled webgl.js exposes onContextLoss and contains the 3e3 ms grace constant, so the "~3s" comments are accurate.

Code quality

  • The JSNI callback is $entry-wrapped — important, since GWT doesn't route native event/promise continuations through its exception handler otherwise.
  • Field naming (rstudioWebGLContextLossHandler_), brace style, and the javadoc on the new native method all read well; the "browser-restored losses recover silently" note is the non-obvious bit and it's documented.

Test coverage

This is an unusually strong e2e test:

  • It forces a real context loss via WEBGL_lose_context on the addon's actual render canvas (skipping the 2D link-layer canvas), rather than simulating the callback.
  • The echo "pw_ctx1""loss_ok" marker split means the echoed command line can't satisfy the assertion — only rendered output can — and asserting on .xterm-rows (DOM-renderer-only) instead of terminalBuffer() is exactly right, since the server-side buffer keeps working when rendering is broken.
  • Typing during the ~3s dead window additionally proves buffered content is repainted after the swap.
  • The skip-vs-fail distinction (capability probed on a detached canvas; a capable environment where the addon canvas never attaches is a failure) prevents a broken addon load from silently reading as an environment skip.
  • Timing is comfortable: a 3s dead window against a 15s poll (TIMEOUTS.consoleReady) with a 10s actionTimeout covering the .xterm-rows auto-wait.

Minor points (none blocking)

  • Shell quoting is POSIX-specific. echo "a""b" concatenates only under POSIX shells; under cmd.exe the quotes are echoed literally, and under PowerShell "" is an escaped quote, so the assertion would fail there. The existing tests in this file already assume a POSIX shell (expr 1 + 1), so this is consistent with the suite's status quo — just worth knowing if terminal tests ever run against cmd/PowerShell on Windows CI.
  • Defense-in-depth option: enableWebGL()'s already-loaded early return could also call terminal_.onWebGLContextLoss(...) — the JSNI guard makes it free — so correctness wouldn't depend on the invariant that every load flows through the loader callback. Not needed today; take it or leave it.
  • Naming nit: rstudioWebGLContextLossHandler_ actually stores the IDisposable registration and is used as a flag; ...Registration_ would be slightly more accurate.
  • Silent downgrade: the fallback only emits a Debug.log, so a user whose GPU resets quietly ends up on the DOM renderer while the pref still says "canvas". That's strictly better than a hung terminal and matches upstream guidance, so fine as-is — but a status-bar notice could be a future nicety.

Verdict

Correct, well-scoped, and carefully tested — the flag guard against the startup double-enable and the flag clear on unload show the edge cases were thought through, and the test discriminates the real failure mode rather than a proxy. Approving; the points above are optional polish.

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.

Terminal does not recover from WebGL context loss

3 participants