@capybara-hq/plugin-browser 0.0.0-stage → 0.1.0-rc.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.
Files changed (63) hide show
  1. package/.capybara-plugin/plugin.json +100 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +2 -0
  4. package/README.md +77 -2
  5. package/dist/index.mjs +920 -0
  6. package/icon.svg +1 -0
  7. package/package.json +19 -4
  8. package/ui/panel.js +704 -0
  9. package/ui/service/daemon.mjs +2077 -0
  10. package/ui/service/vendor/playwright-core/LICENSE +202 -0
  11. package/ui/service/vendor/playwright-core/NOTICE +5 -0
  12. package/ui/service/vendor/playwright-core/README.md +3 -0
  13. package/ui/service/vendor/playwright-core/ThirdPartyNotices.txt +13 -0
  14. package/ui/service/vendor/playwright-core/browsers.json +52 -0
  15. package/ui/service/vendor/playwright-core/cli.js +22 -0
  16. package/ui/service/vendor/playwright-core/index.js +17 -0
  17. package/ui/service/vendor/playwright-core/index.mjs +28 -0
  18. package/ui/service/vendor/playwright-core/lib/bootstrap.js +149 -0
  19. package/ui/service/vendor/playwright-core/lib/coreBundle.js +78764 -0
  20. package/ui/service/vendor/playwright-core/lib/entry/cliDaemon.js +5 -0
  21. package/ui/service/vendor/playwright-core/lib/entry/dashboardApp.js +3 -0
  22. package/ui/service/vendor/playwright-core/lib/entry/mcp.js +10 -0
  23. package/ui/service/vendor/playwright-core/lib/entry/oopBrowserDownload.js +3 -0
  24. package/ui/service/vendor/playwright-core/lib/package.js +50 -0
  25. package/ui/service/vendor/playwright-core/lib/server/chromium/appIcon.png +0 -0
  26. package/ui/service/vendor/playwright-core/lib/server/electron/loader.js +130 -0
  27. package/ui/service/vendor/playwright-core/lib/serverRegistry.js +1939 -0
  28. package/ui/service/vendor/playwright-core/lib/serverRegistry.js.LICENSE +65 -0
  29. package/ui/service/vendor/playwright-core/lib/tools/cli-client/channelSessions.js +143 -0
  30. package/ui/service/vendor/playwright-core/lib/tools/cli-client/cli.js +7 -0
  31. package/ui/service/vendor/playwright-core/lib/tools/cli-client/help.json +813 -0
  32. package/ui/service/vendor/playwright-core/lib/tools/cli-client/minimist.js +128 -0
  33. package/ui/service/vendor/playwright-core/lib/tools/cli-client/output.js +352 -0
  34. package/ui/service/vendor/playwright-core/lib/tools/cli-client/program.js +422 -0
  35. package/ui/service/vendor/playwright-core/lib/tools/cli-client/registry.js +180 -0
  36. package/ui/service/vendor/playwright-core/lib/tools/cli-client/session.js +261 -0
  37. package/ui/service/vendor/playwright-core/lib/tools/dashboard/appIcon.png +0 -0
  38. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/SKILL.md +493 -0
  39. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/element-attributes.md +23 -0
  40. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/playwright-tests.md +39 -0
  41. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/pr-attachments.md +60 -0
  42. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/request-mocking.md +87 -0
  43. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/running-code.md +247 -0
  44. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/session-management.md +227 -0
  45. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/storage-state.md +278 -0
  46. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/test-generation.md +433 -0
  47. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/tracing.md +146 -0
  48. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/video-recording.md +216 -0
  49. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-component-testing/SKILL.md +136 -0
  50. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-component-testing/references/gallery-spec.md +144 -0
  51. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-component-testing/references/migration.md +89 -0
  52. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-component-testing/references/react.md +69 -0
  53. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-component-testing/references/typing.md +173 -0
  54. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-component-testing/references/vue.md +77 -0
  55. package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-trace/SKILL.md +174 -0
  56. package/ui/service/vendor/playwright-core/lib/tools/utils/extension.js +112 -0
  57. package/ui/service/vendor/playwright-core/lib/tools/utils/socketConnection.js +108 -0
  58. package/ui/service/vendor/playwright-core/lib/utilsBundle.js +92408 -0
  59. package/ui/service/vendor/playwright-core/lib/utilsBundle.js.LICENSE +1917 -0
  60. package/ui/service/vendor/playwright-core/lib/webp_codec.LICENSE +173 -0
  61. package/ui/service/vendor/playwright-core/lib/webp_codec.wasm +0 -0
  62. package/ui/service/vendor/playwright-core/lib/xdg-open +1267 -0
  63. package/ui/service/vendor/playwright-core/package.json +34 -0
