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.

expand cross-platform workflow coverage

Autecb27d66f5e64
diff --git a/docs/runtime-v2-architecture.md b/docs/runtime-v2-architecture.md
index ae9a2e1..d191fca 100644
--- a/docs/runtime-v2-architecture.md
+++ b/docs/runtime-v2-architecture.md
@@ -281,6 +281,14 @@ await page.keyboard.insertText(text)
键盘和鼠标状态保存在 Page 对象中。`ControlOrMeta` 会按当前平台映射;macOS
编辑快捷键通过 CDP editing commands 发送。
+Page 对象只在当前脚本轮次内存在,因此鼠标位置不会跨轮保留。新一轮取得 Page
+后,`page.mouse` 从 `(0, 0)` 开始;调用 `wheel()` 前应先用 `move()` 把鼠标移到
+实际要滚动的区域。`ControlOrMeta` 用于选择、复制、粘贴和撤销等跨平台编辑
+快捷键。文档首尾按平台使用原生组合:macOS 使用
+`Meta+ArrowUp` / `Meta+ArrowDown`,Windows 使用
+`Control+Home` / `Control+End`。单元测试固定覆盖 `darwin` 和 `win32` 两套映射,
+真实浏览器 E2E 则验证当前宿主平台。
+
新版没有 `page.keyboard.dispatch()`。它只能在页面中合成
`KeyboardEvent`,`isTrusted=false`,也不能可靠触发剪贴板和浏览器默认行为。
确实需要合成事件时,调用方可以显式使用 `page.evaluate()`。
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 fdb70c0..dbe7323 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
@@ -22,6 +22,13 @@ import {
pageLabelHardStopRestoreCase,
pageLabelRestoreCase,
} from "./page-labels.mjs";
+import {
+ portableKeyboardWorkflowCase,
+ pureCdpWorkflowCase,
+ snapshotWorkflowCase,
+ v1V2ActionParityCase,
+ visualWorkflowCase,
+} from "./workflow-chains.mjs";
export const e2eCases = [
{ name: "environment initialization", body: environmentCase },
@@ -54,4 +61,9 @@ export const e2eCases = [
{ name: "page complex evaluate", body: pageComplexEvaluateCase },
{ name: "page fetch", body: pageFetchCase },
{ name: "page actions and popup adoption", body: pageActionsAndPopupCase },
+ { name: "v1 and v2 action parity", body: v1V2ActionParityCase },
+ { name: "portable keyboard workflow", body: portableKeyboardWorkflowCase },
+ { name: "pure CDP workflow", body: pureCdpWorkflowCase },
+ { name: "snapshot workflow", body: snapshotWorkflowCase },
+ { name: "visual workflow", body: visualWorkflowCase },
];
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs
index 2a4d828..1202ce4 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs
@@ -478,7 +478,20 @@ export function pageActionsAndPopupCase() {
await source.evaluate("window.scrollTo(0, 0)");
const scrolled = await source.scrollBy(300);
assert(scrolled.y > 0, "page.scrollBy scrolls the addressed document");
+ const innerScrollPoint = await source.evaluate(() => {
+ const element = document.querySelector("#inner-scroll");
+ element.scrollIntoView({ block: "center" });
+ element.scrollTop = 0;
+ const rect = element.getBoundingClientRect();
+ return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
+ });
+ await source.mouse.move(innerScrollPoint.x, innerScrollPoint.y);
await source.mouse.wheel(0, 120);
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ assert(
+ await source.evaluate("document.querySelector('#inner-scroll').scrollTop > 0"),
+ "page.mouse.wheel scrolls the inner container under the current pointer"
+ );
assertEqual((await currentTab()).targetId, source.targetId, "Page mouse methods keep their Page active");
await source.evaluate(() => {
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/workflow-chains.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/workflow-chains.mjs
new file mode 100644
index 0000000..c4b932d
--- /dev/null
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/workflow-chains.mjs
@@ -0,0 +1,317 @@
+export function v1V2ActionParityCase() {
+ return `
+ const task = await taskSpace(taskName);
+ const page = await task.newPage(baseUrl + "/?workflow=parity", {
+ as: "workflow-parity",
+ });
+
+ await page.evaluate(() => {
+ window.__parityEvents = [];
+ for (const type of [
+ "mousedown", "mouseup", "click", "keydown", "keyup",
+ "beforeinput", "input", "change"
+ ]) {
+ document.addEventListener(type, (event) => {
+ if (!window.__parityRecording) return;
+ window.__parityEvents.push({
+ type,
+ target: event.target.id || event.target.tagName,
+ trusted: event.isTrusted,
+ key: event.key || "",
+ inputType: event.inputType || "",
+ data: event.data ?? null,
+ });
+ }, true);
+ }
+ });
+
+ const beginRecording = () => page.evaluate(() => {
+ window.__parityEvents = [];
+ window.__parityRecording = true;
+ });
+ const finishRecording = () => page.evaluate(() => {
+ window.__parityRecording = false;
+ return window.__parityEvents;
+ });
+
+ await beginRecording();
+ await click("#click-button");
+ const legacyClickEvents = await finishRecording();
+ await beginRecording();
+ await page.click("#click-button");
+ const pageClickEvents = await finishRecording();
+ for (const events of [legacyClickEvents, pageClickEvents]) {
+ const clickSequence = events
+ .filter((event) => ["mousedown", "mouseup", "click"].includes(event.type))
+ .map((event) => event.type);
+ assertEqual(clickSequence.join(","), "mousedown,mouseup,click", "v1 and v2 click use the native pointer sequence");
+ assert(
+ events.filter((event) => event.type === "click").every((event) => event.trusted),
+ "v1 and v2 click reach the site as trusted events"
+ );
+ }
+
+ await page.evaluate(() => { document.querySelector("#text-input").value = "seed"; });
+ await beginRecording();
+ await fillInput("#text-input", "parity-value", { timeout: 3 });
+ const legacyFillEvents = await finishRecording();
+ const legacyValue = await page.evaluate("document.querySelector('#text-input').value");
+
+ await page.evaluate(() => { document.querySelector("#text-input").value = "seed"; });
+ await beginRecording();
+ await page.fill("#text-input", "parity-value");
+ const pageFillEvents = await finishRecording();
+ const pageValue = await page.evaluate("document.querySelector('#text-input').value");
+ assertEqual(legacyValue, "parity-value", "v1 fill keeps its user-visible result");
+ assertEqual(pageValue, legacyValue, "v2 fill matches the v1 user-visible value");
+ assert(
+ legacyFillEvents.some((event) => event.type === "input"),
+ "v1 fill still emits its compatibility input events"
+ );
+ assert(
+ pageFillEvents.some((event) => event.type === "input" && event.trusted),
+ "v2 fill emits native input"
+ );
+ assert(
+ pageFillEvents
+ .filter((event) => event.type === "input")
+ .every((event) => event.trusted),
+ "v2 fill does not add synthetic duplicate input events"
+ );
+
+ const prepareBackspace = () => page.evaluate(() => {
+ const input = document.querySelector("#text-input");
+ input.value = "abc";
+ input.focus();
+ input.setSelectionRange(3, 3);
+ window.__parityEvents = [];
+ window.__parityRecording = true;
+ });
+ await prepareBackspace();
+ await pressKey("Backspace");
+ const legacyKeyEvents = await finishRecording();
+ const legacyBackspaceValue = await page.evaluate("document.querySelector('#text-input').value");
+ await prepareBackspace();
+ await page.keyboard.press("Backspace");
+ const pageKeyEvents = await finishRecording();
+ const pageBackspaceValue = await page.evaluate("document.querySelector('#text-input').value");
+ assertEqual(legacyBackspaceValue, "ab", "v1 Backspace keeps its editing behavior");
+ assertEqual(pageBackspaceValue, legacyBackspaceValue, "v2 Backspace matches the v1 result");
+ for (const events of [legacyKeyEvents, pageKeyEvents]) {
+ assert(
+ events.some((event) => event.type === "keydown" && event.key === "Backspace" && event.trusted),
+ "v1 and v2 Backspace dispatch a trusted keydown"
+ );
+ }
+
+ await page.close();
+ `;
+}
+
+export function portableKeyboardWorkflowCase() {
+ return `
+ const task = await taskSpace(taskName);
+ const page = await task.newPage(baseUrl + "/?workflow=keyboard", {
+ as: "workflow-keyboard",
+ });
+
+ await page.fill("#text-input", "portable clipboard");
+ await page.keyboard.press("ControlOrMeta+A");
+ await page.keyboard.press("ControlOrMeta+C");
+ await page.evaluate(() => {
+ const target = document.querySelector("#append-input");
+ target.value = "";
+ target.focus();
+ });
+ await page.keyboard.press("ControlOrMeta+V");
+ assertEqual(
+ await page.evaluate("document.querySelector('#append-input').value"),
+ "portable clipboard",
+ "ControlOrMeta copy and paste use the current platform shortcut"
+ );
+ await page.keyboard.press("ControlOrMeta+Z");
+ assertEqual(
+ await page.evaluate("document.querySelector('#append-input').value"),
+ "",
+ "ControlOrMeta undo reverts the native paste"
+ );
+
+ const textLength = await page.evaluate(() => {
+ const area = document.querySelector("#text-area");
+ area.value = Array.from({ length: 40 }, (_, index) => "line " + index).join("\\n");
+ area.focus();
+ area.setSelectionRange(Math.floor(area.value.length / 2), Math.floor(area.value.length / 2));
+ return area.value.length;
+ });
+ const toEnd = process.platform === "darwin" ? "Meta+ArrowDown" : "Control+End";
+ const toStart = process.platform === "darwin" ? "Meta+ArrowUp" : "Control+Home";
+ await page.keyboard.press(toEnd);
+ assertEqual(
+ await page.evaluate("document.querySelector('#text-area').selectionStart"),
+ textLength,
+ "the host-platform document-end shortcut reaches the end"
+ );
+ await page.keyboard.press(toStart);
+ assertEqual(
+ await page.evaluate("document.querySelector('#text-area').selectionStart"),
+ 0,
+ "the host-platform document-start shortcut reaches the beginning"
+ );
+
+ await page.close();
+ `;
+}
+
+export function pureCdpWorkflowCase() {
+ return `
+ const task = await taskSpace(taskName);
+ const page = await task.newPage("about:blank", { as: "workflow-cdp" });
+ const destination = baseUrl + "/?workflow=cdp";
+
+ await page.cdp("Page.navigate", { url: destination }, { timeout: 5_000 });
+ let ready = false;
+ for (let attempt = 0; attempt < 40; attempt += 1) {
+ const response = await page.cdp(
+ "Runtime.evaluate",
+ { expression: "document.readyState", returnByValue: true },
+ { timeout: 2_000 }
+ );
+ if (response.result.value === "complete") {
+ ready = true;
+ break;
+ }
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+ assert(ready, "pure CDP navigation reaches a complete document");
+
+ const rectResponse = await page.cdp(
+ "Runtime.evaluate",
+ {
+ expression:
+ "(() => {" +
+ "const rect = document.querySelector('#click-button').getBoundingClientRect();" +
+ "return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };" +
+ "})()",
+ returnByValue: true,
+ },
+ { timeout: 2_000 }
+ );
+ const point = rectResponse.result.value;
+ await page.cdp("Input.dispatchMouseEvent", {
+ type: "mouseMoved", x: point.x, y: point.y, button: "none", buttons: 0,
+ });
+ await page.cdp("Input.dispatchMouseEvent", {
+ type: "mousePressed", x: point.x, y: point.y, button: "left", buttons: 1, clickCount: 1,
+ });
+ await page.cdp("Input.dispatchMouseEvent", {
+ type: "mouseReleased", x: point.x, y: point.y, button: "left", buttons: 0, clickCount: 1,
+ });
+ const stateResponse = await page.cdp(
+ "Runtime.evaluate",
+ {
+ expression:
+ "({ clicks: window.__fixtureState.clicks," +
+ "trusted: window.__fixtureState.pointerEvents.findLast(" +
+ "event => event.type === 'click')?.trusted })",
+ returnByValue: true,
+ },
+ { timeout: 2_000 }
+ );
+ assertEqual(stateResponse.result.value.clicks, 1, "pure CDP input activates the fixture action");
+ assertEqual(stateResponse.result.value.trusted, true, "pure CDP input remains trusted");
+
+ const concurrent = await Promise.all([
+ page.cdp("Runtime.evaluate", { expression: "21 * 2", returnByValue: true }),
+ page.cdp("Runtime.evaluate", { expression: "6 * 7", returnByValue: true }),
+ ]);
+ assertEqual(concurrent[0].result.value, 42, "the first concurrent CDP Promise keeps its response");
+ assertEqual(concurrent[1].result.value, 42, "the second concurrent CDP Promise keeps its response");
+
+ const screenshot = await page.cdp("Page.captureScreenshot", { format: "png" }, { timeout: 5_000 });
+ assert(screenshot.data.length > 100, "pure CDP capture returns PNG data");
+ await assertRejects(
+ () => page.cdp(
+ "Runtime.evaluate",
+ {
+ expression: "new Promise(resolve => setTimeout(() => resolve('late'), 1000))",
+ awaitPromise: true,
+ },
+ { timeout: 50 }
+ ),
+ "CDP request timed out: Runtime.evaluate",
+ "pure CDP Promise enforces its timeout"
+ );
+
+ await page.close();
+ `;
+}
+
+export function snapshotWorkflowCase() {
+ return `
+ const task = await taskSpace(taskName);
+ const first = await task.newPage(baseUrl + "/?workflow=snapshot-a", {
+ as: "workflow-snapshot-a",
+ });
+ const second = await task.newPage(baseUrl + "/?workflow=snapshot-b", {
+ as: "workflow-snapshot-b",
+ });
+
+ const firstSnapshot = await first.snapshot();
+ const secondSnapshot = await second.snapshot();
+ const refFor = (snapshot) => {
+ const line = snapshot.split("\\n").find((entry) => entry.includes("Increment counter"));
+ const match = line && line.match(/\\[ref=([0-9]+)/);
+ if (!match) throw new Error("snapshot workflow did not expose the click ref");
+ return "@" + match[1];
+ };
+ const firstRef = refFor(firstSnapshot);
+ const secondRef = refFor(secondSnapshot);
+ await first.click(firstRef);
+ assertEqual(await first.evaluate("window.__fixtureState.clicks"), 1, "the first snapshot ref acts on Page A");
+ assertEqual(await second.evaluate("window.__fixtureState.clicks"), 0, "the Page A ref does not affect Page B");
+ await second.click(secondRef);
+ assertEqual(await second.evaluate("window.__fixtureState.clicks"), 1, "the second snapshot ref acts on Page B");
+
+ await first.goto(baseUrl + "/nav-target?workflow=snapshot-navigation");
+ await assertRejects(
+ () => first.click(firstRef),
+ "Unknown ref",
+ "navigation invalidates refs from the previous document"
+ );
+
+ await first.close();
+ await second.close();
+ `;
+}
+
+export function visualWorkflowCase() {
+ return `
+ const task = await taskSpace(taskName);
+ const page = await task.newPage(baseUrl + "/visual", { as: "workflow-visual" });
+ const snapshot = await page.snapshot();
+ assert(
+ !snapshot.includes("CLICK") && !snapshot.includes("DONE"),
+ "the canvas-only control is intentionally absent from the semantic snapshot"
+ );
+
+ const beforePath = join(artifactDir, "visual-before.png");
+ const afterPath = join(artifactDir, "visual-after.png");
+ await page.screenshot(beforePath, { full: false });
+ await page.mouse.move(160, 150);
+ await page.mouse.click(160, 150);
+ await page.screenshot(afterPath, { full: false });
+
+ const before = await readFile(beforePath);
+ const after = await readFile(afterPath);
+ assert(before.length > 100 && after.length > 100, "visual workflow captures both screenshots");
+ assert(!before.equals(after), "the coordinate action changes the rendered screenshot");
+ const visualState = await page.evaluate(() => ({
+ clicks: window.__visualClicks,
+ trusted: window.__visualTrusted,
+ }));
+ assertEqual(visualState.clicks, 1, "the screenshot-derived coordinate activates the canvas target");
+ assertEqual(visualState.trusted, true, "the visual coordinate action uses trusted mouse input");
+
+ await page.close();
+ `;
+}
diff --git a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
index b5d70e2..ed7c7d3 100644
--- a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
@@ -162,6 +162,11 @@ export async function startFixtureServer(taskName) {
res.end(pageHtml("secondary"));
return;
}
+ if (url.pathname === "/visual") {
+ res.writeHead(200, { "content-type": "text/html" });
+ res.end(visualPageHtml());
+ return;
+ }
if (url.pathname === "/slow-page") {
const delayMs = Number(url.searchParams.get("ms") || 250);
setTimeout(() => {
@@ -341,6 +346,7 @@ function pageHtml(kind) {
detail: event.detail,
x: event.clientX,
y: event.clientY,
+ trusted: event.isTrusted,
});
},
true,
@@ -480,3 +486,48 @@ function pageHtml(kind) {
</body>
</html>`;
}
+
+function visualPageHtml() {
+ return `<!doctype html>
+<html>
+ <head>
+ <meta charset="utf-8">
+ <title>ego-lite visual fixture</title>
+ <style>
+ html, body { height: 100%; margin: 0; overflow: hidden; }
+ body { background: #f4f6fa; }
+ canvas { left: 100px; position: fixed; top: 100px; }
+ </style>
+ </head>
+ <body>
+ <canvas id="visual-canvas" width="320" height="180"></canvas>
+ <script>
+ const canvas = document.querySelector("#visual-canvas");
+ const context = canvas.getContext("2d");
+ window.__visualClicks = 0;
+
+ function draw(active) {
+ context.fillStyle = "#172033";
+ context.fillRect(0, 0, canvas.width, canvas.height);
+ context.fillStyle = active ? "#2563eb" : "#dc2626";
+ context.fillRect(20, 20, 120, 60);
+ context.fillStyle = "#ffffff";
+ context.font = "20px sans-serif";
+ context.fillText(active ? "DONE" : "CLICK", 45, 58);
+ }
+
+ canvas.addEventListener("click", (event) => {
+ const rect = canvas.getBoundingClientRect();
+ const x = event.clientX - rect.left;
+ const y = event.clientY - rect.top;
+ if (x >= 20 && x <= 140 && y >= 20 && y <= 80) {
+ window.__visualClicks += 1;
+ window.__visualTrusted = event.isTrusted;
+ draw(true);
+ }
+ });
+ draw(false);
+ </script>
+ </body>
+</html>`;
+}
diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjs
index 87f0278..11c9c52 100644
--- a/package/ego-browser/src/page-model.test.mjs
+++ b/package/ego-browser/src/page-model.test.mjs
@@ -1091,6 +1091,77 @@ test("Page keyboard mirrors Playwright key state and the US layout", async () =>
});
});
+test("Page keyboard maps portable editing shortcuts on macOS", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a", { platform: "darwin" });
+ const page = await task.newPage("https://example.test/first");
+
+ await page.keyboard.press("ControlOrMeta+A");
+ await page.keyboard.press("ControlOrMeta+C");
+ await page.keyboard.press("ControlOrMeta+V");
+ await page.keyboard.press("ControlOrMeta+Z");
+ await page.keyboard.press("Meta+ArrowUp");
+ await page.keyboard.press("Meta+ArrowDown");
+
+ const keyDowns = fixture.calls
+ .filter(
+ ([kind, method, params]) =>
+ kind === "cdp" &&
+ method === "Input.dispatchKeyEvent" &&
+ params.type === "rawKeyDown",
+ )
+ .map(([, , params]) => params);
+ const commandFor = (code) =>
+ keyDowns.find((params) => params.code === code)?.commands;
+
+ assert.deepEqual(commandFor("KeyA"), ["selectAll"]);
+ assert.deepEqual(commandFor("KeyC"), ["copy"]);
+ assert.deepEqual(commandFor("KeyV"), ["paste"]);
+ assert.deepEqual(commandFor("KeyZ"), ["undo"]);
+ assert.deepEqual(commandFor("ArrowUp"), ["moveToBeginningOfDocument"]);
+ assert.deepEqual(commandFor("ArrowDown"), ["moveToEndOfDocument"]);
+ assert(
+ keyDowns
+ .filter((params) => params.code?.startsWith("Key"))
+ .every((params) => params.modifiers === 4),
+ "ControlOrMeta must resolve to Meta on macOS",
+ );
+ });
+});
+
+test("Page keyboard maps portable editing shortcuts on Windows", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a", { platform: "win32" });
+ const page = await task.newPage("https://example.test/first");
+
+ await page.keyboard.press("ControlOrMeta+A");
+ await page.keyboard.press("ControlOrMeta+C");
+ await page.keyboard.press("ControlOrMeta+V");
+ await page.keyboard.press("ControlOrMeta+Z");
+ await page.keyboard.press("Control+Home");
+ await page.keyboard.press("Control+End");
+
+ const keyDowns = fixture.calls
+ .filter(
+ ([kind, method, params]) =>
+ kind === "cdp" &&
+ method === "Input.dispatchKeyEvent" &&
+ params.type === "rawKeyDown",
+ )
+ .map(([, , params]) => params);
+ for (const code of ["KeyA", "KeyC", "KeyV", "KeyZ", "Home", "End"]) {
+ const keyDown = keyDowns.find((params) => params.code === code);
+ assert(keyDown, `${code} must be dispatched on Windows`);
+ assert.equal(keyDown.modifiers, 2, `${code} must carry Control`);
+ assert.deepEqual(
+ keyDown.commands,
+ [],
+ "Windows relies on Chromium's native shortcut handling",
+ );
+ }
+ });
+});
+
test("Page keyboard type emits physical keys when possible and inserts unsupported text", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a", { platform: "darwin" });