Skip to content

The fastest browser for AI agents to run browser automation, built for sharing your logged-in browser state with your AI agents, like Codex or Claude Code, without disturbing you. Zero cost, zero config.

chore(ego-browser): untrack test/ files and ignore them repo-wide

0x0997426835e1b
diff --git a/.gitignore b/.gitignore
index de68e75..320e762 100644
--- a/.gitignore
+++ b/.gitignore
@@ -76,4 +76,5 @@ evals/reports/*
issues.md
browser/
task/
-test-e2e/
\ No newline at end of file
+test-e2e/
+test/
\ No newline at end of file
diff --git a/package/ego-browser/test/browser-e2e.test.js b/package/ego-browser/test/browser-e2e.test.js
deleted file mode 100644
index 712a4a4..0000000
--- a/package/ego-browser/test/browser-e2e.test.js
+++ /dev/null
@@ -1,156 +0,0 @@
-import assert from "node:assert/strict";
-import { spawnSync } from "node:child_process";
-import test from "node:test";
-
-const e2eSkip = { skip: process.env.EGO_BROWSER_E2E !== "1" };
-const egoBin = process.env.EGO_BROWSER_BIN || "ego-browser";
-
-function runScript(script, timeout = 30_000) {
- const result = spawnSync(egoBin, ["nodejs"], {
- input: script,
- encoding: "utf8",
- timeout,
- shell: false,
- stdio: ["pipe", "pipe", "pipe"]
- });
- if (result.error || result.status !== 0) {
- throw new Error(
- `ego-browser nodejs failed: status=${result.status} signal=${result.signal}\n` +
- `stdout: ${result.stdout}\nstderr: ${result.stderr}\nerror: ${result.error?.message || ""}`
- );
- }
- return result;
-}
-
-function lastJsonLine(text) {
- const lines = text.split("\n").map((l) => l.trim()).filter(Boolean);
- for (let i = lines.length - 1; i >= 0; i--) {
- if (lines[i].startsWith("{") || lines[i].startsWith("[")) {
- return JSON.parse(lines[i]);
- }
- }
- throw new Error(`no JSON line found in output:\n${text}`);
-}
-
-test("real browser runtime can navigate, inspect page info, and snapshot", e2eSkip, () => {
- const script = `
- await useOrCreateTaskSpace('e2e-navigate');
- await openOrReuseTab('https://example.com', { wait: true, timeout: 20 });
- const info = await pageInfo();
- const text = await snapshotText();
- cliLog(JSON.stringify({ title: info.title, hasExample: text.includes('Example') }));
- await completeTaskSpace('e2e-navigate', { keep: false });
- `;
- const result = runScript(script, 30_000);
- const payload = lastJsonLine(result.stderr);
- assert.equal(payload.title, "Example Domain");
- assert.equal(payload.hasExample, true);
-});
-
-test("ego.snapshot rejects under user-control after handOffTaskSpace", e2eSkip, () => {
- const script = `
- const name = 'e2e-probe-handoff';
- await useOrCreateTaskSpace(name);
- await openOrReuseTab('https://example.com', { wait: true, timeout: 20 });
- let beforeOk = false, afterRejected = false, afterError = '';
- try { await globalThis.ego.snapshot({ maxResultLength: 1 }); beforeOk = true; } catch (e) { afterError = 'before:' + e.message; }
- await handOffTaskSpace(name);
- try { await globalThis.ego.snapshot({ maxResultLength: 1 }); }
- catch (e) { afterRejected = true; afterError = e.message; }
- await takeOverTaskSpace(name);
- await completeTaskSpace(name, { keep: false });
- cliLog(JSON.stringify({ beforeOk, afterRejected, afterError }));
- `;
- const result = runScript(script);
- const payload = lastJsonLine(result.stderr);
- assert.equal(payload.beforeOk, true, "snapshot should succeed when agent has control");
- assert.equal(payload.afterRejected, true, `snapshot should reject under user-control; got: ${payload.afterError}`);
-});
-
-test("waitForAgentControl blocks until takeOverTaskSpace restores control", e2eSkip, () => {
- const script = `
- const name = 'e2e-wait-control';
- await useOrCreateTaskSpace(name);
- await openOrReuseTab('https://example.com', { wait: true, timeout: 20 });
- await handOffTaskSpace(name);
- setTimeout(() => { takeOverTaskSpace(name).catch(() => {}); }, 3000);
- const t0 = Date.now();
- await waitForAgentControl(name, { interval: 1, timeout: 20 });
- const elapsed = (Date.now() - t0) / 1000;
- await completeTaskSpace(name, { keep: false });
- cliLog(JSON.stringify({ elapsed, blocked: elapsed >= 2 }));
- `;
- const result = runScript(script);
- const payload = lastJsonLine(result.stderr);
- assert.equal(payload.blocked, true, `waitForAgentControl should block ~3s; elapsed=${payload.elapsed}s`);
-});
-
-test("elementEval: arrow (el)=>el.X, (el,arg)=>el[arg], and legacy function(){this} all work in a real page", e2eSkip, () => {
- const script = `
- const name = 'e2e-element-eval';
- await useOrCreateTaskSpace(name);
- await openOrReuseTab('https://example.com', { wait: true, timeout: 20 });
-
- const arrowReadText = await elementEval('h1', (el) => el.textContent);
- const arrowWithArg = await elementEval('h1', (el, prop) => el[prop], 'tagName');
- const legacyThisForm = await elementEval('h1', function () { return this.tagName; });
-
- await completeTaskSpace(name, { keep: false });
- cliLog(JSON.stringify({ arrowReadText, arrowWithArg, legacyThisForm }));
- `;
- const result = runScript(script);
- const payload = lastJsonLine(result.stderr);
- assert.equal(payload.arrowReadText, "Example Domain", "arrow (el)=>el.textContent must read the element");
- assert.equal(payload.arrowWithArg, "H1", "arrow (el, prop)=>el[prop] must forward args after el");
- assert.equal(payload.legacyThisForm, "H1", "legacy function(){return this.tagName} must remain bound to el");
-});
-
-test("fillInput writes into email/number/text inputs without InvalidStateError (symptom A)", e2eSkip, () => {
- const script = `
- const name = 'e2e-fill-input';
- await useOrCreateTaskSpace(name);
- const html = '<input name="email" type="email" value="[email protected]">'
- + '<input name="number" type="number" value="123">'
- + '<input name="text" type="text" value="oldtext">';
- await gotoAndWait('data:text/html;charset=utf-8,' + encodeURIComponent(html), { wait: true, timeout: 20 });
-
- await fillInput('input[name="email"]', '[email protected]');
- await fillInput('input[name="number"]', '456');
- await fillInput('input[name="text"]', 'newtext');
-
- const email = await elementEval('input[name="email"]', (el) => el.value);
- const number = await elementEval('input[name="number"]', (el) => el.value);
- const text = await elementEval('input[name="text"]', (el) => el.value);
-
- await completeTaskSpace(name, { keep: false });
- cliLog(JSON.stringify({ email, number, text }));
- `;
- const result = runScript(script);
- const payload = lastJsonLine(result.stderr);
- assert.equal(payload.email, "[email protected]", "fillInput must write into type=email without InvalidStateError");
- assert.equal(payload.number, "456", "fillInput must write into type=number without InvalidStateError");
- assert.equal(payload.text, "newtext");
-});
-
-test("fillInput addresses inputs by xpath= and loc=css: (symptom B)", e2eSkip, () => {
- const script = `
- const name = 'e2e-fill-selectors';
- await useOrCreateTaskSpace(name);
- const html = '<input name="a" type="email" value="">'
- + '<input name="b" type="text" value="">';
- await gotoAndWait('data:text/html;charset=utf-8,' + encodeURIComponent(html), { wait: true, timeout: 20 });
-
- await fillInput('xpath=//input[@name="a"]', '[email protected]');
- await fillInput('loc=css:input[name="b"]', 'loc-value');
-
- const a = await elementEval('input[name="a"]', (el) => el.value);
- const b = await elementEval('input[name="b"]', (el) => el.value);
-
- await completeTaskSpace(name, { keep: false });
- cliLog(JSON.stringify({ a, b }));
- `;
- const result = runScript(script);
- const payload = lastJsonLine(result.stderr);
- assert.equal(payload.a, "[email protected]", "fillInput must accept xpath= selectors");
- assert.equal(payload.b, "loc-value", "fillInput must accept loc=css: selectors");
-});
diff --git a/package/ego-browser/test/browser-runtime.test.js b/package/ego-browser/test/browser-runtime.test.js
deleted file mode 100644
index c02a801..0000000
--- a/package/ego-browser/test/browser-runtime.test.js
+++ /dev/null
@@ -1,185 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-
-import { installEgoSdk } from "../dist/src/index.js";
-import { browserCdp, browserEgo, browserSnapshotRefsToRefMap } from "../dist/src/browser-runtime.js";
-import * as helpers from "../dist/src/helpers.js";
-import { cdp } from "../dist/src/cdp-eval.js";
-import { RefMap } from "../dist/src/ref-map.js";
-
-function withBrowserRuntime(runtime, fn) {
- const previous = globalThis.ego;
- globalThis.ego = runtime;
- return Promise.resolve()
- .then(fn)
- .finally(() => {
- if (previous === undefined) {
- delete globalThis.ego;
- } else {
- globalThis.ego = previous;
- }
- });
-}
-
-test("installEgoSdk organizes ego into runtime, helpers, and learnings", async () => {
- const target = { ego: { sendCDPMessage() {}, createTab() {} } };
-
- await withBrowserRuntime(target.ego, async () => {
- installEgoSdk(target, {
- ready: undefined,
- context: {
- newTab: async (url) => `opened:${url}`,
- click: async () => {}
- },
- cliLog() {}
- });
- // helpers accessible on target but non-enumerable
- assert.equal(await target.newTab("https://example.com"), "opened:https://example.com");
- assert.equal(Object.keys(target).includes("newTab"), false);
-
- // ego.helpers contains SDK helpers + cliLog
- assert.equal(typeof target.ego.helpers.newTab, "function");
- assert.equal(typeof target.ego.helpers.click, "function");
- assert.equal(typeof target.ego.helpers.cliLog, "function");
-
- // ego.learnings is an empty namespace placeholder
- assert.deepEqual(target.ego.learnings, {});
-
- // ego top-level keeps only runtime built-ins
- assert.equal(typeof target.ego.sendCDPMessage, "function");
- assert.equal(typeof target.ego.createTab, "function");
-
- // helpers not leaked to ego top-level
- assert.equal(target.ego.newTab, undefined);
- assert.equal(target.ego.click, undefined);
-
- // Object.assign(ego, target) cannot copy non-enumerable helpers
- const copy = {};
- Object.assign(copy, target);
- assert.equal(copy.newTab, undefined);
- assert.equal(copy.click, undefined);
-
- // ego runtime methods exposed flat on target (non-enumerable)
- assert.equal(typeof target.createTab, "function");
- assert.equal(typeof target.sendCDPMessage, "function");
- assert.equal(Object.keys(target).includes("createTab"), false);
- });
-});
-
-test("browser runtime cdp rejects when sendCDPMessage throws", async () => {
- await withBrowserRuntime({
- sendCDPMessage() {
- throw new Error("boom");
- }
- }, async () => {
- await assert.rejects(() => browserCdp("Runtime.evaluate", {}, "S1", 20), /boom/);
- });
-});
-
-test("browser runtime cdp times out when no response arrives", async () => {
- const runtime = {
- onCDPMessage: undefined,
- sendCDPMessage() {}
- };
- await withBrowserRuntime(runtime, async () => {
- await assert.rejects(() => browserCdp("Runtime.evaluate", {}, "S1", 20), /timed out/);
- });
-});
-
-test("browser runtime ignores malformed and unknown CDP messages", async () => {
- const runtime = {
- onCDPMessage: undefined,
- sendCDPMessage(message) {
- this.lastMessage = JSON.parse(message);
- }
- };
- await withBrowserRuntime(runtime, async () => {
- const pending = cdp("Runtime.evaluate", { expression: "1 + 1" }, "S1");
- runtime.onCDPMessage("not json");
- runtime.onCDPMessage(JSON.stringify({ id: 999, result: { result: { value: 3 } } }));
- runtime.onCDPMessage(JSON.stringify({ method: "Network.requestWillBeSent", params: { requestId: "r1" } }));
- runtime.onCDPMessage(JSON.stringify({ id: runtime.lastMessage.id, result: { result: { value: 2 } } }));
- assert.deepEqual(await pending, { result: { value: 2 } });
- assert.deepEqual(await helpers.drainEvents(), [{ method: "Network.requestWillBeSent", params: { requestId: "r1" } }]);
- });
-});
-
-test("browser runtime surfaces CDP error responses", async () => {
- const runtime = {
- onCDPMessage: undefined,
- sendCDPMessage(message) {
- this.lastMessage = JSON.parse(message);
- queueMicrotask(() => {
- runtime.onCDPMessage(JSON.stringify({ id: runtime.lastMessage.id, error: { message: "bad" } }));
- });
- }
- };
- await withBrowserRuntime(runtime, async () => {
- await assert.rejects(() => cdp("Runtime.evaluate", { expression: "1 + 1" }, "S1"), /bad/);
- });
-});
-
-test("browser runtime throws without ego binding", () => {
- const previous = globalThis.ego;
- delete globalThis.ego;
- try {
- assert.throws(() => browserEgo(), /browser runtime is not available/);
- } finally {
- if (previous !== undefined) {
- globalThis.ego = previous;
- }
- }
-});
-
-test("browser snapshot refs map by backendNodeId and skips invalid refs", () => {
- const refMap = new RefMap();
- browserSnapshotRefsToRefMap(refMap, [
- null,
- { backendNodeId: 7, role: "button", name: "Save" },
- "x",
- { backendNodeId: 9, role: "link", name: "Docs" },
- { role: "stale", name: "no backend id" }
- ]);
-
- assert.deepEqual(refMap.get("7"), {
- backendNodeId: 7,
- role: "button",
- name: "Save",
- nth: undefined,
- selector: undefined,
- frameId: undefined
- });
- assert.deepEqual(refMap.get("9"), {
- backendNodeId: 9,
- role: "link",
- name: "Docs",
- nth: undefined,
- selector: undefined,
- frameId: undefined
- });
-});
-
-test("browser runtime tab and snapshot helpers use ego APIs", async () => {
- const runtime = {
- sendCDPMessage() {},
- listTabs: async () => ({ tabs: [{ index: 0, targetId: "tab-1", url: "https://example.com", title: "Example", active: true }] }),
- createTab: async (url) => ({ targetId: `created:${url}` }),
- snapshot: async (options) => ({
- content: `scope=${options.scope}`,
- refs: [{ backendNodeId: 42, role: "button", name: "Submit" }]
- })
- };
-
- await withBrowserRuntime(runtime, async () => {
- assert.equal(await helpers.newTab("https://example.com"), "created:https://example.com");
- assert.deepEqual(await helpers.currentTab(), { targetId: "tab-1", url: "https://example.com", title: "Example" });
- assert.deepEqual(await helpers.snapshot({ scope: "only_within_viewport", includeActionMarks: true, includeStableLocator: true }), {
- content: "scope=only_within_viewport",
- refs: [{ backendNodeId: 42, role: "button", name: "Submit" }]
- });
- assert.deepEqual(await helpers.snapshotRaw({ scope: "full_page" }), {
- content: "scope=full_page",
- refs: [{ backendNodeId: 42, role: "button", name: "Submit" }]
- });
- });
-});
diff --git a/package/ego-browser/test/build-artifact.test.js b/package/ego-browser/test/build-artifact.test.js
deleted file mode 100644
index 5dfdc84..0000000
--- a/package/ego-browser/test/build-artifact.test.js
+++ /dev/null
@@ -1,66 +0,0 @@
-import assert from "node:assert/strict";
-import { access, readFile, stat } from "node:fs/promises";
-import { constants } from "node:fs";
-import { dirname, join } from "node:path";
-import { fileURLToPath } from "node:url";
-import { spawnSync } from "node:child_process";
-import test from "node:test";
-
-const root = dirname(dirname(fileURLToPath(import.meta.url)));
-const artifactPath = join(root, "artifacts", "ego-browser", "index.js");
-
-test("build artifact exists as a single executable JavaScript file", async () => {
- const info = await stat(artifactPath);
- assert.equal(info.isFile(), true);
- assert.ok(info.size > 10_000);
- await access(artifactPath, constants.X_OK);
-
- const source = await readFile(artifactPath, "utf8");
- assert.match(source, /^#!\/usr\/bin\/env node\n/);
- assert.equal(source.includes("\n#!/usr/bin/env node"), false);
-});
-
-test("build artifact runs help and stdin scripts directly", () => {
- const help = spawnSync(process.execPath, [artifactPath, "--help"], {
- cwd: root,
- encoding: "utf8"
- });
- assert.equal(help.status, 0, help.stderr);
- assert.match(help.stdout, /ego-browser/);
- assert.match(help.stdout, /Helpers are pre-imported/);
-
- const stdin = spawnSync(process.execPath, [artifactPath], {
- cwd: root,
- input: "cliLog('artifact-ok', typeof pageInfo)\n",
- encoding: "utf8"
- });
- assert.equal(stdin.status, 0, stdin.stderr);
- assert.equal(stdin.stdout, "artifact-ok function\n");
-});
-
-test("build output is isolated from legacy root and bin paths", async () => {
- await assert.rejects(access(join(root, "ego-browser.js")));
- await assert.rejects(access(join(root, "bin")));
-});
-
-test("package bin metadata points at the generated artifact", async () => {
- const pkg = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
- const lock = JSON.parse(await readFile(join(root, "package-lock.json"), "utf8"));
-
- assert.deepEqual(pkg.bin, { index: "./artifacts/ego-browser/index.js" });
- assert.deepEqual(lock.packages[""].bin, { index: "artifacts/ego-browser/index.js" });
- await access(join(root, pkg.bin.index));
-});
-
-test("npm pack includes the generated bin artifact", () => {
- const result = spawnSync("npm", ["pack", "--dry-run", "--json"], {
- cwd: root,
- encoding: "utf8"
- });
- assert.equal(result.status, 0, result.stderr);
- const packs = JSON.parse(result.stdout);
- const files = packs[0].files.map((file) => file.path);
-
- assert.ok(files.includes("artifacts/ego-browser/index.js"));
- assert.ok(files.includes("package.json"));
-});
diff --git a/package/ego-browser/test/build-lock.test.js b/package/ego-browser/test/build-lock.test.js
deleted file mode 100644
index 7a965f4..0000000
--- a/package/ego-browser/test/build-lock.test.js
+++ /dev/null
@@ -1,23 +0,0 @@
-import assert from "node:assert/strict";
-import { rm, writeFile } from "node:fs/promises";
-import { dirname, join } from "node:path";
-import { fileURLToPath } from "node:url";
-import { spawnSync } from "node:child_process";
-import test from "node:test";
-
-const root = dirname(dirname(fileURLToPath(import.meta.url)));
-const lockPath = join(root, ".build.lock");
-
-test("build fails clearly when another build lock exists", async () => {
- await writeFile(lockPath, "test lock");
- try {
- const result = spawnSync(process.execPath, ["scripts/build.mjs"], {
- cwd: root,
- encoding: "utf8"
- });
- assert.notEqual(result.status, 0);
- assert.match(result.stderr, /another ego-browser-v2 build is already running/);
- } finally {
- await rm(lockPath, { force: true });
- }
-});
diff --git a/package/ego-browser/test/element-resolver.test.js b/package/ego-browser/test/element-resolver.test.js
deleted file mode 100644
index 41286a6..0000000
--- a/package/ego-browser/test/element-resolver.test.js
+++ /dev/null
@@ -1,163 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-
-import { resolveElementCenter, resolveElementObjectId } from "../dist/src/element-resolver.js";
-import { parseRef, RefMap } from "../dist/src/ref-map.js";
-
-class FakeCDP {
- constructor(handler) {
- this.calls = [];
- this.handler = handler;
- }
-
- async sendRaw(method, params = {}, sessionId = undefined) {
- this.calls.push([method, params, sessionId]);
- return this.handler(method, params, sessionId);
- }
-}
-
-test("parseRef accepts Agent Browser ref spellings", () => {
- assert.equal(parseRef("@10"), "10");
- assert.equal(parseRef("ref=42"), "42");
- assert.equal(parseRef("7"), "7");
- assert.equal(parseRef("button"), null);
- assert.equal(parseRef("@e1"), null);
-});
-
-test("resolveElementCenter uses cached backendNodeId and iframe session", async () => {
- const refMap = new RefMap();
- refMap.addWithFrame("42", 42, "button", "Submit", undefined, "frame-1");
- const iframeSessions = new Map([["frame-1", "iframe-session"]]);
- const cdp = new FakeCDP(async (method) => {
- assert.equal(method, "DOM.getBoxModel");
- return { model: { content: [0, 0, 20, 0, 20, 10, 0, 10] } };
- });
-
- assert.deepEqual(await resolveElementCenter(cdp, "page-session", refMap, "@42", iframeSessions), {
- x: 10,
- y: 5,
- sessionId: "iframe-session"
- });
- assert.deepEqual(cdp.calls[0], ["DOM.getBoxModel", { backendNodeId: 42 }, "iframe-session"]);
-});
-
-test("resolveElementObjectId falls back to role/name lookup when cached backendNodeId is stale", async () => {
- const refMap = new RefMap();
- refMap.add("42", 42, "button", "Submit");
- let stale = true;
- const cdp = new FakeCDP(async (method, params) => {
- if (method === "DOM.resolveNode" && stale) {
- stale = false;
- throw new Error("stale node");
- }
- if (method === "Accessibility.getFullAXTree") {
- return {
- nodes: [
- {
- nodeId: "1",
- ignored: false,
- role: { value: "button" },
- name: { value: "Submit" },
- backendDOMNodeId: 99
- }
- ]
- };
- }
- if (method === "DOM.resolveNode") {
- assert.equal(params.backendNodeId, 99);
- return { object: { objectId: "object-99" } };
- }
- return {};
- });
-
- assert.deepEqual(await resolveElementObjectId(cdp, "page-session", refMap, "ref=42"), {
- objectId: "object-99",
- sessionId: "page-session"
- });
-});
-
-test("resolveElementObjectId supports CSS and XPath selectors", async () => {
- const cdp = new FakeCDP(async (method, params) => {
- assert.equal(method, "Runtime.evaluate");
- assert.equal(params.returnByValue, false);
- return { result: { objectId: "selector-object" } };
- });
-
- assert.deepEqual(await resolveElementObjectId(cdp, "page-session", new RefMap(), "xpath=//button"), {
- objectId: "selector-object",
- sessionId: "page-session"
- });
- assert.match(cdp.calls[0][1].expression, /document\.evaluate/);
-});
-
-test("resolveElementObjectId supports stable locator strings", async () => {
- const cdp = new FakeCDP(async (method, params) => {
- if (method === "Runtime.evaluate" && params.returnByValue) {
- if (params.expression.includes("querySelectorAll")) {
- return { result: { value: 1 } };
- }
- if (params.expression.includes("HTMLAnchorElement")) {
- return { result: { value: 1 } };
- }
- }
- if (method === "Runtime.evaluate") {
- return { result: { objectId: "locator-object" } };
- }
- return {};
- });
-
- assert.deepEqual(await resolveElementObjectId(cdp, "page-session", new RefMap(), "css:button[data-testid=\"save\"]"), {
- objectId: "locator-object",
- sessionId: "page-session"
- });
- assert.deepEqual(await resolveElementObjectId(cdp, "page-session", new RefMap(), "href:/settings"), {
- objectId: "locator-object",
- sessionId: "page-session"
- });
-});
-
-test("resolveElementCenter supports unique role/name locators and rejects duplicates", async () => {
- const cdp = new FakeCDP(async (method, params) => {
- if (method === "Accessibility.getFullAXTree") {
- return {
- nodes: [
- {
- nodeId: "1",
- ignored: false,
- role: { value: "button" },
- name: { value: "Save" },
- backendDOMNodeId: 44
- }
- ]
- };
- }
- if (method === "DOM.getBoxModel") {
- assert.equal(params.backendNodeId, 44);
- return { model: { content: [0, 0, 20, 0, 20, 10, 0, 10] } };
- }
- return {};
- });
-
- assert.deepEqual(await resolveElementCenter(cdp, "page-session", new RefMap(), "role:button[name=\"Save\"]"), {
- x: 10,
- y: 5,
- sessionId: "page-session"
- });
-
- const duplicate = new FakeCDP(async (method) => {
- if (method === "Accessibility.getFullAXTree") {
- return {
- nodes: [
- { nodeId: "1", ignored: false, role: { value: "button" }, name: { value: "Save" }, backendDOMNodeId: 1 },
- { nodeId: "2", ignored: false, role: { value: "button" }, name: { value: "Save" }, backendDOMNodeId: 2 }
- ]
- };
- }
- return {};
- });
-
- await assert.rejects(
- () => resolveElementCenter(duplicate, "page-session", new RefMap(), "role:button[name=\"Save\"]"),
- /matched 2 elements/
- );
-});
diff --git a/package/ego-browser/test/helpers.test.js b/package/ego-browser/test/helpers.test.js
deleted file mode 100644
index d877c2c..0000000
--- a/package/ego-browser/test/helpers.test.js
+++ /dev/null
@@ -1,1025 +0,0 @@
-import assert from "node:assert/strict";
-import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import test from "node:test";
-
-import * as helpers from "../dist/src/helpers.js";
-import { browserRefMap } from "../dist/src/ref-state.js";
-
-function withOverrides(overrides, fn) {
- const restore = helpers.__testing.setOverrides(overrides);
- return Promise.resolve()
- .then(fn)
- .finally(restore);
-}
-
-test("helpers expose camelCase names without snake_case aliases", () => {
- for (const name of [
- "drain_events",
- "goto_url",
- "site_skills_enabled",
- "site_skills_status",
- "site_skills_for_url",
- "site_skills",
- "run_site_tool",
- "run_site_browser_tool",
- "page_info",
- "type_text",
- "fill_input",
- "press_key",
- "element_eval",
- "element_center",
- "capture_screenshot",
- "list_tabs",
- "current_tab",
- "switch_tab",
- "new_tab",
- "ensure_real_tab",
- "iframe_target",
- "wait_for_load",
- "wait_for_element",
- "wait_for_network_idle",
- "dispatch_key",
- "upload_file",
- "http_get"
- ]) {
- assert.equal(Object.hasOwn(helpers, name), false, `${name} should not be exported`);
- }
-});
-
-test("js wraps top-level return but ignores return inside strings and comments", async () => {
- const calls = [];
- await withOverrides({
- cdpOverride: async (method, params) => {
- calls.push([method, params]);
- return { result: { value: null } };
- }
- }, async () => {
- await helpers.js("const x = 1; return x");
- await helpers.js("document.body.innerText.includes('return ')");
- await helpers.js("// return comment\n1 + 1");
- });
-
- assert.equal(calls[0][1].expression, "(function(){const x = 1; return x})()");
- assert.equal(calls[1][1].expression, "document.body.innerText.includes('return ')");
- assert.equal(calls[2][1].expression, "// return comment\n1 + 1");
-});
-
-test("js accepts a function value, wraps it as an IIFE, and warns once on stderr", async () => {
- const calls = [];
- const originalWrite = process.stderr.write.bind(process.stderr);
- const stderrChunks = [];
- process.stderr.write = (chunk) => {
- stderrChunks.push(typeof chunk === "string" ? chunk : chunk.toString());
- return true;
- };
- try {
- await withOverrides({
- cdpOverride: async (method, params) => {
- calls.push([method, params]);
- return { result: { value: null } };
- }
- }, async () => {
- await helpers.js(() => 1 + 1);
- await helpers.js(() => 2 + 2);
- });
- } finally {
- process.stderr.write = originalWrite;
- }
-
- assert.match(calls[0][1].expression, /^\(\(?\)?\s*=>\s*1\s*\+\s*1\)\(\)$/);
- assert.match(calls[1][1].expression, /^\(\(?\)?\s*=>\s*2\s*\+\s*2\)\(\)$/);
- const warning = stderrChunks.join("");
- assert.match(warning, /\[ego-browser\] js\(\) received a function and auto-wrapped it/);
- assert.match(warning, /CDP Runtime\.evaluate/);
- assert.match(warning, /elementEval\(target, \(el, \.\.\.args\) => \.\.\.\)/);
- const occurrences = warning.match(/\[ego-browser\] js\(\) received a function/g) || [];
- assert.equal(occurrences.length, 1, "warning should be emitted only once per process");
-});
-
-test("js rejects non-string non-function expressions with a clear TypeError", async () => {
- await withOverrides({
- cdpOverride: async () => ({ result: { value: null } })
- }, async () => {
- await assert.rejects(() => helpers.js(123), /expects a string expression or function, got number/);
- await assert.rejects(() => helpers.js(null), /expects a string expression or function, got null/);
- await assert.rejects(() => helpers.js({ source: "1" }), /expects a string expression or function, got object/);
- });
-});
-
-test("js surfaces CDP exception details with expression context", async () => {
- await withOverrides({
- cdpOverride: async () => ({
- result: {
- type: "object",
- subtype: "error",
- description: "ReferenceError: missing is not defined"
- },
- exceptionDetails: {
- text: "Uncaught",
- lineNumber: 0,
- columnNumber: 17
- }
- })
- }, async () => {
- await assert.rejects(() => helpers.js("return missing.value"), /ReferenceError.*missing/);
- });
-});
-
-test("js returns unserializable JavaScript values", () => {
- assert.ok(Number.isNaN(helpers.__testing.decodeUnserializableJsValue("NaN")));
- assert.equal(helpers.__testing.decodeUnserializableJsValue("Infinity"), Infinity);
- assert.equal(Object.is(helpers.__testing.decodeUnserializableJsValue("-0"), -0), true);
- assert.equal(helpers.__testing.decodeUnserializableJsValue("1n"), 1n);
-});
-
-test("gotoUrl includes domain skills only when enabled", async () => {
- const dir = await mkdtemp(join(tmpdir(), "ego-browser-skills-"));
- const previous = process.env.EGO_BROWSER_DOMAIN_SKILLS;
- try {
- await mkdir(join(dir, "domain-skills", "example"), { recursive: true });
- await writeFile(join(dir, "domain-skills", "example", "scraping.md"), "hi");
-
- await withOverrides({
- agentWorkspace: () => dir,
- cdpOverride: async () => ({ frameId: "f" })
- }, async () => {
- delete process.env.EGO_BROWSER_DOMAIN_SKILLS;
- assert.deepEqual(await helpers.gotoUrl("https://www.example.com/"), { frameId: "f" });
- process.env.EGO_BROWSER_DOMAIN_SKILLS = "1";
- assert.deepEqual(await helpers.gotoUrl("https://www.example.com/"), {
- frameId: "f",
- domain_skills: ["scraping.md"]
- });
- });
- } finally {
- if (previous === undefined) {
- delete process.env.EGO_BROWSER_DOMAIN_SKILLS;
- } else {
- process.env.EGO_BROWSER_DOMAIN_SKILLS = previous;
- }
- await rm(dir, { recursive: true, force: true });
- }
-});
-
-test("listTaskSpaces normalizes ego listTaskSpaces object results", async () => {
- const previous = globalThis.ego;
- globalThis.ego = {
- listTaskSpaces: async () => ({ taskIds: ["default", "x-openai-7d-posts"] })
- };
- try {
- const spaces = await helpers.listTaskSpaces();
- assert.deepEqual(spaces, [
- { taskId: "default", id: "default", name: "default" },
- { taskId: "x-openai-7d-posts", id: "x-openai-7d-posts", name: "x-openai-7d-posts" }
- ]);
- } finally {
- if (previous === undefined) {
- delete globalThis.ego;
- } else {
- globalThis.ego = previous;
- }
- }
-});
-
-function withTaskSpaceEgo(extraMethods = {}) {
- return {
- listTaskSpaces: async () => ({ taskIds: ["my-task"] }),
- closeTaskSpace: async () => {},
- completeTaskSpace: async () => {},
- handOffTaskSpace: async () => {},
- takeOverTaskSpace: async () => {},
- ...extraMethods
- };
-}
-
-async function withEgo(ego, fn) {
- const previous = globalThis.ego;
- globalThis.ego = ego;
- try {
- await fn();
- } finally {
- if (previous === undefined) {
- delete globalThis.ego;
- } else {
- globalThis.ego = previous;
- }
- }
-}
-
-test("completeTaskSpace with keep:false closes the task space", async () => {
- const calls = [];
- await withEgo(withTaskSpaceEgo({
- useTaskSpace: (id) => calls.push(["use", id]),
- closeTaskSpace: async (...args) => calls.push(["close", ...args]),
- completeTaskSpace: async () => calls.push(["complete"])
- }), async () => {
- await helpers.completeTaskSpace("my-task", { keep: false });
- });
- assert.deepEqual(calls, [["use", "my-task"], ["close"]]);
-});
-
-test("completeTaskSpace with keep:true keeps the page for the user", async () => {
- const calls = [];
- await withEgo(withTaskSpaceEgo({
- useTaskSpace: (id) => calls.push(["use", id]),
- closeTaskSpace: async (id) => calls.push(["close", id]),
- completeTaskSpace: async () => calls.push(["complete"])
- }), async () => {
- await helpers.completeTaskSpace("my-task", { keep: true });
- });
- assert.deepEqual(calls, [["use", "my-task"], ["complete"]]);
-});
-
-test("completeTaskSpace requires { keep } option", async () => {
- await withEgo(withTaskSpaceEgo(), async () => {
- await assert.rejects(() => helpers.completeTaskSpace("my-task"), /\{ keep: boolean \}/);
- await assert.rejects(() => helpers.completeTaskSpace("my-task", {}), /\{ keep: boolean \}/);
- });
-});
-
-test("completeTaskSpace throws when task space not found", async () => {
- await withEgo(withTaskSpaceEgo(), async () => {
- await assert.rejects(() => helpers.completeTaskSpace("unknown", { keep: false }), /task space not found/);
- });
-});
-
-test("completeTaskSpace surfaces ego { error } responses", async () => {
- await withEgo(withTaskSpaceEgo({
- useTaskSpace: () => {},
- closeTaskSpace: async () => ({ error: "The task is under user control" })
- }), async () => {
- await assert.rejects(
- () => helpers.completeTaskSpace("my-task", { keep: false }),
- /completeTaskSpace: The task is under user control/
- );
- });
-
- await withEgo(withTaskSpaceEgo({
- useTaskSpace: () => {},
- completeTaskSpace: async () => ({ error: "Task not found" })
- }), async () => {
- await assert.rejects(
- () => helpers.completeTaskSpace("my-task", { keep: true }),
- /completeTaskSpace: Task not found/
- );
- });
-});
-
-test("handOffTaskSpace surfaces ego { error } responses", async () => {
- await withEgo(withTaskSpaceEgo({
- handOffTaskSpace: async () => ({ error: "Task not found" })
- }), async () => {
- await assert.rejects(() => helpers.handOffTaskSpace(), /handOffTaskSpace: Task not found/);
- });
-});
-
-test("takeOverTaskSpace surfaces ego { error } responses", async () => {
- await withEgo(withTaskSpaceEgo({
- takeOverTaskSpace: async () => ({ error: "Task not found" })
- }), async () => {
- await assert.rejects(() => helpers.takeOverTaskSpace(), /takeOverTaskSpace: Task not found/);
- });
-});
-
-test("handOffTaskSpace calls ego.handOffTaskSpace with no arguments", async () => {
- let called = false;
- await withEgo(withTaskSpaceEgo({ handOffTaskSpace: async () => { called = true; } }), async () => {
- await helpers.handOffTaskSpace();
- });
- assert.equal(called, true);
-});
-
-test("handOffTaskSpace switches to named task space before handing off", async () => {
- const calls = [];
- await withEgo(withTaskSpaceEgo({
- useTaskSpace: (id) => calls.push(["use", id]),
- handOffTaskSpace: async () => calls.push(["handOff"])
- }), async () => {
- await helpers.handOffTaskSpace("my-task");
- });
- assert.deepEqual(calls, [["use", "my-task"], ["handOff"]]);
-});
-
-test("takeOverTaskSpace calls ego.takeOverTaskSpace with no arguments", async () => {
- let called = false;
- await withEgo(withTaskSpaceEgo({ takeOverTaskSpace: async () => { called = true; } }), async () => {
- await helpers.takeOverTaskSpace();
- });
- assert.equal(called, true);
-});
-
-test("takeOverTaskSpace switches to named task space before taking over", async () => {
- const calls = [];
- await withEgo(withTaskSpaceEgo({
- useTaskSpace: (id) => calls.push(["use", id]),
- takeOverTaskSpace: async () => calls.push(["takeOver"])
- }), async () => {
- await helpers.takeOverTaskSpace("my-task");
- });
- assert.deepEqual(calls, [["use", "my-task"], ["takeOver"]]);
-});
-
-test("waitForAgentControl returns once the probe succeeds", async () => {
- let attempts = 0;
- const ego = withTaskSpaceEgo({
- useTaskSpace: () => {},
- snapshot: async () => {
- attempts += 1;
- if (attempts < 3) throw new Error("The task is under user control");
- return { content: "", refs: [] };
- }
- });
- await withEgo(ego, async () => {
- await helpers.waitForAgentControl("my-task", { interval: 0.01, timeout: 5 });
- });
- assert.equal(attempts, 3);
-});
-
-test("waitForAgentControl throws when timeout elapses", async () => {
- const ego = withTaskSpaceEgo({
- useTaskSpace: () => {},
- snapshot: async () => { throw new Error("The task is under user control"); }
- });
- await withEgo(ego, async () => {
- await assert.rejects(
- () => helpers.waitForAgentControl("my-task", { interval: 0.01, timeout: 0.05 }),
- /waitForAgentControl timed out/
- );
- });
-});
-
-test("waitForAgentControl requires a task space name", async () => {
- await withEgo(withTaskSpaceEgo(), async () => {
- await assert.rejects(() => helpers.waitForAgentControl(), /requires a task space name/);
- });
-});
-
-test("waitForAgentControl propagates non-user-control snapshot errors", async () => {
- const ego = withTaskSpaceEgo({
- useTaskSpace: () => {},
- snapshot: async () => { throw new Error("task space not found"); }
- });
- await withEgo(ego, async () => {
- await assert.rejects(
- () => helpers.waitForAgentControl("my-task", { interval: 0.01, timeout: 5 }),
- /task space not found/
- );
- });
-});
-
-test("assertNoEgoError stringifies non-string error fields", async () => {
- await withEgo(withTaskSpaceEgo({
- handOffTaskSpace: async () => ({ error: { code: 42, message: "boom" } })
- }), async () => {
- await assert.rejects(() => helpers.handOffTaskSpace(), /handOffTaskSpace:.*boom|handOffTaskSpace:.*42/);
- });
-});
-
-test("useOrCreateTaskSpace reuses matching normalized task spaces", async () => {
- const calls = [];
- const previous = globalThis.ego;
- globalThis.ego = {
- listTaskSpaces: async () => ({ taskIds: ["x-openai-7d-posts"] }),
- useTaskSpace: (taskId) => calls.push(["use", taskId])
- };
- try {
- const task = await helpers.useOrCreateTaskSpace("x-openai-7d-posts");
- assert.deepEqual(task, {
- taskId: "x-openai-7d-posts",
- id: "x-openai-7d-posts",
- name: "x-openai-7d-posts"
- });
- assert.deepEqual(calls, [["use", "x-openai-7d-posts"]]);
- } finally {
- if (previous === undefined) {
- delete globalThis.ego;
- } else {
- globalThis.ego = previous;
- }
- }
-});
-
-test("fillInput resolves the selector, clears via native value setter, inserts text, and fires framework events", async () => {
- const calls = [];
- await withOverrides({
- cdpOverride: async (method, params, sessionId) => {
- calls.push([method, params, sessionId]);
- if (method === "Runtime.evaluate") return { result: { objectId: "obj-css" } };
- return {};
- }
- }, async () => {
- await helpers.fillInput("#my-input", "x");
- });
-
- const callFnOn = calls.filter(([m]) => m === "Runtime.callFunctionOn").map(([, p]) => p);
- assert.ok(calls.some(([m, p]) => m === "Runtime.evaluate" && /querySelector/.test(p.expression || "")), "must resolve raw CSS via the unified resolver");
- assert.ok(callFnOn.length > 0 && callFnOn.every((p) => p.objectId === "obj-css"), "callFunctionOn must target the resolved objectId");
- assert.equal(callFnOn.some((p) => /setSelectionRange/.test(p.functionDeclaration)), false, "must not use setSelectionRange");
- assert.equal(calls.some(([m, p]) => m === "Input.dispatchKeyEvent" && p.key === "Backspace"), false, "must not clear with Backspace");
- assert.ok(callFnOn.some((p) => /this\.value\s*=\s*''/.test(p.functionDeclaration)), "must clear via native value setter");
- assert.ok(calls.some(([m, p]) => m === "Input.insertText" && p.text === "x"), "must insert text via CDP");
- assert.ok(callFnOn.some((p) => /'input'/.test(p.functionDeclaration) && /'change'/.test(p.functionDeclaration)), "must fire input/change events");
-});
-
-test("pressKey sends printable text on keyDown", async () => {
- const keyEvents = [];
- await withOverrides({
- cdpOverride: async (method, params) => {
- if (method === "Input.dispatchKeyEvent") {
- keyEvents.push(params);
- }
- return {};
- }
- }, async () => {
- await helpers.pressKey("x");
- });
-
- assert.deepEqual(keyEvents.map((event) => event.type), ["keyDown", "keyUp"]);
- assert.equal(keyEvents[0].key, "x");
- assert.equal(keyEvents[0].code, "KeyX");
- assert.equal(keyEvents[0].text, "x");
- assert.equal(keyEvents[0].unmodifiedText, "x");
-});
-
-test("pressKey sends special-key text when the browser needs it", async () => {
- const keyEvents = [];
- await withOverrides({
- cdpOverride: async (method, params) => {
- if (method === "Input.dispatchKeyEvent") {
- keyEvents.push(params);
- }
- return {};
- }
- }, async () => {
- await helpers.pressKey("Enter");
- });
-
- assert.deepEqual(keyEvents.map((event) => event.type), ["keyDown", "keyUp"]);
- assert.equal(keyEvents[0].text, "\r");
- assert.equal(keyEvents[0].unmodifiedText, "\r");
-});
-
-test("scroll preserves the mouse-wheel signature", async () => {
- const calls = [];
- await withOverrides({
- cdpOverride: async (method, params) => {
- calls.push([method, params]);
- return {};
- }
- }, async () => {
- await helpers.scroll(10, 20, { dx: 1, dy: -250 });
- await helpers.scroll({ dy: 900 });
- });
-
- assert.deepEqual(calls, [
- [
- "Input.dispatchMouseEvent",
- { type: "mouseWheel", x: 10, y: 20, deltaX: 1, deltaY: -250 }
- ],
- [
- "Input.dispatchMouseEvent",
- { type: "mouseWheel", x: 0, y: 0, deltaX: 0, deltaY: 900 }
- ]
- ]);
-});
-
-test("scrollBy uses DOM window scrolling", async () => {
- const expressions = [];
- await withOverrides({
- cdpOverride: async (method, params) => {
- assert.equal(method, "Runtime.evaluate");
- expressions.push(params.expression);
- return { result: { value: { x: 0, y: 900 } } };
- }
- }, async () => {
- const result = await helpers.scrollBy({ dy: 900 });
- assert.deepEqual(result, { x: 0, y: 900 });
- });
-
- assert.match(expressions[0], /window\.scrollBy/);
- assert.match(expressions[0], /top: 900/);
-});
-
-test("scrollToBottomUntil scrolls until a function condition is met", async () => {
- const states = [
- { x: 0, y: 0, viewportHeight: 900, scrollHeight: 3000, atBottom: false },
- { x: 0, y: 900, viewportHeight: 900, scrollHeight: 3000, atBottom: false }
- ];
- let domScrolls = 0;
- await withOverrides({
- cdpOverride: async (method, params) => {
- assert.equal(method, "Runtime.evaluate");
- if (params.expression.includes("window.scrollBy")) {
- domScrolls += 1;
- return { result: { value: { x: 0, y: 900 } } };
- }
- return { result: { value: states.shift() } };
- }
- }, async () => {
- const result = await helpers.scrollToBottomUntil((state) => state.y >= 900, { wait: 0, maxSteps: 3 });
- assert.equal(result.done, true);
- assert.equal(result.reason, "condition");
- assert.equal(result.steps, 1);
- });
-
- assert.equal(domScrolls, 1);
-});
-
-test("click doubleClick and hover accept viewport coordinate targets", async () => {
- const calls = [];
- await withOverrides({
- cdpOverride: async (method, params, sessionId) => {
- calls.push([method, params, sessionId]);
- return {};
- }
- }, async () => {
- await helpers.click({ x: 10, y: 20 });
- await helpers.doubleClick([30, 40]);
- await helpers.hover({ x: 50, y: 60 });
- });
-
- assert.deepEqual(calls, [
- ["Input.dispatchMouseEvent", { type: "mousePressed", x: 10, y: 20, button: "left", buttons: 1, clickCount: 1 }, undefined],
- ["Input.dispatchMouseEvent", { type: "mouseReleased", x: 10, y: 20, button: "left", buttons: 0, clickCount: 1 }, undefined],
- ["Input.dispatchMouseEvent", { type: "mousePressed", x: 30, y: 40, button: "left", buttons: 1, clickCount: 2 }, undefined],
- ["Input.dispatchMouseEvent", { type: "mouseReleased", x: 30, y: 40, button: "left", buttons: 0, clickCount: 2 }, undefined],
- ["Input.dispatchMouseEvent", { type: "mouseMoved", x: 50, y: 60, buttons: 0 }, undefined]
- ]);
-});
-
-test("waitForElement visible check uses checkVisibility with computed-style fallback", async () => {
- const calls = [];
- await withOverrides({
- cdpOverride: async (method, params) => {
- calls.push([method, params]);
- if (method === "Runtime.evaluate") return { result: { objectId: "obj-btn" } };
- if (method === "Runtime.callFunctionOn") return { result: { value: true } };
- return {};
- },
- now: (() => {
- let value = 1000;
- return () => value += 1;
- })(),
- sleep: async () => {}
- }, async () => {
- assert.equal(await helpers.waitForElement("#btn", { visible: true }), true);
- });
- const callFnOn = calls.find(([m]) => m === "Runtime.callFunctionOn");
- assert.ok(callFnOn, "visibility must be checked via callFunctionOn on the resolved element");
- assert.match(callFnOn[1].functionDeclaration, /checkVisibility/);
- assert.match(callFnOn[1].functionDeclaration, /getComputedStyle/);
- assert.equal(callFnOn[1].functionDeclaration.includes("offsetParent"), false);
-});
-
-test("captureScreenshot clips to CSS viewport with scale=1/DPR by default", async () => {
- const tmp = await mkdtemp(join(tmpdir(), "shot-"));
- const path = join(tmp, "shot.png");
- let shotParams;
- try {
- await withOverrides({
- cdpOverride: async (method, params) => {
- if (method === "Runtime.evaluate") {
- if (params.expression.includes("devicePixelRatio")) return { result: { value: 2 } };
- return { result: { value: JSON.stringify({ url: "u", title: "t", w: 1291, h: 805, sx: 0, sy: 0, pw: 1291, ph: 4000 }) } };
- }
- if (method === "Page.captureScreenshot") {
- shotParams = params;
- return { data: Buffer.from("png").toString("base64") };
- }
- return {};
- },
- writeFile: async () => {}
- }, async () => {
- await helpers.captureScreenshot(path);
- });
- } finally {
- await rm(tmp, { recursive: true, force: true });
- }
- assert.deepEqual(shotParams.clip, { x: 0, y: 0, width: 1291, height: 805, scale: 0.5 });
- assert.equal(shotParams.captureBeyondViewport, false);
-});
-
-test("captureScreenshot uses scale=1 when DPR is 1", async () => {
- const tmp = await mkdtemp(join(tmpdir(), "shot-"));
- const path = join(tmp, "shot.png");
- let shotParams;
- try {
- await withOverrides({
- cdpOverride: async (method, params) => {
- if (method === "Runtime.evaluate") {
- if (params.expression.includes("devicePixelRatio")) return { result: { value: 1 } };
- return { result: { value: JSON.stringify({ url: "u", title: "t", w: 1280, h: 800, sx: 0, sy: 0, pw: 1280, ph: 800 }) } };
- }
- if (method === "Page.captureScreenshot") {
- shotParams = params;
- return { data: Buffer.from("png").toString("base64") };
- }
- return {};
- },
- writeFile: async () => {}
- }, async () => {
- await helpers.captureScreenshot(path);
- });
- } finally {
- await rm(tmp, { recursive: true, force: true });
- }
- assert.equal(shotParams.clip.scale, 1);
-});
-
-test("captureScreenshot full uses pw/ph for the clip", async () => {
- const tmp = await mkdtemp(join(tmpdir(), "shot-"));
- const path = join(tmp, "shot.png");
- let shotParams;
- try {
- await withOverrides({
- cdpOverride: async (method, params) => {
- if (method === "Runtime.evaluate") {
- if (params.expression.includes("devicePixelRatio")) return { result: { value: 2 } };
- return { result: { value: JSON.stringify({ url: "u", title: "t", w: 1291, h: 805, sx: 0, sy: 0, pw: 1291, ph: 4000 }) } };
- }
- if (method === "Page.captureScreenshot") {
- shotParams = params;
- return { data: Buffer.from("png").toString("base64") };
- }
- return {};
- },
- writeFile: async () => {}
- }, async () => {
- await helpers.captureScreenshot(path, { full: true });
- });
- } finally {
- await rm(tmp, { recursive: true, force: true });
- }
- assert.deepEqual(shotParams.clip, { x: 0, y: 0, width: 1291, height: 4000, scale: 0.5 });
- assert.equal(shotParams.captureBeyondViewport, true);
-});
-
-test("captureScreenshot custom clip without scale fills in 1/DPR", async () => {
- const tmp = await mkdtemp(join(tmpdir(), "shot-"));
- const path = join(tmp, "shot.png");
- let shotParams;
- try {
- await withOverrides({
- cdpOverride: async (method, params) => {
- if (method === "Runtime.evaluate") {
- if (params.expression.includes("devicePixelRatio")) return { result: { value: 2 } };
- return { result: { value: JSON.stringify({ url: "u", title: "t", w: 1291, h: 805, sx: 0, sy: 0, pw: 1291, ph: 4000 }) } };
- }
- if (method === "Page.captureScreenshot") {
- shotParams = params;
- return { data: Buffer.from("png").toString("base64") };
- }
- return {};
- },
- writeFile: async () => {}
- }, async () => {
- await helpers.captureScreenshot(path, { clip: { x: 100, y: 50, width: 400, height: 300 } });
- });
- } finally {
- await rm(tmp, { recursive: true, force: true });
- }
- assert.deepEqual(shotParams.clip, { x: 100, y: 50, width: 400, height: 300, scale: 0.5 });
-});
-
-test("captureScreenshot custom clip with explicit scale wins over the default", async () => {
- const tmp = await mkdtemp(join(tmpdir(), "shot-"));
- const path = join(tmp, "shot.png");
- let shotParams;
- try {
- await withOverrides({
- cdpOverride: async (method, params) => {
- if (method === "Runtime.evaluate") {
- if (params.expression.includes("devicePixelRatio")) return { result: { value: 2 } };
- return { result: { value: JSON.stringify({ url: "u", title: "t", w: 1291, h: 805, sx: 0, sy: 0, pw: 1291, ph: 4000 }) } };
- }
- if (method === "Page.captureScreenshot") {
- shotParams = params;
- return { data: Buffer.from("png").toString("base64") };
- }
- return {};
- },
- writeFile: async () => {}
- }, async () => {
- await helpers.captureScreenshot(path, { clip: { x: 0, y: 0, width: 200, height: 200, scale: 0.25 } });
- });
- } finally {
- await rm(tmp, { recursive: true, force: true });
- }
- assert.equal(shotParams.clip.scale, 0.25);
-});
-
-test("captureScreenshot raw:true keeps the physical-pixel behavior", async () => {
- const tmp = await mkdtemp(join(tmpdir(), "shot-"));
- const path = join(tmp, "shot.png");
- let shotParams;
- try {
- await withOverrides({
- cdpOverride: async (method, params) => {
- if (method === "Page.captureScreenshot") {
- shotParams = params;
- return { data: Buffer.from("png").toString("base64") };
- }
- return {};
- },
- writeFile: async () => {}
- }, async () => {
- await helpers.captureScreenshot(path, { raw: true });
- });
- } finally {
- await rm(tmp, { recursive: true, force: true });
- }
- assert.equal(shotParams.clip, undefined);
- assert.equal(shotParams.captureBeyondViewport, false);
-});
-
-function withRefEntry(refId, backendNodeId, role, name) {
- browserRefMap.clear();
- browserRefMap.add(String(refId), backendNodeId, role, name);
- return () => browserRefMap.clear();
-}
-
-test("fillInput on @ref resolves to objectId and uses callFunctionOn + Input.insertText", async () => {
- const calls = [];
- const restoreRef = withRefEntry("42", 42, "textbox", "Username");
- try {
- await withOverrides({
- cdpOverride: async (method, params, sessionId) => {
- calls.push([method, params, sessionId]);
- if (method === "DOM.resolveNode") return { object: { objectId: "obj-42" } };
- return {};
- }
- }, async () => {
- await helpers.fillInput("@42", "hello");
- });
- } finally {
- restoreRef();
- }
-
- assert.ok(calls.some(([m]) => m === "DOM.resolveNode"), "must resolve ref via DOM.resolveNode");
- assert.equal(calls.some(([m, p]) => m === "Runtime.evaluate" && /querySelector/.test(p.expression || "")), false, "must not fall back to querySelector");
- const callFnOn = calls.filter(([m]) => m === "Runtime.callFunctionOn");
- assert.ok(callFnOn.every(([, p]) => p.objectId === "obj-42"), "callFunctionOn must target the resolved objectId");
- assert.ok(callFnOn.some(([, p]) => /this\.focus\(\)/.test(p.functionDeclaration)), "must focus the element");
- assert.equal(callFnOn.some(([, p]) => /setSelectionRange/.test(p.functionDeclaration)), false, "must not use setSelectionRange");
- assert.ok(callFnOn.some(([, p]) => /this\.value\s*=\s*''/.test(p.functionDeclaration)), "must clear via native value setter");
- assert.ok(callFnOn.some(([, p]) => /dispatchEvent\(new Event\('input'/.test(p.functionDeclaration) && /'change'/.test(p.functionDeclaration)), "must fire input/change events");
- assert.ok(calls.some(([m, p]) => m === "Input.insertText" && p.text === "hello"), "must insert text via CDP");
- assert.equal(calls.some(([m, p]) => m === "Input.dispatchKeyEvent" && p.key === "Backspace"), false, "must not clear by pressing Backspace");
-});
-
-test("fillInput with clearFirst:false on @ref skips the clear+Backspace path", async () => {
- const calls = [];
- const restoreRef = withRefEntry("7", 7, "textbox", "Email");
- try {
- await withOverrides({
- cdpOverride: async (method, params) => {
- calls.push([method, params]);
- if (method === "DOM.resolveNode") return { object: { objectId: "obj-7" } };
- return {};
- }
- }, async () => {
- await helpers.fillInput("@7", "abc", { clearFirst: false });
- });
- } finally {
- restoreRef();
- }
- assert.equal(calls.some(([m, p]) => m === "Input.dispatchKeyEvent" && p.key === "Backspace"), false);
- assert.equal(calls.some(([, p]) => p && typeof p.functionDeclaration === "string" && /setSelectionRange/.test(p.functionDeclaration)), false);
- assert.ok(calls.some(([m, p]) => m === "Input.insertText" && p.text === "abc"));
-});
-
-test("dispatchKey on @ref focuses via objectId and dispatches a synthetic KeyboardEvent", async () => {
- const calls = [];
- const restoreRef = withRefEntry("9", 9, "textbox", "Search");
- try {
- await withOverrides({
- cdpOverride: async (method, params) => {
- calls.push([method, params]);
- if (method === "DOM.resolveNode") return { object: { objectId: "obj-9" } };
- return {};
- }
- }, async () => {
- await helpers.dispatchKey("@9", "Enter");
- });
- } finally {
- restoreRef();
- }
- assert.equal(calls.some(([m, p]) => m === "Runtime.evaluate" && /querySelector/.test(p.expression || "")), false);
- const callFnOn = calls.filter(([m]) => m === "Runtime.callFunctionOn");
- assert.equal(callFnOn.length, 1);
- assert.equal(callFnOn[0][1].objectId, "obj-9");
- assert.match(callFnOn[0][1].functionDeclaration, /this\.focus\(\)/);
- assert.match(callFnOn[0][1].functionDeclaration, /new KeyboardEvent/);
- assert.deepEqual(callFnOn[0][1].arguments, [
- { value: 13 },
- { value: "Enter" },
- { value: "Enter" },
- { value: "keypress" }
- ]);
-});
-
-test("fillInput routes xpath= selectors through the unified resolver", async () => {
- const calls = [];
- await withOverrides({
- cdpOverride: async (method, params) => {
- calls.push([method, params]);
- if (method === "Runtime.evaluate") return { result: { objectId: "obj-xp" } };
- return {};
- }
- }, async () => {
- await helpers.fillInput("xpath=//input[@name='email']", "[email protected]");
- });
- assert.ok(calls.some(([m, p]) => m === "Runtime.evaluate" && /document\.evaluate/.test(p.expression || "")), "xpath must resolve via document.evaluate, not querySelector");
- assert.ok(calls.filter(([m]) => m === "Runtime.callFunctionOn").every(([, p]) => p.objectId === "obj-xp"));
- assert.ok(calls.some(([m, p]) => m === "Input.insertText" && p.text === "[email protected]"));
-});
-
-test("fillInput routes loc=css: selectors through the unified resolver", async () => {
- const calls = [];
- await withOverrides({
- cdpOverride: async (method, params) => {
- calls.push([method, params]);
- if (method === "Runtime.evaluate") {
- return /querySelectorAll/.test(params.expression) ? { result: { value: 1 } } : { result: { objectId: "obj-loc" } };
- }
- return {};
- }
- }, async () => {
- await helpers.fillInput("loc=css:input[name=\"email\"]", "[email protected]");
- });
- assert.ok(calls.some(([m, p]) => m === "Runtime.evaluate" && /querySelectorAll/.test(p.expression || "")), "loc=css must check uniqueness via querySelectorAll");
- assert.ok(calls.some(([m, p]) => m === "Input.insertText" && p.text === "[email protected]"));
-});
-
-test("dispatchKey routes xpath= selectors through the unified resolver", async () => {
- const calls = [];
- await withOverrides({
- cdpOverride: async (method, params) => {
- calls.push([method, params]);
- if (method === "Runtime.evaluate") return { result: { objectId: "obj-xp" } };
- return {};
- }
- }, async () => {
- await helpers.dispatchKey("xpath=//button", "Enter");
- });
- assert.ok(calls.some(([m, p]) => m === "Runtime.evaluate" && /document\.evaluate/.test(p.expression || "")));
- const callFnOn = calls.find(([m]) => m === "Runtime.callFunctionOn");
- assert.ok(callFnOn, "must dispatch the KeyboardEvent via callFunctionOn on the resolved element");
- assert.match(callFnOn[1].functionDeclaration, /new KeyboardEvent/);
-});
-
-test("waitForElement routes xpath= selectors through the unified resolver", async () => {
- const calls = [];
- await withOverrides({
- cdpOverride: async (method, params) => {
- calls.push([method, params]);
- if (method === "Runtime.evaluate") return { result: { objectId: "obj-xp" } };
- return {};
- },
- now: (() => {
- let value = 1000;
- return () => (value += 1);
- })(),
- sleep: async () => {}
- }, async () => {
- assert.equal(await helpers.waitForElement("xpath=//button"), true);
- });
- assert.ok(calls.some(([m, p]) => m === "Runtime.evaluate" && /document\.evaluate/.test(p.expression || "")), "xpath must resolve via document.evaluate, not querySelector");
-});
-
-test("waitForElement on @ref polls resolveElementObjectId and returns true when it succeeds", async () => {
- const calls = [];
- const restoreRef = withRefEntry("12", 12, "button", "Save");
- try {
- await withOverrides({
- cdpOverride: async (method, params) => {
- calls.push([method, params]);
- if (method === "DOM.resolveNode") return { object: { objectId: "obj-12" } };
- return {};
- },
- now: (() => {
- let value = 1000;
- return () => (value += 1);
- })(),
- sleep: async () => {}
- }, async () => {
- assert.equal(await helpers.waitForElement("@12"), true);
- });
- } finally {
- restoreRef();
- }
- assert.equal(calls.some(([m, p]) => m === "Runtime.evaluate" && /querySelector/.test(p.expression || "")), false);
- assert.ok(calls.some(([m]) => m === "DOM.resolveNode"));
-});
-
-test("waitForElement on @ref with visible:true runs checkVisibility via callFunctionOn", async () => {
- const calls = [];
- const restoreRef = withRefEntry("13", 13, "button", "Save");
- try {
- await withOverrides({
- cdpOverride: async (method, params) => {
- calls.push([method, params]);
- if (method === "DOM.resolveNode") return { object: { objectId: "obj-13" } };
- if (method === "Runtime.callFunctionOn") return { result: { value: true } };
- return {};
- },
- now: (() => {
- let value = 1000;
- return () => (value += 1);
- })(),
- sleep: async () => {}
- }, async () => {
- assert.equal(await helpers.waitForElement("@13", { visible: true }), true);
- });
- } finally {
- restoreRef();
- }
- const callFnOn = calls.find(([m]) => m === "Runtime.callFunctionOn");
- assert.ok(callFnOn);
- assert.match(callFnOn[1].functionDeclaration, /checkVisibility/);
- assert.match(callFnOn[1].functionDeclaration, /getComputedStyle/);
-});
-
-test("waitForElement on unknown @ref returns false after timeout without falling back to querySelector", async () => {
- browserRefMap.clear();
- const calls = [];
- let nowValue = 0;
- const previousEgo = globalThis.ego;
- globalThis.ego = {
- sendCDPMessage() {},
- snapshot: async () => ({ refs: [], content: "" })
- };
- try {
- await withOverrides({
- cdpOverride: async (method, params) => {
- calls.push([method, params]);
- return {};
- },
- now: () => (nowValue += 5000),
- sleep: async () => {}
- }, async () => {
- assert.equal(await helpers.waitForElement("@999", { timeout: 1 }), false);
- });
- } finally {
- browserRefMap.clear();
- if (previousEgo === undefined) delete globalThis.ego; else globalThis.ego = previousEgo;
- }
- assert.equal(calls.some(([m, p]) => m === "Runtime.evaluate" && /querySelector/.test(p.expression || "")), false);
-});
-
-test("elementEval passes the element as the first argument and forwards user args after it", async () => {
- const calls = [];
- await withOverrides({
- cdpOverride: async (method, params) => {
- calls.push([method, params]);
- if (method === "Runtime.evaluate") {
- return { result: { objectId: "OID-EL" } };
- }
- if (method === "Runtime.callFunctionOn") {
- return { result: { value: "hello" } };
- }
- return {};
- }
- }, async () => {
- const arrowNoArgs = await helpers.elementEval("#status", (el) => el.textContent);
- assert.equal(arrowNoArgs, "hello");
- const arrowWithArg = await helpers.elementEval("#input", (el, prop) => el[prop], "value");
- assert.equal(arrowWithArg, "hello");
- await helpers.elementEval("#btn", function () { this.click(); });
- });
-
- const callFnOnCalls = calls.filter(([m]) => m === "Runtime.callFunctionOn");
- assert.equal(callFnOnCalls.length, 3);
-
- const [, noArgsParams] = callFnOnCalls[0];
- assert.deepEqual(noArgsParams.arguments, [{ objectId: "OID-EL" }]);
-
- const [, withArgParams] = callFnOnCalls[1];
- assert.deepEqual(withArgParams.arguments, [{ objectId: "OID-EL" }, { value: "value" }]);
-
- const [, legacyThisParams] = callFnOnCalls[2];
- assert.deepEqual(legacyThisParams.arguments, [{ objectId: "OID-EL" }]);
- assert.equal(legacyThisParams.objectId, "OID-EL");
- assert.match(legacyThisParams.functionDeclaration, /^function/);
-});
-
-test("elementEval regression: arrow-style el.click() no longer fails because el is now supplied", async () => {
- const calls = [];
- await withOverrides({
- cdpOverride: async (method) => {
- if (method === "Runtime.evaluate") {
- return { result: { objectId: "OID-BUTTON" } };
- }
- if (method === "Runtime.callFunctionOn") {
- calls.push("callFunctionOn");
- return { result: { value: null } };
- }
- return {};
- }
- }, async () => {
- await helpers.elementEval("#submit", (el) => el.click());
- });
- assert.equal(calls.length, 1);
-});
diff --git a/package/ego-browser/test/learn-context.test.js b/package/ego-browser/test/learn-context.test.js
deleted file mode 100644
index ab4989f..0000000
--- a/package/ego-browser/test/learn-context.test.js
+++ /dev/null
@@ -1,125 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { pathToFileURL, fileURLToPath } from "node:url";
-import { dirname, join } from "node:path";
-import { loadLearnedContext } from "../dist/src/learning/index.js";
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-const LEARNINGS_ROOT = join(__dirname, "..", "..", "..", "skills", "ego-browser", "learnings");
-const LEARNING_PACK_ROOT = join(__dirname, "..", "..", "..", "skills", "ego-browser", "learnings");
-
-async function withTempLearningRoot(fn) {
- const root = await mkdtemp(join(tmpdir(), "ego-browser-learn-context-"));
- try {
- return await fn(root);
- } finally {
- await rm(root, { recursive: true, force: true });
- }
-}
-
-async function importLearningPackModule(relativePath) {
- return import(pathToFileURL(join(LEARNING_PACK_ROOT, relativePath)).href);
-}
-
-test("learnContext matches x.com and returns tools with knowledge", async () => {
- const ctx = await loadLearnedContext("https://x.com/home", { root: LEARNINGS_ROOT });
- assert.ok(ctx.exists);
- assert.equal(ctx.siteId, "x-com");
- assert.equal(ctx.siteName, "X (Twitter)");
- assert.ok(ctx.knowledge.length > 0);
- assert.ok(ctx.tools.some((t) => t.toolName === "get_timeline_posts"));
- assert.ok(ctx.tools.some((t) => t.toolType === "browser"));
-});
-
-test("learnContext matches google.com and returns search tools", async () => {
- const ctx = await loadLearnedContext("https://www.google.com/search?q=test", { root: LEARNINGS_ROOT });
- assert.ok(ctx.exists);
- assert.equal(ctx.siteId, "google");
- assert.ok(ctx.tools.some((t) => t.toolName === "search_and_extract"));
- assert.ok(ctx.tools.some((t) => t.toolName === "get_autocomplete_suggestions"));
-});
-
-test("learnContext matches github.com and returns repo tools", async () => {
- const ctx = await loadLearnedContext("https://github.com/org/repo", { root: LEARNINGS_ROOT });
- assert.ok(ctx.exists);
- assert.equal(ctx.siteId, "github");
- assert.ok(ctx.tools.some((t) => t.toolName === "search_repos"));
- assert.ok(ctx.tools.some((t) => t.toolName === "get_open_issues"));
-});
-
-test("learnContext returns empty context for unknown domain", async () => {
- const ctx = await loadLearnedContext("https://unknown-random-site.org", { root: LEARNINGS_ROOT });
- assert.ok(!ctx.exists);
- assert.equal(ctx.siteId, null);
- assert.deepEqual(ctx.tools, []);
- assert.deepEqual(ctx.knowledge, []);
-});
-
-test("learnContext does not read traversal note paths", async () => {
- await withTempLearningRoot(async (root) => {
- const site = join(root, "example");
- await mkdir(site, { recursive: true });
- await writeFile(join(root, "secret.md"), "secret\n");
- await writeFile(join(site, "manifest.json"), JSON.stringify({
- id: "example",
- name: "Example",
- domains: ["example.com"],
- notes: ["../../secret.md"],
- nodeTools: {},
- browserTools: {}
- }));
-
- const ctx = await loadLearnedContext("https://example.com", { root });
-
- assert.equal(ctx.exists, true);
- assert.deepEqual(ctx.knowledge, []);
- });
-});
-
-test("learning node tools sanitize numeric limits before page evaluation", async () => {
- const calls = [];
- const ctx = {
- openOrReuseTab: async () => {},
- waitForLoad: async () => {},
- js: async (expression) => {
- calls.push(expression);
- return [];
- }
- };
- const injected = "1);globalThis.pwned=1;//";
-
- const { searchRepos } = await importLearningPackModule("github/tools/search-repos.js");
- await searchRepos(ctx, { query: "agent", maxResults: injected });
- const { searchAndExtract } = await importLearningPackModule("google/tools/search-extract.js");
- await searchAndExtract(ctx, { query: "agent", maxResults: injected });
- const { getTimelinePosts } = await importLearningPackModule("x-com/tools/timeline.js");
- await getTimelinePosts(ctx, { maxPosts: injected });
-
- assert.equal(calls.length, 3);
- assert.ok(calls[0].includes("slice(0, 25)"));
- assert.ok(calls[1].includes("slice(0, 10)"));
- assert.ok(calls[2].includes("slice(0, 50)"));
- assert.ok(calls.every((expression) => !expression.includes("globalThis.pwned")));
-});
-
-test("GitHub issue tool rejects unsafe owner and repo path segments", async () => {
- const { getOpenIssues } = await importLearningPackModule("github/tools/open-issues.js");
- const ctx = {
- openOrReuseTab: async () => {
- throw new Error("navigation should not run");
- },
- waitForLoad: async () => {},
- js: async () => []
- };
-
- await assert.rejects(
- () => getOpenIssues(ctx, { owner: "org/path", repo: "repo" }),
- /valid GitHub owner and repo are required/
- );
- await assert.rejects(
- () => getOpenIssues(ctx, { owner: "org", repo: "repo/issues?q=x" }),
- /valid GitHub owner and repo are required/
- );
-});
diff --git a/package/ego-browser/test/nav-and-driver.test.js b/package/ego-browser/test/nav-and-driver.test.js
deleted file mode 100644
index 0749ebf..0000000
--- a/package/ego-browser/test/nav-and-driver.test.js
+++ /dev/null
@@ -1,498 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-
-import * as helpers from "../dist/src/helpers.js";
-import { browserRefMap } from "../dist/src/ref-state.js";
-
-function withBrowserRuntime(runtime, fn) {
- const previous = globalThis.ego;
- globalThis.ego = runtime;
- return Promise.resolve()
- .then(fn)
- .finally(() => {
- if (previous === undefined) {
- delete globalThis.ego;
- } else {
- globalThis.ego = previous;
- }
- });
-}
-
-function withOverrides(overrides, fn) {
- const restore = helpers.__testing.setOverrides(overrides);
- return Promise.resolve()
- .then(fn)
- .finally(restore);
-}
-
-const sampleTabs = [
- { index: 0, targetId: "t-chrome", url: "chrome://settings", title: "Settings", active: false },
- { index: 1, targetId: "t-page", url: "https://example.com", title: "Example", active: true },
- { index: 2, targetId: "t-blank", url: "about:blank", title: "", active: false }
-];
-
-test("listTabs filters internal targets when includeChrome is false", async () => {
- await withBrowserRuntime({
- sendCDPMessage() {},
- listTabs: async () => ({ tabs: sampleTabs })
- }, async () => {
- const all = await helpers.listTabs();
- assert.deepEqual(all.map((tab) => tab.targetId), ["t-chrome", "t-page", "t-blank"]);
-
- const real = await helpers.listTabs({ includeChrome: false });
- assert.deepEqual(real.map((tab) => tab.targetId), ["t-page"]);
- });
-});
-
-test("currentTab returns active tab and throws on empty list", async () => {
- await withBrowserRuntime({
- sendCDPMessage() {},
- listTabs: async () => ({ tabs: sampleTabs })
- }, async () => {
- assert.deepEqual(await helpers.currentTab(), {
- targetId: "t-page",
- url: "https://example.com",
- title: "Example"
- });
- });
-
- await withBrowserRuntime({
- sendCDPMessage() {},
- listTabs: async () => ({ tabs: [] })
- }, async () => {
- await assert.rejects(() => helpers.currentTab(), /no active browser tab/);
- });
-});
-
-test("switchTab accepts target id or tab-like object and calls Target.activateTarget", async () => {
- const calls = [];
- await withOverrides({
- cdpOverride: async (method, params) => {
- calls.push([method, params]);
- return {};
- }
- }, async () => {
- assert.equal(await helpers.switchTab("t-page"), "t-page");
- assert.equal(await helpers.switchTab({ targetId: "t-blank" }), "t-blank");
- });
- assert.deepEqual(calls, [
- ["Target.activateTarget", { targetId: "t-page" }],
- ["Target.activateTarget", { targetId: "t-blank" }]
- ]);
-});
-
-test("newTab calls createTab and returns the new target id", async () => {
- const created = [];
- await withBrowserRuntime({
- sendCDPMessage() {},
- createTab: async (url) => {
- created.push(url);
- return { targetId: `tab:${url}` };
- }
- }, async () => {
- assert.equal(await helpers.newTab("https://example.com"), "tab:https://example.com");
- assert.equal(await helpers.newTab(), "tab:about:blank");
- });
- assert.deepEqual(created, ["https://example.com", "about:blank"]);
-});
-
-test("openOrReuseTab switches to a matching existing tab", async () => {
- const cdpCalls = [];
- await withBrowserRuntime({
- sendCDPMessage() {},
- listTabs: async () => ({ tabs: sampleTabs })
- }, async () => {
- await withOverrides({
- cdpOverride: async (method, params) => {
- cdpCalls.push([method, params]);
- return {};
- }
- }, async () => {
- const tab = await helpers.openOrReuseTab("https://example.com/", { match: "origin+path", wait: false });
- assert.equal(tab.targetId, "t-page");
- assert.equal(tab.reused, true);
- assert.equal(tab.active, true);
- });
- });
- assert.deepEqual(cdpCalls, [["Target.activateTarget", { targetId: "t-page" }]]);
-});
-
-test("openOrReuseTab opens a new tab and waits by default", async () => {
- const created = [];
- const cdpCalls = [];
- await withBrowserRuntime({
- sendCDPMessage() {},
- listTabs: async () => ({ tabs: [] }),
- createTab: async (url) => {
- created.push(url);
- return { targetId: "new-tab" };
- }
- }, async () => {
- await withOverrides({
- cdpOverride: async (method, params) => {
- cdpCalls.push([method, params]);
- if (method === "Page.getFrameTree") return { frameTree: { frame: { url: "https://openai.com" } } };
- if (method === "Runtime.evaluate") return { result: { value: "complete" } };
- return {};
- }
- }, async () => {
- const tab = await helpers.openOrReuseTab("https://openai.com", { timeout: 1 });
- assert.deepEqual(tab, {
- targetId: "new-tab",
- url: "https://openai.com",
- title: "",
- active: true,
- reused: false
- });
- });
- });
- assert.deepEqual(created, ["https://openai.com"]);
- assert.equal(cdpCalls.some(([method]) => method === "Page.getFrameTree"), true);
- assert.equal(cdpCalls.some(([method]) => method === "Runtime.evaluate"), true);
-});
-
-test("gotoAndWait navigates, waits for load, and settles", async () => {
- const calls = [];
- await withOverrides({
- sleep: async (ms) => calls.push(["sleep", ms]),
- now: (() => {
- let now = 0;
- return () => {
- now += 100;
- return now;
- };
- })(),
- cdpOverride: async (method, params) => {
- calls.push([method, params]);
- if (method === "Page.navigate") return { frameId: "frame-1" };
- if (method === "Page.getFrameTree") return { frameTree: { frame: { url: "https://example.com" } } };
- if (method === "Runtime.evaluate") return { result: { value: "complete" } };
- return {};
- }
- }, async () => {
- const result = await helpers.gotoAndWait("https://example.com", { timeout: 1, settle: 0.25 });
- assert.deepEqual(result, { navigation: { frameId: "frame-1" }, loaded: true });
- });
- assert.deepEqual(calls.at(0), ["Page.navigate", { url: "https://example.com" }]);
- assert.deepEqual(calls.at(-1), ["sleep", 250]);
-});
-
-test("ensureRealTab keeps current page when not internal", async () => {
- const calls = [];
- await withBrowserRuntime({
- sendCDPMessage() {},
- listTabs: async () => ({ tabs: sampleTabs })
- }, async () => {
- await withOverrides({
- cdpOverride: async (method, params) => {
- calls.push([method, params]);
- return {};
- }
- }, async () => {
- const result = await helpers.ensureRealTab();
- assert.deepEqual(result, { targetId: "t-page", url: "https://example.com", title: "Example" });
- });
- });
- assert.equal(calls.length, 0);
-});
-
-test("ensureRealTab switches to first non-internal tab when current is chrome://", async () => {
- const tabs = [
- { index: 0, targetId: "t-chrome", url: "chrome://newtab", title: "New", active: true },
- { index: 1, targetId: "t-real", url: "https://example.com", title: "Example", active: false }
- ];
- const calls = [];
- await withBrowserRuntime({
- sendCDPMessage() {},
- listTabs: async () => ({ tabs })
- }, async () => {
- await withOverrides({
- cdpOverride: async (method, params) => {
- calls.push([method, params]);
- return {};
- }
- }, async () => {
- const result = await helpers.ensureRealTab();
- assert.equal(result.targetId, "t-real");
- });
- });
- assert.deepEqual(calls, [["Target.activateTarget", { targetId: "t-real" }]]);
-});
-
-test("ensureRealTab returns null when no real tabs exist", async () => {
- await withBrowserRuntime({
- sendCDPMessage() {},
- listTabs: async () => ({ tabs: [{ targetId: "t-chrome", url: "chrome://newtab", title: "", active: true }] })
- }, async () => {
- assert.equal(await helpers.ensureRealTab(), null);
- });
-});
-
-test("iframeTarget returns matching iframe target id or null", async () => {
- await withOverrides({
- cdpOverride: async () => ({
- targetInfos: [
- { type: "page", url: "https://example.com", targetId: "page-1" },
- { type: "iframe", url: "https://ads.example.com/banner", targetId: "iframe-1" },
- { type: "iframe", url: "https://example.com/widget", targetId: "iframe-2" }
- ]
- })
- }, async () => {
- assert.equal(await helpers.iframeTarget("ads.example"), "iframe-1");
- assert.equal(await helpers.iframeTarget("widget"), "iframe-2");
- assert.equal(await helpers.iframeTarget("missing"), null);
- });
-});
-
-test("snapshotText returns content with full-page action defaults", async () => {
- const snapshots = [];
- await withBrowserRuntime({
- sendCDPMessage() {},
- snapshot: async (options) => {
- snapshots.push(options);
- return { content: "root\n button \"Save\"", refs: [] };
- }
- }, async () => {
- assert.equal(await helpers.snapshotText(), "root\n button \"Save\"");
- });
- assert.deepEqual(snapshots, [{ scope: "full_page", includeActionMarks: true, includeStableLocator: true }]);
-});
-
-test("snapshotText forwards explicit only_within_viewport scope", async () => {
- const snapshots = [];
- await withBrowserRuntime({
- sendCDPMessage() {},
- snapshot: async (options) => {
- snapshots.push(options);
- return { content: "root", refs: [] };
- }
- }, async () => {
- assert.equal(await helpers.snapshotText({ scope: "only_within_viewport" }), "root");
- });
- assert.deepEqual(snapshots, [{ scope: "only_within_viewport", includeActionMarks: true, includeStableLocator: true }]);
-});
-
-test("waitForLoad returns true once readyState is complete", async () => {
- let calls = 0;
- await withOverrides({
- cdpOverride: async (method) => {
- if (method === "Page.getFrameTree") {
- return { frameTree: { frame: { url: "https://example.com/" } } };
- }
- calls += 1;
- return { result: { value: calls >= 2 ? "complete" : "loading" } };
- },
- now: (() => {
- let value = 0;
- return () => (value += 50);
- })(),
- sleep: async () => {}
- }, async () => {
- assert.equal(await helpers.waitForLoad({ timeout: 1 }), true);
- });
- assert.ok(calls >= 2);
-});
-
-test("waitForLoad returns false when timeout elapses", async () => {
- await withOverrides({
- cdpOverride: async () => ({ result: { value: "loading" } }),
- now: (() => {
- let value = 0;
- return () => (value += 500);
- })(),
- sleep: async () => {}
- }, async () => {
- assert.equal(await helpers.waitForLoad({ timeout: 1 }), false);
- });
-});
-
-test("waitForNetworkIdle returns false when timeout elapses without idle window", async () => {
- await withBrowserRuntime({ sendCDPMessage() {} }, async () => {
- await withOverrides({
- now: (() => {
- let value = 0;
- return () => (value += 5000);
- })(),
- sleep: async () => {}
- }, async () => {
- assert.equal(await helpers.waitForNetworkIdle({ timeout: 1, idleMs: 100 }), false);
- });
- });
-});
-
-test("uploadFile resolves the selector via the unified resolver and sets file inputs by objectId", async () => {
- const calls = [];
- await withOverrides({
- cdpOverride: async (method, params) => {
- calls.push([method, params]);
- if (method === "Runtime.evaluate") return { result: { objectId: "obj-file" } };
- return {};
- }
- }, async () => {
- await helpers.uploadFile("input#file", "/tmp/a.png");
- await helpers.uploadFile("input#file", ["/tmp/a.png", "/tmp/b.png"]);
- });
- assert.equal(calls.some(([m]) => m === "DOM.getDocument"), false, "must not walk DOM via DOM.getDocument");
- assert.deepEqual(calls.at(-1), ["DOM.setFileInputFiles", { files: ["/tmp/a.png", "/tmp/b.png"], objectId: "obj-file" }]);
-});
-
-test("uploadFile throws when selector matches no element", async () => {
- await withOverrides({
- cdpOverride: async (method) => {
- if (method === "Runtime.evaluate") return { result: {} };
- return {};
- }
- }, async () => {
- await assert.rejects(() => helpers.uploadFile("input#missing", "/tmp/a.png"), /Element not found: input#missing/);
- });
-});
-
-test("uploadFile routes xpath= selectors through the unified resolver", async () => {
- const calls = [];
- await withOverrides({
- cdpOverride: async (method, params) => {
- calls.push([method, params]);
- if (method === "Runtime.evaluate") return { result: { objectId: "obj-xp" } };
- return {};
- }
- }, async () => {
- await helpers.uploadFile("xpath=//input[@type='file']", "/tmp/a.png");
- });
- assert.ok(calls.some(([m, p]) => m === "Runtime.evaluate" && /document\.evaluate/.test(p.expression || "")), "xpath must resolve via document.evaluate, not querySelector");
- assert.deepEqual(calls.at(-1), ["DOM.setFileInputFiles", { files: ["/tmp/a.png"], objectId: "obj-xp" }]);
-});
-
-test("uploadFile on @ref resolves to objectId and calls DOM.setFileInputFiles with objectId", async () => {
- browserRefMap.clear();
- browserRefMap.add("57", 57, "textbox", "Resume");
- const calls = [];
- try {
- await withOverrides({
- cdpOverride: async (method, params, sessionId) => {
- calls.push([method, params, sessionId]);
- if (method === "DOM.resolveNode") return { object: { objectId: "obj-57" } };
- return {};
- }
- }, async () => {
- await helpers.uploadFile("@57", "/tmp/cv.pdf");
- await helpers.uploadFile("@57", ["/tmp/a.pdf", "/tmp/b.pdf"]);
- });
- } finally {
- browserRefMap.clear();
- }
- assert.equal(calls.some(([m]) => m === "DOM.getDocument"), false, "must not walk DOM via DOM.getDocument");
- assert.equal(calls.some(([m]) => m === "DOM.querySelector"), false, "must not querySelector on @ref");
- const setCalls = calls.filter(([m]) => m === "DOM.setFileInputFiles");
- assert.equal(setCalls.length, 2);
- assert.deepEqual(setCalls[0][1], { files: ["/tmp/cv.pdf"], objectId: "obj-57" });
- assert.deepEqual(setCalls[1][1], { files: ["/tmp/a.pdf", "/tmp/b.pdf"], objectId: "obj-57" });
-});
-
-test("dragMouse requires at least two points", async () => {
- await assert.rejects(() => helpers.dragMouse([{ x: 1, y: 2 }]), /at least two points/);
-});
-
-function withEgoAndOverrides(egoMock, overrides, fn) {
- return withBrowserRuntime(egoMock, () => withOverrides(overrides, fn));
-}
-
-function makeMockCdp() {
- return async (method) => {
- if (method === "DOM.getDocument") return { root: { nodeId: 1 } };
- if (method === "DOM.querySelector") return { nodeId: 0 };
- return {};
- };
-}
-
-test("click calls animationHighlightMouseToPosition with resolved coordinates", async () => {
- const calls = [];
- const ego = { animationHighlightMouseToPosition: (x, y) => calls.push({ x, y }) };
- await withEgoAndOverrides(ego, { cdpOverride: makeMockCdp() }, async () => {
- await helpers.click({ x: 42, y: 99 });
- });
- assert.deepEqual(calls, [{ x: 42, y: 99 }]);
-});
-
-test("click calls setAgentTaskState when label is provided", async () => {
- const highlights = [];
- const states = [];
- const ego = {
- animationHighlightMouseToPosition: (x, y) => highlights.push({ x, y }),
- setAgentTaskState: (s) => states.push(s)
- };
- await withEgoAndOverrides(ego, { cdpOverride: makeMockCdp() }, async () => {
- await helpers.click({ x: 10, y: 20 }, { label: "submit form" });
- });
- assert.deepEqual(highlights, [{ x: 10, y: 20 }]);
- assert.deepEqual(states, ["submit form"]);
-});
-
-test("click does not call setAgentTaskState when label is omitted", async () => {
- const states = [];
- const ego = {
- animationHighlightMouseToPosition: () => {},
- setAgentTaskState: (s) => states.push(s)
- };
- await withEgoAndOverrides(ego, { cdpOverride: makeMockCdp() }, async () => {
- await helpers.click({ x: 10, y: 20 });
- });
- assert.deepEqual(states, []);
-});
-
-test("hover calls animationHighlightMouseToPosition and setAgentTaskState", async () => {
- const highlights = [];
- const states = [];
- const ego = {
- animationHighlightMouseToPosition: (x, y) => highlights.push({ x, y }),
- setAgentTaskState: (s) => states.push(s)
- };
- await withEgoAndOverrides(ego, { cdpOverride: makeMockCdp() }, async () => {
- await helpers.hover({ x: 5, y: 15 }, { label: "hover menu" });
- });
- assert.deepEqual(highlights, [{ x: 5, y: 15 }]);
- assert.deepEqual(states, ["hover menu"]);
-});
-
-test("dragMouse calls animationHighlightMouseToPosition with the first point", async () => {
- const highlights = [];
- const states = [];
- const ego = {
- animationHighlightMouseToPosition: (x, y) => highlights.push({ x, y }),
- setAgentTaskState: (s) => states.push(s)
- };
- await withEgoAndOverrides(ego, { cdpOverride: makeMockCdp() }, async () => {
- await helpers.dragMouse([{ x: 1, y: 2 }, { x: 3, y: 4 }], { label: "drag card" });
- });
- assert.deepEqual(highlights, [{ x: 1, y: 2 }]);
- assert.deepEqual(states, ["drag card"]);
-});
-
-test("maybeHighlight is a no-op when ego is absent", async () => {
- await withOverrides({ cdpOverride: makeMockCdp() }, async () => {
- await assert.doesNotReject(() => helpers.click({ x: 0, y: 0 }, { label: "test" }));
- });
-});
-
-test("dragMouse presses, moves through path, and releases at the last point", async () => {
- const events = [];
- await withOverrides({
- cdpOverride: async (method, params) => {
- if (method === "Input.dispatchMouseEvent") {
- events.push({ type: params.type, x: params.x, y: params.y, button: params.button });
- }
- return {};
- }
- }, async () => {
- await helpers.dragMouse([
- { x: 10, y: 20 },
- { x: 30, y: 40 },
- { x: 50, y: 60 }
- ]);
- });
- assert.deepEqual(events, [
- { type: "mousePressed", x: 10, y: 20, button: "left" },
- { type: "mouseMoved", x: 30, y: 40, button: "left" },
- { type: "mouseMoved", x: 50, y: 60, button: "left" },
- { type: "mouseReleased", x: 50, y: 60, button: "left" }
- ]);
-});
diff --git a/package/ego-browser/test/run.test.js b/package/ego-browser/test/run.test.js
deleted file mode 100644
index 41e8f6f..0000000
--- a/package/ego-browser/test/run.test.js
+++ /dev/null
@@ -1,130 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-
-import { installEgoSdk } from "../dist/src/index.js";
-import { executionContext, runMain } from "../dist/src/run.js";
-
-function output() {
- let text = "";
- return {
- stream: { write: (chunk) => { text += chunk; } },
- text: () => text
- };
-}
-
-function services(overrides = {}) {
- return {
- resetConnection: async () => {},
- printUpdateBanner: () => {},
- runDoctor: async () => 0,
- ...overrides
- };
-}
-
-test("stdin JavaScript executes with camelCase helpers in scope", async () => {
- const out = output();
- const code = await runMain({
- argv: [],
- stdinText: "cliLog(typeof newTab, typeof new_tab, typeof pageInfo, typeof page_info, typeof runDoctor, typeof run_doctor)",
- stdout: out.stream,
- stderr: output().stream,
- services: services()
- });
-
- assert.equal(code, 0);
- assert.equal(out.text(), "function undefined function undefined undefined undefined\n");
-});
-
-test("non-stdin arguments are rejected with usage", async () => {
- const err = output();
- const code = await runMain({
- argv: ["-c", "cliLog('old path')"],
- stdinText: "cliLog('ignored')",
- stdout: output().stream,
- stderr: err.stream,
- services: services()
- });
-
- assert.equal(code, 2);
- assert.match(err.text(), /ego-browser <<'JS'/);
-});
-
-test("runMain --reload uses resetConnection and prints the browser reset message", async () => {
- const calls = [];
- const out = output();
- const code = await runMain({
- argv: ["--reload"],
- stdout: out.stream,
- stderr: output().stream,
- services: services({
- resetConnection: async () => {
- calls.push("reset");
- }
- })
- });
-
- assert.equal(code, 0);
- assert.deepEqual(calls, ["reset"]);
- assert.equal(out.text(), "browser connection reset on next call\n");
-});
-
-test("executionContext exposes camelCase helpers for sdk loading", async () => {
- const writes = [];
- const context = await executionContext({ write: (chunk) => writes.push(chunk) });
-
- assert.equal(typeof context.newTab, "function");
- assert.equal(typeof context.waitForLoad, "function");
- assert.equal(typeof context.pageInfo, "function");
- assert.equal(typeof context.openOrReuseTab, "function");
- assert.equal(typeof context.gotoAndWait, "function");
- assert.equal(typeof context.snapshot, "function");
- assert.equal(typeof context.snapshotText, "function");
- assert.equal(typeof context.click, "function");
- assert.equal(typeof context.fillInput, "function");
- assert.equal(typeof context.listTaskSpaces, "function");
- assert.equal(typeof context.useOrCreateTaskSpace, "function");
- assert.equal(typeof context.completeTaskSpace, "function");
- assert.equal(typeof context.waitForAgentControl, "function");
- assert.equal(context.closeTaskSpace, undefined);
- assert.equal(context.hasAgentControl, undefined);
- assert.equal(typeof context.cdp, "function");
- assert.equal(typeof context.js, "function");
- assert.equal(context.new_tab, undefined);
-
- context.cliLog("ok", { ready: true });
- assert.deepEqual(writes, ['ok {"ready":true}\n']);
-});
-
-test("executionContext omits testing internals and private exports", async () => {
- const context = await executionContext({ write() {} });
- assert.equal(context.__testing, undefined);
- assert.equal(context._private, undefined);
-});
-
-test("installEgoSdk gates helpers on explicit readiness", async () => {
- const calls = [];
- const target = {};
- let releaseReady;
- const ready = new Promise((resolve) => {
- releaseReady = resolve;
- });
-
- installEgoSdk(target, {
- ready,
- context: {
- newTab: async (url) => {
- calls.push(["newTab", url]);
- return "target-1";
- }
- },
- cliLog: (...args) => calls.push(["cliLog", ...args])
- });
-
- const opened = target.newTab("https://zhihu.com");
- assert.deepEqual(calls, []);
- releaseReady();
- assert.equal(await opened, "target-1");
- assert.deepEqual(calls, [["newTab", "https://zhihu.com"]]);
- target.cliLog("ok");
- assert.deepEqual(calls.at(-1), ["cliLog", "ok"]);
-});
diff --git a/package/ego-browser/test/session-injection.test.js b/package/ego-browser/test/session-injection.test.js
deleted file mode 100644
index 181db8c..0000000
--- a/package/ego-browser/test/session-injection.test.js
+++ /dev/null
@@ -1,198 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-
-import {
- browserCdp,
- ensureSession,
- invalidateSession
-} from "../dist/src/browser-runtime.js";
-import { state } from "../dist/src/state.js";
-
-function mockEgo({ tabs = [{ targetId: "T1", active: true }], attachReply = "S1", onSend } = {}) {
- let lastMessage = null;
- const fake = {
- listTabs: async () => ({ tabs }),
- onCDPMessage: undefined,
- sendCDPMessage(payload) {
- lastMessage = JSON.parse(payload);
- if (onSend) {
- const reply = onSend(lastMessage);
- if (reply !== undefined) {
- queueMicrotask(() => fake.onCDPMessage(JSON.stringify(reply)));
- return;
- }
- }
- let result = {};
- if (lastMessage.method === "Target.attachToTarget") {
- result = { sessionId: attachReply };
- }
- queueMicrotask(() =>
- fake.onCDPMessage(JSON.stringify({ id: lastMessage.id, result }))
- );
- },
- get lastMessage() {
- return lastMessage;
- }
- };
- return fake;
-}
-
-function withEgo(ego, fn) {
- const previous = globalThis.ego;
- globalThis.ego = ego;
- invalidateSession();
- return Promise.resolve()
- .then(fn)
- .finally(() => {
- if (previous === undefined) {
- delete globalThis.ego;
- } else {
- globalThis.ego = previous;
- }
- invalidateSession();
- });
-}
-
-test("browser-level methods skip session injection", async () => {
- const ego = mockEgo();
- await withEgo(ego, async () => {
- await browserCdp("Target.getTargets");
- assert.equal(ego.lastMessage.method, "Target.getTargets");
- assert.equal(ego.lastMessage.sessionId, undefined);
- assert.equal(state.sessionId, null, "no session created for browser-level call");
- });
-});
-
-test("page-level methods auto-attach and inject sessionId", async () => {
- const ego = mockEgo({ attachReply: "SID-ABC" });
- await withEgo(ego, async () => {
- await browserCdp("Runtime.evaluate", { expression: "1+1" });
- assert.equal(ego.lastMessage.method, "Runtime.evaluate");
- assert.equal(ego.lastMessage.sessionId, "SID-ABC");
- assert.equal(state.sessionId, "SID-ABC");
- assert.equal(state.sessionTargetId, "T1");
- });
-});
-
-test("explicit sessionId is respected and not overridden", async () => {
- const ego = mockEgo();
- await withEgo(ego, async () => {
- await browserCdp("Runtime.evaluate", {}, "EXPLICIT-SID");
- assert.equal(ego.lastMessage.sessionId, "EXPLICIT-SID");
- assert.equal(state.sessionId, null, "no auto-attach when sessionId explicit");
- });
-});
-
-test("session cached within TTL avoids re-attach", async () => {
- let attachCalls = 0;
- const ego = mockEgo({
- onSend: (msg) => {
- if (msg.method === "Target.attachToTarget") {
- attachCalls += 1;
- return { id: msg.id, result: { sessionId: "S1" } };
- }
- return { id: msg.id, result: {} };
- }
- });
- await withEgo(ego, async () => {
- await browserCdp("Runtime.evaluate", {});
- await browserCdp("Page.navigate", { url: "x" });
- await browserCdp("Input.dispatchMouseEvent", {});
- assert.equal(attachCalls, 1, "single attach for three page-level calls in TTL window");
- });
-});
-
-test("concurrent ensureSession calls deduplicate to single attach", async () => {
- let attachCalls = 0;
- const ego = mockEgo({
- onSend: (msg) => {
- if (msg.method === "Target.attachToTarget") {
- attachCalls += 1;
- return { id: msg.id, result: { sessionId: "S1" } };
- }
- return { id: msg.id, result: {} };
- }
- });
- await withEgo(ego, async () => {
- await Promise.all([
- ensureSession(),
- ensureSession(),
- ensureSession(),
- ensureSession(),
- ensureSession()
- ]);
- assert.equal(attachCalls, 1, "inflight dedupe collapses to one attach");
- });
-});
-
-test("Session not found triggers single retry with fresh attach", async () => {
- let attachCalls = 0;
- let evalCalls = 0;
- const ego = mockEgo({
- onSend: (msg) => {
- if (msg.method === "Target.attachToTarget") {
- attachCalls += 1;
- return { id: msg.id, result: { sessionId: `S${attachCalls}` } };
- }
- if (msg.method === "Runtime.evaluate") {
- evalCalls += 1;
- if (evalCalls === 1) {
- return { id: msg.id, error: { message: "Session with given id not found" } };
- }
- return { id: msg.id, result: { result: { value: 2 } } };
- }
- return { id: msg.id, result: {} };
- }
- });
- await withEgo(ego, async () => {
- const r = await browserCdp("Runtime.evaluate", { expression: "1+1" });
- assert.equal(attachCalls, 2, "re-attached after session lost");
- assert.equal(evalCalls, 2, "retried evaluate");
- assert.equal(r.result?.result?.value, 2);
- });
-});
-
-test("invalidateSession clears cache", async () => {
- const ego = mockEgo();
- await withEgo(ego, async () => {
- await browserCdp("Runtime.evaluate", {});
- assert.ok(state.sessionId);
- invalidateSession();
- assert.equal(state.sessionId, null);
- assert.equal(state.sessionTargetId, null);
- assert.equal(state.sessionAt, 0);
- });
-});
-
-test("fallback to last tab when none is marked active", async () => {
- const ego = mockEgo({
- tabs: [
- { targetId: "TA", active: false },
- { targetId: "TB", active: false },
- { targetId: "TC", active: false }
- ]
- });
- await withEgo(ego, async () => {
- await browserCdp("Runtime.evaluate", {});
- assert.equal(state.sessionTargetId, "TC", "fell back to last tab");
- });
-});
-
-test("Target.detachedFromTarget event invalidates matching session", async () => {
- const ego = mockEgo();
- await withEgo(ego, async () => {
- await browserCdp("Runtime.evaluate", {});
- assert.equal(state.sessionTargetId, "T1");
- ego.onCDPMessage(
- JSON.stringify({ method: "Target.detachedFromTarget", params: { targetId: "T1" } })
- );
- assert.equal(state.sessionId, null, "detach event cleared cached session");
- });
-});
-
-test("no active tab surfaces a clear error", async () => {
- const ego = mockEgo({ tabs: [] });
- await withEgo(ego, async () => {
- await assert.rejects(() => browserCdp("Runtime.evaluate", {}), /no active tab/);
- });
-});
diff --git a/package/ego-browser/test/site-skills.test.js b/package/ego-browser/test/site-skills.test.js
deleted file mode 100644
index a10987f..0000000
--- a/package/ego-browser/test/site-skills.test.js
+++ /dev/null
@@ -1,144 +0,0 @@
-import assert from "node:assert/strict";
-import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import test from "node:test";
-
-import * as helpers from "../dist/src/helpers.js";
-
-function withOverrides(overrides, fn) {
- const restore = helpers.__testing.setOverrides(overrides);
- return Promise.resolve()
- .then(fn)
- .finally(restore);
-}
-
-async function withSiteSkill(fn) {
- const dir = await mkdtemp(join(tmpdir(), "ego-browser-site-skills-"));
- try {
- await writeFile(join(dir, "package.json"), JSON.stringify({ type: "module" }));
- const site = join(dir, "learnings", "example");
- await mkdir(join(site, "notes"), { recursive: true });
- await mkdir(join(site, "tools"), { recursive: true });
- await mkdir(join(site, "browser-tools"), { recursive: true });
- await writeFile(join(site, "notes", "overview.md"), "# Example\n");
- await writeFile(join(site, "tools", "page.js"), [
- "export async function getTitle(ctx, args = {}) {",
- " return { title: `${args.prefix || ''}${await ctx.js('document.title')}` };",
- "}"
- ].join("\n"));
- await writeFile(join(site, "browser-tools", "extract_title.js"), "async function(args) { return { title: args.prefix + document.title }; }\n");
- await writeFile(join(site, "manifest.json"), JSON.stringify({
- id: "example",
- name: "Example",
- domains: ["example.com", "*.example.net"],
- notes: ["notes/overview.md"],
- nodeTools: {
- get_title: {
- description: "Return the current title.",
- path: "tools/page.js",
- callable: "getTitle",
- args: {
- prefix: {
- type: "string",
- required: false,
- description: "Prefix for the title."
- }
- },
- returns: { type: "object", description: "Title payload." }
- }
- },
- browserTools: {
- extract_title: {
- description: "Extract the current title in page context.",
- path: "browser-tools/extract_title.js",
- args: {
- prefix: {
- type: "string",
- required: false,
- description: "Prefix for the title."
- }
- },
- returns: { type: "object", description: "Title payload." }
- }
- }
- }));
- return await fn(dir);
- } finally {
- await rm(dir, { recursive: true, force: true });
- }
-}
-
-test("siteSkillsForUrl matches manifest domains and exposes declared assets", async () => {
- await withSiteSkill(async (dir) => {
- await withOverrides({ agentWorkspace: () => dir }, async () => {
- const matches = await helpers.siteSkillsForUrl("https://app.example.net/path");
-
- assert.equal(matches.length, 1);
- assert.equal(matches[0].id, "example");
- assert.equal(matches[0].name, "Example");
- assert.deepEqual(matches[0].domains, ["example.com", "*.example.net"]);
- assert.deepEqual(matches[0].notes, [join(dir, "learnings", "example", "notes", "overview.md")]);
- assert.ok(matches[0].nodeTools.get_title);
- assert.ok(matches[0].browserTools.extract_title);
- assert.deepEqual(await helpers.siteSkillsForUrl("https://app.example.com/path"), []);
- });
- });
-});
-
-test("site tools receive helper context and browser tools wrap page JavaScript", async () => {
- await withSiteSkill(async (dir) => {
- const jsExpressions = [];
- await withOverrides({
- agentWorkspace: () => dir,
- cdpOverride: async (method, params) => {
- if (method === "Runtime.evaluate") {
- jsExpressions.push(params.expression);
- if (params.expression === "document.title") {
- return { result: { value: "Example" } };
- }
- return { result: { value: { title: "Title: Example" } } };
- }
- return {};
- }
- }, async () => {
- assert.deepEqual(
- await helpers.runSiteTool("example", "get_title", { prefix: "Title: " }),
- { title: "Title: Example" }
- );
- assert.deepEqual(
- await helpers.runSiteBrowserTool("example", "extract_title", { prefix: "Title: " }),
- { title: "Title: Example" }
- );
- });
- assert.ok(jsExpressions.some((expression) => expression.includes("const __egoBrowserTool = async function(args)")));
- assert.ok(jsExpressions.some((expression) => expression.includes('"prefix":"Title: "')));
- });
-});
-
-test("missing site skill error includes searched root and workspace hint", async () => {
- await withSiteSkill(async (dir) => {
- await withOverrides({ agentWorkspace: () => dir }, async () => {
- const previous = process.env.EGO_BROWSER_AGENT_WORKSPACE;
- try {
- process.env.EGO_BROWSER_AGENT_WORKSPACE = "/tmp/ego-browser-test-workspace";
- await assert.rejects(
- () => helpers.runSiteTool("missing-site", "noop", {}),
- (error) => {
- assert.match(error.message, /site skill not found: "missing-site"/);
- assert.match(error.message, new RegExp(`searched: .*${join(dir, "learnings").replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`));
- assert.match(error.message, /EGO_BROWSER_AGENT_WORKSPACE: \/tmp\/ego-browser-test-workspace/);
- assert.match(error.message, /hint: ensure your write path begins/);
- return true;
- }
- );
- } finally {
- if (previous === undefined) {
- delete process.env.EGO_BROWSER_AGENT_WORKSPACE;
- } else {
- process.env.EGO_BROWSER_AGENT_WORKSPACE = previous;
- }
- }
- });
- });
-});
diff --git a/package/ego-browser/test/state.test.js b/package/ego-browser/test/state.test.js
deleted file mode 100644
index a6e2ada..0000000
--- a/package/ego-browser/test/state.test.js
+++ /dev/null
@@ -1,38 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-
-import { cdpAvailable, send, setOverrides, state } from "../dist/src/state.js";
-
-test("setOverrides restores state after mutation", async () => {
- const restore = setOverrides({
- send: async () => ({ ok: true }),
- cdpOverride: async () => ({ result: { value: 1 } }),
- platform: "test-platform"
- });
-
- try {
- assert.equal(state.platform, "test-platform");
- assert.equal(cdpAvailable(), true);
- await assert.doesNotReject(() => send({ method: "Runtime.evaluate" }));
- } finally {
- restore();
- }
-
- assert.equal(state.platform, process.platform);
- assert.equal(state.cdpOverride, null);
-});
-
-test("cdpAvailable follows explicit override or custom send", async () => {
- const restore = setOverrides({
- cdpOverride: null,
- send: async () => ({ result: {} })
- });
-
- try {
- assert.equal(cdpAvailable(), true);
- } finally {
- restore();
- }
-
- assert.equal(cdpAvailable(), false);
-});
diff --git a/package/ego-browser/test/validate-site-skills.test.js b/package/ego-browser/test/validate-site-skills.test.js
deleted file mode 100644
index 53fccad..0000000
--- a/package/ego-browser/test/validate-site-skills.test.js
+++ /dev/null
@@ -1,136 +0,0 @@
-import assert from "node:assert/strict";
-import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import test from "node:test";
-
-import { validateSiteSkills } from "../dist/scripts/validate-site-skills.js";
-
-function nodeToolSchema() {
- return {
- get_title: {
- description: "Return the current title.",
- path: "tools/page.js",
- callable: "getTitle",
- args: {},
- returns: { type: "object", description: "Title payload." }
- }
- };
-}
-
-function browserToolSchema() {
- return {
- extract_title: {
- description: "Extract the current title.",
- path: "browser-tools/extract_title.js",
- args: {},
- returns: { type: "object", description: "Title payload." }
- }
- };
-}
-
-async function withRoot(fn) {
- const root = await mkdtemp(join(tmpdir(), "ego-browser-validate-skills-"));
- try {
- await writeFile(join(root, "package.json"), JSON.stringify({ type: "module" }));
- return await fn(root);
- } finally {
- await rm(root, { recursive: true, force: true });
- }
-}
-
-async function seedSite(root, options = {}) {
- const siteId = options.siteId || "example";
- const site = join(root, siteId);
- await mkdir(join(site, "notes"), { recursive: true });
- await mkdir(join(site, "tools"), { recursive: true });
- await mkdir(join(site, "browser-tools"), { recursive: true });
- const manifest = {
- id: siteId,
- name: "Example",
- domains: ["example.com", "*.example.com"],
- notes: ["notes/overview.md"],
- nodeTools: nodeToolSchema(),
- browserTools: browserToolSchema(),
- ...(options.manifestExtra || {})
- };
- await writeFile(join(site, "manifest.json"), JSON.stringify(manifest));
- if (options.note !== false) {
- await writeFile(join(site, "notes", "overview.md"), options.noteText || "# Example\n");
- }
- if (options.nodeTool !== false) {
- await writeFile(join(site, "tools", "page.js"), options.nodeToolText || "export async function getTitle(ctx) { return ctx.js('document.title'); }\n");
- }
- if (options.browserTool !== false) {
- await writeFile(join(site, "browser-tools", "extract_title.js"), options.browserToolText || "async function(args) { return document.title; }\n");
- }
- return site;
-}
-
-test("validateSiteSkills accepts valid sites and ignores _template", async () => {
- await withRoot(async (root) => {
- await seedSite(root);
- await mkdir(join(root, "_template"));
-
- assert.deepEqual(await validateSiteSkills(root), []);
- });
-});
-
-test("validateSiteSkills reports manifest, domain, path, callable, and ref errors", async () => {
- await withRoot(async (root) => {
- await seedSite(root, {
- siteId: "bad",
- manifestExtra: {
- id: "wrong",
- domains: ["https://example.com"],
- notes: ["notes/overview.md", "overview.md"],
- nodeTools: {
- broken: {
- description: "Broken.",
- path: "tools/missing.js",
- callable: "missing",
- args: {
- limit: {
- type: "date",
- required: false,
- description: "Bad type."
- }
- },
- returns: { type: "object", description: "Payload." }
- }
- },
- browserTools: {
- nested: {
- description: "Nested.",
- path: "browser-tools/search/extract.js",
- args: {},
- returns: { type: "array", description: "Rows." }
- }
- }
- },
- noteText: "Do not use @42 here.\n"
- });
-
- const errors = await validateSiteSkills(root);
-
- assert.ok(errors.some((error) => error.includes("manifest id must match directory name")));
- assert.ok(errors.some((error) => error.includes("invalid domain")));
- assert.ok(errors.some((error) => error.includes("notes must point to notes/*.md")));
- assert.ok(errors.some((error) => error.includes("path must be a relative tools/*.js path")) || errors.some((error) => error.includes("missing Node tool file")));
- assert.ok(errors.some((error) => error.includes("invalid arg type")));
- assert.ok(errors.some((error) => error.includes("path must be a relative browser-tools/*.js path")));
- assert.ok(errors.some((error) => error.includes("temporary snapshot ref")));
- });
-});
-
-test("validateSiteSkills reports missing Node callable", async () => {
- await withRoot(async (root) => {
- await seedSite(root, {
- nodeToolText: "export async function other(ctx) { return ctx.js('document.title'); }\n"
- });
-
- const errors = await validateSiteSkills(root);
-
- assert.ok(errors.some((error) => error.includes("missing Node callable")));
- });
-});