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.

fix(ego-browser): fall back when wheel input cannot bring a target into view

Zhuowei Wangacce636c7a93
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
index 8683704..ba71913 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
@@ -20,6 +20,7 @@ import {
} from "./page-default-screenshot-path.mjs";
import { pageSnapshotLocatorCase } from "./page-snapshot-locators.mjs";
import { pageSnapshotViewportOverflowCase } from "./page-snapshot-viewport-overflow.mjs";
+import { pageWheelTrapCase } from "./page-wheel-trap.mjs";
import {
pageSnapshotIframeViewportCase,
pageSnapshotLazyIframeCase,
@@ -147,6 +148,7 @@ export const e2eCases = [
body: pageSnapshotIframeViewportCase,
},
{ name: "Page snapshot subtree", body: pageSnapshotSubtreeCase },
+ { name: "Page auto-scroll past a wheel trap", body: pageWheelTrapCase },
{
name: "Page snapshot viewport overflow hint",
body: pageSnapshotViewportOverflowCase,
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-wheel-trap.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-wheel-trap.mjs
new file mode 100644
index 0000000..a5046bc
--- /dev/null
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-wheel-trap.mjs
@@ -0,0 +1,51 @@
+export function pageWheelTrapCase() {
+ return `
+ const task = await taskSpace(taskName);
+ const page = await newPageAt(task, baseUrl + "/wheel-trap?trap=1");
+ const state = () =>
+ page.evaluate(() => ({
+ scrollY,
+ value: document.querySelector("#target").value,
+ wheelEvents: window.__wheelEvents,
+ }));
+
+ let startedAt = Date.now();
+ await page.fill("#target", "hello");
+ const trapped = await state();
+ const trappedMs = Date.now() - startedAt;
+ assertEqual(trapped.value, "hello", "fill reaches an input below a wheel trap");
+ assert(trapped.scrollY > 0, "the page scrolled past the wheel trap: " + JSON.stringify(trapped));
+ assert(trapped.wheelEvents > 0, "wheel input was tried first: " + JSON.stringify(trapped));
+ assert(trappedMs < 3000, "fill past a wheel trap finished within the default timeout: " + trappedMs + "ms");
+
+ await page.goto(baseUrl + "/wheel-trap?trap=0");
+ startedAt = Date.now();
+ await page.fill("#target", "plain");
+ const plain = await state();
+ assertEqual(plain.value, "plain", "fill still works on an ordinary page");
+ assert(plain.scrollY > 0 && plain.wheelEvents > 1, "an ordinary page scrolls with wheel input: " + JSON.stringify(plain));
+
+ // Each wheel event blocks the page for 400ms: the auto-scroll must respect
+ // the action deadline instead of finishing every queued motion, and the
+ // error must report the time the action really took.
+ await page.goto(baseUrl + "/wheel-trap?trap=1&slow=400");
+ startedAt = Date.now();
+ let failure;
+ try {
+ await page.fill("#target", "slow", { timeout: 1000 });
+ } catch (error) {
+ failure = error;
+ }
+ const slowMs = Date.now() - startedAt;
+ assert(failure, "a wheel trap with a slow handler fails within the deadline instead of hanging");
+ const reported = /timed out after (\\d+)ms/.exec(failure.message);
+ assert(reported, "the timeout error reports a duration: " + failure.message);
+ assert(
+ Math.abs(Number(reported[1]) - slowMs) < 500,
+ "the reported duration matches the real one: reported " + reported[1] + "ms, measured " + slowMs + "ms"
+ );
+ assert(slowMs < 3000, "the slow wheel trap does not run far past its 1000ms timeout: " + slowMs + "ms");
+
+ await page.close();
+ `;
+}
diff --git a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
index c088396..28f2d6f 100644
--- a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
@@ -381,6 +381,40 @@ export async function startFixtureServer(taskName) {
</html>`);
return;
}
+ if (url.pathname === "/wheel-trap") {
+ // Mirrors the CITRO-4275 repro: a block that swallows wheel events covers
+ // the bottom of the viewport, and the input sits below it. With
+ // ?slow=<ms> every wheel event also blocks the main thread for that long.
+ const trap = url.searchParams.get("trap") === "1";
+ const slowMs = Number(url.searchParams.get("slow") || 0);
+ res.writeHead(200, { "content-type": "text/html" });
+ res.end(`<!doctype html>
+ <html lang="en">
+ <head>
+ <meta charset="utf-8">
+ <title>wheel trap</title>
+ </head>
+ <body style="margin:0">
+ <div style="height:500px">top</div>
+ <div id="trap" style="height:800px;background:#ddd">wheel trap</div>
+ <input id="target" style="display:block;margin:200px 0 600px">
+ <script>
+ window.__wheelEvents = 0;
+ addEventListener("wheel", () => { window.__wheelEvents += 1; }, { capture: true });
+ const trap = ${trap};
+ const slowMs = ${slowMs};
+ if (trap || slowMs > 0) {
+ document.getElementById("trap").addEventListener("wheel", (event) => {
+ if (trap) event.preventDefault();
+ const until = performance.now() + slowMs;
+ while (performance.now() < until) {}
+ }, { passive: false });
+ }
+ </script>
+ </body>
+ </html>`);
+ return;
+ }
if (url.pathname === "/nav-target") {
res.writeHead(200, { "content-type": "text/html" });
res.end(pageHtml("nav-target"));
diff --git a/package/ego-browser/skill-body/SKILL.md b/package/ego-browser/skill-body/SKILL.md
index 2153e8f..04cf508 100644
--- a/package/ego-browser/skill-body/SKILL.md
+++ b/package/ego-browser/skill-body/SKILL.md
@@ -316,8 +316,9 @@ 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.
+target into view with browser wheel input, falling back to a programmatic
+scroll when the wheel does not move the target. 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
diff --git a/package/ego-browser/src/driver/page-actions.ts b/package/ego-browser/src/driver/page-actions.ts
index c05351f..7fbf437 100644
--- a/package/ego-browser/src/driver/page-actions.ts
+++ b/package/ego-browser/src/driver/page-actions.ts
@@ -23,6 +23,9 @@ type PageActionServices = {
showAgentTaskState(state: string): Promise<void>;
sleep(ms: number): Promise<void>;
platform?: string;
+ now?(): number;
+ /** Absolute `now()` time at which the current action gives up. */
+ actionDeadline?: number;
};
export type MouseButton = "left" | "middle" | "right";
@@ -1426,39 +1429,24 @@ async function resolveElementPoint(
iframeSessions,
);
}
- 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 point = await bringIntoView(services, sessionId, objectId, {
+ actionName,
+ subject: "element",
+ evaluate: async () => {
+ const response = await services.cdp(
+ "Runtime.callFunctionOn",
+ {
+ functionDeclaration: expression,
+ objectId,
+ arguments: position ? [{ value: position }] : [],
+ returnByValue: true,
+ awaitPromise: true,
+ },
+ sessionId,
);
- }
- 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",
- );
- }
+ return runtimeValue(response, expression);
+ },
+ wheel: async (scroll) => {
const pageScrollPoint = await pagePointForFrame(
services,
sessionId,
@@ -1466,36 +1454,130 @@ async function resolveElementPoint(
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,
- },
+ return dispatchWheelMotion(wheelMotionServices(services, sessionId), {
+ x: pageScrollPoint.x,
+ y: pageScrollPoint.y,
+ deltaX: scroll.deltaX,
+ deltaY: scroll.deltaY,
+ });
+ },
+ });
+ 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 };
+}
+
+type WheelRequest = { x: number; y: number; deltaX: number; deltaY: number };
+
+function wheelMotionServices(services: PageActionServices, sessionId: string) {
+ return {
+ dispatch: (params: Record<string, unknown>) =>
+ dispatchMouseEvent(services, sessionId, params),
+ sleep: services.sleep,
+ exhausted: () => actionDeadlinePassed(services),
+ };
+}
+
+function actionDeadlinePassed(services: PageActionServices): boolean {
+ return (
+ services.actionDeadline !== undefined &&
+ services.now !== undefined &&
+ services.now() >= services.actionDeadline
+ );
+}
+
+function sameWheelRequest(a: WheelRequest, b: WheelRequest): boolean {
+ return (
+ Math.abs(a.x - b.x) < 1 &&
+ Math.abs(a.y - b.y) < 1 &&
+ Math.abs(a.deltaX - b.deltaX) < 1 &&
+ Math.abs(a.deltaY - b.deltaY) < 1
+ );
+}
+
+/**
+ * Re-evaluate a target until it reports a position instead of a scroll
+ * request, scrolling with browser wheel input in between.
+ *
+ * Wheel input is the primary path because it is trusted input that reaches
+ * the nearest scrollable container like a user's wheel would. It can fail
+ * silently: the wheel point may land on an element that calls
+ * `preventDefault()` on wheel events (maps, carousels, canvas editors), or
+ * the page may be at the end of its scroll range. When a motion leaves the
+ * target exactly where it was, the next request is identical, and the loop
+ * falls back once to `DOM.scrollIntoViewIfNeeded` (which bypasses a site's
+ * patched `Element.prototype.scrollIntoView`) instead of repeating a motion
+ * that already proved ineffective. The action deadline is checked before
+ * every motion and inside it so a slow wheel handler cannot run the action
+ * far past its timeout.
+ */
+async function bringIntoView<
+ T extends { error?: unknown; scroll?: WheelRequest | null },
+>(
+ services: PageActionServices,
+ sessionId: string,
+ objectId: string,
+ input: {
+ actionName: string;
+ subject: "element" | "iframe";
+ evaluate: () => Promise<T>;
+ wheel: (scroll: WheelRequest) => Promise<boolean>;
+ },
+): Promise<T> {
+ const notVisible = () =>
+ new ElementResolutionError(
+ `${input.actionName} failed: ${input.subject} is not visible in the viewport`,
+ "transient",
+ );
+ let previous: WheelRequest | undefined;
+ let fellBack = false;
+ for (let attempt = 0; attempt <= AUTO_SCROLL_ATTEMPTS; attempt += 1) {
+ const result = await input.evaluate();
+ if (typeof result?.error === "string") {
+ throw new ElementResolutionError(
+ `${input.actionName} failed: ${result.error}`,
+ "transient",
);
- continue;
}
- if (!Number.isFinite(point?.x) || !Number.isFinite(point?.y)) {
- throw new Error(`${actionName} could not resolve the element position`);
+ const scroll = result?.scroll;
+ if (!scroll) return result;
+ if (
+ attempt === AUTO_SCROLL_ATTEMPTS ||
+ !Number.isFinite(scroll.x) ||
+ !Number.isFinite(scroll.y) ||
+ !Number.isFinite(scroll.deltaX) ||
+ !Number.isFinite(scroll.deltaY) ||
+ actionDeadlinePassed(services)
+ ) {
+ throw notVisible();
}
- const pagePoint = await pagePointForFrame(
- services,
- sessionId,
- frameId,
- point,
- pageSessionId,
- );
- return { ...pagePoint, local: point };
+ if (previous && sameWheelRequest(previous, scroll)) {
+ if (fellBack) throw notVisible();
+ fellBack = true;
+ previous = undefined;
+ try {
+ await services.cdp(
+ "DOM.scrollIntoViewIfNeeded",
+ { objectId },
+ sessionId,
+ );
+ } catch {
+ throw notVisible();
+ }
+ continue;
+ }
+ previous = scroll;
+ if (!(await input.wheel(scroll))) throw notVisible();
}
- throw new ElementResolutionError(
- `${actionName} failed: element is not visible in the viewport`,
- "transient",
- );
+ throw notVisible();
}
async function ensureFrameOwnerInView(
@@ -1563,47 +1645,28 @@ async function ensureFrameOwnerInView(
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,
- },
- ownerSessionId,
- );
- 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 bringIntoView(services, ownerSessionId, objectId, {
+ actionName,
+ subject: "iframe",
+ evaluate: async () => {
+ const response = await services.cdp(
+ "Runtime.callFunctionOn",
+ {
+ functionDeclaration: source,
+ objectId,
+ returnByValue: true,
+ awaitPromise: false,
+ },
+ ownerSessionId,
);
- }
- await dispatchWheelMotion(
- {
- dispatch: (params) =>
- dispatchMouseEvent(services, ownerSessionId, params),
- sleep: services.sleep,
- },
- scroll,
- );
- }
+ return runtimeValue(response, source);
+ },
+ wheel: (scroll) =>
+ dispatchWheelMotion(
+ wheelMotionServices(services, ownerSessionId),
+ scroll,
+ ),
+ });
} finally {
await releaseObject(services, ownerSessionId, objectId);
}
diff --git a/package/ego-browser/src/driver/scroll-motion.test.mjs b/package/ego-browser/src/driver/scroll-motion.test.mjs
index e0a2f0e..de410dd 100644
--- a/package/ego-browser/src/driver/scroll-motion.test.mjs
+++ b/package/ego-browser/src/driver/scroll-motion.test.mjs
@@ -80,3 +80,40 @@ test("dispatchWheelMotion keeps small wheel actions immediate", async () => {
assert.equal(events[0].deltaY, 100);
assert.deepEqual(sleeps, []);
});
+
+test("dispatchWheelMotion stops before the next event once the budget is exhausted", async () => {
+ const events = [];
+ let dispatched = 0;
+
+ const completed = await dispatchWheelMotion(
+ {
+ async dispatch(event) {
+ events.push(event);
+ dispatched += 1;
+ },
+ async sleep() {},
+ exhausted: () => dispatched >= 2,
+ },
+ { x: 0, y: 0, deltaX: 0, deltaY: 960 },
+ );
+
+ assert.equal(completed, false);
+ assert.equal(events.length, 2);
+ assert(
+ events.reduce((total, event) => total + event.deltaY, 0) < 960,
+ "a cut motion does not flush the remaining delta",
+ );
+
+ assert.equal(
+ await dispatchWheelMotion(
+ {
+ async dispatch() {},
+ async sleep() {},
+ exhausted: () => true,
+ },
+ { x: 0, y: 0, deltaX: 0, deltaY: 100 },
+ ),
+ true,
+ "a single-event motion still dispatches its one event",
+ );
+});
diff --git a/package/ego-browser/src/driver/scroll-motion.ts b/package/ego-browser/src/driver/scroll-motion.ts
index 2ed5c3b..49d5691 100644
--- a/package/ego-browser/src/driver/scroll-motion.ts
+++ b/package/ego-browser/src/driver/scroll-motion.ts
@@ -9,6 +9,8 @@ type WheelMotion = {
type WheelMotionServices = {
dispatch(params: Record<string, unknown>): Promise<void>;
sleep(ms: number): Promise<void>;
+ /** Stop before the next wheel event once this returns true. */
+ exhausted?(): boolean;
};
const SINGLE_EVENT_DISTANCE = 120;
@@ -20,11 +22,16 @@ 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.
+ *
+ * Returns false when `exhausted()` cut the motion short. A page that handles
+ * each wheel event slowly (a map that zooms on wheel, a busy main thread) can
+ * make one motion take far longer than the action's deadline, so the caller's
+ * budget is checked before every event rather than only between motions.
*/
export async function dispatchWheelMotion(
services: WheelMotionServices,
motion: WheelMotion,
-): Promise<void> {
+): Promise<boolean> {
const distance = Math.max(Math.abs(motion.deltaX), Math.abs(motion.deltaY));
const steps =
distance <= SINGLE_EVENT_DISTANCE
@@ -34,6 +41,7 @@ export async function dispatchWheelMotion(
let emittedY = 0;
for (let step = 1; step <= steps; step += 1) {
+ if (step > 1 && services.exhausted?.()) return false;
const progress = step / steps;
const eased = progress * progress * (3 - 2 * progress);
const cumulativeX = step === steps ? motion.deltaX : motion.deltaX * eased;
@@ -53,4 +61,5 @@ export async function dispatchWheelMotion(
});
if (step < steps) await services.sleep(STEP_INTERVAL_MS);
}
+ return true;
}
diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjs
index 09bc6f0..3ed5041 100644
--- a/package/ego-browser/src/page-model.test.mjs
+++ b/package/ego-browser/src/page-model.test.mjs
@@ -53,6 +53,8 @@ function createFixture(rootDir) {
let rejectedClickPointsRemaining = 0;
let interceptedClickPointsRemaining = 0;
let scrollClickPointsRemaining = 0;
+ let trapClickPoints = false;
+ let wheelDispatchDurationMs = 0;
let fillElementKind = "input";
let fillText = "";
let fillTransform = null;
@@ -505,6 +507,19 @@ function createFixture(rootDir) {
};
}
if (params.functionDeclaration.includes("getBoundingClientRect")) {
+ if (trapClickPoints) {
+ // The wheel point sits on an element that swallows wheel events:
+ // the target never moves, so every evaluation asks for the same
+ // scroll until a programmatic scroll finally brings it in.
+ return {
+ result: {
+ type: "object",
+ value: {
+ scroll: { x: 80, y: 599, deltaX: 0, deltaY: 900 },
+ },
+ },
+ };
+ }
if (scrollClickPointsRemaining > 0) {
scrollClickPointsRemaining -= 1;
return {
@@ -620,7 +635,12 @@ function createFixture(rootDir) {
if (method === "Browser.getVersion") {
return { product: "Ego Lite/Test" };
}
+ if (method === "DOM.scrollIntoViewIfNeeded") {
+ trapClickPoints = false;
+ return {};
+ }
if (method === "Input.dispatchMouseEvent") {
+ if (params.type === "mouseWheel") nowMs += wheelDispatchDurationMs;
if (timeoutNextMouseDispatch) {
timeoutNextMouseDispatch = false;
throw new Error("CDP request timed out: Input.dispatchMouseEvent");
@@ -863,6 +883,12 @@ function createFixture(rootDir) {
scrollNextClickPoint(count = 1) {
scrollClickPointsRemaining = count;
},
+ trapClickPoints() {
+ trapClickPoints = true;
+ },
+ setWheelDispatchDuration(ms) {
+ wheelDispatchDurationMs = ms;
+ },
navigateOnNextClick(url) {
navigateOnNextClickUrl = url;
},
@@ -5802,6 +5828,137 @@ test("Page fill uses the wheel motion engine to bring an element into view", asy
});
});
+test("Page fill falls back to a programmatic scroll when wheel input does not move the target", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await openTestPage(task, "https://example.test/map");
+ fixture.trapClickPoints();
+
+ await page.fill("#below-the-map", "hello");
+
+ const wheelCalls = fixture.calls.filter(
+ ([kind, method, params]) =>
+ kind === "cdp" &&
+ method === "Input.dispatchMouseEvent" &&
+ params.type === "mouseWheel",
+ );
+ assert(wheelCalls.length > 1, "wheel input is still tried first");
+ assert(
+ wheelCalls.length <= 12,
+ `one ineffective motion must not be repeated: ${wheelCalls.length} wheel events`,
+ );
+ const fallbackIndex = fixture.calls.findIndex(
+ ([kind, method, params, session]) =>
+ kind === "cdp" &&
+ method === "DOM.scrollIntoViewIfNeeded" &&
+ params.objectId === `element:${page.targetId}` &&
+ session === `session:${page.targetId}`,
+ );
+ assert(
+ fallbackIndex > 0,
+ "a stalled motion falls back to DOM.scrollIntoViewIfNeeded",
+ );
+ assert(
+ fallbackIndex > fixture.calls.lastIndexOf(wheelCalls.at(-1)),
+ "the fallback runs after the wheel motion proved ineffective",
+ );
+ assert(
+ fixture.calls.findIndex(
+ ([kind, method]) => kind === "cdp" && method === "Input.insertText",
+ ) > fallbackIndex,
+ "text input waits for the fallback scroll",
+ );
+ });
+});
+
+test("Page click gives up when neither wheel input nor the fallback scroll moves the target", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await openTestPage(task, "https://example.test/map");
+ fixture.trapClickPoints();
+ const task2 = taskForRound(fixture, "round-a", {
+ async cdp(method, params, sessionId, timeoutMs) {
+ const result = await fixture.services.cdp(
+ method,
+ params,
+ sessionId,
+ timeoutMs,
+ );
+ // The programmatic scroll is accepted but changes nothing either.
+ if (method === "DOM.scrollIntoViewIfNeeded") fixture.trapClickPoints();
+ return result;
+ },
+ });
+ const stuck = task2.page(page.label);
+
+ await assert.rejects(
+ () => stuck.click("#below-the-map", { timeout: 1_000 }),
+ /page\.click timed out after \d+ms: page\.click failed: element is not visible in the viewport/,
+ );
+ // A motion is a run of consecutive wheel events.
+ let wheelMotions = 0;
+ let inMotion = false;
+ for (const [kind, method, params] of fixture.calls) {
+ const wheel =
+ kind === "cdp" &&
+ method === "Input.dispatchMouseEvent" &&
+ params.type === "mouseWheel";
+ if (wheel && !inMotion) wheelMotions += 1;
+ inMotion = wheel;
+ }
+ const fallbacks = fixture.calls.filter(
+ ([kind, method]) =>
+ kind === "cdp" && method === "DOM.scrollIntoViewIfNeeded",
+ ).length;
+ assert(fallbacks >= 1, "the fallback scroll was attempted");
+ assert(
+ wheelMotions <= fallbacks * 2,
+ `each retry tries at most one wheel motion before and after the fallback: ${wheelMotions} motions, ${fallbacks} fallbacks`,
+ );
+ });
+});
+
+test("Page fill stops auto-scrolling at the action deadline and reports the real duration", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await openTestPage(task, "https://example.test/map");
+ fixture.trapClickPoints();
+ // A map that zooms on every wheel event keeps the renderer busy, so each
+ // dispatched wheel event takes about two seconds to be acknowledged.
+ fixture.setWheelDispatchDuration(2_000);
+ const startedAt = fixture.services.now();
+
+ await assert.rejects(
+ () => page.fill("#below-the-map", "hello", { timeout: 3_000 }),
+ (error) => {
+ const elapsed = fixture.services.now() - startedAt;
+ const reported = Number(
+ /page\.fill timed out after (\d+)ms: /.exec(error.message)?.[1],
+ );
+ assert(
+ reported > 3_000 && reported <= elapsed,
+ `the timeout message reports the real duration, not the configured 3000ms: ${error.message} (elapsed ${elapsed}ms)`,
+ );
+ assert(
+ elapsed < 6_000,
+ `the action overran its 3000ms budget by ${elapsed - 3_000}ms`,
+ );
+ return true;
+ },
+ );
+ const wheelCalls = fixture.calls.filter(
+ ([kind, method, params]) =>
+ kind === "cdp" &&
+ method === "Input.dispatchMouseEvent" &&
+ params.type === "mouseWheel",
+ );
+ assert(
+ wheelCalls.length <= 3,
+ `the motion stops at the deadline instead of finishing: ${wheelCalls.length} wheel events`,
+ );
+ });
+});
+
test("Page click retries a transient visibility change before dispatching input", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.ts
index ccdc589..c013a4d 100644
--- a/package/ego-browser/src/page-model.ts
+++ b/package/ego-browser/src/page-model.ts
@@ -394,6 +394,8 @@ type PageModelServices = {
options: { timeoutMs: number },
): DownloadInterception;
now(): number;
+ /** Absolute `now()` time at which the running element action gives up. */
+ actionDeadline?: number;
sleep(ms: number): Promise<void>;
platform: string;
pageBudget: number;
@@ -2638,11 +2640,18 @@ class Page {
return { refMap, iframeSessions };
}
- /** Services whose CDP transport reports the first `Input.*` command. */
- #inputTrackingServices(onInput: () => void): PageModelServices {
+ /**
+ * Services whose CDP transport reports the first `Input.*` command and
+ * which carry the action deadline into the driver's scroll loops.
+ */
+ #inputTrackingServices(
+ deadline: number,
+ onInput: () => void,
+ ): PageModelServices {
const services = this.#services;
return {
...services,
+ actionDeadline: deadline,
cdp(method, params, sessionId, timeoutMs) {
if (method.startsWith("Input.")) onInput();
return services.cdp(method, params, sessionId, timeoutMs);
@@ -2667,11 +2676,12 @@ class Page {
services: PageModelServices,
) => Promise<Result>,
): Promise<Result> {
- const deadline = this.#services.now() + timeoutMs;
+ const startedAt = this.#services.now();
+ const deadline = startedAt + timeoutMs;
let lastBlocker: Error | undefined;
while (true) {
let inputDispatched = false;
- const services = this.#inputTrackingServices(() => {
+ const services = this.#inputTrackingServices(deadline, () => {
inputDispatched = true;
});
try {
@@ -2692,8 +2702,11 @@ class Page {
if (!retryable && !exhausted) throw error;
if (remainingMs <= 0) {
const blocker = exhausted && lastBlocker ? lastBlocker : error;
+ // Report the time the action really took: a slow page can overrun
+ // the configured timeout, and the configured value is the caller's.
+ const elapsedMs = this.#services.now() - startedAt;
throw new ElementResolutionError(
- `${actionName} timed out after ${timeoutMs}ms: ${blocker.message}`,
+ `${actionName} timed out after ${elapsedMs}ms: ${blocker.message}`,
"transient",
);
}