dsh-duet 0.1.6 → 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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-duet",
3
- "version": "0.1.6",
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
  },
@@ -1,4 +1,4 @@
1
- import { microphoneConstraints } from './microphone.mjs?v=0.1.6'
1
+ import { microphoneConstraints } from './microphone.mjs?v=0.1.8'
2
2
 
3
3
  /** Browser-owned microphone and PCM playback. No microphone is requested in tts_only. */
4
4
  export class DuetAudio {
@@ -1,20 +1,24 @@
1
- import { DuetState, PLUGIN_VERSION } from '../shared/state.mjs?v=0.1.6'
2
- import { DuetAudio } from './audio.mjs?v=0.1.6'
3
- import { HarnessRPCExecutor, rpcNavigationSession } from './rpc.mjs?v=0.1.6'
4
- import { composerAccess, observeComposer, focusedSession, openLocalSession } from './composer.mjs?v=0.1.6'
5
- import { startComposerBridge } from './composer-bridge.mjs?v=0.1.6'
6
- import { mountTutorial } from './tutorial.mjs?v=0.1.6'
7
- import { tutorialAdapter } from './tutorial-adapter.mjs?v=0.1.6'
8
- import { mountRating } from './feedback.mjs?v=0.1.6'
9
- import { createAudioUploadConsent } from './consent.mjs?v=0.1.6'
10
- import { bindDuetShortcuts } from './shortcuts.mjs?v=0.1.6'
11
- import { nativeInteractions } from './interactions.mjs?v=0.1.6'
12
- import { mountConnectionHint } from './connection-hint.mjs?v=0.1.6'
13
- import { mountControlsLayout } from './controls-layout.mjs?v=0.1.6'
14
- import { mountNotice } from './notice.mjs?v=0.1.6'
15
- import { workspaceIssue, requireWorkspace, browserSessionCatalog, sessionCreationPayload } from './workspaces.mjs?v=0.1.6'
16
- import { voiceSocketUrl, bindSettingsLink } from './transport.mjs?v=0.1.6'
17
- import { identityFetch, identityVoiceProtocols } from './identity.mjs?v=0.1.6'
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'
18
22
 
19
23
  export function mountDuet(ctx) {
20
24
  const pageId = crypto.randomUUID()
@@ -24,6 +28,8 @@ export function mountDuet(ctx) {
24
28
  let nextPollAt = 0, pollController, pollWakePending = false, pollFailureSince = null, pollFailures = 0, pollGeneration = -1
25
29
  const notices = mountNotice(() => controls)
26
30
  const labels = new Map()
31
+ const resultResume = {}
32
+ let localSync
27
33
  let clientTraceId = null, diagnosticCount = 0
28
34
  let connectionGuidance = null, reportHintShown = null
29
35
  let tutorial, teaching, ratingPanel, connectionHint, stopControlsLayout, stopSettings
@@ -86,12 +92,20 @@ export function mountDuet(ctx) {
86
92
  if (ws.bufferedAmount > 1_000_000) { receive({ type: 'error', code: 'voice_backpressure' }); return }
87
93
  ws.send(message instanceof ArrayBuffer ? message : JSON.stringify(message))
88
94
  }
89
- const composer = composerAccess(ctx, id => labels.get(id) || id)
95
+ const composer = composerAccess(ctx, id => sessionLabel(labels.get(id), id))
90
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())
91
104
  const rpc = new HarnessRPCExecutor(send, fetch, report, async (request, signal) =>
92
105
  (await interactions(request, signal)) ?? composer.execute(request, signal), rows =>
93
106
  browserSessionCatalog(ctx, rows).map(row => ({ ...row, active: row.session_id === focusedSession(ctx) })), {
94
107
  id: connectionTraceId,
108
+ syncSupported: () => localSync?.active && interactions.supportsSync,
95
109
  creationPayload: payload => sessionCreationPayload(ctx, payload),
96
110
  completed: async (request, body, signal) => {
97
111
  const id = rpcNavigationSession(request, body)
@@ -99,15 +113,23 @@ export function mountDuet(ctx) {
99
113
  },
100
114
  })
101
115
  const connection = {
116
+ resultPush,
102
117
  feedbackTicket: null,
103
118
  send,
104
119
  sendState: state => { if (state) send({ type: 'harness.state', state }) },
105
120
  playing: () => audio.playing(),
106
121
  async close() {
107
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
+ }
108
128
  closed = true
109
129
  clearTimeout(startupTimer)
110
130
  opening.abort()
131
+ resultPush.close()
132
+ stopInteractions?.()
111
133
  stopComposer?.()
112
134
  stopBridge?.(); stopBridge = null
113
135
  rpc.close()
@@ -132,7 +154,7 @@ export function mountDuet(ctx) {
132
154
  if(!identity.ok)throw Error('voice_config_unavailable')
133
155
  requireWorkspace(ctx)
134
156
  if(closed)return
135
- if (mode === 'online') stopBridge = startComposerBridge(ctx, connectionTraceId)
157
+ if (mode === 'online') stopBridge = startComposerBridge(ctx, connectionTraceId, fetch, localSync)
136
158
  report({ event: 'browser.connection_start', page_binding: 'connection_owner_v1' })
137
159
  ws = new WebSocket(voiceSocketUrl({ mode, plugin_version: PLUGIN_VERSION, client_trace_id: connectionTraceId, page_id: pageId }), identityVoiceProtocols())
138
160
  ws.onopen = () => {
@@ -144,6 +166,7 @@ export function mountDuet(ctx) {
144
166
  let message
145
167
  try {
146
168
  message = JSON.parse(event.data)
169
+ if (resultPush.event(message)) return
147
170
  if (message.type === 'harness.rpc.request') {
148
171
  if (mode !== 'online') throw new Error('harness_rpc_requires_online')
149
172
  await rpc.execute(message)
@@ -156,6 +179,8 @@ export function mountDuet(ctx) {
156
179
  compatibility: message.error?.compatibility, policy: message.error?.policy }); return
157
180
  }
158
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)
159
184
  connectionGuidance=message.connection_route?.connection_hint
160
185
  reportHintShown=hint=>{
161
186
  report({event:'browser.connection_hint_shown',connection_hint:hint})
@@ -196,6 +221,8 @@ export function mountDuet(ctx) {
196
221
  }
197
222
  }
198
223
  ws.onclose = event => {
224
+ resultPush.close()
225
+ stopInteractions?.()
199
226
  stopComposer?.()
200
227
  stopBridge?.(); stopBridge = null
201
228
  report({ event: 'browser.ws_closed', code: event.code, reason: event.reason, was_clean: event.wasClean })
@@ -316,7 +343,15 @@ export function mountDuet(ctx) {
316
343
  pollController = controller
317
344
  const timeout = setTimeout(() => controller.abort(), 5000)
318
345
  try {
319
- const [catalog, completed, health] = await Promise.all([api('sessions',controller.signal), api(`results?after=${cursor ?? 0}&limit=100`,controller.signal), api('health',controller.signal)])
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)
320
355
  if (disposed) return
321
356
  catalog.sessions = browserSessionCatalog(ctx, catalog.sessions)
322
357
  const issue = workspaceIssue(ctx)
@@ -327,21 +362,17 @@ export function mountDuet(ctx) {
327
362
  const id = focusedSession(ctx)
328
363
  const scope = id ? ctx.sessions.scope(id) : undefined
329
364
  if (scope) {
330
- try { composer = { session_name: labels.get(id) || id, text: ctx.conversation.input.for(scope).state.getSnapshot().draft } } catch { /* Session input is still mounting; do not invent an empty draft. */ }
365
+ try { composer = { session_name: sessionLabel(labels.get(id), id), text: ctx.conversation.input.for(scope).state.getSnapshot().draft } } catch { /* Session input is still mounting; do not invent an empty draft. */ }
331
366
  }
332
367
  state.update({
333
368
  hidden: document.visibilityState !== 'visible',
334
369
  running: catalog.sessions.some(s => s.running),
335
370
  state: { focused_session_id: id || null, ...(composer ? { composer_state: composer } : {}), sessions: catalog.sessions.map(s => ({ session_id: s.session_id, session_name: s.label, running: s.running })) },
336
- results: bootstrap ? [] : completed.results.map(job => ({
337
- type: 'external_message', message_id: `harness_${job.id}`,
338
- source: { session_id: job.session_id, session_name: labels.get(job.session_id) || job.session_id,
339
- job_id: job.id, status: job.status === 'succeeded' ? 'completed' : 'failed' },
340
- text: (job.status === 'succeeded' ? job.result : (job.error || job.result)) || '未返回结果。',
341
- })),
371
+ results: bootstrap ? [] : completed.results.map(job => resultNotification(job, labels.get(job.session_id))),
342
372
  })
343
373
  resultEpoch = health.focus_epoch
344
374
  cursor = bootstrap ? completed.current_cursor : completed.next_cursor
375
+ state.connection?.resultPush?.changed()
345
376
  if (pollFailures >= 3 && state.mode !== 'off') notice('会话同步已恢复。')
346
377
  pollFailureSince = null; pollFailures = 0
347
378
  } catch (error) {
@@ -357,10 +388,19 @@ export function mountDuet(ctx) {
357
388
  nextPollAt = pollWakePending ? 0 : startedAt + (state.mode !== 'off' || tutorial?.active ? 1000 : document.hidden ? 15000 : 5000)
358
389
  }
359
390
  }
360
- const timer = setInterval(() => { if (Date.now() >= nextPollAt) void poll(); state.tick() }, 1000)
361
- 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() }
362
393
  const unwatchSessions = ctx.sessions.list.subscribe?.(wakePoll)
363
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()
364
404
  const progress = setInterval(() => { if (state.connection) audio.progress(state.connection.send) }, 200)
365
405
  const visibility = () => { state.hidden = document.visibilityState !== 'visible'; state.tick(); void poll() }
366
406
  document.addEventListener('visibilitychange', visibility)
@@ -373,7 +413,7 @@ export function mountDuet(ctx) {
373
413
  if (Date.now() > deadline) throw Error('会话结果同步尚未就绪,请稍后重试教学')
374
414
  await poll(); await new Promise(resolve => setTimeout(resolve, 150))
375
415
  }
376
- })
416
+ }, (context, id) => startComposerBridge(context, id, fetch, localSync))
377
417
  const mountTeaching = () => {
378
418
  if (!tutorial && controls) tutorial = mountTutorial({ controls, adapter: teaching })
379
419
  }
@@ -384,6 +424,9 @@ export function mountDuet(ctx) {
384
424
  disposed = true
385
425
  pollController?.abort()
386
426
  unwatchSessions?.(); unwatchWorkspaces?.()
427
+ localSync.close()
428
+ window.removeEventListener('storage', viewChanged)
429
+ document.removeEventListener('click', viewChanged)
387
430
  notices.dispose()
388
431
  stopShortcuts()
389
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.6'
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,4 +1,5 @@
1
1
  /** Browser-owned drafts: bounded snapshots and explicit overwrite/CAS edit policies. */
2
+ import { sessionLabel } from '../shared/catalog.mjs'
2
3
  const fail = code => { const error = new Error(code); error.code = code; throw error }
3
4
  const hash = async text => [...new Uint8Array(await crypto.subtle.digest('SHA-256',
4
5
  new TextEncoder().encode(text)))].map(v => v.toString(16).padStart(2, '0')).join('')
@@ -26,7 +27,7 @@ export async function openLocalSession(ctx, id, signal) {
26
27
  }
27
28
  }
28
29
 
29
- export function composerAccess(ctx, label = id => id) {
30
+ export function composerAccess(ctx, label = () => '') {
30
31
  const focused = () => focusedSession(ctx)
31
32
  const inputFor = id => {
32
33
  const scope = id && ctx.sessions.scope(id)
@@ -40,7 +41,7 @@ export function composerAccess(ctx, label = id => id) {
40
41
  const digest = await hash(before.draft)
41
42
  const live = input.state.getSnapshot()
42
43
  if (stable && (live.draft !== before.draft || live.draftRev !== before.draftRev || live.phase !== before.phase)) fail('draft_conflict')
43
- return { session_id: id, session_name: label(id), text: before.draft,
44
+ return { session_id: id, session_name: sessionLabel(label(id), id), text: before.draft,
44
45
  revision: before.draftRev, hash: digest, phase: before.phase }
45
46
  }
46
47
  const read = async () => {
@@ -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.6'
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 button = controls.querySelector('[data-voice=mic]') || controls
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
- /** Follow the host's available sidebar width, without depending on DSH classes. */
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 compact = parent.getBoundingClientRect().width < 160
6
- if (controls.dataset.compact === String(compact)) return
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
- controls.style.flexDirection = compact ? 'column' : 'row'
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 ? '6px 0' : '6px 8px'
11
- const entry = controls.querySelector('#dsh-duet-entry')
12
- if (entry) entry.style.display = compact ? 'none' : ''
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(parent)
126
+ for (const node of ancestors) observer.observe(node)
16
127
  update()
17
- return () => observer.disconnect()
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
  }
@@ -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.6').then(module => {
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?.() }
@@ -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.6'
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
+ }
@@ -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.6'
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) {