Repository navigation
e2e: pre-populate r library, fix nb.html test, console-to-bridge refactor - #17716
Merged
Merged
Conversation
…ctor
Pre-populated R user library
- New fixtures/r-libs-setup.ts defines a REQUIRED_PACKAGES manifest and
prepares a stable per-host library at ~/.cache/rstudio-playwright/r-libs/%p/%v
(Windows: %LOCALAPPDATA%\rstudio-playwright\r-libs\%p\%v). globalSetup
expands the R_LIBS_USER template via Rscript, mkdir -p's the resolved
path, and installs anything missing -- idempotent on a warm cache.
- desktop.fixture.ts and server.fixture.ts both spawn rsession with the
matching R_LIBS_USER so RStudio sees the populated lib under the
redirected HOME. Without this, rmarkdown's dependency check fired a
"stringr needs updating" prompt and hung tests like the nb.html one.
- New env vars: PW_RSTUDIO_R_LIBS_USER (override template),
PW_RSTUDIO_R_LIBS_SKIP_PREP (skip prep).
nb.html test fix
- saveSourceDoc is disabled when the editor matches disk (createAndOpenFile
+ executeCurrentChunk both leave the doc clean), so the previous bridge
call was a silent no-op and NotebookHtmlRenderer.onSaveFile never fired.
Add an Enter to dirty the doc, then Ctrl+S, then poll the sandbox for
the .nb.html.
npm scripts
- test:dev (PW_RSTUDIO_DEV=1) and test:server (--project=server) for the
common non-default flavors. Other combinations remain env-var driven.
Console-to-bridge refactor (separate effort, bundled here)
- Replace `.rs.api.executeCommand('X')` typed into the console with the
executeCommand bridge helper, and `.rs.api.closeAllSourceBuffersWithoutSaving()`
with documentCloseAllNoSave. Avoids the R-side round trip and the
console history pollution.
tsconfig: bump target to ES2022 and silence the TS 6 deprecation warnings.
playwright.config.ts: typed ProjectOptions on defineConfig.
README updates the Environment Variables table and Package Dependencies
section to describe the new infrastructure.
Contributor
✅ Snyk checks have passed. No issues have been found so far.
💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse. |
1 of 2 tasks
kevinushey
added a commit
that referenced
this pull request
May 23, 2026
The 'Source columns can be created and closed' test creates three source columns then asserts the column containers go away. #17716 swapped its closeAllSourceDocs (the AppCommand, which closes empty columns as part of its teardown) for documentCloseAllNoSave (the bridge call, which only closes documents and leaves the column containers behind). That made the assertions un-passable; the test had been failing since. Revert the close path back to the AppCommand for this specific test -- documentCloseAllNoSave is still the right shape for the many other tests that just want a clean source pane for the next test, but not when we're asserting on the columns themselves.
kevinushey
added a commit
that referenced
this pull request
May 23, 2026
…7755) * playwright: sweep remaining blind sleeps + appearance theme guard Replace remaining sleep(N) calls across e2e/rstudio/ tests with deterministic waitFor / expect.poll style waits. Adds a waitForActiveDocument helper in utils/commands.ts that polls window.rstudio.documents.active() until the focused doc path matches, useful as a post-condition for file.edit / documentOpen flows. Also fixes a latent race in AppearancePreferencesPane.onApply: themeList_ is populated asynchronously by setThemes(), so clicking OK before themes load NPEs on themeList_.get(...). Skip the theme apply when themeList_ is null -- the dropdown is empty in that case so there's nothing the user could have selected. For air_formatting.test.ts, closeOptions retries OK clicks up to 10x at 200ms intervals to absorb the residual validate() race on dialog close, warning on retry so any recurrence surfaces a precise reproducer. TextEditingTarget.reformat now collapses the selection on completion (built-in and server paths) so the post-reformat state is observable even when the formatter produced identical output. * playwright + automation bridge: pref-RPC await, AppCommand-based restart Bridge / Java - ApplicationAutomation.setPrefValue / clearPrefValue now accept a JS callback wired to writeUserPrefs's completion. The bridge's set / clear return a Promise that resolves only after the setUserPrefs RPC lands on the server, so callers can be sure the pref is observable in R / the session-side cache before doing anything dependent on it. - TextEditingTarget.withFormatContext drops cached air.toml only when the cache is empty AND useAirFormatter is enabled, falling through to the RPC path. Avoids false-built-in formatting when air.toml was created mid-session and the file monitor hasn't yet populated the cache. restartSessionWithSentinel - Switched from `.rs.api.restartSession(command = cat(...))` typed into the console to the restartR AppCommand via the bridge. The console_input RPC path was racing the in-flight shutdown, surfacing as Error: Unable to establish connection with R session when executing 'console_input' Readiness signal is window.rstudio.ready (flipped on RestartStatusEvent.RESTART_INITIATED -> false and DeferredInitCompletedEvent -> true) plus a waitForConsoleIdle tail. Marker format - All "session is up" markers now use `[pw:<event-name> <id>]`: restart-session-ready, project-opened, session-restart-ready. Three separate sources used to share the `__READY_<ts>__` prefix, which made cross-restart logs ambiguous. Tests - utils/commands.ts setPref / clearPref await the bridge Promise so the RPC has landed by the time they return. - reformat.test.ts:105 uses an empty AceEditor marker -- the previous '# placeholder' marker stopped matching once Ctrl+A + type replaced the file's contents. - rmarkdown.test.ts uses a 5s lead-in before checking the interrupt button has hidden post-restart (very short chunks were too brief for the polled expect-visible to catch). - pane_location_persistence.test.ts restores the defensive "if (!isChecked) click" toggle after a reset link click; the prior expect.poll for true assumed sidebar-on-by-default, which isn't guaranteed. - close_open_race.test.ts marks the View() race variant test.fixme; iframe loading during HIDE animation needs separate investigation. - project_id.test.ts, create_projects.test.ts, project_trust_dialog.test.ts pick up the new marker format. * air_formatting: drop closeOptions retry loop The retry loop in closeOptions was actively breaking the test it was meant to stabilize. attemptSaveChanges -> setUserPrefs RPC -> onResponseReceived -> closeDialog is an async chain that takes a server round-trip. The previous helper retried the OK click on a 200ms toBeHidden window, which was nowhere near enough for the RPC to land -- so it would retry, find the OK button already gone from the DOM (the *first* click actually worked), and hang on locator.click waiting for actionability. Diagnostic instrumentation revealed every retry was clicking against "no #rstudio_preferences_confirm element in DOM" -- the dialog had already closed. Simplified to a single click followed by toBeHidden with a 15s window that comfortably covers the RPC. * playwright: isolate cross-file state in debugger + air_formatting Two cross-file state leaks that surfaced as flaky failures only when the full suite ran: debugger.test.ts:94 / debugger.test.ts:206 (flake pattern: pass in isolation, fail in full suite) - Add a defensive "if R is in debug mode, get out" step to the beforeAll in both debugger.test.ts and debugger_extras.test.ts. A prior test file (or an earlier test in a serial chain whose resetAfterTest's stopDebug best-effort didn't fully drain) could leave R at Browse[N]>. Once that happens, the first waitForDebugMode returns instantly against the stale state and getActiveDebugLineRow throws "no visible debug line" because the debug marker is in a hidden editor tab from the previous session. editor.test.ts:44 (trailing whitespace, flake pattern: pass in isolation, fail in full suite) - air_formatting.test.ts opened an 'air_formatting' project in beforeAll but had no afterAll to close it. Later test files inherited the open project context, and TextEditingTarget.maybeFormatOnUserInitiatedSave reads projConfig_.stripTrailingWhitespace() when a project is active -- which defaults to FALSE and silently overrides the global pref the test had just set. - Adds an afterAll to air_formatting.test.ts that calls closeProjectIfOpen, documenting the cross-file contract. * playwright: shared per-test reset helper Add utils/test-reset.ts with resetForNextTest(page) and call it from the shared beforeEach in fixtures/rstudio.fixture.ts. Centralizes the recurring "make sure the prior test didn't leave broken state behind" checks so individual test files don't have to repeat them. What it covers: - Save-changes dialog (Don't Save). Replaces the inline beforeEach in the fixture; previously was the only universal cleanup. - R debug mode. A previous test that didn't drain its continueDebug / waitForDebugExit leaves R at Browse[N]>, which makes the next test's waitForDebugMode return instantly against the wrong session. - Source pane buffers. resetSourcePaneState (kept-or-created Untitled + close everything else), specifically NOT closeAllSourceDocs so the pane never goes through the HIDE animation that races a following file.edit / View() (#17738). What it explicitly doesn't cover (documented inline): - Prefs. Tests own their own pref state in afterAll. - Open projects. Some test files want a project context; the convention remains "the file that opens a project closes it in afterAll". - Working directory. useSuiteSandbox already scopes cwd. Each step short-circuits cheaply when its trigger isn't present, so the common case (clean session) adds ~tens of ms per test. Removes the now-redundant beforeAll defensive cleanup from debugger.test.ts / debugger_extras.test.ts since the per-test reset covers the same ground earlier. * test runners: log Playwright launcher PID on start A stuck full-suite run can take several minutes to abort cleanly because the npx -> playwright -> worker -> Electron -> rsession process tree respawns its children when individual levels are killed. Print the launcher PID up front so users can kill the right process (the launcher will tear down everything beneath it in one shot). Switched runPlaywright from spawnSync to spawn for this -- spawnSync returns after the child exits, which is too late for a "kill this to abort" hint to be useful. The script's event loop stays alive via the inherited stdio anyway, so we just register an 'exit' handler that propagates the child's status and let the loop run. Also fixes a latent gap where signal-killed runs (SIGTERM, SIGINT) previously exited with whatever undefined-ish status spawnSync surfaced; now we report 128 + signal number per shell convention. * test-reset: wait for resetToUntitled to settle + restore console focus Two follow-ups after wiring up the per-test reset: 1. Wait for the active doc to actually be Untitled (path === null) before returning. r.documents.resetToUntitled() dispatches a GWT event whose handler does its work asynchronously (closing tabs, possibly creating a new Untitled); page.evaluate returns the instant the dispatch enqueues, NOT when the handler finishes. Without the wait, a test running immediately after the reset could see the source pane mid- transition. 2. End the reset with `activateConsole` so every test starts with the console focused. resetToUntitled's handler moves focus to the kept / newly-created Untitled tab; the first test action that needs console focus (clearConsole, executeInConsole) would otherwise race that in-flight focus shift and time out in waitForConsoleFocus. This was surfacing as 5s failures on tests that just use the console (release-notes, ansi_erase_in_line) immediately after the per-test reset landed. The settle-wait is best-effort (.catch swallows): a 5s miss falls through to the activateConsole, and any latent staleness surfaces as a more precise assertion failure in the test itself rather than a bare reset-helper timeout. * panes.test.ts: use closeAllSourceDocs to verify empty columns close The 'Source columns can be created and closed' test creates three source columns then asserts the column containers go away. #17716 swapped its closeAllSourceDocs (the AppCommand, which closes empty columns as part of its teardown) for documentCloseAllNoSave (the bridge call, which only closes documents and leaves the column containers behind). That made the assertions un-passable; the test had been failing since. Revert the close path back to the AppCommand for this specific test -- documentCloseAllNoSave is still the right shape for the many other tests that just want a clean source pane for the next test, but not when we're asserting on the columns themselves. * more tweaks * test-reset: fully drain resetToUntitled + surface closeOptions blockers Two cross-file isolation fixes that resolved the remaining flakes in debugger.test.ts (top-level breakpoint, Step Next), air_formatting.test.ts (#3, #7), and editor.test.ts (trailing whitespace) when the full suite ran. resetForNextTest: - Bump the debug-exit waitFor from 5s to 15s and log a clear warning if it still misses. A 5s ceiling that silently swallows its timeout lets the next test run against a stale debug toolbar; waitForDebugMode then returns instantly and getActiveDebugLineRow looks for a marker in a hidden editor tab from the previous session. - After resetSourcePaneState, require BOTH active doc being Untitled AND exactly one source tab remaining in the DOM before returning. The old wait was satisfied as soon as focus switched to the Untitled, often well before the close-all CPS chain had actually closed the other tabs. Lingering tabs (and their hidden Ace editors) were bleeding state into subsequent tests. closeOptions (air_formatting): - On toBeHidden timeout, check for the #rstudio_dlg_ok message-dialog button. attemptSaveChanges silently no-ops when any pane's validate() returns false AND that pane pops up an error modal via GlobalDisplay.showErrorMessage, leaving the prefs dialog wedged open forever. Re-raise with the modal's text so a recurring miss surfaces a precise reproducer instead of a generic toBeHidden error.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
~/.cache/rstudio-playwright/r-libs/%p/%v(Windows:%LOCALAPPDATA%\rstudio-playwright\r-libs\%p\%v) and plumbsR_LIBS_USERthrough Desktop and Server fixtures, so RStudio sees a populated library under the redirectedHOME. Without this, rmarkdown's dependency check would prompt to update stringr mid-test (the issue that surfaced when investigating the nb.html test).rmarkdown_chunks.test.ts:saveSourceDocis disabled when the editor matches disk, so the previous bridge call was a silent no-op. Dirties the doc withEnterbeforeCtrl+SsoNotebookHtmlRenderer.onSaveFileactually fires.typeInConsole(\".rs.api.executeCommand('X')\")(and.rs.api.closeAllSourceBuffersWithoutSaving()) to the bridge helpers (executeCommand,documentCloseAllNoSave) -- avoids the R-side round trip and console-history pollution.test:dev(PW_RSTUDIO_DEV=1) andtest:server(--project=server); other combinations remain env-var driven.PW_RSTUDIO_R_LIBS_USER(override the template) andPW_RSTUDIO_R_LIBS_SKIP_PREP(skip pre-population); both documented in the README.ignoreDeprecations: \"6.0\"to silence TS 6 warnings. playwright.config.ts: typedProjectOptionsondefineConfig.Test plan
npx playwright test rmarkdown_chunks.test.ts -g \"nb.html\"-- nb.html generation test passes (9.4s); globalSetup installs the 23 packages + transitive deps on first run.PW_RSTUDIO_DEV=1 npx playwright test rmarkdown_chunks.test.ts -g \"nb.html\"-- passes (9.3s); warm-cache library prep is a no-op; no teardown error against the dev build's bridge.