Skip to content

automation: reshape bridge as window.rstudio.* namespaced API - #17728

Merged
kevinushey merged 1 commit into
mainfrom
feature/rstudio-namespace-api
May 21, 2026
Merged

kevinushey merged 1 commit into
mainfrom
feature/rstudio-namespace-api

Conversation

@kevinushey

Copy link
Copy Markdown
Collaborator

Intent

Addresses #17724 and #17725.

Summary

Replaces the flat window.rstudioCallbacks automation surface with a namespaced one at window.rstudio. Every AppCommand and every PrefValue is enumerated at agent init and registered as a typed JS object:

window.rstudio.commands.<id>()             // execute
window.rstudio.commands.<id>.isChecked()
window.rstudio.commands.<id>.isEnabled()
window.rstudio.commands.list               // string[] of all command ids

window.rstudio.prefs.<camelName>.get()
window.rstudio.prefs.<camelName>.set(value)
window.rstudio.prefs.<camelName>.clear()

window.rstudio.documents.closeAllNoSave()

window.rstudio.project.path()              // active project file or null
window.rstudio.project.name()
window.rstudio.project.isActive()

The enumeration is the cure for #17724: calling userPrefs_.allPrefs() at agent init forces every UserPrefsAccessor factory to run, which registers the corresponding PrefValue in Prefs.values_. Before this, looking up a pref the GWT code hadn't already accessed returned null, and the bridge's pref == null throw was silently swallowed by GWT's $entry wrapper -- so test calls like setPref('default_project_location', sandbox.dir) no-op'd and the wizard saw the wrong (default) value. With the warm-up, every pref is addressable by name from the first call.

The project namespace gives tests a precise readiness signal after closeProject, which on Desktop tears down the project-bound page and rebuilds the workbench. utils/project.ts's closeProjectIfOpen now polls rstudio.project.isActive() === false rather than just waiting for the console to come back -- the console can settle a few hundred ms before the Files pane refreshes, and a Files-pane refresh racing the rsession's home-dir hand-off was popping an "Error navigating to ~" modal. closeProjectIfOpen also dismisses any such modal as a defensive last step. tests/projects/ignorefiles.test.ts drops its duplicate local copy of closeProjectIfOpen and imports the canonical one.

Drive-bys bundled in

  • electron-desktop-options.ts wraps every config.set in a safeSet() helper. electron-store persists via temp-file + renameSync, and that rename can race against external cleanup of the user-data-dir (Playwright sandbox teardown). The error was popping Electron's "JavaScript error in main process" modal mid-shutdown. Settings are best-effort persistence -- the read paths already fall back to defaults -- so we now log and continue.
  • shutdownRStudio wraps the first documentCloseAllNoSave in try/catch. If a test left the page mid-navigation (e.g. opening a project triggers a session restart that swaps the page), page.evaluate rejects with "context destroyed" and the rest of shutdown (q(), poll + force-kill) would skip. The bridge call is no longer load-bearing -- the force-kill fallback covers it.

Caller migration

utils/commands.ts is rewritten against the new shape; the public API (executeCommand, setPref, getPref, clearPref, isCommandChecked, isCommandEnabled, documentCloseAllNoSave) keeps its existing function signatures, so test call sites don't change. Pref names stay snake_case at the TS API boundary and are converted to camelCase internally before the bridge lookup.

Test plan

  • npm run typecheck (e2e/rstudio) clean
  • ant draft (src/gwt) clean
  • npm run typecheck and npm run lint (src/node/desktop) clean
  • Rscript scripts/generate-options.R regenerated ServerOptions.gen.hpp
  • npm run test:dev -- tests/projects/ignorefiles.test.ts passes -- the canonical victim of Automation bridge: prefSet/prefGet/prefClear silently fail for prefs not yet registered #17724 now succeeds end-to-end
  • Full npm run test:dev -- --grep-invert @ai -- attempted locally but the host went to sleep mid-run, so the 16-failure / 35-did-not-run result isn't trustworthy. Will rely on CI.

Replaces the flat window.rstudioCallbacks surface with a namespaced one at
window.rstudio. ApplicationAutomation.initializeAgent() now enumerates every
AppCommand and every PrefValue at startup and registers a typed JS object
per entry:

  window.rstudio.commands.<id>()             // execute the AppCommand
  window.rstudio.commands.<id>.isChecked()
  window.rstudio.commands.<id>.isEnabled()
  window.rstudio.commands.list               // string[] of all command ids

  window.rstudio.prefs.<camelName>.get()     // current value (any layer)
  window.rstudio.prefs.<camelName>.set(v)    // user-layer + writeUserPrefs
  window.rstudio.prefs.<camelName>.clear()   // remove user value

  window.rstudio.documents.closeAllNoSave()

  window.rstudio.project.path()              // FileSystemItem string or null
  window.rstudio.project.name()
  window.rstudio.project.isActive()

The enumeration is the cure for #17724 (silent failure of prefSet/prefGet/
prefClear when the pref hasn't been touched by some other GWT code yet):
calling userPrefs_.allPrefs() at agent init forces every factory to run and
populate Prefs.values_, so every preference is addressable by name from the
first call. The flat callbacks (commandExecute, prefSet, ...) are gone.

The project namespace gives tests a precise readiness signal after a
project close, which on Desktop tears down the project-bound page and
rebuilds the workbench. utils/project.ts's closeProjectIfOpen now polls
window.rstudio.project.isActive() === false instead of just waiting for
the console to become non-busy -- the console can settle a few hundred ms
before the Files pane finishes refreshing, and a Files-pane refresh
racing the rsession's home-dir hand-off was popping an "Error navigating
to ~" modal. closeProjectIfOpen also dismisses any such modal as a
defensive last step. tests/projects/ignorefiles.test.ts drops its
duplicate local closeProjectIfOpen and imports the canonical one.

Drive-bys:
- electron-desktop-options.ts wraps every config.set in safeSet() so the
  atomic-write race between electron-store's renameSync and external
  user-data-dir cleanup (Playwright sandbox teardown) doesn't pop
  Electron's "JavaScript error in main process" modal. Settings are
  best-effort persistence; the read path already falls back to defaults.
- shutdownRStudio wraps the first documentCloseAllNoSave in try/catch:
  if a test left the page mid-navigation (e.g. opening a project), the
  page.evaluate would reject with "context destroyed" and the rest of
  shutdown (q(), force-kill) would skip. The bridge call is also no
  longer load-bearing for shutdown -- the force-kill fallback covers it.

Addresses #17724.
Addresses #17725.
@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.

@kevinushey
kevinushey merged commit c7ef5af into main May 21, 2026
1 of 2 checks passed
@kevinushey
kevinushey deleted the feature/rstudio-namespace-api branch May 21, 2026 21:09
kevinushey added a commit that referenced this pull request May 21, 2026
* automation: defer initializeAgent until after pref refresh

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.

* electron: pre-seed WEBDIALOG cookie when launched with --automation-agent

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.

* e2e: switch desktop fixture to window.rstudio bridge; tighten port cleanup

- 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`.

* e2e: accept precompiled GWT as an alternative to running devmode

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.
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