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
perf(ego-browser): drop fixed settle delays from actions and fail fast on idle pages
Zhuowei Wang864295c4425e
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjsindex ba71913..fba5230 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs@@ -45,6 +45,10 @@ import {import { pageTextLocatorCase } from "./page-text-locators.mjs";import { pageSelectorCompatibilityCase } from "./page-selector-compatibility.mjs";import { pagePopupWaiterCase } from "./page-popup-waiter.mjs";+import {+ pageActionIdleFailFastCase,+ pageActionPopupReceiptCase,+} from "./page-action-latency.mjs";import {concurrentTaskSpaceDownloadCase,pageDownloadCase,@@ -125,6 +129,8 @@ export const e2eCases = [{ name: "page complex evaluate", body: pageComplexEvaluateCase },{ name: "page fetch", body: pageFetchCase },{ name: "page actions and popup adoption", body: pageActionsAndPopupCase },+ { name: "Page action popup receipts", body: pageActionPopupReceiptCase },+ { name: "Page action idle fail-fast", body: pageActionIdleFailFastCase },{ name: "Page click hit target", body: pageClickHitTargetCase },{ name: "Page action motion tolerance", body: pageActionMotionCase },{ name: "Page drag and canvas drawing", body: pageDragAndDrawCase },diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-action-latency.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-action-latency.mjsnew file mode 100644index 0000000..3239817--- /dev/null+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-action-latency.mjs@@ -0,0 +1,209 @@+export function pageActionPopupReceiptCase() {+ return `+ const task = await taskSpace(taskName);+ const page = await newPageAt(task, baseUrl + "/?page=action-latency");+ try {+ const plainReceipt = await page.click("#click-button");+ assertEqual(+ Object.keys(plainReceipt).length,+ 0,+ "an action without a popup returns an empty receipt"+ );++ await page.evaluate((popupUrl) => {+ const button = document.createElement("button");+ button.id = "action-latency-window-open";+ button.textContent = "Open now";+ button.style.cssText = "position:fixed;left:20px;top:20px;z-index:1000";+ button.addEventListener("click", () => window.open(popupUrl, "_blank"));+ document.body.append(button);+ }, baseUrl + "/secondary?action-latency=window-open");+ const windowOpenReceipt = await page.click("#action-latency-window-open");+ assertEqual(+ windowOpenReceipt.popups?.length ?? 0,+ 1,+ "a popup opened synchronously by the click handler is in the receipt"+ );+ assertIncludes(+ await task.page(windowOpenReceipt.popups[0].label).url(),+ "action-latency=window-open",+ "the window.open popup Page is usable from the receipt"+ );+ await task.page(windowOpenReceipt.popups[0].label).close();++ await page.evaluate((popupUrl) => {+ const link = document.createElement("a");+ link.id = "action-latency-blank-link";+ link.href = popupUrl;+ link.target = "_blank";+ link.textContent = "Open in a new tab";+ link.style.cssText = "position:fixed;left:160px;top:20px;z-index:1000";+ document.body.append(link);+ }, baseUrl + "/secondary?action-latency=link");+ const linkReceipt = await page.click("#action-latency-blank-link");+ assertEqual(+ linkReceipt.popups?.length ?? 0,+ 1,+ "a target=_blank link created by the browser after the click is in the receipt"+ );+ assertIncludes(+ await task.page(linkReceipt.popups[0].label).url(),+ "action-latency=link",+ "the link popup Page is usable from the receipt"+ );+ await task.page(linkReceipt.popups[0].label).close();++ await page.evaluate(() => {+ const form = document.createElement("form");+ form.id = "action-latency-form";+ form.style.cssText =+ "position:fixed;left:20px;top:80px;width:360px;background:white;z-index:1000";+ form.innerHTML = [+ '<input id="al-name">',+ '<input id="al-email">',+ '<select id="al-country"><option value="">--</option><option value="us">US</option></select>',+ '<input type="checkbox" id="al-newsletter">',+ '<textarea id="al-message"></textarea>',+ '<input id="al-extra">',+ '<button type="submit" id="al-submit">Send</button>',+ '<div id="al-result"></div>',+ ].join("");+ form.addEventListener("submit", (event) => {+ event.preventDefault();+ document.getElementById("al-result").textContent = "FORM-OK";+ });+ document.body.append(form);+ });+ // Native mouse input can wait up to a second for an occluded window, so+ // only the fill path is timed; each fill used to spend 100ms in fixed+ // settle and verification delays.+ const startedAt = Date.now();+ await page.fill("#al-name", "Ada");+ await page.fill("#al-email", "[email protected]");+ await page.selectOption("#al-country", "us");+ await page.fill("#al-message", "hello");+ await page.fill("#al-extra", "x");+ const fillElapsedMs = Date.now() - startedAt;+ assert(+ fillElapsedMs < 250,+ "four fills and a select complete without fixed settle delays (" + fillElapsedMs + "ms)"+ );+ await page.click("#al-newsletter");+ await page.click("#al-submit");+ await page.waitForFunction(+ () => document.getElementById("al-result").textContent === "FORM-OK"+ );+ assertEqual(+ await page.evaluate(() =>+ [+ document.getElementById("al-name").value,+ document.getElementById("al-email").value,+ document.getElementById("al-country").value,+ String(document.getElementById("al-newsletter").checked),+ document.getElementById("al-message").value,+ document.getElementById("al-extra").value,+ ].join("|")+ ),+ "Ada|[email protected]|us|true|hello|x",+ "every field keeps its value after the fast fill path"+ );+ } finally {+ await page.close();+ }+ `;+}++export function pageActionIdleFailFastCase() {+ return `+ const task = await taskSpace(taskName);+ const page = await newPageAt(task, baseUrl + "/?page=idle-fail-fast");+ try {+ await page.waitForLoadState("networkidle", { timeout: 5_000 });++ let startedAt = Date.now();+ let missingError;+ try {+ await page.click("#action-latency-missing");+ } catch (error) {+ missingError = error;+ }+ const missingElapsedMs = Date.now() - startedAt;+ assertIncludes(+ missingError?.message || "",+ "Selector #action-latency-missing matched 0 elements",+ "a missing target still names the selector and its match count"+ );+ assertIncludes(+ missingError?.message || "",+ "has been idle",+ "the fast failure explains that the page was idle"+ );+ assertIncludes(+ missingError?.message || "",+ "page.waitForSelector()",+ "the fast failure points at the explicit wait"+ );+ assert(+ missingElapsedMs < 2_000,+ "an idle page rejects a missing target well before the 3s action timeout (" + missingElapsedMs + "ms)"+ );++ await page.evaluate(() => {+ setTimeout(() => {+ const button = document.createElement("button");+ button.id = "action-latency-late";+ button.textContent = "Late";+ button.style.cssText = "position:fixed;left:20px;top:20px;z-index:1000";+ button.addEventListener("click", () => {+ button.textContent = "late-clicked";+ });+ document.body.append(button);+ }, 300);+ });+ await page.click("#action-latency-late");+ assertEqual(+ await page.evaluate(() => document.getElementById("action-latency-late").textContent),+ "late-clicked",+ "a target that appears shortly after the action starts is still clicked"+ );++ await page.evaluate((slowUrl) => {+ window.__actionLatencyFetch = fetch(slowUrl).then(() => {+ const button = document.createElement("button");+ button.id = "action-latency-after-fetch";+ button.textContent = "After fetch";+ button.style.cssText = "position:fixed;left:160px;top:20px;z-index:1000";+ button.addEventListener("click", () => {+ button.textContent = "fetch-clicked";+ });+ document.body.append(button);+ });+ }, baseUrl + "/api/slow?ms=1200");+ startedAt = Date.now();+ await page.click("#action-latency-after-fetch");+ const fetchElapsedMs = Date.now() - startedAt;+ assert(+ fetchElapsedMs >= 1_000,+ "an in-flight request keeps the action waiting for its target (" + fetchElapsedMs + "ms)"+ );+ assertEqual(+ await page.evaluate(() => document.getElementById("action-latency-after-fetch").textContent),+ "fetch-clicked",+ "the target that appears after the response is clicked"+ );++ startedAt = Date.now();+ await assertRejects(+ () => page.waitForSelector("#action-latency-never", { timeout: 700 }),+ "page.waitForSelector timed out after 700ms",+ "an explicit wait keeps its full timeout on an idle page"+ );+ assert(+ Date.now() - startedAt >= 650,+ "waitForSelector does not fail fast on an idle page"+ );+ } finally {+ await page.close();+ }+ `;+}diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-media-playback.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-media-playback.mjsindex 2f1d39b..8447bd6 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-media-playback.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-media-playback.mjs@@ -19,6 +19,12 @@ export function pageMediaPlaybackCase() {timeout: 5_000,});await page.click("#video-pause");+ // Media events are queued tasks; the click returns before they fire.+ await page.waitForFunction(+ () => window.__mediaWorkbench.read().video.events.pause >= 1,+ undefined,+ { timeout: 2_000 }+ );const playedVideo = await page.evaluate(() => window.__mediaWorkbench.read().video);assertEqual(playedVideo.paused, true, "video pauses after visibly progressing");assert(playedVideo.currentTime >= 0.15, "video playback advances currentTime");@@ -56,6 +62,12 @@ export function pageMediaPlaybackCase() {await page.click("#audio-seek");await page.click("#audio-volume");+ // The seeked event fires once the seek completes, after the click returns.+ await page.waitForFunction(+ () => window.__mediaWorkbench.read().audio.events.seeked >= 1,+ undefined,+ { timeout: 2_000 }+ );const final = await page.evaluate(() => window.__mediaWorkbench.read());assert(final.audio.currentTime >= 1.15 && final.audio.currentTime <= 1.3,diff --git a/package/ego-browser/skill-body/SKILL.md b/package/ego-browser/skill-body/SKILL.mdindex 04cf508..ea8813e 100644--- a/package/ego-browser/skill-body/SKILL.md+++ b/package/ego-browser/skill-body/SKILL.md@@ -248,8 +248,13 @@ before it can choose the next target, which wastes compute.Wait for the expected result: use `waitForURL()` for navigation,`waitForSelector()` for element state, or `waitForFunction()` for application-state. Avoid fixed delays when an observable condition exists. A snapshot-captures the current moment; it does not wait for the page to become stable.+state. Avoid fixed delays when an observable condition exists. Element actions+such as `click()` and `fill()` wait up to 3 seconds for their target, but give+up early when the selector matches nothing on an idle page (no DOM changes and+no requests in flight), because that target is not about to appear. When an+element is expected to appear later, wait for it with `waitForSelector()`+first. A snapshot captures the current moment; it does not wait for the page+to become stable.`page.snapshot()` captures the current viewport. For content outside it, use`page.snapshot({ scope: "full_page" })`. When the document scrolls past theviewport, the snapshot ends with a `[more content below the viewport: ...]`diff --git a/package/ego-browser/src/browser-runtime.test.mjs b/package/ego-browser/src/browser-runtime.test.mjsindex 72f6bdc..3e58358 100644--- a/package/ego-browser/src/browser-runtime.test.mjs+++ b/package/ego-browser/src/browser-runtime.test.mjs@@ -1046,6 +1046,11 @@ test("auto-attached OOPIFs are instrumented and resumed without waiting for Netwundefined,"resuming does not await the Network.enable response",);+ assert.equal(+ networkActivity(["session:page-main"]).inflight,+ 1,+ "a migrated request stays counted for the parent until the child is enumerated",+ );assert.equal(networkActivity(["session:page-main", "session:frame-child"]).inflight,1,diff --git a/package/ego-browser/src/browser-runtime.ts b/package/ego-browser/src/browser-runtime.tsindex 858fde0..0c8a62f 100644--- a/package/ego-browser/src/browser-runtime.ts+++ b/package/ego-browser/src/browser-runtime.ts@@ -930,6 +930,7 @@ export function networkActivity(sessionIds: string[]): {let inflight = 0;let lastActivityAt = 0;const pendingRequests: string[] = [];+ const counted = new Set<string>();for (const sessionId of new Set(sessionIds)) {const targetId = sessionTargets.get(sessionId);const target = targetId ? targetStates.get(targetId) : undefined;@@ -941,12 +942,21 @@ export function networkActivity(sessionIds: string[]): {tracking = false;continue;}- inflight += target.inflightNetworkRequests.size;- lastActivityAt = Math.max(lastActivityAt, target.lastNetworkActivityAt);- for (const request of target.inflightNetworkRequests.values()) {- pendingRequests.push(- `${request.type || "Other"} ${request.url || request.requestId}`,- );+ // A request migrates to a child frame target the moment that target+ // attaches, which can precede the caller's next frame enumeration. Count+ // the whole subtree so migration never hides an in-flight request.+ for (const treeTargetId of pageTreeTargetIds(targetId!)) {+ if (counted.has(treeTargetId)) continue;+ counted.add(treeTargetId);+ const member = targetStates.get(treeTargetId);+ if (!member) continue;+ inflight += member.inflightNetworkRequests.size;+ lastActivityAt = Math.max(lastActivityAt, member.lastNetworkActivityAt);+ for (const request of member.inflightNetworkRequests.values()) {+ pendingRequests.push(+ `${request.type || "Other"} ${request.url || request.requestId}`,+ );+ }}}return { tracking, inflight, lastActivityAt, pendingRequests };diff --git a/package/ego-browser/src/driver/downloads.test.mjs b/package/ego-browser/src/driver/downloads.test.mjsindex a765336..9b75a65 100644--- a/package/ego-browser/src/driver/downloads.test.mjs+++ b/package/ego-browser/src/driver/downloads.test.mjs@@ -471,3 +471,74 @@ test("the target stays reserved until its Page behavior is restored", async () =await next.dispose();disposeDownloadArtifacts();});++test("a finished download hands the shared behavior to a still-armed target", async () => {+ const calls = [];+ const listeners = new Map();+ const services = {+ async cdp(method, params, sessionId) {+ calls.push({ method, params, sessionId });+ return {};+ },+ subscribePageEvents(targetId, listener) {+ listeners.set(targetId, listener);+ return () => listeners.delete(targetId);+ },+ };+ const first = preparePageDownload(services, "target-a", { timeoutMs: 1_000 });+ const second = preparePageDownload(services, "target-b", {+ timeoutMs: 1_000,+ });+ await first.ready("session-a");+ await second.ready("session-b");+ const pathA = calls.find((c) => c.sessionId === "session-a").params+ .downloadPath;+ const pathB = calls.find((c) => c.sessionId === "session-b").params+ .downloadPath;++ listeners.get("target-a")({+ method: "Page.downloadWillBegin",+ params: {+ guid: "guid-a",+ url: "https://example.test/a",+ suggestedFilename: "a.txt",+ },+ });+ const downloadA = await first.event;+ await writeFile(join(pathA, "a.txt"), "contents-a");+ listeners.get("target-a")({+ method: "Page.downloadProgress",+ params: { guid: "guid-a", state: "completed" },+ });+ await downloadA.path();++ const afterFinish = calls.filter(+ (c) =>+ c.method === "Page.setDownloadBehavior" && c.sessionId !== "session-a",+ );+ assert.deepEqual(+ afterFinish.at(-1),+ {+ method: "Page.setDownloadBehavior",+ params: { behavior: "allow", downloadPath: pathB },+ sessionId: "session-b",+ },+ "finishing the first download re-applies the second target's directory",+ );+ assert.equal(+ calls.some(+ (c) => c.sessionId === "session-a" && c.params.behavior === "default",+ ),+ false,+ "the shared behavior is not reset to default while another target waits",+ );++ await second.dispose();+ assert.equal(+ calls.at(-1).params.behavior,+ "default",+ "the last interception to go restores the default behavior",+ );+ await downloadA.delete();+ disposeDownloadArtifacts();+});diff --git a/package/ego-browser/src/driver/downloads.ts b/package/ego-browser/src/driver/downloads.tsindex 873a418..ced8603 100644--- a/package/ego-browser/src/driver/downloads.ts+++ b/package/ego-browser/src/driver/downloads.ts@@ -38,6 +38,14 @@ export type DownloadInterception = {const artifactDirectories = new Set<string>();const activeInterceptions = new Set<() => void>();const activeDownloadTargets = new Set<string>();+// Page.setDownloadBehavior is applied to the shared browser context, so the+// most recently armed interception wins. Remember every armed interception so+// that one finishing can hand the behavior back to another that still waits,+// instead of resetting to default underneath it.+const armedDownloadBehaviors = new Map<+ string,+ { sessionId: string; downloadPath: string }+>();/*** Arm one Page session for its next download without changing the shared@@ -75,6 +83,21 @@ export function preparePageDownload(const resetBehavior = async () => {const sessions = [...configuredSessions];configuredSessions.clear();+ armedDownloadBehaviors.delete(targetId);+ const stillArmed = [...armedDownloadBehaviors.values()].at(-1);+ if (stillArmed) {+ // Another Page is still waiting for its download: re-apply its+ // directory rather than resetting the shared behavior to default.+ await services+ .cdp(+ "Page.setDownloadBehavior",+ { behavior: "allow", downloadPath: stillArmed.downloadPath },+ stillArmed.sessionId,+ 1_000,+ )+ .catch(() => {});+ return;+ }await Promise.all(sessions.map((sessionId) =>services@@ -198,6 +221,7 @@ export function preparePageDownload(sessionId,);configuredSessions.add(sessionId);+ armedDownloadBehaviors.set(targetId, { sessionId, downloadPath });},event,async dispose(reason = new Error("download waiter was disposed")) {diff --git a/package/ego-browser/src/driver/page-actions.ts b/package/ego-browser/src/driver/page-actions.tsindex 7fbf437..0937d72 100644--- a/package/ego-browser/src/driver/page-actions.ts+++ b/package/ego-browser/src/driver/page-actions.ts@@ -847,6 +847,10 @@ async function verifyFillOutcome(String(result?.type ?? ""),);lastOutcome = outcome;+ // An accepted value is final: a later application reformat is accepted+ // too, so there is nothing to wait for. Only a rejected reading is+ // re-read, because the control may still be propagating the input.+ if (fillOutcomeAccepted(outcome)) return outcome;const reading = `${outcome}\u0000${String(result?.actual ?? "")}`;if (reading === prior) {consecutiveReads += 1;diff --git a/package/ego-browser/src/driver/pointer.ts b/package/ego-browser/src/driver/pointer.tsindex 9170d9a..5281950 100644--- a/package/ego-browser/src/driver/pointer.ts+++ b/package/ego-browser/src/driver/pointer.ts@@ -113,7 +113,12 @@ export async function click(target: MouseTarget, options: ClickOptions = {}) {if (!isInputDispatchTimeout(error)) throw error;dispatchError = error;}- const completed = await finishClickProbe(point, probeId, clickCount);+ const completed = await finishClickProbe(+ point,+ probeId,+ clickCount,+ Boolean(dispatchError),+ );if (dispatchError && !completed) throw dispatchError;}@@ -147,7 +152,11 @@ export async function hover(target: MouseTarget, options: HoverOptions = {}) {if (!isInputDispatchTimeout(error)) throw error;dispatchError = error;}- const completed = await finishHoverProbe(point, probeId);+ const completed = await finishHoverProbe(+ point,+ probeId,+ Boolean(dispatchError),+ );if (dispatchError && !completed) throw dispatchError;}@@ -207,7 +216,12 @@ export async function dragMouse(if (!isInputDispatchTimeout(error)) throw error;dispatchError = error;}- const completed = await finishDragProbe(resolved, probeId, button);+ const completed = await finishDragProbe(+ resolved,+ probeId,+ button,+ Boolean(dispatchError),+ );if (dispatchError && !completed) throw dispatchError;}@@ -250,9 +264,13 @@ async function finishClickProbe(point: Point,id: string | null,clickCount: number,+ settle: boolean,) {if (!id) return false;- await inputEventDelay(50);+ // The renderer dispatches the click before it acknowledges the mouse input,+ // so the probe is already decided once dispatch returned. Only a timed-out+ // dispatch needs a settle before the page is asked whether input arrived.+ if (settle) await inputEventDelay(50);try {const result = await cdp("Runtime.evaluate",@@ -357,9 +375,13 @@ async function installHoverProbe(point: Point) {}}-async function finishHoverProbe(point: Point, id: string | null) {+async function finishHoverProbe(+ point: Point,+ id: string | null,+ settle: boolean,+) {if (!id) return false;- await inputEventDelay(50);+ if (settle) await inputEventDelay(50);try {const result = await cdp("Runtime.evaluate",@@ -402,9 +424,10 @@ async function finishDragProbe(points: Point[],id: string | null,button: MouseButton,+ settle: boolean,) {if (!id) return false;- await inputEventDelay(50);+ if (settle) await inputEventDelay(50);const first = points[0];const last = points.at(-1);try {diff --git a/package/ego-browser/src/page-discovery.ts b/package/ego-browser/src/page-discovery.tsindex fdd70bc..2b389d0 100644--- a/package/ego-browser/src/page-discovery.ts+++ b/package/ego-browser/src/page-discovery.ts@@ -28,7 +28,11 @@ export function recordUnhandledPage(notice: UnhandledPageNotice): void {for (const listener of [...pageNoticeListeners]) listener(merged);}-/** Refresh the URL of an already-discovered Page without creating a new notice. */+/**+ * Refresh the URL of an already-discovered Page without creating a new notice.+ * Listeners observe discoveries only: a popup waiter armed after the Page was+ * discovered must not resolve with it when its URL settles later.+ */export function refreshUnhandledPageNotice(spaceId: number,targetId: string,@@ -37,7 +41,7 @@ export function refreshUnhandledPageNotice(const key = pageKey(spaceId, targetId);const existing = pendingPageNotices.get(key);if (!existing) return;- recordUnhandledPage({ ...existing, url });+ pendingPageNotices.set(key, { ...existing, url });}/** Mark a Page as used during this round so it needs no further guidance. */diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjsindex 3ed5041..54e850a 100644--- a/package/ego-browser/src/page-model.test.mjs+++ b/package/ego-browser/src/page-model.test.mjs@@ -88,6 +88,13 @@ function createFixture(rootDir) {const snapshotOptions = [];const browserEventListeners = new Set();const sleepDurations = [];+ let targetDiscovery = true;+ let domActivity = null;+ let fileInputClicked = false;++ function dispatchBrowserEvent(event) {+ for (const listener of [...browserEventListeners]) listener(event);+ }function openPendingPopup() {if (!popupOnNextClick) return;@@ -99,6 +106,12 @@ function createFixture(rootDir) {active: false,});popupOnNextClick = null;+ dispatchBrowserEvent({+ method: "Target.targetCreated",+ params: {+ targetInfo: { targetId, type: "page", url: tabs.get(targetId).url },+ },+ });}async function ensureTargetSession(targetId) {assert(tabs.has(targetId), `unknown target ${targetId}`);@@ -157,6 +170,19 @@ function createFixture(rootDir) {return { frameId: "frame-1" };}if (method === "Runtime.evaluate") {+ if (params.expression.includes("__egoBrowserFileInputProbe")) {+ const reading = params.expression.includes("probe.seen === true");+ calls.push([+ reading ? "fileInputProbeRead" : "fileInputProbeInstall",+ sessionId,+ ]);+ return {+ result: {+ type: "boolean",+ value: reading ? fileInputClicked : true,+ },+ };+ }if (loseFrameOnNextResolution) {const failure = loseFrameOnNextResolution;loseFrameOnNextResolution = null;@@ -348,6 +374,12 @@ function createFixture(rootDir) {},};}+ if (params.expression.includes("__egoBrowserDomActivity")) {+ calls.push(["domActivityProbe", sessionId]);+ return domActivity+ ? { result: { type: "object", value: domActivity } }+ : { result: { type: "string", value: "complete" } };+ }if (params.returnByValue === false) {if (!elementPresent) {return { result: { type: "undefined" } };@@ -802,6 +834,10 @@ function createFixture(rootDir) {calls.push(["setPreferredTarget", targetId]);},supportsBackgroundPageDiscovery: () => true,+ async ensureTargetDiscovery(spaceId) {+ calls.push(["ensureTargetDiscovery", spaceId]);+ return targetDiscovery;+ },subscribeBrowserEvents(listener) {browserEventListeners.add(listener);return () => browserEventListeners.delete(listener);@@ -828,6 +864,22 @@ function createFixture(rootDir) {openPopupOnNextClick(url) {popupOnNextClick = url;},+ setTargetDiscovery(enabled) {+ targetDiscovery = enabled;+ },+ setDomActivity(value) {+ domActivity = value;+ },+ setFileInputClicked(value) {+ fileInputClicked = value;+ },+ emitFileChooser(value = { backendNodeId: 91 }) {+ activeFileChooserWaiter?.emit(value);+ },+ markNetworkTracked(sessionId, { lastActivityAt = 0 } = {}) {+ networkSessions.add(sessionId);+ networkLastActivityAt.set(sessionId, lastActivityAt);+ },setViewportMetrics(metrics) {viewportMetrics = metrics;},@@ -6611,3 +6663,323 @@ test("newPage never closes a managed page when native returns its target again",);});});++test("an input action without a popup skips tab polling and settle delays", async () => {+ await withFixture(async (fixture) => {+ let tabListCalls = 0;+ const task = taskForRound(fixture, "round-a", {+ async listTabs() {+ tabListCalls += 1;+ return fixture.services.listTabs();+ },+ });+ const page = await openTestPage(task, "https://example.test/source");+ tabListCalls = 0;+ const sleepsBefore = fixture.sleepDurations.length;+ const callsBefore = fixture.calls.length;++ const receipt = await page.click("#plain-button");++ assert.deepEqual(receipt, {});+ assert.equal(tabListCalls, 0, "no popup means no tab list round trips");+ assert.deepEqual(+ fixture.sleepDurations.slice(sleepsBefore),+ [],+ "the action boundary no longer sleeps to settle the tab list",+ );+ const syncCalls = fixture.calls+ .slice(callsBefore)+ .filter(+ ([kind, method, params]) =>+ kind === "cdp" &&+ method === "Runtime.evaluate" &&+ params?.expression === "0",+ );+ assert.equal(+ syncCalls.length,+ 1,+ "one page round trip orders a popup event ahead of the receipt",+ );+ });+});++test("a popup reported by Target.targetCreated is adopted without a settle delay", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ const page = await openTestPage(task, "https://example.test/source");+ const sleepsBefore = fixture.sleepDurations.length;+ fixture.openPopupOnNextClick("https://example.test/popup");++ const receipt = await page.click("#open-popup");++ assert.equal(receipt.popups.length, 1);+ assert.equal(receipt.popups[0].label, "p2");+ assert.equal(+ await task.page("p2").url(),+ "https://example.test/popup",+ "the popup Page is usable from the receipt",+ );+ assert.deepEqual(fixture.sleepDurations.slice(sleepsBefore), []);+ });+});++test("a target created outside this task space is not adopted as a popup", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ const page = await openTestPage(task, "https://example.test/source");+ const baseCdp = fixture.services.cdp;+ fixture.services.cdp = async (method, params, sessionId, timeoutMs) => {+ if (method === "Input.dispatchMouseEvent") {+ // The user opens a tab in another window while the click runs.+ fixture.emitBrowserEvent("Target.targetCreated", {+ targetInfo: {+ targetId: "target-elsewhere",+ type: "page",+ url: "https://example.test/elsewhere",+ },+ });+ }+ return baseCdp(method, params, sessionId, timeoutMs);+ };++ const receipt = await page.click("#plain-button");++ assert.deepEqual(+ receipt,+ {},+ "a foreign target is not in this space's tab list",+ );+ const ledger = await new PageLedgerStore({ rootDir: fixture.rootDir }).read(+ 7,+ );+ assert.equal(+ Object.values(ledger.pages).some(+ (entry) => entry.targetId === "target-elsewhere",+ ),+ false,+ );+ });+});++test("without target discovery the action boundary falls back to tab polling", async () => {+ await withFixture(async (fixture) => {+ fixture.setTargetDiscovery(false);+ const task = taskForRound(fixture, "round-a");+ const page = await openTestPage(task, "https://example.test/source");+ const sleepsBefore = fixture.sleepDurations.length;+ fixture.openPopupOnNextClick("https://example.test/popup");++ const receipt = await page.click("#open-popup");++ assert.equal(receipt.popups.length, 1);+ assert.deepEqual(+ fixture.sleepDurations.slice(sleepsBefore),+ [50],+ "the polling fallback keeps its settle delay",+ );+ });+});++test("a missing action target fails fast once the page is idle", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ const page = await openTestPage(task, "https://example.test/source");+ fixture.markNetworkTracked("session:target-1", { lastActivityAt: 0 });+ fixture.setElementState({ present: false });+ fixture.setDomActivity({+ readyState: "complete",+ visible: true,+ idleMs: 650,+ framesLoading: false,+ });+ const startedAt = fixture.services.now();++ await assert.rejects(+ () => page.click("#nope"),+ (error) => {+ assert.equal(error.name, "ElementResolutionError");+ assert.equal(error.kind, "permanent");+ assert.match(+ error.message,+ /page\.click failed: Selector #nope matched 0 elements/,+ );+ assert.match(error.message, /idle for 650ms/);+ assert.match(error.message, /page\.waitForSelector\(\)/);+ return true;+ },+ );+ assert.equal(+ fixture.services.now() - startedAt,+ 500,+ "the first attempt never gives up; the second attempt proves the page idle",+ );+ const probes = fixture.calls.filter(+ ([kind]) => kind === "domActivityProbe",+ );+ assert.equal(+ probes.length,+ 1,+ "the page is probed only once idle time could have elapsed",+ );+ });+});++test("a missing action target keeps waiting while the page is busy", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ const page = await openTestPage(task, "https://example.test/source");+ fixture.markNetworkTracked("session:target-1", { lastActivityAt: 0 });+ fixture.setElementState({ present: false });++ // Still mutating: the observer saw a change a moment ago.+ fixture.setDomActivity({+ readyState: "complete",+ visible: true,+ idleMs: 120,+ framesLoading: false,+ });+ let startedAt = fixture.services.now();+ await assert.rejects(+ () => page.click("#nope", { timeout: 1_000 }),+ /page\.click timed out after 1000ms: Selector #nope matched 0 elements/,+ );+ assert.equal(fixture.services.now() - startedAt, 1_000);++ // Idle DOM, but a request is in flight.+ fixture.setDomActivity({+ readyState: "complete",+ visible: true,+ idleMs: 900,+ framesLoading: false,+ });+ const baseActivity = fixture.services.networkActivity;+ const task2 = taskForRound(fixture, "round-a", {+ networkActivity(sessionIds) {+ return { ...baseActivity(sessionIds), tracking: true, inflight: 1 };+ },+ });+ const busyPage = task2.page("p1");+ startedAt = fixture.services.now();+ await assert.rejects(+ () => busyPage.click("#nope", { timeout: 1_000 }),+ /page\.click timed out after 1000ms/,+ );+ assert.equal(fixture.services.now() - startedAt, 1_000);++ // Network cannot be observed at all: never fail early.+ const task3 = taskForRound(fixture, "round-a", {+ networkActivity() {+ return { tracking: false, inflight: 0, lastActivityAt: 0 };+ },+ });+ startedAt = fixture.services.now();+ await assert.rejects(+ () => task3.page("p1").click("#nope", { timeout: 1_000 }),+ /page\.click timed out after 1000ms/,+ );+ assert.equal(fixture.services.now() - startedAt, 1_000);+ });+});++test("page.fill returns after the first accepted read-back", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ const page = await openTestPage(task, "https://example.test/source");+ const callsBefore = fixture.calls.length;+ const sleepsBefore = fixture.sleepDurations.length;++ await page.fill("#text-input", "hello");++ const readBacks = fixture.calls+ .slice(callsBefore)+ .filter(+ ([kind, method, params]) =>+ kind === "cdp" &&+ method === "Runtime.callFunctionOn" &&+ params?.functionDeclaration?.includes("readFilledValue"),+ );+ assert.equal(readBacks.length, 1, "an accepted value is not re-read");+ assert.equal(+ fixture.sleepDurations.slice(sleepsBefore).includes(50),+ false,+ "no verification interval is spent on an accepted value",+ );+ assert.equal(fixture.fillText(), "hello");+ });+});++test("a missing action target keeps waiting while the page is hidden", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ const page = await openTestPage(task, "https://example.test/source");+ fixture.markNetworkTracked("session:target-1", { lastActivityAt: 0 });+ fixture.setElementState({ present: false });+ fixture.setDomActivity({+ readyState: "complete",+ visible: false,+ idleMs: 5_000,+ framesLoading: false,+ });+ const startedAt = fixture.services.now();++ await assert.rejects(+ () => page.click("#nope", { timeout: 1_000 }),+ /page\.click timed out after 1000ms: Selector #nope matched 0 elements/,+ );+ assert.equal(fixture.services.now() - startedAt, 1_000);+ });+});++test("a popup waiter ignores the URL refresh of an earlier popup", async () => {+ await withFixture(async (fixture) => {+ resetPageNotices();+ const task = taskForRound(fixture, "round-a");+ const page = await openTestPage(task, "https://example.test/source");+ fixture.openPopupOnNextClick("about:blank");+ const oldReceipt = await page.click("#old-popup-link");+ const oldTargetId = oldReceipt.popups[0].targetId;++ const pending = page.waitForEvent("popup", { timeout: 200 });+ fixture.tabs.get(oldTargetId).url = "https://example.test/old-final";+ fixture.emitBrowserEvent("Target.targetInfoChanged", {+ targetInfo: {+ targetId: oldTargetId,+ type: "page",+ url: "https://example.test/old-final",+ },+ });+ fixture.openPopupOnNextClick("https://example.test/next");+ const nextReceipt = await page.click("#next-popup-link");++ const popup = await pending;+ assert.equal(popup.label, nextReceipt.popups[0].label);+ assert.notEqual(popup.label, oldReceipt.popups[0].label);+ });+});++test("a click that reaches a file input waits for the trailing chooser event", async () => {+ await withFixture(async (fixture) => {+ fixture.setFileInputClicked(true);+ const task = taskForRound(fixture, "round-a", {+ async sleep(ms) {+ fixture.sleepDurations.push(ms);+ // The chooser event lands only after the action acknowledged its input.+ fixture.emitFileChooser();+ },+ });+ const page = await openTestPage(task, "https://example.test/upload-guard");++ await assert.rejects(+ () => page.click("#open-upload"),+ (error) => {+ assert.equal(error.code, "EGO_FILE_CHOOSER_OPENED");+ return true;+ },+ );+ assert.deepEqual(+ fixture.sleepDurations.slice(-1),+ [1_000],+ "a confirmed file-input click waits for the chooser rather than a blind settle",+ );+ });+});diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.tsindex c013a4d..ffc235b 100644--- a/package/ego-browser/src/page-model.ts+++ b/package/ego-browser/src/page-model.ts@@ -167,6 +167,156 @@ function isRetryableResolutionError();}+/** A resolution failure that found nothing to act on, as opposed to a blocked target. */+function isNoMatchResolutionError(error: unknown): error is Error {+ return (+ error instanceof ElementResolutionError &&+ error.kind === "transient" &&+ /matched 0 elements/.test(error.message)+ );+}++type PopupReceiptEntry = { label: string; targetId: string };++type PopupWatch = {+ collect(sessionId: string): Promise<PopupReceiptEntry[]>;+ dispose(): void;+};++type DomActivityProbe = {+ readyState: string;+ visible: boolean;+ idleMs: number;+ framesLoading: boolean;+};++// Installs one MutationObserver per document on first use and reports the+// time since the last observed mutation (zero right after installation). The+// retry loop separately requires a full idle window since the action started.+const DOM_ACTIVITY_PROBE = `(() => {+ const key = "__egoBrowserDomActivity";+ let tracker = window[key];+ if (!tracker) {+ tracker = { last: performance.now(), observer: null };+ try {+ const observer = new MutationObserver(() => {+ tracker.last = performance.now();+ });+ observer.observe(document.documentElement || document, {+ subtree: true,+ childList: true,+ attributes: true,+ characterData: true,+ });+ tracker.observer = observer;+ } catch (error) {+ tracker.observer = null;+ }+ Object.defineProperty(window, key, {+ value: tracker,+ configurable: true,+ enumerable: false,+ writable: true,+ });+ }+ let framesLoading = false;+ for (const frame of document.querySelectorAll("iframe, frame")) {+ try {+ const doc = frame.contentDocument;+ if (doc && doc.readyState !== "complete") framesLoading = true;+ } catch (error) {+ // Cross-origin frames are covered by network tracking.+ }+ }+ return {+ readyState: document.readyState,+ // Hidden documents run throttled timers, so their quiet is not idleness.+ visible: document.visibilityState === "visible",+ idleMs: tracker.observer ? performance.now() - tracker.last : -1,+ framesLoading,+ };+})()`;++// Records, for one guarded action, whether a click reached a file input in+// the main document. A capture listener sees trusted clicks, label clicks and+// scripted clicks on attached inputs (retargeted through shadow roots); a+// detached input created on the fly only receives its own click, so the+// prototype methods are wrapped for the duration of the action. Frames have+// their own documents, so a page with frames reports "unknown".+const FILE_INPUT_PROBE_INSTALL = `(() => {+ const key = "__egoBrowserFileInputProbe";+ const previous = window[key];+ if (previous) previous.restore();+ const proto = HTMLInputElement.prototype;+ const originals = { click: proto.click, showPicker: proto.showPicker };+ const probe = { seen: false, handler: null, restore: null };+ const markIfFile = (input) => {+ if (input instanceof HTMLInputElement && input.type === "file") probe.seen = true;+ };+ probe.handler = (event) => {+ const path = typeof event.composedPath === "function" ? event.composedPath() : [];+ markIfFile(path.length > 0 ? path[0] : event.target);+ };+ document.addEventListener("click", probe.handler, true);+ for (const name of Object.keys(originals)) {+ if (typeof originals[name] !== "function") continue;+ proto[name] = function (...args) {+ markIfFile(this);+ return originals[name].apply(this, args);+ };+ }+ probe.restore = () => {+ document.removeEventListener("click", probe.handler, true);+ for (const name of Object.keys(originals)) {+ if (typeof originals[name] === "function") proto[name] = originals[name];+ }+ delete window[key];+ };+ Object.defineProperty(window, key, {+ value: probe,+ configurable: true,+ enumerable: false,+ writable: true,+ });+ return true;+})()`;+const FILE_INPUT_PROBE_READ = `(() => {+ const key = "__egoBrowserFileInputProbe";+ const probe = window[key];+ if (!probe) return null;+ probe.restore();+ if (probe.seen === true) return true;+ return document.querySelector("iframe, frame") ? null : false;+})()`;++/**+ * Build the Target.setDiscoverTargets enabler. Browser-level commands are+ * routed through the selected task space, so discovery is enabled once per+ * space. A failed or unsupported attempt resolves false and is retried on the+ * next call.+ */+function createTargetDiscoveryEnabler(+ supported: () => boolean,+ cdp: (method: string, params: Record<string, unknown>) => Promise<unknown>,+): (spaceId: number) => Promise<boolean> {+ const enabling = new Map<number, Promise<boolean>>();+ return (spaceId) => {+ if (!supported()) return Promise.resolve(false);+ let pending = enabling.get(spaceId);+ if (!pending) {+ pending = cdp("Target.setDiscoverTargets", { discover: true }).then(+ () => true,+ () => {+ enabling.delete(spaceId);+ return false;+ },+ );+ enabling.set(spaceId, pending);+ }+ return pending;+ };+}+type AdoptPageOptions = {as?: string;};@@ -384,6 +534,12 @@ type PageModelServices = {invalidateSession(targetId: string): void;setPreferredTarget(targetId: string): void;supportsBackgroundPageDiscovery(): boolean;+ /**+ * Enable target discovery once per task space, under that space's gate+ * selection. Resolves false when the runtime cannot deliver Target.*+ * events, so callers fall back to polling the tab list.+ */+ ensureTargetDiscovery(spaceId: number): Promise<boolean>;subscribeBrowserEvents(listener: (event: any) => void): () => void;subscribePageEvents(targetId: string,@@ -452,6 +608,31 @@ const CREATED_SPACE_TAB_TIMEOUT_MS = 2_000;const CREATED_SPACE_TAB_POLL_INTERVAL_MS = 50;const DEFAULT_PAGE_ACTION_TIMEOUT_MS = 3_000;const PAGE_ACTION_RESOLUTION_RETRY_MS = 500;+// A missing action target stops being retried once the page has shown no DOM+// mutation and no network activity for this long; a page that is still+// loading or rendering keeps the full action timeout.+const MISSING_TARGET_IDLE_MS = 500;+const MISSING_TARGET_PROBE_TIMEOUT_MS = 1_000;+// One page round trip after an action orders a popup's Target.targetCreated+// event ahead of the response, so no settle delay is needed.+const POPUP_SYNC_TIMEOUT_MS = 1_000;+// The native tab list can lag the CDP target event by a few milliseconds.+const POPUP_TAB_LIST_RETRIES = 10;+const POPUP_TAB_LIST_RETRY_MS = 20;+// Legacy settle for runtimes that cannot deliver Target.* events.+const POPUP_POLL_SETTLE_MS = 50;+// After a navigation commits, cross-process iframes are still being created+// and auto-attached. Enumerating frame sessions in that window can attach a+// second session to a child and drop its in-flight requests from network+// tracking (see ensureFrameSessions), so navigation keeps the settle that the+// previous tab-list diff provided. Input actions do not need it.+const NAVIGATION_FRAME_SETTLE_MS = 60;+// A file chooser request can trail the input acknowledgement. When the page+// reports that the action clicked a file input, wait for the chooser event+// (it resolves the race early); when the page could not be asked, fall back+// to the short settle the tab-list diff used to provide.+const FILE_CHOOSER_OPEN_WAIT_MS = 1_000;+const FILE_CHOOSER_SETTLE_MS = 50;const CONTROL_POLL_INTERVAL_MS = 20_000;const PAGE_EVALUATE_EXECUTION_TIMEOUT_MS = 14_000;const PAGE_EVALUATE_TRANSPORT_TIMEOUT_MS = 15_000;@@ -758,6 +939,10 @@ const baseDefaultServices: Omit<PageModelServices, "ledger" | "pageBudget"> = {invalidateSession,setPreferredTarget,supportsBackgroundPageDiscovery: isBrowserRuntime,+ ensureTargetDiscovery: createTargetDiscoveryEnabler(+ () => isBrowserRuntime(),+ (method, params) => browserCdp(method, params),+ ),subscribeBrowserEvents,subscribePageEvents,prepareDownload(targetId, options) {@@ -940,9 +1125,7 @@ class TaskSpace {// cannot fall into the gap between the initial inventory and the callback.try {await this.#services.gate.withSpace(this.id, async () => {- await this.#services.cdp("Target.setDiscoverTargets", {- discover: true,- });+ await this.#services.ensureTargetDiscovery(this.id);await this.#recoverExistingChildPages();});} catch {@@ -1644,6 +1827,7 @@ class Page {waitUntil,});},+ { inputAction: false },);return receipt;}@@ -1661,6 +1845,7 @@ class Page {waitUntil,});},+ { inputAction: false },);return receipt;}@@ -2621,7 +2806,7 @@ class Page {({ refMap, iframeSessions }, services) =>operation(sessionId, refMap, iframeSessions, services),),- options.guardFileChooser,+ { guardFileChooser: options.guardFileChooser },);return receipt;}@@ -2640,6 +2825,58 @@ class Page {return { refMap, iframeSessions };}+ /**+ * Report how long the page has been idle when an action target is missing.+ * Returns null while the page is still loading, mutating, fetching, or+ * hidden (throttled timers), or when the runtime cannot observe network+ * activity, so the action keeps waiting for its full timeout in every+ * uncertain case.+ */+ async #idleWithoutTarget(+ sessionId: string,+ ): Promise<{ idleMs: number } | null> {+ let sessions: string[];+ try {+ sessions = await this.#services.pageNetworkSessions(+ sessionId,+ MISSING_TARGET_PROBE_TIMEOUT_MS,+ );+ } catch {+ return null;+ }+ const network = this.#services.networkActivity(sessions);+ if (!network.tracking || network.inflight > 0) return null;+ if (+ this.#services.now() - network.lastActivityAt <+ MISSING_TARGET_IDLE_MS+ ) {+ return null;+ }+ let probe: DomActivityProbe | undefined;+ try {+ const response = await this.#services.cdp(+ "Runtime.evaluate",+ { expression: DOM_ACTIVITY_PROBE, returnByValue: true },+ sessionId,+ MISSING_TARGET_PROBE_TIMEOUT_MS,+ );+ probe = runtimeValue(response, DOM_ACTIVITY_PROBE) as DomActivityProbe;+ } catch {+ return null;+ }+ if (+ !probe ||+ probe.readyState !== "complete" ||+ !probe.visible ||+ probe.framesLoading ||+ typeof probe.idleMs !== "number" ||+ probe.idleMs < MISSING_TARGET_IDLE_MS+ ) {+ return null;+ }+ return { idleMs: Math.round(probe.idleMs) };+ }+/*** Services whose CDP transport reports the first `Input.*` command and* which carry the action deadline into the driver's scroll loops.@@ -2700,6 +2937,26 @@ class Page {? isRetryableElementStateError(error): isRetryableResolutionError(error, pageSessionId);if (!retryable && !exhausted) throw error;+ // Idle time counts from this action's start, not from the page's+ // last mutation: work started by the previous action may not have+ // touched the DOM yet, so the first attempt never gives up early.+ if (+ !inputDispatched &&+ isNoMatchResolutionError(error) &&+ this.#services.now() - startedAt >= MISSING_TARGET_IDLE_MS+ ) {+ const idle = await this.#idleWithoutTarget(pageSessionId);+ if (idle) {+ throw new ElementResolutionError(+ `${actionName} failed: ${error.message}. The page has been idle ` ++ `for ${idle.idleMs}ms with no DOM changes and no network ` ++ `requests in flight, so the target is not about to appear. ` ++ `Check the selector against a fresh snapshot, or use ` ++ `page.waitForSelector() when the element is expected later.`,+ "permanent",+ );+ }+ }if (remainingMs <= 0) {const blocker = exhausted && lastBlocker ? lastBlocker : error;// Report the time the action really took: a slow page can overrun@@ -2737,7 +2994,9 @@ class Page {operation: (sessionId: string) => Promise<void>,): Promise<PageActionReceipt> {const page = await this.#resolve();- const { receipt } = await this.#runActionBoundary(page, operation, true);+ const { receipt } = await this.#runActionBoundary(page, operation, {+ guardFileChooser: true,+ });return receipt;}@@ -2780,7 +3039,12 @@ class Page {async #runActionBoundary<T>(page: PageTarget,operation: (sessionId: string) => Promise<T>,- guardFileChooser = false,+ {+ guardFileChooser = false,+ // Navigation already waits on page lifecycle; only input actions need+ // the ordering round trip to see a popup created by the input itself.+ inputAction = true,+ }: { guardFileChooser?: boolean; inputAction?: boolean } = {},): Promise<{ value: T; receipt: PageActionReceipt }> {const explicitDownload = this.#pendingDownload;const armedDownload = explicitDownload@@ -2808,11 +3072,12 @@ class Page {cancel: true,}): undefined;+ const popupWatch = await this.#watchPopups(inputAction);try {await fileChooserGuard?.ready;- const before = new Set(- (await this.#services.listTabs()).map((tab) => tab.targetId),- );+ const fileInputProbe = fileChooserGuard+ ? await this.#installFileInputProbe(sessionId)+ : false;let actionError: unknown;let value: T | undefined;try {@@ -2830,28 +3095,32 @@ class Page {};}- // 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);+ if (!inputAction) {+ await this.#services.sleep(NAVIGATION_FRAME_SETTLE_MS);+ }let popupError: unknown;- const popups: Array<{ label: string; targetId: string }> = [];+ let popups: PopupReceiptEntry[] = [];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" },- );- recordDiscoveredPage(this.spaceId, managed, this.label, tab.url);- popups.push({ label: managed.label, targetId: managed.targetId });- }+ popups = await popupWatch.collect(sessionId);} catch (error) {popupError = error;}+ if (fileChooserGuard && !fileChooserGuard.peek()) {+ const clickedFileInput = fileInputProbe+ ? await this.#readFileInputProbe(sessionId)+ : null;+ if (clickedFileInput !== false) {+ await Promise.race([+ fileChooserGuard.event.catch(() => {}),+ this.#services.sleep(+ clickedFileInput+ ? FILE_CHOOSER_OPEN_WAIT_MS+ : FILE_CHOOSER_SETTLE_MS,+ ),+ ]);+ }+ }if (fileChooserGuard?.peek()) {throw unhandledFileChooserError();}@@ -2863,11 +3132,155 @@ class Page {receipt: popups.length > 0 ? { popups } : {},};} finally {+ popupWatch.dispose();await fileChooserGuard?.dispose();}});}+ /**+ * Start observing popups for one action. With target discovery the watch+ * records Target.targetCreated events and costs nothing when no popup+ * opens; without it the watch falls back to diffing the tab list.+ */+ async #watchPopups(inputAction: boolean): Promise<PopupWatch> {+ const discovering = await this.#services.ensureTargetDiscovery(+ this.spaceId,+ );+ if (!discovering) return this.#pollingPopupWatch();+ const created = new Map<string, string>();+ const stop = this.#services.subscribeBrowserEvents((event) => {+ const info = event?.params?.targetInfo;+ if (+ event?.method !== "Target.targetCreated" ||+ info?.type !== "page" ||+ typeof info.targetId !== "string"+ ) {+ return;+ }+ created.set(info.targetId, typeof info.url === "string" ? info.url : "");+ });+ return {+ dispose: stop,+ collect: async (sessionId) => {+ if (created.size === 0 && inputAction) {+ // A popup opened by the input is created by the browser before this+ // page answers any later command, so one round trip delivers its+ // Target.targetCreated event ahead of the response.+ await this.#syncWithPage(sessionId);+ }+ if (created.size === 0) return [];+ return this.#adoptCreatedPopups(created);+ },+ };+ }++ async #pollingPopupWatch(): Promise<PopupWatch> {+ const before = new Set(+ (await this.#services.listTabs()).map((tab) => tab.targetId),+ );+ return {+ dispose: () => {},+ collect: async () => {+ // 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(POPUP_POLL_SETTLE_MS);+ const created = new Map<string, string>();+ for (const tab of await this.#services.listTabs()) {+ if (!before.has(tab.targetId)) created.set(tab.targetId, tab.url);+ }+ if (created.size === 0) return [];+ return this.#adoptCreatedPopups(created);+ },+ };+ }++ /** Returns true when the main document accepted the file-input click probe. */+ async #installFileInputProbe(sessionId: string): Promise<boolean> {+ try {+ const response = await this.#services.cdp(+ "Runtime.evaluate",+ { expression: FILE_INPUT_PROBE_INSTALL, returnByValue: true },+ sessionId,+ POPUP_SYNC_TIMEOUT_MS,+ );+ return runtimeValue(response, FILE_INPUT_PROBE_INSTALL) === true;+ } catch {+ return false;+ }+ }++ /** Returns whether a click reached a file input, or null when unknown. */+ async #readFileInputProbe(sessionId: string): Promise<boolean | null> {+ try {+ const response = await this.#services.cdp(+ "Runtime.evaluate",+ { expression: FILE_INPUT_PROBE_READ, returnByValue: true },+ sessionId,+ POPUP_SYNC_TIMEOUT_MS,+ );+ const value = runtimeValue(response, FILE_INPUT_PROBE_READ);+ return typeof value === "boolean" ? value : null;+ } catch {+ return null;+ }+ }++ async #syncWithPage(sessionId: string): Promise<void> {+ try {+ await this.#services.cdp(+ "Runtime.evaluate",+ { expression: "0", returnByValue: true },+ sessionId,+ POPUP_SYNC_TIMEOUT_MS,+ );+ } catch {+ // A navigating or dialog-blocked page cannot answer; the popup, if any,+ // is adopted by background discovery or the next task.tabs().+ }+ }++ async #adoptCreatedPopups(+ created: Map<string, string>,+ ): Promise<PopupReceiptEntry[]> {+ // Target discovery is browser-wide; the tab list scopes it to this space.+ let tabs = await this.#services.listTabs();+ for (let attempt = 0; attempt < POPUP_TAB_LIST_RETRIES; attempt += 1) {+ const known = new Set(tabs.map((tab) => tab.targetId));+ if ([...created.keys()].every((targetId) => known.has(targetId))) break;+ await this.#services.sleep(POPUP_TAB_LIST_RETRY_MS);+ tabs = await this.#services.listTabs();+ }+ const popups: PopupReceiptEntry[] = [];+ for (const [targetId, eventUrl] of created) {+ const tab = tabs.find((candidate) => candidate.targetId === targetId);+ if (!tab) continue;+ const url = tab.url || eventUrl;+ try {+ const managed = await this.#services.ledger.addPage(+ this.spaceId,+ targetId,+ { openedBy: "agent" },+ );+ recordDiscoveredPage(this.spaceId, managed, this.label, url);+ popups.push({ label: managed.label, targetId: managed.targetId });+ } catch (error) {+ // Background discovery may have adopted the same target first.+ const label =+ typeof this.#services.ledger.read === "function"+ ? labelForTarget(+ await this.#services.ledger.read(this.spaceId),+ targetId,+ )+ : undefined;+ if (!label) throw error;+ popups.push({ label, targetId });+ }+ }+ return popups;+ }+async #refMapForAction(page: PageTarget,sessionId: string,diff --git a/package/ego-browser/src/public-api-schema.ts b/package/ego-browser/src/public-api-schema.tsindex f353b48..f853f87 100644--- a/package/ego-browser/src/public-api-schema.ts+++ b/package/ego-browser/src/public-api-schema.ts@@ -36,7 +36,7 @@ const timeout = option();const actionTimeout = option("positiveMilliseconds",- "Maximum wait for the element to become usable in milliseconds; defaults to 3000.",+ "Maximum wait for the element to become usable in milliseconds; defaults to 3000. A selector that matches nothing on an idle page fails before the timeout.",);const delay = option("nonNegativeNumber", "Input delay in milliseconds.");const button = option("string", "Mouse button.", ["left", "middle", "right"]);