codex-browser-use 4.8.2 → 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.
@@ -164,6 +164,11 @@ function splitIndices(value) {
164
164
  return String(value).split(/[,;\s]+/u).map((entry) => entry.trim()).filter(Boolean);
165
165
  }
166
166
 
167
+ /** @returns {boolean} */
168
+ function allowTabFocus() {
169
+ return process.env.BROWSER_USE_ALLOW_TAB_FOCUS === "1";
170
+ }
171
+
167
172
  /** @param {unknown} ms @returns {Promise<void>} */
168
173
  function sleep(ms) {
169
174
  return new Promise((resolve) => setTimeout(resolve, ms));
@@ -185,11 +190,12 @@ function formatConsoleArgs(params) {
185
190
  */
186
191
  export class BridgeBrowser {
187
192
  /**
188
- * @param {{request:(method:string,params?:Record<string,unknown>)=>Promise<unknown>, close:()=>Promise<void>, sessionId:string, turnId:string, info?:Record<string,unknown>, frameSessions?:Map<number, Map<string,string>>}} options
193
+ * @param {{request:(method:string,params?:Record<string,unknown>)=>Promise<unknown>, close:()=>Promise<void>, isConnected?:()=>boolean, sessionId:string, turnId:string, info?:Record<string,unknown>, frameSessions?:Map<number, Map<string,string>>}} options
189
194
  */
190
- constructor({ request, close, sessionId, turnId, info = {}, frameSessions = new Map() }) {
195
+ constructor({ request, close, isConnected, sessionId, turnId, info = {}, frameSessions = new Map() }) {
191
196
  this.request = request;
192
197
  this.closeFn = close;
198
+ this.isConnectedFn = isConnected ?? null;
193
199
  this.sessionId = sessionId;
194
200
  this.turnId = turnId;
195
201
  this.info = info;
@@ -202,6 +208,8 @@ export class BridgeBrowser {
202
208
  this.activeTabId = null;
203
209
  /** @type {Set<number>} */
204
210
  this.attached = new Set();
211
+ /** @type {Set<number>} */
212
+ this.userCanceledTabs = new Set();
205
213
  /** @type {Map<number, Promise<void>>} */
206
214
  this.attaching = new Map();
207
215
  /** @type {Set<(event: Record<string, unknown>) => void>} */
@@ -218,7 +226,13 @@ export class BridgeBrowser {
218
226
  this.locatorRuntimeInstalled = new Map();
219
227
  /** @type {Set<string>} */
220
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();
221
233
  this.supportsPassiveRead = Boolean(info?.apiSupportOverrides?.["BrowserUser.getTabContext"]);
234
+ this.supportsCdpBatch = Boolean(info?.apiSupportOverrides?.["Bridge.executeCdpBatch"]);
235
+ this.supportsAttachFocusAndPage = Boolean(info?.apiSupportOverrides?.["Bridge.attachFocusAndPage"]);
222
236
  /** @type {Map<number, Map<string,{backendDOMNodeId:number|null,role:string,name:string,frameId?:string|null,sessionId?:string|null,actions?:string[],dialogControl?:string}>>} */
223
237
  this.axCache = new Map();
224
238
  /** @type {Map<number, {documentKey:string, entries:Array<any>}>} */
@@ -229,6 +243,11 @@ export class BridgeBrowser {
229
243
  this.closed = false;
230
244
  }
231
245
 
246
+ /** @returns {boolean} */
247
+ isClosed() {
248
+ return this.closed || (typeof this.isConnectedFn === "function" && !this.isConnectedFn());
249
+ }
250
+
232
251
  /**
233
252
  * @param {{bridgeFile:string, sessionId?:string, turnId?:string, requestTimeoutMs?:number}} options
234
253
  * @returns {Promise<BridgeBrowser>}
@@ -247,16 +266,31 @@ export class BridgeBrowser {
247
266
  browserRef?.#clearTabCaches(tabId);
248
267
  browserRef?.attached.delete(tabId);
249
268
  browserRef?.autoAttached.delete(tabId);
269
+ if (params?.reason === "canceled_by_user") {
270
+ browserRef?.userCanceledTabs.add(tabId);
271
+ }
250
272
  } else if (method === "onTabCreated") {
251
273
  browserRef?.handleTabCreated(params);
252
274
  }
253
275
  });
254
276
  const info = await request("getInfo", { session_id: sessionId, turn_id: turnId });
255
277
  const envCursorMode = process.env.BROWSER_USE_CURSOR_MODE;
256
- if (envCursorMode === "fast" || envCursorMode === "smooth" || envCursorMode === "off") {
257
- await request("setConfig", { session_id: sessionId, turn_id: turnId, cursorMode: envCursorMode }).catch(() => {});
258
- }
259
- browserRef = new BridgeBrowser({ request, close: () => client.close(), sessionId, turnId, info: info ?? {}, frameSessions });
278
+ const configPatch = {
279
+ ...(envCursorMode === "fast" || envCursorMode === "smooth" || envCursorMode === "off"
280
+ ? { cursorMode: envCursorMode }
281
+ : {}),
282
+ allowTabFocus: allowTabFocus(),
283
+ };
284
+ await request("setConfig", { session_id: sessionId, turn_id: turnId, ...configPatch }).catch(() => {});
285
+ browserRef = new BridgeBrowser({
286
+ request,
287
+ close: () => client.close(),
288
+ isConnected: () => !client.closed && Boolean(client.socket && !client.socket.destroyed),
289
+ sessionId,
290
+ turnId,
291
+ info: info ?? {},
292
+ frameSessions,
293
+ });
260
294
  return browserRef;
261
295
  }
262
296
 
@@ -692,6 +726,9 @@ export class BridgeBrowser {
692
726
  } catch (error) {
693
727
  const msg = error instanceof Error ? error.message : String(error);
694
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
+ }
695
732
  this.attached.delete(tabId);
696
733
  this.#clearTabCaches(tabId);
697
734
  this.autoAttached.delete(tabId);
@@ -716,6 +753,60 @@ export class BridgeBrowser {
716
753
  return sessionId ? this.#cdpIn(tabId, sessionId, method, params) : this.#cdp(tabId, method, params);
717
754
  }
718
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
+
719
810
  /** @param {number} tabId @param {string|null} [sessionId] @returns {void} */
720
811
  #clearLocatorRuntime(tabId, sessionId = null) {
721
812
  if (sessionId !== null) {
@@ -733,7 +824,8 @@ export class BridgeBrowser {
733
824
  this.enabledDomains.delete(tabId);
734
825
  this.enablingDomains.delete(tabId);
735
826
  this.frameRouteCache.delete(tabId);
736
- this.#clearLocatorRuntime(tabId);
827
+ this.viewportSizeCache.delete(tabId);
828
+ this.devicePixelRatioCache.delete(tabId);
737
829
  this.#clearLocatorRuntime(tabId);
738
830
  const frameMap = this.frameSessions.get(tabId);
739
831
  if (frameMap) {
@@ -806,6 +898,10 @@ export class BridgeBrowser {
806
898
  this.#assertOpen();
807
899
  const id = Number(tabId);
808
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;
809
905
  let tab;
810
906
  try {
811
907
  tab = await this.#rpc("claimUserTab", { tabId: id });
@@ -816,7 +912,18 @@ export class BridgeBrowser {
816
912
  this.ownedTabs.add(tab.id);
817
913
  this.tabs.set(tab.id, { ...tab, owned: true, origin: tab.origin || "user" });
818
914
  this.activeTabId = tab.id;
819
- 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
+ }
820
927
  return {
821
928
  tab_id: String(tab.id),
822
929
  title: tab.title || "Untitled",
@@ -906,6 +1013,9 @@ export class BridgeBrowser {
906
1013
  /** @param {number} tabId @returns {Promise<void>} */
907
1014
  async attach(tabId) {
908
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
+ }
909
1019
  const inflight = this.attaching.get(tabId);
910
1020
  if (inflight) {
911
1021
  await inflight;
@@ -916,6 +1026,9 @@ export class BridgeBrowser {
916
1026
  await this.#rpc("attach", { tabId });
917
1027
  } catch (error) {
918
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
+ }
919
1032
  if (/Browser tab is unavailable to this session/i.test(msg)) {
920
1033
  this.ownedTabs.delete(tabId);
921
1034
  this.tabs.delete(tabId);
@@ -932,7 +1045,16 @@ export class BridgeBrowser {
932
1045
  this.frameRouteCache.delete(tabId);
933
1046
  this.#clearLocatorRuntime(tabId);
934
1047
  this.#tabState(tabId);
935
- 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
+ }
936
1058
  })().finally(() => {
937
1059
  this.attaching.delete(tabId);
938
1060
  });
@@ -1026,6 +1148,7 @@ export class BridgeBrowser {
1026
1148
  async selectTab(tabId) {
1027
1149
  const id = Number(tabId);
1028
1150
  if (!Number.isSafeInteger(id)) throw new Error("A numeric tab_id is required");
1151
+ this.userCanceledTabs.delete(id);
1029
1152
  const resolved = await this.#resolveTab(id);
1030
1153
  this.activeTabId = resolved;
1031
1154
  await this.attach(resolved);
@@ -1061,6 +1184,7 @@ export class BridgeBrowser {
1061
1184
  this.lastAxSnapshots.delete(id);
1062
1185
  this.frameRouteCache.delete(id);
1063
1186
  const state = this.#tabState(id);
1187
+ const startRev = state.navRevision;
1064
1188
  state.committed = false;
1065
1189
  state.ready = false;
1066
1190
  state.domContentLoaded = false;
@@ -1070,14 +1194,14 @@ export class BridgeBrowser {
1070
1194
  let committed = false;
1071
1195
  try {
1072
1196
  await this.#rpc("navigateTab", { tabId: id, url: target });
1073
- await this.#waitForCommit(id, target, Math.min(5_000, timeoutMs));
1197
+ await this.#waitForCommit(id, target, Math.min(5_000, timeoutMs), startRev);
1074
1198
  committed = true;
1075
1199
  } catch {
1076
1200
  // Fall back to CDP navigation when the tab-level navigation does not commit.
1077
1201
  }
1078
1202
  if (!committed) {
1079
1203
  await this.#navigateWithCdp(id, target);
1080
- await this.#waitForCommit(id, target, timeoutMs);
1204
+ await this.#waitForCommit(id, target, timeoutMs, startRev);
1081
1205
  }
1082
1206
  if (waitUntil !== "commit") {
1083
1207
  await this.#waitForLoad(id, { waitUntil, timeoutMs });
@@ -1187,16 +1311,23 @@ export class BridgeBrowser {
1187
1311
 
1188
1312
  let cssScale = 1;
1189
1313
  let metrics = null;
1314
+ const cachedDpr = this.devicePixelRatioCache.get(id);
1190
1315
  if (scale === "css" && !clip) {
1191
1316
  const [dpr, layout] = await Promise.all([
1192
- this.#evaluateRaw(id, "window.devicePixelRatio").catch(() => 1),
1317
+ cachedDpr !== undefined ? cachedDpr : this.#evaluateRaw(id, "window.devicePixelRatio").catch(() => 1),
1193
1318
  this.#cdp(id, "Page.getLayoutMetrics").catch(() => null),
1194
1319
  ]);
1195
- 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
+ }
1196
1324
  metrics = layout;
1197
1325
  } else if (scale === "css") {
1198
- const dpr = await this.#evaluateRaw(id, "window.devicePixelRatio").catch(() => 1);
1199
- 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
+ }
1200
1331
  }
1201
1332
 
1202
1333
  if (clip && Number.isFinite(clip.width) && Number.isFinite(clip.height)) {
@@ -1279,19 +1410,68 @@ export class BridgeBrowser {
1279
1410
  this.#ensureDomain(id, "Accessibility", "Accessibility.enable"),
1280
1411
  ]);
1281
1412
 
1282
- // Capture main frame AX tree, frame tree, location, and optional screenshot in parallel.
1283
- 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([
1284
1451
  this.#cdp(id, "Accessibility.getFullAXTree"),
1285
1452
  this.#cdp(id, "Page.getFrameTree").catch(() => null),
1286
- this.#evaluateRaw(id, "({title: document.title, url: location.href})").catch(() => ({
1287
- title: this.tabs.get(id)?.title ?? "",
1288
- url: this.tabs.get(id)?.url ?? "",
1289
- })),
1290
1453
  screenshot ? this.screenshot(id, { fullPage, format, quality }).catch(() => null) : null,
1291
1454
  ]);
1292
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
+
1293
1473
  const frameTrees = [{
1294
- nodes: mainTree?.nodes ?? [],
1474
+ nodes: mainNodes,
1295
1475
  frameId: null,
1296
1476
  sessionId: null,
1297
1477
  depth: 0,
@@ -1307,10 +1487,8 @@ export class BridgeBrowser {
1307
1487
  const url = String(location?.url || "");
1308
1488
  const documentKey = `${tabState.loaderId ?? ""}:${url}`;
1309
1489
 
1310
- const useDiff = diff && !full;
1311
- const prev = this.lastAxSnapshots.get(id);
1312
1490
  let diffResult = useDiff
1313
- ? buildAxDiff(prev, { documentKey, lines: merged.lines, entries: merged.entries })
1491
+ ? buildAxDiff(prev, { documentKey, lines: merged.lines, entries: merged.entries, mode })
1314
1492
  : { mode: "full", lines: merged.lines };
1315
1493
  if (useDiff && prev?.hasIndexedBaseline === false && diffResult.mode === "unchanged") {
1316
1494
  diffResult = allowUnindexedBaseline
@@ -1318,7 +1496,18 @@ export class BridgeBrowser {
1318
1496
  : { mode: "full", lines: merged.lines };
1319
1497
  }
1320
1498
 
1321
- 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
+ });
1322
1511
 
1323
1512
  const image = cap?.data ?? null;
1324
1513
  const screenshotMimeType = cap?.mimeType ?? null;
@@ -1433,14 +1622,32 @@ export class BridgeBrowser {
1433
1622
  return { tab_id: String(id), ok: true, action: "set_value", index: String(elementIndex) };
1434
1623
  }
1435
1624
  const sessionId = node.sessionId ?? null;
1436
- const { object } = await this.#cdpTarget(id, sessionId, "DOM.resolveNode", { backendNodeId: node.backendDOMNodeId });
1437
- if (!object?.objectId) throw new Error("Browser element could not be resolved");
1438
- const response = await this.#cdpTarget(id, sessionId, "Runtime.callFunctionOn", {
1439
- objectId: object.objectId,
1440
- functionDeclaration: smartSetValueFunctionDeclaration(),
1441
- arguments: [{ value: String(value) }],
1442
- 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;
1443
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];
1444
1651
  if (response?.exceptionDetails) {
1445
1652
  throw new Error(response.exceptionDetails.exception?.description || response.exceptionDetails.text || "Failed to set element value");
1446
1653
  }
@@ -1491,25 +1698,24 @@ export class BridgeBrowser {
1491
1698
  location: 0,
1492
1699
  };
1493
1700
  if (key.key === "Enter" && key.modifiers === 0) {
1494
- await this.#cdpTarget(tabId, sessionId, "Input.dispatchKeyEvent", {
1495
- type: "rawKeyDown",
1496
- ...base,
1497
- commands: ["insertNewline"],
1498
- });
1499
- await this.#cdpTarget(tabId, sessionId, "Input.dispatchKeyEvent", {
1500
- type: "char",
1501
- ...base,
1502
- text: key.text,
1503
- unmodifiedText: key.text,
1504
- });
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);
1505
1706
  } else {
1506
- await this.#cdpTarget(tabId, sessionId, "Input.dispatchKeyEvent", {
1507
- type: key.text ? "keyDown" : "rawKeyDown",
1508
- ...base,
1509
- ...(key.text ? { text: key.text, unmodifiedText: key.text } : {}),
1510
- });
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);
1511
1718
  }
1512
- await this.#cdpTarget(tabId, sessionId, "Input.dispatchKeyEvent", { type: "keyUp", ...base });
1513
1719
  return key;
1514
1720
  }
1515
1721
 
@@ -1533,8 +1739,13 @@ export class BridgeBrowser {
1533
1739
  const box = await this.#boxModel(id, node, node.sessionId);
1534
1740
  point = { x: box.x, y: box.y };
1535
1741
  } else {
1536
- const metrics = await this.#cdp(id, "Page.getLayoutMetrics");
1537
- 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
+ }
1538
1749
  point = { x: Math.floor(viewport.clientWidth / 2), y: Math.floor(viewport.clientHeight / 2) };
1539
1750
  }
1540
1751
  await this.#cdp(id, "Input.dispatchMouseEvent", { type: "mouseWheel", x: point.x, y: point.y, ...deltas });
@@ -1596,22 +1807,28 @@ export class BridgeBrowser {
1596
1807
  if (!Number.isFinite(start.x) || !Number.isFinite(start.y) || !Number.isFinite(end.x) || !Number.isFinite(end.y)) {
1597
1808
  throw new Error("drag requires valid start and end coordinates or element indices");
1598
1809
  }
1599
- const count = Math.max(2, Math.min(30, Number(steps) || 8));
1600
- await this.#cdp(id, "Input.dispatchMouseEvent", { type: "mouseMoved", x: start.x, y: start.y, button: "none", buttons: 0, clickCount: 0, modifiers: 0 });
1601
- 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
+ ];
1602
1815
  for (let i = 1; i <= count; i++) {
1603
1816
  const ratio = i / count;
1604
- await this.#cdp(id, "Input.dispatchMouseEvent", {
1605
- type: "mouseMoved",
1606
- x: start.x + (end.x - start.x) * ratio,
1607
- y: start.y + (end.y - start.y) * ratio,
1608
- button: "left",
1609
- buttons: 1,
1610
- clickCount: 0,
1611
- 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
+ },
1612
1828
  });
1613
1829
  }
1614
- 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);
1615
1832
  return { tab_id: String(id), ok: true, action: "drag", from: start, to: end };
1616
1833
  }
1617
1834
 
@@ -1709,7 +1926,7 @@ export class BridgeBrowser {
1709
1926
  throw err;
1710
1927
  }
1711
1928
  } finally {
1712
- await this.#cdpTarget(id, sessionId, "Runtime.releaseObject", { objectId }).catch(() => {});
1929
+ void this.#cdpTarget(id, sessionId, "Runtime.releaseObject", { objectId }).catch(() => {});
1713
1930
  }
