dsh-duet 0.1.2 → 0.1.4
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 +7 -6
- package/package.json +2 -2
- package/src/client/audio.mjs +37 -2
- package/src/client/browser.mjs +98 -63
- package/src/client/composer-bridge.mjs +201 -0
- package/src/client/composer.mjs +23 -0
- package/src/client/connection-hint.mjs +33 -7
- package/src/client/controls-layout.mjs +18 -0
- package/src/client/entry.js +1 -408
- package/src/client/feedback.mjs +11 -6
- package/src/client/notice.mjs +47 -0
- package/src/client/rpc.mjs +6 -2
- package/src/client/settings.html +3 -3
- package/src/client/tutorial-adapter.mjs +18 -12
- package/src/client/tutorial.mjs +15 -1
- package/src/host/assets.mjs +4 -0
- package/src/host/endpoint-discovery.mjs +185 -0
- package/src/host/feedback-files.mjs +5 -5
- package/src/host/feedback-store.mjs +3 -3
- package/src/host/notices.mjs +1 -1
- package/src/host/plugin.mjs +43 -16
- package/src/host/proxy.mjs +54 -17
- package/src/host/service-defaults.mjs +12 -4
- package/src/host/service-info.mjs +2 -1
- package/src/host/session-metadata.mjs +17 -0
- package/src/host/settings.mjs +19 -7
- package/src/host/storage-paths.mjs +28 -0
- package/src/host/trace.mjs +2 -2
- package/src/shared/connection-guidance.mjs +9 -0
- package/src/shared/state.mjs +5 -1
package/README.md
CHANGED
|
@@ -1,16 +1,17 @@
|
|
|
1
|
-
# duet
|
|
1
|
+
# duet.
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**DSH 语音操控和语音播报**
|
|
4
|
+
|
|
5
|
+
https://github.com/user-attachments/assets/83152138-c292-4057-a820-efc2bc96f33a
|
|
4
6
|
|
|
5
7
|
duet,意为「二重奏」。这里的 duet 使用全双工语音模型,可以边听边说,
|
|
6
8
|
让你与 DSH 的交流不必一人一句地等待。
|
|
7
9
|
|
|
8
|
-
|
|
9
|
-
任务完成后,duet 会简短播报结果,让你不用一直盯着屏幕。
|
|
10
|
+
说出需求、修改输入、发送任务、切换会话——把键盘上的操作交给声音。你可以随时插话、补充或纠正。处理任务之外,也可以聊聊天。
|
|
10
11
|
|
|
11
|
-
|
|
12
|
+
当然,你也可以用 duet 帮你只播报结果,让你不用一直盯着屏幕。
|
|
12
13
|
|
|
13
|
-
|
|
14
|
+
最重要的是,duet 语音服务目前可以免费使用。
|
|
14
15
|
|
|
15
16
|
## 安装
|
|
16
17
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-duet",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.4",
|
|
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",
|
|
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/resilience.mjs && node tests/browser/page-binding.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,4 @@
|
|
|
1
|
-
import { microphoneConstraints } from './microphone.mjs?v=0.1.
|
|
1
|
+
import { microphoneConstraints } from './microphone.mjs?v=0.1.4'
|
|
2
2
|
|
|
3
3
|
/** Browser-owned microphone and PCM playback. No microphone is requested in tts_only. */
|
|
4
4
|
export class DuetAudio {
|
|
@@ -12,6 +12,7 @@ export class DuetAudio {
|
|
|
12
12
|
this.epoch = 0
|
|
13
13
|
this.nextTime = 0
|
|
14
14
|
this.tones = new Set()
|
|
15
|
+
this.captureCleanup = null
|
|
15
16
|
}
|
|
16
17
|
|
|
17
18
|
prepare() {
|
|
@@ -36,12 +37,43 @@ export class DuetAudio {
|
|
|
36
37
|
}
|
|
37
38
|
}
|
|
38
39
|
|
|
39
|
-
async startMic(send) {
|
|
40
|
+
async startMic(send, onFailure = () => {}) {
|
|
40
41
|
const epoch = this.epoch
|
|
41
42
|
// Exact selection: an unplugged device must not silently use a different mic.
|
|
42
43
|
const stream = await navigator.mediaDevices.getUserMedia(microphoneConstraints())
|
|
43
44
|
if (epoch !== this.epoch) { stream.getTracks().forEach(t => t.stop()); return }
|
|
44
45
|
this.stream = stream
|
|
46
|
+
let failed = false
|
|
47
|
+
const cleanups = [], muteTimers = new Map()
|
|
48
|
+
const fail = code => {
|
|
49
|
+
if (failed || epoch !== this.epoch) return
|
|
50
|
+
failed = true
|
|
51
|
+
this.stop()
|
|
52
|
+
onFailure(code)
|
|
53
|
+
}
|
|
54
|
+
const watch = (target, event, fn) => {
|
|
55
|
+
target.addEventListener(event, fn)
|
|
56
|
+
cleanups.push(() => target.removeEventListener(event, fn))
|
|
57
|
+
}
|
|
58
|
+
this.captureCleanup = () => {
|
|
59
|
+
for (const cleanup of cleanups) cleanup()
|
|
60
|
+
for (const timer of muteTimers.values()) clearTimeout(timer)
|
|
61
|
+
muteTimers.clear()
|
|
62
|
+
}
|
|
63
|
+
for (const track of stream.getAudioTracks()) {
|
|
64
|
+
const muted = () => {
|
|
65
|
+
clearTimeout(muteTimers.get(track))
|
|
66
|
+
// Brief device transitions can recover. This is a media-track failure
|
|
67
|
+
// signal, not an energy/VAD test: ordinary user silence never trips it.
|
|
68
|
+
muteTimers.set(track, setTimeout(() => { if (track.muted) fail('audio_capture_failed') }, 10000))
|
|
69
|
+
}
|
|
70
|
+
watch(track, 'ended', () => fail('microphone_disconnected'))
|
|
71
|
+
watch(track, 'mute', muted)
|
|
72
|
+
watch(track, 'unmute', () => { clearTimeout(muteTimers.get(track)); muteTimers.delete(track) })
|
|
73
|
+
if (track.readyState === 'ended') fail('microphone_disconnected')
|
|
74
|
+
else if (track.muted) muted()
|
|
75
|
+
}
|
|
76
|
+
if (epoch !== this.epoch) return
|
|
45
77
|
const code = `class Capture extends AudioWorkletProcessor {
|
|
46
78
|
constructor(){super();this.phase=0;this.sum=0;this.count=0;this.pcm=new Int16Array(1280);this.offset=0;}
|
|
47
79
|
process(inputs){const a=inputs[0]?.[0];if(!a)return true;
|
|
@@ -56,6 +88,7 @@ export class DuetAudio {
|
|
|
56
88
|
if (epoch !== this.epoch) { stream.getTracks().forEach(t => t.stop()); return }
|
|
57
89
|
this.source = this.context.createMediaStreamSource(stream)
|
|
58
90
|
this.capture = new AudioWorkletNode(this.context, 'duet-audio-capture')
|
|
91
|
+
watch(this.capture, 'processorerror', () => fail('audio_capture_failed'))
|
|
59
92
|
this.capture.port.onmessage = e => { if (epoch === this.epoch) send(e.data) }
|
|
60
93
|
this.mute = this.context.createGain()
|
|
61
94
|
this.mute.gain.value = 0
|
|
@@ -122,6 +155,8 @@ export class DuetAudio {
|
|
|
122
155
|
|
|
123
156
|
stop() {
|
|
124
157
|
this.epoch++
|
|
158
|
+
this.captureCleanup?.()
|
|
159
|
+
this.captureCleanup = null
|
|
125
160
|
for (const tone of this.tones) { try { tone.stop() } catch {} }
|
|
126
161
|
this.tones.clear()
|
|
127
162
|
this.stream?.getTracks().forEach(t => t.stop())
|
package/src/client/browser.mjs
CHANGED
|
@@ -1,27 +1,34 @@
|
|
|
1
|
-
import { DuetState, PLUGIN_VERSION } from '../shared/state.mjs?v=0.1.
|
|
2
|
-
import { DuetAudio } from './audio.mjs?v=0.1.
|
|
3
|
-
import { HarnessRPCExecutor } from './rpc.mjs?v=0.1.
|
|
4
|
-
import { composerAccess, observeComposer, focusedSession } from './composer.mjs?v=0.1.
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
1
|
+
import { DuetState, PLUGIN_VERSION } from '../shared/state.mjs?v=0.1.4'
|
|
2
|
+
import { DuetAudio } from './audio.mjs?v=0.1.4'
|
|
3
|
+
import { HarnessRPCExecutor } from './rpc.mjs?v=0.1.4'
|
|
4
|
+
import { composerAccess, observeComposer, focusedSession, openLocalSession } from './composer.mjs?v=0.1.4'
|
|
5
|
+
import { startComposerBridge } from './composer-bridge.mjs?v=0.1.4'
|
|
6
|
+
import { mountTutorial } from './tutorial.mjs?v=0.1.4'
|
|
7
|
+
import { tutorialAdapter } from './tutorial-adapter.mjs?v=0.1.4'
|
|
8
|
+
import { mountRating } from './feedback.mjs?v=0.1.4'
|
|
9
|
+
import { createAudioUploadConsent } from './consent.mjs?v=0.1.4'
|
|
10
|
+
import { bindDuetShortcuts } from './shortcuts.mjs?v=0.1.4'
|
|
11
|
+
import { nativeInteractions } from './interactions.mjs?v=0.1.4'
|
|
12
|
+
import { mountConnectionHint } from './connection-hint.mjs?v=0.1.4'
|
|
13
|
+
import { mountControlsLayout } from './controls-layout.mjs?v=0.1.4'
|
|
14
|
+
import { mountNotice } from './notice.mjs?v=0.1.4'
|
|
15
|
+
import { workspaceIssue, requireWorkspace, browserSessionCatalog } from './workspaces.mjs?v=0.1.4'
|
|
13
16
|
|
|
14
17
|
export function mountDuet(ctx) {
|
|
18
|
+
const pageId = crypto.randomUUID()
|
|
15
19
|
const audio = new DuetAudio()
|
|
16
20
|
const audioConsent = createAudioUploadConsent()
|
|
17
|
-
let disposed = false, controls,
|
|
21
|
+
let disposed = false, controls, pollRunning = false, cursor = null, resultEpoch = null
|
|
22
|
+
let nextPollAt = 0, pollController, pollWakePending = false, pollFailureSince = null, pollFailures = 0, pollGeneration = -1
|
|
23
|
+
const notices = mountNotice(() => controls)
|
|
18
24
|
const labels = new Map()
|
|
19
25
|
let clientTraceId = null, diagnosticCount = 0
|
|
20
|
-
let
|
|
26
|
+
let connectionGuidance = null, reportHintShown = null
|
|
27
|
+
let tutorial, teaching, ratingPanel, connectionHint, stopControlsLayout
|
|
21
28
|
const diagnostic = data => {
|
|
22
29
|
if (++diagnosticCount > 100) return
|
|
23
30
|
const bounded = Object.fromEntries(Object.entries(data).map(([k, v]) => [k, typeof v === 'string' ? v.slice(0, 4000) : v]))
|
|
24
|
-
const body = JSON.stringify({ client_trace_id: clientTraceId, plugin_version: PLUGIN_VERSION,
|
|
31
|
+
const body = JSON.stringify({ client_trace_id: clientTraceId, plugin_version: PLUGIN_VERSION, page_id: pageId,
|
|
25
32
|
utc: new Date().toISOString(), visibility: document.visibilityState, ...bounded })
|
|
26
33
|
if (body.length > 24000) return
|
|
27
34
|
void fetch('/duplex-control/api/voice/diagnostic', { method: 'POST', credentials: 'same-origin',
|
|
@@ -33,31 +40,12 @@ export function mountDuet(ctx) {
|
|
|
33
40
|
const notice = (text, { upgrade = false } = {}) => {
|
|
34
41
|
connectionHint?.dismiss()
|
|
35
42
|
if (upgrade) { ratingPanel?.dispose(); ratingPanel = null }
|
|
36
|
-
|
|
37
|
-
if (!toast) return
|
|
38
|
-
toast.textContent = text
|
|
39
|
-
toast.hidden = false
|
|
40
|
-
clearTimeout(toastTimer)
|
|
41
|
-
if (upgrade) {
|
|
42
|
-
const help = document.createElement('details')
|
|
43
|
-
const title = document.createElement('summary')
|
|
44
|
-
title.textContent = '如何升级'
|
|
45
|
-
help.append(title)
|
|
46
|
-
const instruction = document.createElement('p')
|
|
47
|
-
instruction.textContent = '通过 npm 安装的用户,可在终端运行:'
|
|
48
|
-
const command = document.createElement('code')
|
|
49
|
-
command.textContent = 'dsh plugin --profile web add dsh-duet@latest'
|
|
50
|
-
command.style.cssText = 'display:block;white-space:normal;overflow-wrap:anywhere;margin:8px 0'
|
|
51
|
-
const after = document.createElement('p')
|
|
52
|
-
after.textContent = '其他安装方式请从原来源更新。完成后重启 DSH 并刷新页面,再手动开启语音。'
|
|
53
|
-
help.append(instruction, command, after)
|
|
54
|
-
const dismiss = document.createElement('button')
|
|
55
|
-
dismiss.textContent = '知道了'
|
|
56
|
-
dismiss.onclick = () => { toast.hidden = true }
|
|
57
|
-
toast.append(help, dismiss)
|
|
58
|
-
} else toastTimer = setTimeout(() => { toast.hidden = true }, 8000)
|
|
43
|
+
notices.show(text, { upgrade })
|
|
59
44
|
}
|
|
60
45
|
const draw = state => {
|
|
46
|
+
if (pollGeneration !== state.generation) {
|
|
47
|
+
pollGeneration = state.generation; nextPollAt = 0; pollFailureSince = null; pollFailures = 0
|
|
48
|
+
}
|
|
61
49
|
if (!controls) return
|
|
62
50
|
for (const [kind, active] of [['mic', state.mode === 'online'], ['speaker', state.mode === 'tts_only']]) {
|
|
63
51
|
const button = controls.querySelector(`[data-voice=${kind}]`)
|
|
@@ -77,15 +65,20 @@ export function mountDuet(ctx) {
|
|
|
77
65
|
const mark = controls.querySelector('[data-duet-mark]')
|
|
78
66
|
mark.style.color = state.ready ? '#7fd6a6' : '#ed9b35'
|
|
79
67
|
mark.title = state.ready ? '语音已连接' : '语音未连接'
|
|
80
|
-
connectionHint?.update({ mode: state.mode, ready: state.ready, teaching: Boolean(tutorial?.active) })
|
|
68
|
+
connectionHint?.update({ mode: state.mode, ready: state.ready, teaching: Boolean(tutorial?.active), guidance:connectionGuidance })
|
|
81
69
|
}
|
|
82
70
|
const connect = (mode, receive) => {
|
|
83
71
|
requireWorkspace(ctx)
|
|
84
72
|
if (!audioConsent.granted()) throw Error('data_upload_consent_required')
|
|
85
73
|
clientTraceId = crypto.randomUUID(); diagnosticCount = 0
|
|
74
|
+
connectionGuidance = null; reportHintShown = null
|
|
86
75
|
const connectionTraceId = clientTraceId
|
|
87
76
|
const report = data => diagnostic({ ...data, client_trace_id: connectionTraceId, mode })
|
|
88
|
-
let ws, closed = false, release, ready = false, stopComposer
|
|
77
|
+
let ws, closed = false, release, ready = false, stopComposer, stopBridge
|
|
78
|
+
const opening = new AbortController()
|
|
79
|
+
const startupTimer = setTimeout(() => {
|
|
80
|
+
if (!closed) receive({ type: 'error', code: 'voice_start_timeout' })
|
|
81
|
+
}, 45000)
|
|
89
82
|
const send = message => {
|
|
90
83
|
if (ws?.readyState !== WebSocket.OPEN || closed) return
|
|
91
84
|
if (ws.bufferedAmount > 1_000_000) { receive({ type: 'error', code: 'voice_backpressure' }); return }
|
|
@@ -94,7 +87,15 @@ export function mountDuet(ctx) {
|
|
|
94
87
|
const composer = composerAccess(ctx, id => labels.get(id) || id)
|
|
95
88
|
const interactions = nativeInteractions(ctx)
|
|
96
89
|
const rpc = new HarnessRPCExecutor(send, fetch, report, async (request, signal) =>
|
|
97
|
-
(await interactions(request, signal)) ?? composer.execute(request, signal), rows =>
|
|
90
|
+
(await interactions(request, signal)) ?? composer.execute(request, signal), rows =>
|
|
91
|
+
browserSessionCatalog(ctx, rows).map(row => ({ ...row, active: row.session_id === focusedSession(ctx) })), {
|
|
92
|
+
id: connectionTraceId,
|
|
93
|
+
completed: async (request, body, signal) => {
|
|
94
|
+
const id = request.path.endsWith('/activate') ? body.active_session_id
|
|
95
|
+
: request.path.endsWith('/fork') ? body.session?.session_id : null
|
|
96
|
+
if (id) await openLocalSession(ctx, id, signal)
|
|
97
|
+
},
|
|
98
|
+
})
|
|
98
99
|
const connection = {
|
|
99
100
|
feedbackTicket: null,
|
|
100
101
|
send,
|
|
@@ -103,7 +104,10 @@ export function mountDuet(ctx) {
|
|
|
103
104
|
async close() {
|
|
104
105
|
report({ event: 'browser.connection_close', buffered_bytes: ws?.bufferedAmount })
|
|
105
106
|
closed = true
|
|
107
|
+
clearTimeout(startupTimer)
|
|
108
|
+
opening.abort()
|
|
106
109
|
stopComposer?.()
|
|
110
|
+
stopBridge?.(); stopBridge = null
|
|
107
111
|
rpc.close()
|
|
108
112
|
audio.stop()
|
|
109
113
|
if (ws && ws.readyState !== WebSocket.CLOSED) {
|
|
@@ -119,12 +123,17 @@ export function mountDuet(ctx) {
|
|
|
119
123
|
const open = async () => {
|
|
120
124
|
if (closed) return
|
|
121
125
|
// Establish/renew the host-signed anonymous cookie before the WS handshake.
|
|
122
|
-
const
|
|
126
|
+
const configTimer = setTimeout(() => opening.abort(Error('voice_start_timeout')), 10000)
|
|
127
|
+
let identity
|
|
128
|
+
try { identity = await fetch('/duplex-control/api/voice/config', {credentials:'same-origin',cache:'no-store',signal:opening.signal}) }
|
|
129
|
+
finally { clearTimeout(configTimer) }
|
|
123
130
|
if(!identity.ok)throw Error('voice_config_unavailable')
|
|
124
131
|
requireWorkspace(ctx)
|
|
125
132
|
if(closed)return
|
|
133
|
+
if (mode === 'online') stopBridge = startComposerBridge(ctx, connectionTraceId)
|
|
134
|
+
report({ event: 'browser.connection_start', page_binding: 'connection_owner_v1' })
|
|
126
135
|
const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:'
|
|
127
|
-
ws = new WebSocket(`${protocol}//${location.host}/duplex-control/voice/ws?mode=${mode}&plugin_version=${PLUGIN_VERSION}&client_trace_id=${connectionTraceId}`)
|
|
136
|
+
ws = new WebSocket(`${protocol}//${location.host}/duplex-control/voice/ws?mode=${mode}&plugin_version=${PLUGIN_VERSION}&client_trace_id=${connectionTraceId}&page_id=${pageId}`)
|
|
128
137
|
ws.onopen = () => {
|
|
129
138
|
send({ type: 'session.update' })
|
|
130
139
|
if (mode === 'online') stopComposer = observeComposer(ctx, composer, send)
|
|
@@ -146,13 +155,21 @@ export function mountDuet(ctx) {
|
|
|
146
155
|
compatibility: message.error?.compatibility, policy: message.error?.policy }); return
|
|
147
156
|
}
|
|
148
157
|
if (message.type === 'session.created' && !ready) {
|
|
158
|
+
connectionGuidance=message.connection_route?.connection_hint
|
|
159
|
+
reportHintShown=hint=>{
|
|
160
|
+
report({event:'browser.connection_hint_shown',connection_hint:hint})
|
|
161
|
+
if(message.connection_hint_reporting===true)send({type:'client.connection_hint',connection_hint:hint})
|
|
162
|
+
}
|
|
163
|
+
report({event:'browser.endpoint_selected', connection_route:message.connection_route})
|
|
149
164
|
if (message.compatibility) receive({ type: 'compatibility', compatibility: message.compatibility })
|
|
150
165
|
connection.feedbackTicket = message.feedback_session_ticket || null
|
|
151
166
|
ready = true
|
|
152
167
|
await audio.prepare()
|
|
153
168
|
if (closed) return
|
|
154
169
|
if (mode === 'online') {
|
|
155
|
-
try { await audio.startMic(send
|
|
170
|
+
try { await audio.startMic(send, code => {
|
|
171
|
+
if (!closed) { report({event:'browser.capture_failed',code}); receive({type:'error',code}) }
|
|
172
|
+
}) }
|
|
156
173
|
catch (error) {
|
|
157
174
|
report({ event: 'browser.microphone_failed', name: error?.name })
|
|
158
175
|
if (!closed) receive({ type: 'error', code: 'microphone_unavailable' })
|
|
@@ -163,6 +180,7 @@ export function mountDuet(ctx) {
|
|
|
163
180
|
context_state: audio.context?.state, base_latency: audio.context?.baseLatency,
|
|
164
181
|
user_agent: navigator.userAgent })
|
|
165
182
|
if (!closed) {
|
|
183
|
+
clearTimeout(startupTimer)
|
|
166
184
|
receive({ type: 'ready' })
|
|
167
185
|
try { audio.connectedChime() } catch { /* A notification must not break voice. */ }
|
|
168
186
|
}
|
|
@@ -178,6 +196,7 @@ export function mountDuet(ctx) {
|
|
|
178
196
|
}
|
|
179
197
|
ws.onclose = event => {
|
|
180
198
|
stopComposer?.()
|
|
199
|
+
stopBridge?.(); stopBridge = null
|
|
181
200
|
report({ event: 'browser.ws_closed', code: event.code, reason: event.reason, was_clean: event.wasClean })
|
|
182
201
|
rpc.close()
|
|
183
202
|
release?.()
|
|
@@ -190,7 +209,9 @@ export function mountDuet(ctx) {
|
|
|
190
209
|
if (closed) return
|
|
191
210
|
if (!lock) { receive({ type: 'error', code: 'voice_tab_in_use' }); return }
|
|
192
211
|
const held = new Promise(resolve => { release = resolve })
|
|
193
|
-
|
|
212
|
+
// Opening may hang; ownership ends when close() releases it, not when
|
|
213
|
+
// a fetch or browser permission request eventually resolves.
|
|
214
|
+
void open().catch(error => { if (!closed) receive({type:'error',code:opening.signal.aborted?'voice_start_timeout':error.message||'voice_connection_failed'}) })
|
|
194
215
|
await held
|
|
195
216
|
}).catch(() => { if (!closed) receive({ type: 'error', code: 'voice_connection_failed' }) })
|
|
196
217
|
} else queueMicrotask(() => receive({ type: 'error', code: 'voice_lock_unavailable' }))
|
|
@@ -266,14 +287,10 @@ export function mountDuet(ctx) {
|
|
|
266
287
|
settings.style.cssText = 'display:flex;color:inherit;padding:5px;border-radius:6px'
|
|
267
288
|
settings.innerHTML = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.325.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 0 1 1.37.49l1.296 2.247a1.125 1.125 0 0 1-.26 1.431l-1.003.827c-.293.241-.438.613-.43.992a7.723 7.723 0 0 1 0 .255c-.008.378.137.75.43.991l1.004.827c.424.35.534.955.26 1.43l-1.298 2.247a1.125 1.125 0 0 1-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.47 6.47 0 0 1-.22.128c-.331.183-.581.495-.644.869l-.213 1.281c-.09.543-.56.94-1.11.94h-2.594c-.55 0-1.019-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 0 1-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 0 1-1.369-.49l-1.297-2.247a1.125 1.125 0 0 1 .26-1.431l1.004-.827c.292-.24.437-.613.43-.991a6.932 6.932 0 0 1 0-.255c.007-.38-.138-.751-.43-.992l-1.004-.827a1.125 1.125 0 0 1-.26-1.43l1.297-2.247a1.125 1.125 0 0 1 1.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.086.22-.128.332-.183.582-.495.644-.869l.214-1.28Z"/><path d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"/></svg>'
|
|
268
289
|
controls.append(settings)
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
toast.setAttribute('aria-live', 'polite')
|
|
272
|
-
toast.hidden = true
|
|
273
|
-
toast.style.cssText = 'position:absolute;bottom:100%;left:0;z-index:9999;min-width:180px;max-width:280px;background:#252c38;color:white;padding:10px;border-radius:8px;font-size:12px;box-shadow:0 3px 18px #0005'
|
|
274
|
-
controls.append(toast)
|
|
290
|
+
stopControlsLayout?.()
|
|
291
|
+
stopControlsLayout = mountControlsLayout(controls)
|
|
275
292
|
connectionHint?.dispose()
|
|
276
|
-
connectionHint = mountConnectionHint(controls)
|
|
293
|
+
connectionHint = mountConnectionHint(controls,{onShown:hint=>reportHintShown?.(hint)})
|
|
277
294
|
draw(state)
|
|
278
295
|
}
|
|
279
296
|
mount()
|
|
@@ -281,25 +298,27 @@ export function mountDuet(ctx) {
|
|
|
281
298
|
const observer = new MutationObserver(mount)
|
|
282
299
|
observer.observe(document.body, { subtree: true, childList: true })
|
|
283
300
|
|
|
284
|
-
const api = async path => {
|
|
301
|
+
const api = async (path, signal) => {
|
|
285
302
|
const response = await fetch(`/duplex-control/api/${path}`, { cache: 'no-store',
|
|
286
|
-
headers: { 'X-Duet-Native-Interactions': '1' } })
|
|
287
|
-
if (!response.ok) throw new Error('harness_unavailable')
|
|
303
|
+
signal, headers: { 'X-Duet-Native-Interactions': '1' } })
|
|
304
|
+
if (!response.ok) throw Object.assign(new Error('harness_unavailable'), {status:response.status})
|
|
288
305
|
return response.json()
|
|
289
306
|
}
|
|
290
307
|
const poll = async () => {
|
|
291
308
|
if (disposed || pollRunning) return
|
|
292
309
|
pollRunning = true
|
|
310
|
+
pollWakePending = false
|
|
311
|
+
const generation = state.generation, controller = new AbortController(), startedAt = Date.now()
|
|
312
|
+
pollController = controller
|
|
313
|
+
const timeout = setTimeout(() => controller.abort(), 5000)
|
|
293
314
|
try {
|
|
294
|
-
const [catalog, completed, health] = await Promise.all([api('sessions'), api(`results?after=${cursor ?? 0}&limit=100
|
|
315
|
+
const [catalog, completed, health] = await Promise.all([api('sessions',controller.signal), api(`results?after=${cursor ?? 0}&limit=100`,controller.signal), api('health',controller.signal)])
|
|
295
316
|
if (disposed) return
|
|
296
317
|
catalog.sessions = browserSessionCatalog(ctx, catalog.sessions)
|
|
297
318
|
const issue = workspaceIssue(ctx)
|
|
298
319
|
if (issue === 'workspace_required' && state.mode !== 'off') state.fail(issue)
|
|
299
320
|
for (const s of catalog.sessions) labels.set(s.session_id, s.label)
|
|
300
321
|
const bootstrap = cursor === null || resultEpoch !== health.focus_epoch
|
|
301
|
-
resultEpoch = health.focus_epoch
|
|
302
|
-
cursor = bootstrap ? completed.current_cursor : completed.next_cursor
|
|
303
322
|
let composer
|
|
304
323
|
const id = focusedSession(ctx)
|
|
305
324
|
const scope = id ? ctx.sessions.scope(id) : undefined
|
|
@@ -317,15 +336,27 @@ export function mountDuet(ctx) {
|
|
|
317
336
|
text: (job.status === 'succeeded' ? job.result : (job.error || job.result)) || '未返回结果。',
|
|
318
337
|
})),
|
|
319
338
|
})
|
|
339
|
+
resultEpoch = health.focus_epoch
|
|
340
|
+
cursor = bootstrap ? completed.current_cursor : completed.next_cursor
|
|
341
|
+
if (pollFailures >= 3 && state.mode !== 'off') notice('会话同步已恢复。')
|
|
342
|
+
pollFailureSince = null; pollFailures = 0
|
|
320
343
|
} catch (error) {
|
|
321
|
-
if (state.mode !== 'off') {
|
|
344
|
+
if (!disposed && generation === state.generation && state.mode !== 'off') {
|
|
322
345
|
diagnostic({ event: 'browser.poll_failed', message: String(error?.message || error), stack: error?.stack })
|
|
323
|
-
|
|
346
|
+
pollFailureSince ??= Date.now(); pollFailures++
|
|
347
|
+
if ([401,403].includes(error.status) || (pollFailures >= 3 && Date.now()-pollFailureSince >= 15000)) state.fail('harness_sync_failed')
|
|
348
|
+
else if (pollFailures === 3) notice('会话同步暂时中断,正在重试。')
|
|
324
349
|
}
|
|
325
350
|
}
|
|
326
|
-
finally {
|
|
351
|
+
finally {
|
|
352
|
+
clearTimeout(timeout); controller.abort(); pollController = null; pollRunning = false
|
|
353
|
+
nextPollAt = pollWakePending ? 0 : startedAt + (state.mode !== 'off' || tutorial?.active ? 1000 : document.hidden ? 15000 : 5000)
|
|
354
|
+
}
|
|
327
355
|
}
|
|
328
|
-
const timer = setInterval(() => { void poll(); state.tick() }, 1000)
|
|
356
|
+
const timer = setInterval(() => { if (Date.now() >= nextPollAt) void poll(); state.tick() }, 1000)
|
|
357
|
+
const wakePoll = () => { pollWakePending = true; nextPollAt = 0 }
|
|
358
|
+
const unwatchSessions = ctx.sessions.list.subscribe?.(wakePoll)
|
|
359
|
+
const unwatchWorkspaces = ctx.workspaces?.list?.subscribe?.(wakePoll)
|
|
329
360
|
const progress = setInterval(() => { if (state.connection) audio.progress(state.connection.send) }, 200)
|
|
330
361
|
const visibility = () => { state.hidden = document.visibilityState !== 'visible'; state.tick(); void poll() }
|
|
331
362
|
document.addEventListener('visibilitychange', visibility)
|
|
@@ -347,6 +378,9 @@ export function mountDuet(ctx) {
|
|
|
347
378
|
teachingObserver.observe(document.body, { subtree: true, childList: true })
|
|
348
379
|
return () => {
|
|
349
380
|
disposed = true
|
|
381
|
+
pollController?.abort()
|
|
382
|
+
unwatchSessions?.(); unwatchWorkspaces?.()
|
|
383
|
+
notices.dispose()
|
|
350
384
|
stopShortcuts()
|
|
351
385
|
observer.disconnect()
|
|
352
386
|
teachingObserver.disconnect()
|
|
@@ -354,7 +388,8 @@ export function mountDuet(ctx) {
|
|
|
354
388
|
audioConsent.cancel()
|
|
355
389
|
ratingPanel?.dispose()
|
|
356
390
|
connectionHint?.dispose()
|
|
357
|
-
clearInterval(timer); clearInterval(progress)
|
|
391
|
+
clearInterval(timer); clearInterval(progress)
|
|
392
|
+
stopControlsLayout?.()
|
|
358
393
|
document.removeEventListener('visibilitychange', visibility)
|
|
359
394
|
window.removeEventListener('error', pageError)
|
|
360
395
|
window.removeEventListener('unhandledrejection', pageError)
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/** Composer requests belong to one explicit voice/tutorial connection, never all tabs. */
|
|
2
|
+
import { focusedSession as currentSession } from './composer.mjs?v=0.1.4'
|
|
3
|
+
|
|
4
|
+
export function startComposerBridge(ctx, clientId, fetchImpl = fetch) {
|
|
5
|
+
const focusedSession = () => currentSession(ctx)
|
|
6
|
+
const bridgeFetch = async (url, options = {}, timeoutMs = 8000) => {
|
|
7
|
+
const request = new AbortController()
|
|
8
|
+
const abort = () => request.abort()
|
|
9
|
+
options.signal?.addEventListener('abort', abort, { once: true })
|
|
10
|
+
if (options.signal?.aborted) abort()
|
|
11
|
+
const timer = setTimeout(abort, timeoutMs)
|
|
12
|
+
try { return await fetchImpl(url, { ...options, signal: request.signal }) }
|
|
13
|
+
finally { clearTimeout(timer); options.signal?.removeEventListener('abort', abort) }
|
|
14
|
+
}
|
|
15
|
+
const controller = new AbortController()
|
|
16
|
+
let pollRunning = false
|
|
17
|
+
let retryTimer
|
|
18
|
+
|
|
19
|
+
const digest = async (text) => {
|
|
20
|
+
const bytes = new TextEncoder().encode(text)
|
|
21
|
+
const hash = await crypto.subtle.digest("SHA-256", bytes)
|
|
22
|
+
return [...new Uint8Array(hash)].map(value => value.toString(16).padStart(2, "0")).join("")
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const composerForSession = async (sessionId) => {
|
|
26
|
+
await ctx.sessions.refresh()
|
|
27
|
+
const sessionContext = ctx.sessions.scope(sessionId)
|
|
28
|
+
if (sessionContext === undefined) {
|
|
29
|
+
const error = new Error(`Harness session ${sessionId} is not ready`)
|
|
30
|
+
error.code = "session_not_ready"
|
|
31
|
+
throw error
|
|
32
|
+
}
|
|
33
|
+
return ctx.conversation.input.for(sessionContext)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const composerState = async (sessionId, input) => {
|
|
37
|
+
const state = input.state.getSnapshot()
|
|
38
|
+
return {
|
|
39
|
+
session_id: sessionId,
|
|
40
|
+
text: state.draft,
|
|
41
|
+
phase: state.phase,
|
|
42
|
+
revision: state.draftRev,
|
|
43
|
+
hash: await digest(state.draft),
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const execute = async (request) => {
|
|
48
|
+
controller.signal.throwIfAborted()
|
|
49
|
+
const input = await composerForSession(request.session_id)
|
|
50
|
+
const before = await composerState(request.session_id, input)
|
|
51
|
+
controller.signal.throwIfAborted()
|
|
52
|
+
const checkFocus = () => {
|
|
53
|
+
if (request.require_focus && focusedSession() !== request.session_id) {
|
|
54
|
+
const error = new Error("Focused session changed; read input_status again")
|
|
55
|
+
error.code = "focus_conflict"
|
|
56
|
+
throw error
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
checkFocus()
|
|
60
|
+
if (["set", "clear", "consume"].includes(request.type)) {
|
|
61
|
+
const overwrite = request.type === "set" && request.overwrite === true
|
|
62
|
+
if (before.phase !== "plain") {
|
|
63
|
+
const error = new Error(`Harness input is busy (${before.phase})`)
|
|
64
|
+
error.code = "composer_busy"
|
|
65
|
+
throw error
|
|
66
|
+
}
|
|
67
|
+
if (!overwrite && (
|
|
68
|
+
before.revision !== request.expected_revision
|
|
69
|
+
|| before.hash !== request.expected_hash
|
|
70
|
+
)) {
|
|
71
|
+
const error = new Error("Harness input changed before the requested edit")
|
|
72
|
+
error.code = "draft_conflict"
|
|
73
|
+
throw error
|
|
74
|
+
}
|
|
75
|
+
// Hashing yields to the browser. Recheck the live draft immediately before
|
|
76
|
+
// the synchronous write so a keystroke during hashing cannot be overwritten.
|
|
77
|
+
const live = input.state.getSnapshot()
|
|
78
|
+
if (!overwrite && (live.draftRev !== before.revision || live.draft !== before.text || live.phase !== before.phase)) {
|
|
79
|
+
const error = new Error("Harness input changed during snapshot")
|
|
80
|
+
error.code = "draft_conflict"
|
|
81
|
+
throw error
|
|
82
|
+
}
|
|
83
|
+
if (live.phase !== "plain") {
|
|
84
|
+
const error = new Error("Harness input is busy")
|
|
85
|
+
error.code = "composer_busy"
|
|
86
|
+
throw error
|
|
87
|
+
}
|
|
88
|
+
checkFocus()
|
|
89
|
+
// DSH 0.1.5 adds generic attachments. The host submit RPC below is
|
|
90
|
+
// text-only: do not clear/send just the text and silently omit files.
|
|
91
|
+
// Older DSH exposes the same browser-owned items as imageIds.
|
|
92
|
+
if (request.type === "consume" && (live.attachmentIds ?? live.imageIds ?? []).length > 0) {
|
|
93
|
+
const error = new Error("输入框含有附件,请在 Harness 页面发送;语音发送目前只支持纯文本")
|
|
94
|
+
error.code = "composer_attachments_unsupported"
|
|
95
|
+
throw error
|
|
96
|
+
}
|
|
97
|
+
const consumed = request.type === "consume" ? before : null
|
|
98
|
+
input.setDraft(["clear", "consume"].includes(request.type) ? "" : String(request.text ?? ""))
|
|
99
|
+
await new Promise(resolve => setTimeout(resolve, 0))
|
|
100
|
+
const after = await composerState(request.session_id, input)
|
|
101
|
+
if (consumed !== null) {
|
|
102
|
+
return {
|
|
103
|
+
...after,
|
|
104
|
+
consumed_text: consumed.text,
|
|
105
|
+
consumed_revision: consumed.revision,
|
|
106
|
+
consumed_hash: consumed.hash,
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return after
|
|
110
|
+
} else if (request.type !== "get") {
|
|
111
|
+
const error = new Error(`Unsupported composer request: ${request.type}`)
|
|
112
|
+
error.code = "unsupported_composer_operation"
|
|
113
|
+
throw error
|
|
114
|
+
}
|
|
115
|
+
return before
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const complete = async (requestId, payload) => {
|
|
119
|
+
await bridgeFetch(`/duplex-control/api/composer/requests/${encodeURIComponent(requestId)}/complete`, {
|
|
120
|
+
method: "POST",
|
|
121
|
+
headers: { "Content-Type": "application/json" },
|
|
122
|
+
body: JSON.stringify({ client_id: clientId, ...payload }),
|
|
123
|
+
cache: "no-store",
|
|
124
|
+
signal: controller.signal,
|
|
125
|
+
})
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const processRequest = async (candidate) => {
|
|
129
|
+
if (controller.signal.aborted || candidate.target_client_id !== clientId) return
|
|
130
|
+
const claimResponse = await bridgeFetch(
|
|
131
|
+
`/duplex-control/api/composer/requests/${encodeURIComponent(candidate.id)}/claim`,
|
|
132
|
+
{
|
|
133
|
+
method: "POST",
|
|
134
|
+
headers: { "Content-Type": "application/json" },
|
|
135
|
+
body: JSON.stringify({ client_id: clientId }),
|
|
136
|
+
cache: "no-store",
|
|
137
|
+
signal: controller.signal,
|
|
138
|
+
},
|
|
139
|
+
)
|
|
140
|
+
if (claimResponse.status === 404 || claimResponse.status === 409) return
|
|
141
|
+
if (!claimResponse.ok) throw new Error(`Composer claim failed: HTTP ${claimResponse.status}`)
|
|
142
|
+
const request = (await claimResponse.json()).request
|
|
143
|
+
if (controller.signal.aborted || request.target_client_id !== clientId) return
|
|
144
|
+
try {
|
|
145
|
+
const composer = await execute(request)
|
|
146
|
+
await complete(request.id, { ok: true, composer })
|
|
147
|
+
} catch (error) {
|
|
148
|
+
await complete(request.id, {
|
|
149
|
+
ok: false,
|
|
150
|
+
error_code: error?.code || "composer_operation_failed",
|
|
151
|
+
error: error instanceof Error ? error.message : String(error),
|
|
152
|
+
status: error?.code === "session_not_ready" ? 503 : 409,
|
|
153
|
+
})
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const poll = async () => {
|
|
158
|
+
if (pollRunning || controller.signal.aborted) return
|
|
159
|
+
clearTimeout(retryTimer)
|
|
160
|
+
pollRunning = true
|
|
161
|
+
let succeeded = false
|
|
162
|
+
try {
|
|
163
|
+
const sessionId = focusedSession() || ''
|
|
164
|
+
const visibility = typeof document === 'undefined' ? 'unknown' : document.visibilityState
|
|
165
|
+
const query = `wait=1&client_id=${encodeURIComponent(clientId)}&session_id=${encodeURIComponent(sessionId)}&visibility=${encodeURIComponent(visibility)}`
|
|
166
|
+
const response = await bridgeFetch(`/duplex-control/api/composer/requests?${query}`, {
|
|
167
|
+
cache: "no-store",
|
|
168
|
+
signal: controller.signal,
|
|
169
|
+
}, 30_000)
|
|
170
|
+
if (!response.ok) return
|
|
171
|
+
const payload = await response.json()
|
|
172
|
+
await Promise.all((payload.requests || []).map(processRequest))
|
|
173
|
+
// Old hosts return an immediate empty list: retain a retry delay
|
|
174
|
+
// rather than spinning if a browser/host upgrade is staggered.
|
|
175
|
+
succeeded = payload.long_poll_supported === true
|
|
176
|
+
} catch (error) {
|
|
177
|
+
if (!controller.signal.aborted) console.warn("duet composer RPC failed:", error)
|
|
178
|
+
} finally {
|
|
179
|
+
pollRunning = false
|
|
180
|
+
if (!controller.signal.aborted) {
|
|
181
|
+
// Successful long polls re-arm without a background-tab timer.
|
|
182
|
+
if (succeeded) void poll()
|
|
183
|
+
else retryTimer = setTimeout(() => { void poll() }, 1000)
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
void poll()
|
|
189
|
+
const resume = () => { void poll() }
|
|
190
|
+
window.addEventListener?.('online', resume)
|
|
191
|
+
window.addEventListener?.('pageshow', resume)
|
|
192
|
+
if (typeof document !== 'undefined') document.addEventListener('visibilitychange', resume)
|
|
193
|
+
return () => {
|
|
194
|
+
controller.abort()
|
|
195
|
+
clearTimeout(retryTimer)
|
|
196
|
+
window.removeEventListener?.('online', resume)
|
|
197
|
+
window.removeEventListener?.('pageshow', resume)
|
|
198
|
+
if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', resume)
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
}
|
package/src/client/composer.mjs
CHANGED
|
@@ -10,6 +10,22 @@ export function focusedSession(ctx) {
|
|
|
10
10
|
return selected.length === 1 ? selected[0][0] : null
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
+
/** Navigation is local to the page owning this connection, never a host broadcast. */
|
|
14
|
+
export async function openLocalSession(ctx, id, signal) {
|
|
15
|
+
signal?.throwIfAborted()
|
|
16
|
+
await ctx.sessions.refresh()
|
|
17
|
+
signal?.throwIfAborted()
|
|
18
|
+
const navigation = typeof ctx.get === 'function' ? ctx.get('uiWorkspace') : ctx.uiWorkspace
|
|
19
|
+
if (navigation?.openSession) navigation.openSession(id)
|
|
20
|
+
else ctx.sessions.open(id)
|
|
21
|
+
const deadline = Date.now() + 3000
|
|
22
|
+
while (focusedSession(ctx) !== id) {
|
|
23
|
+
signal?.throwIfAborted()
|
|
24
|
+
if (Date.now() > deadline) fail('focus_not_ready')
|
|
25
|
+
await new Promise(resolve => setTimeout(resolve, 25))
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
13
29
|
export function composerAccess(ctx, label = id => id) {
|
|
14
30
|
const focused = () => focusedSession(ctx)
|
|
15
31
|
const inputFor = id => {
|
|
@@ -42,6 +58,13 @@ export function composerAccess(ctx, label = id => id) {
|
|
|
42
58
|
return { composer: value }
|
|
43
59
|
}
|
|
44
60
|
const match = request.path.match(/^\/api\/sessions\/([A-Za-z0-9_-]+)\/composer$/)
|
|
61
|
+
if (request.method === 'GET' && match) {
|
|
62
|
+
const id = match[1]
|
|
63
|
+
const value = await snapshot(id, inputFor(id))
|
|
64
|
+
signal?.throwIfAborted()
|
|
65
|
+
if (request.params?.require_focus === 'true' && focused() !== id) fail('focus_conflict')
|
|
66
|
+
return { composer: value }
|
|
67
|
+
}
|
|
45
68
|
if (request.method !== 'PUT' || !match) return undefined
|
|
46
69
|
const id = match[1], payload = request.payload || {}, input = inputFor(id)
|
|
47
70
|
const overwrite = payload.overwrite === true
|