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.
@@ -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.6';
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.6');
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.6').then(({mountShortcutSettings}) => {
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.6').then(({mountMicrophoneSettings}) => {
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 = '暂时无法加载麦克风设置,请刷新重试。'; });
@@ -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.6'
3
- import { focusedSession } from './composer.mjs?v=0.1.6'
4
- import { sessionCreationPayload, workspaceIssue } from './workspaces.mjs?v=0.1.6'
5
- import { startComposerBridge } from './composer-bridge.mjs?v=0.1.6'
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()
@@ -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.6'
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
@@ -1,5 +1,5 @@
1
1
  /** Workspace readiness and browser-local session ordering shared by all voice paths. */
2
- import { orderSessionCatalog, readWorkspaceView } from '../shared/catalog.mjs'
2
+ import { orderSessionCatalog, readWorkspaceView, sessionLabel } from '../shared/catalog.mjs'
3
3
  import { focusedSession } from './composer.mjs'
4
4
 
5
5
  export function workspaceIssue(ctx) {
@@ -31,6 +31,7 @@ export function browserSessionCatalog(ctx, rows) {
31
31
  const archived = new Set(ctx.workspaces?.list?.getSnapshot().archivedSessionIds || [])
32
32
  return orderSessionCatalog(rows.filter(row => !archived.has(row.session_id)).map(row => ({
33
33
  ...row, active: row.session_id === active,
34
+ label: sessionLabel(row.label, row.session_id),
34
35
  updated_at: snapshot.byId?.[row.session_id]?.updatedAt ?? row.updated_at,
35
36
  })), readWorkspaceView())
36
37
  }
@@ -1,10 +1,13 @@
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
+ result_notification: 'shared/result-notification',
4
5
  connection_guidance: 'shared/connection-guidance',
5
6
  audio: 'client/audio', microphone: 'client/microphone', shortcuts: 'client/shortcuts',
6
7
  browser: 'client/browser', rpc: 'client/rpc', composer: 'client/composer',
7
8
  composer_bridge: 'client/composer-bridge',
9
+ harness_sync: 'client/harness-sync',
10
+ local_sync: 'client/local-sync',
8
11
  interactions: 'client/interactions', tutorial: 'client/tutorial',
9
12
  tutorial_adapter: 'client/tutorial-adapter', tutorial_request: 'client/tutorial-request',
10
13
  feedback: 'client/feedback', consent: 'client/consent',
@@ -11,7 +11,8 @@ import { DuetTrace } from './trace.mjs'
11
11
  import { FeedbackService } from './feedback-store.mjs'
12
12
  import { RemoteFeedback } from './feedback-files.mjs'
13
13
  import { PLUGIN_VERSION } from '../shared/state.mjs'
14
- import { buildSessionCatalog } from '../shared/catalog.mjs'
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)
@@ -945,7 +977,7 @@ export function apply(ctx, options = {}) {
945
977
  if (name) {
946
978
  await ctx.sessionController.rename({ sessionId: created.sessionId, title: name })
947
979
  }
948
- sendJson(res, 201, { session: { session_id: created.sessionId, label: name || created.sessionId, active: true } })
980
+ sendJson(res, 201, { session: { session_id: created.sessionId, label: sessionLabel(name, created.sessionId), active: true } })
949
981
  return
950
982
  }
951
983
 
@@ -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' && pathname === `${ROUTE}/api/results`) {
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
@@ -6,6 +6,8 @@ import { duetEnv } from './environment.mjs'
6
6
  import { EndpointDiscovery, connectEndpoint } from './endpoint-discovery.mjs'
7
7
  import {sessionMetadata} from './session-metadata.mjs'
8
8
  import {VOICE_PROTOCOL} from '../shared/identity.mjs'
9
+ import { broadcastText } from '../shared/result-notification.mjs'
10
+ import { sessionLabel } from '../shared/catalog.mjs'
9
11
  import { DEFAULT_DUET_URL, publicServiceAuthorization } from './service-defaults.mjs'
10
12
  export { DEFAULT_DUET_URL } from './service-defaults.mjs'
11
13
  const require = createRequire(import.meta.url)
@@ -34,8 +36,7 @@ export function duetConfig(env = process.env) {
34
36
  export function externalWithState(message, _state) {
35
37
  if (message.type !== 'external_message' || typeof message.text !== 'string') throw new Error('invalid_external_message')
36
38
  // Keep authoritative result metadata separate from result text and UI state.
37
- const text = message.text
38
- if (text.length > 8000) throw new Error('external_message_too_large')
39
+ const text = broadcastText(message.text)
39
40
  const source = message.source
40
41
  if (source !== undefined) {
41
42
  const limits = { session_id: 256, session_name: 512, job_id: 256, status: 16 }
@@ -45,7 +46,7 @@ export function externalWithState(message, _state) {
45
46
  !['completed', 'failed'].includes(source.status)) throw new Error('invalid_external_message_source')
46
47
  }
47
48
  return { type: 'external_message', message_id: message.message_id, text,
48
- ...(source === undefined ? {} : { source: { ...source } }) }
49
+ ...(source === undefined ? {} : { source: { ...source, session_name: sessionLabel(source.session_name, source.session_id) } }) }
49
50
  }