package/ui/panel.js ADDED
@@ -0,0 +1,704 @@
1
+ "use strict";
2
+ (() => {
3
+ // daemon/protocol.ts
4
+ var VIEWPORT = { width: 1280, height: 800 };
5
+ var IDLE_STOP_MS = 15 * 6e4;
6
+ var DEFAULT_FRAME_MAX_BYTES = 256 * 1024;
7
+ var HANDOFF_KEEPALIVE_MS = 24 * 60 * 6e4;
8
+
9
+ // ui-src/panel/i18n.ts
10
+ var STRINGS = {
11
+ en: {
12
+ title: "Browser",
13
+ back: "Back",
14
+ forward: "Forward",
15
+ reload: "Reload",
16
+ address: "Address",
17
+ newTab: "New tab",
18
+ closeTab: "Close tab",
19
+ takeover: "Take over",
20
+ handback: "Hand back to the agent",
21
+ takeoverHint: "You are controlling the browser. Press Esc to hand it back.",
22
+ statusAgent: "The agent is using the browser",
23
+ statusUserElsewhere: "You are controlling the browser from another view",
24
+ statusLoading: "Loading…",
25
+ statusConnecting: "Connecting…",
26
+ blocked: "Blocked by the network setting:",
27
+ allow: "Allow",
28
+ dialog: "The page shows a dialog:",
29
+ emptyTitle: "The browser is not running",
30
+ emptyBody: "It starts when the agent first uses a browser tool.",
31
+ offlineTitle: "The device is offline",
32
+ offlineBody: "The live view needs the device that runs the browser.",
33
+ errorTitle: "The live view stopped",
34
+ errorBody: "The frame was too large or the connection failed.",
35
+ handoff: "The agent asks you to finish in the browser:",
36
+ handoffDone: "Done",
37
+ handoffCancel: "Cancel",
38
+ reconnect: "Reconnect",
39
+ view: "Browser view",
40
+ secure: "Secure connection",
41
+ fileDialog: "The page opened a file chooser; the agent can pick a file with its upload tool.",
42
+ allowFailed: "Could not allow the host:",
43
+ answerFailed: "Could not send your answer:"
44
+ },
45
+ zh: {
46
+ title: "浏览器",
47
+ back: "后退",
48
+ forward: "前进",
49
+ reload: "刷新",
50
+ address: "地址",
51
+ newTab: "新标签页",
52
+ closeTab: "关闭标签页",
53
+ takeover: "接管",
54
+ handback: "交还智能体",
55
+ takeoverHint: "你正在控制浏览器。按 Esc 交还给智能体。",
56
+ statusAgent: "智能体正在使用浏览器",
57
+ statusUserElsewhere: "你正在另一个视图中控制浏览器",
58
+ statusLoading: "加载中…",
59
+ statusConnecting: "正在连接…",
60
+ blocked: "被网络设置拦截:",
61
+ allow: "允许",
62
+ dialog: "页面弹出了对话框:",
63
+ emptyTitle: "浏览器尚未运行",
64
+ emptyBody: "智能体第一次使用浏览器工具时会启动它。",
65
+ offlineTitle: "设备已离线",
66
+ offlineBody: "实时画面需要运行浏览器的设备在线。",
67
+ errorTitle: "实时画面已中断",
68
+ errorBody: "画面过大或连接失败。",
69
+ handoff: "智能体请你在浏览器里完成:",
70
+ handoffDone: "完成",
71
+ handoffCancel: "取消",
72
+ reconnect: "重新连接",
73
+ view: "浏览器画面",
74
+ secure: "安全连接",
75
+ fileDialog: "页面打开了文件选择框;智能体可以用上传工具选择文件。",
76
+ allowFailed: "无法允许该主机:",
77
+ answerFailed: "无法发送你的回答:"
78
+ }
79
+ };
80
+ function t(locale, key) {
81
+ return STRINGS[locale][key];
82
+ }
83
+
84
+ // ui-src/panel/panel.ts
85
+ var PROTOCOL = "capybara-embed/1";
86
+ var ASPECT = VIEWPORT.width / VIEWPORT.height;
87
+ var SIDE_MAX_WIDTH = 640;
88
+ var HIDDEN_CLOSE_MS = 6e4;
89
+ var COMPACT_BELOW = 600;
90
+ var MOVE_INTERVAL_MS = 50;
91
+ var RESTART_RETRY_MS = [1e3, 3e3];
92
+ var EMPTY_POLL_MS = 1e4;
93
+ var EMPTY_POLL_FOR_MS = 30 * 6e4;
94
+ var STRIP_MS = 1e4;
95
+ var PENDING_NAV_MS = 3e4;
96
+ function letterbox(width, height) {
97
+ let w = width;
98
+ let h = Math.round(w / ASPECT);
99
+ if (h > height) {
100
+ h = height;
101
+ w = Math.round(h * ASPECT);
102
+ }
103
+ return { x: Math.round((width - w) / 2), y: Math.round((height - h) / 2), w, h };
104
+ }
105
+ function mapPoint(px, py, rect) {
106
+ const clamp = (v, max) => Math.max(0, Math.min(max, v));
107
+ return {
108
+ x: Math.round(clamp(px / rect.w, 1) * VIEWPORT.width),
109
+ y: Math.round(clamp(py / rect.h, 1) * VIEWPORT.height)
110
+ };
111
+ }
112
+ function mountPanel(opts) {
113
+ const win = opts.window;
114
+ const doc = win.document;
115
+ const doFetch = opts.fetch ?? win.fetch.bind(win);
116
+ const SocketCtor = opts.WebSocket ?? win.WebSocket;
117
+ const post = opts.post ?? ((m) => win.parent.postMessage(m, "*"));
118
+ const decode = opts.decode ?? ((jpeg) => win.createImageBitmap(new Blob([jpeg], { type: "image/jpeg" })));
119
+ const $ = (id) => doc.getElementById(id);
120
+ const view = $("view");
121
+ const stage = $("stage");
122
+ const url = $("url");
123
+ let locale = "en";
124
+ let token = "";
125
+ let started = false;
126
+ let gen = 0;
127
+ let sock = null;
128
+ let mode = "connecting";
129
+ let tabs = [];
130
+ let control = "agent";
131
+ let lastState = null;
132
+ let retried401 = false;
133
+ let attempts = 0;
134
+ let restartRetries = 0;
135
+ let retryTimer;
136
+ let emptyTimer;
137
+ let emptySince;
138
+ let dialogTimer;
139
+ let dialogUrl;
140
+ let noticeTimer;
141
+ let pendingNav = null;
142
+ let seenClick;
143
+ let hiddenTimer;
144
+ let pausedForHidden = false;
145
+ let blockedHost = "";
146
+ let blockedUrl = "";
147
+ let pendingHandoff = null;
148
+ let sentSize = "";
149
+ let lastMove = Number.NEGATIVE_INFINITY;
150
+ let image = null;
151
+ const compact = () => win.innerWidth < COMPACT_BELOW;
152
+ const text = (key) => t(locale, key);
153
+ const interactive = () => !compact() && control === "user";
154
+ function send(msg) {
155
+ if (sock === null) return;
156
+ sock.send(new TextEncoder().encode(JSON.stringify(msg)));
157
+ }
158
+ const bridge = (full) => post({ protocol: PROTOCOL, type: "panel-mode", full });
159
+ function setLabels() {
160
+ const set = (id, key) => {
161
+ $(id).textContent = text(key);
162
+ };
163
+ set("takeover", "takeover");
164
+ set("handback", "handback");
165
+ set("allow", "allow");
166
+ set("reconnect", "reconnect");
167
+ set("blocked-label", "blocked");
168
+ set("dialog-label", "dialog");
169
+ set("handoff-label", "handoff");
170
+ set("handoff-done", "handoffDone");
171
+ set("handoff-cancel", "handoffCancel");
172
+ $("lock").setAttribute("aria-label", text("secure"));
173
+ $("lock").setAttribute("title", text("secure"));
174
+ for (const [id, key] of [
175
+ ["back", "back"],
176
+ ["forward", "forward"],
177
+ ["reload", "reload"]
178
+ ]) {
179
+ $(id).setAttribute("aria-label", text(key));
180
+ $(id).setAttribute("title", text(key));
181
+ $(id).textContent = id === "back" ? "<" : id === "forward" ? ">" : "↻";
182
+ }
183
+ url.setAttribute("aria-label", text("address"));
184
+ view.setAttribute("aria-label", text("view"));
185
+ doc.title = text("title");
186
+ doc.documentElement.lang = locale;
187
+ }
188
+ function renderStatus() {
189
+ const el = $("status");
190
+ el.setAttribute("data-control", control);
191
+ let key;
192
+ if (mode === "connecting") key = "statusConnecting";
193
+ else if (control === "user") key = compact() ? "statusUserElsewhere" : "takeoverHint";
194
+ else if (lastState?.loading === true) key = "statusLoading";
195
+ else key = "statusAgent";
196
+ el.textContent = text(key);
197
+ }
198
+ function renderChrome() {
199
+ const watchOnly = compact();
200
+ const isLive = mode === "live";
201
+ $("takeover").hidden = watchOnly || !isLive || control === "user";
202
+ $("handback").hidden = watchOnly || !isLive || control !== "user";
203
+ for (const id of ["back", "forward", "reload"])
204
+ $(id).disabled = watchOnly;
205
+ url.readOnly = watchOnly;
206
+ view.style.cursor = interactive() ? "default" : "pointer";
207
+ $("lock").hidden = !isLive || lastState?.secure !== true;
208
+ const showEmpty = mode === "empty" || mode === "offline" || mode === "error";
209
+ $("empty").hidden = !showEmpty;
210
+ $("reconnect").hidden = !showEmpty;
211
+ const keys = {
212
+ empty: ["emptyTitle", "emptyBody"],
213
+ offline: ["offlineTitle", "offlineBody"],
214
+ error: ["errorTitle", "errorBody"]
215
+ };
216
+ const k = keys[mode];
217
+ if (k !== void 0) {
218
+ $("empty-title").textContent = text(k[0]);
219
+ $("empty-body").textContent = text(k[1]);
220
+ }
221
+ $("blocked").hidden = blockedHost === "";
222
+ $("blocked-host").textContent = blockedHost;
223
+ renderStatus();
224
+ }
225
+ function renderTabs() {
226
+ const box = $("tabs");
227
+ box.textContent = "";
228
+ const watchOnly = compact();
229
+ for (const tab of tabs) {
230
+ const el = doc.createElement("div");
231
+ el.className = "tab";
232
+ el.setAttribute("role", "tab");
233
+ el.setAttribute("data-active", String(tab.active));
234
+ const label = doc.createElement("button");
235
+ label.type = "button";
236
+ label.className = "label";
237
+ label.textContent = tab.title === "" ? tab.url : tab.title;
238
+ label.disabled = watchOnly;
239
+ label.addEventListener("click", () => send({ t: "tab", action: "switch", tabId: tab.id }));
240
+ el.appendChild(label);
241
+ if (!watchOnly) {
242
+ const close = doc.createElement("button");
243
+ close.type = "button";
244
+ close.textContent = "×";
245
+ close.setAttribute("aria-label", text("closeTab"));
246
+ close.addEventListener("click", () => send({ t: "tab", action: "close", tabId: tab.id }));
247
+ el.appendChild(close);
248
+ }
249
+ box.appendChild(el);
250
+ }
251
+ if (!watchOnly) {
252
+ const add = doc.createElement("button");
253
+ add.type = "button";
254
+ add.textContent = "+";
255
+ add.setAttribute("aria-label", text("newTab"));
256
+ add.addEventListener("click", () => send({ t: "tab", action: "open" }));
257
+ box.appendChild(add);
258
+ }
259
+ }
260
+ function applyState(s) {
261
+ lastState = s;
262
+ pendingHandoff = s.handoff ?? null;
263
+ $("handoff").hidden = pendingHandoff === null;
264
+ $("handoff-message").textContent = pendingHandoff?.message ?? "";
265
+ tabs = s.tabs;
266
+ control = s.control;
267
+ const active = tabs.find((x) => x.active);
268
+ if (doc.activeElement !== url) url.value = active?.url ?? "";
269
+ renderTabs();
270
+ renderChrome();
271
+ if (sock !== null) {
272
+ const { w, h } = layout();
273
+ if (`${w}x${h}` !== sentSize) sizeMessage("resize");
274
+ }
275
+ if (dialogUrl !== void 0 && active?.url !== dialogUrl) hideDialog();
276
+ reopenAllowed(active?.url);
277
+ const click = s.lastClick;
278
+ if (click !== void 0) {
279
+ const fresh = seenClick !== void 0 && click.seq > seenClick;
280
+ seenClick = Math.max(seenClick ?? 0, click.seq);
281
+ if (fresh) flashAt(click.x, click.y);
282
+ } else seenClick ??= 0;
283
+ }
284
+ function flashAt(x, y) {
285
+ const flash = $("flash");
286
+ const r = view.getBoundingClientRect();
287
+ const st = stage.getBoundingClientRect();
288
+ flash.style.left = `${r.left - st.left + x / VIEWPORT.width * r.width}px`;
289
+ flash.style.top = `${r.top - st.top + y / VIEWPORT.height * r.height}px`;
290
+ flash.hidden = false;
291
+ win.setTimeout(() => {
292
+ flash.hidden = true;
293
+ }, 600);
294
+ }
295
+ function reopenAllowed(activeUrl) {
296
+ const p = pendingNav;
297
+ if (p === null) return;
298
+ if (activeUrl === p.url || Date.now() > p.until) {
299
+ pendingNav = null;
300
+ return;
301
+ }
302
+ if (p.sentOn !== sock && sock !== null) {
303
+ p.sentOn = sock;
304
+ send({ t: "nav", url: p.url });
305
+ }
306
+ }
307
+ function showDialog(m) {
308
+ $("dialog-text").textContent = m.kind === "file" ? text("fileDialog") : m.message;
309
+ $("dialog").hidden = false;
310
+ dialogUrl = tabs.find((x) => x.active)?.url ?? "";
311
+ if (dialogTimer !== void 0) clearTimeout(dialogTimer);
312
+ dialogTimer = setTimeout(hideDialog, STRIP_MS);
313
+ }
314
+ function hideDialog() {
315
+ if (dialogTimer !== void 0) clearTimeout(dialogTimer);
316
+ dialogTimer = void 0;
317
+ dialogUrl = void 0;
318
+ $("dialog").hidden = true;
319
+ }
320
+ function notice(key, detail) {
321
+ $("notice-text").textContent = detail === "" ? text(key) : `${text(key)} ${detail}`;
322
+ $("notice").hidden = false;
323
+ if (noticeTimer !== void 0) clearTimeout(noticeTimer);
324
+ noticeTimer = setTimeout(() => {
325
+ $("notice").hidden = true;
326
+ }, STRIP_MS);
327
+ }
328
+ async function refusalOf(res) {
329
+ const body = await res.json().catch(() => ({}));
330
+ const m = body.error?.message;
331
+ return typeof m === "string" ? m.slice(0, 300) : "";
332
+ }
333
+ function layout() {
334
+ const st = stage.getBoundingClientRect();
335
+ const box = letterbox(Math.max(0, Math.floor(st.width)), Math.max(0, Math.floor(st.height)));
336
+ view.style.width = `${box.w}px`;
337
+ view.style.height = `${box.h}px`;
338
+ const dpr = win.devicePixelRatio || 1;
339
+ const cap = control === "user" ? VIEWPORT.width : SIDE_MAX_WIDTH;
340
+ const w = Math.max(1, Math.min(cap, Math.round(box.w * dpr)));
341
+ return { w, h: Math.max(1, Math.round(w / ASPECT)) };
342
+ }
343
+ function sizeMessage(kind) {
344
+ const { w, h } = layout();
345
+ sentSize = `${w}x${h}`;
346
+ send({ t: kind, maxWidth: w, maxHeight: h });
347
+ }
348
+ function draw() {
349
+ if (image === null) return;
350
+ const { w, h } = layout();
351
+ if (view.width !== w || view.height !== h) {
352
+ view.width = w;
353
+ view.height = h;
354
+ }
355
+ const ctx = view.getContext("2d");
356
+ ctx?.drawImage(image, 0, 0, w, h);
357
+ }
358
+ async function onFrame(m) {
359
+ try {
360
+ const bin = win.atob(m.jpeg);
361
+ const bytes = new Uint8Array(bin.length);
362
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
363
+ image = await decode(bytes);
364
+ draw();
365
+ } catch {
366
+ }
367
+ send({ t: "frame-ack", seq: m.seq });
368
+ }
369
+ function show(next) {
370
+ mode = next;
371
+ if (next === "empty") armEmptyPoll();
372
+ renderChrome();
373
+ }
374
+ function armEmptyPoll() {
375
+ emptySince ??= Date.now();
376
+ if (emptyTimer !== void 0) clearTimeout(emptyTimer);
377
+ emptyTimer = setTimeout(() => {
378
+ emptyTimer = void 0;
379
+ if (mode !== "empty" || emptySince === void 0) return;
380
+ if (Date.now() - emptySince >= EMPTY_POLL_FOR_MS) return;
381
+ if (doc.visibilityState === "hidden") armEmptyPoll();
382
+ else void connect();
383
+ }, EMPTY_POLL_MS);
384
+ }
385
+ function stop() {
386
+ gen++;
387
+ if (retryTimer !== void 0) clearTimeout(retryTimer);
388
+ if (emptyTimer !== void 0) clearTimeout(emptyTimer);
389
+ emptyTimer = void 0;
390
+ const s = sock;
391
+ sock = null;
392
+ if (s !== null) {
393
+ s.onclose = null;
394
+ s.onmessage = null;
395
+ s.close();
396
+ }
397
+ }
398
+ async function connect() {
399
+ stop();
400
+ const mine = gen;
401
+ show("connecting");
402
+ let ticketUrl;
403
+ try {
404
+ const res = await doFetch("stream-ticket", {
405
+ method: "POST",
406
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
407
+ body: "{}",
408
+ credentials: "omit"
409
+ });
410
+ const body = await res.json().catch(() => ({}));
411
+ if (mine !== gen) return;
412
+ const code = body.code ?? body.error?.code;
413
+ if (code === "service_not_running") return show("empty");
414
+ if (!res.ok || typeof body.url !== "string") return show("offline");
415
+ ticketUrl = body.url;
416
+ } catch {
417
+ if (mine === gen) show("offline");
418
+ return;
419
+ }
420
+ const ws = new SocketCtor(ticketUrl);
421
+ sock = ws;
422
+ ws.binaryType = "arraybuffer";
423
+ ws.onopen = () => sizeMessage("hello");
424
+ ws.onmessage = (e) => {
425
+ if (mine !== gen) return;
426
+ void onMessage(e.data);
427
+ };
428
+ ws.onclose = (e) => {
429
+ if (mine === gen) onClose(e.code);
430
+ };
431
+ }
432
+ async function onMessage(data) {
433
+ let raw;
434
+ if (typeof data === "string") raw = data;
435
+ else if (data instanceof ArrayBuffer) raw = new TextDecoder().decode(data);
436
+ else if (ArrayBuffer.isView(data)) raw = new TextDecoder().decode(data);
437
+ else if (typeof data.arrayBuffer === "function")
438
+ raw = new TextDecoder().decode(await data.arrayBuffer());
439
+ else return;
440
+ let msg;
441
+ try {
442
+ msg = JSON.parse(raw);
443
+ } catch {
444
+ return;
445
+ }
446
+ retried401 = false;
447
+ attempts = 0;
448
+ restartRetries = 0;
449
+ switch (msg.t) {
450
+ case "state":
451
+ mode = "live";
452
+ emptySince = void 0;
453
+ applyState(msg);
454
+ break;
455
+ case "frame":
456
+ void onFrame(msg);
457
+ break;
458
+ case "blocked":
459
+ blockedHost = msg.host;
460
+ blockedUrl = msg.url;
461
+ renderChrome();
462
+ break;
463
+ case "dialog":
464
+ showDialog(msg);
465
+ break;
466
+ }
467
+ }
468
+ function onClose(code) {
469
+ sock = null;
470
+ lastState = null;
471
+ if (code === 4401 && !retried401) {
472
+ retried401 = true;
473
+ void connect();
474
+ } else if (code === 4404) {
475
+ const wait = RESTART_RETRY_MS[restartRetries];
476
+ if (wait === void 0) show("empty");
477
+ else {
478
+ restartRetries++;
479
+ show("connecting");
480
+ retryTimer = setTimeout(() => void connect(), wait);
481
+ }
482
+ } else if (code === 4409 || code === 4401) show("offline");
483
+ else if (code === 1009) show("error");
484
+ else if (code === 1012 || code === 1013) void connect();
485
+ else {
486
+ attempts++;
487
+ if (attempts > 6) {
488
+ show("offline");
489
+ return;
490
+ }
491
+ show("connecting");
492
+ retryTimer = setTimeout(() => void connect(), Math.min(15e3, 1e3 * 2 ** (attempts - 1)));
493
+ }
494
+ }
495
+ function takeover() {
496
+ send({ t: "takeover" });
497
+ bridge(true);
498
+ view.focus();
499
+ renderChrome();
500
+ }
501
+ function handback() {
502
+ send({ t: "handback" });
503
+ bridge(false);
504
+ renderChrome();
505
+ if (pendingHandoff !== null) void answerHandoff(true);
506
+ }
507
+ function normalizeUrl(raw) {
508
+ const v = raw.trim();
509
+ return /^[a-z][a-z0-9+.-]*:/i.test(v) ? v : `https://${v}`;
510
+ }
511
+ async function allowHost() {
512
+ const host = blockedHost;
513
+ const target = blockedUrl;
514
+ if (host === "") return;
515
+ try {
516
+ const res = await doFetch("network-hosts", {
517
+ method: "POST",
518
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
519
+ body: JSON.stringify({ hosts: [host] }),
520
+ credentials: "omit"
521
+ });
522
+ if (!res.ok) {
523
+ notice("allowFailed", await refusalOf(res));
524
+ return;
525
+ }
526
+ } catch {
527
+ notice("allowFailed", "");
528
+ return;
529
+ }
530
+ blockedHost = "";
531
+ blockedUrl = "";
532
+ renderChrome();
533
+ if (target === "") {
534
+ send({ t: "nav", action: "reload" });
535
+ return;
536
+ }
537
+ pendingNav = { url: target, sentOn: sock, until: Date.now() + PENDING_NAV_MS };
538
+ send({ t: "nav", url: target });
539
+ }
540
+ async function answerHandoff(done) {
541
+ const h = pendingHandoff;
542
+ if (h === null) return;
543
+ try {
544
+ const res = await doFetch("handoff-answer", {
545
+ method: "POST",
546
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
547
+ body: JSON.stringify({ callId: h.callId, done }),
548
+ credentials: "omit"
549
+ });
550
+ if (res.status === 404) {
551
+ if (pendingHandoff?.callId === h.callId) {
552
+ pendingHandoff = null;
553
+ $("handoff").hidden = true;
554
+ }
555
+ return;
556
+ }
557
+ if (!res.ok) {
558
+ notice("answerFailed", await refusalOf(res));
559
+ return;
560
+ }
561
+ } catch {
562
+ notice("answerFailed", "");
563
+ return;
564
+ }
565
+ }
566
+ function onPointer(kind, e) {
567
+ if (compact()) return;
568
+ if (kind === "move") {
569
+ if (!interactive() || e.timeStamp - lastMove < MOVE_INTERVAL_MS) return;
570
+ lastMove = e.timeStamp;
571
+ }
572
+ const r = view.getBoundingClientRect();
573
+ const p = mapPoint(e.clientX - r.left, e.clientY - r.top, {
574
+ x: 0,
575
+ y: 0,
576
+ w: r.width,
577
+ h: r.height
578
+ });
579
+ send({
580
+ t: "mouse",
581
+ kind,
582
+ ...p,
583
+ ...kind === "move" ? {} : { button: e.button === 2 ? "right" : "left" }
584
+ });
585
+ }
586
+ $("takeover").addEventListener("click", takeover);
587
+ $("handback").addEventListener("click", handback);
588
+ $("handoff-done").addEventListener("click", () => void answerHandoff(true));
589
+ $("handoff-cancel").addEventListener("click", () => void answerHandoff(false));
590
+ $("allow").addEventListener("click", () => void allowHost());
591
+ $("reconnect").addEventListener("click", () => {
592
+ retried401 = false;
593
+ attempts = 0;
594
+ void connect();
595
+ });
596
+ $("back").addEventListener("click", () => send({ t: "nav", action: "back" }));
597
+ $("forward").addEventListener("click", () => send({ t: "nav", action: "forward" }));
598
+ $("reload").addEventListener("click", () => send({ t: "nav", action: "reload" }));
599
+ url.addEventListener("keydown", (e) => {
600
+ if (e.key !== "Enter" || compact() || url.value.trim() === "") return;
601
+ send({ t: "nav", url: normalizeUrl(url.value) });
602
+ view.focus();
603
+ });
604
+ view.addEventListener("mousedown", (e) => onPointer("down", e));
605
+ view.addEventListener("mouseup", (e) => onPointer("up", e));
606
+ view.addEventListener("mousemove", (e) => onPointer("move", e));
607
+ view.addEventListener("contextmenu", (e) => e.preventDefault());
608
+ view.addEventListener(
609
+ "wheel",
610
+ (e) => {
611
+ if (compact()) return;
612
+ e.preventDefault();
613
+ const r = view.getBoundingClientRect();
614
+ const p = mapPoint(e.clientX - r.left, e.clientY - r.top, {
615
+ x: 0,
616
+ y: 0,
617
+ w: r.width,
618
+ h: r.height
619
+ });
620
+ send({ t: "mouse", kind: "wheel", ...p, dx: e.deltaX, dy: e.deltaY });
621
+ },
622
+ { passive: false }
623
+ );
624
+ view.addEventListener("keydown", (e) => {
625
+ if (!interactive() || e.key === "Escape" || e.isComposing) return;
626
+ e.preventDefault();
627
+ send({ t: "key", kind: "down", key: e.key, code: e.code });
628
+ });
629
+ view.addEventListener("keyup", (e) => {
630
+ if (!interactive() || e.key === "Escape" || e.isComposing) return;
631
+ e.preventDefault();
632
+ send({ t: "key", kind: "up", key: e.key, code: e.code });
633
+ });
634
+ view.addEventListener("compositionend", (e) => {
635
+ if (interactive() && e.data !== "") send({ t: "key", kind: "char", key: e.data, text: e.data });
636
+ });
637
+ doc.addEventListener("keydown", (e) => {
638
+ if (e.key === "Escape" && interactive()) handback();
639
+ });
640
+ win.addEventListener("resize", () => {
641
+ if (sock === null || mode !== "live") return;
642
+ const { w, h } = layout();
643
+ if (sentSize !== `${w}x${h}`) sizeMessage("resize");
644
+ renderChrome();
645
+ renderTabs();
646
+ draw();
647
+ });
648
+ doc.addEventListener("visibilitychange", () => {
649
+ if (doc.visibilityState === "hidden") {
650
+ if (hiddenTimer === void 0) {
651
+ hiddenTimer = setTimeout(() => {
652
+ hiddenTimer = void 0;
653
+ if (started) {
654
+ pausedForHidden = true;
655
+ stop();
656
+ }
657
+ }, HIDDEN_CLOSE_MS);
658
+ }
659
+ } else {
660
+ if (hiddenTimer !== void 0) clearTimeout(hiddenTimer);
661
+ hiddenTimer = void 0;
662
+ if (pausedForHidden) {
663
+ pausedForHidden = false;
664
+ void connect();
665
+ }
666
+ }
667
+ });
668
+ function applyTheme(tokens, theme) {
669
+ const root = doc.documentElement;
670
+ if (theme === "dark" || theme === "light") root.setAttribute("data-theme", theme);
671
+ if (tokens === null || typeof tokens !== "object") return;
672
+ for (const [name, value] of Object.entries(tokens)) {
673
+ if (name.startsWith("--cb-") && typeof value === "string" && value.length <= 200) {
674
+ root.style.setProperty(name, value);
675
+ }
676
+ }
677
+ }
678
+ setLabels();
679
+ renderChrome();
680
+ win.addEventListener("message", (ev) => {
681
+ if (ev.source !== win.parent) return;
682
+ const m = ev.data;
683
+ if (m === null || typeof m !== "object" || m.protocol !== PROTOCOL) return;
684
+ if (m.type === "init") {
685
+ if (typeof m.token === "string") token = m.token;
686
+ locale = m.locale === "zh" ? "zh" : "en";
687
+ applyTheme(m.tokens, m.theme);
688
+ setLabels();
689
+ renderChrome();
690
+ if (!started) {
691
+ started = true;
692
+ void connect();
693
+ }
694
+ } else if (m.type === "token" && typeof m.token === "string") {
695
+ token = m.token;
696
+ } else if (m.type === "theme") {
697
+ applyTheme(m.tokens, m.theme);
698
+ }
699
+ });
700
+ }
701
+
702
+ // ui-src/panel/entry.ts
703
+ mountPanel({ window });
704
+ })();