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
fix(ego-browser): retry iframe element resolution safely
JackWangfde7039ca664
diff --git a/package/ego-browser/src/driver/page-waits.test.mjs b/package/ego-browser/src/driver/page-waits.test.mjsindex 405dfde..0f36567 100644--- a/package/ego-browser/src/driver/page-waits.test.mjs+++ b/package/ego-browser/src/driver/page-waits.test.mjs@@ -3,9 +3,204 @@ import assert from "node:assert/strict";import {waitForLoadStateInPage,+ waitForSelectorInPage,waitForURLInPage,} from "../../dist/src/driver/page-waits.js";+test("waitForSelectorInPage refreshes iframe sessions while it polls", async () => {+ let now = 0;+ let discoveries = 0;+ const services = {+ async cdp(method, _params, sessionId) {+ if (method === "Runtime.evaluate") {+ return sessionId === "session:frame-current"+ ? { result: { objectId: "object:ready" } }+ : { result: { type: "undefined" } };+ }+ if (method === "Runtime.callFunctionOn") {+ return { result: { value: true } };+ }+ if (method === "Runtime.releaseObject") return {};+ throw new Error(`unexpected CDP method: ${method}`);+ },+ now: () => now,+ async sleep(ms) {+ now += ms;+ },+ };+ const getIframeSessions = async () => {+ discoveries += 1;+ return discoveries === 1+ ? new Map()+ : new Map([["frame-current", "session:frame-current"]]);+ };++ assert.equal(+ await waitForSelectorInPage(+ services,+ "session:page",+ new Map(),+ "#ready",+ { state: "visible", timeout: 2_000 },+ getIframeSessions,+ ),+ true,+ );+ assert.equal(discoveries, 2);+});++test("waitForSelectorInPage retries when a discovered iframe disappears during resolution", async () => {+ let now = 0;+ let discoveries = 0;+ const services = {+ async cdp(method, _params, sessionId) {+ if (+ method === "Runtime.evaluate" &&+ sessionId === "session:frame-stale"+ ) {+ throw new Error("Frame with the given frameId is not found.");+ }+ if (method === "Runtime.evaluate") {+ return sessionId === "session:frame-current"+ ? { result: { objectId: "object:ready" } }+ : { result: { type: "undefined" } };+ }+ if (method === "Runtime.callFunctionOn") {+ return { result: { value: true } };+ }+ if (method === "Runtime.releaseObject") return {};+ throw new Error(`unexpected CDP method: ${method}`);+ },+ now: () => now,+ async sleep(ms) {+ now += ms;+ },+ };+ const getIframeSessions = async () => {+ discoveries += 1;+ return discoveries === 1+ ? new Map([["frame-stale", "session:frame-stale"]])+ : new Map([["frame-current", "session:frame-current"]]);+ };++ assert.equal(+ await waitForSelectorInPage(+ services,+ "session:page",+ new Map(),+ "#ready",+ { state: "visible", timeout: 500 },+ getIframeSessions,+ ),+ true,+ );+ assert.equal(discoveries, 2);+});++test("waitForSelectorInPage rethrows a lost page session instead of reporting hidden", async () => {+ let now = 0;+ const services = {+ async cdp() {+ throw new Error("Target closed");+ },+ now: () => now,+ async sleep(ms) {+ now += ms;+ },+ };++ await assert.rejects(+ () =>+ waitForSelectorInPage(+ services,+ "session:page",+ new Map(),+ "#spinner",+ { state: "hidden", timeout: 500 },+ async () => new Map(),+ ),+ /Target closed/,+ );+});++test("waitForSelectorInPage reports its own timeout at the deadline", async () => {+ let now = 0;+ const discoveryTimeouts = [];+ const services = {+ async cdp(method) {+ if (method === "Runtime.evaluate")+ return { result: { type: "undefined" } };+ throw new Error(`unexpected CDP method: ${method}`);+ },+ now: () => now,+ async sleep(ms) {+ now += ms;+ },+ };+ const getIframeSessions = async (timeoutMs) => {+ discoveryTimeouts.push(timeoutMs);+ if (timeoutMs < 250) {+ const error = new Error("CDP request timed out: Target.getTargets");+ error.code = "EGO_CDP_REQUEST_TIMEOUT";+ throw error;+ }+ return new Map();+ };++ await assert.rejects(+ () =>+ waitForSelectorInPage(+ services,+ "session:page",+ new Map(),+ "#missing",+ { state: "visible", timeout: 500 },+ getIframeSessions,+ ),+ /page\.waitForSelector timed out after 500ms: #missing/,+ );+ assert(+ discoveryTimeouts.every((timeoutMs) => timeoutMs <= 500),+ `frame discovery must never exceed the public timeout: ${discoveryTimeouts}`,+ );+});++test("waitForSelectorInPage throttles iframe discovery while polling", async () => {+ let now = 0;+ let discoveries = 0;+ const services = {+ async cdp(method) {+ if (method === "Runtime.evaluate")+ return { result: { type: "undefined" } };+ throw new Error(`unexpected CDP method: ${method}`);+ },+ now: () => now,+ async sleep(ms) {+ now += ms;+ },+ };++ await assert.rejects(+ () =>+ waitForSelectorInPage(+ services,+ "session:page",+ new Map(),+ "#missing",+ { state: "visible", timeout: 2_000 },+ async () => {+ discoveries += 1;+ return new Map();+ },+ ),+ /timed out/,+ );+ assert(+ discoveries <= 5,+ `expected at most one discovery per 500ms over 2s, got ${discoveries}`,+ );+});+test("waitForURLInPage recovers from a transient execution-context change", async () => {let now = 0;let attempt = 0;diff --git a/package/ego-browser/src/driver/page-waits.ts b/package/ego-browser/src/driver/page-waits.tsindex 81e4b7d..2fe5fc3 100644--- a/package/ego-browser/src/driver/page-waits.ts+++ b/package/ego-browser/src/driver/page-waits.ts@@ -1,9 +1,29 @@+import {+ isCdpRequestTimeoutError,+ isFrameLifecycleError,+ isSessionLostError,+} from "../browser-runtime.js";import {ElementResolutionError,resolveElementObjectId,} from "../element-resolver.js";import { type RefMap } from "../ref-map.js";+const SELECTOR_POLL_INTERVAL_MS = 100;+/** How often a polling wait re-enumerates iframe sessions to catch late frames. */+const FRAME_DISCOVERY_REFRESH_INTERVAL_MS = 500;+/**+ * An element failure worth another resolution attempt: the resolver reported a+ * transient state, or a frame vanished mid-resolution. Session loss is not+ * included; callers decide whether the lost session was the Page itself.+ */+export function isTransientElementError(error: unknown): error is Error {+ return (+ isFrameLifecycleError(error) ||+ (error instanceof ElementResolutionError && error.kind === "transient")+ );+}+type PageWaitServices = {cdp(method: string,@@ -98,7 +118,7 @@ export async function waitForSelectorInPage(refMap: RefMap,selector: string,options: PageWaitForSelectorOptions = {},- iframeSessions = new Map<string, string>(),+ getIframeSessions: (timeoutMs: number) => Promise<Map<string, string>>,): Promise<true> {if (typeof selector !== "string" || selector.length === 0) {throw new TypeError(@@ -109,9 +129,22 @@ export async function waitForSelectorInPage(const state = options.state ?? "visible";const deadline = services.now() + timeoutMs;- while (services.now() <= deadline) {+ let iframeSessions: Map<string, string> | undefined;+ let refreshFrames = false;+ let nextDiscoveryAt = 0;+ while (true) {let resolved: { objectId: string; sessionId: string } | undefined;try {+ if (+ !iframeSessions ||+ (refreshFrames && services.now() >= nextDiscoveryAt)+ ) {+ iframeSessions = await getIframeSessions(+ Math.max(1, deadline - services.now()),+ );+ nextDiscoveryAt = services.now() + FRAME_DISCOVERY_REFRESH_INTERVAL_MS;+ refreshFrames = false;+ }resolved = await resolveElementObjectId(cdpAdapter(services),sessionId,@@ -135,13 +168,24 @@ export async function waitForSelectorInPage(if (state === "visible" ? visible : !visible) return true;}} catch (error) {- if (- !(error instanceof ElementResolutionError) ||- error.kind !== "transient"- ) {+ // Frame discovery is bounded by the remaining budget; a transport timeout+ // at the deadline is this wait's own timeout, not a distinct failure.+ if (isCdpRequestTimeoutError(error) && deadline - services.now() <= 0) {+ break;+ }+ if (!isRetryableSelectorWaitError(error, sessionId)) {throw error;}- if (state === "detached" || state === "hidden") return true;+ if (error instanceof ElementResolutionError) {+ if (state === "detached" || state === "hidden") return true;+ // The element may live in an iframe that appears later; re-enumerate+ // frames at a throttled cadence while polling.+ refreshFrames = true;+ } else {+ // A frame or its session vanished: rediscover before the next attempt.+ refreshFrames = true;+ nextDiscoveryAt = 0;+ }} finally {if (resolved?.objectId) {await services@@ -155,13 +199,27 @@ export async function waitForSelectorInPage(}const remaining = deadline - services.now();if (remaining <= 0) break;- await services.sleep(Math.min(100, remaining));+ await services.sleep(Math.min(SELECTOR_POLL_INTERVAL_MS, remaining));}throw new Error(`page.waitForSelector timed out after ${timeoutMs}ms: ${selector}`,);}+function isRetryableSelectorWaitError(+ error: unknown,+ pageSessionId: string,+): boolean {+ if (isTransientElementError(error)) return true;+ // A lost iframe session is recovered by rediscovery. A lost Page session is+ // terminal: never report a closed page as "hidden" or keep polling it.+ return (+ isSessionLostError(error) &&+ typeof error.sessionId === "string" &&+ error.sessionId !== pageSessionId+ );+}+/** Wait until one Page URL matches an exact string, glob, RegExp, or predicate. */export async function waitForURLInPage(services: PageWaitServices,@@ -847,14 +905,8 @@ async function waitForNetworkIdle(}function isRetryableNetworkRefreshError(error: unknown): boolean {- if (- Boolean(error) &&- typeof error === "object" &&- (error as { code?: unknown }).code === "EGO_CDP_REQUEST_TIMEOUT"- ) {- return true;- }- return /CDP request timed out:|detached Page session|Session (?:with given id )?not found|Target closed|No session/i.test(+ if (isCdpRequestTimeoutError(error) || isSessionLostError(error)) return true;+ return /CDP request timed out:|detached Page session/i.test(error instanceof Error ? error.message : String(error),);}diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjsindex a6d92c7..097a004 100644--- a/package/ego-browser/src/page-model.test.mjs+++ b/package/ego-browser/src/page-model.test.mjs@@ -45,6 +45,8 @@ function createFixture(rootDir) {let activeFileChooserWaiter = null;let systemFileChooserOpened = false;let timeoutNextMouseDispatch = false;+ let loseSessionOnNextMouseRelease = false;+ let loseFrameOnNextResolution = null;let dialogOnNextClick = null;let dialogOnNextFileSet = null;const pendingDialogs = new Map();@@ -141,6 +143,13 @@ function createFixture(rootDir) {return { frameId: "frame-1" };}if (method === "Runtime.evaluate") {+ if (loseFrameOnNextResolution) {+ const failure = loseFrameOnNextResolution;+ loseFrameOnNextResolution = null;+ const error = new Error(failure.message);+ if (failure.sessionId) error.sessionId = failure.sessionId;+ throw error;+ }const targetId = targetForSession(sessionId);const tab = tabs.get(targetId);if (params.expression.includes("__egoPageEvaluate")) {@@ -602,6 +611,10 @@ function createFixture(rootDir) {throw new Error("CDP request timed out: Input.dispatchMouseEvent");}if (params.type === "mouseReleased") {+ if (loseSessionOnNextMouseRelease) {+ loseSessionOnNextMouseRelease = false;+ throw new Error("Session with given id not found");+ }if (dialogOnNextClick) {const dialog = dialogOnNextClick;dialogOnNextClick = null;@@ -791,6 +804,12 @@ function createFixture(rootDir) {timeoutNextMouseDispatch() {timeoutNextMouseDispatch = true;},+ loseSessionOnNextMouseRelease() {+ loseSessionOnNextMouseRelease = true;+ },+ loseFrameOnNextResolution(failure) {+ loseFrameOnNextResolution = failure;+ },openDialogOnNextClick(dialog = {}) {dialogOnNextClick = {type: dialog.type ?? "alert",@@ -5110,6 +5129,136 @@ test("Page click retries a transient visibility change before dispatching input"});});+test("Page click retries when an iframe disappears during session discovery", async () => {+ await withFixture(async (fixture) => {+ let discoveries = 0;+ const discoveryTimeouts = [];+ const task = taskForRound(fixture, "round-a", {+ async ensureFrameSessions(_targetId, timeoutMs) {+ discoveries += 1;+ discoveryTimeouts.push(timeoutMs);+ if (discoveries === 1) {+ throw new Error("Frame with the given frameId is not found.");+ }+ return new Map();+ },+ });+ const page = await openTestPage(task, "https://example.test/first");++ assert.deepEqual(await page.click("#ready", { timeout: 1_000 }), {});+ assert.equal(discoveries, 2);+ assert.deepEqual(discoveryTimeouts, [1_000, 500]);+ });+});++test("Page click does not re-dispatch a gesture after its session was lost", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ const page = await openTestPage(task, "https://example.test/first");+ fixture.loseSessionOnNextMouseRelease();++ await assert.rejects(+ () => page.click("#submit", { timeout: 1_000 }),+ /Session with given id not found/,+ );+ assert.equal(+ fixture.calls.filter(+ ([kind, method, params]) =>+ kind === "cdp" &&+ method === "Input.dispatchMouseEvent" &&+ params.type === "mousePressed",+ ).length,+ 1,+ "a gesture that already reached the page must not be dispatched again",+ );+ });+});++test("Page click reports the action timeout instead of a tail discovery timeout", async () => {+ await withFixture(async (fixture) => {+ const discoveryTimeouts = [];+ const task = taskForRound(fixture, "round-a", {+ async ensureFrameSessions(_targetId, timeoutMs) {+ discoveryTimeouts.push(timeoutMs);+ if (timeoutMs < 250) {+ const error = new Error("CDP request timed out: Target.getTargets");+ error.code = "EGO_CDP_REQUEST_TIMEOUT";+ throw error;+ }+ return new Map();+ },+ });+ const page = await openTestPage(task, "https://example.test/first");+ fixture.rejectClickPoints(100);++ await assert.rejects(+ () => page.click("#changing", { timeout: 1_000 }),+ /page\.click timed out after 1000ms.*not visible/i,+ );+ assert(+ discoveryTimeouts.every((timeoutMs) => timeoutMs <= 1_000),+ `frame discovery must never exceed the action timeout: ${discoveryTimeouts}`,+ );+ });+});++test("Page click retries when an iframe disappears while the element is resolved", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ const page = await openTestPage(task, "https://example.test/first");+ fixture.loseFrameOnNextResolution({+ message: "Frame with the given frameId is not found.",+ });++ assert.deepEqual(await page.click("#ready", { timeout: 1_000 }), {});+ assert.equal(+ fixture.calls.filter(+ ([kind, method, params]) =>+ kind === "cdp" &&+ method === "Input.dispatchMouseEvent" &&+ params.type === "mousePressed",+ ).length,+ 1,+ );+ });+});++test("Page click retries when an iframe session is lost while the element is resolved", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ const page = await openTestPage(task, "https://example.test/first");+ fixture.loseFrameOnNextResolution({+ message: "Session with given id not found",+ sessionId: "session:frame-gone",+ });++ assert.deepEqual(await page.click("#ready", { timeout: 1_000 }), {});+ });+});++test("Page click fails fast when its own session is lost while the element is resolved", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ const page = await openTestPage(task, "https://example.test/first");+ fixture.loseFrameOnNextResolution({+ message: "Session with given id not found",+ sessionId: "session:target-1",+ });++ await assert.rejects(+ () => page.click("#ready", { timeout: 1_000 }),+ /Session with given id not found/,+ );+ assert.equal(+ fixture.calls.some(+ ([kind, method]) =>+ kind === "cdp" && method === "Input.dispatchMouseEvent",+ ),+ false,+ );+ });+});+test("Page click reports the last transient state after its timeout", 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 70d9db0..46941cb 100644--- a/package/ego-browser/src/page-model.ts+++ b/package/ego-browser/src/page-model.ts@@ -12,6 +12,7 @@ import {isCdpRequestTimeoutError,isBrowserRuntime,isPageDialogOpenedError,+ isSessionLostError,networkActivity,pageNetworkSessions,pendingDialog,@@ -70,6 +71,7 @@ import {type PageKeyboardTypeOptions,} from "./driver/page-keyboard.js";import {+ isTransientElementError,navigateInPage,reloadInPage,waitForLoadStateInPage,@@ -127,6 +129,11 @@ type TaskSpaceDescriptor = {recentTabTitles?: string[];};+/**+ * An action failed on element state after resolution (hidden, moving, covered)+ * and may simply be attempted again. Transport and session errors are not+ * included: input may already have reached the page.+ */function isRetryableElementStateError(error: unknown,): error is ElementResolutionError {@@ -137,6 +144,26 @@ function isRetryableElementStateError();}+/**+ * Resolution or frame discovery failed before any input was dispatched. On top+ * of the element-state cases above, a frame that vanished or an iframe session+ * that was lost is recovered by rediscovering frames; losing the Page's own+ * session is terminal.+ */+function isRetryableResolutionError(+ error: unknown,+ pageSessionId: string,+): error is Error {+ if (isTransientElementError(error)) {+ return !error.message.startsWith("Unknown ref:");+ }+ return (+ isSessionLostError(error) &&+ typeof error.sessionId === "string" &&+ error.sessionId !== pageSessionId+ );+}+type AdoptPageOptions = {as?: string;};@@ -341,7 +368,10 @@ type PageModelServices = {lastActivityAt: number;};ensureSession(targetId: string): Promise<string>;- ensureFrameSessions(targetId: string): Promise<Map<string, string>>;+ ensureFrameSessions(+ targetId: string,+ timeoutMs?: number,+ ): Promise<Map<string, string>>;invalidateSession(targetId: string): void;setPreferredTarget(targetId: string): void;supportsBackgroundPageDiscovery(): boolean;@@ -2044,16 +2074,14 @@ class Page {return this.#services.gate.withPage(page, async ({ sessionId }) => {await this.#activate(page.targetId);const refMap = await this.#refMapForAction(page, sessionId, selector);- const iframeSessions = await this.#services.ensureFrameSessions(- page.targetId,- );return waitForSelectorInPage(this.#services,sessionId,refMap,selector,options,- iframeSessions,+ (timeoutMs) =>+ this.#services.ensureFrameSessions(page.targetId, timeoutMs),);});}@@ -2108,9 +2136,9 @@ class Page {validatePublicApiOptions("Page.click", options);return this.#runAction(selector,- (sessionId, refMap, iframeSessions) =>+ (sessionId, refMap, iframeSessions, services) =>clickInPage(- this.#services,+ services,sessionId,refMap,selector,@@ -2133,9 +2161,9 @@ class Page {validatePublicApiOptions("Page.dblclick", options);return this.#runAction(selector,- (sessionId, refMap, iframeSessions) =>+ (sessionId, refMap, iframeSessions, services) =>clickInPage(- this.#services,+ services,sessionId,refMap,selector,@@ -2158,9 +2186,9 @@ class Page {validatePublicApiOptions("Page.hover", options);return this.#runAction(selector,- (sessionId, refMap, iframeSessions) =>+ (sessionId, refMap, iframeSessions, services) =>hoverInPage(- this.#services,+ services,sessionId,refMap,selector,@@ -2180,9 +2208,9 @@ class Page {validatePublicApiOptions("Page.dragAndDrop", options);return this.#runAction([sourceSelector, targetSelector],- (sessionId, refMap, iframeSessions) =>+ (sessionId, refMap, iframeSessions, services) =>dragAndDropInPage(- this.#services,+ services,sessionId,refMap,sourceSelector,@@ -2203,9 +2231,9 @@ class Page {validatePublicApiOptions("Page.fill", options);return this.#runAction(selector,- (sessionId, refMap, iframeSessions) =>+ (sessionId, refMap, iframeSessions, services) =>fillInPage(- this.#services,+ services,sessionId,refMap,selector,@@ -2232,37 +2260,24 @@ class Page {choices.forEach(validateSelectOptionChoice);const timeoutMs = options.timeout ?? DEFAULT_PAGE_ACTION_TIMEOUT_MS;const page = await this.#resolve();- return this.#runInputBoundary(page, async (sessionId) => {- const deadline = this.#services.now() + timeoutMs;- while (true) {- try {- const refMap = await this.#refMapForAction(page, sessionId, selector);- const iframeSessions = await this.#services.ensureFrameSessions(- page.targetId,- );- return await selectOptionInPage(- this.#services,+ return this.#runInputBoundary(page, (sessionId) =>+ this.#retryElementAction(+ "page.selectOption",+ timeoutMs,+ sessionId,+ (remainingMs) =>+ this.#resolveActionTargets(page, sessionId, remainingMs, selector),+ ({ refMap, iframeSessions }, services) =>+ selectOptionInPage(+ services,sessionId,refMap,selector,choices,iframeSessions,- );- } catch (error) {- if (!isRetryableElementStateError(error)) throw error;- const remainingMs = deadline - this.#services.now();- if (remainingMs <= 0) {- throw new ElementResolutionError(- `page.selectOption timed out after ${timeoutMs}ms: ${error.message}`,- "transient",- );- }- await this.#services.sleep(- Math.min(PAGE_ACTION_RESOLUTION_RETRY_MS, remainingMs),- );- }- }- });+ ),+ ),+ );}async focus(@@ -2272,14 +2287,8 @@ class Page {validatePublicApiOptions("Page.focus", options);return this.#runAction(selector,- (sessionId, refMap, iframeSessions) =>- focusInPage(- this.#services,- sessionId,- refMap,- selector,- iframeSessions,- ),+ (sessionId, refMap, iframeSessions, services) =>+ focusInPage(services, sessionId, refMap, selector, iframeSessions),{ actionName: "page.focus", timeout: options.timeout },);}@@ -2293,9 +2302,9 @@ class Page {const { timeout, ...pressOptions } = options;return this.#runAction(selector,- async (sessionId, refMap, iframeSessions) => {+ async (sessionId, refMap, iframeSessions, services) => {await focusInPage(- this.#services,+ services,sessionId,refMap,selector,@@ -2317,9 +2326,9 @@ class Page {): Promise<PageActionReceipt> {return this.#runAction(selector,- (sessionId, refMap, iframeSessions) =>+ (sessionId, refMap, iframeSessions, services) =>setInputFilesInPage(- this.#services,+ services,sessionId,refMap,selector,@@ -2488,6 +2497,7 @@ class Page {sessionId: string,refMap: RefMap,iframeSessions: Map<string, string>,+ services: PageModelServices,) => Promise<void>,options: {actionName?: string;@@ -2501,40 +2511,107 @@ class Page {const actionName = options.actionName ?? "page action";const { receipt } = await this.#runActionBoundary(page,- async (sessionId) => {- const deadline = this.#services.now() + timeoutMs;- while (true) {- try {- const refMap = await this.#refMapForAction(+ (sessionId) =>+ this.#retryElementAction(+ actionName,+ timeoutMs,+ sessionId,+ (remainingMs) =>+ this.#resolveActionTargets(page,sessionId,+ remainingMs,...selectors,- );- const iframeSessions = await this.#services.ensureFrameSessions(- page.targetId,- );- await operation(sessionId, refMap, iframeSessions);- return;- } catch (error) {- if (!isRetryableElementStateError(error)) throw error;- const remainingMs = deadline - this.#services.now();- if (remainingMs <= 0) {- throw new ElementResolutionError(- `${actionName} timed out after ${timeoutMs}ms: ${error.message}`,- "transient",- );- }- await this.#services.sleep(- Math.min(PAGE_ACTION_RESOLUTION_RETRY_MS, remainingMs),- );- }- }- },+ ),+ ({ refMap, iframeSessions }, services) =>+ operation(sessionId, refMap, iframeSessions, services),+ ),options.guardFileChooser,);return receipt;}+ async #resolveActionTargets(+ page: PageTarget,+ sessionId: string,+ remainingMs: number,+ ...selectors: string[]+ ): Promise<{ refMap: RefMap; iframeSessions: Map<string, string> }> {+ const refMap = await this.#refMapForAction(page, sessionId, ...selectors);+ const iframeSessions = await this.#services.ensureFrameSessions(+ page.targetId,+ Math.max(1, remainingMs),+ );+ return { refMap, iframeSessions };+ }++ /** Services whose CDP transport reports the first `Input.*` command. */+ #inputTrackingServices(onInput: () => void): PageModelServices {+ const services = this.#services;+ return {+ ...services,+ cdp(method, params, sessionId, timeoutMs) {+ if (method.startsWith("Input.")) onInput();+ return services.cdp(method, params, sessionId, timeoutMs);+ },+ };+ }++ /**+ * Retry an element action until its deadline. Until the first `Input.*`+ * command reaches the page, failures may include a vanished frame or a lost+ * iframe session and are retried after rediscovering frames. Once input was+ * dispatched only element-state transients are retried, so a gesture that+ * already reached the page is never dispatched twice.+ */+ async #retryElementAction<Prepared, Result>(+ actionName: string,+ timeoutMs: number,+ pageSessionId: string,+ prepare: (remainingMs: number) => Promise<Prepared>,+ perform: (+ prepared: Prepared,+ services: PageModelServices,+ ) => Promise<Result>,+ ): Promise<Result> {+ const deadline = this.#services.now() + timeoutMs;+ let lastBlocker: Error | undefined;+ while (true) {+ let inputDispatched = false;+ const services = this.#inputTrackingServices(() => {+ inputDispatched = true;+ });+ try {+ const prepared = await prepare(deadline - this.#services.now());+ return await perform(prepared, services);+ } catch (error) {+ const remainingMs = deadline - this.#services.now();+ // Frame discovery runs on the remaining budget; a transport timeout at+ // the deadline is this action's timeout, reported with the last real+ // blocker rather than as a CDP failure.+ const exhausted =+ !inputDispatched &&+ isCdpRequestTimeoutError(error) &&+ remainingMs <= 0;+ const retryable = inputDispatched+ ? isRetryableElementStateError(error)+ : isRetryableResolutionError(error, pageSessionId);+ if (!retryable && !exhausted) throw error;+ if (remainingMs <= 0) {+ const blocker = exhausted && lastBlocker ? lastBlocker : error;+ throw new ElementResolutionError(+ `${actionName} timed out after ${timeoutMs}ms: ${blocker.message}`,+ "transient",+ );+ }+ lastBlocker = error;+ await this.#services.sleep(+ Math.min(PAGE_ACTION_RESOLUTION_RETRY_MS, remainingMs),+ );+ }+ }+ }+async #runRawAction(operation: (sessionId: string) => Promise<void>,): Promise<void> {