dsh-duet 0.1.8 → 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.8",
3
+ "version": "0.1.9",
4
4
  "description": "duet(二重奏):只用语音就能操作 DSH,边听边说、随时插话的全双工语音助手。",
5
5
  "keywords": [
6
6
  "dsh-plugin",
@@ -1,4 +1,4 @@
1
- import { microphoneConstraints } from './microphone.mjs?v=0.1.8'
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,24 +1,25 @@
1
- import { DuetState, PLUGIN_VERSION } from '../shared/state.mjs?v=0.1.8'
2
- import { DuetAudio } from './audio.mjs?v=0.1.8'
3
- import { HarnessRPCExecutor, rpcNavigationSession } from './rpc.mjs?v=0.1.8'
4
- import { composerAccess, observeComposer, focusedSession, openLocalSession } from './composer.mjs?v=0.1.8'
5
- import { startComposerBridge } from './composer-bridge.mjs?v=0.1.8'
6
- import { mountTutorial } from './tutorial.mjs?v=0.1.8'
7
- import { tutorialAdapter } from './tutorial-adapter.mjs?v=0.1.8'
8
- import { mountRating } from './feedback.mjs?v=0.1.8'
9
- import { createAudioUploadConsent } from './consent.mjs?v=0.1.8'
10
- import { bindDuetShortcuts } from './shortcuts.mjs?v=0.1.8'
11
- import { nativeInteractions } from './interactions.mjs?v=0.1.8'
12
- import { mountConnectionHint } from './connection-hint.mjs?v=0.1.8'
13
- import { mountControlsLayout } from './controls-layout.mjs?v=0.1.8'
14
- import { mountNotice } from './notice.mjs?v=0.1.8'
15
- import { workspaceIssue, requireWorkspace, browserSessionCatalog, sessionCreationPayload } from './workspaces.mjs?v=0.1.8'
16
- import { voiceSocketUrl, bindSettingsLink } from './transport.mjs?v=0.1.8'
17
- import { identityFetch, identityVoiceProtocols } from './identity.mjs?v=0.1.8'
18
- import { sessionLabel } from '../shared/catalog.mjs?v=0.1.8'
19
- import { resultNotification } from '../shared/result-notification.mjs?v=0.1.8'
20
- import { HarnessSync } from './harness-sync.mjs?v=0.1.8'
21
- import { LocalSync } from './local-sync.mjs?v=0.1.8'
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'
22
23
 
23
24
  export function mountDuet(ctx) {
24
25
  const pageId = crypto.randomUUID()
@@ -34,12 +35,12 @@ export function mountDuet(ctx) {
34
35
  let connectionGuidance = null, reportHintShown = null
35
36
  let tutorial, teaching, ratingPanel, connectionHint, stopControlsLayout, stopSettings
36
37
  const diagnostic = data => {
37
- if (++diagnosticCount > 100) return
38
+ if (++diagnosticCount > 100 && !diagnosticPayload(data)) return
38
39
  const bounded = Object.fromEntries(Object.entries(data).map(([k, v]) => [k, typeof v === 'string' ? v.slice(0, 4000) : v]))
39
40
  const body = JSON.stringify({ client_trace_id: clientTraceId, plugin_version: PLUGIN_VERSION, page_id: pageId,
40
41
  utc: new Date().toISOString(), visibility: document.visibilityState, ...bounded })
41
42
  if (body.length > 24000) return
42
- 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',
43
44
  headers: { 'Content-Type': 'application/json', 'X-Duplex-Settings': '1' }, body, keepalive: true }).catch(() => {})
44
45
  }
45
46
  const pageError = event => diagnostic({ event: 'browser.error', message: String(event.message || event.reason?.message || event.reason), stack: event.error?.stack || event.reason?.stack })
@@ -81,7 +82,17 @@ export function mountDuet(ctx) {
81
82
  clientTraceId = crypto.randomUUID(); diagnosticCount = 0
82
83
  connectionGuidance = null; reportHintShown = null
83
84
  const connectionTraceId = clientTraceId
84
- 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
+ }
85
96
  let ws, closed = false, release, ready = false, stopComposer, stopBridge
86
97
  const opening = new AbortController()
87
98
  const startupTimer = setTimeout(() => {
@@ -91,6 +102,9 @@ export function mountDuet(ctx) {
91
102
  if (ws?.readyState !== WebSocket.OPEN || closed) return
92
103
  if (ws.bufferedAmount > 1_000_000) { receive({ type: 'error', code: 'voice_backpressure' }); return }
93
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
+ }
94
108
  }
95
109
  const composer = composerAccess(ctx, id => sessionLabel(labels.get(id), id))
96
110
  const interactions = nativeInteractions(ctx)
@@ -115,11 +129,12 @@ export function mountDuet(ctx) {
115
129
  const connection = {
116
130
  resultPush,
117
131
  feedbackTicket: null,
132
+ report,
118
133
  send,
119
134
  sendState: state => { if (state) send({ type: 'harness.state', state }) },
120
135
  playing: () => audio.playing(),
121
- async close() {
122
- 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 })
123
138
  // Explicit mode changes start a fresh listening window. An unexpected
124
139
  // socket close retains only this page's last acknowledged cursor.
125
140
  if (mode === 'online' && ws?.readyState === WebSocket.OPEN) {
@@ -138,7 +153,7 @@ export function mountDuet(ctx) {
138
153
  await new Promise(resolve => {
139
154
  const timer = setTimeout(resolve, 1200)
140
155
  ws.addEventListener('close', () => { clearTimeout(timer); resolve() }, { once: true })
141
- if (ws.readyState < WebSocket.CLOSING) ws.close(1000)
156
+ if (ws.readyState < WebSocket.CLOSING) ws.close(1000, 'duet_client_close')
142
157
  })
143
158
  }
144
159
  release?.()
@@ -155,9 +170,9 @@ export function mountDuet(ctx) {
155
170
  requireWorkspace(ctx)
156
171
  if(closed)return
157
172
  if (mode === 'online') stopBridge = startComposerBridge(ctx, connectionTraceId, fetch, localSync)
158
- report({ event: 'browser.connection_start', page_binding: 'connection_owner_v1' })
159
173
  ws = new WebSocket(voiceSocketUrl({ mode, plugin_version: PLUGIN_VERSION, client_trace_id: connectionTraceId, page_id: pageId }), identityVoiceProtocols())
160
174
  ws.onopen = () => {
175
+ report({ event: 'browser.connection_start', page_binding: 'connection_owner_v1' })
161
176
  send({ type: 'session.update' })
162
177
  if (mode === 'online') stopComposer = observeComposer(ctx, composer, send)
163
178
  }
@@ -190,14 +205,24 @@ export function mountDuet(ctx) {
190
205
  if (message.compatibility) receive({ type: 'compatibility', compatibility: message.compatibility })
191
206
  connection.feedbackTicket = message.feedback_session_ticket || null
192
207
  ready = true
193
- 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
+ }
194
214
  if (closed) return
195
215
  if (mode === 'online') {
216
+ let phase = 'permission'
217
+ report({event:'browser.microphone_started',phase})
196
218
  try { await audio.startMic(send, code => {
197
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)
198
223
  }) }
199
224
  catch (error) {
200
- report({ event: 'browser.microphone_failed', name: error?.name })
225
+ report({ event: 'browser.microphone_failed', name: error?.name, phase })
201
226
  if (!closed) receive({ type: 'error', code: 'microphone_unavailable' })
202
227
  return
203
228
  }
@@ -239,13 +264,18 @@ export function mountDuet(ctx) {
239
264
  const held = new Promise(resolve => { release = resolve })
240
265
  // Opening may hang; ownership ends when close() releases it, not when
241
266
  // a fetch or browser permission request eventually resolves.
242
- 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'}) })
243
268
  await held
244
269
  }).catch(() => { if (!closed) receive({ type: 'error', code: 'voice_connection_failed' }) })
245
270
  } else queueMicrotask(() => receive({ type: 'error', code: 'voice_lock_unavailable' }))
246
271
  return connection
247
272
  }
248
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)
249
279
  const mount = () => {
250
280
  const entry = document.getElementById('dsh-duet-entry')
251
281
  if (!entry || document.getElementById('dsh-duet-controls')) return
@@ -422,6 +452,7 @@ export function mountDuet(ctx) {
422
452
  teachingObserver.observe(document.body, { subtree: true, childList: true })
423
453
  return () => {
424
454
  disposed = true
455
+ window.removeEventListener('pagehide', pageHide)
425
456
  pollController?.abort()
426
457
  unwatchSessions?.(); unwatchWorkspaces?.()
427
458
  localSync.close()
@@ -1,5 +1,5 @@
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.8'
2
+ import { focusedSession as currentSession } from './composer.mjs?v=0.1.9'
3
3
 
4
4
  export function startComposerBridge(ctx, clientId, fetchImpl = fetch, feed = null) {
5
5
  const focusedSession = () => currentSession(ctx)
@@ -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.8'
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 = ''
@@ -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.8').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.8'
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
@@ -1,5 +1,5 @@
1
1
  import { IDENTITY_HEADER, IDENTITY_TRANSPORT_HEADER, IDENTITY_TRANSPORT, IDENTITY_STORAGE,
2
- VOICE_PROTOCOL, IDENTITY_PROTOCOL_PREFIX, validIdentityToken } from '../shared/identity.mjs?v=0.1.8'
2
+ VOICE_PROTOCOL, IDENTITY_PROTOCOL_PREFIX, validIdentityToken } from '../shared/identity.mjs?v=0.1.9'
3
3
 
4
4
  /** Desktop strips plugin cookies. Keep the Host-signed value in its origin storage. */
5
5
  export function createIdentityClient(globals = globalThis) {
@@ -152,7 +152,7 @@
152
152
  <footer><span>duet / DeepSeek Harness</span></footer>
153
153
  </main>
154
154
  <script type="module">
155
- import { identityFetch } from '/duet/assets/client/identity.mjs?v=0.1.8';
155
+ import { identityFetch } from '/duet/assets/client/identity.mjs?v=0.1.9';
156
156
  const base = "/duplex-control/api";
157
157
  let debugEnabled = false, settingsRevision = null, feedbackSubmitting = false;
158
158
  const composerChannel = typeof BroadcastChannel === "undefined" ? null : new BroadcastChannel("dsh-duplex-control-v1");
@@ -363,7 +363,7 @@
363
363
  }
364
364
  $('openTutorial').onclick = async () => {
365
365
  try {
366
- const {requestTutorial} = await import('/duet/assets/client/tutorial-request.mjs?v=0.1.8');
366
+ const {requestTutorial} = await import('/duet/assets/client/tutorial-request.mjs?v=0.1.9');
367
367
  requestTutorial(localStorage);
368
368
  $('tutorialStatus').textContent = '请回到 DSH 页面继续教学。';
369
369
  } catch { $('tutorialStatus').textContent = '暂时无法打开教学,请允许浏览器存储后重试。'; }
@@ -372,11 +372,11 @@
372
372
  setInterval(() => { loadDuetConfig().catch(showConnectionUnavailable); }, 2000);
373
373
  void loadNotices();
374
374
  setInterval(loadNotices, 60000);
375
- import('/duet/assets/client/shortcuts.mjs?v=0.1.8').then(({mountShortcutSettings}) => {
375
+ import('/duet/assets/client/shortcuts.mjs?v=0.1.9').then(({mountShortcutSettings}) => {
376
376
  const dispose = mountShortcutSettings({speaker:$('speakerShortcut'),mic:$('micShortcut'),clearSpeaker:$('clearSpeakerShortcut'),clearMic:$('clearMicShortcut'),status:$('shortcutStatus')});
377
377
  window.addEventListener('pagehide', e => {if(!e.persisted)dispose()}, {once:true});
378
378
  }).catch(() => { $('shortcutStatus').textContent = '暂时无法加载快捷键设置,请刷新重试。'; });
379
- import('/duet/assets/client/microphone.mjs?v=0.1.8').then(({mountMicrophoneSettings}) => {
379
+ import('/duet/assets/client/microphone.mjs?v=0.1.9').then(({mountMicrophoneSettings}) => {
380
380
  const dispose = mountMicrophoneSettings({select:$('microphoneDevice'),refresh:$('refreshMicrophones'),status:$('microphoneStatus')});
381
381
  window.addEventListener('pagehide', dispose, {once:true});
382
382
  }).catch(() => { $('microphoneStatus').textContent = '暂时无法加载麦克风设置,请刷新重试。'; });
@@ -1,8 +1,8 @@
1
1
  /** DSH browser services plus existing voice connection; never opens a microphone. */
2
- import { PLUGIN_VERSION } from '../shared/state.mjs?v=0.1.8'
3
- import { focusedSession } from './composer.mjs?v=0.1.8'
4
- import { sessionCreationPayload, workspaceIssue } from './workspaces.mjs?v=0.1.8'
5
- import { startComposerBridge } from './composer-bridge.mjs?v=0.1.8'
2
+ import { PLUGIN_VERSION } from '../shared/state.mjs?v=0.1.9'
3
+ import { focusedSession } from './composer.mjs?v=0.1.9'
4
+ import { sessionCreationPayload, workspaceIssue } from './workspaces.mjs?v=0.1.9'
5
+ import { startComposerBridge } from './composer-bridge.mjs?v=0.1.9'
6
6
  export function tutorialAdapter(ctx, state, audio, pollReady, startBridge = startComposerBridge) {
7
7
  let narration
8
8
  const completed = new Map()
@@ -1,5 +1,5 @@
1
1
  /** Opt-in walkthrough. All writes are limited to sessions created by this run. */
2
- import {consumeTutorialRequest} from './tutorial-request.mjs?v=0.1.8'
2
+ import {consumeTutorialRequest} from './tutorial-request.mjs?v=0.1.9'
3
3
  export const TUTORIAL_KEY = 'dsh-duplex-tutorial-v1'
4
4
  export const QUESTION = '什么是语音交互?请用一句话简单解释,不使用工具。'
5
5
  export const INPUT = '用一句话介绍语音助手。'
@@ -1,6 +1,7 @@
1
1
  /** Explicit public asset inventory. Host code and configuration are never served. */
2
2
  const modules = {
3
3
  state: 'shared/state', catalog: 'shared/catalog',
4
+ diagnostics: 'shared/diagnostics',
4
5
  result_notification: 'shared/result-notification',
5
6
  connection_guidance: 'shared/connection-guidance',
6
7
  audio: 'client/audio', microphone: 'client/microphone', shortcuts: 'client/shortcuts',
@@ -0,0 +1,45 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { diagnosticPayload, DIAGNOSTICS_PROTOCOL } from '../shared/diagnostics.mjs'
3
+
4
+ /** Bounded, asynchronous batches. Telemetry failure never closes a voice socket. */
5
+ export class ConnectionDiagnostics {
6
+ constructor(metadata, fetcher = fetch) {
7
+ this.metadata = metadata; this.fetcher = fetcher
8
+ this.pending = []; this.seen = new Set(); this.count = 0; this.attempts = 0
9
+ }
10
+ add(value) {
11
+ const row = diagnosticPayload({...value, ...this.metadata, event_id: value.event_id || randomUUID()})
12
+ if (!row || this.seen.has(row.event_id) || this.count >= 96) return
13
+ this.seen.add(row.event_id); row.sequence=this.count++; this.pending.push(row)
14
+ this.schedule()
15
+ }
16
+ offer(offer, config, endpoint) {
17
+ if (this.target || offer?.protocol !== DIAGNOSTICS_PROTOCOL || typeof offer.ticket !== 'string' || offer.ticket.length > 4096) return
18
+ const url = new URL(endpoint); url.protocol = url.protocol === 'wss:' ? 'https:' : 'http:'
19
+ url.pathname = '/client-diagnostics'; url.search = ''; url.hash = ''
20
+ this.target = url.href; this.ticket = offer.ticket; this.authorization = config.authorization
21
+ this.schedule()
22
+ }
23
+ schedule(delay = 150) {
24
+ if (!this.target || !this.pending.length || this.timer || this.busy || this.attempts >= 120) return
25
+ this.timer = setTimeout(() => { this.timer = null; void this.flush() }, delay); this.timer.unref?.()
26
+ }
27
+ async flush() {
28
+ if (this.busy || !this.target || !this.pending.length) return
29
+ this.busy = true; this.attempts++
30
+ const rows = this.pending.slice(0, 16)
31
+ let failed = false
32
+ try {
33
+ const response = await this.fetcher(this.target, { method: 'POST', redirect: 'error',
34
+ headers: {'Content-Type':'application/json', ...(this.authorization ? {Authorization:this.authorization} : {})},
35
+ body: JSON.stringify({protocol:DIAGNOSTICS_PROTOCOL, ticket:this.ticket, events:rows}),
36
+ signal: AbortSignal.timeout(3000) })
37
+ if (!response.ok) throw Error('diagnostic_upload_failed')
38
+ await response.body?.cancel()
39
+ this.pending.splice(0, rows.length); this.failures = 0
40
+ } catch { failed = true; this.failures = (this.failures || 0) + 1 }
41
+ finally { this.busy = false }
42
+ // At most three retries in a row, even if the server disappeared at close.
43
+ if (!failed || this.failures < 3) this.schedule(failed ? 1000 : 150)
44
+ }
45
+ }
@@ -12,7 +12,7 @@ import { FeedbackService } from './feedback-store.mjs'
12
12
  import { RemoteFeedback } from './feedback-files.mjs'
13
13
  import { PLUGIN_VERSION } from '../shared/state.mjs'
14
14
  import { buildSessionCatalog, sessionLabel } from '../shared/catalog.mjs'
15
- import { broadcastText } from '../shared/result-notification.mjs'
15
+ import { broadcastText, taskErrorText } from '../shared/result-notification.mjs'
16
16
  import { publicAsset } from './assets.mjs'
17
17
  import { duetEnv } from './environment.mjs'
18
18
  import { EndpointDiscovery } from './endpoint-discovery.mjs'
@@ -367,7 +367,7 @@ export function apply(ctx, options = {}) {
367
367
  }, hostAbort.signal)
368
368
  } catch (error) {
369
369
  job.status = 'failed'
370
- job.error = error instanceof Error ? error.message : String(error)
370
+ job.error = taskErrorText(error)
371
371
  job.completed_at = nowSeconds()
372
372
  completionSequence += 1
373
373
  job.completion_seq = completionSequence
@@ -420,7 +420,7 @@ export function apply(ctx, options = {}) {
420
420
  job.error = 'Harness turn was aborted, not completed'
421
421
  } else if (event.data.reason?.kind === 'error') {
422
422
  job.status = 'failed'
423
- job.error = String(event.data.reason.error || 'Harness turn failed')
423
+ job.error = taskErrorText(event.data.reason.error)
424
424
  } else if (!job.result) {
425
425
  job.status = 'failed'
426
426
  job.error = `Harness turn ended without a final text response (${event.data.reason?.kind || 'unknown'})`
@@ -540,10 +540,13 @@ export function apply(ctx, options = {}) {
540
540
  return
541
541
  }
542
542
  if (req.method === 'POST' && pathname === `${ROUTE}/api/voice/diagnostic`) {
543
- if (!settingsWriteAllowed(req)) { sendError(res, 403, 'same-origin diagnostic request required'); return }
543
+ const rejection = ctx.connection.requestRejection(req)
544
+ if (rejection) { sendError(res, rejection, 'DSH connection required'); return }
545
+ if (!identityWriteAllowed(req)) { sendError(res, 403, 'same-origin diagnostic request required'); return }
544
546
  const body = await readJson(req)
545
547
  if (JSON.stringify(body).length > 24000) { sendError(res, 413, 'diagnostic too large'); return }
546
548
  audit.event('client.diagnostic', body)
549
+ try { duetProxy?.reportDiagnostic?.(req, body) } catch { /* Best effort only. */ }
547
550
  sendJson(res, 200, { ok: true, logging: audit.snapshot() }); return
548
551
  }
549
552
  if (req.method === 'GET' && pathname === `${ROUTE}/api/voice/service-info`) {
@@ -1,6 +1,8 @@
1
1
  /** Same-origin voice relay; endpoint and compatibility policy belong to the DSH host. */
2
2
  import { createRequire } from 'node:module'
3
3
  import { DuetTrace } from './trace.mjs'
4
+ import { ConnectionDiagnostics } from './diagnostics.mjs'
5
+ import { DIAGNOSTICS_PROTOCOL } from '../shared/diagnostics.mjs'
4
6
  import { PLUGIN_VERSION } from '../shared/state.mjs'
5
7
  import { duetEnv } from './environment.mjs'
6
8
  import { EndpointDiscovery, connectEndpoint } from './endpoint-discovery.mjs'
@@ -60,6 +62,7 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
60
62
  const server = new WebSocketServer({ noServer: true, maxPayload: 2_100_000,
61
63
  handleProtocols: protocols => protocols.has(VOICE_PROTOCOL) ? VOICE_PROTOCOL : false })
62
64
  const connections = new Map()
65
+ const reporters = new Map()
63
66
  const stop = ctx.webServer.registerUpgrade({
64
67
  path: '/duplex-control/voice/ws',
65
68
  handler(req, socket, head) {
@@ -85,7 +88,7 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
85
88
  trace.event('browser.closed', { code, reason: reason.toString() })
86
89
  const timer = setTimeout(() => { void trace.close() }, 1500); timer.unref()
87
90
  })
88
- let back, feedbackTicket = null, connectionRoute, selectedConfig
91
+ let back, feedbackTicket = null, connectionRoute, selectedConfig, diagnostics
89
92
  const opening = new AbortController()
90
93
  front.once('close', () => feedback?.close(feedbackTicket))
91
94
  let state = null
@@ -96,6 +99,7 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
96
99
  terminal = true
97
100
  opening.abort()
98
101
  trace.event('proxy.failed', { code })
102
+ diagnostics?.add({event:'proxy.failed',code})
99
103
  if (front.readyState === WebSocket.OPEN) front.send(JSON.stringify({ type: 'error', error: { code } }))
100
104
  front.close(code === 'capacity_exhausted' ? 1013 : 1008)
101
105
  back?.close()
@@ -106,6 +110,11 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
106
110
  let anonymousUserId
107
111
  try{anonymousUserId=feedback?.user(req)}catch{ /* Identity is optional, not admission. */ }
108
112
  const clientMetadata=sessionMetadata(params,mode,anonymousUserId)
113
+ diagnostics = new ConnectionDiagnostics({client_trace_id:clientMetadata.client_trace_id,
114
+ page_id:clientMetadata.page_id, plugin_version:clientMetadata.version, host_version:PLUGIN_VERSION, mode})
115
+ reporters.set(clientMetadata.client_trace_id, {diagnostics, page_id:clientMetadata.page_id, user:anonymousUserId})
116
+ // Allow keepalive HTTP diagnostics to arrive after the browser socket closed.
117
+ front.once('close', () => { const timer=setTimeout(()=>reporters.delete(clientMetadata.client_trace_id),30000); timer.unref() })
109
118
  trace.event('session.metadata',clientMetadata)
110
119
  if (!canUseVoice()) { fail('workspace_required'); return }
111
120
  connections.set(front, { mode, ready: false, trace })
@@ -117,6 +126,7 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
117
126
  const pending = []
118
127
  const startup = setTimeout(() => fail('voice_start_timeout'), 20000)
119
128
  let hintReporting=false,hintReported=false
129
+ let firstInput = false
120
130
  let resultPushConnection = null
121
131
  const sendUpstream = (data, binary) => {
122
132
  if (!binary) {
@@ -139,10 +149,11 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
139
149
  if (binary) {
140
150
  if (mode !== 'online' || !initialized) throw new Error('input_audio_disabled')
141
151
  forward(raw, true)
152
+ if (!firstInput) { firstInput=true; diagnostics.add({event:'proxy.first_input_audio',bytes:raw.length}) }
142
153
  return
143
154
  }
144
155
  const message = JSON.parse(raw.toString())
145
- if (message.type === 'client.diagnostic') return // captured locally, never fed to model
156
+ if (message.type === 'client.diagnostic') { diagnostics.add(message); return }
146
157
  if (message.type === 'client.connection_hint') {
147
158
  if(hintReporting&&!hintReported&&mode==='online'&&connections.get(front)?.ready){
148
159
  hintReported=true
@@ -161,7 +172,7 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
161
172
  if (initialized) throw new Error('voice_mode_requires_reconnect')
162
173
  initialized = true
163
174
  forward(JSON.stringify({ type: 'session.update',
164
- client: clientMetadata,
175
+ client: {...clientMetadata, diagnostics_protocol:DIAGNOSTICS_PROTOCOL},
165
176
  session: {
166
177
  type: 'realtime', preset_id: 'server_default',
167
178
  io_mode:mode === 'tts_only'?'external_only':'online',
@@ -207,6 +218,15 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
207
218
  selectedConfig = {...selected.route.config, endpoints: {online:selected.route.url,tts_only:selected.route.url}}
208
219
  trace.event('endpoint.selected', connectionRoute)
209
220
  back.on('message', (data, binary) => {
221
+ if (!binary) {
222
+ try {
223
+ const offer = JSON.parse(data.toString())
224
+ if (offer.type === 'client.diagnostics.ready') {
225
+ diagnostics.offer(offer, selectedConfig, selected.route.url)
226
+ return
227
+ }
228
+ } catch { /* Other frames follow normal validation. */ }
229
+ }
210
230
  trace.frame('upstream.receive', data, binary)
211
231
  if (!binary) {
212
232
  try {
@@ -216,6 +236,7 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
216
236
  rpcRequests.set(event.request_id, event.connection_id)
217
237
  }
218
238
  if (event.type === 'session.created') {
239
+ if (!diagnostics.target) { fail('voice_server_upgrade_required'); return }
219
240
  if (clientRPC && event.harness_sync?.protocol === 'harness_sync_v1') resultPushConnection = event.harness_sync.connection_id
220
241
  hintReporting=event.connection_hint_reporting===true
221
242
  if (clientRPC && event.session?.config?.harness_control_transport !== 'client_rpc_v1') { fail('harness_rpc_backend_upgrade_required'); return }
@@ -235,22 +256,26 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
235
256
  back.on('unexpected-response', (_request, response) => {
236
257
  response.resume()
237
258
  trace.event('upstream.handshake_failed', { status: response.statusCode })
259
+ diagnostics.add({event:'proxy.handshake_failed',status:response.statusCode})
238
260
  fail([429, 503].includes(response.statusCode) ? 'capacity_exhausted' : response.statusCode === 426 ? 'plugin_upgrade_required' : 'voice_upstream_unavailable')
239
261
  })
240
262
  back.on('close', (code, reason) => {
241
263
  trace.event('upstream.closed', { code, reason: reason.toString() })
264
+ diagnostics.add({event:'proxy.upstream_closed',code})
242
265
  clearTimeout(startup)
243
266
  if (code === 1013) fail('capacity_exhausted')
244
267
  else front.close(code === 1000 ? 1000 : 1011)
245
268
  })
246
269
  for (const [data, binary] of pending.splice(0)) sendUpstream(data, binary)
247
270
  })().catch(error => {
271
+ diagnostics.add({event:'proxy.handshake_failed',status:error.status})
248
272
  if (!opening.signal.aborted) fail([429,503].includes(error.status)?'capacity_exhausted':error.status===426?'plugin_upgrade_required':'voice_upstream_unavailable')
249
273
  })
250
274
  front.on('error', error => { trace.event('browser.error', { message: error.message }); opening.abort(); back?.close() })
251
275
  front.on('close', (code, reason) => {
276
+ diagnostics.add({event:'proxy.browser_closed',code})
252
277
  trace.event('rpc.pending_at_close', { request_ids: [...rpcRequests.keys()] })
253
- opening.abort(); clearTimeout(startup); back?.close()
278
+ opening.abort(); clearTimeout(startup); back?.close(1000, 'duet_browser_closed')
254
279
  const timer = setTimeout(() => back?.terminate(), 1000)
255
280
  timer.unref()
256
281
  })
@@ -264,6 +289,12 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
264
289
  connecting: [...connections.values()].filter(c => !c.ready).length,
265
290
  traces: [...connections.values()].map(c => c.trace.snapshot()),
266
291
  })
292
+ dispose.reportDiagnostic = (req, row) => {
293
+ const entry = reporters.get(row?.client_trace_id)
294
+ if (!entry || entry.page_id !== row.page_id) return
295
+ if (entry.user && feedback?.user(req) !== entry.user) return
296
+ entry.diagnostics.add(row)
297
+ }
267
298
  dispose.closeConnections = code => {
268
299
  for (const socket of connections.keys()) {
269
300
  if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ type: 'error', error: { code } }))
@@ -0,0 +1,31 @@
1
+ /** Only structural connection diagnostics may leave the user's DSH. */
2
+ export const DIAGNOSTICS_PROTOCOL = 'client_diagnostics_v1'
3
+ const events = new Set([
4
+ 'browser.connection_start', 'browser.connection_close', 'browser.pagehide',
5
+ 'browser.audio_prepare_started', 'browser.audio_prepare_failed', 'browser.audio_ready',
6
+ 'browser.microphone_started', 'browser.microphone_granted', 'browser.microphone_failed',
7
+ 'browser.capture_started', 'browser.capture_failed', 'browser.first_input_audio',
8
+ 'browser.server_error', 'browser.message_failed', 'browser.ws_closed', 'browser.ws_error',
9
+ 'browser.open_failed', 'proxy.failed', 'proxy.handshake_failed', 'proxy.upstream_closed',
10
+ 'proxy.browser_closed', 'proxy.first_input_audio',
11
+ ])
12
+ const reasons = new Set(['user_off', 'mode_switch', 'idle_release', 'page_unload', 'unmount', 'error', 'reconnect', 'settings_changed', 'unknown'])
13
+ const names = new Set(['NotAllowedError', 'NotFoundError', 'NotReadableError', 'OverconstrainedError', 'SecurityError', 'AbortError', 'InvalidStateError', 'NotSupportedError', 'TypeError', 'Error'])
14
+ export function diagnosticPayload(value) {
15
+ if (!value || !events.has(value.event)) return null
16
+ const out = { event: value.event }
17
+ for (const key of ['event_id', 'client_trace_id', 'page_id']) if (typeof value[key] === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(value[key])) out[key] = value[key]
18
+ for (const key of ['plugin_version', 'host_version']) if (typeof value[key] === 'string' && /^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(value[key]) && value[key].length <= 64) out[key] = value[key]
19
+ for (const key of ['elapsed_ms', 'buffered_bytes', 'bytes', 'context_sample_rate', 'base_latency', 'status']) if (Number.isFinite(value[key]) && value[key] >= 0 && value[key] <= 1e12) out[key] = value[key]
20
+ if (Number.isInteger(value.code) && value.code >= 1000 && value.code <= 4999) out.code = value.code
21
+ // Never send arbitrary exception messages, stack traces, device labels or URLs.
22
+ if (typeof value.code === 'string' && /^[a-z][a-z0-9_]{0,63}$/.test(value.code)) out.code = value.code
23
+ if (value.name) out.name = names.has(value.name) ? value.name : 'OtherError'
24
+ if (value.reason) out.reason = reasons.has(value.reason) ? value.reason : 'unknown'
25
+ for (const key of ['mode', 'mode_to']) if (['off', 'online', 'tts_only'].includes(value[key])) out[key] = value[key]
26
+ if (['running', 'suspended', 'closed', 'interrupted'].includes(value.context_state)) out.context_state = value.context_state
27
+ if (['visible', 'hidden'].includes(value.visibility)) out.visibility = value.visibility
28
+ if (['permission', 'capture', 'audio_context', 'opening'].includes(value.phase)) out.phase = value.phase
29
+ if (typeof value.was_clean === 'boolean') out.was_clean = value.was_clean
30
+ return out
31
+ }
@@ -3,6 +3,23 @@ import { sessionLabel } from './catalog.mjs'
3
3
  export const MAX_RESULT_TEXT_LENGTH = 8000
4
4
  export const LONG_RESULT_NOTICE = '这条任务消息内容较长,请在 DSH 会话中查看完整内容。'
5
5
 
6
+ /** DSH errors may be serialized objects, not Error instances or strings. */
7
+ export function taskErrorText(error, fallback = '任务执行失败,请在 DSH 中查看详情。') {
8
+ const seen = new Set()
9
+ const message = (value, depth = 0) => {
10
+ if (typeof value === 'string') {
11
+ const text = value.trim()
12
+ return text && text !== '[object Object]' ? text : ''
13
+ }
14
+ if (!value || typeof value !== 'object' || depth > 4 || seen.has(value)) return ''
15
+ seen.add(value)
16
+ // Do not serialize arbitrary response bodies, headers, stacks or credentials.
17
+ return message(value.message, depth + 1) || message(value.error, depth + 1)
18
+ || message(value.cause, depth + 1)
19
+ }
20
+ return message(error) || fallback
21
+ }
22
+
6
23
  /** Never truncate code into a misleading summary. The full result stays in DSH. */
7
24
  export function broadcastText(text) {
8
25
  if (typeof text !== 'string') throw Error('invalid_external_message')
@@ -14,6 +31,7 @@ export function resultNotification(job, name) {
14
31
  type: 'external_message', message_id: `harness_${job.id}`,
15
32
  source: { session_id: job.session_id, session_name: sessionLabel(name, job.session_id),
16
33
  job_id: job.id, status: job.status === 'succeeded' ? 'completed' : 'failed' },
17
- text: broadcastText((job.status === 'succeeded' ? job.result : (job.error || job.result)) || '未返回结果。'),
34
+ text: broadcastText(job.status === 'succeeded' ? (job.result || '未返回结果。')
35
+ : taskErrorText(job.error || job.result)),
18
36
  }
19
37
  }
@@ -1,5 +1,5 @@
1
1
  /** Desired voice mode is independent of a temporarily suspended connection. */
2
- export const PLUGIN_VERSION = '0.1.8'
2
+ export const PLUGIN_VERSION = '0.1.9'
3
3
  export const IDLE_RELEASE_MS = 60_000
4
4
 
5
5
  const safeVersion = value => typeof value === 'string' && value.length <= 32 && /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value) ? value : ''
@@ -41,25 +41,26 @@ export class DuetState {
41
41
  toggleMic() { return this.setMode(this.mode === 'online' ? 'off' : 'online') }
42
42
  toggleSpeaker() { return this.setMode(this.mode === 'tts_only' ? 'off' : 'tts_only') }
43
43
 
44
- async setMode(mode) {
44
+ async setMode(mode, details = {}) {
45
45
  if (!['off', 'tts_only', 'online'].includes(mode)) throw new Error('invalid_voice_mode')
46
46
  if (mode === this.mode && !this.suspended) return
47
+ const reason = details.reason || (mode === 'off' ? 'user_off' : 'mode_switch')
47
48
  this.mode = mode
48
49
  this.suspended = false
49
50
  this.idleSince = null
50
51
  if (mode === 'off') this.pending.clear()
51
52
  // Online notifications belong to the negotiated Harness stream (or legacy adapter).
52
53
  if (mode === 'online') this.pending.clear()
53
- await this.replaceConnection()
54
+ await this.replaceConnection({...details, reason, mode_to:mode})
54
55
  }
55
56
 
56
- async replaceConnection() {
57
+ async replaceConnection(details = {reason:'reconnect'}) {
57
58
  const generation = ++this.generation
58
59
  const previous = this.connection
59
60
  this.connection = null
60
61
  this.ready = false
61
62
  this.sent.clear()
62
- if (previous) this.retiring = this.retiring.then(() => previous.close()).catch(() => {})
63
+ if (previous) this.retiring = this.retiring.then(() => previous.close(details)).catch(() => {})
63
64
  this.changed(this)
64
65
  await this.retiring
65
66
  if (generation !== this.generation || this.mode === 'off' || this.suspended) return
@@ -103,7 +104,7 @@ export class DuetState {
103
104
  const compatibility = compatibilityNotice(code, details, this.mode)
104
105
  if (compatibility) {
105
106
  this.notice(compatibility, { upgrade: code !== 'client_version_unsupported' })
106
- void this.setMode('off')
107
+ void this.setMode('off', {reason:'error',code})
107
108
  return
108
109
  }
109
110
  const policyNotices = {
@@ -117,19 +118,20 @@ export class DuetState {
117
118
  harness_sync_failed: '无法继续同步 DSH 会话,语音已关闭。请检查 DSH 后重新开启。',
118
119
  interaction_mode_unavailable: '交互模式暂时不可用,请稍后再试',
119
120
  broadcast_mode_unavailable: '播报模式暂时不可用,请稍后再试',
121
+ voice_server_upgrade_required: '语音服务版本需要更新,请联系服务管理员。',
120
122
  client_protocol_unsupported: '插件与服务器协议不兼容,请更新插件或联系服务管理员',
121
123
  client_version_unsupported: '当前插件版本暂不受服务器支持,请联系服务管理员',
122
124
  }
123
125
  if (policyNotices[code]) {
124
126
  this.notice(policyNotices[code])
125
- void this.setMode('off')
127
+ void this.setMode('off', {reason:'error',code})
126
128
  return
127
129
  }
128
130
  const busy = ['capacity_exhausted', 'server_busy', 'external_message_queue_full', 'busy'].includes(code)
129
131
  const upgrade = code === 'plugin_upgrade_required'
130
132
  const backendUpgrade = ['harness_result_backend_upgrade_required', 'harness_rpc_backend_upgrade_required'].includes(code)
131
133
  this.notice(code === 'voice_settings_changed' ? '连接配置已更新,请重新打开语音' : upgrade ? '请升级 duet 插件后再连接' : backendUpgrade ? '语音服务器需要更新协议,请稍后再试' : busy ? '服务器忙,请稍后再试' : code === 'voice_tab_in_use' ? '另一个 Harness 页面正在使用语音' : '语音连接不可用,请稍后重试')
132
- void this.setMode('off')
134
+ void this.setMode('off', {reason:'error',code})
133
135
  }
134
136
 
135
137
  update({ hidden, running, state, results = [] }) {
@@ -172,9 +174,9 @@ export class DuetState {
172
174
  this.idleSince ??= this.now()
173
175
  if (!this.suspended && this.now() - this.idleSince >= IDLE_RELEASE_MS) {
174
176
  this.suspended = true
175
- void this.replaceConnection()
177
+ void this.replaceConnection({reason:'idle_release'})
176
178
  }
177
179
  }
178
180
 
179
- async dispose() { await this.setMode('off'); await this.retiring }
181
+ async dispose() { await this.setMode('off', {reason:'unmount'}); await this.retiring }
180
182
  }