dsh-codex-style-computer-use 2.3.4 → 3.1.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.
Files changed (37) hide show
  1. package/README.md +60 -5
  2. package/README.zh.md +50 -5
  3. package/client.js +1556 -32
  4. package/lib/browser/APACHE-2.0.txt +202 -0
  5. package/lib/browser/MIT-dsh-doyourweb.txt +21 -0
  6. package/lib/browser/NOTICE.md +53 -0
  7. package/lib/browser/README.md +139 -0
  8. package/lib/browser/access.js +540 -0
  9. package/lib/browser/approval.js +82 -0
  10. package/lib/browser/bridge.js +1048 -0
  11. package/lib/browser/engine.js +669 -0
  12. package/lib/browser/extension/background.js +474 -0
  13. package/lib/browser/extension/config.js +6 -0
  14. package/lib/browser/extension/manifest.json +25 -0
  15. package/lib/browser/extension/popup.css +89 -0
  16. package/lib/browser/extension/popup.html +35 -0
  17. package/lib/browser/extension/popup.js +99 -0
  18. package/lib/browser/host-protocol.js +132 -0
  19. package/lib/browser/host.js +1089 -0
  20. package/lib/browser/model.js +111 -0
  21. package/lib/browser/pairing.js +126 -0
  22. package/lib/browser/policy.js +131 -0
  23. package/lib/browser/protocol.js +171 -0
  24. package/lib/browser/schema.js +82 -0
  25. package/lib/browser/setup-page.js +145 -0
  26. package/lib/core/bin/dsh-computer-use-worker.exe +0 -0
  27. package/lib/core/bin/dsh-computer-use-worker.exe.json +2 -2
  28. package/lib/core/index.js +58 -1
  29. package/lib/core/worker.cs +32 -1
  30. package/lib/host-debug.js +3 -2
  31. package/lib/index.js +286 -4
  32. package/lib/references-apps.js +586 -0
  33. package/lib/references-files.js +77 -0
  34. package/lib/references.js +233 -0
  35. package/package.json +7 -2
  36. package/scripts/check-behavior.mjs +60 -0
  37. package/scripts/verify-browser-integration.mjs +807 -0
package/client.js CHANGED
@@ -1,20 +1,38 @@
1
1
  /**
2
- * client.js — the settings page for HOST DEBUG MODE.
2
+ * client.js — the browser half of this plugin.
3
3
  *
4
- * WHY IT EXISTS
5
- * The worker refuses every driving op aimed at the DSH window: the host owns the human's approval
6
- * cards, the question card and the Stop control, so an agent that could click it could approve
7
- * itself. Self-iteration (debugging ANOTHER plugin inside this same instance) needs to drive that
8
- * window, and the only honest way to allow it is two gates the agent cannot open itself:
4
+ * THREE THINGS LIVE HERE, and they share one bundle because they are one page's work:
9
5
  *
10
- * 1. THIS conversation holds 完全权限 (session sandbox = danger-full-access);
11
- * 2. debug mode is switched ON by a human here.
6
+ * 1. THE SETTINGS PAGE for HOST DEBUG MODE (unchanged). The worker refuses every driving op aimed
7
+ * at the DSH window; self-iteration needs two gates a human controls, and this page is gate 2.
8
+ * See lib/host-debug.js for the contract; the route is host-side and a tool cannot write it.
12
9
  *
13
- * The switch is stored host-side (lib/host-debug.js) and read hot by the worker, so toggling it
14
- * needs no restart. The page never enables gate 1 — that is the composer's permission pill.
10
+ * 2. THE `@` REFERENCE SOURCES. The composer's own @ menu is where a human points at what they
11
+ * mean, so the open web pages and the running applications appear THERE instead of in a second
12
+ * picker. A pick inserts ONE atomic reference into that conversation's DRAFT; the pick itself
13
+ * sends nothing, focuses nothing and drives nothing. Only a human pick produces a session
14
+ * reference, which is what the host later honours.
15
+ *
16
+ * 3. THE NATIVE BROWSER SIDEBAR: search, live state (connected / available / authorized) and the
17
+ * per-conversation window authorization switch.
18
+ *
19
+ * TWO HOST SURFACES, EACH WITH ONE OWNER (do not merge them):
20
+ * * `/api/computer-use/browser/*` — list, access, setup, focus. Owned by lib/browser/host.js,
21
+ * which owns the bridge, the tab citations and the window access. This bundle only CONSUMES it.
22
+ * * `/api/computer-use/references/*` — apps, apps/resolve. Owned by lib/references.js, which
23
+ * answers from the native worker's window inventory. Enumerating Windows is expensive, so it
24
+ * happens only when the application list is actually asked for — never on a browser @ search.
25
+ *
26
+ * The file/folder/conversation CATEGORY search is not a new source: it decorates the native
27
+ * reference source in place (the `cu-reference-folders` region below) so a folder flood stops hiding
28
+ * files, `@文件:` / `@文件夹:` / `@对话:` narrow the list, and every native behaviour — atomic
29
+ * insertion, folder drill-down, quoting, other sources — survives untouched. That region is the ONE
30
+ * implementation: it only ever runs in the browser, so build/test-reference-folders.mjs extracts it
31
+ * from this shipped bundle and executes it, instead of testing a server-side mirror.
15
32
  *
16
33
  * Same hand-written ModuleLoader bundle as the other DSH plugins: no build step, React comes from
17
- * the shell's `require('react')`.
34
+ * the shell's `require('react')`, and no Harness client package is required as a module (their APIs
35
+ * change without notice). Only React and the DOM are used.
18
36
  */
19
37
  window.__ModuleLoader__.load({
20
38
  id: 'dsh-codex-style-computer-use',
@@ -22,8 +40,11 @@ window.__ModuleLoader__.load({
22
40
  const module = { exports: {} }
23
41
  const exports = module.exports
24
42
  const React = require('react')
25
- const { createElement: h, useState, useEffect, useCallback } = React
43
+ const { createElement: h, useState, useEffect, useCallback, useRef, useSyncExternalStore } = React
26
44
 
45
+ // ============================================================================================
46
+ // 1. SETTINGS → 电脑操控(调试)
47
+ // ============================================================================================
27
48
  const API = '/api/computer-use/host-debug'
28
49
  const TEXT = {
29
50
  nav: '电脑操控(调试)',
@@ -47,6 +68,14 @@ window.__ModuleLoader__.load({
47
68
  since: '开启于',
48
69
  saveHint: '保存后立即生效,无需重启。',
49
70
  danger: '开启后,AI 可以点击、输入、滚动 Harness 窗口。除关闭/最小化/隐藏窗口永远禁止外,其余动作仅受门禁约束。',
71
+ pinTitle: '在侧栏显示浏览器',
72
+ pinOn: '已在侧栏显示',
73
+ pinOff: '已从侧栏移除',
74
+ pinUnknown: '无法读取',
75
+ pinHint: '取消固定后,可在这里把「浏览器」加回侧栏。',
76
+ pinUnavailable: '侧栏还没加载出来,暂时无法切换。',
77
+ pinUnsupported: '当前宿主没有提供侧栏固定接口,这一项无法从这里切换;请在侧栏的「更多」菜单里固定。',
78
+ pinFailed: '切换没有生效,请稍后在侧栏里重试。',
50
79
  }
51
80
 
52
81
  function row (label, value, ok) {
@@ -55,35 +84,84 @@ window.__ModuleLoader__.load({
55
84
  h('b', { style: { color: ok ? 'inherit' : '#c0392b' } }, value))
56
85
  }
57
86
 
58
- function SettingsPage () {
87
+ const subscribeToNothing = () => () => {}
88
+ const selectedId = current => current?.getSnapshot().key ?? null
89
+
90
+ async function requestStatus (sessionId, options) {
91
+ const url = sessionId ? API + '?session=' + encodeURIComponent(sessionId) : API
92
+ const r = await fetch(url, options)
93
+ const status = await r.json()
94
+ if (!r.ok) throw new Error(status.error || ('HTTP ' + r.status))
95
+ return status
96
+ }
97
+
98
+ function SettingsPage ({ current, panelPin }) {
99
+ const sessionId = useSyncExternalStore(current?.subscribe ?? subscribeToNothing, () => selectedId(current))
59
100
  const [state, setState] = useState(null)
60
101
  const [error, setError] = useState(null)
61
102
  const [busy, setBusy] = useState(false)
103
+ const lastRead = useRef(0)
104
+ // The sidebar owns the pinned set, so this component only mirrors it. Reading through the same
105
+ // subscription the sidebar writes keeps "cancelled in the sidebar → shown as off here" true
106
+ // without any second store, and without a poll.
107
+ const pin = panelPin
108
+ ? useSyncExternalStore(panelPin.subscribe, panelPin.getSnapshot)
109
+ : null
110
+ const [pinBusy, setPinBusy] = useState(false)
111
+ const [pinNote, setPinNote] = useState('')
112
+
113
+ /**
114
+ * Flip the sidebar row through the HOST's own pin control.
115
+ *
116
+ * NOTHING IS REMEMBERED HERE. The sidebar re-renders after the host handles the click, the
117
+ * observer republishes, and this component paints whatever actually happened — so a pin the
118
+ * human changed in the sidebar is never contradicted by a local copy.
119
+ */
120
+ async function togglePin () {
121
+ if (!panelPin || pinBusy) return
122
+ setPinBusy(true)
123
+ setPinNote('')
124
+ try {
125
+ const outcome = await panelPin.toggle()
126
+ if (!outcome.ok) setPinNote(
127
+ outcome.reason === 'host-unsupported' ? TEXT.pinUnsupported
128
+ : outcome.reason === 'host-rejected' ? TEXT.pinFailed
129
+ : TEXT.pinFailed)
130
+ } catch (e) { setPinNote(String(e?.message ?? e) || TEXT.pinFailed) } finally { setPinBusy(false) }
131
+ }
62
132
 
63
133
  const load = useCallback(async () => {
134
+ const read = ++lastRead.current
64
135
  setError(null)
65
136
  try {
66
- const r = await fetch(API, { cache: 'no-store' })
67
- const j = await r.json()
68
- if (!r.ok) throw new Error(j.error || ('HTTP ' + r.status))
69
- setState(j)
70
- } catch (e) { setError(String(e?.message ?? e)) }
71
- }, [])
137
+ const status = await requestStatus(selectedId(current), { cache: 'no-store' })
138
+ if (read === lastRead.current) setState(status)
139
+ } catch (e) { if (read === lastRead.current) setError(String(e?.message ?? e)) }
140
+ }, [current])
72
141
 
73
- useEffect(() => { load() }, [load])
142
+ useEffect(() => {
143
+ load()
144
+ return () => { lastRead.current++ }
145
+ }, [load, sessionId])
74
146
 
75
- const save = useCallback(async (enabled) => {
147
+ async function save (enabled) {
76
148
  setBusy(true)
149
+ setError(null)
77
150
  try {
78
- const r = await fetch(API, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ enabled }) })
79
- const j = await r.json()
80
- if (!r.ok) throw new Error(j.error || ('HTTP ' + r.status))
81
- setState(j)
151
+ const saved = await requestStatus(sessionId, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ enabled }) })
152
+ if (saved.session.id === selectedId(current)) {
153
+ lastRead.current++
154
+ setState(saved)
155
+ } else {
156
+ // The switch is shared. Refresh the conversation selected during the save.
157
+ await load()
158
+ }
82
159
  } catch (e) { setError(String(e?.message ?? e)) } finally { setBusy(false) }
83
- }, [])
160
+ }
84
161
 
85
- const sandbox = state?.session?.sandbox ?? null
86
- const full = state?.session?.fullAccess === true
162
+ const permission = state?.session?.id === sessionId ? state.session : null
163
+ const sandbox = permission?.sandbox ?? null
164
+ const full = permission?.fullAccess === true
87
165
  const enabled = state?.enabled === true
88
166
 
