codex-browser-use 0.0.0-stage → 4.8.2
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.
- package/LICENSE +21 -0
- package/README.md +312 -2
- package/bin/browser-use.js +213 -0
- package/bin/chrome-native-host.js +29 -0
- package/extension/background.js +1384 -0
- package/extension/content-script.js +3 -0
- package/extension/icons/icon-128.png +0 -0
- package/extension/icons/icon-16.png +0 -0
- package/extension/icons/icon-32.png +0 -0
- package/extension/icons/icon-48.png +0 -0
- package/extension/manifest.json +33 -0
- package/package.json +44 -4
- package/rules/browser_use.md +26 -0
- package/skill/SKILL.md +72 -0
- package/skill/references/cookbook.md +281 -0
- package/skill/references/tools.md +18 -0
- package/src/ax-tree.js +889 -0
- package/src/backend-discovery.js +123 -0
- package/src/backend-native-driver.js +223 -0
- package/src/backend-page-commands.js +91 -0
- package/src/backend-tabs.js +490 -0
- package/src/backend-transport.js +165 -0
- package/src/bridge-browser.js +3787 -0
- package/src/bridge-client.js +181 -0
- package/src/config.js +166 -0
- package/src/content-extractor.js +576 -0
- package/src/engine-discovery.js +90 -0
- package/src/extension.js +26 -0
- package/src/frame-reader.js +160 -0
- package/src/install.js +303 -0
- package/src/locators.js +1497 -0
- package/src/official-runtime.js +359 -0
- package/src/portable-server.js +244 -0
- package/src/read-only.js +333 -0
- package/src/repl-session.js +180 -0
- package/src/repl-worker.js +190 -0
- package/src/script-runner.js +1546 -0
- package/src/server.js +1121 -0
|
@@ -0,0 +1,1384 @@
|
|
|
1
|
+
const hostName = "com.portable_browser_use.bridge";
|
|
2
|
+
const TAB_GROUP_COLORS = new Set(["grey", "blue", "red", "yellow", "green", "pink", "purple", "cyan", "orange"]);
|
|
3
|
+
const FALLBACK_FAVICON_DATA_URL = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
|
|
4
|
+
const CURSOR_SESSION_ID = "portable-browser-use";
|
|
5
|
+
const CURSOR_TURN_ID = "active-turn";
|
|
6
|
+
const COMPACT_EVENTS = new Set([
|
|
7
|
+
"Target.attachedToTarget",
|
|
8
|
+
"Target.detachedFromTarget",
|
|
9
|
+
"Page.frameStartedLoading",
|
|
10
|
+
"Page.frameStoppedLoading",
|
|
11
|
+
"Page.frameNavigated",
|
|
12
|
+
"Page.navigatedWithinDocument",
|
|
13
|
+
"Page.domContentEventFired",
|
|
14
|
+
"Page.loadEventFired",
|
|
15
|
+
"Page.lifecycleEvent",
|
|
16
|
+
"Page.frameDetached",
|
|
17
|
+
"Page.javascriptDialogOpening",
|
|
18
|
+
"Page.javascriptDialogClosed",
|
|
19
|
+
"Page.fileChooserOpened",
|
|
20
|
+
"Network.requestWillBeSent",
|
|
21
|
+
"Network.responseReceived",
|
|
22
|
+
"Network.loadingFinished",
|
|
23
|
+
"Network.loadingFailed",
|
|
24
|
+
]);
|
|
25
|
+
/** @type {(() => void) | null} */
|
|
26
|
+
let disconnectActive = null;
|
|
27
|
+
let manualDisconnect = false;
|
|
28
|
+
/** @type {ReturnType<typeof setTimeout> | null} */
|
|
29
|
+
let reconnectTimer = null;
|
|
30
|
+
let reconnectAttempts = 0;
|
|
31
|
+
|
|
32
|
+
/** @param {chrome.tabs.Tab} tab @returns {{id:number,url?:string,title?:string,active:boolean,windowId?:number,groupId?:number}} */
|
|
33
|
+
function serializeTab(tab) {
|
|
34
|
+
if (!Number.isSafeInteger(tab?.id)) throw new Error("Chrome returned a tab without an ID");
|
|
35
|
+
return {
|
|
36
|
+
id: tab.id,
|
|
37
|
+
url: tab.url,
|
|
38
|
+
title: tab.title,
|
|
39
|
+
active: Boolean(tab.active),
|
|
40
|
+
...(Number.isSafeInteger(tab.windowId) ? {windowId: tab.windowId} : {}),
|
|
41
|
+
...(Number.isSafeInteger(tab.groupId) && tab.groupId >= 0 ? {groupId: tab.groupId} : {}),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** @param {string|undefined} rawUrl @returns {string|null} */
|
|
46
|
+
function normalizeComparableUrl(rawUrl) {
|
|
47
|
+
if (typeof rawUrl !== "string" || !rawUrl) return null;
|
|
48
|
+
try {
|
|
49
|
+
const parsed = new URL(rawUrl);
|
|
50
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
|
|
51
|
+
return `${parsed.origin}${parsed.pathname.replace(/\/+$/u, "")}${parsed.search}`;
|
|
52
|
+
} catch {
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** @param {string|undefined} url @returns {boolean} */
|
|
58
|
+
function isControllableTabUrl(url) {
|
|
59
|
+
if (typeof url !== "string" || !url) return true;
|
|
60
|
+
return !/^(?:chrome|chrome-extension|chrome-untrusted|devtools|edge|brave|vivaldi|opera|view-source):/iu.test(url.trim());
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** @returns {boolean} */
|
|
64
|
+
function canMessageTabs() {
|
|
65
|
+
return typeof chrome.tabs?.sendMessage === "function";
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** @param {string|undefined} href @returns {boolean} */
|
|
69
|
+
function isBadgedFaviconUrl(href) {
|
|
70
|
+
return typeof href === "string" && href.startsWith("data:image/svg+xml,") && href.includes("codex-favicon-badge");
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Self-contained DOM extractor injected via chrome.scripting.executeScript for zero-debugger passive reads.
|
|
75
|
+
* @param {{format?:string,maxChars?:number}} [opts]
|
|
76
|
+
*/
|
|
77
|
+
function extractPassiveTabContext(opts = {}) {
|
|
78
|
+
const format = opts?.format === "text" ? "text" : "markdown";
|
|
79
|
+
const maxChars = Math.max(200, Number(opts?.maxChars) || 16_000);
|
|
80
|
+
const title = document.title || "";
|
|
81
|
+
const url = location.href || "";
|
|
82
|
+
const selection = typeof window.getSelection === "function" ? String(window.getSelection() || "").trim() : "";
|
|
83
|
+
const headingsCount = document.querySelectorAll("h1,h2,h3,h4,h5,h6").length;
|
|
84
|
+
const linksCount = document.querySelectorAll("a[href]").length;
|
|
85
|
+
|
|
86
|
+
const clip = (str) => {
|
|
87
|
+
const clean = String(str || "").trim();
|
|
88
|
+
if (clean.length <= maxChars) return { text: clean, truncated: false };
|
|
89
|
+
return { text: clean.slice(0, maxChars) + "\n...(truncated)", truncated: true };
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
if (format === "text" || !document.body) {
|
|
93
|
+
const raw = document.body ? (document.body.innerText || "") : "";
|
|
94
|
+
const out = clip(raw);
|
|
95
|
+
return { title, url, format: "text", text: out.text, content: out.text, truncated: out.truncated, headingsCount, linksCount, selection };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const SKIP = new Set(["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE", "SVG", "NAV", "HEADER", "FOOTER", "ASIDE"]);
|
|
99
|
+
const pickRoot = () => {
|
|
100
|
+
for (const sel of ["article", "main", '[role="main"]']) {
|
|
101
|
+
const candidate = document.querySelector(sel);
|
|
102
|
+
if (candidate && (candidate.innerText || "").trim().length >= 200) return candidate;
|
|
103
|
+
}
|
|
104
|
+
return document.body;
|
|
105
|
+
};
|
|
106
|
+
const root = pickRoot();
|
|
107
|
+
const isHidden = (el) => {
|
|
108
|
+
if (!el || el.nodeType !== 1) return false;
|
|
109
|
+
if (SKIP.has(el.tagName) || el.getAttribute("aria-hidden") === "true" || el.hidden) return true;
|
|
110
|
+
const st = getComputedStyle(el);
|
|
111
|
+
return st && (st.display === "none" || st.visibility === "hidden");
|
|
112
|
+
};
|
|
113
|
+
const parts = [];
|
|
114
|
+
let len = 0;
|
|
115
|
+
let truncated = false;
|
|
116
|
+
const push = (chunk) => {
|
|
117
|
+
if (truncated || !chunk) return;
|
|
118
|
+
if (len + chunk.length > maxChars) {
|
|
119
|
+
parts.push(chunk.slice(0, Math.max(0, maxChars - len)));
|
|
120
|
+
truncated = true;
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
parts.push(chunk);
|
|
124
|
+
len += chunk.length;
|
|
125
|
+
};
|
|
126
|
+
const inlineText = (node) => (node.innerText || node.textContent || "").replace(/\s+/g, " ").trim();
|
|
127
|
+
const walk = (node) => {
|
|
128
|
+
if (truncated || !node) return;
|
|
129
|
+
if (node.nodeType === 3) {
|
|
130
|
+
const t = (node.textContent || "").replace(/\s+/g, " ");
|
|
131
|
+
if (t.trim()) push(t);
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
if (node.nodeType !== 1 || isHidden(node)) return;
|
|
135
|
+
const tag = node.tagName;
|
|
136
|
+
if (/^H[1-6]$/.test(tag)) {
|
|
137
|
+
const txt = inlineText(node);
|
|
138
|
+
if (txt) push(`\n\n${"#".repeat(Number(tag[1]))} ${txt}\n\n`);
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
if (tag === "A") {
|
|
142
|
+
const txt = inlineText(node);
|
|
143
|
+
const href = node.getAttribute("href") || "";
|
|
144
|
+
if (txt) push(href && !href.startsWith("javascript:") ? `[${txt}](${href})` : txt);
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
if (tag === "PRE") {
|
|
148
|
+
const code = (node.innerText || node.textContent || "").trim();
|
|
149
|
+
if (code) push(`\n\n\`\`\`\n${code}\n\`\`\`\n\n`);
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
if (tag === "LI") {
|
|
153
|
+
const txt = inlineText(node);
|
|
154
|
+
if (txt) push(`\n- ${txt}`);
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
if (tag === "BLOCKQUOTE") {
|
|
158
|
+
const txt = inlineText(node);
|
|
159
|
+
if (txt) push(`\n> ${txt}\n`);
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
if (tag === "TR") {
|
|
163
|
+
const cells = Array.from(node.children || []).map((c) => inlineText(c).replace(/\|/g, "\\|"));
|
|
164
|
+
if (cells.some(Boolean)) push(`\n| ${cells.join(" | ")} |`);
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
const isBlock = /^(P|DIV|SECTION|ARTICLE|MAIN|TABLE|UL|OL|BR|HR)$/u.test(tag);
|
|
168
|
+
if (isBlock) push("\n");
|
|
169
|
+
for (const child of node.childNodes || []) {
|
|
170
|
+
walk(child);
|
|
171
|
+
if (truncated) break;
|
|
172
|
+
}
|
|
173
|
+
if (isBlock) push("\n");
|
|
174
|
+
};
|
|
175
|
+
walk(root);
|
|
176
|
+
const md = parts.join("").replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim() + (truncated ? "\n...(truncated)" : "");
|
|
177
|
+
return { title, url, format: "markdown", text: md, content: md, truncated, headingsCount, linksCount, selection };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** @returns {void} */
|
|
181
|
+
function connect() {
|
|
182
|
+
const port = chrome.runtime.connectNative(hostName);
|
|
183
|
+
/** @type {Set<number>} */
|
|
184
|
+
const owned = new Set();
|
|
185
|
+
/** @type {Set<number>} */
|
|
186
|
+
const userOwned = new Set();
|
|
187
|
+
/** @type {Set<number>} */
|
|
188
|
+
const attached = new Set();
|
|
189
|
+
/** @type {Set<number>} */
|
|
190
|
+
const agentGroups = new Set();
|
|
191
|
+
/** @type {Map<string, number>} */
|
|
192
|
+
const sessionGroups = new Map();
|
|
193
|
+
/** @type {Map<number, {url:string|null,groupId:number|null,createdAt:number}>} */
|
|
194
|
+
const deliveredAgentTabs = new Map();
|
|
195
|
+
/** @type {Map<number, Map<string,{parentId:string|null,targetId:string}>>} */
|
|
196
|
+
const frames = new Map();
|
|
197
|
+
/** @type {Map<number, {startedAt:number}>} */
|
|
198
|
+
const downloadWatchers = new Map();
|
|
199
|
+
/** @type {Map<number, {id:number,url?:string,filename?:string,state?:string,error?:string}>} */
|
|
200
|
+
const trackedDownloads = new Map();
|
|
201
|
+
/** @type {Map<number, {cursor:null|{x:number,y:number,visible:boolean,animateMovement?:boolean,moveSequence?:number},isVisible:boolean,sessionId:string|null,turnId:string|null}>} */
|
|
202
|
+
const cursorStates = new Map();
|
|
203
|
+
/** @type {Map<number, "active"|"deliverable"|"handoff">} */
|
|
204
|
+
const badgeStates = new Map();
|
|
205
|
+
/** @type {Map<number, string>} */
|
|
206
|
+
const faviconCache = new Map();
|
|
207
|
+
/** @type {Map<number, Promise<boolean>>} */
|
|
208
|
+
const preparingContentScripts = new Map();
|
|
209
|
+
/** @type {Set<number>} */
|
|
210
|
+
const contentScriptReadyTabs = new Set();
|
|
211
|
+
/** @type {Map<number, () => void>} */
|
|
212
|
+
const cursorArrivalWaiters = new Map();
|
|
213
|
+
/** @type {number|null} */
|
|
214
|
+
let activeVisualTabId = null;
|
|
215
|
+
/** @type {"fast"|"smooth"|"off"} */
|
|
216
|
+
let cursorMode = "fast";
|
|
217
|
+
let moveSeq = 0;
|
|
218
|
+
let disconnected = false;
|
|
219
|
+
/** @type {Map<number, {current:{tabId:number,wasUserTab:boolean}|null, previous:{tabId:number,wasUserTab:boolean}|null}>} */
|
|
220
|
+
const windowActiveHistory = new Map();
|
|
221
|
+
/** @type {Set<number>} */
|
|
222
|
+
const restoringFocus = new Set();
|
|
223
|
+
|
|
224
|
+
if (typeof chrome.tabs?.query === "function") {
|
|
225
|
+
void Promise.resolve(chrome.tabs.query({active: true})).then((tabs) => {
|
|
226
|
+
if (disconnected || !Array.isArray(tabs)) return;
|
|
227
|
+
for (const tab of tabs) {
|
|
228
|
+
if (!Number.isSafeInteger(tab?.id) || !Number.isSafeInteger(tab?.windowId)) continue;
|
|
229
|
+
if (!windowActiveHistory.has(tab.windowId)) {
|
|
230
|
+
windowActiveHistory.set(tab.windowId, {
|
|
231
|
+
current: {tabId: tab.id, wasUserTab: !owned.has(tab.id)},
|
|
232
|
+
previous: null,
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}).catch(() => {});
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* @template T
|
|
241
|
+
* @param {Promise<T>} promise
|
|
242
|
+
* @param {number} timeoutMs
|
|
243
|
+
* @returns {Promise<T|null>}
|
|
244
|
+
*/
|
|
245
|
+
async function withTimeout(promise, timeoutMs) {
|
|
246
|
+
if (typeof setTimeout !== "function") return await promise.catch(() => null);
|
|
247
|
+
let timer;
|
|
248
|
+
const deadline = new Promise((resolve) => {
|
|
249
|
+
timer = setTimeout(() => resolve(null), timeoutMs);
|
|
250
|
+
});
|
|
251
|
+
try {
|
|
252
|
+
return await Promise.race([promise.catch(() => null), deadline]);
|
|
253
|
+
} finally {
|
|
254
|
+
if (timer !== undefined && typeof clearTimeout === "function") clearTimeout(timer);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** @param {number} tabId @returns {Promise<boolean>} */
|
|
259
|
+
async function pingContentScript(tabId) {
|
|
260
|
+
if (!canMessageTabs()) return false;
|
|
261
|
+
const res = await withTimeout(chrome.tabs.sendMessage(tabId, {type: "CONTENT_PING"}), 350);
|
|
262
|
+
return res?.ok === true;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** @param {number} tabId @returns {Promise<boolean>} */
|
|
266
|
+
async function prepareContentScript(tabId) {
|
|
267
|
+
if (!canMessageTabs()) return false;
|
|
268
|
+
if (contentScriptReadyTabs.has(tabId)) return true;
|
|
269
|
+
if (await pingContentScript(tabId)) {
|
|
270
|
+
contentScriptReadyTabs.add(tabId);
|
|
271
|
+
return true;
|
|
272
|
+
}
|
|
273
|
+
let pending = preparingContentScripts.get(tabId);
|
|
274
|
+
if (!pending) {
|
|
275
|
+
pending = (async () => {
|
|
276
|
+
if (typeof chrome.scripting?.executeScript !== "function") return false;
|
|
277
|
+
const injected = await withTimeout(
|
|
278
|
+
chrome.scripting.executeScript({
|
|
279
|
+
target: {tabId},
|
|
280
|
+
files: ["content-script.js"],
|
|
281
|
+
injectImmediately: true,
|
|
282
|
+
}),
|
|
283
|
+
800,
|
|
284
|
+
);
|
|
285
|
+
if (injected === null) return false;
|
|
286
|
+
const ok = await pingContentScript(tabId);
|
|
287
|
+
if (ok) contentScriptReadyTabs.add(tabId);
|
|
288
|
+
return ok;
|
|
289
|
+
})().finally(() => {
|
|
290
|
+
preparingContentScripts.delete(tabId);
|
|
291
|
+
});
|
|
292
|
+
preparingContentScripts.set(tabId, pending);
|
|
293
|
+
}
|
|
294
|
+
return await pending;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** @param {number} tabId @returns {Promise<string>} */
|
|
298
|
+
async function getFaviconDataUrl(tabId) {
|
|
299
|
+
const cached = faviconCache.get(tabId);
|
|
300
|
+
if (cached) return cached;
|
|
301
|
+
if (typeof chrome.tabs?.get !== "function") return FALLBACK_FAVICON_DATA_URL;
|
|
302
|
+
try {
|
|
303
|
+
const tab = await chrome.tabs.get(tabId);
|
|
304
|
+
const rawFav = tab?.favIconUrl;
|
|
305
|
+
if (typeof rawFav === "string" && rawFav && !rawFav.startsWith("chrome://") && !isBadgedFaviconUrl(rawFav)) {
|
|
306
|
+
if (rawFav.startsWith("data:")) {
|
|
307
|
+
faviconCache.set(tabId, rawFav);
|
|
308
|
+
return rawFav;
|
|
309
|
+
}
|
|
310
|
+
if (typeof fetch === "function" && typeof FileReader === "function") {
|
|
311
|
+
const res = await withTimeout(fetch(rawFav), 600);
|
|
312
|
+
if (res?.ok) {
|
|
313
|
+
const blob = await res.blob();
|
|
314
|
+
const dataUrl = await new Promise((resolve) => {
|
|
315
|
+
const reader = new FileReader();
|
|
316
|
+
reader.onloadend = () => resolve(typeof reader.result === "string" ? reader.result : rawFav);
|
|
317
|
+
reader.onerror = () => resolve(rawFav);
|
|
318
|
+
reader.readAsDataURL(blob);
|
|
319
|
+
});
|
|
320
|
+
faviconCache.set(tabId, dataUrl);
|
|
321
|
+
return dataUrl;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
faviconCache.set(tabId, rawFav);
|
|
325
|
+
return rawFav;
|
|
326
|
+
}
|
|
327
|
+
if (typeof tab?.url === "string" && tab.url && typeof chrome.runtime?.getURL === "function" &&
|
|
328
|
+
typeof fetch === "function" && typeof FileReader === "function") {
|
|
329
|
+
const faviconUrl = chrome.runtime.getURL(`/_favicon/?pageUrl=${encodeURIComponent(tab.url)}&size=32`);
|
|
330
|
+
const res = await withTimeout(fetch(faviconUrl), 600);
|
|
331
|
+
if (res?.ok) {
|
|
332
|
+
const blob = await res.blob();
|
|
333
|
+
const dataUrl = await new Promise((resolve) => {
|
|
334
|
+
const reader = new FileReader();
|
|
335
|
+
reader.onloadend = () => resolve(typeof reader.result === "string" ? reader.result : FALLBACK_FAVICON_DATA_URL);
|
|
336
|
+
reader.onerror = () => resolve(FALLBACK_FAVICON_DATA_URL);
|
|
337
|
+
reader.readAsDataURL(blob);
|
|
338
|
+
});
|
|
339
|
+
faviconCache.set(tabId, dataUrl);
|
|
340
|
+
return dataUrl;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
} catch {
|
|
344
|
+
// Fall back to transparent 1x1 data URL so content-script always renders the badge SVG.
|
|
345
|
+
}
|
|
346
|
+
return FALLBACK_FAVICON_DATA_URL;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** @param {number} tabId @param {"active"|"deliverable"|"handoff"|null} badge @returns {Promise<void>} */
|
|
350
|
+
async function updateTabFaviconBadge(tabId, badge) {
|
|
351
|
+
if (badge) badgeStates.set(tabId, badge);
|
|
352
|
+
else badgeStates.delete(tabId);
|
|
353
|
+
if (!canMessageTabs()) return;
|
|
354
|
+
try {
|
|
355
|
+
if (badge) {
|
|
356
|
+
if (!(await prepareContentScript(tabId))) return;
|
|
357
|
+
const faviconDataUrl = await getFaviconDataUrl(tabId);
|
|
358
|
+
const delivered = await withTimeout(chrome.tabs.sendMessage(tabId, {
|
|
359
|
+
type: "TAB_FAVICON_BADGE",
|
|
360
|
+
badge,
|
|
361
|
+
faviconDataUrl,
|
|
362
|
+
}), 500);
|
|
363
|
+
if (!delivered) contentScriptReadyTabs.delete(tabId);
|
|
364
|
+
} else {
|
|
365
|
+
const delivered = await withTimeout(chrome.tabs.sendMessage(tabId, {
|
|
366
|
+
type: "TAB_FAVICON_BADGE",
|
|
367
|
+
badge: null,
|
|
368
|
+
faviconDataUrl: null,
|
|
369
|
+
}), 400);
|
|
370
|
+
if (!delivered) contentScriptReadyTabs.delete(tabId);
|
|
371
|
+
}
|
|
372
|
+
} catch {
|
|
373
|
+
// Ignore pages that do not accept content scripts.
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** @param {number} tabId @returns {Promise<void>} */
|
|
378
|
+
async function showTabCursor(tabId) {
|
|
379
|
+
if (cursorMode === "off") return;
|
|
380
|
+
const existing = cursorStates.get(tabId);
|
|
381
|
+
const state = {
|
|
382
|
+
cursor: existing?.cursor ? {...existing.cursor, visible: true} : null,
|
|
383
|
+
isVisible: true,
|
|
384
|
+
sessionId: CURSOR_SESSION_ID,
|
|
385
|
+
turnId: CURSOR_TURN_ID,
|
|
386
|
+
};
|
|
387
|
+
cursorStates.set(tabId, state);
|
|
388
|
+
if (!canMessageTabs()) return;
|
|
389
|
+
if (!(await prepareContentScript(tabId))) return;
|
|
390
|
+
const delivered = await withTimeout(chrome.tabs.sendMessage(tabId, {type: "AGENT_CURSOR_STATE", state}), 400);
|
|
391
|
+
if (!delivered) contentScriptReadyTabs.delete(tabId);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/** @param {number} tabId @returns {Promise<void>} */
|
|
395
|
+
async function hideTabCursor(tabId) {
|
|
396
|
+
const existing = cursorStates.get(tabId);
|
|
397
|
+
const state = {
|
|
398
|
+
cursor: existing?.cursor ? {...existing.cursor, visible: false} : null,
|
|
399
|
+
isVisible: false,
|
|
400
|
+
sessionId: null,
|
|
401
|
+
turnId: null,
|
|
402
|
+
};
|
|
403
|
+
cursorStates.set(tabId, state);
|
|
404
|
+
if (!canMessageTabs()) return;
|
|
405
|
+
await withTimeout(chrome.tabs.sendMessage(tabId, {type: "AGENT_CURSOR_STATE", state}), 350);
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* @param {number} tabId
|
|
410
|
+
* @param {number} x
|
|
411
|
+
* @param {number} y
|
|
412
|
+
* @param {{visible?:boolean, animate?:boolean, waitForArrival?:boolean}} [options]
|
|
413
|
+
* @returns {Promise<void>}
|
|
414
|
+
*/
|
|
415
|
+
async function updateCursorPosition(tabId, x, y, {visible = true, animate = true, waitForArrival = false} = {}) {
|
|
416
|
+
if (cursorMode === "off" || !Number.isFinite(x) || !Number.isFinite(y)) return;
|
|
417
|
+
const prev = cursorStates.get(tabId)?.cursor;
|
|
418
|
+
const targetX = Math.round(x);
|
|
419
|
+
const targetY = Math.round(y);
|
|
420
|
+
const dist = prev && Number.isFinite(prev.x) && Number.isFinite(prev.y)
|
|
421
|
+
? Math.hypot(targetX - prev.x, targetY - prev.y)
|
|
422
|
+
: 999;
|
|
423
|
+
const seq = ++moveSeq;
|
|
424
|
+
const state = {
|
|
425
|
+
cursor: {
|
|
426
|
+
x: targetX,
|
|
427
|
+
y: targetY,
|
|
428
|
+
visible,
|
|
429
|
+
animateMovement: animate,
|
|
430
|
+
moveSequence: seq,
|
|
431
|
+
},
|
|
432
|
+
isVisible: visible,
|
|
433
|
+
sessionId: visible ? CURSOR_SESSION_ID : null,
|
|
434
|
+
turnId: visible ? CURSOR_TURN_ID : null,
|
|
435
|
+
};
|
|
436
|
+
cursorStates.set(tabId, state);
|
|
437
|
+
if (!canMessageTabs()) return;
|
|
438
|
+
const effectiveWait = cursorMode === "smooth" && waitForArrival && visible && animate && dist >= 4;
|
|
439
|
+
if (contentScriptReadyTabs.has(tabId) && !effectiveWait) {
|
|
440
|
+
try {
|
|
441
|
+
const res = chrome.tabs.sendMessage(tabId, {type: "AGENT_CURSOR_STATE", state});
|
|
442
|
+
if (res && typeof res.catch === "function") {
|
|
443
|
+
void res.catch(() => contentScriptReadyTabs.delete(tabId));
|
|
444
|
+
}
|
|
445
|
+
} catch {
|
|
446
|
+
contentScriptReadyTabs.delete(tabId);
|
|
447
|
+
}
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
if (!(await prepareContentScript(tabId))) return;
|
|
451
|
+
|
|
452
|
+
let arrivalPromise = null;
|
|
453
|
+
if (effectiveWait && typeof setTimeout === "function") {
|
|
454
|
+
arrivalPromise = new Promise((resolve) => {
|
|
455
|
+
const timer = setTimeout(() => {
|
|
456
|
+
cursorArrivalWaiters.delete(seq);
|
|
457
|
+
resolve();
|
|
458
|
+
}, 180);
|
|
459
|
+
cursorArrivalWaiters.set(seq, () => {
|
|
460
|
+
if (typeof clearTimeout === "function") clearTimeout(timer);
|
|
461
|
+
cursorArrivalWaiters.delete(seq);
|
|
462
|
+
resolve();
|
|
463
|
+
});
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
const delivered = await withTimeout(chrome.tabs.sendMessage(tabId, {type: "AGENT_CURSOR_STATE", state}), 400);
|
|
468
|
+
if (!delivered) contentScriptReadyTabs.delete(tabId);
|
|
469
|
+
if (arrivalPromise && delivered?.ok === true) {
|
|
470
|
+
await arrivalPromise;
|
|
471
|
+
} else if (arrivalPromise) {
|
|
472
|
+
cursorArrivalWaiters.get(seq)?.();
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/** @param {number} tabId @returns {Promise<void>} */
|
|
477
|
+
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);
|
|
497
|
+
}
|
|
498
|
+
} else {
|
|
499
|
+
await showTabCursor(tabId);
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/** @returns {Promise<void>} */
|
|
505
|
+
async function cleanupStaleVisuals() {
|
|
506
|
+
if (!canMessageTabs() || typeof chrome.tabs?.query !== "function") return;
|
|
507
|
+
try {
|
|
508
|
+
const tabs = await chrome.tabs.query({});
|
|
509
|
+
if (!Array.isArray(tabs)) return;
|
|
510
|
+
await Promise.allSettled(tabs.map(async (tab) => {
|
|
511
|
+
if (!Number.isSafeInteger(tab?.id) || attached.has(tab.id) || badgeStates.has(tab.id)) return;
|
|
512
|
+
const candidateUrl = tab.url || tab.pendingUrl || "";
|
|
513
|
+
if (!isControllableTabUrl(candidateUrl)) return;
|
|
514
|
+
await withTimeout(chrome.tabs.sendMessage(tab.id, {
|
|
515
|
+
type: "TAB_FAVICON_BADGE",
|
|
516
|
+
badge: null,
|
|
517
|
+
faviconDataUrl: null,
|
|
518
|
+
}), 250);
|
|
519
|
+
await withTimeout(chrome.tabs.sendMessage(tab.id, {
|
|
520
|
+
type: "AGENT_CURSOR_STATE",
|
|
521
|
+
state: {cursor: null, isVisible: false, sessionId: null, turnId: null},
|
|
522
|
+
}), 250);
|
|
523
|
+
}));
|
|
524
|
+
} catch {
|
|
525
|
+
// Best-effort cleanup on startup/reconnect.
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/** @param {any} msg @param {chrome.runtime.MessageSender} sender @param {(response?: any) => void} sendResponse */
|
|
530
|
+
function onRuntimeMessage(msg, sender, sendResponse) {
|
|
531
|
+
if (msg?.type === "GET_AGENT_CURSOR_STATE") {
|
|
532
|
+
const tabId = sender?.tab?.id;
|
|
533
|
+
const state = (Number.isSafeInteger(tabId) && cursorStates.get(tabId)) || {
|
|
534
|
+
cursor: null,
|
|
535
|
+
isVisible: false,
|
|
536
|
+
sessionId: null,
|
|
537
|
+
turnId: null,
|
|
538
|
+
};
|
|
539
|
+
sendResponse({ok: true, state});
|
|
540
|
+
return true;
|
|
541
|
+
}
|
|
542
|
+
if (msg?.type === "AGENT_CURSOR_ARRIVED") {
|
|
543
|
+
if (Number.isInteger(msg.moveSequence)) {
|
|
544
|
+
cursorArrivalWaiters.get(msg.moveSequence)?.();
|
|
545
|
+
}
|
|
546
|
+
sendResponse({ok: true});
|
|
547
|
+
return true;
|
|
548
|
+
}
|
|
549
|
+
return false;
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/** @param {number} tabId @param {chrome.tabs.TabChangeInfo} changeInfo */
|
|
553
|
+
function onTabUpdated(tabId, changeInfo) {
|
|
554
|
+
if (disconnected) return;
|
|
555
|
+
if (changeInfo?.status === "loading" || changeInfo?.url) {
|
|
556
|
+
contentScriptReadyTabs.delete(tabId);
|
|
557
|
+
}
|
|
558
|
+
if (changeInfo?.url || (changeInfo?.favIconUrl && !isBadgedFaviconUrl(changeInfo.favIconUrl))) {
|
|
559
|
+
faviconCache.delete(tabId);
|
|
560
|
+
}
|
|
561
|
+
if (changeInfo?.status === "complete" && (attached.has(tabId) || badgeStates.has(tabId))) {
|
|
562
|
+
void syncTabVisuals(tabId);
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/** @param {{tabId:number, windowId?:number}} activeInfo */
|
|
567
|
+
function onTabActivated(activeInfo) {
|
|
568
|
+
const tabId = activeInfo?.tabId;
|
|
569
|
+
if (Number.isSafeInteger(tabId) && Number.isSafeInteger(activeInfo?.windowId)) {
|
|
570
|
+
const hist = windowActiveHistory.get(activeInfo.windowId) ?? {current: null, previous: null};
|
|
571
|
+
if (hist.current?.tabId !== tabId) {
|
|
572
|
+
windowActiveHistory.set(activeInfo.windowId, {
|
|
573
|
+
current: {tabId, wasUserTab: !owned.has(tabId)},
|
|
574
|
+
previous: hist.current,
|
|
575
|
+
});
|
|
576
|
+
} else {
|
|
577
|
+
hist.current.wasUserTab = !owned.has(tabId);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
if (!Number.isSafeInteger(tabId) || attached.has(tabId)) return;
|
|
581
|
+
const badge = badgeStates.get(tabId);
|
|
582
|
+
if (badge === "deliverable" || badge === "handoff") {
|
|
583
|
+
void updateTabFaviconBadge(tabId, null);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
/** @param {number} id @returns {void} */
|
|
588
|
+
const forget = (id) => {
|
|
589
|
+
owned.delete(id);
|
|
590
|
+
userOwned.delete(id);
|
|
591
|
+
attached.delete(id);
|
|
592
|
+
deliveredAgentTabs.delete(id);
|
|
593
|
+
frames.delete(id);
|
|
594
|
+
downloadWatchers.delete(id);
|
|
595
|
+
cursorStates.delete(id);
|
|
596
|
+
badgeStates.delete(id);
|
|
597
|
+
faviconCache.delete(id);
|
|
598
|
+
preparingContentScripts.delete(id);
|
|
599
|
+
contentScriptReadyTabs.delete(id);
|
|
600
|
+
restoringFocus.delete(id);
|
|
601
|
+
for (const hist of windowActiveHistory.values()) {
|
|
602
|
+
if (hist.current?.tabId === id) hist.current = null;
|
|
603
|
+
if (hist.previous?.tabId === id) hist.previous = null;
|
|
604
|
+
}
|
|
605
|
+
};
|
|
606
|
+
|
|
607
|
+
/** @param {chrome.tabGroups.TabGroup} group @returns {void} */
|
|
608
|
+
function onTabGroupRemoved(group) {
|
|
609
|
+
if (disconnected || !Number.isSafeInteger(group?.id)) return;
|
|
610
|
+
agentGroups.delete(group.id);
|
|
611
|
+
for (const [sid, gid] of sessionGroups) {
|
|
612
|
+
if (gid === group.id) sessionGroups.delete(sid);
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
/** @param {chrome.tabs.Tab} tab @returns {void} */
|
|
616
|
+
function onTabCreated(tab) {
|
|
617
|
+
if (disconnected || !Number.isSafeInteger(tab?.id) || !Number.isSafeInteger(tab?.openerTabId)) return;
|
|
618
|
+
if (!owned.has(tab.openerTabId) || owned.has(tab.id) || tab.incognito === true) return;
|
|
619
|
+
const candidateUrl = tab.url || tab.pendingUrl || "";
|
|
620
|
+
if (!isControllableTabUrl(candidateUrl)) return;
|
|
621
|
+
owned.add(tab.id);
|
|
622
|
+
if (tab.active === true && Number.isSafeInteger(tab.windowId) &&
|
|
623
|
+
typeof chrome.tabs?.update === "function" && !restoringFocus.has(tab.id)) {
|
|
624
|
+
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)) {
|
|
627
|
+
restoringFocus.add(tab.id);
|
|
628
|
+
void Promise.resolve(chrome.tabs.update(candidate.tabId, {active: true}))
|
|
629
|
+
.catch(() => {})
|
|
630
|
+
.finally(() => restoringFocus.delete(tab.id));
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
port.postMessage({
|
|
634
|
+
event: "onTabCreated",
|
|
635
|
+
tabId: tab.openerTabId,
|
|
636
|
+
params: {openerTabId: tab.openerTabId, tab: serializeTab(tab)},
|
|
637
|
+
});
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
chrome.tabs.onRemoved.addListener(forget);
|
|
641
|
+
chrome.tabs.onCreated?.addListener(onTabCreated);
|
|
642
|
+
chrome.tabs.onUpdated?.addListener(onTabUpdated);
|
|
643
|
+
chrome.tabs.onActivated?.addListener(onTabActivated);
|
|
644
|
+
chrome.tabGroups?.onRemoved?.addListener(onTabGroupRemoved);
|
|
645
|
+
chrome.runtime.onMessage?.addListener(onRuntimeMessage);
|
|
646
|
+
|
|
647
|
+
/** @param {number} gid @param {number|null} targetWindowId @returns {Promise<chrome.tabGroups.TabGroup|null>} */
|
|
648
|
+
async function getAliveGroup(gid, targetWindowId) {
|
|
649
|
+
if (!Number.isSafeInteger(gid) || gid < 0) return null;
|
|
650
|
+
if (typeof chrome.tabGroups?.get === "function") {
|
|
651
|
+
const g = await chrome.tabGroups.get(gid).catch(() => null);
|
|
652
|
+
if (!g) return null;
|
|
653
|
+
if (targetWindowId !== null && Number.isSafeInteger(g.windowId) && g.windowId !== targetWindowId) return null;
|
|
654
|
+
return g;
|
|
655
|
+
}
|
|
656
|
+
return {id: gid, collapsed: false};
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
/** @param {{method:string,tabId?:number,details?:{method:string,params:object,childSession?:string,url?:string,tabIds?:number[],title?:string,color?:string,groupId?:number|null,sessionId?:string,collapsed?:boolean,focus?:boolean,ungroupFinished?:boolean,closeDuplicateDeliverables?:boolean,keepTabIds?:number[],status?:string,x?:number,y?:number,waitForArrival?:boolean}}} request @returns {Promise<unknown>} */
|
|
660
|
+
async function handle({method, tabId, details}) {
|
|
661
|
+
if (disconnected) throw new Error("Chrome bridge is disconnected");
|
|
662
|
+
if (method === "createBlankTab") {
|
|
663
|
+
let createOpts = {url: "about:blank", active: false};
|
|
664
|
+
if (typeof chrome.windows?.getLastFocused === "function") {
|
|
665
|
+
const win = await chrome.windows.getLastFocused({windowTypes: ["normal"]}).catch(() => null);
|
|
666
|
+
if (Number.isSafeInteger(win?.id)) createOpts = {...createOpts, windowId: win.id};
|
|
667
|
+
}
|
|
668
|
+
const tab = serializeTab(await chrome.tabs.create(createOpts));
|
|
669
|
+
if (disconnected) {
|
|
670
|
+
await chrome.tabs.remove(tab.id);
|
|
671
|
+
throw new Error("Chrome bridge disconnected during tab creation");
|
|
672
|
+
}
|
|
673
|
+
owned.add(tab.id);
|
|
674
|
+
return tab;
|
|
675
|
+
}
|
|
676
|
+
if (method === "listTabs") {
|
|
677
|
+
if (typeof chrome.tabs?.query !== "function") {
|
|
678
|
+
const fallback = [];
|
|
679
|
+
for (const id of owned) {
|
|
680
|
+
try {
|
|
681
|
+
const tab = await chrome.tabs.get(id);
|
|
682
|
+
if (tab) fallback.push({...serializeTab(tab), owned: true, origin: userOwned.has(id) ? "user" : "agent"});
|
|
683
|
+
} catch {
|
|
684
|
+
// Skip closed tabs.
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
return fallback;
|
|
688
|
+
}
|
|
689
|
+
const tabs = await chrome.tabs.query({});
|
|
690
|
+
const out = [];
|
|
691
|
+
for (const tab of Array.isArray(tabs) ? tabs : []) {
|
|
692
|
+
if (!Number.isSafeInteger(tab?.id) || tab.incognito === true) continue;
|
|
693
|
+
const candidateUrl = tab.url || tab.pendingUrl || "";
|
|
694
|
+
if (!isControllableTabUrl(candidateUrl)) continue;
|
|
695
|
+
out.push({
|
|
696
|
+
...serializeTab(tab),
|
|
697
|
+
owned: owned.has(tab.id),
|
|
698
|
+
origin: userOwned.has(tab.id) ? "user" : (owned.has(tab.id) ? "agent" : "user"),
|
|
699
|
+
});
|
|
700
|
+
}
|
|
701
|
+
return out;
|
|
702
|
+
}
|
|
703
|
+
if (method === "claimTab") {
|
|
704
|
+
if (!Number.isSafeInteger(tabId) || typeof chrome.tabs?.get !== "function") {
|
|
705
|
+
throw new Error("Chrome tab is unavailable");
|
|
706
|
+
}
|
|
707
|
+
const tab = await chrome.tabs.get(tabId);
|
|
708
|
+
if (!tab || !Number.isSafeInteger(tab.id) || tab.incognito === true) {
|
|
709
|
+
throw new Error("Chrome tab is unavailable");
|
|
710
|
+
}
|
|
711
|
+
const candidateUrl = tab.url || tab.pendingUrl || "";
|
|
712
|
+
if (!isControllableTabUrl(candidateUrl)) {
|
|
713
|
+
throw new Error("Chrome internal tab cannot be claimed");
|
|
714
|
+
}
|
|
715
|
+
if (!owned.has(tab.id)) {
|
|
716
|
+
owned.add(tab.id);
|
|
717
|
+
userOwned.add(tab.id);
|
|
718
|
+
}
|
|
719
|
+
return {
|
|
720
|
+
...serializeTab(tab),
|
|
721
|
+
owned: true,
|
|
722
|
+
origin: userOwned.has(tab.id) ? "user" : "agent",
|
|
723
|
+
};
|
|
724
|
+
}
|
|
725
|
+
if (method === "setConfig") {
|
|
726
|
+
if (details?.cursorMode === "fast" || details?.cursorMode === "smooth" || details?.cursorMode === "off") {
|
|
727
|
+
cursorMode = details.cursorMode;
|
|
728
|
+
}
|
|
729
|
+
return {ok: true, cursorMode};
|
|
730
|
+
}
|
|
731
|
+
if (method === "readTabContext") {
|
|
732
|
+
if (!Number.isSafeInteger(tabId) || typeof chrome.tabs?.get !== "function") {
|
|
733
|
+
throw new Error("Chrome tab is unavailable");
|
|
734
|
+
}
|
|
735
|
+
const tab = await chrome.tabs.get(tabId);
|
|
736
|
+
if (!tab || !Number.isSafeInteger(tab.id) || tab.incognito === true) {
|
|
737
|
+
throw new Error("Chrome tab is unavailable");
|
|
738
|
+
}
|
|
739
|
+
const candidateUrl = tab.url || tab.pendingUrl || "";
|
|
740
|
+
if (!isControllableTabUrl(candidateUrl)) {
|
|
741
|
+
throw new Error("Chrome internal tab cannot be read");
|
|
742
|
+
}
|
|
743
|
+
if (typeof chrome.scripting?.executeScript !== "function") {
|
|
744
|
+
throw new Error("Chrome scripting API is unavailable");
|
|
745
|
+
}
|
|
746
|
+
const format = details?.format === "text" ? "text" : "markdown";
|
|
747
|
+
const maxChars = Number.isFinite(Number(details?.maxChars)) ? Number(details.maxChars) : 16_000;
|
|
748
|
+
const results = await withTimeout(
|
|
749
|
+
chrome.scripting.executeScript({
|
|
750
|
+
target: {tabId: tab.id},
|
|
751
|
+
func: extractPassiveTabContext,
|
|
752
|
+
args: [{format, maxChars}],
|
|
753
|
+
}),
|
|
754
|
+
5000,
|
|
755
|
+
);
|
|
756
|
+
const extracted = Array.isArray(results) ? results[0]?.result : null;
|
|
757
|
+
if (!extracted || typeof extracted !== "object") {
|
|
758
|
+
throw new Error("Failed to extract passive tab context");
|
|
759
|
+
}
|
|
760
|
+
return {
|
|
761
|
+
...extracted,
|
|
762
|
+
title: extracted.title || tab.title || "",
|
|
763
|
+
url: extracted.url || tab.url || "",
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
if (method === "groupTabs") {
|
|
767
|
+
const tabIds = Array.isArray(details?.tabIds) ? details.tabIds : [];
|
|
768
|
+
if (tabIds.length === 0 || tabIds.some((id) => !Number.isSafeInteger(id) || !owned.has(id))) {
|
|
769
|
+
throw new Error("Chrome bridge can only group owned session tabs");
|
|
770
|
+
}
|
|
771
|
+
if (typeof chrome.tabs?.group !== "function") {
|
|
772
|
+
return {groupId: null, supported: false};
|
|
773
|
+
}
|
|
774
|
+
const title = typeof details?.title === "string" ? details.title.trim().slice(0, 80) : "";
|
|
775
|
+
const color = TAB_GROUP_COLORS.has(details?.color) ? details.color : undefined;
|
|
776
|
+
const requestedGroupId = Number.isSafeInteger(details?.groupId) ? details.groupId : null;
|
|
777
|
+
const sessionId = typeof details?.sessionId === "string" ? details.sessionId : null;
|
|
778
|
+
|
|
779
|
+
let targetWindowId = null;
|
|
780
|
+
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;
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
let existingGroup = null;
|
|
786
|
+
if (requestedGroupId !== null) {
|
|
787
|
+
existingGroup = await getAliveGroup(requestedGroupId, targetWindowId);
|
|
788
|
+
}
|
|
789
|
+
if (!existingGroup && sessionId && sessionGroups.has(sessionId)) {
|
|
790
|
+
existingGroup = await getAliveGroup(sessionGroups.get(sessionId), targetWindowId);
|
|
791
|
+
if (!existingGroup) sessionGroups.delete(sessionId);
|
|
792
|
+
}
|
|
793
|
+
if (!existingGroup && title && typeof chrome.tabGroups?.query === "function") {
|
|
794
|
+
const groups = await chrome.tabGroups.query(targetWindowId !== null ? {windowId: targetWindowId} : {}).catch(() => []);
|
|
795
|
+
const want = title.toLowerCase();
|
|
796
|
+
for (const g of Array.isArray(groups) ? groups : []) {
|
|
797
|
+
if ((g?.title || "").trim().toLowerCase() !== want) continue;
|
|
798
|
+
const reservedByOther = [...sessionGroups.entries()].some(([sid, gid]) => gid === g.id && sid !== sessionId);
|
|
799
|
+
if (!reservedByOther) {
|
|
800
|
+
existingGroup = g;
|
|
801
|
+
break;
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
const targetGroupId = existingGroup ? existingGroup.id : null;
|
|
807
|
+
let groupId;
|
|
808
|
+
if (targetGroupId !== null) {
|
|
809
|
+
try {
|
|
810
|
+
groupId = await chrome.tabs.group({groupId: targetGroupId, tabIds});
|
|
811
|
+
} catch {
|
|
812
|
+
groupId = await chrome.tabs.group({tabIds});
|
|
813
|
+
}
|
|
814
|
+
} else {
|
|
815
|
+
groupId = await chrome.tabs.group({tabIds});
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
if (Number.isSafeInteger(groupId)) {
|
|
819
|
+
agentGroups.add(groupId);
|
|
820
|
+
if (sessionId) sessionGroups.set(sessionId, groupId);
|
|
821
|
+
if (typeof chrome.tabGroups?.update === "function") {
|
|
822
|
+
const updateProps = {};
|
|
823
|
+
if (title) updateProps.title = title;
|
|
824
|
+
if (color) updateProps.color = color;
|
|
825
|
+
if (typeof details?.collapsed === "boolean") {
|
|
826
|
+
updateProps.collapsed = details.collapsed;
|
|
827
|
+
} else {
|
|
828
|
+
const reusedSame = Boolean(existingGroup && groupId === existingGroup.id);
|
|
829
|
+
if (reusedSame && existingGroup.collapsed === true) {
|
|
830
|
+
updateProps.collapsed = false;
|
|
831
|
+
} else if (!reusedSame && typeof chrome.tabGroups?.get === "function") {
|
|
832
|
+
const created = await chrome.tabGroups.get(groupId).catch(() => null);
|
|
833
|
+
if (created?.collapsed === true) updateProps.collapsed = false;
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
if (Object.keys(updateProps).length > 0) {
|
|
837
|
+
await chrome.tabGroups.update(groupId, updateProps).catch(() => {});
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
return {groupId: Number.isSafeInteger(groupId) ? groupId : null, supported: true};
|
|
842
|
+
}
|
|
843
|
+
if (method === "ungroupTabs") {
|
|
844
|
+
const tabIds = Array.isArray(details?.tabIds) ? details.tabIds : [];
|
|
845
|
+
if (tabIds.length === 0 || tabIds.some((id) => !Number.isSafeInteger(id) || (!owned.has(id) && !deliveredAgentTabs.has(id)))) {
|
|
846
|
+
throw new Error("Chrome bridge can only ungroup owned session tabs");
|
|
847
|
+
}
|
|
848
|
+
if (typeof chrome.tabs?.ungroup !== "function") {
|
|
849
|
+
return {ok: true, ungrouped: 0, supported: false};
|
|
850
|
+
}
|
|
851
|
+
await chrome.tabs.ungroup(tabIds).catch(() => {});
|
|
852
|
+
for (const id of tabIds) {
|
|
853
|
+
const meta = deliveredAgentTabs.get(id);
|
|
854
|
+
if (meta) meta.groupId = null;
|
|
855
|
+
}
|
|
856
|
+
return {ok: true, ungrouped: tabIds.length, supported: true};
|
|
857
|
+
}
|
|
858
|
+
if (method === "listTabGroups") {
|
|
859
|
+
if (typeof chrome.tabGroups?.query !== "function") return [];
|
|
860
|
+
const [groups, tabs] = await Promise.all([
|
|
861
|
+
chrome.tabGroups.query({}).catch(() => []),
|
|
862
|
+
typeof chrome.tabs?.query === "function" ? chrome.tabs.query({}).catch(() => []) : [],
|
|
863
|
+
]);
|
|
864
|
+
const counts = new Map();
|
|
865
|
+
for (const t of Array.isArray(tabs) ? tabs : []) {
|
|
866
|
+
if (Number.isSafeInteger(t?.groupId) && t.groupId >= 0) {
|
|
867
|
+
counts.set(t.groupId, (counts.get(t.groupId) ?? 0) + 1);
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
return (Array.isArray(groups) ? groups : []).map((g) => ({
|
|
871
|
+
id: g.id,
|
|
872
|
+
title: g.title || "",
|
|
873
|
+
color: g.color || "grey",
|
|
874
|
+
collapsed: Boolean(g.collapsed),
|
|
875
|
+
windowId: g.windowId,
|
|
876
|
+
tabCount: counts.get(g.id) ?? 0,
|
|
877
|
+
agentManaged: agentGroups.has(g.id),
|
|
878
|
+
}));
|
|
879
|
+
}
|
|
880
|
+
if (method === "cleanupGroups") {
|
|
881
|
+
const ungroupFinished = details?.ungroupFinished === true;
|
|
882
|
+
const closeDuplicateDeliverables = details?.closeDuplicateDeliverables !== false;
|
|
883
|
+
const keepSet = new Set(Array.isArray(details?.keepTabIds) ? details.keepTabIds.filter(Number.isSafeInteger) : []);
|
|
884
|
+
let closedTabs = 0;
|
|
885
|
+
let ungroupedTabs = 0;
|
|
886
|
+
if (closeDuplicateDeliverables && deliveredAgentTabs.size > 1) {
|
|
887
|
+
const seen = new Map();
|
|
888
|
+
const entries = [...deliveredAgentTabs.entries()].sort((a, b) => (b[1].createdAt || 0) - (a[1].createdAt || 0));
|
|
889
|
+
for (const [id, meta] of entries) {
|
|
890
|
+
if (!meta?.url || keepSet.has(id) || owned.has(id) || userOwned.has(id)) continue;
|
|
891
|
+
if (seen.has(meta.url)) {
|
|
892
|
+
await chrome.tabs?.remove?.(id).catch(() => {});
|
|
893
|
+
deliveredAgentTabs.delete(id);
|
|
894
|
+
closedTabs += 1;
|
|
895
|
+
} else {
|
|
896
|
+
seen.set(meta.url, id);
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
if (ungroupFinished && typeof chrome.tabs?.query === "function") {
|
|
901
|
+
for (const gid of [...agentGroups]) {
|
|
902
|
+
const tabsInGroup = await chrome.tabs.query({groupId: gid}).catch(() => []);
|
|
903
|
+
if (!Array.isArray(tabsInGroup) || tabsInGroup.length === 0) {
|
|
904
|
+
onTabGroupRemoved({id: gid});
|
|
905
|
+
continue;
|
|
906
|
+
}
|
|
907
|
+
if (tabsInGroup.some((t) => owned.has(t.id))) continue;
|
|
908
|
+
const releasableIds = tabsInGroup.map((t) => t.id).filter((id) => Number.isSafeInteger(id) && !keepSet.has(id));
|
|
909
|
+
if (releasableIds.length > 0 && typeof chrome.tabs?.ungroup === "function") {
|
|
910
|
+
await chrome.tabs.ungroup(releasableIds).catch(() => {});
|
|
911
|
+
ungroupedTabs += releasableIds.length;
|
|
912
|
+
for (const id of releasableIds) {
|
|
913
|
+
const meta = deliveredAgentTabs.get(id);
|
|
914
|
+
if (meta) meta.groupId = null;
|
|
915
|
+
}
|
|
916
|
+
if (releasableIds.length === tabsInGroup.length) onTabGroupRemoved({id: gid});
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
return {ok: true, closedTabs, ungroupedTabs};
|
|
921
|
+
}
|
|
922
|
+
if (!Number.isSafeInteger(tabId) || !owned.has(tabId)) {
|
|
923
|
+
if (method === "readTab") return null;
|
|
924
|
+
if (method === "closeTab" || method === "releaseTab" || method === "markTab" || method === "moveCursor") return null;
|
|
925
|
+
throw new Error("Unknown Chrome bridge request");
|
|
926
|
+
}
|
|
927
|
+
switch (method) {
|
|
928
|
+
case "readTab": return serializeTab(await chrome.tabs.get(tabId));
|
|
929
|
+
case "closeTab":
|
|
930
|
+
await chrome.tabs.remove(tabId);
|
|
931
|
+
forget(tabId);
|
|
932
|
+
return null;
|
|
933
|
+
case "releaseTab":
|
|
934
|
+
if (attached.has(tabId)) {
|
|
935
|
+
await chrome.debugger.detach({tabId}).catch(() => {});
|
|
936
|
+
attached.delete(tabId);
|
|
937
|
+
frames.delete(tabId);
|
|
938
|
+
}
|
|
939
|
+
await hideTabCursor(tabId);
|
|
940
|
+
if (badgeStates.get(tabId) === "active") {
|
|
941
|
+
await updateTabFaviconBadge(tabId, null);
|
|
942
|
+
}
|
|
943
|
+
owned.delete(tabId);
|
|
944
|
+
userOwned.delete(tabId);
|
|
945
|
+
return null;
|
|
946
|
+
case "markTab": {
|
|
947
|
+
const status = details?.status === "deliverable" ? "deliverable" : (details?.status === "handoff" ? "handoff" : null);
|
|
948
|
+
const tab = typeof chrome.tabs?.get === "function" ? await chrome.tabs.get(tabId).catch(() => null) : null;
|
|
949
|
+
if (details?.focus === true) {
|
|
950
|
+
if (tab && Number.isSafeInteger(tab.groupId) && tab.groupId >= 0 && typeof chrome.tabGroups?.update === "function") {
|
|
951
|
+
await chrome.tabGroups.update(tab.groupId, {collapsed: false}).catch(() => {});
|
|
952
|
+
}
|
|
953
|
+
if (typeof chrome.tabs?.update === "function") {
|
|
954
|
+
await chrome.tabs.update(tabId, {active: true}).catch(() => {});
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
if (status) {
|
|
958
|
+
await updateTabFaviconBadge(tabId, status);
|
|
959
|
+
if (status === "deliverable" && !userOwned.has(tabId)) {
|
|
960
|
+
const normUrl = normalizeComparableUrl(tab?.url || tab?.pendingUrl || "");
|
|
961
|
+
if (normUrl) {
|
|
962
|
+
for (const [oldId, meta] of [...deliveredAgentTabs.entries()]) {
|
|
963
|
+
if (oldId !== tabId && !owned.has(oldId) && !userOwned.has(oldId) && meta.url === normUrl) {
|
|
964
|
+
await chrome.tabs?.remove?.(oldId).catch(() => {});
|
|
965
|
+
deliveredAgentTabs.delete(oldId);
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
deliveredAgentTabs.set(tabId, {
|
|
970
|
+
url: normUrl,
|
|
971
|
+
groupId: Number.isSafeInteger(tab?.groupId) && tab.groupId >= 0 ? tab.groupId : null,
|
|
972
|
+
createdAt: Date.now(),
|
|
973
|
+
});
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
return null;
|
|
977
|
+
}
|
|
978
|
+
case "moveCursor":
|
|
979
|
+
if (Number.isFinite(details?.x) && Number.isFinite(details?.y)) {
|
|
980
|
+
await updateCursorPosition(tabId, Number(details.x), Number(details.y), {
|
|
981
|
+
visible: true,
|
|
982
|
+
animate: true,
|
|
983
|
+
waitForArrival: details?.waitForArrival !== false,
|
|
984
|
+
});
|
|
985
|
+
}
|
|
986
|
+
return null;
|
|
987
|
+
case "attach":
|
|
988
|
+
if (!attached.has(tabId)) {
|
|
989
|
+
await chrome.debugger.attach({tabId}, "1.3");
|
|
990
|
+
if (disconnected || !owned.has(tabId)) {
|
|
991
|
+
await chrome.debugger.detach({tabId});
|
|
992
|
+
throw new Error("Chrome bridge lost the tab during debugger attachment");
|
|
993
|
+
}
|
|
994
|
+
attached.add(tabId);
|
|
995
|
+
frames.set(tabId, new Map());
|
|
996
|
+
}
|
|
997
|
+
badgeStates.set(tabId, "active");
|
|
998
|
+
await syncTabVisuals(tabId);
|
|
999
|
+
return null;
|
|
1000
|
+
case "detach":
|
|
1001
|
+
if (attached.has(tabId)) {
|
|
1002
|
+
await chrome.debugger.detach({tabId});
|
|
1003
|
+
attached.delete(tabId);
|
|
1004
|
+
frames.delete(tabId);
|
|
1005
|
+
}
|
|
1006
|
+
await hideTabCursor(tabId);
|
|
1007
|
+
if (badgeStates.get(tabId) === "active") {
|
|
1008
|
+
await updateTabFaviconBadge(tabId, null);
|
|
1009
|
+
}
|
|
1010
|
+
return null;
|
|
1011
|
+
case "navigate":
|
|
1012
|
+
if (typeof details?.url !== "string") throw new Error("Chrome bridge navigation requires a URL");
|
|
1013
|
+
await chrome.tabs.update(tabId, {url: details.url});
|
|
1014
|
+
return null;
|
|
1015
|
+
case "watchDownloads":
|
|
1016
|
+
downloadWatchers.set(tabId, {startedAt: Date.now()});
|
|
1017
|
+
return null;
|
|
1018
|
+
case "unwatchDownloads":
|
|
1019
|
+
downloadWatchers.delete(tabId);
|
|
1020
|
+
return null;
|
|
1021
|
+
case "execute": {
|
|
1022
|
+
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");
|
|
1026
|
+
}
|
|
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
|
+
}
|
|
1074
|
+
}
|
|
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
|
+
});
|
|
1091
|
+
} else {
|
|
1092
|
+
void updateCursorPosition(tabId, Number(val.x), Number(val.y), {
|
|
1093
|
+
visible: true,
|
|
1094
|
+
animate: true,
|
|
1095
|
+
waitForArrival: false,
|
|
1096
|
+
});
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
return result;
|
|
1101
|
+
}
|
|
1102
|
+
default: throw new Error("Unknown Chrome bridge request");
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
/** @param {Map<string,{parentId:string|null,targetId:string}>} tree @param {string} id @returns {void} */
|
|
1107
|
+
function dropFrame(tree, id) {
|
|
1108
|
+
if (!tree.delete(id)) return;
|
|
1109
|
+
for (const [child, frame] of tree) {
|
|
1110
|
+
if (frame.parentId === id) dropFrame(tree, child);
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
/** @param {chrome.debugger.DebuggerSession} source @param {string} method @param {object} params @returns {void} */
|
|
1115
|
+
function onDebuggerEvent(source, method, params) {
|
|
1116
|
+
const {tabId, sessionId} = source;
|
|
1117
|
+
const tree = frames.get(tabId);
|
|
1118
|
+
if (disconnected || !tree || (sessionId !== undefined && !tree.has(sessionId))) return;
|
|
1119
|
+
if (method === "Target.attachedToTarget") {
|
|
1120
|
+
if (params?.targetInfo?.type !== "iframe" || typeof params.sessionId !== "string" ||
|
|
1121
|
+
typeof params.targetInfo.targetId !== "string") return;
|
|
1122
|
+
tree.set(params.sessionId, {parentId: sessionId ?? null, targetId: params.targetInfo.targetId});
|
|
1123
|
+
} else if (method === "Target.detachedFromTarget") {
|
|
1124
|
+
if (!tree.has(params?.sessionId)) return;
|
|
1125
|
+
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)) {
|
|
1130
|
+
return;
|
|
1131
|
+
}
|
|
1132
|
+
if (sessionId === undefined && (method === "Page.frameStartedLoading" ||
|
|
1133
|
+
(method === "Page.frameNavigated" && !params?.frame?.parentId))) {
|
|
1134
|
+
contentScriptReadyTabs.delete(tabId);
|
|
1135
|
+
}
|
|
1136
|
+
if (method === "Page.loadEventFired" && sessionId === undefined && attached.has(tabId)) {
|
|
1137
|
+
void syncTabVisuals(tabId);
|
|
1138
|
+
}
|
|
1139
|
+
if (method === "Page.frameDetached" && params?.reason === "swap") {
|
|
1140
|
+
// The renderer lost its local frame. A debugger session for the same
|
|
1141
|
+
// frame is already attached, and will signal its own detach separately.
|
|
1142
|
+
for (const frame of tree.values()) {
|
|
1143
|
+
if (frame.parentId === (sessionId ?? null) && frame.targetId === params.frameId) return;
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
let outgoingParams = params;
|
|
1147
|
+
if (method === "Network.requestWillBeSent") {
|
|
1148
|
+
outgoingParams = {
|
|
1149
|
+
requestId: params?.requestId,
|
|
1150
|
+
loaderId: params?.loaderId,
|
|
1151
|
+
documentURL: params?.documentURL,
|
|
1152
|
+
frameId: params?.frameId,
|
|
1153
|
+
type: params?.type,
|
|
1154
|
+
timestamp: params?.timestamp,
|
|
1155
|
+
request: params?.request ? {url: params.request.url, method: params.request.method} : undefined,
|
|
1156
|
+
};
|
|
1157
|
+
} else if (method === "Network.responseReceived") {
|
|
1158
|
+
outgoingParams = {
|
|
1159
|
+
requestId: params?.requestId,
|
|
1160
|
+
loaderId: params?.loaderId,
|
|
1161
|
+
frameId: params?.frameId,
|
|
1162
|
+
type: params?.type,
|
|
1163
|
+
timestamp: params?.timestamp,
|
|
1164
|
+
response: params?.response ? {
|
|
1165
|
+
url: params.response.url,
|
|
1166
|
+
status: params.response.status,
|
|
1167
|
+
statusText: params.response.statusText,
|
|
1168
|
+
mimeType: params.response.mimeType,
|
|
1169
|
+
fromDiskCache: params.response.fromDiskCache,
|
|
1170
|
+
fromServiceWorker: params.response.fromServiceWorker,
|
|
1171
|
+
} : undefined,
|
|
1172
|
+
};
|
|
1173
|
+
}
|
|
1174
|
+
const event = {event: "onCDPEvent", tabId, params: {source: {tabId, sessionId}, method, params: outgoingParams}};
|
|
1175
|
+
if (COMPACT_EVENTS.has(method) || JSON.stringify(event).length < 256 * 1024) {
|
|
1176
|
+
port.postMessage(event);
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1180
|
+
/** @param {string} method @param {{id:number,url?:string,filename?:string,state?:string,error?:string}} payload @returns {void} */
|
|
1181
|
+
function emitDownloadEvent(method, payload) {
|
|
1182
|
+
if (disconnected || downloadWatchers.size === 0) return;
|
|
1183
|
+
for (const tabId of downloadWatchers.keys()) {
|
|
1184
|
+
if (!owned.has(tabId)) continue;
|
|
1185
|
+
port.postMessage({
|
|
1186
|
+
event: "onCDPEvent",
|
|
1187
|
+
tabId,
|
|
1188
|
+
params: {source: {tabId}, method, params: payload},
|
|
1189
|
+
});
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
|
|
1193
|
+
/** @param {chrome.downloads.DownloadItem} item @returns {void} */
|
|
1194
|
+
function onDownloadCreated(item) {
|
|
1195
|
+
if (disconnected || downloadWatchers.size === 0 || !Number.isSafeInteger(item?.id)) return;
|
|
1196
|
+
const entry = {
|
|
1197
|
+
id: item.id,
|
|
1198
|
+
url: item.finalUrl || item.url || undefined,
|
|
1199
|
+
filename: item.filename || undefined,
|
|
1200
|
+
state: item.state || "in_progress",
|
|
1201
|
+
error: item.error || undefined,
|
|
1202
|
+
};
|
|
1203
|
+
if (entry.state === "complete" || entry.state === "interrupted") {
|
|
1204
|
+
trackedDownloads.delete(item.id);
|
|
1205
|
+
} else {
|
|
1206
|
+
trackedDownloads.set(item.id, entry);
|
|
1207
|
+
}
|
|
1208
|
+
emitDownloadEvent("Bridge.downloadCreated", entry);
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
/** @param {chrome.downloads.DownloadDelta} delta @returns {void} */
|
|
1212
|
+
function onDownloadChanged(delta) {
|
|
1213
|
+
if (disconnected || downloadWatchers.size === 0 || !Number.isSafeInteger(delta?.id)) return;
|
|
1214
|
+
const existing = trackedDownloads.get(delta.id);
|
|
1215
|
+
if (!existing) return;
|
|
1216
|
+
const updated = {
|
|
1217
|
+
id: delta.id,
|
|
1218
|
+
url: delta.url?.current ?? existing.url,
|
|
1219
|
+
filename: delta.filename?.current ?? existing.filename,
|
|
1220
|
+
state: delta.state?.current ?? existing.state,
|
|
1221
|
+
error: delta.error?.current ?? existing.error,
|
|
1222
|
+
};
|
|
1223
|
+
if (updated.state === "complete" || updated.state === "interrupted") {
|
|
1224
|
+
trackedDownloads.delete(delta.id);
|
|
1225
|
+
} else {
|
|
1226
|
+
trackedDownloads.set(delta.id, updated);
|
|
1227
|
+
}
|
|
1228
|
+
emitDownloadEvent("Bridge.downloadChanged", updated);
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
/** @param {chrome.debugger.Debuggee} source @param {string} reason @returns {void} */
|
|
1232
|
+
function onDebuggerDetach(source, reason) {
|
|
1233
|
+
frames.delete(source.tabId);
|
|
1234
|
+
if (Number.isSafeInteger(source.tabId)) {
|
|
1235
|
+
if (activeVisualTabId === source.tabId) activeVisualTabId = null;
|
|
1236
|
+
void hideTabCursor(source.tabId);
|
|
1237
|
+
if (badgeStates.get(source.tabId) === "active") {
|
|
1238
|
+
void updateTabFaviconBadge(source.tabId, null);
|
|
1239
|
+
}
|
|
1240
|
+
if (reason === "canceled_by_user" && userOwned.has(source.tabId)) {
|
|
1241
|
+
owned.delete(source.tabId);
|
|
1242
|
+
userOwned.delete(source.tabId);
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
if (!attached.delete(source.tabId) || disconnected) return;
|
|
1246
|
+
port.postMessage({event: "onCDPDetach", tabId: source.tabId, params: {tabId: source.tabId, reason}});
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
chrome.debugger.onEvent.addListener(onDebuggerEvent);
|
|
1250
|
+
chrome.debugger.onDetach.addListener(onDebuggerDetach);
|
|
1251
|
+
chrome.downloads?.onCreated?.addListener(onDownloadCreated);
|
|
1252
|
+
chrome.downloads?.onChanged?.addListener(onDownloadChanged);
|
|
1253
|
+
|
|
1254
|
+
/** @returns {void} */
|
|
1255
|
+
function onDisconnect() {
|
|
1256
|
+
if (disconnected) return;
|
|
1257
|
+
disconnected = true;
|
|
1258
|
+
const error = chrome.runtime.lastError?.message;
|
|
1259
|
+
if (error) console.warn("Portable Browser Bridge:", error);
|
|
1260
|
+
disconnectActive = null;
|
|
1261
|
+
void chrome.action.setBadgeText({text: manualDisconnect ? "OFF" : ""});
|
|
1262
|
+
void chrome.action.setTitle?.({title: "Portable Browser Bridge (Disconnected — click to connect)"});
|
|
1263
|
+
chrome.tabs.onRemoved.removeListener(forget);
|
|
1264
|
+
chrome.tabs.onCreated?.removeListener(onTabCreated);
|
|
1265
|
+
chrome.tabs.onUpdated?.removeListener(onTabUpdated);
|
|
1266
|
+
chrome.tabs.onActivated?.removeListener(onTabActivated);
|
|
1267
|
+
chrome.tabGroups?.onRemoved?.removeListener(onTabGroupRemoved);
|
|
1268
|
+
chrome.runtime.onMessage?.removeListener(onRuntimeMessage);
|
|
1269
|
+
chrome.debugger.onEvent.removeListener(onDebuggerEvent);
|
|
1270
|
+
chrome.debugger.onDetach.removeListener(onDebuggerDetach);
|
|
1271
|
+
chrome.downloads?.onCreated?.removeListener(onDownloadCreated);
|
|
1272
|
+
chrome.downloads?.onChanged?.removeListener(onDownloadChanged);
|
|
1273
|
+
downloadWatchers.clear();
|
|
1274
|
+
trackedDownloads.clear();
|
|
1275
|
+
for (const waiter of cursorArrivalWaiters.values()) waiter();
|
|
1276
|
+
cursorArrivalWaiters.clear();
|
|
1277
|
+
const closing = [...owned].filter((id) => !userOwned.has(id));
|
|
1278
|
+
const releasing = [...userOwned];
|
|
1279
|
+
const currentlyAttached = [...attached];
|
|
1280
|
+
owned.clear();
|
|
1281
|
+
userOwned.clear();
|
|
1282
|
+
attached.clear();
|
|
1283
|
+
frames.clear();
|
|
1284
|
+
for (const id of releasing) {
|
|
1285
|
+
if (currentlyAttached.includes(id)) {
|
|
1286
|
+
void chrome.debugger.detach({tabId: id}).catch(() => {});
|
|
1287
|
+
}
|
|
1288
|
+
void hideTabCursor(id);
|
|
1289
|
+
void updateTabFaviconBadge(id, null);
|
|
1290
|
+
}
|
|
1291
|
+
cursorStates.clear();
|
|
1292
|
+
badgeStates.clear();
|
|
1293
|
+
faviconCache.clear();
|
|
1294
|
+
preparingContentScripts.clear();
|
|
1295
|
+
contentScriptReadyTabs.clear();
|
|
1296
|
+
windowActiveHistory.clear();
|
|
1297
|
+
restoringFocus.clear();
|
|
1298
|
+
agentGroups.clear();
|
|
1299
|
+
sessionGroups.clear();
|
|
1300
|
+
deliveredAgentTabs.clear();
|
|
1301
|
+
void Promise.allSettled(closing.map((id) => chrome.tabs.remove(id))).then((results) => {
|
|
1302
|
+
for (const result of results) {
|
|
1303
|
+
if (result.status === "rejected") console.warn("Portable Browser Bridge tab cleanup:", result.reason);
|
|
1304
|
+
}
|
|
1305
|
+
});
|
|
1306
|
+
if (!manualDisconnect && chrome.runtime?.id && typeof setTimeout === "function" && reconnectAttempts < 5) {
|
|
1307
|
+
const delayMs = Math.min(10_000, 1_500 * (2 ** reconnectAttempts));
|
|
1308
|
+
reconnectAttempts += 1;
|
|
1309
|
+
if (reconnectTimer) clearTimeout(reconnectTimer);
|
|
1310
|
+
reconnectTimer = setTimeout(() => {
|
|
1311
|
+
reconnectTimer = null;
|
|
1312
|
+
if (!disconnectActive && !manualDisconnect) connect();
|
|
1313
|
+
}, delayMs);
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
port.onMessage.addListener(async (request) => {
|
|
1318
|
+
if (!Number.isSafeInteger(request?.id)) return;
|
|
1319
|
+
reconnectAttempts = 0;
|
|
1320
|
+
let reply;
|
|
1321
|
+
try { reply = {id: request.id, ok: true, value: await handle(request)}; }
|
|
1322
|
+
catch (error) { reply = {id: request.id, ok: false, error: error.message}; }
|
|
1323
|
+
if (disconnected) return;
|
|
1324
|
+
const val = reply.value;
|
|
1325
|
+
if (!reply.ok || val === null || val === undefined || typeof val === "boolean" || typeof val === "number") {
|
|
1326
|
+
port.postMessage(reply);
|
|
1327
|
+
return;
|
|
1328
|
+
}
|
|
1329
|
+
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) {
|
|
1333
|
+
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)});
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
});
|
|
1341
|
+
port.onDisconnect.addListener(onDisconnect);
|
|
1342
|
+
disconnectActive = () => {
|
|
1343
|
+
onDisconnect();
|
|
1344
|
+
port.disconnect();
|
|
1345
|
+
};
|
|
1346
|
+
void chrome.action.setBadgeText({text: ""});
|
|
1347
|
+
void chrome.action.setTitle?.({title: "Portable Browser Bridge (Connected)"});
|
|
1348
|
+
void cleanupStaleVisuals();
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
chrome.action.onClicked.addListener(() => {
|
|
1352
|
+
if (disconnectActive) {
|
|
1353
|
+
manualDisconnect = true;
|
|
1354
|
+
if (reconnectTimer) {
|
|
1355
|
+
clearTimeout(reconnectTimer);
|
|
1356
|
+
reconnectTimer = null;
|
|
1357
|
+
}
|
|
1358
|
+
disconnectActive();
|
|
1359
|
+
} else {
|
|
1360
|
+
manualDisconnect = false;
|
|
1361
|
+
reconnectAttempts = 0;
|
|
1362
|
+
connect();
|
|
1363
|
+
}
|
|
1364
|
+
});
|
|
1365
|
+
|
|
1366
|
+
const autoConnect = () => {
|
|
1367
|
+
if (!disconnectActive && !manualDisconnect) {
|
|
1368
|
+
if (reconnectTimer) {
|
|
1369
|
+
clearTimeout(reconnectTimer);
|
|
1370
|
+
reconnectTimer = null;
|
|
1371
|
+
}
|
|
1372
|
+
connect();
|
|
1373
|
+
}
|
|
1374
|
+
};
|
|
1375
|
+
|
|
1376
|
+
const resetAndAutoConnect = () => {
|
|
1377
|
+
manualDisconnect = false;
|
|
1378
|
+
reconnectAttempts = 0;
|
|
1379
|
+
autoConnect();
|
|
1380
|
+
};
|
|
1381
|
+
|
|
1382
|
+
chrome.runtime.onInstalled?.addListener(resetAndAutoConnect);
|
|
1383
|
+
chrome.runtime.onStartup?.addListener(resetAndAutoConnect);
|
|
1384
|
+
if (chrome.runtime?.id) autoConnect();
|