Skip to content

playwright: stabilize chat-pane e2e tests + add automation bridge - #17760

Merged
kevinushey merged 14 commits into
mainfrom
feature/e2e-ai-and-bridge
May 24, 2026
Merged

kevinushey merged 14 commits into
mainfrom
feature/e2e-ai-and-bridge

Conversation

@kevinushey

Copy link
Copy Markdown
Collaborator

Summary

Stabilizes the @ai chat-pane Playwright suite and adds the automation hooks needed to make blocking-state tests deterministic. The headline pieces:

  • Chat setup waits for the chat to actually be usable. dismissSetupPrompts now drives the workspace-trust overlay and polls chatTextarea until it's enabled, so subsequent assertions don't time out against a still-loading sign-in panel. Fails fast with an actionable message if seeded credentials are stale.
  • window.rstudio.chat.{state, blocked, history} surface. ChatPresenter publishes its lifecycle state (ready / starting / manifest-unavailable / unsupported-protocol / ...) at each transition so tests poll a deterministic value instead of racing the iframe content the live PAI backend re-renders.
  • chat_set_update_check_override RPC + JS bridge. Pins the next chat_check_for_updates response to a specific shape; one-shot consumption. Lets the deprecate-pai-blocking suite drive each blocking branch without Playwright HTTP mocking (route.fulfill produces status=0 in dev-mode Electron, which would otherwise take ChatPresenter down onCheckFailed).
  • deprecate-pai-blocking rewritten to use the new state + override surface. Dropped ~240 lines of doc.write + HTTP-route hacks; the suite now runs in ~16s and is deterministic.
  • chat-guardrails Allow for homebrew's version of libboost #3 scoped to the R-side guardrail. Asserts on the conversational outcome (refusal + path-scope context) instead of file presence on disk, since the assistant's separate write tool isn't subject to .rs.chat.withGuardrails.
  • executeInConsole hardening. Verifies the Ace editor was actually consumed after pressing Enter, retries on TimeoutError (with unconditional Escape to dismiss any popup), and surfaces a clear error including the command prefix when submission fails. Fixes a recurring "markers not found" downstream timeout.
  • panes.test.ts source-column lifecycle fix. Adds an ensureDoc step so each new source column has a tab before closeAllSourceDocs -- a column is removed only when its last tab is closed, so previously empty columns persisted.
  • AI credentials seeding by default. globalSetup copies ~/.positai/ and the GitHub Copilot config dir into the sandbox when present; AI-tagged tests skip with a clear reason instead of timing out when nothing is seeded.

Test plan

  • Full non-AI Playwright suite green (240/240 in 12.2m) -- ran via npm run test:desktop-dev -- --grep-invert \"@ai\".
  • Targeted @ai chat-pane tests green: chat-messaging, chat-guardrails, deprecate-pai-blocking (all six branches).
  • roborev reviews on the chat-state and override changes addressed and closed (jobs 677 / 678 / 681).
  • One full @ai pass against an environment with valid Posit AI + Copilot credentials before merge -- the Copilot tests still need a live language-server auth that this PR doesn't change.

kevinushey added 12 commits May 23, 2026 12:31
Add window.rstudio.project.open(path) to the automation bridge, dispatching
SwitchToProjectEvent with forceSaveAll=true so a save-changes prompt can't
deadlock automation. Going through SwitchToProjectEvent directly skips the
confirm-open and project-options-reentry branches in Projects.java.

