codex-browser-use 4.8.3 → 4.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -208,6 +208,8 @@ export class BridgeBrowser {
208
208
  this.activeTabId = null;
209
209
  /** @type {Set<number>} */
210
210
  this.attached = new Set();
211
+ /** @type {Set<number>} */
212
+ this.userCanceledTabs = new Set();
211
213
  /** @type {Map<number, Promise<void>>} */
212
214
  this.attaching = new Map();
213
215
  /** @type {Set<(event: Record<string, unknown>) => void>} */
@@ -224,7 +226,13 @@ export class BridgeBrowser {
224
226
  this.locatorRuntimeInstalled = new Map();
225
227
  /** @type {Set<string>} */
226
228
  this.statelessEvalTabs = new Set();
229
+ /** @type {Map<number, {clientWidth:number, clientHeight:number}>} */
230
+ this.viewportSizeCache = new Map();
231
+ /** @type {Map<number, number>} */
232
+ this.devicePixelRatioCache = new Map();
227
233
  this.supportsPassiveRead = Boolean(info?.apiSupportOverrides?.["BrowserUser.getTabContext"]);
234
+ this.supportsCdpBatch = Boolean(info?.apiSupportOverrides?.["Bridge.executeCdpBatch"]);
235
+ this.supportsAttachFocusAndPage = Boolean(info?.apiSupportOverrides?.["Bridge.attachFocusAndPage"]);
228
236
  /** @type {Map<number, Map<string,{backendDOMNodeId:number|null,role:string,name:string,frameId?:string|null,sessionId?:string|null,actions?:string[],dialogControl?:string}>>} */
229
237
  this.axCache = new Map();
230
238
  /** @type {Map<number, {documentKey:string, entries:Array<any>}>} */
@@ -258,6 +266,9 @@ export class BridgeBrowser {
258
266
  browserRef?.#clearTabCaches(tabId);
259
267
  browserRef?.attached.delete(tabId);
260
268
  browserRef?.autoAttached.delete(tabId);
269
+ if (params?.reason === "canceled_by_user") {
270
+ browserRef?.userCanceledTabs.add(tabId);
271
+ }
261
272
  } else if (method === "onTabCreated") {
262
273
  browserRef?.handleTabCreated(params);
263
274
  }
@@ -715,6 +726,9 @@ export class BridgeBrowser {
715
726
  } catch (error) {
716
727
  const msg = error instanceof Error ? error.message : String(error);
717
728
  if (!/Debugger unattached/i.test(msg)) throw error;
729
+ if (this.userCanceledTabs.has(tabId)) {
730
+ throw new Error(`Browser debugging on tab ${tabId} was canceled by the user. Select or re-claim the tab to resume.`);
731
+ }
718
732
  this.attached.delete(tabId);
719
733
  this.#clearTabCaches(tabId);
720
734
  this.autoAttached.delete(tabId);
@@ -739,6 +753,60 @@ export class BridgeBrowser {
739
753
  return sessionId ? this.#cdpIn(tabId, sessionId, method, params) : this.#cdp(tabId, method, params);
740
754
  }
741
755
 
756
+ /**
757
+ * Execute multiple CDP commands over a single bridge RTT when `Bridge.executeCdpBatch`
758
+ * is supported, falling back cleanly to sequential `#cdpTarget` calls otherwise.
759
+ * @param {number} tabId
760
+ * @param {Array<{method:string, params?:Record<string,unknown>, sessionId?:string|null, fireAndForget?:boolean, ignoreError?:boolean, batchOnly?:boolean}>} commands
761
+ * @param {string|null|undefined} [sessionId]
762
+ * @returns {Promise<Array<any>>}
763
+ */
764
+ async #cdpBatch(tabId, commands, sessionId = null) {
765
+ if (commands.length === 0) return [];
766
+ if (this.supportsCdpBatch) {
767
+ const target = sessionId ? { tabId, sessionId } : { tabId };
768
+ const rpcCommands = commands.map((cmd) => ({
769
+ method: cmd.method,
770
+ commandParams: cmd.params ?? {},
771
+ ...(cmd.sessionId ? { sessionId: cmd.sessionId } : {}),
772
+ ...(cmd.fireAndForget ? { fireAndForget: true } : {}),
773
+ ...(cmd.ignoreError ? { ignoreError: true } : {}),
774
+ }));
775
+ const res = await this.#rpc("executeCdpBatch", { target, commands: rpcCommands });
776
+ return Array.isArray(res?.results) ? res.results : [];
777
+ }
778
+ const results = [];
779
+ let lastObjectId = null;
780
+ for (const cmd of commands) {
781
+ if (cmd.batchOnly) {
782
+ results.push(null);
783
+ continue;
784
+ }
785
+ const params = { ...(cmd.params ?? {}) };
786
+ for (const [k, v] of Object.entries(params)) {
787
+ if (v === "$prev.object.objectId" || v === "$prev.result.objectId") {
788
+ if (!lastObjectId) throw new Error("CDP batch step missing previous objectId");
789
+ params[k] = lastObjectId;
790
+ }
791
+ }
792
+ if (cmd.fireAndForget) {
793
+ void this.#cdpTarget(tabId, cmd.sessionId ?? sessionId, cmd.method, params).catch(() => {});
794
+ results.push(null);
795
+ continue;
796
+ }
797
+ try {
798
+ const out = await this.#cdpTarget(tabId, cmd.sessionId ?? sessionId, cmd.method, params);
799
+ const nextId = out?.object?.objectId ?? out?.result?.objectId;
800
+ if (typeof nextId === "string" && nextId) lastObjectId = nextId;
801
+ results.push(out);
802
+ } catch (error) {
803
+ if (cmd.ignoreError) results.push({ error: error instanceof Error ? error.message : String(error) });
804
+ else throw error;
805
+ }
806
+ }
807
+ return results;
808
+ }
809
+
742
810
  /** @param {number} tabId @param {string|null} [sessionId] @returns {void} */
743
811
  #clearLocatorRuntime(tabId, sessionId = null) {
744
812
  if (sessionId !== null) {
@@ -756,7 +824,8 @@ export class BridgeBrowser {
756
824
  this.enabledDomains.delete(tabId);
757
825
  this.enablingDomains.delete(tabId);
758
826
  this.frameRouteCache.delete(tabId);
759
- this.#clearLocatorRuntime(tabId);
827
+ this.viewportSizeCache.delete(tabId);
828
+ this.devicePixelRatioCache.delete(tabId);
760
829
  this.#clearLocatorRuntime(tabId);
761
830
  const frameMap = this.frameSessions.get(tabId);
762
831
  if (frameMap) {
@@ -829,6 +898,10 @@ export class BridgeBrowser {
829
898
  this.#assertOpen();
830
899
  const id = Number(tabId);
831
900
  if (!Number.isSafeInteger(id)) throw new Error("A numeric tab_id is required");
901
+ this.userCanceledTabs.delete(id);
902
+ const prevOwned = this.ownedTabs.has(id);
903
+ const prevTab = this.tabs.get(id);
904
+ const prevActive = this.activeTabId;
832
905
  let tab;
833
906
  try {
834
907
  tab = await this.#rpc("claimUserTab", { tabId: id });
@@ -839,7 +912,18 @@ export class BridgeBrowser {
839
912
  this.ownedTabs.add(tab.id);
840
913
  this.tabs.set(tab.id, { ...tab, owned: true, origin: tab.origin || "user" });
841
914
  this.activeTabId = tab.id;
842
- await this.attach(tab.id);
915
+ try {
916
+ await this.attach(tab.id);
917
+ } catch (error) {
918
+ if (!prevOwned) {
919
+ await this.#rpc("releaseUserTab", { tabId: tab.id }).catch(() => {});
920
+ this.ownedTabs.delete(tab.id);
921
+ if (prevTab) this.tabs.set(tab.id, prevTab);
922
+ else this.tabs.delete(tab.id);
923
+ this.activeTabId = prevActive;
924
+ }
925
+ throw error;
926
+ }
843
927
  return {
844
928
  tab_id: String(tab.id),
845
929
  title: tab.title || "Untitled",
@@ -929,6 +1013,9 @@ export class BridgeBrowser {
929
1013
  /** @param {number} tabId @returns {Promise<void>} */
930
1014
  async attach(tabId) {
931
1015
  if (this.attached.has(tabId)) return;
1016
+ if (this.userCanceledTabs.has(tabId)) {
1017
+ throw new Error(`Browser debugging on tab ${tabId} was canceled by the user. Select or re-claim the tab to resume.`);
1018
+ }
932
1019
  const inflight = this.attaching.get(tabId);
933
1020
  if (inflight) {
934
1021
  await inflight;
@@ -939,6 +1026,9 @@ export class BridgeBrowser {
939
1026
  await this.#rpc("attach", { tabId });
940
1027
  } catch (error) {
941
1028
  const msg = error instanceof Error ? error.message : String(error);
1029
+ if (/Another debugger is already attached/i.test(msg)) {
1030
+ throw new Error(`Another debugger (such as Chrome DevTools) is already attached to tab ${tabId}. Close DevTools on that tab and retry.`);
1031
+ }
942
1032
  if (/Browser tab is unavailable to this session/i.test(msg)) {
943
1033
  this.ownedTabs.delete(tabId);
944
1034
  this.tabs.delete(tabId);
@@ -955,7 +1045,16 @@ export class BridgeBrowser {
955
1045
  this.frameRouteCache.delete(tabId);
956
1046
  this.#clearLocatorRuntime(tabId);
957
1047
  this.#tabState(tabId);
958
- await this.#cdp(tabId, "Emulation.setFocusEmulationEnabled", { enabled: true }).catch(() => {});
1048
+ if (this.supportsAttachFocusAndPage) {
1049
+ let domains = this.enabledDomains.get(tabId);
1050
+ if (!domains) {
1051
+ domains = new Set();
1052
+ this.enabledDomains.set(tabId, domains);
1053
+ }
1054
+ domains.add("Page");
1055
+ } else {
1056
+ await this.#cdp(tabId, "Emulation.setFocusEmulationEnabled", { enabled: true }).catch(() => {});
1057
+ }
959
1058
  })().finally(() => {
960
1059
  this.attaching.delete(tabId);
961
1060
  });
@@ -1049,6 +1148,7 @@ export class BridgeBrowser {
1049
1148
  async selectTab(tabId) {
1050
1149
  const id = Number(tabId);
1051
1150
  if (!Number.isSafeInteger(id)) throw new Error("A numeric tab_id is required");
1151
+ this.userCanceledTabs.delete(id);
1052
1152
  const resolved = await this.#resolveTab(id);
1053
1153
  this.activeTabId = resolved;
1054
1154
  await this.attach(resolved);
@@ -1084,6 +1184,7 @@ export class BridgeBrowser {
1084
1184
  this.lastAxSnapshots.delete(id);
1085
1185
  this.frameRouteCache.delete(id);
1086
1186
  const state = this.#tabState(id);
1187
+ const startRev = state.navRevision;
1087
1188
  state.committed = false;
1088
1189
  state.ready = false;
1089
1190
  state.domContentLoaded = false;
@@ -1093,14 +1194,14 @@ export class BridgeBrowser {
1093
1194
  let committed = false;
1094
1195
  try {
1095
1196
  await this.#rpc("navigateTab", { tabId: id, url: target });
1096
- await this.#waitForCommit(id, target, Math.min(5_000, timeoutMs));
1197
+ await this.#waitForCommit(id, target, Math.min(5_000, timeoutMs), startRev);
1097
1198
  committed = true;
1098
1199
  } catch {
1099
1200
  // Fall back to CDP navigation when the tab-level navigation does not commit.
1100
1201
  }
1101
1202
  if (!committed) {
1102
1203
  await this.#navigateWithCdp(id, target);
1103
- await this.#waitForCommit(id, target, timeoutMs);
1204
+ await this.#waitForCommit(id, target, timeoutMs, startRev);
1104
1205
  }
1105
1206
  if (waitUntil !== "commit") {
1106
1207
  await this.#waitForLoad(id, { waitUntil, timeoutMs });
@@ -1210,16 +1311,23 @@ export class BridgeBrowser {
1210
1311
 
1211
1312
  let cssScale = 1;
1212
1313
  let metrics = null;
1314
+ const cachedDpr = this.devicePixelRatioCache.get(id);
1213
1315
  if (scale === "css" && !clip) {
1214
1316
  const [dpr, layout] = await Promise.all([
1215
- this.#evaluateRaw(id, "window.devicePixelRatio").catch(() => 1),
1317
+ cachedDpr !== undefined ? cachedDpr : this.#evaluateRaw(id, "window.devicePixelRatio").catch(() => 1),
1216
1318
  this.#cdp(id, "Page.getLayoutMetrics").catch(() => null),
1217
1319
  ]);
1218
- if (typeof dpr === "number" && Number.isFinite(dpr) && dpr > 1) cssScale = 1 / dpr;
1320
+ if (typeof dpr === "number" && Number.isFinite(dpr) && dpr > 0) {
1321
+ this.devicePixelRatioCache.set(id, dpr);
1322
+ if (dpr > 1) cssScale = 1 / dpr;
1323
+ }
1219
1324
  metrics = layout;
1220
1325
  } else if (scale === "css") {
1221
- const dpr = await this.#evaluateRaw(id, "window.devicePixelRatio").catch(() => 1);
1222
- if (typeof dpr === "number" && Number.isFinite(dpr) && dpr > 1) cssScale = 1 / dpr;
1326
+ const dpr = cachedDpr !== undefined ? cachedDpr : await this.#evaluateRaw(id, "window.devicePixelRatio").catch(() => 1);
1327
+ if (typeof dpr === "number" && Number.isFinite(dpr) && dpr > 0) {
1328
+ this.devicePixelRatioCache.set(id, dpr);
1329
+ if (dpr > 1) cssScale = 1 / dpr;
1330
+ }
1223
1331
  }
1224
1332
 
1225
1333
  if (clip && Number.isFinite(clip.width) && Number.isFinite(clip.height)) {
@@ -1302,19 +1410,68 @@ export class BridgeBrowser {
1302
1410
  this.#ensureDomain(id, "Accessibility", "Accessibility.enable"),
1303
1411
  ]);
1304
1412
 
1305
- // Capture main frame AX tree, frame tree, location, and optional screenshot in parallel.
1306
- const [mainTree, frameTreeResp, location, cap] = await Promise.all([
1413
+ const useDiff = diff && !full;
1414
+ const prev = this.lastAxSnapshots.get(id);
1415
+ if (
1416
+ useDiff &&
1417
+ !screenshot &&
1418
+ prev &&
1419
+ prev.hasIndexedBaseline &&
1420
+ prev.mode === mode &&
1421
+ prev.maxLines === maxLines &&
1422
+ tabState.hasEvents &&
1423
+ tabState.lastAxUpdateMs > 0 &&
1424
+ prev.navRevision === tabState.navRevision &&
1425
+ prev.lastAxUpdateMs === tabState.lastAxUpdateMs &&
1426
+ this.axCache.has(id)
1427
+ ) {
1428
+ const cachedTitle = prev.title ?? this.tabs.get(id)?.title ?? "";
1429
+ const cachedUrl = prev.url ?? tabState.url ?? this.tabs.get(id)?.url ?? "";
1430
+ return {
1431
+ tab_id: String(id),
1432
+ title: cachedTitle,
1433
+ url: cachedUrl,
1434
+ mode: "unchanged",
1435
+ axText: [
1436
+ `Title: ${cachedTitle}`,
1437
+ `URL: ${cachedUrl}`,
1438
+ "<ax_state>",
1439
+ "No accessibility changes.",
1440
+ "</ax_state>",
1441
+ ].join("\n"),
1442
+ elementCount: prev.elementCount ?? this.axCache.get(id)?.size ?? 0,
1443
+ screenshotBase64: null,
1444
+ screenshotMimeType: null,
1445
+ notifications: this.drainNotifications(id),
1446
+ };
1447
+ }
1448
+
1449
+ // Capture main frame AX tree, frame tree, and optional screenshot in parallel.
1450
+ const [mainTree, frameTreeResp, cap] = await Promise.all([
1307
1451
  this.#cdp(id, "Accessibility.getFullAXTree"),
1308
1452
  this.#cdp(id, "Page.getFrameTree").catch(() => null),
1309
- this.#evaluateRaw(id, "({title: document.title, url: location.href})").catch(() => ({
1310
- title: this.tabs.get(id)?.title ?? "",
1311
- url: this.tabs.get(id)?.url ?? "",
1312
- })),
1313
1453
  screenshot ? this.screenshot(id, { fullPage, format, quality }).catch(() => null) : null,
1314
1454
  ]);
1315
1455
 
1456
+ const mainNodes = mainTree?.nodes ?? [];
1457
+ const rootAx = mainNodes.find((n) => n?.role?.value === "RootWebArea" || n?.role?.value === "WebArea");
1458
+ const axTitle = typeof rootAx?.name?.value === "string" ? rootAx.name.value : null;
1459
+ const ftUrl = typeof frameTreeResp?.frameTree?.frame?.url === "string" && frameTreeResp.frameTree.frame.url
1460
+ ? frameTreeResp.frameTree.frame.url
1461
+ : null;
1462
+
1463
+ let location;
1464
+ if (axTitle !== null && ftUrl !== null) {
1465
+ location = { title: axTitle, url: ftUrl };
1466
+ } else {
1467
+ location = await this.#evaluateRaw(id, "({title: document.title, url: location.href})").catch(() => ({
1468
+ title: axTitle ?? this.tabs.get(id)?.title ?? "",
1469
+ url: ftUrl ?? tabState.url ?? this.tabs.get(id)?.url ?? "",
1470
+ }));
1471
+ }
1472
+
1316
1473
  const frameTrees = [{
1317
- nodes: mainTree?.nodes ?? [],
1474
+ nodes: mainNodes,
1318
1475
  frameId: null,
1319
1476
  sessionId: null,
1320
1477
  depth: 0,
@@ -1330,10 +1487,8 @@ export class BridgeBrowser {
1330
1487
  const url = String(location?.url || "");
1331
1488
  const documentKey = `${tabState.loaderId ?? ""}:${url}`;
1332
1489
 
1333
- const useDiff = diff && !full;
1334
- const prev = this.lastAxSnapshots.get(id);
1335
1490
  let diffResult = useDiff
1336
- ? buildAxDiff(prev, { documentKey, lines: merged.lines, entries: merged.entries })
1491
+ ? buildAxDiff(prev, { documentKey, lines: merged.lines, entries: merged.entries, mode })
1337
1492
  : { mode: "full", lines: merged.lines };
1338
1493
  if (useDiff && prev?.hasIndexedBaseline === false && diffResult.mode === "unchanged") {
1339
1494
  diffResult = allowUnindexedBaseline
@@ -1341,7 +1496,18 @@ export class BridgeBrowser {
1341
1496
  : { mode: "full", lines: merged.lines };
1342
1497
  }
1343
1498
 
1344
- this.lastAxSnapshots.set(id, { documentKey, entries: merged.entries, hasIndexedBaseline: true });
1499
+ this.lastAxSnapshots.set(id, {
1500
+ documentKey,
1501
+ entries: merged.entries,
1502
+ hasIndexedBaseline: true,
1503
+ mode,
1504
+ maxLines,
1505
+ navRevision: tabState.navRevision,
1506
+ lastAxUpdateMs: tabState.lastAxUpdateMs,
1507
+ title,
1508
+ url,
1509
+ elementCount: merged.count,
1510
+ });
1345
1511
 
1346
1512
  const image = cap?.data ?? null;
1347
1513
  const screenshotMimeType = cap?.mimeType ?? null;
@@ -1456,14 +1622,32 @@ export class BridgeBrowser {
1456
1622
  return { tab_id: String(id), ok: true, action: "set_value", index: String(elementIndex) };
1457
1623
  }
1458
1624
  const sessionId = node.sessionId ?? null;
1459
- const { object } = await this.#cdpTarget(id, sessionId, "DOM.resolveNode", { backendNodeId: node.backendDOMNodeId });
1460
- if (!object?.objectId) throw new Error("Browser element could not be resolved");
1461
- const response = await this.#cdpTarget(id, sessionId, "Runtime.callFunctionOn", {
1462
- objectId: object.objectId,
1463
- functionDeclaration: smartSetValueFunctionDeclaration(),
1464
- arguments: [{ value: String(value) }],
1465
- returnByValue: true,
1625
+ const batchResults = await this.#cdpBatch(id, [
1626
+ { method: "DOM.resolveNode", params: { backendNodeId: node.backendDOMNodeId } },
1627
+ {
1628
+ method: "Runtime.callFunctionOn",
1629
+ params: {
1630
+ objectId: "$prev.object.objectId",
1631
+ functionDeclaration: smartSetValueFunctionDeclaration(),
1632
+ arguments: [{ value: String(value) }],
1633
+ returnByValue: true,
1634
+ },
1635
+ },
1636
+ {
1637
+ method: "Runtime.releaseObject",
1638
+ params: { objectId: "$prev.object.objectId" },
1639
+ fireAndForget: true,
1640
+ batchOnly: true,
1641
+ },
1642
+ ], sessionId).catch((error) => {
1643
+ if (/CDP batch step missing previous objectId/i.test(error?.message || "")) {
1644
+ throw new Error("Browser element could not be resolved");
1645
+ }
1646
+ throw error;
1466
1647
  });
1648
+ const resolved = batchResults[0];
1649
+ if (!resolved?.object?.objectId) throw new Error("Browser element could not be resolved");
1650
+ const response = batchResults[1];
1467
1651
  if (response?.exceptionDetails) {
1468
1652
  throw new Error(response.exceptionDetails.exception?.description || response.exceptionDetails.text || "Failed to set element value");
1469
1653
  }
@@ -1514,25 +1698,24 @@ export class BridgeBrowser {
1514
1698
  location: 0,
1515
1699
  };
1516
1700
  if (key.key === "Enter" && key.modifiers === 0) {
1517
- await this.#cdpTarget(tabId, sessionId, "Input.dispatchKeyEvent", {
1518
- type: "rawKeyDown",
1519
- ...base,
1520
- commands: ["insertNewline"],
1521
- });
1522
- await this.#cdpTarget(tabId, sessionId, "Input.dispatchKeyEvent", {
1523
- type: "char",
1524
- ...base,
1525
- text: key.text,
1526
- unmodifiedText: key.text,
1527
- });
1701
+ await this.#cdpBatch(tabId, [
1702
+ { method: "Input.dispatchKeyEvent", params: { type: "rawKeyDown", ...base, commands: ["insertNewline"] } },
1703
+ { method: "Input.dispatchKeyEvent", params: { type: "char", ...base, text: key.text, unmodifiedText: key.text } },
1704
+ { method: "Input.dispatchKeyEvent", params: { type: "keyUp", ...base } },
1705
+ ], sessionId);
1528
1706
  } else {
1529
- await this.#cdpTarget(tabId, sessionId, "Input.dispatchKeyEvent", {
1530
- type: key.text ? "keyDown" : "rawKeyDown",
1531
- ...base,
1532
- ...(key.text ? { text: key.text, unmodifiedText: key.text } : {}),
1533
- });
1707
+ await this.#cdpBatch(tabId, [
1708
+ {
1709
+ method: "Input.dispatchKeyEvent",
1710
+ params: {
1711
+ type: key.text ? "keyDown" : "rawKeyDown",
1712
+ ...base,
1713
+ ...(key.text ? { text: key.text, unmodifiedText: key.text } : {}),
1714
+ },
1715
+ },
1716
+ { method: "Input.dispatchKeyEvent", params: { type: "keyUp", ...base } },
1717
+ ], sessionId);
1534
1718
  }
1535
- await this.#cdpTarget(tabId, sessionId, "Input.dispatchKeyEvent", { type: "keyUp", ...base });
1536
1719
  return key;
1537
1720
  }
1538
1721
 
@@ -1556,8 +1739,13 @@ export class BridgeBrowser {
1556
1739
  const box = await this.#boxModel(id, node, node.sessionId);
1557
1740
  point = { x: box.x, y: box.y };
1558
1741
  } else {
1559
- const metrics = await this.#cdp(id, "Page.getLayoutMetrics");
1560
- const viewport = metrics?.cssLayoutViewport ?? metrics?.layoutViewport ?? { clientWidth: 1280, clientHeight: 800 };
1742
+ let viewport = this.viewportSizeCache.get(id);
1743
+ if (!viewport) {
1744
+ const metrics = await this.#cdp(id, "Page.getLayoutMetrics");
1745
+ const vp = metrics?.cssLayoutViewport ?? metrics?.layoutViewport ?? { clientWidth: 1280, clientHeight: 800 };
1746
+ viewport = { clientWidth: vp.clientWidth || 1280, clientHeight: vp.clientHeight || 800 };
1747
+ this.viewportSizeCache.set(id, viewport);
1748
+ }
1561
1749
  point = { x: Math.floor(viewport.clientWidth / 2), y: Math.floor(viewport.clientHeight / 2) };
1562
1750
  }
1563
1751
  await this.#cdp(id, "Input.dispatchMouseEvent", { type: "mouseWheel", x: point.x, y: point.y, ...deltas });
@@ -1619,22 +1807,28 @@ export class BridgeBrowser {
1619
1807
  if (!Number.isFinite(start.x) || !Number.isFinite(start.y) || !Number.isFinite(end.x) || !Number.isFinite(end.y)) {
1620
1808
  throw new Error("drag requires valid start and end coordinates or element indices");
1621
1809
  }
1622
- const count = Math.max(2, Math.min(30, Number(steps) || 8));
1623
- await this.#cdp(id, "Input.dispatchMouseEvent", { type: "mouseMoved", x: start.x, y: start.y, button: "none", buttons: 0, clickCount: 0, modifiers: 0 });
1624
- await this.#cdp(id, "Input.dispatchMouseEvent", { type: "mousePressed", x: start.x, y: start.y, button: "left", buttons: 1, clickCount: 1, modifiers: 0 });
1810
+ const count = Math.max(2, Math.min(28, Number(steps) || 8));
1811
+ const commands = [
1812
+ { method: "Input.dispatchMouseEvent", params: { type: "mouseMoved", x: start.x, y: start.y, button: "none", buttons: 0, clickCount: 0, modifiers: 0 } },
1813
+ { method: "Input.dispatchMouseEvent", params: { type: "mousePressed", x: start.x, y: start.y, button: "left", buttons: 1, clickCount: 1, modifiers: 0 } },
1814
+ ];
1625
1815
  for (let i = 1; i <= count; i++) {
1626
1816
  const ratio = i / count;
1627
- await this.#cdp(id, "Input.dispatchMouseEvent", {
1628
- type: "mouseMoved",
1629
- x: start.x + (end.x - start.x) * ratio,
1630
- y: start.y + (end.y - start.y) * ratio,
1631
- button: "left",
1632
- buttons: 1,
1633
- clickCount: 0,
1634
- modifiers: 0,
1817
+ commands.push({
1818
+ method: "Input.dispatchMouseEvent",
1819
+ params: {
1820
+ type: "mouseMoved",
1821
+ x: start.x + (end.x - start.x) * ratio,
1822
+ y: start.y + (end.y - start.y) * ratio,
1823
+ button: "left",
1824
+ buttons: 1,
1825
+ clickCount: 0,
1826
+ modifiers: 0,
1827
+ },
1635
1828
  });
1636
1829
  }
1637
- await this.#cdp(id, "Input.dispatchMouseEvent", { type: "mouseReleased", x: end.x, y: end.y, button: "left", buttons: 0, clickCount: 1, modifiers: 0 });
1830
+ commands.push({ method: "Input.dispatchMouseEvent", params: { type: "mouseReleased", x: end.x, y: end.y, button: "left", buttons: 0, clickCount: 1, modifiers: 0 } });
1831
+ await this.#cdpBatch(id, commands);
1638
1832
  return { tab_id: String(id), ok: true, action: "drag", from: start, to: end };
1639
1833
  }
1640
1834
 
@@ -1732,7 +1926,7 @@ export class BridgeBrowser {
1732
1926
  throw err;
1733
1927
  }
1734
1928
  } finally {
1735
- await this.#cdpTarget(id, sessionId, "Runtime.releaseObject", { objectId }).catch(() => {});
1929
+ void this.#cdpTarget(id, sessionId, "Runtime.releaseObject", { objectId }).catch(() => {});
1736
1930
  }
1737
1931
  if (shouldRetry) {
1738
1932
  await sleep(Math.min(50, Math.max(1, deadline - Date.now())));
@@ -2140,6 +2334,8 @@ export class BridgeBrowser {
2140
2334
  mobile: mob,
2141
2335
  });
2142
2336
  this.#tabState(id).viewportOverride = { width: w, height: h, deviceScaleFactor: dsf, mobile: mob };
2337
+ this.viewportSizeCache.set(id, { clientWidth: w, clientHeight: h });
2338
+ this.devicePixelRatioCache.set(id, dsf);
2143
2339
  return { tab_id: String(id), ok: true, width: w, height: h, deviceScaleFactor: dsf, mobile: mob };
2144
2340
  }
2145
2341
 
@@ -2152,6 +2348,8 @@ export class BridgeBrowser {
2152
2348
  await this.attach(id);
2153
2349
  await this.#cdp(id, "Emulation.clearDeviceMetricsOverride", {});
2154
2350
  this.#tabState(id).viewportOverride = null;
2351
+ this.viewportSizeCache.delete(id);
2352
+ this.devicePixelRatioCache.delete(id);
2155
2353
  return { tab_id: String(id), ok: true, reset: true };
2156
2354
  }
2157
2355
 
@@ -2507,7 +2705,7 @@ export class BridgeBrowser {
2507
2705
  const documentKey = `${tabState.loaderId ?? ""}:${url}`;
2508
2706
  const baseline = mergeFrameAxStates(frameTrees, { maxLines, mode });
2509
2707
  this.axCache.set(id, baseline.index);
2510
- this.lastAxSnapshots.set(id, { documentKey, entries: baseline.entries, hasIndexedBaseline: false });
2708
+ this.lastAxSnapshots.set(id, { documentKey, entries: baseline.entries, hasIndexedBaseline: false, mode, maxLines });
2511
2709
  return { tab_id: String(id), ...snapshot };
2512
2710
  }
2513
2711
 
@@ -2527,7 +2725,11 @@ export class BridgeBrowser {
2527
2725
  if (!Number.isSafeInteger(backendNodeId)) {
2528
2726
  throw new Error(`Locator did not resolve to a DOM node: ${selector}`);
2529
2727
  }
2530
- await this.#cdpTarget(id, sessionId, "Accessibility.enable", {}).catch(() => {});
2728
+ if (!sessionId) {
2729
+ await this.#ensureDomain(id, "Accessibility", "Accessibility.enable").catch(() => {});
2730
+ } else {
2731
+ await this.#cdpTarget(id, sessionId, "Accessibility.enable", {}).catch(() => {});
2732
+ }
2531
2733
  const tree = await this.#cdpTarget(id, sessionId, "Accessibility.getFullAXTree", {});
2532
2734
  let snapshot = formatAriaSnapshot(tree?.nodes ?? [], {
2533
2735
  maxLines,
@@ -2730,6 +2932,31 @@ export class BridgeBrowser {
2730
2932
  };
2731
2933
  }
2732
2934
 
2935
+ /** @param {string} selector @param {{tabId?:unknown, frame?:string, force?:boolean, timeoutMs?:number}} [options] */
2936
+ async locatorFocus(selector, { tabId, frame, force = false, timeoutMs } = {}) {
2937
+ const id = await this.#resolveTab(tabId);
2938
+ await this.attach(id);
2939
+ await this.#runLocatorWithAutoWait(id, selector, {
2940
+ frame,
2941
+ mutation: "focus",
2942
+ force,
2943
+ timeoutMs,
2944
+ });
2945
+ return { tab_id: String(id), ok: true, action: "locator_focus", selector, ...(frame ? { frame } : {}) };
2946
+ }
2947
+
2948
+ /** @param {string} selector @param {{tabId?:unknown, frame?:string, timeoutMs?:number}} [options] */
2949
+ async locatorBoundingBox(selector, { tabId, frame, timeoutMs } = {}) {
2950
+ const id = await this.#resolveTab(tabId);
2951
+ await this.attach(id);
2952
+ const { result } = await this.#runLocatorWithAutoWait(id, selector, {
2953
+ frame,
2954
+ mutation: "box",
2955
+ timeoutMs,
2956
+ });
2957
+ return result?.box ?? null;
2958
+ }
2959
+
2733
2960
  /** @param {string} selector @param {string} value @param {{tabId?:unknown, frame?:string, force?:boolean, timeoutMs?:number, settle?:boolean}} [options] */
2734
2961
  async locatorFill(selector, value, { tabId, frame, force = false, timeoutMs, settle = false } = {}) {
2735
2962
  const id = await this.#resolveTab(tabId);
@@ -2832,6 +3059,7 @@ export class BridgeBrowser {
2832
3059
  const hasExplicit = tabId !== undefined && tabId !== null && tabId !== "";
2833
3060
  const numId = hasExplicit ? Number(tabId) : NaN;
2834
3061
  if (this.supportsPassiveRead && Number.isSafeInteger(numId) &&
3062
+ options?.format !== "tables" && options?.format !== "links" &&
2835
3063
  !this.attached.has(numId) && !this.ownedTabs.has(numId)) {
2836
3064
  try {
2837
3065
  const passive = await this.readTabContext(numId, {
@@ -2866,8 +3094,14 @@ export class BridgeBrowser {
2866
3094
  };
2867
3095
  }
2868
3096
  }
2869
- const text = await this.#evaluateRaw(id, "document.body ? document.body.innerText : ''");
2870
- return { tab_id: String(id), text: String(text ?? "") };
3097
+ const raw = await this.#evaluateRaw(id, "document.body ? document.body.innerText : ''");
3098
+ const text = String(raw ?? "");
3099
+ const truncated = text.length > 16_000;
3100
+ return {
3101
+ tab_id: String(id),
3102
+ text: truncated ? text.slice(0, 16_000) : text,
3103
+ ...(truncated ? { truncated: true } : {}),
3104
+ };
2871
3105
  }
2872
3106
 
2873
3107
  /** @param {string} source @param {{tabId?:unknown, arg?:unknown, hasArg?:boolean}} [options] */
@@ -3027,17 +3261,17 @@ export class BridgeBrowser {
3027
3261
  modifiers: step.modifiers,
3028
3262
  x: step.x,
3029
3263
  y: step.y,
3030
- settle: true,
3264
+ settle: step.settle ?? false,
3031
3265
  });
3032
3266
  break;
3033
3267
  case "set_value":
3034
- result = await this.setValue(step.element_index, step.value, { tabId: stepTab, settle: true });
3268
+ result = await this.setValue(step.element_index, step.value, { tabId: stepTab, settle: step.settle ?? false });
3035
3269
  break;
3036
3270
  case "type_text":
3037
- result = await this.typeText(step.text, { tabId: stepTab, elementIndex: step.element_index, settle: true });
3271
+ result = await this.typeText(step.text, { tabId: stepTab, elementIndex: step.element_index, settle: step.settle ?? false });
3038
3272
  break;
3039
3273
  case "press_key":
3040
- result = await this.pressKey(step.key, { tabId: stepTab, elementIndex: step.element_index, settle: true });
3274
+ result = await this.pressKey(step.key, { tabId: stepTab, elementIndex: step.element_index, settle: step.settle ?? false });
3041
3275
  break;
3042
3276
  case "select_option":
3043
3277
  result = await this.selectOption({
@@ -3089,7 +3323,7 @@ export class BridgeBrowser {
3089
3323
  modifiers: step.modifiers,
3090
3324
  force: step.force === true,
3091
3325
  timeoutMs: step.timeout_ms,
3092
- settle: true,
3326
+ settle: step.settle ?? false,
3093
3327
  });
3094
3328
  break;
3095
3329
  case "locator_fill":
@@ -3098,7 +3332,7 @@ export class BridgeBrowser {
3098
3332
  frame: step.frame,
3099
3333
  force: step.force === true,
3100
3334
  timeoutMs: step.timeout_ms,
3101
- settle: true,
3335
+ settle: step.settle ?? false,
3102
3336
  });
3103
3337
  break;
3104
3338
  case "set_viewport":
@@ -3260,6 +3494,7 @@ export class BridgeBrowser {
3260
3494
  }
3261
3495
  this.turnId = randomUUID();
3262
3496
  this.attached.clear();
3497
+ this.userCanceledTabs.clear();
3263
3498
  this.attaching.clear();
3264
3499
  this.axCache.clear();
3265
3500
  this.enabledDomains.clear();
@@ -3271,6 +3506,8 @@ export class BridgeBrowser {
3271
3506
  this.autoAttached.clear();
3272
3507
  this.locatorRuntimeInstalled.clear();
3273
3508
  this.statelessEvalTabs.clear();
3509
+ this.viewportSizeCache.clear();
3510
+ this.devicePixelRatioCache.clear();
3274
3511
  for (const id of [...this.ownedTabs]) {
3275
3512
  if (!handoffIds.has(id)) {
3276
3513
  this.ownedTabs.delete(id);
@@ -3363,41 +3600,64 @@ export class BridgeBrowser {
3363
3600
 
3364
3601
  // Try fast Shadow-DOM-aware hit-test first; fall back cleanly to #boxModel on minimal mocks.
3365
3602
  let point = null;
3366
- let resolvedObjectId = null;
3367
3603
  try {
3368
- const quads = await this.#cdp(tabId, "DOM.getContentQuads", { backendNodeId: node.backendDOMNodeId });
3369
- if (Array.isArray(quads?.quads) && quads.quads.length > 0) {
3370
- const resolved = await this.#cdp(tabId, "DOM.resolveNode", { backendNodeId: node.backendDOMNodeId });
3371
- resolvedObjectId = resolved?.object?.objectId ?? null;
3372
- if (resolvedObjectId) {
3373
- let hit = await this.#cdp(tabId, "Runtime.callFunctionOn", {
3374
- objectId: resolvedObjectId,
3604
+ const hitBatch = await this.#cdpBatch(tabId, [
3605
+ { method: "DOM.resolveNode", params: { backendNodeId: node.backendDOMNodeId } },
3606
+ {
3607
+ method: "Runtime.callFunctionOn",
3608
+ params: {
3609
+ objectId: "$prev.object.objectId",
3375
3610
  functionDeclaration: hitTestFunctionDeclaration(),
3376
3611
  returnByValue: true,
3377
- });
3378
- let val = hit?.result?.value;
3379
- if (val && (val.offscreen || val.hitsTarget === false)) {
3380
- await this.#scrollIntoView(tabId, node).catch(() => {});
3381
- hit = await this.#cdp(tabId, "Runtime.callFunctionOn", {
3382
- objectId: resolvedObjectId,
3383
- functionDeclaration: hitTestFunctionDeclaration(),
3384
- returnByValue: true,
3385
- });
3386
- val = hit?.result?.value;
3387
- }
3388
- if (val?.hitsTarget && val.point) {
3389
- point = val.point;
3390
- } else if (val && val.hitsTarget === false) {
3391
- throw new Error(`Accessibility element (${node.role} "${node.name}") is covered by <${val.hitTag || "unknown"}> or not hittable`);
3392
- }
3393
- }
3612
+ },
3613
+ },
3614
+ {
3615
+ method: "Runtime.releaseObject",
3616
+ params: { objectId: "$prev.object.objectId" },
3617
+ fireAndForget: true,
3618
+ batchOnly: true,
3619
+ },
3620
+ ]);
3621
+ const resolvedObjectId = hitBatch[0]?.object?.objectId ?? null;
3622
+ let hit = hitBatch[1];
3623
+ let val = hit?.result?.value;
3624
+ if (val && (val.offscreen || val.hitsTarget === false)) {
3625
+ await this.#scrollIntoView(tabId, node).catch(() => {});
3626
+ const retryBatch = await this.#cdpBatch(tabId, [
3627
+ ...(resolvedObjectId && this.supportsCdpBatch
3628
+ ? [{
3629
+ method: "Runtime.callFunctionOn",
3630
+ params: {
3631
+ objectId: resolvedObjectId,
3632
+ functionDeclaration: hitTestFunctionDeclaration(),
3633
+ returnByValue: true,
3634
+ },
3635
+ }]
3636
+ : [
3637
+ { method: "DOM.resolveNode", params: { backendNodeId: node.backendDOMNodeId } },
3638
+ {
3639
+ method: "Runtime.callFunctionOn",
3640
+ params: {
3641
+ objectId: "$prev.object.objectId",
3642
+ functionDeclaration: hitTestFunctionDeclaration(),
3643
+ returnByValue: true,
3644
+ },
3645
+ },
3646
+ ]),
3647
+ ]);
3648
+ hit = retryBatch.at(-1);
3649
+ val = hit?.result?.value;
3650
+ }
3651
+ if (!this.supportsCdpBatch && resolvedObjectId) {
3652
+ void this.#cdp(tabId, "Runtime.releaseObject", { objectId: resolvedObjectId }).catch(() => {});
3653
+ }
3654
+ if (val?.hitsTarget && val.point) {
3655
+ point = val.point;
3656
+ } else if (val && val.hitsTarget === false) {
3657
+ throw new Error(`Accessibility element (${node.role} "${node.name}") is covered by <${val.hitTag || "unknown"}> or not hittable`);
3394
3658
  }
3395
3659
  } catch (error) {
3396
3660
  if (error instanceof Error && error.message.includes("not hittable")) throw error;
3397
- } finally {
3398
- if (resolvedObjectId) {
3399
- await this.#cdp(tabId, "Runtime.releaseObject", { objectId: resolvedObjectId }).catch(() => {});
3400
- }
3401
3661
  }
3402
3662
 
3403
3663
  if (!point) {
@@ -3421,9 +3681,11 @@ export class BridgeBrowser {
3421
3681
  /** @param {number} tabId @param {number} x @param {number} y @param {{clickCount:number, button:string, modifiers?:number}} options */
3422
3682
  async #clickPoint(tabId, x, y, { clickCount, button, modifiers = 0 }) {
3423
3683
  const common = { x, y, button, clickCount, modifiers };
3424
- await this.#cdp(tabId, "Input.dispatchMouseEvent", { type: "mouseMoved", ...common, button: "none", buttons: 0, clickCount: 0 });
3425
- await this.#cdp(tabId, "Input.dispatchMouseEvent", { type: "mousePressed", ...common, buttons: buttonMask(button) });
3426
- await this.#cdp(tabId, "Input.dispatchMouseEvent", { type: "mouseReleased", ...common, buttons: 0 });
3684
+ await this.#cdpBatch(tabId, [
3685
+ { method: "Input.dispatchMouseEvent", params: { type: "mouseMoved", ...common, button: "none", buttons: 0, clickCount: 0 } },
3686
+ { method: "Input.dispatchMouseEvent", params: { type: "mousePressed", ...common, buttons: buttonMask(button) } },
3687
+ { method: "Input.dispatchMouseEvent", params: { type: "mouseReleased", ...common, buttons: 0 } },
3688
+ ]);
3427
3689
  }
