dsh-notify-say 0.5.3 → 0.5.7

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.
@@ -0,0 +1,238 @@
1
+ /**
2
+ * 音色回退的语言一致性(issue #1 回归)。
3
+ *
4
+ * ## 这条测试守的是什么
5
+ *
6
+ * issue #1(dustinmoon78,2026-10-25):用户在设置页选了**中文**音色
7
+ * `zh-clear-female`,而发布包只自带两个音色(日语 `zundamon-normal` +
8
+ * 中文 `zh-soft-female`)。原选曲链找不到指定音色时一路落到
9
+ * `sounds/master-voice.wav` —— 那文件与 `zundamon-normal.wav` 是同一个文件
10
+ * (sha256 相同),说的是「主人、任務完了です!」。
11
+ *
12
+ * 于是:用户明确点了中文,听到的是日语;而且**全程没有一行日志**,
13
+ * 用户只能凭耳朵发现"怎么变日语了",提 issue 时也拿不出证据。
14
+ *
15
+ * ## 修复后的契约(三段,逐条断言)
16
+ *
17
+ * ① **同语系优先**:点选的音色取不到时,先在同一个池里换一个**同语言**的音色,
18
+ * 再考虑任何跨语言的兜底。中文请求绝不该先嫁接到日语上。
19
+ * ② **不越池**:`fail` 仍然是 `fail` 池(不得跑到 done 池去播庆祝台词)——
20
+ * 这是 2026-10-17 那条更早的护栏,新逻辑不能把它弄破。
21
+ * ③ **留痕**:真的换了音色时,日志里必须有一行 `[voice-miss]`,
22
+ * 且 `-Preview` 的输出里带 `[voice-miss]` 标记。
23
+ *
24
+ * ## 为什么这里只用"发布包那套音色"来测
25
+ *
26
+ * 自用目录里 17 个音色全在,`zh-clear-female` 是**装了**的,那条代码路径根本
27
+ * 走不到(实测:自用目录下 `-Voice zh-clear-female` 直接选中它,不会回退)。
28
+ * 用户踩坑的是**发布包**。所以本文件用 `-VoiceRoot` 指向一个只含
29
+ * `zundamon-normal` + `zh-soft-female` 的临时根,复刻发布包形态。
30
+ *
31
+ * ⚠️ 不能用 `-Voice` 指向真实不存在的 key 来测语言回退:那种情况下
32
+ * `Get-VoiceLangOf` 只能按 `zh-` 前缀猜,虽然也能过,但**测不到**
33
+ * "用户点的是真实存在、只是没装的音色"这个真实场景。
34
+ *
35
+ * ⚠️ worktree 长路径:MCI 在 >130 字符的路径上 open 返回 304,
36
+ * 所以本文件**只断言 pick= 字符串**,不断言真的出声(同 fail-voice.test.mjs 的说明)。
37
+ *
38
+ * 运行:node --import ./test/test-env-setup.mjs --test test/voice-fallback.test.mjs
39
+ */
40
+ import { test } from 'node:test';
41
+ import assert from 'node:assert/strict';
42
+ import { spawnSync } from 'node:child_process';
43
+ import { cpSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, existsSync } from 'node:fs';
44
+ import { tmpdir } from 'node:os';
45
+ import { fileURLToPath } from 'node:url';
46
+ import { dirname, join } from 'node:path';
47
+
48
+ const HERE = dirname(fileURLToPath(import.meta.url));
49
+ const PLUGIN = join(HERE, '..');
50
+ const PS1 = join(PLUGIN, 'dsh-notify.ps1');
51
+ const REAL_SOUNDS = join(PLUGIN, 'sounds');
52
+
53
+ /** 发布包里真实存在的两个音色(见 release-build.ps1 的默认自带清单)。 */
54
+ const SHIPPED_JA = 'zundamon-normal';
55
+ const SHIPPED_ZH = 'zh-soft-female';
56
+ /** 自用目录有、发布包**没有**的中文音色 —— issue #1 里用户点的就是这个。 */
57
+ const NOT_SHIPPED_ZH = 'zh-clear-female';
58
+
59
+ /**
60
+ * 造一个"发布包形态"的语音根:只有 zundamon-normal 与 zh-soft-female 两族。
61
+ *
62
+ * 直接从真实 sounds 目录**按音色前缀复制**,不重新合成 —— 音频内容无关紧要,
63
+ * 本测试只断言"选中了哪个文件名"。
64
+ */
65
+ function makeShippedVoiceRoot() {
66
+ const root = mkdtempSync(join(tmpdir(), 'ns-shipped-'));
67
+ const dest = join(root, 'voice-lines');
68
+ mkdirSync(dest, { recursive: true });
69
+ for (const pool of ['', 'fail', 'question', 'approval']) {
70
+ const srcDir = pool ? join(REAL_SOUNDS, 'voice-lines', pool) : join(REAL_SOUNDS, 'voice-lines');
71
+ if (!existsSync(srcDir)) continue;
72
+ const outDir = pool ? join(dest, pool) : dest;
73
+ mkdirSync(outDir, { recursive: true });
74
+ for (const key of [SHIPPED_JA, SHIPPED_ZH]) {
75
+ // 该池里此音色的所有变体(<key>.wav 与 <key>~N.wav)
76
+ for (const f of readdirSync(srcDir)) {
77
+ if (!f.endsWith('.wav')) continue;
78
+ const base = f.replace(/~.*$/, '').replace(/\.wav$/, '');
79
+ if (base !== key) continue;
80
+ cpSync(join(srcDir, f), join(outDir, f));
81
+ }
82
+ }
83
+ }
84
+ return root;
85
+ }
86
+
87
+ /** 跑 ps1 -Preview,返回 stdout / stderr / exit code。用 spawnSync(见 fail-voice.test.mjs 踩坑③)。 */
88
+ function runPs1(args, logDir) {
89
+ const env = { ...process.env };
90
+ if (logDir) env.DSH_NOTIFY_SAY_LOG_DIR = logDir;
91
+ const r = spawnSync('powershell',
92
+ ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', PS1, ...args],
93
+ { encoding: 'utf8', timeout: 60_000, env });
94
+ return {
95
+ out: String(r.stdout || ''),
96
+ err: String(r.stderr || ''),
97
+ code: typeof r.status === 'number' ? r.status : 1,
98
+ };
99
+ }
100
+
101
+ /** 从输出里提取 pick=<name>。 */
102
+ function pickOf(out) {
103
+ const m = /pick=([^\s+]+)/.exec(out.replace('(静音)', ''));
104
+ return m ? m[1] : '';
105
+ }
106
+
107
+ /** 文件名 → 音色 key(去掉 ~N 变体后缀与 .wav)。 */
108
+ function keyOf(file) {
109
+ return file.replace(/~.*$/, '').replace(/\.wav$/, '');
110
+ }
111
+
112
+ /** 某音色 key 是否属于中文(与 ps1 / client.js 同一命名契约:zh- 前缀)。 */
113
+ function isZh(key) {
114
+ return key.startsWith('zh-');
115
+ }
116
+
117
+ // ── 1. 同语系回退:中文请求不该先落到日语 ──────────────────────────────────
118
+ test('F1: 发布包形态下点未安装的中文音色 → 退到**中文**已装音色,不是 master-voice', () => {
119
+ const root = makeShippedVoiceRoot();
120
+ try {
121
+ const { out, err, code } = runPs1(
122
+ ['-Kind', 'done', '-Preview', '-NoSound', '-Voice', NOT_SHIPPED_ZH, '-VoiceRoot', join(root, 'voice-lines'), '-Volume', '0'],
123
+ );
124
+ assert.equal(code, 0, `ps1 应正常退出;stderr=${err.slice(0, 300)}`);
125
+ const pick = pickOf(out);
126
+ assert.notEqual(pick, '', `应选到一个文件,实际输出=${out}`);
127
+ assert.equal(isZh(keyOf(pick)), true,
128
+ `点中文音色时应播中文,实际 pick=${pick}(master-voice 是日语「任務完了です」,正是 issue #1)`);
129
+ assert.notEqual(pick, 'master-voice.wav', '不得落到 master-voice.wav');
130
+ } finally {
131
+ rmSync(root, { recursive: true, force: true });
132
+ }
133
+ });
134
+
135
+ // ── 2. 四个 kind 都要覆盖(issue #1 只写了 done,实际四类都有)────────────────
136
+ for (const kind of ['done', 'question', 'approval', 'fail']) {
137
+ test(`F2-${kind}: -Kind ${kind} + 未安装中文音色 → 仍是中文(四类都不得跨语言)`, () => {
138
+ const root = makeShippedVoiceRoot();
139
+ try {
140
+ const { out, code } = runPs1(
141
+ ['-Kind', kind, '-Preview', '-NoSound', '-Voice', NOT_SHIPPED_ZH, '-VoiceRoot', join(root, 'voice-lines'), '-Volume', '0'],
142
+ );
143
+ assert.equal(code, 0, 'ps1 应正常退出');
144
+ const pick = pickOf(out);
145
+ assert.equal(isZh(keyOf(pick)), true,
146
+ `kind=${kind} 点中文却播了 ${pick};四类都必须同语系回退`);
147
+ } finally {
148
+ rmSync(root, { recursive: true, force: true });
149
+ }
150
+ });
151
+ }
152
+
153
+ // ── 3. 不越池:fail 不得跑到 done 池去播庆祝台词 ────────────────────────────
154
+ test('F3: fail 池缺该中文音色时,仍在 fail 池内换中文音色(不越到 done 池)', () => {
155
+ const root = makeShippedVoiceRoot();
156
+ try {
157
+ const { out, code } = runPs1(
158
+ ['-Kind', 'fail', '-Preview', '-NoSound', '-Voice', NOT_SHIPPED_ZH, '-VoiceRoot', join(root, 'voice-lines'), '-Volume', '0'],
159
+ );
160
+ assert.equal(code, 0, 'ps1 应正常退出');
161
+ const pick = pickOf(out);
162
+ // done 池根目录的 <key>.wav(无 ~N)是"任务完成"台词;fail 必须选带 ~N 的子池变体
163
+ assert.match(pick, /~\d+\.wav$/, `fail 必须留在 fail 池(~N 变体),实际 pick=${pick}`);
164
+ assert.doesNotMatch(pick, /master-voice/, 'fail 不得回落到 master-voice(语义相反)');
165
+ } finally {
166
+ rmSync(root, { recursive: true, force: true });
167
+ }
168
+ });
169
+
170
+ // ── 4. 留痕:换音色必须写 [voice-miss] ──────────────────────────────────────
171
+ test('F4: 真的换了音色时,日志写 [voice-miss] 且 Preview 输出带标记', () => {
172
+ const root = makeShippedVoiceRoot();
173
+ const logDir = mkdtempSync(join(tmpdir(), 'ns-miss-'));
174
+ try {
175
+ const { out, code } = runPs1(
176
+ ['-Kind', 'done', '-Preview', '-NoSound', '-Voice', NOT_SHIPPED_ZH, '-VoiceRoot', join(root, 'voice-lines'), '-Volume', '0'],
177
+ logDir,
178
+ );
179
+ assert.equal(code, 0, 'ps1 应正常退出');
180
+ assert.match(out, /\[voice-miss\]/, 'Preview 输出必须带 [voice-miss](用户当场就能看出换过音色)');
181
+ const logFile = join(logDir, 'notify.log');
182
+ assert.equal(existsSync(logFile), true, `日志文件必须存在:${logFile}`);
183
+ const log = readFileSync(logFile, 'utf8');
184
+ assert.match(log, /\[voice-miss\]/, '日志必须有一行 [voice-miss]');
185
+ assert.match(log, new RegExp(`requested=${NOT_SHIPPED_ZH}`),
186
+ '日志必须写明用户请求的是哪个音色');
187
+ } finally {
188
+ rmSync(root, { recursive: true, force: true });
189
+ rmSync(logDir, { recursive: true, force: true });
190
+ }
191
+ });
192
+
193
+ // ── 5. 没换音色时不得误报(否则日志会被噪声淹没,等于没留痕)────────────────
194
+ test('F5: 点的是已装音色 → 不写 [voice-miss](避免误报把留痕淹掉)', () => {
195
+ const root = makeShippedVoiceRoot();
196
+ const logDir = mkdtempSync(join(tmpdir(), 'ns-nomiss-'));
197
+ try {
198
+ const { out, code } = runPs1(
199
+ ['-Kind', 'done', '-Preview', '-NoSound', '-Voice', SHIPPED_ZH, '-VoiceRoot', join(root, 'voice-lines'), '-Volume', '0'],
200
+ logDir,
201
+ );
202
+ assert.equal(code, 0, 'ps1 应正常退出');
203
+ assert.equal(keyOf(pickOf(out)), SHIPPED_ZH, `应精确选中 ${SHIPPED_ZH},实际 ${pickOf(out)}`);
204
+ assert.doesNotMatch(out, /\[voice-miss\]/, '选中了请求的音色时不该报 miss');
205
+ const log = readFileSync(join(logDir, 'notify.log'), 'utf8');
206
+ assert.doesNotMatch(log, /\[voice-miss\]/, '选中了请求的音色时不该写 miss 日志');
207
+ } finally {
208
+ rmSync(root, { recursive: true, force: true });
209
+ rmSync(logDir, { recursive: true, force: true });
210
+ }
211
+ });
212
+
213
+ // ── 6. 反向:日语请求不该被送到中文去 ──────────────────────────────────────
214
+ test('F6: 点未安装的日语音色 → 退到日语已装音色,不是中文', () => {
215
+ const root = makeShippedVoiceRoot();
216
+ try {
217
+ const { out, code } = runPs1(
218
+ ['-Kind', 'done', '-Preview', '-NoSound', '-Voice', 'ameharu-hau', '-VoiceRoot', join(root, 'voice-lines'), '-Volume', '0'],
219
+ );
220
+ assert.equal(code, 0, 'ps1 应正常退出');
221
+ const pick = pickOf(out);
222
+ assert.equal(isZh(keyOf(pick)), false,
223
+ `点日语却播了中文 ${pick};同语系回退是双向的`);
224
+ } finally {
225
+ rmSync(root, { recursive: true, force: true });
226
+ }
227
+ });
228
+
229
+ // ── 7. 契约漂移守卫:ps1 与 client.js 必须用同一套语言判据 ──────────────────
230
+ test('F7: 语言判据在 ps1 与 client.js 之间不漂移(都按 zh- 前缀)', () => {
231
+ const ps1 = readFileSync(PS1, 'utf8');
232
+ // ps1 侧:Get-VoiceLangOf 必须按 zh- 前缀判,而不是维护第二份清单
233
+ assert.match(ps1, /function Get-VoiceLangOf/, 'ps1 必须有 Get-VoiceLangOf');
234
+ assert.match(ps1, /if \(\$Key -like 'zh-\*'\) \{ return 'zh' \}/,
235
+ 'Get-VoiceLangOf 必须按 zh- 前缀判中文(清单会漂移,前缀不会)');
236
+ // 同语系回退必须用**不退回未过滤**的那个取法
237
+ assert.match(ps1, /function Pick-RandomWavInLang/, 'ps1 必须有 Pick-RandomWavInLang');
238
+ });
@@ -0,0 +1,261 @@
1
+ /**
2
+ * 音色下拉候选 = 内置清单 ∪ 已下载 ∪ 当前值(v0.5.6,issue #3)。
3
+ *
4
+ * ## 这个 bug 是什么(用户 2026-10-25 报的)
5
+ *
6
+ * 设置页的「固定音色」下拉候选取自 `lib/client.js` 里一份**写死的**
7
+ * `VOICE_KEYS`(发行版内置清单)。用户后来在「语音包」区下载的音色
8
+ * 不在那份清单里 —— 于是下载成功了、列表里写着「已安装」,
9
+ * 音色下拉里却根本选不到它,等于白下。
10
+ *
11
+ * 连带发现第二个坑:`VOICE_KEYS` 漏登记了 `tohoku-zunko` / `tohoku-kiritan`
12
+ * 两个音色。它们早就通过了许可审核(`tools/build-voice-packs.ps1` 的
13
+ * `$Approved` 与 `docs/audio-audit/README.md` 的"当前可发布清单"里都有),
14
+ * 只是这份前端清单忘了写。
15
+ *
16
+ * ## 为什么必须渲染真实组件
17
+ *
18
+ * 第一版想写「源码里有 appendInstalled 调用」的文本断言。那种判据在两个
19
+ * 方向都会骗人:注释被改字就假红;调用被挪到不会执行的分支里却恒绿。
20
+ * 所以这里真跑一遍 `SettingsCard()`(假 React,与 ui-final.test.mjs 同款),
21
+ * 从渲染出来的 `<option>` 列表判断。
22
+ */
23
+ import { test } from 'node:test';
24
+ import assert from 'node:assert/strict';
25
+ import { readFileSync } from 'node:fs';
26
+ import { resolve, dirname, join } from 'node:path';
27
+ import { fileURLToPath } from 'node:url';
28
+
29
+ const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
30
+ const CLIENT = readFileSync(join(ROOT, 'lib', 'client.js'), 'utf8');
31
+
32
+ /** 够用的假 React(与 ui-final.test.mjs 同款:effect 只跑一次)。 */
33
+ function fakeReact() {
34
+ const createElement = (type, props, ...children) => ({
35
+ $$typeof: Symbol.for('react.element'),
36
+ type,
37
+ props: { ...(props || {}), children },
38
+ });
39
+ const hooks = { slots: [], index: 0, eff: 0, ranEff: new Set(), rerender: null };
40
+ const useState = (init) => {
41
+ const i = hooks.index++;
42
+ if (hooks.slots[i] === undefined) {
43
+ hooks.slots[i] = { value: typeof init === 'function' ? init() : init };
44
+ }
45
+ const slot = hooks.slots[i];
46
+ const set = (updater) => {
47
+ slot.value = typeof updater === 'function' ? updater(slot.value) : updater;
48
+ if (typeof hooks.rerender === 'function') hooks.rerender();
49
+ };
50
+ return [slot.value, set];
51
+ };
52
+ const useEffect = (fn) => {
53
+ const i = hooks.eff++;
54
+ if (hooks.ranEff.has(i)) return;
55
+ hooks.ranEff.add(i);
56
+ try { fn(); } catch { /* ignore */ }
57
+ };
58
+ const resetIndex = () => { hooks.index = 0; hooks.eff = 0; };
59
+ return { createElement, useState, useEffect, __hooks: hooks, __resetIndex: resetIndex };
60
+ }
61
+
62
+ const FULL = {
63
+ voice: true, voiceMode: 'fixed', voiceName: 'zundamon-normal', volume: 80,
64
+ voiceLang: 'ja', audioSource: 'bundled',
65
+ notifyOnComplete: true, notifyOnError: true, notifyOnBlocked: true,
66
+ notifyOnAborted: false, notifyOnApproval: true, notifyOnQuestion: true,
67
+ subagents: false, idleGate: true,
68
+ showToast: true, ttsVoice: '', ttsRate: 0, devReload: false,
69
+ logLevel: 'info', voiceGain: 2.0, normalizeCustomAudio: false,
70
+ jumpWhenBackground: true, jumpWhenForeground: false,
71
+ debounceSeconds: 60, globalCooldownSeconds: 0,
72
+ audioSourceByKind: {}, ttsTexts: {}, kindSystemSound: {}, kindVoiceName: {},
73
+ customFiles: {},
74
+ };
75
+
76
+ function elements(node, out) {
77
+ const acc = out || [];
78
+ if (!node || typeof node !== 'object') return acc;
79
+ if (Array.isArray(node)) { node.forEach((n) => elements(n, acc)); return acc; }
80
+ if (node.type) acc.push(node);
81
+ elements(node.props && node.props.children, acc);
82
+ return acc;
83
+ }
84
+
85
+ /** 主 state 槽(按形状找,不写死索引)。 */
86
+ function findMainSlot(card) {
87
+ const s = card.r.__hooks.slots.find(
88
+ (x) => x && x.value && typeof x.value === 'object'
89
+ && 'values' in x.value && 'loaded' in x.value,
90
+ );
91
+ if (!s) throw new Error('找不到主 state 槽');
92
+ return s;
93
+ }
94
+
95
+ /**
96
+ * 渲染设置卡。
97
+ *
98
+ * @param {{values?: object, installed?: string[]}} cfg host 的 /config 响应
99
+ */
100
+ async function renderCard(cfg) {
101
+ let captured = null;
102
+ // eslint-disable-next-line no-new-func
103
+ new Function('window', 'document', CLIENT)(
104
+ { __ModuleLoader__: { load(def) { captured = def; } }, addEventListener() {}, removeEventListener() {} },
105
+ undefined,
106
+ );
107
+ if (!captured) throw new Error('client.js 没有注册');
108
+
109
+ const r = fakeReact();
110
+ const mod = captured.factory((id) => {
111
+ if (id === 'react') return r;
112
+ throw new Error('client 不应 require: ' + id);
113
+ });
114
+
115
+ let component = null;
116
+ mod.apply({
117
+ get(id) {
118
+ if (id === 'slots') return { inject(_n, fn) { fn(); }, register(_m, c) { component = c; } };
119
+ return undefined;
120
+ },
121
+ });
122
+ if (!component) throw new Error('没有注册设置卡');
123
+
124
+ globalThis.fetch = (url) => {
125
+ const u = String(url);
126
+ const body = u.includes('version')
127
+ ? {
128
+ ok: true, running: '0.5.6', installed: '0.5.6', latest: '0.5.6',
129
+ hasUpdate: false, needsRestart: false, npmLatest: '0.5.6',
130
+ githubLatest: '0.5.6', installMode: 'managed', changelogUrl: 'x',
131
+ }
132
+ // /config:这是 issue #3 的关键 —— installed 跟着生效值一起来
133
+ : { ok: true, values: { ...FULL, ...((cfg && cfg.values) || {}) }, installed: (cfg && cfg.installed) || [] };
134
+ return Promise.resolve({
135
+ ok: true, status: 200, json: () => Promise.resolve(body),
136
+ });
137
+ };
138
+
139
+ const render = () => { r.__resetIndex(); return component({}); };
140
+ render();
141
+ r.__hooks.rerender = render;
142
+ for (let i = 0; i < 8; i++) await Promise.resolve();
143
+ return { r, render, installed: (cfg && cfg.installed) || [] };
144
+ }
145
+
146
+ /**
147
+ * 内置清单(从源码解析)+ 本次注入的已下载 key = "什么算音色候选"。
148
+ *
149
+ * 为什么不能靠"候选值全是小写字母"来识别音色下拉:
150
+ * `audioSource` 那个下拉的候选是 `bundled` / `tts` / `custom`,
151
+ * 完全符合那个形状 —— 会被误认成音色下拉。
152
+ */
153
+ function knownVoiceKeys(installed) {
154
+ const m = CLIENT.match(/var VOICE_KEYS = \[([\s\S]*?)\n \]/);
155
+ const base = m ? [...m[1].matchAll(/'([a-z0-9-]+)'/g)].map((x) => x[1]) : [];
156
+ return new Set(base.concat(installed || []));
157
+ }
158
+
159
+ /** 取出所有音色下拉的候选 value 列表(不含「跟随全局」那个空 option)。 */
160
+ function voiceOptions(tree, installed) {
161
+ const known = knownVoiceKeys(installed);
162
+ const out = [];
163
+ for (const e of elements(tree)) {
164
+ if (e.type !== 'select') continue;
165
+ const opts = elements(e).filter((x) => x.type === 'option');
166
+ const vals = opts.map((o) => o.props && o.props.value).filter((v) => v);
167
+ // 只算"音色"下拉:候选里至少有一个是已知音色 key
168
+ const looksLikeVoice = vals.some((v) => known.has(v));
169
+ if (looksLikeVoice) out.push(vals);
170
+ }
171
+ return out;
172
+ }
173
+
174
+ // ── V1: 已下载但不在内置清单里的音色,必须出现在下拉里 ────────────────────
175
+ test('V1: 下载过的音色出现在音色下拉里(不再"装了也选不到")', async () => {
176
+ // `namiine-ritsu` 在静态清单里;这里用一个**不在**清单里的 key 模拟"后来下载的"。
177
+ // 用真实存在的 packs 里的名字不合适(那些都在清单里了),
178
+ // 所以造一个只可能来自"已下载"的 key。
179
+ const installed = ['zh-extra-voice', 'ja-extra-voice'];
180
+ const card = await renderCard({ values: { voiceLang: 'ja' }, installed });
181
+ const lists = voiceOptions(card.render(), card.installed);
182
+ assert.ok(lists.length > 0, '应能找到一个音色下拉');
183
+
184
+ const ja = lists[0];
185
+ assert.ok(ja.includes('ja-extra-voice'),
186
+ '已下载的日语���色必须出现在日语下拉里,实际候选:' + ja.join(', '));
187
+ assert.ok(ja.includes('zundamon-normal'), '内置音色不能因此消失');
188
+
189
+ // 中文那一组只在切到 zh 后才有;这里直接验证 ja 组不含中文 key
190
+ assert.ok(!ja.some((k) => k.indexOf('zh-') === 0),
191
+ '日语下拉不得混入中文音色(voiceLang=ja)');
192
+ });
193
+
194
+ // ── V2: 中文下拉同理 ────────────────────────────────────────────────────
195
+ test('V2: 已下载的中文音色出现在中文下拉里,且不混日语', async () => {
196
+ const installed = ['zh-extra-voice'];
197
+ // voiceName 也要给中文的:`keyOpts.unshift(v.voiceName)` 会把"当前生效但
198
+ // 不属于该语言"的音色补进列表(这是有意的,见 client.js 那段注释)。
199
+ // 不给的话默认 voiceName 是 zundamon-normal,日语键会合理地被 unshift 进来。
200
+ const card = await renderCard({ values: { voiceLang: 'zh', voiceName: 'zh-soft-female' }, installed });
201
+ const lists = voiceOptions(card.render(), card.installed);
202
+ assert.ok(lists.length > 0, '应能找到一个音色下拉');
203
+ const zh = lists[0];
204
+ assert.ok(zh.includes('zh-extra-voice'), '已下载的中文音色必须可选,实际:' + zh.join(', '));
205
+ assert.ok(!zh.some((k) => k.indexOf('zh-') !== 0),
206
+ '中文下拉不得混入日语(voiceLang=zh 且当前音色也是中文),实际:' + zh.join(', '));
207
+ });
208
+
209
+ // ── V3: 没注入 installed 时行为与修复前逐字一致 ──────────────────────────
210
+ test('V3: host 不返回 installed 时,下拉退回纯内置清单(向后兼容)', async () => {
211
+ const card = await renderCard({ values: { voiceLang: 'ja' }, installed: [] });
212
+ const lists = voiceOptions(card.render(), card.installed);
213
+ assert.ok(lists.length > 0, '应能找到一个音色下拉');
214
+ const ja = lists[0];
215
+ assert.ok(ja.includes('zundamon-normal'), '内置音色必须仍在');
216
+ assert.ok(ja.indexOf('zh-extra-voice') < 0, '没装的音色不该出现');
217
+ });
218
+
219
+ // ── V4: 漏登记的两个音色补回来了 ────────────────────────────────────────
220
+ test('V4: tohoku-zunko / tohoku-kiritan 已补进内置清单(并与打包脚本同名)', () => {
221
+ const m = CLIENT.match(/var VOICE_KEYS = \[([\s\S]*?)\n \]/);
222
+ assert.ok(m, '应能定位 VOICE_KEYS');
223
+ const keys = [...m[1].matchAll(/'([a-z0-9-]+)'/g)].map((x) => x[1]);
224
+
225
+ for (const k of ['tohoku-zunko', 'tohoku-kiritan']) {
226
+ assert.ok(keys.includes(k),
227
+ k + ' 必须在内置清单里 —— 它通过了许可审核、release 上也有人下载,'
228
+ + '漏在前面等于"下了也在下拉里看不到"');
229
+ // 显示名必须同源
230
+ assert.match(CLIENT, new RegExp("'" + k + "': '"), k + ' 必须有友好显示名');
231
+ }
232
+ assert.ok(keys.length >= 17, '内置清单应至少 17 个音色,实际 ' + keys.length);
233
+ });
234
+
235
+ // ── V5: 下拉候选不得出现许可被禁的音色(即便磁盘上有)──────────────────────
236
+ test('V5: 即便已下载目录里有禁用音色,也不得出现在下拉里', async () => {
237
+ // 这道防线的意义:VOICE_KEYS 的注释里明确说 kasukabe-tsumugi / mochiko
238
+ // 因官方规约禁止再分发。若哪天用户目录里残留了它们的文件(老版本装的),
239
+ // 我们不能因为「已安装」就把它列出来。
240
+ const installed = ['mochiko', 'kasukabe-tsumugi', 'zh-extra-voice'];
241
+ const card = await renderCard({ values: { voiceLang: 'zh' }, installed });
242
+ const lists = voiceOptions(card.render(), card.installed);
243
+ const all = lists.flat();
244
+ for (const banned of ['mochiko', 'kasukabe-tsumugi']) {
245
+ assert.ok(all.indexOf(banned) < 0,
246
+ banned + ' 不得出现在下拉里(官方规约禁止再分发,见 docs/audio-audit/README.md)');
247
+ }
248
+ });
249
+
250
+ // ── V6: 深色模式下下拉可读(issue #3b)─────────────────────────────────
251
+ test('V6: select 声明 colorScheme:inherit,让展开列表跟随宿主深色主题', () => {
252
+ // 原样式只有 background:transparent + color:inherit。原生 <select> 的
253
+ // **展开列表**由浏览器单独绘制,按元素上的 color-scheme 决定配色 ——
254
+ // 不设就默认浅色白底,配上继承来的浅灰文字 = 白字白底看不见。
255
+ assert.match(CLIENT, /colorScheme:\s*'inherit'/,
256
+ 'select 样式必须声明 colorScheme:inherit(否则深色模式下展开列表白字白底)');
257
+ // 不得写死颜色(写死会在另一种主题下翻车)
258
+ const seg = CLIENT.slice(CLIENT.indexOf('select: {'), CLIENT.indexOf('select: {') + 500);
259
+ assert.doesNotMatch(seg, /color:\s*'(black|white|#[0-9a-fA-F]{3,6})'/,
260
+ '不得写死文字颜色 —— 主题切换时会翻车');
261
+ });
@@ -420,7 +420,7 @@ test('W20: 两个地址都失败时明确报错', async () => {
420
420
  assert.match(r.error, /503/, '应把最后一次的失败原因带出来');
421
421
  });
