dsh-duet 0.2.0 → 0.2.1

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.2.0",
3
+ "version": "0.2.1",
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/entry-loading.mjs && node tests/browser/settings.mjs && node tests/browser/tutorial.mjs && node tests/browser/feedback.mjs && node tests/browser/connection-hint.mjs && node tests/browser/controls-layout.mjs && node tests/browser/resilience.mjs && node tests/browser/page-binding.mjs && node tests/browser/stop-task.mjs && node tests/browser/desktop-settings.mjs && node tests/browser/desktop-identity.mjs && node tests/browser/audio-interruption.mjs",
25
+ "test:browser": "node tests/browser/entry-loading.mjs && node tests/browser/settings.mjs && node tests/browser/tutorial.mjs && node tests/browser/feedback.mjs && node tests/browser/connection-hint.mjs && node tests/browser/update-notice.mjs && node tests/browser/voices.mjs && node tests/browser/controls-layout.mjs && node tests/browser/resilience.mjs && node tests/browser/page-binding.mjs && node tests/browser/stop-task.mjs && node tests/browser/desktop-settings.mjs && node tests/browser/desktop-identity.mjs && node tests/browser/audio-interruption.mjs",
26
26
  "test:host": "node tests/host/isolated-host.mjs",
27
27
  "build:avatar": "node scripts/build-avatar.mjs",
28
28
  "build:avatar:desktop": "node scripts/build-avatar-desktop.mjs",
@@ -1,4 +1,4 @@
1
- import { microphoneConstraints } from './microphone.mjs?v=0.2.0'
1
+ import { microphoneConstraints } from './microphone.mjs?v=0.2.1'
2
2
  import { captionCue, captionAt, AudioCaptionTimeline } from '../shared/avatar.mjs'
3
3
 
4
4
  export const AUDIO_STOP_PROTOCOL = 'audio_stop_candidates_v1'
@@ -1,26 +1,26 @@
1
- import { DuetState, PLUGIN_VERSION } from '../shared/state.mjs?v=0.2.0'
2
- import { DuetAudio, AUDIO_STOP_PROTOCOL } from './audio.mjs?v=0.2.0'
3
- import { HarnessRPCExecutor, rpcNavigationSession } from './rpc.mjs?v=0.2.0'
4
- import { composerAccess, observeComposer, focusedSession, openLocalSession } from './composer.mjs?v=0.2.0'
5
- import { startComposerBridge } from './composer-bridge.mjs?v=0.2.0'
6
- import { mountTutorial } from './tutorial.mjs?v=0.2.0'
1
+ import { DuetState, PLUGIN_VERSION } from '../shared/state.mjs?v=0.2.1'
2
+ import { DuetAudio, AUDIO_STOP_PROTOCOL } from './audio.mjs?v=0.2.1'
3
+ import { HarnessRPCExecutor, rpcNavigationSession } from './rpc.mjs?v=0.2.1'
4
+ import { composerAccess, observeComposer, focusedSession, openLocalSession } from './composer.mjs?v=0.2.1'
5
+ import { startComposerBridge } from './composer-bridge.mjs?v=0.2.1'
6
+ import { mountTutorial } from './tutorial.mjs?v=0.2.1'
7
7
  import { mountAvatarTasks } from './avatar-tasks.mjs'
8
- import { tutorialAdapter } from './tutorial-adapter.mjs?v=0.2.0'
9
- import { mountRating } from './feedback.mjs?v=0.2.0'
10
- import { createAudioUploadConsent } from './consent.mjs?v=0.2.0'
11
- import { bindDuetShortcuts } from './shortcuts.mjs?v=0.2.0'
12
- import { nativeInteractions } from './interactions.mjs?v=0.2.0'
13
- import { mountConnectionHint } from './connection-hint.mjs?v=0.2.0'
14
- import { mountControlsLayout } from './controls-layout.mjs?v=0.2.0'
15
- import { mountNotice } from './notice.mjs?v=0.2.0'
16
- import { workspaceIssue, requireWorkspace, browserSessionCatalog, sessionCreationPayload } from './workspaces.mjs?v=0.2.0'
17
- import { voiceSocketUrl, bindSettingsLink } from './transport.mjs?v=0.2.0'
18
- import { identityFetch, identityVoiceProtocols } from './identity.mjs?v=0.2.0'
19
- import { sessionLabel } from '../shared/catalog.mjs?v=0.2.0'
20
- import { resultNotification } from '../shared/result-notification.mjs?v=0.2.0'
21
- import { HarnessSync } from './harness-sync.mjs?v=0.2.0'
22
- import { LocalSync } from './local-sync.mjs?v=0.2.0'
23
- import { diagnosticPayload } from '../shared/diagnostics.mjs?v=0.2.0'
8
+ import { tutorialAdapter } from './tutorial-adapter.mjs?v=0.2.1'
9
+ import { mountRating } from './feedback.mjs?v=0.2.1'
10
+ import { createAudioUploadConsent } from './consent.mjs?v=0.2.1'
11
+ import { bindDuetShortcuts } from './shortcuts.mjs?v=0.2.1'
12
+ import { nativeInteractions } from './interactions.mjs?v=0.2.1'
13
+ import { mountConnectionHint } from './connection-hint.mjs?v=0.2.1'
14
+ import { mountControlsLayout } from './controls-layout.mjs?v=0.2.1'
15
+ import { mountNotice } from './notice.mjs?v=0.2.1'
16
+ import { workspaceIssue, requireWorkspace, browserSessionCatalog, sessionCreationPayload } from './workspaces.mjs?v=0.2.1'
17
+ import { voiceSocketUrl, bindSettingsLink } from './transport.mjs?v=0.2.1'
18
+ import { identityFetch, identityVoiceProtocols } from './identity.mjs?v=0.2.1'
19
+ import { sessionLabel } from '../shared/catalog.mjs?v=0.2.1'
20
+ import { resultNotification } from '../shared/result-notification.mjs?v=0.2.1'
21
+ import { HarnessSync } from './harness-sync.mjs?v=0.2.1'
22
+ import { LocalSync } from './local-sync.mjs?v=0.2.1'
23
+ import { diagnosticPayload } from '../shared/diagnostics.mjs?v=0.2.1'
24
24
  import { mountAvatar } from './avatar.mjs'
25
25
  import { mountAvatarSurfaces } from './avatar-surfaces.mjs'
26
26
  import { audioUnlockPanel } from '../shared/avatar-ui.mjs'
