dsh-duet 0.1.5 → 0.1.7

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.5",
3
+ "version": "0.1.7",
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",
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",
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.5'
1
+ import { microphoneConstraints } from './microphone.mjs?v=0.1.7'
2
2
 
3
3
  /** Browser-owned microphone and PCM playback. No microphone is requested in tts_only. */
4
4
  export class DuetAudio {
@@ -1,19 +1,22 @@
1
- import { DuetState, PLUGIN_VERSION } from '../shared/state.mjs?v=0.1.5'
2
- import { DuetAudio } from './audio.mjs?v=0.1.5'
3
- import { HarnessRPCExecutor } from './rpc.mjs?v=0.1.5'
4
- import { composerAccess, observeComposer, focusedSession, openLocalSession } from './composer.mjs?v=0.1.5'
5
- import { startComposerBridge } from './composer-bridge.mjs?v=0.1.5'
6
- import { mountTutorial } from './tutorial.mjs?v=0.1.5'
7
- import { tutorialAdapter } from './tutorial-adapter.mjs?v=0.1.5'
8
- import { mountRating } from './feedback.mjs?v=0.1.5'
9
- import { createAudioUploadConsent } from './consent.mjs?v=0.1.5'
10
- import { bindDuetShortcuts } from './shortcuts.mjs?v=0.1.5'
11
- import { nativeInteractions } from './interactions.mjs?v=0.1.5'
12
- import { mountConnectionHint } from './connection-hint.mjs?v=0.1.5'
13
- import { mountControlsLayout } from './controls-layout.mjs?v=0.1.5'
14
- import { mountNotice } from './notice.mjs?v=0.1.5'
15
- import { workspaceIssue, requireWorkspace, browserSessionCatalog } from './workspaces.mjs?v=0.1.5'
16
- import { voiceSocketUrl, bindSettingsLink } from './transport.mjs?v=0.1.5'
1
+ import { DuetState, PLUGIN_VERSION } from '../shared/state.mjs?v=0.1.7'
2
+ import { DuetAudio } from './audio.mjs?v=0.1.7'
3
+ import { HarnessRPCExecutor, rpcNavigationSession } from './rpc.mjs?v=0.1.7'
4
+ import { composerAccess, observeComposer, focusedSession, openLocalSession } from './composer.mjs?v=0.1.7'
5
+ import { startComposerBridge } from './composer-bridge.mjs?v=0.1.7'
6
+ import { mountTutorial } from './tutorial.mjs?v=0.1.7'
7
+ import { tutorialAdapter } from './tutorial-adapter.mjs?v=0.1.7'
8
+ import { mountRating } from './feedback.mjs?v=0.1.7'
9
+ import { createAudioUploadConsent } from './consent.mjs?v=0.1.7'
10
+ import { bindDuetShortcuts } from './shortcuts.mjs?v=0.1.7'
11
+ import { nativeInteractions } from './interactions.mjs?v=0.1.7'
12
+ import { mountConnectionHint } from './connection-hint.mjs?v=0.1.7'
13
+ import { mountControlsLayout } from './controls-layout.mjs?v=0.1.7'
14
+ import { mountNotice } from './notice.mjs?v=0.1.7'
15
+ import { workspaceIssue, requireWorkspace, browserSessionCatalog, sessionCreationPayload } from './workspaces.mjs?v=0.1.7'
16
+ import { voiceSocketUrl, bindSettingsLink } from './transport.mjs?v=0.1.7'
17
+ import { identityFetch, identityVoiceProtocols } from './identity.mjs?v=0.1.7'
18
+ import { sessionLabel } from '../shared/catalog.mjs?v=0.1.7'
19
+ import { resultNotification } from '../shared/result-notification.mjs?v=0.1.7'
17
20
 
18
21
  export function mountDuet(ctx) {
19
22
  const pageId = crypto.randomUUID()
@@ -85,15 +88,15 @@ export function mountDuet(ctx) {
85
88
  if (ws.bufferedAmount > 1_000_000) { receive({ type: 'error', code: 'voice_backpressure' }); return }
86
89
  ws.send(message instanceof ArrayBuffer ? message : JSON.stringify(message))
87
90
  }
88
- const composer = composerAccess(ctx, id => labels.get(id) || id)
91
+ const composer = composerAccess(ctx, id => sessionLabel(labels.get(id), id))
89
92
  const interactions = nativeInteractions(ctx)
90
93
  const rpc = new HarnessRPCExecutor(send, fetch, report, async (request, signal) =>
91
94
  (await interactions(request, signal)) ?? composer.execute(request, signal), rows =>
92
95
  browserSessionCatalog(ctx, rows).map(row => ({ ...row, active: row.session_id === focusedSession(ctx) })), {
93
96
  id: connectionTraceId,
97
+ creationPayload: payload => sessionCreationPayload(ctx, payload),
94
98
  completed: async (request, body, signal) => {
95
- const id = request.path.endsWith('/activate') ? body.active_session_id
96
- : request.path.endsWith('/fork') ? body.session?.session_id : null
99
+ const id = rpcNavigationSession(request, body)
97
100
  if (id) await openLocalSession(ctx, id, signal)
98
101
  },
99
102
  })
@@ -123,17 +126,17 @@ export function mountDuet(ctx) {
123
126
  }
124
127
  const open = async () => {
125
128
  if (closed) return
126
- // Establish/renew the host-signed anonymous cookie before the WS handshake.
129
+ // Refresh Desktop-compatible feedback before the WS handshake.
127
130
  const configTimer = setTimeout(() => opening.abort(Error('voice_start_timeout')), 10000)
128
131
  let identity
129
- try { identity = await fetch('/duplex-control/api/voice/config', {credentials:'same-origin',cache:'no-store',signal:opening.signal}) }
132
+ try { identity = await identityFetch('/duplex-control/api/voice/config', {credentials:'same-origin',cache:'no-store',signal:opening.signal}) }
130
133
  finally { clearTimeout(configTimer) }
131
134
  if(!identity.ok)throw Error('voice_config_unavailable')
132
135
  requireWorkspace(ctx)
133
136
  if(closed)return
134
137
  if (mode === 'online') stopBridge = startComposerBridge(ctx, connectionTraceId)
135
138
  report({ event: 'browser.connection_start', page_binding: 'connection_owner_v1' })
136
- ws = new WebSocket(voiceSocketUrl({ mode, plugin_version: PLUGIN_VERSION, client_trace_id: connectionTraceId, page_id: pageId }))
139
+ ws = new WebSocket(voiceSocketUrl({ mode, plugin_version: PLUGIN_VERSION, client_trace_id: connectionTraceId, page_id: pageId }), identityVoiceProtocols())
137
140
  ws.onopen = () => {
138
141
  send({ type: 'session.update' })
139
142
  if (mode === 'online') stopComposer = observeComposer(ctx, composer, send)
@@ -302,7 +305,8 @@ export function mountDuet(ctx) {
302
305
 
303
306
  const api = async (path, signal) => {
304
307
  const response = await fetch(`/duplex-control/api/${path}`, { cache: 'no-store',
305
- signal, headers: { 'X-Duet-Native-Interactions': '1' } })
308
+ signal, headers: { 'X-Duet-Native-Interactions': '1',
309
+ ...(path === 'sessions' ? { 'X-Duet-Catalog-Scope': 'page' } : {}) } })
306
310
  if (!response.ok) throw Object.assign(new Error('harness_unavailable'), {status:response.status})
307
311
  return response.json()
308
312
  }
@@ -325,18 +329,13 @@ export function mountDuet(ctx) {
325
329
  const id = focusedSession(ctx)
326
330
  const scope = id ? ctx.sessions.scope(id) : undefined
327
331
  if (scope) {
328
- 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. */ }
332
+ 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. */ }
329
333
  }
330
334
  state.update({
331
335
  hidden: document.visibilityState !== 'visible',
332
336
  running: catalog.sessions.some(s => s.running),
333
337
  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 })) },
