dsh-duet 0.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 (40) hide show
  1. package/HEROICONS-LICENSE.txt +24 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +77 -0
  5. package/deepseek_harness_duplex_control.patch.yml +3 -0
  6. package/deepseek_harness_duplex_control_plugin.html +392 -0
  7. package/deepseek_harness_duplex_control_plugin.mjs +1105 -0
  8. package/deepseek_harness_duplex_focus_client/lib/client.js +466 -0
  9. package/deepseek_harness_voice_audio.mjs +135 -0
  10. package/deepseek_harness_voice_browser.mjs +343 -0
  11. package/deepseek_harness_voice_catalog.mjs +56 -0
  12. package/deepseek_harness_voice_composer.mjs +125 -0
  13. package/deepseek_harness_voice_consent.mjs +63 -0
  14. package/deepseek_harness_voice_feedback.mjs +48 -0
  15. package/deepseek_harness_voice_feedback_files.mjs +55 -0
  16. package/deepseek_harness_voice_feedback_store.mjs +51 -0
  17. package/deepseek_harness_voice_interactions.mjs +32 -0
  18. package/deepseek_harness_voice_microphone.mjs +59 -0
  19. package/deepseek_harness_voice_notices.mjs +54 -0
  20. package/deepseek_harness_voice_proxy.mjs +223 -0
  21. package/deepseek_harness_voice_rpc.mjs +104 -0
  22. package/deepseek_harness_voice_service_info.mjs +45 -0
  23. package/deepseek_harness_voice_settings.mjs +95 -0
  24. package/deepseek_harness_voice_shortcuts.mjs +69 -0
  25. package/deepseek_harness_voice_state.mjs +171 -0
  26. package/deepseek_harness_voice_trace.mjs +107 -0
  27. package/deepseek_harness_voice_tutorial.mjs +265 -0
  28. package/deepseek_harness_voice_tutorial_adapter.mjs +95 -0
  29. package/deepseek_harness_voice_tutorial_request.mjs +16 -0
  30. package/package.json +57 -0
  31. package/tutorial-audio/broadcast.wav +0 -0
  32. package/tutorial-audio/clear.wav +0 -0
  33. package/tutorial-audio/edit.wav +0 -0
  34. package/tutorial-audio/input.wav +0 -0
  35. package/tutorial-audio/manifest.json +60 -0
  36. package/tutorial-audio/modes_broadcast.wav +0 -0
  37. package/tutorial-audio/modes_interaction.wav +0 -0
  38. package/tutorial-audio/reinput.wav +0 -0
  39. package/tutorial-audio/send.wav +0 -0
  40. package/tutorial-audio/switch.wav +0 -0
