dsh-duet 0.1.7 → 0.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/src/client/audio.mjs +1 -1
- package/src/client/browser.mjs +70 -24
- 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 +2 -0
- package/src/host/plugin.mjs +44 -1
- package/src/host/proxy.mjs +8 -1
- package/src/host/result-feed.mjs +15 -0
- package/src/host/sync-feed.mjs +72 -0
- package/src/shared/state.mjs +2 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-duet",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.8",
|
|
4
4
|
"description": "duet(二重奏):只用语音就能操作 DSH,边听边说、随时插话的全双工语音助手。",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dsh-plugin",
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
"scripts": {
|
|
23
23
|
"test": "node scripts/test.mjs",
|
|
24
24
|
"check": "node scripts/check-package.mjs",
|
|
25
|
-
"test:browser": "node tests/browser/settings.mjs && node tests/browser/tutorial.mjs && node tests/browser/feedback.mjs && node tests/browser/connection-hint.mjs && node tests/browser/resilience.mjs && node tests/browser/page-binding.mjs && node tests/browser/desktop-settings.mjs && node tests/browser/desktop-identity.mjs",
|
|
25
|
+
"test:browser": "node tests/browser/settings.mjs && node tests/browser/tutorial.mjs && node tests/browser/feedback.mjs && node tests/browser/connection-hint.mjs && node tests/browser/controls-layout.mjs && node tests/browser/resilience.mjs && node tests/browser/page-binding.mjs && node tests/browser/desktop-settings.mjs && node tests/browser/desktop-identity.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
package/src/client/browser.mjs
CHANGED
|
@@ -1,22 +1,24 @@
|
|
|
1
|
-
import { DuetState, PLUGIN_VERSION } from '../shared/state.mjs?v=0.1.
|
|
2
|
-
import { DuetAudio } from './audio.mjs?v=0.1.
|
|
3
|
-
import { HarnessRPCExecutor, rpcNavigationSession } from './rpc.mjs?v=0.1.
|
|
4
|
-
import { composerAccess, observeComposer, focusedSession, openLocalSession } from './composer.mjs?v=0.1.
|
|
5
|
-
import { startComposerBridge } from './composer-bridge.mjs?v=0.1.
|
|
6
|
-
import { mountTutorial } from './tutorial.mjs?v=0.1.
|
|
7
|
-
import { tutorialAdapter } from './tutorial-adapter.mjs?v=0.1.
|
|
8
|
-
import { mountRating } from './feedback.mjs?v=0.1.
|
|
9
|
-
import { createAudioUploadConsent } from './consent.mjs?v=0.1.
|
|
10
|
-
import { bindDuetShortcuts } from './shortcuts.mjs?v=0.1.
|
|
11
|
-
import { nativeInteractions } from './interactions.mjs?v=0.1.
|
|
12
|
-
import { mountConnectionHint } from './connection-hint.mjs?v=0.1.
|
|
13
|
-
import { mountControlsLayout } from './controls-layout.mjs?v=0.1.
|
|
14
|
-
import { mountNotice } from './notice.mjs?v=0.1.
|
|
15
|
-
import { workspaceIssue, requireWorkspace, browserSessionCatalog, sessionCreationPayload } from './workspaces.mjs?v=0.1.
|
|
16
|
-
import { voiceSocketUrl, bindSettingsLink } from './transport.mjs?v=0.1.
|
|
17
|
-
import { identityFetch, identityVoiceProtocols } from './identity.mjs?v=0.1.
|
|
18
|
-
import { sessionLabel } from '../shared/catalog.mjs?v=0.1.
|
|
19
|
-
import { resultNotification } from '../shared/result-notification.mjs?v=0.1.
|
|
1
|
+
import { DuetState, PLUGIN_VERSION } from '../shared/state.mjs?v=0.1.8'
|
|
2
|
+
import { DuetAudio } from './audio.mjs?v=0.1.8'
|
|
3
|
+
import { HarnessRPCExecutor, rpcNavigationSession } from './rpc.mjs?v=0.1.8'
|
|
4
|
+
import { composerAccess, observeComposer, focusedSession, openLocalSession } from './composer.mjs?v=0.1.8'
|
|
5
|
+
import { startComposerBridge } from './composer-bridge.mjs?v=0.1.8'
|
|
6
|
+
import { mountTutorial } from './tutorial.mjs?v=0.1.8'
|
|
7
|
+
import { tutorialAdapter } from './tutorial-adapter.mjs?v=0.1.8'
|
|
8
|
+
import { mountRating } from './feedback.mjs?v=0.1.8'
|
|
9
|
+
import { createAudioUploadConsent } from './consent.mjs?v=0.1.8'
|
|
10
|
+
import { bindDuetShortcuts } from './shortcuts.mjs?v=0.1.8'
|
|
11
|
+
import { nativeInteractions } from './interactions.mjs?v=0.1.8'
|
|
12
|
+
import { mountConnectionHint } from './connection-hint.mjs?v=0.1.8'
|
|
13
|
+
import { mountControlsLayout } from './controls-layout.mjs?v=0.1.8'
|
|
14
|
+
import { mountNotice } from './notice.mjs?v=0.1.8'
|
|
15
|
+
import { workspaceIssue, requireWorkspace, browserSessionCatalog, sessionCreationPayload } from './workspaces.mjs?v=0.1.8'
|
|
16
|
+
import { voiceSocketUrl, bindSettingsLink } from './transport.mjs?v=0.1.8'
|
|
17
|
+
import { identityFetch, identityVoiceProtocols } from './identity.mjs?v=0.1.8'
|
|
18
|
+
import { sessionLabel } from '../shared/catalog.mjs?v=0.1.8'
|
|
19
|
+
import { resultNotification } from '../shared/result-notification.mjs?v=0.1.8'
|
|
20
|
+
import { HarnessSync } from './harness-sync.mjs?v=0.1.8'
|
|
21
|
+
import { LocalSync } from './local-sync.mjs?v=0.1.8'
|
|
20
22
|
|
|
21
23
|
export function mountDuet(ctx) {
|
|
22
24
|
const pageId = crypto.randomUUID()
|
|
@@ -26,6 +28,8 @@ export function mountDuet(ctx) {
|
|
|
26
28
|
let nextPollAt = 0, pollController, pollWakePending = false, pollFailureSince = null, pollFailures = 0, pollGeneration = -1
|
|
27
29
|
const notices = mountNotice(() => controls)
|
|
28
30
|
const labels = new Map()
|
|
31
|
+
const resultResume = {}
|
|
32
|
+
let localSync
|
|
29
33
|
let clientTraceId = null, diagnosticCount = 0
|
|
30
34
|
let connectionGuidance = null, reportHintShown = null
|
|
31
35
|
let tutorial, teaching, ratingPanel, connectionHint, stopControlsLayout, stopSettings
|
|
@@ -90,10 +94,18 @@ export function mountDuet(ctx) {
|
|
|
90
94
|
}
|
|
91
95
|
const composer = composerAccess(ctx, id => sessionLabel(labels.get(id), id))
|
|
92
96
|
const interactions = nativeInteractions(ctx)
|
|
97
|
+
const resultPush = new HarnessSync(send, localSync, () => ({
|
|
98
|
+
sessions: browserSessionCatalog(ctx, localSync.snapshot?.sessions || []).map(s => ({
|
|
99
|
+
session_id:s.session_id, label:s.label, active:s.active, running:Boolean(s.running), updated_at:s.updated_at,
|
|
100
|
+
})),
|
|
101
|
+
interactions: interactions.snapshot(),
|
|
102
|
+
}), report, resultResume)
|
|
103
|
+
const stopInteractions = interactions.subscribe(() => resultPush.changed())
|
|
93
104
|
const rpc = new HarnessRPCExecutor(send, fetch, report, async (request, signal) =>
|
|
94
105
|
(await interactions(request, signal)) ?? composer.execute(request, signal), rows =>
|
|
95
106
|
browserSessionCatalog(ctx, rows).map(row => ({ ...row, active: row.session_id === focusedSession(ctx) })), {
|
|
96
107
|
id: connectionTraceId,
|
|
108
|
+
syncSupported: () => localSync?.active && interactions.supportsSync,
|
|
97
109
|
creationPayload: payload => sessionCreationPayload(ctx, payload),
|
|
98
110
|
completed: async (request, body, signal) => {
|
|
99
111
|
const id = rpcNavigationSession(request, body)
|
|
@@ -101,15 +113,23 @@ export function mountDuet(ctx) {
|
|
|
101
113
|
},
|
|
102
114
|
})
|
|
103
115
|
const connection = {
|
|
116
|
+
resultPush,
|
|
104
117
|
feedbackTicket: null,
|
|
105
118
|
send,
|
|
106
119
|
sendState: state => { if (state) send({ type: 'harness.state', state }) },
|
|
107
120
|
playing: () => audio.playing(),
|
|
108
121
|
async close() {
|
|
109
122
|
report({ event: 'browser.connection_close', buffered_bytes: ws?.bufferedAmount })
|
|
123
|
+
// Explicit mode changes start a fresh listening window. An unexpected
|
|
124
|
+
// socket close retains only this page's last acknowledged cursor.
|
|
125
|
+
if (mode === 'online' && ws?.readyState === WebSocket.OPEN) {
|
|
126
|
+
delete resultResume.cursor; delete resultResume.epoch
|
|
127
|
+
}
|
|
110
128
|
closed = true
|
|
111
129
|
clearTimeout(startupTimer)
|
|
112
130
|
opening.abort()
|
|
131
|
+
resultPush.close()
|
|
132
|
+
stopInteractions?.()
|
|
113
133
|
stopComposer?.()
|
|
114
134
|
stopBridge?.(); stopBridge = null
|
|
115
135
|
rpc.close()
|
|
@@ -134,7 +154,7 @@ export function mountDuet(ctx) {
|
|
|
134
154
|
if(!identity.ok)throw Error('voice_config_unavailable')
|
|
135
155
|
requireWorkspace(ctx)
|
|
136
156
|
if(closed)return
|
|
137
|
-
if (mode === 'online') stopBridge = startComposerBridge(ctx, connectionTraceId)
|
|
157
|
+
if (mode === 'online') stopBridge = startComposerBridge(ctx, connectionTraceId, fetch, localSync)
|
|
138
158
|
report({ event: 'browser.connection_start', page_binding: 'connection_owner_v1' })
|
|
139
159
|
ws = new WebSocket(voiceSocketUrl({ mode, plugin_version: PLUGIN_VERSION, client_trace_id: connectionTraceId, page_id: pageId }), identityVoiceProtocols())
|
|
140
160
|
ws.onopen = () => {
|
|
@@ -146,6 +166,7 @@ export function mountDuet(ctx) {
|
|
|
146
166
|
let message
|
|
147
167
|
try {
|
|
148
168
|
message = JSON.parse(event.data)
|
|
169
|
+
if (resultPush.event(message)) return
|
|
149
170
|
if (message.type === 'harness.rpc.request') {
|
|
150
171
|
if (mode !== 'online') throw new Error('harness_rpc_requires_online')
|
|
151
172
|
await rpc.execute(message)
|
|
@@ -158,6 +179,8 @@ export function mountDuet(ctx) {
|
|
|
158
179
|
compatibility: message.error?.compatibility, policy: message.error?.policy }); return
|
|
159
180
|
}
|
|
160
181
|
if (message.type === 'session.created' && !ready) {
|
|
182
|
+
if (message.harness_rpc_max_bytes === 2_000_000) rpc.maxBytes = 2_000_000
|
|
183
|
+
if (mode === 'online') resultPush.offer(message.harness_sync)
|
|
161
184
|
connectionGuidance=message.connection_route?.connection_hint
|
|
162
185
|
reportHintShown=hint=>{
|
|
163
186
|
report({event:'browser.connection_hint_shown',connection_hint:hint})
|
|
@@ -198,6 +221,8 @@ export function mountDuet(ctx) {
|
|
|
198
221
|
}
|
|
199
222
|
}
|
|
200
223
|
ws.onclose = event => {
|
|
224
|
+
resultPush.close()
|
|
225
|
+
stopInteractions?.()
|
|
201
226
|
stopComposer?.()
|
|
202
227
|
stopBridge?.(); stopBridge = null
|
|
203
228
|
report({ event: 'browser.ws_closed', code: event.code, reason: event.reason, was_clean: event.wasClean })
|
|
@@ -318,7 +343,15 @@ export function mountDuet(ctx) {
|
|
|
318
343
|
pollController = controller
|
|
319
344
|
const timeout = setTimeout(() => controller.abort(), 5000)
|
|
320
345
|
try {
|
|
321
|
-
const
|
|
346
|
+
const pushing = state.connection?.resultPush?.active === true
|
|
347
|
+
const cached = localSync?.active ? localSync.snapshot : null
|
|
348
|
+
const [catalog, health] = cached ? [{sessions:cached.sessions}, cached.health]
|
|
349
|
+
: await Promise.all([api('sessions',controller.signal), api('health',controller.signal)])
|
|
350
|
+
const headOnly = pushing || cursor === null || resultEpoch !== health.focus_epoch
|
|
351
|
+
const completed = headOnly ? {results:[],current_cursor:health.result_cursor,next_cursor:health.result_cursor}
|
|
352
|
+
: cached ? {results:[...localSync.results.values()].filter(j => j.completion_seq > cursor),
|
|
353
|
+
next_cursor:cached.cursor,current_cursor:cached.health.result_cursor}
|
|
354
|
+
: await api(`results?after=${cursor}&limit=20`,controller.signal)
|
|
322
355
|
if (disposed) return
|
|
323
356
|
catalog.sessions = browserSessionCatalog(ctx, catalog.sessions)
|
|
324
357
|
const issue = workspaceIssue(ctx)
|
|
@@ -339,6 +372,7 @@ export function mountDuet(ctx) {
|
|
|
339
372
|
})
|
|
340
373
|
resultEpoch = health.focus_epoch
|
|
341
374
|
cursor = bootstrap ? completed.current_cursor : completed.next_cursor
|
|
375
|
+
state.connection?.resultPush?.changed()
|
|
342
376
|
if (pollFailures >= 3 && state.mode !== 'off') notice('会话同步已恢复。')
|
|
343
377
|
pollFailureSince = null; pollFailures = 0
|
|
344
378
|
} catch (error) {
|
|
@@ -354,10 +388,19 @@ export function mountDuet(ctx) {
|
|
|
354
388
|
nextPollAt = pollWakePending ? 0 : startedAt + (state.mode !== 'off' || tutorial?.active ? 1000 : document.hidden ? 15000 : 5000)
|
|
355
389
|
}
|
|
356
390
|
}
|
|
357
|
-
const timer = setInterval(() => { if (Date.now() >= nextPollAt) void poll(); state.tick() }, 1000)
|
|
358
|
-
const wakePoll = () => { pollWakePending = true; nextPollAt = 0 }
|
|
391
|
+
const timer = setInterval(() => { if (!localSync?.active && Date.now() >= nextPollAt) void poll(); state.tick() }, 1000)
|
|
392
|
+
const wakePoll = () => { pollWakePending = true; nextPollAt = 0; localSync?.refresh(); void poll() }
|
|
359
393
|
const unwatchSessions = ctx.sessions.list.subscribe?.(wakePoll)
|
|
360
394
|
const unwatchWorkspaces = ctx.workspaces?.list?.subscribe?.(wakePoll)
|
|
395
|
+
let lastView = localStorage.getItem('dsh.workspace.view.v5')
|
|
396
|
+
const viewChanged = () => { queueMicrotask(() => {
|
|
397
|
+
const value = localStorage.getItem('dsh.workspace.view.v5')
|
|
398
|
+
if (value !== lastView) { lastView = value; wakePoll() }
|
|
399
|
+
}) }
|
|
400
|
+
window.addEventListener('storage', viewChanged)
|
|
401
|
+
document.addEventListener('click', viewChanged)
|
|
402
|
+
localSync = new LocalSync({onChange: () => { pollWakePending = true; void poll() }})
|
|
403
|
+
localSync.start()
|
|
361
404
|
const progress = setInterval(() => { if (state.connection) audio.progress(state.connection.send) }, 200)
|
|
362
405
|
const visibility = () => { state.hidden = document.visibilityState !== 'visible'; state.tick(); void poll() }
|
|
363
406
|
document.addEventListener('visibilitychange', visibility)
|
|
@@ -370,7 +413,7 @@ export function mountDuet(ctx) {
|
|
|
370
413
|
if (Date.now() > deadline) throw Error('会话结果同步尚未就绪,请稍后重试教学')
|
|
371
414
|
await poll(); await new Promise(resolve => setTimeout(resolve, 150))
|
|
372
415
|
}
|
|
373
|
-
})
|
|
416
|
+
}, (context, id) => startComposerBridge(context, id, fetch, localSync))
|
|
374
417
|
const mountTeaching = () => {
|
|
375
418
|
if (!tutorial && controls) tutorial = mountTutorial({ controls, adapter: teaching })
|
|
376
419
|
}
|
|
@@ -381,6 +424,9 @@ export function mountDuet(ctx) {
|
|
|
381
424
|
disposed = true
|
|
382
425
|
pollController?.abort()
|
|
383
426
|
unwatchSessions?.(); unwatchWorkspaces?.()
|
|
427
|
+
localSync.close()
|
|
428
|
+
window.removeEventListener('storage', viewChanged)
|
|
429
|
+
document.removeEventListener('click', viewChanged)
|
|
384
430
|
notices.dispose()
|
|
385
431
|
stopShortcuts()
|
|
386
432
|
observer.disconnect()
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** Composer requests belong to one explicit voice/tutorial connection, never all tabs. */
|
|
2
|
-
import { focusedSession as currentSession } from './composer.mjs?v=0.1.
|
|
2
|
+
import { focusedSession as currentSession } from './composer.mjs?v=0.1.8'
|
|
3
3
|
|
|
4
|
-
export function startComposerBridge(ctx, clientId, fetchImpl = fetch) {
|
|
4
|
+
export function startComposerBridge(ctx, clientId, fetchImpl = fetch, feed = null) {
|
|
5
5
|
const focusedSession = () => currentSession(ctx)
|
|
6
6
|
const bridgeFetch = async (url, options = {}, timeoutMs = 8000) => {
|
|
7
7
|
const request = new AbortController()
|
|
@@ -15,6 +15,7 @@ export function startComposerBridge(ctx, clientId, fetchImpl = fetch) {
|
|
|
15
15
|
const controller = new AbortController()
|
|
16
16
|
let pollRunning = false
|
|
17
17
|
let retryTimer
|
|
18
|
+
const inFlight = new Set()
|
|
18
19
|
|
|
19
20
|
const digest = async (text) => {
|
|
20
21
|
const bytes = new TextEncoder().encode(text)
|
|
@@ -127,6 +128,9 @@ export function startComposerBridge(ctx, clientId, fetchImpl = fetch) {
|
|
|
127
128
|
|
|
128
129
|
const processRequest = async (candidate) => {
|
|
129
130
|
if (controller.signal.aborted || candidate.target_client_id !== clientId) return
|
|
131
|
+
if (inFlight.has(candidate.id)) return
|
|
132
|
+
inFlight.add(candidate.id)
|
|
133
|
+
try {
|
|
130
134
|
const claimResponse = await bridgeFetch(
|
|
131
135
|
`/duplex-control/api/composer/requests/${encodeURIComponent(candidate.id)}/claim`,
|
|
132
136
|
{
|
|
@@ -152,10 +156,12 @@ export function startComposerBridge(ctx, clientId, fetchImpl = fetch) {
|
|
|
152
156
|
status: error?.code === "session_not_ready" ? 503 : 409,
|
|
153
157
|
})
|
|
154
158
|
}
|
|
159
|
+
} finally { inFlight.delete(candidate.id) }
|
|
155
160
|
}
|
|
156
161
|
|
|
157
162
|
const poll = async () => {
|
|
158
163
|
if (pollRunning || controller.signal.aborted) return
|
|
164
|
+
if (feed?.active) return
|
|
159
165
|
clearTimeout(retryTimer)
|
|
160
166
|
pollRunning = true
|
|
161
167
|
let succeeded = false
|
|
@@ -179,12 +185,16 @@ export function startComposerBridge(ctx, clientId, fetchImpl = fetch) {
|
|
|
179
185
|
pollRunning = false
|
|
180
186
|
if (!controller.signal.aborted) {
|
|
181
187
|
// Successful long polls re-arm without a background-tab timer.
|
|
182
|
-
if (succeeded) void poll()
|
|
188
|
+
if (succeeded && !feed?.active) void poll()
|
|
183
189
|
else retryTimer = setTimeout(() => { void poll() }, 1000)
|
|
184
190
|
}
|
|
185
191
|
}
|
|
186
192
|
}
|
|
187
193
|
|
|
194
|
+
const unbind = feed?.bindOwner(() => ({ client_id: clientId, session_id: focusedSession() || null, visibility: document.visibilityState }))
|
|
195
|
+
const uncommand = feed?.onCommand(request => { void processRequest(request).catch(() => {}) })
|
|
196
|
+
const unfeed = feed?.subscribe(() => { clearTimeout(retryTimer); if (!feed.active) void poll() })
|
|
197
|
+
const focus = ctx.sessions.list.subscribe?.(() => feed?.beat())
|
|
188
198
|
void poll()
|
|
189
199
|
const resume = () => { void poll() }
|
|
190
200
|
window.addEventListener?.('online', resume)
|
|
@@ -193,6 +203,7 @@ export function startComposerBridge(ctx, clientId, fetchImpl = fetch) {
|
|
|
193
203
|
return () => {
|
|
194
204
|
controller.abort()
|
|
195
205
|
clearTimeout(retryTimer)
|
|
206
|
+
unbind?.(); uncommand?.(); unfeed?.(); focus?.()
|
|
196
207
|
window.removeEventListener?.('online', resume)
|
|
197
208
|
window.removeEventListener?.('pageshow', resume)
|
|
198
209
|
if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', resume)
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** A brief, non-modal invitation after the microphone is actually ready. */
|
|
2
|
-
import {normalizeGuidance} from '../shared/connection-guidance.mjs?v=0.1.
|
|
2
|
+
import {normalizeGuidance} from '../shared/connection-guidance.mjs?v=0.1.8'
|
|
3
3
|
export function mountConnectionHint(controls, { duration = 8000, onShown = ()=>{} } = {}) {
|
|
4
4
|
const hint = document.createElement('div')
|
|
5
5
|
hint.dataset.duetConnectionHint = ''
|
|
@@ -19,7 +19,8 @@ export function mountConnectionHint(controls, { duration = 8000, onShown = ()=>{
|
|
|
19
19
|
const position = () => {
|
|
20
20
|
if (hint.hidden || disposed) return
|
|
21
21
|
if (!controls.isConnected) { hide(); return }
|
|
22
|
-
const
|
|
22
|
+
const mic = controls.querySelector('[data-voice=mic]')
|
|
23
|
+
const button = mic?.getClientRects().length ? mic : controls.querySelector('#dsh-duet-entry') || controls
|
|
23
24
|
const rect = button.getBoundingClientRect(), width = hint.offsetWidth, height = hint.offsetHeight
|
|
24
25
|
const left = Math.max(16, Math.min(rect.left, innerWidth - width - 16))
|
|
25
26
|
const above = rect.top >= height + 26
|
|
@@ -1,18 +1,139 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/** A compact launcher; its top-layer flyout consumes no host footer space. */
|
|
2
2
|
export function mountControlsLayout(controls) {
|
|
3
3
|
const parent = controls.parentElement
|
|
4
|
+
const hostCompact = parent.getAttribute('data-duet-compact-host')
|
|
5
|
+
const ancestors = []
|
|
6
|
+
for (let node = parent; node; node = node.parentElement) ancestors.push(node)
|
|
7
|
+
// Flex children may retain their intrinsic width after the sidebar shrinks.
|
|
8
|
+
// Measure the available ancestor content boxes, skipping display:contents.
|
|
9
|
+
const geometry = () => {
|
|
10
|
+
let width = Infinity, boundary = parent.getBoundingClientRect(), clipped = false
|
|
11
|
+
for (const node of ancestors) {
|
|
12
|
+
const rect = node.getBoundingClientRect(), style = getComputedStyle(node)
|
|
13
|
+
if (style.display === 'contents' || rect.width <= 0) continue
|
|
14
|
+
const inset = ['paddingLeft', 'paddingRight', 'borderLeftWidth', 'borderRightWidth']
|
|
15
|
+
.reduce((sum, key) => sum + (parseFloat(style[key]) || 0), 0)
|
|
16
|
+
width = Math.min(width, Math.max(0, rect.width - inset))
|
|
17
|
+
if (!clipped && ['hidden', 'clip', 'auto', 'scroll'].includes(style.overflowX)) {
|
|
18
|
+
boundary = rect; clipped = true
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return { width, boundary }
|
|
22
|
+
}
|
|
23
|
+
const entry = controls.querySelector('#dsh-duet-entry')
|
|
24
|
+
if (!entry) return () => {}
|
|
25
|
+
const initial = { controls: controls.style.cssText, entry: entry.style.cssText }
|
|
26
|
+
const label = [...entry.childNodes].find(node => node.nodeType === Node.TEXT_NODE)
|
|
27
|
+
const labelText = label?.textContent
|
|
28
|
+
const actions = document.createElement('div')
|
|
29
|
+
actions.dataset.duetActions = ''
|
|
30
|
+
actions.id = 'dsh-duet-actions'
|
|
31
|
+
actions.setAttribute('role', 'group')
|
|
32
|
+
actions.setAttribute('aria-label', 'duet 语音控制')
|
|
33
|
+
for (const node of [...controls.children]) if (node.matches('[data-voice],a')) actions.append(node)
|
|
34
|
+
controls.append(actions)
|
|
35
|
+
let compact = false, opened = false, timer, disposed = false, pinned = false, suppressFocus = false
|
|
36
|
+
const listeners = []
|
|
37
|
+
const listen = (node, event, fn, options) => {
|
|
38
|
+
node.addEventListener(event, fn, options)
|
|
39
|
+
listeners.push(() => node.removeEventListener(event, fn, options))
|
|
40
|
+
}
|
|
41
|
+
const position = () => {
|
|
42
|
+
if (!opened) return
|
|
43
|
+
const rect = entry.getBoundingClientRect(), width = actions.offsetWidth, height = actions.offsetHeight
|
|
44
|
+
const sidebar = geometry().boundary, right = Math.max(rect.right, sidebar.right) + 8
|
|
45
|
+
actions.style.left = `${Math.max(8, Math.min(right + width <= innerWidth - 8 ? right : Math.min(rect.left, sidebar.left) - width - 8, innerWidth - width - 8))}px`
|
|
46
|
+
actions.style.top = `${Math.max(8, Math.min(rect.top + (rect.height - height) / 2, innerHeight - height - 8))}px`
|
|
47
|
+
}
|
|
48
|
+
const close = () => {
|
|
49
|
+
clearTimeout(timer)
|
|
50
|
+
if (!opened) return
|
|
51
|
+
if (actions.matches(':popover-open')) actions.hidePopover()
|
|
52
|
+
actions.hidden = true; opened = false
|
|
53
|
+
entry.setAttribute('aria-expanded', 'false')
|
|
54
|
+
}
|
|
55
|
+
const open = () => {
|
|
56
|
+
clearTimeout(timer)
|
|
57
|
+
if (!compact || disposed || !controls.isConnected) return
|
|
58
|
+
if (!opened) {
|
|
59
|
+
actions.hidden = false; actions.showPopover(); opened = true
|
|
60
|
+
entry.setAttribute('aria-expanded', 'true')
|
|
61
|
+
}
|
|
62
|
+
position()
|
|
63
|
+
}
|
|
64
|
+
const later = () => {
|
|
65
|
+
clearTimeout(timer)
|
|
66
|
+
timer = setTimeout(() => {
|
|
67
|
+
if (!pinned && !entry.matches(':hover') && !actions.matches(':hover') &&
|
|
68
|
+
!controls.contains(document.activeElement)) close()
|
|
69
|
+
}, 220)
|
|
70
|
+
}
|
|
4
71
|
const update = () => {
|
|
5
|
-
const
|
|
6
|
-
if (controls.dataset.compact === String(
|
|
72
|
+
const next = geometry().width < 160 && typeof actions.showPopover === 'function'
|
|
73
|
+
if (controls.dataset.compact === String(next)) { position(); return }
|
|
74
|
+
close(); compact = next
|
|
7
75
|
controls.dataset.compact = String(compact)
|
|
8
|
-
|
|
76
|
+
if (compact) parent.setAttribute('data-duet-compact-host', 'true')
|
|
77
|
+
else if (hostCompact === null) parent.removeAttribute('data-duet-compact-host')
|
|
78
|
+
else parent.setAttribute('data-duet-compact-host', hostCompact)
|
|
79
|
+
controls.style.flexDirection = 'row'
|
|
9
80
|
controls.style.margin = compact ? '4px 0' : '4px 8px'
|
|
10
|
-
controls.style.padding = compact ? '
|
|
11
|
-
|
|
12
|
-
|
|
81
|
+
controls.style.padding = compact ? '2px 0' : '6px 8px'
|
|
82
|
+
controls.style.justifyContent = compact ? 'center' : ''
|
|
83
|
+
controls.style.minWidth = '0'
|
|
84
|
+
entry.style.cssText = initial.entry
|
|
85
|
+
if (label) label.textContent = compact ? 'D' : labelText
|
|
86
|
+
if (compact) {
|
|
87
|
+
entry.style.cssText += ';display:flex;align-items:center;gap:2px;margin:0;padding:4px;box-sizing:border-box;min-width:32px;height:32px;font-size:23px;cursor:pointer'
|
|
88
|
+
entry.setAttribute('role', 'button'); entry.tabIndex = 0
|
|
89
|
+
entry.setAttribute('aria-label', 'duet 语音控制')
|
|
90
|
+
entry.setAttribute('aria-expanded', 'false'); entry.setAttribute('aria-controls', actions.id)
|
|
91
|
+
actions.setAttribute('popover', 'manual'); actions.hidden = true
|
|
92
|
+
actions.style.cssText = 'position:fixed;inset:auto;margin:0;box-sizing:border-box;align-items:center;gap:6px;padding:9px;border:1px solid #64748b55;border-radius:12px;background:light-dark(#fff,#17212f);color:light-dark(#243247,#edf3ff);color-scheme:light dark;box-shadow:0 8px 28px #0003;max-width:calc(100vw - 16px);z-index:100015'
|
|
93
|
+
if (pinned) open()
|
|
94
|
+
} else {
|
|
95
|
+
for (const attr of ['role', 'tabindex', 'aria-label', 'aria-expanded', 'aria-controls']) entry.removeAttribute(attr)
|
|
96
|
+
actions.removeAttribute('popover'); actions.hidden = false
|
|
97
|
+
actions.style.cssText = 'display:flex;align-items:center;gap:4px'
|
|
98
|
+
}
|
|
13
99
|
}
|
|
100
|
+
const style = document.createElement('style')
|
|
101
|
+
style.textContent = '[data-duet-compact-host="true"]{flex-direction:column!important;align-items:center!important;max-width:100%} #dsh-duet-actions:popover-open{display:flex} #dsh-duet-entry[role=button]:focus-visible{outline:2px solid #80c2ff;outline-offset:2px;border-radius:6px}'
|
|
102
|
+
controls.append(style)
|
|
103
|
+
listen(entry, 'pointerenter', open); listen(entry, 'pointerleave', later)
|
|
104
|
+
listen(actions, 'pointerenter', () => clearTimeout(timer)); listen(actions, 'pointerleave', later)
|
|
105
|
+
listen(entry, 'focus', () => { if (!suppressFocus) open() }); listen(controls, 'focusout', later)
|
|
106
|
+
listen(entry, 'click', event => { if (compact) { event.preventDefault(); open() } })
|
|
107
|
+
listen(entry, 'keydown', event => {
|
|
108
|
+
if (compact && ['Enter', ' ', 'ArrowRight', 'ArrowDown'].includes(event.key)) {
|
|
109
|
+
event.preventDefault(); open(); actions.querySelector('button,a')?.focus()
|
|
110
|
+
}
|
|
111
|
+
})
|
|
112
|
+
listen(document, 'keydown', event => {
|
|
113
|
+
if (event.key === 'Escape' && opened && !pinned) {
|
|
114
|
+
const restore = controls.contains(document.activeElement)
|
|
115
|
+
close()
|
|
116
|
+
if (restore) { suppressFocus = true; entry.focus(); suppressFocus = false }
|
|
117
|
+
}
|
|
118
|
+
})
|
|
119
|
+
listen(document, 'pointerdown', event => { if (!pinned && !controls.contains(event.target)) close() })
|
|
120
|
+
listen(controls, 'duet:reveal-controls', event => {
|
|
121
|
+
pinned = Boolean(event.detail)
|
|
122
|
+
if (pinned) open(); else later()
|
|
123
|
+
})
|
|
124
|
+
listen(window, 'resize', position); listen(window, 'scroll', position, true)
|
|
14
125
|
const observer = new ResizeObserver(update)
|
|
15
|
-
observer.observe(
|
|
126
|
+
for (const node of ancestors) observer.observe(node)
|
|
16
127
|
update()
|
|
17
|
-
return () =>
|
|
128
|
+
return () => {
|
|
129
|
+
close(); disposed = true; observer.disconnect()
|
|
130
|
+
for (const stop of listeners) stop()
|
|
131
|
+
if (label) label.textContent = labelText
|
|
132
|
+
for (const attr of ['role', 'tabindex', 'aria-label', 'aria-expanded', 'aria-controls']) entry.removeAttribute(attr)
|
|
133
|
+
controls.style.cssText = initial.controls; entry.style.cssText = initial.entry
|
|
134
|
+
controls.append(...actions.children); actions.remove(); style.remove()
|
|
135
|
+
delete controls.dataset.compact
|
|
136
|
+
if (hostCompact === null) parent.removeAttribute('data-duet-compact-host')
|
|
137
|
+
else parent.setAttribute('data-duet-compact-host', hostCompact)
|
|
138
|
+
}
|
|
18
139
|
}
|
package/src/client/entry.js
CHANGED
|
@@ -11,7 +11,7 @@ window.__ModuleLoader__.load({
|
|
|
11
11
|
ctx.effect(() => {
|
|
12
12
|
let active = true
|
|
13
13
|
let dispose
|
|
14
|
-
import('/duet/assets/client/browser.mjs?v=0.1.
|
|
14
|
+
import('/duet/assets/client/browser.mjs?v=0.1.8').then(module => {
|
|
15
15
|
if (active) dispose = module.mountDuet(ctx)
|
|
16
16
|
}).catch(error => console.warn('duet controls could not load:', error))
|
|
17
17
|
return () => { active = false; dispose?.() }
|
package/src/client/feedback.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Optional, explicit rating; never opens voice or submits without a user click. */
|
|
2
|
-
import { identityFetch } from './identity.mjs?v=0.1.
|
|
2
|
+
import { identityFetch } from './identity.mjs?v=0.1.8'
|
|
3
3
|
|
|
4
4
|
export function mountRating(anchor, sessionTicket) {
|
|
5
5
|
if(!sessionTicket)return null
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { broadcastText } from '../shared/result-notification.mjs'
|
|
2
|
+
export const SYNC_CAPABILITIES = ['session_state', 'pending_interactions', 'task_results']
|
|
3
|
+
|
|
4
|
+
/** Coalesced state and acknowledged results on the negotiated voice connection. */
|
|
5
|
+
export class HarnessSync {
|
|
6
|
+
constructor(send, feed, readState, report = () => {}, resume = {}) {
|
|
7
|
+
Object.assign(this, { send, feed, readState, report, resume })
|
|
8
|
+
this.active = false; this.closed = false; this.sequence = 0; this.abort = new AbortController()
|
|
9
|
+
}
|
|
10
|
+
offer(value) {
|
|
11
|
+
if (this.offerValue || this.closed || !this.feed?.active || value?.protocol !== 'harness_sync_v1' ||
|
|
12
|
+
JSON.stringify(value.capabilities) !== JSON.stringify(SYNC_CAPABILITIES) ||
|
|
13
|
+
!/^[a-f0-9]{32}$/.test(value.connection_id) || !Number.isSafeInteger(value.cursor) || value.cursor < 0 || typeof value.epoch !== 'string') return
|
|
14
|
+
this.offerValue = value; this.cursor = value.cursor; this.epoch = value.epoch
|
|
15
|
+
if (this.resume.epoch === value.epoch && Number.isSafeInteger(this.resume.cursor)) this.cursor = Math.min(this.resume.cursor, value.cursor)
|
|
16
|
+
Object.assign(this.resume, {epoch:this.epoch,cursor:this.cursor})
|
|
17
|
+
this.send({type:'harness.sync.subscribe', connection_id:value.connection_id, protocol:value.protocol,
|
|
18
|
+
capabilities:SYNC_CAPABILITIES, cursor:this.cursor, epoch:this.epoch, sequence:0, state:this.readState()})
|
|
19
|
+
this.timer = setTimeout(() => this.fallback('negotiation_timeout'), 5000)
|
|
20
|
+
}
|
|
21
|
+
event(event) {
|
|
22
|
+
if (!event.type?.startsWith('harness.sync.')) return false
|
|
23
|
+
if (this.closed || event.connection_id !== this.offerValue?.connection_id) return true
|
|
24
|
+
if (event.type === 'harness.sync.ready' && !this.active) {
|
|
25
|
+
if (JSON.stringify(event.capabilities) !== JSON.stringify(SYNC_CAPABILITIES)) { this.fallback('capability_mismatch'); return true }
|
|
26
|
+
clearTimeout(this.timer); this.active = true
|
|
27
|
+
this.report({event:'browser.harness_transport', transport:'harness_sync_v1'})
|
|
28
|
+
this.stopFeed = this.feed.subscribe(() => {
|
|
29
|
+
if (!this.feed.active) { this.fallback('local_sync_unavailable'); return }
|
|
30
|
+
this.changed(); void this.drain()
|
|
31
|
+
})
|
|
32
|
+
this.feed.replay(this.cursor, this.epoch)
|
|
33
|
+
this.heartbeat = setInterval(() => {
|
|
34
|
+
if (!this.feed.active) { this.fallback('local_sync_unavailable'); return }
|
|
35
|
+
this.send({type:'harness.sync.heartbeat', connection_id:this.offerValue.connection_id})
|
|
36
|
+
}, 15000)
|
|
37
|
+
this.changed(); void this.drain()
|
|
38
|
+
} else if (event.type === 'harness.sync.rejected') this.fallback('negotiation_rejected')
|
|
39
|
+
else if (event.type === 'harness.sync.state_ack' && event.sequence === this.statePending?.sequence) {
|
|
40
|
+
clearInterval(this.stateTimer); this.statePending = null
|
|
41
|
+
if (!event.accepted) this.fallback('state_rejected')
|
|
42
|
+
else if (this.stateDirty) this.changed()
|
|
43
|
+
} else if (event.type === 'harness.sync.ack' && this.pending?.id === event.event_id) {
|
|
44
|
+
event.accepted === true ? this.pending.resolve() : this.pending.reject(Error('result_not_accepted'))
|
|
45
|
+
}
|
|
46
|
+
return true
|
|
47
|
+
}
|
|
48
|
+
async deliver(job) {
|
|
49
|
+
const id = `${this.epoch}:${job.completion_seq}:${job.id}`
|
|
50
|
+
const event = {type:'harness.sync.push', connection_id:this.offerValue.connection_id,
|
|
51
|
+
event_id:id, epoch:this.epoch, result:{id:job.id, session_id:job.session_id,
|
|
52
|
+
status:job.status, completion_seq:job.completion_seq, completed_at:job.completed_at,
|
|
53
|
+
result:broadcastText(job.result || ''), error:broadcastText(job.error || ''), origin:job.origin || ''}}
|
|
54
|
+
await new Promise((resolve, reject) => {
|
|
55
|
+
let attempts = 0
|
|
56
|
+
const retry = () => {
|
|
57
|
+
if (++attempts > 5) { finish(); reject(Error('result_ack_timeout')); return }
|
|
58
|
+
this.send(event)
|
|
59
|
+
}
|
|
60
|
+
const timer = setInterval(retry, 2000)
|
|
61
|
+
const onAbort = () => { finish(); reject(Error('sync_closed')) }
|
|
62
|
+
const finish = () => { clearInterval(timer); this.abort.signal.removeEventListener('abort', onAbort); this.pending = null }
|
|
63
|
+
this.pending = {id, resolve:()=>{finish();resolve()}, reject:error=>{finish();reject(error)}}
|
|
64
|
+
this.abort.signal.addEventListener('abort', onAbort, {once:true}); retry()
|
|
65
|
+
})
|
|
66
|
+
this.cursor = job.completion_seq; this.resume.cursor = this.cursor
|
|
67
|
+
}
|
|
68
|
+
changed() {
|
|
69
|
+
if (!this.active || this.closed) return
|
|
70
|
+
this.stateDirty = true
|
|
71
|
+
if (this.statePending) return
|
|
72
|
+
const state = this.readState(), fingerprint = JSON.stringify(state)
|
|
73
|
+
this.stateDirty = false
|
|
74
|
+
if (fingerprint === this.lastState) return
|
|
75
|
+
this.lastState = fingerprint
|
|
76
|
+
const event = this.statePending = {type:'harness.sync.state', connection_id:this.offerValue.connection_id,
|
|
77
|
+
epoch:this.epoch, sequence:++this.sequence, state}
|
|
78
|
+
let attempts = 0
|
|
79
|
+
this.stateTimer = setInterval(() => { if (++attempts > 4) this.fallback('state_ack_timeout'); else this.send(event) }, 2000)
|
|
80
|
+
this.send(event)
|
|
81
|
+
}
|
|
82
|
+
async drain() {
|
|
83
|
+
if (this.draining || this.closed || !this.active) return
|
|
84
|
+
this.draining = true
|
|
85
|
+
try {
|
|
86
|
+
if (this.feed.epoch !== this.epoch) throw Error('result_source_restarted')
|
|
87
|
+
while (!this.closed && this.active) {
|
|
88
|
+
const job = [...this.feed.results.values()].filter(j => j.completion_seq > this.cursor)
|
|
89
|
+
.sort((a,b) => a.completion_seq - b.completion_seq)[0]
|
|
90
|
+
if (!job) break
|
|
91
|
+
await this.deliver(job)
|
|
92
|
+
}
|
|
93
|
+
} catch (error) { if (!this.closed) this.fallback(error.message) }
|
|
94
|
+
finally { this.draining = false }
|
|
95
|
+
}
|
|
96
|
+
fallback(reason) {
|
|
97
|
+
if (this.closed) return
|
|
98
|
+
if (this.offerValue) this.send({type:'harness.sync.fallback',connection_id:this.offerValue.connection_id})
|
|
99
|
+
this.report({event:'browser.harness_transport',transport:'polling',reason}); this.close()
|
|
100
|
+
}
|
|
101
|
+
close() {
|
|
102
|
+
this.closed = true; this.active = false; clearTimeout(this.timer)
|
|
103
|
+
clearInterval(this.heartbeat); clearInterval(this.stateTimer); this.stopFeed?.(); this.abort.abort()
|
|
104
|
+
}
|
|
105
|
+
}
|
package/src/client/identity.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { IDENTITY_HEADER, IDENTITY_TRANSPORT_HEADER, IDENTITY_TRANSPORT, IDENTITY_STORAGE,
|
|
2
|
-
VOICE_PROTOCOL, IDENTITY_PROTOCOL_PREFIX, validIdentityToken } from '../shared/identity.mjs?v=0.1.
|
|
2
|
+
VOICE_PROTOCOL, IDENTITY_PROTOCOL_PREFIX, validIdentityToken } from '../shared/identity.mjs?v=0.1.8'
|
|
3
3
|
|
|
4
4
|
/** Desktop strips plugin cookies. Keep the Host-signed value in its origin storage. */
|
|
5
5
|
export function createIdentityClient(globals = globalThis) {
|
|
@@ -1,20 +1,22 @@
|
|
|
1
1
|
/** Use the same pending objects as DSH's clickable question/approval cards. */
|
|
2
2
|
export function nativeInteractions(ctx) {
|
|
3
|
-
const firstSeen = new
|
|
3
|
+
const firstSeen = new Map()
|
|
4
4
|
const pending = () => ctx.uiSession.sessionStatus
|
|
5
5
|
? [...ctx.uiSession.sessionStatus.getSnapshot().values()].map(row => row.pendingInteraction).filter(Boolean)
|
|
6
6
|
: [...ctx.uiSession.pendingInteractions.getSnapshot().values()]
|
|
7
7
|
const publicValue = value => {
|
|
8
|
-
if (!firstSeen.has(value)) firstSeen.set(value, Date.now() / 1000)
|
|
9
|
-
|
|
8
|
+
if (!firstSeen.has(value.key)) firstSeen.set(value.key, Date.now() / 1000)
|
|
9
|
+
if (firstSeen.size > 512) firstSeen.delete(firstSeen.keys().next().value)
|
|
10
|
+
return { id: value.key, session_id: value.sessionId, created_at: firstSeen.get(value.key),
|
|
10
11
|
kind: value.kind === 'plan-review' ? 'plan_review' : value.kind,
|
|
11
12
|
...(value.kind === 'approval' ? { approval_id: value.key, tool_name: value.toolName,
|
|
12
13
|
call_id: value.callId || '', reason: value.reason || '' } : { questions: value.questions }) }
|
|
13
14
|
}
|
|
14
|
-
|
|
15
|
+
const snapshot = () => pending().filter(v => ['question', 'plan-review', 'approval'].includes(v.kind)).map(publicValue)
|
|
16
|
+
const execute = async (request, signal) => {
|
|
15
17
|
signal?.throwIfAborted()
|
|
16
18
|
if (request.method === 'GET' && request.path === '/api/interactions') {
|
|
17
|
-
return { interactions:
|
|
19
|
+
return { interactions: snapshot() }
|
|
18
20
|
}
|
|
19
21
|
const match = request.path.match(/^\/api\/interactions\/([^/]+)\/respond$/)
|
|
20
22
|
if (request.method !== 'POST' || !match) return undefined
|
|
@@ -31,4 +33,9 @@ export function nativeInteractions(ctx) {
|
|
|
31
33
|
}
|
|
32
34
|
return { ok: true, interaction_id: value.key }
|
|
33
35
|
}
|
|
36
|
+
execute.snapshot = snapshot
|
|
37
|
+
const store = ctx.uiSession.sessionStatus ?? ctx.uiSession.pendingInteractions
|
|
38
|
+
execute.supportsSync = typeof store.subscribe === 'function'
|
|
39
|
+
execute.subscribe = fn => store.subscribe?.(fn) ?? (() => {})
|
|
40
|
+
return execute
|
|
34
41
|
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { voiceSocketUrl } from './transport.mjs'
|
|
2
|
+
|
|
3
|
+
/** One page-local feed; Desktop uses the same stream base as voice. */
|
|
4
|
+
export class LocalSync {
|
|
5
|
+
constructor({ WebSocketImpl = WebSocket, onChange = () => {} } = {}) {
|
|
6
|
+
this.WebSocketImpl = WebSocketImpl; this.onChange = onChange
|
|
7
|
+
this.listeners = new Set(); this.commands = new Set(); this.results = new Map()
|
|
8
|
+
this.active = false; this.closed = false; this.cursor = null; this.epoch = null
|
|
9
|
+
this.owner = null; this.lastSeen = 0
|
|
10
|
+
this.failures = 0
|
|
11
|
+
}
|
|
12
|
+
start() {
|
|
13
|
+
if (this.closed) return
|
|
14
|
+
let ws
|
|
15
|
+
try { ws = this.ws = new this.WebSocketImpl(voiceSocketUrl({}, globalThis, 'duplex-control/sync/ws')) }
|
|
16
|
+
catch { this.disconnected(); return }
|
|
17
|
+
ws.onopen = () => {
|
|
18
|
+
this.send({ type: 'harness.sync.subscribe', protocol: 'harness_sync_v1', cursor: this.cursor, epoch: this.epoch })
|
|
19
|
+
this.beat()
|
|
20
|
+
clearInterval(this.heartbeat)
|
|
21
|
+
this.lastSeen = Date.now()
|
|
22
|
+
this.heartbeat = setInterval(() => {
|
|
23
|
+
if (Date.now() - this.lastSeen > 45000) { ws.close(); return }
|
|
24
|
+
this.beat()
|
|
25
|
+
}, 15000)
|
|
26
|
+
}
|
|
27
|
+
ws.onmessage = event => {
|
|
28
|
+
try {
|
|
29
|
+
const value = JSON.parse(event.data); this.lastSeen = Date.now()
|
|
30
|
+
if (value.type === 'harness.sync.command') { for (const fn of this.commands) fn(value.request); return }
|
|
31
|
+
if (value.type !== 'harness.sync.snapshot' || value.protocol !== 'harness_sync_v1') return
|
|
32
|
+
if (!Array.isArray(value.sessions) || !Array.isArray(value.results) || !Number.isSafeInteger(value.cursor)) throw Error('invalid_snapshot')
|
|
33
|
+
if (this.epoch !== value.epoch) this.results.clear()
|
|
34
|
+
this.epoch = value.epoch; this.cursor = value.cursor; this.snapshot = value
|
|
35
|
+
for (const job of value.results) this.results.set(job.completion_seq, job)
|
|
36
|
+
while (this.results.size > 500) this.results.delete(this.results.keys().next().value)
|
|
37
|
+
this.active = true; this.failures = 0
|
|
38
|
+
for (const fn of this.listeners) fn(value)
|
|
39
|
+
this.onChange()
|
|
40
|
+
this.send({ type: 'harness.sync.received', cursor: this.cursor, epoch: this.epoch, more: value.has_more === true })
|
|
41
|
+
} catch { ws.close(1008, 'invalid_sync_snapshot') }
|
|
42
|
+
}
|
|
43
|
+
ws.onerror = () => {}
|
|
44
|
+
ws.onclose = () => {
|
|
45
|
+
this.disconnected()
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
disconnected() {
|
|
49
|
+
clearInterval(this.heartbeat); this.active = false
|
|
50
|
+
if (this.closed) return
|
|
51
|
+
for (const fn of this.listeners) fn(null)
|
|
52
|
+
this.onChange()
|
|
53
|
+
this.retry = setTimeout(() => this.start(), Math.min(30000, 3000 * 2 ** this.failures++))
|
|
54
|
+
}
|
|
55
|
+
send(value) { if (this.ws?.readyState === 1) this.ws.send(JSON.stringify(value)) }
|
|
56
|
+
beat() { this.send({ type: 'harness.sync.heartbeat', owner: this.owner?.() ?? null }) }
|
|
57
|
+
bindOwner(read) { this.owner = read; this.beat(); return () => { if (this.owner === read) { this.owner = null; this.beat() } } }
|
|
58
|
+
refresh() { this.send({ type: 'harness.sync.refresh' }) }
|
|
59
|
+
replay(cursor, epoch) { this.send({ type: 'harness.sync.subscribe', protocol: 'harness_sync_v1', cursor, epoch }) }
|
|
60
|
+
subscribe(fn) { this.listeners.add(fn); return () => this.listeners.delete(fn) }
|
|
61
|
+
onCommand(fn) { this.commands.add(fn); return () => this.commands.delete(fn) }
|
|
62
|
+
close() { this.closed = true; clearTimeout(this.retry); clearInterval(this.heartbeat); this.ws?.close(); this.listeners.clear(); this.commands.clear() }
|
|
63
|
+
}
|
package/src/client/rpc.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/** Reverse RPC executes on this authenticated DSH origin, never a supplied URL. */
|
|
2
2
|
import { orderSessionCatalog, readWorkspaceView } from '../shared/catalog.mjs'
|
|
3
|
-
const MAX_BYTES =
|
|
3
|
+
const MAX_BYTES = 2_000_000
|
|
4
4
|
const READ = /^\/api\/(?:health|sessions|jobs|results|interactions|composer\/focused|sessions\/[A-Za-z0-9_-]+\/composer)$/
|
|
5
5
|
const WRITE = /^\/api\/(?:sessions|sessions\/[A-Za-z0-9_-]+\/(?:composer\/submit|activate|rename|fork)|interactions\/(?:(?:question|approval)(?::|%3[Aa]))?[A-Za-z0-9_-]+\/respond)$/
|
|
6
6
|
|
|
@@ -32,6 +32,7 @@ export class HarnessRPCExecutor {
|
|
|
32
32
|
// Native Window.fetch rejects an RPCExecutor receiver (Illegal invocation).
|
|
33
33
|
// Call the captured function plainly, not as an instance method.
|
|
34
34
|
this.send = send; this.fetch = (...args) => fetchImpl(...args); this.closed = false
|
|
35
|
+
this.maxBytes = 256_000
|
|
35
36
|
this.diagnostic = diagnostic
|
|
36
37
|
this.localComposer = localComposer
|
|
37
38
|
this.catalogOrder = catalogOrder
|
|
@@ -84,7 +85,8 @@ export class HarnessRPCExecutor {
|
|
|
84
85
|
return { ...envelope, status: 409, body: { error_code: error.code || 'composer_operation_failed', detail: 'Draft changed or unavailable; read input_status again' } }
|
|
85
86
|
}
|
|
86
87
|
}
|
|
87
|
-
const
|
|
88
|
+
const params = request.path === '/api/results' ? {...request.params, limit:Math.min(20, request.params?.limit || 20)} : request.params
|
|
89
|
+
const query = params ? '?' + new URLSearchParams(params) : ''
|
|
88
90
|
const response = await this.fetch('/duplex-control' + request.path + query, {
|
|
89
91
|
method: request.method, credentials: 'same-origin', redirect: 'error',
|
|
90
92
|
cache: 'no-store', signal: controller.signal,
|
|
@@ -94,13 +96,16 @@ export class HarnessRPCExecutor {
|
|
|
94
96
|
...(request.method !== 'GET' ? { body: JSON.stringify(payload) } : {}),
|
|
95
97
|
})
|
|
96
98
|
const text = await response.text()
|
|
97
|
-
|
|
99
|
+
// Older peers count Python's ASCII-escaped JSON, not its UTF-8 wire form.
|
|
100
|
+
const measured = this.maxBytes > 256_000 ? text : text.replace(/[^\x00-\x7f]/g, c => '\\u' + c.charCodeAt(0).toString(16).padStart(4,'0'))
|
|
101
|
+
if (new TextEncoder().encode(measured).length > this.maxBytes - 4096) throw new Error('harness_rpc_response_too_large')
|
|
98
102
|
const body = JSON.parse(text)
|
|
99
103
|
if (!body || typeof body !== 'object' || Array.isArray(body)) throw new Error('invalid_harness_rpc_body')
|
|
100
104
|
controller.signal.throwIfAborted()
|
|
101
105
|
if (response.ok && this.binding.completed) await this.binding.completed(request, body, controller.signal)
|
|
102
106
|
if (response.status === 200 && request.method === 'GET' && request.path === '/api/sessions' && Array.isArray(body.sessions)) {
|
|
103
|
-
body.duet_rpc_capabilities = ['create_session_v1'
|
|
107
|
+
body.duet_rpc_capabilities = ['create_session_v1',
|
|
108
|
+
...(this.binding.syncSupported?.() === false ? [] : ['harness_sync_v1'])]
|
|
104
109
|
// Both startup prompt and nth_N resolution read this same browser-local
|
|
105
110
|
// order, including manual drag order; archived rows cannot consume ranks.
|
|
106
111
|
body.sessions = this.catalogOrder(body.sessions)
|
package/src/client/settings.html
CHANGED
|
@@ -152,7 +152,7 @@
|
|
|
152
152
|
<footer><span>duet / DeepSeek Harness</span></footer>
|
|
153
153
|
</main>
|
|
154
154
|
<script type="module">
|
|
155
|
-
import { identityFetch } from '/duet/assets/client/identity.mjs?v=0.1.
|
|
155
|
+
import { identityFetch } from '/duet/assets/client/identity.mjs?v=0.1.8';
|
|
156
156
|
const base = "/duplex-control/api";
|
|
157
157
|
let debugEnabled = false, settingsRevision = null, feedbackSubmitting = false;
|
|
158
158
|
const composerChannel = typeof BroadcastChannel === "undefined" ? null : new BroadcastChannel("dsh-duplex-control-v1");
|
|
@@ -363,7 +363,7 @@
|
|
|
363
363
|
}
|
|
364
364
|
$('openTutorial').onclick = async () => {
|
|
365
365
|
try {
|
|
366
|
-
const {requestTutorial} = await import('/duet/assets/client/tutorial-request.mjs?v=0.1.
|
|
366
|
+
const {requestTutorial} = await import('/duet/assets/client/tutorial-request.mjs?v=0.1.8');
|
|
367
367
|
requestTutorial(localStorage);
|
|
368
368
|
$('tutorialStatus').textContent = '请回到 DSH 页面继续教学。';
|
|
369
369
|
} catch { $('tutorialStatus').textContent = '暂时无法打开教学,请允许浏览器存储后重试。'; }
|
|
@@ -372,11 +372,11 @@
|
|
|
372
372
|
setInterval(() => { loadDuetConfig().catch(showConnectionUnavailable); }, 2000);
|
|
373
373
|
void loadNotices();
|
|
374
374
|
setInterval(loadNotices, 60000);
|
|
375
|
-
import('/duet/assets/client/shortcuts.mjs?v=0.1.
|
|
375
|
+
import('/duet/assets/client/shortcuts.mjs?v=0.1.8').then(({mountShortcutSettings}) => {
|
|
376
376
|
const dispose = mountShortcutSettings({speaker:$('speakerShortcut'),mic:$('micShortcut'),clearSpeaker:$('clearSpeakerShortcut'),clearMic:$('clearMicShortcut'),status:$('shortcutStatus')});
|
|
377
377
|
window.addEventListener('pagehide', e => {if(!e.persisted)dispose()}, {once:true});
|
|
378
378
|
}).catch(() => { $('shortcutStatus').textContent = '暂时无法加载快捷键设置,请刷新重试。'; });
|
|
379
|
-
import('/duet/assets/client/microphone.mjs?v=0.1.
|
|
379
|
+
import('/duet/assets/client/microphone.mjs?v=0.1.8').then(({mountMicrophoneSettings}) => {
|
|
380
380
|
const dispose = mountMicrophoneSettings({select:$('microphoneDevice'),refresh:$('refreshMicrophones'),status:$('microphoneStatus')});
|
|
381
381
|
window.addEventListener('pagehide', dispose, {once:true});
|
|
382
382
|
}).catch(() => { $('microphoneStatus').textContent = '暂时无法加载麦克风设置,请刷新重试。'; });
|
package/src/client/transport.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** Use the same physical WebSocket base as DSH's own API gateway. */
|
|
2
|
-
export function voiceSocketUrl(params, globals = globalThis) {
|
|
2
|
+
export function voiceSocketUrl(params, globals = globalThis, path = 'duplex-control/voice/ws') {
|
|
3
3
|
const base = globals.__DSH_TRANSPORT__?.streamBaseUrl ?? globals.document.baseURI
|
|
4
|
-
const url = new URL(
|
|
4
|
+
const url = new URL(path, base)
|
|
5
5
|
if (!['http:', 'https:', 'ws:', 'wss:'].includes(url.protocol)) {
|
|
6
6
|
throw Error('voice_transport_unavailable')
|
|
7
7
|
}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/** DSH browser services plus existing voice connection; never opens a microphone. */
|
|
2
|
-
import { PLUGIN_VERSION } from '../shared/state.mjs?v=0.1.
|
|
3
|
-
import { focusedSession } from './composer.mjs?v=0.1.
|
|
4
|
-
import { sessionCreationPayload, workspaceIssue } from './workspaces.mjs?v=0.1.
|
|
5
|
-
import { startComposerBridge } from './composer-bridge.mjs?v=0.1.
|
|
2
|
+
import { PLUGIN_VERSION } from '../shared/state.mjs?v=0.1.8'
|
|
3
|
+
import { focusedSession } from './composer.mjs?v=0.1.8'
|
|
4
|
+
import { sessionCreationPayload, workspaceIssue } from './workspaces.mjs?v=0.1.8'
|
|
5
|
+
import { startComposerBridge } from './composer-bridge.mjs?v=0.1.8'
|
|
6
6
|
export function tutorialAdapter(ctx, state, audio, pollReady, startBridge = startComposerBridge) {
|
|
7
7
|
let narration
|
|
8
8
|
const completed = new Map()
|
package/src/client/tutorial.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Opt-in walkthrough. All writes are limited to sessions created by this run. */
|
|
2
|
-
import {consumeTutorialRequest} from './tutorial-request.mjs?v=0.1.
|
|
2
|
+
import {consumeTutorialRequest} from './tutorial-request.mjs?v=0.1.8'
|
|
3
3
|
export const TUTORIAL_KEY = 'dsh-duplex-tutorial-v1'
|
|
4
4
|
export const QUESTION = '什么是语音交互?请用一句话简单解释,不使用工具。'
|
|
5
5
|
export const INPUT = '用一句话介绍语音助手。'
|
|
@@ -142,6 +142,7 @@ export function mountTutorial({ controls, adapter }) {
|
|
|
142
142
|
}
|
|
143
143
|
}
|
|
144
144
|
const dismiss = async (forever=false) => {
|
|
145
|
+
controls.dispatchEvent(new CustomEvent('duet:reveal-controls',{detail:false}))
|
|
145
146
|
closed = true; put(sessionStorage,TUTORIAL_KEY,'closed'); if (forever) put(localStorage,TUTORIAL_KEY,'dismissed')
|
|
146
147
|
panel?.remove(); panel=null; highlight?.remove(); highlight=null; pointer?.remove();pointer=null
|
|
147
148
|
await run?.stop(); active=false; lockRelease?.(); lockRelease=null
|
|
@@ -154,6 +155,7 @@ export function mountTutorial({ controls, adapter }) {
|
|
|
154
155
|
if(closed)return
|
|
155
156
|
panel?.remove(); highlight?.remove();pointer?.remove();pointer=null
|
|
156
157
|
targetSelector = selector || '#dsh-duet-controls'
|
|
158
|
+
controls.dispatchEvent(new CustomEvent('duet:reveal-controls',{detail:Boolean(selector?.startsWith('[data-voice='))}))
|
|
157
159
|
target = document.querySelector(targetSelector) || controls
|
|
158
160
|
highlight = element('div',null,document.body); highlight.className='duet-tutorial-highlight'; highlight.setAttribute('aria-hidden','true')
|
|
159
161
|
highlight.dataset.target=targetSelector
|
package/src/host/assets.mjs
CHANGED
|
@@ -6,6 +6,8 @@ const modules = {
|
|
|
6
6
|
audio: 'client/audio', microphone: 'client/microphone', shortcuts: 'client/shortcuts',
|
|
7
7
|
browser: 'client/browser', rpc: 'client/rpc', composer: 'client/composer',
|
|
8
8
|
composer_bridge: 'client/composer-bridge',
|
|
9
|
+
harness_sync: 'client/harness-sync',
|
|
10
|
+
local_sync: 'client/local-sync',
|
|
9
11
|
interactions: 'client/interactions', tutorial: 'client/tutorial',
|
|
10
12
|
tutorial_adapter: 'client/tutorial-adapter', tutorial_request: 'client/tutorial-request',
|
|
11
13
|
feedback: 'client/feedback', consent: 'client/consent',
|
package/src/host/plugin.mjs
CHANGED
|
@@ -12,6 +12,7 @@ import { FeedbackService } from './feedback-store.mjs'
|
|
|
12
12
|
import { RemoteFeedback } from './feedback-files.mjs'
|
|
13
13
|
import { PLUGIN_VERSION } from '../shared/state.mjs'
|
|
14
14
|
import { buildSessionCatalog, sessionLabel } from '../shared/catalog.mjs'
|
|
15
|
+
import { broadcastText } from '../shared/result-notification.mjs'
|
|
15
16
|
import { publicAsset } from './assets.mjs'
|
|
16
17
|
import { duetEnv } from './environment.mjs'
|
|
17
18
|
import { EndpointDiscovery } from './endpoint-discovery.mjs'
|
|
@@ -152,7 +153,12 @@ async function readJson(req) {
|
|
|
152
153
|
return value
|
|
153
154
|
}
|
|
154
155
|
|
|
156
|
+
import { ResultFeed } from './result-feed.mjs'
|
|
157
|
+
import { registerSyncFeed } from './sync-feed.mjs'
|
|
158
|
+
|
|
155
159
|
export function apply(ctx, options = {}) {
|
|
160
|
+
const resultFeed = new ResultFeed()
|
|
161
|
+
ctx.effect(() => () => resultFeed.notify())
|
|
156
162
|
const jobs = new Map()
|
|
157
163
|
const jobOrder = []
|
|
158
164
|
const composerRequests = new Map()
|
|
@@ -169,6 +175,7 @@ export function apply(ctx, options = {}) {
|
|
|
169
175
|
// compatible: their in-memory lastRevision must never shadow a restarted host.
|
|
170
176
|
let focusRevision = Date.now()
|
|
171
177
|
let completionSequence = 0
|
|
178
|
+
let syncFeed
|
|
172
179
|
let composerRequestSequence = 0
|
|
173
180
|
let lastDuetRuntimeSeenAt = 0
|
|
174
181
|
let lastNativeInteractionsSeenAt = -Infinity
|
|
@@ -300,6 +307,7 @@ export function apply(ctx, options = {}) {
|
|
|
300
307
|
composerRequests.set(id, request)
|
|
301
308
|
composerRequestOrder.push(id)
|
|
302
309
|
for (const wake of [...composerPollWaiters]) wake()
|
|
310
|
+
syncFeed?.commands()
|
|
303
311
|
while (composerRequestOrder.length > MAX_COMPOSER_REQUESTS) {
|
|
304
312
|
const staleId = composerRequestOrder.shift()
|
|
305
313
|
const stale = composerRequests.get(staleId)
|
|
@@ -363,6 +371,8 @@ export function apply(ctx, options = {}) {
|
|
|
363
371
|
job.completed_at = nowSeconds()
|
|
364
372
|
completionSequence += 1
|
|
365
373
|
job.completion_seq = completionSequence
|
|
374
|
+
resultFeed.notify()
|
|
375
|
+
syncFeed?.changed()
|
|
366
376
|
throw error
|
|
367
377
|
}
|
|
368
378
|
if (syncFocus) selectSession(sessionId)
|
|
@@ -419,9 +429,12 @@ export function apply(ctx, options = {}) {
|
|
|
419
429
|
}
|
|
420
430
|
completionSequence += 1
|
|
421
431
|
job.completion_seq = completionSequence
|
|
432
|
+
resultFeed.notify()
|
|
433
|
+
syncFeed?.changed()
|
|
422
434
|
}
|
|
423
435
|
|
|
424
436
|
ctx.on('session/event', (session, event) => {
|
|
437
|
+
if (['turn/start', 'turn/end', 'user/message'].includes(event.type)) syncFeed?.changed()
|
|
425
438
|
if (['turn/start', 'turn/end', 'user/message'].includes(event.type)) {
|
|
426
439
|
audit.event('dsh.session_event', { session_id: session.id, event })
|
|
427
440
|
}
|
|
@@ -493,6 +506,25 @@ export function apply(ctx, options = {}) {
|
|
|
493
506
|
if(req.headers.origin!==undefined || req.headers[IDENTITY_TRANSPORT_HEADER.toLowerCase()]!==IDENTITY_TRANSPORT)return false
|
|
494
507
|
try {feedback.user(req);return settingsWriteAllowed(req,{verifiedLocalIdentity:true})} catch {return false}
|
|
495
508
|
}
|
|
509
|
+
ctx.effect(() => {
|
|
510
|
+
syncFeed = registerSyncFeed(ctx, {
|
|
511
|
+
snapshot: async (cursor, epoch) => {
|
|
512
|
+
const head = completionSequence
|
|
513
|
+
const after = epoch === focusEpoch && Number.isSafeInteger(cursor) ? Math.min(cursor, head) : head
|
|
514
|
+
const completed = jobOrder.map(id => jobs.get(id)).filter(job => job?.completion_seq > after)
|
|
515
|
+
.sort((a, b) => a.completion_seq - b.completion_seq)
|
|
516
|
+
const selected = completed.slice(0, 20)
|
|
517
|
+
return { epoch: focusEpoch, cursor: selected.at(-1)?.completion_seq ?? Math.max(after, head),
|
|
518
|
+
has_more: completed.length > selected.length, sessions: await listSessions(),
|
|
519
|
+
results: selected.map(job => ({...publicJob(job), result:broadcastText(job.result || ''), error:broadcastText(job.error || '')})),
|
|
520
|
+
health: { result_cursor: head, focus_epoch: focusEpoch } }
|
|
521
|
+
},
|
|
522
|
+
touch: owner => { lastNativeInteractionsSeenAt = nowSeconds(); browserClients.set(owner.client_id, { ...owner, last_seen_at: nowSeconds() }) },
|
|
523
|
+
commands: id => [...composerRequests.values()].filter(r => !r.claimed_by && r.target_client_id === id).slice(0, 20).map(publicComposerRequest),
|
|
524
|
+
})
|
|
525
|
+
return () => syncFeed.close()
|
|
526
|
+
})
|
|
527
|
+
|
|
496
528
|
const handleApi = async (req, res, pathname) => {
|
|
497
529
|
if(req.method==='POST' && pathname===`${ROUTE}/api/feedback`){
|
|
498
530
|
const rejection = ctx.connection.requestRejection(req)
|
|
@@ -1069,9 +1101,19 @@ export function apply(ctx, options = {}) {
|
|
|
1069
1101
|
sendJson(res, 200, { jobs: values })
|
|
1070
1102
|
return
|
|
1071
1103
|
}
|
|
1072
|
-
if (req.method === 'GET' &&
|
|
1104
|
+
if (req.method === 'GET' && [ `${ROUTE}/api/results`, `${ROUTE}/api/results/wait` ].includes(pathname)) {
|
|
1105
|
+
if (pathname.endsWith('/wait')) {
|
|
1106
|
+
const rejection = ctx.connection.requestRejection(req)
|
|
1107
|
+
if (rejection) { sendError(res, rejection, '请先打开并登录 DSH 主页面'); return }
|
|
1108
|
+
}
|
|
1073
1109
|
const url = new URL(req.url || '/', 'http://localhost')
|
|
1074
1110
|
const after = Math.max(0, Number.parseInt(url.searchParams.get('after') || '0', 10) || 0)
|
|
1111
|
+
const epoch = url.searchParams.get('epoch')
|
|
1112
|
+
if (pathname.endsWith('/wait') && after >= completionSequence && (!epoch || epoch === focusEpoch)) {
|
|
1113
|
+
if (resultFeed.waiters.size >= 64) { sendError(res, 429, 'result_feed_capacity'); return }
|
|
1114
|
+
await resultFeed.wait(req, res)
|
|
1115
|
+
if (res.destroyed || hostAbort.signal.aborted) return
|
|
1116
|
+
}
|
|
1075
1117
|
const limit = Math.max(1, Math.min(200, Number.parseInt(url.searchParams.get('limit') || '100', 10) || 100))
|
|
1076
1118
|
const completed = jobOrder
|
|
1077
1119
|
.map(id => jobs.get(id))
|
|
@@ -1083,6 +1125,7 @@ export function apply(ctx, options = {}) {
|
|
|
1083
1125
|
results: selected.map(publicJob),
|
|
1084
1126
|
next_cursor: nextCursor,
|
|
1085
1127
|
current_cursor: completionSequence,
|
|
1128
|
+
epoch: focusEpoch,
|
|
1086
1129
|
has_more: completed.length > selected.length,
|
|
1087
1130
|
})
|
|
1088
1131
|
return
|
package/src/host/proxy.mjs
CHANGED
|
@@ -57,7 +57,7 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
57
57
|
if (!['ws:', 'wss:'].includes(url.protocol) || url.username || url.password || url.hash) throw new Error('invalid_voice_endpoint')
|
|
58
58
|
}
|
|
59
59
|
const { WebSocket, WebSocketServer } = require('ws')
|
|
60
|
-
const server = new WebSocketServer({ noServer: true, maxPayload:
|
|
60
|
+
const server = new WebSocketServer({ noServer: true, maxPayload: 2_100_000,
|
|
61
61
|
handleProtocols: protocols => protocols.has(VOICE_PROTOCOL) ? VOICE_PROTOCOL : false })
|
|
62
62
|
const connections = new Map()
|
|
63
63
|
const stop = ctx.webServer.registerUpgrade({
|
|
@@ -117,6 +117,7 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
117
117
|
const pending = []
|
|
118
118
|
const startup = setTimeout(() => fail('voice_start_timeout'), 20000)
|
|
119
119
|
let hintReporting=false,hintReported=false
|
|
120
|
+
let resultPushConnection = null
|
|
120
121
|
const sendUpstream = (data, binary) => {
|
|
121
122
|
if (!binary) {
|
|
122
123
|
const message = JSON.parse(data.toString())
|
|
@@ -171,6 +172,11 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
171
172
|
return
|
|
172
173
|
}
|
|
173
174
|
if (!initialized) throw new Error('session_not_started')
|
|
175
|
+
if (message.type?.startsWith('harness.sync.')) {
|
|
176
|
+
if (!clientRPC || !resultPushConnection || message.connection_id !== resultPushConnection ||
|
|
177
|
+
!['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')
|
|
178
|
+
forward(raw.toString()); return
|
|
179
|
+
}
|
|
174
180
|
if (message.type === 'harness.composer.update') {
|
|
175
181
|
if (!clientRPC || raw.length > 100_000) throw new Error('invalid_composer_push')
|
|
176
182
|
forward(raw.toString())
|
|
@@ -210,6 +216,7 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
210
216
|
rpcRequests.set(event.request_id, event.connection_id)
|
|
211
217
|
}
|
|
212
218
|
if (event.type === 'session.created') {
|
|
219
|
+
if (clientRPC && event.harness_sync?.protocol === 'harness_sync_v1') resultPushConnection = event.harness_sync.connection_id
|
|
213
220
|
hintReporting=event.connection_hint_reporting===true
|
|
214
221
|
if (clientRPC && event.session?.config?.harness_control_transport !== 'client_rpc_v1') { fail('harness_rpc_backend_upgrade_required'); return }
|
|
215
222
|
if (mode === 'tts_only' && event.session?.config?.external_message_protocol !== 'harness_result_v2') { fail('harness_result_backend_upgrade_required'); return }
|
|
@@ -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
|
+
}
|
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.8'
|
|
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 : ''
|
|
@@ -48,7 +48,7 @@ export class DuetState {
|
|
|
48
48
|
this.suspended = false
|
|
49
49
|
this.idleSince = null
|
|
50
50
|
if (mode === 'off') this.pending.clear()
|
|
51
|
-
// Online
|
|
51
|
+
// Online notifications belong to the negotiated Harness stream (or legacy adapter).
|
|
52
52
|
if (mode === 'online') this.pending.clear()
|
|
53
53
|
await this.replaceConnection()
|
|
54
54
|
}
|