dsh-gsv-tts 2.3.3 → 3.0.0

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
@@ -1,6 +1,11 @@
1
1
  // dsh-gsv-tts 客户端插件(手写 bundle,遵循 DSH client module 格式)
2
2
  // - 消息操作区(复制/点赞旁)增加"朗读"按钮:朗读该条助手结果(不含思考),调用宿主 /dsh-gsv-tts/speak
3
- // - 设置 → 插件配置:dsh-gsv-tts 设置卡片(音色、自动朗读、API 等,保存后热生效)
3
+ // - 长回复渐进分段播放:/speak 返回 URL 队列,播放器按 <audio> ended 事件顺序续播,段间 0 静音
4
+ // - 播放控件:暂停 / 继续 / 停止 + 进度显示 + 当前消息高亮(作用于整个队列)
5
+ // - 自动朗读(barge-in):轮询 /dsh-gsv-tts/autoplay/poll,新回复到来时按 interruptOnNew 打断或跳过
6
+ // - 设置 → 插件配置:dsh-gsv-tts 设置卡片(音色、自动朗读、打断开关、API 等,保存后热生效)
7
+ // - 音色试听:每条音色旁“试听”按钮(草稿未保存也能试听)+ “全部试听”批量循环播放
8
+ // - 音色市场:包内离线/远端清单拉取、两阶段确认安装、卸载(注册表音色只读托管)
4
9
  window.__ModuleLoader__.load({
5
10
  id: "dsh-gsv-tts",
6
11
  factory: (require) => {
@@ -12,7 +17,7 @@ window.__ModuleLoader__.load({
12
17
  let primitives = require("@deepseek-ai/dsh-client-ui-primitives");
13
18
 
14
19
  // ─── 样式注入 ───
15
- const css = "._gsv_action{width:28px;height:28px;color:var(--dsw-alias-label-tertiary);cursor:pointer;background:0 0;border:none;border-radius:28px;justify-content:center;align-items:center;padding:6px;display:inline-flex;font-size:14px}._gsv_action:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary)}._gsv_action:disabled{cursor:default;opacity:.4}._gsv_failure{color:var(--dsw-alias-label-tertiary);font-size:12px;margin-left:6px}";
20
+ const css = "._gsv_action{width:28px;height:28px;color:var(--dsw-alias-label-tertiary);cursor:pointer;background:0 0;border:none;border-radius:28px;justify-content:center;align-items:center;padding:6px;display:inline-flex;font-size:14px}._gsv_action:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary)}._gsv_action:disabled{cursor:default;opacity:.4}._gsv_failure{color:var(--dsw-alias-label-tertiary);font-size:12px;margin-left:6px}._gsv_action_active{color:var(--dsw-alias-brand,#6e56cf)!important;background:var(--dsw-alias-interactive-bg-hover)}._gsv_paused{opacity:.7}._gsv_controls{display:inline-flex;align-items:center;gap:2px}._gsv_progress{font-size:11px;color:var(--dsw-alias-label-tertiary);margin-left:4px;font-variant-numeric:tabular-nums;white-space:nowrap}._gsv_turn_active{outline:1px solid var(--dsw-alias-brand,#6e56cf);outline-offset:2px;border-radius:8px;animation:_gsv_pulse 2s ease-in-out infinite}@keyframes _gsv_pulse{0%,100%{outline-color:var(--dsw-alias-brand,#6e56cf)}50%{outline-color:transparent}}";
16
21
  const tagId = "dsh-gsv-tts/read-button.css";
17
22
  if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId) + "]") === null) {
18
23
  const tag = document.createElement("style");
@@ -27,13 +32,19 @@ window.__ModuleLoader__.load({
27
32
  const zh = {
28
33
  "read": "朗读结果",
29
34
  "reading": "朗读中…",
35
+ "pause": "暂停",
36
+ "resume": "继续",
37
+ "stop": "停止",
30
38
  "cardTitle": "声音设置",
31
39
  "cardDesc": "调整 TTS 音色、自动朗读等设置,保存后即时生效。",
40
+ "cardLoadFailed": "声音设置加载失败",
32
41
  "field.apiUrl": "API 地址",
33
42
  "field.apiUrlHint": "GSV-TTS-Lite 服务地址",
34
43
  "field.defaultVoice": "默认音色",
35
44
  "field.defaultVoiceHint": "留空使用第一个音色",
36
45
  "field.autoPlay": "自动朗读助手回复",
46
+ "field.interruptOnNew": "新回复打断当前朗读",
47
+ "field.interruptOnNewHint": "关闭后朗读中遇到新回复会跳过,避免叠音",
37
48
  "field.timeout": "请求超时(毫秒)",
38
49
  "field.installDir": "引擎安装目录",
39
50
  "field.voices": "音色预设",
@@ -43,6 +54,30 @@ window.__ModuleLoader__.load({
43
54
  "voice.promptText": "提示文本",
44
55
  "voice.add": "添加音色",
45
56
  "voice.remove": "删除",
57
+ "voice.preview": "试听",
58
+ "voice.previewAll": "全部试听(循环)",
59
+ "voice.previewing": "试听中…",
60
+ "market.title": "音色市场",
61
+ "market.desc": "从清单安装音色(包内离线 / 自定义远端源);第三方来源安装需确认。",
62
+ "market.load": "加载市场",
63
+ "market.loading": "加载中…",
64
+ "market.refresh": "刷新",
65
+ "market.sourceBundled": "包内清单",
66
+ "market.sourceRemote": "远端清单",
67
+ "market.trusted": "官方可信",
68
+ "market.untrusted": "第三方(安装需确认)",
69
+ "market.installed": "已安装",
70
+ "market.install": "安装",
71
+ "market.uninstall": "卸载",
72
+ "market.registryTag": "注册表",
73
+ "market.confirmInstallTitle": "确认安装第三方音色?",
74
+ "market.confirmInstallBody": "请核对来源、作者与许可:",
75
+ "market.confirm": "确认安装",
76
+ "market.cancel": "取消",
77
+ "market.confirmRemoveTitle": "卸载音色?",
78
+ "market.confirmRemoveBody": "是否同时删除本地音频文件?",
79
+ "market.removeDelete": "删除文件",
80
+ "market.removeKeep": "保留文件",
46
81
  "save": "保存",
47
82
  "saving": "保存中…",
48
83
  "discard": "放弃修改",
@@ -62,13 +97,19 @@ window.__ModuleLoader__.load({
62
97
  const en = {
63
98
  "read": "Read result",
64
99
  "reading": "Reading…",
100
+ "pause": "Pause",
101
+ "resume": "Resume",
102
+ "stop": "Stop",
65
103
  "cardTitle": "Voice Settings",
66
104
  "cardDesc": "Adjust TTS voices and auto-read; changes apply instantly.",
105
+ "cardLoadFailed": "Failed to load voice settings",
67
106
  "field.apiUrl": "API URL",
68
107
  "field.apiUrlHint": "GSV-TTS-Lite service URL",
69
108
  "field.defaultVoice": "Default voice",
70
109
  "field.defaultVoiceHint": "Empty uses the first voice",
71
110
  "field.autoPlay": "Auto-read assistant replies",
111
+ "field.interruptOnNew": "New replies interrupt current read",
112
+ "field.interruptOnNewHint": "When off, new replies are skipped while reading to avoid overlap",
72
113
  "field.timeout": "Timeout (ms)",
73
114
  "field.installDir": "Engine install directory",
74
115
  "field.voices": "Voices",
@@ -78,6 +119,30 @@ window.__ModuleLoader__.load({
78
119
  "voice.promptText": "Prompt text",
79
120
  "voice.add": "Add voice",
80
121
  "voice.remove": "Remove",
122
+ "voice.preview": "Preview",
123
+ "voice.previewAll": "Preview all (loop)",
124
+ "voice.previewing": "Previewing…",
125
+ "market.title": "Voice Market",
126
+ "market.desc": "Install voices from a manifest (bundled offline / custom remote source); third-party sources require confirmation.",
127
+ "market.load": "Load market",
128
+ "market.loading": "Loading…",
129
+ "market.refresh": "Refresh",
130
+ "market.sourceBundled": "Bundled manifest",
131
+ "market.sourceRemote": "Remote manifest",
132
+ "market.trusted": "Official trusted",
133
+ "market.untrusted": "Third-party (confirm to install)",
134
+ "market.installed": "Installed",
135
+ "market.install": "Install",
136
+ "market.uninstall": "Uninstall",
137
+ "market.registryTag": "Registry",
138
+ "market.confirmInstallTitle": "Install third-party voice?",
139
+ "market.confirmInstallBody": "Review source, author and license:",
140
+ "market.confirm": "Confirm install",
141
+ "market.cancel": "Cancel",
142
+ "market.confirmRemoveTitle": "Uninstall voice?",
143
+ "market.confirmRemoveBody": "Also delete the local audio files?",
144
+ "market.removeDelete": "Delete files",
145
+ "market.removeKeep": "Keep files",
81
146
  "save": "Save",
82
147
  "saving": "Saving…",
83
148
  "discard": "Discard",
@@ -95,10 +160,211 @@ window.__ModuleLoader__.load({
95
160
  "helpTitle": "Help"
96
161
  };
97
162
 
163
+ // ─── 全局朗读播放器单例 ───
164
+ // 任意时刻最多一个朗读队列在播;start 新队列即打断旧队列(barge-in)。
165
+ // 暂停/继续作用于整个队列:记录当前段 + 段内时间,恢复后从原处续播。
166
+ const player = {
167
+ state: "idle", // idle | loading | playing | paused
168
+ key: null, // 当前队列标识:`${sessionId}:${messageId}` 或 `autoplay:${seq}`
169
+ queue: [],
170
+ // 待播队列:不打断时(interruptOnNew=false)新回复排队,当前队列自然播完自动补读
171
+ backlog: [],
172
+ index: 0,
173
+ audio: null,
174
+ error: null,
175
+ listeners: new Set(),
176
+ _tick: 0,
177
+ subscribe(fn) {
178
+ player.listeners.add(fn);
179
+ return () => player.listeners.delete(fn);
180
+ },
181
+ getSnapshot() {
182
+ return player._tick;
183
+ },
184
+ _emit() {
185
+ player._tick += 1;
186
+ for (const fn of player.listeners) {
187
+ try { fn(player); } catch { /* 忽略订阅者异常 */ }
188
+ }
189
+ },
190
+ _stopAudio() {
191
+ if (player.audio) {
192
+ const a = player.audio;
193
+ player.audio = null;
194
+ a.pause();
195
+ try { a.src = ""; a.load(); } catch { /* 忽略 */ }
196
+ }
197
+ },
198
+ stop() {
199
+ player._stopAudio();
200
+ player.state = "idle";
201
+ player.key = null;
202
+ player.queue = [];
203
+ player.index = 0;
204
+ player.error = null;
205
+ player.backlog = [];
206
+ player.loop = false;
207
+ player._emit();
208
+ },
209
+ play(key, segments, opts) {
210
+ // 打断式播放(barge-in):停止当前并清空待播队列
211
+ player.stop();
212
+ player._start(key, segments, opts);
213
+ },
214
+ // 排队式播放:空闲则直接播;正在播则进入待播队列,当前队列播完自动补读
215
+ enqueue(key, segments, opts) {
216
+ const list = segments || [];
217
+ if (list.length === 0) {
218
+ player.error = "empty";
219
+ player._emit();
220
+ return;
221
+ }
222
+ if (player.state === "idle") {
223
+ player._start(key, list, opts);
224
+ } else {
225
+ player.backlog.push({ key, segments: list, opts });
226
+ }
227
+ player._emit();
228
+ },
229
+ _start(key, segments, opts) {
230
+ const list = segments || [];
231
+ if (list.length === 0) {
232
+ player.error = "empty";
233
+ player._emit();
234
+ return;
235
+ }
236
+ player.key = key;
237
+ player.queue = list.slice();
238
+ player.index = 0;
239
+ player.error = null;
240
+ player.loop = !!(opts && opts.loop); // 循环播放(全部试听用)
241
+ player.state = "loading";
242
+ player._emit();
243
+ player._playIndex(0);
244
+ },
245
+ // 队列自然播完:循环则从头再来;否则有待播则继续补读,再否则回到 idle
246
+ _finish() {
247
+ if (player.loop && player.queue.length > 0) {
248
+ player._playIndex(0);
249
+ } else if (player.backlog.length) {
250
+ const next = player.backlog.shift();
251
+ player._start(next.key, next.segments, next.opts);
252
+ } else {
253
+ player.stop();
254
+ }
255
+ },
256
+ _playIndex(i) {
257
+ const seg = player.queue[i];
258
+ if (!seg) {
259
+ player._finish();
260
+ return;
261
+ }
262
+ player.index = i;
263
+ const audio = new Audio(seg.url);
264
+ player.audio = audio;
265
+ player.state = "playing";
266
+ player._emit();
267
+ audio.addEventListener("ended", () => {
268
+ if (player.audio !== audio) return;
269
+ player._playIndex(i + 1);
270
+ });
271
+ audio.addEventListener("error", () => {
272
+ if (player.audio !== audio) return;
273
+ player.error = "audio-error";
274
+ player._emit();
275
+ });
276
+ audio.addEventListener("timeupdate", () => {
277
+ if (player.audio === audio) player._emit();
278
+ });
279
+ audio.addEventListener("pause", () => {
280
+ if (player.audio === audio && player.state === "playing") {
281
+ player.state = "paused";
282
+ player._emit();
283
+ }
284
+ });
285
+ audio.addEventListener("play", () => {
286
+ if (player.audio === audio) {
287
+ player.state = "playing";
288
+ player._emit();
289
+ }
290
+ });
291
+ audio.play().catch(() => {
292
+ if (player.audio !== audio) return;
293
+ player.state = "paused";
294
+ player.error = "play-denied";
295
+ player._emit();
296
+ });
297
+ },
298
+ pause() {
299
+ if (player.audio && player.state === "playing") {
300
+ player.audio.pause();
301
+ player.state = "paused";
302
+ player._emit();
303
+ }
304
+ },
305
+ resume() {
306
+ if (player.audio && player.state === "paused") {
307
+ player.state = "playing";
308
+ player._emit();
309
+ player.audio.play().catch(() => {
310
+ player.state = "paused";
311
+ player._emit();
312
+ });
313
+ }
314
+ },
315
+ isActive(key) {
316
+ return (player.state === "playing" || player.state === "paused" || player.state === "loading") && player.key === key;
317
+ },
318
+ progress() {
319
+ let elapsed = 0;
320
+ for (let i = 0; i < player.index; i++) elapsed += player.queue[i]?.duration || 0;
321
+ let total = 0;
322
+ for (const s of player.queue) total += s.duration || 0;
323
+ const cur = player.audio;
324
+ if (cur) {
325
+ const d = isFinite(cur.duration) && cur.duration > 0 ? cur.duration : (player.queue[player.index]?.duration || 0);
326
+ if (player.index < player.queue.length) {
327
+ elapsed += Math.min(cur.currentTime || 0, d);
328
+ total = total - (player.queue[player.index]?.duration || 0) + d;
329
+ }
330
+ }
331
+ return { elapsed, total, index: player.index, count: player.queue.length };
332
+ }
333
+ };
334
+
335
+ // 自动播放解锁:首次用户手势时触碰一次 AudioContext,规避浏览器自动播放策略
336
+ if (typeof document !== "undefined" && typeof window !== "undefined") {
337
+ const unlock = () => {
338
+ try {
339
+ const AC = window.AudioContext || window.webkitAudioContext;
340
+ if (AC) {
341
+ const ac = new AC();
342
+ ac.resume();
343
+ setTimeout(() => { try { ac.close(); } catch { /* 忽略 */ } }, 50);
344
+ }
345
+ } catch { /* 忽略 */ }
346
+ };
347
+ document.addEventListener("pointerdown", unlock, { once: true });
348
+ document.addEventListener("keydown", unlock, { once: true });
349
+ }
350
+
351
+ function formatTime(sec) {
352
+ if (!isFinite(sec) || sec < 0) sec = 0;
353
+ const m = Math.floor(sec / 60);
354
+ const s = Math.floor(sec % 60);
355
+ return m + ":" + String(s).padStart(2, "0");
356
+ }
357
+
98
358
  // ─── 朗读按钮(conversation.chat.assistant-actions 插槽) ───
99
359
  function ReadAloudButton({ messageId, sessionId, t }) {
100
360
  const [busy, setBusy] = react.useState(false);
101
361
  const [failure, setFailure] = react.useState(null);
362
+ const rootRef = react.useRef(null);
363
+ const key = (sessionId || "s") + ":" + (messageId || "m");
364
+ react.useSyncExternalStore(player.subscribe, player.getSnapshot);
365
+ const active = player.isActive(key);
366
+ const paused = active && player.state === "paused";
367
+ const progress = active ? player.progress() : null;
102
368
  const onRead = react.useCallback(async () => {
103
369
  setBusy(true);
104
370
  setFailure(null);
@@ -110,17 +376,58 @@ window.__ModuleLoader__.load({
110
376
  });
111
377
  const data = await resp.json().catch(() => ({}));
112
378
  if (!resp.ok) throw new Error(data.message || ("HTTP " + resp.status));
113
- if (!data.audioUrl) throw new Error("no audio url");
114
- const audio = new Audio(data.audioUrl);
115
- await audio.play();
379
+ // 兼容旧服务端:无 segments 时回退单 URL
380
+ let segments = data.segments;
381
+ if ((!segments || segments.length === 0) && data.audioUrl) {
382
+ segments = [{ url: data.audioUrl, duration: data.audioLen || 0 }];
383
+ }
384
+ if (!segments || segments.length === 0) throw new Error(data.error || "no audio");
385
+ await player.play(key, segments);
386
+ if (data.error) setFailure(data.error);
116
387
  } catch (e) {
117
388
  setFailure(String((e && e.message) || e));
118
389
  } finally {
119
390
  setBusy(false);
120
391
  }
121
- }, [sessionId, messageId]);
122
- return jsx.jsxs(react.Fragment, { children: [
123
- jsx.jsx(primitives.Tooltip, {
392
+ }, [key, sessionId, messageId]);
393
+ // 高亮正在朗读的那条消息(插槽 DOM 位于带 data-turn-tail 的消息根节点内)
394
+ react.useEffect(() => {
395
+ if (!active) return;
396
+ const el = rootRef.current;
397
+ const turn = el && el.closest("[data-turn-tail]");
398
+ if (!turn) return;
399
+ turn.classList.add("_gsv_turn_active");
400
+ return () => turn.classList.remove("_gsv_turn_active");
401
+ }, [active]);
402
+ const progressText = progress
403
+ ? formatTime(progress.elapsed) + " / " + formatTime(progress.total) + (progress.count > 1 ? " · " + (progress.index + 1) + "/" + progress.count : "")
404
+ : null;
405
+ return jsx.jsxs("div", { ref: rootRef, style: { display: "inline-flex", alignItems: "center", gap: 2 }, children: [
406
+ active ? jsx.jsxs(react.Fragment, { children: [
407
+ jsx.jsx(primitives.Tooltip, {
408
+ label: paused ? t("resume") : t("pause"),
409
+ side: "bottom",
410
+ children: jsx.jsx("button", {
411
+ type: "button",
412
+ className: "_gsv_action _gsv_action_active" + (paused ? " _gsv_paused" : ""),
413
+ "aria-label": paused ? t("resume") : t("pause"),
414
+ onClick: paused ? () => player.resume() : () => player.pause(),
415
+ children: paused ? "▶" : "⏸"
416
+ })
417
+ }),
418
+ jsx.jsx(primitives.Tooltip, {
419
+ label: t("stop"),
420
+ side: "bottom",
421
+ children: jsx.jsx("button", {
422
+ type: "button",
423
+ className: "_gsv_action",
424
+ "aria-label": t("stop"),
425
+ onClick: () => player.stop(),
426
+ children: "⏹"
427
+ })
428
+ }),
429
+ progressText !== null && jsx.jsx("span", { className: "_gsv_progress", children: progressText })
430
+ ] }) : jsx.jsx(primitives.Tooltip, {
124
431
  label: busy ? t("reading") : t("read"),
125
432
  side: "bottom",
126
433
  children: jsx.jsx("button", {
@@ -136,22 +443,71 @@ window.__ModuleLoader__.load({
136
443
  ] });
137
444
  }
138
445
 
446
+ // ─── 设置 section 错误边界:任何渲染错误都显示为红字,而不是被宿主静默吞成空白 ───
447
+ class GsvErrorBoundary extends react.Component {
448
+ constructor(props) {
449
+ super(props);
450
+ this.state = { error: null };
451
+ }
452
+ static getDerivedStateFromError(e) {
453
+ return { error: String((e && e.message) || e) };
454
+ }
455
+ componentDidCatch(e, info) {
456
+ try { console.error("[dsh-gsv-tts] settings render error:", e, info); } catch { /* 忽略 */ }
457
+ }
458
+ render() {
459
+ if (this.state.error !== null) {
460
+ return react.createElement("div", {
461
+ style: { color: "var(--dsw-alias-danger, #e5484d)", fontSize: 12, marginTop: 6, whiteSpace: "pre-wrap" },
462
+ children: "设置渲染错误: " + this.state.error
463
+ });
464
+ }
465
+ return this.props.children;
466
+ }
467
+ }
468
+
139
469
  // ─── 设置卡片(settings.plugin.item 插槽) ───
140
- const FIELD_LABELS = ["apiUrl", "defaultVoice", "timeout", "installDir"];
141
470
  function TtsSettingsCard({ scope, t }) {
142
- const [snapshot, setSnapshot] = react.useState(() => scope.getSnapshot());
143
- react.useEffect(() => scope.subscribe(() => setSnapshot(scope.getSnapshot())), [scope]);
471
+ // 防御:settings 作用域异常(如服务端命名空间未注册)时显示错误而非整段空白
472
+ const [snapshot, setSnapshot] = react.useState(() => {
473
+ try {
474
+ return scope.getSnapshot();
475
+ } catch (e) {
476
+ return { error: String((e && e.message) || e) };
477
+ }
478
+ });
479
+ react.useEffect(() => {
480
+ try {
481
+ return scope.subscribe(() => setSnapshot(scope.getSnapshot()));
482
+ } catch {
483
+ return () => {};
484
+ }
485
+ }, [scope]);
486
+ // 订阅播放器状态:试听按钮/批量进度随播放变化刷新
487
+ react.useSyncExternalStore(player.subscribe, player.getSnapshot);
144
488
  const value = (snapshot && snapshot.value) || {};
145
489
  const writable = !!(snapshot && snapshot.writable);
146
490
  const [draft, setDraft] = react.useState(null);
147
491
  const [saving, setSaving] = react.useState(false);
148
492
  const [error, setError] = react.useState(null);
493
+ const [previewBusy, setPreviewBusy] = react.useState(null); // 单条:索引 | 批量:"all" | null
494
+ const [previewError, setPreviewError] = react.useState(null);
495
+ // ─── 音色市场状态:必须在下方提前 return 之前声明(hook 数量跨渲染一致,否则 React #310) ───
496
+ const [market, setMarket] = react.useState(null); // { source, trusted, version, voices }
497
+ const [marketLoading, setMarketLoading] = react.useState(false);
498
+ const [marketBusy, setMarketBusy] = react.useState(null); // 'install:<id>' | 'remove:<id>' | null
499
+ const [marketError, setMarketError] = react.useState(null);
500
+ const [confirmInstall, setConfirmInstall] = react.useState(null); // { pkg }
501
+ const [confirmRemove, setConfirmRemove] = react.useState(null); // { id, name }
149
502
  const valueJson = JSON.stringify(value);
150
503
  react.useEffect(() => {
151
504
  setDraft(structuredClone(value));
152
505
  }, [valueJson]);
153
506
  const dirty = draft !== null && JSON.stringify(draft) !== valueJson;
154
507
  if (draft === null) return null;
508
+ if (snapshot && snapshot.error) {
509
+ return jsx.jsx("div", { style: { color: "var(--dsw-alias-danger, #e5484d)", fontSize: 12, marginTop: 6 }, children: t("cardLoadFailed") + ":" + snapshot.error });
510
+ }
155
511
  const patchField = (field, next) => setDraft({ ...draft, [field]: next });
156
512
  const patchVoice = (index, field, next) => {
157
513
  const voices = (draft.voices || []).map((v, i) => i === index ? { ...v, [field]: next } : v);
@@ -159,12 +515,149 @@ window.__ModuleLoader__.load({
159
515
  };
160
516
  const addVoice = () => patchField("voices", [...(draft.voices || []), { name: "", speakerAudioPath: "", promptAudioPath: "", promptText: "" }]);
161
517
  const removeVoice = (index) => patchField("voices", (draft.voices || []).filter((_, i) => i !== index));
518
+ // ─── 音色试听(未保存的草稿音色也可直接试听) ───
519
+ const previewKey = (i, name) => "preview:" + i + ":" + (name || "");
520
+ const previewOne = async (i) => {
521
+ const v = (draft.voices || [])[i];
522
+ if (!v) return;
523
+ const key = previewKey(i, v.name);
524
+ if (player.isActive(key)) { player.stop(); return; }
525
+ setPreviewBusy(i);
526
+ setPreviewError(null);
527
+ try {
528
+ const resp = await fetch("/dsh-gsv-tts/preview", {
529
+ method: "POST",
530
+ headers: { "Content-Type": "application/json" },
531
+ body: JSON.stringify({ voice: { name: v.name ?? "", speakerAudioPath: v.speakerAudioPath ?? "", promptAudioPath: v.promptAudioPath ?? "", promptText: v.promptText ?? "" } })
532
+ });
533
+ const data = await resp.json().catch(() => ({}));
534
+ if (!resp.ok) throw new Error(data.message || ("HTTP " + resp.status));
535
+ if (!data.audioUrl) throw new Error("no audio");
536
+ player.play(key, [{ url: data.audioUrl, duration: data.audioLen || 0 }]);
537
+ } catch (e) {
538
+ setPreviewError(String((e && e.message) || e));
539
+ } finally {
540
+ setPreviewBusy(null);
541
+ }
542
+ };
543
+ const previewAll = async () => {
544
+ if (player.isActive("preview:all")) { player.stop(); return; }
545
+ const voices = draft.voices || [];
546
+ if (voices.length === 0) return;
547
+ setPreviewBusy("all");
548
+ setPreviewError(null);
549
+ try {
550
+ const results = await Promise.all(voices.map(async (v) => {
551
+ try {
552
+ const resp = await fetch("/dsh-gsv-tts/preview", {
553
+ method: "POST",
554
+ headers: { "Content-Type": "application/json" },
555
+ body: JSON.stringify({ voice: { name: v.name ?? "", speakerAudioPath: v.speakerAudioPath ?? "", promptAudioPath: v.promptAudioPath ?? "", promptText: v.promptText ?? "" } })
556
+ });
557
+ const data = await resp.json().catch(() => ({}));
558
+ if (!resp.ok || !data.audioUrl) return { error: data.message || ("HTTP " + resp.status) };
559
+ return { url: data.audioUrl, duration: data.audioLen || 0 };
560
+ } catch (e) {
561
+ return { error: String((e && e.message) || e) };
562
+ }
563
+ }));
564
+ const ok = results.filter((r) => r.url);
565
+ const errs = results.filter((r) => r.error);
566
+ if (ok.length > 0) player.play("preview:all", ok, { loop: true });
567
+ if (errs.length > 0) setPreviewError(errs.map((r) => r.error).join(";"));
568
+ } finally {
569
+ setPreviewBusy(null);
570
+ }
571
+ };
572
+ const batchActive = player.isActive("preview:all");
573
+ const batchProgress = batchActive ? player.progress() : null;
574
+ const batchProgressText = batchProgress
575
+ ? formatTime(batchProgress.elapsed) + " / " + formatTime(batchProgress.total) + " · " + (batchProgress.index + 1) + "/" + batchProgress.count + " 🔁"
576
+ : null;
577
+ // ─── 音色市场(注册表:拉取 / 两阶段安装 / 卸载确认) ───
578
+ const marketLoad = async () => {
579
+ setMarketLoading(true);
580
+ setMarketError(null);
581
+ try {
582
+ const resp = await fetch("/dsh-gsv-tts/registry/list", {
583
+ method: "POST",
584
+ headers: { "Content-Type": "application/json" },
585
+ body: JSON.stringify({})
586
+ });
587
+ const data = await resp.json().catch(() => ({}));
588
+ if (!resp.ok || data.ok === false) throw new Error(data.message || ("HTTP " + resp.status));
589
+ setMarket(data);
590
+ } catch (e) {
591
+ setMarketError(String((e && e.message) || e));
592
+ } finally {
593
+ setMarketLoading(false);
594
+ }
595
+ };
596
+ const marketPreview = async (pkg) => {
597
+ setMarketError(null);
598
+ try {
599
+ const resp = await fetch("/dsh-gsv-tts/preview", {
600
+ method: "POST",
601
+ headers: { "Content-Type": "application/json" },
602
+ body: JSON.stringify({ voice: { name: pkg.name, speakerAudioPath: pkg.speaker, promptAudioPath: pkg.prompt, promptText: pkg.promptText } })
603
+ });
604
+ const data = await resp.json().catch(() => ({}));
605
+ if (!resp.ok || !data.audioUrl) throw new Error(data.message || "no audio");
606
+ player.play("market:" + pkg.id, [{ url: data.audioUrl, duration: data.audioLen || 0 }]);
607
+ } catch (e) {
608
+ setMarketError(String((e && e.message) || e));
609
+ }
610
+ };
611
+ const marketInstall = async (pkg, confirm) => {
612
+ setMarketBusy("install:" + pkg.id);
613
+ setMarketError(null);
614
+ try {
615
+ const resp = await fetch("/dsh-gsv-tts/registry/install", {
616
+ method: "POST",
617
+ headers: { "Content-Type": "application/json" },
618
+ body: JSON.stringify({ id: pkg.id, confirm: confirm === true })
619
+ });
620
+ const data = await resp.json().catch(() => ({}));
621
+ if (!resp.ok) throw new Error(data.message || ("HTTP " + resp.status));
622
+ if (data.ok) {
623
+ setConfirmInstall(null);
624
+ await marketLoad();
625
+ } else if (data.needsConfirm) {
626
+ setConfirmInstall(pkg);
627
+ } else {
628
+ throw new Error(data.message || "安装失败");
629
+ }
630
+ } catch (e) {
631
+ setMarketError(String((e && e.message) || e));
632
+ } finally {
633
+ setMarketBusy(null);
634
+ }
635
+ };
636
+ const marketRemoveById = async (id, deleteFiles) => {
637
+ setMarketBusy("remove:" + id);
638
+ setMarketError(null);
639
+ try {
640
+ const resp = await fetch("/dsh-gsv-tts/registry/remove", {
641
+ method: "POST",
642
+ headers: { "Content-Type": "application/json" },
643
+ body: JSON.stringify({ id, deleteFiles })
644
+ });
645
+ const data = await resp.json().catch(() => ({}));
646
+ if (!resp.ok || !data.ok) throw new Error(data.message || ("HTTP " + resp.status));
647
+ setConfirmRemove(null);
648
+ await marketLoad();
649
+ } catch (e) {
650
+ setMarketError(String((e && e.message) || e));
651
+ } finally {
652
+ setMarketBusy(null);
653
+ }
654
+ };
162
655
  const save = async () => {
163
656
  setSaving(true);
164
657
  setError(null);
165
658
  try {
166
659
  const base = (snapshot && snapshot.base) || {};
167
- for (const field of ["apiUrl", "defaultVoice", "autoPlay", "timeout", "installDir", "voices"]) {
660
+ for (const field of ["apiUrl", "defaultVoice", "autoPlay", "interruptOnNew", "timeout", "installDir", "voices"]) {
168
661
  const next = draft[field];
169
662
  const baseVal = base[field];
170
663
  if (baseVal !== void 0 && JSON.stringify(next) === JSON.stringify(baseVal)) {
@@ -182,6 +675,9 @@ window.__ModuleLoader__.load({
182
675
  const inputStyle = { boxSizing: "border-box", border: "1px solid var(--dsw-alias-border-l2)", background: "var(--dsw-alias-bg-layer-1)", width: "100%", color: "var(--dsw-alias-label-primary)", font: "inherit", borderRadius: 8, padding: "6px 8px", fontSize: 13 };
183
676
  const labelStyle = { display: "block", color: "var(--dsw-alias-label-secondary)", fontSize: 12, margin: "10px 0 4px" };
184
677
  const rowStyle = { display: "flex", gap: 8, alignItems: "center", marginBottom: 6 };
678
+ const linkBtn = { cursor: "pointer", border: "none", background: "0 0", color: "var(--dsw-alias-brand,#6e56cf)", fontSize: 12, padding: 0 };
679
+ const dangerBtn = { cursor: "pointer", border: "none", background: "0 0", color: "var(--dsw-alias-danger, #e5484d)", fontSize: 12, padding: 0 };
680
+ const primaryBtn = { cursor: "pointer", border: "none", borderRadius: 14, height: 26, padding: "0 12px", fontSize: 12, background: "var(--dsw-alias-button-primary-fill)", color: "var(--dsw-alias-label-primary-foreground)" };
185
681
  return jsx.jsxs("div", { children: [
186
682
  jsx.jsx("div", { style: { color: "var(--dsw-alias-label-tertiary)", fontSize: 12, marginTop: 2 }, children: t("cardDesc") }),
187
683
  !writable && jsx.jsx("div", { style: { color: "var(--dsw-alias-label-tertiary)", fontSize: 12, marginTop: 6 }, children: t("readOnly") }),
@@ -197,15 +693,79 @@ window.__ModuleLoader__.load({
197
693
  jsx.jsx("input", { type: "checkbox", disabled: !writable, checked: !!draft.autoPlay, onChange: (e) => patchField("autoPlay", e.target.checked) }),
198
694
  t("field.autoPlay")
199
695
  ] }) }),
696
+ jsx.jsx("label", { style: { ...labelStyle, display: "flex", alignItems: "center", gap: 6, cursor: "pointer" }, children: jsx.jsxs(react.Fragment, { children: [
697
+ jsx.jsx("input", { type: "checkbox", disabled: !writable, checked: draft.interruptOnNew !== false, onChange: (e) => patchField("interruptOnNew", e.target.checked) }),
698
+ t("field.interruptOnNew")
699
+ ] }) }),
700
+ jsx.jsx("div", { style: { color: "var(--dsw-alias-label-tertiary)", fontSize: 11, marginTop: 2 }, children: t("field.interruptOnNewHint") }),
200
701
  jsx.jsx("label", { style: labelStyle, children: t("field.voices") }),
201
- (draft.voices || []).map((v, i) => jsx.jsxs("div", { style: { border: "1px solid var(--dsw-alias-border-l2)", borderRadius: 8, padding: 8, marginBottom: 8 }, children: [
202
- jsx.jsx("input", { style: inputStyle, disabled: !writable, value: v.name ?? "", placeholder: t("voice.name"), onChange: (e) => patchVoice(i, "name", e.target.value) }),
203
- jsx.jsx("input", { style: { ...inputStyle, marginTop: 4 }, disabled: !writable, value: v.speakerAudioPath ?? "", placeholder: t("voice.speaker"), onChange: (e) => patchVoice(i, "speakerAudioPath", e.target.value) }),
204
- jsx.jsx("input", { style: { ...inputStyle, marginTop: 4 }, disabled: !writable, value: v.promptAudioPath ?? "", placeholder: t("voice.prompt"), onChange: (e) => patchVoice(i, "promptAudioPath", e.target.value) }),
205
- jsx.jsx("input", { style: { ...inputStyle, marginTop: 4 }, disabled: !writable, value: v.promptText ?? "", placeholder: t("voice.promptText"), onChange: (e) => patchVoice(i, "promptText", e.target.value) }),
206
- writable && jsx.jsx("button", { type: "button", onClick: () => removeVoice(i), style: { marginTop: 6, cursor: "pointer", border: "none", background: "0 0", color: "var(--dsw-alias-label-tertiary)", fontSize: 12, padding: 0 }, children: t("voice.remove") })
207
- ], }, i)),
702
+ (draft.voices || []).map((v, i) => {
703
+ const isReg = v.source === "registry"; // 注册表音色只读托管
704
+ return jsx.jsxs("div", { style: { border: "1px solid var(--dsw-alias-border-l2)", borderRadius: 8, padding: 8, marginBottom: 8 }, children: [
705
+ jsx.jsx("input", { style: inputStyle, disabled: !writable || isReg, value: v.name ?? "", placeholder: t("voice.name"), onChange: (e) => patchVoice(i, "name", e.target.value) }),
706
+ jsx.jsx("input", { style: { ...inputStyle, marginTop: 4 }, disabled: !writable || isReg, value: v.speakerAudioPath ?? "", placeholder: t("voice.speaker"), onChange: (e) => patchVoice(i, "speakerAudioPath", e.target.value) }),
707
+ jsx.jsx("input", { style: { ...inputStyle, marginTop: 4 }, disabled: !writable || isReg, value: v.promptAudioPath ?? "", placeholder: t("voice.prompt"), onChange: (e) => patchVoice(i, "promptAudioPath", e.target.value) }),
708
+ jsx.jsx("input", { style: { ...inputStyle, marginTop: 4 }, disabled: !writable || isReg, value: v.promptText ?? "", placeholder: t("voice.promptText"), onChange: (e) => patchVoice(i, "promptText", e.target.value) }),
709
+ jsx.jsx("div", { style: { display: "flex", gap: 10, marginTop: 6, alignItems: "center" }, children: [
710
+ jsx.jsx("button", { type: "button", disabled: previewBusy === i, onClick: () => previewOne(i), style: linkBtn, children: previewBusy === i ? t("voice.previewing") : (player.isActive(previewKey(i, v.name)) ? t("stop") : t("voice.preview")) }),
711
+ isReg ? jsx.jsxs(react.Fragment, { children: [
712
+ jsx.jsx("span", { style: { color: "var(--dsw-alias-label-tertiary)", fontSize: 11 }, children: t("market.registryTag") }),
713
+ writable && jsx.jsx("button", { type: "button", disabled: marketBusy === "remove:" + v.id, onClick: () => setConfirmRemove({ id: v.id, name: v.name }), style: dangerBtn, children: marketBusy === "remove:" + v.id ? "…" : t("market.uninstall") })
714
+ ] }) : (writable && jsx.jsx("button", { type: "button", onClick: () => removeVoice(i), style: { cursor: "pointer", border: "none", background: "0 0", color: "var(--dsw-alias-label-tertiary)", fontSize: 12, padding: 0 }, children: t("voice.remove") }))
715
+ ] })
716
+ ] }, i);
717
+ }),
718
+ (draft.voices || []).length > 0 && jsx.jsx("div", { style: { display: "flex", alignItems: "center", gap: 8, marginTop: 8 }, children: [
719
+ jsx.jsx("button", { type: "button", disabled: previewBusy === "all", onClick: previewAll, style: { cursor: "pointer", border: "none", background: "0 0", color: "var(--dsw-alias-brand,#6e56cf)", fontSize: 13, padding: 0 }, children: previewBusy === "all" ? t("voice.previewing") : (batchActive ? t("stop") : t("voice.previewAll")) }),
720
+ batchProgressText !== null && jsx.jsx("span", { className: "_gsv_progress", children: batchProgressText })
721
+ ] }),
722
+ previewError !== null && jsx.jsx("div", { style: { color: "var(--dsw-alias-danger, #e5484d)", fontSize: 12, marginTop: 6 }, children: previewError }),
208
723
  writable && jsx.jsx("button", { type: "button", onClick: addVoice, style: { cursor: "pointer", border: "1px dashed var(--dsw-alias-border-l2)", background: "0 0", color: "var(--dsw-alias-label-secondary)", borderRadius: 8, padding: "4px 10px", fontSize: 13 }, children: t("voice.add") }),
724
+ jsx.jsx("div", { style: { borderTop: "1px solid var(--dsw-alias-border-l2)", marginTop: 14, paddingTop: 8 }, children: [
725
+ jsx.jsx("div", { style: { fontWeight: 600, fontSize: 13, color: "var(--dsw-alias-label-primary)" }, children: t("market.title") }),
726
+ jsx.jsx("div", { style: { color: "var(--dsw-alias-label-tertiary)", fontSize: 12, marginTop: 2 }, children: t("market.desc") }),
727
+ market === null
728
+ ? jsx.jsx("button", { type: "button", disabled: marketLoading, onClick: marketLoad, style: { cursor: "pointer", border: "1px solid var(--dsw-alias-border-l2)", background: "0 0", color: "var(--dsw-alias-label-secondary)", borderRadius: 8, padding: "4px 10px", fontSize: 13, marginTop: 8 }, children: marketLoading ? t("market.loading") : t("market.load") })
729
+ : jsx.jsxs(react.Fragment, { children: [
730
+ jsx.jsxs("div", { style: { display: "flex", alignItems: "center", gap: 8, marginTop: 8, fontSize: 12 }, children: [
731
+ jsx.jsx("span", { style: { color: market.trusted ? "var(--dsw-alias-success, #30a46c)" : "var(--dsw-alias-danger, #e5484d)", fontWeight: 600 }, children: market.source === "bundled" ? t("market.sourceBundled") + " · " + t("market.trusted") : t("market.sourceRemote") + " · " + t("market.untrusted") }),
732
+ jsx.jsx("span", { style: { color: "var(--dsw-alias-label-tertiary)" }, children: "v" + market.version }),
733
+ jsx.jsx("button", { type: "button", onClick: marketLoad, style: linkBtn, children: t("market.refresh") })
734
+ ] }),
735
+ (market.voices || []).map((pkg) => jsx.jsxs("div", { style: { border: "1px solid var(--dsw-alias-border-l2)", borderRadius: 8, padding: 8, marginBottom: 8, marginTop: 8 }, children: [
736
+ jsx.jsxs("div", { style: { display: "flex", alignItems: "center", gap: 8 }, children: [
737
+ jsx.jsx("span", { style: { fontWeight: 600, fontSize: 13, color: "var(--dsw-alias-label-primary)" }, children: pkg.name }),
738
+ pkg.installed && jsx.jsx("span", { style: { color: "var(--dsw-alias-success, #30a46c)", fontSize: 11 }, children: t("market.installed") })
739
+ ] }),
740
+ jsx.jsx("div", { style: { color: "var(--dsw-alias-label-tertiary)", fontSize: 11, marginTop: 2 }, children: (pkg.author || "—") + " · " + pkg.license }),
741
+ jsx.jsxs("div", { style: { display: "flex", gap: 10, marginTop: 6, alignItems: "center" }, children: [
742
+ jsx.jsx("button", { type: "button", onClick: () => marketPreview(pkg), style: linkBtn, children: player.isActive("market:" + pkg.id) ? t("stop") : t("voice.preview") }),
743
+ pkg.installed
744
+ ? jsx.jsx("button", { type: "button", disabled: !writable || marketBusy === "remove:" + pkg.id, onClick: () => setConfirmRemove({ id: pkg.id, name: pkg.name }), style: dangerBtn, children: marketBusy === "remove:" + pkg.id ? "…" : t("market.uninstall") })
745
+ : jsx.jsx("button", { type: "button", disabled: !writable || marketBusy === "install:" + pkg.id, onClick: () => marketInstall(pkg, false), style: linkBtn, children: marketBusy === "install:" + pkg.id ? "…" : t("market.install") })
746
+ ] })
747
+ ] }, pkg.id))
748
+ ] }),
749
+ confirmInstall !== null && jsx.jsx("div", { style: { border: "1px solid var(--dsw-alias-warning,#f5a524)", borderRadius: 8, padding: 8, marginTop: 8 }, children: [
750
+ jsx.jsx("div", { style: { fontWeight: 600, fontSize: 13, color: "var(--dsw-alias-label-primary)" }, children: t("market.confirmInstallTitle") }),
751
+ jsx.jsx("div", { style: { color: "var(--dsw-alias-label-secondary)", fontSize: 12, marginTop: 4 }, children: t("market.confirmInstallBody") }),
752
+ jsx.jsx("div", { style: { color: "var(--dsw-alias-label-tertiary)", fontSize: 12, marginTop: 2 }, children: (confirmInstall.author || "—") + " · " + confirmInstall.license }),
753
+ jsx.jsxs("div", { style: { display: "flex", gap: 10, marginTop: 8 }, children: [
754
+ jsx.jsx("button", { type: "button", onClick: () => marketInstall(confirmInstall, true), style: primaryBtn, children: t("market.confirm") }),
755
+ jsx.jsx("button", { type: "button", onClick: () => setConfirmInstall(null), style: linkBtn, children: t("market.cancel") })
756
+ ] })
757
+ ] }),
758
+ confirmRemove !== null && jsx.jsx("div", { style: { border: "1px solid var(--dsw-alias-border-l2)", borderRadius: 8, padding: 8, marginTop: 8 }, children: [
759
+ jsx.jsx("div", { style: { fontWeight: 600, fontSize: 13, color: "var(--dsw-alias-label-primary)" }, children: t("market.confirmRemoveTitle") + " " + confirmRemove.name }),
760
+ jsx.jsx("div", { style: { color: "var(--dsw-alias-label-secondary)", fontSize: 12, marginTop: 4 }, children: t("market.confirmRemoveBody") }),
761
+ jsx.jsxs("div", { style: { display: "flex", gap: 10, marginTop: 8 }, children: [
762
+ jsx.jsx("button", { type: "button", onClick: () => marketRemoveById(confirmRemove.id, true), style: primaryBtn, children: t("market.removeDelete") }),
763
+ jsx.jsx("button", { type: "button", onClick: () => marketRemoveById(confirmRemove.id, false), style: linkBtn, children: t("market.removeKeep") }),
764
+ jsx.jsx("button", { type: "button", onClick: () => setConfirmRemove(null), style: linkBtn, children: t("market.cancel") })
765
+ ] })
766
+ ] }),
767
+ marketError !== null && jsx.jsx("div", { style: { color: "var(--dsw-alias-danger, #e5484d)", fontSize: 12, marginTop: 6 }, children: marketError })
768
+ ] }),
209
769
  jsx.jsx("div", { style: { display: "flex", gap: 8, marginTop: 12, alignItems: "center" }, children: [
210
770
  jsx.jsx("button", { type: "button", disabled: !writable || saving, onClick: save, style: { cursor: "pointer", border: "none", borderRadius: 14, height: 28, padding: "0 14px", fontSize: 13, background: "var(--dsw-alias-button-primary-fill)", color: "var(--dsw-alias-label-primary-foreground)" }, children: saving ? t("saving") : t("save") }),
211
771
  dirty && jsx.jsx("button", { type: "button", onClick: () => setDraft(structuredClone(value)), style: { cursor: "pointer", border: "none", background: "0 0", color: "var(--dsw-alias-label-tertiary)", fontSize: 13, padding: 0 }, children: t("discard") }),
@@ -261,7 +821,7 @@ window.__ModuleLoader__.load({
261
821
  };
262
822
  const rowStyle = { display: "flex", alignItems: "center", gap: 10, marginTop: 12 };
263
823
  const statusText = status.phase === "on" ? t("engineStarting") : status.phase === "off" ? t("engineStopping") : status.running ? t("engineRunning") : t("engineStopped");
264
- return jsx.jsxs("div", { children: [
824
+ return jsx.jsx(GsvErrorBoundary, { children: jsx.jsxs("div", { children: [
265
825
  jsx.jsx("div", { style: { fontWeight: 600, fontSize: 14, color: "var(--dsw-alias-label-primary)" }, children: t("engineTitle") }),
266
826
  jsx.jsx("div", { style: { color: "var(--dsw-alias-label-tertiary)", fontSize: 12, marginTop: 2 }, children: t("engineDesc") }),
267
827
  jsx.jsxs("div", { style: rowStyle, children: [
@@ -274,7 +834,7 @@ window.__ModuleLoader__.load({
274
834
  status.message !== null && jsx.jsx("div", { style: { color: "var(--dsw-alias-danger, #e5484d)", fontSize: 12, marginTop: 6 }, children: status.message }),
275
835
  jsx.jsx("div", { style: { borderTop: "1px solid var(--dsw-alias-border-l2)", marginTop: 16, paddingTop: 8 }, children: jsx.jsx(TtsSettingsCard, { scope, t }) }),
276
836
  jsx.jsx("div", { style: { borderTop: "1px solid var(--dsw-alias-border-l2)", marginTop: 16, paddingTop: 8 }, children: jsx.jsx(HelpBlock, { t }) })
277
- ] });
837
+ ] }) });
278
838
  }
279
839
 
280
840
  // ─── 帮助文档(渲染在"声音设置"内部) ───
@@ -298,8 +858,9 @@ window.__ModuleLoader__.load({
298
858
  " · 参考音频路径:目标音色的参考音频(决定声音像谁),如 D:\\GSV\\GSV-TTS-Lite\\examples\\laffey.mp3",
299
859
  " · 提示音频路径:语调/情感参考音频,如 D:\\GSV\\GSV-TTS-Lite\\examples\\AnAn.ogg",
300
860
  " · 提示文本:提示音频对应的文字(引擎不支持留空自动转写,请务必填写)",
301
- "3. 点击“保存”,立即生效,无需重启",
302
- "4. 默认音色留空则使用列表第一个音色"
861
+ "3. 可先点击每条音色旁的“试听”,用固定文案听效果(未保存也能试听);“全部试听(循环)”会循环播放所有音色,方便对比",
862
+ "4. 点击“保存”,立即生效,无需重启",
863
+ "5. 默认音色留空则使用列表第一个音色"
303
864
  ] },
304
865
  { title: "三、常见问题", steps: [
305
866
  "· 引擎未启动:打开本页顶部的开关启动(模型加载约 15~90 秒)",
@@ -321,6 +882,51 @@ window.__ModuleLoader__.load({
321
882
  ] });
322
883
  }
323
884
 
885
+ // ─── 自动朗读轮询(常驻,仅 autoPlay 开启时生效;热更新读取最新配置) ───
886
+ let autoplayLastSeq = 0;
887
+ let autoplayInFlight = false;
888
+ async function pollAutoPlay(scope) {
889
+ let cfg;
890
+ try {
891
+ const snap = scope.getSnapshot();
892
+ cfg = (snap && snap.value) || {};
893
+ } catch {
894
+ return;
895
+ }
896
+ if (!cfg.autoPlay) return;
897
+ if (autoplayInFlight) return;
898
+ autoplayInFlight = true;
899
+ try {
900
+ const resp = await fetch("/dsh-gsv-tts/autoplay/poll", {
901
+ method: "POST",
902
+ headers: { "Content-Type": "application/json" },
903
+ body: JSON.stringify({ sinceSeq: autoplayLastSeq })
904
+ });
905
+ const data = await resp.json().catch(() => ({}));
906
+ if (!resp.ok || typeof data.seq !== "number" || data.seq <= autoplayLastSeq) return;
907
+ autoplayLastSeq = data.seq;
908
+ if (!data.text) return;
909
+ const playing = player.state === "playing" || player.state === "paused" || player.state === "loading";
910
+ const speakResp = await fetch("/dsh-gsv-tts/autoplay/speak", {
911
+ method: "POST",
912
+ headers: { "Content-Type": "application/json" },
913
+ body: JSON.stringify({ seq: data.seq })
914
+ });
915
+ const audio = await speakResp.json().catch(() => ({}));
916
+ if (!speakResp.ok || !audio.segments || audio.segments.length === 0) return;
917
+ if (playing && cfg.interruptOnNew === false) {
918
+ // 不打断:排入待播队列,当前队列读完后自动补读(避免叠音且不丢消息)
919
+ player.enqueue("autoplay:" + data.seq, audio.segments);
920
+ } else {
921
+ player.play("autoplay:" + data.seq, audio.segments);
922
+ }
923
+ } catch {
924
+ // 网络抖动 / 引擎未启动:静默,下一轮再试
925
+ } finally {
926
+ autoplayInFlight = false;
927
+ }
928
+ }
929
+
324
930
  // ─── 插件主体 ───
325
931
  const inject = ["slots", "locale", "settingsScope"];
326
932
  function apply(ctx) {
@@ -344,12 +950,29 @@ window.__ModuleLoader__.load({
344
950
  order: 20,
345
951
  label: () => t("engineNav"),
346
952
  locale: NS,
347
- inject: () => ({ scope: ctx.settingsScope.bind({ namespace: "dsh-gsv-tts" }), t: ctx.locale.bind(NS) })
953
+ inject: () => {
954
+ // 防御:settingsScope.bind 异常时给一个兜底 scope,避免宿主渲染整段崩溃
955
+ let scope;
956
+ try {
957
+ scope = ctx.settingsScope.bind({ namespace: "dsh-gsv-tts" });
958
+ } catch (e) {
959
+ scope = { getSnapshot: () => ({ error: String((e && e.message) || e) }), subscribe: () => () => {} };
960
+ }
961
+ return { scope, t: ctx.locale.bind(NS) };
962
+ }
348
963
  }, EngineSection));
964
+ // 自动朗读轮询器:每 2s 轻量探测一次新回复(autoPlay 关闭时无网络请求)
965
+ const scope = ctx.settingsScope.bind({ namespace: "dsh-gsv-tts" });
966
+ ctx.effect(() => {
967
+ const timer = setInterval(() => pollAutoPlay(scope), 2000);
968
+ return () => clearInterval(timer);
969
+ }, "gsv-tts: autoplay");
349
970
  }
350
971
 
351
972
  exports.apply = apply;
352
973
  exports.inject = inject;
974
+ // 额外导出播放器单例:仅供自动化测试驱动,宿主仅使用 apply/inject
975
+ exports.player = player;
353
976
  return module.exports;
354
977
  }
355
978
  });