dsh-duet 0.1.7 → 0.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -3
- package/package.json +2 -2
- package/src/client/audio.mjs +4 -2
- package/src/client/browser.mjs +111 -34
- package/src/client/composer-bridge.mjs +14 -3
- package/src/client/connection-hint.mjs +3 -2
- package/src/client/controls-layout.mjs +130 -9
- package/src/client/entry.js +1 -1
- package/src/client/feedback.mjs +1 -1
- package/src/client/harness-sync.mjs +105 -0
- package/src/client/identity.mjs +1 -1
- package/src/client/interactions.mjs +12 -5
- package/src/client/local-sync.mjs +63 -0
- package/src/client/rpc.mjs +9 -4
- package/src/client/settings.html +4 -4
- package/src/client/transport.mjs +2 -2
- package/src/client/tutorial-adapter.mjs +4 -4
- package/src/client/tutorial.mjs +3 -1
- package/src/host/assets.mjs +3 -0
- package/src/host/diagnostics.mjs +45 -0
- package/src/host/plugin.mjs +50 -4
- package/src/host/proxy.mjs +43 -5
- package/src/host/result-feed.mjs +15 -0
- package/src/host/sync-feed.mjs +72 -0
- package/src/shared/diagnostics.mjs +31 -0
- package/src/shared/result-notification.mjs +19 -1
- package/src/shared/state.mjs +13 -11
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'
|
|
@@ -57,9 +59,10 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
57
59
|
if (!['ws:', 'wss:'].includes(url.protocol) || url.username || url.password || url.hash) throw new Error('invalid_voice_endpoint')
|
|
58
60
|
}
|
|
59
61
|
const { WebSocket, WebSocketServer } = require('ws')
|
|
60
|
-
const server = new WebSocketServer({ noServer: true, maxPayload:
|
|
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,8 @@ 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
|
|
130
|
+
let resultPushConnection = null
|
|
120
131
|
const sendUpstream = (data, binary) => {
|
|
121
132
|
if (!binary) {
|
|
122
133
|
const message = JSON.parse(data.toString())
|
|
@@ -138,10 +149,11 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
138
149
|
if (binary) {
|
|
139
150
|
if (mode !== 'online' || !initialized) throw new Error('input_audio_disabled')
|
|
140
151
|
forward(raw, true)
|
|
152
|
+
if (!firstInput) { firstInput=true; diagnostics.add({event:'proxy.first_input_audio',bytes:raw.length}) }
|
|
141
153
|
return
|
|
142
154
|
}
|
|
143
155
|
const message = JSON.parse(raw.toString())
|
|
144
|
-
if (message.type === 'client.diagnostic')
|
|
156
|
+
if (message.type === 'client.diagnostic') { diagnostics.add(message); return }
|
|
145
157
|
if (message.type === 'client.connection_hint') {
|
|
146
158
|
if(hintReporting&&!hintReported&&mode==='online'&&connections.get(front)?.ready){
|
|
147
159
|
hintReported=true
|
|
@@ -160,7 +172,7 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
160
172
|
if (initialized) throw new Error('voice_mode_requires_reconnect')
|
|
161
173
|
initialized = true
|
|
162
174
|
forward(JSON.stringify({ type: 'session.update',
|
|
163
|
-
client: clientMetadata,
|
|
175
|
+
client: {...clientMetadata, diagnostics_protocol:DIAGNOSTICS_PROTOCOL},
|
|
164
176
|
session: {
|
|
165
177
|
type: 'realtime', preset_id: 'server_default',
|
|
166
178
|
io_mode:mode === 'tts_only'?'external_only':'online',
|
|
@@ -171,6 +183,11 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
171
183
|
return
|
|
172
184
|
}
|
|
173
185
|
if (!initialized) throw new Error('session_not_started')
|
|
186
|
+
if (message.type?.startsWith('harness.sync.')) {
|
|
187
|
+
if (!clientRPC || !resultPushConnection || message.connection_id !== resultPushConnection ||
|
|
188
|
+
!['subscribe','state','heartbeat','push','fallback'].some(kind => message.type === `harness.sync.${kind}`) || raw.length > (['harness.sync.subscribe','harness.sync.state'].includes(message.type) ? 2_000_000 : 100_000)) throw Error('invalid_harness_sync')
|
|
189
|
+
forward(raw.toString()); return
|
|
190
|
+
}
|
|
174
191
|
if (message.type === 'harness.composer.update') {
|
|
175
192
|
if (!clientRPC || raw.length > 100_000) throw new Error('invalid_composer_push')
|
|
176
193
|
forward(raw.toString())
|
|
@@ -201,6 +218,15 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
201
218
|
selectedConfig = {...selected.route.config, endpoints: {online:selected.route.url,tts_only:selected.route.url}}
|
|
202
219
|
trace.event('endpoint.selected', connectionRoute)
|
|
203
220
|
back.on('message', (data, binary) => {
|
|
221
|
+
if (!binary) {
|
|
222
|
+
try {
|
|
223
|
+
const offer = JSON.parse(data.toString())
|
|
224
|
+
if (offer.type === 'client.diagnostics.ready') {
|
|
225
|
+
diagnostics.offer(offer, selectedConfig, selected.route.url)
|
|
226
|
+
return
|
|
227
|
+
}
|
|
228
|
+
} catch { /* Other frames follow normal validation. */ }
|
|
229
|
+
}
|
|
204
230
|
trace.frame('upstream.receive', data, binary)
|
|
205
231
|
if (!binary) {
|
|
206
232
|
try {
|
|
@@ -210,6 +236,8 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
210
236
|
rpcRequests.set(event.request_id, event.connection_id)
|
|
211
237
|
}
|
|
212
238
|
if (event.type === 'session.created') {
|
|
239
|
+
if (!diagnostics.target) { fail('voice_server_upgrade_required'); return }
|
|
240
|
+
if (clientRPC && event.harness_sync?.protocol === 'harness_sync_v1') resultPushConnection = event.harness_sync.connection_id
|
|
213
241
|
hintReporting=event.connection_hint_reporting===true
|
|
214
242
|
if (clientRPC && event.session?.config?.harness_control_transport !== 'client_rpc_v1') { fail('harness_rpc_backend_upgrade_required'); return }
|
|
215
243
|
if (mode === 'tts_only' && event.session?.config?.external_message_protocol !== 'harness_result_v2') { fail('harness_result_backend_upgrade_required'); return }
|
|
@@ -228,22 +256,26 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
228
256
|
back.on('unexpected-response', (_request, response) => {
|
|
229
257
|
response.resume()
|
|
230
258
|
trace.event('upstream.handshake_failed', { status: response.statusCode })
|
|
259
|
+
diagnostics.add({event:'proxy.handshake_failed',status:response.statusCode})
|
|
231
260
|
fail([429, 503].includes(response.statusCode) ? 'capacity_exhausted' : response.statusCode === 426 ? 'plugin_upgrade_required' : 'voice_upstream_unavailable')
|
|
232
261
|
})
|
|
233
262
|
back.on('close', (code, reason) => {
|
|
234
263
|
trace.event('upstream.closed', { code, reason: reason.toString() })
|
|
264
|
+
diagnostics.add({event:'proxy.upstream_closed',code})
|
|
235
265
|
clearTimeout(startup)
|
|
236
266
|
if (code === 1013) fail('capacity_exhausted')
|
|
237
267
|
else front.close(code === 1000 ? 1000 : 1011)
|
|
238
268
|
})
|
|
239
269
|
for (const [data, binary] of pending.splice(0)) sendUpstream(data, binary)
|
|
240
270
|
})().catch(error => {
|
|
271
|
+
diagnostics.add({event:'proxy.handshake_failed',status:error.status})
|
|
241
272
|
if (!opening.signal.aborted) fail([429,503].includes(error.status)?'capacity_exhausted':error.status===426?'plugin_upgrade_required':'voice_upstream_unavailable')
|
|
242
273
|
})
|
|
243
274
|
front.on('error', error => { trace.event('browser.error', { message: error.message }); opening.abort(); back?.close() })
|
|
244
275
|
front.on('close', (code, reason) => {
|
|
276
|
+
diagnostics.add({event:'proxy.browser_closed',code})
|
|
245
277
|
trace.event('rpc.pending_at_close', { request_ids: [...rpcRequests.keys()] })
|
|
246
|
-
opening.abort(); clearTimeout(startup); back?.close()
|
|
278
|
+
opening.abort(); clearTimeout(startup); back?.close(1000, 'duet_browser_closed')
|
|
247
279
|
const timer = setTimeout(() => back?.terminate(), 1000)
|
|
248
280
|
timer.unref()
|
|
249
281
|
})
|
|
@@ -257,6 +289,12 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
257
289
|
connecting: [...connections.values()].filter(c => !c.ready).length,
|
|
258
290
|
traces: [...connections.values()].map(c => c.trace.snapshot()),
|
|
259
291
|
})
|
|
292
|
+
dispose.reportDiagnostic = (req, row) => {
|
|
293
|
+
const entry = reporters.get(row?.client_trace_id)
|
|
294
|
+
if (!entry || entry.page_id !== row.page_id) return
|
|
295
|
+
if (entry.user && feedback?.user(req) !== entry.user) return
|
|
296
|
+
entry.diagnostics.add(row)
|
|
297
|
+
}
|
|
260
298
|
dispose.closeConnections = code => {
|
|
261
299
|
for (const socket of connections.keys()) {
|
|
262
300
|
if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ type: 'error', error: { code } }))
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Legacy HTTP completion waiters; current pages use the local event stream. */
|
|
2
|
+
export class ResultFeed {
|
|
3
|
+
constructor() { this.waiters = new Set() }
|
|
4
|
+
notify() { for (const done of [...this.waiters]) done() }
|
|
5
|
+
wait(req, res, timeout = 25000) {
|
|
6
|
+
return new Promise(resolve => {
|
|
7
|
+
const done = () => {
|
|
8
|
+
clearTimeout(timer); this.waiters.delete(done)
|
|
9
|
+
res.off('close', done); req.off('aborted', done); resolve()
|
|
10
|
+
}
|
|
11
|
+
const timer = setTimeout(done, timeout)
|
|
12
|
+
this.waiters.add(done); res.once('close', done); req.once('aborted', done)
|
|
13
|
+
})
|
|
14
|
+
}
|
|
15
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { WebSocketServer } from 'ws'
|
|
2
|
+
|
|
3
|
+
/** Authenticated local event stream. No timers that query DSH state. */
|
|
4
|
+
export function registerSyncFeed(ctx, { snapshot, touch, commands }) {
|
|
5
|
+
const server = new WebSocketServer({ noServer: true, maxPayload: 16000 })
|
|
6
|
+
const clients = new Set()
|
|
7
|
+
const unregister = ctx.webServer.registerUpgrade({
|
|
8
|
+
path: '/duplex-control/sync/ws',
|
|
9
|
+
handler(req, socket, head) {
|
|
10
|
+
let allowed = !req.headers.origin
|
|
11
|
+
try { if (req.headers.origin) allowed = new URL(req.headers.origin).host === req.headers.host } catch {}
|
|
12
|
+
if (!allowed || ctx.connection?.requestRejection(req) || clients.size >= 64) {
|
|
13
|
+
socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n'); return
|
|
14
|
+
}
|
|
15
|
+
server.handleUpgrade(req, socket, head, ws => {
|
|
16
|
+
const c = { ws, cursor: null, epoch: null, owner: null, busy: false, dirty: false, timer: null }
|
|
17
|
+
clients.add(c)
|
|
18
|
+
const send = value => {
|
|
19
|
+
if (ws.readyState !== 1) return
|
|
20
|
+
const raw = JSON.stringify(value)
|
|
21
|
+
if (Buffer.byteLength(raw) > 2_000_000 || ws.bufferedAmount > 2_000_000) { ws.close(1013, 'sync_backpressure'); return }
|
|
22
|
+
ws.send(raw)
|
|
23
|
+
}
|
|
24
|
+
c.flush = async () => {
|
|
25
|
+
if (c.busy || ws.readyState !== 1) { c.dirty = true; return }
|
|
26
|
+
c.busy = true; c.dirty = false
|
|
27
|
+
try {
|
|
28
|
+
const value = await snapshot(c.cursor, c.epoch)
|
|
29
|
+
c.epoch = value.epoch
|
|
30
|
+
c.cursor ??= value.cursor
|
|
31
|
+
c.sentCursor = value.cursor
|
|
32
|
+
send({ type: 'harness.sync.snapshot', protocol: 'harness_sync_v1', ...value })
|
|
33
|
+
} catch { ws.close(1011, 'sync_snapshot_failed') }
|
|
34
|
+
finally { c.busy = false; if (c.dirty) c.schedule() }
|
|
35
|
+
}
|
|
36
|
+
c.schedule = () => { if (!c.timer) c.timer = setTimeout(() => { c.timer = null; void c.flush() }, 50) }
|
|
37
|
+
c.commands = () => {
|
|
38
|
+
if (c.owner) for (const request of commands(c.owner.client_id)) send({ type: 'harness.sync.command', request })
|
|
39
|
+
}
|
|
40
|
+
ws.on('message', raw => {
|
|
41
|
+
try {
|
|
42
|
+
const event = JSON.parse(raw)
|
|
43
|
+
if (event.type === 'harness.sync.subscribe' && event.protocol === 'harness_sync_v1') {
|
|
44
|
+
if (event.cursor != null && (!Number.isSafeInteger(event.cursor) || event.cursor < 0)) throw Error()
|
|
45
|
+
c.cursor = event.cursor ?? null; c.epoch = event.epoch ?? null; c.schedule()
|
|
46
|
+
} else if (event.type === 'harness.sync.received' && event.epoch === c.epoch) {
|
|
47
|
+
if (!Number.isSafeInteger(event.cursor) || event.cursor < (c.cursor ?? 0) || event.cursor > c.sentCursor) throw Error()
|
|
48
|
+
c.cursor = event.cursor
|
|
49
|
+
if (event.more === true) c.schedule()
|
|
50
|
+
} else if (event.type === 'harness.sync.refresh') c.schedule()
|
|
51
|
+
else if (event.type === 'harness.sync.heartbeat') {
|
|
52
|
+
const owner = event.owner
|
|
53
|
+
if (owner !== null && (!owner || typeof owner.client_id !== 'string' || owner.client_id.length > 128
|
|
54
|
+
|| (owner.session_id !== null && typeof owner.session_id !== 'string'))) throw Error()
|
|
55
|
+
c.owner = owner
|
|
56
|
+
if (owner) touch(owner)
|
|
57
|
+
c.commands()
|
|
58
|
+
send({ type: 'harness.sync.alive' })
|
|
59
|
+
} else throw Error()
|
|
60
|
+
} catch { ws.close(1008, 'invalid_sync_message') }
|
|
61
|
+
})
|
|
62
|
+
ws.on('error', () => {})
|
|
63
|
+
ws.on('close', () => { clearTimeout(c.timer); clients.delete(c) })
|
|
64
|
+
})
|
|
65
|
+
},
|
|
66
|
+
})
|
|
67
|
+
return {
|
|
68
|
+
changed() { for (const c of clients) c.schedule() },
|
|
69
|
+
commands() { for (const c of clients) c.commands() },
|
|
70
|
+
close() { unregister(); for (const c of clients) c.ws.close(1001); server.close() },
|
|
71
|
+
}
|
|
72
|
+
}
|
|
@@ -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.9'
|
|
3
3
|
export const IDLE_RELEASE_MS = 60_000
|
|
4
4
|
|
|
5
5
|
const safeVersion = value => typeof value === 'string' && value.length <= 32 && /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value) ? value : ''
|
|
@@ -41,25 +41,26 @@ export class DuetState {
|
|
|
41
41
|
toggleMic() { return this.setMode(this.mode === 'online' ? 'off' : 'online') }
|
|
42
42
|
toggleSpeaker() { return this.setMode(this.mode === 'tts_only' ? 'off' : 'tts_only') }
|
|
43
43
|
|
|
44
|
-
async setMode(mode) {
|
|
44
|
+
async setMode(mode, details = {}) {
|
|
45
45
|
if (!['off', 'tts_only', 'online'].includes(mode)) throw new Error('invalid_voice_mode')
|
|
46
46
|
if (mode === this.mode && !this.suspended) return
|
|
47
|
+
const reason = details.reason || (mode === 'off' ? 'user_off' : 'mode_switch')
|
|
47
48
|
this.mode = mode
|
|
48
49
|
this.suspended = false
|
|
49
50
|
this.idleSince = null
|
|
50
51
|
if (mode === 'off') this.pending.clear()
|
|
51
|
-
// Online
|
|
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
|
}
|