The fastest browser for AI agents to run browser automation, built for sharing your logged-in browser state with your AI agents, like Codex or Claude Code, without disturbing you. Zero cost, zero config.
JavaScript agent-skillsai-agentautomationbrowserbrowser-automationclaude-codecodexhermes-agentskillsskills-sh
feat(ego-browser): add probe-and-fallback for keyboard/pointer input reliability
Tachikoma44d19a7da526
diff --git a/package/ego-browser/package.json b/package/ego-browser/package.jsonindex 1aff579..1138482 100644--- a/package/ego-browser/package.json+++ b/package/ego-browser/package.json@@ -9,7 +9,7 @@"scripts": {"clean": "rm -rf dist artifacts","build": "node scripts/build.mjs",- "e2e": "bash scripts/run-e2e.sh",+ "e2e": "node scripts/run-real-browser-e2e.mjs","prepare": "if [ \"$CI\" = \"true\" ]; then exit 0; fi; cd ../.. && lefthook install","style:check": "prettier --check","typecheck": "tsc --noEmit",diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/environment.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/environment.mjsnew file mode 100644index 0000000..ffcafd1--- /dev/null+++ b/package/ego-browser/scripts/real-browser-e2e/cases/environment.mjs@@ -0,0 +1,59 @@+export function environmentCase() {+ return `+ const metadataStat = await stat(metadataPath);+ assert(metadataStat.size > 0, "environment metadata file exists");+ const uploadStat = await stat(uploadPath);+ const uploadStatTwo = await stat(uploadPathTwo);+ assert(uploadStat.size > 0 && uploadStatTwo.size > 0, "upload fixture files exist");+ const artifactStat = await stat(artifactDir);+ assert(artifactStat.isDirectory(), "artifact directory exists");++ const healthText = await serverFetch(baseUrl + "/healthz", { timeout: 5 });+ const health = JSON.parse(healthText);+ assertEqual(health.ok, true, "fixture health endpoint is ok through serverFetch");+ assertEqual(health.taskName, taskName, "fixture health endpoint carries the current task name");++ const task = await useOrCreateTaskSpace(taskName);+ assertEqual(task.name, taskName, "environment creates/selects isolated task space");++ let home = await resetHome();+ assert(home.targetId, "environment opens a real fixture tab");++ const info = await pageInfo();+ assertEqual(info.title, "ego-lite helper e2e", "environment page title is stable");+ assertIncludes(info.url, baseUrl + "/", "environment page URL is fixture root");+ assert(info.w > 0 && info.h > 0, "environment viewport is usable");++ const browserHealthText = await browserFetch("/healthz", { timeout: 5 });+ const browserHealth = JSON.parse(browserHealthText);+ assertEqual(browserHealth.ok, true, "fixture health endpoint is ok through browserFetch");++ const jsonText = await serverFetch(baseUrl + "/api/json", { timeout: 5 });+ assertEqual(JSON.parse(jsonText).value, "json fixture", "JSON fixture route is deterministic");++ const runtimeProbe = await cdp("Runtime.evaluate", {+ expression: "1 + 1",+ returnByValue: true,+ });+ assertEqual(runtimeProbe.result.value, 2, "CDP Runtime.evaluate is available");+ try {+ const browserVersion = await cdp("Browser.getVersion");+ assert(browserVersion.product || browserVersion.userAgent, "CDP Browser.getVersion returns capability data");+ } catch (error) {+ cliLog(JSON.stringify({ capabilityWarning: { method: "Browser.getVersion", message: error?.message || String(error) } }));+ }++ await fillInput("#text-input", "dirty", { timeout: 3 });+ assertEqual(await js("return document.querySelector('#text-input').value"), "dirty", "environment can dirty fixture state");+ home = await resetHome();+ assertEqual(await js("return document.querySelector('#text-input').value"), "initial", "resetHome restores deterministic fixture state");++ const envShot = await captureScreenshot(environmentScreenshotPath, { full: false });+ assertEqual(envShot, environmentScreenshotPath, "environment screenshot uses artifact path");+ const envShotStat = await stat(envShot);+ assert(envShotStat.size > 0, "environment screenshot artifact is non-empty");++ const tabs = await listTabs({ includeChrome: false });+ assert(tabs.some((tab) => tab.targetId === home.targetId), "environment tab appears in listTabs");+ `;+}diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/helper-surface.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/helper-surface.mjsnew file mode 100644index 0000000..f028249--- /dev/null+++ b/package/ego-browser/scripts/real-browser-e2e/cases/helper-surface.mjs@@ -0,0 +1,58 @@+export function helperSurfaceCase() {+ return `+ const expectedHelpers = [+ "listTaskSpaces",+ "switchTaskSpace",+ "newTaskSpace",+ "useOrCreateTaskSpace",+ "claimTaskSpace",+ "completeTaskSpace",+ "handOffTaskSpace",+ "takeOverTaskSpace",+ "waitForAgentControl",+ "pageInfo",+ "listTabs",+ "currentTab",+ "switchTab",+ "openOrReuseTab",+ "closeTab",+ "gotoUrl",+ "gotoAndWait",+ "ensureRealTab",+ "iframeTarget",+ "snapshot",+ "snapshotRaw",+ "snapshotText",+ "captureScreenshot",+ "elementCenter",+ "drainEvents",+ "click",+ "doubleClick",+ "hover",+ "dragMouse",+ "scroll",+ "scrollBy",+ "scrollToBottomUntil",+ "pressKey",+ "typeText",+ "fillInput",+ "dispatchKey",+ "uploadFile",+ "wait",+ "waitForLoad",+ "waitForElement",+ "waitForNetworkIdle",+ "serverFetch",+ "browserFetch",+ "cdp",+ "js",+ "help",+ ];+ for (const name of expectedHelpers) {+ assertEqual(typeof globalThis[name], "function", "helper is installed: " + name);+ }+ assertEqual(typeof globalThis.newTab, "undefined", "internal newTab is not exposed");+ const helpText = help("missingHelperForE2E");+ assertIncludes(helpText, "Unknown helper", "help reports unknown helper names");+ `;+}diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjsnew file mode 100644index 0000000..a9b7517--- /dev/null+++ b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs@@ -0,0 +1,19 @@+import { environmentCase } from "./environment.mjs";+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 { keyboardCase } from "./keyboard.mjs";+import { runtimeCase } from "./runtime.mjs";++export const e2eCases = [+ { name: "environment initialization", body: environmentCase },+ { name: "helper surface", body: helperSurfaceCase },+ { 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: "keyboard and file helpers", body: keyboardCase },+ { name: "wait, fetch, cdp, js, help", body: runtimeCase },+];diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/keyboard.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/keyboard.mjsnew file mode 100644index 0000000..573ce92--- /dev/null+++ b/package/ego-browser/scripts/real-browser-e2e/cases/keyboard.mjs@@ -0,0 +1,96 @@+export function keyboardCase() {+ return `+ await useOrCreateTaskSpace(taskName);+ await resetHome();++ await fillInput("#text-input", "filled", { timeout: 3 });+ let value = await js("return document.querySelector('#text-input').value");+ assertEqual(value, "filled", "fillInput writes text");++ await fillInput("loc=css:#text-area", "area text", { timeout: 3 });+ const areaValue = await js("return document.querySelector('#text-area').value");+ assertEqual(areaValue, "area text", "fillInput supports textarea through loc=css");++ await js("const el = document.querySelector('#append-input'); el.focus(); el.setSelectionRange(el.value.length, el.value.length); return el.value");+ await fillInput("#append-input", "-suffix", { clearFirst: false, timeout: 3 });+ const appended = await js("return document.querySelector('#append-input').value");+ assertEqual(appended, "base-suffix", "fillInput clearFirst:false preserves existing input value");++ await js("return document.querySelector('#text-input').focus()");+ await typeText(" text");+ value = await js("return document.querySelector('#text-input').value");+ assertEqual(value, "filled text", "typeText appends focused text");++ await fillInput("#text-input", "abc", { timeout: 3 });+ await js("const el = document.querySelector('#text-input'); el.focus(); el.setSelectionRange(el.value.length, el.value.length); return el.value");+ await pressKey("Backspace");+ await waitForJsValue(+ "document.querySelector('#text-input').value",+ "ab",+ "pressKey Backspace edits the focused input",+ "window.__fixtureState.keyEvents"+ );+ const activeAfterPress = await js("return document.activeElement?.id || ''");+ assertEqual(activeAfterPress, "text-input", "pressKey keeps the focused input active");++ await dispatchKey("#text-input", "Escape", "keydown");+ let keys = await js("return window.__fixtureState.keys.join(',')");+ assertIncludes(keys, "Escape", "dispatchKey dispatches synthetic keyboard input");++ await fillInput("#text-input", "select me", { timeout: 3 });+ const selectAllModifier = process.platform === "darwin" ? 4 : 2;+ await pressKey("a", selectAllModifier);+ await typeText("selected");+ await waitForJsValue(+ "document.querySelector('#text-input').value",+ "selected",+ "pressKey supports platform select-all modifiers"+ );++ await uploadFile("#file-input", uploadPath);+ let fileName = await js("return Array.from(document.querySelector('#file-input').files).map((file) => file.name).join(',')");+ assertEqual(fileName, "fixture-upload.txt", "uploadFile attaches a single file");++ await uploadFile("#file-input", [uploadPath, uploadPathTwo]);+ fileName = await js("return Array.from(document.querySelector('#file-input').files).map((file) => file.name).join(',')");+ assertEqual(fileName, "fixture-upload.txt,fixture-upload-two.txt", "uploadFile attaches multiple files");++ await assertRejects(+ () => fillInput("#missing-input", "nope", { timeout: 0.2 }),+ "element not found",+ "fillInput reports missing elements"+ );+ await assertRejects(+ () => uploadFile("#missing-file-input", uploadPath),+ "Element not found",+ "uploadFile reports missing file inputs"+ );+ await assertRejects(+ () => dispatchKey("#missing-input", "Enter"),+ "Element not found",+ "dispatchKey reports missing targets"+ );++ /* contentEditable typing */+ cliLog(JSON.stringify({ keyboardStep: "contentEditable" }));+ await click("#rich-editor");+ await js("document.querySelector('#rich-editor').focus(); document.querySelector('#rich-editor').textContent = ''; return true;");+ await typeText("hello world");+ const editorText = await js("return document.querySelector('#rich-editor').textContent");+ assertIncludes(editorText, "hello world", "typeText inserts text into contentEditable element");++ /* rapid Backspace sequence */+ cliLog(JSON.stringify({ keyboardStep: "rapid backspace" }));+ await fillInput("#text-input", "test", { timeout: 3 });+ await js("const el = document.querySelector('#text-input'); el.focus(); el.setSelectionRange(el.value.length, el.value.length); return el.value");+ await pressKey("Backspace");+ await pressKey("Backspace");+ await pressKey("Backspace");+ await waitForJsValue(+ "document.querySelector('#text-input').value",+ "t",+ "three rapid Backspaces delete three characters",+ "window.__fixtureState.keyEvents"+ );+ `;+}diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/navigation.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/navigation.mjsnew file mode 100644index 0000000..fb5f438--- /dev/null+++ b/package/ego-browser/scripts/real-browser-e2e/cases/navigation.mjs@@ -0,0 +1,106 @@+export function navigationCase() {+ return `+ await switchTaskSpace(taskName);+ const home = await resetHome();++ const info = await pageInfo();+ assertEqual(info.title, "ego-lite helper e2e", "pageInfo reads fixture title");+ assertIncludes(info.url, baseUrl + "/", "pageInfo reads current URL");+ assert(info.w > 0 && info.h > 0, "pageInfo returns viewport size");+ assert(Number.isFinite(info.pw) && Number.isFinite(info.ph), "pageInfo returns page dimensions");++ const tabs = await listTabs({ includeChrome: false });+ assert(tabs.some((tab) => tab.targetId === home.targetId), "listTabs includes home tab");+ const allTabs = await listTabs();+ assert(allTabs.length >= tabs.length, "listTabs defaults to include chrome/internal tabs");++ const current = await currentTab();+ assertEqual(current.targetId, home.targetId, "currentTab follows selected tab");++ const real = await ensureRealTab();+ assert(real && real.targetId, "ensureRealTab returns a real tab");++ const reused = await openOrReuseTab(baseUrl + "/", { wait: true, timeout: 10 });+ assertEqual(reused.reused, true, "openOrReuseTab reuses exact home URL");++ const byOrigin = await openOrReuseTab(baseUrl + "/not-opened", {+ match: "origin",+ wait: false,+ });+ assertEqual(byOrigin.reused, true, "openOrReuseTab reuses by origin");++ const byPath = await openOrReuseTab(baseUrl + "/?query=1", {+ match: "origin+path",+ wait: false,+ });+ assertEqual(byPath.reused, true, "openOrReuseTab reuses by origin and path");++ const unique = await openOrReuseTab(baseUrl + "/secondary?unique=" + Date.now(), {+ wait: false,+ });+ assertEqual(unique.reused, false, "openOrReuseTab opens a unique exact URL");+ await closeTab(unique.targetId);+ await switchTab(home);++ const secondary = await openOrReuseTab(baseUrl + "/secondary", {+ wait: true,+ timeout: 10,+ });+ await switchTab(secondary);+ assert(await waitForLoad({ timeout: 10 }), "secondary tab loads before target-id evaluation");+ const secondaryTitleViaTarget = await js("return document.title", secondary.targetId);+ assertEqual(secondaryTitleViaTarget, "ego-lite secondary", "js evaluates against explicit target id");+ const homeTitleViaTarget = await js("return document.title", home.targetId);+ assertEqual(homeTitleViaTarget, "ego-lite helper e2e", "js target id leaves current tab independent");++ const secondaryByIncludes = await openOrReuseTab("/secondary", {+ match: "includes",+ wait: false,+ });+ assertEqual(secondaryByIncludes.reused, true, "openOrReuseTab reuses by URL substring");+ await switchTab(secondary);+ const secondaryInfo = await pageInfo();+ assertEqual(secondaryInfo.title, "ego-lite secondary", "switchTab selects secondary tab");++ const closedId = await closeTab(secondary);+ assertEqual(closedId, secondary.targetId, "closeTab returns closed target id");+ await switchTab(home);++ const closeCurrent = await openOrReuseTab(baseUrl + "/secondary?close=current", {+ wait: true,+ timeout: 10,+ });+ await switchTab(closeCurrent);+ const currentClosedId = await closeTab();+ assertEqual(currentClosedId, closeCurrent.targetId, "closeTab closes current tab by default");+ await switchTab(home);++ const afterCloseCurrent = await currentTab();+ assertEqual(afterCloseCurrent.targetId, home.targetId, "switchTab restores home after closing current tab");++ await assertRejects(+ () => closeTab(""),+ "closeTab requires a targetId",+ "closeTab validates empty target id"+ );++ await gotoUrl(baseUrl + "/nav-target");+ assert(await waitForLoad({ timeout: 10 }), "waitForLoad observes gotoUrl navigation");+ const navInfo = await pageInfo();+ assertEqual(navInfo.title, "ego-lite nav target", "gotoUrl navigates current tab");++ const noWaitNav = await gotoAndWait(baseUrl + "/nav-target?no-wait=1", {+ wait: false,+ });+ assertEqual(noWaitNav.loaded, false, "gotoAndWait supports wait:false");+ assert(await waitForLoad({ timeout: 10 }), "waitForLoad can follow wait:false navigation");++ const nav = await gotoAndWait(baseUrl + "/", { timeout: 10, settle: 0.1 });+ 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");+ 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.mjsnew file mode 100644index 0000000..e45dd7f--- /dev/null+++ b/package/ego-browser/scripts/real-browser-e2e/cases/observation.mjs@@ -0,0 +1,141 @@+export function observationCase() {+ return `+ await switchTaskSpace(taskName);+ await resetHome();++ const raw = await snapshotRaw({ includeStableLocator: true });+ assertIncludes(raw.content || "", "Helper e2e fixture", "snapshotRaw contains fixture content");++ const compactRaw = await snapshotRaw({+ scope: "only_within_viewport",+ includeActionMarks: false,+ includeStableLocator: false,+ });+ assertIncludes(compactRaw.content || "", "Helper e2e fixture", "snapshotRaw accepts compact options");++ const snap = await snapshot({+ scope: "full_page",+ includeActionMarks: true,+ includeStableLocator: true,+ });+ assertIncludes(snap.content || "", "Click counter", "snapshot contains button text");+ assert(Array.isArray(snap.refs), "snapshot returns refs array");++ const buttonRef = (snap.refs || []).find(+ (ref) =>+ String(ref?.role || "") === "button" &&+ (String(ref?.name || "").includes("Increment counter") ||+ String(ref?.name || "").includes("Click counter"))+ )?.backendNodeId;+ assert(buttonRef, "snapshot exposes a reusable backend ref for the button");+ const atRefCenter = await elementCenter("@" + buttonRef);+ assert(Number.isFinite(atRefCenter.x) && Number.isFinite(atRefCenter.y), "@ref resolves to coordinates");+ const namedRefCenter = await elementCenter("ref=" + buttonRef);+ assert(Number.isFinite(namedRefCenter.x) && Number.isFinite(namedRefCenter.y), "ref= resolves to coordinates");++ const text = await snapshotText({ scope: "full_page" });+ assertIncludes(text, "Text input", "snapshotText returns text content");++ const viewportText = await snapshotText({ scope: "only_within_viewport" });+ assertIncludes(viewportText, "Helper e2e fixture", "snapshotText supports viewport scope");++ const center = await elementCenter("#click-button");+ assert(Number.isFinite(center.x) && Number.isFinite(center.y), "elementCenter returns coordinates");++ const locatorCenter = await elementCenter("loc=css:#click-button");+ assert(Number.isFinite(locatorCenter.x) && Number.isFinite(locatorCenter.y), "elementCenter resolves loc=css");++ const hrefCenter = await elementCenter("loc=href:/nav-target");+ assert(Number.isFinite(hrefCenter.x) && Number.isFinite(hrefCenter.y), "elementCenter resolves loc=href");++ const xpathCenter = await elementCenter("xpath=//*[@id='click-button']");+ assert(Number.isFinite(xpathCenter.x) && Number.isFinite(xpathCenter.y), "elementCenter resolves xpath");++ await assertRejects(+ () => elementCenter("loc=css:.duplicate-action"),+ "matched 2",+ "elementCenter reports duplicate css locators"+ );+ await assertRejects(+ () => elementCenter("loc=role:button[name='Duplicate action']"),+ "matched 2",+ "elementCenter reports duplicate role locators"+ );+ await assertRejects(+ () => elementCenter("loc=href:/missing-link"),+ "matched 0",+ "elementCenter reports missing href locators"+ );+ await assertRejects(+ () => elementCenter("@999999"),+ "Unknown ref",+ "elementCenter reports unknown refs"+ );+ await assertRejects(+ () => elementCenter("["),+ "Invalid selector",+ "elementCenter reports invalid selectors"+ );+ await assertRejects(+ () => elementCenter("#does-not-exist"),+ "Element not found",+ "elementCenter reports missing elements"+ );++ const screenshotPath = await captureScreenshot(undefined, { full: false });+ const screenshotStat = await stat(screenshotPath);+ assert(screenshotStat.size > 0, "captureScreenshot writes a non-empty png");++ const explicitPath = await captureScreenshot(explicitScreenshotPath, { full: false });+ assertEqual(explicitPath, explicitScreenshotPath, "captureScreenshot returns explicit path");+ const explicitStat = await stat(explicitPath);+ assert(explicitStat.size > 0, "captureScreenshot writes explicit path");++ const fullScreenshotPath = await captureScreenshot(undefined, { full: true });+ const fullScreenshotStat = await stat(fullScreenshotPath);+ assert(fullScreenshotStat.size > 0, "captureScreenshot supports full page");++ const rawScreenshotPath = await captureScreenshot(undefined, {+ raw: true,+ clip: { x: 0, y: 0, width: 120, height: 120, scale: 1 },+ });+ const rawScreenshotStat = await stat(rawScreenshotPath);+ assert(rawScreenshotStat.size > 0, "captureScreenshot supports raw clips");++ await cdp("Network.enable");+ await browserFetch("/api/text", { timeout: 5 });+ const events = await drainEvents();+ assert(Array.isArray(events), "drainEvents returns an array");+ const eventsAfterDrain = await drainEvents();+ assertEqual(eventsAfterDrain.length, 0, "drainEvents clears the event buffer");++ /* dynamic DOM — add element, verify snapshot picks it up */+ cliLog(JSON.stringify({ observationStep: "dynamic DOM" }));+ await click("#remove-element");+ await wait(0.1);+ const textBefore = await snapshotText({ scope: "full_page" });+ assert(!String(textBefore).includes("Dynamic!"), "snapshot text does not contain dynamic element before creation");++ await click("#add-element");+ await waitForElement("#dynamic-element", { timeout: 3, visible: true });+ await wait(0.2);+ const textAfter = await snapshotText({ scope: "full_page" });+ assertIncludes(String(textAfter), "Dynamic!", "snapshot text includes dynamically created element");++ /* iframe interaction — evaluate JS inside the iframe */+ cliLog(JSON.stringify({ observationStep: "iframe" }));+ const frameTarget = await iframeTarget("/frame.html");+ if (frameTarget) {+ const iframeMarkerText = await js(+ "return document.querySelector('#iframe-marker')?.textContent",+ frameTarget+ );+ assertEqual(iframeMarkerText, "iframe target", "js evaluates inside iframe using targetId");++ const iframeTitle = await js("return document.title", frameTarget);+ assertEqual(iframeTitle, "ego-lite iframe", "js reads iframe page title via targetId");+ } else {+ cliLog(JSON.stringify({ iframeWarning: "iframe target not available, skipping iframe tests" }));+ }+ `;+}diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/pointer.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/pointer.mjsnew file mode 100644index 0000000..954dcef--- /dev/null+++ b/package/ego-browser/scripts/real-browser-e2e/cases/pointer.mjs@@ -0,0 +1,245 @@+export function pointerCase() {+ return `+ await useOrCreateTaskSpace(taskName);+ await resetHome();+ cliLog(JSON.stringify({ pointerStep: "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",+ 1,+ "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']");+ await waitForJsValue("window.__fixtureState.clicks", 4, "click role locator fires a page click");+ await click("xpath=//*[@id='click-button']");+ await waitForJsValue("window.__fixtureState.clicks", 5, "click xpath fires a page click");+ const buttonCenter = await elementCenter("#click-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 });+ await waitForJsValue("window.__fixtureState.clicks", 7, "click object coordinates fires a page click");+ await click("#click-button", { clicks: 2 });+ await waitForJsValue("window.__fixtureState.clicks", 8, "click count option fires a page click");+ await waitForJsValue("window.__fixtureState.lastClickDetail", 2, "click count option sets DOM click detail");+ const doubleClicksBefore = await js("return window.__fixtureState.doubleClicks");+ await doubleClick("#click-button");+ await waitForJsValue("window.__fixtureState.clicks", 9, "doubleClick fires a page click");+ await waitForJsValue("window.__fixtureState.lastClickDetail", 2, "doubleClick sets DOM click detail");+ await waitForJsCondition(+ "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");++ await js("window.__fixtureState.hovered = false; return true;");+ await hover("#hover-zone");+ await waitForJsValue("window.__fixtureState.hovered", true, "hover css fires mouseover");+ await js("window.__fixtureState.hovered = false; return true;");+ 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");++ cliLog(JSON.stringify({ pointerStep: "nested scroll" }));+ await js(+ "const inner = document.querySelector('#inner-scroll');" ++ "inner.scrollTop = 0;" ++ "inner.scrollIntoView({ block: 'center', inline: 'nearest' });" ++ "return true;"+ );+ await wait(0.1);+ const innerCenter = await elementCenter("#inner-scroll");+ const innerHit = await js(+ "const el = document.elementFromPoint(" ++ JSON.stringify(innerCenter.x) ++ "," ++ JSON.stringify(innerCenter.y) ++ ");" ++ "return el?.closest?.('#inner-scroll')?.id || el?.id || '';"+ );+ assertEqual(innerHit, "inner-scroll", "nested scroll container is under the wheel target");+ const innerWheelDispatched = await allowWheelDispatch(+ "scroll nested container",+ () => scroll(innerCenter.x, innerCenter.y, { dy: 350 })+ );+ if (innerWheelDispatched) {+ await waitForJsCondition(+ "document.querySelector('#inner-scroll').scrollTop > 0",+ "scroll targets nested scroll containers"+ );+ }++ cliLog(JSON.stringify({ pointerStep: "page wheel" }));+ await resetHome();+ const wheelPoint = await js(+ "const rect = document.querySelector('#scroll-area').getBoundingClientRect();" ++ "return { x: Math.min(Math.max(rect.left + 20, 10), innerWidth - 10), y: Math.min(Math.max(rect.top + 20, 10), innerHeight - 10) };"+ );+ const beforeWheel = await pageInfo();+ const wheelDispatched = await allowWheelDispatch("scroll wheel", () =>+ scroll(wheelPoint.x, wheelPoint.y, { dy: 300 })+ );+ if (wheelDispatched) {+ await waitForJsCondition(+ "scrollY > " + JSON.stringify(beforeWheel.sy),+ "scroll wheel moves the page down"+ );+ const afterWheel = await pageInfo();+ assert(afterWheel.sy > beforeWheel.sy, "scroll wheel moves the page down");+ }++ await resetHome();+ const objectWheelPoint = await js(+ "const rect = document.querySelector('#scroll-area').getBoundingClientRect();" ++ "return { x: Math.min(Math.max(rect.left + 30, 10), innerWidth - 10), y: Math.min(Math.max(rect.top + 30, 10), innerHeight - 10) };"+ );+ const beforeObjectWheel = await pageInfo();+ const objectWheelDispatched = await allowWheelDispatch("scroll object options", () =>+ scroll({ x: objectWheelPoint.x, y: objectWheelPoint.y, dy: 120 })+ );+ if (objectWheelDispatched) {+ await waitForJsCondition(+ "scrollY > " + JSON.stringify(beforeObjectWheel.sy),+ "scroll object options move the page down"+ );+ const afterObjectWheel = await pageInfo();+ 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 });+ assert(by.y > beforeBy.sy, "scrollBy moves the page down and returns scroll position");+ const byNumber = await scrollBy(120);+ assert(byNumber.y > by.y, "scrollBy accepts numeric amount");+ const byTop = await scrollBy({ top: -60 });+ assert(byTop.y < byNumber.y && byTop.y >= 0, "scrollBy accepts top option");++ const bottom = await scrollToBottomUntil(+ "document.querySelector('#bottom-marker').getBoundingClientRect().top < innerHeight",+ { step: 700, maxSteps: 8, wait: 0.05 }+ );+ assert(bottom.done || bottom.reason === "bottom", "scrollToBottomUntil terminates");++ await resetHome();+ const maxStep = await scrollToBottomUntil("false", {+ step: 100,+ maxSteps: 0,+ wait: 0,+ });+ assertEqual(maxStep.reason, "maxSteps", "scrollToBottomUntil reports maxSteps");++ const nullCondition = await scrollToBottomUntil(null, {+ step: 100,+ maxSteps: 0,+ wait: 0,+ });+ assertEqual(nullCondition.reason, "maxSteps", "scrollToBottomUntil accepts null condition");++ const functionCondition = await scrollToBottomUntil(+ (state) => state.y > 100,+ { step: 200, maxSteps: 5, wait: 0 }+ );+ assertEqual(functionCondition.reason, "condition", "scrollToBottomUntil accepts function condition");++ const immediateCondition = await scrollToBottomUntil("true", {+ step: 100,+ maxSteps: 3,+ wait: 0,+ });+ assertEqual(immediateCondition.reason, "condition", "scrollToBottomUntil accepts immediate string condition");++ await assertRejects(+ () => dragMouse(["#drag-source"]),+ "at least two points",+ "dragMouse validates minimum path length"+ );+ await assertRejects(+ () => click({ x: "bad", y: 1 }),+ "invalid mouse target",+ "click validates coordinate targets"+ );+ await assertRejects(+ () => click("#click-button", { button: "sideways" }),+ "unsupported mouse button",+ "click validates mouse buttons"+ );+ await assertRejects(+ () => dragMouse(["#drag-source", "#drag-target"], { button: "sideways" }),+ "unsupported mouse button",+ "dragMouse validates mouse buttons"+ );+ await assertRejects(+ () => scrollBy({ dy: "bad" }),+ "invalid mouse offset",+ "scrollBy validates numeric offsets"+ );+ await assertRejects(+ () => scrollToBottomUntil(42, { maxSteps: 0 }),+ "function or string",+ "scrollToBottomUntil validates condition type"+ );++ /* 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");+ assert(rightClickAfter > rightClickBefore, "click with button:right dispatches mouse events on the target");+ const rightMouseDown = await js(+ "return window.__fixtureState.pointerEvents.some(function(e) { return e.type === 'mousedown' && e.target === 'context-menu-zone'; })"+ );+ 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");+ await click("#click-button");+ await click("#click-button");+ await click("#click-button");+ await click("#click-button");+ await waitForJsValue(+ "window.__fixtureState.clicks",+ clicksBefore + 5,+ "five rapid clicks increment counter correctly (probe cleanup between actions)",+ "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");+ await click("#checkbox");+ await waitForJsValue("window.__fixtureState.checkboxChecked", false, "second click unchecks the checkbox");+ `;+}diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/runtime.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/runtime.mjsnew file mode 100644index 0000000..51956e9--- /dev/null+++ b/package/ego-browser/scripts/real-browser-e2e/cases/runtime.mjs@@ -0,0 +1,138 @@+export function runtimeCase() {+ return `+ await switchTaskSpace(taskName);+ await resetHome();++ const waitedAt = Date.now();+ await wait(0.1);+ assert(Date.now() - waitedAt >= 50, "wait pauses for a measurable duration");+ assert(+ await waitForElement("#delayed", { timeout: 3, visible: true }),+ "waitForElement observes delayed visible element"+ );+ assertEqual(+ await waitForElement("#does-not-exist", { timeout: 0.2 }),+ false,+ "waitForElement returns false for missing elements"+ );+ assertEqual(+ await waitForElement("#never-visible", { timeout: 0.4, visible: true }),+ false,+ "waitForElement visible:true rejects hidden elements"+ );++ const serverText = await serverFetch(baseUrl + "/api/text", { timeout: 5 });+ assertEqual(serverText, "server text fixture", "serverFetch reads fixture API");++ const serverEcho = await serverFetch(baseUrl + "/api/echo", {+ method: "POST",+ body: "payload",+ timeout: 5,+ });+ assertEqual(serverEcho, "echo:POST:payload", "serverFetch sends method and body");++ const serverHeader = await serverFetch(baseUrl + "/api/header", {+ headers: { "x-e2e": "server-header" },+ timeout: 5,+ });+ assertEqual(serverHeader, "server-header", "serverFetch sends custom headers");++ const serverRedirect = await serverFetch(baseUrl + "/api/redirect", { timeout: 5 });+ assertEqual(serverRedirect, "server text fixture", "serverFetch follows redirects");++ await assertRejectsAny(+ () => serverFetch(baseUrl + "/api/slow?ms=1200&case=server-timeout-" + Date.now(), { timeout: 0.05 }),+ "serverFetch honors timeout"+ );++ await assertRejects(+ () => serverFetch(baseUrl + "/api/error", { timeout: 5 }),+ "HTTP 500",+ "serverFetch reports HTTP errors"+ );++ const browserText = await browserFetch("/api/text", { timeout: 5 });+ assertEqual(browserText, "server text fixture", "browserFetch reads fixture API");++ const browserEcho = await browserFetch("/api/echo", {+ method: "POST",+ body: "browser-payload",+ timeout: 5,+ });+ assertEqual(browserEcho, "echo:POST:browser-payload", "browserFetch sends method and body");++ const browserHeader = await browserFetch("/api/header", {+ headers: { "x-e2e": "browser-header" },+ timeout: 5,+ });+ assertEqual(browserHeader, "browser-header", "browserFetch sends custom headers");++ const browserRedirect = await browserFetch("/api/redirect", { timeout: 5 });+ assertEqual(browserRedirect, "server text fixture", "browserFetch follows redirects");++ const browserAbsolute = await browserFetch(baseUrl + "/api/text", { timeout: 5 });+ assertEqual(browserAbsolute, "server text fixture", "browserFetch accepts absolute URLs");++ await assertRejectsAny(+ () => browserFetch("/api/slow?ms=1200&case=browser-timeout-" + Date.now(), { timeout: 0.05 }),+ "browserFetch honors timeout"+ );++ await assertRejects(+ () => browserFetch("/api/error", { timeout: 5 }),+ "HTTP 500",+ "browserFetch reports HTTP errors"+ );++ await cdp("Network.enable");+ await js(+ "window.__slowText = '';" ++ "fetch('/api/slow?ms=300&case=network-idle-' + Date.now())" ++ ".then((response) => response.text())" ++ ".then((text) => { window.__slowText = text; });" ++ "return true;"+ );+ assert(+ await waitForNetworkIdle({ timeout: 5, idleMs: 100 }),+ "waitForNetworkIdle waits for an in-flight slow fetch"+ );+ assertEqual(await js("return window.__slowText"), "slow fixture", "waitForNetworkIdle leaves the slow fetch complete");++ const evalResult = await cdp("Runtime.evaluate", {+ expression: "document.title",+ returnByValue: true,+ });+ assertEqual(evalResult.result.value, "ego-lite helper e2e", "cdp evaluates in page");++ await assertRejects(+ () => cdp("EgoBrowser.MissingMethodForE2E"),+ "EgoBrowser.MissingMethodForE2E",+ "cdp reports unsupported methods"+ );++ const title = await js("return document.title");+ assertEqual(title, "ego-lite helper e2e", "js returns evaluated value");++ const wrappedReturn = await js("const title = document.title; return title;");+ assertEqual(wrappedReturn, "ego-lite helper e2e", "js wraps top-level return statements");++ const arithmetic = await js("1 + 2");+ assertEqual(arithmetic, 3, "js evaluates expression values");++ const titleFromFunction = await js(() => document.title);+ assertEqual(titleFromFunction, "ego-lite helper e2e", "js supports function input");++ await assertRejects(+ () => js("throw new Error('js boom')"),+ "js boom",+ "js reports page exceptions"+ );++ const helpText = help("click", "fillInput");+ assertIncludes(helpText, "click", "help returns helper documentation");+ assertIncludes(helpText, "fillInput", "help returns multiple helper docs");++ const unknownHelp = help("missingHelperForE2E");+ assertIncludes(unknownHelp, "Unknown helper", "help reports unknown helpers");+ `;+}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.mjsnew file mode 100644index 0000000..bbfdf96--- /dev/null+++ b/package/ego-browser/scripts/real-browser-e2e/cases/task-space.mjs@@ -0,0 +1,89 @@+export function taskSpaceCase() {+ return `+ const task = await useOrCreateTaskSpace(taskName);+ assertEqual(task.name, taskName, "useOrCreateTaskSpace selects named task");++ const reusedTask = await useOrCreateTaskSpace(taskName);+ assertEqual(reusedTask.id, task.id, "useOrCreateTaskSpace reuses an existing named task");++ const spaces = await listTaskSpaces();+ assert(spaces.some((space) => space.name === taskName), "listTaskSpaces includes e2e task");+ const listed = spaces.find((space) => space.name === taskName);+ assertEqual(typeof listed.id, "number", "listTaskSpaces returns numeric ids");+ assertEqual(listed.taskId !== undefined, true, "listTaskSpaces returns taskId");+ assertEqual(typeof listed.ownership, "string", "listTaskSpaces returns ownership");++ const switched = await switchTaskSpace(task.id);+ assertEqual(switched.id, task.id, "switchTaskSpace selects by numeric id");+ const switchedByName = await switchTaskSpace(taskName);+ assertEqual(switchedByName.id, task.id, "switchTaskSpace selects by name");+ const switchedByNumericString = await switchTaskSpace(String(task.id));+ assertEqual(switchedByNumericString.id, task.id, "switchTaskSpace selects by numeric string id");++ await waitForAgentControl(taskName, { interval: 0.1, timeout: 3 });+ await takeOverTaskSpace(taskName);+ await waitForAgentControl(taskName, { interval: 0.1, timeout: 3 });++ const scratch = await newTaskSpace(taskName + " scratch");+ assertEqual(scratch.name, taskName + " scratch", "newTaskSpace creates a scratch space");+ const scratchByName = await switchTaskSpace(scratch.name);+ assertEqual(scratchByName.id, scratch.id, "newTaskSpace output can be selected by name");+ const closed = await completeTaskSpace(scratch.id, { keep: false });+ assertEqual(closed.done, true, "completeTaskSpace closes scratch task");++ await assertRejects(+ () => completeTaskSpace(scratch.id, { keep: false }),+ "task space not found",+ "completeTaskSpace reports already-closed task space"+ );++ await switchTaskSpace(taskName);+ await assertRejects(+ () => switchTaskSpace(taskName + " missing"),+ "task space not found",+ "switchTaskSpace reports missing task space"+ );+ await assertRejects(+ () => useOrCreateTaskSpace(99999999),+ "task space not found",+ "useOrCreateTaskSpace rejects missing numeric id"+ );+ await assertRejects(+ () => completeTaskSpace(taskName, {}),+ "requires { keep: boolean }",+ "completeTaskSpace validates keep option"+ );+ await assertRejects(+ () => completeTaskSpace("", { keep: false }),+ "requires a task space name or id",+ "completeTaskSpace validates empty task id"+ );+ await assertRejects(+ () => waitForAgentControl("", { timeout: 0.1 }),+ "requires a task space name or id",+ "waitForAgentControl validates task space id"+ );+ await assertRejects(+ () => takeOverTaskSpace(taskName + " missing"),+ "task space not found",+ "takeOverTaskSpace reports missing task space"+ );+ await assertRejects(+ () => claimTaskSpace(taskName + " missing"),+ "task space not found",+ "claimTaskSpace reports missing task space"+ );+ await assertRejects(+ () => handOffTaskSpace(taskName + " missing"),+ "task space not found",+ "handOffTaskSpace reports missing task space"+ );++ await handOffTaskSpace();+ await takeOverTaskSpace();+ await waitForAgentControl(taskName, { interval: 0.1, timeout: 5 });+ await handOffTaskSpace(taskName);+ await takeOverTaskSpace(taskName);+ await waitForAgentControl(taskName, { interval: 0.1, timeout: 5 });+ `;+}diff --git a/package/ego-browser/scripts/real-browser-e2e/ego-source.mjs b/package/ego-browser/scripts/real-browser-e2e/ego-source.mjsnew file mode 100644index 0000000..4c875b4--- /dev/null+++ b/package/ego-browser/scripts/real-browser-e2e/ego-source.mjs@@ -0,0 +1,186 @@+export function egoSource(body, context) {+ const {+ taskName,+ baseUrl,+ artifactDir,+ tempDir,+ uploadPath,+ uploadPathTwo,+ explicitScreenshotPath,+ environmentScreenshotPath,+ metadataPath,+ keepTaskSpace,+ } = context;+ return `+ const { stat, writeFile } = await import("node:fs/promises");+ const { join } = await import("node:path");+ const taskName = ${JSON.stringify(taskName)};+ const baseUrl = ${JSON.stringify(baseUrl)};+ const artifactDir = ${JSON.stringify(artifactDir)};+ const tempDir = ${JSON.stringify(tempDir)};+ const uploadPath = ${JSON.stringify(uploadPath)};+ const uploadPathTwo = ${JSON.stringify(uploadPathTwo)};+ const explicitScreenshotPath = ${JSON.stringify(explicitScreenshotPath)};+ const environmentScreenshotPath = ${JSON.stringify(environmentScreenshotPath)};+ 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 }));+ await writeFile(join(tempDir, "case-result.json"), JSON.stringify({ ok: true, assertions: __assertionCount }));+ } catch (error) {+ cliLog(JSON.stringify({ ok: false, assertions: __assertionCount, error: error.message }));+ await writeFile(join(tempDir, "case-result.json"), JSON.stringify({ ok: false, assertions: __assertionCount, error: error.message })).catch(() => {});+ error.message = ${JSON.stringify("real browser e2e")} + ": " + error.message;+ throw error;+ }+ `;+}diff --git a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs b/package/ego-browser/scripts/real-browser-e2e/fixture.mjsnew file mode 100644index 0000000..353911d--- /dev/null+++ b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs@@ -0,0 +1,390 @@+import { createServer } from "node:http";++export async function closeFixtureServer(fixtureServer) {+ await new Promise((resolve) => {+ const timer = setTimeout(resolve, 1000);+ timer.unref?.();+ fixtureServer.close(() => {+ clearTimeout(timer);+ resolve();+ });+ fixtureServer.closeIdleConnections?.();+ fixtureServer.closeAllConnections?.();+ });+}++export async function startFixtureServer(taskName) {+ const fixtureServer = createServer((req, res) => {+ const url = new URL(req.url || "/", "http://127.0.0.1");+ if (url.pathname === "/healthz") {+ res.writeHead(200, {+ "content-type": "application/json",+ "access-control-allow-origin": "*",+ });+ res.end(+ JSON.stringify({+ ok: true,+ taskName,+ fixture: "ego-browser-real-e2e",+ now: Date.now(),+ }),+ );+ return;+ }+ if (url.pathname === "/api/json") {+ res.writeHead(200, {+ "content-type": "application/json",+ "access-control-allow-origin": "*",+ });+ res.end(JSON.stringify({ ok: true, value: "json fixture" }));+ return;+ }+ if (url.pathname === "/api/text") {+ res.writeHead(200, {+ "content-type": "text/plain",+ "access-control-allow-origin": "*",+ });+ res.end("server text fixture");+ return;+ }+ if (url.pathname === "/api/header") {+ res.writeHead(200, {+ "content-type": "text/plain",+ "access-control-allow-origin": "*",+ "access-control-allow-headers": "*",+ });+ res.end(req.headers["x-e2e"] || "");+ return;+ }+ if (url.pathname === "/api/redirect") {+ res.writeHead(302, {+ location: "/api/text",+ "access-control-allow-origin": "*",+ });+ res.end();+ return;+ }+ if (url.pathname === "/api/echo") {+ let body = "";+ req.on("data", (chunk) => {+ body += chunk;+ });+ req.on("end", () => {+ res.writeHead(200, {+ "content-type": "text/plain",+ "access-control-allow-origin": "*",+ });+ res.end(`echo:${req.method}:${body}`);+ });+ return;+ }+ if (url.pathname === "/api/error") {+ res.writeHead(500, {+ "content-type": "text/plain",+ "access-control-allow-origin": "*",+ });+ res.end("server error fixture");+ return;+ }+ if (url.pathname === "/api/slow") {+ const delayMs = Number(url.searchParams.get("ms") || 250);+ setTimeout(() => {+ res.writeHead(200, {+ "content-type": "text/plain",+ "access-control-allow-origin": "*",+ });+ res.end("slow fixture");+ }, delayMs);+ return;+ }+ if (req.method === "OPTIONS") {+ res.writeHead(204, {+ "access-control-allow-origin": "*",+ "access-control-allow-methods": "GET,POST,OPTIONS",+ "access-control-allow-headers": "*",+ });+ res.end();+ return;+ }+ if (url.pathname === "/frame.html") {+ res.writeHead(200, { "content-type": "text/html" });+ res.end(pageHtml("frame"));+ return;+ }+ if (url.pathname === "/nav-target") {+ res.writeHead(200, { "content-type": "text/html" });+ res.end(pageHtml("nav-target"));+ return;+ }+ if (url.pathname === "/secondary") {+ res.writeHead(200, { "content-type": "text/html" });+ res.end(pageHtml("secondary"));+ return;+ }+ if (url.pathname === "/favicon.ico") {+ res.writeHead(204);+ res.end();+ return;+ }+ res.writeHead(200, { "content-type": "text/html" });+ res.end(pageHtml("home"));+ });++ await new Promise((resolve, reject) => {+ fixtureServer.once("error", reject);+ fixtureServer.listen(0, "127.0.0.1", () => resolve());+ });+ const address = fixtureServer.address();+ return {+ server: fixtureServer,+ baseUrl: `http://127.0.0.1:${address.port}`,+ };+}++function pageHtml(kind) {+ const title =+ kind === "nav-target"+ ? "ego-lite nav target"+ : kind === "secondary"+ ? "ego-lite secondary"+ : kind === "frame"+ ? "ego-lite iframe"+ : "ego-lite helper e2e";+ const heading =+ kind === "nav-target"+ ? "Navigation target"+ : kind === "secondary"+ ? "Secondary tab"+ : kind === "frame"+ ? "Iframe fixture"+ : "Helper e2e fixture";++ return `<!doctype html>+<html>+ <head>+ <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;+ }+ #drag-target { background: #eef7ee; }+ #rich-editor {+ border: 1px solid #777;+ min-height: 48px;+ padding: 8px;+ width: 320px;+ }+ #context-menu-zone {+ align-items: center;+ background: #f7eef7;+ border: 1px dashed #777;+ display: inline-flex;+ height: 48px;+ justify-content: center;+ margin: 8px;+ width: 160px;+ }+ #dynamic-container { min-height: 24px; margin: 8px 0; }+ .tab-stop {+ border: 1px solid #999;+ display: inline-block;+ margin: 4px;+ padding: 4px 12px;+ }+ .tab-stop:focus { outline: 2px solid #44f; }+ #inner-scroll {+ border: 1px solid #777;+ height: 120px;+ margin-top: 12px;+ overflow: auto;+ width: 320px;+ }+ #inner-scroll-content { height: 620px; padding-top: 520px; }+ #scroll-area { height: 1800px; padding-top: 16px; }+ #bottom-marker { margin-top: 1450px; }+ #delayed { 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>+ <div id="delayed">Delayed element</div>+ <div id="never-visible" style="display:none">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>+ ${kind === "frame" ? '<div id="iframe-marker" data-iframe="true" style="border:2px solid #44f;padding:8px;margin-top:8px;">iframe target</div>' : ""}+ </main>+ <script>+ window.__fixtureState = {+ clicks: 0,+ doubleClicks: 0,+ dragged: false,+ hovered: false,+ keyEvents: [],+ keys: [],+ lastClickDetail: 0,+ lastDoubleClickDetail: 0,+ pointerEvents: [],+ rightClicked: false,+ dynamicElementExists: false,+ tabOrder: [],+ checkboxChecked: false,+ dropdownValue: "alpha",+ };+ 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,+ );+ }+ clickButton.addEventListener("click", (event) => {+ window.__fixtureState.clicks += 1;+ window.__fixtureState.lastClickDetail = event.detail;+ count.textContent = String(window.__fixtureState.clicks);+ });+ clickButton.addEventListener("dblclick", (event) => {+ window.__fixtureState.doubleClicks += 1;+ window.__fixtureState.lastDoubleClickDetail = event.detail;+ });+ for (const type of ["mousemove", "mouseover"]) {+ document.querySelector("#hover-zone").addEventListener(type, () => {+ window.__fixtureState.hovered = true;+ });+ }+ let dragging = false;+ document.querySelector("#drag-source").addEventListener("mousedown", () => {+ dragging = true;+ });+ document.querySelector("#drag-target").addEventListener("mouseup", () => {+ if (dragging) window.__fixtureState.dragged = true;+ dragging = false;+ });+ 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,+ });+ 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,+ });+ });+ }+ document.querySelector("#file-input").addEventListener("change", (event) => {+ document.querySelector("#file-name").textContent =+ Array.from(event.target.files).map((file) => file.name).join(",");+ });++ /* context menu zone — captures right-click */+ const contextZone = document.querySelector("#context-menu-zone");+ contextZone.addEventListener("contextmenu", (event) => {+ event.preventDefault();+ window.__fixtureState.rightClicked = true;+ });++ /* dynamic DOM — add/remove elements */+ document.querySelector("#add-element").addEventListener("click", () => {+ const container = document.querySelector("#dynamic-container");+ if (!document.querySelector("#dynamic-element")) {+ const el = document.createElement("div");+ el.id = "dynamic-element";+ el.setAttribute("role", "status");+ el.textContent = "Dynamic!";+ el.style.cssText = "background:#efe;border:1px solid #7a7;padding:4px 8px;";+ 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;+ }+ });++ /* checkbox */+ 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 */+ for (const stop of document.querySelectorAll(".tab-stop")) {+ stop.addEventListener("focus", () => {+ window.__fixtureState.tabOrder.push(stop.dataset.tab);+ });+ }++ /* delayed element */+ setTimeout(() => {+ const delayed = document.querySelector("#delayed");+ delayed.style.display = "block";+ }, 350);+ </script>+ </body>+</html>`;+}diff --git a/package/ego-browser/scripts/real-browser-e2e/run-command.mjs b/package/ego-browser/scripts/real-browser-e2e/run-command.mjsnew file mode 100644index 0000000..0c70d47--- /dev/null+++ b/package/ego-browser/scripts/real-browser-e2e/run-command.mjs@@ -0,0 +1,91 @@+import { spawn } from "node:child_process";++export function runCommand(command, args, options = {}) {+ return new Promise((resolve, reject) => {+ let stdout = "";+ let stderr = "";+ let settled = false;+ const child = spawn(command, args, {+ cwd: options.cwd ?? process.cwd(),+ env: process.env,+ stdio: options.input ? ["pipe", "pipe", "pipe"] : "inherit",+ });+ const timer =+ options.timeoutMs &&+ setTimeout(() => {+ settled = true;+ child.kill("SIGINT");+ reject(+ new Error(+ `${command} ${args.join(" ")} timed out after ${options.timeoutMs}ms`,+ ),+ );+ }, options.timeoutMs);+ child.on("error", (error) => {+ if (settled) return;+ settled = true;+ if (timer) clearTimeout(timer);+ if (error.code === "ENOENT" && command === "ego-browser") {+ reject(+ new Error(+ "ego-browser command not found; install/open ego lite before running real browser e2e",+ ),+ );+ return;+ }+ reject(error);+ });+ child.stdout?.on("data", (chunk) => {+ stdout += chunk;+ process.stdout.write(chunk);+ });+ child.stderr?.on("data", (chunk) => {+ stderr += chunk;+ process.stderr.write(chunk);+ });+ child.on("close", (code) => {+ if (settled) return;+ settled = true;+ if (timer) clearTimeout(timer);+ if (+ /unknown option.*sdk-path|unrecognized option.*sdk-path/i.test(+ stdout + stderr,+ )+ ) {+ const error = new Error(+ `ego-browser nodejs --sdk-path is not supported; cannot verify SDK path ${options.egoBrowserSdkPath || "configured SDK path"}`,+ );+ error.stdout = stdout;+ error.stderr = stderr;+ reject(error);+ return;+ }+ if (code === 0) {+ if (+ /ego's nodejs process exited with code\s+[1-9]\d*/.test(+ stdout + stderr,+ )+ ) {+ const error = new Error(+ `ego-browser nodejs reported an inner failure while exiting 0`,+ );+ error.stdout = stdout;+ error.stderr = stderr;+ reject(error);+ return;+ }+ resolve({ stdout, stderr });+ } else {+ const error = new Error(+ `${command} ${args.join(" ")} exited with code ${code}`,+ );+ error.stdout = stdout;+ error.stderr = stderr;+ reject(error);+ }+ });+ if (options.input) {+ child.stdin.end(options.input);+ }+ });+}diff --git a/package/ego-browser/scripts/real-browser-e2e/runner.mjs b/package/ego-browser/scripts/real-browser-e2e/runner.mjsnew file mode 100644index 0000000..a01eae7--- /dev/null+++ b/package/ego-browser/scripts/real-browser-e2e/runner.mjs@@ -0,0 +1,307 @@+import {+ mkdir,+ mkdtemp,+ readFile,+ rm,+ stat,+ writeFile,+} from "node:fs/promises";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++import { e2eCases } from "./cases/index.mjs";+import { egoSource } from "./ego-source.mjs";+import { closeFixtureServer, startFixtureServer } from "./fixture.mjs";+import { runCommand } from "./run-command.mjs";++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];++export async function runRealBrowserE2e() {+ const keepTaskSpace =+ process.env.EGO_BROWSER_REAL_E2E_KEEP === "1" ||+ process.env.EGO_BROWSER_REAL_E2E_KEEP === "true";+ const onlyCases = new Set(+ (process.env.EGO_BROWSER_REAL_E2E_ONLY || "")+ .split(",")+ .map((name) => name.trim())+ .filter(Boolean),+ );++ let server;+ let tempDir;+ let passed = false;+ const context = {};+ const caseResults = [];++ function recordResult(name, status, durationMs, assertionCount, message) {+ caseResults.push({ name, status, durationMs, assertionCount, message });+ }++ async function runEgoCase(name, body, timeoutMs = 45000) {+ console.log(`-- ${name}`);+ const source = egoSource(body, {+ ...context,+ keepTaskSpace: keepTaskSpace && passed,+ });+ const startedAt = Date.now();+ try {+ const { stdout } = await runCommand("ego-browser", egoBrowserArgs, {+ cwd: packageDir,+ egoBrowserSdkPath,+ input: source,+ timeoutMs,+ });+ const durationMs = Date.now() - startedAt;+ const assertions = await readCaseAssertionCount(tempDir, stdout);+ recordResult(name, "pass", durationMs, assertions);+ 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);+ recordResult(name, "fail", durationMs, assertions, message);+ console.error(+ `[FAIL] ${name} (${formatDuration(durationMs)}): ${message}`,+ );+ }+ }++ async function maybeRunEgoCase(name, body, timeoutMs = 45000) {+ if (onlyCases.size > 0 && !onlyCases.has(name)) {+ console.log(`-- ${name} (skipped)`);+ recordResult(name, "skip", 0, 0);+ return;+ }+ await runEgoCase(name, body, timeoutMs);+ }++ async function cleanupTaskSpace() {+ const beforeFails = caseResults.filter((r) => r.status === "fail").length;+ await runEgoCase(+ "cleanup",+ `+ try {+ const result = await completeTaskSpace(taskName, { keep: keepTaskSpace });+ cliLog(JSON.stringify({ cleanup: result }));+ } catch (error) {+ if (!String(error?.message || error).includes("task space not found")) {+ throw error;+ }+ }+ `,+ 20000,+ );+ // Remove cleanup result and any failures it produced+ const cleanupResults = caseResults.filter((r) => r.name === "cleanup");+ for (const r of cleanupResults) {+ caseResults.splice(caseResults.indexOf(r), 1);+ }+ }++ const totalStartedAt = Date.now();++ try {+ console.log("== build ==");+ await runCommand("npm", ["run", "build"], { cwd: packageDir });+ await stat(egoBrowserSdkPath);++ tempDir = await mkdtemp(join(tmpdir(), "ego-browser-real-e2e-"));+ const artifactDir = join(tempDir, "artifacts");+ const uploadPath = join(tempDir, "fixture-upload.txt");+ const uploadPathTwo = join(tempDir, "fixture-upload-two.txt");+ const explicitScreenshotPath = join(artifactDir, "explicit-shot.png");+ const environmentScreenshotPath = join(artifactDir, "environment-shot.png");+ const metadataPath = join(tempDir, "metadata.json");+ const taskName = `ego-lite real browser e2e ${Date.now()}-${Math.random()+ .toString(16)+ .slice(2)}`;++ Object.assign(context, {+ artifactDir,+ explicitScreenshotPath,+ environmentScreenshotPath,+ metadataPath,+ taskName,+ tempDir,+ uploadPath,+ uploadPathTwo,+ });++ await mkdir(artifactDir, { recursive: true });+ await writeFile(uploadPath, "ego-browser upload fixture\n", "utf8");+ await writeFile(uploadPathTwo, "second upload fixture\n", "utf8");++ const fixture = await startFixtureServer(taskName);+ server = fixture.server;+ Object.assign(context, { baseUrl: fixture.baseUrl });+ await initializeE2eEnvironment(context, tempDir);++ console.log("== E2E (real browser helpers) ==");+ console.log(`fixture: ${context.baseUrl}`);+ console.log(`task: ${taskName}`);+ console.log(`sdk: ${egoBrowserSdkPath}`);++ for (const testCase of e2eCases) {+ await maybeRunEgoCase(testCase.name, testCase.body());+ }++ passed = caseResults.every((r) => r.status !== "fail");+ printSummary(caseResults, Date.now() - totalStartedAt);++ if (!passed) {+ process.exitCode = 1;+ }+ } catch (error) {+ console.error(error?.stack || error?.message || String(error));+ process.exitCode = error?.code === "ENOENT" ? 127 : 1;+ } finally {+ if (context.taskName) {+ await cleanupTaskSpace().catch((error) => {+ console.error(`[cleanup] ${error?.message || error}`);+ });+ }+ if (server) {+ await closeFixtureServer(server);+ }+ if (tempDir) {+ await rm(tempDir, { recursive: true, force: true });+ }+ }+}++async function initializeE2eEnvironment(context, tempDir) {+ const {+ artifactDir,+ baseUrl,+ metadataPath,+ taskName,+ uploadPath,+ uploadPathTwo,+ } = context;+ const healthUrl = `${baseUrl}/healthz`;+ const response = await fetch(healthUrl, {+ signal: AbortSignal.timeout(5000),+ });+ if (!response.ok) {+ throw new Error(`fixture health check failed: HTTP ${response.status}`);+ }+ const health = await response.json();+ if (health.taskName !== taskName || health.ok !== true) {+ throw new Error(+ `fixture health payload mismatch: ${JSON.stringify(health)}`,+ );+ }+ await stat(uploadPath);+ await stat(uploadPathTwo);+ await stat(artifactDir);+ await writeFile(+ metadataPath,+ JSON.stringify(+ {+ baseUrl,+ taskName,+ tempDir,+ artifactDir,+ startedAt: new Date().toISOString(),+ },+ null,+ 2,+ ),+ "utf8",+ );+}++async function readCaseAssertionCount(tempDir, stdout) {+ const resultPath = join(tempDir, "case-result.json");+ 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 extractAssertionCount(stdout);+}++function extractAssertionCount(stdout) {+ if (!stdout) return 0;+ // Find the last JSON line with "assertions" from cliLog output+ const lines = stdout.split("\n");+ for (let i = lines.length - 1; i >= 0; i--) {+ const line = lines[i].trim();+ if (line.startsWith("{") && line.includes("assertions")) {+ try {+ const parsed = JSON.parse(line);+ if (typeof parsed.assertions === "number") return parsed.assertions;+ } catch {+ // not valid JSON, keep looking+ }+ }+ }+ return 0;+}++function formatDuration(ms) {+ if (ms < 1000) return `${ms}ms`;+ return `${(ms / 1000).toFixed(1)}s`;+}++function printSummary(results, totalMs) {+ const total = results.length;+ 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 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)}%)` : ""}`,+ );+ if (failed > 0) console.log(` Failed: ${failed}/${total}`);+ if (skipped > 0) console.log(` Skipped: ${skipped}/${total}`);+ console.log(` Total time: ${formatDuration(totalMs)}`);+ console.log(` Assertions: ${totalAssertions}`);+ console.log("");++ // Per-case detail table+ const nameWidth = Math.max(...results.map((r) => r.name.length), 4);+ console.log(" Cases:");+ for (const result of results) {+ const statusLabel =+ result.status === "pass"+ ? "PASS"+ : result.status === "fail"+ ? "FAIL"+ : "SKIP";+ const timing =+ result.status === "skip"+ ? " "+ : formatDuration(result.durationMs).padStart(7);+ const assertions =+ result.status === "skip"+ ? " -"+ : ` ${result.assertionCount} assertions`;+ console.log(+ ` ${result.name.padEnd(nameWidth)} ${timing} ${assertions} ${statusLabel}`,+ );+ }++ // Failure details+ const failedResults = results.filter((r) => r.status === "fail");+ if (failedResults.length > 0) {+ console.log("");+ console.log(" Failures:");+ for (const result of failedResults) {+ console.log(` - ${result.name}: ${result.message}`);+ }+ }++ console.log("");+}diff --git a/package/ego-browser/scripts/run-e2e.sh b/package/ego-browser/scripts/run-e2e.shdeleted file mode 100755index 9a96dc9..0000000--- a/package/ego-browser/scripts/run-e2e.sh+++ /dev/null@@ -1,10 +0,0 @@-#!/usr/bin/env bash-set -euo pipefail--cd "$(dirname "$0")/.."--echo "== build =="-npm run build--echo "== E2E (taskspace helpers) =="-EGO_BROWSER_E2E=1 node --test src/taskspace-e2e.test.mjsdiff --git a/package/ego-browser/scripts/run-real-browser-e2e.mjs b/package/ego-browser/scripts/run-real-browser-e2e.mjsnew file mode 100644index 0000000..fb52249--- /dev/null+++ b/package/ego-browser/scripts/run-real-browser-e2e.mjs@@ -0,0 +1,4 @@+#!/usr/bin/env node+import { runRealBrowserE2e } from "./real-browser-e2e/runner.mjs";++await runRealBrowserE2e();diff --git a/package/ego-browser/src/driver/keyboard.test.mjs b/package/ego-browser/src/driver/keyboard.test.mjsindex de0fc40..c3be78a 100644--- a/package/ego-browser/src/driver/keyboard.test.mjs+++ b/package/ego-browser/src/driver/keyboard.test.mjs@@ -10,7 +10,7 @@ test("pressKey maps Command+A to the selectAll editing command", async () => {cdpOverride(method, params, sessionId) {calls.push({ method, params, sessionId });return {};- }+ },});try {await pressKey("a", 4);@@ -31,8 +31,8 @@ test("pressKey maps Command+A to the selectAll editing command", async () => {nativeVirtualKeyCode: 65,text: "a",unmodifiedText: "a",- commands: ["selectAll"]- }+ commands: ["selectAll"],+ },});assert.deepEqual(calls[1].params, {type: "keyUp",@@ -40,7 +40,7 @@ test("pressKey maps Command+A to the selectAll editing command", async () => {code: "KeyA",modifiers: 4,windowsVirtualKeyCode: 65,- nativeVirtualKeyCode: 65+ nativeVirtualKeyCode: 65,});});@@ -50,7 +50,7 @@ test("pressKey maps Control+A to the selectAll editing command", async () => {cdpOverride(method, params, sessionId) {calls.push({ method, params, sessionId });return {};- }+ },});try {await pressKey("a", 2);@@ -67,7 +67,7 @@ test("pressKey does not map modified Command+A variants to selectAll", async ()cdpOverride(method, params, sessionId) {calls.push({ method, params, sessionId });return {};- }+ },});try {await pressKey("a", 12);@@ -84,7 +84,7 @@ test("pressKey leaves ordinary printable keys unchanged", async () => {cdpOverride(method, params, sessionId) {calls.push({ method, params, sessionId });return {};- }+ },});try {await pressKey("x");@@ -101,7 +101,7 @@ test("pressKey leaves ordinary printable keys unchanged", async () => {windowsVirtualKeyCode: 88,nativeVirtualKeyCode: 88,text: "x",- unmodifiedText: "x"+ unmodifiedText: "x",});assert.deepEqual(calls[1].params, {type: "keyUp",@@ -109,6 +109,122 @@ test("pressKey leaves ordinary printable keys unchanged", async () => {code: "KeyX",modifiers: 0,windowsVirtualKeyCode: 88,- nativeVirtualKeyCode: 88+ nativeVirtualKeyCode: 88,+ });+});++test("pressKey maps Backspace and Delete to editing commands", async () => {+ const calls = [];+ const restore = setOverrides({+ cdpOverride(method, params, sessionId) {+ calls.push({ method, params, sessionId });+ return {};+ },});+ try {+ await pressKey("Backspace");+ await pressKey("Delete");+ } finally {+ restore();+ }++ assert.deepEqual(calls[0].params.commands, ["deleteBackward"]);+ assert.deepEqual(calls[2].params.commands, ["deleteForward"]);+});++test("pressKey triggers probe fallback when CDP dispatch is not trusted", async () => {+ // Enable canProbeInputFallback() by providing ego runtime+ const originalEgo = globalThis.ego;+ globalThis.ego = { sendCDPMessage: () => {} };+ let evaluateCallCount = 0;+ const evaluateExpressions = [];+ const restore = setOverrides({+ cdpOverride(method, params, sessionId) {+ if (method === "Runtime.evaluate") {+ evaluateCallCount++;+ evaluateExpressions.push(params.expression);+ // First call: installKeyProbe — return truthy to indicate probe installed+ if (evaluateCallCount === 1) {+ return { result: { value: true } };+ }+ // Second call: finishKeyProbe — simulate CDP dispatch was NOT seen+ // (the CDP keyDown did not produce a trusted event)+ return { result: { value: { seen: false, fallback: true } } };+ }+ // Input.dispatchKeyEvent calls proceed normally+ return {};+ },+ });+ try {+ await pressKey("a");+ } finally {+ restore();+ if (originalEgo === undefined) delete globalThis.ego;+ else globalThis.ego = originalEgo;+ }++ // Verify probe install and finish were called+ assert.equal(+ evaluateCallCount,+ 2,+ "Runtime.evaluate called for install and finish",+ );+ // Install expression should reference __egoBrowserInputProbes+ assert.match(+ evaluateExpressions[0],+ /__egoBrowserInputProbes/,+ "install expression sets up probe",+ );+ // Finish expression should contain the fallback dispatch logic+ assert.match(+ evaluateExpressions[1],+ /dispatchEvent/,+ "finish expression contains fallback dispatch",+ );+ assert.match(+ evaluateExpressions[1],+ /KeyboardEvent/,+ "finish expression dispatches KeyboardEvent in fallback",+ );+});++test("pressKey skips probe fallback when CDP dispatch is trusted", async () => {+ const originalEgo = globalThis.ego;+ globalThis.ego = { sendCDPMessage: () => {} };+ let evaluateCallCount = 0;+ const evaluateExpressions = [];+ const restore = setOverrides({+ cdpOverride(method, params, sessionId) {+ if (method === "Runtime.evaluate") {+ evaluateCallCount++;+ evaluateExpressions.push(params.expression);+ if (evaluateCallCount === 1) {+ return { result: { value: true } };+ }+ // Simulate CDP dispatch WAS seen (trusted event arrived)+ return { result: { value: { seen: true, fallback: false } } };+ }+ return {};+ },+ });+ try {+ await pressKey("x");+ } finally {+ restore();+ if (originalEgo === undefined) delete globalThis.ego;+ else globalThis.ego = originalEgo;+ }++ assert.equal(+ evaluateCallCount,+ 2,+ "Runtime.evaluate called for install and finish",+ );+ // When seen=true, finish should return early without dispatching fallback events+ // The expression still contains the fallback code but it returns early via the seen check+ assert.match(+ evaluateExpressions[1],+ /probe\.seen/,+ "finish expression checks probe.seen flag",+ );});diff --git a/package/ego-browser/src/driver/keyboard.ts b/package/ego-browser/src/driver/keyboard.tsindex 2b7a6d7..1e5682c 100644--- a/package/ego-browser/src/driver/keyboard.ts+++ b/package/ego-browser/src/driver/keyboard.ts@@ -1,4 +1,5 @@import { cdp } from "../cdp-eval.js";+import { browserCdp } from "../browser-runtime.js";import { withHandle, resolveAndCall } from "./element-ops.js";import { waitForElement } from "./waits.js";@@ -21,12 +22,14 @@ const KEYS = {Home: { vk: 36, key: "Home", code: "Home", text: "" },End: { vk: 35, key: "End", code: "End", text: "" },PageUp: { vk: 33, key: "PageUp", code: "PageUp", text: "" },- PageDown: { vk: 34, key: "PageDown", code: "PageDown", text: "" }+ PageDown: { vk: 34, key: "PageDown", code: "PageDown", text: "" },};const PRINTABLE_CODE_RE = /^[A-Za-z0-9]$/;const CTRL_MODIFIER = 2;const META_MODIFIER = 4;+const INPUT_EVENT_DELAY_MS = 25;+const INPUT_DISPATCH_TIMEOUT_MS = 1000;function keyDefinition(key) {const special = KEYS[key];@@ -37,14 +40,25 @@ function keyDefinition(key) {return { vk: 0, key, code: key, text: "" };}const vk = key.toUpperCase().codePointAt(0);- const code = PRINTABLE_CODE_RE.test(key) ? `${/[0-9]/.test(key) ? "Digit" : "Key"}${key.toUpperCase()}` : key;+ const code = PRINTABLE_CODE_RE.test(key)+ ? `${/[0-9]/.test(key) ? "Digit" : "Key"}${key.toUpperCase()}`+ : key;return { vk, key, code, text: key };}function editingCommandsForKey(key, modifiers) {- if ((modifiers === CTRL_MODIFIER || modifiers === META_MODIFIER) && key.toLowerCase() === "a") {+ if (+ (modifiers === CTRL_MODIFIER || modifiers === META_MODIFIER) &&+ key.toLowerCase() === "a"+ ) {return ["selectAll"];}+ if (modifiers === 0 && key === "Backspace") {+ return ["deleteBackward"];+ }+ if (modifiers === 0 && key === "Delete") {+ return ["deleteForward"];+ }return undefined;}@@ -56,15 +70,36 @@ function editingCommandsForKey(key, modifiers) {*/export async function pressKey(key, modifiers = 0) {const { vk, code, text } = keyDefinition(key);- const base = { key, code, modifiers, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk };+ const base = {+ key,+ code,+ modifiers,+ windowsVirtualKeyCode: vk,+ nativeVirtualKeyCode: vk,+ };const commands = editingCommandsForKey(key, modifiers);- await cdp("Input.dispatchKeyEvent", {- type: "keyDown",- ...base,- ...(text ? { text, unmodifiedText: text } : {}),- ...(commands ? { commands } : {})+ const probeId = await installKeyProbe(key);+ let dispatchError: unknown = null;+ try {+ await dispatchKeyEvent({+ type: "keyDown",+ ...base,+ ...(text ? { text, unmodifiedText: text } : {}),+ ...(commands ? { commands } : {}),+ });+ await inputEventDelay();+ await dispatchKeyEvent({ type: "keyUp", ...base });+ } catch (error) {+ if (!isKeyDispatchTimeout(error)) throw error;+ dispatchError = error;+ }+ const completed = await finishKeyProbe(probeId, {+ key,+ code,+ text,+ commands,});- await cdp("Input.dispatchKeyEvent", { type: "keyUp", ...base });+ if (dispatchError && !completed) throw dispatchError;}/**@@ -83,34 +118,57 @@ export async function typeText(text) {* @param {{clearFirst?: boolean, timeout?: number}} [options]* @returns {Promise<void>}*/-export async function fillInput(selector, text, options: FillInputOptions = {}) {+export async function fillInput(+ selector,+ text,+ options: FillInputOptions = {},+) {const clearFirst = options.clearFirst ?? true;const timeout = options.timeout ?? 0;- if (timeout > 0 && !await waitForElement(selector, { timeout })) {- throw new Error(`fillInput: element not found: ${JSON.stringify(selector)}`);+ if (timeout > 0 && !(await waitForElement(selector, { timeout }))) {+ throw new Error(+ `fillInput: element not found: ${JSON.stringify(selector)}`,+ );}await withHandle(selector, async ({ objectId, sessionId }) => {- await cdp("Runtime.callFunctionOn", {- functionDeclaration: "function(){this.focus(); if(typeof this.select==='function') this.select();}",- objectId,- returnByValue: true,- awaitPromise: false- }, sessionId);- if (clearFirst) {- await cdp("Runtime.callFunctionOn", {- functionDeclaration: "function(){this.value=''; this.dispatchEvent(new Event('input',{bubbles:true}));}",+ const focusSource = clearFirst+ ? "function(){this.focus(); if(typeof this.select==='function') this.select();}"+ : "function(){this.focus();}";+ await cdp(+ "Runtime.callFunctionOn",+ {+ functionDeclaration: focusSource,objectId,returnByValue: true,- awaitPromise: false- }, sessionId);+ awaitPromise: false,+ },+ sessionId,+ );+ if (clearFirst) {+ await cdp(+ "Runtime.callFunctionOn",+ {+ functionDeclaration:+ "function(){this.value=''; this.dispatchEvent(new Event('input',{bubbles:true}));}",+ objectId,+ returnByValue: true,+ awaitPromise: false,+ },+ sessionId,+ );}await cdp("Input.insertText", { text }, sessionId);- await cdp("Runtime.callFunctionOn", {- functionDeclaration: "function(){this.dispatchEvent(new Event('input',{bubbles:true})); this.dispatchEvent(new Event('change',{bubbles:true}));}",- objectId,- returnByValue: true,- awaitPromise: false- }, sessionId);+ await cdp(+ "Runtime.callFunctionOn",+ {+ functionDeclaration:+ "function(){this.dispatchEvent(new Event('input',{bubbles:true})); this.dispatchEvent(new Event('change',{bubbles:true}));}",+ objectId,+ returnByValue: true,+ awaitPromise: false,+ },+ sessionId,+ );});}@@ -127,6 +185,155 @@ export async function dispatchKey(selector, key = "Enter", event = "keypress") {await resolveAndCall(selector,"function(keyCode, key, code, event){this.focus(); this.dispatchEvent(new KeyboardEvent(event,{key,code,keyCode,which:keyCode,bubbles:true}));}",- [vk, key, code, event]+ [vk, key, code, event],);}++function inputEventDelay() {+ return new Promise((resolve) => setTimeout(resolve, INPUT_EVENT_DELAY_MS));+}++async function dispatchKeyEvent(params: Record<string, unknown>) {+ await browserCdp(+ "Input.dispatchKeyEvent",+ params,+ undefined,+ INPUT_DISPATCH_TIMEOUT_MS,+ );+}++async function installKeyProbe(key: string) {+ if (!canProbeInputFallback()) return null;+ const id = `key_${Date.now()}_${Math.random().toString(16).slice(2)}`;+ try {+ const result = await cdp("Runtime.evaluate", {+ expression: `(() => {+ window.__egoBrowserInputProbes ||= {};+ const probe = { seen: false };+ probe.handler = (event) => {+ if (event.isTrusted && event.key === ${JSON.stringify(key)}) probe.seen = true;+ };+ document.addEventListener("keydown", probe.handler, true);+ window.__egoBrowserInputProbes[${JSON.stringify(id)}] = probe;+ return true;+ })()`,+ returnByValue: true,+ awaitPromise: false,+ });+ return result.result?.value ? id : null;+ } catch {+ return null;+ }+}++async function finishKeyProbe(+ id: string | null,+ definition: { key: string; code: string; text: string; commands?: string[] },+) {+ if (!id) return false;+ await inputEventDelay();+ try {+ const result = await cdp("Runtime.evaluate", {+ expression: `(() => {+ const probes = window.__egoBrowserInputProbes || {};+ const probe = probes[${JSON.stringify(id)}];+ if (!probe) return { seen: false, fallback: false };+ document.removeEventListener("keydown", probe.handler, true);+ delete probes[${JSON.stringify(id)}];+ if (probe.seen) return { seen: true, fallback: false };++ const target = document.activeElement || document.body;+ const key = ${JSON.stringify(definition.key)};+ const code = ${JSON.stringify(definition.code)};+ const text = ${JSON.stringify(definition.text)};+ const commands = ${JSON.stringify(definition.commands || [])};+ const keyboardInit = {+ key,+ code,+ bubbles: true,+ cancelable: true,+ keyCode: ${JSON.stringify(keyDefinition(definition.key).vk)},+ which: ${JSON.stringify(keyDefinition(definition.key).vk)},+ };+ target.dispatchEvent(new KeyboardEvent("keydown", keyboardInit));++ const isEditable =+ target instanceof HTMLInputElement ||+ target instanceof HTMLTextAreaElement;+ if (isEditable) {+ if (commands.includes("selectAll") && typeof target.select === "function") {+ target.select();+ } else if (commands.includes("deleteBackward")) {+ const start = target.selectionStart ?? target.value.length;+ const end = target.selectionEnd ?? start;+ const from = start === end ? Math.max(0, start - 1) : start;+ const before = target.value;+ target.dispatchEvent(new InputEvent("beforeinput", {+ bubbles: true,+ cancelable: true,+ inputType: "deleteContentBackward",+ }));+ target.value = before.slice(0, from) + before.slice(end);+ target.setSelectionRange(from, from);+ target.dispatchEvent(new InputEvent("input", {+ bubbles: true,+ inputType: "deleteContentBackward",+ }));+ } else if (commands.includes("deleteForward")) {+ const start = target.selectionStart ?? target.value.length;+ const end = target.selectionEnd ?? start;+ const to = start === end ? Math.min(target.value.length, end + 1) : end;+ const before = target.value;+ target.dispatchEvent(new InputEvent("beforeinput", {+ bubbles: true,+ cancelable: true,+ inputType: "deleteContentForward",+ }));+ target.value = before.slice(0, start) + before.slice(to);+ target.setSelectionRange(start, start);+ target.dispatchEvent(new InputEvent("input", {+ bubbles: true,+ inputType: "deleteContentForward",+ }));+ } else if (text) {+ const start = target.selectionStart ?? target.value.length;+ const end = target.selectionEnd ?? start;+ const before = target.value;+ target.dispatchEvent(new InputEvent("beforeinput", {+ bubbles: true,+ cancelable: true,+ data: text,+ inputType: "insertText",+ }));+ target.value = before.slice(0, start) + text + before.slice(end);+ const next = start + text.length;+ target.setSelectionRange(next, next);+ target.dispatchEvent(new InputEvent("input", {+ bubbles: true,+ data: text,+ inputType: "insertText",+ }));+ }+ }++ target.dispatchEvent(new KeyboardEvent("keyup", keyboardInit));+ return { seen: false, fallback: true };+ })()`,+ returnByValue: true,+ awaitPromise: false,+ });+ const value = result.result?.value;+ return Boolean(value?.seen || value?.fallback);+ } catch {+ return false;+ }+}++function canProbeInputFallback() {+ return Boolean((globalThis as any).ego?.sendCDPMessage);+}++function isKeyDispatchTimeout(error: unknown) {+ const message = error instanceof Error ? error.message : String(error ?? "");+ return /CDP request timed out: Input\.dispatchKeyEvent/.test(message);+}diff --git a/package/ego-browser/src/driver/pointer.test.mjs b/package/ego-browser/src/driver/pointer.test.mjsindex 1a4839d..f842762 100644--- a/package/ego-browser/src/driver/pointer.test.mjs+++ b/package/ego-browser/src/driver/pointer.test.mjs@@ -55,10 +55,13 @@ test("click resolves selector offsets without the public elementEval helper", astype: call.params.type,x: call.params.x,y: call.params.y,+ button: call.params.button,+ buttons: call.params.buttons,})),[- { type: "mousePressed", x: 112, y: 208 },- { type: "mouseReleased", x: 112, y: 208 },+ { type: "mouseMoved", x: 112, y: 208, button: "none", buttons: 0 },+ { type: "mousePressed", x: 112, y: 208, button: "left", buttons: 1 },+ { type: "mouseReleased", x: 112, y: 208, button: "left", buttons: 0 },],);});@@ -156,3 +159,101 @@ test("scroll propagates user-control errors from wheel dispatch", async () => {restore();}});++test("click triggers probe fallback when CDP click is not trusted", async () => {+ const originalEgo = globalThis.ego;+ globalThis.ego = { sendCDPMessage: () => {} };+ let probeEvaluateCount = 0;+ const evaluateExpressions = [];+ const restore = setOverrides({+ cdpOverride(method, params, sessionId) {+ if (method === "Runtime.evaluate") {+ // Probe calls contain __egoBrowserInputProbes; element resolution does not+ if (params.expression?.includes("__egoBrowserInputProbes")) {+ probeEvaluateCount++;+ evaluateExpressions.push(params.expression);+ if (probeEvaluateCount === 1) {+ // installClickProbe — elementFromPoint returns truthy+ return { result: { value: true } };+ }+ // finishClickProbe — simulate CDP click was NOT seen+ return { result: { value: { seen: false, fallback: true } } };+ }+ // Element resolution (buildSelectorCenterJs) — return center point+ return { result: { value: { x: 100, y: 200 } } };+ }+ // Input.dispatchMouseEvent calls proceed normally+ return {};+ },+ });+ try {+ await click("#target");+ } finally {+ restore();+ if (originalEgo === undefined) delete globalThis.ego;+ else globalThis.ego = originalEgo;+ }++ // 2 probe Runtime.evaluate calls: install + finish (element resolution excluded)+ assert.equal(+ probeEvaluateCount,+ 2,+ "Runtime.evaluate called for install and finish probes",+ );+ assert.match(+ evaluateExpressions[0],+ /__egoBrowserInputProbes/,+ "install expression sets up click probe",+ );+ assert.match(+ evaluateExpressions[1],+ /dispatchEvent/,+ "finish expression contains fallback mouse events",+ );+ assert.match(+ evaluateExpressions[1],+ /MouseEvent/,+ "finish expression dispatches MouseEvent in fallback",+ );+});++test("click absorbs CDP timeout when probe fallback succeeds", async () => {+ const originalEgo = globalThis.ego;+ globalThis.ego = { sendCDPMessage: () => {} };+ let probeEvaluateCount = 0;+ const restore = setOverrides({+ cdpOverride(method, params, sessionId) {+ if (method === "Runtime.evaluate") {+ // Probe calls contain __egoBrowserInputProbes; element resolution does not+ if (params.expression?.includes("__egoBrowserInputProbes")) {+ probeEvaluateCount++;+ if (probeEvaluateCount === 1) {+ return { result: { value: true } };+ }+ // Fallback succeeded+ return { result: { value: { seen: false, fallback: true } } };+ }+ // Element resolution (buildSelectorCenterJs) — return center point+ return { result: { value: { x: 100, y: 200 } } };+ }+ if (method === "Input.dispatchMouseEvent") {+ // Simulate CDP timeout — the browser couldn't dispatch the event+ throw new Error("CDP request timed out: Input.dispatchMouseEvent");+ }+ return {};+ },+ });+ try {+ // Should NOT throw — timeout is absorbed because fallback succeeded+ await click("#target");+ } finally {+ restore();+ if (originalEgo === undefined) delete globalThis.ego;+ else globalThis.ego = originalEgo;+ }++ assert.ok(+ probeEvaluateCount >= 2,+ "probe install and finish were called despite CDP timeout",+ );+});diff --git a/package/ego-browser/src/driver/pointer.ts b/package/ego-browser/src/driver/pointer.tsindex a47a8b6..8b7c36b 100644--- a/package/ego-browser/src/driver/pointer.ts+++ b/package/ego-browser/src/driver/pointer.ts@@ -62,6 +62,9 @@ type ScrollUntilCondition =| null;type MouseEventOptions = Record<string, unknown>;+const INPUT_EVENT_DELAY_MS = 25;+const INPUT_DISPATCH_TIMEOUT_MS = 1000;+/*** Mouse target accepted by mouse helpers.*@@ -84,18 +87,34 @@ type MouseEventOptions = Record<string, unknown>;export async function click(target: MouseTarget, options: ClickOptions = {}) {const point = await resolveMouseTarget(target);const button = options.button || "left";+ const buttons = pressedButtons(button);const clickCount = options.clickCount ?? options.clicks ?? 1;maybeHighlight(point, options.label);- await dispatchMouse(point, "mousePressed", {- button,- buttons: pressedButtons(button),- clickCount,- });- await dispatchMouse(point, "mouseReleased", {- button,- buttons: 0,- clickCount,- });+ const probeId = await installClickProbe(point);+ let dispatchError: unknown = null;+ try {+ await dispatchMouse(point, "mouseMoved", {+ button: "none",+ buttons: 0,+ });+ await inputEventDelay();+ await dispatchMouse(point, "mousePressed", {+ button,+ buttons,+ clickCount,+ });+ await inputEventDelay();+ await dispatchMouse(point, "mouseReleased", {+ button,+ buttons: 0,+ clickCount,+ });+ } catch (error) {+ if (!isInputDispatchTimeout(error)) throw error;+ dispatchError = error;+ }+ const completed = await finishClickProbe(point, probeId, clickCount);+ if (dispatchError && !completed) throw dispatchError;}/**@@ -120,16 +139,16 @@ export async function doubleClick(export async function hover(target: MouseTarget, options: HoverOptions = {}) {const point = await resolveMouseTarget(target);maybeHighlight(point, options.label);- await cdp(- "Input.dispatchMouseEvent",- {- type: "mouseMoved",- x: point.x,- y: point.y,- buttons: 0,- },- point.sessionId,- );+ const probeId = await installHoverProbe(point);+ let dispatchError: unknown = null;+ try {+ await dispatchMouse(point, "mouseMoved", { buttons: 0 });+ } catch (error) {+ if (!isInputDispatchTimeout(error)) throw error;+ dispatchError = error;+ }+ const completed = await finishHoverProbe(point, probeId);+ if (dispatchError && !completed) throw dispatchError;}/**@@ -154,47 +173,285 @@ export async function dragMouse(const first = resolved[0];const last = resolved.at(-1);maybeHighlight(first, options.label);- await cdp(- "Input.dispatchMouseEvent",- {- type: "mousePressed",- x: first.x,- y: first.y,+ const probeId = await installMouseUpProbe(last);+ let dispatchError: unknown = null;+ try {+ await dispatchMouse(first, "mousePressed", {button,buttons,clickCount: 1,- },- first.sessionId,- );- for (let i = 1; i < resolved.length; i += 1) {- const point = resolved[i];- await cdp(- "Input.dispatchMouseEvent",+ });+ await inputEventDelay();+ for (let i = 1; i < resolved.length; i += 1) {+ const point = resolved[i];+ await dispatchMouse(+ { ...point, sessionId: point.sessionId ?? first.sessionId },+ "mouseMoved",+ {+ button,+ buttons,+ },+ );+ await inputEventDelay(options.delayMs > 0 ? options.delayMs : undefined);+ }+ await dispatchMouse(+ { ...last, sessionId: last.sessionId ?? first.sessionId },+ "mouseReleased",{- type: "mouseMoved",- x: point.x,- y: point.y,button,- buttons,+ buttons: 0,+ clickCount: 1,},- point.sessionId ?? first.sessionId,);- if (options.delayMs > 0 && i < resolved.length - 1) {- await new Promise((resolve) => setTimeout(resolve, options.delayMs));- }+ } catch (error) {+ if (!isInputDispatchTimeout(error)) throw error;+ dispatchError = error;}- await cdp(- "Input.dispatchMouseEvent",- {- type: "mouseReleased",- x: last.x,- y: last.y,- button,- buttons: 0,- clickCount: 1,- },- last.sessionId ?? first.sessionId,- );+ const completed = await finishDragProbe(resolved, probeId, button);+ if (dispatchError && !completed) throw dispatchError;+}++function inputEventDelay(ms = INPUT_EVENT_DELAY_MS) {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++async function installClickProbe(point: Point) {+ if (!canProbeInputFallback()) return null;+ const id = `click_${Date.now()}_${Math.random().toString(16).slice(2)}`;+ try {+ const result = await cdp(+ "Runtime.evaluate",+ {+ expression: `(() => {+ const target = document.elementFromPoint(${JSON.stringify(point.x)}, ${JSON.stringify(point.y)});+ window.__egoBrowserInputProbes ||= {};+ const probe = { seen: false, target };+ probe.handler = (event) => {+ if (event.isTrusted && target && (event.target === target || target.contains(event.target))) {+ probe.seen = true;+ }+ };+ document.addEventListener("click", probe.handler, true);+ window.__egoBrowserInputProbes[${JSON.stringify(id)}] = probe;+ return Boolean(target);+ })()`,+ returnByValue: true,+ awaitPromise: false,+ },+ point.sessionId,+ );+ return result.result?.value ? id : null;+ } catch {+ return null;+ }+}++async function finishClickProbe(+ point: Point,+ id: string | null,+ clickCount: number,+) {+ if (!id) return false;+ await inputEventDelay(50);+ try {+ const result = await cdp(+ "Runtime.evaluate",+ {+ expression: `(() => {+ const probes = window.__egoBrowserInputProbes || {};+ const probe = probes[${JSON.stringify(id)}];+ if (!probe) return { seen: false, fallback: false };+ document.removeEventListener("click", probe.handler, true);+ delete probes[${JSON.stringify(id)}];+ if (probe.seen || !probe.target) return { seen: probe.seen, fallback: false };+ const target = probe.target;+ const init = {+ bubbles: true,+ cancelable: true,+ view: window,+ clientX: ${JSON.stringify(point.x)},+ clientY: ${JSON.stringify(point.y)},+ button: 0,+ };+ target.dispatchEvent(new MouseEvent("mousemove", { ...init, buttons: 0, detail: 0 }));+ target.dispatchEvent(new MouseEvent("mousedown", { ...init, buttons: 1, detail: ${JSON.stringify(clickCount)} }));+ target.dispatchEvent(new MouseEvent("mouseup", { ...init, buttons: 0, detail: ${JSON.stringify(clickCount)} }));+ target.dispatchEvent(new MouseEvent("click", { ...init, buttons: 0, detail: ${JSON.stringify(clickCount)} }));+ if (${JSON.stringify(clickCount)} > 1) {+ target.dispatchEvent(new MouseEvent("dblclick", { ...init, buttons: 0, detail: 2 }));+ }+ return { seen: false, fallback: true };+ })()`,+ returnByValue: true,+ awaitPromise: false,+ },+ point.sessionId,+ );+ const value = result.result?.value;+ return Boolean(value?.seen || value?.fallback);+ } catch {+ return false;+ }+}++async function installMouseUpProbe(point: Point) {+ if (!canProbeInputFallback()) return null;+ const id = `drag_${Date.now()}_${Math.random().toString(16).slice(2)}`;+ try {+ const result = await cdp(+ "Runtime.evaluate",+ {+ expression: `(() => {+ const target = document.elementFromPoint(${JSON.stringify(point.x)}, ${JSON.stringify(point.y)});+ window.__egoBrowserInputProbes ||= {};+ const probe = { seen: false, target };+ probe.handler = (event) => {+ if (event.isTrusted && target && (event.target === target || target.contains(event.target))) {+ probe.seen = true;+ }+ };+ document.addEventListener("mouseup", probe.handler, true);+ window.__egoBrowserInputProbes[${JSON.stringify(id)}] = probe;+ return Boolean(target);+ })()`,+ returnByValue: true,+ awaitPromise: false,+ },+ point.sessionId,+ );+ return result.result?.value ? id : null;+ } catch {+ return null;+ }+}++async function installHoverProbe(point: Point) {+ if (!canProbeInputFallback()) return null;+ const id = `hover_${Date.now()}_${Math.random().toString(16).slice(2)}`;+ try {+ const result = await cdp(+ "Runtime.evaluate",+ {+ expression: `(() => {+ const target = document.elementFromPoint(${JSON.stringify(point.x)}, ${JSON.stringify(point.y)});+ window.__egoBrowserInputProbes ||= {};+ const probe = { seen: false, target };+ probe.handler = (event) => {+ if (event.isTrusted && target && (event.target === target || target.contains(event.target))) {+ probe.seen = true;+ }+ };+ document.addEventListener("mousemove", probe.handler, true);+ document.addEventListener("mouseover", probe.handler, true);+ window.__egoBrowserInputProbes[${JSON.stringify(id)}] = probe;+ return Boolean(target);+ })()`,+ returnByValue: true,+ awaitPromise: false,+ },+ point.sessionId,+ );+ return result.result?.value ? id : null;+ } catch {+ return null;+ }+}++async function finishHoverProbe(point: Point, id: string | null) {+ if (!id) return false;+ await inputEventDelay(50);+ try {+ const result = await cdp(+ "Runtime.evaluate",+ {+ expression: `(() => {+ const probes = window.__egoBrowserInputProbes || {};+ const probe = probes[${JSON.stringify(id)}];+ if (!probe) return { seen: false, fallback: false };+ document.removeEventListener("mousemove", probe.handler, true);+ document.removeEventListener("mouseover", probe.handler, true);+ delete probes[${JSON.stringify(id)}];+ if (probe.seen || !probe.target) return { seen: probe.seen, fallback: false };+ const target = probe.target;+ const init = {+ bubbles: true,+ cancelable: true,+ view: window,+ clientX: ${JSON.stringify(point.x)},+ clientY: ${JSON.stringify(point.y)},+ button: 0,+ buttons: 0,+ };+ target.dispatchEvent(new MouseEvent("mousemove", init));+ target.dispatchEvent(new MouseEvent("mouseover", init));+ return { seen: false, fallback: true };+ })()`,+ returnByValue: true,+ awaitPromise: false,+ },+ point.sessionId,+ );+ const value = result.result?.value;+ return Boolean(value?.seen || value?.fallback);+ } catch {+ return false;+ }+}++async function finishDragProbe(+ points: Point[],+ id: string | null,+ button: MouseButton,+) {+ if (!id) return false;+ await inputEventDelay(50);+ const first = points[0];+ const last = points.at(-1);+ try {+ const result = await cdp(+ "Runtime.evaluate",+ {+ expression: `(() => {+ const probes = window.__egoBrowserInputProbes || {};+ const probe = probes[${JSON.stringify(id)}];+ if (!probe) return { seen: false, fallback: false };+ document.removeEventListener("mouseup", probe.handler, true);+ delete probes[${JSON.stringify(id)}];+ if (probe.seen) return { seen: true, fallback: false };+ const mouseButton = ${JSON.stringify(button === "left" ? 0 : button === "middle" ? 1 : 2)};+ const eventFor = (type, point, buttons) => {+ const target = document.elementFromPoint(point.x, point.y) || document.body;+ target.dispatchEvent(new MouseEvent(type, {+ bubbles: true,+ cancelable: true,+ view: window,+ clientX: point.x,+ clientY: point.y,+ button: mouseButton,+ buttons,+ detail: type === "mousemove" ? 0 : 1,+ }));+ };+ const points = ${JSON.stringify(points.map(({ x, y }) => ({ x, y })))};+ eventFor("mousedown", points[0], 1);+ for (const point of points.slice(1)) eventFor("mousemove", point, 1);+ eventFor("mouseup", points.at(-1), 0);+ return { seen: false, fallback: true };+ })()`,+ returnByValue: true,+ awaitPromise: false,+ },+ last.sessionId ?? first.sessionId,+ );+ const value = result.result?.value;+ return Boolean(value?.seen || value?.fallback);+ } catch {+ return false;+ }+}++function canProbeInputFallback() {+ return Boolean((globalThis as any).ego?.sendCDPMessage);}/**@@ -342,7 +599,7 @@ async function dispatchMouse(type: string,options: MouseEventOptions = {},) {- await cdp(+ await browserCdp("Input.dispatchMouseEvent",{type,@@ -351,9 +608,15 @@ async function dispatchMouse(...options,},point.sessionId,+ INPUT_DISPATCH_TIMEOUT_MS,);}+function isInputDispatchTimeout(error: unknown) {+ const message = error instanceof Error ? error.message : String(error ?? "");+ return /CDP request timed out: Input\.dispatchMouseEvent/.test(message);+}+async function resolveMouseTarget(target: MouseTarget): Promise<Point> {if (typeof target === "string") {return elementCenter(target);