dsh-duet 0.1.7 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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.7'
2
+ VOICE_PROTOCOL, IDENTITY_PROTOCOL_PREFIX, validIdentityToken } from '../shared/identity.mjs?v=0.1.9'
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 WeakMap()
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
- return { id: value.key, session_id: value.sessionId, created_at: firstSeen.get(value),
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
- return async (request, signal) => {
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: pending().filter(v => ['question', 'plan-review', 'approval'].includes(v.kind)).map(publicValue) }
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
+ }
@@ -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 = 256_000
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 query = request.params ? '?' + new URLSearchParams(request.params) : ''
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
- if (new TextEncoder().encode(text).length > MAX_BYTES - 512) throw new Error('harness_rpc_response_too_large')
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)
@@ -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.7';
155
+ import { identityFetch } from '/duet/assets/client/identity.mjs?v=0.1.9';
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.7');
366
+ const {requestTutorial} = await import('/duet/assets/client/tutorial-request.mjs?v=0.1.9');
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.7').then(({mountShortcutSettings}) => {
375
+ import('/duet/assets/client/shortcuts.mjs?v=0.1.9').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.7').then(({mountMicrophoneSettings}) => {
379
+ import('/duet/assets/client/microphone.mjs?v=0.1.9').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 = '暂时无法加载麦克风设置,请刷新重试。'; });
@@ -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('duplex-control/voice/ws', base)
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.7'
3
- import { focusedSession } from './composer.mjs?v=0.1.7'
4
- import { sessionCreationPayload, workspaceIssue } from './workspaces.mjs?v=0.1.7'
5
- import { startComposerBridge } from './composer-bridge.mjs?v=0.1.7'
2
+ import { PLUGIN_VERSION } from '../shared/state.mjs?v=0.1.9'
3
+ import { focusedSession } from './composer.mjs?v=0.1.9'
4
+ import { sessionCreationPayload, workspaceIssue } from './workspaces.mjs?v=0.1.9'
5
+ import { startComposerBridge } from './composer-bridge.mjs?v=0.1.9'
6
6
  export function tutorialAdapter(ctx, state, audio, pollReady, startBridge = startComposerBridge) {
7
7
  let narration
8
8
  const completed = new Map()
@@ -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.7'
2
+ import {consumeTutorialRequest} from './tutorial-request.mjs?v=0.1.9'
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
@@ -1,11 +1,14 @@
1
1
  /** Explicit public asset inventory. Host code and configuration are never served. */
2
2
  const modules = {
3
3
  state: 'shared/state', catalog: 'shared/catalog',
4
+ diagnostics: 'shared/diagnostics',
4
5
  result_notification: 'shared/result-notification',
5
6
  connection_guidance: 'shared/connection-guidance',
6
7
  audio: 'client/audio', microphone: 'client/microphone', shortcuts: 'client/shortcuts',
7
8
  browser: 'client/browser', rpc: 'client/rpc', composer: 'client/composer',
8
9
  composer_bridge: 'client/composer-bridge',
10
+ harness_sync: 'client/harness-sync',
11
+ local_sync: 'client/local-sync',
9
12
  interactions: 'client/interactions', tutorial: 'client/tutorial',
10
13
  tutorial_adapter: 'client/tutorial-adapter', tutorial_request: 'client/tutorial-request',
11
14
  feedback: 'client/feedback', consent: 'client/consent',
@@ -0,0 +1,45 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { diagnosticPayload, DIAGNOSTICS_PROTOCOL } from '../shared/diagnostics.mjs'
3
+
4
+ /** Bounded, asynchronous batches. Telemetry failure never closes a voice socket. */
5
+ export class ConnectionDiagnostics {
6
+ constructor(metadata, fetcher = fetch) {
7
+ this.metadata = metadata; this.fetcher = fetcher
8
+ this.pending = []; this.seen = new Set(); this.count = 0; this.attempts = 0
9
+ }
10
+ add(value) {
11
+ const row = diagnosticPayload({...value, ...this.metadata, event_id: value.event_id || randomUUID()})
12
+ if (!row || this.seen.has(row.event_id) || this.count >= 96) return
13
+ this.seen.add(row.event_id); row.sequence=this.count++; this.pending.push(row)
14
+ this.schedule()
15
+ }
16
+ offer(offer, config, endpoint) {
17
+ if (this.target || offer?.protocol !== DIAGNOSTICS_PROTOCOL || typeof offer.ticket !== 'string' || offer.ticket.length > 4096) return
18
+ const url = new URL(endpoint); url.protocol = url.protocol === 'wss:' ? 'https:' : 'http:'
19
+ url.pathname = '/client-diagnostics'; url.search = ''; url.hash = ''
20
+ this.target = url.href; this.ticket = offer.ticket; this.authorization = config.authorization
21
+ this.schedule()
22
+ }
23
+ schedule(delay = 150) {
24
+ if (!this.target || !this.pending.length || this.timer || this.busy || this.attempts >= 120) return
25
+ this.timer = setTimeout(() => { this.timer = null; void this.flush() }, delay); this.timer.unref?.()
26
+ }
27
+ async flush() {
28
+ if (this.busy || !this.target || !this.pending.length) return
29
+ this.busy = true; this.attempts++
30
+ const rows = this.pending.slice(0, 16)
31
+ let failed = false
32
+ try {
33
+ const response = await this.fetcher(this.target, { method: 'POST', redirect: 'error',
34
+ headers: {'Content-Type':'application/json', ...(this.authorization ? {Authorization:this.authorization} : {})},
35
+ body: JSON.stringify({protocol:DIAGNOSTICS_PROTOCOL, ticket:this.ticket, events:rows}),
36
+ signal: AbortSignal.timeout(3000) })
37
+ if (!response.ok) throw Error('diagnostic_upload_failed')
38
+ await response.body?.cancel()
39
+ this.pending.splice(0, rows.length); this.failures = 0
40
+ } catch { failed = true; this.failures = (this.failures || 0) + 1 }
41
+ finally { this.busy = false }
42
+ // At most three retries in a row, even if the server disappeared at close.
43
+ if (!failed || this.failures < 3) this.schedule(failed ? 1000 : 150)
44
+ }
45
+ }
@@ -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, taskErrorText } 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)
@@ -359,10 +367,12 @@ export function apply(ctx, options = {}) {
359
367
  }, hostAbort.signal)
