Repository navigation
[py] [js] interaction-readiness reference implementation: quiescence oracle as a BiDi preload - #18255
AutomatedTester wants to merge 53 commits into
Conversation
|
/agentic_describe |
PR Summary by QodoPrototype interaction readiness with a BiDi quiescence preload
AI Description
Diagram
High-Level Assessment
Files changed (18)
|
Code Review by Qodo
1.
|
Adds javascript/atoms/quiescence.js, a prototype "quiescence oracle" preload script that installs window.__quiescence to track a document's pending work (timers, fetch/XHR, WebSocket, requestAnimationFrame) and expose isQuiet()/getBlockers()/awaitQuiet()/setPolicy()/markInert(). The Python binding copies the atom into the package and registers it via script.addPreloadScript on the first driver.get() when the session negotiated a BiDi WebSocket, so the API is available on every navigation. Injection is best-effort and guarded so non-BiDi sessions are unaffected. Also adds a served test harness (common/src/web/quiescence.html), a /slow endpoint in the test web server, and BiDi integration tests covering network/timer/interval/rAF blockers, observed inertness, chained work, policy boundaries, and durable cooperative markInert() annotations.
driver.get() already blocks until the page load event, so the quiescence oracle adds little there. browsing_context.navigate() does not wait for the page to settle, which is where window.__quiescence is useful, so the preload is now registered from navigate(). The BiDi browsingContext module is code-generated: give it a driver reference (like the script module already has) and override navigate() in the enhancement manifest to register the preload before executing the command. Tests navigate via browsing_context.navigate() accordingly.
Adds integration tests for window.__quiescence.awaitDomSettled(): idle settle, structural burst debounce, bookkeeping-attribute filtering, periodic-text noise classification, structural re-promotion of a noise region, and active-region diagnostics on timeout. Fails until the atom implements awaitDomSettled/getActiveRegions.
Adds a backward-looking DOM activity tracker to the quiescence atom: a
dedicated MutationObserver feeds a fingerprinted ledger, classifying
structural vs bookkeeping-attribute vs value-only periodic churn. Value-
only mutations on a regular cadence are reclassified as noise (observed
inertness for the DOM), and any net node change re-promotes them.
window.__quiescence.awaitDomSettled({settleMs,timeoutMs,requirePendingQuiet})
resolves once meaningful mutations stop for the settle window; on timeout
it reports the still-active regions. getActiveRegions() exposes the live
churn. Uses a second observer so runTracked's synchronous takeRecords()
does not steal activity records.
MutationObserver is blind to CSS animations/transitions. Adds tests that a finite running animation blocks settle until it finishes, while an infinite-iteration spinner is treated as noise. The finite case fails until awaitDomSettled consults document.getAnimations().
awaitDomSettled now treats a running CSS animation/transition as activity
via document.getAnimations({subtree:true}), covering the MutationObserver
blind spot. Infinite-iteration animations (spinners) are excluded as
periodic noise so they do not block quiescence forever.
…(RED)
Adds tests for root-scoped settle (footer churn ignored for #main), a
durable cooperative markDomInert() annotation, setDomPolicy() disabling
CSS-animation activity, and awaitQuiet({dom:true}) composing pending-work
quiescence with DOM settle. Fails until the atom implements root filtering
and these APIs.
…(GREEN)
awaitDomSettled now accepts a root (element or CSS selector) and scopes the
settle window to that subtree, so unrelated churn elsewhere is ignored.
Replaces the event-driven re-arm with a fixed-cadence poll so a mutation
outside the scoped root cannot reset that root's window, and requires one
full settle window of observation before settling.
markDomInert(node|selector) is a sticky cooperative annotation (durable
across ticks); setDomPolicy(partial) tunes DOM thresholds; awaitQuiet({dom,
root}) composes pending-work quiescence with DOM settle.
Adds tests that mutation inside an open shadow root counts as activity, that a closed shadow root is reported as unobservable, and that child-frame churn does not block the parent context. The two shadow tests fail until the atom hooks attachShadow.
Patches Element.prototype.attachShadow so open shadow roots are attached to the DOM activity observer (MutationObserver does not cross shadow boundaries), letting mutations inside them count toward quiescence. Closed roots are opaque and recorded in the unobservable list surfaced by awaitDomSettled, rather than being silently treated as settled.
Adds tests for a WebDriver.wait_for_dom_settled() wrapper: whole-document settle, CSS-selector root, WebElement root, and active-region reporting on timeout. Fails until the method is implemented.
Adds WebDriver.wait_for_dom_settled(root, timeout, settle_ms, require_pending_quiet), a thin wrapper over the polyfill's awaitDomSettled. root accepts a WebElement or a CSS selector. Installs the polyfill on the current document if the preload never ran (classic get() path) and widens the async-script timeout when needed so the browser does not abort the wait before our own deadline. Refactors the loader to expose the raw IIFE source for that one-shot install.
…ked/inview (GREEN)
Viewport clipping and the obstruction hit test now run in every readable ancestor document, translating through each frame's border and padding, so a parent overlay or a frame scrolled out of the parent's view is no longer reported ready. The walk stops at the first cross-origin ancestor and the result lists cross-origin-ancestor in unobservable, so callers can tell an unchecked boundary from a clear one. Test file changes are formatter and docstring (D205) fixes only.
…bled Trunk narrowed the BiDi test glob to test/selenium/webdriver/common/bidi/. Left at common/bidi_*_tests.py, these suites were collected as classic tests and every session started without webSocketUrl.
…um/atoms A 1:1 port: the body is unchanged apart from the wrapper and the annotations TypeScript needs (optional parameters, a typed listener set, Promise<any> where it inferred unknown). The four Python BiDi suites pass unchanged against the bundled artifact. The atom now default-exports installQuiescence(global = globalThis) and builds through the same registry as the other TypeScript atoms, so @selenium/atoms gains a ./quiescence subpath and an installQuiescence barrel export. Like every TypeScript atom, the injectable form evaluates to the function rather than running itself, so the Python binding now calls it with the page's window. 'use strict' is gone: it is a SyntaxError in a function with a default parameter, and ES modules are strict already.
npm consumers install quiescence by sending installQuiescence.toString() to the browser as a BiDi preload, a CDP new-document script or a Playwright init script. That breaks silently the moment the function references anything at module scope, so quiescence-portable evaluates the source in a bare vm context and checks the ledger it installs. Confirmed it fails with a ReferenceError when a constant is hoisted out. README.npm.md documents the preload install and the query API, and that the API is a prototype tracked by ADR 17886.
a5881a2 to
228e5f0
Compare
|
Code review by qodo was updated up to the latest commit 228e5f0 |
fetch() settles when headers arrive, so the ledger cleared before the page had read and rendered the response; only the settle window stood between "quiet" and unrendered data, and a slow body outlasts it. Each started body read (json/text/arrayBuffer/blob/bytes/formData, on the response or a clone) now holds a 'fetch-body' entry until it finishes. Bodies nobody reads are not tracked, so they cannot block forever. Streamed bodies (res.body.getReader()) remain untracked and are listed under known limitations. The test server's /slow endpoint gains ?bodyMs= to send headers first and the body later. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LA4X4vm8dWmqrXdvW2dvZR
native.now looked up Date on every call, unlike the timer functions
captured beside it. A page or fake-timer library that freezes
window.Date stopped every settle window from elapsing: awaitDomSettled
and awaitQuiet({dom: true}) only ever returned at their deadline, and
the actionability wait, whose timeout is a clock comparison, could poll
indefinitely.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LA4X4vm8dWmqrXdvW2dvZR
|
Code review by qodo was updated up to the latest commit 7c2296e |
The test left a request thread sleeping out a 30 s body, and server_close() joins request threads, so a focused run waited for it. A 3 s body with a 2 s quiet timeout still fails if an unread body were tracked, and frees the thread promptly. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LA4X4vm8dWmqrXdvW2dvZR
|
Code review by qodo was updated up to the latest commit 48efb0f |
Trunk added the accessibility-snapshot atoms in the same registry spots as quiescence (BUILD.bazel tests, defs.bzl ATOMS, index.ts exports); kept both, trunk's entries first. package.json was regenerated from the merged registry with generate-exports.cjs, and its --check passes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LA4X4vm8dWmqrXdvW2dvZR
|
Code review by qodo was updated up to the latest commit ab83d67 |
Firefox holds fetch() until some of the body has arrived, so a response of bare headers kept the request's plain 'fetch' blocker open in Firefox: test_unread_fetch_body_does_not_block timed out there with blocker type 'fetch', and the body-read test passed without ever reaching the 'fetch-body' path. Sending the opening of the JSON with the headers delivers the response in every engine while json()/text() still wait for the rest. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LA4X4vm8dWmqrXdvW2dvZR
|
Code review by qodo was updated up to the latest commit a932dfb |
…pers Atom (each reproduced in Chromium first, then covered by a browser test): - interval/rAF tracking no longer swallows page exceptions (return in finally); errors reach window.onerror again - clearTimeout/clearInterval cancel either timer kind in the ledger too - an XHR send() that throws no longer leaves a stuck entry - data-block and nomodule scripts are not tracked (they never load) - a link becoming rel=stylesheet, an img switching lazy -> eager, and the first src on an unstarted script are now tracked - observers attach to the document node, so a preload that runs before documentElement exists misses nothing - shadow-aware scoping and inertness: a root or inert host covers its open shadow tree - noise is reclassified when its cadence breaks; swapping elements on a cadence is structural, not noise - a root selector that matches nothing waits for the root and reports root-not-found instead of widening to the whole document - setPolicy re-evaluates ignore patterns for requests already in flight - console.debug transitions are opt-in (policy.debugLog) - each rAF chain keeps its own state, so unrelated frame requests no longer reset a running loop - type/clear readiness requires a textual input (bot.dom's list) - the hit test descends open shadow roots and treats an ancestor hit as an obstruction (pointer-events: none targets) - overflow: clip clips; stability waits honour the timeout and state is re-checked after the stability frames Python: - the script timeout is actually widened (and restored) around the waits; assigning to driver.timeouts.script changed a throwaway copy - preload registration retries after a failure, warning once, and calls the BiDi module directly instead of the deprecated driver.script proxy - /slow?bodyMs= ends quietly when the client disconnects mid-body Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LA4X4vm8dWmqrXdvW2dvZR
|
Code review by qodo was updated up to the latest commit 90ec1cc |
It took seconds, like every other timeout in the binding, but the _ms suffix invited milliseconds: settle_ms=150 asked for 150 s of quiet and always timed out. Unreleased, so renamed outright. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LA4X4vm8dWmqrXdvW2dvZR
The quiescence preload was registered by replacing the generated navigate with a hand-written one (untyped parameters, raw command), because the generator drops any command an extra method shadows. A new before_execute enhancement inserts statements into the generated method instead, so navigate keeps its generated signature and contract and only gains the preload call. Regenerating from the pinned CDDL changes nothing else. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LA4X4vm8dWmqrXdvW2dvZR
…t can't be raised Composed containment steps from a shadow root's children straight to its host, so a wait scoped to the ShadowRoot itself stopped seeing changes below its children (a regression from the shadow-host fix). Plain containment covers that scope again, composed containment the host. A failure to raise the script timeout is now a warning: the wait can then be aborted by the browser instead of returning its diagnosis. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LA4X4vm8dWmqrXdvW2dvZR
| "navigate": { | ||
| "before_execute": [ | ||
| "# Register the quiescence preload (once) so window.__quiescence is", | ||
| "# installed on the document this navigation creates. Unlike the classic", | ||
| "# GET command, browsingContext.navigate does not wait for the page to", | ||
| "# load, so the quiescence oracle is registered here rather than in get().", | ||
| "if self._driver is not None:", | ||
| " self._driver._ensure_quiescence_preload()", | ||
| ], | ||
| }, |
There was a problem hiding this comment.
5. Navigate silently patches every page 📘 Rule violation ⚙ Maintainability
The before_execute hook on the generated browsingContext.navigate calls _ensure_quiescence_preload() on every navigation, and the first call registers a BiDi preload that wraps setTimeout, setInterval, requestAnimationFrame, fetch, XHR and WebSocket and adds window.__quiescence to every later page in the session. Existing users of the stable public navigate method get this global side effect without opting in, and neither its signature nor its docstring discloses it.
Agent Prompt
## Issue description
The generated `browsingContext.navigate` now registers the quiescence preload on every call, which injects global wrappers into every page the session loads. Callers who only want navigation get this side effect silently.
## Fix Focus Areas
- py/private/bidi_enhancements_manifest.py[224-233]
- py/selenium/webdriver/remote/webdriver.py[621-653]
## Recommended Fix
Remove the `before_execute` hook from the `navigate` enhancement. Register the preload only from `wait_for_dom_settled()` and `wait_until_actionable()`, which already call `_ensure_quiescence_preload()`. If navigation-time installation is required, make it opt-in through a documented session or capability flag, and state the behaviour change in the docstring.
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
|
Code review by qodo was updated up to the latest commit 029b576 |
timeouts.py is its own Bazel library that the BiDi test targets do not depend on, so importing it made dom_quiescence_tests fail to collect on every browser, and driver.timeouts (which imports it lazily) made the script-timeout helper fall back to its warning branch there. The helper and its test now use the Get/Set Timeouts commands directly, which needs nothing beyond the remote module. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LA4X4vm8dWmqrXdvW2dvZR
driver.script.execute returns the deserialized return value, so the
probe's check for a RemoteValue dict ({'type': 'boolean', 'value': True})
never matched: the page reported the resource blocker on the first poll
and the wait still timed out. This is the long-standing
test_parser_created_slow_image_is_awaited failure on every browser.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LA4X4vm8dWmqrXdvW2dvZR
|
/agentic_review |
|
Code review by qodo was updated up to the latest commit 0809b26 |
🔗 Related Issues
Reference implementation for ADR #17886, "Selenium waits for interaction readiness before it interacts". Draft: this exists so the ADR has something concrete to point at and CI to run against. It is not the proposed API shape, and it isn't ready to merge until the ADR is accepted.
💥 What does this PR do?
Adds a page-script oracle that answers "is this page done?" and "can this element be interacted with right now?", installed as a BiDi preload script.
fetch, XHR, WebSocket and subresource loads (images, media, frames, objects, dynamically inserted scripts and stylesheets). Long-delay timers, long-period intervals, and periodic tasks observed to have no effect are classified inert, so clocks and keep-alive polls don't block.aria-disabledand thefieldset/legendexception), editable when the interaction writes, in the viewport, unobstructed at its interaction point, and not moving. The checks that apply depend on the interaction. Viewport and obstruction are checked in every ancestor document up to the first cross-origin one.driver.wait_for_dom_settled()anddriver.wait_until_actionable(). ADR decisions 4 and 5 replace these two methods; they're here to make the semantics testable.@selenium/atoms. The atom isjavascript/atoms/typescript/quiescence.tsand is published as@selenium/atoms/quiescence(installQuiescence). The function is self-contained, so other tools can install it withinstallQuiescence.toString()as a BiDi, CDP or Playwright preload.🔧 Implementation Notes
perpetualMotion, because waiting for it provably never ends. Sub-pixel motion under 0.5px doesn't count as movement.unobservable, e.g.cross-origin-ancestor,closed-shadow, orlate-installwhen the atom was injected into an already-loaded document rather than preloaded. Each of these means "couldn't check", not "passed". The full list of limitations is in the header ofquiescence.ts, and ADR decision 10 mirrors it.ATOMSregistry as every other TypeScript atom, andpackage.jsonwas regenerated withgenerate-exports.cjs.jimevans/acquiescence's test suite.💡 Additional Considerations
Open before this can leave draft:
stable: resolved in the ADR (71677c3):pendingWorkandsettlednessare synchronous;actionabilityreturns a promise because stability is sampled across animation frames, which is what this implementation does.se:interactionReadinesscapability, the implicit-wait replacement, client-side element-location retry, readiness error subclasses, and thesettledpage load strategy.javascript/atoms/(BUILD,defs.bzlregistry,package.json,index.ts; additive only, no existing atom changes) andcommon/src/web/(two new fixtures).Tests: 134 browser tests across four suites under
py/test/selenium/webdriver/common/bidi/: quiescence 27, DOM quiescence 21, resource quiescence 15, element actionability 71. All pass on Chrome over BiDi. Also//javascript/atoms:quiescence-portable(verified to fail when the function references module scope),atoms-load-in-nodeandexports-up-to-date.🤖 AI assistance
🔄 Types of changes
🤖 Generated with Claude Code