dsh-voice-mode 0.7.23 → 0.7.24

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/README.en.md CHANGED
@@ -3,7 +3,7 @@
3
3
  [![License: MIT](https://img.shields.io/github/license/qishuilalala/dsh-voice-mode?style=flat-square&color=blue)](./LICENSE)
4
4
  [![Latest Release](https://img.shields.io/github/v/release/qishuilalala/dsh-voice-mode?style=flat-square&color=brightgreen&include_prereleases)](https://github.com/qishuilalala/dsh-voice-mode/releases)
5
5
  [![npm version](https://img.shields.io/npm/v/dsh-voice-mode?style=flat-square&color=orange)](https://www.npmjs.com/package/dsh-voice-mode)
6
- [![Tests: 433 passing](https://img.shields.io/badge/tests-433%20%E2%9C%93-2ea043?style=flat-square)](https://github.com/qishuilalala/dsh-voice-mode/blob/main/docs/rules/STATE.md)
6
+ [![Tests: 440 passing](https://img.shields.io/badge/tests-440%20%E2%9C%93-2ea043?style=flat-square)](https://github.com/qishuilalala/dsh-voice-mode/blob/main/docs/rules/STATE.md)
7
7
 
8
8
  Full-duplex voice conversation mode for DeepSeek Harness (dsh): speak, get a
9
9
  spoken answer. Streamed zipformer2 ASR → editable draft → auto send → the
@@ -16,7 +16,7 @@ interrupts playback and the running turn. No API key.
16
16
 
17
17
  ![Real recording: streaming transcription → auto-send → sentence-by-sentence read-aloud with live captions](https://raw.githubusercontent.com/qishuilalala/dsh-voice-mode/HEAD/plugin/dsh-voice-mode/assets/demo-voice-flow.gif)
18
18
 
19
- > **Runtime changes (most recent batch: v0.7.17 – v0.7.19, 2026-10-02)**: (1) **Settings work on every dsh version** — fixed the settings page and persistence on dsh 0.1.7+ (dedicated Settings → Voice Mode page, writes survive restarts); (2) **i18n reworked** — the UI follows dsh's official language setting, Chinese/English are fully consistent and switch without a reload; (3) **fixed fresh-install failures with npm/pnpm and `failed to import` on dsh ≥0.1.7** (affects 0.7.17 and earlier — please upgrade to ≥0.7.18); (4) **local Kokoro fixed on the official Electron desktop host** — needs Node.js ≥18 on PATH (see the desktop note below). Earlier batches (v0.7.10: silent-audio fixes, etc.) and the full history are in [`CHANGELOG.md`](https://github.com/qishuilalala/dsh-voice-mode/blob/main/CHANGELOG.md).
19
+ > **Runtime changes (latest: v0.7.18 – v0.7.24)**: (1) **Settings work on every dsh version** — fixed the settings page and persistence on dsh 0.1.7+ (Settings → Voice Mode page, writes survive restarts); (2) **i18n rebuilt** — the UI follows dsh's official language setting, zh/en fully consistent, switching needs no refresh; (3) **fixed fresh npm/pnpm installs and the dsh ≥0.1.7 installed-form "failed to import"** (0.7.17 and earlier are affected — upgrade to ≥0.7.18); (4) **local Kokoro fixed under the official desktop (Electron) app** — needs Node.js ≥18 on PATH (or set `DSHVM_NODE`); (5) **v0.7.24: Edge cloud read-aloud restored** — since 2026-10-15 Microsoft's service rejects the old handshake (v0.7.23 and earlier are silent on the default Edge engine; local VITS / Kokoro are unaffected), so the inlined msedge-tts is bumped to 2.1.0; when read-aloud **fails several sentences in a row** the plugin now suggests switching to a local engine; plus host hardening (`/models/retry` is same-origin POST only, model-tree path checks, raw error strings no longer sent downstream). Compatible with dsh up to 0.2.1-alpha.3 (its Settings entry moved into the sidebar "More" menu; both of this plugin's entry points still work).
20
20
 
21
21
  ---
22
22
 
@@ -41,7 +41,7 @@ interrupts playback and the running turn. No API key.
41
41
  - `hold` push-to-talk: short tap to enter/exit, **hold the mic button to talk, release to send** (swipe up to cancel, `Esc`/blur abandons the segment; pauses do not split while held, up to 10 min); hold `Ctrl` to record-by-keyboard, release to send
42
42
  - **Wake word (optional, off by default)**: after setting `wakeWord`, entering voice mode starts in standby, and recognition only begins once the wake word is spoken (e.g. `你好小D`). **You may say it together with your command** ("wake word, check the weather") — the wake word is stripped from the transcript/caption and never sent; matching is fault-tolerant (homophone substitutions, a wrong first char, leading fillers); 3-4 characters recommended; in standby the status bar live-shows "say '<word>' · what it heard". Boundaries (important): **toggle mode only** (inactive with `hold` / manual barge-in); **it must be repeated after each completed utterance or barge-in** (if you only said the wake word, the engine keeps listening so you may pause before the command); **saying it while the agent is reading does not trigger** (barge-in is VAD-based and unrelated to the wake word)
43
43
  - **Caption tiers (batch 3)**: `captionFontSize` 4 levels (0=12px / 1=14px / 2=18px / 3=24px) + `captionMaxWidth` 3 levels (0=50vw / 1=70vw / 2=90vw); adapts to narrow viewports
44
- - **Yield semantics (batch 5 / ADR-0008)**: `backchannelYield` on by default (I10-exempt) — saying `嗯 / 对 / right` while the AI is reading auto-pauses for 1.5 s; genuine speech still triggers hard barge-in; lets the LLM yield the turn
44
+ - **Yield semantics (ADR-0008)**: `backchannelYield` on by default — saying `嗯 / 对 / right` while the AI is reading auto-pauses for 1.5 s; genuine speech still triggers hard barge-in; lets the LLM yield the turn
45
45
  - **Output pipeline**: only the final answer's `text-delta` is read (reasoning/tool calls are skipped), streamed sentence-by-sentence (Edge cloud by default; local VITS / Kokoro, int8/fp32, optional) with a live caption overlay at the bottom-right; tool calls trigger a beep; the full text is still written to the chat; in voice mode a spoken-format system prompt is injected (short natural sentences, no Markdown decoration), and the reader side strips markers as well for a smoother listening experience
46
46
  - **Barge-in**: three sensitivity levels of voice-onset detection → local mute + host synth queue invalidation (epoch) + running turn cancellation (the half-finished part is kept and naturally flows into your new message). With a wake word set, barge-in **remains speak-to-interrupt** (the gate is the VAD, not the wake word; the engine returns to standby afterwards)
47
47
  - **Lazy model download with progress**: the zipformer2 Chinese streaming model (~160 MB, `.part` resumable) is downloaded on first use with live progress in the status bar; `npm run prefetch` can pre-download it
@@ -78,7 +78,7 @@ dsh plugin --profile web add dsh-voice-mode
78
78
  npx -y @deepseek-ai/dsh plugin --profile web add dsh-voice-mode
79
79
 
80
80
  # Option 2: local tarball
81
- dsh plugin --profile web add ./dsh-voice-mode-0.1.0.tgz
81
+ dsh plugin --profile web add ./dsh-voice-mode-<version>.tgz
82
82
 
83
83
  # Option 3: from source
84
84
  git clone https://github.com/qishuilalala/dsh-voice-mode.git
@@ -120,26 +120,7 @@ If a wake word is configured, you land in standby first (the status bar prompts
120
120
  - On dsh 0.1.7+ the values are stored in the plugin's own file `~/.dsh/voice-mode.settings.json` (under `$DSH_HOME`) and take precedence over same-named keys in the profile config. The first run migrates the old `voice-mode:` block from `settings.yaml(.imported)` once. To reset, set the file's content to `{}` (do not delete it).
121
121
 
122
122
 
123
- ### 4 new settings (11 batches of comprehensive fixes)
124
-
125
- | Key | Default | Description |
126
- | --- | --- | --- |
127
- | `senseITN` | `true` | Batch 2 P0: SenseVoice inverse text normalization (number / date / currency; on by default) |
128
- | `captionFontSize` | `0` | Batch 3 P0: caption font tier 0=12px / 1=14px / 2=18px / 3=24px (default 0 is byte-equivalent to legacy) |
129
- | `captionMaxWidth` | `1` | Batch 3 P0: caption width tier 0=50vw / 1=70vw / 2=90vw |
130
- | `backchannelYield` | `true` | Batch 5 P1: yield semantics (ADR-0008); saying `嗯 / 对` while reading auto-pauses for 1.5 s; genuine speech still triggers hard barge-in. I10-exempt (default-on is a product decision); off = behavior identical to pre-change |
131
-
132
- ### 5 defaults micro-adjusted (batch J)
133
-
134
- | Key | Old | New | Why |
135
- | --- | --- | --- | --- |
136
- | `rate` | 1.0 | **1.1** | Edge TTS defaults slightly slow; +10% improves perceived quality |
137
- | `idleTimeoutMinutes` | 10 | **5** | More responsive idle exit (reading still counts as activity) |
138
- | `interruptLevel` description | old wording | new wording | Make "3/2/1 frame confirmation" explicit |
139
-
140
- > Field names unchanged → 100% backward compatible with existing `~/.dsh/settings.yaml`.
141
-
142
- ### Full 19-key settings table
123
+ ### Full 23-key settings table
143
124
 
144
125
  | Key | Default | Description |
145
126
  | --- | --- | --- |
@@ -161,10 +142,10 @@ If a wake word is configured, you land in standby first (the status bar prompts
161
142
  | `spokenFormat` | `true` | Spoken-format system prompt: inject "short natural sentences, no Markdown decoration" into voice-mode replies only, **applies live** |
162
143
  | `senseVoice` | `true` | Re-transcribe the finalized utterance with SenseVoice (punctuation + number normalization, more accurate; on by default). **Turning it off saves ~228 MB of models** and uses streaming recognition only (faster, less accurate) |
163
144
  | `toolBeep` | `false` | Tool-call beep (off by default): when on, a short beep plays each time the agent calls a tool; off = silent |
164
- | `senseITN` | `true` | Batch 2 P0: SenseVoice inverse text normalization (number / date / currency; on by default) |
165
- | `captionFontSize` | `0` | Batch 3 P0: caption font tier 0=12px / 1=14px / 2=18px / 3=24px (default 0 is byte-equivalent to legacy) |
166
- | `captionMaxWidth` | `1` | Batch 3 P0: caption width tier 0=50vw / 1=70vw / 2=90vw |
167
- | `backchannelYield` | `true` | Batch 5 P1: yield semantics (ADR-0008); saying `嗯 / 对` while reading auto-pauses for 1.5 s; genuine speech still triggers hard barge-in. I10-exempt (default-on is a product decision); off = behavior identical to pre-change |
145
+ | `senseITN` | `true` | SenseVoice inverse text normalization (number / date / currency; on by default) |
146
+ | `captionFontSize` | `0` | Caption font tier 0=12px / 1=14px / 2=18px / 3=24px (default 0 is byte-equivalent to legacy) |
147
+ | `captionMaxWidth` | `1` | Caption width tier 0=50vw / 1=70vw / 2=90vw |
148
+ | `backchannelYield` | `true` | Yield semantics (ADR-0008); saying `嗯 / 对` while reading auto-pauses for 1.5 s; genuine speech still triggers hard barge-in; off = behavior identical to pre-change |
168
149
  | `yieldMs` | `1500` | Yield-window length (ms, 500-3000): how long TTS frames are dropped after `backchannelYield` triggers; if you really want to speak in the window the normal `hardBreak` takes over, and playback resumes when the window ends |
169
150
 
170
151
  Effect timing: `voice`/`rate`/`ttsEngine`/`kokoroModel`/`spokenFormat` take effect **immediately** (TTS hot-swap); the rest apply on the next voice-mode entry. Defaults come from the plugin config (`base` layer) — they follow the config unless explicitly changed.
@@ -296,10 +277,9 @@ flowchart LR
296
277
  | Multi-language | English-first | **SenseVoice auto-recognition + ITN** |
297
278
  | TTS engine | Cloud TTS | **Edge cloud + local VITS/Kokoro** (three-way switch) |
298
279
  | Barge-in detection | Basic VAD | **3 sensitivity levels + echo gate + yield semantics** |
299
- | Hotword biasing | None | None (removed in v0.7.7; see version note) |
300
280
  | Caption a11y | None | **4 font tiers + 3 width tiers + theme-following** |
301
281
  | Wake word | None | **Lightweight streaming match + prefix filler whitelist** |
302
- | dsh compatibility | — | **full range since 0.1.1-rc.2 (incl. 0.1.7-rc.1)** |
282
+ | dsh compatibility | — | **full range since 0.1.1-rc.2 (incl. 0.2.1-alpha.3)** |
303
283
 
304
284
  ---
305
285
 
@@ -324,11 +304,11 @@ Also: the on-device recording fixture used for debugging is **off by default**;
324
304
 
325
305
  ### Compatibility declaration (what the plugin market's version filter reads)
326
306
 
327
- `package.json` declares `engines.dsh = ">=0.1.1-rc.2"` (the market uses it for "filter by host version"). Verified range: **0.1.1-rc.2 → 0.2.1-alpha.1** (including an Electron host equivalent to the official desktop app). The upper bound is open; a weekly CI check watches upstream releases and opens an issue for any uncovered version. `peerDependencies` only lists `@deepseek-ai/cordis` and `react` (provided by the host).
307
+ `package.json` declares `engines.dsh = ">=0.1.1-rc.2"` (the market uses it for "filter by host version"). Verified range: **0.1.1-rc.2 → 0.2.1-alpha.3** (including an Electron host equivalent to the official desktop app). The upper bound is open; a weekly CI check watches upstream releases and opens an issue for any uncovered version. `peerDependencies` only lists `@deepseek-ai/cordis` and `react` (provided by the host).
328
308
 
329
309
  ## 🚧 Known limitations
330
310
 
331
- - Barge-in relies on browser echo cancellation (`echoCancellation`); loud speaker volume may leak into the mic (no JS-level AEC)
311
+ - Barge-in relies on browser echo cancellation (`echoCancellation`); loud speaker volume may leak into the mic (a self-built NLMS canceller only kicks in as a fallback when native AEC is unavailable)
332
312
  - `Ctrl+Shift+V` overrides the browser's "paste as plain text" shortcut (normal `Ctrl+V` paste still works)
333
313
  - The recognition model prioritizes Simplified Chinese; recognition quality is affected by ambient noise
334
314
  - Browser autoplay policy: reading requires prior user interaction on the page (clicking the mic satisfies it); if the browser blocks playback and the status bar shows no hint, make sure the page is foregrounded and not muted
@@ -336,6 +316,11 @@ Also: the on-device recording fixture used for debugging is **off by default**;
336
316
  - In hold mode, switching windows/tabs while holding **abandons the segment** (prevents continuous recording); come back and hold again
337
317
  - The hero (new-session empty state) has no voice entry: voice mode is a session-level feature; enter a session first and use the mic button in the input toolbar
338
318
  - The preview request timeout uses `AbortSignal.timeout` (Chrome 103+ / Firefox 100+ / Safari 16+); on older browsers clicking preview immediately shows a failure hint — an expected degradation
319
+ - **Cloud read-aloud (Edge) depends on a Microsoft online service**: the server side may change its handshake or limits at any time (it did on 2026-10-15 — see CHANGELOG 0.7.24). If several sentences in a row fail, the status bar/toast suggests switching to local VITS / Kokoro, which the settings panel does in one click
320
+ - `spokenFormat` is injected through the official `system-prompt/assemble` waterfall; if the current session uses a **complete prompt** (persona `complete: true` agent preset) it is not injected (the official `complete` contract wins)
321
+ - Local Kokoro needs about 1 s to rebuild its engine before the next sentence after a barge-in (the price of killing in-flight synthesis)
322
+ - **Apple Safari / iOS**: needs **HTTPS or localhost** (a secure context is mandatory; the mic is unavailable on `http://` LAN IPs); grant the mic on first entry (iOS: Settings → Safari → Microphone if denied); recognition and read-aloud pause while backgrounded or locked and resume on return (sentences may be lost)
323
+ - **Security note**: the plugin's HTTP surface (`/voice-mode/*`) follows the host's security model — do not expose the dsh port to the public internet; behind a reverse proxy, authenticate at the proxy (e.g. basic auth)
339
324
 
340
325
  ---
341
326
 
@@ -347,6 +332,7 @@ Also: the on-device recording fixture used for debugging is **off by default**;
347
332
  | Status bar stuck on `Loading model… x%` | Check the network; the model is large (160 MB) — `npm run prefetch` first; on mainland networks set `modelHost` to `https://hf-mirror.com` |
348
333
  | Status bar shows `Model download failed (<file>)` | Both mirrors are unreachable: check network/proxy and re-enter voice mode (resumable) |
349
334
  | Local Kokoro on the official desktop app shows "failed" and asks for Node.js | The desktop host is Electron, where Kokoro's native add-on cannot run: install Node.js >= 18 on PATH (or set `DSHVM_NODE` to its path) and retry, or use the default Edge / local VITS (unaffected on desktop) |
335
+ | No sound and no captions on the default (Edge cloud) engine | Edge read-aloud depends on a Microsoft online service. If several sentences fail in a row you will see "cloud read-aloud unavailable" — switch the engine to local VITS / Kokoro in settings. v0.7.23 and earlier are silent since 2026-10-15 (server-side handshake rejection) — upgrade to ≥0.7.24 |
350
336
  | Caption appears (overlay) but no sound | Check system volume/output; if autoplay is blocked, click anywhere on the page and retry |
351
337
  | Status bar shows `朗读连接失败:正在重试…` | Edge TTS unreachable (overseas service), auto-retries; if it persists, check network/proxy |
352
338
  | Poor recognition | Get closer to the mic, reduce ambient noise; if echo remains, raise the interrupt sensitivity by one step |
@@ -375,33 +361,20 @@ Full backlog (43 P0-P3 items) at [`docs/competitive/backlog.md`](https://github.
375
361
 
376
362
  ### Dependency discipline (important)
377
363
 
378
- Three categories, each with its own home:
379
-
380
- - **Third-party runtime deps** (`msedge-tts` / `sherpa-onnx`) and **registry-resolvable framework packages**
381
- (`@deepseek-ai/schemastery`) → `dependencies`. schemastery is a public npm package and the
382
- dsh host platform does not shadow it internally, so installing it into a profile causes no
383
- version conflicts.
384
- - **Host framework packages** (`@deepseek-ai/cordis` / `@deepseek-ai/dsh-web` / `react`) →
385
- `peerDependencies`. Host packages are provided by the dsh runtime; putting them in
386
- dependencies makes dshmarket treat it as "shadowing host versions" and blocks marketplace
387
- upgrades. Peer versions must match the current dsh runtime
388
- (locally: cordis `^4.0.1`, dsh-web `^0.1.0-rc.6 || ^0.1.1-rc.0`, react `^18.2.0`),
389
- and be bumped when dsh is upgraded.
390
- - **Type-only references** (`@deepseek-ai/dsh-settings` / `dsh-host-webserver` / `dsh-llm`) →
391
- no runtime imports between instances (`import type` + esbuild stripping), no declaration needed;
392
- during development the types link via pnpm `file:` to the local dsh distribution's node_modules
393
- (the registry's rc.1 type snapshot lags behind the distribution; the distribution types are the
394
- runtime truth).
395
-
396
- `dependencies` must contain only true third-party runtime deps — never host-shared packages; after
397
- changing deps, run `npm pack --dry-run` and `pnpm test` as regression.
364
+ - **Runtime dependencies** (`dependencies`): `@deepseek-ai/schemastery`, `sherpa-onnx`, `sherpa-onnx-node` — external at runtime, resolved from the registry.
365
+ - **`msedge-tts` is a build-time `devDependency`** and is inlined together with all of its transitive dependencies into `lib/msedge-tts.cjs` (ADR-0011): it ships a `preinstall: npx only-allow pnpm` that pnpm 11 rejects, and its `require("buffer/index")` breaks under dsh ≥0.1.7's resolver. Inlined packages are listed in `THIRD_PARTY_NOTICES.md`; the inlined `axios` is pinned `>=1.20.0` via `pnpm-workspace.yaml` overrides, and CI runs `pnpm audit`.
366
+ - **Host framework packages** (`@deepseek-ai/cordis`, `react`) → `peerDependencies` (provided by the dsh runtime; putting them in `dependencies` would make dshmarket treat the plugin as shadowing host versions).
367
+ - **Type-only references** (`@deepseek-ai/dsh-settings` / `dsh-host-webserver` / `dsh-llm` / `dsh-system-prompt`) are `devDependencies` used for type checking only; no runtime imports between instances.
368
+
369
+ After changing dependencies run `npm pack --dry-run`, `npm test` and `bash scripts/verify-install.sh` (fresh install of the packed tarball with pnpm + npm).
398
370
 
399
371
  ### Build & test
400
372
 
401
373
  ```sh
402
- pnpm install && pnpm build # esbuild: lib/index.js (host) + lib/client.js (browser)
403
- pnpm test # segmenter/wakeword unit tests + pre-release self-check (no network)
404
- node test/hold-e2e.js # hold-mode acceptance (standalone browser, /asr route interception)
374
+ pnpm install && pnpm build # esbuild: lib/index.js (host) + lib/client.js (browser) + lib/msedge-tts.cjs
375
+ pnpm test # 34 test files chained: unit tests + harnesses (fake browser driving the real engine) + structure guards + pre-release self-check (no network)
376
+ bash scripts/smoke-runtime.sh <dsh-core-bin.js> <port> # boot an isolated dsh core: endpoints, mic button, settings page, i18n
377
+ bash scripts/full-e2e.sh <dsh-core-bin.js> <port> # real-LLM end to end: create → toggle → prompt → SSE audio frames
405
378
  systemctl restart dsh # Linux; restart the dsh process on other platforms
406
379
  ```
407
380
 
@@ -412,18 +385,22 @@ systemctl restart dsh # Linux; restart the dsh process on other platform
412
385
  ### Structure
413
386
 
414
387
  ```
415
- src/index.ts host: single-active pointer, llm/stream tap, SSE, settings registration
416
- src/asr-host.ts host: zipformer2 streaming ASR + lazy model download (.part resume)
417
- src/tts-queue.ts host: per-session TTS queue + epoch barge-in
418
- src/segmenter.ts host: sentence segmentation (markdown stripping + terminating punctuation)
419
- src/client.tsx client: mic button + status bar + reading overlay + barge-in
420
- src/asr.ts client: getUserMedia + RMS VAD + partial polling
421
- scripts/prefetch.mjs model pre-download (cross-platform cache dir + resume)
422
- test/segmenter.test.mjs sentence segmentation unit tests
423
- test/wakeword.test.mjs wake-word matching unit tests
424
- test/verify-client.mjs pre-release self-check (bundle manifest/exports/shape)
425
- test/hold-e2e.js hold-mode end-to-end acceptance (standalone browser)
426
- scripts/list-voices.mjs print all Edge TTS voices (source of the voice table)
388
+ src/index.ts host: single-active pointer, llm/stream tap, SSE, settings registration, spoken-style prompt injection
389
+ src/asr-host.ts host: zipformer2 streaming ASR + SenseVoice finalization + lazy model download (.part resume)
390
+ src/models.ts host: model download/verification (SHA256 pinning + host allowlist + path checks)
391
+ src/security.ts host: rate limiter and guards
392
+ src/tts-local.ts host: local TTS engines (VITS WASM / Kokoro native addon, child-process management)
393
+ src/tts-runtime.ts host: picks a real Node for the Kokoro child under Electron hosts
394
+ src/tts-queue.ts host: per-session TTS queue + epoch barge-in + consecutive-failure streak
395
+ src/settings-store.ts, settings-http-scope.ts host: ≥0.1.7 settings self-persistence (ADR-0009)
396
+ src/segmenter.ts host: sentence segmentation + text sanitizing
397
+ src/asr.ts client: capture, VAD segmentation, incremental recognition, wake word, hold-to-talk gate
398
+ src/client.tsx client: mic button + mode toggle + status bar + caption overlay + barge-in
399
+ src/strings.ts, i18n.ts, error-text.ts client: zh/en dictionary + official locale service + stable error-code texts
400
+ src/voice-catalog.ts, voice-labels.ts voice catalog (single source) + per-language labels
401
+ src/errors.ts, prompts.ts stable error codes; LLM spoken-style prompts and preview sentences
402
+ test/*.test.mjs unit tests, harnesses and structure guards (see `npm test`)
403
+ scripts/ smoke-runtime.sh, full-e2e.sh, verify-install.sh, verify-dual.sh (version matrix), list-voices.mjs, prefetch.mjs
427
404
  ```
428
405
 
429
406
  Integration probes (`hold-e2e.js`, `spoken-prompt-rpc.sh`, `spoken-toggle-ui-check.js`) live in the repo root `test/`, outside this npm package.
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  [![License: MIT](https://img.shields.io/github/license/qishuilalala/dsh-voice-mode?style=flat-square&color=blue)](LICENSE)
4
4
  [![Latest Release](https://img.shields.io/github/v/release/qishuilalala/dsh-voice-mode?style=flat-square&color=brightgreen&include_prereleases)](https://github.com/qishuilalala/dsh-voice-mode/releases)
5
5
  [![npm version](https://img.shields.io/npm/v/dsh-voice-mode?style=flat-square&color=orange)](https://www.npmjs.com/package/dsh-voice-mode)
6
- [![Tests: 433 passing](https://img.shields.io/badge/tests-433%20%E2%9C%93-2ea043?style=flat-square)](https://github.com/qishuilalala/dsh-voice-mode/blob/main/docs/rules/STATE.md)
6
+ [![Tests: 440 passing](https://img.shields.io/badge/tests-440%20%E2%9C%93-2ea043?style=flat-square)](https://github.com/qishuilalala/dsh-voice-mode/blob/main/docs/rules/STATE.md)
7
7
 
8
8
  DeepSeek Harness 语音双工对话模式:会话内一键进入 → 边说边出字的流式识别 → 停顿自动发送 → 最终答复按句流式朗读 + 实时字幕,开口即可打断(真 barge-in)。无需 API Key,识别模型在本地宿主端推理。
9
9
 
@@ -15,9 +15,7 @@ DeepSeek Harness 语音双工对话模式:会话内一键进入 → 边说边
15
15
 
16
16
  ![语音模式真实录制:流式转写 → 自动发送 → 按句朗读 + 实时字幕](https://raw.githubusercontent.com/qishuilalala/dsh-voice-mode/HEAD/plugin/dsh-voice-mode/assets/demo-voice-flow.gif)
17
17
 
18
- ![全双工对话闭环:声音 → 文字 → 声音](https://raw.githubusercontent.com/qishuilalala/dsh-voice-mode/HEAD/plugin/dsh-voice-mode/assets/duplex-banner.png)
19
-
20
- > **运行时变更(最近一批:v0.7.17 ~ v0.7.19,2026-10-02)**:① **设置面全版本打通**——dsh 0.1.7+ 上设置页与持久化修复(Settings → 语音模式 专属页、写入与重启保留);② **国际化重做**——界面语言跟随 dsh 官方语言设置,中/英文完整一致、切换无需刷新;③ **修复 npm/pnpm 全新安装失败与 dsh ≥0.1.7 已安装形态「failed to import」**(0.7.17 及更早版本受影响,请升级到 ≥0.7.18);④ **官方桌面端(Electron)下本地 Kokoro 修复**——需系统 PATH 上有 Node.js ≥18(见下文「桌面端提示」)。此前批次(v0.7.10:输出链路静默丢音根治等)与完整历史见 [`CHANGELOG.md`](https://github.com/qishuilalala/dsh-voice-mode/blob/main/CHANGELOG.md)。
18
+ > **运行时变更(最近:v0.7.18 ~ v0.7.24)**:① **设置面全版本打通**——dsh 0.1.7+ 上设置页与持久化修复(Settings → 语音模式 专属页、写入与重启保留);② **国际化重做**——界面语言跟随 dsh 官方语言设置,中/英文完整一致、切换无需刷新;③ **修复 npm/pnpm 全新安装失败与 dsh ≥0.1.7 已安装形态「failed to import」**(0.7.17 及更早版本受影响,请升级到 ≥0.7.18);④ **官方桌面端(Electron)下本地 Kokoro 修复**——需系统 PATH 上有 Node.js ≥18(或设 `DSHVM_NODE`);⑤ **v0.7.24:恢复 Edge 云端朗读**——微软服务端自 2026-10-15 起拒绝旧版握手(v0.7.23 及更早的默认 Edge 朗读无声,本地 VITS / Kokoro 不受影响),内联的 msedge-tts 升到 2.1.0;朗读**连续失败时**会提示切换本地引擎;另有 host 加固(`/models/retry` 仅同源 POST、模型树路径校验、错误原文不下行)。兼容 dsh 至 0.2.1-alpha.3(其设置入口移入侧栏「More」菜单,本插件两处入口仍有效)。
21
19
 
22
20
  ---
23
21
 
@@ -47,15 +45,15 @@ DeepSeek Harness 语音双工对话模式:会话内一键进入 → 边说边
47
45
  - `toggle`(默认)持续聆听:RMS VAD 分段 → zipformer2 流式识别(边说边出字,实时字幕预览)→ 静音约 1500 毫秒断句进草稿,连续多段拼成一条消息,再静音约 1500 毫秒(合计约 3 秒)自动发送;按住 `Ctrl` 强制立即发送
48
46
  - `hold` 按住说话:短按进入/退出,**按住麦克风按钮说话、松手即发**(滑出取消、`Esc`/失焦放弃本段);按住期间停顿不断句(上限 10 分钟);`Ctrl` 按住即录、松开即发
49
47
  - **唤醒词(可选,默认关)**:设置 `wakeWord` 后进入待机态,说出唤醒词才开始识别(如「你好小D」)。**可直接与命令连说**(「你好小D,帮我查天气」)——唤醒词会在定稿/字幕里自动剥掉、不进消息;匹配带容错(同音字替换「小莫→小墨」、首字错、前置语气词「呃/喂/我说」),建议 3-4 字;待机态状态条实时显示「说『x』开始 · 它听到的转写」,唤醒成败可自查。边界(重要):**仅 `toggle` 模式生效**(`hold` / 手动打断下唤醒词静默失效);**说完整一句后回到待机态需重说唤醒词**(只喊唤醒词、还没说命令时保持聆听,可停顿想好再说);**朗读期说唤醒词不触发**(打断由 VAD 开口即触发,与唤醒词无关)
50
- - **字幕档位**(批 3):`captionFontSize` 4 档(0=12px / 1=14px / 2=18px / 3=24px)+ `captionMaxWidth` 3 档(0=50vw / 1=70vw / 2=90vw),窄屏自适应
51
- - **让位语义**(批 5 / ADR-0008):`backchannelYield` 默认开(I10 豁免)—— 朗读期用户插话「嗯/对」自动让位 1.5s,真要说走硬打断;让 LLM 主动让出话轮(人格层让位);关掉恢复改造前行为
48
+ - **字幕档位**:`captionFontSize` 4 档(0=12px / 1=14px / 2=18px / 3=24px)+ `captionMaxWidth` 3 档(0=50vw / 1=70vw / 2=90vw),窄屏自适应
49
+ - **让位语义**(ADR-0008):`backchannelYield` 默认开—— 朗读期用户插话「嗯/对」自动让位 1.5s,真要说走硬打断;让 LLM 主动让出话轮(人格层让位);关掉恢复改造前行为
52
50
  - **输出链路**:只朗读最终答复的 `text-delta`(reasoning/工具调用不读),按句流式朗读(默认 Edge 云端;可切本地 VITS/Kokoro,中英混读选 Kokoro)+ 右下角实时字幕浮层;工具调用触发提示音;全文照常写入聊天记录;口语化提示词(设置 `spokenFormat`,默认开)让回复为自然短句、不带 Markdown 排版符号
53
51
  - **开口打断(barge-in)**:服务端 Silero VAD 帧级检测 + 回声门控(echoGateDb)三档灵敏度 → 本地静音 + host 合成队列作废 + 正在运行的回合取消(保留半截并自然续入新消息);朗读中自动切超灵敏档。开启唤醒词后打断**仍是开口即打断**(打断门控是 VAD,不是唤醒词;打断后回待机态)
54
52
  - **模型懒加载与进度**:首次使用自动下载识别/合成模型(`.part` 断点续传),状态条实时显示进度;可用 `npm run prefetch` 预下载
55
53
  - **设置**:入口随 dsh 版本而不同(见下方「设置」),可调朗读引擎/音色/语速/打断灵敏度/静音停顿/空闲超时/模型镜像/自动发送/交互模式/唤醒词/口语化提示词/字幕档位/让位语义;**音色可试听**(按当前音色+语速即时合成预览,自定义 ShortName 亦可)
56
54
  - **界面语言**:跟随 dsh 的语言设置(设置 → 通用 → 语言),**切换即时生效、无需刷新**——设置页、语音状态条、字幕、音色名称/性别/口音、错误提示全部随之变化;LLM 口语化提示词也按界面语言选中/英文版。插件词典注册在 dsh 官方 locale 服务的 `voice-mode` 命名空间,社区语言包可据此补充其它语言,缺失的语言回落英文。插件名称与描述在「插件」页同样按语言显示。
57
55
  - **容错**:麦克风被拒红点提示、模型下载失败可见提示、TTS 连接失败状态条提示(自动退避重试)、提交失败文字留在草稿、SSE 断线自动重连
58
- - **空闲退出**:5 分钟无活动自动退出并释放麦克风(**正在朗读计为活动**,长朗读不会中途下线;批 J 已微调默认 10→5)
56
+ - **空闲退出**:5 分钟无活动自动退出并释放麦克风(**正在朗读计为活动**,长朗读不会中途下线)
59
57
 
60
58
  ---
61
59
 
@@ -104,12 +102,12 @@ bundle 插件安装后需重启 dsh 生效(Linux:`systemctl restart dsh`;
104
102
  | `ttsEngine` | `edge` | 朗读引擎:`edge` 微软云端(默认,快)/ `vits` 本地中文 / `kokoro` 本地中英;**即时生效** |
105
103
  | `kokoroModel` | `int8` | Kokoro 模型精度:`int8`(默认,109MB,纯 CPU/低带宽推荐)/ `fp32`(311MB,音质更好,独显/大内存推荐);两档共用 103 音色,**即时生效** |
106
104
  | `voice` | 按引擎 | 音色:VITS 五说话人;Kokoro 103 个(下拉+◀▶,62 深沉/68 浑厚/75 清亮/76 磁性置顶);Edge 进入时自动加载全量 322 个。行内「试听」可即时预览 |
107
- | `rate` | `1.1` | 朗读语速倍率(0.5 慢速 ~ 2.0 快速),**即时生效**(批 J 1.0→1.1) |
105
+ | `rate` | `1.1` | 朗读语速倍率(0.5 慢速 ~ 2.0 快速),**即时生效** |
108
106
  | `interruptLevel` | `0` | 发声打断灵敏度(服务端 VAD 帧级检测 + 回声门控):0 高门槛(3 帧)/ 1 中(2 帧)/ 2 低(1 帧) |
109
107
  | `bargeInMode` | `detect` | 打断方式:`detect` 自动探测本机原生回声消除状态(默认;未生效时切为长按打断)/ `auto` 强制开口即打断(耳机、安静环境推荐)/ `manual` 长按打断(外放推荐)。批 7O 默认,I10 豁免(ADR-0006) |
110
108
  | `echoGateDb` | `6` | 回声门控阈值(dB):自动打断要求残差高于回声地板此值。**原生 AEC 生效时此门控闲置**(Safari / 耳机等无原生 AEC 环境才兜底生效);打不断降 3-4,噪音误打断升 8-10。**不要为「打不断」调它**(详见 ADR-0006) |
111
109
  | `silenceMs` | `1500` | 说完整一句的静音停顿毫秒数 |
112
- | `idleTimeoutMinutes` | `5` | 无活动自动退出语音模式的分钟数(朗读计为活动;批 J 10→5) |
110
+ | `idleTimeoutMinutes` | `5` | 无活动自动退出语音模式的分钟数(朗读计为活动) |
113
111
  | `modelHost` | 默认源 | 模型下载源(国内网络填 `https://hf-mirror.com`) |
114
112
  | `autoSend` | `true` | 静音到点自动发送(连续多段拼成一条消息);关闭则只进草稿(按住 `Ctrl` / hold 松手仍会发送) |
115
113
  | `autoResume` | `false` | 切回上次语音会话时自动恢复语音模式(默认关)。开启后:下次进入语音会话即自动进入语音模式 + 恢复上次会话;关闭则需手动按 `Ctrl+Shift+V` 重新进入 |
@@ -118,11 +116,11 @@ bundle 插件安装后需重启 dsh 生效(Linux:`systemctl restart dsh`;
118
116
  | `wakeWord` | 空(关) | 唤醒词(如「你好小D」):进入后先说唤醒词激活,避免误触;空 = 关闭。**可与命令连说**,词头自动剥掉不进消息;匹配带容错(编辑距离 ≤1 + 前 3 字符前导窗口,吸收同音字/语气词);**建议 3-4 字**——单字词无容错、2 字词的容错会连带吸收所有同首字的 2 字词(如「小莫」也会唤醒「小张」),介意误唤醒用 3 字以上;每句断句或打断后回待机需重说;**仅 toggle 模式生效**(hold / 手动打断下不生效);朗读期说唤醒词不触发 |
119
117
  | `toolBeep` | `false` | 工具调用提示音(默认关):开启后 AI 调用工具时「滴」一声;关闭则全程静默 |
120
118
  | `spokenFormat` | `true` | 语音会话注入口语化提示词:开启后**仅当前语音会话**的回复被注入「口语化短句、不用 Markdown 排版符号」提示词(朗读更顺),**即时生效** |
121
- | `senseITN` | `true` | 批 2 P0:SenseVoice 逆文本归一化(数字/日期/货币规范化;默认开) |
119
+ | `senseITN` | `true` | SenseVoice 逆文本归一化(数字/日期/货币规范化;默认开) |
122
120
  | `senseVoice` | `true` | 定稿是否用 SenseVoice 重译(带标点 + 数字归一化,更准;默认开)。**关闭可省 ~228MB 模型**,只走流式识别(更快、精度下降) |
123
- | `captionFontSize` | `0` | 批 3 P0:字幕字号档位 0=12px / 1=14px / 2=18px / 3=24px(默认 0 与现状字节等价) |
124
- | `captionMaxWidth` | `1` | 批 3 P0:字幕宽度档位 0=50vw / 1=70vw / 2=90vw(视口 <686px 接近 480px,>686px 宽于 480px) |
125
- | `backchannelYield` | `true` | 批 5 P1:让位语义(ADR-0008);朗读期说「嗯/对」自动让位 1.5s + 真要说走硬打断。I10 豁免(默认开是产品决策);关 = 行为等同改造前 |
121
+ | `captionFontSize` | `0` | 字幕字号档位 0=12px / 1=14px / 2=18px / 3=24px(默认 0 与现状字节等价) |
122
+ | `captionMaxWidth` | `1` | 字幕宽度档位 0=50vw / 1=70vw / 2=90vw(视口 <686px 接近 480px,>686px 宽于 480px) |
123
+ | `backchannelYield` | `true` | 让位语义(ADR-0008);朗读期说「嗯/对」自动让位 1.5s + 真要说走硬打断;关 = 行为等同改造前 |
126
124
  | `yieldMs` | `1500` | 让位窗口时长(ms,500-3000):`backchannelYield` 命中后 TTS 丢帧持续时长;窗口内用户真要说则由原 `hardBreak` 接管,窗口到点自动恢复播放 |
127
125
 
128
126
  生效范围:`voice`/`rate`/`ttsEngine`/`kokoroModel`/`spokenFormat` **立即生效**;其余设置下次进入语音模式时生效。设置项默认值由插件配置(`base` 层)提供。
@@ -163,10 +161,10 @@ bundle 插件安装后需重启 dsh 生效(Linux:`systemctl restart dsh`;
163
161
  cacheDir: ~/.cache/dsh-voice-mode/models # 可覆盖;否则用平台默认
164
162
  # 以下为设置项播种的默认值(设置面板优先级更高,面板是权威源):
165
163
  voice: zh-CN-XiaoxiaoNeural
166
- rate: 1.1 # 批 J 1.0→1.1
164
+ rate: 1.1
167
165
  interruptLevel: 0
168
166
  silenceMs: 1500
169
- idleTimeoutMinutes: 5 # 批 J 10→5
167
+ idleTimeoutMinutes: 5
170
168
  modelHost: https://huggingface.co
171
169
  ```
172
170
 
@@ -243,7 +241,7 @@ flowchart LR
243
241
  - 朗读默认 **Edge 云端**;本地 VITS 纯中文 / Kokoro 原生中英(跑在独立子进程、崩溃自愈)可选(隐私优先);
244
242
  - 同一时间仅一个会话处于语音模式(全局单活);LLM 流被无损观察(不阻塞)。
245
243
 
246
- 详细架构决策:见 [`docs/adr/`](https://github.com/qishuilalala/dsh-voice-mode/blob/main/docs/adr/README.md) 8 个 ADR。
244
+ 详细架构决策:见 [`docs/adr/`](https://github.com/qishuilalala/dsh-voice-mode/blob/main/docs/adr/README.md) 11 个 ADR。
247
245
 
248
246
  ---
249
247
 
@@ -255,10 +253,9 @@ flowchart LR
255
253
  | 多语种 | 英文为主 | **SenseVoice 自动识别(zh/en/ja/ko/yue)+ ITN** |
256
254
  | 朗读引擎 | 云端 TTS | **Edge 云端 + 本地 VITS/Kokoro** 三选一 |
257
255
  | 打断检测 | 基础 VAD | **三档灵敏度 + 回声门控 + 让位语义** |
258
- | 热词偏置 | 无 | 无(已移除,详见 v0.7.7 文档说明) |
259
256
  | 字幕 a11y | 无 | **4 档字号 + 3 档宽度 + 主题跟随** |
260
257
  | 唤醒词 | 无 | **轻量流式匹配 + 前缀语气词白名单** |
261
- | 兼容 dsh | — | **0.1.1-rc.2 起全版本(含 0.2.1-alpha.1)** |
258
+ | 兼容 dsh | — | **0.1.1-rc.2 起全版本(含 0.2.1-alpha.3)** |
262
259
 
263
260
  ---
264
261
 
@@ -283,10 +280,11 @@ flowchart LR
283
280
 
284
281
  ### 兼容声明(插件市场的版本筛选依据)
285
282
 
286
- `package.json` 声明 `engines.dsh = ">=0.1.1-rc.2"`(插件市场据此在「按宿主版本筛选」时判定兼容)。已实测范围 **0.1.1-rc.2 → 0.2.1-alpha.1**(含官方桌面端等价的 Electron 宿主);上限开放,由每周 CI 巡检上游新版本并复验,出现未覆盖版本会自动开 issue。`peerDependencies` 仅声明 `@deepseek-ai/cordis` 与 `react`(宿主提供)。
283
+ `package.json` 声明 `engines.dsh = ">=0.1.1-rc.2"`(插件市场据此在「按宿主版本筛选」时判定兼容)。已实测范围 **0.1.1-rc.2 → 0.2.1-alpha.3**(含官方桌面端等价的 Electron 宿主);上限开放,由每周 CI 巡检上游新版本并复验,出现未覆盖版本会自动开 issue。`peerDependencies` 仅声明 `@deepseek-ai/cordis` 与 `react`(宿主提供)。
287
284
 
288
285
  ## 🚧 已知限制
289
286
 
287
+ - **云端朗读(Edge)依赖微软在线服务**:服务端可能随时调整握手/限流(2026-10-15 即发生过,见 CHANGELOG 0.7.24);若连续多句朗读失败,状态条/弹出提示会建议切换本地 VITS / Kokoro,设置面板可一键切换
290
288
  - 发声打断依赖浏览器回声消除(`echoCancellation`);扬声器音量过大时可能漏声到麦克风
291
289
  - `Ctrl+Shift+V` 会覆盖浏览器「粘贴纯文本」快捷键(普通粘贴仍可用 `Ctrl+V`)
292
290
  - 识别质量受环境噪声影响;zipformer2 中文流式 + SenseVoice 多语(中英日韩粤)定稿
@@ -310,7 +308,7 @@ flowchart LR
310
308
  | --- | --- |
311
309
  | 点麦克风无反应,状态条红字 | 浏览器拒绝麦克风:地址栏(iOS 为 设置 → Safari → 麦克风)开启后重试 |
312
310
  | 状态条「正在加载模型… x%」卡住 | 检查网络;模型较大可先 `npm run prefetch`;国内网络 `modelHost` 配 `https://hf-mirror.com` |
313
- | 朗读无声音/无字幕 | 本地引擎首次合成需加载模型;若持续失败查看状态条提示(自动退避重试);确认页面前台且未静音 |
311
+ | 朗读无声音/无字幕 | **默认 Edge 云端朗读依赖微软在线服务**:连续多句失败会提示「云端朗读暂不可用」,到设置把朗读引擎切到本地 VITS / Kokoro;v0.7.23 及更早版本在 2026-10-15 起整体无声,请升级到 ≥0.7.24。 本地引擎首次合成需加载模型;若持续失败查看状态条提示(自动退避重试);确认页面前台且未静音 |
314
312
  | AI 回复**偶尔不朗读**(某句没声/整条没声) | 已定位三类原因并修(v0.7.10):① 云端 TTS 偶发超时——单句自动重试 3 次,仍失败会**跳过该句并在状态条提示**「有一句朗读失败,已跳过」(此前是静默丢句);② 浏览器挂起 AudioContext(切到后台标签页/长时间静音后回来)——播放被调度但无声、UI 却显示朗读中;现在每次入队与**任意点击/按键**都会自动恢复;③ SSE 断线丢帧导致整句不完整——按设计丢弃该句(避免播坏音频),可开 `localStorage['dsh-voice-mode.telemetry']='1'` 看 `tts-drop-sentence` 诊断 |
315
313
  | 语音模式进不去 | 检查插件 `enabled`;多标签页时确认当前会话为活动会话 |
316
314
  | 识别到但不是我要说的 | 环境噪声或唤醒词误判:降低音量、提高 `interruptLevel`(高门槛)或启用 `wakeWord` |
@@ -343,7 +341,7 @@ flowchart LR
343
341
 
344
342
  ```sh
345
343
  pnpm install && pnpm build # esbuild:lib/index.js(host)+ lib/client.js(browser)
346
- pnpm test # segmenter/wakeword 单测 + 发布前自检(无需网络)
344
+ pnpm test # 34 个测试文件串联:单测 + 台架(假浏览器驱动真引擎)+ 结构守卫 + 发布前自检(无需网络)
347
345
  systemctl restart dsh # 本机加载新 host 代码;其他平台重启 dsh 进程
348
346
  ```
349
347
 
@@ -356,7 +354,9 @@ src/models.ts host:模型下载/校验(SHA256 固定 + 域名白名
356
354
  src/security.ts host:限流器与安全守卫
357
355
  src/tts-local.ts host:本地 TTS 引擎(VITS WASM / Kokoro 原生 addon,子进程管理)
358
356
  src/tts-vits-worker.ts 子进程:合成执行(base64 IPC,空文本静音守卫)
359
- src/tts-queue.ts host:逐会话 TTS 队列 + epoch 打断机制
357
+ src/tts-queue.ts host:逐会话 TTS 队列 + epoch 打断 + 连续失败计数(云端整体不可用时给出可行动提示)
358
+ src/tts-runtime.ts host:Electron 宿主下 Kokoro 子进程的真 Node 选择
359
+ src/settings-store.ts / settings-http-scope.ts host:≥0.1.7 设置自持久化(覆盖层文件 + 端点,ADR-0009)
360
360
  src/segmenter.ts host:句子切分 + 文本消毒(markdown 剥离 + 噪声字符剔除)
361
361
  src/asr.ts client:音频采集、VAD 分段、增量识别、唤醒词、按住说门控
362
362
  src/client.tsx client:麦克风按钮 + 模式切换按钮 + 状态条 + 字幕浮层 + 打断
@@ -35,7 +35,7 @@ comment in `build.mjs` for why). Their licenses are reproduced below. Generated
35
35
  | mime-db | 1.52.0 | MIT |
36
36
  | mime-types | 2.1.35 | MIT |
37
37
  | ms | 2.1.3 | MIT |
38
- | msedge-tts | 2.0.7 | MIT |
38
+ | msedge-tts | 2.1.0 | MIT |
39
39
  | ws | 8.21.3 | MIT |
40
40
 
41
41
  ## agent-base 6.0.0
@@ -835,7 +835,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
835
835
  SOFTWARE.
836
836
  ```
837
837
 
838
- ## msedge-tts 2.0.7
838
+ ## msedge-tts 2.1.0
839
839
 
840
840
  - License: MIT
841
841
  - Source: https://github.com/Migushthe2nd/MsEdgeTTS.git
@@ -1 +1,35 @@
1
- <svg xmlns="http://www.w3.org/2000/svg" font-family="Segoe UI, system-ui, sans-serif" font-size="14" viewBox="0 0 960 640"><defs><marker id="arr" markerHeight="8" markerWidth="8" orient="auto" refX="7" refY="4"><path fill="#8b949e" d="M0,0 L8,4 L0,8 z"/></marker><marker id="arrR" markerHeight="8" markerWidth="8" orient="auto" refX="7" refY="4"><path fill="#f85149" d="M0,0 L8,4 L0,8 z"/></marker></defs><rect width="960" height="640" fill="#0d1117"/><text x="480" y="30" fill="#e6edf3" font-size="20" font-weight="700" text-anchor="middle">dsh-voice-mode — 语音双工数据流</text><rect width="200" height="56" x="30" y="70" fill="#161b22" stroke="#58a6ff" stroke-width="1.5" rx="10"/><text x="130" y="92" fill="#58a6ff" font-weight="700" text-anchor="middle">麦克风 Mic</text><text x="130" y="112" fill="#8b949e" font-size="12" text-anchor="middle">16kHz 单声道 · AEC 回声消除</text><rect width="200" height="70" x="30" y="165" fill="#161b22" stroke="#58a6ff" stroke-width="1.5" rx="10"/><text x="130" y="189" fill="#58a6ff" font-weight="700" text-anchor="middle">浏览器 VAD 分段</text><text x="130" y="209" fill="#8b949e" font-size="12" text-anchor="middle">静音 700ms 断句 / 按住说门控</text><text x="130" y="227" fill="#8b949e" font-size="12" text-anchor="middle">增量传输(每 0.9s 只传新增)</text><rect width="200" height="56" x="30" y="285" fill="#161b22" stroke="#3fb950" stroke-width="1.5" rx="10"/><text x="130" y="309" fill="#3fb950" font-weight="700" text-anchor="middle">草稿 → 自动发送</text><text x="130" y="329" fill="#8b949e" font-size="12" text-anchor="middle">autoSend / 按住说松手发送</text><rect width="200" height="70" x="30" y="405" fill="#161b22" stroke="#3fb950" stroke-width="1.5" rx="10"/><text x="130" y="429" fill="#3fb950" font-weight="700" text-anchor="middle">播放 + 字幕浮层</text><text x="130" y="449" fill="#8b949e" font-size="12" text-anchor="middle">SSE 音频帧(WAV/MP3)</text><text x="130" y="467" fill="#8b949e" font-size="12" text-anchor="middle">逐段顺序 · 世代链防重播</text><rect width="290" height="60" x="330" y="70" fill="#161b22" stroke="#58a6ff" stroke-width="1.5" rx="10"/><text x="475" y="94" fill="#58a6ff" font-weight="700" text-anchor="middle">zipformer2 流式识别</text><text x="475" y="114" fill="#8b949e" font-size="12" text-anchor="middle">host 本地 WASM · 启动预热 · SHA256 校验</text><rect width="290" height="56" x="330" y="165" fill="#161b22" stroke="#d29922" stroke-width="1.5" rx="10"/><text x="475" y="189" fill="#d29922" font-weight="700" text-anchor="middle">SenseVoice 定稿</text><text x="475" y="207" fill="#8b949e" font-size="12" text-anchor="middle">带标点 · 数字归一化</text><rect width="290" height="56" x="330" y="255" fill="#161b22" stroke="#a371f7" stroke-width="1.5" rx="10"/><text x="475" y="279" fill="#a371f7" font-weight="700" text-anchor="middle">llm/stream 无损 tap → 分句</text><text x="475" y="297" fill="#8b949e" font-size="12" text-anchor="middle">text-delta 过滤 · markdown 剥离</text><rect width="290" height="56" x="330" y="345" fill="#161b22" stroke="#a371f7" stroke-width="1.5" rx="10"/><text x="475" y="369" fill="#a371f7" font-weight="700" text-anchor="middle">TTS 队列(epoch 打断)</text><text x="475" y="387" fill="#8b949e" font-size="12" text-anchor="middle">打断即杀在途合成 · 积压作废</text><rect width="290" height="100" x="330" y="435" fill="#161b22" stroke="#3fb950" stroke-width="1.5" rx="10"/><text x="475" y="459" fill="#3fb950" font-weight="700" text-anchor="middle">朗读引擎 TTS</text><text x="475" y="481" fill="#8b949e" font-size="12" text-anchor="middle">Edge 云端(默认,322 音色)</text><text x="475" y="501" fill="#8b949e" font-size="12" text-anchor="middle">VITS 本地 · 纯中文(WASM)</text><text x="475" y="521" fill="#8b949e" font-size="12" text-anchor="middle">Kokoro 本地 · 中英(int8 109MB / fp32 311MB)</text><rect width="240" height="200" x="690" y="70" fill="#161b22" stroke="#30363d" stroke-width="1" rx="10"/><text x="810" y="98" fill="#e6edf3" font-weight="700" text-anchor="middle">安全面(四层)</text><text x="710" y="126" fill="#8b949e" font-size="12">① 会话存在性校验</text><text x="710" y="146" fill="#8b949e" font-size="12">② 回环 + Origin 校验</text><text x="710" y="166" fill="#8b949e" font-size="12">③ 全端点限流</text><text x="710" y="186" fill="#8b949e" font-size="12">④ 模型 SHA256 + 域名白名单</text><text x="710" y="214" fill="#8b949e" font-size="12">打断:VAD 帧级检测 + 回声门控</text><text x="710" y="234" fill="#8b949e" font-size="12">模式:持续聆听 ⇄ 按住说</text><text x="710" y="254" fill="#8b949e" font-size="12">空闲:朗读计为活动</text><line x1="130" x2="130" y1="126" y2="163" stroke="#8b949e" stroke-width="1.5" marker-end="url(#arr)"/><line x1="230" x2="326" y1="190" y2="100" stroke="#8b949e" stroke-width="1.5" marker-end="url(#arr)"/><line x1="475" x2="475" y1="130" y2="163" stroke="#8b949e" stroke-width="1.5" marker-end="url(#arr)"/><line x1="330" x2="232" y1="193" y2="313" stroke="#8b949e" stroke-width="1.5" marker-end="url(#arr)"/><line x1="230" x2="326" y1="313" y2="283" stroke="#8b949e" stroke-width="1.5" marker-end="url(#arr)"/><line x1="475" x2="475" y1="311" y2="343" stroke="#8b949e" stroke-width="1.5" marker-end="url(#arr)"/><line x1="475" x2="475" y1="401" y2="433" stroke="#8b949e" stroke-width="1.5" marker-end="url(#arr)"/><line x1="330" x2="232" y1="485" y2="440" stroke="#8b949e" stroke-width="1.5" marker-end="url(#arr)"/><path fill="none" stroke="#f85149" stroke-width="1.5" marker-end="url(#arrR)" d="M130,475 L130,600 L475,600 L475,403"/><text x="300" y="592" fill="#f85149" font-size="12" text-anchor="middle">说话打断:本地静音 + 队列作废 + 回合取消</text></svg>
1
+ <svg xmlns="http://www.w3.org/2000/svg" font-family="Noto Sans CJK SC, PingFang SC, Microsoft YaHei, Segoe UI, system-ui, sans-serif" viewBox="0 0 1110 700" width="1110" height="700">
2
+ <defs><marker id="a7d8590" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto"><path d="M0,0 L10,5 L0,10 z" fill="#7d8590"/></marker><marker id="af85149" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto"><path d="M0,0 L10,5 L0,10 z" fill="#f85149"/></marker></defs>
3
+ <rect width="1110" height="700" fill="#0d1117"/>
4
+ <text x="555" y="40" text-anchor="middle" font-size="24" font-weight="700" fill="#e6edf3">dsh-voice-mode · 语音双工数据流</text>
5
+ <text x="185.0" y="92" text-anchor="middle" font-size="15" font-weight="700" fill="#58a6ff" opacity="0.9">浏览器侧</text>
6
+ <line x1="40" y1="100" x2="330" y2="100" stroke="#58a6ff" stroke-width="2" opacity="0.5"/>
7
+ <text x="555.0" y="92" text-anchor="middle" font-size="15" font-weight="700" fill="#3fb950" opacity="0.9">host 侧(本地推理)</text>
8
+ <line x1="410" y1="100" x2="700" y2="100" stroke="#3fb950" stroke-width="2" opacity="0.5"/>
9
+ <text x="925.0" y="92" text-anchor="middle" font-size="15" font-weight="700" fill="#a371f7" opacity="0.9">朗读输出</text>
10
+ <line x1="780" y1="100" x2="1070" y2="100" stroke="#a371f7" stroke-width="2" opacity="0.5"/>
11
+ <rect x="40" y="120" width="290" height="92" rx="12" fill="#161b22" stroke="#58a6ff" stroke-width="2"/><text x="185.0" y="152" text-anchor="middle" font-size="17" font-weight="700" fill="#58a6ff">麦克风 Mic</text><text x="185.0" y="177" text-anchor="middle" font-size="13" fill="#9aa5b1">16kHz 单声道</text><text x="185.0" y="196" text-anchor="middle" font-size="13" fill="#9aa5b1">浏览器原生回声消除(AEC)</text>
12
+ <rect x="40" y="260" width="290" height="92" rx="12" fill="#161b22" stroke="#58a6ff" stroke-width="2"/><text x="185.0" y="292" text-anchor="middle" font-size="17" font-weight="700" fill="#58a6ff">浏览器 VAD 分段</text><text x="185.0" y="317" text-anchor="middle" font-size="13" fill="#9aa5b1">停顿 1500ms 断句(silenceMs 可调)</text><text x="185.0" y="336" text-anchor="middle" font-size="13" fill="#9aa5b1">增量上传(每 0.9s 只传新增)</text>
13
+ <rect x="40" y="400" width="290" height="92" rx="12" fill="#161b22" stroke="#58a6ff" stroke-width="2"/><text x="185.0" y="432" text-anchor="middle" font-size="17" font-weight="700" fill="#58a6ff">草稿 → 自动发送</text><text x="185.0" y="457" text-anchor="middle" font-size="13" fill="#9aa5b1">静音到点自动发送</text><text x="185.0" y="476" text-anchor="middle" font-size="13" fill="#9aa5b1">按住说:松手发送</text>
14
+ <rect x="410" y="120" width="290" height="92" rx="12" fill="#161b22" stroke="#3fb950" stroke-width="2"/><text x="555.0" y="152" text-anchor="middle" font-size="17" font-weight="700" fill="#3fb950">zipformer2 流式识别</text><text x="555.0" y="177" text-anchor="middle" font-size="13" fill="#9aa5b1">host 本地 · 边说边出字</text><text x="555.0" y="196" text-anchor="middle" font-size="13" fill="#9aa5b1">启动预热 · 模型 SHA256 校验</text>
15
+ <rect x="410" y="260" width="290" height="92" rx="12" fill="#161b22" stroke="#e3b341" stroke-width="2"/><text x="555.0" y="292" text-anchor="middle" font-size="17" font-weight="700" fill="#e3b341">SenseVoice 定稿</text><text x="555.0" y="317" text-anchor="middle" font-size="13" fill="#9aa5b1">带标点 · 数字/日期归一化(ITN)</text>
16
+ <rect x="410" y="400" width="290" height="92" rx="12" fill="#161b22" stroke="#a371f7" stroke-width="2"/><text x="555.0" y="432" text-anchor="middle" font-size="17" font-weight="700" fill="#a371f7">LLM 文本流 → 分句</text><text x="555.0" y="457" text-anchor="middle" font-size="13" fill="#9aa5b1">llm/stream 无损 tap</text><text x="555.0" y="476" text-anchor="middle" font-size="13" fill="#9aa5b1">text-delta 过滤 · markdown 剥离</text>
17
+ <rect x="780" y="120" width="290" height="92" rx="12" fill="#161b22" stroke="#a371f7" stroke-width="2"/><text x="925.0" y="152" text-anchor="middle" font-size="17" font-weight="700" fill="#a371f7">TTS 队列</text><text x="925.0" y="177" text-anchor="middle" font-size="13" fill="#9aa5b1">逐句合成 · epoch 打断</text><text x="925.0" y="196" text-anchor="middle" font-size="13" fill="#9aa5b1">打断即杀在途合成 · 积压作废</text>
18
+ <rect x="780" y="260" width="290" height="92" rx="12" fill="#161b22" stroke="#3fb950" stroke-width="2"/><text x="925.0" y="292" text-anchor="middle" font-size="17" font-weight="700" fill="#3fb950">朗读引擎</text><text x="925.0" y="317" text-anchor="middle" font-size="13" fill="#9aa5b1">Edge 云端(默认)</text><text x="925.0" y="336" text-anchor="middle" font-size="13" fill="#9aa5b1">本地 VITS(纯中文)/ Kokoro(中英)</text>
19
+ <rect x="780" y="400" width="290" height="92" rx="12" fill="#161b22" stroke="#58a6ff" stroke-width="2"/><text x="925.0" y="432" text-anchor="middle" font-size="17" font-weight="700" fill="#58a6ff">播放 + 实时字幕</text><text x="925.0" y="457" text-anchor="middle" font-size="13" fill="#9aa5b1">SSE 音频帧 · 逐句顺序播放</text><text x="925.0" y="476" text-anchor="middle" font-size="13" fill="#9aa5b1">世代链防重播</text>
20
+ <path d="M185.0,212 L185.0,260" fill="none" stroke="#7d8590" stroke-width="2" marker-end="url(#a7d8590)"/>
21
+ <path d="M330,286 L365,286 L365,166 L410,166" fill="none" stroke="#7d8590" stroke-width="2" marker-end="url(#a7d8590)"/>
22
+ <path d="M555.0,212 L555.0,260" fill="none" stroke="#7d8590" stroke-width="2" marker-end="url(#a7d8590)"/>
23
+ <path d="M410,326 L350,326 L350,430 L330,430" fill="none" stroke="#7d8590" stroke-width="2" marker-end="url(#a7d8590)"/>
24
+ <path d="M330,466 L410,466" fill="none" stroke="#7d8590" stroke-width="2" marker-end="url(#a7d8590)"/>
25
+ <path d="M700,446.0 L740,446.0 L740,166.0 L780,166.0" fill="none" stroke="#7d8590" stroke-width="2" marker-end="url(#a7d8590)"/>
26
+ <path d="M925.0,212 L925.0,260" fill="none" stroke="#7d8590" stroke-width="2" marker-end="url(#a7d8590)"/>
27
+ <path d="M925.0,352 L925.0,400" fill="none" stroke="#7d8590" stroke-width="2" marker-end="url(#a7d8590)"/>
28
+ <rect x="330" y="560" width="450" height="64" rx="12" fill="#161b22" stroke="#f85149" stroke-width="2"/>
29
+ <text x="555.0" y="586" text-anchor="middle" font-size="17" font-weight="700" fill="#f85149">开口即打断(barge-in)</text>
30
+ <text x="555.0" y="608" text-anchor="middle" font-size="13" fill="#9aa5b1">VAD 帧级检测 + 回声门控 → 取消回合 · 作废队列</text>
31
+ <path d="M40,306.0 L22,306.0 L22,592.0 L330,592.0" fill="none" stroke="#f85149" stroke-width="2" stroke-dasharray="7 5" marker-end="url(#af85149)"/>
32
+ <path d="M780,592.0 L1076,592.0 L1076,166.0 L1070,166.0" fill="none" stroke="#f85149" stroke-width="2" stroke-dasharray="7 5" marker-end="url(#af85149)"/>
33
+ <text x="555" y="662" text-anchor="middle" font-size="13" fill="#7d8590">安全面:会话存在性校验 · 回环 + Origin 校验 · 全端点限流 · 模型 SHA256 固定 + 下载域名白名单</text>
34
+ <text x="555" y="684" text-anchor="middle" font-size="12" fill="#6e7681">空闲计时:朗读计为活动 · 模式:持续聆听 ⇄ 按住说</text>
35
+ </svg>
package/lib/client.js CHANGED
@@ -1396,7 +1396,8 @@ var import_react = require("react");
1396
1396
  var zh = {
1397
1397
  stateVoiceMode: "\u8BED\u97F3\u6A21\u5F0F",
1398
1398
  ttsNoticeFail: "\u6717\u8BFB\u8FDE\u63A5\u5931\u8D25\uFF1A\u6B63\u5728\u91CD\u8BD5\u2026",
1399
- ttsSkipNotice: "\u6709\u4E00\u53E5\u6717\u8BFB\u5931\u8D25\uFF0C\u5DF2\u8DF3\u8FC7\uFF08\u4E91\u7AEF\u6717\u8BFB\u7F51\u7EDC\u6296\u52A8\uFF0C\u53EF\u91CD\u53D1\u8FD9\u6761\u6D88\u606F\uFF09",
1399
+ ttsSkipNotice: "\u6709\u4E00\u53E5\u6717\u8BFB\u5931\u8D25\uFF0C\u5DF2\u8DF3\u8FC7\uFF08\u53EF\u91CD\u53D1\u8FD9\u6761\u6D88\u606F\uFF09",
1400
+ ttsUnavailableNotice: "\u6717\u8BFB\u8FDE\u7EED\u5931\u8D25\uFF1A\u4E91\u7AEF\u6717\u8BFB\u6682\u4E0D\u53EF\u7528\u3002\u53EF\u7A0D\u540E\u518D\u8BD5\uFF0C\u6216\u5728\u8BBE\u7F6E\u91CC\u628A\u6717\u8BFB\u5F15\u64CE\u5207\u6362\u4E3A\u672C\u5730 VITS / Kokoro",
1400
1401
  enterFail: "\u8FDB\u5165\u8BED\u97F3\u6A21\u5F0F\u5931\u8D25",
1401
1402
  disabled: "\u8BED\u97F3\u6A21\u5F0F\u5DF2\u7981\u7528\uFF08\u63D2\u4EF6 enabled=false\uFF09",
1402
1403
  sendFailKept: "\u53D1\u9001\u5931\u8D25\uFF0C\u5DF2\u4FDD\u7559\u5728\u8349\u7A3F",
@@ -1631,7 +1632,8 @@ var zh = {
1631
1632
  var en = {
1632
1633
  stateVoiceMode: "Voice Mode",
1633
1634
  ttsNoticeFail: "Read-aloud connection failed: retrying\u2026",
1634
- ttsSkipNotice: "One sentence failed to read and was skipped (cloud TTS network hiccup \u2014 resend the message to retry)",
1635
+ ttsSkipNotice: "One sentence failed to read and was skipped (resend the message to retry)",
1636
+ ttsUnavailableNotice: "Read-aloud keeps failing: cloud TTS is unavailable. Try again later, or switch the read-aloud engine to local VITS / Kokoro in settings",
1635
1637
  enterFail: "Failed to enter voice mode",
1636
1638
  disabled: "Voice mode disabled (plugin enabled=false)",
1637
1639
  sendFailKept: "Send failed; text kept in draft",
@@ -2751,7 +2753,7 @@ function EngineStatusInline() {
2751
2753
  children: acting ? acting === "clean" ? t("ttsDeleting") : t("ttsDownloading") : action === "clean" ? t("ttsDelete") : t("ttsDownload")
2752
2754
  }
2753
2755
  ),
2754
- tts.error && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { style: { fontSize: 11, color: "var(--dsw-alias-state-error-primary)", flexBasis: "100%" }, children: tts.errorCode === "kokoro_needs_node" ? t("errKokoroNeedsNode") : tts.error })
2756
+ tts.error && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { style: { fontSize: 11, color: "var(--dsw-alias-state-error-primary)", flexBasis: "100%" }, children: tts.errorCode === "kokoro_needs_node" ? t("errKokoroNeedsNode") : t("engineError") })
2755
2757
  ] });
2756
2758
  }
2757
2759
  function ModelStatusView() {
@@ -3101,7 +3103,7 @@ var TELEMETRY_VIEW = [
3101
3103
  { stage: "first-tts-chunk", key: "telFirstChunk" },
3102
3104
  { stage: "first-audio-played", key: "telFirstPlayed" }
3103
3105
  ];
3104
- var BUILD_TAG = "2b278a6";
3106
+ var BUILD_TAG = "66b3fc0";
3105
3107
  var TELEMETRY_FLAG = "dsh-voice-mode.telemetry";
3106
3108
  var telemetryEnabled = typeof localStorage !== "undefined" && localStorage.getItem(TELEMETRY_FLAG) === "1";
3107
3109
  console.log("[dsh-voice] build=" + BUILD_TAG);
@@ -3696,9 +3698,20 @@ function createVoiceBus(basePath = BASE_PATH2, ctx) {
3696
3698
  try {
3697
3699
  const p = JSON.parse(e.data);
3698
3700
  if (p.sessionId !== activeSessionId) return;
3699
- ui.ttsNotice = t("ttsSkipNotice");
3701
+ const down = (p.streak ?? 1) >= 2;
3702
+ const msg = down ? t("ttsUnavailableNotice") : t("ttsSkipNotice");
3703
+ ui.ttsNotice = msg;
3704
+ if (down && p.streak === 2) {
3705
+ ui.error = msg;
3706
+ setTimeout(() => {
3707
+ if (ui.error === msg) {
3708
+ ui.error = null;
3709
+ notify();
3710
+ }
3711
+ }, 8e3);
3712
+ }
3700
3713
  notify();
3701
- debugLog("tts-skip", { text: (p.text ?? "").slice(0, 40) });
3714
+ debugLog("tts-skip", { text: (p.text ?? "").slice(0, 40), streak: p.streak });
3702
3715
  } catch {
3703
3716
  }
3704
3717
  });
package/lib/index.js CHANGED
@@ -205,7 +205,8 @@ async function ensureModelFile(opts) {
205
205
  lastError = String(e);
206
206
  }
207
207
  }
208
- broadcast("asr-error", { file: spec.file, reason: "checksum_or_download_failed", detail: lastError });
208
+ if (lastError) console.warn(`[dsh-voice-mode] model download failed: ${spec.file}: ${lastError}`);
209
+ broadcast("asr-error", { file: spec.file, reason: "checksum_or_download_failed" });
209
210
  return false;
210
211
  }
211
212
  async function downloadVerified(opts) {
@@ -267,6 +268,11 @@ async function downloadVerified(opts) {
267
268
  await rename(partPath, localPath);
268
269
  return true;
269
270
  }
271
+ function isSafeModelRel(rel, subdir) {
272
+ if (!rel.startsWith(subdir + "/")) return false;
273
+ if (rel.includes("\\") || rel.includes("\0")) return false;
274
+ return !rel.split("/").some((seg) => seg === "" || seg === "." || seg === "..");
275
+ }
270
276
  async function ensureModelTree(opts) {
271
277
  const { repo, repoDir, subdir, primaryHost, allowCustomHost, broadcast } = opts;
272
278
  const hosts = [...new Set([primaryHost, HOST_PRIMARY, HOST_FALLBACK].filter(Boolean))];
@@ -278,7 +284,7 @@ async function ensureModelTree(opts) {
278
284
  const res = await fetch(host + "/api/models/" + repo + "?blobs=true", { headers: { "user-agent": "dsh-voice-mode" } });
279
285
  if (res.ok) {
280
286
  const j = await res.json();
281
- tree = (j.siblings ?? []).map((s) => s.rfilename ?? "").filter((f) => f.startsWith(subdir + "/") && f.length > 0);
287
+ tree = (j.siblings ?? []).map((s) => s.rfilename ?? "").filter((f) => isSafeModelRel(f, subdir));
282
288
  if (tree.length > 0) break;
283
289
  }
284
290
  } catch {
@@ -1181,7 +1187,7 @@ var TtsQueue = class {
1181
1187
  enqueue(sessionId, text) {
1182
1188
  let q = this.queues.get(sessionId);
1183
1189
  if (!q) {
1184
- q = { pending: [], busy: false, seq: 0, epoch: 0, errorNotified: false, backoff: 0 };
1190
+ q = { pending: [], busy: false, seq: 0, epoch: 0, errorNotified: false, backoff: 0, failStreak: 0 };
1185
1191
  this.queues.set(sessionId, q);
1186
1192
  }
1187
1193
  if (q.pending.length >= 500) {
@@ -1234,10 +1240,12 @@ var TtsQueue = class {
1234
1240
  }
1235
1241
  if (item.epoch !== q.epoch) continue;
1236
1242
  if (buf === null) {
1237
- this.onSkip?.(sessionId, item.text);
1243
+ q.failStreak++;
1244
+ this.onSkip?.(sessionId, item.text, q.failStreak);
1238
1245
  continue;
1239
1246
  }
1240
1247
  q.errorNotified = false;
1248
+ q.failStreak = 0;
1241
1249
  q.backoff = 0;
1242
1250
  const sentenceId = q.seq++;
1243
1251
  const mime = this.engine.mime;
@@ -1942,7 +1950,8 @@ var RateLimiter = class {
1942
1950
  var en = {
1943
1951
  stateVoiceMode: "Voice Mode",
1944
1952
  ttsNoticeFail: "Read-aloud connection failed: retrying\u2026",
1945
- ttsSkipNotice: "One sentence failed to read and was skipped (cloud TTS network hiccup \u2014 resend the message to retry)",
1953
+ ttsSkipNotice: "One sentence failed to read and was skipped (resend the message to retry)",
1954
+ ttsUnavailableNotice: "Read-aloud keeps failing: cloud TTS is unavailable. Try again later, or switch the read-aloud engine to local VITS / Kokoro in settings",
1946
1955
  enterFail: "Failed to enter voice mode",
1947
1956
  disabled: "Voice mode disabled (plugin enabled=false)",
1948
1957
  sendFailKept: "Send failed; text kept in draft",
@@ -2295,7 +2304,7 @@ function readLegacyVoiceSettings(dir, keys) {
2295
2304
  var name = "voice-mode";
2296
2305
  var NS_VOICE_MODE = "voice-mode";
2297
2306
  var BASE_PATH = "/voice-mode";
2298
- var PREVIEW_NETWORK_PATTERN = /fetch failed|ECONN|ENOTFOUND|getaddrinfo|ETIMEDOUT|EAI_AGAIN|network|unreachable|socket hang up|aborted/i;
2307
+ var PREVIEW_NETWORK_PATTERN = /fetch failed|ECONN|ENOTFOUND|getaddrinfo|ETIMEDOUT|EAI_AGAIN|network|unreachable|socket hang up|aborted|WebSocket error/i;
2299
2308
  var PREVIEW_ENGINE_PATTERN = /model download|model verify|init failed|child exited|tts child|local TTS|prepare|sherpa|local Kokoro/i;
2300
2309
  var PREVIEW_TEXT_PATTERN = /empty or invalid audio|invalid audio|invalid text|too long|truncat/i;
2301
2310
  function classifyPreviewError(msg) {
@@ -2663,7 +2672,8 @@ function apply(ctx, config) {
2663
2672
  engine: makeEngine(engineKind),
2664
2673
  onError: (sessionId) => broadcast("tts-error", { sessionId }),
2665
2674
  // 单句重试耗尽被跳过:显式下行(客户端提示 + 诊断),不再静默丢句。
2666
- onSkip: (sessionId, text) => broadcast("tts-skip", { sessionId, text: text.slice(0, 80) })
2675
+ // streak = 连续被跳过的句数:客户端据此区分偶发抖动与「云端整体不可用」(如服务端拒绝握手)。
2676
+ onSkip: (sessionId, text, streak) => broadcast("tts-skip", { sessionId, text: text.slice(0, 80), streak })
2667
2677
  });
2668
2678
  queue.updateVoice(vset.voice, vset.rate);
2669
2679
  const unsubscribe = queue.subscribe((frame) => broadcast("audio", frame));
@@ -2951,6 +2961,13 @@ function apply(ctx, config) {
2951
2961
  path: `${base}/models/retry`,
2952
2962
  handler: (req, res) => {
2953
2963
  if (denyNonLoopback(req, res)) return;
2964
+ if (req.method !== "POST") {
2965
+ res.statusCode = 405;
2966
+ res.setHeader("allow", "POST");
2967
+ res.end();
2968
+ return;
2969
+ }
2970
+ if (denyCrossOrigin(req, res)) return;
2954
2971
  if (!config.enabled) {
2955
2972
  respondJson2(res, 403, { code: "voice_disabled", error: "voice mode disabled" });
2956
2973
  return;
@@ -22595,9 +22595,9 @@ var require_buffer = __commonJS({
22595
22595
  }
22596
22596
  });
22597
22597
 
22598
- // node_modules/.pnpm/msedge-tts@2.0.7_debug@4.4.3/node_modules/msedge-tts/dist/Output.js
22598
+ // node_modules/.pnpm/msedge-tts@2.1.0_debug@4.4.3/node_modules/msedge-tts/dist/Output.js
22599
22599
  var require_Output = __commonJS({
22600
- "node_modules/.pnpm/msedge-tts@2.0.7_debug@4.4.3/node_modules/msedge-tts/dist/Output.js"(exports2) {
22600
+ "node_modules/.pnpm/msedge-tts@2.1.0_debug@4.4.3/node_modules/msedge-tts/dist/Output.js"(exports2) {
22601
22601
  "use strict";
22602
22602
  Object.defineProperty(exports2, "__esModule", { value: true });
22603
22603
  exports2.OUTPUT_EXTENSIONS = exports2.OUTPUT_FORMAT = void 0;
@@ -22615,9 +22615,9 @@ var require_Output = __commonJS({
22615
22615
  }
22616
22616
  });
22617
22617
 
22618
- // node_modules/.pnpm/msedge-tts@2.0.7_debug@4.4.3/node_modules/msedge-tts/dist/Prosody.js
22618
+ // node_modules/.pnpm/msedge-tts@2.1.0_debug@4.4.3/node_modules/msedge-tts/dist/Prosody.js
22619
22619
  var require_Prosody = __commonJS({
22620
- "node_modules/.pnpm/msedge-tts@2.0.7_debug@4.4.3/node_modules/msedge-tts/dist/Prosody.js"(exports2) {
22620
+ "node_modules/.pnpm/msedge-tts@2.1.0_debug@4.4.3/node_modules/msedge-tts/dist/Prosody.js"(exports2) {
22621
22621
  "use strict";
22622
22622
  Object.defineProperty(exports2, "__esModule", { value: true });
22623
22623
  exports2.VOLUME = exports2.PITCH = exports2.RATE = exports2.ProsodyOptions = void 0;
@@ -22673,9 +22673,9 @@ var require_Prosody = __commonJS({
22673
22673
  }
22674
22674
  });
22675
22675
 
22676
- // node_modules/.pnpm/msedge-tts@2.0.7_debug@4.4.3/node_modules/msedge-tts/dist/utils.js
22676
+ // node_modules/.pnpm/msedge-tts@2.1.0_debug@4.4.3/node_modules/msedge-tts/dist/utils.js
22677
22677
  var require_utils = __commonJS({
22678
- "node_modules/.pnpm/msedge-tts@2.0.7_debug@4.4.3/node_modules/msedge-tts/dist/utils.js"(exports2) {
22678
+ "node_modules/.pnpm/msedge-tts@2.1.0_debug@4.4.3/node_modules/msedge-tts/dist/utils.js"(exports2) {
22679
22679
  "use strict";
22680
22680
  Object.defineProperty(exports2, "__esModule", { value: true });
22681
22681
  exports2.joinPath = void 0;
@@ -22686,9 +22686,9 @@ var require_utils = __commonJS({
22686
22686
  }
22687
22687
  });
22688
22688
 
22689
- // node_modules/.pnpm/msedge-tts@2.0.7_debug@4.4.3/node_modules/msedge-tts/dist/MsEdgeTTS.js
22689
+ // node_modules/.pnpm/msedge-tts@2.1.0_debug@4.4.3/node_modules/msedge-tts/dist/MsEdgeTTS.js
22690
22690
  var require_MsEdgeTTS = __commonJS({
22691
- "node_modules/.pnpm/msedge-tts@2.0.7_debug@4.4.3/node_modules/msedge-tts/dist/MsEdgeTTS.js"(exports2) {
22691
+ "node_modules/.pnpm/msedge-tts@2.1.0_debug@4.4.3/node_modules/msedge-tts/dist/MsEdgeTTS.js"(exports2) {
22692
22692
  "use strict";
22693
22693
  var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
22694
22694
  if (k2 === void 0) k2 = k;
@@ -22759,19 +22759,25 @@ var require_MsEdgeTTS = __commonJS({
22759
22759
  var MsEdgeTTS2 = class _MsEdgeTTS {
22760
22760
  static TRUSTED_CLIENT_TOKEN = "6A5AA1D4EAFF4E9FB37E23D68491D6F4";
22761
22761
  static VOICES_URL = `https://speech.platform.bing.com/consumer/speech/synthesize/readaloud/voices/list?trustedclienttoken=${_MsEdgeTTS.TRUSTED_CLIENT_TOKEN}`;
22762
- static WSS_URL = "wss://speech.platform.bing.com/consumer/speech/synthesize/readaloud/edge/v1";
22762
+ static WSS_URL = "wss://api.msedgeservices.com/tts/cognitiveservices/websocket/v1";
22763
22763
  static JSON_XML_DELIM = "\r\n\r\n";
22764
22764
  static AUDIO_DELIM = "Path:audio\r\n";
22765
- static VOICE_LANG_REGEX = /\w{2}-\w{2}/;
22765
+ static VOICE_LANG_REGEX = /\b[a-z]{2,}-[A-Z]{2}\b/;
22766
+ static _clockOffsetMs = 0;
22766
22767
  _enableLogger;
22767
22768
  _isBrowser;
22768
22769
  _ws;
22770
+ _clientInit;
22771
+ _clientGeneration = 0;
22769
22772
  _voice;
22770
22773
  _outputFormat;
22771
22774
  _metadataOptions = new MetadataOptions();
22772
22775
  _streams = {};
22776
+ _retiredSockets = [];
22773
22777
  _startTime = 0;
22774
22778
  _agent;
22779
+ _connectionTimeoutMs;
22780
+ _synthesisTimeoutMs;
22775
22781
  _log(...o) {
22776
22782
  if (this._enableLogger) {
22777
22783
  console.log(...o);
@@ -22786,24 +22792,81 @@ var require_MsEdgeTTS = __commonJS({
22786
22792
  this._agent = options?.agent || void 0;
22787
22793
  this._enableLogger = options?.enableLogger || false;
22788
22794
  this._isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
22795
+ this._connectionTimeoutMs = options?.connectionTimeoutMs === void 0 ? 1e4 : options.connectionTimeoutMs;
22796
+ this._synthesisTimeoutMs = options?.synthesisTimeoutMs === void 0 ? 6e4 : options.synthesisTimeoutMs;
22797
+ for (const [name, value] of Object.entries({ connectionTimeoutMs: this._connectionTimeoutMs, synthesisTimeoutMs: this._synthesisTimeoutMs })) {
22798
+ if (!Number.isInteger(value) || value < 0 || value > 2147483647) {
22799
+ throw new Error(`${name} must be an integer between 0 and 2147483647 milliseconds.`);
22800
+ }
22801
+ }
22789
22802
  }
22790
22803
  static async getSynthUrl() {
22791
22804
  const req_id = _MsEdgeTTS.generateUUID();
22792
22805
  const secMsGEC = await _MsEdgeTTS.generateSecMsGec(this.TRUSTED_CLIENT_TOKEN);
22793
- return `${this.WSS_URL}?TrustedClientToken=${this.TRUSTED_CLIENT_TOKEN}&Sec-MS-GEC=${secMsGEC}&Sec-MS-GEC-Version=1-143.0.3650.96&ConnectionId=${req_id}`;
22794
- }
22795
- async _initClient() {
22806
+ return `${this.WSS_URL}?Ocp-Apim-Subscription-Key=${this.TRUSTED_CLIENT_TOKEN}&Sec-MS-GEC=${secMsGEC}&Sec-MS-GEC-Version=1-143.0.3650.96&ConnectionId=${req_id}`;
22807
+ }
22808
+ _initClient() {
22809
+ if (this._clientInit)
22810
+ return this._clientInit;
22811
+ const init = this._createClient();
22812
+ const tracked = init.finally(() => {
22813
+ if (this._clientInit === tracked)
22814
+ this._clientInit = void 0;
22815
+ });
22816
+ this._clientInit = tracked;
22817
+ return tracked;
22818
+ }
22819
+ async _createClient(retryClock = true, deadline = this._connectionTimeoutMs ? Date.now() + this._connectionTimeoutMs : 0, generation = this._clientGeneration) {
22820
+ const previous = this._ws;
22821
+ if (previous) {
22822
+ if (previous.readyState === previous.OPEN && Object.values(this._streams).some((stream) => stream.socket === previous && !stream.turnEnded)) {
22823
+ if (!this._retiredSockets.includes(previous))
22824
+ this._retiredSockets.push(previous);
22825
+ } else {
22826
+ this._closeSocket(previous);
22827
+ }
22828
+ }
22796
22829
  const synthUrl = await _MsEdgeTTS.getSynthUrl();
22830
+ if (generation !== this._clientGeneration)
22831
+ throw new Error("Edge TTS connection closed before initialization completed.");
22832
+ const remaining = deadline ? deadline - Date.now() : 0;
22833
+ if (deadline && remaining <= 0)
22834
+ throw new Error(`Edge TTS connection timed out after ${this._connectionTimeoutMs} milliseconds.`);
22797
22835
  const options = {
22798
22836
  headers: {
22799
22837
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0",
22800
22838
  "Origin": "chrome-extension://jdiccldimpdaibmpdkjnbmckianbfold"
22801
22839
  }
22802
22840
  };
22803
- this._ws = this._isBrowser ? new isomorphic_ws_1.default(synthUrl, options) : new isomorphic_ws_1.default(synthUrl, { ...options, agent: this._agent });
22804
- this._ws.binaryType = "arraybuffer";
22841
+ const ws = this._ws = this._isBrowser ? new isomorphic_ws_1.default(synthUrl) : new isomorphic_ws_1.default(synthUrl, { ...options, agent: this._agent });
22842
+ ws.binaryType = "arraybuffer";
22805
22843
  return new Promise((resolve, reject) => {
22806
- this._ws.onopen = () => {
22844
+ let connecting = true;
22845
+ const connectionTimeout = this._connectionTimeoutMs ? setTimeout(() => {
22846
+ connecting = false;
22847
+ reject(new Error(`Edge TTS connection timed out after ${this._connectionTimeoutMs} milliseconds.`));
22848
+ this._closeSocket(ws);
22849
+ }, remaining) : void 0;
22850
+ if (!this._isBrowser) {
22851
+ ws.once("unexpected-response", (request, response) => {
22852
+ if (!connecting || ws.readyState !== ws.CONNECTING || generation !== this._clientGeneration) {
22853
+ request.destroy();
22854
+ response.destroy();
22855
+ return;
22856
+ }
22857
+ const error = Object.assign(new Error(`Unexpected server response: ${response.statusCode}`), {
22858
+ statusCode: response.statusCode,
22859
+ serverDate: response.headers.date
22860
+ });
22861
+ request.destroy(error);
22862
+ response.destroy();
22863
+ });
22864
+ }
22865
+ ws.onopen = () => {
22866
+ if (!connecting)
22867
+ return;
22868
+ connecting = false;
22869
+ clearTimeout(connectionTimeout);
22807
22870
  this._log("Connected in", (Date.now() - this._startTime) / 1e3, "seconds");
22808
22871
  this._send(`Content-Type:application/json; charset=utf-8\r
22809
22872
  Path:${messageTypes.SPEECH_CONFIG}${_MsEdgeTTS.JSON_XML_DELIM}
@@ -22820,39 +22883,58 @@ Path:${messageTypes.SPEECH_CONFIG}${_MsEdgeTTS.JSON_XML_DELIM}
22820
22883
  }
22821
22884
  }
22822
22885
  }
22823
- `).then(resolve);
22886
+ `, void 0, ws).then(resolve, (error) => {
22887
+ this._closeSocket(ws);
22888
+ reject(error);
22889
+ });
22824
22890
  };
22825
- this._ws.onmessage = (m) => {
22891
+ ws.onmessage = (m) => {
22826
22892
  const buffer = index_1.Buffer.from(m.data);
22827
22893
  const message = buffer.toString();
22828
- const requestId = /X-RequestId:(.*?)\r\n/gm.exec(message)[1];
22894
+ const requestId = /X-RequestId:(.*?)\r\n/.exec(message)?.[1];
22895
+ const stream = requestId && this._streams[requestId];
22896
+ if (!stream || stream.audio.destroyed || stream.turnEnded || stream.socket !== ws)
22897
+ return;
22829
22898
  if (message.includes(`Path:${messageTypes.TURN_START}`)) {
22830
22899
  this._log("->", message);
22900
+ this._resetSynthesisTimeout(requestId);
22831
22901
  } else if (message.includes(`Path:${messageTypes.TURN_END}`)) {
22832
22902
  this._log("->", message);
22833
- this._streams[requestId].turnEnded = true;
22834
- this._streams[requestId].audio.push(null);
22903
+ clearTimeout(stream.timeout);
22904
+ stream.timeout = void 0;
22905
+ stream.turnEnded = true;
22906
+ stream.audio.push(null);
22907
+ this._closeRetiredSockets();
22835
22908
  } else if (message.includes(`Path:${messageTypes.RESPONSE}`)) {
22836
22909
  this._log("->", message);
22910
+ this._resetSynthesisTimeout(requestId);
22837
22911
  } else if (message.includes(`Path:${messageTypes.AUDIO_METADATA}`)) {
22838
22912
  const dataStartIndex = buffer.indexOf(_MsEdgeTTS.JSON_XML_DELIM) + _MsEdgeTTS.JSON_XML_DELIM.length;
22839
22913
  const data = buffer.subarray(dataStartIndex);
22840
22914
  this._log("->", message);
22915
+ this._resetSynthesisTimeout(requestId);
22841
22916
  this._pushMetadata(data, requestId);
22842
22917
  } else if (message.includes(`Path:${messageTypes.AUDIO}`) && m.data instanceof ArrayBuffer) {
22843
22918
  const dataStartIndex = buffer.indexOf(_MsEdgeTTS.AUDIO_DELIM) + _MsEdgeTTS.AUDIO_DELIM.length;
22844
22919
  const headers = buffer.subarray(0, dataStartIndex).toString();
22845
22920
  const data = buffer.subarray(dataStartIndex);
22846
22921
  this._log("->", headers);
22922
+ this._resetSynthesisTimeout(requestId);
22847
22923
  this._pushAudioData(data, requestId);
22848
22924
  } else {
22849
22925
  this._log("->", "UNKNOWN MESSAGE", message);
22850
22926
  }
22851
22927
  };
22852
- this._ws.onclose = () => {
22928
+ ws.onclose = () => {
22929
+ connecting = false;
22930
+ clearTimeout(connectionTimeout);
22931
+ reject(new Error("Edge TTS connection closed before initialization completed."));
22853
22932
  this._log("disconnected after:", (Date.now() - this._startTime) / 1e3, "seconds");
22854
22933
  for (const requestId in this._streams) {
22855
22934
  const stream = this._streams[requestId];
22935
+ if (stream.socket !== ws)
22936
+ continue;
22937
+ clearTimeout(stream.timeout);
22856
22938
  if (stream.turnEnded) {
22857
22939
  stream.audio.push(null);
22858
22940
  } else {
@@ -22860,14 +22942,47 @@ Path:${messageTypes.SPEECH_CONFIG}${_MsEdgeTTS.JSON_XML_DELIM}
22860
22942
  }
22861
22943
  }
22862
22944
  };
22863
- this._ws.onerror = (event) => {
22945
+ ws.onerror = (event) => {
22946
+ connecting = false;
22947
+ clearTimeout(connectionTimeout);
22864
22948
  const underlying = event?.error ?? event;
22865
22949
  const message = underlying?.message ?? String(underlying);
22866
22950
  const code = underlying?.code ?? event?.code;
22867
22951
  const wrapped = new Error(`Edge TTS WebSocket error: ${message}${code ? ` (code=${code})` : ""}`);
22868
22952
  wrapped.cause = underlying;
22869
22953
  reject(wrapped);
22954
+ for (const stream of Object.values(this._streams)) {
22955
+ if (stream.socket === ws && !stream.turnEnded)
22956
+ stream.audio.destroy(wrapped);
22957
+ }
22958
+ this._closeSocket(ws);
22870
22959
  };
22960
+ }).catch((error) => {
22961
+ const underlying = error.cause;
22962
+ const serverTime = typeof underlying?.serverDate === "string" ? Date.parse(underlying.serverDate) : NaN;
22963
+ if (retryClock && underlying?.statusCode === 403 && Number.isFinite(serverTime) && generation === this._clientGeneration && (!deadline || Date.now() < deadline)) {
22964
+ _MsEdgeTTS._clockOffsetMs = serverTime - Date.now();
22965
+ return this._createClient(false, deadline, generation);
22966
+ }
22967
+ throw error;
22968
+ });
22969
+ }
22970
+ _closeSocket(socket) {
22971
+ if (socket.readyState === socket.CLOSED)
22972
+ return;
22973
+ const terminate = socket.terminate;
22974
+ if (socket.readyState !== socket.OPEN && terminate)
22975
+ terminate.call(socket);
22976
+ else
22977
+ socket.close();
22978
+ }
22979
+ _closeRetiredSockets() {
22980
+ this._retiredSockets = this._retiredSockets.filter((socket) => {
22981
+ if (Object.values(this._streams).some((stream) => stream.socket === socket && !stream.turnEnded)) {
22982
+ return true;
22983
+ }
22984
+ socket.close();
22985
+ return false;
22871
22986
  });
22872
22987
  }
22873
22988
  static generateUUID() {
@@ -22878,7 +22993,7 @@ Path:${messageTypes.SPEECH_CONFIG}${_MsEdgeTTS.JSON_XML_DELIM}
22878
22993
  });
22879
22994
  }
22880
22995
  static async generateSecMsGec(trustedClientToken) {
22881
- const ticks = Math.floor(Date.now() / 1e3) + 11644473600;
22996
+ const ticks = Math.floor((Date.now() + _MsEdgeTTS._clockOffsetMs) / 1e3) + 11644473600;
22882
22997
  const rounded = ticks - ticks % 300;
22883
22998
  const windowsTicks = rounded * 1e7;
22884
22999
  const encoder = new TextEncoder();
@@ -22886,23 +23001,58 @@ Path:${messageTypes.SPEECH_CONFIG}${_MsEdgeTTS.JSON_XML_DELIM}
22886
23001
  const hashBuffer = await crypto.subtle.digest("SHA-256", data);
22887
23002
  return Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, "0")).join("").toUpperCase();
22888
23003
  }
22889
- async _send(message) {
22890
- for (let i = 1; i <= 3 && this._ws.readyState !== this._ws.OPEN; i++) {
23004
+ async _send(message, requestId, initialSocket) {
23005
+ let socket = initialSocket ?? this._ws;
23006
+ for (let i = 1; !initialSocket && i <= 3 && socket.readyState !== socket.OPEN; i++) {
23007
+ if (requestId && !this._streams[requestId])
23008
+ return;
22891
23009
  if (i == 1) {
22892
23010
  this._startTime = Date.now();
22893
23011
  }
22894
23012
  this._log("connecting: ", i);
22895
23013
  await this._initClient();
23014
+ socket = this._ws;
22896
23015
  }
22897
- this._ws.send(message, () => {
23016
+ if (requestId) {
23017
+ const stream = this._streams[requestId];
23018
+ if (!stream || stream.audio.destroyed || stream.turnEnded)
23019
+ return;
23020
+ stream.socket = socket;
23021
+ }
23022
+ if (socket.readyState !== socket.OPEN)
23023
+ throw new Error("Edge TTS WebSocket is not open.");
23024
+ if (requestId)
23025
+ this._resetSynthesisTimeout(requestId);
23026
+ if (this._isBrowser) {
23027
+ socket.send(message);
22898
23028
  this._log("<-", message);
23029
+ return;
23030
+ }
23031
+ await new Promise((resolve, reject) => {
23032
+ socket.send(message, (error) => {
23033
+ if (error)
23034
+ return reject(error);
23035
+ this._log("<-", message);
23036
+ resolve();
23037
+ });
22899
23038
  });
22900
23039
  }
23040
+ _resetSynthesisTimeout(requestId) {
23041
+ const stream = this._streams[requestId];
23042
+ if (!stream || stream.audio.destroyed || stream.turnEnded)
23043
+ return;
23044
+ clearTimeout(stream.timeout);
23045
+ if (this._synthesisTimeoutMs) {
23046
+ stream.timeout = setTimeout(() => {
23047
+ stream.audio.destroy(new Error(`Edge TTS synthesis timed out after ${this._synthesisTimeoutMs} milliseconds without activity.`));
23048
+ }, this._synthesisTimeoutMs);
23049
+ }
23050
+ }
22901
23051
  _pushAudioData(data, requestId) {
22902
- this._streams[requestId].audio.push(data);
23052
+ this._streams[requestId]?.audio.push(data);
22903
23053
  }
22904
23054
  _pushMetadata(data, requestId) {
22905
- this._streams[requestId].metadata.push(data);
23055
+ this._streams[requestId]?.metadata?.push(data);
22906
23056
  }
22907
23057
  _SSMLTemplate(input, options = {}) {
22908
23058
  options = { ...new Prosody_1.ProsodyOptions(), ...options };
@@ -22938,16 +23088,16 @@ Path:${messageTypes.SPEECH_CONFIG}${_MsEdgeTTS.JSON_XML_DELIM}
22938
23088
  const oldOutputFormat = this._outputFormat;
22939
23089
  const oldOptions = JSON.stringify(this._metadataOptions);
22940
23090
  this._voice = voiceName;
22941
- if (!this._metadataOptions.voiceLocale || !metadataOptions.voiceLocale && oldVoice !== this._voice) {
23091
+ Object.assign(this._metadataOptions, metadataOptions);
23092
+ if (!metadataOptions?.voiceLocale && (!this._metadataOptions.voiceLocale || oldVoice !== this._voice)) {
22942
23093
  const voiceLangMatch = _MsEdgeTTS.VOICE_LANG_REGEX.exec(this._voice);
22943
23094
  if (!voiceLangMatch)
22944
23095
  throw new Error("Could not infer voiceLocale from voiceName, and no voiceLocale was specified!");
22945
23096
  this._metadataOptions.voiceLocale = voiceLangMatch[0];
22946
23097
  }
22947
23098
  this._outputFormat = outputFormat;
22948
- Object.assign(this._metadataOptions, metadataOptions);
22949
23099
  const changed = oldVoice !== this._voice || oldOutputFormat !== this._outputFormat || oldOptions !== JSON.stringify(this._metadataOptions);
22950
- if (!changed && this._ws.readyState === this._ws.OPEN) {
23100
+ if (!changed && !this._clientInit && this._ws?.readyState === isomorphic_ws_1.default.OPEN && !this._retiredSockets.includes(this._ws)) {
22951
23101
  return;
22952
23102
  }
22953
23103
  this._startTime = Date.now();
@@ -22961,7 +23111,18 @@ Path:${messageTypes.SPEECH_CONFIG}${_MsEdgeTTS.JSON_XML_DELIM}
22961
23111
  * Close the WebSocket connection.
22962
23112
  */
22963
23113
  close() {
22964
- this._ws?.close();
23114
+ this._clientGeneration++;
23115
+ const sockets = new Set(this._retiredSockets);
23116
+ if (this._ws)
23117
+ sockets.add(this._ws);
23118
+ this._retiredSockets = [];
23119
+ for (const stream of Object.values(this._streams)) {
23120
+ clearTimeout(stream.timeout);
23121
+ if (!stream.turnEnded) {
23122
+ stream.audio.destroy(new Error("Stream closed before the synthesis completed (no turn.end received). The audio is likely truncated."));
23123
+ }
23124
+ }
23125
+ sockets.forEach((socket) => this._closeSocket(socket));
22965
23126
  }
22966
23127
  /**
22967
23128
  * Writes raw audio synthesised from text to a file. Uses a basic {@link _SSMLTemplate SML template}.
@@ -23023,7 +23184,7 @@ Path:${messageTypes.SPEECH_CONFIG}${_MsEdgeTTS.JSON_XML_DELIM}
23023
23184
  resolve(audioFilePath);
23024
23185
  } else {
23025
23186
  reject(new Error("No audio data received"));
23026
- fs.unlinkSync(audioFilePath);
23187
+ fs.rmSync(audioFilePath, { force: true });
23027
23188
  }
23028
23189
  });
23029
23190
  writableAudioFile.once("error", reject);
@@ -23043,7 +23204,7 @@ Path:${messageTypes.SPEECH_CONFIG}${_MsEdgeTTS.JSON_XML_DELIM}
23043
23204
  resolve(metadataFilePath);
23044
23205
  } else {
23045
23206
  reject(new Error("No metadata received"));
23046
- fs.unlinkSync(metadataFilePath);
23207
+ fs.rmSync(metadataFilePath, { force: true });
23047
23208
  }
23048
23209
  });
23049
23210
  metadataStream.once("error", reject);
@@ -23072,7 +23233,9 @@ Path:${messageTypes.SSML}${_MsEdgeTTS.JSON_XML_DELIM}` + requestSSML.trim();
23072
23233
  read() {
23073
23234
  },
23074
23235
  destroy(error, callback) {
23236
+ clearTimeout(self2._streams[requestId]?.timeout);
23075
23237
  delete self2._streams[requestId];
23238
+ self2._closeRetiredSockets();
23076
23239
  callback(error);
23077
23240
  }
23078
23241
  });
@@ -23093,7 +23256,9 @@ Path:${messageTypes.SSML}${_MsEdgeTTS.JSON_XML_DELIM}` + requestSSML.trim();
23093
23256
  metadata: metadataStream,
23094
23257
  turnEnded: false
23095
23258
  };
23096
- this._send(request).then();
23259
+ this._send(request, requestId).catch((error) => {
23260
+ this._streams[requestId]?.audio.destroy(error);
23261
+ });
23097
23262
  return { audioStream, metadataStream, requestId };
23098
23263
  }
23099
23264
  };
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "dsh-voice-mode",
3
- "description": "Full-duplex voice plugin for DeepSeek Harness: local zipformer2 streaming ASR (no API key) → editable draft; Edge TTS or local VITS / Kokoro read-aloud with live captions; true barge-in; hardened HTTP surface + model SHA256 pinning; compatible with all dsh releases since 0.1.1-rc.2 (verified 0.1.1-rc.2 → 0.2.0-rc.2).",
3
+ "description": "Full-duplex voice plugin for DeepSeek Harness: local zipformer2 streaming ASR (no API key) → editable draft; Edge TTS or local VITS / Kokoro read-aloud with live captions; true barge-in; hardened HTTP surface + model SHA256 pinning; compatible with all dsh releases since 0.1.1-rc.2 (verified 0.1.1-rc.2 → 0.2.1-alpha.3).",
4
4
  "icon": "./icon.svg",
5
- "version": "0.7.23",
5
+ "version": "0.7.24",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",
8
8
  "repository": {
@@ -47,7 +47,7 @@
47
47
  "scripts": {
48
48
  "build": "node build.mjs",
49
49
  "prepack": "node build.mjs",
50
- "test": "node test/segmenter.test.mjs && node test/aec.test.mjs && node test/download.test.mjs && node test/endpoint.test.mjs && node test/endpoint-short.test.mjs && node test/resample.test.mjs && node test/sense-worker.test.mjs && node test/detect-route.test.mjs && node test/verify-client.mjs && node test/asr-host-rebuild.test.mjs && node test/barge-in-manual.test.mjs && node test/sense-lang.test.mjs && node test/caption-a11y.test.mjs && node test/emotion.test.mjs && node test/emotion-tts-local.test.mjs && node test/emotion-integration.test.mjs && node test/backchannel.test.mjs && node test/strings-coverage.test.mjs && node test/yield-ms-wiring.test.mjs && node test/matchBackchannel.test.mjs && node test/settings-load.test.mjs && node test/preview-error.test.mjs && node test/hold-clear.test.mjs && node test/barge-in-detect.test.mjs && node test/wakeword.test.mjs && node test/wake-standby.test.mjs && node test/wake-flow.test.mjs && node test/tts-playback.test.mjs && node test/settings-store.test.mjs && node test/i18n.test.mjs && node test/i18n-protocol.test.mjs && node test/package-install.test.mjs && node test/tts-runtime.test.mjs",
50
+ "test": "node test/segmenter.test.mjs && node test/aec.test.mjs && node test/download.test.mjs && node test/endpoint.test.mjs && node test/endpoint-short.test.mjs && node test/resample.test.mjs && node test/sense-worker.test.mjs && node test/detect-route.test.mjs && node test/verify-client.mjs && node test/asr-host-rebuild.test.mjs && node test/barge-in-manual.test.mjs && node test/sense-lang.test.mjs && node test/caption-a11y.test.mjs && node test/emotion.test.mjs && node test/emotion-tts-local.test.mjs && node test/emotion-integration.test.mjs && node test/backchannel.test.mjs && node test/strings-coverage.test.mjs && node test/yield-ms-wiring.test.mjs && node test/matchBackchannel.test.mjs && node test/settings-load.test.mjs && node test/preview-error.test.mjs && node test/hold-clear.test.mjs && node test/barge-in-detect.test.mjs && node test/wakeword.test.mjs && node test/wake-standby.test.mjs && node test/wake-flow.test.mjs && node test/tts-playback.test.mjs && node test/settings-store.test.mjs && node test/i18n.test.mjs && node test/i18n-protocol.test.mjs && node test/package-install.test.mjs && node test/tts-runtime.test.mjs && node test/host-hardening.test.mjs",
51
51
  "verify:client": "node test/verify-client.mjs",
52
52
  "prefetch": "node scripts/prefetch.mjs",
53
53
  "list-voices": "node scripts/list-voices.mjs",
@@ -91,7 +91,6 @@
91
91
  "react": "^18.2.0"
92
92
  },
93
93
  "devDependencies": {
94
- "msedge-tts": "^2.0.7",
95
94
  "@deepseek-ai/cordis": "^4.0.2",
96
95
  "@deepseek-ai/dsh-host-webserver": "0.1.5-rc.1",
97
96
  "@deepseek-ai/dsh-llm": "0.1.5-rc.1",
@@ -100,6 +99,7 @@
100
99
  "@types/node": "^26.0.0",
101
100
  "@types/react": "^19.0.0",
102
101
  "esbuild": "^0.25.0",
102
+ "msedge-tts": "^2.1.0",
103
103
  "playwright-core": "1.62.1",
104
104
  "typescript": "^5.9.2"
105
105
  },