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.
@@ -6,6 +6,8 @@ const CURSOR_TURN_ID = "active-turn";
6
6
  const COMPACT_EVENTS = new Set([
7
7
  "Target.attachedToTarget",
8
8
  "Target.detachedFromTarget",
9
+ "Accessibility.loadComplete",
10
+ "Accessibility.nodesUpdated",
9
11
  "Page.frameStartedLoading",
10
12
  "Page.frameStoppedLoading",
11
13
  "Page.frameNavigated",
@@ -22,6 +24,33 @@ const COMPACT_EVENTS = new Set([
22
24
  "Network.loadingFinished",
23
25
  "Network.loadingFailed",
24
26
  ]);
27
+ const FORWARDED_CDP_EVENTS = new Set(COMPACT_EVENTS);
28
+ const AX_NOTIFY_THROTTLE_MS = 20;
29
+ const utf8Encoder = typeof TextEncoder === "function" ? new TextEncoder() : null;
30
+
31
+ const NON_ASCII_RE = /[^\x00-\x7f]/;
32
+
33
+ /** @param {string} value @returns {number} */
34
+ function utf8ByteLength(value) {
35
+ if (!NON_ASCII_RE.test(value)) return value.length;
36
+ if (utf8Encoder) return utf8Encoder.encode(value).length;
37
+ let bytes = 0;
38
+ for (let i = 0; i < value.length; i++) {
39
+ const code = value.charCodeAt(i);
40
+ if (code < 0x80) bytes += 1;
41
+ else if (code < 0x800) bytes += 2;
42
+ else if (code >= 0xd800 && code <= 0xdbff) {
43
+ bytes += 4;
44
+ i += 1;
45
+ } else bytes += 3;
46
+ }
47
+ return bytes;
48
+ }
49
+
50
+ /** @param {unknown} raw @param {number} [maxLen] @returns {unknown} */
51
+ function truncateLongUrl(raw, maxLen = 4096) {
52
+ return typeof raw === "string" && raw.length > maxLen ? `${raw.slice(0, maxLen)}…` : raw;
53
+ }
25
54
  /** @type {(() => void) | null} */
26
55
  let disconnectActive = null;
27
56
  let manualDisconnect = false;
@@ -190,6 +219,8 @@ function connect() {
190
219
  const agentGroups = new Set();
191
220
  /** @type {Map<string, number>} */
192
221
  const sessionGroups = new Map();
222
+ /** @type {Map<number, number>} */
223
+ const userOriginalGroups = new Map();
193
224
  /** @type {Map<number, {url:string|null,groupId:number|null,createdAt:number}>} */
194
225
  const deliveredAgentTabs = new Map();
195
226
  /** @type {Map<number, Map<string,{parentId:string|null,targetId:string}>>} */
@@ -208,6 +239,10 @@ function connect() {
208
239
  const preparingContentScripts = new Map();
209
240
  /** @type {Set<number>} */
210
241
  const contentScriptReadyTabs = new Set();
242
+ /** @type {Set<number>} */
243
+ const syncingVisualTabs = new Set();
244
+ /** @type {Map<number, number>} */
245
+ const lastAxNotifyAt = new Map();
211
246
  /** @type {Map<number, () => void>} */
212
247
  const cursorArrivalWaiters = new Map();
213
248
  /** @type {number|null} */
@@ -217,26 +252,48 @@ function connect() {
217
252
  let allowTabFocus = false;
218
253
  let moveSeq = 0;
219
254
  let disconnected = false;
220
- /** @type {Map<number, {current:{tabId:number,wasUserTab:boolean}|null, previous:{tabId:number,wasUserTab:boolean}|null}>} */
255
+ /** @type {Map<number, {current:{tabId:number,wasUserTab:boolean}|null, previous:{tabId:number,wasUserTab:boolean}|null, recent:Array<{tabId:number,wasUserTab:boolean}>}>} */
221
256
  const windowActiveHistory = new Map();
222
257
  /** @type {Set<number>} */
258
+ const newlyCreatedPopups = new Set();
259
+ /** @type {Set<number>} */
223
260
  const restoringFocus = new Set();
261
+ /** @type {number|null} */
262
+ let lastUserWindowId = null;
224
263
 
225
264
  if (typeof chrome.tabs?.query === "function") {
226
265
  void Promise.resolve(chrome.tabs.query({active: true})).then((tabs) => {
227
266
  if (disconnected || !Array.isArray(tabs)) return;
228
267
  for (const tab of tabs) {
229
268
  if (!Number.isSafeInteger(tab?.id) || !Number.isSafeInteger(tab?.windowId)) continue;
269
+ if (!owned.has(tab.id) && lastUserWindowId === null) lastUserWindowId = tab.windowId;
230
270
  if (!windowActiveHistory.has(tab.windowId)) {
271
+ const entry = {tabId: tab.id, wasUserTab: !owned.has(tab.id)};
231
272
  windowActiveHistory.set(tab.windowId, {
232
- current: {tabId: tab.id, wasUserTab: !owned.has(tab.id)},
273
+ current: entry,
233
274
  previous: null,
275
+ recent: [entry],
234
276
  });
235
277
  }
236
278
  }
237
279
  }).catch(() => {});
238
280
  }
239
281
 
282
+ /** @param {number} windowId */
283
+ function onWindowFocusChanged(windowId) {
284
+ if (disconnected || !Number.isSafeInteger(windowId) || windowId < 0) return;
285
+ const hist = windowActiveHistory.get(windowId);
286
+ if (!hist?.current || hist.current.wasUserTab || !owned.has(hist.current.tabId)) {
287
+ lastUserWindowId = windowId;
288
+ }
289
+ }
290
+
291
+ /** @param {number} windowId */
292
+ function onWindowRemoved(windowId) {
293
+ windowActiveHistory.delete(windowId);
294
+ if (lastUserWindowId === windowId) lastUserWindowId = null;
295
+ }
296
+
240
297
  /**
241
298
  * @template T
242
299
  * @param {Promise<T>} promise
@@ -436,7 +493,11 @@ function connect() {
436
493
  };
437
494
  cursorStates.set(tabId, state);
438
495
  if (!canMessageTabs()) return;
439
- const effectiveWait = cursorMode === "smooth" && waitForArrival && visible && animate && dist >= 4;
496
+ let effectiveWait = cursorMode === "smooth" && waitForArrival && visible && animate && dist >= 4;
497
+ if (effectiveWait && typeof chrome.tabs?.get === "function") {
498
+ const tabInfo = await chrome.tabs.get(tabId).catch(() => null);
499
+ if (tabInfo && tabInfo.active === false) effectiveWait = false;
500
+ }
440
501
  if (contentScriptReadyTabs.has(tabId) && !effectiveWait) {
441
502
  try {
442
503
  const res = chrome.tabs.sendMessage(tabId, {type: "AGENT_CURSOR_STATE", state});
@@ -476,29 +537,34 @@ function connect() {
476
537
 
477
538
  /** @param {number} tabId @returns {Promise<void>} */
478
539
  async function syncTabVisuals(tabId) {
479
- if (!canMessageTabs()) return;
480
- if (activeVisualTabId !== null && activeVisualTabId !== tabId) {
481
- const prevId = activeVisualTabId;
482
- activeVisualTabId = tabId;
483
- await hideTabCursor(prevId).catch(() => {});
484
- if (badgeStates.get(prevId) === "active") {
485
- await updateTabFaviconBadge(prevId, null).catch(() => {});
486
- }
487
- } else {
488
- activeVisualTabId = tabId;
489
- }
490
- const badge = badgeStates.get(tabId) ?? (attached.has(tabId) ? "active" : null);
491
- if (badge) await updateTabFaviconBadge(tabId, badge);
492
- if (attached.has(tabId) && cursorMode !== "off") {
493
- const state = cursorStates.get(tabId);
494
- if (state?.isVisible) {
495
- if (await prepareContentScript(tabId)) {
496
- const delivered = await withTimeout(chrome.tabs.sendMessage(tabId, {type: "AGENT_CURSOR_STATE", state}), 400);
497
- if (!delivered) contentScriptReadyTabs.delete(tabId);
540
+ if (!canMessageTabs() || syncingVisualTabs.has(tabId)) return;
541
+ syncingVisualTabs.add(tabId);
542
+ try {
543
+ if (activeVisualTabId !== null && activeVisualTabId !== tabId) {
544
+ const prevId = activeVisualTabId;
545
+ activeVisualTabId = tabId;
546
+ await hideTabCursor(prevId).catch(() => {});
547
+ if (badgeStates.get(prevId) === "active") {
548
+ await updateTabFaviconBadge(prevId, null).catch(() => {});
498
549
  }
499
550
  } else {
500
- await showTabCursor(tabId);
551
+ activeVisualTabId = tabId;
552
+ }
553
+ const badge = badgeStates.get(tabId) ?? (attached.has(tabId) ? "active" : null);
554
+ if (badge) await updateTabFaviconBadge(tabId, badge);
555
+ if (attached.has(tabId) && cursorMode !== "off") {
556
+ const state = cursorStates.get(tabId);
557
+ if (state?.isVisible) {
558
+ if (await prepareContentScript(tabId)) {
559
+ const delivered = await withTimeout(chrome.tabs.sendMessage(tabId, {type: "AGENT_CURSOR_STATE", state}), 400);
560
+ if (!delivered) contentScriptReadyTabs.delete(tabId);
561
+ }
562
+ } else {
563
+ await showTabCursor(tabId);
564
+ }
501
565
  }
566
+ } finally {
567
+ syncingVisualTabs.delete(tabId);
502
568
  }
503
569
  }
504
570
 
@@ -568,14 +634,22 @@ function connect() {
568
634
  function onTabActivated(activeInfo) {
569
635
  const tabId = activeInfo?.tabId;
570
636
  if (Number.isSafeInteger(tabId) && Number.isSafeInteger(activeInfo?.windowId)) {
571
- const hist = windowActiveHistory.get(activeInfo.windowId) ?? {current: null, previous: null};
637
+ const wasUser = !owned.has(tabId);
638
+ if (wasUser) lastUserWindowId = activeInfo.windowId;
639
+ const hist = windowActiveHistory.get(activeInfo.windowId) ?? {current: null, previous: null, recent: []};
640
+ const recent = Array.isArray(hist.recent) ? hist.recent.filter((e) => e.tabId !== tabId) : [];
641
+ const entry = {tabId, wasUserTab: wasUser};
642
+ recent.push(entry);
643
+ if (recent.length > 10) recent.shift();
572
644
  if (hist.current?.tabId !== tabId) {
573
645
  windowActiveHistory.set(activeInfo.windowId, {
574
- current: {tabId, wasUserTab: !owned.has(tabId)},
646
+ current: entry,
575
647
  previous: hist.current,
648
+ recent,
576
649
  });
577
650
  } else {
578
- hist.current.wasUserTab = !owned.has(tabId);
651
+ hist.current.wasUserTab = wasUser;
652
+ hist.recent = recent;
579
653
  }
580
654
  }
581
655
  if (!Number.isSafeInteger(tabId) || attached.has(tabId)) return;
@@ -590,6 +664,7 @@ function connect() {
590
664
  owned.delete(id);
591
665
  userOwned.delete(id);
592
666
  attached.delete(id);
667
+ userOriginalGroups.delete(id);
593
668
  deliveredAgentTabs.delete(id);
594
669
  frames.delete(id);
595
670
  downloadWatchers.delete(id);
@@ -598,10 +673,15 @@ function connect() {
598
673
  faviconCache.delete(id);
599
674
  preparingContentScripts.delete(id);
600
675
  contentScriptReadyTabs.delete(id);
676
+ syncingVisualTabs.delete(id);
677
+ lastAxNotifyAt.delete(id);
678
+ newlyCreatedPopups.delete(id);
601
679
  restoringFocus.delete(id);
680
+ if (activeVisualTabId === id) activeVisualTabId = null;
602
681
  for (const hist of windowActiveHistory.values()) {
603
682
  if (hist.current?.tabId === id) hist.current = null;
604
683
  if (hist.previous?.tabId === id) hist.previous = null;
684
+ if (Array.isArray(hist.recent)) hist.recent = hist.recent.filter((e) => e.tabId !== id);
605
685
  }
606
686
  };
607
687
 
@@ -620,13 +700,34 @@ function connect() {
620
700
  const candidateUrl = tab.url || tab.pendingUrl || "";
621
701
  if (!isControllableTabUrl(candidateUrl)) return;
622
702
  owned.add(tab.id);
623
- if (tab.active === true && Number.isSafeInteger(tab.windowId) &&
624
- typeof chrome.tabs?.update === "function" && !restoringFocus.has(tab.id)) {
703
+ newlyCreatedPopups.add(tab.id);
704
+ if (tab.active === true && !allowTabFocus && Number.isSafeInteger(tab.windowId) &&
705
+ !restoringFocus.has(tab.id)) {
625
706
  const hist = windowActiveHistory.get(tab.windowId);
626
- const candidate = hist?.current?.tabId === tab.id ? hist?.previous : hist?.current;
627
- if (candidate && candidate.tabId !== tab.id && candidate.wasUserTab && !owned.has(candidate.tabId)) {
707
+ const recent = Array.isArray(hist?.recent) ? hist.recent : [];
708
+ let restoreEntry = null;
709
+ for (let i = recent.length - 1; i >= 0; i--) {
710
+ const item = recent[i];
711
+ if (!item || item.tabId === tab.id || newlyCreatedPopups.has(item.tabId)) continue;
712
+ restoreEntry = item;
713
+ break;
714
+ }
715
+ if (!restoreEntry) {
716
+ const candidate = hist?.current?.tabId === tab.id ? hist?.previous : hist?.current;
717
+ if (candidate && candidate.tabId !== tab.id && !newlyCreatedPopups.has(candidate.tabId)) {
718
+ restoreEntry = candidate;
719
+ }
720
+ }
721
+ if (restoreEntry && restoreEntry.wasUserTab && !owned.has(restoreEntry.tabId) &&
722
+ typeof chrome.tabs?.update === "function") {
723
+ restoringFocus.add(tab.id);
724
+ void Promise.resolve(chrome.tabs.update(restoreEntry.tabId, {active: true}))
725
+ .catch(() => {})
726
+ .finally(() => restoringFocus.delete(tab.id));
727
+ } else if (!restoreEntry && Number.isSafeInteger(lastUserWindowId) &&
728
+ lastUserWindowId !== tab.windowId && typeof chrome.windows?.update === "function") {
628
729
  restoringFocus.add(tab.id);
629
- void Promise.resolve(chrome.tabs.update(candidate.tabId, {active: true}))
730
+ void Promise.resolve(chrome.windows.update(lastUserWindowId, {focused: true}))
630
731
  .catch(() => {})
631
732
  .finally(() => restoringFocus.delete(tab.id));
632
733
  }
@@ -643,6 +744,8 @@ function connect() {
643
744
  chrome.tabs.onUpdated?.addListener(onTabUpdated);
644
745
  chrome.tabs.onActivated?.addListener(onTabActivated);
645
746
  chrome.tabGroups?.onRemoved?.addListener(onTabGroupRemoved);
747
+ chrome.windows?.onFocusChanged?.addListener(onWindowFocusChanged);
748
+ chrome.windows?.onRemoved?.addListener(onWindowRemoved);
646
749
  chrome.runtime.onMessage?.addListener(onRuntimeMessage);
647
750
 
648
751
  /** @param {number} gid @param {number|null} targetWindowId @returns {Promise<chrome.tabGroups.TabGroup|null>} */
@@ -662,11 +765,28 @@ function connect() {
662
765
  if (disconnected) throw new Error("Chrome bridge is disconnected");
663
766
  if (method === "createBlankTab") {
664
767
  let createOpts = {url: "about:blank", active: false};
768
+ let hasWindow = false;
665
769
  if (typeof chrome.windows?.getLastFocused === "function") {
666
770
  const win = await chrome.windows.getLastFocused({windowTypes: ["normal"]}).catch(() => null);
667
- if (Number.isSafeInteger(win?.id)) createOpts = {...createOpts, windowId: win.id};
771
+ if (Number.isSafeInteger(win?.id)) {
772
+ createOpts = {...createOpts, windowId: win.id};
773
+ hasWindow = true;
774
+ }
775
+ }
776
+ let createdRaw = null;
777
+ if (hasWindow || typeof chrome.windows?.create !== "function") {
778
+ createdRaw = await chrome.tabs.create(createOpts).catch(async (err) => {
779
+ if (/No current window/i.test(err?.message || "") && typeof chrome.windows?.create === "function") {
780
+ const win = await chrome.windows.create({url: "about:blank", focused: false, type: "normal"});
781
+ return win?.tabs?.[0] ?? null;
782
+ }
783
+ throw err;
784
+ });
785
+ } else {
786
+ const win = await chrome.windows.create({url: "about:blank", focused: false, type: "normal"});
787
+ createdRaw = win?.tabs?.[0] ?? null;
668
788
  }
669
- const tab = serializeTab(await chrome.tabs.create(createOpts));
789
+ const tab = serializeTab(createdRaw);
670
790
  if (disconnected) {
671
791
  await chrome.tabs.remove(tab.id);
672
792
  throw new Error("Chrome bridge disconnected during tab creation");
@@ -716,6 +836,9 @@ function connect() {
716
836
  if (!owned.has(tab.id)) {
717
837
  owned.add(tab.id);
718
838
  userOwned.add(tab.id);
839
+ if (Number.isSafeInteger(tab.groupId) && tab.groupId >= 0 && !agentGroups.has(tab.groupId)) {
840
+ userOriginalGroups.set(tab.id, tab.groupId);
841
+ }
719
842
  }
720
843
  return {
721
844
  ...serializeTab(tab),
@@ -781,9 +904,18 @@ function connect() {
781
904
  const sessionId = typeof details?.sessionId === "string" ? details.sessionId : null;
782
905
 
783
906
  let targetWindowId = null;
907
+ let windowTabIds = tabIds;
784
908
  if (typeof chrome.tabs?.get === "function") {
785
- const firstTab = await chrome.tabs.get(tabIds[0]).catch(() => null);
786
- if (Number.isSafeInteger(firstTab?.windowId)) targetWindowId = firstTab.windowId;
909
+ const tabObjects = await Promise.all(tabIds.map((id) => chrome.tabs.get(id).catch(() => null)));
910
+ const firstTab = tabObjects.find((t) => Number.isSafeInteger(t?.windowId)) ?? null;
911
+ if (firstTab && Number.isSafeInteger(firstTab.windowId)) {
912
+ targetWindowId = firstTab.windowId;
913
+ const sameWindow = tabIds.filter((_, idx) => {
914
+ const wid = tabObjects[idx]?.windowId;
915
+ return wid === undefined || wid === targetWindowId;
916
+ });
917
+ if (sameWindow.length > 0) windowTabIds = sameWindow;
918
+ }
787
919
  }
788
920
 
789
921
  let existingGroup = null;
@@ -811,12 +943,12 @@ function connect() {
811
943
  let groupId;
812
944
  if (targetGroupId !== null) {
813
945
  try {
814
- groupId = await chrome.tabs.group({groupId: targetGroupId, tabIds});
946
+ groupId = await chrome.tabs.group({groupId: targetGroupId, tabIds: windowTabIds});
815
947
  } catch {
816
- groupId = await chrome.tabs.group({tabIds});
948
+ groupId = await chrome.tabs.group({tabIds: windowTabIds});
817
949
  }
818
950
  } else {
819
- groupId = await chrome.tabs.group({tabIds});
951
+ groupId = await chrome.tabs.group({tabIds: windowTabIds});
820
952
  }
821
953
 
822
954
  if (Number.isSafeInteger(groupId)) {
@@ -925,28 +1057,142 @@ function connect() {
925
1057
  }
926
1058
  if (!Number.isSafeInteger(tabId) || !owned.has(tabId)) {
927
1059
  if (method === "readTab") return null;
928
- if (method === "closeTab" || method === "releaseTab" || method === "markTab" || method === "moveCursor") return null;
1060
+ if (method === "closeTab" || method === "releaseTab" || method === "markTab" ||
1061
+ method === "moveCursor" || method === "detach" || method === "unwatchDownloads") return null;
929
1062
  throw new Error("Unknown Chrome bridge request");
930
1063
  }
1064
+
1065
+ /** @param {number} targetTabId @param {{method:string,params?:object,childSession?:string}} cmdDetails @returns {Promise<unknown>} */
1066
+ async function executeSingleCdp(targetTabId, cmdDetails) {
1067
+ if (!attached.has(targetTabId)) throw new Error("Debugger unattached");
1068
+ const sessionId = cmdDetails.childSession;
1069
+ if (sessionId !== undefined && !frames.get(targetTabId)?.has(sessionId)) {
1070
+ throw new Error("Child debugger session is unavailable to this tab");
1071
+ }
1072
+ const target = sessionId === undefined ? {tabId: targetTabId} : {tabId: targetTabId, sessionId};
1073
+ const cdpMethod = cmdDetails.method;
1074
+ const cdpParams = cmdDetails.params ?? {};
1075
+
1076
+ if (canMessageTabs() && cursorMode !== "off") {
1077
+ if (cdpMethod === "Input.dispatchMouseEvent" && Number.isFinite(cdpParams?.x) && Number.isFinite(cdpParams?.y)) {
1078
+ const cx = Number(cdpParams.x);
1079
+ const cy = Number(cdpParams.y);
1080
+ if (cdpParams.type === "mouseMoved") {
1081
+ const wait = cursorMode === "smooth" && !cdpParams.buttons;
1082
+ if (wait) {
1083
+ await updateCursorPosition(targetTabId, cx, cy, {
1084
+ visible: true,
1085
+ animate: true,
1086
+ waitForArrival: true,
1087
+ });
1088
+ } else {
1089
+ void updateCursorPosition(targetTabId, cx, cy, {
1090
+ visible: true,
1091
+ animate: true,
1092
+ waitForArrival: false,
1093
+ });
1094
+ }
1095
+ } else if (cdpParams.type === "mousePressed" || cdpParams.type === "mouseWheel") {
1096
+ const prev = cursorStates.get(targetTabId)?.cursor;
1097
+ const unchanged = cdpParams.type === "mousePressed" && cursorMode === "fast" &&
1098
+ prev?.visible === true && Math.hypot(prev.x - cx, prev.y - cy) < 1;
1099
+ if (!unchanged) {
1100
+ void updateCursorPosition(targetTabId, cx, cy, {
1101
+ visible: true,
1102
+ animate: true,
1103
+ waitForArrival: false,
1104
+ });
1105
+ }
1106
+ }
1107
+ } else if (cdpMethod === "DOM.focus" && cursorMode === "smooth" &&
1108
+ (cdpParams?.objectId || Number.isSafeInteger(cdpParams?.backendNodeId))) {
1109
+ const boxReq = cdpParams.objectId
1110
+ ? {objectId: cdpParams.objectId}
1111
+ : {backendNodeId: cdpParams.backendNodeId};
1112
+ const box = await chrome.debugger.sendCommand(target, "DOM.getBoxModel", boxReq).catch(() => null);
1113
+ const quad = box?.model?.border;
1114
+ if (Array.isArray(quad) && quad.length === 8) {
1115
+ const cx = (quad[0] + quad[2]) / 2;
1116
+ const cy = (quad[1] + quad[5]) / 2;
1117
+ if (Number.isFinite(cx) && Number.isFinite(cy)) {
1118
+ await updateCursorPosition(targetTabId, cx, cy, {visible: true, animate: true, waitForArrival: true});
1119
+ }
1120
+ }
1121
+ }
1122
+ }
1123
+
1124
+ const result = await chrome.debugger.sendCommand(target, cdpMethod, cdpParams);
1125
+
1126
+ if (canMessageTabs() && cursorMode !== "off" &&
1127
+ (cdpMethod === "Runtime.evaluate" || cdpMethod === "Runtime.callFunctionOn")) {
1128
+ const val = result?.result?.value;
1129
+ if (val && typeof val === "object" && Number.isFinite(val.x) && Number.isFinite(val.y) &&
1130
+ (val.__cursorMove === true || val.hovered === true)) {
1131
+ const wait = cursorMode === "smooth";
1132
+ if (wait) {
1133
+ await updateCursorPosition(targetTabId, Number(val.x), Number(val.y), {
1134
+ visible: true,
1135
+ animate: true,
1136
+ waitForArrival: true,
1137
+ });
1138
+ } else {
1139
+ void updateCursorPosition(targetTabId, Number(val.x), Number(val.y), {
1140
+ visible: true,
1141
+ animate: true,
1142
+ waitForArrival: false,
1143
+ });
1144
+ }
1145
+ }
1146
+ }
1147
+ return result;
1148
+ }
1149
+
1150
+ /** @param {unknown} rawParams @param {string|null} lastObjectId @returns {object} */
1151
+ function resolveBatchParams(rawParams, lastObjectId) {
1152
+ if (!rawParams || typeof rawParams !== "object" || Array.isArray(rawParams)) return {};
1153
+ let cloned = null;
1154
+ for (const [k, v] of Object.entries(rawParams)) {
1155
+ if (v === "$prev.object.objectId" || v === "$prev.result.objectId") {
1156
+ if (!lastObjectId) throw new Error("CDP batch step missing previous objectId");
1157
+ if (!cloned) cloned = {...rawParams};
1158
+ cloned[k] = lastObjectId;
1159
+ }
1160
+ }
1161
+ return cloned ?? rawParams;
1162
+ }
1163
+
931
1164
  switch (method) {
932
1165
  case "readTab": return serializeTab(await chrome.tabs.get(tabId));
933
1166
  case "closeTab":
934
1167
  await chrome.tabs.remove(tabId);
935
1168
  forget(tabId);
936
1169
  return null;
937
- case "releaseTab":
1170
+ case "releaseTab": {
938
1171
  if (attached.has(tabId)) {
939
1172
  await chrome.debugger.detach({tabId}).catch(() => {});
940
1173
  attached.delete(tabId);
941
1174
  frames.delete(tabId);
942
1175
  }
943
- await hideTabCursor(tabId);
1176
+ void hideTabCursor(tabId).catch(() => {});
944
1177
  if (badgeStates.get(tabId) === "active") {
945
- await updateTabFaviconBadge(tabId, null);
1178
+ void updateTabFaviconBadge(tabId, null).catch(() => {});
946
1179
  }
1180
+ const origGroupId = userOriginalGroups.get(tabId);
1181
+ userOriginalGroups.delete(tabId);
1182
+ if (Number.isSafeInteger(origGroupId) && origGroupId >= 0 && typeof chrome.tabs?.group === "function") {
1183
+ const aliveOrig = await getAliveGroup(origGroupId, null);
1184
+ if (aliveOrig) {
1185
+ await chrome.tabs.group({groupId: origGroupId, tabIds: [tabId]}).catch(() => {});
1186
+ }
1187
+ }
1188
+ downloadWatchers.delete(tabId);
1189
+ cursorStates.delete(tabId);
1190
+ faviconCache.delete(tabId);
1191
+ newlyCreatedPopups.delete(tabId);
947
1192
  owned.delete(tabId);
948
1193
  userOwned.delete(tabId);
949
1194
  return null;
1195
+ }
950
1196
  case "markTab": {
951
1197
  const status = details?.status === "deliverable" ? "deliverable" : (details?.status === "handoff" ? "handoff" : null);
952
1198
  const tab = typeof chrome.tabs?.get === "function" ? await chrome.tabs.get(tabId).catch(() => null) : null;
@@ -959,7 +1205,7 @@ function connect() {
959
1205
  }
960
1206
  }
961
1207
  if (status) {
962
- await updateTabFaviconBadge(tabId, status);
1208
+ void updateTabFaviconBadge(tabId, status).catch(() => {});
963
1209
  if (status === "deliverable" && !userOwned.has(tabId)) {
964
1210
  const normUrl = normalizeComparableUrl(tab?.url || tab?.pendingUrl || "");
965
1211
  if (normUrl) {
@@ -998,8 +1244,12 @@ function connect() {
998
1244
  attached.add(tabId);
999
1245
  frames.set(tabId, new Map());
1000
1246
  }
1247
+ await Promise.all([
1248
+ chrome.debugger.sendCommand({tabId}, "Emulation.setFocusEmulationEnabled", {enabled: true}).catch(() => {}),
1249
+ chrome.debugger.sendCommand({tabId}, "Page.enable", {}).catch(() => {}),
1250
+ ]);
1001
1251
  badgeStates.set(tabId, "active");
1002
- await syncTabVisuals(tabId);
1252
+ void syncTabVisuals(tabId).catch(() => {});
1003
1253
  return null;
1004
1254
  case "detach":
1005
1255
  if (attached.has(tabId)) {
@@ -1007,9 +1257,9 @@ function connect() {
1007
1257
  attached.delete(tabId);
1008
1258
  frames.delete(tabId);
1009
1259
  }
1010
- await hideTabCursor(tabId);
1260
+ void hideTabCursor(tabId).catch(() => {});
1011
1261
  if (badgeStates.get(tabId) === "active") {
1012
- await updateTabFaviconBadge(tabId, null);
1262
+ void updateTabFaviconBadge(tabId, null).catch(() => {});
1013
1263
  }
1014
1264
  return null;
1015
1265
  case "navigate":
@@ -1022,86 +1272,45 @@ function connect() {
1022
1272
  case "unwatchDownloads":
1023
1273
  downloadWatchers.delete(tabId);
1024
1274
  return null;
1025
- case "execute": {
1275
+ case "execute":
1276
+ return await executeSingleCdp(tabId, details ?? {});
1277
+ case "executeBatch": {
1026
1278
  if (!attached.has(tabId)) throw new Error("Debugger unattached");
1027
- const sessionId = details.childSession;
1028
- if (sessionId !== undefined && !frames.get(tabId)?.has(sessionId)) {
1029
- throw new Error("Child debugger session is unavailable to this tab");
1279
+ const commands = Array.isArray(details?.commands) ? details.commands : null;
1280
+ if (!commands || commands.length > 32) {
1281
+ throw new Error("Chrome bridge executeBatch requires an array of at most 32 commands");
1030
1282
  }
1031
- const target = sessionId === undefined ? {tabId} : {tabId, sessionId};
1032
- const cdpMethod = details.method;
1033
- const cdpParams = details.params;
1034
-
1035
- if (canMessageTabs() && cursorMode !== "off") {
1036
- if (cdpMethod === "Input.dispatchMouseEvent" && Number.isFinite(cdpParams?.x) && Number.isFinite(cdpParams?.y)) {
1037
- if (cdpParams.type === "mouseMoved") {
1038
- const wait = cursorMode === "smooth" && !cdpParams.buttons;
1039
- if (wait) {
1040
- await updateCursorPosition(tabId, Number(cdpParams.x), Number(cdpParams.y), {
1041
- visible: true,
1042
- animate: true,
1043
- waitForArrival: true,
1044
- });
1045
- } else {
1046
- void updateCursorPosition(tabId, Number(cdpParams.x), Number(cdpParams.y), {
1047
- visible: true,
1048
- animate: true,
1049
- waitForArrival: false,
1050
- });
1051
- }
1052
- } else if (cdpParams.type === "mousePressed" || cdpParams.type === "mouseWheel") {
1053
- void updateCursorPosition(tabId, Number(cdpParams.x), Number(cdpParams.y), {
1054
- visible: true,
1055
- animate: true,
1056
- waitForArrival: false,
1057
- });
1058
- }
1059
- } else if (cdpMethod === "DOM.focus" &&
1060
- (cdpParams?.objectId || Number.isSafeInteger(cdpParams?.backendNodeId))) {
1061
- const boxReq = cdpParams.objectId
1062
- ? {objectId: cdpParams.objectId}
1063
- : {backendNodeId: cdpParams.backendNodeId};
1064
- const box = await chrome.debugger.sendCommand(target, "DOM.getBoxModel", boxReq).catch(() => null);
1065
- const quad = box?.model?.border;
1066
- if (Array.isArray(quad) && quad.length === 8) {
1067
- const cx = (quad[0] + quad[2]) / 2;
1068
- const cy = (quad[1] + quad[5]) / 2;
1069
- if (Number.isFinite(cx) && Number.isFinite(cy)) {
1070
- const wait = cursorMode === "smooth";
1071
- if (wait) {
1072
- await updateCursorPosition(tabId, cx, cy, {visible: true, animate: true, waitForArrival: true});
1073
- } else {
1074
- void updateCursorPosition(tabId, cx, cy, {visible: true, animate: true, waitForArrival: false});
1075
- }
1076
- }
1077
- }
1283
+ const results = [];
1284
+ let lastObjectId = null;
1285
+ for (const cmd of commands) {
1286
+ const resolvedParams = resolveBatchParams(cmd?.params, lastObjectId);
1287
+ if (cmd?.fireAndForget === true) {
1288
+ void executeSingleCdp(tabId, {
1289
+ method: cmd.method,
1290
+ params: resolvedParams,
1291
+ childSession: cmd.childSession,
1292
+ }).catch(() => {});
1293
+ results.push(null);
1294
+ continue;
1078
1295
  }
1079
- }
1080
-
1081
- const result = await chrome.debugger.sendCommand(target, cdpMethod, cdpParams);
1082
-
1083
- if (canMessageTabs() && cursorMode !== "off" &&
1084
- (cdpMethod === "Runtime.evaluate" || cdpMethod === "Runtime.callFunctionOn")) {
1085
- const val = result?.result?.value;
1086
- if (val && typeof val === "object" && Number.isFinite(val.x) && Number.isFinite(val.y) &&
1087
- (val.__cursorMove === true || val.hovered === true)) {
1088
- const wait = cursorMode === "smooth";
1089
- if (wait) {
1090
- await updateCursorPosition(tabId, Number(val.x), Number(val.y), {
1091
- visible: true,
1092
- animate: true,
1093
- waitForArrival: true,
1094
- });
1296
+ try {
1297
+ const res = await executeSingleCdp(tabId, {
1298
+ method: cmd?.method,
1299
+ params: resolvedParams,
1300
+ childSession: cmd?.childSession,
1301
+ });
1302
+ const nextId = res?.object?.objectId ?? res?.result?.objectId;
1303
+ if (typeof nextId === "string" && nextId) lastObjectId = nextId;
1304
+ results.push(res);
1305
+ } catch (error) {
1306
+ if (cmd?.ignoreError === true) {
1307
+ results.push({error: error instanceof Error ? error.message : String(error)});
1095
1308
  } else {
1096
- void updateCursorPosition(tabId, Number(val.x), Number(val.y), {
1097
- visible: true,
1098
- animate: true,
1099
- waitForArrival: false,
1100
- });
1309
+ throw error;
1101
1310
  }
1102
1311
  }
1103
1312
  }
1104
- return result;
1313
+ return {results};
1105
1314
  }
1106
1315
  default: throw new Error("Unknown Chrome bridge request");
1107
1316
  }
@@ -1127,10 +1336,7 @@ function connect() {
1127
1336
  } else if (method === "Target.detachedFromTarget") {
1128
1337
  if (!tree.has(params?.sessionId)) return;
1129
1338
  dropFrame(tree, params.sessionId);
1130
- } else if (!/^(?:Page|Runtime|DOM)\./u.test(method) &&
1131
- !["Accessibility.loadComplete", "Accessibility.nodesUpdated",
1132
- "Network.requestWillBeSent", "Network.responseReceived",
1133
- "Network.loadingFinished", "Network.loadingFailed"].includes(method)) {
1339
+ } else if (!FORWARDED_CDP_EVENTS.has(method)) {
1134
1340
  return;
1135
1341
  }
1136
1342
  if (sessionId === undefined && (method === "Page.frameStartedLoading" ||
@@ -1138,7 +1344,7 @@ function connect() {
1138
1344
  contentScriptReadyTabs.delete(tabId);
1139
1345
  }
1140
1346
  if (method === "Page.loadEventFired" && sessionId === undefined && attached.has(tabId)) {
1141
- void syncTabVisuals(tabId);
1347
+ void syncTabVisuals(tabId).catch(() => {});
1142
1348
  }
1143
1349
  if (method === "Page.frameDetached" && params?.reason === "swap") {
1144
1350
  // The renderer lost its local frame. A debugger session for the same
@@ -1148,15 +1354,22 @@ function connect() {
1148
1354
  }
1149
1355
  }
1150
1356
  let outgoingParams = params;
1151
- if (method === "Network.requestWillBeSent") {
1357
+ if (method === "Accessibility.loadComplete" || method === "Accessibility.nodesUpdated") {
1358
+ const now = Date.now();
1359
+ if (now - (lastAxNotifyAt.get(tabId) ?? 0) < AX_NOTIFY_THROTTLE_MS) return;
1360
+ lastAxNotifyAt.set(tabId, now);
1361
+ outgoingParams = {};
1362
+ } else if (method === "Page.frameNavigated" && typeof params?.frame?.url === "string" && params.frame.url.length > 4096) {
1363
+ outgoingParams = {...params, frame: {...params.frame, url: truncateLongUrl(params.frame.url)}};
1364
+ } else if (method === "Network.requestWillBeSent") {
1152
1365
  outgoingParams = {
1153
1366
  requestId: params?.requestId,
1154
1367
  loaderId: params?.loaderId,
1155
- documentURL: params?.documentURL,
1368
+ documentURL: truncateLongUrl(params?.documentURL),
1156
1369
  frameId: params?.frameId,
1157
1370
  type: params?.type,
1158
1371
  timestamp: params?.timestamp,
1159
- request: params?.request ? {url: params.request.url, method: params.request.method} : undefined,
1372
+ request: params?.request ? {url: truncateLongUrl(params.request.url), method: params.request.method} : undefined,
1160
1373
  };
1161
1374
  } else if (method === "Network.responseReceived") {
1162
1375
  outgoingParams = {
@@ -1166,7 +1379,7 @@ function connect() {
1166
1379
  type: params?.type,
1167
1380
  timestamp: params?.timestamp,
1168
1381
  response: params?.response ? {
1169
- url: params.response.url,
1382
+ url: truncateLongUrl(params.response.url),
1170
1383
  status: params.response.status,
1171
1384
  statusText: params.response.statusText,
1172
1385
  mimeType: params.response.mimeType,
@@ -1176,7 +1389,7 @@ function connect() {
1176
1389
  };
1177
1390
  }
1178
1391
  const event = {event: "onCDPEvent", tabId, params: {source: {tabId, sessionId}, method, params: outgoingParams}};
1179
- if (COMPACT_EVENTS.has(method) || JSON.stringify(event).length < 256 * 1024) {
1392
+ if (COMPACT_EVENTS.has(method) || utf8ByteLength(JSON.stringify(event)) < 256 * 1024) {
1180
1393
  port.postMessage(event);
1181
1394
  }
1182
1395
  }
@@ -1269,6 +1482,8 @@ function connect() {
1269
1482
  chrome.tabs.onUpdated?.removeListener(onTabUpdated);
1270
1483
  chrome.tabs.onActivated?.removeListener(onTabActivated);
1271
1484
  chrome.tabGroups?.onRemoved?.removeListener(onTabGroupRemoved);
1485
+ chrome.windows?.onFocusChanged?.removeListener(onWindowFocusChanged);
1486
+ chrome.windows?.onRemoved?.removeListener(onWindowRemoved);
1272
1487
  chrome.runtime.onMessage?.removeListener(onRuntimeMessage);
1273
1488
  chrome.debugger.onEvent.removeListener(onDebuggerEvent);
1274
1489
  chrome.debugger.onDetach.removeListener(onDebuggerDetach);
@@ -1298,7 +1513,9 @@ function connect() {
1298
1513
  preparingContentScripts.clear();
1299
1514
  contentScriptReadyTabs.clear();
1300
1515
  windowActiveHistory.clear();
1516
+ newlyCreatedPopups.clear();
1301
1517
  restoringFocus.clear();
1518
+ userOriginalGroups.clear();
1302
1519
  agentGroups.clear();
1303
1520
  sessionGroups.clear();
1304
1521
  deliveredAgentTabs.clear();
@@ -1315,6 +1532,13 @@ function connect() {
1315
1532
  reconnectTimer = null;
1316
1533
  if (!disconnectActive && !manualDisconnect) connect();
1317
1534
  }, delayMs);
1535
+ try {
1536
+ chrome.alarms?.create?.("bu_reconnect", {delayInMinutes: Math.max(0.5, delayMs / 60_000)});
1537
+ } catch {
1538
+ // Best-effort SW wakeup alarm.
1539
+ }
1540
+ } else if (!manualDisconnect && reconnectAttempts >= 5) {
1541
+ void chrome.action?.setBadgeText?.({text: "!"});
1318
1542
  }
1319
1543
  }
1320
1544
 
@@ -1331,15 +1555,33 @@ function connect() {
1331
1555
  return;
1332
1556
  }
1333
1557
  const serialized = JSON.stringify(val);
1334
- const size = 512 * 1024;
1335
- if (serialized.length <= size) port.postMessage(reply);
1336
- else if (serialized.length > size * 64) {
1558
+ const charLimit = 512 * 1024;
1559
+ const rawByteLimit = 768 * 1024;
1560
+ const totalBytes = utf8ByteLength(serialized);
1561
+ if (serialized.length <= charLimit && totalBytes <= rawByteLimit) {
1562
+ try {
1563
+ port.postMessage(reply);
1564
+ return;
1565
+ } catch {
1566
+ // Fall back to chunked delivery if Chrome rejects the payload.
1567
+ }
1568
+ }
1569
+ if (totalBytes > 16 * 1024 * 1024) {
1337
1570
  port.postMessage({id: reply.id, ok: false, error: "Chrome native response exceeds bridge limit"});
1338
- } else {
1339
- for (let offset = 0; offset < serialized.length; offset += size) {
1340
- port.postMessage({id: reply.id, index: offset / size, final: offset + size >= serialized.length,
1341
- chunk: serialized.slice(offset, offset + size)});
1571
+ return;
1572
+ }
1573
+ // Use 256K char chunks when multi-byte UTF-8 or escaping could exceed 1 MiB, else 512K chars.
1574
+ const chunkStep = totalBytes > serialized.length * 1.1 ? 200 * 1024 : charLimit;
1575
+ let index = 0;
1576
+ for (let offset = 0; offset < serialized.length; ) {
1577
+ let end = Math.min(serialized.length, offset + chunkStep);
1578
+ let piece = serialized.slice(offset, end);
1579
+ while (end > offset + 1024 && utf8ByteLength(piece) > 700 * 1024) {
1580
+ end = offset + Math.floor((end - offset) / 2);
1581
+ piece = serialized.slice(offset, end);
1342
1582
  }
1583
+ port.postMessage({id: reply.id, index: index++, final: end >= serialized.length, chunk: piece});
1584
+ offset = end;
1343
1585
  }
1344
1586
  });
1345
1587
  port.onDisconnect.addListener(onDisconnect);
@@ -1352,16 +1594,28 @@ function connect() {
1352
1594
  void cleanupStaleVisuals();
1353
1595
  }
1354
1596
 
1597
+ function persistManualDisconnect(val) {
1598
+ try {
1599
+ const res = chrome.storage?.local?.set?.({manualDisconnect: Boolean(val)});
1600
+ if (res && typeof res.catch === "function") void res.catch(() => {});
1601
+ } catch {
1602
+ // Ignore when storage API is absent.
1603
+ }
1604
+ }
1605
+
1355
1606
  chrome.action.onClicked.addListener(() => {
1356
1607
  if (disconnectActive) {
1357
1608
  manualDisconnect = true;
1609
+ persistManualDisconnect(true);
1358
1610
  if (reconnectTimer) {
1359
1611
  clearTimeout(reconnectTimer);
1360
1612
  reconnectTimer = null;
1361
1613
  }
1614
+ try { void chrome.alarms?.clear?.("bu_reconnect"); } catch { /* ignore */ }
1362
1615
  disconnectActive();
1363
1616
  } else {
1364
1617
  manualDisconnect = false;
1618
+ persistManualDisconnect(false);
1365
1619
  reconnectAttempts = 0;
1366
1620
  connect();
1367
1621
  }
@@ -1379,10 +1633,38 @@ const autoConnect = () => {
1379
1633
 
1380
1634
  const resetAndAutoConnect = () => {
1381
1635
  manualDisconnect = false;
1636
+ persistManualDisconnect(false);
1382
1637
  reconnectAttempts = 0;
1383
1638
  autoConnect();
1384
1639
  };
1385
1640
 
1641
+ chrome.alarms?.onAlarm?.addListener((alarm) => {
1642
+ if (alarm?.name === "bu_reconnect") autoConnect();
1643
+ });
1386
1644
  chrome.runtime.onInstalled?.addListener(resetAndAutoConnect);
1387
1645
  chrome.runtime.onStartup?.addListener(resetAndAutoConnect);
1388
- if (chrome.runtime?.id) autoConnect();
1646
+ if (chrome.runtime?.id) {
1647
+ if (typeof chrome.storage?.local?.get === "function") {
1648
+ let storageHandled = false;
1649
+ const applyStoredState = (data) => {
1650
+ if (storageHandled) return;
1651
+ storageHandled = true;
1652
+ if (data?.manualDisconnect === true) {
1653
+ manualDisconnect = true;
1654
+ void chrome.action?.setBadgeText?.({text: "OFF"});
1655
+ } else {
1656
+ autoConnect();
1657
+ }
1658
+ };
1659
+ try {
1660
+ const maybePromise = chrome.storage.local.get(["manualDisconnect"], applyStoredState);
1661
+ if (maybePromise && typeof maybePromise.then === "function") {
1662
+ void maybePromise.then(applyStoredState).catch(() => applyStoredState(null));
1663
+ }
1664
+ } catch {
1665
+ applyStoredState(null);
1666
+ }
1667
+ } else {
1668
+ autoConnect();
1669
+ }
1670
+ }