createAndOpenProject now uses the new bridge helper instead of writing an
.Rprofile sentinel marker and polling console output for it. The readiness
signal is the same window.rstudio.ready flag the rest of the bridge already
relies on (flipped on the new session's DeferredInitCompletedEvent), and the
.Rproj file creation collapses to a single console roundtrip.
Seed AI provider credentials by default when the host has them. Previously
the PW_SANDBOX_SEED_POSITAI / PW_SANDBOX_SEED_COPILOT env vars were opt-in;
now globalSetup copies ~/.positai/ and/or the GitHub Copilot config dir
into the sandbox user-home automatically when those source dirs exist. It
sets PW_AI_SEEDED_POSITAI=1 / PW_AI_SEEDED_COPILOT=1 to advertise the
result. PW_SANDBOX_NO_SEED_CREDENTIALS=1 opts out for hosts that aren't
dedicated test accounts.

Add utils/ai-credentials.ts exporting requireAiCredentials(test, provider).
Each @ai test.describe calls it; tests skip with a clear "no credentials
seeded" reason when the matching PW_AI_SEEDED_* flag is unset, replacing
what was previously a 5-minute mysterious timeout when the host had no
credentials and the test waited for a completion that would never arrive.

Drop nine dead-weight sleeps from code_suggestions.test.ts. Each was
immediately followed by an expect().toBeVisible(...) or toHaveCount(0,
...) whose own timeout already gated on the right condition, so the
intervening sleep was pure latency. ~16s saved per provider, ~32s across
the parameterized suite.
Skip the per-run "ready to test" confirmation prompt -- after picking a
mode, just run. Surface test:desktop-dev first in the mode list when a
build/ directory exists at the repo root, since a developer with a local
build typically wants to test against it.
Three findings from roborev job 674:

- openProject() now also waits for the console-busy class to clear after
  ready=true, mirroring restartSessionWithSentinel. Without this a caller
  could land a console action into a still-busy post-switch session.
- requireAiCredentials() gates on a strict `=== '1'` comparison and
  sandbox-setup clears PW_AI_SEEDED_POSITAI/COPILOT before deciding
  whether to seed, so a stray "0" / "false" / inherited value can't smuggle
  past the skip check.
- ApplicationAutomation now also resets window.rstudio.ready on
  OpenProjectErrorEvent. project.open() preemptively flips ready=false to
  close the kQuit-arrival window; on the failure path ready would
  otherwise stay false forever and the helper would time out instead of
  surfacing the real error.
dismissSetupPrompts now polls until the chat textarea is actually enabled
(the only real "ready" signal), clicking through the TrustOverlay modal
along the way. Previously it returned as soon as install/update/trust
buttons were handled in a one-shot snapshot, leaving every downstream
test to time out on a disabled textarea when the trust dialog rendered
late or when seeded credentials were stale.

waitForChatReady fails fast with an actionable message if a Sign-In
button appears, since the test harness has no OAuth path -- a stale
refresh token (rotated by the host between globalSetup and test
execution) used to surface as a 15s "textarea disabled" timeout in
every chat test; now it surfaces once with "sign in on the host and
re-run".
Test 3 ("write outside project directory is denied") was asserting file
absence on disk, but the assistant has a built-in write tool that isn't
subject to .rs.chat.withGuardrails -- so the file existed when the
assistant used it. Check the conversational outcome (R guardrail
"blocked" error or pre-emptive refusal) instead, since R-side
enforcement is what this test claims to cover and is also covered
deterministically by chat-guardrails-paths.test.ts.
Two related additions to make ChatPresenter blocking states observable
and controllable from Playwright tests:

1. window.rstudio.chat.{state,blocked,history}
   ChatPresenter writes its lifecycle state (ready / starting / restarting
   / manifest-unavailable / unsupported-protocol / incompatible-version /
   version-update-required / version-no-update / not-installed /
   update-available / assistant-not-selected / error / crashed) into
   window.rstudio.chat at each transition. Tests poll a deterministic
   value instead of racing the iframe content, which the live PAI backend
   actively re-renders. No-op outside --automation-agent mode.

2. chat_set_update_check_override RPC + window.rstudio.chat.setUpdateCheckOverride()
   Installs (object) or clears (null) a static override that the next
   chat_check_for_updates returns verbatim. Tests use this to drive each
   blocking branch without faking HTTP responses -- Playwright route.fulfill
   produces status=0 in the renderer's XHR in dev-mode Electron, so any
   JS-side mock takes ChatPresenter down the onCheckFailed path instead
   of the manifest-unavailable / unsupported-protocol / etc. callbacks
   the tests need to exercise. The in-rsession override is the only path
   that reliably reaches those callbacks.
Rewrites the deprecate-pai-blocking suite to assert on
window.rstudio.chat.state (deterministic, populated by ChatPresenter at
every transition) and install per-test response overrides via the new
chat_set_update_check_override RPC. The previous mechanism mocked the
RPC at the HTTP layer with Playwright route.fulfill plus a doc.write
hack to inject blocking HTML directly into the iframe; both fought the
live chat backend and only worked when the chat was stuck on the trust
overlay (i.e. only before the workspace-trust dismissal was wired up).

Side effects:
  - The Playwright RPC interceptor (interceptUpdateCheck /
    setUpdateCheckMock / clearUpdateCheckMock) and the UpdateCheckResult
    type are unused now; removed from ChatPaneActions.
  - Test runtime drops from ~21s (with one passing and one failing) to
    ~16s with all six tests green.
- chat-guardrails #3: require both a refusal/blocking signal AND
  path-scope context in the response. A bare refusal of the prompt's
  "no built-in tool" instruction would otherwise satisfy the earlier
  matcher without actually exercising the outside-path R guardrail.

- chat_set_update_check_override: consume the override after the next
  chat_check_for_updates returns it, matching the documented "next
  response" semantics. Previously the value persisted until explicitly
  cleared, so a forgotten clear in a test's afterEach could bleed
  forced results into unrelated subsequent checks.

- ChatPresenter docstring: drop "update-check-failed" (and add the
  missing "restarting") so the documented state set matches the values
  actually emitted by setAutomationChatState.
executeInConsole writes to the Ace editor and presses Enter, but Enter
can be intercepted by an autocomplete/signature-help popup that takes
the keystroke for selection rather than submission. When that happens
the command sits in the editor and R never goes busy, so the existing
waitForConsoleIdle wait returns immediately on an idle R and downstream
captureResult-style helpers throw "markers not found" with no context
about what actually broke.

Now: after each Enter, poll for the editor value to clear (Ace empties
the buffer on submit). If it's still populated, dismiss any popup,
re-focus the editor, and try again, up to 3 attempts. After the final
attempt fails surface a clear error including the command prefix so the
failure is diagnosable instead of bubbling up as an unrelated downstream
timeout.
Two refinements to the executeInConsole retry loop:

- Cover all Enter-intercepting overlays on retry, not just the
  completions popup. On the first attempt we still only dismiss
  #rstudio_popup_completions if it's already visible (setValue
  shouldn't have created a new overlay). But once Enter has failed
  to submit, send Escape unconditionally to clear whatever overlay
  intercepted it (completions, signature help, hover tooltip, ...)
  and then re-focus the editor.

- Only retry on TimeoutError. Other waitForFunction failures
  (frame teardown, exec-context destroyed, JS evaluation errors)
  were being swallowed and replaced by the generic submission-failure
  message, masking the root cause. Re-throw non-timeout errors
  immediately.
The "Source columns can be created and closed" test was relying on
closeAllSourceDocs to tear down empty source columns. That's not what
the product actually does -- a source column is removed only when its
last tab is closed (via LastSourceDocClosedEvent firing from
SourceColumn.closeTabIndex). newSourceColumn auto-populates only the
FIRST new column (the "always have a source doc when source view is
shown" invariant); columns 2 and 3 stayed empty, the close had nothing
to close in them, and they persisted -- then the empty columns got
re-populated with fresh Untitled docs during the assertion wait,
producing a misleading "Source2_pane count 1 expected 0".

Add an ensureDoc helper that clicks the new pane (focusing it as the
active column) and then runs newSourceDoc if the pane started empty.
Every column now has a doc by the time closeAllSourceDocs fires, so
every column's LastSourceDocClosedEvent fires and every column is
removed.
@kevinushey kevinushey added this to the Blue Plumbago milestone May 24, 2026
@posit-snyk-bot

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

Six fixes from the critical review of #17760:

- Gate chat_set_update_check_override on --automation-agent. The RPC was
  callable by any authenticated client in any session; in Server mode that
  would let a logged-in user pin chat_check_for_updates to return false and
  suppress legitimate update notifications. The handler now returns
  operation_not_permitted unless rsession started with the automation flag.

- Move the stranded openProject docstring above the actual function. It
  was sitting above getChatState, so JSDoc tooling and human readers
  associated the openProject docs with the wrong function.

- Tighten the waitForChatReady sign-in error. The previous message
  speculated about refresh-token rotation; now it just states the
  precondition and the action ("Sign in on the host (~/.positai) and
  re-run.").

- Anchor triggerRecheckAndExpectState (and the recovery test's ready
  assertion) on the LAST history entry rather than the current state. A
  transient transition can no longer satisfy the assertion -- the last
  recorded entry must match both state and blocked.

- Narrow requireAiCredentials's TestType from <any, any> to <{}, {}> so
  the helper doesn't launder any through utility code. {} (not unknown,
  which fails the TestType constraint) is the minimum that accepts
  extended-fixture `test` objects.

- Add a comment to panes.test.ts ensureDoc flagging the undocumented
  click-to-activate dependency, so a future test debugger knows where to
  look if newSourceDoc starts landing in the wrong column.
The "Default quadrants exist and have expected visibility" test was
asserting the source pane is collapsed (0 width OR 0 height) at startup,
on the premise that "no source docs are open" in the default state. That
premise was wrong: RStudio's session-init creates a default Untitled tab
asynchronously, not gated on DeferredInitCompletedEvent, so a fresh-session
isolation run reliably sees Untitled1 in the source pane by the time
assertions run. The test only passed in the full non-AI suite because
preceding files happened to leave the source pane in an unusual 0-doc
state that didn't naturally occur on init.

Sidestep the race entirely: use documents.resetToUntitled() in beforeAll
to land the pane in a deterministic "exactly one Untitled" state (the
helper already exists and is used elsewhere for the same reason), poll
for that state to settle, and rewrite the source-pane assertion to match.
The pane is now expected to have dimensions > 0 and exactly one tab. No
close-and-reclose dance, no timing windows -- the bridge call leaves the
source pane in a known state and the assertion verifies it.

Side effect: the column-management test that comes next now starts from
the same canonical state instead of relying on whatever auto-Untitled
behavior happened to fire.
@kevinushey
kevinushey merged commit cf6f82f into main May 24, 2026
1 of 2 checks passed
@kevinushey
kevinushey deleted the feature/e2e-ai-and-bridge branch May 24, 2026 07:13
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