1714
1931
  if (shouldRetry) {
1715
1932
  await sleep(Math.min(50, Math.max(1, deadline - Date.now())));
@@ -2117,6 +2334,8 @@ export class BridgeBrowser {
2117
2334
  mobile: mob,
2118
2335
  });
2119
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);
2120
2339
  return { tab_id: String(id), ok: true, width: w, height: h, deviceScaleFactor: dsf, mobile: mob };
2121
2340
  }
2122
2341
 
@@ -2129,6 +2348,8 @@ export class BridgeBrowser {
2129
2348
  await this.attach(id);
2130
2349
  await this.#cdp(id, "Emulation.clearDeviceMetricsOverride", {});
2131
2350
  this.#tabState(id).viewportOverride = null;
2351
+ this.viewportSizeCache.delete(id);
2352
+ this.devicePixelRatioCache.delete(id);
2132
2353
  return { tab_id: String(id), ok: true, reset: true };
2133
2354
  }
2134
2355
 
@@ -2484,7 +2705,7 @@ export class BridgeBrowser {
2484
2705
  const documentKey = `${tabState.loaderId ?? ""}:${url}`;
2485
2706
  const baseline = mergeFrameAxStates(frameTrees, { maxLines, mode });
2486
2707
  this.axCache.set(id, baseline.index);
2487
- this.lastAxSnapshots.set(id, { documentKey, entries: baseline.entries, hasIndexedBaseline: false });
2708
+ this.lastAxSnapshots.set(id, { documentKey, entries: baseline.entries, hasIndexedBaseline: false, mode, maxLines });
2488
2709
  return { tab_id: String(id), ...snapshot };
2489
2710
  }
