dsh-duet 0.1.8 → 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/README.md +16 -3
- package/package.json +2 -2
- package/src/client/audio.mjs +82 -10
- package/src/client/browser.mjs +64 -32
- package/src/client/composer-bridge.mjs +1 -1
- package/src/client/composer.mjs +3 -3
- package/src/client/connection-hint.mjs +1 -1
- package/src/client/controls-layout.mjs +1 -1
- package/src/client/entry.js +1 -1
- package/src/client/feedback.mjs +1 -1
- package/src/client/identity.mjs +1 -1
- package/src/client/interactions.mjs +5 -1
- package/src/client/rpc.mjs +22 -5
- package/src/client/settings.html +4 -4
- package/src/client/tutorial-adapter.mjs +4 -4
- package/src/client/tutorial.mjs +1 -1
- package/src/host/assets.mjs +1 -0
- package/src/host/diagnostics.mjs +45 -0
- package/src/host/plugin.mjs +36 -7
- package/src/host/proxy.mjs +37 -4
- package/src/host/stop-task.mjs +37 -0
- package/src/shared/diagnostics.mjs +31 -0
- package/src/shared/result-notification.mjs +19 -1
- package/src/shared/state.mjs +12 -10
package/README.md
CHANGED
|
@@ -15,7 +15,11 @@ duet,意为「二重奏」。这里的 duet 使用全双工语音模型,可
|
|
|
15
15
|
|
|
16
16
|
## 安装
|
|
17
17
|
|
|
18
|
-
|
|
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
|
-
|
|
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.
|
|
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
|
},
|
package/src/client/audio.mjs
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import { microphoneConstraints } from './microphone.mjs?v=0.1.
|
|
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 {
|
|
@@ -37,10 +39,11 @@ export class DuetAudio {
|
|
|
37
39
|
}
|
|
38
40
|
}
|
|
39
41
|
|
|
40
|
-
async startMic(send, onFailure = () => {}) {
|
|
42
|
+
async startMic(send, onFailure = () => {}, report = () => {}) {
|
|
41
43
|
const epoch = this.epoch
|
|
42
44
|
// Exact selection: an unplugged device must not silently use a different mic.
|
|
43
45
|
const stream = await navigator.mediaDevices.getUserMedia(microphoneConstraints())
|
|
46
|
+
report({event:'browser.microphone_granted'})
|
|
44
47
|
if (epoch !== this.epoch) { stream.getTracks().forEach(t => t.stop()); return }
|
|
45
48
|
this.stream = stream
|
|
46
49
|
let failed = false
|
|
@@ -93,11 +96,12 @@ export class DuetAudio {
|
|
|
93
96
|
this.mute = this.context.createGain()
|
|
94
97
|
this.mute.gain.value = 0
|
|
95
98
|
this.source.connect(this.capture).connect(this.mute).connect(this.context.destination)
|
|
99
|
+
report({event:'browser.capture_started'})
|
|
96
100
|
}
|
|
97
101
|
|
|
98
102
|
event(event, send) {
|
|
99
103
|
const key = `${event.response_id}:${event.generation}`
|
|
100
|
-
if (event.type === 'output_audio_buffer.clear') { this.
|
|
104
|
+
if (event.type === 'output_audio_buffer.clear') { this.interrupt(event, send); return }
|
|
101
105
|
if (event.type === 'response.output_audio.done') {
|
|
102
106
|
const response = this.responses.get(key)
|
|
103
107
|
if (response) { response.done = true; this.progress(send) }
|
|
@@ -113,40 +117,108 @@ export class DuetAudio {
|
|
|
113
117
|
for (let i = 0; i < pcm.length; i++) data[i] = pcm[i] / 32768
|
|
114
118
|
const node = this.context.createBufferSource()
|
|
115
119
|
node.buffer = buffer
|
|
116
|
-
|
|
120
|
+
const gain = this.context.createGain()
|
|
121
|
+
node.connect(gain)
|
|
122
|
+
gain.connect(this.context.destination)
|
|
117
123
|
const start = Math.max(this.context.currentTime + 0.04, this.nextTime)
|
|
118
124
|
this.nextTime = start + pcm.length / rate
|
|
119
|
-
const response = this.responses.get(key) || { response_id: event.response_id, generation: event.generation, played: 0, basePlayed: 0, chunks: [] }
|
|
120
|
-
|
|
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)
|
|
121
129
|
this.responses.set(key, response)
|
|
122
130
|
this.nodes.add(node)
|
|
123
|
-
node.onended = () => {
|
|
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
|
+
}
|
|
124
137
|
node.start(start)
|
|
125
138
|
}
|
|
126
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
|
+
|
|
127
146
|
progress(send) {
|
|
128
147
|
if (!this.context) return
|
|
129
148
|
for (const [key, r] of this.responses) {
|
|
130
|
-
const played =
|
|
149
|
+
const played = this.playedAt(r, this.context.currentTime)
|
|
131
150
|
if (played > r.played) {
|
|
132
151
|
r.played = played
|
|
133
152
|
send({ type: 'output_audio_buffer.playback_progress', response_id: r.response_id, generation: r.generation, played_samples: played })
|
|
134
153
|
}
|
|
135
|
-
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) {
|
|
136
155
|
r.basePlayed += r.chunks.shift().samples
|
|
137
156
|
}
|
|
138
|
-
if (r.done && !r.chunks.length) this.responses.delete(key)
|
|
157
|
+
if (r.done && !r.stopping && !r.chunks.length) this.responses.delete(key)
|
|
139
158
|
}
|
|
140
159
|
}
|
|
141
160
|
|
|
142
161
|
playing() { return this.nodes.size > 0 }
|
|
143
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
|
+
|
|
144
215
|
clear(send = () => {}) {
|
|
145
216
|
this.progress(send)
|
|
146
217
|
for (const [key, r] of this.responses) {
|
|
147
218
|
this.cleared.add(key)
|
|
148
219
|
send({ type: 'output_audio_buffer.cleared', response_id: r.response_id, generation: r.generation, played_samples: r.played })
|
|
149
220
|
}
|
|
221
|
+
for (const r of this.responses.values()) for (const c of r.chunks) c.gain.disconnect()
|
|
150
222
|
for (const node of this.nodes) { node.onended = null; node.stop(); node.disconnect() }
|
|
151
223
|
this.nodes.clear()
|
|
152
224
|
this.responses.clear()
|
package/src/client/browser.mjs
CHANGED
|
@@ -1,24 +1,25 @@
|
|
|
1
|
-
import { DuetState, PLUGIN_VERSION } from '../shared/state.mjs?v=0.1.
|
|
2
|
-
import { DuetAudio } from './audio.mjs?v=0.1.
|
|
3
|
-
import { HarnessRPCExecutor, rpcNavigationSession } from './rpc.mjs?v=0.1.
|
|
4
|
-
import { composerAccess, observeComposer, focusedSession, openLocalSession } from './composer.mjs?v=0.1.
|
|
5
|
-
import { startComposerBridge } from './composer-bridge.mjs?v=0.1.
|
|
6
|
-
import { mountTutorial } from './tutorial.mjs?v=0.1.
|
|
7
|
-
import { tutorialAdapter } from './tutorial-adapter.mjs?v=0.1.
|
|
8
|
-
import { mountRating } from './feedback.mjs?v=0.1.
|
|
9
|
-
import { createAudioUploadConsent } from './consent.mjs?v=0.1.
|
|
10
|
-
import { bindDuetShortcuts } from './shortcuts.mjs?v=0.1.
|
|
11
|
-
import { nativeInteractions } from './interactions.mjs?v=0.1.
|
|
12
|
-
import { mountConnectionHint } from './connection-hint.mjs?v=0.1.
|
|
13
|
-
import { mountControlsLayout } from './controls-layout.mjs?v=0.1.
|
|
14
|
-
import { mountNotice } from './notice.mjs?v=0.1.
|
|
15
|
-
import { workspaceIssue, requireWorkspace, browserSessionCatalog, sessionCreationPayload } from './workspaces.mjs?v=0.1.
|
|
16
|
-
import { voiceSocketUrl, bindSettingsLink } from './transport.mjs?v=0.1.
|
|
17
|
-
import { identityFetch, identityVoiceProtocols } from './identity.mjs?v=0.1.
|
|
18
|
-
import { sessionLabel } from '../shared/catalog.mjs?v=0.1.
|
|
19
|
-
import { resultNotification } from '../shared/result-notification.mjs?v=0.1.
|
|
20
|
-
import { HarnessSync } from './harness-sync.mjs?v=0.1.
|
|
21
|
-
import { LocalSync } from './local-sync.mjs?v=0.1.
|
|
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'
|
|
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
|
|
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
|
|
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)
|
|
@@ -105,6 +119,7 @@ export function mountDuet(ctx) {
|
|
|
105
119
|
(await interactions(request, signal)) ?? composer.execute(request, signal), rows =>
|
|
106
120
|
browserSessionCatalog(ctx, rows).map(row => ({ ...row, active: row.session_id === focusedSession(ctx) })), {
|
|
107
121
|
id: connectionTraceId,
|
|
122
|
+
focused: () => focusedSession(ctx),
|
|
108
123
|
syncSupported: () => localSync?.active && interactions.supportsSync,
|
|
109
124
|
creationPayload: payload => sessionCreationPayload(ctx, payload),
|
|
110
125
|
completed: async (request, body, signal) => {
|
|
@@ -115,11 +130,12 @@ export function mountDuet(ctx) {
|
|
|
115
130
|
const connection = {
|
|
116
131
|
resultPush,
|
|
117
132
|
feedbackTicket: null,
|
|
133
|
+
report,
|
|
118
134
|
send,
|
|
119
135
|
sendState: state => { if (state) send({ type: 'harness.state', state }) },
|
|
120
136
|
playing: () => audio.playing(),
|
|
121
|
-
async close() {
|
|
122
|
-
report({ event: 'browser.connection_close', buffered_bytes: ws?.bufferedAmount })
|
|
137
|
+
async close(details = {reason:'unknown'}) {
|
|
138
|
+
report({ event: 'browser.connection_close', ...details, buffered_bytes: ws?.bufferedAmount })
|
|
123
139
|
// Explicit mode changes start a fresh listening window. An unexpected
|
|
124
140
|
// socket close retains only this page's last acknowledged cursor.
|
|
125
141
|
if (mode === 'online' && ws?.readyState === WebSocket.OPEN) {
|
|
@@ -138,7 +154,7 @@ export function mountDuet(ctx) {
|
|
|
138
154
|
await new Promise(resolve => {
|
|
139
155
|
const timer = setTimeout(resolve, 1200)
|
|
140
156
|
ws.addEventListener('close', () => { clearTimeout(timer); resolve() }, { once: true })
|
|
141
|
-
if (ws.readyState < WebSocket.CLOSING) ws.close(1000)
|
|
157
|
+
if (ws.readyState < WebSocket.CLOSING) ws.close(1000, 'duet_client_close')
|
|
142
158
|
})
|
|
143
159
|
}
|
|
144
160
|
release?.()
|
|
@@ -155,10 +171,10 @@ export function mountDuet(ctx) {
|
|
|
155
171
|
requireWorkspace(ctx)
|
|
156
172
|
if(closed)return
|
|
157
173
|
if (mode === 'online') stopBridge = startComposerBridge(ctx, connectionTraceId, fetch, localSync)
|
|
158
|
-
report({ event: 'browser.connection_start', page_binding: 'connection_owner_v1' })
|
|
159
174
|
ws = new WebSocket(voiceSocketUrl({ mode, plugin_version: PLUGIN_VERSION, client_trace_id: connectionTraceId, page_id: pageId }), identityVoiceProtocols())
|
|
160
175
|
ws.onopen = () => {
|
|
161
|
-
|
|
176
|
+
report({ event: 'browser.connection_start', page_binding: 'connection_owner_v1' })
|
|
177
|
+
send({ type: 'session.update', client: {audio_stop_protocol:AUDIO_STOP_PROTOCOL} })
|
|
162
178
|
if (mode === 'online') stopComposer = observeComposer(ctx, composer, send)
|
|
163
179
|
}
|
|
164
180
|
ws.onmessage = async event => {
|
|
@@ -190,14 +206,24 @@ export function mountDuet(ctx) {
|
|
|
190
206
|
if (message.compatibility) receive({ type: 'compatibility', compatibility: message.compatibility })
|
|
191
207
|
connection.feedbackTicket = message.feedback_session_ticket || null
|
|
192
208
|
ready = true
|
|
193
|
-
|
|
209
|
+
report({event:'browser.audio_prepare_started'})
|
|
210
|
+
try { await audio.prepare() }
|
|
211
|
+
catch (error) {
|
|
212
|
+
report({event:'browser.audio_prepare_failed',name:error?.name,phase:'audio_context',context_state:audio.context?.state})
|
|
213
|
+
throw error
|
|
214
|
+
}
|
|
194
215
|
if (closed) return
|
|
195
216
|
if (mode === 'online') {
|
|
217
|
+
let phase = 'permission'
|
|
218
|
+
report({event:'browser.microphone_started',phase})
|
|
196
219
|
try { await audio.startMic(send, code => {
|
|
197
220
|
if (!closed) { report({event:'browser.capture_failed',code}); receive({type:'error',code}) }
|
|
221
|
+
}, event => {
|
|
222
|
+
if (event.event === 'browser.microphone_granted') phase = 'capture'
|
|
223
|
+
report(event)
|
|
198
224
|
}) }
|
|
199
225
|
catch (error) {
|
|
200
|
-
report({ event: 'browser.microphone_failed', name: error?.name })
|
|
226
|
+
report({ event: 'browser.microphone_failed', name: error?.name, phase })
|
|
201
227
|
if (!closed) receive({ type: 'error', code: 'microphone_unavailable' })
|
|
202
228
|
return
|
|
203
229
|
}
|
|
@@ -239,13 +265,18 @@ export function mountDuet(ctx) {
|
|
|
239
265
|
const held = new Promise(resolve => { release = resolve })
|
|
240
266
|
// Opening may hang; ownership ends when close() releases it, not when
|
|
241
267
|
// 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'}) })
|
|
268
|
+
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
269
|
await held
|
|
244
270
|
}).catch(() => { if (!closed) receive({ type: 'error', code: 'voice_connection_failed' }) })
|
|
245
271
|
} else queueMicrotask(() => receive({ type: 'error', code: 'voice_lock_unavailable' }))
|
|
246
272
|
return connection
|
|
247
273
|
}
|
|
248
274
|
const state = new DuetState({ connect, changed: draw, notice })
|
|
275
|
+
const pageHide = () => {
|
|
276
|
+
state.connection?.report({event:'browser.pagehide',reason:'page_unload'})
|
|
277
|
+
void state.setMode('off', {reason:'page_unload'})
|
|
278
|
+
}
|
|
279
|
+
window.addEventListener('pagehide', pageHide)
|
|
249
280
|
const mount = () => {
|
|
250
281
|
const entry = document.getElementById('dsh-duet-entry')
|
|
251
282
|
if (!entry || document.getElementById('dsh-duet-controls')) return
|
|
@@ -422,6 +453,7 @@ export function mountDuet(ctx) {
|
|
|
422
453
|
teachingObserver.observe(document.body, { subtree: true, childList: true })
|
|
423
454
|
return () => {
|
|
424
455
|
disposed = true
|
|
456
|
+
window.removeEventListener('pagehide', pageHide)
|
|
425
457
|
pollController?.abort()
|
|
426
458
|
unwatchSessions?.(); unwatchWorkspaces?.()
|
|
427
459
|
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.
|
|
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)
|
package/src/client/composer.mjs
CHANGED
|
@@ -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_
|
|
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.
|
|
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 ? '
|
|
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
|
package/src/client/entry.js
CHANGED
|
@@ -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.
|
|
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?.() }
|
package/src/client/feedback.mjs
CHANGED
|
@@ -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.
|
|
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
|
package/src/client/identity.mjs
CHANGED
|
@@ -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.
|
|
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)
|
|
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 })
|
package/src/client/rpc.mjs
CHANGED
|
@@ -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
|
-
|
|
5
|
-
const
|
|
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 (
|
|
11
|
-
if (request.path === '/api/sessions' ||
|
|
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' &&
|
|
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.
|
package/src/client/settings.html
CHANGED
|
@@ -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.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
3
|
-
import { focusedSession } from './composer.mjs?v=0.1.
|
|
4
|
-
import { sessionCreationPayload, workspaceIssue } from './workspaces.mjs?v=0.1.
|
|
5
|
-
import { startComposerBridge } from './composer-bridge.mjs?v=0.1.
|
|
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()
|
package/src/client/tutorial.mjs
CHANGED
|
@@ -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.
|
|
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 = '用一句话介绍语音助手。'
|
package/src/host/assets.mjs
CHANGED
|
@@ -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
|
+
}
|
package/src/host/plugin.mjs
CHANGED
|
@@ -12,10 +12,11 @@ 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'
|
|
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()
|
|
@@ -367,7 +369,7 @@ export function apply(ctx, options = {}) {
|
|
|
367
369
|
}, hostAbort.signal)
|
|
368
370
|
} catch (error) {
|
|
369
371
|
job.status = 'failed'
|
|
370
|
-
job.error =
|
|
372
|
+
job.error = taskErrorText(error)
|
|
371
373
|
job.completed_at = nowSeconds()
|
|
372
374
|
completionSequence += 1
|
|
373
375
|
job.completion_seq = completionSequence
|
|
@@ -417,10 +419,10 @@ 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 = '
|
|
422
|
+
job.error = '任务执行已终止,未完成。'
|
|
421
423
|
} else if (event.data.reason?.kind === 'error') {
|
|
422
424
|
job.status = 'failed'
|
|
423
|
-
job.error =
|
|
425
|
+
job.error = taskErrorText(event.data.reason.error)
|
|
424
426
|
} else if (!job.result) {
|
|
425
427
|
job.status = 'failed'
|
|
426
428
|
job.error = `Harness turn ended without a final text response (${event.data.reason?.kind || 'unknown'})`
|
|
@@ -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)
|
|
@@ -540,10 +544,13 @@ export function apply(ctx, options = {}) {
|
|
|
540
544
|
return
|
|
541
545
|
}
|
|
542
546
|
if (req.method === 'POST' && pathname === `${ROUTE}/api/voice/diagnostic`) {
|
|
543
|
-
|
|
547
|
+
const rejection = ctx.connection.requestRejection(req)
|
|
548
|
+
if (rejection) { sendError(res, rejection, 'DSH connection required'); return }
|
|
549
|
+
if (!identityWriteAllowed(req)) { sendError(res, 403, 'same-origin diagnostic request required'); return }
|
|
544
550
|
const body = await readJson(req)
|
|
545
551
|
if (JSON.stringify(body).length > 24000) { sendError(res, 413, 'diagnostic too large'); return }
|
|
546
552
|
audit.event('client.diagnostic', body)
|
|
553
|
+
try { duetProxy?.reportDiagnostic?.(req, body) } catch { /* Best effort only. */ }
|
|
547
554
|
sendJson(res, 200, { ok: true, logging: audit.snapshot() }); return
|
|
548
555
|
}
|
|
549
556
|
if (req.method === 'GET' && pathname === `${ROUTE}/api/voice/service-info`) {
|
|
@@ -829,7 +836,29 @@ export function apply(ctx, options = {}) {
|
|
|
829
836
|
// A page owns its focus. Do not remove blank sessions using host focus
|
|
830
837
|
// before that page can select its own current blank session.
|
|
831
838
|
const pageCatalog = browserOwner(req) || req.headers['x-duet-catalog-scope'] === 'page'
|
|
832
|
-
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) })
|
|
833
862
|
return
|
|
834
863
|
}
|
|
835
864
|
const composer = pathname.match(new RegExp(`^${ROUTE}/api/sessions/([^/]+)/composer$`))
|
package/src/host/proxy.mjs
CHANGED
|
@@ -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')
|
|
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,9 @@ 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,
|
|
176
|
+
...(message.client?.audio_stop_protocol === 'audio_stop_candidates_v1'
|
|
177
|
+
? {audio_stop_protocol:'audio_stop_candidates_v1'} : {})},
|
|
165
178
|
session: {
|
|
166
179
|
type: 'realtime', preset_id: 'server_default',
|
|
167
180
|
io_mode:mode === 'tts_only'?'external_only':'online',
|
|
@@ -207,6 +220,15 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
207
220
|
selectedConfig = {...selected.route.config, endpoints: {online:selected.route.url,tts_only:selected.route.url}}
|
|
208
221
|
trace.event('endpoint.selected', connectionRoute)
|
|
209
222
|
back.on('message', (data, binary) => {
|
|
223
|
+
if (!binary) {
|
|
224
|
+
try {
|
|
225
|
+
const offer = JSON.parse(data.toString())
|
|
226
|
+
if (offer.type === 'client.diagnostics.ready') {
|
|
227
|
+
diagnostics.offer(offer, selectedConfig, selected.route.url)
|
|
228
|
+
return
|
|
229
|
+
}
|
|
230
|
+
} catch { /* Other frames follow normal validation. */ }
|
|
231
|
+
}
|
|
210
232
|
trace.frame('upstream.receive', data, binary)
|
|
211
233
|
if (!binary) {
|
|
212
234
|
try {
|
|
@@ -216,6 +238,7 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
216
238
|
rpcRequests.set(event.request_id, event.connection_id)
|
|
217
239
|
}
|
|
218
240
|
if (event.type === 'session.created') {
|
|
241
|
+
if (!diagnostics.target) { fail('voice_server_upgrade_required'); return }
|
|
219
242
|
if (clientRPC && event.harness_sync?.protocol === 'harness_sync_v1') resultPushConnection = event.harness_sync.connection_id
|
|
220
243
|
hintReporting=event.connection_hint_reporting===true
|
|
221
244
|
if (clientRPC && event.session?.config?.harness_control_transport !== 'client_rpc_v1') { fail('harness_rpc_backend_upgrade_required'); return }
|
|
@@ -235,22 +258,26 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
235
258
|
back.on('unexpected-response', (_request, response) => {
|
|
236
259
|
response.resume()
|
|
237
260
|
trace.event('upstream.handshake_failed', { status: response.statusCode })
|
|
261
|
+
diagnostics.add({event:'proxy.handshake_failed',status:response.statusCode})
|
|
238
262
|
fail([429, 503].includes(response.statusCode) ? 'capacity_exhausted' : response.statusCode === 426 ? 'plugin_upgrade_required' : 'voice_upstream_unavailable')
|
|
239
263
|
})
|
|
240
264
|
back.on('close', (code, reason) => {
|
|
241
265
|
trace.event('upstream.closed', { code, reason: reason.toString() })
|
|
266
|
+
diagnostics.add({event:'proxy.upstream_closed',code})
|
|
242
267
|
clearTimeout(startup)
|
|
243
268
|
if (code === 1013) fail('capacity_exhausted')
|
|
244
269
|
else front.close(code === 1000 ? 1000 : 1011)
|
|
245
270
|
})
|
|
246
271
|
for (const [data, binary] of pending.splice(0)) sendUpstream(data, binary)
|
|
247
272
|
})().catch(error => {
|
|
273
|
+
diagnostics.add({event:'proxy.handshake_failed',status:error.status})
|
|
248
274
|
if (!opening.signal.aborted) fail([429,503].includes(error.status)?'capacity_exhausted':error.status===426?'plugin_upgrade_required':'voice_upstream_unavailable')
|
|
249
275
|
})
|
|
250
276
|
front.on('error', error => { trace.event('browser.error', { message: error.message }); opening.abort(); back?.close() })
|
|
251
277
|
front.on('close', (code, reason) => {
|
|
278
|
+
diagnostics.add({event:'proxy.browser_closed',code})
|
|
252
279
|
trace.event('rpc.pending_at_close', { request_ids: [...rpcRequests.keys()] })
|
|
253
|
-
opening.abort(); clearTimeout(startup); back?.close()
|
|
280
|
+
opening.abort(); clearTimeout(startup); back?.close(1000, 'duet_browser_closed')
|
|
254
281
|
const timer = setTimeout(() => back?.terminate(), 1000)
|
|
255
282
|
timer.unref()
|
|
256
283
|
})
|
|
@@ -264,6 +291,12 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
264
291
|
connecting: [...connections.values()].filter(c => !c.ready).length,
|
|
265
292
|
traces: [...connections.values()].map(c => c.trace.snapshot()),
|
|
266
293
|
})
|
|
294
|
+
dispose.reportDiagnostic = (req, row) => {
|
|
295
|
+
const entry = reporters.get(row?.client_trace_id)
|
|
296
|
+
if (!entry || entry.page_id !== row.page_id) return
|
|
297
|
+
if (entry.user && feedback?.user(req) !== entry.user) return
|
|
298
|
+
entry.diagnostics.add(row)
|
|
299
|
+
}
|
|
267
300
|
dispose.closeConnections = code => {
|
|
268
301
|
for (const socket of connections.keys()) {
|
|
269
302
|
if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ type: 'error', error: { code } }))
|
|
@@ -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
|
+
}
|
|
@@ -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(
|
|
34
|
+
text: broadcastText(job.status === 'succeeded' ? (job.result || '未返回结果。')
|
|
35
|
+
: taskErrorText(job.error || job.result)),
|
|
18
36
|
}
|
|
19
37
|
}
|
package/src/shared/state.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Desired voice mode is independent of a temporarily suspended connection. */
|
|
2
|
-
export const PLUGIN_VERSION = '0.1.
|
|
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 : ''
|
|
@@ -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
|
}
|