dsh-browser-cdp 0.0.1 → 0.17.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 (53) hide show
  1. package/LICENSE +27 -0
  2. package/README.md +279 -9
  3. package/THIRD_PARTY_NOTICES.md +62 -0
  4. package/bin/cdp-cast-worker.mjs +6960 -0
  5. package/bin/cdp-chrome-wrapper.sh +53 -0
  6. package/bin/cdp-render-worker.mjs +610 -0
  7. package/bin/record-normalize.d.mts +32 -0
  8. package/bin/record-normalize.mjs +156 -0
  9. package/cordis.patch.yml +17 -0
  10. package/dsh-plugin.json +148 -0
  11. package/lib/client.js +3235 -0
  12. package/lib/index.js +8865 -0
  13. package/lib/launcher-CQyI8-By.js +3 -0
  14. package/lib/launcher-DBaxfIsF.js +269 -0
  15. package/package.json +90 -14
  16. package/runtime/PATCHES.md +30 -0
  17. package/runtime/ego-browser/dist/out/index.js +7206 -0
  18. package/runtime/ego-browser/screenshot-clip.d.mts +22 -0
  19. package/runtime/ego-browser/screenshot-clip.mjs +45 -0
  20. package/runtime/ego-linux/bin/ego-browser.mjs +399 -0
  21. package/runtime/ego-linux/src/agent-identity.mjs +65 -0
  22. package/runtime/ego-linux/src/chrome.mjs +867 -0
  23. package/runtime/ego-linux/src/cursor.mjs +1292 -0
  24. package/runtime/ego-linux/src/desktop.mjs +73 -0
  25. package/runtime/ego-linux/src/paths.mjs +35 -0
  26. package/runtime/ego-linux/src/session.mjs +37 -0
  27. package/runtime/ego-linux/src/shim.mjs +145 -0
  28. package/runtime/ego-linux/src/snapshot.mjs +424 -0
  29. package/runtime/ego-linux/src/spaces-server.mjs +355 -0
  30. package/runtime/ego-linux/src/spaces-ui.mjs +456 -0
  31. package/runtime/ego-linux/src/tabs.mjs +109 -0
  32. package/runtime/ego-linux/src/task-spaces.mjs +671 -0
  33. package/runtime/ego-linux/src/transport.mjs +321 -0
  34. package/runtime/ego-linux/src/window-fit.mjs +107 -0
  35. package/runtime/skills/ego-browser/SKILL.md +209 -0
  36. package/runtime/skills/ego-browser/agents/openai.yaml +7 -0
  37. package/runtime/skills/ego-browser/assets/composer-icon.png +0 -0
  38. package/runtime/skills/ego-browser/assets/logo.png +0 -0
  39. package/runtime/skills/ego-browser/learnings/google/browser-tools/autocomplete.js +11 -0
  40. package/runtime/skills/ego-browser/learnings/google/manifest.json +40 -0
  41. package/runtime/skills/ego-browser/learnings/google/notes/overview.md +23 -0
  42. package/runtime/skills/ego-browser/learnings/google/tools/search-extract.js +35 -0
  43. package/runtime/skills/ego-browser/learnings/x-com/browser-tools/extract-post.js +9 -0
  44. package/runtime/skills/ego-browser/learnings/x-com/manifest.json +51 -0
  45. package/runtime/skills/ego-browser/learnings/x-com/notes/overview.md +18 -0
  46. package/runtime/skills/ego-browser/learnings/x-com/notes/timeline.md +19 -0
  47. package/runtime/skills/ego-browser/learnings/x-com/tools/search-users.js +33 -0
  48. package/runtime/skills/ego-browser/learnings/x-com/tools/timeline.js +32 -0
  49. package/runtime/skills/ego-browser/references/install.md +131 -0
  50. package/runtime/skills/ego-browser/references/task-spaces.md +122 -0
  51. package/runtime/skills/ego-browser/references/video.md +17 -0
  52. package/runtime/skills/ego-browser/scripts/install.sh +309 -0
  53. package/index.js +0 -11
