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.
JavaScript agent-skillsai-agentautomationbrowserbrowser-automationclaude-codecodexhermes-agentskillsskills-sh
fix(ego-browser): keep the v1 click probe armed before input is dispatched
Zhuowei Wangb766db6611a4
diff --git a/package/ego-browser/src/driver/pointer.test.mjs b/package/ego-browser/src/driver/pointer.test.mjsindex db3b874..9915c2a 100644--- a/package/ego-browser/src/driver/pointer.test.mjs+++ b/package/ego-browser/src/driver/pointer.test.mjs@@ -174,18 +174,47 @@ function withFakeEgo(run) {});}-test("click dispatches native input without a page-side probe when the renderer acknowledges it", async () => {+function methodSequence(calls) {+ return calls.map((call) =>+ call.method === "Input.dispatchMouseEvent"+ ? `${call.method}:${call.params.type}`+ : call.method,+ );+}++function isProbeExpression(call) {+ return Boolean(call.params.expression?.includes("__egoBrowserInputProbes"));+}++/**+ * CDP double for a v1 click on a CSS selector with native bindings: the+ * resolving evaluate returns the center, a probe read answers `probeResult`,+ * and native input either succeeds or times out.+ */+function clickOverride({ inputTimesOut = false, probeResult } = {}) {const calls = [];const restore = setOverrides({cdpOverride(method, params) {calls.push({ method, params });if (method === "Runtime.evaluate") {- // Element resolution (buildSelectorCenterJs) — return center point+ if (params.expression.includes("probe.dispose();\n delete")) {+ // finishClickProbe+ return { result: { value: probeResult } };+ }+ // Resolution (buildSelectorCenterJs) plus the probe installreturn { result: { value: { x: 100, y: 200 } } };}+ if (method === "Input.dispatchMouseEvent" && inputTimesOut) {+ throw new Error("CDP request timed out: Input.dispatchMouseEvent");+ }return {};},});+ return { calls, restore };+}++test("click resolves a CSS selector and installs its probe in one page call, then never reads it back", async () => {+ const { calls, restore } = clickOverride();try {await withFakeEgo(() => click("#target"));} finally {@@ -193,107 +222,139 @@ test("click dispatches native input without a page-side probe when the renderer}assert.deepEqual(- calls.map((call) =>- call.method === "Input.dispatchMouseEvent"- ? `${call.method}:${call.params.type}`- : call.method,- ),+ methodSequence(calls),["Runtime.evaluate","Input.dispatchMouseEvent:mouseMoved","Input.dispatchMouseEvent:mousePressed","Input.dispatchMouseEvent:mouseReleased",],- "a normal click is element resolution plus three native input events",+ "a normal click is one resolving page call plus three native input events",);- assert.equal(- calls.some((call) =>- call.params.expression?.includes("__egoBrowserInputProbes"),- ),- false,- "the normal path never installs or reads a click probe",+ assert.match(+ calls[0].params.expression,+ /querySelector|document\./,+ "the single page call resolves the selector",+ );+ assert.match(+ calls[0].params.expression,+ /addEventListener\("click", probe\.handler, true\)/,+ "the same page call installs the trusted-click probe before any input",+ );+ assert.match(+ calls[0].params.expression,+ /setTimeout\(\(\) => \{\s*probe\.dispose\(\);/,+ "the probe removes itself so an acknowledged click never reads it back",+ );+ assert.deepEqual(+ calls.slice(1).map((call) => [call.params.x, call.params.y]),+ [+ [100, 200],+ [100, 200],+ [100, 200],+ ],);});-test("click probes for the trusted click and falls back to synthetic events only after a dispatch timeout", async () => {- const calls = [];- const probeExpressions = [];- const restore = setOverrides({- cdpOverride(method, params) {- calls.push({ method, params });- if (method === "Runtime.evaluate") {- if (params.expression?.includes("__egoBrowserInputProbes")) {- probeExpressions.push(params.expression);- if (probeExpressions.length === 1) {- // installClickProbe — elementFromPoint returns truthy- return { result: { value: true } };- }- // finishClickProbe — the trusted click never arrived- return { result: { value: { seen: false, fallback: true } } };- }- return { result: { value: { x: 100, y: 200 } } };- }- if (method === "Input.dispatchMouseEvent") {- // Simulate CDP timeout — the browser couldn't dispatch the event- throw new Error("CDP request timed out: Input.dispatchMouseEvent");- }- return {};- },+test("click installs the probe before input for coordinate targets and skips the read-back", async () => {+ const { calls, restore } = clickOverride();+ try {+ await withFakeEgo(() => click([30, 40]));+ } finally {+ restore();+ }++ assert.deepEqual(methodSequence(calls), [+ "Runtime.evaluate",+ "Input.dispatchMouseEvent:mouseMoved",+ "Input.dispatchMouseEvent:mousePressed",+ "Input.dispatchMouseEvent:mouseReleased",+ ]);+ assert(isProbeExpression(calls[0]), "the probe is installed before input");+ assert.match(calls[0].params.expression, /\{"x":30,"y":40\}/);+});++test("click reads the probe and falls back to synthetic events only after a dispatch timeout", async () => {+ const { calls, restore } = clickOverride({+ inputTimesOut: true,+ probeResult: { seen: false, fallback: true },+ });+ try {+ // Does not throw: the fallback reached the element.+ await withFakeEgo(() => click("#target"));+ } finally {+ restore();+ }++ assert.deepEqual(methodSequence(calls), [+ "Runtime.evaluate",+ "Input.dispatchMouseEvent:mouseMoved",+ "Runtime.evaluate",+ ]);+ assert(isProbeExpression(calls[0]), "the probe was installed before input");+ const finish = calls[2].params.expression;+ assert.match(finish, /probe\.dispose\(\)/);+ assert.match(finish, /if \(probe\.seen \|\| !probe\.target\) return/);+ assert.match(finish, /dispatchEvent\(new MouseEvent\("click"/);+});++test("click treats a trusted click that landed before the dispatch timeout as delivered", async () => {+ // The renderer can deliver the event and still miss the CDP deadline. The+ // probe installed before dispatch has seen the click, so no synthetic click+ // is replayed and the timeout is absorbed.+ const { calls, restore } = clickOverride({+ inputTimesOut: true,+ probeResult: { seen: true, fallback: false },});try {- // Should NOT throw — timeout is absorbed because fallback succeededawait withFakeEgo(() => click("#target"));} finally {restore();}+ assert.deepEqual(methodSequence(calls), [+ "Runtime.evaluate",+ "Input.dispatchMouseEvent:mouseMoved",+ "Runtime.evaluate",+ ]);assert.equal(- probeExpressions.length,+ calls.filter(isProbeExpression).length,2,- "the probe is installed and read once each after the timeout",- );- const firstInput = calls.findIndex(- (call) => call.method === "Input.dispatchMouseEvent",- );- const probeInstall = calls.findIndex((call) =>- call.params.expression?.includes("__egoBrowserInputProbes"),- );- assert(- firstInput >= 0 && probeInstall > firstInput,- "the probe is installed only after native input timed out",- );- assert.match(- probeExpressions[1],- /dispatchEvent/,- "finish expression contains fallback mouse events",- );- assert.match(- probeExpressions[1],- /MouseEvent/,- "finish expression dispatches MouseEvent in fallback",+ "the probe is installed once before input and read once after the timeout",);});-test("click rethrows a dispatch timeout when the fallback finds no element", async () => {+test("click rethrows a dispatch timeout when the probe has no element to fall back to", async () => {+ const { restore } = clickOverride({+ inputTimesOut: true,+ probeResult: { seen: false, fallback: false },+ });+ try {+ await assert.rejects(+ () => withFakeEgo(() => click("#target")),+ /CDP request timed out: Input\.dispatchMouseEvent/,+ );+ } finally {+ restore();+ }+});++test("click reports a missing CSS selector as a transient resolution error", async () => {const restore = setOverrides({- cdpOverride(method, params) {- if (method === "Runtime.evaluate") {- if (params.expression?.includes("__egoBrowserInputProbes")) {- // installClickProbe — nothing under the point- return { result: { value: false } };- }- return { result: { value: { x: 100, y: 200 } } };- }- if (method === "Input.dispatchMouseEvent") {- throw new Error("CDP request timed out: Input.dispatchMouseEvent");- }+ cdpOverride(method) {+ if (method === "Runtime.evaluate") return { result: { value: null } };return {};},});try {await assert.rejects(- () => withFakeEgo(() => click("#target")),- /CDP request timed out: Input\.dispatchMouseEvent/,+ () => withFakeEgo(() => click("#missing")),+ (error) => {+ assert.equal(error.name, "ElementResolutionError");+ assert.equal(error.kind, "transient");+ assert.equal(error.message, "Element not found: #missing");+ return true;+ },);} finally {restore();diff --git a/package/ego-browser/src/driver/pointer.ts b/package/ego-browser/src/driver/pointer.tsindex 06af052..48e6918 100644--- a/package/ego-browser/src/driver/pointer.ts+++ b/package/ego-browser/src/driver/pointer.ts@@ -1,5 +1,10 @@import { cdp, js } from "../cdp-eval.js";import { browserCdp } from "../browser-runtime.js";+import {+ ElementResolutionError,+ buildSelectorCenterJs,+ isRawSelector,+} from "../element-resolver.js";import { elementCenter } from "./observe.js";import { resolveAndCall } from "./element-ops.js";@@ -67,6 +72,11 @@ type MouseEventOptions = Record<string, unknown>;// the pointer-driven drags keep their caller-chosen pauses.const INPUT_EVENT_DELAY_MS = 0;const INPUT_DISPATCH_TIMEOUT_MS = 1000;+// A click probe is only read back after a dispatch timeout; an acknowledged+// click leaves it to remove itself.+const CLICK_PROBE_TTL_MS = 5_000;++type ClickTarget = Point & { probeId: string | null };/*** Mouse target accepted by mouse helpers.@@ -88,7 +98,7 @@ const INPUT_DISPATCH_TIMEOUT_MS = 1000;* @returns {Promise<void>}*/export async function click(target: MouseTarget, options: ClickOptions = {}) {- const point = await resolveMouseTarget(target);+ const { probeId, ...point } = await resolveClickTarget(target);const button = options.button || "left";const buttons = pressedButtons(button);const clickCount = options.clickCount ?? options.clicks ?? 1;@@ -112,11 +122,12 @@ export async function click(target: MouseTarget, options: ClickOptions = {}) {});} catch (error) {if (!isInputDispatchTimeout(error)) throw error;- // The renderer did not acknowledge native input in time (typically an- // occluded or hidden window). Only this path pays for the page-side- // probe: it waits briefly for the trusted click to land and otherwise- // dispatches synthetic mouse events to the element under the point.- const completed = await recoverTimedOutClick(point, clickCount);+ // The renderer did not acknowledge the input in time (typically an+ // occluded window). A timeout does not prove the event was dropped, so+ // the probe installed before dispatch decides: a trusted click that+ // already reached the target counts as delivered; otherwise synthetic+ // mouse events go to the element under the point.+ const completed = await finishClickProbe(point, probeId, clickCount);if (!completed) throw error;}}@@ -229,30 +240,102 @@ function inputEventDelay(ms = INPUT_EVENT_DELAY_MS) {return new Promise((resolve) => setTimeout(resolve, ms));}-async function recoverTimedOutClick(point: Point, clickCount: number) {- const probeId = await installClickProbe(point);- return finishClickProbe(point, probeId, clickCount);+/**+ * Resolve the click point and install the trusted-click probe before any+ * input is dispatched. A plain CSS selector does both in the one+ * `Runtime.evaluate` that already resolves it; refs, locators, offsets, and+ * coordinates resolve first and install the probe in a call of their own+ * rather than risk a replayed click. Without native bindings there is no+ * fallback, so no probe is installed.+ */+async function resolveClickTarget(target: MouseTarget): Promise<ClickTarget> {+ if (typeof target === "string" && canProbeInputFallback()) {+ const point = await resolveRawSelectorClickTarget(target);+ if (point) return point;+ }+ const point = await resolveMouseTarget(target);+ return { ...point, probeId: await installClickProbe(point) };+}++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 };+ })()`;+ const result = await cdp("Runtime.evaluate", {+ expression,+ returnByValue: true,+ awaitPromise: false,+ });+ // An invalid selector or an unexpected value is reported by the shared+ // resolver, which evaluates the same selector again.+ if (result.exceptionDetails) return null;+ const value = result.result?.value;+ if (value === null) {+ throw new ElementResolutionError(+ `Element not found: ${selector}`,+ "transient",+ );+ }+ if (typeof value?.x !== "number" || typeof value?.y !== "number") {+ return null;+ }+ return { x: value.x, y: value.y, sessionId: undefined, probeId: id };+}++function newProbeId(kind: string) {+ return `${kind}_${Date.now()}_${Math.random().toString(16).slice(2)}`;+}++/**+ * Page-side click probe: remembers the element under `pointExpression` and+ * whether a trusted click reached it. The listener removes itself on the+ * first matching click, and the whole probe removes itself after+ * CLICK_PROBE_TTL_MS so an acknowledged click never has to read it back.+ */+function clickProbeInstallJs(id: string, pointExpression: string) {+ return `+ const probePoint = ${pointExpression};+ window.__egoBrowserInputProbes ||= {};+ const probe = { seen: false, target: document.elementFromPoint(probePoint.x, probePoint.y) };+ probe.dispose = () => {+ document.removeEventListener("click", probe.handler, true);+ clearTimeout(probe.timer);+ };+ probe.handler = (event) => {+ if (+ event.isTrusted && probe.target &&+ (event.target === probe.target || probe.target.contains(event.target))+ ) {+ probe.seen = true;+ probe.dispose();+ }+ };+ probe.timer = setTimeout(() => {+ probe.dispose();+ delete window.__egoBrowserInputProbes[${JSON.stringify(id)}];+ }, ${JSON.stringify(CLICK_PROBE_TTL_MS)});+ document.addEventListener("click", probe.handler, true);+ window.__egoBrowserInputProbes[${JSON.stringify(id)}] = probe;+ `;}async function installClickProbe(point: Point) {if (!canProbeInputFallback()) return null;- const id = `click_${Date.now()}_${Math.random().toString(16).slice(2)}`;+ const id = newProbeId("click");try {const result = await cdp("Runtime.evaluate",{expression: `(() => {- const target = document.elementFromPoint(${JSON.stringify(point.x)}, ${JSON.stringify(point.y)});- window.__egoBrowserInputProbes ||= {};- const probe = { seen: false, target };- probe.handler = (event) => {- if (event.isTrusted && target && (event.target === target || target.contains(event.target))) {- probe.seen = true;- }- };- document.addEventListener("click", probe.handler, true);- window.__egoBrowserInputProbes[${JSON.stringify(id)}] = probe;- return Boolean(target);+ ${clickProbeInstallJs(id, JSON.stringify({ x: point.x, y: point.y }))}+ return Boolean(probe.target);})()`,returnByValue: true,awaitPromise: false,@@ -271,8 +354,8 @@ async function finishClickProbe(clickCount: number,) {if (!id) return false;- // The probe is installed after a dispatch timeout, so give a late trusted- // click a moment to land before the page is asked whether input arrived.+ // Give a trusted click that the renderer is still delivering a moment to+ // land before the page is asked whether input arrived.await inputEventDelay(50);try {const result = await cdp(@@ -282,7 +365,7 @@ async function finishClickProbe(const probes = window.__egoBrowserInputProbes || {};const probe = probes[${JSON.stringify(id)}];if (!probe) return { seen: false, fallback: false };- document.removeEventListener("click", probe.handler, true);+ probe.dispose();delete probes[${JSON.stringify(id)}];if (probe.seen || !probe.target) return { seen: probe.seen, fallback: false };const target = probe.target;diff --git a/package/ego-browser/src/element-resolver.ts b/package/ego-browser/src/element-resolver.tsindex 4fcf458..80cd676 100644--- a/package/ego-browser/src/element-resolver.ts+++ b/package/ego-browser/src/element-resolver.ts@@ -2170,7 +2170,21 @@ function buildCssCountJs(selector) {})()`;}-function buildSelectorCenterJs(selector) {+/**+ * True for a plain CSS selector: not a `@ref` and not a `loc=` / role / href+ * locator. A malformed locator is reported by the caller's resolver path.+ */+export function isRawSelector(input: unknown): boolean {+ if (typeof input !== "string" || input.trim().length === 0) return false;+ if (parseRef(input)) return false;+ try {+ return parseLocatorOrThrow(input) === null;+ } catch {+ return false;+ }+}++export function buildSelectorCenterJs(selector) {const findExpr = buildFindElementJs(selector);return `(() => {const el = ${findExpr};