3428
3690
 
3429
3691
  /**
@@ -3712,9 +3974,10 @@ export class BridgeBrowser {
3712
3974
  const state = this.tabStates.get(tabId);
3713
3975
  if (!state || !state.hasEvents || state.dialog) return;
3714
3976
 
3977
+ const settleStartMs = Date.now();
3715
3978
  const startRev = state.navRevision;
3716
3979
  if (expectNavigation && !state.loading) {
3717
- const detectDeadline = Date.now() + 30;
3980
+ const detectDeadline = Date.now() + 10;
3718
3981
  while (Date.now() < detectDeadline) {
3719
3982
  if (state.dialog || state.loading || state.navRevision !== startRev) break;
3720
3983
  await this.#waitForTabWakeup(tabId, Math.max(1, detectDeadline - Date.now()));
@@ -3722,29 +3985,36 @@ export class BridgeBrowser {
3722
3985
  }
3723
3986
 
3724
3987
  const navTriggered = state.loading || state.navRevision !== startRev;
3725
- const effectiveWaitMs = navTriggered ? timeoutMs : Math.min(timeoutMs, 150);
3988
+ const effectiveWaitMs = navTriggered ? timeoutMs : Math.min(timeoutMs, 100);
3726
3989
  const deadline = Date.now() + effectiveWaitMs;
3727
3990
  while (state.loading && !state.dialog && Date.now() < deadline) {
3728
3991
  await this.#waitForTabWakeup(tabId, Math.min(35, Math.max(1, deadline - Date.now())));
3729
3992
  }
3730
3993
 
3731
- // Wait briefly for AX updates to settle (60ms quiet window).
3732
- const quietCap = navTriggered ? 250 : 100;
3733
- const quietDeadline = Math.min(deadline, Date.now() + quietCap);
3734
- while (!state.dialog && Date.now() < quietDeadline) {
3735
- const sinceAx = Date.now() - Math.max(state.lastAxUpdateMs, 0);
3736
- if (state.lastAxUpdateMs === 0 || sinceAx >= 60) break;
3737
- await this.#waitForTabWakeup(tabId, Math.min(60 - sinceAx, Math.max(1, quietDeadline - Date.now())));
3994
+ // Only settle AX briefly (20ms quiet window) when an AX update actually fired around this action.
3995
+ if (state.lastAxUpdateMs >= settleStartMs - 15) {
3996
+ const quietCap = navTriggered ? 120 : 25;
3997
+ const quietDeadline = Math.min(deadline, Date.now() + quietCap);
3998
+ while (!state.dialog && Date.now() < quietDeadline) {
3999
+ const sinceAx = Date.now() - state.lastAxUpdateMs;
4000
+ if (sinceAx >= 20) break;
4001
+ await this.#waitForTabWakeup(tabId, Math.min(20 - sinceAx, Math.max(1, quietDeadline - Date.now())));
4002
+ }
3738
4003
  }
3739
4004
  }
3740
4005
 
3741
- /** @param {number} tabId @param {string} target @param {number} [timeoutMs] */
3742
- async #waitForCommit(tabId, target, timeoutMs = DEFAULT_LOAD_TIMEOUT_MS) {
4006
+ /** @param {number} tabId @param {string} target @param {number} [timeoutMs] @param {number} [startRev] */
4007
+ async #waitForCommit(tabId, target, timeoutMs = DEFAULT_LOAD_TIMEOUT_MS, startRev) {
3743
4008
  const deadline = Date.now() + timeoutMs;
3744
4009
  const state = this.#tabState(tabId);
3745
4010
  let lastEvalAt = state.hasEvents ? Date.now() : 0;
4011
+ const matchesTargetOrRedirect = (url) => {
4012
+ if (!url || url === "about:blank") return false;
4013
+ if (sameUrl(url, target)) return true;
4014
+ return startRev !== undefined && state.hasEvents && state.committed && state.navRevision > startRev;
4015
+ };
3746
4016
  while (Date.now() < deadline) {
3747
- if (state.committed && state.url && state.url !== "about:blank" && sameUrl(state.url, target)) return;
4017
+ if (state.committed && matchesTargetOrRedirect(state.url)) return;
3748
4018
  const now = Date.now();
3749
4019
  if (!state.hasEvents || (!state.committed && now - lastEvalAt >= 400)) {
3750
4020
  lastEvalAt = now;