422
422
  // ── W21: 下载走流式限额(不先读完整响应)────────────────────────────────
423
- test('W21: 有 res.body 时用流式读取,超限立即中止', async () => {
423
+ test('W21: 有 res.body 时用流式读取,超限立即中止', async () => withDataDir(async () => {
424
424
  // 第三轮审阅指出:原来 `res.arrayBuffer()` 读完整响应才查大小 ——
425
425
  // Content-Length 是服务器说了算的,谎报时内存会被吃满再检查。
426
426
  const { installVoicePack } = await import('../lib/voice-pack-download.js');
@@ -461,10 +461,10 @@ test('W21: 有 res.body 时用流式读取,超限立即中止', async () => {
461
461
  assert.equal(cancelled, true, '超限后必须 cancel 流,停止继续拉取');
462
462
  assert.ok(pulled < 40,
463
463
  `应在超过 32 MB 时立即中止,不该读完 40 块(实际拉了 ${pulled} 块)`);
464
- });
464
+ }));
465
465
 
466
466
  // ── W22: 没有 res.body 时退回 arrayBuffer(老运行时兼容)────────────────
467
- test('W22: 没有 res.body 时退回整块读取,并事后校验大小', async () => {
467
+ test('W22: 没有 res.body 时退回整块读取,并事后校验大小', async () => withDataDir(async () => {
468
468
  const { installVoicePack } = await import('../lib/voice-pack-download.js');
469
469
 
470
470
  // 32 MB + 1 字节,且不带 body → 走 arrayBuffer 分支,事后应被拒
@@ -483,10 +483,17 @@ test('W22: 没有 res.body 时退回整块读取,并事后校验大小', async
483
483
  });
484
484
  assert.equal(r.ok, false);
485
485
  assert.equal(r.error, 'pack-too-large', '退回分支也必须事后校验大小');
486
- });
486
+ }));
487
487
 
488
488
  // ── W23: 流式路径能正确拼接分块 ─────────────────────────────────────────
489
- test('W23: 流式分块能正确拼成完整 zip(不是只拿第一块)', async () => {
489
+ // ⚠️ 必须包 withDataDir:installVoicePack 会往**真实**的用户目录写盘
490
+ // (%LOCALAPPDATA%\dsh-notify-say\voice-lines\<key>)。W21~W23 原来没包,
491
+ // 于是在 2026-11-23 实测发现:跑一次 `npm test` 就往本机用户目录里留下
492
+ // 一个 w23-test(里面只有一个 a.txt,零 wav),并且它会被当成"已安装音色"
493
+ // 出现在设置页的音色下拉里 —— 测试污染了用户数据。
494
+ // 教训同 test-env-setup.mjs 的 notify.log 那次:**只隔离 DSH_HOME 不够**,
495
+ // 凡是有写盘路径的模块,都要把它的根目录一起指到临时目录。
496
+ test('W23: 流式分块能正确拼成完整 zip(不是只拿第一块)', async () => withDataDir(async () => {
490
497
  const { installVoicePack, listZipEntries } = await import('../lib/voice-pack-download.js');
491
498
  const { createHash } = await import('node:crypto');
492
499
 
@@ -526,7 +533,7 @@ test('W23: 流式分块能正确拼成完整 zip(不是只拿第一块)', as
526
533
  // 但**绝不该是 sha256-mismatch** —— 那说明分块没拼对。
527
534
  assert.notEqual(r.error, 'sha256-mismatch',
528
535
  '分块拼接错误会导致哈希对不上;这里哈希应匹配,说明拼装正确');
529
- });
536
+ }));
530
537
  // ── 测试辅助:构造最小 stored ZIP ────────────────────────────────────────
531
538
  function buildTinyZip(name, content) {
532
539
  const nameBuf = Buffer.from(name, 'utf8');
package/tts-speak.ps1 CHANGED
@@ -62,7 +62,13 @@ $ErrorActionPreference = 'Stop'
62
62
  function Write-Log([string]$msg) {
63
63
  if ($Preview) { return }
64
64
  try {
65
- $dir = Join-Path $env:TEMP 'dsh-notify-say'
65
+ # v0.5.4:与 lib/log-path.js / dsh-notify.ps1 同口径,支持覆盖目录。
66
+ $dir = $env:DSH_NOTIFY_SAY_LOG_DIR
67
+ if ([string]::IsNullOrWhiteSpace($dir)) {
68
+ $dir = Join-Path $env:TEMP 'dsh-notify-say'
69
+ } else {
70
+ $dir = $dir.Trim()
71
+ }
66
72
  if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Force -Path $dir | Out-Null }
67
73
  $line = ('{0} [tts] {1}' -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $msg)
68
74
  Add-Content -LiteralPath (Join-Path $dir 'notify.log') -Value $line -Encoding UTF8 -ErrorAction SilentlyContinue