dsh-embedded-browser-next 0.0.0-stage → 1.0.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.js ADDED
@@ -0,0 +1,3991 @@
1
+ /**
2
+ * dsh-embedded-browser — browser half.
3
+ *
4
+ * One Chrome lives on the DSH host and **every DSH session owns one tab in it**.
5
+ * This half puts that tab in the Web UI as an **on-demand right-Sidebar tab**:
6
+ *
7
+ * - `ctx.sidebarRightTabs` declares the page type (`kind` {@link TAB_KIND}, id
8
+ * {@link TAB_ID}), and the keyed `sidebar.right.pane.tab` /
9
+ * `sidebar.right.pane.tab.title` seats draw its body and chip. Registering a
10
+ * type is not opening one — no session shows a 浏览器 tab until it actually
11
+ * has a browser, which is what keeps the surface out of everybody else's way.
12
+ * - The body is the live picture of *this* session's tab, with the human's
13
+ * mouse, wheel, keyboard and IME replayed into the very CDP target the AI
14
+ * drives, plus the hand-over banner `browser_embedded_ask_human` waits on. The
15
+ * slot entry is session-scoped, so the component always knows which tab it
16
+ * shows, and its mount/unmount lifetime *is* the focus protocol (mount asks
17
+ * the host to put this tab in front and stream it at full rate, unmount gives
18
+ * it back — unmount never closes the tab).
19
+ * - {@link watchSessions} opens that tab by itself the moment the session has a
20
+ * browser, or a human request lands in a session whose tab is closed. It is
21
+ * the only reason a tab ever appears: nothing is pinned per session any more.
22
+ *
23
+ * Plain JavaScript on purpose: the module loader factory must not depend on a
24
+ * build step or on npm packages beyond React, which the host provides.
25
+ */
26
+
27
+ window.__ModuleLoader__.load({
28
+ id: 'dsh-embedded-browser-next',
29
+ factory: (require) => {
30
+ const React = require('react')
31
+ const { useCallback, useEffect, useRef, useState } = React
32
+ const h = React.createElement
33
+
34
+ /** Tab type identity: the `id` both keyed seats (body, title) register under. */
35
+ const TAB_ID = 'dsh-embedded-browser/panel'
36
+ /** Page kind the type opens; `sidebarRight.openTabIn(session, TAB_KIND)` names it. */
37
+ const TAB_KIND = 'embedded-browser'
38
+ /**
39
+ * The DSH conversation currently on screen, as last seen by the tab watcher.
40
+ *
41
+ * A panel needs this because "am I visible" cannot answer "is somebody looking
42
+ * at me": collapsing the Sidebar and switching to another conversation both
43
+ * report `tab.visible === false`, yet they mean opposite things for residency.
44
+ * Collapsing keeps the person in this conversation (the browser should stay
45
+ * warm); switching takes them away (the idle clock should start).
46
+ *
47
+ * The watcher already resolves this question once per tick for its own reasons,
48
+ * so it publishes the answer here instead of every panel asking separately.
49
+ */
50
+ let currentDshSession = ''
51
+ /** Every route this plugin owns; all same-origin, all cookie-authenticated. */
52
+ const BASE = '/api/dsh-embedded-browser'
53
+
54
+ /**
55
+ * [dsh-rc5 fix] Resolve the live channel against the host's real HTTP origin.
56
+ *
57
+ * The desktop shell serves this page from its own custom scheme: `location`
58
+ * there is `dsh-app://app/`, so `window.location.host` is the literal string
59
+ * `app` and a hand-built `ws://app/...` dials a host that does not exist —
60
+ * close code 1006, and **nothing at all in the host log**. HTTP still works
61
+ * because the custom protocol forwards it; WebSocket cannot.
62
+ *
63
+ * The shell therefore publishes the owning Host's HTTP origin as
64
+ * `globalThis.__DSH_TRANSPORT__.streamBaseUrl`, which is exactly what the
65
+ * official `@deepseek-ai/dsh-client-connection` carrier uses. Fall back to
66
+ * `document.baseURI` (plain web host) and finally to `location.href`.
67
+ */
68
+ /**
69
+ * [dsh-rc5 fix] Every origin that could own this host's live channel, best first.
70
+ *
71
+ * The order is not cosmetic. The desktop shell serves this page from a custom
72
+ * scheme (`dsh-app://app/`), so anything derived from `location` is dead on
73
+ * arrival — and hard-coding one source is exactly what made this break again on
74
+ * the next shell change. The origin the host itself answered on wins; the
75
+ * transport hint, the document base and the page origin follow as fallbacks, and
76
+ * the dialer rotates through them, so a future carrier change self-heals.
77
+ */
78
+ function streamCandidates(advertised) {
79
+ const values = []
80
+ const add = (value) => {
81
+ if (typeof value !== 'string' || value === '') return
82
+ let parsed
83
+ try {
84
+ parsed = new URL(value)
85
+ } catch {
86
+ return
87
+ }
88
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return
89
+ if (values.some((entry) => entry.origin === parsed.origin)) return
90
+ values.push(parsed)
91
+ }
92
+ add(advertised)
93
+ add(typeof globalThis === 'undefined' ? undefined : globalThis.__DSH_TRANSPORT__?.streamBaseUrl)
94
+ add(typeof document === 'undefined' ? undefined : document.baseURI)
95
+ add(typeof window === 'undefined' ? undefined : window.location.href)
96
+ return values
97
+ }
98
+
99
+ /** The live channel URL for one session, resolved against `base`. */
100
+ function streamUrl(sessionId, base) {
101
+ const url = new URL(`${STREAM_PATH}?session=${encodeURIComponent(sessionId)}`, base)
102
+ url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
103
+ return url.toString()
104
+ }
105
+
106
+ /**
107
+ * [diagnostics] Report one panel step to the host so it lands in the trace file.
108
+ * Never throws: a diagnostic must not be able to break the panel.
109
+ */
110
+ function trace(stage, extra) {
111
+ try {
112
+ const query = new URLSearchParams({ stage, ...extra }).toString()
113
+ void fetch(`${BASE}/debug?${query}`, { cache: 'no-store' }).catch(() => {})
114
+ } catch {
115
+ /* diagnostics only */
116
+ }
117
+ }
118
+ const STREAM_PATH = `${BASE}/stream`
119
+ const MJPEG_PATH = `${BASE}/mjpeg`
120
+ const STATE_PATH = `${BASE}/state`
121
+ const SESSIONS_PATH = `${BASE}/sessions`
122
+ const OPEN_PATH = `${BASE}/open`
123
+ const CLOSE_PATH = `${BASE}/close`
124
+ const DONE_PATH = `${BASE}/human-done`
125
+ const SETTINGS_PATH = `${BASE}/settings`
126
+ const OPEN_EXTERNAL_PATH = `${BASE}/open-external`
127
+ const OPEN_WINDOW_PATH = `${BASE}/open-window`
128
+ const RESTORE_PANEL_PATH = `${BASE}/restore-panel`
129
+ /** Session state poll, used only while the websocket is not live. */
130
+ const STATE_POLL_MS = 2000
131
+ /**
132
+ * 主画面走 Electron 的 `<webview>`(原生渲染),而不是 MJPEG 像素流。
133
+ *
134
+ * 一条硬约束决定了这里必须用 `document.createElement` 手工建元素:**不能让
135
+ * React 渲染 `<webview>`**。第一版那样做过,结果是整个面板空白、连工具栏都
136
+ * 没了——渲染阶段就抛了。手工建的元素最坏只是自己消失。
137
+ *
138
+ * `<webview>` 也不是随便就能挂的:宿主窗口虽然开了 `webviewTag`,但主进程的
139
+ * `will-attach-webview` 只放行「持有租约、`src=about:blank#<lease>`、partition
140
+ * 等于租约给出的那个」的附加请求。所以必须先从 `dshDesktop.browser.acquire`
141
+ * 拿到租约,再用那个 partition 和那个 src 造元素。
142
+ */
143
+ const NATIVE_VIEW = true
144
+ /**
145
+ * Scale the guest down so a desktop-width site fits the panel.
146
+ *
147
+ * Measured behaviour of the sites people actually use here: GitHub reflows to
148
+ * any width (its content is a fixed-width column, centred), but Bilibili, Taobao
149
+ * and Bing ship a *desktop* layout with a minimum width around 1000–1200 px and
150
+ * do not fall back to their mobile layout just because the viewport got narrow.
151
+ * In a ~780 px panel that means the right-hand side is simply cut off.
152
+ *
153
+ * Setting a zoom factor renders the same CSS viewport into fewer physical
154
+ * pixels, so the whole layout fits — text gets smaller, nothing is lost, and
155
+ * because the guest is native, input keeps landing where it looks like it lands.
156
+ */
157
+ const FIT_WIDTH = true
158
+ /**
159
+ * What counts as "something a person can operate". Shared by the inventory and
160
+ * by click-by-label, so the two can never disagree about what is clickable.
161
+ *
162
+ * `lib/browser.js` carries the same string for the headless tab. This file is a
163
+ * plain browser script (no build step), so the two cannot import one another;
164
+ * `test/click-text.test.mjs` compares them, and changing one side alone turns
165
+ * the suite red. That guard exists because the copies had already drifted:
166
+ * `[onclick]` and `[role=menuitem]` were missing here, so the same label
167
+ * resolved headless and vanished in the panel.
168
+ */
169
+ const GUEST_INTERACTIVE =
170
+ 'a[href],button,input:not([type=hidden]),select,textarea,summary,[role=button],[role=link],[role=tab],[role=menuitem],[role=checkbox],[contenteditable=""],[contenteditable=true],[onclick]'
171
+ // #region click-text-probe
172
+ const CLICK_TEXT_PROBE = `(() => {
173
+ const INTERACTIVE = __INTERACTIVE__;
174
+ const want = __WANT__;
175
+ const needle = __NEEDLE__;
176
+ const norm = (value) => String(value == null ? '' : value).replace(/\\s+/g, ' ').trim();
177
+ const labelOf = (el) => norm(el.getAttribute('aria-label') || el.getAttribute('placeholder') || el.getAttribute('title') || el.innerText || el.textContent || '');
178
+ const shown = (el) => {
179
+ const style = getComputedStyle(el);
180
+ if (style.display === 'none' || style.visibility === 'hidden') return false;
181
+ const rect = el.getBoundingClientRect();
182
+ return !(rect.width === 0 && rect.height === 0);
183
+ };
184
+ const cssOf = (el) => {
185
+ if (el.id) return '#' + CSS.escape(el.id);
186
+ const parts = [];
187
+ let at = el;
188
+ while (at && at.nodeType === 1 && parts.length < 6) {
189
+ if (at.id) { parts.unshift('#' + CSS.escape(at.id)); break; }
190
+ let part = at.tagName.toLowerCase();
191
+ const parent = at.parentElement;
192
+ if (parent) part += ':nth-child(' + ([].indexOf.call(parent.children, at) + 1) + ')';
193
+ parts.unshift(part);
194
+ at = parent;
195
+ }
196
+ return parts.join(' > ');
197
+ };
198
+ const describe = (el) => ({ tag: el.tagName.toLowerCase(), label: labelOf(el).slice(0, 60), selector: cssOf(el) });
199
+ // A wrapper's innerText is the same string as the button's, so without this
200
+ // every button inside a div would come back "ambiguous" — wrapper and button
201
+ // both counted. Keep the innermost, drop every ancestor of a kept one.
202
+ const innermost = (list) => list.filter((el) => !list.some((other) => other !== el && el.contains(other)));
203
+ const narrow = (list) => {
204
+ const labelled = list.map((el) => ({ el: el, label: labelOf(el).toLowerCase() }));
205
+ const exact = labelled.filter((one) => one.label === needle);
206
+ const pool = exact.length > 0 ? exact : labelled.filter((one) => one.label.indexOf(needle) !== -1);
207
+ return pool.map((one) => one.el);
208
+ };
209
+ const looksClickable = (el) => {
210
+ if (el.closest('a[href],button,label,summary,[role=button],[role=link],[role=tab],[role=menuitem],[onclick],[tabindex]') !== null) return true;
211
+ return getComputedStyle(el).cursor === 'pointer';
212
+ };
213
+ const answer = (match, el, pool) => {
214
+ el.scrollIntoView({ block: 'center', inline: 'center' });
215
+ const rect = el.getBoundingClientRect();
216
+ const out = {
217
+ ok: true,
218
+ match: match,
219
+ tag: el.tagName.toLowerCase(),
220
+ label: labelOf(el).slice(0, 80),
221
+ x: Math.round(rect.left + rect.width / 2),
222
+ y: Math.round(rect.top + rect.height / 2),
223
+ matches: pool.length,
224
+ };
225
+ if (pool.length > 1) {
226
+ out.ambiguous = true;
227
+ out.candidates = pool.slice(0, 5).map(describe);
228
+ }
229
+ return JSON.stringify(out);
230
+ };
231
+ const semantic = [];
232
+ for (const node of document.querySelectorAll(INTERACTIVE)) if (shown(node)) semantic.push(node);
233
+ let pool = narrow(innermost(semantic));
234
+ if (pool.length > 0) return answer('semantic', pool[0], pool);
235
+ // textContent is cheap; only the survivors pay for a layout read.
236
+ const loose = [];
237
+ for (const node of document.querySelectorAll('body *')) {
238
+ const tag = node.tagName;
239
+ if (tag === 'SCRIPT' || tag === 'STYLE' || tag === 'NOSCRIPT') continue;
240
+ if (String(node.textContent || '').toLowerCase().indexOf(needle) === -1) continue;
241
+ if (labelOf(node) === '') continue;
242
+ if (!shown(node)) continue;
243
+ // Past this many candidates the page is not answering a text search; a
244
+ // selector is. Capping keeps the scan bounded instead of quadratic.
245
+ if (loose.length >= 800) break;
246
+ loose.push(node);
247
+ }
248
+ pool = narrow(innermost(loose));
249
+ const clickable = pool.filter(looksClickable);
250
+ if (clickable.length > 0) return answer('fallback', clickable[0], clickable);
251
+ if (pool.length > 0) {
252
+ const where = pool.slice(0, 3).map((el) => { const one = describe(el); return one.tag + ' ' + one.selector; }).join(', ');
253
+ return JSON.stringify({
254
+ ok: false,
255
+ match: 'fallback',
256
+ reason: 'no clickable element matching ' + JSON.stringify(want) + ' — the page shows ' + pool.length + ' matching text(s) (' + where + ') but none of them looks clickable; pass selector or x/y instead',
257
+ candidates: pool.slice(0, 5).map(describe),
258
+ });
259
+ }
260
+ return JSON.stringify({
261
+ ok: false,
262
+ match: 'none',
263
+ reason: 'no clickable element matching ' + JSON.stringify(want) + ' — nothing visible on this page contains that text; call browser_embedded_snapshot to see what is there',
264
+ });
265
+ })()`
266
+ // #endregion click-text-probe
267
+ /**
268
+ * Build a page inventory inside the guest, for the agent.
269
+ *
270
+ * Every listed node is stamped with `data-deb-index` so a later action can find it
271
+ * again by position; `loc` is the handle that survives a renumbering. `__LIMIT__`
272
+ * and `__TEXT__` are substituted per call — an unbounded inventory of a heavy
273
+ * page is an unbounded prompt.
274
+ *
275
+ * `total` counts everything visible, not just what fits under `__LIMIT__`, so the
276
+ * tool layer can say "15 of 200" instead of quietly looking at a truncated page.
277
+ */
278
+ const GUEST_SNAPSHOT_JS = `(() => {
279
+ const interactive = ${JSON.stringify(GUEST_INTERACTIVE)}
280
+ for (const node of document.querySelectorAll('[data-deb-index]')) node.removeAttribute('data-deb-index')
281
+ // Collect first, decide later. An index is only stamped on a node that is
282
+ // actually going out, or clicking index N could land on an element the
283
+ // caller never saw.
284
+ const candidates = []
285
+ for (const node of document.querySelectorAll(interactive)) {
286
+ const rect = node.getBoundingClientRect()
287
+ const style = getComputedStyle(node)
288
+ if (style.display === 'none' || style.visibility === 'hidden') continue
289
+ if (rect.width === 0 && rect.height === 0) continue
290
+ candidates.push({ node, rect })
291
+ }
292
+ const total = candidates.length
293
+ /**
294
+ * What is on screen goes first, but only when the list will be cut: a page
295
+ * that fits reads better in document order, and reordering it would move
296
+ * every number for nothing.
297
+ */
298
+ const view = { left: 0, top: 0, right: innerWidth, bottom: innerHeight }
299
+ const onScreen = (rect) =>
300
+ rect.bottom > view.top && rect.top < view.bottom && rect.right > view.left && rect.left < view.right
301
+ const requested = __LIMIT__
302
+ const limit = requested > 0 ? requested : Math.min(__CAP__, Math.max(__FLOOR__, total))
303
+ const start = Math.min(Math.max(0, __OFFSET__), total)
304
+ // Document order, always. Paging is a contract — "these, and no others, once" —
305
+ // and promoting the on-screen run breaks it: page 1 ended at below-1 while
306
+ // page 2 began at below-4, so below-2 and below-3 were never listed at all
307
+ // (measured on this panel). Being on screen is reported per entry instead,
308
+ // which guides the caller without moving anything.
309
+ const ordered = candidates
310
+ const picked = []
311
+ let used = 0
312
+ for (let order = start; order < ordered.length && picked.length < limit; order += 1) {
313
+ const node = ordered[order].node
314
+ const label = String(
315
+ node.getAttribute('aria-label') ||
316
+ node.getAttribute('placeholder') ||
317
+ node.getAttribute('title') ||
318
+ node.innerText ||
319
+ node.textContent ||
320
+ '',
321
+ ).replace(/\\s+/g, ' ').trim().slice(0, 80)
322
+ const href = node.getAttribute('href')
323
+ const id = node.getAttribute('id')
324
+ /**
325
+ * A bounded selector for the node, used only when a click's index marker
326
+ * has died with the DOM node (a framework re-render). id and href are the
327
+ * stable cases; everything else falls back to a short :nth-child path,
328
+ * which still finds the same node in a structurally unchanged page.
329
+ */
330
+ const cssPath = (el) => {
331
+ if (el.id) return '#' + CSS.escape(el.id)
332
+ const parts = []
333
+ let at = el
334
+ while (at && at.nodeType === 1 && parts.length < 8) {
335
+ if (at.id) { parts.unshift('#' + CSS.escape(at.id)); break }
336
+ let part = at.tagName.toLowerCase()
337
+ const parent = at.parentElement
338
+ if (parent) part += ':nth-child(' + ([...parent.children].indexOf(at) + 1) + ')'
339
+ parts.unshift(part)
340
+ at = parent
341
+ }
342
+ return parts.join(' > ')
343
+ }
344
+ const loc = href !== null && node.tagName === 'A' ? 'href:' + href : id !== null ? 'css:#' + CSS.escape(id) : 'css:' + cssPath(node)
345
+ // The character budget is the real ceiling: 240 elements of prose is a
346
+ // context dump, not a page read. loc is a handle the renderer never
347
+ // shows, so it must not eat into the visible budget.
348
+ const cost = label.length + 40
349
+ // The character budget is the real ceiling: 240 elements of prose is a
350
+ // context dump, not a page read. One element always goes out, so a single
351
+ // enormous label cannot produce an empty list.
352
+ if (picked.length > 0 && used + cost > __BUDGET__) break
353
+ used += cost
354
+ picked.push({
355
+ node,
356
+ loc,
357
+ tag: node.tagName.toLowerCase(),
358
+ type: node.getAttribute('type') || undefined,
359
+ label,
360
+ value: node.value === undefined ? '' : String(node.value).slice(0, 60),
361
+ disabled: node.disabled === true,
362
+ onScreen: onScreen(ordered[order].rect) === true ? true : undefined,
363
+ })
364
+ }
365
+ const elements = picked.map((entry, index) => {
366
+ entry.node.setAttribute('data-deb-index', String(index))
367
+ return {
368
+ index,
369
+ loc: entry.loc,
370
+ tag: entry.tag,
371
+ type: entry.type,
372
+ label: entry.label,
373
+ value: entry.value,
374
+ disabled: entry.disabled,
375
+ onScreen: entry.onScreen,
376
+ }
377
+ })
378
+ // What a later click needs to re-find an entry whose marker died with the
379
+ // DOM node. Kept on the page because that is where the lookup happens.
380
+ globalThis.__debRefs = elements.map((entry) => ({ loc: entry.loc, tag: entry.tag, label: entry.label }))
381
+ const body = document.body
382
+ const text = body ? String(body.innerText || '').replace(/\\n{3,}/g, '\\n\\n').slice(0, __TEXT__) : ''
383
+ // Frames are reported even though their contents are not. "There is a dialog
384
+ // here and you cannot see into it" is the difference between an agent that
385
+ // clicks the right spot and one that reports clicking is impossible: a
386
+ // cross-origin frame is a hard wall for this document, but real input at
387
+ // these coordinates goes through to whatever renderer owns the point.
388
+ const frames = []
389
+ for (const node of document.querySelectorAll('iframe,frame')) {
390
+ const rect = node.getBoundingClientRect()
391
+ const style = getComputedStyle(node)
392
+ if (style.display === 'none' || style.visibility === 'hidden') continue
393
+ if (rect.width === 0 && rect.height === 0) continue
394
+ if (frames.length >= 12) break
395
+ let src = ''
396
+ try { src = String(node.src || node.getAttribute('src') || '').slice(0, 200) } catch { src = '' }
397
+ let origin = ''
398
+ try { origin = src === '' ? '' : new URL(src, location.href).origin } catch { origin = '' }
399
+ let readable = false
400
+ try {
401
+ // 已设 src 但导航还没提交时,frame 里仍是初始的 about:blank:同源、可读、
402
+ // 但什么都没装。要求「真文档」才不会在加载窗口里说「可读」。
403
+ const doc = node.contentDocument
404
+ readable = Boolean(doc && doc.body && !/^about:/.test(String((doc.location && doc.location.href) || '')))
405
+ } catch { readable = false }
406
+ frames.push({
407
+ x: Math.round(rect.x),
408
+ y: Math.round(rect.y),
409
+ w: Math.round(rect.width),
410
+ h: Math.round(rect.height),
411
+ origin: origin === '' ? undefined : origin === location.origin ? 'same' : origin,
412
+ readable,
413
+ src: src === '' ? undefined : src,
414
+ })
415
+ }
416
+ return { url: location.href, title: document.title, collapsed: innerWidth <= 0 || innerHeight <= 0, elements, text, total, offset: start, more: start + elements.length < total, frames }
417
+ })()`
418
+ /**
419
+ * Make download links work inside the guest.
420
+ *
421
+ * The host calls `event.preventDefault()` on every `will-download` for this
422
+ * partition, so a download link is silently inert — measured, not guessed. The
423
+ * page is the only side that can fetch with the site's cookies, so it fetches the
424
+ * bytes itself and parks them in a queue the panel drains. `dom-ready` fires for
425
+ * every document, which is what re-arms this after each navigation.
426
+ */
427
+ const DOWNLOAD_HOOK_JS = `(() => {
428
+ if (window.__debDownloadHooked === true) return 'already'
429
+ window.__debDownloadHooked = true
430
+ window.__debDownloadQueue = []
431
+ const ceiling = 32 * 1024 * 1024
432
+ const toBase64 = (bytes) => {
433
+ let binary = ''
434
+ for (let index = 0; index < bytes.length; index += 32768) {
435
+ binary += String.fromCharCode.apply(null, bytes.subarray(index, index + 32768))
436
+ }
437
+ return btoa(binary)
438
+ }
439
+ document.addEventListener('click', (event) => {
440
+ const origin = event.target
441
+ const link = origin !== null && typeof origin.closest === 'function' ? origin.closest('a[download]') : null
442
+ if (link === null) return
443
+ event.preventDefault()
444
+ event.stopPropagation()
445
+ const url = link.href
446
+ const label = link.getAttribute('download') || ''
447
+ ;(async () => {
448
+ try {
449
+ const response = await fetch(url, { credentials: 'include' })
450
+ if (response.ok !== true) {
451
+ window.__debDownloadQueue.push({ state: 'error', reason: 'HTTP ' + response.status })
452
+ return
453
+ }
454
+ const blob = await response.blob()
455
+ if (blob.size > ceiling) {
456
+ window.__debDownloadQueue.push({ state: 'error', reason: '文件超过 32MB 上限' })
457
+ return
458
+ }
459
+ const bytes = new Uint8Array(await blob.arrayBuffer())
460
+ window.__debDownloadQueue.push({
461
+ state: 'ready',
462
+ name: label,
463
+ type: blob.type || '',
464
+ size: bytes.length,
465
+ base64: toBase64(bytes),
466
+ })
467
+ } catch (error) {
468
+ window.__debDownloadQueue.push({ state: 'error', reason: String((error && error.message) || error) })
469
+ }
470
+ })()
471
+ }, true)
472
+ return 'fresh'
473
+ })()`
474
+ /** Page metadata plus a coarse bot-check signal, in the shape the tool layer expects. */
475
+ const GUEST_PAGE_INFO_JS = `(() => {
476
+ const frames = [...document.querySelectorAll('iframe')].map((f) => String(f.src || ''))
477
+ const captcha =
478
+ frames.some((src) => /recaptcha|hcaptcha|turnstile|geetest|captcha/i.test(src)) ||
479
+ document.querySelector('[class*=captcha],[id*=captcha],[class*=verify]') !== null
480
+ return {
481
+ url: location.href,
482
+ title: document.title,
483
+ readyState: document.readyState,
484
+ viewport: { width: innerWidth, height: innerHeight },
485
+ scroll: { x: Math.round(scrollX), y: Math.round(scrollY), height: Math.round(document.documentElement.scrollHeight) },
486
+ humanCheck: { detected: captcha, kind: captcha ? 'captcha-fingerprint' : null },
487
+ }
488
+ })()`
489
+ /**
490
+ * Key names, in the vocabulary `sendInputEvent` actually accepts.
491
+ *
492
+ * The tool description tells the agent "ArrowUp/Down/Left/Right", but Electron's
493
+ * accelerator table spells those `Up`/`Down`/`Left`/`Right`; handing it
494
+ * `ArrowDown` produced an event with an unknown key code and the page never moved.
495
+ */
496
+ const GUEST_KEYS = {
497
+ arrowup: 'Up',
498
+ arrowdown: 'Down',
499
+ arrowleft: 'Left',
500
+ arrowright: 'Right',
501
+ up: 'Up',
502
+ down: 'Down',
503
+ left: 'Left',
504
+ right: 'Right',
505
+ enter: 'Enter',
506
+ return: 'Return',
507
+ esc: 'Escape',
508
+ escape: 'Escape',
509
+ space: 'Space',
510
+ spacebar: 'Space',
511
+ tab: 'Tab',
512
+ backspace: 'Backspace',
513
+ back: 'Backspace',
514
+ delete: 'Delete',
515
+ del: 'Delete',
516
+ home: 'Home',
517
+ end: 'End',
518
+ pageup: 'PageUp',
519
+ pagedown: 'PageDown',
520
+ insert: 'Insert',
521
+ }
522
+ /** Reconnect backoff, so a host restart does not become a request storm. */
523
+ const RECONNECT_BASE_MS = 800
524
+ const RECONNECT_MAX_MS = 15000
525
+ /**
526
+ * Auto-open poll. Deliberately unhurried: the only thing it is waiting for
527
+ * is "this session just got a browser", and nobody is staring at the Sidebar
528
+ * waiting for it. Every tick is one more request on an origin whose
529
+ * connections are already scarce — the live tab holds a WebSocket, and on
530
+ * HTTP/1.1 a browser allows about six per origin shared by every tab, which
531
+ * streaming plugins each sit on (see references/PITFALLS.md #18).
532
+ */
533
+ const REVEAL_POLL_MS = 5000
534
+ /** Auto-open poll while the document is hidden: nothing is being watched. */
535
+ const REVEAL_IDLE_POLL_MS = 20000
536
+ /** The chip's hand-over dot is decoration: a slow poll is enough. */
537
+ const TITLE_POLL_MS = 5000
538
+
539
+ /** `m:ss` for the hand-over timer. */
540
+ function formatWaited(ms) {
541
+ const total = Math.max(0, Math.round(Number(ms) / 1000))
542
+ return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`
543
+ }
544
+
545
+ /** Copy for both shipped locales. */
546
+ const DICT = {
547
+ zh: {
548
+ title: '浏览器',
549
+ guideTitle: '内嵌浏览器',
550
+ guideDescription: '在容器内自带 Chrome 里打开一个页面,可在此查看并接管(登录、扫码、验证码)。',
551
+ back: '后退',
552
+ forward: '前进',
553
+ reload: '刷新',
554
+ refresh: '重绘',
555
+ closeTab: '结束并清理',
556
+ closeTabTitle: '关闭这个会话的浏览器标签页(未提交的页面状态会丢失)',
557
+ closeTabConfirm: '关闭这个会话的浏览器标签页?未提交的表单与页面状态会丢失;登录态存在共享 profile 里,不会丢。',
558
+ connecting: '连接中…',
559
+ mountWaitSocket: '等宿主连线',
560
+ mountNoSocket: '连不上宿主,重载插件',
561
+ mountAcquire: '申请浏览器…',
562
+ mountStuck: '挂载超时,重载插件',
563
+ panelCollapsed: '面板现在是 0×0(被折叠或隐藏),点击/输入不会到达页面:把右侧栏展开、让面板可见后再操作',
564
+ connected: '已连接',
565
+ still: '静止',
566
+ offline: '连接断开,正在重连…',
567
+ stopped: '浏览器未启动',
568
+ failed: '浏览器启动失败',
569
+ checking: '正在检查这个会话的浏览器…',
570
+ empty: '这个会话还没有打开浏览器',
571
+ emptyHint: '打开后这里就是 AI 正在操作的页面;登录、扫码、验证码都可以直接在这里完成。',
572
+ open: '在此会话打开浏览器',
573
+ starting: '正在打开…',
574
+ openFailed: '打开失败',
575
+ waitingFrame: '正在获取画面…',
576
+ humanTitle: '需要你操作',
577
+ humanDone: '我已完成',
578
+ humanHint: '完成上方操作后点此按钮,AI 会接着往下做;也可以留一句话再回复。',
579
+ humanWaited: '已等待',
580
+ humanBlankPage: '当前页面还是空白的(AI 还没打开页面)',
581
+ replyOpen: '留言',
582
+ reply: '回复',
583
+ replyPlaceholder: '留一句话给 AI(可选)',
584
+ pollHint: '降帧快照 ~7fps(标签页不在前台)',
585
+ noSession: '这里拿不到会话 id,无法确定这个标签页对应哪个浏览器标签页。',
586
+ pending: '需要你',
587
+ tab: '把焦点移到下一个可输入元素(免鼠标定位)',
588
+ shiftTab: '焦点移到上一个元素',
589
+ enter: '回车(提交 / 确认)',
590
+ instructions: '点画面任意处即可聚焦,然后用键盘/输入法打字(登录页常用);表单还可以用工具栏的 Tab / Enter 逐项跳转提交。AI 看到的是同一个页面。',
591
+ nativeNote: '原生渲染',
592
+ address: '输入网址,回车打开',
593
+ addressHint: '回车打开;Esc 取消编辑',
594
+ pinOff: '固定',
595
+ pinOn: '已固定',
596
+ pinOffHint: '固定这个对话的浏览器,闲置时不回收。不突破「同时保留上限」。',
597
+ pinOnHint: '已固定,闲置不回收。上限满时,最久未用的固定台仍会被关闭。',
598
+ floatLabel: '浮窗',
599
+ floatHint: '弹成浮动面板,可拖动、放大。页面不重新加载,登录状态和滚动位置保留。',
600
+ dockLabel: '收回',
601
+ dockHint: '把浮动面板收回右侧边栏。',
602
+ floatFailed: '浮窗没切成',
603
+ openWindowLabel: '独立窗口',
604
+ openWindowHint: '在独立的浏览器窗口里打开当前页面:登录态存在本地,退出客户端也不丢;AI 仍能继续操作。第一次会重启一次浏览器(登录态保留),面板会自动重连。',
605
+ openWindowDone: '已在独立窗口打开',
606
+ openWindowRestarted: '已切到独立窗口(浏览器重启过一次,登录态保留)',
607
+ openWindowFailed: '没能打开独立窗口',
608
+ movedToWindow: '页面已移到独立窗口,接下来工具操作的是那个窗口',
609
+ windowedNotice: '页面在独立窗口里:工具操作的是那个窗口。点下面的「回到面板」,或者工具栏的「浮窗」,把它收回来。',
610
+ restoreLabel: '回到面板',
611
+ restoreHint: '把这个页面从独立浏览器窗口收回侧栏面板(窗口会关掉,插件那台浏览器转回后台,登录态不丢)。',
612
+ restoreDone: '已收回面板(独立窗口已关闭,插件浏览器的登录态保留)',
613
+ restoreNotWindowed: '页面本来就在面板里',
614
+ restoreFailed: '收回面板失败',
615
+ windowClosed: '独立窗口被关掉了。页面地址已保住,后台浏览器会自己回来;点「回到面板」在侧栏继续。',
616
+ windowRestored: '独立窗口关掉后,后台浏览器已恢复,页面还在',
617
+ settingsTitle: '浏览器设置',
618
+ settingsLabel: '设置',
619
+ settingsClose: '收起设置',
620
+ settingsHint: '打开浏览器设置:浏览器保留方式、闲置回收时间、同时保留上限',
621
+ settingMode: '浏览器保留方式',
622
+ modeOnDemand: '按需开(推荐)',
623
+ modeAlways: '每个对话各留一台',
624
+ modeOff: '只在后台跑',
625
+ settingIdle: '闲置多久关掉',
626
+ neverReclaim: '从不关掉',
627
+ unitMin: '分钟',
628
+ settingCap: '同时保留上限',
629
+ unlimited: '不限',
630
+ settingShutdown: '整台浏览器闲置多久关掉',
631
+ noteShutdown: '整台浏览器闲置多久后关闭。面板打开或有人在看算作使用。与上面的每对话回收相互独立。',
632
+ settingsNote: '以上为全局设置;单个对话可点工具栏「固定」,闲置时不回收。注意:侧栏面板里的登录态在退出客户端后会清空;需要跨重启保留登录的网站,请点工具栏「独立窗口」登录(AI 仍可继续操作)。',
633
+ noteMode: '按需开:打开面板才启动,闲置后自动关闭。每个对话各留一台:用过的对话各保留一份,内存占用最高。只在后台跑:不显示画面,但登录态仍存在那台浏览器里——你看不到它在做什么。',
634
+ noteIdle: '切换对话或关闭页签后开始计时。收起侧边栏不计时。固定的对话不受影响。',
635
+ noteCap: '同时存在的最多台数。超出时先关未固定的,再按最久未用关。每台约占 150–300 MB。',
636
+ settingsFailed: '设置没保存成功',
637
+ },
638
+ en: {
639
+ title: 'Browser',
640
+ guideTitle: 'Embedded browser',
641
+ guideDescription: 'Open a page in a Chrome that lives in this container, and watch or take it over here (logins, QR codes, CAPTCHAs).',
642
+ back: 'Back',
643
+ forward: 'Forward',
644
+ reload: 'Reload',
645
+ refresh: 'Repaint',
646
+ closeTab: 'Close tab',
647
+ closeTabTitle: 'Close this session’s browser tab (its page state is discarded)',
648
+ closeTabConfirm: 'Close this session’s browser tab? Unsaved form and page state are lost — logins live in the shared profile and stay.',
649
+ connecting: 'Connecting…',
650
+ mountWaitSocket: 'Waiting for the host',
651
+ mountNoSocket: 'No host link — reload the plugin',
652
+ mountAcquire: 'Requesting a browser…',
653
+ mountStuck: 'Attach timed out — reload the plugin',
654
+ panelCollapsed: 'The panel is 0x0 (collapsed or hidden): clicks and typing cannot reach the page. Expand the sidebar or make the panel visible first.',
655
+ connected: 'Connected',
656
+ still: 'idle',
657
+ offline: 'Disconnected — reconnecting…',
658
+ stopped: 'Browser not running',
659
+ failed: 'Browser failed to start',
660
+ checking: 'Checking this session’s browser…',
661
+ empty: 'This session has no browser open yet',
662
+ emptyHint: 'Once opened, this is the page the AI is working on — logins, QR codes and CAPTCHAs can be done right here.',
663
+ open: 'Open a browser in this session',
664
+ starting: 'Opening…',
665
+ openFailed: 'Could not open',
666
+ waitingFrame: 'Fetching the first frame…',
667
+ humanTitle: 'Your turn',
668
+ humanDone: 'Done',
669
+ humanHint: 'Finish the step above, then press this — the AI continues from there. You can also leave a note in the reply field.',
670
+ humanWaited: 'Waiting',
671
+ humanBlankPage: 'The page is still blank (the AI has not opened one)',
672
+ replyOpen: 'Note',
673
+ reply: 'Reply',
674
+ replyPlaceholder: 'Leave the AI a note (optional)',
675
+ pollHint: 'Low-rate stills ~7fps (tab not in front)',
676
+ noSession: 'No session id here, so this tab cannot tell which browser tab it shows.',
677
+ pending: 'Needs you',
678
+ tab: 'Move focus to the next field (no mouse aiming needed)',
679
+ shiftTab: 'Move focus to the previous element',
680
+ enter: 'Enter (submit / confirm)',
681
+ instructions: 'Click anywhere in the picture to focus it, then type with your keyboard or IME (handy for logins); use the Tab / Enter buttons to walk a form without aiming the mouse. The AI sees the same page.',
682
+ nativeNote: 'native',
683
+ address: 'Type a URL and press Enter',
684
+ addressHint: 'Enter to open, Esc to cancel',
685
+ pinOff: 'Pin',
686
+ pinOn: 'Pinned',
687
+ pinOffHint: 'Keep this conversation’s browser open while idle. It does not raise the limit on live browsers.',
688
+ pinOnHint: 'Pinned: idle does not close it. At the limit, the least recently used pinned browser can still be closed.',
689
+ floatLabel: 'Float',
690
+ floatHint: 'Pop the page into a floating panel: draggable, resizable. It does not reload, so logins and scroll position stay.',
691
+ dockLabel: 'Dock',
692
+ dockHint: 'Return the floating panel to the right Sidebar.',
693
+ floatFailed: 'Could not change the float state',
694
+ openWindowLabel: 'Open in window',
695
+ openWindowHint: 'Open this page in a real browser window: its logins live on disk, so they survive quitting the app, and the agent can keep operating it. The first time restarts the browser once (logins are kept) and the panel reconnects.',
696
+ openWindowDone: 'Opened in a real window',
697
+ openWindowRestarted: 'Switched to a real window (the browser restarted once; logins kept)',
698
+ openWindowFailed: 'Could not open a window',
699
+ movedToWindow: 'Moved to the real window — tool calls now drive that window, not this panel',
700
+ windowedNotice: 'The page is in a real browser window; tool calls drive that window. Use 「Back to panel」 below — or the toolbar’s 「Float」 — to bring it back.',
701
+ restoreLabel: 'Back to panel',
702
+ restoreHint: 'Bring this page back from the real browser window into the Sidebar: the window closes, the plugin browser goes back to the background, and its logins are kept.',
703
+ restoreDone: 'Back in the panel (the real window closed; the plugin browser kept its logins)',
704
+ restoreNotWindowed: 'The page is in the panel already',
705
+ restoreFailed: 'Could not bring the page back',
706
+ windowClosed: 'The real window was closed. The page addresses were kept and the background browser comes back on its own; press 「Back to panel」 to continue in the Sidebar.',
707
+ windowRestored: 'The background browser is back after the window was closed; the pages are still there',
708
+ settingsTitle: 'Browser settings',
709
+ settingsLabel: 'Settings',
710
+ settingsClose: 'Hide settings',
711
+ settingsHint: 'Browser settings: how browsers are kept, the idle window, and the cap on live ones',
712
+ settingMode: 'How browsers are kept',
713
+ modeOnDemand: 'On demand (recommended)',
714
+ modeAlways: 'One per conversation',
715
+ modeOff: 'Background only',
716
+ settingIdle: 'Close when idle for',
717
+ neverReclaim: 'Never',
718
+ unitMin: 'min',
719
+ settingCap: 'Max kept at once',
720
+ unlimited: 'No limit',
721
+ settingShutdown: 'Close the whole browser when idle for',
722
+ noteShutdown: 'How long the whole browser may sit idle before it closes. An open panel or someone watching counts as use. Independent of the per-conversation reclaim above.',
723
+ settingsNote: 'These settings apply globally; use “Pin” in the toolbar to keep one conversation from being reclaimed while idle. Note: logins inside the sidebar panel are cleared when you quit the app — for sites that must stay signed in across restarts, use “Open in window” in the toolbar (the AI can still drive them).',
724
+ noteMode: 'On demand: starts with the panel and closes once idle. One per conversation: every conversation that used one keeps its browser — the most memory. Background only: no picture, but logins still live in that browser — you cannot see what it is doing.',
725
+ noteIdle: 'Counted from when you switch conversation or close the tab. Collapsing the sidebar does not count. Pinned conversations are exempt.',
726
+ noteCap: 'How many may exist at once. Over the limit, unpinned ones close first, then the least recently used. Each costs about 150–300 MB.',
727
+ settingsFailed: 'Could not save settings',
728
+ },
729
+ }
730
+
731
+ /** Pick the dictionary that matches the GUI language. */
732
+ function pickDict(locale) {
733
+ const code = String(locale ?? '').toLowerCase()
734
+ return code.startsWith('zh') ? DICT.zh : DICT.en
735
+ }
736
+
737
+ /**
738
+ * Stylesheet, scoped by data attribute; colours follow the host theme.
739
+ *
740
+ * `.deb-overlay` is an *informational* layer over a live canvas and must stay
741
+ * click-through (a full-canvas overlay without `pointer-events:none` silently
742
+ * eats every click on the page below — see references/PITFALLS.md #10). The
743
+ * interactive empty state is a separate class without that rule.
744
+ */
745
+ const CSS = `
746
+ [data-dsh-embedded-browser]{display:flex;flex-direction:column;flex:1 1 auto;height:100%;min-height:0;background:var(--dsw-alias-bg-base,#111);color:var(--dsw-alias-label-primary,#eee)}
747
+ [data-dsh-embedded-browser] .deb-bar{display:flex;align-items:center;gap:8px;padding:6px 10px;border-bottom:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.25));background:var(--dsw-alias-bg-layer-1,transparent);font-size:12.5px}
748
+ [data-dsh-embedded-browser] .deb-dot{width:8px;height:8px;border-radius:50%;background:var(--dsw-alias-state-warn-primary,#e0a020);flex:none}
749
+ [data-dsh-embedded-browser] .deb-dot[data-state="online"]{background:var(--dsw-alias-state-success-primary,#3ecf8e)}
750
+ [data-dsh-embedded-browser] .deb-dot[data-state="offline"]{background:var(--dsw-alias-state-error-primary,#e5484d)}
751
+ [data-dsh-embedded-browser] .deb-title{font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:34%}
752
+ [data-dsh-embedded-browser] .deb-url{color:var(--dsw-alias-label-secondary,#999);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;flex:1;min-width:0;font-variant-numeric:tabular-nums}
753
+ [data-dsh-embedded-browser] .deb-note{flex:none;font-size:11.5px;color:var(--dsw-alias-label-secondary,#999);white-space:nowrap}
754
+ [data-dsh-embedded-browser] .deb-tools{display:flex;align-items:center;gap:6px;flex-wrap:wrap;padding:6px 10px;border-bottom:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.25));background:var(--dsw-alias-bg-layer-1,transparent)}
755
+ [data-dsh-embedded-browser] button.deb-btn{border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.3));background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.08));color:inherit;border-radius:6px;padding:3px 9px;font-size:12.5px;font-family:inherit;cursor:pointer;flex:none}
756
+ [data-dsh-embedded-browser] button.deb-btn:hover:not(:disabled){background:var(--dsw-alias-bg-overlay,rgba(127,127,127,.18))}
757
+ [data-dsh-embedded-browser] button.deb-btn:disabled{opacity:.45;cursor:default}
758
+ [data-dsh-embedded-browser] button.deb-danger{border-color:var(--dsw-alias-state-error-primary,#e5484d);color:var(--dsw-alias-state-error-primary,#e5484d)}
759
+ [data-dsh-embedded-browser] button.deb-primary{border:0;border-radius:6px;padding:5px 14px;font-size:13px;font-weight:600;font-family:inherit;cursor:pointer;background:var(--dsw-alias-brand-primary,#3b82f6);color:#fff;flex:none}
760
+ [data-dsh-embedded-browser] button.deb-primary:disabled{opacity:.5;cursor:default}
761
+ [data-dsh-embedded-browser] .deb-spacer{flex:1;min-width:8px}
762
+ [data-dsh-embedded-browser] button.deb-pin[data-on="true"]{border-color:var(--dsw-alias-brand-primary,#3b82f6);color:var(--dsw-alias-brand-primary,#3b82f6);background:color-mix(in srgb,var(--dsw-alias-brand-primary,#3b82f6) 12%,transparent)}
763
+ [data-dsh-embedded-browser] .deb-settings{display:flex;flex-direction:column;gap:8px;padding:10px 12px;border-bottom:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.25));background:var(--dsw-alias-bg-layer-1,transparent);font-size:12.5px}
764
+ [data-dsh-embedded-browser] .deb-settings-head{font-weight:600}
765
+ [data-dsh-embedded-browser] .deb-settings-row{display:flex;align-items:center;gap:10px}
766
+ [data-dsh-embedded-browser] .deb-settings-label{flex:0 0 auto;min-width:96px;color:var(--dsw-alias-label-secondary,#999)}
767
+ [data-dsh-embedded-browser] .deb-settings-select{flex:1;min-width:0;border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.35));border-radius:6px;background:var(--dsw-alias-bg-base,#111);color:inherit;padding:3px 6px;font-size:12.5px;font-family:inherit}
768
+ [data-dsh-embedded-browser] .deb-settings-note{color:var(--dsw-alias-label-secondary,#999);font-size:11.5px;line-height:1.5}
769
+ [data-dsh-embedded-browser] .deb-settings-item{display:flex;flex-direction:column;gap:3px}
770
+ [data-dsh-embedded-browser] .deb-settings-foot{margin-top:2px;padding-top:6px;border-top:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.18))}
771
+ [data-dsh-embedded-browser] .deb-banner{display:flex;flex-direction:column;gap:6px;padding:8px 12px;background:var(--dsw-alias-bg-overlay,rgba(224,160,32,.16));border-bottom:1px solid var(--dsw-alias-state-warn-primary,#e0a020);font-size:13px}
772
+ [data-dsh-embedded-browser] .deb-banner-row{display:flex;align-items:center;gap:8px;min-width:0}
773
+ [data-dsh-embedded-browser] .deb-banner-tag{color:var(--dsw-alias-state-warn-primary,#e0a020);flex:none}
774
+ [data-dsh-embedded-browser] .deb-banner-text{flex:1;min-width:0;line-height:1.45;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden}
775
+ [data-dsh-embedded-browser] .deb-banner-blank{flex:none;opacity:.75;font-size:12px;border:1px dashed var(--dsw-alias-state-warn-primary,#e0a020);border-radius:999px;padding:1px 8px}
776
+ [data-dsh-embedded-browser] .deb-banner-actions{justify-content:flex-end}
777
+ [data-dsh-embedded-browser] .deb-waited{font-variant-numeric:tabular-nums;font-size:12px;opacity:.7;flex:none}
778
+ [data-dsh-embedded-browser] .deb-waited-late{opacity:1;color:var(--dsw-alias-state-danger-primary,#e5534b);font-weight:600}
779
+ [data-dsh-embedded-browser] button.deb-ghost{border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.35));border-radius:6px;background:transparent;color:inherit;padding:4px 12px;font-size:12.5px;font-family:inherit;cursor:pointer;flex:none}
780
+ [data-dsh-embedded-browser] button.deb-ghost:disabled{opacity:.45;cursor:default}
781
+ [data-dsh-embedded-browser] .deb-banner strong{color:var(--dsw-alias-state-warn-primary,#e0a020);flex:none}
782
+ [data-dsh-embedded-browser] .deb-banner .deb-grow{flex:1;min-width:140px}
783
+ [data-dsh-embedded-browser] .deb-banner input.deb-reply{flex:0 1 240px;min-width:140px;border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.35));border-radius:6px;background:var(--dsw-alias-bg-base,#111);color:inherit;padding:4px 8px;font-size:12.5px;font-family:inherit}
784
+ [data-dsh-embedded-browser] .deb-stage{position:relative;flex:1;min-height:0;display:flex;align-items:center;justify-content:center;overflow:hidden;background:var(--dsw-alias-bg-base,#0b0b0b)}
785
+ [data-dsh-embedded-browser] canvas.deb-canvas{display:block;max-width:100%;max-height:100%;outline:none;cursor:default;background:#fff;box-shadow:0 1px 3px rgba(0,0,0,.35)}
786
+ [data-dsh-embedded-browser] img.deb-live{display:block;max-width:100%;max-height:100%;outline:none;cursor:default;background:#fff;box-shadow:0 1px 3px rgba(0,0,0,.35);-webkit-user-drag:none;user-select:none;image-rendering:auto}
787
+ [data-dsh-embedded-browser] webview.deb-native{position:absolute;inset:0;width:100%;height:100%;border:0;background:#fff;display:flex}
788
+ [data-dsh-embedded-browser] input.deb-address{flex:1 1 auto;min-width:0;border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.35));border-radius:6px;background:var(--dsw-alias-bg-base,#111);color:inherit;padding:3px 8px;font-size:12px;font-family:inherit}
789
+ [data-dsh-embedded-browser] input.deb-address:focus{outline:1px solid var(--dsw-alias-brand-primary,#4c8dff);outline-offset:-1px}
790
+ [data-dsh-embedded-browser] .deb-hint{position:absolute;left:12px;right:12px;bottom:10px;font-size:12px;text-align:center;color:var(--dsw-alias-label-secondary,#999);pointer-events:none}
791
+ [data-dsh-embedded-browser] .deb-toast{position:absolute;top:10px;right:12px;max-width:72%;padding:6px 10px;border-radius:8px;font-size:12px;line-height:1.5;background:rgba(20,24,32,.92);color:#fff;box-shadow:0 4px 16px rgba(0,0,0,.35);pointer-events:none;word-break:break-all;z-index:3}
792
+ [data-dsh-embedded-browser] .deb-overlay{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;flex-direction:column;gap:10px;color:var(--dsw-alias-label-secondary,#999);font-size:13px;text-align:center;padding:24px;pointer-events:none}
793
+ [data-dsh-embedded-browser] .deb-overlay-note{max-width:34em;line-height:1.6}
794
+ [data-dsh-embedded-browser] .deb-sink{position:absolute;opacity:0;width:1px;height:1px;border:0;padding:0;resize:none;left:0;top:0}
795
+ [data-dsh-embedded-browser] .deb-empty{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;flex-direction:column;gap:10px;padding:24px;text-align:center;font-size:13px;color:var(--dsw-alias-label-secondary,#999)}
796
+ [data-dsh-embedded-browser] .deb-empty-title{font-size:14px;font-weight:600;color:var(--dsw-alias-label-primary,#eee)}
797
+ [data-dsh-embedded-browser] .deb-empty-note{max-width:420px;line-height:1.6}
798
+ [data-dsh-embedded-browser] .deb-empty-error{max-width:420px;color:var(--dsw-alias-state-error-primary,#e5484d);word-break:break-word}
799
+ [data-dsh-embedded-browser] .deb-notice{display:flex;align-items:center;justify-content:center;flex:1;min-height:0;padding:24px;text-align:center;font-size:13px;color:var(--dsw-alias-label-secondary,#999)}
800
+ .deb-tab-title{display:inline-flex;align-items:center;gap:5px;min-width:0;max-width:100%}
801
+ .deb-tab-title .deb-tab-text{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
802
+ .deb-tab-dot{flex:none;width:7px;height:7px;border-radius:50%;background:var(--dsw-alias-state-warn-primary,#e0a020)}
803
+ `
804
+
805
+ /** Modifier list for the host's key dispatch. */
806
+ const modifiersOf = (event) => {
807
+ const list = []
808
+ if (event.altKey) list.push('alt')
809
+ if (event.ctrlKey) list.push('ctrl')
810
+ if (event.metaKey) list.push('meta')
811
+ if (event.shiftKey) list.push('shift')
812
+ return list
813
+ }
814
+
815
+ /** Keys forwarded explicitly; everything else is typed through the sink. */
816
+ const SPECIAL_KEYS = {
817
+ Enter: { key: 'Enter', code: 'Enter', keyCode: 13, text: '\r' },
818
+ Tab: { key: 'Tab', code: 'Tab', keyCode: 9 },
819
+ Escape: { key: 'Escape', code: 'Escape', keyCode: 27 },
820
+ Backspace: { key: 'Backspace', code: 'Backspace', keyCode: 8 },
821
+ Delete: { key: 'Delete', code: 'Delete', keyCode: 46 },
822
+ ArrowUp: { key: 'ArrowUp', code: 'ArrowUp', keyCode: 38 },
823
+ ArrowDown: { key: 'ArrowDown', code: 'ArrowDown', keyCode: 40 },
824
+ ArrowLeft: { key: 'ArrowLeft', code: 'ArrowLeft', keyCode: 37 },
825
+ ArrowRight: { key: 'ArrowRight', code: 'ArrowRight', keyCode: 39 },
826
+ Home: { key: 'Home', code: 'Home', keyCode: 36 },
827
+ End: { key: 'End', code: 'End', keyCode: 35 },
828
+ PageUp: { key: 'PageUp', code: 'PageUp', keyCode: 33 },
829
+ PageDown: { key: 'PageDown', code: 'PageDown', keyCode: 34 },
830
+ }
831
+
832
+ /**
833
+ * Fetch one JSON document on the GUI's own origin.
834
+ *
835
+ * Every route is protected by the Web UI's session cookie, so the request
836
+ * must stay same-origin and credentialed; a non-2xx answer is an error the
837
+ * caller renders instead of a silently empty panel.
838
+ */
839
+ async function requestJson(url, options) {
840
+ const { method = 'GET', body } = options ?? {}
841
+ const init = { method, credentials: 'same-origin', headers: { accept: 'application/json' } }
842
+ if (body !== undefined) {
843
+ init.headers['content-type'] = 'application/json'
844
+ init.body = JSON.stringify(body)
845
+ }
846
+ const response = await fetch(url, init)
847
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
848
+ return await response.json()
849
+ }
850
+
851
+ /**
852
+ * Normalize the `/state` payload (`GET /state`, the body of `POST /open`, and
853
+ * the `status` field of a `hello` message) into the few fields the panel uses.
854
+ */
855
+ function snapshotFromState(payload) {
856
+ const session = payload?.session ?? {}
857
+ return {
858
+ open: session.open === true,
859
+ running: payload?.running === true,
860
+ url: typeof session.url === 'string' ? session.url : null,
861
+ title: typeof session.title === 'string' ? session.title : null,
862
+ human: payload?.human ?? null,
863
+ stream: payload?.stream === 'poll' || payload?.stream === 'screencast' ? payload.stream : null,
864
+ pinned: payload?.pinned === true,
865
+ // [dsh-rc5 fix] The origin the host answered on: the only address the live
866
+ // channel may dial, because `location` is a custom scheme in the shell.
867
+ streamBaseUrl: typeof payload?.streamBaseUrl === 'string' ? payload.streamBaseUrl : null,
868
+ }
869
+ }
870
+
871
+ /** Normalize a pushed `{ type: 'state' }` message (a flatter shape). */
872
+ function snapshotFromMessage(message) {
873
+ return {
874
+ open: message.open === true,
875
+ running: message.running === true,
876
+ url: typeof message.url === 'string' ? message.url : null,
877
+ title: typeof message.title === 'string' ? message.title : null,
878
+ // Bumped only when the AI navigates; a follow of the human's own click keeps
879
+ // the number, which is what stops the host from dragging the guest back.
880
+ navSeq: typeof message.navSeq === 'number' ? message.navSeq : undefined,
881
+ human: message.human ?? null,
882
+ stream: message.stream === 'poll' || message.stream === 'screencast' ? message.stream : null,
883
+ pinned: message.pinned === true,
884
+ }
885
+ }
886
+
887
+ /** Whether two pending-request snapshots describe the same request. */
888
+ function sameHuman(left, right) {
889
+ if (left === right) return true
890
+ if (left === undefined || left === null || right === undefined || right === null) return false
891
+ return left.id === right.id && left.instruction === right.instruction
892
+ }
893
+
894
+ /** The sidebar entry glyph: a small window with a cursor. */
895
+ function BrowserIcon(props) {
896
+ const { size = 16, active = false } = props ?? {}
897
+ return h(
898
+ 'svg',
899
+ { width: size, height: size, viewBox: '0 0 16 16', 'aria-hidden': 'true', style: { display: 'block' } },
900
+ h('rect', { x: 1.5, y: 2.5, width: 13, height: 11, rx: 2, fill: 'none', stroke: 'currentColor', strokeWidth: active ? 1.6 : 1.3 }),
901
+ h('path', { d: 'M1.5 5.5h13', stroke: 'currentColor', strokeWidth: 1.2 }),
902
+ h('circle', { cx: 3.6, cy: 4, r: 0.6, fill: 'currentColor' }),
903
+ h('circle', { cx: 5.6, cy: 4, r: 0.6, fill: 'currentColor' }),
904
+ h('path', { d: 'M7 8.5l4.6 1.9-1.8.8-.8 1.8z', fill: 'currentColor' }),
905
+ )
906
+ }
907
+
908
+ /**
909
+ * One session's browser tab, drawn as the right-Sidebar tab body.
910
+ *
911
+ * The slot entry is session-scoped, so `sessionId` already identifies the
912
+ * very browser tab this component must show. Its **visibility** is the focus
913
+ * protocol: a docked body is mounted while its tab is the visible one, which
914
+ * is the moment to ask the host to put this browser tab in front and stream
915
+ * it at full rate; hiding hands the foreground back. **It never closes the
916
+ * browser tab** — that belongs to the session, not to the surface.
917
+ */
918
+ /**
919
+ * [dsh-rc5 fix] rc.5 stopped passing `sessionId` as a prop of a right-Sidebar
920
+ * tab body: the body learns its identity from the slot-owned `useTabInfo()`
921
+ * hook instead (`{ tab }`, holding `tab.sessionId`). Reading `props.sessionId`
922
+ * alone left it undefined, so the panel never dialled its WebSocket and sat on
923
+ * "连接中…" forever with zero panels attached to the host.
924
+ */
925
+ function useSessionId(props) {
926
+ let fromTab = ''
927
+ if (typeof props.useTabInfo === 'function') {
928
+ const info = props.useTabInfo()
929
+ if (typeof info?.tab?.sessionId === 'string') fromTab = info.tab.sessionId
930
+ }
931
+ return typeof props.sessionId === 'string' && props.sessionId !== '' ? props.sessionId : fromTab
932
+ }
933
+
934
+ function SessionPanel(props) {
935
+ const { dict } = props
936
+ const sessionId = useSessionId(props)
937
+ /**
938
+ * Where this body sits, and whether it already floats.
939
+ *
940
+ * Read here (render time — `useTabInfo` is a hook, so it cannot be called
941
+ * from a click handler) and consulted at click time: `tab.id` survives the
942
+ * move, `panel.isFloating` is the Sidebar's own answer, so the button needs
943
+ * no local state to stay truthful.
944
+ */
945
+ const tabInfo = typeof props.useTabInfo === 'function' ? props.useTabInfo() : undefined
946
+ const floatTabId = tabInfo?.tab?.id
947
+ const floatPaneId = tabInfo?.panel?.id
948
+ const floated = tabInfo?.panel?.isFloating === true
949
+ /** Read by the socket's open handler, which runs outside this render. */
950
+ const floatedRef = useRef(false)
951
+ floatedRef.current = floated
952
+ /**
953
+ * What *this panel* did, because `panel.isFloating` does not follow it.
954
+ *
955
+ * Measured 2026-11-27 on this DSH build: after `sidebarRight.float(tabId)`
956
+ * the tab really moves, but `useTabInfo().panel.isFloating` keeps reporting
957
+ * false on later renders. Docking is gated on that flag, so a page the agent
958
+ * floated could never be docked again — `present(sidebar)` returned
959
+ * `moved: false` and the layer stayed `float`. Belief is kept here and
960
+ * reported over the socket, so the host and the tool agree with reality
961
+ * instead of with a flag the Sidebar stopped updating.
962
+ */
963
+ const ourFloatRef = useRef(false)
964
+ /** The pane `float()` handed back, if it hands one back at all. */
965
+ const ourFloatPaneRef = useRef(undefined)
966
+ useEffect(() => {
967
+ trace('MOUNT', { sid: sessionId, props: Object.keys(props).join('|') })
968
+ }, [sessionId])
969
+ // A docked body stays mounted while its tab is inactive or the column is
970
+ // collapsed, so "am I on screen" is not "am I mounted": the stream must be
971
+ // driven by visibility, or a hidden tab would keep stealing the browser's
972
+ // foreground and spend bandwidth nobody is looking at.
973
+ const visible = props.visible !== false
974
+ const canvasRef = useRef(null)
975
+ /**
976
+ * Whatever is currently showing pixels — a `<canvas>` or an `<img>`.
977
+ * Pointer coordinates are measured against this, so switching transports
978
+ * does not need a second mapping path.
979
+ */
980
+ const surfaceRef = useRef(null)
981
+ const stageRef = useRef(null)
982
+ /**
983
+ * The live `<webview>` element. Held in a ref rather than React state on
984
+ * purpose: it is created and appended by hand (see `NATIVE_VIEW`), and a
985
+ * re-render must never touch it.
986
+ */
987
+ const viewRef = useRef(null)
988
+ /** URL the guest is actually showing, kept in sync with `did-navigate`. */
989
+ const viewUrlRef = useRef('')
990
+ /**
991
+ * URL the *host* asked this guest to load. It is the loop breaker: a
992
+ * `did-navigate` whose URL equals this one came from the host, so it must
993
+ * not be reported back, or host and guest would push each other forever.
994
+ */
995
+ const hostUrlRef = useRef('')
996
+ /** Last `navSeq` this panel obeyed; a repeat means "not an AI navigation". */
997
+ const appliedNavSeqRef = useRef(0)
998
+ const [viewUrl, setViewUrl] = useState('')
999
+ const [viewTitle, setViewTitle] = useState('')
1000
+ const [nativeReady, setNativeReady] = useState(false)
1001
+ /**
1002
+ * True while the host says this page lives in a real browser window.
1003
+ *
1004
+ * The panel must not mount a guest then: a mounted guest wins tool routing,
1005
+ * and the agent would keep driving the panel copy while the human looks at
1006
+ * the window (measured 2026-11-29).
1007
+ */
1008
+ const [windowed, setWindowed] = useState(false)
1009
+ /**
1010
+ * What the native surface is waiting for, in words a person can act on.
1011
+ *
1012
+ * Every possible cause used to render the same 「连接中…」: no socket, no
1013
+ * lease, a refused attach, a guest that never finished loading. On
1014
+ * 2026-11-27 that cost an hour of guessing, because the panel was painting
1015
+ * normally while nothing at all was happening behind it. An empty stage now
1016
+ * means "the mount effect is running"; a populated one says what it waits on.
1017
+ */
1018
+ const [mountStage, setMountStage] = useState('')
1019
+ /** Bumped to force the mount effect to start over when it gets stuck. */
1020
+ const [mountNonce, setMountNonce] = useState(0)
1021
+ /** `status.url` mirrored, for one-shot reads inside non-reactive effects. */
1022
+ const statusUrlRef = useRef('')
1023
+ /** Last URL this panel itself pushed into the guest, for click de-duplication. */
1024
+ const guestNavRef = useRef({ url: '', at: 0 })
1025
+ const lastAspectRef = useRef(0)
1026
+ /** Last time this panel asked the host to reshape the viewport. */
1027
+ const lastAspectSentAtRef = useRef(0)
1028
+ const sinkRef = useRef(null)
1029
+ const socketRef = useRef(null)
1030
+ const decodingRef = useRef(false)
1031
+ // Newest frame waiting for the decoder; older ones are dropped rather than
1032
+ // queued, so a slow decode costs frames but never adds lag.
1033
+ const pendingFrameRef = useRef(undefined)
1034
+ /** Rolling per-window tally reported to the host for the stream log. */
1035
+ const metricsRef = useRef({ frames: 0, bytes: 0, decodeMs: 0, paintMs: 0 })
1036
+ /**
1037
+ * The page's CSS viewport, from the host. Pointer coordinates are mapped
1038
+ * through this — never through the canvas, whose pixel size is decided by
1039
+ * the host's frame ceiling and says nothing about the page.
1040
+ */
1041
+ const viewportRef = useRef({ width: 1440, height: 900 })
1042
+ // The newest pointer position that has not been sent yet, flushed once per
1043
+ // animation frame (coalescing beats dropping: the cursor never teleports).
1044
+ const pendingMoveRef = useRef(undefined)
1045
+ const moveFrameRef = useRef(0)
1046
+ // Whether a button is held while the pointer moves. A drag repaints the page
1047
+ // (text selection, a slider, a canvas), so the host must treat those moves as
1048
+ // activity — hovering must not, or the picture would go coarse on nothing.
1049
+ const draggingRef = useRef(false)
1050
+ const [open, setOpen] = useState(undefined)
1051
+ const [connection, setConnection] = useState('idle')
1052
+ const [status, setStatus] = useState({})
1053
+ const [streamMode, setStreamMode] = useState(undefined)
1054
+ const [fps, setFps] = useState(undefined)
1055
+ /** `mjpeg` renders into an <img>; `ws` decodes into the canvas fallback. */
1056
+ const [transport, setTransport] = useState('ws')
1057
+ /** Current MJPEG URL, bumped to force a reconnect after a broken stream. */
1058
+ const [liveUrl, setLiveUrl] = useState('')
1059
+ const [liveGeneration, setLiveGeneration] = useState(0)
1060
+ const [human, setHuman] = useState(undefined)
1061
+ /** How long the human has been the blocker: a silent banner is easy to ignore. */
1062
+ const [waited, setWaited] = useState(0)
1063
+ const humanSinceRef = useRef(0)
1064
+ /** The note field stays folded away until asked for: it must not take the width prose needs. */
1065
+ const [replyOpen, setReplyOpen] = useState(false)
1066
+ /**
1067
+ * Whether this conversation's real browser is pinned.
1068
+ *
1069
+ * Pinning is the human's promise that this page stays alive no matter how
1070
+ * long the conversation sits idle; everything unpinned is closed once it has
1071
+ * been unused for the configured window. The host owns the state (it is the
1072
+ * side that reclaims), so this is a read-back, never a local toggle that could
1073
+ * drift from reality.
1074
+ */
1075
+ const [pinned, setPinned] = useState(false)
1076
+ const [settings, setSettings] = useState(undefined)
1077
+ const [settingsOpen, setSettingsOpen] = useState(false)
1078
+
1079
+ /**
1080
+ * Tell the host whether a person is still in this conversation.
1081
+ *
1082
+ * `visible` cannot answer that. Collapsing the Sidebar and switching to
1083
+ * another conversation both report `tab.visible === false`, but they mean
1084
+ * opposite things for residency: collapsing keeps the person here (the
1085
+ * browser should stay warm), switching takes them away (the idle clock should
1086
+ * start). The tab watcher already resolves "which conversation is on screen"
1087
+ * once per tick, so this reads that answer and reports the *change*.
1088
+ *
1089
+ * Before this, only the pixel-stream panel ever said `focus`, so a native
1090
+ * panel reported "nobody is watching" forever and an idle browser was
1091
+ * reclaimed even while a person was staring at it.
1092
+ */
1093
+ useEffect(() => {
1094
+ if (NATIVE_VIEW !== true || open !== true) return undefined
1095
+ let last
1096
+ const report = () => {
1097
+ const socket = socketRef.current
1098
+ if (socket === null || socket.readyState !== 1) return
1099
+ // The watcher has not resolved it yet: saying anything now would be a
1100
+ // guess, and a wrong `blur` starts the idle clock on a page being watched.
1101
+ if (currentDshSession === '') return
1102
+ const onScreen = currentDshSession === sessionId
1103
+ if (onScreen === last) return
1104
+ last = onScreen
1105
+ try {
1106
+ socket.send(JSON.stringify({ type: onScreen ? 'focus' : 'blur' }))
1107
+ } catch {
1108
+ /* the reconnect re-announces */
1109
+ }
1110
+ }
1111
+ const timer = setInterval(report, 3_000)
1112
+ return () => clearInterval(timer)
1113
+ }, [open, sessionId])
1114
+ /**
1115
+ * Tick while a hand-over is open, and fold the note field away when it ends.
1116
+ */
1117
+ useEffect(() => {
1118
+ if (human === undefined) {
1119
+ humanSinceRef.current = 0
1120
+ setWaited(0)
1121
+ setReplyOpen(false)
1122
+ return undefined
1123
+ }
1124
+ if (humanSinceRef.current === 0) humanSinceRef.current = Date.now()
1125
+ const tick = () => setWaited(Date.now() - humanSinceRef.current)
1126
+ tick()
1127
+ const timer = setInterval(tick, 1_000)
1128
+ return () => clearInterval(timer)
1129
+ }, [human])
1130
+ /**
1131
+ * A hand-over must be visible.
1132
+ *
1133
+ * The Sidebar keeps this body mounted while the column is collapsed, so a
1134
+ * request can arrive at a panel nobody can see. Expanding here is what turns
1135
+ * "waiting for a person" into something a person can actually answer — the
1136
+ * old behaviour waited out the whole timeout in silence.
1137
+ */
1138
+ useEffect(() => {
1139
+ if (human === undefined) return
1140
+ const side = props.sidebarRef?.current
1141
+ try {
1142
+ if (typeof side?.isExpanded === 'function' && side.isExpanded() !== true && typeof side.toggleExpanded === 'function') {
1143
+ side.toggleExpanded()
1144
+ }
1145
+ } catch {
1146
+ /* the Sidebar catches up on its own */
1147
+ }
1148
+ }, [human])
1149
+ /**
1150
+ * Tell the host which surface this body is drawn on.
1151
+ *
1152
+ * The Sidebar moves a tab between a docked pane and a floating panel without
1153
+ * telling anyone — same tab id, same body, same `<webview>`. The host needs
1154
+ * the difference: it is what the model is told when it asks where the page
1155
+ * is, and it is how "float this so I can watch it" becomes verifiable rather
1156
+ * than assumed.
1157
+ */
1158
+ useEffect(() => {
1159
+ const socket = socketRef.current
1160
+ if (socket === null || socket.readyState !== 1) return
1161
+ try {
1162
+ socket.send(JSON.stringify({ type: 'surface', floating: floated === true }))
1163
+ } catch {
1164
+ /* the reconnect re-announces */
1165
+ }
1166
+ }, [floated, open])
1167
+ const [failure, setFailure] = useState(undefined)
1168
+ const [hasFrame, setHasFrame] = useState(false)
1169
+ const [busy, setBusy] = useState(false)
1170
+ const [notice, setNotice] = useState('')
1171
+ /**
1172
+ * The host cancels every `will-download` on this partition, so a download link
1173
+ * inside the guest does *nothing at all* — silently. The guest fetches the bytes
1174
+ * itself (it is the only side holding the site's cookies) and hands them over;
1175
+ * the node half writes the file. This is the only feedback the human gets, so it
1176
+ * has to be visible but not in the way.
1177
+ */
1178
+ const noticeTimer = useRef(undefined)
1179
+ const flash = useCallback((text) => {
1180
+ setNotice(text)
1181
+ clearTimeout(noticeTimer.current)
1182
+ noticeTimer.current = setTimeout(() => setNotice(''), 9000)
1183
+ }, [])
1184
+ /**
1185
+ * 「浮窗」/「收回」: move this page between the column and a floating panel.
1186
+ *
1187
+ * `sidebarRight.float(tabId)` and `dock(paneId)` are two recorded layout
1188
+ * operations of the Sidebar's controller — the tab keeps its id, its body
1189
+ * and this live `<webview>`, so the page is not reloaded and the agent's
1190
+ * browser stays the same one. The controller arrives through `inject`
1191
+ * after the first render, which is why it is read from the ref here rather
1192
+ * than captured during render.
1193
+ */
1194
+ /**
1195
+ * Bring the page back from the real browser window.
1196
+ *
1197
+ * The window is a different browser, so the panel cannot simply re-dock its
1198
+ * tab: the host has to stop the window, hand routing back and let this panel
1199
+ * mount its guest again. Until that finishes there is nothing on a panel
1200
+ * layer to float or dock — measured 2026-11-29: 「切到独立窗口后再点浮窗」
1201
+ * floated an empty panel and there was no control that could bring the page
1202
+ * back at all.
1203
+ */
1204
+ const restoreFromWindow = async () => {
1205
+ const answer = await requestJson(RESTORE_PANEL_PATH, { method: 'POST', body: { sessionId } })
1206
+ if (answer?.ok !== true) throw new Error(String(answer?.error ?? 'refused'))
1207
+ setWindowed(false)
1208
+ // The window closed and the background browser came back; let the state
1209
+ // push catch up so the guest can mount on the URL it was showing.
1210
+ flash(answer.wasWindowed === true ? dict.restoreDone : dict.restoreNotWindowed)
1211
+ return answer
1212
+ }
1213
+
1214
+ const toggleFloat = () => {
1215
+ if (windowed === true) {
1216
+ setBusy(true)
1217
+ void (async () => {
1218
+ try {
1219
+ await restoreFromWindow()
1220
+ // The guest needs a beat to mount before its tab can be moved; the
1221
+ // Sidebar keeps the tab either way, so this is only about what the
1222
+ // human sees when the panel comes back.
1223
+ await new Promise((resolve) => setTimeout(resolve, 600))
1224
+ const controller = props.sidebarRef?.current
1225
+ if (floated !== true && floatTabId !== undefined && typeof controller?.float === 'function') {
1226
+ controller.float(floatTabId)
1227
+ }
1228
+ } catch (error) {
1229
+ flash(`${dict.restoreFailed}:${error?.message ?? error}`)
1230
+ } finally {
1231
+ setBusy(false)
1232
+ }
1233
+ })()
1234
+ return
1235
+ }
1236
+ const side = props.sidebarRef?.current
1237
+ try {
1238
+ if (floated) {
1239
+ if (floatPaneId !== undefined && typeof side?.dock === 'function') side.dock(floatPaneId)
1240
+ else flash(dict.floatFailed)
1241
+ } else if (floatTabId !== undefined && typeof side?.float === 'function') {
1242
+ side.float(floatTabId)
1243
+ } else {
1244
+ flash(dict.floatFailed)
1245
+ }
1246
+ } catch (error) {
1247
+ flash(`${dict.floatFailed}:${error?.message ?? error}`)
1248
+ }
1249
+ }
1250
+ const [reply, setReply] = useState('')
1251
+ /**
1252
+ * Address bar. The panel used to be read-only — a person could watch the AI's
1253
+ * page but could not open one of their own — which is not a browser, it is a
1254
+ * picture of one. The draft is held separately from the live URL so typing is
1255
+ * not fought by `did-navigate` updates from the guest.
1256
+ */
1257
+ const [addressDraft, setAddressDraft] = useState('')
1258
+ const [addressEditing, setAddressEditing] = useState(false)
1259
+ // [dsh-rc5 fix] Origin advertised by the host on the last state response.
1260
+ const [streamBase, setStreamBase] = useState('')
1261
+
1262
+ /**
1263
+ * Fold one normalized snapshot into render state.
1264
+ *
1265
+ * The functional setters keep object identities stable when nothing
1266
+ * changed, so the 2s poll cannot re-render the canvas away or fight a
1267
+ * half-typed reply.
1268
+ */
1269
+ const applySnapshot = useCallback((snapshot) => {
1270
+ if (snapshot === undefined || snapshot === null) return
1271
+ setOpen(snapshot.open === true)
1272
+ // Mirrored into a ref so the one-shot "load the first page" step can read
1273
+ // it without taking `status` as a dependency (which would rebuild the
1274
+ // guest on every navigation).
1275
+ statusUrlRef.current = typeof snapshot.url === 'string' ? snapshot.url : ''
1276
+ if (typeof snapshot.streamBaseUrl === 'string' && snapshot.streamBaseUrl !== '') {
1277
+ setStreamBase((current) => (current === snapshot.streamBaseUrl ? current : snapshot.streamBaseUrl))
1278
+ }
1279
+ setStatus((current) =>
1280
+ current.running === snapshot.running &&
1281
+ current.url === snapshot.url &&
1282
+ current.title === snapshot.title &&
1283
+ current.navSeq === snapshot.navSeq
1284
+ ? current
1285
+ : { running: snapshot.running, url: snapshot.url, title: snapshot.title, navSeq: snapshot.navSeq },
1286
+ )
1287
+ setHuman((current) => (sameHuman(current, snapshot.human) ? current : snapshot.human ?? undefined))
1288
+ setPinned((current) => (current === (snapshot.pinned === true) ? current : snapshot.pinned === true))
1289
+ setStreamMode((current) => {
1290
+ const next = snapshot.stream === 'screencast' || snapshot.stream === 'poll' ? snapshot.stream : undefined
1291
+ return current === next ? current : next
1292
+ })
1293
+ }, [])
1294
+
1295
+ /** Paint one JPEG frame onto the canvas. */
1296
+ const paint = useCallback(async (buffer) => {
1297
+ const canvas = canvasRef.current
1298
+ if (canvas === null) return
1299
+ const startedAt = performance.now()
1300
+ let bitmap
1301
+ try {
1302
+ // `event.data` is already a Blob; wrapping it in another Blob copied the
1303
+ // whole frame (a few hundred KB) before every decode.
1304
+ const source = buffer instanceof Blob ? buffer : new Blob([buffer], { type: 'image/jpeg' })
1305
+ bitmap = await createImageBitmap(source)
1306
+ } catch {
1307
+ /* a torn frame is not worth surfacing */
1308
+ return
1309
+ }
1310
+ const decodedAt = performance.now()
1311
+ try {
1312
+ // Reshaping the backing store is expensive — a 2160×1350 canvas is
1313
+ // ~11 MB — and assigning width/height reallocates it even when the
1314
+ // value did not change. Only do it when the frame really resized.
1315
+ if (canvas.width !== bitmap.width || canvas.height !== bitmap.height) {
1316
+ canvas.width = bitmap.width
1317
+ canvas.height = bitmap.height
1318
+ }
1319
+ canvas.getContext('2d').drawImage(bitmap, 0, 0)
1320
+ setHasFrame(true)
1321
+ // A frame that paints is the proof that whatever failed has recovered:
1322
+ // a genuinely broken browser stops sending them, and the note stays.
1323
+ setFailure(undefined)
1324
+ } finally {
1325
+ // ImageBitmap is an explicit resource: leaving it to the GC ties up a
1326
+ // decoded full-viewport surface for every frame in flight.
1327
+ bitmap.close()
1328
+ }
1329
+ const metrics = metricsRef.current
1330
+ metrics.frames += 1
1331
+ metrics.bytes += buffer instanceof Blob ? buffer.size : 0
1332
+ metrics.decodeMs += decodedAt - startedAt
1333
+ metrics.paintMs += performance.now() - decodedAt
1334
+ }, [])
1335
+
1336
+ /** Send one panel message when the socket is open; otherwise do nothing. */
1337
+ const send = useCallback((message) => {
1338
+ const socket = socketRef.current
1339
+ if (socket !== null && socket.readyState === 1) socket.send(JSON.stringify(message))
1340
+ }, [])
1341
+
1342
+ /**
1343
+ * Map a pointer event to page viewport coordinates — CSS pixels, which is
1344
+ * the space CDP's Input domain speaks.
1345
+ *
1346
+ * The basis is the **page viewport**, never the canvas. Frames are sized by
1347
+ * the host's frame ceiling (`renderScale`, capped by the panel's physical
1348
+ * width), so `canvas.width` is neither the viewport nor `viewport × scale`.
1349
+ * Deriving the mapping from it was off by roughly half, which is exactly how
1350
+ * "I point at the bottom and it clicks near the top" happened.
1351
+ */
1352
+ const toPageCoords = (event) => {
1353
+ const surface = surfaceRef.current
1354
+ if (surface === null) return { x: 0, y: 0 }
1355
+ const rect = surface.getBoundingClientRect()
1356
+ const viewport = viewportRef.current
1357
+ const scaleX = viewport.width / Math.max(1, rect.width)
1358
+ const scaleY = viewport.height / Math.max(1, rect.height)
1359
+ return {
1360
+ x: (event.clientX - rect.left) * scaleX,
1361
+ y: (event.clientY - rect.top) * scaleY,
1362
+ }
1363
+ }
1364
+
1365
+ /** Send one key and keep the keyboard sink focused for follow-up typing. */
1366
+ const pressKey = (spec, modifiers = []) => {
1367
+ send({ type: 'input', kind: 'key', event: 'down', ...spec, modifiers })
1368
+ send({ type: 'input', kind: 'key', event: 'up', ...spec, modifiers })
1369
+ sinkRef.current?.focus?.()
1370
+ }
1371
+
1372
+ /**
1373
+ * The live channel of *this* session's tab.
1374
+ *
1375
+ * Reconnects with backoff while this tab is on screen, asks for `focus` on
1376
+ * (re)connect — the host then activates this browser tab and upgrades it to
1377
+ * a full-rate screencast — and seeds one frame with `play`, because a static
1378
+ * page produces no frames of its own. A session without a tab, or a tab the
1379
+ * human is not looking at, never holds a socket at all.
1380
+ */
1381
+ useEffect(() => {
1382
+ // `visible` deliberately does **not** gate this connection any more. The
1383
+ // host keeps a desktop browser tab mounted across tab switches, Session
1384
+ // switches, collapse and docking (`keepMounted`), so the guest behind this
1385
+ // socket is still a live page while the tab is in the background — and
1386
+ // dropping the socket used to mean dropping the guest, which silently sent
1387
+ // every tool call back to the invisible headless tab. A background tab now
1388
+ // keeps its browser; only a closed tab (`open !== true`) lets it go.
1389
+ if (sessionId === '' || open !== true) {
1390
+ trace('GATE-BLOCK', { sid: sessionId, open: String(open), visible: String(visible) })
1391
+ setConnection('idle')
1392
+ return undefined
1393
+ }
1394
+ trace('GATE-PASS', { sid: sessionId })
1395
+ const candidates = streamCandidates(streamBase)
1396
+ trace('WS-CANDIDATES', { list: candidates.map((entry) => entry.origin).join('|') })
1397
+ let disposed = false
1398
+ let attempt = 0
1399
+ let timer
1400
+ const clearTimer = () => {
1401
+ if (timer !== undefined) {
1402
+ clearTimeout(timer)
1403
+ timer = undefined
1404
+ }
1405
+ }
1406
+ const schedule = () => {
1407
+ if (disposed) return
1408
+ const delay = Math.min(RECONNECT_MAX_MS, RECONNECT_BASE_MS * 2 ** attempt) + Math.round(Math.random() * 250)
1409
+ attempt += 1
1410
+ clearTimer()
1411
+ timer = setTimeout(connect, delay)
1412
+ }
1413
+ const connect = () => {
1414
+ if (disposed) return
1415
+ setConnection('connecting')
1416
+ const candidate = candidates.length === 0 ? undefined : candidates[attempt % candidates.length]
1417
+ const url = candidate === undefined ? '' : streamUrl(sessionId, candidate)
1418
+ trace('WS-DIAL', {
1419
+ url,
1420
+ base: candidate === undefined ? '-' : candidate.origin,
1421
+ host: String(window.location.host ?? ''),
1422
+ transport: String(globalThis.__DSH_TRANSPORT__?.streamBaseUrl ?? '-'),
1423
+ })
1424
+ if (url === '') {
1425
+ trace('WS-NOBASE', { sid: sessionId })
1426
+ setConnection('idle')
1427
+ return
1428
+ }
1429
+ let socket
1430
+ try {
1431
+ socket = new WebSocket(url)
1432
+ } catch (error) {
1433
+ trace('WS-THROW', { msg: String(error?.message ?? error) })
1434
+ schedule()
1435
+ return
1436
+ }
1437
+ socket.binaryType = 'arraybuffer'
1438
+ socketRef.current = socket
1439
+ socket.onopen = () => {
1440
+ if (disposed) {
1441
+ try {
1442
+ socket.close()
1443
+ } catch {
1444
+ /* already closing */
1445
+ }
1446
+ return
1447
+ }
1448
+ attempt = 0
1449
+ setConnection('live')
1450
+ setFailure(undefined)
1451
+ trace('WS-OPEN', { sid: sessionId })
1452
+ if (NATIVE_VIEW) {
1453
+ // A native guest paints itself. Telling the host "this panel is not a
1454
+ // viewer" is stronger than `blur`: it keeps a poller from being started
1455
+ // for a picture nothing displays.
1456
+ socket.send(JSON.stringify({ type: 'native' }))
1457
+ // Announce the guest on *every* connect, not just the first mount. The
1458
+ // host routes tool calls by connection, so a reconnect that forgets this
1459
+ // silently sends every call back to the invisible headless tab.
1460
+ if (viewRef.current !== null && viewRef.current !== undefined) {
1461
+ socket.send(JSON.stringify({ type: 'guest-ready' }))
1462
+ }
1463
+ // "Somebody is looking at this browser" — separate from "this panel is
1464
+ // a viewer". Residency must not reclaim a page while a person has it on
1465
+ // screen, and before this the native path never said so.
1466
+ socket.send(JSON.stringify({ type: 'focus' }))
1467
+ socket.send(JSON.stringify({ type: 'surface', floating: floatedRef.current === true }))
1468
+ } else {
1469
+ if (document.visibilityState !== 'hidden') socket.send(JSON.stringify({ type: 'focus' }))
1470
+ // A static page emits nothing by itself: ask for one frame.
1471
+ socket.send(JSON.stringify({ type: 'play' }))
1472
+ }
1473
+ }
1474
+ socket.onclose = () => {
1475
+ if (socketRef.current === socket) socketRef.current = null
1476
+ if (disposed) return
1477
+ trace('WS-CLOSE', { sid: sessionId, attempt: String(attempt) })
1478
+ setConnection('offline')
1479
+ schedule()
1480
+ }
1481
+ socket.onerror = () => {
1482
+ /* `onclose` always follows and owns the reconnect */
1483
+ }
1484
+ socket.onmessage = (event) => {
1485
+ if (typeof event.data !== 'string') {
1486
+ // Coalesce instead of drop. The old code refused every frame that
1487
+ // arrived while one was decoding, then waited for the *next* one, so
1488
+ // the ceiling became "one frame per decode interval, plus a gap" —
1489
+ // which is how a 56 fps stream reached the panel as ~25.
1490
+ pendingFrameRef.current = event.data
1491
+ if (decodingRef.current) return
1492
+ decodingRef.current = true
1493
+ void (async () => {
1494
+ try {
1495
+ while (pendingFrameRef.current !== undefined) {
1496
+ const frame = pendingFrameRef.current
1497
+ pendingFrameRef.current = undefined
1498
+ await paint(frame)
1499
+ }
1500
+ } finally {
1501
+ decodingRef.current = false
1502
+ }
1503
+ })()
1504
+ return
1505
+ }
1506
+ let message
1507
+ try {
1508
+ message = JSON.parse(event.data)
1509
+ } catch {
1510
+ return
1511
+ }
1512
+ if (message.type === 'hello') {
1513
+ const snapshot = snapshotFromState(message.status ?? {})
1514
+ if (message.human !== undefined && message.human !== null) snapshot.human = message.human
1515
+ snapshot.stream = message.mode === 'screencast' || message.mode === 'poll' ? message.mode : null
1516
+ // `hello` is the first word a (re)connecting panel hears, and the
1517
+ // host already knows whether this page lives in a real window. Take
1518
+ // it as authoritative: the mount effect keys on `windowed`, and
1519
+ // waiting for a later state push lets a 300ms timer mount a guest
1520
+ // that would then steal routing from the window.
1521
+ setWindowed(message.windowed === true)
1522
+ // A (re)connect may follow a recreated tab whose viewport went back
1523
+ // to the configured shape: drop the dead band so the current aspect
1524
+ // is offered again instead of being suppressed as "unchanged".
1525
+ lastAspectRef.current = 0
1526
+ if (message.viewport !== null && message.viewport !== undefined) {
1527
+ const width = Number(message.viewport.width)
1528
+ const height = Number(message.viewport.height)
1529
+ if (width > 0 && height > 0) viewportRef.current = { width, height }
1530
+ }
1531
+ setTransport(message.transport === 'mjpeg' ? 'mjpeg' : 'ws')
1532
+ applySnapshot(snapshot)
1533
+ return
1534
+ }
1535
+ if (message.type === 'state') {
1536
+ applySnapshot(snapshotFromMessage(message))
1537
+ setWindowed(message.windowed === true)
1538
+ setFps(typeof message.fps === 'number' ? message.fps : undefined)
1539
+ // A navigation or a reshaped session changes the viewport; the
1540
+ // pointer mapping has to follow it or clicks drift by the old ratio.
1541
+ if (message.viewport !== null && message.viewport !== undefined) {
1542
+ const vw = Number(message.viewport.width)
1543
+ const vh = Number(message.viewport.height)
1544
+ if (vw > 0 && vh > 0) viewportRef.current = { width: vw, height: vh }
1545
+ }
1546
+ // A navigation resets the emulated viewport to the configured shape.
1547
+ // The panel container did not resize, so `ResizeObserver` stays
1548
+ // quiet and nothing would ever re-offer this panel's aspect — the
1549
+ // letterbox would quietly come back and the fix would look flaky.
1550
+ const shaped = message.viewport
1551
+ const stage = NATIVE_VIEW ? null : stageRef.current
1552
+ if (shaped !== null && shaped !== undefined && stage !== null && socket.readyState === 1) {
1553
+ const rect = stage.getBoundingClientRect()
1554
+ const got = shaped.width / shaped.height
1555
+ if (rect.width >= 80 && rect.height >= 80 && Number.isFinite(got) && got > 0) {
1556
+ const want = rect.width / rect.height
1557
+ // Two guards, because this message is what used to close the
1558
+ // start/stop loop: only act on a real mismatch, and at most once
1559
+ // every few seconds, so a host that cannot honour the shape is
1560
+ // retried calmly instead of hammered.
1561
+ const at = Date.now()
1562
+ if (Math.abs(want - got) / got >= 0.05 && at - lastAspectSentAtRef.current > 2000) {
1563
+ lastAspectSentAtRef.current = at
1564
+ lastAspectRef.current = want
1565
+ const pixelWidth = rect.width * (window.devicePixelRatio || 1)
1566
+ socket.send(JSON.stringify({ type: 'viewport', aspect: want, pixelWidth: Math.round(pixelWidth) }))
1567
+ }
1568
+ }
1569
+ }
1570
+ return
1571
+ }
1572
+ if (message.type === 'guest-call') {
1573
+ // The agent is asking this panel to operate its own page. Always answer,
1574
+ // even on failure: a silent drop leaves the tool call waiting for its
1575
+ // whole timeout with no idea why.
1576
+ const callId = message.id
1577
+ void (async () => {
1578
+ try {
1579
+ const result = await runGuestCall(String(message.method ?? ''), message.params ?? {})
1580
+ socket.send(JSON.stringify({ type: 'guest-result', id: callId, ok: true, result: result === undefined ? null : result }))
1581
+ } catch (error) {
1582
+ socket.send(JSON.stringify({ type: 'guest-result', id: callId, ok: false, error: String(error?.message ?? error) }))
1583
+ }
1584
+ })()
1585
+ return
1586
+ }
1587
+ if (message.type === 'reclaim') {
1588
+ // The host is reclaiming memory: nobody is looking at this page, no
1589
+ // call is in flight, and the idle window has passed. Tear the guest
1590
+ // down and *say so* — the host keeps routing to this browser until it
1591
+ // hears that the page is really gone, because routing a call into a
1592
+ // torn-down page would be worse than keeping an idle one alive.
1593
+ //
1594
+ // `reason: 'window'` is the other case: the page was moved into a real
1595
+ // browser window on purpose. Same teardown, different message to the
1596
+ // human — nothing was lost, the controls moved.
1597
+ const element = viewRef.current
1598
+ viewRef.current = null
1599
+ if (element !== null && element !== undefined) {
1600
+ try {
1601
+ element.remove()
1602
+ } catch {
1603
+ /* already detached */
1604
+ }
1605
+ }
1606
+ setNativeReady(false)
1607
+ if (message.reason === 'window') {
1608
+ // Record it locally at once: the state push that carries
1609
+ // `windowed: true` may arrive a beat later, and until it does the
1610
+ // watchdog would remount a guest — the panel would show a second
1611
+ // copy of the page that is already in the real window.
1612
+ setWindowed(true)
1613
+ flash(dict.movedToWindow)
1614
+ }
1615
+ try {
1616
+ socket.send(JSON.stringify({ type: 'guest-gone' }))
1617
+ } catch {
1618
+ /* the reconnect will re-announce if the host still wants one */
1619
+ }
1620
+ return
1621
+ }
1622
+ if (message.type === 'stream') {
1623
+ setStreamMode(message.mode === 'screencast' || message.mode === 'poll' ? message.mode : undefined)
1624
+ return
1625
+ }
1626
+ if (message.type === 'human-request') {
1627
+ setHuman(message.request ?? undefined)
1628
+ return
1629
+ }
1630
+ if (message.type === 'human-done' || message.type === 'human-timeout') {
1631
+ setHuman((current) => (current !== undefined && current.id === message.id ? undefined : current))
1632
+ return
1633
+ }
1634
+ if (message.type === 'download-saved') {
1635
+ flash(`已下载 ${message.name ?? ''} → ${message.path ?? ''}`.trim())
1636
+ return
1637
+ }
1638
+ if (message.type === 'download-failed') {
1639
+ flash(`下载失败:${message.reason ?? '未知原因'}`)
1640
+ return
1641
+ }
1642
+ if (message.type === 'error') {
1643
+ setFailure(String(message.message ?? 'failed'))
1644
+ return
1645
+ }
1646
+ if (message.type === 'window-closed') {
1647
+ // Somebody closed the real window (or the fallback is running).
1648
+ // Nothing about this panel's page depends on that window any more.
1649
+ setWindowed(false)
1650
+ flash(dict.windowClosed)
1651
+ return
1652
+ }
1653
+ if (message.type === 'browser-restored') {
1654
+ flash(dict.windowRestored)
1655
+ return
1656
+ }
1657
+ if (message.type === 'browser-stopped') {
1658
+ setFailure(undefined)
1659
+ setHasFrame(false)
1660
+ }
1661
+ // `sessions` overview messages belong to the sidebar panel, not here.
1662
+ }
1663
+ }
1664
+ connect()
1665
+ return () => {
1666
+ disposed = true
1667
+ clearTimer()
1668
+ const socket = socketRef.current
1669
+ socketRef.current = null
1670
+ if (socket !== null) {
1671
+ try {
1672
+ if (socket.readyState === 1) socket.send(JSON.stringify({ type: 'blur' }))
1673
+ } catch {
1674
+ /* the socket may already be gone */
1675
+ }
1676
+ try {
1677
+ socket.close()
1678
+ } catch {
1679
+ /* already closed */
1680
+ }
1681
+ }
1682
+ setConnection('idle')
1683
+ if (moveFrameRef.current !== 0) {
1684
+ cancelAnimationFrame(moveFrameRef.current)
1685
+ moveFrameRef.current = 0
1686
+ }
1687
+ pendingMoveRef.current = undefined
1688
+ pendingFrameRef.current = undefined
1689
+ }
1690
+ }, [sessionId, open, streamBase, applySnapshot, paint])
1691
+
1692
+ /**
1693
+ * Tell the host how tall this panel is, so the page viewport can match the
1694
+ * Sidebar's shape instead of being letter-boxed into it.
1695
+ *
1696
+ * Only the aspect ratio travels. The host keeps the configured width — so
1697
+ * the page stays a desktop layout and stays readable — and derives the
1698
+ * height from this panel, which is what turns the empty bands above and
1699
+ * below the frame into page. A 2% dead band keeps a Sidebar drag from
1700
+ * re-setting the viewport once per pixel.
1701
+ */
1702
+ useEffect(() => {
1703
+ // Reshaping the host's viewport only exists to fit the pixel stream into the
1704
+ // panel. A native guest is laid out by the panel itself, so there is nothing
1705
+ // to negotiate — and doing it anyway would resize the page under the human.
1706
+ if (NATIVE_VIEW) return undefined
1707
+ if (open !== true || connection !== 'live') return undefined
1708
+ const stage = stageRef.current
1709
+ if (stage === null || typeof ResizeObserver !== 'function') return undefined
1710
+ const push = () => {
1711
+ const rect = stage.getBoundingClientRect()
1712
+ if (rect.width < 80 || rect.height < 80) return
1713
+ const aspect = rect.width / rect.height
1714
+ const previous = lastAspectRef.current
1715
+ if (previous > 0 && Math.abs(aspect - previous) / previous < 0.02) return
1716
+ // Same rate limit as the state-driven retry: a resize storm must not turn
1717
+ // into a restart storm on the host.
1718
+ const at = Date.now()
1719
+ if (at - lastAspectSentAtRef.current < 500) return
1720
+ lastAspectSentAtRef.current = at
1721
+ lastAspectRef.current = aspect
1722
+ // The frame ceiling comes from this panel's *physical* width: pushing
1723
+ // 2160 px into a 1700 px panel bought no visible sharpness and spent
1724
+ // ~40% of the bandwidth the decoder was already waiting on.
1725
+ const pixelWidth = rect.width * (window.devicePixelRatio || 1)
1726
+ send({ type: 'viewport', aspect, pixelWidth: Math.round(pixelWidth) })
1727
+ }
1728
+ push()
1729
+ const observer = new ResizeObserver(push)
1730
+ observer.observe(stage)
1731
+ return () => observer.disconnect()
1732
+ }, [open, connection, send])
1733
+
1734
+ /**
1735
+ * Report this panel's own decode and paint cost every few seconds.
1736
+ *
1737
+ * The status bar says how many frames arrived; it cannot say where the time
1738
+ * went. These numbers land in `browser-stream.log` beside the host's own,
1739
+ * which is what turns "it feels slow" into "the decoder needs 34 ms" or
1740
+ * "the socket is 1 MB behind".
1741
+ */
1742
+ useEffect(() => {
1743
+ if (connection !== 'live') return undefined
1744
+ const timer = setInterval(() => {
1745
+ const metrics = metricsRef.current
1746
+ if (metrics.frames === 0) return
1747
+ send({
1748
+ type: 'metrics',
1749
+ frames: metrics.frames,
1750
+ bytes: metrics.bytes,
1751
+ decodeAvg: Number((metrics.decodeMs / metrics.frames).toFixed(1)),
1752
+ paintAvg: Number((metrics.paintMs / metrics.frames).toFixed(1)),
1753
+ })
1754
+ metricsRef.current = { frames: 0, bytes: 0, decodeMs: 0, paintMs: 0 }
1755
+ }, 3000)
1756
+ return () => clearInterval(timer)
1757
+ }, [connection, send])
1758
+
1759
+ /**
1760
+ * Build (and rebuild) the MJPEG URL.
1761
+ *
1762
+ * The stream is a `multipart/x-mixed-replace` response, so the browser's own
1763
+ * image pipeline decodes and composites every part while the panel thread
1764
+ * never touches a pixel — that is the entire reason this transport exists.
1765
+ * A generation counter rides in the query so a reconnect is a genuinely new
1766
+ * request rather than a cached or half-dead one.
1767
+ *
1768
+ * The URL stays **relative on purpose**. The desktop shell serves this page
1769
+ * from `dsh-app://app` and forwards every other `/api/*` path to the Host
1770
+ * while injecting the authenticated cookie — that is how every JSON call
1771
+ * here already works. An absolute `http://127.0.0.1:<port>/…` image request
1772
+ * leaves that path, arrives at the Host directly, and the Host's trust fence
1773
+ * sees `Sec-Fetch-Site: cross-site` and answers 403 before authentication is
1774
+ * even consulted. Relative also means the identical code works in a plain
1775
+ * browser, where the page origin *is* the Host, and where the forwarded
1776
+ * response body stays a stream instead of being buffered.
1777
+ */
1778
+ useEffect(() => {
1779
+ // `visible` must be part of this gate. The socket already stops when the
1780
+ // panel is hidden, but an `<img>` left mounted keeps pulling the whole
1781
+ // stream down the wire — the host keeps encoding and the browser keeps
1782
+ // decoding for a picture nobody can see. Dropping the URL unmounts the
1783
+ // element, which closes the HTTP response, which tells the hub that this
1784
+ // session no longer has a viewer.
1785
+ if (transport !== 'mjpeg' || open !== true || visible !== true || sessionId === '') {
1786
+ setLiveUrl('')
1787
+ return
1788
+ }
1789
+ setLiveUrl(`${MJPEG_PATH}?session=${encodeURIComponent(sessionId)}&g=${liveGeneration}`)
1790
+ }, [transport, open, visible, sessionId, liveGeneration])
1791
+
1792
+ /**
1793
+ * Retry a broken stream with exponential backoff.
1794
+ *
1795
+ * A rejected request fires `error` at once, so a flat retry turns one
1796
+ * misconfiguration into a request per second for as long as the panel stays
1797
+ * open — that is exactly what filled the trace file. The counter resets on
1798
+ * the first decoded frame, so a genuine drop still reconnects promptly.
1799
+ */
1800
+ const liveFailures = useRef(0)
1801
+ const reconnectLive = useCallback(() => {
1802
+ liveFailures.current += 1
1803
+ const delay = Math.min(700 * 2 ** (liveFailures.current - 1), 8000)
1804
+ window.setTimeout(() => setLiveGeneration((generation) => generation + 1), delay)
1805
+ }, [])
1806
+
1807
+ /**
1808
+ * Prove that a frame actually arrived.
1809
+ *
1810
+ * A `multipart/x-mixed-replace` image is *still loading* while the stream is
1811
+ * open, so `load` may never fire at all — waiting for it would leave the
1812
+ * panel stuck on「等待画面」forever. `naturalWidth` becomes non-zero as soon
1813
+ * as the first part has been decoded, so poll it briefly instead.
1814
+ */
1815
+ useEffect(() => {
1816
+ if (transport !== 'mjpeg' || liveUrl === '') return undefined
1817
+ setHasFrame(false)
1818
+ const timer = window.setInterval(() => {
1819
+ const image = surfaceRef.current
1820
+ if (!image || image.naturalWidth === 0) return
1821
+ window.clearInterval(timer)
1822
+ liveFailures.current = 0
1823
+ setHasFrame(true)
1824
+ setFailure(undefined)
1825
+ }, 250)
1826
+ return () => window.clearInterval(timer)
1827
+ }, [transport, liveUrl])
1828
+
1829
+ /**
1830
+ * State poll for everything the socket cannot tell us yet: whether this
1831
+ * session has a tab at all, and what it shows while the socket is down
1832
+ * (reconnecting, or the host restarted). It stays out of the way while the
1833
+ * socket is live, which pushes state itself.
1834
+ */
1835
+ useEffect(() => {
1836
+ if (sessionId === '') return undefined
1837
+ let cancelled = false
1838
+ const tick = async () => {
1839
+ const socket = socketRef.current
1840
+ if (socket !== null && socket.readyState === 1) return
1841
+ try {
1842
+ const payload = await requestJson(`${STATE_PATH}?session=${encodeURIComponent(sessionId)}`)
1843
+ if (cancelled) return
1844
+ applySnapshot(snapshotFromState(payload))
1845
+ } catch {
1846
+ /* the GUI may be reloading; the next tick recovers */
1847
+ }
1848
+ }
1849
+ void tick()
1850
+ const timer = setInterval(() => void tick(), STATE_POLL_MS)
1851
+ return () => {
1852
+ cancelled = true
1853
+ clearInterval(timer)
1854
+ }
1855
+ }, [sessionId, applySnapshot])
1856
+
1857
+ /**
1858
+ * Drain the bytes the guest parked after a download link was clicked.
1859
+ *
1860
+ * One tiny `executeJavaScript` per second that answers `null` when there is
1861
+ * nothing to do; the bytes themselves only travel once something was clicked.
1862
+ * The host has already cancelled the real download, so this is the only path.
1863
+ */
1864
+ useEffect(() => {
1865
+ if (NATIVE_VIEW !== true || open !== true) return undefined
1866
+ const timer = setInterval(async () => {
1867
+ const element = viewRef.current
1868
+ if (element === null || element === undefined) return
1869
+ let item
1870
+ try {
1871
+ item = await element.executeJavaScript(
1872
+ '(() => { const q = window.__debDownloadQueue; return Array.isArray(q) && q.length > 0 ? q.shift() : null })()',
1873
+ )
1874
+ } catch {
1875
+ return
1876
+ }
1877
+ if (item === null || item === undefined) return
1878
+ if (item.state !== 'ready') {
1879
+ flash(`下载失败:${item.reason ?? '未知原因'}`)
1880
+ return
1881
+ }
1882
+ send({ type: 'download', name: item.name ?? '', base64: item.base64, size: item.size })
1883
+ }, 1000)
1884
+ return () => clearInterval(timer)
1885
+ }, [open, send, flash])
1886
+
1887
+ /**
1888
+ * Mount the native surface.
1889
+ *
1890
+ * This is the architecture change in one effect: the panel shows a real
1891
+ * Chromium guest instead of a JPEG of one. The element is created by hand
1892
+ * (React rendering `<webview>` took the entire panel down), and the host only
1893
+ * lets it attach because it carries a lease from the browser bridge.
1894
+ */
1895
+ useEffect(() => {
1896
+ if (NATIVE_VIEW !== true || open !== true) return undefined
1897
+ // A page the host put into a real window is not this panel's to mount:
1898
+ // a guest here wins tool routing and the agent would drive the panel copy.
1899
+ if (windowed === true) return undefined
1900
+ const stage = stageRef.current
1901
+ if (stage === null || stage === undefined) return undefined
1902
+ let cancelled = false
1903
+ let element
1904
+ let loaded = false
1905
+ let grantedLease
1906
+ let grantedBridge
1907
+ let unsubscribeOpen
1908
+ let fitTimer
1909
+ let fitObserver
1910
+ const report = (name, extra) => send({ type: 'probe', data: { stage: name, ...extra } })
1911
+ let attempts = 0
1912
+ let gaveUp = false
1913
+ const start = () => {
1914
+ if (cancelled || gaveUp) return
1915
+ // `send()` drops messages until the socket is up, and the socket is the
1916
+ // only channel to the host's log; retry instead of reporting into the void.
1917
+ const socket = socketRef.current
1918
+ if (socket === null || socket.readyState !== 1) {
1919
+ attempts += 1
1920
+ // This loop used to be silent and endless: the panel said 「连接中」
1921
+ // while no dial, no acquire and no log line were happening at all. It
1922
+ // now says what it waits for, and gives up loudly instead of politely.
1923
+ setMountStage(`${dict.mountWaitSocket}(${attempts})`)
1924
+ if (attempts > 60) {
1925
+ gaveUp = true
1926
+ report('mount-no-socket', { attempts })
1927
+ setMountStage(dict.mountNoSocket)
1928
+ return
1929
+ }
1930
+ setTimeout(start, 250)
1931
+ return
1932
+ }
1933
+ attempts = 0
1934
+ setMountStage(dict.mountAcquire)
1935
+ const desktop = globalThis.dshDesktop
1936
+ const bridge = desktop?.browser
1937
+ if (bridge === undefined || typeof bridge.acquire !== 'function') {
1938
+ report('no-browser-bridge', { hasDshDesktop: typeof desktop })
1939
+ return
1940
+ }
1941
+ // A fixed workspace key is exactly right: it is only the storage identity,
1942
+ // and every session sharing one login store is the point.
1943
+ bridge
1944
+ .acquire('dsh-embedded-browser')
1945
+ .then((grant) => {
1946
+ const leaseId = grant?.lease
1947
+ if (cancelled) {
1948
+ // The lease arrived after this effect was torn down. Nothing else
1949
+ // will ever free it: cleanup ran before `grantedLease` existed, and
1950
+ // a leaked lease leaves the *next* mount waiting for a browser that
1951
+ // never arrives — which is exactly the silent 「连接中」 measured on
1952
+ // 2026-11-27, one switch-away per leak.
1953
+ try {
1954
+ bridge.release?.(leaseId)?.catch?.(() => {})
1955
+ } catch {
1956
+ /* the host may already be gone */
1957
+ }
1958
+ return
1959
+ }
1960
+ const partition = grant?.partition
1961
+ if (typeof leaseId !== 'string' || typeof partition !== 'string') {
1962
+ report('bad-grant', { leaseId: String(leaseId), partition: String(partition) })
1963
+ return
1964
+ }
1965
+ grantedLease = leaseId
1966
+ grantedBridge = bridge
1967
+ try {
1968
+ element = document.createElement('webview')
1969
+ element.className = 'deb-native'
1970
+ element.setAttribute('partition', partition)
1971
+ // Without this a page can enter "web fullscreen" (a CSS trick that only
1972
+ // fills its own box) but never real fullscreen, because the request is
1973
+ // refused at the guest boundary. The panel is still the ceiling — the
1974
+ // host decides whether to honour it — but the attribute is what makes
1975
+ // the request arrive at all.
1976
+ element.setAttribute('allowfullscreen', '')
1977
+ element.setAttribute('src', `about:blank#${leaseId}`)
1978
+ stage.appendChild(element)
1979
+ viewRef.current = element
1980
+ } catch (error) {
1981
+ report('attach-threw', { message: String(error?.message ?? error) })
1982
+ return
1983
+ }
1984
+ // The human's own navigation must reach the host, or the AI would keep
1985
+ // operating the page it opened while the human looks at another one.
1986
+ const publish = (url) => {
1987
+ if (typeof url !== 'string' || url === '') return
1988
+ // The guest starts on `about:blank#<lease>`; that is plumbing, not a
1989
+ // page, and reporting it would send the host's browser to a blank tab.
1990
+ if (url.startsWith('about:')) return
1991
+ // Diagnostic: one click that opens "two or three videos" means the
1992
+ // guest really navigated that many times. The only way to tell is to
1993
+ // read the sequence, so every guest navigation is logged.
1994
+ report('guest-nav', { url: url.slice(0, 160) })
1995
+ viewUrlRef.current = url
1996
+ setViewUrl(url)
1997
+ // A navigation this panel caused itself must not be reported back as
1998
+ // the human's: the echo would make the host follow its own command.
1999
+ if (hostUrlRef.current === url) return
2000
+ send({ type: 'view-nav', url })
2001
+ }
2002
+ element.addEventListener('dom-ready', () => {
2003
+ setNativeReady(true)
2004
+ setMountStage('')
2005
+ // A new document has no click hook; re-arm it on every page. This only
2006
+ // injects script — it never calls `loadURL`, so it cannot cause the
2007
+ // reload loop that the first-load guard below exists for.
2008
+ void element.executeJavaScript(DOWNLOAD_HOOK_JS).catch(() => {})
2009
+ // `dom-ready` fires after **every** navigation, so loading here
2010
+ // unconditionally made the guest reload itself in a loop.
2011
+ if (loaded === true) return
2012
+ loaded = true
2013
+ const initial = statusUrlRef.current
2014
+ if (initial === '') return
2015
+ hostUrlRef.current = initial
2016
+ element
2017
+ .loadURL(initial)
2018
+ .catch((error) => report('first-load-failed', { message: String(error?.message ?? error) }))
2019
+ })
2020
+ element.addEventListener('did-navigate', (event) => publish(event?.url))
2021
+ element.addEventListener('did-navigate-in-page', (event) => {
2022
+ if (typeof event?.url !== 'string' || event.url === '') return
2023
+ viewUrlRef.current = event.url
2024
+ setViewUrl(event.url)
2025
+ })
2026
+ element.addEventListener('page-title-updated', (event) => {
2027
+ if (typeof event?.title === 'string') setViewTitle(event.title)
2028
+ })
2029
+ element.addEventListener('did-fail-load', (event) =>
2030
+ report('did-fail-load', { code: event?.errorCode, desc: event?.errorDescription }),
2031
+ )
2032
+ /**
2033
+ * Make a desktop-width page fit, and report the two numbers that decide
2034
+ * whether that is even the right diagnosis.
2035
+ *
2036
+ * `elementW` is the box the panel gives the guest; `innerW` is the CSS
2037
+ * viewport the page sees; `scrollW` is how wide the page insists on
2038
+ * being. If they disagree the panel is being lied to about its own size;
2039
+ * if `scrollW` is simply larger, the site just is that wide.
2040
+ */
2041
+ const fitGuest = async () => {
2042
+ if (cancelled) return
2043
+ const current = viewRef.current
2044
+ if (current === null || current === undefined) return
2045
+ const rect = current.getBoundingClientRect()
2046
+ if (rect.width < 120) return
2047
+ let info
2048
+ try {
2049
+ info = await current.executeJavaScript(
2050
+ '({ w: window.innerWidth || 0, '
2051
+ + 'sw: (document.documentElement && document.documentElement.scrollWidth) || 0, '
2052
+ + 'dpr: window.devicePixelRatio || 1 })',
2053
+ )
2054
+ } catch {
2055
+ return
2056
+ }
2057
+ const innerWidth = Number(info?.w ?? 0)
2058
+ if (innerWidth <= 0) return
2059
+ const scrollWidth = Number(info?.sw ?? 0)
2060
+ report('size', {
2061
+ elementW: Math.round(rect.width),
2062
+ elementH: Math.round(rect.height),
2063
+ innerW: innerWidth,
2064
+ scrollW: scrollWidth,
2065
+ })
2066
+ if (FIT_WIDTH !== true) return
2067
+ // The page needs `needed` CSS pixels; the panel offers `rect.width`.
2068
+ const needed = Math.max(innerWidth, scrollWidth)
2069
+ const zoom = Math.max(0.4, Math.min(1.25, rect.width / needed))
2070
+ if (Math.abs(zoom - 1) < 0.02) {
2071
+ try {
2072
+ current.setZoomFactor?.(1)
2073
+ } catch {
2074
+ /* older host without zoom control */
2075
+ }
2076
+ return
2077
+ }
2078
+ try {
2079
+ current.setZoomFactor?.(zoom)
2080
+ } catch {
2081
+ /* older host without zoom control */
2082
+ }
2083
+ }
2084
+ element.addEventListener('did-finish-load', () => void fitGuest())
2085
+ element.addEventListener('dom-ready', () => void fitGuest())
2086
+ // A panel that is resized (the Sidebar is draggable) must re-fit; the
2087
+ // guest itself never sees that resize.
2088
+ if (typeof ResizeObserver === 'function') {
2089
+ fitObserver = new ResizeObserver(() => {
2090
+ if (fitTimer !== undefined) clearTimeout(fitTimer)
2091
+ fitTimer = setTimeout(() => void fitGuest(), 250)
2092
+ })
2093
+ fitObserver.observe(stage)
2094
+ }
2095
+ // Links that ask for a new window (`target="_blank"`, `window.open`)
2096
+ // are routed to the lease holder by the host, because a plugin cannot
2097
+ // open a real second window. Dropping them is exactly the "clicking a
2098
+ // video does nothing" report — the page scrolls, the click lands, and
2099
+ // the navigation goes nowhere. So follow the request in place.
2100
+ // One click must produce exactly one navigation. It can arrive twice —
2101
+ // once as the link's own same-tab navigation and once as the host's
2102
+ // new-window request — and loading both looks like "it opened two or
2103
+ // three videos". A short window keyed on the URL collapses them.
2104
+ if (typeof bridge.onOpenRequested === 'function') {
2105
+ try {
2106
+ unsubscribeOpen = bridge.onOpenRequested(leaseId, (url) => {
2107
+ if (cancelled || typeof url !== 'string' || url === '') return
2108
+ const now = Date.now()
2109
+ const last = guestNavRef.current
2110
+ if (last.url === url && now - last.at < 1500) return
2111
+ guestNavRef.current = { url, at: now }
2112
+ try {
2113
+ element.loadURL(url).catch(() => {})
2114
+ } catch {
2115
+ /* the guest is gone */
2116
+ }
2117
+ })
2118
+ } catch {
2119
+ /* older host without the callback */
2120
+ }
2121
+ }
2122
+ // A plugin cannot open a real second window, and this guest's host does
2123
+ // not surface new-window requests either (measured: removing this made
2124
+ // every `target="_blank"` click do nothing at all). So the only working
2125
+ // route is to rewrite the target before the click lands.
2126
+ const guard = () => {
2127
+ const script = `(() => {
2128
+ if (window.__debLinkGuard === true) return
2129
+ window.__debLinkGuard = true
2130
+ const fix = (root) => {
2131
+ const links = root.querySelectorAll ? root.querySelectorAll('a[target="_blank"]') : []
2132
+ for (const link of links) link.target = '_self'
2133
+ }
2134
+ fix(document)
2135
+ new MutationObserver((records) => {
2136
+ for (const record of records) {
2137
+ for (const node of record.addedNodes) if (node.nodeType === 1) fix(node)
2138
+ }
2139
+ }).observe(document.documentElement, { childList: true, subtree: true })
2140
+ })()`
2141
+ try {
2142
+ element.executeJavaScript?.(script)?.catch?.(() => {})
2143
+ } catch {
2144
+ /* the guest cannot execute scripts (yet) */
2145
+ }
2146
+ }
2147
+ element.addEventListener('did-finish-load', guard)
2148
+ element.addEventListener('did-navigate', guard)
2149
+ report('native-attached', { partition })
2150
+ // This panel can now serve the agent's tool calls: it owns the page the
2151
+ // human is looking at, and it is a browser sites do not treat as a bot.
2152
+ send({ type: 'guest-ready' })
2153
+ })
2154
+ .catch((error) => report('acquire-failed', { message: String(error?.message ?? error) }))
2155
+ }
2156
+ const timer = setTimeout(start, 300)
2157
+ return () => {
2158
+ cancelled = true
2159
+ clearTimeout(timer)
2160
+ viewRef.current = null
2161
+ setNativeReady(false)
2162
+ setMountStage('')
2163
+ if (fitTimer !== undefined) clearTimeout(fitTimer)
2164
+ try {
2165
+ fitObserver?.disconnect()
2166
+ } catch {
2167
+ /* already gone */
2168
+ }
2169
+ if (typeof unsubscribeOpen === 'function') {
2170
+ try {
2171
+ unsubscribeOpen()
2172
+ } catch {
2173
+ /* the host may already be gone */
2174
+ }
2175
+ }
2176
+ try {
2177
+ element?.remove()
2178
+ } catch {
2179
+ /* already detached */
2180
+ }
2181
+ // A lease is an entry in the host's guest table; leaving it behind leaks
2182
+ // one per mount, and the partition only goes away with the last lease.
2183
+ if (grantedLease !== undefined) {
2184
+ try {
2185
+ grantedBridge?.release?.(grantedLease)?.catch?.(() => {})
2186
+ } catch {
2187
+ /* the host may already be gone */
2188
+ }
2189
+ }
2190
+ }
2191
+ }, [open, send, mountNonce, windowed])
2192
+
2193
+ /**
2194
+ * Watchdog for a mount that never finishes.
2195
+ *
2196
+ * The measured failure (2026-11-27) is a panel that is up, whose socket is
2197
+ * up, and whose guest either never arrives or never reports ready — after
2198
+ * which every tool call silently goes to the invisible browser. One forced
2199
+ * remount costs nothing; sitting there forever costs the human's trust in
2200
+ * what is on their screen, which is the whole point of the panel.
2201
+ */
2202
+ useEffect(() => {
2203
+ if (NATIVE_VIEW !== true || open !== true) return undefined
2204
+ if (windowed === true) return undefined
2205
+ const startedAt = Date.now()
2206
+ const probe = setTimeout(() => {
2207
+ if (nativeReady === true) return
2208
+ if (Date.now() - startedAt < 10_000) return
2209
+ if (mountNonce >= 3) {
2210
+ // Three honest attempts is enough; after that the reason has to be
2211
+ // visible rather than retried into a loop.
2212
+ send({ type: 'probe', data: { stage: 'mount-watchdog-giveup', nonce: mountNonce } })
2213
+ setMountStage(dict.mountStuck)
2214
+ return
2215
+ }
2216
+ send({ type: 'probe', data: { stage: 'mount-watchdog', nonce: mountNonce } })
2217
+ setMountNonce((value) => value + 1)
2218
+ }, 12_000)
2219
+ return () => clearTimeout(probe)
2220
+ }, [open, nativeReady, mountNonce, send, dict.mountStuck, windowed])
2221
+
2222
+ /**
2223
+ * Follow the host, but only when the AI itself navigated.
2224
+ *
2225
+ * The host's URL is not a trustworthy instruction on its own: when the human
2226
+ * clicks a link in the guest, the host follows *them*, and its own tab can
2227
+ * then bounce (a site redirecting a headless tab back to its home page).
2228
+ * Pushing that bounce at the panel is what made one click "open two or three
2229
+ * videos" and then land back on the home page. `navSeq` is bumped only by an
2230
+ * AI-initiated navigation, so it is the one signal safe to obey.
2231
+ */
2232
+ useEffect(() => {
2233
+ if (NATIVE_VIEW !== true || nativeReady !== true) return
2234
+ const element = viewRef.current
2235
+ if (element === null || element === undefined) return
2236
+ const url = typeof status.url === 'string' ? status.url : ''
2237
+ if (url === '' || url.startsWith('about:')) return
2238
+ // First paint. The panel can mount before the host has a page (a refresh
2239
+ // with the browser not opened yet), and in that case `dom-ready` saw no URL
2240
+ // and the sequence never moves — without this the guest would sit on
2241
+ // about:blank forever, and the panel would look broken.
2242
+ if (viewUrlRef.current === '') {
2243
+ hostUrlRef.current = url
2244
+ try {
2245
+ element.loadURL(url).catch(() => {})
2246
+ } catch {
2247
+ /* the guest may be mid-teardown */
2248
+ }
2249
+ return
2250
+ }
2251
+ const seq = status.navSeq
2252
+ if (typeof seq !== 'number') return
2253
+ if (seq === appliedNavSeqRef.current) return
2254
+ appliedNavSeqRef.current = seq
2255
+ // The guest may already be exactly here (the AI navigated to the page the
2256
+ // human is on); loading it again would only cost a reload.
2257
+ if (viewUrlRef.current === url) return
2258
+ hostUrlRef.current = url
2259
+ try {
2260
+ element.loadURL(url).catch(() => {})
2261
+ } catch {
2262
+ /* the guest may be mid-teardown */
2263
+ }
2264
+ }, [status, nativeReady])
2265
+
2266
+ /**
2267
+ * The wheel must reach the page instead of scrolling the GUI behind the
2268
+ * picture. React registers `wheel` passively at its root, where
2269
+ * `preventDefault()` is a no-op, so this one listener is attached natively.
2270
+ *
2271
+ * It goes on the **stage**, not on the canvas. With the `mjpeg` transport
2272
+ * the pixels are an `<img>` and there is no canvas at all — `canvasRef` is
2273
+ * only assigned in the canvas branch — so a listener bound to the canvas
2274
+ * never ran, and the wheel silently did nothing. That was the "鼠标没法控制
2275
+ * 上下滑动" report: the page was scrollable the whole time. The stage is the
2276
+ * one element that exists in both transports and is never replaced.
2277
+ */
2278
+ useEffect(() => {
2279
+ if (open !== true) return undefined
2280
+ // A native guest handles its own wheel; forwarding it to the host as well
2281
+ // would scroll the page twice (and cancel the native one with preventDefault).
2282
+ if (NATIVE_VIEW) return undefined
2283
+ const stage = stageRef.current
2284
+ if (stage === null || typeof stage.addEventListener !== 'function') return undefined
2285
+ const onWheel = (event) => {
2286
+ event.preventDefault()
2287
+ const point = toPageCoords(event)
2288
+ send({ type: 'input', kind: 'wheel', x: point.x, y: point.y, deltaX: event.deltaX, deltaY: event.deltaY })
2289
+ }
2290
+ stage.addEventListener('wheel', onWheel, { passive: false })
2291
+ return () => stage.removeEventListener('wheel', onWheel)
2292
+ }, [open, send, sessionId])
2293
+
2294
+ // Focus the keyboard sink as soon as a picture exists, so typing works
2295
+ // without an extra click (a click also focuses it — see onPointerDown).
2296
+ // A native guest takes the keyboard itself, so stealing focus from it here
2297
+ // would make typing go nowhere.
2298
+ useEffect(() => {
2299
+ if (open !== true || NATIVE_VIEW) return undefined
2300
+ const timer = setTimeout(() => sinkRef.current?.focus?.(), 120)
2301
+ return () => clearTimeout(timer)
2302
+ }, [open])
2303
+
2304
+ /** A human arriving (or leaving) the page changes whether we want frames. */
2305
+ useEffect(() => {
2306
+ if (sessionId === '') return undefined
2307
+ const onVisibility = () => {
2308
+ const socket = socketRef.current
2309
+ if (socket === null || socket.readyState !== 1) return
2310
+ if (document.visibilityState === 'hidden') socket.send(JSON.stringify({ type: 'blur' }))
2311
+ else if (NATIVE_VIEW) {
2312
+ // Nothing to repaint: the guest is drawn by the host process.
2313
+ } else {
2314
+ socket.send(JSON.stringify({ type: 'focus' }))
2315
+ socket.send(JSON.stringify({ type: 'play' }))
2316
+ }
2317
+ }
2318
+ document.addEventListener('visibilitychange', onVisibility)
2319
+ return () => document.removeEventListener('visibilitychange', onVisibility)
2320
+ }, [sessionId])
2321
+
2322
+ /**
2323
+ * Answer a takeover request: over the socket when it is open, otherwise over
2324
+ * the HTTP endpoint, so a request can still be settled while the picture is
2325
+ * reconnecting.
2326
+ */
2327
+ const sendOrPost = (message, body) => {
2328
+ const socket = socketRef.current
2329
+ if (socket !== null && socket.readyState === 1) {
2330
+ socket.send(JSON.stringify(message))
2331
+ return
2332
+ }
2333
+ void requestJson(DONE_PATH, { method: 'POST', body }).catch(() => {})
2334
+ }
2335
+
2336
+ /** 「我已完成」: settle the pending request without a reply. */
2337
+ const finishHuman = () => {
2338
+ const requestId = human?.id
2339
+ if (requestId === undefined) return
2340
+ sendOrPost({ type: 'human-done', requestId }, { id: requestId })
2341
+ setHuman(undefined)
2342
+ }
2343
+
2344
+ /** Reply: settles the request with a note the waiting tool call receives. */
2345
+ const submitReply = () => {
2346
+ const requestId = human?.id
2347
+ const text = reply.trim()
2348
+ if (requestId === undefined || text === '') return
2349
+ sendOrPost({ type: 'human-reply', requestId, text }, { id: requestId, text })
2350
+ setReply('')
2351
+ setHuman(undefined)
2352
+ }
2353
+
2354
+ /** Empty state: open this session's tab, then let the socket take over. */
2355
+ const openBrowser = async () => {
2356
+ if (sessionId === '') return
2357
+ setBusy(true)
2358
+ try {
2359
+ const payload = await requestJson(OPEN_PATH, { method: 'POST', body: { sessionId } })
2360
+ applySnapshot(snapshotFromState(payload))
2361
+ setFailure(undefined)
2362
+ } catch (error) {
2363
+ setFailure(String(error?.message ?? error))
2364
+ } finally {
2365
+ setBusy(false)
2366
+ }
2367
+ }
2368
+
2369
+ /** Toolbar close: discards the page, so it always asks first. */
2370
+ const closeTab = async () => {
2371
+ if (sessionId === '') return
2372
+ if (typeof window.confirm === 'function' && !window.confirm(dict.closeTabConfirm)) return
2373
+ setBusy(true)
2374
+ try {
2375
+ await requestJson(CLOSE_PATH, { method: 'POST', body: { sessionId } })
2376
+ setHasFrame(false)
2377
+ setFailure(undefined)
2378
+ applySnapshot({ open: false, running: status.running !== false, url: null, title: null, human: null, stream: null })
2379
+ } catch (error) {
2380
+ setFailure(String(error?.message ?? error))
2381
+ } finally {
2382
+ setBusy(false)
2383
+ }
2384
+ }
2385
+
2386
+ /**
2387
+ * Toolbar navigation against the native guest.
2388
+ *
2389
+ * The guest has its own history stack, and it is the one the human sees, so
2390
+ * back/forward must move *it* — driving the host instead would move a page
2391
+ * nobody is looking at. When the guest cannot go that way, the host is asked,
2392
+ * which is also how a page that only exists in the host's tab is reached.
2393
+ */
2394
+ const viewNav = (action) => {
2395
+ const element = viewRef.current
2396
+ const fallback = () => send({ type: 'nav', action })
2397
+ if (element === null || element === undefined) {
2398
+ fallback()
2399
+ return
2400
+ }
2401
+ try {
2402
+ if (action === 'back') {
2403
+ if (element.canGoBack?.() === true) element.goBack()
2404
+ else fallback()
2405
+ } else if (action === 'forward') {
2406
+ if (element.canGoForward?.() === true) element.goForward()
2407
+ else fallback()
2408
+ } else {
2409
+ element.reload()
2410
+ }
2411
+ } catch {
2412
+ fallback()
2413
+ }
2414
+ }
2415
+
2416
+ /**
2417
+ * Open whatever is in the address bar.
2418
+ *
2419
+ * Without this the panel is a picture of a browser: the AI can go somewhere
2420
+ * and the human can watch, but the human cannot open a page of their own.
2421
+ */
2422
+ const goToAddress = () => {
2423
+ const raw = addressDraft.trim()
2424
+ if (raw === '') return
2425
+ // A bare `example.com` is an address, not a search term. Only honour a scheme
2426
+ // when there really is one, or `localhost:3000` would be read as `localhost:`.
2427
+ const hasScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(raw)
2428
+ // Something with a dot and a plausible TLD is treated as a host; anything else
2429
+ // ("bilibili", "今天天气") is a search, which is what a browser address bar does.
2430
+ const looksLikeHost = !/\s/.test(raw) && /^[^\s/]+\.[a-z]{2,}([/:?].*)?$/i.test(raw)
2431
+ const target = hasScheme
2432
+ ? raw
2433
+ : looksLikeHost
2434
+ ? `https://${raw}`
2435
+ : `https://cn.bing.com/search?q=${encodeURIComponent(raw)}`
2436
+ setAddressEditing(false)
2437
+ const element = viewRef.current
2438
+ if (element !== null && element !== undefined) {
2439
+ // The guest is the truth: load it there, and let `did-navigate` tell the
2440
+ // host to follow. Clearing `hostUrlRef` is what marks this as the human's
2441
+ // own navigation rather than an echo of a host command.
2442
+ hostUrlRef.current = ''
2443
+ try {
2444
+ element.loadURL(target).catch(() => {})
2445
+ } catch {
2446
+ /* the guest is gone */
2447
+ }
2448
+ return
2449
+ }
2450
+ // Nothing is open in this session yet; let the host create the tab.
2451
+ send({ type: 'open', url: target })
2452
+ }
2453
+
2454
+ /**
2455
+ * Poll an in-guest condition until it holds or the budget runs out.
2456
+ *
2457
+ * Polling beats an observer here: the condition may be a selector, a URL or a
2458
+ * script result, and one 120 ms tick covers all three without leaving anything
2459
+ * behind on a page the agent may navigate away from.
2460
+ */
2461
+ const guestWait = async (run, params) => {
2462
+ const op = String(params?.op ?? 'delay')
2463
+ const timeoutMs = Math.max(0, Number(params?.timeoutMs ?? 10_000))
2464
+ const started = Date.now()
2465
+ if (op === 'delay') {
2466
+ const delay = Math.max(0, Number(params?.ms ?? params?.timeoutMs ?? 0))
2467
+ await new Promise((resolve) => setTimeout(resolve, delay))
2468
+ return { op: 'delay', waited: true, waitedMs: delay }
2469
+ }
2470
+ if (op === 'selector') {
2471
+ const selector = String(params?.selector ?? '')
2472
+ if (selector === '') throw new Error('op=selector needs a selector')
2473
+ for (;;) {
2474
+ const seen = await run(`(() => {
2475
+ const node = document.querySelector(${JSON.stringify(selector)})
2476
+ if (node === null) return false
2477
+ const style = getComputedStyle(node)
2478
+ return Boolean(node.offsetWidth || node.offsetHeight || node.getClientRects().length) && style.visibility !== 'hidden'
2479
+ })()`)
2480
+ if (seen === true) return { op, selector, waited: true, state: 'visible' }
2481
+ if (Date.now() - started > timeoutMs) throw new Error(`wait for ${JSON.stringify(selector)} timed out after ${timeoutMs}ms`)
2482
+ await new Promise((resolve) => setTimeout(resolve, 120))
2483
+ }
2484
+ }
2485
+ if (op === 'url') {
2486
+ const pattern = String(params?.pattern ?? '')
2487
+ if (pattern === '') throw new Error('op=url needs a pattern')
2488
+ const regex = pattern.startsWith('/') && pattern.endsWith('/') ? new RegExp(pattern.slice(1, -1)) : undefined
2489
+ for (;;) {
2490
+ const current = String(await run('location.href'))
2491
+ const hit = regex !== undefined ? regex.test(current) : current.includes(pattern)
2492
+ if (hit) return { op, pattern, waited: true, url: current }
2493
+ if (Date.now() - started > timeoutMs) throw new Error(`wait for url ${pattern} timed out after ${timeoutMs}ms`)
2494
+ await new Promise((resolve) => setTimeout(resolve, 120))
2495
+ }
2496
+ }
2497
+ if (op === 'function') {
2498
+ const expression = String(params?.expression ?? '')
2499
+ if (expression === '') throw new Error('op=function needs an expression')
2500
+ for (;;) {
2501
+ const hit = await run(`(() => { try { return Boolean(${expression}) } catch { return false } })()`)
2502
+ if (hit === true) return { op, expression, waited: true }
2503
+ if (Date.now() - started > timeoutMs) throw new Error(`wait for expression ${expression} timed out after ${timeoutMs}ms`)
2504
+ await new Promise((resolve) => setTimeout(resolve, 120))
2505
+ }
2506
+ }
2507
+ if (op === 'load') {
2508
+ for (;;) {
2509
+ const state = String(await run('document.readyState'))
2510
+ if (state === 'complete') return { op, waited: true, readyState: state }
2511
+ if (Date.now() - started > timeoutMs) throw new Error(`wait for load timed out after ${timeoutMs}ms (readyState=${state})`)
2512
+ await new Promise((resolve) => setTimeout(resolve, 120))
2513
+ }
2514
+ }
2515
+ throw new Error(`unsupported wait op ${JSON.stringify(op)}; use delay, selector, url, function or load`)
2516
+ }
2517
+
2518
+ /**
2519
+ * Run one operation inside the guest on behalf of the agent.
2520
+ *
2521
+ * The panel owns the page, so every question about that page has to be answered
2522
+ * here. DOM reads go through `executeJavaScript`; anything that must look like a
2523
+ * real user action goes through `sendInputEvent`, because a synthetic event
2524
+ * carries `isTrusted === false` and plenty of pages ignore those.
2525
+ */
2526
+ /**
2527
+ * Move this page between surfaces on the agent's request.
2528
+ *
2529
+ * The element is untouched — the Sidebar re-homes the *tab*, which keeps its
2530
+ * id and its body, so the live `<webview>` (scroll position, typed text, the
2531
+ * page the agent is working on) survives the move. `window` is not a Sidebar
2532
+ * operation at all: it belongs to a deployment whose browser is a real window.
2533
+ */
2534
+ const presentSurface = (mode) => {
2535
+ const side = props.sidebarRef?.current
2536
+ const wanted = String(mode ?? '')
2537
+ if (wanted === 'float') {
2538
+ if (typeof side?.float !== 'function' || floatTabId === undefined) {
2539
+ throw new Error('present: this Sidebar build cannot float the tab')
2540
+ }
2541
+ const already = floated === true || ourFloatRef.current === true
2542
+ let returned
2543
+ if (floated !== true) returned = side.float(floatTabId)
2544
+ // A dock needs the *floating* pane's id, and `panel.id` in props is the
2545
+ // pane the tab came from — docking that is a silent no-op (measured: the
2546
+ // panel stayed 380x165 while the host was told "sidebar"). If the
2547
+ // Sidebar hands back the new pane, keep it; the probe records the shape
2548
+ // so the guess can be replaced by a fact.
2549
+ const paneId = returned?.paneId ?? returned?.pane?.id ?? returned?.id
2550
+ if (typeof paneId === 'string' && paneId !== '') ourFloatPaneRef.current = paneId
2551
+ send({
2552
+ type: 'probe',
2553
+ data: {
2554
+ stage: 'float-return',
2555
+ kind: typeof returned,
2556
+ paneId: typeof paneId === 'string' ? paneId : '-',
2557
+ keys: returned !== null && typeof returned === 'object' ? Object.keys(returned).join(',') : '-',
2558
+ },
2559
+ })
2560
+ ourFloatRef.current = true
2561
+ send({ type: 'surface', floating: true })
2562
+ return { layer: 'float', moved: already !== true }
2563
+ }
2564
+ if (wanted === 'sidebar') {
2565
+ if (typeof side?.dock !== 'function' || floatPaneId === undefined) {
2566
+ throw new Error('present: this Sidebar build cannot dock the floating panel')
2567
+ }
2568
+ const wasFloating = floated === true || ourFloatRef.current === true
2569
+ const pane = ourFloatPaneRef.current ?? floatPaneId
2570
+ if (wasFloating) side.dock(pane)
2571
+ ourFloatRef.current = false
2572
+ ourFloatPaneRef.current = undefined
2573
+ send({ type: 'surface', floating: false })
2574
+ return { layer: 'sidebar', moved: wasFloating, pane: pane === floatPaneId ? 'props' : 'returned' }
2575
+ }
2576
+ if (wanted === 'window') {
2577
+ throw new Error('present: window is not a panel operation — this deployment\'s browser is not headed, so it has no window to show; set mode: "headed" to give it one')
2578
+ }
2579
+ throw new Error(`present: unknown mode ${JSON.stringify(mode)} (sidebar | float | window)`)
2580
+ }
2581
+
2582
+ const runGuestCall = async (method, params) => {
2583
+ const element = viewRef.current
2584
+ if (element === null || element === undefined) {
2585
+ throw new Error('guest-unavailable: the native panel is not mounted')
2586
+ }
2587
+ const run = async (expression, userGesture = false) => await element.executeJavaScript(expression, userGesture)
2588
+ /** A JS expression resolving to the target node, from index or selector. */
2589
+ /**
2590
+ * A JS expression resolving to the target node, from index or selector.
2591
+ *
2592
+ * An index whose marker is gone is retried through the loc the snapshot
2593
+ * recorded for it — a framework re-render replaces the node (dropping the
2594
+ * attribute) without moving the element. Tag and label must agree before
2595
+ * the retry is accepted: clicking a neighbour is worse than asking for a
2596
+ * fresh snapshot.
2597
+ */
2598
+ const pick = (args) => {
2599
+ if (typeof args?.index === 'number') {
2600
+ const index = Number(args.index)
2601
+ return `(() => {
2602
+ let node = document.querySelector('[data-deb-index="${index}"]')
2603
+ if (node !== null) return node
2604
+ const refs = globalThis.__debRefs
2605
+ const ref = Array.isArray(refs) ? refs[${index}] : undefined
2606
+ if (ref === undefined || typeof ref.loc !== 'string') return null
2607
+ let selector
2608
+ if (ref.loc.indexOf('css:') === 0) selector = ref.loc.slice(4)
2609
+ else if (ref.loc.indexOf('href:') === 0) {
2610
+ selector = 'a[href="' + String(ref.loc.slice(5)).replace(/\\\\/g, '\\\\\\\\').replace(/"/g, '\\\\"') + '"]'
2611
+ } else return null
2612
+ try { node = document.querySelector(selector) } catch { return null }
2613
+ if (node === null || node.tagName.toLowerCase() !== ref.tag) return null
2614
+ const label = String(node.getAttribute('aria-label') || node.getAttribute('placeholder') || node.innerText || node.value || '').replace(/\\s+/g, ' ').trim()
2615
+ if (ref.label && label && label.indexOf(ref.label.slice(0, 24)) !== 0) return null
2616
+ node.setAttribute('data-deb-index', '${index}')
2617
+ return node
2618
+ })()`
2619
+ }
2620
+ const selector = typeof args?.selector === 'string' ? args.selector.trim() : ''
2621
+ if (selector === '') throw new Error('name the element with index (from a snapshot) or selector')
2622
+ return `document.querySelector(${JSON.stringify(selector)})`
2623
+ }
2624
+ /** Resolve the node, scroll it into view, and report where it really is. */
2625
+ const pointOf = async (args) => {
2626
+ const point = await run(`(() => {
2627
+ // A collapsed panel is 0x0: coordinates then mean nothing, but the DOM
2628
+ // still answers every question, so a click "succeeds" and does nothing.
2629
+ // Measured 2026-11-28: three clicks reported verified=true against a
2630
+ // 0x0 panel and not one event arrived at the page.
2631
+ if (innerWidth <= 0 || innerHeight <= 0) return { collapsed: true }
2632
+ const node = ${pick(args)}
2633
+ if (node === null) return null
2634
+ node.scrollIntoView({ block: 'center', inline: 'center' })
2635
+ const rect = node.getBoundingClientRect()
2636
+ const style = getComputedStyle(node)
2637
+ if (style.display === 'none' || style.visibility === 'hidden') return { hidden: true }
2638
+ if (rect.width === 0 && rect.height === 0) return { hidden: true }
2639
+ return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2, w: rect.width, h: rect.height }
2640
+ })()`)
2641
+ if (point === null) {
2642
+ throw new Error(
2643
+ `no element matches ${args?.selector ?? `#${args?.index}`} — the page changed after the snapshot that numbered it (a navigation, a re-render, or a newer snapshot renumbered them); call browser_embedded_snapshot again`,
2644
+ )
2645
+ }
2646
+ if (point.collapsed === true) throw new Error(dict.panelCollapsed)
2647
+ if (point.hidden === true) throw new Error('element is hidden (display:none or zero size)')
2648
+ return point
2649
+ }
2650
+ /**
2651
+ * A hand-supplied viewport point, if the call named one.
2652
+ *
2653
+ * Coordinates are the only way into a cross-origin frame: this document
2654
+ * cannot query inside it, but the panel injects real input at a point and
2655
+ * the browser routes that input to whichever renderer owns the point.
2656
+ */
2657
+ const explicitPoint = async (args) => {
2658
+ const x = Number(args?.x)
2659
+ const y = Number(args?.y)
2660
+ if (!Number.isFinite(x) || !Number.isFinite(y)) return undefined
2661
+ const size = await run('({ w: innerWidth, h: innerHeight })')
2662
+ if (size.w <= 0 || size.h <= 0) throw new Error(dict.panelCollapsed)
2663
+ const px = Math.round(x)
2664
+ const py = Math.round(y)
2665
+ if (px < 0 || py < 0 || px >= size.w || py >= size.h) {
2666
+ throw new Error(`(${px},${py}) is outside the ${size.w}x${size.h} viewport — x and y are viewport CSS pixels, not screenshot pixels`)
2667
+ }
2668
+ return { x: px, y: py, explicit: true }
2669
+ }
2670
+ const pointFor = async (args) => (await explicitPoint(args)) ?? (await pointOf(args))
2671
+ /** What sits under a point, measured before anything is dispatched. */
2672
+ const hitAt = async (point) => {
2673
+ const hit = await run(`(() => {
2674
+ const node = document.elementFromPoint(${point.x}, ${point.y})
2675
+ if (node === null) return null
2676
+ const tag = node.tagName.toLowerCase()
2677
+ const frame = tag === 'iframe' || tag === 'frame'
2678
+ let frameReadable
2679
+ if (frame) {
2680
+ // 面板里跨域 frame 是独立进程:这里的输入进不去(实测同源能中、
2681
+ // 跨域一下都不中)。把「读不到」报上去,免得调用方以为点空了。
2682
+ try {
2683
+ const doc = node.contentDocument
2684
+ frameReadable = Boolean(doc && doc.body && !/^about:/.test(String((doc.location && doc.location.href) || '')))
2685
+ } catch { frameReadable = false }
2686
+ }
2687
+ return {
2688
+ hit: tag,
2689
+ label: String(node.getAttribute('aria-label') || node.innerText || '').replace(/\\s+/g, ' ').trim().slice(0, 60),
2690
+ inFrame: frame ? true : undefined,
2691
+ frameReadable,
2692
+ }
2693
+ })()`)
2694
+ return hit ?? undefined
2695
+ }
2696
+ const withHit = (spot) =>
2697
+ spot === undefined
2698
+ ? {}
2699
+ : {
2700
+ hit: spot.hit,
2701
+ ...(spot.label === '' ? {} : { label: spot.label }),
2702
+ ...(spot.inFrame === true ? { inFrame: true } : {}),
2703
+ ...(spot.inFrame === true && spot.frameReadable === false ? { frameReadable: false } : {}),
2704
+ }
2705
+ /**
2706
+ * Page coordinates → input coordinates.
2707
+ *
2708
+ * `getBoundingClientRect` answers in CSS pixels, but `sendInputEvent` speaks
2709
+ * device-independent pixels *before* page zoom. With the fit-to-width zoom
2710
+ * active (a desktop-width site scaled into a narrow panel) the two differ by
2711
+ * the zoom factor — and ignoring it clicked a different element than the one
2712
+ * that was measured.
2713
+ */
2714
+ const zoomFactor = () => {
2715
+ try {
2716
+ const zoom = typeof element.getZoomFactor === 'function' ? element.getZoomFactor() : 1
2717
+ return typeof zoom === 'number' && Number.isFinite(zoom) && zoom > 0 ? zoom : 1
2718
+ } catch {
2719
+ return 1
2720
+ }
2721
+ }
2722
+ const toInput = (point) => {
2723
+ const zoom = zoomFactor()
2724
+ return { x: point.x * zoom, y: point.y * zoom }
2725
+ }
2726
+
2727
+ switch (method) {
2728
+ case 'present':
2729
+ return presentSurface(params?.mode)
2730
+ case 'info':
2731
+ return await run('({ url: location.href, title: document.title, w: innerWidth, h: innerHeight })')
2732
+ case 'eval':
2733
+ return await run(String(params?.expression ?? ''), params?.userGesture === true)
2734
+ case 'navigate': {
2735
+ const url = String(params?.url ?? '')
2736
+ if (url === '') throw new Error('navigate needs a url')
2737
+ hostUrlRef.current = ''
2738
+ await element.loadURL(url)
2739
+ await new Promise((resolve) => setTimeout(resolve, params?.settleMs ?? 250))
2740
+ return await run('({ url: location.href, title: document.title })')
2741
+ }
2742
+ case 'back':
2743
+ if (element.canGoBack?.() === true) element.goBack()
2744
+ return { url: element.getURL?.() ?? '' }
2745
+ case 'forward':
2746
+ if (element.canGoForward?.() === true) element.goForward()
2747
+ return { url: element.getURL?.() ?? '' }
2748
+ case 'reload':
2749
+ element.reload()
2750
+ return { url: element.getURL?.() ?? '' }
2751
+ case 'snapshot': {
2752
+ // The host decides the policy and passes it down; these defaults only
2753
+ // exist so an older host cannot make the panel throw.
2754
+ const asked = Number(params?.maxElements)
2755
+ const offset = Math.max(0, Math.floor(Number(params?.offset ?? 0)) || 0)
2756
+ const floor = Math.max(1, Math.floor(Number(params?.floor ?? 80)) || 80)
2757
+ const cap = Math.max(floor, Math.floor(Number(params?.cap ?? 240)) || 240)
2758
+ const budget = Math.max(500, Math.floor(Number(params?.budget ?? 12000)) || 12000)
2759
+ return await run(
2760
+ GUEST_SNAPSHOT_JS
2761
+ .replace('__LIMIT__', String(Number.isFinite(asked) && asked > 0 ? Math.floor(asked) : 0))
2762
+ .replace('__OFFSET__', String(offset))
2763
+ .replace('__FLOOR__', String(floor))
2764
+ .replace('__CAP__', String(cap))
2765
+ .replace('__BUDGET__', String(budget))
2766
+ .replace('__TEXT__', String(Math.max(0, Number(params?.maxChars ?? 4000)))),
2767
+ )
2768
+ }
2769
+ case 'pageInfo':
2770
+ return await run(GUEST_PAGE_INFO_JS)
2771
+ case 'click': {
2772
+ const target = await pointFor(params)
2773
+ const spot = await hitAt(target).catch(() => undefined)
2774
+ const point = toInput(target)
2775
+ const base = { x: Math.round(point.x), y: Math.round(point.y), button: 'left', clickCount: params?.double === true ? 2 : 1 }
2776
+ element.sendInputEvent({ type: 'mouseDown', ...base })
2777
+ element.sendInputEvent({ type: 'mouseUp', ...base })
2778
+ return { x: base.x, y: base.y, verified: true, ...withHit(spot) }
2779
+ }
2780
+ case 'hover': {
2781
+ const target = await pointFor(params)
2782
+ const spot = await hitAt(target).catch(() => undefined)
2783
+ const point = toInput(target)
2784
+ element.sendInputEvent({ type: 'mouseMove', x: Math.round(point.x), y: Math.round(point.y) })
2785
+ return { hovered: true, ...withHit(spot) }
2786
+ }
2787
+ case 'type': {
2788
+ const text = String(params?.text ?? '')
2789
+ const target = await pointFor(params)
2790
+ const spot = await hitAt(target).catch(() => undefined)
2791
+ const point = toInput(target)
2792
+ const at = { x: Math.round(point.x), y: Math.round(point.y), button: 'left', clickCount: 1 }
2793
+ element.sendInputEvent({ type: 'mouseDown', ...at })
2794
+ element.sendInputEvent({ type: 'mouseUp', ...at })
2795
+ for (const character of text) element.sendInputEvent({ type: 'char', keyCode: character })
2796
+ if (params?.submit === true) {
2797
+ element.sendInputEvent({ type: 'keyDown', keyCode: 'Return' })
2798
+ element.sendInputEvent({ type: 'keyUp', keyCode: 'Return' })
2799
+ }
2800
+ return { x: at.x, y: at.y, submitted: params?.submit === true, ...withHit(spot) }
2801
+ }
2802
+ case 'fill': {
2803
+ // The native value setter, so React/Vue observe the change and non-Latin
2804
+ // text works (`sendInputEvent` carries one key per event).
2805
+ const text = String(params?.text ?? '')
2806
+ const filled = await run(`(() => {
2807
+ const node = ${pick(params)}
2808
+ if (node === null) return { ok: false, reason: 'no such element' }
2809
+ if (node.isContentEditable === true) {
2810
+ node.focus()
2811
+ node.textContent = ${JSON.stringify(text)}
2812
+ node.dispatchEvent(new Event('input', { bubbles: true }))
2813
+ return { ok: true, value: node.textContent, mode: 'contenteditable' }
2814
+ }
2815
+ if (!('value' in node)) return { ok: false, reason: 'element has no value property: ' + node.tagName.toLowerCase() }
2816
+ const proto = node instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype
2817
+ const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set
2818
+ node.focus()
2819
+ if (setter) setter.call(node, ${JSON.stringify(text)})
2820
+ else node.value = ${JSON.stringify(text)}
2821
+ node.dispatchEvent(new Event('input', { bubbles: true }))
2822
+ node.dispatchEvent(new Event('change', { bubbles: true }))
2823
+ return { ok: true, value: node.value }
2824
+ })()`)
2825
+ if (filled?.ok !== true) throw new Error(`fill failed: ${filled?.reason ?? 'unknown reason'}`)
2826
+ return { value: filled.value }
2827
+ }
2828
+ case 'press': {
2829
+ const raw = String(params?.key ?? '').trim()
2830
+ if (raw === '') throw new Error('press needs a key')
2831
+ const alias = GUEST_KEYS[raw.toLowerCase()]
2832
+ const key = alias !== undefined ? alias : /^[a-z0-9]$/i.test(raw) ? raw.toUpperCase() : raw
2833
+ element.sendInputEvent({ type: 'keyDown', keyCode: key })
2834
+ element.sendInputEvent({ type: 'keyUp', keyCode: key })
2835
+ return { pressed: key }
2836
+ }
2837
+ case 'scroll': {
2838
+ const direction = String(params?.direction ?? 'down').toLowerCase()
2839
+ const rect = element.getBoundingClientRect()
2840
+ const pixels = Number(params?.pixels ?? 0)
2841
+ const delta = pixels > 0 ? pixels : Math.round(0.8 * (rect.height || 800))
2842
+ if (direction === 'top' || direction === 'bottom') {
2843
+ // `top` used to fall through to the signed branch and scroll *down* one
2844
+ // page — the opposite of what was asked, with a success shape returned.
2845
+ return await run(`(() => {
2846
+ const before = window.scrollY
2847
+ const max = Math.max(0, document.documentElement.scrollHeight - window.innerHeight)
2848
+ window.scrollTo(window.scrollX, ${direction === 'top' ? 0 : 'max'})
2849
+ return { before, after: window.scrollY, max: Math.round(max) }
2850
+ })()`)
2851
+ }
2852
+ const horizontal = direction === 'left' || direction === 'right'
2853
+ const sign = direction === 'up' || direction === 'left' ? -1 : 1
2854
+ return await run(`(() => {
2855
+ const before = ${horizontal ? 'window.scrollX' : 'window.scrollY'}
2856
+ window.scrollBy(${horizontal ? `${sign} * ${delta}` : 0}, ${horizontal ? 0 : `${sign} * ${delta}`})
2857
+ return { before, after: ${horizontal ? 'window.scrollX' : 'window.scrollY'} }
2858
+ })()`)
2859
+ }
2860
+ case 'clickText': {
2861
+ // Click-by-label has to happen in the guest too, or the tool clicks a
2862
+ // string in an invisible browser while the human watches a different page.
2863
+ // The resolver is the same script the headless tab runs, so the two
2864
+ // worlds cannot disagree about what "the element that says X" means.
2865
+ const want = String(params?.text ?? '').trim()
2866
+ if (want === '') throw new Error('clickText needs some text to look for')
2867
+ // Function replacements: the needle is caller text, and `$&`/`$1` in it
2868
+ // would otherwise be read as a substitution pattern.
2869
+ const raw = await run(
2870
+ CLICK_TEXT_PROBE.replace('__INTERACTIVE__', () => JSON.stringify(GUEST_INTERACTIVE))
2871
+ .replace('__WANT__', () => JSON.stringify(want))
2872
+ .replace('__NEEDLE__', () => JSON.stringify(want.toLowerCase())),
2873
+ )
2874
+ const found = typeof raw === 'string' ? JSON.parse(raw) : raw
2875
+ if (found?.ok !== true) throw new Error(found?.reason ?? `no clickable element matching ${JSON.stringify(want)}`)
2876
+ // Measured before the click: afterwards the page may have navigated
2877
+ // away from under the pointer.
2878
+ const spot = await hitAt({ x: found.x, y: found.y }).catch(() => undefined)
2879
+ const point = toInput({ x: found.x, y: found.y })
2880
+ const base = { x: Math.round(point.x), y: Math.round(point.y), button: 'left', clickCount: params?.double === true ? 2 : 1 }
2881
+ element.sendInputEvent({ type: 'mouseDown', ...base })
2882
+ element.sendInputEvent({ type: 'mouseUp', ...base })
2883
+ return {
2884
+ found: true,
2885
+ label: found.label,
2886
+ tag: found.tag,
2887
+ match: found.match,
2888
+ x: base.x,
2889
+ y: base.y,
2890
+ matches: found.matches,
2891
+ ...(found.ambiguous === true ? { ambiguous: true, candidates: found.candidates } : {}),
2892
+ verified: true,
2893
+ ...(spot === undefined ? {} : { hit: spot.hit }),
2894
+ }
2895
+ }
2896
+ case 'drag': {
2897
+ // Both endpoints are measured in one pass: `scrollIntoView` on the drop
2898
+ // target would move the source out from under a coordinate taken before it.
2899
+ const probe = await run(`(() => {
2900
+ const a = ${pick(params?.from)}
2901
+ const b = ${pick(params?.to)}
2902
+ if (a === null || b === null) return null
2903
+ a.scrollIntoView({ block: 'center', inline: 'center' })
2904
+ const ra = a.getBoundingClientRect()
2905
+ const rb = b.getBoundingClientRect()
2906
+ const label = (node) => String(node.getAttribute('aria-label') || node.innerText || node.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 40)
2907
+ return {
2908
+ ax: ra.left + ra.width / 2, ay: ra.top + ra.height / 2,
2909
+ bx: rb.left + rb.width / 2, by: rb.top + rb.height / 2,
2910
+ fromLabel: label(a), toLabel: label(b),
2911
+ fromTag: a.tagName.toLowerCase(), toTag: b.tagName.toLowerCase(),
2912
+ draggable: a.draggable === true || a.getAttribute('draggable') === 'true',
2913
+ payload: a.getAttribute('href') || (a.innerText || '').trim().slice(0, 200),
2914
+ }
2915
+ })()`)
2916
+ if (probe === null) throw new Error('drag could not resolve both endpoints')
2917
+ const fromTarget = { found: true, x: Math.round(probe.ax), y: Math.round(probe.ay), tag: probe.fromTag, label: probe.fromLabel }
2918
+ const toTarget = { found: true, x: Math.round(probe.bx), y: Math.round(probe.by), tag: probe.toTag, label: probe.toLabel }
2919
+ if (probe.draggable === true) {
2920
+ // A `<webview>` cannot start an OS drag: Chromium hands `dragstart` to the
2921
+ // browser process, the drag loop never begins, and mousedown plus moves
2922
+ // therefore produce no `drop` at all (measured on the fixture page). So the
2923
+ // event sequence is synthesized: the page's own handlers run, `isTrusted` is
2924
+ // false, and that is the price of dragging from inside the panel.
2925
+ const outcome = await run(`(() => {
2926
+ const a = ${pick(params?.from)}
2927
+ const b = ${pick(params?.to)}
2928
+ if (a === null || b === null) return { ok: false, reason: 'an endpoint disappeared' }
2929
+ const transfer = new DataTransfer()
2930
+ transfer.setData('text/plain', ${JSON.stringify(String(probe.payload ?? ''))})
2931
+ const href = a.getAttribute('href')
2932
+ if (href !== null) transfer.setData('text/uri-list', href)
2933
+ transfer.effectAllowed = 'all'
2934
+ const fire = (node, type) => node.dispatchEvent(new DragEvent(type, { bubbles: true, cancelable: true, dataTransfer: transfer }))
2935
+ fire(a, 'dragstart')
2936
+ fire(b, 'dragenter')
2937
+ fire(b, 'dragover')
2938
+ // A drop handler that accepts the drag calls preventDefault, which makes
2939
+ // dispatchEvent return false. That is the only honest "it landed" signal.
2940
+ const notPrevented = fire(b, 'drop')
2941
+ fire(a, 'dragend')
2942
+ return { ok: true, accepted: notPrevented === false, targetClass: String(b.getAttribute('class') || '') }
2943
+ })()`)
2944
+ if (outcome?.ok !== true) throw new Error(`drag failed: ${outcome?.reason ?? 'unknown reason'}`)
2945
+ return { from: fromTarget, to: toTarget, mode: 'drag-events', accepted: outcome.accepted === true, targetClass: outcome.targetClass }
2946
+ }
2947
+ const a = toInput({ x: probe.ax, y: probe.ay })
2948
+ const b = toInput({ x: probe.bx, y: probe.by })
2949
+ const start = { x: Math.round(a.x), y: Math.round(a.y) }
2950
+ const end = { x: Math.round(b.x), y: Math.round(b.y) }
2951
+ // Hover first, then press: Chromium settles the pointer on the source before
2952
+ // the button goes down, which is what makes a pointer drag read as one.
2953
+ element.sendInputEvent({ type: 'mouseMove', x: start.x, y: start.y })
2954
+ element.sendInputEvent({ type: 'mouseDown', x: start.x, y: start.y, button: 'left', clickCount: 1 })
2955
+ const steps = 12
2956
+ let lastX = start.x
2957
+ let lastY = start.y
2958
+ for (let step = 1; step <= steps; step += 1) {
2959
+ const x = Math.round(start.x + ((end.x - start.x) * step) / steps)
2960
+ const y = Math.round(start.y + ((end.y - start.y) * step) / steps)
2961
+ element.sendInputEvent({ type: 'mouseMove', x, y, button: 'left', movementX: x - lastX, movementY: y - lastY })
2962
+ lastX = x
2963
+ lastY = y
2964
+ }
2965
+ element.sendInputEvent({ type: 'mouseUp', x: end.x, y: end.y, button: 'left', clickCount: 1 })
2966
+ return { from: fromTarget, to: toTarget, mode: 'pointer', steps }
2967
+ }
2968
+ case 'upload': {
2969
+ // A file input cannot be filled from the page (no filesystem), so the node
2970
+ // half reads the bytes and hands them over; the page rebuilds real `File`
2971
+ // objects and puts them on the input the way a picker would.
2972
+ const files = Array.isArray(params?.files) ? params.files : []
2973
+ if (files.length === 0) throw new Error('upload needs at least one file')
2974
+ const result = await run(`(() => {
2975
+ const node = ${pick(params?.target ?? params)}
2976
+ if (node === null) return { ok: false, reason: 'no such element' }
2977
+ if (node.tagName !== 'INPUT' || node.type !== 'file') {
2978
+ return { ok: false, reason: 'target is not an <input type=file>: ' + node.tagName.toLowerCase() }
2979
+ }
2980
+ const transfer = new DataTransfer()
2981
+ for (const file of ${JSON.stringify(files)}) {
2982
+ const binary = atob(file.base64)
2983
+ const bytes = new Uint8Array(binary.length)
2984
+ for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index)
2985
+ transfer.items.add(new File([bytes], file.name, { type: file.type || 'application/octet-stream' }))
2986
+ }
2987
+ node.files = transfer.files
2988
+ node.dispatchEvent(new Event('input', { bubbles: true }))
2989
+ node.dispatchEvent(new Event('change', { bubbles: true }))
2990
+ return { ok: true, names: [...node.files].map((file) => file.name + ' (' + file.size + 'B)') }
2991
+ })()`)
2992
+ if (result?.ok !== true) throw new Error(`upload failed: ${result?.reason ?? 'unknown reason'}`)
2993
+ return { files: result.names }
2994
+ }
2995
+ case 'download': {
2996
+ // The host cancels `will-download` on this partition, so a real download is
2997
+ // impossible; fetching in the page is not a workaround, it is the only side
2998
+ // that can carry the site's cookies. The bytes go back over the guest
2999
+ // channel and the node half writes them.
3000
+ const url = String(params?.url ?? '')
3001
+ if (url === '') throw new Error('download needs a url')
3002
+ const cap = Math.max(1024, Number(params?.maxBytes) || 32 * 1024 * 1024)
3003
+ const fetched = await run(`(async () => {
3004
+ try {
3005
+ const response = await fetch(${JSON.stringify(url)}, { credentials: 'include' })
3006
+ if (response.ok !== true) return { ok: false, reason: 'HTTP ' + response.status }
3007
+ const blob = await response.blob()
3008
+ if (blob.size > ${cap}) return { ok: false, reason: 'bigger than the ' + ${cap} + '-byte ceiling: ' + blob.size }
3009
+ const bytes = new Uint8Array(await blob.arrayBuffer())
3010
+ let binary = ''
3011
+ for (let index = 0; index < bytes.length; index += 32768) {
3012
+ binary += String.fromCharCode.apply(null, bytes.subarray(index, index + 32768))
3013
+ }
3014
+ const disposition = response.headers.get('content-disposition') || ''
3015
+ const match = /filename\\*?=(?:UTF-8'')?"?([^";]+)"?/i.exec(disposition)
3016
+ return {
3017
+ ok: true,
3018
+ base64: btoa(binary),
3019
+ size: bytes.length,
3020
+ type: blob.type || '',
3021
+ name: match === null ? '' : decodeURIComponent(match[1]),
3022
+ }
3023
+ } catch (error) {
3024
+ return { ok: false, reason: String((error && error.message) || error) }
3025
+ }
3026
+ })()`, true)
3027
+ if (fetched?.ok !== true) throw new Error(`download failed: ${fetched?.reason ?? 'unknown reason'}`)
3028
+ return fetched
3029
+ }
3030
+ case 'http': {
3031
+ const url = String(params?.url ?? '')
3032
+ if (/^https?:\/\//i.test(url) !== true) throw new Error('url must start with http:// or https://')
3033
+ const cap = Math.max(1000, Number(params?.maxBytes) || 200_000)
3034
+ const method = String(params?.method ?? 'GET')
3035
+ const body = params?.body
3036
+ const raw = await run(`(async () => {
3037
+ try {
3038
+ const response = await fetch(${JSON.stringify(url)}, {
3039
+ method: ${JSON.stringify(method)},
3040
+ headers: ${JSON.stringify(params?.headers ?? {})},
3041
+ ${body === undefined ? '' : `body: ${JSON.stringify(typeof body === 'string' ? body : JSON.stringify(body))},`}
3042
+ credentials: 'include',
3043
+ })
3044
+ const text = await response.text()
3045
+ return JSON.stringify({
3046
+ ok: true,
3047
+ status: response.status,
3048
+ statusText: response.statusText,
3049
+ url: response.url,
3050
+ contentType: response.headers.get('content-type'),
3051
+ truncated: text.length > ${cap},
3052
+ body: text.slice(0, ${cap}),
3053
+ })
3054
+ } catch (error) {
3055
+ return JSON.stringify({ ok: false, reason: String((error && error.message) || error) })
3056
+ }
3057
+ })()`, true)
3058
+ const parsed = JSON.parse(raw)
3059
+ if (parsed.ok !== true) throw new Error(`fetch failed: ${parsed.reason}`)
3060
+ return parsed
3061
+ }
3062
+ case 'read': {
3063
+ const selector = String(params?.selector ?? '')
3064
+ if (selector === '') throw new Error('read needs a selector')
3065
+ const what = String(params?.what ?? 'text')
3066
+ const attribute = params?.attribute === undefined ? '' : String(params.attribute)
3067
+ const value = await run(`(() => {
3068
+ const all = document.querySelectorAll(${JSON.stringify(selector)})
3069
+ const node = all[0]
3070
+ if (node === undefined) return { ok: false }
3071
+ const style = getComputedStyle(node)
3072
+ const name = ${JSON.stringify(what)}
3073
+ const pickValue = (kind) => {
3074
+ if (kind === 'html') return String(node.innerHTML || '').slice(0, 20000)
3075
+ if (kind === 'value') return node.value !== undefined ? String(node.value) : ''
3076
+ if (kind === 'attribute') return node.getAttribute(${JSON.stringify(attribute)}) ?? null
3077
+ if (kind === 'visible') return Boolean(node.offsetWidth || node.offsetHeight || node.getClientRects().length) && style.visibility !== 'hidden'
3078
+ if (kind === 'enabled') return node.disabled !== true
3079
+ if (kind === 'count') return all.length
3080
+ return String(node.innerText ?? node.textContent ?? '').replace(/\\s+/g, ' ').trim().slice(0, 20000)
3081
+ }
3082
+ return { ok: true, what: name, count: all.length, tag: node.tagName.toLowerCase(), result: pickValue(name) }
3083
+ })()`)
3084
+ if (value?.ok !== true) throw new Error(`no element matches ${JSON.stringify(selector)}`)
3085
+ return value
3086
+ }
3087
+ case 'select': {
3088
+ const value = String(params?.value ?? '')
3089
+ const chosen = await run(`(() => {
3090
+ const node = ${pick(params)}
3091
+ if (node === null) return { missing: true }
3092
+ const want = ${JSON.stringify(value)}
3093
+ for (const option of node.options ?? []) {
3094
+ if (option.value === want || option.text === want) {
3095
+ node.value = option.value
3096
+ node.dispatchEvent(new Event('input', { bubbles: true }))
3097
+ node.dispatchEvent(new Event('change', { bubbles: true }))
3098
+ return { value: node.value }
3099
+ }
3100
+ }
3101
+ return { missing: false, value: null, options: [...(node.options ?? [])].map((o) => o.text) }
3102
+ })()`)
3103
+ if (chosen?.missing === true) throw new Error('select target not found')
3104
+ if (chosen?.value === null && Array.isArray(chosen?.options)) {
3105
+ throw new Error(`no option matches ${JSON.stringify(value)}; options: ${chosen.options.join(' | ')}`)
3106
+ }
3107
+ return chosen
3108
+ }
3109
+ case 'check': {
3110
+ const wanted = params?.checked !== false
3111
+ const state = await run(`(() => {
3112
+ const node = ${pick(params)}
3113
+ if (node === null) return { missing: true }
3114
+ if (node.checked !== ${wanted}) node.click()
3115
+ return { checked: node.checked === true }
3116
+ })()`)
3117
+ if (state?.missing === true) throw new Error('check target not found')
3118
+ return state
3119
+ }
3120
+ case 'waitFor':
3121
+ return await guestWait(run, params)
3122
+ case 'screenshot': {
3123
+ const image = await element.capturePage()
3124
+ const size = image.getSize()
3125
+ return { dataUrl: image.toDataURL(), width: size.width, height: size.height }
3126
+ }
3127
+ default:
3128
+ throw new Error(`guest cannot do "${method}"`)
3129
+ }
3130
+ }
3131
+
3132
+ const onPointerDown = (event) => {
3133
+ sinkRef.current?.focus?.()
3134
+ canvasRef.current?.setPointerCapture?.(event.pointerId)
3135
+ draggingRef.current = true
3136
+ const point = toPageCoords(event)
3137
+ send({ type: 'input', kind: 'mouse', event: 'down', x: point.x, y: point.y, button: 'left', clickCount: 1 })
3138
+ }
3139
+ const onPointerUp = (event) => {
3140
+ draggingRef.current = false
3141
+ const point = toPageCoords(event)
3142
+ send({ type: 'input', kind: 'mouse', event: 'up', x: point.x, y: point.y, button: 'left', clickCount: 1 })
3143
+ }
3144
+ /** Flush the newest coalesced pointer position into the page. */
3145
+ const flushMove = () => {
3146
+ moveFrameRef.current = 0
3147
+ const point = pendingMoveRef.current
3148
+ pendingMoveRef.current = undefined
3149
+ if (point === undefined) return
3150
+ send({ type: 'input', kind: 'mouse', event: 'move', x: point.x, y: point.y, buttons: draggingRef.current ? 1 : 0 })
3151
+ }
3152
+ const onPointerMove = (event) => {
3153
+ // Coalesce instead of dropping. The old 40 ms throttle discarded every
3154
+ // event inside its window, which made the cursor visibly jump at 25 Hz
3155
+ // and read as "not keeping up"; one send per animation frame is both
3156
+ // faster and cheaper on the CDP side.
3157
+ pendingMoveRef.current = toPageCoords(event)
3158
+ if (moveFrameRef.current === 0) moveFrameRef.current = requestAnimationFrame(flushMove)
3159
+ }
3160
+ const onKeyDown = (event) => {
3161
+ const special = SPECIAL_KEYS[event.key]
3162
+ if (special !== undefined) {
3163
+ event.preventDefault()
3164
+ send({
3165
+ type: 'input',
3166
+ kind: 'key',
3167
+ event: 'down',
3168
+ key: special.key,
3169
+ code: special.code,
3170
+ keyCode: special.keyCode,
3171
+ text: special.text,
3172
+ modifiers: modifiersOf(event),
3173
+ })
3174
+ return
3175
+ }
3176
+ // Everything else is typed: the sink's input event carries the glyph,
3177
+ // and IME composition arrives through compositionend.
3178
+ }
3179
+ const onKeyUp = (event) => {
3180
+ const special = SPECIAL_KEYS[event.key]
3181
+ if (special === undefined) return
3182
+ send({
3183
+ type: 'input',
3184
+ kind: 'key',
3185
+ event: 'up',
3186
+ key: special.key,
3187
+ code: special.code,
3188
+ keyCode: special.keyCode,
3189
+ modifiers: modifiersOf(event),
3190
+ })
3191
+ }
3192
+ const onInput = (event) => {
3193
+ const text = event.target.value
3194
+ event.target.value = ''
3195
+ if (text !== '') send({ type: 'input', kind: 'text', text })
3196
+ }
3197
+ const onCompositionEnd = (event) => {
3198
+ const text = event.data
3199
+ if (typeof text === 'string' && text !== '') send({ type: 'input', kind: 'text', text })
3200
+ }
3201
+ const onPaste = (event) => {
3202
+ const text = event.clipboardData?.getData?.('text') ?? ''
3203
+ if (text !== '') {
3204
+ event.preventDefault()
3205
+ send({ type: 'input', kind: 'text', text })
3206
+ }
3207
+ }
3208
+
3209
+ if (sessionId === '') {
3210
+ return h('div', { 'data-dsh-embedded-browser': '' }, h('div', { className: 'deb-notice' }, dict.noSession))
3211
+ }
3212
+
3213
+ const hostUrl = typeof status.url === 'string' ? status.url : ''
3214
+ // With a native guest the guest itself is the truth: it can be on a page the
3215
+ // host has not caught up with yet, and showing the host's stale URL would be
3216
+ // actively wrong.
3217
+ const url = NATIVE_VIEW && viewUrl !== '' ? viewUrl : hostUrl
3218
+ const httpUrl = /^https?:\/\//i.test(url) ? url : ''
3219
+ /**
3220
+ * 「独立窗口」: show this page in a real browser window.
3221
+ *
3222
+ * A headless Chromium has no window, so the host may restart it with
3223
+ * `--headless` off. The profile (and every login in it) survives, and the
3224
+ * page comes back on the same URL — the panel reconnects when it does.
3225
+ * Unlike 「浏览器打开」, the page stays in the plugin's browser, so the
3226
+ * agent can keep operating it.
3227
+ */
3228
+ const openInWindow = async () => {
3229
+ if (httpUrl === '') return
3230
+ setBusy(true)
3231
+ try {
3232
+ const answer = await requestJson(OPEN_WINDOW_PATH, { method: 'POST', body: { sessionId, url: httpUrl } })
3233
+ if (answer?.ok !== true) throw new Error(String(answer?.error ?? 'refused'))
3234
+ flash(answer.restarted === true ? dict.openWindowRestarted : dict.openWindowDone)
3235
+ } catch (error) {
3236
+ flash(`${dict.openWindowFailed}:${error?.message ?? error}`)
3237
+ } finally {
3238
+ setBusy(false)
3239
+ }
3240
+ }
3241
+ const title =
3242
+ NATIVE_VIEW && viewTitle !== ''
3243
+ ? viewTitle
3244
+ : typeof status.title === 'string'
3245
+ ? status.title
3246
+ : ''
3247
+ const running = status.running !== false
3248
+ const live = connection === 'live'
3249
+ const canType = NATIVE_VIEW ? open === true && nativeReady : live && open === true
3250
+ const dotState = open === true && live ? (running ? 'online' : 'offline') : connection === 'offline' ? 'offline' : ''
3251
+ // Three states, because a blank rate used to be ambiguous: a still page
3252
+ // emits no frames at all, so "no number" read the same as "the stream
3253
+ // died". `null` means no measurement yet; `0` means measured and still.
3254
+ const rateNote = typeof fps !== 'number' ? '' : fps > 0 ? `${fps} fps` : dict.still
3255
+ const withRate = (label) => (rateNote === '' ? label : `${label} · ${rateNote}`)
3256
+ const barNote =
3257
+ open !== true
3258
+ ? ''
3259
+ : NATIVE_VIEW
3260
+ ? // Frame rate is meaningless here: nothing is being streamed. While the
3261
+ // guest is not ready, say what it waits for instead of a stage-neutral
3262
+ // 「连接中」 that covered four different failures.
3263
+ nativeReady
3264
+ ? dict.nativeNote
3265
+ : mountStage !== ''
3266
+ ? mountStage
3267
+ : dict.connecting
3268
+ : live
3269
+ ? streamMode === 'poll'
3270
+ ? withRate(dict.pollHint)
3271
+ : withRate(dict.connected)
3272
+ : connection === 'offline'
3273
+ ? dict.offline
3274
+ : dict.connecting
3275
+ // Typing/pointer help only makes sense while the panel is forwarding input.
3276
+ const hint = open === true && NATIVE_VIEW !== true ? (live ? dict.instructions : barNote) : ''
3277
+
3278
+ /**
3279
+ * Flip this conversation's pin.
3280
+ *
3281
+ * Optimistic on purpose: the tick is a promise about memory, not an
3282
+ * operation on the page, so it must feel instant. The host echoes the real
3283
+ * value back through the next state push, which overwrites a failed guess.
3284
+ */
3285
+ const togglePin = () => {
3286
+ const next = !pinned
3287
+ setPinned(next)
3288
+ send({ type: 'residency', pinned: next })
3289
+ }
3290
+
3291
+ /** Open the settings row and read the live policy from the host. */
3292
+ const openSettings = async () => {
3293
+ setSettingsOpen((current) => !current)
3294
+ try {
3295
+ setSettings(await requestJson(SETTINGS_PATH))
3296
+ } catch (error) {
3297
+ flash(`${dict.settingsFailed}:${error?.message ?? error}`)
3298
+ }
3299
+ }
3300
+
3301
+ /** Apply one policy change; the host answers with the new live values. */
3302
+ const changeSettings = async (patch) => {
3303
+ try {
3304
+ setSettings(await requestJson(SETTINGS_PATH, { method: 'POST', body: patch }))
3305
+ } catch (error) {
3306
+ flash(`${dict.settingsFailed}:${error?.message ?? error}`)
3307
+ }
3308
+ }
3309
+
3310
+ /**
3311
+ * The policy editor.
3312
+ *
3313
+ * Three choices, all host-wide, all persisted beside the browser profile:
3314
+ * how much real browser this deployment hands out, how long an unpinned one
3315
+ * may sit idle, and how many may exist at once. Per-conversation pinning is
3316
+ * the tick box in the toolbar, not a row here — it belongs next to the page
3317
+ * it protects.
3318
+ */
3319
+ const renderSettings = () => {
3320
+ const current = settings ?? {}
3321
+ const mode = current.mode ?? 'on-demand'
3322
+ const idle = current.idleMinutes ?? 15
3323
+ const cap = current.maxLive ?? 3
3324
+ const row = (label, control, note) =>
3325
+ h(
3326
+ 'div',
3327
+ { className: 'deb-settings-item' },
3328
+ h('label', { className: 'deb-settings-row' }, h('span', { className: 'deb-settings-label' }, label), control),
3329
+ note === undefined || note === '' ? null : h('div', { className: 'deb-settings-note' }, note),
3330
+ )
3331
+ const select = (value, options, onPick) =>
3332
+ h(
3333
+ 'select',
3334
+ {
3335
+ className: 'deb-settings-select',
3336
+ value: String(value),
3337
+ onChange: (event) => onPick(event.target.value),
3338
+ },
3339
+ options.map((option) => h('option', { key: option.value, value: option.value }, option.label)),
3340
+ )
3341
+ return h(
3342
+ 'div',
3343
+ { className: 'deb-settings' },
3344
+ h('div', { className: 'deb-settings-head' }, dict.settingsTitle),
3345
+ row(
3346
+ dict.settingMode,
3347
+ select(mode, [
3348
+ { value: 'on-demand', label: dict.modeOnDemand },
3349
+ { value: 'always', label: dict.modeAlways },
3350
+ { value: 'off', label: dict.modeOff },
3351
+ ], (next) => void changeSettings({ mode: next })),
3352
+ dict.noteMode,
3353
+ ),
3354
+ row(
3355
+ dict.settingIdle,
3356
+ select(idle, [
3357
+ { value: '0', label: dict.neverReclaim },
3358
+ { value: '5', label: `5 ${dict.unitMin}` },
3359
+ { value: '15', label: `15 ${dict.unitMin}` },
3360
+ { value: '30', label: `30 ${dict.unitMin}` },
3361
+ { value: '60', label: `60 ${dict.unitMin}` },
3362
+ ], (next) => void changeSettings({ idleMinutes: Number(next) })),
3363
+ dict.noteIdle,
3364
+ ),
3365
+ row(
3366
+ dict.settingCap,
3367
+ select(cap, [
3368
+ { value: '1', label: '1' },
3369
+ { value: '2', label: '2' },
3370
+ { value: '3', label: '3' },
3371
+ { value: '5', label: '5' },
3372
+ { value: '8', label: '8' },
3373
+ { value: '0', label: dict.unlimited },
3374
+ ], (next) => void changeSettings({ maxLive: Number(next) })),
3375
+ dict.noteCap,
3376
+ ),
3377
+ // The second clock. Residency reclaims one conversation's browser; this
3378
+ // one shuts the whole browser process down, window and all.
3379
+ row(
3380
+ dict.settingShutdown,
3381
+ select(current.idleShutdownMinutes ?? 10, [
3382
+ { value: '0', label: dict.neverReclaim },
3383
+ { value: '10', label: `10 ${dict.unitMin}` },
3384
+ { value: '30', label: `30 ${dict.unitMin}` },
3385
+ { value: '60', label: `60 ${dict.unitMin}` },
3386
+ { value: '120', label: `120 ${dict.unitMin}` },
3387
+ ], (next) => void changeSettings({ idleShutdownMinutes: Number(next) })),
3388
+ dict.noteShutdown,
3389
+ ),
3390
+ h('div', { className: 'deb-settings-note deb-settings-foot' }, dict.settingsNote),
3391
+ )
3392
+ }
3393
+
3394
+ return h(
3395
+ 'div',
3396
+ { 'data-dsh-embedded-browser': '' },
3397
+ h(
3398
+ 'div',
3399
+ { className: 'deb-bar' },
3400
+ h('span', { className: 'deb-dot', 'data-state': dotState }),
3401
+ h('span', { className: 'deb-title', title: title !== '' ? title : dict.title }, title !== '' ? title : dict.title),
3402
+ h('span', { className: 'deb-url', title: url }, url),
3403
+ barNote !== '' ? h('span', { className: 'deb-note' }, barNote) : null,
3404
+ ),
3405
+ open === true
3406
+ ? h(
3407
+ 'div',
3408
+ { className: 'deb-tools' },
3409
+ h('button', { type: 'button', className: 'deb-btn', disabled: !canType, title: dict.back, onClick: () => viewNav('back') }, '←'),
3410
+ h('button', { type: 'button', className: 'deb-btn', disabled: !canType, title: dict.forward, onClick: () => viewNav('forward') }, '→'),
3411
+ h('button', { type: 'button', className: 'deb-btn', disabled: !canType, title: dict.reload, onClick: () => viewNav('reload') }, '⟳'),
3412
+ // 「重画」resends a frame over the pixel transport; a native guest
3413
+ // repaints itself and has no use for it.
3414
+ NATIVE_VIEW !== true
3415
+ ? h('button', { type: 'button', className: 'deb-btn', disabled: !canType, title: dict.refresh, onClick: () => send({ type: 'play' }) }, '❐')
3416
+ : null,
3417
+ h('span', { className: 'deb-spacer' }),
3418
+ h('input', {
3419
+ className: 'deb-address',
3420
+ type: 'text',
3421
+ spellCheck: false,
3422
+ placeholder: dict.address,
3423
+ title: dict.addressHint,
3424
+ value: addressEditing ? addressDraft : url,
3425
+ onFocus: () => {
3426
+ setAddressDraft(url)
3427
+ setAddressEditing(true)
3428
+ },
3429
+ onChange: (event) => {
3430
+ setAddressEditing(true)
3431
+ setAddressDraft(event.target.value)
3432
+ },
3433
+ onBlur: () => setAddressEditing(false),
3434
+ onKeyDown: (event) => {
3435
+ if (event.key === 'Enter') {
3436
+ event.preventDefault()
3437
+ goToAddress()
3438
+ return
3439
+ }
3440
+ if (event.key === 'Escape') {
3441
+ event.preventDefault()
3442
+ setAddressEditing(false)
3443
+ event.target.blur()
3444
+ }
3445
+ },
3446
+ }),
3447
+ h('span', { className: 'deb-spacer' }),
3448
+ // These three exist because the panel had to synthesise keys through
3449
+ // the host. A native guest receives real keystrokes, so they would
3450
+ // only ever act on the page the human is *not* looking at.
3451
+ NATIVE_VIEW !== true
3452
+ ? h('button', { type: 'button', className: 'deb-btn', disabled: !canType, title: dict.tab, onClick: () => pressKey({ key: 'Tab', code: 'Tab', keyCode: 9 }) }, '⇥ Tab')
3453
+ : null,
3454
+ NATIVE_VIEW !== true
3455
+ ? h('button', { type: 'button', className: 'deb-btn', disabled: !canType, title: dict.shiftTab, onClick: () => pressKey({ key: 'Tab', code: 'Tab', keyCode: 9 }, ['shift']) }, '⇤ ⇧Tab')
3456
+ : null,
3457
+ NATIVE_VIEW !== true
3458
+ ? h('button', { type: 'button', className: 'deb-btn', disabled: !canType, title: dict.enter, onClick: () => pressKey({ key: 'Enter', code: 'Enter', keyCode: 13, text: '\r' }) }, '⏎ Enter')
3459
+ : null,
3460
+ h('span', { className: 'deb-spacer' }),
3461
+ // 「独立窗口」sits beside 「浮窗」 because it is the same kind of
3462
+ // control — which surface the page lives on. Unlike the old
3463
+ // 「浏览器打开」 it keeps the page in **this** browser, so the agent
3464
+ // can keep operating it and the profile keeps the logins.
3465
+ h(
3466
+ 'button',
3467
+ {
3468
+ type: 'button',
3469
+ className: 'deb-btn',
3470
+ disabled: httpUrl === '' || busy,
3471
+ title: dict.openWindowHint,
3472
+ onClick: () => void openInWindow(),
3473
+ },
3474
+ dict.openWindowLabel,
3475
+ ),
3476
+ // 「浮窗」 sits beside the settings word rather than among the
3477
+ // navigation buttons: it changes which surface the page lives on,
3478
+ // not the page itself. Kept as a word for the same reason the
3479
+ // settings control is one.
3480
+ h(
3481
+ 'button',
3482
+ {
3483
+ type: 'button',
3484
+ className: 'deb-btn',
3485
+ title: floated ? dict.dockHint : dict.floatHint,
3486
+ 'data-on': floated ? 'true' : undefined,
3487
+ onClick: toggleFloat,
3488
+ },
3489
+ floated ? dict.dockLabel : dict.floatLabel,
3490
+ ),
3491
+ // A word, not a glyph. `⚙` renders as a six-pointed star or a small
3492
+ // flower in several of the fonts this panel inherits, and a control
3493
+ // nobody recognises is a control nobody uses — the settings row was
3494
+ // reported as "doesn't look like a gear" the day it shipped.
3495
+ h(
3496
+ 'button',
3497
+ {
3498
+ type: 'button',
3499
+ className: 'deb-btn deb-settings-btn',
3500
+ title: dict.settingsHint,
3501
+ 'data-on': settingsOpen ? 'true' : undefined,
3502
+ 'aria-expanded': settingsOpen ? 'true' : 'false',
3503
+ onClick: () => void openSettings(),
3504
+ },
3505
+ settingsOpen ? dict.settingsClose : dict.settingsLabel,
3506
+ ),
3507
+ // The tick box. Unpinned, this browser is closed once it has sat
3508
+ // unused for the idle window; pinned, it stays up for as long as the
3509
+ // conversation exists. It is never a "switch which browser" control:
3510
+ // closing one and using the other mid-job is the amnesia bug.
3511
+ h(
3512
+ 'button',
3513
+ {
3514
+ type: 'button',
3515
+ className: pinned ? 'deb-btn deb-pin' : 'deb-btn',
3516
+ 'data-on': pinned ? 'true' : undefined,
3517
+ title: pinned ? dict.pinOnHint : dict.pinOffHint,
3518
+ onClick: togglePin,
3519
+ },
3520
+ pinned ? dict.pinOn : dict.pinOff,
3521
+ ),
3522
+ h('button', { type: 'button', className: 'deb-btn deb-danger', disabled: busy, title: dict.closeTabTitle, onClick: () => void closeTab() }, dict.closeTab),
3523
+ )
3524
+ : null,
3525
+ human !== undefined
3526
+ ? h(
3527
+ 'div',
3528
+ { className: 'deb-banner', role: 'status', 'aria-live': 'assertive' },
3529
+ // Row one: what to do, and the whole width to say it in. The instruction
3530
+ // used to share its row with an input and two buttons, so prose was
3531
+ // squeezed into a 140 px column while controls got the room.
3532
+ h(
3533
+ 'div',
3534
+ { className: 'deb-banner-row' },
3535
+ h('strong', { className: 'deb-banner-tag' }, dict.humanTitle),
3536
+ h('span', { className: 'deb-banner-text', title: String(human.instruction ?? '') }, human.instruction),
3537
+ url === '' || url === 'about:blank'
3538
+ ? h('span', { className: 'deb-banner-blank' }, dict.humanBlankPage)
3539
+ : null,
3540
+ ),
3541
+ // Row two: how long they have been waiting, then what to press.
3542
+ h(
3543
+ 'div',
3544
+ { className: 'deb-banner-row deb-banner-actions' },
3545
+ h(
3546
+ 'span',
3547
+ { className: waited >= 60_000 ? 'deb-waited deb-waited-late' : 'deb-waited' },
3548
+ `${dict.humanWaited} ${formatWaited(waited)}`,
3549
+ ),
3550
+ h('span', { className: 'deb-grow' }),
3551
+ replyOpen
3552
+ ? h('input', {
3553
+ className: 'deb-reply',
3554
+ value: reply,
3555
+ placeholder: dict.replyPlaceholder,
3556
+ onChange: (event) => setReply(event.target.value),
3557
+ onKeyDown: (event) => {
3558
+ if (event.key !== 'Enter') return
3559
+ event.preventDefault()
3560
+ submitReply()
3561
+ },
3562
+ })
3563
+ : null,
3564
+ replyOpen
3565
+ ? h('button', { type: 'button', className: 'deb-ghost', disabled: reply.trim() === '', onClick: submitReply }, dict.reply)
3566
+ : h('button', { type: 'button', className: 'deb-ghost', onClick: () => setReplyOpen(true) }, dict.replyOpen),
3567
+ h('button', { type: 'button', className: 'deb-primary', title: dict.humanHint, onClick: finishHuman }, dict.humanDone),
3568
+ ),
3569
+ )
3570
+ : null,
3571
+ settingsOpen ? renderSettings() : null,
3572
+ h(
3573
+ 'div',
3574
+ { className: 'deb-stage', ref: stageRef },
3575
+ // The native guest is appended to this stage by the mount effect; React
3576
+ // must not render it (that is what blanked the panel), so this branch
3577
+ // renders nothing at all and the effect owns the element.
3578
+ open === true && NATIVE_VIEW
3579
+ ? null
3580
+ : open === true && transport === 'mjpeg' && liveUrl !== ''
3581
+ ? h('img', {
3582
+ ref: surfaceRef,
3583
+ className: 'deb-live',
3584
+ src: liveUrl,
3585
+ alt: 'live',
3586
+ draggable: false,
3587
+ tabIndex: 0,
3588
+ onPointerDown,
3589
+ onPointerUp,
3590
+ onPointerMove,
3591
+ onFocus: () => sinkRef.current?.focus?.(),
3592
+ onLoad: () => {
3593
+ liveFailures.current = 0
3594
+ setHasFrame(true)
3595
+ setFailure(undefined)
3596
+ },
3597
+ onError: reconnectLive,
3598
+ })
3599
+ : open === true
3600
+ ? h('canvas', {
3601
+ ref: (node) => {
3602
+ canvasRef.current = node
3603
+ surfaceRef.current = node
3604
+ },
3605
+ className: 'deb-canvas',
3606
+ tabIndex: 0,
3607
+ onPointerDown,
3608
+ onPointerUp,
3609
+ onPointerMove,
3610
+ onFocus: () => sinkRef.current?.focus?.(),
3611
+ })
3612
+ : null,
3613
+ // A native guest receives real keyboard events itself; an invisible
3614
+ // textarea competing for focus would swallow them.
3615
+ open === true && NATIVE_VIEW !== true
3616
+ ? h('textarea', {
3617
+ ref: sinkRef,
3618
+ className: 'deb-sink',
3619
+ 'aria-label': 'browser panel keyboard sink',
3620
+ onInput,
3621
+ onKeyDown,
3622
+ onKeyUp,
3623
+ onCompositionEnd,
3624
+ onPaste,
3625
+ })
3626
+ : null,
3627
+ // The page lives in a real window; this panel has nothing to show and must
3628
+ // not mount a guest (a guest would take tool routing back). The button is
3629
+ // the way home: without it the only exit from a window was to close it,
3630
+ // which used to end every session at once.
3631
+ open === true && windowed === true
3632
+ ? h(
3633
+ 'div',
3634
+ { className: 'deb-overlay', style: { pointerEvents: 'auto' } },
3635
+ h('div', { className: 'deb-overlay-note' }, dict.windowedNotice),
3636
+ h(
3637
+ 'button',
3638
+ {
3639
+ type: 'button',
3640
+ className: 'deb-primary',
3641
+ disabled: busy,
3642
+ title: dict.restoreHint,
3643
+ onClick: () => {
3644
+ setBusy(true)
3645
+ void restoreFromWindow()
3646
+ .catch((error) => flash(`${dict.restoreFailed}:${error?.message ?? error}`))
3647
+ .finally(() => setBusy(false))
3648
+ },
3649
+ },
3650
+ dict.restoreLabel,
3651
+ ),
3652
+ )
3653
+ : null,
3654
+ open === true && failure !== undefined ? h('div', { className: 'deb-overlay' }, `${dict.failed}:${failure}`) : null,
3655
+ // The host's headless browser being down does not stop a native guest from
3656
+ // showing a page, so this notice would be a lie here.
3657
+ open === true && failure === undefined && running === false && NATIVE_VIEW !== true
3658
+ ? h('div', { className: 'deb-overlay' }, dict.stopped)
3659
+ : null,
3660
+ // "waiting for the first frame" is a pixel-stream concept; a native guest
3661
+ // paints itself as soon as it has a page.
3662
+ open === true && failure === undefined && running && !hasFrame && live && NATIVE_VIEW !== true
3663
+ ? h('div', { className: 'deb-overlay' }, dict.waitingFrame)
3664
+ : null,
3665
+ open === undefined ? h('div', { className: 'deb-empty' }, h('div', { className: 'deb-empty-note' }, dict.checking)) : null,
3666
+ open === false
3667
+ ? h(
3668
+ 'div',
3669
+ { className: 'deb-empty' },
3670
+ h('div', { className: 'deb-empty-title' }, dict.empty),
3671
+ h('div', { className: 'deb-empty-note' }, dict.emptyHint),
3672
+ h('button', { type: 'button', className: 'deb-primary', disabled: busy, onClick: () => void openBrowser() }, busy ? dict.starting : dict.open),
3673
+ failure !== undefined ? h('div', { className: 'deb-empty-error' }, `${dict.openFailed}:${failure}`) : null,
3674
+ )
3675
+ : null,
3676
+ hint !== '' ? h('div', { className: 'deb-hint' }, hint) : null,
3677
+ notice !== '' ? h('div', { className: 'deb-toast' }, notice) : null,
3678
+ ),
3679
+ )
3680
+ }
3681
+
3682
+ /**
3683
+ * The tab chip: the glyph the type is recognised by, plus a dot while the
3684
+ * session it belongs to is waiting for a person.
3685
+ *
3686
+ * The chip is the discovery path for a request raised while the human is
3687
+ * looking at something else, so it polls on its own instead of reading the
3688
+ * body's state — a body is not even mounted while its tab is inactive.
3689
+ */
3690
+ function BrowserTabTitle(props) {
3691
+ const { dict } = props
3692
+ const sessionId = useSessionId(props)
3693
+ const [waiting, setWaiting] = useState(false)
3694
+ useEffect(() => {
3695
+ if (typeof sessionId !== 'string' || sessionId === '') return undefined
3696
+ let cancelled = false
3697
+ const tick = async () => {
3698
+ try {
3699
+ const payload = await requestJson(SESSIONS_PATH)
3700
+ if (cancelled) return
3701
+ const pending = Array.isArray(payload?.pending) ? payload.pending : []
3702
+ setWaiting(pending.some((request) => request?.sessionId === sessionId))
3703
+ } catch {
3704
+ /* cosmetic badge: a failed poll keeps the last known value */
3705
+ }
3706
+ }
3707
+ void tick()
3708
+ const timer = setInterval(() => void tick(), TITLE_POLL_MS)
3709
+ return () => {
3710
+ cancelled = true
3711
+ clearInterval(timer)
3712
+ }
3713
+ }, [sessionId])
3714
+ return h(
3715
+ 'span',
3716
+ { className: 'deb-tab-title' },
3717
+ h(BrowserIcon, { size: 14 }),
3718
+ h('span', { className: 'deb-tab-text' }, dict.title),
3719
+ waiting ? h('span', { className: 'deb-tab-dot', title: dict.pending }) : null,
3720
+ )
3721
+ }
3722
+
3723
+ /** Guide-page glyph: the same mark, at the size that page asks for. */
3724
+ function GuideIcon(props) {
3725
+ return h(BrowserIcon, { size: props?.size ?? 16 })
3726
+ }
3727
+
3728
+ /**
3729
+ * Open this plugin's tab by itself, the moment there is something to show.
3730
+ *
3731
+ * Nothing is pinned per session any more, so this watcher is the *only*
3732
+ * reason the tab appears. Two reasons count:
3733
+ *
3734
+ * - the session has a browser tab at all (the AI started driving one), once
3735
+ * per stretch of "this session has a browser" — a human who closes the tab
3736
+ * is obeyed until the browser itself comes back;
3737
+ * - a **new** hand-over request landed for this session, which reopens the
3738
+ * tab even if the human closed it before: a request nobody can see is a
3739
+ * request that hangs until it times out.
3740
+ *
3741
+ * It polls the **host-wide** state, because "does this session have a
3742
+ * browser" is exactly what a closed tab cannot tell us — but it only ever
3743
+ * acts on the session currently on screen. Opening into a session nobody is
3744
+ * looking at would move the Sidebar out from under whatever the human is
3745
+ * actually doing, and the chip's dot already covers discovery for the
3746
+ * sessions they switch to.
3747
+ *
3748
+ * @param ctx - client context; `sessions` and `sidebarRight` are optional.
3749
+ * @returns a disposer removing the poll and its subscription.
3750
+ */
3751
+ function watchSessions(ctx) {
3752
+ const sessions = ctx.get('sessions')
3753
+ const sidebar = ctx.get('sidebarRight')
3754
+ // `ctx.inject` already waited for both; these stay as the cheap guard for
3755
+ // a Sidebar build that provides the name without the Tab-domain method.
3756
+ if (sessions === undefined || sidebar === undefined) return () => {}
3757
+ if (typeof sidebar.openTabIn !== 'function') return () => {}
3758
+ const list = sessions.list
3759
+ if (list === undefined || typeof list.getSnapshot !== 'function' || typeof list.subscribe !== 'function') return () => {}
3760
+
3761
+ /** Sessions we already opened for the browser being present. */
3762
+ const openedForBrowser = new Set()
3763
+ /** Session → the hand-over request id we already opened for. */
3764
+ const openedForRequest = new Map()
3765
+ let disposed = false
3766
+ let timer
3767
+
3768
+ const evaluate = async () => {
3769
+ if (disposed) return
3770
+ let payload
3771
+ try {
3772
+ payload = await requestJson(SESSIONS_PATH)
3773
+ } catch {
3774
+ return /* the GUI may be reloading; the next tick recovers */
3775
+ }
3776
+ if (disposed) return
3777
+ // Which conversation the user is looking at. Older hosts exposed it as
3778
+ // `snapshot.current`; current builds only carry `{ids, byId, phase,
3779
+ // projectionsBySession}`, so fall back to the retain counts the host
3780
+ // itself uses to answer the same question. Never hard-code one source:
3781
+ // this is exactly the field that took the panel down for good.
3782
+ const snapshot = list.getSnapshot()
3783
+ let current = typeof snapshot?.current === 'string' ? snapshot.current : ''
3784
+ if (current === '') {
3785
+ const ids = Array.isArray(snapshot?.ids) ? snapshot.ids : []
3786
+ for (const id of ids) {
3787
+ let retainedBy
3788
+ try {
3789
+ retainedBy = sessions.retainInfo?.(id)?.getSnapshot?.()?.retainedBy
3790
+ } catch {
3791
+ retainedBy = undefined
3792
+ }
3793
+ if ((retainedBy?.mainView ?? 0) > 0) {
3794
+ current = id
3795
+ break
3796
+ }
3797
+ }
3798
+ }
3799
+ if (current === '') return
3800
+ // Publish the answer before any of this tick's early returns: panels use it
3801
+ // to decide whether a person is still with them, and a session that has no
3802
+ // browser row yet is still "the conversation on screen".
3803
+ currentDshSession = current
3804
+ const rows = Array.isArray(payload?.sessions) ? payload.sessions : []
3805
+ const pending = Array.isArray(payload?.pending) ? payload.pending : []
3806
+ if (!rows.some((row) => row?.id === current)) {
3807
+ // The browser for this session is gone: forget it, so opening one
3808
+ // again later brings the tab back on its own.
3809
+ openedForBrowser.delete(current)
3810
+ openedForRequest.delete(current)
3811
+ return
3812
+ }
3813
+ const request = pending.find((entry) => entry?.sessionId === current)
3814
+ if (request !== undefined && openedForRequest.get(current) !== request.id) {
3815
+ openedForRequest.set(current, request.id)
3816
+ openedForBrowser.add(current)
3817
+ reveal(sidebar, current)
3818
+ return
3819
+ }
3820
+ if (openedForBrowser.has(current)) return
3821
+ openedForBrowser.add(current)
3822
+ reveal(sidebar, current)
3823
+ }
3824
+
3825
+ const reveal = (service, sessionId) => {
3826
+ try {
3827
+ service.openTabIn(sessionId, TAB_KIND, { revealIfOpened: true })
3828
+ } catch (error) {
3829
+ console.warn('[dsh-embedded-browser] could not open the sidebar tab:', error)
3830
+ }
3831
+ }
3832
+
3833
+ const schedule = () => {
3834
+ if (disposed) return
3835
+ const hidden = typeof document !== 'undefined' && document.visibilityState === 'hidden'
3836
+ clearTimeout(timer)
3837
+ timer = setTimeout(() => {
3838
+ void evaluate().finally(schedule)
3839
+ }, hidden ? REVEAL_IDLE_POLL_MS : REVEAL_POLL_MS)
3840
+ }
3841
+
3842
+ const dispose = () => {
3843
+ if (disposed) return
3844
+ disposed = true
3845
+ clearTimeout(timer)
3846
+ unsubscribe?.()
3847
+ }
3848
+
3849
+ const unsubscribe = list.subscribe(() => {
3850
+ // A new current session must be evaluated at once, not up to two
3851
+ // seconds later: that is exactly the moment its tab should appear.
3852
+ schedule()
3853
+ })
3854
+ void evaluate().finally(schedule)
3855
+
3856
+ return () => {
3857
+ if (disposed) {
3858
+ unsubscribe()
3859
+ return
3860
+ }
3861
+ dispose()
3862
+ }
3863
+ }
3864
+
3865
+ /**
3866
+ * Mount the surfaces: styles, the tab type, its two keyed seats, and the
3867
+ * watcher that opens the tab when there is something to show.
3868
+ *
3869
+ * @param ctx - the client context provided by the DSH web runtime.
3870
+ */
3871
+ function apply(ctx) {
3872
+ const dict = pickDict(typeof navigator !== 'undefined' ? navigator.language : 'en')
3873
+
3874
+ // Styles: inserted once per plugin activation and removed with the fiber.
3875
+ const style = document.createElement('style')
3876
+ style.dataset.plugin = 'dsh-embedded-browser'
3877
+ style.textContent = CSS
3878
+ document.head.append(style)
3879
+ ctx.effect(() => () => style.remove())
3880
+
3881
+ // The tab type is two halves that must agree: a static definition in the
3882
+ // registry (what the type IS, and what `openTab` names) and a keyed slot
3883
+ // body under the very same id (what it looks like). A kind whose type
3884
+ // registered no body renders the owner's "nothing can view this" notice,
3885
+ // so both halves are installed together or not at all.
3886
+ //
3887
+ // **`ctx.get` is the wrong tool for a service that mounts later**, and on
3888
+ // the client half this plugin really is loaded before the Sidebar's
3889
+ // `provide()` runs even though the boot graph lists us last: reading it at
3890
+ // apply time came back `undefined` and the tab type was silently never
3891
+ // registered (found in the browser console, 2026-09-21). `ctx.inject`
3892
+ // waits for the declaration instead — the same rule the host half follows
3893
+ // for `webServer`/`connection`. A client without the Sidebar at all just
3894
+ // never runs these callbacks, which is the desired outcome: a browser-only
3895
+ // plugin must not take the workbench down with it.
3896
+ ctx.inject(['sidebarRightTabs'], (tabsCtx) =>
3897
+ tabsCtx.effect(
3898
+ () =>
3899
+ tabsCtx.sidebarRightTabs.register({
3900
+ id: TAB_ID,
3901
+ kind: TAB_KIND,
3902
+ title: () => dict.title,
3903
+ /**
3904
+ * Keep this body mounted across tab switches, Session switches,
3905
+ * collapse and docking.
3906
+ *
3907
+ * The body owns a real `<webview>` — a live page, not a picture of
3908
+ * one. Without this flag the Sidebar treats it as an ordinary tab and
3909
+ * throws the DOM away the moment the human looks at another
3910
+ * conversation: the guest dies with it, every tool call falls back to
3911
+ * the invisible headless tab, and the agent silently changes browsers
3912
+ * mid-job. The shipped browser tab declares this for exactly the same
3913
+ * reason (`keepMounted: desktop !== undefined`).
3914
+ *
3915
+ * The cost is memory (a mounted guest is a renderer process), which is
3916
+ * why `residency` reclaims idle unpinned ones instead of keeping every
3917
+ * conversation alive forever.
3918
+ */
3919
+ keepMounted: true,
3920
+ guide: [
3921
+ {
3922
+ order: 45,
3923
+ title: () => dict.guideTitle,
3924
+ description: () => dict.guideDescription,
3925
+ icon: GuideIcon,
3926
+ },
3927
+ ],
3928
+ }),
3929
+ 'embedded-browser: tab type',
3930
+ ),
3931
+ )
3932
+
3933
+ // Slot declarations arrive with their owning plugin's fiber, which may
3934
+ // mount after this one: `slots.inject` waits for the declaration instead
3935
+ // of failing registration.
3936
+ const disposers = []
3937
+ const track = (dispose) => {
3938
+ if (typeof dispose === 'function') disposers.push(dispose)
3939
+ }
3940
+ /**
3941
+ * The Sidebar's navigation controller, for the panel's 「浮窗」 button.
3942
+ *
3943
+ * `ctx.get('sidebarRight')` would read it once at apply time, before the
3944
+ * Sidebar has provided it — the same trap that kept `sidebarRightTabs`
3945
+ * from registering at all (see the note below). `inject` waits for the
3946
+ * declaration instead. It lands in a ref because the slot body is
3947
+ * registered first and must not close over `undefined`; the body reads
3948
+ * `ref.current` at click time, not at render time.
3949
+ */
3950
+ const sidebarRef = { current: undefined }
3951
+ ctx.inject(['sidebarRight'], (sideCtx) => {
3952
+ sidebarRef.current = sideCtx.sidebarRight
3953
+ sideCtx.effect(() => () => {
3954
+ sidebarRef.current = undefined
3955
+ })
3956
+ })
3957
+ try {
3958
+ track(
3959
+ ctx.slots.inject('sidebar.right.pane.tab', () =>
3960
+ ctx.slots.register({ name: 'sidebar.right.pane.tab', key: TAB_ID }, function Body(props) {
3961
+ const info = props.useTabInfo?.()
3962
+ return h(SessionPanel, { ...props, dict, sidebarRef, visible: info?.tab?.visible !== false })
3963
+ }),
3964
+ ),
3965
+ )
3966
+ track(
3967
+ ctx.slots.inject('sidebar.right.pane.tab.title', () =>
3968
+ ctx.slots.register({ name: 'sidebar.right.pane.tab.title', key: TAB_ID }, (props) =>
3969
+ h(BrowserTabTitle, { ...props, dict }),
3970
+ ),
3971
+ ),
3972
+ )
3973
+ } catch (error) {
3974
+ console.warn('[dsh-embedded-browser] slot registration failed:', error)
3975
+ }
3976
+ ctx.effect(() => () => {
3977
+ for (const dispose of disposers.splice(0)) dispose()
3978
+ })
3979
+
3980
+ // Same rule for the watcher: it drives `sidebarRight.openTabIn` and reads
3981
+ // the `sessions` list, so it waits for both rather than deciding from an
3982
+ // apply-time snapshot that they are missing.
3983
+ ctx.inject(['sessions', 'sidebarRight'], (watchCtx) =>
3984
+ watchCtx.effect(() => watchSessions(watchCtx), 'embedded-browser: tab reveal watcher'),
3985
+ )
3986
+ }
3987
+
3988
+ const exports = { apply, inject: ['slots'] }
3989
+ return exports
3990
+ },
3991
+ })