claude-chrome-android 1.2.2 → 1.4.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.
- package/README.md +25 -0
- package/dist/claude-code-bridge.crx +0 -0
- package/dist/cli.js +248 -157
- package/dist/edge-claude-ext/background.js +1492 -0
- package/dist/edge-claude-ext/content.js +1044 -0
- package/dist/edge-claude-ext/icon128.png +0 -0
- package/dist/edge-claude-ext/icon16.png +0 -0
- package/dist/edge-claude-ext/icon48.png +0 -0
- package/dist/edge-claude-ext/launcher.html +63 -0
- package/dist/edge-claude-ext/launcher.js +98 -0
- package/dist/edge-claude-ext/manifest.json +35 -0
- package/dist/edge-claude-ext/popup.html +444 -0
- package/dist/edge-claude-ext/popup.js +637 -0
- package/package.json +3 -2
|
@@ -0,0 +1,1492 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Claude Code Browser Bridge — Service Worker (background.js)
|
|
3
|
+
*
|
|
4
|
+
* Maintains a WebSocket connection to the local bridge server
|
|
5
|
+
* (ws://127.0.0.1:18963) and handles tool requests from Claude Code
|
|
6
|
+
* by dispatching them to content scripts or using chrome.* APIs.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
// --- Configuration -----------------------------------------------------------
|
|
10
|
+
|
|
11
|
+
const EXT_VERSION = chrome.runtime.getManifest().version;
|
|
12
|
+
const WS_URL = "ws://127.0.0.1:18963/ws";
|
|
13
|
+
const BRIDGE_HEALTH_URL = "http://127.0.0.1:18963/health";
|
|
14
|
+
const RECONNECT_BASE_MS = 1000;
|
|
15
|
+
const RECONNECT_MAX_MS = 30000;
|
|
16
|
+
const KEEPALIVE_INTERVAL_MS = 20000;
|
|
17
|
+
const SCRIPTING_TIMEOUT_MS = 10000;
|
|
18
|
+
const CONTENT_SCRIPT_TIMEOUT_MS = 30000;
|
|
19
|
+
|
|
20
|
+
// --- State -------------------------------------------------------------------
|
|
21
|
+
|
|
22
|
+
/** @type {WebSocket|null} */
|
|
23
|
+
let ws = null;
|
|
24
|
+
let reconnectAttempts = 0;
|
|
25
|
+
let reconnectTimer = null;
|
|
26
|
+
let keepaliveTimer = null;
|
|
27
|
+
let missedPongs = 0;
|
|
28
|
+
let connectionState = "disconnected"; // disconnected | connecting | connected
|
|
29
|
+
|
|
30
|
+
// MCP tab group tracking
|
|
31
|
+
let mcpTabGroup = new Map(); // tabId -> tab info
|
|
32
|
+
|
|
33
|
+
// Message log ring buffer for popup diagnostics
|
|
34
|
+
const messageLog = [];
|
|
35
|
+
const MAX_LOG_ENTRIES = 50;
|
|
36
|
+
|
|
37
|
+
// Stats
|
|
38
|
+
const stats = {
|
|
39
|
+
connectedAt: null,
|
|
40
|
+
toolRequestsReceived: 0,
|
|
41
|
+
toolResponsesSent: 0,
|
|
42
|
+
toolErrors: 0,
|
|
43
|
+
reconnects: 0,
|
|
44
|
+
lastToolName: null,
|
|
45
|
+
lastToolTime: null,
|
|
46
|
+
wsMessagesSent: 0,
|
|
47
|
+
wsMessagesReceived: 0,
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
// --- Logging -----------------------------------------------------------------
|
|
51
|
+
|
|
52
|
+
function addLog(level, msg, data) {
|
|
53
|
+
const entry = {
|
|
54
|
+
ts: Date.now(),
|
|
55
|
+
level, // info | warn | error | tool | ws
|
|
56
|
+
msg,
|
|
57
|
+
data: data ? JSON.stringify(data).slice(0, 500) : undefined,
|
|
58
|
+
};
|
|
59
|
+
messageLog.push(entry);
|
|
60
|
+
if (messageLog.length > MAX_LOG_ENTRIES) messageLog.shift();
|
|
61
|
+
|
|
62
|
+
// Also console.log for devtools
|
|
63
|
+
const prefix = `[bridge:${level}]`;
|
|
64
|
+
if (level === "error") console.error(prefix, msg, data || "");
|
|
65
|
+
else console.log(prefix, msg, data || "");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// --- WebSocket Connection ----------------------------------------------------
|
|
69
|
+
|
|
70
|
+
function connect() {
|
|
71
|
+
if (ws && (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING)) {
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
connectionState = "connecting";
|
|
76
|
+
broadcastState();
|
|
77
|
+
addLog("ws", "Connecting to bridge...", { url: WS_URL });
|
|
78
|
+
|
|
79
|
+
try {
|
|
80
|
+
ws = new WebSocket(WS_URL);
|
|
81
|
+
} catch (err) {
|
|
82
|
+
addLog("error", "WebSocket creation failed", { error: err.message });
|
|
83
|
+
scheduleReconnect();
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
ws.onopen = () => {
|
|
88
|
+
connectionState = "connected";
|
|
89
|
+
reconnectAttempts = 0;
|
|
90
|
+
stats.connectedAt = Date.now();
|
|
91
|
+
addLog("ws", `Connected to bridge server (ext v${EXT_VERSION})`);
|
|
92
|
+
broadcastState();
|
|
93
|
+
|
|
94
|
+
sendMessage({ type: "ping" });
|
|
95
|
+
|
|
96
|
+
clearInterval(keepaliveTimer);
|
|
97
|
+
missedPongs = 0;
|
|
98
|
+
keepaliveTimer = setInterval(() => {
|
|
99
|
+
if (ws?.readyState === WebSocket.OPEN) {
|
|
100
|
+
// 2 missed pongs = bridge is unresponsive, force reconnect.
|
|
101
|
+
// Uses counter instead of Date.now() to handle Android doze/sleep gracefully.
|
|
102
|
+
if (missedPongs >= 2) {
|
|
103
|
+
addLog("warn", "Bridge unresponsive (2 missed pongs) — forcing reconnect");
|
|
104
|
+
ws.close(4000, "Pong timeout");
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
missedPongs++;
|
|
108
|
+
sendMessage({ type: "ping" });
|
|
109
|
+
}
|
|
110
|
+
}, KEEPALIVE_INTERVAL_MS);
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
ws.onmessage = (event) => {
|
|
114
|
+
stats.wsMessagesReceived++;
|
|
115
|
+
try {
|
|
116
|
+
const msg = JSON.parse(event.data);
|
|
117
|
+
handleBridgeMessage(msg);
|
|
118
|
+
} catch (err) {
|
|
119
|
+
addLog("error", "Failed to parse message", { error: err.message });
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
ws.onclose = (event) => {
|
|
124
|
+
addLog("ws", "Disconnected", { code: event.code, reason: event.reason });
|
|
125
|
+
connectionState = "disconnected";
|
|
126
|
+
ws = null;
|
|
127
|
+
stats.connectedAt = null;
|
|
128
|
+
clearInterval(keepaliveTimer);
|
|
129
|
+
broadcastState();
|
|
130
|
+
scheduleReconnect();
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
ws.onerror = () => {
|
|
134
|
+
addLog("error", "WebSocket error");
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function scheduleReconnect() {
|
|
139
|
+
if (reconnectTimer) return;
|
|
140
|
+
const delay = Math.min(
|
|
141
|
+
RECONNECT_BASE_MS * Math.pow(2, reconnectAttempts),
|
|
142
|
+
RECONNECT_MAX_MS
|
|
143
|
+
);
|
|
144
|
+
reconnectAttempts++;
|
|
145
|
+
stats.reconnects++;
|
|
146
|
+
addLog("ws", `Reconnecting in ${delay}ms`, { attempt: reconnectAttempts });
|
|
147
|
+
reconnectTimer = setTimeout(() => {
|
|
148
|
+
reconnectTimer = null;
|
|
149
|
+
connect();
|
|
150
|
+
}, delay);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function sendMessage(msg) {
|
|
154
|
+
if (ws?.readyState === WebSocket.OPEN) {
|
|
155
|
+
ws.send(JSON.stringify(msg));
|
|
156
|
+
stats.wsMessagesSent++;
|
|
157
|
+
return true;
|
|
158
|
+
}
|
|
159
|
+
return false;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// --- Message Handling --------------------------------------------------------
|
|
163
|
+
|
|
164
|
+
async function handleBridgeMessage(msg) {
|
|
165
|
+
switch (msg.type) {
|
|
166
|
+
case "pong":
|
|
167
|
+
case "heartbeat":
|
|
168
|
+
missedPongs = 0;
|
|
169
|
+
break;
|
|
170
|
+
|
|
171
|
+
case "bridge_connected":
|
|
172
|
+
stats.bridgeVersion = msg.version || "unknown";
|
|
173
|
+
addLog("info", `Bridge handshake (bridge v${stats.bridgeVersion}, ext v${EXT_VERSION})`, msg);
|
|
174
|
+
break;
|
|
175
|
+
|
|
176
|
+
case "status_response":
|
|
177
|
+
addLog("info", "Bridge status", msg);
|
|
178
|
+
break;
|
|
179
|
+
|
|
180
|
+
case "mcp_connected":
|
|
181
|
+
addLog("info", "MCP server connected to native host");
|
|
182
|
+
break;
|
|
183
|
+
|
|
184
|
+
case "tool_request":
|
|
185
|
+
await handleToolRequest(msg);
|
|
186
|
+
break;
|
|
187
|
+
|
|
188
|
+
case "error":
|
|
189
|
+
addLog("error", "Bridge error", { error: msg.error });
|
|
190
|
+
break;
|
|
191
|
+
|
|
192
|
+
default:
|
|
193
|
+
addLog("warn", `Unknown message type: ${msg.type}`, msg);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// --- Tool Request Dispatch ---------------------------------------------------
|
|
198
|
+
|
|
199
|
+
// Per-tab tool execution queue — prevents concurrent tool requests from racing
|
|
200
|
+
// on the same tab's DOM state. Each request awaits the previous one's completion.
|
|
201
|
+
const tabQueues = new Map(); // tabId → Promise chain
|
|
202
|
+
|
|
203
|
+
function enqueueToolForTab(tabId, handler) {
|
|
204
|
+
const prev = tabQueues.get(tabId) ?? Promise.resolve();
|
|
205
|
+
// Swallow errors in chain so a failed request doesn't block subsequent ones
|
|
206
|
+
const next = prev.catch(() => {}).then(() => handler());
|
|
207
|
+
tabQueues.set(tabId, next);
|
|
208
|
+
return next; // Caller gets the actual resolution/rejection of their handler
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async function handleToolRequest(msg) {
|
|
212
|
+
const { method, params, requestId } = msg;
|
|
213
|
+
stats.toolRequestsReceived++;
|
|
214
|
+
|
|
215
|
+
// Unwrap execute_tool wrapper from MCP server
|
|
216
|
+
if (method === "execute_tool" && params?.tool) {
|
|
217
|
+
addLog("tool", `Unwrap execute_tool → ${params.tool}`, { args: params.args });
|
|
218
|
+
return handleToolRequest({
|
|
219
|
+
type: msg.type,
|
|
220
|
+
method: params.tool,
|
|
221
|
+
params: params.args || {},
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// Queue tab-targeting tools so they execute sequentially per tab
|
|
226
|
+
const tabId = resolveTabId(params?.tabId);
|
|
227
|
+
if (tabId != null) {
|
|
228
|
+
return enqueueToolForTab(tabId, () => executeToolRequest(msg));
|
|
229
|
+
}
|
|
230
|
+
return executeToolRequest(msg);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async function executeToolRequest(msg) {
|
|
234
|
+
const { method, params, requestId } = msg;
|
|
235
|
+
|
|
236
|
+
const startTime = Date.now();
|
|
237
|
+
stats.lastToolName = method;
|
|
238
|
+
stats.lastToolTime = startTime;
|
|
239
|
+
addLog("tool", `→ ${method}`, params);
|
|
240
|
+
|
|
241
|
+
try {
|
|
242
|
+
let result;
|
|
243
|
+
switch (method) {
|
|
244
|
+
case "javascript_tool":
|
|
245
|
+
result = await handleJavascriptTool(params);
|
|
246
|
+
break;
|
|
247
|
+
case "read_page":
|
|
248
|
+
result = await handleReadPage(params);
|
|
249
|
+
break;
|
|
250
|
+
case "find":
|
|
251
|
+
result = await handleFind(params);
|
|
252
|
+
break;
|
|
253
|
+
case "navigate":
|
|
254
|
+
result = await handleNavigate(params);
|
|
255
|
+
break;
|
|
256
|
+
case "form_input":
|
|
257
|
+
result = await handleFormInput(params);
|
|
258
|
+
break;
|
|
259
|
+
case "computer":
|
|
260
|
+
result = await handleComputer(params);
|
|
261
|
+
break;
|
|
262
|
+
case "tabs_context_mcp":
|
|
263
|
+
result = await handleTabsContext(params);
|
|
264
|
+
break;
|
|
265
|
+
case "tabs_create_mcp":
|
|
266
|
+
result = await handleTabsCreate(params);
|
|
267
|
+
break;
|
|
268
|
+
case "read_console_messages":
|
|
269
|
+
result = await handleReadConsole(params);
|
|
270
|
+
break;
|
|
271
|
+
case "get_page_text":
|
|
272
|
+
result = await handleGetPageText(params);
|
|
273
|
+
break;
|
|
274
|
+
case "update_plan":
|
|
275
|
+
result = handleUpdatePlan(params);
|
|
276
|
+
break;
|
|
277
|
+
case "shortcuts_list":
|
|
278
|
+
result = { result: [] }; // no side panel shortcuts on Android
|
|
279
|
+
break;
|
|
280
|
+
case "shortcuts_execute":
|
|
281
|
+
result = { error: "Keyboard shortcuts are not available on Android Edge" };
|
|
282
|
+
break;
|
|
283
|
+
case "read_network_requests":
|
|
284
|
+
result = handleReadNetworkRequests(params);
|
|
285
|
+
break;
|
|
286
|
+
case "resize_window":
|
|
287
|
+
result = await handleResizeWindow(params);
|
|
288
|
+
break;
|
|
289
|
+
case "upload_image":
|
|
290
|
+
result = await handleUploadImage(params);
|
|
291
|
+
break;
|
|
292
|
+
case "gif_creator":
|
|
293
|
+
result = await handleGifCreator(params);
|
|
294
|
+
break;
|
|
295
|
+
default:
|
|
296
|
+
result = { error: `Unsupported tool: ${method}` };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const elapsed = Date.now() - startTime;
|
|
300
|
+
stats.toolResponsesSent++;
|
|
301
|
+
addLog("tool", `← ${method} OK (${elapsed}ms)`, { resultPreview: JSON.stringify(result).slice(0, 200) });
|
|
302
|
+
|
|
303
|
+
// CRITICAL: Do NOT include `method` in response — cli.js response classifier
|
|
304
|
+
// M7z() checks `"method" in A` first and misclassifies as notification,
|
|
305
|
+
// causing handleResponse() to never fire and the tool call to timeout.
|
|
306
|
+
// Include requestId for parallel dispatch (bridge matches response to caller)
|
|
307
|
+
const response = { type: "tool_response", result };
|
|
308
|
+
if (requestId) response.requestId = requestId;
|
|
309
|
+
sendMessage(response);
|
|
310
|
+
} catch (err) {
|
|
311
|
+
const elapsed = Date.now() - startTime;
|
|
312
|
+
stats.toolErrors++;
|
|
313
|
+
addLog("error", `← ${method} FAIL (${elapsed}ms)`, { error: err.message });
|
|
314
|
+
const errResponse = { type: "tool_response", error: err.message || String(err) };
|
|
315
|
+
if (requestId) errResponse.requestId = requestId;
|
|
316
|
+
sendMessage(errResponse);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// --- Tool Implementations ----------------------------------------------------
|
|
321
|
+
|
|
322
|
+
async function handleJavascriptTool(params) {
|
|
323
|
+
const { text, tabId } = params;
|
|
324
|
+
const tid = resolveTabId(tabId);
|
|
325
|
+
|
|
326
|
+
// Content script uses <script>-tag injection + window.postMessage to run
|
|
327
|
+
// code in the page's MAIN world, with a DOM-property fallback for pages
|
|
328
|
+
// whose CSP blocks inline scripts. chrome.scripting.executeScript(world:MAIN)
|
|
329
|
+
// hangs indefinitely on Android Edge so we avoid it.
|
|
330
|
+
return await executeViaContentScript(tid, "javascript_exec", { code: text });
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
async function handleReadPage(params) {
|
|
334
|
+
const { tabId, filter, depth, ref_id, max_chars } = params;
|
|
335
|
+
const tid = resolveTabId(tabId);
|
|
336
|
+
return await executeViaContentScript(tid, "read_page", {
|
|
337
|
+
filter: filter || "all",
|
|
338
|
+
depth: depth || 15,
|
|
339
|
+
ref_id: ref_id || null,
|
|
340
|
+
max_chars: max_chars || 50000,
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
async function handleFind(params) {
|
|
345
|
+
const { query, tabId } = params;
|
|
346
|
+
const tid = resolveTabId(tabId);
|
|
347
|
+
return await executeViaContentScript(tid, "find", { query });
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
async function handleNavigate(params) {
|
|
351
|
+
const { url, tabId } = params;
|
|
352
|
+
const tid = resolveTabId(tabId);
|
|
353
|
+
|
|
354
|
+
if (url === "back") {
|
|
355
|
+
await chrome.tabs.goBack(tid);
|
|
356
|
+
return { result: "Navigated back" };
|
|
357
|
+
}
|
|
358
|
+
if (url === "forward") {
|
|
359
|
+
await chrome.tabs.goForward(tid);
|
|
360
|
+
return { result: "Navigated forward" };
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
let fullUrl = url;
|
|
364
|
+
if (!/^https?:\/\//i.test(fullUrl)) {
|
|
365
|
+
fullUrl = "https://" + fullUrl;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
await chrome.tabs.update(tid, { url: fullUrl });
|
|
369
|
+
|
|
370
|
+
await new Promise((resolve) => {
|
|
371
|
+
const listener = (updatedTabId, changeInfo) => {
|
|
372
|
+
if (updatedTabId === tid && changeInfo.status === "complete") {
|
|
373
|
+
chrome.tabs.onUpdated.removeListener(listener);
|
|
374
|
+
resolve();
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
chrome.tabs.onUpdated.addListener(listener);
|
|
378
|
+
setTimeout(() => {
|
|
379
|
+
chrome.tabs.onUpdated.removeListener(listener);
|
|
380
|
+
resolve();
|
|
381
|
+
}, 15000);
|
|
382
|
+
});
|
|
383
|
+
|
|
384
|
+
return { result: `Navigated to ${fullUrl}` };
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
async function handleFormInput(params) {
|
|
388
|
+
const { ref, value, tabId } = params;
|
|
389
|
+
const tid = resolveTabId(tabId);
|
|
390
|
+
return await executeViaContentScript(tid, "form_input", { ref, value });
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
async function handleComputer(params) {
|
|
394
|
+
const { action, tabId, coordinate, text } = params;
|
|
395
|
+
const tid = resolveTabId(tabId);
|
|
396
|
+
|
|
397
|
+
// Parse modifier keys (e.g. "ctrl+shift") into event properties
|
|
398
|
+
const modifiers = parseModifiers(params.modifiers);
|
|
399
|
+
|
|
400
|
+
switch (action) {
|
|
401
|
+
case "screenshot":
|
|
402
|
+
try {
|
|
403
|
+
const dataUrl = await chrome.tabs.captureVisibleTab(null, { format: "png" });
|
|
404
|
+
return { result: dataUrl, type: "image/png", encoding: "base64" };
|
|
405
|
+
} catch (err) {
|
|
406
|
+
return await executeViaContentScript(tid, "screenshot", {});
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
case "type":
|
|
410
|
+
return await executeViaContentScript(tid, "type_text", { text, modifiers });
|
|
411
|
+
|
|
412
|
+
case "key":
|
|
413
|
+
return await executeViaContentScript(tid, "key_press", { keys: text, modifiers });
|
|
414
|
+
|
|
415
|
+
case "scroll":
|
|
416
|
+
return await executeViaContentScript(tid, "scroll", {
|
|
417
|
+
x: coordinate?.[0] || 0,
|
|
418
|
+
y: coordinate?.[1] || 0,
|
|
419
|
+
direction: params.scroll_direction,
|
|
420
|
+
amount: params.scroll_amount || 3,
|
|
421
|
+
modifiers,
|
|
422
|
+
});
|
|
423
|
+
|
|
424
|
+
case "scroll_to":
|
|
425
|
+
return await executeViaContentScript(tid, "scroll_to", { ref: params.ref_id });
|
|
426
|
+
|
|
427
|
+
case "left_click":
|
|
428
|
+
case "right_click":
|
|
429
|
+
case "double_click":
|
|
430
|
+
case "triple_click":
|
|
431
|
+
return await executeViaContentScript(tid, "click", {
|
|
432
|
+
x: coordinate?.[0] || 0,
|
|
433
|
+
y: coordinate?.[1] || 0,
|
|
434
|
+
ref: params.ref,
|
|
435
|
+
button: action.replace("_click", ""),
|
|
436
|
+
clickCount: action === "double_click" ? 2 : action === "triple_click" ? 3 : 1,
|
|
437
|
+
modifiers,
|
|
438
|
+
});
|
|
439
|
+
|
|
440
|
+
case "left_click_drag":
|
|
441
|
+
return await executeViaContentScript(tid, "drag", {
|
|
442
|
+
startX: coordinate?.[0] || 0,
|
|
443
|
+
startY: coordinate?.[1] || 0,
|
|
444
|
+
endX: params.end_coordinate?.[0] || 0,
|
|
445
|
+
endY: params.end_coordinate?.[1] || 0,
|
|
446
|
+
modifiers,
|
|
447
|
+
});
|
|
448
|
+
|
|
449
|
+
case "hover":
|
|
450
|
+
return await executeViaContentScript(tid, "hover", {
|
|
451
|
+
x: coordinate?.[0] || 0,
|
|
452
|
+
y: coordinate?.[1] || 0,
|
|
453
|
+
modifiers,
|
|
454
|
+
});
|
|
455
|
+
|
|
456
|
+
case "zoom": {
|
|
457
|
+
// Capture full screenshot, then crop via bridge for zoomed view
|
|
458
|
+
const zoomFactor = params.zoom_factor || 2;
|
|
459
|
+
try {
|
|
460
|
+
const fullShot = await chrome.tabs.captureVisibleTab(null, { format: "png" });
|
|
461
|
+
// Determine image dimensions from the data URL via bridge crop
|
|
462
|
+
// Use viewport-based crop centered on coordinate
|
|
463
|
+
const dims = await executeViaContentScript(tid, "get_viewport_dims", {});
|
|
464
|
+
const vw = dims?.width || 1080;
|
|
465
|
+
const vh = dims?.height || 1920;
|
|
466
|
+
const zx = coordinate?.[0] || Math.round(vw / 2);
|
|
467
|
+
const zy = coordinate?.[1] || Math.round(vh / 2);
|
|
468
|
+
const cropW = Math.round(vw / zoomFactor);
|
|
469
|
+
const cropH = Math.round(vh / zoomFactor);
|
|
470
|
+
const cropX = Math.max(0, Math.min(Math.round(zx - cropW / 2), vw - cropW));
|
|
471
|
+
const cropY = Math.max(0, Math.min(Math.round(zy - cropH / 2), vh - cropH));
|
|
472
|
+
|
|
473
|
+
const resp = await fetch("http://127.0.0.1:18963/crop", {
|
|
474
|
+
method: "POST",
|
|
475
|
+
headers: { "Content-Type": "application/json" },
|
|
476
|
+
body: JSON.stringify({ image: fullShot, crop: { x: cropX, y: cropY, width: cropW, height: cropH } }),
|
|
477
|
+
});
|
|
478
|
+
const data = await resp.json();
|
|
479
|
+
if (data.image) {
|
|
480
|
+
return { result: data.image, type: "image/png", encoding: "base64" };
|
|
481
|
+
}
|
|
482
|
+
return { error: data.error || "Crop failed" };
|
|
483
|
+
} catch (err) {
|
|
484
|
+
return { error: `Zoom failed: ${err.message}` };
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
case "wait":
|
|
489
|
+
const waitMs = (params.duration || 2) * 1000;
|
|
490
|
+
await new Promise((r) => setTimeout(r, waitMs));
|
|
491
|
+
return { result: `Waited ${params.duration || 2}s` };
|
|
492
|
+
|
|
493
|
+
default:
|
|
494
|
+
return { error: `Unsupported computer action: ${action}` };
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/** Parse modifier string (e.g. "ctrl+shift") into event property flags */
|
|
499
|
+
function parseModifiers(modStr) {
|
|
500
|
+
if (!modStr) return {};
|
|
501
|
+
const mods = modStr.toLowerCase().split("+").map((s) => s.trim());
|
|
502
|
+
return {
|
|
503
|
+
ctrlKey: mods.includes("ctrl") || mods.includes("control"),
|
|
504
|
+
shiftKey: mods.includes("shift"),
|
|
505
|
+
altKey: mods.includes("alt"),
|
|
506
|
+
metaKey: mods.includes("meta") || mods.includes("cmd") || mods.includes("command"),
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
async function handleTabsContext(params) {
|
|
511
|
+
const { createIfEmpty } = params;
|
|
512
|
+
const tabs = await chrome.tabs.query({});
|
|
513
|
+
|
|
514
|
+
if (mcpTabGroup.size === 0 && tabs.length > 0) {
|
|
515
|
+
for (const tab of tabs) {
|
|
516
|
+
mcpTabGroup.set(tab.id, {
|
|
517
|
+
id: tab.id,
|
|
518
|
+
url: tab.url || tab.pendingUrl || "",
|
|
519
|
+
title: tab.title || "",
|
|
520
|
+
active: tab.active,
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
if (createIfEmpty && mcpTabGroup.size === 0) {
|
|
526
|
+
const newTab = await chrome.tabs.create({ url: "about:blank" });
|
|
527
|
+
mcpTabGroup.set(newTab.id, {
|
|
528
|
+
id: newTab.id,
|
|
529
|
+
url: "about:blank",
|
|
530
|
+
title: "New Tab",
|
|
531
|
+
active: true,
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
const tabList = [];
|
|
536
|
+
for (const [tabId] of mcpTabGroup) {
|
|
537
|
+
try {
|
|
538
|
+
const tab = await chrome.tabs.get(tabId);
|
|
539
|
+
const info = {
|
|
540
|
+
id: tab.id,
|
|
541
|
+
url: tab.url || tab.pendingUrl || "",
|
|
542
|
+
title: tab.title || "",
|
|
543
|
+
active: tab.active,
|
|
544
|
+
};
|
|
545
|
+
mcpTabGroup.set(tabId, info);
|
|
546
|
+
tabList.push(info);
|
|
547
|
+
} catch {
|
|
548
|
+
mcpTabGroup.delete(tabId);
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
return {
|
|
553
|
+
result: {
|
|
554
|
+
tabs: tabList,
|
|
555
|
+
activeTabId: tabList.find((t) => t.active)?.id || tabList[0]?.id,
|
|
556
|
+
},
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
async function handleTabsCreate(_params) {
|
|
561
|
+
const newTab = await chrome.tabs.create({ url: "about:blank" });
|
|
562
|
+
mcpTabGroup.set(newTab.id, {
|
|
563
|
+
id: newTab.id,
|
|
564
|
+
url: "about:blank",
|
|
565
|
+
title: "New Tab",
|
|
566
|
+
active: true,
|
|
567
|
+
});
|
|
568
|
+
return { result: { tabId: newTab.id } };
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
async function handleReadConsole(params) {
|
|
572
|
+
const { tabId } = params;
|
|
573
|
+
const tid = resolveTabId(tabId);
|
|
574
|
+
return await executeViaContentScript(tid, "read_console", {});
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
// --- New Tool Handlers -------------------------------------------------------
|
|
578
|
+
|
|
579
|
+
async function handleGetPageText(params) {
|
|
580
|
+
const { tabId, max_chars } = params;
|
|
581
|
+
const tid = resolveTabId(tabId);
|
|
582
|
+
return await executeViaContentScript(tid, "get_page_text", {
|
|
583
|
+
max_chars: max_chars || 100000,
|
|
584
|
+
});
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
/** Auto-approve on Android (no side panel UI for plan display) */
|
|
588
|
+
function handleUpdatePlan(params) {
|
|
589
|
+
const { domains } = params;
|
|
590
|
+
return {
|
|
591
|
+
result: {
|
|
592
|
+
approved: true,
|
|
593
|
+
domains: domains || [],
|
|
594
|
+
note: "Auto-approved on Android (no side panel UI)",
|
|
595
|
+
},
|
|
596
|
+
};
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
// --- Network request tracking ------------------------------------------------
|
|
600
|
+
|
|
601
|
+
/** Per-tab network request ring buffer. @type {Map<number, Array>} */
|
|
602
|
+
const networkRequests = new Map();
|
|
603
|
+
const MAX_NETWORK_ENTRIES = 100;
|
|
604
|
+
|
|
605
|
+
// Register webRequest listener if the API is available (requires webRequest permission)
|
|
606
|
+
try {
|
|
607
|
+
if (chrome.webRequest?.onCompleted) {
|
|
608
|
+
chrome.webRequest.onCompleted.addListener(
|
|
609
|
+
(details) => {
|
|
610
|
+
if (!details.tabId || details.tabId < 0) return;
|
|
611
|
+
if (!networkRequests.has(details.tabId)) {
|
|
612
|
+
networkRequests.set(details.tabId, []);
|
|
613
|
+
}
|
|
614
|
+
const buf = networkRequests.get(details.tabId);
|
|
615
|
+
buf.push({
|
|
616
|
+
url: details.url,
|
|
617
|
+
method: details.method,
|
|
618
|
+
statusCode: details.statusCode,
|
|
619
|
+
type: details.type,
|
|
620
|
+
timestamp: details.timeStamp,
|
|
621
|
+
fromCache: details.fromCache || false,
|
|
622
|
+
});
|
|
623
|
+
// Ring buffer: trim oldest entries
|
|
624
|
+
while (buf.length > MAX_NETWORK_ENTRIES) buf.shift();
|
|
625
|
+
},
|
|
626
|
+
{ urls: ["<all_urls>"] }
|
|
627
|
+
);
|
|
628
|
+
addLog("info", "webRequest.onCompleted listener registered");
|
|
629
|
+
}
|
|
630
|
+
} catch (err) {
|
|
631
|
+
addLog("warn", "webRequest not available", { error: err.message });
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
// Clear network buffer on cross-domain navigation
|
|
635
|
+
chrome.tabs.onUpdated.addListener((tabId, changeInfo) => {
|
|
636
|
+
if (changeInfo.url && networkRequests.has(tabId)) {
|
|
637
|
+
try {
|
|
638
|
+
const oldEntries = networkRequests.get(tabId);
|
|
639
|
+
const oldDomain = oldEntries.length > 0 ? new URL(oldEntries[0].url).hostname : "";
|
|
640
|
+
const newDomain = new URL(changeInfo.url).hostname;
|
|
641
|
+
if (oldDomain && newDomain !== oldDomain) {
|
|
642
|
+
networkRequests.set(tabId, []);
|
|
643
|
+
}
|
|
644
|
+
} catch {}
|
|
645
|
+
}
|
|
646
|
+
});
|
|
647
|
+
|
|
648
|
+
function handleReadNetworkRequests(params) {
|
|
649
|
+
const { tabId, since, type_filter } = params;
|
|
650
|
+
const tid = resolveTabId(tabId);
|
|
651
|
+
let entries = networkRequests.get(tid) || [];
|
|
652
|
+
|
|
653
|
+
if (since) {
|
|
654
|
+
entries = entries.filter((e) => e.timestamp > since);
|
|
655
|
+
}
|
|
656
|
+
if (type_filter) {
|
|
657
|
+
entries = entries.filter((e) => e.type === type_filter);
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
return {
|
|
661
|
+
result: entries.slice(-100), // return last 100 matching
|
|
662
|
+
count: entries.length,
|
|
663
|
+
// Note: if empty, the bridge may intercept this tool call and return CDP Network data instead
|
|
664
|
+
};
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
async function handleResizeWindow(params) {
|
|
668
|
+
const { width, height } = params;
|
|
669
|
+
// Try chrome.windows.update first (works on desktop)
|
|
670
|
+
try {
|
|
671
|
+
const [win] = await chrome.windows.getAll();
|
|
672
|
+
if (win?.id) {
|
|
673
|
+
await chrome.windows.update(win.id, { width, height });
|
|
674
|
+
return { result: `Resized window to ${width}x${height}` };
|
|
675
|
+
}
|
|
676
|
+
} catch {}
|
|
677
|
+
|
|
678
|
+
// Fallback: bridge handles this via CDP Emulation.setDeviceMetricsOverride
|
|
679
|
+
// (the bridge intercepts resize_window when CDP is available)
|
|
680
|
+
return { error: `Window resize not supported natively on Android. Bridge will use CDP if available.` };
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
async function handleUploadImage(params) {
|
|
684
|
+
const { tabId, ref, coordinate, image_data } = params;
|
|
685
|
+
const tid = resolveTabId(tabId);
|
|
686
|
+
return await executeViaContentScript(tid, "upload_image", {
|
|
687
|
+
ref,
|
|
688
|
+
x: coordinate?.[0],
|
|
689
|
+
y: coordinate?.[1],
|
|
690
|
+
image_data,
|
|
691
|
+
});
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
/** GIF creator — captures PNG frames, encodes via bridge's /gif endpoint */
|
|
695
|
+
const gifState = { recording: false, frames: [], tabId: null, timer: null, maxTimer: null };
|
|
696
|
+
const GIF_BRIDGE_URL = "http://127.0.0.1:18963/gif";
|
|
697
|
+
const GIF_MAX_DURATION_MS = 60_000; // Hard cap: 60s max recording
|
|
698
|
+
|
|
699
|
+
async function handleGifCreator(params) {
|
|
700
|
+
const { action } = params;
|
|
701
|
+
|
|
702
|
+
switch (action) {
|
|
703
|
+
case "start_recording": {
|
|
704
|
+
if (gifState.recording) return { error: "Already recording" };
|
|
705
|
+
gifState.recording = true;
|
|
706
|
+
gifState.frames = [];
|
|
707
|
+
gifState.tabId = resolveTabId(params.tabId);
|
|
708
|
+
|
|
709
|
+
// Capture at ~2fps (500ms intervals), max 30s / 60 frames
|
|
710
|
+
gifState.timer = setInterval(async () => {
|
|
711
|
+
if (gifState.frames.length >= 60) {
|
|
712
|
+
clearInterval(gifState.timer);
|
|
713
|
+
gifState.recording = false;
|
|
714
|
+
return;
|
|
715
|
+
}
|
|
716
|
+
try {
|
|
717
|
+
const dataUrl = await chrome.tabs.captureVisibleTab(null, { format: "png" });
|
|
718
|
+
gifState.frames.push({ data: dataUrl, ts: Date.now() });
|
|
719
|
+
} catch {}
|
|
720
|
+
}, 500);
|
|
721
|
+
|
|
722
|
+
// Hard cap: stop recording after 60s even if stop_recording is never called
|
|
723
|
+
gifState.maxTimer = setTimeout(() => {
|
|
724
|
+
if (gifState.recording) {
|
|
725
|
+
clearInterval(gifState.timer);
|
|
726
|
+
gifState.recording = false;
|
|
727
|
+
gifState.maxTimer = null;
|
|
728
|
+
addLog("warn", `GIF: max duration (${GIF_MAX_DURATION_MS / 1000}s) reached, auto-stopped`);
|
|
729
|
+
}
|
|
730
|
+
}, GIF_MAX_DURATION_MS);
|
|
731
|
+
|
|
732
|
+
return { result: "Recording started (max 30s / 60 frames)" };
|
|
733
|
+
}
|
|
734
|
+
case "stop_recording": {
|
|
735
|
+
if (!gifState.recording) return { error: "Not recording" };
|
|
736
|
+
clearInterval(gifState.timer);
|
|
737
|
+
if (gifState.maxTimer) { clearTimeout(gifState.maxTimer); gifState.maxTimer = null; }
|
|
738
|
+
gifState.recording = false;
|
|
739
|
+
return {
|
|
740
|
+
result: `Recording stopped. ${gifState.frames.length} frames captured.`,
|
|
741
|
+
frameCount: gifState.frames.length,
|
|
742
|
+
};
|
|
743
|
+
}
|
|
744
|
+
case "export": {
|
|
745
|
+
if (gifState.frames.length === 0) return { error: "No frames captured. Start and stop a recording first." };
|
|
746
|
+
|
|
747
|
+
// Calculate inter-frame delay from timestamps
|
|
748
|
+
const avgDelay = gifState.frames.length > 1
|
|
749
|
+
? Math.round((gifState.frames[gifState.frames.length - 1].ts - gifState.frames[0].ts) / (gifState.frames.length - 1))
|
|
750
|
+
: 500;
|
|
751
|
+
|
|
752
|
+
try {
|
|
753
|
+
addLog("info", `GIF: encoding ${gifState.frames.length} frames via bridge`);
|
|
754
|
+
const resp = await fetch(GIF_BRIDGE_URL, {
|
|
755
|
+
method: "POST",
|
|
756
|
+
headers: { "Content-Type": "application/json" },
|
|
757
|
+
body: JSON.stringify({
|
|
758
|
+
frames: gifState.frames,
|
|
759
|
+
delay: avgDelay,
|
|
760
|
+
maxWidth: params.maxWidth || 480,
|
|
761
|
+
}),
|
|
762
|
+
});
|
|
763
|
+
const data = await resp.json();
|
|
764
|
+
if (data.error) return { error: `GIF encoding failed: ${data.error}` };
|
|
765
|
+
|
|
766
|
+
const filename = params.filename || `recording_${Date.now()}.gif`;
|
|
767
|
+
return {
|
|
768
|
+
result: data.gif,
|
|
769
|
+
filename,
|
|
770
|
+
size: data.size,
|
|
771
|
+
frameCount: gifState.frames.length,
|
|
772
|
+
type: "image/gif",
|
|
773
|
+
encoding: "base64",
|
|
774
|
+
};
|
|
775
|
+
} catch (err) {
|
|
776
|
+
return { error: `GIF export failed: ${err.message}` };
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
default:
|
|
780
|
+
return { error: `Unknown gif_creator action: ${action}. Use start_recording, stop_recording, or export.` };
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
// --- Content Script Communication --------------------------------------------
|
|
785
|
+
|
|
786
|
+
// Persistent port connections from content scripts (keyed by tab ID).
|
|
787
|
+
// These are far more reliable than chrome.tabs.sendMessage on Android Edge,
|
|
788
|
+
// which corrupts message channels after 2-3 calls.
|
|
789
|
+
/** @type {Map<number, chrome.runtime.Port>} */
|
|
790
|
+
const contentPorts = new Map();
|
|
791
|
+
/** @type {Map<string, {resolve: Function, timer: number, port: chrome.runtime.Port}>} */
|
|
792
|
+
const pendingPortRequests = new Map();
|
|
793
|
+
const MAX_PENDING_PORT_REQUESTS = 100;
|
|
794
|
+
let portReqCounter = 0;
|
|
795
|
+
|
|
796
|
+
chrome.runtime.onConnect.addListener((port) => {
|
|
797
|
+
if (port.name !== "cfc-content") return;
|
|
798
|
+
const tabId = port.sender?.tab?.id;
|
|
799
|
+
if (!tabId) return;
|
|
800
|
+
|
|
801
|
+
contentPorts.set(tabId, port);
|
|
802
|
+
addLog("info", `Content port connected for tab ${tabId}`);
|
|
803
|
+
|
|
804
|
+
port.onMessage.addListener((msg) => {
|
|
805
|
+
if (!msg._reqId) return;
|
|
806
|
+
const pending = pendingPortRequests.get(msg._reqId);
|
|
807
|
+
if (pending) {
|
|
808
|
+
clearTimeout(pending.timer);
|
|
809
|
+
pendingPortRequests.delete(msg._reqId);
|
|
810
|
+
// Provide fallback if content script sent a malformed/empty payload
|
|
811
|
+
pending.resolve(msg.result ?? { error: "Empty response from content script" });
|
|
812
|
+
}
|
|
813
|
+
});
|
|
814
|
+
|
|
815
|
+
port.onDisconnect.addListener(() => {
|
|
816
|
+
contentPorts.delete(tabId);
|
|
817
|
+
// Only clean up requests belonging to THIS port — not other tabs' requests.
|
|
818
|
+
// Uses object identity (pending.port === port) instead of tabId matching
|
|
819
|
+
// to avoid race conditions on rapid tab reloads where new port connects
|
|
820
|
+
// before old disconnect fires.
|
|
821
|
+
let cleaned = 0;
|
|
822
|
+
for (const [reqId, pending] of pendingPortRequests.entries()) {
|
|
823
|
+
if (pending.port === port) {
|
|
824
|
+
clearTimeout(pending.timer);
|
|
825
|
+
pending.resolve({ error: `Content port disconnected for tab ${tabId}` });
|
|
826
|
+
pendingPortRequests.delete(reqId);
|
|
827
|
+
cleaned++;
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
addLog("info", `Content port disconnected for tab ${tabId}, cleared ${cleaned} pending requests`);
|
|
831
|
+
});
|
|
832
|
+
});
|
|
833
|
+
|
|
834
|
+
// --- On-demand content script injection --------------------------------------
|
|
835
|
+
// Default mode: only inject content.js when a tool targets the tab (saves 30-80MB).
|
|
836
|
+
// "all-pages" mode: inject into every tab on startup (original behavior).
|
|
837
|
+
let cfcInjectionMode = "on-demand"; // "on-demand" | "all-pages"
|
|
838
|
+
|
|
839
|
+
// Load injection mode from storage on startup
|
|
840
|
+
chrome.storage.local.get("cfcInjectionMode", (data) => {
|
|
841
|
+
cfcInjectionMode = data.cfcInjectionMode || "on-demand";
|
|
842
|
+
if (cfcInjectionMode === "all-pages") {
|
|
843
|
+
injectContentScriptIntoAllTabs();
|
|
844
|
+
}
|
|
845
|
+
});
|
|
846
|
+
|
|
847
|
+
// React to setting changes from popup
|
|
848
|
+
chrome.storage.onChanged.addListener((changes, area) => {
|
|
849
|
+
if (area === "local" && changes.cfcInjectionMode) {
|
|
850
|
+
cfcInjectionMode = changes.cfcInjectionMode.newValue || "on-demand";
|
|
851
|
+
addLog("info", `Injection mode changed to: ${cfcInjectionMode}`);
|
|
852
|
+
if (cfcInjectionMode === "all-pages") {
|
|
853
|
+
injectContentScriptIntoAllTabs();
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
});
|
|
857
|
+
|
|
858
|
+
/** Inject content.js into all existing tabs (for "all-pages" mode) */
|
|
859
|
+
async function injectContentScriptIntoAllTabs() {
|
|
860
|
+
try {
|
|
861
|
+
const tabs = await chrome.tabs.query({});
|
|
862
|
+
for (const tab of tabs) {
|
|
863
|
+
if (!tab.url || tab.url.startsWith("chrome://") || tab.url.startsWith("edge://")) continue;
|
|
864
|
+
if (contentPorts.has(tab.id)) continue; // already connected
|
|
865
|
+
try {
|
|
866
|
+
await new Promise((resolve, reject) => {
|
|
867
|
+
chrome.tabs.executeScript(tab.id, { file: "content.js" }, () => {
|
|
868
|
+
if (chrome.runtime.lastError) reject(new Error(chrome.runtime.lastError.message));
|
|
869
|
+
else resolve();
|
|
870
|
+
});
|
|
871
|
+
});
|
|
872
|
+
} catch {
|
|
873
|
+
// Permission denied or tab not scriptable — skip
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
addLog("info", `Injected content.js into existing tabs (all-pages mode)`);
|
|
877
|
+
} catch (err) {
|
|
878
|
+
addLog("warn", `Failed to inject into all tabs: ${err.message}`);
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
/** Ensure content script is loaded in a tab before dispatching tool requests */
|
|
883
|
+
async function ensureContentScript(tabId) {
|
|
884
|
+
if (contentPorts.has(tabId)) return; // already connected
|
|
885
|
+
try {
|
|
886
|
+
await new Promise((resolve, reject) => {
|
|
887
|
+
chrome.tabs.executeScript(tabId, { file: "content.js" }, () => {
|
|
888
|
+
if (chrome.runtime.lastError) reject(new Error(chrome.runtime.lastError.message));
|
|
889
|
+
else resolve();
|
|
890
|
+
});
|
|
891
|
+
});
|
|
892
|
+
// Wait briefly for content script to connect its port
|
|
893
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
894
|
+
} catch (err) {
|
|
895
|
+
addLog("warn", `Content script injection failed for tab ${tabId}: ${err.message}`);
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
async function executeViaContentScript(tabId, action, params) {
|
|
900
|
+
// Ensure content script is loaded before dispatching (on-demand injection)
|
|
901
|
+
await ensureContentScript(tabId);
|
|
902
|
+
const port = contentPorts.get(tabId);
|
|
903
|
+
if (port) {
|
|
904
|
+
return executeViaPort(port, tabId, action, params);
|
|
905
|
+
}
|
|
906
|
+
// Fall back to sendMessage if no persistent port
|
|
907
|
+
return executeViaSendMessage(tabId, action, params);
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
function executeViaPort(port, tabId, action, params) {
|
|
911
|
+
// Guard against unbounded growth (e.g. tab frozen or content script dead).
|
|
912
|
+
// Reject immediately — falling back to sendMessage would just add another
|
|
913
|
+
// 30s timeout and potentially trigger content script re-injection while
|
|
914
|
+
// 100 dead requests are still leaking.
|
|
915
|
+
if (pendingPortRequests.size >= MAX_PENDING_PORT_REQUESTS) {
|
|
916
|
+
addLog("warn", `Pending port requests at limit (${MAX_PENDING_PORT_REQUESTS})`);
|
|
917
|
+
return Promise.reject(new Error("Tab unresponsive: max concurrent tool requests exceeded"));
|
|
918
|
+
}
|
|
919
|
+
return new Promise((resolve, reject) => {
|
|
920
|
+
const reqId = `req_${++portReqCounter}`;
|
|
921
|
+
const timer = setTimeout(() => {
|
|
922
|
+
pendingPortRequests.delete(reqId);
|
|
923
|
+
addLog("warn", `Port timeout for ${action} on tab ${tabId}, falling back to sendMessage`);
|
|
924
|
+
// Fall back to sendMessage on timeout
|
|
925
|
+
executeViaSendMessage(tabId, action, params).then(resolve).catch(reject);
|
|
926
|
+
}, CONTENT_SCRIPT_TIMEOUT_MS);
|
|
927
|
+
|
|
928
|
+
pendingPortRequests.set(reqId, { resolve, timer, port });
|
|
929
|
+
|
|
930
|
+
try {
|
|
931
|
+
port.postMessage({ _reqId: reqId, action, params });
|
|
932
|
+
} catch (err) {
|
|
933
|
+
clearTimeout(timer);
|
|
934
|
+
pendingPortRequests.delete(reqId);
|
|
935
|
+
// Port broken — remove and fall back
|
|
936
|
+
contentPorts.delete(tabId);
|
|
937
|
+
executeViaSendMessage(tabId, action, params).then(resolve).catch(reject);
|
|
938
|
+
}
|
|
939
|
+
});
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
function executeViaSendMessage(tabId, action, params) {
|
|
943
|
+
return new Promise((resolve, reject) => {
|
|
944
|
+
const timeout = setTimeout(() => {
|
|
945
|
+
reject(new Error(`Content script timeout for ${action}`));
|
|
946
|
+
}, CONTENT_SCRIPT_TIMEOUT_MS);
|
|
947
|
+
|
|
948
|
+
chrome.tabs.sendMessage(tabId, { action, params }, (response) => {
|
|
949
|
+
clearTimeout(timeout);
|
|
950
|
+
if (chrome.runtime.lastError) {
|
|
951
|
+
injectAndRetry(tabId, action, params).then(resolve).catch(reject);
|
|
952
|
+
return;
|
|
953
|
+
}
|
|
954
|
+
resolve(response);
|
|
955
|
+
});
|
|
956
|
+
});
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
async function injectAndRetry(tabId, action, params) {
|
|
960
|
+
await Promise.race([
|
|
961
|
+
new Promise((resolve, reject) => {
|
|
962
|
+
chrome.tabs.executeScript(tabId, { file: "content.js" }, () => {
|
|
963
|
+
if (chrome.runtime.lastError) reject(new Error(chrome.runtime.lastError.message));
|
|
964
|
+
else resolve();
|
|
965
|
+
});
|
|
966
|
+
}),
|
|
967
|
+
new Promise((_, reject) =>
|
|
968
|
+
setTimeout(() => reject(new Error("Content script injection timeout")), SCRIPTING_TIMEOUT_MS)
|
|
969
|
+
),
|
|
970
|
+
]);
|
|
971
|
+
|
|
972
|
+
// Wait for content script to connect its port
|
|
973
|
+
await new Promise((r) => setTimeout(r, 500));
|
|
974
|
+
|
|
975
|
+
// Try port first if it connected during injection
|
|
976
|
+
const port = contentPorts.get(tabId);
|
|
977
|
+
if (port) {
|
|
978
|
+
return executeViaPort(port, tabId, action, params);
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
return new Promise((resolve, reject) => {
|
|
982
|
+
chrome.tabs.sendMessage(tabId, { action, params }, (response) => {
|
|
983
|
+
if (chrome.runtime.lastError) {
|
|
984
|
+
reject(new Error(`Content script unavailable: ${chrome.runtime.lastError.message}`));
|
|
985
|
+
return;
|
|
986
|
+
}
|
|
987
|
+
resolve(response);
|
|
988
|
+
});
|
|
989
|
+
});
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
// --- Utility -----------------------------------------------------------------
|
|
993
|
+
|
|
994
|
+
function resolveTabId(tabId) {
|
|
995
|
+
if (tabId && mcpTabGroup.has(tabId)) return tabId;
|
|
996
|
+
for (const [id, info] of mcpTabGroup) {
|
|
997
|
+
if (info.active) return id;
|
|
998
|
+
}
|
|
999
|
+
const first = mcpTabGroup.keys().next();
|
|
1000
|
+
if (!first.done) return first.value;
|
|
1001
|
+
return tabId ?? null; // explicit null instead of undefined pass-through
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
function broadcastState() {
|
|
1005
|
+
chrome.runtime.sendMessage({
|
|
1006
|
+
type: "state_update",
|
|
1007
|
+
state: connectionState,
|
|
1008
|
+
tabCount: mcpTabGroup.size,
|
|
1009
|
+
stats,
|
|
1010
|
+
}).catch(() => {});
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
// --- Tab tracking ------------------------------------------------------------
|
|
1014
|
+
|
|
1015
|
+
chrome.tabs.onRemoved.addListener((tabId) => {
|
|
1016
|
+
const wasMcpTab = mcpTabGroup.has(tabId);
|
|
1017
|
+
mcpTabGroup.delete(tabId);
|
|
1018
|
+
networkRequests.delete(tabId);
|
|
1019
|
+
tabQueues.delete(tabId);
|
|
1020
|
+
// Force-disconnect port to flush pending requests (onDisconnect may not
|
|
1021
|
+
// fire if renderer was killed abruptly via CDP /json/close)
|
|
1022
|
+
const port = contentPorts.get(tabId);
|
|
1023
|
+
if (port) {
|
|
1024
|
+
try { port.disconnect(); } catch {}
|
|
1025
|
+
}
|
|
1026
|
+
contentPorts.delete(tabId);
|
|
1027
|
+
// Notify bridge so it can trigger CDP memory pressure on surviving renderers
|
|
1028
|
+
sendMessage({ type: "tab_removed", tabId, wasMcpTab });
|
|
1029
|
+
});
|
|
1030
|
+
|
|
1031
|
+
chrome.tabs.onUpdated.addListener((tabId, changeInfo) => {
|
|
1032
|
+
if (mcpTabGroup.has(tabId)) {
|
|
1033
|
+
const info = mcpTabGroup.get(tabId);
|
|
1034
|
+
if (changeInfo.url) info.url = changeInfo.url;
|
|
1035
|
+
if (changeInfo.title) info.title = changeInfo.title;
|
|
1036
|
+
}
|
|
1037
|
+
});
|
|
1038
|
+
|
|
1039
|
+
// --- Message listener for popup & content scripts ----------------------------
|
|
1040
|
+
|
|
1041
|
+
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
|
|
1042
|
+
if (msg.type === "get_state") {
|
|
1043
|
+
sendResponse({
|
|
1044
|
+
state: connectionState,
|
|
1045
|
+
tabCount: mcpTabGroup.size,
|
|
1046
|
+
wsUrl: WS_URL,
|
|
1047
|
+
stats,
|
|
1048
|
+
});
|
|
1049
|
+
return true;
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
if (msg.type === "get_logs") {
|
|
1053
|
+
const since = msg.since || 0;
|
|
1054
|
+
sendResponse({
|
|
1055
|
+
logs: messageLog.filter((e) => e.ts > since),
|
|
1056
|
+
total: messageLog.length,
|
|
1057
|
+
});
|
|
1058
|
+
return true;
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
if (msg.type === "get_detailed_state") {
|
|
1062
|
+
sendResponse({
|
|
1063
|
+
state: connectionState,
|
|
1064
|
+
extVersion: EXT_VERSION,
|
|
1065
|
+
bridgeVersion: stats.bridgeVersion || "unknown",
|
|
1066
|
+
tabCount: mcpTabGroup.size,
|
|
1067
|
+
wsUrl: WS_URL,
|
|
1068
|
+
stats: { ...stats },
|
|
1069
|
+
tabs: Array.from(mcpTabGroup.values()),
|
|
1070
|
+
reconnectAttempts,
|
|
1071
|
+
logCount: messageLog.length,
|
|
1072
|
+
cfcInjectionMode,
|
|
1073
|
+
});
|
|
1074
|
+
return true;
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
if (msg.type === "reconnect") {
|
|
1078
|
+
reconnectAttempts = 0;
|
|
1079
|
+
clearTimeout(reconnectTimer);
|
|
1080
|
+
reconnectTimer = null;
|
|
1081
|
+
if (ws) {
|
|
1082
|
+
ws.close();
|
|
1083
|
+
ws = null;
|
|
1084
|
+
}
|
|
1085
|
+
connect();
|
|
1086
|
+
sendResponse({ ok: true });
|
|
1087
|
+
return true;
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
if (msg.type === "run_test") {
|
|
1091
|
+
runSelfTest(msg.testName)
|
|
1092
|
+
.then((result) => sendResponse(result))
|
|
1093
|
+
.catch((err) => sendResponse({ pass: false, error: err.message }));
|
|
1094
|
+
return true;
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
if (msg.type === "launch_bridge") {
|
|
1098
|
+
launchBridge()
|
|
1099
|
+
.then((result) => sendResponse(result))
|
|
1100
|
+
.catch((err) => sendResponse({ ok: false, error: err.message }));
|
|
1101
|
+
return true;
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
if (msg.type === "stop_bridge") {
|
|
1105
|
+
stopBridge()
|
|
1106
|
+
.then((result) => sendResponse(result))
|
|
1107
|
+
.catch((err) => sendResponse({ ok: false, error: err.message }));
|
|
1108
|
+
return true;
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
// --- Dev tool panel handlers -------------------------------------------------
|
|
1112
|
+
|
|
1113
|
+
if (msg.type === "get_network") {
|
|
1114
|
+
const tabs = [];
|
|
1115
|
+
chrome.tabs.query({ active: true, currentWindow: true }, (activeTabs) => {
|
|
1116
|
+
const tid = activeTabs[0]?.id;
|
|
1117
|
+
if (!tid) { sendResponse({ entries: [], count: 0 }); return; }
|
|
1118
|
+
const entries = networkRequests.get(tid) || [];
|
|
1119
|
+
sendResponse({ entries: entries.slice(-200), count: entries.length });
|
|
1120
|
+
});
|
|
1121
|
+
return true;
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
if (msg.type === "clear_network") {
|
|
1125
|
+
chrome.tabs.query({ active: true, currentWindow: true }, (activeTabs) => {
|
|
1126
|
+
const tid = activeTabs[0]?.id;
|
|
1127
|
+
if (tid) networkRequests.set(tid, []);
|
|
1128
|
+
sendResponse({ ok: true });
|
|
1129
|
+
});
|
|
1130
|
+
return true;
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
if (msg.type === "get_console") {
|
|
1134
|
+
chrome.tabs.query({ active: true, currentWindow: true }, (activeTabs) => {
|
|
1135
|
+
const tid = activeTabs[0]?.id;
|
|
1136
|
+
if (!tid) { sendResponse({ result: [], count: 0 }); return; }
|
|
1137
|
+
executeViaContentScript(tid, "read_console", {})
|
|
1138
|
+
.then((result) => sendResponse(result))
|
|
1139
|
+
.catch((err) => sendResponse({ result: [], error: err.message }));
|
|
1140
|
+
});
|
|
1141
|
+
return true;
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
if (msg.type === "clear_console") {
|
|
1145
|
+
chrome.tabs.query({ active: true, currentWindow: true }, (activeTabs) => {
|
|
1146
|
+
const tid = activeTabs[0]?.id;
|
|
1147
|
+
if (!tid) { sendResponse({ ok: false }); return; }
|
|
1148
|
+
executeViaContentScript(tid, "clear_console", {})
|
|
1149
|
+
.then((result) => sendResponse(result))
|
|
1150
|
+
.catch((err) => sendResponse({ error: err.message }));
|
|
1151
|
+
});
|
|
1152
|
+
return true;
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
if (msg.type === "get_storage") {
|
|
1156
|
+
chrome.tabs.query({ active: true, currentWindow: true }, (activeTabs) => {
|
|
1157
|
+
const tid = activeTabs[0]?.id;
|
|
1158
|
+
if (!tid) { sendResponse({ result: { localStorage: [], sessionStorage: [] } }); return; }
|
|
1159
|
+
executeViaContentScript(tid, "get_storage", {})
|
|
1160
|
+
.then((result) => sendResponse(result))
|
|
1161
|
+
.catch((err) => sendResponse({ error: err.message }));
|
|
1162
|
+
});
|
|
1163
|
+
return true;
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
if (msg.type === "get_cookies") {
|
|
1167
|
+
chrome.tabs.query({ active: true, currentWindow: true }, (activeTabs) => {
|
|
1168
|
+
const tabUrl = activeTabs[0]?.url;
|
|
1169
|
+
if (!tabUrl || tabUrl.startsWith("chrome://") || tabUrl.startsWith("edge://")) {
|
|
1170
|
+
sendResponse({ cookies: [] });
|
|
1171
|
+
return;
|
|
1172
|
+
}
|
|
1173
|
+
chrome.cookies.getAll({ url: tabUrl }, (cookies) => {
|
|
1174
|
+
sendResponse({
|
|
1175
|
+
cookies: (cookies || []).map((c) => ({
|
|
1176
|
+
name: c.name,
|
|
1177
|
+
value: c.value.length > 200 ? c.value.slice(0, 200) + "..." : c.value,
|
|
1178
|
+
domain: c.domain,
|
|
1179
|
+
path: c.path,
|
|
1180
|
+
secure: c.secure,
|
|
1181
|
+
httpOnly: c.httpOnly,
|
|
1182
|
+
expirationDate: c.expirationDate,
|
|
1183
|
+
})),
|
|
1184
|
+
});
|
|
1185
|
+
});
|
|
1186
|
+
});
|
|
1187
|
+
return true;
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
if (msg.type === "delete_storage_item") {
|
|
1191
|
+
const { storageType, key, domain, path, url } = msg;
|
|
1192
|
+
if (storageType === "cookie") {
|
|
1193
|
+
// Delete cookie via chrome.cookies API
|
|
1194
|
+
const cookieUrl = url || `https://${domain}${path || "/"}`;
|
|
1195
|
+
chrome.cookies.remove({ url: cookieUrl, name: key }, (details) => {
|
|
1196
|
+
sendResponse(details ? { ok: true } : { error: "Cookie not found" });
|
|
1197
|
+
});
|
|
1198
|
+
return true;
|
|
1199
|
+
}
|
|
1200
|
+
// Delegate to content script for localStorage/sessionStorage
|
|
1201
|
+
chrome.tabs.query({ active: true, currentWindow: true }, (activeTabs) => {
|
|
1202
|
+
const tid = activeTabs[0]?.id;
|
|
1203
|
+
if (!tid) { sendResponse({ error: "No active tab" }); return; }
|
|
1204
|
+
executeViaContentScript(tid, "delete_storage_item", { storageType, key })
|
|
1205
|
+
.then((result) => sendResponse(result))
|
|
1206
|
+
.catch((err) => sendResponse({ error: err.message }));
|
|
1207
|
+
});
|
|
1208
|
+
return true;
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
// Launcher page notifies us after the share completes — we poll as single source of truth
|
|
1212
|
+
if (msg.type === "bridge_launch_initiated") {
|
|
1213
|
+
addLog("info", "Bridge launch initiated via share");
|
|
1214
|
+
pollForBridgeStartup();
|
|
1215
|
+
sendResponse({ ok: true });
|
|
1216
|
+
return true;
|
|
1217
|
+
}
|
|
1218
|
+
});
|
|
1219
|
+
|
|
1220
|
+
// --- Self-test suite ---------------------------------------------------------
|
|
1221
|
+
|
|
1222
|
+
async function runSelfTest(testName) {
|
|
1223
|
+
const start = Date.now();
|
|
1224
|
+
try {
|
|
1225
|
+
switch (testName) {
|
|
1226
|
+
case "ws_connection": {
|
|
1227
|
+
return {
|
|
1228
|
+
pass: connectionState === "connected",
|
|
1229
|
+
detail: `State: ${connectionState}`,
|
|
1230
|
+
ms: Date.now() - start,
|
|
1231
|
+
};
|
|
1232
|
+
}
|
|
1233
|
+
case "bridge_health": {
|
|
1234
|
+
const resp = await fetch(BRIDGE_HEALTH_URL);
|
|
1235
|
+
const data = await resp.json();
|
|
1236
|
+
return {
|
|
1237
|
+
pass: data.status === "ok",
|
|
1238
|
+
detail: `nativeHost: ${data.nativeHost}, clients: ${data.clients}, uptime: ${Math.round(data.uptime)}s`,
|
|
1239
|
+
ms: Date.now() - start,
|
|
1240
|
+
data,
|
|
1241
|
+
};
|
|
1242
|
+
}
|
|
1243
|
+
case "tabs_query": {
|
|
1244
|
+
const tabs = await chrome.tabs.query({});
|
|
1245
|
+
return {
|
|
1246
|
+
pass: tabs.length > 0,
|
|
1247
|
+
detail: `${tabs.length} tabs found`,
|
|
1248
|
+
ms: Date.now() - start,
|
|
1249
|
+
};
|
|
1250
|
+
}
|
|
1251
|
+
case "tabs_context": {
|
|
1252
|
+
const result = await handleTabsContext({});
|
|
1253
|
+
const tabCount = result?.result?.tabs?.length || 0;
|
|
1254
|
+
return {
|
|
1255
|
+
pass: tabCount > 0,
|
|
1256
|
+
detail: `${tabCount} tabs in MCP group`,
|
|
1257
|
+
ms: Date.now() - start,
|
|
1258
|
+
};
|
|
1259
|
+
}
|
|
1260
|
+
case "navigate": {
|
|
1261
|
+
const tabs = await chrome.tabs.query({ active: true });
|
|
1262
|
+
const tid = tabs[0]?.id;
|
|
1263
|
+
if (!tid) return { pass: false, detail: "No active tab" };
|
|
1264
|
+
const result = await handleNavigate({ url: "http://127.0.0.1:18963/health", tabId: tid });
|
|
1265
|
+
return {
|
|
1266
|
+
pass: !!result?.result,
|
|
1267
|
+
detail: result?.result || result?.error,
|
|
1268
|
+
ms: Date.now() - start,
|
|
1269
|
+
};
|
|
1270
|
+
}
|
|
1271
|
+
case "js_exec": {
|
|
1272
|
+
const tabs = await chrome.tabs.query({ active: true });
|
|
1273
|
+
const tid = tabs[0]?.id;
|
|
1274
|
+
if (!tid) return { pass: false, detail: "No active tab" };
|
|
1275
|
+
const result = await handleJavascriptTool({ text: "1+1", tabId: tid });
|
|
1276
|
+
return {
|
|
1277
|
+
pass: result?.result === "2",
|
|
1278
|
+
detail: `Result: ${result?.result || result?.error}`,
|
|
1279
|
+
ms: Date.now() - start,
|
|
1280
|
+
};
|
|
1281
|
+
}
|
|
1282
|
+
case "read_page": {
|
|
1283
|
+
const tabs = await chrome.tabs.query({ active: true });
|
|
1284
|
+
const tid = tabs[0]?.id;
|
|
1285
|
+
if (!tid) return { pass: false, detail: "No active tab" };
|
|
1286
|
+
const result = await handleReadPage({ tabId: tid, depth: 3, max_chars: 1000 });
|
|
1287
|
+
const hasRefs = result?.result?.includes("[ref_");
|
|
1288
|
+
return {
|
|
1289
|
+
pass: hasRefs,
|
|
1290
|
+
detail: hasRefs ? `Got tree (${result.result.length} chars)` : (result?.error || "No refs found"),
|
|
1291
|
+
ms: Date.now() - start,
|
|
1292
|
+
};
|
|
1293
|
+
}
|
|
1294
|
+
case "screenshot": {
|
|
1295
|
+
try {
|
|
1296
|
+
const dataUrl = await chrome.tabs.captureVisibleTab(null, { format: "png" });
|
|
1297
|
+
return {
|
|
1298
|
+
pass: dataUrl?.startsWith("data:image"),
|
|
1299
|
+
detail: `Screenshot ${Math.round(dataUrl.length / 1024)}KB`,
|
|
1300
|
+
ms: Date.now() - start,
|
|
1301
|
+
};
|
|
1302
|
+
} catch (err) {
|
|
1303
|
+
return { pass: false, detail: err.message, ms: Date.now() - start };
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
case "tool_roundtrip": {
|
|
1307
|
+
if (connectionState !== "connected") {
|
|
1308
|
+
return { pass: false, detail: "Not connected to bridge" };
|
|
1309
|
+
}
|
|
1310
|
+
// Send ping and verify pong comes back
|
|
1311
|
+
const sent = sendMessage({ type: "ping" });
|
|
1312
|
+
return {
|
|
1313
|
+
pass: sent,
|
|
1314
|
+
detail: sent ? "Ping sent to bridge" : "Failed to send ping",
|
|
1315
|
+
ms: Date.now() - start,
|
|
1316
|
+
};
|
|
1317
|
+
}
|
|
1318
|
+
default:
|
|
1319
|
+
return { pass: false, detail: `Unknown test: ${testName}` };
|
|
1320
|
+
}
|
|
1321
|
+
} catch (err) {
|
|
1322
|
+
return { pass: false, error: err.message, ms: Date.now() - start };
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
|
|
1326
|
+
// --- Bridge launcher ---------------------------------------------------------
|
|
1327
|
+
|
|
1328
|
+
async function stopBridge() {
|
|
1329
|
+
addLog("info", "Requesting bridge shutdown");
|
|
1330
|
+
|
|
1331
|
+
// 1. Try graceful shutdown via POST /shutdown
|
|
1332
|
+
try {
|
|
1333
|
+
const ctrl = new AbortController();
|
|
1334
|
+
const timer = setTimeout(() => ctrl.abort(), 3000);
|
|
1335
|
+
await fetch("http://127.0.0.1:18963/shutdown", {
|
|
1336
|
+
method: "POST",
|
|
1337
|
+
signal: ctrl.signal,
|
|
1338
|
+
});
|
|
1339
|
+
clearTimeout(timer);
|
|
1340
|
+
} catch {
|
|
1341
|
+
// Timeout or bridge already dead — continue to verify
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
// 2. Wait, then verify bridge is actually dead via /health
|
|
1345
|
+
await new Promise((r) => setTimeout(r, 800));
|
|
1346
|
+
let stillAlive = false;
|
|
1347
|
+
try {
|
|
1348
|
+
const ctrl = new AbortController();
|
|
1349
|
+
const timer = setTimeout(() => ctrl.abort(), 1500);
|
|
1350
|
+
const resp = await fetch(BRIDGE_HEALTH_URL, { signal: ctrl.signal });
|
|
1351
|
+
clearTimeout(timer);
|
|
1352
|
+
stillAlive = resp.ok;
|
|
1353
|
+
} catch {
|
|
1354
|
+
// Health check failed = bridge is dead = success
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
// 3. Cleanup WS regardless
|
|
1358
|
+
if (ws) {
|
|
1359
|
+
ws.close();
|
|
1360
|
+
ws = null;
|
|
1361
|
+
}
|
|
1362
|
+
connectionState = "disconnected";
|
|
1363
|
+
clearTimeout(reconnectTimer);
|
|
1364
|
+
reconnectTimer = null;
|
|
1365
|
+
broadcastState();
|
|
1366
|
+
|
|
1367
|
+
if (stillAlive) {
|
|
1368
|
+
addLog("warn", "Bridge didn't stop gracefully — kill manually: pkill -f claude-chrome-bridge");
|
|
1369
|
+
return { ok: false, error: "Bridge didn't stop. Kill manually in Termux: pkill -f claude-chrome-bridge" };
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
addLog("info", "Bridge stopped successfully");
|
|
1373
|
+
return { ok: true, detail: "Bridge stopped" };
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
async function launchBridge() {
|
|
1377
|
+
addLog("info", "Attempting to launch bridge");
|
|
1378
|
+
|
|
1379
|
+
// Check if bridge is already running (fast 2s timeout)
|
|
1380
|
+
try {
|
|
1381
|
+
const ctrl = new AbortController();
|
|
1382
|
+
const timer = setTimeout(() => ctrl.abort(), 2000);
|
|
1383
|
+
const resp = await fetch(BRIDGE_HEALTH_URL, { signal: ctrl.signal });
|
|
1384
|
+
clearTimeout(timer);
|
|
1385
|
+
const data = await resp.json();
|
|
1386
|
+
if (data.status === "ok") {
|
|
1387
|
+
addLog("info", "Bridge already running — reconnecting");
|
|
1388
|
+
if (connectionState !== "connected") {
|
|
1389
|
+
reconnectAttempts = 0;
|
|
1390
|
+
connect();
|
|
1391
|
+
}
|
|
1392
|
+
return { ok: true, method: "already_running", detail: `Already running v${data.version}` };
|
|
1393
|
+
}
|
|
1394
|
+
} catch {
|
|
1395
|
+
addLog("info", "Bridge not responding — popup will fire deep-link");
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
// Try starting bridge via tmx daemon HTTP API (always-on, no share sheet needed)
|
|
1399
|
+
try {
|
|
1400
|
+
const daemonCtrl = new AbortController();
|
|
1401
|
+
const daemonTimer = setTimeout(() => daemonCtrl.abort(), 3000);
|
|
1402
|
+
const daemonResp = await fetch("http://127.0.0.1:18970/api/bridge", {
|
|
1403
|
+
method: "POST",
|
|
1404
|
+
signal: daemonCtrl.signal,
|
|
1405
|
+
});
|
|
1406
|
+
clearTimeout(daemonTimer);
|
|
1407
|
+
if (daemonResp.ok) {
|
|
1408
|
+
const data = await daemonResp.json();
|
|
1409
|
+
addLog("info", `Bridge start via daemon: ${data.status}`, data);
|
|
1410
|
+
if (data.status === "starting" || data.status === "already_running") {
|
|
1411
|
+
pollForBridgeStartup();
|
|
1412
|
+
return { ok: true, method: "daemon", detail: data.status };
|
|
1413
|
+
}
|
|
1414
|
+
}
|
|
1415
|
+
} catch {
|
|
1416
|
+
addLog("info", "Daemon not reachable — falling back to deep-link");
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
// Try TermuxService intent via daemon (creates a real Termux tab running the bridge)
|
|
1420
|
+
try {
|
|
1421
|
+
const tsCtrl = new AbortController();
|
|
1422
|
+
const tsTimer = setTimeout(() => tsCtrl.abort(), 5000);
|
|
1423
|
+
const tsResp = await fetch("http://127.0.0.1:18970/api/bridge/termux-service", {
|
|
1424
|
+
method: "POST",
|
|
1425
|
+
signal: tsCtrl.signal,
|
|
1426
|
+
});
|
|
1427
|
+
clearTimeout(tsTimer);
|
|
1428
|
+
if (tsResp.ok) {
|
|
1429
|
+
const data = await tsResp.json();
|
|
1430
|
+
addLog("info", `Bridge start via TermuxService: ${data.status}`, data);
|
|
1431
|
+
if (data.status === "starting") {
|
|
1432
|
+
pollForBridgeStartup();
|
|
1433
|
+
return { ok: true, method: "termux_service", detail: data.status };
|
|
1434
|
+
}
|
|
1435
|
+
}
|
|
1436
|
+
} catch {
|
|
1437
|
+
addLog("info", "TermuxService API not reachable — falling back to deep-link");
|
|
1438
|
+
}
|
|
1439
|
+
|
|
1440
|
+
// Deep-link is fired from popup.js (needs user gesture context for intent: URI).
|
|
1441
|
+
// Start background polling so we auto-connect when bridge comes up.
|
|
1442
|
+
pollForBridgeStartup();
|
|
1443
|
+
|
|
1444
|
+
return { ok: false, method: "needs_deeplink" };
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1447
|
+
/**
|
|
1448
|
+
* Poll for bridge startup in the background after a deep-link launch.
|
|
1449
|
+
* Runs in the service worker — doesn't depend on popup being open.
|
|
1450
|
+
* Auto-connects when bridge comes up.
|
|
1451
|
+
*/
|
|
1452
|
+
async function pollForBridgeStartup() {
|
|
1453
|
+
for (let i = 0; i < 8; i++) {
|
|
1454
|
+
await new Promise((r) => setTimeout(r, 1500));
|
|
1455
|
+
try {
|
|
1456
|
+
const ctrl = new AbortController();
|
|
1457
|
+
const timer = setTimeout(() => ctrl.abort(), 1500);
|
|
1458
|
+
const resp = await fetch(BRIDGE_HEALTH_URL, { signal: ctrl.signal });
|
|
1459
|
+
clearTimeout(timer);
|
|
1460
|
+
const data = await resp.json();
|
|
1461
|
+
if (data.status === "ok") {
|
|
1462
|
+
addLog("info", `Bridge started via deep-link: v${data.version}`);
|
|
1463
|
+
if (connectionState !== "connected") {
|
|
1464
|
+
reconnectAttempts = 0;
|
|
1465
|
+
connect();
|
|
1466
|
+
}
|
|
1467
|
+
return;
|
|
1468
|
+
}
|
|
1469
|
+
} catch { /* bridge not ready yet */ }
|
|
1470
|
+
}
|
|
1471
|
+
addLog("warn", "Deep-link sent but bridge didn't respond in 12s");
|
|
1472
|
+
}
|
|
1473
|
+
|
|
1474
|
+
// --- Startup -----------------------------------------------------------------
|
|
1475
|
+
|
|
1476
|
+
addLog("info", "Background page starting");
|
|
1477
|
+
// Delay initial connect slightly — MV2 background page may not have
|
|
1478
|
+
// WebSocket ready synchronously on first load (observed on Edge Android).
|
|
1479
|
+
// Also handles race when bridge starts after Edge.
|
|
1480
|
+
setTimeout(connect, 1000);
|
|
1481
|
+
|
|
1482
|
+
// Retry on chrome.runtime.onStartup (cold start / browser restart)
|
|
1483
|
+
chrome.runtime.onStartup.addListener(() => {
|
|
1484
|
+
addLog("info", "onStartup fired — ensuring WS connection");
|
|
1485
|
+
setTimeout(connect, 2000);
|
|
1486
|
+
});
|
|
1487
|
+
|
|
1488
|
+
// Retry on install/update
|
|
1489
|
+
chrome.runtime.onInstalled.addListener((details) => {
|
|
1490
|
+
addLog("info", `onInstalled: ${details.reason}`);
|
|
1491
|
+
setTimeout(connect, 1000);
|
|
1492
|
+
});
|