2490
2711
 
@@ -2504,7 +2725,11 @@ export class BridgeBrowser {
2504
2725
  if (!Number.isSafeInteger(backendNodeId)) {
2505
2726
  throw new Error(`Locator did not resolve to a DOM node: ${selector}`);
2506
2727
  }
2507
- 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
+ }
2508
2733
  const tree = await this.#cdpTarget(id, sessionId, "Accessibility.getFullAXTree", {});
2509
2734
  let snapshot = formatAriaSnapshot(tree?.nodes ?? [], {
2510
2735
  maxLines,
@@ -2707,6 +2932,31 @@ export class BridgeBrowser {
2707
2932
  };
2708
2933
  }
2709
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
+
2710
2960
  /** @param {string} selector @param {string} value @param {{tabId?:unknown, frame?:string, force?:boolean, timeoutMs?:number, settle?:boolean}} [options] */
2711
2961
  async locatorFill(selector, value, { tabId, frame, force = false, timeoutMs, settle = false } = {}) {
2712
2962
  const id = await this.#resolveTab(tabId);
@@ -2809,6 +3059,7 @@ export class BridgeBrowser {
2809
3059
  const hasExplicit = tabId !== undefined && tabId !== null && tabId !== "";
2810
3060
  const numId = hasExplicit ? Number(tabId) : NaN;
2811
3061
  if (this.supportsPassiveRead && Number.isSafeInteger(numId) &&
3062
+ options?.format !== "tables" && options?.format !== "links" &&
2812
3063
  !this.attached.has(numId) && !this.ownedTabs.has(numId)) {
2813
3064
  try {
2814
3065
  const passive = await this.readTabContext(numId, {
@@ -2843,8 +3094,14 @@ export class BridgeBrowser {
2843
3094
  };
2844
3095
  }
2845
3096
  }
2846
- const text = await this.#evaluateRaw(id, "document.body ? document.body.innerText : ''");
2847
- 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
+ };
2848
3105
  }
2849
3106
 
2850
3107
  /** @param {string} source @param {{tabId?:unknown, arg?:unknown, hasArg?:boolean}} [options] */
@@ -3004,17 +3261,17 @@ export class BridgeBrowser {
3004
3261
  modifiers: step.modifiers,
3005
3262
  x: step.x,
3006
3263
  y: step.y,
3007
- settle: true,
3264
+ settle: step.settle ?? false,
3008
3265
  });
3009
3266
  break;
3010
3267
  case "set_value":
3011
- 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 });
3012
3269
  break;
