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 ego-browser real browser E2E coverage

Tachikoma3c5538e89624
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/adversarial.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/adversarial.mjs
new file mode 100644
index 0000000..bd924f7
--- /dev/null
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/adversarial.mjs
@@ -0,0 +1,63 @@
+import { homeCase, buttonRefSetup } from "./shared.mjs";
+
+export const adversarialCases = [
+ {
+ name: "adversarial stale ref falls back after replacement",
+ body: homeCase(`
+ ${buttonRefSetup()}
+ await js(\`
+ const oldButton = document.querySelector('#click-button');
+ const replacement = oldButton.cloneNode(true);
+ replacement.addEventListener('click', (event) => {
+ window.__fixtureState.clicks += 11;
+ window.__fixtureState.lastClickDetail = event.detail;
+ document.querySelector('#click-count').textContent = String(window.__fixtureState.clicks);
+ });
+ oldButton.replaceWith(replacement);
+ return true;
+ \`);
+ await click("@" + buttonRef);
+ await waitForJsValue(
+ "window.__fixtureState.clicks",
+ 11,
+ "stale backend ref falls back to the replacement with the same role/name"
+ );
+ `),
+ },
+ {
+ name: "adversarial js serialization boundaries",
+ body: homeCase(`
+ assert(Number.isNaN(await js("NaN")), "js decodes NaN unserializable value");
+ assertEqual(await js("Infinity"), Infinity, "js decodes positive Infinity");
+ assertEqual(await js("-Infinity"), -Infinity, "js decodes negative Infinity");
+ assert(Object.is(await js("-0"), -0), "js preserves negative zero");
+ assert(
+ (await js("12345678901234567890n")) === 12345678901234567890n,
+ "js decodes BigInt unserializable value"
+ );
+ `),
+ },
+ {
+ name: "adversarial js wrapping boundaries",
+ body: homeCase(`
+ assertEqual(await js("Promise.resolve(42)"), 42, "js awaits promise values");
+ assertEqual(await js("'return is inside a string'"), "return is inside a string", "js does not wrap return inside strings");
+ assertEqual(await js("// return is inside a comment\\n1 + 4"), 5, "js does not wrap return inside comments");
+ assertEqual(await js("const returned = 1; returned + 1"), 2, "js does not treat returned as return keyword");
+ await assertRejects(
+ () => js("throw 'primitive boom'"),
+ "primitive boom",
+ "js reports thrown primitive values"
+ );
+ `),
+ },
+ {
+ name: "adversarial fetch origin follows current page",
+ body: homeCase(`
+ await gotoAndWait(baseUrl + "/nav-target", { timeout: 10 });
+ assertEqual(await browserFetch("/api/text", { timeout: 5 }), "server text fixture", "browserFetch resolves relative URLs against current page origin after navigation");
+ await gotoAndWait(baseUrl + "/", { timeout: 10 });
+ assertEqual(await browserFetch("/api/text", { timeout: 5 }), "server text fixture", "browserFetch still resolves after navigating back home");
+ `),
+ },
+];
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/canvas.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/canvas.mjs
new file mode 100644
index 0000000..affb91c
--- /dev/null
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/canvas.mjs
@@ -0,0 +1,135 @@
+import { homeCase } from "./shared.mjs";
+
+/* Canvas drawing helper: returns a drawAt function that maps canvas-relative
+ fractions (0–1) to viewport coordinates for dragMouse. This adapts to the
+ actual rendered canvas size instead of assuming fixed 400×300. */
+function canvasSetup() {
+ return `
+ const canvasRect = await js(\`(() => {
+ const c = document.querySelector("#draw-canvas");
+ const r = c.getBoundingClientRect();
+ return { left: r.left, top: r.top, w: r.width, h: r.height };
+ })()\`);
+ assert(canvasRect.w > 0 && canvasRect.h > 0, "canvas has non-zero rendered dimensions");
+ function drawAt(fx, fy) {
+ return [Math.round(canvasRect.left + canvasRect.w * fx), Math.round(canvasRect.top + canvasRect.h * fy)];
+ }
+ `;
+}
+
+/* Returns a JS expression string that checks if pixel at canvas-relative
+ fraction (fx, fy) has non-zero alpha (something was drawn there).
+ Converts fraction to integer pixel coordinates at evaluation time. */
+function pixelDrawn(fx, fy) {
+ return (
+ `(() => { const c = document.querySelector("#draw-canvas"); ` +
+ `const ctx = c.getContext("2d"); ` +
+ `const d = ctx.getImageData(` +
+ `Math.round(${fx} * c.width), Math.round(${fy} * c.height), 1, 1).data; ` +
+ `return d[3] > 0; })()`
+ );
+}
+
+export const canvasCases = [
+ {
+ name: "canvas draw single stroke",
+ body: homeCase(`
+ ${canvasSetup()}
+
+ /* Draw a horizontal line across the middle of the canvas. */
+ await dragMouse([drawAt(0.05, 0.5), drawAt(0.5, 0.5), drawAt(0.95, 0.5)], { delayMs: 10 });
+
+ await waitForJsValue("window.__fixtureState.canvasStrokes", 1, "single drag creates one stroke");
+ await waitForJsCondition("window.__fixtureState.canvasPoints >= 3", "stroke has at least 3 points");
+ assertEqual(
+ await js("return window.__fixtureState.canvasDrawing"),
+ false,
+ "canvas drawing state resets after mouseup"
+ );
+
+ /* Verify pixels were drawn at three positions along the stroke path. */
+ assert(await js("return " + ${JSON.stringify(pixelDrawn(0.15, 0.5))}), "pixels drawn at stroke start region");
+ assert(await js("return " + ${JSON.stringify(pixelDrawn(0.5, 0.5))}), "pixels drawn at stroke midpoint");
+ assert(await js("return " + ${JSON.stringify(pixelDrawn(0.85, 0.5))}), "pixels drawn at stroke end region");
+
+ /* Verify the last recorded point is near the end of the stroke. */
+ const lastPoint = await js("return window.__fixtureState.canvasLastPoint");
+ const lastFrac = lastPoint.x / await js("return document.querySelector('#draw-canvas').width");
+ assert(lastFrac > 0.8, "canvas last point x is near stroke end");
+ `),
+ },
+ {
+ name: "canvas draw multiple strokes",
+ body: homeCase(`
+ ${canvasSetup()}
+
+ /* Stroke 1: horizontal line in the upper third. */
+ await dragMouse([drawAt(0.1, 0.25), drawAt(0.5, 0.25), drawAt(0.9, 0.25)], { delayMs: 15 });
+ await waitForJsValue("window.__fixtureState.canvasStrokes", 1, "first stroke registered");
+ assert(await js("return " + ${JSON.stringify(pixelDrawn(0.5, 0.25))}), "pixels drawn on first stroke path");
+
+ /* Stroke 2: horizontal line in the lower third. */
+ await wait(0.1);
+ await dragMouse([drawAt(0.1, 0.75), drawAt(0.5, 0.75), drawAt(0.9, 0.75)], { delayMs: 15 });
+ await waitForJsValue("window.__fixtureState.canvasStrokes", 2, "second stroke registered");
+ await waitForJsCondition("window.__fixtureState.canvasPoints >= 6", "two strokes have at least 6 points total");
+
+ /* Verify pixels on second stroke — check a small area around the expected point. */
+ const secondStrokeFound = await js(\`(() => {
+ const c = document.querySelector("#draw-canvas");
+ const ctx = c.getContext("2d");
+ const cx = Math.round(0.5 * c.width);
+ const cy = Math.round(0.75 * c.height);
+ for (let dy = -5; dy <= 5; dy++) {
+ const d = ctx.getImageData(cx, cy + dy, 1, 1).data;
+ if (d[3] > 0) return true;
+ }
+ return false;
+ })()\`);
+ assert(secondStrokeFound, "pixels drawn on second stroke path");
+
+ /* Verify a point between the strokes has no pixels (strokes don't bleed). */
+ const gapAlpha = await js(
+ "return document.querySelector('#draw-canvas').getContext('2d').getImageData(" +
+ "Math.round(document.querySelector('#draw-canvas').width / 2), " +
+ "Math.round(document.querySelector('#draw-canvas').height / 2), 1, 1).data[3]"
+ );
+ assertEqual(gapAlpha, 0, "no pixels between the two strokes at the gap");
+
+ /* Stroke 3: vertical line. */
+ await wait(0.1);
+ await dragMouse([drawAt(0.3, 0.1), drawAt(0.3, 0.5), drawAt(0.3, 0.9)], { delayMs: 15 });
+ await waitForJsValue("window.__fixtureState.canvasStrokes", 3, "third stroke registered");
+ assert(await js("return " + ${JSON.stringify(pixelDrawn(0.3, 0.5))}), "pixels drawn on vertical stroke");
+ `),
+ },
+ {
+ name: "canvas draw zigzag path",
+ body: homeCase(`
+ ${canvasSetup()}
+
+ /* Draw a zigzag with 5 points: left → right-up → left-down → right-up → right. */
+ await dragMouse(
+ [drawAt(0.08, 0.5), drawAt(0.3, 0.17), drawAt(0.5, 0.83), drawAt(0.75, 0.17), drawAt(0.93, 0.5)],
+ { delayMs: 15 }
+ );
+
+ await waitForJsValue("window.__fixtureState.canvasStrokes", 1, "zigzag is a single stroke");
+ await waitForJsCondition("window.__fixtureState.canvasPoints >= 5", "zigzag has at least 5 points");
+
+ /* Verify pixels at multiple segments of the zigzag path. */
+ assert(await js("return " + ${JSON.stringify(pixelDrawn(0.08, 0.5))}), "pixels at zigzag start");
+ assert(await js("return " + ${JSON.stringify(pixelDrawn(0.3, 0.17))}), "pixels at zigzag peak 1");
+ assert(await js("return " + ${JSON.stringify(pixelDrawn(0.5, 0.83))}), "pixels at zigzag valley");
+ assert(await js("return " + ${JSON.stringify(pixelDrawn(0.75, 0.17))}), "pixels at zigzag peak 2");
+ assert(await js("return " + ${JSON.stringify(pixelDrawn(0.93, 0.5))}), "pixels at zigzag end");
+
+ /* Verify drawing is complete. */
+ assertEqual(
+ await js("return window.__fixtureState.canvasDrawing"),
+ false,
+ "zigzag drawing state is complete"
+ );
+ `),
+ },
+];
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/environment.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/environment.mjs
index ffcafd1..4121755 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/environment.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/environment.mjs
@@ -17,7 +17,7 @@ export function environmentCase() {
assertEqual(task.name, taskName, "environment creates/selects isolated task space");
let home = await resetHome();
- assert(home.targetId, "environment opens a real fixture tab");
+ assert(typeof home.targetId === "string" && home.targetId.length > 0, "environment opens a real fixture tab with valid targetId");
const info = await pageInfo();
assertEqual(info.title, "ego-lite helper e2e", "environment page title is stable");
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 4aeb03d..24d004e 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
@@ -3,11 +3,25 @@ import { helperSurfaceCase } from "./helper-surface.mjs";
import { taskSpaceCase } from "./task-space.mjs";
import { navigationCase } from "./navigation.mjs";
import { observationCase } from "./observation.mjs";
-import { pointerCase } from "./pointer.mjs";
+import {
+ pointerClickCase,
+ pointerHoverDragCase,
+ pointerInteractionRegressionCase,
+ pointerValidationCase,
+ scrollHelpersCase,
+} from "./pointer.mjs";
import { keyboardCase } from "./keyboard.mjs";
import { keyboardRegressionCase } from "./keyboard-regression.mjs";
-import { runtimeCase } from "./runtime.mjs";
+import {
+ cdpJsHelpCase,
+ fetchHelpersCase,
+ waitHelpersCase,
+} from "./runtime.mjs";
import { runtimeRegressionCase } from "./runtime-regression.mjs";
+import { adversarialCases } from "./adversarial.mjs";
+import { workflowCases } from "./workflows.mjs";
+import { interactionsCases } from "./interactions.mjs";
+import { canvasCases } from "./canvas.mjs";
export const e2eCases = [
{ name: "environment initialization", body: environmentCase },
@@ -15,9 +29,22 @@ export const e2eCases = [
{ name: "task spaces and control", body: taskSpaceCase },
{ name: "navigation helpers", body: navigationCase },
{ name: "observation helpers", body: observationCase },
- { name: "pointer and scroll helpers", body: pointerCase },
+ { name: "pointer click helpers", body: pointerClickCase },
+ { name: "pointer hover drag helpers", body: pointerHoverDragCase },
+ { name: "scroll helpers", body: scrollHelpersCase },
+ { name: "pointer validation", body: pointerValidationCase },
+ {
+ name: "pointer interaction regression",
+ body: pointerInteractionRegressionCase,
+ },
{ name: "keyboard and file helpers", body: keyboardCase },
{ name: "keyboard regression", body: keyboardRegressionCase },
- { name: "wait, fetch, cdp, js, help", body: runtimeCase },
+ { name: "wait helpers", body: waitHelpersCase },
+ { name: "fetch helpers", body: fetchHelpersCase },
+ { name: "cdp js help", body: cdpJsHelpCase },
{ name: "runtime regression", body: runtimeRegressionCase },
+ ...adversarialCases,
+ ...workflowCases,
+ ...interactionsCases,
+ ...canvasCases,
];
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/interactions.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/interactions.mjs
new file mode 100644
index 0000000..2b3219e
--- /dev/null
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/interactions.mjs
@@ -0,0 +1,142 @@
+import { homeCase } from "./shared.mjs";
+
+export const interactionsCases = [
+ {
+ name: "pointer events handler tracking",
+ body: homeCase(`
+ /* Pointer Events may not be generated from CDP Input.dispatchMouseEvent
+ in the ego-lite browser. Simulate the full pointer event lifecycle via
+ JS to verify the fixture handlers and state tracking work correctly. */
+
+ const pointerResult = await js(\`(() => {
+ const area = document.querySelector("#pointer-area");
+ const rect = area.getBoundingClientRect();
+ const cx = rect.left + rect.width / 2;
+ const cy = rect.top + rect.height / 2;
+ const common = { bubbles: true, cancelable: true, pointerId: 1, pointerType: "mouse", clientX: cx, clientY: cy };
+
+ area.dispatchEvent(new PointerEvent("pointerenter", { ...common, pressure: 0 }));
+ area.dispatchEvent(new PointerEvent("pointermove", { ...common, pressure: 0 }));
+ area.dispatchEvent(new PointerEvent("pointerdown", { ...common, pressure: 0.5 }));
+ area.dispatchEvent(new PointerEvent("pointerup", { ...common, pressure: 0 }));
+ area.dispatchEvent(new PointerEvent("pointerleave", { ...common, pressure: 0 }));
+
+ return {
+ types: window.__fixtureState.pointerEventTypes.slice(),
+ downCount: window.__fixtureState.pointerDownCount,
+ moveCount: window.__fixtureState.pointerMoveCount,
+ lastType: window.__fixtureState.lastPointerType,
+ lastPressure: window.__fixtureState.lastPointerPressure,
+ };
+ })()\`);
+
+ assertIncludes(pointerResult.types.join(","), "pointerenter", "pointerenter tracked in event types");
+ assertIncludes(pointerResult.types.join(","), "pointerdown", "pointerdown tracked in event types");
+ assertIncludes(pointerResult.types.join(","), "pointerup", "pointerup tracked in event types");
+ assertIncludes(pointerResult.types.join(","), "pointerleave", "pointerleave tracked in event types");
+ assertEqual(pointerResult.downCount, 1, "pointerdown counted exactly once");
+ assert(pointerResult.moveCount >= 1, "pointermove counted at least once");
+ assertEqual(pointerResult.lastType, "mouse", "pointer type is mouse");
+ `),
+ },
+ {
+ name: "pointer events pressure tracking",
+ body: homeCase(`
+ /* Verify that pressure values are tracked correctly across different
+ pointer event phases (hover=0, active=0.5). */
+
+ const pressureResult = await js(\`(() => {
+ const area = document.querySelector("#pointer-area");
+ const rect = area.getBoundingClientRect();
+ const cx = rect.left + rect.width / 2;
+ const cy = rect.top + rect.height / 2;
+ const common = { bubbles: true, cancelable: true, pointerId: 1, pointerType: "mouse", clientX: cx, clientY: cy };
+
+ /* Hover: pressure should be 0. */
+ area.dispatchEvent(new PointerEvent("pointermove", { ...common, pressure: 0 }));
+ const hoverPressure = window.__fixtureState.lastPointerPressure;
+
+ /* Active press: pressure should be 0.5. */
+ area.dispatchEvent(new PointerEvent("pointerdown", { ...common, pressure: 0.5 }));
+ const activePressure = window.__fixtureState.lastPointerPressure;
+
+ return { hoverPressure, activePressure, count: window.__fixtureState.pointerDownCount };
+ })()\`);
+
+ assertEqual(pressureResult.hoverPressure, 0, "hover pressure is 0");
+ assertEqual(pressureResult.activePressure, 0.5, "active pointer pressure is 0.5");
+ assertEqual(pressureResult.count, 1, "one pointerdown counted");
+ `),
+ },
+ {
+ name: "html5 dnd simulate drop via js",
+ body: homeCase(`
+ /* HTML5 DnD requires browser-native drag initiation that CDP cannot trigger.
+ Simulate the full event sequence via JS to verify the fixture handlers
+ and state tracking work correctly. */
+
+ const dndResult = await js(\`(() => {
+ const source = document.querySelector("#dnd-source");
+ const target = document.querySelector("#dnd-target");
+ const dt = new DataTransfer();
+
+ source.dispatchEvent(new DragEvent("dragstart", {
+ bubbles: true, cancelable: true, dataTransfer: dt,
+ }));
+
+ dt.dropEffect = "move";
+ target.dispatchEvent(new DragEvent("dragover", {
+ bubbles: true, cancelable: true, dataTransfer: dt,
+ }));
+
+ const hasDragOver = target.classList.contains("drag-over");
+
+ target.dispatchEvent(new DragEvent("drop", {
+ bubbles: true, cancelable: true, dataTransfer: dt,
+ }));
+
+ source.dispatchEvent(new DragEvent("dragend", {
+ bubbles: true, cancelable: true, dataTransfer: dt,
+ }));
+
+ return {
+ dndDropped: window.__fixtureState.dndDropped,
+ dndData: window.__fixtureState.dndData,
+ hasDragOver,
+ targetText: target.textContent,
+ };
+ })()\`);
+
+ assert(dndResult.dndDropped, "drop handler set dndDropped to true");
+ assertEqual(dndResult.dndData, "dnd-payload", "dataTransfer carried the payload");
+ assert(dndResult.hasDragOver, "dragover added drag-over class to target");
+ assertEqual(dndResult.targetText, "Dropped!", "target text updated on drop");
+ `),
+ },
+ {
+ name: "html5 dnd drag cancel",
+ body: homeCase(`
+ /* Simulate a cancelled drag: dragstart fires but no drop target receives
+ the drop event, then dragend fires. */
+
+ await js(\`(() => {
+ const source = document.querySelector("#dnd-source");
+ const dt = new DataTransfer();
+ source.dispatchEvent(new DragEvent("dragstart", {
+ bubbles: true, cancelable: true, dataTransfer: dt,
+ }));
+ source.dispatchEvent(new DragEvent("dragend", {
+ bubbles: true, cancelable: true, dataTransfer: dt,
+ }));
+ })()\`);
+
+ assertEqual(
+ await js("return window.__fixtureState.dndDropped"),
+ false,
+ "cancelled drag leaves dndDropped as false"
+ );
+ const statusText = await js("return document.querySelector('#dnd-status').textContent");
+ assertIncludes(statusText, "cancelled", "dnd status shows drag cancelled");
+ `),
+ },
+];
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/navigation.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/navigation.mjs
index fb5f438..0044220 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/navigation.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/navigation.mjs
@@ -1,6 +1,6 @@
export function navigationCase() {
return `
- await switchTaskSpace(taskName);
+ await useOrCreateTaskSpace(taskName);
const home = await resetHome();
const info = await pageInfo();
@@ -19,6 +19,8 @@ export function navigationCase() {
const real = await ensureRealTab();
assert(real && real.targetId, "ensureRealTab returns a real tab");
+ const realTabListed = (await listTabs()).some((t) => t.targetId === real.targetId);
+ assert(realTabListed, "ensureRealTab target appears in listTabs");
const reused = await openOrReuseTab(baseUrl + "/", { wait: true, timeout: 10 });
assertEqual(reused.reused, true, "openOrReuseTab reuses exact home URL");
@@ -99,7 +101,7 @@ export function navigationCase() {
assert(nav.loaded, "gotoAndWait returns loaded true");
const frame = await iframeTarget("/frame.html");
- assert(frame === null || typeof frame === "string", "iframeTarget returns a target id or null");
+ assert(frame === null || (typeof frame === "string" && frame.length > 0), "iframeTarget returns a non-empty session id or null");
const missingFrame = await iframeTarget("/missing-frame-for-e2e");
assertEqual(missingFrame, null, "iframeTarget returns null for missing frames");
`;
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/observation.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/observation.mjs
index e45dd7f..3b3f5b6 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/observation.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/observation.mjs
@@ -1,6 +1,6 @@
export function observationCase() {
return `
- await switchTaskSpace(taskName);
+ await useOrCreateTaskSpace(taskName);
await resetHome();
const raw = await snapshotRaw({ includeStableLocator: true });
@@ -84,7 +84,10 @@ export function observationCase() {
const screenshotPath = await captureScreenshot(undefined, { full: false });
const screenshotStat = await stat(screenshotPath);
- assert(screenshotStat.size > 0, "captureScreenshot writes a non-empty png");
+ assert(screenshotStat.size > 100, "captureScreenshot writes a non-trivial png");
+ const screenshotBuf = await readFile(screenshotPath);
+ assertEqual(screenshotBuf[0], 137, "screenshot starts with PNG magic byte 137");
+ assertEqual(screenshotBuf[1], 80, "screenshot has PNG header byte P (80)");
const explicitPath = await captureScreenshot(explicitScreenshotPath, { full: false });
assertEqual(explicitPath, explicitScreenshotPath, "captureScreenshot returns explicit path");
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/pointer.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/pointer.mjs
index 954dcef..0759203 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/pointer.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/pointer.mjs
@@ -1,11 +1,10 @@
-export function pointerCase() {
+export function pointerClickCase() {
return `
await useOrCreateTaskSpace(taskName);
await resetHome();
- cliLog(JSON.stringify({ pointerStep: "ready" }));
+ cliLog(JSON.stringify({ pointerStep: "click ready" }));
assertEqual(await js("return window.__fixtureState.clicks"), 0, "click fixture starts at zero");
- cliLog(JSON.stringify({ pointerStep: "click css" }));
await click("#click-button", { label: "click helper e2e" });
await waitForJsValue(
"window.__fixtureState.clicks",
@@ -13,10 +12,8 @@ export function pointerCase() {
"click css fires a page click",
"window.__fixtureState.pointerEvents"
);
- cliLog(JSON.stringify({ pointerStep: "click selector offset" }));
await click({ selector: "#click-button", x: 12, y: 12 });
await waitForJsValue("window.__fixtureState.clicks", 2, "click selector offset fires a page click");
- cliLog(JSON.stringify({ pointerStep: "click locators" }));
await click("loc=css:#click-button");
await waitForJsValue("window.__fixtureState.clicks", 3, "click loc css fires a page click");
await click("loc=role:button[name='Increment counter']");
@@ -24,6 +21,18 @@ export function pointerCase() {
await click("xpath=//*[@id='click-button']");
await waitForJsValue("window.__fixtureState.clicks", 5, "click xpath fires a page click");
const buttonCenter = await elementCenter("#click-button");
+ const hitElement = await js(
+ "return document.elementFromPoint(" +
+ JSON.stringify(buttonCenter.x) +
+ "," +
+ JSON.stringify(buttonCenter.y) +
+ ")?.id || document.elementFromPoint(" +
+ JSON.stringify(buttonCenter.x) +
+ "," +
+ JSON.stringify(buttonCenter.y) +
+ ")?.className || ''"
+ );
+ assertEqual(hitElement, "click-button", "pointer coordinates resolve to the intended button");
await click([buttonCenter.x, buttonCenter.y]);
await waitForJsValue("window.__fixtureState.clicks", 6, "click tuple coordinates fires a page click");
await click({ x: buttonCenter.x, y: buttonCenter.y });
@@ -39,20 +48,14 @@ export function pointerCase() {
"window.__fixtureState.doubleClicks > " + JSON.stringify(doubleClicksBefore),
"doubleClick fires a DOM dblclick"
);
- cliLog(JSON.stringify({ pointerStep: "hover" }));
- await wait(0.1);
- const hitElement = await js(
- "return document.elementFromPoint(" +
- JSON.stringify(buttonCenter.x) +
- "," +
- JSON.stringify(buttonCenter.y) +
- ")?.id || document.elementFromPoint(" +
- JSON.stringify(buttonCenter.x) +
- "," +
- JSON.stringify(buttonCenter.y) +
- ")?.className || ''"
- );
- assertEqual(hitElement, "click-button", "pointer coordinates resolve to the intended button");
+ `;
+}
+
+export function pointerHoverDragCase() {
+ return `
+ await useOrCreateTaskSpace(taskName);
+ await resetHome();
+ cliLog(JSON.stringify({ pointerStep: "hover drag ready" }));
await js("window.__fixtureState.hovered = false; return true;");
await hover("#hover-zone");
@@ -61,12 +64,18 @@ export function pointerCase() {
await hover({ selector: "#hover-zone" });
await waitForJsValue("window.__fixtureState.hovered", true, "hover selector object fires mouseover");
- cliLog(JSON.stringify({ pointerStep: "drag" }));
await js("window.__fixtureState.dragged = false; return true;");
await dragMouse(["#drag-source", "#drag-target"], { delayMs: 10 });
await waitForJsValue("window.__fixtureState.dragged", true, "dragMouse fires drag source and target events");
+ `;
+}
+
+export function scrollHelpersCase() {
+ return `
+ await useOrCreateTaskSpace(taskName);
+ await resetHome();
+ cliLog(JSON.stringify({ pointerStep: "scroll ready" }));
- cliLog(JSON.stringify({ pointerStep: "nested scroll" }));
await js(
"const inner = document.querySelector('#inner-scroll');" +
"inner.scrollTop = 0;" +
@@ -95,7 +104,6 @@ export function pointerCase() {
);
}
- cliLog(JSON.stringify({ pointerStep: "page wheel" }));
await resetHome();
const wheelPoint = await js(
"const rect = document.querySelector('#scroll-area').getBoundingClientRect();" +
@@ -132,7 +140,6 @@ export function pointerCase() {
assert(afterObjectWheel.sy > beforeObjectWheel.sy, "scroll object options move the page down");
}
- cliLog(JSON.stringify({ pointerStep: "dom scroll helpers" }));
await resetHome();
const beforeBy = await pageInfo();
const by = await scrollBy({ dy: 450 });
@@ -175,6 +182,13 @@ export function pointerCase() {
wait: 0,
});
assertEqual(immediateCondition.reason, "condition", "scrollToBottomUntil accepts immediate string condition");
+ `;
+}
+
+export function pointerValidationCase() {
+ return `
+ await useOrCreateTaskSpace(taskName);
+ await resetHome();
await assertRejects(
() => dragMouse(["#drag-source"]),
@@ -206,9 +220,15 @@ export function pointerCase() {
"function or string",
"scrollToBottomUntil validates condition type"
);
+ `;
+}
+
+export function pointerInteractionRegressionCase() {
+ return `
+ await useOrCreateTaskSpace(taskName);
+ await resetHome();
+ cliLog(JSON.stringify({ pointerStep: "interaction regression ready" }));
- /* right-click — CDP dispatches mousedown with button=right; contextmenu synthesis is browser-dependent */
- cliLog(JSON.stringify({ pointerStep: "right click" }));
const rightClickBefore = await js("return window.__fixtureState.pointerEvents.length");
await click("#context-menu-zone", { button: "right" });
const rightClickAfter = await js("return window.__fixtureState.pointerEvents.length");
@@ -218,8 +238,6 @@ export function pointerCase() {
);
assert(rightMouseDown, "right-click produces a mousedown event on the context-menu-zone");
- /* rapid clicks — probe cleanup between actions */
- cliLog(JSON.stringify({ pointerStep: "rapid clicks" }));
await resetHome();
const clicksBefore = await js("return window.__fixtureState.clicks");
await click("#click-button");
@@ -234,8 +252,6 @@ export function pointerCase() {
"window.__fixtureState.pointerEvents"
);
- /* checkbox toggle */
- cliLog(JSON.stringify({ pointerStep: "checkbox" }));
await js("document.querySelector('#checkbox').checked = false; window.__fixtureState.checkboxChecked = false; return true;");
await click("#checkbox");
await waitForJsValue("window.__fixtureState.checkboxChecked", true, "first click checks the checkbox");
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/runtime-regression.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/runtime-regression.mjs
index a35b312..0750817 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/runtime-regression.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/runtime-regression.mjs
@@ -47,7 +47,19 @@ export function runtimeRegressionCase() {
/* js rejects invalid input types (neither string nor function). */
await assertRejectsAny(() => js(123), "js rejects non-string/function input");
- /* serverFetch returns the body and respects exact content length. */
+ /* serverFetch returns the body and respects exact content length, including
+ lower boundary values (n=0, n=1) that were previously only tested in the
+ now-removed theory-expanded suite. */
+ assertEqual(
+ (await serverFetch(baseUrl + "/api/bytes?n=0", { timeout: 5 })).length,
+ 0,
+ "serverFetch returns empty body for zero-byte request"
+ );
+ assertEqual(
+ (await serverFetch(baseUrl + "/api/bytes?n=1", { timeout: 5 })).length,
+ 1,
+ "serverFetch returns one byte for single-byte request"
+ );
const bytes = await serverFetch(baseUrl + "/api/bytes?n=4096", { timeout: 5 });
assertEqual(bytes.length, 4096, "serverFetch returns a body of the exact requested length");
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/runtime.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/runtime.mjs
index 51956e9..a32da3c 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/runtime.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/runtime.mjs
@@ -1,6 +1,6 @@
-export function runtimeCase() {
+export function waitHelpersCase() {
return `
- await switchTaskSpace(taskName);
+ await useOrCreateTaskSpace(taskName);
await resetHome();
const waitedAt = Date.now();
@@ -20,6 +20,13 @@ export function runtimeCase() {
false,
"waitForElement visible:true rejects hidden elements"
);
+ `;
+}
+
+export function fetchHelpersCase() {
+ return `
+ await useOrCreateTaskSpace(taskName);
+ await resetHome();
const serverText = await serverFetch(baseUrl + "/api/text", { timeout: 5 });
assertEqual(serverText, "server text fixture", "serverFetch reads fixture API");
@@ -83,6 +90,13 @@ export function runtimeCase() {
"HTTP 500",
"browserFetch reports HTTP errors"
);
+ `;
+}
+
+export function cdpJsHelpCase() {
+ return `
+ await useOrCreateTaskSpace(taskName);
+ await resetHome();
await cdp("Network.enable");
await js(
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/shared.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/shared.mjs
new file mode 100644
index 0000000..bcd242d
--- /dev/null
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/shared.mjs
@@ -0,0 +1,38 @@
+/**
+ * Shared case-construction helpers for E2E case files.
+ *
+ * caseBody / homeCase wrap a case body string with the common boilerplate
+ * (useOrCreateTaskSpace + resetHome) so each case file only expresses its
+ * unique logic. buttonRefSetup returns a reusable snippet for snapshot-based
+ * ref resolution.
+ */
+
+export function caseBody(body) {
+ return () => `
+ await useOrCreateTaskSpace(taskName);
+ ${body}
+ `;
+}
+
+export function homeCase(body) {
+ return caseBody(`
+ await resetHome();
+ ${body}
+ `);
+}
+
+export function buttonRefSetup() {
+ return `
+ const snap = await snapshot({
+ scope: "full_page",
+ includeActionMarks: true,
+ includeStableLocator: true,
+ });
+ const buttonRef = (snap.refs || []).find(
+ (ref) =>
+ String(ref?.role || "") === "button" &&
+ String(ref?.name || "").includes("Increment counter")
+ )?.backendNodeId;
+ assert(buttonRef, "snapshot exposes increment button ref");
+ `;
+}
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/task-space.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/task-space.mjs
index bbfdf96..cc420b7 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/task-space.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/task-space.mjs
@@ -79,11 +79,28 @@ export function taskSpaceCase() {
"handOffTaskSpace reports missing task space"
);
+ // handOff → takeOver cycle: verify ownership transitions via listTaskSpaces
await handOffTaskSpace();
+ const afterHandoff = await listTaskSpaces();
+ const handedOff = afterHandoff.find((s) => s.name === taskName);
+ assert(handedOff.ownership !== "agent", "handOffTaskSpace transfers ownership away from agent");
+
await takeOverTaskSpace();
+ const afterTakeover = await listTaskSpaces();
+ const taken = afterTakeover.find((s) => s.name === taskName);
+ assertEqual(taken.ownership, "agent", "takeOverTaskSpace restores agent ownership");
+
await waitForAgentControl(taskName, { interval: 0.1, timeout: 5 });
+
+ // Repeat with explicit name parameter
await handOffTaskSpace(taskName);
+ const afterHandoff2 = await listTaskSpaces();
+ assert(afterHandoff2.find((s) => s.name === taskName).ownership !== "agent", "handOffTaskSpace(name) transfers ownership away from agent");
+
await takeOverTaskSpace(taskName);
+ const afterTakeover2 = await listTaskSpaces();
+ assertEqual(afterTakeover2.find((s) => s.name === taskName).ownership, "agent", "takeOverTaskSpace(name) restores agent ownership");
+
await waitForAgentControl(taskName, { interval: 0.1, timeout: 5 });
`;
}
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/workflows.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/workflows.mjs
new file mode 100644
index 0000000..1ba982f
--- /dev/null
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/workflows.mjs
@@ -0,0 +1,200 @@
+/*
+ * Workflow tests: multi-step scenarios that simulate real agent behavior
+ * across pages, tabs, and state transitions. These cover paths that isolated
+ * per-subsystem tests miss — state leakage, cross-tab consistency, and
+ * sequential interaction chains.
+ */
+
+import { homeCase } from "./shared.mjs";
+
+export const workflowCases = [
+ {
+ name: "workflow multi-page navigation",
+ body: homeCase(`
+ /* Step 1: capture initial home state. */
+ const homeInfo = await pageInfo();
+ assertEqual(homeInfo.title, "ego-lite helper e2e", "workflow: home title before navigation");
+
+ /* Step 2: click the nav link to navigate within the current tab. */
+ await click("#nav-link");
+ assert(await waitForLoad({ timeout: 10 }), "workflow: nav-target page loads");
+ const navInfo = await pageInfo();
+ assertEqual(navInfo.title, "ego-lite nav target", "workflow: page title changes after navigation");
+ assertIncludes(navInfo.url, "/nav-target", "workflow: URL reflects nav-target");
+
+ /* Step 3: open a secondary page in a new tab. */
+ const secondary = await openOrReuseTab(baseUrl + "/secondary", {
+ wait: true,
+ timeout: 10,
+ });
+ assertEqual(secondary.reused, false, "workflow: secondary tab is new");
+ await switchTab(secondary);
+ const secTitle = await js("return document.title");
+ assertEqual(secTitle, "ego-lite secondary", "workflow: secondary tab title is correct");
+
+ /* Step 4: switch back to the nav-target tab and verify its state persisted. */
+ const tabs = await listTabs({ includeChrome: false });
+ const navTab = tabs.find((t) => String(t.url || "").includes("/nav-target"));
+ assert(navTab, "workflow: nav-target tab still exists in tab list");
+ await switchTab(navTab.targetId);
+ const navTitleAfterSwitch = await js("return document.title");
+ assertEqual(navTitleAfterSwitch, "ego-lite nav target", "workflow: nav-target title persists across tab switches");
+
+ /* Step 5: navigate back home via gotoUrl and verify clean state. */
+ await gotoUrl(baseUrl + "/");
+ assert(await waitForLoad({ timeout: 10 }), "workflow: home page reloads");
+ const backHomeInfo = await pageInfo();
+ assertEqual(backHomeInfo.title, "ego-lite helper e2e", "workflow: home title restored after multi-tab navigation");
+
+ /* Step 6: close the secondary tab and verify tab count. */
+ const tabsBeforeClose = (await listTabs({ includeChrome: false })).length;
+ await closeTab(secondary.targetId);
+ // Poll for tab count to decrease (closeTab may resolve before the tab list updates)
+ const deadline = Date.now() + 2000;
+ let remaining;
+ do {
+ remaining = await listTabs({ includeChrome: false });
+ if (remaining.length < tabsBeforeClose) break;
+ await wait(0.1);
+ } while (Date.now() < deadline);
+ assert(remaining.length < tabsBeforeClose, "workflow: tab count decreased after closing secondary");
+
+ /* Step 7: verify browserFetch still works after all the navigation. */
+ const text = await browserFetch("/api/text", { timeout: 5 });
+ assertEqual(text, "server text fixture", "workflow: browserFetch works after multi-page navigation");
+ `),
+ },
+ {
+ name: "workflow form interaction chain",
+ body: homeCase(`
+ /* Step 1: fill a text input and verify the value. */
+ await fillInput("#text-input", "hello", { timeout: 3 });
+ assertEqual(
+ await js("return document.querySelector('#text-input').value"),
+ "hello",
+ "workflow: fillInput sets text value"
+ );
+
+ /* Step 2: append more text with typeText. */
+ await click("#text-input");
+ await typeText(" world");
+ assertEqual(
+ await js("return document.querySelector('#text-input').value"),
+ "hello world",
+ "workflow: typeText appends to existing value"
+ );
+
+ /* Step 3: select-all then overwrite using fillInput (which clears first). */
+ await fillInput("#text-input", "replaced", { timeout: 3 });
+ assertEqual(
+ await js("return document.querySelector('#text-input').value"),
+ "replaced",
+ "workflow: fillInput replaces entire value"
+ );
+
+ /* Step 4: fill the textarea and verify independently. */
+ await fillInput("#text-area", "area content", { timeout: 3 });
+ assertEqual(
+ await js("return document.querySelector('#text-area').value"),
+ "area content",
+ "workflow: textarea value set independently"
+ );
+ /* Text input should not have been affected by textarea fill. */
+ assertEqual(
+ await js("return document.querySelector('#text-input').value"),
+ "replaced",
+ "workflow: text input unchanged after textarea fill"
+ );
+
+ /* Step 5: toggle checkbox and verify state. */
+ assertEqual(
+ await js("return window.__fixtureState.checkboxChecked"),
+ false,
+ "workflow: checkbox starts unchecked"
+ );
+ await click("#checkbox");
+ await waitForJsCondition("window.__fixtureState.checkboxChecked", "workflow: checkbox becomes checked after click");
+
+ /* Step 6: click a second time to uncheck. */
+ await click("#checkbox");
+ await waitForJsValue(
+ "window.__fixtureState.checkboxChecked",
+ false,
+ "workflow: checkbox toggles back to unchecked"
+ );
+
+ /* Step 7: interact with dynamic DOM — add element, verify, remove, verify. */
+ await click("#add-element");
+ const appeared = await waitForElement("#dynamic-element", { timeout: 3, visible: true });
+ assertEqual(appeared, true, "workflow: dynamically added element becomes visible");
+ const dynText = await js("return document.querySelector('#dynamic-element')?.textContent");
+ assertIncludes(dynText, "Dynamic", "workflow: dynamic element has expected text");
+
+ await click("#remove-element");
+ const gone = await waitForElement("#dynamic-element", { timeout: 3 });
+ assertEqual(gone, false, "workflow: dynamically removed element disappears");
+
+ /* Step 8: verify the click counter tracked only #click-button clicks (none in this workflow). */
+ const totalClicks = await js("return window.__fixtureState.clicks");
+ assertEqual(totalClicks, 0, "workflow: click counter only tracks #click-button, not form interactions");
+ `),
+ },
+ {
+ name: "workflow observation and recovery",
+ body: homeCase(`
+ /* Step 1: take a snapshot and capture refs for known elements. */
+ const snap1 = await snapshot({
+ scope: "full_page",
+ includeActionMarks: true,
+ includeStableLocator: true,
+ });
+ const buttonRef = (snap1.refs || []).find(
+ (r) => String(r?.role || "") === "button" && String(r?.name || "").includes("Increment")
+ )?.backendNodeId;
+ assert(buttonRef, "workflow: initial snapshot exposes button ref");
+
+ /* Step 2: click using the ref and verify it works. */
+ await click("@" + buttonRef);
+ await waitForJsValue("window.__fixtureState.clicks", 1, "workflow: click via ref increments counter");
+
+ /* Step 3: modify the DOM, then verify the snapshot reflects the new element. */
+ await click("#add-element");
+ await waitForElement("#dynamic-element", { timeout: 3, visible: true });
+ const textAfterAdd = await snapshotText({ scope: "full_page" });
+ assertIncludes(String(textAfterAdd), "Dynamic!", "workflow: snapshot text includes dynamic element after mutation");
+
+ /* Step 4: use the old button ref — it should still work because the
+ element is still present (not replaced, just a sibling added). */
+ await click("@" + buttonRef);
+ await waitForJsValue("window.__fixtureState.clicks", 2, "workflow: old ref still valid when element is unchanged");
+
+ /* Step 5: remove the dynamic element and verify the ref becomes stale. */
+ await click("#remove-element");
+ await waitForElement("#dynamic-element", { timeout: 3 });
+ // The dynamic element is gone; trying to click its stale ref should
+ // either fall back (if another element matches the role/name) or fail.
+ // We just verify the element is truly removed.
+ const dynExists = await js("return !!document.querySelector('#dynamic-element')");
+ assertEqual(dynExists, false, "workflow: dynamic element removed from DOM");
+
+ /* Step 6: take a screenshot and verify the file is created. */
+ const screenshotPath = join(artifactDir, "workflow-shot.png");
+ await captureScreenshot(screenshotPath);
+ const screenshotStat = await stat(screenshotPath);
+ assert(screenshotStat.size > 0, "workflow: screenshot file is non-empty");
+
+ /* Step 7: drain events and verify the buffer mechanism. */
+ const events = await drainEvents();
+ assert(Array.isArray(events), "workflow: drainEvents returns an array");
+ const emptyEvents = await drainEvents();
+ assertEqual(emptyEvents.length, 0, "workflow: second drain returns empty buffer");
+
+ /* Step 8: take a snapshotText and verify it reflects current DOM state. */
+ const text = await snapshotText({ scope: "full_page" });
+ assertIncludes(text, "Helper e2e fixture", "workflow: snapshotText includes page heading");
+ // Dynamic element was removed, so its text should not appear
+ const hasDynamic = String(text).includes("Dynamic!");
+ assertEqual(hasDynamic, false, "workflow: snapshotText reflects removal of dynamic element");
+ `),
+ },
+];
diff --git a/package/ego-browser/scripts/real-browser-e2e/ego-source.mjs b/package/ego-browser/scripts/real-browser-e2e/ego-source.mjs
index 4c875b4..8199d04 100644
--- a/package/ego-browser/scripts/real-browser-e2e/ego-source.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/ego-source.mjs
@@ -1,3 +1,10 @@
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { dirname, join } from "node:path";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const preamble = readFileSync(join(__dirname, "preamble.mjs"), "utf-8");
+
export function egoSource(body, context) {
const {
taskName,
@@ -12,8 +19,12 @@ export function egoSource(body, context) {
keepTaskSpace,
} = context;
return `
- const { stat, writeFile } = await import("node:fs/promises");
- const { join } = await import("node:path");
+ ${preamble}
+
+ const verboseAssertions =
+ process.env.EGO_BROWSER_REAL_E2E_VERBOSE_ASSERTIONS === "1" ||
+ process.env.EGO_BROWSER_REAL_E2E_VERBOSE_ASSERTIONS === "true";
+
const taskName = ${JSON.stringify(taskName)};
const baseUrl = ${JSON.stringify(baseUrl)};
const artifactDir = ${JSON.stringify(artifactDir)};
@@ -25,153 +36,6 @@ export function egoSource(body, context) {
const metadataPath = ${JSON.stringify(metadataPath)};
const keepTaskSpace = ${JSON.stringify(keepTaskSpace)};
- let __assertionCount = 0;
-
- function assert(condition, message) {
- __assertionCount++;
- if (!condition) throw new Error(message);
- }
-
- function assertEqual(actual, expected, message) {
- __assertionCount++;
- if (actual !== expected) {
- throw new Error(
- message + ": expected " + JSON.stringify(expected) + ", got " + JSON.stringify(actual)
- );
- }
- }
-
- function assertIncludes(text, expected, message) {
- __assertionCount++;
- assert(
- String(text).includes(expected),
- message + ": expected " + JSON.stringify(String(text).slice(0, 500)) + " to include " + JSON.stringify(expected)
- );
- }
-
- async function assertRejects(fn, expected, message) {
- __assertionCount++;
- try {
- await fn();
- } catch (error) {
- assertIncludes(error?.message || String(error), expected, message);
- return;
- }
- throw new Error(message + ": expected rejection");
- }
-
- async function assertRejectsAny(fn, message) {
- __assertionCount++;
- try {
- await fn();
- } catch {
- return;
- }
- throw new Error(message + ": expected rejection");
- }
-
- async function waitForJsValue(expression, expected, message, debugExpression = null) {
- const deadline = Date.now() + 2000;
- let last;
- while (Date.now() <= deadline) {
- last = await js(expression);
- if (last === expected) return last;
- await wait(0.05);
- }
- let detail = "";
- if (debugExpression) {
- detail = "; debug=" + JSON.stringify(await js(debugExpression));
- }
- throw new Error(
- message + detail + ": expected " + JSON.stringify(expected) + ", got " + JSON.stringify(last)
- );
- }
-
- async function waitForJsCondition(expression, message, debugExpression = null) {
- const deadline = Date.now() + 2000;
- let last;
- while (Date.now() <= deadline) {
- last = await js(expression);
- if (last) return last;
- await wait(0.05);
- }
- let detail = "";
- if (debugExpression) {
- detail = "; debug=" + JSON.stringify(await js(debugExpression));
- }
- throw new Error(message + detail + ": condition stayed false, last value " + JSON.stringify(last));
- }
-
- async function allowWheelDispatch(label, fn) {
- try {
- await fn();
- return true;
- } catch (error) {
- const message = error?.message || String(error);
- if (/Input\\.dispatchMouseEvent|CDP request timed out: Input\\.dispatchMouseEvent/.test(message)) {
- cliLog(JSON.stringify({ inputDispatchWarning: { label, message } }));
- return false;
- }
- throw error;
- }
- }
-
- async function setStableViewport() {
- await cdp("Page.bringToFront").catch(() => {});
- await cdp("Emulation.clearDeviceMetricsOverride").catch(() => {});
- await cdp("Emulation.setDeviceMetricsOverride", {
- width: 1280,
- height: 800,
- deviceScaleFactor: 1,
- mobile: false,
- }).catch(() => {});
- await wait(0.1);
- }
-
- async function hitTestClickButton() {
- return js(
- "const el = document.querySelector('#click-button');" +
- "if (!el) return '';" +
- "const r = el.getBoundingClientRect();" +
- "const hit = document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2);" +
- "return hit?.closest?.('#click-button')?.id || hit?.id || '';"
- ).catch(() => "");
- }
-
- async function closeFixtureTabs() {
- const tabs = await listTabs({ includeChrome: false }).catch(() => []);
- for (const tab of tabs) {
- if (String(tab.url || "").startsWith(baseUrl)) {
- await closeTab(tab.targetId).catch(() => {});
- }
- }
- }
-
- async function resetHome() {
- await takeOverTaskSpace(taskName).catch(() => {});
- await waitForAgentControl(taskName, { interval: 0.1, timeout: 5 });
- await closeFixtureTabs();
- const tab = await openOrReuseTab(baseUrl + "/?e2e-reset=" + Date.now(), { wait: true, timeout: 10 });
- await switchTab(tab.targetId);
- await setStableViewport();
- const nav = await gotoAndWait(baseUrl + "/", { timeout: 10 });
- assert(nav.loaded, "home page loaded");
- await setStableViewport();
- assert(
- await waitForElement("#click-button", { timeout: 3, visible: true }),
- "home fixture click button is visible"
- );
- for (let i = 0; i < 10; i += 1) {
- const info = await pageInfo();
- if (info.w > 0 && info.h > 0 && await hitTestClickButton() === "click-button") return tab;
- await setStableViewport();
- }
- const info = await pageInfo();
- assert(info.w > 0 && info.h > 0, "viewport initialized with non-zero size");
- assertEqual(await hitTestClickButton(), "click-button", "viewport hit-testing reaches the click fixture");
- return tab;
- }
-
try {
${body}
cliLog(JSON.stringify({ ok: true, assertions: __assertionCount }));
diff --git a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
index 012bc91..e38ed9b 100644
--- a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
@@ -194,99 +194,309 @@ function pageHtml(kind) {
<meta charset="utf-8">
<title>${title}</title>
<style>
- body { font-family: system-ui, sans-serif; margin: 24px; }
- button, input { font: inherit; }
- #hover-zone, #drag-source, #drag-target {
- align-items: center;
- border: 1px solid #777;
- display: inline-flex;
- height: 64px;
- justify-content: center;
- margin: 8px;
- width: 160px;
+ :root {
+ --bg: #f5f6f8;
+ --surface: #ffffff;
+ --text: #1a1a2e;
+ --text2: #6b7280;
+ --border: #e2e5ea;
+ --accent: #3b82f6;
+ --accent-bg: #eff6ff;
+ --green: #16a34a;
+ --green-bg: #f0fdf4;
+ --red: #dc2626;
+ --purple-bg: #f5f3ff;
+ --radius: 6px;
}
- #drag-target { background: #eef7ee; }
- #rich-editor {
- border: 1px solid #777;
- min-height: 48px;
- padding: 8px;
- width: 320px;
+ *, *::before, *::after { box-sizing: border-box; }
+ body {
+ font-family: system-ui, -apple-system, sans-serif;
+ background: var(--bg);
+ color: var(--text);
+ margin: 0;
+ padding: 10px 16px;
+ line-height: 1.35;
+ font-size: 13px;
+ }
+ main { max-width: 960px; }
+ h1 { font-size: 1.1rem; font-weight: 700; margin: 0 0 2px; letter-spacing: -0.02em; }
+ h2 { font-size: 0.7rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.06em; color: var(--text2); margin: 6px 0 2px; }
+ [data-testid="status"] { color: var(--text2); font-size: 0.8rem; margin: 0 0 6px; }
+
+ .card-row { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; margin-bottom: 2px; }
+ .card {
+ background: var(--surface);
+ border: 1px solid var(--border);
+ border-radius: var(--radius);
+ padding: 6px 10px;
+ margin-bottom: 4px;
+ }
+
+ /* Buttons */
+ button, .btn {
+ font: inherit; font-size: 0.8rem; font-weight: 500;
+ padding: 4px 10px; border-radius: 5px;
+ border: 1px solid var(--border); background: var(--surface);
+ color: var(--text); cursor: pointer;
+ }
+ button:hover, .btn:hover { background: #f0f1f3; }
+ .btn-primary { background: var(--accent); color: #fff; border-color: var(--accent); }
+ .btn-primary:hover { background: #2563eb; }
+ #click-count {
+ display: inline-flex; align-items: center; justify-content: center;
+ min-width: 22px; height: 22px; padding: 0 6px;
+ background: var(--accent-bg); color: var(--accent);
+ border-radius: 11px; font-size: 0.8rem; font-weight: 600;
+ margin-left: 6px;
+ }
+ .duplicate-action { margin-right: 3px; }
+
+ /* Links */
+ a { color: var(--accent); text-decoration: none; font-weight: 500; font-size: 0.8rem; }
+ a:hover { text-decoration: underline; }
+
+ /* Form controls */
+ label { display: block; margin-bottom: 4px; font-size: 0.8rem; color: var(--text2); }
+ label span { display: block; margin-bottom: 1px; font-weight: 500; font-size: 0.75rem; }
+ input:not([type="checkbox"]):not([type="file"]), textarea, select {
+ font: inherit; font-size: 0.8rem;
+ padding: 3px 8px; border: 1px solid var(--border);
+ border-radius: 4px; width: 100%; max-width: 220px;
+ background: var(--surface); color: var(--text);
}
+ input:focus, textarea:focus, select:focus { outline: none; border-color: var(--accent); }
+ textarea { resize: vertical; min-height: 28px; height: 28px; }
+ input[type="file"] { font-size: 0.75rem; }
+ input[type="checkbox"] { margin-right: 4px; vertical-align: middle; }
+ .form-row { display: flex; gap: 8px; flex-wrap: wrap; align-items: flex-end; }
+ .form-cols { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
+
+ /* Interaction zones */
+ .zone {
+ display: inline-flex; align-items: center; justify-content: center;
+ padding: 6px 14px; border: 2px dashed var(--border);
+ border-radius: var(--radius); font-size: 0.8rem; color: var(--text2);
+ user-select: none;
+ }
+ #hover-zone { width: 100px; height: 36px; }
+ #hover-zone:hover { border-color: var(--accent); background: var(--accent-bg); }
+ #drag-source, #drag-target {
+ width: 100px; height: 36px; margin: 2px;
+ }
+ #drag-source { border-style: solid; cursor: grab; }
+ #drag-source:active { cursor: grabbing; }
+ #drag-target { background: var(--green-bg); border-color: var(--green); }
+ .drag-row { display: flex; align-items: center; gap: 6px; }
+ .drag-arrow { color: var(--text2); font-size: 1rem; }
+
+ /* Context menu zone */
#context-menu-zone {
- align-items: center;
- background: #f7eef7;
- border: 1px dashed #777;
- display: inline-flex;
- height: 48px;
- justify-content: center;
- margin: 8px;
- width: 160px;
+ background: var(--purple-bg);
+ border-color: #a78bfa; width: 100px; height: 36px;
+ }
+
+ /* Rich editor */
+ #rich-editor {
+ border: 1px solid var(--border); border-radius: 4px;
+ min-height: 28px; padding: 4px 8px; width: 100%; max-width: 220px;
+ font-size: 0.8rem;
+ }
+ #rich-editor:focus { outline: none; border-color: var(--accent); }
+
+ /* Dynamic DOM */
+ .dynamic-actions { display: flex; gap: 4px; }
+ #dynamic-container { min-height: 4px; margin-top: 4px; }
+ #dynamic-element {
+ display: inline-block; background: var(--green-bg);
+ border: 1px solid var(--green); border-radius: 4px;
+ padding: 2px 8px; font-size: 0.8rem; color: var(--green);
}
- #dynamic-container { min-height: 24px; margin: 8px 0; }
+
+ /* Canvas */
+ #draw-canvas {
+ border: 1px solid var(--border); border-radius: var(--radius);
+ cursor: crosshair; display: block; background: #fff;
+ }
+
+ /* HTML5 DnD */
+ #dnd-source {
+ width: 80px; height: 34px;
+ background: var(--accent-bg); border: 2px solid var(--accent);
+ border-radius: var(--radius); display: inline-flex;
+ align-items: center; justify-content: center;
+ font-size: 0.8rem; font-weight: 500; color: var(--accent);
+ cursor: grab; margin: 2px;
+ }
+ #dnd-source:active { cursor: grabbing; }
+ #dnd-target {
+ width: 100px; height: 34px;
+ background: var(--green-bg); border: 2px dashed var(--green);
+ border-radius: var(--radius); display: inline-flex;
+ align-items: center; justify-content: center;
+ font-size: 0.8rem; font-weight: 500; color: var(--green);
+ margin: 2px;
+ }
+ #dnd-target.drag-over { background: #dcfce7; border-style: solid; }
+ .dnd-row { display: flex; align-items: center; gap: 8px; }
+
+ /* Pointer events area */
+ #pointer-area {
+ width: 100%; height: 70px;
+ border: 1px solid var(--border); border-radius: var(--radius);
+ background: #fafbfc; position: relative;
+ display: flex; align-items: center; justify-content: center;
+ font-size: 0.8rem; color: var(--text2);
+ touch-action: none;
+ }
+ #pointer-area .pointer-indicator {
+ position: absolute; width: 6px; height: 6px;
+ border-radius: 50%; background: var(--accent);
+ transform: translate(-50%, -50%); pointer-events: none;
+ opacity: 0;
+ }
+
+ /* Tab trap */
+ #tab-trap { display: flex; gap: 4px; }
.tab-stop {
- border: 1px solid #999;
- display: inline-block;
- margin: 4px;
- padding: 4px 12px;
+ border: 1px solid var(--border); border-radius: 4px;
+ display: inline-block; padding: 3px 10px;
+ font-size: 0.8rem; cursor: pointer;
}
- .tab-stop:focus { outline: 2px solid #44f; }
+ .tab-stop:focus { outline: none; border-color: var(--accent); background: var(--accent-bg); }
+
+ /* Scroll areas */
#inner-scroll {
- border: 1px solid #777;
- height: 120px;
- margin-top: 12px;
- overflow: auto;
- width: 320px;
+ border: 1px solid var(--border); border-radius: var(--radius);
+ height: 80px; margin-top: 4px; overflow: auto; width: 220px;
}
- #inner-scroll-content { height: 620px; padding-top: 520px; }
+ #inner-scroll-content { height: 620px; padding-top: 520px; font-size: 0.8rem; color: var(--text2); }
#scroll-area { height: 1800px; padding-top: 16px; }
- #bottom-marker { margin-top: 1450px; }
+ #bottom-marker { margin-top: 1450px; font-size: 0.8rem; color: var(--text2); }
+
+ /* Utility */
#delayed { display: none; }
+ #never-visible { display: none; }
+ #file-name, #key-log { font-size: 0.75rem; color: var(--text2); margin: 2px 0; min-height: 1em; }
+ #controlled-state { font-size: 0.75rem; color: var(--text2); margin-left: 6px; }
+ #dnd-status, #pointer-log { font-size: 0.75rem; color: var(--text2); margin-top: 2px; }
+ iframe { display: none; }
</style>
</head>
<body>
<main>
<h1>${heading}</h1>
<p data-testid="status">ready</p>
- <button id="click-button" aria-label="Increment counter">Click counter</button>
- <button class="duplicate-action" type="button">Duplicate action</button>
- <button class="duplicate-action" type="button">Duplicate action</button>
- <a id="nav-link" href="/nav-target">Go to nav target</a>
- <span id="click-count">0</span>
- <div id="hover-zone">Hover zone</div>
- <div id="drag-source">Drag source</div>
- <div id="drag-target">Drag target</div>
- <label>Text input <input id="text-input" value="initial"></label>
- <label>Append input <input id="append-input" value="base"></label>
- <label>Text area <textarea id="text-area">seed</textarea></label>
- <label>File input <input id="file-input" type="file" multiple></label>
- <div id="file-name"></div>
- <div id="key-log"></div>
- <label>Dropdown <select id="dropdown">
- <option value="alpha">Alpha</option>
- <option value="beta">Beta</option>
- <option value="gamma">Gamma</option>
- </select></label>
- <label><input type="checkbox" id="checkbox"> Toggle checkbox</label>
- <div id="rich-editor" contenteditable="true">edit me</div>
- <div id="context-menu-zone">Right-click here</div>
- <button id="add-element" type="button">Add element</button>
- <button id="remove-element" type="button">Remove element</button>
- <div id="dynamic-container"></div>
- <div id="tab-trap">
- <span class="tab-stop" tabindex="0" data-tab="first">First</span>
- <span class="tab-stop" tabindex="0" data-tab="second">Second</span>
- <span class="tab-stop" tabindex="0" data-tab="third">Third</span>
+
+ <div class="card">
+ <button id="click-button" class="btn-primary" aria-label="Increment counter">Click counter</button>
+ <span id="click-count">0</span>
+ <button class="duplicate-action" type="button">Duplicate action</button>
+ <button class="duplicate-action" type="button">Duplicate action</button>
+ <a id="nav-link" href="/nav-target" style="margin-left:8px">Go to nav target</a>
+ </div>
+
+ <div class="card-row">
+ <div>
+ <h2>Pointer &amp; Mouse</h2>
+ <div class="card">
+ <div style="display:flex;gap:6px;flex-wrap:wrap">
+ <div id="hover-zone" class="zone">Hover zone</div>
+ <div id="context-menu-zone" class="zone">Right-click here</div>
+ </div>
+ <div class="drag-row" style="margin-top:4px">
+ <div id="drag-source" class="zone">Drag source</div>
+ <span class="drag-arrow">&rarr;</span>
+ <div id="drag-target" class="zone">Drag target</div>
+ </div>
+ </div>
+ </div>
+ <div>
+ <h2>HTML5 Drag &amp; Drop</h2>
+ <div class="card">
+ <div class="dnd-row">
+ <div id="dnd-source" draggable="true">Drag me</div>
+ <span class="drag-arrow">&rarr;</span>
+ <div id="dnd-target">Drop here</div>
+ </div>
+ <div id="dnd-status">Awaiting drag</div>
+ </div>
+ <h2>Pointer Events</h2>
+ <div class="card">
+ <div id="pointer-area">
+ <span class="pointer-label">Move pointer here</span>
+ <div class="pointer-indicator"></div>
+ </div>
+ <div id="pointer-log">No events</div>
+ </div>
+ </div>
+ </div>
+
+ <div class="card-row">
+ <div>
+ <h2>Form Inputs</h2>
+ <div class="card">
+ <div class="form-cols">
+ <label><span>Text input</span><input id="text-input" value="initial"></label>
+ <label><span>Append input</span><input id="append-input" value="base"></label>
+ </div>
+ <label><span>Text area</span><textarea id="text-area">seed</textarea></label>
+ <div class="form-row">
+ <label style="flex:1;max-width:160px"><span>Dropdown</span><select id="dropdown">
+ <option value="alpha">Alpha</option>
+ <option value="beta">Beta</option>
+ <option value="gamma">Gamma</option>
+ </select></label>
+ <label style="margin-bottom:0"><input type="checkbox" id="checkbox"> Toggle</label>
+ </div>
+ <label><span>File input</span><input id="file-input" type="file" multiple></label>
+ <div id="file-name"></div>
+ <div id="key-log"></div>
+ </div>
+ </div>
+ <div>
+ <h2>Rich Text &amp; Dynamic DOM</h2>
+ <div class="card">
+ <label><span>Content editable</span><div id="rich-editor" contenteditable="true">edit me</div></label>
+ <div class="dynamic-actions">
+ <button id="add-element" type="button">Add element</button>
+ <button id="remove-element" type="button">Remove element</button>
+ </div>
+ <div id="dynamic-container"></div>
+ </div>
+ </div>
+ </div>
+
+ <div class="card-row">
+ <div>
+ <h2>Canvas Drawing</h2>
+ <div class="card">
+ <canvas id="draw-canvas" width="300" height="150"></canvas>
+ </div>
+ </div>
+ <div>
+ <h2>Advanced</h2>
+ <div class="card">
+ <div class="form-cols">
+ <label><span>Email</span><input id="email-input" type="email" value="[email protected]"></label>
+ <label><span>Number</span><input id="number-input" type="number" value="123"></label>
+ </div>
+ <label style="display:flex;align-items:center;gap:6px"><span style="margin:0">Controlled</span><input id="controlled-input" type="text" style="flex:1;max-width:160px"><span id="controlled-state"></span></label>
+ <div id="tab-trap">
+ <span class="tab-stop" tabindex="0" data-tab="first">First</span>
+ <span class="tab-stop" tabindex="0" data-tab="second">Second</span>
+ <span class="tab-stop" tabindex="0" data-tab="third">Third</span>
+ </div>
+ </div>
+ </div>
</div>
+
<div id="delayed">Delayed element</div>
- <div id="never-visible" style="display:none">Never visible</div>
+ <div id="never-visible">Never visible</div>
<iframe id="fixture-frame" src="/frame.html"></iframe>
<div id="inner-scroll"><div id="inner-scroll-content">Inner scroll marker</div></div>
<section id="scroll-area"><div id="bottom-marker">Bottom marker</div></section>
- <label>Email input <input id="email-input" type="email" value="[email protected]"></label>
- <label>Number input <input id="number-input" type="number" value="123"></label>
- <label>Controlled input <input id="controlled-input" type="text"></label>
- <span id="controlled-state"></span>
- ${kind === "frame" ? '<div id="iframe-marker" data-iframe="true" style="border:2px solid #44f;padding:8px;margin-top:8px;">iframe target</div>' : ""}
+
+ ${kind === "frame" ? '<div id="iframe-marker" data-iframe="true" style="border:2px solid var(--accent);padding:4px 8px;margin-top:4px;border-radius:4px;font-size:0.8rem">iframe target</div>' : ""}
</main>
<script>
window.__fixtureState = {
@@ -305,23 +515,31 @@ function pageHtml(kind) {
checkboxChecked: false,
dropdownValue: "alpha",
valueEvents: {},
+ canvasStrokes: 0,
+ canvasPoints: 0,
+ canvasDrawing: false,
+ canvasLastPoint: null,
+ /* HTML5 DnD */
+ dndDropped: false,
+ dndData: "",
+ /* Pointer Events API */
+ pointerEventTypes: [],
+ pointerDownCount: 0,
+ pointerMoveCount: 0,
+ lastPointerType: "",
+ lastPointerPressure: 0,
};
+
+ /* ---- click / dblclick tracking ---- */
const count = document.querySelector("#click-count");
const clickButton = document.querySelector("#click-button");
for (const type of ["mousemove", "mousedown", "mouseup", "click", "dblclick"]) {
- document.addEventListener(
- type,
- (event) => {
- window.__fixtureState.pointerEvents.push({
- type,
- target: event.target.id || event.target.tagName,
- detail: event.detail,
- x: event.clientX,
- y: event.clientY,
- });
- },
- true,
- );
+ document.addEventListener(type, (event) => {
+ window.__fixtureState.pointerEvents.push({
+ type, target: event.target.id || event.target.tagName,
+ detail: event.detail, x: event.clientX, y: event.clientY,
+ });
+ }, true);
}
clickButton.addEventListener("click", (event) => {
window.__fixtureState.clicks += 1;
@@ -332,43 +550,41 @@ function pageHtml(kind) {
window.__fixtureState.doubleClicks += 1;
window.__fixtureState.lastDoubleClickDetail = event.detail;
});
+
+ /* ---- hover zone ---- */
for (const type of ["mousemove", "mouseover"]) {
document.querySelector("#hover-zone").addEventListener(type, () => {
window.__fixtureState.hovered = true;
});
}
+
+ /* ---- mouse-based drag (legacy) ---- */
let dragging = false;
- document.querySelector("#drag-source").addEventListener("mousedown", () => {
- dragging = true;
- });
+ document.querySelector("#drag-source").addEventListener("mousedown", () => { dragging = true; });
document.querySelector("#drag-target").addEventListener("mouseup", () => {
if (dragging) window.__fixtureState.dragged = true;
dragging = false;
});
+
+ /* ---- keyboard tracking ---- */
document.querySelector("#text-input").addEventListener("keydown", (event) => {
window.__fixtureState.keys.push(event.key);
- window.__fixtureState.keyEvents.push({
- type: event.type,
- key: event.key,
- value: event.target.value,
- });
+ window.__fixtureState.keyEvents.push({ type: event.type, key: event.key, value: event.target.value });
document.querySelector("#key-log").textContent = window.__fixtureState.keys.join(",");
});
for (const type of ["beforeinput", "input", "keyup"]) {
document.querySelector("#text-input").addEventListener(type, (event) => {
- window.__fixtureState.keyEvents.push({
- type,
- key: event.key || event.inputType || "",
- value: event.target.value,
- });
+ window.__fixtureState.keyEvents.push({ type, key: event.key || event.inputType || "", value: event.target.value });
});
}
+
+ /* ---- file input ---- */
document.querySelector("#file-input").addEventListener("change", (event) => {
document.querySelector("#file-name").textContent =
Array.from(event.target.files).map((file) => file.name).join(",");
});
- /* value inputs (email/number) — track input/change for fillInput regressions */
+ /* ---- value inputs (email/number) ---- */
for (const id of ["email-input", "number-input"]) {
const valueInput = document.querySelector("#" + id);
for (const type of ["input", "change"]) {
@@ -378,39 +594,25 @@ function pageHtml(kind) {
}
}
- /* react-style controlled input — every input event writes value back through
- the native prototype setter, mirroring React/Vue controlled components.
- Guards fillInput's persistence on inputs that fight back. */
+ /* ---- react-style controlled input ---- */
(function () {
const el = document.querySelector("#controlled-input");
const stateEl = document.querySelector("#controlled-state");
- const setter = Object.getOwnPropertyDescriptor(
- HTMLInputElement.prototype,
- "value",
- ).set;
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set;
let state = "";
- function render() {
- if (el.value !== state) setter.call(el, state);
- stateEl.textContent = state;
- }
- el.addEventListener("input", () => {
- state = el.value;
- render();
- });
- el.addEventListener("change", () => {
- stateEl.textContent = state + " (change)";
- });
+ function render() { if (el.value !== state) setter.call(el, state); stateEl.textContent = state; }
+ el.addEventListener("input", () => { state = el.value; render(); });
+ el.addEventListener("change", () => { stateEl.textContent = state + " (change)"; });
render();
})();
- /* context menu zone — captures right-click */
- const contextZone = document.querySelector("#context-menu-zone");
- contextZone.addEventListener("contextmenu", (event) => {
+ /* ---- context menu ---- */
+ document.querySelector("#context-menu-zone").addEventListener("contextmenu", (event) => {
event.preventDefault();
window.__fixtureState.rightClicked = true;
});
- /* dynamic DOM — add/remove elements */
+ /* ---- dynamic DOM ---- */
document.querySelector("#add-element").addEventListener("click", () => {
const container = document.querySelector("#dynamic-container");
if (!document.querySelector("#dynamic-element")) {
@@ -418,41 +620,116 @@ function pageHtml(kind) {
el.id = "dynamic-element";
el.setAttribute("role", "status");
el.textContent = "Dynamic!";
- el.style.cssText = "background:#efe;border:1px solid #7a7;padding:4px 8px;";
+ el.style.cssText = "";
container.appendChild(el);
window.__fixtureState.dynamicElementExists = true;
}
});
document.querySelector("#remove-element").addEventListener("click", () => {
const el = document.querySelector("#dynamic-element");
- if (el) {
- el.remove();
- window.__fixtureState.dynamicElementExists = false;
- }
+ if (el) { el.remove(); window.__fixtureState.dynamicElementExists = false; }
});
- /* checkbox */
+ /* ---- checkbox / dropdown ---- */
document.querySelector("#checkbox").addEventListener("change", (event) => {
window.__fixtureState.checkboxChecked = event.target.checked;
});
-
- /* dropdown */
document.querySelector("#dropdown").addEventListener("change", (event) => {
window.__fixtureState.dropdownValue = event.target.value;
});
- /* tab-trap focus tracking */
+ /* ---- tab-trap focus tracking ---- */
for (const stop of document.querySelectorAll(".tab-stop")) {
stop.addEventListener("focus", () => {
window.__fixtureState.tabOrder.push(stop.dataset.tab);
});
}
- /* delayed element */
+ /* ---- delayed element ---- */
setTimeout(() => {
const delayed = document.querySelector("#delayed");
delayed.style.display = "block";
}, 350);
+
+ /* ---- canvas drawing ---- */
+ (function () {
+ const canvas = document.querySelector("#draw-canvas");
+ const ctx = canvas.getContext("2d");
+ ctx.strokeStyle = "#000"; ctx.lineWidth = 2; ctx.lineCap = "round";
+ canvas.addEventListener("mousedown", (e) => {
+ const rect = canvas.getBoundingClientRect();
+ const x = e.clientX - rect.left, y = e.clientY - rect.top;
+ ctx.beginPath(); ctx.moveTo(x, y);
+ window.__fixtureState.canvasDrawing = true;
+ window.__fixtureState.canvasStrokes++;
+ window.__fixtureState.canvasPoints++;
+ window.__fixtureState.canvasLastPoint = { x, y };
+ });
+ canvas.addEventListener("mousemove", (e) => {
+ if (!window.__fixtureState.canvasDrawing) return;
+ const rect = canvas.getBoundingClientRect();
+ const x = e.clientX - rect.left, y = e.clientY - rect.top;
+ ctx.lineTo(x, y); ctx.stroke();
+ ctx.beginPath(); ctx.moveTo(x, y);
+ window.__fixtureState.canvasPoints++;
+ window.__fixtureState.canvasLastPoint = { x, y };
+ });
+ canvas.addEventListener("mouseup", () => { window.__fixtureState.canvasDrawing = false; });
+ })();
+
+ /* ---- HTML5 Drag and Drop ---- */
+ (function () {
+ const source = document.querySelector("#dnd-source");
+ const target = document.querySelector("#dnd-target");
+ const status = document.querySelector("#dnd-status");
+ source.addEventListener("dragstart", (e) => {
+ e.dataTransfer.setData("text/plain", "dnd-payload");
+ e.dataTransfer.effectAllowed = "move";
+ status.textContent = "Dragging...";
+ });
+ target.addEventListener("dragover", (e) => {
+ e.preventDefault();
+ e.dataTransfer.dropEffect = "move";
+ target.classList.add("drag-over");
+ });
+ target.addEventListener("dragleave", () => { target.classList.remove("drag-over"); });
+ target.addEventListener("drop", (e) => {
+ e.preventDefault();
+ target.classList.remove("drag-over");
+ const data = e.dataTransfer.getData("text/plain");
+ window.__fixtureState.dndDropped = true;
+ window.__fixtureState.dndData = data;
+ status.textContent = "Dropped: " + data;
+ target.textContent = "Dropped!";
+ });
+ source.addEventListener("dragend", () => {
+ if (!window.__fixtureState.dndDropped) status.textContent = "Drag cancelled";
+ });
+ })();
+
+ /* ---- Pointer Events API ---- */
+ (function () {
+ const area = document.querySelector("#pointer-area");
+ const indicator = area.querySelector(".pointer-indicator");
+ const log = document.querySelector("#pointer-log");
+ for (const type of ["pointerdown", "pointermove", "pointerup", "pointerenter", "pointerleave", "pointercancel"]) {
+ area.addEventListener(type, (e) => {
+ window.__fixtureState.pointerEventTypes.push(type);
+ if (type === "pointerdown") window.__fixtureState.pointerDownCount++;
+ if (type === "pointermove") {
+ window.__fixtureState.pointerMoveCount++;
+ const rect = area.getBoundingClientRect();
+ indicator.style.left = (e.clientX - rect.left) + "px";
+ indicator.style.top = (e.clientY - rect.top) + "px";
+ indicator.style.opacity = "1";
+ }
+ if (type === "pointerleave") indicator.style.opacity = "0";
+ window.__fixtureState.lastPointerType = e.pointerType;
+ window.__fixtureState.lastPointerPressure = e.pressure;
+ log.textContent = type + " (" + e.pointerType + ") p=" + e.pressure.toFixed(2);
+ });
+ }
+ })();
</script>
</body>
</html>`;
diff --git a/package/ego-browser/scripts/real-browser-e2e/preamble.mjs b/package/ego-browser/scripts/real-browser-e2e/preamble.mjs
new file mode 100644
index 0000000..512050f
--- /dev/null
+++ b/package/ego-browser/scripts/real-browser-e2e/preamble.mjs
@@ -0,0 +1,269 @@
+// E2E test preamble — assertion helpers and utility functions.
+// This file is read by ego-source.mjs and injected into the generated test
+// script that runs inside ego-browser. It is NOT imported as a module; it is
+// concatenated into the script body so all declarations are in the same scope
+// as the case body and epilogue.
+
+const { stat, readFile, writeFile } = await import("node:fs/promises");
+const { join } = await import("node:path");
+
+let __assertionCount = 0;
+
+function formatAssertionValue(value) {
+ try {
+ return JSON.stringify(value).slice(0, 500);
+ } catch {
+ return String(value).slice(0, 500);
+ }
+}
+
+function logAssertion(status, message, details = {}) {
+ if (!verboseAssertions) return;
+ cliLog(
+ JSON.stringify({
+ assertion: {
+ status,
+ message,
+ ...details,
+ },
+ }),
+ );
+}
+
+function assert(condition, message) {
+ __assertionCount++;
+ logAssertion("start", message);
+ if (!condition) {
+ logAssertion("fail", message);
+ throw new Error(message);
+ }
+ logAssertion("pass", message);
+}
+
+function assertEqual(actual, expected, message) {
+ __assertionCount++;
+ logAssertion("start", message);
+ if (actual !== expected) {
+ logAssertion("fail", message, {
+ expected: formatAssertionValue(expected),
+ actual: formatAssertionValue(actual),
+ });
+ throw new Error(
+ message +
+ ": expected " +
+ JSON.stringify(expected) +
+ ", got " +
+ JSON.stringify(actual),
+ );
+ }
+ logAssertion("pass", message);
+}
+
+function assertIncludes(text, expected, message) {
+ __assertionCount++;
+ logAssertion("start", message);
+ if (!String(text).includes(expected)) {
+ logAssertion("fail", message, {
+ expected: formatAssertionValue(expected),
+ actual: formatAssertionValue(String(text).slice(0, 500)),
+ });
+ throw new Error(
+ message +
+ ": expected " +
+ JSON.stringify(String(text).slice(0, 500)) +
+ " to include " +
+ JSON.stringify(expected),
+ );
+ }
+ logAssertion("pass", message);
+}
+
+async function assertRejects(fn, expected, message) {
+ __assertionCount++;
+ logAssertion("start", message);
+ try {
+ await fn();
+ } catch (error) {
+ const errorMessage = error?.message || String(error);
+ if (!String(errorMessage).includes(expected)) {
+ logAssertion("fail", message, {
+ expected: formatAssertionValue(expected),
+ actual: formatAssertionValue(errorMessage),
+ });
+ throw new Error(
+ message +
+ ": expected " +
+ JSON.stringify(String(errorMessage).slice(0, 500)) +
+ " to include " +
+ JSON.stringify(expected),
+ );
+ }
+ logAssertion("pass", message);
+ return;
+ }
+ logAssertion("fail", message, { expected: "rejection" });
+ throw new Error(message + ": expected rejection");
+}
+
+async function assertRejectsAny(fn, message) {
+ __assertionCount++;
+ logAssertion("start", message);
+ try {
+ await fn();
+ } catch {
+ logAssertion("pass", message);
+ return;
+ }
+ logAssertion("fail", message, { expected: "rejection" });
+ throw new Error(message + ": expected rejection");
+}
+
+async function waitForJsValue(
+ expression,
+ expected,
+ message,
+ debugExpression = null,
+) {
+ __assertionCount++;
+ logAssertion("start", message);
+ const deadline = Date.now() + 2000;
+ let last;
+ while (Date.now() <= deadline) {
+ last = await js(expression);
+ if (last === expected) {
+ logAssertion("pass", message);
+ return last;
+ }
+ await wait(0.05);
+ }
+ let detail = "";
+ if (debugExpression) {
+ detail = "; debug=" + JSON.stringify(await js(debugExpression));
+ }
+ logAssertion("fail", message, {
+ expected: formatAssertionValue(expected),
+ actual: formatAssertionValue(last),
+ });
+ throw new Error(
+ message +
+ detail +
+ ": expected " +
+ JSON.stringify(expected) +
+ ", got " +
+ JSON.stringify(last),
+ );
+}
+
+async function waitForJsCondition(expression, message, debugExpression = null) {
+ __assertionCount++;
+ logAssertion("start", message);
+ const deadline = Date.now() + 2000;
+ let last;
+ while (Date.now() <= deadline) {
+ last = await js(expression);
+ if (last) {
+ logAssertion("pass", message);
+ return last;
+ }
+ await wait(0.05);
+ }
+ let detail = "";
+ if (debugExpression) {
+ detail = "; debug=" + JSON.stringify(await js(debugExpression));
+ }
+ logAssertion("fail", message, {
+ actual: formatAssertionValue(last),
+ });
+ throw new Error(
+ message +
+ detail +
+ ": condition stayed false, last value " +
+ JSON.stringify(last),
+ );
+}
+
+async function allowWheelDispatch(label, fn) {
+ try {
+ await fn();
+ return true;
+ } catch (error) {
+ const message = error?.message || String(error);
+ if (
+ /Input\.dispatchMouseEvent|CDP request timed out: Input\.dispatchMouseEvent/.test(
+ message,
+ )
+ ) {
+ cliLog(JSON.stringify({ inputDispatchWarning: { label, message } }));
+ return false;
+ }
+ throw error;
+ }
+}
+
+async function setStableViewport() {
+ await cdp("Page.bringToFront").catch(() => {});
+ await cdp("Emulation.clearDeviceMetricsOverride").catch(() => {});
+ await cdp("Emulation.setDeviceMetricsOverride", {
+ width: 1280,
+ height: 800,
+ deviceScaleFactor: 1,
+ mobile: false,
+ }).catch(() => {});
+ await wait(0.1);
+}
+
+async function hitTestClickButton() {
+ return js(
+ "const el = document.querySelector('#click-button');" +
+ "if (!el) return '';" +
+ "const r = el.getBoundingClientRect();" +
+ "const hit = document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2);" +
+ "return hit?.closest?.('#click-button')?.id || hit?.id || '';",
+ ).catch(() => "");
+}
+
+async function closeFixtureTabs() {
+ const tabs = await listTabs({ includeChrome: false }).catch(() => []);
+ for (const tab of tabs) {
+ if (String(tab.url || "").startsWith(baseUrl)) {
+ await closeTab(tab.targetId).catch(() => {});
+ }
+ }
+}
+
+async function resetHome() {
+ await takeOverTaskSpace(taskName).catch(() => {});
+ await waitForAgentControl(taskName, { interval: 0.1, timeout: 5 });
+ await closeFixtureTabs();
+ const tab = await openOrReuseTab(baseUrl + "/?e2e-reset=" + Date.now(), {
+ wait: true,
+ timeout: 10,
+ });
+ await switchTab(tab.targetId);
+ await setStableViewport();
+ const nav = await gotoAndWait(baseUrl + "/", { timeout: 10 });
+ assert(nav.loaded, "home page loaded");
+ await setStableViewport();
+ assert(
+ await waitForElement("#click-button", { timeout: 3, visible: true }),
+ "home fixture click button is visible",
+ );
+ for (let i = 0; i < 10; i += 1) {
+ const info = await pageInfo();
+ if (
+ info.w > 0 &&
+ info.h > 0 &&
+ (await hitTestClickButton()) === "click-button"
+ )
+ return tab;
+ await setStableViewport();
+ }
+ const info = await pageInfo();
+ assert(info.w > 0 && info.h > 0, "viewport initialized with non-zero size");
+ assertEqual(
+ await hitTestClickButton(),
+ "click-button",
+ "viewport hit-testing reaches the click fixture",
+ );
+ return tab;
+}
diff --git a/package/ego-browser/scripts/real-browser-e2e/run-command.mjs b/package/ego-browser/scripts/real-browser-e2e/run-command.mjs
index 0c70d47..0ae07b5 100644
--- a/package/ego-browser/scripts/real-browser-e2e/run-command.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/run-command.mjs
@@ -5,6 +5,7 @@ export function runCommand(command, args, options = {}) {
let stdout = "";
let stderr = "";
let settled = false;
+ const echo = options.echo !== false;
const child = spawn(command, args, {
cwd: options.cwd ?? process.cwd(),
env: process.env,
@@ -37,11 +38,11 @@ export function runCommand(command, args, options = {}) {
});
child.stdout?.on("data", (chunk) => {
stdout += chunk;
- process.stdout.write(chunk);
+ if (echo) process.stdout.write(chunk);
});
child.stderr?.on("data", (chunk) => {
stderr += chunk;
- process.stderr.write(chunk);
+ if (echo) process.stderr.write(chunk);
});
child.on("close", (code) => {
if (settled) return;
diff --git a/package/ego-browser/scripts/real-browser-e2e/runner.mjs b/package/ego-browser/scripts/real-browser-e2e/runner.mjs
index a01eae7..146b023 100644
--- a/package/ego-browser/scripts/real-browser-e2e/runner.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/runner.mjs
@@ -19,6 +19,9 @@ const runnerDir = dirname(fileURLToPath(import.meta.url));
const packageDir = join(runnerDir, "..", "..");
const egoBrowserSdkPath = join(packageDir, "dist", "out", "index.js");
const egoBrowserArgs = ["nodejs", "--sdk-path", egoBrowserSdkPath];
+const verboseCaseOutput =
+ process.env.EGO_BROWSER_REAL_E2E_VERBOSE_CASE_OUTPUT === "1" ||
+ process.env.EGO_BROWSER_REAL_E2E_VERBOSE_CASE_OUTPUT === "true";
export async function runRealBrowserE2e() {
const keepTaskSpace =
@@ -30,6 +33,21 @@ export async function runRealBrowserE2e() {
.map((name) => name.trim())
.filter(Boolean),
);
+ const availableCaseNames = [
+ "nodejs bridge smoke",
+ ...e2eCases.map((testCase) => testCase.name),
+ ];
+ const unknownOnlyCases = [...onlyCases].filter(
+ (name) => !availableCaseNames.includes(name),
+ );
+ if (unknownOnlyCases.length > 0) {
+ console.error(
+ `Unknown EGO_BROWSER_REAL_E2E_ONLY case(s): ${unknownOnlyCases.join(", ")}`,
+ );
+ console.error(`Available cases: ${availableCaseNames.join(", ")}`);
+ process.exitCode = 2;
+ return;
+ }
let server;
let tempDir;
@@ -41,34 +59,108 @@ export async function runRealBrowserE2e() {
caseResults.push({ name, status, durationMs, assertionCount, message });
}
- async function runEgoCase(name, body, timeoutMs = 45000) {
+ async function runNodeBridgeSmoke(timeoutMs = 15000) {
+ const name = "nodejs bridge smoke";
console.log(`-- ${name}`);
+ const startedAt = Date.now();
+ const marker = `EGO_NODEJS_BRIDGE_SMOKE_${Date.now()}`;
+ const source = `
+ console.log(${JSON.stringify(marker)});
+ console.log(JSON.stringify({
+ egoType: typeof globalThis.ego,
+ hasSendCDPMessage: typeof globalThis.ego?.sendCDPMessage,
+ processVersion: process.version,
+ cliLogType: typeof globalThis.cliLog,
+ helperCount: Object.keys(globalThis.ego?.helpers || {}).length
+ }));
+ `;
+ try {
+ const { stdout, stderr } = await runCommand(
+ "ego-browser",
+ egoBrowserArgs,
+ {
+ cwd: packageDir,
+ egoBrowserSdkPath,
+ echo: verboseCaseOutput,
+ input: source,
+ timeoutMs,
+ },
+ );
+ const probe = parseNodeBridgeSmoke(`${stdout}\n${stderr}`, marker);
+ if (
+ probe.egoType !== "object" ||
+ probe.hasSendCDPMessage !== "function" ||
+ probe.cliLogType !== "function" ||
+ typeof probe.processVersion !== "string" ||
+ probe.helperCount <= 0
+ ) {
+ throw new Error(
+ `nodejs bridge smoke returned invalid runtime data: ${JSON.stringify(probe)}`,
+ );
+ }
+ const durationMs = Date.now() - startedAt;
+ recordResult(name, "pass", durationMs, 5);
+ console.log(
+ `-- ${name} passed (${formatDuration(durationMs)}, 5 assertions)`,
+ );
+ } catch (error) {
+ const durationMs = Date.now() - startedAt;
+ const message = error?.message || String(error);
+ recordResult(name, "fail", durationMs, 0, message);
+ console.error(
+ `[FAIL] ${name} (${formatDuration(durationMs)}): ${message}`,
+ );
+ }
+ }
+
+ async function maybeRunNodeBridgeSmoke() {
+ await runNodeBridgeSmoke();
+ }
+
+ async function runEgoCase(name, body, timeoutMs = 45000, options = {}) {
+ const visible = options.visible !== false;
+ if (visible) console.log(`-- ${name}`);
const source = egoSource(body, {
...context,
keepTaskSpace: keepTaskSpace && passed,
});
const startedAt = Date.now();
+ await rm(caseResultPath(tempDir), { force: true });
try {
const { stdout } = await runCommand("ego-browser", egoBrowserArgs, {
cwd: packageDir,
egoBrowserSdkPath,
+ echo: verboseCaseOutput,
input: source,
timeoutMs,
});
const durationMs = Date.now() - startedAt;
- const assertions = await readCaseAssertionCount(tempDir, stdout);
+ const caseResult = await readCaseResult(tempDir, stdout);
+ if (!caseResult.ok) {
+ const error = new Error(caseResult.error);
+ error.stdout = stdout;
+ throw error;
+ }
+ const assertions = caseResult.assertions;
recordResult(name, "pass", durationMs, assertions);
- console.log(
- `-- ${name} passed (${formatDuration(durationMs)}, ${assertions} assertions)`,
- );
+ if (visible) {
+ console.log(
+ `-- ${name} passed (${formatDuration(durationMs)}, ${assertions} assertions)`,
+ );
+ }
} catch (error) {
const durationMs = Date.now() - startedAt;
- const message = error?.message || String(error);
- const assertions = await readCaseAssertionCount(tempDir, error?.stdout);
+ const caseResult = await readCaseResult(tempDir, error?.stdout);
+ const message = caseResult.error || error?.message || String(error);
+ const assertions = caseResult.assertions;
recordResult(name, "fail", durationMs, assertions, message);
- console.error(
- `[FAIL] ${name} (${formatDuration(durationMs)}): ${message}`,
- );
+ if (visible) {
+ console.error(
+ `[FAIL] ${name} (${formatDuration(durationMs)}): ${message}`,
+ );
+ } else {
+ console.error(`[${name}] ${message}`);
+ }
}
}
@@ -96,6 +188,7 @@ export async function runRealBrowserE2e() {
}
`,
20000,
+ { visible: false },
);
// Remove cleanup result and any failures it produced
const cleanupResults = caseResults.filter((r) => r.name === "cleanup");
@@ -147,6 +240,18 @@ export async function runRealBrowserE2e() {
console.log(`task: ${taskName}`);
console.log(`sdk: ${egoBrowserSdkPath}`);
+ await maybeRunNodeBridgeSmoke();
+ if (
+ caseResults.some(
+ (r) => r.name === "nodejs bridge smoke" && r.status === "fail",
+ )
+ ) {
+ context.skipCleanup = true;
+ printSummary(caseResults, Date.now() - totalStartedAt);
+ process.exitCode = 1;
+ return;
+ }
+
for (const testCase of e2eCases) {
await maybeRunEgoCase(testCase.name, testCase.body());
}
@@ -161,7 +266,7 @@ export async function runRealBrowserE2e() {
console.error(error?.stack || error?.message || String(error));
process.exitCode = error?.code === "ENOENT" ? 127 : 1;
} finally {
- if (context.taskName) {
+ if (context.taskName && !context.skipCleanup) {
await cleanupTaskSpace().catch((error) => {
console.error(`[cleanup] ${error?.message || error}`);
});
@@ -217,16 +322,55 @@ async function initializeE2eEnvironment(context, tempDir) {
);
}
+function parseNodeBridgeSmoke(stdout, marker) {
+ const lines = String(stdout || "")
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .filter(Boolean);
+ const markerIndex = lines.indexOf(marker);
+ if (markerIndex === -1) {
+ throw new Error(
+ "nodejs bridge did not print the console.log smoke marker; ego-browser nodejs may have exited without executing stdin",
+ );
+ }
+ const payload = lines[markerIndex + 1];
+ if (!payload) {
+ throw new Error("nodejs bridge smoke did not print runtime probe data");
+ }
+ try {
+ return JSON.parse(payload);
+ } catch (error) {
+ throw new Error(
+ `nodejs bridge smoke printed invalid runtime probe data: ${payload}`,
+ );
+ }
+}
+
+function caseResultPath(tempDir) {
+ return join(tempDir, "case-result.json");
+}
+
async function readCaseAssertionCount(tempDir, stdout) {
- const resultPath = join(tempDir, "case-result.json");
+ return (await readCaseResult(tempDir, stdout)).assertions;
+}
+
+async function readCaseResult(tempDir, stdout) {
+ const resultPath = caseResultPath(tempDir);
try {
const raw = await readFile(resultPath, "utf8");
const parsed = JSON.parse(raw);
- if (typeof parsed.assertions === "number") return parsed.assertions;
- } catch {
- // file not written or not valid JSON — fall back to stdout
+ return {
+ ok: parsed.ok === true,
+ assertions: typeof parsed.assertions === "number" ? parsed.assertions : 0,
+ error: parsed.error || "case-result.json reported failure",
+ };
+ } catch (error) {
+ return {
+ ok: false,
+ assertions: extractAssertionCount(stdout),
+ error: `case-result.json was not written or readable; ego-browser nodejs may have exited without executing stdin (${error?.message || error})`,
+ };
}
- return extractAssertionCount(stdout);
}
function extractAssertionCount(stdout) {
@@ -257,12 +401,13 @@ function printSummary(results, totalMs) {
const passed = results.filter((r) => r.status === "pass").length;
const failed = results.filter((r) => r.status === "fail").length;
const skipped = results.filter((r) => r.status === "skip").length;
+ const executed = passed + failed;
const totalAssertions = results.reduce((sum, r) => sum + r.assertionCount, 0);
console.log("");
console.log("== E2E Summary ==");
console.log(
- ` Passed: ${passed}/${total}${total > 0 ? ` (${Math.round((passed / total) * 100)}%)` : ""}`,
+ ` Passed: ${passed}/${executed}${executed > 0 ? ` (${Math.round((passed / executed) * 100)}%)` : ""}`,
);
if (failed > 0) console.log(` Failed: ${failed}/${total}`);
if (skipped > 0) console.log(` Skipped: ${skipped}/${total}`);