89
167
  return h('div', { style: { padding: '18px 22px', lineHeight: 1.55, maxWidth: 760 } },
@@ -94,7 +172,7 @@ window.__ModuleLoader__.load({
94
172
  row(TEXT.gate1, full ? TEXT.fullYes : (sandbox ? (TEXT.fullNo + ':' + sandbox) : TEXT.fullUnknown), full),
95
173
  row(TEXT.gate2, enabled ? TEXT.on : TEXT.off, enabled),
96
174
  h('p', { style: { margin: '10px 0 0', opacity: .75, fontSize: 13 } }, TEXT.gateHint),
97
- !full ? h('p', { style: { margin: '6px 0 0', color: '#c0392b', fontSize: 13 } }, TEXT.warnGate1) : null,
175
+ sandbox && !full ? h('p', { style: { margin: '6px 0 0', color: '#c0392b', fontSize: 13 } }, TEXT.warnGate1) : null,
98
176
  !enabled ? h('p', { style: { margin: '6px 0 0', opacity: .75, fontSize: 13 } }, TEXT.warnOff) : null,
99
177
  state.lastBlockedAt ? h('p', { style: { margin: '6px 0 0', fontSize: 13 } }, TEXT.warnBlocked + '(' + TEXT.blockedAt + ':' + state.lastBlockedAt + ')') : null,
100
178
  h('p', { style: { margin: '6px 0 0', fontSize: 13, opacity: .6 } },
@@ -102,24 +180,1470 @@ window.__ModuleLoader__.load({
102
180
  ) : h('p', { style: { opacity: .7 } }, TEXT.loading),
103
181
  h('div', { style: { display: 'flex', gap: 10, margin: '16px 0 14px' } },
104
182
  h('button', {
105
- disabled: busy,
183
+ disabled: busy || !state,
106
184
  onClick: () => save(!enabled),
107
185
  style: { padding: '7px 16px', borderRadius: 6, border: '1px solid rgba(127,127,127,.4)', cursor: 'pointer', fontWeight: 600, background: enabled ? 'transparent' : '#1f6feb', color: enabled ? 'inherit' : '#fff' },
108
186
  }, busy ? '…' : (enabled ? '关闭调试模式' : '开启调试模式')),
109
187
  h('button', { disabled: busy, onClick: load, style: { padding: '7px 14px', borderRadius: 6, border: '1px solid rgba(127,127,127,.3)', cursor: 'pointer', background: 'transparent' } }, TEXT.reload)
110
188
  ),
111
- h('p', { style: { margin: 0, fontSize: 13, lineHeight: 1.5, padding: '10px 12px', border: '1px solid rgba(200,120,0,.5)', borderRadius: 6, background: 'rgba(200,120,0,.08)' } }, '⚠ ' + TEXT.danger)
189
+ // The debug warning belongs to the debug switch above it: it stays IMMEDIATELY after the
190
+ // buttons, before any other block, so it cannot read as a caption for the sidebar switch.
191
+ h('p', { style: { margin: '0 0 14px', fontSize: 13, lineHeight: 1.5, padding: '10px 12px', border: '1px solid rgba(200,120,0,.5)', borderRadius: 6, background: 'rgba(200,120,0,.08)' } }, '⚠ ' + TEXT.danger),
192
+ panelPin ? h('div', { style: { margin: 0, paddingTop: 12, borderTop: '1px solid rgba(127,127,127,.18)' } },
193
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 12 } },
194
+ h('label', { style: { display: 'flex', alignItems: 'center', gap: 7, cursor: pin?.available ? 'pointer' : 'default', flex: 1 } },
195
+ h('input', {
196
+ type: 'checkbox',
197
+ // Checked means "the sidebar row is showing". Unknown (sidebar not mounted) leaves it
198
+ // unchecked and disabled rather than guessing a state this component cannot see.
199
+ checked: pin?.pinned === true,
200
+ disabled: pinBusy || !pin?.available,
201
+ onChange: () => { void togglePin() },
202
+ }),
203
+ h('span', null, TEXT.pinTitle)),
204
+ h('span', { style: { opacity: .7, fontSize: 13 } },
205
+ pin?.available ? (pin.pinned ? TEXT.pinOn : TEXT.pinOff) : TEXT.pinUnknown)),
206
+ h('p', { style: { margin: '8px 0 0', opacity: .7, fontSize: 13 } },
207
+ pin?.available ? TEXT.pinHint : TEXT.pinUnavailable),
208
+ pinNote ? h('p', { style: { margin: '6px 0 0', fontSize: 13, color: '#c0392b' } }, pinNote) : null
209
+ ) : null
112
210
  )
113
211
  }
114
212
 
