dsh-duet 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/HEROICONS-LICENSE.txt +24 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +77 -0
- package/deepseek_harness_duplex_control.patch.yml +3 -0
- package/deepseek_harness_duplex_control_plugin.html +392 -0
- package/deepseek_harness_duplex_control_plugin.mjs +1105 -0
- package/deepseek_harness_duplex_focus_client/lib/client.js +466 -0
- package/deepseek_harness_voice_audio.mjs +135 -0
- package/deepseek_harness_voice_browser.mjs +343 -0
- package/deepseek_harness_voice_catalog.mjs +56 -0
- package/deepseek_harness_voice_composer.mjs +125 -0
- package/deepseek_harness_voice_consent.mjs +63 -0
- package/deepseek_harness_voice_feedback.mjs +48 -0
- package/deepseek_harness_voice_feedback_files.mjs +55 -0
- package/deepseek_harness_voice_feedback_store.mjs +51 -0
- package/deepseek_harness_voice_interactions.mjs +32 -0
- package/deepseek_harness_voice_microphone.mjs +59 -0
- package/deepseek_harness_voice_notices.mjs +54 -0
- package/deepseek_harness_voice_proxy.mjs +223 -0
- package/deepseek_harness_voice_rpc.mjs +104 -0
- package/deepseek_harness_voice_service_info.mjs +45 -0
- package/deepseek_harness_voice_settings.mjs +95 -0
- package/deepseek_harness_voice_shortcuts.mjs +69 -0
- package/deepseek_harness_voice_state.mjs +171 -0
- package/deepseek_harness_voice_trace.mjs +107 -0
- package/deepseek_harness_voice_tutorial.mjs +265 -0
- package/deepseek_harness_voice_tutorial_adapter.mjs +95 -0
- package/deepseek_harness_voice_tutorial_request.mjs +16 -0
- package/package.json +57 -0
- package/tutorial-audio/broadcast.wav +0 -0
- package/tutorial-audio/clear.wav +0 -0
- package/tutorial-audio/edit.wav +0 -0
- package/tutorial-audio/input.wav +0 -0
- package/tutorial-audio/manifest.json +60 -0
- package/tutorial-audio/modes_broadcast.wav +0 -0
- package/tutorial-audio/modes_interaction.wav +0 -0
- package/tutorial-audio/reinput.wav +0 -0
- package/tutorial-audio/send.wav +0 -0
- package/tutorial-audio/switch.wav +0 -0
|
@@ -0,0 +1,466 @@
|
|
|
1
|
+
window.__ModuleLoader__.load({
|
|
2
|
+
id: "dsh-duet",
|
|
3
|
+
factory: () => {
|
|
4
|
+
const module = { exports: {} }
|
|
5
|
+
const exports = module.exports
|
|
6
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" })
|
|
7
|
+
|
|
8
|
+
const inject = ["sessions", "conversation", "uiSession"]
|
|
9
|
+
|
|
10
|
+
function apply(ctx) {
|
|
11
|
+
const focusedSession = () => {
|
|
12
|
+
const snapshot = ctx.sessions.list.getSnapshot()
|
|
13
|
+
if ('current' in snapshot) return snapshot.current || null
|
|
14
|
+
const selected = Object.entries(snapshot.byId || {}).filter(([, row]) => row.retainedBy?.mainView > 0)
|
|
15
|
+
return selected.length === 1 ? selected[0][0] : null
|
|
16
|
+
}
|
|
17
|
+
const browserClientId = crypto.randomUUID()
|
|
18
|
+
// A hung fetch must not permanently hold heartbeatRunning/pollRunning.
|
|
19
|
+
const bridgeFetch = async (url, options = {}, timeoutMs = 8000) => {
|
|
20
|
+
const request = new AbortController()
|
|
21
|
+
const abort = () => request.abort()
|
|
22
|
+
options.signal?.addEventListener('abort', abort, { once: true })
|
|
23
|
+
if (options.signal?.aborted) abort()
|
|
24
|
+
const timer = setTimeout(abort, timeoutMs)
|
|
25
|
+
try { return await fetch(url, { ...options, signal: request.signal }) }
|
|
26
|
+
finally {
|
|
27
|
+
clearTimeout(timer)
|
|
28
|
+
options.signal?.removeEventListener('abort', abort)
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
ctx.effect(() => {
|
|
32
|
+
let active = true
|
|
33
|
+
let dispose
|
|
34
|
+
import('/duplex-control/deepseek_harness_voice_browser.mjs?v=0.1.0').then(module => {
|
|
35
|
+
if (active) dispose = module.mountVoice(ctx)
|
|
36
|
+
}).catch(error => console.warn('Duplex voice controls could not load:', error))
|
|
37
|
+
return () => { active = false; dispose?.() }
|
|
38
|
+
}, 'duplex-voice-client: three-state microphone and playback controls')
|
|
39
|
+
ctx.effect(() => {
|
|
40
|
+
const entryId = "dsh-duplex-control-entry"
|
|
41
|
+
|
|
42
|
+
const mountEntry = () => {
|
|
43
|
+
if (document.getElementById(entryId) !== null) return
|
|
44
|
+
const settingsSlot = document.querySelector('[data-slot="sidebar.settings"]')
|
|
45
|
+
const settingsButton = settingsSlot?.querySelector("button")
|
|
46
|
+
const settingsLabel = settingsSlot?.querySelector("span")
|
|
47
|
+
if (settingsSlot === null || settingsSlot.parentElement === null || settingsButton == null) return
|
|
48
|
+
|
|
49
|
+
const entry = document.createElement("span")
|
|
50
|
+
entry.id = entryId
|
|
51
|
+
entry.setAttribute("aria-label", "duet")
|
|
52
|
+
entry.setAttribute("data-duplex-surface", "control-entry")
|
|
53
|
+
entry.style.textDecoration = "none"
|
|
54
|
+
entry.style.marginBottom = "4px"
|
|
55
|
+
|
|
56
|
+
const label = document.createElement("span")
|
|
57
|
+
label.textContent = "duet"
|
|
58
|
+
entry.style.fontWeight = "750"
|
|
59
|
+
entry.style.letterSpacing = "-0.4px"
|
|
60
|
+
entry.append(label)
|
|
61
|
+
settingsSlot.parentElement.insertBefore(entry, settingsSlot)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
mountEntry()
|
|
65
|
+
const observer = new MutationObserver(mountEntry)
|
|
66
|
+
observer.observe(document.body, { childList: true, subtree: true })
|
|
67
|
+
return () => {
|
|
68
|
+
observer.disconnect()
|
|
69
|
+
document.getElementById(entryId)?.remove()
|
|
70
|
+
}
|
|
71
|
+
}, "duplex-control-client: mount main page entry")
|
|
72
|
+
|
|
73
|
+
ctx.effect(() => {
|
|
74
|
+
if (typeof BroadcastChannel === "undefined") return () => {}
|
|
75
|
+
const channel = new BroadcastChannel("dsh-duplex-control-v1")
|
|
76
|
+
|
|
77
|
+
const currentComposer = () => {
|
|
78
|
+
const sessionId = focusedSession()
|
|
79
|
+
if (typeof sessionId !== "string") throw new Error("Harness currently has no selected session")
|
|
80
|
+
const sessionContext = ctx.sessions.scope(sessionId)
|
|
81
|
+
if (sessionContext === undefined) throw new Error(`Harness session ${sessionId} is not ready`)
|
|
82
|
+
return {
|
|
83
|
+
sessionId,
|
|
84
|
+
input: ctx.conversation.input.for(sessionContext),
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const composerState = (sessionId, input) => {
|
|
89
|
+
const state = input.state.getSnapshot()
|
|
90
|
+
return {
|
|
91
|
+
session_id: sessionId,
|
|
92
|
+
draft: state.draft,
|
|
93
|
+
phase: state.phase,
|
|
94
|
+
draft_revision: state.draftRev,
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
channel.onmessage = (event) => {
|
|
99
|
+
const message = event.data
|
|
100
|
+
if (
|
|
101
|
+
message === null
|
|
102
|
+
|| typeof message !== "object"
|
|
103
|
+
|| message.source !== "duplex-control-page"
|
|
104
|
+
|| typeof message.request_id !== "string"
|
|
105
|
+
) return
|
|
106
|
+
if (!["composer/get", "composer/set", "composer/clear"].includes(message.type)) return
|
|
107
|
+
|
|
108
|
+
const respond = (payload) => channel.postMessage({
|
|
109
|
+
source: "harness-main-page",
|
|
110
|
+
type: "composer/result",
|
|
111
|
+
request_id: message.request_id,
|
|
112
|
+
...payload,
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
try {
|
|
116
|
+
const { sessionId, input } = currentComposer()
|
|
117
|
+
if (message.type === "composer/set") {
|
|
118
|
+
const text = String(message.text ?? "")
|
|
119
|
+
if (text.length > 100_000) throw new Error("Draft is too large")
|
|
120
|
+
const before = input.state.getSnapshot()
|
|
121
|
+
if (before.phase !== "plain") {
|
|
122
|
+
throw new Error(`Harness input is busy (${before.phase})`)
|
|
123
|
+
}
|
|
124
|
+
input.setDraft(message.mode === "append" ? `${before.draft}${text}` : text)
|
|
125
|
+
} else if (message.type === "composer/clear") {
|
|
126
|
+
const before = input.state.getSnapshot()
|
|
127
|
+
if (before.phase !== "plain") {
|
|
128
|
+
throw new Error(`Harness input is busy (${before.phase})`)
|
|
129
|
+
}
|
|
130
|
+
input.setDraft("")
|
|
131
|
+
}
|
|
132
|
+
respond({ ok: true, composer: composerState(sessionId, input) })
|
|
133
|
+
} catch (error) {
|
|
134
|
+
respond({ ok: false, error: error instanceof Error ? error.message : String(error) })
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
return () => channel.close()
|
|
139
|
+
}, "duplex-control-client: bridge current composer")
|
|
140
|
+
|
|
141
|
+
ctx.effect(() => {
|
|
142
|
+
const controller = new AbortController()
|
|
143
|
+
const clientId = browserClientId
|
|
144
|
+
let pollRunning = false
|
|
145
|
+
let retryTimer
|
|
146
|
+
|
|
147
|
+
const digest = async (text) => {
|
|
148
|
+
const bytes = new TextEncoder().encode(text)
|
|
149
|
+
const hash = await crypto.subtle.digest("SHA-256", bytes)
|
|
150
|
+
return [...new Uint8Array(hash)].map(value => value.toString(16).padStart(2, "0")).join("")
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const composerForSession = async (sessionId) => {
|
|
154
|
+
await ctx.sessions.refresh()
|
|
155
|
+
const sessionContext = ctx.sessions.scope(sessionId)
|
|
156
|
+
if (sessionContext === undefined) {
|
|
157
|
+
const error = new Error(`Harness session ${sessionId} is not ready`)
|
|
158
|
+
error.code = "session_not_ready"
|
|
159
|
+
throw error
|
|
160
|
+
}
|
|
161
|
+
return ctx.conversation.input.for(sessionContext)
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const composerState = async (sessionId, input) => {
|
|
165
|
+
const state = input.state.getSnapshot()
|
|
166
|
+
return {
|
|
167
|
+
session_id: sessionId,
|
|
168
|
+
text: state.draft,
|
|
169
|
+
phase: state.phase,
|
|
170
|
+
revision: state.draftRev,
|
|
171
|
+
hash: await digest(state.draft),
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const execute = async (request) => {
|
|
176
|
+
const input = await composerForSession(request.session_id)
|
|
177
|
+
const before = await composerState(request.session_id, input)
|
|
178
|
+
const checkFocus = () => {
|
|
179
|
+
if (request.require_focus && focusedSession() !== request.session_id) {
|
|
180
|
+
const error = new Error("Focused session changed; read input_status again")
|
|
181
|
+
error.code = "focus_conflict"
|
|
182
|
+
throw error
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
checkFocus()
|
|
186
|
+
if (["set", "clear", "consume"].includes(request.type)) {
|
|
187
|
+
const overwrite = request.type === "set" && request.overwrite === true
|
|
188
|
+
if (before.phase !== "plain") {
|
|
189
|
+
const error = new Error(`Harness input is busy (${before.phase})`)
|
|
190
|
+
error.code = "composer_busy"
|
|
191
|
+
throw error
|
|
192
|
+
}
|
|
193
|
+
if (!overwrite && (
|
|
194
|
+
before.revision !== request.expected_revision
|
|
195
|
+
|| before.hash !== request.expected_hash
|
|
196
|
+
)) {
|
|
197
|
+
const error = new Error("Harness input changed before the requested edit")
|
|
198
|
+
error.code = "draft_conflict"
|
|
199
|
+
throw error
|
|
200
|
+
}
|
|
201
|
+
// Hashing yields to the browser. Recheck the live draft immediately before
|
|
202
|
+
// the synchronous write so a keystroke during hashing cannot be overwritten.
|
|
203
|
+
const live = input.state.getSnapshot()
|
|
204
|
+
if (!overwrite && (live.draftRev !== before.revision || live.draft !== before.text || live.phase !== before.phase)) {
|
|
205
|
+
const error = new Error("Harness input changed during snapshot")
|
|
206
|
+
error.code = "draft_conflict"
|
|
207
|
+
throw error
|
|
208
|
+
}
|
|
209
|
+
if (live.phase !== "plain") {
|
|
210
|
+
const error = new Error("Harness input is busy")
|
|
211
|
+
error.code = "composer_busy"
|
|
212
|
+
throw error
|
|
213
|
+
}
|
|
214
|
+
checkFocus()
|
|
215
|
+
// DSH 0.1.5 adds generic attachments. The host submit RPC below is
|
|
216
|
+
// text-only: do not clear/send just the text and silently omit files.
|
|
217
|
+
// Older DSH exposes the same browser-owned items as imageIds.
|
|
218
|
+
if (request.type === "consume" && (live.attachmentIds ?? live.imageIds ?? []).length > 0) {
|
|
219
|
+
const error = new Error("输入框含有附件,请在 Harness 页面发送;语音发送目前只支持纯文本")
|
|
220
|
+
error.code = "composer_attachments_unsupported"
|
|
221
|
+
throw error
|
|
222
|
+
}
|
|
223
|
+
const consumed = request.type === "consume" ? before : null
|
|
224
|
+
input.setDraft(["clear", "consume"].includes(request.type) ? "" : String(request.text ?? ""))
|
|
225
|
+
await new Promise(resolve => setTimeout(resolve, 0))
|
|
226
|
+
const after = await composerState(request.session_id, input)
|
|
227
|
+
if (consumed !== null) {
|
|
228
|
+
return {
|
|
229
|
+
...after,
|
|
230
|
+
consumed_text: consumed.text,
|
|
231
|
+
consumed_revision: consumed.revision,
|
|
232
|
+
consumed_hash: consumed.hash,
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
return after
|
|
236
|
+
} else if (request.type !== "get") {
|
|
237
|
+
const error = new Error(`Unsupported composer request: ${request.type}`)
|
|
238
|
+
error.code = "unsupported_composer_operation"
|
|
239
|
+
throw error
|
|
240
|
+
}
|
|
241
|
+
return before
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const complete = async (requestId, payload) => {
|
|
245
|
+
await bridgeFetch(`/duplex-control/api/composer/requests/${encodeURIComponent(requestId)}/complete`, {
|
|
246
|
+
method: "POST",
|
|
247
|
+
headers: { "Content-Type": "application/json" },
|
|
248
|
+
body: JSON.stringify({ client_id: clientId, ...payload }),
|
|
249
|
+
cache: "no-store",
|
|
250
|
+
signal: controller.signal,
|
|
251
|
+
})
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const processRequest = async (candidate) => {
|
|
255
|
+
const claimResponse = await bridgeFetch(
|
|
256
|
+
`/duplex-control/api/composer/requests/${encodeURIComponent(candidate.id)}/claim`,
|
|
257
|
+
{
|
|
258
|
+
method: "POST",
|
|
259
|
+
headers: { "Content-Type": "application/json" },
|
|
260
|
+
body: JSON.stringify({ client_id: clientId }),
|
|
261
|
+
cache: "no-store",
|
|
262
|
+
signal: controller.signal,
|
|
263
|
+
},
|
|
264
|
+
)
|
|
265
|
+
if (claimResponse.status === 404 || claimResponse.status === 409) return
|
|
266
|
+
if (!claimResponse.ok) throw new Error(`Composer claim failed: HTTP ${claimResponse.status}`)
|
|
267
|
+
const request = (await claimResponse.json()).request
|
|
268
|
+
try {
|
|
269
|
+
const composer = await execute(request)
|
|
270
|
+
await complete(request.id, { ok: true, composer })
|
|
271
|
+
} catch (error) {
|
|
272
|
+
await complete(request.id, {
|
|
273
|
+
ok: false,
|
|
274
|
+
error_code: error?.code || "composer_operation_failed",
|
|
275
|
+
error: error instanceof Error ? error.message : String(error),
|
|
276
|
+
status: error?.code === "session_not_ready" ? 503 : 409,
|
|
277
|
+
})
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const poll = async () => {
|
|
282
|
+
if (pollRunning || controller.signal.aborted) return
|
|
283
|
+
clearTimeout(retryTimer)
|
|
284
|
+
pollRunning = true
|
|
285
|
+
let succeeded = false
|
|
286
|
+
try {
|
|
287
|
+
const sessionId = focusedSession() || ''
|
|
288
|
+
const visibility = typeof document === 'undefined' ? 'unknown' : document.visibilityState
|
|
289
|
+
const query = `wait=1&client_id=${encodeURIComponent(clientId)}&session_id=${encodeURIComponent(sessionId)}&visibility=${encodeURIComponent(visibility)}`
|
|
290
|
+
const response = await bridgeFetch(`/duplex-control/api/composer/requests?${query}`, {
|
|
291
|
+
cache: "no-store",
|
|
292
|
+
signal: controller.signal,
|
|
293
|
+
}, 30_000)
|
|
294
|
+
if (!response.ok) return
|
|
295
|
+
const payload = await response.json()
|
|
296
|
+
await Promise.all((payload.requests || []).map(processRequest))
|
|
297
|
+
// Old hosts return an immediate empty list: retain a retry delay
|
|
298
|
+
// rather than spinning if a browser/host upgrade is staggered.
|
|
299
|
+
succeeded = payload.long_poll_supported === true
|
|
300
|
+
} catch (error) {
|
|
301
|
+
if (!controller.signal.aborted) console.warn("duplex composer RPC failed:", error)
|
|
302
|
+
} finally {
|
|
303
|
+
pollRunning = false
|
|
304
|
+
if (!controller.signal.aborted) {
|
|
305
|
+
// Successful long polls re-arm without a background-tab timer.
|
|
306
|
+
if (succeeded) void poll()
|
|
307
|
+
else retryTimer = setTimeout(() => { void poll() }, 1000)
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
void poll()
|
|
313
|
+
const resume = () => { void poll() }
|
|
314
|
+
window.addEventListener?.('online', resume)
|
|
315
|
+
window.addEventListener?.('pageshow', resume)
|
|
316
|
+
if (typeof document !== 'undefined') document.addEventListener('visibilitychange', resume)
|
|
317
|
+
return () => {
|
|
318
|
+
controller.abort()
|
|
319
|
+
clearTimeout(retryTimer)
|
|
320
|
+
window.removeEventListener?.('online', resume)
|
|
321
|
+
window.removeEventListener?.('pageshow', resume)
|
|
322
|
+
if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', resume)
|
|
323
|
+
}
|
|
324
|
+
}, "duplex-control-client: bridge server composer RPC")
|
|
325
|
+
|
|
326
|
+
ctx.effect(() => {
|
|
327
|
+
const controller = new AbortController()
|
|
328
|
+
const focusClientId = browserClientId
|
|
329
|
+
let lastEpoch
|
|
330
|
+
let lastRevision = -1
|
|
331
|
+
let lastPublishedSession
|
|
332
|
+
let pollRunning = false
|
|
333
|
+
let heartbeatRunning = false
|
|
334
|
+
let publishRunning = false
|
|
335
|
+
let publishPending = false
|
|
336
|
+
let publishReady = false
|
|
337
|
+
|
|
338
|
+
const selectedSession = focusedSession
|
|
339
|
+
|
|
340
|
+
const observeEpoch = (epoch) => {
|
|
341
|
+
if (typeof epoch !== "string" || epoch === lastEpoch) return
|
|
342
|
+
lastEpoch = epoch
|
|
343
|
+
lastRevision = -1
|
|
344
|
+
lastPublishedSession = undefined
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
const heartbeat = async () => {
|
|
348
|
+
if (heartbeatRunning) return
|
|
349
|
+
heartbeatRunning = true
|
|
350
|
+
try {
|
|
351
|
+
const response = await bridgeFetch("/duplex-control/api/browser-clients/heartbeat", {
|
|
352
|
+
method: "POST",
|
|
353
|
+
headers: { "Content-Type": "application/json" },
|
|
354
|
+
body: JSON.stringify({
|
|
355
|
+
client_id: focusClientId,
|
|
356
|
+
session_id: selectedSession(),
|
|
357
|
+
visibility: document.visibilityState,
|
|
358
|
+
}),
|
|
359
|
+
cache: "no-store",
|
|
360
|
+
signal: controller.signal,
|
|
361
|
+
})
|
|
362
|
+
if (response.ok) observeEpoch((await response.json()).focus_epoch)
|
|
363
|
+
} catch (error) {
|
|
364
|
+
if (!controller.signal.aborted) console.warn("duplex heartbeat failed:", error)
|
|
365
|
+
} finally {
|
|
366
|
+
heartbeatRunning = false
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
const publishSelection = async () => {
|
|
371
|
+
if (!publishReady) return
|
|
372
|
+
if (publishRunning) {
|
|
373
|
+
publishPending = true
|
|
374
|
+
return
|
|
375
|
+
}
|
|
376
|
+
publishRunning = true
|
|
377
|
+
try {
|
|
378
|
+
do {
|
|
379
|
+
publishPending = false
|
|
380
|
+
const sessionId = selectedSession()
|
|
381
|
+
if (sessionId === lastPublishedSession) continue
|
|
382
|
+
const response = await bridgeFetch("/duplex-control/api/focus", {
|
|
383
|
+
method: "POST",
|
|
384
|
+
headers: { "Content-Type": "application/json" },
|
|
385
|
+
body: JSON.stringify({ session_id: sessionId }),
|
|
386
|
+
cache: "no-store",
|
|
387
|
+
signal: controller.signal,
|
|
388
|
+
})
|
|
389
|
+
if (!response.ok) {
|
|
390
|
+
const payload = await response.json().catch(() => ({}))
|
|
391
|
+
throw new Error(payload.detail || `HTTP ${response.status}`)
|
|
392
|
+
}
|
|
393
|
+
lastPublishedSession = sessionId
|
|
394
|
+
} while (publishPending)
|
|
395
|
+
} catch (error) {
|
|
396
|
+
if (!controller.signal.aborted) console.warn("duplex selection publish failed:", error)
|
|
397
|
+
} finally {
|
|
398
|
+
publishRunning = false
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
const poll = async () => {
|
|
403
|
+
if (pollRunning) return
|
|
404
|
+
pollRunning = true
|
|
405
|
+
try {
|
|
406
|
+
const response = await bridgeFetch("/duplex-control/api/focus", {
|
|
407
|
+
cache: "no-store",
|
|
408
|
+
signal: controller.signal,
|
|
409
|
+
})
|
|
410
|
+
if (!response.ok) return
|
|
411
|
+
const focus = await response.json()
|
|
412
|
+
observeEpoch(focus.focus_epoch)
|
|
413
|
+
if (!Number.isInteger(focus.revision) || focus.revision <= lastRevision) return
|
|
414
|
+
if (focus.revision === 0 || typeof focus.session_id !== "string") {
|
|
415
|
+
lastRevision = focus.revision
|
|
416
|
+
return
|
|
417
|
+
}
|
|
418
|
+
await ctx.sessions.refresh()
|
|
419
|
+
if (ctx.sessions.list.getSnapshot().byId[focus.session_id] === undefined) return
|
|
420
|
+
lastPublishedSession = focus.session_id
|
|
421
|
+
// New DSH separates controller selection from the visible panel.
|
|
422
|
+
// Use the UI navigation API so a selected session is not hidden
|
|
423
|
+
// behind the empty-workspace/settings panel while RPC edits it.
|
|
424
|
+
const navigation = typeof ctx.get === "function" ? ctx.get("uiWorkspace") : ctx.uiWorkspace
|
|
425
|
+
if (navigation?.openSession) navigation.openSession(focus.session_id)
|
|
426
|
+
else ctx.sessions.open(focus.session_id)
|
|
427
|
+
lastRevision = focus.revision
|
|
428
|
+
} catch (error) {
|
|
429
|
+
if (!controller.signal.aborted) console.warn("duplex focus sync failed:", error)
|
|
430
|
+
} finally {
|
|
431
|
+
pollRunning = false
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
const unsubscribe = ctx.sessions.list.subscribe(() => { void publishSelection() })
|
|
436
|
+
void poll().finally(() => {
|
|
437
|
+
publishReady = true
|
|
438
|
+
void publishSelection()
|
|
439
|
+
})
|
|
440
|
+
void heartbeat()
|
|
441
|
+
const timer = setInterval(() => {
|
|
442
|
+
void poll()
|
|
443
|
+
void publishSelection()
|
|
444
|
+
}, 500)
|
|
445
|
+
const heartbeatTimer = setInterval(() => { void heartbeat() }, 1000)
|
|
446
|
+
const onVisibilityChange = () => { void heartbeat(); void poll(); void publishSelection() }
|
|
447
|
+
document.addEventListener("visibilitychange", onVisibilityChange)
|
|
448
|
+
window.addEventListener?.('online', onVisibilityChange)
|
|
449
|
+
window.addEventListener?.('pageshow', onVisibilityChange)
|
|
450
|
+
return () => {
|
|
451
|
+
controller.abort()
|
|
452
|
+
clearInterval(timer)
|
|
453
|
+
clearInterval(heartbeatTimer)
|
|
454
|
+
document.removeEventListener("visibilitychange", onVisibilityChange)
|
|
455
|
+
window.removeEventListener?.('online', onVisibilityChange)
|
|
456
|
+
window.removeEventListener?.('pageshow', onVisibilityChange)
|
|
457
|
+
unsubscribe()
|
|
458
|
+
}
|
|
459
|
+
}, "duplex-focus-client: synchronize host and browser focus")
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
exports.apply = apply
|
|
463
|
+
exports.inject = inject
|
|
464
|
+
return module.exports
|
|
465
|
+
},
|
|
466
|
+
})
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { microphoneConstraints } from './deepseek_harness_voice_microphone.mjs?v=0.1.0'
|
|
2
|
+
|
|
3
|
+
/** Browser-owned microphone and PCM playback. No microphone is requested in tts_only. */
|
|
4
|
+
export class VoiceAudio {
|
|
5
|
+
constructor() {
|
|
6
|
+
this.context = null
|
|
7
|
+
this.stream = null
|
|
8
|
+
this.capture = null
|
|
9
|
+
this.nodes = new Set()
|
|
10
|
+
this.responses = new Map()
|
|
11
|
+
this.cleared = new Set()
|
|
12
|
+
this.epoch = 0
|
|
13
|
+
this.nextTime = 0
|
|
14
|
+
this.tones = new Set()
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
prepare() {
|
|
18
|
+
this.context ??= new AudioContext()
|
|
19
|
+
return this.context.resume()
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
connectedChime() {
|
|
23
|
+
if (this.context?.state !== 'running') return
|
|
24
|
+
// Two soft voices enter in turn and briefly resolve together (C5 + E5).
|
|
25
|
+
for (const [frequency, offset] of [[523.25, 0], [659.25, 0.11]]) {
|
|
26
|
+
const oscillator = this.context.createOscillator(), gain = this.context.createGain()
|
|
27
|
+
const start = this.context.currentTime + offset, end = start + 0.36
|
|
28
|
+
oscillator.type = 'sine'; oscillator.frequency.value = frequency
|
|
29
|
+
gain.gain.setValueAtTime(0, start)
|
|
30
|
+
gain.gain.linearRampToValueAtTime(0.055, start + 0.025)
|
|
31
|
+
gain.gain.exponentialRampToValueAtTime(0.0001, end)
|
|
32
|
+
oscillator.connect(gain).connect(this.context.destination)
|
|
33
|
+
this.tones.add(oscillator)
|
|
34
|
+
oscillator.onended = () => { this.tones.delete(oscillator); oscillator.disconnect(); gain.disconnect() }
|
|
35
|
+
oscillator.start(start); oscillator.stop(end)
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async startMic(send) {
|
|
40
|
+
const epoch = this.epoch
|
|
41
|
+
// Exact selection: an unplugged device must not silently use a different mic.
|
|
42
|
+
const stream = await navigator.mediaDevices.getUserMedia(microphoneConstraints())
|
|
43
|
+
if (epoch !== this.epoch) { stream.getTracks().forEach(t => t.stop()); return }
|
|
44
|
+
this.stream = stream
|
|
45
|
+
const code = `class Capture extends AudioWorkletProcessor {
|
|
46
|
+
constructor(){super();this.phase=0;this.sum=0;this.count=0;this.pcm=new Int16Array(1280);this.offset=0;}
|
|
47
|
+
process(inputs){const a=inputs[0]?.[0];if(!a)return true;
|
|
48
|
+
for(const x of a){this.sum+=x;this.count++;this.phase+=16000;
|
|
49
|
+
if(this.phase>=sampleRate){this.phase-=sampleRate;const v=Math.max(-1,Math.min(1,this.sum/this.count));this.pcm[this.offset++]=v<0?v*32768:v*32767;this.sum=0;this.count=0;
|
|
50
|
+
if(this.offset===1280){this.port.postMessage(this.pcm.buffer,[this.pcm.buffer]);this.pcm=new Int16Array(1280);this.offset=0;}}}return true;}}
|
|
51
|
+
registerProcessor('duplex-voice-capture',Capture)`
|
|
52
|
+
if (!this.captureLoaded) {
|
|
53
|
+
const url = URL.createObjectURL(new Blob([code], { type: 'text/javascript' }))
|
|
54
|
+
try { await this.context.audioWorklet.addModule(url); this.captureLoaded = true } finally { URL.revokeObjectURL(url) }
|
|
55
|
+
}
|
|
56
|
+
if (epoch !== this.epoch) { stream.getTracks().forEach(t => t.stop()); return }
|
|
57
|
+
this.source = this.context.createMediaStreamSource(stream)
|
|
58
|
+
this.capture = new AudioWorkletNode(this.context, 'duplex-voice-capture')
|
|
59
|
+
this.capture.port.onmessage = e => { if (epoch === this.epoch) send(e.data) }
|
|
60
|
+
this.mute = this.context.createGain()
|
|
61
|
+
this.mute.gain.value = 0
|
|
62
|
+
this.source.connect(this.capture).connect(this.mute).connect(this.context.destination)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
event(event, send) {
|
|
66
|
+
const key = `${event.response_id}:${event.generation}`
|
|
67
|
+
if (event.type === 'output_audio_buffer.clear') { this.cleared.add(key); this.clear(send); return }
|
|
68
|
+
if (event.type === 'response.output_audio.done') {
|
|
69
|
+
const response = this.responses.get(key)
|
|
70
|
+
if (response) { response.done = true; this.progress(send) }
|
|
71
|
+
return
|
|
72
|
+
}
|
|
73
|
+
if (event.type !== 'response.output_audio.delta') return
|
|
74
|
+
if (this.cleared.has(key)) return
|
|
75
|
+
const bytes = Uint8Array.from(atob(event.delta), c => c.charCodeAt(0))
|
|
76
|
+
const pcm = new Int16Array(bytes.buffer)
|
|
77
|
+
const rate = Number(event.sample_rate || 48000)
|
|
78
|
+
const buffer = this.context.createBuffer(1, pcm.length, rate)
|
|
79
|
+
const data = buffer.getChannelData(0)
|
|
80
|
+
for (let i = 0; i < pcm.length; i++) data[i] = pcm[i] / 32768
|
|
81
|
+
const node = this.context.createBufferSource()
|
|
82
|
+
node.buffer = buffer
|
|
83
|
+
node.connect(this.context.destination)
|
|
84
|
+
const start = Math.max(this.context.currentTime + 0.04, this.nextTime)
|
|
85
|
+
this.nextTime = start + pcm.length / rate
|
|
86
|
+
const response = this.responses.get(key) || { response_id: event.response_id, generation: event.generation, played: 0, basePlayed: 0, chunks: [] }
|
|
87
|
+
response.chunks.push({ start, samples: pcm.length, rate })
|
|
88
|
+
this.responses.set(key, response)
|
|
89
|
+
this.nodes.add(node)
|
|
90
|
+
node.onended = () => { this.nodes.delete(node); node.disconnect(); this.progress(send) }
|
|
91
|
+
node.start(start)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
progress(send) {
|
|
95
|
+
if (!this.context) return
|
|
96
|
+
for (const [key, r] of this.responses) {
|
|
97
|
+
const played = r.chunks.reduce((n, c) => n + Math.min(c.samples, Math.max(0, Math.floor((this.context.currentTime - c.start) * c.rate))), r.basePlayed)
|
|
98
|
+
if (played > r.played) {
|
|
99
|
+
r.played = played
|
|
100
|
+
send({ type: 'output_audio_buffer.playback_progress', response_id: r.response_id, generation: r.generation, played_samples: played })
|
|
101
|
+
}
|
|
102
|
+
while (r.chunks.length && this.context.currentTime >= r.chunks[0].start + r.chunks[0].samples / r.chunks[0].rate) {
|
|
103
|
+
r.basePlayed += r.chunks.shift().samples
|
|
104
|
+
}
|
|
105
|
+
if (r.done && !r.chunks.length) this.responses.delete(key)
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
playing() { return this.nodes.size > 0 }
|
|
110
|
+
|
|
111
|
+
clear(send = () => {}) {
|
|
112
|
+
this.progress(send)
|
|
113
|
+
for (const [key, r] of this.responses) {
|
|
114
|
+
this.cleared.add(key)
|
|
115
|
+
send({ type: 'output_audio_buffer.cleared', response_id: r.response_id, generation: r.generation, played_samples: r.played })
|
|
116
|
+
}
|
|
117
|
+
for (const node of this.nodes) { node.onended = null; node.stop(); node.disconnect() }
|
|
118
|
+
this.nodes.clear()
|
|
119
|
+
this.responses.clear()
|
|
120
|
+
this.nextTime = 0
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
stop() {
|
|
124
|
+
this.epoch++
|
|
125
|
+
for (const tone of this.tones) { try { tone.stop() } catch {} }
|
|
126
|
+
this.tones.clear()
|
|
127
|
+
this.stream?.getTracks().forEach(t => t.stop())
|
|
128
|
+
this.stream = null
|
|
129
|
+
this.source?.disconnect()
|
|
130
|
+
this.capture?.disconnect()
|
|
131
|
+
this.mute?.disconnect()
|
|
132
|
+
this.clear()
|
|
133
|
+
this.cleared.clear()
|
|
134
|
+
}
|
|
135
|
+
}
|