claude-chrome-android 1.6.0 → 1.7.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 +38 -0
- package/dist/claude-code-bridge.crx +0 -0
- package/dist/cli.js +457 -44
- package/dist/edge-claude-ext/background.js +22 -6
- package/dist/edge-claude-ext/content.js +13 -5
- package/dist/edge-claude-ext/manifest.json +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -159,9 +159,47 @@ The bridge serves the CRX at `http://127.0.0.1:18963/ext/crx` — open this URL
|
|
|
159
159
|
| `BRIDGE_TOKEN` | *(empty)* | Optional shared secret for auth |
|
|
160
160
|
| `BRIDGE_LOG_LEVEL` | `info` | debug, info, warn, error |
|
|
161
161
|
| `CDP_PORT` | `9223` | ADB forward port for Chrome DevTools Protocol |
|
|
162
|
+
| `BRIDGE_ADB_SERIAL` | *(this phone)* | adb serial of the device to automate. Unset, the bridge picks the attached device whose `boot_id` matches the phone it runs on, then the first one running Edge Canary |
|
|
163
|
+
| `BRIDGE_WAKE_FROZEN_TABS` | `1` | `0` makes tools fail fast on a tab Edge has frozen instead of briefly showing Edge to wake it |
|
|
164
|
+
|
|
165
|
+
## Working while Edge is in the background
|
|
166
|
+
|
|
167
|
+
Tools keep working when another app (Termux, a game, anything) is in front.
|
|
168
|
+
Android and Edge get in the way in three ways, and the bridge handles each:
|
|
169
|
+
|
|
170
|
+
1. **Android freezes Edge's tab processes** about 40–60 s after Edge leaves the
|
|
171
|
+
foreground. Before each tool the bridge exempts new ones with
|
|
172
|
+
`cmd activity unfreeze --sticky` over adb (once per process, at most every 10 s).
|
|
173
|
+
2. **Edge freezes some hidden pages itself**, often within a couple of minutes.
|
|
174
|
+
Such a page still answers synchronous `javascript_tool` code but runs no timers,
|
|
175
|
+
promises or extension page tools. The bridge checks the target page first and,
|
|
176
|
+
if it is frozen, wakes it: Edge shows for about a second, then the app you were
|
|
177
|
+
using comes back. It does not wake while the screen is off, the phone is
|
|
178
|
+
locked or a call is active, nor more than once every 5 s. In those cases (or
|
|
179
|
+
with `BRIDGE_WAKE_FROZEN_TABS=0`) page tools fail in about 2 s with the reason,
|
|
180
|
+
instead of timing out after 30 s.
|
|
181
|
+
3. **Hidden tabs are throttled**: timers fire about once a minute and
|
|
182
|
+
`requestAnimationFrame` never fires. Click and scroll results on a hidden tab
|
|
183
|
+
say so; re-read the page before relying on what the input changed.
|
|
184
|
+
|
|
185
|
+
Screenshots have to bring Edge forward to render a frame; the previously
|
|
186
|
+
focused app is restored afterwards. `GET /health` reports these layers under
|
|
187
|
+
`cdp.background` (renderers exempted, frozen pages found, wakes, skipped wakes
|
|
188
|
+
and the last reason).
|
|
162
189
|
|
|
163
190
|
## Changelog
|
|
164
191
|
|
|
192
|
+
### 1.7.0
|
|
193
|
+
|
|
194
|
+
- Tools work while Edge is not the foreground app: Edge's renderer processes are exempted from Android's cached-apps freezer; tabs Edge froze itself are detected and woken (screen on, unlocked, no call; refocuses the previous app), or fail in ~2 s with the reason (`BRIDGE_WAKE_FROZEN_TABS=0`)
|
|
195
|
+
- Tab ids always resolve to their own tab: an unknown URL is refreshed from the extension instead of falling back to the first page, and duplicate URLs prefer an unclaimed target
|
|
196
|
+
- Screenshots restore the previously focused app after `Page.bringToFront`; the adb screencap fallback refuses to capture another app
|
|
197
|
+
- adb device choice prefers the phone the bridge runs on (`boot_id` match) when several devices are attached
|
|
198
|
+
- Per-tool outcome and duration in the bridge log; background-layer counters in `/health`
|
|
199
|
+
- Extension 1.13.0: page requests no longer wait on a throttled timer, page-script waits fit inside the 30 s tool timeout, tab-less tools skip the per-tab queue, `navigate` reports a load that did not finish
|
|
200
|
+
|
|
201
|
+
### 1.6.0
|
|
202
|
+
|
|
165
203
|
### 1.6.0
|
|
166
204
|
|
|
167
205
|
- Direct Streamable-HTTP MCP transport on the bridge daemon (`POST /mcp`, stateless, origin/host checked, optional `BRIDGE_TOKEN` bearer auth) so Codex and other MCP clients connect without a per-session relay subprocess; the stdio relay (`--mcp`) answers `ping` and negotiates protocol version 2025-03-26
|
|
Binary file
|
package/dist/cli.js
CHANGED
|
@@ -72,6 +72,7 @@ var require_buffer_util = __commonJS({
|
|
|
72
72
|
"node_modules/ws/lib/buffer-util.js"(exports2, module2) {
|
|
73
73
|
"use strict";
|
|
74
74
|
init_import_meta_shim();
|
|
75
|
+
var { websocketMask, websocketUnmask } = require("http");
|
|
75
76
|
var { EMPTY_BUFFER } = require_constants();
|
|
76
77
|
var FastBuffer = Buffer[Symbol.species];
|
|
77
78
|
function concat(list, totalLength) {
|
|
@@ -126,7 +127,16 @@ var require_buffer_util = __commonJS({
|
|
|
126
127
|
toBuffer,
|
|
127
128
|
unmask: _unmask
|
|
128
129
|
};
|
|
129
|
-
if (
|
|
130
|
+
if (websocketMask) {
|
|
131
|
+
module2.exports.mask = function(source, mask, output, offset, length) {
|
|
132
|
+
if (length < 24) _mask(source, mask, output, offset, length);
|
|
133
|
+
else websocketMask(source, mask, output, offset, length);
|
|
134
|
+
};
|
|
135
|
+
module2.exports.unmask = function(buffer, mask) {
|
|
136
|
+
if (buffer.length < 24) _unmask(buffer, mask);
|
|
137
|
+
else websocketUnmask(buffer, mask);
|
|
138
|
+
};
|
|
139
|
+
} else if (!process.env.WS_NO_BUFFER_UTIL) {
|
|
130
140
|
try {
|
|
131
141
|
const bufferUtil = require("bufferutil");
|
|
132
142
|
module2.exports.mask = function(source, mask, output, offset, length) {
|
|
@@ -1193,6 +1203,7 @@ var require_receiver = __commonJS({
|
|
|
1193
1203
|
unmask(data, this._mask);
|
|
1194
1204
|
}
|
|
1195
1205
|
}
|
|
1206
|
+
this._mask = void 0;
|
|
1196
1207
|
if (this._opcode > 7) {
|
|
1197
1208
|
this.controlMessage(data, cb);
|
|
1198
1209
|
return;
|
|
@@ -1526,12 +1537,15 @@ var require_sender = __commonJS({
|
|
|
1526
1537
|
target[2] = target[3] = 0;
|
|
1527
1538
|
target.writeUIntBE(dataLength, 4, 6);
|
|
1528
1539
|
}
|
|
1529
|
-
if (!options.mask)
|
|
1540
|
+
if (!options.mask) {
|
|
1541
|
+
return dataLength ? [target, data] : [target];
|
|
1542
|
+
}
|
|
1530
1543
|
target[1] |= 128;
|
|
1531
1544
|
target[offset - 4] = mask[0];
|
|
1532
1545
|
target[offset - 3] = mask[1];
|
|
1533
1546
|
target[offset - 2] = mask[2];
|
|
1534
1547
|
target[offset - 1] = mask[3];
|
|
1548
|
+
if (!dataLength) return [target];
|
|
1535
1549
|
if (skipMasking) return [target, data];
|
|
1536
1550
|
if (merge) {
|
|
1537
1551
|
applyMask(data, mask, target, offset, dataLength);
|
|
@@ -2291,6 +2305,7 @@ var require_websocket = __commonJS({
|
|
|
2291
2305
|
var https = require("https");
|
|
2292
2306
|
var http2 = require("http");
|
|
2293
2307
|
var net = require("net");
|
|
2308
|
+
var querystring = require("querystring");
|
|
2294
2309
|
var tls = require("tls");
|
|
2295
2310
|
var { randomBytes, createHash } = require("crypto");
|
|
2296
2311
|
var { Duplex, Readable: Readable2 } = require("stream");
|
|
@@ -2369,12 +2384,17 @@ var require_websocket = __commonJS({
|
|
|
2369
2384
|
protocols = [protocols];
|
|
2370
2385
|
}
|
|
2371
2386
|
}
|
|
2372
|
-
initAsClient(this, address, protocols, options);
|
|
2387
|
+
options = initAsClient(this, address, protocols, options);
|
|
2373
2388
|
} else {
|
|
2374
|
-
this._autoPong = options.autoPong;
|
|
2375
|
-
this._closeTimeout = options.closeTimeout;
|
|
2376
2389
|
this._isServer = true;
|
|
2377
2390
|
}
|
|
2391
|
+
if (options.autoPong) {
|
|
2392
|
+
this._autoPong = true;
|
|
2393
|
+
this._autoPongComplete = () => autoPongComplete(this);
|
|
2394
|
+
this._pendingAutoPongs = 0;
|
|
2395
|
+
this._maxPendingAutoPongs = options.maxPendingAutoPongs | 0;
|
|
2396
|
+
}
|
|
2397
|
+
this._closeTimeout = options.closeTimeout;
|
|
2378
2398
|
}
|
|
2379
2399
|
/**
|
|
2380
2400
|
* For historical reasons, the custom "nodebuffer" type is used by the default
|
|
@@ -2785,6 +2805,7 @@ var require_websocket = __commonJS({
|
|
|
2785
2805
|
maxBufferedChunks: 256 * 1024,
|
|
2786
2806
|
maxFragments: 16 * 1024,
|
|
2787
2807
|
maxPayload: 100 * 1024 * 1024,
|
|
2808
|
+
maxPendingAutoPongs: 60,
|
|
2788
2809
|
skipUTF8Validation: false,
|
|
2789
2810
|
perMessageDeflate: true,
|
|
2790
2811
|
followRedirects: false,
|
|
@@ -2800,8 +2821,6 @@ var require_websocket = __commonJS({
|
|
|
2800
2821
|
path: void 0,
|
|
2801
2822
|
port: void 0
|
|
2802
2823
|
};
|
|
2803
|
-
websocket._autoPong = opts.autoPong;
|
|
2804
|
-
websocket._closeTimeout = opts.closeTimeout;
|
|
2805
2824
|
if (!protocolVersions.includes(opts.protocolVersion)) {
|
|
2806
2825
|
throw new RangeError(
|
|
2807
2826
|
`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
|
|
@@ -2817,10 +2836,9 @@ var require_websocket = __commonJS({
|
|
|
2817
2836
|
throw new SyntaxError(`Invalid URL: ${address}`);
|
|
2818
2837
|
}
|
|
2819
2838
|
}
|
|
2820
|
-
if (parsedUrl.protocol === "http:") {
|
|
2821
|
-
parsedUrl
|
|
2822
|
-
|
|
2823
|
-
parsedUrl.protocol = "wss:";
|
|
2839
|
+
if (parsedUrl.protocol === "http:" || parsedUrl.protocol === "https:") {
|
|
2840
|
+
parsedUrl = new URL2(parsedUrl);
|
|
2841
|
+
parsedUrl.protocol = parsedUrl.protocol === "http:" ? "ws:" : "wss:";
|
|
2824
2842
|
}
|
|
2825
2843
|
websocket._url = parsedUrl.href;
|
|
2826
2844
|
const isSecure = parsedUrl.protocol === "wss:";
|
|
@@ -2889,12 +2907,19 @@ var require_websocket = __commonJS({
|
|
|
2889
2907
|
}
|
|
2890
2908
|
}
|
|
2891
2909
|
if (parsedUrl.username || parsedUrl.password) {
|
|
2892
|
-
|
|
2910
|
+
const username = querystring.unescape(parsedUrl.username);
|
|
2911
|
+
const password = querystring.unescape(parsedUrl.password);
|
|
2912
|
+
opts.auth = `${username}:${password}`;
|
|
2893
2913
|
}
|
|
2894
2914
|
if (isIpcUrl) {
|
|
2895
|
-
const
|
|
2896
|
-
|
|
2897
|
-
|
|
2915
|
+
const i = opts.path.indexOf(":");
|
|
2916
|
+
if (i === -1) {
|
|
2917
|
+
opts.socketPath = opts.path;
|
|
2918
|
+
opts.path = "";
|
|
2919
|
+
} else {
|
|
2920
|
+
opts.socketPath = opts.path.slice(0, i);
|
|
2921
|
+
opts.path = opts.path.slice(i + 1);
|
|
2922
|
+
}
|
|
2898
2923
|
}
|
|
2899
2924
|
let req;
|
|
2900
2925
|
if (opts.followRedirects) {
|
|
@@ -3038,6 +3063,7 @@ var require_websocket = __commonJS({
|
|
|
3038
3063
|
} else {
|
|
3039
3064
|
req.end();
|
|
3040
3065
|
}
|
|
3066
|
+
return opts;
|
|
3041
3067
|
}
|
|
3042
3068
|
function emitErrorAndClose(websocket, err) {
|
|
3043
3069
|
websocket._readyState = WebSocket3.CLOSING;
|
|
@@ -3089,8 +3115,13 @@ var require_websocket = __commonJS({
|
|
|
3089
3115
|
function receiverOnConclude(code, reason) {
|
|
3090
3116
|
const websocket = this[kWebSocket];
|
|
3091
3117
|
websocket._closeFrameReceived = true;
|
|
3092
|
-
websocket._closeMessage = reason;
|
|
3093
3118
|
websocket._closeCode = code;
|
|
3119
|
+
if (reason.length === 0) {
|
|
3120
|
+
websocket._closeMessage = EMPTY_BUFFER;
|
|
3121
|
+
} else {
|
|
3122
|
+
websocket._closeMessage = Buffer.allocUnsafeSlow(reason.length);
|
|
3123
|
+
websocket._closeMessage.set(reason);
|
|
3124
|
+
}
|
|
3094
3125
|
if (websocket._socket[kWebSocket] === void 0) return;
|
|
3095
3126
|
websocket._socket.removeListener("data", socketOnData);
|
|
3096
3127
|
process.nextTick(resume, websocket._socket);
|
|
@@ -3121,9 +3152,19 @@ var require_websocket = __commonJS({
|
|
|
3121
3152
|
}
|
|
3122
3153
|
function receiverOnPing(data) {
|
|
3123
3154
|
const websocket = this[kWebSocket];
|
|
3124
|
-
if (websocket._autoPong
|
|
3155
|
+
if (websocket._autoPong && websocket.readyState === WebSocket3.OPEN) {
|
|
3156
|
+
if (websocket._maxPendingAutoPongs > 0 && websocket._pendingAutoPongs >= websocket._maxPendingAutoPongs) {
|
|
3157
|
+
websocket.terminate();
|
|
3158
|
+
} else {
|
|
3159
|
+
websocket._pendingAutoPongs++;
|
|
3160
|
+
websocket.pong(data, !this._isServer, websocket._autoPongComplete);
|
|
3161
|
+
}
|
|
3162
|
+
}
|
|
3125
3163
|
websocket.emit("ping", data);
|
|
3126
3164
|
}
|
|
3165
|
+
function autoPongComplete(websocket) {
|
|
3166
|
+
websocket._pendingAutoPongs--;
|
|
3167
|
+
}
|
|
3127
3168
|
function receiverOnPong(data) {
|
|
3128
3169
|
this[kWebSocket].emit("pong", data);
|
|
3129
3170
|
}
|
|
@@ -3380,6 +3421,8 @@ var require_websocket_server = __commonJS({
|
|
|
3380
3421
|
* fragments
|
|
3381
3422
|
* @param {Number} [options.maxPayload=104857600] The maximum allowed message
|
|
3382
3423
|
* size
|
|
3424
|
+
* @param {Number} [options.maxPendingAutoPongs=60] The maximum number of
|
|
3425
|
+
* pending automatic pongs
|
|
3383
3426
|
* @param {Boolean} [options.noServer=false] Enable no server mode
|
|
3384
3427
|
* @param {String} [options.path] Accept only connections matching this path
|
|
3385
3428
|
* @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
|
|
@@ -3402,6 +3445,7 @@ var require_websocket_server = __commonJS({
|
|
|
3402
3445
|
maxBufferedChunks: 256 * 1024,
|
|
3403
3446
|
maxFragments: 16 * 1024,
|
|
3404
3447
|
maxPayload: 100 * 1024 * 1024,
|
|
3448
|
+
maxPendingAutoPongs: 60,
|
|
3405
3449
|
skipUTF8Validation: false,
|
|
3406
3450
|
perMessageDeflate: false,
|
|
3407
3451
|
handleProtocols: null,
|
|
@@ -4045,6 +4089,17 @@ function getAdbSerial() {
|
|
|
4045
4089
|
_adbSerial = lines[0]?.split(" ")[0] ?? "";
|
|
4046
4090
|
return _adbSerial;
|
|
4047
4091
|
}
|
|
4092
|
+
const localBootId = readLocalBootId();
|
|
4093
|
+
if (localBootId) {
|
|
4094
|
+
for (const line of lines) {
|
|
4095
|
+
const serial = line.split(" ")[0];
|
|
4096
|
+
const check = runSync([ADB_PATH, "-s", serial, "shell", "cat", "/proc/sys/kernel/random/boot_id"], { timeoutMs: ADB_CALL_TIMEOUT_MS });
|
|
4097
|
+
if (check.exitCode === 0 && check.stdout.toString().trim() === localBootId) {
|
|
4098
|
+
_adbSerial = serial;
|
|
4099
|
+
return _adbSerial;
|
|
4100
|
+
}
|
|
4101
|
+
}
|
|
4102
|
+
}
|
|
4048
4103
|
for (const line of lines) {
|
|
4049
4104
|
const serial = line.split(" ")[0];
|
|
4050
4105
|
const check = runSync([ADB_PATH, "-s", serial, "shell", "pidof", "com.microsoft.emmx.canary"], { timeoutMs: ADB_CALL_TIMEOUT_MS });
|
|
@@ -4060,6 +4115,14 @@ function getAdbSerial() {
|
|
|
4060
4115
|
return _adbSerial;
|
|
4061
4116
|
}
|
|
4062
4117
|
}
|
|
4118
|
+
function readLocalBootId() {
|
|
4119
|
+
try {
|
|
4120
|
+
const { readFileSync: readFileSync2 } = require("fs");
|
|
4121
|
+
return readFileSync2("/proc/sys/kernel/random/boot_id", "utf-8").trim();
|
|
4122
|
+
} catch {
|
|
4123
|
+
return "";
|
|
4124
|
+
}
|
|
4125
|
+
}
|
|
4063
4126
|
function adb(...args) {
|
|
4064
4127
|
const serial = getAdbSerial();
|
|
4065
4128
|
return serial ? [ADB_PATH, "-s", serial, ...args] : [ADB_PATH, ...args];
|
|
@@ -4553,6 +4616,24 @@ function drainTabQueue(tabId) {
|
|
|
4553
4616
|
next.resolve({ type: "tool_response", error: "All bridge clients disconnected before dispatch" });
|
|
4554
4617
|
}
|
|
4555
4618
|
}
|
|
4619
|
+
function refreshTabUrlsFromExtension() {
|
|
4620
|
+
if (wsClients.size === 0) return Promise.resolve();
|
|
4621
|
+
const requestId = `req_${++toolRequestCounter}_${Date.now()}_tabs`;
|
|
4622
|
+
return new Promise((resolve3) => {
|
|
4623
|
+
const timeout = setTimeout(() => {
|
|
4624
|
+
pendingToolMap.delete(requestId);
|
|
4625
|
+
resolve3();
|
|
4626
|
+
}, TAB_URL_REFRESH_TIMEOUT_MS);
|
|
4627
|
+
pendingToolMap.set(requestId, { resolve: () => resolve3(), timeout, tabId: -1 });
|
|
4628
|
+
const request = JSON.stringify({ type: "tool_request", method: "tabs_context_mcp", params: {}, requestId });
|
|
4629
|
+
for (const client of wsClients) {
|
|
4630
|
+
try {
|
|
4631
|
+
client.send(request);
|
|
4632
|
+
} catch {
|
|
4633
|
+
}
|
|
4634
|
+
}
|
|
4635
|
+
});
|
|
4636
|
+
}
|
|
4556
4637
|
function spawnNativeHost() {
|
|
4557
4638
|
if (nativeHost) {
|
|
4558
4639
|
log("warn", "Native host already running, killing first");
|
|
@@ -4627,11 +4708,12 @@ function handleNativeMessage(json, reply = sendToNativeHost) {
|
|
|
4627
4708
|
outJson = JSON.stringify(parsed);
|
|
4628
4709
|
log("debug", `Unwrapped execute_tool \u2192 ${parsed.method}`);
|
|
4629
4710
|
}
|
|
4711
|
+
if (parsed.type === "tool_request") void cdpManager.thawRenderers();
|
|
4630
4712
|
if (parsed.type === "tool_request" && parsed.method === "javascript_tool" && cdpManager.isAvailable()) {
|
|
4631
4713
|
const code = parsed.params?.text ?? "";
|
|
4632
4714
|
const tabId = parsed.params?.tabId;
|
|
4633
4715
|
log("info", `CDP: intercepting javascript_tool (${code.slice(0, 80)})`);
|
|
4634
|
-
cdpManager.evaluateJS(code, tabId).then((cdpResult) => {
|
|
4716
|
+
cdpManager.ensurePageAwake(tabId).then(() => cdpManager.evaluateJS(code, tabId)).then((cdpResult) => {
|
|
4635
4717
|
const response = JSON.stringify({ type: "tool_response", result: cdpResult });
|
|
4636
4718
|
log("debug", `CDP\u2192native: ${response.slice(0, 200)}`);
|
|
4637
4719
|
try {
|
|
@@ -4677,6 +4759,12 @@ function handleNativeMessage(json, reply = sendToNativeHost) {
|
|
|
4677
4759
|
}
|
|
4678
4760
|
}
|
|
4679
4761
|
}
|
|
4762
|
+
} else if (cdpResult.final) {
|
|
4763
|
+
log("warn", `CDP screenshot failed: ${cdpResult.error}`);
|
|
4764
|
+
try {
|
|
4765
|
+
reply(JSON.stringify({ type: "tool_response", error: cdpResult.error }));
|
|
4766
|
+
} catch {
|
|
4767
|
+
}
|
|
4680
4768
|
} else {
|
|
4681
4769
|
log("warn", `CDP screenshot failed: ${cdpResult.error}`);
|
|
4682
4770
|
for (const client of wsClients) {
|
|
@@ -4705,6 +4793,13 @@ function handleNativeMessage(json, reply = sendToNativeHost) {
|
|
|
4705
4793
|
cdpManager.captureScreenshot(tabId).then((cdpResult) => {
|
|
4706
4794
|
if (!cdpResult.data) {
|
|
4707
4795
|
log("warn", `CDP zoom screenshot failed: ${cdpResult.error}`);
|
|
4796
|
+
if (cdpResult.final) {
|
|
4797
|
+
try {
|
|
4798
|
+
reply(JSON.stringify({ type: "tool_response", error: cdpResult.error }));
|
|
4799
|
+
} catch {
|
|
4800
|
+
}
|
|
4801
|
+
return;
|
|
4802
|
+
}
|
|
4708
4803
|
for (const client of wsClients) {
|
|
4709
4804
|
try {
|
|
4710
4805
|
client.send(outJson);
|
|
@@ -4775,12 +4870,13 @@ function handleNativeMessage(json, reply = sendToNativeHost) {
|
|
|
4775
4870
|
const action = parsed.params.action;
|
|
4776
4871
|
const tabId = parsed.params?.tabId;
|
|
4777
4872
|
log("info", `CDP: intercepting computer ${action} (tab ${tabId ?? "active"})`);
|
|
4778
|
-
cdpManager.dispatchComputerAction(action, parsed.params ?? {}, tabId).then((cdpResult) => {
|
|
4873
|
+
cdpManager.ensurePageAwake(tabId).then(() => cdpManager.dispatchComputerAction(action, parsed.params ?? {}, tabId)).then(async (cdpResult) => {
|
|
4779
4874
|
if (cdpResult.result) {
|
|
4875
|
+
const note = await cdpManager.hiddenTabNote(tabId);
|
|
4780
4876
|
try {
|
|
4781
4877
|
reply(JSON.stringify({
|
|
4782
4878
|
type: "tool_response",
|
|
4783
|
-
result: { result: cdpResult.result }
|
|
4879
|
+
result: { result: cdpResult.result + note }
|
|
4784
4880
|
}));
|
|
4785
4881
|
} catch (e) {
|
|
4786
4882
|
log("warn", `sendToNativeHost failed after CDP ${action}: ${e.message}`);
|
|
@@ -4856,6 +4952,30 @@ function handleNativeMessage(json, reply = sendToNativeHost) {
|
|
|
4856
4952
|
return;
|
|
4857
4953
|
}
|
|
4858
4954
|
}
|
|
4955
|
+
if (parsed.type === "tool_request" && EXTENSION_PAGE_TOOLS.has(parsed.method) && typeof parsed.params?.tabId === "number" && cdpManager.isAvailable()) {
|
|
4956
|
+
const tabId = parsed.params.tabId;
|
|
4957
|
+
void (async () => {
|
|
4958
|
+
const awake = await cdpManager.ensurePageAwake(tabId);
|
|
4959
|
+
if (!awake.ok) {
|
|
4960
|
+
log("warn", `${parsed.method}: tab ${tabId} is frozen by Edge and was not woken: ${awake.reason}`);
|
|
4961
|
+
try {
|
|
4962
|
+
reply(JSON.stringify({
|
|
4963
|
+
type: "tool_response",
|
|
4964
|
+
error: `Tab ${tabId} is frozen by Edge (hidden while Edge is not the foreground app), so its page cannot run ${parsed.method}, and it was not woken because ${awake.reason}. Select the tab in Edge or bring Edge to the front and retry; synchronous javascript_tool code and computer input still reach it.`
|
|
4965
|
+
}));
|
|
4966
|
+
} catch {
|
|
4967
|
+
}
|
|
4968
|
+
return;
|
|
4969
|
+
}
|
|
4970
|
+
for (const client of wsClients) {
|
|
4971
|
+
try {
|
|
4972
|
+
client.send(outJson);
|
|
4973
|
+
} catch {
|
|
4974
|
+
}
|
|
4975
|
+
}
|
|
4976
|
+
})();
|
|
4977
|
+
return;
|
|
4978
|
+
}
|
|
4859
4979
|
} catch {
|
|
4860
4980
|
}
|
|
4861
4981
|
for (const ws of wsClients) {
|
|
@@ -4901,7 +5021,7 @@ function shutdown() {
|
|
|
4901
5021
|
log("info", "Bridge stopped");
|
|
4902
5022
|
process.exit(0);
|
|
4903
5023
|
}
|
|
4904
|
-
var import_path, import_node_zlib, SCRIPT_DIR, MANIFEST_PATH, BRIDGE_VERSION, WS_PORT, WS_HOST, BRIDGE_TOKEN, MAX_MESSAGE_SIZE, RECONNECT_DELAY_MS, HEARTBEAT_INTERVAL_MS, TERMUX_PREFIX, TERMUX_BIN, ADB_PATH, _adbSerial, _adbSerialTs, ADB_SERIAL_TTL_MS, NATIVE_HOST_WRAPPER, BUN_GLOBAL_CLI, NPM_GLOBAL_CLI, CLI_PATH, RUNTIME_PATH, LOG_LEVEL, LOG_PRIORITY, NativeMessageDecoder, CDP_PORT, CDP_PID_CHECK_INTERVAL_MS, CDP_MAX_BACKOFF_ATTEMPTS, CDP_TARGET_CACHE_TTL_MS, CDP_TIMEOUT_MS, CdpManager, cdpManager, crc32Table, toolRequestCounter, pendingToolMap, busyTabs, HTTP_TOOL_TIMEOUT_MS, lastToolName, lastToolTime, nativeHost, nativeHostKillTimer, stdoutDecoder, wsClients, server, TEST_PAGE_HTML;
|
|
5024
|
+
var import_path, import_node_zlib, SCRIPT_DIR, MANIFEST_PATH, BRIDGE_VERSION, WS_PORT, WS_HOST, BRIDGE_TOKEN, MAX_MESSAGE_SIZE, RECONNECT_DELAY_MS, HEARTBEAT_INTERVAL_MS, TERMUX_PREFIX, TERMUX_BIN, ADB_PATH, _adbSerial, _adbSerialTs, ADB_SERIAL_TTL_MS, NATIVE_HOST_WRAPPER, BUN_GLOBAL_CLI, NPM_GLOBAL_CLI, CLI_PATH, RUNTIME_PATH, LOG_LEVEL, LOG_PRIORITY, NativeMessageDecoder, CDP_PORT, CDP_PID_CHECK_INTERVAL_MS, CDP_MAX_BACKOFF_ATTEMPTS, CDP_TARGET_CACHE_TTL_MS, CDP_TIMEOUT_MS, EDGE_RENDERER_PREFIX, RENDERER_THAW_INTERVAL_MS, RENDERER_THAW_TIMEOUT_MS, PAGE_PROBE_TIMEOUT_MS, WAKE_FROZEN_TABS, WAKE_MIN_INTERVAL_MS, MESSAGE_CHANNEL_PROBE, EXTENSION_PAGE_TOOLS, CdpManager, cdpManager, crc32Table, toolRequestCounter, pendingToolMap, busyTabs, HTTP_TOOL_TIMEOUT_MS, lastToolName, lastToolTime, nativeHost, nativeHostKillTimer, stdoutDecoder, wsClients, TAB_URL_REFRESH_TIMEOUT_MS, server, TEST_PAGE_HTML;
|
|
4905
5025
|
var init_claude_chrome_bridge = __esm({
|
|
4906
5026
|
"../claude-chrome-bridge.ts"() {
|
|
4907
5027
|
init_import_meta_shim();
|
|
@@ -4996,6 +5116,14 @@ var init_claude_chrome_bridge = __esm({
|
|
|
4996
5116
|
CDP_MAX_BACKOFF_ATTEMPTS = 10;
|
|
4997
5117
|
CDP_TARGET_CACHE_TTL_MS = 1e4;
|
|
4998
5118
|
CDP_TIMEOUT_MS = 15e3;
|
|
5119
|
+
EDGE_RENDERER_PREFIX = "com.microsoft.emmx.canary:sandboxed_process";
|
|
5120
|
+
RENDERER_THAW_INTERVAL_MS = 1e4;
|
|
5121
|
+
RENDERER_THAW_TIMEOUT_MS = 5e3;
|
|
5122
|
+
PAGE_PROBE_TIMEOUT_MS = 1500;
|
|
5123
|
+
WAKE_FROZEN_TABS = process.env.BRIDGE_WAKE_FROZEN_TABS !== "0";
|
|
5124
|
+
WAKE_MIN_INTERVAL_MS = 5e3;
|
|
5125
|
+
MESSAGE_CHANNEL_PROBE = "new Promise((r) => { const c = new MessageChannel(); c.port1.onmessage = () => r(1); c.port2.postMessage(0); })";
|
|
5126
|
+
EXTENSION_PAGE_TOOLS = /* @__PURE__ */ new Set(["get_page_text", "read_page", "find", "form_input"]);
|
|
4999
5127
|
CdpManager = class {
|
|
5000
5128
|
penBusy = false;
|
|
5001
5129
|
ws = null;
|
|
@@ -5236,7 +5364,9 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5236
5364
|
if (r.description) return { result: r.description };
|
|
5237
5365
|
return { result: String(r) };
|
|
5238
5366
|
} catch (err) {
|
|
5239
|
-
|
|
5367
|
+
const message = err.message;
|
|
5368
|
+
const hint = message.startsWith("CDP timeout") ? " (if the code awaited setTimeout, requestAnimationFrame or a MessageChannel-based library: a hidden tab \u2014 Edge not in the foreground \u2014 defers those; its side effects may still happen later)" : "";
|
|
5369
|
+
return { error: `CDP eval failed: ${message}${hint}` };
|
|
5240
5370
|
}
|
|
5241
5371
|
}
|
|
5242
5372
|
/** Resolve an extension tabId to a CDP targetId by URL matching */
|
|
@@ -5249,32 +5379,53 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5249
5379
|
return this.tabTargetMap.get(tabId);
|
|
5250
5380
|
}
|
|
5251
5381
|
if (tabId !== void 0) {
|
|
5252
|
-
|
|
5253
|
-
if (
|
|
5254
|
-
|
|
5255
|
-
|
|
5256
|
-
|
|
5257
|
-
log("debug", `CDP: resolveTarget(${tabId}) \u2192 URL match ${target.targetId.slice(0, 16)}... (${tabUrl})`);
|
|
5258
|
-
return target.targetId;
|
|
5259
|
-
}
|
|
5260
|
-
log("debug", `CDP: resolveTarget(${tabId}) \u2014 URL ${tabUrl} not found in ${this.cachedTargets.length} targets`);
|
|
5261
|
-
} else {
|
|
5262
|
-
log("debug", `CDP: resolveTarget(${tabId}) \u2014 no cached URL (cache size: ${this.tabUrlCache.size})`);
|
|
5382
|
+
let target = this.matchTabByUrl(tabId);
|
|
5383
|
+
if (!target && this.tabUrlRefresher) {
|
|
5384
|
+
await this.tabUrlRefresher();
|
|
5385
|
+
await this.refreshTargets();
|
|
5386
|
+
target = this.matchTabByUrl(tabId);
|
|
5263
5387
|
}
|
|
5388
|
+
if (target) {
|
|
5389
|
+
this.tabTargetMap.set(tabId, target);
|
|
5390
|
+
return target;
|
|
5391
|
+
}
|
|
5392
|
+
log("warn", `CDP: no target found for tab ${tabId} (url ${this.tabUrlCache.get(tabId) ?? "unknown"})`);
|
|
5393
|
+
return null;
|
|
5264
5394
|
}
|
|
5265
5395
|
const firstPage = this.cachedTargets.find((t) => t.type === "page");
|
|
5266
5396
|
log("debug", `CDP: resolveTarget(${tabId ?? "none"}) \u2192 fallback to first page: ${firstPage?.url ?? "none"}`);
|
|
5267
5397
|
return firstPage?.targetId ?? null;
|
|
5268
5398
|
}
|
|
5399
|
+
/** Asks the extension for current tab URLs (fills tabUrlCache); set by the server */
|
|
5400
|
+
tabUrlRefresher = null;
|
|
5401
|
+
setTabUrlRefresher(refresher) {
|
|
5402
|
+
this.tabUrlRefresher = refresher;
|
|
5403
|
+
}
|
|
5404
|
+
/**
|
|
5405
|
+
* Target for an extension tab by its cached URL. When several page targets
|
|
5406
|
+
* share the URL (the same page open twice), prefer one not already mapped to
|
|
5407
|
+
* a different tab.
|
|
5408
|
+
*/
|
|
5409
|
+
matchTabByUrl(tabId) {
|
|
5410
|
+
const tabUrl = this.tabUrlCache.get(tabId);
|
|
5411
|
+
if (!tabUrl) return null;
|
|
5412
|
+
const candidates = this.cachedTargets.filter((t) => t.url === tabUrl && t.type === "page");
|
|
5413
|
+
if (candidates.length === 0) return null;
|
|
5414
|
+
const claimed = new Set(
|
|
5415
|
+
[...this.tabTargetMap].filter(([otherTab]) => otherTab !== tabId).map(([, targetId]) => targetId)
|
|
5416
|
+
);
|
|
5417
|
+
return (candidates.find((t) => !claimed.has(t.targetId)) ?? candidates[0]).targetId;
|
|
5418
|
+
}
|
|
5269
5419
|
/** Fetch CDP targets via Target.getTargets (not /json/list — those IDs differ) */
|
|
5270
5420
|
async refreshTargets() {
|
|
5271
5421
|
try {
|
|
5272
5422
|
const result = await this.sendCommand("Target.getTargets");
|
|
5273
5423
|
this.cachedTargets = result.targetInfos;
|
|
5274
5424
|
this.targetsLastFetched = Date.now();
|
|
5275
|
-
for (const
|
|
5276
|
-
const target = this.
|
|
5277
|
-
if (target) this.tabTargetMap.set(tabId, target
|
|
5425
|
+
for (const tabId of this.tabUrlCache.keys()) {
|
|
5426
|
+
const target = this.matchTabByUrl(tabId);
|
|
5427
|
+
if (target) this.tabTargetMap.set(tabId, target);
|
|
5428
|
+
else this.tabTargetMap.delete(tabId);
|
|
5278
5429
|
}
|
|
5279
5430
|
} catch (err) {
|
|
5280
5431
|
log("debug", `CDP: refreshTargets failed \u2014 ${err.message}`);
|
|
@@ -5329,8 +5480,12 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5329
5480
|
* renderer surface (the actual page content), so it works even when the Edge
|
|
5330
5481
|
* app is backgrounded. `Page.bringToFront` is REQUIRED first: a backgrounded
|
|
5331
5482
|
* renderer has no compositor surface and `captureScreenshot` fails with
|
|
5332
|
-
* "Internal error" until the tab is the active one
|
|
5333
|
-
*
|
|
5483
|
+
* "Internal error" until the tab is the active one. bringToFront DOES bring
|
|
5484
|
+
* the Edge app to the foreground on Edge 154 Android (measured 2026-11-25:
|
|
5485
|
+
* focus moved from RustDesk and from Termux to ChromeTabbedActivity), so a
|
|
5486
|
+
* screenshot taken while the user is in another app briefly takes over the
|
|
5487
|
+
* screen; the previously focused activity is started again after capture
|
|
5488
|
+
* (not possible for the lock screen or notification shade).
|
|
5334
5489
|
*
|
|
5335
5490
|
* Fallback — ADB `screencap`: grabs the whole device screen (so Edge must be
|
|
5336
5491
|
* foregrounded to show the page). Used only when CDP is unavailable or the
|
|
@@ -5348,11 +5503,17 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5348
5503
|
sessionId = attach.sessionId;
|
|
5349
5504
|
this.sessionMap.set(targetId, sessionId);
|
|
5350
5505
|
}
|
|
5506
|
+
const before = this.readDeviceState();
|
|
5507
|
+
let shot;
|
|
5351
5508
|
try {
|
|
5352
|
-
|
|
5353
|
-
|
|
5509
|
+
try {
|
|
5510
|
+
await this.sendCommand("Page.bringToFront", {}, sessionId);
|
|
5511
|
+
} catch {
|
|
5512
|
+
}
|
|
5513
|
+
shot = await this.sendCommand("Page.captureScreenshot", { format: "png" }, sessionId);
|
|
5514
|
+
} finally {
|
|
5515
|
+
this.refocus(before.focus, "captured screenshot");
|
|
5354
5516
|
}
|
|
5355
|
-
const shot = await this.sendCommand("Page.captureScreenshot", { format: "png" }, sessionId);
|
|
5356
5517
|
if (shot?.data) {
|
|
5357
5518
|
log("info", `CDP: Page.captureScreenshot captured ~${Math.round(shot.data.length * 3 / 4)} bytes`);
|
|
5358
5519
|
return { data: normalizeScreenshot(shot.data) };
|
|
@@ -5363,11 +5524,22 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5363
5524
|
log("debug", `CDP: Page.captureScreenshot failed, falling back to ADB screencap \u2014 ${err.message}`);
|
|
5364
5525
|
}
|
|
5365
5526
|
}
|
|
5527
|
+
try {
|
|
5528
|
+
const focus = runSync(adb("shell", "dumpsys", "window"), { timeoutMs: 3e3 });
|
|
5529
|
+
const focusLine = focus.stdout.toString().split("\n").find((l) => l.includes("mCurrentFocus")) ?? "";
|
|
5530
|
+
if (focus.exitCode === 0 && !focusLine.includes("com.microsoft.emmx.canary")) {
|
|
5531
|
+
return {
|
|
5532
|
+
error: "Screenshot not available: CDP capture failed and Edge is not the foreground app, so ADB screencap would capture a different app",
|
|
5533
|
+
final: true
|
|
5534
|
+
};
|
|
5535
|
+
}
|
|
5536
|
+
} catch {
|
|
5537
|
+
}
|
|
5366
5538
|
try {
|
|
5367
5539
|
const tmpPath = "/data/data/com.termux/files/usr/tmp/cdp-screencap.png";
|
|
5368
|
-
const cap = runSync(adb("shell", "screencap", "-p", "/sdcard/cdp-screencap.png"));
|
|
5540
|
+
const cap = runSync(adb("shell", "screencap", "-p", "/sdcard/cdp-screencap.png"), { timeoutMs: 1e4 });
|
|
5369
5541
|
if (cap.exitCode === 0) {
|
|
5370
|
-
const pull = runSync(adb("pull", "/sdcard/cdp-screencap.png", tmpPath));
|
|
5542
|
+
const pull = runSync(adb("pull", "/sdcard/cdp-screencap.png", tmpPath), { timeoutMs: 1e4 });
|
|
5371
5543
|
if (pull.exitCode === 0 && await fileExists(tmpPath)) {
|
|
5372
5544
|
const { readFile: rf } = await import("node:fs/promises");
|
|
5373
5545
|
const buf = await rf(tmpPath);
|
|
@@ -5517,6 +5689,165 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5517
5689
|
return { error: `CDP input failed: ${err.message}` };
|
|
5518
5690
|
}
|
|
5519
5691
|
}
|
|
5692
|
+
/** Attached CDP session for an extension tab (or the active one), or null when it has no target */
|
|
5693
|
+
async sessionForTab(tabId) {
|
|
5694
|
+
const targetId = await this.resolveTarget(tabId);
|
|
5695
|
+
if (!targetId) return null;
|
|
5696
|
+
let sessionId = this.sessionMap.get(targetId);
|
|
5697
|
+
if (!sessionId) {
|
|
5698
|
+
const attach = await this.sendCommand("Target.attachToTarget", { targetId, flatten: true });
|
|
5699
|
+
sessionId = attach.sessionId;
|
|
5700
|
+
this.sessionMap.set(targetId, sessionId);
|
|
5701
|
+
}
|
|
5702
|
+
return sessionId;
|
|
5703
|
+
}
|
|
5704
|
+
/** Runtime.evaluate that gives up after `ms`; null means no answer in time */
|
|
5705
|
+
async evaluateWithin(sessionId, expression, awaitPromise, ms) {
|
|
5706
|
+
const call = this.sendCommand("Runtime.evaluate", { expression, returnByValue: true, awaitPromise }, sessionId).then((r) => r.result?.value ?? "undefined");
|
|
5707
|
+
const timeout = new Promise((resolve3) => setTimeout(() => resolve3(null), ms));
|
|
5708
|
+
return Promise.race([call, timeout]).catch(() => null);
|
|
5709
|
+
}
|
|
5710
|
+
/**
|
|
5711
|
+
* True when Edge has frozen the tab's page (Page Lifecycle "frozen"): it
|
|
5712
|
+
* still answers synchronous CDP evaluation, but its task queues are
|
|
5713
|
+
* suspended, so timers, MessageChannel and every extension content-script
|
|
5714
|
+
* request wait until the tab becomes visible. Observed on hidden tabs
|
|
5715
|
+
* within ~45 s to hours of Edge leaving the foreground, not on every tab;
|
|
5716
|
+
* neither Page.setWebLifecycleState nor the Chromium background-throttling
|
|
5717
|
+
* switches undo it (2026-11-27). False when the page answers, and also when
|
|
5718
|
+
* it does not even answer synchronously (an OS-frozen or dead renderer is a
|
|
5719
|
+
* different problem, handled by thawRenderers).
|
|
5720
|
+
*/
|
|
5721
|
+
async pageIsFrozen(tabId) {
|
|
5722
|
+
try {
|
|
5723
|
+
const sessionId = await this.sessionForTab(tabId);
|
|
5724
|
+
if (!sessionId) return false;
|
|
5725
|
+
if (await this.evaluateWithin(sessionId, "1", false, PAGE_PROBE_TIMEOUT_MS) === null) return false;
|
|
5726
|
+
return await this.evaluateWithin(sessionId, MESSAGE_CHANNEL_PROBE, true, PAGE_PROBE_TIMEOUT_MS) === null;
|
|
5727
|
+
} catch {
|
|
5728
|
+
return false;
|
|
5729
|
+
}
|
|
5730
|
+
}
|
|
5731
|
+
/** Counters for /health: how often each background layer was hit */
|
|
5732
|
+
backgroundStats = {
|
|
5733
|
+
renderersExempted: 0,
|
|
5734
|
+
sweepFailures: 0,
|
|
5735
|
+
frozenPagesDetected: 0,
|
|
5736
|
+
wakes: 0,
|
|
5737
|
+
wakesSkipped: 0,
|
|
5738
|
+
lastWakeSkipReason: null
|
|
5739
|
+
};
|
|
5740
|
+
lastWakeAt = 0;
|
|
5741
|
+
wakeInFlight = null;
|
|
5742
|
+
/**
|
|
5743
|
+
* One adb call for everything a wake decision needs: whether the screen is
|
|
5744
|
+
* on, whether the keyguard (lock screen) is showing, whether a phone call is
|
|
5745
|
+
* active, and the focused activity ("pkg/cls", or null for system windows
|
|
5746
|
+
* such as the notification shade).
|
|
5747
|
+
*/
|
|
5748
|
+
readDeviceState() {
|
|
5749
|
+
const out = runSync(adb(
|
|
5750
|
+
"shell",
|
|
5751
|
+
"dumpsys power | grep -m1 mWakefulness=; dumpsys window | grep -E -m2 'mCurrentFocus|isKeyguardShowing'; dumpsys telephony.registry | grep -m1 mCallState"
|
|
5752
|
+
), { timeoutMs: 4e3 }).stdout.toString();
|
|
5753
|
+
const focusLine = out.split("\n").find((l) => l.includes("mCurrentFocus")) ?? "";
|
|
5754
|
+
return {
|
|
5755
|
+
awake: /mWakefulness=Awake/.test(out),
|
|
5756
|
+
keyguard: /isKeyguardShowing=true/.test(out),
|
|
5757
|
+
inCall: /mCallState=[12]\b/.test(out),
|
|
5758
|
+
focus: /\s(\S+\/\S+)\}/.exec(focusLine)?.[1] ?? null
|
|
5759
|
+
};
|
|
5760
|
+
}
|
|
5761
|
+
/** Start the previously focused activity again after Edge was brought forward. */
|
|
5762
|
+
refocus(previous, why) {
|
|
5763
|
+
if (!previous || previous.startsWith("com.microsoft.emmx.canary/")) return;
|
|
5764
|
+
runSync(adb("shell", "am", "start", "-n", previous), { timeoutMs: 5e3 });
|
|
5765
|
+
log("info", `CDP: ${why}; refocused ${previous}`);
|
|
5766
|
+
}
|
|
5767
|
+
/**
|
|
5768
|
+
* Wake a frozen tab: Page.bringToFront makes it visible (Chromium resumes
|
|
5769
|
+
* it), which also brings the Edge app to the foreground, so afterwards the
|
|
5770
|
+
* previously focused activity is started again. Refuses (returns a reason)
|
|
5771
|
+
* when the screen is off, the lock screen is up or a call is active: the
|
|
5772
|
+
* restore could not return there, and taking over the screen mid-call is
|
|
5773
|
+
* worse than a failed tool. Concurrent requests share one wake, and wakes
|
|
5774
|
+
* are at least WAKE_MIN_INTERVAL_MS apart.
|
|
5775
|
+
*/
|
|
5776
|
+
async wakeFrozenTab(tabId) {
|
|
5777
|
+
if (this.wakeInFlight) return { ok: await this.wakeInFlight, reason: "shared wake" };
|
|
5778
|
+
if (Date.now() - this.lastWakeAt < WAKE_MIN_INTERVAL_MS) return this.skipWake("another wake ran under 5 s ago");
|
|
5779
|
+
const state = this.readDeviceState();
|
|
5780
|
+
if (!state.awake) return this.skipWake("the screen is off");
|
|
5781
|
+
if (state.keyguard) return this.skipWake("the phone is locked");
|
|
5782
|
+
if (state.inCall) return this.skipWake("a phone call is active");
|
|
5783
|
+
const sessionId = await this.sessionForTab(tabId);
|
|
5784
|
+
if (!sessionId) return this.skipWake("the tab has no CDP target");
|
|
5785
|
+
this.lastWakeAt = Date.now();
|
|
5786
|
+
this.wakeInFlight = (async () => {
|
|
5787
|
+
try {
|
|
5788
|
+
await this.sendCommand("Page.bringToFront", {}, sessionId);
|
|
5789
|
+
for (let i = 0; i < 6; i++) {
|
|
5790
|
+
if (await this.evaluateWithin(sessionId, MESSAGE_CHANNEL_PROBE, true, 500) !== null) return true;
|
|
5791
|
+
}
|
|
5792
|
+
return false;
|
|
5793
|
+
} catch {
|
|
5794
|
+
return false;
|
|
5795
|
+
} finally {
|
|
5796
|
+
this.refocus(state.focus, `woke frozen tab ${tabId ?? "active"}`);
|
|
5797
|
+
}
|
|
5798
|
+
})();
|
|
5799
|
+
try {
|
|
5800
|
+
const ok = await this.wakeInFlight;
|
|
5801
|
+
if (ok) this.backgroundStats.wakes++;
|
|
5802
|
+
return ok ? { ok } : { ok, reason: "the page did not resume after bringToFront" };
|
|
5803
|
+
} finally {
|
|
5804
|
+
this.wakeInFlight = null;
|
|
5805
|
+
}
|
|
5806
|
+
}
|
|
5807
|
+
skipWake(reason) {
|
|
5808
|
+
this.backgroundStats.wakesSkipped++;
|
|
5809
|
+
this.backgroundStats.lastWakeSkipReason = reason;
|
|
5810
|
+
return { ok: false, reason };
|
|
5811
|
+
}
|
|
5812
|
+
/**
|
|
5813
|
+
* Make sure a tab can run page work before a tool touches it: thaw Edge's
|
|
5814
|
+
* renderers (Android freezer), then, if Edge has frozen the page itself,
|
|
5815
|
+
* wake it (unless disabled or unsafe). `ok: false` carries why; callers that
|
|
5816
|
+
* only need synchronous CDP may proceed anyway.
|
|
5817
|
+
*/
|
|
5818
|
+
async ensurePageAwake(tabId) {
|
|
5819
|
+
await this.thawRenderers();
|
|
5820
|
+
if (!await this.pageIsFrozen(tabId)) return { ok: true, frozen: false };
|
|
5821
|
+
this.backgroundStats.frozenPagesDetected++;
|
|
5822
|
+
if (!WAKE_FROZEN_TABS) return { ok: false, frozen: true, reason: "waking is disabled (BRIDGE_WAKE_FROZEN_TABS=0)" };
|
|
5823
|
+
const woke = await this.wakeFrozenTab(tabId);
|
|
5824
|
+
return { ok: woke.ok, frozen: true, reason: woke.reason };
|
|
5825
|
+
}
|
|
5826
|
+
/**
|
|
5827
|
+
* A note to append to an input result when the tab is hidden (Edge is not
|
|
5828
|
+
* the foreground app). The input itself is delivered, but the page's timers
|
|
5829
|
+
* run about once a minute and requestAnimationFrame / MessageChannel tasks
|
|
5830
|
+
* stall, so handlers that continue through them (e.g. React's scheduler)
|
|
5831
|
+
* may not have updated the page yet. Returns "" for a visible tab or when
|
|
5832
|
+
* the check does not answer within 1.5 s.
|
|
5833
|
+
*/
|
|
5834
|
+
async hiddenTabNote(tabId) {
|
|
5835
|
+
try {
|
|
5836
|
+
const targetId = await this.resolveTarget(tabId);
|
|
5837
|
+
const sessionId = targetId ? this.sessionMap.get(targetId) : void 0;
|
|
5838
|
+
if (!sessionId) return "";
|
|
5839
|
+
const check = this.sendCommand("Runtime.evaluate", {
|
|
5840
|
+
expression: "document.visibilityState",
|
|
5841
|
+
returnByValue: true
|
|
5842
|
+
}, sessionId);
|
|
5843
|
+
const timeout = new Promise((resolve3) => setTimeout(() => resolve3(null), 1500));
|
|
5844
|
+
const r = await Promise.race([check, timeout]);
|
|
5845
|
+
if (r?.result?.value !== "hidden") return "";
|
|
5846
|
+
return " (tab hidden: Edge is not the foreground app, so page timers run about once a minute and animation frames do not run; the page may not have reacted yet, re-read it before relying on the result)";
|
|
5847
|
+
} catch {
|
|
5848
|
+
return "";
|
|
5849
|
+
}
|
|
5850
|
+
}
|
|
5520
5851
|
/** Parse modifier string like "ctrl+shift" into CDP modifier flags */
|
|
5521
5852
|
parseModifiers(mods) {
|
|
5522
5853
|
if (!mods) return {};
|
|
@@ -5613,9 +5944,74 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5613
5944
|
isAvailable() {
|
|
5614
5945
|
return this.state === "connected" && this.ws?.readyState === WebSocket.OPEN;
|
|
5615
5946
|
}
|
|
5947
|
+
/** Renderers already given a sticky unfreeze (it lasts their lifetime),
|
|
5948
|
+
* keyed "pid:starttime" so a reused pid is never mistaken for a handled one */
|
|
5949
|
+
thawedRenderers = /* @__PURE__ */ new Set();
|
|
5950
|
+
lastThawSweep = 0;
|
|
5951
|
+
thawInFlight = null;
|
|
5952
|
+
/**
|
|
5953
|
+
* Exempt Edge's tab renderers from Android's cached-apps freezer.
|
|
5954
|
+
*
|
|
5955
|
+
* When the Edge app is not in the foreground, Chromium drops its renderer
|
|
5956
|
+
* processes to cached priority and Android freezes them at the cgroup level
|
|
5957
|
+
* (cgroup.freeze=1) after ~40-60 s. A frozen renderer answers nothing: every
|
|
5958
|
+
* CDP Runtime/Input command and every extension content-script call for its
|
|
5959
|
+
* tabs waits until the 15 s / 30 s timeouts. `Page.setWebLifecycleState`
|
|
5960
|
+
* cannot reach it, and `Page.bringToFront` only works by foregrounding the
|
|
5961
|
+
* Edge app. `cmd activity unfreeze --sticky` (shell uid, via adb) thaws a
|
|
5962
|
+
* process and keeps it thawed for its lifetime, so each renderer needs it
|
|
5963
|
+
* once; later sweeps only pick up renderers spawned since.
|
|
5964
|
+
*
|
|
5965
|
+
* Callers do not need to await this: a command queued to a frozen renderer
|
|
5966
|
+
* runs as soon as the sweep thaws it (a healthy sweep takes ~70-200 ms).
|
|
5967
|
+
* Hidden-tab throttling still applies to a thawed tab: timers are batched to
|
|
5968
|
+
* about once a minute, and requestAnimationFrame / MessageChannel tasks did
|
|
5969
|
+
* not run within 8 s in measurements.
|
|
5970
|
+
*/
|
|
5971
|
+
thawRenderers() {
|
|
5972
|
+
if (this.thawInFlight) return this.thawInFlight;
|
|
5973
|
+
if (Date.now() - this.lastThawSweep < RENDERER_THAW_INTERVAL_MS) return Promise.resolve();
|
|
5974
|
+
this.lastThawSweep = Date.now();
|
|
5975
|
+
const skip = [...this.thawedRenderers].join(" ");
|
|
5976
|
+
const script = `for p in $(ps -A -o PID,NAME | awk '$2 ~ /^${EDGE_RENDERER_PREFIX.replace(/\./g, "\\.")}/ {print $1}'); do k="$p:$(cut -d' ' -f22 /proc/$p/stat 2>/dev/null)"; echo "live $k"; case " ${skip} " in *" $k "*) continue;; esac; cmd activity unfreeze --sticky "$p" >/dev/null 2>&1 && echo "thawed $k"; done; echo "sweep-done"`;
|
|
5977
|
+
this.thawInFlight = (async () => {
|
|
5978
|
+
try {
|
|
5979
|
+
const proc = spawnProcess(adb("shell", script));
|
|
5980
|
+
const timer = setTimeout(() => proc.kill(9), RENDERER_THAW_TIMEOUT_MS);
|
|
5981
|
+
const out = proc.stdout ? await new Response(proc.stdout).text() : "";
|
|
5982
|
+
const exitCode = await proc.exited;
|
|
5983
|
+
clearTimeout(timer);
|
|
5984
|
+
if (exitCode !== 0 || !out.includes("sweep-done")) {
|
|
5985
|
+
throw new Error(`adb shell exited ${exitCode}${out.includes("sweep-done") ? "" : ", sweep incomplete"}`);
|
|
5986
|
+
}
|
|
5987
|
+
const live = /* @__PURE__ */ new Set();
|
|
5988
|
+
const newlyThawed = [];
|
|
5989
|
+
for (const line of out.split("\n")) {
|
|
5990
|
+
const [kind, key] = line.trim().split(" ");
|
|
5991
|
+
if (!key || !/^\d+:\d+$/.test(key)) continue;
|
|
5992
|
+
if (kind === "live") live.add(key);
|
|
5993
|
+
else if (kind === "thawed") newlyThawed.push(key);
|
|
5994
|
+
}
|
|
5995
|
+
for (const key of this.thawedRenderers) if (!live.has(key)) this.thawedRenderers.delete(key);
|
|
5996
|
+
for (const key of newlyThawed) this.thawedRenderers.add(key);
|
|
5997
|
+
this.backgroundStats.renderersExempted += newlyThawed.length;
|
|
5998
|
+
if (newlyThawed.length) {
|
|
5999
|
+
log("info", `CDP: exempted Edge renderer(s) ${newlyThawed.map((k) => k.split(":")[0]).join(", ")} from the Android freezer`);
|
|
6000
|
+
}
|
|
6001
|
+
} catch (err) {
|
|
6002
|
+
this.lastThawSweep = 0;
|
|
6003
|
+
this.backgroundStats.sweepFailures++;
|
|
6004
|
+
log("warn", `CDP: renderer freezer sweep failed \u2014 ${err.message}; frozen tabs will time out until a sweep succeeds`);
|
|
6005
|
+
} finally {
|
|
6006
|
+
this.thawInFlight = null;
|
|
6007
|
+
}
|
|
6008
|
+
})();
|
|
6009
|
+
return this.thawInFlight;
|
|
6010
|
+
}
|
|
5616
6011
|
/** Get status info for /health endpoint */
|
|
5617
6012
|
getStatus() {
|
|
5618
6013
|
return {
|
|
6014
|
+
background: { ...this.backgroundStats, wakeFrozenTabs: WAKE_FROZEN_TABS, renderersTracked: this.thawedRenderers.size },
|
|
5619
6015
|
state: this.state,
|
|
5620
6016
|
edgePid: this.edgePid,
|
|
5621
6017
|
port: CDP_PORT,
|
|
@@ -5805,6 +6201,8 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5805
6201
|
nativeHostKillTimer = null;
|
|
5806
6202
|
stdoutDecoder = new NativeMessageDecoder();
|
|
5807
6203
|
wsClients = /* @__PURE__ */ new Set();
|
|
6204
|
+
TAB_URL_REFRESH_TIMEOUT_MS = 5e3;
|
|
6205
|
+
cdpManager.setTabUrlRefresher(refreshTabUrlsFromExtension);
|
|
5808
6206
|
server = createBridgeServer({
|
|
5809
6207
|
hostname: WS_HOST,
|
|
5810
6208
|
port: WS_PORT,
|
|
@@ -5842,6 +6240,7 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5842
6240
|
if (!params || typeof params !== "object" || Array.isArray(params)) throw new Error("Expected a stroke object");
|
|
5843
6241
|
lastToolName = "pen_stroke";
|
|
5844
6242
|
lastToolTime = (/* @__PURE__ */ new Date()).toISOString();
|
|
6243
|
+
await cdpManager.thawRenderers();
|
|
5845
6244
|
const result = await cdpManager.penStroke(params);
|
|
5846
6245
|
return Response.json({ result });
|
|
5847
6246
|
} catch (error) {
|
|
@@ -5994,7 +6393,8 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5994
6393
|
}
|
|
5995
6394
|
try {
|
|
5996
6395
|
const body = await req.json();
|
|
5997
|
-
const
|
|
6396
|
+
const toolStart = Date.now();
|
|
6397
|
+
const requestId = `req_${++toolRequestCounter}_${toolStart}`;
|
|
5998
6398
|
const tabId = body.params?.tabId || 0;
|
|
5999
6399
|
const toolRequest = JSON.stringify({
|
|
6000
6400
|
type: "tool_request",
|
|
@@ -6004,6 +6404,7 @@ var init_claude_chrome_bridge = __esm({
|
|
|
6004
6404
|
});
|
|
6005
6405
|
lastToolName = body.method;
|
|
6006
6406
|
lastToolTime = (/* @__PURE__ */ new Date()).toISOString();
|
|
6407
|
+
void cdpManager.thawRenderers();
|
|
6007
6408
|
if (body.method === "computer" && (body.params?.action === "screenshot" || body.params?.action === "zoom")) {
|
|
6008
6409
|
const action = body.params.action;
|
|
6009
6410
|
const shotTabId = body.params.tabId;
|
|
@@ -6036,6 +6437,12 @@ var init_claude_chrome_bridge = __esm({
|
|
|
6036
6437
|
{ headers: { "Content-Type": "application/json" } }
|
|
6037
6438
|
);
|
|
6038
6439
|
}
|
|
6440
|
+
if (shot.final) {
|
|
6441
|
+
return new Response(
|
|
6442
|
+
JSON.stringify({ type: "tool_response", error: shot.error }),
|
|
6443
|
+
{ headers: { "Content-Type": "application/json" } }
|
|
6444
|
+
);
|
|
6445
|
+
}
|
|
6039
6446
|
log("warn", `HTTP /tool: ADB screencap failed (${shot.error ?? "unknown"}); forwarding ${action} to extension`);
|
|
6040
6447
|
}
|
|
6041
6448
|
const MAX_PENDING_TOOLS = 50;
|
|
@@ -6082,6 +6489,12 @@ var init_claude_chrome_bridge = __esm({
|
|
|
6082
6489
|
}
|
|
6083
6490
|
}
|
|
6084
6491
|
});
|
|
6492
|
+
const toolError = result;
|
|
6493
|
+
const errText = toolError?.error ?? toolError?.result?.error;
|
|
6494
|
+
log(
|
|
6495
|
+
errText ? "warn" : "info",
|
|
6496
|
+
`HTTP /tool: ${body.method} [${requestId}] ${errText ? `failed: ${String(errText).slice(0, 160)}` : "ok"} in ${Date.now() - toolStart} ms`
|
|
6497
|
+
);
|
|
6085
6498
|
return new Response(
|
|
6086
6499
|
JSON.stringify(result),
|
|
6087
6500
|
{ headers: { "Content-Type": "application/json" } }
|
|
@@ -15,7 +15,13 @@ const RECONNECT_BASE_MS = 1000;
|
|
|
15
15
|
const RECONNECT_MAX_MS = 30000;
|
|
16
16
|
const KEEPALIVE_INTERVAL_MS = 20000;
|
|
17
17
|
const SCRIPTING_TIMEOUT_MS = 10000;
|
|
18
|
-
|
|
18
|
+
// Per attempt: the port request and its sendMessage fallback each get this
|
|
19
|
+
// long, so both together (24 s) finish inside the bridge's 30 s tool timeout.
|
|
20
|
+
// At 30 s each, a dead tab held its queue for 60 s after the caller had already
|
|
21
|
+
// been told "timed out", and every later request for that tab waited behind it.
|
|
22
|
+
const CONTENT_SCRIPT_TIMEOUT_MS = 12000;
|
|
23
|
+
/** Tools that never touch a tab's page; they must not wait in a tab's queue. */
|
|
24
|
+
const TAB_AGNOSTIC_TOOLS = new Set(["tabs_context_mcp", "tabs_create_mcp", "update_plan", "shortcuts_list"]);
|
|
19
25
|
|
|
20
26
|
// --- State -------------------------------------------------------------------
|
|
21
27
|
|
|
@@ -222,7 +228,10 @@ async function handleToolRequest(msg) {
|
|
|
222
228
|
});
|
|
223
229
|
}
|
|
224
230
|
|
|
225
|
-
// Queue tab-targeting tools so they execute sequentially per tab
|
|
231
|
+
// Queue tab-targeting tools so they execute sequentially per tab. Tab-less
|
|
232
|
+
// tools run at once: resolveTabId() falls back to the active MCP tab, which
|
|
233
|
+
// queued e.g. tabs_context_mcp behind a hung request on that tab.
|
|
234
|
+
if (TAB_AGNOSTIC_TOOLS.has(method)) return executeToolRequest(msg);
|
|
226
235
|
const tabId = resolveTabId(params?.tabId);
|
|
227
236
|
if (tabId != null) {
|
|
228
237
|
return enqueueToolForTab(tabId, () => executeToolRequest(msg));
|
|
@@ -367,21 +376,28 @@ async function handleNavigate(params) {
|
|
|
367
376
|
|
|
368
377
|
await chrome.tabs.update(tid, { url: fullUrl });
|
|
369
378
|
|
|
370
|
-
|
|
379
|
+
// Resolves true on load complete, false when the 15 s wait gives up (a slow
|
|
380
|
+
// page, or a hidden tab whose renderer is throttled while Edge is not the
|
|
381
|
+
// foreground app). Report the difference instead of claiming success.
|
|
382
|
+
const loaded = await new Promise((resolve) => {
|
|
371
383
|
const listener = (updatedTabId, changeInfo) => {
|
|
372
384
|
if (updatedTabId === tid && changeInfo.status === "complete") {
|
|
373
385
|
chrome.tabs.onUpdated.removeListener(listener);
|
|
374
|
-
resolve();
|
|
386
|
+
resolve(true);
|
|
375
387
|
}
|
|
376
388
|
};
|
|
377
389
|
chrome.tabs.onUpdated.addListener(listener);
|
|
378
390
|
setTimeout(() => {
|
|
379
391
|
chrome.tabs.onUpdated.removeListener(listener);
|
|
380
|
-
resolve();
|
|
392
|
+
resolve(false);
|
|
381
393
|
}, 15000);
|
|
382
394
|
});
|
|
383
395
|
|
|
384
|
-
return {
|
|
396
|
+
return {
|
|
397
|
+
result: loaded
|
|
398
|
+
? `Navigated to ${fullUrl}`
|
|
399
|
+
: `Navigation to ${fullUrl} started, but the page had not finished loading after 15 s; re-read it before relying on its content`,
|
|
400
|
+
};
|
|
385
401
|
}
|
|
386
402
|
|
|
387
403
|
async function handleFormInput(params) {
|
|
@@ -89,8 +89,11 @@ function connectPort() {
|
|
|
89
89
|
|
|
90
90
|
port.onMessage.addListener((msg) => {
|
|
91
91
|
if (!msg.action || !msg._reqId) return;
|
|
92
|
-
// Decouple from port message handler
|
|
93
|
-
|
|
92
|
+
// Decouple from the port message handler. A microtask, not setTimeout(0):
|
|
93
|
+
// while Edge is not the foreground app the tab is hidden and Chromium runs
|
|
94
|
+
// its timers about once a minute, so a timer-deferred request outlived the
|
|
95
|
+
// bridge's 30 s tool timeout (and still ran afterwards).
|
|
96
|
+
queueMicrotask(() => {
|
|
94
97
|
handleAction(msg.action, msg.params || {})
|
|
95
98
|
.then((result) => {
|
|
96
99
|
try { port.postMessage({ _reqId: msg._reqId, result }); } catch {}
|
|
@@ -98,7 +101,7 @@ function connectPort() {
|
|
|
98
101
|
.catch((err) => {
|
|
99
102
|
try { port.postMessage({ _reqId: msg._reqId, result: { error: err.message || String(err) } }); } catch {}
|
|
100
103
|
});
|
|
101
|
-
}
|
|
104
|
+
});
|
|
102
105
|
});
|
|
103
106
|
|
|
104
107
|
port.onDisconnect.addListener(() => {
|
|
@@ -117,11 +120,12 @@ connectPort();
|
|
|
117
120
|
// Keep legacy onMessage as fallback for backward compatibility
|
|
118
121
|
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
|
|
119
122
|
if (!msg.action) return;
|
|
120
|
-
|
|
123
|
+
// Microtask for the same reason as the port handler above.
|
|
124
|
+
queueMicrotask(() => {
|
|
121
125
|
handleAction(msg.action, msg.params || {})
|
|
122
126
|
.then((result) => { try { sendResponse(result); } catch {} })
|
|
123
127
|
.catch((err) => { try { sendResponse({ error: err.message || String(err) }); } catch {} });
|
|
124
|
-
}
|
|
128
|
+
});
|
|
125
129
|
return true;
|
|
126
130
|
});
|
|
127
131
|
|
|
@@ -489,6 +493,10 @@ function formInput(params) {
|
|
|
489
493
|
*/
|
|
490
494
|
const MAIN_WORLD_TIMEOUT_MS = 5000;
|
|
491
495
|
|
|
496
|
+
// TODO: the result comes back through window.postMessage, which a hidden tab
|
|
497
|
+
// (Edge not in the foreground) may defer like its timers and MessageChannel;
|
|
498
|
+
// measure it before relying on this path while Edge is backgrounded. It only
|
|
499
|
+
// runs when the bridge has no CDP connection.
|
|
492
500
|
function executeInMainWorld(code) {
|
|
493
501
|
return new Promise((resolve, reject) => {
|
|
494
502
|
const id = (crypto?.randomUUID && crypto.randomUUID()) ||
|
package/package.json
CHANGED