dsh-voice-mode 0.7.25 → 0.7.26

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/lib/index.js CHANGED
@@ -183,6 +183,16 @@ async function sha256OfFile(path) {
183
183
  });
184
184
  return hash.digest("hex");
185
185
  }
186
+ var MODEL_FETCH_HEADERS_TIMEOUT_MS = 6e4;
187
+ async function fetchWithHeadersTimeout(url, init) {
188
+ const ac = new AbortController();
189
+ const timer = setTimeout(() => ac.abort(new Error("model fetch headers timeout")), MODEL_FETCH_HEADERS_TIMEOUT_MS);
190
+ try {
191
+ return await fetch(url, { ...init, signal: ac.signal });
192
+ } finally {
193
+ clearTimeout(timer);
194
+ }
195
+ }
186
196
  async function ensureModelFile(opts) {
187
197
  const { repoDir, spec, primaryHost, broadcast } = opts;
188
198
  const localPath = join(repoDir, spec.file);
@@ -216,7 +226,7 @@ async function downloadVerified(opts) {
216
226
  const resumeFrom = partSt?.isFile() ? partSt.size : 0;
217
227
  const headers = { "user-agent": "dsh-voice-mode" };
218
228
  if (resumeFrom > 0) headers.range = `bytes=${resumeFrom}-`;
219
- const res = await fetch(url, { headers, redirect: "follow" });
229
+ const res = await fetchWithHeadersTimeout(url, { headers, redirect: "follow" });
220
230
  if (!redirectHostAllowed(res.url, allowCustomHost)) return false;
221
231
  if (res.status === 416) {
222
232
  if (await sha256OfFile(partPath).catch(() => "") === spec.sha256) {
@@ -281,7 +291,9 @@ async function ensureModelTree(opts) {
281
291
  let tree = [];
282
292
  for (const host of hosts) {
283
293
  try {
284
- const res = await fetch(host + "/api/models/" + repo + "?blobs=true", { headers: { "user-agent": "dsh-voice-mode" } });
294
+ const res = await fetchWithHeadersTimeout(host + "/api/models/" + repo + "?blobs=true", {
295
+ headers: { "user-agent": "dsh-voice-mode" }
296
+ });
285
297
  if (res.ok) {
286
298
  const j = await res.json();
287
299
  tree = (j.siblings ?? []).map((s) => s.rfilename ?? "").filter((f) => isSafeModelRel(f, subdir));
@@ -535,6 +547,7 @@ function createAsrRuntime(options) {
535
547
  let senseWorker = null;
536
548
  let senseWorkerSyncing = null;
537
549
  let senseWorkerLangKey = "";
550
+ let senseDisposed = false;
538
551
  const getSenseWorker = async () => {
539
552
  if (!senseVoice()) return null;
540
553
  const langKey = `auto\0${senseITN() ? "1" : "0"}`;
@@ -547,6 +560,7 @@ function createAsrRuntime(options) {
547
560
  if (senseWorker) return senseWorker;
548
561
  if (senseWorkerSyncing) return senseWorkerSyncing;
549
562
  senseWorkerSyncing = (async () => {
563
+ if (senseDisposed) return null;
550
564
  const sensePath = await ensureSenseModel();
551
565
  if (!sensePath) return null;
552
566
  try {
@@ -569,6 +583,10 @@ function createAsrRuntime(options) {
569
583
  await client.terminate();
570
584
  return null;
571
585
  }
586
+ if (senseDisposed) {
587
+ await client.terminate();
588
+ return null;
589
+ }
572
590
  senseWorker = client;
573
591
  return client;
574
592
  } catch (e) {
@@ -576,7 +594,7 @@ function createAsrRuntime(options) {
576
594
  return null;
577
595
  }
578
596
  })().finally(() => {
579
- if (!senseWorker) senseWorkerSyncing = null;
597
+ if (!senseWorker || senseDisposed) senseWorkerSyncing = null;
580
598
  });
581
599
  return senseWorkerSyncing;
582
600
  };
@@ -679,10 +697,15 @@ function createAsrRuntime(options) {
679
697
  if (sessSegs.size === 0) segments.delete(sessionId);
680
698
  const finalizeP = (async () => {
681
699
  const all = seg.allSamples;
700
+ let senseTimer = null;
682
701
  const senseP = all.length > 0 ? Promise.race([
683
702
  senseTranscribe(all),
684
- new Promise((resolve) => setTimeout(() => resolve(null), 2e4))
685
- ]) : Promise.resolve(null);
703
+ new Promise((resolve) => {
704
+ senseTimer = setTimeout(() => resolve(null), 2e4);
705
+ })
706
+ ]).finally(() => {
707
+ if (senseTimer) clearTimeout(senseTimer);
708
+ }) : Promise.resolve(null);
686
709
  const pad = new Float32Array(rec.config.featConfig.sampleRate / 2);
687
710
  seg.stream.acceptWaveform(rec.config.featConfig.sampleRate, pad);
688
711
  while (rec.isReady(seg.stream)) rec.decode(seg.stream);
@@ -744,6 +767,15 @@ function createAsrRuntime(options) {
744
767
  finalized.delete(sid);
745
768
  }
746
769
  }
770
+ for (const sid of finalized.keys()) {
771
+ if (segments.has(sid) || finalizing.has(sid)) continue;
772
+ finalized.delete(sid);
773
+ resetGen.delete(sid);
774
+ }
775
+ for (const sid of resetGen.keys()) {
776
+ if (segments.has(sid) || finalizing.has(sid)) continue;
777
+ resetGen.delete(sid);
778
+ }
747
779
  for (const [sid, at] of detectVadLastUse) {
748
780
  if (now - at > SEGMENT_IDLE_MS) {
749
781
  try {
@@ -797,6 +829,7 @@ function createAsrRuntime(options) {
797
829
  },
798
830
  dispose: () => {
799
831
  clearInterval(sweepTimer);
832
+ senseDisposed = true;
800
833
  let w = senseWorker;
801
834
  senseWorker = null;
802
835
  senseWorkerSyncing = null;
@@ -840,10 +873,15 @@ function createAsrRuntime(options) {
840
873
  // 内部 5s 上限防止慢模型下载 hang 住 enterMode(失败/超时静默降级走 finalize 时 race)。
841
874
  warmupSense: async () => {
842
875
  if (!senseVoice()) return;
876
+ let warmupTimer = null;
843
877
  await Promise.race([
844
878
  getSenseWorker().then(() => void 0).catch(() => void 0),
845
- new Promise((resolve) => setTimeout(resolve, 5e3))
846
- ]);
879
+ new Promise((resolve) => {
880
+ warmupTimer = setTimeout(resolve, 5e3);
881
+ })
882
+ ]).finally(() => {
883
+ if (warmupTimer) clearTimeout(warmupTimer);
884
+ });
847
885
  },
848
886
  // 批 A:仅清缓存键——不 dispose recognizer/senseWorker,避免破坏 I1(in-flight
849
887
  // finalize 拿到的旧 recognizer 引用被 free 会丢句)。让现有 fingerprint-gated 路径
@@ -1065,6 +1103,7 @@ var SentenceSegmenter = class {
1065
1103
  import { MsEdgeTTS, OUTPUT_FORMAT } from "./msedge-tts.cjs";
1066
1104
  var MP3_MAGIC = 255;
1067
1105
  var TTS_METADATA = { wordBoundaryEnabled: false, sentenceBoundaryEnabled: false };
1106
+ var EDGE_VOICES_TIMEOUT_MS = 3e4;
1068
1107
  function prosodyFromRate(rate) {
1069
1108
  if (rate !== void 0 && rate > 0 && rate !== 1) return { rate };
1070
1109
  return void 0;
@@ -1113,7 +1152,15 @@ async function listEdgeVoices(force = false) {
1113
1152
  if (edgeVoicesCache && !force) return edgeVoicesCache;
1114
1153
  const tts = new MsEdgeTTS();
1115
1154
  try {
1116
- const voices = await tts.getVoices();
1155
+ let voicesTimer = null;
1156
+ const voices = await Promise.race([
1157
+ tts.getVoices(),
1158
+ new Promise((_, reject) => {
1159
+ voicesTimer = setTimeout(() => reject(new Error("edge voices request timed out")), EDGE_VOICES_TIMEOUT_MS);
1160
+ })
1161
+ ]).finally(() => {
1162
+ if (voicesTimer) clearTimeout(voicesTimer);
1163
+ });
1117
1164
  edgeVoicesCache = voices.map((v) => ({
1118
1165
  ShortName: v.ShortName,
1119
1166
  Locale: v.Locale,
@@ -1136,6 +1183,38 @@ var TtsQueue = class {
1136
1183
  onError;
1137
1184
  /** 单句合成重试耗尽被跳过通知(每句一次;此前是静默丢句——真机「回复偶尔不朗读」根因之一)。 */
1138
1185
  onSkip;
1186
+ /**
1187
+ * M7②(Issue #15 R11):退避重启计时器句柄集。
1188
+ *
1189
+ * 漏洞:pump 失败退避路径的 `setTimeout(() => void this.pump(...), delay)` 不持句柄,
1190
+ * close() 无从取消。close 后计时器仍触发 pump → 若该会话还有 pending,就会调
1191
+ * engine.synthesize → 本地引擎 ensureReady() **重新 fork 合成子进程**——插件已卸载、
1192
+ * 引擎已 close,却留下一个孤儿子进程(热重载每代泄漏一个,CPU/内存常驻)。
1193
+ * 修法:句柄入集,触发即自摘;close() 时全量 clearTimeout(与 asr-host senseP、
1194
+ * listEdgeVoices 的 timer 修法同构)。
1195
+ */
1196
+ backoffTimers = /* @__PURE__ */ new Set();
1197
+ /**
1198
+ * R13(Issue #15 Important-1):重试 sleep 计时器句柄集。
1199
+ *
1200
+ * 与 backoffTimers 分开而非合并:语义不同(一个是「失败退避后重启泵」,一个是
1201
+ * 「单句合成重试间的 sleep」),且 sleep 由 retrySleep 统一创建、落定即自摘。
1202
+ * 不持句柄的后果:close 落进 400/800ms sleep 窗口时,该 timer 仍会走完——
1203
+ * 残留一个 ref'd Timeout 拖住事件循环 ≤800ms(同型反模式家族第 5 处,
1204
+ * 前三处:asr-host senseP、listEdgeVoices、warmupSense;第四处 backoffTimers)。
1205
+ */
1206
+ retryTimers = /* @__PURE__ */ new Set();
1207
+ /** R13:可取消的重试 sleep——句柄入集供 close() 取消;落定即自摘。 */
1208
+ retrySleep(ms) {
1209
+ if (this.closed) return Promise.resolve();
1210
+ return new Promise((resolve) => {
1211
+ const timer = setTimeout(() => {
1212
+ this.retryTimers.delete(timer);
1213
+ resolve();
1214
+ }, ms);
1215
+ this.retryTimers.add(timer);
1216
+ });
1217
+ }
1139
1218
  constructor(options) {
1140
1219
  this.engine = options.engine;
1141
1220
  this.onError = options.onError;
@@ -1146,13 +1225,27 @@ var TtsQueue = class {
1146
1225
  return this.engine.mime;
1147
1226
  }
1148
1227
  /**
1149
- * 运行时切换引擎(设置面板「朗读引擎」即时生效):
1150
- * 关闭旧引擎、清空所有会话队列;新句子用新引擎合成。
1228
+ * 运行时切换引擎(设置面板「朗读引擎」即时生效 / Kokoro 精度切换 / 清理模型缓存后重建):
1229
+ * 关闭旧引擎、作废所有会话的在途与积压;新句子用新引擎合成。
1230
+ *
1231
+ * B1(Issue #15 审查 Blocker):早年实现只 `this.queues.clear()`——不升各队列的
1232
+ * epoch,也不保留队列本身,两处都错:
1233
+ * 1) 孤儿泵不停播:在途 synthesize 完成后 `item.epoch === q.epoch` 恒真,旧引擎的
1234
+ * 帧继续下行,与新引擎的帧双轨广播(prune() 已修同一反模式,setEngine 漏修);
1235
+ * 2) seq 归零撞拒绝线:删队列后重入的新 SessionQueue seq 从 0 起算,而 client 的
1236
+ * sentenceId 拒绝线(rejectSeqUpTo)是「旧会话遗留的最大句号」,新回复前 N 句
1237
+ * 全部 ≤ 线被静默丢弃——正是 /toggle 用 cancel 而非 prune 保 seq 连续的同一条
1238
+ * 不变式(index.ts:1177 进模式 cancel / :1191 让出旧会话 cancel(previous) / :1210 退出 cancel)。
1239
+ * 故此处与 cancel() 同构:逐队列 epoch++ + 清积压,但保留 SessionQueue 对象本身
1240
+ * (seq 连续递增,跨引擎切换不归零)。
1151
1241
  */
1152
1242
  setEngine(engine) {
1153
1243
  const old = this.engine;
1154
1244
  this.engine = engine;
1155
- this.queues.clear();
1245
+ for (const q of this.queues.values()) {
1246
+ q.epoch++;
1247
+ q.pending.length = 0;
1248
+ }
1156
1249
  void old.close().catch(() => {
1157
1250
  });
1158
1251
  }
@@ -1168,6 +1261,7 @@ var TtsQueue = class {
1168
1261
  }
1169
1262
  /** 触发当前引擎预热/下载模型并初始化(设置面板「下载」按钮;Edge 为无操作)。 */
1170
1263
  async prepare() {
1264
+ if (this.closed) return;
1171
1265
  await this.engine.prepare?.();
1172
1266
  }
1173
1267
  /**
@@ -1175,6 +1269,7 @@ var TtsQueue = class {
1175
1269
  * 失败(含非法音色)抛错。
1176
1270
  */
1177
1271
  async synthesize(text, options = {}) {
1272
+ if (this.closed) throw new Error("tts queue closed");
1178
1273
  return this.engine.synthesize(text, options);
1179
1274
  }
1180
1275
  subscribe(listener) {
@@ -1183,8 +1278,21 @@ var TtsQueue = class {
1183
1278
  this.listeners.delete(listener);
1184
1279
  };
1185
1280
  }
1281
+ /**
1282
+ * I-1(Issue #15 R12):关闭闸门。close() 最早期置位,此后:
1283
+ * · enqueue 不再入队/起泵;
1284
+ * · pump 入口直接返回;
1285
+ * · pump while 不再取新句(在途那句已发出的 synthesize 允许自然结束——无法取消,
1286
+ * 但其结果不再广播,因为客户端已断开、广播无接收方);
1287
+ * · finally 的 pending>0 分支不再重排(即时重启与 backoff timer 都不排)。
1288
+ * 缺此闸门时 close 后仍会触达 engine.synthesize,而 tts-local 的 close() 已把
1289
+ * child/childInit/ready 全置 null → ensureReady 首行守卫失效 → 重走模型校验 + fork
1290
+ * 新子进程(热重载每代泄漏一个孤儿子进程)。详见 close() 处注释。
1291
+ */
1292
+ closed = false;
1186
1293
  /** 为某会话入队一句;若泵空闲则启动。 */
1187
1294
  enqueue(sessionId, text) {
1295
+ if (this.closed) return;
1188
1296
  let q = this.queues.get(sessionId);
1189
1297
  if (!q) {
1190
1298
  q = { pending: [], busy: false, seq: 0, epoch: 0, errorNotified: false, backoff: 0, failStreak: 0 };
@@ -1219,25 +1327,28 @@ var TtsQueue = class {
1219
1327
  this.queues.delete(sessionId);
1220
1328
  }
1221
1329
  async pump(sessionId, q) {
1222
- if (q.busy) return;
1330
+ if (this.closed || q.busy) return;
1223
1331
  q.busy = true;
1224
1332
  try {
1225
1333
  while (q.pending.length > 0) {
1334
+ if (this.closed) break;
1226
1335
  const item = q.pending.shift();
1227
1336
  const MAX_SYNTH_ATTEMPTS = 3;
1228
1337
  let buf = null;
1229
1338
  for (let attempt = 0; attempt < MAX_SYNTH_ATTEMPTS; attempt++) {
1230
1339
  if (item.epoch !== q.epoch) break;
1340
+ if (this.closed) break;
1231
1341
  try {
1232
1342
  buf = await this.engine.synthesize(item.text);
1233
1343
  break;
1234
1344
  } catch (e) {
1235
1345
  console.warn(`[dsh-voice-mode] synthesis failed (${attempt + 1}/${MAX_SYNTH_ATTEMPTS}): ${String(e)}`);
1236
1346
  if (attempt < MAX_SYNTH_ATTEMPTS - 1) {
1237
- await new Promise((r) => setTimeout(r, 400 * (attempt + 1)));
1347
+ await this.retrySleep(400 * (attempt + 1));
1238
1348
  }
1239
1349
  }
1240
1350
  }
1351
+ if (this.closed) break;
1241
1352
  if (item.epoch !== q.epoch) continue;
1242
1353
  if (buf === null) {
1243
1354
  q.failStreak++;
@@ -1288,15 +1399,26 @@ var TtsQueue = class {
1288
1399
  } finally {
1289
1400
  q.busy = false;
1290
1401
  if (this.queues.get(sessionId) !== q) return;
1402
+ if (this.closed) return;
1291
1403
  if (q.pending.length > 0) {
1292
1404
  const delay = q.errorNotified ? q.backoff : 0;
1293
1405
  q.backoff = Math.min(8e3, delay + 1e3);
1294
- if (delay > 0) setTimeout(() => void this.pump(sessionId, q), delay);
1295
- else void this.pump(sessionId, q);
1406
+ if (delay > 0) {
1407
+ const timer = setTimeout(() => {
1408
+ this.backoffTimers.delete(timer);
1409
+ void this.pump(sessionId, q);
1410
+ }, delay);
1411
+ this.backoffTimers.add(timer);
1412
+ } else void this.pump(sessionId, q);
1296
1413
  }
1297
1414
  }
1298
1415
  }
1299
1416
  async close() {
1417
+ this.closed = true;
1418
+ for (const timer of this.backoffTimers) clearTimeout(timer);
1419
+ this.backoffTimers.clear();
1420
+ for (const timer of this.retryTimers) clearTimeout(timer);
1421
+ this.retryTimers.clear();
1300
1422
  await this.engine.close();
1301
1423
  }
1302
1424
  };
@@ -1662,6 +1784,7 @@ function createSherpaLocalEngine(options) {
1662
1784
  const workerPath = fileURLToPath2(new URL("./tts-vits-worker.cjs", import.meta.url));
1663
1785
  let child = null;
1664
1786
  let childInit = false;
1787
+ let closed = false;
1665
1788
  const respawnChild = async () => {
1666
1789
  if (child) {
1667
1790
  child.kill();
@@ -1700,6 +1823,7 @@ function createSherpaLocalEngine(options) {
1700
1823
  engineErrorCode = void 0;
1701
1824
  downloadProgress = null;
1702
1825
  try {
1826
+ if (closed) return;
1703
1827
  if (!child || !childInit) {
1704
1828
  for (const f of spec.files) {
1705
1829
  const ok = await ensureModelFile({
@@ -1710,6 +1834,7 @@ function createSherpaLocalEngine(options) {
1710
1834
  allowCustomHost,
1711
1835
  broadcast: trackedBroadcast
1712
1836
  });
1837
+ if (closed) return;
1713
1838
  if (!ok) throw new Error("local TTS model download/verify failed: " + f.file);
1714
1839
  }
1715
1840
  if (options.kind === "kokoro") {
@@ -1776,9 +1901,15 @@ function createSherpaLocalEngine(options) {
1776
1901
  } finally {
1777
1902
  engineLoading = false;
1778
1903
  }
1779
- })().finally(() => {
1780
- ready = null;
1781
- });
1904
+ })().then(
1905
+ (v) => {
1906
+ return v;
1907
+ },
1908
+ (e) => {
1909
+ ready = null;
1910
+ throw e;
1911
+ }
1912
+ );
1782
1913
  }
1783
1914
  return ready;
1784
1915
  };
@@ -1822,7 +1953,9 @@ function createSherpaLocalEngine(options) {
1822
1953
  // 设置面板「下载」按钮:无文本也触发模型下载 + 子进程初始化(与首次合成路径一致)。
1823
1954
  prepare: () => ensureReady(),
1824
1955
  async synthesize(text, opts = {}) {
1956
+ if (closed) throw new Error("local TTS engine closed");
1825
1957
  await ensureReady();
1958
+ if (closed) throw new Error("local TTS engine closed");
1826
1959
  const sid = spec.toSid(opts.voice ?? voice);
1827
1960
  const spd = typeof opts.rate === "number" && Number.isFinite(opts.rate) ? Math.min(2, Math.max(0.5, opts.rate)) : speed;
1828
1961
  const segments = parseEmotionTags(text);
@@ -1869,6 +2002,7 @@ function createSherpaLocalEngine(options) {
1869
2002
  return pcmToWav(floatToPcm16(merged), resolvedSampleRate || 16e3);
1870
2003
  },
1871
2004
  async close() {
2005
+ closed = true;
1872
2006
  const c = child;
1873
2007
  if (c) {
1874
2008
  try {
@@ -1956,17 +2090,23 @@ var en = {
1956
2090
  disabled: "Voice mode disabled (plugin enabled=false)",
1957
2091
  sendFailKept: "Send failed; text kept in draft",
1958
2092
  micDenied: "Microphone denied: allow mic access for this site",
2093
+ micBusy: "Microphone is in use by another program \u2014 close it and retry",
1959
2094
  micUnavailable: "Microphone unavailable",
1960
2095
  recognizing: "Recognizing\u2026",
2096
+ // UX-I1 联动态:纠错在途 / 纠错放弃回退 / 附和词忽略 / 语音按钮态文案。
2097
+ correctFixing: "Correcting\u2026",
2098
+ correctAbandoned: "Original text kept in draft",
2099
+ backchannelDropped: "Backchannel ignored, not sent",
2100
+ buttonLoading: "Loading\u2026",
2101
+ buttonListening: "Listening",
1961
2102
  holdToTalk: "Hold to talk",
1962
2103
  releaseToSend: "Release to send",
1963
- voiceDetected: "Voice active",
1964
2104
  entering: "Entering\u2026",
1965
2105
  voiceBtn: "Voice",
1966
2106
  ariaActive: "Voice mode active",
1967
2107
  ariaEnter: "Enter voice mode",
1968
2108
  titleHold: "Voice mode \xB7 hold to talk, release to send; tap to exit; Esc/blur cancels; Ctrl+Shift+V exits",
1969
- titleToggle: "Voice mode \xB7 click to exit (Ctrl+Shift+V) \xB7 hold Ctrl to send now",
2109
+ titleToggle: "Voice mode \xB7 click to exit (Ctrl+Shift+V) \xB7 hold Ctrl while speaking to send now",
1970
2110
  titleEnter: "Enter voice mode (Ctrl+Shift+V)",
1971
2111
  loadingModel: "Loading model\u2026",
1972
2112
  listening: "Listening\u2026",
@@ -1977,13 +2117,18 @@ var en = {
1977
2117
  sayWake: 'Say "{wake}" to start',
1978
2118
  reading: "Reading aloud\u2026",
1979
2119
  recognitionFail: "Recognition failed, try again",
2120
+ partialFail: "Live captions temporarily unavailable (recognition channel error, retrying)",
2121
+ detectFail: "Break-in detection temporarily unavailable (detect channel error, retrying)",
2122
+ sseReconnect: "State sync disconnected, reconnecting\u2026",
2123
+ diagCopy: "Copy diagnostics",
2124
+ diagCopied: "Diagnostics copied",
2125
+ diagCopyFailed: "Copy failed (clipboard rejected by browser)",
1980
2126
  sessionExpired: "Voice session expired, reconnecting\u2026",
1981
2127
  sessionExpiredFail: "Voice session reconnect failed; please re-enter voice mode",
1982
2128
  modelDownloadFail: "Model download failed ({file}): check network and re-enter voice mode",
1983
2129
  startFail: "Voice mode failed to start: {err}",
1984
2130
  holdDots: "Hold to talk\u2026",
1985
2131
  exit: "Exit",
1986
- skip: "Skip",
1987
2132
  configUnavailableNote: " (settings document not ready; the panel will appear when it is).",
1988
2133
  previewNameFirst: "Enter a voice ShortName first",
1989
2134
  previewDisabled: "Voice mode disabled (plugin enabled=false); preview unavailable",
@@ -2010,7 +2155,7 @@ var en = {
2010
2155
  descVoiceKokoro: "Kokoro zh-en voices (103; \u25C0\u25B6 to cycle; 48-51 named Chinese, others numbered with measured gender; mixed zh-en supported)",
2011
2156
  descRate: "Speech rate (0.5 slow \u2013 2.0 fast, 1.1 default; more compact replies)",
2012
2157
  descInterrupt: "Interrupt sensitivity (0 high \u22480.3 s confirm / 1 medium \u22480.2 s / 2 low \u22480.1 s, most responsive); lower = higher barrier = harder to interrupt",
2013
- descBargeIn: "Barge-in mode (detect: auto-probe native echo cancellation, fall back to hold-to-talk when inactive \u2014 default; auto: force interrupt by speaking \u2014 headphones/quiet; manual: for loudspeaker, no echo-triggered self-interrupt \u2014 hold mic/Ctrl to interrupt)",
2158
+ descBargeIn: "Barge-in mode (detect: auto-probe native echo cancellation, fall back to hold-to-talk when inactive \u2014 default; auto: force interrupt by speaking \u2014 headphones/quiet; manual: for loudspeaker, no echo-triggered self-interrupt \u2014 hold mic/Ctrl to interrupt). Note: in manual mode (including detect falling back to manual on machines without native echo cancellation) audio outside a press is not recognized \u2014 in toggle mode you can long-press to speak only while the agent is playing; when idle there is no voice input, so use hold mode or switch to auto/detect",
2014
2159
  bargeInDetect: "Auto-detect",
2015
2160
  bargeInAuto: "Auto",
2016
2161
  bargeInManual: "Manual",
@@ -2021,22 +2166,29 @@ var en = {
2021
2166
  aecOffHint: "Native echo cancellation is not active (speaker echo may self-interrupt); use headphones or Manual barge-in",
2022
2167
  // 批 7O(ADR-0006):detect 模式第一级探测降级提示(英文)。
2023
2168
  bargeInDetectFallback: "Native echo cancellation is off \u2014 switched to hold-to-talk barge-in",
2169
+ // R1 收尾(fix-client 直连 tk() 调用):连续 3 次回声拒断的解释出口 + 快捷键非法停用提示。
2170
+ echoRejectHint: "Strong echo detected \u2014 barge-in is limited by echo protection. Use headphones or switch to manual barge-in",
2171
+ shortcutInvalid: "Invalid shortcut, disabled. Fix it in settings (e.g. Ctrl+Shift+V); leave empty to use the mic button only",
2024
2172
  elapsedHint: "Current voice session duration",
2025
2173
  botLevelsHint: "AI playback level (blue bar = TTS playback, green bar = microphone)",
2026
2174
  interruptConfirm: "interrupt confirm",
2027
2175
  sev0: "0 high",
2028
2176
  sev1: "1 medium",
2029
2177
  sev2: "2 low",
2178
+ // 数值单位(设置卡片「当前生效值」用:中文汉字单位、英文国际缩写,避免「1500 ms」直出)
2179
+ unitMs: "ms",
2180
+ unitMin: "min",
2181
+ unitDb: "dB",
2030
2182
  descSilence: "Silence pause before a sentence is committed (default 1500 ms; at least 250 ms of speech required, guards against noise triggers)",
2031
- descIdle: "Auto-exit voice mode after idle minutes (default 5; batch G added 30 s warning before exit)",
2183
+ descIdle: "Auto-exit voice mode after idle minutes (default 5; a 30-second countdown warning appears before exit)",
2032
2184
  descModelHost: "ASR model download source (official source / mirror, or any custom URL)",
2033
- descAutoSend: "Auto-send once quiet (consecutive segments join into one message; off = draft only; Ctrl / hold still sends)",
2185
+ descAutoSend: "Auto-send once quiet (consecutive segments join into one message; off = draft only; holding Ctrl while speaking sends immediately; in hold mode, releasing sends)",
2034
2186
  // 批 7N 重做 5/5:clarify that toggling takes effect on next session entry (not the current one).
2035
2187
  descAutoResume: "Auto-resume voice mode when switching back to the last voice session (default off; takes effect on next session entry \u2014 auto-enters voice mode and restores the last session; when disabled, you must press Ctrl+Shift+V to re-enter)",
2036
2188
  descSpokenFormat: "Inject spoken-format prompt into voice replies (colloquial, short sentences, no Markdown; default on, live)",
2037
- descSenseVoice: "Re-transcribe the finalized utterance with SenseVoice (punctuation + ITN, more accurate; default on \u2014 turn off to skip the 228 MB model and keep streaming only)",
2189
+ descSenseVoice: "Recognition mode: on = accurate mode (SenseVoice finalization with punctuation + ITN; long utterances may take seconds on CPU); off = fast mode (streaming result finalized directly, skips the 228 MB re-transcription model, slightly less accurate)",
2190
+ recognizingSec: "Recognizing\u2026 {sec}s",
2038
2191
  descToolBeep: "Tool-call beep (default off): beep when the agent is thinking/calling tools; keep off if it annoys you",
2039
- senseITN: "Inverse text normalization",
2040
2192
  descSenseITN: "SenseVoice number/date/format normalization (default on; turn off to keep raw spoken form)",
2041
2193
  descCaptionFontSize: "Caption font size (Small 12 / Standard 14 / Large 18 / X-Large 24 px; default Small matches current behavior)",
2042
2194
  descCaptionMaxWidth: "Caption width (50vw / 70vw / 90vw; default 70vw; capped at 30vh height so multi-line 24px never overlaps the input box)",
@@ -2047,19 +2199,25 @@ var en = {
2047
2199
  captionWidth50: "Narrow",
2048
2200
  captionWidth70: "Medium",
2049
2201
  captionWidth90: "Wide",
2050
- skipReading: "Skip current reading",
2051
- backchannelYield: "Short-reply yielding",
2052
- descBackchannelYield: 'When the user says a short answer like "mm-hmm/right" while the agent is reading aloud, yield automatically (skip the current TTS sentence + drop frames for 1.5s; if the user really wants to speak, the existing hardBreak takes over; off = no yielding, behavior matches pre-batch-5)',
2053
- // 批 G 任务 3:让位窗口时长(500-3000ms,默认 1500)。
2054
- yieldMs: "Yield window",
2055
- descYieldMs: "How long (ms) to drop frames after a yield trigger (500-3000, default 1500; within the window the existing hardBreak takes over if the user really wants to speak; auto-resume after the window expires)",
2202
+ skipReading: "Skip this sentence",
2203
+ descBackchannelYield: 'When the user says a short answer like "mm-hmm/right" while the agent is reading aloud, yield automatically (skip the current TTS sentence + drop frames for 1.5s; if the user really wants to speak, the existing hardBreak takes over; off = no yielding, behavior matches before this change). Only triggers in hold-to-talk mode: in continuous-listening mode speech is not recognized during playback (speaking is treated as an interrupt)',
2204
+ // Issue #15 batch 1 / ADR-0012: barge-in speech salvage.
2205
+ descBargeInSalvage: "When you speak to interrupt while the agent is reading aloud, keep what you said from speech onset to break confirmation and merge it into recognition (fixes swallowed break-in speech; off = discard pre-break audio; recommended off only on speakers without echo cancellation)",
2206
+ descLlmCorrect: "Before sending, run one LLM pass over the whole transcribed text (typos/homophones/punctuation only, meaning preserved; requires a default model configured in the host \u2014 otherwise the original text is sent as-is). On = one extra correction round trip per message: usually under 1 second, at most ~10 seconds; at most 10 times per minute \u2014 when voice mode is off or the limit is hit, the original text is sent. Failed or abnormal output also falls back to the original text",
2207
+ descYieldMs: "How long (ms) to drop frames after a yield trigger (500-3000, default 1500; within the window the existing hardBreak takes over if the user really wants to speak; auto-resume after the window expires). Hold-to-talk mode only, during playback",
2056
2208
  descMode: "Interaction mode (toggle: continuous listen + auto-send / hold: press to talk)",
2057
2209
  modeToggle: "Continuous listening",
2058
2210
  modeHold: "Hold to talk",
2059
- descWakeWord: 'Wake word (default off; e.g. "Hey D"): recognition starts only after you say it, to avoid accidental triggers. You may say it together with your command ("Hey D, check the weather" \u2014 the wake word is stripped and never sent); it must be repeated after each utterance split or barge-in; toggle mode only (inactive in hold / manual barge-in); saying it while the agent is reading does not trigger (barge-in stays VAD-based). Fault-tolerant matching (homophones / leading fillers); 3-4 characters recommended; not a dedicated KWS engine \u2014 noisy environments may delay or falsely trigger',
2211
+ descWakeWord: 'Wake word (default off; e.g. "Hey D"): recognition starts only after you say it, to avoid accidental triggers. You may say it together with your command ("Hey D, check the weather" \u2014 the wake word is stripped and never sent); it must be repeated after each utterance split or barge-in; toggle mode only (inactive in hold / manual barge-in \u2014 and equally inactive when the detect probe fails and falls back to manual, the default on machines without native echo cancellation such as Safari); saying it while the agent is reading does not trigger (barge-in stays VAD-based). Fault-tolerant matching (homophones / leading fillers); 3-4 characters recommended; not a dedicated KWS engine \u2014 noisy environments may delay or falsely trigger',
2060
2212
  wakePlaceholder: "e.g. Hey D",
2061
- settingsCardDesc: "Engine / voice / rate / interrupt / barge-in / echo gate / silence / idle / model host / auto-send / auto-resume / mode / wake word / tool beep / ITN / caption font / caption width / yielding / yield window",
2062
- settingsEffectiveNote: "Engine / voice / rate / model precision / spoken format / re-transcribe / caption font / caption width / yielding / yield window apply immediately; ITN applies immediately (next time you enter voice mode the streaming recognizer is rebuilt); the rest (interrupt / barge-in / echo gate / shortcut / silence / idle / mirror / auto-send / auto-resume / mode / wake word / tool beep) apply next time you enter voice mode.",
2213
+ settingsCardDesc: "Engine / voice / rate / interrupt / barge-in / echo gate / silence / idle / model host / auto-send / auto-resume / mode / wake word / tool beep / ITN / caption font / caption width / yielding / yield window / barge-in salvage / LLM correction",
2214
+ settingsEffectiveNote: "When settings apply, in four tiers: \u2460 immediately \u2014 engine / voice / rate / Kokoro model precision (immediate when cached, else next download) / spoken format (applies to later replies) / model mirror (next download attempt); \u2461 next recognition \u2014 finalization re-transcription (SenseVoice) / ITN; \u2462 next utterance \u2014 silence threshold (endpoint; the send wait stays a fixed 1.2s); \u2463 next time you enter voice mode \u2014 interrupt sensitivity / barge-in mode / echo gate / shortcut / auto-send / auto-resume / interaction mode / wake word / tool beep / caption font / caption width / backchannel yielding / yield window / barge-in salvage / LLM correction / idle timeout. Items that take effect next time you enter voice mode are listed at the top of this card with their current effective values.",
2215
+ effectivePending: "{count} change(s) will apply next time you enter voice mode: {items}",
2216
+ valueOn: "On",
2217
+ valueOff: "Off",
2218
+ valueQuoted: '"{value}"',
2219
+ effectiveItem: "{label} (currently effective: {value})",
2220
+ effectiveItemSep: ", ",
2063
2221
  configUnavailable: "Configuration unavailable",
2064
2222
  telUtteranceEnd: "end",
2065
2223
  telEndpoint: "endpoint",
@@ -2093,7 +2251,6 @@ var en = {
2093
2251
  ttsDownloadHint: "Download this engine's local model; becomes ready immediately after",
2094
2252
  dataFlowHint: "Data flow: ASR recognition (zipformer2+SenseVoice) is always local; TTS playback depends on engine (edge=Microsoft cloud, vits/kokoro=local)",
2095
2253
  ttsDeleteHint: "Delete local models (frees space; auto re-downloads on next use)",
2096
- kokoroModel: "Kokoro model precision",
2097
2254
  kokoroModelInt8: "int8 (default)",
2098
2255
  kokoroModelFp32: "fp32 (better quality)",
2099
2256
  descKokoroModel: "Kokoro model precision: int8 is smaller/faster (CPU server or low bandwidth; default); fp32 sounds better but ~311MB and slower (GPU or large memory). Both share the same 103 voices; switches live.",
@@ -2108,7 +2265,10 @@ var en = {
2108
2265
  captionFontSizeLabel: "Caption size",
2109
2266
  captionMaxWidthLabel: "Caption width",
2110
2267
  backchannelYieldLabel: "Short-reply yielding",
2111
- // 批 G 任务 3:让位窗口(FIELD_LABELS.yieldMs 镜像键,*Label 后缀)。
2268
+ // Issue #15 batch 1 / ADR-0012: barge-in speech salvage (row title key).
2269
+ bargeInSalvageLabel: "Barge-in speech salvage",
2270
+ llmCorrectLabel: "LLM correction",
2271
+ // Yield window (row title key).
2112
2272
  yieldMsLabel: "Yield window",
2113
2273
  // 批 G 任务 2:空闲预警 + 退出提示文案。
2114
2274
  idleWarn30s: "Auto-exit in 30 seconds (adjustable in settings)",
@@ -2176,6 +2336,41 @@ var en = {
2176
2336
  voiceHintEnglishVoice: "Note: this is an English voice and reads Chinese replies poorly. For Chinese conversations, pick a Chinese voice (zh-\u2026)."
2177
2337
  };
2178
2338
 
2339
+ // src/llm-correct.ts
2340
+ function correctionSystem(lang) {
2341
+ return lang === "en" ? "You are a speech-recognition corrector. The user text comes from ASR and may contain homophone errors, typos, or missing/wrong punctuation. Make only minimal fixes: correct typos/homophones and fix punctuation, preserving the original meaning and colloquial style. Do not rewrite sentences, do not add content, do not answer questions, and do not alter numbers or proper nouns. Output only the corrected text, with no explanation. If the input has no obvious errors, return it unchanged." : "\u4F60\u662F\u4E2D\u6587\u8BED\u97F3\u8BC6\u522B\u7EA0\u9519\u5668\u3002\u7528\u6237\u7684\u8BDD\u6765\u81EA\u8BED\u97F3\u8BC6\u522B\uFF08ASR\uFF09\uFF0C\u53EF\u80FD\u6709\u540C\u97F3\u5B57\u3001\u9519\u522B\u5B57\u3001\u6807\u70B9\u7F3A\u5931\u6216\u9519\u8BEF\u3002\u8BF7\u53EA\u505A\u6700\u5C0F\u4FEE\u6B63\uFF1A\u6539\u9519\u522B\u5B57/\u540C\u97F3\u5B57\u3001\u8865\u6807\u70B9\uFF0C\u4FDD\u6301\u539F\u610F\u4E0E\u53E3\u8BED\u98CE\u683C\uFF1B\u4E0D\u8981\u6539\u5199\u53E5\u5B50\u3001\u4E0D\u8981\u8865\u5145\u5185\u5BB9\u3001\u4E0D\u8981\u56DE\u7B54\u95EE\u9898\u3001\u4E0D\u8981\u6539\u53D8\u6570\u5B57\u548C\u4E13\u4E1A\u672F\u8BED\u3002\u53EA\u8F93\u51FA\u4FEE\u6B63\u540E\u7684\u6587\u672C\uFF0C\u4E0D\u8981\u4EFB\u4F55\u89E3\u91CA\u3002\u5982\u679C\u539F\u6587\u6CA1\u6709\u660E\u663E\u9519\u8BEF\uFF0C\u539F\u6837\u8FD4\u56DE\u3002";
2342
+ }
2343
+ var CORRECTION_PREAMBLE_RE = /^(?:以下是|这是)?(?:修正|纠正|更正|纠错)|^(?:here is (?:the )?)?(?:corrected|correction)\b/i;
2344
+ async function correctText(ctx, text, lang) {
2345
+ const trimmed = String(text ?? "").trim();
2346
+ if (!trimmed) return text;
2347
+ try {
2348
+ const llm = ctx?.get?.("llm");
2349
+ const sel = ctx?.get?.("agentDefaultModel")?.currentSelection?.();
2350
+ if (!llm || typeof llm.stream !== "function") return text;
2351
+ if (!sel?.provider || !sel?.model) return text;
2352
+ const stream = llm.stream({
2353
+ provider: sel.provider,
2354
+ model: sel.model,
2355
+ system: correctionSystem(lang),
2356
+ // host 侧自弃 10s(早于客户端 12s,审查 M3):超时后流抛错→catch→回退原文,
2357
+ // 客户端不必等自己的 AbortSignal.timeout 才拿到响应(省 token 与等待)。
2358
+ signal: AbortSignal.timeout(1e4),
2359
+ messages: [{ role: "user", content: [{ type: "text", text: trimmed }] }]
2360
+ });
2361
+ let out = "";
2362
+ for await (const chunk of stream) {
2363
+ if (chunk && chunk.type === "text-delta" && typeof chunk.text === "string") out += chunk.text;
2364
+ }
2365
+ const corrected = out.trim();
2366
+ if (corrected.length > Math.max(trimmed.length * 3, trimmed.length + 24)) return text;
2367
+ if (CORRECTION_PREAMBLE_RE.test(corrected)) return text;
2368
+ return corrected || text;
2369
+ } catch {
2370
+ return text;
2371
+ }
2372
+ }
2373
+
2179
2374
  // src/prompts.ts
2180
2375
  var ZH = "\u3010\u8BED\u97F3\u6A21\u5F0F\u3011\u5F53\u524D\u56DE\u590D\u4F1A\u88AB\u8BED\u97F3\u6717\u8BFB\uFF0C\u8BF7\u59CB\u7EC8\u7528\u7528\u6237\u6240\u7528\u8BED\u8A00\u3001\u4EE5\u53E3\u8BED\u5316\u7684\u77ED\u53E5\u76F4\u63A5\u56DE\u7B54\uFF0C\u50CF\u9762\u5BF9\u9762\u804A\u5929\u4E00\u6837\u81EA\u7136\uFF0C\u907F\u514D\u4E66\u9762\u8BED\u548C\u957F\u96BE\u53E5\u3002\u4E0D\u8981\u4F7F\u7528\u4EFB\u4F55 Markdown \u6216\u6392\u7248\u7B26\u53F7\uFF08\u661F\u53F7\u3001\u4E0B\u5212\u7EBF\u3001\u53CD\u5F15\u53F7\u3001\u4E95\u53F7\u3001\u5217\u8868\u4E0E\u8868\u683C\u6807\u8BB0\u3001\u4EE3\u7801\u5757\u7B49\uFF09\u3002\u9700\u8981\u5206\u70B9\u8BF4\u660E\u65F6\u7528\u300C\u7B2C\u4E00\u3001\u7B2C\u4E8C\u300D\u6216\u8FDE\u8D2F\u7684\u77ED\u53E5\u8868\u8FBE\uFF1B\u9664\u975E\u7528\u6237\u660E\u786E\u8981\u6C42\uFF0C\u4E0D\u8981\u8F93\u51FA\u4EE3\u7801\u7247\u6BB5\u3001\u5B8C\u6574 URL \u6216\u5197\u957F\u5B9A\u4E49\uFF0C\u7528\u4E00\u4E24\u53E5\u8BDD\u6982\u62EC\u542B\u4E49\u5373\u53EF\u3002\u56DE\u7B54\u7B80\u6D01\u76F4\u63A5\uFF0C\u4E0D\u8981\u91CD\u590D\u548C\u5BD2\u6684\u3002\u5982\u679C\u7528\u6237\u5728\u4F60\u6717\u8BFB\u65F6\u63D2\u8BDD\uFF08\u54EA\u6015\u53EA\u662F\u300C\u55EF/\u5BF9\u300D\u8FD9\u6837\u7684\u77ED\u5E94\u7B54\uFF09\uFF0C\u7ACB\u5373\u505C\u6B62\u5F53\u524D\u53E5\uFF0C\u628A\u8BDD\u8F6E\u8BA9\u7ED9\u7528\u6237\uFF1B\u56DE\u7B54\u540E\u7559\u51FA\u505C\u987F\uFF0C\u4E0D\u8981\u8FDE\u95EE\u4E24\u4E2A\u95EE\u9898\uFF1B\u7528\u6237\u6C89\u9ED8\u65F6\u4E0D\u8981\u4E3B\u52A8\u627E\u65B0\u8BDD\u9898\u3002";
2181
2376
  var EN = '[Voice mode] Your reply will be read aloud. Always answer in the language the user is using, in short conversational sentences, directly and naturally, as if talking face to face; avoid written-style phrasing and long, complex sentences. Do not use any Markdown or formatting symbols (asterisks, underscores, backticks, hash signs, list or table markup, code blocks, etc.). When you need to list points, say them as "first, second" or as connected short sentences; unless the user explicitly asks, do not output code snippets, full URLs or lengthy definitions \u2014 summarize the meaning in a sentence or two. Keep answers concise and direct; no repetition or pleasantries. If the user interrupts while you are being read aloud (even with a short acknowledgment like "uh-huh" or "yeah"), stop the current sentence immediately and yield the turn; leave a pause after answering and never ask two questions in a row; when the user is silent, do not bring up a new topic on your own.';
@@ -2354,6 +2549,10 @@ var VOICE_SETTINGS_DEFAULTS = {
2354
2549
  captionMaxWidth: 1,
2355
2550
  // 批 5:backchannel 默认 true(产品决策;关 = 不挂 onBackchannel 回调,行为等同改造前)。
2356
2551
  backchannelYield: true,
2552
+ // Issue #15 批 1 / ADR-0012:打断抢救默认开(I10 有意豁免:默认体验破损=本 issue 存在原因)。
2553
+ bargeInSalvage: true,
2554
+ // Issue #15 批 4:LLM 纠错默认关(默认开=未申报的 I10 豁免+每条多一次 RTT/token)。
2555
+ llmCorrect: false,
2357
2556
  // 批 G 任务 3:让位窗口默认 1500ms(与改造前批 5 行为字节等价;用户可调 500-3000ms)。
2358
2557
  yieldMs: 1500
2359
2558
  };
@@ -2380,6 +2579,8 @@ var DESC = {
2380
2579
  captionFontSize: en.descCaptionFontSize,
2381
2580
  captionMaxWidth: en.descCaptionMaxWidth,
2382
2581
  backchannelYield: en.descBackchannelYield,
2582
+ bargeInSalvage: en.descBargeInSalvage,
2583
+ llmCorrect: en.descLlmCorrect,
2383
2584
  yieldMs: en.descYieldMs
2384
2585
  };
2385
2586
  function createVoiceSettingsSchema(defs) {
@@ -2424,6 +2625,14 @@ function createVoiceSettingsSchema(defs) {
2424
2625
  backchannelYield: z.boolean().default(d.backchannelYield).description(
2425
2626
  DESC.backchannelYield
2426
2627
  ),
2628
+ // Issue #15 批 1 / ADR-0012:打断语音抢救(默认 true,I10 有意豁免)。
2629
+ bargeInSalvage: z.boolean().default(d.bargeInSalvage).description(
2630
+ DESC.bargeInSalvage
2631
+ ),
2632
+ // Issue #15 批 4:LLM 纠错(默认 false)。
2633
+ llmCorrect: z.boolean().default(d.llmCorrect).description(
2634
+ DESC.llmCorrect
2635
+ ),
2427
2636
  yieldMs: z.number().min(500).max(3e3).default(d.yieldMs).description(
2428
2637
  DESC.yieldMs
2429
2638
  )
@@ -2439,10 +2648,14 @@ var Config = z.object({
2439
2648
  allowLan: z.boolean().default(false),
2440
2649
  allowCustomModelHost: z.boolean().default(false),
2441
2650
  voice: z.string().default("zh-CN-XiaoxiaoNeural"),
2442
- rate: z.number().default(1.1),
2651
+ // I3(Issue #15 审查 Important):数值旋钮补 min/max,与 VoiceSettingsValue schema
2652
+ // (createVoiceSettingsSchema)逐字段一致。早年 Config 层是裸 z.number()——cordis.patch.yml
2653
+ // 手滑写 rate:5 会得到五倍速朗读、silenceMs:10 会把每句话按音节碎切,且没有任何一层会拦。
2654
+ // 两层同界:Config 是 baseline、settings schema 是覆盖层,任一层失守都让非法值直达运行时。
2655
+ rate: z.number().min(0.5).max(2).default(1.1),
2443
2656
  interruptLevel: z.union([z.const(0), z.const(1), z.const(2)]).default(0),
2444
- silenceMs: z.number().default(1500),
2445
- idleTimeoutMinutes: z.number().default(5),
2657
+ silenceMs: z.number().min(500).max(3e4).default(1500),
2658
+ idleTimeoutMinutes: z.number().min(1).max(120).default(5),
2446
2659
  // 设置面板字段(与 VoiceSettingsValue 一一对应;0.1.7+ 由插件自身 Config 派生读取)。
2447
2660
  // 注意:刻意不标 .volatile() —— schemastery 3.18.4 的 volatile 会破坏 schema 函数
2448
2661
  // 调用形态(sv({}) → {field:{}}),而 0.1.5-rc.3 起的设置分层会调用插件 Config 做
@@ -2453,7 +2666,10 @@ var Config = z.object({
2453
2666
  autoResume: z.boolean().default(false),
2454
2667
  mode: z.union([z.const("toggle"), z.const("hold")]).default("toggle"),
2455
2668
  bargeInMode: z.union([z.const("auto"), z.const("manual"), z.const("detect")]).default("detect"),
2456
- echoGateDb: z.number().default(6),
2669
+ // I3 + M7(zod 界):echoGateDb / yieldMs 与 settings schema 同界(3-12 dB / 500-3000ms)。
2670
+ // client 与 NumberField 虽会 clamp,但那只是 UI 兜底——Config 层无界时 YAML 手滑
2671
+ // 仍可把回声门阈设成 0(句句误打断)或让位窗口设成 60000(让位后一分钟不说话)。
2672
+ echoGateDb: z.number().min(3).max(12).default(6),
2457
2673
  shortcut: z.string().default("Ctrl+Shift+V"),
2458
2674
  spokenFormat: z.boolean().default(true),
2459
2675
  senseVoice: z.boolean().default(true),
@@ -2463,7 +2679,12 @@ var Config = z.object({
2463
2679
  captionFontSize: z.union([z.const(0), z.const(1), z.const(2), z.const(3)]).default(0),
2464
2680
  captionMaxWidth: z.union([z.const(0), z.const(1), z.const(2)]).default(1),
2465
2681
  backchannelYield: z.boolean().default(true),
2466
- yieldMs: z.number().default(1500)
2682
+ // Issue #15 批 4:LLM 纠错默认关。
2683
+ llmCorrect: z.boolean().default(false),
2684
+ // Issue #15 批 1 / ADR-0012:打断语音抢救(默认 true,I10 有意豁免)。
2685
+ bargeInSalvage: z.boolean().default(true),
2686
+ // I3 + M7(zod 界):500-3000ms,与 settings schema 一致。
2687
+ yieldMs: z.number().min(500).max(3e3).default(1500)
2467
2688
  });
2468
2689
  function voiceSettingsFromConfig(config) {
2469
2690
  const {
@@ -2489,7 +2710,9 @@ function voiceSettingsFromConfig(config) {
2489
2710
  captionFontSize,
2490
2711
  captionMaxWidth,
2491
2712
  backchannelYield,
2492
- yieldMs
2713
+ yieldMs,
2714
+ bargeInSalvage,
2715
+ llmCorrect
2493
2716
  } = config;
2494
2717
  return {
2495
2718
  ttsEngine,
@@ -2514,7 +2737,9 @@ function voiceSettingsFromConfig(config) {
2514
2737
  captionFontSize,
2515
2738
  captionMaxWidth,
2516
2739
  backchannelYield,
2517
- yieldMs
2740
+ yieldMs,
2741
+ bargeInSalvage,
2742
+ llmCorrect
2518
2743
  };
2519
2744
  }
2520
2745
  function apply(ctx, config) {
@@ -2529,6 +2754,11 @@ function apply(ctx, config) {
2529
2754
  broadcast("turn", { sessionId, state });
2530
2755
  };
2531
2756
  const turnGen = /* @__PURE__ */ new Map();
2757
+ const clearTurnState = (sessionId) => {
2758
+ setTurn(sessionId, "idle");
2759
+ turnStates.delete(sessionId);
2760
+ turnGen.delete(sessionId);
2761
+ };
2532
2762
  const sessions = ctx.get("sessions");
2533
2763
  const limiter = new RateLimiter();
2534
2764
  const limiterPrune = setInterval(() => limiter.prune(Date.now(), 6e4), 6e4);
@@ -2536,22 +2766,26 @@ function apply(ctx, config) {
2536
2766
  const normalizedModelHost = () => validateModelHost(vset.modelHost, config.allowCustomModelHost) ?? HOST_PRIMARY;
2537
2767
  const denyNonLoopback = (req, res) => {
2538
2768
  if (!config.allowLan && !isLoopbackRequest(req)) {
2539
- res.statusCode = 403;
2540
- res.setHeader("content-type", "application/json");
2541
- res.end(JSON.stringify({ code: "forbidden", error: "loopback only (allowLan=false)" }));
2769
+ respondJson2(res, 403, { code: "forbidden", error: "loopback only (allowLan=false)" });
2542
2770
  return true;
2543
2771
  }
2544
2772
  return false;
2545
2773
  };
2546
2774
  const denyCrossOrigin = (req, res) => {
2547
2775
  if (!sameOriginRequest(req)) {
2548
- res.statusCode = 403;
2549
- res.setHeader("content-type", "application/json");
2550
- res.end(JSON.stringify({ code: "forbidden", error: "cross-origin request denied" }));
2776
+ respondJson2(res, 403, { code: "forbidden", error: "cross-origin request denied" });
2551
2777
  return true;
2552
2778
  }
2553
2779
  return false;
2554
2780
  };
2781
+ const clientKey = (req) => {
2782
+ if (isLoopbackRequest(req)) {
2783
+ const xff = req.headers["x-forwarded-for"];
2784
+ const first = (typeof xff === "string" ? xff : Array.isArray(xff) ? xff[0] : "").split(",")[0].trim();
2785
+ if (first) return first;
2786
+ }
2787
+ return req.socket.remoteAddress ?? "unknown";
2788
+ };
2555
2789
  const sseClients = /* @__PURE__ */ new Set();
2556
2790
  const latestConnByTab = /* @__PURE__ */ new Map();
2557
2791
  const broadcast = (event, payload) => {
@@ -2644,10 +2878,27 @@ function apply(ctx, config) {
2644
2878
  allowCustomHost: config.allowCustomModelHost,
2645
2879
  broadcast,
2646
2880
  // 批 7N(ADR-0006):打断方式 getter(实时读设置);manual 模式下 feed 需 manualPressed=true。
2881
+ //
2882
+ // I5(Issue #15 审查 Important)——toggle + manual 的已知缺口,注释如实登记:
2883
+ // manual 下 host 与客户端双重丢帧(asr-host.ts feed 入口 manualPressed=false 直接
2884
+ // 返回、asr.ts handleAudio 非 holdActive 丢弃),而客户端的 hold 入口(mic 长按 /
2885
+ // Ctrl)**仅在 bus.ui.playing 为真时开放**(client.tsx 的 toggle 分支与 Ctrl 分支均以
2886
+ // playing 为条件)。于是 toggle + manual 组合下:AI 朗读中可以长按打断并说话,
2887
+ // 待机态(不播放)则完全无法输入——用户看到的是「麦克风亮着但说话没反应」的静默致聋,
2888
+ // 而 bargeInMode=detect 在原生 AEC 未生效的机器上会自动落到 manual,即默认路径就可能命中。
2889
+ // 待机态 push-to-talk 属产品决策(要改的是客户端手势开放条件),PM 已登记待用户拍板,
2890
+ // 此处不加功能;host 侧只保证「manual 时非按压帧不入流」这一既有语义不被悄悄扩大。
2647
2891
  bargeInMode: () => vset.bargeInMode
2648
2892
  });
2649
2893
  ctx.effect(() => () => asr.dispose());
2650
- void asr.warmup();
2894
+ const warmupAsrIfCached = () => {
2895
+ if (!config.enabled) return;
2896
+ const st = asr.modelStatus();
2897
+ if (!st.asr.ready || !st.vad.ready) return;
2898
+ if (st.sense.enabled && !st.sense.ready) return;
2899
+ void asr.warmup();
2900
+ };
2901
+ warmupAsrIfCached();
2651
2902
  const makeEngine = (kind) => {
2652
2903
  if (kind === "edge") return new EdgeTtsEngine(config.voice, config.rate);
2653
2904
  if (kind === "kokoro") {
@@ -2725,8 +2976,7 @@ function apply(ctx, config) {
2725
2976
  activeTabId = null;
2726
2977
  queue.cancel(sid);
2727
2978
  asr.reset(sid);
2728
- setTurn(sid, "idle");
2729
- turnStates.delete(sid);
2979
+ clearTurnState(sid);
2730
2980
  broadcast("mode", { active: null, ownerTabId: activeTabId });
2731
2981
  };
2732
2982
  ctx.on("system-prompt/assemble", (assembly, context, next) => {
@@ -2796,6 +3046,8 @@ function apply(ctx, config) {
2796
3046
  captionFontSize: vset.captionFontSize,
2797
3047
  captionMaxWidth: vset.captionMaxWidth,
2798
3048
  backchannelYield: vset.backchannelYield,
3049
+ bargeInSalvage: vset.bargeInSalvage,
3050
+ llmCorrect: vset.llmCorrect,
2799
3051
  yieldMs: vset.yieldMs,
2800
3052
  senseITN: vset.senseITN,
2801
3053
  cacheDir: config.cacheDir,
@@ -2813,10 +3065,8 @@ function apply(ctx, config) {
2813
3065
  handler: (req, res) => {
2814
3066
  if (denyNonLoopback(req, res)) return;
2815
3067
  if (denyCrossOrigin(req, res)) return;
2816
- if (!limiter.hit(`preview:${req.socket.remoteAddress ?? "unknown"}`, 20, 6e4)) {
2817
- res.statusCode = 429;
2818
- res.setHeader("content-type", "application/json");
2819
- res.end(JSON.stringify({ code: "rate_limited", error: "rate limited" }));
3068
+ if (!limiter.hit(`preview:${clientKey(req)}`, 20, 6e4)) {
3069
+ respondJson2(res, 429, { code: "rate_limited", error: "rate limited" });
2820
3070
  return;
2821
3071
  }
2822
3072
  if (!config.enabled) {
@@ -2864,6 +3114,42 @@ function apply(ctx, config) {
2864
3114
  }
2865
3115
  })
2866
3116
  );
3117
+ ctx.effect(
3118
+ () => ctx.webServer.register({
3119
+ kind: "exact",
3120
+ path: `${base}/correct`,
3121
+ handler: (req, res) => {
3122
+ if (denyNonLoopback(req, res)) return;
3123
+ if (denyCrossOrigin(req, res)) return;
3124
+ collectBody(req, res, MAX_JSON_BODY, (body) => {
3125
+ let text = "";
3126
+ let lang = "zh";
3127
+ try {
3128
+ const parsed = JSON.parse(body || "{}");
3129
+ text = typeof parsed.text === "string" ? parsed.text : "";
3130
+ lang = normalizePromptLang(parsed.lang);
3131
+ } catch {
3132
+ }
3133
+ const trimmed = text.trim();
3134
+ if (!trimmed) {
3135
+ respondJson2(res, 200, { text });
3136
+ return;
3137
+ }
3138
+ if (!config.enabled) {
3139
+ respondJson2(res, 403, { code: "voice_disabled", error: "voice mode disabled", text: trimmed });
3140
+ return;
3141
+ }
3142
+ if (!limiter.hit(`correct:${clientKey(req)}`, 10, 6e4)) {
3143
+ respondJson2(res, 429, { code: "rate_limited", error: "rate limited", text: trimmed });
3144
+ return;
3145
+ }
3146
+ void correctText(ctx, trimmed, lang).then((corrected) => {
3147
+ respondJson2(res, 200, { text: corrected });
3148
+ }).catch(() => respondJson2(res, 200, { text: trimmed }));
3149
+ });
3150
+ }
3151
+ })
3152
+ );
2867
3153
  ctx.effect(
2868
3154
  () => ctx.webServer.register({
2869
3155
  kind: "exact",
@@ -2888,14 +3174,16 @@ function apply(ctx, config) {
2888
3174
  respondJson2(res, 400, { code: "bad_request", error: "sessionId required" });
2889
3175
  return;
2890
3176
  }
2891
- if (on !== void 0 && typeof on !== "boolean") {
3177
+ if (on === void 0) {
3178
+ respondJson2(res, 400, { code: "bad_request", error: "on required" });
3179
+ return;
3180
+ }
3181
+ if (typeof on !== "boolean") {
2892
3182
  respondJson2(res, 400, { code: "bad_request", error: "invalid on" });
2893
3183
  return;
2894
3184
  }
2895
3185
  if (!limiter.hit(`toggle:${sessionId}`, 2, 2e3)) {
2896
- res.statusCode = 429;
2897
- res.setHeader("content-type", "application/json");
2898
- res.end(JSON.stringify({ code: "rate_limited", error: "rate limited" }));
3186
+ respondJson2(res, 429, { code: "rate_limited", error: "rate limited" });
2899
3187
  return;
2900
3188
  }
2901
3189
  if (on === true) {
@@ -2921,8 +3209,7 @@ function apply(ctx, config) {
2921
3209
  if (previous && previous !== sessionId) {
2922
3210
  queue.cancel(previous);
2923
3211
  asr.reset(previous);
2924
- setTurn(previous, "idle");
2925
- turnStates.delete(previous);
3212
+ clearTurnState(previous);
2926
3213
  }
2927
3214
  broadcast("mode", { active: activeVoiceSession, ownerTabId: activeTabId });
2928
3215
  } else {
@@ -2935,8 +3222,7 @@ function apply(ctx, config) {
2935
3222
  }
2936
3223
  queue.cancel(sessionId);
2937
3224
  asr.reset(sessionId);
2938
- setTurn(sessionId, "idle");
2939
- turnStates.delete(sessionId);
3225
+ clearTurnState(sessionId);
2940
3226
  broadcast("mode", { active: null, ownerTabId: null });
2941
3227
  }
2942
3228
  }
@@ -2989,6 +3275,9 @@ function apply(ctx, config) {
2989
3275
  }
2990
3276
  void asr.retryModel(kind).then((done) => {
2991
3277
  respondJson2(res, 200, { ok: done, kind });
3278
+ }).catch((e) => {
3279
+ console.warn(`[dsh-voice-mode] model retry failed: ${String(e)}`);
3280
+ respondJson2(res, 500, { code: "internal", error: "model retry failed" });
2992
3281
  });
2993
3282
  });
2994
3283
  }
@@ -3018,8 +3307,8 @@ function apply(ctx, config) {
3018
3307
  respondJson2(res, 400, { code: "bad_request", error: "invalid json" });
3019
3308
  return;
3020
3309
  }
3021
- const dir = join5(config.cacheDir, engine === "kokoro" ? kokoroModelDir(vset.kokoroModel) : TTS_MODEL_REPO);
3022
- void rm(dir, { recursive: true, force: true }).then(() => {
3310
+ const dirs = engine === "kokoro" ? [kokoroModelDir("int8"), kokoroModelDir("fp32")].map((d) => join5(config.cacheDir, d)) : [join5(config.cacheDir, TTS_MODEL_REPO)];
3311
+ void Promise.all(dirs.map((dir) => rm(dir, { recursive: true, force: true }))).then(() => {
3023
3312
  if (engineKind === engine) {
3024
3313
  queue.setEngine(makeEngine(engine));
3025
3314
  queue.updateVoice(vset.voice, vset.rate);
@@ -3092,6 +3381,7 @@ function apply(ctx, config) {
3092
3381
  path: `${base}/asr`,
3093
3382
  handler: (req, res) => {
3094
3383
  if (denyNonLoopback(req, res)) return;
3384
+ if (denyCrossOrigin(req, res)) return;
3095
3385
  let sid = "";
3096
3386
  try {
3097
3387
  const url = new URL(req.url ?? "/", "http://localhost");
@@ -3210,21 +3500,15 @@ function apply(ctx, config) {
3210
3500
  } catch {
3211
3501
  }
3212
3502
  if (!mode) {
3213
- res.statusCode = 400;
3214
- res.setHeader("content-type", "application/json");
3215
- res.end(JSON.stringify({ code: "bad_request", error: "mode must be toggle or hold" }));
3503
+ respondJson2(res, 400, { code: "bad_request", error: "mode must be toggle or hold" });
3216
3504
  return;
3217
3505
  }
3218
3506
  const persistMode = settingsScopeRef ? settingsScopeRef.update({ mode }) : persistSettings({ mode });
3219
3507
  void persistMode.then(() => {
3220
- res.statusCode = 200;
3221
- res.setHeader("content-type", "application/json");
3222
- res.end(JSON.stringify({ ok: true, mode }));
3508
+ respondJson2(res, 200, { ok: true, mode });
3223
3509
  }).catch((e) => {
3224
3510
  console.warn(`[dsh-voice-mode] mode update failed: ${String(e)}`);
3225
- res.statusCode = 500;
3226
- res.setHeader("content-type", "application/json");
3227
- res.end(JSON.stringify({ code: "internal", error: "mode update failed" }));
3511
+ respondJson2(res, 500, { code: "internal", error: "mode update failed" });
3228
3512
  });
3229
3513
  });
3230
3514
  }
@@ -3236,6 +3520,7 @@ function apply(ctx, config) {
3236
3520
  path: `${base}/stream`,
3237
3521
  handler: (req, res) => {
3238
3522
  if (denyNonLoopback(req, res)) return;
3523
+ if (denyCrossOrigin(req, res)) return;
3239
3524
  if (sseClients.size >= 4) {
3240
3525
  respondJson2(res, 429, { code: "too_many_streams", error: "too many streams" });
3241
3526
  return;
@@ -3304,6 +3589,8 @@ function collectBody(req, res, maxBytes, onBody) {
3304
3589
  if (received > maxBytes) {
3305
3590
  tooLarge = true;
3306
3591
  respondJson2(res, 413, { code: "payload_too_large", error: "request body too large" });
3592
+ req.pause();
3593
+ res.once("finish", () => req.destroy());
3307
3594
  return;
3308
3595
  }
3309
3596
  chunks.push(c);