360
368
  } catch (error) {
361
369
  job.status = 'failed'
362
- job.error = error instanceof Error ? error.message : String(error)
370
+ job.error = taskErrorText(error)
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)
@@ -410,7 +420,7 @@ export function apply(ctx, options = {}) {
410
420
  job.error = 'Harness turn was aborted, not completed'
411
421
  } else if (event.data.reason?.kind === 'error') {
412
422
  job.status = 'failed'
413
- job.error = String(event.data.reason.error || 'Harness turn failed')
423
+ job.error = taskErrorText(event.data.reason.error)
414
424
  } else if (!job.result) {
415
425
  job.status = 'failed'
416
426
  job.error = `Harness turn ended without a final text response (${event.data.reason?.kind || 'unknown'})`
@@ -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)
@@ -508,10 +540,13 @@ export function apply(ctx, options = {}) {
508
540
  return
509
541
  }
510
542
  if (req.method === 'POST' && pathname === `${ROUTE}/api/voice/diagnostic`) {
511
- if (!settingsWriteAllowed(req)) { sendError(res, 403, 'same-origin diagnostic request required'); return }
543
+ const rejection = ctx.connection.requestRejection(req)
544
+ if (rejection) { sendError(res, rejection, 'DSH connection required'); return }
545
+ if (!identityWriteAllowed(req)) { sendError(res, 403, 'same-origin diagnostic request required'); return }
512
546
  const body = await readJson(req)
513
547
  if (JSON.stringify(body).length > 24000) { sendError(res, 413, 'diagnostic too large'); return }
514
548
  audit.event('client.diagnostic', body)
549
+ try { duetProxy?.reportDiagnostic?.(req, body) } catch { /* Best effort only. */ }
515
550
  sendJson(res, 200, { ok: true, logging: audit.snapshot() }); return
516
551
  }
517
552
  if (req.method === 'GET' && pathname === `${ROUTE}/api/voice/service-info`) {
@@ -1069,9 +1104,19 @@ export function apply(ctx, options = {}) {
1069
1104
  sendJson(res, 200, { jobs: values })
1070
1105
  return
1071
1106
  }
1072
- if (req.method === 'GET' && pathname === `${ROUTE}/api/results`) {
1107
+ if (req.method === 'GET' && [ `${ROUTE}/api/results`, `${ROUTE}/api/results/wait` ].includes(pathname)) {
1108
+ if (pathname.endsWith('/wait')) {
1109
+ const rejection = ctx.connection.requestRejection(req)
1110
+ if (rejection) { sendError(res, rejection, '请先打开并登录 DSH 主页面'); return }
1111
+ }
1073
1112
  const url = new URL(req.url || '/', 'http://localhost')
1074
1113
  const after = Math.max(0, Number.parseInt(url.searchParams.get('after') || '0', 10) || 0)
1114
+ const epoch = url.searchParams.get('epoch')
1115
+ if (pathname.endsWith('/wait') && after >= completionSequence && (!epoch || epoch === focusEpoch)) {
1116
+ if (resultFeed.waiters.size >= 64) { sendError(res, 429, 'result_feed_capacity'); return }
1117
+ await resultFeed.wait(req, res)
1118
+ if (res.destroyed || hostAbort.signal.aborted) return
1119
+ }
1075
1120
  const limit = Math.max(1, Math.min(200, Number.parseInt(url.searchParams.get('limit') || '100', 10) || 100))
1076
1121
  const completed = jobOrder
1077
1122
  .map(id => jobs.get(id))
@@ -1083,6 +1128,7 @@ export function apply(ctx, options = {}) {
1083
1128
  results: selected.map(publicJob),
1084
1129
  next_cursor: nextCursor,
1085
1130
  current_cursor: completionSequence,
1131
+ epoch: focusEpoch,
1086
1132
  has_more: completed.length > selected.length,
1087
1133
  })
1088
1134
  return