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.
@@ -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,34 +239,61 @@ 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} */
214
249
  let activeVisualTabId = null;
215
250
  /** @type {"fast"|"smooth"|"off"} */
216
251
  let cursorMode = "fast";
252
+ let allowTabFocus = false;
217
253
  let moveSeq = 0;
218
254
  let disconnected = false;
219
- /** @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}>}>} */
220
256
  const windowActiveHistory = new Map();
221
257
  /** @type {Set<number>} */
258
+ const newlyCreatedPopups = new Set();
259
+ /** @type {Set<number>} */
222
260
  const restoringFocus = new Set();
261
+ /** @type {number|null} */
262
+ let lastUserWindowId = null;
223
263
 
224
264
  if (typeof chrome.tabs?.query === "function") {
225
265
  void Promise.resolve(chrome.tabs.query({active: true})).then((tabs) => {
226
266
  if (disconnected || !Array.isArray(tabs)) return;
227
267
  for (const tab of tabs) {
228
268
  if (!Number.isSafeInteger(tab?.id) || !Number.isSafeInteger(tab?.windowId)) continue;
269
+ if (!owned.has(tab.id) && lastUserWindowId === null) lastUserWindowId = tab.windowId;
229
270
  if (!windowActiveHistory.has(tab.windowId)) {
271
+ const entry = {tabId: tab.id, wasUserTab: !owned.has(tab.id)};
230
272
  windowActiveHistory.set(tab.windowId, {
231
- current: {tabId: tab.id, wasUserTab: !owned.has(tab.id)},
273
+ current: entry,
232
274
  previous: null,
275
+ recent: [entry],
233
276
  });
234
277
  }
235
278
  }
236
279
  }).catch(() => {});
237
280
  }
238
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
+
239
297
  /**
240
298
  * @template T
241
299
  * @param {Promise<T>} promise
@@ -435,7 +493,11 @@ function connect() {
435
493
  };
436
494
  cursorStates.set(tabId, state);
437
495
  if (!canMessageTabs()) return;
438
- 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
+ }
439
501
  if (contentScriptReadyTabs.has(tabId) && !effectiveWait) {
440
502
  try {
441
503
  const res = chrome.tabs.sendMessage(tabId, {type: "AGENT_CURSOR_STATE", state});
@@ -475,29 +537,34 @@ function connect() {
475
537
 
476
538
  /** @param {number} tabId @returns {Promise<void>} */
477
539
  async function syncTabVisuals(tabId) {
478
- if (!canMessageTabs()) return;
479
- if (activeVisualTabId !== null && activeVisualTabId !== tabId) {
480
- const prevId = activeVisualTabId;
481
- activeVisualTabId = tabId;
482
- await hideTabCursor(prevId).catch(() => {});
483
- if (badgeStates.get(prevId) === "active") {
484
- await updateTabFaviconBadge(prevId, null).catch(() => {});
485
- }
486
- } else {
487
- activeVisualTabId = tabId;
488
- }
489
- const badge = badgeStates.get(tabId) ?? (attached.has(tabId) ? "active" : null);
490
- if (badge) await updateTabFaviconBadge(tabId, badge);
491
- if (attached.has(tabId) && cursorMode !== "off") {
492
- const state = cursorStates.get(tabId);
493
- if (state?.isVisible) {
494
- if (await prepareContentScript(tabId)) {
495
- const delivered = await withTimeout(chrome.tabs.sendMessage(tabId, {type: "AGENT_CURSOR_STATE", state}), 400);
496
- 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(() => {});
497
549
  }
498
550
  } else {
499
- 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
+ }
500
565
  }
566
+ } finally {
567
+ syncingVisualTabs.delete(tabId);
501
568
  }
502
569
  }
503
570
 
