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.

fix: unify helper surface, report skipped task-space ops, narrow scroll fallback

Aute2f42ec4e1c59
diff --git a/package/ego-browser/src/driver/observe.ts b/package/ego-browser/src/driver/observe.ts
index fe058f9..cdf76e2 100644
--- a/package/ego-browser/src/driver/observe.ts
+++ b/package/ego-browser/src/driver/observe.ts
@@ -6,7 +6,6 @@ import { cdp, js } from "../cdp-eval.js";
import { pageInfo } from "./nav.js";
import { browserEgo, browserSnapshotRefsToRefMap, drainBrowserEvents, ensureSession, isBrowserRuntime, pendingDialog } from "../browser-runtime.js";
import { resolveElementCenter } from "../element-resolver.js";
-import { withHandle } from "./element-ops.js";
import { browserRefMap, ensureRefMapForRef, registerSnapshotForRefRefresh } from "../ref-state.js";
type SnapshotOptions = {
@@ -62,25 +61,12 @@ export async function elementCenter(selectorOrRef) {
return resolveElementCenter({ sendRaw: cdp }, undefined, browserRefMap, selectorOrRef);
}
-export async function fillElement(selectorOrRef, value) {
- await withHandle(selectorOrRef, async ({ objectId, sessionId }) => {
- await cdp("Runtime.callFunctionOn", {
- functionDeclaration: "function() { this.focus(); }",
- objectId,
- returnByValue: true,
- awaitPromise: false
- }, sessionId);
- await cdp("Runtime.callFunctionOn", {
- functionDeclaration: "function() { this.select && this.select(); this.value = ''; this.dispatchEvent(new Event('input', { bubbles: true })); }",
- objectId,
- returnByValue: true,
- awaitPromise: false
- }, sessionId);
- await cdp("Input.insertText", { text: String(value) }, sessionId);
- });
-}
+// Sequence number for default screenshot file names. Combined with the pid it
+// keeps concurrent agent processes (parallel task spaces) from overwriting each
+// other's shots in the shared tmpdir, and successive shots in one run distinct.
+let screenshotSeq = 0;
-export async function captureScreenshot(path = join(tmpdir(), "ego-browser-shot.png"), options: CaptureScreenshotOptions = {}) {
+export async function captureScreenshot(path = join(tmpdir(), `ego-browser-shot-${process.pid}-${++screenshotSeq}.png`), options: CaptureScreenshotOptions = {}) {
const full = options.full ?? false;
const raw = options.raw ?? false;
const params: any = {
diff --git a/package/ego-browser/src/driver/pointer.test.mjs b/package/ego-browser/src/driver/pointer.test.mjs
index 9402f05..ee6ba82 100644
--- a/package/ego-browser/src/driver/pointer.test.mjs
+++ b/package/ego-browser/src/driver/pointer.test.mjs
@@ -67,13 +67,13 @@ test("scroll defaults to scrolling down (positive deltaY, DOM wheel convention)"
assert.equal(calls[0].params.deltaX, 0);
});
-test("scroll falls back to DOM scrolling when mouseWheel dispatch fails", async () => {
+test("scroll falls back to DOM scrolling only when wheel dispatch is unsupported", async () => {
const calls = [];
const restore = setOverrides({
cdpOverride(method, params, sessionId) {
calls.push({ method, params, sessionId });
if (method === "Input.dispatchMouseEvent") {
- throw new Error("CDP request timed out: Input.dispatchMouseEvent");
+ throw new Error("'Input.dispatchMouseEvent' wasn't found");
}
if (method === "Runtime.evaluate") {
return { result: { value: { x: 0, y: 450 } } };
@@ -99,3 +99,41 @@ test("scroll falls back to DOM scrolling when mouseWheel dispatch fails", async
assert.equal(calls[1].method, "Runtime.evaluate");
assert.match(calls[1].params.expression, /window\.scrollBy/);
});
+
+test("scroll propagates wheel dispatch timeouts instead of silently degrading", async () => {
+ // Regression: any error (including timeouts and "user is controlling") used
+ // to silently fall back to window.scrollBy, which is not equivalent to a
+ // real wheel event and masked the original failure.
+ const calls = [];
+ const restore = setOverrides({
+ cdpOverride(method) {
+ calls.push(method);
+ if (method === "Input.dispatchMouseEvent") {
+ throw new Error("CDP request timed out: Input.dispatchMouseEvent");
+ }
+ return {};
+ }
+ });
+ try {
+ await assert.rejects(() => scroll({ dy: 450 }), /timed out/);
+ } finally {
+ restore();
+ }
+ assert.deepEqual(calls, ["Input.dispatchMouseEvent"]);
+});
+
+test("scroll propagates user-control errors from wheel dispatch", async () => {
+ const restore = setOverrides({
+ cdpOverride(method) {
+ if (method === "Input.dispatchMouseEvent") {
+ throw new Error("user is controlling this task space");
+ }
+ return {};
+ }
+ });
+ try {
+ await assert.rejects(() => scroll(), /user is controlling/);
+ } finally {
+ restore();
+ }
+});
diff --git a/package/ego-browser/src/driver/pointer.ts b/package/ego-browser/src/driver/pointer.ts
index 0d83f54..c1f736d 100644
--- a/package/ego-browser/src/driver/pointer.ts
+++ b/package/ego-browser/src/driver/pointer.ts
@@ -193,11 +193,34 @@ export async function scroll(x: number | ScrollOptions = 0, y: number | ScrollOp
};
try {
await browserCdp("Input.dispatchMouseEvent", params, undefined, 1000);
- } catch {
+ } catch (error) {
+ // Degrade to DOM scrolling only when the target genuinely cannot dispatch
+ // wheel events. Everything else (timeouts, "user is controlling", session
+ // loss) propagates — window.scrollBy is NOT equivalent to a real wheel
+ // event (virtualized lists and inner scroll panes ignore window scrolling),
+ // so a silent fallback would hide the failure behind a different behavior.
+ if (!isWheelDispatchUnsupported(error)) {
+ throw error;
+ }
+ if (!hasWarnedAboutWheelFallback) {
+ hasWarnedAboutWheelFallback = true;
+ const message = error instanceof Error ? error.message : String(error);
+ process.stderr.write(
+ `[ego-browser] scroll(): wheel dispatch unsupported on this target (${message}); ` +
+ `falling back to DOM scrollBy(). Wheel-only behaviors (virtualized lists, inner scroll panes) may not trigger.\n`
+ );
+ }
return scrollBy({ dx: params.deltaX, dy: params.deltaY });
}
}
+let hasWarnedAboutWheelFallback = false;
+
+function isWheelDispatchUnsupported(error: unknown) {
+ const message = error instanceof Error ? error.message : String(error ?? "");
+ return /not (?:supported|implemented)|wasn't found|isn't found|unknown (?:method|command)|method not found/i.test(message);
+}
+
/**
* Scroll the window with DOM APIs. Positive dy scrolls down, negative dy scrolls up
* (same sign convention as scroll()).
diff --git a/package/ego-browser/src/helpers.test.mjs b/package/ego-browser/src/helpers.test.mjs
index 53b8d1e..c2e56bb 100644
--- a/package/ego-browser/src/helpers.test.mjs
+++ b/package/ego-browser/src/helpers.test.mjs
@@ -463,7 +463,8 @@ test("completeTaskSpace claims user-owned spaces before closing", async () => {
return "7 task space closed.";
}
}, async () => {
- await completeTaskSpace("checkout-flow", { keep: false });
+ const result = await completeTaskSpace("checkout-flow", { keep: false });
+ assert.deepEqual(result, { done: true });
});
assert.deepEqual(calls, [
["listTaskSpaces"],
@@ -473,7 +474,7 @@ test("completeTaskSpace claims user-owned spaces before closing", async () => {
]);
});
-test("completeTaskSpace keep true is a no-op for user-owned spaces", async () => {
+test("completeTaskSpace keep true skips user-owned spaces and reports it", async () => {
const calls = [];
await withEgo({
async listTaskSpaces() {
@@ -488,14 +489,15 @@ test("completeTaskSpace keep true is a no-op for user-owned spaces", async () =>
calls.push(["completeTaskSpace"]);
}
}, async () => {
- await completeTaskSpace("checkout-flow", { keep: true });
+ const result = await completeTaskSpace("checkout-flow", { keep: true });
+ assert.deepEqual(result, { done: false, skipped: "user-owned" });
});
assert.deepEqual(calls, [
["listTaskSpaces"]
]);
});
-test("handOffTaskSpace is a no-op for user-owned spaces", async () => {
+test("handOffTaskSpace skips user-owned spaces and reports it", async () => {
const calls = [];
await withEgo({
async listTaskSpaces() {
@@ -510,13 +512,43 @@ test("handOffTaskSpace is a no-op for user-owned spaces", async () => {
calls.push(["handOffTaskSpace"]);
}
}, async () => {
- await handOffTaskSpace("checkout-flow");
+ const result = await handOffTaskSpace("checkout-flow");
+ assert.deepEqual(result, { done: false, skipped: "user-owned" });
});
assert.deepEqual(calls, [
["listTaskSpaces"]
]);
});
+test("handOffTaskSpace reports done for agent-owned spaces", async () => {
+ const calls = [];
+ await withEgo({
+ async listTaskSpaces() {
+ calls.push(["listTaskSpaces"]);
+ return {
+ taskSpaces: [
+ { taskId: "checkout-flow", id: 7, name: "checkout-flow", ownership: "agent" }
+ ]
+ };
+ },
+ async useTaskSpace(id) {
+ calls.push(["useTaskSpace", id]);
+ return id;
+ },
+ async handOffTaskSpace() {
+ calls.push(["handOffTaskSpace"]);
+ }
+ }, async () => {
+ const result = await handOffTaskSpace("checkout-flow");
+ assert.deepEqual(result, { done: true });
+ });
+ assert.deepEqual(calls, [
+ ["listTaskSpaces"],
+ ["useTaskSpace", 7],
+ ["handOffTaskSpace"]
+ ]);
+});
+
test("useOrCreateTaskSpace rejects unknown ownership", async () => {
await withEgo({
async listTaskSpaces() {
diff --git a/package/ego-browser/src/helpers.ts b/package/ego-browser/src/helpers.ts
index d33f327..1764f71 100644
--- a/package/ego-browser/src/helpers.ts
+++ b/package/ego-browser/src/helpers.ts
@@ -1,4 +1,4 @@
-import { existsSync, readdirSync } from "node:fs";
+import { existsSync } from "node:fs";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
@@ -33,11 +33,12 @@ export {
switchTab,
openOrReuseTab,
closeTab,
+ gotoUrl,
gotoAndWait,
ensureRealTab,
iframeTarget
} from "./driver/nav.js";
-export { snapshot, snapshotRaw, snapshotText, captureScreenshot, elementCenter, fillElement, drainEvents } from "./driver/observe.js";
+export { snapshot, snapshotRaw, snapshotText, captureScreenshot, elementCenter, drainEvents } from "./driver/observe.js";
export { wait, waitForLoad, waitForElement, waitForNetworkIdle } from "./driver/waits.js";
export { uploadFile } from "./driver/files.js";
export { browserFetch, serverFetch } from "./http.js";
@@ -54,6 +55,20 @@ export async function listTaskSpaces() {
return normalizeTaskSpaces(assertNoEgoError(await ego.listTaskSpaces(), "listTaskSpaces"));
}
+/*
+ * Task space ownership policy (`ownership`: "agent" | "user").
+ * What each helper does when the target space is user-owned:
+ *
+ * switchTaskSpace -> throws (agent-owned only)
+ * useOrCreateTaskSpace -> claims it (ownership transfers to the agent)
+ * handOffTaskSpace -> skipped, resolves { done: false, skipped: "user-owned" }
+ * completeTaskSpace { keep: true } -> skipped, resolves { done: false, skipped: "user-owned" }
+ * completeTaskSpace { keep: false } -> claims it, then closes it
+ * takeOverTaskSpace / waitForAgentControl -> no ownership check (operates as-is)
+ *
+ * Keep this table in sync with the one in skills/ego-browser/SKILL.md.
+ */
+
/**
* Select an existing task space by id/name for the current Node invocation.
* @param {string|number} nameOrId Task space id or name.
@@ -144,9 +159,12 @@ async function selectTaskSpaceIfProvided(ego, nameOrId?: string | number, op = "
* Finish working on a task space. With `{ keep: true }` the page stays open
* with the agent overlay dismissed so the user can review the result; with
* `{ keep: false }` the task space is closed entirely.
+ * User-owned spaces: `keep:true` is skipped (the user already has the page) and
+ * resolves `{ done: false, skipped: "user-owned" }`; `keep:false` claims the
+ * space first, then closes it.
* @param {string|number} nameOrId Task space id or name.
* @param {{ keep: boolean }} options Required. `keep:true` hands the page to the user; `keep:false` closes the space.
- * @returns {Promise<void>}
+ * @returns {Promise<{done: boolean, skipped?: "user-owned"}>} `{ done: true }` when the space was completed or closed; `{ done: false, skipped: "user-owned" }` when nothing was done.
*/
export async function completeTaskSpace(nameOrId: string | number, options: { keep: boolean }) {
if ((typeof nameOrId !== "string" && typeof nameOrId !== "number") || nameOrId === "") {
@@ -165,7 +183,9 @@ export async function completeTaskSpace(nameOrId: string | number, options: { ke
throw new Error(`task space not found: ${nameOrId}`);
}
if (options.keep) {
- if (match.ownership === "user") return;
+ if (match.ownership === "user") {
+ return { done: false, skipped: "user-owned" as const };
+ }
await selectTaskSpace(ego, match, "completeTaskSpace");
if (typeof ego.completeTaskSpace !== "function") {
throw new Error("completeTaskSpace requires ego.completeTaskSpace");
@@ -182,12 +202,15 @@ export async function completeTaskSpace(nameOrId: string | number, options: { ke
}
assertNoEgoError(await ego.closeTaskSpace(), "completeTaskSpace");
}
+ return { done: true };
}
/**
* Hand off a task space back to the user, hiding the agent overlay.
+ * User-owned spaces are skipped (the user already controls them) and resolve
+ * `{ done: false, skipped: "user-owned" }`.
* @param {string|number} [nameOrId] Task space id or name. If provided, switches to that space first.
- * @returns {Promise<void>}
+ * @returns {Promise<{done: boolean, skipped?: "user-owned"}>} `{ done: true }` when control was handed off; `{ done: false, skipped: "user-owned" }` when nothing was done.
*/
export async function handOffTaskSpace(nameOrId?: string | number) {
const ego = globalThis.ego;
@@ -196,10 +219,13 @@ export async function handOffTaskSpace(nameOrId?: string | number) {
}
if (nameOrId !== undefined) {
const match = await findTaskSpace(nameOrId);
- if (match.ownership === "user") return;
+ if (match.ownership === "user") {
+ return { done: false, skipped: "user-owned" as const };
+ }
await selectTaskSpace(ego, match, "handOffTaskSpace");
}
assertNoEgoError(await ego.handOffTaskSpace(), "handOffTaskSpace");
+ return { done: true };
}
/**
@@ -270,29 +296,6 @@ export async function waitForAgentControl(nameOrId: string | number, options: {
}
}
-/**
- * Navigate the current tab to a URL and include matching site skill hints when enabled.
- * @param {string} url URL to navigate to.
- * @returns {Promise<object>} CDP navigation result, optionally with domain_skills.
- */
-export async function gotoUrl(url) {
- const result = await nav.gotoUrl(url);
- if (process.env.EGO_BROWSER_DOMAIN_SKILLS !== "1") {
- return result;
- }
- const host = new URL(url).hostname.replace(/^www\./, "").split(".")[0];
- const dir = join(state.agentWorkspace(), "domain-skills", host);
- if (!existsSync(dir)) {
- return result;
- }
- const skills = readdirSync(dir, { recursive: true })
- .filter((file) => String(file).endsWith(".md"))
- .map((file) => String(file).split("/").at(-1))
- .sort()
- .slice(0, 10);
- return { ...result, domain_skills: skills };
-}
-
function normalizeTaskSpaces(raw) {
if (Array.isArray(raw?.taskSpaces)) {
return raw.taskSpaces.map(normalizeTaskSpace).filter(Boolean);
@@ -411,7 +414,6 @@ export function helperContext(extra: any = {}) {
js,
serverFetch,
browserFetch,
- gotoUrl,
siteSkills,
siteSkillsForUrl,
runSiteTool,
diff --git a/package/ego-browser/src/run.ts b/package/ego-browser/src/run.ts
index 099120f..918931e 100644
--- a/package/ego-browser/src/run.ts
+++ b/package/ego-browser/src/run.ts
@@ -109,24 +109,16 @@ async function execute(code: string, stdout: WritableLike) {
export async function executionContext(stdout: WritableLike = processStdout) {
const agentHelpers = await helpers.loadAgentHelpers();
- const context = publicContext({ ...helpers, ...agentHelpers });
- context.cliLog = (...args) => {
+ // Single source of truth for the agent-facing surface: the same helperContext()
+ // that installEgoSdk() exposes in the browser runtime, so the CLI and SDK paths
+ // cannot drift apart (and `help` exists in both).
+ const context: Record<string, any> = helpers.helperContext(agentHelpers);
+ context.cliLog = (...args: unknown[]) => {
write(stdout, `${args.map(formatCliLogValue).join(" ")}\n`);
};
return context;
}
-function publicContext(moduleLike: Record<string, any>) {
- const out: Record<string, any> = {};
- for (const [name, value] of Object.entries(moduleLike)) {
- if (name === "__testing" || name.startsWith("_")) {
- continue;
- }
- out[name] = value;
- }
- return out;
-}
-
function readAll(stream: ReadableLike) {
return new Promise<string>((resolve, reject) => {
let data = "";
diff --git a/package/ego-browser/src/taskspace-e2e.test.mjs b/package/ego-browser/src/taskspace-e2e.test.mjs
index 2d37522..c9b8314 100644
--- a/package/ego-browser/src/taskspace-e2e.test.mjs
+++ b/package/ego-browser/src/taskspace-e2e.test.mjs
@@ -180,6 +180,28 @@ test("taskspace e2e exposes newTaskSpace but not claimTaskSpace as a helper", as
});
});
+test("cli e2e exposes the unified helperContext surface (help present, internals hidden)", async () => {
+ const ego = new FakeEgo();
+ const result = await runTaskspaceScript(ego, `
+ cliLog(JSON.stringify({
+ helpType: typeof help,
+ helpResultType: typeof help("click"),
+ newTabType: typeof newTab,
+ helperContextType: typeof helperContext,
+ loadAgentHelpersType: typeof loadAgentHelpers
+ }));
+ `);
+
+ assert.equal(result.exitCode, 0);
+ assert.deepEqual(firstJsonLine(result.stdout), {
+ helpType: "function",
+ helpResultType: "string",
+ newTabType: "undefined",
+ helperContextType: "undefined",
+ loadAgentHelpersType: "undefined"
+ });
+});
+
test("taskspace e2e rejects explicit use of a user-owned task space", async () => {
const ego = new FakeEgo([
{ taskId: "checkout-flow", id: 7, name: "checkout-flow", createdBy: "user", ownership: "user" }
diff --git a/skills/ego-browser/SKILL.md b/skills/ego-browser/SKILL.md
index c54c3ad..519c5c9 100644
--- a/skills/ego-browser/SKILL.md
+++ b/skills/ego-browser/SKILL.md
@@ -63,6 +63,19 @@ Use a descriptive string name for a new task space. Prefer using the numeric `id
To continue work from an existing user-owned task space, use `listTaskSpaces()` to find the space, call `useOrCreateTaskSpace(id)` to claim it, then use `listTabs()` and `switchTab(targetId)` to select the exact tab before acting. This is different from resuming a handoff from your own prior task space, which starts with `takeOverTaskSpace(nameOrId)`.
+**Ownership policy** — every task space has `ownership: 'agent' | 'user'`; the helpers treat user-owned spaces differently:
+
+| Helper | When the target space is user-owned |
+|---|---|
+| `switchTaskSpace` | throws — agent-owned spaces only |
+| `useOrCreateTaskSpace` | claims it (ownership transfers to the agent) |
+| `handOffTaskSpace` | skipped — resolves `{ done: false, skipped: 'user-owned' }` |
+| `completeTaskSpace(…, { keep: true })` | skipped — resolves `{ done: false, skipped: 'user-owned' }` |
+| `completeTaskSpace(…, { keep: false })` | claims it, then closes it |
+| `takeOverTaskSpace` / `waitForAgentControl` | no ownership check |
+
+`handOffTaskSpace` and `completeTaskSpace` resolve `{ done: true }` when the operation actually happened. Check `done` before telling the user the handoff/cleanup is finished — a `skipped` result usually means you targeted a space that was never yours.
+
**`completeTaskSpace(nameOrId, { keep })` must occupy its own dedicated final heredoc, and run only after a prior heredoc's output has confirmed the task is genuinely done.** `keep` is required: pass `false` to close the space, or `true` to complete the space and leave the page visible to the user.
When passing a string that may create a new task space, the string should reflect the task's intent (e.g. `'search github issues'`); don't use literal placeholders.