The fastest browser for AI agents to run browser automation, built for sharing your logged-in browser state with your AI agents, like Codex or Claude Code, without disturbing you. Zero cost, zero config.
JavaScript agent-skillsai-agentautomationbrowserbrowser-automationclaude-codecodexhermes-agentskillsskills-sh
feat(ego-browser): compact snapshot output
Autebe48d119a40b
diff --git a/docs/native-bindings-api.md b/docs/native-bindings-api.mdindex 21e65db..46e4e38 100644--- a/docs/native-bindings-api.md+++ b/docs/native-bindings-api.md@@ -379,6 +379,9 @@ Result:}```+When no stable, unique locator is available, omit `loc` from both `refs` and+the textual snapshot. Do not return `unstable` or `ambiguous` as locator values.+If the browser side reports a snapshot error, the promise rejects with an`Error`. The `message` contains the human-readable error, and `error_code`contains a stable code such as `EGO_SNAPSHOT_FAILED`,diff --git a/docs/native-snapshot-ref-requirement.md b/docs/native-snapshot-ref-requirement.mdindex f185c0c..48c52da 100644--- a/docs/native-snapshot-ref-requirement.md+++ b/docs/native-snapshot-ref-requirement.md@@ -1,4 +1,28 @@-# Native snapshot metadata requirements+# Native snapshot requirements++## Compact snapshot text++Please simplify the snapshot tree before serializing `content`:++- Omit text nodes that are empty, whitespace-only (including NBSP), or contain+ only zero-width formatting characters.+- Omit an unnamed `container` with no remaining children.+- Replace an unnamed `container` with its only remaining child.+- Keep unnamed containers with multiple children because they preserve+ grouping.+- Keep named or ref-bearing containers and semantic nodes such as `image`,+ `svg_root`, `canvas`, `iframe`, `root`, list items, and table cells.++The transformation must preserve the order of remaining nodes, refs, stable+locators, URLs, and iframe boundaries. It applies to both viewport and full-page+snapshots. Never remove or rewrite non-empty page text because it is+non-interactive, because its parent container is simplified, or while cleaning+locator metadata.++Acceptance: a fixture containing nested containers, blank text, two sibling+groups, an iframe, an image, an SVG, a canvas, and an empty table cell is+captured twice. The compact output is identical on the second pass, the sibling+groups remain distinct, and every ref still resolves to its original node.## Snapshot refs for iframe content@@ -48,6 +72,7 @@ Please cover at least these cases in native tests:- the same role and name in the top-level document and an iframe;- a locator whose element type does not match the source node.-Return `ambiguous` or `unstable`, or omit the locator, when uniqueness and node-identity cannot both be established. The JS runtime validates advertised-locators and downgrades invalid ones as a compatibility safeguard.+Omit the locator when uniqueness and node identity cannot both be established.+Do not serialize `loc=unstable` or `loc=ambiguous` in `content`, and do not use+those status strings in `refs`. The JS runtime validates advertised locators+and omits invalid ones as a compatibility safeguard.diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-snapshot-locators.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-snapshot-locators.mjsindex 47721c6..10c1f6b 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-snapshot-locators.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-snapshot-locators.mjs@@ -18,7 +18,7 @@ export function pageSnapshotLocatorCase() {.filter((line) => line.includes("locator=duplicate"));assertEqual(duplicateLines.length, 2, "snapshot contains both duplicate links");assert(- duplicateLines.every((line) => line.includes("loc=unstable")),+ duplicateLines.every((line) => !line.includes(", loc=")),"snapshot does not advertise a duplicate href as a stable locator");assertIncludes(diff --git a/package/ego-browser/scripts/repro-popup-foreground.sh b/package/ego-browser/scripts/repro-popup-foreground.shnew file mode 100755index 0000000..e0e9843--- /dev/null+++ b/package/ego-browser/scripts/repro-popup-foreground.sh@@ -0,0 +1,79 @@+#!/usr/bin/env bash++set -euo pipefail++# Minimal macOS reproduction for Ego Lite being activated when a page-created+# popup opens. This deliberately keeps the TaskSpace Agent-owned throughout.+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+PACKAGE_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"+SDK_PATH="${PACKAGE_DIR}/dist/out/index.js"+DEFAULT_EGO_CLI="/Applications/ego lite.app/Contents/Frameworks/ego Framework.framework/Versions/Current/Helpers/ego-browser"+EGO_CLI="${EGO_BROWSER_REAL_E2E_CLI:-${DEFAULT_EGO_CLI}}"++if [[ "$(uname -s)" != "Darwin" ]]; then+ echo "This reproduction currently targets Ego Lite on macOS." >&2+ exit 1+fi++if [[ ! -x "${EGO_CLI}" ]]; then+ echo "Ego Lite CLI was not found at: ${EGO_CLI}" >&2+ echo "Override it with EGO_BROWSER_REAL_E2E_CLI=/path/to/ego-browser" >&2+ exit 1+fi++echo "Building the workspace SDK..."+(cd "${PACKAGE_DIR}" && npm run build)++if [[ ! -f "${SDK_PATH}" ]]; then+ echo "SDK build output was not created at: ${SDK_PATH}" >&2+ exit 1+fi++echo+echo "The popup will open in 5 seconds."+echo "Keep another application in front and watch whether Ego Lite takes focus."+sleep 5++"${EGO_CLI}" nodejs --sdk-path "${SDK_PATH}" <<'EOF'+const task = await taskSpace(`popup foreground reproduction ${Date.now()}`);++try {+ const page = task.page("p1");+ const html = `+ <!doctype html>+ <meta charset="utf-8">+ <title>Ego Lite popup foreground reproduction</title>+ <button id="open-popup">Open popup</button>+ `;++ await page.goto(+ "data:text/html;base64," + Buffer.from(html).toString("base64"),+ );+ await page.evaluate(() => {+ document.querySelector("#open-popup").addEventListener("click", () => {+ window.open("about:blank", "_blank");+ });+ });++ // A trusted browser click makes the site create a popup target. The popup+ // creation is the event under test; no handoff or permission prompt occurs.+ const receipt = await page.click("#open-popup");+ console.log(+ JSON.stringify({+ reproduced: true,+ spaceId: task.spaceId,+ ownership: task.ownership,+ popups: receipt.popups || [],+ }),+ );++ // Leave the result visible briefly, then remove all reproduction state.+ await new Promise((resolve) => setTimeout(resolve, 8_000));+} finally {+ await task.close().catch((error) => {+ console.error(`Cleanup failed for TaskSpace ${task.spaceId}: ${error.message}`);+ });+}+EOF++echo "Reproduction finished; the temporary TaskSpace was cleaned up."diff --git a/package/ego-browser/src/driver/observe.test.mjs b/package/ego-browser/src/driver/observe.test.mjsindex 33f5a47..e5fa10c 100644--- a/package/ego-browser/src/driver/observe.test.mjs+++ b/package/ego-browser/src/driver/observe.test.mjs@@ -8,7 +8,7 @@ import {browserCdp,invalidateSession,} from "../../dist/src/browser-runtime.js";-import { captureScreenshot } from "../../dist/src/driver/observe.js";+import { captureScreenshot, snapshot } from "../../dist/src/driver/observe.js";import { setOverrides } from "../../dist/src/state.js";function withCdpRuntime(fn) {@@ -76,6 +76,34 @@ function withCdpRuntime(fn) {});}+test("snapshot compacts the native result before returning it", async () => {+ const previous = globalThis.ego;+ const calls = [];+ globalThis.ego = {+ async snapshot(options) {+ calls.push(options);+ return {+ content: [+ "root",+ " container",+ " button [ref=1, loc=unstable]",+ ].join("\n"),+ refs: [{ refId: 1, backendNodeId: 1, loc: "unstable" }],+ };+ },+ };++ try {+ const result = await snapshot({ scope: "full_page" });+ assert.deepEqual(calls, [{ scope: "full_page" }]);+ assert.equal(result.content, "root\n button [ref=1]");+ assert.equal(result.refs[0].loc, undefined);+ } finally {+ if (previous === undefined) delete globalThis.ego;+ else globalThis.ego = previous;+ }+});+test("captureScreenshot skips page metric JavaScript while a native dialog is pending", async () => {const writes = [];const restore = setOverrides({diff --git a/package/ego-browser/src/driver/observe.ts b/package/ego-browser/src/driver/observe.tsindex 46d6a24..0bb9cee 100644--- a/package/ego-browser/src/driver/observe.ts+++ b/package/ego-browser/src/driver/observe.ts@@ -14,6 +14,7 @@ import {} from "../browser-runtime.js";import { invokeEgo } from "../ego-errors.js";import { resolveElementCenter } from "../element-resolver.js";+import { compactSnapshotResult } from "../snapshot-result.js";import {browserRefMap,ensureRefMapForRef,@@ -49,6 +50,7 @@ export async function snapshot(options: SnapshotOptions = {}) {const result: any = await invokeEgo("snapshot", () =>browserEgo().snapshot(options),);+ compactSnapshotResult(result);browserSnapshotRefsToRefMap(browserRefMap, result.refs || []);return result;}diff --git a/package/ego-browser/src/snapshot-result.test.mjs b/package/ego-browser/src/snapshot-result.test.mjsindex 51d14d8..b6baf8e 100644--- a/package/ego-browser/src/snapshot-result.test.mjs+++ b/package/ego-browser/src/snapshot-result.test.mjs@@ -2,12 +2,112 @@ import test from "node:test";import assert from "node:assert/strict";import {+ compactSnapshotContent,+ compactSnapshotResult,enrichSnapshotRefFrames,preparePageSnapshotResult,sanitizeSnapshotLocators,validateSnapshotLocator,} from "../dist/src/snapshot-result.js";+test("snapshot compaction removes only redundant text and containers", () => {+ const content = [+ "root",+ " container",+ " container",+ " container",+ " button [ref=1, loc=unstable]",+ ' text "Save"',+ " container",+ ' text "A"',+ ' text "B"',+ " text",+ ' text " "',+ ' text ""',+ ' container "Section"',+ ' text "Title"',+ " container [ref=2, loc=ambiguous]",+ " button [ref=3, loc=css:#confirm]",+ " button [ref=5, loc=css:[loc=unstable]]",+ " anchor [ref=6, loc=unstable, url=https://example.com/item]",+ ' text "literal [ref=9, loc=unstable]"',+ " image",+ " svg_root",+ " canvas",+ " iframe [ref=4, loc=unstable]",+ " root",+ " list",+ " list_item",+ " table",+ " table_row",+ " table_cell",+ ].join("\n");++ const compact = [+ "root",+ " button [ref=1]",+ ' text "Save"',+ " container",+ ' text "A"',+ ' text "B"',+ ' container "Section"',+ ' text "Title"',+ " container [ref=2]",+ " button [ref=3, loc=css:#confirm]",+ " button [ref=5, loc=css:[loc=unstable]]",+ " anchor [ref=6, url=https://example.com/item]",+ ' text "literal [ref=9, loc=unstable]"',+ " image",+ " svg_root",+ " canvas",+ " iframe [ref=4]",+ " root",+ " list",+ " list_item",+ " table",+ " table_row",+ " table_cell",+ ].join("\n");++ assert.equal(compactSnapshotContent(content), compact);+ assert.equal(compactSnapshotContent(compact), compact);+ assert.equal(+ compactSnapshotContent("snapshot unavailable"),+ "snapshot unavailable",+ );+});++test("snapshot compaction omits unusable locator statuses from refs", () => {+ const result = {+ content: [+ "root",+ " button [ref=1, loc=unstable]",+ " button [ref=2, loc=ambiguous]",+ " button [ref=3, loc=css:#save]",+ ].join("\n"),+ refs: [+ { refId: 1, backendNodeId: 1, loc: "unstable" },+ { refId: 2, backendNodeId: 2, loc: "ambiguous" },+ { refId: 3, backendNodeId: 3, loc: "css:#save" },+ ],+ };++ compactSnapshotResult(result);++ assert.equal(+ result.content,+ [+ "root",+ " button [ref=1]",+ " button [ref=2]",+ " button [ref=3, loc=css:#save]",+ ].join("\n"),+ );+ assert.equal(result.refs[0].loc, undefined);+ assert.equal(result.refs[1].loc, undefined);+ assert.equal(result.refs[2].loc, "css:#save");+});+test("snapshot locator validation batches DOM queries and object cleanup", async () => {const calls = [];const services = {@@ -184,7 +284,8 @@ test("role locator validation keeps healthy trees when one frame detaches", asyntest("invalid native snapshot locators are hidden without removing their refs", async () => {const result = {content: [- 'textfield "Prompt" [ref=10, loc=css:input[aria-label="Prompt"]]',+ 'textfield "Prompt" [ref=10, loc=css:#prompt, url=https://example.com/prompt]',+ 'text "literal ref=10, loc=css:#prompt"','button "Save" [ref=11, loc=role:button[name="Save"]]',].join("\n"),refs: [@@ -192,7 +293,7 @@ test("invalid native snapshot locators are hidden without removing their refs",backendNodeId: 10,role: "textfield",name: "Prompt",- loc: 'css:input[aria-label="Prompt"]',+ loc: "css:#prompt",},{backendNodeId: 11,@@ -208,10 +309,15 @@ test("invalid native snapshot locators are hidden without removing their refs",async (ref) => ref.backendNodeId === 11,);- assert.match(result.content, /ref=10, loc=unstable/);- assert.doesNotMatch(result.content, /loc=css:input/);- assert.match(result.content, /ref=11, loc=role:button/);- assert.equal(result.refs[0].loc, "unstable");+ assert.equal(+ result.content,+ [+ 'textfield "Prompt" [ref=10, url=https://example.com/prompt]',+ 'text "literal ref=10, loc=css:#prompt"',+ 'button "Save" [ref=11, loc=role:button[name="Save"]]',+ ].join("\n"),+ );+ assert.equal(result.refs[0].loc, undefined);assert.equal(result.refs[1].loc, 'role:button[name="Save"]');});diff --git a/package/ego-browser/src/snapshot-result.ts b/package/ego-browser/src/snapshot-result.tsindex a6ee308..d406aa3 100644--- a/package/ego-browser/src/snapshot-result.ts+++ b/package/ego-browser/src/snapshot-result.ts@@ -14,6 +14,11 @@ type SnapshotResult = {refs?: SnapshotRef[];};+type SnapshotTreeNode = {+ text: string;+ children: SnapshotTreeNode[];+};+type CdpAdapter = {sendRaw(method: string,@@ -30,6 +35,133 @@ type SnapshotServices = {): Promise<any>;};+/**+ * Remove redundant native snapshot wrappers without changing semantic nodes.+ *+ * Native output uses two-space indentation as its tree encoding. If an older+ * runtime returns another shape, leave it untouched instead of risking a+ * lossy rewrite.+ */+export function compactSnapshotContent(content: string): string {+ if (typeof content !== "string" || content.length === 0) return content;++ const newline = content.includes("\r\n") ? "\r\n" : "\n";+ const trailingNewline = content.endsWith(newline);+ const lines = content.split(/\r?\n/).filter((line) => line.trim().length > 0);+ const rootIndex = lines.findIndex((line) => line.trim() === "root");+ if (rootIndex < 0) return content;++ const roots: SnapshotTreeNode[] = [];+ const stack: Array<{ indent: number; node: SnapshotTreeNode }> = [];+ for (const line of lines.slice(rootIndex)) {+ const indent = line.length - line.trimStart().length;+ if (indent % 2 !== 0) return content;++ const node: SnapshotTreeNode = { text: line.trim(), children: [] };+ while (stack.length && stack.at(-1)!.indent >= indent) stack.pop();+ if (stack.length) stack.at(-1)!.node.children.push(node);+ else roots.push(node);+ stack.push({ indent, node });+ }++ const compacted = roots.flatMap(compactSnapshotNode);+ const rendered = [+ ...lines.slice(0, rootIndex),+ ...renderSnapshotTree(compacted),+ ].join(newline);+ return rendered + (trailingNewline ? newline : "");+}++/** Compact textual content and omit native locator status sentinels. */+export function compactSnapshotResult(result: SnapshotResult): SnapshotResult {+ if (!result || typeof result !== "object") return result;+ if (typeof result.content === "string") {+ result.content = compactSnapshotContent(result.content);+ }+ for (const ref of result.refs || []) {+ if (ref.loc === "unstable" || ref.loc === "ambiguous") delete ref.loc;+ }+ return result;+}++function compactSnapshotNode(node: SnapshotTreeNode): SnapshotTreeNode[] {+ const text = omitUnusableLocatorStatus(node.text);+ const children = node.children.flatMap(compactSnapshotNode);+ if (isEmptySnapshotText(text)) return [];+ if (text === "container" && children.length === 0) return [];+ if (text === "container" && children.length === 1) return children;+ return [{ text, children }];+}++function omitUnusableLocatorStatus(text: string): string {+ const metadataIndex = findSnapshotMetadataStart(text);+ if (metadataIndex < 0) return text;++ const metadata = text.slice(metadataIndex);+ if (!metadata.endsWith("]")) return text;+ const compacted = metadata.replace(+ /^(\[ref=[^,\]]+),\s*loc=(?:unstable|ambiguous)(?=,|\])/,+ "$1",+ );+ return compacted === metadata+ ? text+ : `${text.slice(0, metadataIndex)}${compacted}`;+}++function findSnapshotMetadataStart(text: string): number {+ let quoted = false;+ let escaped = false;+ for (let index = 0; index < text.length; index += 1) {+ const character = text[index];+ if (escaped) {+ escaped = false;+ continue;+ }+ if (quoted && character === "\\") {+ escaped = true;+ continue;+ }+ if (character === '"') {+ quoted = !quoted;+ continue;+ }+ if (+ !quoted &&+ text.startsWith("[ref=", index) &&+ (index === 0 || /\s/.test(text[index - 1]))+ ) {+ return index;+ }+ }+ return -1;+}++function isEmptySnapshotText(text: string): boolean {+ if (text === "text") return true;+ const match = text.match(/^text\s+("(?:\\.|[^"\\])*")$/);+ if (!match) return false;+ try {+ const value = JSON.parse(match[1]);+ return (+ typeof value === "string" && value.replace(/[\s\p{Cf}]/gu, "") === ""+ );+ } catch {+ return false;+ }+}++function renderSnapshotTree(+ nodes: SnapshotTreeNode[],+ depth = 0,+ output: string[] = [],+): string[] {+ for (const node of nodes) {+ output.push(`${" ".repeat(depth)}${node.text}`);+ renderSnapshotTree(node.children, depth + 1, output);+ }+ return output;+}+/*** Add frame provenance that older native snapshots omit.*@@ -93,13 +225,14 @@ export async function validateSnapshotLocator(return valid.has(0);}-/** Replace invalid native stable locators while retaining their short-lived refs. */+/** Omit invalid native stable locators while retaining their short-lived refs. */export async function sanitizeSnapshotLocators(result: SnapshotResult,validator: (ref: SnapshotRef) => Promise<boolean>,): Promise<SnapshotResult> {if (!Array.isArray(result?.refs)) return result;+ const invalidLocators = new Map<string, Set<string>>();for (const ref of result.refs) {const locator = ref?.loc;if (@@ -111,19 +244,58 @@ export async function sanitizeSnapshotLocators(}if (await validator(ref)) continue;- ref.loc = "unstable";+ delete ref.loc;const refId = ref.refId ?? ref.backendNodeId;- if (typeof result.content === "string" && refId !== undefined) {- result.content = result.content.replaceAll(- `ref=${refId}, loc=${locator}`,- `ref=${refId}, loc=unstable`,- );+ if (refId !== undefined) {+ const refLocators = invalidLocators.get(String(refId)) ?? new Set();+ refLocators.add(locator);+ invalidLocators.set(String(refId), refLocators);}}+ if (typeof result.content === "string" && invalidLocators.size > 0) {+ result.content = omitSnapshotLocators(result.content, invalidLocators);+ }return result;}-/** Prepare one native snapshot for the Page API without changing its text shape. */+function omitSnapshotLocators(+ content: string,+ invalidLocators: Map<string, Set<string>>,+): string {+ const newline = content.includes("\r\n") ? "\r\n" : "\n";+ return content+ .split(/\r?\n/)+ .map((line) => omitSnapshotLineLocator(line, invalidLocators))+ .join(newline);+}++function omitSnapshotLineLocator(+ text: string,+ invalidLocators: Map<string, Set<string>>,+): string {+ const metadataIndex = findSnapshotMetadataStart(text);+ if (metadataIndex < 0) return text;++ const metadata = text.slice(metadataIndex);+ if (!metadata.endsWith("]")) return text;+ const prefix = metadata.match(/^\[ref=([^,\]]+),\s*loc=/);+ if (!prefix) return text;++ const candidates = invalidLocators.get(prefix[1]);+ if (!candidates) return text;+ for (const locator of candidates) {+ const locatorEnd = prefix[0].length + locator.length;+ if (+ metadata.startsWith(locator, prefix[0].length) &&+ (metadata[locatorEnd] === "," || metadata[locatorEnd] === "]")+ ) {+ return `${text.slice(0, metadataIndex)}[ref=${prefix[1]}${metadata.slice(locatorEnd)}`;+ }+ }+ return text;+}++/** Add frame provenance and validate stable locators for the Page API. */export async function preparePageSnapshotResult(services: SnapshotServices,pageSessionId: string,diff --git a/skills/ego-browser/SKILL.md b/skills/ego-browser/SKILL.mdindex 2594aaa..0ada1d1 100644--- a/skills/ego-browser/SKILL.md+++ b/skills/ego-browser/SKILL.md@@ -120,16 +120,28 @@ ego-browser provides the following Page API:or Node.js modules from the surrounding heredoc. Define browser-side helpersinside the callback or pass one JSON-serializable value as its second argument.+Work efficiently:++- Each time you observe, collect only the cheapest page state sufficient to+ choose the next action. Use a snapshot for semantic or locator ground truth+ and a screenshot for visual confirmation; do not request both by default.+- If an action does not produce the expected result, inspect the current page+ before deciding whether to retry. Do not blindly repeat it or immediately+ fall back to coordinates or raw CDP.+- Once the page clearly shows the requested result, stop; do not confirm the+ same result through multiple surfaces.+### Semantic pages: snapshot and selectorsPrefer snapshots and semantic selectors for ordinary DOM pages. Use screenshotsand coordinates only when useful DOM semantics are unavailable.-Before choosing an unfamiliar target, take a snapshot. When the next step-depends on an action's result, keep the action, an expected-state wait, and the-next snapshot in the same heredoc. Print the snapshot last so the next round-can act on it directly. If no decision depends on intermediate states, batch-deterministic actions and observe only after the last verified result.+Before choosing an unfamiliar target, take a snapshot. When the current state+is sufficient to plan several actions on the same Page, complete them in one+heredoc, then observe the result once. Observe between actions only when an+intermediate result changes what should happen next. Keep the action sequence,+the wait for its final expected state, and the next snapshot in the same+heredoc. Print the snapshot last so the next round can act on it directly.The final snapshot is the next round's starting view of the changed page;without it, that round usually has to spend a separate browser call observingbefore it can choose the next target, which wastes compute.