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): add resilient page interactions

Aute3817fbb3f741
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 8c74e3d..5261e40 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
@@ -86,6 +86,7 @@ export const e2eCases = [
expectedTermination: true,
markerName: "dialog-hard-stop.json",
expectedOutput: "The page has displayed a dialog that requires review.",
+ acceptedCompletionOutput: '"dialogReceipt":true',
},
{
name: "Page JavaScript dialog recovery",
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-click-hit-target.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-click-hit-target.mjs
index e2ae158..252419e 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-click-hit-target.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-click-hit-target.mjs
@@ -23,7 +23,7 @@ export function pageClickHitTargetCase() {
});
await assertRejects(
- () => page.click("#covered-target"),
+ () => page.click("#covered-target", { timeout: 500 }),
"intercepts pointer events",
"high-level click rejects when another element covers its action point"
);
@@ -44,12 +44,14 @@ export function pageClickHitTargetCase() {
"low-level coordinate click still targets the topmost element"
);
- await page.evaluate("document.querySelector('#click-overlay').remove()");
+ await page.evaluate(() => {
+ setTimeout(() => document.querySelector("#click-overlay")?.remove(), 650);
+ });
await page.click("#covered-target");
assertEqual(
- (await page.evaluate("window.__hitTargetClicks")).target,
- 1,
- "the target becomes clickable after the overlay is removed"
+ JSON.stringify(await page.evaluate("window.__hitTargetClicks")),
+ JSON.stringify({ target: 1, overlay: 1 }),
+ "the high-level click waits until a temporary overlay is removed"
);
await page.evaluate(() => {
@@ -74,7 +76,7 @@ export function pageClickHitTargetCase() {
document.body.append(target);
});
await assertRejects(
- () => page.click("#hover-covered-target"),
+ () => page.click("#hover-covered-target", { timeout: 500 }),
"intercepts pointer events",
"click rechecks the hit target after mouse movement"
);
@@ -103,6 +105,20 @@ export function pageClickHitTargetCase() {
"a descendant at the action point is a valid hit target"
);
+ await page.evaluate(() => {
+ for (const text of ["First duplicate", "Second duplicate"]) {
+ const button = document.createElement("button");
+ button.className = "strict-duplicate";
+ button.textContent = text;
+ document.body.append(button);
+ }
+ });
+ await assertRejects(
+ () => page.click("button.strict-duplicate"),
+ "matched 2 elements",
+ "raw CSS Page actions reject ambiguous selectors"
+ );
+
await page.close();
`;
}
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-dialogs.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-dialogs.mjs
index 5cfb322..ff89ef7 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-dialogs.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-dialogs.mjs
@@ -25,9 +25,17 @@ export function pageJavaScriptDialogHandoffCase() {
JSON.stringify({ label: page.label, targetId: page.targetId })
);
- // Ego Lite hands the space to the user as soon as the site opens the dialog.
- // The hard-stop output terminates this script before click() can return.
- await page.click("#dialog-alert");
+ // Ego Lite may hand control to the user, which terminates this script. If
+ // it keeps Agent control, the Page layer must return the dialog instead of
+ // waiting for the blocked input command to time out.
+ const receipt = await page.click("#dialog-alert");
+ assertEqual(receipt.dialog?.type, "alert", "the action reports the dialog type");
+ assertEqual(
+ receipt.dialog?.message,
+ "Alert from real E2E",
+ "the action reports the dialog message"
+ );
+ cliLog(JSON.stringify({ dialogReceipt: true }));
`;
}
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-keyboard.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-keyboard.mjs
index b7000c0..58ae380 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-keyboard.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-keyboard.mjs
@@ -28,6 +28,12 @@ export function pageKeyboardInterfaceCase() {
});
}
});
+ await page.focus("#text-area");
+ assertEqual(
+ await page.evaluate("document.activeElement?.id"),
+ "text-area",
+ "page.focus addresses one selector"
+ );
// U+0020 through U+007E covers every printable ASCII character.
const printable = Array.from(
@@ -119,7 +125,7 @@ export function pageKeyboardInterfaceCase() {
"uppercase modifier keeps the shortcut trusted",
);
- await page.keyboard.press("ControlOrMeta+A");
+ await page.press("#text-area", "ControlOrMeta+A");
await page.keyboard.type("replaced");
await page.keyboard.press("ArrowLeft");
await page.keyboard.press("Backspace");
@@ -152,6 +158,14 @@ export function pageKeyboardInterfaceCase() {
"insertText inserts one native text payload"
);
+ await page.press("#text-area", "ControlOrMeta+A");
+ await page.keyboard.paste("pasted\\t世界\\nnext");
+ assertEqual(
+ await page.evaluate("document.querySelector('#text-area').value"),
+ "pasted\\t世界\\nnext",
+ "paste uses native clipboard input and preserves tabs and newlines"
+ );
+
await page.evaluate("window.__pageKeyboardContractEvents = []");
await page.keyboard.press("Numpad1");
const numpadEvent = (await page.evaluate("window.__pageKeyboardContractEvents"))
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-screenshot.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-screenshot.mjs
index 8c9b959..0705827 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-screenshot.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-screenshot.mjs
@@ -22,7 +22,7 @@ export function pageScrolledScreenshotCase() {
}));
assert(scrollPosition.x > 0 && scrollPosition.y >= 1400, "fixture is scrolled in both axes");
- const defaultPath = join(artifactDir, "scrolled-default.png");
+ const defaultPath = join(artifactDir, "nested", "scrolled-default.png");
const rawPath = join(artifactDir, "scrolled-raw.png");
await page.screenshot({ path: defaultPath, fullPage: false });
await page.screenshot({ path: rawPath, fullPage: false, raw: true });
diff --git a/package/ego-browser/scripts/real-browser-e2e/runner.mjs b/package/ego-browser/scripts/real-browser-e2e/runner.mjs
index 9921b30..a3650e8 100644
--- a/package/ego-browser/scripts/real-browser-e2e/runner.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/runner.mjs
@@ -81,6 +81,7 @@ export async function runRealBrowserE2e() {
markerName,
timeoutMs = 45000,
expectedOutput,
+ acceptedCompletionOutput,
) {
console.log(`-- ${name}`);
const source = egoSource(body, {
@@ -103,31 +104,49 @@ export async function runRealBrowserE2e() {
const durationMs = Date.now() - startedAt;
try {
- if (!commandError && !expectedOutput) {
+ const output = [
+ commandResult?.stdout,
+ commandResult?.stderr,
+ commandError?.stdout,
+ commandError?.stderr,
+ commandError?.message,
+ ]
+ .filter(Boolean)
+ .join("\n");
+ const completedWithAcceptedOutput =
+ !commandError &&
+ acceptedCompletionOutput &&
+ output.includes(acceptedCompletionOutput);
+ const reportedExpectedTermination =
+ expectedOutput && output.includes(expectedOutput);
+ if (
+ !commandError &&
+ !reportedExpectedTermination &&
+ !completedWithAcceptedOutput
+ ) {
throw new Error("the browser script completed instead of terminating");
}
- if (expectedOutput) {
- const output = [
- commandResult?.stdout,
- commandResult?.stderr,
- commandError?.stdout,
- commandError?.stderr,
- commandError?.message,
- ]
- .filter(Boolean)
- .join("\n");
- if (!output.includes(expectedOutput)) {
- throw new Error(
- `the browser script did not report the expected hard stop: ${expectedOutput}`,
- );
- }
+ if (commandError && expectedOutput && !reportedExpectedTermination) {
+ throw new Error(
+ `the browser script did not report the expected hard stop: ${expectedOutput}`,
+ );
}
// The marker is written only after openPage() has returned. Its presence
// distinguishes the intended hard stop from an unrelated startup error.
await stat(join(tempDir, markerName));
- recordResult(name, "pass", durationMs, 1);
+ const assertions = completedWithAcceptedOutput
+ ? (extractAssertionCount(
+ commandResult?.stdout,
+ commandResult?.stderr,
+ ) ?? 1)
+ : 1;
+ recordResult(name, "pass", durationMs, assertions);
console.log(
- `-- ${name} passed (${formatDuration(durationMs)}, expected termination)`,
+ `-- ${name} passed (${formatDuration(durationMs)}, ${
+ completedWithAcceptedOutput
+ ? `${assertions} assertions, accepted completion`
+ : "expected termination"
+ })`,
);
} catch (error) {
const message = error?.message || String(error);
@@ -151,6 +170,7 @@ export async function runRealBrowserE2e() {
testCase.markerName,
testCase.timeoutMs,
testCase.expectedOutput,
+ testCase.acceptedCompletionOutput,
);
return;
}
diff --git a/package/ego-browser/src/clipboard.test.mjs b/package/ego-browser/src/clipboard.test.mjs
new file mode 100644
index 0000000..2a36d51
--- /dev/null
+++ b/package/ego-browser/src/clipboard.test.mjs
@@ -0,0 +1,147 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ ClipboardRestoreError,
+ withTemporaryClipboardText,
+} from "../dist/src/clipboard.js";
+
+test("temporary clipboard text is restored after the action", async () => {
+ const events = [];
+ const value = await withTemporaryClipboardText(
+ "temporary",
+ async () => {
+ events.push("action");
+ return 42;
+ },
+ {
+ async beginTransaction(text) {
+ events.push(["begin", text]);
+ return {
+ async finish() {
+ events.push("finish");
+ return "restored";
+ },
+ };
+ },
+ },
+ );
+
+ assert.equal(value, 42);
+ assert.deepEqual(events, [["begin", "temporary"], "action", "finish"]);
+});
+
+test("temporary clipboard text is restored when the action throws", async () => {
+ let finished = false;
+ const primary = new Error("paste input failed");
+
+ await assert.rejects(
+ () =>
+ withTemporaryClipboardText(
+ "temporary",
+ async () => {
+ throw primary;
+ },
+ {
+ async beginTransaction() {
+ return {
+ async finish() {
+ finished = true;
+ return "restored";
+ },
+ };
+ },
+ },
+ ),
+ (error) => error === primary,
+ );
+ assert.equal(finished, true);
+});
+
+test("a restore failure reports that the paste action already completed", async () => {
+ await assert.rejects(
+ () =>
+ withTemporaryClipboardText("temporary", async () => "done", {
+ async beginTransaction() {
+ return {
+ async finish() {
+ throw new Error("pasteboard unavailable");
+ },
+ };
+ },
+ }),
+ (error) => {
+ assert.ok(error instanceof ClipboardRestoreError);
+ assert.equal(error.code, "EGO_CLIPBOARD_RESTORE_FAILED");
+ assert.equal(error.pasteCompleted, true);
+ assert.match(error.message, /paste completed.*do not retry/i);
+ return true;
+ },
+ );
+});
+
+test("an external clipboard change is respected instead of restoring stale data", async () => {
+ const value = await withTemporaryClipboardText("temporary", async () => 7, {
+ async beginTransaction() {
+ return {
+ async finish() {
+ return "changed";
+ },
+ };
+ },
+ });
+
+ assert.equal(value, 7);
+});
+
+test("clipboard transactions are serialized within one runtime", async () => {
+ const events = [];
+ let releaseFirst;
+ const firstHold = new Promise((resolve) => {
+ releaseFirst = resolve;
+ });
+ let markFirstStarted;
+ const firstStarted = new Promise((resolve) => {
+ markFirstStarted = resolve;
+ });
+ const beginTransaction = async (text) => {
+ events.push(`begin:${text}`);
+ return {
+ async finish() {
+ events.push(`finish:${text}`);
+ return "restored";
+ },
+ };
+ };
+
+ const first = withTemporaryClipboardText(
+ "first",
+ async () => {
+ events.push("action:first");
+ markFirstStarted();
+ await firstHold;
+ },
+ { beginTransaction },
+ );
+ await firstStarted;
+ const second = withTemporaryClipboardText(
+ "second",
+ async () => {
+ events.push("action:second");
+ },
+ { beginTransaction },
+ );
+ await Promise.resolve();
+ assert.deepEqual(events, ["begin:first", "action:first"]);
+
+ releaseFirst();
+ await Promise.all([first, second]);
+ assert.deepEqual(events, [
+ "begin:first",
+ "action:first",
+ "finish:first",
+ "begin:second",
+ "action:second",
+ "finish:second",
+ ]);
+});
diff --git a/package/ego-browser/src/clipboard.ts b/package/ego-browser/src/clipboard.ts
new file mode 100644
index 0000000..284e7ef
--- /dev/null
+++ b/package/ego-browser/src/clipboard.ts
@@ -0,0 +1,323 @@
+import { spawn } from "node:child_process";
+import type { Writable } from "node:stream";
+
+export type ClipboardTransactionStatus = "restored" | "changed";
+
+export type ClipboardTransaction = {
+ finish(): Promise<ClipboardTransactionStatus>;
+};
+
+type ClipboardTransactionOptions = {
+ beginTransaction?: (text: string) => Promise<ClipboardTransaction>;
+};
+
+type ClipboardHostMessage = {
+ state: "ready" | "restored" | "changed" | "error";
+ message?: string;
+};
+
+export class ClipboardRestoreError extends Error {
+ readonly code = "EGO_CLIPBOARD_RESTORE_FAILED";
+ readonly pasteCompleted = true;
+
+ constructor(cause: unknown) {
+ super(
+ "The paste completed, but ego-browser could not restore the clipboard. Do not retry the paste.",
+ { cause },
+ );
+ this.name = "ClipboardRestoreError";
+ }
+}
+
+let transactionQueue: Promise<void> = Promise.resolve();
+
+/**
+ * Run one action while the macOS clipboard temporarily contains `text`.
+ * Transactions are serialized within the process because the pasteboard is a
+ * single user resource shared by every Page.
+ */
+export async function withTemporaryClipboardText<T>(
+ text: string,
+ action: () => Promise<T>,
+ options: ClipboardTransactionOptions = {},
+): Promise<T> {
+ if (typeof text !== "string") {
+ throw new TypeError("page.keyboard.paste text must be a string");
+ }
+ if (typeof action !== "function") {
+ throw new TypeError("clipboard action must be a function");
+ }
+
+ let releaseQueue!: () => void;
+ const previous = transactionQueue;
+ transactionQueue = new Promise<void>((resolve) => {
+ releaseQueue = resolve;
+ });
+ await previous;
+
+ try {
+ const beginTransaction =
+ options.beginTransaction ?? beginDarwinClipboardTransaction;
+ const transaction = await beginTransaction(text);
+ let value!: T;
+ let actionError: unknown;
+ try {
+ value = await action();
+ } catch (error) {
+ actionError = error;
+ }
+
+ let restoreError: unknown;
+ try {
+ await transaction.finish();
+ } catch (error) {
+ restoreError = error;
+ }
+
+ if (actionError !== undefined) {
+ if (restoreError !== undefined) {
+ throw new AggregateError(
+ [actionError, restoreError],
+ "The paste action failed and ego-browser could not restore the clipboard.",
+ );
+ }
+ throw actionError;
+ }
+ if (restoreError !== undefined) {
+ throw new ClipboardRestoreError(restoreError);
+ }
+ return value;
+ } finally {
+ releaseQueue();
+ }
+}
+
+/**
+ * Keep the original NSPasteboard items inside a short-lived JXA process. The
+ * data never crosses stdout or enters the Node heap, and every readable format
+ * is restored unless another process changes the clipboard first.
+ */
+async function beginDarwinClipboardTransaction(
+ text: string,
+): Promise<ClipboardTransaction> {
+ if (process.platform !== "darwin") {
+ throw new Error(
+ "page.keyboard.paste currently requires macOS clipboard support",
+ );
+ }
+
+ const child = spawn(
+ "/usr/bin/osascript",
+ ["-l", "JavaScript", "-e", DARWIN_CLIPBOARD_HOST],
+ { stdio: ["pipe", "pipe", "pipe", "pipe"] },
+ );
+ const messages = clipboardMessages(child.stdout);
+ let stderr = "";
+ child.stderr.setEncoding("utf8");
+ child.stderr.on("data", (chunk) => {
+ if (stderr.length < 16_384) stderr += chunk;
+ });
+ const exit = new Promise<{
+ code: number | null;
+ signal: NodeJS.Signals | null;
+ }>((resolve, reject) => {
+ child.once("error", reject);
+ child.once("exit", (code, signal) => resolve({ code, signal }));
+ });
+
+ child.stdin.end(text, "utf8");
+ const first = await nextHostMessage(messages, exit, () => stderr);
+ if (first.state !== "ready") {
+ throw new Error(first.message || "could not prepare the macOS clipboard");
+ }
+
+ let finished = false;
+ return {
+ async finish() {
+ if (finished) throw new Error("clipboard transaction already finished");
+ finished = true;
+ const signalPipe = child.stdio[3] as Writable | null;
+ if (!signalPipe) {
+ throw new Error("clipboard restore pipe is unavailable");
+ }
+ signalPipe.end("1");
+ const result = await nextHostMessage(messages, exit, () => stderr);
+ const completion = await exit;
+ if (completion.code !== 0) {
+ throw clipboardHostExitError(completion, stderr);
+ }
+ if (result.state === "restored" || result.state === "changed") {
+ return result.state;
+ }
+ throw new Error(
+ result.message || "could not restore the macOS clipboard",
+ );
+ },
+ };
+}
+
+function clipboardMessages(stream: NodeJS.ReadableStream) {
+ const queued: ClipboardHostMessage[] = [];
+ const waiters: Array<{
+ resolve: (message: ClipboardHostMessage) => void;
+ reject: (error: unknown) => void;
+ }> = [];
+ let buffer = "";
+ let ended = false;
+ stream.setEncoding?.("utf8");
+ stream.on("data", (chunk) => {
+ buffer += String(chunk);
+ while (true) {
+ const newline = buffer.indexOf("\n");
+ if (newline < 0) break;
+ const line = buffer.slice(0, newline).trim();
+ buffer = buffer.slice(newline + 1);
+ if (!line) continue;
+ let message: ClipboardHostMessage;
+ try {
+ message = JSON.parse(line);
+ } catch (error) {
+ rejectWaiter(new Error(`invalid clipboard host response: ${line}`));
+ continue;
+ }
+ const waiter = waiters.shift();
+ if (waiter) waiter.resolve(message);
+ else queued.push(message);
+ }
+ });
+ stream.on("error", rejectWaiter);
+ stream.on("end", () => {
+ ended = true;
+ rejectWaiter(new Error("clipboard host closed without a response"));
+ });
+
+ function rejectWaiter(error: unknown) {
+ const waiter = waiters.shift();
+ if (waiter) waiter.reject(error);
+ }
+
+ return {
+ next(): Promise<ClipboardHostMessage> {
+ const message = queued.shift();
+ if (message) return Promise.resolve(message);
+ if (ended) {
+ return Promise.reject(
+ new Error("clipboard host closed without a response"),
+ );
+ }
+ return new Promise((resolve, reject) => {
+ waiters.push({ resolve, reject });
+ });
+ },
+ };
+}
+
+async function nextHostMessage(
+ messages: ReturnType<typeof clipboardMessages>,
+ exit: Promise<{ code: number | null; signal: NodeJS.Signals | null }>,
+ stderr: () => string,
+): Promise<ClipboardHostMessage> {
+ try {
+ // Child `exit` may be emitted before its stdout pipe drains. Read the
+ // protocol message first so a successful restore cannot race with exit.
+ return await messages.next();
+ } catch (error) {
+ const completion = await exit;
+ if (completion.code !== 0 || completion.signal) {
+ throw clipboardHostExitError(completion, stderr());
+ }
+ throw error;
+ }
+}
+
+function clipboardHostExitError(
+ completion: { code: number | null; signal: NodeJS.Signals | null },
+ stderr: string,
+) {
+ const detail = stderr.trim();
+ return new Error(
+ `clipboard host exited ${
+ completion.signal
+ ? `on ${completion.signal}`
+ : `with code ${completion.code}`
+ }${detail ? `: ${detail}` : ""}`,
+ );
+}
+
+const DARWIN_CLIPBOARD_HOST = String.raw`
+ObjC.import("AppKit");
+ObjC.import("Foundation");
+
+const pasteboard = $.NSPasteboard.generalPasteboard;
+
+function emit(message) {
+ const line = $(JSON.stringify(message) + "\n").dataUsingEncoding($.NSUTF8StringEncoding);
+ $.NSFileHandle.fileHandleWithStandardOutput.writeData(line);
+}
+
+function snapshotPasteboard() {
+ const snapshot = [];
+ const sourceItems = pasteboard.pasteboardItems;
+ for (let itemIndex = 0; itemIndex < Number(sourceItems.count); itemIndex += 1) {
+ const sourceItem = sourceItems.objectAtIndex(itemIndex);
+ const values = [];
+ const types = sourceItem.types;
+ for (let typeIndex = 0; typeIndex < Number(types.count); typeIndex += 1) {
+ const type = types.objectAtIndex(typeIndex);
+ const data = sourceItem.dataForType(type);
+ if (data) values.push({ type, data });
+ }
+ snapshot.push(values);
+ }
+ return snapshot;
+}
+
+function restorePasteboard(snapshot) {
+ pasteboard.clearContents;
+ if (snapshot.length === 0) return;
+ const restoredItems = [];
+ for (const values of snapshot) {
+ const item = $.NSPasteboardItem.alloc.init;
+ for (const value of values) item.setDataForType(value.data, value.type);
+ restoredItems.push(item);
+ }
+ if (!pasteboard.writeObjects($(restoredItems))) {
+ throw new Error("NSPasteboard rejected the saved clipboard items");
+ }
+}
+
+const input = $.NSFileHandle.fileHandleWithStandardInput.readDataToEndOfFile;
+const text = ObjC.unwrap(
+ $.NSString.alloc.initWithDataEncoding(input, $.NSUTF8StringEncoding)
+);
+const saved = snapshotPasteboard();
+
+try {
+ pasteboard.clearContents;
+ if (!pasteboard.setStringForType($(text), $.NSPasteboardTypeString)) {
+ throw new Error("NSPasteboard rejected the temporary text");
+ }
+} catch (error) {
+ try { restorePasteboard(saved); } catch (_) {}
+ emit({ state: "error", message: String(error.message || error) });
+ throw error;
+}
+
+const temporaryChangeCount = Number(pasteboard.changeCount);
+emit({ state: "ready" });
+
+const restoreSignal = $.NSFileHandle.alloc.initWithFileDescriptorCloseOnDealloc(3, false);
+restoreSignal.readDataOfLength(1);
+
+try {
+ if (Number(pasteboard.changeCount) !== temporaryChangeCount) {
+ emit({ state: "changed" });
+ } else {
+ restorePasteboard(saved);
+ emit({ state: "restored" });
+ }
+} catch (error) {
+ emit({ state: "error", message: String(error.message || error) });
+ throw error;
+}
+`;
diff --git a/package/ego-browser/src/driver/observe.test.mjs b/package/ego-browser/src/driver/observe.test.mjs
index 02a69b7..33f5a47 100644
--- a/package/ego-browser/src/driver/observe.test.mjs
+++ b/package/ego-browser/src/driver/observe.test.mjs
@@ -1,5 +1,8 @@
import test from "node:test";
import assert from "node:assert/strict";
+import { mkdtemp, readFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import {
browserCdp,
@@ -139,3 +142,16 @@ test("captureScreenshot clips the currently visible scrolled viewport", async ()
restore();
}
});
+
+test("captureScreenshot creates missing parent directories", async () => {
+ const root = await mkdtemp(join(tmpdir(), "ego-browser-screenshot-test-"));
+ const outputPath = join(root, "nested", "screenshots", "page.png");
+ try {
+ await withCdpRuntime(async () => {
+ assert.equal(await captureScreenshot(outputPath), outputPath);
+ });
+ assert.equal(await readFile(outputPath, "utf8"), "png");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/package/ego-browser/src/driver/observe.ts b/package/ego-browser/src/driver/observe.ts
index 9e0c69a..46d6a24 100644
--- a/package/ego-browser/src/driver/observe.ts
+++ b/package/ego-browser/src/driver/observe.ts
@@ -1,4 +1,5 @@
-import { join } from "node:path";
+import { mkdir } from "node:fs/promises";
+import { dirname, join } from "node:path";
import { tmpdir } from "node:os";
import { state } from "../state.js";
@@ -164,6 +165,7 @@ export async function captureScreenshotForSession(
}
}
const result = await cdp("Page.captureScreenshot", params, sessionId);
+ await mkdir(dirname(outputPath), { recursive: true });
await state.writeFile(outputPath, Buffer.from(result.data, "base64"));
return outputPath;
}
diff --git a/package/ego-browser/src/driver/page-actions.ts b/package/ego-browser/src/driver/page-actions.ts
index 650d01e..fb09754 100644
--- a/package/ego-browser/src/driver/page-actions.ts
+++ b/package/ego-browser/src/driver/page-actions.ts
@@ -24,20 +24,27 @@ export type PageClickOptions = {
clickCount?: number;
delay?: number;
position?: { x: number; y: number };
+ force?: boolean;
+ timeout?: number;
};
export type PageFillOptions = {
clearFirst?: boolean;
+ timeout?: number;
};
export type PageHoverOptions = {
position?: { x: number; y: number };
+ force?: boolean;
+ timeout?: number;
};
export type PageDragAndDropOptions = {
button?: MouseButton;
sourcePosition?: { x: number; y: number };
targetPosition?: { x: number; y: number };
+ force?: boolean;
+ timeout?: number;
};
export type PageMouseClickOptions = {
@@ -84,14 +91,18 @@ export async function clickInPage(
refMap,
selector,
iframeSessions,
+ { strict: true },
);
try {
- const point = await resolveElementPoint(
+ let point = await resolveElementPoint(
services,
target.sessionId,
target.objectId,
options.position,
target.frameId,
+ "page.click",
+ options.force,
+ true,
);
const buttons = pressedButtons(button);
await dispatchMouseEvent(services, target.sessionId, {
@@ -102,16 +113,39 @@ export async function clickInPage(
buttons: 0,
modifiers,
});
- for (let count = 1; count <= clickCount; count += 1) {
- // Moving the pointer or completing an earlier click can change layout.
- // Recheck before every press so hover-created overlays fail closed.
- await assertElementReceivesPointerEvents(
+ if (target.frameId) {
+ // Moving into a same-process 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(
services,
target.sessionId,
- target.objectId,
+ target.frameId,
point.local,
- count === 1,
);
+ point = { ...pagePoint, local: point.local };
+ await dispatchMouseEvent(services, target.sessionId, {
+ type: "mouseMoved",
+ x: point.x,
+ y: point.y,
+ button: "none",
+ buttons: 0,
+ modifiers,
+ });
+ }
+ for (let count = 1; count <= clickCount; count += 1) {
+ // Moving the pointer or completing an earlier click can change layout.
+ // Recheck before every press so hover-created overlays fail closed.
+ // A same-process iframe must keep its native move/press sequence
+ // contiguous; the initial check already covered its local hit target.
+ if (!options.force && !target.frameId) {
+ await assertElementReceivesPointerEvents(
+ services,
+ target.sessionId,
+ target.objectId,
+ point.local,
+ );
+ }
await dispatchMouseEvent(services, target.sessionId, {
type: "mousePressed",
x: point.x,
@@ -168,6 +202,7 @@ export async function fillInPage(
refMap,
selector,
iframeSessions,
+ { strict: true },
);
try {
const preparationSource = `function fillPreparation(value, clearFirst) {
@@ -184,6 +219,13 @@ export async function fillInPage(
return { x: (left + right) / 2, y: (top + bottom) / 2 };
};
const tag = this.nodeName.toLowerCase();
+ const view = this.ownerDocument.defaultView;
+ const rect = this.getBoundingClientRect();
+ const style = view?.getComputedStyle(this);
+ if (
+ !view || rect.width <= 0 || rect.height <= 0 ||
+ style?.visibility === "hidden" || style?.display === "none"
+ ) return { error: "element is not visible" };
if (this.disabled) return { error: "element is disabled" };
if (this.readOnly) return { error: "element is read only" };
@@ -241,7 +283,7 @@ export async function fillInPage(
};
let result = await prepare();
if (typeof result?.error === "string") {
- throw new Error(`page.fill failed: ${result.error}`);
+ throw fillPreparationError(result.error);
}
showAgentCursor(
services,
@@ -283,7 +325,7 @@ export async function fillInPage(
);
result = await prepare();
if (typeof result?.error === "string") {
- throw new Error(`page.fill failed: ${result.error}`);
+ throw fillPreparationError(result.error);
}
if (result?.status !== "needsinput") {
throw new Error("page.fill received an invalid preparation result");
@@ -317,6 +359,55 @@ export async function fillInPage(
}
}
+/** Focus one strictly resolved element in an explicit Page session. */
+export async function focusInPage(
+ services: PageActionServices,
+ sessionId: string,
+ refMap: RefMap,
+ selector: string,
+ iframeSessions = new Map<string, string>(),
+): Promise<void> {
+ assertPageSelector(selector);
+ const resolved = await resolveElementObjectId(
+ cdpAdapter(services),
+ sessionId,
+ refMap,
+ selector,
+ iframeSessions,
+ { strict: true },
+ );
+ const source = `function focusElementForAction() {
+ if (!this.isConnected) return { error: "element is not connected" };
+ if (typeof this.focus !== "function") return { error: "element is not focusable" };
+ this.focus();
+ const active = this.ownerDocument.activeElement;
+ return active === this || this.contains(active)
+ ? { focused: true }
+ : { error: "element could not be focused" };
+ }`;
+ try {
+ const response = await services.cdp(
+ "Runtime.callFunctionOn",
+ {
+ functionDeclaration: source,
+ objectId: resolved.objectId,
+ returnByValue: true,
+ awaitPromise: false,
+ },
+ resolved.sessionId,
+ );
+ const result = runtimeValue(response, source);
+ if (typeof result?.error === "string") {
+ throw new ElementResolutionError(
+ `page.focus failed: ${result.error}`,
+ "transient",
+ );
+ }
+ } finally {
+ await releaseObject(services, resolved.sessionId, resolved.objectId);
+ }
+}
+
async function dispatchFillInput(
services: PageActionServices,
sessionId: string,
@@ -419,6 +510,9 @@ async function clickResolvedElement(
objectId,
undefined,
frameId,
+ "page.fill",
+ false,
+ true,
);
await dispatchMouseEvent(services, sessionId, {
type: "mouseMoved",
@@ -433,7 +527,6 @@ async function clickResolvedElement(
sessionId,
objectId,
point.local,
- true,
);
await dispatchMouseEvent(services, sessionId, {
type: "mousePressed",
@@ -472,6 +565,7 @@ export async function hoverInPage(
refMap,
selector,
iframeSessions,
+ { strict: true },
);
try {
const point = await resolveElementPoint(
@@ -480,6 +574,8 @@ export async function hoverInPage(
resolved.objectId,
options.position,
resolved.frameId,
+ "page.hover",
+ options.force,
);
await dispatchMouseEvent(services, resolved.sessionId, {
type: "mouseMoved",
@@ -513,6 +609,7 @@ export async function dragAndDropInPage(
refMap,
sourceSelector,
iframeSessions,
+ { strict: true },
);
let target;
try {
@@ -522,6 +619,7 @@ export async function dragAndDropInPage(
refMap,
targetSelector,
iframeSessions,
+ { strict: true },
);
const sourcePoint = await resolveElementPoint(
services,
@@ -529,6 +627,8 @@ export async function dragAndDropInPage(
source.objectId,
options.sourcePosition,
source.frameId,
+ "page.dragAndDrop",
+ options.force,
);
const targetPoint = await resolveElementPoint(
services,
@@ -536,6 +636,8 @@ export async function dragAndDropInPage(
target.objectId,
options.targetPosition,
target.frameId,
+ "page.dragAndDrop",
+ options.force,
);
const button = options.button ?? "left";
const buttons = pressedButtons(button);
@@ -709,6 +811,9 @@ async function resolveElementPoint(
objectId: string,
position?: { x: number; y: number },
frameId?: string,
+ actionName = "page.click",
+ force = false,
+ checkEnabled = false,
): Promise<{ x: number; y: number; local: { x: number; y: number } }> {
if (
position !== undefined &&
@@ -717,13 +822,16 @@ async function resolveElementPoint(
!Number.isFinite(position.x) ||
!Number.isFinite(position.y))
) {
- throw new TypeError("page.click position requires finite x and y offsets");
+ throw new TypeError(
+ `${actionName} position requires finite x and y offsets`,
+ );
}
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})";
- const expression = `function(${position ? "position" : ""}) {
- ${HIT_TARGET_HELPERS}
+ const expression = `async function(${position ? "position" : ""}) {
+ ${force ? "" : HIT_TARGET_HELPERS}
+ if (!this.isConnected) return { error: "element is not connected" };
let rect = this.getBoundingClientRect();
let point = ${pointExpression};
const outsideViewport =
@@ -742,9 +850,38 @@ async function resolveElementPoint(
) {
return { error: "element is not visible in the viewport" };
}
- const interceptor = interceptingElementAtPoint(this, point);
- if (interceptor) {
- return { error: describeHitTarget(interceptor) + " intercepts pointer events" };
+ if (${checkEnabled ? "true" : "false"}) {
+ const disabled = this.matches?.(":disabled") ||
+ this.closest?.('[aria-disabled="true"]');
+ if (disabled) return { error: "element is disabled" };
+ }
+ const firstRect = { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
+ await new Promise((resolve) => {
+ let settled = false;
+ const finish = () => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ resolve();
+ };
+ const timer = setTimeout(finish, 100);
+ requestAnimationFrame(() => requestAnimationFrame(finish));
+ });
+ rect = this.getBoundingClientRect();
+ if (
+ Math.abs(rect.x - firstRect.x) > 0.25 ||
+ Math.abs(rect.y - firstRect.y) > 0.25 ||
+ Math.abs(rect.width - firstRect.width) > 0.25 ||
+ Math.abs(rect.height - firstRect.height) > 0.25
+ ) {
+ return { error: "element is not stable" };
+ }
+ point = ${pointExpression};
+ if (!${force ? "true" : "false"}) {
+ const interceptor = interceptingElementAtPoint(this, point);
+ if (interceptor) {
+ return { error: describeHitTarget(interceptor) + " intercepts pointer events" };
+ }
}
return point;
}`;
@@ -755,22 +892,19 @@ async function resolveElementPoint(
objectId,
arguments: position ? [{ value: position }] : [],
returnByValue: true,
- awaitPromise: false,
+ awaitPromise: true,
},
sessionId,
);
const point = runtimeValue(response, expression);
if (typeof point?.error === "string") {
- if (point.error === "element is not visible in the viewport") {
- throw new ElementResolutionError(
- `page.click failed: ${point.error}`,
- "transient",
- );
- }
- throw new Error(`page.click failed: ${point.error}`);
+ throw new ElementResolutionError(
+ `${actionName} failed: ${point.error}`,
+ "transient",
+ );
}
if (!Number.isFinite(point?.x) || !Number.isFinite(point?.y)) {
- throw new Error("page.click could not resolve the element position");
+ throw new Error(`${actionName} could not resolve the element position`);
}
const pagePoint = await pagePointForFrame(
services,
@@ -819,7 +953,6 @@ async function assertElementReceivesPointerEvents(
sessionId: string,
objectId: string,
point: { x: number; y: number },
- retryDisconnected = false,
): Promise<void> {
const expression = `function(point) {
${HIT_TARGET_HELPERS}
@@ -842,16 +975,25 @@ async function assertElementReceivesPointerEvents(
);
const result = runtimeValue(response, expression);
if (typeof result?.error === "string") {
- if (retryDisconnected && result.error === "element is not connected") {
- throw new ElementResolutionError(
- `page.click failed: ${result.error}`,
- "transient",
- );
- }
- throw new Error(`page.click failed: ${result.error}`);
+ throw new ElementResolutionError(
+ `page.click failed: ${result.error}`,
+ "transient",
+ );
}
}
+function fillPreparationError(message: string) {
+ const transient = new Set([
+ "element is not connected",
+ "element is not visible",
+ "element is disabled",
+ "element is read only",
+ ]);
+ return transient.has(message)
+ ? new ElementResolutionError(`page.fill failed: ${message}`, "transient")
+ : new Error(`page.fill failed: ${message}`);
+}
+
// This is a compact adaptation of Playwright's composed-tree hit-target check.
// It handles ordinary descendants, slots, and nested shadow roots without
// exposing an injected helper or trusting only document.elementFromPoint().
diff --git a/package/ego-browser/src/driver/page-input.ts b/package/ego-browser/src/driver/page-input.ts
index 2e9a977..8bb4301 100644
--- a/package/ego-browser/src/driver/page-input.ts
+++ b/package/ego-browser/src/driver/page-input.ts
@@ -36,6 +36,7 @@ export async function setInputFilesInPage(
refMap,
selector,
iframeSessions,
+ { strict: true },
);
let inputObjectId: string | undefined;
try {
diff --git a/package/ego-browser/src/driver/page-keyboard.ts b/package/ego-browser/src/driver/page-keyboard.ts
index 27c8ab1..dd7e88e 100644
--- a/package/ego-browser/src/driver/page-keyboard.ts
+++ b/package/ego-browser/src/driver/page-keyboard.ts
@@ -6,6 +6,10 @@ export type PageKeyboardServices = {
timeoutMs?: number,
): Promise<any>;
sleep(ms: number): Promise<void>;
+ withTemporaryClipboardText<T>(
+ text: string,
+ action: () => Promise<T>,
+ ): Promise<T>;
platform?: string;
};
@@ -95,33 +99,51 @@ export class PageKeyboardController {
chord: string,
options: PageKeyboardPressOptions = {},
): Promise<unknown> {
+ return this.#runObserved((sessionId) =>
+ this.pressInSession(sessionId, chord, options),
+ );
+ }
+
+ /** Press a chord inside an existing Page action boundary. */
+ async pressInSession(
+ sessionId: string,
+ chord: string,
+ options: PageKeyboardPressOptions = {},
+ ): Promise<void> {
const tokens = splitChord(chord);
- return this.#runObserved(async (sessionId) => {
- const pressed: string[] = [];
- let actionError: unknown;
+ const pressed: string[] = [];
+ let actionError: unknown;
+ try {
+ for (const token of tokens) {
+ pressed.push(token);
+ await this.#down(sessionId, token);
+ }
+ if (options.delay) await this.#services.sleep(options.delay);
+ } catch (error) {
+ actionError = error;
+ }
+
+ let releaseError: unknown;
+ // Releasing in reverse order prevents a failed shortcut from leaving a
+ // modifier held for every later mouse or keyboard action on this Page.
+ for (const token of pressed.reverse()) {
try {
- for (const token of tokens) {
- pressed.push(token);
- await this.#down(sessionId, token);
- }
- if (options.delay) await this.#services.sleep(options.delay);
+ await this.#up(sessionId, token);
} catch (error) {
- actionError = error;
+ releaseError ??= error;
}
+ }
+ if (actionError) throw actionError;
+ if (releaseError) throw releaseError;
+ }
- let releaseError: unknown;
- // Releasing in reverse order prevents a failed shortcut from leaving a
- // modifier held for every later mouse or keyboard action on this Page.
- for (const token of pressed.reverse()) {
- try {
- await this.#up(sessionId, token);
- } catch (error) {
- releaseError ??= error;
- }
- }
- if (actionError) throw actionError;
- if (releaseError) throw releaseError;
- });
+ async paste(text: string): Promise<unknown> {
+ assertText(text, "page.keyboard.paste");
+ return this.#runObserved((sessionId) =>
+ this.#services.withTemporaryClipboardText(text, () =>
+ this.pressInSession(sessionId, "ControlOrMeta+V"),
+ ),
+ );
}
async insertText(text: string): Promise<unknown> {
diff --git a/package/ego-browser/src/element-resolver.test.mjs b/package/ego-browser/src/element-resolver.test.mjs
index b40f252..7b9aa22 100644
--- a/package/ego-browser/src/element-resolver.test.mjs
+++ b/package/ego-browser/src/element-resolver.test.mjs
@@ -209,6 +209,65 @@ test("ambiguous text locators fail permanently instead of choosing one match", a
);
});
+test("ambiguous raw CSS selectors fail instead of choosing the first match", async () => {
+ const cdp = new FakeCDP(async (method, params) => {
+ if (method === "Runtime.evaluate") {
+ assert.match(params.expression, /querySelectorAll/);
+ return { result: { value: 3 } };
+ }
+ return {};
+ });
+
+ await assert.rejects(
+ () =>
+ resolveElementObjectId(
+ cdp,
+ "session:page",
+ new RefMap(),
+ "button.save",
+ new Map(),
+ { strict: true },
+ ),
+ (error) => {
+ assert.ok(error instanceof ElementResolutionError);
+ assert.equal(error.kind, "permanent");
+ assert.match(error.message, /Selector button\.save matched 3 elements/);
+ return true;
+ },
+ );
+});
+
+test("ambiguous raw XPath selectors fail instead of choosing the first match", async () => {
+ const cdp = new FakeCDP(async (method, params) => {
+ if (method === "Runtime.evaluate") {
+ assert.match(params.expression, /ORDERED_NODE_SNAPSHOT_TYPE/);
+ return { result: { value: 2 } };
+ }
+ return {};
+ });
+
+ await assert.rejects(
+ () =>
+ resolveElementObjectId(
+ cdp,
+ "session:page",
+ new RefMap(),
+ "xpath=//button",
+ new Map(),
+ { strict: true },
+ ),
+ (error) => {
+ assert.ok(error instanceof ElementResolutionError);
+ assert.equal(error.kind, "permanent");
+ assert.match(
+ error.message,
+ /Selector xpath=\/\/button matched 2 elements/,
+ );
+ return true;
+ },
+ );
+});
+
test("semantic locators search cross-process iframe sessions", async () => {
const cdp = new FakeCDP(async (method, _params, sessionId) => {
if (method === "Accessibility.getFullAXTree") {
diff --git a/package/ego-browser/src/element-resolver.ts b/package/ego-browser/src/element-resolver.ts
index 6fb005e..e67b6e3 100644
--- a/package/ego-browser/src/element-resolver.ts
+++ b/package/ego-browser/src/element-resolver.ts
@@ -95,10 +95,7 @@ export async function resolveElementCenter(
candidateSessionId,
);
if (result.exceptionDetails) {
- throw new ElementResolutionError(
- `Invalid selector: ${selectorOrRef}: ${exceptionText(result)}`,
- "permanent",
- );
+ throw invalidSelectorError(selectorOrRef, result);
}
const value = result.result?.value;
if (typeof value?.x === "number" && typeof value?.y === "number") {
@@ -117,7 +114,8 @@ export async function resolveElementObjectId(
refMap,
selectorOrRef,
iframeSessions = new Map(),
-) {
+ options: { strict?: boolean } = {},
+): Promise<{ objectId: string; sessionId: string; frameId?: string }> {
const refId = parseRef(selectorOrRef);
if (refId) {
const entry = refMap.get(refId);
@@ -190,7 +188,15 @@ export async function resolveElementObjectId(
return resolveLocatorObjectId(cdp, sessionId, locator, iframeSessions);
}
- for (const candidateSessionId of pageSessions(sessionId, iframeSessions)) {
+ const sessions = pageSessions(sessionId, iframeSessions);
+ if (options.strict) {
+ return resolveRawSelectorObjectId(
+ cdp,
+ sessions,
+ parseRawSelector(selectorOrRef),
+ );
+ }
+ for (const candidateSessionId of sessions) {
const result = await send(
cdp,
"Runtime.evaluate",
@@ -203,10 +209,7 @@ export async function resolveElementObjectId(
candidateSessionId,
);
if (result.exceptionDetails) {
- throw new ElementResolutionError(
- `Invalid selector: ${selectorOrRef}: ${exceptionText(result)}`,
- "permanent",
- );
+ throw invalidSelectorError(selectorOrRef, result);
}
const objectId = result.result?.objectId;
if (objectId) return { objectId, sessionId: candidateSessionId };
@@ -217,6 +220,91 @@ export async function resolveElementObjectId(
);
}
+async function resolveRawSelectorObjectId(cdp, sessions, selector) {
+ const match = await findUniqueRawSelectorSession(cdp, sessions, selector);
+ const result = await send(
+ cdp,
+ "Runtime.evaluate",
+ {
+ expression: buildFindElementJs(selector.raw),
+ returnByValue: false,
+ awaitPromise: false,
+ objectGroup: "ego-browser",
+ },
+ match.sessionId,
+ );
+ if (result.exceptionDetails) {
+ throw invalidSelectorError(selector.raw, result);
+ }
+ const objectId = result.result?.objectId;
+ if (!objectId) {
+ throw new ElementResolutionError(
+ `Element not found: ${selector.raw}`,
+ "transient",
+ );
+ }
+ return { objectId, sessionId: match.sessionId };
+}
+
+async function findUniqueRawSelectorSession(cdp, sessions, selector) {
+ const mainCount = await rawSelectorCount(cdp, sessions[0], selector);
+ if (mainCount > 1) throw rawSelectorCountError(selector.raw, mainCount);
+ if (mainCount === 1) return { sessionId: sessions[0] };
+
+ const matches = [];
+ let count = 0;
+ for (const candidateSessionId of sessions.slice(1)) {
+ const candidateCount = await rawSelectorCount(
+ cdp,
+ candidateSessionId,
+ selector,
+ );
+ count += candidateCount;
+ if (candidateCount > 0) {
+ matches.push({ count: candidateCount, sessionId: candidateSessionId });
+ }
+ }
+ if (count === 0) {
+ throw new ElementResolutionError(
+ `Selector ${selector.raw} matched 0 elements`,
+ "transient",
+ );
+ }
+ if (count > 1) throw rawSelectorCountError(selector.raw, count);
+ return matches[0];
+}
+
+async function rawSelectorCount(cdp, sessionId, selector) {
+ const result = await send(
+ cdp,
+ "Runtime.evaluate",
+ {
+ expression: buildRawSelectorCountJs(selector),
+ returnByValue: true,
+ awaitPromise: false,
+ },
+ sessionId,
+ );
+ if (result.exceptionDetails) {
+ throw invalidSelectorError(selector.raw, result);
+ }
+ return Number(result.result?.value || 0);
+}
+
+function rawSelectorCountError(raw, count) {
+ return new ElementResolutionError(
+ `Selector ${raw} matched ${count} elements`,
+ "permanent",
+ );
+}
+
+function invalidSelectorError(raw, result) {
+ return new ElementResolutionError(
+ `Invalid selector: ${raw}: ${exceptionText(result)}`,
+ "permanent",
+ );
+}
+
function resolveFrameSession(frameId, sessionId, iframeSessions) {
if (!frameId) {
return sessionId;
@@ -573,6 +661,20 @@ function buildFindElementJs(selector) {
return buildCssFindJs(selector);
}
+function parseRawSelector(input) {
+ const raw = String(input);
+ return raw.startsWith("xpath=")
+ ? { kind: "xpath", selector: raw.slice(6), raw }
+ : { kind: "css", selector: raw, raw };
+}
+
+function buildRawSelectorCountJs(selector) {
+ if (selector.kind === "xpath") {
+ return `document.evaluate(${JSON.stringify(selector.selector)}, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength`;
+ }
+ return buildCssCountJs(selector.selector);
+}
+
function buildLocatorFindJs(locator) {
if (locator.kind === "css") {
return buildCssFindJs(locator.selector);
diff --git a/package/ego-browser/src/page-actions.test.mjs b/package/ego-browser/src/page-actions.test.mjs
index 2f88faa..cf856c7 100644
--- a/package/ego-browser/src/page-actions.test.mjs
+++ b/package/ego-browser/src/page-actions.test.mjs
@@ -34,8 +34,12 @@ test("Page click translates same-process iframe coordinates to the Page viewport
return { backendNodeId: 90 };
}
if (method === "DOM.getBoxModel") {
+ const callCount = calls.filter(
+ ([calledMethod]) => calledMethod === "DOM.getBoxModel",
+ ).length;
+ const y = callCount === 1 ? 200 : 219;
return {
- model: { content: [100, 200, 300, 200, 300, 400, 100, 400] },
+ model: { content: [100, y, 300, y, 300, y + 200, 100, y + 200] },
};
}
return {};
@@ -57,19 +61,38 @@ test("Page click translates same-process iframe coordinates to the Page viewport
const pointerEvents = calls
.filter(([method]) => method === "Input.dispatchMouseEvent")
.map(([, params]) => params);
- assert.equal(pointerEvents.length, 3);
+ assert.equal(pointerEvents.length, 4);
assert(
- pointerEvents.every(({ x, y }) => x === 110 && y === 220),
- "native input must use top-level Page coordinates",
+ pointerEvents[0].x === 110 && pointerEvents[0].y === 220,
+ "the initial move uses the first top-level Page coordinates",
+ );
+ assert(
+ pointerEvents.slice(1).every(({ x, y }) => x === 110 && y === 239),
+ "the press uses coordinates translated again after the pointer move",
);
const hitTest = calls.find(
([method, params]) =>
method === "Runtime.callFunctionOn" &&
params.functionDeclaration.includes("isConnected"),
);
- assert.deepEqual(
- hitTest[1].arguments[0].value,
- { x: 10, y: 20 },
- "the iframe-local hit test must keep local coordinates",
+ assert.match(
+ hitTest[1].functionDeclaration,
+ /elementsFromPoint\(point\.x, point\.y\)/,
+ "the iframe-local actionability check uses its own document",
+ );
+ const moveIndex = calls.findLastIndex(
+ ([method, params]) =>
+ method === "Input.dispatchMouseEvent" && params.type === "mouseMoved",
+ );
+ const pressIndex = calls.findIndex(
+ ([method, params]) =>
+ method === "Input.dispatchMouseEvent" && params.type === "mousePressed",
+ );
+ assert.equal(
+ calls
+ .slice(moveIndex + 1, pressIndex)
+ .some(([method]) => method === "Runtime.callFunctionOn"),
+ false,
+ "same-process iframe input keeps mouseMoved and mousePressed contiguous",
);
});
diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjs
index 3cd64f0..50dfb48 100644
--- a/package/ego-browser/src/page-model.test.mjs
+++ b/package/ego-browser/src/page-model.test.mjs
@@ -35,7 +35,7 @@ function createFixture(rootDir) {
let dialogOnNextClick = null;
const pendingDialogs = new Map();
let rejectedClickPointsRemaining = 0;
- let interceptNextClickPoint = false;
+ let interceptedClickPointsRemaining = 0;
let fillElementKind = "input";
let fillText = "";
let ignoredFillInsertionsRemaining = 0;
@@ -166,6 +166,20 @@ function createFixture(rootDir) {
},
};
}
+ if (
+ /return __egoQueryAllOpenShadow\([^;]+\)\.length;/.test(
+ params.expression,
+ )
+ ) {
+ return {
+ result: { type: "number", value: elementPresent ? 1 : 0 },
+ };
+ }
+ if (params.expression.includes("ORDERED_NODE_SNAPSHOT_TYPE")) {
+ return {
+ result: { type: "number", value: elementPresent ? 1 : 0 },
+ };
+ }
if (params.expression.includes("innerWidth")) {
return {
result: {
@@ -197,6 +211,11 @@ function createFixture(rootDir) {
return { result: { type: "string", value: "complete" } };
}
if (method === "Runtime.callFunctionOn") {
+ if (params.functionDeclaration.includes("focusElementForAction")) {
+ return {
+ result: { type: "object", value: { focused: true } },
+ };
+ }
if (params.functionDeclaration.includes("resolveFileInputForUpload")) {
const targetId = targetForSession(sessionId);
return {
@@ -266,10 +285,10 @@ function createFixture(rootDir) {
}
if (params.functionDeclaration.includes("getBoundingClientRect")) {
if (
- interceptNextClickPoint &&
+ interceptedClickPointsRemaining > 0 &&
params.functionDeclaration.includes("elementFromPoint")
) {
- interceptNextClickPoint = false;
+ interceptedClickPointsRemaining -= 1;
return {
result: {
type: "object",
@@ -400,6 +419,14 @@ function createFixture(rootDir) {
async showAgentMousePosition(x, y) {
calls.push(["showAgentMousePosition", x, y]);
},
+ async withTemporaryClipboardText(text, action) {
+ calls.push(["clipboard", "write", text]);
+ try {
+ return await action();
+ } finally {
+ calls.push(["clipboard", "restore"]);
+ }
+ },
async snapshot(options = {}) {
const tab = tabs.get(activeTarget);
snapshotOptions.push({ ...options });
@@ -513,7 +540,10 @@ function createFixture(rootDir) {
rejectedClickPointsRemaining = count;
},
interceptNextClickPoint() {
- interceptNextClickPoint = true;
+ interceptedClickPointsRemaining = 1;
+ },
+ interceptClickPoints(count) {
+ interceptedClickPointsRemaining = count;
},
navigateOnNextClick(url) {
navigateOnNextClickUrl = url;
@@ -657,8 +687,8 @@ test("v2 methods reject option fields that are absent from the public schema", a
const page = await task.openPage("https://example.test/options");
await assert.rejects(
- () => page.click("button", { force: true }),
- /page\.click received unknown option: force/,
+ () => page.click("button", { trial: true }),
+ /page\.click received unknown option: trial/,
);
});
});
@@ -1619,6 +1649,100 @@ test("Page keyboard press and type use the addressed target session", async () =
});
});
+test("Page focus and selector-scoped press resolve and focus one element", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a", { platform: "darwin" });
+ const page = await task.openPage("https://example.test/editor");
+
+ assert.deepEqual(await page.focus("[contenteditable]"), {});
+ assert.deepEqual(
+ await page.press("[contenteditable]", "ControlOrMeta+A", {
+ delay: 5,
+ timeout: 200,
+ }),
+ {},
+ );
+
+ const focusCalls = fixture.calls.filter(
+ ([kind, method, params]) =>
+ kind === "cdp" &&
+ method === "Runtime.callFunctionOn" &&
+ params.functionDeclaration.includes("focusElementForAction"),
+ );
+ assert.equal(focusCalls.length, 2);
+ assert(focusCalls.every((call) => call[3] === `session:${page.targetId}`));
+ const keyDown = fixture.calls.find(
+ ([kind, method, params]) =>
+ kind === "cdp" &&
+ method === "Input.dispatchKeyEvent" &&
+ params.type === "rawKeyDown" &&
+ params.code === "KeyA",
+ );
+ assert.equal(keyDown[2].modifiers, 4);
+ });
+});
+
+test("Page keyboard paste restores the clipboard after the native shortcut", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a", { platform: "darwin" });
+ const page = await task.openPage("https://example.test/table");
+
+ assert.deepEqual(await page.keyboard.paste("a\tb\nc\td"), {});
+
+ const writeIndex = fixture.calls.findIndex(
+ (call) => call[0] === "clipboard" && call[1] === "write",
+ );
+ const pasteIndex = fixture.calls.findIndex(
+ ([kind, method, params]) =>
+ kind === "cdp" &&
+ method === "Input.dispatchKeyEvent" &&
+ params.type === "rawKeyDown" &&
+ params.code === "KeyV",
+ );
+ const restoreIndex = fixture.calls.findIndex(
+ (call) => call[0] === "clipboard" && call[1] === "restore",
+ );
+ assert(writeIndex >= 0 && writeIndex < pasteIndex);
+ assert(pasteIndex < restoreIndex);
+ assert.deepEqual(fixture.calls[writeIndex], [
+ "clipboard",
+ "write",
+ "a\tb\nc\td",
+ ]);
+ });
+});
+
+test("Page keyboard paste still restores the clipboard when input fails", async () => {
+ await withFixture(async (fixture) => {
+ let restored = false;
+ let failNextKey = true;
+ const task = taskForRound(fixture, "round-a", {
+ platform: "darwin",
+ async withTemporaryClipboardText(_text, action) {
+ try {
+ return await action();
+ } finally {
+ restored = true;
+ }
+ },
+ async cdp(method, params, sessionId, timeoutMs) {
+ if (method === "Input.dispatchKeyEvent" && failNextKey) {
+ failNextKey = false;
+ throw new Error("keyboard transport failed");
+ }
+ return fixture.services.cdp(method, params, sessionId, timeoutMs);
+ },
+ });
+ const page = await task.openPage("https://example.test/table");
+
+ await assert.rejects(
+ () => page.keyboard.paste("one\ttwo"),
+ /keyboard transport failed/,
+ );
+ assert.equal(restored, true);
+ });
+});
+
test("Page keyboard type uses the main keyboard for digits and period", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
@@ -2358,6 +2482,11 @@ test("Page click scrolls the element into view before computing its point", asyn
params.functionDeclaration.includes("getBoundingClientRect"),
);
assert.match(pointCall[2].functionDeclaration, /scrollIntoView/);
+ assert.match(
+ pointCall[2].functionDeclaration,
+ /setTimeout\(finish, 100\)/,
+ "stability sampling must not wait indefinitely for background animation frames",
+ );
});
});
@@ -2388,15 +2517,15 @@ test("Page click retries a transient visibility change before dispatching input"
});
});
-test("Page click reports a persistent transient state after bounded retries", async () => {
+test("Page click reports the last transient state after its timeout", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
const page = await task.openPage("https://example.test/first");
- fixture.rejectClickPoints(3);
+ fixture.rejectClickPoints(100);
await assert.rejects(
- () => page.click("#changing"),
- /page state changed.*new snapshot.*current selector/i,
+ () => page.click("#changing", { timeout: 1_000 }),
+ /page\.click timed out after 1000ms.*not visible/i,
);
assert.equal(
fixture.calls.filter(
@@ -2417,15 +2546,34 @@ test("Page click reports a persistent transient state after bounded retries", as
});
});
-test("Page click fails closed when another element intercepts the point", async () => {
+test("Page click waits for a temporary pointer interceptor", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
const page = await task.openPage("https://example.test/first");
fixture.interceptNextClickPoint();
+ assert.deepEqual(await page.click("#covered", { timeout: 100 }), {});
+ assert(
+ fixture.calls.some(
+ ([kind, method, params]) =>
+ kind === "cdp" &&
+ method === "Input.dispatchMouseEvent" &&
+ params.type === "mouseReleased",
+ ),
+ "input is dispatched after the overlay disappears",
+ );
+ });
+});
+
+test("Page click times out while a pointer interceptor remains", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await task.openPage("https://example.test/first");
+ fixture.interceptClickPoints(100);
+
await assert.rejects(
- () => page.click("#covered"),
- /overlay.*intercepts pointer events/,
+ () => page.click("#covered", { timeout: 100 }),
+ /page\.click timed out after 100ms.*overlay.*intercepts pointer events/i,
);
assert.equal(
fixture.calls.some(
@@ -2438,6 +2586,27 @@ test("Page click fails closed when another element intercepts the point", async
});
});
+test("Page click force bypasses only the pointer interception check", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await task.openPage("https://example.test/first");
+ fixture.interceptClickPoints(100);
+
+ assert.deepEqual(
+ await page.click("#intentionally-covered", { force: true }),
+ {},
+ );
+ assert(
+ fixture.calls.some(
+ ([kind, method, params]) =>
+ kind === "cdp" &&
+ method === "Input.dispatchMouseEvent" &&
+ params.type === "mouseReleased",
+ ),
+ );
+ });
+});
+
test("close leaves an anchor tab and the next page gets a new label", 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 0ce9bb8..a79f08f 100644
--- a/package/ego-browser/src/page-model.ts
+++ b/package/ego-browser/src/page-model.ts
@@ -14,6 +14,7 @@ import {
type FileChooserOpenedEvent,
} from "./browser-runtime.js";
import { runtimeValue } from "./cdp-eval.js";
+import { withTemporaryClipboardText } from "./clipboard.js";
import {
captureScreenshotForSession,
snapshotRaw,
@@ -25,6 +26,7 @@ import {
clickInPage,
dragAndDropInPage,
fillInPage,
+ focusInPage,
hoverInPage,
mouseButtonInPage,
mouseButtonMask,
@@ -118,6 +120,10 @@ type CdpOptions = {
timeout?: number;
};
+type PagePressOptions = PageKeyboardPressOptions & {
+ timeout?: number;
+};
+
type WaitForControlOptions = {
interval?: number;
timeout?: number;
@@ -232,6 +238,10 @@ type PageModelServices = {
timeoutMs?: number,
): Promise<any>;
showAgentMousePosition(x: number, y: number): Promise<void>;
+ withTemporaryClipboardText<T>(
+ text: string,
+ action: () => Promise<T>,
+ ): Promise<T>;
snapshot(options?: SnapshotOptions): Promise<any>;
screenshot(
path: string | undefined,
@@ -272,8 +282,8 @@ export type PageActionReceipt = {
const PAGE_CLOSE_CONFIRM_TIMEOUT_MS = 2_000;
const PAGE_CLOSE_CONFIRM_INTERVAL_MS = 50;
-const PAGE_ACTION_RESOLUTION_ATTEMPTS = 3;
-const PAGE_ACTION_RESOLUTION_RETRY_MS = 50;
+const DEFAULT_PAGE_ACTION_TIMEOUT_MS = 3_000;
+const PAGE_ACTION_RESOLUTION_RETRY_MS = 500;
const CONTROL_POLL_INTERVAL_MS = 20_000;
const CONTROL_WAIT_TIMEOUT_MS = 600_000;
@@ -438,6 +448,19 @@ class PageKeyboard {
return (await this.#controller.press(chord, options)) as PageActionReceipt;
}
+ async pressInSession(
+ sessionId: string,
+ chord: string,
+ options: PageKeyboardPressOptions = {},
+ ): Promise<void> {
+ validatePublicApiOptions("Page.keyboard.press", options);
+ await this.#controller.pressInSession(sessionId, chord, options);
+ }
+
+ async paste(text: string): Promise<PageActionReceipt> {
+ return (await this.#controller.paste(text)) as PageActionReceipt;
+ }
+
async insertText(text: string): Promise<void> {
await this.#controller.insertText(text);
}
@@ -536,6 +559,7 @@ const baseDefaultServices: Omit<PageModelServices, "ledger" | "pageBudget"> = {
ego.animationHighlightMouseToPosition(x, y),
);
},
+ withTemporaryClipboardText,
snapshot: snapshotRaw,
screenshot: captureScreenshotForSession,
pendingDialog,
@@ -1250,7 +1274,11 @@ class Page {
this.keyboard.modifierMask(),
iframeSessions,
),
- true,
+ {
+ actionName: "page.click",
+ guardFileChooser: true,
+ timeout: options.timeout,
+ },
);
}
@@ -1271,7 +1299,11 @@ class Page {
this.keyboard.modifierMask(),
iframeSessions,
),
- true,
+ {
+ actionName: "page.dblclick",
+ guardFileChooser: true,
+ timeout: options.timeout,
+ },
);
}
@@ -1280,16 +1312,19 @@ class Page {
options: PageHoverOptions = {},
): Promise<PageActionReceipt> {
validatePublicApiOptions("Page.hover", options);
- return this.#runAction(selector, (sessionId, refMap, iframeSessions) =>
- hoverInPage(
- this.#services,
- sessionId,
- refMap,
- selector,
- options,
- this.keyboard.modifierMask(),
- iframeSessions,
- ),
+ return this.#runAction(
+ selector,
+ (sessionId, refMap, iframeSessions) =>
+ hoverInPage(
+ this.#services,
+ sessionId,
+ refMap,
+ selector,
+ options,
+ this.keyboard.modifierMask(),
+ iframeSessions,
+ ),
+ { actionName: "page.hover", timeout: options.timeout },
);
}
@@ -1312,6 +1347,7 @@ class Page {
this.keyboard.modifierMask(),
iframeSessions,
),
+ { actionName: "page.dragAndDrop", timeout: options.timeout },
);
}
@@ -1321,16 +1357,65 @@ class Page {
options: PageFillOptions = {},
): Promise<PageActionReceipt> {
validatePublicApiOptions("Page.fill", options);
- return this.#runAction(selector, (sessionId, refMap, iframeSessions) =>
- fillInPage(
- this.#services,
- sessionId,
- refMap,
- selector,
- value,
- options,
- iframeSessions,
- ),
+ return this.#runAction(
+ selector,
+ (sessionId, refMap, iframeSessions) =>
+ fillInPage(
+ this.#services,
+ sessionId,
+ refMap,
+ selector,
+ value,
+ options,
+ iframeSessions,
+ ),
+ { actionName: "page.fill", timeout: options.timeout },
+ );
+ }
+
+ async focus(
+ selector: string,
+ options: { timeout?: number } = {},
+ ): Promise<PageActionReceipt> {
+ validatePublicApiOptions("Page.focus", options);
+ return this.#runAction(
+ selector,
+ (sessionId, refMap, iframeSessions) =>
+ focusInPage(
+ this.#services,
+ sessionId,
+ refMap,
+ selector,
+ iframeSessions,
+ ),
+ { actionName: "page.focus", timeout: options.timeout },
+ );
+ }
+
+ async press(
+ selector: string,
+ chord: string,
+ options: PagePressOptions = {},
+ ): Promise<PageActionReceipt> {
+ validatePublicApiOptions("Page.press", options);
+ const { timeout, ...pressOptions } = options;
+ return this.#runAction(
+ selector,
+ async (sessionId, refMap, iframeSessions) => {
+ await focusInPage(
+ this.#services,
+ sessionId,
+ refMap,
+ selector,
+ iframeSessions,
+ );
+ await this.keyboard.pressInSession(sessionId, chord, pressOptions);
+ },
+ {
+ actionName: "page.press",
+ guardFileChooser: true,
+ timeout,
+ },
);
}
@@ -1338,15 +1423,18 @@ class Page {
selector: string,
path: string | string[],
): Promise<PageActionReceipt> {
- return this.#runAction(selector, (sessionId, refMap, iframeSessions) =>
- setInputFilesInPage(
- this.#services,
- sessionId,
- refMap,
- selector,
- path,
- iframeSessions,
- ),
+ return this.#runAction(
+ selector,
+ (sessionId, refMap, iframeSessions) =>
+ setInputFilesInPage(
+ this.#services,
+ sessionId,
+ refMap,
+ selector,
+ path,
+ iframeSessions,
+ ),
+ { actionName: "page.setInputFiles" },
);
}
@@ -1514,18 +1602,21 @@ class Page {
refMap: RefMap,
iframeSessions: Map<string, string>,
) => Promise<void>,
- guardFileChooser = false,
+ options: {
+ actionName?: string;
+ guardFileChooser?: boolean;
+ timeout?: number;
+ } = {},
): Promise<PageActionReceipt> {
const page = await this.#resolve();
const selectors = Array.isArray(selector) ? selector : [selector];
+ const timeoutMs = options.timeout ?? DEFAULT_PAGE_ACTION_TIMEOUT_MS;
+ const actionName = options.actionName ?? "page action";
const { receipt } = await this.#runActionBoundary(
page,
async (sessionId) => {
- for (
- let attempt = 1;
- attempt <= PAGE_ACTION_RESOLUTION_ATTEMPTS;
- attempt += 1
- ) {
+ const deadline = this.#services.now() + timeoutMs;
+ while (true) {
try {
const refMap = await this.#refMapForAction(page, ...selectors);
const iframeSessions = await this.#services.ensureFrameSessions(
@@ -1535,17 +1626,20 @@ class Page {
return;
} catch (error) {
if (!isRetryableElementStateError(error)) throw error;
- if (attempt === PAGE_ACTION_RESOLUTION_ATTEMPTS) {
+ const remainingMs = deadline - this.#services.now();
+ if (remainingMs <= 0) {
throw new ElementResolutionError(
- `The page state changed while resolving this action after ${attempt} attempts: ${error.message}. Take a new snapshot and use a current selector.`,
+ `${actionName} timed out after ${timeoutMs}ms: ${error.message}`,
"transient",
);
}
- await this.#services.sleep(PAGE_ACTION_RESOLUTION_RETRY_MS);
+ await this.#services.sleep(
+ Math.min(PAGE_ACTION_RESOLUTION_RETRY_MS, remainingMs),
+ );
}
}
},
- guardFileChooser,
+ options.guardFileChooser,
);
return receipt;
}
diff --git a/package/ego-browser/src/public-api-schema.test.mjs b/package/ego-browser/src/public-api-schema.test.mjs
index 9781e6f..f503485 100644
--- a/package/ego-browser/src/public-api-schema.test.mjs
+++ b/package/ego-browser/src/public-api-schema.test.mjs
@@ -23,7 +23,10 @@ test("the public API schema contains the v2 entry points and object methods", ()
"Page.targetId",
"Page.waitForURL",
"Page.waitForTimeout",
+ "Page.focus",
+ "Page.press",
"Page.keyboard.press",
+ "Page.keyboard.paste",
]) {
assert(names.has(name), `missing public API schema entry: ${name}`);
}
@@ -36,6 +39,8 @@ test("schema-driven option validation rejects unknown and invalid fields", () =>
button: "left",
clickCount: 2,
delay: 0,
+ force: true,
+ timeout: 500,
});
assert.throws(
@@ -66,4 +71,9 @@ test("the generated reference contains signatures and option descriptions", () =
);
assert.match(markdown, /`as` — Permanent Page label\.<br>`timeout`/);
assert.match(markdown, /Open and durably label a new Page/);
+ assert.match(
+ markdown,
+ /Maximum actionability wait in milliseconds; defaults to 3000/,
+ );
+ assert.match(markdown, /missing parent directories are created/);
});
diff --git a/package/ego-browser/src/public-api-schema.ts b/package/ego-browser/src/public-api-schema.ts
index 9cc99b2..129937a 100644
--- a/package/ego-browser/src/public-api-schema.ts
+++ b/package/ego-browser/src/public-api-schema.ts
@@ -33,12 +33,17 @@ const timeout = option(
"positiveMilliseconds",
"Maximum duration in milliseconds.",
);
+const actionTimeout = option(
+ "positiveMilliseconds",
+ "Maximum actionability wait in milliseconds; defaults to 3000.",
+);
const delay = option("nonNegativeNumber", "Input delay in milliseconds.");
const button = option("string", "Mouse button.", ["left", "middle", "right"]);
const position = option(
"point",
"CSS-pixel offset from the element's top-left corner.",
);
+const force = option("boolean", "Bypass pointer interception checks.");
/**
* Single source of truth for the v2 surface shown to Agents. Runtime option
@@ -212,7 +217,10 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [
signature: "await page.screenshot({ path?, fullPage?, clip?, raw? })",
summary: "Capture this Page to a PNG file.",
options: {
- path: option("string", "Absolute output path."),
+ path: option(
+ "string",
+ "Output path; missing parent directories are created.",
+ ),
fullPage: option("boolean", "Capture the full scrollable page."),
clip: option("clip", "CSS-pixel clipping rectangle."),
raw: option("boolean", "Bypass device-pixel-ratio correction."),
@@ -328,46 +336,64 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [
{
name: "Page.click",
signature:
- "await page.click(selector, { button?, clickCount?, delay?, position? })",
+ "await page.click(selector, { button?, clickCount?, delay?, position?, force?, timeout? })",
summary: "Click an element with native CDP input.",
options: {
button,
clickCount: option("positiveInteger", "Number of clicks."),
delay,
position,
+ force,
+ timeout: actionTimeout,
},
},
{
name: "Page.dblclick",
- signature: "await page.dblclick(selector, { button?, delay?, position? })",
+ signature:
+ "await page.dblclick(selector, { button?, delay?, position?, force?, timeout? })",
summary: "Double-click an element with native CDP input.",
- options: { button, delay, position },
+ options: { button, delay, position, force, timeout: actionTimeout },
},
{
name: "Page.hover",
- signature: "await page.hover(selector, { position? })",
+ signature: "await page.hover(selector, { position?, force?, timeout? })",
summary: "Move the mouse over an element.",
- options: { position },
+ options: { position, force, timeout: actionTimeout },
},
{
name: "Page.dragAndDrop",
signature:
- "await page.dragAndDrop(source, target, { button?, sourcePosition?, targetPosition? })",
+ "await page.dragAndDrop(source, target, { button?, sourcePosition?, targetPosition?, force?, timeout? })",
summary: "Drag from one element to another.",
options: {
button,
sourcePosition: position,
targetPosition: position,
+ force,
+ timeout: actionTimeout,
},
},
{
name: "Page.fill",
- signature: "await page.fill(selector, value, { clearFirst? })",
+ signature: "await page.fill(selector, value, { clearFirst?, timeout? })",
summary: "Focus and fill an input-like element, then verify its value.",
options: {
clearFirst: option("boolean", "Clear the current value before filling."),
+ timeout: actionTimeout,
},
},
+ {
+ name: "Page.focus",
+ signature: "await page.focus(selector, { timeout? })",
+ summary: "Resolve one element and focus it.",
+ options: { timeout: actionTimeout },
+ },
+ {
+ name: "Page.press",
+ signature: "await page.press(selector, chord, { delay?, timeout? })",
+ summary: "Focus one element and press a key or shortcut chord.",
+ options: { delay, timeout: actionTimeout },
+ },
{
name: "Page.setInputFiles",
signature: "await page.setInputFiles(selector, pathOrPaths)",
@@ -479,6 +505,12 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [
signature: "await page.keyboard.insertText(text)",
summary: "Insert text without synthesizing key presses.",
},
+ {
+ name: "Page.keyboard.paste",
+ signature: "await page.keyboard.paste(text)",
+ summary:
+ "Paste text into the focused element and restore the user clipboard.",
+ },
] as const;
const entriesByName = new Map(
diff --git a/skills/ego-browser/SKILL.md b/skills/ego-browser/SKILL.md
index 903ae5a..9e7967d 100644
--- a/skills/ego-browser/SKILL.md
+++ b/skills/ego-browser/SKILL.md
@@ -133,6 +133,8 @@ await page.dragAndDrop(source, target, {
targetPosition,
});
await page.fill(selector, value, { clearFirst });
+await page.focus(selector);
+await page.press(selector, chord, { delay });
await page.scrollBy(deltaY, { deltaX, behavior });
await page.setInputFiles(selector, pathOrPaths);
const chooserPromise = page.waitForFileChooser({ timeout });
@@ -147,6 +149,7 @@ await page.mouse.wheel(deltaX, deltaY);
await page.keyboard.down(key);
await page.keyboard.up(key);
await page.keyboard.press(chord, { delay });
+await page.keyboard.paste(text);
await page.keyboard.type(text, { delay });
await page.keyboard.insertText(text);
```
@@ -178,6 +181,9 @@ Element actions accept:
- `xpath=...`
- raw CSS selectors
+Every selector action requires exactly one match. Narrow an ambiguous selector
+instead of relying on the first matching element.
+
Unquoted text locators normalize whitespace, ignore case, and match a substring;
quote the value for an exact, case-sensitive match, such as
`text="Save changes"`. A text locator selects the smallest matching element and
@@ -206,14 +212,17 @@ spreadsheets, maps, and other interfaces that lack useful DOM semantics:
```js
const path = await page.screenshot({ path: "/absolute/path/before.png" });
await page.mouse.click(420, 260);
-await page.keyboard.type("hello");
+await page.keyboard.paste("hello\tworld");
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. Low-level mouse and keyboard methods
-do not return action receipts, so verify their effect explicitly.
+`ControlOrMeta` for portable shortcuts. Verify coordinate and raw keyboard
+input explicitly.
+
+`keyboard.paste()` is an ego-browser convenience for ordinary paste behavior.
+It restores the user's clipboard after sending the native paste shortcut.
For rich-text editors and editable table cells, verify the first edit. If
`fill()` says the target rejected the text, click it, use `page.keyboard`, and
diff --git a/skills/ego-browser/references/api.md b/skills/ego-browser/references/api.md
index 7523d62..0ef49d7 100644
--- a/skills/ego-browser/references/api.md
+++ b/skills/ego-browser/references/api.md
@@ -37,35 +37,37 @@ High-level Page actions return a receipt that may contain `popups` or a synchron
## Page
-| API | Options | Purpose |
-| --------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
-| `page.label` | — | Durable Page label used to restore the tab across rounds. |
-| `page.spaceId` | — | Numeric identifier of the Page's task space. |
-| `page.openedBy` | — | Conservative origin attribution for this Page. |
-| `page.targetId` | — | Internal browser target identifier for advanced Target-domain CDP only. |
-| `await page.goto(url, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Navigate this Page in place. |
-| `await page.snapshot({ scope?, includeActionMarks?, includeStableLocator? })` | `scope` (full_page, only_within_viewport) — Snapshot scope; defaults to only_within_viewport.<br>`includeActionMarks` — Include action marks.<br>`includeStableLocator` — Include stable locators. | Return a semantic snapshot of the current viewport with Page provenance. |
-| `await page.screenshot({ path?, fullPage?, clip?, raw? })` | `path` — Absolute output path.<br>`fullPage` — Capture the full scrollable page.<br>`clip` — CSS-pixel clipping rectangle.<br>`raw` — Bypass device-pixel-ratio correction. | Capture this Page to a PNG file. |
-| `await page.url()` | — | Read this Page's current URL. |
-| `await page.waitForURL(urlOrRegExp, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Wait for an exact URL or regular-expression match. |
-| `await page.waitForTimeout(timeout)` | — | Wait a fixed number of milliseconds without activating this Page. |
-| `await page.title()` | — | Read this Page's current title. |
-| `await page.info()` | — | Read URL, title, viewport, scroll, and dialog state. |
-| `await page.evaluate(fnOrString, argument?)` | — | Run JavaScript in this Page with JSON-serializable data. |
-| `await page.fetch(url, options?)` | `timeout` — Maximum duration in milliseconds.<br>`method` — HTTP method.<br>`headers` — Request headers.<br>`body` — Request body.<br>`cache` (default, no-store, reload, no-cache, force-cache, only-if-cached) — Fetch cache mode.<br>`credentials` (omit, same-origin, include) — Fetch credentials mode.<br>`integrity` — Subresource integrity value.<br>`keepalive` — Allow the request to outlive the page.<br>`mode` (cors, no-cors, same-origin) — Fetch request mode.<br>`redirect` (follow, error, manual) — Redirect handling mode.<br>`referrer` — Request referrer.<br>`referrerPolicy` — Request referrer policy. | Run window.fetch in this Page and return a structured response. |
-| `await page.cdp(method, params?, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Send a CDP command through this Page's target session. |
-| `await page.waitForSelector(selector, { timeout?, state? })` | `timeout` — Maximum duration in milliseconds.<br>`state` (attached, detached, visible, hidden) — Required element state. | Wait for an element state in this Page. |
-| `await page.waitForLoadState(state, { timeout?, idleMs? })` | `timeout` — Maximum duration in milliseconds.<br>`idleMs` — Required network-idle window in milliseconds. | Wait for DOM content, load, or network-idle state. |
-| `await page.events()` | — | Read and clear CDP events buffered for this Page. |
-| `await page.click(selector, { button?, clickCount?, delay?, position? })` | `button` (left, middle, right) — Mouse button.<br>`clickCount` — Number of clicks.<br>`delay` — Input delay in milliseconds.<br>`position` — CSS-pixel offset from the element's top-left corner. | Click an element with native CDP input. |
-| `await page.dblclick(selector, { button?, delay?, position? })` | `button` (left, middle, right) — Mouse button.<br>`delay` — Input delay in milliseconds.<br>`position` — CSS-pixel offset from the element's top-left corner. | Double-click an element with native CDP input. |
-| `await page.hover(selector, { position? })` | `position` — CSS-pixel offset from the element's top-left corner. | Move the mouse over an element. |
-| `await page.dragAndDrop(source, target, { button?, sourcePosition?, targetPosition? })` | `button` (left, middle, right) — Mouse button.<br>`sourcePosition` — CSS-pixel offset from the element's top-left corner.<br>`targetPosition` — CSS-pixel offset from the element's top-left corner. | Drag from one element to another. |
-| `await page.fill(selector, value, { clearFirst? })` | `clearFirst` — Clear the current value before filling. | Focus and fill an input-like element, then verify its value. |
-| `await page.setInputFiles(selector, pathOrPaths)` | — | Set files on a file input without opening the system chooser. |
-| `page.waitForFileChooser({ timeout? })` | `timeout` — Maximum duration in milliseconds. | Wait for a dynamically created file chooser. |
-| `await page.scrollBy(deltaY, { deltaX?, behavior? })` | `deltaX` — Horizontal CSS-pixel delta.<br>`behavior` (auto, instant, smooth) — Scroll behavior. | Scroll this Page by CSS-pixel deltas. |
-| `await page.close()` | — | Close this Page after confirming its tab disappeared. |
+| API | Options | Purpose |
+| --------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
+| `page.label` | — | Durable Page label used to restore the tab across rounds. |
+| `page.spaceId` | — | Numeric identifier of the Page's task space. |
+| `page.openedBy` | — | Conservative origin attribution for this Page. |
+| `page.targetId` | — | Internal browser target identifier for advanced Target-domain CDP only. |
+| `await page.goto(url, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Navigate this Page in place. |
+| `await page.snapshot({ scope?, includeActionMarks?, includeStableLocator? })` | `scope` (full_page, only_within_viewport) — Snapshot scope; defaults to only_within_viewport.<br>`includeActionMarks` — Include action marks.<br>`includeStableLocator` — Include stable locators. | Return a semantic snapshot of the current viewport with Page provenance. |
+| `await page.screenshot({ path?, fullPage?, clip?, raw? })` | `path` — Output path; missing parent directories are created.<br>`fullPage` — Capture the full scrollable page.<br>`clip` — CSS-pixel clipping rectangle.<br>`raw` — Bypass device-pixel-ratio correction. | Capture this Page to a PNG file. |
+| `await page.url()` | — | Read this Page's current URL. |
+| `await page.waitForURL(urlOrRegExp, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Wait for an exact URL or regular-expression match. |
+| `await page.waitForTimeout(timeout)` | — | Wait a fixed number of milliseconds without activating this Page. |
+| `await page.title()` | — | Read this Page's current title. |
+| `await page.info()` | — | Read URL, title, viewport, scroll, and dialog state. |
+| `await page.evaluate(fnOrString, argument?)` | — | Run JavaScript in this Page with JSON-serializable data. |
+| `await page.fetch(url, options?)` | `timeout` — Maximum duration in milliseconds.<br>`method` — HTTP method.<br>`headers` — Request headers.<br>`body` — Request body.<br>`cache` (default, no-store, reload, no-cache, force-cache, only-if-cached) — Fetch cache mode.<br>`credentials` (omit, same-origin, include) — Fetch credentials mode.<br>`integrity` — Subresource integrity value.<br>`keepalive` — Allow the request to outlive the page.<br>`mode` (cors, no-cors, same-origin) — Fetch request mode.<br>`redirect` (follow, error, manual) — Redirect handling mode.<br>`referrer` — Request referrer.<br>`referrerPolicy` — Request referrer policy. | Run window.fetch in this Page and return a structured response. |
+| `await page.cdp(method, params?, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Send a CDP command through this Page's target session. |
+| `await page.waitForSelector(selector, { timeout?, state? })` | `timeout` — Maximum duration in milliseconds.<br>`state` (attached, detached, visible, hidden) — Required element state. | Wait for an element state in this Page. |
+| `await page.waitForLoadState(state, { timeout?, idleMs? })` | `timeout` — Maximum duration in milliseconds.<br>`idleMs` — Required network-idle window in milliseconds. | Wait for DOM content, load, or network-idle state. |
+| `await page.events()` | — | Read and clear CDP events buffered for this Page. |
+| `await page.click(selector, { button?, clickCount?, delay?, position?, force?, timeout? })` | `button` (left, middle, right) — Mouse button.<br>`clickCount` — Number of clicks.<br>`delay` — Input delay in milliseconds.<br>`position` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Click an element with native CDP input. |
+| `await page.dblclick(selector, { button?, delay?, position?, force?, timeout? })` | `button` (left, middle, right) — Mouse button.<br>`delay` — Input delay in milliseconds.<br>`position` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Double-click an element with native CDP input. |
+| `await page.hover(selector, { position?, force?, timeout? })` | `position` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Move the mouse over an element. |
+| `await page.dragAndDrop(source, target, { button?, sourcePosition?, targetPosition?, force?, timeout? })` | `button` (left, middle, right) — Mouse button.<br>`sourcePosition` — CSS-pixel offset from the element's top-left corner.<br>`targetPosition` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Drag from one element to another. |
+| `await page.fill(selector, value, { clearFirst?, timeout? })` | `clearFirst` — Clear the current value before filling.<br>`timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Focus and fill an input-like element, then verify its value. |
+| `await page.focus(selector, { timeout? })` | `timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Resolve one element and focus it. |
+| `await page.press(selector, chord, { delay?, timeout? })` | `delay` — Input delay in milliseconds.<br>`timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Focus one element and press a key or shortcut chord. |
+| `await page.setInputFiles(selector, pathOrPaths)` | — | Set files on a file input without opening the system chooser. |
+| `page.waitForFileChooser({ timeout? })` | `timeout` — Maximum duration in milliseconds. | Wait for a dynamically created file chooser. |
+| `await page.scrollBy(deltaY, { deltaX?, behavior? })` | `deltaX` — Horizontal CSS-pixel delta.<br>`behavior` (auto, instant, smooth) — Scroll behavior. | Scroll this Page by CSS-pixel deltas. |
+| `await page.close()` | — | Close this Page after confirming its tab disappeared. |
## Page.mouse
@@ -79,10 +81,11 @@ High-level Page actions return a receipt that may contain `popups` or a synchron
## Page.keyboard
-| API | Options | Purpose |
-| ---------------------------------------------- | -------------------------------------- | --------------------------------------------------- |
-| `await page.keyboard.down(key)` | — | Press and hold a keyboard key. |
-| `await page.keyboard.up(key)` | — | Release a keyboard key. |
-| `await page.keyboard.press(chord, { delay? })` | `delay` — Input delay in milliseconds. | Press and release a key or portable shortcut chord. |
-| `await page.keyboard.type(text, { delay? })` | `delay` — Input delay in milliseconds. | Type text using physical keys where possible. |
-| `await page.keyboard.insertText(text)` | — | Insert text without synthesizing key presses. |
+| API | Options | Purpose |
+| ---------------------------------------------- | -------------------------------------- | ------------------------------------------------------------------- |
+| `await page.keyboard.down(key)` | — | Press and hold a keyboard key. |
+| `await page.keyboard.up(key)` | — | Release a keyboard key. |
+| `await page.keyboard.press(chord, { delay? })` | `delay` — Input delay in milliseconds. | Press and release a key or portable shortcut chord. |
+| `await page.keyboard.type(text, { delay? })` | `delay` — Input delay in milliseconds. | Type text using physical keys where possible. |
+| `await page.keyboard.insertText(text)` | — | Insert text without synthesizing key presses. |
+| `await page.keyboard.paste(text)` | — | Paste text into the focused element and restore the user clipboard. |