dsh-folia 4.26.0-pre.45 → 4.26.0-pre.46

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/client.js CHANGED
@@ -946,6 +946,9 @@ window.__ModuleLoader__.load({
946
946
  "提交中…(正在准备)": "Submitting… (preparing)",
947
947
  "已等待 {s} 秒": "Waiting {s}s",
948
948
  "解压/落位中…": "Extracting…",
949
+ // pre.46:挂载自愈的 3 次退避重试期间,卡片显示“正在补收尾…”而不是干等 90 秒。
950
+ "正在补收尾…": "Finishing install…",
951
+ "第 {a}/{t} 次 · 下载已完成,正在补落地": "Attempt {a}/{t} · download finished, finishing install",
949
952
  // ── 「下载已完成但安装没落地」的自愈(4.23.6)──────────────────────────────
950
953
  // 死锁形态:job=done、落地没发生、卡片永远「解压/落位中…」。两类文案:
951
954
  // ① 超时之后**结果**(失败原因,卡片上的红字 +「重试」);
@@ -18025,18 +18028,23 @@ window.__ModuleLoader__.load({
18025
18028
  doneOf: (c) => Boolean(c.installed),
18026
18029
  path: "/boot/download",
18027
18030
  body: (c) => ({ id: c.id }),
18028
- onTry: (c) => {
18031
+ // pre.46:一次 → 0s / 3s / 8s 三次退避;全部失败才把原因写到卡片上。
18032
+ attempts: 3,
18033
+ backoff: [3000, 8000],
18034
+ onTry: (c, attempt, total) => {
18029
18035
  if (!alive) return;
18036
+ cards.heal(c.id, attempt, total);
18030
18037
  setNote({ ok: true, text: weT("下载已完成但没落地,正在自动收尾:{name}", { name: c.title || c.id }) });
18031
18038
  },
18032
18039
  onOk: (c) => {
18033
18040
  if (!alive) return;
18041
+ cards.healOk(c.id);
18034
18042
  setNote({ ok: true, text: weT("下载已完成,已自动收尾:{name}", { name: c.title || c.id }) });
18035
18043
  load(true);
18036
18044
  },
18037
18045
  onFail: (c, code) => {
18038
18046
  if (!alive) return;
18039
- cards.fail(c.id, code);
18047
+ cards.healFail(c.id, code);
18040
18048
  setNote({ ok: false, text: weT("自动收尾失败:{why}", { why: dlFailReason(code) }) });
18041
18049
  },
18042
18050
  }).catch(() => { /* dlHealStuck 内部已兜住 */ });
@@ -20086,19 +20094,23 @@ window.__ModuleLoader__.load({
20086
20094
  doneOf: (it) => Boolean(it.installed) || cards.okOf(it.id),
20087
20095
  path: "/skins/install",
20088
20096
  body: (it) => ({ id: it.id, url: it.url }),
20089
- onTry: (it) => {
20097
+ // pre.46:一次 → 0s / 3s / 8s 三次退避;全部失败才把原因写到卡片上。
20098
+ attempts: 3,
20099
+ backoff: [3000, 8000],
20100
+ onTry: (it, attempt, total) => {
20090
20101
  if (!alive) return;
20102
+ cards.heal(it.id, attempt, total);
20091
20103
  setNote({ ok: true, text: weT("下载已完成但没落地,正在自动补装:{name}", { name: it.title || it.id }) });
20092
20104
  },
20093
20105
  onOk: (it) => {
20094
20106
  if (!alive) return;
20095
- cards.markOk(it.id);
20107
+ cards.healOk(it.id);
20096
20108
  setNote({ ok: true, text: weT("下载已完成,已自动补装:{name} —— 点「应用」就能切换", { name: it.title || it.id }) });
20097
20109
  load(true);
20098
20110
  },
20099
20111
  onFail: (it, code) => {
20100
20112
  if (!alive) return;
20101
- cards.fail(it.id, code);
20113
+ cards.healFail(it.id, code);
20102
20114
  setNote({ ok: false, text: weT("自动补装失败:{why}", { why: dlFailReason(code) }) });
20103
20115
  },
20104
20116
  }).catch(() => { /* dlHealStuck 内部已兜住;这里只防未处理的 rejection */ });
@@ -24716,13 +24728,18 @@ window.__ModuleLoader__.load({
24716
24728
  }
24717
24729
 
24718
24730
  /**
24719
- * 挂载自愈**执行体**:对 `dlHealTargets()` 挑出来的条目各补打一次收尾请求。
24731
+ * 挂载自愈**执行体**:对 `dlHealTargets()` 挑出来的条目各补打收尾请求。
24720
24732
  *
24721
- * 约定(四个回调都由页签提供,本函数不认识组件、也不认识 React):
24733
+ * 约定(回调都由页签提供,本函数不认识组件、也不认识 React):
24722
24734
  * · `path` / `body(it)` 打哪个宿主接口、带什么体(三个模块各一条,都是幂等的);
24723
- * · `onTry(it)` 发出前(用来写"正在自动补装…"的提示与卡片 submitting);
24724
- * · `onOk(it)` 宿主明确回 2xx(页签据此 `cards.markOk()` + 重拉清单);
24725
- * · `onFail(it, code)` 失败(页签据此 `cards.fail()` **把原因写在卡片上**,不许静默)。
24735
+ * · `onTry(it, attempt, total)` 每次发出前(用来写「正在补收尾… 第 a/t 次」与卡片 healing);
24736
+ * · `onRetry(it, code, attempt, total)` 退避重试前(可选;默认没有额外动作);
24737
+ * · `onOk(it)` 宿主明确回 2xx(页签据此 `cards.healOk()` + 重拉清单);
24738
+ * · `onFail(it, code)` **全部 attempts 都失败**(页签据此 `cards.healFail()` 把原因写在卡片上)。
24739
+ *
24740
+ * pre.46:一次 → 带退避多次(调用方传 `attempts: 3, backoff: [3000, 8000]`)。
24741
+ * 默认仍是 1 次,保持既有调用点/判据的语义;`dlHealOnce` 仍按 `<kind>:<id>` 每次会话只领一次,
24742
+ * 所以“3 次”是**同一次挂载内**的退避重试,切页签不会无限重打。
24726
24743
  *
24727
24744
  * 绝不抛:任何一个模块/一张卡片失败都不该让别的卡片或整页挂掉。
24728
24745
  *
@@ -24735,21 +24752,41 @@ window.__ModuleLoader__.load({
24735
24752
  const targets = (() => {
24736
24753
  try { return dlHealTargets(o.jobs, kind, o.items, o.doneOf); } catch { return []; }
24737
24754
  })();
24755
+ const attempts = Math.max(1, Math.min(5, Number(o.attempts) || 1));
24756
+ const backoff = Array.isArray(o.backoff) ? o.backoff : [3000, 8000];
24757
+ const post = typeof o.post === "function" ? o.post : apiPostJson;
24758
+ const sleep = typeof o.sleep === "function"
24759
+ ? o.sleep
24760
+ : (ms) => new Promise((resolve) => { setTimeout(resolve, ms); });
24738
24761
  for (const it of targets) {
24739
24762
  if (!dlHealOnce(kind + ":" + it.id)) continue;
24740
24763
  tried.push(it);
24741
- try { if (typeof o.onTry === "function") o.onTry(it); } catch { /* 提示失败不影响补装 */ }
24742
24764
  /** 空串 = 成功;非空 = 宿主给的错误码(或兜底码)。 */
24743
- let code;
24744
- try {
24745
- const resp = await apiPostJson(String(o.path || ""), typeof o.body === "function" ? o.body(it) : (o.body || {}), { parse: "always" });
24746
- const data = (resp && resp.data) || null;
24747
- // 宿主回 `{ ok:false, error }` 时把**它的**错误码带出去(比 `http-500` 有信息量)。
24748
- if (resp && resp.ok && data && data.ok === false) code = String(data.error || "failed");
24749
- else if (!(resp && resp.ok)) code = String((data && data.error) || ("http-" + ((resp && resp.status) || 0)));
24750
- else code = "";
24751
- } catch (e) {
24752
- code = /timeout|超时/i.test(String((e && e.message) || "")) ? "submit-timeout" : "network";
24765
+ let code = "";
24766
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
24767
+ if (attempt > 1) {
24768
+ const wait = Math.max(0, Number(backoff[attempt - 2]) || 0);
24769
+ try {
24770
+ if (typeof o.onRetry === "function") o.onRetry(it, code, attempt, attempts);
24771
+ } catch { /* 重试提示失败不影响补装 */ }
24772
+ if (wait > 0) {
24773
+ // eslint-disable-next-line no-await-in-loop -- 退避本来就是按 attempt 串行等待
24774
+ try { await sleep(wait); } catch { /* 定时器失败就立刻重试 */ }
24775
+ }
24776
+ }
24777
+ try { if (typeof o.onTry === "function") o.onTry(it, attempt, attempts); } catch { /* 提示失败不影响补装 */ }
24778
+ code = "";
24779
+ try {
24780
+ const resp = await post(String(o.path || ""), typeof o.body === "function" ? o.body(it) : (o.body || {}), { parse: "always" });
24781
+ const data = (resp && resp.data) || null;
24782
+ // 宿主回 `{ ok:false, error }` 时把**它的**错误码带出去(比 `http-500` 有信息量)。
24783
+ if (resp && resp.ok && data && data.ok === false) code = String(data.error || "failed");
24784
+ else if (!(resp && resp.ok)) code = String((data && data.error) || ("http-" + ((resp && resp.status) || 0)));
24785
+ else code = "";
24786
+ } catch (e) {
24787
+ code = /timeout|超时/i.test(String((e && e.message) || "")) ? "submit-timeout" : "network";
24788
+ }
24789
+ if (!code) break;
24753
24790
  }
24754
24791
  try {
24755
24792
  if (code) { if (typeof o.onFail === "function") o.onFail(it, code); }
@@ -24827,7 +24864,7 @@ window.__ModuleLoader__.load({
24827
24864
  */
24828
24865
  const DL_PHASES = {
24829
24866
  IDLE: "idle", SUBMITTING: "submitting", QUEUED: "queued",
24830
- RUNNING: "running", INSTALLING: "installing", DONE: "done", FAILED: "failed",
24867
+ RUNNING: "running", INSTALLING: "installing", HEALING: "healing", DONE: "done", FAILED: "failed",
24831
24868
  };
24832
24869
 
24833
24870
  /** 提交请求的宽容窗口:超过它还没返回 ⇒ 按「提交超时」失败并给「重试」,不让卡片永远停在提交中。
@@ -25078,6 +25115,21 @@ window.__ModuleLoader__.load({
25078
25115
  // 而"我们刚试过、宿主明确回了错"比"队列说 done"更具体,所以它优先。
25079
25116
  // 它不盖正常路径:`begin()`(用户点下去)会清掉这条失败,`markOk()` 让卡片直接变 done。
25080
25117
  if (o.err && o.err.code) return fail(o.err.code);
25118
+ // ②c pre.46:**正在补收尾**(挂载自愈的 3 次退避重试期间)。
25119
+ //
25120
+ // 必须排在 ③ 之前:否则卡片会先显示「解压/落位中…」,用户只能干等;
25121
+ // 而自愈其实已经在打幂等的 `/boot/download` / `/skins/install`。
25122
+ // 失败后 `healFail` 会清掉这一格并写 `err` ⇒ 落在 ②b 的红字 +「重试」。
25123
+ if (o.heal && String(o.heal.id || "") === String(o.id || "")) {
25124
+ const attempt = Math.max(1, Number(o.heal.attempt) || 1);
25125
+ const total = Math.max(1, Number(o.heal.total) || 3);
25126
+ return make(
25127
+ DL_PHASES.HEALING,
25128
+ weT("正在补收尾…"),
25129
+ weT("第 {a}/{t} 次 · 下载已完成,正在补落地", { a: attempt, t: total }),
25130
+ true, false, "",
25131
+ );
25132
+ }
25081
25133
  // ③ 包下完了、还没落地:宿主正在解压 / 规范化清单 / 写目录。
25082
25134
  //
25083
25135
  // ⚠️ 4.23.6:这一格**必须有上界**(老实现无条件映射成 installing:disabled、retry=false、
@@ -25805,6 +25857,8 @@ window.__ModuleLoader__.load({
25805
25857
  const [sub, setSub] = React.useState(null);
25806
25858
  const [errs, setErrs] = React.useState({});
25807
25859
  const [okIds, setOkIds] = React.useState({});
25860
+ /** pre.46:正在挂载自愈的卡片 `id → { attempt, total, at }`(卡片显示「正在补收尾…」)。 */
25861
+ const [heals, setHeals] = React.useState({});
25808
25862
  const [eta, setEta] = React.useState({});
25809
25863
  const [nowMs, setNowMs] = React.useState(() => Date.now());
25810
25864
  const samplesRef = React.useRef(new Map());
@@ -25953,6 +26007,53 @@ window.__ModuleLoader__.load({
25953
26007
  * 而不是静默回到「安装」——那正是"点了没反应"的另一种样子。
25954
26008
  */
25955
26009
  markOk: (id) => { setOkIds((m) => (m[key(id)] ? m : { ...m, [key(id)]: true })); },
26010
+ /**
26011
+ * pre.46:挂载自愈进行中 —— 卡片显示「正在补收尾…」而不是「解压/落位中…」。
26012
+ * 每次重试都更新 attempt/total,用户能看到“第 2/3 次”。
26013
+ */
26014
+ heal: (id, attempt, total) => {
26015
+ const k = key(id);
26016
+ setHeals((m) => ({ ...m, [k]: { attempt: Math.max(1, Number(attempt) || 1), total: Math.max(1, Number(total) || 3), at: Date.now() } }));
26017
+ // 新一轮补收尾 ⇒ 清掉上一轮的失败红字(失败会由 healFail 重新写)
26018
+ setErrs((m) => {
26019
+ if (!Object.prototype.hasOwnProperty.call(m, k)) return m;
26020
+ const n = { ...m };
26021
+ delete n[k];
26022
+ return n;
26023
+ });
26024
+ },
26025
+ healEnd: (id) => {
26026
+ const k = key(id);
26027
+ setHeals((m) => {
26028
+ if (!Object.prototype.hasOwnProperty.call(m, k)) return m;
26029
+ const n = { ...m };
26030
+ delete n[k];
26031
+ return n;
26032
+ });
26033
+ },
26034
+ /** 补收尾成功:清 healing + 标记已装(皮肤页签据此立刻变 done)。 */
26035
+ healOk: (id) => {
26036
+ const k = key(id);
26037
+ setHeals((m) => {
26038
+ if (!Object.prototype.hasOwnProperty.call(m, k)) return m;
26039
+ const n = { ...m };
26040
+ delete n[k];
26041
+ return n;
26042
+ });
26043
+ setOkIds((m) => (m[k] ? m : { ...m, [k]: true }));
26044
+ },
26045
+ /** 3 次都失败:清 healing + 写失败原因(卡片红字 +「重试」)。 */
26046
+ healFail: (id, code) => {
26047
+ const k = key(id);
26048
+ setHeals((m) => {
26049
+ if (!Object.prototype.hasOwnProperty.call(m, k)) return m;
26050
+ const n = { ...m };
26051
+ delete n[k];
26052
+ return n;
26053
+ });
26054
+ setErrs((m) => ({ ...m, [k]: { code: String(code == null ? "failed" : code) } }));
26055
+ },
26056
+ healOf: (id) => heals[key(id)] || null,
25956
26057
  // 卸载成功后必须把它忘掉:否则卡片会一直按"已安装"渲染(站点已删、徽标还在)。
25957
26058
  clearOk: (id) => {
25958
26059
  const k = key(id);
@@ -25976,7 +26077,8 @@ window.__ModuleLoader__.load({
25976
26077
  const since = stallOf(x.id, x.job, x.done);
25977
26078
  const st = dlCardState({
25978
26079
  id: x.id, job: x.job, done: x.done, labels: x.labels,
25979
- sub: api.subOf(x.id), err: api.errOf(x.id), etaSec: api.etaOf(x.job), nowMs,
26080
+ sub: api.subOf(x.id), err: api.errOf(x.id), heal: api.healOf(x.id),
26081
+ etaSec: api.etaOf(x.job), nowMs,
25980
26082
  installStallMs: stallMs, installingSince: since,
25981
26083
  });
25982
26084
  // 已经判过超时 ⇒ 标记 expired:秒表停转(不空转),卡片保持 failed +「重试」。
@@ -1333,6 +1333,17 @@ const roots = [
1333
1333
  /* ── 朗读(P1):合成 / 停止 / 状态 / 工作联动 ─────────────────────────────── */
1334
1334
 
1335
1335
  const TTS_UNAVAILABLE_HINT = '本机语音合成不可用(系统语音与 Edge 系统音色都失败了)';
1336
+ /** 最近一次 /tts 的真实结果(/tts/state 与排障用;不参与缓存)。 */
1337
+ let lastTts = null;
1338
+
1339
+ /** 响应头只允许 latin1 ⇒ JSON/中文统一 URI 编码;过长截断,避免头被服务器拒绝。 */
1340
+ function ttsHeaderValue(value) {
1341
+ try {
1342
+ return encodeURIComponent(typeof value === 'string' ? value : JSON.stringify(value)).slice(0, 1200);
1343
+ } catch {
1344
+ return '';
1345
+ }
1346
+ }
1336
1347
 
1337
1348
  function jsonSend(res, payload, status = 200) {
1338
1349
  res.statusCode = status;
@@ -1383,24 +1394,43 @@ const roots = [
1383
1394
  } catch (error) {
1384
1395
  result = { ok: false, code: 'tts-unavailable', error: String((error && error.message) || error) };
1385
1396
  }
1397
+ const requestedVoice = String((result && result.requestedVoice) || voice || '');
1386
1398
  if (!result || result.ok !== true) {
1387
1399
  const code = (result && result.code) || 'tts-unavailable';
1388
1400
  const status = code === 'tts-stopped' ? 409 : (code === 'empty-text' ? 400 : 503);
1401
+ const attempts = (result && result.attempts) || [];
1402
+ lastTts = { requestedVoice, actualVoice: null, engine: null, attempts, code, at: Date.now() };
1389
1403
  jsonSend(res, {
1390
1404
  ok: false,
1391
1405
  code,
1406
+ requestedVoice,
1407
+ actualVoice: null,
1408
+ engine: null,
1392
1409
  hint: (result && result.hint) || (code === 'tts-stopped' ? '已停止' : TTS_UNAVAILABLE_HINT),
1393
- attempts: (result && result.attempts) || [],
1410
+ attempts,
1394
1411
  }, status);
1395
1412
  return;
1396
1413
  }
1414
+ const actualVoice = String(result.voice || '');
1415
+ const attempts = result.attempts || [];
1416
+ lastTts = {
1417
+ requestedVoice,
1418
+ actualVoice,
1419
+ engine: String(result.engine || 'system'),
1420
+ attempts,
1421
+ code: null,
1422
+ cached: Boolean(result.cached),
1423
+ at: Date.now(),
1424
+ };
1397
1425
  res.statusCode = 200;
1398
1426
  res.setHeader('Content-Type', 'audio/wav');
1399
1427
  res.setHeader('Content-Length', String(result.wav.length));
1400
1428
  res.setHeader('Cache-Control', 'no-store');
1401
1429
  res.setHeader('X-Folia-TTS-Engine', String(result.engine || 'system'));
1402
1430
  // 响应头必须是 latin1;音色名做一次 URI 编码,客户端 decodeURIComponent 还原
1403
- res.setHeader('X-Folia-TTS-Voice', encodeURIComponent(String(result.voice || '')));
1431
+ res.setHeader('X-Folia-TTS-Voice', encodeURIComponent(actualVoice));
1432
+ res.setHeader('X-Folia-TTS-Requested-Voice', ttsHeaderValue(requestedVoice));
1433
+ res.setHeader('X-Folia-TTS-Attempts', ttsHeaderValue(attempts));
1404
1434
  res.setHeader('X-Folia-TTS-Ms', String(Number(result.ms) || 0));
1405
1435
  res.setHeader('X-Folia-TTS-Cached', result.cached ? '1' : '0');
1406
1436
  res.end(result.wav);
@@ -1420,6 +1450,13 @@ const roots = [
1420
1450
  ok: true,
1421
1451
  ...status,
1422
1452
  voice: config.voice,
1453
+ // pre.46:把“用户要的音色 / 上次实际用的音色 / 引擎 / 每跳原因”一起回,
1454
+ // 排障时不用再猜为什么设置没生效。
1455
+ requestedVoice: String((config.voice && config.voice.name) || ''),
1456
+ actualVoice: lastTts ? lastTts.actualVoice : null,
1457
+ engine: lastTts ? lastTts.engine : null,
1458
+ attempts: lastTts ? lastTts.attempts : [],
1459
+ lastTts,
1423
1460
  maxChars: TTS_MAX_CHARS,
1424
1461
  clients: speakClients.size,
1425
1462
  });
@@ -42,6 +42,32 @@ const readline = require('node:readline');
42
42
  /** 合成链的顺序(单一真源;服务端缓存/判据都读它)。 */
43
43
  const ENGINES = Object.freeze(['sapi', 'edge']);
44
44
 
45
+ /**
46
+ * Edge / WinRT 的音色命名(例:`zh-CN-XiaoxiaoNeural`)。
47
+ * 这种名字**只存在于 Edge/OneCore 目录**,SAPI 一定没有 ⇒ 必须把 edge 排到第一跳,
48
+ * 否则 SAPI 找不到时会回落到 Huihui 并"成功",用户的音色设置永远不生效。
49
+ */
50
+ const NEURAL_VOICE_RE = /^[a-z]{2}-[A-Z]{2}-[A-Za-z0-9]+Neural$/;
51
+
52
+ function isNeuralVoice(voice) {
53
+ return NEURAL_VOICE_RE.test(String(voice == null ? '' : voice).trim());
54
+ }
55
+
56
+ /**
57
+ * 按用户指定的音色决定引擎顺序:
58
+ * · 空 / SAPI 风格名(`Microsoft Xxx Desktop` …)⇒ 默认 `['sapi','edge']`
59
+ * · Edge 风格 neural 名 ⇒ `['edge','sapi']`
60
+ * `engines` 参数只是"允许的子集"(判据/强制单引擎用),不会把顺序倒回去;
61
+ * 指定音色在某个引擎里不存在时由脚本 `throw voice-not-found`,**不许**静默用默认音色成功。
62
+ */
63
+ function engineOrderForVoice(voice, engines) {
64
+ const base = (Array.isArray(engines) && engines.length ? engines : ENGINES)
65
+ .filter((engine) => engine === 'sapi' || engine === 'edge');
66
+ const list = base.length ? base : ENGINES.slice();
67
+ if (!isNeuralVoice(voice)) return list;
68
+ return [...list].sort((a, b) => (a === 'edge' ? 0 : 1) - (b === 'edge' ? 0 : 1));
69
+ }
70
+
45
71
  /** 单句字数上限(与路由一致;多出来的截掉而不是报错)。 */
46
72
  const MAX_TEXT_CHARS = 240;
47
73
 
@@ -83,6 +109,26 @@ function validateWav(file) {
83
109
  }
84
110
  }
85
111
 
112
+ /**
113
+ * PowerShell 的 stderr → 一条人能读的原因。
114
+ *
115
+ * `throw 'voice-not-found: <name>'` 在 Windows PowerShell 5.1 里会把
116
+ * “CategoryInfo / FullyQualifiedErrorId / 抛出的源码行”整段打出来;原样塞进 attempts
117
+ * 会是一屏 `+ [string]$cfg.voice) }`。这里只取 `FullyQualifiedErrorId` 那一行
118
+ * (最干净、包含音色名),否则取 CategoryInfo 的括号内容,再否则取最后一行。
119
+ */
120
+ function cleanEngineError(stderr) {
121
+ const text = String(stderr || '');
122
+ const fq = /FullyQualifiedErrorId\s*:\s*([^\r\n]+)/i.exec(text);
123
+ if (fq && /voice-not-found/i.test(fq[1])) return fq[1].trim();
124
+ const vn = /voice-not-found:\s*([A-Za-z0-9 ._-]+)/i.exec(text);
125
+ if (vn) return 'voice-not-found: ' + vn[1].trim();
126
+ const cat = /CategoryInfo\s*:\s*[^:]+:\s*\(([^)]*)\)/.exec(text);
127
+ if (cat) return cat[1].trim().slice(0, 200);
128
+ const lines = text.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
129
+ return (lines[lines.length - 1] || 'synthesis-failed').slice(0, 200);
130
+ }
131
+
86
132
  /* ── PowerShell 脚本(ASCII;中文只经 JSON 文件)────────────────────────────── */
87
133
 
88
134
  /** SAPI:System.Speech 的桌面音色。 */
@@ -94,16 +140,22 @@ $cfg = Get-Content -Raw -Encoding UTF8 $Req | ConvertFrom-Json
94
140
  $synth = New-Object System.Speech.Synthesis.SpeechSynthesizer
95
141
  try {
96
142
  $picked = ''
97
- # Always resolve an actual voice: exact request name, then zh-CN default, then any.
98
- # stdout prints 'OK <name>' so the caller reports the REAL voice (SAPI and Edge
99
- # have different voice catalogs; the requested name may belong to the other one).
143
+ # An explicit voice MUST exist in this engine's catalog. Do not silently fall
144
+ # back to the system default: the caller reports this attempt as failed and
145
+ # tries the next engine (the voice may belong to the Edge/OneCore catalog).
146
+ # stdout prints 'OK <name>' so callers report the REAL voice.
100
147
  $voices = @($synth.GetInstalledVoices() | Where-Object { $_.Enabled } | ForEach-Object { $_.VoiceInfo })
101
- $match = $null
102
- if ($cfg.voice) { $match = $voices | Where-Object { $_.Name -eq [string]$cfg.voice } | Select-Object -First 1 }
103
- if (-not $match) { $match = $voices | Where-Object { $_.Culture.Name -eq 'zh-CN' } | Select-Object -First 1 }
104
- if (-not $match) { $match = $voices | Where-Object { $_.Culture.Name -like 'zh*' } | Select-Object -First 1 }
105
- if (-not $match) { $match = $voices | Select-Object -First 1 }
106
- if ($match) { $synth.SelectVoice($match.Name); $picked = $match.Name }
148
+ if ($cfg.voice) {
149
+ $match = $voices | Where-Object { $_.Name -eq [string]$cfg.voice } | Select-Object -First 1
150
+ if (-not $match) { throw ('voice-not-found: ' + [string]$cfg.voice) }
151
+ $synth.SelectVoice($match.Name)
152
+ $picked = $match.Name
153
+ } else {
154
+ $match = $voices | Where-Object { $_.Culture.Name -eq 'zh-CN' } | Select-Object -First 1
155
+ if (-not $match) { $match = $voices | Where-Object { $_.Culture.Name -like 'zh*' } | Select-Object -First 1 }
156
+ if (-not $match) { $match = $voices | Select-Object -First 1 }
157
+ if ($match) { $synth.SelectVoice($match.Name); $picked = $match.Name }
158
+ }
107
159
  $rate = 0
108
160
  if ($null -ne $cfg.rate) { $rate = [int][math]::Max(-10, [math]::Min(10, [double]$cfg.rate)) }
109
161
  $synth.Rate = $rate
@@ -141,15 +193,17 @@ $cfg = Get-Content -Raw -Encoding UTF8 $Req | ConvertFrom-Json
141
193
  $synth = New-Object Windows.Media.SpeechSynthesis.SpeechSynthesizer
142
194
  try {
143
195
  $picked = ''
196
+ # Same rule as SAPI: an explicit voice must exist in this engine's catalog;
197
+ # otherwise fail this attempt (the caller falls through to the next engine).
198
+ $voices = [Windows.Media.SpeechSynthesis.SpeechSynthesizer]::AllVoices
144
199
  if ($cfg.voice) {
145
- $voices = [Windows.Media.SpeechSynthesis.SpeechSynthesizer]::AllVoices
146
200
  $match = $voices | Where-Object { $_.DisplayName -eq [string]$cfg.voice -or $_.Id -eq [string]$cfg.voice } | Select-Object -First 1
147
- if (-not $match) { $match = $voices | Where-Object { $_.Language -like 'zh*' } | Select-Object -First 1 }
148
- if (-not $match) { $match = $voices | Select-Object -First 1 }
149
- if ($match) { $synth.Voice = $match; $picked = $match.DisplayName }
201
+ if (-not $match) { throw ('voice-not-found: ' + [string]$cfg.voice) }
202
+ $synth.Voice = $match
203
+ $picked = $match.DisplayName
150
204
  } else {
151
- $match = [Windows.Media.SpeechSynthesis.SpeechSynthesizer]::AllVoices | Where-Object { $_.Language -like 'zh*' } | Select-Object -First 1
152
- if (-not $match) { $match = [Windows.Media.SpeechSynthesis.SpeechSynthesizer]::AllVoices | Select-Object -First 1 }
205
+ $match = $voices | Where-Object { $_.Language -like 'zh*' } | Select-Object -First 1
206
+ if (-not $match) { $match = $voices | Select-Object -First 1 }
153
207
  if ($match) { $synth.Voice = $match; $picked = $match.DisplayName }
154
208
  }
155
209
  $rate = 0
@@ -266,12 +320,11 @@ async function runEngine(engine, text, options, deps) {
266
320
  }
267
321
  const wav = result.ok ? validateWav(outFile) : { ok: false, error: 'powershell-exit-' + result.code };
268
322
  if (!wav.ok) {
269
- let stderr = String(result.stderr || '').trim();
270
- if (stderr.length > 300) stderr = stderr.slice(-300);
323
+ const reason = result.ok ? (wav.error || 'synthesis-failed') : cleanEngineError(result.stderr);
271
324
  try { fs.unlinkSync(outFile); } catch { /* ignore */ }
272
325
  return {
273
326
  ok: false,
274
- error: stderr || wav.error || 'synthesis-failed',
327
+ error: String(reason || 'synthesis-failed').slice(0, 300),
275
328
  engine,
276
329
  ms: Date.now() - started,
277
330
  };
@@ -311,8 +364,10 @@ function runEdgeEngine(text, options, deps) {
311
364
  async function synthesizeOnce(text, options = {}, deps = {}) {
312
365
  const clean = String(text == null ? '' : text).trim().slice(0, MAX_TEXT_CHARS);
313
366
  if (!clean) return { ok: false, code: 'empty-text', error: 'empty-text', attempts: [] };
314
- const engines = (Array.isArray(options.engines) ? options.engines : ENGINES)
315
- .filter((engine) => engine === 'sapi' || engine === 'edge');
367
+ const requestedVoice = String(options.voice == null ? '' : options.voice).trim();
368
+ // 音色 → 引擎顺序:neural 名先走 edge;SAPI 名/空先走 sapi。显式音色在某一跳不存在时
369
+ // 脚本会 `voice-not-found`,这里记一次 attempt 后继续下一跳,绝不当成“用默认音色成功”。
370
+ const engines = engineOrderForVoice(requestedVoice, options.engines);
316
371
  const runSapi = typeof deps.runSapi === 'function' ? deps.runSapi : runSapiEngine;
317
372
  const runEdge = typeof deps.runEdge === 'function' ? deps.runEdge : runEdgeEngine;
318
373
  const attempts = [];
@@ -331,7 +386,8 @@ async function synthesizeOnce(text, options = {}, deps = {}) {
331
386
  engine,
332
387
  file: jumped.file,
333
388
  bytes: valid.bytes,
334
- voice: String(jumped.voice || options.voice || ''),
389
+ voice: String(jumped.voice || requestedVoice || ''),
390
+ requestedVoice,
335
391
  ms: Number(jumped.ms) || 0,
336
392
  attempts,
337
393
  };
@@ -346,7 +402,10 @@ async function synthesizeOnce(text, options = {}, deps = {}) {
346
402
  code: 'tts-unavailable',
347
403
  error: attempts.map((item) => item.engine + ': ' + item.error).join(' | '),
348
404
  attempts,
349
- hint: '本机语音合成不可用:系统语音(SAPI)和 Edge 系统音色都没出声。',
405
+ requestedVoice,
406
+ hint: requestedVoice
407
+ ? '本机没有这个音色(已依次尝试 ' + engines.join(' → ') + '),换一个音色或把音色留空。'
408
+ : '本机语音合成不可用:系统语音(SAPI)和 Edge 系统音色都没出声。',
350
409
  };
351
410
  }
352
411
 
@@ -465,6 +524,9 @@ module.exports = {
465
524
  ENGINES,
466
525
  MAX_TEXT_CHARS,
467
526
  ENGINE_TIMEOUT_MS,
527
+ NEURAL_VOICE_RE,
528
+ isNeuralVoice,
529
+ engineOrderForVoice,
468
530
  powershellPath,
469
531
  validateWav,
470
532
  runSapiEngine,
package/lib/tts/tts.js CHANGED
@@ -27,6 +27,26 @@ export const TTS_MAX_CHARS = 240;
27
27
  /** 合成链(与 worker 的 ENGINES 对齐;路由状态里会回给界面)。 */
28
28
  export const TTS_ENGINES = Object.freeze(['sapi', 'edge']);
29
29
 
30
+ /** Edge / WinRT 音色命名(`zh-CN-XiaoxiaoNeural`)—— 这类名字只存在于 Edge 目录。 */
31
+ export const NEURAL_VOICE_RE = /^[a-z]{2}-[A-Z]{2}-[A-Za-z0-9]+Neural$/;
32
+
33
+ export function isNeuralVoice(voice) {
34
+ return NEURAL_VOICE_RE.test(String(voice == null ? '' : voice).trim());
35
+ }
36
+
37
+ /** 用户音色 → 首选引擎(缓存 key 与路由状态都用它;实际引擎仍以合成结果为准)。 */
38
+ export function preferredEngineForVoice(voice) {
39
+ return isNeuralVoice(voice) ? 'edge' : 'sapi';
40
+ }
41
+
42
+ /**
43
+ * 缓存 key 的**唯一实现**(判据直接喂它做负对照)。
44
+ * 必须带 `engine`:同一句话用 SAPI 与 Edge 得到的是**不同音色**,不加引擎会互相命中。
45
+ */
46
+ export function ttsCacheKey(engine, voice, rate, text) {
47
+ return sha256('v1|' + String(engine || '') + '|' + String(voice || '') + '|' + normalizeTtsRate(rate) + '|' + normalizeTtsText(text));
48
+ }
49
+
30
50
  const WORKER_FILE = fileURLToPath(new URL('./tts-worker.cjs', import.meta.url));
31
51
 
32
52
  /** 去掉控制字符、折叠空白;超过上限截断(路由已先做一次,这里是兜底)。 */
@@ -189,7 +209,7 @@ export function createTtsService(options = {}) {
189
209
  return { wav: join(cacheDir, key + '.wav'), meta: join(cacheDir, key + '.json') };
190
210
  }
191
211
 
192
- function readCache(key) {
212
+ function readCache(key, requestedVoice) {
193
213
  const { wav, meta } = cachePaths(key);
194
214
  try {
195
215
  if (!existsSync(wav)) return null;
@@ -198,11 +218,23 @@ export function createTtsService(options = {}) {
198
218
  const bytes = readFileSync(wav);
199
219
  let info = {};
200
220
  try { info = JSON.parse(readFileSync(meta, 'utf8')); } catch { info = {}; }
221
+ const wantVoice = String(requestedVoice || '').trim().toLowerCase();
222
+ const gotVoice = String(info.voice || '').trim().toLowerCase();
223
+ // 用户明确指定了音色 ⇒ 缓存里的**实际音色**必须就是它;否则这是修复前留下的
224
+ // “回落到 Huihui 却按成功缓存”的旧条目 —— 不许复用,删掉让本轮重新合成。
225
+ if (wantVoice && gotVoice && wantVoice !== gotVoice) {
226
+ try { unlinkSync(wav); } catch { /* ignore */ }
227
+ try { unlinkSync(meta); } catch { /* ignore */ }
228
+ return null;
229
+ }
230
+ if (wantVoice && !gotVoice) return null;
201
231
  return {
202
232
  ok: true,
203
233
  wav: bytes,
204
234
  engine: info.engine || 'cache',
205
235
  voice: info.voice || '',
236
+ requestedVoice: info.requestedVoice || String(requestedVoice || ''),
237
+ attempts: [],
206
238
  ms: 0,
207
239
  cached: true,
208
240
  bytes: bytes.length,
@@ -260,8 +292,14 @@ export function createTtsService(options = {}) {
260
292
  if (!clean) return { ok: false, code: 'empty-text', hint: '没有要读的文字' };
261
293
  const voice = String(speech.voice || '').trim().slice(0, 120);
262
294
  const rate = normalizeTtsRate(speech.rate);
263
- const key = sha256('v1|' + voice + '|' + rate + '|' + clean);
264
- const cached = readCache(key);
295
+ const engines = Array.isArray(speech.engines)
296
+ ? speech.engines.filter((engine) => engine === 'sapi' || engine === 'edge')
297
+ : null;
298
+ // 缓存 key 带**引擎**:neural 音色路由到 edge,SAPI 音色/空路由到 sapi;
299
+ // 同一句话在两条引擎下是不同音色,绝不允许互相命中(pre.45 的实际缺陷)。
300
+ const engineTag = engines && engines.length ? engines.join('+') : preferredEngineForVoice(voice);
301
+ const key = ttsCacheKey(engineTag, voice, rate, clean);
302
+ const cached = readCache(key, voice);
265
303
  if (cached) return cached;
266
304
 
267
305
  const gen = generation;
@@ -270,26 +308,34 @@ export function createTtsService(options = {}) {
270
308
  if (gen !== generation) return { ok: false, code: 'tts-stopped' };
271
309
  let msg;
272
310
  try {
273
- msg = await request({ text: clean, voice, rate });
311
+ msg = await request({
312
+ text: clean,
313
+ voice,
314
+ rate,
315
+ ...(engines && engines.length ? { engines } : {}),
316
+ });
274
317
  } catch (error) {
275
318
  const message = String((error && error.message) || error);
276
319
  return {
277
320
  ok: false,
278
321
  code: message === 'tts-timeout' ? 'tts-timeout' : 'tts-worker-failed',
279
322
  error: message,
323
+ requestedVoice: voice,
324
+ attempts: [],
280
325
  hint: message === 'tts-timeout' ? '语音合成超时,稍后再试' : '语音合成进程没起来',
281
326
  };
282
327
  }
283
328
  // 关键:stop 之后回来的结果一律丢弃(客户端已经停了,不能再补一句)
284
329
  if (gen !== generation) {
285
330
  if (msg && msg.file) { try { rmSync(msg.file, { force: true }); } catch { /* ignore */ } }
286
- return { ok: false, code: 'tts-stopped' };
331
+ return { ok: false, code: 'tts-stopped', requestedVoice: voice };
287
332
  }
288
333
  if (!msg || msg.ok !== true || !msg.file) {
289
334
  return {
290
335
  ok: false,
291
336
  code: (msg && msg.code) || 'tts-unavailable',
292
337
  error: (msg && msg.error) || 'tts-unavailable',
338
+ requestedVoice: voice,
293
339
  attempts: (msg && msg.attempts) || [],
294
340
  hint: (msg && msg.hint) || '本机语音合成不可用(系统语音与 Edge 系统音色都失败了)',
295
341
  };
@@ -298,20 +344,28 @@ export function createTtsService(options = {}) {
298
344
  try {
299
345
  wav = readFileSync(msg.file);
300
346
  } catch (error) {
301
- return { ok: false, code: 'tts-read-failed', error: String((error && error.message) || error) };
347
+ return { ok: false, code: 'tts-read-failed', error: String((error && error.message) || error), requestedVoice: voice };
302
348
  } finally {
303
349
  try { rmSync(msg.file, { force: true }); } catch { /* ignore */ }
304
350
  }
305
351
  if (!wav || wav.length < 1024 || wav.toString('ascii', 0, 4) !== 'RIFF') {
306
- return { ok: false, code: 'tts-bad-wav', error: 'worker 返回的不是有效 WAV' };
352
+ return { ok: false, code: 'tts-bad-wav', error: 'worker 返回的不是有效 WAV', requestedVoice: voice };
307
353
  }
308
- const info = { engine: msg.engine || 'system', voice: msg.voice || voice, rate, text: clean };
354
+ const info = {
355
+ engine: msg.engine || 'system',
356
+ voice: msg.voice || voice,
357
+ requestedVoice: voice,
358
+ rate,
359
+ text: clean,
360
+ };
309
361
  writeCache(key, wav, info);
310
362
  return {
311
363
  ok: true,
312
364
  wav,
313
365
  engine: info.engine,
314
366
  voice: info.voice,
367
+ requestedVoice: info.requestedVoice,
368
+ attempts: (msg && msg.attempts) || [],
315
369
  ms: Number(msg.ms) || 0,
316
370
  cached: false,
317
371
  bytes: wav.length,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-folia",
3
- "version": "4.26.0-pre.45",
3
+ "version": "4.26.0-pre.46",
4
4
  "description": "DSH 壁纸引擎:本机 WE 壁纸实时渲染,视频/网页/开机动画/桌宠皮肤,一键拉取在线素材。",
5
5
  "type": "module",
6
6
  "engines": {