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): stop v1 click dispatching outside the viewport

Joway@MacMinifddd70962b06
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/pointer.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/pointer.mjs
index 66bf98e..743b5d7 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/pointer.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/pointer.mjs
@@ -247,5 +247,32 @@ export function pointerCase() {
await waitForJsValue("window.__fixtureState.checkboxChecked", true, "first click checks the checkbox");
await click("#checkbox");
await waitForJsValue("window.__fixtureState.checkboxChecked", false, "second click unchecks the checkbox");
+
+ /* element point outside the viewport: scroll to it, or report it */
+ cliLog(JSON.stringify({ pointerStep: "click below fold" }));
+ const belowFold = await gotoAndWait(baseUrl + "/click-below-fold", { timeout: 10 });
+ assert(belowFold.loaded, "below-fold fixture loaded");
+ await click("#partial");
+ await waitForJsValue("window.__clicked.join()", "partial", "click reaches a button whose center is below the fold");
+ await click("#far");
+ await waitForJsValue("window.__clicked.join()", "partial,far", "click scrolls to a button far below the fold");
+ await js("window.scrollTo({ top: 0, behavior: 'instant' }); return true;");
+ await click("loc=css:#far");
+ await waitForJsValue("window.__clicked.join()", "partial,far,far", "click scrolls a locator target into view");
+ await assertRejects(
+ () => click("#unreachable"),
+ "not visible in the viewport",
+ "click reports an element it cannot bring into the viewport"
+ );
+ await assertRejects(
+ () => click("loc=css:#unreachable"),
+ "not visible in the viewport",
+ "click reports an unreachable locator target"
+ );
+ assertEqual(
+ await js("return window.__clicked.join()"),
+ "partial,far,far",
+ "a rejected click dispatches nothing"
+ );
`;
}
diff --git a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
index 88c8baf..3a8c857 100644
--- a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
@@ -390,6 +390,40 @@ export async function startFixtureServer(taskName) {
</html>`);
return;
}
+ if (url.pathname === "/click-below-fold") {
+ // Mirrors the CITRO-3536 repro: #partial shows its top edge above the
+ // fold while its center sits below it.
+ res.writeHead(200, { "content-type": "text/html" });
+ res.end(`<!doctype html>
+ <html lang="en">
+ <head>
+ <meta charset="utf-8">
+ <title>click below fold</title>
+ <style>
+ html { scroll-behavior: smooth; }
+ body { margin: 0; font: 16px sans-serif; }
+ button { display: block; height: 40px; }
+ #spacer { height: calc(100vh - 12px); }
+ #gap { height: 3000px; }
+ #unreachable { position: fixed; top: -200px; }
+ </style>
+ </head>
+ <body>
+ <div id="spacer"></div>
+ <button id="partial">Partial</button>
+ <div id="gap"></div>
+ <button id="far">Far</button>
+ <button id="unreachable">Unreachable</button>
+ <script>
+ window.__clicked = [];
+ for (const button of document.querySelectorAll("button")) {
+ button.addEventListener("click", () => window.__clicked.push(button.id));
+ }
+ </script>
+ </body>
+ </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
diff --git a/package/ego-browser/src/driver/action-target.ts b/package/ego-browser/src/driver/action-target.ts
index 0c1f3e9..04da26f 100644
--- a/package/ego-browser/src/driver/action-target.ts
+++ b/package/ego-browser/src/driver/action-target.ts
@@ -244,6 +244,37 @@ export const SCROLL_TARGET_HELPERS = `
${SCROLL_TARGET_FUNCTIONS}
`;
+/**
+ * Browser-side point for the v1 `click()` helper. A point already inside the
+ * viewport is kept. Otherwise the element is scrolled to the viewport center;
+ * if it cannot get there (fixed position, end of the scroll range), a click
+ * without a caller-chosen offset settles for its visible part. A point that is
+ * still outside is reported, because input dispatched there hits nothing.
+ */
+export const CLICK_POINT_HELPERS = `
+ ${SCROLL_TARGET_HELPERS}
+ function clickPointForElement(element, offset) {
+ const view = element.ownerDocument.defaultView;
+ const inViewport = (point) =>
+ point.x >= 0 && point.y >= 0 &&
+ point.x < view.innerWidth && point.y < view.innerHeight;
+ const elementPoint = () => {
+ const rect = element.getBoundingClientRect();
+ return offset
+ ? { x: rect.x + offset.x, y: rect.y + offset.y }
+ : { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
+ };
+ let point = elementPoint();
+ if (inViewport(point)) return point;
+ element.scrollIntoView({ block: "center", inline: "center", behavior: "instant" });
+ point = elementPoint();
+ if (inViewport(point)) return point;
+ const visible = offset ? null : actionPointForElement(element);
+ if (visible && inViewport(visible)) return visible;
+ return { error: "element is not visible in the viewport" };
+ }
+`;
+
/**
* Scroll targeting plus the enabled check, for a forced click that skips the
* hit test but still refuses a disabled element.
diff --git a/package/ego-browser/src/driver/pointer.test.mjs b/package/ego-browser/src/driver/pointer.test.mjs
index 8546b83..b449ea1 100644
--- a/package/ego-browser/src/driver/pointer.test.mjs
+++ b/package/ego-browser/src/driver/pointer.test.mjs
@@ -165,6 +165,213 @@ test("scroll propagates user-control errors from wheel dispatch", async () => {
}
});
+/**
+ * A one-element page that runs the real page-side expressions. `rect` is where
+ * the element starts; `scrollable: false` models content that cannot move, such
+ * as a fixed element, and otherwise scrollIntoView centers it in the viewport.
+ */
+function fakePage({ rect, scrollable = true }) {
+ const view = { innerWidth: 800, innerHeight: 600 };
+ const current = { ...rect };
+ const scrolls = [];
+ const domRect = () => ({
+ x: current.left,
+ y: current.top,
+ left: current.left,
+ top: current.top,
+ width: current.width,
+ height: current.height,
+ right: current.left + current.width,
+ bottom: current.top + current.height,
+ });
+ const element = {
+ ownerDocument: { defaultView: view },
+ getBoundingClientRect: domRect,
+ getClientRects: () => [domRect()],
+ scrollIntoView(options) {
+ scrolls.push(options);
+ if (!scrollable) return;
+ current.top = (view.innerHeight - current.height) / 2;
+ current.left = (view.innerWidth - current.width) / 2;
+ },
+ };
+ const document = {
+ querySelectorAll: (selector) => (selector === "*" ? [] : [element]),
+ elementFromPoint: () => element,
+ addEventListener() {},
+ removeEventListener() {},
+ };
+ const run = (source, ...args) =>
+ new Function(
+ "document",
+ "window",
+ "innerWidth",
+ "innerHeight",
+ "setTimeout",
+ "clearTimeout",
+ "__args",
+ `return (${source});`,
+ )(
+ document,
+ view,
+ view.innerWidth,
+ view.innerHeight,
+ () => 0,
+ () => {},
+ args,
+ );
+ const calls = [];
+ const restore = setOverrides({
+ cdpOverride(method, params) {
+ calls.push({ method, params });
+ if (method === "Runtime.evaluate") {
+ if (params.objectGroup === "ego-browser") {
+ return { result: { objectId: "object-1" } };
+ }
+ return { result: { value: run(params.expression) } };
+ }
+ if (method === "Runtime.callFunctionOn") {
+ const args = params.arguments.map((arg) => arg.value);
+ const value = new Function(
+ "__fn",
+ "__args",
+ "return __fn.apply(this, __args);",
+ ).call(element, run(params.functionDeclaration), args);
+ return { result: { value } };
+ }
+ return {};
+ },
+ });
+ return { calls, restore, scrolls };
+}
+
+function dispatchedPoints(calls) {
+ return calls
+ .filter((call) => call.method === "Input.dispatchMouseEvent")
+ .map((call) => [call.params.x, call.params.y]);
+}
+
+const CENTER_BELOW_FOLD = { left: 100, top: 590, width: 100, height: 40 };
+const FULLY_BELOW_FOLD = { left: 100, top: 2000, width: 100, height: 40 };
+const CENTERED_POINT = [400, 300];
+
+for (const [name, target] of [
+ ["a CSS selector", "#target"],
+ ["a loc=css locator", "loc=css:#target"],
+ ["a selector object", { selector: "#target" }],
+]) {
+ test(`click scrolls ${name} into view when its center is below the fold`, async () => {
+ const { calls, restore, scrolls } = fakePage({ rect: CENTER_BELOW_FOLD });
+ try {
+ await withFakeEgo(() => click(target));
+ } finally {
+ restore();
+ }
+ assert.equal(scrolls.length, 1);
+ assert.deepEqual(dispatchedPoints(calls), [
+ CENTERED_POINT,
+ CENTERED_POINT,
+ CENTERED_POINT,
+ ]);
+ });
+}
+
+test("click on a CSS selector scrolls and probes in its one resolving page call", async () => {
+ const { calls, restore, scrolls } = fakePage({ rect: FULLY_BELOW_FOLD });
+ try {
+ await withFakeEgo(() => click("#target"));
+ } finally {
+ restore();
+ }
+ assert.deepEqual(scrolls, [
+ { block: "center", inline: "center", behavior: "instant" },
+ ]);
+ assert.deepEqual(methodSequence(calls), [
+ "Runtime.evaluate",
+ "Input.dispatchMouseEvent:mouseMoved",
+ "Input.dispatchMouseEvent:mousePressed",
+ "Input.dispatchMouseEvent:mouseReleased",
+ ]);
+});
+
+test("click leaves an element whose center is in the viewport where it is", async () => {
+ const { calls, restore, scrolls } = fakePage({
+ rect: { left: 100, top: 570, width: 100, height: 40 },
+ });
+ try {
+ await withFakeEgo(() => click("#target"));
+ } finally {
+ restore();
+ }
+ assert.deepEqual(scrolls, []);
+ assert.deepEqual(dispatchedPoints(calls)[0], [150, 590]);
+});
+
+test("click uses the visible part of an element that cannot scroll to its center", async () => {
+ for (const target of ["#target", "loc=css:#target"]) {
+ const { calls, restore } = fakePage({
+ rect: CENTER_BELOW_FOLD,
+ scrollable: false,
+ });
+ try {
+ await withFakeEgo(() => click(target));
+ } finally {
+ restore();
+ }
+ assert.deepEqual(dispatchedPoints(calls)[0], [150, 595], String(target));
+ }
+});
+
+test("click reports an element it cannot bring into the viewport instead of succeeding", async () => {
+ for (const target of [
+ "#target",
+ "loc=css:#target",
+ { selector: "#target", x: 4, y: 4 },
+ ]) {
+ const { calls, restore } = fakePage({
+ rect: FULLY_BELOW_FOLD,
+ scrollable: false,
+ });
+ try {
+ await assert.rejects(
+ () => withFakeEgo(() => click(target)),
+ (error) => {
+ assert.equal(error.name, "ElementResolutionError");
+ assert.equal(error.kind, "transient");
+ assert.match(error.message, /not visible in the viewport/);
+ return true;
+ },
+ );
+ } finally {
+ restore();
+ }
+ assert.deepEqual(dispatchedPoints(calls), [], JSON.stringify(target));
+ }
+});
+
+test("click scrolls a selector-relative point back into the viewport", async () => {
+ const { calls, restore, scrolls } = fakePage({ rect: FULLY_BELOW_FOLD });
+ try {
+ await withFakeEgo(() => click({ selector: "#target", x: 4, y: 6 }));
+ } finally {
+ restore();
+ }
+ assert.equal(scrolls.length, 1);
+ // Centered element: left 350, top 280, plus the caller's offset.
+ assert.deepEqual(dispatchedPoints(calls)[0], [354, 286]);
+});
+
+test("click does not second-guess explicit coordinates", async () => {
+ const { calls, restore, scrolls } = fakePage({ rect: CENTER_BELOW_FOLD });
+ try {
+ await withFakeEgo(() => click([30, 900]));
+ } finally {
+ restore();
+ }
+ assert.deepEqual(scrolls, []);
+ assert.deepEqual(dispatchedPoints(calls)[0], [30, 900]);
+});
+
function withFakeEgo(run) {
const originalEgo = globalThis.ego;
globalThis.ego = { sendCDPMessage: () => {} };
@@ -201,7 +408,7 @@ function clickOverride({ inputTimesOut = false, probeResult } = {}) {
// finishClickProbe
return { result: { value: probeResult } };
}
- // Resolution (buildSelectorCenterJs) plus the probe install
+ // Resolution (clickPointForElement) plus the probe install
return { result: { value: { x: 100, y: 200 } } };
}
if (method === "Input.dispatchMouseEvent" && inputTimesOut) {
@@ -370,6 +577,7 @@ test("click falls back to the shared resolver when the fast path finds no elemen
"Runtime.evaluate",
"Runtime.evaluate",
"Runtime.evaluate",
+ "Runtime.evaluate",
"Input.dispatchMouseEvent:mouseMoved",
"Input.dispatchMouseEvent:mousePressed",
"Input.dispatchMouseEvent:mouseReleased",
@@ -383,10 +591,15 @@ test("click falls back to the shared resolver when the fast path finds no elemen
false,
"the shared resolver evaluates the selector without a probe",
);
- assert(isProbeExpression(calls[2]), "the probe is installed before input");
- assert.match(calls[2].params.expression, /\{"x":70,"y":80\}/);
+ assert.match(
+ calls[2].params.expression,
+ /70 >= 0 && 80 >= 0/,
+ "the resolved point is checked against the viewport",
+ );
+ assert(isProbeExpression(calls[3]), "the probe is installed before input");
+ assert.match(calls[3].params.expression, /\{"x":70,"y":80\}/);
assert.deepEqual(
- calls.slice(3).map((call) => [call.params.x, call.params.y]),
+ calls.slice(4).map((call) => [call.params.x, call.params.y]),
[
[70, 80],
[70, 80],
diff --git a/package/ego-browser/src/driver/pointer.ts b/package/ego-browser/src/driver/pointer.ts
index dac0d3f..2f5a740 100644
--- a/package/ego-browser/src/driver/pointer.ts
+++ b/package/ego-browser/src/driver/pointer.ts
@@ -1,6 +1,11 @@
import { cdp, js } from "../cdp-eval.js";
import { browserCdp } from "../browser-runtime.js";
-import { buildSelectorCenterJs, isRawSelector } from "../element-resolver.js";
+import {
+ buildFindElementJs,
+ ElementResolutionError,
+ isRawSelector,
+} from "../element-resolver.js";
+import { CLICK_POINT_HELPERS } from "./action-target.js";
import { elementCenter } from "./observe.js";
import { resolveAndCall } from "./element-ops.js";
@@ -88,7 +93,9 @@ type ClickTarget = Point & { probeId: string | null };
*/
/**
- * Click a mouse target.
+ * Click a mouse target. An element target whose point is outside the viewport
+ * is scrolled into view first, and the click rejects if it still cannot be
+ * reached. Explicit viewport coordinates are dispatched as given.
* @param {MouseTarget} target CSS selector, @ref, viewport point, or selector-relative point.
* @param {{button?: "left"|"middle"|"right", clickCount?: number, clicks?: number, label?: string}} [options]
* @returns {Promise<void>}
@@ -250,20 +257,79 @@ async function resolveClickTarget(target: MouseTarget): Promise<ClickTarget> {
const point = await resolveRawSelectorClickTarget(target);
if (point) return point;
}
- const point = await resolveMouseTarget(target);
+ const point = await resolveElementClickPoint(target);
return { ...point, probeId: await installClickProbe(point) };
}
+/**
+ * Resolve a click point on the shared resolver path, bringing an element target
+ * into the viewport when its point falls outside. Explicit coordinates are the
+ * caller's own decision and pass through unchanged.
+ */
+async function resolveElementClickPoint(target: MouseTarget): Promise<Point> {
+ const point = await resolveMouseTarget(target);
+ const selector =
+ typeof target === "string"
+ ? target
+ : target && typeof target === "object" && "selector" in target
+ ? target.selector
+ : "";
+ if (!selector || (await pointInViewport(point))) return point;
+ const offset =
+ typeof target === "object" &&
+ "selector" in target &&
+ (target.x !== undefined || target.y !== undefined)
+ ? { x: numberValue(target.x), y: numberValue(target.y) }
+ : null;
+ const { result, sessionId } = await resolveAndCall(
+ selector,
+ `function(offset){${CLICK_POINT_HELPERS}
+ return clickPointForElement(this, offset);
+ }`,
+ [offset],
+ );
+ const value = result.result?.value;
+ if (value?.error) throw clickPointError(selector, value.error);
+ if (typeof value?.x !== "number" || typeof value?.y !== "number") {
+ throw clickPointError(selector, "element position is unavailable");
+ }
+ return { x: value.x, y: value.y, sessionId };
+}
+
+async function pointInViewport(point: Point): Promise<boolean> {
+ const { x, y } = point;
+ const result = await cdp(
+ "Runtime.evaluate",
+ {
+ expression: `${x} >= 0 && ${y} >= 0 && ${x} < innerWidth && ${y} < innerHeight`,
+ returnByValue: true,
+ awaitPromise: false,
+ },
+ point.sessionId,
+ );
+ return result.result?.value !== false;
+}
+
+function clickPointError(selector: string, reason: string) {
+ return new ElementResolutionError(
+ `click failed: ${reason}: ${selector}`,
+ "transient",
+ );
+}
+
async function resolveRawSelectorClickTarget(
selector: string,
): Promise<ClickTarget | null> {
if (!isRawSelector(selector)) return null;
const id = newProbeId("click");
const expression = `(() => {
- const center = ${buildSelectorCenterJs(selector)};
- if (!center) return null;
- ${clickProbeInstallJs(id, "center")}
- return { x: center.x, y: center.y };
+ ${CLICK_POINT_HELPERS}
+ const element = ${buildFindElementJs(selector)};
+ if (!element) return null;
+ const point = clickPointForElement(element, null);
+ if (point.error) return point;
+ ${clickProbeInstallJs(id, "point")}
+ return { x: point.x, y: point.y };
})()`;
const result = await cdp("Runtime.evaluate", {
expression,
@@ -277,6 +343,7 @@ async function resolveRawSelectorClickTarget(
// installs one after resolving.
if (result.exceptionDetails) return null;
const value = result.result?.value;
+ if (value?.error) throw clickPointError(selector, value.error);
if (typeof value?.x !== "number" || typeof value?.y !== "number") {
return null;
}
diff --git a/package/ego-browser/src/element-resolver.ts b/package/ego-browser/src/element-resolver.ts
index 80cd676..cee5f87 100644
--- a/package/ego-browser/src/element-resolver.ts
+++ b/package/ego-browser/src/element-resolver.ts
@@ -1697,7 +1697,7 @@ function resolveAxSession(frameId, sessionId, iframeSessions) {
return [{ frameId }, sessionId];
}
-function buildFindElementJs(selector) {
+export function buildFindElementJs(selector) {
if (String(selector).startsWith("xpath=")) {
return `document.evaluate(${JSON.stringify(String(selector).slice(6))}, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue`;
}
@@ -2184,7 +2184,7 @@ export function isRawSelector(input: unknown): boolean {
}
}
-export function buildSelectorCenterJs(selector) {
+function buildSelectorCenterJs(selector) {
const findExpr = buildFindElementJs(selector);
return `(() => {
const el = ${findExpr};