/** * BiDi implementation of the browser-neutral Driver contract in ../driver.ts (ADR-001), for * Firefox. THE CONNECTION IDENTITY IS A BiDi ws ENDPOINT, not a port: createFirefoxDriver(port) * derives the loopback endpoint of a Firefox this toolkit launched, while * createFirefoxDriverForEndpoint(wsUrl) takes a user-supplied one for ATTACH mode (a Firefox the * user started with --remote-debugging-port; see ../backend.ts). Attach is a first-class path, * not a workaround — what is impossible is RELAUNCHING the binary to open a port on a running * instance (bidi/launch.ts's header), not connecting to a port that is already open. * lifetime is "session": a BiDi socket cannot be resumed, so this file memoizes ONE * BidiConnection per endpoint at module scope (the connections map below), page() * retains a holder, release() decrements it, and only BrowserDriver.dispose() ever closes the * socket — after sending session.end, so an attached Firefox (which outlives us) gets its single * session slot back. There is deliberately no reconnect-and-resume path: if the socket dies, every pending * and future call on it rejects with "disconnected" rather than silently starting a fresh * session underneath a caller who still thinks they hold the old one. (driver.ts's LifetimeModel * doc says a "session" driver "MUST re-establish itself transparently if the transport dies"; * this driver does not, on purpose, per the verified BiDi behavior in bidi/client.ts's own * header. See the final report for why that doc comment and this implementation disagree.) * * Uid codec (scheme "bidi"): `bidi:`, per THE UID CODEC block in ../driver.ts. A stamp is * page state (an attribute written by ../bidi/snapshot.ts's in-page walker, or by this file's * STAMP_ONE_SOURCE for a single located element), never protocol state, so it survives a fresh * session and a fresh CLI process. It does NOT survive navigation or a page re-render, per * uidStability "document-stamp". * * take_snapshot has no BiDi equivalent domain, so ../bidi/snapshot.ts's takeStampedSnapshot walks * the DOM in-page and returns a pre-formatted indented text tree (the same line grammar * ../tools/snapshot.ts and formatSnapshotLine use). This file's job is the adapter: run that * function through script.callFunction and PARSE its text back into SnapshotNode[], which is * genuinely new integration work, not a reimplementation of the walker itself. */ import { keepFrontApp } from "../frontApp.ts"; import { spawn } from "node:child_process"; import { fileURLToPath } from "node:url"; import { existsSync } from "node:fs"; import type { TargetSelector } from "../types.ts"; import { UID_STAMP_ATTR, isDriverError, interpolatePoints, clearViewportRecord, readViewportRecord, renderRestoreFailureNote, writeViewportRecord, type BrowserCookie, type BrowserDriver, type Capability, type DeleteCookiesFilter, type HandledDialogInfo, type DriverError, type DriverErrorCode, type DriverEvent, type DragDestination, type DragOptions, type SetCookieParams, type DriverUid, type ElementLocator, type EmulationOptions, type InterceptRule, type KeyPress, type LifetimeModel, type MouseButtonOptions, type RawMouseEvent, type NavigateOptions, type NavigateResult, type PageDriver, type PageInfo, type ScreenshotOptions, type ScreenshotResult, type ScrollOptions, type SnapshotNode, type UidStability, type BandConsumer, type CaptureDelivery, } from "../driver.ts"; import { assertLeaseOk, defaultLabel, isPidAlive } from "../leases.ts"; import { resolveLiveLabel } from "../origins.ts"; import { isWorkerSelector, WORKER_SELECTOR_UNSUPPORTED_MESSAGE } from "../workers.ts"; import { FRAME_SELECTOR_UNSUPPORTED_MESSAGE, isFrameSelector } from "../frames.ts"; import { BEACON_FUNCTION_DECLARATION, BEACON_READ_EXPRESSION, BEACON_SOURCE, recordDispatch } from "../activity.ts"; import { BidiConnection, BidiError, connectBidiSessionUrl } from "./client.ts"; import { acquireSessionSlot, advertiseMux, muxDaemonLogFile, readSessionSlot, releaseSessionSlot, sessionWaitMs, SessionSlotBusyError, type AcquireResult, type SessionSlotHandle, type SessionSlotRecord, } from "./session-lease.ts"; import { startBidiMux, type BidiMux } from "./mux.ts"; import { defaultMarionettePort, forceClearOrphanSession } from "./marionette.ts"; import { takeStampedSnapshot } from "./snapshot.ts"; import { selectRule, buildFulfillParams, effectiveAction } from "../tools/network_mock.ts"; import type { BrowsingContextId, BrowsingContextInfo, BrowsingContextLocator, BrowsingContextReadinessState, BrowsingContextCaptureScreenshotParameters, BrowsingContextCreateParameters, ScriptSharedReference, ScriptRemoteValue, ScriptLocalValue, ScriptNodeRemoteValue, ScriptExceptionDetails, InputSourceActions, InputPointerSourceAction, InputKeySourceAction, InputWheelSourceAction, NetworkCookie, } from "./protocol.ts"; /* ---------------------------------- cookies ---------------------------------- */ /** * BiDi's cookie shape to the neutral one. Three differences to absorb: * - the value is a network.BytesValue, either a plain string or base64, so a * base64 one is decoded rather than handed back as opaque base64; * - `expiry` is optional and simply absent for a session cookie, which becomes * the neutral -1 that CDP reports directly; * - `session` has no BiDi field at all, so it is derived from that same * absence, which is exactly what a session cookie means. * `sameSite` already uses the lowercase vocabulary the neutral shape adopted. */ export function normalizeBidiCookie(c: NetworkCookie): BrowserCookie { const value = c.value.type === "base64" ? Buffer.from(c.value.value, "base64").toString("utf8") : c.value.value; const hasExpiry = typeof c.expiry === "number"; return { name: c.name, value, domain: c.domain, path: c.path, expires: hasExpiry ? (c.expiry as number) : -1, size: typeof c.size === "number" ? c.size : Buffer.byteLength(`${c.name}${value}`, "utf8"), httpOnly: c.httpOnly === true, secure: c.secure === true, sameSite: c.sameSite ?? "default", session: !hasExpiry, }; } /** * The host of a url, for the BiDi cookie calls that require a `domain` and have * no `url` parameter of their own. * * Exported so a test can pin the failure cases without a browser. Every branch * that cannot produce a host THROWS: an absent url, an unparseable one, and a * parseable one with an empty host (about:blank, data:, javascript:) all raise * a message naming the tool and what it needs. The alternative, sending the * call without a domain, is a request Firefox answers cleanly while writing or * deleting nothing recognizable, which is the exact wrong-but-plausible ack * this driver refuses to emit. */ export function hostFromUrl(url: string | undefined, toolName: string): string { if (url === undefined || url === "") { throw driverError("unsupported", `${toolName} on Firefox needs a 'domain': BiDi's storage cookie calls have no 'url' parameter, and no url was given to derive one from.`); } let host = ""; try { host = new URL(url).hostname; } catch { throw driverError("unsupported", `${toolName} could not parse the url '${url}' to derive the 'domain' BiDi requires. Pass 'domain' explicitly.`); } if (host === "") { throw driverError("unsupported", `${toolName} cannot derive a 'domain' from '${url}': that url has no host. Pass 'domain' explicitly.`); } return host; } /* ------------------------------ error + uid codec ------------------------------ */ function driverError(code: DriverErrorCode, message: string, data?: unknown): DriverError { return Object.assign(new Error(message), { code, ...(data !== undefined ? { data } : {}) }) as DriverError; } function encodeUid(stamp: string): DriverUid { return `bidi:${stamp}`; } function decodeStamp(uid: DriverUid): string { if (!uid.startsWith("bidi:")) throw driverError("foreign-uid", `uid is not owned by the bidi driver: ${uid}`); const payload = uid.slice(5); if (!payload.length) throw driverError("foreign-uid", `malformed bidi uid payload: ${uid}`); return payload; } function cssEscape(s: string): string { return s.replace(/["\\]/g, (c) => `\\${c}`); } /** Maps a thrown BidiError (or anything else) onto the neutral DriverErrorCode vocabulary. */ function mapBidiError(e: unknown): DriverError { if (e instanceof BidiError) { const code = e.code; if (code === "no such node" || code === "no such element") return driverError("no-such-element", e.message); if (code === "no such frame") return driverError("no-such-target", e.message); if (code === "invalid session id") return driverError("disconnected", e.message); if (code === "unsupported operation") return driverError("unsupported", e.message); // A Firefox older than the one a capability was verified on answers a newer BiDi command with // "unknown command". That is a capability gap, not a protocol fault: surface it as "unsupported" // and name the version that has it (BIDI_CAPABILITY_MIN_FIREFOX). if (code === "unknown command") return driverError("unsupported", `${e.message} (this Firefox predates that WebDriver BiDi command; see BIDI_CAPABILITY_MIN_FIREFOX for the version each capability needs)`); if (!code && /timed out/i.test(e.message)) return driverError("timeout", e.message); if (!code && /(disposed|not open|connection closed)/i.test(e.message)) return driverError("disconnected", e.message); // NS_ERROR_FILE_ACCESS_DENIED from browsingContext.navigate means the browser process was // refused at the OS level while opening the file:// target — not a protocol failure. Two // mechanisms produce it (#6): (1) the automation prefs that relax file:// handling were never // applied — launch.ts now seeds them via user.js, so this should not surface for a // toolkit-launched Firefox; (2) kernel-level confinement of the browser itself (Ubuntu's snap // Firefox is the common one: a snap process cannot see host paths outside its mount // namespace), which no preference can bypass. The error must name the way out rather than // relay the raw nsresult. if (/NS_ERROR_FILE_ACCESS_DENIED/i.test(e.message)) { return driverError( "page-error", `${e.message} — the browser process was not allowed to open this file:// path. For a snap- or AppArmor-confined Firefox (Ubuntu default) that is kernel-level and no preference fixes it: serve the directory over a local http server (e.g. python3 -m http.server) and navigate to the http://127.0.0.1:/ URL instead. If this Firefox was launched by cdp-toolkit and still fails, please report it at https://github.com/sblattj/cdp-toolkit/issues.`, ); } return driverError("page-error", e.message); } return driverError("page-error", e instanceof Error ? e.message : String(e)); } /* ---------------------------- script value (de)serialization ---------------------------- */ function serializeArg(v: unknown): ScriptLocalValue { if (v === undefined) return { type: "undefined" }; if (v === null) return { type: "null" }; if (typeof v === "string") return { type: "string", value: v }; if (typeof v === "number") return { type: "number", value: Number.isNaN(v) ? "NaN" : v }; if (typeof v === "boolean") return { type: "boolean", value: v }; if (Array.isArray(v)) return { type: "array", value: v.map(serializeArg) }; if (typeof v === "object") return { type: "object", value: Object.entries(v as Record).map(([k, val]) => [k, serializeArg(val)]) }; return { type: "string", value: String(v) }; } /** Inverse of serializeArg for the subset of ScriptRemoteValue shapes our tools actually produce. */ function deserializeRemote(rv: ScriptRemoteValue): unknown { switch (rv.type) { case "undefined": return undefined; case "null": return null; case "string": return rv.value; case "boolean": return rv.value; case "bigint": return rv.value; case "number": return typeof rv.value === "number" ? rv.value : rv.value; case "array": return (rv.value ?? []).map(deserializeRemote); case "object": { const out: Record = {}; for (const [k, v] of rv.value ?? []) out[typeof k === "string" ? k : String(deserializeRemote(k))] = deserializeRemote(v); return out; } case "node": return { bidiSharedId: rv.sharedId }; default: return undefined; } } function exceptionMessage(d: ScriptExceptionDetails): string { if (d.text) return d.text; const ex = deserializeRemote(d.exception); return typeof ex === "string" ? ex : "evaluation threw"; } /* -------------------------------- snapshot line parsing -------------------------------- */ // Mirrors formatSnapshotLine's grammar in ./snapshot.ts: `[] [ ""][ []]`. const LINE_RE = /^((?: {2})*)\[([0-9a-f]+)\] ([a-zA-Z_][\w-]*)(?: ("(?:[^"\\]|\\.)*"))?(?: \[(.*)\])?$/; function splitExtras(s: string): string[] { const out: string[] = []; let cur = ""; let inQuotes = false; for (let i = 0; i < s.length; i++) { const ch = s[i]!; if (ch === '"' && s[i - 1] !== "\\") inQuotes = !inQuotes; if (ch === " " && !inQuotes) { if (cur) out.push(cur); cur = ""; } else cur += ch; } if (cur) out.push(cur); return out; } function parseSnapshotLine(line: string): SnapshotNode | undefined { const m = LINE_RE.exec(line); if (!m) return undefined; const indent = m[1] ?? "", stamp = m[2]!, role = m[3]!, nameLit = m[4], extrasRaw = m[5]; const depth = indent.length / 2; let name: string | undefined; if (nameLit) { try { name = JSON.parse(nameLit) as string; } catch { name = nameLit; } } const extras: Record = {}; if (extrasRaw) { for (const tok of splitExtras(extrasRaw)) { const eq = tok.indexOf("="); if (eq === -1) { extras[tok] = "true"; continue; } const key = tok.slice(0, eq); let val = tok.slice(eq + 1); if (val.startsWith('"')) { try { val = JSON.parse(val) as string; } catch { /* keep raw */ } } extras[key] = val; } } return { uid: encodeUid(stamp), role, depth, ...(name !== undefined ? { name } : {}), ...(Object.keys(extras).length ? { extras } : {}) }; } const INTERACTIVE_ROLES = new Set([ "button", "link", "textbox", "searchbox", "checkbox", "radio", "combobox", "listbox", "option", "slider", "spinbutton", "progressbar", "meter", ]); // Stamps ONE already-located element (locate()'s mint path), reusing an existing stamp per the // same rule ../bidi/snapshot.ts's nextStamp()/stampOf() apply during a full-tree walk. Payload is // two padded random hex blocks (8+4), matching THE UID CODEC's documented exactly-12-lowercase- // hex-char bidi payload grammar exactly and the same padding technique nextStamp() now uses. const STAMP_ONE_SOURCE = `function(){var a=${JSON.stringify(UID_STAMP_ATTR)};var e=this.getAttribute(a);if(e)return e;var s=Math.floor(Math.random()*0x100000000).toString(16).padStart(8,"0")+Math.floor(Math.random()*0x10000).toString(16).padStart(4,"0");this.setAttribute(a,s);return s;}`; /* ------------------------------- element locator resolution ------------------------------- */ async function locateNodes(conn: BidiConnection, contextId: BrowsingContextId, locator: BrowsingContextLocator): Promise { try { const { nodes } = await conn.send("browsingContext.locateNodes", { context: contextId, locator, maxNodeCount: 1 }); return nodes; } catch (e) { throw mapBidiError(e); } } function sharedRefOf(node: ScriptNodeRemoteValue, describe: string): ScriptSharedReference { if (!node.sharedId) throw driverError("page-error", `located node has no sharedId (${describe})`); return { sharedId: node.sharedId }; } /** THE UID CODEC: "More than one match MUST take the first node in document order", which is * what locateNodes returns nodes in; we always ask for maxNodeCount 1 so there is only one to take. */ async function resolveElementLocator(conn: BidiConnection, contextId: BrowsingContextId, loc: ElementLocator): Promise { if ("uid" in loc) { const stamp = decodeStamp(loc.uid); const nodes = await locateNodes(conn, contextId, { type: "css", value: `[${UID_STAMP_ATTR}="${cssEscape(stamp)}"]` }); if (!nodes.length) throw driverError("stale-uid", `uid does not resolve: ${loc.uid}`); return sharedRefOf(nodes[0]!, loc.uid); } if ("css" in loc) { const nodes = await locateNodes(conn, contextId, { type: "css", value: loc.css }); if (!nodes.length) throw driverError("no-such-element", `css '${loc.css}' matched no element`); return sharedRefOf(nodes[0]!, `css '${loc.css}'`); } if ("xpath" in loc) { const nodes = await locateNodes(conn, contextId, { type: "xpath", value: loc.xpath }); if (!nodes.length) throw driverError("no-such-element", `xpath '${loc.xpath}' matched no element`); return sharedRefOf(nodes[0]!, `xpath '${loc.xpath}'`); } const nodes = await locateNodes(conn, contextId, { type: "innerText", value: loc.text, matchType: "partial" }); if (!nodes.length) throw driverError("no-such-element", `text '${loc.text}' matched no element`); return sharedRefOf(nodes[0]!, `text '${loc.text}'`); } /* ---------------------------------- keys ---------------------------------- */ // WebDriver normalized key values (Unicode PUA), the BiDi-side counterpart of CDP's NAMED_KEYS. const KEY_VALUES: Record = { enter: "\uE007", return: "\uE007", tab: "\uE004", escape: "\uE00C", esc: "\uE00C", backspace: "\uE003", delete: "\uE017", space: " ", arrowup: "\uE013", arrowdown: "\uE015", arrowleft: "\uE012", arrowright: "\uE014", up: "\uE013", down: "\uE015", left: "\uE012", right: "\uE014", home: "\uE011", end: "\uE010", pageup: "\uE00E", pagedown: "\uE00F", }; const MODIFIER_VALUES: Record = { shift: "\uE008", control: "\uE009", ctrl: "\uE009", alt: "\uE00A", meta: "\uE03D", cmd: "\uE03D", command: "\uE03D" }; const BUTTON_CODES: Record<"left" | "right" | "middle", number> = { left: 0, middle: 1, right: 2 }; const RAW_MOUSE_SOURCE_ID = "cdp-raw-mouse"; /** Modifier names (Alt/Control/Meta/Shift, any case, plus the aliases pressKey takes) to WebDriver * key values, in the order given. Unknown names are refused, never skipped. */ function modifierKeyValues(mods: readonly string[] | undefined): string[] { const out: string[] = []; for (const m of mods ?? []) { const v = MODIFIER_VALUES[m.toLowerCase()]; if (v === undefined) throw driverError("page-error", `unknown modifier '${m}' (use Alt, Control, Meta, or Shift)`); if (!out.includes(v)) out.push(v); } return out; } /** * The input sources for pointer `actions` with `keys` held across them. With no keys it is the plain * pointer source. With keys, a "key" source is TICK-ALIGNED with the pointer source in the same * performActions call: [keyDown x k, pause x n, keyUp x k] against [pause x k, ...actions, pause x k], * so every modifier is down before the first pointer action and released after the last. This is the * shape measured on Firefox 160.0 (a lone key source or a misaligned one did not reach the click). */ function modifierChord(pointerId: string, actions: InputPointerSourceAction[], keys: readonly string[]): InputSourceActions[] { const pointer: InputPointerSourceAction[] = actions; if (keys.length === 0) return [{ type: "pointer", id: pointerId, actions: pointer }]; const k = keys.length; const pause = (): { type: "pause" } => ({ type: "pause" }); const keyActions: InputKeySourceAction[] = [ ...keys.map((v): InputKeySourceAction => ({ type: "keyDown", value: v })), ...pointer.map(pause), ...[...keys].reverse().map((v): InputKeySourceAction => ({ type: "keyUp", value: v })), ]; const pointerActions: InputPointerSourceAction[] = [ ...Array.from({ length: k }, pause), ...pointer, ...Array.from({ length: k }, pause), ]; return [ { type: "key", id: "cdp-keyboard", actions: keyActions }, { type: "pointer", id: pointerId, actions: pointerActions }, ]; } /** Same scroll-settle technique as cdp/driver.ts's ARM_SCROLL_SETTLE_WATCH / awaitScrollSettle, * see that file's doc comment for the full rationale: a capture-phase 'scroll' listener on * window, debounced 60ms with a 500ms cap, so scroll()'s caller observes the settled position. */ const ARM_SCROLL_SETTLE_WATCH_SOURCE = "function(){window.__cdpScrollSettle=new Promise((resolve)=>{let t;const done=()=>{window.removeEventListener('scroll',on,true);resolve(true);};" + "const on=()=>{clearTimeout(t);t=setTimeout(done,60);};window.addEventListener('scroll',on,true);t=setTimeout(done,60);setTimeout(done,500);});}"; const AWAIT_SCROLL_SETTLE_SOURCE = "function(){return window.__cdpScrollSettle;}"; /** * Firefox 153 capabilities. Only what was empirically verified is declared: emulate.deviceMetrics * (browsingContext.setViewport) and the userAgent path (universal, no capability token) both work. * emulate.cpuThrottling, trace.performance (emulate.mediaFeatures and emulate.networkConditions were * added later at Firefox 160, see BIDI_CAPABILITY_MIN_FIREFOX), heap.snapshot, audit.lighthouse, input.insertTextAtomic and snapshot.accessibilityTree are all * deliberately absent, several because Firefox 153 does not implement the underlying BiDi command * at all (see protocol.ts's "Firefox 153: not implemented" tags), the rest because this driver has * no accessibility-tree source or CPU-multiplier primitive to offer. locate.xpath rides * browsingContext.locateNodes({type:"xpath"}), verified working. locate.text is NOT declared: * locateNodes({type:"innerText"}) throws "locator.type argument with value: innerText is not * supported yet" on real Firefox 153.0.3, contradicting the initial assumption that both text and * xpath locators were live; ElementLocator's `text` branch still resolves and correctly surfaces * "unsupported" rather than silently misbehaving, it is simply not offered as a capability. * capture.screencast is absent because WebDriver BiDi has no streamed-frame primitive at all: * the spec offers only the one-shot browsingContext.captureScreenshot, with no screencast * start/stop command and no per-repaint frame event to subscribe to, so the screen-recording * pair is honestly missing under Firefox rather than present and throwing. * network.intercept rides network.addIntercept + network.beforeRequestSent, verified working * (see intercept()'s comment on why urlPatterns is never populated). screenshot.fullPage uses * captureScreenshot's origin:"document", screenshot.element uses its clip:{type:"element"}, both verified. * screenshot.renderSize IS declared, and it is the one screenshot capability here that is not a * Chrome-only gap: it rides browsingContext.setViewport, the very command emulate.deviceMetrics * above already rides, applied for one capture and undone afterwards. Refusing it would be dishonest * in the opposite direction — claiming a missing primitive this driver demonstrably has. * screenshot.scale (Firefox >= 160, BIDI_CAPABILITY_MIN_FIREFOX) is the same trick one step on: * captureScreenshot itself still has no scale parameter, but setViewport({devicePixelRatio}) with NO * viewport key multiplies the capture and leaves the layout viewport alone (measured on 160.0: * a 1366x683 capture became 2732x1366 at ratio 2, innerWidth/innerHeight unchanged), so scale rides * that for one capture and undoes it, like renderSize. network.responseBodyPostHoc (Firefox >= 160) * is armed per SESSION, see armPostHocBodies. * screenshot.tile stays undeclared, but no longer for an unmeasured reason: live-fired against * Firefox 153.0.3, a 20,000px-tall page captured with take_screenshot --fullPage true came back * as a single 1366x20000 PNG at scale 1, verified complete top-to-bottom — no clip, no bands. * Chrome's band tiling exists solely to route around its 16384-device-px encode cap; Firefox has * no such cap, so screenshot.tile (the capability gating explicit tile:true forced banding) has * no gap here to close. It stays undeclared because it would advertise a forced-tiling primitive * this backend has never needed, not because band-tiling behavior is untested. */ /** * Capabilities verified on a Firefox NEWER than 153, keyed to the first major version they were * measured on. They are declared in BIDI_CAPABILITIES (tool listing is static: capabilities.ts reads * this set without opening a socket), and each method that rides one calls requireFirefox(conn, * token) before touching browser state, so an older Firefox gets an "unsupported" DriverError that * names the version instead of a half-applied change or a raw "unknown command". * * input.raw (dispatch_mouse) and input.modifierClick (click with modifiers), measured on headless * Firefox 160.0: a pointerDown issued in one input.performActions call stays held for a pointerUp in * a LATER call that reuses the same pointer source id (page saw mousedown, then mouseup+click), so * one raw event per call works; and a modifier chord works when a "key" source (keyDown of the * modifier, pauses, keyUp) is TICK-ALIGNED with the pointer source in ONE call (page saw * shiftKey/ctrlKey/altKey/metaKey on the click). input.html5Drag is NOT declared: on 160.0 a * pointer drag starts a real drag session (dragstart, dragenter, dragover reach the page) but the * session never completes under BiDi input (no drop, no dragend, no mouseup, even after a pause or * a second performActions call), so a drag cannot be delivered; see test/bidi-input-ff160.test.ts. * * browser.downloads (160): browser.setDownloadBehavior {type:"allowed", destinationFolder} plus the * browsingContext.downloadWillBegin/downloadEnd events, measured on headless Firefox 160.0 — the * file landed in the folder, downloadEnd carried status "complete" and its filepath, and * `downloadBehavior: null` put a later download back in the profile's own download dir. Drives * wait_for_download through ../bidi-browser-tools.ts. * browser.permissions (160): permissions.setPermission {descriptor, state, origin}, measured on * Firefox 160.0 — navigator.permissions.query followed granted/denied/prompt. Drives * grant_permissions through ../bidi-browser-tools.ts, which also documents the Chrome asymmetries. */ export const BIDI_CAPABILITY_MIN_FIREFOX: Readonly>> = { "browser.downloads": 160, "browser.permissions": 160, "emulate.mediaFeatures": 160, "emulate.networkConditions": 160, "input.raw": 160, "input.modifierClick": 160, "network.responseBodyPostHoc": 160, "screenshot.scale": 160, }; /** Firefox major version from session.new's capabilities.browserVersion (e.g. "160.0" -> 160). * undefined when the session reported none (a stub connection in tests): treated as new enough. */ export function firefoxMajor(conn: { capabilities: unknown }): number | undefined { const v = (conn.capabilities as { browserVersion?: unknown } | undefined)?.browserVersion; if (typeof v !== "string") return undefined; const major = Number.parseInt(v, 10); return Number.isFinite(major) ? major : undefined; } /** Throw "unsupported" when `token` needs a newer Firefox than the one this session is on. */ export function requireFirefox(conn: { capabilities: unknown }, token: Capability): void { const min = BIDI_CAPABILITY_MIN_FIREFOX[token]; if (min === undefined) return; const major = firefoxMajor(conn); if (major !== undefined && major < min) { const v = (conn.capabilities as { browserVersion?: string }).browserVersion; throw driverError("unsupported", `${token} needs Firefox ${min} or newer; this Firefox is ${v}.`); } } /** * Largest single response body the session-wide collector keeps, in bytes. maxEncodedDataSize is a * PER-RESPONSE cap (measured on Firefox 160.0: cap 10 dropped a 20-byte body; cap 2,000,000 kept every * 1 MB body). A larger body is simply not retained and reads back as "no such network data". The * TOTAL is Firefox's own and not ours to set: with a 2 MB cap or a 20 MB cap alike, 260 sequential * 1 MB responses left the oldest ~60 answering "unavailable network data" (evicted) and the newest * ~160 readable, so the browser's own budget is on the order of 100-200 MB regardless of this number * (no pref for it was found; attach mode gets the browser default). This number only bounds how * much of that budget one response can take. */ const POST_HOC_BODY_MAX_BYTES = 2 * 1024 * 1024; /** * Arm the ONE session-wide response collector that makes network.responseBodyPostHoc true. * * WHY HERE. network.addDataCollector is scoped to the BiDi SESSION, and it only retains bodies of * requests that start after it exists. This toolkit shares ONE real session per browser (the holder * path of getConnection, which the mux daemon reaches through hostFirefoxMux), so the place that * covers every client, every tab and every request since the session began is the moment that real * session is created: no `contexts`/`userContexts`, so tabs opened later are covered too. A JOINED * connection must NOT arm another: its commands are forwarded to the same upstream session and a * second collector would double-retain every body. Best-effort and silent on a Firefox older than * 160 (the capability is version-gated, see requireFirefox): a failed arm leaves reads answering * "no such network data" rather than failing the connection the caller asked for. */ async function armPostHocBodies(conn: BidiConnection): Promise { // Opt-out for an everyday Firefox where retaining response bodies is unwanted. With it off, a // body is readable only after startBodyCapture, and an unarmed read is the "no such network // data" DriverError, the same as on a Firefox older than 160. if (process.env.CDP_FIREFOX_BODY_COLLECTOR === "off") return; try { requireFirefox(conn, "network.responseBodyPostHoc"); } catch { return; } try { await conn.send("network.addDataCollector", { dataTypes: ["response"], maxEncodedDataSize: POST_HOC_BODY_MAX_BYTES }); } catch (e) { console.error(`[cdp-toolkit] firefox response-body collector not armed: ${e instanceof Error ? e.message : String(e)}`); } } const BIDI_CAPABILITIES: ReadonlySet = new Set([ "emulate.deviceMetrics", "screenshot.fullPage", "screenshot.element", "screenshot.renderSize", "network.intercept", "locate.xpath", ...(Object.keys(BIDI_CAPABILITY_MIN_FIREFOX) as Capability[]), ]); /* --------------------------------- module-scope session memoization --------------------------------- */ // "session" LifetimeModel: ONE BidiConnection per BiDi ws endpoint, shared by every page() // acquisition on that endpoint. Keyed by the endpoint URL string rather than a port because attach // mode's endpoint may be any host/port/path (../backend.ts's normalizeBidiEndpoint), and the URL is // the only identity both modes share. getConnection retains a holder on every call (fresh or // reused); callers release() it. const connections = new Map(); // This process's OWN Firefox BiDi session-slot ownership, keyed by endpoint (see session-lease.ts). // The slot LOCK is a file on disk — that is the cross-process source of truth — and this map is our // in-process record of which endpoints WE currently hold a live claim on, so dispose() releases // exactly the slots we took, and a re-dial after a dead socket reuses our own claim instead of // contending with our own pid. Populated in getConnection's create body; cleared on dispose() and // on a terminal dial failure that never established a session. const slotHandles = new Map(); // The BiDi multiplexer WE host, keyed by the FIREFOX endpoint whose real session it fronts (see // ./mux.ts). Populated by getConnection's holder path right after the real connection is cached; // closed first thing in dispose(), so joiners see their sockets drop while we still hold the slot. // Absent when this process is not a holder, when startBidiMux failed (the holder just runs alone), // or under CDP_FIREFOX_MUX=off. const muxes = new Map(); // Firefox endpoints this process reached THROUGH another process's mux rather than by owning the // session. Keyed by the FIREFOX endpoint (the connections map's key) even though the socket really // points at the holder's loopback mux, so page()/the beacon map/dispose all stay keyed on one // identity. Membership means exactly two things: we hold NO session slot for this endpoint (never // release one), and a dead socket here must NOT take the `owned` re-dial branch — it must re-run // acquire, which either joins the new holder or wins the slot outright. const joined = new Set(); // In-flight create dedup, keyed by endpoint. Two page() acquisitions can both cache-miss and call // getConnection concurrently; without this both would run the acquire+dial body, and the second // would either contend for the slot we just took (same pid → wait then SessionSlotBusyError against // ourselves) or open a second BiDi session. The first caller stores its create-promise here and // every other awaits it; cleared in a finally once the create settles. const connecting = new Map>(); // Per-endpoint SESSION EPOCH: how many times THIS process has established a connection to this // endpoint (as a holder, or through a mux). Firefox regenerates every browsing-context id whenever // its single BiDi session is re-created, so any id this process handed out before an epoch bump is // dead — measured on Firefox 153.0.3: after session.end + session.new the tab survives at the same // url but browsingContext.getTree reports a NEW context id. The epoch is what lets a // "no such frame"/"no context matching" failure say WHY instead of reading like a typo. We track it // per ENDPOINT, not per id (the brief's permitted simplification): the hint is appended whenever // epoch > 1, which can over-attach the hint to an id that was simply closed, and never under-attach. const sessionEpochs = new Map(); // Reverse lookup so resolveContext (which only has a BidiConnection) can find its endpoint's epoch. const connEndpoints = new WeakMap(); // Per-endpoint cleanup BidiBrowserDriver.dispose() runs on the live connection before session.end // (see setDisposeHook). Keyed by endpoint, then by the registering feature. const disposeHooks = new Map Promise>>(); function bumpEpoch(endpoint: string, conn: BidiConnection): void { sessionEpochs.set(endpoint, (sessionEpochs.get(endpoint) ?? 0) + 1); connEndpoints.set(conn, endpoint); } /** Appended to a no-such-target error once this process has re-connected at least once. */ const STALE_ID_HINT = " — the Firefox BiDi session was re-established after its previous holder went away, and Firefox " + "assigns new context ids per session — re-resolve the tab with list_pages (url:/title: selectors) " + "and claim it again"; function withStaleIdHint(conn: BidiConnection, err: unknown): unknown { const endpoint = connEndpoints.get(conn); if (endpoint === undefined) return err; if ((sessionEpochs.get(endpoint) ?? 0) <= 1) return err; const e = err as DriverError; if (!isDriverError(e) || e.code !== "no-such-target") return err; if (e.message.includes("re-established")) return err; e.message += STALE_ID_HINT; return e; } /** * Which mux strategy this connection uses. `off` is the pre-mux behavior (no mux hosted, * an advertised one ignored). `host` hosts the mux IN THIS PROCESS — correct for LAUNCH mode * (a private Firefox this toolkit owns, which dies with us anyway) and an opt-in for anyone who * does not want a stray process. Unset/`daemon` in ATTACH mode is the DEFAULT and the whole point * of the daemon: the real Firefox session must not live in a client process, because when that * client exits — even cleanly — Firefox regenerates every context id and every other client's * cached ids, tab leases and origin records go stale. */ type MuxMode = "off" | "host" | "daemon"; function muxMode(attached: boolean): MuxMode { const raw = process.env.CDP_FIREFOX_MUX; if (raw === "off") return "off"; if (raw === "host") return "host"; if (raw === "daemon") return "daemon"; return attached ? "daemon" : "host"; } /** Absolute path of the daemon entry point, or undefined if we cannot find one to spawn. * Order: explicit env override (tests), the source tree (`bun run src/…`), then the built * bundle. `import.meta.url` inside dist is dist/{mcp,cli,index}.js, so the sibling is * dist/bidi/mux-daemon.js (scripts/build.ts roots entrypoints at src/). */ function resolveDaemonScript(): string | undefined { const override = process.env.CDP_FIREFOX_MUX_DAEMON; if (override) return override; for (const rel of ["./mux-daemon.ts", "./mux-daemon.js", "./bidi/mux-daemon.js", "../bidi/mux-daemon.js"]) { let p: string; try { p = fileURLToPath(new URL(rel, import.meta.url)); } catch { continue; } if (existsSync(p)) return p; } return undefined; } const sleep = (ms: number): Promise => new Promise((r) => setTimeout(r, ms)); // The label stamped on a slot record WE take. defaultLabel() is "pid-", which is right for an // MCP server but useless for the daemon, whose record a human reads when they wonder what process // is holding their browser. hostFirefoxMux sets it to "mux-daemon(spawned by pid N)". let slotLabelOverride: string | undefined; /** A LIVE holder advertising a mux, or undefined. */ async function liveAdvertisedHolder(endpoint: string): Promise<{ endpoint: string; holder: SessionSlotRecord } | undefined> { const rec = await readSessionSlot(endpoint).catch(() => undefined); if (!rec || !rec.muxEndpoint || !isPidAlive(rec.pid)) return undefined; return { endpoint: rec.muxEndpoint, holder: rec }; } /** * DAEMON MODE: get a mux endpoint to join WITHOUT ever becoming the holder in this process. * Returns the advertised endpoint, or undefined meaning "no daemon could be brought up — fall * back to the in-process host path", which is what turns a genuinely unavailable browser back * into the existing actionable busy/Marionette errors instead of a mystery timeout. * Throws only for the deadline case, which is a real failure with a real diagnostic (the log). */ async function ensureMuxDaemon(endpoint: string): Promise<{ endpoint: string; holder: SessionSlotRecord } | undefined> { const already = await liveAdvertisedHolder(endpoint); if (already) return already; const script = resolveDaemonScript(); if (!script) return undefined; // no daemon to spawn: host it ourselves let exited = false; const child = spawn(process.execPath, [script, endpoint, String(process.pid)], { detached: true, stdio: "ignore", env: { ...process.env, CDP_FIREFOX_MUX: "host" }, }); child.once("error", () => { exited = true; }); // Fires even on an unref'ed child while WE are alive, which is exactly the fast negative signal // we need: a daemon that refused (busy slot, Marionette missing, dial error) exits non-zero at // once, and we fall back rather than waiting out the deadline. child.once("exit", () => { exited = true; }); child.unref(); const deadline = Date.now() + sessionWaitMs() + 5_000; while (Date.now() < deadline) { const hit = await liveAdvertisedHolder(endpoint); if (hit) return hit; if (exited) return undefined; // daemon gave up: host in-process and surface ITS error await sleep(50); } throw driverError("disconnected", `Firefox's single WebDriver BiDi session on ${endpoint} could not be brought up: a mux daemon was ` + `spawned (${script}) but never advertised a multiplexer within ${sessionWaitMs() + 5_000}ms. ` + `Its diagnostics are in ${muxDaemonLogFile(endpoint)}. Retry, or set CDP_FIREFOX_MUX=host to run ` + `the session in this process instead.`); } /** * Release a slot claim we took in THIS getConnection call after a dial that never established a * live session, so a later attempt re-acquires cleanly. When `owned` is true we did NOT acquire in * this call (we reused a pre-existing claim — our previous socket died without dispose), so the * handle predates this call and must be left intact: we still own Firefox's slot, only the socket * failed to re-establish. */ async function releaseSlotOnDialFailure(endpoint: string, owned: boolean): Promise { if (owned) return; const h = slotHandles.get(endpoint); if (h) { await releaseSessionSlot(h).catch(() => undefined); slotHandles.delete(endpoint); } } /** * The actionable error for issue #4: Firefox is holding an orphaned BiDi session on this endpoint * that Marionette recovery could NOT auto-clear (Firefox launched without --marionette, or the * Marionette channel timed out / could not confirm). Distinguished from the live-busy case (issue * #5, a LIVE lease holder) because here NO live process holds our lease — a session Firefox itself * stranded is wedging the slot, and the fix is to enable Marionette or restart Firefox. */ function orphanNotClearedError(endpoint: string): DriverError { return driverError("disconnected", `Firefox holds an orphaned WebDriver BiDi session on ${endpoint} that could not be auto-cleared. ` + `Marionette recovery needs Firefox launched with --marionette (default port 2828, or set ` + `CDP_FIREFOX_MARIONETTE_PORT); otherwise restart Firefox to free the slot. (A client killed without ` + `session.end can leave a session Firefox does not reap.)`); } // getConnection: the ONE Firefox-session choke point. Beyond memoizing a BidiConnection per endpoint // it now runs the cross-process SESSION-slot coordination (session-lease.ts) plus Marionette orphan // recovery (marionette.ts). Firefox serves exactly ONE WebDriver-BiDi session per browser, and it // never reaps an abandoned one (verified: still held 10s after an abrupt socket death). Two ills // follow that this closes: (#5) two LIVE processes attaching to one user-launched Firefox used to // hard-wedge on the raw "Maximum number of active sessions" with no way to tell a live holder from a // crash; the lease now names the LIVE holder and says wait-and-retry. (#4) a process killed without // session.end used to leave the slot occupied until Firefox restarted; when the lease shows the // prior holder's PID is DEAD, or Firefox itself still refuses on a re-dial, a blind Marionette // WebDriver:DeleteSession (which shares Firefox's one session slot) force-clears the orphan WITHOUT // killing the user's browser, and we retry. Marionette recovery is best-effort and degrades to a // clear, actionable error when Firefox has no --marionette port (the launch-mode norm). // // AND THE THIRD OUTCOME, THE MUX JOIN. "Wait and retry" was the honest answer while one process // could only ever hand the session to the next one. It no longer is: the holder now hosts a // loopback BiDi multiplexer over its one real session (./mux.ts) and advertises it in the slot // record, so when acquire reports a LIVE holder WITH a muxEndpoint we do not wait at all — we dial // the holder's mux with the same connectBidiSessionUrl and the same dialOpts we would use against // Firefox, and cache the resulting socket under the FIREFOX endpoint key. Downstream, a joined // connection is indistinguishable from a real one; the only bookkeeping is the `joined` set, which // records that we hold NO slot (so dispose releases nothing and ends nothing) and that a dead // socket here must re-run acquire rather than take the `owned` re-dial shortcut. A live holder with // NO mux is still plain busy, exactly as before. On the holder side, the only addition is that // after the real connection is cached we start a mux and advertise it — best-effort, because a // holder that fails to start one is simply a holder that serves nobody but itself. async function getConnection(endpoint: string, timeoutMs?: number, attached = false): Promise { const existing = connections.get(endpoint); if (existing && existing.isOpen) { existing.retain(); return existing; } // A cached connection whose socket has died (ws.onclose fired) can only reject every // send() with "connection not open" — reusing it would strand the endpoint permanently. // Evict it so the code below re-dials and creates a fresh BiDi session. We deliberately do NOT // release the session slot here: a dead socket is transient and WE still own Firefox's slot, so // the create body below re-dials WITHOUT re-acquiring (its `owned` branch), avoiding a needless // contention against our own pid. No other cleanup is needed: a dead connection already had // `closed` set and rejectAll() cleared its per-call timers, and BidiConnection holds no // heartbeat/keepalive resource to leak (see client.ts). if (existing) connections.delete(endpoint); // Concurrency: dedup in-flight creates on this endpoint. An awaiter shares the create's outcome // but needs its OWN holder — the create's connectBidiSessionUrl retains exactly once, for the // caller that started it, so every other caller retains again for itself (callers all release()). const inflight = connecting.get(endpoint); if (inflight) { const conn = await inflight; conn.retain(); return conn; } const create = (async (): Promise => { const mport = defaultMarionettePort(); // Firefox 153's default unhandledPromptBehavior is "dismiss": a page-blocking alert()/confirm() // gets auto-dismissed before handleDialog() ever runs, and Firefox's own userPromptOpened event // reports handler:"dismiss" on it (verified: a bare session.new left "no such alert" on the very // next handleUserPrompt call). Setting "ignore" here is what makes handleDialog() able to see // and answer a live prompt at all. Declared before the acquire so the JOIN path can dial the // holder's mux with byte-identical options — a joined connection must be indistinguishable. const dialOpts = { ...(timeoutMs !== undefined ? { timeoutMs } : {}), capabilities: { alwaysMatch: { unhandledPromptBehavior: { default: "ignore" as const } } }, }; // Do we ALREADY hold this endpoint's slot? (e.g. our previous socket died without dispose, so // the eviction above kept the claim.) If so, re-dial WITHOUT re-acquiring: acquireSessionSlot // against our own live pid would just poll to its wait ceiling and then throw // SessionSlotBusyError against ourselves. We already own Firefox's slot; only the socket needs // re-establishing (and if Firefox stranded our old session, the re-dial's retry path clears it). let owned = slotHandles.has(endpoint); // ...UNLESS the dead socket we just evicted was a JOINED one. A joiner owns no slot and no // session, so the `owned` shortcut would re-dial Firefox directly against a session someone // else holds. Drop the join marker and run the full acquire, which either joins whoever holds // the slot NOW (the old holder recovered, or a new one took over) or wins the slot outright. if (joined.has(endpoint)) { joined.delete(endpoint); owned = false; } // DAEMON MODE (the default in ATTACH mode). Never become the holder in-process: either join a // daemon that already advertises a mux, or spawn one and join it as soon as it does. The real // session then outlives every client, which is the entire point — see ensureMuxDaemon. // A daemon that refuses returns undefined and we fall through to the host path below, so an // unavailable browser still produces the existing actionable busy/Marionette errors. if (!owned && muxMode(attached) === "daemon") { const target = await ensureMuxDaemon(endpoint); if (target) { try { const joinedConn = await connectBidiSessionUrl(target.endpoint, dialOpts); // already retained once connections.set(endpoint, joinedConn); joined.add(endpoint); bumpEpoch(endpoint, joinedConn); return joinedConn; } catch (e) { // The daemon died between advertising and our dial. Fall through to the ordinary // acquire loop, which steals the orphan record and re-runs the whole flow. console.error(`[cdp-toolkit] firefox mux daemon at ${target.endpoint} could not be dialed: ${e instanceof Error ? e.message : String(e)}`); } } } // The acquire runs in a loop only so the JOIN path can retry itself exactly ONCE (below); // every other path breaks out on its first pass. for (let attempt = 0; ; attempt++) { if (owned) break; // Cross-process coordination (session-lease.ts): take the endpoint's single BiDi session slot, // classifying any current holder. A LIVE holder that ADVERTISES A MUX is JOINED rather than // waited on; a LIVE holder without one still throws SessionSlotBusyError exactly as before; a // DEAD holder's orphan is stolen and surfaced as staleHolder so we can force-clear Firefox's // stranded session before we call session.new. let acq: AcquireResult; try { acq = await acquireSessionSlot(endpoint, { label: slotLabelOverride ?? defaultLabel(), marionettePort: mport }); } catch (e) { if (e instanceof SessionSlotBusyError) { // Issue #5: a distinguishable LIVE holder, NOT a wedge. Map to an actionable disconnected // error that names who holds the one session and why Firefox can serve only one per browser. const who = e.holderLabel ? `'${e.holderLabel}' (pid ${e.holderPid})` : "another live process"; throw driverError("disconnected", `Firefox's single WebDriver BiDi session on ${endpoint} is held by a LIVE process ${who}. ` + `Firefox serves exactly ONE BiDi session per browser instance, so this server cannot take it ` + `while that process is running. Wait for it to release the session and retry, or point this ` + `server at a different endpoint/browser.`); } throw e; } if (acq.joinMux) { // JOIN: the live holder fronts its one real session with a loopback BiDi mux, so we dial // THAT instead of Firefox. We take no slot and open no real session — but we cache the // socket under the FIREFOX endpoint key, so page(), the beacon map and dispose() are all // keyed on one identity and neither knows nor cares that the bytes go via the holder. const { endpoint: muxEndpoint, holder } = acq.joinMux; try { const joinedConn = await connectBidiSessionUrl(muxEndpoint, dialOpts); // already retained once connections.set(endpoint, joinedConn); joined.add(endpoint); bumpEpoch(endpoint, joinedConn); return joinedConn; } catch (e) { // A holder can die between advertising and our dial, leaving a stale muxEndpoint in a // record whose pid is about to read dead. Re-run the WHOLE acquire once: we will either // steal that orphan and become the holder ourselves, or join whoever took over. if (attempt === 0) continue; const who = `'${holder.label}' (pid ${holder.pid})`; throw driverError("disconnected", `Firefox's single WebDriver BiDi session on ${endpoint} is held by a LIVE process ${who}, ` + `which advertises a BiDi multiplexer at ${muxEndpoint}, but that multiplexer could not be ` + `dialed (${e instanceof Error ? e.message : String(e)}). The holder is most likely shutting ` + `down; retry in a moment, or point this server at a different endpoint/browser.`); } } // We took the slot ourselves: the ordinary HOLDER path, unchanged. if (acq.handle) slotHandles.set(endpoint, acq.handle); if (acq.staleHolder) { // Issue #4 auto-recovery: we stole a DEAD holder's lease, but Firefox itself may still hold // that holder's orphaned BiDi session. Force-clear it over Marionette BEFORE dialing, or // session.new below will still hit "Maximum number of active sessions". Best-effort: a false // result means Firefox has no --marionette (launch mode, or the user never enabled it); we // still dial, and the re-dial retry path below surfaces a clear error if the orphan persists. await forceClearOrphanSession(acq.staleHolder.marionettePort ?? mport); } break; } let conn: BidiConnection; try { conn = await connectBidiSessionUrl(endpoint, dialOpts); // already retained once } catch (e) { if (e instanceof BidiError && /maximum number of active sessions/i.test(e.message)) { // Firefox still holds a BiDi session our lease didn't account for: a FOREIGN client we don't // coordinate with, OUR OWN orphan from a dead socket (the `owned` re-dial), or a pre-lease // orphan. Recovery: blind Marionette force-clear, then retry the dial EXACTLY once. const cleared = await forceClearOrphanSession(mport); if (!cleared) { await releaseSlotOnDialFailure(endpoint, owned); throw orphanNotClearedError(endpoint); } try { conn = await connectBidiSessionUrl(endpoint, dialOpts); // already retained once } catch (e2) { await releaseSlotOnDialFailure(endpoint, owned); if (e2 instanceof BidiError && /maximum number of active sessions/i.test(e2.message)) { throw orphanNotClearedError(endpoint); // cleared, yet still refused: treat as unrecoverable } throw e2; } } else { // Any other dial failure never established a session: release a slot we took THIS call and // rethrow unchanged (the `owned` re-dial never acquired, so its claim is left intact). await releaseSlotOnDialFailure(endpoint, owned); throw e; } } connections.set(endpoint, conn); bumpEpoch(endpoint, conn); // We own the real session: arm the post-hoc body collector on it (never on a joined one). await armPostHocBodies(conn); // We are the HOLDER. Front our one real session with a loopback BiDi mux and advertise it in // the slot record, so any other process that wants this Firefox JOINS us instead of being told // the slot is busy. Strictly additive and strictly best-effort: any failure here leaves a // perfectly good holder that simply serves nobody but itself (exactly pre-mux behavior), so it // is logged to stderr and swallowed rather than failing the connection the caller asked for. if (muxMode(attached) !== "off") { try { const mux = await startBidiMux(conn); muxes.set(endpoint, mux); const h = slotHandles.get(endpoint); if (h) await advertiseMux(h, mux.endpoint); } catch (e) { console.error(`[cdp-toolkit] firefox mux not started: ${e instanceof Error ? e.message : String(e)}`); } } return conn; })(); connecting.set(endpoint, create); try { return await create; } finally { connecting.delete(endpoint); } } /** * Contexts that already carry a beacon preload script, keyed endpoint:context -> * the script id BiDi handed back. * * WHY FIREFOX NEEDS NO HELD CONNECTION where Chrome does. This driver's * LifetimeModel is "session": ONE BidiConnection is memoized per endpoint above and * lives until dispose(), so a preload script registered on it stays registered * across navigations for free. Chrome's equivalent registration is cleared when * the registering client disconnects, and this toolkit's CDP lifetime is * "per-call", which is why cdp/driver.ts has to hold a socket per beaconed tab * and this file does not. The map exists only to avoid stacking a second * registration on a context that already has one; the in-page script is * idempotent, so a duplicate would be harmless but pointless. */ const bidiBeaconScripts = new Map(); /* ----------------------------------- context/page lookup ----------------------------------- */ async function safeTitle(conn: BidiConnection, contextId: BrowsingContextId): Promise { try { const res = await conn.send("script.evaluate", { expression: "document.title", target: { context: contextId }, awaitPromise: false }); return res.type === "success" && res.result.type === "string" ? res.result.value : ""; } catch { return ""; } } async function pageInfoOf(conn: BidiConnection, ctx: BrowsingContextInfo): Promise { return { id: ctx.context, url: ctx.url, title: await safeTitle(conn, ctx.context) }; } /** Same TargetSelector grammar as client.ts's resolveTarget, but resolved entirely over BiDi * (browsingContext.getTree): there is no HTTP discovery endpoint here, per client.ts's own footer. * * THE Firefox choke point for tab leases. Keyed "firefox", never a bare id: a CDP targetId and a * BiDi context id are not disjoint by construction, so one bare key space could produce a false * collision between an unrelated Chrome tab and a Firefox context. Note this backend needs the * lease far less than Chrome does (backend.ts: every MCP server process launches its OWN Firefox, * so two sessions cannot race over one instance the way they do over Chrome on port 9222). It is * here for consistency and for a future shared-instance setup, not to close an observed gap. */ async function resolveContext( conn: BidiConnection, selector: TargetSelector, opts: { lease?: string } = {}, ): Promise { const { contexts } = await conn.send("browsingContext.getTree", {}).catch((e) => { throw mapBidiError(e); }); if (!contexts.length) throw driverError("no-such-target", "no browsing contexts available"); // A no-such-target here is the exact symptom of Firefox's per-session context-id regeneration // once this process has re-connected at least once, so the error explains it rather than reading // like a typo. The CODE is left untouched (still no-such-target), so caller handling is unchanged. const hit = await pickContext(conn, contexts, selector).catch((e) => { throw withStaleIdHint(conn, e); }); // liveIds deliberately not passed: hit is by construction a member of contexts, so target-gone // could never fire for the context just resolved (see leases.ts's assertLeaseOk callers). await assertLeaseOk("firefox", hit.context, { lease: opts.lease, url: hit.url }); return hit; } async function pickContext( conn: BidiConnection, contexts: BrowsingContextInfo[], selector: TargetSelector, ): Promise { if (selector === undefined || selector === "active") return contexts[0]!; if (selector.startsWith("index:")) { const t = contexts[Number(selector.slice(6))]; if (!t) throw driverError("no-such-target", `no context at ${selector}`); return t; } if (selector.startsWith("url:")) { const needle = selector.slice(4); const t = contexts.find((c) => c.url.includes(needle)); if (!t) throw driverError("no-such-target", `no context with url containing '${needle}'`); return t; } if (selector.startsWith("title:")) { const needle = selector.slice(6); for (const c of contexts) if ((await safeTitle(conn, c.context)).includes(needle)) return c; throw driverError("no-such-target", `no context with title containing '${needle}'`); } if (selector.startsWith("label:")) { const label = selector.slice(6); const { matchIds, knownLabels } = await resolveLiveLabel("firefox", label, contexts.map((c) => c.context)); if (matchIds.length > 1) { throw driverError("no-such-target", `label 'label:${label}' matches more than one live target: ${matchIds.join(", ")}. Resolve by target id instead.`); } if (matchIds.length === 1) { const hit = contexts.find((c) => c.context === matchIds[0]); if (hit) return hit; } throw driverError( "no-such-target", knownLabels.length ? `no live target with label '${label}' (labels currently in use: ${knownLabels.join(", ")})` : `no live target with label '${label}' (no labels are currently assigned to any open target)`, ); } if (isWorkerSelector(selector)) { // Capability-gated, not unimplemented: "unsupported" is the DriverErrorCode // that tells a caller to check the capability rather than retry. The tool // itself stays available on Firefox — only this arm of the grammar is // refused, exactly as drag's mode:'html5' is. Refusing loudly beats the // alternative the bare-id fall-through would produce, which is a confusing // "no context matching 'worker:abc'" that reads like a typo. throw driverError("unsupported", WORKER_SELECTOR_UNSUPPORTED_MESSAGE); } if (isFrameSelector(selector)) { // Capability-gated for the same reason as the worker: arm above. WebDriver // BiDi has no iframe TARGET to resolve to — an iframe is a realm inside its // tab's browsing context — so the honest error names the capability // ('frame.targets', Chrome-only) rather than retrying or reading as a typo. throw driverError("unsupported", FRAME_SELECTOR_UNSUPPORTED_MESSAGE); } const exact = contexts.find((c) => c.context === selector); if (exact) return exact; throw driverError("no-such-target", `no context matching '${selector}'`); } /* ---------------------------------- PageDriver ---------------------------------- */ class BidiPageDriver implements PageDriver { private released = false; private bodyCollector?: string; constructor(private readonly conn: BidiConnection, private readonly contextId: BrowsingContextId, readonly info: PageInfo, readonly browser: BrowserDriver) {} /** `location.href` and `document.readyState` in one round trip, NUL-joined so the result comes * back as one plain string (deserializeRemote's simplest shape). Empty strings on any failure — * a transient evaluate error during a navigation is normal and must not abort a poll. */ private async urlAndReadyState(): Promise<[string, string]> { const raw = await this.conn.send("script.evaluate", { expression: "location.href + '\\u0000' + document.readyState", target: { context: this.contextId }, awaitPromise: false, }).then((r) => (r.type === "success" ? String(deserializeRemote(r.result) ?? "") : "")).catch(() => ""); const [url = "", ready = ""] = raw.split("\u0000"); return [url, ready]; } /** * Bounded readiness wait after a history traversal. * * WHY THIS EXISTS AT ALL. browsingContext.navigate and .reload both take a `wait` readiness state * and block server-side until it is reached, which is why the two branches below simply return * `waitedFor: waitUntil`. browsingContext.traverseHistory takes NO `wait` parameter and returns * as soon as the traversal is dispatched, so this driver owns the wait for that one path — the * same position cdp/driver.ts is in for every navigation. * * Polling rather than a `browsingContext.load` subscription, matching waitForText's in-file * pattern: a bfcache restore does not necessarily re-fire a load event, so an event wait could * hang on a perfectly successful traversal while a poll observes the settled document directly. * * KNOWN LIMIT, stated rather than hidden: "we moved" is inferred from the url changing. A * traversal between two history entries with the IDENTICAL url therefore cannot be confirmed and * burns the whole budget before returning "timeout" — with the correct url, and after the * traversal really did happen. That is the honest reading of the only signal available here. */ private async settleAfterTraversal(beforeUrl: string, waitUntil: "load" | "domcontentloaded", timeoutMs: number): Promise<{ waitedFor: NavigateResult["waitedFor"]; url: string }> { const ready = waitUntil === "domcontentloaded" ? ["interactive", "complete"] : ["complete"]; const deadline = Date.now() + timeoutMs; for (;;) { const [url, state] = await this.urlAndReadyState(); if (url && url !== beforeUrl && ready.includes(state)) return { waitedFor: waitUntil, url }; if (Date.now() >= deadline) return { waitedFor: "timeout", url: url || beforeUrl }; await new Promise((r) => setTimeout(r, 50)); } } async navigate(opts: NavigateOptions): Promise { const reload = opts.reload === true; const history = opts.history; if (!reload && !history && !opts.url) throw driverError("page-error", "navigate: 'url' is required unless reload:true"); const waitUntil = opts.waitUntil ?? "load"; const wait: BrowsingContextReadinessState = waitUntil === "domcontentloaded" ? "interactive" : "complete"; const sendOpts = opts.timeoutMs !== undefined ? { timeoutMs: opts.timeoutMs } : {}; try { if (reload) { // Firefox rejects ANY `ignoreCache` argument to browsingContext.reload — even an // explicit `false` — with `Argument "ignoreCache" is not supported yet` (observed on // Firefox 153.0.3): the server-side validator refuses the key unconditionally, it does // not read its value. So the key is OMITTED from the params unless a hard reload was // actually requested, and a requested hard reload fails fast HERE with a // backend-capability error instead of an opaque mid-flight protocol rejection — the // same doctrine as click()'s modifiers on this backend. If a future Firefox starts // honoring the argument, re-verify and lift the guard. if (opts.ignoreCache === true) { throw driverError( "unsupported", "navigate: ignoreCache:true (hard reload) is not supported on the Firefox WebDriver-BiDi backend — Firefox rejects the ignoreCache argument outright. A plain reload (reload:true, no ignoreCache) works.", ); } const r = await this.conn.send("browsingContext.reload", { context: this.contextId, wait }, sendOpts); return { url: r.url, contextId: this.contextId, reloaded: true, waitedFor: waitUntil }; } if (history) { const [beforeUrl] = await this.urlAndReadyState(); // NavigateOptions.history forbids a silent no-op. Firefox answers a traversal past either // end of the session history with a "no such history entry" error, which mapBidiError would // relay verbatim — a message that never names the direction the caller asked for. Rewrapped // here so back-at-the-start and forward-at-the-end read the same on both backends. await this.conn.send("browsingContext.traverseHistory", { context: this.contextId, delta: history === "back" ? -1 : 1 }, sendOpts) .catch((e) => { const msg = e instanceof Error ? e.message : String(e); if (/no such history entry|history/i.test(msg)) throw driverError("page-error", `navigate: no history entry to go ${history} to (${msg})`); throw e; }); const settled = await this.settleAfterTraversal(beforeUrl, waitUntil, opts.timeoutMs ?? 15_000); return { url: settled.url, contextId: this.contextId, traversed: history, waitedFor: settled.waitedFor }; } const r = await this.conn.send("browsingContext.navigate", { context: this.contextId, url: opts.url as string, wait }, sendOpts); return { url: r.url, contextId: this.contextId, waitedFor: waitUntil }; } catch (e) { // NavigateResult.waitedFor's "committed"/"timeout" values assume CDP's fire-and-forget // navigate plus separate milestone events (see cdp/driver.ts's own comment on this). BiDi's // navigate blocks server-side until `wait` is satisfied, so under this driver there is no // soft "timeout" return: an unreachable milestone surfaces as a thrown timeout error instead. throw mapBidiError(e); } } async waitForText(text: string, timeoutMs = 15_000, pollMs = 250): Promise<{ found: true; elapsedMs: number }> { const start = Date.now(); const expr = `(() => { const b = document.body; return !!b && typeof b.innerText === 'string' && b.innerText.includes(${JSON.stringify(text)}); })()`; for (;;) { const found = await this.conn.send("script.evaluate", { expression: expr, target: { context: this.contextId }, awaitPromise: true }) .then((r) => r.type === "success" && deserializeRemote(r.result) === true) .catch(() => false); if (found) return { found: true, elapsedMs: Date.now() - start }; if (Date.now() - start >= timeoutMs) throw driverError("timeout", `waitForText: '${text}' not found within ${timeoutMs}ms`); await new Promise((r) => setTimeout(r, Math.min(pollMs, Math.max(0, timeoutMs - (Date.now() - start))))); } } private async callFunctionValue(functionDeclaration: string, args: unknown[], thisRef?: ScriptSharedReference): Promise { try { const res = await this.conn.send("script.callFunction", { functionDeclaration, awaitPromise: true, target: { context: this.contextId }, arguments: args.map(serializeArg), ...(thisRef ? { this: thisRef as ScriptLocalValue } : {}), }); if (res.type === "exception") throw driverError("page-error", exceptionMessage(res.exceptionDetails)); return deserializeRemote(res.result); } catch (e) { throw isDriverError(e) ? e : mapBidiError(e); } } async evaluate(expression: string, opts?: { args?: readonly unknown[]; awaitPromise?: boolean }): Promise { const awaitPromise = opts?.awaitPromise ?? true; if (opts?.args && opts.args.length > 0) return this.callFunctionValue(expression, [...opts.args]); try { const res = await this.conn.send("script.evaluate", { expression, awaitPromise, target: { context: this.contextId } }); if (res.type === "exception") throw driverError("page-error", exceptionMessage(res.exceptionDetails)); return deserializeRemote(res.result); } catch (e) { throw isDriverError(e) ? e : mapBidiError(e); } } async callOnElement(loc: ElementLocator, functionDeclaration: string, args: readonly unknown[] = []): Promise { const ref = await resolveElementLocator(this.conn, this.contextId, loc); return this.callFunctionValue(functionDeclaration, [...args], ref); } async snapshot(opts?: { interactiveOnly?: boolean }): Promise { const { snapshot } = await takeStampedSnapshot((src) => this.callFunctionValue(src, [])); const nodes: SnapshotNode[] = []; for (const line of snapshot.split("\n")) { if (!line) continue; const n = parseSnapshotLine(line); if (n) nodes.push(n); } return opts?.interactiveOnly ? nodes.filter((n) => INTERACTIVE_ROLES.has(n.role)) : nodes; } async locate(loc: ElementLocator): Promise { if ("uid" in loc) { await this.resolve(loc.uid); return loc.uid; } const ref = await resolveElementLocator(this.conn, this.contextId, loc); const stamp = await this.callFunctionValue(STAMP_ONE_SOURCE, [], ref); if (typeof stamp !== "string") throw driverError("page-error", "stamping the located element did not return a string"); return encodeUid(stamp); } async resolve(uid: DriverUid): Promise { const stamp = decodeStamp(uid); const nodes = await locateNodes(this.conn, this.contextId, { type: "css", value: `[${UID_STAMP_ATTR}="${cssEscape(stamp)}"]` }); if (!nodes.length) throw driverError("stale-uid", `uid does not resolve: ${uid}`); } /** * THE INPUT DISPATCH CHOKE POINT for Firefox, and the direct counterpart of * cdp/driver.ts's dispatchInput. Every synthesized input this driver produces * is already funnelled through this one method (hover, click, scroll, drag, * setValue, typeText, pressKey all build actions and call it), so the * dispatch-log write that keeps the toolkit's own input from reading as a * human's needs exactly one line, here. See ../activity.ts. * * scroll and the generalised drag arrived on the OTHER 1.8.0 branch (Track P) * and inherited the log for free by building on this method — which is the * whole argument for a choke point, and the reason this list is worth keeping * accurate rather than deleting. * * NOT routed through here: input.setFiles (upload_file). Same reasoning as the * CDP side — it fires none of the beacon's events, so logging it could only * suppress a real human input, never prevent a false one. */ private async performActions(actions: InputSourceActions[]): Promise { recordDispatch("firefox", this.contextId); try { await this.conn.send("input.performActions", { context: this.contextId, actions }); } catch (e) { throw mapBidiError(e); } } // Scroll into view + read the viewport-space center, mirroring cdp/driver.ts's centerOf. private async centerOf(ref: ScriptSharedReference): Promise<{ x: number; y: number }> { const fn = "function(){this.scrollIntoView({block:'center',inline:'center'});const r=this.getBoundingClientRect();if(r.width===0&&r.height===0)return null;return {x:r.left+r.width/2,y:r.top+r.height/2};}"; const val = await this.callFunctionValue(fn, [], ref); if (!val || typeof val !== "object") throw driverError("page-error", "element has zero size / is not visible; cannot compute a click point"); return val as { x: number; y: number }; } async hover(loc: ElementLocator): Promise<{ x: number; y: number }> { const ref = await resolveElementLocator(this.conn, this.contextId, loc); const { x, y } = await this.centerOf(ref); await this.performActions([{ type: "pointer", id: "cdp-mouse", actions: [{ type: "pointerMove", x, y, duration: 0 }] }]); return { x, y }; } // modifiers (1.8.0 Track P1). Chrome expresses it as a bitmask on the same mousePressed/mouseReleased // events (cdp/driver.ts's inputModifierBits); BiDi has no such field on pointerDown/pointerUp, so a // chord is a SECOND "key" source ticked in lockstep with the pointer source inside ONE // performActions call (modifierChord below). Measured on Firefox 160.0 (shift+click saw // shiftKey=true); an older Firefox is refused by requireFirefox("input.modifierClick"). async click(loc: ElementLocator, opts?: MouseButtonOptions): Promise<{ x: number; y: number }> { const hasModifiers = !!opts?.modifiers && opts.modifiers.length > 0; if (hasModifiers) requireFirefox(this.conn, "input.modifierClick"); const keys = modifierKeyValues(opts?.modifiers); const ref = await resolveElementLocator(this.conn, this.contextId, loc); const { x, y } = await this.centerOf(ref); const button = BUTTON_CODES[opts?.button ?? "left"]; const actions: InputPointerSourceAction[] = [{ type: "pointerMove", x, y, duration: 0 }]; for (let i = 0; i < (opts?.clickCount ?? 1); i++) actions.push({ type: "pointerDown", button }, { type: "pointerUp", button }); await this.performActions(modifierChord("cdp-mouse", actions, keys)); return { x, y }; } // dispatch_mouse on Firefox (capability "input.raw", 160+): ONE raw pointer event per call. BiDi's // pointer source is a virtual device with session-lifetime state, so a "down" in one call stays held // for an "up" in a later call as long as the source id is the same: RAW_MOUSE_SOURCE_ID is a constant // for that reason (and distinct from click/drag's "cdp-mouse", which always finish their own press). // The state lives in the shared BiDi session (bidi/mux.ts), not in this driver instance, so it // survives the per-tool-call driver acquisition. Unlike CDP, BiDi has no coordinate-less event: every // action is a pointerMove to (x,y) first, so a "down"/"up" also emits a mousemove if the pointer // was elsewhere. clickCount is not a BiDi field (the browser derives click counts from timing), so // it is ignored here. async dispatchMouse(event: RawMouseEvent): Promise { requireFirefox(this.conn, "input.raw"); const keys = modifierKeyValues(event.modifiers); const button = BUTTON_CODES[event.button ?? "left"]; const actions: InputPointerSourceAction[] = [{ type: "pointerMove", x: event.x, y: event.y, duration: 0 }]; if (event.action === "down") actions.push({ type: "pointerDown", button }); else if (event.action === "up") actions.push({ type: "pointerUp", button }); await this.performActions(modifierChord(RAW_MOUSE_SOURCE_ID, actions, keys)); } // 1.8.0 Track P1: BiDi's "wheel" input source (a distinct source type from "pointer"/"key") // carries x/y/deltaX/deltaY directly on its one "scroll" action — no tick synchronization with // another source needed, unlike click's modifiers above, which is what makes this tractable. // Same settle-wait rationale as cdp/driver.ts's armScrollSettleWatch: a wheel-triggered scroll // is a browser-animated effect, not a synchronous DOM mutation, so a caller reading scroll // position immediately after performActions resolves risks the pre-scroll value. Not empirically // verified against real Firefox this pass (no Firefox available in this environment), but applied // for consistency with the verified Chrome behavior rather than left as a known, unfixed gap. async scroll(anchor: ElementLocator | { x: number; y: number } | undefined, opts: ScrollOptions): Promise<{ x: number; y: number }> { const { x, y } = await this.resolveScrollPoint(anchor); const deltaX = Math.round(opts.deltaX ?? 0); const deltaY = Math.round(opts.deltaY ?? 0); await this.callFunctionValue(ARM_SCROLL_SETTLE_WATCH_SOURCE, []); const actions: InputWheelSourceAction[] = [{ type: "scroll", x: Math.round(x), y: Math.round(y), deltaX, deltaY }]; await this.performActions([{ type: "wheel", id: "cdp-wheel", actions }]); await this.callFunctionValue(AWAIT_SCROLL_SETTLE_SOURCE, []).catch(() => undefined); return { x, y }; } private async resolveScrollPoint(anchor: ElementLocator | { x: number; y: number } | undefined): Promise<{ x: number; y: number }> { if (anchor === undefined) { const v = await this.callFunctionValue("function(){return {x: window.innerWidth / 2, y: window.innerHeight / 2};}", []); if (!v || typeof v !== "object") throw driverError("page-error", "could not measure viewport for scroll center"); return v as { x: number; y: number }; } if ("x" in anchor) return anchor; return this.centerOf(await resolveElementLocator(this.conn, this.contextId, anchor)); } // 1.8.0 Track P2. mode:"html5" is REFUSED here, never silently downgraded to mouse mode: WebDriver // BiDi has no drag-interception primitive at all (no setInterceptDrags equivalent, no drag event // to subscribe to, no dispatchDragEvent), so there is nothing to port. The param-level refusal // mirrors click's modifiers-on-Firefox above — `drag` itself stays in tools/list because mouse // mode is fully supported here. `to` accepting a point or an offset, and `steps`, are both // backend-neutral and DO work on this driver. async drag(from: ElementLocator, to: DragDestination, opts?: DragOptions): Promise<{ from: { x: number; y: number }; to: { x: number; y: number } }> { if (opts?.mode === "html5") { throw driverError( "unsupported", "drag: mode:'html5' is not supported by the Firefox/BiDi driver (WebDriver BiDi has no drag-interception primitive); " + "omit 'mode' for the synthetic-mouse drag, or use --browser chrome for real HTML5 drag events.", ); } const fromPt = await this.centerOf(await resolveElementLocator(this.conn, this.contextId, from)); const toPt = await this.resolveDragDestination(to, fromPt); const steps = Math.max(1, Math.trunc(opts?.steps ?? 2)); const actions: InputPointerSourceAction[] = [ { type: "pointerMove", x: fromPt.x, y: fromPt.y, duration: 0 }, { type: "pointerDown", button: 0 }, ]; for (const pt of interpolatePoints(fromPt, toPt, steps)) actions.push({ type: "pointerMove", x: pt.x, y: pt.y, duration: 50 }); actions.push({ type: "pointerUp", button: 0 }); await this.performActions([{ type: "pointer", id: "cdp-mouse", actions }]); return { from: fromPt, to: toPt }; } private async resolveDragDestination(to: DragDestination, fromPt: { x: number; y: number }): Promise<{ x: number; y: number }> { if ("dx" in to) return { x: fromPt.x + to.dx, y: fromPt.y + to.dy }; if ("x" in to) return to; return this.centerOf(await resolveElementLocator(this.conn, this.contextId, to)); } // No atomic value-commit primitive over BiDi (established fact): every key goes through // input.performActions, batched into ONE call regardless of string length, so setValue/typeText // cost exactly 2 round trips (one evaluate to focus/clear, one performActions for the keys). private async sendKeys(text: string): Promise { if (!text.length) return; const actions: InputKeySourceAction[] = []; for (const ch of text) actions.push({ type: "keyDown", value: ch }, { type: "keyUp", value: ch }); await this.performActions([{ type: "key", id: "cdp-keyboard", actions }]); } // /