@@ -53,10 +53,10 @@ export function mountDuet(ctx) {
53
53
  const pageError = event => diagnostic({ event: 'browser.error', message: String(event.message || event.reason?.message || event.reason), stack: event.error?.stack || event.reason?.stack })
54
54
  window.addEventListener('error', pageError)
55
55
  window.addEventListener('unhandledrejection', pageError)
56
- const notice = (text, { upgrade = false } = {}) => {
56
+ const notice = (text, { upgrade = false, releaseNotes } = {}) => {
57
57
  connectionHint?.dismiss()
58
58
  if (upgrade) { ratingPanel?.dispose(); ratingPanel = null }
59
- notices.show(text, { upgrade })
59
+ notices.show(text, { upgrade, releaseNotes })
60
60
  }
61
61
  const draw = state => {
62
62
  if (pollGeneration !== state.generation) {
@@ -196,6 +196,7 @@ export function mountDuet(ctx) {
196
196
  try {
197
197
  message = JSON.parse(event.data)
198
198
  if (resultPush.event(message)) return
199
+ if(message.type==='voice.policy'){receive(message);return}
199
200
  if (message.type === 'harness.rpc.request') {
200
201
  if (mode !== 'online') throw new Error('harness_rpc_requires_online')
201
202
  await rpc.execute(message)
@@ -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.2.0'
2
+ import { focusedSession as currentSession } from './composer.mjs?v=0.2.1'
3
3
 
4
4
  export function startComposerBridge(ctx, clientId, fetchImpl = fetch, feed = null, onWrite = () => {}) {
5
5
  const focusedSession = () => currentSession(ctx)
@@ -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.2.0'
2
+ import {normalizeGuidance} from '../shared/connection-guidance.mjs?v=0.2.1'
3
3
  export function mountConnectionHint(controls, { duration = 8000, onShown = ()=>{} } = {}) {
4
4
  const hint = document.createElement('div')
5
5
  hint.dataset.duetConnectionHint = ''
@@ -13,7 +13,7 @@ window.__ModuleLoader__.load({
13
13
  ctx.effect(() => {
14
14
  let active = true
15
15
  let dispose
16
- import('/duet/assets/client/browser.mjs?v=0.2.0').then(module => {
16
+ import('/duet/assets/client/browser.mjs?v=0.2.1').then(module => {
17
17
  if (active) dispose = module.mountDuet(ctx)
18
18
  }).catch(error => {
19
19
  console.warn('duet controls could not load:', error)
@@ -1,5 +1,5 @@
1
1
  /** Optional, explicit rating; never opens voice or submits without a user click. */
2
- import { identityFetch } from './identity.mjs?v=0.2.0'
2
+ import { identityFetch } from './identity.mjs?v=0.2.1'
3
3
 
4
4
  export function mountRating(anchor, sessionTicket, {origin='page'} = {}) {
5
5
  if(!sessionTicket)return null
@@ -1,5 +1,5 @@
1
1
  import { IDENTITY_HEADER, IDENTITY_TRANSPORT_HEADER, IDENTITY_TRANSPORT, IDENTITY_STORAGE,
2
- VOICE_PROTOCOL, IDENTITY_PROTOCOL_PREFIX, validIdentityToken } from '../shared/identity.mjs?v=0.2.0'
2
+ VOICE_PROTOCOL, IDENTITY_PROTOCOL_PREFIX, validIdentityToken } from '../shared/identity.mjs?v=0.2.1'
3
3
 
4
4
  /** Desktop strips plugin cookies. Keep the Host-signed value in its origin storage. */
5
5
  export function createIdentityClient(globals = globalThis) {
@@ -10,7 +10,7 @@ export function createIdentityClient(globals = globalThis) {
10
10
  }
11
11
  async function fetchIdentity(path, options = {}) {
12
12
  if (!desktop()) return globals.fetch(path, options)
13
- if (!['/duplex-control/api/voice/config', '/duplex-control/api/feedback', '/duplex-control/api/duet/nickname', '/duplex-control/api/avatar/activity'].includes(path)) {
13
+ if (!['/duplex-control/api/voice/config', '/duplex-control/api/voices', '/duplex-control/api/feedback', '/duplex-control/api/duet/nickname', '/duplex-control/api/avatar/activity'].includes(path)) {
14
14
  return globals.fetch(path, options)
15
15
  }
16
16
  const config = path.endsWith('/voice/config') && (!options.method || options.method === 'GET')
@@ -6,7 +6,7 @@ export function mountNotice(anchor) {
6
6
  panel.setAttribute('role', 'status')
7
7
  panel.setAttribute('aria-live', 'polite')
8
8
  panel.hidden = true
9
- panel.style.cssText = 'position:fixed;z-index:100021;box-sizing:border-box;width:280px;max-width:calc(100vw - 24px);max-height:calc(100vh - 24px);overflow:auto;background:#252c38;color:white;padding:14px;border:1px solid #52647d;border-radius:12px;font:13px/1.6 system-ui;box-shadow:0 8px 28px #0005;overflow-wrap:anywhere'
9
+ panel.style.cssText = 'position:fixed;z-index:100021;box-sizing:border-box;width:320px;max-width:calc(100vw - 24px);max-height:calc(100vh - 24px);overflow:auto;background:#eff9ff;color:#163c56;padding:16px;border:1px solid #a5d8f4;border-radius:12px;font:13px/1.65 system-ui,sans-serif;box-shadow:0 8px 28px #153e6524;overflow-wrap:anywhere'
10
10
  document.body.append(panel)
11
11
  let timer, disposed = false
12
12
  const hide = () => { panel.hidden = true; clearTimeout(timer) }
@@ -26,20 +26,35 @@ export function mountNotice(anchor) {
26
26
  const observer = new ResizeObserver(position)
27
27
  observer.observe(panel)
28
28
  return {
29
- show(text, {upgrade = false} = {}) {
29
+ show(text, {upgrade = false, releaseNotes} = {}) {
30
30
  if (disposed) return
31
31
  clearTimeout(timer); panel.textContent = text; panel.hidden = false
32
32
  if (upgrade) {
33
+ panel.textContent = ''
34
+ const heading=document.createElement('strong');heading.textContent='更新 duet';heading.style.cssText='display:block;font-size:15px;margin-bottom:6px'
35
+ const message=document.createElement('p');message.textContent=text;message.style.cssText='margin:0 0 12px'
36
+ panel.append(heading,message)
37
+ if(typeof releaseNotes==='string' && releaseNotes.trim()){
38
+ const label=document.createElement('strong');label.textContent='更新内容';label.style.fontSize='12px'
39
+ const notes=document.createElement('p');notes.dataset.duetReleaseNotes='';notes.textContent=releaseNotes.slice(0,1000).trim()
40
+ notes.style.cssText='white-space:pre-wrap;margin:6px 0 14px;padding:10px 12px;border-radius:8px;background:#ffffffa8'
41
+ panel.append(label,notes)
42
+ }
33
43
  const help = document.createElement('details'), title = document.createElement('summary')
44
+ help.style.cssText='border-top:1px solid #a5d8f4;padding-top:10px'
45
+ title.style.cssText='cursor:pointer;font-weight:600'
34
46
  title.textContent = '如何升级'; help.append(title)
35
47
  const before = document.createElement('p'), command = document.createElement('code'), after = document.createElement('p')
36
48
  before.textContent = '通过 npm 安装的用户,可在终端运行:'
37
49
  command.textContent = 'dsh plugin --profile web add dsh-duet@latest'
38
- command.style.cssText = 'display:block;white-space:normal;margin:8px 0'
50
+ command.style.cssText = 'display:block;white-space:normal;margin:8px 0;padding:10px;border-radius:8px;background:#ffffffa8;user-select:text;font:12px/1.6 monospace'
39
51
  after.textContent = '其他安装方式请从原来源更新。完成后重启 DSH 并刷新页面,再手动开启语音。'
40
52
  help.append(before, command, after); panel.append(help)
41
53
  help.addEventListener('toggle', position)
42
- const close = document.createElement('button'); close.type = 'button'; close.textContent = '知道了'; close.onclick = hide; panel.append(close)
54
+ const actions=document.createElement('div');actions.style.cssText='display:flex;justify-content:flex-end;margin-top:14px'
55
+ const close = document.createElement('button'); close.type = 'button'; close.textContent = '知道了'; close.onclick = hide
56
+ close.style.cssText='font:inherit;padding:7px 15px;border-radius:8px;border:1px solid #a5d8f4;background:#dcefff;color:#185a89;cursor:pointer'
57
+ actions.append(close);panel.append(actions)
43
58
  } else timer = setTimeout(hide, 8000)
44
59
  position()
45
60
  },
@@ -97,6 +97,48 @@
97
97
  <button id="saveNickname" type="button" disabled>保存昵称</button>
98
98
  <p id="nicknameStatus" class="muted" role="status" aria-live="polite"></p>
99
99
  </section>
100
+ <section class="panel" style="margin-bottom:18px">
101
+ <h2>音色</h2>
102
+ <div id="duetVoices">
103
+ <p data-availability role="status" hidden></p>
104
+ <label for="duetVoiceChoice">选择音色</label>
105
+ <select id="duetVoiceChoice" data-choice disabled><option value="default">默认音色</option></select>
106
+ <p class="section-note">选择后,下次开启语音时生效。最多添加 5 个自定义音色。</p>
107
+ <button data-remove type="button" class="secondary" hidden>移除此音色</button>
108
+ <div data-recovery hidden>
109
+ <p data-voice-issue role="status"></p>
110
+ <div data-reupload-fields hidden>
111
+ <p class="muted">可使用本机保存的原音频重新上传;如果本机文件也已丢失,请重新选择最初上传的同一份文件。恢复不会重新识别或更改你修正过的文字。</p>
112
+ <input data-reupload-file type="file" accept="audio/wav,audio/mpeg,audio/mp4,.m4a">
113
+ <button data-reupload type="button">重新上传并恢复音色</button>
114
+ </div>
115
+ <button data-recovery-back type="button" class="secondary">返回</button>
116
+ <button data-recovery-remove type="button" class="secondary">移除此音色</button>
117
+ </div>
118
+ <div data-create hidden style="margin-top:16px;padding-top:16px;border-top:1px solid #334266">
119
+ <h3 style="margin-top:0;font-size:14px">新增音色</h3>
120
+ <div data-upload-fields>
121
+ <p class="section-note">上传一段 3–15 秒、清晰无背景音乐的 WAV、MP3 或 M4A,不超过 10 MB。</p>
122
+ <label>音色名称<input data-name maxlength="40" placeholder="例如:我的声音"></label>
123
+ <label>参考音频<input data-file type="file" accept="audio/wav,audio/mpeg,audio/mp4,.wav,.mp3,.m4a"></label>
124
+ <label><input data-consent type="checkbox" style="width:auto"> 我有权使用该音频,并同意上传用于识别和音色合成。</label>
125
+ <button data-upload type="button">上传并自动识别</button>
126
+ </div>
127
+ <div data-editor hidden>
128
+ <p data-uploaded-name></p>
129
+ <label for="duetVoiceTranscript">音频中说的话</label>
130
+ <p id="duetVoiceTextHelp" class="section-note">上传的音频中说了什么文本,如果自动识别有误请修改准确,否则影响合成效果。</p>
131
+ <textarea id="duetVoiceTranscript" data-text maxlength="400" rows="3" aria-describedby="duetVoiceTextHelp" placeholder="请填写上传音频中说的完整原话"></textarea>
132
+ <p data-recognition role="status" aria-live="polite" class="muted"></p>
133
+ <button data-refresh type="button" class="secondary" hidden>刷新识别结果</button>
134
+ <button data-save type="button">保存并使用此音色</button>
135
+ <button data-remove-draft type="button" class="secondary" style="margin-top:8px">移除此音色</button>
136
+ </div>
137
+ <button data-cancel type="button" class="secondary" style="margin-top:8px">取消</button>
138
+ </div>
139
+ <p data-status role="status" aria-live="polite"></p>
140
+ </div>
141
+ </section>
100
142
  <section class="panel" style="margin-bottom:18px">
101
143
  <h2>3D 形象</h2>
102
144
  <label><input id="avatarEnabled" type="checkbox" style="width:auto"> 打开3D形象(实验)</label>
@@ -202,7 +244,11 @@
202
244
  if(enabled||await avatarConfirm.ask())avatarSave({enabled});
203
245
  };
204
246
  window.addEventListener('pagehide',()=>{avatarConfirm.dispose();avatarChannel?.close();window.removeEventListener('storage',avatarStorage);},{once:true});
205
- import { identityFetch } from '/duet/assets/client/identity.mjs?v=0.2.0';
247
+ import { identityFetch } from '/duet/assets/client/identity.mjs?v=0.2.1';
248
+ import('/duet/assets/client/voices.mjs').then(({mountVoices})=>{
249
+ const disposeVoices=mountVoices(document.getElementById('duetVoices'));
250
+ window.addEventListener('pagehide',disposeVoices,{once:true});
251
+ }).catch(()=>{document.querySelector('#duetVoices [data-status]').textContent='音色设置暂不可用,请刷新后重试。';});
206
252
  const base = "/duplex-control/api";
207
253
  let debugEnabled = false, settingsRevision = null, feedbackSubmitting = false;
208
254
  let nicknameDirty = false, nicknameRevision = null;
@@ -437,7 +483,7 @@
437
483
  }
438
484
  $('openTutorial').onclick = async () => {
439
485
  try {
440
- const {requestTutorial} = await import('/duet/assets/client/tutorial-request.mjs?v=0.2.0');
486
+ const {requestTutorial} = await import('/duet/assets/client/tutorial-request.mjs?v=0.2.1');
441
487
  requestTutorial(localStorage);
442
488
  $('tutorialStatus').textContent = '请回到 DSH 页面继续教学。';
443
489
  } catch { $('tutorialStatus').textContent = '暂时无法打开教学,请允许浏览器存储后重试。'; }
@@ -446,11 +492,11 @@
446
492
  setInterval(() => { loadDuetConfig().catch(showConnectionUnavailable); }, 2000);
447
493
  void loadNotices();
448
494
  setInterval(loadNotices, 60000);
449
- import('/duet/assets/client/shortcuts.mjs?v=0.2.0').then(({mountShortcutSettings}) => {
495
+ import('/duet/assets/client/shortcuts.mjs?v=0.2.1').then(({mountShortcutSettings}) => {
450
496
  const dispose = mountShortcutSettings({speaker:$('speakerShortcut'),mic:$('micShortcut'),clearSpeaker:$('clearSpeakerShortcut'),clearMic:$('clearMicShortcut'),status:$('shortcutStatus')});
451
497
  window.addEventListener('pagehide', e => {if(!e.persisted)dispose()}, {once:true});
452
498
  }).catch(() => { $('shortcutStatus').textContent = '暂时无法加载快捷键设置,请刷新重试。'; });
453
- import('/duet/assets/client/microphone.mjs?v=0.2.0').then(({mountMicrophoneSettings}) => {
499
+ import('/duet/assets/client/microphone.mjs?v=0.2.1').then(({mountMicrophoneSettings}) => {
454
500
  const dispose = mountMicrophoneSettings({select:$('microphoneDevice'),refresh:$('refreshMicrophones'),status:$('microphoneStatus')});
455
501
  window.addEventListener('pagehide', dispose, {once:true});
456
502
  }).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.2.0'
3
- import { focusedSession } from './composer.mjs?v=0.2.0'
4
- import { sessionCreationPayload, workspaceIssue } from './workspaces.mjs?v=0.2.0'
5
- import { startComposerBridge } from './composer-bridge.mjs?v=0.2.0'
2
+ import { PLUGIN_VERSION } from '../shared/state.mjs?v=0.2.1'
3
+ import { focusedSession } from './composer.mjs?v=0.2.1'
4
+ import { sessionCreationPayload, workspaceIssue } from './workspaces.mjs?v=0.2.1'
5
+ import { startComposerBridge } from './composer-bridge.mjs?v=0.2.1'
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.2.0'
2
+ import {consumeTutorialRequest} from './tutorial-request.mjs?v=0.2.1'
3
3
  export const TUTORIAL_KEY = 'dsh-duplex-tutorial-v1'
4
4
  export const QUESTION = '什么是语音交互?请用一句话简单解释,不使用工具。'
5
5
  export const INPUT = '用一句话介绍语音助手。'
@@ -0,0 +1,137 @@
1
+ import {identityFetch} from './identity.mjs'
2
+ const messages={local_voice_limit:'最多保留 5 个自定义音色。',ip_voice_limit:'当前网络已授权 5 个音色,请先移除一个。',
3
+ challenge_daily_limit:'今天的音色验证次数已用完,请明天再试。',upload_daily_limit:'今天的音频上传次数已用完。',
4
+ voice_proof_invalid:'原音频验证未通过,请检查本地原文件。',voice_original_unavailable:'找不到本地原音频。',
5
+ audio_duration_must_be_3_to_15_seconds:'请选择 3–15 秒的音频。',voice_service_unavailable:'音色服务暂不可用,请稍后重试。'}
6
+ const pending=v=>['queued','recognizing'].includes(v.status)
7
+ messages.custom_voice_disabled='自定义音色暂不可用,已切换为默认音色。'
8
+ Object.assign(messages,{voice_disabled:'此音色已被服务端停用,不能使用或通过重新上传恢复。请选择其他音色。',
9
+ voice_audio_missing:'服务端的参考音频已丢失,请重新上传原音频恢复。',
10
+ voice_not_found:'服务端已没有这份音色记录,请移除后重新新增音色。',
11
+ voice_original_mismatch:'请选择最初上传的同一份音频文件,不能用其他音频替换。'})
12
+ const ADD='__add__'
13
+ export function mountVoices(root){
14
+ let state={selected:'default',voices:[]},busy=false,loaded=false,stopped=false,timer,featureTimer,adding=false,editing=null,draft=null,recovering=null
15
+ const attempts=new Map(),failed=new Set(),get=s=>root.querySelector(s)
16
+ const choice=get('[data-choice]'),status=get('[data-status]'),text=get('[data-text]')
17
+ const api=async body=>{
18
+ const r=await identityFetch('/duplex-control/api/voices',body?{method:'POST',headers:{'Content-Type':'application/json','X-Duplex-Settings':'1'},body:JSON.stringify(body)}:{})
19
+ const v=await r.json();if(!r.ok)throw Error(v.detail||'voice_service_unavailable');return v
20
+ }
21
+ const fail=e=>{status.textContent=messages[e.message]||'音色操作未成功,请稍后重试。'}
22
+ const close=()=>{adding=false;editing=null;draft=null;recovering=null;get('[data-name]').value='';get('[data-file]').value='';get('[data-consent]').checked=false;get('[data-reupload-file]').value=''}
23
+ const draw=()=>{
24
+ if(stopped)return
25
+ const disabled=state.custom_voice_enabled===false
26
+ if(disabled){close();state.selected='default'}
27
+ if(recovering&&!state.voices.some(v=>v.voice_id===recovering&&v.issue))recovering=null
28
+ get('[data-availability]').hidden=!disabled
29
+ get('[data-availability]').textContent=disabled?messages.custom_voice_disabled:''
30
+ choice.replaceChildren(new Option('默认音色','default'))
31
+ for(const v of state.voices){const option=new Option(v.name+(v.issue==='voice_disabled'?'(已停用)':v.issue?'(需恢复)':v.status==='ready'?'':'(待完成)'),v.voice_id);option.disabled=disabled;choice.add(option)}
32
+ const add=new Option('+ 新增音色',ADD);add.disabled=disabled||state.voices.length>=5;choice.add(add)
33
+ choice.value=recovering||(adding?(editing||ADD):state.selected);choice.disabled=busy||!loaded
34
+ const recovery=state.voices.find(v=>v.voice_id===recovering)
35
+ get('[data-recovery]').hidden=!recovery
36
+ get('[data-voice-issue]').textContent=recovery?(messages[recovery.issue]||'') : ''
37
+ get('[data-reupload-fields]').hidden=recovery?.issue!=='voice_audio_missing'
38
+ for(const el of root.querySelectorAll('[data-recovery] input,[data-recovery] button'))el.disabled=busy||!loaded
39
+ get('[data-create]').hidden=!adding;get('[data-upload-fields]').hidden=!!editing;get('[data-editor]').hidden=!editing
40
+ get('[data-remove]').hidden=state.selected==='default'||adding||!!recovering
41
+ get('[data-cancel]').textContent=editing?'返回选择音色':'取消'
42
+ for(const el of root.querySelectorAll('[data-create] input,[data-create] button,[data-remove]'))el.disabled=busy||!loaded
43
+ text.disabled=busy
44
+ const voice=state.voices.find(v=>v.voice_id===editing)
45
+ if(voice){
46
+ get('[data-uploaded-name]').textContent=voice.name
47
+ const value=draft??voice.ref_text??'';if(text.value!==value)text.value=value
48
+ get('[data-refresh]').hidden=!(failed.has(editing)||(!pending(voice)&&voice.status!=='ready'))
49
+ get('[data-recognition]').textContent=failed.has(editing)?'暂时未获取到识别结果,可以刷新结果,也可以直接填写音频中的原话。':
50
+ pending(voice)?'正在自动识别,请稍候…':voice.status==='ready'?'请核对上方文字与音频一致。':'未能自动识别,请填写音频中的原话。'
51
+ get('[data-save]').disabled=busy||!text.value.trim()
52
+ }
53
+ }
54
+ const schedule=()=>{clearTimeout(timer);if(!stopped&&state.custom_voice_enabled!==false&&state.voices.some(v=>pending(v)&&!failed.has(v.voice_id)))timer=setTimeout(poll,3000)}
55
+ async function run(work){
56
+ if(busy||stopped||!loaded)return false
57
+ busy=true;draw()
58
+ try{await work();return true}catch(e){if(!stopped)fail(e);return false}
59
+ finally{busy=false;draw();schedule()}
60
+ }
61
+ // Refresh reads the existing ASR result; it never starts another recognition.
62
+ async function refresh(id){
63
+ try{state=await api({op:'refresh',voice_id:id});failed.delete(id)}
64
+ catch(e){failed.add(id);throw e}
65
+ }
66
+ async function poll(){
67
+ if(stopped)return
68
+ if(busy){schedule();return}
69
+ await run(async()=>{
70
+ for(const v of state.voices.filter(v=>pending(v)&&!failed.has(v.voice_id))){
71
+ if(stopped)return
72
+ const count=attempts.get(v.voice_id)||0
73
+ if(count>=30){failed.add(v.voice_id);continue}
74
+ attempts.set(v.voice_id,count+1)
75
+ try{await refresh(v.voice_id)}catch{/* Keep retry scoped to this draft. */}
76
+ }
77
+ })
78
+ }
79
+ choice.onchange=()=>{
80
+ const id=choice.value
81
+ if(id===ADD){close();adding=true;status.textContent='';draw();get('[data-name]').focus();return}
82
+ const voice=state.voices.find(v=>v.voice_id===id)
83
+ if(voice?.issue){close();recovering=id;status.textContent='';draw();return}
84
+ if(voice&&voice.status!=='ready'){close();adding=true;editing=id;status.textContent='';draw();schedule();return}
85
+ void run(async()=>{state=await api({op:'select',voice_id:id});close();status.textContent='已选择,下次语音连接生效。'})
86
+ }
87
+ text.oninput=()=>{draft=text.value;get('[data-save]').disabled=busy||!text.value.trim()}
88
+ get('[data-cancel]').onclick=()=>{if(busy)return;close();status.textContent='';draw()}
89
+ get('[data-recovery-back]').onclick=()=>{if(busy)return;close();status.textContent='';draw()}
90
+ get('[data-recovery-remove]').onclick=()=>void run(async()=>{state=await api({op:'remove',voice_id:recovering});close()})
91
+ get('[data-reupload]').onclick=()=>void run(async()=>{
92
+ const file=get('[data-reupload-file]').files[0];let audio
93
+ if(file){
94
+ if(file.size>10*1024*1024)throw Error('invalid_audio_size')
95
+ const bytes=new Uint8Array(await file.arrayBuffer());let raw=''
96
+ for(let i=0;i<bytes.length;i+=8192)raw+=String.fromCharCode(...bytes.subarray(i,i+8192))
97
+ audio=btoa(raw)
98
+ }
99
+ const id=recovering
100
+ try{state=await api({op:'restore',voice_id:id,...(audio?{audio}:{})});close();status.textContent='音色已恢复,下次语音连接生效。'}
101
+ catch(e){state=await api();recovering=id;throw e}
102
+ })
103
+ get('[data-remove]').onclick=()=>void run(async()=>{state=await api({op:'remove',voice_id:state.selected});status.textContent='已移除,恢复默认音色。'})
104
+ get('[data-remove-draft]').onclick=()=>void run(async()=>{
105
+ state=await api({op:'remove',voice_id:editing});close();status.textContent='已移除此音色。'
106
+ })
107
+ get('[data-refresh]').onclick=()=>void run(async()=>{attempts.delete(editing);await refresh(editing)})
108
+ get('[data-save]').onclick=()=>void run(async()=>{
109
+ const index=state.voices.findIndex(v=>v.voice_id===editing),value=text.value.trim()
110
+ if(index<0||!value)return
111
+ if(value!==state.voices[index].ref_text){state=await api({op:'text',voice_id:editing,ref_text:value});editing=state.voices[index].voice_id;draft=value}
112
+ state=await api({op:'select',voice_id:editing});close();status.textContent='音色已保存并选择,下次语音连接生效。'
113
+ })
114
+ get('[data-upload]').onclick=()=>void run(async()=>{
115
+ const file=get('[data-file]').files[0],name=get('[data-name]').value.trim()
116
+ if(!get('[data-consent]').checked){status.textContent='请先确认你有权使用这段参考音频。';return}
117
+ if(!file||file.size>10*1024*1024||!name){status.textContent='请填写音色名称,并选择不超过 10 MB 的参考音频。';return}
118
+ status.textContent='正在上传…'
119
+ const bytes=new Uint8Array(await file.arrayBuffer());let raw=''
120
+ for(let i=0;i<bytes.length;i+=8192)raw+=String.fromCharCode(...bytes.subarray(i,i+8192))
121
+ if(stopped)return
122
+ const count=state.voices.length;state=await api({op:'upload',name,audio:btoa(raw)})
123
+ editing=state.voices[count].voice_id;draft=null;status.textContent=''
124
+ })
125
+ api().then(v=>{if(stopped)return;state=v;loaded=true;draw();schedule()}).catch(e=>{if(!stopped)fail(e)})
126
+ async function refreshFeature(){
127
+ if(stopped)return
128
+ if(!busy&&loaded){
129
+ busy=true
130
+ try{state=await api();draw();schedule()}catch{/* Keep the last known policy. */}
131
+ finally{busy=false;draw()}
132
+ }
133
+ if(!stopped)featureTimer=setTimeout(refreshFeature,15000)
134
+ }
135
+ featureTimer=setTimeout(refreshFeature,15000)
136
+ return()=>{stopped=true;clearTimeout(timer);clearTimeout(featureTimer)}
137
+ }
@@ -15,6 +15,7 @@ const modules = {
15
15
  connection_hint: 'client/connection-hint',
16
16
  controls_layout: 'client/controls-layout',
17
17
  notice: 'client/notice',
18
+ voices: 'client/voices',
18
19
  workspaces: 'client/workspaces',
19
20
  transport: 'client/transport',
20
21
  identity: 'client/identity', identity_protocol: 'shared/identity',
@@ -20,6 +20,7 @@ import { AvatarActivityOutbox } from './avatar-activity.mjs'
20
20
  import { duetEnv } from './environment.mjs'
21
21
  import { EndpointDiscovery } from './endpoint-discovery.mjs'
22
22
  import { StopTasks } from './stop-task.mjs'
23
+ import { DuetVoices } from './voices.mjs'
23
24
 
24
25
  const ROUTE = '/duplex-control'
25
26
  const PAGE_ROUTE = '/duet'
@@ -141,12 +142,12 @@ function sendError(res, status, message) {
141
142
  sendJson(res, status, { detail: message })
142
143
  }
143
144
 
144
- async function readJson(req) {
145
+ async function readJson(req, maximum = MAX_BODY_BYTES) {
145
146
  let size = 0
146
147
  const chunks = []
147
148
  for await (const chunk of req) {
148
149
  size += chunk.length
149
- if (size > MAX_BODY_BYTES) throw new Error('request body is too large')
150
+ if (size > maximum) throw new Error('request body is too large')
150
151
  chunks.push(chunk)
151
152
  }
152
153
  if (chunks.length === 0) return {}
@@ -195,6 +196,12 @@ export function apply(ctx, options = {}) {
195
196
  { ...options.traceOptions, secrets: [voice.authorization] })
196
197
  ctx.effect(() => () => { void audit.close({ reason: 'plugin_dispose' }) })
197
198
  const discovery = new EndpointDiscovery(() => settings.effective(), {...options.endpointDiscoveryOptions, changed: () => {notices.invalidate();serviceInfo.invalidate()}})
199
+ const voices = new DuetVoices(() => discovery.effective(), {scope:()=>settings.effective().endpoints.online,...options.voiceOptions})
200
+ voice.prepareVoice = () => voices.prepare()
201
+ voice.respondVoiceChallenge = challenge => voices.respondChallenge(challenge)
202
+ voice.applyVoicePolicy = policy => voices.applyPolicy(policy)
203
+ voice.applyVoiceIssue = issue => voices.applyIssue(issue)
204
+ ctx.effect(() => () => voices.close())
198
205
  const notices = new ServiceNotices(() => discovery.effective(), (url,options) => discovery.fetch(url,options))
199
206
  const serviceInfo = new ServiceInfo(() => discovery.effective(), (url,options) => discovery.fetch(url,options))
200
207
  discovery.refreshIfDue()
@@ -538,6 +545,17 @@ export function apply(ctx, options = {}) {
538
545
  })
539
546
 
540
547
  const handleApi = async (req, res, pathname) => {
548
+ if(pathname===`${ROUTE}/api/voices`){
549
+ const rejection=ctx.connection.requestRejection(req)
550
+ if(rejection){sendError(res,rejection,'DSH connection required');return}
551
+ try {
552
+ if(req.method==='GET'){sendJson(res,200,await voices.refreshAvailability());return}
553
+ if(req.method!=='POST'){sendError(res,405,'method_not_allowed');return}
554
+ if(!identityWriteAllowed(req)){sendError(res,403,'same-origin voice request required');return}
555
+ sendJson(res,200,await voices.update(await readJson(req,14*1024*1024)))
556
+ }catch(error){sendError(res,400,/^[a-z_]+$/.test(error.message)?error.message:'voice_request_failed')}
557
+ return
558
+ }
541
559
  if(req.method==='POST'&&pathname===`${ROUTE}/api/avatar/activity`){
542
560
  const rejection=ctx.connection.requestRejection(req)
543
561
  if(rejection){sendError(res,rejection,'DSH connection required');return}
@@ -91,6 +91,8 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
91
91
  const timer = setTimeout(() => { void trace.close() }, 1500); timer.unref()
92
92
  })
93
93
  let back, feedbackTicket = null, connectionRoute, selectedConfig, diagnostics
94
+ let chosenVoice = 'default'
95
+ let voiceChallengeStarted = false
94
96
  const opening = new AbortController()
95
97
  front.once('close', () => feedback?.close(feedbackTicket))
96
98
  let state = null
@@ -135,7 +137,9 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
135
137
  if (!binary) {
136
138
  const message = JSON.parse(data.toString())
137
139
  if (message.type === 'session.update') data = JSON.stringify({...message,
138
- client: {...message.client, connection_route: connectionRoute}})
140
+ session: {...message.session, ...(chosenVoice!=='default'?{voice_id:chosenVoice}:{})},
141
+ client: {...message.client, connection_route: connectionRoute,
142
+ ...(chosenVoice!=='default'?{voice_possession_protocol:'voice_possession_v1'}:{})}})
139
143
  }
140
144
  trace.frame('upstream.send', data, binary)
141
145
  back.send(data, {binary})
@@ -218,6 +222,8 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
218
222
  } catch (error) { fail(error.message || 'invalid_voice_event') }
219
223
  })
220
224
  void (async () => {
225
+ chosenVoice = await config.prepareVoice?.() || 'default'
226
+ if (opening.signal.aborted || front.readyState !== WebSocket.OPEN) return
221
227
  const routes = await discovery.plan(mode)
222
228
  const selected = await connectEndpoint(WebSocket, routes, {signal: opening.signal, trace})
223
229
  if (opening.signal.aborted || front.readyState !== WebSocket.OPEN) { selected.socket.close(); return }
@@ -231,6 +237,27 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
231
237
  if (!binary) {
232
238
  try {
233
239
  const offer = JSON.parse(data.toString())
240
+ if(offer.type==='voice.unavailable'&&offer.selected==='default'){
241
+ chosenVoice='default'
242
+ Promise.resolve(config.applyVoiceIssue?.(offer)).catch(()=>{
243
+ trace.event('voice.issue_persist_failed',{code:'voice_links_unavailable'})
244
+ })
245
+ }
246
+ if(offer.type==='voice.policy'&&offer.enabled===false&&offer.selected==='default'){
247
+ chosenVoice='default'
248
+ // Queue persistence before forwarding: the reconnect waits for it.
249
+ Promise.resolve(config.applyVoicePolicy?.(offer)).catch(()=>{
250
+ trace.event('voice.policy_persist_failed', {code:'voice_links_unavailable'})
251
+ })
252
+ }
253
+ if (offer.type === 'voice.challenge') {
254
+ if(chosenVoice==='default'||voiceChallengeStarted||!config.respondVoiceChallenge){fail('voice_proof_invalid');return}
255
+ voiceChallengeStarted=true
256
+ Promise.resolve(config.respondVoiceChallenge(offer.challenge)).then(proof=>{
257
+ if(!terminal&&back.readyState===WebSocket.OPEN)back.send(JSON.stringify({type:'voice.proof',...proof}))
258
+ }).catch(()=>fail('voice_proof_invalid'))
259
+ return // Original-file proof and nonce never enter browser/trace.
260
+ }
234
261
  if (offer.type === 'client.diagnostics.ready') {
235
262
  diagnostics.offer(offer, selectedConfig, selected.route.url)
236
263
  return
@@ -0,0 +1,205 @@
1
+ /** User-authorized reference upload and original-file proof. */
2
+ import {mkdir,readFile,writeFile,rename,lstat} from 'node:fs/promises'
3
+ import {join} from 'node:path'
4
+ import {randomUUID,createHash,createHmac} from 'node:crypto'
5
+ import {Agent as HTTPAgent,request as httpRequest} from 'node:http'
6
+ import {Agent as HTTPSAgent,request as httpsRequest} from 'node:https'
7
+ import {duetHome} from './storage-paths.mjs'
8
+
9
+ const VID=/^voice_[a-f0-9]{32}$/
10
+ const MAX=10*1024*1024
11
+ const VOICE_ISSUES=new Set(['voice_disabled','voice_audio_missing','voice_not_found'])
12
+ function voiceHTTP(){
13
+ const agents={'http:':new HTTPAgent({keepAlive:true,maxSockets:1,maxTotalSockets:4}),
14
+ 'https:':new HTTPSAgent({keepAlive:true,maxSockets:1,maxTotalSockets:4})}
15
+ return {close(){for(const agent of Object.values(agents))agent.destroy()},
16
+ fetch(url,options){return new Promise((resolve,reject)=>{
17
+ const request=(url.protocol==='https:'?httpsRequest:httpRequest)(url,{method:'POST',
18
+ agent:agents[url.protocol],headers:options.headers,signal:options.signal},response=>{
19
+ const chunks=[];let size=0
20
+ response.on('error',reject)
21
+ response.on('data',chunk=>{size+=chunk.length;if(size>16384){response.destroy();reject(Error('voice_response_too_large'))}else chunks.push(chunk)})
22
+ response.on('end',()=>{try{resolve(new Response([204,205,304].includes(response.statusCode)?null:Buffer.concat(chunks),{status:response.statusCode}))}catch(error){reject(error)}})
23
+ });request.on('error',reject);request.end(options.body)
24
+ })}}
25
+ }
26
+ export class DuetVoices {
27
+ constructor(getConfig,{root=join(duetHome(),'voices'),fetchImpl,scope}={}){
28
+ this.transport=fetchImpl?null:voiceHTTP()
29
+ this.getConfig=getConfig;this.root=root;this.fetch=fetchImpl||this.transport.fetch;this.scope=scope||(async()=>(await this.getConfig()).endpoints.online);this.tail=Promise.resolve()
30
+ this.feature={enabled:true,revision:-1};this.featureAt=0;this.featureEpoch=0
31
+ }
32
+ close(){this.transport?.close()}
33
+ async state(){
34
+ try{return JSON.parse(await readFile(join(this.root,'links.json'),'utf8'))}
35
+ catch(e){if(e.code==='ENOENT')return {selected:'default',voices:[]};throw Error('voice_links_unavailable')}
36
+ }
37
+ async save(state){
38
+ await mkdir(this.root,{recursive:true,mode:0o700})
39
+ const path=join(this.root,'links.json'),temp=path+'.'+randomUUID()+'.tmp'
40
+ await writeFile(temp,JSON.stringify(state),{mode:0o600,flag:'wx'});await rename(temp,path)
41
+ }
42
+ async public(){const s=await this.state();return {selected:this.feature.enabled?s.selected:'default',custom_voice_enabled:this.feature.enabled,voices:s.voices.map(({file,...v})=>v)}}
43
+ queue(work){const next=this.tail.then(work,work);this.tail=next.catch(()=>{});return next}
44
+ async resetDefault(){const s=await this.state();if(s.selected!=='default'){s.selected='default';await this.save(s)}}
45
+ async checkAvailability(force=false){
46
+ if(!force&&Date.now()-this.featureAt<15000)return
47
+ const epoch=this.featureEpoch
48
+ try{
49
+ const value=await this.remote('status',{})
50
+ if(epoch===this.featureEpoch&&typeof value.enabled==='boolean'&&Number.isInteger(value.revision)&&value.revision>=this.feature.revision){
51
+ this.feature=value;this.featureAt=Date.now()
52
+ }
53
+ }catch{/* A temporary outage does not reverse a known disabled policy. */}
54
+ if(!this.feature.enabled)await this.resetDefault()
55
+ }
56
+ refreshAvailability(){return this.queue(async()=>{
57
+ await this.checkAvailability()
58
+ if(this.feature.enabled){
59
+ const s=await this.state();let changed=false
60
+ for(const row of s.voices.filter(v=>v.issue)){
61
+ try{await this.remote('check',{voice_id:row.voice_id});delete row.issue;changed=true}
62
+ catch(e){if(VOICE_ISSUES.has(e.message)&&row.issue!==e.message){row.issue=e.message;changed=true}}
63
+ }
64
+ if(changed)await this.save(s)
65
+ }
66
+ return this.public()
67
+ })}
68
+ applyPolicy(value){
69
+ if(value?.enabled!==false||value?.selected!=='default')return Promise.resolve()
70
+ ++this.featureEpoch;this.feature={...this.feature,enabled:false};this.featureAt=0
71
+ return this.queue(()=>this.resetDefault())
72
+ }
73
+ applyIssue(value){
74
+ if(!VOICE_ISSUES.has(value?.code)||!VID.test(value?.voice_id))return Promise.resolve()
75
+ return this.queue(async()=>{
76
+ const s=await this.state(),row=s.voices.find(v=>v.voice_id===value.voice_id)
77
+ if(row){row.issue=value.code;if(s.selected===row.voice_id)s.selected='default';await this.save(s)}
78
+ })
79
+ }
80
+ async original(row){
81
+ if(!/^[a-f0-9]{64}\.audio$/.test(row.file))throw Error('voice_original_unavailable')
82
+ try{
83
+ const p=join(this.root,row.file),st=await lstat(p)
84
+ if(!st.isFile()||st.isSymbolicLink()||st.size>MAX)throw Error('voice_original_unavailable')
85
+ return await readFile(p)
86
+ }catch{throw Error('voice_original_unavailable')}
87
+ }
88
+ async remote(operation,body,raw,uploadId,voiceId){
89
+ const c=await this.getConfig(),url=new URL(c.endpoints.online)
90
+ url.protocol=url.protocol==='wss:'?'https:':'http:';url.pathname='/voices/'+operation;url.search='';url.hash=''
91
+ const r=await this.fetch(url,{method:'POST',redirect:'error',signal:AbortSignal.timeout(operation==='status'?3000:45000),
92
+ headers:{...(c.authorization?{Authorization:c.authorization}:{}),'Content-Type':raw?'application/octet-stream':'application/json',...(uploadId?{'X-Upload-Id':uploadId}:{}),...(voiceId?{'X-Voice-Id':voiceId}:{})},body:raw||JSON.stringify(body)})
93
+ const reader=r.body.getReader();let data=Buffer.alloc(0)
94
+ try{while(true){const {done,value}=await reader.read();if(done)break;data=Buffer.concat([data,value]);if(data.length>16384)throw Error('voice_response_too_large')}}finally{await reader.cancel().catch(()=>{})}
95
+ let result;try{result=JSON.parse(data)}catch{throw Error('voice_service_unavailable')}
96
+ if(!r.ok)throw Error(result.error?.code||result.detail||'voice_service_unavailable')
97
+ return result
98
+ }
99
+ update(body){return this.queue(async()=>{
100
+ try{return await this.mutate(body)}catch(error){
101
+ if(error.message==='custom_voice_disabled'){++this.featureEpoch;this.feature.enabled=false;this.featureAt=0;await this.resetDefault()}
102
+ if(VOICE_ISSUES.has(error.message)&&VID.test(body.voice_id)){
103
+ const s=await this.state(),row=s.voices.find(v=>v.voice_id===body.voice_id)
104
+ if(row){row.issue=error.message;if(s.selected===row.voice_id)s.selected='default';await this.save(s)}
105
+ }
106
+ throw error
107
+ }
108
+ })}
109
+ async mutate(body){
110
+ if(body.op!=='remove'&&!(body.op==='select'&&body.voice_id==='default')){
111
+ await this.checkAvailability()
112
+ if(!this.feature.enabled)throw Error('custom_voice_disabled')
113
+ }
114
+ const s=await this.state()
115
+ if(body.op==='select'){
116
+ if(body.voice_id!=='default'&&!s.voices.some(v=>v.voice_id===body.voice_id))throw Error('voice_not_found')
117
+ const row=s.voices.find(v=>v.voice_id===body.voice_id)
118
+ if(row?.issue){await this.remote('check',{voice_id:row.voice_id});delete row.issue}
119
+ s.selected=body.voice_id;await this.save(s);return this.public()
120
+ }
121
+ if(body.op==='upload'){
122
+ if(s.voices.length>=5)throw Error('local_voice_limit')
123
+ if(typeof body.audio!=='string'||body.audio.length>Math.ceil(MAX/3)*4)throw Error('invalid_audio_size')
124
+ const raw=Buffer.from(body.audio,'base64');if(!raw.length||raw.length>MAX||raw.toString('base64')!==body.audio)throw Error('invalid_audio_size')
125
+ const label=typeof body.name==='string'?body.name.trim():''
126
+ if(!label||label.length>40||/[\x00-\x1f]/.test(label))throw Error('invalid_voice_name')
127
+ const file=createHash('sha256').update(raw).digest('hex')+'.audio'
128
+ await mkdir(this.root,{recursive:true,mode:0o700})
129
+ await writeFile(join(this.root,file),raw,{mode:0o600})
130
+ const scope=await this.scope()
131
+ const value=await this.remote('upload',null,raw,randomUUID())
132
+ if(!VID.test(value.voice_id))throw Error('invalid_voice_response')
133
+ s.voices.push({voice_id:value.voice_id,name:label,file,scope,ref_text:value.ref_text||'',status:value.status})
134
+ await this.save(s);return this.public()
135
+ }
136
+ const row=s.voices.find(v=>v.voice_id===body.voice_id)
137
+ if(!row)throw Error('voice_not_found')
138
+ const sameService=row.scope===await this.scope()
139
+ if(!sameService&&body.op!=='remove')throw Error('voice_service_changed')
140
+ if(body.op==='restore'){
141
+ if(row.issue==='voice_disabled')throw Error('voice_disabled')
142
+ let raw
143
+ if(body.audio!==undefined){
144
+ if(typeof body.audio!=='string'||body.audio.length>Math.ceil(MAX/3)*4)throw Error('invalid_audio_size')
145
+ raw=Buffer.from(body.audio,'base64')
146
+ if(!raw.length||raw.length>MAX||raw.toString('base64')!==body.audio)throw Error('invalid_audio_size')
147
+ }else raw=await this.original(row)
148
+ const v=await this.remote('restore',null,raw,undefined,row.voice_id)
149
+ if(v.voice_id!==row.voice_id)throw Error('invalid_voice_response')
150
+ const file=createHash('sha256').update(raw).digest('hex')+'.audio'
151
+ await writeFile(join(this.root,file),raw,{mode:0o600})
152
+ Object.assign(row,{file,ref_text:v.ref_text,status:v.status});delete row.issue;s.selected=row.voice_id
153
+ }else if(body.op==='refresh'){
154
+ const v=await this.withProof(row,'info',{voice_id:row.voice_id});row.ref_text=v.ref_text;row.status=v.status
155
+ }else if(body.op==='text'){
156
+ if(typeof body.ref_text!=='string'||!body.ref_text.trim()||body.ref_text.length>400)throw Error('invalid_ref_text')
157
+ const v=await this.withProof(row,'text',{voice_id:row.voice_id,ref_text:body.ref_text})
158
+ if(!VID.test(v.voice_id))throw Error('invalid_voice_response')
159
+ if(s.selected===row.voice_id)s.selected=v.voice_id
160
+ Object.assign(row,{voice_id:v.voice_id,ref_text:v.ref_text,status:v.status})
161
+ }else if(body.op==='remove'){
162
+ if(sameService)await this.remote('release',{voice_id:row.voice_id})
163
+ s.voices=s.voices.filter(v=>v!==row);if(s.selected===row.voice_id)s.selected='default'
164
+ }else throw Error('invalid_voice_operation')
165
+ await this.save(s);return this.public()
166
+ }
167
+ async prepare(){
168
+ return this.queue(async()=>{
169
+ if((await this.state()).selected==='default')return 'default'
170
+ await this.checkAvailability(true)
171
+ const s=await this.state();if(s.selected==='default'||!this.feature.enabled)return 'default'
172
+ const row=s.voices.find(v=>v.voice_id===s.selected);if(!row)throw Error('voice_not_found')
173
+ if(row.scope!==await this.scope())throw Error('voice_service_changed')
174
+ return row.voice_id
175
+ })
176
+ }
177
+ async withProof(row,op,body){
178
+ try{return await this.remote(op,body)}catch(error){
179
+ if(error.message!=='voice_proof_required')throw error
180
+ await this.authorize(row)
181
+ return this.remote(op,body)
182
+ }
183
+ }
184
+ async authorize(row){
185
+ const c=await this.remote('challenge',{voice_id:row.voice_id})
186
+ if(c.authorized===true)return
187
+ const result=await this.remote('verify',await this.proof(c,row))
188
+ if(result.authorized!==true)throw Error('voice_proof_invalid')
189
+ }
190
+ async respondChallenge(c){
191
+ await this.tail
192
+ const s=await this.state(),row=s.voices.find(v=>v.voice_id===s.selected)
193
+ if(!row||row.voice_id!==c?.voice_id||row.scope!==await this.scope())throw Error('voice_proof_invalid')
194
+ return this.proof(c,row)
195
+ }
196
+ async proof(c,row){
197
+ if(c.protocol!=='voice_possession_v1'||c.voice_id!==row.voice_id||!/^\w{32}$/.test(c.challenge_id)||
198
+ !/^[a-f0-9]{64}$/.test(c.nonce)||!/^[a-f0-9]{64}$/.test(c.binding)||!Number.isInteger(c.expires_at)||
199
+ c.expires_at<=Date.now()/1000||c.expires_at>Date.now()/1000+300)throw Error('invalid_voice_challenge')
200
+ const raw=await this.original(row),context={}
201
+ for(const k of ['binding','challenge_id','expires_at','protocol','voice_id'])context[k]=c[k]
202
+ const proof=createHmac('sha256',Buffer.from(c.nonce,'hex')).update(JSON.stringify(context)).update(Buffer.from([0])).update(raw).digest('hex')
203
+ return {challenge_id:c.challenge_id,proof}
204
+ }
205
+ }
@@ -1,5 +1,5 @@
1
1
  /** Desired voice mode is independent of a temporarily suspended connection. */
2
- export const PLUGIN_VERSION = '0.2.0'
2
+ export const PLUGIN_VERSION = '0.2.1'
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 : ''
@@ -75,12 +75,22 @@ export class DuetState {
75
75
  }
76
76
 
77
77
  receive(event) {
78
- if (event.type === 'compatibility') {
78
+ if(event.type==='voice.unavailable'&&event.selected==='default'){
79
+ const message={voice_disabled:'此音色已被服务端停用,已切换为默认音色。',
80
+ voice_audio_missing:'参考音频已丢失,已使用默认音色。请到设置中重新上传原音频。',
81
+ voice_not_found:'此音色已不存在,已使用默认音色。请到设置中重新新增音色。'}[event.code]
82
+ if(message){this.notice(message);if(event.reconnect_required===true&&this.mode!=='off')void this.replaceConnection({reason:'voice_unavailable'})}
83
+ }else if(event.type==='voice.policy'&&event.enabled===false&&event.selected==='default'){
84
+ this.notice('自定义音色暂不可用,已切换为默认音色。')
85
+ if(event.reconnect_required===true&&this.mode!=='off')void this.replaceConnection({reason:'voice_policy_changed'})
86
+ } else if (event.type === 'compatibility') {
79
87
  const recommended = safeVersion(event.compatibility?.recommended_client_version)
80
88
  const newer = recommended && recommended.split('.').reduce((result, v, i) => result || Math.sign(Number(v) - Number(PLUGIN_VERSION.split('.')[i])), 0) > 0
81
89
  if (newer && this.recommendationShown !== recommended) {
82
90
  this.recommendationShown = recommended
83
- this.notice(`当前插件 ${PLUGIN_VERSION},推荐更新到 ${recommended}。当前连接可以继续使用。`, { upgrade: true })
91
+ this.notice(`当前插件 ${PLUGIN_VERSION},推荐更新到 ${recommended}。当前连接可以继续使用。`, {
92
+ upgrade: true, releaseNotes: event.compatibility?.recommended_release_notes,
93
+ })
84
94
  }
85
95
  } else if (event.type === 'ready') {
86
96
  this.ready = true
@@ -103,7 +113,8 @@ export class DuetState {
103
113
  fail(code, details = {}) {
104
114
  const compatibility = compatibilityNotice(code, details, this.mode)
105
115
  if (compatibility) {
106
- this.notice(compatibility, { upgrade: code !== 'client_version_unsupported' })
116
+ this.notice(compatibility, { upgrade: code !== 'client_version_unsupported',
117
+ releaseNotes: details.compatibility?.recommended_release_notes || details.policy?.recommended_release_notes })
107
118
  void this.setMode('off', {reason:'error',code})
108
119
  return
109
120
  }