dsh-voice-mode 0.7.26 → 0.7.28

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
@@ -294,6 +294,7 @@ async function ensureModelTree(opts) {
294
294
  const res = await fetchWithHeadersTimeout(host + "/api/models/" + repo + "?blobs=true", {
295
295
  headers: { "user-agent": "dsh-voice-mode" }
296
296
  });
297
+ if (!redirectHostAllowed(res.url, allowCustomHost)) continue;
297
298
  if (res.ok) {
298
299
  const j = await res.json();
299
300
  tree = (j.siblings ?? []).map((s) => s.rfilename ?? "").filter((f) => isSafeModelRel(f, subdir));
@@ -321,12 +322,12 @@ async function ensureModelTree(opts) {
321
322
  for (const host of hosts) {
322
323
  try {
323
324
  const url = host + "/" + repo + "/resolve/main/" + encodeURIComponent(rel);
324
- const res = await fetch(url, { headers: { "user-agent": "dsh-voice-mode" }, redirect: "follow" });
325
+ const res = await fetchWithHeadersTimeout(url, { headers: { "user-agent": "dsh-voice-mode" }, redirect: "follow" });
325
326
  if (!redirectHostAllowed(res.url, allowCustomHost)) continue;
326
327
  if (res.status !== 200) continue;
327
- const sink = createWriteStream(partPath);
328
328
  const reader = res.body?.getReader();
329
329
  if (!reader) continue;
330
+ const sink = createWriteStream(partPath);
330
331
  let size = 0;
331
332
  await new Promise((resolve, reject) => {
332
333
  sink.on("error", reject);
@@ -424,6 +425,7 @@ function createAsrRuntime(options) {
424
425
  const finalizing = /* @__PURE__ */ new Map();
425
426
  const resetGen = /* @__PURE__ */ new Map();
426
427
  let recognizer = null;
428
+ let recognizerDisposed = false;
427
429
  let modelsReady = false;
428
430
  let modelsLoading = null;
429
431
  let asrFailAt = 0;
@@ -449,7 +451,9 @@ function createAsrRuntime(options) {
449
451
  return modelsLoading;
450
452
  };
451
453
  const getRecognizer = async () => {
454
+ if (recognizerDisposed) return null;
452
455
  if (!await ensureModels()) return null;
456
+ if (recognizerDisposed) return null;
453
457
  if (recognizer) return recognizer;
454
458
  const t = (f) => join2(repoDir, f);
455
459
  recognizer = createOnlineRecognizer({
@@ -830,6 +834,7 @@ function createAsrRuntime(options) {
830
834
  dispose: () => {
831
835
  clearInterval(sweepTimer);
832
836
  senseDisposed = true;
837
+ recognizerDisposed = true;
833
838
  let w = senseWorker;
834
839
  senseWorker = null;
835
840
  senseWorkerSyncing = null;
@@ -1063,39 +1068,115 @@ function splitSentences(chunk) {
1063
1068
  }
1064
1069
  return { sentences, tail: chunk.slice(lastEnd) };
1065
1070
  }
1071
+ function cutHead(text, max) {
1072
+ let idx = -1;
1073
+ for (let i = Math.min(max, text.length) - 1; i > 0; i--) {
1074
+ if (/[,,、\s]/.test(text[i])) {
1075
+ idx = i + 1;
1076
+ break;
1077
+ }
1078
+ }
1079
+ if (idx <= 0) idx = Math.max(1, Math.floor(max / 2));
1080
+ return [text.slice(0, idx), text.slice(idx)];
1081
+ }
1066
1082
  var SentenceSegmenter = class {
1067
1083
  buffer = "";
1068
1084
  maxChars;
1085
+ /** 是否处在 ``` 代码块内(跨 delta 有效:流式 delta 只有几个 token,代码块总是被切碎送达,
1086
+ * plainText 的整块正则匹配不到,代码会被逐句念出——「总是朗读」覆盖打字会话后尤其明显)。 */
1087
+ inFence = false;
1088
+ /** delta 末尾悬挂的 1-2 个反引号(被切开的 ``` 前半;连续 3 个及以上是完整围栏,不悬挂)。 */
1089
+ ticks = "";
1090
+ /** 围栏内被抑制的内容暂存:流结束时若仍未闭合则回退输出(宁可念代码,也不吞掉整回合正文)。 */
1091
+ fenced = "";
1069
1092
  constructor(options = {}) {
1070
1093
  this.maxChars = options.maxSentenceChars ?? 200;
1071
1094
  }
1095
+ /** 去掉 ``` 代码块内容(状态跨 delta 保持);进入代码块处补一个换行,让前面的文字先成句。 */
1096
+ dropFences(chunk) {
1097
+ let s = this.ticks + chunk;
1098
+ this.ticks = "";
1099
+ const trail = /`+$/.exec(s);
1100
+ const hang = trail ? trail[0].length : 0;
1101
+ if (hang > 0 && hang <= 2) {
1102
+ this.ticks = s.slice(-hang);
1103
+ s = s.slice(0, -hang);
1104
+ }
1105
+ let out = "";
1106
+ for (; ; ) {
1107
+ const m = /`{3,}/.exec(s);
1108
+ if (!m) {
1109
+ if (this.inFence) this.fenced += s;
1110
+ else out += s;
1111
+ return out;
1112
+ }
1113
+ if (this.inFence) this.fenced += s.slice(0, m.index);
1114
+ else out += s.slice(0, m.index) + "\n";
1115
+ this.inFence = !this.inFence;
1116
+ if (!this.inFence) this.fenced = "";
1117
+ s = s.slice(m.index + m[0].length);
1118
+ }
1119
+ }
1120
+ /**
1121
+ * 安全阀:把超过 maxChars 的文字墙切下一段(feed 与 flush 共用同一口径)。
1122
+ * 切点取 ≤ maxChars 内**最后一个**「,,、\s」——取第一个会把无标点的英文/代码逐词切成
1123
+ * 几十个小段;超长段必须 ≤ maxChars,否则阀形同虚设。没有可用分隔符时取一半。
1124
+ */
1125
+ cutWall() {
1126
+ const [head, rest] = cutHead(this.buffer, this.maxChars);
1127
+ this.buffer = rest;
1128
+ return sanitizeForTts(head).trim();
1129
+ }
1130
+ /** 成句本身超过 maxChars(长逗号句)同样过安全阀,逐段输出。 */
1131
+ capSentence(s, out) {
1132
+ let rest = s;
1133
+ while (rest.length > this.maxChars) {
1134
+ const [head, tail] = cutHead(rest, this.maxChars);
1135
+ rest = tail;
1136
+ const t2 = sanitizeForTts(head).trim();
1137
+ if (t2 && !SKIP_PREFIX.test(t2)) out.push(t2);
1138
+ }
1139
+ const t = sanitizeForTts(rest).trim();
1140
+ if (t && !SKIP_PREFIX.test(t)) out.push(t);
1141
+ }
1072
1142
  /** 喂入一段 raw delta,返回它补全的完整句子。 */
1073
1143
  feed(chunk) {
1074
- const cleaned = plainText(chunk);
1144
+ const cleaned = plainText(this.dropFences(chunk));
1075
1145
  if (!cleaned) return [];
1076
1146
  this.buffer += cleaned;
1077
1147
  const { sentences, tail } = splitSentences(this.buffer);
1078
1148
  this.buffer = tail;
1079
1149
  const out = [];
1080
- for (const s of sentences) {
1081
- const t = sanitizeForTts(s).trim();
1082
- if (t && !SKIP_PREFIX.test(t)) out.push(t);
1083
- }
1084
- if (this.buffer.length > this.maxChars) {
1085
- const cut = this.buffer.search(/[,,、\s]/);
1086
- const idx = cut > 0 ? cut : Math.floor(this.maxChars / 2);
1087
- const head = sanitizeForTts(this.buffer.slice(0, idx)).trim();
1088
- this.buffer = this.buffer.slice(idx);
1089
- if (head) out.push(head);
1150
+ for (const s of sentences) this.capSentence(s, out);
1151
+ while (this.buffer.length > this.maxChars) {
1152
+ const head = this.cutWall();
1153
+ if (head && !SKIP_PREFIX.test(head)) out.push(head);
1090
1154
  }
1091
1155
  return out;
1092
1156
  }
1093
- /** 收尾:flush 剩余缓冲(流结束)。 */
1157
+ /**
1158
+ * 收尾:flush 剩余缓冲(流结束)。
1159
+ * 整回合未见闭合围栏 → 把围栏内被抑制的内容回退输出(v0.7.27 之前未配对围栏零损失,
1160
+ * 全靠这一条守住;否则一个孤立的 ``` 会静默吞掉本回合剩余正文)。
1161
+ *
1162
+ * 过安全阀后的多段仍按「代码内容」朗读:既有取舍是「宁念代码不吞正文」,切分只改朗读粒度
1163
+ * (每段一次合成请求)、不改取舍;段序 = 原文字序,段内容 = 原文字符的连续切片(切点沿用
1164
+ * feed() 同一口径)。不回退成「整体不念」——那等于回到吞正文的老问题。
1165
+ */
1094
1166
  flush() {
1167
+ if (this.inFence) this.buffer = plainText(this.buffer + this.fenced);
1168
+ const out = [];
1169
+ while (this.buffer.length > this.maxChars) {
1170
+ const head = this.cutWall();
1171
+ if (head && !SKIP_PREFIX.test(head)) out.push(head);
1172
+ }
1095
1173
  const t = sanitizeForTts(this.buffer).trim();
1096
1174
  this.buffer = "";
1097
- if (t && !SKIP_PREFIX.test(t)) return [t];
1098
- return [];
1175
+ this.inFence = false;
1176
+ this.ticks = "";
1177
+ this.fenced = "";
1178
+ if (t && !SKIP_PREFIX.test(t)) out.push(t);
1179
+ return out;
1099
1180
  }
1100
1181
  };
1101
1182
 
@@ -1176,13 +1257,73 @@ async function listEdgeVoices(force = false) {
1176
1257
  }
1177
1258
  }
1178
1259
  var TtsQueue = class {
1260
+ /**
1261
+ * 各会话队列:只在**有活**时存在(见 pump finally 的退休处置),不再随历史会话数增长。
1262
+ *
1263
+ * R15(Issue #15 T-3):本表原先每会话留一个空 SessionQueue 且永不回收,而所有对外
1264
+ * 清理入口都是 cancel()(index.ts:1007/1376/1390/1409/1665)——cancel 按设计必须保留
1265
+ * 队列对象,故 turn 退出路径下这张表只增不减(量级 = 历史会话数,非本次回归)。
1266
+ * 真正的回收点只能是「队列已排空、泵已收工」的那一刻。
1267
+ *
1268
+ * 【不变式:seq 单调】回收绝不能让某会话的 sentenceId 归零或回退——client 的
1269
+ * rejectSeqUpTo(client.tsx:1359/1385,`frame.sentenceId <= rejectLine` 即丢弃)记的是
1270
+ * 「本会话已见过的最大句号」,新句必须**大于**它,否则新回复前 N 句被静默丢弃(静音)。
1271
+ * 这正是 index.ts:1376/1409 与 setEngine B1 都写明「用 cancel 而非 prune 保 seq 连续」
1272
+ * 的同一条理由,也是不用 prune() 回收的直接原因。
1273
+ * 故 seq 已上移为本类的全局计数器(见下方 seq),会话维度不再持有任何 seq 状态——
1274
+ * 这样「回收」与「seq 不归零」不再互相排斥:会话回来时拿到的必然是一个比它历史上
1275
+ * 任何一句都大的句号(全局单调在会话上的投影必然严格递增)。
1276
+ */
1179
1277
  queues = /* @__PURE__ */ new Map();
1278
+ /**
1279
+ * 句序号发号器(**全局**,非每会话)。
1280
+ *
1281
+ * 为什么不是每会话:每会话 seq 必须活到会话彻底消失,可任何「活到会话消失」的形态
1282
+ * (墓碑表、有界 LRU 淘汰)都只是把同一张永不回收的表换个名字——LRU 淘汰后该会话再回来
1283
+ * 仍会 seq 归零,仍撞 rejectSeqUpTo。全局计数器则让「会话维度 seq 状态」根本不存在,
1284
+ * 回收得以无条件成立。
1285
+ *
1286
+ * 只在成功广播时自增(pump 的 `const sentenceId = this.seq++` 位于成功分支内),
1287
+ * 与改动前逐字等价。client 只把 sentenceId 用于**比较**(`> rejectLine` 放行、
1288
+ * `!== curSentenceId` 重建拼帧缓冲),从不假设连续或小值——见 client.tsx:1354
1289
+ * 「host 的 sentenceId 跨回合单调递增,新回合必然 > 线」。
1290
+ */
1291
+ seq = 0;
1180
1292
  listeners = /* @__PURE__ */ new Set();
1181
1293
  engine;
1182
1294
  /** TTS 全体不可达通知(每会话去重,成功后复位)。 */
1183
1295
  onError;
1184
1296
  /** 单句合成重试耗尽被跳过通知(每句一次;此前是静默丢句——真机「回复偶尔不朗读」根因之一)。 */
1185
1297
  onSkip;
1298
+ /** 某会话队列跑空(无在途、无积压):「说完就关」据此判定朗读真正结束——客户端只能看到
1299
+ * 句间的播放空档,分不清「后面还有句子在合成」与「已全部读完」。
1300
+ *
1301
+ * R15(Issue #15 Important-2):本回调的口径取决于 awaitTurnEnd,见下方 openTurns。 */
1302
+ onIdle;
1303
+ /**
1304
+ * R15(Issue #15 Important-2):回合闸门——「队列排空」≠「回合结束」。
1305
+ *
1306
+ * 缺陷(逐行核对 8c0368a):onIdle 原义「排空一次即发」,无「回合是否真正结束」约束。
1307
+ * 而 host 在**每一条** llm/stream 的 finally 都把 turn 打回 listening(index.ts:1875,
1308
+ * 于是一条流结束 = 回合结束)。带工具调用的 agent 在第一轮流结束与第二轮开始之间存在
1309
+ * 秒级到分钟级的空档:第一段文本排空 → tts-idle → 客户端 ttsDrained=true;播完、playing
1310
+ * =false → mic-gesture.onceFinished(sawRun && !running && ttsDrained && !playing)成立
1311
+ * → 维持 ONCE_SETTLE_MS=1.2s 后 exitMode('manual') → /toggle off → queue.cancel;第二轮
1312
+ * llm/stream 因 activeVoiceSession 已空不再被 tap(index.ts:957)→ **后半段回复永不朗读**,
1313
+ * 麦克风在 AI 还在干活时熄灭。非工具场景的等价触发是句间停顿 >1.2s。
1314
+ *
1315
+ * 修法:onIdle 降级为「候选空闲」,真正的结束信号由 host 在**回合真正结束**时确认——
1316
+ * 即宿主 dsh 的 `agent/turn-stopping`(契约原文「the model owes no response: no live
1317
+ * tool calls, no fresh steering」,正是工具空档与真回合结束的判别式),在那儿调
1318
+ * noteTurnEnd(sessionId)。队列侧:enqueue 视为「新回合在途」标记,pump finally 的排空
1319
+ * 回调在该标记存在时**不发**(那只是句间空档);回合结束标记被清且队列已排空时补发。
1320
+ *
1321
+ * awaitTurnEnd 缺省 false = 闸门关闭,保持原语义(排空即发),供尚未接回合结束钩子的
1322
+ * 宿主零行为变化地兼容;置 true 后本集合才被 enqueue 填充。
1323
+ */
1324
+ awaitTurnEnd;
1325
+ /** awaitTurnEnd 开启时:某会话当前有一轮可能仍在进行(已入队过文本、回合尚未确认结束)。 */
1326
+ openTurns = /* @__PURE__ */ new Set();
1186
1327
  /**
1187
1328
  * M7②(Issue #15 R11):退避重启计时器句柄集。
1188
1329
  *
@@ -1219,6 +1360,59 @@ var TtsQueue = class {
1219
1360
  this.engine = options.engine;
1220
1361
  this.onError = options.onError;
1221
1362
  this.onSkip = options.onSkip;
1363
+ this.onIdle = options.onIdle;
1364
+ this.awaitTurnEnd = options.awaitTurnEnd === true;
1365
+ }
1366
+ /**
1367
+ * R15(Issue #15 Important-2):host 确认该会话的一轮作答**真正结束**(不会再有新的
1368
+ * llm/stream)时调用,接线点为宿主 dsh 的 `agent/turn-stopping`。
1369
+ *
1370
+ * 置 awaitTurnEnd 后:关闭该会话的在途标记;若队列此刻已排空则立即补发一次 onIdle
1371
+ * ——回合结束时 pump 的 finally 可能早已过去(最后一句播完时就发过「候选空闲」被
1372
+ * 闸门拦下),此时没有后续回调可等,必须在此补发。
1373
+ * 幂等/重复调用无害:重复触发时消费侧有 `!ttsDrained` 去重护栏(client.tsx:1189)。
1374
+ */
1375
+ noteTurnEnd(sessionId) {
1376
+ if (this.closed) return;
1377
+ this.openTurns.delete(sessionId);
1378
+ if (!this.awaitTurnEnd) return;
1379
+ if (!this.isIdle(sessionId)) return;
1380
+ try {
1381
+ this.onIdle?.(sessionId);
1382
+ } catch {
1383
+ }
1384
+ }
1385
+ /** 该会话当前无在途合成、无积压(未建队列也算空闲)。 */
1386
+ isIdle(sessionId) {
1387
+ const q = this.queues.get(sessionId);
1388
+ return !q || !q.busy && q.pending.length === 0;
1389
+ }
1390
+ /**
1391
+ * R15(Issue #15 T-4):回合作废——本轮**不会再有任何后续文本**,但与「回合正常结束」
1392
+ * (noteTurnEnd)不同的一点是:**不补发 onIdle**。
1393
+ *
1394
+ * 为何队列侧无法自行判断 abort(宿主侧实测 + 本文件调用点实测):
1395
+ * · 回合 abort 时宿主是 `catch → 直接重抛`:不派发 `agent/turn-stopping`、不派发
1396
+ * `agent/error`、不经本插件的任何入口——队列侧**收不到任何信号**,无法自愈;
1397
+ * · 唯一在队列侧与 abort「沾边」的入口是 cancel(),但它是五处语义完全不同的出口的
1398
+ * 共同出口,对队列可见的输入**只有 sessionId 一个**:/cancel「停止朗读」与用户打断
1399
+ * (index.ts:1665)、进模式 (:1376)、退模式 (:1409)、会话让出 (:1007/:1390)。
1400
+ * 在 cancel() 里清 openTurns,「停止朗读」后队列排空就会补发一条 tts-idle → 把
1401
+ * R15 Important-1(回合间空档误发致 mode:once 提前退出、后半段永不朗读)**重新
1402
+ * 引进来**。故这里刻意不挂 cancel(),宁可把区分权交回 host。
1403
+ *
1404
+ * 语义(与 noteTurnEnd 唯一的差别就是不发 onIdle):
1405
+ * · 只合闸门(清 openTurns):此后该会话若还有句子读尽,pump finally 会正常补发;
1406
+ * 下一回合的 enqueue 也照常重开闸门,语义与 noteTurnEnd 之后完全一致。
1407
+ * · 不主动补发:abort 时队列可能已空,此时该不该让 mode:once 立即收尾取决于 host
1408
+ * 的上下文(用户是否马上又要开口),队列无从判断。若 host 判定「abort 前已读尽」,
1409
+ * 在其后紧接一次 noteTurnEnd(sessionId) 即可补发(两次调用对 openTurns 幂等)。
1410
+ *
1411
+ * 接线点:宿主侧在判定回合被 abort / blocked / 空首步时调用(这三类路径都不派发
1412
+ * agent/turn-stopping——error 半边已由 ctx.on('agent/error') 覆盖,见 index.ts:1112)。
1413
+ */
1414
+ abandonTurn(sessionId) {
1415
+ this.openTurns.delete(sessionId);
1222
1416
  }
1223
1417
  /** 当前引擎音频 MIME(/preview 的 Content-Type 也用它)。 */
1224
1418
  get mime() {
@@ -1236,8 +1430,10 @@ var TtsQueue = class {
1236
1430
  * sentenceId 拒绝线(rejectSeqUpTo)是「旧会话遗留的最大句号」,新回复前 N 句
1237
1431
  * 全部 ≤ 线被静默丢弃——正是 /toggle 用 cancel 而非 prune 保 seq 连续的同一条
1238
1432
  * 不变式(index.ts:1177 进模式 cancel / :1191 让出旧会话 cancel(previous) / :1210 退出 cancel)。
1239
- * 故此处与 cancel() 同构:逐队列 epoch++ + 清积压,但保留 SessionQueue 对象本身
1240
- * (seq 连续递增,跨引擎切换不归零)。
1433
+ * 故此处与 cancel() 同构:逐队列 epoch++ + 清积压,但保留 SessionQueue 对象本身。
1434
+ * R15 T-3 后这条顾虑的一半已由构造消除:seq 是**全局**发号器(不再随队列存亡),
1435
+ * 故即便队列对象事后被回收,重入的会话拿到的句号仍必然 > 旧线;但 epoch 仍必须
1436
+ * 逐队列提升才能压住孤儿泵,那部分保留原样。
1241
1437
  */
1242
1438
  setEngine(engine) {
1243
1439
  const old = this.engine;
@@ -1293,9 +1489,10 @@ var TtsQueue = class {
1293
1489
  /** 为某会话入队一句;若泵空闲则启动。 */
1294
1490
  enqueue(sessionId, text) {
1295
1491
  if (this.closed) return;
1492
+ if (this.awaitTurnEnd) this.openTurns.add(sessionId);
1296
1493
  let q = this.queues.get(sessionId);
1297
1494
  if (!q) {
1298
- q = { pending: [], busy: false, seq: 0, epoch: 0, errorNotified: false, backoff: 0, failStreak: 0 };
1495
+ q = { pending: [], busy: false, epoch: 0, errorNotified: false, backoff: 0, failStreak: 0 };
1299
1496
  this.queues.set(sessionId, q);
1300
1497
  }
1301
1498
  if (q.pending.length >= 500) {
@@ -1324,6 +1521,7 @@ var TtsQueue = class {
1324
1521
  q.epoch++;
1325
1522
  q.pending.length = 0;
1326
1523
  }
1524
+ this.openTurns.delete(sessionId);
1327
1525
  this.queues.delete(sessionId);
1328
1526
  }
1329
1527
  async pump(sessionId, q) {
@@ -1358,7 +1556,7 @@ var TtsQueue = class {
1358
1556
  q.errorNotified = false;
1359
1557
  q.failStreak = 0;
1360
1558
  q.backoff = 0;
1361
- const sentenceId = q.seq++;
1559
+ const sentenceId = this.seq++;
1362
1560
  const mime = this.engine.mime;
1363
1561
  const dataFrame = {
1364
1562
  sessionId,
@@ -1400,7 +1598,15 @@ var TtsQueue = class {
1400
1598
  q.busy = false;
1401
1599
  if (this.queues.get(sessionId) !== q) return;
1402
1600
  if (this.closed) return;
1403
- if (q.pending.length > 0) {
1601
+ if (q.pending.length === 0) {
1602
+ if (!this.openTurns.has(sessionId)) {
1603
+ try {
1604
+ this.onIdle?.(sessionId);
1605
+ } catch {
1606
+ }
1607
+ }
1608
+ this.queues.delete(sessionId);
1609
+ } else {
1404
1610
  const delay = q.errorNotified ? q.backoff : 0;
1405
1611
  q.backoff = Math.min(8e3, delay + 1e3);
1406
1612
  if (delay > 0) {
@@ -1415,6 +1621,7 @@ var TtsQueue = class {
1415
1621
  }
1416
1622
  async close() {
1417
1623
  this.closed = true;
1624
+ this.openTurns.clear();
1418
1625
  for (const timer of this.backoffTimers) clearTimeout(timer);
1419
1626
  this.backoffTimers.clear();
1420
1627
  for (const timer of this.retryTimers) clearTimeout(timer);
@@ -1846,6 +2053,7 @@ function createSherpaLocalEngine(options) {
1846
2053
  allowCustomHost,
1847
2054
  broadcast: trackedBroadcast
1848
2055
  });
2056
+ if (closed) return;
1849
2057
  if (!treeOk) throw new Error("local TTS model download failed: espeak-ng-data");
1850
2058
  }
1851
2059
  if (!child) {
@@ -1855,6 +2063,7 @@ function createSherpaLocalEngine(options) {
1855
2063
  stdio: ["ignore", "ignore", "pipe", "ipc"],
1856
2064
  ...runtime.execPath ? { execPath: runtime.execPath, env: runtime.env } : {}
1857
2065
  });
2066
+ const me = child;
1858
2067
  let stderrTail = "";
1859
2068
  child.stderr?.on("data", (chunk) => {
1860
2069
  stderrTail += String(chunk);
@@ -1876,12 +2085,14 @@ function createSherpaLocalEngine(options) {
1876
2085
  });
1877
2086
  child.on("error", (e) => {
1878
2087
  rejectAll(e instanceof Error ? e : new Error(String(e)));
2088
+ if (child !== me) return;
1879
2089
  child = null;
1880
2090
  childInit = false;
1881
2091
  ready = null;
1882
2092
  });
1883
2093
  child.on("exit", (code) => {
1884
2094
  rejectAll(new Error(`tts child exited with code ${code}`));
2095
+ if (child !== me) return;
1885
2096
  child = null;
1886
2097
  childInit = false;
1887
2098
  ready = null;
@@ -1889,6 +2100,7 @@ function createSherpaLocalEngine(options) {
1889
2100
  }
1890
2101
  if (!childInit) {
1891
2102
  const init = await call({ type: "init", kind: options.kind, paths: spec.workerPaths(repoDir) });
2103
+ if (closed) return;
1892
2104
  if (!init.ok) throw new Error(init.error ?? "tts child init failed");
1893
2105
  childInit = true;
1894
2106
  }
@@ -2129,7 +2341,7 @@ var en = {
2129
2341
  startFail: "Voice mode failed to start: {err}",
2130
2342
  holdDots: "Hold to talk\u2026",
2131
2343
  exit: "Exit",
2132
- configUnavailableNote: " (settings document not ready; the panel will appear when it is).",
2344
+ configUnavailableNote: " (settings document not ready; retrying \u2014 the panel will appear when it is).",
2133
2345
  previewNameFirst: "Enter a voice ShortName first",
2134
2346
  previewDisabled: "Voice mode disabled (plugin enabled=false); preview unavailable",
2135
2347
  // 批 G 任务 6:本地 TTS 引擎未下载模型时禁用试听按钮 + 提示。
@@ -2169,6 +2381,17 @@ var en = {
2169
2381
  // R1 收尾(fix-client 直连 tk() 调用):连续 3 次回声拒断的解释出口 + 快捷键非法停用提示。
2170
2382
  echoRejectHint: "Strong echo detected \u2014 barge-in is limited by echo protection. Use headphones or switch to manual barge-in",
2171
2383
  shortcutInvalid: "Invalid shortcut, disabled. Fix it in settings (e.g. Ctrl+Shift+V); leave empty to use the mic button only",
2384
+ descComposerShortcut: "Shortcut to toggle voice mode while the composer has focus (default Alt/Option+Enter)",
2385
+ composerShortcutLabel: "Enter / exit voice mode (in composer)",
2386
+ shortcutRecord: "Record",
2387
+ shortcutRecording: "Press a key combo\u2026",
2388
+ shortcutCancel: "Cancel",
2389
+ shortcutNeedModifier: "At least one modifier is required",
2390
+ shortcutUnsupportedKey: "Only letters, digits, Enter, Space and Tab are supported",
2391
+ shortcutPlaceholder: "Click Record, then press a combo",
2392
+ shortcutReset: "Reset to default",
2393
+ shortcutNote: "Alt/Option+Enter toggles inside the composer; Cmd / Ctrl / Alt / Shift combos are supported; leaving it empty means mic button only. While recording, Backspace clears and Esc cancels; avoid browser-reserved combos (Cmd+W / T / N / L). Changes apply immediately.",
2394
+ secShortcut: "Shortcut",
2172
2395
  elapsedHint: "Current voice session duration",
2173
2396
  botLevelsHint: "AI playback level (blue bar = TTS playback, green bar = microphone)",
2174
2397
  interruptConfirm: "interrupt confirm",
@@ -2205,13 +2428,24 @@ var en = {
2205
2428
  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
2429
  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
2430
  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",
2208
- descMode: "Interaction mode (toggle: continuous listen + auto-send / hold: press to talk)",
2431
+ descMode: "Interaction mode (toggle: continuous listen + auto-send / hold: press to talk / once: one utterance, then exit after the reply is read aloud)",
2209
2432
  modeToggle: "Continuous listening",
2210
2433
  modeHold: "Hold to talk",
2434
+ modeOnce: "One-shot",
2435
+ stopReading: "Stop reading",
2436
+ readAloudLabel: "Read replies",
2437
+ readAloudVoice: "Voice mode",
2438
+ readAloudAlways: "Always",
2439
+ readAloudOff: "Off",
2440
+ descReadAloud: "Voice mode = read replies only in voice mode (default); Always = read every reply in the current session, typed ones included; Off = never read aloud",
2441
+ showCaptionsLabel: "Caption overlay",
2442
+ descShowCaptions: "Show a floating caption of the current sentence while reading aloud",
2443
+ showStatusBarLabel: "Status bar",
2444
+ descShowStatusBar: "Show the voice status bar above the composer (waveform, transcript, timer, notices, exit); when off, state shows only on the mic button",
2211
2445
  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',
2212
2446
  wakePlaceholder: "e.g. Hey D",
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.",
2447
+ settingsCardDesc: "Engine / voice / rate / interrupt / barge-in / echo gate / silence / idle / model host / auto-send / read replies / status bar / caption overlay / auto-resume / mode / wake word / tool beep / ITN / caption font / caption width / yielding / yield window / barge-in salvage / LLM correction",
2448
+ 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) / read replies / status bar / caption overlay / 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
2449
  effectivePending: "{count} change(s) will apply next time you enter voice mode: {items}",
2216
2450
  valueOn: "On",
2217
2451
  valueOff: "Off",
@@ -2288,7 +2522,7 @@ var en = {
2288
2522
  bargeInModeLabel: "Interrupt mode",
2289
2523
  echoGateDbLabel: "Echo gate",
2290
2524
  modeLabel: "Interaction mode",
2291
- shortcutLabel: "Shortcut",
2525
+ shortcutLabel: "Enter / exit voice mode (app-wide)",
2292
2526
  wakeWordLabel: "Wake word",
2293
2527
  toolBeepLabel: "Tool-call beep",
2294
2528
  autoSendLabel: "Auto-send",
@@ -2324,6 +2558,7 @@ var en = {
2324
2558
  errUnknownSession: "Voice session expired \u2014 re-enter voice mode",
2325
2559
  errForbidden: "Request denied (local access only, or origin mismatch)",
2326
2560
  errBadRequest: "Invalid request",
2561
+ errMethodNotAllowed: "Request method not allowed",
2327
2562
  errEngineNotActive: "That read-aloud engine is not active",
2328
2563
  errModelDownload: "Model download failed \u2014 check your network",
2329
2564
  errTooManyStreams: "Too many voice connections \u2014 close other voice tabs and retry",
@@ -2340,7 +2575,16 @@ var en = {
2340
2575
  function correctionSystem(lang) {
2341
2576
  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
2577
  }
2343
- var CORRECTION_PREAMBLE_RE = /^(?:以下是|这是)?(?:修正|纠正|更正|纠错)|^(?:here is (?:the )?)?(?:corrected|correction)\b/i;
2578
+ var CORRECTION_PREAMBLE_RE = /^(?:以下是|这是)?(?:修正|纠正|更正|纠错)|^(?:here(?:'s| is) (?:the |an |a )?)?(?:corrected|correction)\b/i;
2579
+ var CORRECTION_FILLER_WORDS = "\u5F53\u7136\u53EF\u4EE5|\u5F53\u7136|\u597D\u5427|\u597D\u7684?|\u884C\u5427|\u884C|\u662F\u7684|\u55EF|\u6536\u5230|\u660E\u767D\u4E86|\u77E5\u9053\u4E86|Thank you|Of course|Got it|OK|Okay|Sure|Certainly|Alright|Understood|Hello|Hi|Yes|Thanks";
2580
+ var CORRECTION_FILLER_PREFIX_RE = new RegExp(
2581
+ "^(?:(?:" + CORRECTION_FILLER_WORDS + ")(?:\\s*[,\uFF0C\u3001:\uFF1A.\u3002!\uFF01?\uFF1F)\uFF09]|\\s))+",
2582
+ "i"
2583
+ );
2584
+ var CORRECTION_PURE_FILLER_RE = new RegExp(
2585
+ "^(?:(?:" + CORRECTION_FILLER_WORDS + ")(?:\\s*[,\uFF0C\u3001:\uFF1A.\u3002!\uFF01?\uFF1F)\uFF09]\\s*|\\s+))*(?:" + CORRECTION_FILLER_WORDS + ")\\s*$",
2586
+ "i"
2587
+ );
2344
2588
  async function correctText(ctx, text, lang) {
2345
2589
  const trimmed = String(text ?? "").trim();
2346
2590
  if (!trimmed) return text;
@@ -2365,6 +2609,17 @@ async function correctText(ctx, text, lang) {
2365
2609
  const corrected = out.trim();
2366
2610
  if (corrected.length > Math.max(trimmed.length * 3, trimmed.length + 24)) return text;
2367
2611
  if (CORRECTION_PREAMBLE_RE.test(corrected)) return text;
2612
+ let noFiller = corrected;
2613
+ for (; ; ) {
2614
+ const next = noFiller.replace(CORRECTION_FILLER_PREFIX_RE, "").trimStart();
2615
+ const after = CORRECTION_PURE_FILLER_RE.test(next) ? "" : next;
2616
+ if (after === noFiller) break;
2617
+ noFiller = after;
2618
+ }
2619
+ if (noFiller !== corrected) {
2620
+ if (noFiller === "") return text;
2621
+ if (CORRECTION_PREAMBLE_RE.test(noFiller)) return text;
2622
+ }
2368
2623
  return corrected || text;
2369
2624
  } catch {
2370
2625
  return text;
@@ -2498,6 +2753,7 @@ function readLegacyVoiceSettings(dir, keys) {
2498
2753
  // src/index.ts
2499
2754
  var name = "voice-mode";
2500
2755
  var NS_VOICE_MODE = "voice-mode";
2756
+ var MUTED_STREAMS_WITHOUT_TURN = 4;
2501
2757
  var BASE_PATH = "/voice-mode";
2502
2758
  var PREVIEW_NETWORK_PATTERN = /fetch failed|ECONN|ENOTFOUND|getaddrinfo|ETIMEDOUT|EAI_AGAIN|network|unreachable|socket hang up|aborted|WebSocket error/i;
2503
2759
  var PREVIEW_ENGINE_PATTERN = /model download|model verify|init failed|child exited|tts child|local TTS|prepare|sherpa|local Kokoro/i;
@@ -2533,11 +2789,15 @@ var VOICE_SETTINGS_DEFAULTS = {
2533
2789
  autoSend: true,
2534
2790
  autoResume: false,
2535
2791
  mode: "toggle",
2792
+ readAloud: "voice",
2793
+ showCaptions: true,
2794
+ showStatusBar: true,
2536
2795
  // 批 7O(ADR-0006):bargeInMode 默认 'auto' → 'detect'(I10 豁免:ADR-0006 已 accepted 拍板,
2537
2796
  // 老用户显式 auto 不受影响,新用户/未调过的用户开箱即对)。
2538
2797
  bargeInMode: "detect",
2539
2798
  echoGateDb: 6,
2540
2799
  shortcut: "Ctrl+Shift+V",
2800
+ composerShortcut: "Alt+Enter",
2541
2801
  spokenFormat: true,
2542
2802
  senseVoice: true,
2543
2803
  wakeWord: "",
@@ -2568,6 +2828,10 @@ var DESC = {
2568
2828
  autoSend: en.descAutoSend,
2569
2829
  autoResume: en.descAutoResume,
2570
2830
  mode: en.descMode,
2831
+ readAloud: en.descReadAloud,
2832
+ showCaptions: en.descShowCaptions,
2833
+ showStatusBar: en.descShowStatusBar,
2834
+ composerShortcut: en.descComposerShortcut,
2571
2835
  bargeInMode: en.descBargeIn,
2572
2836
  echoGateDb: en.descEchoGate,
2573
2837
  shortcut: en.descShortcut,
@@ -2605,7 +2869,11 @@ function createVoiceSettingsSchema(defs) {
2605
2869
  autoSend: z.boolean().default(d.autoSend).description(DESC.autoSend),
2606
2870
  // 批 7N 重做 5/5:与 strings.ts descAutoResume 同步——明确「下次进入语音会话即生效」。
2607
2871
  autoResume: z.boolean().default(d.autoResume).description(DESC.autoResume),
2608
- mode: z.union([z.const("toggle"), z.const("hold")]).default(d.mode).description(DESC.mode),
2872
+ mode: z.union([z.const("toggle"), z.const("hold"), z.const("once")]).default(d.mode).description(DESC.mode),
2873
+ readAloud: z.union([z.const("voice"), z.const("always"), z.const("off")]).default(d.readAloud).description(DESC.readAloud),
2874
+ showCaptions: z.boolean().default(d.showCaptions).description(DESC.showCaptions),
2875
+ showStatusBar: z.boolean().default(d.showStatusBar).description(DESC.showStatusBar),
2876
+ composerShortcut: z.string().default(d.composerShortcut).description(DESC.composerShortcut),
2609
2877
  bargeInMode: z.union([z.const("auto"), z.const("manual"), z.const("detect")]).default(d.bargeInMode).description(DESC.bargeInMode),
2610
2878
  echoGateDb: z.number().min(3).max(12).default(d.echoGateDb).description(
2611
2879
  DESC.echoGateDb
@@ -2664,13 +2932,17 @@ var Config = z.object({
2664
2932
  // 本插件自带 settings-form 设置面板 + /voice-mode/config,不受影响)。
2665
2933
  autoSend: z.boolean().default(true),
2666
2934
  autoResume: z.boolean().default(false),
2667
- mode: z.union([z.const("toggle"), z.const("hold")]).default("toggle"),
2935
+ mode: z.union([z.const("toggle"), z.const("hold"), z.const("once")]).default("toggle"),
2936
+ readAloud: z.union([z.const("voice"), z.const("always"), z.const("off")]).default("voice"),
2937
+ showCaptions: z.boolean().default(true),
2938
+ showStatusBar: z.boolean().default(true),
2668
2939
  bargeInMode: z.union([z.const("auto"), z.const("manual"), z.const("detect")]).default("detect"),
2669
2940
  // I3 + M7(zod 界):echoGateDb / yieldMs 与 settings schema 同界(3-12 dB / 500-3000ms)。
2670
2941
  // client 与 NumberField 虽会 clamp,但那只是 UI 兜底——Config 层无界时 YAML 手滑
2671
2942
  // 仍可把回声门阈设成 0(句句误打断)或让位窗口设成 60000(让位后一分钟不说话)。
2672
2943
  echoGateDb: z.number().min(3).max(12).default(6),
2673
2944
  shortcut: z.string().default("Ctrl+Shift+V"),
2945
+ composerShortcut: z.string().default("Alt+Enter"),
2674
2946
  spokenFormat: z.boolean().default(true),
2675
2947
  senseVoice: z.boolean().default(true),
2676
2948
  wakeWord: z.string().default(""),
@@ -2686,6 +2958,9 @@ var Config = z.object({
2686
2958
  // I3 + M7(zod 界):500-3000ms,与 settings schema 一致。
2687
2959
  yieldMs: z.number().min(500).max(3e3).default(1500)
2688
2960
  });
2961
+ function displayOf(v) {
2962
+ return { readAloud: v.readAloud, showCaptions: v.showCaptions, showStatusBar: v.showStatusBar };
2963
+ }
2689
2964
  function voiceSettingsFromConfig(config) {
2690
2965
  const {
2691
2966
  ttsEngine,
@@ -2699,9 +2974,13 @@ function voiceSettingsFromConfig(config) {
2699
2974
  autoSend,
2700
2975
  autoResume,
2701
2976
  mode,
2977
+ readAloud,
2978
+ showCaptions,
2979
+ showStatusBar,
2702
2980
  bargeInMode,
2703
2981
  echoGateDb,
2704
2982
  shortcut,
2983
+ composerShortcut,
2705
2984
  spokenFormat,
2706
2985
  senseVoice,
2707
2986
  wakeWord,
@@ -2726,9 +3005,13 @@ function voiceSettingsFromConfig(config) {
2726
3005
  autoSend,
2727
3006
  autoResume,
2728
3007
  mode,
3008
+ readAloud,
3009
+ showCaptions,
3010
+ showStatusBar,
2729
3011
  bargeInMode,
2730
3012
  echoGateDb,
2731
3013
  shortcut,
3014
+ composerShortcut,
2732
3015
  spokenFormat,
2733
3016
  senseVoice,
2734
3017
  wakeWord,
@@ -2744,20 +3027,34 @@ function voiceSettingsFromConfig(config) {
2744
3027
  }
2745
3028
  function apply(ctx, config) {
2746
3029
  let activeVoiceSession = null;
3030
+ let focusedSessionId = null;
3031
+ let focusedTabId = null;
2747
3032
  let activeTabId = null;
2748
3033
  let activeVoiceLang = "zh";
2749
3034
  let ownerYieldTimer = null;
3035
+ const readMuted = /* @__PURE__ */ new Map();
3036
+ const turnOfSession = /* @__PURE__ */ new Map();
3037
+ const tapInFlight = /* @__PURE__ */ new Set();
2750
3038
  const turnStates = /* @__PURE__ */ new Map();
2751
- const setTurn = (sessionId, state) => {
3039
+ const setTurn = (sessionId, state, turn) => {
2752
3040
  if (turnStates.get(sessionId) === state) return;
2753
3041
  turnStates.set(sessionId, state);
2754
- broadcast("turn", { sessionId, state });
3042
+ broadcast("turn", { sessionId, state, turn });
2755
3043
  };
2756
3044
  const turnGen = /* @__PURE__ */ new Map();
2757
- const clearTurnState = (sessionId) => {
2758
- setTurn(sessionId, "idle");
3045
+ const dropTurnTables = (sessionId) => {
2759
3046
  turnStates.delete(sessionId);
2760
3047
  turnGen.delete(sessionId);
3048
+ readMuted.delete(sessionId);
3049
+ turnOfSession.delete(sessionId);
3050
+ };
3051
+ const clearTurnState = (sessionId) => {
3052
+ setTurn(sessionId, "idle");
3053
+ dropTurnTables(sessionId);
3054
+ };
3055
+ const reclaimFocusState = (sessionId) => {
3056
+ if (sessionId === null || sessionId === activeVoiceSession || tapInFlight.has(sessionId)) return;
3057
+ dropTurnTables(sessionId);
2761
3058
  };
2762
3059
  const sessions = ctx.get("sessions");
2763
3060
  const limiter = new RateLimiter();
@@ -2924,7 +3221,13 @@ function apply(ctx, config) {
2924
3221
  onError: (sessionId) => broadcast("tts-error", { sessionId }),
2925
3222
  // 单句重试耗尽被跳过:显式下行(客户端提示 + 诊断),不再静默丢句。
2926
3223
  // streak = 连续被跳过的句数:客户端据此区分偶发抖动与「云端整体不可用」(如服务端拒绝握手)。
2927
- onSkip: (sessionId, text, streak) => broadcast("tts-skip", { sessionId, text: text.slice(0, 80), streak })
3224
+ onSkip: (sessionId, text, streak) => broadcast("tts-skip", { sessionId, text: text.slice(0, 80), streak }),
3225
+ onIdle: (sessionId) => broadcast("tts-idle", { sessionId }),
3226
+ // R15(Issue #15 Important-2 host 侧接线):onIdle 降级为「候选空闲」——「队列排空」不等于
3227
+ // 「回合结束」。带工具调用的回合会在工具执行期间把队列排空一次,据此发 tts-idle 会让
3228
+ // mode:once 在空档里提前 exitMode(麦克风熄灭、后半段回复永不朗读)。置 true 后 tts-idle
3229
+ // 只在 host 经 `agent/turn-stopping` 确认回合真正结束后才发(见下方钩子)。
3230
+ awaitTurnEnd: true
2928
3231
  });
2929
3232
  queue.updateVoice(vset.voice, vset.rate);
2930
3233
  const unsubscribe = queue.subscribe((frame) => broadcast("audio", frame));
@@ -2933,6 +3236,7 @@ function apply(ctx, config) {
2933
3236
  const applyVset = (next) => {
2934
3237
  const prev = vset;
2935
3238
  vset = next;
3239
+ broadcast("display", displayOf(next));
2936
3240
  if (next.ttsEngine !== engineKind) {
2937
3241
  engineKind = next.ttsEngine;
2938
3242
  queue.setEngine(makeEngine(engineKind));
@@ -2991,19 +3295,49 @@ function apply(ctx, config) {
2991
3295
  const rawSessionId = options.sessionId;
2992
3296
  if (!config.enabled || rawSessionId === void 0 || options.purpose !== void 0) return next();
2993
3297
  const sessionId = rawSessionId;
2994
- if (activeVoiceSession !== sessionId) return next();
3298
+ const alwaysRead = vset.readAloud === "always" && focusedSessionId === sessionId && activeVoiceSession === null;
3299
+ if (activeVoiceSession !== sessionId && !alwaysRead) return next();
2995
3300
  const gen = (turnGen.get(sessionId) ?? 0) + 1;
2996
3301
  turnGen.set(sessionId, gen);
3302
+ const mute = readMuted.get(sessionId);
3303
+ const pos = turnOfSession.get(sessionId);
3304
+ if (mute !== void 0) {
3305
+ const atTurnBoundary = pos !== void 0 && (mute.turn === null ? pos.step === 1 : pos.turn !== mute.turn);
3306
+ if (atTurnBoundary) {
3307
+ readMuted.delete(sessionId);
3308
+ } else if (pos === void 0 || mute.turn === null) {
3309
+ mute.streams += 1;
3310
+ if (mute.streams > MUTED_STREAMS_WITHOUT_TURN) readMuted.delete(sessionId);
3311
+ }
3312
+ }
3313
+ tapInFlight.add(sessionId);
2997
3314
  return tapActiveStream(
2998
3315
  sessionId,
2999
3316
  next(),
3000
3317
  queue,
3001
3318
  broadcast,
3002
3319
  (state) => {
3003
- if ((turnGen.get(sessionId) ?? 0) === gen) setTurn(sessionId, state);
3004
- }
3320
+ const turn = turnOfSession.get(sessionId)?.turn;
3321
+ if (state === "listening") {
3322
+ tapInFlight.delete(sessionId);
3323
+ if (focusedSessionId !== sessionId && activeVoiceSession !== sessionId) {
3324
+ reclaimFocusState(sessionId);
3325
+ }
3326
+ }
3327
+ if ((turnGen.get(sessionId) ?? 0) !== gen) return;
3328
+ setTurn(sessionId, state, turn);
3329
+ },
3330
+ vset.readAloud !== "off",
3331
+ () => readMuted.has(sessionId)
3005
3332
  );
3006
3333
  });
3334
+ ctx.on("agent/turn-stopping", ({ agent }) => queue.noteTurnEnd(agent.id));
3335
+ ctx.on("agent/error", ({ agent }) => queue.noteTurnEnd(agent.id));
3336
+ ctx.on("agent/pre-step", ({ agent, turn, step }, next) => {
3337
+ const sid = agent.id;
3338
+ if (sid === activeVoiceSession || sid === focusedSessionId) turnOfSession.set(sid, { turn, step });
3339
+ return next();
3340
+ });
3007
3341
  const base = BASE_PATH;
3008
3342
  ctx.effect(
3009
3343
  () => ctx.webServer.register({
@@ -3038,9 +3372,13 @@ function apply(ctx, config) {
3038
3372
  autoSend: vset.autoSend,
3039
3373
  autoResume: vset.autoResume,
3040
3374
  mode: vset.mode,
3375
+ readAloud: vset.readAloud,
3376
+ showCaptions: vset.showCaptions,
3377
+ showStatusBar: vset.showStatusBar,
3041
3378
  bargeInMode: vset.bargeInMode,
3042
3379
  echoGateDb: vset.echoGateDb,
3043
3380
  shortcut: vset.shortcut,
3381
+ composerShortcut: vset.composerShortcut,
3044
3382
  wakeWord: vset.wakeWord,
3045
3383
  toolBeep: vset.toolBeep,
3046
3384
  captionFontSize: vset.captionFontSize,
@@ -3064,11 +3402,12 @@ function apply(ctx, config) {
3064
3402
  path: `${base}/preview`,
3065
3403
  handler: (req, res) => {
3066
3404
  if (denyNonLoopback(req, res)) return;
3067
- if (denyCrossOrigin(req, res)) return;
3068
- if (!limiter.hit(`preview:${clientKey(req)}`, 20, 6e4)) {
3069
- respondJson2(res, 429, { code: "rate_limited", error: "rate limited" });
3405
+ if (req.method !== "POST") {
3406
+ res.setHeader("allow", "POST");
3407
+ respondJson2(res, 405, { code: "method_not_allowed", error: "POST required" });
3070
3408
  return;
3071
3409
  }
3410
+ if (denyCrossOrigin(req, res)) return;
3072
3411
  if (!config.enabled) {
3073
3412
  respondJson2(res, 403, { code: "voice_disabled", error: "voice mode disabled" });
3074
3413
  return;
@@ -3092,6 +3431,10 @@ function apply(ctx, config) {
3092
3431
  respondJson2(res, 400, { code: "bad_request", error: "voice required" });
3093
3432
  return;
3094
3433
  }
3434
+ if (!limiter.hit(`preview:${clientKey(req)}`, 20, 6e4)) {
3435
+ respondJson2(res, 429, { code: "rate_limited", error: "rate limited" });
3436
+ return;
3437
+ }
3095
3438
  const sample = previewSample(currentEngine(), voice);
3096
3439
  let buf;
3097
3440
  try {
@@ -3248,9 +3591,8 @@ function apply(ctx, config) {
3248
3591
  handler: (req, res) => {
3249
3592
  if (denyNonLoopback(req, res)) return;
3250
3593
  if (req.method !== "POST") {
3251
- res.statusCode = 405;
3252
3594
  res.setHeader("allow", "POST");
3253
- res.end();
3595
+ respondJson2(res, 405, { code: "method_not_allowed", error: "POST required" });
3254
3596
  return;
3255
3597
  }
3256
3598
  if (denyCrossOrigin(req, res)) return;
@@ -3382,6 +3724,11 @@ function apply(ctx, config) {
3382
3724
  handler: (req, res) => {
3383
3725
  if (denyNonLoopback(req, res)) return;
3384
3726
  if (denyCrossOrigin(req, res)) return;
3727
+ if (req.method !== "POST") {
3728
+ res.setHeader("allow", "POST");
3729
+ respondJson2(res, 405, { code: "method_not_allowed", error: "POST required" });
3730
+ return;
3731
+ }
3385
3732
  let sid = "";
3386
3733
  try {
3387
3734
  const url = new URL(req.url ?? "/", "http://localhost");
@@ -3413,19 +3760,23 @@ function apply(ctx, config) {
3413
3760
  collectBody(req, res, MAX_JSON_BODY, (body) => {
3414
3761
  let sessionId;
3415
3762
  let keepAsr = false;
3763
+ let isInterrupt = false;
3416
3764
  try {
3417
3765
  const parsed = JSON.parse(body || "{}");
3418
3766
  sessionId = parsed.sessionId;
3419
3767
  keepAsr = parsed.keepAsr === true;
3768
+ isInterrupt = parsed.reason === "interrupt";
3420
3769
  } catch {
3421
3770
  }
3422
- if (sessionId && sessionId === activeVoiceSession) {
3771
+ if (sessionId && (sessionId === activeVoiceSession || sessionId === focusedSessionId)) {
3423
3772
  if (!limiter.hit(`cancel:${sessionId}`, 2, 1e3)) {
3424
3773
  respondJson2(res, 429, { code: "rate_limited", error: "rate limited" });
3425
3774
  return;
3426
3775
  }
3427
3776
  queue.cancel(sessionId);
3428
- if (!keepAsr) asr.reset(sessionId);
3777
+ if (isInterrupt) queue.abandonTurn(sessionId);
3778
+ readMuted.set(sessionId, { turn: turnOfSession.get(sessionId)?.turn ?? null, streams: 0 });
3779
+ if (!keepAsr && sessionId === activeVoiceSession) asr.reset(sessionId);
3429
3780
  }
3430
3781
  respondJson2(res, 200, { ok: true });
3431
3782
  });
@@ -3443,9 +3794,8 @@ function apply(ctx, config) {
3443
3794
  return;
3444
3795
  }
3445
3796
  if (req.method !== "POST") {
3446
- res.statusCode = 405;
3447
3797
  res.setHeader("allow", "GET, POST");
3448
- res.end();
3798
+ respondJson2(res, 405, { code: "method_not_allowed", error: "GET or POST required" });
3449
3799
  return;
3450
3800
  }
3451
3801
  if (denyCrossOrigin(req, res)) return;
@@ -3496,11 +3846,11 @@ function apply(ctx, config) {
3496
3846
  let mode;
3497
3847
  try {
3498
3848
  const parsed = JSON.parse(body || "{}");
3499
- mode = parsed.mode === "toggle" || parsed.mode === "hold" ? parsed.mode : void 0;
3849
+ mode = parsed.mode === "toggle" || parsed.mode === "hold" || parsed.mode === "once" ? parsed.mode : void 0;
3500
3850
  } catch {
3501
3851
  }
3502
3852
  if (!mode) {
3503
- respondJson2(res, 400, { code: "bad_request", error: "mode must be toggle or hold" });
3853
+ respondJson2(res, 400, { code: "bad_request", error: "mode must be toggle, hold or once" });
3504
3854
  return;
3505
3855
  }
3506
3856
  const persistMode = settingsScopeRef ? settingsScopeRef.update({ mode }) : persistSettings({ mode });
@@ -3514,6 +3864,45 @@ function apply(ctx, config) {
3514
3864
  }
3515
3865
  })
3516
3866
  );
3867
+ ctx.effect(
3868
+ () => ctx.webServer.register({
3869
+ kind: "exact",
3870
+ path: `${base}/focus`,
3871
+ handler: (req, res) => {
3872
+ if (denyNonLoopback(req, res)) return;
3873
+ if (denyCrossOrigin(req, res)) return;
3874
+ collectBody(req, res, MAX_JSON_BODY, (body) => {
3875
+ let parsed = {};
3876
+ try {
3877
+ parsed = JSON.parse(body || "{}");
3878
+ } catch {
3879
+ }
3880
+ const { sessionId, tabId } = parsed;
3881
+ const prevFocus = focusedSessionId;
3882
+ const validTab = typeof tabId === "string" && tabId.length > 0 && tabId.length <= 64;
3883
+ const validSid = typeof sessionId === "string" && sessionId.length > 0 && sessionId.length <= 128;
3884
+ if (!validTab || !(validSid || sessionId === null)) {
3885
+ respondJson2(res, 400, { code: "bad_request", error: "expected {sessionId: string|null, tabId: string}" });
3886
+ return;
3887
+ }
3888
+ if (validSid) {
3889
+ if (sessions && !sessions.get(sessionId)) {
3890
+ respondJson2(res, 403, { code: "unknown_session", error: "unknown session" });
3891
+ return;
3892
+ }
3893
+ focusedSessionId = sessionId;
3894
+ focusedTabId = tabId;
3895
+ } else if (tabId === focusedTabId) {
3896
+ focusedSessionId = null;
3897
+ focusedTabId = null;
3898
+ }
3899
+ if (prevFocus !== null && prevFocus !== focusedSessionId) reclaimFocusState(prevFocus);
3900
+ broadcast("focus", { sessionId: focusedSessionId, tabId: focusedTabId });
3901
+ respondJson2(res, 200, { ok: true, sessionId: focusedSessionId, tabId: focusedTabId });
3902
+ });
3903
+ }
3904
+ })
3905
+ );
3517
3906
  ctx.effect(
3518
3907
  () => ctx.webServer.register({
3519
3908
  kind: "exact",
@@ -3521,10 +3910,6 @@ function apply(ctx, config) {
3521
3910
  handler: (req, res) => {
3522
3911
  if (denyNonLoopback(req, res)) return;
3523
3912
  if (denyCrossOrigin(req, res)) return;
3524
- if (sseClients.size >= 4) {
3525
- respondJson2(res, 429, { code: "too_many_streams", error: "too many streams" });
3526
- return;
3527
- }
3528
3913
  let tabId = null;
3529
3914
  try {
3530
3915
  const u = new URL(req.url ?? "/", "http://localhost");
@@ -3532,6 +3917,21 @@ function apply(ctx, config) {
3532
3917
  } catch {
3533
3918
  }
3534
3919
  if (tabId !== null && tabId.length > 64) tabId = null;
3920
+ if (tabId !== null) {
3921
+ for (const old of sseClients) {
3922
+ if (old.tabId !== tabId) continue;
3923
+ sseClients.delete(old);
3924
+ try {
3925
+ old.send("replaced", {});
3926
+ } catch {
3927
+ }
3928
+ old.end();
3929
+ }
3930
+ }
3931
+ if (sseClients.size >= 8) {
3932
+ respondJson2(res, 429, { code: "too_many_streams", error: "too many streams" });
3933
+ return;
3934
+ }
3535
3935
  res.writeHead(200, {
3536
3936
  "content-type": "text/event-stream; charset=utf-8",
3537
3937
  "cache-control": "no-cache, no-transform",
@@ -3544,7 +3944,13 @@ data: ${JSON.stringify(payload)}
3544
3944
 
3545
3945
  `);
3546
3946
  };
3547
- const client = { tabId, send };
3947
+ const end = () => {
3948
+ try {
3949
+ res.end();
3950
+ } catch {
3951
+ }
3952
+ };
3953
+ const client = { tabId, send, end };
3548
3954
  sseClients.add(client);
3549
3955
  if (tabId !== null) latestConnByTab.set(tabId, client);
3550
3956
  if (tabId !== null && tabId === activeTabId && ownerYieldTimer) {
@@ -3552,10 +3958,13 @@ data: ${JSON.stringify(payload)}
3552
3958
  ownerYieldTimer = null;
3553
3959
  }
3554
3960
  send("mode", { active: activeVoiceSession, ownerTabId: activeTabId });
3961
+ send("focus", { sessionId: focusedSessionId, tabId: focusedTabId });
3962
+ send("display", displayOf(vset));
3555
3963
  const heartbeat = setInterval(() => {
3556
3964
  try {
3557
3965
  res.write(": hb\n");
3558
3966
  } catch {
3967
+ cleanup();
3559
3968
  }
3560
3969
  }, 25e3);
3561
3970
  let cleaned = false;
@@ -3566,6 +3975,13 @@ data: ${JSON.stringify(payload)}
3566
3975
  sseClients.delete(client);
3567
3976
  if (tabId !== null && latestConnByTab.get(tabId) === client) {
3568
3977
  latestConnByTab.delete(tabId);
3978
+ if (tabId === focusedTabId) {
3979
+ const prevFocus = focusedSessionId;
3980
+ focusedSessionId = null;
3981
+ focusedTabId = null;
3982
+ reclaimFocusState(prevFocus);
3983
+ broadcast("focus", { sessionId: null, tabId: null });
3984
+ }
3569
3985
  if (tabId === activeTabId) {
3570
3986
  if (ownerYieldTimer) clearTimeout(ownerYieldTimer);
3571
3987
  ownerYieldTimer = setTimeout(() => yieldActiveSession(activeVoiceSession), 8e3);
@@ -3608,7 +4024,7 @@ function collectBody(req, res, maxBytes, onBody) {
3608
4024
  req.on("error", () => {
3609
4025
  });
3610
4026
  }
3611
- async function* tapActiveStream(sessionId, inner, queue, broadcast, onTurn) {
4027
+ async function* tapActiveStream(sessionId, inner, queue, broadcast, onTurn, speak = true, muted = () => false) {
3612
4028
  const segmenter = new SentenceSegmenter();
3613
4029
  let firstTokenBroadcast = false;
3614
4030
  let firstSentenceBroadcast = false;
@@ -3618,7 +4034,7 @@ async function* tapActiveStream(sessionId, inner, queue, broadcast, onTurn) {
3618
4034
  if (flushed) return;
3619
4035
  flushed = true;
3620
4036
  for (const s of segmenter.flush()) {
3621
- queue.enqueue(sessionId, s);
4037
+ if (speak && !muted()) queue.enqueue(sessionId, s);
3622
4038
  }
3623
4039
  };
3624
4040
  try {
@@ -3634,7 +4050,7 @@ async function* tapActiveStream(sessionId, inner, queue, broadcast, onTurn) {
3634
4050
  firstSentenceBroadcast = true;
3635
4051
  broadcast("latency", { sessionId, stage: "first-sentence-text" });
3636
4052
  }
3637
- queue.enqueue(sessionId, s);
4053
+ if (speak && !muted()) queue.enqueue(sessionId, s);
3638
4054
  }
3639
4055
  }
3640
4056
  if (chunk.type === "tool-call-delta" && chunk.name) {