dsh-duet 0.1.1 → 0.1.2

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.1",
3
+ "version": "0.1.2",
4
4
  "description": "duet(二重奏):只用语音就能操作 DSH,边听边说、随时插话的全双工语音助手。",
5
5
  "keywords": [
6
6
  "dsh-plugin",
@@ -10,8 +10,7 @@
10
10
  ],
11
11
  "license": "Apache-2.0",
12
12
  "author": {
13
- "name": "YuMS",
14
- "email": "yumaoshu@gmail.com"
13
+ "name": "YuMS"
15
14
  },
16
15
  "repository": {
17
16
  "type": "git",
@@ -23,7 +22,7 @@
23
22
  "scripts": {
24
23
  "test": "node scripts/test.mjs",
25
24
  "check": "node scripts/check-package.mjs",
26
- "test:browser": "node tests/browser/settings.mjs && node tests/browser/tutorial.mjs && node tests/browser/feedback.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",
27
26
  "test:host": "node tests/host/isolated-host.mjs",
28
27
  "prepack": "npm run check"
29
28
  },
@@ -59,6 +58,7 @@
59
58
  "client": {
60
59
  "inject": [
61
60
  "@deepseek-ai/dsh-api-session-controller",
61
+ "@deepseek-ai/dsh-api-workspace-controller",
62
62
  "@deepseek-ai/dsh-client-ui-session",
63
63
  "@deepseek-ai/dsh-client-ui-conversation"
64
64
  ],
@@ -1,4 +1,4 @@
1
- import { microphoneConstraints } from './microphone.mjs?v=0.1.1'
1
+ import { microphoneConstraints } from './microphone.mjs?v=0.1.2'
2
2
 
3
3
  /** Browser-owned microphone and PCM playback. No microphone is requested in tts_only. */
4
4
  export class DuetAudio {
@@ -1,13 +1,15 @@
1
- import { DuetState, PLUGIN_VERSION } from '../shared/state.mjs?v=0.1.1'
2
- import { DuetAudio } from './audio.mjs?v=0.1.1'
3
- import { HarnessRPCExecutor } from './rpc.mjs?v=0.1.1'
4
- import { composerAccess, observeComposer, focusedSession } from './composer.mjs?v=0.1.1'
5
- import { mountTutorial } from './tutorial.mjs?v=0.1.1'
6
- import { tutorialAdapter } from './tutorial-adapter.mjs?v=0.1.1'
7
- import { mountRating } from './feedback.mjs?v=0.1.1'
8
- import { createAudioUploadConsent } from './consent.mjs?v=0.1.1'
9
- import { bindDuetShortcuts } from './shortcuts.mjs?v=0.1.1'
10
- import { nativeInteractions } from './interactions.mjs?v=0.1.1'
1
+ import { DuetState, PLUGIN_VERSION } from '../shared/state.mjs?v=0.1.2'
2
+ import { DuetAudio } from './audio.mjs?v=0.1.2'
3
+ import { HarnessRPCExecutor } from './rpc.mjs?v=0.1.2'
4
+ import { composerAccess, observeComposer, focusedSession } from './composer.mjs?v=0.1.2'
5
+ import { mountTutorial } from './tutorial.mjs?v=0.1.2'
6
+ import { tutorialAdapter } from './tutorial-adapter.mjs?v=0.1.2'
7
+ import { mountRating } from './feedback.mjs?v=0.1.2'
8
+ import { createAudioUploadConsent } from './consent.mjs?v=0.1.2'
9
+ import { bindDuetShortcuts } from './shortcuts.mjs?v=0.1.2'
10
+ import { nativeInteractions } from './interactions.mjs?v=0.1.2'
11
+ import { mountConnectionHint } from './connection-hint.mjs?v=0.1.2'
12
+ import { workspaceIssue, requireWorkspace, browserSessionCatalog } from './workspaces.mjs?v=0.1.2'
11
13
 
12
14
  export function mountDuet(ctx) {
13
15
  const audio = new DuetAudio()
@@ -15,7 +17,7 @@ export function mountDuet(ctx) {
15
17
  let disposed = false, controls, toastTimer, pollRunning = false, cursor = null, resultEpoch = null
16
18
  const labels = new Map()
17
19
  let clientTraceId = null, diagnosticCount = 0
18
- let tutorial, teaching, ratingPanel
20
+ let tutorial, teaching, ratingPanel, connectionHint
19
21
  const diagnostic = data => {
20
22
  if (++diagnosticCount > 100) return
21
23
  const bounded = Object.fromEntries(Object.entries(data).map(([k, v]) => [k, typeof v === 'string' ? v.slice(0, 4000) : v]))
@@ -29,6 +31,7 @@ export function mountDuet(ctx) {
29
31
  window.addEventListener('error', pageError)
30
32
  window.addEventListener('unhandledrejection', pageError)
31
33
  const notice = (text, { upgrade = false } = {}) => {
34
+ connectionHint?.dismiss()
32
35
  if (upgrade) { ratingPanel?.dispose(); ratingPanel = null }
33
36
  const toast = controls?.querySelector('[role=status]')
34
37
  if (!toast) return
@@ -74,8 +77,10 @@ export function mountDuet(ctx) {
74
77
  const mark = controls.querySelector('[data-duet-mark]')
75
78
  mark.style.color = state.ready ? '#7fd6a6' : '#ed9b35'
76
79
  mark.title = state.ready ? '语音已连接' : '语音未连接'
80
+ connectionHint?.update({ mode: state.mode, ready: state.ready, teaching: Boolean(tutorial?.active) })
77
81
  }
78
82
  const connect = (mode, receive) => {
83
+ requireWorkspace(ctx)
79
84
  if (!audioConsent.granted()) throw Error('data_upload_consent_required')
80
85
  clientTraceId = crypto.randomUUID(); diagnosticCount = 0
81
86
  const connectionTraceId = clientTraceId
@@ -89,7 +94,7 @@ export function mountDuet(ctx) {
89
94
  const composer = composerAccess(ctx, id => labels.get(id) || id)
90
95
  const interactions = nativeInteractions(ctx)
91
96
  const rpc = new HarnessRPCExecutor(send, fetch, report, async (request, signal) =>
92
- (await interactions(request, signal)) ?? composer.execute(request, signal))
97
+ (await interactions(request, signal)) ?? composer.execute(request, signal), rows => browserSessionCatalog(ctx, rows))
93
98
  const connection = {
94
99
  feedbackTicket: null,
95
100
  send,
@@ -116,6 +121,7 @@ export function mountDuet(ctx) {
116
121
  // Establish/renew the host-signed anonymous cookie before the WS handshake.
117
122
  const identity=await fetch('/duplex-control/api/voice/config',{credentials:'same-origin',cache:'no-store'})
118
123
  if(!identity.ok)throw Error('voice_config_unavailable')
124
+ requireWorkspace(ctx)
119
125
  if(closed)return
120
126
  const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:'
121
127
  ws = new WebSocket(`${protocol}//${location.host}/duplex-control/voice/ws?mode=${mode}&plugin_version=${PLUGIN_VERSION}&client_trace_id=${connectionTraceId}`)
@@ -223,8 +229,17 @@ export function mountDuet(ctx) {
223
229
  button.append(ring)
224
230
  button.onclick = () => {
225
231
  if (tutorial?.active) { notice('请先结束教学,再切换模式。'); return }
232
+ const requestedMode = kind === 'mic' ? 'online' : 'tts_only'
233
+ const checkWorkspace = () => {
234
+ if (state.mode === requestedMode) return true // Closing is always allowed.
235
+ const issue = workspaceIssue(ctx)
236
+ if (issue) { state.fail(issue); return false }
237
+ return true
238
+ }
239
+ if (!checkWorkspace()) return
226
240
  const activate = () => {
227
241
  if (disposed || tutorial?.active) return
242
+ if (!checkWorkspace()) return
228
243
  // Unlock playback inside user activation, before any network await.
229
244
  const enabling = kind === 'mic' ? state.mode !== 'online' : state.mode !== 'tts_only'
230
245
  if (enabling) void audio.prepare().catch(() => state.fail('audio_permission_denied'))
@@ -257,6 +272,8 @@ export function mountDuet(ctx) {
257
272
  toast.hidden = true
258
273
  toast.style.cssText = 'position:absolute;bottom:100%;left:0;z-index:9999;min-width:180px;max-width:280px;background:#252c38;color:white;padding:10px;border-radius:8px;font-size:12px;box-shadow:0 3px 18px #0005'
259
274
  controls.append(toast)
275
+ connectionHint?.dispose()
276
+ connectionHint = mountConnectionHint(controls)
260
277
  draw(state)
261
278
  }
262
279
  mount()
@@ -276,6 +293,9 @@ export function mountDuet(ctx) {
276
293
  try {
277
294
  const [catalog, completed, health] = await Promise.all([api('sessions'), api(`results?after=${cursor ?? 0}&limit=100`), api('health')])
278
295
  if (disposed) return
296
+ catalog.sessions = browserSessionCatalog(ctx, catalog.sessions)
297
+ const issue = workspaceIssue(ctx)
298
+ if (issue === 'workspace_required' && state.mode !== 'off') state.fail(issue)
279
299
  for (const s of catalog.sessions) labels.set(s.session_id, s.label)
280
300
  const bootstrap = cursor === null || resultEpoch !== health.focus_epoch
281
301
  resultEpoch = health.focus_epoch
@@ -333,6 +353,7 @@ export function mountDuet(ctx) {
333
353
  tutorial?.dispose()
334
354
  audioConsent.cancel()
335
355
  ratingPanel?.dispose()
356
+ connectionHint?.dispose()
336
357
  clearInterval(timer); clearInterval(progress); clearTimeout(toastTimer)
337
358
  document.removeEventListener('visibilitychange', visibility)
338
359
  window.removeEventListener('error', pageError)
@@ -0,0 +1,43 @@
1
+ /** A brief, non-modal invitation after the microphone is actually ready. */
2
+ export function mountConnectionHint(controls, { duration = 8000 } = {}) {
3
+ const hint = document.createElement('div')
4
+ hint.dataset.duetConnectionHint = ''
5
+ hint.setAttribute('role', 'status')
6
+ hint.setAttribute('aria-live', 'polite')
7
+ hint.hidden = true
8
+ hint.style.cssText = 'position:absolute;bottom:calc(100% + 10px);left:0;z-index:9998;box-sizing:border-box;width:268px;max-width:calc(100vw - 32px);padding:12px 15px;border:1px solid #a5d8f4;border-radius:12px;background:#eff9ff;color:#163c56;font:13px/1.65 system-ui,sans-serif;box-shadow:0 8px 28px #153e6524;pointer-events:none'
9
+ hint.textContent = '连接成功,可以试试对我说“你好”。'
10
+ const arrow = document.createElement('span')
11
+ arrow.setAttribute('aria-hidden', 'true')
12
+ arrow.style.cssText = 'position:absolute;bottom:-6px;width:10px;height:10px;transform:rotate(45deg);background:#eff9ff;border-right:1px solid #a5d8f4;border-bottom:1px solid #a5d8f4'
13
+ hint.append(arrow)
14
+ controls.append(hint)
15
+ let wasReady = false, timer, disposed = false
16
+ const hide = () => { hint.hidden = true; clearTimeout(timer) }
17
+ const dismiss = event => { if (event.type !== 'keydown' || event.key === 'Escape') hide() }
18
+ controls.addEventListener('pointerdown', dismiss)
19
+ document.addEventListener('keydown', dismiss)
20
+ return {
21
+ dismiss: hide,
22
+ update({ mode, ready, teaching = false }) {
23
+ if (disposed) return
24
+ const active = mode === 'online' && ready
25
+ if (!active || teaching) hide()
26
+ if (active && !wasReady && !teaching) {
27
+ const button = controls.querySelector('[data-voice=mic]')
28
+ arrow.style.left = `${Math.max(16, Math.min(244, (button?.offsetLeft || 32) + (button?.offsetWidth || 30) / 2 - 5))}px`
29
+ hint.hidden = false
30
+ clearTimeout(timer)
31
+ timer = setTimeout(hide, duration)
32
+ }
33
+ wasReady = active
34
+ },
35
+ dispose() {
36
+ disposed = true
37
+ hide()
38
+ controls.removeEventListener('pointerdown', dismiss)
39
+ document.removeEventListener('keydown', dismiss)
40
+ hint.remove()
41
+ },
42
+ }
43
+ }
@@ -5,7 +5,7 @@ window.__ModuleLoader__.load({
5
5
  const exports = module.exports
6
6
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" })
7
7
 
8
- const inject = ["sessions", "conversation", "uiSession"]
8
+ const inject = ["sessions", "conversation", "uiSession", "workspaces"]
9
9
 
10
10
  function apply(ctx) {
11
11
  const focusedSession = () => {
@@ -31,7 +31,7 @@ window.__ModuleLoader__.load({
31
31
  ctx.effect(() => {
32
32
  let active = true
33
33
  let dispose
34
- import('/duet/assets/client/browser.mjs?v=0.1.1').then(module => {
34
+ import('/duet/assets/client/browser.mjs?v=0.1.2').then(module => {
35
35
  if (active) dispose = module.mountDuet(ctx)
36
36
  }).catch(error => console.warn('duet controls could not load:', error))
37
37
  return () => { active = false; dispose?.() }
@@ -1,7 +1,9 @@
1
1
  /** Use the same pending objects as DSH's clickable question/approval cards. */
2
2
  export function nativeInteractions(ctx) {
3
3
  const firstSeen = new WeakMap()
4
- const pending = () => [...ctx.uiSession.pendingInteractions.getSnapshot().values()]
4
+ const pending = () => ctx.uiSession.sessionStatus
5
+ ? [...ctx.uiSession.sessionStatus.getSnapshot().values()].map(row => row.pendingInteraction).filter(Boolean)
6
+ : [...ctx.uiSession.pendingInteractions.getSnapshot().values()]
5
7
  const publicValue = value => {
6
8
  if (!firstSeen.has(value)) firstSeen.set(value, Date.now() / 1000)
7
9
  return { id: value.key, session_id: value.sessionId, created_at: firstSeen.get(value),
@@ -20,12 +20,13 @@ export function validateRPC(request) {
20
20
  }
21
21
 
22
22
  export class HarnessRPCExecutor {
23
- constructor(send, fetchImpl = fetch, diagnostic = () => {}, localComposer = null) {
23
+ constructor(send, fetchImpl = fetch, diagnostic = () => {}, localComposer = null, catalogOrder = rows => orderSessionCatalog(rows, readWorkspaceView())) {
24
24
  // Native Window.fetch rejects an RPCExecutor receiver (Illegal invocation).
25
25
  // Call the captured function plainly, not as an instance method.
26
26
  this.send = send; this.fetch = (...args) => fetchImpl(...args); this.closed = false
27
27
  this.diagnostic = diagnostic
28
28
  this.localComposer = localComposer
29
+ this.catalogOrder = catalogOrder
29
30
  this.connectionId = null; this.seen = new Map(); this.retired = new Set(); this.controllers = new Set()
30
31
  }
31
32
 
@@ -84,7 +85,7 @@ export class HarnessRPCExecutor {
84
85
  if (response.status === 200 && request.path === '/api/sessions' && Array.isArray(body.sessions)) {
85
86
  // Both startup prompt and nth_N resolution read this same browser-local
86
87
  // order, including manual drag order; archived rows cannot consume ranks.
87
- body.sessions = orderSessionCatalog(body.sessions, readWorkspaceView())
88
+ body.sessions = this.catalogOrder(body.sessions)
88
89
  }
89
90
  return { ...envelope, status: response.status, body }
90
91
  } catch (error) {
@@ -85,8 +85,6 @@
85
85
  <details id="advancedConnection"><summary>连接配置</summary>
86
86
  <label for="backendUrl">服务地址</label>
87
87
  <input id="backendUrl" type="url" placeholder="wss://服务地址/ws?protocol=realtime_v2" autocomplete="off">
88
- <label for="authToken">访问密钥</label>
89
- <input id="authToken" type="password" placeholder="请输入访问密钥" autocomplete="new-password" spellcheck="false">
90
88
  <div class="row"><button id="saveDuet" disabled>保存连接配置</button></div>
91
89
  <div id="settingsMessage" role="status" style="margin-top:10px"></div>
92
90
  </details>
@@ -304,8 +302,6 @@
304
302
  if (fill) {
305
303
  settingsRevision = config.revision;
306
304
  $('backendUrl').value = config.backend_url || '';
307
- $('authToken').value = '';
308
- $('authToken').placeholder = config.token_placeholder;
309
305
  }
310
306
  const c = config.connection || {};
311
307
  $('duetMark').style.color = c.online || c.tts_only ? '#7fd6a6' : '#ed9b35';
@@ -337,7 +333,7 @@
337
333
  $('saveDuet').onclick = async () => {
338
334
  $('saveDuet').disabled = true;
339
335
  try {
340
- await api('/voice/config', {method:'PUT', headers:{'Content-Type':'application/json','X-Duplex-Settings':'1'}, body:JSON.stringify({backend_url:$('backendUrl').value.trim(), auth_token:$('authToken').value, revision:settingsRevision})});
336
+ await api('/voice/config', {method:'PUT', headers:{'Content-Type':'application/json','X-Duplex-Settings':'1'}, body:JSON.stringify({backend_url:$('backendUrl').value.trim(), revision:settingsRevision})});
341
337
  $('settingsMessage').textContent = '配置已保存;如需语音,请在 DSH 主页面重新打开。';
342
338
  await loadDuetConfig(true);
343
339
  } catch (error) { $('settingsMessage').textContent = debugEnabled ? `保存失败:${error.message}` : '保存失败,请稍后重试。'; }
@@ -370,7 +366,7 @@
370
366
  }
371
367
  $('openTutorial').onclick = async () => {
372
368
  try {
373
- const {requestTutorial} = await import('/duet/assets/client/tutorial-request.mjs?v=0.1.1');
369
+ const {requestTutorial} = await import('/duet/assets/client/tutorial-request.mjs?v=0.1.2');
374
370
  requestTutorial(localStorage);
375
371
  $('tutorialStatus').textContent = '请回到 DSH 页面继续教学。';
376
372
  } catch { $('tutorialStatus').textContent = '暂时无法打开教学,请允许浏览器存储后重试。'; }
@@ -379,11 +375,11 @@
379
375
  setInterval(() => { loadDuetConfig().catch(() => { $('duetConnection').textContent = '语音连接信息不可用'; }); }, 2000);
380
376
  void loadNotices();
381
377
  setInterval(loadNotices, 60000);
382
- import('/duet/assets/client/shortcuts.mjs?v=0.1.1').then(({mountShortcutSettings}) => {
378
+ import('/duet/assets/client/shortcuts.mjs?v=0.1.2').then(({mountShortcutSettings}) => {
383
379
  const dispose = mountShortcutSettings({speaker:$('speakerShortcut'),mic:$('micShortcut'),clearSpeaker:$('clearSpeakerShortcut'),clearMic:$('clearMicShortcut'),status:$('shortcutStatus')});
384
380
  window.addEventListener('pagehide', e => {if(!e.persisted)dispose()}, {once:true});
385
381
  }).catch(() => { $('shortcutStatus').textContent = '暂时无法加载快捷键设置,请刷新重试。'; });
386
- import('/duet/assets/client/microphone.mjs?v=0.1.1').then(({mountMicrophoneSettings}) => {
382
+ import('/duet/assets/client/microphone.mjs?v=0.1.2').then(({mountMicrophoneSettings}) => {
387
383
  const dispose = mountMicrophoneSettings({select:$('microphoneDevice'),refresh:$('refreshMicrophones'),status:$('microphoneStatus')});
388
384
  window.addEventListener('pagehide', dispose, {once:true});
389
385
  }).catch(() => { $('microphoneStatus').textContent = '暂时无法加载麦克风设置,请刷新重试。'; });
@@ -1,6 +1,7 @@
1
1
  /** DSH browser services plus existing voice connection; never opens a microphone. */
2
- import { PLUGIN_VERSION } from '../shared/state.mjs?v=0.1.1'
3
- import { focusedSession } from './composer.mjs?v=0.1.1'
2
+ import { PLUGIN_VERSION } from '../shared/state.mjs?v=0.1.2'
3
+ import { focusedSession } from './composer.mjs?v=0.1.2'
4
+ import { requireWorkspace } from './workspaces.mjs?v=0.1.2'
4
5
  export function tutorialAdapter(ctx, state, audio, pollReady) {
5
6
  let narration
6
7
  const completed = new Map()
@@ -41,6 +42,7 @@ export function tutorialAdapter(ctx, state, audio, pollReady) {
41
42
  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)}},
42
43
  unlock:()=>audio.prepare(),
43
44
  async create(name,signal){
45
+ requireWorkspace(ctx)
44
46
  const catalog=await api('sessions',signal), cwd=catalog.sessions.find(s=>s.session_id===current())?.cwd
45
47
  const d=await api('sessions',signal,'POST',{name,...(cwd?{cwd}:{})});return d.session.session_id
46
48
  },
@@ -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.1'
2
+ import {consumeTutorialRequest} from './tutorial-request.mjs?v=0.1.2'
3
3
  export const TUTORIAL_KEY = 'dsh-duplex-tutorial-v1'
4
4
  export const QUESTION = '什么是语音交互?请用一句话简单解释,不使用工具。'
5
5
  export const INPUT = '用一句话介绍语音助手。'
@@ -0,0 +1,25 @@
1
+ /** Workspace readiness and browser-local session ordering shared by all voice paths. */
2
+ import { orderSessionCatalog, readWorkspaceView } from '../shared/catalog.mjs'
3
+ import { focusedSession } from './composer.mjs'
4
+
5
+ export function workspaceIssue(ctx) {
6
+ const snapshot = ctx.workspaces?.list?.getSnapshot()
7
+ if (!snapshot || snapshot.phase !== 'ready' || snapshot.state === 'loading') return 'workspace_loading'
8
+ if (snapshot.state === 'error') return 'workspace_unavailable'
9
+ return snapshot.items.length ? null : 'workspace_required'
10
+ }
11
+
12
+ export function requireWorkspace(ctx) {
13
+ const issue = workspaceIssue(ctx)
14
+ if (issue) throw Error(issue)
15
+ }
16
+
17
+ export function browserSessionCatalog(ctx, rows) {
18
+ const snapshot = ctx.sessions.list.getSnapshot()
19
+ const active = focusedSession(ctx)
20
+ const archived = new Set(ctx.workspaces?.list?.getSnapshot().archivedSessionIds || [])
21
+ return orderSessionCatalog(rows.filter(row => !archived.has(row.session_id)).map(row => ({
22
+ ...row, active: row.session_id === active,
23
+ updated_at: snapshot.byId?.[row.session_id]?.updatedAt ?? row.updated_at,
24
+ })), readWorkspaceView())
25
+ }
@@ -6,6 +6,8 @@ const modules = {
6
6
  interactions: 'client/interactions', tutorial: 'client/tutorial',
7
7
  tutorial_adapter: 'client/tutorial-adapter', tutorial_request: 'client/tutorial-request',
8
8
  feedback: 'client/feedback', consent: 'client/consent',
9
+ connection_hint: 'client/connection-hint',
10
+ workspaces: 'client/workspaces',
9
11
  }
10
12
  const aliases = {
11
13
  state: 'DuetState as VoiceState', audio: 'DuetAudio as VoiceAudio',
@@ -173,7 +173,7 @@ export function apply(ctx, options = {}) {
173
173
  const feedbackStore = options.feedbackStore ?? (options.feedbackDisabled ? null : new RemoteFeedback(()=>settings.effective(),{keyPath:options.feedbackIdentityPath}))
174
174
  const feedback = new FeedbackService(feedbackStore)
175
175
  let duetProxy
176
- ctx.effect(() => { duetProxy = registerDuetProxy(ctx, voice, feedback); return duetProxy })
176
+ ctx.effect(() => { duetProxy = registerDuetProxy(ctx, voice, feedback, () => (ctx.workspaceRegistry.list?.() || []).length > 0); return duetProxy })
177
177
 
178
178
  ctx.effect(() => () => { hostAbort.abort() })
179
179
 
@@ -2,8 +2,9 @@
2
2
  import { createRequire } from 'node:module'
3
3
  import { DuetTrace } from './trace.mjs'
4
4
  import { duetEnv } from './environment.mjs'
5
+ import { DEFAULT_DUET_URL, publicServiceAuthorization } from './service-defaults.mjs'
6
+ export { DEFAULT_DUET_URL } from './service-defaults.mjs'
5
7
  const require = createRequire(import.meta.url)
6
- export const DEFAULT_DUET_URL = 'ws://duet-router.1781574661016173.ap-southeast-1.pai-eas.aliyuncs.com/ws?protocol=realtime_v2'
7
8
 
8
9
  export function compatibleVersion(version, min = '0.1.0', maxExclusive = '0.2.0') {
9
10
  const parse = v => /^\d+\.\d+\.\d+$/.test(v || '') ? v.split('.').map(Number) : null
@@ -13,15 +14,16 @@ export function compatibleVersion(version, min = '0.1.0', maxExclusive = '0.2.0'
13
14
  }
14
15
 
15
16
  export function duetConfig(env = process.env) {
17
+ const endpoints = {
18
+ online: duetEnv('ONLINE_URL', env) || duetEnv('URL', env) || DEFAULT_DUET_URL,
19
+ tts_only: duetEnv('TTS_ONLY_URL', env) || duetEnv('URL', env) || DEFAULT_DUET_URL,
20
+ }
16
21
  return {
17
22
  min_version: duetEnv('MIN_VERSION', env) || '0.1.0',
18
23
  max_version_exclusive: duetEnv('MAX_VERSION_EXCLUSIVE', env) || '0.2.0',
19
24
  control_transport: duetEnv('CONTROL_TRANSPORT', env) || 'client_rpc_v1',
20
- authorization: duetEnv('AUTHORIZATION', env) || '',
21
- endpoints: {
22
- online: duetEnv('ONLINE_URL', env) || duetEnv('URL', env) || DEFAULT_DUET_URL,
23
- tts_only: duetEnv('TTS_ONLY_URL', env) || duetEnv('URL', env) || DEFAULT_DUET_URL,
24
- },
25
+ authorization: publicServiceAuthorization(endpoints),
26
+ endpoints,
25
27
  }
26
28
  }
27
29
 
@@ -42,7 +44,7 @@ export function externalWithState(message, _state) {
42
44
  ...(source === undefined ? {} : { source: { ...source } }) }
43
45
  }
44
46
 
45
- export function registerDuetProxy(ctx, config = duetConfig(), feedback = null) {
47
+ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, canUseVoice = () => true) {
46
48
  if (!['http', 'client_rpc_v1'].includes(config.control_transport || 'http')) throw new Error('invalid_harness_transport')
47
49
  if (!compatibleVersion(config.min_version, config.min_version, config.max_version_exclusive)) throw new Error('invalid_plugin_version_policy')
48
50
  for (const target of Object.values(config.endpoints)) {
@@ -92,6 +94,7 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null) {
92
94
  const mode = params.get('mode')
93
95
  if (!compatibleVersion(params.get('plugin_version'), config.min_version, config.max_version_exclusive)) { fail('plugin_upgrade_required'); return }
94
96
  if (!['online', 'tts_only'].includes(mode)) { fail('invalid_voice_mode'); return }
97
+ if (!canUseVoice()) { fail('workspace_required'); return }
95
98
  connections.set(front, { mode, ready: false, trace })
96
99
  front.on('close', () => connections.delete(front))
97
100
  const target = config.endpoints[mode]
@@ -0,0 +1,12 @@
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'
3
+ export const PUBLIC_TRIAL_AUTHORIZATION = "ZTZhZWI4YzA3ODcyZWI2NzZhZjU4MDk3NGE3NGUxODQ2MjgxYWVjYQ=="
4
+
5
+ /** Never forward the trial credential to a user-selected third-party service. */
6
+ export function publicServiceAuthorization(endpoints) {
7
+ const urls = Object.values(endpoints)
8
+ return urls.length && urls.every(value => {
9
+ const url = new URL(value), expected = new URL(DEFAULT_DUET_URL)
10
+ return url.origin === expected.origin && url.pathname === expected.pathname && !url.username && !url.password
11
+ }) ? PUBLIC_TRIAL_AUTHORIZATION : ''
12
+ }
@@ -1,16 +1,17 @@
1
- /** Host-only settings. Never return stored credentials to the browser. */
1
+ /** Host-only endpoint settings; trial authentication comes from the package. */
2
2
  import { readFileSync } from 'node:fs'
3
3
  import { mkdir, writeFile, rename, unlink } from 'node:fs/promises'
4
4
  import { dirname, join } from 'node:path'
5
5
  import { homedir } from 'node:os'
6
6
  import { randomUUID } from 'node:crypto'
7
7
  import { duetEnv } from './environment.mjs'
8
+ import { publicServiceAuthorization } from './service-defaults.mjs'
8
9
 
9
10
  export function validateBackendURL(value, insecureOrigin = null) {
10
11
  if (typeof value !== 'string' || value.length > 2048) throw new Error('invalid_backend_url')
11
12
  const url = new URL(value)
12
13
  if (!['ws:', 'wss:'].includes(url.protocol) || url.username || url.password || url.hash) throw new Error('invalid_backend_url')
13
- // Credentials belong in the host-only token field, never in URLs or logs.
14
+ // Credentials never belong in URLs or logs.
14
15
  if ([...url.searchParams.keys()].some(k => k !== 'protocol')) throw new Error('backend_url_query_not_allowed')
15
16
  if (url.protocol === 'ws:' && !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) && url.origin !== insecureOrigin) throw new Error('backend_requires_wss')
16
17
  return url.toString()
@@ -33,15 +34,14 @@ export class DuetSettings {
33
34
  validate(data) {
34
35
  if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('invalid_voice_settings')
35
36
  const backend_url = validateBackendURL(data.backend_url, data.insecure_origin)
36
- const auth_token = data.auth_token
37
- if (typeof auth_token !== 'string' || auth_token.length > 8192 || /[\r\n\0]/.test(auth_token)) throw new Error('invalid_auth_token')
38
37
  const url = new URL(backend_url)
39
38
  const insecure_origin = url.protocol === 'ws:' && url.origin === data.insecure_origin ? url.origin : null
40
- return { backend_url, auth_token: auth_token || 'test', ...(insecure_origin ? { insecure_origin } : {}) }
39
+ return { backend_url, ...(insecure_origin ? { insecure_origin } : {}) }
41
40
  }
42
41
 
43
42
  effective() {
44
- return this.saved ? { ...this.base, endpoints: { online: this.saved.backend_url, tts_only: this.saved.backend_url }, authorization: this.saved.auth_token === 'test' ? '' : this.saved.auth_token } : this.base
43
+ const endpoints = this.saved ? { online: this.saved.backend_url, tts_only: this.saved.backend_url } : this.base.endpoints
44
+ return { ...this.base, endpoints, authorization: publicServiceAuthorization(endpoints) }
45
45
  }
46
46
 
47
47
  public() {
@@ -56,7 +56,7 @@ export class DuetSettings {
56
56
  min_version: config.min_version, max_version_exclusive: config.max_version_exclusive,
57
57
  modes: Object.keys(config.endpoints), endpoints,
58
58
  backend_url: endpoints.online, config_source: this.saved ? 'plugin_settings' : 'environment_or_default',
59
- auth_configured: Boolean(config.authorization), token_placeholder: config.authorization ? '已保存;留空保持不变' : '请输入访问密钥',
59
+ auth_configured: Boolean(config.authorization),
60
60
  debug: this.debug, revision: this.revision,
61
61
  insecure_transport: new URL(config.endpoints.online).protocol !== 'wss:',
62
62
  }
@@ -65,15 +65,10 @@ export class DuetSettings {
65
65
  async save(input) {
66
66
  if (this.writing) throw new Error('settings_write_in_progress')
67
67
  if (!input || input.revision !== this.revision) throw new Error('settings_revision_conflict')
68
- const current = this.effective()
69
68
  // A deliberate, authenticated per-origin opt-in, never a global TLS bypass.
70
69
  const insecureOrigin = input.allow_insecure_http === true ? new URL(input.backend_url).origin : this.saved?.insecure_origin
71
70
  const url = validateBackendURL(input.backend_url, insecureOrigin)
72
- // Never send a retained credential to a newly selected server.
73
- const token = input.auth_token === '' || input.auth_token === undefined
74
- ? url === current.endpoints.online ? current.authorization || 'test' : 'test'
75
- : input.auth_token
76
- const next = this.validate({ backend_url: url, auth_token: token, insecure_origin: insecureOrigin })
71
+ const next = this.validate({ backend_url: url, insecure_origin: insecureOrigin })
77
72
  this.writing = true
78
73
  const temp = `${this.path}.${randomUUID()}.tmp`
79
74
  try {
@@ -19,10 +19,21 @@ function reconcile(rows, ids) {
19
19
  export function orderSessionCatalog(rows, view = {}) {
20
20
  const visible = rows.filter(row => !row.archived && row.origin !== 'subagent' && (!row.blank || row.active))
21
21
  const accounts = view?.sessionOrderByAccount || {}
22
+ // 0.1.5 persists the effective activity-promoted order; 0.1.6 derives recency
23
+ // live and keeps stored orders only for manual mode (same v5 storage key).
24
+ const legacy = Object.hasOwn(view, 'sessionUpdatedAtByAccount')
25
+ const recent = members => [...members].sort((a,b) => (b.updated_at || 0) - (a.updated_at || 0)
26
+ || (String(a.session_id) < String(b.session_id) ? -1 : 1))
27
+ const ordered = (members, key) => {
28
+ const stored = accounts[key]
29
+ const updated = (view.orderBy || 'updated') === 'updated'
30
+ const result = updated && (!legacy || !Array.isArray(stored))
31
+ ? recent(members) : reconcile(members, stored)
32
+ if (legacy) return result
33
+ return [...result.filter(row => row.blank && row.active), ...result.filter(row => !row.blank || !row.active)]
34
+ }
22
35
  if (view?.groupBy === 'flat') {
23
- const recent = [...visible].sort((a,b) => (b.updated_at || 0) - (a.updated_at || 0)
24
- || String(a.session_id).localeCompare(String(b.session_id)))
25
- return reconcile(recent, accounts.__flat_session_order__)
36
+ return ordered(visible, '__flat_session_order__')
26
37
  }
27
38
  const groups = new Map()
28
39
  for (const row of visible) {
@@ -30,7 +41,7 @@ export function orderSessionCatalog(rows, view = {}) {
30
41
  if (!groups.has(key)) groups.set(key, [])
31
42
  groups.get(key).push(row)
32
43
  }
33
- return [...groups].flatMap(([key, members]) => reconcile(members, accounts[key]))
44
+ return [...groups].flatMap(([key, members]) => ordered(members, key))
34
45
  }
35
46
 
36
47
  export function buildSessionCatalog(items, {workspaces = [], archivedIds = [], activeId, includeBlank = false} = {}) {
@@ -1,5 +1,5 @@
1
1
  /** Desired voice mode is independent of a temporarily suspended connection. */
2
- export const PLUGIN_VERSION = '0.1.1'
2
+ export const PLUGIN_VERSION = '0.1.2'
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 : ''
@@ -105,6 +105,9 @@ export class DuetState {
105
105
  return
106
106
  }
107
107
  const policyNotices = {
108
+ workspace_required: '请先在 DSH 中创建 workspace,再开启 duet。',
109
+ workspace_loading: '正在加载 workspace,请稍后再试。',
110
+ workspace_unavailable: '无法读取 workspace,请刷新 DSH 后重试。',
108
111
  microphone_unavailable: '无法使用所选麦克风,请在设置中检查设备与浏览器权限',
109
112
  interaction_mode_unavailable: '交互模式暂时不可用,请稍后再试',
110
113
  broadcast_mode_unavailable: '播报模式暂时不可用,请稍后再试',