claude-chrome-android 1.6.0 → 1.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +45 -0
- package/dist/claude-code-bridge.crx +0 -0
- package/dist/cli.js +526 -68
- 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 +6 -7
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Will Stone
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -159,9 +159,54 @@ 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.1
|
|
193
|
+
|
|
194
|
+
- After waking a tab or taking a screenshot, the bridge brings back the task that was in front through its root package's launcher intent. Starting the focused activity by component left Edge on top of apps that run inside another app's task, such as a Chrome web app
|
|
195
|
+
- Bundles `ws` 8.23.0 (fixes GHSA-96hv-2xvq-fx4p memory-exhaustion DoS and GHSA-58qx-3vcg-4xpx uninitialised-memory disclosure in the bridge's WebSocket server); builds with esbuild 0.28; drops the unused `@anthropic-ai/claude-code` dev dependency
|
|
196
|
+
- The package now ships its MIT `LICENSE`
|
|
197
|
+
- Extension 1.13.1: the CRX contains only the files Edge loads (no store listing, privacy or tester notes); built with crx3 2.0
|
|
198
|
+
|
|
199
|
+
### 1.7.0
|
|
200
|
+
|
|
201
|
+
- 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`)
|
|
202
|
+
- 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
|
|
203
|
+
- Screenshots restore the previously focused app after `Page.bringToFront`; the adb screencap fallback refuses to capture another app
|
|
204
|
+
- adb device choice prefers the phone the bridge runs on (`boot_id` match) when several devices are attached
|
|
205
|
+
- Per-tool outcome and duration in the bridge log; background-layer counters in `/health`
|
|
206
|
+
- 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
|
|
207
|
+
|
|
208
|
+
### 1.6.0
|
|
209
|
+
|
|
165
210
|
### 1.6.0
|
|
166
211
|
|
|
167
212
|
- 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
|
@@ -6,11 +6,20 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
|
6
6
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
7
|
var __getProtoOf = Object.getPrototypeOf;
|
|
8
8
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
-
var __esm = (fn, res) => function __init() {
|
|
10
|
-
|
|
9
|
+
var __esm = (fn, res, err) => function __init() {
|
|
10
|
+
if (err) throw err[0];
|
|
11
|
+
try {
|
|
12
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
13
|
+
} catch (e) {
|
|
14
|
+
throw err = [e], e;
|
|
15
|
+
}
|
|
11
16
|
};
|
|
12
17
|
var __commonJS = (cb, mod) => function __require() {
|
|
13
|
-
|
|
18
|
+
try {
|
|
19
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
20
|
+
} catch (e) {
|
|
21
|
+
throw mod = 0, e;
|
|
22
|
+
}
|
|
14
23
|
};
|
|
15
24
|
var __export = (target, all) => {
|
|
16
25
|
for (var name in all)
|
|
@@ -57,10 +66,10 @@ var require_constants = __commonJS({
|
|
|
57
66
|
EMPTY_BUFFER: Buffer.alloc(0),
|
|
58
67
|
GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
|
|
59
68
|
hasBlob,
|
|
60
|
-
kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
|
|
61
|
-
kListener: Symbol("kListener"),
|
|
62
|
-
kStatusCode: Symbol("status-code"),
|
|
63
|
-
kWebSocket: Symbol("websocket"),
|
|
69
|
+
kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
|
|
70
|
+
kListener: /* @__PURE__ */ Symbol("kListener"),
|
|
71
|
+
kStatusCode: /* @__PURE__ */ Symbol("status-code"),
|
|
72
|
+
kWebSocket: /* @__PURE__ */ Symbol("websocket"),
|
|
64
73
|
NOOP: () => {
|
|
65
74
|
}
|
|
66
75
|
};
|
|
@@ -72,6 +81,7 @@ var require_buffer_util = __commonJS({
|
|
|
72
81
|
"node_modules/ws/lib/buffer-util.js"(exports2, module2) {
|
|
73
82
|
"use strict";
|
|
74
83
|
init_import_meta_shim();
|
|
84
|
+
var { websocketMask, websocketUnmask } = require("http");
|
|
75
85
|
var { EMPTY_BUFFER } = require_constants();
|
|
76
86
|
var FastBuffer = Buffer[Symbol.species];
|
|
77
87
|
function concat(list, totalLength) {
|
|
@@ -126,7 +136,16 @@ var require_buffer_util = __commonJS({
|
|
|
126
136
|
toBuffer,
|
|
127
137
|
unmask: _unmask
|
|
128
138
|
};
|
|
129
|
-
if (
|
|
139
|
+
if (websocketMask) {
|
|
140
|
+
module2.exports.mask = function(source, mask, output, offset, length) {
|
|
141
|
+
if (length < 24) _mask(source, mask, output, offset, length);
|
|
142
|
+
else websocketMask(source, mask, output, offset, length);
|
|
143
|
+
};
|
|
144
|
+
module2.exports.unmask = function(buffer, mask) {
|
|
145
|
+
if (buffer.length < 24) _unmask(buffer, mask);
|
|
146
|
+
else websocketUnmask(buffer, mask);
|
|
147
|
+
};
|
|
148
|
+
} else if (!process.env.WS_NO_BUFFER_UTIL) {
|
|
130
149
|
try {
|
|
131
150
|
const bufferUtil = require("bufferutil");
|
|
132
151
|
module2.exports.mask = function(source, mask, output, offset, length) {
|
|
@@ -148,8 +167,8 @@ var require_limiter = __commonJS({
|
|
|
148
167
|
"node_modules/ws/lib/limiter.js"(exports2, module2) {
|
|
149
168
|
"use strict";
|
|
150
169
|
init_import_meta_shim();
|
|
151
|
-
var kDone = Symbol("kDone");
|
|
152
|
-
var kRun = Symbol("kRun");
|
|
170
|
+
var kDone = /* @__PURE__ */ Symbol("kDone");
|
|
171
|
+
var kRun = /* @__PURE__ */ Symbol("kRun");
|
|
153
172
|
var Limiter = class {
|
|
154
173
|
/**
|
|
155
174
|
* Creates a new `Limiter`.
|
|
@@ -205,11 +224,11 @@ var require_permessage_deflate = __commonJS({
|
|
|
205
224
|
var { kStatusCode } = require_constants();
|
|
206
225
|
var FastBuffer = Buffer[Symbol.species];
|
|
207
226
|
var TRAILER = Buffer.from([0, 0, 255, 255]);
|
|
208
|
-
var kPerMessageDeflate = Symbol("permessage-deflate");
|
|
209
|
-
var kTotalLength = Symbol("total-length");
|
|
210
|
-
var kCallback = Symbol("callback");
|
|
211
|
-
var kBuffers = Symbol("buffers");
|
|
212
|
-
var kError = Symbol("error");
|
|
227
|
+
var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
|
|
228
|
+
var kTotalLength = /* @__PURE__ */ Symbol("total-length");
|
|
229
|
+
var kCallback = /* @__PURE__ */ Symbol("callback");
|
|
230
|
+
var kBuffers = /* @__PURE__ */ Symbol("buffers");
|
|
231
|
+
var kError = /* @__PURE__ */ Symbol("error");
|
|
213
232
|
var zlibLimiter;
|
|
214
233
|
var PerMessageDeflate2 = class {
|
|
215
234
|
/**
|
|
@@ -1193,6 +1212,7 @@ var require_receiver = __commonJS({
|
|
|
1193
1212
|
unmask(data, this._mask);
|
|
1194
1213
|
}
|
|
1195
1214
|
}
|
|
1215
|
+
this._mask = void 0;
|
|
1196
1216
|
if (this._opcode > 7) {
|
|
1197
1217
|
this.controlMessage(data, cb);
|
|
1198
1218
|
return;
|
|
@@ -1418,7 +1438,7 @@ var require_sender = __commonJS({
|
|
|
1418
1438
|
var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
|
|
1419
1439
|
var { isBlob, isValidStatusCode } = require_validation();
|
|
1420
1440
|
var { mask: applyMask, toBuffer } = require_buffer_util();
|
|
1421
|
-
var kByteLength = Symbol("kByteLength");
|
|
1441
|
+
var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
|
|
1422
1442
|
var maskBuffer = Buffer.alloc(4);
|
|
1423
1443
|
var RANDOM_POOL_SIZE = 8 * 1024;
|
|
1424
1444
|
var randomPool;
|
|
@@ -1526,12 +1546,15 @@ var require_sender = __commonJS({
|
|
|
1526
1546
|
target[2] = target[3] = 0;
|
|
1527
1547
|
target.writeUIntBE(dataLength, 4, 6);
|
|
1528
1548
|
}
|
|
1529
|
-
if (!options.mask)
|
|
1549
|
+
if (!options.mask) {
|
|
1550
|
+
return dataLength ? [target, data] : [target];
|
|
1551
|
+
}
|
|
1530
1552
|
target[1] |= 128;
|
|
1531
1553
|
target[offset - 4] = mask[0];
|
|
1532
1554
|
target[offset - 3] = mask[1];
|
|
1533
1555
|
target[offset - 2] = mask[2];
|
|
1534
1556
|
target[offset - 1] = mask[3];
|
|
1557
|
+
if (!dataLength) return [target];
|
|
1535
1558
|
if (skipMasking) return [target, data];
|
|
1536
1559
|
if (merge) {
|
|
1537
1560
|
applyMask(data, mask, target, offset, dataLength);
|
|
@@ -1904,14 +1927,14 @@ var require_event_target = __commonJS({
|
|
|
1904
1927
|
"use strict";
|
|
1905
1928
|
init_import_meta_shim();
|
|
1906
1929
|
var { kForOnEventAttribute, kListener } = require_constants();
|
|
1907
|
-
var kCode = Symbol("kCode");
|
|
1908
|
-
var kData = Symbol("kData");
|
|
1909
|
-
var kError = Symbol("kError");
|
|
1910
|
-
var kMessage = Symbol("kMessage");
|
|
1911
|
-
var kReason = Symbol("kReason");
|
|
1912
|
-
var kTarget = Symbol("kTarget");
|
|
1913
|
-
var kType = Symbol("kType");
|
|
1914
|
-
var kWasClean = Symbol("kWasClean");
|
|
1930
|
+
var kCode = /* @__PURE__ */ Symbol("kCode");
|
|
1931
|
+
var kData = /* @__PURE__ */ Symbol("kData");
|
|
1932
|
+
var kError = /* @__PURE__ */ Symbol("kError");
|
|
1933
|
+
var kMessage = /* @__PURE__ */ Symbol("kMessage");
|
|
1934
|
+
var kReason = /* @__PURE__ */ Symbol("kReason");
|
|
1935
|
+
var kTarget = /* @__PURE__ */ Symbol("kTarget");
|
|
1936
|
+
var kType = /* @__PURE__ */ Symbol("kType");
|
|
1937
|
+
var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
|
|
1915
1938
|
var Event = class {
|
|
1916
1939
|
/**
|
|
1917
1940
|
* Create a new `Event`.
|
|
@@ -2291,6 +2314,7 @@ var require_websocket = __commonJS({
|
|
|
2291
2314
|
var https = require("https");
|
|
2292
2315
|
var http2 = require("http");
|
|
2293
2316
|
var net = require("net");
|
|
2317
|
+
var querystring = require("querystring");
|
|
2294
2318
|
var tls = require("tls");
|
|
2295
2319
|
var { randomBytes, createHash } = require("crypto");
|
|
2296
2320
|
var { Duplex, Readable: Readable2 } = require("stream");
|
|
@@ -2315,7 +2339,7 @@ var require_websocket = __commonJS({
|
|
|
2315
2339
|
} = require_event_target();
|
|
2316
2340
|
var { format, parse } = require_extension();
|
|
2317
2341
|
var { toBuffer } = require_buffer_util();
|
|
2318
|
-
var kAborted = Symbol("kAborted");
|
|
2342
|
+
var kAborted = /* @__PURE__ */ Symbol("kAborted");
|
|
2319
2343
|
var protocolVersions = [8, 13];
|
|
2320
2344
|
var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
|
|
2321
2345
|
var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
|
|
@@ -2369,12 +2393,17 @@ var require_websocket = __commonJS({
|
|
|
2369
2393
|
protocols = [protocols];
|
|
2370
2394
|
}
|
|
2371
2395
|
}
|
|
2372
|
-
initAsClient(this, address, protocols, options);
|
|
2396
|
+
options = initAsClient(this, address, protocols, options);
|
|
2373
2397
|
} else {
|
|
2374
|
-
this._autoPong = options.autoPong;
|
|
2375
|
-
this._closeTimeout = options.closeTimeout;
|
|
2376
2398
|
this._isServer = true;
|
|
2377
2399
|
}
|
|
2400
|
+
if (options.autoPong) {
|
|
2401
|
+
this._autoPong = true;
|
|
2402
|
+
this._autoPongComplete = () => autoPongComplete(this);
|
|
2403
|
+
this._pendingAutoPongs = 0;
|
|
2404
|
+
this._maxPendingAutoPongs = options.maxPendingAutoPongs | 0;
|
|
2405
|
+
}
|
|
2406
|
+
this._closeTimeout = options.closeTimeout;
|
|
2378
2407
|
}
|
|
2379
2408
|
/**
|
|
2380
2409
|
* For historical reasons, the custom "nodebuffer" type is used by the default
|
|
@@ -2785,6 +2814,7 @@ var require_websocket = __commonJS({
|
|
|
2785
2814
|
maxBufferedChunks: 256 * 1024,
|
|
2786
2815
|
maxFragments: 16 * 1024,
|
|
2787
2816
|
maxPayload: 100 * 1024 * 1024,
|
|
2817
|
+
maxPendingAutoPongs: 60,
|
|
2788
2818
|
skipUTF8Validation: false,
|
|
2789
2819
|
perMessageDeflate: true,
|
|
2790
2820
|
followRedirects: false,
|
|
@@ -2800,8 +2830,6 @@ var require_websocket = __commonJS({
|
|
|
2800
2830
|
path: void 0,
|
|
2801
2831
|
port: void 0
|
|
2802
2832
|
};
|
|
2803
|
-
websocket._autoPong = opts.autoPong;
|
|
2804
|
-
websocket._closeTimeout = opts.closeTimeout;
|
|
2805
2833
|
if (!protocolVersions.includes(opts.protocolVersion)) {
|
|
2806
2834
|
throw new RangeError(
|
|
2807
2835
|
`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
|
|
@@ -2817,10 +2845,9 @@ var require_websocket = __commonJS({
|
|
|
2817
2845
|
throw new SyntaxError(`Invalid URL: ${address}`);
|
|
2818
2846
|
}
|
|
2819
2847
|
}
|
|
2820
|
-
if (parsedUrl.protocol === "http:") {
|
|
2821
|
-
parsedUrl
|
|
2822
|
-
|
|
2823
|
-
parsedUrl.protocol = "wss:";
|
|
2848
|
+
if (parsedUrl.protocol === "http:" || parsedUrl.protocol === "https:") {
|
|
2849
|
+
parsedUrl = new URL2(parsedUrl);
|
|
2850
|
+
parsedUrl.protocol = parsedUrl.protocol === "http:" ? "ws:" : "wss:";
|
|
2824
2851
|
}
|
|
2825
2852
|
websocket._url = parsedUrl.href;
|
|
2826
2853
|
const isSecure = parsedUrl.protocol === "wss:";
|
|
@@ -2889,12 +2916,19 @@ var require_websocket = __commonJS({
|
|
|
2889
2916
|
}
|
|
2890
2917
|
}
|
|
2891
2918
|
if (parsedUrl.username || parsedUrl.password) {
|
|
2892
|
-
|
|
2919
|
+
const username = querystring.unescape(parsedUrl.username);
|
|
2920
|
+
const password = querystring.unescape(parsedUrl.password);
|
|
2921
|
+
opts.auth = `${username}:${password}`;
|
|
2893
2922
|
}
|
|
2894
2923
|
if (isIpcUrl) {
|
|
2895
|
-
const
|
|
2896
|
-
|
|
2897
|
-
|
|
2924
|
+
const i = opts.path.indexOf(":");
|
|
2925
|
+
if (i === -1) {
|
|
2926
|
+
opts.socketPath = opts.path;
|
|
2927
|
+
opts.path = "";
|
|
2928
|
+
} else {
|
|
2929
|
+
opts.socketPath = opts.path.slice(0, i);
|
|
2930
|
+
opts.path = opts.path.slice(i + 1);
|
|
2931
|
+
}
|
|
2898
2932
|
}
|
|
2899
2933
|
let req;
|
|
2900
2934
|
if (opts.followRedirects) {
|
|
@@ -3038,6 +3072,7 @@ var require_websocket = __commonJS({
|
|
|
3038
3072
|
} else {
|
|
3039
3073
|
req.end();
|
|
3040
3074
|
}
|
|
3075
|
+
return opts;
|
|
3041
3076
|
}
|
|
3042
3077
|
function emitErrorAndClose(websocket, err) {
|
|
3043
3078
|
websocket._readyState = WebSocket3.CLOSING;
|
|
@@ -3089,8 +3124,13 @@ var require_websocket = __commonJS({
|
|
|
3089
3124
|
function receiverOnConclude(code, reason) {
|
|
3090
3125
|
const websocket = this[kWebSocket];
|
|
3091
3126
|
websocket._closeFrameReceived = true;
|
|
3092
|
-
websocket._closeMessage = reason;
|
|
3093
3127
|
websocket._closeCode = code;
|
|
3128
|
+
if (reason.length === 0) {
|
|
3129
|
+
websocket._closeMessage = EMPTY_BUFFER;
|
|
3130
|
+
} else {
|
|
3131
|
+
websocket._closeMessage = Buffer.allocUnsafeSlow(reason.length);
|
|
3132
|
+
websocket._closeMessage.set(reason);
|
|
3133
|
+
}
|
|
3094
3134
|
if (websocket._socket[kWebSocket] === void 0) return;
|
|
3095
3135
|
websocket._socket.removeListener("data", socketOnData);
|
|
3096
3136
|
process.nextTick(resume, websocket._socket);
|
|
@@ -3121,9 +3161,19 @@ var require_websocket = __commonJS({
|
|
|
3121
3161
|
}
|
|
3122
3162
|
function receiverOnPing(data) {
|
|
3123
3163
|
const websocket = this[kWebSocket];
|
|
3124
|
-
if (websocket._autoPong
|
|
3164
|
+
if (websocket._autoPong && websocket.readyState === WebSocket3.OPEN) {
|
|
3165
|
+
if (websocket._maxPendingAutoPongs > 0 && websocket._pendingAutoPongs >= websocket._maxPendingAutoPongs) {
|
|
3166
|
+
websocket.terminate();
|
|
3167
|
+
} else {
|
|
3168
|
+
websocket._pendingAutoPongs++;
|
|
3169
|
+
websocket.pong(data, !this._isServer, websocket._autoPongComplete);
|
|
3170
|
+
}
|
|
3171
|
+
}
|
|
3125
3172
|
websocket.emit("ping", data);
|
|
3126
3173
|
}
|
|
3174
|
+
function autoPongComplete(websocket) {
|
|
3175
|
+
websocket._pendingAutoPongs--;
|
|
3176
|
+
}
|
|
3127
3177
|
function receiverOnPong(data) {
|
|
3128
3178
|
this[kWebSocket].emit("pong", data);
|
|
3129
3179
|
}
|
|
@@ -3380,6 +3430,8 @@ var require_websocket_server = __commonJS({
|
|
|
3380
3430
|
* fragments
|
|
3381
3431
|
* @param {Number} [options.maxPayload=104857600] The maximum allowed message
|
|
3382
3432
|
* size
|
|
3433
|
+
* @param {Number} [options.maxPendingAutoPongs=60] The maximum number of
|
|
3434
|
+
* pending automatic pongs
|
|
3383
3435
|
* @param {Boolean} [options.noServer=false] Enable no server mode
|
|
3384
3436
|
* @param {String} [options.path] Accept only connections matching this path
|
|
3385
3437
|
* @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
|
|
@@ -3402,6 +3454,7 @@ var require_websocket_server = __commonJS({
|
|
|
3402
3454
|
maxBufferedChunks: 256 * 1024,
|
|
3403
3455
|
maxFragments: 16 * 1024,
|
|
3404
3456
|
maxPayload: 100 * 1024 * 1024,
|
|
3457
|
+
maxPendingAutoPongs: 60,
|
|
3405
3458
|
skipUTF8Validation: false,
|
|
3406
3459
|
perMessageDeflate: false,
|
|
3407
3460
|
handleProtocols: null,
|
|
@@ -4045,6 +4098,17 @@ function getAdbSerial() {
|
|
|
4045
4098
|
_adbSerial = lines[0]?.split(" ")[0] ?? "";
|
|
4046
4099
|
return _adbSerial;
|
|
4047
4100
|
}
|
|
4101
|
+
const localBootId = readLocalBootId();
|
|
4102
|
+
if (localBootId) {
|
|
4103
|
+
for (const line of lines) {
|
|
4104
|
+
const serial = line.split(" ")[0];
|
|
4105
|
+
const check = runSync([ADB_PATH, "-s", serial, "shell", "cat", "/proc/sys/kernel/random/boot_id"], { timeoutMs: ADB_CALL_TIMEOUT_MS });
|
|
4106
|
+
if (check.exitCode === 0 && check.stdout.toString().trim() === localBootId) {
|
|
4107
|
+
_adbSerial = serial;
|
|
4108
|
+
return _adbSerial;
|
|
4109
|
+
}
|
|
4110
|
+
}
|
|
4111
|
+
}
|
|
4048
4112
|
for (const line of lines) {
|
|
4049
4113
|
const serial = line.split(" ")[0];
|
|
4050
4114
|
const check = runSync([ADB_PATH, "-s", serial, "shell", "pidof", "com.microsoft.emmx.canary"], { timeoutMs: ADB_CALL_TIMEOUT_MS });
|
|
@@ -4060,6 +4124,14 @@ function getAdbSerial() {
|
|
|
4060
4124
|
return _adbSerial;
|
|
4061
4125
|
}
|
|
4062
4126
|
}
|
|
4127
|
+
function readLocalBootId() {
|
|
4128
|
+
try {
|
|
4129
|
+
const { readFileSync: readFileSync2 } = require("fs");
|
|
4130
|
+
return readFileSync2("/proc/sys/kernel/random/boot_id", "utf-8").trim();
|
|
4131
|
+
} catch {
|
|
4132
|
+
return "";
|
|
4133
|
+
}
|
|
4134
|
+
}
|
|
4063
4135
|
function adb(...args) {
|
|
4064
4136
|
const serial = getAdbSerial();
|
|
4065
4137
|
return serial ? [ADB_PATH, "-s", serial, ...args] : [ADB_PATH, ...args];
|
|
@@ -4553,6 +4625,24 @@ function drainTabQueue(tabId) {
|
|
|
4553
4625
|
next.resolve({ type: "tool_response", error: "All bridge clients disconnected before dispatch" });
|
|
4554
4626
|
}
|
|
4555
4627
|
}
|
|
4628
|
+
function refreshTabUrlsFromExtension() {
|
|
4629
|
+
if (wsClients.size === 0) return Promise.resolve();
|
|
4630
|
+
const requestId = `req_${++toolRequestCounter}_${Date.now()}_tabs`;
|
|
4631
|
+
return new Promise((resolve3) => {
|
|
4632
|
+
const timeout = setTimeout(() => {
|
|
4633
|
+
pendingToolMap.delete(requestId);
|
|
4634
|
+
resolve3();
|
|
4635
|
+
}, TAB_URL_REFRESH_TIMEOUT_MS);
|
|
4636
|
+
pendingToolMap.set(requestId, { resolve: () => resolve3(), timeout, tabId: -1 });
|
|
4637
|
+
const request = JSON.stringify({ type: "tool_request", method: "tabs_context_mcp", params: {}, requestId });
|
|
4638
|
+
for (const client of wsClients) {
|
|
4639
|
+
try {
|
|
4640
|
+
client.send(request);
|
|
4641
|
+
} catch {
|
|
4642
|
+
}
|
|
4643
|
+
}
|
|
4644
|
+
});
|
|
4645
|
+
}
|
|
4556
4646
|
function spawnNativeHost() {
|
|
4557
4647
|
if (nativeHost) {
|
|
4558
4648
|
log("warn", "Native host already running, killing first");
|
|
@@ -4627,11 +4717,12 @@ function handleNativeMessage(json, reply = sendToNativeHost) {
|
|
|
4627
4717
|
outJson = JSON.stringify(parsed);
|
|
4628
4718
|
log("debug", `Unwrapped execute_tool \u2192 ${parsed.method}`);
|
|
4629
4719
|
}
|
|
4720
|
+
if (parsed.type === "tool_request") void cdpManager.thawRenderers();
|
|
4630
4721
|
if (parsed.type === "tool_request" && parsed.method === "javascript_tool" && cdpManager.isAvailable()) {
|
|
4631
4722
|
const code = parsed.params?.text ?? "";
|
|
4632
4723
|
const tabId = parsed.params?.tabId;
|
|
4633
4724
|
log("info", `CDP: intercepting javascript_tool (${code.slice(0, 80)})`);
|
|
4634
|
-
cdpManager.evaluateJS(code, tabId).then((cdpResult) => {
|
|
4725
|
+
cdpManager.ensurePageAwake(tabId).then(() => cdpManager.evaluateJS(code, tabId)).then((cdpResult) => {
|
|
4635
4726
|
const response = JSON.stringify({ type: "tool_response", result: cdpResult });
|
|
4636
4727
|
log("debug", `CDP\u2192native: ${response.slice(0, 200)}`);
|
|
4637
4728
|
try {
|
|
@@ -4677,6 +4768,12 @@ function handleNativeMessage(json, reply = sendToNativeHost) {
|
|
|
4677
4768
|
}
|
|
4678
4769
|
}
|
|
4679
4770
|
}
|
|
4771
|
+
} else if (cdpResult.final) {
|
|
4772
|
+
log("warn", `CDP screenshot failed: ${cdpResult.error}`);
|
|
4773
|
+
try {
|
|
4774
|
+
reply(JSON.stringify({ type: "tool_response", error: cdpResult.error }));
|
|
4775
|
+
} catch {
|
|
4776
|
+
}
|
|
4680
4777
|
} else {
|
|
4681
4778
|
log("warn", `CDP screenshot failed: ${cdpResult.error}`);
|
|
4682
4779
|
for (const client of wsClients) {
|
|
@@ -4705,6 +4802,13 @@ function handleNativeMessage(json, reply = sendToNativeHost) {
|
|
|
4705
4802
|
cdpManager.captureScreenshot(tabId).then((cdpResult) => {
|
|
4706
4803
|
if (!cdpResult.data) {
|
|
4707
4804
|
log("warn", `CDP zoom screenshot failed: ${cdpResult.error}`);
|
|
4805
|
+
if (cdpResult.final) {
|
|
4806
|
+
try {
|
|
4807
|
+
reply(JSON.stringify({ type: "tool_response", error: cdpResult.error }));
|
|
4808
|
+
} catch {
|
|
4809
|
+
}
|
|
4810
|
+
return;
|
|
4811
|
+
}
|
|
4708
4812
|
for (const client of wsClients) {
|
|
4709
4813
|
try {
|
|
4710
4814
|
client.send(outJson);
|
|
@@ -4775,12 +4879,13 @@ function handleNativeMessage(json, reply = sendToNativeHost) {
|
|
|
4775
4879
|
const action = parsed.params.action;
|
|
4776
4880
|
const tabId = parsed.params?.tabId;
|
|
4777
4881
|
log("info", `CDP: intercepting computer ${action} (tab ${tabId ?? "active"})`);
|
|
4778
|
-
cdpManager.dispatchComputerAction(action, parsed.params ?? {}, tabId).then((cdpResult) => {
|
|
4882
|
+
cdpManager.ensurePageAwake(tabId).then(() => cdpManager.dispatchComputerAction(action, parsed.params ?? {}, tabId)).then(async (cdpResult) => {
|
|
4779
4883
|
if (cdpResult.result) {
|
|
4884
|
+
const note = await cdpManager.hiddenTabNote(tabId);
|
|
4780
4885
|
try {
|
|
4781
4886
|
reply(JSON.stringify({
|
|
4782
4887
|
type: "tool_response",
|
|
4783
|
-
result: { result: cdpResult.result }
|
|
4888
|
+
result: { result: cdpResult.result + note }
|
|
4784
4889
|
}));
|
|
4785
4890
|
} catch (e) {
|
|
4786
4891
|
log("warn", `sendToNativeHost failed after CDP ${action}: ${e.message}`);
|
|
@@ -4856,6 +4961,30 @@ function handleNativeMessage(json, reply = sendToNativeHost) {
|
|
|
4856
4961
|
return;
|
|
4857
4962
|
}
|
|
4858
4963
|
}
|
|
4964
|
+
if (parsed.type === "tool_request" && EXTENSION_PAGE_TOOLS.has(parsed.method) && typeof parsed.params?.tabId === "number" && cdpManager.isAvailable()) {
|
|
4965
|
+
const tabId = parsed.params.tabId;
|
|
4966
|
+
void (async () => {
|
|
4967
|
+
const awake = await cdpManager.ensurePageAwake(tabId);
|
|
4968
|
+
if (!awake.ok) {
|
|
4969
|
+
log("warn", `${parsed.method}: tab ${tabId} is frozen by Edge and was not woken: ${awake.reason}`);
|
|
4970
|
+
try {
|
|
4971
|
+
reply(JSON.stringify({
|
|
4972
|
+
type: "tool_response",
|
|
4973
|
+
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.`
|
|
4974
|
+
}));
|
|
4975
|
+
} catch {
|
|
4976
|
+
}
|
|
4977
|
+
return;
|
|
4978
|
+
}
|
|
4979
|
+
for (const client of wsClients) {
|
|
4980
|
+
try {
|
|
4981
|
+
client.send(outJson);
|
|
4982
|
+
} catch {
|
|
4983
|
+
}
|
|
4984
|
+
}
|
|
4985
|
+
})();
|
|
4986
|
+
return;
|
|
4987
|
+
}
|
|
4859
4988
|
} catch {
|
|
4860
4989
|
}
|
|
4861
4990
|
for (const ws of wsClients) {
|
|
@@ -4901,7 +5030,7 @@ function shutdown() {
|
|
|
4901
5030
|
log("info", "Bridge stopped");
|
|
4902
5031
|
process.exit(0);
|
|
4903
5032
|
}
|
|
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;
|
|
5033
|
+
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
5034
|
var init_claude_chrome_bridge = __esm({
|
|
4906
5035
|
"../claude-chrome-bridge.ts"() {
|
|
4907
5036
|
init_import_meta_shim();
|
|
@@ -4996,6 +5125,14 @@ var init_claude_chrome_bridge = __esm({
|
|
|
4996
5125
|
CDP_MAX_BACKOFF_ATTEMPTS = 10;
|
|
4997
5126
|
CDP_TARGET_CACHE_TTL_MS = 1e4;
|
|
4998
5127
|
CDP_TIMEOUT_MS = 15e3;
|
|
5128
|
+
EDGE_RENDERER_PREFIX = "com.microsoft.emmx.canary:sandboxed_process";
|
|
5129
|
+
RENDERER_THAW_INTERVAL_MS = 1e4;
|
|
5130
|
+
RENDERER_THAW_TIMEOUT_MS = 5e3;
|
|
5131
|
+
PAGE_PROBE_TIMEOUT_MS = 1500;
|
|
5132
|
+
WAKE_FROZEN_TABS = process.env.BRIDGE_WAKE_FROZEN_TABS !== "0";
|
|
5133
|
+
WAKE_MIN_INTERVAL_MS = 5e3;
|
|
5134
|
+
MESSAGE_CHANNEL_PROBE = "new Promise((r) => { const c = new MessageChannel(); c.port1.onmessage = () => r(1); c.port2.postMessage(0); })";
|
|
5135
|
+
EXTENSION_PAGE_TOOLS = /* @__PURE__ */ new Set(["get_page_text", "read_page", "find", "form_input"]);
|
|
4999
5136
|
CdpManager = class {
|
|
5000
5137
|
penBusy = false;
|
|
5001
5138
|
ws = null;
|
|
@@ -5236,7 +5373,9 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5236
5373
|
if (r.description) return { result: r.description };
|
|
5237
5374
|
return { result: String(r) };
|
|
5238
5375
|
} catch (err) {
|
|
5239
|
-
|
|
5376
|
+
const message = err.message;
|
|
5377
|
+
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)" : "";
|
|
5378
|
+
return { error: `CDP eval failed: ${message}${hint}` };
|
|
5240
5379
|
}
|
|
5241
5380
|
}
|
|
5242
5381
|
/** Resolve an extension tabId to a CDP targetId by URL matching */
|
|
@@ -5249,32 +5388,53 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5249
5388
|
return this.tabTargetMap.get(tabId);
|
|
5250
5389
|
}
|
|
5251
5390
|
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})`);
|
|
5391
|
+
let target = this.matchTabByUrl(tabId);
|
|
5392
|
+
if (!target && this.tabUrlRefresher) {
|
|
5393
|
+
await this.tabUrlRefresher();
|
|
5394
|
+
await this.refreshTargets();
|
|
5395
|
+
target = this.matchTabByUrl(tabId);
|
|
5263
5396
|
}
|
|
5397
|
+
if (target) {
|
|
5398
|
+
this.tabTargetMap.set(tabId, target);
|
|
5399
|
+
return target;
|
|
5400
|
+
}
|
|
5401
|
+
log("warn", `CDP: no target found for tab ${tabId} (url ${this.tabUrlCache.get(tabId) ?? "unknown"})`);
|
|
5402
|
+
return null;
|
|
5264
5403
|
}
|
|
5265
5404
|
const firstPage = this.cachedTargets.find((t) => t.type === "page");
|
|
5266
5405
|
log("debug", `CDP: resolveTarget(${tabId ?? "none"}) \u2192 fallback to first page: ${firstPage?.url ?? "none"}`);
|
|
5267
5406
|
return firstPage?.targetId ?? null;
|
|
5268
5407
|
}
|
|
5408
|
+
/** Asks the extension for current tab URLs (fills tabUrlCache); set by the server */
|
|
5409
|
+
tabUrlRefresher = null;
|
|
5410
|
+
setTabUrlRefresher(refresher) {
|
|
5411
|
+
this.tabUrlRefresher = refresher;
|
|
5412
|
+
}
|
|
5413
|
+
/**
|
|
5414
|
+
* Target for an extension tab by its cached URL. When several page targets
|
|
5415
|
+
* share the URL (the same page open twice), prefer one not already mapped to
|
|
5416
|
+
* a different tab.
|
|
5417
|
+
*/
|
|
5418
|
+
matchTabByUrl(tabId) {
|
|
5419
|
+
const tabUrl = this.tabUrlCache.get(tabId);
|
|
5420
|
+
if (!tabUrl) return null;
|
|
5421
|
+
const candidates = this.cachedTargets.filter((t) => t.url === tabUrl && t.type === "page");
|
|
5422
|
+
if (candidates.length === 0) return null;
|
|
5423
|
+
const claimed = new Set(
|
|
5424
|
+
[...this.tabTargetMap].filter(([otherTab]) => otherTab !== tabId).map(([, targetId]) => targetId)
|
|
5425
|
+
);
|
|
5426
|
+
return (candidates.find((t) => !claimed.has(t.targetId)) ?? candidates[0]).targetId;
|
|
5427
|
+
}
|
|
5269
5428
|
/** Fetch CDP targets via Target.getTargets (not /json/list — those IDs differ) */
|
|
5270
5429
|
async refreshTargets() {
|
|
5271
5430
|
try {
|
|
5272
5431
|
const result = await this.sendCommand("Target.getTargets");
|
|
5273
5432
|
this.cachedTargets = result.targetInfos;
|
|
5274
5433
|
this.targetsLastFetched = Date.now();
|
|
5275
|
-
for (const
|
|
5276
|
-
const target = this.
|
|
5277
|
-
if (target) this.tabTargetMap.set(tabId, target
|
|
5434
|
+
for (const tabId of this.tabUrlCache.keys()) {
|
|
5435
|
+
const target = this.matchTabByUrl(tabId);
|
|
5436
|
+
if (target) this.tabTargetMap.set(tabId, target);
|
|
5437
|
+
else this.tabTargetMap.delete(tabId);
|
|
5278
5438
|
}
|
|
5279
5439
|
} catch (err) {
|
|
5280
5440
|
log("debug", `CDP: refreshTargets failed \u2014 ${err.message}`);
|
|
@@ -5329,8 +5489,12 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5329
5489
|
* renderer surface (the actual page content), so it works even when the Edge
|
|
5330
5490
|
* app is backgrounded. `Page.bringToFront` is REQUIRED first: a backgrounded
|
|
5331
5491
|
* renderer has no compositor surface and `captureScreenshot` fails with
|
|
5332
|
-
* "Internal error" until the tab is the active one
|
|
5333
|
-
*
|
|
5492
|
+
* "Internal error" until the tab is the active one. bringToFront DOES bring
|
|
5493
|
+
* the Edge app to the foreground on Edge 154 Android (measured 2026-11-25:
|
|
5494
|
+
* focus moved from RustDesk and from Termux to ChromeTabbedActivity), so a
|
|
5495
|
+
* screenshot taken while the user is in another app briefly takes over the
|
|
5496
|
+
* screen; the previously focused activity is started again after capture
|
|
5497
|
+
* (not possible for the lock screen or notification shade).
|
|
5334
5498
|
*
|
|
5335
5499
|
* Fallback — ADB `screencap`: grabs the whole device screen (so Edge must be
|
|
5336
5500
|
* foregrounded to show the page). Used only when CDP is unavailable or the
|
|
@@ -5348,11 +5512,17 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5348
5512
|
sessionId = attach.sessionId;
|
|
5349
5513
|
this.sessionMap.set(targetId, sessionId);
|
|
5350
5514
|
}
|
|
5515
|
+
const before = this.readDeviceState();
|
|
5516
|
+
let shot;
|
|
5351
5517
|
try {
|
|
5352
|
-
|
|
5353
|
-
|
|
5518
|
+
try {
|
|
5519
|
+
await this.sendCommand("Page.bringToFront", {}, sessionId);
|
|
5520
|
+
} catch {
|
|
5521
|
+
}
|
|
5522
|
+
shot = await this.sendCommand("Page.captureScreenshot", { format: "png" }, sessionId);
|
|
5523
|
+
} finally {
|
|
5524
|
+
this.refocus(before, "captured screenshot");
|
|
5354
5525
|
}
|
|
5355
|
-
const shot = await this.sendCommand("Page.captureScreenshot", { format: "png" }, sessionId);
|
|
5356
5526
|
if (shot?.data) {
|
|
5357
5527
|
log("info", `CDP: Page.captureScreenshot captured ~${Math.round(shot.data.length * 3 / 4)} bytes`);
|
|
5358
5528
|
return { data: normalizeScreenshot(shot.data) };
|
|
@@ -5363,11 +5533,22 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5363
5533
|
log("debug", `CDP: Page.captureScreenshot failed, falling back to ADB screencap \u2014 ${err.message}`);
|
|
5364
5534
|
}
|
|
5365
5535
|
}
|
|
5536
|
+
try {
|
|
5537
|
+
const focus = runSync(adb("shell", "dumpsys", "window"), { timeoutMs: 3e3 });
|
|
5538
|
+
const focusLine = focus.stdout.toString().split("\n").find((l) => l.includes("mCurrentFocus")) ?? "";
|
|
5539
|
+
if (focus.exitCode === 0 && !focusLine.includes("com.microsoft.emmx.canary")) {
|
|
5540
|
+
return {
|
|
5541
|
+
error: "Screenshot not available: CDP capture failed and Edge is not the foreground app, so ADB screencap would capture a different app",
|
|
5542
|
+
final: true
|
|
5543
|
+
};
|
|
5544
|
+
}
|
|
5545
|
+
} catch {
|
|
5546
|
+
}
|
|
5366
5547
|
try {
|
|
5367
5548
|
const tmpPath = "/data/data/com.termux/files/usr/tmp/cdp-screencap.png";
|
|
5368
|
-
const cap = runSync(adb("shell", "screencap", "-p", "/sdcard/cdp-screencap.png"));
|
|
5549
|
+
const cap = runSync(adb("shell", "screencap", "-p", "/sdcard/cdp-screencap.png"), { timeoutMs: 1e4 });
|
|
5369
5550
|
if (cap.exitCode === 0) {
|
|
5370
|
-
const pull = runSync(adb("pull", "/sdcard/cdp-screencap.png", tmpPath));
|
|
5551
|
+
const pull = runSync(adb("pull", "/sdcard/cdp-screencap.png", tmpPath), { timeoutMs: 1e4 });
|
|
5371
5552
|
if (pull.exitCode === 0 && await fileExists(tmpPath)) {
|
|
5372
5553
|
const { readFile: rf } = await import("node:fs/promises");
|
|
5373
5554
|
const buf = await rf(tmpPath);
|
|
@@ -5517,6 +5698,201 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5517
5698
|
return { error: `CDP input failed: ${err.message}` };
|
|
5518
5699
|
}
|
|
5519
5700
|
}
|
|
5701
|
+
/** Attached CDP session for an extension tab (or the active one), or null when it has no target */
|
|
5702
|
+
async sessionForTab(tabId) {
|
|
5703
|
+
const targetId = await this.resolveTarget(tabId);
|
|
5704
|
+
if (!targetId) return null;
|
|
5705
|
+
let sessionId = this.sessionMap.get(targetId);
|
|
5706
|
+
if (!sessionId) {
|
|
5707
|
+
const attach = await this.sendCommand("Target.attachToTarget", { targetId, flatten: true });
|
|
5708
|
+
sessionId = attach.sessionId;
|
|
5709
|
+
this.sessionMap.set(targetId, sessionId);
|
|
5710
|
+
}
|
|
5711
|
+
return sessionId;
|
|
5712
|
+
}
|
|
5713
|
+
/** Runtime.evaluate that gives up after `ms`; null means no answer in time */
|
|
5714
|
+
async evaluateWithin(sessionId, expression, awaitPromise, ms) {
|
|
5715
|
+
const call = this.sendCommand("Runtime.evaluate", { expression, returnByValue: true, awaitPromise }, sessionId).then((r) => r.result?.value ?? "undefined");
|
|
5716
|
+
const timeout = new Promise((resolve3) => setTimeout(() => resolve3(null), ms));
|
|
5717
|
+
return Promise.race([call, timeout]).catch(() => null);
|
|
5718
|
+
}
|
|
5719
|
+
/**
|
|
5720
|
+
* True when Edge has frozen the tab's page (Page Lifecycle "frozen"): it
|
|
5721
|
+
* still answers synchronous CDP evaluation, but its task queues are
|
|
5722
|
+
* suspended, so timers, MessageChannel and every extension content-script
|
|
5723
|
+
* request wait until the tab becomes visible. Observed on hidden tabs
|
|
5724
|
+
* within ~45 s to hours of Edge leaving the foreground, not on every tab;
|
|
5725
|
+
* neither Page.setWebLifecycleState nor the Chromium background-throttling
|
|
5726
|
+
* switches undo it (2026-11-27). False when the page answers, and also when
|
|
5727
|
+
* it does not even answer synchronously (an OS-frozen or dead renderer is a
|
|
5728
|
+
* different problem, handled by thawRenderers).
|
|
5729
|
+
*/
|
|
5730
|
+
async pageIsFrozen(tabId) {
|
|
5731
|
+
try {
|
|
5732
|
+
const sessionId = await this.sessionForTab(tabId);
|
|
5733
|
+
if (!sessionId) return false;
|
|
5734
|
+
if (await this.evaluateWithin(sessionId, "1", false, PAGE_PROBE_TIMEOUT_MS) === null) return false;
|
|
5735
|
+
return await this.evaluateWithin(sessionId, MESSAGE_CHANNEL_PROBE, true, PAGE_PROBE_TIMEOUT_MS) === null;
|
|
5736
|
+
} catch {
|
|
5737
|
+
return false;
|
|
5738
|
+
}
|
|
5739
|
+
}
|
|
5740
|
+
/** Counters for /health: how often each background layer was hit */
|
|
5741
|
+
backgroundStats = {
|
|
5742
|
+
renderersExempted: 0,
|
|
5743
|
+
sweepFailures: 0,
|
|
5744
|
+
frozenPagesDetected: 0,
|
|
5745
|
+
wakes: 0,
|
|
5746
|
+
wakesSkipped: 0,
|
|
5747
|
+
lastWakeSkipReason: null
|
|
5748
|
+
};
|
|
5749
|
+
lastWakeAt = 0;
|
|
5750
|
+
wakeInFlight = null;
|
|
5751
|
+
/**
|
|
5752
|
+
* Everything a wake decision needs, in two small adb calls: whether the
|
|
5753
|
+
* screen is on, whether the keyguard (lock screen) is showing, whether a
|
|
5754
|
+
* phone call is active, and what to bring back afterwards. `focus` is the
|
|
5755
|
+
* focused activity ("pkg/cls", or null for system windows such as the
|
|
5756
|
+
* notification shade); `taskPackage` is the package at the ROOT of the top
|
|
5757
|
+
* task. They differ for activities that run inside another app's task, e.g.
|
|
5758
|
+
* a Chrome web app (focus com.android.chrome/...SameTaskWebApkActivity,
|
|
5759
|
+
* root org.chromium.webapk.<id>): starting such an activity by component
|
|
5760
|
+
* does not bring the task back, while the root package's launcher intent
|
|
5761
|
+
* resumes the existing task.
|
|
5762
|
+
*/
|
|
5763
|
+
readDeviceState() {
|
|
5764
|
+
const out = runSync(
|
|
5765
|
+
adb(
|
|
5766
|
+
"shell",
|
|
5767
|
+
"dumpsys power | grep -m1 mWakefulness=; dumpsys window | grep -E -m2 'mCurrentFocus|isKeyguardShowing'; dumpsys telephony.registry | grep -m1 mCallState; dumpsys activity activities | grep -m1 topResumedActivity"
|
|
5768
|
+
),
|
|
5769
|
+
{ timeoutMs: 4e3 }
|
|
5770
|
+
).stdout.toString();
|
|
5771
|
+
const focusLine = out.split("\n").find((l) => l.includes("mCurrentFocus")) ?? "";
|
|
5772
|
+
const taskId = /topResumedActivity=.*\st(\d+)\}/.exec(out)?.[1] ?? null;
|
|
5773
|
+
let taskPackage = null;
|
|
5774
|
+
if (taskId) {
|
|
5775
|
+
const recents = runSync(
|
|
5776
|
+
adb("shell", "dumpsys activity recents | grep -E 'Recent #|^ intent='"),
|
|
5777
|
+
{ timeoutMs: 4e3 }
|
|
5778
|
+
).stdout.toString().split("\n");
|
|
5779
|
+
const header = recents.findIndex((l) => l.includes(` #${taskId} `));
|
|
5780
|
+
const intentLine = header >= 0 ? recents[header + 1] ?? "" : "";
|
|
5781
|
+
taskPackage = /cmp=([^/\s}]+)\//.exec(intentLine)?.[1] ?? null;
|
|
5782
|
+
}
|
|
5783
|
+
return {
|
|
5784
|
+
awake: /mWakefulness=Awake/.test(out),
|
|
5785
|
+
keyguard: /isKeyguardShowing=true/.test(out),
|
|
5786
|
+
inCall: /mCallState=[12]\b/.test(out),
|
|
5787
|
+
focus: /\s(\S+\/\S+)\}/.exec(focusLine)?.[1] ?? null,
|
|
5788
|
+
taskPackage
|
|
5789
|
+
};
|
|
5790
|
+
}
|
|
5791
|
+
/**
|
|
5792
|
+
* Bring back what was in front before Edge was brought forward: relaunch the
|
|
5793
|
+
* top task's root package through its launcher intent (resumes the task as
|
|
5794
|
+
* it was), falling back to starting the focused activity by component.
|
|
5795
|
+
*/
|
|
5796
|
+
refocus(previous, why) {
|
|
5797
|
+
const edge = "com.microsoft.emmx.canary";
|
|
5798
|
+
if (previous.taskPackage && previous.taskPackage !== edge) {
|
|
5799
|
+
const launch = runSync(
|
|
5800
|
+
adb("shell", "monkey", "-p", previous.taskPackage, "-c", "android.intent.category.LAUNCHER", "1"),
|
|
5801
|
+
{ timeoutMs: 8e3 }
|
|
5802
|
+
);
|
|
5803
|
+
if (launch.exitCode === 0 && !/No activities found|aborted/i.test(launch.stdout.toString())) {
|
|
5804
|
+
log("info", `CDP: ${why}; resumed task of ${previous.taskPackage}`);
|
|
5805
|
+
return;
|
|
5806
|
+
}
|
|
5807
|
+
}
|
|
5808
|
+
if (!previous.focus || previous.focus.startsWith(`${edge}/`)) return;
|
|
5809
|
+
runSync(adb("shell", "am", "start", "-n", previous.focus), { timeoutMs: 5e3 });
|
|
5810
|
+
log("info", `CDP: ${why}; refocused ${previous.focus}`);
|
|
5811
|
+
}
|
|
5812
|
+
/**
|
|
5813
|
+
* Wake a frozen tab: Page.bringToFront makes it visible (Chromium resumes
|
|
5814
|
+
* it), which also brings the Edge app to the foreground, so afterwards the
|
|
5815
|
+
* previously focused activity is started again. Refuses (returns a reason)
|
|
5816
|
+
* when the screen is off, the lock screen is up or a call is active: the
|
|
5817
|
+
* restore could not return there, and taking over the screen mid-call is
|
|
5818
|
+
* worse than a failed tool. Concurrent requests share one wake, and wakes
|
|
5819
|
+
* are at least WAKE_MIN_INTERVAL_MS apart.
|
|
5820
|
+
*/
|
|
5821
|
+
async wakeFrozenTab(tabId) {
|
|
5822
|
+
if (this.wakeInFlight) return { ok: await this.wakeInFlight, reason: "shared wake" };
|
|
5823
|
+
if (Date.now() - this.lastWakeAt < WAKE_MIN_INTERVAL_MS) return this.skipWake("another wake ran under 5 s ago");
|
|
5824
|
+
const state = this.readDeviceState();
|
|
5825
|
+
if (!state.awake) return this.skipWake("the screen is off");
|
|
5826
|
+
if (state.keyguard) return this.skipWake("the phone is locked");
|
|
5827
|
+
if (state.inCall) return this.skipWake("a phone call is active");
|
|
5828
|
+
const sessionId = await this.sessionForTab(tabId);
|
|
5829
|
+
if (!sessionId) return this.skipWake("the tab has no CDP target");
|
|
5830
|
+
this.lastWakeAt = Date.now();
|
|
5831
|
+
this.wakeInFlight = (async () => {
|
|
5832
|
+
try {
|
|
5833
|
+
await this.sendCommand("Page.bringToFront", {}, sessionId);
|
|
5834
|
+
for (let i = 0; i < 6; i++) {
|
|
5835
|
+
if (await this.evaluateWithin(sessionId, MESSAGE_CHANNEL_PROBE, true, 500) !== null) return true;
|
|
5836
|
+
}
|
|
5837
|
+
return false;
|
|
5838
|
+
} catch {
|
|
5839
|
+
return false;
|
|
5840
|
+
} finally {
|
|
5841
|
+
this.refocus(state, `woke frozen tab ${tabId ?? "active"}`);
|
|
5842
|
+
}
|
|
5843
|
+
})();
|
|
5844
|
+
try {
|
|
5845
|
+
const ok = await this.wakeInFlight;
|
|
5846
|
+
if (ok) this.backgroundStats.wakes++;
|
|
5847
|
+
return ok ? { ok } : { ok, reason: "the page did not resume after bringToFront" };
|
|
5848
|
+
} finally {
|
|
5849
|
+
this.wakeInFlight = null;
|
|
5850
|
+
}
|
|
5851
|
+
}
|
|
5852
|
+
skipWake(reason) {
|
|
5853
|
+
this.backgroundStats.wakesSkipped++;
|
|
5854
|
+
this.backgroundStats.lastWakeSkipReason = reason;
|
|
5855
|
+
return { ok: false, reason };
|
|
5856
|
+
}
|
|
5857
|
+
/**
|
|
5858
|
+
* Make sure a tab can run page work before a tool touches it: thaw Edge's
|
|
5859
|
+
* renderers (Android freezer), then, if Edge has frozen the page itself,
|
|
5860
|
+
* wake it (unless disabled or unsafe). `ok: false` carries why; callers that
|
|
5861
|
+
* only need synchronous CDP may proceed anyway.
|
|
5862
|
+
*/
|
|
5863
|
+
async ensurePageAwake(tabId) {
|
|
5864
|
+
await this.thawRenderers();
|
|
5865
|
+
if (!await this.pageIsFrozen(tabId)) return { ok: true, frozen: false };
|
|
5866
|
+
this.backgroundStats.frozenPagesDetected++;
|
|
5867
|
+
if (!WAKE_FROZEN_TABS) return { ok: false, frozen: true, reason: "waking is disabled (BRIDGE_WAKE_FROZEN_TABS=0)" };
|
|
5868
|
+
const woke = await this.wakeFrozenTab(tabId);
|
|
5869
|
+
return { ok: woke.ok, frozen: true, reason: woke.reason };
|
|
5870
|
+
}
|
|
5871
|
+
/**
|
|
5872
|
+
* A note to append to an input result when the tab is hidden (Edge is not
|
|
5873
|
+
* the foreground app). The input itself is delivered, but the page's timers
|
|
5874
|
+
* run about once a minute and requestAnimationFrame / MessageChannel tasks
|
|
5875
|
+
* stall, so handlers that continue through them (e.g. React's scheduler)
|
|
5876
|
+
* may not have updated the page yet. Returns "" for a visible tab or when
|
|
5877
|
+
* the check does not answer within 1.5 s.
|
|
5878
|
+
*/
|
|
5879
|
+
async hiddenTabNote(tabId) {
|
|
5880
|
+
try {
|
|
5881
|
+
const targetId = await this.resolveTarget(tabId);
|
|
5882
|
+
const sessionId = targetId ? this.sessionMap.get(targetId) : void 0;
|
|
5883
|
+
if (!sessionId) return "";
|
|
5884
|
+
const check = this.sendCommand("Runtime.evaluate", {
|
|
5885
|
+
expression: "document.visibilityState",
|
|
5886
|
+
returnByValue: true
|
|
5887
|
+
}, sessionId);
|
|
5888
|
+
const timeout = new Promise((resolve3) => setTimeout(() => resolve3(null), 1500));
|
|
5889
|
+
const r = await Promise.race([check, timeout]);
|
|
5890
|
+
if (r?.result?.value !== "hidden") return "";
|
|
5891
|
+
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)";
|
|
5892
|
+
} catch {
|
|
5893
|
+
return "";
|
|
5894
|
+
}
|
|
5895
|
+
}
|
|
5520
5896
|
/** Parse modifier string like "ctrl+shift" into CDP modifier flags */
|
|
5521
5897
|
parseModifiers(mods) {
|
|
5522
5898
|
if (!mods) return {};
|
|
@@ -5613,9 +5989,74 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5613
5989
|
isAvailable() {
|
|
5614
5990
|
return this.state === "connected" && this.ws?.readyState === WebSocket.OPEN;
|
|
5615
5991
|
}
|
|
5992
|
+
/** Renderers already given a sticky unfreeze (it lasts their lifetime),
|
|
5993
|
+
* keyed "pid:starttime" so a reused pid is never mistaken for a handled one */
|
|
5994
|
+
thawedRenderers = /* @__PURE__ */ new Set();
|
|
5995
|
+
lastThawSweep = 0;
|
|
5996
|
+
thawInFlight = null;
|
|
5997
|
+
/**
|
|
5998
|
+
* Exempt Edge's tab renderers from Android's cached-apps freezer.
|
|
5999
|
+
*
|
|
6000
|
+
* When the Edge app is not in the foreground, Chromium drops its renderer
|
|
6001
|
+
* processes to cached priority and Android freezes them at the cgroup level
|
|
6002
|
+
* (cgroup.freeze=1) after ~40-60 s. A frozen renderer answers nothing: every
|
|
6003
|
+
* CDP Runtime/Input command and every extension content-script call for its
|
|
6004
|
+
* tabs waits until the 15 s / 30 s timeouts. `Page.setWebLifecycleState`
|
|
6005
|
+
* cannot reach it, and `Page.bringToFront` only works by foregrounding the
|
|
6006
|
+
* Edge app. `cmd activity unfreeze --sticky` (shell uid, via adb) thaws a
|
|
6007
|
+
* process and keeps it thawed for its lifetime, so each renderer needs it
|
|
6008
|
+
* once; later sweeps only pick up renderers spawned since.
|
|
6009
|
+
*
|
|
6010
|
+
* Callers do not need to await this: a command queued to a frozen renderer
|
|
6011
|
+
* runs as soon as the sweep thaws it (a healthy sweep takes ~70-200 ms).
|
|
6012
|
+
* Hidden-tab throttling still applies to a thawed tab: timers are batched to
|
|
6013
|
+
* about once a minute, and requestAnimationFrame / MessageChannel tasks did
|
|
6014
|
+
* not run within 8 s in measurements.
|
|
6015
|
+
*/
|
|
6016
|
+
thawRenderers() {
|
|
6017
|
+
if (this.thawInFlight) return this.thawInFlight;
|
|
6018
|
+
if (Date.now() - this.lastThawSweep < RENDERER_THAW_INTERVAL_MS) return Promise.resolve();
|
|
6019
|
+
this.lastThawSweep = Date.now();
|
|
6020
|
+
const skip = [...this.thawedRenderers].join(" ");
|
|
6021
|
+
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"`;
|
|
6022
|
+
this.thawInFlight = (async () => {
|
|
6023
|
+
try {
|
|
6024
|
+
const proc = spawnProcess(adb("shell", script));
|
|
6025
|
+
const timer = setTimeout(() => proc.kill(9), RENDERER_THAW_TIMEOUT_MS);
|
|
6026
|
+
const out = proc.stdout ? await new Response(proc.stdout).text() : "";
|
|
6027
|
+
const exitCode = await proc.exited;
|
|
6028
|
+
clearTimeout(timer);
|
|
6029
|
+
if (exitCode !== 0 || !out.includes("sweep-done")) {
|
|
6030
|
+
throw new Error(`adb shell exited ${exitCode}${out.includes("sweep-done") ? "" : ", sweep incomplete"}`);
|
|
6031
|
+
}
|
|
6032
|
+
const live = /* @__PURE__ */ new Set();
|
|
6033
|
+
const newlyThawed = [];
|
|
6034
|
+
for (const line of out.split("\n")) {
|
|
6035
|
+
const [kind, key] = line.trim().split(" ");
|
|
6036
|
+
if (!key || !/^\d+:\d+$/.test(key)) continue;
|
|
6037
|
+
if (kind === "live") live.add(key);
|
|
6038
|
+
else if (kind === "thawed") newlyThawed.push(key);
|
|
6039
|
+
}
|
|
6040
|
+
for (const key of this.thawedRenderers) if (!live.has(key)) this.thawedRenderers.delete(key);
|
|
6041
|
+
for (const key of newlyThawed) this.thawedRenderers.add(key);
|
|
6042
|
+
this.backgroundStats.renderersExempted += newlyThawed.length;
|
|
6043
|
+
if (newlyThawed.length) {
|
|
6044
|
+
log("info", `CDP: exempted Edge renderer(s) ${newlyThawed.map((k) => k.split(":")[0]).join(", ")} from the Android freezer`);
|
|
6045
|
+
}
|
|
6046
|
+
} catch (err) {
|
|
6047
|
+
this.lastThawSweep = 0;
|
|
6048
|
+
this.backgroundStats.sweepFailures++;
|
|
6049
|
+
log("warn", `CDP: renderer freezer sweep failed \u2014 ${err.message}; frozen tabs will time out until a sweep succeeds`);
|
|
6050
|
+
} finally {
|
|
6051
|
+
this.thawInFlight = null;
|
|
6052
|
+
}
|
|
6053
|
+
})();
|
|
6054
|
+
return this.thawInFlight;
|
|
6055
|
+
}
|
|
5616
6056
|
/** Get status info for /health endpoint */
|
|
5617
6057
|
getStatus() {
|
|
5618
6058
|
return {
|
|
6059
|
+
background: { ...this.backgroundStats, wakeFrozenTabs: WAKE_FROZEN_TABS, renderersTracked: this.thawedRenderers.size },
|
|
5619
6060
|
state: this.state,
|
|
5620
6061
|
edgePid: this.edgePid,
|
|
5621
6062
|
port: CDP_PORT,
|
|
@@ -5805,6 +6246,8 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5805
6246
|
nativeHostKillTimer = null;
|
|
5806
6247
|
stdoutDecoder = new NativeMessageDecoder();
|
|
5807
6248
|
wsClients = /* @__PURE__ */ new Set();
|
|
6249
|
+
TAB_URL_REFRESH_TIMEOUT_MS = 5e3;
|
|
6250
|
+
cdpManager.setTabUrlRefresher(refreshTabUrlsFromExtension);
|
|
5808
6251
|
server = createBridgeServer({
|
|
5809
6252
|
hostname: WS_HOST,
|
|
5810
6253
|
port: WS_PORT,
|
|
@@ -5842,6 +6285,7 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5842
6285
|
if (!params || typeof params !== "object" || Array.isArray(params)) throw new Error("Expected a stroke object");
|
|
5843
6286
|
lastToolName = "pen_stroke";
|
|
5844
6287
|
lastToolTime = (/* @__PURE__ */ new Date()).toISOString();
|
|
6288
|
+
await cdpManager.thawRenderers();
|
|
5845
6289
|
const result = await cdpManager.penStroke(params);
|
|
5846
6290
|
return Response.json({ result });
|
|
5847
6291
|
} catch (error) {
|
|
@@ -5994,7 +6438,8 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5994
6438
|
}
|
|
5995
6439
|
try {
|
|
5996
6440
|
const body = await req.json();
|
|
5997
|
-
const
|
|
6441
|
+
const toolStart = Date.now();
|
|
6442
|
+
const requestId = `req_${++toolRequestCounter}_${toolStart}`;
|
|
5998
6443
|
const tabId = body.params?.tabId || 0;
|
|
5999
6444
|
const toolRequest = JSON.stringify({
|
|
6000
6445
|
type: "tool_request",
|
|
@@ -6004,6 +6449,7 @@ var init_claude_chrome_bridge = __esm({
|
|
|
6004
6449
|
});
|
|
6005
6450
|
lastToolName = body.method;
|
|
6006
6451
|
lastToolTime = (/* @__PURE__ */ new Date()).toISOString();
|
|
6452
|
+
void cdpManager.thawRenderers();
|
|
6007
6453
|
if (body.method === "computer" && (body.params?.action === "screenshot" || body.params?.action === "zoom")) {
|
|
6008
6454
|
const action = body.params.action;
|
|
6009
6455
|
const shotTabId = body.params.tabId;
|
|
@@ -6036,6 +6482,12 @@ var init_claude_chrome_bridge = __esm({
|
|
|
6036
6482
|
{ headers: { "Content-Type": "application/json" } }
|
|
6037
6483
|
);
|
|
6038
6484
|
}
|
|
6485
|
+
if (shot.final) {
|
|
6486
|
+
return new Response(
|
|
6487
|
+
JSON.stringify({ type: "tool_response", error: shot.error }),
|
|
6488
|
+
{ headers: { "Content-Type": "application/json" } }
|
|
6489
|
+
);
|
|
6490
|
+
}
|
|
6039
6491
|
log("warn", `HTTP /tool: ADB screencap failed (${shot.error ?? "unknown"}); forwarding ${action} to extension`);
|
|
6040
6492
|
}
|
|
6041
6493
|
const MAX_PENDING_TOOLS = 50;
|
|
@@ -6082,6 +6534,12 @@ var init_claude_chrome_bridge = __esm({
|
|
|
6082
6534
|
}
|
|
6083
6535
|
}
|
|
6084
6536
|
});
|
|
6537
|
+
const toolError = result;
|
|
6538
|
+
const errText = toolError?.error ?? toolError?.result?.error;
|
|
6539
|
+
log(
|
|
6540
|
+
errText ? "warn" : "info",
|
|
6541
|
+
`HTTP /tool: ${body.method} [${requestId}] ${errText ? `failed: ${String(errText).slice(0, 160)}` : "ok"} in ${Date.now() - toolStart} ms`
|
|
6542
|
+
);
|
|
6085
6543
|
return new Response(
|
|
6086
6544
|
JSON.stringify(result),
|
|
6087
6545
|
{ 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
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "claude-chrome-android",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "Claude Code Browser Bridge for Android
|
|
3
|
+
"version": "1.7.1",
|
|
4
|
+
"description": "Claude Code Browser Bridge for Android — connects Claude Code CLI to Chrome/Edge via WebSocket",
|
|
5
5
|
"author": "willstone",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"repository": {
|
|
@@ -23,13 +23,12 @@
|
|
|
23
23
|
"typecheck": "tsc --noEmit -p tsconfig.json"
|
|
24
24
|
},
|
|
25
25
|
"devDependencies": {
|
|
26
|
-
"@
|
|
27
|
-
"@types/
|
|
28
|
-
"@types/node": "26.6.5",
|
|
26
|
+
"@types/bun": "1.4.5",
|
|
27
|
+
"@types/node": "26.6.11",
|
|
29
28
|
"@types/ws": "8.18.2",
|
|
30
|
-
"esbuild": "^0.
|
|
29
|
+
"esbuild": "^0.28.2",
|
|
31
30
|
"typescript": "^5.9.3",
|
|
32
|
-
"ws": "^8.
|
|
31
|
+
"ws": "^8.23.0"
|
|
33
32
|
},
|
|
34
33
|
"keywords": [
|
|
35
34
|
"claude",
|