claude-chrome-android 1.5.1 → 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.
@@ -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
- const CONTENT_SCRIPT_TIMEOUT_MS = 30000;
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
- await new Promise((resolve) => {
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 { result: `Navigated to ${fullUrl}` };
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) {
@@ -1108,6 +1124,25 @@ chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
1108
1124
  return true;
1109
1125
  }
1110
1126
 
1127
+ if (msg.type === "start_zapper") {
1128
+ // Element zapper: inject content.js into the active tab and enter
1129
+ // tap-to-remove mode (for dismissing overlays/paywalls by hand)
1130
+ chrome.tabs.query({ active: true, currentWindow: true }, (activeTabs) => {
1131
+ const tid = activeTabs[0]?.id;
1132
+ if (!tid) {
1133
+ sendResponse({ ok: false, error: "No active tab" });
1134
+ return;
1135
+ }
1136
+ executeViaContentScript(tid, "zapper_start", {})
1137
+ .then((result) => {
1138
+ addLog("info", `Zapper started on tab ${tid}`);
1139
+ sendResponse({ ok: !result?.error, ...result });
1140
+ })
1141
+ .catch((err) => sendResponse({ ok: false, error: err.message }));
1142
+ });
1143
+ return true;
1144
+ }
1145
+
1111
1146
  // --- Dev tool panel handlers -------------------------------------------------
1112
1147
 
1113
1148
  if (msg.type === "get_network") {
@@ -1373,6 +1408,20 @@ async function stopBridge() {
1373
1408
  return { ok: true, detail: "Bridge stopped" };
1374
1409
  }
1375
1410
 
1411
+ /**
1412
+ * Read the operad daemon token from storage. The daemon's /api/* endpoints
1413
+ * require Authorization: Bearer <token> (operad commit c3e71ce6); without it
1414
+ * they return 401 and every launch falls back to the share sheet.
1415
+ * @returns {Promise<Record<string, string>>} headers to spread into fetch opts
1416
+ */
1417
+ function operadAuthHeaders() {
1418
+ return new Promise((resolve) => {
1419
+ chrome.storage.local.get("operadToken", (data) => {
1420
+ resolve(data.operadToken ? { Authorization: `Bearer ${data.operadToken}` } : {});
1421
+ });
1422
+ });
1423
+ }
1424
+
1376
1425
  async function launchBridge() {
1377
1426
  addLog("info", "Attempting to launch bridge");
1378
1427
 
@@ -1396,14 +1445,19 @@ async function launchBridge() {
1396
1445
  }
1397
1446
 
1398
1447
  // Try starting bridge via tmx daemon HTTP API (always-on, no share sheet needed)
1448
+ const authHeaders = await operadAuthHeaders();
1399
1449
  try {
1400
1450
  const daemonCtrl = new AbortController();
1401
1451
  const daemonTimer = setTimeout(() => daemonCtrl.abort(), 3000);
1402
1452
  const daemonResp = await fetch("http://127.0.0.1:18970/api/bridge", {
1403
1453
  method: "POST",
1454
+ headers: authHeaders,
1404
1455
  signal: daemonCtrl.signal,
1405
1456
  });
1406
1457
  clearTimeout(daemonTimer);
1458
+ if (daemonResp.status === 401) {
1459
+ addLog("warn", "Daemon rejected request (401) — paste `operad token` output into the popup's Daemon Token field");
1460
+ }
1407
1461
  if (daemonResp.ok) {
1408
1462
  const data = await daemonResp.json();
1409
1463
  addLog("info", `Bridge start via daemon: ${data.status}`, data);
@@ -1422,6 +1476,7 @@ async function launchBridge() {
1422
1476
  const tsTimer = setTimeout(() => tsCtrl.abort(), 5000);
1423
1477
  const tsResp = await fetch("http://127.0.0.1:18970/api/bridge/termux-service", {
1424
1478
  method: "POST",
1479
+ headers: authHeaders,
1425
1480
  signal: tsCtrl.signal,
1426
1481
  });
1427
1482
  clearTimeout(tsTimer);
@@ -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 to avoid blocking
93
- setTimeout(() => {
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
- }, 0);
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
- setTimeout(() => {
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
- }, 0);
128
+ });
125
129
  return true;
126
130
  });
127
131
 
@@ -169,6 +173,10 @@ async function handleAction(action, params) {
169
173
  return { width: window.innerWidth, height: window.innerHeight };
170
174
  case "upload_image":
171
175
  return uploadImage(params);
176
+ case "zapper_start":
177
+ return zapperStart();
178
+ case "zapper_stop":
179
+ return zapperStop();
172
180
  default:
173
181
  return { error: `Unknown action: ${action}` };
174
182
  }
@@ -485,6 +493,10 @@ function formInput(params) {
485
493
  */
486
494
  const MAIN_WORLD_TIMEOUT_MS = 5000;
487
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.
488
500
  function executeInMainWorld(code) {
489
501
  return new Promise((resolve, reject) => {
490
502
  const id = (crypto?.randomUUID && crypto.randomUUID()) ||
@@ -1042,3 +1054,294 @@ function uploadImage(params) {
1042
1054
  return { error: `Upload failed: ${err.message}` };
1043
1055
  }
1044
1056
  }
1057
+
1058
+ // --- Element Zapper ------------------------------------------------------------
1059
+ // Tap-to-fix mode for client-side overlays, popups, and paywalls where the
1060
+ // content exists in the DOM but is visually blocked. Started from the popup
1061
+ // ("Zap Element") via the background's start_zapper handler. Tapping an element
1062
+ // selects it (with a smart climb to the enclosing fixed-position overlay root
1063
+ // when one covers most of the viewport). Toolbar: Wider / Remove / Reveal /
1064
+ // Undo / Done. Two paywall archetypes are handled:
1065
+ // • Overlay covers content → Remove deletes the selected overlay element.
1066
+ // • Content obscured in place → Reveal strips blur/opacity/pointer-events
1067
+ // locks page-wide (e.g. mlive applies filter:blur() directly to the article
1068
+ // paragraphs, so removing them would delete the content — un-blur instead).
1069
+ // Removing or revealing also unlocks page scroll (sites set overflow:hidden on
1070
+ // html/body while gated). Removed nodes stay on an undo stack so a mis-tap is
1071
+ // recoverable until Done; Reveal is non-destructive.
1072
+
1073
+ let zapperState = null;
1074
+
1075
+ function zapperStart() {
1076
+ if (zapperState) return { result: "Zapper already active" };
1077
+
1078
+ const MAX_Z = 2147483647;
1079
+ const state = {
1080
+ selected: null,
1081
+ undoStack: [],
1082
+ unlockStyle: null,
1083
+ listeners: [],
1084
+ };
1085
+
1086
+ // Highlight box tracking the selected element (pointer-events:none so it
1087
+ // never interferes with elementFromPoint or taps)
1088
+ const highlight = document.createElement("div");
1089
+ highlight.setAttribute("data-cfc-zapper", "");
1090
+ highlight.style.cssText =
1091
+ "position:fixed;pointer-events:none;z-index:" + MAX_Z + ";display:none;" +
1092
+ "background:rgba(248,81,73,0.25);border:2px solid #f85149;border-radius:4px;" +
1093
+ "box-sizing:border-box;transition:top 0.08s,left 0.08s,width 0.08s,height 0.08s";
1094
+
1095
+ // Floating toolbar — touch-friendly, fixed to bottom of viewport
1096
+ const bar = document.createElement("div");
1097
+ bar.setAttribute("data-cfc-zapper", "");
1098
+ bar.style.cssText =
1099
+ "position:fixed;left:8px;right:8px;bottom:12px;z-index:" + MAX_Z + ";" +
1100
+ "background:#161b22;color:#c9d1d9;border:1px solid #30363d;border-radius:12px;" +
1101
+ "box-shadow:0 4px 24px rgba(0,0,0,0.6);padding:10px 12px;" +
1102
+ "font:13px -apple-system,system-ui,sans-serif;box-sizing:border-box";
1103
+
1104
+ const label = document.createElement("div");
1105
+ label.style.cssText =
1106
+ "font-family:monospace;font-size:11px;color:#8b949e;margin-bottom:8px;" +
1107
+ "white-space:nowrap;overflow:hidden;text-overflow:ellipsis";
1108
+ const DEFAULT_HINT = "Tap an overlay to Remove, or Reveal to un-blur content";
1109
+ label.textContent = DEFAULT_HINT;
1110
+
1111
+ const row = document.createElement("div");
1112
+ row.style.cssText = "display:flex;gap:8px";
1113
+
1114
+ function mkBtn(text, bg) {
1115
+ const b = document.createElement("button");
1116
+ b.setAttribute("data-cfc-zapper", "");
1117
+ b.textContent = text;
1118
+ b.style.cssText =
1119
+ "flex:1;min-height:40px;border:1px solid #30363d;border-radius:8px;" +
1120
+ "background:" + (bg || "#21262d") + ";color:#fff;font:600 13px -apple-system,system-ui,sans-serif";
1121
+ row.appendChild(b);
1122
+ return b;
1123
+ }
1124
+
1125
+ const widerBtn = mkBtn("Wider");
1126
+ const removeBtn = mkBtn("Remove", "#da3633");
1127
+ const revealBtn = mkBtn("Reveal", "#1f6feb");
1128
+ const undoBtn = mkBtn("Undo");
1129
+ const doneBtn = mkBtn("Done", "#238636");
1130
+
1131
+ bar.appendChild(label);
1132
+ bar.appendChild(row);
1133
+ document.documentElement.appendChild(highlight);
1134
+ document.documentElement.appendChild(bar);
1135
+ state.highlight = highlight;
1136
+ state.bar = bar;
1137
+
1138
+ function describe(el) {
1139
+ let s = "<" + el.tagName.toLowerCase();
1140
+ if (el.id) s += " id=" + el.id;
1141
+ else if (typeof el.className === "string" && el.className.trim()) {
1142
+ s += " ." + el.className.trim().split(/\s+/).slice(0, 2).join(".");
1143
+ }
1144
+ const r = el.getBoundingClientRect();
1145
+ return s + "> " + Math.round(r.width) + "×" + Math.round(r.height);
1146
+ }
1147
+
1148
+ function refreshUi() {
1149
+ if (state.selected && state.selected.isConnected) {
1150
+ const r = state.selected.getBoundingClientRect();
1151
+ highlight.style.display = "block";
1152
+ highlight.style.top = r.top + "px";
1153
+ highlight.style.left = r.left + "px";
1154
+ highlight.style.width = r.width + "px";
1155
+ highlight.style.height = r.height + "px";
1156
+ label.textContent = describe(state.selected);
1157
+ } else {
1158
+ state.selected = null;
1159
+ highlight.style.display = "none";
1160
+ label.textContent = DEFAULT_HINT;
1161
+ }
1162
+ removeBtn.style.opacity = state.selected ? "1" : "0.4";
1163
+ widerBtn.style.opacity = state.selected ? "1" : "0.4";
1164
+ undoBtn.style.opacity = state.undoStack.length ? "1" : "0.4";
1165
+ }
1166
+
1167
+ // Prefer the outermost fixed/sticky (or positioned high-z absolute) ancestor
1168
+ // when it covers most of the viewport — that's the overlay root sites mount
1169
+ // paywalls/modals on. Otherwise keep the exact tapped element.
1170
+ function pickOverlayRoot(el) {
1171
+ let best = el;
1172
+ let cur = el;
1173
+ const viewArea = window.innerWidth * window.innerHeight;
1174
+ while (cur && cur !== document.body && cur !== document.documentElement) {
1175
+ const cs = getComputedStyle(cur);
1176
+ const positioned =
1177
+ cs.position === "fixed" || cs.position === "sticky" ||
1178
+ (cs.position === "absolute" && (parseInt(cs.zIndex, 10) || 0) >= 1);
1179
+ if (positioned) {
1180
+ const r = cur.getBoundingClientRect();
1181
+ if (r.width * r.height >= 0.5 * viewArea) best = cur;
1182
+ }
1183
+ cur = cur.parentElement;
1184
+ }
1185
+ return best;
1186
+ }
1187
+
1188
+ // While an overlay is up, sites lock scroll with overflow:hidden (and
1189
+ // sometimes position:fixed) on html/body — undo that once we zap something.
1190
+ function applyScrollUnlock() {
1191
+ if (state.unlockStyle) return;
1192
+ const st = document.createElement("style");
1193
+ st.setAttribute("data-cfc-zapper", "");
1194
+ st.textContent =
1195
+ "html,body{overflow:auto !important;position:static !important;height:auto !important;}";
1196
+ document.documentElement.appendChild(st);
1197
+ state.unlockStyle = st;
1198
+ }
1199
+
1200
+ function onPointerDown(e) {
1201
+ if (e.target && e.target.closest && e.target.closest("[data-cfc-zapper]")) return;
1202
+ e.preventDefault();
1203
+ e.stopPropagation();
1204
+ e.stopImmediatePropagation();
1205
+ const el = document.elementFromPoint(e.clientX, e.clientY);
1206
+ if (!el || el === document.documentElement || el === document.body) {
1207
+ state.selected = null;
1208
+ } else {
1209
+ state.selected = pickOverlayRoot(el);
1210
+ }
1211
+ refreshUi();
1212
+ }
1213
+
1214
+ // Swallow the rest of the tap gesture so the page never reacts to zap taps
1215
+ function swallow(e) {
1216
+ if (e.target && e.target.closest && e.target.closest("[data-cfc-zapper]")) return;
1217
+ e.preventDefault();
1218
+ e.stopPropagation();
1219
+ e.stopImmediatePropagation();
1220
+ }
1221
+
1222
+ function listen(type, fn, opts) {
1223
+ document.addEventListener(type, fn, opts);
1224
+ state.listeners.push([type, fn, opts]);
1225
+ }
1226
+
1227
+ listen("pointerdown", onPointerDown, { capture: true, passive: false });
1228
+ for (const t of ["pointerup", "mousedown", "mouseup", "click", "touchstart", "touchend", "touchmove"]) {
1229
+ listen(t, swallow, { capture: true, passive: false });
1230
+ }
1231
+ const reposition = () => refreshUi();
1232
+ listen("scroll", reposition, { capture: true, passive: true });
1233
+ window.addEventListener("resize", reposition, { passive: true });
1234
+ state.listeners.push(["__window_resize", reposition, null]);
1235
+
1236
+ widerBtn.addEventListener("click", () => {
1237
+ const p = state.selected && state.selected.parentElement;
1238
+ if (p && p !== document.body && p !== document.documentElement) {
1239
+ state.selected = p;
1240
+ refreshUi();
1241
+ }
1242
+ });
1243
+
1244
+ removeBtn.addEventListener("click", () => {
1245
+ const el = state.selected;
1246
+ if (!el || !el.isConnected) return;
1247
+ state.undoStack.push({ el, parent: el.parentNode, next: el.nextSibling });
1248
+ el.remove();
1249
+ applyScrollUnlock();
1250
+ state.selected = null;
1251
+ refreshUi();
1252
+ });
1253
+
1254
+ // Reveal: for paywalls that obscure the real content in place (blur filter,
1255
+ // low opacity, pointer-events/user-select locks) rather than covering it with
1256
+ // a removable overlay — the content is in the DOM, so we un-hide it instead of
1257
+ // deleting it. Scoped to the selection subtree when one is picked, else the
1258
+ // whole page. Non-destructive; a persistent override style prevents re-hiding.
1259
+ function revealObscured(scope) {
1260
+ const root = scope && scope.isConnected ? scope : document.body;
1261
+ // Include the scope itself plus every descendant.
1262
+ const els = [root, ...root.querySelectorAll("*")];
1263
+ let count = 0;
1264
+ for (const el of els) {
1265
+ if (el.closest && el.closest("[data-cfc-zapper]")) continue;
1266
+ const cs = getComputedStyle(el);
1267
+ let changed = false;
1268
+ if (cs.filter && cs.filter !== "none" && /blur|grayscale/i.test(cs.filter)) {
1269
+ el.style.setProperty("filter", "none", "important");
1270
+ el.style.setProperty("-webkit-filter", "none", "important");
1271
+ changed = true;
1272
+ }
1273
+ // Faded-out content (not fully hidden — opacity:0 is usually a real hide).
1274
+ const op = parseFloat(cs.opacity);
1275
+ if (!isNaN(op) && op > 0 && op < 0.6 && (el.textContent || "").trim().length > 20) {
1276
+ el.style.setProperty("opacity", "1", "important");
1277
+ changed = true;
1278
+ }
1279
+ // Reading/selection locks used to discourage copying gated text.
1280
+ if (cs.pointerEvents === "none") { el.style.setProperty("pointer-events", "auto", "important"); changed = true; }
1281
+ if (cs.userSelect === "none") { el.style.setProperty("user-select", "text", "important"); changed = true; }
1282
+ if (el.classList && el.classList.length) {
1283
+ for (const c of [...el.classList]) {
1284
+ if (/blur|obfuscat|paywall|gated|faded/i.test(c)) { el.classList.remove(c); changed = true; }
1285
+ }
1286
+ }
1287
+ if (changed) count++;
1288
+ }
1289
+ // Persistent override so classes re-applied by the site's JS can't re-blur.
1290
+ if (!state.revealStyle) {
1291
+ const st = document.createElement("style");
1292
+ st.setAttribute("data-cfc-zapper", "");
1293
+ st.textContent =
1294
+ '[class*="blur" i],[class*="obfuscat" i],[class*="gated" i],[class*="paywall" i]' +
1295
+ "{filter:none !important;-webkit-filter:none !important;opacity:1 !important;}";
1296
+ document.documentElement.appendChild(st);
1297
+ state.revealStyle = st;
1298
+ }
1299
+ applyScrollUnlock();
1300
+ return count;
1301
+ }
1302
+
1303
+ revealBtn.addEventListener("click", () => {
1304
+ // These paywalls blur many elements across the article, so default to the
1305
+ // whole page. A picked container narrows it only when the user selected one
1306
+ // bigger than a single inline/text node.
1307
+ const sel = state.selected;
1308
+ const scope = sel && sel.querySelectorAll && sel.querySelectorAll("*").length > 3 ? sel : document.body;
1309
+ const n = revealObscured(scope);
1310
+ label.textContent = "Revealed " + n + " element(s) — content un-blurred";
1311
+ });
1312
+
1313
+ undoBtn.addEventListener("click", () => {
1314
+ const entry = state.undoStack.pop();
1315
+ if (entry && entry.parent) {
1316
+ try {
1317
+ entry.parent.insertBefore(entry.el, entry.next && entry.next.parentNode === entry.parent ? entry.next : null);
1318
+ } catch {}
1319
+ }
1320
+ if (!state.undoStack.length && state.unlockStyle) {
1321
+ state.unlockStyle.remove();
1322
+ state.unlockStyle = null;
1323
+ }
1324
+ refreshUi();
1325
+ });
1326
+
1327
+ doneBtn.addEventListener("click", () => zapperStop());
1328
+
1329
+ zapperState = state;
1330
+ refreshUi();
1331
+ return { result: "Zapper started — Remove overlays, or Reveal to un-blur in-place content" };
1332
+ }
1333
+
1334
+ function zapperStop() {
1335
+ const state = zapperState;
1336
+ if (!state) return { result: "Zapper not active" };
1337
+ for (const [type, fn, opts] of state.listeners) {
1338
+ if (type === "__window_resize") window.removeEventListener("resize", fn);
1339
+ else document.removeEventListener(type, fn, opts);
1340
+ }
1341
+ state.bar.remove();
1342
+ state.highlight.remove();
1343
+ // Removed elements stay removed and the scroll unlock persists — that's the
1344
+ // point of zapping. Only the mode UI is torn down.
1345
+ zapperState = null;
1346
+ return { result: `Zapper stopped (${state.undoStack.length} element(s) removed)` };
1347
+ }
@@ -1,98 +1,79 @@
1
- // Launch bridge — tries daemon API first, falls back to navigator.share() → Termux.
2
- // Browser intent: URIs add CATEGORY_BROWSABLE which Termux doesn't declare,
3
- // so navigator.share() (native OS share, no BROWSABLE) is the only path
4
- // when the daemon isn't running.
5
-
1
+ // The background owns daemon startup and connection polling. Sharing stays in
2
+ // this tab's click handler so Android receives a fresh user activation.
6
3
  const btn = document.getElementById("share-btn");
7
4
  const status = document.getElementById("status");
8
- const setupHint = document.getElementById("setup-hint");
5
+ let connected = false;
6
+ let waitingTimer;
7
+
8
+ /** Mark a confirmed connection; late startup callbacks must not overwrite it. */
9
+ function showConnected() {
10
+ if (connected) return;
11
+ connected = true;
12
+ clearTimeout(waitingTimer);
13
+ status.textContent = "Bridge connected";
14
+ btn.textContent = "Already Running";
15
+ btn.disabled = true;
16
+ setTimeout(() => window.close(), 1000);
17
+ }
18
+
19
+ /** Keep manual recovery available if startup never establishes a connection. */
20
+ function waitForConnection() {
21
+ if (connected) return;
22
+ clearTimeout(waitingTimer);
23
+ status.textContent = "Waiting for bridge to connect...";
24
+ btn.textContent = "Starting...";
25
+ btn.disabled = true;
26
+ waitingTimer = setTimeout(() => {
27
+ if (connected) return;
28
+ status.textContent = "Bridge didn't respond — share to Termux or use the command below";
29
+ btn.textContent = "Share to Termux";
30
+ btn.disabled = false;
31
+ }, 15000);
32
+ }
9
33
 
10
- // Listen for state updates from background.js (single source of truth for polling)
11
34
  chrome.runtime.onMessage.addListener((msg) => {
12
- if (msg.type === "state_update") {
13
- if (msg.state === "connected") {
14
- status.textContent = "Bridge connected";
15
- // Auto-close launcher tab after successful connection
16
- setTimeout(() => window.close(), 1000);
17
- }
18
- }
35
+ if (msg.type === "state_update" && msg.state === "connected") showConnected();
19
36
  });
20
37
 
21
- // On load: try daemon API first — may start bridge without share sheet
22
- (async () => {
23
- // Check if already connected
24
- chrome.runtime.sendMessage({ type: "get_state" }, (resp) => {
25
- if (resp?.state === "connected") {
26
- status.textContent = "Bridge is already connected";
27
- btn.textContent = "Already Running";
28
- btn.disabled = true;
29
- }
30
- });
31
-
32
- // Try starting via daemon HTTP API (works when Termux is running)
38
+ btn.disabled = true;
39
+ status.textContent = "Checking bridge...";
40
+ chrome.runtime.sendMessage({ type: "get_state" }, (state) => {
41
+ const stateError = chrome.runtime.lastError;
42
+ if (!stateError && state?.state === "connected") {
43
+ showConnected();
44
+ return;
45
+ }
46
+ if (connected) return;
33
47
  status.textContent = "Trying daemon...";
34
- try {
35
- const ctrl = new AbortController();
36
- const timer = setTimeout(() => ctrl.abort(), 3000);
37
- const resp = await fetch("http://127.0.0.1:18970/api/bridge", {
38
- method: "POST",
39
- signal: ctrl.signal,
40
- });
41
- clearTimeout(timer);
42
- if (resp.ok) {
43
- const data = await resp.json();
44
- if (data.status === "starting" || data.status === "already_running") {
45
- status.textContent = `Bridge ${data.status} via daemon — waiting for connection...`;
46
- btn.textContent = "Starting...";
47
- btn.disabled = true;
48
- // Tell background to start polling
49
- chrome.runtime.sendMessage({ type: "bridge_launch_initiated" });
50
- // Auto-close timeout
51
- setTimeout(() => {
52
- if (status.textContent.includes("waiting")) {
53
- status.textContent = "Bridge didn't respond — try share button below";
54
- btn.textContent = "Share to Termux";
55
- btn.disabled = false;
56
- }
57
- }, 12000);
58
- return; // Daemon handled it
59
- }
48
+ chrome.runtime.sendMessage({ type: "launch_bridge" }, (response) => {
49
+ const launchError = chrome.runtime.lastError;
50
+ if (connected) return;
51
+ if (!launchError && response?.ok) {
52
+ waitForConnection();
53
+ return;
60
54
  }
61
- } catch {
62
- // Daemon not reachable — Termux may not be running
63
- }
64
-
65
- // Daemon didn't work — show share button
66
- status.textContent = "Tap below to share to Termux and start the bridge";
67
- })();
55
+ status.textContent = "Choose Share to Termux, then select Termux in the share sheet";
56
+ btn.disabled = false;
57
+ });
58
+ });
68
59
 
69
60
  btn.addEventListener("click", async () => {
70
61
  btn.textContent = "Opening share sheet...";
71
62
  btn.disabled = true;
72
-
63
+ clearTimeout(waitingTimer);
73
64
  try {
65
+ // This exact URL matches both installed and generated termux-url-opener
66
+ // handlers (*cfcbridge*/start*). Share only text to avoid merged payloads.
74
67
  await navigator.share({ text: "https://cfcbridge.example.com/start" });
75
- // User picked a target (hopefully Termux)
76
- status.textContent = "Shared — waiting for bridge to start...";
77
- btn.textContent = "Share to Termux";
78
- btn.disabled = false;
79
-
80
- // Notify background.js to start polling (it's the single source of truth)
68
+ if (connected) return;
69
+ waitForConnection();
81
70
  chrome.runtime.sendMessage({ type: "bridge_launch_initiated" });
82
-
83
- // Simple local timeout — background handles the actual polling
84
- setTimeout(() => {
85
- if (status.textContent.includes("waiting")) {
86
- status.textContent = "Bridge didn't start — try again or start manually in Termux";
87
- }
88
- }, 15000);
89
- } catch (e) {
71
+ } catch (error) {
72
+ if (connected) return;
90
73
  btn.textContent = "Share to Termux";
91
74
  btn.disabled = false;
92
- if (e.name === "AbortError") {
93
- status.textContent = "Cancelled — tap to try again";
94
- } else {
95
- status.textContent = "Error: " + e.message;
96
- }
75
+ status.textContent = error.name === "AbortError"
76
+ ? "Cancelled — tap to try again"
77
+ : "Sharing unavailable — use the command below: " + error.message;
97
78
  }
98
79
  });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 2,
3
3
  "name": "Claude Code Browser Bridge",
4
- "version": "1.11.1",
4
+ "version": "1.13.0",
5
5
  "description": "Bridges Claude Code CLI to Edge Android via WebSocket",
6
6
  "permissions": [
7
7
  "activeTab",