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 target-scoped page actions and popup adoption
Aute661cd484aa7c
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjsindex 9bcc21a..04127e7 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs@@ -11,6 +11,7 @@ import { runtimeRegressionCase } from "./runtime-regression.mjs";import { eventIsolationCase } from "./event-isolation.mjs";import {pageAdoptionCase,+ pageActionsAndPopupCase,pageBasicOperationsCase,pageBudgetCase,pageLabelCloseCase,@@ -48,4 +49,5 @@ export const e2eCases = [{ name: "page inventory and budget", body: pageBudgetCase },{ name: "page adoption and release", body: pageAdoptionCase },{ name: "page basic operations", body: pageBasicOperationsCase },+ { name: "page actions and popup adoption", body: pageActionsAndPopupCase },];diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjsindex d5805c1..68eee70 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs@@ -242,3 +242,70 @@ export function pageBasicOperationsCase() {await second.close();`;}++export function pageActionsAndPopupCase() {+ return `+ const task = await taskSpace(taskName);+ await openOrReuseTab(baseUrl + "/?page-actions=unknown", {+ wait: true,+ timeout: 10,+ });+ const unknownBefore = (await task.listPages())+ .filter((item) => item.label === undefined)+ .map((item) => item.targetId);+ const source = await task.newPage(baseUrl + "/?page-actions=source", {+ as: "page-actions-source",+ });+ const comparison = await task.newPage(baseUrl + "/secondary?page-actions=comparison", {+ as: "page-actions-comparison",+ });+ const budgetFiller = await task.newPage(baseUrl + "/secondary?page-actions=budget", {+ as: "page-actions-budget",+ });++ assertEqual((await currentTab()).targetId, budgetFiller.targetId, "the budget page starts active");+ assertEqual(await source.fill("#text-input", "page-filled").then(() => source.evaluate("document.querySelector('#text-input').value")), "page-filled", "page.fill writes into the addressed page");+ assertEqual((await currentTab()).targetId, budgetFiller.targetId, "page.fill does not activate its page");++ await source.evaluate((popupUrl) => {+ const link = document.createElement("a");+ link.id = "page-popup-link";+ link.href = popupUrl;+ link.target = "_blank";+ link.textContent = "Open managed popup";+ document.body.append(link);+ }, baseUrl + "/secondary?page-actions=popup");+ const receipt = await source.click("#page-popup-link");++ assertEqual(receipt.popups.length, 1, "page.click reports the popup it opened");+ const popup = receipt.popups[0];+ assertEqual(typeof popup.label, "string", "the popup receives a durable label");+ assertIncludes(+ await task.page(popup.label).url(),+ "page-actions=popup",+ "the receipt label resolves the popup Page"+ );+ const inventory = await task.listPages();+ assertEqual(+ inventory.find((item) => item.targetId === popup.targetId).openedBy,+ "agent",+ "the popup is recorded as agent-created"+ );+ assert(+ unknownBefore.every(+ (targetId) => inventory.find((item) => item.targetId === targetId)?.label === undefined+ ),+ "tabs that existed before the action remain untracked"+ );+ await assertRejects(+ () => task.newPage(baseUrl + "/secondary?page-actions=blocked"),+ "Page budget reached (4/3)",+ "an adopted popup can exceed the budget and backpressure later newPage calls"+ );++ await task.page(popup.label).close();+ await source.close();+ await comparison.close();+ await budgetFiller.close();+ `;+}diff --git a/package/ego-browser/src/driver/page-actions.ts b/package/ego-browser/src/driver/page-actions.tsnew file mode 100644index 0000000..487d888--- /dev/null+++ b/package/ego-browser/src/driver/page-actions.ts@@ -0,0 +1,378 @@+import { runtimeValue } from "../cdp-eval.js";+import { resolveElementObjectId } from "../element-resolver.js";+import { parseRef, RefMap } from "../ref-map.js";++type PageActionServices = {+ cdp(+ method: string,+ params?: Record<string, unknown>,+ sessionId?: string,+ timeoutMs?: number,+ ): Promise<any>;+ sleep(ms: number): Promise<void>;+};++type MouseButton = "left" | "middle" | "right";++export type PageClickOptions = {+ button?: MouseButton;+ clickCount?: number;+ position?: { x: number; y: number };+};++export type PageFillOptions = {+ clearFirst?: boolean;+};++const INPUT_EVENT_DELAY_MS = 25;+const INPUT_DISPATCH_TIMEOUT_MS = 1_000;++/**+ * Click an element through one explicit target session. Page refs are rejected+ * until the Page model owns a target-scoped ref registry; accepting the legacy+ * process-global map here could silently click the same numeric ref on another+ * tab.+ */+export async function clickInPage(+ services: PageActionServices,+ sessionId: string,+ selector: string,+ options: PageClickOptions = {},+): Promise<void> {+ assertPageSelector(selector);+ const button = options.button ?? "left";+ if (!(["left", "middle", "right"] as string[]).includes(button)) {+ throw new TypeError(`page.click received unsupported button: ${button}`);+ }+ const clickCount = options.clickCount ?? 1;+ if (!Number.isInteger(clickCount) || clickCount < 1) {+ throw new TypeError("page.click clickCount must be a positive integer");+ }+ const target = await resolveElementObjectId(+ cdpAdapter(services),+ sessionId,+ new RefMap(),+ selector,+ );+ try {+ const point = await resolveElementPoint(+ services,+ target.sessionId,+ target.objectId,+ options.position,+ );+ const buttons = pressedButtons(button);+ const probeId = await installClickProbe(+ services,+ target.sessionId,+ target.objectId,+ button,+ );+ let dispatchError: unknown;+ try {+ await services.cdp(+ "Input.dispatchMouseEvent",+ {+ type: "mouseMoved",+ x: point.x,+ y: point.y,+ button: "none",+ buttons: 0,+ },+ target.sessionId,+ INPUT_DISPATCH_TIMEOUT_MS,+ );+ await services.sleep(INPUT_EVENT_DELAY_MS);+ await services.cdp(+ "Input.dispatchMouseEvent",+ {+ type: "mousePressed",+ x: point.x,+ y: point.y,+ button,+ buttons,+ clickCount,+ },+ target.sessionId,+ INPUT_DISPATCH_TIMEOUT_MS,+ );+ await services.sleep(INPUT_EVENT_DELAY_MS);+ await services.cdp(+ "Input.dispatchMouseEvent",+ {+ type: "mouseReleased",+ x: point.x,+ y: point.y,+ button,+ buttons: 0,+ clickCount,+ },+ target.sessionId,+ INPUT_DISPATCH_TIMEOUT_MS,+ );+ } catch (error) {+ if (!isInputDispatchTimeout(error)) throw error;+ dispatchError = error;+ }+ const completed = await finishClickProbe(+ services,+ target.sessionId,+ target.objectId,+ point,+ probeId,+ button,+ clickCount,+ );+ if (dispatchError && !completed) throw dispatchError;+ } finally {+ await services+ .cdp(+ "Runtime.releaseObject",+ { objectId: target.objectId },+ target.sessionId,+ )+ .catch(() => {});+ }+}++/** Focus, replace, and notify an input-like element in one target session. */+export async function fillInPage(+ services: PageActionServices,+ sessionId: string,+ selector: string,+ value: string,+ options: PageFillOptions = {},+): Promise<void> {+ assertPageSelector(selector);+ if (typeof value !== "string") {+ throw new TypeError("page.fill value must be a string");+ }+ const clearFirst = options.clearFirst ?? true;+ if (typeof clearFirst !== "boolean") {+ throw new TypeError("page.fill clearFirst must be a boolean");+ }++ const resolved = await resolveElementObjectId(+ cdpAdapter(services),+ sessionId,+ new RefMap(),+ selector,+ );+ try {+ await services.cdp(+ "Runtime.callFunctionOn",+ {+ functionDeclaration: clearFirst+ ? "function(){this.focus(); if(typeof this.select==='function') this.select();}"+ : "function(){this.focus();}",+ objectId: resolved.objectId,+ returnByValue: true,+ awaitPromise: false,+ },+ resolved.sessionId,+ );+ if (clearFirst) {+ await services.cdp(+ "Runtime.callFunctionOn",+ {+ functionDeclaration:+ "function(){this.value=''; this.dispatchEvent(new Event('input',{bubbles:true}));}",+ objectId: resolved.objectId,+ returnByValue: true,+ awaitPromise: false,+ },+ resolved.sessionId,+ );+ }+ await services.cdp("Input.insertText", { text: value }, resolved.sessionId);+ await services.cdp(+ "Runtime.callFunctionOn",+ {+ functionDeclaration:+ "function(){this.dispatchEvent(new Event('input',{bubbles:true})); this.dispatchEvent(new Event('change',{bubbles:true}));}",+ objectId: resolved.objectId,+ returnByValue: true,+ awaitPromise: false,+ },+ resolved.sessionId,+ );+ } finally {+ await services+ .cdp(+ "Runtime.releaseObject",+ { objectId: resolved.objectId },+ resolved.sessionId,+ )+ .catch(() => {});+ }+}++async function resolveElementPoint(+ services: PageActionServices,+ sessionId: string,+ objectId: string,+ position?: { x: number; y: number },+): Promise<{ x: number; y: number }> {+ if (+ position !== undefined &&+ (!position ||+ typeof position !== "object" ||+ !Number.isFinite(position.x) ||+ !Number.isFinite(position.y))+ ) {+ throw new TypeError("page.click position requires finite x and y offsets");+ }+ const expression = position+ ? "function(position){const rect=this.getBoundingClientRect(); return {x:rect.x+position.x,y:rect.y+position.y};}"+ : "function(){const rect=this.getBoundingClientRect(); return {x:rect.x+rect.width/2,y:rect.y+rect.height/2};}";+ const response = await services.cdp(+ "Runtime.callFunctionOn",+ {+ functionDeclaration: expression,+ objectId,+ arguments: position ? [{ value: position }] : [],+ returnByValue: true,+ awaitPromise: false,+ },+ sessionId,+ );+ const point = runtimeValue(response, expression);+ if (!Number.isFinite(point?.x) || !Number.isFinite(point?.y)) {+ throw new Error("page.click could not resolve the element position");+ }+ return point;+}++async function installClickProbe(+ services: PageActionServices,+ sessionId: string,+ objectId: string,+ button: MouseButton,+): Promise<string | null> {+ const id = `page_click_${Date.now()}_${Math.random().toString(16).slice(2)}`;+ const eventName = clickEventName(button);+ try {+ const response = await services.cdp(+ "Runtime.callFunctionOn",+ {+ functionDeclaration: `function(id, eventName) {+ const target = this;+ window.__egoBrowserInputProbes ||= {};+ const probe = { seen: false, target };+ probe.handler = (event) => {+ if (event.isTrusted && target && (event.target === target || target.contains(event.target))) {+ probe.seen = true;+ }+ };+ document.addEventListener(eventName, probe.handler, true);+ window.__egoBrowserInputProbes[id] = probe;+ return true;+ }`,+ objectId,+ arguments: [{ value: id }, { value: eventName }],+ returnByValue: true,+ awaitPromise: false,+ },+ sessionId,+ );+ return response.result?.value ? id : null;+ } catch {+ return null;+ }+}++async function finishClickProbe(+ services: PageActionServices,+ sessionId: string,+ objectId: string,+ point: { x: number; y: number },+ id: string | null,+ button: MouseButton,+ clickCount: number,+): Promise<boolean> {+ if (!id) return false;+ await services.sleep(50);+ const mouseButton = button === "left" ? 0 : button === "middle" ? 1 : 2;+ const buttons = pressedButtons(button);+ const eventName = clickEventName(button);+ try {+ const response = await services.cdp(+ "Runtime.callFunctionOn",+ {+ functionDeclaration: `function(id, eventName) {+ const probes = window.__egoBrowserInputProbes || {};+ const probe = probes[id];+ if (probe) {+ document.removeEventListener(eventName, probe.handler, true);+ delete probes[id];+ if (probe.seen) return { seen: true, fallback: false };+ }+ const target = probe?.target || this;+ const init = {+ bubbles: true,+ cancelable: true,+ view: window,+ clientX: ${JSON.stringify(point.x)},+ clientY: ${JSON.stringify(point.y)},+ button: ${JSON.stringify(mouseButton)},+ };+ target.dispatchEvent(new MouseEvent("mousemove", { ...init, buttons: 0, detail: 0 }));+ target.dispatchEvent(new MouseEvent("mousedown", { ...init, buttons: ${JSON.stringify(buttons)}, detail: ${JSON.stringify(clickCount)} }));+ target.dispatchEvent(new MouseEvent("mouseup", { ...init, buttons: 0, detail: ${JSON.stringify(clickCount)} }));+ target.dispatchEvent(new MouseEvent(eventName, { ...init, buttons: 0, detail: ${JSON.stringify(clickCount)} }));+ if (eventName === "click" && ${JSON.stringify(clickCount)} > 1) {+ target.dispatchEvent(new MouseEvent("dblclick", { ...init, buttons: 0, detail: 2 }));+ }+ return { seen: false, fallback: true };+ }`,+ objectId,+ arguments: [{ value: id }, { value: eventName }],+ returnByValue: true,+ awaitPromise: false,+ },+ sessionId,+ );+ const value = response.result?.value;+ return Boolean(value?.seen || value?.fallback);+ } catch {+ return false;+ }+}++function assertPageSelector(selector: unknown): asserts selector is string {+ if (typeof selector !== "string" || selector.trim().length === 0) {+ throw new TypeError("Page actions require a non-empty selector string");+ }+ if (parseRef(selector)) {+ throw new Error(+ "page-scoped ref support is not available yet; use CSS, xpath=, or loc= for this Page action",+ );+ }+}++function cdpAdapter(services: PageActionServices) {+ return {+ sendRaw(method, params, sessionId) {+ return services.cdp(method, params, sessionId);+ },+ };+}++function pressedButtons(button: MouseButton): number {+ if (button === "left") return 1;+ if (button === "right") return 2;+ return 4;+}++function clickEventName(+ button: MouseButton,+): "click" | "auxclick" | "contextmenu" {+ if (button === "left") return "click";+ if (button === "middle") return "auxclick";+ return "contextmenu";+}++function isInputDispatchTimeout(error: unknown): boolean {+ const message = error instanceof Error ? error.message : String(error ?? "");+ return /CDP request timed out: Input\.dispatchMouseEvent/.test(message);+}diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjsindex b85d7ff..4b9561d 100644--- a/package/ego-browser/src/page-model.test.mjs+++ b/package/ego-browser/src/page-model.test.mjs@@ -23,6 +23,20 @@ function createFixture(rootDir) {let nextTarget = 1;let selectedSpace = null;let activeTarget = null;+ let popupOnNextClick = null;+ let timeoutNextMouseDispatch = false;++ function openPendingPopup() {+ if (!popupOnNextClick) return;+ const targetId = `target-${nextTarget++}`;+ tabs.set(targetId, {+ targetId,+ url: popupOnNextClick,+ title: "Popup",+ active: false,+ });+ popupOnNextClick = null;+ }async function ensureTargetSession(targetId) {assert(tabs.has(targetId), `unknown target ${targetId}`);calls.push(["ensureSession", targetId]);@@ -94,9 +108,34 @@ function createFixture(rootDir) {},};}+ if (params.returnByValue === false) {+ return {+ result: {+ type: "object",+ objectId: `element:${targetId}`,+ },+ };+ }return { result: { type: "string", value: "complete" } };}if (method === "Runtime.callFunctionOn") {+ if (params.functionDeclaration.includes("getBoundingClientRect")) {+ return {+ result: { type: "object", value: { x: 40, y: 60 } },+ };+ }+ if (params.functionDeclaration.includes("const probe = { seen")) {+ return { result: { type: "boolean", value: true } };+ }+ if (params.functionDeclaration.includes("target.dispatchEvent")) {+ openPendingPopup();+ return {+ result: {+ type: "object",+ value: { seen: false, fallback: true },+ },+ };+ }return {result: {type: "object",@@ -105,6 +144,15 @@ function createFixture(rootDir) {};}if (method === "Runtime.releaseObject") return {};+ if (method === "Input.insertText") return {};+ if (method === "Input.dispatchMouseEvent") {+ if (timeoutNextMouseDispatch) {+ timeoutNextMouseDispatch = false;+ throw new Error("CDP request timed out: Input.dispatchMouseEvent");+ }+ if (params.type === "mouseReleased") openPendingPopup();+ return {};+ }if (method === "Target.activateTarget") {activeTarget = params.targetId;return { success: true };@@ -144,6 +192,12 @@ function createFixture(rootDir) {rootDir,services,tabs,+ openPopupOnNextClick(url) {+ popupOnNextClick = url;+ },+ timeoutNextMouseDispatch() {+ timeoutNextMouseDispatch = true;+ },};}@@ -272,6 +326,88 @@ test("Page evaluate rejects ambiguous or non-serializable arguments", async () =});});+test("Page click stays target-scoped and adopts only tabs opened by the action", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a", { pageBudget: 2 });+ const first = await task.newPage("https://example.test/first");+ await task.newPage("https://example.test/second");+ fixture.tabs.set("target-user", {+ targetId: "target-user",+ url: "https://example.test/user",+ title: "Existing user page",+ active: false,+ });+ fixture.openPopupOnNextClick("https://example.test/popup");+ fixture.timeoutNextMouseDispatch();++ const receipt = await first.click("#open-popup");++ assert.deepEqual(receipt, {+ popups: [{ label: "p3", targetId: "target-3" }],+ });+ const inventory = await task.listPages();+ assert.equal(+ inventory.find((item) => item.targetId === "target-user").label,+ undefined,+ "a tab that existed before the action must remain untracked",+ );+ assert.equal(+ inventory.find((item) => item.targetId === "target-3").label,+ "p3",+ "a popup opened by the action is managed even above the budget",+ );+ assert(+ fixture.calls.some(+ ([kind, method, , sessionId]) =>+ kind === "cdp" &&+ method === "Input.dispatchMouseEvent" &&+ sessionId === "session:target-1",+ ),+ );+ assert.equal(fixture.activeTarget(), "target-2");+ await assert.rejects(+ () => task.newPage("https://example.test/blocked"),+ /Page budget reached \(3\/2\)/,+ );+ });+});++test("Page fill uses its target session and reports no popup when none opened", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ const first = await task.newPage("https://example.test/first");+ await task.newPage("https://example.test/second");++ assert.deepEqual(await first.fill("#text-input", "filled"), {});+ const insertText = fixture.calls.find(+ ([kind, method]) => kind === "cdp" && method === "Input.insertText",+ );+ assert.deepEqual(insertText, [+ "cdp",+ "Input.insertText",+ { text: "filled" },+ "session:target-1",+ ]);+ assert.equal(fixture.activeTarget(), "target-2");+ });+});++test("Page actions reject global refs until the page-scoped ref registry exists", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ const page = await task.newPage("https://example.test/first");++ await assert.rejects(+ () => page.click("@21"),+ /page-scoped ref support is not available yet/,+ );+ await assert.rejects(+ () => page.fill("@21", "wrong"),+ /page-scoped ref support is not available yet/,+ );+ });+});+test("close leaves an anchor tab and the next page gets a new label", async () => {await withFixture(async (fixture) => {const task = taskForRound(fixture, "round-a");diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.tsindex 409195f..b694544 100644--- a/package/ego-browser/src/page-model.ts+++ b/package/ego-browser/src/page-model.ts@@ -12,6 +12,12 @@ import {snapshotRaw,type CaptureScreenshotOptions,} from "./driver/observe.js";+import {+ clickInPage,+ fillInPage,+ type PageClickOptions,+ type PageFillOptions,+} from "./driver/page-actions.js";import { assertNoEgoError } from "./ego-errors.js";import {withPage as defaultWithPage,@@ -123,6 +129,10 @@ export type PageInventoryItem = {openedBy: PageOrigin;};+export type PageActionReceipt = {+ popups?: Array<{ label: string; targetId: string }>;+};+export class PageBudgetError extends Error {readonly code = "EGO_PAGE_BUDGET_REACHED";readonly spaceId: number;@@ -505,6 +515,25 @@ export class Page {);}+ async click(+ selector: string,+ options: PageClickOptions = {},+ ): Promise<PageActionReceipt> {+ return this.#runAction((sessionId) =>+ clickInPage(this.#services, sessionId, selector, options),+ );+ }++ async fill(+ selector: string,+ value: string,+ options: PageFillOptions = {},+ ): Promise<PageActionReceipt> {+ return this.#runAction((sessionId) =>+ fillInPage(this.#services, sessionId, selector, value, options),+ );+ }+async close(): Promise<void> {const page = await this.#resolve();await this.#services.gate.withSpace(this.spaceId, async () => {@@ -559,6 +588,48 @@ export class Page {),);}++ async #runAction(+ operation: (sessionId: string) => Promise<void>,+ ): Promise<PageActionReceipt> {+ const page = await this.#resolve();+ return this.#services.gate.withPage(page, async ({ sessionId }) => {+ const before = new Set(+ (await this.#services.listTabs()).map((tab) => tab.targetId),+ );+ let actionError: unknown;+ try {+ await operation(sessionId);+ } catch (error) {+ actionError = error;+ }++ // A popup is normally created synchronously by the input event. A short+ // settle covers native tab-list propagation without turning this into a+ // navigation wait or silently changing the page's active state.+ await this.#services.sleep(50);+ let popupError: unknown;+ const popups: Array<{ label: string; targetId: string }> = [];+ try {+ const after = await this.#services.listTabs();+ for (const tab of after) {+ if (before.has(tab.targetId)) continue;+ const managed = await this.#services.ledger.addPage(+ this.spaceId,+ tab.targetId,+ { openedBy: "agent" },+ );+ popups.push({ label: managed.label, targetId: managed.targetId });+ }+ } catch (error) {+ popupError = error;+ }++ if (actionError) throw actionError;+ if (popupError) throw popupError;+ return popups.length > 0 ? { popups } : {};+ });+ }}async function evaluateInSession<T>(