dsh-duet 0.1.9 → 0.1.10

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-duet",
3
- "version": "0.1.9",
3
+ "version": "0.1.10",
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/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",
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/stop-task.mjs && node tests/browser/desktop-settings.mjs && node tests/browser/desktop-identity.mjs && node tests/browser/audio-interruption.mjs",
26
26
  "test:host": "node tests/host/isolated-host.mjs",
27
27
  "prepack": "npm run check"
28
28
  },
@@ -1,4 +1,6 @@
1
- import { microphoneConstraints } from './microphone.mjs?v=0.1.9'
1
+ import { microphoneConstraints } from './microphone.mjs?v=0.1.10'
2
+
3
+ export const AUDIO_STOP_PROTOCOL = 'audio_stop_candidates_v1'
2
4
 
3
5
  /** Browser-owned microphone and PCM playback. No microphone is requested in tts_only. */
4
6
  export class DuetAudio {
@@ -99,7 +101,7 @@ export class DuetAudio {
99
101
 
100
102
  event(event, send) {
101
103
  const key = `${event.response_id}:${event.generation}`
102
- if (event.type === 'output_audio_buffer.clear') { this.cleared.add(key); this.clear(send); return }
104
+ if (event.type === 'output_audio_buffer.clear') { this.interrupt(event, send); return }
103
105
  if (event.type === 'response.output_audio.done') {
104
106
  const response = this.responses.get(key)
105
107
  if (response) { response.done = true; this.progress(send) }
@@ -115,40 +117,108 @@ export class DuetAudio {
115
117
  for (let i = 0; i < pcm.length; i++) data[i] = pcm[i] / 32768
116
118
  const node = this.context.createBufferSource()
117
119
  node.buffer = buffer
118
- node.connect(this.context.destination)
120
+ const gain = this.context.createGain()
121
+ node.connect(gain)
122
+ gain.connect(this.context.destination)
119
123
  const start = Math.max(this.context.currentTime + 0.04, this.nextTime)
120
124
  this.nextTime = start + pcm.length / rate
121
- const response = this.responses.get(key) || { response_id: event.response_id, generation: event.generation, played: 0, basePlayed: 0, chunks: [] }
122
- response.chunks.push({ start, samples: pcm.length, rate })
125
+ const response = this.responses.get(key) || { response_id: event.response_id, generation: event.generation, played: 0, basePlayed: 0, received: 0, chunks: [] }
126
+ const chunk = { start, samples: pcm.length, rate, sampleStart: response.received, node, gain, ended: false }
127
+ response.received += pcm.length
128
+ response.chunks.push(chunk)
123
129
  this.responses.set(key, response)
124
130
  this.nodes.add(node)
125
- node.onended = () => { this.nodes.delete(node); node.disconnect(); this.progress(send) }
131
+ node.onended = () => {
132
+ chunk.ended = true
133
+ this.nodes.delete(node); node.disconnect(); gain.disconnect()
134
+ this.progress(send)
135
+ this.finishStop(key, response, send)
136
+ }
126
137
  node.start(start)
127
138
  }
128
139
 
140
+ playedAt(r, time) {
141
+ const until = Math.min(time, r.stopAt ?? Infinity)
142
+ return r.chunks.reduce((n, c) => n + Math.min(c.samples, Math.max(0,
143
+ Math.floor((until - c.start) * c.rate + 1e-6))), r.basePlayed)
144
+ }
145
+
129
146
  progress(send) {
130
147
  if (!this.context) return
131
148
  for (const [key, r] of this.responses) {
132
- const played = r.chunks.reduce((n, c) => n + Math.min(c.samples, Math.max(0, Math.floor((this.context.currentTime - c.start) * c.rate))), r.basePlayed)
149
+ const played = this.playedAt(r, this.context.currentTime)
133
150
  if (played > r.played) {
134
151
  r.played = played
135
152
  send({ type: 'output_audio_buffer.playback_progress', response_id: r.response_id, generation: r.generation, played_samples: played })
136
153
  }
137
- while (r.chunks.length && this.context.currentTime >= r.chunks[0].start + r.chunks[0].samples / r.chunks[0].rate) {
154
+ while (!r.stopping && r.chunks.length && this.context.currentTime >= r.chunks[0].start + r.chunks[0].samples / r.chunks[0].rate) {
138
155
  r.basePlayed += r.chunks.shift().samples
139
156
  }
140
- if (r.done && !r.chunks.length) this.responses.delete(key)
157
+ if (r.done && !r.stopping && !r.chunks.length) this.responses.delete(key)
141
158
  }
142
159
  }
143
160
 
144
161
  playing() { return this.nodes.size > 0 }
145
162
 
163
+ interrupt(event, send) {
164
+ const key = `${event.response_id}:${event.generation}`
165
+ if (this.cleared.has(key)) return
166
+ this.cleared.add(key)
167
+ const r = this.responses.get(key)
168
+ if (!r || !this.context) return
169
+ const now = this.context.currentTime, played = this.playedAt(r, now)
170
+ const smooth = event.audio_stop_protocol === AUDIO_STOP_PROTOCOL
171
+ const bound = Number.isFinite(event.max_wait_ms) ? Math.max(0, Math.min(300, event.max_wait_ms)) / 1000 : 0.3
172
+ const fadeMs = Number.isFinite(event.fade_ms) ? Math.max(0, Math.min(12, event.fade_ms)) : 12
173
+ const fade = smooth ? Math.min(fadeMs / 1000, bound) : 0
174
+ let cut = now + fade, selected = null, reason = 'immediate_fallback'
175
+ const candidates = event.stop_candidates_samples
176
+ const valid = smooth && Array.isArray(candidates) && candidates.length <= 3 &&
177
+ candidates.every((v, i) => Number.isSafeInteger(v) && v >= 0 && v <= r.received && (!i || v > candidates[i - 1]))
178
+ if (valid) {
179
+ for (const sample of candidates) {
180
+ if (sample <= played) continue
181
+ const c = r.chunks.find(c => c.sampleStart < sample && sample <= c.sampleStart + c.samples)
182
+ if (!c) continue
183
+ const when = c.start + (sample - c.sampleStart) / c.rate
184
+ if (when > now && when <= now + bound) { cut = when; selected = sample; reason = 'candidate'; break }
185
+ }
186
+ }
187
+ r.stopping = true; r.stopAt = cut; r.stopReason = reason; r.selectedStop = selected
188
+ for (const c of r.chunks) {
189
+ if (c.ended) continue
190
+ const end = c.start + c.samples / c.rate
191
+ const fadeStart = Math.max(now, cut - fade)
192
+ if (end > fadeStart) {
193
+ c.gain.gain.setValueAtTime(1, fadeStart)
194
+ c.gain.gain.linearRampToValueAtTime(0, cut)
195
+ }
196
+ if (end >= cut) c.node.stop(c.start >= cut ? now : cut)
197
+ }
198
+ // Only the interrupted response is shortened. A newer response keeps its queue.
199
+ this.nextTime = Math.max(now, ...[...this.responses.values()].flatMap(response =>
200
+ response.chunks.filter(c => !c.ended).map(c => Math.min(
201
+ c.start + c.samples / c.rate, response.stopAt ?? Infinity))))
202
+ this.finishStop(key, r, send)
203
+ }
204
+
205
+ finishStop(key, r, send) {
206
+ if (!r.stopping || r.acknowledged || r.chunks.some(c => !c.ended)) return
207
+ r.acknowledged = true
208
+ const played = this.playedAt(r, this.context.currentTime)
209
+ send({type:'output_audio_buffer.cleared', response_id:r.response_id, generation:r.generation,
210
+ played_samples:played, audio_stop_protocol:AUDIO_STOP_PROTOCOL,
211
+ selected_stop_sample:r.selectedStop, stop_reason:r.stopReason})
212
+ this.responses.delete(key)
213
+ }
214
+
146
215
  clear(send = () => {}) {
147
216
  this.progress(send)
148
217
  for (const [key, r] of this.responses) {
149
218
  this.cleared.add(key)
150
219
  send({ type: 'output_audio_buffer.cleared', response_id: r.response_id, generation: r.generation, played_samples: r.played })
151
220
  }
221
+ for (const r of this.responses.values()) for (const c of r.chunks) c.gain.disconnect()
152
222
  for (const node of this.nodes) { node.onended = null; node.stop(); node.disconnect() }
153
223
  this.nodes.clear()
154
224
  this.responses.clear()
@@ -1,25 +1,25 @@
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'
1
+ import { DuetState, PLUGIN_VERSION } from '../shared/state.mjs?v=0.1.10'
2
+ import { DuetAudio, AUDIO_STOP_PROTOCOL } from './audio.mjs?v=0.1.10'
3
+ import { HarnessRPCExecutor, rpcNavigationSession } from './rpc.mjs?v=0.1.10'
4
+ import { composerAccess, observeComposer, focusedSession, openLocalSession } from './composer.mjs?v=0.1.10'
5
+ import { startComposerBridge } from './composer-bridge.mjs?v=0.1.10'
6
+ import { mountTutorial } from './tutorial.mjs?v=0.1.10'
7
+ import { tutorialAdapter } from './tutorial-adapter.mjs?v=0.1.10'
8
+ import { mountRating } from './feedback.mjs?v=0.1.10'
9
+ import { createAudioUploadConsent } from './consent.mjs?v=0.1.10'
10
+ import { bindDuetShortcuts } from './shortcuts.mjs?v=0.1.10'
11
+ import { nativeInteractions } from './interactions.mjs?v=0.1.10'
12
+ import { mountConnectionHint } from './connection-hint.mjs?v=0.1.10'
13
+ import { mountControlsLayout } from './controls-layout.mjs?v=0.1.10'
14
+ import { mountNotice } from './notice.mjs?v=0.1.10'
15
+ import { workspaceIssue, requireWorkspace, browserSessionCatalog, sessionCreationPayload } from './workspaces.mjs?v=0.1.10'
16
+ import { voiceSocketUrl, bindSettingsLink } from './transport.mjs?v=0.1.10'
17
+ import { identityFetch, identityVoiceProtocols } from './identity.mjs?v=0.1.10'
18
+ import { sessionLabel } from '../shared/catalog.mjs?v=0.1.10'
19
+ import { resultNotification } from '../shared/result-notification.mjs?v=0.1.10'
20
+ import { HarnessSync } from './harness-sync.mjs?v=0.1.10'
21
+ import { LocalSync } from './local-sync.mjs?v=0.1.10'
22
+ import { diagnosticPayload } from '../shared/diagnostics.mjs?v=0.1.10'
23
23
 
24
24
  export function mountDuet(ctx) {
25
25
  const pageId = crypto.randomUUID()
@@ -119,6 +119,7 @@ export function mountDuet(ctx) {
119
119
  (await interactions(request, signal)) ?? composer.execute(request, signal), rows =>
120
120
  browserSessionCatalog(ctx, rows).map(row => ({ ...row, active: row.session_id === focusedSession(ctx) })), {
121
121
  id: connectionTraceId,
122
+ focused: () => focusedSession(ctx),
122
123
  syncSupported: () => localSync?.active && interactions.supportsSync,
123
124
  creationPayload: payload => sessionCreationPayload(ctx, payload),
124
125
  completed: async (request, body, signal) => {
@@ -173,7 +174,7 @@ export function mountDuet(ctx) {
173
174
  ws = new WebSocket(voiceSocketUrl({ mode, plugin_version: PLUGIN_VERSION, client_trace_id: connectionTraceId, page_id: pageId }), identityVoiceProtocols())
174
175
  ws.onopen = () => {
175
176
  report({ event: 'browser.connection_start', page_binding: 'connection_owner_v1' })
176
- send({ type: 'session.update' })
177
+ send({ type: 'session.update', client: {audio_stop_protocol:AUDIO_STOP_PROTOCOL} })
177
178
  if (mode === 'online') stopComposer = observeComposer(ctx, composer, send)
178
179
  }
179
180
  ws.onmessage = async event => {
@@ -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.9'
2
+ import { focusedSession as currentSession } from './composer.mjs?v=0.1.10'
3
3
 
4
4
  export function startComposerBridge(ctx, clientId, fetchImpl = fetch, feed = null) {
5
5
  const focusedSession = () => currentSession(ctx)
@@ -58,16 +58,16 @@ export function composerAccess(ctx, label = () => '') {
58
58
  if (!value) fail('session_not_ready')
59
59
  return { composer: value }
60
60
  }
61
- const match = request.path.match(/^\/api\/sessions\/([A-Za-z0-9_-]+)\/composer$/)
61
+ const match = request.path.match(/^\/api\/sessions\/((?:[A-Za-z0-9_:-]|%3[Aa]){1,256})\/composer$/)
62
62
  if (request.method === 'GET' && match) {
63
- const id = match[1]
63
+ const id = decodeURIComponent(match[1])
64
64
  const value = await snapshot(id, inputFor(id))
65
65
  signal?.throwIfAborted()
66
66
  if (request.params?.require_focus === 'true' && focused() !== id) fail('focus_conflict')
67
67
  return { composer: value }
68
68
  }
69
69
  if (request.method !== 'PUT' || !match) return undefined
70
- const id = match[1], payload = request.payload || {}, input = inputFor(id)
70
+ const id = decodeURIComponent(match[1]), payload = request.payload || {}, input = inputFor(id)
71
71
  const overwrite = payload.overwrite === true
72
72
  const before = overwrite ? null : await snapshot(id, input)
73
73
  signal?.throwIfAborted()
@@ -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.9'
2
+ import {normalizeGuidance} from '../shared/connection-guidance.mjs?v=0.1.10'
3
3
  export function mountConnectionHint(controls, { duration = 8000, onShown = ()=>{} } = {}) {
4
4
  const hint = document.createElement('div')
5
5
  hint.dataset.duetConnectionHint = ''
@@ -82,7 +82,7 @@ export function mountControlsLayout(controls) {
82
82
  controls.style.justifyContent = compact ? 'center' : ''
83
83
  controls.style.minWidth = '0'
84
84
  entry.style.cssText = initial.entry
85
- if (label) label.textContent = compact ? 'D' : labelText
85
+ if (label) label.textContent = compact ? 'd' : labelText
86
86
  if (compact) {
87
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
88
  entry.setAttribute('role', 'button'); entry.tabIndex = 0
@@ -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.9').then(module => {
14
+ import('/duet/assets/client/browser.mjs?v=0.1.10').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.9'
2
+ import { identityFetch } from './identity.mjs?v=0.1.10'
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.9'
2
+ VOICE_PROTOCOL, IDENTITY_PROTOCOL_PREFIX, validIdentityToken } from '../shared/identity.mjs?v=0.1.10'
3
3
 
4
4
  /** Desktop strips plugin cookies. Keep the Host-signed value in its origin storage. */
5
5
  export function createIdentityClient(globals = globalThis) {
@@ -26,7 +26,11 @@ export function nativeInteractions(ctx) {
26
26
  if (value.kind === 'approval') {
27
27
  if (!['allowed-once', 'rejected'].includes(payload.outcome)) throw Error('invalid_approval_outcome')
28
28
  await value.answer(payload.outcome)
29
- } else if (payload.cancelled === true) await value.cancel()
29
+ } else if (payload.cancelled === true) {
30
+ if (typeof value.cancel === 'function') await value.cancel()
31
+ else if (value.dismissal === 'cancel' && typeof value.dismiss === 'function') await value.dismiss()
32
+ else throw Object.assign(Error('当前问题不能直接取消,请在 DSH 中处理。'), {code:'question_cancel_unavailable'})
33
+ }
30
34
  else {
31
35
  if (!Array.isArray(payload.answers)) throw Error('invalid_question_answers')
32
36
  await value.answer({ answers: payload.answers })
@@ -1,14 +1,17 @@
1
1
  /** Reverse RPC executes on this authenticated DSH origin, never a supplied URL. */
2
2
  import { orderSessionCatalog, readWorkspaceView } from '../shared/catalog.mjs'
3
3
  const MAX_BYTES = 2_000_000
4
- const READ = /^\/api\/(?:health|sessions|jobs|results|interactions|composer\/focused|sessions\/[A-Za-z0-9_-]+\/composer)$/
5
- const WRITE = /^\/api\/(?:sessions|sessions\/[A-Za-z0-9_-]+\/(?:composer\/submit|activate|rename|fork)|interactions\/(?:(?:question|approval)(?::|%3[Aa]))?[A-Za-z0-9_-]+\/respond)$/
4
+ // Only colons may be escaped in a session segment: never decode arbitrary paths.
5
+ const SESSION = '(?:[A-Za-z0-9_:-]|%3[Aa]){1,256}'
6
+ const READ = new RegExp(`^/api/(?:health|sessions|jobs|results|interactions|composer/focused|sessions/${SESSION}/(?:composer|execution))$`)
7
+ const WRITE = new RegExp(`^/api/(?:sessions|sessions/${SESSION}/(?:composer/submit|activate|rename|fork|cancel)|interactions/(?:(?:question|approval)(?::|%3[Aa])(?:[A-Za-z0-9_:-]|%3[Aa]){1,1024}|[A-Za-z0-9_-]{1,256})/respond)$`)
8
+ const sessionRoute = (path, suffix) => new RegExp(`^/api/sessions/${SESSION}/${suffix}$`).test(path)
6
9
 
7
10
  // Navigate only the connection-owning page after a successful mutation.
8
11
  export function rpcNavigationSession(request, body) {
9
12
  if (request.method !== 'POST') return null
10
- if (/^\/api\/sessions\/[A-Za-z0-9_-]+\/activate$/.test(request.path)) return body.active_session_id
11
- if (request.path === '/api/sessions' || /^\/api\/sessions\/[A-Za-z0-9_-]+\/fork$/.test(request.path)) return body.session?.session_id
13
+ if (sessionRoute(request.path, 'activate')) return body.active_session_id
14
+ if (request.path === '/api/sessions' || sessionRoute(request.path, 'fork')) return body.session?.session_id
12
15
  return null
13
16
  }
14
17
 
@@ -17,8 +20,12 @@ export function validateRPC(request) {
17
20
  || !/^[a-f0-9]{32}$/.test(request.connection_id || '')) throw new Error('invalid_harness_rpc')
18
21
  if (!((request.method === 'GET' && READ.test(request.path))
19
22
  || (request.method === 'POST' && WRITE.test(request.path))
20
- || (request.method === 'PUT' && /^\/api\/sessions\/[A-Za-z0-9_-]+\/composer$/.test(request.path)))) throw new Error('harness_rpc_route_not_allowed')
23
+ || (request.method === 'PUT' && sessionRoute(request.path, 'composer')))) throw new Error('harness_rpc_route_not_allowed')
21
24
  if (new TextEncoder().encode(JSON.stringify(request)).length > MAX_BYTES) throw new Error('harness_rpc_too_large')
25
+ if (sessionRoute(request.path, 'cancel') && (typeof request.payload?.execution_id !== 'string'
26
+ || !/^[a-f0-9-]{36}$/.test(request.payload.execution_id)
27
+ || typeof request.payload.require_focus !== 'boolean'
28
+ || Object.keys(request.payload).some(k => !['execution_id','require_focus'].includes(k)))) throw new Error('invalid_stop_request')
22
29
  if (request.params != null) {
23
30
  const focus = /\/composer$/.test(request.path) && JSON.stringify(request.params) === '{"require_focus":"true"}'
24
31
  const results = request.path === '/api/results' && typeof request.params === 'object'
@@ -73,6 +80,13 @@ export class HarnessRPCExecutor {
73
80
  const envelope = { type: 'harness.rpc.response', connection_id: request.connection_id, request_id: request.request_id }
74
81
  try {
75
82
  let payload = request.payload ?? {}
83
+ if (sessionRoute(request.path, '(?:execution|cancel)')) {
84
+ if (!this.stopSupported || !this.binding.id) return { ...envelope, status:409,
85
+ body:{error_code:'harness_stop_task_upgrade_required'} }
86
+ const id = decodeURIComponent(request.path.split('/')[3])
87
+ if (payload.require_focus && this.binding.focused?.() !== id) return { ...envelope, status:409,
88
+ body:{error_code:'focus_conflict'} }
89
+ }
76
90
  if (request.method === 'POST' && request.path === '/api/sessions' && this.binding.creationPayload) {
77
91
  try { payload = this.binding.creationPayload(payload) }
78
92
  catch (error) { return { ...envelope, status: 409, body: { error_code: error.code || error.message || 'workspace_selection_required' } } }
@@ -104,7 +118,10 @@ export class HarnessRPCExecutor {
104
118
  controller.signal.throwIfAborted()
105
119
  if (response.ok && this.binding.completed) await this.binding.completed(request, body, controller.signal)
106
120
  if (response.status === 200 && request.method === 'GET' && request.path === '/api/sessions' && Array.isArray(body.sessions)) {
121
+ this.stopSupported = body.duet_rpc_capabilities?.includes('stop_task_v1') === true
122
+ && typeof this.binding.focused === 'function'
107
123
  body.duet_rpc_capabilities = ['create_session_v1',
124
+ ...(this.stopSupported ? ['stop_task_v1'] : []),
108
125
  ...(this.binding.syncSupported?.() === false ? [] : ['harness_sync_v1'])]
109
126
  // Both startup prompt and nth_N resolution read this same browser-local
110
127
  // order, including manual drag order; archived rows cannot consume ranks.
@@ -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.9';
155
+ import { identityFetch } from '/duet/assets/client/identity.mjs?v=0.1.10';
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.9');
366
+ const {requestTutorial} = await import('/duet/assets/client/tutorial-request.mjs?v=0.1.10');
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.9').then(({mountShortcutSettings}) => {
375
+ import('/duet/assets/client/shortcuts.mjs?v=0.1.10').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.9').then(({mountMicrophoneSettings}) => {
379
+ import('/duet/assets/client/microphone.mjs?v=0.1.10').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.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'
2
+ import { PLUGIN_VERSION } from '../shared/state.mjs?v=0.1.10'
3
+ import { focusedSession } from './composer.mjs?v=0.1.10'
4
+ import { sessionCreationPayload, workspaceIssue } from './workspaces.mjs?v=0.1.10'
5
+ import { startComposerBridge } from './composer-bridge.mjs?v=0.1.10'
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.9'
2
+ import {consumeTutorialRequest} from './tutorial-request.mjs?v=0.1.10'
3
3
  export const TUTORIAL_KEY = 'dsh-duplex-tutorial-v1'
4
4
  export const QUESTION = '什么是语音交互?请用一句话简单解释,不使用工具。'
5
5
  export const INPUT = '用一句话介绍语音助手。'
@@ -16,6 +16,7 @@ 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'
19
+ import { StopTasks } from './stop-task.mjs'
19
20
 
20
21
  const ROUTE = '/duplex-control'
21
22
  const PAGE_ROUTE = '/duet'
@@ -165,6 +166,7 @@ export function apply(ctx, options = {}) {
165
166
  const composerPollWaiters = new Set()
166
167
  const composerRequestOrder = []
167
168
  const currentTurn = new Map()
169
+ const stopTasks = new StopTasks(request => ctx.sessionController.cancel(request))
168
170
  const jobByTurn = new Map()
169
171
  const pendingInteractions = new Map()
170
172
  const browserClients = new Map()
@@ -417,7 +419,7 @@ export function apply(ctx, options = {}) {
417
419
  job.completed_at = nowSeconds()
418
420
  if (event.data.reason?.kind === 'aborted') {
419
421
  job.status = 'failed'
420
- job.error = 'Harness turn was aborted, not completed'
422
+ job.error = '任务执行已终止,未完成。'
421
423
  } else if (event.data.reason?.kind === 'error') {
422
424
  job.status = 'failed'
423
425
  job.error = taskErrorText(event.data.reason.error)
@@ -441,6 +443,7 @@ export function apply(ctx, options = {}) {
441
443
  const sessionId = String(session.id)
442
444
  if (event.type === 'turn/start') {
443
445
  currentTurn.set(sessionId, event.data.turn)
446
+ stopTasks.start(sessionId, event.data.turn)
444
447
  return
445
448
  }
446
449
  if (event.type === 'user/message') {
@@ -490,10 +493,11 @@ export function apply(ctx, options = {}) {
490
493
  return
491
494
  }
492
495
  if (event.type !== 'turn/end') return
496
+ stopTasks.end(sessionId, event.data.turn)
493
497
  const key = turnKey(sessionId, event.data.turn)
494
498
  const id = jobByTurn.get(key)
495
499
  const job = id === undefined ? undefined : jobs.get(id)
496
- currentTurn.delete(sessionId)
500
+ if (currentTurn.get(sessionId) === event.data.turn) currentTurn.delete(sessionId)
497
501
  jobByTurn.delete(key)
498
502
  if (job === undefined) return
499
503
  completeJob(job, event)
@@ -832,7 +836,29 @@ export function apply(ctx, options = {}) {
832
836
  // A page owns its focus. Do not remove blank sessions using host focus
833
837
  // before that page can select its own current blank session.
834
838
  const pageCatalog = browserOwner(req) || req.headers['x-duet-catalog-scope'] === 'page'
835
- sendJson(res, 200, { sessions: await listSessions({forCatalog:!pageCatalog}) })
839
+ sendJson(res, 200, { sessions: await listSessions({forCatalog:!pageCatalog}),
840
+ duet_rpc_capabilities: typeof ctx.sessionController.cancel === 'function' ? ['stop_task_v1'] : [] })
841
+ return
842
+ }
843
+ const stopRoute = pathname.match(new RegExp(`^${ROUTE}/api/sessions/([^/]+)/(execution|cancel)$`))
844
+ if (stopRoute && ((req.method === 'GET' && stopRoute[2] === 'execution')
845
+ || (req.method === 'POST' && stopRoute[2] === 'cancel'))) {
846
+ const owner = browserOwner(req)
847
+ if (!owner) throw codedError('stop_task_owner_required', '停止操作需要连接所属页面')
848
+ if (typeof ctx.sessionController.cancel !== 'function') {
849
+ throw codedError('harness_stop_task_upgrade_required', '请升级 DSH 和 duet 插件后使用停止任务')
850
+ }
851
+ const sessionId = decodeURIComponent(stopRoute[1])
852
+ const body = req.method === 'POST' ? await readJson(req) : null
853
+ if (req.method === 'POST' && (!body || typeof body !== 'object' || Array.isArray(body)
854
+ || Object.keys(body).some(k => !['execution_id', 'require_focus'].includes(k))
855
+ || typeof body.require_focus !== 'boolean')) throw codedError('invalid_stop_request', '无效停止请求', 400)
856
+ const sessions = await listSessions()
857
+ if (!sessions.some(s => s.session_id === sessionId)) throw codedError('session_not_found', '会话不存在')
858
+ // Focus checks run in the owning browser; Host never substitutes global focus.
859
+ sendJson(res, 200, body
860
+ ? await stopTasks.request(sessionId, body.execution_id, owner)
861
+ : { execution: stopTasks.snapshot(sessionId) })
836
862
  return
837
863
  }
838
864
  const composer = pathname.match(new RegExp(`^${ROUTE}/api/sessions/([^/]+)/composer$`))
@@ -172,7 +172,9 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
172
172
  if (initialized) throw new Error('voice_mode_requires_reconnect')
173
173
  initialized = true
174
174
  forward(JSON.stringify({ type: 'session.update',
175
- client: {...clientMetadata, diagnostics_protocol:DIAGNOSTICS_PROTOCOL},
175
+ client: {...clientMetadata, diagnostics_protocol:DIAGNOSTICS_PROTOCOL,
176
+ ...(message.client?.audio_stop_protocol === 'audio_stop_candidates_v1'
177
+ ? {audio_stop_protocol:'audio_stop_candidates_v1'} : {})},
176
178
  session: {
177
179
  type: 'realtime', preset_id: 'server_default',
178
180
  io_mode:mode === 'tts_only'?'external_only':'online',
@@ -0,0 +1,37 @@
1
+ import { randomUUID } from 'node:crypto'
2
+
3
+ const fail = code => { const error = new Error(code); error.code = code; error.status = 409; throw error }
4
+
5
+ /** Bind cancellation to one observed execution, never a later turn in the session. */
6
+ export class StopTasks {
7
+ constructor(cancel) { this.cancel = cancel; this.live = new Map(); this.receipts = new Map() }
8
+ start(sessionId, turn) {
9
+ if (this.live.get(sessionId)?.turn === turn) return
10
+ this.live.set(sessionId, { execution_id: randomUUID(), turn })
11
+ }
12
+ end(sessionId, turn) {
13
+ if (this.live.get(sessionId)?.turn === turn) this.live.delete(sessionId)
14
+ }
15
+ snapshot(sessionId) {
16
+ const execution = this.live.get(sessionId)
17
+ if (!execution) fail('no_running_task')
18
+ return { session_id: sessionId, execution_id: execution.execution_id }
19
+ }
20
+ request(sessionId, executionId, owner) {
21
+ if (!owner) fail('stop_task_owner_required')
22
+ if (typeof executionId !== 'string' || !/^[a-f0-9-]{36}$/.test(executionId)) fail('invalid_execution_id')
23
+ const key = `${owner}:${sessionId}:${executionId}`
24
+ if (this.receipts.has(key)) return this.receipts.get(key)
25
+ if (this.live.get(sessionId)?.execution_id !== executionId) fail('execution_changed')
26
+ // DSH's public Host cancel is synchronous: no await between identity check
27
+ // and cancellation. Do not retry rejected/unknown outcomes automatically.
28
+ const result = this.cancel({ sessionId })
29
+ const pending = Promise.resolve(result).then(value => {
30
+ if (value?.accepted !== true) fail('stop_not_accepted')
31
+ return { accepted: true, session_id: sessionId, execution_id: executionId }
32
+ })
33
+ this.receipts.set(key, pending)
34
+ while (this.receipts.size > 500) this.receipts.delete(this.receipts.keys().next().value)
35
+ return pending
36
+ }
37
+ }
@@ -1,5 +1,5 @@
1
1
  /** Desired voice mode is independent of a temporarily suspended connection. */
2
- export const PLUGIN_VERSION = '0.1.9'
2
+ export const PLUGIN_VERSION = '0.1.10'
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 : ''