@@ -0,0 +1,343 @@
1
+ import { VoiceState, PLUGIN_VERSION } from './deepseek_harness_voice_state.mjs?v=0.1.0'
2
+ import { VoiceAudio } from './deepseek_harness_voice_audio.mjs?v=0.1.0'
3
+ import { HarnessRPCExecutor } from './deepseek_harness_voice_rpc.mjs?v=0.1.0'
4
+ import { composerAccess, observeComposer, focusedSession } from './deepseek_harness_voice_composer.mjs?v=0.1.0'
5
+ import { mountTutorial } from './deepseek_harness_voice_tutorial.mjs?v=0.1.0'
6
+ import { tutorialAdapter } from './deepseek_harness_voice_tutorial_adapter.mjs?v=0.1.0'
7
+ import { mountRating } from './deepseek_harness_voice_feedback.mjs?v=0.1.0'
8
+ import { createAudioUploadConsent } from './deepseek_harness_voice_consent.mjs?v=0.1.0'
9
+ import { bindVoiceShortcuts } from './deepseek_harness_voice_shortcuts.mjs?v=0.1.0'
10
+ import { nativeInteractions } from './deepseek_harness_voice_interactions.mjs?v=0.1.0'
11
+
12
+ export function mountVoice(ctx) {
13
+ const audio = new VoiceAudio()
14
+ const audioConsent = createAudioUploadConsent()
15
+ let disposed = false, controls, toastTimer, pollRunning = false, cursor = null, resultEpoch = null
16
+ const labels = new Map()
17
+ let clientTraceId = null, diagnosticCount = 0
18
+ let tutorial, teaching, ratingPanel
19
+ const diagnostic = data => {
20
+ if (++diagnosticCount > 100) return
21
+ const bounded = Object.fromEntries(Object.entries(data).map(([k, v]) => [k, typeof v === 'string' ? v.slice(0, 4000) : v]))
22
+ const body = JSON.stringify({ client_trace_id: clientTraceId, plugin_version: PLUGIN_VERSION,
23
+ utc: new Date().toISOString(), visibility: document.visibilityState, ...bounded })
24
+ if (body.length > 24000) return
25
+ void fetch('/duplex-control/api/voice/diagnostic', { method: 'POST', credentials: 'same-origin',
26
+ headers: { 'Content-Type': 'application/json', 'X-Duplex-Settings': '1' }, body, keepalive: true }).catch(() => {})
27
+ }
28
+ const pageError = event => diagnostic({ event: 'browser.error', message: String(event.message || event.reason?.message || event.reason), stack: event.error?.stack || event.reason?.stack })
29
+ window.addEventListener('error', pageError)
30
+ window.addEventListener('unhandledrejection', pageError)
31
+ const notice = (text, { upgrade = false } = {}) => {
32
+ if (upgrade) { ratingPanel?.dispose(); ratingPanel = null }
33
+ const toast = controls?.querySelector('[role=status]')
34
+ if (!toast) return
35
+ toast.textContent = text
36
+ toast.hidden = false
37
+ clearTimeout(toastTimer)
38
+ if (upgrade) {
39
+ const help = document.createElement('details')
40
+ const title = document.createElement('summary')
41
+ title.textContent = '如何升级'
42
+ help.append(title)
43
+ const instruction = document.createElement('p')
44
+ instruction.textContent = '通过 npm 安装的用户,可在终端运行:'
45
+ const command = document.createElement('code')
46
+ command.textContent = 'dsh plugin --profile web add dsh-duet@latest'
47
+ command.style.cssText = 'display:block;white-space:normal;overflow-wrap:anywhere;margin:8px 0'
48
+ const after = document.createElement('p')
49
+ after.textContent = '其他安装方式请从原来源更新。完成后重启 DSH 并刷新页面,再手动开启语音。'
50
+ help.append(instruction, command, after)
51
+ const dismiss = document.createElement('button')
52
+ dismiss.textContent = '知道了'
53
+ dismiss.onclick = () => { toast.hidden = true }
54
+ toast.append(help, dismiss)
55
+ } else toastTimer = setTimeout(() => { toast.hidden = true }, 8000)
56
+ }
57
+ const draw = state => {
58
+ if (!controls) return
59
+ for (const [kind, active] of [['mic', state.mode === 'online'], ['speaker', state.mode === 'tts_only']]) {
60
+ const button = controls.querySelector(`[data-voice=${kind}]`)
61
+ button.setAttribute('aria-pressed', String(active))
62
+ button.setAttribute('aria-label', `${active ? '关闭' : '打开'}${kind === 'mic' ? '交互模式' : '播报模式'}`)
63
+ button.title = button.getAttribute('aria-label')
64
+ const pending = active && !state.ready && !state.suspended
65
+ button.style.background = active && !pending ? '#dcefff' : 'transparent'
66
+ button.style.color = active && !pending ? '#185a89' : 'currentColor'
67
+ button.dataset.pending = String(pending)
68
+ button.setAttribute('aria-busy', String(pending))
69
+ button.querySelector('[data-connecting-ring]').hidden = !pending
70
+ if (pending) button.title = `正在开启${kind === 'mic' ? '交互模式' : '播报模式'}`
71
+ }
72
+ // Suspended/idle-countdown is intentionally not exposed as a fourth UI mode.
73
+ controls.dataset.mode = state.mode
74
+ const mark = controls.querySelector('[data-duet-mark]')
75
+ mark.style.color = state.ready ? '#7fd6a6' : '#ed9b35'
76
+ mark.title = state.ready ? '语音已连接' : '语音未连接'
77
+ }
78
+ const connect = (mode, receive) => {
79
+ if (!audioConsent.granted()) throw Error('data_upload_consent_required')
80
+ clientTraceId = crypto.randomUUID(); diagnosticCount = 0
81
+ const connectionTraceId = clientTraceId
82
+ const report = data => diagnostic({ ...data, client_trace_id: connectionTraceId, mode })
83
+ let ws, closed = false, release, ready = false, stopComposer
84
+ const send = message => {
85
+ if (ws?.readyState !== WebSocket.OPEN || closed) return
86
+ if (ws.bufferedAmount > 1_000_000) { receive({ type: 'error', code: 'voice_backpressure' }); return }
87
+ ws.send(message instanceof ArrayBuffer ? message : JSON.stringify(message))
88
+ }
89
+ const composer = composerAccess(ctx, id => labels.get(id) || id)
90
+ const interactions = nativeInteractions(ctx)
91
+ const rpc = new HarnessRPCExecutor(send, fetch, report, async (request, signal) =>
92
+ (await interactions(request, signal)) ?? composer.execute(request, signal))
93
+ const connection = {
94
+ feedbackTicket: null,
95
+ send,
96
+ sendState: state => { if (state) send({ type: 'harness.state', state }) },
97
+ playing: () => audio.playing(),
98
+ async close() {
99
+ report({ event: 'browser.connection_close', buffered_bytes: ws?.bufferedAmount })
100
+ closed = true
101
+ stopComposer?.()
102
+ rpc.close()
103
+ audio.stop()
104
+ if (ws && ws.readyState !== WebSocket.CLOSED) {
105
+ await new Promise(resolve => {
106
+ const timer = setTimeout(resolve, 1200)
107
+ ws.addEventListener('close', () => { clearTimeout(timer); resolve() }, { once: true })
108
+ if (ws.readyState < WebSocket.CLOSING) ws.close(1000)
109
+ })
110
+ }
111
+ release?.()
112
+ },
113
+ }
114
+ const open = async () => {
115
+ if (closed) return
116
+ // Establish/renew the host-signed anonymous cookie before the WS handshake.
117
+ const identity=await fetch('/duplex-control/api/voice/config',{credentials:'same-origin',cache:'no-store'})
118
+ if(!identity.ok)throw Error('voice_config_unavailable')
119
+ if(closed)return
120
+ const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:'
121
+ ws = new WebSocket(`${protocol}//${location.host}/duplex-control/voice/ws?mode=${mode}&plugin_version=${PLUGIN_VERSION}&client_trace_id=${connectionTraceId}`)
122
+ ws.onopen = () => {
123
+ send({ type: 'session.update' })
124
+ if (mode === 'online') stopComposer = observeComposer(ctx, composer, send)
125
+ }
126
+ ws.onmessage = async event => {
127
+ if (closed) return
128
+ let message
129
+ try {
130
+ message = JSON.parse(event.data)
131
+ if (message.type === 'harness.rpc.request') {
132
+ if (mode !== 'online') throw new Error('harness_rpc_requires_online')
133
+ await rpc.execute(message)
134
+ return
135
+ }
136
+ if (message.type === 'error') {
137
+ report({ event: 'browser.server_error', code: message.error?.code || message.code,
138
+ message: message.error?.message || message.message })
139
+ receive({ type: 'error', code: message.error?.code || message.code,
140
+ compatibility: message.error?.compatibility, policy: message.error?.policy }); return
141
+ }
142
+ if (message.type === 'session.created' && !ready) {
143
+ if (message.compatibility) receive({ type: 'compatibility', compatibility: message.compatibility })
144
+ connection.feedbackTicket = message.feedback_session_ticket || null
145
+ ready = true
146
+ await audio.prepare()
147
+ if (closed) return
148
+ if (mode === 'online') {
149
+ try { await audio.startMic(send) }
150
+ catch (error) {
151
+ report({ event: 'browser.microphone_failed', name: error?.name })
152
+ if (!closed) receive({ type: 'error', code: 'microphone_unavailable' })
153
+ return
154
+ }
155
+ }
156
+ report({ event: 'browser.audio_ready', context_sample_rate: audio.context?.sampleRate,
157
+ context_state: audio.context?.state, base_latency: audio.context?.baseLatency,
158
+ user_agent: navigator.userAgent })
159
+ if (!closed) {
160
+ receive({ type: 'ready' })
161
+ try { audio.connectedChime() } catch { /* A notification must not break voice. */ }
162
+ }
163
+ }
164
+ audio.event(message, send)
165
+ teaching?.observe(message)
166
+ receive(message)
167
+ } catch (error) {
168
+ report({ event: 'browser.message_failed', event_type: message?.type, request_id: message?.request_id,
169
+ path: message?.path, message: String(error?.message || error), stack: error?.stack })
170
+ if (!closed) receive({ type: 'error', code: 'voice_stream_failed' })
171
+ }
172
+ }
173
+ ws.onclose = event => {
174
+ stopComposer?.()
175
+ report({ event: 'browser.ws_closed', code: event.code, reason: event.reason, was_clean: event.wasClean })
176
+ rpc.close()
177
+ release?.()
178
+ if (!closed) receive({ type: 'error', code: event.code === 1013 ? 'capacity_exhausted' : 'voice_disconnected' })
179
+ }
180
+ ws.onerror = () => { report({ event: 'browser.ws_error' }); if (!closed) receive({ type: 'error', code: 'voice_connection_failed' }) }
181
+ }
182
+ if (navigator.locks) {
183
+ void navigator.locks.request('dsh-duplex-voice-owner', { ifAvailable: true }, async lock => {
184
+ if (closed) return
185
+ if (!lock) { receive({ type: 'error', code: 'voice_tab_in_use' }); return }
186
+ const held = new Promise(resolve => { release = resolve })
187
+ await open()
188
+ await held
189
+ }).catch(() => { if (!closed) receive({ type: 'error', code: 'voice_connection_failed' }) })
190
+ } else queueMicrotask(() => receive({ type: 'error', code: 'voice_lock_unavailable' }))
191
+ return connection
192
+ }
193
+ const state = new VoiceState({ connect, changed: draw, notice })
194
+ const mount = () => {
195
+ const entry = document.getElementById('dsh-duplex-control-entry')
196
+ if (!entry || document.getElementById('dsh-duplex-voice-controls')) return
197
+ controls = document.createElement('div')
198
+ controls.id = 'dsh-duplex-voice-controls'
199
+ controls.style.cssText = 'display:flex;gap:4px;position:relative;padding:6px 8px;align-items:center;margin:4px 8px;max-width:100%'
200
+ const style = document.createElement('style')
201
+ style.textContent = '@keyframes duet-connecting-snake{from{stroke-dashoffset:0}to{stroke-dashoffset:-100}} #dsh-duplex-voice-controls [data-connecting-ring]{position:absolute;inset:0;pointer-events:none} #dsh-duplex-voice-controls [data-connecting-ring] svg{display:block;width:100%;height:100%;overflow:visible} #dsh-duplex-voice-controls [data-connecting-ring] rect{fill:none;stroke:#ed9b35;stroke-width:2;stroke-linecap:round;stroke-dasharray:28 72;animation:duet-connecting-snake 1.6s linear infinite!important} #dsh-duplex-voice-controls [data-connecting-ring][hidden]{display:none}'
202
+ controls.append(style)
203
+ const parent = entry.parentElement
204
+ parent.insertBefore(controls, entry)
205
+ entry.style.cssText = 'font-family:Inter,"PingFang SC",sans-serif;font-size:28px;font-weight:700;letter-spacing:-1.1px;line-height:1.1;color:inherit;margin-right:auto;padding:4px;cursor:default;user-select:none'
206
+ entry.textContent = 'duet'
207
+ const dot = document.createElement('span')
208
+ dot.textContent = '.'; dot.dataset.duetMark = ''; dot.style.color = '#ed9b35'
209
+ entry.append(dot)
210
+ controls.append(entry)
211
+ // Heroicons 24/outline (MIT); all controls share the same optical box/stroke.
212
+ for (const [kind, path] of [['mic', '<path d="M7.5 3.75 3 8.25m0 0 4.5 4.5M3 8.25h18m-4.5 3L21 15.75m0 0-4.5 4.5M21 15.75H3"/>'], ['speaker', '<path d="M19.114 5.636a9 9 0 0 1 0 12.728M16.463 8.288a5.25 5.25 0 0 1 0 7.424M6.75 8.25l4.72-4.72a.75.75 0 0 1 1.28.53v15.88a.75.75 0 0 1-1.28.53l-4.72-4.72H4.51c-.88 0-1.704-.507-1.938-1.354A9.009 9.009 0 0 1 2.25 12c0-.83.112-1.633.322-2.396C2.806 8.756 3.63 8.25 4.51 8.25H6.75Z"/>']]) {
213
+ const button = document.createElement('button')
214
+ button.type = 'button'
215
+ button.dataset.voice = kind
216
+ button.style.cssText = 'position:relative;border:0;border-radius:6px;background:transparent;cursor:pointer;padding:5px;display:flex'
217
+ button.innerHTML = `<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${path}</svg>`
218
+ const ring = document.createElement('span')
219
+ ring.dataset.connectingRing = ''; ring.hidden = true; ring.setAttribute('aria-hidden', 'true')
220
+ // The rectangle stays fixed; only the short stroke advances around its
221
+ // perimeter. Outer radius 6 matches the original button, not a circle.
222
+ ring.innerHTML = '<svg viewBox="0 0 30 30" preserveAspectRatio="none" aria-hidden="true"><rect x="1" y="1" width="28" height="28" rx="5" pathLength="100"/></svg>'
223
+ button.append(ring)
224
+ button.onclick = () => {
225
+ if (tutorial?.active) { notice('请先结束教学,再切换模式。'); return }
226
+ const activate = () => {
227
+ if (disposed || tutorial?.active) return
228
+ // Unlock playback inside user activation, before any network await.
229
+ const enabling = kind === 'mic' ? state.mode !== 'online' : state.mode !== 'tts_only'
230
+ if (enabling) void audio.prepare().catch(() => state.fail('audio_permission_denied'))
231
+ const ticket = !enabling && state.ready ? state.connection?.feedbackTicket : null
232
+ // Capture the ended connection, never consult the next session after await.
233
+ void (async()=>{
234
+ await (kind === 'mic' ? state.toggleMic() : state.toggleSpeaker())
235
+ if(ticket && !disposed){ratingPanel?.dispose();ratingPanel=mountRating(controls,ticket)}
236
+ })()
237
+ }
238
+ audioConsent.cancel()
239
+ const mode = kind === 'mic' ? 'online' : 'tts_only'
240
+ if (state.mode !== mode) audioConsent.request(activate)
241
+ else activate()
242
+ }
243
+ controls.append(button)
244
+ }
245
+ const settings = document.createElement('a')
246
+ settings.href = '/duet/'
247
+ settings.target = '_blank'
248
+ settings.rel = 'noopener noreferrer'
249
+ settings.title = 'duet 设置'
250
+ settings.setAttribute('aria-label', 'duet 设置')
251
+ settings.style.cssText = 'display:flex;color:inherit;padding:5px;border-radius:6px'
252
+ settings.innerHTML = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.325.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 0 1 1.37.49l1.296 2.247a1.125 1.125 0 0 1-.26 1.431l-1.003.827c-.293.241-.438.613-.43.992a7.723 7.723 0 0 1 0 .255c-.008.378.137.75.43.991l1.004.827c.424.35.534.955.26 1.43l-1.298 2.247a1.125 1.125 0 0 1-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.47 6.47 0 0 1-.22.128c-.331.183-.581.495-.644.869l-.213 1.281c-.09.543-.56.94-1.11.94h-2.594c-.55 0-1.019-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 0 1-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 0 1-1.369-.49l-1.297-2.247a1.125 1.125 0 0 1 .26-1.431l1.004-.827c.292-.24.437-.613.43-.991a6.932 6.932 0 0 1 0-.255c.007-.38-.138-.751-.43-.992l-1.004-.827a1.125 1.125 0 0 1-.26-1.43l1.297-2.247a1.125 1.125 0 0 1 1.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.086.22-.128.332-.183.582-.495.644-.869l.214-1.28Z"/><path d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"/></svg>'
253
+ controls.append(settings)
254
+ const toast = document.createElement('div')
255
+ toast.setAttribute('role', 'status')
256
+ toast.setAttribute('aria-live', 'polite')
257
+ toast.hidden = true
258
+ toast.style.cssText = 'position:absolute;bottom:100%;left:0;z-index:9999;min-width:180px;max-width:280px;background:#252c38;color:white;padding:10px;border-radius:8px;font-size:12px;box-shadow:0 3px 18px #0005'
259
+ controls.append(toast)
260
+ draw(state)
261
+ }
262
+ mount()
263
+ const stopShortcuts = bindVoiceShortcuts(kind => controls?.querySelector(`[data-voice=${kind}]`)?.click())
264
+ const observer = new MutationObserver(mount)
265
+ observer.observe(document.body, { subtree: true, childList: true })
266
+
267
+ const api = async path => {
268
+ const response = await fetch(`/duplex-control/api/${path}`, { cache: 'no-store',
269
+ headers: { 'X-Duet-Native-Interactions': '1' } })
270
+ if (!response.ok) throw new Error('harness_unavailable')
271
+ return response.json()
272
+ }
273
+ const poll = async () => {
274
+ if (disposed || pollRunning) return
275
+ pollRunning = true
276
+ try {
277
+ const [catalog, completed, health] = await Promise.all([api('sessions'), api(`results?after=${cursor ?? 0}&limit=100`), api('health')])
278
+ if (disposed) return
279
+ for (const s of catalog.sessions) labels.set(s.session_id, s.label)
280
+ const bootstrap = cursor === null || resultEpoch !== health.focus_epoch
281
+ resultEpoch = health.focus_epoch
282
+ cursor = bootstrap ? completed.current_cursor : completed.next_cursor
283
+ let composer
284
+ const id = focusedSession(ctx)
285
+ const scope = id ? ctx.sessions.scope(id) : undefined
286
+ if (scope) {
287
+ try { composer = { session_name: labels.get(id) || id, text: ctx.conversation.input.for(scope).state.getSnapshot().draft } } catch { /* Session input is still mounting; do not invent an empty draft. */ }
288
+ }
289
+ state.update({
290
+ hidden: document.visibilityState !== 'visible',
291
+ running: catalog.sessions.some(s => s.running),
292
+ state: { focused_session_id: id || null, ...(composer ? { composer_state: composer } : {}), sessions: catalog.sessions.map(s => ({ session_id: s.session_id, session_name: s.label, running: s.running })) },
293
+ results: bootstrap ? [] : completed.results.map(job => ({
294
+ type: 'external_message', message_id: `harness_${job.id}`,
295
+ source: { session_id: job.session_id, session_name: labels.get(job.session_id) || job.session_id,
296
+ job_id: job.id, status: job.status === 'succeeded' ? 'completed' : 'failed' },
297
+ text: (job.status === 'succeeded' ? job.result : (job.error || job.result)) || '未返回结果。',
298
+ })),
299
+ })
300
+ } catch (error) {
301
+ if (state.mode !== 'off') {
302
+ diagnostic({ event: 'browser.poll_failed', message: String(error?.message || error), stack: error?.stack })
303
+ state.fail('harness_unavailable')
304
+ }
305
+ }
306
+ finally { pollRunning = false }
307
+ }
308
+ const timer = setInterval(() => { void poll(); state.tick() }, 1000)
309
+ const progress = setInterval(() => { if (state.connection) audio.progress(state.connection.send) }, 200)
310
+ const visibility = () => { state.hidden = document.visibilityState !== 'visible'; state.tick(); void poll() }
311
+ document.addEventListener('visibilitychange', visibility)
312
+ void poll()
313
+ teaching = tutorialAdapter(ctx, state, audio, async signal => {
314
+ await audioConsent.ensure(signal)
315
+ const deadline = Date.now() + 15000
316
+ while (cursor === null) {
317
+ signal.throwIfAborted()
318
+ if (Date.now() > deadline) throw Error('会话结果同步尚未就绪,请稍后重试教学')
319
+ await poll(); await new Promise(resolve => setTimeout(resolve, 150))
320
+ }
321
+ })
322
+ const mountTeaching = () => {
323
+ if (!tutorial && controls) tutorial = mountTutorial({ controls, adapter: teaching })
324
+ }
325
+ mountTeaching()
326
+ const teachingObserver = new MutationObserver(mountTeaching)
327
+ teachingObserver.observe(document.body, { subtree: true, childList: true })
328
+ return () => {
329
+ disposed = true
330
+ stopShortcuts()
331
+ observer.disconnect()
332
+ teachingObserver.disconnect()
333
+ tutorial?.dispose()
334
+ audioConsent.cancel()
335
+ ratingPanel?.dispose()
336
+ clearInterval(timer); clearInterval(progress); clearTimeout(toastTimer)
337
+ document.removeEventListener('visibilitychange', visibility)
338
+ window.removeEventListener('error', pageError)
339
+ window.removeEventListener('unhandledrejection', pageError)
340
+ controls?.remove()
341
+ void state.dispose().finally(() => audio.context?.close())
342
+ }
343
+ }
@@ -0,0 +1,56 @@
1
+ /** Mirror DSH workspace order, never the global activity-sorted search list. */
2
+ export const WORKSPACE_VIEW_KEY = 'dsh.workspace.view.v5'
3
+
4
+ export function readWorkspaceView() {
5
+ try { return JSON.parse(globalThis.localStorage?.getItem(WORKSPACE_VIEW_KEY) || '{}') || {} }
6
+ catch { return {} }
7
+ }
8
+
9
+ function reconcile(rows, ids) {
10
+ const byId = new Map(rows.map(row => [row.session_id, row]))
11
+ const ordered = []
12
+ for (const id of Array.isArray(ids) ? ids : []) {
13
+ if (!byId.has(id)) continue
14
+ ordered.push(byId.get(id)); byId.delete(id)
15
+ }
16
+ return [...ordered, ...byId.values()]
17
+ }
18
+
19
+ export function orderSessionCatalog(rows, view = {}) {
20
+ const visible = rows.filter(row => !row.archived && row.origin !== 'subagent' && (!row.blank || row.active))
21
+ const accounts = view?.sessionOrderByAccount || {}
22
+ if (view?.groupBy === 'flat') {
23
+ const recent = [...visible].sort((a,b) => (b.updated_at || 0) - (a.updated_at || 0)
24
+ || String(a.session_id).localeCompare(String(b.session_id)))
25
+ return reconcile(recent, accounts.__flat_session_order__)
26
+ }
27
+ const groups = new Map()
28
+ for (const row of visible) {
29
+ const key = row.workspace_id || ''
30
+ if (!groups.has(key)) groups.set(key, [])
31
+ groups.get(key).push(row)
32
+ }
33
+ return [...groups].flatMap(([key, members]) => reconcile(members, accounts[key]))
34
+ }
35
+
36
+ export function buildSessionCatalog(items, {workspaces = [], archivedIds = [], activeId, includeBlank = false} = {}) {
37
+ const archived = new Set(archivedIds)
38
+ const byId = new Map(items.filter(item => !archived.has(item.sessionId)
39
+ && item.origin !== 'subagent' && (includeBlank || !item.blank || item.sessionId === activeId))
40
+ .map(item => [item.sessionId, item]))
41
+ const result = []
42
+ const add = (id, workspaceId) => {
43
+ const item = byId.get(id)
44
+ if (!item) return
45
+ byId.delete(id)
46
+ result.push({session_id:id, label:item.projections?.values?.title || id,
47
+ active:id === activeId, running:item.running, updated_at:item.updatedAt,
48
+ cwd:item.cwd || '', workspace_id:workspaceId, archived:false,
49
+ blank:!!item.blank, origin:item.origin})
50
+ }
51
+ for (const workspace of workspaces) {
52
+ for (const id of workspace.sessionIds || []) add(id, workspace.id || workspace.workspaceId || '')
53
+ }
54
+ for (const id of [...byId.keys()]) add(id, '')
55
+ return result
56
+ }
@@ -0,0 +1,125 @@
1
+ /** Browser-owned drafts: bounded snapshots and explicit overwrite/CAS edit policies. */
2
+ const fail = code => { const error = new Error(code); error.code = code; throw error }
3
+ const hash = async text => [...new Uint8Array(await crypto.subtle.digest('SHA-256',
4
+ new TextEncoder().encode(text)))].map(v => v.toString(16).padStart(2, '0')).join('')
5
+
6
+ export function focusedSession(ctx) {
7
+ const snapshot = ctx.sessions.list.getSnapshot()
8
+ if ('current' in snapshot) return snapshot.current || null
9
+ const selected = Object.entries(snapshot.byId || {}).filter(([, row]) => row.retainedBy?.mainView > 0)
10
+ return selected.length === 1 ? selected[0][0] : null
11
+ }
12
+
13
+ export function composerAccess(ctx, label = id => id) {
14
+ const focused = () => focusedSession(ctx)
15
+ const inputFor = id => {
16
+ const scope = id && ctx.sessions.scope(id)
17
+ if (!scope) fail('session_not_ready')
18
+ return ctx.conversation.input.for(scope)
19
+ }
20
+ const snapshot = async (id, input, stable = true) => {
21
+ const before = input.state.getSnapshot()
22
+ if (typeof before.draft !== 'string' || new TextEncoder().encode(before.draft).length > 64_000
23
+ || !Number.isSafeInteger(before.draftRev) || before.draftRev < 0) fail('invalid_composer_snapshot')
24
+ const digest = await hash(before.draft)
25
+ const live = input.state.getSnapshot()
26
+ if (stable && (live.draft !== before.draft || live.draftRev !== before.draftRev || live.phase !== before.phase)) fail('draft_conflict')
27
+ return { session_id: id, session_name: label(id), text: before.draft,
28
+ revision: before.draftRev, hash: digest, phase: before.phase }
29
+ }
30
+ const read = async () => {
31
+ const id = focused()
32
+ if (!id) return null
33
+ const value = await snapshot(id, inputFor(id))
34
+ if (focused() !== id) fail('focus_conflict')
35
+ return value
36
+ }
37
+ const execute = async (request, signal) => {
38
+ signal?.throwIfAborted()
39
+ if (request.method === 'GET' && request.path === '/api/composer/focused') {
40
+ const value = await read()
41
+ if (!value) fail('session_not_ready')
42
+ return { composer: value }
43
+ }
44
+ const match = request.path.match(/^\/api\/sessions\/([A-Za-z0-9_-]+)\/composer$/)
45
+ if (request.method !== 'PUT' || !match) return undefined
46
+ const id = match[1], payload = request.payload || {}, input = inputFor(id)
47
+ const overwrite = payload.overwrite === true
48
+ const before = overwrite ? null : await snapshot(id, input)
49
+ signal?.throwIfAborted()
50
+ if (payload.require_focus && focused() !== id) fail('focus_conflict')
51
+ if (typeof payload.text !== 'string' || new TextEncoder().encode(payload.text).length > 64_000) fail('invalid_composer_text')
52
+ // No await between checking the live value and the synchronous write.
53
+ const live = input.state.getSnapshot()
54
+ if (live.phase !== 'plain') fail('composer_busy')
55
+ if (!overwrite && (before.revision !== payload.expected_revision || before.hash !== payload.expected_hash
56
+ || live.draftRev !== before.revision || live.draft !== before.text || live.phase !== before.phase)) fail('draft_conflict')
57
+ input.setDraft(payload.text)
58
+ // Capture the committed value synchronously; later keystrokes must not turn
59
+ // a successful overwrite into a spurious conflict during asynchronous hashing.
60
+ return { composer: await snapshot(id, input, false) }
61
+ }
62
+ return { read, execute, focused, inputFor }
63
+ }
64
+
65
+ export class ComposerPublisher {
66
+ constructor(read, send, { now = Date.now, later = setTimeout, cancel = clearTimeout } = {}) {
67
+ Object.assign(this, { read, send })
68
+ // Window timer functions reject a class instance as their receiver.
69
+ this.now = () => now()
70
+ this.later = (fn, ms) => later(fn, ms)
71
+ this.cancel = timer => cancel(timer)
72
+ this.last = -Infinity; this.sequence = 0; this.closed = false; this.running = false
73
+ this.dirty = false; this.timer = null; this.epoch = 0
74
+ }
75
+ changed({ focus = false } = {}) {
76
+ if (this.closed) return
77
+ this.dirty = true
78
+ if (focus) { this.epoch++; this.last = -Infinity }
79
+ if (this.running) return
80
+ this.cancel(this.timer)
81
+ this.timer = this.later(() => { this.timer = null; void this.publish() }, Math.max(0, this.last + 2000 - this.now()))
82
+ }
83
+ async publish() {
84
+ if (this.closed || this.running) return
85
+ this.running = true; this.dirty = false
86
+ const epoch = this.epoch
87
+ try {
88
+ const composer = await this.read()
89
+ if (!this.closed && epoch === this.epoch) {
90
+ this.send({ type: 'harness.composer.update', sequence: ++this.sequence, composer })
91
+ this.last = this.now()
92
+ }
93
+ } catch {
94
+ // Invalidate a previous good snapshot; never invent an empty draft.
95
+ if (!this.closed && epoch === this.epoch) {
96
+ this.send({ type: 'harness.composer.update', sequence: ++this.sequence, composer: null })
97
+ this.last = this.now()
98
+ }
99
+ } finally {
100
+ this.running = false
101
+ if (this.dirty) this.changed()
102
+ }
103
+ }
104
+ close() { this.closed = true; this.cancel(this.timer) }
105
+ }
106
+
107
+ export function observeComposer(ctx, access, send) {
108
+ const publisher = new ComposerPublisher(access.read, send)
109
+ let id, input, unsubscribeInput
110
+ const bind = () => {
111
+ const nextId = access.focused()
112
+ let nextInput
113
+ try { nextInput = access.inputFor(nextId) } catch { /* unmounted */ }
114
+ if (nextId === id && nextInput === input) return
115
+ const focus = nextId !== id
116
+ unsubscribeInput?.(); id = nextId; input = nextInput
117
+ unsubscribeInput = input?.state.subscribe(() => publisher.changed())
118
+ publisher.changed({ focus })
119
+ }
120
+ const unsubscribe = ctx.sessions.list.subscribe(bind)
121
+ bind(); publisher.changed({ focus: true })
122
+ // Refresh unchanged snapshots so an idle browser remains a valid cache source.
123
+ const heartbeat = setInterval(() => { bind(); publisher.changed() }, 10_000)
124
+ return () => { clearInterval(heartbeat); unsubscribe(); unsubscribeInput?.(); publisher.close() }
125
+ }
@@ -0,0 +1,63 @@
1
+ /** Versioned permission for interaction audio and necessary session context. */
2
+ export const AUDIO_CONSENT_KEY = 'dsh-duet.data-upload-consent.v3'
3
+
4
+ export function createAudioUploadConsent(storage) {
5
+ const key = AUDIO_CONSENT_KEY
6
+ if (storage === undefined) {
7
+ try { storage = globalThis.localStorage } catch { storage = null }
8
+ }
9
+ let accepted = false, dialog = null, dismissed = null
10
+ const granted = () => {
11
+ try { return accepted || storage?.getItem(key) === 'accepted' }
12
+ catch { return accepted }
13
+ }
14
+ const cancel = (confirmed = false) => {
15
+ if (!dialog) return
16
+ const current = dialog; dialog = null
17
+ current.close(); current.remove()
18
+ const notify = dismissed; dismissed = null
19
+ if (!confirmed) notify?.()
20
+ }
21
+ const request = (onAccept, onDismiss) => {
22
+ if (granted()) { onAccept(); return }
23
+ if (dialog) { dialog.querySelector('button')?.focus(); return }
24
+ dismissed = onDismiss
25
+ dialog = document.createElement('dialog')
26
+ dialog.id = 'duet-audio-consent'
27
+ dialog.setAttribute('aria-labelledby', 'duet-audio-consent-title')
28
+ dialog.setAttribute('aria-describedby', 'duet-audio-consent-description')
29
+ dialog.style.cssText = 'max-width:380px;width:calc(100vw - 40px);border:1px solid #9aa8b8;border-radius:16px;padding:24px;background:Canvas;color:CanvasText;font:14px/1.7 system-ui;box-shadow:0 16px 60px #0004'
30
+ const title = document.createElement('h2')
31
+ title.id = 'duet-audio-consent-title'; title.textContent = '开启 duet'
32
+ title.style.cssText = 'font-size:18px;margin:0 0 12px'
33
+ const description = document.createElement('p')
34
+ description.id = 'duet-audio-consent-description'
35
+ description.style.whiteSpace = 'pre-line'
36
+ description.textContent = '为了提供语音交互和任务播报,您同意 duet 根据所使用的功能,将以下信息传至服务器:\n\n• 开启交互模式时,麦克风采集的交互音频。\n• 必要的会话信息,包括会话标识、名称、运行状态和当前选中的会话。\n• 功能所需的输入框内容、任务结果及相关上下文。\n\n这些信息用于理解语音、执行会话操作、生成回复和语音播报。\n\n仅在交互模式下会采集和上传麦克风音频。'
37
+ const actions = document.createElement('div')
38
+ actions.style.cssText = 'display:flex;gap:12px;justify-content:flex-end;margin-top:20px'
39
+ for (const [label, agree] of [['暂不开启', false], ['同意并开启', true]]) {
40
+ const button = document.createElement('button')
41
+ button.type = 'button'; button.textContent = label
42
+ button.style.cssText = `padding:8px 14px;border-radius:8px;border:1px solid #9aa8b8;cursor:pointer;background:${agree ? '#dcefff' : 'transparent'};color:${agree ? '#185a89' : 'inherit'}`
43
+ button.onclick = () => {
44
+ if (!agree) { cancel(); return }
45
+ accepted = true
46
+ try { storage?.setItem(key, 'accepted') } catch { /* This page only. */ }
47
+ cancel(true); onAccept()
48
+ }
49
+ actions.append(button)
50
+ }
51
+ dialog.append(title, description, actions)
52
+ dialog.addEventListener('cancel', event => { event.preventDefault(); cancel() })
53
+ document.body.append(dialog); dialog.showModal()
54
+ }
55
+ const ensure = signal => new Promise((resolve, reject) => {
56
+ if (signal?.aborted) { reject(signal.reason); return }
57
+ const done = error => { signal?.removeEventListener('abort', abort); error ? reject(error) : resolve() }
58
+ const abort = () => { cancel(); done(signal.reason || Error('授权已取消')) }
59
+ signal?.addEventListener('abort', abort, { once: true })
60
+ request(() => done(), () => done(Error('未同意数据传输,教学已停止')))
61
+ })
62
+ return { granted, request, cancel, ensure }
63
+ }
@@ -0,0 +1,48 @@
1
+ /** Optional, explicit rating; never opens voice or submits without a user click. */
2
+ export function mountRating(anchor, sessionTicket) {
3
+ if(!sessionTicket)return null
4
+ const panel=document.createElement('section')
5
+ panel.setAttribute('role','region');panel.setAttribute('aria-label','本次语音体验评分')
6
+ panel.style.cssText='position:fixed;z-index:100020;width:min(300px,calc(100vw - 24px));box-sizing:border-box;background:#17212f;color:#edf3ff;border:1px solid #52647d;border-radius:16px;padding:16px;box-shadow:0 12px 40px #0006;font:14px/1.6 system-ui'
7
+ const title=document.createElement('h3');title.textContent='这次语音体验怎么样?';title.style.margin='0 0 10px';panel.append(title)
8
+ const stars=document.createElement('div');stars.setAttribute('role','group');stars.setAttribute('aria-label','1 到 5 星');panel.append(stars)
9
+ let rating=0,busy=false,requestId=crypto.randomUUID()
10
+ const buttons=[]
11
+ for(let value=1;value<=5;value++){
12
+ const b=document.createElement('button');b.type='button';b.textContent='☆';b.setAttribute('aria-label',`${value} 星`);b.setAttribute('aria-pressed','false')
13
+ b.style.cssText='border:0;background:transparent;color:#efbd61;font-size:32px;cursor:pointer;padding:2px 6px'
14
+ b.onclick=()=>{if(busy)return;rating=value;requestId=crypto.randomUUID();buttons.forEach((x,i)=>{x.textContent=i<rating?'★':'☆';x.setAttribute('aria-pressed',String(i+1===rating))});submit.disabled=false}
15
+ stars.append(b);buttons.push(b)
16
+ }
17
+ const submit=document.createElement('button');submit.type='button';submit.textContent='提交评分';submit.disabled=true
18
+ submit.style.cssText='border:0;border-radius:8px;background:#b3e9cb;color:#152a1e;padding:8px 14px;cursor:pointer'
19
+ const skip=document.createElement('button');skip.type='button';skip.textContent='暂不评价(10s)';skip.style.cssText='border:0;background:transparent;color:#b9c9dc;padding:8px 14px;cursor:pointer'
20
+ const position=()=>{
21
+ const rect=anchor.getBoundingClientRect(),box=panel.getBoundingClientRect()
22
+ panel.style.left=Math.max(12,Math.min(rect.left,innerWidth-box.width-12))+'px'
23
+ panel.style.top=(rect.top>=box.height+20?rect.top-box.height-12:rect.bottom+12)+'px'
24
+ }
25
+ let countdown,timeout
26
+ const dispose=()=>{clearInterval(countdown);clearTimeout(timeout);panel.remove();document.removeEventListener('keydown',onKey);window.removeEventListener('resize',position);window.removeEventListener('scroll',position,true)}
27
+ const onKey=e=>{if(e.key==='Escape')dispose()}
28
+ skip.onclick=dispose
29
+ submit.onclick=async()=>{
30
+ if(busy||!rating)return
31
+ busy=true;submit.disabled=true;buttons.forEach(b=>b.disabled=true)
32
+ try {
33
+ const r=await fetch('/duplex-control/api/feedback',{method:'POST',credentials:'same-origin',
34
+ headers:{'Content-Type':'application/json','X-Duplex-Settings':'1'},signal:AbortSignal.timeout(15000),
35
+ body:JSON.stringify({kind:'rating',request_id:requestId,session_ticket:sessionTicket,rating})})
36
+ const result=await r.json()
37
+ if(!r.ok||result.persisted!==true)throw Error('not_saved')
38
+ dispose()
39
+ }catch{title.textContent='提交失败,请重试';submit.disabled=false;buttons.forEach(b=>b.disabled=false)}
40
+ finally{busy=false}
41
+ }
42
+ panel.append(submit,skip);document.body.append(panel);document.addEventListener('keydown',onKey)
43
+ position();window.addEventListener('resize',position);window.addEventListener('scroll',position,true)
44
+ const deadline=Date.now()+10000
45
+ countdown=setInterval(()=>{skip.textContent=`暂不评价(${Math.max(0,Math.ceil((deadline-Date.now())/1000))}s)`},250)
46
+ timeout=setTimeout(dispose,10000)
47
+ return {dispose}
48
+ }