dsh-shared-browser 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.cjs ADDED
@@ -0,0 +1,2712 @@
1
+ /**
2
+ * dsh-shared-browser — Client half.
3
+ *
4
+ * The tab type is taken over through the public `sidebarRightTabs` registry
5
+ * (`kind: 'browser'`, `priority: 'extension'`), so this file needs no edit to
6
+ * DSH: unloading the bundle hands the tab back to the built-in browser.
7
+ *
8
+ * Inside the tab we draw a desktop-browser chrome around the SAME Electron
9
+ * `<webview>` the shell owns — one process, one partition, the user's real
10
+ * logins — and we implement what the stock browser lacks: zoom, find in page,
11
+ * device emulation, history, bookmarks, permissions, storage clearing,
12
+ * screenshots, region screenshots, element picking, element comments,
13
+ * console/network capture, a DevTools panel, and "add to chat".
14
+ *
15
+ * The Host half reaches us over `/dsh-shared-browser/events` (SSE commands) and
16
+ * `/dsh-shared-browser/report` (results and telemetry). Page internals are read
17
+ * through an injected agent that `executeJavaScript` polls, so nothing here
18
+ * depends on a preload script the desktop shell refuses to keep.
19
+ */
20
+ window.__ModuleLoader__.load({
21
+ id: 'dsh-shared-browser',
22
+ factory(require) {
23
+ const React = require('react')
24
+ const h = React.createElement
25
+ const { useCallback, useEffect, useRef, useState } = React
26
+
27
+ const VERSION = '0.6.0'
28
+ const PLUGIN_ID = 'dsh-shared-browser'
29
+ const BASE = '/dsh-shared-browser'
30
+
31
+ /**
32
+ * Standard Chrome identity for the built-in webview: Cloudflare and friends
33
+ * reject the stock `@deepseek-ai/dsh-desktop/… Electron/…` token outright
34
+ * ("browser extension or network configuration not compatible"). The client
35
+ * hints cannot be rewritten from the renderer, so this only levels the UA.
36
+ */
37
+ const COMPAT_UA = String(navigator.userAgent || '')
38
+ .replace(/\s*@deepseek-ai\/\S+/g, '')
39
+ .replace(/\s*Electron\/\S+/g, '')
40
+ .replace(/\s{2,}/g, ' ')
41
+ .trim()
42
+ let compatUaEnabled = true
43
+ function effectiveUserAgent() {
44
+ return compatUaEnabled === true ? COMPAT_UA : ''
45
+ }
46
+
47
+ /* ------------------------------------------------------------------ i18n */
48
+
49
+ const ZH = {
50
+ 'browser.label': '浏览器',
51
+ 'external.label': '外部浏览器',
52
+ 'browser.guide': '共享浏览器:截图、元素评论、控制台,Agent 可直接操作',
53
+ 'browser.untitled': '新标签页',
54
+ 'browser.menu': '菜单',
55
+ 'action.back': '后退',
56
+ 'action.forward': '前进',
57
+ 'action.reload': '刷新',
58
+ 'action.stop': '停止',
59
+ 'action.go': '前往',
60
+ 'action.screenshot': '截图到聊天',
61
+ 'action.region': '区域截图',
62
+ 'action.pick': '选取元素到聊天',
63
+ 'action.comment': '评论元素',
64
+ 'action.devtools': '开发者工具 (F12)',
65
+ 'menu.newTab': '新建标签页',
66
+ 'menu.zoomIn': '放大',
67
+ 'menu.zoomOut': '缩小',
68
+ 'menu.zoomReset': '重置缩放',
69
+ 'menu.find': '在页面中查找',
70
+ 'menu.emulate': '设备仿真',
71
+ 'menu.external': '在外部浏览器中打开',
72
+ 'menu.history': '历史记录',
73
+ 'menu.bookmark': '添加到收藏夹',
74
+ 'menu.bookmarks': '收藏夹',
75
+ 'menu.permissions': '网站权限',
76
+ 'menu.clearStorage': '清除存储(全局)',
77
+ 'menu.settings': '浏览器设置',
78
+ 'menu.screenshot': '截图',
79
+ 'menu.region': '区域截图',
80
+ 'menu.pick': '选取元素',
81
+ 'menu.comment': '评论元素',
82
+ 'menu.consoleLog': '控制台日志',
83
+ 'menu.devtools': '开发者工具',
84
+ 'menu.copyUrl': '复制地址',
85
+ 'devtools.title': '开发者工具',
86
+ 'devtools.console': '控制台',
87
+ 'devtools.elements': '元素',
88
+ 'devtools.network': '网络',
89
+ 'devtools.eval': '运行',
90
+ 'devtools.empty': '暂无记录',
91
+ 'devtools.hint': '在此运行 JavaScript,Enter 执行,Shift+Enter 换行',
92
+ 'devtools.clear': '清空',
93
+ 'devtools.elementsHint': '元素树请用工具 bb_snapshot 获取;这里显示选取到的元素。',
94
+ 'find.placeholder': '在页面中查找',
95
+ 'find.none': '无匹配',
96
+ 'find.count': '第 {n} / {total}',
97
+ 'addr.placeholder': '输入 HTTP(S) 地址',
98
+ 'noBridge': '当前环境没有桌面浏览器桥,仍由内置浏览器接管此页签。',
99
+ 'pick.hint': '点击页面元素以添加到聊天(Esc 取消)',
100
+ 'comment.hint': '点击元素后填写评论(Esc 取消)',
101
+ 'comment.placeholder': '对这个元素的评论,Agent 会读到',
102
+ 'comment.submit': '添加评论',
103
+ 'comment.cancel': '取消',
104
+ 'region.hint': '拖拽选择区域(Esc 取消)',
105
+ 'toast.added': '已添加到聊天输入框',
106
+ 'toast.copied': '已复制',
107
+ 'toast.cleared': '已清除',
108
+ 'toast.saved': '已保存',
109
+ 'toast.failed': '操作失败',
110
+ 'toast.captureBlocked': '截图失败:请把 DSH 窗口切到前台后重试',
111
+ 'permissions.title': '网站权限',
112
+ 'permissions.body': '桌面端共享浏览器按工作区隔离,且默认拒绝所有站点权限请求(摄像头、麦克风、通知、定位、弹窗、下载)。该策略在 DSH 桌面壳内固定,插件无法在运行时放开。',
113
+ 'permissions.site': '当前站点',
114
+ 'note.screenshot': '截图',
115
+ 'note.region': '区域截图',
116
+ 'note.site': '地址',
117
+ 'element.link': '链接',
118
+ 'element.selector': '选择器',
119
+ 'element.text': '文本',
120
+ 'element.comment': '评论',
121
+ 'permissions.partition': '存储分区',
122
+ 'history.title': '历史记录',
123
+ 'history.empty': '暂无历史记录',
124
+ 'history.clear': '清空历史',
125
+ 'bookmarks.title': '收藏夹',
126
+ 'bookmarks.empty': '暂无收藏',
127
+ 'settings.title': '浏览器设置',
128
+ 'settings.defaultZoom': '当前缩放',
129
+ 'settings.compatUa': '兼容 UA(隐藏 Electron 标识)',
130
+ 'settings.compatHint': 'Cloudflare 等防护会拒绝 Electron 标识;开启后以标准 Chrome 身份访问。',
131
+ 'settings.zoomHint': '缩放只作用于当前页签。',
132
+ 'emulate.title': '设备仿真',
133
+ 'emulate.none': '关闭仿真',
134
+ 'emulate.desktop': '桌面 1280×800',
135
+ 'title.close': '关闭',
136
+ 'status.loading': '加载中…',
137
+ }
138
+
139
+ const EN = {
140
+ 'browser.label': 'Browser',
141
+ 'external.label': 'External browser',
142
+ 'browser.guide': 'Shared browser: screenshots, element comments, console — Agent can drive it',
143
+ 'browser.untitled': 'New tab',
144
+ 'browser.menu': 'Menu',
145
+ 'action.back': 'Back',
146
+ 'action.forward': 'Forward',
147
+ 'action.reload': 'Reload',
148
+ 'action.stop': 'Stop',
149
+ 'action.go': 'Go',
150
+ 'action.screenshot': 'Screenshot to chat',
151
+ 'action.region': 'Region screenshot',
152
+ 'action.pick': 'Pick element to chat',
153
+ 'action.comment': 'Comment element',
154
+ 'action.devtools': 'DevTools (F12)',
155
+ 'menu.newTab': 'New tab',
156
+ 'menu.zoomIn': 'Zoom in',
157
+ 'menu.zoomOut': 'Zoom out',
158
+ 'menu.zoomReset': 'Reset zoom',
159
+ 'menu.find': 'Find in page',
160
+ 'menu.emulate': 'Device emulation',
161
+ 'menu.external': 'Open in external browser',
162
+ 'menu.history': 'History',
163
+ 'menu.bookmark': 'Add to bookmarks',
164
+ 'menu.bookmarks': 'Bookmarks',
165
+ 'menu.permissions': 'Site permissions',
166
+ 'menu.clearStorage': 'Clear storage (all)',
167
+ 'menu.settings': 'Browser settings',
168
+ 'menu.screenshot': 'Screenshot',
169
+ 'menu.region': 'Region screenshot',
170
+ 'menu.pick': 'Pick element',
171
+ 'menu.comment': 'Comment element',
172
+ 'menu.consoleLog': 'Console log',
173
+ 'menu.devtools': 'DevTools',
174
+ 'menu.copyUrl': 'Copy address',
175
+ 'devtools.title': 'DevTools',
176
+ 'devtools.console': 'Console',
177
+ 'devtools.elements': 'Elements',
178
+ 'devtools.network': 'Network',
179
+ 'devtools.eval': 'Console input',
180
+ 'devtools.empty': 'Nothing captured yet',
181
+ 'devtools.hint': 'Run JavaScript here. Enter executes, Shift+Enter adds a line.',
182
+ 'devtools.clear': 'Clear',
183
+ 'devtools.elementsHint': 'Read the element tree with bb_snapshot; this shows the element you picked.',
184
+ 'find.placeholder': 'Find in page',
185
+ 'find.none': 'No matches',
186
+ 'find.count': '{n} of {total}',
187
+ 'addr.placeholder': 'Enter an HTTP(S) address',
188
+ 'noBridge': 'No desktop browser bridge here; the built-in browser keeps this tab.',
189
+ 'pick.hint': 'Click a page element to add it to chat (Esc cancels)',
190
+ 'comment.hint': 'Click an element, then write the comment (Esc cancels)',
191
+ 'comment.placeholder': 'Comment for this element; the agent reads it',
192
+ 'comment.submit': 'Add comment',
193
+ 'comment.cancel': 'Cancel',
194
+ 'region.hint': 'Drag to select a region (Esc cancels)',
195
+ 'toast.added': 'Added to the chat composer',
196
+ 'toast.copied': 'Copied',
197
+ 'toast.cleared': 'Cleared',
198
+ 'toast.saved': 'Saved',
199
+ 'toast.failed': 'Operation failed',
200
+ 'toast.captureBlocked': 'Capture failed: bring the DSH window to the front and try again',
201
+ 'permissions.title': 'Site permissions',
202
+ 'permissions.body': 'The desktop shared browser is per-workspace and refuses every site permission request (camera, microphone, notifications, geolocation, popups, downloads). That policy lives in the desktop shell; a plugin cannot relax it at runtime.',
203
+ 'permissions.site': 'Current site',
204
+ 'note.screenshot': 'Screenshot',
205
+ 'note.region': 'Region screenshot',
206
+ 'note.site': 'Address',
207
+ 'element.link': 'Link',
208
+ 'element.selector': 'Selector',
209
+ 'element.text': 'Text',
210
+ 'element.comment': 'Comment',
211
+ 'permissions.partition': 'Storage partition',
212
+ 'history.title': 'History',
213
+ 'history.empty': 'No history yet',
214
+ 'history.clear': 'Clear history',
215
+ 'bookmarks.title': 'Bookmarks',
216
+ 'bookmarks.empty': 'No bookmarks yet',
217
+ 'settings.title': 'Browser settings',
218
+ 'settings.defaultZoom': 'Current zoom',
219
+ 'settings.compatUa': 'Compatibility UA (hide Electron)',
220
+ 'settings.compatHint': 'Cloudflare-style checks reject the Electron token; this presents a standard Chrome identity.',
221
+ 'settings.zoomHint': 'Zoom applies to this tab only.',
222
+ 'emulate.title': 'Device emulation',
223
+ 'emulate.none': 'Disable emulation',
224
+ 'emulate.desktop': 'Desktop 1280×800',
225
+ 'title.close': 'Close',
226
+ 'status.loading': 'Loading…',
227
+ }
228
+
229
+ const strings = String((typeof navigator !== 'undefined' && navigator.language) || 'zh').toLowerCase().startsWith('zh') ? ZH : EN
230
+
231
+ /** Look up one localized string, substituting `{name}` placeholders. */
232
+ const t = (key, vars) => {
233
+ const template = strings[key] ?? EN[key] ?? key
234
+ if (vars === undefined) return template
235
+ return template.replace(/\{(\w+)\}/gu, (_, name) => (vars[name] === undefined ? `{${name}}` : String(vars[name])))
236
+ }
237
+
238
+ /* ------------------------------------------------------------- utilities */
239
+
240
+ const route = path => `${BASE}${path}`
241
+ const clamp = (value, min, max) => Math.min(Math.max(value, min), max)
242
+
243
+ /** Truncate text without splitting a surrogate pair. */
244
+ const cut = (text, max) => {
245
+ const value = String(text ?? '')
246
+ return value.length <= max ? value : `${value.slice(0, max)}…`
247
+ }
248
+
249
+ const load = (key, fallback) => {
250
+ try {
251
+ const raw = window.localStorage.getItem(`dsb.${key}`)
252
+ return raw === null ? fallback : JSON.parse(raw)
253
+ } catch {
254
+ return fallback
255
+ }
256
+ }
257
+
258
+ const save = (key, value) => {
259
+ try { window.localStorage.setItem(`dsb.${key}`, JSON.stringify(value)) } catch { /* storage is optional */ }
260
+ }
261
+
262
+ const ZOOM_STEPS = [0.5, 0.67, 0.8, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3]
263
+
264
+ /** Next or previous stop of the zoom ladder. */
265
+ const nextZoom = (current, direction) => {
266
+ const index = ZOOM_STEPS.findIndex(step => Math.abs(step - current) < 0.001)
267
+ const base = index === -1 ? 4 : index
268
+ return ZOOM_STEPS[clamp(base + direction, 0, ZOOM_STEPS.length - 1)]
269
+ }
270
+
271
+ const EMULATION_PRESETS = {
272
+ 'iphone-14': { width: 390, height: 844, ua: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1' },
273
+ 'pixel-7': { width: 412, height: 915, ua: 'Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/152.0.0.0 Mobile Safari/537.36' },
274
+ 'galaxy-s23': { width: 360, height: 780, ua: 'Mozilla/5.0 (Linux; Android 14; SM-S911B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/152.0.0.0 Mobile Safari/537.36' },
275
+ 'ipad-mini': { width: 744, height: 1133, ua: 'Mozilla/5.0 (iPad; CPU OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1' },
276
+ 'desktop-720': { width: 1280, height: 800, ua: null },
277
+ }
278
+
279
+ /* --------------------------------------------------------------- in-page */
280
+
281
+ /**
282
+ * Agent installed into the guest page: console/error/network capture, element
283
+ * description and refs, the picker, and comment markers.
284
+ *
285
+ * A guest without a preload cannot call back into the host renderer, so the
286
+ * agent only ever appends to a queue the renderer drains.
287
+ */
288
+ const AGENT_SOURCE = String.raw`(function () {
289
+ if (window.__dsbAgent && window.__dsbAgent.version === 1) return 'already';
290
+ var queue = [];
291
+ var MAX = 600;
292
+ function push(event) {
293
+ queue.push(event);
294
+ if (queue.length > MAX) queue.splice(0, queue.length - MAX);
295
+ }
296
+ function str(value, limit) {
297
+ limit = limit || 600;
298
+ try {
299
+ if (typeof value === 'string') return value.length > limit ? value.slice(0, limit) + '…' : value;
300
+ if (value instanceof Error) return (value.name || 'Error') + ': ' + value.message;
301
+ var text = JSON.stringify(value);
302
+ if (text === undefined) text = String(value);
303
+ return text.length > limit ? text.slice(0, limit) + '…' : text;
304
+ } catch (error) { return String(value); }
305
+ }
306
+ function visible(el) {
307
+ if (!el || el.nodeType !== 1) return false;
308
+ var rect = el.getBoundingClientRect();
309
+ if (rect.width < 1 || rect.height < 1) return false;
310
+ var style = getComputedStyle(el);
311
+ return style.visibility !== 'hidden' && style.display !== 'none' && Number(style.opacity) > 0.02;
312
+ }
313
+ function cssPath(el) {
314
+ if (!el || el.nodeType !== 1) return '';
315
+ if (el.id && /^[A-Za-z][\w-]*$/.test(el.id)) return '#' + el.id;
316
+ var testId = el.getAttribute('data-testid') || el.getAttribute('data-test-id');
317
+ if (testId) return '[data-testid="' + testId.replace(/"/g, '\\"') + '"]';
318
+ var parts = [];
319
+ var node = el;
320
+ var guard = 0;
321
+ while (node && node.nodeType === 1 && guard++ < 8) {
322
+ var part = node.tagName.toLowerCase();
323
+ if (node.id && /^[A-Za-z][\w-]*$/.test(node.id)) { parts.unshift('#' + node.id); break; }
324
+ var parent = node.parentElement;
325
+ var siblings = parent ? Array.prototype.filter.call(parent.children, function (child) { return child.tagName === node.tagName; }) : [];
326
+ if (siblings.length > 1) part += ':nth-of-type(' + (siblings.indexOf(node) + 1) + ')';
327
+ parts.unshift(part);
328
+ if (!parent || parent === document.body) { parts.unshift('body'); break; }
329
+ node = parent;
330
+ }
331
+ return parts.join(' > ');
332
+ }
333
+ function labelOf(el) {
334
+ var aria = el.getAttribute && (el.getAttribute('aria-label') || el.getAttribute('title'));
335
+ if (aria) return aria.trim();
336
+ var text = (el.innerText || el.value || el.getAttribute('placeholder') || el.getAttribute('alt') || '').trim();
337
+ return text.replace(/\s+/g, ' ').slice(0, 160);
338
+ }
339
+ function describe(el) {
340
+ var rect = el.getBoundingClientRect();
341
+ return {
342
+ tag: el.tagName.toLowerCase(),
343
+ selector: cssPath(el),
344
+ ref: el.getAttribute('data-dsb-ref') || null,
345
+ text: (el.innerText || el.value || '').trim().replace(/\s+/g, ' ').slice(0, 400),
346
+ html: (el.outerHTML || '').slice(0, 1200),
347
+ role: el.getAttribute('role') || null,
348
+ name: labelOf(el),
349
+ id: el.id || null,
350
+ classes: (typeof el.className === 'string') ? el.className.slice(0, 200) : null,
351
+ href: el.getAttribute ? el.getAttribute('href') : null,
352
+ rect: { x: Math.round(rect.left), y: Math.round(rect.top), width: Math.round(rect.width), height: Math.round(rect.height) }
353
+ };
354
+ }
355
+ var INTERACTIVE = 'a,button,input,select,textarea,summary,label,[role="button"],[role="link"],[role="tab"],[role="checkbox"],[role="radio"],[contenteditable="true"],[tabindex]:not([tabindex="-1"])';
356
+ function isInteractive(el) {
357
+ try { return el.matches(INTERACTIVE) || el.hasAttribute('onclick') } catch (error) { return false }
358
+ }
359
+ var refSeq = 0;
360
+ var refs = new Map();
361
+ function assignRef(el) {
362
+ var existing = el.getAttribute('data-dsb-ref');
363
+ if (existing) return existing;
364
+ var ref = 'e' + (++refSeq);
365
+ el.setAttribute('data-dsb-ref', ref);
366
+ try { refs.set(ref, new WeakRef(el)) } catch (error) { /* WeakRef missing */ }
367
+ return ref;
368
+ }
369
+ function resolve(target) {
370
+ if (!target) return null;
371
+ if (/^e[0-9]+$/.test(target)) {
372
+ var el = document.querySelector('[data-dsb-ref="' + target + '"]');
373
+ if (el) return el;
374
+ var held = refs.get(target);
375
+ return held && held.deref ? (held.deref() || null) : null;
376
+ }
377
+ try { return document.querySelector(target) } catch (error) { return null }
378
+ }
379
+ function snapshot(options) {
380
+ options = options || {};
381
+ var interactiveOnly = options.interactiveOnly === true;
382
+ var maxDepth = options.maxDepth || 12;
383
+ var budget = options.maxChars || 20000;
384
+ var lines = [];
385
+ var used = 0;
386
+ function walk(el, depth) {
387
+ if (used > budget || depth > maxDepth) return;
388
+ if (!el || el.nodeType !== 1 || !visible(el)) return;
389
+ var tag = el.tagName.toLowerCase();
390
+ if (['script', 'style', 'noscript', 'template', 'svg', 'path', 'head'].indexOf(tag) >= 0) return;
391
+ var interactive = isInteractive(el);
392
+ if (!interactiveOnly || interactive) {
393
+ var text = labelOf(el);
394
+ if (interactive || text.length > 1) {
395
+ var ref = assignRef(el);
396
+ var line = ref + ' <' + tag + '>' + (text ? ' "' + text + '"' : '');
397
+ if (used + line.length <= budget) { lines.push(line); used += line.length + 1; }
398
+ }
399
+ }
400
+ var children = Array.prototype.slice.call(el.children).slice(0, 150);
401
+ for (var index = 0; index < children.length; index += 1) walk(children[index], depth + 1);
402
+ }
403
+ walk(document.body, 0);
404
+ return { lines: lines, truncated: used > budget, url: location.href, title: document.title };
405
+ }
406
+ /* -------------------------------------------- console, errors, network */
407
+ ['log', 'info', 'warn', 'error', 'debug'].forEach(function (level) {
408
+ var original = console[level];
409
+ if (typeof original !== 'function') return;
410
+ console[level] = function () {
411
+ try {
412
+ var args = Array.prototype.slice.call(arguments).map(function (value) { return str(value, 400); });
413
+ push({ type: 'console', level: level === 'warn' ? 'warning' : level === 'log' ? 'info' : level, text: args.join(' '), source: 'console', ts: Date.now() });
414
+ } catch (error) { /* never break the page's logging */ }
415
+ return original.apply(this, arguments);
416
+ };
417
+ });
418
+ window.addEventListener('error', function (event) {
419
+ var target = event.target;
420
+ if (target && target !== window && target.tagName) {
421
+ push({ type: 'console', level: 'error', text: 'resource error: ' + target.tagName.toLowerCase() + ' ' + (target.src || target.href || ''), source: 'error', ts: Date.now() });
422
+ return;
423
+ }
424
+ push({ type: 'console', level: 'error', text: (event.message || 'error') + ' @ ' + (event.filename || location.href) + ':' + (event.lineno || 0), source: 'error', ts: Date.now() });
425
+ }, true);
426
+ window.addEventListener('unhandledrejection', function (event) {
427
+ push({ type: 'console', level: 'error', text: 'Unhandled rejection: ' + str(event.reason), source: 'unhandledrejection', ts: Date.now() });
428
+ });
429
+ if (typeof window.fetch === 'function') {
430
+ var originalFetch = window.fetch;
431
+ window.fetch = function (input, init) {
432
+ var url = typeof input === 'string' ? input : (input && input.url) || '';
433
+ var method = (init && init.method) || (input && input.method) || 'GET';
434
+ var started = performance.now();
435
+ return originalFetch.apply(this, arguments).then(function (response) {
436
+ push({ type: 'network', method: method, url: url, status: response.status, ok: response.ok, ms: Math.round(performance.now() - started), ts: Date.now() });
437
+ return response;
438
+ }, function (error) {
439
+ push({ type: 'network', method: method, url: url, status: 0, ok: false, ms: Math.round(performance.now() - started), error: str(error, 200), ts: Date.now() });
440
+ throw error;
441
+ });
442
+ };
443
+ }
444
+ if (window.XMLHttpRequest) {
445
+ var openXhr = XMLHttpRequest.prototype.open;
446
+ var sendXhr = XMLHttpRequest.prototype.send;
447
+ XMLHttpRequest.prototype.open = function (method, url) {
448
+ this.__dsb = { method: method, url: url };
449
+ return openXhr.apply(this, arguments);
450
+ };
451
+ XMLHttpRequest.prototype.send = function () {
452
+ var xhr = this;
453
+ var started = performance.now();
454
+ xhr.addEventListener('loadend', function () {
455
+ var meta = xhr.__dsb || {};
456
+ push({ type: 'network', method: meta.method || 'GET', url: meta.url || '', status: xhr.status, ok: xhr.status >= 200 && xhr.status < 400, ms: Math.round(performance.now() - started), ts: Date.now() });
457
+ });
458
+ return sendXhr.apply(this, arguments);
459
+ };
460
+ }
461
+ /* ---------------------------------------------------------------- picker */
462
+ function pickBox() {
463
+ var box = document.getElementById('__dsb_pick_box');
464
+ if (box) return box;
465
+ box = document.createElement('div');
466
+ box.id = '__dsb_pick_box';
467
+ box.style.cssText = 'position:fixed;z-index:2147483646;pointer-events:none;border:2px solid #3b82f6;background:rgba(59,130,246,0.12);border-radius:2px;transition:all 40ms linear;display:none';
468
+ document.documentElement.appendChild(box);
469
+ return box;
470
+ }
471
+ var picker = null;
472
+ function stopPicker() {
473
+ if (!picker) return false;
474
+ document.removeEventListener('mousemove', picker.move, true);
475
+ document.removeEventListener('click', picker.click, true);
476
+ document.removeEventListener('keydown', picker.key, true);
477
+ var box = pickBox();
478
+ box.style.display = 'none';
479
+ picker = null;
480
+ return true;
481
+ }
482
+ function startPicker(mode) {
483
+ stopPicker();
484
+ var box = pickBox();
485
+ picker = {
486
+ mode: mode || 'pick',
487
+ move: function (event) {
488
+ var el = event.target;
489
+ if (!el || el === box) return;
490
+ var rect = el.getBoundingClientRect();
491
+ box.style.display = 'block';
492
+ box.style.left = rect.left + 'px';
493
+ box.style.top = rect.top + 'px';
494
+ box.style.width = rect.width + 'px';
495
+ box.style.height = rect.height + 'px';
496
+ picker.hover = el;
497
+ },
498
+ click: function (event) {
499
+ event.preventDefault();
500
+ event.stopPropagation();
501
+ var el = (picker && picker.hover) || event.target;
502
+ if (!el || el === box) return;
503
+ var info = describe(el);
504
+ info.ref = assignRef(el);
505
+ push({ type: 'pick', mode: picker.mode, element: info, ts: Date.now() });
506
+ stopPicker();
507
+ },
508
+ key: function (event) {
509
+ if (event.key === 'Escape') { push({ type: 'pick', mode: 'cancel', ts: Date.now() }); stopPicker(); }
510
+ }
511
+ };
512
+ document.addEventListener('mousemove', picker.move, true);
513
+ document.addEventListener('click', picker.click, true);
514
+ document.addEventListener('keydown', picker.key, true);
515
+ return true;
516
+ }
517
+ /* ------------------------------------------------------- comment markers */
518
+ /* Right-click inside the page opens the plugin's own menu: the guest has no
519
+ native context menu, so the page side forwards the position instead. */
520
+ document.addEventListener('contextmenu', function (event) {
521
+ if (picker) return;
522
+ event.preventDefault();
523
+ push({ type: 'menu', x: event.clientX, y: event.clientY, ts: Date.now() });
524
+ }, true);
525
+
526
+ function drawMarkers(list) {
527
+ var layer = document.getElementById('__dsb_markers');
528
+ if (!layer) {
529
+ layer = document.createElement('div');
530
+ layer.id = '__dsb_markers';
531
+ layer.style.cssText = 'position:fixed;inset:0;pointer-events:none;z-index:2147483645';
532
+ document.documentElement.appendChild(layer);
533
+ }
534
+ layer.textContent = '';
535
+ (list || []).forEach(function (comment) {
536
+ var el = null;
537
+ try { el = document.querySelector(comment.selector) } catch (error) { el = null }
538
+ if (!el) return;
539
+ var rect = el.getBoundingClientRect();
540
+ var pin = document.createElement('div');
541
+ pin.title = comment.note || '';
542
+ pin.textContent = String(comment.index || '•');
543
+ pin.style.cssText = 'position:absolute;left:' + Math.round(rect.left) + 'px;top:' + Math.round(rect.top) + 'px;transform:translate(-50%,-50%);min-width:18px;height:18px;border-radius:9px;background:' + (comment.color || '#f59e0b') + ';color:#111;font:600 11px/18px system-ui;text-align:center;box-shadow:0 1px 4px rgba(0,0,0,0.35);pointer-events:auto;cursor:help;padding:0 4px';
544
+ layer.appendChild(pin);
545
+ });
546
+ return true;
547
+ }
548
+ /* ------------------------------------------------------------ page actions */
549
+ function rectOf(target) {
550
+ var el = resolve(target);
551
+ if (!el) return null;
552
+ try { el.scrollIntoView({ block: 'center', inline: 'center' }) } catch (error) { /* detached */ }
553
+ var rect = el.getBoundingClientRect();
554
+ return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2, left: rect.left, top: rect.top, width: rect.width, height: rect.height };
555
+ }
556
+ function nativeSet(el, text) {
557
+ var proto = el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
558
+ var descriptor = Object.getOwnPropertyDescriptor(proto, 'value');
559
+ if (descriptor && descriptor.set) descriptor.set.call(el, text); else el.value = text;
560
+ el.dispatchEvent(new Event('input', { bubbles: true }));
561
+ el.dispatchEvent(new Event('change', { bubbles: true }));
562
+ }
563
+ /* Count text occurrences without relying on the guest find session. */
564
+ function countText(text, limit) {
565
+ var needle = String(text || '').toLowerCase();
566
+ if (needle === '') return 0;
567
+ var cap = limit || 2000;
568
+ var total = 0;
569
+ var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, null);
570
+ var node;
571
+ while ((node = walker.nextNode())) {
572
+ var value = node.nodeValue;
573
+ if (!value) continue;
574
+ var hay = value.toLowerCase();
575
+ var index = hay.indexOf(needle);
576
+ while (index !== -1) {
577
+ total += 1;
578
+ if (total >= cap) return total;
579
+ index = hay.indexOf(needle, index + needle.length);
580
+ }
581
+ }
582
+ return total;
583
+ }
584
+ window.__dsbAgent = {
585
+ version: 1,
586
+ drain: function () {
587
+ var out = queue.slice();
588
+ queue.length = 0;
589
+ return out;
590
+ },
591
+ snapshot: snapshot,
592
+ text: function (selector, maxChars) {
593
+ var root = selector ? resolve(selector) : (document.querySelector('main,article,[role="main"]') || document.body);
594
+ if (!root) return { text: '', url: location.href, title: document.title };
595
+ var text = (root.innerText || root.textContent || '').replace(/\n{3,}/g, '\n\n').trim();
596
+ var limit = maxChars || 20000;
597
+ return { text: text.length > limit ? text.slice(0, limit) + '…' : text, url: location.href, title: document.title };
598
+ },
599
+ describe: function (target) { var el = resolve(target); return el ? describe(el) : null },
600
+ rect: rectOf,
601
+ countText: countText,
602
+ setValue: function (target, text) {
603
+ var el = resolve(target);
604
+ if (!el) return false;
605
+ el.focus();
606
+ nativeSet(el, text);
607
+ return true;
608
+ },
609
+ appendValue: function (target, text) {
610
+ var el = resolve(target);
611
+ if (!el) return false;
612
+ el.focus();
613
+ nativeSet(el, String(el.value || '') + text);
614
+ return true;
615
+ },
616
+ submit: function (target) {
617
+ var el = target ? resolve(target) : document.activeElement;
618
+ if (!el) return false;
619
+ var form = el.form || (el.closest ? el.closest('form') : null);
620
+ if (form && typeof form.requestSubmit === 'function') { form.requestSubmit(); return true; }
621
+ el.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true }));
622
+ return true;
623
+ },
624
+ startPicker: startPicker,
625
+ stopPicker: stopPicker,
626
+ markers: function (list) { try { return drawMarkers(list) } catch (error) { return false } },
627
+ storage: function (clear) {
628
+ var report = { origin: location.origin, localStorageKeys: 0, sessionStorageKeys: 0, cookies: 0, cleared: false };
629
+ try { report.localStorageKeys = localStorage.length } catch (error) { /* opaque origin */ }
630
+ try { report.sessionStorageKeys = sessionStorage.length } catch (error) { /* opaque origin */ }
631
+ try { report.cookies = document.cookie ? document.cookie.split(';').filter(Boolean).length : 0 } catch (error) { /* denied */ }
632
+ if (!clear) return report;
633
+ try { localStorage.clear() } catch (error) { /* denied */ }
634
+ try { sessionStorage.clear() } catch (error) { /* denied */ }
635
+ try {
636
+ document.cookie.split(';').forEach(function (cookie) {
637
+ var name = cookie.split('=')[0].trim();
638
+ if (!name) return;
639
+ document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';
640
+ });
641
+ } catch (error) { /* denied */ }
642
+ if (window.caches && caches.keys) {
643
+ caches.keys().then(function (keys) { keys.forEach(function (key) { caches.delete(key) }) }).catch(function () {});
644
+ }
645
+ try {
646
+ if (indexedDB && indexedDB.databases) {
647
+ indexedDB.databases().then(function (list) {
648
+ (list || []).forEach(function (entry) { if (entry && entry.name) indexedDB.deleteDatabase(entry.name) });
649
+ }).catch(function () {});
650
+ }
651
+ } catch (error) { /* unsupported */ }
652
+ report.cleared = true;
653
+ return report;
654
+ }
655
+ };
656
+ return 'installed';
657
+ })()`
658
+
659
+ /* ------------------------------------------------------------ page guest */
660
+
661
+ /** Imperative wrapper around one `<webview>` guest. */
662
+ class Guest {
663
+ /**
664
+ * @param {HTMLElement} container - mount point inside the tab body.
665
+ * @param {{ lease: string, partition: string }} reservation - desktop reservation.
666
+ * @param {(event: Record<string, any>) => void} onEvent - state sink.
667
+ */
668
+ constructor(container, reservation, onEvent) {
669
+ this.reservation = reservation
670
+ this.onEvent = onEvent
671
+ this.url = 'about:blank'
672
+ this.title = ''
673
+ this.loading = false
674
+ this.ready = false
675
+ /** True once the guest is attached and can accept navigation. */
676
+ this.attached = false
677
+ /** Target held until the guest attaches. */
678
+ this.pending = null
679
+ this.find = { text: '', active: 0, total: 0 }
680
+ this.handlers = []
681
+ this.pollTimer = null
682
+ this.keepAlive = null
683
+ /** Set by `create()`: the element must exist before `bind()` subscribes to it. */
684
+ this.element = null
685
+ this.create(container)
686
+ }
687
+
688
+ /**
689
+ * Create the element with exactly the attributes the desktop gate checks,
690
+ * mount it, then subscribe.
691
+ * @param {HTMLElement} container - mount point inside the tab body.
692
+ * @returns {Electron.WebviewTag} the mounted element.
693
+ */
694
+ /** Apply the compatibility UA now that the guest exists. */
695
+ applyUserAgent() {
696
+ const wanted = effectiveUserAgent()
697
+ if (this.userAgent === wanted) return
698
+ this.userAgent = wanted
699
+ try { this.element.setUserAgent(wanted) } catch { /* older shells */ }
700
+ }
701
+
702
+ create(container) {
703
+ const element = document.createElement('webview')
704
+ element.className = 'dsb-webview'
705
+ element.dataset.sidebarBrowserFrame = 'webview'
706
+ element.setAttribute('name', this.reservation.lease)
707
+ element.setAttribute('partition', this.reservation.partition)
708
+ element.setAttribute('allowpopups', '')
709
+ element.setAttribute('src', `about:blank#${this.reservation.lease}`)
710
+ element.style.cssText = 'display:flex;flex:1 1 auto;width:100%;height:100%;min-height:0;border:0;background:#fff'
711
+ try { element.setUserAgent(effectiveUserAgent()) } catch { /* older shells ignore it */ }
712
+ this.element = element
713
+ container.appendChild(element)
714
+ this.bind()
715
+ return element
716
+ }
717
+
718
+ /**
719
+ * Give the guest an explicit viewport size. A webview keeps its previous
720
+ * layout size when it merely sits in a flex box, so emulation would
721
+ * otherwise show a desktop viewport squeezed into a phone frame.
722
+ * @param {number|null} width - CSS pixels, or null to fill the container.
723
+ * @param {number|null} height - CSS pixels, or null to fill the container.
724
+ */
725
+ resize(width, height, scale = 1) {
726
+ if (this.element === null) return
727
+ if (width === null || height === null) {
728
+ this.element.style.cssText = 'display:flex;flex:1 1 auto;width:100%;height:100%;min-height:0;border:0;background:#fff'
729
+ return
730
+ }
731
+ // `display:flex` matters: with block/inline-block the guest keeps its
732
+ // default 150px viewport height even though the box is taller. The
733
+ // scale lives on the guest itself because an Electron webview ignores
734
+ // transforms on its ancestors.
735
+ this.element.style.cssText = `display:flex;flex:0 0 auto;width:${width}px;height:${height}px;border:0;background:#fff;transform:scale(${scale});transform-origin:center center`
736
+ }
737
+
738
+ /** Subscribe one DOM event and keep it for teardown. */
739
+ on(name, handler) {
740
+ const bound = event => {
741
+ try { handler(event) } catch (error) { /* never let a guest event break the UI */ }
742
+ }
743
+ this.element.addEventListener(name, bound)
744
+ this.handlers.push([name, bound])
745
+ }
746
+
747
+ /** Wire navigation, console and find events. */
748
+ bind() {
749
+ const ready = () => {
750
+ const first = this.attached === false
751
+ this.attached = true
752
+ /* The tag ignores `setUserAgent` before it is attached, so the level
753
+ UA is applied here — ahead of the first real navigation below. */
754
+ this.applyUserAgent()
755
+ if (this.ready === false) {
756
+ this.ready = true
757
+ this.onEvent({ kind: 'ready' })
758
+ }
759
+ if (first && this.pending !== null) {
760
+ const target = this.pending
761
+ this.pending = null
762
+ this.element.loadURL(target).catch(() => {})
763
+ }
764
+ this.installAgent()
765
+ }
766
+ this.on('dom-ready', ready)
767
+ this.on('did-start-loading', () => { this.loading = true; this.onEvent({ kind: 'loading', loading: true }) })
768
+ // `dom-ready` never fires for the initial `about:blank#lease` mount, so a
769
+ // guest that has settled counts as ready too; otherwise the tab sits on
770
+ // "loading" forever and no tool can reach the page agent.
771
+ this.on('did-stop-loading', () => { this.loading = false; ready(); this.sync(); this.onEvent({ kind: 'loading', loading: false }) })
772
+ this.on('did-start-navigation', (event) => {
773
+ if (event.isMainFrame === false) return
774
+ this.url = event.url || this.url
775
+ this.onEvent({ kind: 'url', url: this.url })
776
+ })
777
+ this.on('did-navigate', (event) => {
778
+ this.url = event.url || this.url
779
+ this.installAgent()
780
+ this.record()
781
+ this.sync()
782
+ this.onEvent({ kind: 'url', url: this.url })
783
+ })
784
+ this.on('did-navigate-in-page', (event) => {
785
+ this.url = event.url || this.url
786
+ this.record()
787
+ this.sync()
788
+ this.onEvent({ kind: 'url', url: this.url })
789
+ })
790
+ this.on('page-title-updated', (event) => { this.title = event.title || ''; this.onEvent({ kind: 'title', title: this.title }) })
791
+ this.on('did-fail-load', (event) => {
792
+ if (event.errorCode === -3) return
793
+ this.loading = false
794
+ this.onEvent({ kind: 'failed', url: event.validatedURL, description: event.errorDescription })
795
+ })
796
+ this.on('render-process-gone', () => { this.onEvent({ kind: 'gone' }) })
797
+ this.on('destroyed', () => { this.onEvent({ kind: 'destroyed' }) })
798
+ this.on('console-message', (event) => {
799
+ const raw = String(event.level ?? 'info')
800
+ this.onEvent({
801
+ kind: 'console',
802
+ entry: {
803
+ level: raw === 'warning' || raw === '1' ? 'warning' : raw === 'error' || raw === '3' ? 'error' : 'info',
804
+ text: cut(event.message ?? '', 2000),
805
+ source: 'webview',
806
+ url: this.url,
807
+ ts: Date.now(),
808
+ },
809
+ })
810
+ })
811
+ this.on('found-in-page', (event) => {
812
+ if (!event) return
813
+ // The webview re-wraps the IPC payload: counts live on `result`.
814
+ const result = event.result ?? event
815
+ this.find = { text: this.find.text, active: result.activeMatchOrdinal ?? 0, total: result.matches ?? 0 }
816
+ this.onEvent({ kind: 'find', find: this.find })
817
+ })
818
+ }
819
+
820
+ /** Begin the event pump and the agent watchdog. */
821
+ start() {
822
+ if (this.pollTimer !== null) return
823
+ this.pollTimer = setInterval(() => { this.poll() }, 400)
824
+ this.keepAlive = setInterval(() => { if (this.ready) this.installAgent() }, 5000)
825
+ // A mounted guest whose document already settled got no `did-stop-loading`
826
+ // we could hear: probe once, then leave the flag alone.
827
+ setTimeout(() => {
828
+ if (this.ready) return
829
+ this.run('document.readyState').then((state) => {
830
+ if (this.ready === false && (state === 'complete' || state === 'interactive')) {
831
+ this.ready = true
832
+ this.onEvent({ kind: 'ready' })
833
+ this.installAgent()
834
+ }
835
+ }).catch(() => {})
836
+ }, 1200)
837
+ }
838
+
839
+ /** Stop every timer. */
840
+ stop() {
841
+ if (this.pollTimer !== null) clearInterval(this.pollTimer)
842
+ if (this.keepAlive !== null) clearInterval(this.keepAlive)
843
+ this.pollTimer = null
844
+ this.keepAlive = null
845
+ }
846
+
847
+ /** Run one expression in the guest and return its value. */
848
+ async run(code) {
849
+ return this.element.executeJavaScript(code, true)
850
+ }
851
+
852
+ /** Drain the agent's event queue. */
853
+ async poll() {
854
+ if (!this.ready) return
855
+ try {
856
+ const events = await this.run('window.__dsbAgent ? window.__dsbAgent.drain() : []')
857
+ if (Array.isArray(events) === false) return
858
+ for (const event of events) this.onEvent({ kind: 'agent', event })
859
+ } catch { /* navigation replaced the context */ }
860
+ }
861
+
862
+ /** Install the page agent (idempotent). */
863
+ async installAgent() {
864
+ try {
865
+ const result = await this.run(AGENT_SOURCE)
866
+ if (result !== 'installed' && result !== 'already') return false
867
+ return true
868
+ } catch {
869
+ return false
870
+ }
871
+ }
872
+
873
+ /** Refresh back/forward availability. */
874
+ sync() {
875
+ let canGoBack = false
876
+ let canGoForward = false
877
+ try {
878
+ canGoBack = this.element.canGoBack()
879
+ canGoForward = this.element.canGoForward()
880
+ } catch { /* navigator not attached yet */ }
881
+ this.onEvent({ kind: 'nav', canGoBack, canGoForward })
882
+ }
883
+
884
+ /** Remember this visit in the shared history. */
885
+ record() {
886
+ if (!/^https?:/u.test(this.url)) return
887
+ this.onEvent({ kind: 'visit', url: this.url, title: this.title || this.url })
888
+ }
889
+
890
+ /** Load one address and wait for it to settle. */
891
+ async load(url, waitMs) {
892
+ this.url = url
893
+ this.onEvent({ kind: 'url', url })
894
+ if (this.attached === false) {
895
+ // A guest that has not finished attaching silently drops `loadURL`,
896
+ // so hold the target until the first document signals readiness.
897
+ this.pending = url
898
+ return { url: this.url, title: this.title, pending: true }
899
+ }
900
+ await this.element.loadURL(url)
901
+ if (waitMs !== 0) await this.waitForReady(waitMs ?? 15000)
902
+ return { url: this.url, title: this.title }
903
+ }
904
+
905
+ /** Wait until the document reports interactive/complete. */
906
+ async waitForReady(timeoutMs) {
907
+ const deadline = Date.now() + clamp(timeoutMs ?? 15000, 300, 60000)
908
+ while (Date.now() < deadline) {
909
+ try {
910
+ const state = await this.run('document.readyState')
911
+ if (state === 'complete' || state === 'interactive') return true
912
+ } catch { /* mid-navigation */ }
913
+ await new Promise(resolve => setTimeout(resolve, 200))
914
+ }
915
+ return false
916
+ }
917
+
918
+ /** Capture the viewport, an element rect, or a page rect. */
919
+ async capture(rect) {
920
+ /* capturePage can stay pending forever when the window is minimised or the
921
+ guest surface is occluded, which used to leave the toast spinning. Race it
922
+ against a deadline, retry once and surface a plain error instead. */
923
+ const element = this.element
924
+ if (element === null) throw new Error('capturePage without a guest')
925
+ const once = () => new Promise((resolve, reject) => {
926
+ const timer = setTimeout(() => reject(new Error('capturePage timed out')), 3000)
927
+ Promise.resolve(element.capturePage(rect)).then(
928
+ image => { clearTimeout(timer); resolve(image) },
929
+ error => { clearTimeout(timer); reject(error) },
930
+ )
931
+ })
932
+ let image = null
933
+ let reason = null
934
+ for (let attempt = 0; attempt < 2 && image === null; attempt += 1) {
935
+ try {
936
+ image = await once()
937
+ } catch (error) {
938
+ reason = error
939
+ await new Promise(resolve => setTimeout(resolve, 120))
940
+ }
941
+ }
942
+ if (image === null) throw reason ?? new Error('capturePage returned nothing')
943
+ if (typeof image.isEmpty === 'function' && image.isEmpty()) throw new Error('capturePage produced an empty image')
944
+ const dataUrl = typeof image.toDataURL === 'function' ? image.toDataURL() : null
945
+ if (!dataUrl) throw new Error('capturePage produced no data URL')
946
+ const size = typeof image.getSize === 'function' ? image.getSize() : null
947
+ return { dataUrl, width: size?.width ?? null, height: size?.height ?? null }
948
+ }
949
+
950
+ /** Remove the element and every listener. */
951
+ destroy() {
952
+ this.stop()
953
+ for (const [name, handler] of this.handlers) {
954
+ try { this.element.removeEventListener(name, handler) } catch { /* gone */ }
955
+ }
956
+ this.handlers = []
957
+ try { this.element.remove() } catch { /* already detached */ }
958
+ }
959
+ }
960
+
961
+ /* ---------------------------------------------------------------- bridge */
962
+
963
+ /** One SSE command stream plus REST reports, shared by every tab. */
964
+ class Bridge {
965
+ constructor() {
966
+ this.source = null
967
+ this.onCommand = null
968
+ this.openPane = null
969
+ this.connected = false
970
+ this.sessionId = null
971
+ }
972
+
973
+ /** Begin streaming; EventSource reconnects by itself. */
974
+ start() {
975
+ if (this.source !== null) return
976
+ const suffix = this.sessionId === null ? '' : `&sessionId=${encodeURIComponent(this.sessionId)}`
977
+ const source = new EventSource(`${route('/events')}?version=${encodeURIComponent(VERSION)}${suffix}`)
978
+ this.source = source
979
+ source.addEventListener('open', () => {
980
+ this.connected = true
981
+ this.post({ type: 'hello', version: VERSION, sessionId: this.sessionId })
982
+ })
983
+ source.addEventListener('error', () => { this.connected = false })
984
+ source.addEventListener('command', (event) => {
985
+ let payload
986
+ try { payload = JSON.parse(event.data) } catch { return }
987
+ this.dispatch(payload)
988
+ })
989
+ }
990
+
991
+ /** Adopt the Session once the UI knows it, and tell the Host again. */
992
+ identify(sessionId) {
993
+ if (typeof sessionId !== 'string' || sessionId === '') return
994
+ if (this.sessionId === sessionId) return
995
+ this.sessionId = sessionId
996
+ if (this.connected) this.post({ type: 'hello', version: VERSION, sessionId })
997
+ }
998
+
999
+ /** POST one report, retried once while the Host may still be booting. */
1000
+ async post(payload) {
1001
+ for (let attempt = 0; attempt < 2; attempt += 1) {
1002
+ try {
1003
+ const response = await fetch(route('/report'), {
1004
+ method: 'POST',
1005
+ headers: { 'content-type': 'application/json' },
1006
+ body: JSON.stringify(payload),
1007
+ })
1008
+ if (response.ok) return await response.json().catch(() => ({ ok: true }))
1009
+ } catch { /* Host not ready */ }
1010
+ await new Promise(resolve => setTimeout(resolve, 400))
1011
+ }
1012
+ return { ok: false }
1013
+ }
1014
+
1015
+ /** Run one Host command and report its result. */
1016
+ async dispatch(payload) {
1017
+ const { id, op, args, tabId } = payload
1018
+ if (op === 'ensure') {
1019
+ /* A mounted pane already serves commands; otherwise open one. An
1020
+ external mirror always needs its own pane, even when a built-in one
1021
+ already serves commands. */
1022
+ const wantsExternal = args !== null && typeof args === 'object' && typeof args.external === 'string'
1023
+ if (wantsExternal && typeof this.openPane === 'function') {
1024
+ try {
1025
+ this.openPane(args)
1026
+ await this.post({ type: 'result', id, ok: true, value: { opened: true, ready: true, external: true } })
1027
+ } catch (error) {
1028
+ await this.post({ type: 'result', id, ok: false, error: String(error && error.message ? error.message : error) })
1029
+ }
1030
+ return
1031
+ }
1032
+ if (typeof this.onCommand === 'function') {
1033
+ await this.post({ type: 'result', id, ok: true, value: { opened: false, ready: true } })
1034
+ return
1035
+ }
1036
+ if (typeof this.openPane === 'function') {
1037
+ try {
1038
+ this.openPane(args ?? {})
1039
+ await this.post({ type: 'result', id, ok: true, value: { opened: true, ready: false } })
1040
+ } catch (error) {
1041
+ await this.post({ type: 'result', id, ok: false, error: String(error && error.message ? error.message : error) })
1042
+ }
1043
+ return
1044
+ }
1045
+ }
1046
+ if (typeof this.onCommand !== 'function' && op === 'open' && typeof this.openPane === 'function') {
1047
+ /* `open` is how an Agent starts using the browser: mount a pane, then
1048
+ wait for its command handler instead of failing the call. */
1049
+ try { this.openPane(args ?? {}) } catch { /* reported below */ }
1050
+ const deadline = Date.now() + 12000
1051
+ while (Date.now() < deadline && typeof this.onCommand !== 'function') {
1052
+ await new Promise(resolve => setTimeout(resolve, 250))
1053
+ }
1054
+ }
1055
+ if (typeof this.onCommand !== 'function') {
1056
+ await this.post({ type: 'result', id, ok: false, error: '浏览器页签尚未就绪。' })
1057
+ return
1058
+ }
1059
+ try {
1060
+ const value = await this.onCommand(op, args ?? {}, tabId ?? null)
1061
+ await this.post({ type: 'result', id, ok: true, value: value ?? null })
1062
+ } catch (error) {
1063
+ await this.post({ type: 'result', id, ok: false, error: String(error && error.message ? error.message : error) })
1064
+ }
1065
+ }
1066
+
1067
+ /** Fire-and-forget telemetry. */
1068
+ report(payload) {
1069
+ this.post(payload).catch(() => {})
1070
+ }
1071
+ }
1072
+
1073
+ /* ------------------------------------------------------------ app state */
1074
+
1075
+ const bridge = new Bridge()
1076
+ /** @type {Map<string, any>} tabId → instance */
1077
+ const instances = new Map()
1078
+ let activeTabId = null
1079
+ let serviceContext = null
1080
+ let reportTimer = null
1081
+
1082
+ const settings = Object.assign({ defaultZoom: 1, keepConsole: true, commentColor: '#f59e0b', compatUa: true }, load('settings', {}))
1083
+ const historyLog = load('history', [])
1084
+ /**
1085
+ * One bookmark per address. Older builds could store duplicates, so the
1086
+ * stored list is folded on load instead of trusting it.
1087
+ */
1088
+ const bookmarks = (() => {
1089
+ const stored = load('bookmarks', [])
1090
+ if (!Array.isArray(stored)) return []
1091
+ const seen = new Set()
1092
+ return stored.filter((item) => {
1093
+ if (item === null || typeof item !== 'object' || typeof item.url !== 'string' || item.url === '') return false
1094
+ if (seen.has(item.url)) return false
1095
+ seen.add(item.url)
1096
+ return true
1097
+ })
1098
+ })()
1099
+
1100
+ /** Push the tab list to the Host (coalesced). */
1101
+ const scheduleReport = () => {
1102
+ if (reportTimer !== null) return
1103
+ reportTimer = setTimeout(() => {
1104
+ reportTimer = null
1105
+ const tabs = [...instances.values()].map((entry) => ({
1106
+ id: entry.tabId,
1107
+ url: entry.guest?.url ?? '',
1108
+ title: entry.guest?.title || entry.title || t('browser.untitled'),
1109
+ loading: entry.guest?.loading === true,
1110
+ visible: entry.tabId === activeTabId,
1111
+ }))
1112
+ bridge.report({ type: 'tabs', tabs, activeTabId })
1113
+ }, 200)
1114
+ }
1115
+
1116
+ /* ------------------------------------------------------------- chat glue */
1117
+
1118
+ /** Resolve the session-scoped conversation faces. */
1119
+ function conversationFor(sessionId) {
1120
+ if (serviceContext === null || !sessionId) return null
1121
+ try {
1122
+ const sessions = serviceContext.get('sessions')
1123
+ if (!sessions || typeof sessions.scope !== 'function') return null
1124
+ // The service itself is addressed by session; the session scope is only
1125
+ // needed as the context for `input.for(scope)`.
1126
+ const conversation = serviceContext.get('conversation')
1127
+ const scope = sessions.scope(sessionId)
1128
+ if (!conversation || scope === undefined || scope === null) return null
1129
+ return { conversation, scope }
1130
+ } catch {
1131
+ return null
1132
+ }
1133
+ }
1134
+
1135
+ /** Decode a data URL into a File the composer can take. */
1136
+ function fileFromDataUrl(dataUrl, name) {
1137
+ const match = /^data:([^;,]+);base64,(.*)$/su.exec(String(dataUrl ?? ''))
1138
+ if (match === null) throw new Error('bad data url')
1139
+ const binary = atob(match[2])
1140
+ const bytes = new Uint8Array(binary.length)
1141
+ for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index)
1142
+ return new File([bytes], name, { type: match[1] })
1143
+ }
1144
+
1145
+ /**
1146
+ * Put a note and/or an image into the composer draft of one session.
1147
+ * @returns {{ added: boolean, attachments: number, reason?: string }}
1148
+ */
1149
+ function addToComposer(request) {
1150
+ const faces = conversationFor(request.sessionId)
1151
+ if (faces === null) return { added: false, attachments: 0, reason: '会话输入框不可用,请先切到对应会话。' }
1152
+ const { conversation, scope } = faces
1153
+ let attachmentIds = []
1154
+ if (request.image) {
1155
+ try {
1156
+ const file = fileFromDataUrl(request.image.dataUrl, request.image.name)
1157
+ attachmentIds = conversation.createDrafts(request.sessionId, [file], false).map(draft => draft.id)
1158
+ } catch {
1159
+ attachmentIds = []
1160
+ }
1161
+ }
1162
+ try {
1163
+ const input = conversation.input.for(scope)
1164
+ if (attachmentIds.length > 0) input.addAttachments(attachmentIds)
1165
+ if (typeof request.note === 'string' && request.note.trim() !== '') {
1166
+ const accepted = input.insertQuote(request.note, { label: t('browser.label'), title: t('browser.label'), body: cut(request.note, 400) })
1167
+ if (!accepted) input.setDraft(`${request.note}\n`)
1168
+ }
1169
+ return { added: true, attachments: attachmentIds.length }
1170
+ } catch (error) {
1171
+ return { added: false, attachments: attachmentIds.length, reason: String(error && error.message ? error.message : error) }
1172
+ }
1173
+ }
1174
+
1175
+ /* ------------------------------------------------------------- rendering */
1176
+
1177
+ const styles = `
1178
+ .dsb-root{display:flex;flex-direction:column;min-height:0;height:100%;font:12px/1.4 system-ui,-apple-system,"Segoe UI",sans-serif;color:inherit;background:transparent;position:relative}
1179
+ .dsb-bar{display:flex;align-items:center;gap:2px;padding:4px 6px;min-height:34px;border-bottom:1px solid color-mix(in srgb,currentColor 14%,transparent);flex:0 0 auto;overflow:hidden}
1180
+ .dsb-btn{display:inline-flex;align-items:center;justify-content:center;min-width:24px;height:24px;padding:0 5px;border:0;border-radius:5px;background:transparent;color:inherit;cursor:pointer;font:inherit;opacity:.82;flex:0 0 auto}
1181
+ .dsb-btn:hover:not(:disabled){background:color-mix(in srgb,currentColor 12%,transparent);opacity:1}
1182
+ .dsb-btn:disabled{opacity:.32;cursor:default}
1183
+ .dsb-btn[data-on="true"]{background:color-mix(in srgb,currentColor 18%,transparent);opacity:1}
1184
+ .dsb-addr{flex:1 1 auto;min-width:50px;height:24px;padding:0 8px;border-radius:6px;border:1px solid color-mix(in srgb,currentColor 18%,transparent);background:color-mix(in srgb,currentColor 5%,transparent);color:inherit;font:inherit;outline:none}
1185
+ .dsb-addr:focus{border-color:color-mix(in srgb,currentColor 45%,transparent)}
1186
+ .dsb-sep{width:1px;height:16px;margin:0 3px;background:color-mix(in srgb,currentColor 16%,transparent);flex:0 0 auto}
1187
+ .dsb-stage{position:relative;flex:1 1 auto;min-height:0;overflow:hidden;background:#fff;display:flex}
1188
+ .dsb-view{position:relative;display:flex;flex:1 1 auto;min-height:0;height:100%}
1189
+ .dsb-stage[data-emulate="true"]{background:#e8e8ea;align-items:center;justify-content:center}
1190
+ .dsb-stage[data-emulate="true"] .dsb-view{flex:0 0 auto}
1191
+ .dsb-view[data-hidden="true"]{visibility:hidden;pointer-events:none}
1192
+ .dsb-emulate{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;overflow:auto;background:color-mix(in srgb,#111 14%,transparent);z-index:4}
1193
+ .dsb-device{display:flex;background:#fff;box-shadow:0 8px 32px rgba(0,0,0,.35);transform-origin:center center}
1194
+ .dsb-pop.dsb-pop-menu{position:fixed;right:auto;top:auto;z-index:30;max-height:calc(100vh - 24px)}
1195
+ .dsb-pop{position:absolute;right:6px;top:38px;z-index:20;min-width:240px;max-width:360px;max-height:340px;overflow:auto;padding:6px;border-radius:8px;border:1px solid color-mix(in srgb,currentColor 18%,transparent);background:var(--dsw-alias-bg-elevated,#fbfbfa);color:inherit;box-shadow:0 12px 32px rgba(0,0,0,.22)}
1196
+ .dsb-row{display:flex;align-items:center;gap:6px;width:100%;padding:4px 6px;border:0;border-radius:5px;background:transparent;color:inherit;font:inherit;cursor:pointer;text-align:left}
1197
+ .dsb-row:hover{background:color-mix(in srgb,currentColor 10%,transparent)}
1198
+ .dsb-hint{position:absolute;left:50%;top:8px;transform:translateX(-50%);z-index:12;padding:4px 10px;border-radius:999px;background:#1f2937;color:#f9fafb;font-size:11px;box-shadow:0 4px 16px rgba(0,0,0,.3);pointer-events:none;max-width:90%}
1199
+ .dsb-toast{position:absolute;left:50%;bottom:12px;transform:translateX(-50%);z-index:14;padding:5px 12px;border-radius:999px;background:#111827;color:#f9fafb;font-size:11px;box-shadow:0 4px 16px rgba(0,0,0,.3);pointer-events:none}
1200
+ .dsb-comment{position:absolute;left:8px;bottom:8px;z-index:16;width:min(320px,86%);padding:8px;border-radius:8px;border:1px solid color-mix(in srgb,currentColor 20%,transparent);background:var(--dsw-alias-bg-elevated,#fbfbfa);box-shadow:0 12px 32px rgba(0,0,0,.25)}
1201
+ .dsb-comment textarea{width:100%;min-height:56px;resize:vertical;border-radius:6px;border:1px solid color-mix(in srgb,currentColor 20%,transparent);background:transparent;color:inherit;font:inherit;padding:4px 6px}
1202
+ .dsb-region{position:absolute;inset:0;z-index:9;cursor:crosshair;background:rgba(59,130,246,.08)}
1203
+ .dsb-region-box{position:absolute;border:1px solid #3b82f6;background:rgba(59,130,246,.18);pointer-events:none}
1204
+ .dsb-devtools{flex:0 0 40%;display:flex;flex-direction:column;min-height:120px;border-top:1px solid color-mix(in srgb,currentColor 18%,transparent);background:color-mix(in srgb,currentColor 3%,transparent)}
1205
+ .dsb-tabs{display:flex;align-items:center;gap:2px;padding:3px 4px;border-bottom:1px solid color-mix(in srgb,currentColor 12%,transparent);flex:0 0 auto}
1206
+ .dsb-tab{padding:2px 8px;border-radius:5px;border:0;background:transparent;color:inherit;cursor:pointer;font:inherit;opacity:.7}
1207
+ .dsb-tab[data-on="true"]{background:color-mix(in srgb,currentColor 14%,transparent);opacity:1}
1208
+ .dsb-log{flex:1 1 auto;overflow:auto;padding:4px 6px;font:11px/1.5 ui-monospace,SFMono-Regular,Consolas,monospace;min-height:0;margin:0;white-space:pre-wrap}
1209
+ .dsb-line{display:flex;gap:6px;padding:1px 0;white-space:pre-wrap;word-break:break-word}
1210
+ .dsb-line[data-level="error"]{color:#dc2626}
1211
+ .dsb-line[data-level="warning"]{color:#b45309}
1212
+ .dsb-line em{opacity:.55;font-style:normal;flex:0 0 auto}
1213
+ .dsb-eval{display:flex;flex-direction:column;gap:4px;padding:6px;min-height:0;flex:1 1 auto}
1214
+ .dsb-eval textarea{min-height:52px;max-height:120px;resize:vertical;border-radius:6px;border:1px solid color-mix(in srgb,currentColor 18%,transparent);background:transparent;color:inherit;font:11px/1.5 ui-monospace,Consolas,monospace;padding:6px}
1215
+ .dsb-find{display:flex;align-items:center;gap:4px;padding:3px 6px;border-bottom:1px solid color-mix(in srgb,currentColor 12%,transparent);flex:0 0 auto}
1216
+ .dsb-find input{flex:1 1 auto;min-width:50px;height:22px;padding:0 8px;border-radius:6px;border:1px solid color-mix(in srgb,currentColor 18%,transparent);background:transparent;color:inherit;font:inherit}
1217
+ .dsb-muted{opacity:.6}
1218
+ .dsb-list{display:flex;flex-direction:column;gap:1px;max-height:260px;overflow:auto}
1219
+ .dsb-entry{display:flex;flex-direction:column;gap:1px;padding:3px 6px;border-radius:5px;border:0;background:transparent;color:inherit;font:inherit;cursor:pointer;text-align:left;overflow:hidden}
1220
+ .dsb-entry:hover{background:color-mix(in srgb,currentColor 9%,transparent)}
1221
+ .dsb-entry span{opacity:.6;font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1222
+ .dsb-entry strong{font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1223
+ .dsb-fill{flex:1 1 auto}
1224
+ .dsb-ext-stage{position:relative;flex:1 1 auto;display:flex;align-items:center;justify-content:center;background:#202124;overflow:hidden}
1225
+ .dsb-ext-frame{max-width:100%;max-height:100%;object-fit:contain;cursor:crosshair;user-select:none}
1226
+ `
1227
+
1228
+ /**
1229
+ * Sidebar mirror for a tab that lives in the user's own browser. The page is
1230
+ * drawn by Edge/Chrome, so the pane shows frames from the host bridge and
1231
+ * forwards pointer input back to it.
1232
+ * @param {{ external?: string, useTabInfo?: () => any }} props - seat props.
1233
+ */
1234
+ function ExternalPane(props) {
1235
+ const info = typeof props.useTabInfo === 'function' ? props.useTabInfo() : null
1236
+ const tab = info?.tab ?? null
1237
+ const external = String(props.external ?? '')
1238
+ const [address, setAddress] = useState(tab?.navigation?.params?.url ?? '')
1239
+ const [tick, setTick] = useState(0)
1240
+ const [busy, setBusy] = useState(false)
1241
+ const [notice, setNotice] = useState(null)
1242
+ const visible = tab === null ? true : tab.visible === true
1243
+ const frameRef = useRef(null)
1244
+
1245
+ /* Frames are polled, not streamed: a screenshot round trip is cheap and
1246
+ stays readable even when the pane is small. */
1247
+ useEffect(() => {
1248
+ if (visible === false) return undefined
1249
+ const timer = setInterval(() => setTick(current => current + 1), 900)
1250
+ return () => clearInterval(timer)
1251
+ }, [visible])
1252
+
1253
+ const post = useCallback(async (op, args) => {
1254
+ const response = await fetch(`${BASE}/external/command`, {
1255
+ method: 'POST',
1256
+ headers: { 'content-type': 'application/json' },
1257
+ body: JSON.stringify({ tab: external, op, args: args ?? {} }),
1258
+ })
1259
+ const payload = await response.json().catch(() => null)
1260
+ if (payload === null || payload.ok !== true) throw new Error(payload?.error ?? '外部浏览器命令失败')
1261
+ return payload.value
1262
+ }, [external])
1263
+
1264
+ const forward = useCallback((payload) => {
1265
+ fetch(`${BASE}/external/input`, {
1266
+ method: 'POST',
1267
+ headers: { 'content-type': 'application/json' },
1268
+ body: JSON.stringify({ tab: external, ...payload }),
1269
+ }).catch(() => null)
1270
+ }, [external])
1271
+
1272
+ const pointOf = (event) => {
1273
+ const frame = frameRef.current
1274
+ if (frame === null) return null
1275
+ const rect = frame.getBoundingClientRect()
1276
+ if (rect.width === 0 || rect.height === 0) return null
1277
+ const scaleX = (frame.naturalWidth || rect.width) / rect.width
1278
+ const scaleY = (frame.naturalHeight || rect.height) / rect.height
1279
+ return { x: Math.round((event.clientX - rect.left) * scaleX), y: Math.round((event.clientY - rect.top) * scaleY) }
1280
+ }
1281
+
1282
+ const go = useCallback(async () => {
1283
+ const target = address.trim()
1284
+ if (target === '') return
1285
+ setBusy(true)
1286
+ try {
1287
+ await post('navigate', { url: target })
1288
+ setTick(current => current + 1)
1289
+ } catch (error) {
1290
+ setNotice(String(error?.message ?? error))
1291
+ } finally {
1292
+ setBusy(false)
1293
+ }
1294
+ }, [address, post])
1295
+
1296
+ return h('div', { className: 'dsb-root dsb-ext' },
1297
+ h('div', { className: 'dsb-bar' },
1298
+ h('button', {
1299
+ className: 'dsb-btn',
1300
+ title: t('action.reload'),
1301
+ onClick: () => { post('navigate', { action: 'reload' }).then(() => setTick(c => c + 1)).catch(() => null) },
1302
+ }, '⟳'),
1303
+ h('input', {
1304
+ className: 'dsb-addr',
1305
+ value: address,
1306
+ placeholder: t('address.placeholder'),
1307
+ onChange: event => setAddress(event.target.value),
1308
+ onKeyDown: event => { if (event.key === 'Enter') { event.preventDefault(); go() } },
1309
+ }),
1310
+ h('button', { className: 'dsb-btn', title: t('action.go'), disabled: busy, onClick: go }, '↵'),
1311
+ h('span', { className: 'dsb-fill' }),
1312
+ h('span', { className: 'dsb-chip' }, t('external.label')),
1313
+ ),
1314
+ notice === null ? null : h('div', { className: 'dsb-hint' }, notice),
1315
+ h('div', { className: 'dsb-ext-stage' },
1316
+ h('img', {
1317
+ ref: frameRef,
1318
+ className: 'dsb-ext-frame',
1319
+ alt: '',
1320
+ draggable: false,
1321
+ src: `${BASE}/external/frame?tab=${encodeURIComponent(external)}&t=${tick}`,
1322
+ onPointerDown: event => {
1323
+ const point = pointOf(event)
1324
+ if (point !== null) forward({ kind: 'mouse', type: 'down', ...point })
1325
+ },
1326
+ onPointerUp: event => {
1327
+ const point = pointOf(event)
1328
+ if (point !== null) forward({ kind: 'mouse', type: 'up', ...point })
1329
+ },
1330
+ onWheel: event => {
1331
+ const point = pointOf(event)
1332
+ if (point !== null) forward({ kind: 'wheel', ...point, deltaY: event.deltaY })
1333
+ },
1334
+ })),
1335
+ )
1336
+ }
1337
+
1338
+ /**
1339
+ * Seat entry point: tabs opened for the external channel render the mirror,
1340
+ * everything else keeps the in-app webview.
1341
+ * @param {{ useTabInfo?: () => any, sessionId?: string }} props - seat props.
1342
+ */
1343
+ function BrowserBody(props) {
1344
+ const info = typeof props.useTabInfo === 'function' ? props.useTabInfo() : null
1345
+ const params = info?.tab?.navigation?.params ?? null
1346
+ const external = params !== null && typeof params.external === 'string' ? params.external : null
1347
+ return external === null ? h(BuiltinBody, props) : h(ExternalPane, { ...props, external })
1348
+ }
1349
+
1350
+ /**
1351
+ * One in-app browser tab: chrome, guest stage, overlays, DevTools panel.
1352
+ * @param {{ useTabInfo?: () => any, sessionId?: string }} props - seat props.
1353
+ */
1354
+ function BuiltinBody(props) {
1355
+ const info = typeof props.useTabInfo === 'function' ? props.useTabInfo() : null
1356
+ const tab = info?.tab ?? null
1357
+ const tabId = tab?.id ?? 'unknown-tab'
1358
+ /**
1359
+ * Session identity of the sidebar pane that hosts this tab. The seat's
1360
+ * `inject` face carries hooks, not the session id, so read the pane the
1361
+ * dockkit renders around us (a public `data-*` attribute, not another
1362
+ * plugin's internals) and fall back to a seat-provided id if one appears.
1363
+ */
1364
+ const rootRef = useRef(null)
1365
+ const [sessionId, setSessionId] = useState(props.sessionId ?? null)
1366
+ const initialUrl = tab?.navigation?.params?.url ?? null
1367
+ const visible = tab === null ? true : tab.visible === true
1368
+
1369
+ const [url, setUrl] = useState(initialUrl ?? '')
1370
+ const [title, setTitle] = useState('')
1371
+ const [loading, setLoading] = useState(false)
1372
+ const [ready, setReady] = useState(false)
1373
+ const [nav, setNav] = useState({ canGoBack: false, canGoForward: false })
1374
+ const [zoom, setZoom] = useState(settings.defaultZoom)
1375
+ const [compatUa, setCompatUa] = useState(settings.compatUa !== false)
1376
+ const [findOpen, setFindOpen] = useState(false)
1377
+ const [findText, setFindText] = useState('')
1378
+ const [findState, setFindState] = useState({ active: 0, total: 0 })
1379
+ const [devtools, setDevtools] = useState({ open: false, panel: 'console' })
1380
+ const [consoleLog, setConsoleLog] = useState([])
1381
+ const [networkLog, setNetworkLog] = useState([])
1382
+ const [hint, setHint] = useState(null)
1383
+ const [toast, setToast] = useState(null)
1384
+ const [menu, setMenu] = useState(null)
1385
+ const [popover, setPopover] = useState(null)
1386
+ const [comment, setComment] = useState(null)
1387
+ const [emulate, setEmulate] = useState(null)
1388
+ const [picked, setPicked] = useState(null)
1389
+ const [region, setRegion] = useState(null)
1390
+ const [evalText, setEvalText] = useState('')
1391
+ const [evalResult, setEvalResult] = useState(null)
1392
+ const [failure, setFailure] = useState(null)
1393
+
1394
+ const viewRef = useRef(null)
1395
+ const guestRef = useRef(null)
1396
+ const instanceRef = useRef(null)
1397
+ const consoleRef = useRef([])
1398
+ const networkRef = useRef([])
1399
+ const commentsRef = useRef([])
1400
+ const regionRef = useRef(null)
1401
+ const liveRef = useRef({})
1402
+
1403
+ /* Resolve the hosting pane's session. The panel that carries the data
1404
+ attribute is not always an ancestor of the tab body, so fall back to the
1405
+ ui-session adapter (the same source the sidebar itself follows). */
1406
+ useEffect(() => {
1407
+ if (props.sessionId) {
1408
+ setSessionId(props.sessionId)
1409
+ bridge.identify(props.sessionId)
1410
+ return undefined
1411
+ }
1412
+ const sync = () => {
1413
+ const node = rootRef.current
1414
+ const panel = node && node.closest ? node.closest('[data-sidebar-right-session]') : null
1415
+ const near = panel ? panel.getAttribute('data-sidebar-right-session') : null
1416
+ const found = near ?? readSessionId()
1417
+ if (typeof found !== 'string' || found === '') return false
1418
+ setSessionId(found)
1419
+ bridge.identify(found)
1420
+ return true
1421
+ }
1422
+ if (sync()) return undefined
1423
+ const timer = window.setInterval(() => { if (sync()) window.clearInterval(timer) }, 700)
1424
+ return () => window.clearInterval(timer)
1425
+ }, [props.sessionId, tabId])
1426
+
1427
+ liveRef.current = {
1428
+ tabId,
1429
+ sessionId,
1430
+ url,
1431
+ zoom,
1432
+ devtools,
1433
+ emulate,
1434
+ picked,
1435
+ comment,
1436
+ nav,
1437
+ visible,
1438
+ region,
1439
+ findText,
1440
+ }
1441
+
1442
+ const flash = useCallback((text) => {
1443
+ setToast(text)
1444
+ window.setTimeout(() => setToast(current => (current === text ? null : current)), 2200)
1445
+ }, [])
1446
+
1447
+ /* --------------------------------------------------- log/comment sinks */
1448
+ const pushConsole = useCallback((entry) => {
1449
+ const next = [...consoleRef.current, entry].slice(settings.keepConsole ? -500 : -100)
1450
+ consoleRef.current = next
1451
+ setConsoleLog(next)
1452
+ }, [])
1453
+
1454
+ const pushNetwork = useCallback((entry) => {
1455
+ const next = [...networkRef.current, entry].slice(-200)
1456
+ networkRef.current = next
1457
+ setNetworkLog(next)
1458
+ }, [])
1459
+
1460
+ const pushHistory = useCallback((visited, pageTitle) => {
1461
+ if (!visited) return
1462
+ const previous = historyLog[historyLog.length - 1]
1463
+ if (previous !== undefined && previous.url === visited) return
1464
+ historyLog.push({ url: visited, title: pageTitle || visited, ts: Date.now() })
1465
+ if (historyLog.length > 300) historyLog.splice(0, historyLog.length - 300)
1466
+ save('history', historyLog)
1467
+ }, [])
1468
+
1469
+ const rememberComment = useCallback((payload) => {
1470
+ commentsRef.current = [...commentsRef.current, payload]
1471
+ }, [])
1472
+
1473
+ const commentMarkers = useCallback(() => commentsRef.current.map((entry, index) => ({
1474
+ selector: entry.selector,
1475
+ note: entry.note,
1476
+ index: index + 1,
1477
+ color: settings.commentColor,
1478
+ })), [])
1479
+
1480
+ const syncMarkers = useCallback(() => {
1481
+ const guest = guestRef.current
1482
+ if (guest === null) return
1483
+ guest.run(`window.__dsbAgent && window.__dsbAgent.markers(${JSON.stringify(commentMarkers())})`).catch(() => {})
1484
+ }, [commentMarkers])
1485
+
1486
+ /* -------------------------------------------------------- chat actions */
1487
+ const addNote = useCallback((note) => {
1488
+ const result = addToComposer({ sessionId, note })
1489
+ flash(result.added ? t('toast.added') : (result.reason ?? t('toast.failed')))
1490
+ return result
1491
+ }, [flash, sessionId])
1492
+
1493
+ const addCapture = useCallback(async (rect, kind) => {
1494
+ const guest = guestRef.current
1495
+ if (guest === null) throw new Error('页面尚未就绪')
1496
+ let capture
1497
+ try {
1498
+ capture = await guest.capture(rect)
1499
+ } catch (error) {
1500
+ /* Occluded or minimised windows cannot be captured; say so instead of
1501
+ leaving the user with a generic failure. */
1502
+ console.warn('[dsh-shared-browser] capture failed', error)
1503
+ throw new Error(t('toast.captureBlocked'))
1504
+ }
1505
+ const note = [
1506
+ rect ? `${t('note.region')} · ${Math.round(rect.x)},${Math.round(rect.y)} ${Math.round(rect.width)}×${Math.round(rect.height)}` : t('note.screenshot'),
1507
+ guest.url ? `${t('note.site')}: ${guest.url}` : null,
1508
+ ].filter(Boolean).join('\n')
1509
+ const result = addToComposer({ sessionId, note, image: { dataUrl: capture.dataUrl, name: `dsh-browser-${kind}.png` } })
1510
+ flash(result.added ? t('toast.added') : (result.reason ?? t('toast.failed')))
1511
+ return { ...result, width: capture.width, height: capture.height }
1512
+ }, [flash, sessionId])
1513
+
1514
+ const elementNote = useCallback((element, note) => {
1515
+ return [
1516
+ `${element.tag}${element.name ? ` “${cut(element.name, 80)}”` : ''}`,
1517
+ element.url ? `${t('note.site')}: ${element.url}` : null,
1518
+ element.href ? `${t('element.link')}: ${element.href}` : null,
1519
+ `${t('element.selector')}: \`${element.selector}\``,
1520
+ element.text ? `${t('element.text')}: ${cut(element.text.replace(/\n/gu, ' '), 300)}` : null,
1521
+ note ? `${t('element.comment')}: ${note}` : null,
1522
+ element.html ? '```html\n' + cut(element.html, 1000) + '\n```' : null,
1523
+ ].filter(Boolean).join('\n')
1524
+ }, [])
1525
+
1526
+ const deliverElement = useCallback((element, note) => {
1527
+ const guest = guestRef.current
1528
+ const payload = { ...element, url: guest?.url ?? '', note: note ?? null }
1529
+ const record = { ...payload, id: `${tabId}-${Date.now()}`, tabId, index: commentsRef.current.length + 1, color: settings.commentColor }
1530
+ bridge.report({ type: 'comment', comment: record })
1531
+ rememberComment(payload)
1532
+ const result = addToComposer({ sessionId, note: elementNote(payload, note) })
1533
+ flash(result.added ? t('toast.added') : (result.reason ?? t('toast.failed')))
1534
+ syncMarkers()
1535
+ return { ...result, element: payload, comment: record }
1536
+ }, [elementNote, flash, rememberComment, sessionId, syncMarkers, tabId])
1537
+
1538
+ /* -------------------------------------------------------- guest events */
1539
+ const handleGuestEvent = useCallback((event) => {
1540
+ const guest = guestRef.current
1541
+ switch (event.kind) {
1542
+ case 'ready': setReady(true); break
1543
+ case 'loading': setLoading(event.loading === true); break
1544
+ case 'url': {
1545
+ const next = event.url ?? ''
1546
+ setUrl(next)
1547
+ if (next !== '' && !next.startsWith('about:blank')) save(`url:${tabId}`, next)
1548
+ break
1549
+ }
1550
+ case 'title': setTitle(event.title ?? ''); break
1551
+ case 'nav': setNav({ canGoBack: event.canGoBack === true, canGoForward: event.canGoForward === true }); break
1552
+ case 'find': setFindState({ active: event.find?.active ?? 0, total: event.find?.total ?? 0 }); break
1553
+ case 'failed': setFailure(event.description ?? 'load-failed'); break
1554
+ case 'gone':
1555
+ case 'destroyed': setReady(false); break
1556
+ case 'visit': pushHistory(event.url, event.title); break
1557
+ case 'console': {
1558
+ const entry = { ...event.entry, url: guest?.url ?? '' }
1559
+ pushConsole(entry)
1560
+ bridge.report({ type: 'console', entries: [{ ...entry, tabId }] })
1561
+ break
1562
+ }
1563
+ case 'agent': {
1564
+ const agentEvent = event.event
1565
+ if (agentEvent?.type === 'console') {
1566
+ pushConsole({ ...agentEvent, url: guest?.url ?? '' })
1567
+ bridge.report({ type: 'console', entries: [{ ...agentEvent, tabId, url: guest?.url ?? '' }] })
1568
+ } else if (agentEvent?.type === 'network') {
1569
+ pushNetwork(agentEvent)
1570
+ bridge.report({ type: 'network', entries: [{ ...agentEvent, tabId, url: guest?.url ?? '' }] })
1571
+ } else if (agentEvent?.type === 'menu') {
1572
+ /* Page coordinates become pane coordinates through the stage. */
1573
+ const view = viewRef.current
1574
+ const rect = view === null ? { left: 0, top: 0 } : view.getBoundingClientRect()
1575
+ setMenu({ x: rect.left + Number(agentEvent.x ?? 0), y: rect.top + Number(agentEvent.y ?? 0) })
1576
+ } else if (agentEvent?.type === 'pick') {
1577
+ if (agentEvent.mode === 'cancel') { setHint(null); setComment(null); break }
1578
+ setHint(null)
1579
+ setPicked(agentEvent.element)
1580
+ setComment({ element: agentEvent.element, note: '' })
1581
+ }
1582
+ break
1583
+ }
1584
+ default: break
1585
+ }
1586
+ }, [pushConsole, pushHistory, pushNetwork, tabId])
1587
+
1588
+ /* ------------------------------------------------------------- mounting */
1589
+ useEffect(() => {
1590
+ const desktop = typeof window !== 'undefined' ? window.dshDesktop : undefined
1591
+ if (desktop === undefined || desktop.protocolVersion !== 1 || desktop.browser === undefined) {
1592
+ setFailure('no-bridge')
1593
+ return undefined
1594
+ }
1595
+ let disposed = false
1596
+ let reservation = null
1597
+ const host = viewRef.current
1598
+ if (host === null) return undefined
1599
+
1600
+ /** Workspace key shared with the built-in browser, so logins carry over. */
1601
+ const workspaceKey = () => {
1602
+ try {
1603
+ const sessions = serviceContext?.get('sessions')
1604
+ const record = sessions?.list?.getSnapshot?.().byId?.[sessionId]
1605
+ if (record?.cwd) return `cwd:${record.cwd}`
1606
+ } catch { /* fall through */ }
1607
+ return sessionId === null ? 'cwd:default' : `session:${sessionId}`
1608
+ }
1609
+
1610
+ desktop.browser.acquire(workspaceKey()).then((acquired) => {
1611
+ if (disposed) {
1612
+ desktop.browser.release(acquired.lease).catch(() => {})
1613
+ return
1614
+ }
1615
+ reservation = acquired
1616
+ const guest = new Guest(host, acquired, handleGuestEvent)
1617
+ guestRef.current = guest
1618
+ const preset = liveRef.current.emulate ?? null
1619
+ if (preset !== null) guest.resize(preset.width, preset.height, emulateScale(preset))
1620
+ guest.start()
1621
+ const instance = createInstance()
1622
+ instanceRef.current = instance
1623
+ instances.set(tabId, instance)
1624
+ scheduleReport()
1625
+ // Reloading the shell discards the guest, so remember where each tab was.
1626
+ const target = initialUrl ?? load(`url:${tabId}`, '') ?? 'about:blank'
1627
+ if (typeof window !== 'undefined' && window.__dshBrowserDebug !== undefined) {
1628
+ window.__dshBrowserDebug.lastMount = { tabId, initialUrl, saved: load(`url:${tabId}`, null), target }
1629
+ }
1630
+ if (typeof target === 'string' && target !== 'about:blank' && target !== '') guest.load(target, 15000).catch((error) => setFailure(String(error && error.message ? error.message : error)))
1631
+ }).catch((error) => {
1632
+ setFailure(String(error && error.message ? error.message : error))
1633
+ })
1634
+
1635
+ return () => {
1636
+ disposed = true
1637
+ instances.delete(tabId)
1638
+ scheduleReport()
1639
+ const guest = guestRef.current
1640
+ guestRef.current = null
1641
+ instanceRef.current = null
1642
+ if (guest !== null) guest.destroy()
1643
+ if (reservation !== null) desktop.browser.release(reservation.lease).catch(() => {})
1644
+ }
1645
+ }, [tabId])
1646
+
1647
+ /* --------------------------------------------------- visibility + bars */
1648
+ useEffect(() => {
1649
+ if (visible) activeTabId = tabId
1650
+ scheduleReport()
1651
+ }, [visible, tabId, url, title, loading])
1652
+
1653
+ /* ------------------------------------------------------- zoom plumbing */
1654
+ const applyZoom = useCallback((factor) => {
1655
+ const value = clamp(Number(factor) || 1, 0.25, 5)
1656
+ setZoom(value)
1657
+ const guest = guestRef.current
1658
+ if (guest !== null) {
1659
+ try { guest.element.setZoomFactor(value) } catch { /* unsupported */ }
1660
+ }
1661
+ return { zoom: value }
1662
+ }, [])
1663
+
1664
+ const zoomStep = useCallback((direction) => applyZoom(nextZoom(liveRef.current.zoom ?? 1, direction)), [applyZoom])
1665
+
1666
+ /* ------------------------------------------------------- find plumbing */
1667
+ // The guest find session does not always report `found-in-page` (Electron
1668
+ // only emits it for some guests), so the count comes from the page agent
1669
+ // while `findInPage` still drives the native highlight and scrolling.
1670
+ const runFind = useCallback(async (text, direction = 'new') => {
1671
+ const guest = guestRef.current
1672
+ if (guest === null) return { matched: false }
1673
+ const clean = String(text ?? '')
1674
+ guest.find.text = clean
1675
+ if (clean.trim() === '') {
1676
+ try { guest.element.stopFindInPage('clearSelection') } catch { /* detached */ }
1677
+ setFindState({ active: 0, total: 0 })
1678
+ return { matched: true }
1679
+ }
1680
+ let total = 0
1681
+ try {
1682
+ total = Number(await guest.run(`window.__dsbAgent ? window.__dsbAgent.countText(${JSON.stringify(clean)}) : 0`)) || 0
1683
+ } catch { total = 0 }
1684
+ try {
1685
+ guest.element.findInPage(clean, { findNext: direction !== 'new', forward: direction !== 'previous' })
1686
+ } catch { /* detached */ }
1687
+ setFindState((previous) => {
1688
+ if (total === 0) return { active: 0, total: 0 }
1689
+ const cycle = previous.total === total && previous.active > 0
1690
+ if (direction === 'previous') return { active: cycle ? ((previous.active - 2 + total) % total) + 1 : total, total }
1691
+ if (direction === 'next') return { active: cycle ? (previous.active % total) + 1 : 1, total }
1692
+ return { active: 1, total }
1693
+ })
1694
+ return { matched: total > 0 }
1695
+ }, [])
1696
+
1697
+ /* ------------------------------------------------------ storage/emulate */
1698
+ const clearStorage = useCallback(async () => {
1699
+ const guest = guestRef.current
1700
+ if (guest === null) return { cleared: false }
1701
+ const report = await guest.run('window.__dsbAgent ? window.__dsbAgent.storage(true) : null').catch(() => null)
1702
+ flash(t('toast.cleared'))
1703
+ return { cleared: true, report }
1704
+ }, [flash])
1705
+
1706
+ const applyEmulation = useCallback((device) => {
1707
+ const guest = guestRef.current
1708
+ const preset = device === 'none' ? null : EMULATION_PRESETS[device] ?? null
1709
+ if (guest !== null) {
1710
+ try { guest.element.setUserAgent(preset?.ua ?? effectiveUserAgent()) } catch { /* the attribute is optional */ }
1711
+ guest.resize(preset?.width ?? null, preset?.height ?? null, preset === null ? 1 : emulateScale(preset))
1712
+ }
1713
+ setEmulate(preset === null ? null : { device, ...preset })
1714
+ return { emulation: preset === null ? null : { device, ...preset } }
1715
+ }, [])
1716
+
1717
+ /* ------------------------------------------------------------ instance */
1718
+ const createInstance = () => {
1719
+ const state = () => liveRef.current
1720
+ const guest = () => guestRef.current
1721
+
1722
+ /** Resolve a target element and its centre point, or throw. */
1723
+ const rectOf = async (args) => {
1724
+ const target = args.ref ?? args.selector ?? null
1725
+ if (target === null) throw new Error('需要 ref 或 selector。')
1726
+ const rect = await guest().run(`window.__dsbAgent ? window.__dsbAgent.rect(${JSON.stringify(target)}) : null`)
1727
+ if (rect === null) throw new Error(`元素未找到: ${target}`)
1728
+ return rect
1729
+ }
1730
+
1731
+ const handlers = {
1732
+ async open(args) {
1733
+ const target = String(args.url ?? '')
1734
+ if (target === '') throw new Error('缺少 url。')
1735
+ const result = await guest().load(target, args.waitMs ?? 15000)
1736
+ return { tabId: state().tabId, ...result }
1737
+ },
1738
+ async navigate(args) {
1739
+ const action = args.action ?? (typeof args.url === 'string' && args.url !== '' ? 'goto' : 'reload')
1740
+ const g = guest()
1741
+ if (action === 'goto') {
1742
+ const result = await g.load(String(args.url ?? ''), args.waitMs ?? 15000)
1743
+ return { tabId: state().tabId, action, ...result }
1744
+ }
1745
+ if (action === 'back') g.element.goBack()
1746
+ else if (action === 'forward') g.element.goForward()
1747
+ else if (action === 'reload') g.element.reload()
1748
+ else if (action === 'stop') g.element.stop()
1749
+ await g.waitForReady(2000)
1750
+ g.sync()
1751
+ return { tabId: state().tabId, action, url: g.url, title: g.title }
1752
+ },
1753
+ async tabs(args) {
1754
+ const action = args.action ?? 'list'
1755
+ if (action === 'list') {
1756
+ return { tabs: [...instances.values()].map(entry => ({ id: entry.tabId, url: entry.guest?.url ?? '', title: entry.guest?.title || entry.title || t('browser.untitled'), visible: entry.tabId === activeTabId })), activeTabId }
1757
+ }
1758
+ if (action === 'activate') {
1759
+ ctxFocus(args.tabId ?? state().tabId)
1760
+ activeTabId = args.tabId ?? state().tabId
1761
+ scheduleReport()
1762
+ return { activeTabId }
1763
+ }
1764
+ if (action === 'close') {
1765
+ ctxClose(args.tabId ?? state().tabId)
1766
+ return { closed: args.tabId ?? state().tabId }
1767
+ }
1768
+ if (action === 'reload') { guest().element.reload(); return { tabId: state().tabId, reloaded: true } }
1769
+ if (action === 'open') { ctxOpenTab(String(args.url ?? 'about:blank'), args.background === true); return { opened: args.url ?? null } }
1770
+ throw new Error(`未知 tabs 操作: ${action}`)
1771
+ },
1772
+ async snapshot(args) {
1773
+ const options = {
1774
+ interactiveOnly: args.interactiveOnly === true,
1775
+ maxDepth: args.maxDepth ?? 12,
1776
+ maxChars: args.maxChars ?? 20000,
1777
+ }
1778
+ const value = await guest().run(`window.__dsbAgent ? window.__dsbAgent.snapshot(${JSON.stringify(options)}) : null`)
1779
+ if (value === null) throw new Error('页面代理未就绪,页面可能仍在加载。')
1780
+ const lines = Array.isArray(value.lines) ? value.lines : []
1781
+ // The model reads the tree as text; the array is only useful for counts.
1782
+ return { tabId: state().tabId, url: value.url, title: value.title, text: lines.join('\n'), lineCount: lines.length, truncated: value.truncated === true }
1783
+ },
1784
+ async text(args) {
1785
+ const value = await guest().run(`window.__dsbAgent ? window.__dsbAgent.text(${JSON.stringify(args.selector ?? null)}, ${Number(args.maxChars ?? 20000)}) : null`)
1786
+ if (value === null) throw new Error('页面代理未就绪。')
1787
+ return { tabId: state().tabId, ...value }
1788
+ },
1789
+ async click(args) {
1790
+ const g = guest()
1791
+ if (typeof args.x === 'number' && typeof args.y === 'number' && args.ref === undefined && args.selector === undefined) {
1792
+ const point = { x: Math.round(args.x), y: Math.round(args.y) }
1793
+ g.element.sendInputEvent({ type: 'mouseDown', ...point, button: args.button ?? 'left', clickCount: args.clickCount ?? 1 })
1794
+ g.element.sendInputEvent({ type: 'mouseUp', ...point, button: args.button ?? 'left', clickCount: args.clickCount ?? 1 })
1795
+ return { tabId: state().tabId, clicked: `${point.x},${point.y}` }
1796
+ }
1797
+ const rect = await rectOf(args)
1798
+ const point = { x: Math.round(rect.x), y: Math.round(rect.y) }
1799
+ try {
1800
+ g.element.sendInputEvent({ type: 'mouseDown', ...point, button: args.button ?? 'left', clickCount: args.clickCount ?? 1 })
1801
+ g.element.sendInputEvent({ type: 'mouseUp', ...point, button: args.button ?? 'left', clickCount: args.clickCount ?? 1 })
1802
+ } catch {
1803
+ const selector = args.selector ?? `[data-dsb-ref="${args.ref}"]`
1804
+ await g.run(`(function(){var el=document.querySelector(${JSON.stringify(selector)});if(!el)return false;el.click();return true})()`)
1805
+ }
1806
+ return { tabId: state().tabId, clicked: args.ref ?? args.selector, point }
1807
+ },
1808
+ async type(args) {
1809
+ const g = guest()
1810
+ const text = String(args.text ?? '')
1811
+ const target = args.ref ?? args.selector ?? null
1812
+ if (target !== null) {
1813
+ const code = args.clear === false
1814
+ ? `window.__dsbAgent ? window.__dsbAgent.appendValue(${JSON.stringify(target)}, ${JSON.stringify(text)}) : false`
1815
+ : `window.__dsbAgent ? window.__dsbAgent.setValue(${JSON.stringify(target)}, ${JSON.stringify(text)}) : false`
1816
+ const ok = await g.run(code)
1817
+ if (ok !== true) throw new Error(`输入失败,元素未找到: ${target}`)
1818
+ } else {
1819
+ await g.run('document.activeElement && document.activeElement.focus && document.activeElement.focus()').catch(() => {})
1820
+ for (const character of text) {
1821
+ g.element.sendInputEvent({ type: 'char', keyCode: character })
1822
+ if (args.delayMs) await new Promise(resolve => setTimeout(resolve, args.delayMs))
1823
+ }
1824
+ }
1825
+ if (args.submit === true) {
1826
+ await g.run(`window.__dsbAgent ? window.__dsbAgent.submit(${JSON.stringify(target)}) : false`).catch(() => {})
1827
+ }
1828
+ return { tabId: state().tabId, typed: text.length, submitted: args.submit === true }
1829
+ },
1830
+ async press(args) {
1831
+ const keys = String(args.keys ?? '').trim()
1832
+ if (keys === '') throw new Error('缺少 keys。')
1833
+ const parts = keys.split('+').map(part => part.trim()).filter(Boolean)
1834
+ const key = parts.length > 0 ? parts[parts.length - 1] : keys
1835
+ const modifiers = parts.slice(0, -1).map(part => part.toLowerCase())
1836
+ const event = { keyCode: normaliseKey(key), modifiers }
1837
+ guest().element.sendInputEvent({ type: 'keyDown', ...event })
1838
+ guest().element.sendInputEvent({ type: 'keyUp', ...event })
1839
+ return { tabId: state().tabId, keys, key, modifiers }
1840
+ },
1841
+ async wait(args) {
1842
+ const g = guest()
1843
+ const deadline = Date.now() + clamp(Number(args.timeoutMs ?? 10000), 200, 60000)
1844
+ const wantHidden = args.state === 'hidden'
1845
+ while (Date.now() < deadline) {
1846
+ if (typeof args.selector === 'string' && args.selector !== '') {
1847
+ const found = await g.run(`!!document.querySelector(${JSON.stringify(args.selector)})`)
1848
+ if (found === !wantHidden) return { tabId: state().tabId, matched: 'selector', value: args.selector }
1849
+ } else if (typeof args.text === 'string' && args.text !== '') {
1850
+ const found = await g.run(`document.body.innerText.includes(${JSON.stringify(args.text)})`)
1851
+ if (found === !wantHidden) return { tabId: state().tabId, matched: 'text', value: args.text }
1852
+ } else {
1853
+ const stateName = await g.run('document.readyState')
1854
+ if (stateName === 'complete') return { tabId: state().tabId, matched: 'readyState' }
1855
+ }
1856
+ await new Promise(resolve => setTimeout(resolve, 250))
1857
+ }
1858
+ throw new Error('等待超时。')
1859
+ },
1860
+ async evaluate(args) {
1861
+ const value = await guest().run(String(args.expression ?? ''))
1862
+ return { tabId: state().tabId, value: value === undefined ? null : value }
1863
+ },
1864
+ async screenshot(args) {
1865
+ const g = guest()
1866
+ if (typeof args.selector === 'string' && args.selector !== '') {
1867
+ const rect = await g.run(`(function(){var el=document.querySelector(${JSON.stringify(args.selector)});if(!el)return null;try{el.scrollIntoView({block:'center'})}catch(e){}var r=el.getBoundingClientRect();return {x:r.left,y:r.top,width:r.width,height:r.height}})()`)
1868
+ if (rect === null) throw new Error(`元素未找到: ${args.selector}`)
1869
+ const capture = await g.capture({ x: Math.max(0, Math.floor(rect.x)), y: Math.max(0, Math.floor(rect.y)), width: Math.ceil(rect.width), height: Math.ceil(rect.height) })
1870
+ return { ...capture, name: args.name ?? 'element' }
1871
+ }
1872
+ if (args.fullPage === true) {
1873
+ const metrics = await g.run('({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight})')
1874
+ const capture = await g.capture({ x: 0, y: 0, width: Math.min(metrics.w, 4096), height: Math.min(metrics.h, 4096) })
1875
+ return { ...capture, name: args.name ?? 'fullpage' }
1876
+ }
1877
+ const capture = await g.capture()
1878
+ return { ...capture, name: args.name ?? 'screenshot' }
1879
+ },
1880
+ async regionScreenshot(args) {
1881
+ const rect = {
1882
+ x: Math.max(0, Math.round(Number(args.x ?? 0))),
1883
+ y: Math.max(0, Math.round(Number(args.y ?? 0))),
1884
+ width: Math.max(1, Math.round(Number(args.width ?? 200))),
1885
+ height: Math.max(1, Math.round(Number(args.height ?? 200))),
1886
+ }
1887
+ const capture = await guest().capture(rect)
1888
+ return { ...capture, rect, name: args.name ?? 'region' }
1889
+ },
1890
+ async find(args) {
1891
+ const action = args.action ?? 'find'
1892
+ const text = String(args.text ?? '')
1893
+ const g = guest()
1894
+ if (action === 'stop') { g.element.stopFindInPage('clearSelection'); return { stopped: true } }
1895
+ g.find.text = text
1896
+ g.element.findInPage(text, { findNext: action !== 'find', forward: action !== 'previous' })
1897
+ return { tabId: state().tabId, text, action }
1898
+ },
1899
+ async zoom(args) {
1900
+ const action = args.action ?? 'reset'
1901
+ if (action === 'in') return applyZoom(nextZoom(state().zoom ?? 1, 1))
1902
+ if (action === 'out') return applyZoom(nextZoom(state().zoom ?? 1, -1))
1903
+ if (action === 'set') return applyZoom(Number(args.factor ?? 1))
1904
+ return applyZoom(settings.defaultZoom)
1905
+ },
1906
+ async devtools(args) {
1907
+ const action = args.action ?? 'toggle'
1908
+ const current = state().devtools ?? { open: false, panel: 'console' }
1909
+ const open = action === 'open' ? true : action === 'close' ? false : !current.open
1910
+ setDevtools({ open, panel: args.panel ?? current.panel })
1911
+ return { tabId: state().tabId, open, panel: args.panel ?? current.panel }
1912
+ },
1913
+ async storage(args) {
1914
+ if ((args.action ?? 'status') === 'clear') return clearStorage()
1915
+ const report = await guest().run('window.__dsbAgent ? window.__dsbAgent.storage(false) : null').catch(() => null)
1916
+ return { tabId: state().tabId, ...(report ?? {}) }
1917
+ },
1918
+ async permissions() {
1919
+ const g = guest()
1920
+ return {
1921
+ tabId: state().tabId,
1922
+ url: g.url,
1923
+ partition: g.reservation.partition,
1924
+ policy: 'deny-all',
1925
+ permissions: ['camera', 'microphone', 'notifications', 'geolocation', 'display-capture', 'clipboard-read', 'popups', 'downloads'],
1926
+ note: '桌面壳固定拒绝站点权限与下载。',
1927
+ }
1928
+ },
1929
+ async history(args) {
1930
+ if ((args.action ?? 'list') === 'clear') {
1931
+ historyLog.length = 0
1932
+ save('history', historyLog)
1933
+ return { cleared: true }
1934
+ }
1935
+ const needle = String(args.query ?? '').toLowerCase()
1936
+ const limit = clamp(Number(args.limit ?? 50), 1, 300)
1937
+ const entries = historyLog
1938
+ .filter(entry => needle === '' || entry.url.toLowerCase().includes(needle) || String(entry.title).toLowerCase().includes(needle))
1939
+ .slice(-limit)
1940
+ .reverse()
1941
+ return { count: entries.length, entries }
1942
+ },
1943
+ async emulate(args) {
1944
+ const device = String(args.device ?? 'none')
1945
+ if (device === 'none' && typeof args.width !== 'number') return applyEmulation('none')
1946
+ if (EMULATION_PRESETS[device] !== undefined) return applyEmulation(device)
1947
+ const preset = { width: Math.max(160, Number(args.width ?? 390)), height: Math.max(200, Number(args.height ?? 844)), ua: null }
1948
+ try { guest().element.setUserAgent(effectiveUserAgent()) } catch { /* unsupported */ }
1949
+ setEmulate({ device: 'custom', ...preset })
1950
+ return { emulation: { device: 'custom', ...preset } }
1951
+ },
1952
+ async comment(args) {
1953
+ const target = args.ref ?? args.selector ?? null
1954
+ let element = state().picked
1955
+ if (target !== null) {
1956
+ element = await guest().run(`window.__dsbAgent ? window.__dsbAgent.describe(${JSON.stringify(target)}) : null`)
1957
+ }
1958
+ if (!element) throw new Error('未找到要评论的元素:先选取元素或传入 selector。')
1959
+ const payload = { ...element, url: guest().url, note: String(args.note ?? ''), tabId: state().tabId, id: `${state().tabId}-${Date.now()}`, index: commentsRef.current.length + 1, color: settings.commentColor }
1960
+ rememberComment(payload)
1961
+ bridge.report({ type: 'comment', comment: payload })
1962
+ syncMarkers()
1963
+ return payload
1964
+ },
1965
+ async addToChat(args) {
1966
+ const kind = String(args.kind ?? 'screenshot')
1967
+ if (kind === 'element') {
1968
+ const target = args.ref ?? args.selector ?? null
1969
+ let element = state().picked
1970
+ if (target !== null) {
1971
+ element = await guest().run(`window.__dsbAgent ? window.__dsbAgent.describe(${JSON.stringify(target)}) : null`)
1972
+ }
1973
+ if (!element) throw new Error('未找到元素:先选取元素或传入 selector。')
1974
+ return deliverElement(element, args.note ?? null)
1975
+ }
1976
+ if (kind === 'console') {
1977
+ const tail = consoleRef.current.slice(-40).map(entry => `[${entry.level}] ${cut(entry.text, 300)}`).join('\n')
1978
+ const note = `**${t('browser.label')}** · ${t('menu.consoleLog')}\n地址: ${guest().url}\n\`\`\`\n${tail || t('devtools.empty')}\n\`\`\``
1979
+ const result = addToComposer({ sessionId: state().sessionId, note })
1980
+ flash(result.added ? t('toast.added') : (result.reason ?? t('toast.failed')))
1981
+ return { ...result, lines: tail === '' ? 0 : tail.split('\n').length }
1982
+ }
1983
+ if (kind === 'region') {
1984
+ const rect = {
1985
+ x: Math.max(0, Number(args.x ?? 0)),
1986
+ y: Math.max(0, Number(args.y ?? 0)),
1987
+ width: Math.max(1, Number(args.width ?? 300)),
1988
+ height: Math.max(1, Number(args.height ?? 300)),
1989
+ }
1990
+ return addCapture(rect, 'region')
1991
+ }
1992
+ return addCapture(null, 'screenshot')
1993
+ },
1994
+ }
1995
+
1996
+ return {
1997
+ tabId,
1998
+ sessionId,
1999
+ /** Live guest accessor: the ref is filled asynchronously by the mount effect. */
2000
+ get guest() { return guestRef.current },
2001
+ get title() { return guestRef.current?.title ?? '' },
2002
+ async handle(op, args) {
2003
+ const handler = handlers[op]
2004
+ if (handler === undefined) throw new Error(`未知浏览器操作: ${op}`)
2005
+ if (guestRef.current === null && op !== 'tabs') throw new Error('浏览器尚未就绪。')
2006
+ return handler(args ?? {})
2007
+ },
2008
+ }
2009
+ }
2010
+
2011
+ /* --------------------------------------------------------- host routing */
2012
+ useEffect(() => {
2013
+ bridge.onCommand = async (op, args, tabIdWanted) => {
2014
+ if (op === 'tabs') {
2015
+ const owner = instances.get(activeTabId) ?? instances.get(tabId) ?? [...instances.values()][0]
2016
+ if (owner === undefined) throw new Error('当前没有可用的浏览器页签。')
2017
+ return owner.handle(op, args)
2018
+ }
2019
+ const target = tabIdWanted === null ? instances.get(activeTabId) : instances.get(tabIdWanted)
2020
+ const fallback = target ?? (instances.size === 1 ? [...instances.values()][0] : undefined)
2021
+ if (fallback === undefined) throw new Error('当前没有可用的浏览器页签:请先打开 Browser 页签。')
2022
+ return fallback.handle(op, args)
2023
+ }
2024
+ return () => { bridge.onCommand = null }
2025
+ }, [tabId])
2026
+
2027
+ /* Ctrl+D bookmarks the current page and Ctrl+H opens history: both
2028
+ accelerators are advertised in the menu, so they have to work too. */
2029
+ const addBookmark = useCallback(() => {
2030
+ const entry = { url: guestRef.current?.url ?? '', title: guestRef.current?.title || url, ts: Date.now() }
2031
+ /* One bookmark per address: an existing entry is refreshed in place. */
2032
+ const at = bookmarks.findIndex(item => item.url === entry.url)
2033
+ if (at === -1) bookmarks.push(entry)
2034
+ else bookmarks[at] = entry
2035
+ save('bookmarks', bookmarks)
2036
+ flash(t('toast.saved'))
2037
+ }, [bookmarks, save, flash, t, url])
2038
+
2039
+ /* ------------------------------------------------------------ shortcuts */
2040
+ useEffect(() => {
2041
+ const onKey = (event) => {
2042
+ if (!visible) return
2043
+ const meta = event.ctrlKey || event.metaKey
2044
+ const key = String(event.key || '')
2045
+ if (key === 'F12') { event.preventDefault(); setDevtools(current => ({ open: !current.open, panel: current.panel })); return }
2046
+ if (meta && key.toLowerCase() === 'f') { event.preventDefault(); setFindOpen(true); return }
2047
+ if (meta && (key === '=' || key === '+')) { event.preventDefault(); zoomStep(1); return }
2048
+ if (meta && key === '-') { event.preventDefault(); zoomStep(-1); return }
2049
+ if (meta && key === '0') { event.preventDefault(); applyZoom(settings.defaultZoom); return }
2050
+ if (meta && key.toLowerCase() === 'h') { event.preventDefault(); setPopover('history'); return }
2051
+ if (meta && key.toLowerCase() === 'd') { event.preventDefault(); addBookmark(); return }
2052
+ if (key === 'Escape') {
2053
+ setComment(null)
2054
+ setHint(null)
2055
+ setRegion(null)
2056
+ setMenu(null)
2057
+ setPopover(null)
2058
+ /* Escape also closes the find bar, like Chromium does. */
2059
+ if (findOpen) {
2060
+ setFindOpen(false)
2061
+ runFind('')
2062
+ }
2063
+ }
2064
+ }
2065
+ window.addEventListener('keydown', onKey)
2066
+ return () => window.removeEventListener('keydown', onKey)
2067
+ }, [visible, zoomStep, applyZoom, findOpen, runFind, addBookmark])
2068
+
2069
+ /* Compatibility UA lives in module scope because the Guest is created
2070
+ outside React; this keeps the live element in sync with the setting. */
2071
+ useEffect(() => {
2072
+ compatUaEnabled = compatUa
2073
+ settings.compatUa = compatUa
2074
+ save('settings', settings)
2075
+ const current = guestRef.current
2076
+ if (current !== null && (liveRef.current.emulate ?? null) === null) {
2077
+ try { current.element.setUserAgent(effectiveUserAgent()) } catch { /* unsupported */ }
2078
+ }
2079
+ }, [compatUa])
2080
+
2081
+ /* Dismiss the menu and popovers on an outside click, like a real browser. */
2082
+ useEffect(() => {
2083
+ if (menu === null && popover === null) return undefined
2084
+ const onDown = (event) => {
2085
+ const target = event.target
2086
+ if (target instanceof Element && target.closest('.dsb-pop') !== null) return
2087
+ setMenu(null)
2088
+ setPopover(null)
2089
+ }
2090
+ document.addEventListener('pointerdown', onDown, true)
2091
+ return () => document.removeEventListener('pointerdown', onDown, true)
2092
+ }, [menu, popover])
2093
+
2094
+ /* -------------------------------------------------------- address entry */
2095
+ const navigateTo = useCallback((raw) => {
2096
+ const text = String(raw ?? '').trim()
2097
+ if (text === '') return
2098
+ const guest = guestRef.current
2099
+ if (guest === null) return
2100
+ const target = /^(https?|file|about|data):/iu.test(text)
2101
+ ? text
2102
+ : (/^[\w-]+(\.[\w-]+)+/u.test(text) ? `https://${text}` : `https://www.bing.com/search?q=${encodeURIComponent(text)}`)
2103
+ guest.load(target, 15000).catch((error) => setFailure(String(error && error.message ? error.message : error)))
2104
+ }, [])
2105
+
2106
+ /* ---------------------------------------------------------- region pick */
2107
+ const beginRegion = useCallback(() => {
2108
+ setRegion({ startX: 0, startY: 0, x: 0, y: 0, width: 0, height: 0, dragging: false })
2109
+ setHint(t('region.hint'))
2110
+ }, [])
2111
+
2112
+ const regionPoint = (event) => {
2113
+ const stage = event.currentTarget.getBoundingClientRect()
2114
+ return { x: Math.round(event.clientX - stage.left), y: Math.round(event.clientY - stage.top) }
2115
+ }
2116
+
2117
+ const regionHandlers = {
2118
+ onMouseDown: (event) => {
2119
+ event.preventDefault()
2120
+ const point = regionPoint(event)
2121
+ const next = { startX: point.x, startY: point.y, x: point.x, y: point.y, width: 0, height: 0, dragging: true }
2122
+ regionRef.current = next
2123
+ setRegion(next)
2124
+ },
2125
+ onMouseMove: (event) => {
2126
+ // The point has to be read from the live event: inside a state updater
2127
+ // React has already cleared `currentTarget`.
2128
+ const current = regionRef.current
2129
+ if (current === null || current.dragging !== true) return
2130
+ const point = regionPoint(event)
2131
+ const next = {
2132
+ ...current,
2133
+ x: Math.min(current.startX, point.x),
2134
+ y: Math.min(current.startY, point.y),
2135
+ width: Math.abs(point.x - current.startX),
2136
+ height: Math.abs(point.y - current.startY),
2137
+ }
2138
+ regionRef.current = next
2139
+ setRegion(next)
2140
+ },
2141
+ onMouseUp: () => {
2142
+ // Read the drag from the ref: a state updater must stay pure, and the
2143
+ // box has to be known before the capture starts.
2144
+ const box = regionRef.current
2145
+ regionRef.current = null
2146
+ setRegion(null)
2147
+ if (box === null || box.dragging !== true) return
2148
+ if (box.width < 4 || box.height < 4) return
2149
+ setHint(null)
2150
+ addCapture({ x: box.x, y: box.y, width: box.width, height: box.height }, 'region').catch((error) => flash(error?.message ?? t('toast.failed')))
2151
+ },
2152
+ onMouseLeave: () => { regionRef.current = null; setRegion(null) },
2153
+ }
2154
+
2155
+ /* ------------------------------------------------------------- pickers */
2156
+ const startPicker = useCallback((mode) => {
2157
+ const guest = guestRef.current
2158
+ if (guest === null) return
2159
+ setHint(mode === 'comment' ? t('comment.hint') : t('pick.hint'))
2160
+ guest.run(`window.__dsbAgent && window.__dsbAgent.startPicker(${JSON.stringify(mode)})`).catch(() => {})
2161
+ }, [])
2162
+
2163
+ /* -------------------------------------------------------------- actions */
2164
+ const actions = {
2165
+ newTab: () => ctxOpenTab(null, false),
2166
+ zoomIn: () => zoomStep(1),
2167
+ zoomOut: () => zoomStep(-1),
2168
+ zoomReset: () => applyZoom(settings.defaultZoom),
2169
+ find: () => setFindOpen(true),
2170
+ emulate: () => setPopover('emulate'),
2171
+ external: () => {
2172
+ const current = guestRef.current?.url ?? ''
2173
+ if (current !== '') {
2174
+ try { window.open(current, '_blank') } catch { /* shell refused */ }
2175
+ }
2176
+ },
2177
+ history: () => setPopover('history'),
2178
+ bookmark: () => addBookmark(),
2179
+ bookmarks: () => setPopover('bookmarks'),
2180
+ permissions: () => setPopover('permissions'),
2181
+ clearStorage: () => { clearStorage() },
2182
+ settings: () => setPopover('settings'),
2183
+ screenshot: () => { addCapture(null, 'screenshot').catch((error) => flash(error?.message ?? t('toast.failed'))) },
2184
+ region: () => beginRegion(),
2185
+ pick: () => startPicker('pick'),
2186
+ comment: () => startPicker('comment'),
2187
+ consoleLog: () => addNote(consoleTailNote(consoleRef.current, guestRef.current?.url ?? '')),
2188
+ devtools: () => setDevtools(current => ({ open: !current.open, panel: current.panel })),
2189
+ copyUrl: () => {
2190
+ const current = guestRef.current?.url ?? url
2191
+ navigator.clipboard?.writeText(current).then(() => flash(t('toast.copied'))).catch(() => {})
2192
+ },
2193
+ }
2194
+
2195
+ const submitComment = useCallback(() => {
2196
+ const current = liveRef.current.comment
2197
+ if (current === null || current === undefined) return
2198
+ deliverElement(current.element, current.note.trim() === '' ? null : current.note.trim())
2199
+ setComment(null)
2200
+ setPicked(null)
2201
+ }, [deliverElement])
2202
+
2203
+ /* ------------------------------------------------------------ rendering */
2204
+ if (failure === 'no-bridge') {
2205
+ return h('div', { className: 'dsb-root dsb-muted', style: { padding: 12 } }, t('noBridge'))
2206
+ }
2207
+
2208
+ // The guest is mounted once into a stable container: Electron keeps the
2209
+ // guest layer pinned to the element it was attached to, so re-parenting
2210
+ // it for emulation would leave the page drawn in the wrong place.
2211
+ const stage = h('div', { className: 'dsb-stage', 'data-emulate': emulate === null ? 'false' : 'true' },
2212
+ h('div', { className: 'dsb-view', ref: viewRef, 'data-hidden': visible ? 'false' : 'true' }),
2213
+ emulate === null ? null : h('div', { className: 'dsb-hint' }, `${emulate.device} · ${emulate.width}×${emulate.height}`),
2214
+ region !== null ? h('div', {
2215
+ className: 'dsb-region',
2216
+ onMouseDown: regionHandlers.onMouseDown,
2217
+ onMouseMove: regionHandlers.onMouseMove,
2218
+ onMouseUp: regionHandlers.onMouseUp,
2219
+ onMouseLeave: regionHandlers.onMouseLeave,
2220
+ }, region.width > 0 ? h('div', { className: 'dsb-region-box', style: { left: region.x, top: region.y, width: region.width, height: region.height } }) : null) : null,
2221
+ hint !== null ? h('div', { className: 'dsb-hint' }, hint) : null,
2222
+ toast !== null ? h('div', { className: 'dsb-toast' }, toast) : null,
2223
+ comment !== null ? h('div', { className: 'dsb-comment' },
2224
+ h('div', { className: 'dsb-muted', style: { marginBottom: 4 } }, `${comment.element.tag} · ${cut(comment.element.selector, 56)}`),
2225
+ h('textarea', {
2226
+ value: comment.note,
2227
+ placeholder: t('comment.placeholder'),
2228
+ autoFocus: true,
2229
+ onChange: (event) => setComment({ element: comment.element, note: event.target.value }),
2230
+ }),
2231
+ h('div', { style: { display: 'flex', gap: 4, marginTop: 6 } },
2232
+ h('button', { className: 'dsb-btn', onClick: submitComment }, t('comment.submit')),
2233
+ h('button', { className: 'dsb-btn', onClick: () => setComment(null) }, t('comment.cancel')),
2234
+ ),
2235
+ ) : null,
2236
+ menu !== null ? renderMenu(menu, actions, () => setMenu(null)) : null,
2237
+ popover !== null ? renderPopover(popover, {
2238
+ close: () => setPopover(null),
2239
+ url: guestRef.current?.url ?? url,
2240
+ partition: guestRef.current?.reservation?.partition ?? '',
2241
+ zoom,
2242
+ applyZoom,
2243
+ flash,
2244
+ history: historyLog,
2245
+ bookmarks,
2246
+ navigate: (value) => { setPopover(null); navigateTo(value) },
2247
+ emulateNow: (device) => { setPopover(null); if (device === 'none') applyEmulation('none'); else applyEmulation(device) },
2248
+ compatUa,
2249
+ setCompatUa,
2250
+ }) : null,
2251
+ )
2252
+
2253
+ return h('div', { className: 'dsb-root', ref: rootRef },
2254
+ h('div', { className: 'dsb-bar' },
2255
+ h('button', { className: 'dsb-btn', title: t('action.back'), disabled: nav.canGoBack !== true, onClick: () => guestRef.current?.element.goBack() }, '‹'),
2256
+ h('button', { className: 'dsb-btn', title: t('action.forward'), disabled: nav.canGoForward !== true, onClick: () => guestRef.current?.element.goForward() }, '›'),
2257
+ h('button', {
2258
+ className: 'dsb-btn',
2259
+ title: loading ? t('action.stop') : t('action.reload'),
2260
+ onClick: () => {
2261
+ const guest = guestRef.current
2262
+ if (guest === null) return
2263
+ if (guest.loading) guest.element.stop()
2264
+ else guest.element.reload()
2265
+ },
2266
+ }, loading ? '×' : '⟳'),
2267
+ h('input', {
2268
+ className: 'dsb-addr',
2269
+ value: url === 'about:blank' ? '' : url,
2270
+ placeholder: t('addr.placeholder'),
2271
+ spellCheck: false,
2272
+ onChange: (event) => setUrl(event.target.value),
2273
+ onFocus: (event) => event.currentTarget.select(),
2274
+ onKeyDown: (event) => {
2275
+ if (event.key === 'Enter') { event.preventDefault(); navigateTo(event.currentTarget.value); event.currentTarget.blur() }
2276
+ if (event.key === 'Escape') event.currentTarget.blur()
2277
+ },
2278
+ }),
2279
+ h('button', { className: 'dsb-btn', title: t('action.go'), onClick: () => navigateTo(url === 'about:blank' ? '' : url) }, '↵'),
2280
+ h('span', { className: 'dsb-sep' }),
2281
+ h('button', { className: 'dsb-btn', title: t('action.screenshot'), onClick: actions.screenshot }, '⤓'),
2282
+ h('button', { className: 'dsb-btn', title: t('action.region'), onClick: beginRegion }, '▣'),
2283
+ h('button', { className: 'dsb-btn', title: t('action.pick'), onClick: () => startPicker('pick') }, '⌖'),
2284
+ h('button', { className: 'dsb-btn', title: t('action.comment'), onClick: () => startPicker('comment') }, '✎'),
2285
+ h('button', { className: 'dsb-btn', title: t('action.devtools'), 'data-on': devtools.open ? 'true' : 'false', onClick: () => setDevtools(current => ({ open: !current.open, panel: current.panel })) }, '⚙'),
2286
+ h('button', {
2287
+ className: 'dsb-btn',
2288
+ title: t('browser.menu'),
2289
+ onClick: (event) => {
2290
+ const rect = event.currentTarget.getBoundingClientRect()
2291
+ setMenu({ x: rect.right, y: rect.bottom })
2292
+ },
2293
+ }, '☰'),
2294
+ ),
2295
+ findOpen ? h('div', { className: 'dsb-find' },
2296
+ h('input', {
2297
+ autoFocus: true,
2298
+ value: findText,
2299
+ placeholder: t('find.placeholder'),
2300
+ onChange: (event) => { setFindText(event.target.value); runFind(event.target.value, 'new') },
2301
+ onKeyDown: (event) => {
2302
+ if (event.key === 'Enter') { event.preventDefault(); runFind(findText, event.shiftKey ? 'previous' : 'next') }
2303
+ if (event.key === 'Escape') { setFindOpen(false); runFind('') }
2304
+ },
2305
+ }),
2306
+ h('span', { className: 'dsb-muted' }, findState.total === 0 ? t('find.none') : t('find.count', { n: findState.active, total: findState.total })),
2307
+ h('button', { className: 'dsb-btn', onClick: () => { setFindOpen(false); runFind('') } }, '×'),
2308
+ ) : null,
2309
+ h('div', { style: { display: 'flex', flex: '1 1 auto', minHeight: 0, flexDirection: 'column' } },
2310
+ stage,
2311
+ devtools.open ? renderDevtools({
2312
+ panel: devtools.panel,
2313
+ consoleLog,
2314
+ networkLog,
2315
+ picked,
2316
+ evalText,
2317
+ evalResult,
2318
+ onPanel: (panel) => setDevtools({ open: true, panel }),
2319
+ onClose: () => setDevtools({ open: false, panel: devtools.panel }),
2320
+ onClear: () => { consoleRef.current = []; setConsoleLog([]); networkRef.current = []; setNetworkLog([]) },
2321
+ onEval: (text) => {
2322
+ setEvalText(text)
2323
+ const guest = guestRef.current
2324
+ if (guest === null) return
2325
+ guest.run(text).then((value) => setEvalResult({ ok: true, value: value === undefined ? null : value })).catch((error) => setEvalResult({ ok: false, error: String(error && error.message ? error.message : error) }))
2326
+ },
2327
+ }) : null,
2328
+ ),
2329
+ ready ? null : h('div', { className: 'dsb-hint' }, t('status.loading')),
2330
+ )
2331
+ }
2332
+
2333
+ /* ----------------------------------------------------------- UI helpers */
2334
+
2335
+ /** Fit a device frame into the stage. */
2336
+ function emulateScale(preset) {
2337
+ if (preset === null || preset === undefined) return 1
2338
+ const available = (typeof window === 'undefined' ? 800 : window.innerHeight) * 0.62
2339
+ return clamp(available / preset.height, 0.35, 1)
2340
+ }
2341
+
2342
+ /** Map a browser key name onto Electron's sendInputEvent keyCode. */
2343
+ function normaliseKey(key) {
2344
+ const named = {
2345
+ Enter: 'Return', Escape: 'Escape', Tab: 'Tab', Backspace: 'Backspace', Delete: 'Delete',
2346
+ ArrowUp: 'Up', ArrowDown: 'Down', ArrowLeft: 'Left', ArrowRight: 'Right',
2347
+ Home: 'Home', End: 'End', PageUp: 'Prior', PageDown: 'Next', ' ': 'Space', Space: 'Space',
2348
+ }
2349
+ return named[key] ?? key
2350
+ }
2351
+
2352
+ /** Console excerpt inserted by "console log to chat". */
2353
+ function consoleTailNote(entries, url) {
2354
+ const tail = entries.slice(-40).map(entry => `[${entry.level}] ${cut(entry.text, 300)}`).join('\n')
2355
+ return `**${t('browser.label')}** · ${t('menu.consoleLog')}\n地址: ${url}\n\`\`\`\n${tail || t('devtools.empty')}\n\`\`\``
2356
+ }
2357
+
2358
+ /** The right-click / menu-button menu, mirroring the product browser menu. */
2359
+ function renderMenu(menu, actions, close) {
2360
+ const items = [
2361
+ ['newTab', 'menu.newTab', 'Ctrl+T'],
2362
+ 'sep',
2363
+ ['zoomIn', 'menu.zoomIn', 'Ctrl+='],
2364
+ ['zoomOut', 'menu.zoomOut', 'Ctrl+-'],
2365
+ ['zoomReset', 'menu.zoomReset', 'Ctrl+NumPad0'],
2366
+ 'sep',
2367
+ ['find', 'menu.find', 'Ctrl+F'],
2368
+ ['emulate', 'menu.emulate', ''],
2369
+ ['external', 'menu.external', ''],
2370
+ 'sep',
2371
+ ['history', 'menu.history', 'Ctrl+H'],
2372
+ ['bookmark', 'menu.bookmark', 'Ctrl+D'],
2373
+ ['bookmarks', 'menu.bookmarks', ''],
2374
+ ['permissions', 'menu.permissions', ''],
2375
+ ['clearStorage', 'menu.clearStorage', ''],
2376
+ 'sep',
2377
+ ['screenshot', 'menu.screenshot', ''],
2378
+ ['region', 'menu.region', ''],
2379
+ ['pick', 'menu.pick', ''],
2380
+ ['comment', 'menu.comment', ''],
2381
+ ['consoleLog', 'menu.consoleLog', ''],
2382
+ ['devtools', 'menu.devtools', 'F12'],
2383
+ ['copyUrl', 'menu.copyUrl', ''],
2384
+ 'sep',
2385
+ ['settings', 'menu.settings', ''],
2386
+ ]
2387
+ // The menu is anchored at a viewport point (a right click inside the page or the
2388
+ // toolbar button), so it lives in the fixed layer and is clamped to the window.
2389
+ // Popovers below keep the stage-relative absolute placement.
2390
+ const width = 270
2391
+ const height = 420
2392
+ const anchorX = Math.round(menu.x)
2393
+ const anchorY = Math.round(menu.y)
2394
+ const left = anchorX + width + 10 > window.innerWidth
2395
+ ? Math.max(8, anchorX - width - 2)
2396
+ : Math.max(8, anchorX + 2)
2397
+ const top = Math.max(34, Math.min(anchorY, window.innerHeight - height - 8))
2398
+ return h('div', {
2399
+ className: 'dsb-pop dsb-pop-menu',
2400
+ style: { left, top },
2401
+ onMouseLeave: close,
2402
+ }, items.map((item, index) => {
2403
+ if (item === 'sep') return h('div', { key: `sep${index}`, style: { height: 1, margin: '4px 2px', background: 'color-mix(in srgb,currentColor 14%,transparent)' } })
2404
+ const [id, key, shortcut] = item
2405
+ return h('button', {
2406
+ key: id,
2407
+ className: 'dsb-row',
2408
+ onClick: () => {
2409
+ close()
2410
+ const run = actions[id]
2411
+ if (typeof run === 'function') run()
2412
+ },
2413
+ }, h('span', { className: 'dsb-fill' }, t(key)), shortcut ? h('span', { className: 'dsb-muted' }, shortcut) : null)
2414
+ }))
2415
+ }
2416
+
2417
+ /** History, bookmarks, permissions, settings and emulation popovers. */
2418
+ function renderPopover(kind, api) {
2419
+ const shell = (title, body) => h('div', { className: 'dsb-pop' },
2420
+ h('div', { style: { display: 'flex', alignItems: 'center', marginBottom: 4 } },
2421
+ h('strong', { style: { flex: '1 1 auto', fontWeight: 600 } }, title),
2422
+ h('button', { className: 'dsb-btn', onClick: api.close, title: t('title.close') }, '×'),
2423
+ ),
2424
+ body,
2425
+ )
2426
+ if (kind === 'history') {
2427
+ const entries = [...api.history].reverse().slice(0, 60)
2428
+ return shell(t('history.title'), h('div', { className: 'dsb-list' },
2429
+ entries.length === 0
2430
+ ? h('div', { className: 'dsb-muted' }, t('history.empty'))
2431
+ : entries.map((entry, index) => h('button', {
2432
+ key: `${entry.ts}-${index}`,
2433
+ className: 'dsb-entry',
2434
+ title: entry.url,
2435
+ onClick: () => api.navigate(entry.url),
2436
+ }, h('strong', null, cut(entry.title || entry.url, 60)), h('span', null, cut(entry.url, 80)))),
2437
+ h('button', {
2438
+ className: 'dsb-btn',
2439
+ style: { marginTop: 4 },
2440
+ onClick: () => { api.history.length = 0; save('history', api.history); api.flash(t('toast.cleared')) },
2441
+ }, t('history.clear')),
2442
+ ))
2443
+ }
2444
+ if (kind === 'bookmarks') {
2445
+ const entries = [...api.bookmarks].reverse().slice(0, 60)
2446
+ return shell(t('bookmarks.title'), h('div', { className: 'dsb-list' },
2447
+ entries.length === 0
2448
+ ? h('div', { className: 'dsb-muted' }, t('bookmarks.empty'))
2449
+ : entries.map((entry, index) => h('button', {
2450
+ key: `${entry.ts}-${index}`,
2451
+ className: 'dsb-entry',
2452
+ title: entry.url,
2453
+ onClick: () => api.navigate(entry.url),
2454
+ }, h('strong', null, cut(entry.title || entry.url, 60)), h('span', null, cut(entry.url, 80)))),
2455
+ ))
2456
+ }
2457
+ if (kind === 'permissions') {
2458
+ return shell(t('permissions.title'), h('div', null,
2459
+ h('div', { className: 'dsb-muted' }, t('permissions.site')),
2460
+ h('div', { style: { marginBottom: 6, wordBreak: 'break-all' } }, api.url || '—'),
2461
+ h('div', { className: 'dsb-muted' }, t('permissions.partition')),
2462
+ h('div', { style: { marginBottom: 6, wordBreak: 'break-all' } }, api.partition || '—'),
2463
+ h('div', { className: 'dsb-muted', style: { lineHeight: 1.5 } }, t('permissions.body')),
2464
+ ))
2465
+ }
2466
+ if (kind === 'settings') {
2467
+ return shell(t('settings.title'), h('div', { style: { display: 'flex', flexDirection: 'column', gap: 6 } },
2468
+ h('label', { style: { display: 'flex', alignItems: 'center', gap: 6 } },
2469
+ h('input', {
2470
+ type: 'checkbox',
2471
+ checked: api.compatUa === true,
2472
+ onChange: (event) => api.setCompatUa(event.target.checked),
2473
+ }),
2474
+ h('span', null, t('settings.compatUa')),
2475
+ ),
2476
+ h('div', { className: 'dsb-muted' }, t('settings.compatHint')),
2477
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 4 } },
2478
+ h('span', null, t('settings.defaultZoom')),
2479
+ h('button', { className: 'dsb-btn', onClick: () => api.applyZoom(nextZoom(api.zoom, -1)) }, '−'),
2480
+ h('span', { style: { minWidth: 42, textAlign: 'center' } }, `${Math.round(api.zoom * 100)}%`),
2481
+ h('button', { className: 'dsb-btn', onClick: () => api.applyZoom(nextZoom(api.zoom, 1)) }, '+'),
2482
+ ),
2483
+ h('div', { className: 'dsb-muted' }, t('settings.zoomHint')),
2484
+ ))
2485
+ }
2486
+ if (kind === 'emulate') {
2487
+ const devices = ['none', 'iphone-14', 'pixel-7', 'galaxy-s23', 'ipad-mini', 'desktop-720']
2488
+ return shell(t('emulate.title'), h('div', { className: 'dsb-list' },
2489
+ devices.map(device => h('button', {
2490
+ key: device,
2491
+ className: 'dsb-entry',
2492
+ onClick: () => api.emulateNow(device),
2493
+ }, h('strong', null, device === 'none' ? t('emulate.none') : device === 'desktop-720' ? t('emulate.desktop') : device))),
2494
+ ))
2495
+ }
2496
+ return null
2497
+ }
2498
+
2499
+ /** The DevTools panel: console, elements, network, eval. */
2500
+ function renderDevtools(model) {
2501
+ const tabs = [
2502
+ ['console', 'devtools.console'],
2503
+ ['elements', 'devtools.elements'],
2504
+ ['network', 'devtools.network'],
2505
+ ['eval', 'devtools.eval'],
2506
+ ]
2507
+ let body = null
2508
+ if (model.panel === 'console') {
2509
+ body = model.consoleLog.length === 0
2510
+ ? h('div', { className: 'dsb-log dsb-muted' }, t('devtools.empty'))
2511
+ : h('div', { className: 'dsb-log' }, model.consoleLog.slice(-400).map((entry, index) => h('div', {
2512
+ key: `console-${index}`,
2513
+ className: 'dsb-line',
2514
+ 'data-level': entry.level ?? 'info',
2515
+ }, h('em', null, new Date(entry.ts ?? Date.now()).toLocaleTimeString()), h('span', null, cut(entry.text ?? '', 2000)))))
2516
+ } else if (model.panel === 'network') {
2517
+ body = model.networkLog.length === 0
2518
+ ? h('div', { className: 'dsb-log dsb-muted' }, t('devtools.empty'))
2519
+ : h('div', { className: 'dsb-log' }, model.networkLog.slice(-200).map((entry, index) => h('div', {
2520
+ key: `network-${index}`,
2521
+ className: 'dsb-line',
2522
+ 'data-level': entry.ok === true ? 'info' : 'error',
2523
+ }, h('em', null, String(entry.status ?? 0)), h('span', null, `${entry.method ?? 'GET'} ${cut(entry.url ?? '', 240)} · ${entry.ms ?? 0}ms`))))
2524
+ } else if (model.panel === 'elements') {
2525
+ body = h('div', { className: 'dsb-eval' },
2526
+ h('div', { className: 'dsb-muted' }, t('devtools.elementsHint')),
2527
+ h('pre', { className: 'dsb-log' }, model.picked === null ? '' : JSON.stringify(model.picked, null, 2)),
2528
+ )
2529
+ } else {
2530
+ body = h('div', { className: 'dsb-eval' },
2531
+ h('textarea', {
2532
+ value: model.evalText,
2533
+ placeholder: t('devtools.hint'),
2534
+ onChange: (event) => model.onEval(event.target.value),
2535
+ onKeyDown: (event) => {
2536
+ if (event.key === 'Enter' && !event.shiftKey) { event.preventDefault(); model.onEval(event.currentTarget.value) }
2537
+ },
2538
+ }),
2539
+ h('pre', { className: 'dsb-log', style: { flex: '0 1 auto', maxHeight: 140 } },
2540
+ model.evalResult === null ? '' : model.evalResult.ok ? JSON.stringify(model.evalResult.value, null, 2) : `⚠ ${model.evalResult.error}`),
2541
+ )
2542
+ }
2543
+ return h('div', { className: 'dsb-devtools' },
2544
+ h('div', { className: 'dsb-tabs' },
2545
+ h('strong', { style: { padding: '0 6px', fontWeight: 600, opacity: 0.8 } }, t('devtools.title')),
2546
+ tabs.map(([id, key]) => h('button', {
2547
+ key: id,
2548
+ className: 'dsb-tab',
2549
+ 'data-on': model.panel === id ? 'true' : 'false',
2550
+ onClick: () => model.onPanel(id),
2551
+ }, t(key))),
2552
+ h('span', { className: 'dsb-fill' }),
2553
+ h('button', { className: 'dsb-btn', onClick: model.onClear }, t('devtools.clear')),
2554
+ h('button', { className: 'dsb-btn', onClick: model.onClose, title: t('title.close') }, '×'),
2555
+ ),
2556
+ body,
2557
+ )
2558
+ }
2559
+
2560
+ /* ------------------------------------------------------- sidebar bridges */
2561
+
2562
+ /** Open a browser tab (or focus the active one) through the sidebar service. */
2563
+ function ctxOpenTab(url, background, external) {
2564
+ const ctx = serviceContext
2565
+ if (ctx === null) return
2566
+ try {
2567
+ const sidebar = ctx.get('sidebarRight')
2568
+ if (sidebar && typeof sidebar.openTab === 'function') {
2569
+ const params = url === null ? {} : external === null || external === undefined ? { url } : { url, external }
2570
+ sidebar.openTab('browser', url === null ? {} : { params, revealIfOpened: background !== true })
2571
+ return
2572
+ }
2573
+ } catch { /* fall through */ }
2574
+ }
2575
+
2576
+ /**
2577
+ * The Session the user is looking at: the ui-session adapter the sidebar
2578
+ * follows, then the panel's data attribute as a fallback.
2579
+ * @returns {string|null} session id.
2580
+ */
2581
+ function readSessionId() {
2582
+ try {
2583
+ const key = serviceContext?.get?.('uiSession')?.adapter?.current?.getSnapshot?.().key
2584
+ if (typeof key === 'string' && key !== '') return key
2585
+ } catch { /* the service is optional in some carriers */ }
2586
+ const values = new Set()
2587
+ for (const node of document.querySelectorAll('[data-sidebar-right-session]')) {
2588
+ const id = node.getAttribute('data-sidebar-right-session')
2589
+ if (typeof id === 'string' && id !== '') values.add(id)
2590
+ }
2591
+ if (values.size === 1) { const [only] = values; return only }
2592
+ return null
2593
+ }
2594
+
2595
+ function ctxFocus(tabId) {
2596
+ try { serviceContext?.get('sidebarRight')?.focus?.(tabId) } catch { /* optional */ }
2597
+ }
2598
+
2599
+ function ctxClose(tabId) {
2600
+ try { serviceContext?.get('sidebarRight')?.close?.(tabId) } catch { /* optional */ }
2601
+ }
2602
+
2603
+ /* ------------------------------------------------------------ plugin API */
2604
+
2605
+ return {
2606
+ inject: ['slots', 'sidebarRightTabs', 'sessions', 'conversation'],
2607
+
2608
+ apply(ctx) {
2609
+ serviceContext = ctx
2610
+
2611
+ const desktop = typeof window !== 'undefined' ? window.dshDesktop : undefined
2612
+ const bridgeable = desktop !== undefined && desktop.protocolVersion === 1 && desktop.browser !== undefined
2613
+
2614
+ const style = document.createElement('style')
2615
+ style.dataset.plugin = PLUGIN_ID
2616
+ style.textContent = styles
2617
+ document.head.appendChild(style)
2618
+ ctx.effect(() => () => { style.remove() }, 'shared-browser styles')
2619
+
2620
+ if (!bridgeable) {
2621
+ // The Web carrier renders the browser as an iframe the app manages; a
2622
+ // guest-driven takeover would break it, so the built-in stays in place.
2623
+ console.info('[dsh-shared-browser] 没有桌面浏览器桥,保留内置浏览器。')
2624
+ return
2625
+ }
2626
+
2627
+ ctx.inject(['sessions'], (sessionCtx) => {
2628
+ try {
2629
+ const list = sessionCtx.sessions.list.getSnapshot()
2630
+ const first = Object.values(list.byId ?? {})[0]
2631
+ bridge.sessionId = first?.id ?? null
2632
+ } catch { /* the bridge still works without a pre-known session */ }
2633
+ })
2634
+
2635
+ bridge.start()
2636
+ /* The Host may ask for a browser tab before the user ever opened one. */
2637
+ bridge.openPane = (args) => {
2638
+ const target = typeof args.url === 'string' && args.url !== '' ? args.url : 'about:blank'
2639
+ const external = typeof args.external === 'string' && args.external !== '' ? args.external : null
2640
+ ctxOpenTab(target, false, external)
2641
+ }
2642
+ ctx.effect(() => () => { bridge.source?.close?.() }, 'shared-browser stream')
2643
+
2644
+ // Read-only diagnostics for support and for the browser tools' own tests.
2645
+ if (typeof window !== 'undefined' && window.__dshBrowserDebug === undefined) {
2646
+ window.__dshBrowserDebug = {
2647
+ version: VERSION,
2648
+ session: () => bridge.sessionId,
2649
+ probe: (sessionId) => {
2650
+ const id = sessionId ?? bridge.sessionId ?? null
2651
+ const step = (fn) => { try { return fn() } catch (error) { return `ERR ${String(error && error.message ? error.message : error)}` } }
2652
+ const sessions = step(() => serviceContext?.get?.('sessions'))
2653
+ return {
2654
+ id,
2655
+ sessions: step(() => typeof sessions?.scope),
2656
+ strictGet: step(() => String(typeof serviceContext?.get?.('conversation'))),
2657
+ proxy: step(() => String(typeof serviceContext?.conversation)),
2658
+ scopeId: step(() => sessions?.scope?.(id) === undefined ? 'undefined' : 'ctx'),
2659
+ input: step(() => String(typeof serviceContext?.conversation?.input?.for)),
2660
+ tabs: [...instances.keys()],
2661
+ }
2662
+ },
2663
+ }
2664
+ }
2665
+
2666
+ ctx.inject(['sidebarRightTabs', 'slots'], (uiCtx) => {
2667
+ uiCtx.effect(() => uiCtx.sidebarRightTabs.register({
2668
+ id: PLUGIN_ID,
2669
+ kind: 'browser',
2670
+ multiple: true,
2671
+ keepMounted: true,
2672
+ priority: 'extension',
2673
+ title: () => t('browser.label'),
2674
+ // The type in force owns the guide page too: without an entry here the
2675
+ // Browser capsule would vanish from the sidebar's start page.
2676
+ guide: [{
2677
+ id: 'new',
2678
+ commandId: 'browser.new',
2679
+ order: 30,
2680
+ title: () => t('browser.label'),
2681
+ description: () => t('browser.guide'),
2682
+ }],
2683
+ }), 'shared-browser tab type')
2684
+
2685
+ uiCtx.slots.inject('sidebar.right.pane.tab', () => uiCtx.slots.register({
2686
+ name: 'sidebar.right.pane.tab',
2687
+ key: PLUGIN_ID,
2688
+ }, BrowserBody))
2689
+
2690
+ uiCtx.slots.inject('sidebar.right.pane.tab.title', () => uiCtx.slots.register({
2691
+ name: 'sidebar.right.pane.tab.title',
2692
+ key: PLUGIN_ID,
2693
+ }, (props) => {
2694
+ const info = typeof props.useTabInfo === 'function' ? props.useTabInfo() : null
2695
+ const external = info?.tab?.navigation?.params?.external
2696
+ if (typeof external === 'string' && external !== '') return t('external.label')
2697
+ const instance = info?.tab?.id ? instances.get(info.tab.id) : null
2698
+ /* `guest` is a live accessor, so the title follows page navigations. */
2699
+ const live = instance?.guest?.title
2700
+ return live || info?.tab?.title || t('browser.label')
2701
+ }))
2702
+ })
2703
+
2704
+ // The Host keeps every tab listed even while the user never calls a tool.
2705
+ ctx.effect(() => {
2706
+ const timer = setInterval(scheduleReport, 5000)
2707
+ return () => clearInterval(timer)
2708
+ }, 'shared-browser heartbeat')
2709
+ },
2710
+ }
2711
+ },
2712
+ })