334
- results: bootstrap ? [] : completed.results.map(job => ({
335
- type: 'external_message', message_id: `harness_${job.id}`,
336
- source: { session_id: job.session_id, session_name: labels.get(job.session_id) || job.session_id,
337
- job_id: job.id, status: job.status === 'succeeded' ? 'completed' : 'failed' },
338
- text: (job.status === 'succeeded' ? job.result : (job.error || job.result)) || '未返回结果。',
339
- })),
338
+ results: bootstrap ? [] : completed.results.map(job => resultNotification(job, labels.get(job.session_id))),
340
339
  })
341
340
  resultEpoch = health.focus_epoch
342
341
  cursor = bootstrap ? completed.current_cursor : completed.next_cursor
@@ -1,5 +1,5 @@
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.5'
2
+ import { focusedSession as currentSession } from './composer.mjs?v=0.1.7'
3
3
 
4
4
  export function startComposerBridge(ctx, clientId, fetchImpl = fetch) {
5
5
  const focusedSession = () => currentSession(ctx)
@@ -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.5'
2
+ import {normalizeGuidance} from '../shared/connection-guidance.mjs?v=0.1.7'
3
3
  export function mountConnectionHint(controls, { duration = 8000, onShown = ()=>{} } = {}) {
4
4
  const hint = document.createElement('div')
5
5
  hint.dataset.duetConnectionHint = ''
@@ -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.5').then(module => {
14
+ import('/duet/assets/client/browser.mjs?v=0.1.7').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,4 +1,6 @@
1
1
  /** Optional, explicit rating; never opens voice or submits without a user click. */
2
+ import { identityFetch } from './identity.mjs?v=0.1.7'
3
+
2
4
  export function mountRating(anchor, sessionTicket) {
3
5
  if(!sessionTicket)return null
4
6
  const panel=document.createElement('section')
@@ -34,7 +36,7 @@ export function mountRating(anchor, sessionTicket) {
34
36
  requestController=new AbortController()
35
37
  requestTimeout=setTimeout(()=>requestController.abort(),15000)
36
38
  try {
37
- const r=await fetch('/duplex-control/api/feedback',{method:'POST',credentials:'same-origin',
39
+ const r=await identityFetch('/duplex-control/api/feedback',{method:'POST',credentials:'same-origin',
38
40
  headers:{'Content-Type':'application/json','X-Duplex-Settings':'1'},signal:requestController.signal,
39
41
  body:JSON.stringify({kind:'rating',request_id:requestId,session_ticket:sessionTicket,rating})})
40
42
  const result=await r.json()
@@ -0,0 +1,50 @@
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'
3
+
4
+ /** Desktop strips plugin cookies. Keep the Host-signed value in its origin storage. */
5
+ export function createIdentityClient(globals = globalThis) {
6
+ const desktop = () => globals.location?.protocol === 'dsh-app:'
7
+ const read = () => {
8
+ const token = globals.localStorage.getItem(IDENTITY_STORAGE)
9
+ return validIdentityToken(token) ? token : null
10
+ }
11
+ async function fetchIdentity(path, options = {}) {
12
+ if (!desktop()) return globals.fetch(path, options)
13
+ if (!['/duplex-control/api/voice/config', '/duplex-control/api/feedback'].includes(path)) {
14
+ return globals.fetch(path, options)
15
+ }
16
+ const config = path.endsWith('/voice/config') && (!options.method || options.method === 'GET')
17
+ const request = async () => {
18
+ const headers = new Headers(options.headers)
19
+ const token = read()
20
+ if (token) headers.set(IDENTITY_HEADER, token)
21
+ headers.set(IDENTITY_TRANSPORT_HEADER, IDENTITY_TRANSPORT)
22
+ const response = await globals.fetch(path, {...options, headers, credentials:'same-origin', cache:'no-store'})
23
+ if (config && response.ok) {
24
+ const payload = await response.clone().json()
25
+ if (payload.feedback_enabled) {
26
+ if (!validIdentityToken(payload.feedback_identity)) throw Error('feedback_identity_unavailable')
27
+ globals.localStorage.setItem(IDENTITY_STORAGE, payload.feedback_identity)
28
+ }
29
+ }
30
+ return response
31
+ }
32
+ // Re-read storage inside the shared lock: concurrent page/iframe bootstrap
33
+ // must reuse the first issued identity instead of overwriting each other.
34
+ if (config) {
35
+ if (!globals.navigator?.locks) throw Error('feedback_identity_lock_unavailable')
36
+ return globals.navigator.locks.request(IDENTITY_STORAGE, {signal:options.signal}, request)
37
+ }
38
+ return request()
39
+ }
40
+ function voiceProtocols() {
41
+ if (!desktop()) return []
42
+ const token = read()
43
+ return token ? [VOICE_PROTOCOL, IDENTITY_PROTOCOL_PREFIX + token] : []
44
+ }
45
+ return {fetch:fetchIdentity, voiceProtocols}
46
+ }
47
+
48
+ const client = createIdentityClient()
49
+ export const identityFetch = client.fetch
50
+ export const identityVoiceProtocols = client.voiceProtocols
@@ -2,7 +2,15 @@
2
2
  import { orderSessionCatalog, readWorkspaceView } from '../shared/catalog.mjs'
3
3
  const MAX_BYTES = 256_000
4
4
  const READ = /^\/api\/(?:health|sessions|jobs|results|interactions|composer\/focused|sessions\/[A-Za-z0-9_-]+\/composer)$/
5
- const WRITE = /^\/api\/(?:sessions\/[A-Za-z0-9_-]+\/(?:composer\/submit|activate|rename|fork)|interactions\/(?:(?:question|approval)(?::|%3[Aa]))?[A-Za-z0-9_-]+\/respond)$/
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
+
7
+ // Navigate only the connection-owning page after a successful mutation.
8
+ export function rpcNavigationSession(request, body) {
9
+ if (request.method !== 'POST') return null
10
+ if (/^\/api\/sessions\/[A-Za-z0-9_-]+\/activate$/.test(request.path)) return body.active_session_id
11
+ if (request.path === '/api/sessions' || /^\/api\/sessions\/[A-Za-z0-9_-]+\/fork$/.test(request.path)) return body.session?.session_id
12
+ return null
13
+ }
6
14
 
7
15
  export function validateRPC(request) {
8
16
  if (request.type !== 'harness.rpc.request' || !/^[a-f0-9]{32}$/.test(request.request_id || '')
@@ -63,6 +71,11 @@ export class HarnessRPCExecutor {
63
71
  const timer = setTimeout(() => controller.abort(), 12_000)
64
72
  const envelope = { type: 'harness.rpc.response', connection_id: request.connection_id, request_id: request.request_id }
65
73
  try {
74
+ let payload = request.payload ?? {}
75
+ if (request.method === 'POST' && request.path === '/api/sessions' && this.binding.creationPayload) {
76
+ try { payload = this.binding.creationPayload(payload) }
77
+ catch (error) { return { ...envelope, status: 409, body: { error_code: error.code || error.message || 'workspace_selection_required' } } }
78
+ }
66
79
  if (this.localComposer) {
67
80
  try {
68
81
  const body = await this.localComposer(request, controller.signal)
@@ -78,7 +91,7 @@ export class HarnessRPCExecutor {
78
91
  headers: { 'Content-Type': 'application/json', 'X-Duplex-Control-Client': 'realtime-client-rpc-v1',
79
92
  'X-Duet-Native-Interactions': '1',
80
93
  ...(this.binding.id ? { 'X-Duet-Browser-Client': this.binding.id } : {}) },
81
- ...(request.method !== 'GET' ? { body: JSON.stringify(request.payload ?? {}) } : {}),
94
+ ...(request.method !== 'GET' ? { body: JSON.stringify(payload) } : {}),
82
95
  })
83
96
  const text = await response.text()
84
97
  if (new TextEncoder().encode(text).length > MAX_BYTES - 512) throw new Error('harness_rpc_response_too_large')
@@ -86,7 +99,8 @@ export class HarnessRPCExecutor {
86
99
  if (!body || typeof body !== 'object' || Array.isArray(body)) throw new Error('invalid_harness_rpc_body')
87
100
  controller.signal.throwIfAborted()
88
101
  if (response.ok && this.binding.completed) await this.binding.completed(request, body, controller.signal)
89
- if (response.status === 200 && request.path === '/api/sessions' && Array.isArray(body.sessions)) {
102
+ if (response.status === 200 && request.method === 'GET' && request.path === '/api/sessions' && Array.isArray(body.sessions)) {
103
+ body.duet_rpc_capabilities = ['create_session_v1']
90
104
  // Both startup prompt and nth_N resolution read this same browser-local
91
105
  // order, including manual drag order; archived rows cannot consume ranks.
92
106
  body.sessions = this.catalogOrder(body.sessions)
@@ -70,13 +70,13 @@
70
70
  <h1>duet<span id="duetMark" style="color:#ed9b35">.</span></h1>
71
71
  <div class="sub">用声音控制dsh,让工作变得更自由。</div>
72
72
  <div class="connection" id="connectionStatus">
73
- <div><div class="connection-title" id="connectionTitle">正在连接 DSH</div><div class="connection-detail" id="connectionDetail"></div></div>
73
+ <div><div class="connection-title" id="connectionTitle">正在读取连接状态</div><div class="connection-detail" id="connectionDetail"></div></div>
74
74
  </div>
75
75
  <section class="panel" style="margin-bottom:18px">
76
76
  <h2>连接概览</h2>
77
77
  <p class="section-note">选择一种语音模式,点击当前模式即可关闭。</p>
78
78
  <div class="cards">
79
- <div class="metric"><small>当前模式</small><strong id="duetConnection">全部关闭</strong></div>
79
+ <div class="metric"><small>当前模式</small><strong id="duetConnection">读取中</strong></div>
80
80
  <div class="metric"><small>服务配置</small><strong id="authState">检查中</strong></div>
81
81
  <div class="metric"><small>插件版本</small><strong id="pluginVersion">检查中</strong></div>
82
82
  <div class="metric"><small>双工模型</small><strong id="duplexModel" style="font-size:16px;overflow-wrap:anywhere">检查中</strong></div>
@@ -151,7 +151,8 @@
151
151
  </div>
152
152
  <footer><span>duet / DeepSeek Harness</span></footer>
153
153
  </main>
154
- <script>
154
+ <script type="module">
155
+ import { identityFetch } from '/duet/assets/client/identity.mjs?v=0.1.7';
155
156
  const base = "/duplex-control/api";
156
157
  let debugEnabled = false, settingsRevision = null, feedbackSubmitting = false;
157
158
  const composerChannel = typeof BroadcastChannel === "undefined" ? null : new BroadcastChannel("dsh-duplex-control-v1");
@@ -160,7 +161,7 @@
160
161
  const $ = id => document.getElementById(id);
161
162
  const escapeHtml = value => String(value ?? "").replace(/[&<>"']/g, c => ({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[c]));
162
163
  async function api(path, options = {}) {
163
- const response = await fetch(base + path, {headers:{"Content-Type":"application/json"}, ...options});
164
+ const response = await identityFetch(base + path, {headers:{"Content-Type":"application/json"}, ...options});
164
165
  const payload = await response.json();
165
166
  if (!response.ok) throw new Error(payload.detail || `HTTP ${response.status}`);
166
167
  return payload;
@@ -199,36 +200,32 @@
199
200
  if (overwrite) $("composerDraft").value = composer.draft;
200
201
  $("composerMeta").textContent = `${composer.session_id} · ${composer.phase} · revision ${composer.draft_revision}`;
201
202
  }
202
- function sessionLabel(sessionId) {
203
- return sessionLabels.get(sessionId) || sessionId || "未选择";
204
- }
205
- async function loadConnectionStatus() {
203
+ function showConnectionStatus(config) {
204
+ const connection = config.connection || {};
206
205
  const card = $("connectionStatus");
207
- try {
208
- const health = await api("/health");
209
- const age = health.browser_client_last_seen_at === null
210
- ? null
211
- : Math.max(0, Date.now() / 1000 - health.browser_client_last_seen_at);
212
- card.className = "connection";
213
- if (!health.browser_client_connected) {
214
- card.classList.add("disconnected");
215
- $("connectionTitle").textContent = "DSH 主页面未连接";
216
- $("connectionDetail").textContent = debugEnabled ? `请打开或刷新 DSH 主页面;duet 当前选择:${sessionLabel(health.active_session_id)}` : '请回到 DSH 页面开启语音模式。';
217
- } else if (!health.browser_focus_matches) {
218
- card.classList.add("mismatch");
219
- $("connectionTitle").textContent = "正在连接 DSH 会话";
220
- $("connectionDetail").textContent = debugEnabled ? `duet:${sessionLabel(health.active_session_id)} · DSH:${sessionLabel(health.browser_focus_session_id)} · 最近心跳 ${age?.toFixed(1)} 秒前` : '';
221
- } else {
222
- card.classList.add("connected");
223
- $("connectionTitle").textContent = "DSH 主页面已连接";
224
- $("connectionDetail").textContent = debugEnabled ? `焦点一致:${sessionLabel(health.active_session_id)} · 最近心跳 ${age?.toFixed(1)} 秒前` : `插件 ${health.plugin_version} · 主页面连接正常`;
225
- }
226
- } catch (error) {
227
- card.className = "connection disconnected";
228
- $("connectionTitle").textContent = "duet 暂时不可用";
229
- $("connectionDetail").textContent = debugEnabled ? error.message : '暂时无法连接,请稍后重试。';
206
+ card.className = "connection";
207
+ if (connection.online || connection.tts_only) {
208
+ card.classList.add("connected");
209
+ $("connectionTitle").textContent = "语音已连接";
210
+ const mode = connection.online ? '交互模式' : '播报模式';
211
+ $("connectionDetail").textContent = `${mode} · 插件 ${config.plugin_version || '—'}`;
212
+ } else if (connection.connecting) {
213
+ card.classList.add("mismatch");
214
+ $("connectionTitle").textContent = "语音正在连接";
215
+ $("connectionDetail").textContent = "正在连接语音服务,请稍候。";
216
+ } else {
217
+ card.classList.add("disconnected");
218
+ $("connectionTitle").textContent = "语音未开启";
219
+ $("connectionDetail").textContent = "请回到 DSH 页面开启语音模式。";
230
220
  }
231
221
  }
222
+ function showConnectionUnavailable() {
223
+ $("connectionStatus").className = "connection disconnected";
224
+ $("connectionTitle").textContent = "语音连接信息不可用";
225
+ $("connectionDetail").textContent = "暂时无法读取连接状态,请稍后重试。";
226
+ $('duetConnection').textContent = '语音连接信息不可用';
227
+ $('duetMark').style.color = '#ed9b35';
228
+ }
232
229
  async function loadSessions() {
233
230
  const sessions = (await api("/sessions")).sessions;
234
231
  sessionLabels.clear();
@@ -291,9 +288,13 @@
291
288
  catch (error) { showMessage(error.message, true); }
292
289
  };
293
290
  $("refresh").onclick = async () => Promise.all([loadSessions(), loadJobs()]);
294
- async function refresh() { try { await Promise.all([loadSessions(), loadJobs(), loadConnectionStatus()]); } catch (error) { showMessage(error.message, true); } }
291
+ async function refresh() { try { await Promise.all([loadSessions(), loadJobs()]); } catch (error) { showMessage(error.message, true); } }
295
292
  async function loadDuetConfig(fill = false) {
296
293
  const config = await api('/voice/config');
294
+ showConnectionStatus(config);
295
+ const c = config.connection || {};
296
+ $('duetMark').style.color = c.online || c.tts_only ? '#7fd6a6' : '#ed9b35';
297
+ $('duetConnection').textContent = c.online ? '交互模式' : c.tts_only ? '播报模式' : c.connecting ? '正在连接' : '未开启';
297
298
  const info = await api('/voice/service-info').catch(() => ({status:'unavailable'}));
298
299
  $('duplexModel').textContent = info.status === 'ok' ? info.models.duplex : '暂不可用';
299
300
  $('ttsModel').textContent = info.status === 'ok' ? info.models.tts : '暂不可用';
@@ -303,9 +304,6 @@
303
304
  settingsRevision = config.revision;
304
305
  $('backendUrl').value = config.backend_url || '';
305
306
  }
306
- const c = config.connection || {};
307
- $('duetMark').style.color = c.online || c.tts_only ? '#7fd6a6' : '#ed9b35';
308
- $('duetConnection').textContent = c.online ? '交互模式' : c.tts_only ? '播报模式' : c.connecting ? '正在连接' : '未开启';
309
307
  $('authState').textContent = config.backend_url ? '已配置' : '待配置';
310
308
  $('pluginVersion').textContent = config.plugin_version || '—';
311
309
  $('saveDuet').disabled = false;
@@ -361,25 +359,24 @@
361
359
  await refresh();
362
360
  composerRequest('composer/get').then(composer => showComposer(composer)).catch(() => {});
363
361
  setInterval(() => { void refresh(); }, 2000);
364
- } else setInterval(loadConnectionStatus, 2000);
365
- await loadConnectionStatus();
362
+ }
366
363
  }
367
364
  $('openTutorial').onclick = async () => {
368
365
  try {
369
- const {requestTutorial} = await import('/duet/assets/client/tutorial-request.mjs?v=0.1.5');
366
+ const {requestTutorial} = await import('/duet/assets/client/tutorial-request.mjs?v=0.1.7');
370
367
  requestTutorial(localStorage);
371
368
  $('tutorialStatus').textContent = '请回到 DSH 页面继续教学。';
372
369
  } catch { $('tutorialStatus').textContent = '暂时无法打开教学,请允许浏览器存储后重试。'; }
373
370
  };
374
- initialize().catch(error => { $('settingsMessage').textContent = debugEnabled ? `配置读取失败:${error.message}` : '暂时无法加载设置,请刷新重试。'; });
375
- setInterval(() => { loadDuetConfig().catch(() => { $('duetConnection').textContent = '语音连接信息不可用'; }); }, 2000);
371
+ initialize().catch(error => { showConnectionUnavailable(); $('settingsMessage').textContent = debugEnabled ? `配置读取失败:${error.message}` : '暂时无法加载设置,请刷新重试。'; });
372
+ setInterval(() => { loadDuetConfig().catch(showConnectionUnavailable); }, 2000);
376
373
  void loadNotices();
377
374
  setInterval(loadNotices, 60000);
378
- import('/duet/assets/client/shortcuts.mjs?v=0.1.5').then(({mountShortcutSettings}) => {
375
+ import('/duet/assets/client/shortcuts.mjs?v=0.1.7').then(({mountShortcutSettings}) => {
379
376
  const dispose = mountShortcutSettings({speaker:$('speakerShortcut'),mic:$('micShortcut'),clearSpeaker:$('clearSpeakerShortcut'),clearMic:$('clearMicShortcut'),status:$('shortcutStatus')});
380
377
  window.addEventListener('pagehide', e => {if(!e.persisted)dispose()}, {once:true});
381
378
  }).catch(() => { $('shortcutStatus').textContent = '暂时无法加载快捷键设置,请刷新重试。'; });
382
- import('/duet/assets/client/microphone.mjs?v=0.1.5').then(({mountMicrophoneSettings}) => {
379
+ import('/duet/assets/client/microphone.mjs?v=0.1.7').then(({mountMicrophoneSettings}) => {
383
380
  const dispose = mountMicrophoneSettings({select:$('microphoneDevice'),refresh:$('refreshMicrophones'),status:$('microphoneStatus')});
384
381
  window.addEventListener('pagehide', dispose, {once:true});
385
382
  }).catch(() => { $('microphoneStatus').textContent = '暂时无法加载麦克风设置,请刷新重试。'; });
@@ -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.5'
3
- import { focusedSession } from './composer.mjs?v=0.1.5'
4
- import { requireWorkspace, workspaceIssue } from './workspaces.mjs?v=0.1.5'
5
- import { startComposerBridge } from './composer-bridge.mjs?v=0.1.5'
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'
6
6
  export function tutorialAdapter(ctx, state, audio, pollReady, startBridge = startComposerBridge) {
7
7
  let narration
8
8
  const completed = new Map()
@@ -44,9 +44,8 @@ export function tutorialAdapter(ctx, state, audio, pollReady, startBridge = star
44
44
  observe(event){if(event.type==='external_message.done'){completed.set(event.message_id,event.status);if(completed.size>128)completed.delete(completed.keys().next().value)}},
45
45
  unlock:()=>audio.prepare(),
46
46
  async create(name,signal){
47
- requireWorkspace(ctx)
48
- const catalog=await api('sessions',signal), cwd=catalog.sessions.find(s=>s.session_id===current())?.cwd
49
- const d=await api('sessions',signal,'POST',{name,...(cwd?{cwd}:{})});return d.session.session_id
47
+ const payload=sessionCreationPayload(ctx,{name})
48
+ const d=await api('sessions',signal,'POST',payload);return d.session.session_id
50
49
  },
51
50
  async focus(id,signal){
52
51
  await api(`sessions/${encodeURIComponent(id)}/activate`,signal,'POST',{})
@@ -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.5'
2
+ import {consumeTutorialRequest} from './tutorial-request.mjs?v=0.1.7'
3
3
  export const TUTORIAL_KEY = 'dsh-duplex-tutorial-v1'
4
4
  export const QUESTION = '什么是语音交互?请用一句话简单解释,不使用工具。'
5
5
  export const INPUT = '用一句话介绍语音助手。'
@@ -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) {
@@ -14,12 +14,24 @@ export function requireWorkspace(ctx) {
14
14
  if (issue) throw Error(issue)
15
15
  }
16
16
 
17
+ /** Resolve at command time from this page, not the host's global focus/cwd. */
18
+ export function sessionCreationPayload(ctx, payload = {}) {
19
+ requireWorkspace(ctx)
20
+ const current = focusedSession(ctx)
21
+ const items = ctx.workspaces.list.getSnapshot().items
22
+ const workspace = items.find(item => item.sessionIds?.includes(current))
23
+ ?? (!current && items.length === 1 ? items[0] : null)
24
+ if (!workspace?.workspaceId) throw Object.assign(new Error('workspace_selection_required'), { code: 'workspace_selection_required' })
25
+ return { name: payload.name, workspace_id: workspace.workspaceId }
26
+ }
27
+
17
28
  export function browserSessionCatalog(ctx, rows) {
18
29
  const snapshot = ctx.sessions.list.getSnapshot()
19
30
  const active = focusedSession(ctx)
20
31
  const archived = new Set(ctx.workspaces?.list?.getSnapshot().archivedSessionIds || [])
21
32
  return orderSessionCatalog(rows.filter(row => !archived.has(row.session_id)).map(row => ({
22
33
  ...row, active: row.session_id === active,
34
+ label: sessionLabel(row.label, row.session_id),
23
35
  updated_at: snapshot.byId?.[row.session_id]?.updatedAt ?? row.updated_at,
24
36
  })), readWorkspaceView())
25
37
  }
@@ -1,6 +1,7 @@
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',
@@ -13,6 +14,7 @@ const modules = {
13
14
  notice: 'client/notice',
14
15
  workspaces: 'client/workspaces',
15
16
  transport: 'client/transport',
17
+ identity: 'client/identity', identity_protocol: 'shared/identity',
16
18
  }
17
19
  const aliases = {
18
20
  state: 'DuetState as VoiceState', audio: 'DuetAudio as VoiceAudio',
@@ -3,6 +3,7 @@ import {createHmac,randomBytes,timingSafeEqual} from 'node:crypto'
3
3
  import {existsSync,mkdirSync,readFileSync,openSync,writeFileSync,fsyncSync,closeSync,linkSync,unlinkSync} from 'node:fs'
4
4
  import {dirname} from 'node:path'
5
5
  import {defaultStateFile} from './storage-paths.mjs'
6
+ import {IDENTITY_HEADER, IDENTITY_PROTOCOL_PREFIX, validIdentityToken} from '../shared/identity.mjs'
6
7
 
7
8
  const COOKIE='duplex_feedback_user'
8
9
  export class RemoteFeedback {
@@ -25,21 +26,27 @@ export class RemoteFeedback {
25
26
  this.key=key;return key
26
27
  }
27
28
  sign(id){return createHmac('sha256',this.identityKey()).update(id).digest('hex')}
28
- userId(req){
29
+ identityToken(req){
30
+ const header=req.headers?.[IDENTITY_HEADER.toLowerCase()]
31
+ const protocols=String(req.headers?.['sec-websocket-protocol']||'').split(',').map(x=>x.trim()).filter(x=>x.startsWith(IDENTITY_PROTOCOL_PREFIX))
32
+ if(protocols.length>1)throw Error('feedback_identity_unavailable')
29
33
  const cookie=String(req.headers?.cookie||'').split(';').map(x=>x.trim()).find(x=>x.startsWith(COOKIE+'='))?.slice(COOKIE.length+1)
30
- if(!cookie||!/^([a-f0-9]{32})\.([a-f0-9]{64})$/.test(cookie))throw Error('feedback_identity_unavailable')
31
- const [id,mac]=cookie.split('.')
34
+ const token=header??(protocols.length?protocols[0].slice(IDENTITY_PROTOCOL_PREFIX.length):cookie)
35
+ if(!validIdentityToken(token))throw Error('feedback_identity_unavailable')
36
+ const [id,mac]=token.split('.')
32
37
  if(!timingSafeEqual(Buffer.from(this.sign(id)),Buffer.from(mac)))throw Error('feedback_identity_unavailable')
33
- return 'anon_'+id
38
+ return token
34
39
  }
35
- ensureIdentity(req,res){
36
- try{return this.userId(req)}catch{}
40
+ userId(req){return 'anon_'+this.identityToken(req).split('.')[0]}
41
+ ensureCredential(req,res){
42
+ try{return this.identityToken(req)}catch{}
37
43
  const id=randomBytes(16).toString('hex'),signed=id+'.'+this.sign(id)
38
44
  // Same-origin HttpOnly cookie; identity is pseudonymous browser, not account.
39
45
  const secure=req.socket?.encrypted||req.headers['x-forwarded-proto']==='https'
40
46
  res.setHeader('Set-Cookie',`${COOKIE}=${signed}; Path=/duplex-control; HttpOnly; SameSite=Strict; Max-Age=31536000${secure?'; Secure':''}`)
41
- return 'anon_'+id
47
+ return signed
42
48
  }
49
+ ensureIdentity(req,res){return 'anon_'+this.ensureCredential(req,res).split('.')[0]}
43
50
  async insert(record,{config:connectionConfig}={}){
44
51
  const config=connectionConfig||await this.getConfig(),url=new URL(config.endpoints.online)
45
52
  url.protocol=url.protocol==='wss:'?'https:':'http:'
@@ -4,13 +4,14 @@ import { readFile } from 'node:fs/promises'
4
4
  import { randomUUID } from 'node:crypto'
5
5
  import { registerDuetProxy, duetConfig } from './proxy.mjs'
6
6
  import { DuetSettings, settingsWriteAllowed } from './settings.mjs'
7
+ import { IDENTITY_TRANSPORT_HEADER, IDENTITY_TRANSPORT } from '../shared/identity.mjs'
7
8
  import { ServiceNotices } from './notices.mjs'
8
9
  import { ServiceInfo } from './service-info.mjs'
9
10
  import { DuetTrace } from './trace.mjs'
10
11
  import { FeedbackService } from './feedback-store.mjs'
11
12
  import { RemoteFeedback } from './feedback-files.mjs'
12
13
  import { PLUGIN_VERSION } from '../shared/state.mjs'
13
- import { buildSessionCatalog } from '../shared/catalog.mjs'
14
+ import { buildSessionCatalog, sessionLabel } from '../shared/catalog.mjs'
14
15
  import { publicAsset } from './assets.mjs'
15
16
  import { duetEnv } from './environment.mjs'
16
17
  import { EndpointDiscovery } from './endpoint-discovery.mjs'
@@ -485,9 +486,18 @@ export function apply(ctx, options = {}) {
485
486
  completeJob(job, event)
486
487
  })
487
488
 
489
+ const identityWriteAllowed = req => {
490
+ if(settingsWriteAllowed(req))return true
491
+ // Desktop strips Origin after enforcing dsh-app://app in its bridge.
492
+ // Never infer a trusted bridge from an absent header alone.
493
+ if(req.headers.origin!==undefined || req.headers[IDENTITY_TRANSPORT_HEADER.toLowerCase()]!==IDENTITY_TRANSPORT)return false
494
+ try {feedback.user(req);return settingsWriteAllowed(req,{verifiedLocalIdentity:true})} catch {return false}
495
+ }
488
496
  const handleApi = async (req, res, pathname) => {
489
497
  if(req.method==='POST' && pathname===`${ROUTE}/api/feedback`){
490
- if(!settingsWriteAllowed(req)){sendError(res,403,'same-origin feedback request required');return}
498
+ const rejection = ctx.connection.requestRejection(req)
499
+ if(rejection){sendError(res,rejection,'请先打开并登录 DSH 主页面');return}
500
+ if(!identityWriteAllowed(req)){sendError(res,403,'same-origin feedback request required');return}
491
501
  try {sendJson(res,201,await feedback.submit(req,await readJson(req)))}
492
502
  catch(error){
493
503
  const code=String(error.message||'')
@@ -509,12 +519,17 @@ export function apply(ctx, options = {}) {
509
519
  return
510
520
  }
511
521
  if (req.method === 'GET' && pathname === `${ROUTE}/api/voice/config`) {
512
- try{feedbackStore?.ensureIdentity?.(req,res)}catch{sendJson(res,503,{error_code:'feedback_identity_unavailable'});return}
513
- sendJson(res, 200, { ...settings.public(), plugin_version: PLUGIN_VERSION, feedback_enabled: feedback.enabled, connection: duetProxy?.snapshot?.() || { online: 0, tts_only: 0 } })
522
+ let identity
523
+ try {
524
+ if(req.headers[IDENTITY_TRANSPORT_HEADER.toLowerCase()]===IDENTITY_TRANSPORT)identity=feedbackStore?.ensureCredential?.(req,res)
525
+ else feedbackStore?.ensureIdentity?.(req,res)
526
+ } catch {sendJson(res,503,{error_code:'feedback_identity_unavailable'});return}
527
+ sendJson(res, 200, { ...settings.public(), plugin_version: PLUGIN_VERSION, feedback_enabled: feedback.enabled,
528
+ ...(identity?{feedback_identity:identity}:{}), connection: duetProxy?.snapshot?.() || { online: 0, tts_only: 0 } })
514
529
  return
515
530
  }
516
531
  if (req.method === 'PUT' && pathname === `${ROUTE}/api/voice/config`) {
517
- if (!settingsWriteAllowed(req)) { sendError(res, 403, 'same-origin settings request required'); return }
532
+ if (!identityWriteAllowed(req)) { sendError(res, 403, 'same-origin settings request required'); return }
518
533
  try {
519
534
  const result = await settings.save(await readJson(req))
520
535
  Object.assign(voice, settings.effective())
@@ -779,7 +794,10 @@ export function apply(ctx, options = {}) {
779
794
  return
780
795
  }
781
796
  if (req.method === 'GET' && pathname === `${ROUTE}/api/sessions`) {
782
- sendJson(res, 200, { sessions: await listSessions({forCatalog:true}) })
797
+ // A page owns its focus. Do not remove blank sessions using host focus
798
+ // before that page can select its own current blank session.
799
+ const pageCatalog = browserOwner(req) || req.headers['x-duet-catalog-scope'] === 'page'
800
+ sendJson(res, 200, { sessions: await listSessions({forCatalog:!pageCatalog}) })
783
801
  return
784
802
  }
785
803
  const composer = pathname.match(new RegExp(`^${ROUTE}/api/sessions/([^/]+)/composer$`))
@@ -905,11 +923,17 @@ export function apply(ctx, options = {}) {
905
923
  if (req.method === 'POST' && pathname === `${ROUTE}/api/sessions`) {
906
924
  const body = await readJson(req)
907
925
  const name = String(body.name || '').trim()
908
- const cwd = String(body.cwd || process.cwd()).trim()
926
+ const cwd = String(body.cwd || '').trim()
909
927
  // Current DSH only enables the blank-session composer for a session
910
928
  // owned by a registered workspace. cwd alone creates an orphan session.
911
- let workspaceId
912
- if (typeof ctx.workspaceController.create === 'function') {
929
+ let workspaceId = typeof body.workspace_id === 'string' ? body.workspace_id.trim() : ''
930
+ if (workspaceId) {
931
+ if (!(ctx.workspaceRegistry.list?.() || []).some(workspace => workspace.id === workspaceId)) {
932
+ throw codedError('workspace_not_found', 'Selected workspace is no longer available', 409)
933
+ }
934
+ } else if (!cwd || browserOwner(req)) {
935
+ throw codedError('workspace_selection_required', 'Select a workspace before creating a session', 409)
936
+ } else if (typeof ctx.workspaceController.create === 'function') {
913
937
  const resolved = await ctx.workspaceController.create({ path: cwd })
914
938
  workspaceId = resolved.workspace?.workspaceId
915
939
  if (typeof workspaceId !== 'string' || !workspaceId) {
@@ -921,7 +945,7 @@ export function apply(ctx, options = {}) {
921
945
  if (name) {
922
946
  await ctx.sessionController.rename({ sessionId: created.sessionId, title: name })
923
947
  }
924
- sendJson(res, 201, { session: { session_id: created.sessionId, label: name || created.sessionId, active: true } })
948
+ sendJson(res, 201, { session: { session_id: created.sessionId, label: sessionLabel(name, created.sessionId), active: true } })
925
949
  return
926
950
  }
927
951
 
@@ -5,6 +5,9 @@ import { PLUGIN_VERSION } from '../shared/state.mjs'
5
5
  import { duetEnv } from './environment.mjs'
6
6
  import { EndpointDiscovery, connectEndpoint } from './endpoint-discovery.mjs'
7
7
  import {sessionMetadata} from './session-metadata.mjs'
8
+ import {VOICE_PROTOCOL} from '../shared/identity.mjs'
9
+ import { broadcastText } from '../shared/result-notification.mjs'
10
+ import { sessionLabel } from '../shared/catalog.mjs'
8
11
  import { DEFAULT_DUET_URL, publicServiceAuthorization } from './service-defaults.mjs'
9
12
  export { DEFAULT_DUET_URL } from './service-defaults.mjs'
10
13
  const require = createRequire(import.meta.url)
@@ -33,8 +36,7 @@ export function duetConfig(env = process.env) {
33
36
  export function externalWithState(message, _state) {
34
37
  if (message.type !== 'external_message' || typeof message.text !== 'string') throw new Error('invalid_external_message')
35
38
  // Keep authoritative result metadata separate from result text and UI state.
36
- const text = message.text
37
- if (text.length > 8000) throw new Error('external_message_too_large')
39
+ const text = broadcastText(message.text)
38
40
  const source = message.source
39
41
  if (source !== undefined) {
40
42
  const limits = { session_id: 256, session_name: 512, job_id: 256, status: 16 }
@@ -44,7 +46,7 @@ export function externalWithState(message, _state) {
44
46
  !['completed', 'failed'].includes(source.status)) throw new Error('invalid_external_message_source')
45
47
  }
46
48
  return { type: 'external_message', message_id: message.message_id, text,
47
- ...(source === undefined ? {} : { source: { ...source } }) }
49
+ ...(source === undefined ? {} : { source: { ...source, session_name: sessionLabel(source.session_name, source.session_id) } }) }
48
50
  }
49
51
 
50
52
  export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, canUseVoice = () => true, discovery = new EndpointDiscovery(() => config)) {
@@ -55,7 +57,8 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
55
57
  if (!['ws:', 'wss:'].includes(url.protocol) || url.username || url.password || url.hash) throw new Error('invalid_voice_endpoint')
56
58
  }
57
59
  const { WebSocket, WebSocketServer } = require('ws')
58
- const server = new WebSocketServer({ noServer: true, maxPayload: 1_000_000 })
60
+ const server = new WebSocketServer({ noServer: true, maxPayload: 1_000_000,
61
+ handleProtocols: protocols => protocols.has(VOICE_PROTOCOL) ? VOICE_PROTOCOL : false })
59
62
  const connections = new Map()
60
63
  const stop = ctx.webServer.registerUpgrade({
61
64
  path: '/duplex-control/voice/ws',
@@ -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
 
@@ -94,10 +95,10 @@ export class DuetSettings {
94
95
  }
95
96
  }
96
97
 
97
- export function settingsWriteAllowed(req) {
98
+ export function settingsWriteAllowed(req, { verifiedLocalIdentity = false } = {}) {
98
99
  try {
99
100
  return req.headers['x-duplex-settings'] === '1'
100
- && new URL(req.headers.origin).host === req.headers.host
101
+ && ((req.headers.origin === undefined && verifiedLocalIdentity) || new URL(req.headers.origin).host === req.headers.host)
101
102
  && String(req.headers['content-type'] || '').startsWith('application/json')
102
103
  } catch { return false }
103
104
  }
@@ -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,8 @@
1
+ /** Anonymous identity transport, independent of DSH authentication. */
2
+ export const IDENTITY_HEADER = 'X-Duet-Identity'
3
+ export const IDENTITY_TRANSPORT_HEADER = 'X-Duet-Identity-Transport'
4
+ export const IDENTITY_TRANSPORT = 'local-v1'
5
+ export const IDENTITY_STORAGE = 'dsh-duet.feedback-identity.v1'
6
+ export const VOICE_PROTOCOL = 'duet-voice-v1'
7
+ export const IDENTITY_PROTOCOL_PREFIX = 'duet-identity.'
8
+ export const validIdentityToken = value => typeof value === 'string' && /^[a-f0-9]{32}\.[a-f0-9]{64}$/.test(value)
@@ -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
+ }
@@ -1,5 +1,5 @@
1
1
  /** Desired voice mode is independent of a temporarily suspended connection. */
2
- export const PLUGIN_VERSION = '0.1.5'
2
+ export const PLUGIN_VERSION = '0.1.7'
3
3
  export const IDLE_RELEASE_MS = 60_000
4
4
 
5
5
  const safeVersion = value => typeof value === 'string' && value.length <= 32 && /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value) ? value : ''
@@ -89,10 +89,10 @@ export class DuetState {
89
89
  this.pending.delete(event.message_id)
90
90
  this.sent.delete(event.message_id)
91
91
  this.flush()
92
- } else if (event.type === 'error') {
92
+ } else if (event.type === 'error' || (event.type === 'warning' && event.warning?.code === 'malformed_dense_action')) {
93
93
  // A rejected model action is not a dead transport. Never execute/retry it,
94
94
  // but leave the user able to clarify instead of closing their microphone.
95
- if (event.code === 'malformed_dense_action') {
95
+ if ((event.code || event.warning?.code) === 'malformed_dense_action') {
96
96
  this.notice('这次操作指令格式有误,未执行。语音仍已连接,请重新说明。')
97
97
  } else this.fail(event.code, event)
98
98
  }