50
51
 
51
52
  export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, canUseVoice = () => true, discovery = new EndpointDiscovery(() => config)) {
@@ -56,7 +57,7 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
56
57
  if (!['ws:', 'wss:'].includes(url.protocol) || url.username || url.password || url.hash) throw new Error('invalid_voice_endpoint')
57
58
  }
58
59
  const { WebSocket, WebSocketServer } = require('ws')
59
- const server = new WebSocketServer({ noServer: true, maxPayload: 1_000_000,
60
+ const server = new WebSocketServer({ noServer: true, maxPayload: 2_100_000,
60
61
  handleProtocols: protocols => protocols.has(VOICE_PROTOCOL) ? VOICE_PROTOCOL : false })
61
62
  const connections = new Map()
62
63
  const stop = ctx.webServer.registerUpgrade({
@@ -116,6 +117,7 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
116
117
  const pending = []
117
118
  const startup = setTimeout(() => fail('voice_start_timeout'), 20000)
118
119
  let hintReporting=false,hintReported=false
120
+ let resultPushConnection = null
119
121
  const sendUpstream = (data, binary) => {
120
122
  if (!binary) {
121
123
  const message = JSON.parse(data.toString())
@@ -170,6 +172,11 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
170
172
  return
171
173
  }
172
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
+ }
173
180
  if (message.type === 'harness.composer.update') {
174
181
  if (!clientRPC || raw.length > 100_000) throw new Error('invalid_composer_push')
175
182
  forward(raw.toString())
@@ -209,6 +216,7 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
209
216
  rpcRequests.set(event.request_id, event.connection_id)
210
217
  }
211
218
  if (event.type === 'session.created') {
219
+ if (clientRPC && event.harness_sync?.protocol === 'harness_sync_v1') resultPushConnection = event.harness_sync.connection_id
212
220
  hintReporting=event.connection_hint_reporting===true
213
221
  if (clientRPC && event.session?.config?.harness_control_transport !== 'client_rpc_v1') { fail('harness_rpc_backend_upgrade_required'); return }
214
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
+ }
@@ -1,13 +1,12 @@
1
1
  /** Public trial connection details distributed with the plugin. */
2
- export const DEFAULT_DUET_URL = 'ws://duet-router.1781574661016173.ap-southeast-1.pai-eas.aliyuncs.com/ws?protocol=realtime_v2'
2
+ export const DEFAULT_DUET_URL = 'wss://duet-router-acc.router.dsh-duet.com/ws?protocol=realtime_v2'
3
3
  export const PUBLIC_TRIAL_AUTHORIZATION = "ZTZhZWI4YzA3ODcyZWI2NzZhZjU4MDk3NGE3NGUxODQ2MjgxYWVjYQ=="
4
4
 
5
- export const PUBLIC_TRIAL_GATEWAY_URL = 'ws://duet-router-acc.gw-bmmaj5gve68z3gw34o.ap-southeast-1.pai-eas.aliyuncs.com/ws?protocol=realtime_v2'
6
5
  export const PUBLIC_TRIAL_ACCELERATOR_URL = 'ws://47.117.104.188/ws?protocol=realtime_v2'
7
6
 
8
7
  export function isPublicTrialEndpoint(value) {
9
8
  const url = new URL(value)
10
- return [DEFAULT_DUET_URL, PUBLIC_TRIAL_GATEWAY_URL, PUBLIC_TRIAL_ACCELERATOR_URL].some(value => {
9
+ return [DEFAULT_DUET_URL, PUBLIC_TRIAL_ACCELERATOR_URL].some(value => {
11
10
  const expected = new URL(value)
12
11
  return url.origin === expected.origin && url.pathname === expected.pathname && !url.username && !url.password
13
12
  })
@@ -0,0 +1,25 @@
1
+ /** Retired addresses are migration inputs only, never connection/auth targets. */
2
+ import { writeFileSync, renameSync, unlinkSync } from 'node:fs'
3
+ import { randomUUID } from 'node:crypto'
4
+ import { DEFAULT_DUET_URL } from './service-defaults.mjs'
5
+
6
+ export function migrateRetiredSettings(data, path) {
7
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return data
8
+ let url
9
+ try { url = new URL(data.backend_url) } catch { return data }
10
+ const retired = [
11
+ 'duet-router.1781574661016173.ap-southeast-1.pai-eas.aliyuncs.com',
12
+ 'duet-router-acc.gw-bmmaj5gve68z3gw34o.ap-southeast-1.pai-eas.aliyuncs.com',
13
+ ]
14
+ if (!retired.includes(url.hostname) || !['ws:', 'wss:', 'http:', 'https:'].includes(url.protocol)
15
+ || url.port || url.username || url.password || url.hash || !['/', '/ws'].includes(url.pathname)
16
+ || [...url.searchParams].some(([k,v]) => k !== 'protocol' || v !== 'realtime_v2')) return data
17
+ const next = { backend_url: DEFAULT_DUET_URL }
18
+ const temp = `${path}.${randomUUID()}.tmp`
19
+ try {
20
+ writeFileSync(temp, JSON.stringify(next) + '\n', { mode: 0o600, flag: 'wx' })
21
+ renameSync(temp, path)
22
+ } catch { /* Read-only storage must not prevent using the current default. */ }
23
+ finally { try { unlinkSync(temp) } catch {} }
24
+ return next
25
+ }
@@ -6,6 +6,7 @@ import { defaultStateFile } from './storage-paths.mjs'
6
6
  import { randomUUID } from 'node:crypto'
7
7
  import { duetEnv } from './environment.mjs'
8
8
  import { publicServiceAuthorization, isPublicTrialEndpoint } from './service-defaults.mjs'
9
+ import { migrateRetiredSettings } from './settings-migration.mjs'
9
10
 
10
11
  export function normalizeBackendURL(value) {
11
12
  if (typeof value !== 'string' || value.length > 2048) throw new Error('invalid_backend_url')
@@ -38,7 +39,7 @@ export class DuetSettings {
38
39
  this.writing = false
39
40
  try {
40
41
  const data = JSON.parse(readFileSync(this.path, 'utf8'))
41
- this.saved = this.validate(data)
42
+ this.saved = this.validate(migrateRetiredSettings(data, this.path))
42
43
  } catch (error) { if (error.code !== 'ENOENT') throw new Error('invalid_voice_settings_file') }
43
44
  }
44
45
 
@@ -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
+ }
@@ -1,6 +1,11 @@
1
1
  /** Mirror DSH workspace order, never the global activity-sorted search list. */
2
2
  export const WORKSPACE_VIEW_KEY = 'dsh.workspace.view.v5'
3
3
 
4
+ export function sessionLabel(name, id) {
5
+ const text = typeof name === 'string' ? name.trim() : ''
6
+ return text && text !== id ? text : '未命名会话'
7
+ }
8
+
4
9
  export function readWorkspaceView() {
5
10
  try { return JSON.parse(globalThis.localStorage?.getItem(WORKSPACE_VIEW_KEY) || '{}') || {} }
6
11
  catch { return {} }
@@ -54,7 +59,7 @@ export function buildSessionCatalog(items, {workspaces = [], archivedIds = [], a
54
59
  const item = byId.get(id)
55
60
  if (!item) return
56
61
  byId.delete(id)
57
- result.push({session_id:id, label:item.projections?.values?.title || id,
62
+ result.push({session_id:id, label:sessionLabel(item.projections?.values?.title, id),
58
63
  active:id === activeId, running:item.running, updated_at:item.updatedAt,
59
64
  cwd:item.cwd || '', workspace_id:workspaceId, archived:false,
60
65
  blank:!!item.blank, origin:item.origin})
@@ -0,0 +1,19 @@
1
+ import { sessionLabel } from './catalog.mjs'
2
+
3
+ export const MAX_RESULT_TEXT_LENGTH = 8000
4
+ export const LONG_RESULT_NOTICE = '这条任务消息内容较长,请在 DSH 会话中查看完整内容。'
5
+
6
+ /** Never truncate code into a misleading summary. The full result stays in DSH. */
7
+ export function broadcastText(text) {
8
+ if (typeof text !== 'string') throw Error('invalid_external_message')
9
+ return text.length > MAX_RESULT_TEXT_LENGTH ? LONG_RESULT_NOTICE : text
10
+ }
11
+
12
+ export function resultNotification(job, name) {
13
+ return {
14
+ type: 'external_message', message_id: `harness_${job.id}`,
15
+ source: { session_id: job.session_id, session_name: sessionLabel(name, job.session_id),
16
+ job_id: job.id, status: job.status === 'succeeded' ? 'completed' : 'failed' },
17
+ text: broadcastText((job.status === 'succeeded' ? job.result : (job.error || job.result)) || '未返回结果。'),
18
+ }
19
+ }