The fastest browser for AI agents to run browser automation, built for sharing your logged-in browser state with your AI agents, like Codex or Claude Code, without disturbing you. Zero cost, zero config.
JavaScript agent-skillsai-agentautomationbrowserbrowser-automationclaude-codecodexhermes-agentskillsskills-sh
Add ego-browser mutation testing checks
Tachikomae0d006db9200
diff --git a/package/ego-browser/package.json b/package/ego-browser/package.jsonindex 1138482..3992795 100644--- a/package/ego-browser/package.json+++ b/package/ego-browser/package.json@@ -14,6 +14,7 @@"style:check": "prettier --check","typecheck": "tsc --noEmit","test": "npm run build && npm run typecheck && node --test \"src/**/*.test.mjs\" \"test/*.test.js\"",+ "mutation-check": "npm run build && node scripts/mutation-check.mjs","validate:learnings": "npm run build && EGO_BROWSER_AGENT_WORKSPACE=../../skills/ego-browser node dist/scripts/validate-site-skills.js","validate:site-skills": "npm run build && EGO_BROWSER_AGENT_WORKSPACE=../../skills/ego-browser node dist/scripts/validate-site-skills.js"},diff --git a/package/ego-browser/scripts/mutation-check.mjs b/package/ego-browser/scripts/mutation-check.mjsnew file mode 100644index 0000000..86f2dce--- /dev/null+++ b/package/ego-browser/scripts/mutation-check.mjs@@ -0,0 +1,397 @@+#!/usr/bin/env node+/**+ * Lightweight mutation testing for ego-browser.+ *+ * Parses compiled JS in dist/src/ with acorn, injects targeted mutations+ * (operator flips, return value swaps, boundary shifts), runs the+ * corresponding test file, and reports kill rate.+ *+ * Usage:+ * node scripts/mutation-check.mjs # check all modules+ * node scripts/mutation-check.mjs cdp-eval # check one module+ * node scripts/mutation-check.mjs --verbose # print each mutant+ *+ * Requires: npm run build (to produce dist/ output).+ */++import { readFileSync, writeFileSync, existsSync } from "node:fs";+import { join, dirname } from "node:path";+import { fileURLToPath } from "node:url";+import { execSync } from "node:child_process";+import * as acorn from "acorn";++const __dirname = dirname(fileURLToPath(import.meta.url));+const PKG_DIR = join(__dirname, "..");+const DIST_SRC = join(PKG_DIR, "dist", "src");++/* ── module → test file mapping ── */+const MODULE_MAP = {+ "cdp-eval": {+ src: "cdp-eval.js",+ test: "src/cdp-eval.test.mjs",+ focus: [+ "hasReturnStatement",+ "decodeUnserializableJsValue",+ "runtimeValue",+ ],+ },+ "element-resolver": {+ src: "element-resolver.js",+ test: "src/element-resolver.test.mjs",+ focus: [+ "matchCountKind",+ "boxModelCenter",+ "isStaleBackendNodeError",+ "isBoxModelUnavailableError",+ ],+ },+ "browser-runtime": {+ src: "browser-runtime.js",+ test: "src/browser-runtime.test.mjs",+ focus: ["ensureSession", "handleMessage"],+ },+ helpers: {+ src: "helpers.js",+ test: "src/helpers.test.mjs",+ focus: ["isAgentOwned", "findMatchingTaskSpace"],+ },+};++/* ── mutation operators ── */+const BINARY_FLIPS = {+ "===": "!==",+ "!==": "===",+ "==": "!=",+ "!=": "==",+ ">": "<=",+ "<": ">=",+ ">=": "<",+ "<=": ">",+ "&&": "||",+ "||": "&&",+};++const ARITHMETIC_FLIPS = {+ "+": "-",+ "-": "+",+ "*": "/",+};++const RETURN_VALUE_SWAPS = [+ { from: "true", to: "false" },+ { from: "false", to: "true" },+ { from: "null", to: "undefined" },+ { from: "0", to: "1" },+ { from: "1", to: "0" },+];++/* ── AST walker ── */+function walk(node, visitors) {+ if (!node || typeof node !== "object") return;+ const visit = visitors[node.type];+ if (visit) visit(node);+ for (const key of Object.keys(node)) {+ if (key === "type" || key === "start" || key === "end" || key === "loc")+ continue;+ const child = node[key];+ if (Array.isArray(child)) {+ for (const c of child) walk(c, visitors);+ } else if (child && typeof child === "object" && child.type) {+ walk(child, visitors);+ }+ }+}++/* ── mutation candidate collection ── */+function collectMutations(source, focusFunctions) {+ let ast;+ try {+ ast = acorn.parse(source, {+ ecmaVersion: 2022,+ sourceType: "module",+ locations: true,+ });+ } catch {+ return [];+ }++ const mutations = [];++ walk(ast, {+ BinaryExpression(node) {+ if (!inFocus(source, node.start, focusFunctions)) return;+ const op = node.operator;+ if (BINARY_FLIPS[op]) {+ const original = source.slice(node.start, node.end);+ const mutated = original.replace(op, BINARY_FLIPS[op]);+ mutations.push({+ type: `binary:${op}→${BINARY_FLIPS[op]}`,+ start: node.start,+ end: node.end,+ original,+ mutated,+ line: node.loc?.start?.line,+ });+ }+ if (ARITHMETIC_FLIPS[op] && !isStringContext(source, node)) {+ const original = source.slice(node.start, node.end);+ const mutated = original.replace(op, ARITHMETIC_FLIPS[op]);+ mutations.push({+ type: `arith:${op}→${ARITHMETIC_FLIPS[op]}`,+ start: node.start,+ end: node.end,+ original,+ mutated,+ line: node.loc?.start?.line,+ });+ }+ },+ ReturnStatement(node) {+ if (!inFocus(source, node.start, focusFunctions)) return;+ if (!node.argument) return;+ const argSrc = source+ .slice(node.argument.start, node.argument.end)+ .trim();+ for (const swap of RETURN_VALUE_SWAPS) {+ if (argSrc === swap.from) {+ mutations.push({+ type: `return:${swap.from}→${swap.to}`,+ start: node.argument.start,+ end: node.argument.end,+ original: argSrc,+ mutated: swap.to,+ line: node.loc?.start?.line,+ });+ break;+ }+ }+ },+ UnaryExpression(node) {+ if (!inFocus(source, node.start, focusFunctions)) return;+ if (node.operator === "!" && node.argument.type === "Identifier") {+ mutations.push({+ type: "negate:!x→x",+ start: node.start,+ end: node.end,+ original: source.slice(node.start, node.end),+ mutated: source.slice(node.argument.start, node.argument.end),+ line: node.loc?.start?.line,+ });+ }+ },+ });++ return deduplicateMutations(mutations);+}++function inFocus(source, offset, focusFunctions) {+ if (!focusFunctions || focusFunctions.length === 0) return true;+ // Check if the offset is inside a function whose name is in the focus list.+ // Simple heuristic: scan backward from offset for a function declaration/export+ // containing one of the focus names.+ const before = source.slice(Math.max(0, offset - 2000), offset);+ for (const name of focusFunctions) {+ // Match both `function name(` and `async function name(` and `export function name(`+ const pattern = new RegExp(+ `(?:export\\s+)?(?:async\\s+)?function\\s+${name}\\s*\\(`,+ );+ if (pattern.test(before)) return true;+ // Also match arrow functions: `const name = ... =>`+ const arrowPattern = new RegExp(`(?:const|let|var)\\s+${name}\\s*=`);+ if (arrowPattern.test(before)) return true;+ }+ return false;+}++function isStringContext(source, node) {+ // Skip arithmetic flips that look like string concatenation+ return node.left?.type === "Literal" && typeof node.left.value === "string";+}++function deduplicateMutations(mutations) {+ const seen = new Set();+ return mutations.filter((m) => {+ const key = `${m.start}:${m.end}:${m.type}`;+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });+}++/* ── mutation application ── */+function applyMutation(source, mutation) {+ return (+ source.slice(0, mutation.start) ++ mutation.mutated ++ source.slice(mutation.end)+ );+}++/* ── test runner ── */+function runTest(testFile, timeoutMs = 15000) {+ try {+ execSync(`node --test "${testFile}"`, {+ cwd: PKG_DIR,+ timeout: timeoutMs,+ stdio: "pipe",+ env: { ...process.env, NODE_OPTIONS: "" },+ });+ return { passed: true };+ } catch (error) {+ return {+ passed: false,+ output: error.stderr?.toString().slice(-500) || "",+ };+ }+}++/* ── main ── */+function main() {+ const args = process.argv.slice(2);+ const verbose = args.includes("--verbose");+ const targetModules = args.filter((a) => !a.startsWith("--"));++ const modules =+ targetModules.length > 0+ ? Object.fromEntries(+ targetModules+ .filter((m) => MODULE_MAP[m])+ .map((m) => [m, MODULE_MAP[m]]),+ )+ : MODULE_MAP;++ if (Object.keys(modules).length === 0) {+ console.error(+ "No matching modules found. Available:",+ Object.keys(MODULE_MAP).join(", "),+ );+ process.exit(1);+ }++ // Check that dist/ exists+ if (!existsSync(DIST_SRC)) {+ console.error("dist/src/ not found. Run `npm run build` first.");+ process.exit(1);+ }++ const report = [];+ let totalMutations = 0;+ let totalKilled = 0;+ let totalSurvived = 0;+ let totalSkipped = 0;++ for (const [moduleName, config] of Object.entries(modules)) {+ const srcPath = join(DIST_SRC, config.src);+ if (!existsSync(srcPath)) {+ console.error(` [skip] ${config.src} not found in dist/src/`);+ totalSkipped++;+ continue;+ }++ const source = readFileSync(srcPath, "utf-8");+ const mutations = collectMutations(source, config.focus);++ if (mutations.length === 0) {+ console.log(` [${moduleName}] no mutation candidates found`);+ continue;+ }++ console.log(`\n[${moduleName}] ${mutations.length} mutations to test`);++ const moduleResults = [];+ let killed = 0;+ let survived = 0;++ for (let i = 0; i < mutations.length; i++) {+ const m = mutations[i];+ const mutated = applyMutation(source, m);++ // Backup original+ writeFileSync(srcPath, mutated, "utf-8");+ try {+ const result = runTest(config.test);+ const status = result.passed ? "SURVIVED" : "KILLED";++ if (result.passed) {+ survived++;+ totalSurvived++;+ } else {+ killed++;+ totalKilled++;+ }++ moduleResults.push({ ...m, status });++ if (verbose || status === "SURVIVED") {+ const marker = status === "KILLED" ? "✗" : "✓";+ console.log(` ${marker} L${m.line || "?"} ${m.type} — ${status}`);+ }++ const pct = Math.round(((i + 1) / mutations.length) * 100);+ process.stdout.write(` ${i + 1}/${mutations.length} (${pct}%)\r`);+ } finally {+ // Always restore original+ writeFileSync(srcPath, source, "utf-8");+ }+ }++ totalMutations += mutations.length;++ const killRate =+ mutations.length > 0 ? Math.round((killed / mutations.length) * 100) : 0;+ report.push({+ module: moduleName,+ total: mutations.length,+ killed,+ survived,+ killRate,+ survivedMutations: moduleResults.filter((r) => r.status === "SURVIVED"),+ });+ }++ // ── Summary ──+ console.log("\n" + "═".repeat(60));+ console.log("MUTATION TESTING REPORT");+ console.log("═".repeat(60));++ for (const r of report) {+ const bar =+ "█".repeat(Math.round(r.killRate / 5)) ++ "░".repeat(20 - Math.round(r.killRate / 5));+ const indicator =+ r.killRate >= 80 ? "OK" : r.killRate >= 60 ? "WARN" : "LOW";+ console.log(`\n ${r.module}:`);+ console.log(+ ` ${bar} ${r.killRate}% (${r.killed}/${r.total} killed) [${indicator}]`,+ );++ if (r.survivedMutations.length > 0 && r.survivedMutations.length <= 10) {+ console.log(" Survived mutations:");+ for (const s of r.survivedMutations) {+ console.log(+ ` L${s.line || "?"} ${s.type}: ${s.original.trim().slice(0, 60)}`,+ );+ }+ } else if (r.survivedMutations.length > 10) {+ console.log(+ ` ${r.survivedMutations.length} survived mutations (use --verbose for details)`,+ );+ }+ }++ const overallRate =+ totalMutations > 0 ? Math.round((totalKilled / totalMutations) * 100) : 0;+ console.log(`\n${"─".repeat(60)}`);+ console.log(+ ` Overall: ${totalKilled}/${totalMutations} killed (${overallRate}%)`,+ );+ console.log(` ${totalSurvived} survived, ${totalSkipped} skipped`);+ console.log("═".repeat(60));++ if (overallRate < 60) {+ console.log("\n Kill rate below 60% — consider strengthening assertions.");+ process.exit(1);+ }+}++main();diff --git a/package/ego-browser/src/browser-runtime.test.mjs b/package/ego-browser/src/browser-runtime.test.mjsindex fc65f41..3629244 100644--- a/package/ego-browser/src/browser-runtime.test.mjs+++ b/package/ego-browser/src/browser-runtime.test.mjs@@ -1,66 +1,703 @@import test from "node:test";import assert from "node:assert/strict";-import { browserCdp } from "../dist/src/browser-runtime.js";+import {+ browserCdp,+ drainBrowserEvents,+ invalidateSession,+ isBrowserRuntime,+ pendingDialog,+ setPreferredTarget,+ clearPreferredTarget,+ ensureSession,+ browserSnapshotRefsToRefMap,+} from "../dist/src/browser-runtime.js";+import { state } from "../dist/src/state.js";-// Gap A: ensureSession() calls the raw listTabs binding to attach a session.-// When the task is blocked it returns { error, error_code }; the result must-// surface the ego-browser-owned wording for the code (not the native error-// message) and carry error_code, instead of throwing the bare native error message.-test("browserCdp surfaces the owned message and error_code when ensureSession is blocked", async () => {+/**+ * Install a mock ego that auto-responds to every CDP send with { result: {} }.+ * Use the returned `calls` array to inspect what was sent, and `ego.onCDPMessage`+ * (set by rawCdp after the first send) to deliver events directly.+ */+function installAutoEgo(listTabsResult) {+ const calls = [];+ const tabs = listTabsResult || {+ tabs: [{ targetId: "tab-1", active: true }],+ };+ globalThis.ego = {+ async listTabs() {+ return tabs;+ },+ sendCDPMessage(payload) {+ const parsed = JSON.parse(payload);+ calls.push(parsed);+ setTimeout(() => {+ if (globalThis.ego?.onCDPMessage) {+ const result =+ parsed.method === "Target.attachToTarget"+ ? { sessionId: `auto-sess-${parsed.id}` }+ : {};+ globalThis.ego.onCDPMessage(+ JSON.stringify({ id: parsed.id, result }),+ );+ }+ }, 0);+ },+ };+ return calls;+}++/**+ * Install a mock ego with manual control over sendCDPMessage.+ * Returns the calls array; use ego.onCDPMessage after a send to deliver responses.+ */+function installManualEgo(listTabsResult) {+ const calls = [];+ const tabs = listTabsResult || {+ tabs: [{ targetId: "tab-1", active: true }],+ };globalThis.ego = {async listTabs() {- return {- error: "Task space 10 is not assigned to an agent.",- error_code: "EGO_TASK_SPACE_INACTIVE",- };+ return tabs;+ },+ sendCDPMessage(payload) {+ calls.push(JSON.parse(payload));},};+ return calls;+}++/** Fire a CDP event through the handler set up by rawCdp. */+function fireEvent(method, params = {}, sessionId) {+ const msg = { method, params };+ if (sessionId) msg.sessionId = sessionId;+ globalThis.ego.onCDPMessage(JSON.stringify(msg));+}++function cleanup() {+ delete globalThis.ego;+ invalidateSession();+ clearPreferredTarget();+ drainBrowserEvents();+ state.cdpOverride = null;+ state.sessionInflight = null;+}++/* ------------------------------------------------------------------ */+/* isBrowserRuntime */+/* ------------------------------------------------------------------ */++test("isBrowserRuntime returns false when ego is not installed", () => {+ delete globalThis.ego;+ assert.equal(isBrowserRuntime(), false);+});++test("isBrowserRuntime returns true when ego has sendCDPMessage", () => {+ installAutoEgo();+ try {+ assert.equal(isBrowserRuntime(), true);+ } finally {+ cleanup();+ }+});++test("isBrowserRuntime returns false when ego lacks sendCDPMessage", () => {+ globalThis.ego = { listTabs() {} };+ try {+ assert.equal(isBrowserRuntime(), false);+ } finally {+ delete globalThis.ego;+ }+});++/* ------------------------------------------------------------------ */+/* rawCdp — request/response */+/* ------------------------------------------------------------------ */++test("browserCdp with explicit sessionId sends and resolves on matching response", async () => {+ const calls = installManualEgo();+ try {+ const promise = browserCdp(+ "Runtime.evaluate",+ { expression: "1" },+ "sess-1",+ 5000,+ );+ assert.equal(calls.length, 1);+ assert.equal(calls[0].method, "Runtime.evaluate");+ assert.equal(calls[0].sessionId, "sess-1");+ globalThis.ego.onCDPMessage(+ JSON.stringify({ id: calls[0].id, result: { value: 42 } }),+ );+ const result = await promise;+ assert.deepEqual(result.result, { value: 42 });+ } finally {+ cleanup();+ }+});++test("browserCdp rejects when CDP response carries an error", async () => {+ const calls = installManualEgo();+ try {+ const promise = browserCdp("Runtime.evaluate", {}, "sess-1", 5000);+ globalThis.ego.onCDPMessage(+ JSON.stringify({ id: calls[0].id, error: { message: "SyntaxError" } }),+ );+ await assert.rejects(promise, /SyntaxError/);+ } finally {+ cleanup();+ }+});++test("browserCdp times out when no response arrives", async () => {+ installManualEgo();try {await assert.rejects(- () => browserCdp("Runtime.evaluate", {}, undefined, 1000),- (err) => {- assert.equal(err.error_code, "EGO_TASK_SPACE_INACTIVE");- // Owned guidance block, not the native "Task space 10 ..." text.- assert.match(err.message, /claimTaskSpace\(id\)/);- assert.doesNotMatch(err.message, /\b10\b/);- return true;- },+ () => browserCdp("Runtime.evaluate", {}, "sess-1", 100),+ /CDP request timed out: Runtime\.evaluate/,);} finally {- delete globalThis.ego;+ cleanup();}});-// Gap B: a raw CDP send that fails locally is reported through-// ego.onSendCDPMessageError, not as a CDP response. Without wiring the request-// would hang until the 15s timeout; wired, it rejects immediately with the-// owned message and error_code.-test("browserCdp rejects the in-flight request via onSendCDPMessageError", async () => {+test("browserCdp rejects when sendCDPMessage throws synchronously", async () => {globalThis.ego = {sendCDPMessage() {- // The binding delivers the failure asynchronously through the event loop.- queueMicrotask(() =>- globalThis.ego.onSendCDPMessageError(- "native reconstructed text",- "EGO_TASK_SPACE_INACTIVE",- ),- );+ throw new Error("binding gone");},};try {await assert.rejects(- // Browser-level method skips ensureSession; short timeout bounds a regression.- () => browserCdp("Browser.getVersion", {}, undefined, 1000),- (err) => {- assert.equal(err.error_code, "EGO_TASK_SPACE_INACTIVE");- // Owned guidance block, not the native reconstructed text.- assert.match(err.message, /claimTaskSpace\(id\)/);- assert.doesNotMatch(err.message, /native reconstructed text/);- return true;- },+ () => browserCdp("Target.getVersion", {}, undefined, 1000),+ /binding gone/,);} finally {- delete globalThis.ego;+ cleanup();}});++test("handleMessage ignores unparseable JSON", async () => {+ const calls = installManualEgo();+ try {+ // Trigger rawCdp to set up onCDPMessage+ const p = browserCdp("Target.getVersion", {}, undefined, 5000);+ globalThis.ego.onCDPMessage("not valid json{{{");+ const evts = drainBrowserEvents();+ assert.equal(evts.length, 0, "bad JSON is silently ignored");+ // Clean up: respond to the pending request+ globalThis.ego.onCDPMessage(+ JSON.stringify({ id: calls[0].id, result: {} }),+ );+ await p;+ } finally {+ cleanup();+ }+});++test("handleMessage ignores responses for unknown request ids", async () => {+ const calls = installManualEgo();+ try {+ const p = browserCdp("Target.getVersion", {}, undefined, 5000);+ globalThis.ego.onCDPMessage(JSON.stringify({ id: 999999, result: {} }));+ const evts = drainBrowserEvents();+ assert.equal(evts.length, 0, "unknown id produces no events");+ globalThis.ego.onCDPMessage(+ JSON.stringify({ id: calls[0].id, result: {} }),+ );+ await p;+ } finally {+ cleanup();+ }+});++/* ------------------------------------------------------------------ */+/* drainBrowserEvents — event buffer */+/* ------------------------------------------------------------------ */++test("drainBrowserEvents collects CDP events and clears the buffer", async () => {+ const calls = installManualEgo();+ try {+ const p = browserCdp("Target.getVersion", {}, undefined, 5000);+ globalThis.ego.onCDPMessage(+ JSON.stringify({ id: calls[0].id, result: {} }),+ );+ await p;++ fireEvent("Network.requestWillBeSent", { requestId: "1" });+ fireEvent("Page.loadEventFired", { timestamp: 123 });++ const first = drainBrowserEvents();+ assert.equal(first.length, 2);+ assert.equal(first[0].method, "Network.requestWillBeSent");+ assert.equal(first[1].method, "Page.loadEventFired");++ const second = drainBrowserEvents();+ assert.equal(second.length, 0, "second drain returns empty");+ } finally {+ cleanup();+ }+});++test("drainBrowserEvents caps at MAX_BUFFERED_EVENTS (10000)", async () => {+ const calls = installManualEgo();+ try {+ const p = browserCdp("Target.getVersion", {}, undefined, 5000);+ globalThis.ego.onCDPMessage(+ JSON.stringify({ id: calls[0].id, result: {} }),+ );+ await p;++ for (let i = 0; i < 10005; i++) {+ fireEvent(`evt.${i}`, {});+ }+ const evts = drainBrowserEvents();+ assert.equal(evts.length, 10000, "buffer capped at 10000 events");+ assert.equal(evts[0].method, "evt.5", "oldest events dropped");+ assert.equal(evts[evts.length - 1].method, "evt.10004");+ } finally {+ cleanup();+ }+});++/* ------------------------------------------------------------------ */+/* Dialog tracking */+/* ------------------------------------------------------------------ */++test("pendingDialog tracks dialog open and close", async () => {+ const calls = installManualEgo();+ try {+ state.sessionId = "sess-d";+ const p = browserCdp("Target.getVersion", {}, undefined, 5000);+ globalThis.ego.onCDPMessage(+ JSON.stringify({ id: calls[0].id, result: {} }),+ );+ await p;++ assert.equal(pendingDialog(), null, "no dialog initially");++ fireEvent(+ "Page.javascriptDialogOpening",+ { type: "alert", message: "Hello" },+ "sess-d",+ );+ const dialog = pendingDialog();+ assert.ok(dialog, "dialog is pending after opening event");+ assert.equal(dialog.type, "alert");+ assert.equal(dialog.message, "Hello");++ fireEvent("Page.javascriptDialogClosed", {}, "sess-d");+ assert.equal(pendingDialog(), null, "dialog cleared after close event");+ } finally {+ cleanup();+ }+});++test("pendingDialog uses state.sessionId when event has no sessionId", async () => {+ const calls = installManualEgo();+ try {+ state.sessionId = "sess-fallback";+ const p = browserCdp("Target.getVersion", {}, undefined, 5000);+ globalThis.ego.onCDPMessage(+ JSON.stringify({ id: calls[0].id, result: {} }),+ );+ await p;++ fireEvent("Page.javascriptDialogOpening", {+ type: "confirm",+ message: "Sure?",+ });+ const dialog = pendingDialog("sess-fallback");+ assert.ok(dialog, "dialog tracked via state.sessionId fallback");+ assert.equal(dialog.type, "confirm");+ } finally {+ cleanup();+ }+});++test("pendingDialog returns null for a different session", async () => {+ const calls = installManualEgo();+ try {+ state.sessionId = "sess-a";+ const p = browserCdp("Target.getVersion", {}, undefined, 5000);+ globalThis.ego.onCDPMessage(+ JSON.stringify({ id: calls[0].id, result: {} }),+ );+ await p;++ fireEvent("Page.javascriptDialogOpening", { type: "alert" }, "sess-b");+ assert.equal(pendingDialog("sess-a"), null, "no dialog on sess-a");+ assert.ok(pendingDialog("sess-b"), "dialog exists on sess-b");+ } finally {+ cleanup();+ }+});++/* ------------------------------------------------------------------ */+/* Target detach — invalidates session and cleans up dialog state */+/* ------------------------------------------------------------------ */++test("Target.detachedFromTarget invalidates session when targetId matches", async () => {+ const calls = installManualEgo();+ try {+ state.sessionId = "sess-detach";+ state.sessionTargetId = "target-1";+ state.sessionAt = Date.now();++ const p = browserCdp("Target.getVersion", {}, undefined, 5000);+ globalThis.ego.onCDPMessage(+ JSON.stringify({ id: calls[0].id, result: {} }),+ );+ await p;++ fireEvent("Page.javascriptDialogOpening", { type: "alert" }, "sess-detach");+ assert.ok(pendingDialog("sess-detach"), "dialog present before detach");++ fireEvent("Target.detachedFromTarget", {+ targetId: "target-1",+ sessionId: "sess-detach",+ });++ assert.equal(state.sessionId, null, "session invalidated after detach");+ assert.equal(state.sessionTargetId, null);+ assert.equal(+ pendingDialog("sess-detach"),+ null,+ "dialog cleaned up on detach",+ );+ } finally {+ cleanup();+ }+});++test("Target.targetDestroyed also invalidates session", async () => {+ const calls = installManualEgo();+ try {+ state.sessionId = "sess-destroy";+ state.sessionTargetId = "target-x";+ state.sessionAt = Date.now();++ const p = browserCdp("Target.getVersion", {}, undefined, 5000);+ globalThis.ego.onCDPMessage(+ JSON.stringify({ id: calls[0].id, result: {} }),+ );+ await p;++ fireEvent("Target.targetDestroyed", { targetId: "target-x" });+ assert.equal(+ state.sessionId,+ null,+ "session invalidated on target destroyed",+ );+ } finally {+ cleanup();+ }+});++test("Target.detachedFromTarget does not invalidate session for a different target", async () => {+ const calls = installManualEgo();+ try {+ state.sessionId = "sess-keep";+ state.sessionTargetId = "target-ours";+ state.sessionAt = Date.now();++ const p = browserCdp("Target.getVersion", {}, undefined, 5000);+ globalThis.ego.onCDPMessage(+ JSON.stringify({ id: calls[0].id, result: {} }),+ );+ await p;++ fireEvent("Target.detachedFromTarget", {+ targetId: "target-other",+ sessionId: "sess-other",+ });+ assert.equal(+ state.sessionId,+ "sess-keep",+ "session not invalidated for different target",+ );+ } finally {+ cleanup();+ }+});++/* ------------------------------------------------------------------ */+/* invalidateSession */+/* ------------------------------------------------------------------ */++test("invalidateSession clears session state and dialog tracking", async () => {+ const calls = installManualEgo();+ try {+ state.sessionId = "sess-inv";+ state.sessionTargetId = "target-1";+ state.sessionAt = Date.now();++ const p = browserCdp("Target.getVersion", {}, undefined, 5000);+ globalThis.ego.onCDPMessage(+ JSON.stringify({ id: calls[0].id, result: {} }),+ );+ await p;++ fireEvent("Page.javascriptDialogOpening", { type: "alert" }, "sess-inv");+ invalidateSession();+ assert.equal(state.sessionId, null);+ assert.equal(state.sessionTargetId, null);+ assert.equal(state.sessionAt, 0);+ assert.equal(+ pendingDialog("sess-inv"),+ null,+ "dialog cleared by invalidation",+ );+ } finally {+ cleanup();+ }+});++/* ------------------------------------------------------------------ */+/* setPreferredTarget / clearPreferredTarget */+/* ------------------------------------------------------------------ */++test("setPreferredTarget and clearPreferredTarget manage state", () => {+ setPreferredTarget("target-42");+ assert.equal(state.preferredTargetId, "target-42");+ clearPreferredTarget();+ assert.equal(state.preferredTargetId, null);+});++test("setPreferredTarget treats empty string as null", () => {+ setPreferredTarget("");+ assert.equal(state.preferredTargetId, null);+ setPreferredTarget(undefined);+ assert.equal(state.preferredTargetId, null);+});++/* ------------------------------------------------------------------ */+/* ensureSession — session caching, TTL, tab selection */+/* ------------------------------------------------------------------ */++test("ensureSession returns cached session within TTL", async () => {+ installAutoEgo();+ try {+ state.sessionId = "cached-session";+ state.sessionAt = Date.now();+ const result = await ensureSession();+ assert.equal(result, "cached-session");+ } finally {+ cleanup();+ }+});++test("ensureSession re-attaches when TTL has expired", async () => {+ installAutoEgo();+ try {+ state.sessionId = "old-session";+ state.sessionAt = Date.now() - 3000; // expired (> 2000ms TTL)+ const result = await ensureSession();+ assert.equal(typeof result, "string", "returns a session id string");+ assert.ok(result.length > 0, "session id is non-empty");+ } finally {+ cleanup();+ }+});++test("ensureSession deduplicates concurrent calls via sessionInflight", async () => {+ installAutoEgo();+ try {+ const p1 = ensureSession();+ const p2 = ensureSession();+ const [r1, r2] = await Promise.all([p1, p2]);+ assert.equal(r1, r2, "both callers get the same session id");+ } finally {+ cleanup();+ }+});++test("ensureSession selects the preferred tab when available", async () => {+ const calls = installAutoEgo({+ tabs: [+ { targetId: "tab-bg", active: false },+ { targetId: "tab-preferred", active: false },+ { targetId: "tab-active", active: true },+ ],+ });+ try {+ setPreferredTarget("tab-preferred");+ await ensureSession();+ const attach = calls.find((c) => c.method === "Target.attachToTarget");+ assert.ok(attach, "Target.attachToTarget was called");+ assert.equal(+ attach.params.targetId,+ "tab-preferred",+ "attaches to preferred tab",+ );+ const pageEnable = calls.find((c) => c.method === "Page.enable");+ assert.ok(pageEnable, "Page.enable was called for the attached session");+ assert.equal(pageEnable.sessionId, `auto-sess-${attach.id}`);+ } finally {+ cleanup();+ }+});++test("ensureSession falls back to the last tab when no active tab is found", async () => {+ const calls = installAutoEgo({+ tabs: [+ { targetId: "tab-1", active: false },+ { targetId: "tab-last", active: false },+ ],+ });+ try {+ await ensureSession();+ const attach = calls.find((c) => c.method === "Target.attachToTarget");+ assert.ok(attach, "Target.attachToTarget was called");+ assert.equal(attach.params.targetId, "tab-last", "falls back to last tab");+ } finally {+ cleanup();+ }+});++test("ensureSession throws when no tabs are available", async () => {+ installAutoEgo({ tabs: [] });+ try {+ await assert.rejects(() => ensureSession(), /no active tab/);+ } finally {+ cleanup();+ }+});++test("ensureSession skips re-attach when targetId matches existing session", async () => {+ const calls = installAutoEgo();+ try {+ state.sessionId = "existing";+ state.sessionTargetId = "tab-1"; // matches the default tab+ state.sessionAt = Date.now() - 3000; // force re-entry past TTL++ await ensureSession();+ const attach = calls.find((c) => c.method === "Target.attachToTarget");+ assert.equal(attach, undefined, "skips re-attach when target unchanged");+ } finally {+ cleanup();+ }+});++/* ------------------------------------------------------------------ */+/* SESSION_LOST retry */+/* ------------------------------------------------------------------ */++test("browserCdp does NOT retry SESSION_LOST for explicit sessionId", async () => {+ const calls = installManualEgo();+ try {+ const promise = browserCdp("Runtime.evaluate", {}, "explicit-sess", 5000);+ globalThis.ego.onCDPMessage(+ JSON.stringify({+ id: calls[0].id,+ error: { message: "Session not found" },+ }),+ );+ await assert.rejects(promise, /Session not found/);+ } finally {+ cleanup();+ }+});++test("browserCdp does NOT retry SESSION_LOST for browser-level methods", async () => {+ const calls = installManualEgo();+ try {+ const promise = browserCdp("Browser.getVersion", {}, undefined, 5000);+ globalThis.ego.onCDPMessage(+ JSON.stringify({ id: calls[0].id, error: { message: "Target closed" } }),+ );+ await assert.rejects(promise, /Target closed/);+ } finally {+ cleanup();+ }+});++/* ------------------------------------------------------------------ */+/* handleSendError — rejects all pending on local send failure */+/* ------------------------------------------------------------------ */++test("handleSendError rejects all pending requests with ego error", async () => {+ installManualEgo();+ try {+ const p1 = browserCdp("Target.getVersion", {}, undefined, 5000);+ const p2 = browserCdp("Browser.getVersion", {}, undefined, 5000);++ globalThis.ego.onSendCDPMessageError(+ "native text",+ "EGO_TASK_SPACE_USER_IN_CONTROL",+ );++ await assert.rejects(p1, (err) => {+ assert.equal(err.error_code, "EGO_TASK_SPACE_USER_IN_CONTROL");+ return true;+ });+ await assert.rejects(p2, (err) => {+ assert.equal(err.error_code, "EGO_TASK_SPACE_USER_IN_CONTROL");+ return true;+ });+ } finally {+ cleanup();+ }+});++/* ------------------------------------------------------------------ */+/* browserSnapshotRefsToRefMap */+/* ------------------------------------------------------------------ */++test("browserSnapshotRefsToRefMap populates ref map from snapshot refs", () => {+ const refMap = {+ _data: new Map(),+ clear() {+ this._data.clear();+ },+ add(id, backendNodeId, role, name) {+ this._data.set(id, { backendNodeId, role, name });+ },+ };+ browserSnapshotRefsToRefMap(refMap, [+ { backendNodeId: 42, role: "button", name: "Submit" },+ { backendNodeId: 100, role: "link", name: "Home" },+ ]);+ assert.equal(refMap._data.size, 2);+ assert.equal(refMap._data.get("42").role, "button");+ assert.equal(refMap._data.get("100").name, "Home");+});++test("browserSnapshotRefsToRefMap clears the map before populating", () => {+ const refMap = {+ _data: new Map([["old", { backendNodeId: 1 }]]),+ clear() {+ this._data.clear();+ },+ add(id, backendNodeId, role, name) {+ this._data.set(id, { backendNodeId, role, name });+ },+ };+ browserSnapshotRefsToRefMap(refMap, [+ { backendNodeId: 5, role: "textbox", name: "" },+ ]);+ assert.equal(refMap._data.size, 1);+ assert.equal(refMap._data.has("old"), false, "old entries cleared");+});++test("browserSnapshotRefsToRefMap skips null, non-object, and missing backendNodeId refs", () => {+ const refMap = {+ _data: new Map(),+ clear() {+ this._data.clear();+ },+ add(id, backendNodeId, role, name) {+ this._data.set(id, { backendNodeId, role, name });+ },+ };+ browserSnapshotRefsToRefMap(refMap, [+ null,+ "not an object",+ { role: "button" },+ { backendNodeId: null, role: "button" },+ { backendNodeId: undefined, role: "button" },+ { backendNodeId: 7, role: "link", name: "ok" },+ ]);+ assert.equal(refMap._data.size, 1, "only the valid ref is added");+ assert.ok(refMap._data.has("7"));+});diff --git a/package/ego-browser/src/cdp-eval.test.mjs b/package/ego-browser/src/cdp-eval.test.mjsnew file mode 100644index 0000000..c2e8cb7--- /dev/null+++ b/package/ego-browser/src/cdp-eval.test.mjs@@ -0,0 +1,468 @@+import test from "node:test";+import assert from "node:assert/strict";++import {+ hasReturnStatement,+ decodeUnserializableJsValue,+ runtimeValue,+ js,+ cdp,+} from "../dist/src/cdp-eval.js";+import { setOverrides } from "../dist/src/state.js";++/* ------------------------------------------------------------------ */+/* hasReturnStatement — the state-machine parser */+/* ------------------------------------------------------------------ */++test("hasReturnStatement detects a bare return", () => {+ assert.equal(hasReturnStatement("return 1"), true);+});++test("hasReturnStatement detects return with semicolon", () => {+ assert.equal(hasReturnStatement("return;"), true);+});++test("hasReturnStatement detects return followed by newline", () => {+ assert.equal(hasReturnStatement("return\n42"), true);+});++test("hasReturnStatement returns false for a plain expression", () => {+ assert.equal(hasReturnStatement("1 + 2"), false);+});++test("hasReturnStatement returns false for empty input", () => {+ assert.equal(hasReturnStatement(""), false);+});++test("hasReturnStatement ignores return inside a single-quoted string", () => {+ assert.equal(hasReturnStatement("'return 1'"), false);+});++test("hasReturnStatement ignores return inside a double-quoted string", () => {+ assert.equal(hasReturnStatement('"return 1"'), false);+});++test("hasReturnStatement ignores return inside a template literal", () => {+ assert.equal(hasReturnStatement("`return 1`"), false);+});++test("hasReturnStatement ignores return after an escaped quote in a string", () => {+ assert.equal(hasReturnStatement("'it\\'s return 1'"), false);+});++test("hasReturnStatement detects return after a closed string", () => {+ assert.equal(hasReturnStatement("'hello' + return"), true);+});++test("hasReturnStatement ignores return inside a line comment", () => {+ assert.equal(hasReturnStatement("// return 1"), false);+});++test("hasReturnStatement detects return after a line comment", () => {+ assert.equal(hasReturnStatement("// comment\nreturn 1"), true);+});++test("hasReturnStatement ignores return inside a block comment", () => {+ assert.equal(hasReturnStatement("/* return 1 */"), false);+});++test("hasReturnStatement detects return after a block comment", () => {+ assert.equal(hasReturnStatement("/* comment */ return 1"), true);+});++test("hasReturnStatement ignores return inside a multiline block comment", () => {+ assert.equal(hasReturnStatement("/*\nreturn 1\n*/ 42"), false);+});++test("hasReturnStatement does not match 'returned' as a variable name", () => {+ assert.equal(hasReturnStatement("var returned = 1"), false);+});++test("hasReturnStatement does not match 'returnCode' as a variable name", () => {+ assert.equal(hasReturnStatement("var returnCode = 1"), false);+});++test("hasReturnStatement does not match 'xreturn' prefix", () => {+ assert.equal(hasReturnStatement("var xreturn = 1"), false);+});++test("hasReturnStatement handles return inside a string with mixed quotes", () => {+ // The outer quotes are double, inner single quotes are content+ assert.equal(hasReturnStatement('"return"'), false);+});++test("hasReturnStatement detects return in complex expression after string", () => {+ assert.equal(hasReturnStatement("const x = 'hello'; return x"), true);+});++/* ------------------------------------------------------------------ */+/* decodeUnserializableJsValue — special CDP value decoding */+/* ------------------------------------------------------------------ */++test("decodeUnserializableJsValue decodes NaN", () => {+ assert.ok(Number.isNaN(decodeUnserializableJsValue("NaN")));+});++test("decodeUnserializableJsValue decodes Infinity", () => {+ assert.equal(+ decodeUnserializableJsValue("Infinity"),+ Number.POSITIVE_INFINITY,+ );+});++test("decodeUnserializableJsValue decodes -Infinity", () => {+ assert.equal(+ decodeUnserializableJsValue("-Infinity"),+ Number.NEGATIVE_INFINITY,+ );+});++test("decodeUnserializableJsValue decodes -0 using Object.is", () => {+ const result = decodeUnserializableJsValue("-0");+ assert.ok(Object.is(result, -0), "result must be negative zero");+});++test("decodeUnserializableJsValue decodes BigInt", () => {+ assert.equal(decodeUnserializableJsValue("42n"), 42n);+});++test("decodeUnserializableJsValue decodes large BigInt", () => {+ assert.equal(+ decodeUnserializableJsValue("9007199254740993n"),+ 9007199254740993n,+ );+});++test("decodeUnserializableJsValue passes through unknown strings", () => {+ assert.equal(decodeUnserializableJsValue("something"), "something");+});++/* ------------------------------------------------------------------ */+/* runtimeValue — CDP RemoteObject to JS value conversion */+/* ------------------------------------------------------------------ */++test("runtimeValue extracts a string value", () => {+ const result = runtimeValue(+ { result: { type: "string", value: "hello" } },+ "'hello'",+ );+ assert.equal(result, "hello");+});++test("runtimeValue extracts a number value", () => {+ const result = runtimeValue({ result: { type: "number", value: 42 } }, "42");+ assert.equal(result, 42);+});++test("runtimeValue extracts a boolean value", () => {+ const result = runtimeValue(+ { result: { type: "boolean", value: true } },+ "true",+ );+ assert.equal(result, true);+});++test("runtimeValue extracts null", () => {+ const result = runtimeValue(+ { result: { type: "object", subtype: "null", value: null } },+ "null",+ );+ assert.equal(result, null);+});++test("runtimeValue extracts undefined when no value key exists", () => {+ const result = runtimeValue({ result: { type: "undefined" } }, "undefined");+ assert.equal(result, null); // falls through to the null default+});++test("runtimeValue decodes unserializable NaN", () => {+ const result = runtimeValue(+ { result: { type: "number", unserializableValue: "NaN" } },+ "NaN",+ );+ assert.ok(Number.isNaN(result));+});++test("runtimeValue decodes unserializable -0", () => {+ const result = runtimeValue(+ { result: { type: "number", unserializableValue: "-0" } },+ "-0",+ );+ assert.ok(Object.is(result, -0));+});++test("runtimeValue throws on exception details", () => {+ assert.throws(+ () =>+ runtimeValue(+ {+ result: { type: "object", subtype: "error" },+ exceptionDetails: {+ text: "Uncaught",+ lineNumber: 0,+ columnNumber: 5,+ },+ },+ "throw new Error()",+ ),+ /JavaScript evaluation failed at line 0, column 5/,+ );+});++test("runtimeValue reports thrown primitive exception values", () => {+ assert.throws(+ () =>+ runtimeValue(+ {+ result: { type: "object", subtype: "error" },+ exceptionDetails: {+ text: "Uncaught",+ exception: { value: "primitive boom" },+ },+ },+ "throw value",+ ),+ /primitive boom/,+ );+});++test("runtimeValue falls back to exception className", () => {+ assert.throws(+ () =>+ runtimeValue(+ {+ result: { type: "object", subtype: "error" },+ exceptionDetails: {+ text: "Uncaught",+ exception: { className: "CustomError" },+ },+ },+ "throw custom",+ ),+ /CustomError/,+ );+});++test("runtimeValue truncates long expressions in error messages", () => {+ const expression = "x".repeat(200);+ const expectedSnippet = `${"x".repeat(157)}...`;+ assert.throws(+ () =>+ runtimeValue(+ {+ result: { type: "object", subtype: "error" },+ exceptionDetails: { text: "Uncaught" },+ },+ expression,+ ),+ (error) => {+ assert.match(+ error.message,+ new RegExp(`expression: ${expectedSnippet}$`),+ );+ assert.doesNotMatch(error.message, new RegExp(`x{158}\\.\\.\\.$`));+ return true;+ },+ );+});++test("runtimeValue throws on result subtype error without exceptionDetails", () => {+ assert.throws(+ () =>+ runtimeValue(+ {+ result: {+ type: "object",+ subtype: "error",+ description: "ReferenceError: x is not defined",+ },+ },+ "x",+ ),+ /JavaScript evaluation failed/,+ );+});++/* ------------------------------------------------------------------ */+/* cdp() — thin wrapper over state.send */+/* ------------------------------------------------------------------ */++test("cdp sends method and params through cdpOverride", async () => {+ const calls = [];+ const restore = setOverrides({+ cdpOverride: async (method, params, sessionId) => {+ calls.push([method, params, sessionId]);+ return { value: "ok" };+ },+ });+ try {+ const result = await cdp("Runtime.evaluate", { expression: "1" });+ assert.equal(result.value, "ok");+ assert.equal(calls.length, 1);+ assert.equal(calls[0][0], "Runtime.evaluate");+ } finally {+ restore();+ }+});++test("cdp tracks Network domain state on enable", async () => {+ const restore = setOverrides({+ cdpOverride: async () => ({}),+ });+ try {+ await cdp("Network.enable");+ // networkDomainEnabled is side-effect on state; we just verify no error+ } finally {+ restore();+ }+});++/* ------------------------------------------------------------------ */+/* js() — expression evaluation with auto-wrapping */+/* ------------------------------------------------------------------ */++test("js auto-wraps expressions with return in an IIFE", async () => {+ let capturedExpression;+ const restore = setOverrides({+ cdpOverride: async (method, params) => {+ if (method === "Runtime.evaluate") {+ capturedExpression = params.expression;+ return { result: { type: "number", value: 42 } };+ }+ return {};+ },+ });+ try {+ const result = await js("return 42");+ assert.equal(result, 42);+ assert.match(capturedExpression, /^\(function\(\)\{/);+ } finally {+ restore();+ }+});++test("js passes plain expressions without IIFE wrapping", async () => {+ let capturedExpression;+ const restore = setOverrides({+ cdpOverride: async (method, params) => {+ if (method === "Runtime.evaluate") {+ capturedExpression = params.expression;+ return { result: { type: "number", value: 3 } };+ }+ return {};+ },+ });+ try {+ const result = await js("1 + 2");+ assert.equal(result, 3);+ assert.equal(capturedExpression, "1 + 2");+ } finally {+ restore();+ }+});++test("js does not wrap when expression already starts with paren", async () => {+ let capturedExpression;+ const restore = setOverrides({+ cdpOverride: async (method, params) => {+ if (method === "Runtime.evaluate") {+ capturedExpression = params.expression;+ return { result: { type: "number", value: 10 } };+ }+ return {};+ },+ });+ try {+ await js("(function(){ return 10 })()");+ assert.equal(capturedExpression, "(function(){ return 10 })()");+ } finally {+ restore();+ }+});++test("js converts a function argument to a string call", async () => {+ let capturedExpression;+ const restore = setOverrides({+ cdpOverride: async (method, params) => {+ if (method === "Runtime.evaluate") {+ capturedExpression = params.expression;+ return { result: { type: "undefined" } };+ }+ return {};+ },+ });+ try {+ await js(function () {+ return 1;+ });+ assert.match(capturedExpression, /^\(function\s*\(\)/);+ assert.match(capturedExpression, /\(\)$/);+ } finally {+ restore();+ }+});++test("js rejects non-string/non-function input", async () => {+ await assert.rejects(+ () => js(123),+ /expects a string expression or function/,+ );+ await assert.rejects(+ () => js(null),+ /expects a string expression or function/,+ );+});++test("js propagates page exceptions", async () => {+ const restore = setOverrides({+ cdpOverride: async (method, params) => {+ if (method === "Runtime.evaluate") {+ return {+ result: {+ type: "object",+ subtype: "error",+ description: "ReferenceError: x is not defined",+ },+ exceptionDetails: {+ text: "Uncaught",+ lineNumber: 0,+ columnNumber: 0,+ exception: { description: "ReferenceError: x is not defined" },+ },+ };+ }+ return {};+ },+ });+ try {+ await assert.rejects(() => js("x"), /ReferenceError/);+ } finally {+ restore();+ }+});++test("js attaches to a target session when targetId is given", async () => {+ const calls = [];+ const restore = setOverrides({+ cdpOverride: async (method, params, sessionId) => {+ calls.push([method, params, sessionId]);+ if (method === "Target.attachToTarget") {+ return { sessionId: "sess-123" };+ }+ if (method === "Runtime.evaluate") {+ return { result: { type: "string", value: "iframe-result" } };+ }+ return {};+ },+ });+ try {+ const result = await js("document.title", "target-abc");+ assert.equal(result, "iframe-result");+ // First call should be attachToTarget, second should be evaluate with the session+ assert.equal(calls[0][0], "Target.attachToTarget");+ assert.equal(calls[1][0], "Runtime.evaluate");+ assert.equal(calls[1][2], "sess-123");+ } finally {+ restore();+ }+});diff --git a/package/ego-browser/src/element-resolver.test.mjs b/package/ego-browser/src/element-resolver.test.mjsindex 885cf76..1b85c77 100644--- a/package/ego-browser/src/element-resolver.test.mjs+++ b/package/ego-browser/src/element-resolver.test.mjs@@ -30,13 +30,13 @@ test("resolveElementCenter computes the center from a valid box model", async ()refMap.add("5", 100, "button", "ok");const cdp = new FakeCDP(async (method) => {if (method === "DOM.getBoxModel") {- return { model: { content: [0, 0, 10, 0, 10, 10, 0, 10] } };+ return { model: { content: [10, 20, 30, 20, 30, 60, 10, 60] } };}return {};});const point = await resolveElementCenter(cdp, undefined, refMap, "@5");- assert.equal(point.x, 5);- assert.equal(point.y, 5);+ assert.equal(point.x, 20);+ assert.equal(point.y, 40);});test("degenerate box model throws transient instead of returning (0,0)", async () => {@@ -119,3 +119,101 @@ test("role locator with degenerate box model throws transient", async () => {},);});++test("css locator matched 0 elements is transient", async () => {+ const cdp = new FakeCDP(async (method) => {+ if (method === "Runtime.evaluate") {+ return {+ result: {+ value: { error: "Locator css:.missing matched 0 elements" },+ },+ };+ }+ return {};+ });+ await assert.rejects(+ () =>+ resolveElementCenter(cdp, undefined, new RefMap(), "loc=css:.missing"),+ (error) => {+ assert.ok(error instanceof ElementResolutionError);+ assert.equal(error.kind, "transient");+ return true;+ },+ );+});++test("css locator matched multiple elements is permanent", async () => {+ const cdp = new FakeCDP(async (method) => {+ if (method === "Runtime.evaluate") {+ return {+ result: {+ value: { error: "Locator css:.duplicate matched 2 elements" },+ },+ };+ }+ return {};+ });+ await assert.rejects(+ () =>+ resolveElementCenter(cdp, undefined, new RefMap(), "loc=css:.duplicate"),+ (error) => {+ assert.ok(error instanceof ElementResolutionError);+ assert.equal(error.kind, "permanent");+ return true;+ },+ );+});++test("role locator matches numeric AX names", async () => {+ const cdp = new FakeCDP(async (method) => {+ if (method === "Accessibility.getFullAXTree") {+ return {+ nodes: [+ {+ role: { value: "button" },+ name: { value: 7 },+ backendDOMNodeId: 100,+ },+ ],+ };+ }+ if (method === "DOM.getBoxModel") {+ return { model: { content: [10, 20, 30, 20, 30, 60, 10, 60] } };+ }+ return {};+ });+ const point = await resolveElementCenter(+ cdp,+ undefined,+ new RefMap(),+ "loc=role:button[name=7]",+ );+ assert.deepEqual(point, { x: 20, y: 40, sessionId: undefined });+});++test("role locator matches boolean AX names", async () => {+ const cdp = new FakeCDP(async (method) => {+ if (method === "Accessibility.getFullAXTree") {+ return {+ nodes: [+ {+ role: { value: "button" },+ name: { value: true },+ backendDOMNodeId: 100,+ },+ ],+ };+ }+ if (method === "DOM.getBoxModel") {+ return { model: { content: [10, 20, 30, 20, 30, 60, 10, 60] } };+ }+ return {};+ });+ const point = await resolveElementCenter(+ cdp,+ undefined,+ new RefMap(),+ "loc=role:button[name=true]",+ );+ assert.deepEqual(point, { x: 20, y: 40, sessionId: undefined });+});diff --git a/package/ego-browser/src/helpers.test.mjs b/package/ego-browser/src/helpers.test.mjsindex 116dba3..723c503 100644--- a/package/ego-browser/src/helpers.test.mjs+++ b/package/ego-browser/src/helpers.test.mjs@@ -493,6 +493,40 @@ test("useOrCreateTaskSpace resolves string names before numeric id strings", asyassert.deepEqual(calls, [["listTaskSpaces"], ["useTaskSpace", 8]]);});+test("useOrCreateTaskSpace resolves numeric strings by id when name is absent", async () => {+ const calls = [];+ await withEgo(+ {+ async listTaskSpaces() {+ calls.push(["listTaskSpaces"]);+ return {+ taskSpaces: [+ {+ taskId: "checkout-flow",+ id: 7,+ name: "checkout-flow",+ ownership: "agent",+ },+ ],+ };+ },+ useTaskSpace(id) {+ calls.push(["useTaskSpace", id]);+ return id;+ },+ },+ async () => {+ assert.deepEqual(await useOrCreateTaskSpace("7"), {+ taskId: "checkout-flow",+ id: 7,+ name: "checkout-flow",+ ownership: "agent",+ });+ },+ );+ assert.deepEqual(calls, [["listTaskSpaces"], ["useTaskSpace", 7]]);+});+test("useOrCreateTaskSpace rejects missing numeric ids instead of creating", async () => {const calls = [];await withEgo(