Skip to content

The fastest browser for AI agents to run browser automation, built for sharing your logged-in browser state with your AI agents, like Codex or Claude Code, without disturbing you. Zero cost, zero config.

feat(ego-browser): use wheel motion for page actions

Autefbc2e425d09d
diff --git a/docs/native-snapshot-ref-requirement.md b/docs/native-snapshot-ref-requirement.md
index 48c52da..ab17c8b 100644
--- a/docs/native-snapshot-ref-requirement.md
+++ b/docs/native-snapshot-ref-requirement.md
@@ -24,6 +24,18 @@ groups, an iframe, an image, an SVG, a canvas, and an empty table cell is
captured twice. The compact output is identical on the second pass, the sibling
groups remain distinct, and every ref still resolves to its original node.
+## Deferred: targeted snapshot scope
+
+A future snapshot API should be able to limit capture to one subtree selected
+by a current ref or selector, including content inside an iframe or OOPIF. The
+browser should apply the scope before serializing the snapshot; filtering a
+full snapshot in JS does not reduce native work or transferred content.
+
+The selected root must resolve uniquely, retain Page and frame provenance, and
+produce refs that remain valid for normal Page actions. A missing or ambiguous
+root should fail clearly. The exact public API is intentionally undecided, and
+this requirement is not scheduled for the current implementation.
+
## Snapshot refs for iframe content
`ego.snapshot()` already includes text from ordinary iframes and OOPIFs, but
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs
index 55ecf4b..4ad7aa5 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs
@@ -710,15 +710,16 @@ export function pageActionsAndPopupCase() {
true,
"page.mouse.wheel scrolls the addressed document asynchronously"
);
- const innerScrollPoint = await source.evaluate(() => {
+ const innerScrollPoint = await source.evaluate(async () => {
const element = document.querySelector("#inner-scroll");
- element.scrollIntoView({ block: "center" });
+ element.scrollIntoView({ block: "center", behavior: "instant" });
element.scrollTop = 0;
+ await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
const rect = element.getBoundingClientRect();
return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
});
await source.mouse.move(innerScrollPoint.x, innerScrollPoint.y);
- await source.mouse.wheel(0, 120);
+ await source.mouse.wheel(0, 300);
let innerScrolled = false;
for (let attempt = 0; attempt < 20; attempt += 1) {
innerScrolled = await source.evaluate(
@@ -731,6 +732,52 @@ export function pageActionsAndPopupCase() {
assertEqual((await currentTab()).targetId, source.targetId, "Page mouse methods keep their Page active");
await source.evaluate(() => {
+ window.scrollTo(0, 0);
+ window.__preventedWheelEvents = [];
+ const preventWheel = (event) => {
+ window.__preventedWheelEvents.push({
+ deltaY: event.deltaY,
+ trusted: event.isTrusted,
+ });
+ event.preventDefault();
+ };
+ window.__removePreventedWheel = () => {
+ removeEventListener("wheel", preventWheel, true);
+ delete window.__removePreventedWheel;
+ };
+ addEventListener("wheel", preventWheel, { capture: true, passive: false });
+ });
+ await source.mouse.move(10, 10);
+ await source.mouse.wheel(0, 300);
+ const preventedWheel = await source.evaluate(() => {
+ const result = {
+ scrollY,
+ events: window.__preventedWheelEvents,
+ };
+ window.__removePreventedWheel();
+ return result;
+ });
+ assertEqual(preventedWheel.scrollY, 0, "wheel preventDefault still blocks the motion");
+ assert(
+ preventedWheel.events.length > 0 &&
+ preventedWheel.events.every((event) => event.trusted === true),
+ "a prevented motion remains observable as trusted wheel input"
+ );
+
+ await source.evaluate(() => {
+ window.__autoScrollProbe = { scrollIntoViewCalls: 0, wheelEvents: [] };
+ const originalScrollIntoView = Element.prototype.scrollIntoView;
+ Element.prototype.scrollIntoView = function(...args) {
+ window.__autoScrollProbe.scrollIntoViewCalls += 1;
+ return originalScrollIntoView.apply(this, args);
+ };
+ document.addEventListener("wheel", (event) => {
+ window.__autoScrollProbe.wheelEvents.push({
+ deltaX: event.deltaX,
+ deltaY: event.deltaY,
+ trusted: event.isTrusted,
+ });
+ }, true);
const spacer = document.createElement("div");
spacer.style.height = "2200px";
const button = document.createElement("button");
@@ -745,9 +792,72 @@ export function pageActionsAndPopupCase() {
const offscreenResult = await source.evaluate(() => ({
trusted: window.__pageOffscreenClickTrusted,
scrollY,
+ probe: window.__autoScrollProbe,
}));
assertEqual(offscreenResult.trusted, true, "offscreen Page click remains a trusted browser event");
assert(offscreenResult.scrollY > 0, "Page click scrolls an offscreen element into view");
+ assertEqual(
+ offscreenResult.probe.scrollIntoViewCalls,
+ 0,
+ "Page actions do not invoke the site's scrollIntoView implementation"
+ );
+ assert(
+ offscreenResult.probe.wheelEvents.length > 1 &&
+ offscreenResult.probe.wheelEvents.every((event) => event.trusted === true),
+ "Page actions bring offscreen elements into view with trusted wheel input"
+ );
+
+ await source.evaluate(() => {
+ window.__autoScrollProbe.wheelEvents = [];
+ const scroller = document.createElement("div");
+ scroller.id = "page-nested-auto-scroll";
+ scroller.style.cssText =
+ "position:fixed;left:20px;top:180px;width:300px;height:120px;" +
+ "overflow:auto;background:white;z-index:2147483647";
+ const content = document.createElement("div");
+ content.style.height = "760px";
+ const input = document.createElement("input");
+ input.id = "page-nested-offscreen-field";
+ const button = document.createElement("button");
+ button.id = "page-nested-offscreen-button";
+ button.textContent = "Nested offscreen action";
+ button.style.marginTop = "680px";
+ button.addEventListener("click", (event) => {
+ window.__pageNestedOffscreenClickTrusted = event.isTrusted;
+ });
+ content.append(input, button);
+ scroller.append(content);
+ document.body.append(scroller);
+ });
+ await source.click("#page-nested-offscreen-button");
+ const nestedScrollResult = await source.evaluate(() => ({
+ trusted: window.__pageNestedOffscreenClickTrusted,
+ scrollTop: document.querySelector("#page-nested-auto-scroll").scrollTop,
+ wheelEvents: window.__autoScrollProbe.wheelEvents,
+ }));
+ assertEqual(
+ nestedScrollResult.trusted,
+ true,
+ "nested offscreen Page click remains a trusted browser event"
+ );
+ assert(
+ nestedScrollResult.scrollTop > 0 && nestedScrollResult.wheelEvents.length > 1,
+ "Page actions scroll the nearest nested container with the shared wheel motion"
+ );
+ await source.evaluate("window.__autoScrollProbe.wheelEvents = []");
+ await source.fill("#page-nested-offscreen-field", "nested fill");
+ const nestedFillResult = await source.evaluate(() => ({
+ value: document.querySelector("#page-nested-offscreen-field").value,
+ scrollTop: document.querySelector("#page-nested-auto-scroll").scrollTop,
+ wheelEvents: window.__autoScrollProbe.wheelEvents,
+ }));
+ assertEqual(nestedFillResult.value, "nested fill", "Page.fill reaches a clipped field");
+ assert(
+ nestedFillResult.scrollTop < nestedScrollResult.scrollTop &&
+ nestedFillResult.wheelEvents.length > 1 &&
+ nestedFillResult.wheelEvents.every((event) => event.trusted === true),
+ "Page.fill uses trusted wheel input before entering text"
+ );
await source.evaluate((popupUrl) => {
const link = document.createElement("a");
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-oopif.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-oopif.mjs
index d9b2243..67ff55a 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-oopif.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-oopif.mjs
@@ -2,12 +2,45 @@ export function pageOopifActionCase() {
return `
const task = await taskSpace(taskName);
const page = await newPageAt(task, baseUrl + "/?page-api=oopif");
+ const initialFrameState = await page.evaluate(() => {
+ const frame = document.querySelector("#fixture-frame");
+ frame.style.cssText =
+ "display:block;margin-top:1600px;width:500px;height:300px";
+ window.__rootWheelEvents = [];
+ window.addEventListener(
+ "wheel",
+ (event) => window.__rootWheelEvents.push({
+ deltaY: event.deltaY,
+ trusted: event.isTrusted,
+ }),
+ { passive: true }
+ );
+ return {
+ frameTop: frame.getBoundingClientRect().top,
+ viewportHeight: innerHeight,
+ };
+ });
+ assert(
+ initialFrameState.frameTop > initialFrameState.viewportHeight,
+ "the cross-site iframe starts below the viewport"
+ );
const snapshot = await page.snapshot({ scope: "full_page" });
assertIncludes(snapshot, "Run iframe action", "snapshot includes cross-site iframe content");
assertIncludes(snapshot, "Iframe field", "snapshot includes the iframe input");
await page.click('loc=role:button[name="Run iframe action"]');
await page.fill('loc=css:#iframe-field', "filled through Page");
+ const outerScrollState = await page.evaluate(() => ({
+ scrollY,
+ wheelEvents: window.__rootWheelEvents,
+ }));
+ assert(outerScrollState.scrollY > 0, "Page actions scroll the iframe owner into view");
+ assert(
+ outerScrollState.wheelEvents.length > 0 &&
+ outerScrollState.wheelEvents.every((event) => event.trusted),
+ "the outer document receives trusted wheel input"
+ );
+
const frame = (await task.cdp("Target.getTargets")).targetInfos.find(
(target) =>
target.type === "iframe" &&
diff --git a/package/ego-browser/src/driver/action-target.test.mjs b/package/ego-browser/src/driver/action-target.test.mjs
index ff61389..ec3c168 100644
--- a/package/ego-browser/src/driver/action-target.test.mjs
+++ b/package/ego-browser/src/driver/action-target.test.mjs
@@ -1,7 +1,11 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { ACTION_TARGET_STATE_HELPERS } from "../../dist/src/driver/action-target.js";
+import {
+ ACTION_TARGET_STATE_HELPERS,
+ HIT_TARGET_HELPERS,
+ SCROLL_TARGET_HELPERS,
+} from "../../dist/src/driver/action-target.js";
function stateHelpers() {
return Function(`
@@ -133,3 +137,72 @@ test("action enabled state uses the nearest interactive owner for ARIA", () => {
"aria-disabled does not disable a target without a supporting role",
);
});
+
+test("scroll targeting recognizes an element clipped by a nested scroller", () => {
+ const { scrollRequestForPoint } = Function(`
+ ${SCROLL_TARGET_HELPERS}
+ return { scrollRequestForPoint };
+ `)();
+ const body = { parentElement: null };
+ const documentElement = { parentElement: null };
+ const view = {
+ innerWidth: 800,
+ innerHeight: 600,
+ getComputedStyle() {
+ return { overflowX: "hidden", overflowY: "auto" };
+ },
+ };
+ const ownerDocument = { body, documentElement, defaultView: view };
+ const scroller = {
+ ownerDocument,
+ parentElement: body,
+ scrollLeft: 0,
+ scrollTop: 0,
+ scrollWidth: 300,
+ clientWidth: 300,
+ scrollHeight: 900,
+ clientHeight: 120,
+ getBoundingClientRect() {
+ return { left: 20, top: 100, right: 320, bottom: 220 };
+ },
+ };
+ const target = { ownerDocument, parentElement: scroller };
+
+ assert.deepEqual(scrollRequestForPoint(target, { x: 80, y: 700 }), {
+ x: 170,
+ y: 160,
+ deltaX: 0,
+ deltaY: 540,
+ });
+ assert.equal(scrollRequestForPoint(target, { x: 80, y: 160 }), null);
+});
+
+test("action targeting chooses a real inline fragment instead of the bounding-box gap", () => {
+ const { actionPointForElement } = Function(`
+ ${HIT_TARGET_HELPERS}
+ return { actionPointForElement };
+ `)();
+ const target = {
+ ownerDocument: {
+ defaultView: { innerWidth: 800, innerHeight: 600 },
+ },
+ getClientRects() {
+ return [
+ { left: 700, top: 100, right: 780, bottom: 120, width: 80, height: 20 },
+ { left: 20, top: 140, right: 100, bottom: 160, width: 80, height: 20 },
+ ];
+ },
+ getBoundingClientRect() {
+ return {
+ left: 20,
+ top: 100,
+ right: 780,
+ bottom: 160,
+ width: 760,
+ height: 60,
+ };
+ },
+ };
+
+ assert.deepEqual(actionPointForElement(target), { x: 740, y: 110 });
+});
diff --git a/package/ego-browser/src/driver/action-target.ts b/package/ego-browser/src/driver/action-target.ts
index bad7d6e..a7d2d15 100644
--- a/package/ego-browser/src/driver/action-target.ts
+++ b/package/ego-browser/src/driver/action-target.ts
@@ -126,6 +126,124 @@ export const ACTION_TARGET_STATE_HELPERS = `
${ACTION_TARGET_STATE_FUNCTIONS}
`;
+const SCROLL_TARGET_FUNCTIONS = `
+ function actionPointForElement(target) {
+ const view = target?.ownerDocument?.defaultView;
+ if (!view) return null;
+ const rects = Array.from(target.getClientRects?.() || []).filter(
+ (rect) => rect.width > 0 && rect.height > 0
+ );
+ if (rects.length === 0) {
+ const rect = target.getBoundingClientRect?.();
+ if (!rect || rect.width <= 0 || rect.height <= 0) return null;
+ rects.push(rect);
+ }
+ let best = null;
+ for (const rect of rects) {
+ const left = Math.max(0, rect.left);
+ const top = Math.max(0, rect.top);
+ const right = Math.min(view.innerWidth, rect.right);
+ const bottom = Math.min(view.innerHeight, rect.bottom);
+ const visibleArea = Math.max(0, right - left) * Math.max(0, bottom - top);
+ const centerX = (rect.left + rect.right) / 2;
+ const centerY = (rect.top + rect.bottom) / 2;
+ const distanceX = centerX - Math.max(0, Math.min(view.innerWidth, centerX));
+ const distanceY = centerY - Math.max(0, Math.min(view.innerHeight, centerY));
+ const viewportDistance = distanceX * distanceX + distanceY * distanceY;
+ if (
+ !best ||
+ visibleArea > best.visibleArea ||
+ (visibleArea === best.visibleArea && viewportDistance < best.viewportDistance)
+ ) {
+ best = { rect, left, top, right, bottom, visibleArea, viewportDistance };
+ }
+ }
+ if (best.visibleArea > 0) {
+ return {
+ x: (best.left + best.right) / 2,
+ y: (best.top + best.bottom) / 2,
+ };
+ }
+ return {
+ x: (best.rect.left + best.rect.right) / 2,
+ y: (best.rect.top + best.rect.bottom) / 2,
+ };
+ }
+ function visibleScrollArea(rect, view) {
+ return {
+ left: Math.max(0, rect.left),
+ top: Math.max(0, rect.top),
+ right: Math.min(view.innerWidth, rect.right),
+ bottom: Math.min(view.innerHeight, rect.bottom),
+ };
+ }
+ function scrollRequestForPoint(target, point) {
+ const view = target?.ownerDocument?.defaultView;
+ if (!view) return null;
+ let ancestor = composedParent(target);
+ while (ancestor) {
+ if (
+ ancestor !== target.ownerDocument.body &&
+ ancestor !== target.ownerDocument.documentElement
+ ) {
+ const style = view.getComputedStyle(ancestor);
+ const canScrollX =
+ /^(auto|scroll|overlay)$/.test(style.overflowX) &&
+ ancestor.scrollWidth > ancestor.clientWidth + 1;
+ const canScrollY =
+ /^(auto|scroll|overlay)$/.test(style.overflowY) &&
+ ancestor.scrollHeight > ancestor.clientHeight + 1;
+ if (canScrollX || canScrollY) {
+ const area = visibleScrollArea(ancestor.getBoundingClientRect(), view);
+ if (area.right > area.left && area.bottom > area.top) {
+ let deltaX = canScrollX &&
+ (point.x < area.left || point.x >= area.right)
+ ? point.x - (area.left + area.right) / 2
+ : 0;
+ let deltaY = canScrollY &&
+ (point.y < area.top || point.y >= area.bottom)
+ ? point.y - (area.top + area.bottom) / 2
+ : 0;
+ if (
+ (deltaX < 0 && ancestor.scrollLeft <= 0) ||
+ (deltaX > 0 && ancestor.scrollLeft >= ancestor.scrollWidth - ancestor.clientWidth - 1)
+ ) deltaX = 0;
+ if (
+ (deltaY < 0 && ancestor.scrollTop <= 0) ||
+ (deltaY > 0 && ancestor.scrollTop >= ancestor.scrollHeight - ancestor.clientHeight - 1)
+ ) deltaY = 0;
+ if (deltaX || deltaY) {
+ return {
+ x: (area.left + area.right) / 2,
+ y: (area.top + area.bottom) / 2,
+ deltaX,
+ deltaY,
+ };
+ }
+ }
+ }
+ }
+ ancestor = composedParent(ancestor);
+ }
+ if (
+ point.x >= 0 && point.y >= 0 &&
+ point.x < view.innerWidth && point.y < view.innerHeight
+ ) return null;
+ return {
+ x: Math.max(0, Math.min(view.innerWidth - 1, point.x)),
+ y: Math.max(0, Math.min(view.innerHeight - 1, point.y)),
+ deltaX: point.x - view.innerWidth / 2,
+ deltaY: point.y - view.innerHeight / 2,
+ };
+ }
+`;
+
+/** Browser-side scroll targeting shared by candidate selection and actions. */
+export const SCROLL_TARGET_HELPERS = `
+ ${COMPOSED_PARENT_HELPER}
+ ${SCROLL_TARGET_FUNCTIONS}
+`;
+
/** Editing semantics layered on top of the shared composed-tree traversal. */
export const EDIT_ACTION_TARGET_HELPERS = `
${COMPOSED_TREE_HELPERS}
@@ -190,6 +308,7 @@ export const EDIT_ACTION_TARGET_HELPERS = `
// about shadow descendants, interactive ancestors, or modal blockers.
export const HIT_TARGET_HELPERS = `
${ACTION_TARGET_STATE_HELPERS}
+ ${SCROLL_TARGET_FUNCTIONS}
function isExplicitInteractiveElement(element) {
const tag = String(element?.tagName || "").toUpperCase();
if (["BUTTON", "INPUT", "SELECT", "TEXTAREA", "OPTION", "SUMMARY", "LABEL"].includes(tag)) {
diff --git a/package/ego-browser/src/driver/page-actions.ts b/package/ego-browser/src/driver/page-actions.ts
index 5514cd4..dd2ac64 100644
--- a/package/ego-browser/src/driver/page-actions.ts
+++ b/package/ego-browser/src/driver/page-actions.ts
@@ -8,7 +8,9 @@ import {
ACTION_TARGET_STATE_HELPERS,
EDIT_ACTION_TARGET_HELPERS,
HIT_TARGET_HELPERS,
+ SCROLL_TARGET_HELPERS,
} from "./action-target.js";
+import { dispatchWheelMotion } from "./scroll-motion.js";
type PageActionServices = {
cdp(
@@ -210,6 +212,7 @@ type MouseMoveState = PageMouseMoveOptions & {
const INPUT_EVENT_DELAY_MS = 25;
const FILL_VERIFICATION_ATTEMPTS = 5;
const FILL_VERIFICATION_INTERVAL_MS = 50;
+const AUTO_SCROLL_ATTEMPTS = 6;
type FillOutcome =
| "exact"
| "equivalent"
@@ -250,6 +253,7 @@ export async function clickInPage(
target.frameId,
"page.click",
options.force,
+ sessionId,
);
const buttons = pressedButtons(button);
await dispatchMouseEvent(services, target.sessionId, {
@@ -261,7 +265,7 @@ export async function clickInPage(
modifiers,
});
if (target.frameId) {
- // Moving into a same-process iframe can adjust the outer document's
+ // Moving into an iframe can adjust the outer document's
// scroll position. Translate the frame-local point again before the
// press so native input uses the post-hover viewport coordinates.
const pagePoint = await pagePointForFrame(
@@ -269,6 +273,7 @@ export async function clickInPage(
target.sessionId,
target.frameId,
point.local,
+ sessionId,
);
point = { ...pagePoint, local: point.local };
await assertElementEnabled(
@@ -373,6 +378,16 @@ export async function fillInPage(
resolved.sessionId,
resolved.objectId,
);
+ await resolveElementPoint(
+ services,
+ resolved.sessionId,
+ actionObjectId,
+ undefined,
+ resolved.frameId,
+ "page.fill",
+ true,
+ sessionId,
+ );
const preparationSource = `function fillPreparation(value, clearFirst) {
${ACTION_TARGET_STATE_HELPERS}
if (!this.isConnected) return { error: "element is not connected" };
@@ -413,7 +428,7 @@ export async function fillInPage(
}
if (directTypes.has(type)) {
const nextValue = value.trim();
- this.focus();
+ this.focus({ preventScroll: true });
if (isActionTargetDisabled(this)) return { error: "element is disabled" };
this.value = nextValue;
if (this.value !== nextValue) return { error: "malformed value" };
@@ -425,7 +440,7 @@ export async function fillInPage(
return { error: "element is not an input, textarea, or contenteditable element" };
}
- this.focus();
+ this.focus({ preventScroll: true });
if (isActionTargetDisabled(this)) return { error: "element is disabled" };
const cursorPoint = visibleCursorPoint();
const kind = this.isContentEditable ? "contenteditable" : tag;
@@ -472,6 +487,7 @@ export async function fillInPage(
resolved.sessionId,
resolved.frameId,
result?.cursorPoint,
+ sessionId,
),
);
const status = typeof result === "string" ? result : result?.status;
@@ -512,6 +528,7 @@ export async function fillInPage(
resolved.sessionId,
actionObjectId,
resolved.frameId,
+ sessionId,
);
result = await prepare();
if (typeof result?.error === "string") {
@@ -860,6 +877,7 @@ async function clickResolvedElement(
sessionId: string,
objectId: string,
frameId?: string,
+ pageSessionId = sessionId,
): Promise<void> {
const point = await resolveElementPoint(
services,
@@ -869,6 +887,7 @@ async function clickResolvedElement(
frameId,
"page.fill",
false,
+ pageSessionId,
);
await assertElementReceivesPointerEvents(
services,
@@ -991,6 +1010,7 @@ export async function hoverInPage(
resolved.frameId,
"page.hover",
options.force,
+ sessionId,
);
await dispatchMouseEvent(services, resolved.sessionId, {
type: "mouseMoved",
@@ -1050,6 +1070,7 @@ export async function dragAndDropInPage(
source.frameId,
"page.dragAndDrop",
options.force,
+ sessionId,
);
const targetPoint = await resolveElementPoint(
services,
@@ -1059,6 +1080,7 @@ export async function dragAndDropInPage(
target.frameId,
"page.dragAndDrop",
options.force,
+ sessionId,
);
const button = options.button ?? "left";
const buttons = pressedButtons(button);
@@ -1216,14 +1238,19 @@ export async function wheelInPage(
if (!Number.isFinite(deltaX) || !Number.isFinite(deltaY)) {
throw new TypeError("page.mouse.wheel requires finite deltaX and deltaY");
}
- await dispatchMouseEvent(services, sessionId, {
- type: "mouseWheel",
- x,
- y,
- modifiers,
- deltaX,
- deltaY,
- });
+ await dispatchWheelMotion(
+ {
+ dispatch: (params) => dispatchMouseEvent(services, sessionId, params),
+ sleep: services.sleep,
+ },
+ {
+ x,
+ y,
+ modifiers,
+ deltaX,
+ deltaY,
+ },
+ );
}
async function resolveElementPoint(
@@ -1234,6 +1261,7 @@ async function resolveElementPoint(
frameId?: string,
actionName = "page.click",
force = false,
+ pageSessionId = sessionId,
): Promise<{ x: number; y: number; local: { x: number; y: number } }> {
if (
position !== undefined &&
@@ -1248,28 +1276,17 @@ async function resolveElementPoint(
}
const pointExpression = position
? "({x:rect.x+position.x,y:rect.y+position.y})"
- : "({x:rect.x+rect.width/2,y:rect.y+rect.height/2})";
+ : "actionPointForElement(this)";
const expression = `async function(${position ? "position" : ""}) {
- ${force ? "" : HIT_TARGET_HELPERS}
+ ${force ? SCROLL_TARGET_HELPERS : HIT_TARGET_HELPERS}
if (!this.isConnected) return { error: "element is not connected" };
let rect = this.getBoundingClientRect();
let point = ${pointExpression};
- const outsideViewport =
- rect.width <= 0 || rect.height <= 0 ||
- point.x < 0 || point.y < 0 ||
- point.x >= window.innerWidth || point.y >= window.innerHeight;
- if (outsideViewport) {
- this.scrollIntoView({ block: "center", inline: "center", behavior: "instant" });
- rect = this.getBoundingClientRect();
- point = ${pointExpression};
- }
- if (
- rect.width <= 0 || rect.height <= 0 ||
- point.x < 0 || point.y < 0 ||
- point.x >= window.innerWidth || point.y >= window.innerHeight
- ) {
- return { error: "element is not visible in the viewport" };
+ if (rect.width <= 0 || rect.height <= 0 || !point) {
+ return { error: "element is not visible" };
}
+ const scroll = scrollRequestForPoint(this, point);
+ if (scroll) return { scroll };
const firstRect = { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
await new Promise((resolve) => {
let settled = false;
@@ -1300,34 +1317,167 @@ async function resolveElementPoint(
}
return point;
}`;
- const response = await services.cdp(
- "Runtime.callFunctionOn",
- {
- functionDeclaration: expression,
- objectId,
- arguments: position ? [{ value: position }] : [],
- returnByValue: true,
- awaitPromise: true,
- },
- sessionId,
+ if (frameId) {
+ await ensureFrameOwnerInView(services, pageSessionId, frameId, actionName);
+ }
+ for (let attempt = 0; attempt <= AUTO_SCROLL_ATTEMPTS; attempt += 1) {
+ const response = await services.cdp(
+ "Runtime.callFunctionOn",
+ {
+ functionDeclaration: expression,
+ objectId,
+ arguments: position ? [{ value: position }] : [],
+ returnByValue: true,
+ awaitPromise: true,
+ },
+ sessionId,
+ );
+ const point = runtimeValue(response, expression);
+ if (typeof point?.error === "string") {
+ throw new ElementResolutionError(
+ `${actionName} failed: ${point.error}`,
+ "transient",
+ );
+ }
+ const scroll = point?.scroll;
+ if (scroll) {
+ if (
+ attempt === AUTO_SCROLL_ATTEMPTS ||
+ !Number.isFinite(scroll.x) ||
+ !Number.isFinite(scroll.y) ||
+ !Number.isFinite(scroll.deltaX) ||
+ !Number.isFinite(scroll.deltaY)
+ ) {
+ throw new ElementResolutionError(
+ `${actionName} failed: element is not visible in the viewport`,
+ "transient",
+ );
+ }
+ const pageScrollPoint = await pagePointForFrame(
+ services,
+ sessionId,
+ frameId,
+ scroll,
+ pageSessionId,
+ );
+ await dispatchWheelMotion(
+ {
+ dispatch: (params) => dispatchMouseEvent(services, sessionId, params),
+ sleep: services.sleep,
+ },
+ {
+ x: pageScrollPoint.x,
+ y: pageScrollPoint.y,
+ deltaX: scroll.deltaX,
+ deltaY: scroll.deltaY,
+ },
+ );
+ continue;
+ }
+ if (!Number.isFinite(point?.x) || !Number.isFinite(point?.y)) {
+ throw new Error(`${actionName} could not resolve the element position`);
+ }
+ const pagePoint = await pagePointForFrame(
+ services,
+ sessionId,
+ frameId,
+ point,
+ pageSessionId,
+ );
+ return { ...pagePoint, local: point };
+ }
+ throw new ElementResolutionError(
+ `${actionName} failed: element is not visible in the viewport`,
+ "transient",
);
- const point = runtimeValue(response, expression);
- if (typeof point?.error === "string") {
+}
+
+async function ensureFrameOwnerInView(
+ services: PageActionServices,
+ pageSessionId: string,
+ frameId: string,
+ actionName: string,
+): Promise<void> {
+ const owner = await services.cdp(
+ "DOM.getFrameOwner",
+ { frameId },
+ pageSessionId,
+ );
+ const backendNodeId = owner?.backendNodeId;
+ if (backendNodeId === undefined || backendNodeId === null) {
throw new ElementResolutionError(
- `${actionName} failed: ${point.error}`,
+ `${actionName} failed: iframe is not available`,
"transient",
);
}
- if (!Number.isFinite(point?.x) || !Number.isFinite(point?.y)) {
- throw new Error(`${actionName} could not resolve the element position`);
- }
- const pagePoint = await pagePointForFrame(
- services,
- sessionId,
- frameId,
- point,
+ const resolved = await services.cdp(
+ "DOM.resolveNode",
+ { backendNodeId, objectGroup: "ego-browser" },
+ pageSessionId,
);
- return { ...pagePoint, local: point };
+ const objectId = resolved?.object?.objectId;
+ if (!objectId) {
+ throw new ElementResolutionError(
+ `${actionName} failed: iframe is not available`,
+ "transient",
+ );
+ }
+ const source = `function() {
+ ${SCROLL_TARGET_HELPERS}
+ if (!this.isConnected) return { error: "iframe is not connected" };
+ const rect = this.getBoundingClientRect();
+ if (rect.width <= 0 || rect.height <= 0) {
+ return { error: "iframe is not visible" };
+ }
+ const point = actionPointForElement(this);
+ if (!point) return { error: "iframe is not visible" };
+ return { scroll: scrollRequestForPoint(this, point) };
+ }`;
+ try {
+ for (let attempt = 0; attempt <= AUTO_SCROLL_ATTEMPTS; attempt += 1) {
+ const response = await services.cdp(
+ "Runtime.callFunctionOn",
+ {
+ functionDeclaration: source,
+ objectId,
+ returnByValue: true,
+ awaitPromise: false,
+ },
+ pageSessionId,
+ );
+ const result = runtimeValue(response, source);
+ if (typeof result?.error === "string") {
+ throw new ElementResolutionError(
+ `${actionName} failed: ${result.error}`,
+ "transient",
+ );
+ }
+ const scroll = result?.scroll;
+ if (!scroll) return;
+ if (
+ attempt === AUTO_SCROLL_ATTEMPTS ||
+ !Number.isFinite(scroll.x) ||
+ !Number.isFinite(scroll.y) ||
+ !Number.isFinite(scroll.deltaX) ||
+ !Number.isFinite(scroll.deltaY)
+ ) {
+ throw new ElementResolutionError(
+ `${actionName} failed: iframe is not visible in the viewport`,
+ "transient",
+ );
+ }
+ await dispatchWheelMotion(
+ {
+ dispatch: (params) =>
+ dispatchMouseEvent(services, pageSessionId, params),
+ sleep: services.sleep,
+ },
+ scroll,
+ );
+ }
+ } finally {
+ await releaseObject(services, pageSessionId, objectId);
+ }
}
async function pagePointForFrame(
@@ -1335,6 +1485,7 @@ async function pagePointForFrame(
sessionId: string,
frameId: string | undefined,
point: { x?: unknown; y?: unknown } | null | undefined,
+ pageSessionId = sessionId,
): Promise<{ x: number; y: number } | null | undefined> {
if (
!point ||
@@ -1342,11 +1493,16 @@ async function pagePointForFrame(
!Number.isFinite(point.x) ||
typeof point.y !== "number" ||
!Number.isFinite(point.y) ||
- !frameId
+ !frameId ||
+ sessionId !== pageSessionId
) {
return point as { x: number; y: number } | null | undefined;
}
- const owner = await services.cdp("DOM.getFrameOwner", { frameId }, sessionId);
+ const owner = await services.cdp(
+ "DOM.getFrameOwner",
+ { frameId },
+ pageSessionId,
+ );
const backendNodeId = owner?.backendNodeId;
if (backendNodeId === undefined || backendNodeId === null) {
throw new Error(`page action could not resolve iframe ${frameId}`);
@@ -1354,7 +1510,7 @@ async function pagePointForFrame(
const box = await services.cdp(
"DOM.getBoxModel",
{ backendNodeId },
- sessionId,
+ pageSessionId,
);
const content = box?.model?.content;
if (!Array.isArray(content) || content.length < 2) {
diff --git a/package/ego-browser/src/driver/scroll-motion.test.mjs b/package/ego-browser/src/driver/scroll-motion.test.mjs
new file mode 100644
index 0000000..e0a2f0e
--- /dev/null
+++ b/package/ego-browser/src/driver/scroll-motion.test.mjs
@@ -0,0 +1,82 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { dispatchWheelMotion } from "../../dist/src/driver/scroll-motion.js";
+
+test("dispatchWheelMotion preserves the requested delta within one bounded motion", async () => {
+ const events = [];
+ const sleeps = [];
+
+ await dispatchWheelMotion(
+ {
+ async dispatch(event) {
+ events.push(event);
+ },
+ async sleep(ms) {
+ sleeps.push(ms);
+ },
+ },
+ { x: 40, y: 80, deltaX: -150, deltaY: 600, modifiers: 2 },
+ );
+
+ assert(events.length > 1);
+ assert(events.length <= 12);
+ assert.equal(
+ events.reduce((total, event) => total + event.deltaX, 0),
+ -150,
+ );
+ assert.equal(
+ events.reduce((total, event) => total + event.deltaY, 0),
+ 600,
+ );
+ assert(events.every((event) => event.x === 40 && event.y === 80));
+ assert(events.every((event) => event.modifiers === 2));
+ assert(sleeps.reduce((total, duration) => total + duration, 0) <= 88);
+});
+
+test("dispatchWheelMotion paces a page-sized scroll without visible jumps", async () => {
+ const events = [];
+ const sleeps = [];
+
+ await dispatchWheelMotion(
+ {
+ async dispatch(event) {
+ events.push(event);
+ },
+ async sleep(ms) {
+ sleeps.push(ms);
+ },
+ },
+ { x: 400, y: 300, deltaX: 0, deltaY: 960 },
+ );
+
+ assert(events.length >= 10);
+ assert(events.length <= 12);
+ assert(
+ events.every((event) => event.deltaY > 0 && event.deltaY <= 960 * 0.18),
+ "a single wheel event must not carry a visibly large part of the motion",
+ );
+ const duration = sleeps.reduce((total, value) => total + value, 0);
+ assert(duration >= 80);
+ assert(duration <= 100);
+});
+
+test("dispatchWheelMotion keeps small wheel actions immediate", async () => {
+ const events = [];
+ const sleeps = [];
+
+ await dispatchWheelMotion(
+ {
+ async dispatch(event) {
+ events.push(event);
+ },
+ async sleep(ms) {
+ sleeps.push(ms);
+ },
+ },
+ { x: 0, y: 0, deltaX: 0, deltaY: 100 },
+ );
+
+ assert.equal(events.length, 1);
+ assert.equal(events[0].deltaY, 100);
+ assert.deepEqual(sleeps, []);
+});
diff --git a/package/ego-browser/src/driver/scroll-motion.ts b/package/ego-browser/src/driver/scroll-motion.ts
new file mode 100644
index 0000000..2ed5c3b
--- /dev/null
+++ b/package/ego-browser/src/driver/scroll-motion.ts
@@ -0,0 +1,56 @@
+type WheelMotion = {
+ x: number;
+ y: number;
+ deltaX: number;
+ deltaY: number;
+ modifiers?: number;
+};
+
+type WheelMotionServices = {
+ dispatch(params: Record<string, unknown>): Promise<void>;
+ sleep(ms: number): Promise<void>;
+};
+
+const SINGLE_EVENT_DISTANCE = 120;
+const PIXELS_PER_STEP = 80;
+const MAX_STEPS = 12;
+const STEP_INTERVAL_MS = 8;
+
+/**
+ * Dispatch one logical wheel action as a short eased browser-input motion.
+ * Small deltas stay immediate, while page-sized deltas are spread over enough
+ * input frames to remain visually continuous without creating a long gesture.
+ */
+export async function dispatchWheelMotion(
+ services: WheelMotionServices,
+ motion: WheelMotion,
+): Promise<void> {
+ const distance = Math.max(Math.abs(motion.deltaX), Math.abs(motion.deltaY));
+ const steps =
+ distance <= SINGLE_EVENT_DISTANCE
+ ? 1
+ : Math.min(MAX_STEPS, Math.ceil(distance / PIXELS_PER_STEP));
+ let emittedX = 0;
+ let emittedY = 0;
+
+ for (let step = 1; step <= steps; step += 1) {
+ const progress = step / steps;
+ const eased = progress * progress * (3 - 2 * progress);
+ const cumulativeX = step === steps ? motion.deltaX : motion.deltaX * eased;
+ const cumulativeY = step === steps ? motion.deltaY : motion.deltaY * eased;
+ const deltaX = cumulativeX - emittedX;
+ const deltaY = cumulativeY - emittedY;
+ emittedX = cumulativeX;
+ emittedY = cumulativeY;
+
+ await services.dispatch({
+ type: "mouseWheel",
+ x: motion.x,
+ y: motion.y,
+ modifiers: motion.modifiers ?? 0,
+ deltaX,
+ deltaY,
+ });
+ if (step < steps) await services.sleep(STEP_INTERVAL_MS);
+ }
+}
diff --git a/package/ego-browser/src/element-resolver.test.mjs b/package/ego-browser/src/element-resolver.test.mjs
index 1d4cde2..5202347 100644
--- a/package/ego-browser/src/element-resolver.test.mjs
+++ b/package/ego-browser/src/element-resolver.test.mjs
@@ -658,7 +658,11 @@ test("pointer action resolution skips a covered Page match for a frame match", a
new Map([["frame-child", "session:frame-child"]]),
{ strict: true, actionability: "pointer-enabled" },
),
- { objectId: "frame-button", sessionId: "session:frame-child" },
+ {
+ objectId: "frame-button",
+ sessionId: "session:frame-child",
+ frameId: "frame-child",
+ },
);
});
@@ -752,6 +756,7 @@ test("semantic locators search cross-process iframe sessions", async () => {
assert.deepEqual(resolved, {
objectId: "iframe-button",
sessionId: "session:frame-child",
+ frameId: "frame-child",
});
});
@@ -894,7 +899,11 @@ test("a unique interactable frame role wins over a blocked Page duplicate", asyn
new Map([["frame-child", "session:frame-child"]]),
{ actionability: "pointer-enabled" },
),
- { objectId: "node:session:frame-child", sessionId: "session:frame-child" },
+ {
+ objectId: "node:session:frame-child",
+ sessionId: "session:frame-child",
+ frameId: "frame-child",
+ },
);
});
diff --git a/package/ego-browser/src/element-resolver.ts b/package/ego-browser/src/element-resolver.ts
index 9875a93..f8b8453 100644
--- a/package/ego-browser/src/element-resolver.ts
+++ b/package/ego-browser/src/element-resolver.ts
@@ -12,6 +12,7 @@ type ElementActionability =
type PageRuntimeContext = {
sessionId: string;
frameId?: string;
+ ownerFrameId?: string;
contextId?: number;
};
@@ -171,9 +172,7 @@ export async function resolveElementObjectId(
return {
objectId,
sessionId: effectiveSessionId,
- ...(entry.frameId && effectiveSessionId === sessionId
- ? { frameId: entry.frameId }
- : {}),
+ ...(entry.frameId ? { frameId: entry.frameId } : {}),
};
}
} catch {
@@ -205,9 +204,7 @@ export async function resolveElementObjectId(
return {
objectId,
sessionId: effectiveSessionId,
- ...(entry.frameId && effectiveSessionId === sessionId
- ? { frameId: entry.frameId }
- : {}),
+ ...(entry.frameId ? { frameId: entry.frameId } : {}),
};
}
@@ -561,7 +558,9 @@ async function resolveRawSelectorObjectId(
return {
objectId,
sessionId: match.sessionId,
- ...(match.frameId ? { frameId: match.frameId } : {}),
+ ...(match.ownerFrameId || match.frameId
+ ? { frameId: match.ownerFrameId || match.frameId }
+ : {}),
};
}
@@ -747,7 +746,9 @@ function pageSessions(sessionId, iframeSessions) {
}
function pageContexts(sessionId, iframeSessions) {
- const contexts = [{ sessionId, frameId: undefined }];
+ const contexts: PageRuntimeContext[] = [
+ { sessionId, frameId: undefined, ownerFrameId: undefined },
+ ];
const entries =
iframeSessions instanceof Map
? iframeSessions.entries()
@@ -756,6 +757,7 @@ function pageContexts(sessionId, iframeSessions) {
contexts.push({
sessionId: frameSessionId,
frameId: frameSessionId === sessionId ? frameId : undefined,
+ ownerFrameId: frameId,
});
}
return contexts;
@@ -943,7 +945,9 @@ async function resolveLocatorObjectId(
return {
objectId,
sessionId: match.sessionId,
- ...(match.frameId ? { frameId: match.frameId } : {}),
+ ...(match.ownerFrameId || match.frameId
+ ? { frameId: match.ownerFrameId || match.frameId }
+ : {}),
};
}
const contexts = await runtimePageContexts(cdp, sessionId, iframeSessions);
@@ -970,7 +974,9 @@ async function resolveLocatorObjectId(
return {
objectId,
sessionId: match.sessionId,
- ...(match.frameId ? { frameId: match.frameId } : {}),
+ ...(match.ownerFrameId || match.frameId
+ ? { frameId: match.ownerFrameId || match.frameId }
+ : {}),
};
}
@@ -1112,6 +1118,7 @@ async function findUniqueRoleMatch(
matches.push({
backendNodeId: node.backendDOMNodeId,
frameId: context.frameId,
+ ownerFrameId: context.ownerFrameId,
sessionId: context.sessionId,
});
}
@@ -1243,10 +1250,9 @@ async function roleMatchActionability(
isActionTargetDisabled(this)
) return { actionable: false, blocker: "element is disabled" };
if (${JSON.stringify(actionabilityRequiresPointer(actionability))}) {
- const point = { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
- const offscreen = point.x < 0 || point.y < 0 ||
- point.x >= view.innerWidth || point.y >= view.innerHeight;
- if (!offscreen) {
+ const point = actionPointForElement(this);
+ if (!point) return { actionable: false };
+ if (!scrollRequestForPoint(this, point)) {
const interceptor = interceptingElementAtPoint(this, point);
if (interceptor) {
return {
@@ -1592,10 +1598,10 @@ function buildActionableElementsJs(
isActionTargetDisabled(element)
) return false;
if (!${JSON.stringify(actionabilityRequiresPointer(actionability))}) return true;
- const point = { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
- const offscreen = point.x < 0 || point.y < 0 ||
- point.x >= view.innerWidth || point.y >= view.innerHeight;
- return offscreen || !interceptingElementAtPoint(element, point);
+ const point = actionPointForElement(element);
+ if (!point) return false;
+ return Boolean(scrollRequestForPoint(element, point)) ||
+ !interceptingElementAtPoint(element, point);
});
return __egoActionableMatches;
})()`;
@@ -1626,9 +1632,9 @@ async function firstActionabilityBlocker(
isActionTargetDisabled(element)
) return "element is disabled";
if (!${JSON.stringify(actionabilityRequiresPointer(actionability))}) continue;
- const point = { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
- if (point.x < 0 || point.y < 0 ||
- point.x >= view.innerWidth || point.y >= view.innerHeight) continue;
+ const point = actionPointForElement(element);
+ if (!point) continue;
+ if (scrollRequestForPoint(element, point)) continue;
const interceptor = interceptingElementAtPoint(element, point);
if (interceptor) {
return describeHitTarget(interceptor) + " intercepts pointer events";
diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjs
index 4625261..880c2a2 100644
--- a/package/ego-browser/src/page-model.test.mjs
+++ b/package/ego-browser/src/page-model.test.mjs
@@ -43,6 +43,7 @@ function createFixture(rootDir) {
const pendingDialogs = new Map();
let rejectedClickPointsRemaining = 0;
let interceptedClickPointsRemaining = 0;
+ let scrollClickPointsRemaining = 0;
let fillElementKind = "input";
let fillText = "";
let fillTransform = null;
@@ -74,6 +75,7 @@ function createFixture(rootDir) {
const sessionTargets = new Map();
const snapshotOptions = [];
const browserEventListeners = new Set();
+ const sleepDurations = [];
function openPendingPopup() {
if (!popupOnNextClick) return;
@@ -472,6 +474,17 @@ function createFixture(rootDir) {
};
}
if (params.functionDeclaration.includes("getBoundingClientRect")) {
+ if (scrollClickPointsRemaining > 0) {
+ scrollClickPointsRemaining -= 1;
+ return {
+ result: {
+ type: "object",
+ value: {
+ scroll: { x: 80, y: 300, deltaX: 0, deltaY: 600 },
+ },
+ },
+ };
+ }
if (
interceptedClickPointsRemaining > 0 &&
params.functionDeclaration.includes("elementFromPoint")
@@ -740,6 +753,7 @@ function createFixture(rootDir) {
},
now: () => nowMs,
sleep: async (ms) => {
+ sleepDurations.push(ms);
nowMs += ms;
},
};
@@ -749,6 +763,7 @@ function createFixture(rootDir) {
gate,
rootDir,
services,
+ sleepDurations,
snapshotOptions,
tabs,
addExternalTab(targetId, url, { active = false, ...details } = {}) {
@@ -801,6 +816,9 @@ function createFixture(rootDir) {
interceptClickPoints(count) {
interceptedClickPointsRemaining = count;
},
+ scrollNextClickPoint(count = 1) {
+ scrollClickPointsRemaining = count;
+ },
navigateOnNextClick(url) {
navigateOnNextClickUrl = url;
},
@@ -3298,16 +3316,32 @@ test("Page mouse.wheel scrolls the addressed page", async () => {
const first = await openTestPage(task, "https://example.test/first");
await openTestPage(task, "https://example.test/second");
+ const sleepCountBeforeWheel = fixture.sleepDurations.length;
await first.mouse.wheel(0, 450);
- const scrollCall = fixture.calls.find(
+ const scrollCalls = fixture.calls.filter(
([kind, method, params]) =>
kind === "cdp" &&
method === "Input.dispatchMouseEvent" &&
- params.type === "mouseWheel" &&
- params.deltaY === 450,
+ params.type === "mouseWheel",
+ );
+ assert(
+ scrollCalls.length > 1,
+ "a large wheel delta should be rendered as a short motion",
+ );
+ assert.equal(
+ scrollCalls.reduce((total, [, , params]) => total + params.deltaY, 0),
+ 450,
+ );
+ assert(
+ scrollCalls.every((call) => call[3] === `session:${first.targetId}`),
+ );
+ assert(
+ fixture.sleepDurations
+ .slice(sleepCountBeforeWheel)
+ .reduce((total, duration) => total + duration, 0) <= 100,
+ "the visual transition must stay short",
);
- assert.equal(scrollCall[3], `session:${first.targetId}`);
assert.equal(fixture.activeTarget(), first.targetId);
});
});
@@ -4448,25 +4482,97 @@ test("an unknown Page ref fails after one target-scoped refresh", async () => {
});
});
-test("Page click scrolls the element into view before computing its point", async () => {
+test("Page click uses the wheel motion engine to bring an element into view", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
const page = await openTestPage(task, "https://example.test/first");
+ fixture.scrollNextClickPoint();
await page.click("#offscreen");
- const pointCall = fixture.calls.find(
+ const pointCalls = fixture.calls.filter(
([kind, method, params]) =>
kind === "cdp" &&
method === "Runtime.callFunctionOn" &&
params.functionDeclaration.includes("getBoundingClientRect"),
);
- assert.match(pointCall[2].functionDeclaration, /scrollIntoView/);
+ assert(
+ pointCalls.length >= 2,
+ "the element position is rechecked after scrolling",
+ );
+ assert.doesNotMatch(pointCalls[0][2].functionDeclaration, /scrollIntoView/);
+ const stabilityCall = pointCalls.find(([, , params]) =>
+ params.functionDeclaration.includes("setTimeout(finish, 100)"),
+ );
+ assert(stabilityCall, "the final point check samples element stability");
assert.match(
- pointCall[2].functionDeclaration,
+ stabilityCall[2].functionDeclaration,
/setTimeout\(finish, 100\)/,
"stability sampling must not wait indefinitely for background animation frames",
);
+ const wheelCalls = fixture.calls.filter(
+ ([kind, method, params]) =>
+ kind === "cdp" &&
+ method === "Input.dispatchMouseEvent" &&
+ params.type === "mouseWheel",
+ );
+ assert(wheelCalls.length > 1);
+ assert.equal(
+ wheelCalls.reduce((total, [, , params]) => total + params.deltaY, 0),
+ 600,
+ );
+ const wheelEnd = fixture.calls.lastIndexOf(wheelCalls.at(-1));
+ const press = fixture.calls.findIndex(
+ ([kind, method, params]) =>
+ kind === "cdp" &&
+ method === "Input.dispatchMouseEvent" &&
+ params.type === "mousePressed",
+ );
+ assert(
+ wheelEnd < press,
+ "scrolling must finish before the click is dispatched",
+ );
+ });
+});
+
+test("Page fill uses the wheel motion engine to bring an element into view", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await openTestPage(task, "https://example.test/first");
+ fixture.scrollNextClickPoint();
+
+ await page.fill("#offscreen-field", "filled");
+
+ const pointCalls = fixture.calls.filter(
+ ([kind, method, params]) =>
+ kind === "cdp" &&
+ method === "Runtime.callFunctionOn" &&
+ params.functionDeclaration.includes("getBoundingClientRect"),
+ );
+ assert(
+ pointCalls.length >= 2,
+ "the field position is rechecked after scrolling",
+ );
+ assert.doesNotMatch(pointCalls[0][2].functionDeclaration, /scrollIntoView/);
+ const wheelCalls = fixture.calls.filter(
+ ([kind, method, params]) =>
+ kind === "cdp" &&
+ method === "Input.dispatchMouseEvent" &&
+ params.type === "mouseWheel",
+ );
+ assert(wheelCalls.length > 1);
+ assert.equal(
+ wheelCalls.reduce((total, [, , params]) => total + params.deltaY, 0),
+ 600,
+ );
+ const insertText = fixture.calls.findIndex(
+ ([kind, method]) => kind === "cdp" && method === "Input.insertText",
+ );
+ const wheelEnd = fixture.calls.lastIndexOf(wheelCalls.at(-1));
+ assert(
+ wheelEnd < insertText,
+ "scrolling must finish before text input is dispatched",
+ );
});
});
@@ -4482,7 +4588,7 @@ test("Page click retries a transient visibility change before dispatching input"
([kind, method, params]) =>
kind === "cdp" &&
method === "Runtime.callFunctionOn" &&
- params.functionDeclaration.includes("getBoundingClientRect"),
+ params.functionDeclaration.includes("setTimeout(finish, 100)"),
).length,
2,
);
diff --git a/package/ego-browser/src/public-api-schema.ts b/package/ego-browser/src/public-api-schema.ts
index fdb7943..a09faf2 100644
--- a/package/ego-browser/src/public-api-schema.ts
+++ b/package/ego-browser/src/public-api-schema.ts
@@ -550,7 +550,7 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [
name: "Page.mouse.wheel",
signature: "await page.mouse.wheel(deltaX, deltaY)",
summary:
- "Send a wheel event at the current Page position; move or click over the intended scroll container first in each process.",
+ "Perform a short wheel-input motion at the current Page position; move or click over the intended scroll container first in each process.",
},
{
name: "Page.keyboard.down",
diff --git a/skills/ego-browser/SKILL.md b/skills/ego-browser/SKILL.md
index ad223ac..c7ae5b3 100644
--- a/skills/ego-browser/SKILL.md
+++ b/skills/ego-browser/SKILL.md
@@ -206,6 +206,10 @@ When a selector identifies a wrapper, `focus()` and `press()` may use its
interactive ancestor or unique editable descendant; `fill()` and
`setInputFiles()` only continue to a unique compatible control.
+`click()`, `fill()`, `hover()`, and `dragAndDrop()` automatically bring their
+target into view with browser wheel input. Do not pre-scroll solely to make a
+DOM target actionable.
+
Snapshot node names are accessibility roles. Use a ref now or `loc=...` to find
the element again. After the page changes, take a new snapshot. When a useful
node has no ref, construct a selector from its role, text, or surrounding
@@ -238,8 +242,9 @@ console.log({ screenshot: path });
Inspect the screenshot with an image-viewing tool. Coordinates use CSS pixels;
keyboard names and `+`-separated chords follow Playwright syntax. Use
`ControlOrMeta` for portable shortcuts and verify the resulting page state.
-`mouse.wheel()` sends the event at the current mouse position. In each heredoc,
-move or click over the intended scrollable area before using it.
+`mouse.wheel()` performs a short wheel-input motion at the current mouse
+position and resolves when that motion completes. In each heredoc, move or
+click over the intended scrollable area before using it.
On macOS, `keyboard.paste()` sends the native paste shortcut and then restores
the user's clipboard. Pass `{ text, html }` when a rich editor needs structured
diff --git a/skills/ego-browser/references/api.md b/skills/ego-browser/references/api.md
index 7ac5ef3..3157370 100644
--- a/skills/ego-browser/references/api.md
+++ b/skills/ego-browser/references/api.md
@@ -80,13 +80,13 @@ Selectors accept refs, Ego locators, XPath, and raw CSS. A small compatibility s
## Page.mouse
-| API | Options | Purpose |
-| ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
-| `await page.mouse.click(x, y, { button?, clickCount?, delay? })` | `button` (left, middle, right) — Mouse button.<br>`clickCount` — Number of clicks.<br>`delay` — Input delay in milliseconds. | Click CSS-pixel coordinates with native CDP input. |
-| `await page.mouse.move(x, y, { steps? })` | `steps` — Number of movement steps. | Move the mouse to CSS-pixel coordinates. |
-| `await page.mouse.down({ button?, clickCount? })` | `button` (left, middle, right) — Mouse button.<br>`clickCount` — Click count reported to the page. | Press a mouse button at the current Page position. |
-| `await page.mouse.up({ button?, clickCount? })` | `button` (left, middle, right) — Mouse button.<br>`clickCount` — Click count reported to the page. | Release a mouse button at the current Page position. |
-| `await page.mouse.wheel(deltaX, deltaY)` | — | Send a wheel event at the current Page position; move or click over the intended scroll container first in each process. |
+| API | Options | Purpose |
+| ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
+| `await page.mouse.click(x, y, { button?, clickCount?, delay? })` | `button` (left, middle, right) — Mouse button.<br>`clickCount` — Number of clicks.<br>`delay` — Input delay in milliseconds. | Click CSS-pixel coordinates with native CDP input. |
+| `await page.mouse.move(x, y, { steps? })` | `steps` — Number of movement steps. | Move the mouse to CSS-pixel coordinates. |
+| `await page.mouse.down({ button?, clickCount? })` | `button` (left, middle, right) — Mouse button.<br>`clickCount` — Click count reported to the page. | Press a mouse button at the current Page position. |
+| `await page.mouse.up({ button?, clickCount? })` | `button` (left, middle, right) — Mouse button.<br>`clickCount` — Click count reported to the page. | Release a mouse button at the current Page position. |
+| `await page.mouse.wheel(deltaX, deltaY)` | — | Perform a short wheel-input motion at the current Page position; move or click over the intended scroll container first in each process. |
## Page.keyboard