From 501ddd7d92f903dfac7703c7e49279c855f3090e Mon Sep 17 00:00:00 2001 From: Anmol202005 <183815727+Anmol202005@users.noreply.github.com> Date: Wed, 21 Oct 2026 13:32:20 +0530 Subject: [PATCH 01/11] feat(expect): add cross-engine toBeInViewport matcher --- .changeset/viewport-matcher.md | 5 + docs/reference/expect.mdx | 20 ++++ packages/core/src/locator/engine.ts | 21 ++++ packages/core/src/types.ts | 2 + packages/e2e/src/expect/async.ts | 64 ++++++++++ packages/e2e/tests/types/sdk-types.ts | 6 + .../e2e/tests/unit/expect-viewport.test.ts | 109 ++++++++++++++++++ .../skills/e2e/references/writing-tests.md | 2 +- skills/e2e/references/writing-tests.md | 2 +- 9 files changed, 229 insertions(+), 2 deletions(-) create mode 100644 .changeset/viewport-matcher.md create mode 100644 packages/e2e/tests/unit/expect-viewport.test.ts diff --git a/.changeset/viewport-matcher.md b/.changeset/viewport-matcher.md new file mode 100644 index 0000000000..b459236dd1 --- /dev/null +++ b/.changeset/viewport-matcher.md @@ -0,0 +1,5 @@ +--- +"e2e": patch +--- + +Add the cross-engine `toBeInViewport` locator matcher with an optional intersection ratio. diff --git a/docs/reference/expect.mdx b/docs/reference/expect.mdx index 5886afd361..a2d90229c1 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 viewport intersection | | [`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,23 @@ await expect(screen.getByRole('dialog')).not.toBeVisible({ timeout: 10_000 }); await expect(screen.getByRole('dialog')).toBeVisible({ visible: false }); // as toBeHidden() ``` +#### `toBeInViewport` + +Waits until the match's box intersects the viewport. The default passes when +any positive area is inside. Set `ratio` from `0` to `1` to require that share +of the box; `0` also means any positive area. The calculation uses the +reported box and viewport rectangle, ignores clipping by overflow ancestors, +and does not check whether another element covers the match. It never scrolls. +A missing box fails with an unavailable-geometry message, including under +`.not`. It trusts the engine's coordinates, so the result depends on the +engine reporting scroll-aware boxes. + +```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(); +``` + #### `toBeAttached` Waits for one match to exist, hidden or shown, where `toBeVisible` needs a @@ -971,6 +989,8 @@ export interface AsyncExpectation { toBeVisible(options?: { visible?: boolean; timeout?: number }): Promise; /** Waits for hidden or absent state. */ toBeHidden(options?: { timeout?: number }): Promise; + /** Waits until a share of the match's box intersects the viewport. */ + 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/core/src/locator/engine.ts b/packages/core/src/locator/engine.ts index 8314af9498..9cc0a74825 100644 --- a/packages/core/src/locator/engine.ts +++ b/packages/core/src/locator/engine.ts @@ -447,6 +447,27 @@ if (sampled && reads.cutOff(cause)) throw await notFound(cause); return this.readOne(expression, reads, missingFrame); } + /** Reads a matched node's box and the current viewport for geometry assertions. */ + async readWithViewport( + expression: LocatorExpression, + deadline: Deadline, + ): Promise<{ + node: SemanticNode | null; + count: number; + viewport?: { width: number; height: number }; + }> { + const { node, count } = await this.tryRead(expression, deadline); + if (node === null) return { node, count }; + + try { + const observation = await this.session.observe(this.operationWithin(deadline)); + return { node, count, viewport: observation.viewport }; + } catch (cause) { + if (asEngineError(cause)?.code === 'NODE_STALE') return { node: null, count: 0 }; + throw translateLocatorError(cause, expression); + } + } + /** * Reads the one current match at once, for `isVisible` and `isHidden`: * null for zero matches, a missing frame, or a node that went stale; two diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index c39647f428..90b801b9e3 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -1101,6 +1101,8 @@ export interface AsyncExpectation { toBeVisible(options?: { visible?: boolean; timeout?: number }): Promise; /** Waits for hidden or absent state. */ toBeHidden(options?: { timeout?: number }): Promise; + /** Waits until a share of the match's box intersects the viewport. */ + 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/src/expect/async.ts b/packages/e2e/src/expect/async.ts index ab77f7053e..58005ffd95 100644 --- a/packages/e2e/src/expect/async.ts +++ b/packages/e2e/src/expect/async.ts @@ -35,10 +35,13 @@ interface Sample { readonly node: SemanticNode | null; /** Every current match, read; only a `wholeSet: 'read'` matcher asks for them. */ readonly nodes: readonly SemanticNode[]; + readonly viewport?: { width: number; height: number }; } interface MatcherSpec { readonly name: string; + /** Reads the matched node box and the current viewport for a geometry check. */ + readonly needsViewport?: boolean; /** * Evaluates the whole sample instead of requiring one node: `true` counts * the matches, `'read'` also reads each of them. @@ -236,6 +239,12 @@ class AsyncExpectationImpl implements AsyncExpectation { private async sample(spec: MatcherSpec, reads: ReadWindow): Promise { const { engine } = this.internals.context; + if (spec.needsViewport === true) { + return { + ...(await engine.readWithViewport(this.internals.expression, deadline)), + nodes: [], + }; + } if (spec.wholeSet === 'read') { const nodes = await engine.readAllNow(this.internals.expression, reads); return { count: nodes.length, node: null, nodes }; @@ -364,6 +373,44 @@ 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' || !Number.isFinite(ratio) || ratio < 0 || ratio > 1)) { + throw new TestError('INVALID_ARGUMENT', `${api} option ratio must be between 0 and 1`); + } + + const expectedRatio = ratio as number | undefined; + return this.poll( + { + name: 'toBeInViewport', + needsViewport: true, + evaluableNode: (node) => node.rect !== undefined, + predicate: (sample) => { + const rect = sample.node?.rect; + if (rect === undefined || sample.viewport === undefined) return false; + + const intersectionRatio = viewportIntersectionRatio(rect, sample.viewport); + return expectedRatio === undefined || expectedRatio === 0 + ? intersectionRatio > 0 + : intersectionRatio >= expectedRatio; + }, + describeExpected: + expectedRatio === undefined + ? 'a positive area inside the viewport' + : `at least ${expectedRatio} of its area inside the viewport`, + observed: (sample) => { + if (sample.node === null) return 'no node'; + if (sample.node.rect === undefined) return 'no bounding box'; + if (sample.viewport === undefined) return 'no viewport geometry'; + return `bounding box intersection ratio ${viewportIntersectionRatio(sample.node.rect, sample.viewport)}`; + }, + }, + options?.timeout, + ); + } + toBeAttached(options?: { attached?: boolean; timeout?: number }): Promise { const attached = this.readOptions('toBeAttached', options, 'attached') ?? true; return this.poll( @@ -554,6 +601,23 @@ function matchesSubsequence( return next === patterns.length; } +/** The share of a node's box that intersects the viewport. */ +function viewportIntersectionRatio( + rect: { x: number; y: number; width: number; height: number }, + viewport: { width: number; height: number }, +): number { + const area = rect.width * rect.height; + if (area <= 0) return 0; + + const left = Math.max(0, rect.x); + const top = Math.max(0, rect.y); + const right = Math.min(viewport.width, rect.x + rect.width); + const bottom = Math.min(viewport.height, rect.y + rect.height); + const intersection = Math.max(0, right - left) * Math.max(0, bottom - top); + + return intersection / area; +} + /** * The node's field as the matcher reads it. Text and name read as the empty * string when absent, since a node without text has none. A value reads as 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/expect-viewport.test.ts b/packages/e2e/tests/unit/expect-viewport.test.ts new file mode 100644 index 0000000000..1912267fe9 --- /dev/null +++ b/packages/e2e/tests/unit/expect-viewport.test.ts @@ -0,0 +1,109 @@ +import { describe, expect, it } from 'vitest'; +import { EngineError, resolveExpression, type SemanticNode } from '../../src/engine/index.ts'; +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 viewport = { width: 1280, height: 720 }; + +function target(rect?: { x: number; y: number; width: number; height: number }): SemanticNode { + return { + ref: { id: 'target', revision: '' }, + role: 'generic', + testId: 'target', + ...(rect === undefined ? {} : { rect }), + }; +} + +function screenWith(rect?: { x: number; y: number; width: number; height: number }) { + return createScreenFixture([target(rect)]); +} + +describe('toBeInViewport', () => { + it('uses any positive intersection by default and a ratio when supplied', async () => { + const screen = screenWith({ x: -90, y: 10, width: 100, height: 50 }); + const locator = screen.getByTestId('target'); + + await expectFixture(locator).toBeInViewport(); + await expectFixture(locator).toBeInViewport({ ratio: 0 }); + await expectFixture(locator).toBeInViewport({ ratio: 0.1 }); + await expect(expectFixture(locator).toBeInViewport({ ratio: 0.11, timeout: 50 })).rejects.toMatchObject({ + code: 'ASSERTION_FAILED', + }); + }); + + it('treats offscreen and zero-size boxes as out of the viewport', async () => { + await expectFixture(screenWith({ x: 1300, y: 10, width: 20, height: 20 }).getByTestId('target')).not.toBeInViewport({ + ratio: 0, + timeout: 30, + }); + await expectFixture(screenWith({ x: 20, y: 20, width: 0, height: 20 }).getByTestId('target')).not.toBeInViewport({ + timeout: 30, + }); + }); + + it('fails clearly when the box is missing, including under .not', async () => { + const locator = screenWith().getByTestId('target'); + + await expect(expectFixture(locator).toBeInViewport({ timeout: 30 })).rejects.toMatchObject({ + code: 'ASSERTION_FAILED', + message: expect.stringContaining('observed: no bounding box'), + }); + await expect(expectFixture(locator).not.toBeInViewport({ timeout: 30 })).rejects.toMatchObject({ + code: 'ASSERTION_FAILED', + message: expect.stringContaining('observed: no bounding box'), + }); + }); + + it('rejects invalid ratios and unknown options before reading', () => { + const locator = expectFixture(screenWith({ x: 0, y: 0, width: 10, height: 10 }).getByTestId('target')); + + expect(() => locator.toBeInViewport({ ratio: -0.1 })).toThrow( + expect.objectContaining({ code: 'INVALID_ARGUMENT' }), + ); + expect(() => locator.toBeInViewport({ ratio: 1.1 })).toThrow(expect.objectContaining({ code: 'INVALID_ARGUMENT' })); + expect(() => locator.toBeInViewport({ ratio: Number.NaN })).toThrow( + expect.objectContaining({ code: 'INVALID_ARGUMENT' }), + ); + expect(() => locator.toBeInViewport({ ratio: 0.5, threshold: 0.5 } as never)).toThrow( + expect.objectContaining({ code: 'INVALID_ARGUMENT' }), + ); + }); + + it('polls until the box enters the viewport', async () => { + const state = { rect: { x: 1300, y: 10, width: 20, height: 20 } }; + const currentTarget = (): SemanticNode => target(state.rect); + const screen = screenOver({ + locate: (expression) => resolveExpression(expression, [currentTarget()]), + observe: () => ({ ...snapshot([currentTarget()]), viewport }), + timeoutMs: 300, + }).screen; + + setTimeout(() => { + state.rect = { x: 20, y: 20, width: 20, height: 20 }; + }, 25); + + await expectFixture(screen.getByTestId('target')).toBeInViewport({ timeout: 200 }); + }); + + it('retries when navigation makes the viewport observation stale', async () => { + let observations = 0; + const node = target({ x: 20, y: 20, width: 20, height: 20 }); + const screen = screenOver({ + locate: (expression) => resolveExpression(expression, [node]), + observe: () => { + observations += 1; + if (observations === 1) throw new EngineError('NODE_STALE', 'navigation changed', { retryable: true }); + return { ...snapshot([node]), viewport }; + }, + timeoutMs: 300, + }).screen; + + await expectFixture(screen.getByTestId('target')).toBeInViewport({ timeout: 200 }); + expect(observations).toBeGreaterThan(1); + }); +}); diff --git a/plugins/e2e/skills/e2e/references/writing-tests.md b/plugins/e2e/skills/e2e/references/writing-tests.md index 3415d03e36..be50db1515 100644 --- a/plugins/e2e/skills/e2e/references/writing-tests.md +++ b/plugins/e2e/skills/e2e/references/writing-tests.md @@ -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 diff --git a/skills/e2e/references/writing-tests.md b/skills/e2e/references/writing-tests.md index 3415d03e36..be50db1515 100644 --- a/skills/e2e/references/writing-tests.md +++ b/skills/e2e/references/writing-tests.md @@ -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 From 7f56640da534100667706bcfa0ab768c5aaf8d7f Mon Sep 17 00:00:00 2001 From: Anmol202005 <183815727+Anmol202005@users.noreply.github.com> Date: Wed, 21 Oct 2026 13:43:32 +0530 Subject: [PATCH 02/11] docs(expect): describe viewport geometry timeout --- docs/reference/expect.mdx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/reference/expect.mdx b/docs/reference/expect.mdx index a2d90229c1..f7cf3c40d5 100644 --- a/docs/reference/expect.mdx +++ b/docs/reference/expect.mdx @@ -113,7 +113,8 @@ any positive area is inside. Set `ratio` from `0` to `1` to require that share of the box; `0` also means any positive area. The calculation uses the reported box and viewport rectangle, ignores clipping by overflow ancestors, and does not check whether another element covers the match. It never scrolls. -A missing box fails with an unavailable-geometry message, including under +If the engine never reports a box before the assertion timeout, the assertion +fails with `ASSERTION_FAILED` and `observed: no bounding box`, including under `.not`. It trusts the engine's coordinates, so the result depends on the engine reporting scroll-aware boxes. From ff16d3292e16d156f7dc0582d8bdabeee62e9ce3 Mon Sep 17 00:00:00 2001 From: Krzysztof Moch Date: Fri, 20 Nov 2026 13:16:58 +0100 Subject: [PATCH 03/11] feat(expect): measure toBeInViewport through an engine viewportIntersection Reworks the imported matcher so each engine measures what it can honestly report, instead of the harness comparing a node box with a second observation's viewport. - Engines get an optional `viewportIntersection(ref)` member (`viewport-intersection` capability, `engine/viewportIntersection` on the protocol). The harness reads the match and measures that ref once per poll sample, inside the read window. - The web engine measures with an IntersectionObserver, as Playwright does, so scroll containers, overflow ancestors, and frames clip the box. - The mobile engine answers only whether the node is on screen: agent-device reports bounds already clipped, so `ratio` there is UNSUPPORTED_CAPABILITY. - No match reads as outside the viewport, so `.not` passes for a node a device left out of its tree. A node that goes stale before it is measured is sampled again rather than read as gone. Co-authored-by: Anmol202005 <183815727+Anmol202005@users.noreply.github.com> --- .changeset/viewport-matcher.md | 14 +- .../mobile-benchmark/tests/flows-lists.e2e.ts | 5 + apps/testbed/tests/controls.e2e.ts | 13 ++ docs/migrate/playwright.mdx | 4 +- docs/reference/engine-protocol.mdx | 1 + docs/reference/engine.mdx | 31 +++- docs/reference/expect.mdx | 34 ++-- packages/core/src/engine/contract.ts | 17 ++ packages/core/src/engine/index.ts | 10 ++ packages/core/src/engine/manifest.ts | 8 + packages/core/src/engine/protocol/protocol.ts | 1 + packages/core/src/engine/session.ts | 23 +++ packages/core/src/engine/surface.ts | 3 + packages/core/src/locator/engine.ts | 33 ++-- packages/core/src/types.ts | 6 +- .../e2e/schema/engine-manifest-v1.schema.json | 2 + .../fixtures/engine-manifest-v1.valid.json | 2 + packages/e2e/src/expect/async.ts | 94 +++++----- packages/e2e/tests/helpers/screen-over.ts | 10 +- .../e2e/tests/unit/expect-viewport.test.ts | 167 ++++++++++-------- packages/mobile/src/engine.ts | 1 + packages/mobile/src/surface.ts | 27 +++ packages/mobile/tests/unit/engine.test.ts | 22 ++- packages/web/src/engine.ts | 1 + packages/web/src/surface.ts | 62 +++++++ .../integration/viewport-intersection.test.ts | 100 +++++++++++ .../skills/e2e/references/writing-tests.md | 5 +- skills/e2e/references/writing-tests.md | 5 +- 28 files changed, 542 insertions(+), 159 deletions(-) create mode 100644 packages/web/tests/integration/viewport-intersection.test.ts diff --git a/.changeset/viewport-matcher.md b/.changeset/viewport-matcher.md index b459236dd1..f0939adab3 100644 --- a/.changeset/viewport-matcher.md +++ b/.changeset/viewport-matcher.md @@ -1,5 +1,17 @@ --- "e2e": patch +"@e2e-dev/core": patch +"@e2e-dev/web": patch +"@e2e-dev/mobile": patch --- -Add the cross-engine `toBeInViewport` locator matcher with an optional intersection ratio. +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` passes once nothing matches. The web +engine measures with an `IntersectionObserver`, as Playwright does, so +scrolling and `overflow` ancestors and frames clip the box. The mobile engine +reports only whether the node is on screen, since a device reports bounds +already clipped, so `ratio` there fails with `UNSUPPORTED_CAPABILITY`. +Engines implement the optional `viewportIntersection` method for the new +`viewport-intersection` capability. `@e2e-dev/web` and `@e2e-dev/mobile` now +need `@e2e-dev/core` 0.24.1 or later. 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..0bdd114d8f 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` [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..1e94dfe37c 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` | | `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..e648cef509 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 node `locate` +returned is inside the viewport, for +[`toBeInViewport`](/reference/expect#tobeinviewport), without scrolling or +changing app state. Clip the box by the viewport and by every ancestor that +clips its content: a scroll container, `overflow: hidden`, 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; +} +``` + +Leave out `ratio` when the platform reports only the visible part of a box, +as a device does; `toBeInViewport({ ratio })` then fails with +`UNSUPPORTED_CAPABILITY` rather than read that part as the whole. Throw +retryable `NODE_STALE` if the node no longer binds, and +`UNSUPPORTED_CAPABILITY` for a node the platform reports no bounds for. 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. diff --git a/docs/reference/expect.mdx b/docs/reference/expect.mdx index f7cf3c40d5..10b5caae24 100644 --- a/docs/reference/expect.mdx +++ b/docs/reference/expect.mdx @@ -74,7 +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 viewport intersection | +| [`toBeInViewport`](#tobeinviewport) | Waits for the match to be inside the viewport | | [`toBeAttached`](#tobeattached) | Waits for one match to exist | | [`toBeEnabled`](#tobeenabled-and-tobedisabled) | Waits for enabled state | | [`toBeDisabled`](#tobeenabled-and-tobedisabled) | Waits for disabled state | @@ -108,15 +108,10 @@ await expect(screen.getByRole('dialog')).toBeVisible({ visible: false }); // as #### `toBeInViewport` -Waits until the match's box intersects the viewport. The default passes when -any positive area is inside. Set `ratio` from `0` to `1` to require that share -of the box; `0` also means any positive area. The calculation uses the -reported box and viewport rectangle, ignores clipping by overflow ancestors, -and does not check whether another element covers the match. It never scrolls. -If the engine never reports a box before the assertion timeout, the assertion -fails with `ASSERTION_FAILED` and `observed: no bounding box`, including under -`.not`. It trusts the engine's coordinates, so the result depends on the -engine reporting scroll-aware boxes. +Waits for part of the one match to be inside the viewport. It never scrolls, +and says nothing about another element covering the match. No match is +outside the viewport, so `.not` passes once nothing matches. An empty box, or +none, is outside. ```ts await expect(screen.getByRole('toolbar', 'Selection')).toBeInViewport(); @@ -124,6 +119,19 @@ await expect(screen.getByRole('toolbar', 'Selection')).toBeInViewport({ ratio: 0 await expect(screen.getByRole('alert')).not.toBeInViewport(); ``` +`ratio`, from `0` to `1`, is the share of the box that must be inside; `0` +means any part, as the default does. What counts as inside depends on the +engine: + +| Engine | Measures | `ratio` | +| --- | --- | --- | +| `@e2e-dev/web` | An `IntersectionObserver`, as Playwright does: the viewport, every scrolling or `overflow` ancestor, and frames clip the box | Supported | +| `@e2e-dev/mobile` | The bounds the device reports, already clipped to the screen and to scroll containers; a node with nothing on screen leaves the tree | `UNSUPPORTED_CAPABILITY` once the node is on screen, since the device reports only its visible part | + +A node the engine has no bounds for fails at once with +`UNSUPPORTED_CAPABILITY`, `.not` included, and so does a target whose engine +does not implement [`viewportIntersection`](/reference/engine#viewport-intersection). + #### `toBeAttached` Waits for one match to exist, hidden or shown, where `toBeVisible` needs a @@ -990,7 +998,11 @@ export interface AsyncExpectation { toBeVisible(options?: { visible?: boolean; timeout?: number }): Promise; /** Waits for hidden or absent state. */ toBeHidden(options?: { timeout?: number }): Promise; - /** Waits until a share of the match's box intersects the viewport. */ + /** + * 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; diff --git a/packages/core/src/engine/contract.ts b/packages/core/src/engine/contract.ts index af3bbb66e2..b2c357f7cb 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's share of the whole box, from 0 to 1, as an + * `IntersectionObserver` reports it. 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..900c9b75fb 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); @@ -459,6 +461,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 +505,20 @@ 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 or a missing verdict. + */ +function checkIntersection(value: ViewportIntersection, engineName: string): ViewportIntersection { + const { intersects, ratio } = (value ?? {}) as Partial>; + const validRatio = ratio === undefined || (typeof ratio === 'number' && ratio >= 0 && ratio <= 1); + 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`, + { 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..fdb04779db 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'; @@ -205,6 +206,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 9cc0a74825..c84ca7be2a 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'; @@ -447,23 +448,27 @@ if (sampled && reads.cutOff(cause)) throw await notFound(cause); return this.readOne(expression, reads, missingFrame); } - /** Reads a matched node's box and the current viewport for geometry assertions. */ - async readWithViewport( + /** + * 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 node that went stale + * before it was measured has a null `intersection`, so the poll samples + * again instead of reading the node as gone. + */ + async readViewport( expression: LocatorExpression, - deadline: Deadline, - ): Promise<{ - node: SemanticNode | null; - count: number; - viewport?: { width: number; height: number }; - }> { - const { node, count } = await this.tryRead(expression, deadline); - if (node === null) return { node, count }; - + reads: ReadWindow, + ): Promise<{ node: SemanticNode | null; count: number; intersection: ViewportIntersection | null }> { + const { node, count } = await this.readOne(expression, reads, 'empty'); + if (node === null) return { node, count, intersection: null }; try { - const observation = await this.session.observe(this.operationWithin(deadline)); - return { node, count, viewport: observation.viewport }; + const intersection = await reads.read((timeoutMs) => + this.session.viewportIntersection(node.ref, this.readOperation(timeoutMs)), + ); + return { node, count, intersection }; } catch (cause) { - if (asEngineError(cause)?.code === 'NODE_STALE') return { node: null, count: 0 }; + if (asEngineError(cause)?.code === 'NODE_STALE') return { node, count, intersection: null }; throw translateLocatorError(cause, expression); } } diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index 90b801b9e3..88e8489d4d 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -1101,7 +1101,11 @@ export interface AsyncExpectation { toBeVisible(options?: { visible?: boolean; timeout?: number }): Promise; /** Waits for hidden or absent state. */ toBeHidden(options?: { timeout?: number }): Promise; - /** Waits until a share of the match's box intersects the viewport. */ + /** + * 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; 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.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 58005ffd95..6b4975cda9 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,18 +30,25 @@ 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[]; - readonly viewport?: { width: number; height: number }; + /** + * How much of `node` is inside the viewport, for a `measuresViewport` + * matcher; null when the node went stale before it was measured. + */ + readonly intersection?: ViewportIntersection | null; } interface MatcherSpec { readonly name: string; - /** Reads the matched node box and the current viewport for a geometry check. */ - readonly needsViewport?: boolean; + /** 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. @@ -58,7 +65,7 @@ interface MatcherSpec { * rejects keeps the poll waiting, negated or not: `not.toHaveValue` on a * heading is not a pass. */ - readonly evaluableNode?: (node: SemanticNode) => boolean; + readonly evaluableNode?: (node: SemanticNode, sample: Sample) => boolean; /** * The matcher reads what an engine withholds on a secure field, its value, * text, or attributes; a name is never withheld. A secure node in the sample @@ -234,16 +241,14 @@ class AsyncExpectationImpl implements AsyncExpectation { private conditionEvaluable(spec: MatcherSpec, sample: Sample): boolean { if (spec.wholeSet !== undefined) return true; if (sample.node === null) return spec.evaluableWithoutNode === true; - return spec.evaluableNode?.(sample.node) ?? true; + return spec.evaluableNode?.(sample.node, sample) ?? true; } private async sample(spec: MatcherSpec, reads: ReadWindow): Promise { const { engine } = this.internals.context; - if (spec.needsViewport === true) { - return { - ...(await engine.readWithViewport(this.internals.expression, deadline)), - nodes: [], - }; + if (spec.measuresViewport === true) { + const { node, count, intersection } = await engine.readViewport(this.internals.expression, reads); + return { count, node, nodes: [], intersection }; } if (spec.wholeSet === 'read') { const nodes = await engine.readAllNow(this.internals.expression, reads); @@ -377,34 +382,38 @@ class AsyncExpectationImpl implements AsyncExpectation { const api = this.api('toBeInViewport'); rejectUnknownOptions(api, options, ['ratio', 'timeout']); const ratio: unknown = options?.ratio; - if (ratio !== undefined && (typeof ratio !== 'number' || !Number.isFinite(ratio) || ratio < 0 || ratio > 1)) { - throw new TestError('INVALID_ARGUMENT', `${api} option ratio must be between 0 and 1`); + 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`); } - - const expectedRatio = ratio as number | undefined; + // 0 asks for any area inside, as the default does. + const minimum = ratio === 0 ? undefined : ratio; return this.poll( { name: 'toBeInViewport', - needsViewport: true, - evaluableNode: (node) => node.rect !== undefined, - predicate: (sample) => { - const rect = sample.node?.rect; - if (rect === undefined || sample.viewport === undefined) return false; - - const intersectionRatio = viewportIntersectionRatio(rect, sample.viewport); - return expectedRatio === undefined || expectedRatio === 0 - ? intersectionRatio > 0 - : intersectionRatio >= expectedRatio; + measuresViewport: true, + // No match is outside the viewport: a device leaves offscreen nodes out of its tree. + evaluableWithoutNode: true, + evaluableNode: (_node, sample) => sample.intersection != null, + predicate: ({ node, intersection }) => { + if (node === null || intersection == null || !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: - expectedRatio === undefined - ? 'a positive area inside the viewport' - : `at least ${expectedRatio} of its area inside the viewport`, - observed: (sample) => { - if (sample.node === null) return 'no node'; - if (sample.node.rect === undefined) return 'no bounding box'; - if (sample.viewport === undefined) return 'no viewport geometry'; - return `bounding box intersection ratio ${viewportIntersectionRatio(sample.node.rect, sample.viewport)}`; + minimum === undefined ? 'inside the viewport' : `at least ${minimum} of its box inside the viewport`, + observed: ({ node, intersection }) => { + if (node === null) return 'no node'; + if (intersection == null) return 'a node that went stale before it was measured'; + if (!intersection.intersects) return 'outside the viewport'; + return intersection.ratio === undefined + ? 'inside the viewport' + : `${Number(intersection.ratio.toFixed(3))} of its box inside the viewport`; }, }, options?.timeout, @@ -601,23 +610,6 @@ function matchesSubsequence( return next === patterns.length; } -/** The share of a node's box that intersects the viewport. */ -function viewportIntersectionRatio( - rect: { x: number; y: number; width: number; height: number }, - viewport: { width: number; height: number }, -): number { - const area = rect.width * rect.height; - if (area <= 0) return 0; - - const left = Math.max(0, rect.x); - const top = Math.max(0, rect.y); - const right = Math.min(viewport.width, rect.x + rect.width); - const bottom = Math.min(viewport.height, rect.y + rect.height); - const intersection = Math.max(0, right - left) * Math.max(0, bottom - top); - - return intersection / area; -} - /** * The node's field as the matcher reads it. Text and name read as the empty * string when absent, since a node without text has none. A value reads as 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/unit/expect-viewport.test.ts b/packages/e2e/tests/unit/expect-viewport.test.ts index 1912267fe9..371d1ed7f7 100644 --- a/packages/e2e/tests/unit/expect-viewport.test.ts +++ b/packages/e2e/tests/unit/expect-viewport.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { EngineError, resolveExpression, type SemanticNode } from '../../src/engine/index.ts'; +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'; @@ -8,102 +8,123 @@ import { useFakeTime } from '../helpers/fake-time.ts'; useFakeTime(); -const viewport = { width: 1280, height: 720 }; - -function target(rect?: { x: number; y: number; width: number; height: number }): SemanticNode { - return { - ref: { id: 'target', revision: '' }, - role: 'generic', - testId: 'target', - ...(rect === undefined ? {} : { rect }), - }; +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; } -function screenWith(rect?: { x: number; y: number; width: number; height: number }) { - return createScreenFixture([target(rect)]); -} +const failure = (promise: Promise) => promise.then(() => expect.unreachable('expected a failure'), (error: unknown) => error); describe('toBeInViewport', () => { - it('uses any positive intersection by default and a ratio when supplied', async () => { - const screen = screenWith({ x: -90, y: 10, width: 100, height: 50 }); - const locator = screen.getByTestId('target'); + 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 }); - await expect(expectFixture(locator).toBeInViewport({ ratio: 0.11, timeout: 50 })).rejects.toMatchObject({ + 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('treats offscreen and zero-size boxes as out of the viewport', async () => { - await expectFixture(screenWith({ x: 1300, y: 10, width: 20, height: 20 }).getByTestId('target')).not.toBeInViewport({ - ratio: 0, - timeout: 30, - }); - await expectFixture(screenWith({ x: 20, y: 20, width: 0, height: 20 }).getByTestId('target')).not.toBeInViewport({ - timeout: 30, + 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('fails clearly when the box is missing, including under .not', async () => { - const locator = screenWith().getByTestId('target'); + 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 expect(expectFixture(locator).toBeInViewport({ timeout: 30 })).rejects.toMatchObject({ - code: 'ASSERTION_FAILED', - message: expect.stringContaining('observed: no bounding box'), - }); - await expect(expectFixture(locator).not.toBeInViewport({ timeout: 30 })).rejects.toMatchObject({ - code: 'ASSERTION_FAILED', - message: expect.stringContaining('observed: no bounding box'), + 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(); + 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' }); + + const noCapability = createScreenFixture([target]).getByTestId('target'); + expect(await failure(expectFixture(noCapability).not.toBeInViewport())).toMatchObject({ + code: 'UNSUPPORTED_CAPABILITY', + message: expect.stringContaining('viewport geometry'), }); }); - it('rejects invalid ratios and unknown options before reading', () => { - const locator = expectFixture(screenWith({ x: 0, y: 0, width: 10, height: 10 }).getByTestId('target')); - - expect(() => locator.toBeInViewport({ ratio: -0.1 })).toThrow( - expect.objectContaining({ code: 'INVALID_ARGUMENT' }), - ); - expect(() => locator.toBeInViewport({ ratio: 1.1 })).toThrow(expect.objectContaining({ code: 'INVALID_ARGUMENT' })); - expect(() => locator.toBeInViewport({ ratio: Number.NaN })).toThrow( - expect.objectContaining({ code: 'INVALID_ARGUMENT' }), - ); - expect(() => locator.toBeInViewport({ ratio: 0.5, threshold: 0.5 } as never)).toThrow( - expect.objectContaining({ code: 'INVALID_ARGUMENT' }), - ); + 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('polls until the box enters the viewport', async () => { - const state = { rect: { x: 1300, y: 10, width: 20, height: 20 } }; - const currentTarget = (): SemanticNode => target(state.rect); - const screen = screenOver({ - locate: (expression) => resolveExpression(expression, [currentTarget()]), - observe: () => ({ ...snapshot([currentTarget()]), viewport }), - timeoutMs: 300, - }).screen; + 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'); - setTimeout(() => { - state.rect = { x: 20, y: 20, width: 20, height: 20 }; - }, 25); + 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'); + }); - await expectFixture(screen.getByTestId('target')).toBeInViewport({ timeout: 200 }); + it('fails on an engine answer outside the contract', async () => { + const locator = screenMeasuring(() => ({ intersects: true, ratio: 2 })).getByTestId('target'); + expect(await failure(expectFixture(locator).toBeInViewport())).toMatchObject({ code: 'ENGINE_FAILURE' }); }); - it('retries when navigation makes the viewport observation stale', async () => { - let observations = 0; - const node = target({ x: 20, y: 20, width: 20, height: 20 }); - const screen = screenOver({ - locate: (expression) => resolveExpression(expression, [node]), - observe: () => { - observations += 1; - if (observations === 1) throw new EngineError('NODE_STALE', 'navigation changed', { retryable: true }); - return { ...snapshot([node]), viewport }; - }, - timeoutMs: 300, - }).screen; - - await expectFixture(screen.getByTestId('target')).toBeInViewport({ timeout: 200 }); - expect(observations).toBeGreaterThan(1); + 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/mobile/src/engine.ts b/packages/mobile/src/engine.ts index 56efd5e198..54e10ea545 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) => surface.viewportIntersection(ref), 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..46b25b3959 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 screen that capture measured `node.rect` against, when it reported one. */ + readonly viewport: ViewportSize | undefined; /** Whether `fill` and `clear` may type into the node, judged with the children `node` leaves out. */ readonly takesText: boolean; } @@ -1316,6 +1319,29 @@ 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`. A rect whose window could not + * be placed on the screen is not measured against it. + */ + async viewportIntersection(ref: NodeRef): Promise { + const entry = this.resolveRef(ref); + const rect = entry.node.rect; + const screen = entry.viewport ?? this.knownViewport; + if (rect === undefined || (screen === undefined && !entry.originUnknown)) { + 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 bounds = entry.originUnknown || screen === undefined ? rect : { x: 0, y: 0, ...screen }; + const width = Math.min(rect.x + rect.width, bounds.x + bounds.width) - Math.max(rect.x, bounds.x); + const height = Math.min(rect.y + rect.height, bounds.y + bounds.height) - Math.max(rect.y, bounds.y); + 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 +1390,7 @@ export class AgentDeviceSurface { controlRef: control.ref, keyboardVisible: snapshot.keyboardVisible, originUnknown: snapshot.originUnknown, + viewport: snapshot.viewport, takesText: mayTakeText(entry.node), refsGeneration: snapshot.refsGeneration, }; diff --git a/packages/mobile/tests/unit/engine.test.ts b/packages/mobile/tests/unit/engine.test.ts index e0b946130c..7a6b8da7a9 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,26 @@ 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' }], + })); + 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 }); + 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('finds an Android view by its id without its package', async () => { const h = harness({ platform: 'android' }); await openAttempt(h); 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..7a12b4e9bf 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,43 @@ export class PlaywrightSurface { }, navigationStaleOr); } + /** + * Measures how much of a located or observed element is inside the + * viewport with an `IntersectionObserver`, as Playwright's + * `toBeInViewport` does, so scrolling and overflow ancestors and frames + * clip it. An element with no box, or an empty one, is outside. + */ + viewportIntersection(ref: NodeRef, operation: OperationContext): Promise { + return this.guard(operation, 'measure viewport intersection', async (currentOperation) => { + 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]!; + } + currentOperation.signal.throwIfAborted(); + try { + 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 +1549,27 @@ 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. + */ +function measureViewportIntersection(element: Element): Promise { + if (!element.isConnected) return Promise.resolve('detached'); + const box = element.getBoundingClientRect(); + if (element.getClientRects().length === 0 || box.width <= 0 || box.height <= 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(); + const ratio = entries.at(-1)?.intersectionRatio ?? 0; + resolve({ intersects: ratio > 0, ratio }); + }); + observer.observe(element); + view.requestAnimationFrame(() => {}); + }); +} 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..65c855ba7a --- /dev/null +++ b/packages/web/tests/integration/viewport-intersection.test.ts @@ -0,0 +1,100 @@ +/** + * `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('#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' }); + }); +}); diff --git a/plugins/e2e/skills/e2e/references/writing-tests.md b/plugins/e2e/skills/e2e/references/writing-tests.md index be50db1515..2180502fbf 100644 --- a/plugins/e2e/skills/e2e/references/writing-tests.md +++ b/plugins/e2e/skills/e2e/references/writing-tests.md @@ -434,7 +434,10 @@ 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 takes no `ratio` +(`UNSUPPORTED_CAPABILITY`). 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 be50db1515..2180502fbf 100644 --- a/skills/e2e/references/writing-tests.md +++ b/skills/e2e/references/writing-tests.md @@ -434,7 +434,10 @@ 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 takes no `ratio` +(`UNSUPPORTED_CAPABILITY`). 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 }` From f7a9b7271b5a4e3498d35b5fd474aaade8f4d60c Mon Sep 17 00:00:00 2001 From: Krzysztof Moch Date: Fri, 20 Nov 2026 13:33:51 +0100 Subject: [PATCH 04/11] fix(expect): refuse toBeInViewport before the resolve on an engine that cannot measure Also drops the schema rule that required engine/locate beside engine/viewportIntersection (the client may build locate itself), adds the capability to the web lifecycle test and to the docs' capability lists. --- docs/reference/engine.mdx | 1 + docs/reference/test.mdx | 3 ++- packages/core/src/engine/session.ts | 1 + packages/core/src/engine/surface.ts | 2 ++ packages/core/src/locator/engine.ts | 9 ++++++++- packages/e2e/tests/unit/expect-viewport.test.ts | 13 ++++++++----- packages/web/tests/integration/lifecycle.test.ts | 1 + 7 files changed, 23 insertions(+), 7 deletions(-) diff --git a/docs/reference/engine.mdx b/docs/reference/engine.mdx index e648cef509..5652690aa5 100644 --- a/docs/reference/engine.mdx +++ b/docs/reference/engine.mdx @@ -566,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/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/session.ts b/packages/core/src/engine/session.ts index 900c9b75fb..8f2a24337e 100644 --- a/packages/core/src/engine/session.ts +++ b/packages/core/src/engine/session.ts @@ -341,6 +341,7 @@ export function createEngineSession(options: EngineSessionOptions): TargetSessio actions, pointerActions, tapModifiers, + measuresViewport: engine?.viewportIntersection !== undefined, app, artifacts, appLog: createAppLogRoute(), diff --git a/packages/core/src/engine/surface.ts b/packages/core/src/engine/surface.ts index fdb04779db..9457eacf44 100644 --- a/packages/core/src/engine/surface.ts +++ b/packages/core/src/engine/surface.ts @@ -198,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. */ diff --git a/packages/core/src/locator/engine.ts b/packages/core/src/locator/engine.ts index c84ca7be2a..34192cbe44 100644 --- a/packages/core/src/locator/engine.ts +++ b/packages/core/src/locator/engine.ts @@ -454,12 +454,19 @@ if (sampled && reads.cutOff(cause)) throw await notFound(cause); * measure of the same ref, all inside `reads`, never a second observation. * Zero matches or a missing frame read as no node. A node that went stale * before it was measured has a null `intersection`, so the poll samples - * again instead of reading the node as gone. + * 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; intersection: ViewportIntersection | null }> { + 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 } = await this.readOne(expression, reads, 'empty'); if (node === null) return { node, count, intersection: null }; try { diff --git a/packages/e2e/tests/unit/expect-viewport.test.ts b/packages/e2e/tests/unit/expect-viewport.test.ts index 371d1ed7f7..c278348acd 100644 --- a/packages/e2e/tests/unit/expect-viewport.test.ts +++ b/packages/e2e/tests/unit/expect-viewport.test.ts @@ -78,11 +78,14 @@ describe('toBeInViewport', () => { }).getByTestId('target'); expect(await failure(expectFixture(unmeasurable).not.toBeInViewport())).toMatchObject({ code: 'UNSUPPORTED_CAPABILITY' }); - const noCapability = createScreenFixture([target]).getByTestId('target'); - expect(await failure(expectFixture(noCapability).not.toBeInViewport())).toMatchObject({ - code: 'UNSUPPORTED_CAPABILITY', - message: expect.stringContaining('viewport geometry'), - }); + // 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 () => { 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'); }); From fad87d784bcbd2648cf33416d6d25281da79ffdc Mon Sep 17 00:00:00 2001 From: Krzysztof Moch Date: Fri, 20 Nov 2026 13:43:09 +0100 Subject: [PATCH 05/11] fix(viewport): address review round 1 - mobile: refuse a node whose window has no known place on the screen, and measure against the confirmed screen, not a capture's own size - web: measure inside readingTab, and dispose a handle when the operation aborts - test defineEngine's locate requirement and the resolveLocators path - docs: strictness list, zero-size difference from Playwright, page-world note --- .changeset/viewport-matcher.md | 4 +-- docs/migrate/playwright.mdx | 2 +- docs/reference/expect.mdx | 9 ++++--- packages/core/src/engine/contract.ts | 6 ++--- .../e2e/tests/unit/engine-protocol.test.ts | 4 +++ packages/e2e/tests/unit/engine.test.ts | 7 ++++++ packages/mobile/src/surface.ts | 25 +++++++++++-------- packages/mobile/tests/unit/engine.test.ts | 11 ++++++++ packages/web/src/surface.ts | 14 ++++++----- 9 files changed, 55 insertions(+), 27 deletions(-) diff --git a/.changeset/viewport-matcher.md b/.changeset/viewport-matcher.md index f0939adab3..773260a778 100644 --- a/.changeset/viewport-matcher.md +++ b/.changeset/viewport-matcher.md @@ -8,8 +8,8 @@ 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` passes once nothing matches. The web -engine measures with an `IntersectionObserver`, as Playwright does, so -scrolling and `overflow` ancestors and frames clip the box. The mobile engine +engine measures with the page's `IntersectionObserver`, the check Playwright +makes, so scrolling and `overflow` ancestors and frames clip the box. The mobile engine reports only whether the node is on screen, since a device reports bounds already clipped, so `ratio` there fails with `UNSUPPORTED_CAPABILITY`. Engines implement the optional `viewportIntersection` method for the new diff --git a/docs/migrate/playwright.mdx b/docs/migrate/playwright.mdx index 0bdd114d8f..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()`, `toBeInViewport()`, `toHaveText()`, `toContainText()`, `toHaveValue()`, `toHaveAttribute()`, `toHaveCount()`, `toHaveAccessibleName()`, `toHaveRole()`, `toBeEditable()` | the same, with `{ visible }`, `{ enabled }`, `{ editable }`, `{ checked }`, `{ attached }`, `{ ratio }`, and `{ ignoreCase }`; `toBeInViewport` [differs on a device](/reference/expect#tobeinviewport) | +| `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) | diff --git a/docs/reference/expect.mdx b/docs/reference/expect.mdx index 10b5caae24..9d11fb9fe5 100644 --- a/docs/reference/expect.mdx +++ b/docs/reference/expect.mdx @@ -125,7 +125,7 @@ engine: | Engine | Measures | `ratio` | | --- | --- | --- | -| `@e2e-dev/web` | An `IntersectionObserver`, as Playwright does: the viewport, every scrolling or `overflow` ancestor, and frames clip the box | Supported | +| `@e2e-dev/web` | The page's `IntersectionObserver`, the check Playwright makes: the viewport, every scrolling or `overflow` ancestor, and frames clip the box. An app that replaces `IntersectionObserver` changes the answer | Supported | | `@e2e-dev/mobile` | The bounds the device reports, already clipped to the screen and to scroll containers; a node with nothing on screen leaves the tree | `UNSUPPORTED_CAPABILITY` once the node is on screen, since the device reports only its visible part | A node the engine has no bounds for fails at once with @@ -889,11 +889,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 diff --git a/packages/core/src/engine/contract.ts b/packages/core/src/engine/contract.ts index b2c357f7cb..cc42923b86 100644 --- a/packages/core/src/engine/contract.ts +++ b/packages/core/src/engine/contract.ts @@ -259,9 +259,9 @@ 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, as an - * `IntersectionObserver` reports it. Absent where the platform reports - * only the visible part of a box, so the whole is unknown. + * 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; } diff --git a/packages/e2e/tests/unit/engine-protocol.test.ts b/packages/e2e/tests/unit/engine-protocol.test.ts index 45cac105c6..c74929775b 100644 --- a/packages/e2e/tests/unit/engine-protocol.test.ts +++ b/packages/e2e/tests/unit/engine-protocol.test.ts @@ -686,6 +686,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/mobile/src/surface.ts b/packages/mobile/src/surface.ts index 46b25b3959..f0f6b4d428 100644 --- a/packages/mobile/src/surface.ts +++ b/packages/mobile/src/surface.ts @@ -229,8 +229,6 @@ interface NodeBinding { readonly keyboardVisible: boolean; /** Whether the capture `node.rect` came from could not place its window on the screen. */ readonly originUnknown: boolean; - /** The screen that capture measured `node.rect` against, when it reported one. */ - readonly viewport: ViewportSize | undefined; /** Whether `fill` and `clear` may type into the node, judged with the children `node` leaves out. */ readonly takesText: boolean; } @@ -1324,21 +1322,27 @@ export class AgentDeviceSurface { * 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`. A rect whose window could not - * be placed on the screen is not measured against it. + * unknown, and the answer carries no `ratio`. The screen is the one the + * session confirmed, not a capture's own size, which an app drawn smaller + * than the screen shrinks. A rect whose window could not be placed on the + * screen is refused rather than guessed at. */ async viewportIntersection(ref: NodeRef): Promise { const entry = this.resolveRef(ref); const rect = entry.node.rect; - const screen = entry.viewport ?? this.knownViewport; - if (rect === undefined || (screen === undefined && !entry.originUnknown)) { - throw new EngineError('UNSUPPORTED_CAPABILITY', `node ${ref.id} has no bounds on the screen, so whether it is in the viewport is unknown`, { + const screen = this.knownViewport; + if (entry.originUnknown) { + throw new EngineError('UNSUPPORTED_CAPABILITY', `whether node ${ref.id} is in the viewport is unknown: the ${ORIGIN_UNKNOWN_BOUNDS}`, { retryable: false, }); } - const bounds = entry.originUnknown || screen === undefined ? rect : { x: 0, y: 0, ...screen }; - const width = Math.min(rect.x + rect.width, bounds.x + bounds.width) - Math.max(rect.x, bounds.x); - const height = Math.min(rect.y + rect.height, bounds.y + bounds.height) - Math.max(rect.y, bounds.y); + if (rect === undefined || screen === undefined) { + throw new EngineError('UNSUPPORTED_CAPABILITY', `node ${ref.id} has no bounds on a screen of known size, so whether it is in the viewport is unknown`, { + retryable: false, + }); + } + 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 }; } @@ -1390,7 +1394,6 @@ export class AgentDeviceSurface { controlRef: control.ref, keyboardVisible: snapshot.keyboardVisible, originUnknown: snapshot.originUnknown, - viewport: snapshot.viewport, takesText: mayTakeText(entry.node), refsGeneration: snapshot.refsGeneration, }; diff --git a/packages/mobile/tests/unit/engine.test.ts b/packages/mobile/tests/unit/engine.test.ts index 7a6b8da7a9..0c672f3dd3 100644 --- a/packages/mobile/tests/unit/engine.test.ts +++ b/packages/mobile/tests/unit/engine.test.ts @@ -1811,6 +1811,17 @@ describe('location', () => { await expect(measure('Unplaced')).rejects.toMatchObject({ code: 'UNSUPPORTED_CAPABILITY' }); }); + 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); diff --git a/packages/web/src/surface.ts b/packages/web/src/surface.ts index 7a12b4e9bf..417195ec40 100644 --- a/packages/web/src/surface.ts +++ b/packages/web/src/surface.ts @@ -966,12 +966,14 @@ export class PlaywrightSurface { /** * Measures how much of a located or observed element is inside the - * viewport with an `IntersectionObserver`, as Playwright's - * `toBeInViewport` does, so scrolling and overflow ancestors and frames - * clip it. An element with no box, or an empty one, is outside. + * 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', async (currentOperation) => { + 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') { @@ -985,8 +987,8 @@ export class PlaywrightSurface { } element = handles[0]!; } - currentOperation.signal.throwIfAborted(); 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') { @@ -998,7 +1000,7 @@ export class PlaywrightSurface { } finally { if (target.kind === 'locator') void element.dispose().catch(() => undefined); } - }, navigationStaleOr); + }), navigationStaleOr); } // --- location tier --- From 9a40160d2c9cb89f832b4d0d1048f4ef27a5a99b Mon Sep 17 00:00:00 2001 From: Krzysztof Moch Date: Fri, 20 Nov 2026 13:56:43 +0100 Subject: [PATCH 06/11] fix(viewport): address review round 2 - web: clamp the measured ratio to 0..1 in the page - skill: list toBeInViewport among the matchers that accept zero matches --- packages/web/src/surface.ts | 3 ++- plugins/e2e/skills/e2e/references/writing-tests.md | 2 +- skills/e2e/references/writing-tests.md | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/web/src/surface.ts b/packages/web/src/surface.ts index 417195ec40..8574f4ed13 100644 --- a/packages/web/src/surface.ts +++ b/packages/web/src/surface.ts @@ -1568,7 +1568,8 @@ function measureViewportIntersection(element: Element): Promise { const observer = new view.IntersectionObserver((entries) => { observer.disconnect(); - const ratio = entries.at(-1)?.intersectionRatio ?? 0; + // Clamped: a browser can round a fully visible box a hair past 1. + const ratio = Math.min(1, Math.max(0, entries.at(-1)?.intersectionRatio ?? 0)); resolve({ intersects: ratio > 0, ratio }); }); observer.observe(element); diff --git a/plugins/e2e/skills/e2e/references/writing-tests.md b/plugins/e2e/skills/e2e/references/writing-tests.md index 2180502fbf..fdbd699320 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 diff --git a/skills/e2e/references/writing-tests.md b/skills/e2e/references/writing-tests.md index 2180502fbf..fdbd699320 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 From ab75f2c9691e595027bab2c1597e7dc2e99767f6 Mon Sep 17 00:00:00 2001 From: Krzysztof Moch Date: Fri, 20 Nov 2026 14:01:34 +0100 Subject: [PATCH 07/11] docs(engine-protocol): say ratio is left out, not null, when unmeasured --- docs/reference/engine-protocol.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reference/engine-protocol.mdx b/docs/reference/engine-protocol.mdx index 1e94dfe37c..aa7e16742a 100644 --- a/docs/reference/engine-protocol.mdx +++ b/docs/reference/engine-protocol.mdx @@ -229,7 +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` | +| `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` | From 85cf0c7fbfc753425d434f30defda3102131f192 Mon Sep 17 00:00:00 2001 From: Krzysztof Moch Date: Fri, 20 Nov 2026 16:46:13 +0100 Subject: [PATCH 08/11] docs(expect): tighten the toBeInViewport docs Reviewed with Gemini 4 Neon against the code: ratio 0 works on mobile and only ratio > 0 is refused, a missing box on the web reads as outside while missing bounds or screen position is UNSUPPORTED_CAPABILITY, and an out-of-range ratio is INVALID_ARGUMENT. --- .changeset/viewport-matcher.md | 10 +++---- docs/reference/engine.mdx | 20 +++++++------- docs/reference/expect.mdx | 26 ++++++++++--------- .../skills/e2e/references/writing-tests.md | 4 +-- skills/e2e/references/writing-tests.md | 4 +-- 5 files changed, 33 insertions(+), 31 deletions(-) diff --git a/.changeset/viewport-matcher.md b/.changeset/viewport-matcher.md index 773260a778..ec5aa2c985 100644 --- a/.changeset/viewport-matcher.md +++ b/.changeset/viewport-matcher.md @@ -7,11 +7,11 @@ 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` passes once nothing matches. The web -engine measures with the page's `IntersectionObserver`, the check Playwright -makes, so scrolling and `overflow` ancestors and frames clip the box. The mobile engine -reports only whether the node is on screen, since a device reports bounds -already clipped, so `ratio` there fails with `UNSUPPORTED_CAPABILITY`. +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`. Engines implement the optional `viewportIntersection` method for the new `viewport-intersection` capability. `@e2e-dev/web` and `@e2e-dev/mobile` now need `@e2e-dev/core` 0.24.1 or later. diff --git a/docs/reference/engine.mdx b/docs/reference/engine.mdx index 5652690aa5..91e54431bc 100644 --- a/docs/reference/engine.mdx +++ b/docs/reference/engine.mdx @@ -447,11 +447,10 @@ See [Project tools](/tools#read-a-nodes-computed-style) for `ToolContext.read`. #### Viewport intersection -`viewportIntersection(ref, context)` measures how much of a node `locate` -returned is inside the viewport, for -[`toBeInViewport`](/reference/expect#tobeinviewport), without scrolling or -changing app state. Clip the box by the viewport and by every ancestor that -clips its content: a scroll container, `overflow: hidden`, a frame. +`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 { @@ -462,12 +461,13 @@ export interface ViewportIntersection { } ``` -Leave out `ratio` when the platform reports only the visible part of a box, -as a device does; `toBeInViewport({ ratio })` then fails with -`UNSUPPORTED_CAPABILITY` rather than read that part as the whole. Throw +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` for a node the platform reports no bounds for. The -harness fails the step with `ENGINE_FAILURE` on an answer outside this shape. +`UNSUPPORTED_CAPABILITY` if the platform cannot report the node's bounds or +screen position. The harness fails the step with `ENGINE_FAILURE` on an answer +outside this shape. #### Agent verbs diff --git a/docs/reference/expect.mdx b/docs/reference/expect.mdx index 9d11fb9fe5..2bea61ab52 100644 --- a/docs/reference/expect.mdx +++ b/docs/reference/expect.mdx @@ -74,7 +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 inside the viewport | +| [`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 | @@ -109,9 +109,9 @@ await expect(screen.getByRole('dialog')).toBeVisible({ visible: false }); // as #### `toBeInViewport` Waits for part of the one match to be inside the viewport. It never scrolls, -and says nothing about another element covering the match. No match is -outside the viewport, so `.not` passes once nothing matches. An empty box, or -none, is outside. +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(); @@ -119,18 +119,20 @@ await expect(screen.getByRole('toolbar', 'Selection')).toBeInViewport({ ratio: 0 await expect(screen.getByRole('alert')).not.toBeInViewport(); ``` -`ratio`, from `0` to `1`, is the share of the box that must be inside; `0` -means any part, as the default does. What counts as inside depends on the -engine: +`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` | The page's `IntersectionObserver`, the check Playwright makes: the viewport, every scrolling or `overflow` ancestor, and frames clip the box. An app that replaces `IntersectionObserver` changes the answer | Supported | -| `@e2e-dev/mobile` | The bounds the device reports, already clipped to the screen and to scroll containers; a node with nothing on screen leaves the tree | `UNSUPPORTED_CAPABILITY` once the node is on screen, since the device reports only its visible part | +| `@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 | -A node the engine has no bounds for fails at once with -`UNSUPPORTED_CAPABILITY`, `.not` included, and so does a target whose engine -does not implement [`viewportIntersection`](/reference/engine#viewport-intersection). +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` diff --git a/plugins/e2e/skills/e2e/references/writing-tests.md b/plugins/e2e/skills/e2e/references/writing-tests.md index fdbd699320..4ce4afddd9 100644 --- a/plugins/e2e/skills/e2e/references/writing-tests.md +++ b/plugins/e2e/skills/e2e/references/writing-tests.md @@ -436,8 +436,8 @@ 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; `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 takes no `ratio` -(`UNSUPPORTED_CAPABILITY`). A failed matcher is `ASSERTION_FAILED`, exit code 1. +match as outside, and on a device fails with `UNSUPPORTED_CAPABILITY` for +`ratio > 0`. 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 fdbd699320..4ce4afddd9 100644 --- a/skills/e2e/references/writing-tests.md +++ b/skills/e2e/references/writing-tests.md @@ -436,8 +436,8 @@ 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; `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 takes no `ratio` -(`UNSUPPORTED_CAPABILITY`). A failed matcher is `ASSERTION_FAILED`, exit code 1. +match as outside, and on a device fails with `UNSUPPORTED_CAPABILITY` for +`ratio > 0`. 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 }` From c9cd8777ef14b74f3f977d399c894d3d75bf50b6 Mon Sep 17 00:00:00 2001 From: Krzysztof Moch Date: Mon, 23 Nov 2026 08:17:03 +0100 Subject: [PATCH 09/11] fix(viewport): address kdy1's review - web: an element replaced before the observer fires is NODE_STALE, not outside, and the zero-size check reads the observer's own entry, so the box and the ratio come from one frame - core: a ref superseded between the resolve and the read is a stale sample the poll never evaluates, like one stale at the measure, so `.not` cannot pass on either race; tryRead's other callers are unchanged - mobile: the measure confirms a capture whose size is not the known screen's through viewportFor, as observe does, so a resized screen is picked up without an observe - core: reject an engine answer whose ratio contradicts intersects - expect: print a share in full when rounding would show the threshold as met - changeset: drop the 0.24.1 floor sentence; main's floors are 0.25.0 --- .changeset/viewport-matcher.md | 3 +- docs/reference/engine.mdx | 4 +- packages/core/src/engine/session.ts | 8 ++-- packages/core/src/locator/engine.ts | 35 +++++++++------- packages/e2e/src/expect/async.ts | 40 +++++++++++++------ .../e2e/tests/unit/expect-viewport.test.ts | 15 +++++-- .../e2e/tests/unit/locator-engine.test.ts | 18 +++++++++ packages/mobile/src/engine.ts | 2 +- packages/mobile/src/surface.ts | 30 ++++++++------ packages/mobile/tests/unit/engine.test.ts | 17 ++++++++ packages/web/src/surface.ts | 22 +++++++--- .../integration/viewport-intersection.test.ts | 22 ++++++++++ 12 files changed, 159 insertions(+), 57 deletions(-) diff --git a/.changeset/viewport-matcher.md b/.changeset/viewport-matcher.md index ec5aa2c985..edfbd0645a 100644 --- a/.changeset/viewport-matcher.md +++ b/.changeset/viewport-matcher.md @@ -13,5 +13,4 @@ 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`. Engines implement the optional `viewportIntersection` method for the new -`viewport-intersection` capability. `@e2e-dev/web` and `@e2e-dev/mobile` now -need `@e2e-dev/core` 0.24.1 or later. +`viewport-intersection` capability. diff --git a/docs/reference/engine.mdx b/docs/reference/engine.mdx index 91e54431bc..2632510f9f 100644 --- a/docs/reference/engine.mdx +++ b/docs/reference/engine.mdx @@ -466,8 +466,8 @@ 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. The harness fails the step with `ENGINE_FAILURE` on an answer -outside this shape. +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 diff --git a/packages/core/src/engine/session.ts b/packages/core/src/engine/session.ts index 8f2a24337e..2fea0314d6 100644 --- a/packages/core/src/engine/session.ts +++ b/packages/core/src/engine/session.ts @@ -509,15 +509,17 @@ export function createEngineSession(options: EngineSessionOptions): TargetSessio /** * An engine's `viewportIntersection` answer, held to the contract: a matcher - * must never pass on a ratio outside 0 to 1 or a missing verdict. + * 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); + 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`, + `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 }, ); } diff --git a/packages/core/src/locator/engine.ts b/packages/core/src/locator/engine.ts index 34192cbe44..61bd77d1a6 100644 --- a/packages/core/src/locator/engine.ts +++ b/packages/core/src/locator/engine.ts @@ -445,37 +445,39 @@ 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 node that went stale - * before it was measured has a null `intersection`, 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. + * 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; intersection: ViewportIntersection | null }> { + ): 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 } = await this.readOne(expression, reads, 'empty'); - if (node === null) return { node, count, intersection: null }; + 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, intersection }; + return { node, count, stale, intersection }; } catch (cause) { - if (asEngineError(cause)?.code === 'NODE_STALE') return { node, count, intersection: null }; + if (asEngineError(cause)?.code === 'NODE_STALE') return { node, count, stale: true }; throw translateLocatorError(cause, expression); } } @@ -490,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/e2e/src/expect/async.ts b/packages/e2e/src/expect/async.ts index 6b4975cda9..5028aa9fc2 100644 --- a/packages/e2e/src/expect/async.ts +++ b/packages/e2e/src/expect/async.ts @@ -38,11 +38,13 @@ interface Sample { 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; /** - * How much of `node` is inside the viewport, for a `measuresViewport` - * matcher; null when the node went stale before it was measured. + * 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 intersection?: ViewportIntersection | null; + readonly stale?: boolean; } interface MatcherSpec { @@ -65,7 +67,7 @@ interface MatcherSpec { * rejects keeps the poll waiting, negated or not: `not.toHaveValue` on a * heading is not a pass. */ - readonly evaluableNode?: (node: SemanticNode, sample: Sample) => boolean; + readonly evaluableNode?: (node: SemanticNode) => boolean; /** * The matcher reads what an engine withholds on a secure field, its value, * text, or attributes; a name is never withheld. A secure node in the sample @@ -239,16 +241,17 @@ 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, sample) ?? true; + return spec.evaluableNode?.(sample.node) ?? true; } private async sample(spec: MatcherSpec, reads: ReadWindow): Promise { const { engine } = this.internals.context; if (spec.measuresViewport === true) { - const { node, count, intersection } = await engine.readViewport(this.internals.expression, reads); - return { count, node, nodes: [], intersection }; + 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); @@ -393,9 +396,8 @@ class AsyncExpectationImpl implements AsyncExpectation { measuresViewport: true, // No match is outside the viewport: a device leaves offscreen nodes out of its tree. evaluableWithoutNode: true, - evaluableNode: (_node, sample) => sample.intersection != null, predicate: ({ node, intersection }) => { - if (node === null || intersection == null || !intersection.intersects) return false; + if (node === null || intersection === undefined || !intersection.intersects) return false; if (minimum === undefined) return true; if (intersection.ratio === undefined) { throw new ConfigurationError( @@ -407,13 +409,13 @@ class AsyncExpectationImpl implements AsyncExpectation { }, describeExpected: minimum === undefined ? 'inside the viewport' : `at least ${minimum} of its box inside the viewport`, - observed: ({ node, intersection }) => { - if (node === null) return 'no node'; - if (intersection == null) return 'a node that went stale before it was measured'; + 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' - : `${Number(intersection.ratio.toFixed(3))} of its box inside the viewport`; + : `${describeRatio(intersection.ratio, minimum)} of its box inside the viewport`; }, }, options?.timeout, @@ -576,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/unit/expect-viewport.test.ts b/packages/e2e/tests/unit/expect-viewport.test.ts index c278348acd..dcaa742317 100644 --- a/packages/e2e/tests/unit/expect-viewport.test.ts +++ b/packages/e2e/tests/unit/expect-viewport.test.ts @@ -117,9 +117,18 @@ describe('toBeInViewport', () => { expect(String((error as Error).message)).not.toContain('hunter2'); }); - it('fails on an engine answer outside the contract', async () => { - const locator = screenMeasuring(() => ({ intersects: true, ratio: 2 })).getByTestId('target'); - expect(await failure(expectFixture(locator).toBeInViewport())).toMatchObject({ code: 'ENGINE_FAILURE' }); + 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: 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', () => { 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/mobile/src/engine.ts b/packages/mobile/src/engine.ts index 54e10ea545..9ca24ab590 100644 --- a/packages/mobile/src/engine.ts +++ b/packages/mobile/src/engine.ts @@ -48,7 +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) => surface.viewportIntersection(ref), + 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 f0f6b4d428..2a8d44ae42 100644 --- a/packages/mobile/src/surface.ts +++ b/packages/mobile/src/surface.ts @@ -229,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; } @@ -1225,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; @@ -1259,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 }; } @@ -1267,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); @@ -1322,25 +1323,27 @@ export class AgentDeviceSurface { * 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 the - * session confirmed, not a capture's own size, which an app drawn smaller - * than the screen shrinks. A rect whose window could not be placed on the - * screen is refused rather than guessed at. + * 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): Promise { + async viewportIntersection(ref: NodeRef, operation: OperationContext, budget: InputBudget): Promise { const entry = this.resolveRef(ref); const rect = entry.node.rect; - const screen = this.knownViewport; 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 || screen === undefined) { - throw new EngineError('UNSUPPORTED_CAPABILITY', `node ${ref.id} has no bounds on a screen of known size, so whether it is in the viewport is unknown`, { + 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 }; @@ -1394,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, }; @@ -1851,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 0c672f3dd3..931888e6e7 100644 --- a/packages/mobile/tests/unit/engine.test.ts +++ b/packages/mobile/tests/unit/engine.test.ts @@ -1811,6 +1811,23 @@ describe('location', () => { 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] })); diff --git a/packages/web/src/surface.ts b/packages/web/src/surface.ts index 8574f4ed13..0372f71711 100644 --- a/packages/web/src/surface.ts +++ b/packages/web/src/surface.ts @@ -1555,21 +1555,31 @@ function inFrame(node: SemanticNode, frame: Rect | null | undefined): SemanticNo /** * 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. + * 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'); - const box = element.getBoundingClientRect(); - if (element.getClientRects().length === 0 || box.width <= 0 || box.height <= 0) { - return Promise.resolve({ intersects: false, ratio: 0 }); - } + 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, entries.at(-1)?.intersectionRatio ?? 0)); + const ratio = Math.min(1, Math.max(0, entry.intersectionRatio)); resolve({ intersects: ratio > 0, ratio }); }); observer.observe(element); diff --git a/packages/web/tests/integration/viewport-intersection.test.ts b/packages/web/tests/integration/viewport-intersection.test.ts index 65c855ba7a..bc43b08615 100644 --- a/packages/web/tests/integration/viewport-intersection.test.ts +++ b/packages/web/tests/integration/viewport-intersection.test.ts @@ -97,4 +97,26 @@ describe('viewport intersection on the web engine', () => { 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' }); + } + }); }); From d11239598cec2d09a7e4a8f8ddb55b21dda8cde4 Mon Sep 17 00:00:00 2001 From: Krzysztof Moch Date: Mon, 23 Nov 2026 08:30:48 +0100 Subject: [PATCH 10/11] test(viewport): cover the invalid manifest, contract answers, fold, and flat boxes From michal-e2e's review: the invalid manifest fixture now fails on the viewportIntersection rule alone, ratio 0 runs on an engine that reports no share, the contract test covers every refused answer, a mobile fold measures against the new screen, and a zero-height web element reads as outside. The changeset, skill, and errors reference name when ratio is refused on a device. --- .changeset/viewport-matcher.md | 3 ++- docs/reference/errors.mdx | 2 +- .../fixtures/engine-manifest-v1.invalid.json | 7 +++--- .../e2e/tests/unit/engine-protocol.test.ts | 4 ++++ .../e2e/tests/unit/expect-viewport.test.ts | 10 ++++++++- .../e2e/tests/unit/schema-fixtures.test.ts | 11 +++++++++- packages/mobile/tests/unit/engine.test.ts | 22 ++++++++++++++++++- .../integration/viewport-intersection.test.ts | 2 ++ .../skills/e2e/references/writing-tests.md | 3 ++- skills/e2e/references/writing-tests.md | 3 ++- 10 files changed, 57 insertions(+), 10 deletions(-) diff --git a/.changeset/viewport-matcher.md b/.changeset/viewport-matcher.md index edfbd0645a..ad774b13c3 100644 --- a/.changeset/viewport-matcher.md +++ b/.changeset/viewport-matcher.md @@ -11,6 +11,7 @@ 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`. +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/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/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/tests/unit/engine-protocol.test.ts b/packages/e2e/tests/unit/engine-protocol.test.ts index c74929775b..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', () => { diff --git a/packages/e2e/tests/unit/expect-viewport.test.ts b/packages/e2e/tests/unit/expect-viewport.test.ts index dcaa742317..b583def0d2 100644 --- a/packages/e2e/tests/unit/expect-viewport.test.ts +++ b/packages/e2e/tests/unit/expect-viewport.test.ts @@ -61,6 +61,8 @@ describe('toBeInViewport', () => { 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({ @@ -118,7 +120,13 @@ describe('toBeInViewport', () => { }); 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: 1 }, { intersects: true, ratio: 0 }]) { + 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' }); } 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/tests/unit/engine.test.ts b/packages/mobile/tests/unit/engine.test.ts index 931888e6e7..326280a87e 100644 --- a/packages/mobile/tests/unit/engine.test.ts +++ b/packages/mobile/tests/unit/engine.test.ts @@ -1795,7 +1795,11 @@ describe('location', () => { 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' }], + 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) => { @@ -1805,6 +1809,8 @@ describe('location', () => { 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 }); @@ -3682,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/tests/integration/viewport-intersection.test.ts b/packages/web/tests/integration/viewport-intersection.test.ts index bc43b08615..d3c64165b7 100644 --- a/packages/web/tests/integration/viewport-intersection.test.ts +++ b/packages/web/tests/integration/viewport-intersection.test.ts @@ -29,6 +29,7 @@ const DOCUMENT = `
+