3013
3270
  case "type_text":
3014
- 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 });
3015
3272
  break;
3016
3273
  case "press_key":
3017
- 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 });
3018
3275
  break;
3019
3276
  case "select_option":
3020
3277
  result = await this.selectOption({
@@ -3066,7 +3323,7 @@ export class BridgeBrowser {
3066
3323
  modifiers: step.modifiers,
3067
3324
  force: step.force === true,
3068
3325
  timeoutMs: step.timeout_ms,
3069
- settle: true,
3326
+ settle: step.settle ?? false,
3070
3327
  });
3071
3328
  break;
3072
3329
  case "locator_fill":
@@ -3075,7 +3332,7 @@ export class BridgeBrowser {
3075
3332
  frame: step.frame,
3076
3333
  force: step.force === true,
3077
3334
  timeoutMs: step.timeout_ms,
3078
- settle: true,
3335
+ settle: step.settle ?? false,
3079
3336
  });
3080
3337
  break;
3081
3338
  case "set_viewport":
@@ -3194,17 +3451,19 @@ export class BridgeBrowser {
3194
3451
 
3195
3452
  /** @param {Array<{tab_id:unknown, mode?:string, focus?:boolean}>} [entries] */
3196
3453
  async markTabs(entries = []) {
3454
+ const canFocus = allowTabFocus();
3197
3455
  const marked = [];
3198
3456
  for (const entry of entries) {
3199
3457
  const id = await this.#resolveTab(entry?.tab_id);
3200
3458
  const mode = entry?.mode === "deliverable" ? "deliverable" : "handoff";
3201
- if (mode === "deliverable" && entry?.focus === true && this.attached.has(id)) {
3459
+ const focusTab = canFocus && entry?.focus === true;
3460
+ if (mode === "deliverable" && focusTab && this.attached.has(id)) {
3202
3461
  await this.#cdp(id, "Page.bringToFront").catch(() => {});
3203
3462
  }
3204
3463
  await this.#rpc("markTab", {
3205
3464
  tabId: id,
3206
3465
  status: mode,
3207
- ...(entry?.focus === true ? { focus: true } : {}),
3466
+ ...(focusTab ? { focus: true } : {}),
3208
3467
  });
3209
3468
  marked.push({ tab_id: String(id), mode });
3210
3469
  }
@@ -3213,18 +3472,20 @@ export class BridgeBrowser {
3213
3472
 
3214
3473
  /** @param {{keep?:Array<{tab_id:unknown, mode?:string, focus?:boolean}>, ungroup?:boolean}} [options] */
3215
3474
  async endTurn({ keep = [], ungroup = false } = {}) {
3475
+ const canFocus = allowTabFocus();
3216
3476
  const handoffIds = new Set();
3217
3477
  for (const entry of keep) {
3218
3478
  const id = await this.#resolveTab(entry?.tab_id);
3219
3479
  const mode = entry?.mode === "deliverable" ? "deliverable" : "handoff";
3480
+ const focusTab = canFocus && entry?.focus === true;
3220
3481
  if (mode === "handoff") handoffIds.add(id);
3221
- if (mode === "deliverable" && entry?.focus === true && this.attached.has(id)) {
3482
+ if (mode === "deliverable" && focusTab && this.attached.has(id)) {
3222
3483
  await this.#cdp(id, "Page.bringToFront").catch(() => {});
3223
3484
  }
3224
3485
  await this.#rpc("markTab", {
3225
3486
  tabId: id,
3226
3487
  status: mode,
3227
- ...(entry?.focus === true ? { focus: true } : {}),
3488
+ ...(focusTab ? { focus: true } : {}),
3228
3489
  });
3229
3490
  }
3230
3491
  await this.#rpc("turnEnded", { ...(ungroup === true ? { ungroup: true } : {}) });
@@ -3233,6 +3494,7 @@ export class BridgeBrowser {
3233
3494
  }
3234
3495
  this.turnId = randomUUID();
3235
3496
  this.attached.clear();
3497
+ this.userCanceledTabs.clear();
3236
3498
  this.attaching.clear();
3237
3499
  this.axCache.clear();
3238
3500
  this.enabledDomains.clear();
@@ -3244,6 +3506,8 @@ export class BridgeBrowser {
3244
3506
  this.autoAttached.clear();
3245
3507
  this.locatorRuntimeInstalled.clear();
3246
3508
  this.statelessEvalTabs.clear();
3509
+ this.viewportSizeCache.clear();
3510
+ this.devicePixelRatioCache.clear();
3247
3511
  for (const id of [...this.ownedTabs]) {
3248
3512
  if (!handoffIds.has(id)) {
3249
3513
  this.ownedTabs.delete(id);
@@ -3336,41 +3600,64 @@ export class BridgeBrowser {
3336
3600
 
3337
3601
  // Try fast Shadow-DOM-aware hit-test first; fall back cleanly to #boxModel on minimal mocks.
3338
3602
  let point = null;
3339
- let resolvedObjectId = null;
3340
3603
  try {
3341
- const quads = await this.#cdp(tabId, "DOM.getContentQuads", { backendNodeId: node.backendDOMNodeId });
3342
- if (Array.isArray(quads?.quads) && quads.quads.length > 0) {
3343
- const resolved = await this.#cdp(tabId, "DOM.resolveNode", { backendNodeId: node.backendDOMNodeId });
3344
- resolvedObjectId = resolved?.object?.objectId ?? null;
3345
- if (resolvedObjectId) {
3346
- let hit = await this.#cdp(tabId, "Runtime.callFunctionOn", {
3347
- 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",
3348
3610
  functionDeclaration: hitTestFunctionDeclaration(),
3349
3611
  returnByValue: true,
3350
- });
3351
- let val = hit?.result?.value;
3352
- if (val && (val.offscreen || val.hitsTarget === false)) {
3353
- await this.#scrollIntoView(tabId, node).catch(() => {});
3354
- hit = await this.#cdp(tabId, "Runtime.callFunctionOn", {
3355
- objectId: resolvedObjectId,
3356
- functionDeclaration: hitTestFunctionDeclaration(),
3357
- returnByValue: true,
3358
- });
3359
- val = hit?.result?.value;
3360
- }
3361
- if (val?.hitsTarget && val.point) {
3362
- point = val.point;
3363
- } else if (val && val.hitsTarget === false) {
3364
- throw new Error(`Accessibility element (${node.role} "${node.name}") is covered by <${val.hitTag || "unknown"}> or not hittable`);
3365
- }
3366
- }
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`);
3367
3658
  }
3368
3659
  } catch (error) {
3369
3660
  if (error instanceof Error && error.message.includes("not hittable")) throw error;
3370
- } finally {
3371
- if (resolvedObjectId) {
3372
- await this.#cdp(tabId, "Runtime.releaseObject", { objectId: resolvedObjectId }).catch(() => {});
3373
- }
3374
3661
  }
3375
3662
 
3376
3663
  if (!point) {
@@ -3394,9 +3681,11 @@ export class BridgeBrowser {
3394
3681
  /** @param {number} tabId @param {number} x @param {number} y @param {{clickCount:number, button:string, modifiers?:number}} options */
3395
3682
  async #clickPoint(tabId, x, y, { clickCount, button, modifiers = 0 }) {
3396
3683
  const common = { x, y, button, clickCount, modifiers };
3397
- await this.#cdp(tabId, "Input.dispatchMouseEvent", { type: "mouseMoved", ...common, button: "none", buttons: 0, clickCount: 0 });
3398
- await this.#cdp(tabId, "Input.dispatchMouseEvent", { type: "mousePressed", ...common, buttons: buttonMask(button) });
3399
- 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
+ ]);
3400
3689
  }
3401
3690
 
3402
3691
  /**
@@ -3685,9 +3974,10 @@ export class BridgeBrowser {
3685
3974
  const state = this.tabStates.get(tabId);
3686
3975
  if (!state || !state.hasEvents || state.dialog) return;
3687
3976
 
3977
+ const settleStartMs = Date.now();
3688
3978
  const startRev = state.navRevision;
3689
3979
  if (expectNavigation && !state.loading) {
3690
- const detectDeadline = Date.now() + 30;
3980
+ const detectDeadline = Date.now() + 10;
3691
3981
  while (Date.now() < detectDeadline) {
3692
3982
  if (state.dialog || state.loading || state.navRevision !== startRev) break;
3693
3983
  await this.#waitForTabWakeup(tabId, Math.max(1, detectDeadline - Date.now()));
@@ -3695,29 +3985,36 @@ export class BridgeBrowser {
3695
3985
  }
3696
3986
 
3697
3987
  const navTriggered = state.loading || state.navRevision !== startRev;
3698
- const effectiveWaitMs = navTriggered ? timeoutMs : Math.min(timeoutMs, 150);
3988
+ const effectiveWaitMs = navTriggered ? timeoutMs : Math.min(timeoutMs, 100);
3699
3989
  const deadline = Date.now() + effectiveWaitMs;
3700
3990
  while (state.loading && !state.dialog && Date.now() < deadline) {
3701
3991
  await this.#waitForTabWakeup(tabId, Math.min(35, Math.max(1, deadline - Date.now())));
3702
3992
  }
3703
3993
 
3704
- // Wait briefly for AX updates to settle (60ms quiet window).
3705
- const quietCap = navTriggered ? 250 : 100;
3706
- const quietDeadline = Math.min(deadline, Date.now() + quietCap);
3707
- while (!state.dialog && Date.now() < quietDeadline) {
3708
- const sinceAx = Date.now() - Math.max(state.lastAxUpdateMs, 0);
3709
- if (state.lastAxUpdateMs === 0 || sinceAx >= 60) break;
3710
- 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
+ }
3711
4003
  }
3712
4004
  }
3713
4005
 
3714
- /** @param {number} tabId @param {string} target @param {number} [timeoutMs] */
3715
- 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) {
3716
4008
  const deadline = Date.now() + timeoutMs;
3717
4009
  const state = this.#tabState(tabId);
3718
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
+ };
3719
4016
  while (Date.now() < deadline) {
3720
- if (state.committed && state.url && state.url !== "about:blank" && sameUrl(state.url, target)) return;
4017
+ if (state.committed && matchesTargetOrRedirect(state.url)) return;
3721
4018
  const now = Date.now();
3722
4019
  if (!state.hasEvents || (!state.committed && now - lastEvalAt >= 400)) {
3723
4020
  lastEvalAt = now;