213
+ // ============================================================================================
214
+ // 2. THE PINNED-STATE BRIDGE
215
+ // Delimited so the regression test can extract THIS EXACT CODE from the shipped bundle.
216
+ // ============================================================================================
217
+ /* <cu-panel-pin> */
218
+ //
219
+ // THE HOST'S OFFICIAL SEAM (confirmed against the host source the coordinator supplied): the
220
+ // root-scoped `sidebar.panellist.actions` slot passes every registration
221
+ // `{ entries, onOpen, onPinnedChange, onDismiss }`. That is the real pin API — the sidebar's own
222
+ // pinned set stays private, but `onPinnedChange(id, pinned)` reads and writes it.
223
+ //
224
+ // So this module registers ONE occupant that renders `null` and only CAPTURES those callbacks.
225
+ // It never adds a menu row, never duplicates an entry, and disappears with the menu it belongs to.
226
+ //
227
+ // THE HARD CASE, AND WHY THIS FILE IS SHAPED THIS WAY: when the human cancels our pin, the sidebar
228
+ // row UNMOUNTS. There is then NO icon of ours anywhere in the DOM — the More menu is closed and the
229
+ // glyph simply does not exist. "No icon" is therefore the NORMAL cancelled state, not "unavailable",
230
+ // and it is exactly the state this switch must be able to escape. So absence reads as
231
+ // `pinned:false`, and the write path needs no glyph either: it calls the official
232
+ // `onPinnedChange`, opening the native More menu only to obtain that callback.
233
+ //
234
+ // READING is ONE scoped DOM query inside the sidebar's navigation landmark. The More popup is not
235
+ // inside `nav`, so the menu's copy of our icon can never answer for the row — no tree walk needed.
236
+ const PIN_ATTR = 'data-cu-glyph'
237
+ const PIN_MARK = 'browser'
238
+ /** Where our row can legitimately live: the sidebar's own navigation landmark. */
239
+ const PIN_SCOPE = 'nav'
240
+ /** What the host's "More" trigger is called, in the spellings this package ships. */
241
+ const MORE_TOKENS = ['more', '更多']
242
+
243
+ // NOTE: this block is SELF-CONTAINED on purpose (the regression test extracts it from the shipped
244
+ // bundle and runs it alone), so it carries its own text normaliser rather than reaching into the
245
+ // reference-group section further down.
246
+ const pinNormalize = text => String(text == null ? '' : text).replace(/\uFF1A/g, ':').toLowerCase()
247
+
248
+ /** Is this node the host's "More" trigger? */
249
+ function isMoreControlLabel (text) {
250
+ const value = pinNormalize(text).trim()
251
+ if (!value) return false
252
+ return MORE_TOKENS.some(token => {
253
+ // `more` as a word (never inside "anymore"…), the CJK spelling directly.
254
+ if (/^[a-z]/.test(token)) return new RegExp(`(?:^|[^a-z])${token}(?:[^a-z]|$)`).test(value)
255
+ return value.includes(token)
256
+ })
257
+ }
258
+
259
+ /** Is this element a menu/modal surface? */
260
+ function isMenuSurface (element) {
261
+ if (!element || typeof element.getAttribute !== 'function') return false
262
+ const role = element.getAttribute('role')
263
+ if (role === 'menu' || role === 'menubar' || role === 'dialog' || role === 'listbox') return true
264
+ return element.getAttribute('aria-modal') === 'true'
265
+ }
266
+
267
+ /**
268
+ * Is our row currently on the sidebar?
269
+ *
270
+ * ONE scoped query and nothing else. The selector runs inside `nav` — the sidebar's own navigation
271
+ * landmark — which does NOT contain the More popup, so the menu's copy of our icon can never be
272
+ * mistaken for the row without examining any ancestor.
273
+ *
274
+ * A MOUNTED sidebar with no icon of ours means the human cancelled the pin: the row truly is gone.
275
+ * That is a real, reportable state (not "unknown"), which is what makes the switch able to undo it.
276
+ *
277
+ * @param {Document|Element|null} root
278
+ * @returns {{present: boolean, scopeFound: boolean}}
279
+ */
280
+ function readPinnedRow (root) {
281
+ if (!root || typeof root.querySelector !== 'function') return { present: false, scopeFound: false }
282
+ let scope = null
283
+ try { scope = root.querySelector(PIN_SCOPE) } catch { scope = null }
284
+ if (!scope) return { present: false, scopeFound: false }
285
+ let glyph = null
286
+ try { glyph = scope.querySelector(`[${PIN_ATTR}="${PIN_MARK}"]`) } catch { glyph = null }
287
+ return { present: !!glyph, scopeFound: true }
288
+ }
289
+
290
+ /** The host's "More" trigger inside the sidebar, if it is offered. */
291
+ function findMoreControl (root) {
292
+ if (!root || typeof root.querySelectorAll !== 'function') return null
293
+ let scope = root
294
+ try { scope = root.querySelector(PIN_SCOPE) ?? root } catch { scope = root }
295
+ let candidates = []
296
+ try { candidates = [...scope.querySelectorAll('button, [role="button"]')] } catch { candidates = [] }
297
+ for (const element of candidates) {
298
+ if (isMenuSurface(element)) continue
299
+ const label = [element.getAttribute?.('aria-label'), element.getAttribute?.('title'),
300
+ element.getAttribute?.('data-tooltip'), element.textContent]
301
+ .filter(value => typeof value === 'string').join(' ')
302
+ if (isMoreControlLabel(label)) return element
303
+ }
304
+ return null
305
+ }
306
+
307
+ /** Poll `test` until it passes or the deadline expires. */
308
+ const pinWaitFor = (test, timeoutMs, stepMs = 25) => new Promise(resolve => {
309
+ const started = Date.now()
310
+ const tick = () => {
311
+ let ok = false
312
+ try { ok = test() } catch { ok = false }
313
+ if (ok) return resolve(true)
314
+ if (Date.now() - started >= timeoutMs) return resolve(false)
315
+ setTimeout(tick, stepMs)
316
+ }
317
+ tick()
318
+ })
319
+
320
+ /**
321
+ * The live mirror of the sidebar's pinned state, shared by Settings and the observer.
322
+ *
323
+ * `read()` answers "is our row on the sidebar?" from the DOM, excluding menu copies.
324
+ * `toggle()` prefers the host's official `onPinnedChange`, captured from our null-rendering
325
+ * `sidebar.panellist.actions` occupant; when that callback is not captured yet it opens the native
326
+ * More menu the way a human would, waits for the occupant to mount, uses the callback ONCE, then
327
+ * dismisses and restores focus — and only closes a menu this module opened.
328
+ */
329
+ function createPanelPin ({
330
+ root = null, subscribeRoot = null,
331
+ slotApi = null, openMenu = null, closeMenu = null, restoreFocus = null,
332
+ entryId = null, menuTimeoutMs = 800,
333
+ } = {}) {
334
+ const listeners = new Set()
335
+ let snapshot = { pinned: false, available: false, action: null }
336
+ const publish = next => {
337
+ const changed = next.pinned !== snapshot.pinned || next.available !== snapshot.available ||
338
+ next.action !== snapshot.action
339
+ snapshot = next
340
+ if (changed) for (const listener of [...listeners]) { try { listener() } catch { /* a listener never breaks the others */ } }
341
+ return snapshot
342
+ }
343
+ const rootNow = () => {
344
+ try { return typeof root === 'function' ? root() : root } catch { return null }
345
+ }
346
+ const read = () => {
347
+ const found = readPinnedRow(rootNow())
348
+ // ONLY "the sidebar is not mounted" is unknown. A mounted sidebar with no icon of ours means
349
+ // the human cancelled the pin — the row genuinely is not there — so it reads as off and stays
350
+ // operable, which is the whole point of this switch.
351
+ if (!found.scopeFound) return publish({ pinned: false, available: false, action: null })
352
+ return publish({ pinned: found.present, available: true, action: found.present ? 'hide' : 'show' })
353
+ }
354
+ read()
355
+ const stop = typeof subscribeRoot === 'function' ? subscribeRoot(() => { read() }) : null
356
+ const captured = () => {
357
+ try { return slotApi?.current?.() ?? null } catch { return null }
358
+ }
359
+ return {
360
+ getSnapshot: () => snapshot,
361
+ subscribe (listener) {
362
+ listeners.add(listener)
363
+ // A new subscriber gets a fresh read, so a panel opened later is never stale.
364
+ if (listeners.size === 1) read()
365
+ return () => { listeners.delete(listener) }
366
+ },
367
+ refresh: read,
368
+ dispose () { try { stop?.() } catch { /* already gone */ } listeners.clear() },
369
+ /** Is the host's official pin callback reachable right now? */
370
+ hasOfficialSeam: () => captured() !== null,
371
+ /**
372
+ * Set the pin through the host, ONCE.
373
+ *
374
+ * @param {boolean} desired true = show the row on the sidebar
375
+ * @returns {Promise<{ok: boolean, reason?: string, closedMenu?: boolean}>}
376
+ */
377
+ async setPinned (desired) {
378
+ read()
379
+ // 1. The official callback, when the menu (or our occupant) already supplied it.
380
+ let api = captured()
381
+ let opened = false
382
+ if (!api) {
383
+ if (typeof openMenu !== 'function') return { ok: false, reason: 'host-unsupported' }
384
+ opened = await openMenu()
385
+ if (!opened) return { ok: false, reason: 'host-unsupported' }
386
+ // THE SLOT MOUNTS ASYNCHRONOUSLY. Opening is not the same as having our occupant mounted,
387
+ // so wait for the callback rather than reading it once and declaring the host unsupported.
388
+ await pinWaitFor(() => captured() !== null, menuTimeoutMs)
389
+ api = captured()
390
+ if (!api) {
391
+ try { closeMenu?.() } catch { /* already gone */ }
392
+ return { ok: false, reason: 'host-unsupported' }
393
+ }
394
+ }
395
+ try {
396
+ const id = entryId ?? null
397
+ if (id === null || typeof api.onPinnedChange !== 'function') return { ok: false, reason: 'host-unsupported' }
398
+ await api.onPinnedChange(id, desired)
399
+ } catch { return { ok: false, reason: 'host-rejected' } }
400
+ finally {
401
+ // Leave the menu exactly as we found it: only the one WE opened is dismissed.
402
+ if (opened) {
403
+ try { api.onDismiss?.() } catch { /* the host may already be closing */ }
404
+ try { closeMenu?.() } catch { /* idem */ }
405
+ try { restoreFocus?.() } catch { /* the old focus target may be gone */ }
406
+ }
407
+ }
408
+ read()
409
+ return { ok: true, closedMenu: opened }
410
+ },
411
+ /**
412
+ * Flip the current state.
413
+ *
414
+ * There is deliberately NO glyph-pressing path: when the row is cancelled the glyph does not
415
+ * exist at all, which is exactly the case that must work. Both directions use `setPinned`.
416
+ */
417
+ async toggle () {
418
+ read()
419
+ return this.setPinned(!snapshot.pinned)
420
+ },
421
+ }
422
+ }
423
+ /* </cu-panel-pin> */
424
+
425
+ // ============================================================================================
426
+ // 2. THE FILE / FOLDER / CONVERSATION CATEGORY REGION
427
+ // Delimited so the regression test can extract THIS EXACT CODE from the shipped bundle and run
428
+ // it. It is the only implementation — the plugin has no build step and a browser bundle cannot
429
+ // import a server module, so there is no second copy to keep in step.
430
+ // ============================================================================================
431
+ /* <cu-reference-folders> */
432
+ // The KEY of each entry IS the category's `kind`: the native candidates classify as
433
+ // '文件' / '文件夹' / '对话' (see referenceKindOf), so resolving a query must hand back that same
434
+ // string. Deriving it here — instead of repeating `kind:` inside every entry — is what keeps the
435
+ // two sides from drifting apart, and it is why `referenceQuery` returns `{kind: key, ...}`.
436
+ const REFERENCE_GROUPS = {
437
+ 文件夹: { prefix: '文件夹:', label: '文件夹', icon: 'folder', aliases: ['文件夹', '目录', 'folder', 'folders', 'directory', 'directories'] },
438
+ 文件: { prefix: '文件:', label: '文件', icon: 'file', aliases: ['文件', 'file', 'files'] },
439
+ 对话: { prefix: '对话:', label: '对话', icon: 'session', aliases: ['对话', '会话', 'session', 'sessions'] },
440
+ }
441
+ const REFERENCE_TOGGLE = 'computer-use-reference-group'
442
+ const REFERENCE_PREVIEW = 3
443
+ const REFERENCE_ORDER = { 文件: 0, 文件夹: 1, 对话: 2 }
444
+ const REFERENCE_MARK = '__computerUseReferenceGroups'
445
+
446
+ // The IME produces U+FF1A; the alias itself is ASCII. Mapping ONE code unit onto ONE code unit
447
+ // keeps every slice index below valid for the text the user actually typed.
448
+ function referenceNormalize (text) {
449
+ return String(text == null ? '' : text).replace(/\uFF1A/g, ':').toLowerCase()
450
+ }
451
+
452
+ /**
453
+ * Resolve a typed query into a category, or `undefined` for an ordinary search.
454
+ *
455
+ * ACCEPTED SPELLINGS (all real, all measurable in the composer):
456
+ * `文件:` / `文件:` / `file:` / `file:` → the FILE category, no filter
457
+ * `文件夹:` / `folder:` … → the FOLDER category
458
+ * `对话:` / `session:` … → the CONVERSATION category
459
+ * `文件: QA-Doc`, `file: QA` → the category AND the filter
460
+ * A space after the colon is the filter separator, so `@file: QA` keeps filtering instead of
461
+ * falling back to the unfiltered menu.
462
+ *
463
+ * THE ALIAS MUST BE THE TEXT THAT WAS TYPED, in exactly one of two shapes:
464
+ * normalized === alias → the bare category
465
+ * normalized.startsWith(alias+':') → the category plus its filter
466
+ * Anything else is an ordinary search. Both tests are an IDENTITY check, not a length check:
467
+ * `@README` is 6 characters — the same as `folder` — so a length-based slice silently turned a
468
+ * plain file search into "the folder category".
469
+ *
470
+ * @returns {{kind: string, label: string, prefix: string, icon: string, query: string}|undefined}
471
+ */
472
+ function referenceQuery (query = '') {
473
+ const raw = String(query == null ? '' : query)
474
+ const normalized = referenceNormalize(raw)
475
+ for (const [kind, group] of Object.entries(REFERENCE_GROUPS)) {
476
+ for (const alias of group.aliases) {
477
+ // (1) The query IS the alias: the bare category, no filter.
478
+ if (normalized === alias) return { ...group, kind, query: '' }
479
+ // (2) The query is the alias followed by a colon: the category AND its filter. The colon is
480
+ // consumed as a separator, so `file:QA` → 'QA', and the slice reads the ORIGINAL text so
481
+ // the filter keeps the characters the user typed. `referenceNormalize` has already mapped
482
+ // the IME's full-width ':' onto ':', so both spellings match here identically.
483
+ if (normalized.startsWith(alias + ':')) {
484
+ return { ...group, kind, query: raw.slice(alias.length + 1).replace(/^\s+/, '') }
485
+ }
486
+ // Anything else — a longer word, a near-miss, an unrelated term — is an ordinary search.
487
+ // These two tests ARE the identity check: a query whose LENGTH merely equals an alias
488
+ // (`README` vs `folder`) never matches either branch.
489
+ }
490
+ }
491
+ }
492
+
493
+ function referenceValue (candidate) {
494
+ try {
495
+ const value = JSON.parse(candidate && candidate.value)
496
+ return value && typeof value === 'object' ? value : {}
497
+ } catch { return {} }
498
+ }
499
+
500
+ /** The domain a native candidate belongs to: a directory is a FOLDER, not a file. */
501
+ function referenceKindOf (candidate) {
502
+ const value = referenceValue(candidate)
503
+ if (value.kind === 'file') return value.fileKind === 'directory' ? '文件夹' : '文件'
504
+ if (value.kind === 'directory' || value.kind === 'folder') return '文件夹'
505
+ if (value.kind === 'session') return '对话'
506
+ return undefined
507
+ }
508
+
509
+ function referenceToggleRow (kind, expanded, section, count) {
510
+ const group = REFERENCE_GROUPS[kind]
511
+ return {
512
+ name: expanded ? ('收起' + group.label) : (count > REFERENCE_PREVIEW ? `展开${group.label}(${count})` : `搜索${group.label}`),
513
+ section,
514
+ icon: group.icon,
515
+ ...(expanded || count ? {} : { description: '暂无候选,输入名称搜索或进入文件夹' }),
516
+ ...(expanded ? {} : { drill: true }),
517
+ value: JSON.stringify({ kind: REFERENCE_TOGGLE, text: expanded ? '@' : '@' + group.prefix }),
518
+ }
519
+ }
520
+
521
+ /**
522
+ * Narrow one candidate list to one domain and prepend its 收起 row.
523
+ *
524
+ * The projection keeps each native row's own `section` and only supplies one where the native
525
+ * row had none: the shipped source already sections its own rows (subagents vs. other sessions,
526
+ * for example), and overwriting them would silently re-bucket rows the user is looking for.
527
+ * @param {readonly object[]} items native candidates
528
+ * @param {{kind: string, label: string}} category
529
+ */
530
+ function referenceCategorized (items, category) {
531
+ const matches = (items || []).filter(item => referenceKindOf(item) === category.kind)
532
+ .map(item => item.section === undefined ? { ...item, section: category.label } : item)
533
+ return [referenceToggleRow(category.kind, true, category.label, matches.length), ...matches]
534
+ }
535
+
536
+ /**
537
+ * Group the unfiltered candidate list by domain, previewing each group.
538
+ * Native rows keep their identity; only a `section` and (for folders) `drill` are added.
539
+ *
540
+ * AN EMPTY GROUP IS NOT INVENTED. The shipped provider already reserves a slot for every file
541
+ * when it can, so a file group that is simply absent from the answer means the source did not
542
+ * report files — not that the user should be shown a "search files" row in a list where files were
543
+ * never expected (a category view, or a workspace with no files). The one exception is the case
544
+ * this decorator exists for: the provider's cap was consumed ENTIRELY by directories, which is
545
+ * measurable, and only then is the file row supplied so files stay reachable.
546
+ *
547
+ * @param {readonly object[]} items native candidates
548
+ * @param {number} preview rows shown per group before its 展开 row
549
+ * @param {{filesStarved?: boolean, limit?: number}} [hints]
550
+ */
551
+ function referenceGrouped (items, preview, hints = {}) {
552
+ const sections = new Map()
553
+ const list = items || []
554
+ for (const item of list) {
555
+ const kind = referenceKindOf(item)
556
+ if (!kind) {
557
+ const key = 'other:' + (item.section || '')
558
+ if (!sections.has(key)) sections.set(key, { kind: undefined, section: item.section, items: [] })
559
+ sections.get(key).items.push(item)
560
+ continue
561
+ }
562
+ const section = REFERENCE_GROUPS[kind].label
563
+ const key = kind + ':' + section
564
+ if (!sections.has(key)) sections.set(key, { kind, section, items: [] })
565
+ sections.get(key).items.push(kind === '文件夹' ? { ...item, section, drill: true } : { ...item, section })
566
+ }
567
+ // Files were crowded out by directories: the provider returned a FULL list of directories only.
568
+ // That is the measured starvation case, and the only one where a file row is useful.
569
+ const starved = hints.filesStarved === true ||
570
+ (Number.isSafeInteger(hints.limit) && hints.limit > 0 && list.length >= hints.limit && list.length > 0 &&
571
+ list.every(item => referenceKindOf(item) === '文件夹'))
572
+ if (starved && ![...sections.values()].some(section => section.kind === '文件')) {
573
+ sections.set('文件:文件', { kind: '文件', section: '文件', items: [] })
574
+ }
575
+ return [...sections.values()]
576
+ .sort((a, b) => sectionRank(a) - sectionRank(b))
577
+ .flatMap(({ kind, section, items }) => !kind ? items : [
578
+ ...items.slice(0, preview),
579
+ ...(items.length > preview || !items.length ? [referenceToggleRow(kind, false, section, items.length)] : []),
580
+ ])
581
+ }
582
+
583
+ function sectionRank (section) {
584
+ const rank = REFERENCE_ORDER[section.kind]
585
+ return rank === undefined ? 3 : rank
586
+ }
587
+
588
+ /**
589
+ * The live source roster of an installed `inputTriggers` service, or null when this host does not
590
+ * expose it. A host that keeps the roster private still gets newly registered sources decorated
591
+ * through the `registerSource` wrapper below; only the sources registered BEFORE this plugin would
592
+ * stay untouched, which is a documented degradation rather than a failure.
593
+ */
594
+ function referenceSourceList (service) {
595
+ try {
596
+ const live = service && service.live
597
+ const raw = live && live.sources
598
+ if (Array.isArray(raw)) return raw
599
+ if (raw && typeof raw.values === 'function') return [...raw.values()]
600
+ if (raw && typeof raw[Symbol.iterator] === 'function' && typeof raw !== 'string') return [...raw]
601
+ } catch { /* a frozen or proxied service: degrade */ }
602
+ return null
603
+ }
604
+
605
+ /**
606
+ * Decorate the native reference source in place and restore it on dispose.
607
+ *
608
+ * @param {{live?: {sources?: object[]}, registerSource?: Function, config?: {maxResults?: number}}} service
609
+ * `ctx.inputTriggers`
610
+ * @param {{preview?: number, limit?: number}} [options]
611
+ * `limit` is the native provider's result cap. When it is known, "the cap was consumed by
612
+ * directories" becomes measurable, which is the only condition under which an empty file group
613
+ * is worth adding. Without it the decorator never invents one.
614
+ * @returns {() => void} idempotent restore
615
+ */
616
+ function installReferenceGroups (service, options = {}) {
617
+ if (!service || typeof service !== 'object') return () => {}
618
+ const preview = Number.isSafeInteger(options.preview) && options.preview > 0 ? options.preview : REFERENCE_PREVIEW
619
+ // The cap may be configured on the trigger service or on the file-reference provider it wraps;
620
+ // either declaration is the same budget, so the first readable one is used.
621
+ const limit = Number.isSafeInteger(options.limit) && options.limit > 0
622
+ ? options.limit
623
+ : Number.isSafeInteger(service.config?.maxResults) && service.config.maxResults > 0
624
+ ? service.config.maxResults
625
+ : undefined
626
+ const wrapped = new Map()
627
+
628
+ function decorate (source) {
629
+ if (!source || wrapped.has(source) || source[REFERENCE_MARK] === true) return
630
+ if (source.trigger !== '@' || source.name !== 'reference') return
631
+ const original = { candidates: source.candidates, onPick: source.onPick, header: source.header, order: source.order }
632
+ if (typeof original.candidates !== 'function' || typeof original.onPick !== 'function') return
633
+ // The provider's own cap, when the source carries one, wins over the service-level default.
634
+ const sourceLimit = Number.isSafeInteger(source.config?.maxResults) && source.config.maxResults > 0
635
+ ? source.config.maxResults
636
+ : limit
637
+ const patched = {
638
+ order: Math.min(Number.isFinite(original.order) ? original.order : 0, -100),
639
+ async candidates (session, request) {
640
+ const live = request || {}
641
+ const category = live.quoted ? undefined : referenceQuery(live.query)
642
+ const items = await original.candidates.call(source, session,
643
+ category ? { ...live, query: category.query } : live)
644
+ if (category) return referenceCategorized(items, category)
645
+ if (live.query || live.quoted || live.drilled) return items
646
+ return referenceGrouped(items, preview, { limit: sourceLimit })
647
+ },
648
+ onPick (pick) {
649
+ const value = referenceValue(pick && pick.candidate)
650
+ if (value.kind === REFERENCE_TOGGLE) return { text: value.text, continue: true }
651
+ return original.onPick.call(source, pick)
652
+ },
653
+ header (session, request) {
654
+ const category = request && !request.quoted ? referenceQuery(request.query) : undefined
655
+ if (!category) return typeof original.header === 'function' ? original.header.call(source, session, request) : undefined
656
+ return [{ label: category.label, current: true, value: '' }]
657
+ },
658
+ }
659
+ for (const key of Object.keys(patched)) source[key] = patched[key]
660
+ source[REFERENCE_MARK] = true
661
+ wrapped.set(source, { original, patched })
662
+ }
663
+
664
+ for (const source of referenceSourceList(service) || []) decorate(source)
665
+ const descriptor = Object.getOwnPropertyDescriptor(service, 'registerSource')
666
+ const register = service.registerSource
667
+ const registerSource = typeof register === 'function'
668
+ ? function (source) { decorate(source); return register.call(this, source) }
669
+ : undefined
670
+ if (registerSource) {
671
+ try { Object.defineProperty(service, 'registerSource', { configurable: true, writable: true, value: registerSource }) } catch { /* frozen service: decorate what exists */ }
672
+ }
673
+ return () => {
674
+ for (const [source, { original, patched }] of wrapped) {
675
+ for (const key of Object.keys(patched)) {
676
+ if (source[key] !== patched[key]) continue
677
+ if (original[key] === undefined) delete source[key]
678
+ else source[key] = original[key]
679
+ }
680
+ delete source[REFERENCE_MARK]
681
+ }
682
+ wrapped.clear()
683
+ if (registerSource && Object.getOwnPropertyDescriptor(service, 'registerSource')?.value === registerSource) {
684
+ if (descriptor) Object.defineProperty(service, 'registerSource', descriptor)
685
+ else delete service.registerSource
686
+ }
687
+ }
688
+ }
689
+ /* </cu-reference-folders> */
690
+
691
+ // ============================================================================================
692
+ // 3. THE TWO HOST SURFACES, AND THE CANDIDATES BUILT FROM THEM
693
+ // ============================================================================================
694
+ /** Browser routes: owned by lib/browser/host.js. This bundle only consumes them. */
695
+ const BROWSER_API = '/api/computer-use/browser'
696
+ /** Reference routes: owned by lib/references.js (running applications only). */
697
+ const REFERENCES_API = '/api/computer-use/references'
698
+
699
+ const PAGE_SOURCE = 'computer-use-pages'
700
+ const APP_SOURCE = 'computer-use-apps'
701
+ const PANEL_TAB = 'computer-use-browser'
702
+ const PAGE_REF = /dsh-browser:\/\/[a-z0-9-]+\/\d+/i
703
+ const APP_REF = /^dsh-app:\/\/[0-9a-f-]{36}\/[0-9a-f]{24}$/i
704
+ /**
705
+ * A CHIP'S REF CARRIES ITS OWN OWNING CONVERSATION.
706
+ *
707
+ * `codec.serialize(ref, signal)` receives no session (verified against the installed
708
+ * `ReferenceCodec`), yet a reference belongs to exactly one conversation. A `Map<appRef, session>`
709
+ * cannot express that: the same window may be added to two different drafts, and the second pick
710
+ * overwrote the first; reloading the page lost the map entirely.
711
+ *
712
+ * So the identity travels WITH the chip, inside the ref this source owns:
713
+ *
714
+ * dsh-app:<sessionId>::<appRef>::<label>
715
+ *
716
+ * The persisted draft keeps that string, so the binding survives reload; the same ref can sit in
717
+ * two drafts at once; and nothing is remembered in process memory that a reload could lose. The
718
+ * trailing label is what lets copy/cut rebuild the plain mention without a lookup table (and it is
719
+ * cosmetic — a missing or altered label changes nothing the host verifies).
720
+ *
721
+ * `clipboardText` stays the plain `@[label](dsh-app://…)` mention, so copy/cut and the model still
722
+ * see the reference the host understands. The host re-verifies the pick AND the process on every
723
+ * resolve, so this encoding is a binder, not a permission.
724
+ */
725
+ const appChipRef = (sessionId, appRef, label) =>
726
+ `dsh-app:${encodeURIComponent(String(sessionId || ''))}::${appRef}::${encodeURIComponent(String(label || ''))}`
727
+
728
+ /** Split a chip ref back into `{sessionId, appRef, label}`; a bare appRef yields no session. */
729
+ function splitAppChipRef (value) {
730
+ const text = String(value == null ? '' : value)
731
+ const separator = text.indexOf('::')
732
+ if (text.startsWith('dsh-app:') && separator > 8) {
733
+ const sessionId = decodeURIComponent(text.slice('dsh-app:'.length, separator))
734
+ const rest = text.slice(separator + 2)
735
+ const tail = rest.indexOf('::')
736
+ const appRef = tail < 0 ? rest : rest.slice(0, tail)
737
+ const label = tail < 0 ? '' : decodeURIComponent(rest.slice(tail + 2))
738
+ if (APP_REF.test(appRef)) return { sessionId: sessionId || null, appRef, label }
739
+ }
740
+ const bare = text.match(/dsh-app:\/\/[0-9a-f-]{36}\/[0-9a-f]{24}/i)
741
+ // A legacy bare mention, or a chip written by an older version: the app ref is known, the
742
+ // conversation is not (the send path then falls back to the listing session, or refuses).
743
+ return bare ? { sessionId: null, appRef: bare[0], label: '' } : null
744
+ }
745
+
746
+ const UI = {
747
+ nav: '浏览器',
748
+ pages: '网页',
749
+ apps: '应用',
750
+ add: '加入草稿',
751
+ added: '已加入当前会话草稿',
752
+ noSession: '打开一个聊天会话后可加入草稿。',
753
+ sessionThenTab: '先在左侧打开一个聊天会话,再从右侧栏的「浏览器」页签查看网页与应用。',
754
+ search: '搜索网页标题、地址或应用',
755
+ loading: '正在读取…',
756
+ disconnected: '浏览器尚未连接',
757
+ authorized: '本会话已授权',
758
+ unauthorized: '本会话未授权',
759
+ authUnknown: '授权状态未知',
760
+ sleeping: '休眠,打开后可用',
761
+ weakIdentity: '窗口身份较弱',
762
+ setup: '连接设置',
763
+ refresh: '刷新',
764
+ window: '目标浏览器窗口',
765
+ pickWindow: '请选择窗口',
766
+ noWindow: '没有已连接的窗口',
767
+ windowUnknown: '暂时无法选择窗口',
768
+ allow: '允许 Agent 无需 @ 使用浏览器',
769
+ allowHint: '仅限当前会话和选定窗口。Agent 使用已有网页前会请你选定。',
770
+ emptyPages: '暂无可引用网页',
771
+ emptyApps: '暂无可引用应用',
772
+ emptySearch: '没有找到匹配结果',
773
+ emptyPagesHint: '在已连接的浏览器中打开一个网页。',
774
+ emptyAppsHint: '打开一个应用窗口后刷新。',
775
+ noService: '浏览器扩展服务未连接,暂不能列出网页。',
776
+ appsUnavailable: '暂时读不到正在运行的应用窗口。',
777
+ revoke: '关闭本会话授权',
778
+ revoked: '已关闭本会话授权',
779
+ focusHint: '点击草稿里的网页引用会在浏览器中定位该网页。',
780
+ appsHint: '应用引用绑定到具体窗口;进程退出或窗口被替换后会被拒绝执行。',
781
+ }
782
+
783
+ /** One authenticated same-origin GET/POST. Never sends credentials; the browser carries them. */
784
+ async function requestJson (base, path, options) {
785
+ const response = await fetch(base + path, { cache: 'no-store', ...options })
786
+ let body = {}
787
+ try { body = await response.json() } catch { body = {} }
788
+ if (!response.ok) {
789
+ const error = new Error(body?.error || ('HTTP ' + response.status))
790
+ error.status = response.status
791
+ throw error
792
+ }
793
+ return body
794
+ }
795
+
796
+ const browserApi = (path, options) => requestJson(BROWSER_API, path, options)
797
+ const referencesApi = (path, options) => requestJson(REFERENCES_API, path, options)
798
+
799
+ function queryString (params) {
800
+ const search = new URLSearchParams()
801
+ for (const [key, value] of Object.entries(params)) {
802
+ if (value === undefined || value === null || value === '') continue
803
+ search.set(key, String(value))
804
+ }
805
+ const text = search.toString()
806
+ return text ? '?' + text : ''
807
+ }
808
+
809
+ const mentionLabel = (value, fallback) => String(value || fallback).replace(/[\[\]\\\r\n]/g, ' ').trim().slice(0, 128) || fallback
810
+ const pageMention = page => `@[${mentionLabel(page.title || page.url, '网页')}](${page.ref})`
811
+ const appMention = app => `@[${mentionLabel(app.label || app.name, '应用')}](${app.ref})`
812
+
813
+ function hostOf (url) {
814
+ try {
815
+ const parsed = new URL(url)
816
+ return parsed.protocol === 'file:' ? '本地 HTML' : parsed.hostname
817
+ } catch { return '' }
818
+ }
819
+
820
+ function pageRow (page) {
821
+ const parts = [hostOf(page.url), page.browser].filter(Boolean)
822
+ parts.push(page.authorized === true ? UI.authorized : page.authorized === false ? UI.unauthorized : UI.authUnknown)
823
+ if (page.sleeping) parts.push(UI.sleeping)
824
+ return {
825
+ name: page.title || page.url || page.ref,
826
+ description: parts.join(' · '),
827
+ icon: 'file',
828
+ section: UI.pages,
829
+ value: JSON.stringify({ kind: 'page', ref: page.ref, label: page.title || page.url || page.ref }),
830
+ }
831
+ }
832
+
833
+ function appRow (app) {
834
+ const parts = [app.process || '', app.identityStrength === 'weak' ? UI.weakIdentity : ''].filter(Boolean)
835
+ return {
836
+ name: app.label || app.name || app.ref,
837
+ ...(parts.length ? { description: parts.join(' · ') } : {}),
838
+ icon: 'file',
839
+ section: UI.apps,
840
+ value: JSON.stringify({ kind: 'app', ref: app.ref, label: app.label || app.name || app.ref }),
841
+ }
842
+ }
843
+
844
+ const pageReference = page => ({ source: PAGE_SOURCE, ref: page.ref, label: page.title || page.url || page.ref, appearance: 'file', clipboardText: pageMention(page) })
845
+
846
+ /**
847
+ * THE ONE WAY AN APPLICATION CHIP IS BUILT — used by the `@` picker AND by the sidebar, so both
848
+ * entry points produce the same carrier and neither can forget the conversation.
849
+ *
850
+ * `ref` is the session-bearing chip ref (see `appChipRef`); `clipboardText` is the plain mention a
851
+ * human copies and the host parses.
852
+ */
853
+ const appReference = (app, sessionId) => ({
854
+ source: APP_SOURCE,
855
+ ref: appChipRef(sessionId, app.ref, app.label || app.name),
856
+ label: app.label || app.name,
857
+ appearance: 'file',
858
+ clipboardText: appMention(app),
859
+ })
860
+
861
+ /**
862
+ * Insert one reference chip into the conversation's OWN draft.
863
+ *
864
+ * This is the same draft the human is editing: existing text, chips, quotes and attachments
865
+ * survive, and nothing is submitted. The shell's own revision guard decides, so a draft that is
866
+ * already submitting refuses instead of corrupting.
867
+ */
868
+ function insertDraftReference (conversation, sessionId, reference) {
869
+ if (!conversation || !sessionId || !reference) return false
870
+ let shell = null
871
+ try { shell = conversation.input?.shell?.(sessionId) ?? null } catch { shell = null }
872
+ if (!shell || typeof shell.insertReference !== 'function') return false
873
+ const state = shell.state?.getSnapshot?.()
874
+ if (!state || state.phase === 'submitting' || state.phase === 'adjudicating') return false
875
+ const end = shell.projection.detectText.length
876
+ const inserted = shell.insertReference(reference, { start: end, end, draftRev: state.draftRev })
877
+ if (!inserted) return false
878
+ try { shell.actions?.persistDraft?.() } catch { /* the chip is already in the editor */ }
879
+ return true
880
+ }
881
+
882
+ /**
883
+ * Report a HUMAN pick to the host, so a session reference is created only by a pick.
884
+ *
885
+ * The promise is RETURNED, not discarded: a human can pick a row and press Enter before the
886
+ * report lands, and the send-time resolve would then be refused as "never picked". The send path
887
+ * awaits the one outstanding report for its own chip (see `pendingPicks`), so that race is closed
888
+ * without making a failed report fatal — a failure still degrades to a stricter host.
889
+ */
890
+ const pendingPicks = new Map() // `${session}\u0000${appRef}` → Promise
891
+ function reportPick (sessionId, appRef, value) {
892
+ if (!sessionId || !appRef) return Promise.resolve(false)
893
+ const key = `${sessionId}\u0000${appRef}`
894
+ const promise = referencesApi('/apps/resolve', {
895
+ method: 'POST', headers: { 'content-type': 'application/json' },
896
+ body: JSON.stringify({ session: sessionId, ref: appRef, pick: true }),
897
+ }).then(() => true, () => false).finally(() => {
898
+ if (pendingPicks.get(key) === promise) pendingPicks.delete(key)
899
+ })
900
+ pendingPicks.set(key, promise)
901
+ return promise
902
+ }
903
+
904
+ /** Wait for this chip's own pick report, if one is still in flight. */
905
+ async function settlePick (sessionId, appRef) {
906
+ const pending = pendingPicks.get(`${sessionId}\u0000${appRef}`)
907
+ if (pending) { try { await pending } catch { /* the resolve below reports the true state */ } }
908
+ }
909
+
910
+ /**
911
+ * One live inventory feed, shared by the open @ menu and the mounted sidebar tab. It polls only
912
+ * while something is listening, and it reads the bridge's in-memory inventory (never a page).
913
+ * A change in connection, tab set or authorization re-polls the open menu.
914
+ *
915
+ * IT DOES NOT FETCH ON SUBSCRIBE. Every consumer already performs its own first read (the menu
916
+ * through `candidates`, the panel through its list effect), so polling here as well would put a
917
+ * SECOND `/list` behind the same render. The feed's job is change detection afterwards — the
918
+ * interval, the window-focus event, and nothing else.
919
+ */
920
+ function createPageFeed (intervalMs = 1200) {
921
+ const listeners = new Set()
922
+ let timer = null
923
+ let controller = null
924
+ let busy = false
925
+ let snapshot = ''
926
+
927
+ const signature = value => JSON.stringify([
928
+ value?.connected !== false,
929
+ value?.error || '',
930
+ (value?.tabs || []).map(tab => [tab.ref, tab.title, tab.url, tab.browser, tab.authorized]),
931
+ value?.access ? [value.access.enabled, value.access.profile, value.access.windowId] : null,
932
+ ])
933
+
934
+ async function poll (sessionId) {
935
+ if (busy || !listeners.size) return
936
+ const current = controller
937
+ busy = true
938
+ let next = ''
939
+ try {
940
+ next = signature(await browserApi('/list' + queryString({ session: sessionId }), { signal: current?.signal }))
941
+ } catch { next = 'unavailable' } finally { busy = false }
942
+ if (!current || current.signal.aborted || next === snapshot) return
943
+ snapshot = next
944
+ for (const listener of [...listeners]) { try { listener() } catch { /* one listener must not stop the rest */ } }
945
+ }
946
+
947
+ function watch (sessionId, listener, signal) {
948
+ if (signal?.aborted) return () => {}
949
+ const notify = () => listener()
950
+ listeners.add(notify)
951
+ const refresh = () => { void poll(sessionId) }
952
+ const stop = () => {
953
+ try { signal?.removeEventListener?.('abort', stop) } catch { /* already gone */ }
954
+ if (!listeners.delete(notify)) return
955
+ if (listeners.size) return
956
+ clearInterval(timer); timer = null
957
+ controller?.abort(); controller = null
958
+ globalThis.window?.removeEventListener?.('focus', refresh)
959
+ }
960
+ try { signal?.addEventListener?.('abort', stop, { once: true }) } catch { /* a plain object signal in tests */ }
961
+ // Start observing, not fetching: see the note above.
962
+ if (listeners.size === 1) {
963
+ controller = new AbortController()
964
+ timer = setInterval(refresh, intervalMs)
965
+ globalThis.window?.addEventListener?.('focus', refresh)
966
+ }
967
+ return stop
968
+ }
969
+
970
+ return { watch }
971
+ }
972
+
973
+ async function openSetupPage () {
974
+ const value = await browserApi('/setup', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' })
975
+ if (value?.url) globalThis.window?.open?.(value.url, '_blank', 'noopener')
976
+ }
977
+
978
+ /**
979
+ * The two @ sources.
980
+ *
981
+ * A browser @ search reads ONLY the browser route: enumerating desktop windows for every
982
+ * keystroke would be both slow and beside the point. The application source asks its own route.
983
+ * Both decline a quoted path, a drilled hit and a category query — those belong to the native file
984
+ * source, which owns quoting and navigation.
985
+ */
986
+ function registerReferenceSources (scope, feed) {
987
+ const invalidations = new Set()
988
+ const lexicon = () => []
989
+ const subscribeLexicon = (_session, listener) => { invalidations.add(listener); return () => { invalidations.delete(listener) } }
990
+ const repoll = () => { for (const listener of [...invalidations]) { try { listener() } catch { /* the controller owns its failures */ } } }
991
+ const decline = request => Boolean(request?.quoted || request?.drilled || referenceQuery(request?.query || ''))
992
+ const setupRow = description => ({ name: UI.setup, label: UI.setup, description, icon: 'file', section: UI.pages, value: 'setup' })
993
+ /**
994
+ * WHICH CONVERSATION A REFERENCE BELONGS TO.
995
+ *
996
+ * The real codec is `serialize(ref, signal)` — the host passes NO session (see
997
+ * `ReferenceCodec` in dsh-client-ui-input-trigger). The conversation therefore travels inside the
998
+ * CHIP's own ref (`appChipRef`): each draft carries its own binding, two drafts can hold the same
999
+ * window at once, and a reload restores it because the ref is persisted with the draft. Nothing
1000
+ * here is kept in process memory any more, which is what the old `Map` got wrong.
1001
+ *
1002
+ * It is a BINDING, not an authorization: the host re-verifies the pick AND the process on every
1003
+ * resolve, so a wrong or stale carrier can only ever cause a refusal.
1004
+ */
1005
+ // The session whose candidate list is currently on screen. Used only as the FALLBACK for a
1006
+ // legacy bare-appRef carrier that predates `appChipRef`; a session-bearing carrier never needs it.
1007
+ let currentSession = null
1008
+
1009
+ async function pageCandidates (sessionId, request) {
1010
+ if (decline(request)) return []
1011
+ if (request?.signal) feed.watch(sessionId, repoll, request.signal)
1012
+ let value
1013
+ try {
1014
+ value = await browserApi('/list' + queryString({ session: sessionId, q: request?.query || '' }), { signal: request?.signal })
1015
+ } catch (error) {
1016
+ if (request?.signal?.aborted) return []
1017
+ return [setupRow(String(error?.message ?? error))]
1018
+ }
1019
+ if (value?.connected === false) return [setupRow(value.error ? String(value.error) : UI.disconnected)]
1020
+ const rows = (value?.tabs || []).map(pageRow)
1021
+ if (!rows.length && !request?.query) return [setupRow(UI.emptyPages)]
1022
+ return rows
1023
+ }
1024
+
1025
+ async function appCandidates (sessionId, request) {
1026
+ if (decline(request)) return []
1027
+ // NOTE: no page feed here. An application search must reach ONLY its own route — watching
1028
+ // the browser inventory here would put a `/browser/list` behind every application keystroke.
1029
+ if (sessionId) currentSession = sessionId
1030
+ let value
1031
+ try {
1032
+ value = await referencesApi('/apps' + queryString({ session: sessionId, q: request?.query || '' }), { signal: request?.signal })
1033
+ } catch (error) {
1034
+ if (request?.signal?.aborted) return []
1035
+ return []
1036
+ }
1037
+ if (value?.unavailable) return []
1038
+ return (value?.apps || []).map(appRow)
1039
+ }
1040
+
1041
+ /**
1042
+ * The owner of one chip ref, and the app ref it names.
1043
+ *
1044
+ * A session-bearing carrier answers its own session; a legacy bare mention has none, so the
1045
+ * session whose list is on screen is used and the host still decides. This is the ONLY place the
1046
+ * two are combined, so both entry points (`@` and the sidebar) behave identically.
1047
+ */
1048
+ const ownerOfChip = ref => {
1049
+ const split = splitAppChipRef(ref)
1050
+ if (!split) return null
1051
+ return { sessionId: split.sessionId || currentSession, appRef: split.appRef, label: split.label }
1052
+ }
1053
+
1054
+ scope.effect(() => scope.inputTriggers.registerSource({
1055
+ trigger: '@', name: PAGE_SOURCE, showGroupTitle: false, lexicon, subscribeLexicon,
1056
+ candidates: (session, request) => pageCandidates(session?.sessionId, request),
1057
+ onPick (pick) {
1058
+ if (pick?.candidate?.value === 'setup') {
1059
+ void openSetupPage().catch(error => console.warn('dsh-computer-use: setup page unavailable', error))
1060
+ return { text: '' }
1061
+ }
1062
+ const value = referenceValue(pick?.candidate)
1063
+ if (value.kind !== 'page' || !value.ref) return { text: '' }
1064
+ return {
1065
+ insert: {
1066
+ source: PAGE_SOURCE, ref: value.ref, label: value.label, appearance: 'file',
1067
+ clipboardText: `@[${mentionLabel(value.label, '网页')}](${value.ref})`,
1068
+ },
1069
+ }
1070
+ },
1071
+ // Clicking the chip reveals the page in the human's browser. That is a navigation in THEIR
1072
+ // browser, never an automation act, and the browser route refuses a tab this conversation
1073
+ // never authorized.
1074
+ openReference (session, reference) {
1075
+ const ref = String(reference?.ref || '')
1076
+ if (!PAGE_REF.test(ref)) return false
1077
+ void browserApi('/focus', {
1078
+ method: 'POST', headers: { 'content-type': 'application/json' },
1079
+ body: JSON.stringify({ ref, session: session?.sessionId }),
1080
+ }).catch(error => console.warn('dsh-computer-use: browser focus failed', error))
1081
+ return true
1082
+ },
1083
+ codec: { clipboardText: ref => ref, serialize: async ref => ref },
1084
+ }))
1085
+
1086
+ /**
1087
+ * Serialize ONE application reference at SEND time.
1088
+ *
1089
+ * The chip was inserted when the window was picked; by the time the message is sent the process
1090
+ * may have exited or been replaced. Re-checking here is the difference between a model reading a
1091
+ * verified window and a model being handed a stale HWND, so a refusal THROWS: the composer keeps
1092
+ * the draft and shows the reason instead of sending a dead handle.
1093
+ *
1094
+ * The session comes from the CHIP's own ref, so the host can answer "did THIS conversation pick
1095
+ * it": an unverified mention pasted from elsewhere must not smuggle a window handle into the
1096
+ * model. A pick report still in flight is awaited first, so "pick, then press Enter" cannot be
1097
+ * refused for a race.
1098
+ */
1099
+ async function serializeAppReference (chipRef) {
1100
+ const owner = ownerOfChip(chipRef)
1101
+ if (!owner) throw new Error('应用引用格式无效;请重新用 @ 选择正在运行的应用')
1102
+ const { sessionId, appRef } = owner
1103
+ if (!sessionId) throw new Error('这个应用引用没有所属会话;请在聊天里重新用 @ 选择应用')
1104
+ await settlePick(sessionId, appRef)
1105
+ let answer
1106
+ try {
1107
+ answer = await referencesApi('/apps/resolve', {
1108
+ method: 'POST', headers: { 'content-type': 'application/json' },
1109
+ body: JSON.stringify({ session: sessionId, ref: appRef }),
1110
+ })
1111
+ } catch (error) {
1112
+ throw new Error(`无法核验应用引用:${error?.message ?? error}。请重新用 @ 选择应用`)
1113
+ }
1114
+ if (!answer?.ok) throw new Error(`${answer?.message || '应用窗口已不可用'}(${answer?.code || 'APP_RESOLVE_FAILED'})`)
1115
+ // The verified context IS the send payload: it names the window (hwnd/pid/start time) the
1116
+ // model may act on. A host answer without it means the verification did not actually run, so
1117
+ // sending the bare mention would hand the model an UNVERIFIED handle — refuse instead.
1118
+ const context = typeof answer.context === 'string' ? answer.context.trim() : ''
1119
+ if (!context) throw new Error('应用窗口核验没有返回可用的目标信息(APP_RESOLVE_INCOMPLETE);请重新用 @ 选择应用')
1120
+ return context
1121
+ }
1122
+
1123
+ scope.effect(() => scope.inputTriggers.registerSource({
1124
+ trigger: '@', name: APP_SOURCE, showGroupTitle: false, lexicon, subscribeLexicon,
1125
+ candidates: (session, request) => appCandidates(session?.sessionId, request),
1126
+ onPick (pick) {
1127
+ const value = referenceValue(pick?.candidate)
1128
+ if (value.kind !== 'app' || !APP_REF.test(String(value.ref || ''))) return { text: '' }
1129
+ // The conversation that actually picked it — carried ON the chip from here on, because
1130
+ // `serialize(ref, signal)` gets no session later.
1131
+ const pickSession = pick?.session?.sessionId ?? currentSession
1132
+ if (pickSession) void reportPick(pickSession, value.ref)
1133
+ return { insert: appReference({ ...value }, pickSession) }
1134
+ },
1135
+ // An application reference is a POINTER, not a command: clicking its chip must not pull a
1136
+ // window to the front. Answering false leaves the editor gesture exactly as it was.
1137
+ openReference () { return false },
1138
+ codec: {
1139
+ // Copy/cut put the PLAIN mention back, never the session-bearing carrier: the carrier is an
1140
+ // internal binding, and a pasted mention is re-verified by the host like any other.
1141
+ clipboardText: ref => {
1142
+ const owner = ownerOfChip(ref)
1143
+ return owner ? `@[${mentionLabel(owner.label, '应用')}](${owner.appRef})` : String(ref ?? '')
1144
+ },
1145
+ // Resolution happens HERE, at send, against the live inventory.
1146
+ serialize: async (ref, _signal) => serializeAppReference(ref),
1147
+ },
1148
+ }))
1149
+ }
1150
+
1151
+ // ---- the sidebar tab ------------------------------------------------------------------------
1152
+ const STYLES = `
1153
+ .cu-ref{--cu-ink:var(--dsw-alias-label-primary,#242424);--cu-muted:var(--dsw-alias-label-secondary,#666);--cu-ground:var(--dsw-alias-bg-base,#fff);--cu-hover:var(--dsw-alias-interactive-bg-hover,#f3f3f3);--cu-line:var(--dsw-alias-border-l3,#e5e5e5);--cu-focus:var(--dsw-focus-ring-color,#06c);--cu-radius:8px;box-sizing:border-box;height:100%;min-width:0;overflow:auto;padding:12px 16px;color:var(--cu-ink);background:var(--cu-ground);font-size:14px;line-height:1.5;container-type:inline-size}
1154
+ .cu-ref *{box-sizing:border-box}.cu-ref header,.cu-ref .cu-head,.cu-ref .cu-tabs,.cu-ref .cu-tools{display:flex;align-items:center;gap:8px}
1155
+ .cu-ref header{justify-content:space-between;flex-wrap:wrap;margin-bottom:8px}.cu-ref h2{margin:0;font-size:18px;font-weight:600}
1156
+ .cu-ref button,.cu-ref input,.cu-ref select{font:inherit;color:inherit;border:1px solid var(--cu-line);border-radius:var(--cu-radius);background:transparent;padding:5px 8px;min-height:32px}
1157
+ .cu-ref button{cursor:pointer;display:inline-flex;align-items:center;justify-content:center;gap:6px}
1158
+ .cu-ref button:hover{background:var(--cu-hover)}.cu-ref button:disabled{cursor:default;opacity:.5}
1159
+ .cu-ref :is(button,input,select):focus-visible{outline:2px solid var(--cu-focus);outline-offset:1px}
1160
+ .cu-ref .cu-icon{width:32px;padding:0;border-color:transparent}
1161
+ .cu-ref .cu-tabs{gap:16px;border-bottom:1px solid var(--cu-line);margin-bottom:8px}
1162
+ .cu-ref .cu-tabs button{border:0;border-radius:0;background:none;color:var(--cu-muted);padding:0 0 4px;min-height:32px}
1163
+ .cu-ref .cu-tabs button[aria-selected=true]{color:var(--cu-ink);font-weight:600}
1164
+ .cu-ref .cu-search{margin-bottom:8px}.cu-ref .cu-search input{width:100%;min-height:34px;background:var(--cu-hover);border-color:transparent}
1165
+ .cu-ref .cu-access{padding:8px 0 12px;display:grid;gap:6px}.cu-ref .cu-access select{width:100%;min-height:32px;background:var(--cu-ground);text-overflow:ellipsis}
1166
+ .cu-ref .cu-muted{color:var(--cu-muted);font-size:12px}.cu-ref p{margin:4px 0}
1167
+ .cu-ref ul{list-style:none;padding:0;margin:0}.cu-ref li+li{border-top:1px solid var(--cu-line)}
1168
+ .cu-ref .cu-object{display:flex;align-items:center;gap:8px;width:100%;min-height:48px;text-align:left;border:0;padding:4px 6px;justify-content:flex-start}
1169
+ .cu-ref .cu-object>span{min-width:0;flex:1;display:block}.cu-ref .cu-object strong,.cu-ref .cu-object small{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1170
+ .cu-ref .cu-object strong{font-weight:500}
1171
+ .cu-ref .cu-empty{margin-top:8px;padding:12px;background:var(--cu-hover);border-radius:var(--cu-radius)}
1172
+ .cu-ref .cu-empty strong{display:block;font-weight:500}
1173
+ .cu-ref label.cu-check{display:flex;align-items:center;gap:7px}.cu-ref input[type=checkbox]{min-height:0;accent-color:var(--cu-ink)}
1174
+ .cu-ref .cu-status{margin:0 0 8px;overflow-wrap:anywhere}
1175
+ `
1176
+
1177
+ /**
1178
+ * The sidebar row glyph: a solid pointer that leans from its tip at the upper left down to the
1179
+ * lower right, with four short click rays around the tip.
1180
+ *
1181
+ * THE SIZE MUST BE A NUMBER, NEVER A PERCENTAGE. Measured on the first real 3.1.0 install
1182
+ * (DSH Desktop 0.2.2-rc.5): `width:"100%" height:"100%"` rendered a ~270×270 pointer between
1183
+ * Automation tasks and Markdown and pushed the "浏览器" label out of the visible row. The cause is
1184
+ * that `100%` resolves against the parent, and the host's leading cell does not give this element
1185
+ * a definite width — so the SVG fell back to an unresolvable percentage and laid itself out at the
1186
+ * largest size its own aspect box allowed. No parent constraint may be assumed here.
1187
+ *
1188
+ * So the glyph is 16 CSS px square — the same as the neighbouring panel icons and the host's own
1189
+ * 16px leading cell — with `flex: none` and fixed `style` dimensions so a flex row cannot stretch
1190
+ * it either. A host that passes a `size` (16 or 18) is honoured; anything else falls back to 16.
1191
+ * Colour stays `currentColor`, so normal/hover/selected all still come from the row.
1192
+ *
1193
+ * `aria-hidden` because the row already supplies the accessible name from its `label`; a second
1194
+ * naming node would make screen readers announce the row twice. This element deliberately renders
1195
+ * NO text: the visible label belongs to the host, which is what keeps the row's left layout and
1196
+ * its unpin button in place.
1197
+ */
1198
+ function BrowserPanelIcon (props) {
1199
+ const requested = Number(props && props.size)
1200
+ const size = requested === 18 || requested === 16 ? requested : 16
1201
+ return h('svg', {
1202
+ viewBox: '0 0 16 16', width: size, height: size,
1203
+ // Explicit, non-shrinking box: a percentage here is what produced the giant pointer, and a
1204
+ // bare width/height attribute alone can still be stretched by a flex parent.
1205
+ style: { width: `${size}px`, height: `${size}px`, flex: 'none', display: 'block' },
1206
+ fill: 'none', stroke: 'currentColor', strokeWidth: 1.5,
1207
+ strokeLinecap: 'round', strokeLinejoin: 'round',
1208
+ 'aria-hidden': 'true', focusable: 'false', 'data-cu-glyph': 'browser',
1209
+ },
1210
+ // The solid pointer: the TIP is the upper-left vertex, and the body opens toward the lower
1211
+ // right — the silhouette of the macOS Computer Use mark, not a symmetric cursor glyph.
1212
+ h('path', { d: 'M5.6 4.3 L5.6 13.4 L8.1 10.9 L9.9 13.7 L11.7 12.6 L9.95 9.95 L13.4 9.95 Z', fill: 'currentColor', stroke: 'currentColor', strokeWidth: 1 }),
1213
+ // The four click rays around the tip, each short and clear of the arrow so both read at 16px.
1214
+ h('path', { d: 'M4.5 2.9 L4.5 0.9' }),
1215
+ h('path', { d: 'M2.6 4.4 L1.2 3.0' }),
1216
+ h('path', { d: 'M7.6 2.7 L8.2 1.1' }),
1217
+ h('path', { d: 'M2.4 6.4 L0.8 6.6' }))
1218
+ }
1219
+
1220
+ function BrowserPanel ({ sessionId, conversation }) {
1221
+ const feed = useRef(null)
1222
+ if (!feed.current) feed.current = createPageFeed()
1223
+ const [view, setView] = useState('pages')
1224
+ const [query, setQuery] = useState('')
1225
+ const [search, setSearch] = useState('')
1226
+ const [pages, setPages] = useState(null)
1227
+ const [apps, setApps] = useState(null)
1228
+ const [access, setAccess] = useState(null)
1229
+ // Which conversation the `access` value describes. A state read for conversation A must never be
1230
+ // painted onto conversation B, so the picker says "unknown" until its own read lands.
1231
+ const [accessSession, setAccessSession] = useState(null)
1232
+ const [busy, setBusy] = useState(true)
1233
+ const [error, setError] = useState('')
1234
+ const [notice, setNotice] = useState('')
1235
+ const [revision, setRevision] = useState(0)
1236
+ const [saving, setSaving] = useState(false)
1237
+
1238
+ useEffect(() => {
1239
+ const timer = setTimeout(() => setSearch(query.trim()), 200)
1240
+ return () => clearTimeout(timer)
1241
+ }, [query])
1242
+
1243
+ // One effect per (view, query): a browser list never enumerates desktop windows, and the
1244
+ // application list never touches the bridge.
1245
+ //
1246
+ // THE TWO ROUTES CARRY DIFFERENT THINGS, and mixing them is what left the window picker empty:
1247
+ // * `GET /browser/list` → `{connected, tabs, windows}` — the TABS and the WINDOW INVENTORY.
1248
+ // It does NOT carry the conversation's access state (there is no `access` field).
1249
+ // * `GET /browser/access` → `{enabled, profile?, windowId?, windows, refs}` — the conversation's
1250
+ // AUTHORIZATION. Separate because it is per-conversation state, not an inventory.
1251
+ // So the picker takes its candidates from the list, and its selected value from the access
1252
+ // state; the authorization itself is refreshed on its own cadence (see the effect below).
1253
+ useEffect(() => {
1254
+ if (!sessionId) { setBusy(false); return undefined }
1255
+ const controller = new AbortController()
1256
+ let alive = true
1257
+ setBusy(true)
1258
+ setError('')
1259
+ const load = async () => {
1260
+ try {
1261
+ if (view === 'pages') {
1262
+ const value = await browserApi('/list' + queryString({ session: sessionId, q: search }), { signal: controller.signal })
1263
+ if (!alive) return
1264
+ setPages(value)
1265
+ } else {
1266
+ const value = await referencesApi('/apps' + queryString({ session: sessionId, q: search }), { signal: controller.signal })
1267
+ if (!alive) return
1268
+ setApps(value)
1269
+ }
1270
+ setBusy(false)
1271
+ } catch (failure) {
1272
+ if (!alive || controller.signal.aborted) return
1273
+ setBusy(false)
1274
+ setError(String(failure?.message ?? failure))
1275
+ }
1276
+ }
1277
+ void load()
1278
+ const stop = view === 'pages' ? feed.current.watch(sessionId, () => setRevision(value => value + 1), controller.signal) : () => {}
1279
+ return () => { alive = false; stop(); controller.abort() }
1280
+ }, [sessionId, view, search, revision])
1281
+
1282
+ // The authorization is read ONCE per conversation (and again after a write), never on every
1283
+ // list refresh: it only changes when the human flips the switch, and the POST answer carries the
1284
+ // new state inline. That keeps a polling panel from doubling its requests.
1285
+ useEffect(() => {
1286
+ if (!sessionId) { setAccess(null); setAccessSession(null); return undefined }
1287
+ const controller = new AbortController()
1288
+ let alive = true
1289
+ const load = async () => {
1290
+ try {
1291
+ const value = await browserApi('/access' + queryString({ session: sessionId }), { signal: controller.signal })
1292
+ if (!alive) return
1293
+ setAccess(value)
1294
+ setAccessSession(sessionId)
1295
+ } catch (failure) {
1296
+ if (!alive || controller.signal.aborted) return
1297
+ // A refused/unavailable access read is NOT "enabled": show the picker, disabled.
1298
+ setAccess(null)
1299
+ setError(String(failure?.message ?? failure))
1300
+ }
1301
+ }
1302
+ void load()
1303
+ return () => { alive = false; controller.abort() }
1304
+ }, [sessionId, revision])
1305
+
1306
+ const add = useCallback((reference, label) => {
1307
+ const ok = insertDraftReference(conversation, sessionId, reference)
1308
+ setNotice(ok ? `${UI.added} · ${label}` : UI.noSession)
1309
+ }, [conversation, sessionId])
1310
+
1311
+ const saveAccess = useCallback(async (enabled, window) => {
1312
+ if (!sessionId) return
1313
+ setSaving(true)
1314
+ setError('')
1315
+ try {
1316
+ const body = { session: sessionId, enabled, ...(window ? { profile: window.profile, windowId: window.windowId } : {}) }
1317
+ // The POST answer IS the new state (the browser host returns the same shape as GET /access),
1318
+ // so it is adopted directly: a refresh request here would be a second round trip for a value
1319
+ // we just received, and it would race the switch the human just flipped.
1320
+ setAccess(await browserApi('/access', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }))
1321
+ setAccessSession(sessionId)
1322
+ setNotice(enabled ? '' : UI.revoked)
1323
+ } catch (failure) { setError(String(failure?.message ?? failure)) } finally { setSaving(false) }
1324
+ }, [sessionId])
1325
+
1326
+ // The WINDOW INVENTORY comes from `list` (top-level `windows`); the SELECTED window and the
1327
+ // switch come from `access`. A GET /access answer also carries `windows`, so it is used as a
1328
+ // fallback when the list has not arrived yet — either source is the real protocol, and neither
1329
+ // is invented here.
1330
+ const windows = (() => {
1331
+ const fromList = Array.isArray(pages?.windows) ? pages.windows : []
1332
+ if (fromList.length) return fromList
1333
+ return Array.isArray(access?.windows) ? access.windows : []
1334
+ })()
1335
+ const windowKey = window => `${window.profile}/${window.windowId}`
1336
+ // The picker only shows a SELECTION the host would accept: a remembered window that is no longer
1337
+ // offered is not a selection (`setAccess` refuses it), so it is reported as "no window".
1338
+ const selectedKey = access?.profile === undefined ? '' : windowKey(access)
1339
+ const selected = windows.some(window => windowKey(window) === selectedKey) ? selectedKey : ''
1340
+ const accessLoaded = accessSession === sessionId
1341
+ const items = view === 'pages' ? (pages?.tabs || []) : (apps?.apps || [])
1342
+ const unavailable = view === 'pages' ? (pages?.error || pages?.unavailable) : apps?.unavailable
1343
+
1344
+ const title = item => view === 'pages' ? (item.title || item.url) : (item.label || item.name)
1345
+ const subtitle = item => view === 'pages'
1346
+ ? [hostOf(item.url), item.browser,
1347
+ item.authorized === true ? UI.authorized : item.authorized === false ? UI.unauthorized : UI.authUnknown,
1348
+ item.sleeping ? UI.sleeping : ''].filter(Boolean).join(' · ')
1349
+ : [item.process || '', item.identityStrength === 'weak' ? UI.weakIdentity : ''].filter(Boolean).join(' · ')
1350
+
1351
+ // Rows are built in their own pass: one element per object, each with one add control.
1352
+ //
1353
+ // THE SIDEBAR IS THE SECOND PICK ENTRY POINT, so it goes through the SAME carrier: an application
1354
+ // row builds `appReference(item, sessionId)` (the chip ref carries this conversation) and reports
1355
+ // the pick, exactly as the `@` source does. Letting the sidebar insert a bare appRef was the other
1356
+ // half of the "same window in two drafts" bug.
1357
+ const rows = items.map((item, index) => {
1358
+ const label = title(item)
1359
+ const detail = subtitle(item)
1360
+ const reference = view === 'pages' ? pageReference(item) : appReference(item, sessionId)
1361
+ const insert = () => {
1362
+ if (view !== 'pages') void reportPick(sessionId, item.ref)
1363
+ add(reference, label)
1364
+ }
1365
+ return h('li', { key: item.ref || index },
1366
+ h('button', {
1367
+ className: 'cu-object',
1368
+ title: `${label}\n${detail}\n${UI.add}`,
1369
+ disabled: !sessionId,
1370
+ onClick: insert,
1371
+ },
1372
+ h('span', null, h('strong', null, label), h('small', null, detail)),
1373
+ '+'))
1374
+ })
1375
+
1376
+ return h('section', { className: 'cu-ref', 'aria-label': UI.nav },
1377
+ h('header', null,
1378
+ h('div', { className: 'cu-head' }, h('h2', null, UI.nav)),
1379
+ h('div', { className: 'cu-tools' },
1380
+ h('button', {
1381
+ className: 'cu-icon', title: UI.refresh, 'aria-label': UI.refresh, disabled: busy,
1382
+ onClick: () => setRevision(value => value + 1),
1383
+ }, '↻'))),
1384
+ h('div', { className: 'cu-tabs', role: 'tablist', 'aria-label': '引用内容' },
1385
+ ...['pages', 'apps'].map(key => h('button', {
1386
+ key, role: 'tab', 'aria-selected': view === key, tabIndex: view === key ? 0 : -1,
1387
+ onClick: () => { setView(key); setQuery('') },
1388
+ }, key === 'pages' ? UI.pages : UI.apps))),
1389
+ view === 'pages' && sessionId ? h('div', { className: 'cu-access' },
1390
+ h('label', null,
1391
+ h('span', { className: 'cu-muted' }, UI.window),
1392
+ h('select', {
1393
+ value: selected, disabled: saving || !windows.length,
1394
+ onChange: event => {
1395
+ const window = windows.find(item => windowKey(item) === event.target.value)
1396
+ // Choosing a window is an explicit human act: it enables access for THAT window. The
1397
+ // checkbox alone never guesses one.
1398
+ if (window) void saveAccess(true, window)
1399
+ },
1400
+ },
1401
+ h('option', { value: '' }, !accessLoaded ? UI.windowUnknown : (windows.length ? UI.pickWindow : UI.noWindow)),
1402
+ ...windows.map(window => h('option', { key: windowKey(window), value: windowKey(window) },
1403
+ `${window.browser || '浏览器'} · ${window.profileLabel || window.profile} · ${window.activeTitle || `${window.tabCount || 0} 个可用网页`} · 窗口 ${window.windowId}`)))),
1404
+ h('label', { className: 'cu-check' },
1405
+ h('input', {
1406
+ type: 'checkbox', checked: access?.enabled === true, disabled: saving || !selected,
1407
+ onChange: event => {
1408
+ // Turning the switch ON requires a selected window (the human's explicit choice);
1409
+ // turning it OFF always works and drops the scope.
1410
+ if (event.target.checked) {
1411
+ const window = windows.find(item => windowKey(item) === selected)
1412
+ if (window) void saveAccess(true, window)
1413
+ return
1414
+ }
1415
+ void saveAccess(false, access)
1416
+ },
1417
+ }), UI.allow),
1418
+ h('p', { className: 'cu-muted' }, UI.allowHint),
1419
+ access?.enabled === true
1420
+ ? h('div', null, h('button', { disabled: saving, onClick: () => void saveAccess(false, access) }, UI.revoke))
1421
+ : null)
1422
+ : null,
1423
+ h('div', { className: 'cu-search' },
1424
+ h('input', {
1425
+ type: 'search', 'aria-label': UI.search, placeholder: UI.search, value: query,
1426
+ onChange: event => setQuery(event.target.value),
1427
+ })),
1428
+ h('p', { className: 'cu-muted cu-status', role: 'status' },
1429
+ busy ? UI.loading : (error || notice || (!sessionId ? UI.noSession : ''))),
1430
+ view === 'pages' && pages && pages.connected === false
1431
+ ? h('p', { className: 'cu-muted' }, pages.error ? String(pages.error) : UI.disconnected)
1432
+ : null,
1433
+ h('ul', null, ...rows),
1434
+ !busy && !items.length
1435
+ ? h('div', { className: 'cu-empty' },
1436
+ h('strong', null, unavailable
1437
+ ? (view === 'pages' ? UI.noService : UI.appsUnavailable)
1438
+ : (search ? UI.emptySearch : (view === 'pages' ? UI.emptyPages : UI.emptyApps))),
1439
+ h('p', null, view === 'pages' ? UI.emptyPagesHint : UI.emptyAppsHint),
1440
+ view === 'pages'
1441
+ ? h('button', { onClick: () => void openSetupPage().catch(failure => setError(String(failure?.message ?? failure))) }, UI.setup)
1442
+ : null)
1443
+ : null,
1444
+ h('p', { className: 'cu-muted' }, view === 'pages' ? UI.focusHint : UI.appsHint))
1445
+ }
1446
+
1447
+ // ============================================================================================
1448
+ // apply
1449
+ // ============================================================================================
115
1450
  function apply (ctx) {
1451
+ // ---- THE OFFICIAL PIN SEAM: our null-rendering `sidebar.panellist.actions` occupant ----
1452
+ //
1453
+ // The host passes `{ entries, onOpen, onPinnedChange, onDismiss }` to every registration of that
1454
+ // slot. Registering an occupant that returns null adds NO menu row and NO button; it exists only
1455
+ // so this plugin can hold the real callbacks. `captured` is the single handoff point the pin
1456
+ // logic reads, and it goes back to null whenever the host unmounts the menu.
1457
+ const slotHandoff = { api: null }
1458
+ const PANEL_ID = 'computer-use-browser'
1459
+ function PinBridge (props) {
1460
+ // The props ARE the API: `{ entries, onOpen, onPinnedChange, onDismiss }`. Nothing is
1461
+ // rendered, so this occupant cannot duplicate a menu entry or add a button.
1462
+ const api = props && typeof props === 'object' ? props : null
1463
+ slotHandoff.api = api
1464
+ useEffect(() => () => {
1465
+ // The menu closed: those callbacks belong to that mounted menu, so stop handing them out.
1466
+ if (slotHandoff.api === api) slotHandoff.api = null
1467
+ }, [])
1468
+ return null
1469
+ }
1470
+
1471
+ // The sidebar row's pinned state, shared with the settings page.
1472
+ //
1473
+ // THE HOST HAS NO STANDALONE PIN SERVICE: the pinned set is private sidebar state whose only
1474
+ // public access is the callbacks above. Presence is read with ONE scoped query inside the
1475
+ // sidebar's navigation landmark (never the whole page), and every write goes through the
1476
+ // captured `onPinnedChange` — so a cancelled row needs no icon to come back.
1477
+ let restoreFocusTarget = null
1478
+ const panelPin = createPanelPin({
1479
+ entryId: PANEL_ID,
1480
+ slotApi: { current: () => slotHandoff.api },
1481
+ root: () => (typeof document === 'undefined' ? null : document),
1482
+ subscribeRoot: notify => {
1483
+ if (typeof MutationObserver !== 'function' || typeof document === 'undefined' || !document.body) return () => {}
1484
+ const observer = new MutationObserver(() => notify())
1485
+ observer.observe(document.body, { childList: true, subtree: true, attributes: true,
1486
+ attributeFilter: ['aria-label', 'title', 'data-tooltip', 'aria-hidden', 'role', 'aria-modal'] })
1487
+ return () => { try { observer.disconnect() } catch { /* already gone */ } }
1488
+ },
1489
+ // Open the native More menu exactly as a human does, remembering where focus was. This is the
1490
+ // ONLY way to obtain `onPinnedChange` while our row is cancelled — and the row being cancelled
1491
+ // is precisely the state we must be able to leave.
1492
+ openMenu: async () => {
1493
+ if (typeof document === 'undefined' || !document.body) return false
1494
+ const previous = typeof document.activeElement === 'object' ? document.activeElement : null
1495
+ const trigger = findMoreControl(document)
1496
+ if (!trigger) return false
1497
+ restoreFocusTarget = () => { try { previous?.focus?.() } catch { /* gone */ } }
1498
+ try {
1499
+ if (typeof trigger.click === 'function') trigger.click()
1500
+ else return false
1501
+ } catch { return false }
1502
+ return true
1503
+ },
1504
+ // Close only what this module opened, through the host's own dismiss when we have it.
1505
+ closeMenu: () => {
1506
+ const api = slotHandoff.api
1507
+ try { api?.onDismiss?.() } catch { /* the host may already be closing */ }
1508
+ },
1509
+ restoreFocus: () => { try { restoreFocusTarget?.() } catch { /* gone */ } },
1510
+ })
1511
+ // The observer is a plugin-scoped resource: unloading must stop watching the document.
1512
+ if (typeof ctx.effect === 'function') ctx.effect(() => () => { try { panelPin.dispose() } catch { /* already gone */ } })
1513
+
1514
+ // Registered through `inject` so the occupant follows the slot's own lifetime. It renders null.
1515
+ ctx.slots.inject('sidebar.panellist.actions', () => ctx.slots.register({
1516
+ name: 'sidebar.panellist.actions', id: 'computer-use-browser-pin',
1517
+ }, PinBridge))
1518
+
1519
+ // ---- settings page: gate 2 of the host-driving debug switch ----
116
1520
  ctx.slots.inject('settings.section', () => ctx.slots.register({
117
1521
  name: 'settings.section',
118
1522
  id: 'computer-use-debug',
119
1523
  order: 52,
120
1524
  label: () => TEXT.nav,
121
1525
  locale: 'settings.computerUseDebug',
122
- }, () => h(SettingsPage)))
1526
+ }, () => h(SettingsPage, { current: ctx.get('uiSession')?.adapter?.current, panelPin })))
1527
+
1528
+ // ---- @ 网页 / @ 应用, and the native file/folder/conversation grouping ----
1529
+ // `inject` waits for the trigger pipeline: a profile that does not mount it keeps the settings
1530
+ // page working and gets no reference sources, which is the honest degradation.
1531
+ ctx.inject(['inputTriggers'], scope => {
1532
+ scope.effect(() => installReferenceGroups(scope.inputTriggers))
1533
+ registerReferenceSources(scope, createPageFeed())
1534
+ })
1535
+
1536
+ // ---- the native Browser sidebar tab ----
1537
+ // `sessions` and `layout` are OPTIONAL here: the tab and its body work without them, and the
1538
+ // launcher hand-over degrades to a plain "no conversation" notice. Requiring all five would
1539
+ // make the whole surface disappear on a host that renames either one.
1540
+ ctx.inject(['slots', 'sidebarRight', 'sidebarRightTabs'], scope => {
1541
+ const style = document.createElement('style')
1542
+ style.setAttribute('data-plugin', 'dsh-codex-style-computer-use')
1543
+ style.textContent = STYLES
1544
+ document.head.appendChild(style)
1545
+ scope.effect(() => () => style.remove())
1546
+
1547
+ scope.effect(() => scope.sidebarRightTabs.register({
1548
+ id: PANEL_TAB, kind: PANEL_TAB, priority: 'extension', title: () => UI.nav,
1549
+ }))
1550
+
1551
+ scope.slots.inject('sidebar.right.pane.tab', () => scope.slots.register({
1552
+ name: 'sidebar.right.pane.tab',
1553
+ key: PANEL_TAB,
1554
+ inject: sessionId => ({ sessionId, conversation: scope.get('conversation') }),
1555
+ }, BrowserPanel))
1556
+
1557
+ scope.slots.inject('sidebar.right.pane.tab.title', () => scope.slots.register({
1558
+ name: 'sidebar.right.pane.tab.title', key: PANEL_TAB,
1559
+ }, () => h('span', null, UI.nav)))
1560
+
1561
+ // THE MAIN SEAT AND THE PANEL LIST GO TOGETHER. `sidebar.panellist` is a global navigation
1562
+ // row: the Sidebar calls `ctx.layout.selectPanel(id)`, and that throws
1563
+ // `main panel "<id>" is not registered` — rendering nothing at all — unless the SAME key is
1564
+ // registered in the root-scoped `main` slot. So the row and this launcher are one unit.
1565
+ //
1566
+ // HOW THE HAND-OVER WORKS, AND WHY THE FRAME IS NOT CANCELLED ON UNMOUNT
1567
+ // The Browser panel belongs to a Session (it reads that Session's window authorization), so the
1568
+ // main column is the wrong home for it: selecting the row deselects the global panel, which
1569
+ // UNMOUNTS this component, and then the right Sidebar only exists once the Conversation is back
1570
+ // on screen. Opening the tab must therefore survive this component's own unmount — cancelling
1571
+ // the frame in the effect cleanup (the obvious React reflex) cancels the very open that makes
1572
+ // the click do anything, which is exactly the measured "click does nothing" bug. The frame is
1573
+ // owned by the PLUGIN scope instead and cancelled only when the plugin unloads.
1574
+ const pendingFrames = new Set()
1575
+ scope.effect(() => () => {
1576
+ for (const frame of pendingFrames) { try { cancelAnimationFrame(frame) } catch { /* already gone */ } }
1577
+ pendingFrames.clear()
1578
+ })
1579
+
1580
+ function openSidebarTab () {
1581
+ try {
1582
+ scope.sidebarRight.openTab(PANEL_TAB)
1583
+ return true
1584
+ } catch (error) {
1585
+ console.warn('dsh-computer-use: sidebar tab unavailable', error)
1586
+ return false
1587
+ }
1588
+ }
1589
+
1590
+ function handOverToSidebar () {
1591
+ try { scope.get('layout')?.selectPanel?.(null) } catch (error) {
1592
+ // Deselecting the global panel failed. The panel list would keep showing this seat, so
1593
+ // opening the tab is still the best available outcome.
1594
+ console.warn('dsh-computer-use: layout hand-over failed', error)
1595
+ }
1596
+ // Two frames: the Conversation must be committed (and the right Sidebar mounted) before a
1597
+ // tab can be placed in it. One frame is enough on a warm layout; two is safe either way.
1598
+ let frame = 0
1599
+ frame = requestAnimationFrame(() => {
1600
+ pendingFrames.delete(frame)
1601
+ frame = requestAnimationFrame(() => {
1602
+ pendingFrames.delete(frame)
1603
+ openSidebarTab()
1604
+ })
1605
+ pendingFrames.add(frame)
1606
+ })
1607
+ pendingFrames.add(frame)
1608
+ }
1609
+
1610
+ function LaunchReferencePanel () {
1611
+ const sessions = scope.get('sessions')
1612
+ const current = Object.values(sessions?.list?.getSnapshot?.()?.byId ?? {})
1613
+ .find(session => (session?.retainedBy?.mainView ?? 0) > 0)
1614
+ useEffect(() => {
1615
+ if (!current) return
1616
+ handOverToSidebar()
1617
+ // NO cleanup cancelling the frames: selecting the panel unmounts this component, and the
1618
+ // open must outlive that. The plugin-scope effect above is the only owner.
1619
+ }, [])
1620
+ // A Session is on screen: the effect is moving the human to its right-side tab, so the main
1621
+ // column keeps painting the Conversation and this renders nothing.
1622
+ if (current) return null
1623
+ // No Session: state it plainly instead of showing an empty column with a dead icon. The
1624
+ // Browser panel is session-scoped, so there is nothing honest to open here.
1625
+ return h('div', { className: 'cu-ref' },
1626
+ h('header', null, h('div', { className: 'cu-head' }, h('h2', null, UI.nav))),
1627
+ h('p', { className: 'cu-muted' }, UI.noSession),
1628
+ h('p', { className: 'cu-muted' }, UI.sessionThenTab))
1629
+ }
1630
+
1631
+ scope.slots.inject('main', () => scope.slots.register({ name: 'main', key: PANEL_TAB }, LaunchReferencePanel))
1632
+
1633
+ // The row is metadata only (id, order, a resolved label) plus the occupant that draws its
1634
+ // icon; this plugin draws its own glyph rather than importing a client package.
1635
+ //
1636
+ // THE HOST OWNS THE ROW GEOMETRY, SO THE OCCUPANT MUST NOT. `sidebar.panellist` renders this
1637
+ // component inside the row's own 16px leading cell with a 6px label gap (sidebar README,
1638
+ // "Expanded navigation uses … a 16px leading cell with a 6px label gap"). The old version
1639
+ // returned the TEXT `◎`, a full-width CJK glyph: it rendered wider than 16px, pushed the
1640
+ // label right of every neighbouring row, and drew a small ring inside that oversized box.
1641
+ // This returns an SVG that fills exactly the cell it is given, so the label baseline, the
1642
+ // hover/selected fill and the collapsed tooltip all come from the host, unchanged.
1643
+ scope.slots.inject('sidebar.panellist', () => scope.slots.register({
1644
+ name: 'sidebar.panellist', id: PANEL_TAB, order: 25, label: UI.nav,
1645
+ }, BrowserPanelIcon))
1646
+ })
123
1647
  }
124
1648
 
125
1649
  exports.apply = apply