diff --git a/.changeset/viewport-matcher.md b/.changeset/viewport-matcher.md new file mode 100644 index 0000000000..ad774b13c3 --- /dev/null +++ b/.changeset/viewport-matcher.md @@ -0,0 +1,17 @@ +--- +"e2e": patch +"@e2e-dev/core": patch +"@e2e-dev/web": patch +"@e2e-dev/mobile": patch +--- + +Add `expect(locator).toBeInViewport({ ratio })`, which waits for part of the +match, or that share of its box, to be inside the viewport without scrolling. +No match counts as outside, so `.not` accepts zero matches. The web engine +measures with the page's `IntersectionObserver`, matching Playwright, so +scrolling and `overflow` ancestors and frames clip the box. The mobile engine +reports only whether the node is on screen, because a device reports bounds +already clipped, so `ratio > 0` there fails with `UNSUPPORTED_CAPABILITY` +once the node is on screen. +Engines implement the optional `viewportIntersection` method for the new +`viewport-intersection` capability. diff --git a/apps/mobile-benchmark/tests/flows-lists.e2e.ts b/apps/mobile-benchmark/tests/flows-lists.e2e.ts index 9d0223982b..d29254ebbb 100644 --- a/apps/mobile-benchmark/tests/flows-lists.e2e.ts +++ b/apps/mobile-benchmark/tests/flows-lists.e2e.ts @@ -52,7 +52,12 @@ test('sticky chrome: accept below the fold, then continue', async ({ app, device await screen.getByTestId('continue-button').tap(); await expect(screen.getByText('Accept the terms at the bottom first')).toBeVisible(); const accept = screen.getByTestId('accept-terms'); + await expect(accept).not.toBeInViewport(); await screen.scrollUntilVisible(accept, { direction: 'down' }); + await expect(accept).toBeInViewport(); + // A device reports only the visible part of a box, so no share of it can be measured. + const refused = await expect(accept).toBeInViewport({ ratio: 0.5 }).then(() => undefined, (error: unknown) => error); + expect(refused).toHaveProperty('code', 'UNSUPPORTED_CAPABILITY'); await accept.tap(); await expect(screen.getByText('Terms accepted ✓')).toBeVisible(); await screen.getByTestId('continue-button').tap(); diff --git a/apps/testbed/tests/controls.e2e.ts b/apps/testbed/tests/controls.e2e.ts index 1218c1e2e5..de3f846f4f 100644 --- a/apps/testbed/tests/controls.e2e.ts +++ b/apps/testbed/tests/controls.e2e.ts @@ -257,6 +257,19 @@ test.describe('controls', { requires: ['browser'], tags: ['controls'] }, () => { expect(error).toHaveProperty('message', expect.stringContaining('opened no file chooser')); }); + test('toBeInViewport follows the scroll position, and no match is outside the viewport', async ({ screen }) => { + const footnote = screen.getByText('Footnote', { exact: true }); + await expect(footnote).not.toBeInViewport(); + const error = await failure(() => expect(footnote).toBeInViewport({ timeout: 500 })); + expect(error).toHaveProperty('code', 'ASSERTION_FAILED'); + expect(error).toHaveProperty('message', expect.stringContaining('observed: outside the viewport')); + + await footnote.scrollIntoView(); + await expect(screen.getByLabel('Footnote state')).toHaveText('in view'); + await expect(footnote).toBeInViewport({ ratio: 1 }); + await expect(screen.getByText('No such footnote')).not.toBeInViewport(); + }); + test('a missing locator fails as LOCATOR_NOT_FOUND after its timeout', async ({ screen }) => { expect(await failure(() => screen.getByRole('button', 'Nope').tap({ timeout: 500 }))).toHaveProperty( 'code', diff --git a/docs/migrate/playwright.mdx b/docs/migrate/playwright.mdx index db106ca790..33b9dde21c 100644 --- a/docs/migrate/playwright.mdx +++ b/docs/migrate/playwright.mdx @@ -134,7 +134,7 @@ run only in a browser, so a test that uses it declares | Playwright | e2e | | --- | --- | -| `toBeVisible()`, `toBeHidden()`, `toBeEnabled()`, `toBeDisabled()`, `toBeChecked()`, `toBeFocused()`, `toBeAttached()`, `toHaveText()`, `toContainText()`, `toHaveValue()`, `toHaveAttribute()`, `toHaveCount()`, `toHaveAccessibleName()`, `toHaveRole()`, `toBeEditable()` | the same, with `{ visible }`, `{ enabled }`, `{ editable }`, `{ checked }`, `{ attached }`, and `{ ignoreCase }` | +| `toBeVisible()`, `toBeHidden()`, `toBeEnabled()`, `toBeDisabled()`, `toBeChecked()`, `toBeFocused()`, `toBeAttached()`, `toBeInViewport()`, `toHaveText()`, `toContainText()`, `toHaveValue()`, `toHaveAttribute()`, `toHaveCount()`, `toHaveAccessibleName()`, `toHaveRole()`, `toBeEditable()` | the same, with `{ visible }`, `{ enabled }`, `{ editable }`, `{ checked }`, `{ attached }`, `{ ratio }`, and `{ ignoreCase }`; `toBeInViewport` reads a zero-size element as outside and [differs on a device](/reference/expect#tobeinviewport) | | `toHaveId(id)`, `toContainClass(name)` | `toHaveAttribute('id', id)`, `toHaveAttribute('class', RegExp)` | | `expect(page).toHaveURL()`, `toHaveTitle()` | `expect(browser).toHaveURL()`, `toHaveTitle()` | | `expect(page).toHaveScreenshot()`, `expect(locator).toHaveScreenshot()` | `expect(screen).toHaveScreenshot()` and the locator form, see [Visual comparison](/visual-testing) | @@ -268,7 +268,7 @@ purpose. Use the workaround, or keep the test in Playwright. | Playwright | Use today | | --- | --- | -| `toBeEmpty()`, `toBeInViewport()` | `toHaveValue('')` on a form control, `toHaveText('')` on other elements; `expect.poll` over `boundingBox()` | +| `toBeEmpty()` | `toHaveValue('')` on a form control, `toHaveText('')` on other elements | | `{ fullPage, clip }`, `snapshotPathTemplate`, `ignoreSnapshots` | The viewport or one locator in `toHaveScreenshot`; a tag and `--exclude-tag` to skip visual tests | | `expect.configure()` | `{ timeout }` on each call | | `@axe-core/playwright` | axe-core through `browser.addInitScript({ path: 'node_modules/axe-core/axe.min.js' })`, then `axe.run()` in `browser.evaluate` | diff --git a/docs/reference/engine-protocol.mdx b/docs/reference/engine-protocol.mdx index f17bf188e8..aa7e16742a 100644 --- a/docs/reference/engine-protocol.mdx +++ b/docs/reference/engine-protocol.mdx @@ -229,6 +229,7 @@ params are the member's arguments by name, with every `OperationContext` as | --- | --- | --- | | `engine/observe` | `{ operation, options? }` | `EngineSnapshot` | | `engine/readStyle` | `{ ref, properties, operation }` | `ComputedStyleValues` | +| `engine/viewportIntersection` | `{ ref, operation }` | `ViewportIntersection`; leave `ratio` out, never `null`, when the platform cannot measure it | | `engine/locate` | `{ expression, operation }` | `SemanticNode[]` | | `engine/perform` | `{ ref, action, operation }` | `null` | | `engine/performAt` | `{ point, action, operation }` | `null` | diff --git a/docs/reference/engine.mdx b/docs/reference/engine.mdx index 054f41c124..2632510f9f 100644 --- a/docs/reference/engine.mdx +++ b/docs/reference/engine.mdx @@ -106,9 +106,10 @@ rules: | `spiVersion` | Anything but `1`. | | `platform` | Empty. | | `workers` | Not a positive safe integer. | -| `observe`, `readStyle`, `locate`, `perform`, `performAt`, `prepare`, `finish`, `doctor`, `init`, `startAttempt`, `settleAttempt`, `endAttempt`, `dispose`, `validateApp` | Not a function. | +| `observe`, `readStyle`, `viewportIntersection`, `locate`, `perform`, `performAt`, `prepare`, `finish`, `doctor`, `init`, `startAttempt`, `settleAttempt`, `endAttempt`, `dispose`, `validateApp` | Not a function. | | any other top-level key | On an object literal, `app` included: declare the app on the target and check it in `validateApp`. A class instance's own fields are not checked. | | `readStyle`, `perform`, `locate`, `performAt`, `keyboard` | Declared without `observe`. | +| `viewportIntersection` | Declared without `locate`. | | `perform`, `actions` | One without the other. An `actions` list that is empty, repeats a kind, or names one outside `KNOWN_LOCATOR_ACTION_KINDS`. | | `performAt`, `pointerActions` | One without the other. A `pointerActions` list that is empty, repeats a kind, or names one outside `POINTER_ACTION_KINDS`. | | `tapModifiers` | Not a boolean, or `true` without `perform`. | @@ -140,6 +141,7 @@ The body of one target. Every member but `name`, `version`, and | `workers` | `number` | | [`observe`](#observation) | method | | [`readStyle`](#rendered-node-properties) | method | +| [`viewportIntersection`](#viewport-intersection) | method | | [`perform`, `actions`](#actions) | method, kinds | | [`locate`](#capabilities) | method | | [`performAt`, `pointerActions`](#pointer-actions) | method, kinds | @@ -189,6 +191,8 @@ export interface Engine { observe?(context: OperationContext, options?: EngineObserveOptions): Promise; /** capability: computed-style, requires observation. Read-only rendered properties of an observation ref. */ readStyle?(ref: NodeRef, properties: readonly ComputedStyleProperty[], context: OperationContext): Promise; + /** capability: viewport-intersection, requires location. How much of a located node is inside the viewport. */ + viewportIntersection?(ref: NodeRef, context: OperationContext): Promise; /** * Performs one action on a ref from the newest observation or `locate`, * with the platform's actionability checks. Both agent tools and locator @@ -407,6 +411,7 @@ member. Three gaps end differently: | `readStyle` | `computed-style` | `observe` | Allow-listed rendered properties for read-only project tools. | | `perform` + `actions` | `actions` | `observe` | Node actions of the declared kinds, with platform actionability checks. | | `locate` | `location` | `observe` | `screen`, `Locator`, `expect(locator)`. | +| `viewportIntersection` | `viewport-intersection` | `locate` | `expect(locator).toBeInViewport()`. | | `tapModifiers: true` | - | `perform` | `modifiers` on `tap`, `doubleTap`, and `secondaryTap`. | | `selectsDevice: true` | - | `prepare` | `e2e run --device`, the device `prepare` binds. | | `launchArgumentValues: true` | - | - | The object form of `app.launchArguments`, in `EngineAppInfo.launchArgumentValues`. | @@ -440,6 +445,30 @@ throws `INVALID_ARGUMENT` for an empty list or a property outside the allow-list. Call it before page access. See [Project tools](/tools#read-a-nodes-computed-style) for `ToolContext.read`. +#### Viewport intersection + +`viewportIntersection(ref, context)` measures how much of a located node is +inside the viewport for [`toBeInViewport`](/reference/expect#tobeinviewport), +without scrolling or changing app state. Clip the box by the viewport and every +clipping ancestor, such as a scroll container, `overflow: hidden`, or a frame. + +```ts +export interface ViewportIntersection { + /** Whether a positive area of the box is inside; false for a node with no box or an empty one. */ + readonly intersects: boolean; + /** The inside area's share of the whole box, from 0 to 1; absent where the platform reports only the visible part of a box. */ + readonly ratio?: number; +} +``` + +Omit `ratio` when the platform reports only the visible part of a box, as a +device does. `toBeInViewport` with `ratio > 0` then fails with +`UNSUPPORTED_CAPABILITY` instead of reading that part as the whole box. Throw +retryable `NODE_STALE` if the node no longer binds, and +`UNSUPPORTED_CAPABILITY` if the platform cannot report the node's bounds or +screen position. A `ratio` is above `0` exactly when `intersects` is true. The +harness fails the step with `ENGINE_FAILURE` on an answer outside this shape. + #### Agent verbs The agent offers the model only the verbs the engine's declarations unlock. @@ -537,6 +566,7 @@ engine. A target with `app.url` has `browser`, and one with `app.bundleId` or export type EngineCapability = | 'observation' | 'computed-style' + | 'viewport-intersection' | 'actions' | 'location' | 'pointer' diff --git a/docs/reference/errors.mdx b/docs/reference/errors.mdx index eb37032963..882d5ad7e4 100644 --- a/docs/reference/errors.mdx +++ b/docs/reference/errors.mdx @@ -148,7 +148,7 @@ These appear in terminal output and in the report as plain string codes. | `TEST_AMBIGUOUS` | `e2e mcp`: `open_session`'s `test` selected several tests on the session's target. The message lists them as `file:line` | configuration | 2 | | `SESSION_TEST_UNSUPPORTED` | `e2e mcp`: `open_session`'s `test` selected a test a session cannot run alone: a serial group member, a test that starts from a setup test's `session`, or a test that runs as several agents. Run it with `e2e run` | configuration | 2 | | `UNSUPPORTED_ARTIFACT` | A [`video` mode](/reference/config#recording) set on a target, or on a test that will run there, records on some attempt, and the target's engine cannot record video. The message names the target, and the test for a test's mode. A mode from the config root or `--video` never raises it: it applies to the targets that can record, with a notice naming the rest | configuration | 2 | -| `UNSUPPORTED_CAPABILITY` | A fixture, action, or tier the target's engine does not declare: a built-in fixture a worker fixture uses while no test or suite hook runs (a fixture the target does not have is `COLLECTION_ERROR`), `screen` without `locate`, state restore without `state`, screenshots without `artifacts`, `app.clearState()` on a persistent browser context (the message names the mode), `agent.assert` `vision` with an executor that does not declare `vision: true`, `app.startRecording()` while the test's video records, or `browser.webmcp` in a browser or on a page without WebMCP. Also `e2e run --device` when no selected target's engine chooses a device (`web()`), or the target's devices come from a device provider | configuration | 2 | +| `UNSUPPORTED_CAPABILITY` | A fixture, action, or tier the target's engine does not declare: a built-in fixture a worker fixture uses while no test or suite hook runs (a fixture the target does not have is `COLLECTION_ERROR`), `screen` without `locate`, state restore without `state`, screenshots without `artifacts`, `app.clearState()` on a persistent browser context (the message names the mode), `agent.assert` `vision` with an executor that does not declare `vision: true`, `app.startRecording()` while the test's video records, `browser.webmcp` in a browser or on a page without WebMCP, or `toBeInViewport` on an engine without `viewportIntersection`, on a node whose bounds or screen position the engine cannot report, or with `ratio` above 0 on an engine that reports no share of the box, such as a device. Also `e2e run --device` when no selected target's engine chooses a device (`web()`), or the target's devices come from a device provider | configuration | 2 | | `NO_TESTS` | Zero runnable ordinary test-target pairs. The message names the cause: no file matched the `tests` globs (it lists look-alike files), a positional matched nothing (it names the `!` entry that excludes a file the positional names), a file registered no tests, or filters excluded everything. Suppress with `--pass-with-no-tests`. When [test filters](/filters) leave nothing to run, the run passes instead (exit 0). Also `e2e mcp`'s `open_session` when its `test` selects no runnable test. | configuration | 2 | | `RUNNER_BUSY` | A suite overlapped another suite, an opening or open host, or a live attempt; or a host opened during a suite; or `e2e run --step` started without a terminal in a directory where another run is already controlled with `e2e run --step`; or a test reached `screen.pause()` in a run without a terminal while another run in the directory was controlled that way; or a run killed while it took control of the directory left its lock (the message names the file to remove). Await the suite and close existing hosts before you retry; end a stepped run with `e2e run --step stop`, or remove the lock file the message names. | configuration | 2 | | `RUNNER_NOT_INSTALLED` | `test`, `describe`, or a hook from `@e2e-dev/web`, `@e2e-dev/mobile`, or `@e2e-dev/desktop` was called where `e2e` is not installed, as in a program on `@e2e-dev/core` alone. The engine factory from the same entry still works. Install `e2e` to write tests | configuration | 2 | diff --git a/docs/reference/expect.mdx b/docs/reference/expect.mdx index 5886afd361..2bea61ab52 100644 --- a/docs/reference/expect.mdx +++ b/docs/reference/expect.mdx @@ -74,6 +74,7 @@ await expect(screen.getByTestId('cart-empty'), 'the cart is empty').toBeVisible( | --- | --- | | [`toBeVisible`](#tobevisible-and-tobehidden) | Waits for visibility | | [`toBeHidden`](#tobevisible-and-tobehidden) | Waits for hidden or absent state | +| [`toBeInViewport`](#tobeinviewport) | Waits for the match to be in view | | [`toBeAttached`](#tobeattached) | Waits for one match to exist | | [`toBeEnabled`](#tobeenabled-and-tobedisabled) | Waits for enabled state | | [`toBeDisabled`](#tobeenabled-and-tobedisabled) | Waits for disabled state | @@ -105,6 +106,34 @@ await expect(screen.getByRole('dialog')).not.toBeVisible({ timeout: 10_000 }); await expect(screen.getByRole('dialog')).toBeVisible({ visible: false }); // as toBeHidden() ``` +#### `toBeInViewport` + +Waits for part of the one match to be inside the viewport. It never scrolls, +and it says nothing about another element covering the match. No match counts +as outside the viewport, so `.not` accepts zero matches. A zero-size box, or a +web element with no box such as `display: none`, also counts as outside. + +```ts +await expect(screen.getByRole('toolbar', 'Selection')).toBeInViewport(); +await expect(screen.getByRole('toolbar', 'Selection')).toBeInViewport({ ratio: 0.5 }); +await expect(screen.getByRole('alert')).not.toBeInViewport(); +``` + +`ratio` is a number from `0` to `1` setting the share of the box that must be +inside. `0` means any positive area, the same as omitting `ratio`. Any value +outside `0` to `1` fails with `INVALID_ARGUMENT`. What counts as inside depends +on the engine: + +| Engine | Measures | `ratio` | +| --- | --- | --- | +| `@e2e-dev/web` | Uses the page's `IntersectionObserver`, matching Playwright. The viewport, scrolling or `overflow` ancestors, and frames clip the box. Replacing `IntersectionObserver` changes the result | Supported | +| `@e2e-dev/mobile` | Checks device-reported bounds against the confirmed screen. Scroll containers clip the bounds, and offscreen nodes leave the tree | `ratio > 0` fails with `UNSUPPORTED_CAPABILITY` once the node is on screen, because the device reports only the visible part | + +It fails at once with `UNSUPPORTED_CAPABILITY`, `.not` included, if the target's +engine does not implement +[`viewportIntersection`](/reference/engine#viewport-intersection), or if the +engine cannot report a node's bounds or screen position. + #### `toBeAttached` Waits for one match to exist, hidden or shown, where `toBeVisible` needs a @@ -862,11 +891,12 @@ has held: - A positive locator matcher requires exactly one match. The exceptions are `toHaveCount` and the list form of `toHaveText` and `toContainText`. -- Zero matches keep polling until the timeout. +- Zero matches keep polling until the timeout, except for the matchers below + that accept them. - Multiple matches fail immediately with `LOCATOR_AMBIGUOUS`. - `toBeHidden`, `toBeVisible({ visible: false })`, - `toBeAttached({ attached: false })`, negated visibility, and negated - `toBeAttached` accept zero matches. + `toBeAttached({ attached: false })`, negated visibility, negated + `toBeAttached`, and negated `toBeInViewport` accept zero matches. - For those, for `toHaveCount` and the list forms, and for `waitFor({ state: 'detached' })` and `'hidden'`, a locator under a frame that is not in the document is zero matches rather than a wait for the @@ -971,6 +1001,12 @@ export interface AsyncExpectation { toBeVisible(options?: { visible?: boolean; timeout?: number }): Promise; /** Waits for hidden or absent state. */ toBeHidden(options?: { timeout?: number }): Promise; + /** + * Waits for part of the match to be inside the viewport, after clipping by + * scrolling and overflow ancestors; `ratio` (0 to 1) sets the share of its + * box that must be. No match is outside the viewport. It never scrolls. + */ + toBeInViewport(options?: { ratio?: number; timeout?: number }): Promise; /** Waits for one match to exist, visible or not; `attached: false` waits for none. */ toBeAttached(options?: { attached?: boolean; timeout?: number }): Promise; /** Waits for enabled state; `enabled: false` waits for disabled state. */ diff --git a/docs/reference/test.mdx b/docs/reference/test.mdx index 48ace63e4c..9d235701d3 100644 --- a/docs/reference/test.mdx +++ b/docs/reference/test.mdx @@ -732,7 +732,8 @@ test('onboarding asks for the camera', { requires: ['native-app'] }, async ({ ap Accepted values: - The harness capabilities of the target's engine: `observation`, `actions`, - `location`, `pointer`, `keyboard`, `computed-style`, `state`, `artifacts`. + `location`, `pointer`, `keyboard`, `computed-style`, `viewport-intersection`, + `state`, `artifacts`. - One per built-in fixture an engine contributes: `browser`, `device`. See [the engine contract](/reference/engine#engine). - The kind of app the target declares: `browser` for an `app.url`, diff --git a/packages/core/src/engine/contract.ts b/packages/core/src/engine/contract.ts index af3bbb66e2..cc42923b86 100644 --- a/packages/core/src/engine/contract.ts +++ b/packages/core/src/engine/contract.ts @@ -249,6 +249,23 @@ export interface ViewportSize { readonly height: number; } +/** + * How much of a node's box is inside the viewport, after clipping by the + * viewport and by every ancestor that clips its content (a scroll container, + * `overflow: hidden`, a frame), as `Engine.viewportIntersection` measures it. + * It says nothing about another node covering the box. + */ +export interface ViewportIntersection { + /** Whether a positive area of the box is inside; false for a node with no box or an empty one. */ + readonly intersects: boolean; + /** + * The inside area over the whole box's area, from 0 to 1. Absent where + * the platform reports only the visible part of a box, so the whole is + * unknown. + */ + readonly ratio?: number; +} + /** * Masked viewport pixels captured for one observation revision. * diff --git a/packages/core/src/engine/index.ts b/packages/core/src/engine/index.ts index b486540ae4..37f97067da 100644 --- a/packages/core/src/engine/index.ts +++ b/packages/core/src/engine/index.ts @@ -67,6 +67,7 @@ import type { PointerAction, PointerActionKind, SemanticNode, + ViewportIntersection, ViewportPoint, ViewportSize, } from './contract.ts'; @@ -100,6 +101,7 @@ export { isSecret } from '../secrets.ts'; export type EngineCapability = | 'observation' | 'computed-style' + | 'viewport-intersection' | 'actions' | 'location' | 'pointer' @@ -743,6 +745,14 @@ export interface Engine { * protocol as JSON and are redacted by the harness before a tool sees them. */ readStyle?(ref: NodeRef, properties: readonly ComputedStyleProperty[], context: OperationContext): Promise; + /** + * capability: viewport-intersection - requires location. Measures how much + * of a node `locate` returned is inside the viewport, for `toBeInViewport`, + * without scrolling or changing app state. Throw NODE_STALE if the node no + * longer binds, and `UNSUPPORTED_CAPABILITY` for a node whose geometry the + * platform does not report. + */ + viewportIntersection?(ref: NodeRef, context: OperationContext): Promise; /** * capability: actions - requires observation. Performs exactly one action * on a ref this engine minted, from the newest observation or from diff --git a/packages/core/src/engine/manifest.ts b/packages/core/src/engine/manifest.ts index 1bc4e9bc0b..00b340e166 100644 --- a/packages/core/src/engine/manifest.ts +++ b/packages/core/src/engine/manifest.ts @@ -22,6 +22,7 @@ const KNOWN_KEYS = [ 'workers', 'observe', 'readStyle', + 'viewportIntersection', 'locate', 'perform', 'actions', @@ -68,6 +69,7 @@ const RETIRED_HOOKS: Readonly(declared: EngineSpec< } capabilities.add('location'); } + if (spec.viewportIntersection !== undefined) { + if (!capabilities.has('location')) { + throw invalid(name, 'declares viewportIntersection without locate: it measures located nodes'); + } + capabilities.add('viewport-intersection'); + } if (spec.performAt !== undefined) { if (!capabilities.has('observation')) { throw invalid(name, 'declares performAt without observe: a point is read off the observation pixels'); diff --git a/packages/core/src/engine/protocol/protocol.ts b/packages/core/src/engine/protocol/protocol.ts index d03d48290b..7b542c9d5f 100644 --- a/packages/core/src/engine/protocol/protocol.ts +++ b/packages/core/src/engine/protocol/protocol.ts @@ -50,6 +50,7 @@ const lifecycle = (member: LifecycleMethod['member']): LifecycleMethod => ({ kin export const METHODS = { 'engine/observe': operation('observe', ['operation', 'options'], 'snapshot'), 'engine/readStyle': operation('readStyle', ['ref', 'properties', 'operation']), + 'engine/viewportIntersection': operation('viewportIntersection', ['ref', 'operation']), 'engine/locate': operation('locate', ['expression', 'operation']), 'engine/perform': operation('perform', ['ref', 'action', 'operation']), 'engine/performAt': operation('performAt', ['point', 'action', 'operation']), diff --git a/packages/core/src/engine/session.ts b/packages/core/src/engine/session.ts index c1b4ceeb52..2fea0314d6 100644 --- a/packages/core/src/engine/session.ts +++ b/packages/core/src/engine/session.ts @@ -38,6 +38,7 @@ import { type SessionApp, type SessionArtifacts, type TargetSession, + type ViewportIntersection, } from './surface.ts'; export interface EngineSessionOptions { @@ -293,6 +294,7 @@ export function createEngineSession(options: EngineSessionOptions): TargetSessio const locateRaw = guard('locators (screen)', engine?.locate); const observeRaw = guard('observation', engine?.observe); const readStyleRaw = guard('computed styles', engine?.readStyle); + const viewportIntersectionRaw = guard('viewport geometry (toBeInViewport)', engine?.viewportIntersection); const performRaw = guard('actions', engine?.perform); const actions: ReadonlySet = new Set(engine?.actions ?? []); const performAtRaw = guard('point actions', engine?.performAt); @@ -339,6 +341,7 @@ export function createEngineSession(options: EngineSessionOptions): TargetSessio actions, pointerActions, tapModifiers, + measuresViewport: engine?.viewportIntersection !== undefined, app, artifacts, appLog: createAppLogRoute(), @@ -459,6 +462,10 @@ export function createEngineSession(options: EngineSessionOptions): TargetSessio return node; }, readStyle: readStyleRaw, + async viewportIntersection(ref, operation) { + rejectSupersededLocate(ref); + return checkIntersection(await viewportIntersectionRaw(ref, operation), engine?.name ?? targetName); + }, async perform(ref, action, operation) { if (!actions.has(action.kind)) unsupported(`the "${action.kind}" action`); if ('modifiers' in action && action.modifiers !== undefined && !tapModifiers) { @@ -499,3 +506,22 @@ export function createEngineSession(options: EngineSessionOptions): TargetSessio }; return session; } + +/** + * An engine's `viewportIntersection` answer, held to the contract: a matcher + * must never pass on a ratio outside 0 to 1, a missing verdict, or a ratio + * that contradicts the verdict (`{ intersects: false, ratio: 1 }`). + */ +function checkIntersection(value: ViewportIntersection, engineName: string): ViewportIntersection { + const { intersects, ratio } = (value ?? {}) as Partial>; + const validRatio = + ratio === undefined || (typeof ratio === 'number' && ratio >= 0 && ratio <= 1 && ratio > 0 === intersects); + if (typeof intersects !== 'boolean' || !validRatio) { + throw new EngineError( + 'ENGINE_FAILURE', + `engine ${engineName} returned an invalid viewport intersection: intersects must be a boolean, and ratio a number from 0 to 1 that is above 0 exactly when intersects is true`, + { retryable: false }, + ); + } + return ratio === undefined ? { intersects } : { intersects, ratio }; +} diff --git a/packages/core/src/engine/surface.ts b/packages/core/src/engine/surface.ts index 761ef1bbe5..9457eacf44 100644 --- a/packages/core/src/engine/surface.ts +++ b/packages/core/src/engine/surface.ts @@ -20,6 +20,7 @@ import type { PointerActionKind, ScrollDirection, SemanticNode, + ViewportIntersection, ViewportPoint, ViewportSize, } from './contract.ts'; @@ -197,6 +198,8 @@ export interface TargetSession { readonly pointerActions: ReadonlySet; /** Whether the engine declared `tapModifiers`, so the tap actions may carry `modifiers`. */ readonly tapModifiers: boolean; + /** Whether the engine implements `viewportIntersection`, so `toBeInViewport` can refuse before it waits for a match. */ + readonly measuresViewport: boolean; /** Captures one atomic agent observation; the harness redacts it downstream. */ observe(operation: OperationContext, options?: EngineObserveOptions): Promise; /** Resolves immediately; the runner owns query polling and strictness. */ @@ -205,6 +208,8 @@ export interface TargetSession { read(ref: NodeRef, operation: OperationContext): Promise; /** Reads requested rendered properties without changing app state. */ readStyle(ref: NodeRef, properties: readonly ComputedStyleProperty[], operation: OperationContext): Promise; + /** Measures how much of a located node is inside the viewport, checked against the contract's shape. */ + viewportIntersection(ref: NodeRef, operation: OperationContext): Promise; /** Performs exactly one action on a located or observed node. */ perform(ref: NodeRef, action: LocatorAction, operation: OperationContext): Promise; /** diff --git a/packages/core/src/locator/engine.ts b/packages/core/src/locator/engine.ts index 8314af9498..61bd77d1a6 100644 --- a/packages/core/src/locator/engine.ts +++ b/packages/core/src/locator/engine.ts @@ -8,6 +8,7 @@ import { type OperationContext, type PointerAction, type SemanticNode, + type ViewportIntersection, type ViewportPoint, type ViewportSize, } from '../engine/surface.ts'; @@ -444,7 +445,41 @@ if (sampled && reads.cutOff(cause)) throw await notFound(cause); reads: ReadWindow, missingFrame: MissingFrame = 'wait', ): Promise<{ node: SemanticNode | null; count: number }> { - return this.readOne(expression, reads, missingFrame); + const { node, count } = await this.readOne(expression, reads, missingFrame); + return { node, count }; + } + + /** + * Reads the one current match and measures how much of it is inside the + * viewport, for `toBeInViewport`: one resolve, one read from it, and one + * measure of the same ref, all inside `reads`, never a second observation. + * Zero matches or a missing frame read as no node. A ref that went stale + * before it was read or measured is `stale`, so the poll samples again + * instead of reading the node as gone. An engine that cannot measure is + * refused before the resolve, so a missing match never hides it. + */ + async readViewport( + expression: LocatorExpression, + reads: ReadWindow, + ): Promise<{ node: SemanticNode | null; count: number; stale: boolean; intersection?: ViewportIntersection }> { + if (!this.session.measuresViewport) { + throw new ConfigurationError( + 'UNSUPPORTED_CAPABILITY', + 'toBeInViewport is not available on this target: its engine does not implement viewportIntersection', + ); + } + const { node, count, stale } = await this.readOne(expression, reads, 'empty'); + if (stale) return { node: null, count: 1, stale }; + if (node === null) return { node, count, stale }; + try { + const intersection = await reads.read((timeoutMs) => + this.session.viewportIntersection(node.ref, this.readOperation(timeoutMs)), + ); + return { node, count, stale, intersection }; + } catch (cause) { + if (asEngineError(cause)?.code === 'NODE_STALE') return { node, count, stale: true }; + throw translateLocatorError(cause, expression); + } } /** @@ -457,19 +492,24 @@ if (sampled && reads.cutOff(cause)) throw await notFound(cause); return node; } + /** + * Resolves and reads the one current match. A ref superseded between the + * resolve and the read is no node with `stale` set: most callers read it as + * gone, and `readViewport` samples again. + */ private async readOne( expression: LocatorExpression, reads: ReadWindow, missingFrame: MissingFrame, - ): Promise<{ node: SemanticNode | null; count: number }> { + ): Promise<{ node: SemanticNode | null; count: number; stale: boolean }> { const ref = await this.singleOf(await this.resolveOnce(expression, reads, missingFrame), expression); - if (ref === null) return { node: null, count: 0 }; + if (ref === null) return { node: null, count: 0, stale: false }; try { const node = await reads.read((timeoutMs) => this.session.read(ref, this.readOperation(timeoutMs))); - return { node, count: 1 }; + return { node, count: 1, stale: false }; } catch (cause) { if (asEngineError(cause)?.code === 'NODE_STALE') { - return { node: null, count: 0 }; + return { node: null, count: 0, stale: true }; } throw translateLocatorError(cause, expression); } diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index c39647f428..88e8489d4d 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -1101,6 +1101,12 @@ export interface AsyncExpectation { toBeVisible(options?: { visible?: boolean; timeout?: number }): Promise; /** Waits for hidden or absent state. */ toBeHidden(options?: { timeout?: number }): Promise; + /** + * Waits for part of the match to be inside the viewport, after clipping by + * scrolling and overflow ancestors; `ratio` (0 to 1) sets the share of its + * box that must be. No match is outside the viewport. It never scrolls. + */ + toBeInViewport(options?: { ratio?: number; timeout?: number }): Promise; /** Waits for one match to exist, visible or not; `attached: false` waits for none. */ toBeAttached(options?: { attached?: boolean; timeout?: number }): Promise; /** Waits for enabled state; `enabled: false` waits for disabled state. */ diff --git a/packages/e2e/schema/engine-manifest-v1.schema.json b/packages/e2e/schema/engine-manifest-v1.schema.json index 7866ca3753..0d54b3aae3 100644 --- a/packages/e2e/schema/engine-manifest-v1.schema.json +++ b/packages/e2e/schema/engine-manifest-v1.schema.json @@ -41,6 +41,7 @@ "enum": [ "engine/observe", "engine/readStyle", + "engine/viewportIntersection", "engine/locate", "engine/perform", "engine/performAt", @@ -226,6 +227,7 @@ "engine/perform", "engine/locate", "engine/readStyle", + "engine/viewportIntersection", "engine/performAt", "keyboard/type", "keyboard/press", diff --git a/packages/e2e/schema/fixtures/engine-manifest-v1.invalid.json b/packages/e2e/schema/fixtures/engine-manifest-v1.invalid.json index f142c3bf7e..e3ec932e62 100644 --- a/packages/e2e/schema/fixtures/engine-manifest-v1.invalid.json +++ b/packages/e2e/schema/fixtures/engine-manifest-v1.invalid.json @@ -1,7 +1,8 @@ { - "name": "web", + "name": "android", "version": "0.1.0", "spiVersion": 1, - "methods": ["engine/observe", "engine/perform"], - "actions": ["setInputFiles", "setInputFilePayloads", "setInputFilePayloads"] + "methods": [ + "engine/viewportIntersection" + ] } diff --git a/packages/e2e/schema/fixtures/engine-manifest-v1.valid.json b/packages/e2e/schema/fixtures/engine-manifest-v1.valid.json index 4bc10f027b..5a4ad9d0ca 100644 --- a/packages/e2e/schema/fixtures/engine-manifest-v1.valid.json +++ b/packages/e2e/schema/fixtures/engine-manifest-v1.valid.json @@ -7,6 +7,8 @@ "methods": [ "engine/observe", "engine/readStyle", + "engine/viewportIntersection", + "engine/locate", "engine/perform", "engine/performAt", "keyboard/type", diff --git a/packages/e2e/src/expect/async.ts b/packages/e2e/src/expect/async.ts index ab77f7053e..5028aa9fc2 100644 --- a/packages/e2e/src/expect/async.ts +++ b/packages/e2e/src/expect/async.ts @@ -1,7 +1,7 @@ /** Runner-owned polling locator assertions. */ -import type { SemanticNode } from '@e2e-dev/core/lib/engine/surface'; -import { TestError } from '@e2e-dev/core/lib/internal/errors'; +import type { SemanticNode, ViewportIntersection } from '@e2e-dev/core/lib/engine/surface'; +import { ConfigurationError, TestError } from '@e2e-dev/core/lib/internal/errors'; import { rejectUnknownOptions } from '@e2e-dev/core/lib/internal/options'; import { isTextMatch, @@ -30,15 +30,27 @@ import type { import { labelAmbiguous, withMessage } from './heading.ts'; import { expectScreenshot } from './screenshot.ts'; +/** Slack on a measured share, so `ratio: 0.5` passes on a box measured at 0.4999999999. */ +const RATIO_TOLERANCE = 1e-9; + interface Sample { readonly count: number; readonly node: SemanticNode | null; /** Every current match, read; only a `wholeSet: 'read'` matcher asks for them. */ readonly nodes: readonly SemanticNode[]; + /** How much of `node` is inside the viewport, for a `measuresViewport` matcher. */ + readonly intersection?: ViewportIntersection; + /** + * The ref went stale before it was read or measured. Such a sample is never + * evaluated, negated or not: a node a race superseded is not a gone one. + */ + readonly stale?: boolean; } interface MatcherSpec { readonly name: string; + /** Also measures how much of the one match is inside the viewport (`Sample.intersection`). */ + readonly measuresViewport?: boolean; /** * Evaluates the whole sample instead of requiring one node: `true` counts * the matches, `'read'` also reads each of them. @@ -229,6 +241,7 @@ class AsyncExpectationImpl implements AsyncExpectation { * visibility matchers also accept zero matches. */ private conditionEvaluable(spec: MatcherSpec, sample: Sample): boolean { + if (sample.stale === true) return false; if (spec.wholeSet !== undefined) return true; if (sample.node === null) return spec.evaluableWithoutNode === true; return spec.evaluableNode?.(sample.node) ?? true; @@ -236,6 +249,10 @@ class AsyncExpectationImpl implements AsyncExpectation { private async sample(spec: MatcherSpec, reads: ReadWindow): Promise { const { engine } = this.internals.context; + if (spec.measuresViewport === true) { + const { node, count, stale, intersection } = await engine.readViewport(this.internals.expression, reads); + return { count, node, nodes: [], stale, ...(intersection === undefined ? {} : { intersection }) }; + } if (spec.wholeSet === 'read') { const nodes = await engine.readAllNow(this.internals.expression, reads); return { count: nodes.length, node: null, nodes }; @@ -364,6 +381,47 @@ class AsyncExpectationImpl implements AsyncExpectation { return this.visibilityMatcher('toBeHidden', false, options?.timeout); } + toBeInViewport(options?: { ratio?: number; timeout?: number }): Promise { + const api = this.api('toBeInViewport'); + rejectUnknownOptions(api, options, ['ratio', 'timeout']); + const ratio: unknown = options?.ratio; + if (ratio !== undefined && !(typeof ratio === 'number' && ratio >= 0 && ratio <= 1)) { + throw new TestError('INVALID_ARGUMENT', `${api} option ratio must be a number from 0 to 1`); + } + // 0 asks for any area inside, as the default does. + const minimum = ratio === 0 ? undefined : ratio; + return this.poll( + { + name: 'toBeInViewport', + measuresViewport: true, + // No match is outside the viewport: a device leaves offscreen nodes out of its tree. + evaluableWithoutNode: true, + predicate: ({ node, intersection }) => { + if (node === null || intersection === undefined || !intersection.intersects) return false; + if (minimum === undefined) return true; + if (intersection.ratio === undefined) { + throw new ConfigurationError( + 'UNSUPPORTED_CAPABILITY', + `${api} option ratio needs the share of the box inside the viewport, and this target's engine reports only the part of a box that is visible; drop ratio to check that any of it is`, + ); + } + return intersection.ratio > minimum - RATIO_TOLERANCE; + }, + describeExpected: + minimum === undefined ? 'inside the viewport' : `at least ${minimum} of its box inside the viewport`, + observed: ({ node, stale, intersection }) => { + if (stale === true) return 'a node that went stale before it was measured'; + if (node === null || intersection === undefined) return 'no node'; + if (!intersection.intersects) return 'outside the viewport'; + return intersection.ratio === undefined + ? 'inside the viewport' + : `${describeRatio(intersection.ratio, minimum)} of its box inside the viewport`; + }, + }, + options?.timeout, + ); + } + toBeAttached(options?: { attached?: boolean; timeout?: number }): Promise { const attached = this.readOptions('toBeAttached', options, 'attached') ?? true; return this.poll( @@ -520,6 +578,18 @@ class AsyncExpectationImpl implements AsyncExpectation { } } +/** + * A measured share as a failure message prints it: three decimals, unless + * rounding would put it on the other side of `minimum` than the comparison + * did (0.99975 against 1 would print as 1), then in full. + */ +function describeRatio(ratio: number, minimum: number | undefined): string { + const rounded = Number(ratio.toFixed(3)); + if (minimum === undefined) return String(rounded); + const met = ratio > minimum - RATIO_TOLERANCE; + return rounded >= minimum === met ? String(rounded) : String(ratio); +} + /** A list of text matches, as opposed to one string or RegExp. */ function isTextMatchList(expected: TextMatch | readonly TextMatch[]): expected is readonly TextMatch[] { return Array.isArray(expected); diff --git a/packages/e2e/tests/helpers/screen-over.ts b/packages/e2e/tests/helpers/screen-over.ts index 41c8c3e277..7979b09b47 100644 --- a/packages/e2e/tests/helpers/screen-over.ts +++ b/packages/e2e/tests/helpers/screen-over.ts @@ -1,6 +1,6 @@ /** * A `screen` over an in-memory engine for unit tests of the locator tier: the - * engine is whatever `locate`, `observe`, `perform`, and `keyboard` the test + * engine is whatever `locate`, `observe`, `perform`, `viewportIntersection`, and `keyboard` the test * hands in, wired through the real `LocatorEngine` and `createScreen` with a * `StepRecorder` the test reads back. `createScreenFixture` (screen-fixture.ts) * is the preset over a fixed node list. @@ -17,6 +17,7 @@ import { type NodeRef, type OperationContext, type SemanticNode, + type ViewportIntersection, } from '@e2e-dev/core/lib/engine/index'; import { prepareObservation } from '@e2e-dev/core/lib/agent/observation'; import { createEngineSession } from '@e2e-dev/core/lib/engine/session'; @@ -36,6 +37,8 @@ export interface ScreenOverOptions { readonly perform?: (ref: NodeRef, action: LocatorAction, operation: OperationContext) => void | Promise; /** Action kinds the engine declares with `perform`; default every kind. */ readonly actions?: readonly LocatorActionKind[]; + /** Answers every `viewportIntersection`; without it the engine declares none. */ + readonly viewportIntersection?: (ref: NodeRef) => ViewportIntersection | Promise; /** The keyboard the engine declares, if any. */ readonly keyboard?: EngineKeyboard; /** Writes a screenshot under `artifactsDir` and returns its relative path; without it the engine declares no artifacts. */ @@ -52,7 +55,7 @@ export interface ScreenOverOptions { /** A screen and the recorder of its steps over the engine `options` describe. */ export function screenOver(options: ScreenOverOptions): { screen: Screen; steps: StepRecorder } { - const { perform, screenshot } = options; + const { perform, screenshot, viewportIntersection } = options; const engine = defineEngine({ name: 'fake', version: '1', @@ -67,6 +70,9 @@ export function screenOver(options: ScreenOverOptions): { screen: Screen; steps: await perform(ref, action, operation); }, }), + ...(viewportIntersection === undefined + ? {} + : { viewportIntersection: async (ref: NodeRef) => viewportIntersection(ref) }), ...(options.keyboard === undefined ? {} : { keyboard: options.keyboard }), ...(screenshot === undefined ? {} : { artifacts: { screenshot: async (label: string | undefined) => screenshot(label) } }), ...(options.tapModifiers === undefined ? {} : { tapModifiers: options.tapModifiers }), diff --git a/packages/e2e/tests/integration/mcp-run-code.test.ts b/packages/e2e/tests/integration/mcp-run-code.test.ts index 4c022cedf6..05d4aa8ac9 100644 --- a/packages/e2e/tests/integration/mcp-run-code.test.ts +++ b/packages/e2e/tests/integration/mcp-run-code.test.ts @@ -238,6 +238,13 @@ return (await browser.reload()) === undefined;`); expect(either.text).toContain('Test lines: 1.\n'); }); + it('measures a node against the viewport with toBeInViewport', async () => { + const inside = await runCode("await expect(screen.getByRole('button', 'Increment')).toBeInViewport({ ratio: 1 });"); + expect(inside.isError, inside.text).toBe(false); + const absent = await runCode("await expect(screen.getByRole('button', 'Nowhere')).not.toBeInViewport();"); + expect(absent.isError, absent.text).toBe(false); + }); + it('computes on what it reads: variables, loops, value assertions, a caught failure, a return value, and the console', async () => { const result = await runCode( `const counter = screen.getByRole('status', 'Counter'); diff --git a/packages/e2e/tests/types/sdk-types.ts b/packages/e2e/tests/types/sdk-types.ts index 3a7a9b4ef2..b6f0f59c98 100644 --- a/packages/e2e/tests/types/sdk-types.ts +++ b/packages/e2e/tests/types/sdk-types.ts @@ -545,10 +545,16 @@ void screen.getByRole('button').waitFor({ state: 'gone' }); // Playwright's state flags and ignoreCase are taken where Playwright takes them, and nowhere else. void asyncExpectation.toBeChecked({ checked: false }); void asyncExpectation.toBeVisible({ visible: false, timeout: 1000 }); +void asyncExpectation.toBeInViewport({ ratio: 0 }); +void asyncExpectation.toBeInViewport({ ratio: 0.5, timeout: 1000 }); void asyncExpectation.toContainText('error', { ignoreCase: true }); void asyncExpectation.toHaveAttribute('data-kind', 'error', { ignoreCase: true }); // @ts-expect-error toBeChecked has no indeterminate state void asyncExpectation.toBeChecked({ indeterminate: true }); +// @ts-expect-error toBeInViewport takes a numeric ratio +void asyncExpectation.toBeInViewport({ ratio: 'half' }); +// @ts-expect-error toBeInViewport has no threshold option +void asyncExpectation.toBeInViewport({ threshold: 0.5 }); // @ts-expect-error a value is compared as it is, case included void asyncExpectation.toHaveValue('a', { ignoreCase: true }); // @ts-expect-error presence has no case to ignore diff --git a/packages/e2e/tests/unit/engine-protocol.test.ts b/packages/e2e/tests/unit/engine-protocol.test.ts index 45cac105c6..c6bb9d8a33 100644 --- a/packages/e2e/tests/unit/engine-protocol.test.ts +++ b/packages/e2e/tests/unit/engine-protocol.test.ts @@ -573,6 +573,8 @@ describe('engine protocol', () => { { ...base, methods: ['engine/observe', 'engine/teleport'] }, { ...base, methods: ['engine/readStyle'] }, { ...base, methods: ['engine/observe'], actions: ['tap'] }, + { ...base, methods: ['engine/observe'], actions: ['blur'] }, + { ...base, methods: ['engine/viewportIntersection'] }, { ...base, methods: ['engine/observe'], tapModifiers: true }, { ...base, methods: ['engine/observe'], selectsDevice: true }, // The client serves prepare for finish alone, which would drop the device it never forwards. @@ -586,6 +588,8 @@ describe('engine protocol', () => { expect(validate(refused), JSON.stringify(refused)).toBe(false); expect(() => connectEngine({ manifest: refused as never, transport: loopbackTransport(local) }), JSON.stringify(refused)).toThrow(ConfigurationError); } + // Only a worker-isolated engine names its isolation; `attempt` is the default, left out. + expect(validate({ ...base, methods: ['engine/observe'], isolation: 'attempt' })).toBe(false); }); describe('launch arguments', () => { @@ -686,6 +690,10 @@ describe('engine protocol', () => { expect(() => connectEngine({ manifest: { name: 'x', version: '1', spiVersion: 1, methods: ['engine/perform'] }, transport })).toThrow(/perform without observe/); expect(() => connectEngine({ manifest: { name: 'x', version: '1', spiVersion: 1, methods: ['engine/observe', 'engine/perform'] }, transport })).toThrow(/perform without actions/); expect(() => connectEngine({ manifest: { name: 'x', version: '1', spiVersion: 1, methods: ['engine/observe', 'engine/observe'] }, transport })).toThrow(/twice/); + // The schema cannot require engine/locate beside it: resolveLocators builds locate on the client. + const measuring = { name: 'x', version: '1', spiVersion: 1 as const, methods: ['engine/observe', 'engine/viewportIntersection'] as const }; + expect(() => connectEngine({ manifest: measuring, transport })).toThrow(/viewportIntersection without locate/); + expect(connectEngine({ manifest: measuring, transport, resolveLocators: true }).capabilities.has('viewport-intersection')).toBe(true); }); }); diff --git a/packages/e2e/tests/unit/engine.test.ts b/packages/e2e/tests/unit/engine.test.ts index e91dc97375..0fbfcb0462 100644 --- a/packages/e2e/tests/unit/engine.test.ts +++ b/packages/e2e/tests/unit/engine.test.ts @@ -54,6 +54,13 @@ describe('defineEngine', () => { expect(() => defineEngine({ ...bare, pointerActions: ['tap'], performAt: async () => undefined })).toThrow(/performAt without observe/); }); + it('rejects viewportIntersection without locate: it measures located nodes', () => { + const viewportIntersection = async () => ({ intersects: true }); + expect(() => defineEngine(observingEngine({ viewportIntersection }))).toThrow(/viewportIntersection without locate/); + const handle = defineEngine(observingEngine({ locate: async () => [], viewportIntersection })); + expect(handle.capabilities.has('viewport-intersection')).toBe(true); + }); + it('requires the action list with perform, and perform with the action list', () => { expect(() => defineEngine(observingEngine({ perform: async () => undefined }))).toThrow( /perform without actions: list the action kinds/, diff --git a/packages/e2e/tests/unit/expect-viewport.test.ts b/packages/e2e/tests/unit/expect-viewport.test.ts new file mode 100644 index 0000000000..b583def0d2 --- /dev/null +++ b/packages/e2e/tests/unit/expect-viewport.test.ts @@ -0,0 +1,150 @@ +import { describe, expect, it } from 'vitest'; +import { EngineError, resolveExpression, type SemanticNode, type ViewportIntersection } from '@e2e-dev/core/lib/engine/index'; +import { expect as expectFixture } from '../../src/expect/index.ts'; +import { createScreenFixture } from '../helpers/screen-fixture.ts'; +import { screenOver } from '../helpers/screen-over.ts'; +import { snapshot } from '../helpers/snapshot.ts'; +import { useFakeTime } from '../helpers/fake-time.ts'; + +useFakeTime(); + +const target: SemanticNode = { ref: { id: 'target', revision: '' }, role: 'generic', testId: 'target' }; + +/** A screen whose `target` node is present while `present()` says so, measured by `measure`. */ +function screenMeasuring( + measure: () => ViewportIntersection | Promise, + present: () => boolean = () => true, + node: SemanticNode = target, +) { + return screenOver({ + locate: (expression) => resolveExpression(expression, present() ? [node] : []), + observe: () => snapshot([node]), + viewportIntersection: measure, + timeoutMs: 300, + }).screen; +} + +const failure = (promise: Promise) => promise.then(() => expect.unreachable('expected a failure'), (error: unknown) => error); + +describe('toBeInViewport', () => { + it('passes on any area inside by default and compares the share with ratio', async () => { + const locator = screenMeasuring(() => ({ intersects: true, ratio: 0.1 })).getByTestId('target'); + + await expectFixture(locator).toBeInViewport(); + await expectFixture(locator).toBeInViewport({ ratio: 0 }); + await expectFixture(locator).toBeInViewport({ ratio: 0.1 }); + expect(await failure(expectFixture(locator).toBeInViewport({ ratio: 0.11, timeout: 50 }))).toMatchObject({ + code: 'ASSERTION_FAILED', + message: expect.stringMatching(/expected: at least 0\.11 of its box inside the viewport\nobserved: 0\.1 of its box/), + }); + }); + + it('reads no match and a box outside as outside the viewport', async () => { + const absent = screenMeasuring(() => ({ intersects: true, ratio: 1 }), () => false).getByTestId('target'); + await expectFixture(absent).not.toBeInViewport({ timeout: 50 }); + expect(await failure(expectFixture(absent).toBeInViewport({ timeout: 50 }))).toMatchObject({ + message: expect.stringContaining('observed: no node'), + }); + + const outside = screenMeasuring(() => ({ intersects: false, ratio: 0 })).getByTestId('target'); + await expectFixture(outside).not.toBeInViewport({ timeout: 50 }); + }); + + it('polls until the node enters the viewport', async () => { + let inside = false; + setTimeout(() => (inside = true), 25); + const locator = screenMeasuring(() => (inside ? { intersects: true, ratio: 1 } : { intersects: false, ratio: 0 })); + + await expectFixture(locator.getByTestId('target')).toBeInViewport({ timeout: 200 }); + }); + + it('refuses ratio on an engine that measures only the visible part of a box, even under .not', async () => { + const visiblePart = screenMeasuring(() => ({ intersects: true })).getByTestId('target'); + await expectFixture(visiblePart).toBeInViewport(); + // 0 asks for any part, which needs no share. + await expectFixture(visiblePart).toBeInViewport({ ratio: 0 }); + for (const negated of [false, true]) { + const expectation = negated ? expectFixture(visiblePart).not : expectFixture(visiblePart); + expect(await failure(expectation.toBeInViewport({ ratio: 0.5 }))).toMatchObject({ + code: 'UNSUPPORTED_CAPABILITY', + message: expect.stringContaining('drop ratio'), + }); + } + // Nothing of the node is on screen, so no share is needed to answer. + await expectFixture(screenMeasuring(() => ({ intersects: false })).getByTestId('target')).not.toBeInViewport({ ratio: 0.5 }); + }); + + it('fails at once when the engine cannot measure the node, even under .not', async () => { + const unmeasurable = screenMeasuring(() => { + throw new EngineError('UNSUPPORTED_CAPABILITY', 'node target has no bounds on the screen', { retryable: false }); + }).getByTestId('target'); + expect(await failure(expectFixture(unmeasurable).not.toBeInViewport())).toMatchObject({ code: 'UNSUPPORTED_CAPABILITY' }); + + // Refused before the resolve: a missing match must not let `.not` pass on an engine that cannot measure. + for (const nodes of [[target], []]) { + const noCapability = createScreenFixture(nodes).getByTestId('target'); + expect(await failure(expectFixture(noCapability).not.toBeInViewport())).toMatchObject({ + code: 'UNSUPPORTED_CAPABILITY', + message: expect.stringContaining('does not implement viewportIntersection'), + }); + } + }); + + it('samples a node that went stale before it was measured again instead of reading it as gone', async () => { + let measures = 0; + const flaky = screenMeasuring(() => { + measures += 1; + if (measures === 1) throw new EngineError('NODE_STALE', 'navigation changed', { retryable: true }); + return { intersects: true, ratio: 1 }; + }).getByTestId('target'); + await expectFixture(flaky).toBeInViewport({ timeout: 200 }); + expect(measures).toBe(2); + + const stale = screenMeasuring(() => { + throw new EngineError('NODE_STALE', 'navigation changed', { retryable: true }); + }).getByTestId('target'); + expect(await failure(expectFixture(stale).not.toBeInViewport({ timeout: 50 }))).toMatchObject({ + code: 'ASSERTION_FAILED', + message: expect.stringContaining('observed: a node that went stale before it was measured'), + }); + }); + + it('measures a secure field without reading or printing its value', async () => { + const secure: SemanticNode = { ...target, role: 'textbox', value: 'hunter2', states: { secure: true } }; + const locator = screenMeasuring(() => ({ intersects: false, ratio: 0 }), () => true, secure).getByTestId('target'); + + await expectFixture(locator).not.toBeInViewport(); + const error = await failure(expectFixture(locator).toBeInViewport({ timeout: 50 })); + expect(error).toMatchObject({ code: 'ASSERTION_FAILED' }); + expect(String((error as Error).message)).not.toContain('hunter2'); + }); + + it('fails on an engine answer outside the contract or one that contradicts itself', async () => { + for (const answer of [ + { intersects: true, ratio: 2 }, + { intersects: false, ratio: -0.1 }, + { intersects: 'yes' } as unknown as ViewportIntersection, + { intersects: false, ratio: 1 }, + { intersects: true, ratio: 0 }, + ]) { + const locator = screenMeasuring(() => answer).getByTestId('target'); + expect(await failure(expectFixture(locator).not.toBeInViewport({ ratio: 1 }))).toMatchObject({ code: 'ENGINE_FAILURE' }); + } + }); + + it('prints a share that falls short of ratio in full when rounding would show it as met', async () => { + const locator = screenMeasuring(() => ({ intersects: true, ratio: 0.99975 })).getByTestId('target'); + expect(await failure(expectFixture(locator).toBeInViewport({ ratio: 1, timeout: 50 }))).toMatchObject({ + message: expect.stringContaining('observed: 0.99975 of its box inside the viewport'), + }); + }); + + it('rejects an invalid ratio and unknown options before reading', () => { + const locator = expectFixture(createScreenFixture([target]).getByTestId('target')); + + for (const ratio of [-0.1, 1.1, Number.NaN, '0.5']) { + expect(() => locator.toBeInViewport({ ratio: ratio as number })).toThrow(expect.objectContaining({ code: 'INVALID_ARGUMENT' })); + } + expect(() => locator.toBeInViewport({ threshold: 0.5 } as never)).toThrow(expect.objectContaining({ code: 'INVALID_ARGUMENT' })); + }); +}); diff --git a/packages/e2e/tests/unit/locator-engine.test.ts b/packages/e2e/tests/unit/locator-engine.test.ts index 082938d72b..73b3326ec5 100644 --- a/packages/e2e/tests/unit/locator-engine.test.ts +++ b/packages/e2e/tests/unit/locator-engine.test.ts @@ -112,6 +112,10 @@ function makeEngine(script: ScreenScript, options: { actionTimeout?: number; bud }, actions: new Set(LOCATOR_ACTION_KINDS), pointerActions: new Set(['tap']), + measuresViewport: true, + async viewportIntersection() { + return { intersects: true, ratio: 1 }; + }, } as unknown as TargetSession; const engine = new LocatorEngine({ session, @@ -124,6 +128,20 @@ function makeEngine(script: ScreenScript, options: { actionTimeout?: number; bud return { engine, calls, origins, resolveTimeouts, performed }; } +describe('readViewport', () => { + it('reads a ref superseded between the resolve and the read as stale, not as gone', async () => { + const { engine } = makeEngine({ read: ['stale'] }); + const reads = engine.reads(engine.deadline(1_000)); + expect(await engine.readViewport(EXPRESSION, reads)).toEqual({ node: null, count: 1, stale: true }); + expect(await engine.readViewport(EXPRESSION, reads)).toEqual({ + node: NODE, + count: 1, + stale: false, + intersection: { intersects: true, ratio: 1 }, + }); + }); +}); + describe('locator.blur', () => { it.each([true, false])('honors the declared capability (supported: %s)', async (supported) => { const locate = vi.fn(async () => [NODE]); diff --git a/packages/e2e/tests/unit/schema-fixtures.test.ts b/packages/e2e/tests/unit/schema-fixtures.test.ts index b3a2a6c261..376045cedb 100644 --- a/packages/e2e/tests/unit/schema-fixtures.test.ts +++ b/packages/e2e/tests/unit/schema-fixtures.test.ts @@ -53,10 +53,19 @@ describe.each(schemas)('%s schema', (name) => { }); it('rejects the duplicate payload action specifically', () => { - expect(validate(readJson('fixtures', 'engine-manifest-v1.invalid.json'))).toBe(false); + expect(validate({ + name: 'web', version: '0.1.0', spiVersion: 1, + methods: ['engine/observe', 'engine/perform'], + actions: ['setInputFiles', 'setInputFilePayloads', 'setInputFilePayloads'], + })).toBe(false); expect(validate.errors).toEqual([expect.objectContaining({ instancePath: '/actions', keyword: 'uniqueItems' })]); }); + it('rejects the invalid fixture for viewportIntersection without engine/observe', () => { + expect(validate(readJson('fixtures', 'engine-manifest-v1.invalid.json'))).toBe(false); + expect(validate.errors).toEqual(expect.arrayContaining([expect.objectContaining({ instancePath: '/methods', keyword: 'contains' })])); + }); + it('rejects a method listed twice', () => { const manifest = readJson('fixtures', 'engine-manifest-v1.valid.json') as { methods: string[] }; manifest.methods.push('lifecycle/doctor'); diff --git a/packages/mobile/src/engine.ts b/packages/mobile/src/engine.ts index 56efd5e198..9ca24ab590 100644 --- a/packages/mobile/src/engine.ts +++ b/packages/mobile/src/engine.ts @@ -48,6 +48,7 @@ export function buildEngine(surface: AgentDeviceSurface): MobileEngine { // operation enforces its own; see InputBudget in support.ts. observe: (operation, options) => surface.observe(operation, options, surface.inputBudget('observe', operation)), locate: (expression, operation) => surface.locate(expression, operation, surface.inputBudget('locate', operation)), + viewportIntersection: (ref, operation) => surface.viewportIntersection(ref, operation, surface.inputBudget('viewport intersection', operation)), perform: (ref, action, operation) => surface.perform(ref, action, operation, surface.inputBudget(action.kind, operation)), actions: DEVICE_ACTIONS, performAt: (point, action, operation) => surface.performAt(point, action, operation, surface.inputBudget(action.kind, operation)), diff --git a/packages/mobile/src/surface.ts b/packages/mobile/src/surface.ts index ed642dbe2d..2a8d44ae42 100644 --- a/packages/mobile/src/surface.ts +++ b/packages/mobile/src/surface.ts @@ -43,6 +43,7 @@ import { type ProviderRecording, type VideoSegment, type SemanticNode, + type ViewportIntersection, type ViewportPoint, type ViewportSize, ConfigurationError, @@ -228,6 +229,8 @@ interface NodeBinding { readonly keyboardVisible: boolean; /** Whether the capture `node.rect` came from could not place its window on the screen. */ readonly originUnknown: boolean; + /** The size that capture read off its own tree, which `viewportFor` checks against the screen. */ + readonly captureViewport: ViewportSize | undefined; /** Whether `fill` and `clear` may type into the node, judged with the children `node` leaves out. */ readonly takesText: boolean; } @@ -1224,8 +1227,7 @@ export class AgentDeviceSurface { * measures every rect and point against the viewport, so an invented one * would misplace every tap. */ - private async viewportFor(projected: ProjectedSnapshot, signal: AbortSignal, budget: InputBudget): Promise { - const read = projected.viewport; + private async viewportFor(read: ViewportSize | undefined, signal: AbortSignal, budget: InputBudget): Promise { const known = this.knownViewport; if (known !== undefined) { if (read === undefined) return known; @@ -1258,7 +1260,7 @@ export class AgentDeviceSurface { async viewport(operation: OperationContext, budget: InputBudget): Promise { const raw = await this.snapshotOrEmpty(operation, this.interactiveSnapshots, budget); const projected = this.project(raw); - const { width, height } = await this.viewportFor(projected, operation.signal, budget); + const { width, height } = await this.viewportFor(projected.viewport, operation.signal, budget); return { width, height }; } @@ -1266,7 +1268,7 @@ export class AgentDeviceSurface { const raw = await this.snapshotOrEmpty(operation, this.interactiveSnapshots, budget); const projected = this.project(raw); this.generation = new Map(projected.index.map((entry) => [entry.id, this.bind(entry, projected)])); - const viewport = await this.viewportFor(projected, operation.signal, budget); + const viewport = await this.viewportFor(projected.viewport, operation.signal, budget); const location = screenLocation(raw.appBundleId ?? raw.appName ?? this.appIdentity, screenTitle(projected)); const capture = options?.pixels === true ? await this.capturePixels(operation, projected, viewport, { normalizeStatusBar: options.comparable === true }, budget) : undefined; const keyboardVisible = measuredKeyboard(raw); @@ -1316,6 +1318,37 @@ export class AgentDeviceSurface { ); } + /** + * Whether a positive area of a node is on the screen, read off the capture + * that located it. agent-device clips each rect to the window and to its + * scrolling ancestors, and leaves out a node with nothing on screen, so a + * rect is only the visible part of a box: the share of the whole is + * unknown, and the answer carries no `ratio`. The screen is the one + * `viewportFor` confirms, as `observe` does: a capture whose size is not + * the known screen's asks the device, since an app drawn smaller than the + * screen shrinks it and a resized screen (a foldable, Split View) grows it. + * A rect whose window could not be placed on the screen is refused rather + * than guessed at. + */ + async viewportIntersection(ref: NodeRef, operation: OperationContext, budget: InputBudget): Promise { + const entry = this.resolveRef(ref); + const rect = entry.node.rect; + if (entry.originUnknown) { + throw new EngineError('UNSUPPORTED_CAPABILITY', `whether node ${ref.id} is in the viewport is unknown: the ${ORIGIN_UNKNOWN_BOUNDS}`, { + retryable: false, + }); + } + if (rect === undefined) { + throw new EngineError('UNSUPPORTED_CAPABILITY', `node ${ref.id} has no bounds on the screen, so whether it is in the viewport is unknown`, { + retryable: false, + }); + } + const screen = await this.viewportFor(entry.captureViewport, operation.signal, budget); + const width = Math.min(rect.x + rect.width, screen.width) - Math.max(rect.x, 0); + const height = Math.min(rect.y + rect.height, screen.height) - Math.max(rect.y, 0); + return { intersects: width > 0 && height > 0 }; + } + private resolveRef(ref: NodeRef): NodeBinding { const entry = this.located.get(ref.id) ?? this.generation.get(ref.id); if (entry === undefined) { @@ -1364,6 +1397,7 @@ export class AgentDeviceSurface { controlRef: control.ref, keyboardVisible: snapshot.keyboardVisible, originUnknown: snapshot.originUnknown, + captureViewport: snapshot.viewport, takesText: mayTakeText(entry.node), refsGeneration: snapshot.refsGeneration, }; @@ -1821,7 +1855,7 @@ export class AgentDeviceSurface { for (const axis of ['horizontal', 'vertical'] as const) { const { raw } = reading; const projected = projectSnapshot(raw.nodes ?? [], { mintId: () => 'keyboard', viewport: raw.viewport }); - const viewport = await this.viewportFor(projected, signal, input); + const viewport = await this.viewportFor(projected.viewport, signal, input); const top = keyboardTop(raw, viewport); if (top === undefined) { throw new EngineError( diff --git a/packages/mobile/tests/unit/engine.test.ts b/packages/mobile/tests/unit/engine.test.ts index e0b946130c..326280a87e 100644 --- a/packages/mobile/tests/unit/engine.test.ts +++ b/packages/mobile/tests/unit/engine.test.ts @@ -100,7 +100,7 @@ async function screenRootOf(h: Harness): Promise { describe('manifest', () => { it('declares observation, actions, location, artifacts, the device fixture, and session hooks', () => { const pinned = harness().engine; - expect([...pinned.capabilities].toSorted()).toEqual(['actions', 'artifacts', 'device', 'keyboard', 'location', 'observation', 'pointer']); + expect([...pinned.capabilities].toSorted()).toEqual(['actions', 'artifacts', 'device', 'keyboard', 'location', 'observation', 'pointer', 'viewport-intersection']); expect(pinned.name).toBe('mobile'); expect(describeEngine(pinned).launchArgumentValues).toBe(true); expect(pinned.version).not.toBe('unknown'); @@ -1791,6 +1791,60 @@ describe('location', () => { ]); }); + it('answers whether a located node is on the screen, never the share agent-device clipped away', async () => { + const h = harness(); + h.fake.respond('capture.snapshot', () => ({ + ...SETTINGS_SNAPSHOT, + nodes: [ + ...SETTINGS_NODES, + { ref: '@e11', index: 11, parentIndex: 0, depth: 1, type: 'button', label: 'Unplaced' }, + { ref: '@e12', index: 12, parentIndex: 0, depth: 1, type: 'button', label: 'Lower', rect: { x: 10, y: 600, width: 100, height: 40 } }, + ], + })); + await openAttempt(h); + const measure = async (label: string) => { + const [node] = await h.engine.locate!({ kind: 'query', query: { kind: 'text', value: { kind: 'string', value: label, exact: true } } }, operation()); + const issued = h.fake.calls.length; + // Read off the capture the locate took: no second snapshot, no device command. + return h.engine.viewportIntersection!(node!.ref, operation()).finally(() => expect(h.fake.calls).toHaveLength(issued)); + }; + expect(await measure('About')).toEqual({ intersects: true }); + // Below y 390 on the 390x844 screen: the height is measured against the height, not the width. + expect(await measure('Lower')).toEqual({ intersects: true }); + expect(await measure('Password')).toEqual({ intersects: true }); + // Below the 844-point screen. + expect(await measure('Hidden')).toEqual({ intersects: false }); + await expect(measure('Unplaced')).rejects.toMatchObject({ code: 'UNSUPPORTED_CAPABILITY' }); + }); + + it('measures against a resized screen once the device confirms it, without waiting for an observe', async () => { + const h = harness(); + await openAttempt(h); + const below = { ref: '@e11', index: 11, parentIndex: 0, depth: 1, type: 'button', label: 'Below', rect: { x: 10, y: 850, width: 100, height: 20 } }; + const locateBelow = async () => { + const [node] = await h.engine.locate!({ kind: 'query', query: { kind: 'text', value: { kind: 'string', value: 'Below', exact: true } } }, operation()); + return h.engine.viewportIntersection!(node!.ref, operation()); + }; + h.fake.respond('capture.snapshot', () => ({ ...SETTINGS_SNAPSHOT, nodes: [...SETTINGS_NODES, below] })); + expect(await locateBelow()).toEqual({ intersects: false }); + + // A foldable unfolds: the tree grows to 402x874, and the device's screen agrees. + h.fake.respond('capture.snapshot', () => ({ ...SETTINGS_SNAPSHOT, nodes: [...SETTINGS_NODES, below], viewport: { width: 402, height: 874 } })); + h.fake.respond('capture.screenshot', () => ({ logicalWidth: 402, logicalHeight: 874 })); + expect(await locateBelow()).toEqual({ intersects: true }); + }); + + it('refuses to say whether a node is in the viewport when its window has no known place on the screen', async () => { + const h = harness(); + h.fake.respond('capture.snapshot', () => ({ ...SETTINGS_SNAPSHOT, warnings: [ORIGIN_WARNING] })); + await openAttempt(h); + const [hidden] = await h.engine.locate!({ kind: 'query', query: { kind: 'text', value: { kind: 'string', value: 'Hidden', exact: true } } }, operation()); + await expect(h.engine.viewportIntersection!(hidden!.ref, operation())).rejects.toMatchObject({ + code: 'UNSUPPORTED_CAPABILITY', + message: expect.stringContaining(ORIGIN_UNKNOWN_BOUNDS), + }); + }); + it('finds an Android view by its id without its package', async () => { const h = harness({ platform: 'android' }); await openAttempt(h); @@ -3634,6 +3688,20 @@ describe('device fixture', () => { }); }); + it('measures toBeInViewport against the unfolded screen after fold', async () => { + const h = harness({ platform: 'android', bundleId: 'com.example.app' }); + // A real device's screenshot reports no logical size, so the tree's size stands once it changes. + h.fake.respond('capture.screenshot', () => ({ width: 1236, height: 2745 })); + h.fake.respond('capture.snapshot', () => ({ ...SETTINGS_SNAPSHOT, viewport: { width: 412, height: 915 } })); + await openAttempt(h); + await h.engine.observe!(operation()); + await fixture(h).fold('open'); + const inner = { ref: '@e11', index: 11, parentIndex: 0, depth: 1, type: 'button', label: 'Inner pane', rect: { x: 600, y: 100, width: 120, height: 40 } }; + h.fake.respond('capture.snapshot', () => ({ ...SETTINGS_SNAPSHOT, nodes: [...SETTINGS_NODES, inner], viewport: { width: 841, height: 701 } })); + const [node] = await h.engine.locate!({ kind: 'query', query: { kind: 'text', value: { kind: 'string', value: 'Inner pane', exact: true } } }, operation()); + expect(await h.engine.viewportIntersection!(node!.ref, operation())).toEqual({ intersects: true }); + }); + it('folds an iOS simulator or an Android emulator through the one device command, and maps a hingeless device to UNSUPPORTED_CAPABILITY', async () => { const ios = harness(); await openAttempt(ios); diff --git a/packages/web/src/engine.ts b/packages/web/src/engine.ts index 8bf416da6b..736e05ba0d 100644 --- a/packages/web/src/engine.ts +++ b/packages/web/src/engine.ts @@ -131,6 +131,7 @@ export function web(options: WebOptions = {}): WebEngine { dispose: (context) => surface.dispose(context), observe: (operation, observeOptions) => surface.observe(operation, observeOptions), readStyle: (ref, properties, operation) => surface.readStyle(ref, properties, operation), + viewportIntersection: (ref, operation) => surface.viewportIntersection(ref, operation), locate: (expression, operation) => surface.locate(expression, operation), perform: (ref, action, operation) => surface.perform(ref, action, operation), // A browser honors the SPI v1 actions plus blur and in-memory uploads; `actions.ts` dispatches each. diff --git a/packages/web/src/surface.ts b/packages/web/src/surface.ts index ff8a2a1dff..0372f71711 100644 --- a/packages/web/src/surface.ts +++ b/packages/web/src/surface.ts @@ -41,6 +41,7 @@ import { type Secret, type SemanticNode, type VideoSegment, + type ViewportIntersection, type ViewportPoint, type ViewportSize, } from '@e2e-dev/core/engine'; @@ -963,6 +964,45 @@ export class PlaywrightSurface { }, navigationStaleOr); } + /** + * Measures how much of a located or observed element is inside the + * viewport with the page's `IntersectionObserver`, the check Playwright's + * `toBeInViewport` makes, so scrolling and overflow ancestors and frames + * clip it. An element with no box, or an empty one, is outside. It runs + * in the page's own world, as `readStyle` does, so an app that replaces + * `IntersectionObserver` changes what it reads. + */ + viewportIntersection(ref: NodeRef, operation: OperationContext): Promise { + return this.guard(operation, 'measure viewport intersection', (currentOperation) => this.readingTab(async () => { + const target = await this.requireSession().refs.lookup(ref); + let element: ElementHandle; + if (target.kind === 'element') { + element = target.element; + } else { + // A strict locator that matches anything but one element no longer names the node it located. + const handles = await target.locator.elementHandles(); + if (handles.length !== 1) { + for (const handle of handles) void handle.dispose().catch(() => undefined); + throw new EngineError('NODE_STALE', `node reference ${ref.id} no longer matches one element`, { retryable: true }); + } + element = handles[0]!; + } + try { + currentOperation.signal.throwIfAborted(); + const measured = await element.evaluate(measureViewportIntersection); + if (measured === 'detached') throw new EngineError('NODE_STALE', 'node is detached; locate it again', { retryable: true }); + if (measured === 'unsupported') { + throw new EngineError('UNSUPPORTED_CAPABILITY', 'the browser has no IntersectionObserver to measure the viewport with', { + retryable: false, + }); + } + return measured; + } finally { + if (target.kind === 'locator') void element.dispose().catch(() => undefined); + } + }), navigationStaleOr); + } + // --- location tier --- /** @@ -1511,3 +1551,38 @@ function inFrame(node: SemanticNode, frame: Rect | null | undefined): SemanticNo const { rect, origin, ...rest } = node; return frame === null ? rest : { ...rest, ...placeBoxInFrame(rect, origin, frame) }; } + +/** + * The in-page half of `viewportIntersection`: one `IntersectionObserver` + * callback, which reports the element's first intersection right after it + * is observed. The empty animation frame makes Firefox deliver it. The + * callback's own entry decides: an element the page replaced before it + * fired is stale, and its box and ratio come from that one frame, since a + * zero-area target that intersects reports a ratio of 1. + */ +function measureViewportIntersection(element: Element): Promise { + if (!element.isConnected) return Promise.resolve('detached'); + if (element.getClientRects().length === 0) return Promise.resolve({ intersects: false, ratio: 0 }); + const view = element.ownerDocument.defaultView; + if (view === null || typeof view.IntersectionObserver !== 'function') return Promise.resolve('unsupported'); + return new Promise((resolve) => { + const observer = new view.IntersectionObserver((entries) => { + observer.disconnect(); + if (!element.isConnected) { + resolve('detached'); + return; + } + const entry = entries.at(-1); + const box = entry?.boundingClientRect; + if (entry === undefined || box === undefined || box.width <= 0 || box.height <= 0) { + resolve({ intersects: false, ratio: 0 }); + return; + } + // Clamped: a browser can round a fully visible box a hair past 1. + const ratio = Math.min(1, Math.max(0, entry.intersectionRatio)); + resolve({ intersects: ratio > 0, ratio }); + }); + observer.observe(element); + view.requestAnimationFrame(() => {}); + }); +} diff --git a/packages/web/tests/integration/lifecycle.test.ts b/packages/web/tests/integration/lifecycle.test.ts index 7d32bcfbbd..ae4ebb41c8 100644 --- a/packages/web/tests/integration/lifecycle.test.ts +++ b/packages/web/tests/integration/lifecycle.test.ts @@ -222,6 +222,7 @@ describe('web engine lifecycle', () => { 'observation', 'pointer', 'state', + 'viewport-intersection', ]); expect(engine.name).toBe('web'); }); diff --git a/packages/web/tests/integration/viewport-intersection.test.ts b/packages/web/tests/integration/viewport-intersection.test.ts new file mode 100644 index 0000000000..d3c64165b7 --- /dev/null +++ b/packages/web/tests/integration/viewport-intersection.test.ts @@ -0,0 +1,124 @@ +/** + * `viewportIntersection` measures what Playwright's `toBeInViewport` does: + * the share of an element's box inside the viewport once the viewport and + * every clipping ancestor, a scroll container or a frame included, cut it. + */ + +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import type { Page } from 'playwright-core'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import type { LocatorExpression, NodeRef } from '@e2e-dev/core/engine'; +import { surfaceOf, web } from '../../src/index.ts'; +import { ignoreTrace, noSecrets } from '../helpers/secrets.ts'; + +const BOX = 'position: absolute; width: 100px; height: 100px'; + +const DOCUMENT = ` + +
+
+
+
+
+
+
+
+
+
+
+
+
+ + + +`; + +describe('viewport intersection on the web engine', () => { + const engine = web({}); + const artifactsDir = mkdtempSync(path.join(tmpdir(), 'e2e-viewport-')); + const signal = new AbortController().signal; + const operation = { signal, timeoutMs: 5_000, runId: 'viewport', attemptId: 'attempt', origin: 'test' as const }; + const cleanup = { signal, timeoutMs: 30_000 }; + let page: Page; + + /** The one element `selector` names, inside `frame` when given. */ + async function locate(selector: string, frame?: string): Promise { + const source: LocatorExpression = { kind: 'selector', selector }; + const [node, ...rest] = await engine.locate!(frame === undefined ? source : { kind: 'frame', selector: frame, source }, operation); + expect(rest).toEqual([]); + return node!.ref; + } + + const measure = async (selector: string, frame?: string) => + engine.viewportIntersection!(await locate(selector, frame), operation); + + beforeAll(async () => { + await engine.init!({ runId: 'viewport', targetName: 'fixture', projectRoot: process.cwd(), app: {}, env: {}, headed: false, workerSlot: 0, signal, log: () => undefined }); + await engine.startAttempt!({ attemptId: 'attempt', artifactsDir, signal, resolveSecret: noSecrets, ...ignoreTrace }); + await engine.session!.open!('about:blank', operation); + page = surfaceOf(engine)!.page(); + await page.setContent(DOCUMENT); + await page.frameLocator('#frame').locator('#framed').waitFor({ state: 'attached' }); + }); + + afterAll(async () => { + await engine.endAttempt!(cleanup); + await engine.dispose!(cleanup); + rmSync(artifactsDir, { recursive: true, force: true }); + }); + + it('measures the share of the box the viewport and clipping ancestors leave', async () => { + expect(await measure('#inside')).toEqual({ intersects: true, ratio: 1 }); + expect(await measure('#half-off')).toEqual({ intersects: true, ratio: 0.5 }); + expect(await measure('#below')).toEqual({ intersects: false, ratio: 0 }); + expect(await measure('#half-clipped')).toEqual({ intersects: true, ratio: 0.5 }); + expect(await measure('#clipped-out')).toEqual({ intersects: false, ratio: 0 }); + expect(await measure('#scrolled-away')).toEqual({ intersects: false, ratio: 0 }); + expect(await measure('#framed', '#frame')).toEqual({ intersects: true, ratio: 0.5 }); + }); + + it('reads an element with no box or an empty one as outside', async () => { + expect(await measure('#empty')).toEqual({ intersects: false, ratio: 0 }); + expect(await measure('#flat')).toEqual({ intersects: false, ratio: 0 }); + expect(await measure('#no-box')).toEqual({ intersects: false, ratio: 0 }); + }); + + it('measures a password field like any other element', async () => { + expect(await measure('#secret')).toEqual({ intersects: true, ratio: 1 }); + }); + + it('follows scrolling, and a removed element is stale', async () => { + const below = await locate('#below'); + await page.evaluate(() => window.scrollTo(0, 1950)); + expect(await engine.viewportIntersection!(below, operation)).toEqual({ intersects: true, ratio: 1 }); + await page.evaluate(() => window.scrollTo(0, 0)); + + await page.locator('#below').evaluate((element) => element.remove()); + await expect(engine.viewportIntersection!(below, operation)).rejects.toMatchObject({ code: 'NODE_STALE' }); + }); + + it('reads an element the page replaces every frame as stale, never as outside', async () => { + await page.evaluate(() => { + const make = () => { + const ticker = document.createElement('button'); + ticker.id = 'ticker'; + ticker.textContent = 'Ticker'; + ticker.style.cssText = 'position: fixed; left: 10px; top: 600px'; + return ticker; + }; + document.body.append(make()); + const swap = () => { + document.getElementById('ticker')?.replaceWith(make()); + requestAnimationFrame(swap); + }; + requestAnimationFrame(swap); + }); + for (let round = 0; round < 5; round += 1) { + const ticker = await locate('#ticker'); + await expect(engine.viewportIntersection!(ticker, operation)).rejects.toMatchObject({ code: 'NODE_STALE' }); + } + }); +}); diff --git a/plugins/e2e/skills/e2e/references/writing-tests.md b/plugins/e2e/skills/e2e/references/writing-tests.md index 3415d03e36..54b87bd09d 100644 --- a/plugins/e2e/skills/e2e/references/writing-tests.md +++ b/plugins/e2e/skills/e2e/references/writing-tests.md @@ -282,7 +282,7 @@ substring; a `RegExp` matches as written. `LOCATOR_AMBIGUOUS`; at zero, actions and reads poll until the action timeout then `LOCATOR_NOT_FOUND`, assertions until the assertion timeout then `ASSERTION_FAILED`. Exceptions: - `toHaveCount`, `toBeVisible`, `toBeHidden`, `toBeAttached`, list-form + `toHaveCount`, `toBeVisible`, `toBeHidden`, `toBeAttached`, `toBeInViewport`, list-form `toHaveText` and `toContainText`, `isVisible()` (false at zero), `isHidden()` (true), `count()`, `all()`, `allTextContents()`. - Narrow with `filter({ hasText })` (a case-insensitive substring, unlike a @@ -423,7 +423,7 @@ typed; prefer it when the app already has a schema for the response. | Locator matchers | Browser matchers | Value matchers | | --- | --- | --- | -| `toBeVisible`, `toBeHidden`, `toBeAttached`, `toBeEnabled`, `toBeDisabled`, `toBeEditable`, `toBeChecked`, `toBeSelected`, `toBeExpanded`, `toBeFocused`, `toHaveText`, `toContainText`, `toHaveValue`, `toHaveAttribute`, `toHaveCount`, `toHaveAccessibleName`, `toHaveRole`, `toHaveScreenshot` (also on `screen`) | `toHaveURL`, `toHaveTitle`, `toHaveClass(locator, expected)` | `toBe`, `toEqual`, `toMatchObject`, `toBeTruthy`, `toBeFalsy`, `toBeNull`, `toBeUndefined`, `toBeDefined`, `toHaveLength`, `toHaveProperty`, `toContain`, `toMatch`, `toBeGreaterThan`, `toBeGreaterThanOrEqual`, `toBeLessThan`, `toBeLessThanOrEqual`, `toBeCloseTo`, `toMatchSchema` | +| `toBeVisible`, `toBeHidden`, `toBeInViewport`, `toBeAttached`, `toBeEnabled`, `toBeDisabled`, `toBeEditable`, `toBeChecked`, `toBeSelected`, `toBeExpanded`, `toBeFocused`, `toHaveText`, `toContainText`, `toHaveValue`, `toHaveAttribute`, `toHaveCount`, `toHaveAccessibleName`, `toHaveRole`, `toHaveScreenshot` (also on `screen`) | `toHaveURL`, `toHaveTitle`, `toHaveClass(locator, expected)` | `toBe`, `toEqual`, `toMatchObject`, `toBeTruthy`, `toBeFalsy`, `toBeNull`, `toBeUndefined`, `toBeDefined`, `toHaveLength`, `toHaveProperty`, `toContain`, `toMatch`, `toBeGreaterThan`, `toBeGreaterThanOrEqual`, `toBeLessThan`, `toBeLessThanOrEqual`, `toBeCloseTo`, `toMatchSchema` | `toHaveText` compares the whole normalized text, `toContainText` a substring or RegExp, `toHaveValue` a form control's value as is, whitespace included @@ -434,7 +434,11 @@ in order; `toContainText(['Alpha', 'Beta'])` needs each entry in a distinct match, in order, extra matches allowed. `toHaveAttribute(name)` checks presence, `toHaveAttribute(name, value)` the value; `toBeAttached` waits for a match, hidden or not; `toHaveClass` compares the whole normalized class -list or tests a RegExp. A failed matcher is `ASSERTION_FAILED`, exit code 1. +list or tests a RegExp; `toBeInViewport({ ratio })` waits for part of a match +(or that share of its box) inside the viewport without scrolling, reads no +match as outside, and on a device fails with `UNSUPPORTED_CAPABILITY` for +`ratio > 0` once the node is on screen. A failed matcher is `ASSERTION_FAILED`, +exit code 1. Playwright's `{ checked: false }`, `{ enabled: false }`, `{ editable: false }`, `{ visible: false }`, and `{ attached: false }` flip their matchers, and `{ ignoreCase: true }` diff --git a/skills/e2e/references/writing-tests.md b/skills/e2e/references/writing-tests.md index 3415d03e36..54b87bd09d 100644 --- a/skills/e2e/references/writing-tests.md +++ b/skills/e2e/references/writing-tests.md @@ -282,7 +282,7 @@ substring; a `RegExp` matches as written. `LOCATOR_AMBIGUOUS`; at zero, actions and reads poll until the action timeout then `LOCATOR_NOT_FOUND`, assertions until the assertion timeout then `ASSERTION_FAILED`. Exceptions: - `toHaveCount`, `toBeVisible`, `toBeHidden`, `toBeAttached`, list-form + `toHaveCount`, `toBeVisible`, `toBeHidden`, `toBeAttached`, `toBeInViewport`, list-form `toHaveText` and `toContainText`, `isVisible()` (false at zero), `isHidden()` (true), `count()`, `all()`, `allTextContents()`. - Narrow with `filter({ hasText })` (a case-insensitive substring, unlike a @@ -423,7 +423,7 @@ typed; prefer it when the app already has a schema for the response. | Locator matchers | Browser matchers | Value matchers | | --- | --- | --- | -| `toBeVisible`, `toBeHidden`, `toBeAttached`, `toBeEnabled`, `toBeDisabled`, `toBeEditable`, `toBeChecked`, `toBeSelected`, `toBeExpanded`, `toBeFocused`, `toHaveText`, `toContainText`, `toHaveValue`, `toHaveAttribute`, `toHaveCount`, `toHaveAccessibleName`, `toHaveRole`, `toHaveScreenshot` (also on `screen`) | `toHaveURL`, `toHaveTitle`, `toHaveClass(locator, expected)` | `toBe`, `toEqual`, `toMatchObject`, `toBeTruthy`, `toBeFalsy`, `toBeNull`, `toBeUndefined`, `toBeDefined`, `toHaveLength`, `toHaveProperty`, `toContain`, `toMatch`, `toBeGreaterThan`, `toBeGreaterThanOrEqual`, `toBeLessThan`, `toBeLessThanOrEqual`, `toBeCloseTo`, `toMatchSchema` | +| `toBeVisible`, `toBeHidden`, `toBeInViewport`, `toBeAttached`, `toBeEnabled`, `toBeDisabled`, `toBeEditable`, `toBeChecked`, `toBeSelected`, `toBeExpanded`, `toBeFocused`, `toHaveText`, `toContainText`, `toHaveValue`, `toHaveAttribute`, `toHaveCount`, `toHaveAccessibleName`, `toHaveRole`, `toHaveScreenshot` (also on `screen`) | `toHaveURL`, `toHaveTitle`, `toHaveClass(locator, expected)` | `toBe`, `toEqual`, `toMatchObject`, `toBeTruthy`, `toBeFalsy`, `toBeNull`, `toBeUndefined`, `toBeDefined`, `toHaveLength`, `toHaveProperty`, `toContain`, `toMatch`, `toBeGreaterThan`, `toBeGreaterThanOrEqual`, `toBeLessThan`, `toBeLessThanOrEqual`, `toBeCloseTo`, `toMatchSchema` | `toHaveText` compares the whole normalized text, `toContainText` a substring or RegExp, `toHaveValue` a form control's value as is, whitespace included @@ -434,7 +434,11 @@ in order; `toContainText(['Alpha', 'Beta'])` needs each entry in a distinct match, in order, extra matches allowed. `toHaveAttribute(name)` checks presence, `toHaveAttribute(name, value)` the value; `toBeAttached` waits for a match, hidden or not; `toHaveClass` compares the whole normalized class -list or tests a RegExp. A failed matcher is `ASSERTION_FAILED`, exit code 1. +list or tests a RegExp; `toBeInViewport({ ratio })` waits for part of a match +(or that share of its box) inside the viewport without scrolling, reads no +match as outside, and on a device fails with `UNSUPPORTED_CAPABILITY` for +`ratio > 0` once the node is on screen. A failed matcher is `ASSERTION_FAILED`, +exit code 1. Playwright's `{ checked: false }`, `{ enabled: false }`, `{ editable: false }`, `{ visible: false }`, and `{ attached: false }` flip their matchers, and `{ ignoreCase: true }`