package/lib/client.js ADDED
@@ -0,0 +1,3235 @@
1
+ window.__ModuleLoader__.load({ id: "dsh-browser-cdp", factory: (require) => {
2
+ var module = { exports: {} }; var exports = module.exports;
3
+
4
+ //#region src/client/index.ts
5
+ var React = require("react");
6
+ var createSnapshotStore = require("@deepseek-ai/dsh-client-store").createSnapshotStore;
7
+ var useSyncExternalStore = React.useSyncExternalStore;
8
+ var useRef = React.useRef;
9
+ function bindSnapshotSelector(source) {
10
+ var subscribe = function(fn) {
11
+ return source.subscribe(fn);
12
+ };
13
+ var getSnapshot = function() {
14
+ return source.getSnapshot();
15
+ };
16
+ return function useSelector(sel, eq) {
17
+ var snapshot = useSyncExternalStore(subscribe, getSnapshot);
18
+ var prevSnapshotRef = useRef();
19
+ var prevSelectedRef = useRef();
20
+ if (prevSnapshotRef.current !== snapshot) {
21
+ prevSnapshotRef.current = snapshot;
22
+ prevSelectedRef.current = sel(snapshot);
23
+ }
24
+ return prevSelectedRef.current;
25
+ };
26
+ }
27
+ const inject = [
28
+ "slots",
29
+ "locale",
30
+ "connection"
31
+ ];
32
+ var _egoLocale = (function() {
33
+ try {
34
+ return (navigator.language || "").startsWith("zh") ? "zh" : "en";
35
+ } catch {
36
+ return "en";
37
+ }
38
+ })();
39
+ var watchEn = {
40
+ title: "Agent Browser",
41
+ titleLive: "Agent Browser · Live",
42
+ liveView: "Live view",
43
+ pinned: "Pinned",
44
+ realtime: "Live",
45
+ noScreenshot: "(no screenshot — about:blank or browser not rendering)",
46
+ noActivePages: "No active browser pages",
47
+ noActiveHint: "Pages will appear here as the agent browses with bcdp_*",
48
+ openExternal: "Open real page",
49
+ raiseWindow: "Pop out window",
50
+ raiseWindowHint: "Raise the agent browser as a real window (a headless instance is replaced by a visible one on the same profile)",
51
+ pickMode: "Pick element",
52
+ pickModeHint: "Click an element in the live page to quote it into the conversation",
53
+ picking: "Picking… click an element in the page",
54
+ picked: "Element captured",
55
+ pickFailed: "Pick failed",
56
+ pickQuoted: "✓ Quoted to composer",
57
+ pickDeliverFailed: "Delivery failed",
58
+ noUrl: "No URL to open",
59
+ closeTab: "Close tab",
60
+ newTab: "(new tab)",
61
+ history: "Browsing history",
62
+ historyHide: "Hide history",
63
+ historyShow: "Show history",
64
+ noHistory: "No browsing history",
65
+ current: "current",
66
+ refresh: "Refresh",
67
+ backToLive: "← Back to live",
68
+ dragHint: "Drag to move panel",
69
+ loginTitle: "Log in via the CDP browser bridge window on your desktop",
70
+ loginBtn: "Logged in, save",
71
+ loginSaving: "Saving…",
72
+ loginSaved: "Saved {n} sessions",
73
+ loginNotConnected: "Browser not connected",
74
+ loginFailed: "Save failed",
75
+ loginDismiss: "Dismiss",
76
+ captchaTitle: "⚠️ CAPTCHA detected",
77
+ captchaHint: "Complete verification in the CDP browser bridge window; the agent will continue.",
78
+ captchaDismiss: "Dismiss",
79
+ hintReset: "Reset · scroll to pan · Ctrl+scroll to zoom · double-click to reset",
80
+ hintPan: "Ctrl+scroll to zoom · Ctrl+drag to pan · double-click to reset",
81
+ hintScroll: "Ctrl+drag to pan · scroll to pan",
82
+ hintNotCaptured: "Not captured · operation not delivered · click again to recover",
83
+ failed: "failed",
84
+ stale: "⚠ Not captured",
85
+ captured: "Captured",
86
+ fabTitle: "Agent Browser live view",
87
+ settingsTitle: "Show settings",
88
+ settingsHide: "Hide settings"
89
+ };
90
+ var watchDict = {
91
+ en: watchEn,
92
+ zh: {
93
+ title: "CDP 浏览器",
94
+ titleLive: "CDP 浏览器 · 实时",
95
+ liveView: "只读观察窗",
96
+ pinned: "已固定查看",
97
+ realtime: "正在实时浏览",
98
+ noScreenshot: "(暂无截图 — about:blank 或浏览器未渲染)",
99
+ noActivePages: "暂无活跃浏览器页",
100
+ noActiveHint: "当 agent 开始用 bcdp_* 操作网页时,这里会实时显示",
101
+ openExternal: "⧉ 打开真实页",
102
+ raiseWindow: "弹出窗口",
103
+ raiseWindowHint: "把 agent 浏览器弹出为真实窗口(无头实例会被同 Profile 的有头实例替换,标签页保留)",
104
+ pickMode: "选择元素",
105
+ pickModeHint: "在实时页面里点选一个元素,引用到对话",
106
+ picking: "点选中…请点击页面里的元素",
107
+ picked: "已捕获元素",
108
+ pickFailed: "点选失败",
109
+ pickQuoted: "✓ 已引用到输入框",
110
+ pickDeliverFailed: "投递失败",
111
+ noUrl: "无可打开的地址",
112
+ closeTab: "关闭标签",
113
+ newTab: "(新标签页)",
114
+ history: "历史浏览轨迹",
115
+ historyHide: "收起历史轨迹",
116
+ historyShow: "历史浏览轨迹",
117
+ noHistory: "暂无浏览记录",
118
+ current: "当前",
119
+ refresh: "刷新",
120
+ backToLive: "← 返回实时",
121
+ dragHint: "拖动移动面板",
122
+ loginTitle: "需要账号登录时,请到桌面上那个 「CDP 浏览器代理」 Chrome 窗口完成登录。",
123
+ loginBtn: "已登录,保存",
124
+ loginSaving: "保存中…",
125
+ loginSaved: "已保存 {n} 条会话",
126
+ loginNotConnected: "未连接浏览器",
127
+ loginFailed: "保存失败",
128
+ loginDismiss: "关闭提示",
129
+ captchaTitle: "⚠️ 检测到人机验证",
130
+ captchaHint: "请在桌面那个 「CDP 浏览器代理」 浏览器窗口手动完成验证,agent 会继续。",
131
+ captchaDismiss: "关闭提示",
132
+ hintReset: "已复位 · 滚轮滚动页面 · Ctrl+滚轮缩放 · 双击复位",
133
+ hintPan: "Ctrl+滚轮缩放 · Ctrl+拖动平移 · 双击复位",
134
+ hintScroll: "Ctrl+拖动平移 · 滚轮滚动页面",
135
+ hintNotCaptured: "画面未接管 · 本次操作未送达 · 再点一次即可恢复",
136
+ failed: "失败",
137
+ stale: "⚠ 未接管",
138
+ captured: "已接管",
139
+ fabTitle: "CDP 浏览器实时视图",
140
+ settingsTitle: "展开设置",
141
+ settingsHide: "收起设置"
142
+ }
143
+ };
144
+ function wt(key, params = void 0) {
145
+ var text = (watchDict[_egoLocale] || watchEn)[key] || watchEn[key] || key;
146
+ if (params) for (var k in params) text = text.replace(new RegExp("{" + k + "}", "g"), String(params[k]));
147
+ return text;
148
+ }
149
+ const SPACES_ROUTE = "/api/bcdp/spaces";
150
+ const EGO_CLOSE_ROUTE = "/api/bcdp/close";
151
+ const WATCH_START_ROUTE = "/api/bcdp/watch/start";
152
+ const WATCH_SWITCH_ROUTE = "/api/bcdp/watch/switch";
153
+ const WATCH_STOP_ROUTE = "/api/bcdp/watch/stop";
154
+ const WATCH_STATUS_ROUTE = "/api/bcdp/watch/status";
155
+ const VIDEO_ROUTE = "/api/bcdp/video";
156
+ function postJson(path, body) {
157
+ return fetch(path, {
158
+ method: "POST",
159
+ headers: { "content-type": "application/json" },
160
+ body: JSON.stringify(body || {})
161
+ }).then(function(res) {
162
+ return res.json().catch(function() {
163
+ return {};
164
+ });
165
+ });
166
+ }
167
+ function createKeyboardProxy(send) {
168
+ var input = document.createElement("textarea");
169
+ input.className = "dsh-ego-keyboard-proxy";
170
+ input.tabIndex = -1;
171
+ input.setAttribute("autocomplete", "off");
172
+ input.setAttribute("autocapitalize", "off");
173
+ input.setAttribute("spellcheck", "false");
174
+ input.style.cssText = "position:fixed;z-index:2147483647;width:1px;height:1px;opacity:.01;pointer-events:none;resize:none;padding:0;border:0;left:0;top:0;";
175
+ document.body.appendChild(input);
176
+ var composing = false;
177
+ var armed = false;
178
+ var activeTargetId = null;
179
+ var pressed = /* @__PURE__ */ new Map();
180
+ var lastCompositionText = "", lastCompositionAt = 0, lastPasteText = "", lastPasteAt = 0;
181
+ var blurCount = 0, lastBlurAt = 0;
182
+ var modifiers = function(e) {
183
+ return (e.altKey ? 1 : 0) | (e.ctrlKey ? 2 : 0) | (e.metaKey ? 4 : 0) | (e.shiftKey ? 8 : 0);
184
+ };
185
+ var keyId = function(e) {
186
+ return e.code || e.key;
187
+ };
188
+ var keyPayload = function(e) {
189
+ return {
190
+ key: e.key,
191
+ code: e.code || "",
192
+ modifiers: modifiers(e),
193
+ autoRepeat: !!e.repeat,
194
+ windowsVirtualKeyCode: Number(e.keyCode || e.which || 0)
195
+ };
196
+ };
197
+ var isDshInput = function(target) {
198
+ if (!target || target === input) return false;
199
+ var tag = target.tagName;
200
+ if (tag === "INPUT" || tag === "TEXTAREA") return true;
201
+ if (target.isContentEditable) return true;
202
+ return false;
203
+ };
204
+ var releaseAllKeys = function() {
205
+ for (const record of pressed.values()) send(record.targetId, "keyUp", Object.assign({}, record.payload, { autoRepeat: false }));
206
+ pressed.clear();
207
+ };
208
+ input.addEventListener("compositionstart", function(e) {
209
+ composing = true;
210
+ e.stopPropagation();
211
+ });
212
+ input.addEventListener("compositionend", function(e) {
213
+ composing = false;
214
+ e.stopPropagation();
215
+ if (e.data && activeTargetId) {
216
+ lastCompositionText = e.data;
217
+ lastCompositionAt = Date.now();
218
+ send(activeTargetId, "insertText", { text: e.data });
219
+ }
220
+ window.setTimeout(function() {
221
+ input.value = "";
222
+ }, 0);
223
+ });
224
+ input.addEventListener("beforeinput", function(e) {
225
+ e.stopPropagation();
226
+ if (composing || /Composition/i.test(e.inputType || "")) return;
227
+ if (e.data && e.data === lastCompositionText && Date.now() - lastCompositionAt < 100) {
228
+ e.preventDefault();
229
+ return;
230
+ }
231
+ if (e.data && e.data === lastPasteText && Date.now() - lastPasteAt < 100) {
232
+ e.preventDefault();
233
+ return;
234
+ }
235
+ if (e.data && activeTargetId) {
236
+ e.preventDefault();
237
+ send(activeTargetId, "insertText", { text: e.data });
238
+ input.value = "";
239
+ }
240
+ });
241
+ input.addEventListener("paste", function(e) {
242
+ var text = e.clipboardData && e.clipboardData.getData("text/plain");
243
+ if (!text) return;
244
+ e.preventDefault();
245
+ e.stopPropagation();
246
+ lastPasteText = text;
247
+ lastPasteAt = Date.now();
248
+ if (activeTargetId) send(activeTargetId, "insertText", { text });
249
+ input.value = "";
250
+ });
251
+ input.addEventListener("keydown", function(e) {
252
+ e.stopPropagation();
253
+ if (composing || e.key === "Process" || e.key === "Dead") return;
254
+ if (e.getModifierState && e.getModifierState("AltGraph") && e.key.length === 1) return;
255
+ var isShortcut = e.ctrlKey || e.metaKey || e.altKey;
256
+ var isControl = e.key.length > 1;
257
+ if (!isShortcut && !isControl) return;
258
+ if ((e.ctrlKey || e.metaKey) && String(e.key).toLowerCase() === "v") return;
259
+ if (!activeTargetId) return;
260
+ e.preventDefault();
261
+ var payload = keyPayload(e);
262
+ pressed.set(keyId(e), {
263
+ targetId: activeTargetId,
264
+ payload
265
+ });
266
+ send(activeTargetId, "keyDown", payload);
267
+ });
268
+ input.addEventListener("keyup", function(e) {
269
+ e.stopPropagation();
270
+ var id = keyId(e);
271
+ var record = pressed.get(id);
272
+ if (!record) return;
273
+ e.preventDefault();
274
+ pressed.delete(id);
275
+ send(record.targetId, "keyUp", keyPayload(e));
276
+ });
277
+ input.addEventListener("blur", function() {
278
+ if (!armed || !activeTargetId) return;
279
+ var now = Date.now();
280
+ if (now - lastBlurAt < 1e3) {
281
+ blurCount++;
282
+ if (blurCount > 3) return;
283
+ } else blurCount = 0;
284
+ lastBlurAt = now;
285
+ window.setTimeout(function() {
286
+ if (armed && activeTargetId) try {
287
+ input.focus({ preventScroll: true });
288
+ } catch (err) {
289
+ input.focus();
290
+ }
291
+ }, 0);
292
+ });
293
+ var onDocKeyDown = function(e) {
294
+ if (!armed || !activeTargetId) return;
295
+ if (e.target === input) return;
296
+ if (composing || e.key === "Process" || e.key === "Dead") return;
297
+ if (e.getModifierState && e.getModifierState("AltGraph") && e.key.length === 1) return;
298
+ if (isDshInput(e.target) && document.activeElement === e.target) return;
299
+ var isShortcut = e.ctrlKey || e.metaKey || e.altKey;
300
+ var isControl = e.key.length > 1;
301
+ if (!isShortcut && !isControl) {
302
+ e.preventDefault();
303
+ e.stopPropagation();
304
+ send(activeTargetId, "insertText", { text: e.key });
305
+ return;
306
+ }
307
+ if ((e.ctrlKey || e.metaKey) && String(e.key).toLowerCase() === "v") return;
308
+ e.preventDefault();
309
+ e.stopPropagation();
310
+ var payload = keyPayload(e);
311
+ pressed.set(keyId(e), {
312
+ targetId: activeTargetId,
313
+ payload
314
+ });
315
+ send(activeTargetId, "keyDown", payload);
316
+ };
317
+ var onDocKeyUp = function(e) {
318
+ if (!armed || !activeTargetId) return;
319
+ if (e.target === input) return;
320
+ var id = keyId(e);
321
+ var record = pressed.get(id);
322
+ if (!record) return;
323
+ e.preventDefault();
324
+ e.stopPropagation();
325
+ pressed.delete(id);
326
+ send(record.targetId, "keyUp", keyPayload(e));
327
+ };
328
+ var onDocPointerDown = function(e) {
329
+ if (armed && isDshInput(e.target) && e.target !== input) {
330
+ armed = false;
331
+ releaseAllKeys();
332
+ }
333
+ };
334
+ document.addEventListener("keydown", onDocKeyDown, true);
335
+ document.addEventListener("keyup", onDocKeyUp, true);
336
+ document.addEventListener("pointerdown", onDocPointerDown, true);
337
+ return {
338
+ focusAt: function(e, targetId) {
339
+ if (activeTargetId && targetId !== activeTargetId) releaseAllKeys();
340
+ activeTargetId = targetId;
341
+ armed = true;
342
+ blurCount = 0;
343
+ input.style.left = Math.max(0, e.clientX) + "px";
344
+ input.style.top = Math.max(0, e.clientY) + "px";
345
+ try {
346
+ input.focus({ preventScroll: true });
347
+ } catch (err) {
348
+ input.focus();
349
+ }
350
+ },
351
+ dispose: function() {
352
+ armed = false;
353
+ document.removeEventListener("keydown", onDocKeyDown, true);
354
+ document.removeEventListener("keyup", onDocKeyUp, true);
355
+ document.removeEventListener("pointerdown", onDocPointerDown, true);
356
+ releaseAllKeys();
357
+ input.remove();
358
+ }
359
+ };
360
+ }
361
+ function createMsePlayer(video, generation, mime, onFailure) {
362
+ if (!window.MediaSource || !window.MediaSource.isTypeSupported(mime)) {
363
+ onFailure("当前浏览器不支持此 H.264 流");
364
+ return function() {};
365
+ }
366
+ var mediaSource = new MediaSource();
367
+ var objectUrl = URL.createObjectURL(mediaSource);
368
+ var abort = new AbortController();
369
+ var sourceBuffer = null, queue = [], queuedBytes = 0, disposed = false, reader = null, reading = false;
370
+ var MAX_QUEUED_VIDEO_BYTES = 4 * 1024 * 1024;
371
+ video.src = objectUrl;
372
+ video.muted = true;
373
+ video.autoplay = true;
374
+ video.playsInline = true;
375
+ function appendNext() {
376
+ if (disposed || !sourceBuffer || sourceBuffer.updating || queue.length === 0) return;
377
+ var chunk = queue.shift();
378
+ queuedBytes -= chunk.byteLength;
379
+ try {
380
+ sourceBuffer.appendBuffer(chunk);
381
+ } catch (error) {
382
+ onFailure(error.message);
383
+ }
384
+ }
385
+ function pump() {
386
+ if (disposed || reading || !reader || queuedBytes >= MAX_QUEUED_VIDEO_BYTES) return;
387
+ reading = true;
388
+ reader.read().then(function(part) {
389
+ reading = false;
390
+ if (disposed) return;
391
+ if (part.done) {
392
+ onFailure("视频流已断开");
393
+ return;
394
+ }
395
+ queue.push(part.value);
396
+ queuedBytes += part.value.byteLength;
397
+ appendNext();
398
+ pump();
399
+ }).catch(function(error) {
400
+ reading = false;
401
+ if (!disposed && error.name !== "AbortError") onFailure(error.message);
402
+ });
403
+ }
404
+ mediaSource.addEventListener("sourceopen", function() {
405
+ if (disposed) return;
406
+ try {
407
+ sourceBuffer = mediaSource.addSourceBuffer(mime);
408
+ } catch (error) {
409
+ onFailure(error.message);
410
+ return;
411
+ }
412
+ sourceBuffer.mode = "segments";
413
+ sourceBuffer.addEventListener("updateend", function() {
414
+ if (video.buffered.length) {
415
+ var end = video.buffered.end(video.buffered.length - 1);
416
+ if (end - video.currentTime > .8) video.currentTime = Math.max(0, end - .15);
417
+ if (!sourceBuffer.updating && video.buffered.start(0) < end - 3) try {
418
+ sourceBuffer.remove(video.buffered.start(0), end - 2);
419
+ } catch (e) {}
420
+ }
421
+ appendNext();
422
+ pump();
423
+ });
424
+ fetch(VIDEO_ROUTE + "?generation=" + encodeURIComponent(generation), { signal: abort.signal }).then(function(res) {
425
+ if (!res.ok || !res.body) throw new Error("视频流连接失败 (" + res.status + ")");
426
+ reader = res.body.getReader();
427
+ pump();
428
+ }).catch(function(error) {
429
+ if (!disposed && error.name !== "AbortError") onFailure(error.message);
430
+ });
431
+ });
432
+ return function() {
433
+ disposed = true;
434
+ abort.abort();
435
+ queue = [];
436
+ queuedBytes = 0;
437
+ try {
438
+ video.pause();
439
+ video.removeAttribute("src");
440
+ video.load();
441
+ } catch (e) {}
442
+ try {
443
+ URL.revokeObjectURL(objectUrl);
444
+ } catch (e) {}
445
+ };
446
+ }
447
+ const OPEN_KEY = "dsh.ego.watch.open";
448
+ const ACTIVE_WINDOW_MS = 3e3;
449
+ const PANEL_CSS = `
450
+ /* ---- deep Apple / macOS dark-glass chrome ---- */
451
+ :root { --ego-ios-gap: 6px; }
452
+
453
+ #dsh-ego-fab {
454
+ position: fixed; left: 0; top: 0; z-index: 9999;
455
+ width: 48px; height: 48px; border-radius: 50%;
456
+ border: 1px solid rgba(255,255,255,.14);
457
+ background: rgba(30,30,32,.72);
458
+ -webkit-backdrop-filter: blur(22px) saturate(180%);
459
+ backdrop-filter: blur(22px) saturate(180%);
460
+ color: #f5f5f7; cursor: grab;
461
+ touch-action: none; user-select: none; -webkit-user-select: none;
462
+ box-shadow: 0 10px 30px rgba(0,0,0,.45);
463
+ display: flex; align-items: center; justify-content: center;
464
+ }
465
+ #dsh-ego-fab.dsh-ego-dragging { cursor: grabbing; opacity:.85; }
466
+ #dsh-ego-fab:hover { transform: scale(1.09); }
467
+ #dsh-ego-fab[hidden] { display: none; }
468
+ #dsh-ego-fab .dsh-ego-dot {
469
+ position: absolute; top: 1px; right: 1px; width: 11px; height: 11px;
470
+ border-radius: 50%; background: #86868b;
471
+ border: 2px solid rgba(30,30,32,.9);
472
+ }
473
+ #dsh-ego-fab svg { width: 22px; height: 22px; }
474
+ /* FAB status dot: steady green while the agent is driving the browser
475
+ (busy), breathing green when idle (browser open, no recent action). */
476
+ #dsh-ego-fab.dsh-ego-live:not(.dsh-ego-busy) .dsh-ego-dot {
477
+ background: #30d158; box-shadow: 0 0 8px #30d158aa;
478
+ animation: dsh-ego-breathe 2.4s ease-in-out infinite;
479
+ }
480
+ #dsh-ego-fab.dsh-ego-busy .dsh-ego-dot {
481
+ background: #30d158; box-shadow: 0 0 9px #30d158cc; animation: none;
482
+ }
483
+ @keyframes dsh-ego-breathe {
484
+ 0%, 100% { box-shadow: 0 0 2px #30d15822; opacity: .5; }
485
+ 50% { box-shadow: 0 0 11px #30d158ee; opacity: 1; }
486
+ }
487
+
488
+ #dsh-ego-panel {
489
+ position: fixed; left: 0; top: 0; z-index: 9998;
490
+ width: 408px; max-height: 78vh;
491
+ display: flex; flex-direction: column; overflow: hidden;
492
+ border: 1px solid rgba(255,255,255,.12);
493
+ border-radius: 16px;
494
+ background: rgba(28,28,30,.74);
495
+ -webkit-backdrop-filter: blur(26px) saturate(180%);
496
+ backdrop-filter: blur(26px) saturate(180%);
497
+ color: #f5f5f7;
498
+ box-shadow: 0 14px 44px rgba(0,0,0,.55), inset 0 1px 0 rgba(255,255,255,.08);
499
+ /* Pop-out animation: the panel springs up-left out of the ball's spot.
500
+ transform-origin sits near its bottom-right (closest to the FAB). */
501
+ opacity: 0; pointer-events: none;
502
+ transform-origin: 82% 100%;
503
+ transform: translateY(12px) scale(.88);
504
+ transition: opacity .26s cubic-bezier(.16,.8,.3,1.05),
505
+ transform .26s cubic-bezier(.16,.8,.3,1.15),
506
+ visibility .26s;
507
+ will-change: transform, opacity;
508
+ }
509
+ #dsh-ego-panel.dsh-ego-panel-open { opacity: 1; pointer-events: auto; transform: none; }
510
+ #dsh-ego-panel[hidden] { display: none; }
511
+ #dsh-ego-panel.open-drawer { width: 640px; }
512
+
513
+ /* FAB press / open feedback */
514
+ #dsh-ego-fab:active { transform: scale(.95); }
515
+ #dsh-ego-fab.dsh-ego-on { transform: scale(1.12); box-shadow: 0 0 0 6px rgba(10,132,255,.22), 0 10px 30px rgba(0,0,0,.5); }
516
+ #dsh-ego-fab.dsh-ego-on:hover { transform: scale(1.18); }
517
+
518
+ /* Drag handles for the panel: its header doubles as a title-bar grip. */
519
+ #dsh-ego-head { cursor: grab; }
520
+ #dsh-ego-head.dsh-ego-grabbing { cursor: grabbing; }
521
+ #dsh-ego-head .dsh-ego-grip {
522
+ flex: none; width: 22px; height: 22px; border-radius: 6px;
523
+ display: inline-flex; align-items: center; justify-content: center;
524
+ color:#86868b; opacity:.8;
525
+ }
526
+ #dsh-ego-head .dsh-ego-grip svg { width: 13px; height: 13px; }
527
+
528
+ #dsh-ego-head { display:flex; align-items:center; gap:4px; padding:10px 14px;
529
+ border-bottom:1px solid rgba(255,255,255,.08); }
530
+ #dsh-ego-title { flex:1; font-size:13px; font-weight:600; letter-spacing:.2px;
531
+ white-space:nowrap; overflow:hidden; text-overflow:ellipsis; display:flex; align-items:center; gap:6px; }
532
+ #dsh-ego-title svg { width:16px; height:16px; color:#0a84ff; flex-shrink:0; }
533
+ #dsh-ego-iconbtn {
534
+ background: transparent; border:none; color: #aeaeb2; cursor: pointer;
535
+ width: 28px; height: 28px; border-radius: 8px; padding: 0;
536
+ display:flex; align-items:center; justify-content:center;
537
+ transition: background .15s ease, color .15s ease;
538
+ }
539
+ #dsh-ego-iconbtn svg { width: 15px; height: 15px; }
540
+ #dsh-ego-iconbtn:hover { background: rgba(255,255,255,.12); color: #f5f5f7; }
541
+ #dsh-ego-iconbtn.off { opacity:.5; }
542
+ #dsh-ego-iconbtn.spinning svg { animation: dsh-ego-spin .7s linear infinite; }
543
+ @keyframes dsh-ego-spin { to { transform: rotate(360deg); } }
544
+
545
+ #dsh-ego-body { flex:1; overflow-y:auto; padding:12px 14px; min-height:60px; }
546
+ .dsh-ego-empty { padding:20px 12px; text-align:center; color:#86868b; font-size:12.5px; line-height:1.7; }
547
+ .dsh-ego-off { padding:6px 14px 10px; text-align:center; font-size:11px; color:#6e6e73; }
548
+ .dsh-ego-off svg { width:11px; height:11px; vertical-align:-1px; color:#6e6e73; }
549
+
550
+ /* ---- login guide strip (top of the panel body) ---- */
551
+ #dsh-ego-login { display:none; align-items:center; gap:8px; margin:0 14px 9px; padding:7px 10px;
552
+ border-radius:9px; border:1px solid rgba(255,214,10,.28); background: rgba(255,214,10,.09); }
553
+ #dsh-ego-login.show { display:flex; }
554
+ #dsh-ego-login .dsh-ego-login-txt { flex:1; min-width:0; font-size:11px; line-height:1.45; color:#f5f5f7; }
555
+ #dsh-ego-login .dsh-ego-login-txt b { color:#ffd60a; }
556
+ #dsh-ego-login .dsh-ego-login-btn { flex:none; background:#0a84ff; color:#fff; border:none; border-radius:8px;
557
+ font-size:11px; padding:4px 10px; cursor:pointer; white-space:nowrap; transition: background .15s ease; }
558
+ #dsh-ego-login .dsh-ego-login-btn:hover { background:#338cff; }
559
+ #dsh-ego-login .dsh-ego-login-btn.saving { opacity:.55; pointer-events:none; }
560
+ #dsh-ego-login .dsh-ego-login-note { flex:none; font-size:10.5px; color:#6e6e73; white-space:nowrap; }
561
+ /* dismiss (×) on guide strips so the user can close them and reclaim the space */
562
+ .dsh-ego-dismiss { flex:none; width:18px; height:18px; line-height:1; border-radius:50%; border:none;
563
+ background: rgba(255,255,255,.12); color:inherit; font-size:13px; cursor:pointer; opacity:.75;
564
+ display:inline-flex; align-items:center; justify-content:center; padding:0; transition: background .15s,opacity .15s; }
565
+ .dsh-ego-dismiss:hover { background: rgba(255,69,58,.35); opacity:1; }
566
+ #dsh-ego-login .dsh-ego-dismiss { color:#ffd60a; }
567
+ #dsh-ego-captcha .dsh-ego-dismiss { color:#ffd8d5; }
568
+
569
+ /* ---- human-verification (CAPTCHA) reminder strip ---- */
570
+ #dsh-ego-captcha { display:none; align-items:center; gap:8px; margin:0 14px 9px; padding:8px 11px;
571
+ border-radius:9px; border:1px solid rgba(255,69,58,.4); background: rgba(255,69,58,.13); color:#ffe1de; }
572
+ #dsh-ego-captcha.show { display:flex; }
573
+ #dsh-ego-captcha .dsh-ego-captcha-txt { flex:1; min-width:0; font-size:11.5px; line-height:1.5; }
574
+ #dsh-ego-captcha .dsh-ego-captcha-txt b { color:#ff6961; }
575
+ #dsh-ego-captcha .dsh-ego-captcha-kind { flex:none; font-size:10px; padding:2px 8px; border-radius:999px;
576
+ background: rgba(255,255,255,.12); color:#ffd8d5; text-transform:uppercase; letter-spacing:.4px; }
577
+
578
+ /* ---- tab bar: frosted pills ---- */
579
+ #dsh-ego-tabs { display:flex; gap:6px; padding:9px 12px;
580
+ border-bottom:1px solid rgba(255,255,255,.08); overflow-x:auto; flex-shrink:0; scrollbar-width:thin; }
581
+ #dsh-ego-tabs:empty { display:none; }
582
+ .dsh-ego-tab {
583
+ display:inline-flex; align-items:center; gap:6px; max-width:176px; white-space:nowrap;
584
+ padding:5px 12px; border-radius: 999px; cursor:pointer; font-size:11.5px; flex-shrink:0;
585
+ border:1px solid rgba(255,255,255,.1);
586
+ background: rgba(72,72,74,.45); color:#aeaeb2;
587
+ transition: background .15s ease, color .15s ease, border-color .15s ease;
588
+ }
589
+ .dsh-ego-tab > .dsh-ego-tabtxt { overflow:hidden; text-overflow:ellipsis; }
590
+ .dsh-ego-tab:hover { color:#f5f5f7; background: rgba(72,72,74,.65); }
591
+ .dsh-ego-tab.active {
592
+ background: #0a84ff; color:#fff; border-color: transparent;
593
+ box-shadow: 0 2px 10px rgba(10,132,255,.35);
594
+ }
595
+ .dsh-ego-tab .dsh-ego-tabdot { width:7px; height:7px; border-radius:50%; background:#86868b; flex-shrink:0; }
596
+ .dsh-ego-tab.active .dsh-ego-tabdot { background:#fff; }
597
+ .dsh-ego-tab .dsh-ego-tabclose { flex-shrink:0; width:14px; height:14px; line-height:13px; text-align:center;
598
+ border-radius:50%; font-size:12px; color:#86868b; margin-left:2px; }
599
+ .dsh-ego-tab .dsh-ego-tabclose:hover { background:rgba(255,255,255,.2); color:#ff453a; }
600
+ .dsh-ego-tab.active .dsh-ego-tabclose { color:rgba(255,255,255,.85); }
601
+ .dsh-ego-tab.active .dsh-ego-tabclose:hover { color:#ff453a; background:rgba(255,255,255,.25); }
602
+
603
+ /* ---- main live view ---- */
604
+ .dsh-ego-liveview { display:flex; flex-direction:column; gap:9px; min-height:60px;
605
+ overflow:hidden; /* clips the zoomed image so it doesn't bleed outside */ }
606
+ .dsh-ego-livebadge { font-size:11px; color:#86868b; letter-spacing:.3px;
607
+ display:flex; align-items:center; gap:6px; }
608
+ .dsh-ego-state-dot { display:inline-block; width:8px; height:8px; border-radius:50%;
609
+ background:#30d158; box-shadow:0 0 6px #30d15888; flex-shrink:0;
610
+ animation: dsh-ego-breathe 2.4s ease-in-out infinite; }
611
+ .dsh-ego-state-dot.busy { background:#30d158; box-shadow:0 0 7px #30d158bb; animation:none; }
612
+ .dsh-ego-state-dot.pin { background:#0a84ff; box-shadow:0 0 6px #0a84ff88; animation:none; }
613
+ .dsh-ego-back {
614
+ background: rgba(255,255,255,.12); color:#f5f5f7;
615
+ border:1px solid rgba(255,255,255,.12); border-radius:7px;
616
+ cursor:pointer; font-size:11px; padding:3px 9px;
617
+ display:inline-flex; align-items:center; gap:4px;
618
+ transition: background .15s ease;
619
+ }
620
+ .dsh-ego-back:hover { background: rgba(255,255,255,.2); }
621
+ .dsh-ego-back.dsh-ego-pick-on { background: rgba(56,189,248,.3); color: #7dd3fc; }
622
+ .dsh-ego-liveimg {
623
+ width:100%; border-radius:11px; display:block;
624
+ max-height:50vh; object-fit:contain;
625
+ border:1px solid rgba(255,255,255,.14);
626
+ background:#000; /* letterbox behind landscape jpeg */
627
+ box-shadow: 0 4px 16px rgba(0,0,0,.35);
628
+ user-select:none; -webkit-user-select:none; touch-action:none;
629
+ will-change:transform; cursor:grab;
630
+ }
631
+ .dsh-ego-zoomhint { font-size:10.5px; color:#6e6e73; letter-spacing:.2px; margin-top:-3px; }
632
+ .dsh-ego-livetitle { font-size:13px; font-weight:600; }
633
+ .dsh-ego-liveurl { font-size:11.5px; color:#86868b; word-break:break-all; }
634
+ .dsh-ego-liveurl.dsh-ego-hint { color:#75c2ff; font-style:italic; font-weight:500; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; text-shadow:0 0 6px rgba(117,194,255,.4); }
635
+ .dsh-ego-hint { animation: dsh-ego-hint-in .2s ease; }
636
+ @keyframes dsh-ego-hint-in { from { opacity:.3 } to { opacity:1 } }
637
+
638
+ /* ---- history drawer ---- */
639
+ #dsh-ego-history { display:none; flex-direction:column; width:224px; flex-shrink:0;
640
+ border-left:1px solid rgba(255,255,255,.08); background: rgba(0,0,0,.18); }
641
+ #dsh-ego-history.open { display:flex; }
642
+ #dsh-ego-historyhead { padding:9px 12px; font-size:12px; font-weight:600; color:#86868b;
643
+ display:flex; align-items:center; gap:6px;
644
+ border-bottom:1px solid rgba(255,255,255,.06); }
645
+ #dsh-ego-historyhead svg { width:12px; height:12px; }
646
+ #dsh-ego-historylist { overflow-y:auto; padding:7px; }
647
+ .dsh-ego-hitem { display:flex; gap:8px; align-items:center; padding:6px; border-radius:9px; cursor:pointer;
648
+ transition: background .15s ease; }
649
+ .dsh-ego-hitem:hover { background: rgba(255,255,255,.1); }
650
+ .dsh-ego-hthumb { width:58px; height:42px; border-radius:6px; object-fit:cover; background:#000;
651
+ flex-shrink:0; border:1px solid rgba(255,255,255,.14); }
652
+ .dsh-ego-hinfo { min-width:0; }
653
+ .dsh-ego-hurl { font-size:10.5px; color:#86868b; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
654
+ .dsh-ego-htitle { font-size:10.5px; font-weight:500; color:#f5f5f7; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
655
+ .dsh-ego-hactive { color:#30d158; font-size:10.5px; }
656
+ .dsh-ego-hnone { padding:16px 8px; text-align:center; font-size:11px; color:#6e6e73; }
657
+
658
+ #dsh-ego-cols { display:flex; flex:1; min-height:0; }
659
+ .dsh-ego-maincol { flex:1; min-width:0; display:flex; flex-direction:column; }
660
+ `;
661
+ const ICON_GLOBE = `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"><circle cx="12" cy="12" r="9"/><path d="M12 3c2.5 2.4 3.8 5.4 3.8 9S14.5 18.6 12 21"/><path d="M12 3C9.5 5.4 8.2 8.4 8.2 12s1.3 6.6 3.8 9"/><path d="M3 12h18"/></svg>`;
662
+ const ICON_REFRESH = `<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M20 12a8 8 0 1 1-2.5-5.8"/><path d="M20 4.5V9h-4.5"/></svg>`;
663
+ const ICON_CLOCK = `<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"><circle cx="12" cy="12" r="9"/><path d="M12 7.5V12l3 2"/></svg>`;
664
+ const ICON_CLOSE = `<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>`;
665
+ const ICON_GRIP = `<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><circle cx="8" cy="6" r="1.8"/><circle cx="16" cy="6" r="1.8"/><circle cx="8" cy="12" r="1.8"/><circle cx="16" cy="12" r="1.8"/><circle cx="8" cy="18" r="1.8"/><circle cx="16" cy="18" r="1.8"/></svg>`;
666
+ function apply(ctx) {
667
+ var betterSidebarService;
668
+ try {
669
+ betterSidebarService = typeof ctx.get === "function" ? ctx.get("betterSidebar") : void 0;
670
+ } catch (e) {
671
+ betterSidebarService = void 0;
672
+ }
673
+ if (betterSidebarService !== void 0) ctx.effect(() => mountSidebarTab(ctx, betterSidebarService), "dsh-browser-cdp sidebar tab");
674
+ else {
675
+ var disposeFloating = null;
676
+ ctx.effect(() => {
677
+ disposeFloating = mountFloatingWatch(ctx);
678
+ return function() {
679
+ if (disposeFloating) {
680
+ var d = disposeFloating;
681
+ disposeFloating = null;
682
+ d();
683
+ }
684
+ };
685
+ }, "dsh-browser-cdp watch panel");
686
+ if (typeof ctx.inject === "function") ctx.inject(["betterSidebar"], function(sidebarCtx) {
687
+ var svc;
688
+ try {
689
+ svc = typeof sidebarCtx.get === "function" ? sidebarCtx.get("betterSidebar") : sidebarCtx.betterSidebar;
690
+ } catch (e) {
691
+ svc = void 0;
692
+ }
693
+ if (!svc) return;
694
+ if (disposeFloating) {
695
+ var d2 = disposeFloating;
696
+ disposeFloating = null;
697
+ d2();
698
+ }
699
+ sidebarCtx.effect(function() {
700
+ return mountSidebarTab(sidebarCtx, svc);
701
+ }, "dsh-browser-cdp sidebar tab");
702
+ });
703
+ }
704
+ }
705
+ function mountFloatingWatch(ctx) {
706
+ if (document.getElementById("dsh-ego-fab") !== null) return () => {};
707
+ const style = document.createElement("style");
708
+ style.textContent = PANEL_CSS;
709
+ document.head.appendChild(style);
710
+ const panel = document.createElement("div");
711
+ panel.id = "dsh-ego-panel";
712
+ panel.hidden = true;
713
+ panel.innerHTML = `
714
+ <div id="dsh-ego-head">
715
+ <span class="dsh-ego-grip" title="${wt("dragHint")}">${ICON_GRIP}</span>
716
+ <span id="dsh-ego-title">${ICON_GLOBE}<span style="margin-left:6px;flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${wt("title")}</span></span>
717
+ <button id="dsh-ego-refresh" class="dsh-ego-iconbtn" title="${wt("refresh")}">${ICON_REFRESH}</button>
718
+ <button id="dsh-ego-historybtn" class="dsh-ego-iconbtn off" title="${wt("historyShow")}">${ICON_CLOCK}</button>
719
+ <button id="dsh-ego-close" class="dsh-ego-iconbtn" title="${wt("settingsHide")}">${ICON_CLOSE}</button>
720
+ </div>
721
+ <div id="dsh-ego-tabs"></div>
722
+ <div id="dsh-ego-login">
723
+ <span class="dsh-ego-login-txt">${wt("loginTitle")}</span>
724
+ <button id="dsh-ego-login-btn" class="dsh-ego-login-btn" type="button">${wt("loginBtn")}</button>
725
+ <span class="dsh-ego-login-note" id="dsh-ego-login-note"></span>
726
+ <button class="dsh-ego-dismiss" type="button" title="${wt("loginDismiss")}" data-dismiss="login">×</button>
727
+ </div>
728
+ <div id="dsh-ego-captcha">
729
+ <span class="dsh-ego-captcha-txt"><b>${wt("captchaTitle")}</b> — ${wt("captchaHint")}</span>
730
+ <span class="dsh-ego-captcha-kind" id="dsh-ego-captcha-kind"></span>
731
+ <button class="dsh-ego-dismiss" type="button" title="${wt("captchaDismiss")}" data-dismiss="captcha">×</button>
732
+ </div>
733
+ <div id="dsh-ego-cols">
734
+ <div class="dsh-ego-maincol">
735
+ <div id="dsh-ego-body"></div>
736
+ </div>
737
+ <aside id="dsh-ego-history">
738
+ <div id="dsh-ego-historyhead">${ICON_CLOCK} ${wt("history")}</div>
739
+ <div id="dsh-ego-historylist"></div>
740
+ </aside>
741
+ </div>
742
+ <div class="dsh-ego-off">${wt("liveView")} · ${wt("realtime")} · ${ICON_CLOCK} ${wt("historyShow")}</div>
743
+ `;
744
+ const fab = document.createElement("button");
745
+ fab.id = "dsh-ego-fab";
746
+ fab.type = "button";
747
+ fab.title = wt("fabTitle");
748
+ fab.textContent = "";
749
+ fab.innerHTML = `${ICON_GLOBE}<span class="dsh-ego-dot"></span>`;
750
+ const body = panel.querySelector("#dsh-ego-body");
751
+ const titleEl = panel.querySelector("#dsh-ego-title");
752
+ const refreshBtn = panel.querySelector("#dsh-ego-refresh");
753
+ const closeBtn = panel.querySelector("#dsh-ego-close");
754
+ const historyBtn = panel.querySelector("#dsh-ego-historybtn");
755
+ const historyEl = panel.querySelector("#dsh-ego-history");
756
+ const historyList = panel.querySelector("#dsh-ego-historylist");
757
+ const tabsEl = panel.querySelector("#dsh-ego-tabs");
758
+ const loginEl = panel.querySelector("#dsh-ego-login");
759
+ const loginBtn = panel.querySelector("#dsh-ego-login-btn");
760
+ const loginNote = panel.querySelector("#dsh-ego-login-note");
761
+ const captchaEl = panel.querySelector("#dsh-ego-captcha");
762
+ const captchaKindEl = panel.querySelector("#dsh-ego-captcha-kind");
763
+ const FLUSH_ROUTE$1 = "/api/bcdp/flush";
764
+ const dismissedGuides = {
765
+ login: false,
766
+ captcha: false
767
+ };
768
+ const bindGuideDismiss = (which, el) => {
769
+ const btn = el && el.querySelector("[data-dismiss=\"" + which + "\"]");
770
+ if (!btn) return;
771
+ btn.addEventListener("click", () => {
772
+ dismissedGuides[which] = true;
773
+ el.classList.remove("show");
774
+ });
775
+ };
776
+ bindGuideDismiss("login", loginEl);
777
+ bindGuideDismiss("captcha", captchaEl);
778
+ const setTitle = (text) => {
779
+ const label = titleEl.querySelector("span:last-child");
780
+ if (label) label.textContent = text;
781
+ };
782
+ let disposed = false;
783
+ let historyOpen = false;
784
+ let lastList = [];
785
+ const setHistory = (open) => {
786
+ historyOpen = open;
787
+ historyEl.classList.toggle("open", open);
788
+ panel.classList.toggle("open-drawer", open);
789
+ historyBtn.classList.toggle("off", !open);
790
+ historyBtn.title = open ? wt("historyHide") : wt("historyShow");
791
+ if (open) renderHistory(lastList);
792
+ };
793
+ const renderHistory = (spaces) => {
794
+ historyList.innerHTML = "";
795
+ const list = Array.isArray(spaces) ? [...spaces].sort((a, b) => (a.lastActive ?? 0) - (b.lastActive ?? 0)) : [];
796
+ if (list.length === 0) {
797
+ historyList.innerHTML = `<div class="dsh-ego-hnone">${wt("noHistory")}</div>`;
798
+ return;
799
+ }
800
+ for (const s of list) {
801
+ const item = document.createElement("div");
802
+ item.className = "dsh-ego-hitem";
803
+ const thumbSrc = frameCache.get(s.targetId);
804
+ const thumb = thumbSrc ? `<img class="dsh-ego-hthumb" src="${thumbSrc}" alt="">` : `<div class="dsh-ego-hthumb"></div>`;
805
+ const active = s.targetId === currentActiveId;
806
+ item.innerHTML = `${thumb}
807
+ <div class="dsh-ego-hinfo">
808
+ <div class="dsh-ego-htitle">${escapeHtml(s.title || s.url || wt("newTab"))}</div>
809
+ <div class="dsh-ego-hurl">${escapeHtml(s.url || "(about:blank)")}</div>
810
+ ${active ? "<div class=\"dsh-ego-hactive\">● " + wt("current") + "</div>" : ""}
811
+ </div>`;
812
+ item.addEventListener("click", () => openPreview(s));
813
+ historyList.appendChild(item);
814
+ }
815
+ };
816
+ let pinned = null;
817
+ let currentActiveId = null;
818
+ let agentActiveId = null;
819
+ let selectedTabId = null;
820
+ let zoomState = {
821
+ scale: 1,
822
+ tx: 0,
823
+ ty: 0
824
+ };
825
+ const frameCache = /* @__PURE__ */ new Map();
826
+ let liveImg = null;
827
+ let liveImgTargetId = null;
828
+ var pickCtl = createPickControl(function(pick, message) {
829
+ if (pickUrlLine) pickUrlLine.textContent = message || "";
830
+ if (pickBtnEl) {
831
+ pickBtnEl.textContent = pick === "failed" ? wt("pickFailed") : pick === "on" ? wt("picking") : wt("pickMode");
832
+ pickBtnEl.classList.toggle("dsh-ego-pick-on", pick === "on");
833
+ }
834
+ }, function(el, a) {
835
+ return deliverPickToConversation(ctx, el, a);
836
+ });
837
+ var pickBtnEl = null;
838
+ var pickUrlLine = null;
839
+ let pendingLiveFrame = null;
840
+ let liveFlushRaf = null;
841
+ const pageMeta = /* @__PURE__ */ new Map();
842
+ const watchClientId = "floating-" + Math.random().toString(36).slice(2);
843
+ let watchStarted = false, watchTargetId = null, watchRenewTimer = null, watchStopTimer = null, watchRequest = null, captureBackend = "cdp", streamGeneration = 0, streamState = "idle", streamMime = "video/mp4; codecs=\"avc1.42E01E\"", videoCleanup = null;
844
+ const effectiveVisible = () => !panel.hidden;
845
+ const stopVideo = () => {
846
+ if (videoCleanup) try {
847
+ videoCleanup();
848
+ } catch {}
849
+ videoCleanup = null;
850
+ };
851
+ const applyCaptureStatus = (status) => {
852
+ if (!status || typeof status !== "object") return;
853
+ if (Number.isFinite(status.generation) && status.generation < streamGeneration) return;
854
+ if (status.generation === streamGeneration && streamState === "streaming" && status.state === "starting") return;
855
+ const nextBackend = status.backend || captureBackend;
856
+ const nextGeneration = status.generation ?? streamGeneration;
857
+ const nextState = status.state || streamState;
858
+ const nextMime = status.mime || streamMime;
859
+ const changed = captureBackend !== nextBackend || streamGeneration !== nextGeneration || streamState !== nextState || streamMime !== nextMime;
860
+ captureBackend = nextBackend;
861
+ streamGeneration = nextGeneration;
862
+ streamState = nextState;
863
+ status.message || status.code;
864
+ streamMime = nextMime;
865
+ if (changed) {
866
+ stopVideo();
867
+ const current = lastList.find((s) => s.targetId === (selectedTabId || currentActiveId));
868
+ if (current) renderLiveMain(current, selectedTabId !== null);
869
+ }
870
+ };
871
+ const requestWatch = (route, body$1) => {
872
+ if (watchRequest) return null;
873
+ watchRequest = postJson(route, body$1).finally(() => {
874
+ watchRequest = null;
875
+ });
876
+ return watchRequest;
877
+ };
878
+ const syncWatch = (targetId) => {
879
+ if (disposed || !effectiveVisible() || !targetId) return;
880
+ if (watchStopTimer) {
881
+ window.clearTimeout(watchStopTimer);
882
+ watchStopTimer = null;
883
+ }
884
+ if (watchStarted && watchTargetId === targetId) return;
885
+ const request = requestWatch(watchStarted ? WATCH_SWITCH_ROUTE : WATCH_START_ROUTE, {
886
+ clientId: watchClientId,
887
+ targetId
888
+ });
889
+ if (!request) {
890
+ watchRequest.finally(() => syncWatch(targetId));
891
+ return;
892
+ }
893
+ request.then((status) => {
894
+ watchStarted = status && status.ok !== false;
895
+ watchTargetId = status?.targetId || targetId;
896
+ if (watchTargetId !== targetId) {
897
+ selectedTabId = null;
898
+ currentActiveId = watchTargetId;
899
+ }
900
+ applyCaptureStatus(status);
901
+ if (!effectiveVisible()) stopWatch(true);
902
+ }).catch(() => {});
903
+ if (!watchRenewTimer) watchRenewTimer = window.setInterval(() => {
904
+ if (effectiveVisible() && watchTargetId) {
905
+ const renewal = requestWatch(WATCH_START_ROUTE, {
906
+ clientId: watchClientId,
907
+ targetId: watchTargetId
908
+ });
909
+ if (renewal) renewal.then(applyCaptureStatus).catch(() => {});
910
+ }
911
+ }, 5e3);
912
+ };
913
+ const stopWatch = (immediate) => {
914
+ if (watchRenewTimer) {
915
+ window.clearInterval(watchRenewTimer);
916
+ watchRenewTimer = null;
917
+ }
918
+ const stop = () => {
919
+ watchStopTimer = null;
920
+ watchStarted = false;
921
+ watchTargetId = null;
922
+ postJson(WATCH_STOP_ROUTE, { clientId: watchClientId }).catch(() => {});
923
+ };
924
+ if (immediate) stop();
925
+ else {
926
+ if (watchStopTimer) window.clearTimeout(watchStopTimer);
927
+ watchStopTimer = window.setTimeout(stop, 1500);
928
+ }
929
+ };
930
+ const INPUT_ROUTE$1 = "/api/bcdp/input";
931
+ let inputBusy = false;
932
+ /**
933
+ * Send a pointer/wheel intention to the agent browser. Coordinates
934
+ * are already in browser CSS pixels; the worker turns them into CDP
935
+ * Input.dispatchMouseEvent on the page the panel is showing.
936
+ * `type`: mouseMoved | mousePressed | mouseReleased | mouseWheel.
937
+ */
938
+ const sendInput = (targetId, type, params) => {
939
+ if (!!!targetId || type !== "mouseReleased" && type !== "keyUp" && !effectiveVisible()) return;
940
+ if (inputBusy && type === "mouseMoved") return;
941
+ if (type === "mouseMoved") {
942
+ inputBusy = true;
943
+ window.setTimeout(() => {
944
+ inputBusy = false;
945
+ }, 24);
946
+ }
947
+ fetch(INPUT_ROUTE$1, {
948
+ method: "POST",
949
+ headers: { "content-type": "application/json" },
950
+ body: JSON.stringify({
951
+ targetId,
952
+ type,
953
+ ...params
954
+ })
955
+ }).then((res) => {
956
+ if (res.status === 409) {
957
+ liveImgTargetId = null;
958
+ refresh();
959
+ }
960
+ }).catch(() => {});
961
+ };
962
+ const keyboardProxy = createKeyboardProxy((targetId, type, params) => sendInput(targetId, type, params));
963
+ /**
964
+ * Map an event's client coords to the agent page's CSS pixels.
965
+ *
966
+ * The shown <img> is the screencast frame laid out with
967
+ * object-fit:contain, so the page fills a centered letterboxed box
968
+ * inside the element. We find that box from the image's natural
969
+ * (frame) size vs its rendered box, then scale into the page's CSS
970
+ * viewport (vw/vh), which the worker attaches to each frame.
971
+ */
972
+ const browserXY = (e) => {
973
+ if (liveImgTargetId == null) return null;
974
+ const m = pageMeta.get(liveImgTargetId);
975
+ const vw = m?.vw, vh = m?.vh;
976
+ if (!Number.isFinite(vw) || !Number.isFinite(vh)) return null;
977
+ const img = liveImg;
978
+ if (!img) return null;
979
+ const rect = img.getBoundingClientRect();
980
+ const natW = img.naturalWidth || img.videoWidth || rect.width;
981
+ const natH = img.naturalHeight || img.videoHeight || rect.height;
982
+ if (!natW || !natH) return null;
983
+ const scale = Math.min(rect.width / natW, rect.height / natH);
984
+ const contentW = natW * scale;
985
+ const contentH = natH * scale;
986
+ const ox = (rect.width - contentW) / 2;
987
+ const oy = (rect.height - contentH) / 2;
988
+ const rx = e.clientX - rect.left - ox;
989
+ const ry = e.clientY - rect.top - oy;
990
+ return {
991
+ x: rx / contentW * vw,
992
+ y: ry / contentH * vh
993
+ };
994
+ };
995
+ const makeZoomImage = (urlEl, tagName = "img") => {
996
+ const img = document.createElement(tagName);
997
+ img.className = "dsh-ego-liveimg";
998
+ if (tagName === "img") img.draggable = false;
999
+ else {
1000
+ img.muted = true;
1001
+ img.autoplay = true;
1002
+ img.playsInline = true;
1003
+ }
1004
+ img.title = "滚轮缩放 · 按住拖动平移 · 缩小到最小或双击复位";
1005
+ const realText = urlEl ? urlEl.textContent : "";
1006
+ let hintTimer = null;
1007
+ const clearHint = () => {
1008
+ if (hintTimer) {
1009
+ window.clearTimeout(hintTimer);
1010
+ hintTimer = null;
1011
+ }
1012
+ };
1013
+ const showHint = (txt) => {
1014
+ if (!urlEl) return;
1015
+ urlEl.textContent = txt;
1016
+ urlEl.classList.add("dsh-ego-hint");
1017
+ clearHint();
1018
+ hintTimer = window.setTimeout(() => {
1019
+ urlEl.textContent = realText;
1020
+ urlEl.classList.remove("dsh-ego-hint");
1021
+ hintTimer = null;
1022
+ }, 2e3);
1023
+ };
1024
+ const apply$1 = () => {
1025
+ img.style.transformOrigin = "0 0";
1026
+ img.style.transform = `translate(${zoomState.tx}px, ${zoomState.ty}px) scale(${zoomState.scale})`;
1027
+ };
1028
+ let viewPanning = false;
1029
+ let browserDrag = false;
1030
+ let sx = 0, sy = 0, stx = 0, sty = 0;
1031
+ let lastDragPos = null;
1032
+ let dragTargetId = null;
1033
+ let downButtons = 0;
1034
+ const resetView = () => {
1035
+ zoomState = {
1036
+ scale: 1,
1037
+ tx: 0,
1038
+ ty: 0
1039
+ };
1040
+ apply$1();
1041
+ showHint(wt("hintReset"));
1042
+ };
1043
+ img.title = wt("hintReset");
1044
+ img.addEventListener("wheel", (e) => {
1045
+ e.preventDefault();
1046
+ e.stopPropagation();
1047
+ if (e.ctrlKey || e.metaKey) {
1048
+ const rect = img.getBoundingClientRect();
1049
+ const mx = e.clientX - rect.left, my = e.clientY - rect.top;
1050
+ const next = Math.min(8, Math.max(1, zoomState.scale * (e.deltaY < 0 ? 1.15 : 1 / 1.15)));
1051
+ if (next <= 1) {
1052
+ resetView();
1053
+ return;
1054
+ }
1055
+ zoomState.tx = mx - (mx - zoomState.tx) * (next / zoomState.scale);
1056
+ zoomState.ty = my - (my - zoomState.ty) * (next / zoomState.scale);
1057
+ zoomState.scale = next;
1058
+ apply$1();
1059
+ showHint(wt("hintPan"));
1060
+ return;
1061
+ }
1062
+ const p = browserXY(e);
1063
+ if (p && liveImgTargetId) sendInput(liveImgTargetId, "mouseWheel", {
1064
+ x: p.x,
1065
+ y: p.y,
1066
+ deltaX: e.deltaX || 0,
1067
+ deltaY: e.deltaY || (e.deltaMode === 1 ? 40 : e.deltaY || 100)
1068
+ });
1069
+ }, { passive: false });
1070
+ img.addEventListener("pointerdown", (e) => {
1071
+ if (e.button !== 0) return;
1072
+ if (pickCtl.isEnabled()) {
1073
+ const pp = browserXY(e);
1074
+ if (pp && liveImgTargetId) pickCtl.clickAt(pp.x, pp.y, liveImgTargetId);
1075
+ return;
1076
+ }
1077
+ img.setPointerCapture(e.pointerId);
1078
+ sx = e.clientX;
1079
+ sy = e.clientY;
1080
+ stx = zoomState.tx;
1081
+ sty = zoomState.ty;
1082
+ if (e.ctrlKey || e.metaKey) {
1083
+ viewPanning = true;
1084
+ img.style.cursor = "grabbing";
1085
+ showHint(wt("hintScroll"));
1086
+ return;
1087
+ }
1088
+ browserDrag = true;
1089
+ dragTargetId = liveImgTargetId;
1090
+ keyboardProxy.focusAt(e, dragTargetId);
1091
+ lastDragPos = null;
1092
+ downButtons = 1;
1093
+ const p = browserXY(e);
1094
+ if (p) {
1095
+ lastDragPos = p;
1096
+ sendInput(dragTargetId, "mousePressed", {
1097
+ x: p.x,
1098
+ y: p.y,
1099
+ button: "left",
1100
+ buttons: 1,
1101
+ clickCount: 1
1102
+ });
1103
+ }
1104
+ });
1105
+ img.addEventListener("pointermove", (e) => {
1106
+ if (viewPanning) {
1107
+ zoomState.tx = stx + (e.clientX - sx);
1108
+ zoomState.ty = sty + (e.clientY - sy);
1109
+ apply$1();
1110
+ return;
1111
+ }
1112
+ if (!browserDrag) {
1113
+ const p$1 = browserXY(e);
1114
+ if (p$1) sendInput(liveImgTargetId, "mouseMoved", {
1115
+ x: p$1.x,
1116
+ y: p$1.y,
1117
+ buttons: 0
1118
+ });
1119
+ return;
1120
+ }
1121
+ const p = browserXY(e);
1122
+ if (p) {
1123
+ sendInput(dragTargetId, "mouseMoved", {
1124
+ x: p.x,
1125
+ y: p.y,
1126
+ buttons: downButtons
1127
+ });
1128
+ lastDragPos = p;
1129
+ }
1130
+ });
1131
+ const stopDrag = (e) => {
1132
+ if (viewPanning) {
1133
+ viewPanning = false;
1134
+ img.style.cursor = e.ctrlKey ? "grab" : "grab";
1135
+ }
1136
+ if (browserDrag) {
1137
+ browserDrag = false;
1138
+ if (lastDragPos && dragTargetId) sendInput(dragTargetId, "mouseReleased", {
1139
+ x: lastDragPos.x,
1140
+ y: lastDragPos.y,
1141
+ button: "left",
1142
+ buttons: 0,
1143
+ clickCount: 1
1144
+ });
1145
+ dragTargetId = null;
1146
+ }
1147
+ img.style.cursor = "grab";
1148
+ };
1149
+ img.addEventListener("pointerup", stopDrag);
1150
+ img.addEventListener("pointercancel", stopDrag);
1151
+ img.addEventListener("pointerleave", (e) => {
1152
+ if (browserDrag || viewPanning) stopDrag(e);
1153
+ });
1154
+ img.addEventListener("dblclick", (e) => {
1155
+ e.preventDefault();
1156
+ resetView();
1157
+ });
1158
+ img.style.cursor = "grab";
1159
+ apply$1();
1160
+ return img;
1161
+ };
1162
+ const renderTabs = (spaces) => {
1163
+ tabsEl.innerHTML = "";
1164
+ const list = Array.isArray(spaces) ? spaces : [];
1165
+ if (list.length === 0) {
1166
+ if (selectedTabId) selectedTabId = null;
1167
+ return;
1168
+ }
1169
+ for (const s of list) {
1170
+ const tab = document.createElement("div");
1171
+ tab.className = "dsh-ego-tab";
1172
+ tab.title = s.url || "";
1173
+ tab.__tid = s.targetId;
1174
+ const dot = document.createElement("span");
1175
+ dot.className = "dsh-ego-tabdot";
1176
+ const txt = document.createElement("span");
1177
+ txt.className = "dsh-ego-tabtxt";
1178
+ txt.textContent = s.title || s.url || wt("newTab");
1179
+ tab.appendChild(dot);
1180
+ tab.appendChild(txt);
1181
+ const closeBtn$1 = document.createElement("span");
1182
+ closeBtn$1.className = "dsh-ego-tabclose";
1183
+ closeBtn$1.title = wt("closeTab");
1184
+ closeBtn$1.textContent = "×";
1185
+ closeBtn$1.addEventListener("click", (e) => {
1186
+ e.stopPropagation();
1187
+ (async () => {
1188
+ try {
1189
+ await fetch(EGO_CLOSE_ROUTE, {
1190
+ method: "POST",
1191
+ headers: { "content-type": "application/json" },
1192
+ body: JSON.stringify({ targetId: s.targetId })
1193
+ });
1194
+ } catch {}
1195
+ if (selectedTabId === s.targetId) {
1196
+ selectedTabId = null;
1197
+ pinned = null;
1198
+ }
1199
+ })().then(() => refresh());
1200
+ });
1201
+ tab.appendChild(closeBtn$1);
1202
+ if (s.targetId === selectedTabId || selectedTabId === null && s.targetId === currentActiveId) tab.classList.add("active");
1203
+ tab.addEventListener("click", () => {
1204
+ if (selectedTabId === s.targetId) {
1205
+ selectedTabId = null;
1206
+ pinned = null;
1207
+ renderSpaces(lastList);
1208
+ return;
1209
+ }
1210
+ selectedTabId = s.targetId;
1211
+ pinned = null;
1212
+ renderLiveMain(s, true);
1213
+ syncWatch(s.targetId);
1214
+ [...tabsEl.querySelectorAll(".dsh-ego-tab")].forEach((t) => t.classList.toggle("active", t.__tid === s.targetId));
1215
+ });
1216
+ tabsEl.appendChild(tab);
1217
+ }
1218
+ };
1219
+ const renderSingleView = (s) => {
1220
+ body.innerHTML = "";
1221
+ const view = document.createElement("div");
1222
+ view.className = "dsh-ego-liveview";
1223
+ const badge = document.createElement("div");
1224
+ badge.className = "dsh-ego-livebadge";
1225
+ badge.innerHTML = pinned ? `<span class="dsh-ego-state-dot pin"></span> ${wt("pinned")}` : `<span class="dsh-ego-state-dot${fab.classList.contains("dsh-ego-busy") ? " busy" : ""}"></span> ${wt("realtime")}`;
1226
+ view.appendChild(badge);
1227
+ if (pinned) {
1228
+ const back = document.createElement("button");
1229
+ back.className = "dsh-ego-back";
1230
+ back.type = "button";
1231
+ back.textContent = wt("backToLive");
1232
+ back.addEventListener("click", () => {
1233
+ pinned = null;
1234
+ renderSpaces(lastList);
1235
+ });
1236
+ badge.appendChild(back);
1237
+ }
1238
+ const t = document.createElement("div");
1239
+ t.className = "dsh-ego-livetitle";
1240
+ t.textContent = s.title || s.url || wt("newTab");
1241
+ const u = document.createElement("div");
1242
+ u.className = "dsh-ego-liveurl";
1243
+ u.textContent = s.url || "";
1244
+ const cached = frameCache.get(s.targetId);
1245
+ if (captureBackend === "ffmpeg" || cached) {
1246
+ const img = makeZoomImage(u, captureBackend === "ffmpeg" ? "video" : "img");
1247
+ if (captureBackend === "ffmpeg" && streamState === "streaming") {
1248
+ stopVideo();
1249
+ videoCleanup = createMsePlayer(img, streamGeneration, streamMime, (message) => {});
1250
+ } else img.src = cached;
1251
+ img.alt = "live";
1252
+ attachLiveImg(s.targetId, img);
1253
+ view.appendChild(img);
1254
+ } else {
1255
+ const n = document.createElement("div");
1256
+ n.className = "dsh-ego-liveurl";
1257
+ n.textContent = wt("noScreenshot");
1258
+ view.appendChild(n);
1259
+ }
1260
+ view.appendChild(t);
1261
+ view.appendChild(u);
1262
+ body.appendChild(view);
1263
+ };
1264
+ const openPreview = (s) => {
1265
+ if (disposed) return;
1266
+ pinned = s;
1267
+ renderSingleView(s);
1268
+ };
1269
+ const renderSpaces = (spaces) => {
1270
+ if (disposed) return;
1271
+ lastList = Array.isArray(spaces) ? spaces : [];
1272
+ for (const s of lastList) {
1273
+ const prev = pageMeta.get(s.targetId) || { targetId: s.targetId };
1274
+ pageMeta.set(s.targetId, {
1275
+ url: s.url,
1276
+ title: s.title,
1277
+ targetId: s.targetId,
1278
+ ...Number.isFinite(s.viewportW) ? { vw: s.viewportW } : prev.vw !== void 0 ? { vw: prev.vw } : {},
1279
+ ...Number.isFinite(s.viewportH) ? { vh: s.viewportH } : prev.vh !== void 0 ? { vh: prev.vh } : {}
1280
+ });
1281
+ }
1282
+ const liveIds = new Set(lastList.map((s) => s.targetId));
1283
+ for (const id of [...pageMeta.keys()]) if (!liveIds.has(id)) pageMeta.delete(id);
1284
+ for (const id of [...frameCache.keys()]) if (!liveIds.has(id)) frameCache.delete(id);
1285
+ const sorted = [...lastList].sort((a, b) => (b.lastActive ?? 0) - (a.lastActive ?? 0));
1286
+ const activeMarked = lastList.find((s) => s.active === true) || sorted[0] || null;
1287
+ if (activeMarked) {
1288
+ agentActiveId = activeMarked.targetId;
1289
+ currentActiveId = activeMarked.targetId;
1290
+ }
1291
+ maybeShowLoginGuide();
1292
+ maybeShowCaptchaGuide();
1293
+ renderTabs(lastList);
1294
+ if (historyOpen) renderHistory(lastList);
1295
+ if (pinned) return;
1296
+ if (lastList.length === 0) {
1297
+ setTitle("Agent 浏览器");
1298
+ body.innerHTML = `<div class="dsh-ego-empty">${wt("noActivePages")}<br><span style="font-size:11px;">${wt("noActiveHint")}</span></div>`;
1299
+ fab.classList.remove("dsh-ego-live", "dsh-ego-busy");
1300
+ return;
1301
+ }
1302
+ lastList.length;
1303
+ fab.classList.add("dsh-ego-live");
1304
+ const busy = lastList.some((s) => Date.now() - (s.lastActive || 0) <= ACTIVE_WINDOW_MS);
1305
+ if (busy !== lastSawActive) {
1306
+ fab.classList.toggle("dsh-ego-busy", busy);
1307
+ lastSawActive = busy;
1308
+ } else fab.classList.remove("dsh-ego-busy");
1309
+ const sel = selectedTabId !== null ? lastList.find((x) => x.targetId === selectedTabId) : null;
1310
+ const current = sel || activeMarked;
1311
+ currentActiveId = current.targetId;
1312
+ syncWatch(current.targetId);
1313
+ setTitle(sel ? wt("title") : wt("titleLive"));
1314
+ renderLiveMain(current, sel);
1315
+ };
1316
+ const attachLiveImg = (targetId, img) => {
1317
+ liveImg = img;
1318
+ liveImgTargetId = targetId;
1319
+ const cached = frameCache.get(targetId);
1320
+ if (cached) img.src = cached;
1321
+ };
1322
+ const renderLiveMain = (current, isPinned) => {
1323
+ body.innerHTML = "";
1324
+ const view = document.createElement("div");
1325
+ view.className = "dsh-ego-liveview";
1326
+ const badge = document.createElement("div");
1327
+ badge.className = "dsh-ego-livebadge";
1328
+ badge.innerHTML = isPinned ? `<span class="dsh-ego-state-dot pin"></span> ${wt("pinned")}` : `<span class="dsh-ego-state-dot${fab.classList.contains("dsh-ego-busy") ? " busy" : ""}"></span> ${wt("realtime")}`;
1329
+ view.appendChild(badge);
1330
+ const t = document.createElement("div");
1331
+ t.className = "dsh-ego-livetitle";
1332
+ t.textContent = current.title || current.url || wt("newTab");
1333
+ const u = document.createElement("div");
1334
+ u.className = "dsh-ego-liveurl";
1335
+ u.textContent = current.url || "";
1336
+ pickUrlLine = u;
1337
+ const pickBtn = document.createElement("button");
1338
+ pickBtn.type = "button";
1339
+ pickBtn.className = "dsh-ego-back";
1340
+ pickBtn.title = wt("pickModeHint");
1341
+ pickBtn.textContent = wt("pickMode");
1342
+ pickBtnEl = pickBtn;
1343
+ pickBtn.addEventListener("click", () => {
1344
+ pickCtl.toggle(current.targetId);
1345
+ });
1346
+ badge.appendChild(pickBtn);
1347
+ const openHere = document.createElement("button");
1348
+ openHere.type = "button";
1349
+ openHere.className = "dsh-ego-back";
1350
+ openHere.title = wt("openExternal");
1351
+ openHere.textContent = wt("openExternal");
1352
+ openHere.addEventListener("click", () => {
1353
+ const url = current.url;
1354
+ if (url && !url.startsWith("about:") && !url.startsWith("chrome://")) window.open(url, "_blank", "noopener");
1355
+ else openHere.textContent = wt("noUrl");
1356
+ });
1357
+ badge.appendChild(openHere);
1358
+ const raiseBtn = document.createElement("button");
1359
+ raiseBtn.type = "button";
1360
+ raiseBtn.className = "dsh-ego-back";
1361
+ raiseBtn.title = wt("raiseWindowHint");
1362
+ raiseBtn.textContent = wt("raiseWindow");
1363
+ raiseBtn.addEventListener("click", () => {
1364
+ fetch("/api/bcdp/raise", {
1365
+ method: "POST",
1366
+ headers: { "content-type": "application/json" },
1367
+ body: "{}"
1368
+ }).then((r) => r.json().catch(() => null)).catch(() => null);
1369
+ });
1370
+ badge.appendChild(raiseBtn);
1371
+ const cached = frameCache.get(current.targetId);
1372
+ if (captureBackend === "ffmpeg" || cached) {
1373
+ const img = makeZoomImage(u, captureBackend === "ffmpeg" ? "video" : "img");
1374
+ if (captureBackend === "ffmpeg" && streamState === "streaming") {
1375
+ stopVideo();
1376
+ videoCleanup = createMsePlayer(img, streamGeneration, streamMime, (message) => {});
1377
+ } else img.src = cached;
1378
+ img.alt = "live";
1379
+ attachLiveImg(current.targetId, img);
1380
+ view.appendChild(img);
1381
+ } else {
1382
+ const n = document.createElement("div");
1383
+ n.className = "dsh-ego-liveurl";
1384
+ n.textContent = wt("noScreenshot");
1385
+ view.appendChild(n);
1386
+ }
1387
+ view.appendChild(t);
1388
+ view.appendChild(u);
1389
+ body.appendChild(view);
1390
+ };
1391
+ let lastSawActive = false;
1392
+ const refresh = () => {
1393
+ (async () => {
1394
+ try {
1395
+ const res = await fetch(SPACES_ROUTE, { cache: "no-store" });
1396
+ if (disposed || !res.ok) {
1397
+ renderEmpty();
1398
+ return;
1399
+ }
1400
+ const data = await res.json();
1401
+ if (!data || data.ok !== true) {
1402
+ renderEmpty();
1403
+ return;
1404
+ }
1405
+ applyCaptureStatus(data.capture);
1406
+ renderSpaces(data.spaces);
1407
+ } catch {
1408
+ renderEmpty();
1409
+ }
1410
+ })();
1411
+ };
1412
+ const renderEmpty = () => {
1413
+ if (body.children.length === 0) renderSpaces([]);
1414
+ };
1415
+ let sse = null;
1416
+ let lastFrameAt = 0;
1417
+ const FRAME_FOLLOW_MIN_MS$1 = 350;
1418
+ let followTimer = null;
1419
+ const applyFrame = (targetId, dataUrl, vw, vh) => {
1420
+ if (disposed) return;
1421
+ frameCache.set(targetId, dataUrl);
1422
+ const MAX_CACHED_FRAMES = 12;
1423
+ if (frameCache.size > MAX_CACHED_FRAMES) for (const [id] of frameCache) {
1424
+ if (id === targetId || id === liveImgTargetId) continue;
1425
+ frameCache.delete(id);
1426
+ if (frameCache.size <= MAX_CACHED_FRAMES) break;
1427
+ }
1428
+ if (Number.isFinite(vw) && Number.isFinite(vh)) {
1429
+ const cur = pageMeta.get(targetId) || { targetId };
1430
+ pageMeta.set(targetId, {
1431
+ ...cur,
1432
+ vw,
1433
+ vh
1434
+ });
1435
+ }
1436
+ if (liveImg && liveImgTargetId === targetId) {
1437
+ pendingLiveFrame = dataUrl;
1438
+ if (!liveFlushRaf && !disposed) liveFlushRaf = window.requestAnimationFrame(() => {
1439
+ liveFlushRaf = null;
1440
+ if (disposed || !liveImg || pendingLiveFrame == null) return;
1441
+ try {
1442
+ liveImg.src = pendingLiveFrame;
1443
+ } catch {}
1444
+ pendingLiveFrame = null;
1445
+ });
1446
+ return;
1447
+ }
1448
+ if (!pinned && selectedTabId === null && targetId === agentActiveId) {
1449
+ const now = Date.now();
1450
+ if (now - lastFrameAt >= FRAME_FOLLOW_MIN_MS$1) {
1451
+ lastFrameAt = now;
1452
+ if (followTimer) window.clearTimeout(followTimer);
1453
+ followTimer = window.setTimeout(() => {
1454
+ if (disposed || pinned || selectedTabId !== null) return;
1455
+ if (liveImg && liveImgTargetId === targetId) return;
1456
+ const meta = pageMeta.get(targetId);
1457
+ if (!meta) return;
1458
+ currentActiveId = targetId;
1459
+ renderLiveMain({
1460
+ ...meta,
1461
+ targetId
1462
+ }, false);
1463
+ }, 0);
1464
+ }
1465
+ }
1466
+ };
1467
+ let reconnectFallbackTimer = null;
1468
+ const openStream = () => {
1469
+ if (disposed) return;
1470
+ fetch(WATCH_STATUS_ROUTE, { cache: "no-store" }).then((res) => res.ok ? res.json() : null).then(applyCaptureStatus).catch(() => {});
1471
+ try {
1472
+ if (sse) sse.close();
1473
+ } catch {}
1474
+ doConnected = false;
1475
+ sse = new EventSource("/api/bcdp/stream");
1476
+ sse.onopen = () => {
1477
+ doConnected = true;
1478
+ };
1479
+ sse.addEventListener("frame", (ev) => {
1480
+ try {
1481
+ const m = JSON.parse(ev.data);
1482
+ if (!m || !m.targetId || !m.data) return;
1483
+ if (Number.isFinite(m.vw) && Number.isFinite(m.vh)) {
1484
+ const cur = pageMeta.get(m.targetId) || { targetId: m.targetId };
1485
+ pageMeta.set(m.targetId, {
1486
+ ...cur,
1487
+ vw: m.vw,
1488
+ vh: m.vh
1489
+ });
1490
+ }
1491
+ applyFrame(m.targetId, `data:image/jpeg;base64,${m.data}`, m.vw, m.vh);
1492
+ } catch {}
1493
+ });
1494
+ sse.addEventListener("spaces", (ev) => {
1495
+ if (disposed) return;
1496
+ try {
1497
+ const list = JSON.parse(ev.data);
1498
+ if (Array.isArray(list)) renderSpaces(list);
1499
+ } catch {}
1500
+ });
1501
+ sse.addEventListener("capture-status", (ev) => {
1502
+ try {
1503
+ applyCaptureStatus(JSON.parse(ev.data));
1504
+ } catch {}
1505
+ });
1506
+ sse.onerror = () => {
1507
+ doConnected = false;
1508
+ if (reconnectFallbackTimer) return;
1509
+ reconnectFallbackTimer = window.setTimeout(() => {
1510
+ reconnectFallbackTimer = null;
1511
+ if (disposed) return;
1512
+ refresh();
1513
+ }, 1500);
1514
+ };
1515
+ };
1516
+ let doConnected = false;
1517
+ const DRAG_KEY = "dsh.ego.watch.pos";
1518
+ const DRAG_PANEL_KEY = "dsh.ego.watch.panelPos";
1519
+ const FAB_W = 48, FAB_H = 48;
1520
+ const PANEL_W = 408, PANEL_GAP = 8;
1521
+ const loadPos = (key) => {
1522
+ try {
1523
+ const s = JSON.parse(localStorage.getItem(key) || "null");
1524
+ if (s && Number.isFinite(s.x) && Number.isFinite(s.y)) return s;
1525
+ } catch {}
1526
+ return null;
1527
+ };
1528
+ let pos = loadPos(DRAG_KEY) || {
1529
+ x: window.innerWidth - 18 - FAB_W,
1530
+ y: window.innerHeight - 104 - FAB_H
1531
+ };
1532
+ let panelPos = loadPos(DRAG_PANEL_KEY);
1533
+ const clampFab = () => {
1534
+ const vw = window.innerWidth, vh = window.innerHeight;
1535
+ pos.x = Math.max(4, Math.min(vw - FAB_W - 4, pos.x));
1536
+ pos.y = Math.max(4, Math.min(vh - FAB_H - 4, pos.y));
1537
+ };
1538
+ const placeFab = () => {
1539
+ clampFab();
1540
+ fab.style.left = pos.x + "px";
1541
+ fab.style.top = pos.y + "px";
1542
+ };
1543
+ const placePanel = () => {
1544
+ panel.style.left = panelPos.x + "px";
1545
+ panel.style.top = panelPos.y + "px";
1546
+ };
1547
+ /** Position the panel against the ball: just above it (below when near
1548
+ * the top edge), clamped inside the viewport. */
1549
+ const snapPanelToFab = () => {
1550
+ const vw = window.innerWidth, vh = window.innerHeight;
1551
+ const pw = panel.classList.contains("open-drawer") ? 640 : PANEL_W;
1552
+ const ph = panel.offsetHeight > 0 ? panel.offsetHeight : Math.min(Math.round(vh * .7), 520);
1553
+ let px = pos.x + FAB_W - pw;
1554
+ let py = pos.y - ph - PANEL_GAP;
1555
+ if (py < 8) py = pos.y + FAB_H + PANEL_GAP;
1556
+ px = Math.max(8, Math.min(vw - pw - 8, px));
1557
+ py = Math.max(8, Math.min(vh - ph - 8, py));
1558
+ panelPos = {
1559
+ x: Math.round(px),
1560
+ y: Math.round(py)
1561
+ };
1562
+ placePanel();
1563
+ };
1564
+ placeFab();
1565
+ if (panelPos) placePanel();
1566
+ let suppressFabClick = false;
1567
+ /**
1568
+ * Make `el` drag the FAB or the panel (`which` = 'fab' | 'panel').
1569
+ * Movement under ~5px is treated as a click, so the FAB still toggles.
1570
+ * Interactive children (buttons/icons) never start a drag.
1571
+ */
1572
+ const makeDraggable = (el, which) => {
1573
+ const state = () => which === "fab" ? pos : panelPos;
1574
+ let sx = 0, sy = 0, bx = 0, by = 0, active = false, dragged = false;
1575
+ const down = (e) => {
1576
+ if (e.button !== 0) return;
1577
+ if (e.target && e.target.closest) {
1578
+ const hit = e.target.closest("button, a, input, [role=\"button\"]");
1579
+ if (hit && hit !== el) return;
1580
+ }
1581
+ active = true;
1582
+ dragged = false;
1583
+ sx = e.clientX;
1584
+ sy = e.clientY;
1585
+ const s = state();
1586
+ bx = s.x;
1587
+ by = s.y;
1588
+ try {
1589
+ el.setPointerCapture(e.pointerId);
1590
+ } catch {}
1591
+ el.classList.add("dsh-ego-dragging");
1592
+ e.preventDefault();
1593
+ };
1594
+ const move = (e) => {
1595
+ if (!active) return;
1596
+ const dx = e.clientX - sx, dy = e.clientY - sy;
1597
+ if (!dragged && Math.abs(dx) + Math.abs(dy) > 5) dragged = true;
1598
+ if (dragged) {
1599
+ const s = state();
1600
+ s.x = bx + dx;
1601
+ s.y = by + dy;
1602
+ which === "fab" ? placeFab() : placePanel();
1603
+ }
1604
+ };
1605
+ const up = (e) => {
1606
+ if (!active) return;
1607
+ active = false;
1608
+ el.classList.remove("dsh-ego-dragging");
1609
+ try {
1610
+ el.releasePointerCapture(e.pointerId);
1611
+ } catch {}
1612
+ if (dragged) {
1613
+ if (which === "fab") suppressFabClick = true;
1614
+ try {
1615
+ localStorage.setItem(which === "fab" ? DRAG_KEY : DRAG_PANEL_KEY, JSON.stringify(state()));
1616
+ } catch {}
1617
+ }
1618
+ };
1619
+ el.addEventListener("pointerdown", down);
1620
+ el.addEventListener("pointermove", move);
1621
+ el.addEventListener("pointerup", up);
1622
+ el.addEventListener("pointercancel", up);
1623
+ };
1624
+ makeDraggable(fab, "fab");
1625
+ makeDraggable(panel.querySelector("#dsh-ego-head"), "panel");
1626
+ const setOpen = (open) => {
1627
+ if (open) {
1628
+ panel.hidden = false;
1629
+ panel.classList.remove("dsh-ego-panel-hide");
1630
+ snapPanelToFab();
1631
+ panel.offsetHeight;
1632
+ panel.classList.add("dsh-ego-panel-open");
1633
+ fab.classList.add("on");
1634
+ refresh();
1635
+ openStream();
1636
+ if (currentActiveId) syncWatch(selectedTabId || currentActiveId);
1637
+ } else {
1638
+ panel.classList.remove("dsh-ego-panel-open");
1639
+ clearTimeout(panel._dshHideT);
1640
+ panel._dshHideT = setTimeout(() => {
1641
+ panel.classList.add("dsh-ego-panel-hide");
1642
+ panel.hidden = true;
1643
+ fab.classList.remove("on");
1644
+ }, 280);
1645
+ try {
1646
+ if (sse) sse.close();
1647
+ } catch {}
1648
+ sse = null;
1649
+ stopWatch(false);
1650
+ stopVideo();
1651
+ }
1652
+ try {
1653
+ localStorage.setItem(OPEN_KEY, open ? "1" : "0");
1654
+ } catch {}
1655
+ };
1656
+ fab.addEventListener("click", () => {
1657
+ if (suppressFabClick) {
1658
+ suppressFabClick = false;
1659
+ return;
1660
+ }
1661
+ setOpen(panel.hidden);
1662
+ });
1663
+ closeBtn.addEventListener("click", () => setOpen(false));
1664
+ refreshBtn.addEventListener("click", () => {
1665
+ refreshBtn.classList.add("spinning");
1666
+ window.setTimeout(() => refreshBtn.classList.remove("spinning"), 800);
1667
+ refresh();
1668
+ });
1669
+ historyBtn.addEventListener("click", () => setHistory(!historyOpen));
1670
+ const maybeShowLoginGuide = () => {
1671
+ if (disposed || dismissedGuides.login) return;
1672
+ const show = lastList.some((s) => s.url && !s.url.startsWith("about:")) && !captchaEl.classList.contains("show");
1673
+ loginEl.classList.toggle("show", show);
1674
+ loginNote.textContent = "";
1675
+ };
1676
+ const maybeShowCaptchaGuide = () => {
1677
+ if (disposed || dismissedGuides.captcha) return;
1678
+ const hit = lastList.find((s) => s.humanCheck && s.humanCheck.detected);
1679
+ const show = !!hit;
1680
+ captchaEl.classList.toggle("show", show);
1681
+ if (show && captchaKindEl) captchaKindEl.textContent = hit.humanCheck.kind || "captcha";
1682
+ };
1683
+ loginBtn.addEventListener("click", () => {
1684
+ (async () => {
1685
+ loginBtn.classList.add("saving");
1686
+ loginBtn.textContent = wt("loginSaving");
1687
+ try {
1688
+ const j = await (await fetch(FLUSH_ROUTE$1, {
1689
+ method: "POST",
1690
+ headers: { "content-type": "application/json" },
1691
+ body: "{}"
1692
+ })).json();
1693
+ if (j && j.ok) loginNote.textContent = wt("loginSaved", { n: j.total ?? "" });
1694
+ else loginNote.textContent = j?.error ? wt("loginNotConnected") : wt("loginFailed");
1695
+ } catch {
1696
+ loginNote.textContent = wt("loginFailed");
1697
+ } finally {
1698
+ loginBtn.classList.remove("saving");
1699
+ loginBtn.textContent = wt("loginBtn");
1700
+ }
1701
+ })();
1702
+ });
1703
+ document.body.appendChild(fab);
1704
+ document.body.appendChild(panel);
1705
+ try {
1706
+ localStorage.removeItem(OPEN_KEY);
1707
+ } catch {}
1708
+ panel.hidden = true;
1709
+ fab.classList.remove("on");
1710
+ refresh();
1711
+ const onVisibility = () => {
1712
+ if (document.visibilityState !== "hidden" && !panel.hidden) {
1713
+ if (!sse) openStream();
1714
+ syncWatch(selectedTabId || currentActiveId);
1715
+ }
1716
+ };
1717
+ document.addEventListener("visibilitychange", onVisibility);
1718
+ return () => {
1719
+ disposed = true;
1720
+ if (liveFlushRaf != null) try {
1721
+ window.cancelAnimationFrame(liveFlushRaf);
1722
+ } catch {}
1723
+ if (followTimer) window.clearTimeout(followTimer);
1724
+ if (reconnectFallbackTimer) window.clearTimeout(reconnectFallbackTimer);
1725
+ document.removeEventListener("visibilitychange", onVisibility);
1726
+ if (watchRenewTimer) window.clearInterval(watchRenewTimer);
1727
+ if (watchStopTimer) window.clearTimeout(watchStopTimer);
1728
+ stopWatch(true);
1729
+ stopVideo();
1730
+ keyboardProxy.dispose();
1731
+ try {
1732
+ pickCtl.disable();
1733
+ } catch {}
1734
+ try {
1735
+ if (sse) sse.close();
1736
+ } catch {}
1737
+ fab.remove();
1738
+ panel.remove();
1739
+ style.remove();
1740
+ };
1741
+ }
1742
+ var INPUT_ROUTE = "/api/bcdp/input";
1743
+ var FLUSH_ROUTE = "/api/bcdp/flush";
1744
+ var FRAME_FOLLOW_MIN_MS = 350;
1745
+ var TAB_CSS = `
1746
+ .dsh-ego-side-root {
1747
+ display: flex; flex-direction: column; height: 100%; min-height: 0;
1748
+ overflow: hidden; color: inherit; background: transparent;
1749
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;
1750
+ }
1751
+ .dsh-ego-side-root * { box-sizing: border-box; }
1752
+
1753
+ .dsh-ego-side-head {
1754
+ display: flex; align-items: center; gap: 4px; padding: 8px 10px;
1755
+ border-bottom: 1px solid rgba(128,128,128,.18); flex-shrink: 0;
1756
+ }
1757
+ .dsh-ego-side-title {
1758
+ flex: 1; font-size: 12.5px; font-weight: 600; letter-spacing: .2px;
1759
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
1760
+ display: flex; align-items: center; gap: 5px; opacity: .85;
1761
+ }
1762
+ .dsh-ego-side-title svg { width: 14px; height: 14px; flex-shrink: 0; }
1763
+ .dsh-ego-side-iconbtn {
1764
+ background: transparent; border: none; cursor: pointer;
1765
+ width: 26px; height: 26px; border-radius: 7px; padding: 0;
1766
+ display: flex; align-items: center; justify-content: center;
1767
+ color: inherit; opacity: .6;
1768
+ transition: background .15s ease, opacity .15s ease;
1769
+ }
1770
+ .dsh-ego-side-iconbtn:hover { background: rgba(128,128,128,.18); opacity: 1; }
1771
+ .dsh-ego-side-iconbtn.off { opacity: .4; }
1772
+ .dsh-ego-side-iconbtn.spinning svg { animation: dsh-ego-side-spin .7s linear infinite; }
1773
+ @keyframes dsh-ego-side-spin { to { transform: rotate(360deg); } }
1774
+
1775
+ /* ---- guide strips (login / captcha) ---- */
1776
+ .dsh-ego-side-login, .dsh-ego-side-captcha {
1777
+ display: flex; align-items: center; gap: 7px; margin: 0 10px 7px; padding: 6px 9px;
1778
+ border-radius: 8px; font-size: 11px; line-height: 1.4;
1779
+ }
1780
+ .dsh-ego-side-login {
1781
+ border: 1px solid rgba(255,214,10,.3); background: rgba(255,214,10,.1);
1782
+ }
1783
+ .dsh-ego-side-captcha {
1784
+ border: 1px solid rgba(255,69,58,.4); background: rgba(255,69,58,.13);
1785
+ }
1786
+ .dsh-ego-side-login .dsh-ego-side-login-txt { flex: 1; min-width: 0; }
1787
+ .dsh-ego-side-login .dsh-ego-side-login-txt b { color: #ffd60a; }
1788
+ .dsh-ego-side-login-btn {
1789
+ flex: none; background: #0a84ff; color: #fff; border: none; border-radius: 7px;
1790
+ font-size: 10.5px; padding: 4px 9px; cursor: pointer; white-space: nowrap;
1791
+ transition: background .15s ease;
1792
+ }
1793
+ .dsh-ego-side-login-btn:hover { background: #338cff; }
1794
+ .dsh-ego-side-login-btn.saving { opacity: .55; pointer-events: none; }
1795
+ .dsh-ego-side-login-note { flex: none; font-size: 10px; opacity: .6; white-space: nowrap; }
1796
+ .dsh-ego-side-captcha-txt { flex: 1; min-width: 0; }
1797
+ .dsh-ego-side-captcha-txt b { color: #ff6961; }
1798
+ .dsh-ego-side-captcha-kind {
1799
+ flex: none; font-size: 9.5px; padding: 2px 7px; border-radius: 999px;
1800
+ background: rgba(255,255,255,.15); text-transform: uppercase; letter-spacing: .3px;
1801
+ }
1802
+
1803
+ /* ---- tab strip: frosted pills ---- */
1804
+ .dsh-ego-side-tabs {
1805
+ display: flex; gap: 5px; padding: 7px 10px; flex-shrink: 0;
1806
+ border-bottom: 1px solid rgba(128,128,128,.12);
1807
+ overflow-x: auto; scrollbar-width: thin;
1808
+ }
1809
+ .dsh-ego-side-tabs:empty { display: none; }
1810
+ .dsh-ego-side-tab {
1811
+ display: inline-flex; align-items: center; gap: 5px; max-width: 160px;
1812
+ white-space: nowrap; padding: 4px 10px; border-radius: 999px; cursor: pointer;
1813
+ font-size: 11px; flex-shrink: 0;
1814
+ border: 1px solid rgba(128,128,128,.2); background: rgba(128,128,128,.12);
1815
+ opacity: .7; transition: background .15s, opacity .15s, border-color .15s;
1816
+ }
1817
+ .dsh-ego-side-tab > .dsh-ego-side-tabtxt { overflow: hidden; text-overflow: ellipsis; }
1818
+ .dsh-ego-side-tab:hover { opacity: 1; background: rgba(128,128,128,.2); }
1819
+ .dsh-ego-side-tab.active {
1820
+ background: #0a84ff; color: #fff; border-color: transparent; opacity: 1;
1821
+ box-shadow: 0 2px 8px rgba(10,132,255,.3);
1822
+ }
1823
+ .dsh-ego-side-tabdot { width: 6px; height: 6px; border-radius: 50%; background: currentColor; opacity: .5; flex-shrink: 0; }
1824
+ .dsh-ego-side-tab.active .dsh-ego-side-tabdot { background: #fff; opacity: 1; }
1825
+ .dsh-ego-side-tabclose {
1826
+ flex-shrink: 0; width: 13px; height: 13px; line-height: 12px; text-align: center;
1827
+ border-radius: 50%; font-size: 11px; opacity: .5; margin-left: 1px;
1828
+ }
1829
+ .dsh-ego-side-tabclose:hover { background: rgba(255,255,255,.2); color: #ff453a; opacity: 1; }
1830
+
1831
+ /* ---- main body ---- */
1832
+ .dsh-ego-side-body { flex: 1; min-height: 0; overflow-y: auto; padding: 10px; }
1833
+ .dsh-ego-side-empty { padding: 20px 12px; text-align: center; font-size: 12px; opacity: .5; line-height: 1.7; }
1834
+
1835
+ .dsh-ego-side-liveview { display: flex; flex-direction: column; gap: 7px; min-height: 60px; overflow: hidden; }
1836
+ .dsh-ego-side-livebadge {
1837
+ font-size: 10.5px; opacity: .6; letter-spacing: .2px;
1838
+ display: flex; align-items: center; gap: 6px; flex-wrap: wrap;
1839
+ }
1840
+ .dsh-ego-side-state-dot {
1841
+ display: inline-block; width: 7px; height: 7px; border-radius: 50%;
1842
+ background: #30d158; box-shadow: 0 0 5px #30d15888; flex-shrink: 0;
1843
+ animation: dsh-ego-side-breathe 2.4s ease-in-out infinite;
1844
+ }
1845
+ .dsh-ego-side-state-dot.busy { background: #30d158; box-shadow: 0 0 6px #30d158bb; animation: none; }
1846
+ .dsh-ego-side-state-dot.pin { background: #0a84ff; box-shadow: 0 0 5px #0a84ff88; animation: none; }
1847
+ @keyframes dsh-ego-side-breathe {
1848
+ 0%, 100% { box-shadow: 0 0 2px #30d15822; opacity: .5; }
1849
+ 50% { box-shadow: 0 0 10px #30d158ee; opacity: 1; }
1850
+ }
1851
+ .dsh-ego-side-back {
1852
+ background: rgba(128,128,128,.18); border: 1px solid rgba(128,128,128,.2);
1853
+ border-radius: 6px; cursor: pointer; font-size: 10.5px; padding: 2px 8px;
1854
+ display: inline-flex; align-items: center; gap: 3px;
1855
+ transition: background .15s ease; color: inherit;
1856
+ }
1857
+ .dsh-ego-side-back:hover { background: rgba(128,128,128,.3); }
1858
+ .dsh-ego-side-back.dsh-ego-pick-on { background: rgba(56,189,248,.28); color: #0ea5e9; }
1859
+ .dsh-ego-side-liveimg {
1860
+ width: 100%; border-radius: 9px; display: block;
1861
+ max-height: 50vh; object-fit: contain;
1862
+ border: 1px solid rgba(128,128,128,.2); background: #000;
1863
+ user-select: none; -webkit-user-select: none; touch-action: none;
1864
+ will-change: transform; cursor: grab;
1865
+ }
1866
+ .dsh-ego-side-livetitle { font-size: 12px; font-weight: 600; }
1867
+ .dsh-ego-side-liveurl { font-size: 10.5px; opacity: .55; word-break: break-all; }
1868
+ .dsh-ego-side-liveurl.dsh-ego-side-hint { color: #75c2ff; font-style: italic; font-weight: 500; opacity: 1; }
1869
+ .dsh-ego-side-hint { animation: dsh-ego-side-hint-in .2s ease; }
1870
+ @keyframes dsh-ego-side-hint-in { from { opacity: .3 } to { opacity: 1 } }
1871
+
1872
+ /* ---- history overlay (covers the body area) ---- */
1873
+ .dsh-ego-side-history {
1874
+ flex: 1; min-height: 0; display: flex; flex-direction: column;
1875
+ overflow: hidden;
1876
+ }
1877
+ .dsh-ego-side-historyhead {
1878
+ padding: 8px 10px; font-size: 11px; font-weight: 600; opacity: .6;
1879
+ display: flex; align-items: center; gap: 5px;
1880
+ border-bottom: 1px solid rgba(128,128,128,.1); flex-shrink: 0;
1881
+ }
1882
+ .dsh-ego-side-historyhead svg { width: 11px; height: 11px; }
1883
+ .dsh-ego-side-historylist { overflow-y: auto; padding: 5px; }
1884
+ .dsh-ego-side-hitem {
1885
+ display: flex; gap: 7px; align-items: center; padding: 5px; border-radius: 8px;
1886
+ cursor: pointer; transition: background .15s ease;
1887
+ }
1888
+ .dsh-ego-side-hitem:hover { background: rgba(128,128,128,.15); }
1889
+ .dsh-ego-side-hitem.active { background: rgba(10,132,255,.15); }
1890
+ .dsh-ego-side-hthumb {
1891
+ width: 52px; height: 38px; border-radius: 5px; object-fit: cover; background: #000;
1892
+ flex-shrink: 0; border: 1px solid rgba(128,128,128,.2);
1893
+ }
1894
+ .dsh-ego-side-hinfo { min-width: 0; flex: 1; }
1895
+ .dsh-ego-side-htitle { font-size: 10px; font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
1896
+ .dsh-ego-side-hurl { font-size: 9.5px; opacity: .5; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
1897
+ .dsh-ego-side-hactive { color: #30d158; font-size: 9.5px; }
1898
+ .dsh-ego-side-hnone { padding: 16px 8px; text-align: center; font-size: 10.5px; opacity: .4; }
1899
+ `;
1900
+ /**
1901
+ * M1.6 — quote a picked element into the conversation composer.
1902
+ * 2026-09-23 revision 2: NO auto-submit, ever. Elements from ONE page
1903
+ * accumulate into ONE dictionary block, wrapped like the image
1904
+ * attachments are — the block carries its source CDP connection
1905
+ * (endpoint + targetId) so the agent can find the element's DOM again
1906
+ * (backendNodeId is directly addressable via bcdp_cdp DOM.describeNode).
1907
+ * Format inside the draft:
1908
+ * [CDP-PICKS page="..." targetId="..." endpoint="..."]
1909
+ * {"cdpEndpoint":..., "targetId":..., "pageUrl":..., "elements":[{n,backendNodeId,tag,id,name,focusable,describe}]}
1910
+ * [/CDP-PICKS]
1911
+ */
1912
+ function deliverPickToConversation(ctx, element, action) {
1913
+ try {
1914
+ var describe = element && typeof element.describe === "string" ? element.describe : "";
1915
+ if (describe === "") return {
1916
+ ok: false,
1917
+ code: "empty-describe"
1918
+ };
1919
+ if (action !== "quote") return {
1920
+ ok: false,
1921
+ code: "bad-action"
1922
+ };
1923
+ var sessionId = ctx.sessions.list.getSnapshot().current;
1924
+ if (!sessionId) return {
1925
+ ok: false,
1926
+ code: "no-active-session"
1927
+ };
1928
+ var actx = ctx.sessions.scope(sessionId);
1929
+ if (!actx) return {
1930
+ ok: false,
1931
+ code: "no-session-scope"
1932
+ };
1933
+ var conversation = ctx.get("conversation");
1934
+ if (!conversation || !conversation.input) return {
1935
+ ok: false,
1936
+ code: "no-conversation-service"
1937
+ };
1938
+ var input = conversation.input.for(actx);
1939
+ if (!input || typeof input.setDraft !== "function") return {
1940
+ ok: false,
1941
+ code: "no-input-facade"
1942
+ };
1943
+ var snap = input.state && input.state.getSnapshot ? input.state.getSnapshot() : null;
1944
+ var draft = snap && typeof snap.draft === "string" ? snap.draft : "";
1945
+ var src = element.source || {
1946
+ endpoint: "",
1947
+ targetId: "",
1948
+ pageUrl: "",
1949
+ pageTitle: ""
1950
+ };
1951
+ var entry = {
1952
+ backendNodeId: element.backendNodeId,
1953
+ tag: element.tag,
1954
+ id: element.id,
1955
+ name: element.name,
1956
+ focusable: !!element.keyboardFocusable,
1957
+ describe
1958
+ };
1959
+ var re = /\[CDP-PICKS[^\]]*\]\n([\s\S]*?)\n\[\/CDP-PICKS\]/g, found = null, mm;
1960
+ while ((mm = re.exec(draft)) !== null) try {
1961
+ var obj = JSON.parse(mm[1]);
1962
+ if (obj && obj.targetId === src.targetId && obj.cdpEndpoint === src.endpoint) {
1963
+ found = mm;
1964
+ mm[0].split("\n")[0];
1965
+ break;
1966
+ }
1967
+ } catch (e) {}
1968
+ var elements = [Object.assign({ n: 1 }, entry)];
1969
+ var page = {
1970
+ cdpEndpoint: src.endpoint,
1971
+ targetId: src.targetId,
1972
+ pageUrl: src.pageUrl,
1973
+ pageTitle: src.pageTitle
1974
+ };
1975
+ if (found) try {
1976
+ var prev = JSON.parse(found[1]);
1977
+ var list = prev && prev.elements ? prev.elements : [];
1978
+ var maxN = 0;
1979
+ for (var k = 0; k < list.length; k++) if (list[k].n > maxN) maxN = list[k].n;
1980
+ entry.n = maxN + 1;
1981
+ list.push(entry);
1982
+ page.elements = list;
1983
+ draft = draft.slice(0, found.index) + draft.slice(found.index + found[0].length);
1984
+ } catch (e) {}
1985
+ if (!page.elements) page.elements = elements;
1986
+ var block = "[CDP-PICKS page=\"" + String(src.pageTitle || src.pageUrl || "").replace(/"/g, "'") + "\" targetId=\"" + src.targetId + "\" endpoint=\"" + src.endpoint + "\"]\n" + JSON.stringify(page, null, 2) + "\n[/CDP-PICKS]";
1987
+ draft = draft ? draft + (draft.charAt(draft.length - 1) === "\n" ? "" : "\n") + block : block;
1988
+ input.setDraft(draft);
1989
+ return {
1990
+ ok: true,
1991
+ code: "drafted",
1992
+ count: page.elements.length
1993
+ };
1994
+ } catch (err) {
1995
+ return {
1996
+ ok: false,
1997
+ code: "deliver-failed",
1998
+ message: String(err && err.message || err)
1999
+ };
2000
+ }
2001
+ }
2002
+ function createPickControl(onState, deliver) {
2003
+ var enabled = false;
2004
+ var timer = null;
2005
+ var seenPicks = 0;
2006
+ var deliveredPicks = -1;
2007
+ var request = null;
2008
+ function emit(pick, message) {
2009
+ onState(pick, message);
2010
+ }
2011
+ function stopPolling() {
2012
+ if (timer) {
2013
+ window.clearInterval(timer);
2014
+ timer = null;
2015
+ }
2016
+ }
2017
+ function post(enabledNow, targetId) {
2018
+ var body = { enabled: enabledNow };
2019
+ if (targetId) body.targetId = targetId;
2020
+ return fetch("/api/bcdp/pick", {
2021
+ method: "POST",
2022
+ headers: { "content-type": "application/json" },
2023
+ body: JSON.stringify(body)
2024
+ }).then(function(r) {
2025
+ return r.json().catch(function() {
2026
+ return null;
2027
+ });
2028
+ }).catch(function() {
2029
+ return null;
2030
+ });
2031
+ }
2032
+ function applyState(state) {
2033
+ if (!state || typeof state !== "object") return;
2034
+ if (state.lastPick && state.lastAction && state.picks !== deliveredPicks && typeof deliver === "function") {
2035
+ deliveredPicks = state.picks;
2036
+ var result = deliver(state.lastPick, state.lastAction);
2037
+ if (result && result.ok) emit("picked", wt("pickQuoted") + " (" + result.count + ")");
2038
+ else emit("failed", wt("pickDeliverFailed") + (result && result.code ? " (" + result.code + ")" : ""));
2039
+ }
2040
+ if (state.picks !== seenPicks) seenPicks = state.picks;
2041
+ if (state.enabled) emit("on", state.code === "picking" ? wt("picking") : state.message || wt("picking"));
2042
+ else if (state.code === "picked") emit("picked", state.lastPick ? state.lastPick.describe : wt("picked"));
2043
+ else if (state.code && state.code !== "idle" && state.code !== "delivered") {
2044
+ emit("failed", state.message || state.code);
2045
+ enabled = false;
2046
+ stopPolling();
2047
+ } else if (!state.enabled) {
2048
+ enabled = false;
2049
+ stopPolling();
2050
+ if (state.code === "idle" && !(state.lastPick && state.lastAction)) emit("off", "");
2051
+ }
2052
+ }
2053
+ function pollOnce() {
2054
+ if (request) return;
2055
+ request = fetch("/api/bcdp/pick").then(function(r) {
2056
+ return r.json().catch(function() {
2057
+ return null;
2058
+ });
2059
+ }).catch(function() {
2060
+ return null;
2061
+ });
2062
+ request.then(function(res) {
2063
+ request = null;
2064
+ if (res && res.ok !== false && res.state) applyState(res.state);
2065
+ else {
2066
+ enabled = false;
2067
+ stopPolling();
2068
+ emit("off", "");
2069
+ }
2070
+ });
2071
+ }
2072
+ function toggle(targetId) {
2073
+ if (enabled) {
2074
+ disable();
2075
+ return;
2076
+ }
2077
+ if (!targetId) {
2078
+ emit("failed", wt("noActivePages"));
2079
+ return;
2080
+ }
2081
+ post(true, targetId).then(function(res) {
2082
+ var state = res && res.ok !== false ? res.state : null;
2083
+ if (!state || state.enabled !== true) {
2084
+ emit("failed", state && state.message || res && res.error || wt("pickFailed"));
2085
+ return;
2086
+ }
2087
+ enabled = true;
2088
+ seenPicks = state.picks || 0;
2089
+ deliveredPicks = state.lastAction ? state.picks || 0 : (state.picks || 0) - 1;
2090
+ emit("on", wt("picking"));
2091
+ stopPolling();
2092
+ timer = window.setInterval(pollOnce, 1e3);
2093
+ });
2094
+ }
2095
+ function clickAt(x, y, targetId) {
2096
+ if (!enabled || !targetId) return;
2097
+ fetch("/api/bcdp/pick/click", {
2098
+ method: "POST",
2099
+ headers: { "content-type": "application/json" },
2100
+ body: JSON.stringify({
2101
+ targetId,
2102
+ x,
2103
+ y
2104
+ })
2105
+ }).then(function(r) {
2106
+ return r.json().catch(function() {
2107
+ return null;
2108
+ });
2109
+ }).catch(function() {
2110
+ return null;
2111
+ }).then(function(res) {
2112
+ if (res && res.ok !== false && res.state) applyState(res.state);
2113
+ else emit("failed", res && (res.error || res.code) || wt("pickFailed"));
2114
+ });
2115
+ }
2116
+ function disable() {
2117
+ var wasEnabled = enabled;
2118
+ enabled = false;
2119
+ stopPolling();
2120
+ emit("off", "");
2121
+ if (wasEnabled) post(false, "");
2122
+ }
2123
+ return {
2124
+ toggle,
2125
+ disable,
2126
+ clickAt,
2127
+ isEnabled: function() {
2128
+ return enabled;
2129
+ }
2130
+ };
2131
+ }
2132
+ function LivePreviewController(ctx) {
2133
+ this.ctx = ctx;
2134
+ this.store = createSnapshotStore(this._initialState());
2135
+ this.frameCache = /* @__PURE__ */ new Map();
2136
+ this.pageMeta = /* @__PURE__ */ new Map();
2137
+ this.lastList = [];
2138
+ this.pinned = null;
2139
+ this.currentActiveId = null;
2140
+ this.agentActiveId = null;
2141
+ this.selectedTabId = null;
2142
+ this.zoomState = {
2143
+ scale: 1,
2144
+ tx: 0,
2145
+ ty: 0
2146
+ };
2147
+ this.liveCount = 0;
2148
+ this.disposed = false;
2149
+ this.visible = false;
2150
+ this.clientId = "sidebar-" + Math.random().toString(36).slice(2);
2151
+ this.watchStarted = false;
2152
+ this.watchTargetId = null;
2153
+ this.watchRenewTimer = null;
2154
+ this.watchStopTimer = null;
2155
+ this.watchRequest = null;
2156
+ this.backend = "cdp";
2157
+ this.streamGeneration = 0;
2158
+ this.streamState = "idle";
2159
+ this.streamMessage = "";
2160
+ this.streamMime = "video/mp4; codecs=\"avc1.42E01E\"";
2161
+ this.liveVideo = null;
2162
+ this.videoCleanup = null;
2163
+ this.documentVisible = document.visibilityState !== "hidden";
2164
+ this.onDocumentVisibility = this._handleDocumentVisibility.bind(this);
2165
+ this.sse = null;
2166
+ this.reconnectFallbackTimer = null;
2167
+ this.lastSawActive = false;
2168
+ this.lastFrameAt = 0;
2169
+ this.followTimer = null;
2170
+ this.pendingLiveFrame = null;
2171
+ this.liveFlushRaf = null;
2172
+ this.liveImg = null;
2173
+ this.liveImgTargetId = null;
2174
+ this.wiringStale = false;
2175
+ this._lastUnwiredAt = 0;
2176
+ this._wiredRecomputeQueued = false;
2177
+ this.historyOpen = false;
2178
+ this._zoomHint = null;
2179
+ this._zoomHintTimer = null;
2180
+ this._pointerState = null;
2181
+ var self = this;
2182
+ this.keyboardProxy = createKeyboardProxy(function(targetId, type, params) {
2183
+ self.sendInput(targetId, type, params);
2184
+ });
2185
+ this.dismissedGuides = {
2186
+ login: false,
2187
+ captcha: false
2188
+ };
2189
+ this._pick = "off";
2190
+ this._pickMessage = "";
2191
+ this._pickTargetId = null;
2192
+ this.pickControl = createPickControl(function(pick, message) {
2193
+ self._setPickState(pick, message);
2194
+ }, function(el, a) {
2195
+ return deliverPickToConversation(ctx, el, a);
2196
+ });
2197
+ }
2198
+ LivePreviewController.prototype._initialState = function() {
2199
+ return {
2200
+ spaces: [],
2201
+ pinned: null,
2202
+ selectedTabId: null,
2203
+ currentTargetId: null,
2204
+ currentSpace: null,
2205
+ liveCount: 0,
2206
+ busy: false,
2207
+ showLoginGuide: false,
2208
+ captchaKind: null,
2209
+ historyOpen: false,
2210
+ zoomHint: null,
2211
+ wiringStale: false,
2212
+ backend: "cdp",
2213
+ streamState: "idle",
2214
+ streamMessage: "",
2215
+ streamGeneration: 0,
2216
+ streamMime: "video/mp4; codecs=\"avc1.42E01E\"",
2217
+ pick: "off",
2218
+ pickMessage: ""
2219
+ };
2220
+ };
2221
+ LivePreviewController.prototype.subscribe = function(cb) {
2222
+ return this.store.subscribe(cb);
2223
+ };
2224
+ LivePreviewController.prototype.getSnapshot = function() {
2225
+ return this.store.getSnapshot();
2226
+ };
2227
+ LivePreviewController.prototype._setPickState = function(pick, message) {
2228
+ this._pick = pick;
2229
+ this._pickMessage = message || "";
2230
+ var self = this;
2231
+ this.store.update(function(s) {
2232
+ s.pick = self._pick;
2233
+ s.pickMessage = self._pickMessage;
2234
+ });
2235
+ };
2236
+ LivePreviewController.prototype._recompute = function() {
2237
+ var hasPage = this.lastList.some(function(s) {
2238
+ return s.url && !s.url.startsWith("about:");
2239
+ });
2240
+ var captchaHit = this.lastList.find(function(s) {
2241
+ return s.humanCheck && s.humanCheck.detected;
2242
+ });
2243
+ var self = this;
2244
+ var currentSpace = null;
2245
+ var currentTargetId = null;
2246
+ if (this.pinned) {
2247
+ currentSpace = this.pinned;
2248
+ currentTargetId = this.pinned.targetId;
2249
+ } else if (this.selectedTabId !== null) {
2250
+ currentSpace = this.lastList.find(function(s) {
2251
+ return s.targetId === self.selectedTabId;
2252
+ }) || null;
2253
+ currentTargetId = this.selectedTabId;
2254
+ if (currentSpace && !currentSpace.thumbnail) {
2255
+ var cached = this.frameCache.get(currentTargetId);
2256
+ if (cached) currentSpace = Object.assign({}, currentSpace, { thumbnail: cached });
2257
+ }
2258
+ } else {
2259
+ var activeMarked = this.lastList.find(function(s) {
2260
+ return s.active === true;
2261
+ });
2262
+ if (!activeMarked && this.lastList.length > 0) activeMarked = this.lastList.slice().sort(function(a, b) {
2263
+ return (b.lastActive || 0) - (a.lastActive || 0);
2264
+ })[0];
2265
+ if (activeMarked) {
2266
+ currentSpace = Object.assign({}, activeMarked);
2267
+ currentTargetId = activeMarked.targetId;
2268
+ if (!currentSpace.thumbnail) {
2269
+ var cached2 = this.frameCache.get(currentTargetId);
2270
+ if (cached2) currentSpace.thumbnail = cached2;
2271
+ }
2272
+ }
2273
+ }
2274
+ this.currentActiveId = currentTargetId;
2275
+ this.wiringStale = currentTargetId != null && this.liveImgTargetId !== currentTargetId;
2276
+ var showLogin = hasPage && !captchaHit && !this.dismissedGuides.login;
2277
+ var captchaKind = captchaHit && !this.dismissedGuides.captcha ? captchaHit.humanCheck.kind || "captcha" : null;
2278
+ if (this.pickControl.isEnabled() && currentTargetId !== this._pickTargetId) this.togglePick();
2279
+ this.store.update(function(s) {
2280
+ s.spaces = self.lastList;
2281
+ s.pinned = self.pinned;
2282
+ s.selectedTabId = self.selectedTabId;
2283
+ s.currentTargetId = currentTargetId;
2284
+ s.currentSpace = currentSpace;
2285
+ s.liveCount = self.liveCount;
2286
+ s.busy = self.lastSawActive;
2287
+ s.showLoginGuide = showLogin;
2288
+ s.captchaKind = captchaKind;
2289
+ s.historyOpen = self.historyOpen;
2290
+ s.zoomHint = self._zoomHint;
2291
+ s.wiringStale = self.wiringStale;
2292
+ s.backend = self.backend;
2293
+ s.streamState = self.streamState;
2294
+ s.streamMessage = self.streamMessage;
2295
+ s.streamGeneration = self.streamGeneration;
2296
+ s.streamMime = self.streamMime;
2297
+ s.pick = self._pick;
2298
+ s.pickMessage = self._pickMessage;
2299
+ });
2300
+ this._syncWatch(currentTargetId);
2301
+ };
2302
+ LivePreviewController.prototype.start = function() {
2303
+ document.addEventListener("visibilitychange", this.onDocumentVisibility);
2304
+ this._recompute();
2305
+ if (this.visible) {
2306
+ this.refresh();
2307
+ this.openStream();
2308
+ }
2309
+ };
2310
+ LivePreviewController.prototype.togglePick = function() {
2311
+ var targetId = this.currentActiveId;
2312
+ if (this.pickControl.isEnabled()) {
2313
+ this._pickTargetId = null;
2314
+ this.pickControl.toggle(targetId);
2315
+ return;
2316
+ }
2317
+ this._pickTargetId = targetId;
2318
+ this.pickControl.toggle(targetId);
2319
+ };
2320
+ LivePreviewController.prototype.dispose = function() {
2321
+ this.keyboardProxy.dispose();
2322
+ this.disposed = true;
2323
+ try {
2324
+ this.pickControl.disable();
2325
+ } catch (e) {}
2326
+ if (this.liveFlushRaf != null) try {
2327
+ window.cancelAnimationFrame(this.liveFlushRaf);
2328
+ } catch (e) {}
2329
+ if (this.followTimer) window.clearTimeout(this.followTimer);
2330
+ if (this.reconnectFallbackTimer) window.clearTimeout(this.reconnectFallbackTimer);
2331
+ if (this._zoomHintTimer) window.clearTimeout(this._zoomHintTimer);
2332
+ document.removeEventListener("visibilitychange", this.onDocumentVisibility);
2333
+ if (this.watchRenewTimer) window.clearInterval(this.watchRenewTimer);
2334
+ if (this.watchStopTimer) window.clearTimeout(this.watchStopTimer);
2335
+ this._stopWatch(true);
2336
+ this._destroyVideo();
2337
+ this.closeStream();
2338
+ };
2339
+ LivePreviewController.prototype._handleDocumentVisibility = function() {
2340
+ this.documentVisible = document.visibilityState !== "hidden";
2341
+ if (this.documentVisible && this.visible) {
2342
+ this.refresh();
2343
+ if (!this.sse) this.openStream();
2344
+ this._syncWatch(this.currentActiveId);
2345
+ }
2346
+ };
2347
+ LivePreviewController.prototype.setVisible = function(v) {
2348
+ this.visible;
2349
+ this.visible = v;
2350
+ if (v) {
2351
+ this.refresh();
2352
+ this.openStream();
2353
+ this._syncWatch(this.currentActiveId);
2354
+ } else {
2355
+ this.closeStream();
2356
+ this._stopWatch(false);
2357
+ this._destroyVideo();
2358
+ }
2359
+ };
2360
+ LivePreviewController.prototype._requestWatch = function(route, body) {
2361
+ if (this.watchRequest) return null;
2362
+ var self = this;
2363
+ this.watchRequest = postJson(route, body).finally(function() {
2364
+ self.watchRequest = null;
2365
+ });
2366
+ return this.watchRequest;
2367
+ };
2368
+ LivePreviewController.prototype._applyCaptureStatus = function(status) {
2369
+ if (!status || typeof status !== "object") return;
2370
+ if (Number.isFinite(status.generation) && status.generation < this.streamGeneration) return;
2371
+ if (status.generation === this.streamGeneration && this.streamState === "streaming" && status.state === "starting") return;
2372
+ var nextBackend = status.backend || this.backend;
2373
+ var nextGeneration = status.generation ?? this.streamGeneration;
2374
+ var nextState = status.state || this.streamState;
2375
+ var generationChanged = this.streamGeneration !== nextGeneration;
2376
+ this.backend = nextBackend;
2377
+ this.streamState = nextState;
2378
+ this.streamMessage = status.message || status.code || "";
2379
+ this.streamGeneration = nextGeneration;
2380
+ this.streamMime = status.mime || this.streamMime;
2381
+ if (generationChanged || this.backend !== "ffmpeg") this._destroyVideo();
2382
+ this._recompute();
2383
+ };
2384
+ LivePreviewController.prototype._syncWatch = function(targetId) {
2385
+ if (this.disposed || !this.visible || !targetId) return;
2386
+ var self = this;
2387
+ if (this.watchStopTimer) {
2388
+ window.clearTimeout(this.watchStopTimer);
2389
+ this.watchStopTimer = null;
2390
+ }
2391
+ var route = this.watchStarted ? WATCH_SWITCH_ROUTE : WATCH_START_ROUTE;
2392
+ if (this.watchStarted && this.watchTargetId === targetId) return;
2393
+ var body = {
2394
+ clientId: this.clientId,
2395
+ targetId
2396
+ };
2397
+ var request = this._requestWatch(route, body);
2398
+ if (!request) {
2399
+ this.watchRequest.finally(function() {
2400
+ self._syncWatch(targetId);
2401
+ });
2402
+ return;
2403
+ }
2404
+ request.then(function(status) {
2405
+ self.watchStarted = status && status.ok !== false;
2406
+ self.watchTargetId = status && status.targetId || targetId;
2407
+ if (self.watchTargetId !== targetId) {
2408
+ self.selectedTabId = null;
2409
+ self.currentActiveId = self.watchTargetId;
2410
+ }
2411
+ self._applyCaptureStatus(status);
2412
+ if (!self.visible) self._stopWatch(true);
2413
+ }).catch(function() {});
2414
+ if (!this.watchRenewTimer) this.watchRenewTimer = window.setInterval(function() {
2415
+ if (self.visible && self.watchTargetId) {
2416
+ var renewal = self._requestWatch(WATCH_START_ROUTE, {
2417
+ clientId: self.clientId,
2418
+ targetId: self.watchTargetId
2419
+ });
2420
+ if (renewal) renewal.then(function(status) {
2421
+ self._applyCaptureStatus(status);
2422
+ }).catch(function() {});
2423
+ }
2424
+ }, 5e3);
2425
+ };
2426
+ LivePreviewController.prototype._stopWatch = function(immediate) {
2427
+ var self = this;
2428
+ if (this.watchRenewTimer) {
2429
+ window.clearInterval(this.watchRenewTimer);
2430
+ this.watchRenewTimer = null;
2431
+ }
2432
+ var stop = function() {
2433
+ self.watchStopTimer = null;
2434
+ self.watchStarted = false;
2435
+ self.watchTargetId = null;
2436
+ postJson(WATCH_STOP_ROUTE, { clientId: self.clientId }).catch(function() {});
2437
+ };
2438
+ if (immediate) stop();
2439
+ else {
2440
+ if (this.watchStopTimer) window.clearTimeout(this.watchStopTimer);
2441
+ this.watchStopTimer = window.setTimeout(stop, 1500);
2442
+ }
2443
+ };
2444
+ LivePreviewController.prototype._destroyVideo = function() {
2445
+ if (this.videoCleanup) try {
2446
+ this.videoCleanup();
2447
+ } catch (e) {}
2448
+ this.videoCleanup = null;
2449
+ this.liveVideo = null;
2450
+ };
2451
+ LivePreviewController.prototype.setLiveVideo = function(video, targetId) {
2452
+ this._destroyVideo();
2453
+ this.liveVideo = video;
2454
+ this.liveImg = video;
2455
+ this.liveImgTargetId = targetId;
2456
+ if (!video || this.backend !== "ffmpeg" || this.streamState !== "streaming") return;
2457
+ var self = this;
2458
+ this.videoCleanup = createMsePlayer(video, this.streamGeneration, this.streamMime, function(message) {
2459
+ self.streamState = "failed";
2460
+ self.streamMessage = message;
2461
+ self._recompute();
2462
+ });
2463
+ };
2464
+ LivePreviewController.prototype.setLiveImg = function(img, targetId) {
2465
+ this.liveImg = img;
2466
+ this.liveImgTargetId = targetId;
2467
+ if (img && targetId != null) {
2468
+ var cached = this.frameCache.get(targetId);
2469
+ if (cached) try {
2470
+ img.src = cached;
2471
+ } catch (e) {}
2472
+ }
2473
+ };
2474
+ LivePreviewController.prototype.refresh = function() {
2475
+ var self = this;
2476
+ (async function() {
2477
+ try {
2478
+ var res = await fetch(SPACES_ROUTE, { cache: "no-store" });
2479
+ if (self.disposed || !res.ok) {
2480
+ self._renderEmpty();
2481
+ return;
2482
+ }
2483
+ var data = await res.json();
2484
+ if (!data || data.ok !== true) {
2485
+ self._renderEmpty();
2486
+ return;
2487
+ }
2488
+ self._applyCaptureStatus(data.capture);
2489
+ self._processSpaces(data.spaces);
2490
+ } catch (e) {
2491
+ self._renderEmpty();
2492
+ }
2493
+ })();
2494
+ };
2495
+ LivePreviewController.prototype._renderEmpty = function() {
2496
+ if (this.lastList.length === 0) this._processSpaces([]);
2497
+ };
2498
+ LivePreviewController.prototype._processSpaces = function(spaces) {
2499
+ if (this.disposed) return;
2500
+ this.lastList = Array.isArray(spaces) ? spaces : [];
2501
+ for (var i = 0; i < this.lastList.length; i++) {
2502
+ var s = this.lastList[i];
2503
+ var prev = this.pageMeta.get(s.targetId) || { targetId: s.targetId };
2504
+ var meta = {
2505
+ url: s.url,
2506
+ title: s.title,
2507
+ targetId: s.targetId
2508
+ };
2509
+ if (Number.isFinite(s.viewportW)) meta.vw = s.viewportW;
2510
+ else if (prev.vw !== void 0) meta.vw = prev.vw;
2511
+ if (Number.isFinite(s.viewportH)) meta.vh = s.viewportH;
2512
+ else if (prev.vh !== void 0) meta.vh = prev.vh;
2513
+ this.pageMeta.set(s.targetId, meta);
2514
+ }
2515
+ var liveIds = new Set(this.lastList.map(function(s$1) {
2516
+ return s$1.targetId;
2517
+ }));
2518
+ var pm = this.pageMeta;
2519
+ pm.forEach(function(_, id) {
2520
+ if (!liveIds.has(id)) pm.delete(id);
2521
+ });
2522
+ var fc = this.frameCache;
2523
+ fc.forEach(function(_, id) {
2524
+ if (!liveIds.has(id)) fc.delete(id);
2525
+ });
2526
+ var activeMarked = this.lastList.find(function(s$1) {
2527
+ return s$1.active === true;
2528
+ });
2529
+ if (activeMarked) this.agentActiveId = activeMarked.targetId;
2530
+ this.liveCount = this.lastList.length;
2531
+ var busy = this.lastList.some(function(s$1) {
2532
+ return Date.now() - (s$1.lastActive || 0) <= ACTIVE_WINDOW_MS;
2533
+ });
2534
+ if (busy !== this.lastSawActive) this.lastSawActive = busy;
2535
+ this._recompute();
2536
+ };
2537
+ LivePreviewController.prototype.openStream = function() {
2538
+ if (this.disposed || !this.visible) return;
2539
+ this.closeStream();
2540
+ var self = this;
2541
+ fetch(WATCH_STATUS_ROUTE, { cache: "no-store" }).then(function(res) {
2542
+ return res.ok ? res.json() : null;
2543
+ }).then(function(status) {
2544
+ self._applyCaptureStatus(status);
2545
+ }).catch(function() {});
2546
+ try {
2547
+ this.sse = new EventSource("/api/bcdp/stream");
2548
+ } catch (e) {
2549
+ return;
2550
+ }
2551
+ this.sse.addEventListener("frame", function(ev) {
2552
+ try {
2553
+ var m = JSON.parse(ev.data);
2554
+ if (!m || !m.targetId || !m.data) return;
2555
+ if (Number.isFinite(m.vw) && Number.isFinite(m.vh)) {
2556
+ var cur = self.pageMeta.get(m.targetId) || { targetId: m.targetId };
2557
+ self.pageMeta.set(m.targetId, Object.assign({}, cur, {
2558
+ vw: m.vw,
2559
+ vh: m.vh
2560
+ }));
2561
+ }
2562
+ self.applyFrame(m.targetId, "data:image/jpeg;base64," + m.data, m.vw, m.vh);
2563
+ } catch (e) {}
2564
+ });
2565
+ this.sse.addEventListener("spaces", function(ev) {
2566
+ if (self.disposed) return;
2567
+ try {
2568
+ var list = JSON.parse(ev.data);
2569
+ if (Array.isArray(list)) self._processSpaces(list);
2570
+ } catch (e) {}
2571
+ });
2572
+ this.sse.addEventListener("capture-status", function(ev) {
2573
+ try {
2574
+ self._applyCaptureStatus(JSON.parse(ev.data));
2575
+ } catch (e) {}
2576
+ });
2577
+ this.sse.onerror = function() {
2578
+ if (self.reconnectFallbackTimer) return;
2579
+ self.reconnectFallbackTimer = window.setTimeout(function() {
2580
+ self.reconnectFallbackTimer = null;
2581
+ if (self.disposed || !self.visible) return;
2582
+ self.refresh();
2583
+ }, 1500);
2584
+ };
2585
+ };
2586
+ LivePreviewController.prototype.closeStream = function() {
2587
+ try {
2588
+ if (this.sse) this.sse.close();
2589
+ } catch (e) {}
2590
+ this.sse = null;
2591
+ };
2592
+ LivePreviewController.prototype.applyFrame = function(targetId, dataUrl, vw, vh) {
2593
+ if (this.disposed) return;
2594
+ this.frameCache.delete(targetId);
2595
+ this.frameCache.set(targetId, dataUrl);
2596
+ var MAX_CACHED_FRAMES = 12;
2597
+ if (this.frameCache.size > MAX_CACHED_FRAMES) {
2598
+ var self = this;
2599
+ this.frameCache.forEach(function(_, id) {
2600
+ if (self.frameCache.size <= MAX_CACHED_FRAMES) return;
2601
+ if (id === targetId || id === self.liveImgTargetId) return;
2602
+ self.frameCache.delete(id);
2603
+ });
2604
+ }
2605
+ if (Number.isFinite(vw) && Number.isFinite(vh)) {
2606
+ var cur = this.pageMeta.get(targetId) || { targetId };
2607
+ this.pageMeta.set(targetId, Object.assign({}, cur, {
2608
+ vw,
2609
+ vh
2610
+ }));
2611
+ }
2612
+ if (this.liveImg && this.liveImgTargetId === targetId) {
2613
+ var self2 = this;
2614
+ this.pendingLiveFrame = dataUrl;
2615
+ if (!this.liveFlushRaf && !this.disposed) this.liveFlushRaf = window.requestAnimationFrame(function() {
2616
+ self2.liveFlushRaf = null;
2617
+ if (self2.disposed || !self2.liveImg || self2.pendingLiveFrame == null) return;
2618
+ try {
2619
+ self2.liveImg.src = self2.pendingLiveFrame;
2620
+ } catch (e) {}
2621
+ self2.pendingLiveFrame = null;
2622
+ });
2623
+ return;
2624
+ }
2625
+ if (!this.pinned && this.selectedTabId === null && targetId === this.agentActiveId) {
2626
+ var now = Date.now();
2627
+ if (now - this.lastFrameAt >= FRAME_FOLLOW_MIN_MS) {
2628
+ this.lastFrameAt = now;
2629
+ if (this.followTimer) window.clearTimeout(this.followTimer);
2630
+ var self3 = this;
2631
+ this.followTimer = window.setTimeout(function() {
2632
+ if (self3.disposed || self3.pinned || self3.selectedTabId !== null) return;
2633
+ if (self3.liveImg && self3.liveImgTargetId === targetId) return;
2634
+ if (!self3.pageMeta.get(targetId)) return;
2635
+ self3.currentActiveId = targetId;
2636
+ self3._recompute();
2637
+ }, 0);
2638
+ }
2639
+ }
2640
+ };
2641
+ LivePreviewController.prototype.sendInput = function(targetId, type, params) {
2642
+ if (!!!targetId || this.disposed || type !== "mouseReleased" && type !== "keyUp" && !this.visible) return;
2643
+ var self = this;
2644
+ fetch(INPUT_ROUTE, {
2645
+ method: "POST",
2646
+ headers: { "content-type": "application/json" },
2647
+ body: JSON.stringify(Object.assign({
2648
+ targetId,
2649
+ type
2650
+ }, params))
2651
+ }).then(function(res) {
2652
+ if (res.status === 409) {
2653
+ self.liveImgTargetId = null;
2654
+ self._pointerState = null;
2655
+ self.refresh();
2656
+ }
2657
+ }).catch(function() {});
2658
+ };
2659
+ LivePreviewController.prototype.browserXY = function(e) {
2660
+ if (this.liveImgTargetId == null || !this.liveImg) return null;
2661
+ var m = this.pageMeta.get(this.liveImgTargetId);
2662
+ var vw = m && m.vw, vh = m && m.vh;
2663
+ if (!Number.isFinite(vw) || !Number.isFinite(vh)) return null;
2664
+ var img = this.liveImg;
2665
+ var rect = img.getBoundingClientRect();
2666
+ var natW = img.naturalWidth || img.videoWidth || rect.width;
2667
+ var natH = img.naturalHeight || img.videoHeight || rect.height;
2668
+ if (!natW || !natH) return null;
2669
+ var scale = Math.min(rect.width / natW, rect.height / natH);
2670
+ var contentW = natW * scale;
2671
+ var contentH = natH * scale;
2672
+ var ox = (rect.width - contentW) / 2;
2673
+ var oy = (rect.height - contentH) / 2;
2674
+ var rx = e.clientX - rect.left - ox;
2675
+ var ry = e.clientY - rect.top - oy;
2676
+ return {
2677
+ x: rx / contentW * vw,
2678
+ y: ry / contentH * vh
2679
+ };
2680
+ };
2681
+ LivePreviewController.prototype.pinTo = function(space) {
2682
+ if (this.disposed) return;
2683
+ this.pinned = space;
2684
+ this.selectedTabId = null;
2685
+ this._recompute();
2686
+ };
2687
+ LivePreviewController.prototype.unpin = function() {
2688
+ this.pinned = null;
2689
+ this._recompute();
2690
+ };
2691
+ LivePreviewController.prototype.selectTab = function(targetId) {
2692
+ if (this.selectedTabId === targetId) {
2693
+ this.selectedTabId = null;
2694
+ this.pinned = null;
2695
+ } else {
2696
+ this.selectedTabId = targetId;
2697
+ this.pinned = null;
2698
+ }
2699
+ this._recompute();
2700
+ this._syncWatch(this.selectedTabId || this.currentActiveId);
2701
+ };
2702
+ LivePreviewController.prototype.closeTab = function(targetId) {
2703
+ var self = this;
2704
+ (async function() {
2705
+ try {
2706
+ await fetch(EGO_CLOSE_ROUTE, {
2707
+ method: "POST",
2708
+ headers: { "content-type": "application/json" },
2709
+ body: JSON.stringify({ targetId })
2710
+ });
2711
+ } catch (e) {}
2712
+ if (self.selectedTabId === targetId) {
2713
+ self.selectedTabId = null;
2714
+ self.pinned = null;
2715
+ }
2716
+ self.refresh();
2717
+ })();
2718
+ };
2719
+ LivePreviewController.prototype.toggleHistory = function() {
2720
+ this.historyOpen = !this.historyOpen;
2721
+ this._recompute();
2722
+ };
2723
+ LivePreviewController.prototype.dismissGuide = function(which) {
2724
+ this.dismissedGuides[which] = true;
2725
+ this._recompute();
2726
+ };
2727
+ LivePreviewController.prototype.flushLogin = function() {
2728
+ return (async function() {
2729
+ return (await fetch(FLUSH_ROUTE, {
2730
+ method: "POST",
2731
+ headers: { "content-type": "application/json" },
2732
+ body: "{}"
2733
+ })).json();
2734
+ })();
2735
+ };
2736
+ LivePreviewController.prototype._showHint = function(txt) {
2737
+ this._zoomHint = txt;
2738
+ this._recompute();
2739
+ if (this._zoomHintTimer) window.clearTimeout(this._zoomHintTimer);
2740
+ var self = this;
2741
+ this._zoomHintTimer = window.setTimeout(function() {
2742
+ self._zoomHint = null;
2743
+ self._recompute();
2744
+ }, 2e3);
2745
+ };
2746
+ LivePreviewController.prototype.noteWired = function() {
2747
+ if (!this.wiringStale) return;
2748
+ this.wiringStale = false;
2749
+ if (this._wiredRecomputeQueued) return;
2750
+ this._wiredRecomputeQueued = true;
2751
+ var self = this;
2752
+ Promise.resolve().then(function() {
2753
+ self._wiredRecomputeQueued = false;
2754
+ if (!self.disposed) self._recompute();
2755
+ });
2756
+ };
2757
+ LivePreviewController.prototype._signalUnwired = function() {
2758
+ var now = Date.now();
2759
+ if (now - this._lastUnwiredAt < 5e3) return;
2760
+ this._lastUnwiredAt = now;
2761
+ try {
2762
+ console.warn("[dsh-browser-cdp] live view not wired (liveImgTargetId=" + this.liveImgTargetId + ", current=" + this.currentActiveId + ") — input dropped");
2763
+ } catch (e) {}
2764
+ this._showHint(wt("hintNotCaptured"));
2765
+ };
2766
+ LivePreviewController.prototype._applyZoom = function() {
2767
+ if (!this.liveImg) return;
2768
+ this.liveImg.style.transformOrigin = "0 0";
2769
+ this.liveImg.style.transform = "translate(" + this.zoomState.tx + "px," + this.zoomState.ty + "px) scale(" + this.zoomState.scale + ")";
2770
+ };
2771
+ LivePreviewController.prototype.resetZoom = function() {
2772
+ this.zoomState = {
2773
+ scale: 1,
2774
+ tx: 0,
2775
+ ty: 0
2776
+ };
2777
+ this._applyZoom();
2778
+ this._showHint(wt("hintReset"));
2779
+ };
2780
+ LivePreviewController.prototype.handleWheel = function(e) {
2781
+ e.preventDefault();
2782
+ e.stopPropagation();
2783
+ if (e.ctrlKey || e.metaKey) {
2784
+ if (!this.liveImg) return;
2785
+ var rect = this.liveImg.getBoundingClientRect();
2786
+ var mx = e.clientX - rect.left, my = e.clientY - rect.top;
2787
+ var next = Math.min(8, Math.max(1, this.zoomState.scale * (e.deltaY < 0 ? 1.15 : 1 / 1.15)));
2788
+ if (next <= 1) {
2789
+ this.resetZoom();
2790
+ return;
2791
+ }
2792
+ this.zoomState.tx = mx - (mx - this.zoomState.tx) * (next / this.zoomState.scale);
2793
+ this.zoomState.ty = my - (my - this.zoomState.ty) * (next / this.zoomState.scale);
2794
+ this.zoomState.scale = next;
2795
+ this._applyZoom();
2796
+ this._showHint(wt("hintPan"));
2797
+ return;
2798
+ }
2799
+ var p = this.browserXY(e);
2800
+ if (p && this.liveImgTargetId) this.sendInput(this.liveImgTargetId, "mouseWheel", {
2801
+ x: p.x,
2802
+ y: p.y,
2803
+ deltaX: e.deltaX || 0,
2804
+ deltaY: e.deltaY || (e.deltaMode === 1 ? 40 : e.deltaY || 100)
2805
+ });
2806
+ else this._signalUnwired();
2807
+ };
2808
+ LivePreviewController.prototype.handlePointerDown = function(e) {
2809
+ if (e.button !== 0) return;
2810
+ if (this.pickControl.isEnabled()) {
2811
+ var pp = this.browserXY(e);
2812
+ if (pp) this.pickControl.clickAt(pp.x, pp.y, this.liveImgTargetId);
2813
+ return;
2814
+ }
2815
+ this._pointerState = {
2816
+ viewPanning: false,
2817
+ browserDrag: false,
2818
+ sx: e.clientX,
2819
+ sy: e.clientY,
2820
+ stx: this.zoomState.tx,
2821
+ sty: this.zoomState.ty,
2822
+ lastDragPos: null,
2823
+ downButtons: 0,
2824
+ targetId: this.liveImgTargetId
2825
+ };
2826
+ try {
2827
+ e.currentTarget.setPointerCapture(e.pointerId);
2828
+ } catch (err) {}
2829
+ if (e.ctrlKey || e.metaKey) {
2830
+ this._pointerState.viewPanning = true;
2831
+ e.currentTarget.style.cursor = "grabbing";
2832
+ this._showHint(wt("hintScroll"));
2833
+ return;
2834
+ }
2835
+ this._pointerState.browserDrag = true;
2836
+ this.keyboardProxy.focusAt(e, this._pointerState.targetId);
2837
+ this._pointerState.downButtons = 1;
2838
+ var p = this.browserXY(e);
2839
+ if (p) {
2840
+ this._pointerState.lastDragPos = p;
2841
+ this.sendInput(this._pointerState.targetId, "mousePressed", {
2842
+ x: p.x,
2843
+ y: p.y,
2844
+ button: "left",
2845
+ buttons: 1,
2846
+ clickCount: 1
2847
+ });
2848
+ } else this._signalUnwired();
2849
+ };
2850
+ LivePreviewController.prototype.handlePointerMove = function(e) {
2851
+ if (!this._pointerState) {
2852
+ var p = this.browserXY(e);
2853
+ if (p) this.sendInput(this.liveImgTargetId, "mouseMoved", {
2854
+ x: p.x,
2855
+ y: p.y,
2856
+ buttons: 0
2857
+ });
2858
+ return;
2859
+ }
2860
+ if (this._pointerState.viewPanning) {
2861
+ this.zoomState.tx = this._pointerState.stx + (e.clientX - this._pointerState.sx);
2862
+ this.zoomState.ty = this._pointerState.sty + (e.clientY - this._pointerState.sy);
2863
+ this._applyZoom();
2864
+ return;
2865
+ }
2866
+ if (this._pointerState.browserDrag) {
2867
+ var p2 = this.browserXY(e);
2868
+ if (p2) {
2869
+ this.sendInput(this._pointerState.targetId, "mouseMoved", {
2870
+ x: p2.x,
2871
+ y: p2.y,
2872
+ buttons: this._pointerState.downButtons
2873
+ });
2874
+ this._pointerState.lastDragPos = p2;
2875
+ }
2876
+ }
2877
+ };
2878
+ LivePreviewController.prototype.handlePointerUp = function(e) {
2879
+ if (!this._pointerState) return;
2880
+ if (this._pointerState.viewPanning) {
2881
+ if (e.currentTarget) e.currentTarget.style.cursor = "grab";
2882
+ }
2883
+ if (this._pointerState.browserDrag) {
2884
+ if (this._pointerState.lastDragPos && this._pointerState.targetId) this.sendInput(this._pointerState.targetId, "mouseReleased", {
2885
+ x: this._pointerState.lastDragPos.x,
2886
+ y: this._pointerState.lastDragPos.y,
2887
+ button: "left",
2888
+ buttons: 0,
2889
+ clickCount: 1
2890
+ });
2891
+ }
2892
+ if (e.currentTarget) e.currentTarget.style.cursor = "grab";
2893
+ this._pointerState = null;
2894
+ };
2895
+ LivePreviewController.prototype.handleDoubleClick = function(e) {
2896
+ e.preventDefault();
2897
+ this.resetZoom();
2898
+ };
2899
+ function EgoBrowserTab(props) {
2900
+ var visible = props.visible;
2901
+ var ctx = props.ctx;
2902
+ var controllerRef = React.useRef(null);
2903
+ if (controllerRef.current === null) controllerRef.current = new LivePreviewController(ctx);
2904
+ var controller = controllerRef.current;
2905
+ var useSnapshotRef = React.useRef(null);
2906
+ if (useSnapshotRef.current === null) useSnapshotRef.current = bindSnapshotSelector(controller.store);
2907
+ var state = useSnapshotRef.current(function(s) {
2908
+ return s;
2909
+ });
2910
+ var imgRef = React.useRef(null);
2911
+ var videoRef = React.useRef(null);
2912
+ var bindLiveImg = function(el) {
2913
+ imgRef.current = el;
2914
+ if (el && state.currentTargetId != null && (controller.liveImg !== el || controller.liveImgTargetId !== state.currentTargetId)) {
2915
+ controller.setLiveImg(el, state.currentTargetId);
2916
+ controller.noteWired();
2917
+ }
2918
+ };
2919
+ var bindLiveVideo = function(el) {
2920
+ videoRef.current = el;
2921
+ if (el && state.currentTargetId != null && (controller.liveImg !== el || controller.liveImgTargetId !== state.currentTargetId)) {
2922
+ controller.setLiveVideo(el, state.currentTargetId);
2923
+ controller.noteWired();
2924
+ }
2925
+ };
2926
+ React.useEffect(function() {
2927
+ controller.start();
2928
+ return function() {
2929
+ controller.dispose();
2930
+ };
2931
+ }, [controller]);
2932
+ React.useEffect(function() {
2933
+ controller.setVisible(visible);
2934
+ }, [visible, controller]);
2935
+ React.useEffect(function() {
2936
+ if (imgRef.current && state.currentTargetId != null) controller.setLiveImg(imgRef.current, state.currentTargetId);
2937
+ if (videoRef.current && state.currentTargetId != null) controller.setLiveVideo(videoRef.current, state.currentTargetId);
2938
+ }, [
2939
+ state.currentTargetId,
2940
+ state.backend,
2941
+ state.streamGeneration,
2942
+ state.streamState,
2943
+ controller
2944
+ ]);
2945
+ React.useEffect(function() {
2946
+ var img = imgRef.current || videoRef.current;
2947
+ if (!img) return;
2948
+ var handler = function(e) {
2949
+ controller.handleWheel(e);
2950
+ };
2951
+ img.addEventListener("wheel", handler, { passive: false });
2952
+ return function() {
2953
+ img.removeEventListener("wheel", handler);
2954
+ };
2955
+ }, [
2956
+ controller,
2957
+ state.currentTargetId,
2958
+ state.backend,
2959
+ state.streamGeneration
2960
+ ]);
2961
+ var h = React.createElement;
2962
+ var header = h("div", { className: "dsh-ego-side-head" }, h("span", { className: "dsh-ego-side-title" }, h("span", { dangerouslySetInnerHTML: { __html: ICON_GLOBE } }), h("span", { style: { marginLeft: "5px" } }, state.busy ? wt("titleLive") : wt("title"))), h("button", {
2963
+ className: "dsh-ego-side-iconbtn" + (state.busy ? " spinning" : ""),
2964
+ title: wt("refresh"),
2965
+ onClick: function() {
2966
+ controller.refresh();
2967
+ }
2968
+ }, h("span", { dangerouslySetInnerHTML: { __html: ICON_REFRESH } })), h("button", {
2969
+ className: "dsh-ego-side-iconbtn" + (state.historyOpen ? "" : " off"),
2970
+ title: state.historyOpen ? wt("historyHide") : wt("historyShow"),
2971
+ onClick: function() {
2972
+ controller.toggleHistory();
2973
+ }
2974
+ }, h("span", { dangerouslySetInnerHTML: { __html: ICON_CLOCK } })));
2975
+ if (state.historyOpen) {
2976
+ var sorted = state.spaces.slice().sort(function(a, b) {
2977
+ return (a.lastActive || 0) - (b.lastActive || 0);
2978
+ });
2979
+ return h("div", { className: "dsh-ego-side-root" }, header, h("div", { className: "dsh-ego-side-history" }, h("div", { className: "dsh-ego-side-historyhead" }, h("span", { dangerouslySetInnerHTML: { __html: ICON_CLOCK } }), " " + wt("history")), h("div", { className: "dsh-ego-side-historylist" }, sorted.length === 0 ? h("div", { className: "dsh-ego-side-hnone" }, wt("noHistory")) : sorted.map(function(s) {
2980
+ return h("div", {
2981
+ key: s.targetId,
2982
+ className: "dsh-ego-side-hitem" + (s.targetId === state.currentTargetId ? " active" : ""),
2983
+ onClick: function() {
2984
+ controller.pinTo(s);
2985
+ controller.toggleHistory();
2986
+ }
2987
+ }, s.thumbnail ? h("img", {
2988
+ className: "dsh-ego-side-hthumb",
2989
+ src: s.thumbnail,
2990
+ alt: ""
2991
+ }) : h("div", { className: "dsh-ego-side-hthumb" }), h("div", { className: "dsh-ego-side-hinfo" }, h("div", { className: "dsh-ego-side-htitle" }, s.title || s.url || wt("newTab")), h("div", { className: "dsh-ego-side-hurl" }, s.url || "(about:blank)"), s.targetId === state.currentTargetId ? h("div", { className: "dsh-ego-side-hactive" }, "● " + wt("current")) : null));
2992
+ }))));
2993
+ }
2994
+ var guides = [];
2995
+ if (state.showLoginGuide) guides.push(h(EgoLoginGuide, {
2996
+ key: "login",
2997
+ controller
2998
+ }));
2999
+ if (state.captchaKind) guides.push(h(EgoCaptchaGuide, {
3000
+ key: "captcha",
3001
+ kind: state.captchaKind,
3002
+ controller
3003
+ }));
3004
+ var tabsEl = state.spaces.length > 0 ? h("div", { className: "dsh-ego-side-tabs" }, state.spaces.map(function(s) {
3005
+ var isActive = s.targetId === state.selectedTabId || state.selectedTabId === null && s.targetId === state.currentTargetId;
3006
+ return h("div", {
3007
+ key: s.targetId,
3008
+ className: "dsh-ego-side-tab" + (isActive ? " active" : ""),
3009
+ title: s.url || "",
3010
+ onClick: function() {
3011
+ controller.selectTab(s.targetId);
3012
+ }
3013
+ }, h("span", { className: "dsh-ego-side-tabdot" }), h("span", { className: "dsh-ego-side-tabtxt" }, s.title || s.url || wt("newTab")), h("span", {
3014
+ className: "dsh-ego-side-tabclose",
3015
+ title: wt("closeTab"),
3016
+ onClick: function(e) {
3017
+ e.stopPropagation();
3018
+ controller.closeTab(s.targetId);
3019
+ }
3020
+ }, "×"));
3021
+ })) : null;
3022
+ var body;
3023
+ var currentSpace = state.currentSpace;
3024
+ if (!currentSpace) body = h("div", { className: "dsh-ego-side-body" }, h("div", { className: "dsh-ego-side-empty" }, h("div", null, wt("noActivePages")), h("div", { style: { fontSize: "11px" } }, wt("noActiveHint"))));
3025
+ else {
3026
+ var liveImg = state.backend === "ffmpeg" ? h("video", {
3027
+ ref: bindLiveVideo,
3028
+ key: "livevideo-" + state.streamGeneration,
3029
+ className: "dsh-ego-side-liveimg",
3030
+ muted: true,
3031
+ autoPlay: true,
3032
+ playsInline: true,
3033
+ onPointerDown: function(e) {
3034
+ controller.handlePointerDown(e);
3035
+ },
3036
+ onPointerMove: function(e) {
3037
+ controller.handlePointerMove(e);
3038
+ },
3039
+ onPointerUp: function(e) {
3040
+ controller.handlePointerUp(e);
3041
+ },
3042
+ onPointerCancel: function(e) {
3043
+ controller.handlePointerUp(e);
3044
+ },
3045
+ onDoubleClick: function(e) {
3046
+ controller.handleDoubleClick(e);
3047
+ }
3048
+ }) : currentSpace.thumbnail ? h("img", {
3049
+ ref: bindLiveImg,
3050
+ key: "liveimg",
3051
+ className: "dsh-ego-side-liveimg",
3052
+ src: currentSpace.thumbnail,
3053
+ alt: "live",
3054
+ draggable: false,
3055
+ onPointerDown: function(e) {
3056
+ controller.handlePointerDown(e);
3057
+ },
3058
+ onPointerMove: function(e) {
3059
+ controller.handlePointerMove(e);
3060
+ },
3061
+ onPointerUp: function(e) {
3062
+ controller.handlePointerUp(e);
3063
+ },
3064
+ onPointerCancel: function(e) {
3065
+ controller.handlePointerUp(e);
3066
+ },
3067
+ onDoubleClick: function(e) {
3068
+ controller.handleDoubleClick(e);
3069
+ }
3070
+ }) : h("div", { className: "dsh-ego-side-liveurl" }, state.streamMessage || wt("noScreenshot"));
3071
+ body = h("div", { className: "dsh-ego-side-body" }, h("div", { className: "dsh-ego-side-liveview" }, h("div", { className: "dsh-ego-side-livebadge" }, h("span", { className: "dsh-ego-side-state-dot" + (state.pinned ? " pin" : state.busy ? " busy" : "") }), h("span", { style: { flex: 1 } }, (state.backend === "ffmpeg" ? "FFmpeg · H.264" : "CDP") + " · " + (state.streamState === "failed" ? state.streamMessage || wt("failed") : state.streamState) + (state.currentTargetId ? state.wiringStale ? " · " + wt("stale") : " · " + wt("captured") : "")), state.pinned ? h("button", {
3072
+ className: "dsh-ego-side-back",
3073
+ type: "button",
3074
+ onClick: function() {
3075
+ controller.unpin();
3076
+ }
3077
+ }, wt("backToLive")) : null, h("button", {
3078
+ className: "dsh-ego-side-back" + (state.pick === "on" ? " dsh-ego-pick-on" : ""),
3079
+ type: "button",
3080
+ title: wt("pickModeHint"),
3081
+ onClick: function() {
3082
+ controller.togglePick();
3083
+ }
3084
+ }, state.pick === "failed" ? wt("pickFailed") : state.pick === "on" ? wt("picking") : wt("pickMode")), h("button", {
3085
+ className: "dsh-ego-side-back",
3086
+ type: "button",
3087
+ title: wt("openExternal"),
3088
+ onClick: function() {
3089
+ var url = currentSpace.url;
3090
+ if (url && !url.startsWith("about:") && !url.startsWith("chrome://")) window.open(url, "_blank", "noopener");
3091
+ }
3092
+ }, wt("openExternal")), h("button", {
3093
+ className: "dsh-ego-side-back",
3094
+ type: "button",
3095
+ title: wt("raiseWindowHint"),
3096
+ onClick: function() {
3097
+ fetch("/api/bcdp/raise", {
3098
+ method: "POST",
3099
+ headers: { "content-type": "application/json" },
3100
+ body: "{}"
3101
+ }).then(function(r) {
3102
+ return r.json().catch(function() {
3103
+ return null;
3104
+ });
3105
+ }).catch(function() {
3106
+ return null;
3107
+ });
3108
+ }
3109
+ }, wt("raiseWindow"))), liveImg, h("div", { className: "dsh-ego-side-livetitle" }, currentSpace.title || currentSpace.url || wt("newTab")), h("div", { className: "dsh-ego-side-liveurl" + (state.zoomHint ? " dsh-ego-side-hint" : "") }, state.zoomHint || currentSpace.url || "")));
3110
+ }
3111
+ return h("div", { className: "dsh-ego-side-root" }, header, guides, tabsEl, body);
3112
+ }
3113
+ function EgoLoginGuide(props) {
3114
+ var controller = props.controller;
3115
+ var h = React.createElement;
3116
+ var noteState = React.useState("");
3117
+ var note = noteState[0], setNote = noteState[1];
3118
+ var savingState = React.useState(false);
3119
+ var saving = savingState[0], setSaving = savingState[1];
3120
+ return h("div", { className: "dsh-ego-side-login" }, h("span", { className: "dsh-ego-side-login-txt" }, wt("loginTitle")), h("button", {
3121
+ className: "dsh-ego-side-login-btn" + (saving ? " saving" : ""),
3122
+ type: "button",
3123
+ disabled: saving,
3124
+ onClick: function() {
3125
+ setSaving(true);
3126
+ setNote("");
3127
+ controller.flushLogin().then(function(j) {
3128
+ if (j && j.ok) setNote(wt("loginSaved", { n: j.total || "" }));
3129
+ else setNote(j && j.error ? wt("loginNotConnected") : wt("loginFailed"));
3130
+ }).catch(function() {
3131
+ setNote(wt("loginFailed"));
3132
+ }).finally(function() {
3133
+ setSaving(false);
3134
+ });
3135
+ }
3136
+ }, saving ? wt("loginSaving") : wt("loginBtn")), note ? h("span", { className: "dsh-ego-side-login-note" }, note) : null, h("button", {
3137
+ className: "dsh-ego-side-iconbtn",
3138
+ type: "button",
3139
+ title: wt("loginDismiss"),
3140
+ onClick: function() {
3141
+ controller.dismissGuide("login");
3142
+ }
3143
+ }, "×"));
3144
+ }
3145
+ function EgoCaptchaGuide(props) {
3146
+ var controller = props.controller;
3147
+ var kind = props.kind;
3148
+ var h = React.createElement;
3149
+ return h("div", { className: "dsh-ego-side-captcha" }, h("span", { className: "dsh-ego-side-captcha-txt" }, h("b", null, wt("captchaTitle")), " — " + wt("captchaHint")), h("span", { className: "dsh-ego-side-captcha-kind" }, kind), h("button", {
3150
+ className: "dsh-ego-side-iconbtn",
3151
+ type: "button",
3152
+ title: wt("captchaDismiss"),
3153
+ onClick: function() {
3154
+ controller.dismissGuide("captcha");
3155
+ }
3156
+ }, "×"));
3157
+ }
3158
+ function mountSidebarTab(ctx, betterSidebar) {
3159
+ if (!betterSidebar) return function() {};
3160
+ var styleEl = document.createElement("style");
3161
+ styleEl.textContent = TAB_CSS;
3162
+ document.head.appendChild(styleEl);
3163
+ var disposeTab = betterSidebar.registerTab({
3164
+ id: "dsh-browser-cdp:watch",
3165
+ title: function() {
3166
+ return wt("title");
3167
+ },
3168
+ order: 70,
3169
+ single: true,
3170
+ component: EgoBrowserTab
3171
+ });
3172
+ var probeDisposed = false;
3173
+ var baseline = null;
3174
+ var autoOpened = {};
3175
+ var openWatchTab = function(sessionId) {
3176
+ var key = sessionId || "";
3177
+ if (autoOpened[key] === true) return;
3178
+ autoOpened[key] = true;
3179
+ try {
3180
+ betterSidebar.openTab({ type: "dsh-browser-cdp:watch" }, sessionId ? { sessionId } : void 0);
3181
+ } catch (e) {}
3182
+ };
3183
+ (async function() {
3184
+ if (probeDisposed) return;
3185
+ try {
3186
+ var res = await fetch(SPACES_ROUTE, { cache: "no-store" });
3187
+ if (!res.ok) return;
3188
+ var data = await res.json();
3189
+ if (data && typeof data.toolCallCount === "number") baseline = data.toolCallCount;
3190
+ } catch (e) {}
3191
+ })();
3192
+ var probeSse = null;
3193
+ try {
3194
+ probeSse = new EventSource("/api/bcdp/stream");
3195
+ } catch (e) {}
3196
+ if (probeSse) probeSse.addEventListener("tool-call", function(ev) {
3197
+ if (probeDisposed) return;
3198
+ try {
3199
+ var m = JSON.parse(ev.data);
3200
+ if (!m || typeof m.count !== "number") return;
3201
+ var sid = typeof m.sessionId === "string" && m.sessionId !== "" ? m.sessionId : void 0;
3202
+ if (baseline === null) {
3203
+ baseline = m.count;
3204
+ if (m.count > 0) openWatchTab(sid);
3205
+ return;
3206
+ }
3207
+ if (m.count > baseline) openWatchTab(sid);
3208
+ } catch (e) {}
3209
+ });
3210
+ return function() {
3211
+ probeDisposed = true;
3212
+ try {
3213
+ if (probeSse) probeSse.close();
3214
+ } catch (e) {}
3215
+ disposeTab();
3216
+ styleEl.remove();
3217
+ };
3218
+ }
3219
+ function escapeHtml(s) {
3220
+ return String(s).replace(/[&<>"']/g, (c) => ({
3221
+ "&": "&amp;",
3222
+ "<": "&lt;",
3223
+ ">": "&gt;",
3224
+ "\"": "&quot;",
3225
+ "'": "&#39;"
3226
+ })[c]);
3227
+ }
3228
+ const name = "dsh-browser-cdp";
3229
+
3230
+ //#endregion
3231
+ exports.apply = apply;
3232
+ exports.inject = inject;
3233
+ exports.name = name;
3234
+ return module.exports; } });
3235
+ //# sourceMappingURL=client.js.map