Skip to content

fix double-load and gray-screen on automation-agent startup - #17733

Merged
kevinushey merged 4 commits into
mainfrom
bugfix/automation-startup-race
May 21, 2026
Merged

kevinushey merged 4 commits into
mainfrom
bugfix/automation-startup-race

Conversation

@kevinushey

Copy link
Copy Markdown
Collaborator

Summary

Three tightly related fixes that came out of triaging the Playwright desktop-dev tests after a fresh ant devmode recompile. The first is a real bug (any automation user hits it after #17728 lands); the other two eliminate startup races / costs that the test fixture exposed.

1. automation: defer initializeAgent until after pref refresh (Application.java)

ApplicationAutomation.initializeAgent() now iterates userPrefs_.allPrefs() to populate the window.rstudio bridge (#17728). In desktop mode, prefs are loaded without sessionInfo on the initial pass and only fully populated inside a writeUserPrefs(...) callback (the existing comment in Application.java already flagged this). Previously initializeAgent() ran before that callback, so it hit a half-populated pref set and crashed GWT bootstrap with a gray-screen renderer. Move the call inside the callback.

2. electron: pre-seed WEBDIALOG cookie when launched with --automation-agent (main-window.ts)

GWT's bootstrap reads the WEBDIALOG cookie as a deferred-binding property (rstudio.useNativeDialogs in RStudio.gwt.xml) to pick the dialog permutation at compile-time. e2e/rstudio/fixtures/base-prefs.jsonc sets native_file_dialogs: false so Playwright can drive dialogs; in a fresh electron-userdata the cookie is unset, so initializeWorkbench() detected a pref/cookie mismatch on first load and fired a ReloadEvent that cost ~4s per test launch. Pre-seeding the cookie before loadURL when --automation-agent is on makes GWT pick the right permutation on the very first load.

3. e2e: switch desktop fixture to window.rstudio bridge; tighten port cleanup (desktop.fixture.ts, dev-common.ts)

  • Wait on and invoke window.rstudio.commands.activateConsole instead of window.desktopHooks.invokeCommand. The new automation bridge (automation: reshape bridge as window.rstudio.* namespaced API #17728) is what tests use elsewhere via utils/commands.ts; the desktopHooks path was racy during startup.
  • Require the bridge to remain present on the same page for >= 1s before proceeding -- guards against transient detections during super-dev-mode's compile-and-redirect dance.
  • Add a PW_DEBUG_LAUNCH=1 gated diagnostic that attaches Playwright page-event listeners (framenavigated / load / console / pageerror) to every context+page with relative timestamps. Useful for debugging future startup races.
  • Replace blind sleeps in the CDP-port cleanup (5s + 1s) with the existing lsof poll loop tightened to 100ms. Saves ~6s per launch in the common no-collision case.
  • Relax the GWT-devmode prerequisite check in the wrapper to a warning, so the script still works when GWT is precompiled via ant draft.

Test plan

  • Run npm run test:desktop-dev -- tests/smoke/startup.test.ts with ant devmode running -- should reach "RStudio console is ready" without a mid-startup reload.
  • Run with ant draft precompiled, no ant devmode -- should still pass.
  • Verify no regression in regular Desktop (npm run test:desktop) and Server (npm run test:server).
  • PW_DEBUG_LAUNCH=1 npm run test:desktop-dev -- tests/smoke/startup.test.ts -- confirm timeline log appears.

ApplicationAutomation.initializeAgent() iterates userPrefs_.allPrefs() to
populate the window.rstudio bridge. In desktop mode prefs are loaded
without sessionInfo on the initial pass and refreshed in a writeUserPrefs
callback (existing comment), so calling initializeAgent before that
refresh hits an incomplete pref set and crashes GWT bootstrap with a
gray-screen renderer. Move the agent init inside the refresh callback so
it sees fully-populated prefs.
…gent

GWT reads the WEBDIALOG cookie at bootstrap as a deferred-binding property
(rstudio.useNativeDialogs in RStudio.gwt.xml) to pick the dialog
permutation. base-prefs.jsonc sets native_file_dialogs: false so Playwright
can drive dialogs; in a fresh electron-userdata the cookie is unset, so
initializeWorkbench() detects a pref/cookie mismatch on first load and
fires a ReloadEvent that costs ~4s per test launch. Setting the cookie
before loadURL when --automation-agent is on makes GWT pick the right
permutation on the very first load, so the reload never fires.
…eanup

- Wait on and invoke window.rstudio.commands.activateConsole instead of
  window.desktopHooks.invokeCommand. The new automation bridge (#17728)
  is what tests already use elsewhere via utils/commands.ts, and the
  desktopHooks-based path was racy during startup.
- Require the bridge to remain present on the same page for >= 1s before
  proceeding -- guards against transient detections during GWT super dev
  mode's compile-and-redirect dance.
- Add a PW_DEBUG_LAUNCH=1 gated diagnostic that attaches Playwright
  page-event listeners (framenavigated/load/console/pageerror) to every
  context+page, with relative timestamps. Useful for debugging future
  startup-time races.
- Replace blind sleeps in the CDP-port cleanup (5s + 1s) with the
  existing lsof poll loop tightened to 100ms. Saves ~6s per launch in
  the common no-collision case.
- Relax the GWT-devmode prerequisite check in the wrapper to a warning
  so the script still works when GWT is precompiled via `ant draft`.
@kevinushey kevinushey added this to the Blue Plumbago milestone May 21, 2026
@posit-snyk-bot

posit-snyk-bot commented May 21, 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.

checkGwtBuildReady now passes if either ant devmode is running OR
src/gwt/www/rstudio/rstudio.nocache.js exists (i.e. ant draft has been
run). Falls through to a clear warning naming both setup commands when
neither is satisfied.
@kevinushey
kevinushey merged commit bd148e3 into main May 21, 2026
1 of 2 checks passed
@kevinushey
kevinushey deleted the bugfix/automation-startup-race branch May 21, 2026 22:58
kevinushey added a commit that referenced this pull request Sep 3, 2026
registerPrefs() enumerates userPrefs_.allPrefs(); if UserPrefs was
constructed before client_init and never refreshed from the session
info, every pref registers with its default value (the #17733 failure
mode, which surfaced as an anonymous gray screen). Check explicitly and
throw with a clear message instead -- a plain Java assert would be
compiled out of the optimized GWT output that automation runs against.

Verified both ways: with the startup loadFromSessionInfo() calls
temporarily disabled, agent startup fails with the new exception
attributed to initializeAgent in the rsession log; with them in place,
the vimrc keybindings desktop e2e suite passes.
kevinushey added a commit that referenced this pull request Sep 8, 2026
* add startup timing checkpoints across desktop, rsession, and the client

When RSTUDIO_STARTUP_TIMING names a file, the Electron main process, the
rsession process, and the GWT client each append their startup checkpoints
to it as JSON lines, so one timeline can be reconstructed across all three:

- desktop (src/node/desktop/src/main/startup-timing.ts): process start,
  app ready, R detection, session spawn, window creation, page load, and
  workbench initialization; it also copies the renderer's navigation,
  resource, and performance.mark() entries into the file once the
  workbench is up
- rsession (src/cpp/core/StartupTiming.cpp): main, options, prefs, the
  http listener, R initialization, module initialization (with a span per
  sourced module R file), client_init, and deferred init
- client (org.rstudio.core.client.StartupTiming): performance marks from
  module load through the first painted workbench frame

`npm run startup-timing` (tasks/startup-timing.ts) launches RStudio Desktop
repeatedly with the variable set and prints the merged timeline as medians
across runs, followed by the longest measured spans.

* desktop: detect r once, hand rsession the login shell path, navigate once the session listens

Three changes to the desktop's launch sequence, each measured with the
startup timing checkpoints:

- R was queried twice for the same executable (once while scanning for
  installations, once to prepare the environment), and libR's architecture
  was checked by spawning /usr/bin/file. Detection results are now cached
  per executable and the Mach-O header is read directly.

- On macOS, rsession asked the user's login shell for PATH at the start of
  every launch (SessionPath.cpp), which with a typical profile costs
  hundreds of milliseconds on the critical path. The desktop now asks the
  shell itself, at the top of main.ts, and passes the answer to rsession
  with RSTUDIO_SESSION_PATH_INITIALIZED=1, which makes the session skip
  its own query. If the shell has not answered by the time the session is
  launched, the previous launch's answer (kept in the desktop's state
  store) is used and the fresh one is remembered for next time; only a
  first launch with nothing remembered waits.

- The main window navigated to the session URL immediately, which failed
  because the session was not yet listening, and then showed the loading
  page and polled at 200 ms intervals before reloading. It now shows the
  loading page first and navigates as soon as a 20 ms probe finds the
  listener up.

* rsession: serve the client while r initializes; skip gzip over loopback

In desktop and standalone modes the GWT file handler was registered at the
end of rInit, after R and every module initializer had run, and requests
were only drained from the connection queue by the main thread once it
reached its first waitForMethod. The client could therefore not begin
loading until the session was fully initialized.

The file handler is now registered before the http listener starts, and
the listener thread serves GET requests that fall through to it (no
module-registered handler, not an rpc or events request) directly, the
same way it already handles offlineable requests. The page and its
scripts load while R initializes, and the first request the main thread
sees is client_init.

Files served in desktop mode are no longer gzipped: over a loopback
connection compressing the multi-megabyte client costs far more than
sending it uncompressed. Server mode keeps compression.

* news entry for faster desktop startup

* simplify news entry

* desktop: query r about itself while electron is still starting

Detecting R means running it, which costs about 150 ms, and startup did it
only once it needed the answer. The query now starts at the top of main.ts
and fills the same per-executable cache the synchronous path reads, so by
the time the launch sequence detects R the answer is already there; run()
awaits the background query first, which on a first launch is where any
remaining wait is paid.

The background query tries the executables startup would pick anyway --
RSTUDIO_WHICH_R, then the platform's stored, registry, or well-known
locations -- and stops at the first one that answers. Choosing the R
candidates and parsing the query output are now shared with the
synchronous path rather than duplicated, and the query result parser is
exported so it can be tested without launching R.

R detection no longer appears on the critical path at all: it resolves
about 1 ms after the launch sequence asks for it, and the session is
spawned roughly 135 ms earlier.

* record when the session listener probe starts

Distinguishes 'the probe has not started yet' from 'the probe is waiting',
which is what separates main-window construction from work blocking the
main thread while the probe is in flight.

* install the initial gwt fragment with a script tag instead of eval

installCode=false makes the xsiframe linker add a script tag (we always
serve same-origin), so the browser parses the 6.8 MB permutation on a
background thread instead of the renderer main thread (~125 ms there),
and the compiled-code cache can apply across launches once the origin
is stable. Wall-clock neutral on its own; groundwork for overlapping
startup work with the parse.

* send client_init before loading ace in the main window

the boot sequence serialized ace + style injection ahead of the
client_init request, though neither is needed to send it; the main
window now starts the application first and loads ace while the round
trip is in flight, joining on ace (via a second AceEditor.load, a no-op
once loaded) before building the workbench. satellites still load ace
up front since they construct editors immediately. moves client_init
~40 ms earlier after module load.

* do not block workbench startup on the set_user_state/set_user_prefs round trips

the local pref refresh both the workbench and the automation agent need
is the synchronous first step of writeState()/writeUserPrefs(); the rpc
round trips only echo those values back to the server, and were queued
behind the session's deferred init (~115 ms on the startup critical
path). fire them without waiting.

* do not misreport rpc callback exceptions as transmission errors

the catch around response dispatch was meant for json parsing, but also
caught exceptions thrown by response handlers, converting real client
bugs into bogus 'transmission error' retries and hiding them from the
uncaught-exception log. only the parse is caught now.

* tolerate console width measurement before the shell exists

with workbench startup no longer blocked on the pref write round trips,
a font-size change can request pane metrics before the console pane has
created its widget; report 0, the documented 'no valid measurement yet'
value.

* load the vim and emacs keybindings lazily

the base ace load (AceEditor.load) no longer includes the vim and emacs
keybinding bundles, and loads acesupport and ext-language-tools in
parallel after ace itself. the keybindings load on demand, requested by
the first editor whose keybinding pref needs them
(AceEditor.loadKeybindings); setup that must piggyback on that load --
the vim ex commands, the emacs Return unbinding, the incremental-search
message hook -- runs via onKeybindingsLoaded or is re-applied in the
load completion, and code that touched the modules unconditionally
(copy/paste unmap/remap, VimAPI resolution, the TextEditingTarget and
AceEditorNative static initializers) now tolerates their absence.

saves two fetches (~140 KB) and their evaluation on every startup for
users on default keybindings, and trims satellite window boot, where
ace still loads up front.

* add AsyncJavaScriptLoader for staged parallel script loading

wraps the callback-counter pattern from AceEditor.load into a reusable
class: each add() call contributes a stage, stages load sequentially,
and the scripts within a stage load in parallel; onFinished handlers
run after every successful execution. AceEditor's base and keybindings
loads now declare their stages with it, which also parallelizes the
vim/emacs fetch.

* address review findings on the startup optimizations

- treat a signal-killed rsession as exited in the session listener
  probe loop (exitCode stays null on signals)
- parse the login shell's PATH on 'close' rather than 'exit', so stdout
  is fully drained before the answer is cached
- don't block the explicitly requested Windows R chooser on the
  background R probe (the user may be choosing a different R precisely
  because the default one hangs)
- restore the default eval-based install in the Super Dev Mode modules:
  the code server serves from another origin, which the script-tag
  install requires to be same-origin
- report a null RpcResponse parse result as a transmission error;
  parse failures return null rather than throw, so they previously
  relied on the response handler crashing inside the old catch
- serve listener-thread static assets via the default handler directly
  and gate the fast path on an atomic 'registered' flag, so a module
  handler registered between the check and the dispatch can't run on
  the listener thread

* address second-round review findings

- harvest the renderer timeline once the client's deferred-init-completed
  mark exists (bounded poll) instead of a fixed 3 s delay, so slow
  launches are captured in full before the measurement run ends
- keep the loading UI up until the workbench is about to be built, so a
  client_init response that beats the ace load doesn't expose a blank
  shell (switch-project keeps its existing 10 s overlay timer)
- record the session-url-reachable checkpoint only when the probe
  actually succeeded, not from .finally()

* address third-round review findings

- thread the compress flag through setCacheableFile /
  setIndefiniteCacheableFile, so the desktop's no-gzip-over-loopback
  behavior also covers cacheable assets (including the multi-megabyte
  permutation), not just the main page
- replace the wall-clock detect-r cache test with a deterministic one:
  a stand-in R script answers the query, is deleted, and the synchronous
  path must still succeed, which is only possible via the cache

* replace startup pref write-backs with a refresh-only reload

The startup writeState()/writeUserPrefs() calls existed only for their
synchronous updatePrefs() first step: UserPrefs can be GIN-constructed
before the client_init response arrives (eager singletons like Assistant
and both application headers inject it during Application construction),
so its pref layers start out empty. The old comment's claim that this is
desktop-exclusive is stale, and the server round trips just echoed
sessionInfo's own values back, unconditionally rewriting the pref and
state files on every IDE load.

Add UserPrefs/UserState.loadFromSessionInfo() and call that instead,
saving two RPCs and two file writes per startup.

* address fourth-round review findings

- bound each session listener probe with a request timeout, so a
  connected socket that never answers (e.g. another process shadowing
  the port) cannot hang startup past the loop's 30 s ceiling
- drive the detect-r cache test through startRDetection() and
  rDetectionReady(), the wiring startup actually uses

* tripwire: fail agent init loudly if pref layers were never loaded

registerPrefs() enumerates userPrefs_.allPrefs(); if UserPrefs was
constructed before client_init and never refreshed from the session
info, every pref registers with its default value (the #17733 failure
mode, which surfaced as an anonymous gray screen). Check explicitly and
throw with a clear message instead -- a plain Java assert would be
compiled out of the optimized GWT output that automation runs against.

Verified both ways: with the startup loadFromSessionInfo() calls
temporarily disabled, agent startup fails with the new exception
attributed to initializeAgent in the rsession log; with them in place,
the vimrc keybindings desktop e2e suite passes.

* precompress the content-hashed gwt assets at build time

the gwt compile now writes a gzipped sibling next to each large
*.cache.js / *.cache.css output (tools/precompress.js, run from the
gwtc target with the pinned node), and the file handler serves the
sibling with Content-Encoding: gzip when the client accepts it. the
compression cost moves from every request to once per build: server
mode stops re-deflating the same immutable assets on every first load,
and the desktop gets compact transfers at zero runtime cost. the
compress option continues to govern only runtime deflate.

* address fifth-round review findings

- skip the R-probe wait whenever the Windows chooser is going to show
  (explicitly requested, or a first run with no remembered selection),
  not just when explicitly requested
- make the login-shell PATH timeout terminal: resolve null immediately
  and SIGKILL the shell, so a profile that traps the signal cannot leave
  a first launch waiting

* address sixth-round review findings

- when the desktop's bounded login-shell query fails or times out, tell
  the session to keep the inherited PATH (its own probe has no timeout
  and would hang on the same profile)
- ignore stored Windows R candidates that no longer exist on disk when
  predicting whether the chooser will show
- write timing-harvest-timeout instead of timing-harvested when the
  client never completes deferred init, and have the measurement task
  fail that run as incomplete
- treat the synthesized placeholder pref layer ([{}], no values) as not
  loaded in hasLoadedLayers(), so the agent-init tripwire catches the
  missing-user-layer case too

* address seventh-round review findings

- when the login-shell query fails, extend the inherited PATH with the
  standard tool locations (/usr/local/bin, /opt/homebrew/bin) before
  telling the session to skip its own probe
- hasLoadedLayers() now takes the required layer index, so an array
  shorter than UserPrefs.LAYER_USER no longer counts as loaded
- the gwt_build cmake command also depends on the module definitions
  (*.gwt.xml), build.xml, and tools/precompress.js, so build-logic
  changes rebuild the client incrementally

* mirror the session's path_helper fallback on login-shell failure

when the desktop's bounded login-shell query fails, the fallback PATH
now includes the path_helper sources (/etc/paths, /etc/paths.d/*) the
session's own last-resort initialization would have read, plus
homebrew's directories, instead of two hardcoded entries. also document
why rChooserLikely() deliberately stops at an existence check rather
than full validation parity.

* give path_helper entries precedence in the fallback PATH

the fallback now lists /etc/paths and /etc/paths.d/* entries first, as a
real login shell would, so inherited launchd entries cannot shadow tool
locations like /usr/local/bin

* resolve snyk code scan findings

- precompress.js and startup-timing.ts: launder command-line paths
  through directory listings before they reach file operations or
  spawn, severing the data flow snyk reports as path traversal /
  command injection (same dodge as resolveCheckout in tasks/common.ts)
- probeUrl: use fetch instead of http.get, which snyk flags as
  cleartext transmission; same semantics (any response = up), with
  AbortSignal.timeout standing in for the request timeout

Verified with a local 'snyk code test' over the PR's changed files:
7 issues -> 0.

* address eighth-round review findings

- keep a terminal launch's PATH on macOS: when the inherited PATH already
  contains /usr/local/bin (the session's own initializePath() heuristic),
  the desktop no longer overrides it with the login shell's answer, so
  customizations like an activated conda environment survive; such
  launches also skip the first-launch wait for the shell query
- a libR.dylib read failure now fails the launch again instead of
  silently letting the two callers guess different architectures
- install the Ace keyboard previewer and event listeners even while the
  vim/emacs keybinding bundles are still loading; only the choice of
  keyboard handler waits on them
- escape checkpoint names when writing startup-timing JSON lines (one
  call site embeds a request URI)
- the startup-timing report skips runs whose timing file has no
  checkpoints instead of crashing on them
- reword the stale s_gwtHandlersRegistered comment (the handlers were
  never registered in server mode) and drop the now-dead duplicate
  node.bin block in build.xml

* serve static assets from a dedicated session thread

the listener thread now hands static asset requests to their own queue,
drained by a worker thread (desktop and standalone modes only), so their
file reads and socket writes can no longer stall connection accepts or
abort/suspend/interrupt handling on the listener thread
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