dsh-duet 0.1.7 → 0.1.9

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/README.md CHANGED
@@ -15,7 +15,11 @@ duet,意为「二重奏」。这里的 duet 使用全双工语音模型,可
15
15
 
16
16
  ## 安装
17
17
 
18
- 已验证兼容 DSH `0.1.5-rc.2` 和 `0.1.6-alpha.2`。
18
+ 支持 DSH Web 和 Desktop。当前版本已通过 DSH `0.2.0-rc.1` 的 Web 集成测试。
19
+
20
+ ### Web
21
+
22
+ 需要 Node.js 22 LTS(22.19.0 起)或 24 及以上版本。
19
23
 
20
24
  安装并打开 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness):
21
25
 
@@ -31,13 +35,22 @@ dsh plugin --profile web add dsh-duet
31
35
  dsh web
32
36
  ```
33
37
 
34
- 也支持 DSH 的 GitHub 插件安装方式:`dsh plugin --profile web add github:YuMS/dsh-duet`。
35
- 两种方式任选其一。
38
+ ### Desktop
39
+
40
+ 在 DSH Desktop 的插件管理页面选择“添加插件”,输入 `dsh-duet` 并安装。
41
+ 安装后若未出现 duet 按钮,退出并重新打开 DSH Desktop。
42
+
43
+ ### 更新
44
+
45
+ Web 用户重新运行 `dsh plugin --profile web add dsh-duet@latest`,然后重启 DSH。
46
+ Desktop 用户在插件管理页面更新。
36
47
 
37
48
  ## 使用
38
49
 
39
50
  duet 支持两种模式。
40
51
 
52
+ 使用前,请先在 DSH 中创建或选择一个 workspace。
53
+
41
54
  | 按钮 | 模式 | 用途 |
42
55
  | --- | --- | --- |
43
56
  | 喇叭 | 播报模式 | 任务完成后,进行简短的播报 |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-duet",
3
- "version": "0.1.7",
3
+ "version": "0.1.9",
4
4
  "description": "duet(二重奏):只用语音就能操作 DSH,边听边说、随时插话的全双工语音助手。",
5
5
  "keywords": [
6
6
  "dsh-plugin",
@@ -22,7 +22,7 @@
22
22
  "scripts": {
23
23
  "test": "node scripts/test.mjs",
24
24
  "check": "node scripts/check-package.mjs",
25
- "test:browser": "node tests/browser/settings.mjs && node tests/browser/tutorial.mjs && node tests/browser/feedback.mjs && node tests/browser/connection-hint.mjs && node tests/browser/resilience.mjs && node tests/browser/page-binding.mjs && node tests/browser/desktop-settings.mjs && node tests/browser/desktop-identity.mjs",
25
+ "test:browser": "node tests/browser/settings.mjs && node tests/browser/tutorial.mjs && node tests/browser/feedback.mjs && node tests/browser/connection-hint.mjs && node tests/browser/controls-layout.mjs && node tests/browser/resilience.mjs && node tests/browser/page-binding.mjs && node tests/browser/desktop-settings.mjs && node tests/browser/desktop-identity.mjs",
26
26
  "test:host": "node tests/host/isolated-host.mjs",
27
27
  "prepack": "npm run check"
28
28
  },
@@ -1,4 +1,4 @@
1
- import { microphoneConstraints } from './microphone.mjs?v=0.1.7'
1
+ import { microphoneConstraints } from './microphone.mjs?v=0.1.9'
2
2
 
3
3
  /** Browser-owned microphone and PCM playback. No microphone is requested in tts_only. */
4
4
  export class DuetAudio {
@@ -37,10 +37,11 @@ export class DuetAudio {
37
37
  }
38
38
  }
39
39
 
40
- async startMic(send, onFailure = () => {}) {
40
+ async startMic(send, onFailure = () => {}, report = () => {}) {
41
41
  const epoch = this.epoch
42
42
  // Exact selection: an unplugged device must not silently use a different mic.
43
43
  const stream = await navigator.mediaDevices.getUserMedia(microphoneConstraints())
44
+ report({event:'browser.microphone_granted'})
44
45
  if (epoch !== this.epoch) { stream.getTracks().forEach(t => t.stop()); return }
45
46
  this.stream = stream
46
47
  let failed = false
@@ -93,6 +94,7 @@ export class DuetAudio {
93
94
  this.mute = this.context.createGain()
94
95
  this.mute.gain.value = 0
95
96
  this.source.connect(this.capture).connect(this.mute).connect(this.context.destination)
97
+ report({event:'browser.capture_started'})
96
98
  }
97
99
 
98
100
  event(event, send) {
@@ -1,22 +1,25 @@
1
- import { DuetState, PLUGIN_VERSION } from '../shared/state.mjs?v=0.1.7'
2
- import { DuetAudio } from './audio.mjs?v=0.1.7'
3
- import { HarnessRPCExecutor, rpcNavigationSession } from './rpc.mjs?v=0.1.7'
4
- import { composerAccess, observeComposer, focusedSession, openLocalSession } from './composer.mjs?v=0.1.7'
5
- import { startComposerBridge } from './composer-bridge.mjs?v=0.1.7'
6
- import { mountTutorial } from './tutorial.mjs?v=0.1.7'
7
- import { tutorialAdapter } from './tutorial-adapter.mjs?v=0.1.7'
8
- import { mountRating } from './feedback.mjs?v=0.1.7'
9
- import { createAudioUploadConsent } from './consent.mjs?v=0.1.7'
10
- import { bindDuetShortcuts } from './shortcuts.mjs?v=0.1.7'
11
- import { nativeInteractions } from './interactions.mjs?v=0.1.7'
12
- import { mountConnectionHint } from './connection-hint.mjs?v=0.1.7'
13
- import { mountControlsLayout } from './controls-layout.mjs?v=0.1.7'
14
- import { mountNotice } from './notice.mjs?v=0.1.7'
15
- import { workspaceIssue, requireWorkspace, browserSessionCatalog, sessionCreationPayload } from './workspaces.mjs?v=0.1.7'
16
- import { voiceSocketUrl, bindSettingsLink } from './transport.mjs?v=0.1.7'
17
- import { identityFetch, identityVoiceProtocols } from './identity.mjs?v=0.1.7'
18
- import { sessionLabel } from '../shared/catalog.mjs?v=0.1.7'
19
- import { resultNotification } from '../shared/result-notification.mjs?v=0.1.7'
1
+ import { DuetState, PLUGIN_VERSION } from '../shared/state.mjs?v=0.1.9'
2
+ import { DuetAudio } from './audio.mjs?v=0.1.9'
3
+ import { HarnessRPCExecutor, rpcNavigationSession } from './rpc.mjs?v=0.1.9'
4
+ import { composerAccess, observeComposer, focusedSession, openLocalSession } from './composer.mjs?v=0.1.9'
5
+ import { startComposerBridge } from './composer-bridge.mjs?v=0.1.9'
6
+ import { mountTutorial } from './tutorial.mjs?v=0.1.9'
7
+ import { tutorialAdapter } from './tutorial-adapter.mjs?v=0.1.9'
8
+ import { mountRating } from './feedback.mjs?v=0.1.9'
9
+ import { createAudioUploadConsent } from './consent.mjs?v=0.1.9'
10
+ import { bindDuetShortcuts } from './shortcuts.mjs?v=0.1.9'
11
+ import { nativeInteractions } from './interactions.mjs?v=0.1.9'
12
+ import { mountConnectionHint } from './connection-hint.mjs?v=0.1.9'
13
+ import { mountControlsLayout } from './controls-layout.mjs?v=0.1.9'
14
+ import { mountNotice } from './notice.mjs?v=0.1.9'
15
+ import { workspaceIssue, requireWorkspace, browserSessionCatalog, sessionCreationPayload } from './workspaces.mjs?v=0.1.9'
16
+ import { voiceSocketUrl, bindSettingsLink } from './transport.mjs?v=0.1.9'
17
+ import { identityFetch, identityVoiceProtocols } from './identity.mjs?v=0.1.9'
18
+ import { sessionLabel } from '../shared/catalog.mjs?v=0.1.9'
19
+ import { resultNotification } from '../shared/result-notification.mjs?v=0.1.9'
20
+ import { HarnessSync } from './harness-sync.mjs?v=0.1.9'
21
+ import { LocalSync } from './local-sync.mjs?v=0.1.9'
22
+ import { diagnosticPayload } from '../shared/diagnostics.mjs?v=0.1.9'
20
23
 
21
24
  export function mountDuet(ctx) {
22
25
  const pageId = crypto.randomUUID()
@@ -26,16 +29,18 @@ export function mountDuet(ctx) {
26
29
  let nextPollAt = 0, pollController, pollWakePending = false, pollFailureSince = null, pollFailures = 0, pollGeneration = -1
27
30
  const notices = mountNotice(() => controls)
28
31
  const labels = new Map()
32
+ const resultResume = {}
33
+ let localSync
29
34
  let clientTraceId = null, diagnosticCount = 0
30
35
  let connectionGuidance = null, reportHintShown = null
31
36
  let tutorial, teaching, ratingPanel, connectionHint, stopControlsLayout, stopSettings
32
37
  const diagnostic = data => {
33
- if (++diagnosticCount > 100) return
38
+ if (++diagnosticCount > 100 && !diagnosticPayload(data)) return
34
39
  const bounded = Object.fromEntries(Object.entries(data).map(([k, v]) => [k, typeof v === 'string' ? v.slice(0, 4000) : v]))
35
40
  const body = JSON.stringify({ client_trace_id: clientTraceId, plugin_version: PLUGIN_VERSION, page_id: pageId,
36
41
  utc: new Date().toISOString(), visibility: document.visibilityState, ...bounded })
37
42
  if (body.length > 24000) return
38
- void fetch('/duplex-control/api/voice/diagnostic', { method: 'POST', credentials: 'same-origin',
43
+ void identityFetch('/duplex-control/api/voice/diagnostic', { method: 'POST', credentials: 'same-origin',
39
44
  headers: { 'Content-Type': 'application/json', 'X-Duplex-Settings': '1' }, body, keepalive: true }).catch(() => {})
40
45
  }
41
46
  const pageError = event => diagnostic({ event: 'browser.error', message: String(event.message || event.reason?.message || event.reason), stack: event.error?.stack || event.reason?.stack })
@@ -77,7 +82,17 @@ export function mountDuet(ctx) {
77
82
  clientTraceId = crypto.randomUUID(); diagnosticCount = 0
78
83
  connectionGuidance = null; reportHintShown = null
79
84
  const connectionTraceId = clientTraceId
80
- const report = data => diagnostic({ ...data, client_trace_id: connectionTraceId, mode })
85
+ const started = performance.now()
86
+ let firstInput = false
87
+ const report = data => {
88
+ const row = {...data, event_id:crypto.randomUUID(), client_trace_id:connectionTraceId,
89
+ page_id:pageId, plugin_version:PLUGIN_VERSION, mode, elapsed_ms:Math.round(performance.now()-started), visibility:document.visibilityState}
90
+ diagnostic(row)
91
+ const payload = diagnosticPayload(row)
92
+ if (payload && ws?.readyState === WebSocket.OPEN && !closed && ws.bufferedAmount < 100000) {
93
+ try { ws.send(JSON.stringify({type:'client.diagnostic', ...payload})) } catch { /* HTTP fallback remains best effort. */ }
94
+ }
95
+ }
81
96
  let ws, closed = false, release, ready = false, stopComposer, stopBridge
82
97
  const opening = new AbortController()
83
98
  const startupTimer = setTimeout(() => {
@@ -87,13 +102,24 @@ export function mountDuet(ctx) {
87
102
  if (ws?.readyState !== WebSocket.OPEN || closed) return
88
103
  if (ws.bufferedAmount > 1_000_000) { receive({ type: 'error', code: 'voice_backpressure' }); return }
89
104
  ws.send(message instanceof ArrayBuffer ? message : JSON.stringify(message))
105
+ if (message instanceof ArrayBuffer && !firstInput) {
106
+ firstInput = true; report({event:'browser.first_input_audio',bytes:message.byteLength})
107
+ }
90
108
  }
91
109
  const composer = composerAccess(ctx, id => sessionLabel(labels.get(id), id))
92
110
  const interactions = nativeInteractions(ctx)
111
+ const resultPush = new HarnessSync(send, localSync, () => ({
112
+ sessions: browserSessionCatalog(ctx, localSync.snapshot?.sessions || []).map(s => ({
113
+ session_id:s.session_id, label:s.label, active:s.active, running:Boolean(s.running), updated_at:s.updated_at,
114
+ })),
115
+ interactions: interactions.snapshot(),
116
+ }), report, resultResume)
117
+ const stopInteractions = interactions.subscribe(() => resultPush.changed())
93
118
  const rpc = new HarnessRPCExecutor(send, fetch, report, async (request, signal) =>
94
119
  (await interactions(request, signal)) ?? composer.execute(request, signal), rows =>
95
120
  browserSessionCatalog(ctx, rows).map(row => ({ ...row, active: row.session_id === focusedSession(ctx) })), {
96
121
  id: connectionTraceId,
122
+ syncSupported: () => localSync?.active && interactions.supportsSync,
97
123
  creationPayload: payload => sessionCreationPayload(ctx, payload),
98
124
  completed: async (request, body, signal) => {
99
125
  const id = rpcNavigationSession(request, body)
@@ -101,15 +127,24 @@ export function mountDuet(ctx) {
101
127
  },
102
128
  })
103
129
  const connection = {
130
+ resultPush,
104
131
  feedbackTicket: null,
132
+ report,
105
133
  send,
106
134
  sendState: state => { if (state) send({ type: 'harness.state', state }) },
107
135
  playing: () => audio.playing(),
108
- async close() {
109
- report({ event: 'browser.connection_close', buffered_bytes: ws?.bufferedAmount })
136
+ async close(details = {reason:'unknown'}) {
137
+ report({ event: 'browser.connection_close', ...details, buffered_bytes: ws?.bufferedAmount })
138
+ // Explicit mode changes start a fresh listening window. An unexpected
139
+ // socket close retains only this page's last acknowledged cursor.
140
+ if (mode === 'online' && ws?.readyState === WebSocket.OPEN) {
141
+ delete resultResume.cursor; delete resultResume.epoch
142
+ }
110
143
  closed = true
111
144
  clearTimeout(startupTimer)
112
145
  opening.abort()
146
+ resultPush.close()
147
+ stopInteractions?.()
113
148
  stopComposer?.()
114
149
  stopBridge?.(); stopBridge = null
115
150
  rpc.close()
@@ -118,7 +153,7 @@ export function mountDuet(ctx) {
118
153
  await new Promise(resolve => {
119
154
  const timer = setTimeout(resolve, 1200)
120
155
  ws.addEventListener('close', () => { clearTimeout(timer); resolve() }, { once: true })
121
- if (ws.readyState < WebSocket.CLOSING) ws.close(1000)
156
+ if (ws.readyState < WebSocket.CLOSING) ws.close(1000, 'duet_client_close')
122
157
  })
123
158
  }
124
159
  release?.()
@@ -134,10 +169,10 @@ export function mountDuet(ctx) {
134
169
  if(!identity.ok)throw Error('voice_config_unavailable')
135
170
  requireWorkspace(ctx)
136
171
  if(closed)return
137
- if (mode === 'online') stopBridge = startComposerBridge(ctx, connectionTraceId)
138
- report({ event: 'browser.connection_start', page_binding: 'connection_owner_v1' })
172
+ if (mode === 'online') stopBridge = startComposerBridge(ctx, connectionTraceId, fetch, localSync)
139
173
  ws = new WebSocket(voiceSocketUrl({ mode, plugin_version: PLUGIN_VERSION, client_trace_id: connectionTraceId, page_id: pageId }), identityVoiceProtocols())
140
174
  ws.onopen = () => {
175
+ report({ event: 'browser.connection_start', page_binding: 'connection_owner_v1' })
141
176
  send({ type: 'session.update' })
142
177
  if (mode === 'online') stopComposer = observeComposer(ctx, composer, send)
143
178
  }
@@ -146,6 +181,7 @@ export function mountDuet(ctx) {
146
181
  let message
147
182
  try {
148
183
  message = JSON.parse(event.data)
184
+ if (resultPush.event(message)) return
149
185
  if (message.type === 'harness.rpc.request') {
150
186
  if (mode !== 'online') throw new Error('harness_rpc_requires_online')
151
187
  await rpc.execute(message)
@@ -158,6 +194,8 @@ export function mountDuet(ctx) {
158
194
  compatibility: message.error?.compatibility, policy: message.error?.policy }); return
159
195
  }
160
196
  if (message.type === 'session.created' && !ready) {
197
+ if (message.harness_rpc_max_bytes === 2_000_000) rpc.maxBytes = 2_000_000
198
+ if (mode === 'online') resultPush.offer(message.harness_sync)
161
199
  connectionGuidance=message.connection_route?.connection_hint
162
200
  reportHintShown=hint=>{
163
201
  report({event:'browser.connection_hint_shown',connection_hint:hint})
@@ -167,14 +205,24 @@ export function mountDuet(ctx) {
167
205
  if (message.compatibility) receive({ type: 'compatibility', compatibility: message.compatibility })
168
206
  connection.feedbackTicket = message.feedback_session_ticket || null
169
207
  ready = true
170
- await audio.prepare()
208
+ report({event:'browser.audio_prepare_started'})
209
+ try { await audio.prepare() }
210
+ catch (error) {
211
+ report({event:'browser.audio_prepare_failed',name:error?.name,phase:'audio_context',context_state:audio.context?.state})
212
+ throw error
213
+ }
171
214
  if (closed) return
172
215
  if (mode === 'online') {
216
+ let phase = 'permission'
217
+ report({event:'browser.microphone_started',phase})
173
218
  try { await audio.startMic(send, code => {
174
219
  if (!closed) { report({event:'browser.capture_failed',code}); receive({type:'error',code}) }
220
+ }, event => {
221
+ if (event.event === 'browser.microphone_granted') phase = 'capture'
222
+ report(event)
175
223
  }) }
176
224
  catch (error) {
177
- report({ event: 'browser.microphone_failed', name: error?.name })
225
+ report({ event: 'browser.microphone_failed', name: error?.name, phase })
178
226
  if (!closed) receive({ type: 'error', code: 'microphone_unavailable' })
179
227
  return
180
228
  }
@@ -198,6 +246,8 @@ export function mountDuet(ctx) {
198
246
  }
199
247
  }
200
248
  ws.onclose = event => {
249
+ resultPush.close()
250
+ stopInteractions?.()
201
251
  stopComposer?.()
202
252
  stopBridge?.(); stopBridge = null
203
253
  report({ event: 'browser.ws_closed', code: event.code, reason: event.reason, was_clean: event.wasClean })
@@ -214,13 +264,18 @@ export function mountDuet(ctx) {
214
264
  const held = new Promise(resolve => { release = resolve })
215
265
  // Opening may hang; ownership ends when close() releases it, not when
216
266
  // a fetch or browser permission request eventually resolves.
217
- void open().catch(error => { if (!closed) receive({type:'error',code:opening.signal.aborted?'voice_start_timeout':error.message||'voice_connection_failed'}) })
267
+ void open().catch(error => { report({event:'browser.open_failed',name:error?.name,phase:'opening'}); if (!closed) receive({type:'error',code:opening.signal.aborted?'voice_start_timeout':error.message||'voice_connection_failed'}) })
218
268
  await held
219
269
  }).catch(() => { if (!closed) receive({ type: 'error', code: 'voice_connection_failed' }) })
220
270
  } else queueMicrotask(() => receive({ type: 'error', code: 'voice_lock_unavailable' }))
221
271
  return connection
222
272
  }
223
273
  const state = new DuetState({ connect, changed: draw, notice })
274
+ const pageHide = () => {
275
+ state.connection?.report({event:'browser.pagehide',reason:'page_unload'})
276
+ void state.setMode('off', {reason:'page_unload'})
277
+ }
278
+ window.addEventListener('pagehide', pageHide)
224
279
  const mount = () => {
225
280
  const entry = document.getElementById('dsh-duet-entry')
226
281
  if (!entry || document.getElementById('dsh-duet-controls')) return
@@ -318,7 +373,15 @@ export function mountDuet(ctx) {
318
373
  pollController = controller
319
374
  const timeout = setTimeout(() => controller.abort(), 5000)
320
375
  try {
321
- const [catalog, completed, health] = await Promise.all([api('sessions',controller.signal), api(`results?after=${cursor ?? 0}&limit=100`,controller.signal), api('health',controller.signal)])
376
+ const pushing = state.connection?.resultPush?.active === true
377
+ const cached = localSync?.active ? localSync.snapshot : null
378
+ const [catalog, health] = cached ? [{sessions:cached.sessions}, cached.health]
379
+ : await Promise.all([api('sessions',controller.signal), api('health',controller.signal)])
380
+ const headOnly = pushing || cursor === null || resultEpoch !== health.focus_epoch
381
+ const completed = headOnly ? {results:[],current_cursor:health.result_cursor,next_cursor:health.result_cursor}
382
+ : cached ? {results:[...localSync.results.values()].filter(j => j.completion_seq > cursor),
383
+ next_cursor:cached.cursor,current_cursor:cached.health.result_cursor}
384
+ : await api(`results?after=${cursor}&limit=20`,controller.signal)
322
385
  if (disposed) return
323
386
  catalog.sessions = browserSessionCatalog(ctx, catalog.sessions)
324
387
  const issue = workspaceIssue(ctx)
@@ -339,6 +402,7 @@ export function mountDuet(ctx) {
339
402
  })
340
403
  resultEpoch = health.focus_epoch
341
404
  cursor = bootstrap ? completed.current_cursor : completed.next_cursor
405
+ state.connection?.resultPush?.changed()
342
406
  if (pollFailures >= 3 && state.mode !== 'off') notice('会话同步已恢复。')
343
407
  pollFailureSince = null; pollFailures = 0
344
408
  } catch (error) {
@@ -354,10 +418,19 @@ export function mountDuet(ctx) {
354
418
  nextPollAt = pollWakePending ? 0 : startedAt + (state.mode !== 'off' || tutorial?.active ? 1000 : document.hidden ? 15000 : 5000)
355
419
  }
356
420
  }
357
- const timer = setInterval(() => { if (Date.now() >= nextPollAt) void poll(); state.tick() }, 1000)
358
- const wakePoll = () => { pollWakePending = true; nextPollAt = 0 }
421
+ const timer = setInterval(() => { if (!localSync?.active && Date.now() >= nextPollAt) void poll(); state.tick() }, 1000)
422
+ const wakePoll = () => { pollWakePending = true; nextPollAt = 0; localSync?.refresh(); void poll() }
359
423
  const unwatchSessions = ctx.sessions.list.subscribe?.(wakePoll)
360
424
  const unwatchWorkspaces = ctx.workspaces?.list?.subscribe?.(wakePoll)
425
+ let lastView = localStorage.getItem('dsh.workspace.view.v5')
426
+ const viewChanged = () => { queueMicrotask(() => {
427
+ const value = localStorage.getItem('dsh.workspace.view.v5')
428
+ if (value !== lastView) { lastView = value; wakePoll() }
429
+ }) }
430
+ window.addEventListener('storage', viewChanged)
431
+ document.addEventListener('click', viewChanged)
432
+ localSync = new LocalSync({onChange: () => { pollWakePending = true; void poll() }})
433
+ localSync.start()
361
434
  const progress = setInterval(() => { if (state.connection) audio.progress(state.connection.send) }, 200)
362
435
  const visibility = () => { state.hidden = document.visibilityState !== 'visible'; state.tick(); void poll() }
363
436
  document.addEventListener('visibilitychange', visibility)
@@ -370,7 +443,7 @@ export function mountDuet(ctx) {
370
443
  if (Date.now() > deadline) throw Error('会话结果同步尚未就绪,请稍后重试教学')
371
444
  await poll(); await new Promise(resolve => setTimeout(resolve, 150))
372
445
  }
373
- })
446
+ }, (context, id) => startComposerBridge(context, id, fetch, localSync))
374
447
  const mountTeaching = () => {
375
448
  if (!tutorial && controls) tutorial = mountTutorial({ controls, adapter: teaching })
376
449
  }
@@ -379,8 +452,12 @@ export function mountDuet(ctx) {
379
452
  teachingObserver.observe(document.body, { subtree: true, childList: true })
380
453
  return () => {
381
454
  disposed = true
455
+ window.removeEventListener('pagehide', pageHide)
382
456
  pollController?.abort()
383
457
  unwatchSessions?.(); unwatchWorkspaces?.()
458
+ localSync.close()
459
+ window.removeEventListener('storage', viewChanged)
460
+ document.removeEventListener('click', viewChanged)
384
461
  notices.dispose()
385
462
  stopShortcuts()
386
463
  observer.disconnect()
@@ -1,7 +1,7 @@
1
1
  /** Composer requests belong to one explicit voice/tutorial connection, never all tabs. */
2
- import { focusedSession as currentSession } from './composer.mjs?v=0.1.7'
2
+ import { focusedSession as currentSession } from './composer.mjs?v=0.1.9'
3
3
 
4
- export function startComposerBridge(ctx, clientId, fetchImpl = fetch) {
4
+ export function startComposerBridge(ctx, clientId, fetchImpl = fetch, feed = null) {
5
5
  const focusedSession = () => currentSession(ctx)
6
6
  const bridgeFetch = async (url, options = {}, timeoutMs = 8000) => {
7
7
  const request = new AbortController()
@@ -15,6 +15,7 @@ export function startComposerBridge(ctx, clientId, fetchImpl = fetch) {
15
15
  const controller = new AbortController()
16
16
  let pollRunning = false
17
17
  let retryTimer
18
+ const inFlight = new Set()
18
19
 
19
20
  const digest = async (text) => {
20
21
  const bytes = new TextEncoder().encode(text)
@@ -127,6 +128,9 @@ export function startComposerBridge(ctx, clientId, fetchImpl = fetch) {
127
128
 
128
129
  const processRequest = async (candidate) => {
129
130
  if (controller.signal.aborted || candidate.target_client_id !== clientId) return
131
+ if (inFlight.has(candidate.id)) return
132
+ inFlight.add(candidate.id)
133
+ try {
130
134
  const claimResponse = await bridgeFetch(
131
135
  `/duplex-control/api/composer/requests/${encodeURIComponent(candidate.id)}/claim`,
132
136
  {
@@ -152,10 +156,12 @@ export function startComposerBridge(ctx, clientId, fetchImpl = fetch) {
152
156
  status: error?.code === "session_not_ready" ? 503 : 409,
153
157
  })
154
158
  }
159
+ } finally { inFlight.delete(candidate.id) }
155
160
  }
156
161
 
157
162
  const poll = async () => {
158
163
  if (pollRunning || controller.signal.aborted) return
164
+ if (feed?.active) return
159
165
  clearTimeout(retryTimer)
160
166
  pollRunning = true
161
167
  let succeeded = false
@@ -179,12 +185,16 @@ export function startComposerBridge(ctx, clientId, fetchImpl = fetch) {
179
185
  pollRunning = false
180
186
  if (!controller.signal.aborted) {
181
187
  // Successful long polls re-arm without a background-tab timer.
182
- if (succeeded) void poll()
188
+ if (succeeded && !feed?.active) void poll()
183
189
  else retryTimer = setTimeout(() => { void poll() }, 1000)
184
190
  }
185
191
  }
186
192
  }
187
193
 
194
+ const unbind = feed?.bindOwner(() => ({ client_id: clientId, session_id: focusedSession() || null, visibility: document.visibilityState }))
195
+ const uncommand = feed?.onCommand(request => { void processRequest(request).catch(() => {}) })
196
+ const unfeed = feed?.subscribe(() => { clearTimeout(retryTimer); if (!feed.active) void poll() })
197
+ const focus = ctx.sessions.list.subscribe?.(() => feed?.beat())
188
198
  void poll()
189
199
  const resume = () => { void poll() }
190
200
  window.addEventListener?.('online', resume)
@@ -193,6 +203,7 @@ export function startComposerBridge(ctx, clientId, fetchImpl = fetch) {
193
203
  return () => {
194
204
  controller.abort()
195
205
  clearTimeout(retryTimer)
206
+ unbind?.(); uncommand?.(); unfeed?.(); focus?.()
196
207
  window.removeEventListener?.('online', resume)
197
208
  window.removeEventListener?.('pageshow', resume)
198
209
  if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', resume)
@@ -1,5 +1,5 @@
1
1
  /** A brief, non-modal invitation after the microphone is actually ready. */
2
- import {normalizeGuidance} from '../shared/connection-guidance.mjs?v=0.1.7'
2
+ import {normalizeGuidance} from '../shared/connection-guidance.mjs?v=0.1.9'
3
3
  export function mountConnectionHint(controls, { duration = 8000, onShown = ()=>{} } = {}) {
4
4
  const hint = document.createElement('div')
5
5
  hint.dataset.duetConnectionHint = ''
@@ -19,7 +19,8 @@ export function mountConnectionHint(controls, { duration = 8000, onShown = ()=>{
19
19
  const position = () => {
20
20
  if (hint.hidden || disposed) return
21
21
  if (!controls.isConnected) { hide(); return }
22
- const button = controls.querySelector('[data-voice=mic]') || controls
22
+ const mic = controls.querySelector('[data-voice=mic]')
23
+ const button = mic?.getClientRects().length ? mic : controls.querySelector('#dsh-duet-entry') || controls
23
24
  const rect = button.getBoundingClientRect(), width = hint.offsetWidth, height = hint.offsetHeight
24
25
  const left = Math.max(16, Math.min(rect.left, innerWidth - width - 16))
25
26
  const above = rect.top >= height + 26
@@ -1,18 +1,139 @@
1
- /** Follow the host's available sidebar width, without depending on DSH classes. */
1
+ /** A compact launcher; its top-layer flyout consumes no host footer space. */
2
2
  export function mountControlsLayout(controls) {
3
3
  const parent = controls.parentElement
4
+ const hostCompact = parent.getAttribute('data-duet-compact-host')
5
+ const ancestors = []
6
+ for (let node = parent; node; node = node.parentElement) ancestors.push(node)
7
+ // Flex children may retain their intrinsic width after the sidebar shrinks.
8
+ // Measure the available ancestor content boxes, skipping display:contents.
9
+ const geometry = () => {
10
+ let width = Infinity, boundary = parent.getBoundingClientRect(), clipped = false
11
+ for (const node of ancestors) {
12
+ const rect = node.getBoundingClientRect(), style = getComputedStyle(node)
13
+ if (style.display === 'contents' || rect.width <= 0) continue
14
+ const inset = ['paddingLeft', 'paddingRight', 'borderLeftWidth', 'borderRightWidth']
15
+ .reduce((sum, key) => sum + (parseFloat(style[key]) || 0), 0)
16
+ width = Math.min(width, Math.max(0, rect.width - inset))
17
+ if (!clipped && ['hidden', 'clip', 'auto', 'scroll'].includes(style.overflowX)) {
18
+ boundary = rect; clipped = true
19
+ }
20
+ }
21
+ return { width, boundary }
22
+ }
23
+ const entry = controls.querySelector('#dsh-duet-entry')
24
+ if (!entry) return () => {}
25
+ const initial = { controls: controls.style.cssText, entry: entry.style.cssText }
26
+ const label = [...entry.childNodes].find(node => node.nodeType === Node.TEXT_NODE)
27
+ const labelText = label?.textContent
28
+ const actions = document.createElement('div')
29
+ actions.dataset.duetActions = ''
30
+ actions.id = 'dsh-duet-actions'
31
+ actions.setAttribute('role', 'group')
32
+ actions.setAttribute('aria-label', 'duet 语音控制')
33
+ for (const node of [...controls.children]) if (node.matches('[data-voice],a')) actions.append(node)
34
+ controls.append(actions)
35
+ let compact = false, opened = false, timer, disposed = false, pinned = false, suppressFocus = false
36
+ const listeners = []
37
+ const listen = (node, event, fn, options) => {
38
+ node.addEventListener(event, fn, options)
39
+ listeners.push(() => node.removeEventListener(event, fn, options))
40
+ }
41
+ const position = () => {
42
+ if (!opened) return
43
+ const rect = entry.getBoundingClientRect(), width = actions.offsetWidth, height = actions.offsetHeight
44
+ const sidebar = geometry().boundary, right = Math.max(rect.right, sidebar.right) + 8
45
+ actions.style.left = `${Math.max(8, Math.min(right + width <= innerWidth - 8 ? right : Math.min(rect.left, sidebar.left) - width - 8, innerWidth - width - 8))}px`
46
+ actions.style.top = `${Math.max(8, Math.min(rect.top + (rect.height - height) / 2, innerHeight - height - 8))}px`
47
+ }
48
+ const close = () => {
49
+ clearTimeout(timer)
50
+ if (!opened) return
51
+ if (actions.matches(':popover-open')) actions.hidePopover()
52
+ actions.hidden = true; opened = false
53
+ entry.setAttribute('aria-expanded', 'false')
54
+ }
55
+ const open = () => {
56
+ clearTimeout(timer)
57
+ if (!compact || disposed || !controls.isConnected) return
58
+ if (!opened) {
59
+ actions.hidden = false; actions.showPopover(); opened = true
60
+ entry.setAttribute('aria-expanded', 'true')
61
+ }
62
+ position()
63
+ }
64
+ const later = () => {
65
+ clearTimeout(timer)
66
+ timer = setTimeout(() => {
67
+ if (!pinned && !entry.matches(':hover') && !actions.matches(':hover') &&
68
+ !controls.contains(document.activeElement)) close()
69
+ }, 220)
70
+ }
4
71
  const update = () => {
5
- const compact = parent.getBoundingClientRect().width < 160
6
- if (controls.dataset.compact === String(compact)) return
72
+ const next = geometry().width < 160 && typeof actions.showPopover === 'function'
73
+ if (controls.dataset.compact === String(next)) { position(); return }
74
+ close(); compact = next
7
75
  controls.dataset.compact = String(compact)
8
- controls.style.flexDirection = compact ? 'column' : 'row'
76
+ if (compact) parent.setAttribute('data-duet-compact-host', 'true')
77
+ else if (hostCompact === null) parent.removeAttribute('data-duet-compact-host')
78
+ else parent.setAttribute('data-duet-compact-host', hostCompact)
79
+ controls.style.flexDirection = 'row'
9
80
  controls.style.margin = compact ? '4px 0' : '4px 8px'
10
- controls.style.padding = compact ? '6px 0' : '6px 8px'
11
- const entry = controls.querySelector('#dsh-duet-entry')
12
- if (entry) entry.style.display = compact ? 'none' : ''
81
+ controls.style.padding = compact ? '2px 0' : '6px 8px'
82
+ controls.style.justifyContent = compact ? 'center' : ''
83
+ controls.style.minWidth = '0'
84
+ entry.style.cssText = initial.entry
85
+ if (label) label.textContent = compact ? 'D' : labelText
86
+ if (compact) {
87
+ entry.style.cssText += ';display:flex;align-items:center;gap:2px;margin:0;padding:4px;box-sizing:border-box;min-width:32px;height:32px;font-size:23px;cursor:pointer'
88
+ entry.setAttribute('role', 'button'); entry.tabIndex = 0
89
+ entry.setAttribute('aria-label', 'duet 语音控制')
90
+ entry.setAttribute('aria-expanded', 'false'); entry.setAttribute('aria-controls', actions.id)
91
+ actions.setAttribute('popover', 'manual'); actions.hidden = true
92
+ actions.style.cssText = 'position:fixed;inset:auto;margin:0;box-sizing:border-box;align-items:center;gap:6px;padding:9px;border:1px solid #64748b55;border-radius:12px;background:light-dark(#fff,#17212f);color:light-dark(#243247,#edf3ff);color-scheme:light dark;box-shadow:0 8px 28px #0003;max-width:calc(100vw - 16px);z-index:100015'
93
+ if (pinned) open()
94
+ } else {
95
+ for (const attr of ['role', 'tabindex', 'aria-label', 'aria-expanded', 'aria-controls']) entry.removeAttribute(attr)
96
+ actions.removeAttribute('popover'); actions.hidden = false
97
+ actions.style.cssText = 'display:flex;align-items:center;gap:4px'
98
+ }
13
99
  }
100
+ const style = document.createElement('style')
101
+ style.textContent = '[data-duet-compact-host="true"]{flex-direction:column!important;align-items:center!important;max-width:100%} #dsh-duet-actions:popover-open{display:flex} #dsh-duet-entry[role=button]:focus-visible{outline:2px solid #80c2ff;outline-offset:2px;border-radius:6px}'
102
+ controls.append(style)
103
+ listen(entry, 'pointerenter', open); listen(entry, 'pointerleave', later)
104
+ listen(actions, 'pointerenter', () => clearTimeout(timer)); listen(actions, 'pointerleave', later)
105
+ listen(entry, 'focus', () => { if (!suppressFocus) open() }); listen(controls, 'focusout', later)
106
+ listen(entry, 'click', event => { if (compact) { event.preventDefault(); open() } })
107
+ listen(entry, 'keydown', event => {
108
+ if (compact && ['Enter', ' ', 'ArrowRight', 'ArrowDown'].includes(event.key)) {
109
+ event.preventDefault(); open(); actions.querySelector('button,a')?.focus()
110
+ }
111
+ })
112
+ listen(document, 'keydown', event => {
113
+ if (event.key === 'Escape' && opened && !pinned) {
114
+ const restore = controls.contains(document.activeElement)
115
+ close()
116
+ if (restore) { suppressFocus = true; entry.focus(); suppressFocus = false }
117
+ }
118
+ })
119
+ listen(document, 'pointerdown', event => { if (!pinned && !controls.contains(event.target)) close() })
120
+ listen(controls, 'duet:reveal-controls', event => {
121
+ pinned = Boolean(event.detail)
122
+ if (pinned) open(); else later()
123
+ })
124
+ listen(window, 'resize', position); listen(window, 'scroll', position, true)
14
125
  const observer = new ResizeObserver(update)
15
- observer.observe(parent)
126
+ for (const node of ancestors) observer.observe(node)
16
127
  update()
17
- return () => observer.disconnect()
128
+ return () => {
129
+ close(); disposed = true; observer.disconnect()
130
+ for (const stop of listeners) stop()
131
+ if (label) label.textContent = labelText
132
+ for (const attr of ['role', 'tabindex', 'aria-label', 'aria-expanded', 'aria-controls']) entry.removeAttribute(attr)
133
+ controls.style.cssText = initial.controls; entry.style.cssText = initial.entry
134
+ controls.append(...actions.children); actions.remove(); style.remove()
135
+ delete controls.dataset.compact
136
+ if (hostCompact === null) parent.removeAttribute('data-duet-compact-host')
137
+ else parent.setAttribute('data-duet-compact-host', hostCompact)
138
+ }
18
139
  }
@@ -11,7 +11,7 @@ window.__ModuleLoader__.load({
11
11
  ctx.effect(() => {
12
12
  let active = true
13
13
  let dispose
14
- import('/duet/assets/client/browser.mjs?v=0.1.7').then(module => {
14
+ import('/duet/assets/client/browser.mjs?v=0.1.9').then(module => {
15
15
  if (active) dispose = module.mountDuet(ctx)
16
16
  }).catch(error => console.warn('duet controls could not load:', error))
17
17
  return () => { active = false; dispose?.() }
@@ -1,5 +1,5 @@
1
1
  /** Optional, explicit rating; never opens voice or submits without a user click. */
2
- import { identityFetch } from './identity.mjs?v=0.1.7'
2
+ import { identityFetch } from './identity.mjs?v=0.1.9'
3
3
 
4
4
  export function mountRating(anchor, sessionTicket) {
5
5
  if(!sessionTicket)return null