@@ -567,14 +634,22 @@ function connect() {
567
634
  function onTabActivated(activeInfo) {
568
635
  const tabId = activeInfo?.tabId;
569
636
  if (Number.isSafeInteger(tabId) && Number.isSafeInteger(activeInfo?.windowId)) {
570
- 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();
571
644
  if (hist.current?.tabId !== tabId) {
572
645
  windowActiveHistory.set(activeInfo.windowId, {
573
- current: {tabId, wasUserTab: !owned.has(tabId)},
646
+ current: entry,
574
647
  previous: hist.current,
648
+ recent,
575
649
  });
576
650
  } else {
577
- hist.current.wasUserTab = !owned.has(tabId);
651
+ hist.current.wasUserTab = wasUser;
652
+ hist.recent = recent;
578
653
  }
579
654
  }
580
655
  if (!Number.isSafeInteger(tabId) || attached.has(tabId)) return;
@@ -589,6 +664,7 @@ function connect() {
589
664
  owned.delete(id);
590
665
  userOwned.delete(id);
591
666
  attached.delete(id);
667
+ userOriginalGroups.delete(id);
592
668
  deliveredAgentTabs.delete(id);
593
669
  frames.delete(id);
594
670
  downloadWatchers.delete(id);
@@ -597,10 +673,15 @@ function connect() {
597
673
  faviconCache.delete(id);
598
674
  preparingContentScripts.delete(id);
599
675
  contentScriptReadyTabs.delete(id);
676
+ syncingVisualTabs.delete(id);
677
+ lastAxNotifyAt.delete(id);
678
+ newlyCreatedPopups.delete(id);
600
679
  restoringFocus.delete(id);
680
+ if (activeVisualTabId === id) activeVisualTabId = null;
601
681
  for (const hist of windowActiveHistory.values()) {
602
682
  if (hist.current?.tabId === id) hist.current = null;
603
683
  if (hist.previous?.tabId === id) hist.previous = null;
684
+ if (Array.isArray(hist.recent)) hist.recent = hist.recent.filter((e) => e.tabId !== id);
604
685
  }
605
686
  };
606
687
 
@@ -619,13 +700,34 @@ function connect() {
619
700
  const candidateUrl = tab.url || tab.pendingUrl || "";
620
701
  if (!isControllableTabUrl(candidateUrl)) return;
621
702
  owned.add(tab.id);
622
- if (tab.active === true && Number.isSafeInteger(tab.windowId) &&
623
- 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)) {
624
706
  const hist = windowActiveHistory.get(tab.windowId);
625
- const candidate = hist?.current?.tabId === tab.id ? hist?.previous : hist?.current;
626
- 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") {
627
729
  restoringFocus.add(tab.id);
628
- void Promise.resolve(chrome.tabs.update(candidate.tabId, {active: true}))
730
+ void Promise.resolve(chrome.windows.update(lastUserWindowId, {focused: true}))
629
731
  .catch(() => {})
630
732
  .finally(() => restoringFocus.delete(tab.id));
631
733
  }
@@ -642,6 +744,8 @@ function connect() {
642
744
  chrome.tabs.onUpdated?.addListener(onTabUpdated);
643
745
  chrome.tabs.onActivated?.addListener(onTabActivated);
644
746
  chrome.tabGroups?.onRemoved?.addListener(onTabGroupRemoved);
747
+ chrome.windows?.onFocusChanged?.addListener(onWindowFocusChanged);
748
+ chrome.windows?.onRemoved?.addListener(onWindowRemoved);
645
749
  chrome.runtime.onMessage?.addListener(onRuntimeMessage);
646
750
 
647
751
  /** @param {number} gid @param {number|null} targetWindowId @returns {Promise<chrome.tabGroups.TabGroup|null>} */
@@ -661,11 +765,28 @@ function connect() {
661
765
  if (disconnected) throw new Error("Chrome bridge is disconnected");
662
766
  if (method === "createBlankTab") {
663
767
  let createOpts = {url: "about:blank", active: false};
768
+ let hasWindow = false;
664
769
  if (typeof chrome.windows?.getLastFocused === "function") {
665
770
  const win = await chrome.windows.getLastFocused({windowTypes: ["normal"]}).catch(() => null);
666
- 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;
667
788
  }
668
- const tab = serializeTab(await chrome.tabs.create(createOpts));
789
+ const tab = serializeTab(createdRaw);
669
790
  if (disconnected) {
670
791
  await chrome.tabs.remove(tab.id);
671
792
  throw new Error("Chrome bridge disconnected during tab creation");
@@ -715,6 +836,9 @@ function connect() {
715
836
  if (!owned.has(tab.id)) {
716
837
  owned.add(tab.id);
717
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
+ }
718
842
  }
719
843
  return {
720
844
  ...serializeTab(tab),
@@ -726,7 +850,10 @@ function connect() {
726
850
  if (details?.cursorMode === "fast" || details?.cursorMode === "smooth" || details?.cursorMode === "off") {
727
851
  cursorMode = details.cursorMode;
728
852
  }
729
- return {ok: true, cursorMode};
853
+ if (typeof details?.allowTabFocus === "boolean") {
854
+ allowTabFocus = details.allowTabFocus;
855
+ }
856
+ return {ok: true, cursorMode, allowTabFocus};
730
857
  }
731
858
  if (method === "readTabContext") {
732
859
  if (!Number.isSafeInteger(tabId) || typeof chrome.tabs?.get !== "function") {
@@ -777,9 +904,18 @@ function connect() {
777
904
  const sessionId = typeof details?.sessionId === "string" ? details.sessionId : null;
778
905
 
779
906
  let targetWindowId = null;
907
+ let windowTabIds = tabIds;
780
908
  if (typeof chrome.tabs?.get === "function") {
781
- const firstTab = await chrome.tabs.get(tabIds[0]).catch(() => null);
782
- 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
+ }
783
919
  }
784
920
 
785
921
  let existingGroup = null;
@@ -807,12 +943,12 @@ function connect() {
807
943
  let groupId;
808
944
  if (targetGroupId !== null) {
809
945
  try {
810
- groupId = await chrome.tabs.group({groupId: targetGroupId, tabIds});
946
+ groupId = await chrome.tabs.group({groupId: targetGroupId, tabIds: windowTabIds});
811
947
  } catch {
812
- groupId = await chrome.tabs.group({tabIds});
948
+ groupId = await chrome.tabs.group({tabIds: windowTabIds});
813
949
  }
814
950
  } else {
815
- groupId = await chrome.tabs.group({tabIds});
951
+ groupId = await chrome.tabs.group({tabIds: windowTabIds});
816
952
  }
817
953
 
818
954
  if (Number.isSafeInteger(groupId)) {
@@ -921,28 +1057,142 @@ function connect() {
921
1057
  }
922
1058
  if (!Number.isSafeInteger(tabId) || !owned.has(tabId)) {
923
1059
  if (method === "readTab") return null;
924
- 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;
925
1062
  throw new Error("Unknown Chrome bridge request");
926
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
+
927
1164
  switch (method) {
928
1165
  case "readTab": return serializeTab(await chrome.tabs.get(tabId));
929
1166
  case "closeTab":
930
1167
  await chrome.tabs.remove(tabId);
931
1168
  forget(tabId);
932
1169
  return null;
933
- case "releaseTab":
1170
+ case "releaseTab": {
934
1171
  if (attached.has(tabId)) {
935
1172
  await chrome.debugger.detach({tabId}).catch(() => {});
936
1173
  attached.delete(tabId);
937
1174
  frames.delete(tabId);
938
1175
  }
939
- await hideTabCursor(tabId);
1176
+ void hideTabCursor(tabId).catch(() => {});
940
1177
  if (badgeStates.get(tabId) === "active") {
941
- await updateTabFaviconBadge(tabId, null);
1178
+ void updateTabFaviconBadge(tabId, null).catch(() => {});
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
+ }
942
1187
  }
1188
+ downloadWatchers.delete(tabId);
1189
+ cursorStates.delete(tabId);
1190
+ faviconCache.delete(tabId);
1191
+ newlyCreatedPopups.delete(tabId);
943
1192
  owned.delete(tabId);
944
1193
  userOwned.delete(tabId);
945
1194
  return null;
1195
+ }
946
1196
  case "markTab": {
947
1197
  const status = details?.status === "deliverable" ? "deliverable" : (details?.status === "handoff" ? "handoff" : null);
948
1198
  const tab = typeof chrome.tabs?.get === "function" ? await chrome.tabs.get(tabId).catch(() => null) : null;
@@ -950,12 +1200,12 @@ function connect() {
950
1200
  if (tab && Number.isSafeInteger(tab.groupId) && tab.groupId >= 0 && typeof chrome.tabGroups?.update === "function") {
951
1201
  await chrome.tabGroups.update(tab.groupId, {collapsed: false}).catch(() => {});
952
1202
  }
953
- if (typeof chrome.tabs?.update === "function") {
1203
+ if (allowTabFocus && typeof chrome.tabs?.update === "function") {
954
1204
  await chrome.tabs.update(tabId, {active: true}).catch(() => {});
955
1205
  }
956
1206
  }
957
1207
  if (status) {
958
- await updateTabFaviconBadge(tabId, status);
1208
+ void updateTabFaviconBadge(tabId, status).catch(() => {});
959
1209
  if (status === "deliverable" && !userOwned.has(tabId)) {
960
1210
  const normUrl = normalizeComparableUrl(tab?.url || tab?.pendingUrl || "");
961
1211
  if (normUrl) {
@@ -994,8 +1244,12 @@ function connect() {
994
1244
  attached.add(tabId);
995
1245
  frames.set(tabId, new Map());
996
1246
  }
1247
+ await Promise.all([
1248
+ chrome.debugger.sendCommand({tabId}, "Emulation.setFocusEmulationEnabled", {enabled: true}).catch(() => {}),
1249
+ chrome.debugger.sendCommand({tabId}, "Page.enable", {}).catch(() => {}),
1250
+ ]);
997
1251
  badgeStates.set(tabId, "active");
998
- await syncTabVisuals(tabId);
1252
+ void syncTabVisuals(tabId).catch(() => {});
999
1253
  return null;
1000
1254
  case "detach":
1001
1255
  if (attached.has(tabId)) {
@@ -1003,9 +1257,9 @@ function connect() {
1003
1257
  attached.delete(tabId);
1004
1258
  frames.delete(tabId);
1005
1259
  }
1006
- await hideTabCursor(tabId);
1260
+ void hideTabCursor(tabId).catch(() => {});
1007
1261
  if (badgeStates.get(tabId) === "active") {
1008
- await updateTabFaviconBadge(tabId, null);
1262
+ void updateTabFaviconBadge(tabId, null).catch(() => {});
1009
1263
  }
1010
1264
  return null;
1011
1265
  case "navigate":
@@ -1018,86 +1272,45 @@ function connect() {
1018
1272
  case "unwatchDownloads":
1019
1273
  downloadWatchers.delete(tabId);
1020
1274
  return null;
1021
- case "execute": {
1275
+ case "execute":
1276
+ return await executeSingleCdp(tabId, details ?? {});
1277
+ case "executeBatch": {
1022
1278
  if (!attached.has(tabId)) throw new Error("Debugger unattached");
1023
- const sessionId = details.childSession;
1024
- if (sessionId !== undefined && !frames.get(tabId)?.has(sessionId)) {
1025
- 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");
1026
1282
  }
1027
- const target = sessionId === undefined ? {tabId} : {tabId, sessionId};
1028
- const cdpMethod = details.method;
1029
- const cdpParams = details.params;
1030
-
1031
- if (canMessageTabs() && cursorMode !== "off") {
1032
- if (cdpMethod === "Input.dispatchMouseEvent" && Number.isFinite(cdpParams?.x) && Number.isFinite(cdpParams?.y)) {
1033
- if (cdpParams.type === "mouseMoved") {
1034
- const wait = cursorMode === "smooth" && !cdpParams.buttons;
1035
- if (wait) {
1036
- await updateCursorPosition(tabId, Number(cdpParams.x), Number(cdpParams.y), {
1037
- visible: true,
1038
- animate: true,
1039
- waitForArrival: true,
1040
- });
1041
- } else {
1042
- void updateCursorPosition(tabId, Number(cdpParams.x), Number(cdpParams.y), {
1043
- visible: true,
1044
- animate: true,
1045
- waitForArrival: false,
1046
- });
1047
- }
1048
- } else if (cdpParams.type === "mousePressed" || cdpParams.type === "mouseWheel") {
1049
- void updateCursorPosition(tabId, Number(cdpParams.x), Number(cdpParams.y), {
1050
- visible: true,
1051
- animate: true,
1052
- waitForArrival: false,
1053
- });
1054
- }
1055
- } else if (cdpMethod === "DOM.focus" &&
1056
- (cdpParams?.objectId || Number.isSafeInteger(cdpParams?.backendNodeId))) {
1057
- const boxReq = cdpParams.objectId
1058
- ? {objectId: cdpParams.objectId}
1059
- : {backendNodeId: cdpParams.backendNodeId};
1060
- const box = await chrome.debugger.sendCommand(target, "DOM.getBoxModel", boxReq).catch(() => null);
1061
- const quad = box?.model?.border;
1062
- if (Array.isArray(quad) && quad.length === 8) {
1063
- const cx = (quad[0] + quad[2]) / 2;
1064
- const cy = (quad[1] + quad[5]) / 2;
1065
- if (Number.isFinite(cx) && Number.isFinite(cy)) {
1066
- const wait = cursorMode === "smooth";
1067
- if (wait) {
1068
- await updateCursorPosition(tabId, cx, cy, {visible: true, animate: true, waitForArrival: true});
1069
- } else {
1070
- void updateCursorPosition(tabId, cx, cy, {visible: true, animate: true, waitForArrival: false});
1071
- }
1072
- }
1073
- }
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;
1074
1295
  }
1075
- }
1076
-
1077
- const result = await chrome.debugger.sendCommand(target, cdpMethod, cdpParams);
1078
-
1079
- if (canMessageTabs() && cursorMode !== "off" &&
1080
- (cdpMethod === "Runtime.evaluate" || cdpMethod === "Runtime.callFunctionOn")) {
1081
- const val = result?.result?.value;
1082
- if (val && typeof val === "object" && Number.isFinite(val.x) && Number.isFinite(val.y) &&
1083
- (val.__cursorMove === true || val.hovered === true)) {
1084
- const wait = cursorMode === "smooth";
1085
- if (wait) {
1086
- await updateCursorPosition(tabId, Number(val.x), Number(val.y), {
1087
- visible: true,
1088
- animate: true,
1089
- waitForArrival: true,
1090
- });
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)});
1091
1308
  } else {
1092
- void updateCursorPosition(tabId, Number(val.x), Number(val.y), {
1093
- visible: true,
1094
- animate: true,
1095
- waitForArrival: false,
1096
- });
1309
+ throw error;
1097
1310
  }
1098
1311
  }
1099
1312
  }
1100
- return result;
1313
+ return {results};
1101
1314
  }
1102
1315
  default: throw new Error("Unknown Chrome bridge request");
1103
1316
  }
@@ -1123,10 +1336,7 @@ function connect() {
1123
1336
  } else if (method === "Target.detachedFromTarget") {
1124
1337
  if (!tree.has(params?.sessionId)) return;
1125
1338
  dropFrame(tree, params.sessionId);
1126
- } else if (!/^(?:Page|Runtime|DOM)\./u.test(method) &&
1127
- !["Accessibility.loadComplete", "Accessibility.nodesUpdated",
1128
- "Network.requestWillBeSent", "Network.responseReceived",
1129
- "Network.loadingFinished", "Network.loadingFailed"].includes(method)) {
1339
+ } else if (!FORWARDED_CDP_EVENTS.has(method)) {
1130
1340
  return;
1131
1341
  }
1132
1342
  if (sessionId === undefined && (method === "Page.frameStartedLoading" ||
@@ -1134,7 +1344,7 @@ function connect() {
1134
1344
  contentScriptReadyTabs.delete(tabId);
1135
1345
  }
1136
1346
  if (method === "Page.loadEventFired" && sessionId === undefined && attached.has(tabId)) {
1137
- void syncTabVisuals(tabId);
1347
+ void syncTabVisuals(tabId).catch(() => {});
1138
1348
  }
1139
1349
  if (method === "Page.frameDetached" && params?.reason === "swap") {
1140
1350
  // The renderer lost its local frame. A debugger session for the same
@@ -1144,15 +1354,22 @@ function connect() {
1144
1354
  }
1145
1355
  }
1146
1356
  let outgoingParams = params;
1147
- 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") {
1148
1365
  outgoingParams = {
1149
1366
  requestId: params?.requestId,
1150
1367
  loaderId: params?.loaderId,
1151
- documentURL: params?.documentURL,
1368
+ documentURL: truncateLongUrl(params?.documentURL),
1152
1369
  frameId: params?.frameId,
1153
1370
  type: params?.type,
1154
1371
  timestamp: params?.timestamp,
1155
- 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,
1156
1373
  };
1157
1374
  } else if (method === "Network.responseReceived") {
1158
1375
  outgoingParams = {
@@ -1162,7 +1379,7 @@ function connect() {
1162
1379
  type: params?.type,
1163
1380
  timestamp: params?.timestamp,
1164
1381
  response: params?.response ? {
1165
- url: params.response.url,
1382
+ url: truncateLongUrl(params.response.url),
1166
1383
  status: params.response.status,
1167
1384
  statusText: params.response.statusText,
1168
1385
  mimeType: params.response.mimeType,
@@ -1172,7 +1389,7 @@ function connect() {
1172
1389
  };
1173
1390
  }
1174
1391
  const event = {event: "onCDPEvent", tabId, params: {source: {tabId, sessionId}, method, params: outgoingParams}};
1175
- if (COMPACT_EVENTS.has(method) || JSON.stringify(event).length < 256 * 1024) {
1392
+ if (COMPACT_EVENTS.has(method) || utf8ByteLength(JSON.stringify(event)) < 256 * 1024) {
1176
1393
  port.postMessage(event);
1177
1394
  }
1178
1395
  }
@@ -1265,6 +1482,8 @@ function connect() {
1265
1482
  chrome.tabs.onUpdated?.removeListener(onTabUpdated);
1266
1483
  chrome.tabs.onActivated?.removeListener(onTabActivated);
1267
1484
  chrome.tabGroups?.onRemoved?.removeListener(onTabGroupRemoved);
1485
+ chrome.windows?.onFocusChanged?.removeListener(onWindowFocusChanged);
1486
+ chrome.windows?.onRemoved?.removeListener(onWindowRemoved);
1268
1487
  chrome.runtime.onMessage?.removeListener(onRuntimeMessage);
1269
1488
  chrome.debugger.onEvent.removeListener(onDebuggerEvent);
1270
1489
  chrome.debugger.onDetach.removeListener(onDebuggerDetach);
@@ -1294,7 +1513,9 @@ function connect() {
1294
1513
  preparingContentScripts.clear();
1295
1514
  contentScriptReadyTabs.clear();
1296
1515
  windowActiveHistory.clear();
1516
+ newlyCreatedPopups.clear();
1297
1517
  restoringFocus.clear();
1518
+ userOriginalGroups.clear();
1298
1519
  agentGroups.clear();
1299
1520
  sessionGroups.clear();
1300
1521
  deliveredAgentTabs.clear();
@@ -1311,6 +1532,13 @@ function connect() {
1311
1532
  reconnectTimer = null;
1312
1533
  if (!disconnectActive && !manualDisconnect) connect();
1313
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: "!"});
1314
1542
  }
1315
1543
  }
1316
1544
 
@@ -1327,15 +1555,33 @@ function connect() {
1327
1555
  return;
1328
1556
  }
1329
1557
  const serialized = JSON.stringify(val);
1330
- const size = 512 * 1024;
1331
- if (serialized.length <= size) port.postMessage(reply);
1332
- 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) {
1333
1570
  port.postMessage({id: reply.id, ok: false, error: "Chrome native response exceeds bridge limit"});
1334
- } else {
1335
- for (let offset = 0; offset < serialized.length; offset += size) {
1336
- port.postMessage({id: reply.id, index: offset / size, final: offset + size >= serialized.length,
1337
- 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);
1338
1582
  }
1583
+ port.postMessage({id: reply.id, index: index++, final: end >= serialized.length, chunk: piece});
1584
+ offset = end;
1339
1585
  }
1340
1586
  });
1341
1587
  port.onDisconnect.addListener(onDisconnect);
@@ -1348,16 +1594,28 @@ function connect() {
1348
1594
  void cleanupStaleVisuals();
1349
1595
  }
1350
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
+
1351
1606
  chrome.action.onClicked.addListener(() => {
1352
1607
  if (disconnectActive) {
1353
1608
  manualDisconnect = true;
1609
+ persistManualDisconnect(true);
1354
1610
  if (reconnectTimer) {
1355
1611
  clearTimeout(reconnectTimer);
1356
1612
  reconnectTimer = null;
1357
1613
  }
1614
+ try { void chrome.alarms?.clear?.("bu_reconnect"); } catch { /* ignore */ }
1358
1615
  disconnectActive();
1359
1616
  } else {
1360
1617
  manualDisconnect = false;
1618
+ persistManualDisconnect(false);
1361
1619
  reconnectAttempts = 0;
1362
1620
  connect();
1363
1621
  }
@@ -1375,10 +1633,38 @@ const autoConnect = () => {
1375
1633
 
1376
1634
  const resetAndAutoConnect = () => {
1377
1635
  manualDisconnect = false;
1636
+ persistManualDisconnect(false);
1378
1637
  reconnectAttempts = 0;
1379
1638
  autoConnect();
1380
1639
  };
1381
1640
 
1641
+ chrome.alarms?.onAlarm?.addListener((alarm) => {
1642
+ if (alarm?.name === "bu_reconnect") autoConnect();
1643
+ });
1382
1644
  chrome.runtime.onInstalled?.addListener(resetAndAutoConnect);
1383
1645
  chrome.runtime.onStartup?.addListener(resetAndAutoConnect);
1384
- 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
+ }