dsh-mimo-speak 0.0.0-stage → 0.1.2

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.
Files changed (109) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +197 -2
  3. package/README.zh.md +166 -0
  4. package/cordis.patch.yml +20 -0
  5. package/icon.svg +6 -0
  6. package/lib/client.js +3607 -0
  7. package/lib/client.js.map +1 -0
  8. package/lib/node/brief.d.ts +23 -0
  9. package/lib/node/brief.js +110 -0
  10. package/lib/node/brief.js.map +1 -0
  11. package/lib/node/client/BundleConfigCard.d.ts +15 -0
  12. package/lib/node/client/BundleConfigCard.js +22 -0
  13. package/lib/node/client/BundleConfigCard.js.map +1 -0
  14. package/lib/node/client/PlayerBar.d.ts +45 -0
  15. package/lib/node/client/PlayerBar.js +83 -0
  16. package/lib/node/client/PlayerBar.js.map +1 -0
  17. package/lib/node/client/SettingsSectionCard.d.ts +14 -0
  18. package/lib/node/client/SettingsSectionCard.js +19 -0
  19. package/lib/node/client/SettingsSectionCard.js.map +1 -0
  20. package/lib/node/client/SpeakAction.d.ts +32 -0
  21. package/lib/node/client/SpeakAction.js +651 -0
  22. package/lib/node/client/SpeakAction.js.map +1 -0
  23. package/lib/node/client/SpeakerIcon.d.ts +11 -0
  24. package/lib/node/client/SpeakerIcon.js +5 -0
  25. package/lib/node/client/SpeakerIcon.js.map +1 -0
  26. package/lib/node/client/TtsSettingsForm.d.ts +27 -0
  27. package/lib/node/client/TtsSettingsForm.js +164 -0
  28. package/lib/node/client/TtsSettingsForm.js.map +1 -0
  29. package/lib/node/client/api.d.ts +89 -0
  30. package/lib/node/client/api.js +247 -0
  31. package/lib/node/client/api.js.map +1 -0
  32. package/lib/node/client/audio-bus.d.ts +29 -0
  33. package/lib/node/client/audio-bus.js +91 -0
  34. package/lib/node/client/audio-bus.js.map +1 -0
  35. package/lib/node/client/chat-text.d.ts +32 -0
  36. package/lib/node/client/chat-text.js +90 -0
  37. package/lib/node/client/chat-text.js.map +1 -0
  38. package/lib/node/client/highlight.d.ts +45 -0
  39. package/lib/node/client/highlight.js +198 -0
  40. package/lib/node/client/highlight.js.map +1 -0
  41. package/lib/node/client/index.d.ts +26 -0
  42. package/lib/node/client/index.js +89 -0
  43. package/lib/node/client/index.js.map +1 -0
  44. package/lib/node/client/locales.d.ts +19 -0
  45. package/lib/node/client/locales.js +180 -0
  46. package/lib/node/client/locales.js.map +1 -0
  47. package/lib/node/client/panel-visibility.d.ts +24 -0
  48. package/lib/node/client/panel-visibility.js +16 -0
  49. package/lib/node/client/panel-visibility.js.map +1 -0
  50. package/lib/node/client/settings-controller.d.ts +116 -0
  51. package/lib/node/client/settings-controller.js +201 -0
  52. package/lib/node/client/settings-controller.js.map +1 -0
  53. package/lib/node/client/settings-registration.d.ts +24 -0
  54. package/lib/node/client/settings-registration.js +21 -0
  55. package/lib/node/client/settings-registration.js.map +1 -0
  56. package/lib/node/client/slots.d.ts +48 -0
  57. package/lib/node/client/slots.js +15 -0
  58. package/lib/node/client/slots.js.map +1 -0
  59. package/lib/node/client/speech-cache.d.ts +59 -0
  60. package/lib/node/client/speech-cache.js +68 -0
  61. package/lib/node/client/speech-cache.js.map +1 -0
  62. package/lib/node/client/split-speech.d.ts +20 -0
  63. package/lib/node/client/split-speech.js +100 -0
  64. package/lib/node/client/split-speech.js.map +1 -0
  65. package/lib/node/client/status.d.ts +28 -0
  66. package/lib/node/client/status.js +60 -0
  67. package/lib/node/client/status.js.map +1 -0
  68. package/lib/node/client/stream-dispose.d.ts +119 -0
  69. package/lib/node/client/stream-dispose.js +249 -0
  70. package/lib/node/client/stream-dispose.js.map +1 -0
  71. package/lib/node/client/styles.d.ts +19 -0
  72. package/lib/node/client/styles.js +176 -0
  73. package/lib/node/client/styles.js.map +1 -0
  74. package/lib/node/client/use-audio-player.d.ts +44 -0
  75. package/lib/node/client/use-audio-player.js +102 -0
  76. package/lib/node/client/use-audio-player.js.map +1 -0
  77. package/lib/node/client/use-audio-queue.d.ts +44 -0
  78. package/lib/node/client/use-audio-queue.js +151 -0
  79. package/lib/node/client/use-audio-queue.js.map +1 -0
  80. package/lib/node/client/use-stream-player.d.ts +41 -0
  81. package/lib/node/client/use-stream-player.js +60 -0
  82. package/lib/node/client/use-stream-player.js.map +1 -0
  83. package/lib/node/edge-tts.d.ts +21 -0
  84. package/lib/node/edge-tts.js +111 -0
  85. package/lib/node/edge-tts.js.map +1 -0
  86. package/lib/node/index.d.ts +97 -0
  87. package/lib/node/index.js +463 -0
  88. package/lib/node/index.js.map +1 -0
  89. package/lib/node/normalize.d.ts +30 -0
  90. package/lib/node/normalize.js +72 -0
  91. package/lib/node/normalize.js.map +1 -0
  92. package/lib/node/settings.d.ts +186 -0
  93. package/lib/node/settings.js +74 -0
  94. package/lib/node/settings.js.map +1 -0
  95. package/lib/node/summarize.d.ts +29 -0
  96. package/lib/node/summarize.js +131 -0
  97. package/lib/node/summarize.js.map +1 -0
  98. package/lib/node/tool.d.ts +54 -0
  99. package/lib/node/tool.js +123 -0
  100. package/lib/node/tool.js.map +1 -0
  101. package/lib/node/tts.d.ts +127 -0
  102. package/lib/node/tts.js +361 -0
  103. package/lib/node/tts.js.map +1 -0
  104. package/lib/node/wav.d.ts +32 -0
  105. package/lib/node/wav.js +63 -0
  106. package/lib/node/wav.js.map +1 -0
  107. package/locale/en.json +6 -0
  108. package/locale/zh.json +6 -0
  109. package/package.json +122 -4
package/lib/client.js ADDED
@@ -0,0 +1,3607 @@
1
+ window.__ModuleLoader__.load({
2
+ id: "dsh-mimo-speak",
3
+ factory: (require) => {
4
+ var module = { exports: {} };
5
+ var exports = module.exports;
6
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
7
+ let react = require("react");
8
+ let _deepseek_ai_dsh_client_ui_primitives = require("@deepseek-ai/dsh-client-ui-primitives");
9
+ let react_jsx_runtime = require("react/jsx-runtime");
10
+ let _deepseek_ai_dsh_client_store = require("@deepseek-ai/dsh-client-store");
11
+ // src/settings.ts
12
+ /**
13
+ * Settings and route vocabulary shared by the Host and browser halves.
14
+ *
15
+ * Both bundles inline this file, so it must stay pure: constants and types
16
+ * only, no Node or DOM APIs. The namespace is the profile entry id the bundle
17
+ * patch inserts (`cordis.patch.yml`), and the route paths are the seam the two
18
+ * halves meet on.
19
+ * @module dsh-mimo-speak/settings
20
+ */
21
+ /** Settings namespace: the profile entry id of this plugin's loader row. */
22
+ const MIMOSPEAK_NAMESPACE = "mimo-speak";
23
+ /**
24
+ * Key this plugin's configuration card registers under on the Plugins page's
25
+ * `plugins.bundle.config` keyed slot: the bundle's npm package name, which is
26
+ * the keying convention the Plugins page fixes for bundle-owned configuration
27
+ * (the page dispatches with `entryKey: pkg.name`).
28
+ */
29
+ const MIMOSPEAK_PACKAGE_KEY = "dsh-mimo-speak";
30
+ /** Route prefix owned by this plugin on `ctx.webServer`. */
31
+ const MIMOSPEAK_API_PREFIX = "/api/mimo-speak";
32
+ /** `GET` route reporting the resolved engine configuration without secrets. */
33
+ const MIMOSPEAK_STATUS_PATH = `${MIMOSPEAK_API_PREFIX}/status`;
34
+ /** `POST` route synthesizing one text into WAV audio. */
35
+ const MIMOSPEAK_SYNTHESIZE_PATH = `${MIMOSPEAK_API_PREFIX}/synthesize`;
36
+ /** `POST` route streaming one text as raw PCM chunks (SSE). */
37
+ const MIMOSPEAK_SYNTHESIZE_STREAM_PATH = `${MIMOSPEAK_API_PREFIX}/synthesize-stream`;
38
+ /** `POST` route running a short round-trip health check against the engine. */
39
+ const MIMOSPEAK_TEST_PATH = `${MIMOSPEAK_API_PREFIX}/test`;
40
+ /** POST text → a short spoken summary (used by the brief read scope). */
41
+ const MIMOSPEAK_SUMMARY_PATH = `${MIMOSPEAK_API_PREFIX}/summary`;
42
+ /** MiMo platform endpoint base; `/chat/completions` is appended. */
43
+ const DEFAULT_BASE_URL = "https://api.xiaomimimo.com/v1";
44
+ /** MiMo TTS model id. */
45
+ const DEFAULT_MODEL = "mimo-v2.5-tts";
46
+ /** Preset voice used when no clone sample is configured. */
47
+ const DEFAULT_VOICE = "mimo_default";
48
+ /** Longest text one synthesis accepts, in characters. */
49
+ const DEFAULT_MAX_CHARS = 2e3;
50
+ const DEFAULT_FALLBACK_ENGINE = "none";
51
+ /** Default Edge-TTS voice: Xiaoxiao, the standard mainland-Chinese female voice. */
52
+ const DEFAULT_EDGE_VOICE = "zh-CN-XiaoxiaoNeural";
53
+ const DEFAULT_READ_SCOPE = "smart";
54
+ /** Sample sentence the Plugins-page card's audition button speaks. */
55
+ const AUDITION_TEXT = "你好,这是 MiMo 语音合成的试听效果。";
56
+ // src/client/settings-registration.ts
57
+ /**
58
+ * Registration facts for the two configuration surfaces. Kept as data so the
59
+ * slot wiring can be asserted without mounting React or a DSH client.
60
+ * @module dsh-mimo-speak/client/settings-registration
61
+ */
62
+ /** List-slot id of the MiMo page in DSH global Settings. */
63
+ const SETTINGS_SECTION_ID = "mimo-speak-settings";
64
+ /** DOM id prefixes: the Plugins card keeps its historic ids; Settings differs. */
65
+ const PLUGINS_FORM_ID_PREFIX = "mimo-speak";
66
+ const SETTINGS_FORM_ID_PREFIX = "mimo-speak-settings";
67
+ // src/client/api.ts
68
+ /**
69
+ * Browser → Host calls for speech synthesis.
70
+ *
71
+ * Both halves share their route vocabulary through `src/settings.ts`; the
72
+ * browser sends text and receives WAV bytes, so the MiMo API key never enters
73
+ * the page. Failures arrive as stable codes the UI maps to localized copy.
74
+ * @module dsh-mimo-speak/client/api
75
+ */
76
+ /** A synthesize failure carrying the Host's stable code. */
77
+ var TtsClientError = class extends Error {
78
+ code;
79
+ /**
80
+ * @param code - stable failure code; `generic` when the Host gave none.
81
+ * @param message - Host-supplied detail, safe to show.
82
+ */
83
+ constructor(code, message) {
84
+ super(message);
85
+ this.code = code;
86
+ this.name = "TtsClientError";
87
+ }
88
+ };
89
+ /**
90
+ * Read the answering engine off an audio response.
91
+ *
92
+ * The Host answers MiMo synthesis as `audio/wav` and the Edge fallback as
93
+ * `audio/mpeg`, so the content type is the honest signal: the client can say
94
+ * "the fallback voice is reading this" instead of switching voices silently.
95
+ * @param blob - the audio response body.
96
+ * @returns the engine that produced it.
97
+ */
98
+ function speechEngineOf(blob) {
99
+ return blob.type.includes("mpeg") ? "edge" : "mimo";
100
+ }
101
+ /**
102
+ * Ask the Host for a short spoken summary of one reply.
103
+ *
104
+ * Used by the brief read scope: summarizing first and speaking the summary is
105
+ * what "简要播报" should mean, instead of mechanically picking sentences.
106
+ * @param text - the reply text to condense.
107
+ * @param signal - aborts the request when the reader stops.
108
+ * @returns the summary text.
109
+ */
110
+ async function requestSummary(text, signal) {
111
+ let response;
112
+ try {
113
+ response = await fetch(MIMOSPEAK_SUMMARY_PATH, {
114
+ method: "POST",
115
+ headers: { "content-type": "application/json" },
116
+ body: JSON.stringify({ text }),
117
+ ...signal === void 0 ? {} : { signal }
118
+ });
119
+ } catch (cause) {
120
+ throw new TtsClientError("generic", cause instanceof Error ? cause.message : String(cause));
121
+ }
122
+ if (!response.ok) {
123
+ let code = "generic";
124
+ let message = `summary request failed with HTTP ${response.status}`;
125
+ try {
126
+ const body = await response.json();
127
+ if (typeof body.error?.code === "string") code = body.error.code;
128
+ if (typeof body.error?.message === "string") message = body.error.message;
129
+ } catch {}
130
+ throw new TtsClientError(code, message);
131
+ }
132
+ const body = await response.json();
133
+ if (typeof body.summary !== "string" || body.summary.trim() === "") throw new TtsClientError("generic", "The summary route returned no text.");
134
+ return body.summary.trim();
135
+ }
136
+ async function fetchTtsStatus() {
137
+ const response = await fetch(MIMOSPEAK_STATUS_PATH, {
138
+ method: "GET",
139
+ cache: "no-store"
140
+ });
141
+ if (!response.ok) throw new TtsClientError("generic", `status request failed with HTTP ${response.status}`);
142
+ return await response.json();
143
+ }
144
+ /**
145
+ * Synthesize one text into playable WAV audio.
146
+ * @param request - text and optional style/voice overrides (settings-page
147
+ * audition previews unsaved values through these).
148
+ * @param signal - aborts the request when the reader stops.
149
+ * @returns the WAV payload as a Blob ready for `URL.createObjectURL`.
150
+ * @throws {TtsClientError} when the Host refuses or the transport fails.
151
+ */
152
+ async function requestSpeech(request, signal) {
153
+ let response;
154
+ try {
155
+ response = await fetch(MIMOSPEAK_SYNTHESIZE_PATH, {
156
+ method: "POST",
157
+ headers: { "content-type": "application/json" },
158
+ body: JSON.stringify(request),
159
+ ...signal === void 0 ? {} : { signal }
160
+ });
161
+ } catch (error) {
162
+ throw new TtsClientError("generic", error instanceof Error ? error.message : String(error));
163
+ }
164
+ if (response.ok) return await response.blob();
165
+ let code = "generic";
166
+ let message = `synthesize request failed with HTTP ${response.status}`;
167
+ try {
168
+ const body = await response.json();
169
+ if (typeof body.error?.code === "string") code = body.error.code;
170
+ if (typeof body.error?.message === "string") message = body.error.message;
171
+ } catch {}
172
+ throw new TtsClientError(code, message);
173
+ }
174
+ /**
175
+ * Stream one text as raw PCM chunks and feed each chunk to `onChunk`.
176
+ *
177
+ * The Host answers with `text/event-stream`; every `data:` line carries one
178
+ * JSON object with either a `pcm` base64 payload, a terminal `done`, or an
179
+ * `error`. The browser decodes and schedules each chunk as it arrives, so the
180
+ * first chunk is playable before the rest of the utterance exists.
181
+ * @param request - text and optional style/voice overrides.
182
+ * @param onChunk - invoked once per decoded PCM chunk, in arrival order.
183
+ * @param signal - aborts the request mid-stream when the reader stops.
184
+ * @returns the terminal stats event.
185
+ * @throws {TtsClientError} when the Host refuses or the transport fails.
186
+ */
187
+ async function requestSpeechStream(request, onChunk, signal) {
188
+ let response;
189
+ try {
190
+ response = await fetch(MIMOSPEAK_SYNTHESIZE_STREAM_PATH, {
191
+ method: "POST",
192
+ headers: { "content-type": "application/json" },
193
+ body: JSON.stringify(request),
194
+ ...signal === void 0 ? {} : { signal }
195
+ });
196
+ } catch (error) {
197
+ throw new TtsClientError("generic", error instanceof Error ? error.message : String(error));
198
+ }
199
+ if (!response.ok) {
200
+ let code = "generic";
201
+ let message = `stream request failed with HTTP ${response.status}`;
202
+ try {
203
+ const failure = await response.json();
204
+ if (typeof failure.error?.code === "string") code = failure.error.code;
205
+ if (typeof failure.error?.message === "string") message = failure.error.message;
206
+ } catch {}
207
+ throw new TtsClientError(code, message);
208
+ }
209
+ const body = response.body;
210
+ if (body === null) throw new TtsClientError("generic", "stream request returned no body.");
211
+ const reader = body.getReader();
212
+ const decoder = new TextDecoder();
213
+ let buffer = "";
214
+ try {
215
+ for (;;) {
216
+ const { done, value } = await reader.read();
217
+ if (done) break;
218
+ buffer += decoder.decode(value, { stream: true });
219
+ let newlineAt = buffer.indexOf("\n");
220
+ while (newlineAt !== -1) {
221
+ const line = buffer.slice(0, newlineAt).trim();
222
+ buffer = buffer.slice(newlineAt + 1);
223
+ newlineAt = buffer.indexOf("\n");
224
+ if (!line.startsWith("data:")) continue;
225
+ const payloadText = line.slice(5).trim();
226
+ if (payloadText === "") continue;
227
+ let payload;
228
+ try {
229
+ payload = JSON.parse(payloadText);
230
+ } catch {
231
+ continue;
232
+ }
233
+ if (payload.error !== void 0) throw new TtsClientError(typeof payload.error.code === "string" ? payload.error.code : "generic", typeof payload.error.message === "string" ? payload.error.message : "stream failed");
234
+ if (typeof payload.pcm === "string" && payload.pcm !== "") {
235
+ const binary = atob(payload.pcm);
236
+ const bytes = new Uint8Array(binary.length);
237
+ for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
238
+ onChunk(bytes);
239
+ }
240
+ if (payload.done === true) return;
241
+ }
242
+ }
243
+ } finally {
244
+ reader.releaseLock();
245
+ }
246
+ }
247
+ /**
248
+ * Run the Host-side round-trip health check.
249
+ * @returns which engine answered, its latency, and its voice.
250
+ * @throws {TtsClientError} when the Host refuses or both engines fail.
251
+ */
252
+ async function requestSpeechTest() {
253
+ let response;
254
+ try {
255
+ response = await fetch(MIMOSPEAK_TEST_PATH, { method: "POST" });
256
+ } catch (error) {
257
+ throw new TtsClientError("generic", error instanceof Error ? error.message : String(error));
258
+ }
259
+ if (response.ok) return await response.json();
260
+ let code = "generic";
261
+ let message = `test request failed with HTTP ${response.status}`;
262
+ try {
263
+ const body = await response.json();
264
+ if (typeof body.error?.code === "string") code = body.error.code;
265
+ if (typeof body.error?.message === "string") message = body.error.message;
266
+ } catch {}
267
+ throw new TtsClientError(code, message);
268
+ }
269
+ // src/brief.ts
270
+ /**
271
+ * Extractive briefing for long replies.
272
+ *
273
+ * A spoken reply does not need every caveat a written one carries: the point of
274
+ * read-aloud is to know what happened. The rule is deliberately mechanical, so
275
+ * the result is predictable and fits in one sentence:
276
+ *
277
+ * **一段一行,只念每段的第一句;整篇只有一段时念前几句。**
278
+ *
279
+ * Table rows, bare links, code notes and horizontal rules are skipped, because
280
+ * reading them aloud conveys nothing. Nothing is invented and no model is
281
+ * called, so a brief always agrees with the reply it came from.
282
+ * @module dsh-mimo-speak/brief
283
+ */
284
+ /** Terminators that really end a sentence. */
285
+ const STRONG_TERMINATORS = /* @__PURE__ */ new Set([
286
+ "。",
287
+ "!",
288
+ "?",
289
+ ";",
290
+ "!",
291
+ "?",
292
+ ";",
293
+ "…"
294
+ ]);
295
+ /** Leading decoration that exists for the screen, not the ear. */
296
+ const DECORATION = /^[\s#>]*[-+*•·]?\s*/u;
297
+ /** Whole lines that carry no speakable meaning in a brief. */
298
+ const SKIPPED_LINE = /^(?:-{3,}|\*{3,}|_{3,}|代码略[。.]?|code omitted[.]?)$/iu;
299
+ /**
300
+ * Split one block into sentences, keeping each terminator.
301
+ * @param block - one non-empty line of speakable text.
302
+ * @returns its sentences, in order.
303
+ */
304
+ function sentencesOf(block) {
305
+ const out = [];
306
+ let buffer = "";
307
+ for (const character of block) {
308
+ buffer += character;
309
+ if (STRONG_TERMINATORS.has(character)) {
310
+ out.push(buffer.trim());
311
+ buffer = "";
312
+ }
313
+ }
314
+ if (buffer.trim() !== "") out.push(buffer.trim());
315
+ return out.filter((sentence) => sentence !== "");
316
+ }
317
+ /**
318
+ * Condense text into its opening points.
319
+ * @param text - speakable plain text (already markdown-normalized).
320
+ * @param limit - soft character budget for the result.
321
+ * @param maxSentences - hard cap on spoken sentences.
322
+ * @param prefix - optional lead-in spoken before the brief (e.g. 「简要播报」).
323
+ * @returns the briefed text; the input itself when it is already short.
324
+ */
325
+ function briefText(text, limit = 260, maxSentences = 6, prefix = "") {
326
+ const blocks = text.split("\n").filter((line) => {
327
+ const trimmed = line.trim();
328
+ if (trimmed === "") return false;
329
+ if (trimmed.startsWith("|")) return false;
330
+ if (SKIPPED_LINE.test(trimmed)) return false;
331
+ if (/^https?:\/\/\S+$/u.test(trimmed)) return false;
332
+ return true;
333
+ }).map((line) => line.replace(/(\*\*|__|~~)/gu, "").replace(/[*_]([^*_\n]+)[*_]/gu, "$1").replace(DECORATION, "").trim()).filter((line) => line !== "");
334
+ if (blocks.length === 0) return "";
335
+ const whole = blocks.join("\n");
336
+ if (whole.length <= limit) return whole;
337
+ const picks = [];
338
+ let used = 0;
339
+ /** @returns whether another sentence still fits. */
340
+ const take = (sentence) => {
341
+ if (picks.length > 0 && used + sentence.length > limit) return false;
342
+ picks.push(sentence);
343
+ used += sentence.length;
344
+ return picks.length < maxSentences;
345
+ };
346
+ if (blocks.length === 1) {
347
+ for (const sentence of sentencesOf(blocks[0])) if (!take(sentence)) break;
348
+ } else for (const block of blocks) {
349
+ const first = sentencesOf(block)[0];
350
+ if (first === void 0) continue;
351
+ if (!take(first)) break;
352
+ }
353
+ const body = picks.join("");
354
+ return prefix === "" ? body : `${prefix}${body}`;
355
+ }
356
+ // src/normalize.ts
357
+ /**
358
+ * Markdown → speakable-text normalization applied Host-side before synthesis.
359
+ *
360
+ * The MiMo TTS endpoint speaks whatever it is given; assistant replies are
361
+ * Markdown, and reading decoration, fences, and URLs aloud is noise. The
362
+ * normalization here is deliberately conservative: it removes presentation
363
+ * markup while keeping the words, and it never invents text.
364
+ * @module dsh-mimo-speak/normalize
365
+ */
366
+ /** Replacement spoken for a fenced code block (reading code aloud is noise). */
367
+ const CODE_FENCE_NOTE = "代码略。";
368
+ /**
369
+ * Convert assistant Markdown into text worth speaking aloud.
370
+ *
371
+ * Removes fenced code (kept as a short spoken note), inline-code markers,
372
+ * heading/list/quote markers, emphasis markers, tables (cells joined with
373
+ * commas), images, HTML tags, and link targets (the anchor text stays).
374
+ * @param markdown - raw assistant reply text.
375
+ * @returns plain text suitable for TTS input.
376
+ */
377
+ function toSpeakableText(markdown) {
378
+ let text = markdown;
379
+ text = text.replace(/```[\s\S]*?```/g, `\n${CODE_FENCE_NOTE}\n`);
380
+ text = text.replace(/~~~[\s\S]*?~~~/g, `\n${CODE_FENCE_NOTE}\n`);
381
+ text = text.replace(/`([^`\n]*)`/g, "$1");
382
+ text = text.replace(/!\[[^\]]*\]\([^)]*\)/g, "");
383
+ text = text.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1");
384
+ text = text.replace(/\[([^\]]*)\]\[[^\]]*\]/g, "$1");
385
+ text = text.replace(/^\[[^\]]*\]:\s+\S+.*$/gmu, "");
386
+ text = text.replace(/<\/?[a-zA-Z][^>\n]*>/g, "");
387
+ text = text.replace(/^#{1,6}\s+/gmu, "");
388
+ text = text.replace(/^\s*(?:[-*+]|\d+[.)])\s+/gmu, "");
389
+ text = text.replace(/^\s*>\s?/gmu, "");
390
+ text = text.replace(/^\s*(?:-{3,}|\*{3,}|_{3,})\s*$/gmu, "\n");
391
+ text = text.replace(/^\|?[\s:|-]+\|[\s:|-]*$/gmu, "");
392
+ text = text.replace(/\s*\|\s*/g, ",");
393
+ text = text.replace(/(\*\*|__|~~)/g, "");
394
+ text = text.replace(/(?<!\w)\*([^*\n]+)\*(?!\w)/g, "$1");
395
+ text = text.replace(/(?<!\w)_([^_\n]+)_(?!\w)/g, "$1");
396
+ text = text.replace(/\\([\\`*_{}[\]()#+\-.!])/g, "$1");
397
+ text = text.replace(/[ \t]+/g, " ");
398
+ text = text.split("\n").map((line) => line.trim()).filter((line) => line !== "").join("\n");
399
+ return text.trim();
400
+ }
401
+ // src/client/audio-bus.ts
402
+ /**
403
+ * One pause registry for every player this plugin owns.
404
+ *
405
+ * The plugin plays audio through three different engines — the chunk queue
406
+ * (`<audio>` elements), the progressive PCM stream (`AudioContext`), and the
407
+ * settings-page sample player. Each used to keep its own module-local registry,
408
+ * so a stream starting while a queued reply played left both audible. Routing
409
+ * every engine through this one bus means starting audio anywhere pauses
410
+ * everything else, whichever engine produced it.
411
+ * @module dsh-mimo-speak/client/audio-bus
412
+ */
413
+ /** Pause callbacks keyed by the owning player's identity token. */
414
+ const pausers = /* @__PURE__ */ new Map();
415
+ /**
416
+ * Register one player's pause control.
417
+ * @param token - the player's stable identity (a ref object or Audio element).
418
+ * @param pause - stops that player without toggling its state.
419
+ * @returns a disposer that unregisters the player.
420
+ */
421
+ function registerAudioPauser(token, pause) {
422
+ pausers.set(token, pause);
423
+ return () => {
424
+ pausers.delete(token);
425
+ };
426
+ }
427
+ /**
428
+ * Pause every registered player except the caller.
429
+ * @param self - the caller's identity token, left untouched.
430
+ */
431
+ function pauseOtherAudio(self) {
432
+ for (const [token, pause] of pausers) {
433
+ if (token === self) continue;
434
+ try {
435
+ pause();
436
+ } catch {}
437
+ }
438
+ }
439
+ /**
440
+ * Listeners told when page code starts capturing microphone audio.
441
+ *
442
+ * Reading aloud while the microphone is open is self-defeating: the recorder
443
+ * captures the assistant's own voice and the transcript comes back as the
444
+ * reply it just spoke. The official voice-input bundle records through
445
+ * `getUserMedia`, so watching that one call covers any recorder — no coupling
446
+ * to another plugin's internals, and no cooperation needed from it.
447
+ */
448
+ const captureListeners = /* @__PURE__ */ new Set();
449
+ /** Whether `getUserMedia` is already wrapped in this page. */
450
+ let captureWatchInstalled = false;
451
+ /**
452
+ * Subscribe to microphone capture starts.
453
+ * @param listener - called once per successful audio capture request.
454
+ * @returns the unsubscribe function.
455
+ */
456
+ function onAudioCaptureStart(listener) {
457
+ captureListeners.add(listener);
458
+ installCaptureWatch();
459
+ return () => {
460
+ captureListeners.delete(listener);
461
+ };
462
+ }
463
+ /** Wrap `getUserMedia` once per page, leaving its behavior untouched. */
464
+ function installCaptureWatch() {
465
+ if (captureWatchInstalled) return;
466
+ const devices = navigator.mediaDevices;
467
+ if (devices === void 0 || typeof devices.getUserMedia !== "function") return;
468
+ captureWatchInstalled = true;
469
+ const original = devices.getUserMedia.bind(devices);
470
+ devices.getUserMedia = async (constraints) => {
471
+ const stream = await original(constraints);
472
+ if (!(constraints?.audio !== void 0 && constraints.audio !== false)) return stream;
473
+ for (const listener of captureListeners) try {
474
+ listener();
475
+ } catch {}
476
+ return stream;
477
+ };
478
+ }
479
+ // src/client/chat-text.ts
480
+ /** Code blocks shorter than this many lines are worth speaking in smart mode. */
481
+ const SMART_CODE_LINE_LIMIT = 24;
482
+ /** Whether a block contributes text under the active read scope. */
483
+ function blockIncluded(block, scope) {
484
+ if (block.kind === "text") return true;
485
+ if (scope === "text" || scope === "brief") return false;
486
+ if (block.kind !== "code") return false;
487
+ if (scope === "all") return true;
488
+ return block.text.split("\n").length <= SMART_CODE_LINE_LIMIT && block.text.length <= 1200;
489
+ }
490
+ /**
491
+ * Extract the speakable text of one finalized assistant message.
492
+ * @param snapshot - current Chat snapshot of the viewed Session.
493
+ * @param messageId - durable identity of the target assistant message.
494
+ * @param scope - which parts of the reply are read aloud.
495
+ * @returns the message's text blocks joined in order, or undefined when the
496
+ * message is not in the loaded window.
497
+ */
498
+ function speakableTextFor(snapshot, messageId, scope = "text") {
499
+ const matches = [];
500
+ for (const node of snapshot.nodes.values()) {
501
+ if (node.kind !== "assistant-step") continue;
502
+ const candidate = node;
503
+ const data = candidate.data;
504
+ const blocks = data.finalNode?.blocks ?? data.blocks;
505
+ if (data.finalNode?.messageId !== messageId) continue;
506
+ const text = blocks.filter((block) => blockIncluded(block, scope)).map((block) => block.text).join("\n").trim();
507
+ matches.push({
508
+ anchorSeq: candidate.anchorSeq,
509
+ visibility: candidate.visibility,
510
+ text
511
+ });
512
+ }
513
+ if (matches.length === 0) return void 0;
514
+ return (matches.find((match) => match.visibility === "visible") ?? matches[0]).text;
515
+ }
516
+ /**
517
+ * Identify the newest finalized assistant message in the Chat snapshot.
518
+ *
519
+ * Automatic read-aloud only ever speaks this message, so a reply that
520
+ * finished while the user scrolled up, or an older reply re-rendered for any
521
+ * other reason, never steals the speaker.
522
+ * @param snapshot - current Chat snapshot of the viewed Session.
523
+ * @returns the message id of the newest assistant step, or an empty string.
524
+ */
525
+ function latestAssistantMessageId(snapshot) {
526
+ let latestSeq = -1;
527
+ let latestId = "";
528
+ for (const node of snapshot.nodes.values()) {
529
+ if (node.kind !== "assistant-step") continue;
530
+ const candidate = node;
531
+ const id = candidate.data.finalNode?.messageId;
532
+ if (typeof id !== "string" || id === "") continue;
533
+ if (candidate.anchorSeq > latestSeq) {
534
+ latestSeq = candidate.anchorSeq;
535
+ latestId = id;
536
+ }
537
+ }
538
+ return latestId;
539
+ }
540
+ // src/client/highlight.ts
541
+ /**
542
+ * Sentence highlighting for the speak entry.
543
+ *
544
+ * While a chunk plays, the sentence it came from is tinted inside the message
545
+ * bubble. The highlighter walks the message's text nodes once, indexes their
546
+ * letters/digits (a normalization that survives Markdown and inline styles),
547
+ * and maps each chunk text back to DOM ranges through the CSS Custom
548
+ * Highlight API — so no DOM is mutated and scroll position never jumps.
549
+ *
550
+ * When the API is unavailable the highlighter silently no-ops.
551
+ * @module dsh-mimo-speak/client/highlight
552
+ */
553
+ const STYLE_ID = "dsh-mimo-speak-highlight-style";
554
+ const HIGHLIGHT_NAME = "dsh-mimo-speak-sentence";
555
+ /**
556
+ * The instance that most recently painted. Every instance writes the same
557
+ * highlight name, so a clear() from a stale instance — an older message
558
+ * finishing while the new one speaks — would otherwise wipe the live paint.
559
+ */
560
+ let owner = null;
561
+ /** Whether the browser supports the CSS Custom Highlight API. */
562
+ function highlightSupported() {
563
+ return typeof window !== "undefined" && typeof window.CSS !== "undefined" && window.CSS.highlights !== void 0 && typeof window.Highlight === "function";
564
+ }
565
+ function ensureStyle() {
566
+ if (typeof document === "undefined" || document.getElementById(STYLE_ID) !== null) return;
567
+ const style = document.createElement("style");
568
+ style.id = STYLE_ID;
569
+ style.textContent = `::highlight(${HIGHLIGHT_NAME}){background-color:color-mix(in srgb,var(--dsw-alias-brand-primary,#ffc400) 26%,transparent)}`;
570
+ document.head.appendChild(style);
571
+ }
572
+ /** Keep only letters and digits, case-folded, so matching ignores Markdown. */
573
+ function keyChar(char) {
574
+ const code = char.codePointAt(0);
575
+ if (code === void 0) return "";
576
+ if (code >= 48 && code <= 57 || code >= 97 && code <= 122) return char;
577
+ if (code >= 65 && code <= 90) return char.toLowerCase();
578
+ if (code >= 19968 && code <= 40959) return char;
579
+ if (/\p{L}/u.test(char) || /\p{N}/u.test(char)) return char.normalize("NFC").toLowerCase();
580
+ return "";
581
+ }
582
+ /** Build the folded key plus per-key source offsets for one string. */
583
+ function keyOf(text) {
584
+ let key = "";
585
+ const at = [];
586
+ for (let index = 0; index < text.length; index += 1) {
587
+ const folded = keyChar(text[index]);
588
+ if (folded === "") continue;
589
+ key += folded;
590
+ at.push(index);
591
+ }
592
+ return {
593
+ key,
594
+ at
595
+ };
596
+ }
597
+ /**
598
+ * Locate the message bubble containing the speak button, by walking up from
599
+ * the button until an ancestor's text carries the opening of the spoken text.
600
+ * @param fromEl - the action row element (or any descendant of the bubble).
601
+ * @param probeText - the speakable text whose opening identifies the bubble.
602
+ * @returns the closest matching ancestor, or null.
603
+ */
604
+ function findMessageContainer(fromEl, probeText) {
605
+ if (fromEl === null || typeof document === "undefined") return null;
606
+ const probe = keyOf(probeText.slice(0, 80)).key.slice(0, 40);
607
+ if (probe === "") return null;
608
+ let element = fromEl.parentElement;
609
+ for (let depth = 0; element !== null && depth < 14; depth += 1, element = element.parentElement) if (keyOf(element.textContent ?? "").key.includes(probe)) return element;
610
+ return null;
611
+ }
612
+ /** Highlight one sentence of one message while it plays. */
613
+ var SentenceHighlighter = class {
614
+ container;
615
+ token = {};
616
+ nodes = [];
617
+ map = [];
618
+ key = "";
619
+ /** Text length the index was built from; a re-render invalidates it. */
620
+ indexedSignature = "";
621
+ constructor(container) {
622
+ this.container = container ?? document.body;
623
+ if (highlightSupported()) ensureStyle();
624
+ }
625
+ /** Whether any highlight can actually be painted. */
626
+ get supported() {
627
+ return highlightSupported();
628
+ }
629
+ /** Index the message's text nodes, rebuilding when the text changed. */
630
+ index() {
631
+ const signature = `${this.container.textContent?.length ?? -1}`;
632
+ if (this.indexedSignature === signature) return;
633
+ this.indexedSignature = signature;
634
+ this.nodes.length = 0;
635
+ this.map.length = 0;
636
+ this.key = "";
637
+ const walker = document.createTreeWalker(this.container, NodeFilter.SHOW_TEXT, { acceptNode: (node) => {
638
+ const parent = node.parentElement;
639
+ if (parent === null) return NodeFilter.FILTER_REJECT;
640
+ const tag = parent.tagName;
641
+ if (tag === "SCRIPT" || tag === "STYLE" || tag === "BUTTON" || tag === "PRE") return NodeFilter.FILTER_REJECT;
642
+ if (parent.closest(".mimo-speak-root") !== null) return NodeFilter.FILTER_REJECT;
643
+ if ((node.nodeValue ?? "").trim() === "") return NodeFilter.FILTER_REJECT;
644
+ return NodeFilter.FILTER_ACCEPT;
645
+ } });
646
+ let node;
647
+ while ((node = walker.nextNode()) !== null) {
648
+ const text = node.nodeValue ?? "";
649
+ const { key, at } = keyOf(text);
650
+ if (key === "") continue;
651
+ this.nodes.push({
652
+ node,
653
+ text,
654
+ keyLength: at.length
655
+ });
656
+ for (let index = 0; index < at.length; index += 1) this.map.push([this.nodes.length - 1, at[index]]);
657
+ this.key += key;
658
+ }
659
+ }
660
+ /**
661
+ * Paint the sentence `text` onto the message, searching from the key offset
662
+ * `from` so repeated phrases highlight their later occurrence.
663
+ * @param text - one chunk (a substring of the message).
664
+ * @param from - key offset to search from.
665
+ * @returns the key offset just past the painted range (feed it back next).
666
+ */
667
+ show(text, from) {
668
+ if (!highlightSupported()) return from;
669
+ try {
670
+ this.index();
671
+ const { key } = keyOf(text);
672
+ if (key === "" || this.key === "") return from;
673
+ let start = this.key.indexOf(key, Math.max(0, from));
674
+ if (start < 0) start = this.key.indexOf(key);
675
+ if (start < 0) return from;
676
+ const end = start + key.length;
677
+ if (start >= this.map.length || end > this.map.length) return from;
678
+ const first = this.map[start];
679
+ const last = this.map[end - 1];
680
+ const range = new Range();
681
+ range.setStart(this.nodes[first[0]].node, first[1]);
682
+ range.setEnd(this.nodes[last[0]].node, last[1] + 1);
683
+ const highlight = new Highlight(range);
684
+ owner = this.token;
685
+ window.CSS.highlights.set(HIGHLIGHT_NAME, highlight);
686
+ return end;
687
+ } catch {
688
+ return from;
689
+ }
690
+ }
691
+ /** Remove the painted sentence, unless another instance owns it now. */
692
+ clear() {
693
+ if (!highlightSupported()) return;
694
+ if (owner !== null && owner !== this.token) return;
695
+ owner = null;
696
+ try {
697
+ window.CSS.highlights.delete(HIGHLIGHT_NAME);
698
+ } catch {}
699
+ }
700
+ };
701
+ // src/client/panel-visibility.ts
702
+ /**
703
+ * @param state - the panel's inputs.
704
+ * @returns whether the panel may render beside the speaker button.
705
+ */
706
+ function playerPanelVisible(state) {
707
+ return state.progressBar && state.panelOpen && (state.hasAudio || state.loading);
708
+ }
709
+ // src/client/PlayerBar.tsx
710
+ /**
711
+ * The compact player bar: play/pause, a draggable progress track, and the
712
+ * position/duration readout.
713
+ *
714
+ * The track is a `role="slider"` surface — pointer drag with capture,
715
+ * click-to-seek, and arrow-key seeking — so the progress bar is operable
716
+ * without a pointer. Dragging seeks continuously: WAV playback from an object
717
+ * URL repositions cheaply, and the thumb follows the pointer instead of
718
+ * lagging behind it.
719
+ * @module dsh-mimo-speak/client/PlayerBar
720
+ */
721
+ /** Format seconds as `m:ss` (clamped at zero; durations are short). */
722
+ function clock(seconds) {
723
+ const whole = Math.max(0, Math.floor(seconds));
724
+ const minutes = Math.floor(whole / 60);
725
+ const remainder = whole % 60;
726
+ return `${String(minutes)}:${remainder < 10 ? "0" : ""}${String(remainder)}`;
727
+ }
728
+ /**
729
+ * Render one player bar.
730
+ * @param props - playback state, controls, and localized names.
731
+ * @returns the play control, the seekable track, and the time readout.
732
+ */
733
+ function PlayerBar({ state, onToggle, onSeek, labels, seekable = true, compact = false }) {
734
+ const trackRef = (0, react.useRef)(null);
735
+ const [dragging, setDragging] = (0, react.useState)(false);
736
+ const duration = state.duration > 0 ? state.duration : 0;
737
+ const ratio = duration > 0 ? Math.min(1, state.currentTime / duration) : 0;
738
+ /** @param clientX - pointer x in viewport coordinates. @returns the seek target in seconds. */
739
+ const positionAt = (0, react.useCallback)((clientX) => {
740
+ const track = trackRef.current;
741
+ if (track === null) return 0;
742
+ const bounds = track.getBoundingClientRect();
743
+ return (bounds.width > 0 ? Math.min(1, Math.max(0, (clientX - bounds.left) / bounds.width)) : 0) * duration;
744
+ }, [duration]);
745
+ const playButton = /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
746
+ type: "button",
747
+ className: "mimo-speak-barButton",
748
+ "aria-label": state.playing ? labels.pause : labels.play,
749
+ onClick: onToggle,
750
+ children: state.playing ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconPauseOutlineRegular, { size: 14 }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconPlayOutlineRegular, { size: 14 })
751
+ });
752
+ if (compact) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
753
+ className: "mimo-speak-bar mimo-speak-barCompact",
754
+ children: playButton
755
+ });
756
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
757
+ className: "mimo-speak-bar",
758
+ children: [
759
+ playButton,
760
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
761
+ ref: trackRef,
762
+ className: dragging ? "mimo-speak-track mimo-speak-trackDragging" : seekable ? "mimo-speak-track" : "mimo-speak-track mimo-speak-trackStatic",
763
+ role: "slider",
764
+ tabIndex: seekable ? 0 : -1,
765
+ "aria-label": labels.progress,
766
+ "aria-valuemin": 0,
767
+ "aria-valuemax": Math.max(0, Math.round(duration)),
768
+ "aria-valuenow": Math.round(state.currentTime),
769
+ "aria-valuetext": `${clock(state.currentTime)} / ${clock(duration)}`,
770
+ onPointerDown: seekable ? (event) => {
771
+ event.currentTarget.setPointerCapture(event.pointerId);
772
+ setDragging(true);
773
+ onSeek(positionAt(event.clientX));
774
+ } : void 0,
775
+ onPointerMove: seekable ? (event) => {
776
+ if (!dragging) return;
777
+ onSeek(positionAt(event.clientX));
778
+ } : void 0,
779
+ onPointerUp: seekable ? (event) => {
780
+ if (!dragging) return;
781
+ setDragging(false);
782
+ if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
783
+ onSeek(positionAt(event.clientX));
784
+ } : void 0,
785
+ onPointerCancel: seekable ? () => {
786
+ setDragging(false);
787
+ } : void 0,
788
+ onKeyDown: seekable ? (event) => {
789
+ const step = event.shiftKey ? 15 : 5;
790
+ if (event.key === "ArrowRight" || event.key === "ArrowUp") {
791
+ event.preventDefault();
792
+ onSeek(state.currentTime + step);
793
+ } else if (event.key === "ArrowLeft" || event.key === "ArrowDown") {
794
+ event.preventDefault();
795
+ onSeek(state.currentTime - step);
796
+ } else if (event.key === "Home") {
797
+ event.preventDefault();
798
+ onSeek(0);
799
+ } else if (event.key === "End" && duration > 0) {
800
+ event.preventDefault();
801
+ onSeek(duration);
802
+ }
803
+ } : void 0,
804
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
805
+ className: "mimo-speak-fill",
806
+ style: { width: `${(ratio * 100).toFixed(2)}%` }
807
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
808
+ className: "mimo-speak-thumb",
809
+ style: { left: `${(ratio * 100).toFixed(2)}%` }
810
+ })]
811
+ }),
812
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
813
+ className: "mimo-speak-time",
814
+ children: [clock(state.currentTime), seekable ? ` / ${clock(duration)}` : ""]
815
+ })
816
+ ]
817
+ });
818
+ }
819
+ // src/client/speech-cache.ts
820
+ /** Entries kept before the oldest are revoked. */
821
+ const CACHE_CAP = 60;
822
+ const cache = /* @__PURE__ */ new Map();
823
+ const order = [];
824
+ /**
825
+ * Build the cache key for one chunk.
826
+ * @param signature - how the current configuration sounds.
827
+ * @param text - the chunk text.
828
+ * @returns a key that changes whenever the sound or the words do.
829
+ */
830
+ function speechCacheKey(signature, text) {
831
+ return [
832
+ signature.voice,
833
+ signature.model,
834
+ signature.style,
835
+ signature.baseUrl,
836
+ signature.edgeVoice,
837
+ String(signature.maxChars),
838
+ text
839
+ ].join("\0");
840
+ }
841
+ /**
842
+ * Look one chunk up.
843
+ * @param key - from `speechCacheKey`.
844
+ * @returns the cached audio, when present.
845
+ */
846
+ function cachedSpeech(key) {
847
+ return cache.get(key);
848
+ }
849
+ /**
850
+ * Store one chunk, dropping the oldest entries past the cap.
851
+ * @param key - from `speechCacheKey`.
852
+ * @param value - the object URL and its engine.
853
+ */
854
+ function cacheSpeech(key, value) {
855
+ if (cache.has(key)) return;
856
+ cache.set(key, value);
857
+ order.push(key);
858
+ while (order.length > CACHE_CAP) {
859
+ const oldest = order.shift();
860
+ if (oldest === void 0) break;
861
+ const stale = cache.get(oldest);
862
+ cache.delete(oldest);
863
+ if (stale !== void 0) URL.revokeObjectURL(stale.url);
864
+ }
865
+ }
866
+ /**
867
+ * Drop every cached chunk.
868
+ *
869
+ * Called after a settings save: the user just asked for different audio, so
870
+ * replaying anything cached under the previous configuration would quietly
871
+ * ignore the change.
872
+ */
873
+ function clearSpeechCache() {
874
+ for (const value of cache.values()) URL.revokeObjectURL(value.url);
875
+ cache.clear();
876
+ order.length = 0;
877
+ }
878
+ // src/client/split-speech.ts
879
+ /**
880
+ * Sentence-aligned text splitting for pipelined playback.
881
+ *
882
+ * The browser splits already-normalized speakable text into chunks around a
883
+ * configured size, then synthesizes and plays them back-to-back while the next
884
+ * chunk is still being produced. Splitting at sentence boundaries keeps chunks
885
+ * sounding natural; a sentence longer than the budget is hard-split at a
886
+ * punctuation or whitespace seam.
887
+ * @module dsh-mimo-speak/client/split-speech
888
+ */
889
+ /** Characters that end a spoken sentence. */
890
+ const SENTENCE_END = "。!?!?;;…\n";
891
+ /** Longest tolerated chunk before a sentence is hard-split. */
892
+ function clampChunkChars(value) {
893
+ if (!Number.isFinite(value)) return 120;
894
+ return Math.min(1e3, Math.max(20, Math.round(value)));
895
+ }
896
+ /**
897
+ * Hard-split one over-long sentence at punctuation seams, preferring the
898
+ * second half of the budget so the tail of each chunk stays natural.
899
+ * @param piece - one sentence that exceeds the chunk budget.
900
+ * @param limit - chunk size in characters.
901
+ * @returns the sentence broken into budget-sized pieces.
902
+ */
903
+ function hardSplit(piece, limit) {
904
+ const parts = [];
905
+ let rest = piece;
906
+ while (rest.length > limit) {
907
+ let cut = -1;
908
+ const floor = Math.floor(limit * .5);
909
+ for (let index = Math.min(limit, rest.length - 1); index > floor; index -= 1) {
910
+ const char = rest.charAt(index);
911
+ if (char === " " || char === "\n" || char === "," || char === "," || char === "、") {
912
+ cut = index + 1;
913
+ break;
914
+ }
915
+ }
916
+ if (cut <= 0) cut = limit;
917
+ parts.push(rest.slice(0, cut));
918
+ rest = rest.slice(cut);
919
+ }
920
+ if (rest.length > 0) parts.push(rest);
921
+ return parts;
922
+ }
923
+ /**
924
+ * Split normalized speakable text into ordered chunks at sentence boundaries.
925
+ *
926
+ * @param text - plain text, already stripped of Markdown by the Host's
927
+ * normalizer; this function only partitions it for playback.
928
+ * @param chunkChars - target chunk size in characters.
929
+ * @returns speakable chunks, each non-empty and at most `chunkChars` long
930
+ * except when a single unbroken sentence must be hard-split.
931
+ */
932
+ function splitForSpeech(text, chunkChars) {
933
+ const trimmed = (text ?? "").trim();
934
+ if (trimmed.length === 0) return [];
935
+ const limit = clampChunkChars(chunkChars);
936
+ const sentences = [];
937
+ let buffer = "";
938
+ for (let index = 0; index < trimmed.length; index += 1) {
939
+ const char = trimmed.charAt(index);
940
+ buffer += char;
941
+ if (SENTENCE_END.indexOf(char) >= 0) {
942
+ sentences.push(buffer);
943
+ buffer = "";
944
+ }
945
+ }
946
+ if (buffer.length > 0) sentences.push(buffer);
947
+ const chunks = [];
948
+ let current = "";
949
+ for (const sentence of sentences) {
950
+ if (sentence.trim().length === 0) continue;
951
+ if (sentence.length > limit) {
952
+ if (current.trim().length > 0) {
953
+ chunks.push(current.trim());
954
+ current = "";
955
+ }
956
+ for (const part of hardSplit(sentence, limit)) if (part.trim().length > 0) chunks.push(part.trim());
957
+ continue;
958
+ }
959
+ if (current.length + sentence.length > limit && current.trim().length > 0) {
960
+ chunks.push(current.trim());
961
+ current = "";
962
+ }
963
+ current += sentence;
964
+ }
965
+ if (current.trim().length > 0) chunks.push(current.trim());
966
+ return chunks.filter((chunk) => chunk.length > 0);
967
+ }
968
+ // src/client/SpeakerIcon.tsx
969
+ const Artwork = ({ size = 16, className }) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
970
+ width: size,
971
+ height: size,
972
+ viewBox: "0 0 16 16",
973
+ fill: "none",
974
+ "aria-hidden": "true",
975
+ focusable: "false",
976
+ className,
977
+ children: [
978
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", {
979
+ d: "M2.5 6h2.1L8 3.2v9.6L4.6 10H2.5a.5.5 0 0 1-.5-.5v-3a.5.5 0 0 1 .5-.5z",
980
+ fill: "currentColor"
981
+ }),
982
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", {
983
+ d: "M10.2 5.6a3.4 3.4 0 0 1 0 4.8",
984
+ stroke: "currentColor",
985
+ strokeWidth: "1.2",
986
+ strokeLinecap: "round"
987
+ }),
988
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", {
989
+ d: "M12.6 3.6a6.6 6.6 0 0 1 0 8.8",
990
+ stroke: "currentColor",
991
+ strokeWidth: "1.2",
992
+ strokeLinecap: "round",
993
+ opacity: "0.65"
994
+ })
995
+ ]
996
+ });
997
+ /** Regular one-pixel volume artwork. */
998
+ const IconVolumeOutlineRegular = (props) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Artwork, { ...props });
999
+ // src/client/use-audio-queue.ts
1000
+ /**
1001
+ * The pipelined playback engine behind the speak entry: one hidden
1002
+ * `HTMLAudioElement` fed from a queue of chunk object URLs, so the next chunk
1003
+ * is already waiting when the current one ends and playback runs back-to-back.
1004
+ *
1005
+ * Starting this player pauses every other player this plugin owns through the
1006
+ * shared audio bus, so a stream and a queued reply never overlap.
1007
+ * @module dsh-mimo-speak/client/use-audio-queue
1008
+ */
1009
+ const IDLE$3 = {
1010
+ playing: false,
1011
+ currentTime: 0,
1012
+ duration: 0,
1013
+ ended: false,
1014
+ waiting: false
1015
+ };
1016
+ /**
1017
+ * Bind one hidden audio element to a queue of chunk URLs.
1018
+ * @returns playback state plus enqueue/clear/toggle/seek/pause controls.
1019
+ */
1020
+ function useAudioQueue() {
1021
+ const [state, setState] = (0, react.useState)(IDLE$3);
1022
+ const elementRef = (0, react.useRef)(null);
1023
+ const queueRef = (0, react.useRef)([]);
1024
+ /** Set once the queue runs dry mid-stream, so a late enqueue resumes play. */
1025
+ const waitingRef = (0, react.useRef)(false);
1026
+ /** Set by the producer once no more chunks will be enqueued. */
1027
+ const finishedRef = (0, react.useRef)(false);
1028
+ const publish = (0, react.useCallback)((patch) => {
1029
+ setState((previous) => ({
1030
+ ...previous,
1031
+ ...patch
1032
+ }));
1033
+ }, []);
1034
+ const loadNext = (0, react.useCallback)(() => {
1035
+ const audio = elementRef.current;
1036
+ if (audio === null) return;
1037
+ const url = queueRef.current.shift();
1038
+ if (url === void 0) {
1039
+ waitingRef.current = true;
1040
+ publish(finishedRef.current ? {
1041
+ ended: true,
1042
+ playing: false,
1043
+ currentTime: 0,
1044
+ waiting: false
1045
+ } : {
1046
+ playing: false,
1047
+ currentTime: 0,
1048
+ waiting: true
1049
+ });
1050
+ return;
1051
+ }
1052
+ waitingRef.current = false;
1053
+ publish({ waiting: false });
1054
+ audio.src = url;
1055
+ audio.play().catch(() => {
1056
+ publish({ playing: false });
1057
+ });
1058
+ }, [publish]);
1059
+ (0, react.useEffect)(() => {
1060
+ const audio = new Audio();
1061
+ elementRef.current = audio;
1062
+ const onTime = () => {
1063
+ publish({ currentTime: audio.currentTime });
1064
+ };
1065
+ const onLoaded = () => {
1066
+ publish({ duration: Number.isFinite(audio.duration) ? audio.duration : 0 });
1067
+ };
1068
+ const onPlay = () => {
1069
+ pauseOtherAudio(audio);
1070
+ publish({
1071
+ playing: true,
1072
+ ended: false
1073
+ });
1074
+ };
1075
+ const onPause = () => {
1076
+ publish({ playing: false });
1077
+ };
1078
+ const onEnded = () => {
1079
+ publish({
1080
+ playing: false,
1081
+ currentTime: 0
1082
+ });
1083
+ loadNext();
1084
+ };
1085
+ audio.addEventListener("timeupdate", onTime);
1086
+ audio.addEventListener("loadedmetadata", onLoaded);
1087
+ audio.addEventListener("durationchange", onLoaded);
1088
+ audio.addEventListener("play", onPlay);
1089
+ audio.addEventListener("pause", onPause);
1090
+ audio.addEventListener("ended", onEnded);
1091
+ setState({
1092
+ playing: false,
1093
+ currentTime: 0,
1094
+ duration: 0,
1095
+ ended: false,
1096
+ waiting: false
1097
+ });
1098
+ const unregister = registerAudioPauser(audio, () => {
1099
+ audio.pause();
1100
+ });
1101
+ return () => {
1102
+ unregister();
1103
+ audio.pause();
1104
+ audio.removeAttribute("src");
1105
+ audio.load();
1106
+ audio.removeEventListener("timeupdate", onTime);
1107
+ audio.removeEventListener("loadedmetadata", onLoaded);
1108
+ audio.removeEventListener("durationchange", onLoaded);
1109
+ audio.removeEventListener("play", onPlay);
1110
+ audio.removeEventListener("pause", onPause);
1111
+ audio.removeEventListener("ended", onEnded);
1112
+ elementRef.current = null;
1113
+ };
1114
+ }, [loadNext, publish]);
1115
+ return {
1116
+ state,
1117
+ enqueue: (0, react.useCallback)((url) => {
1118
+ const audio = elementRef.current;
1119
+ if (audio === null) return;
1120
+ queueRef.current.push(url);
1121
+ if (audio.src === "" || waitingRef.current) loadNext();
1122
+ }, [loadNext]),
1123
+ clear: (0, react.useCallback)(() => {
1124
+ queueRef.current = [];
1125
+ waitingRef.current = false;
1126
+ finishedRef.current = false;
1127
+ const audio = elementRef.current;
1128
+ if (audio === null) return;
1129
+ audio.pause();
1130
+ audio.removeAttribute("src");
1131
+ audio.load();
1132
+ publish({
1133
+ playing: false,
1134
+ currentTime: 0,
1135
+ duration: 0,
1136
+ ended: false,
1137
+ waiting: false
1138
+ });
1139
+ }, [publish]),
1140
+ toggle: (0, react.useCallback)(() => {
1141
+ const audio = elementRef.current;
1142
+ if (audio === null) return;
1143
+ if (audio.paused) {
1144
+ pauseOtherAudio(audio);
1145
+ if (audio.ended) audio.currentTime = 0;
1146
+ audio.play().catch(() => {
1147
+ publish({ playing: false });
1148
+ });
1149
+ } else audio.pause();
1150
+ }, [publish]),
1151
+ seek: (0, react.useCallback)((seconds) => {
1152
+ const audio = elementRef.current;
1153
+ if (audio === null) return;
1154
+ const duration = Number.isFinite(audio.duration) ? audio.duration : 0;
1155
+ const target = Math.max(0, duration > 0 ? Math.min(seconds, duration) : seconds);
1156
+ audio.currentTime = target;
1157
+ publish({
1158
+ currentTime: target,
1159
+ ended: false
1160
+ });
1161
+ }, [publish]),
1162
+ pause: (0, react.useCallback)(() => {
1163
+ const audio = elementRef.current;
1164
+ if (audio !== null) audio.pause();
1165
+ }, []),
1166
+ finish: (0, react.useCallback)(() => {
1167
+ finishedRef.current = true;
1168
+ if (waitingRef.current) publish({
1169
+ ended: true,
1170
+ playing: false,
1171
+ currentTime: 0,
1172
+ waiting: false
1173
+ });
1174
+ }, [publish])
1175
+ };
1176
+ }
1177
+ // src/client/stream-dispose.ts
1178
+ /** A fresh, live timeline. */
1179
+ function createStreamTimeline() {
1180
+ return {
1181
+ disposed: false,
1182
+ playing: false,
1183
+ finished: false,
1184
+ nextAt: 0,
1185
+ totalDuration: 0
1186
+ };
1187
+ }
1188
+ /**
1189
+ * Whether one more chunk may be scheduled. This is the single decision point
1190
+ * `feed` consults before it touches the context factory, so a disposed player
1191
+ * can never rebuild its `AudioContext`.
1192
+ * @param timeline - the player's live bookkeeping.
1193
+ */
1194
+ function streamShouldFeed(timeline) {
1195
+ return !timeline.disposed;
1196
+ }
1197
+ /**
1198
+ * The context time the next chunk should start at: never earlier than the
1199
+ * timeline's back-to-back position, and never before the context clock.
1200
+ * @param timeline - the player's live bookkeeping.
1201
+ * @param ctxNow - the current `AudioContext.currentTime`.
1202
+ */
1203
+ function feedStartAt(timeline, ctxNow) {
1204
+ return Math.max(timeline.nextAt, ctxNow + .02);
1205
+ }
1206
+ /** Record that one chunk of `duration` seconds started at `when`. */
1207
+ function recordScheduledChunk(timeline, when, duration) {
1208
+ timeline.nextAt = when + duration;
1209
+ timeline.totalDuration += duration;
1210
+ }
1211
+ /** Disable the player and reset every field a late callback could misuse. */
1212
+ function disposeStreamTimeline(timeline) {
1213
+ timeline.disposed = true;
1214
+ timeline.playing = false;
1215
+ timeline.finished = false;
1216
+ timeline.nextAt = 0;
1217
+ timeline.totalDuration = 0;
1218
+ }
1219
+ /** Re-enable after a remount (StrictMode setup or in-place re-entry). */
1220
+ function resetStreamTimeline(timeline) {
1221
+ timeline.disposed = false;
1222
+ }
1223
+ const IDLE$2 = {
1224
+ playing: false,
1225
+ currentTime: 0,
1226
+ duration: 0,
1227
+ ended: false
1228
+ };
1229
+ /**
1230
+ * Bind one context to a stream of PCM chunks.
1231
+ * @param deps - injected context factory, state publisher, timers and bus hook.
1232
+ * @returns scheduling controls plus dispose/revive.
1233
+ */
1234
+ function createStreamSink(deps) {
1235
+ const timeline = createStreamTimeline();
1236
+ let ctx = null;
1237
+ let sources = [];
1238
+ let startedAt = 0;
1239
+ let playedBeforePause = 0;
1240
+ let tick = null;
1241
+ const publish = (patch) => {
1242
+ deps.onState(patch);
1243
+ };
1244
+ const clearTick = () => {
1245
+ if (tick !== null) {
1246
+ deps.clearInterval(tick);
1247
+ tick = null;
1248
+ }
1249
+ };
1250
+ const syncProgress = () => {
1251
+ if (ctx === null || !timeline.playing) return;
1252
+ const elapsed = Math.max(0, ctx.currentTime - startedAt);
1253
+ publish({ currentTime: playedBeforePause + elapsed });
1254
+ };
1255
+ const startTick = () => {
1256
+ clearTick();
1257
+ tick = deps.setInterval(syncProgress, 200);
1258
+ };
1259
+ const ensureCtx = () => {
1260
+ if (ctx === null) ctx = deps.createContext();
1261
+ return ctx;
1262
+ };
1263
+ const stopSources = () => {
1264
+ for (const source of sources) try {
1265
+ source.stop();
1266
+ } catch {}
1267
+ sources = [];
1268
+ };
1269
+ const maybeEnded = () => {
1270
+ if (!timeline.finished || !timeline.playing) return;
1271
+ if (sources.length > 0) return;
1272
+ const total = timeline.totalDuration;
1273
+ if (playedBeforePause + (ctx !== null ? Math.max(0, ctx.currentTime - startedAt) : 0) >= total - .05) {
1274
+ timeline.playing = false;
1275
+ clearTick();
1276
+ publish({
1277
+ playing: false,
1278
+ ended: true,
1279
+ currentTime: 0
1280
+ });
1281
+ }
1282
+ };
1283
+ const feed = (pcm) => {
1284
+ if (!streamShouldFeed(timeline)) return;
1285
+ const context = ensureCtx();
1286
+ let resumePromise = Promise.resolve();
1287
+ if (!timeline.playing) {
1288
+ timeline.playing = true;
1289
+ timeline.finished = false;
1290
+ playedBeforePause = 0;
1291
+ timeline.totalDuration = 0;
1292
+ startedAt = context.currentTime + .08;
1293
+ timeline.nextAt = startedAt;
1294
+ deps.onStart();
1295
+ resumePromise = context.state === "suspended" ? context.resume().catch(() => {}) : Promise.resolve();
1296
+ startTick();
1297
+ }
1298
+ const length = Math.floor(pcm.length / 2);
1299
+ if (length === 0) return;
1300
+ const floats = new Float32Array(length);
1301
+ const view = new DataView(pcm.buffer, pcm.byteOffset, pcm.byteLength);
1302
+ for (let index = 0; index < length; index += 1) floats[index] = view.getInt16(index * 2, true) / 32768;
1303
+ const buffer = context.createBuffer(1, length, PCM_SAMPLE_RATE);
1304
+ buffer.copyToChannel(floats, 0);
1305
+ const source = context.createBufferSource();
1306
+ source.buffer = buffer;
1307
+ source.connect(context.destination);
1308
+ const when = feedStartAt(timeline, context.currentTime);
1309
+ source.start(when);
1310
+ recordScheduledChunk(timeline, when, buffer.duration);
1311
+ sources.push(source);
1312
+ source.onended = () => {
1313
+ sources = sources.filter((item) => item !== source);
1314
+ maybeEnded();
1315
+ };
1316
+ publish({
1317
+ playing: context.state === "running",
1318
+ ended: false,
1319
+ duration: timeline.totalDuration
1320
+ });
1321
+ if (context.state !== "running") resumePromise.then(() => {
1322
+ if (timeline.playing) publish({ playing: context.state === "running" });
1323
+ });
1324
+ };
1325
+ const finish = () => {
1326
+ if (!streamShouldFeed(timeline)) return;
1327
+ timeline.finished = true;
1328
+ maybeEnded();
1329
+ };
1330
+ const clear = () => {
1331
+ if (!streamShouldFeed(timeline)) return;
1332
+ stopSources();
1333
+ timeline.playing = false;
1334
+ timeline.finished = false;
1335
+ timeline.totalDuration = 0;
1336
+ clearTick();
1337
+ publish(IDLE$2);
1338
+ };
1339
+ const toggle = () => {
1340
+ if (!streamShouldFeed(timeline)) return;
1341
+ const context = ensureCtx();
1342
+ if (timeline.playing) {
1343
+ if (context.state === "suspended") {
1344
+ context.resume().catch(() => {});
1345
+ startedAt = context.currentTime;
1346
+ startTick();
1347
+ publish({
1348
+ playing: true,
1349
+ ended: false
1350
+ });
1351
+ return;
1352
+ }
1353
+ context.suspend().catch(() => {});
1354
+ const elapsed = Math.max(0, context.currentTime - startedAt);
1355
+ playedBeforePause += elapsed;
1356
+ clearTick();
1357
+ publish({ playing: false });
1358
+ return;
1359
+ }
1360
+ context.resume().catch(() => {});
1361
+ startedAt = context.currentTime;
1362
+ timeline.playing = true;
1363
+ timeline.finished = timeline.finished && sources.length === 0;
1364
+ startTick();
1365
+ publish({
1366
+ playing: true,
1367
+ ended: false
1368
+ });
1369
+ };
1370
+ const pause = () => {
1371
+ if (!streamShouldFeed(timeline)) return;
1372
+ if (ctx === null || !timeline.playing) return;
1373
+ if (ctx.state === "suspended") {
1374
+ clearTick();
1375
+ publish({ playing: false });
1376
+ return;
1377
+ }
1378
+ const elapsed = Math.max(0, ctx.currentTime - startedAt);
1379
+ playedBeforePause += elapsed;
1380
+ ctx.suspend().catch(() => {});
1381
+ clearTick();
1382
+ publish({ playing: false });
1383
+ };
1384
+ const scheduled = () => {
1385
+ return timeline.disposed ? 0 : timeline.totalDuration;
1386
+ };
1387
+ const dispose = () => {
1388
+ if (timeline.disposed) return;
1389
+ disposeStreamTimeline(timeline);
1390
+ stopSources();
1391
+ clearTick();
1392
+ if (ctx !== null) ctx.close().catch(() => {});
1393
+ ctx = null;
1394
+ startedAt = 0;
1395
+ playedBeforePause = 0;
1396
+ sources = [];
1397
+ };
1398
+ const revive = () => {
1399
+ resetStreamTimeline(timeline);
1400
+ };
1401
+ return {
1402
+ feed,
1403
+ finish,
1404
+ clear,
1405
+ toggle,
1406
+ pause,
1407
+ scheduled,
1408
+ dispose,
1409
+ revive
1410
+ };
1411
+ }
1412
+ /** MiMo streams 24 kHz mono PCM; the context renders at the native rate. */
1413
+ const PCM_SAMPLE_RATE = 24e3;
1414
+ // src/client/use-stream-player.ts
1415
+ /**
1416
+ * Progressive PCM playback behind the speak entry's streaming path.
1417
+ *
1418
+ * The Host streams one utterance as raw 24 kHz / 16-bit / mono PCM chunks; each
1419
+ * chunk is converted to an `AudioBuffer` and scheduled back-to-back on one
1420
+ * `AudioContext`, so the first chunk is audible within a second while later
1421
+ * chunks keep arriving. Seek is not supported (the stream is transient), so
1422
+ * this player exposes the same `AudioPlayerState` surface minus seeking.
1423
+ *
1424
+ * All scheduling and the dispose guard live in `stream-dispose.ts`; this hook
1425
+ * only binds that sink to React state, the shared audio bus and the browser's
1426
+ * timers, so the sink runs (and is tested) without React or a DOM.
1427
+ * @module dsh-mimo-speak/client/use-stream-player
1428
+ */
1429
+ const IDLE$1 = {
1430
+ playing: false,
1431
+ currentTime: 0,
1432
+ duration: 0,
1433
+ ended: false
1434
+ };
1435
+ /**
1436
+ * Bind one `AudioContext` to a stream of PCM chunks.
1437
+ * @returns playback state plus feed/finish/clear/toggle/pause controls.
1438
+ */
1439
+ function useStreamPlayer() {
1440
+ const [state, setState] = (0, react.useState)(IDLE$1);
1441
+ /** Identity this player registers with the shared audio bus. */
1442
+ const token = (0, react.useMemo)(() => ({}), []);
1443
+ const sinkRef = (0, react.useRef)(null);
1444
+ if (sinkRef.current === null) sinkRef.current = createStreamSink({
1445
+ createContext: () => new AudioContext({ sampleRate: PCM_SAMPLE_RATE }),
1446
+ onState: (patch) => {
1447
+ setState((previous) => ({
1448
+ ...previous,
1449
+ ...patch
1450
+ }));
1451
+ },
1452
+ setInterval: (handler, ms) => window.setInterval(handler, ms),
1453
+ clearInterval: (handle) => {
1454
+ window.clearInterval(handle);
1455
+ },
1456
+ onStart: () => {
1457
+ pauseOtherAudio(token);
1458
+ }
1459
+ });
1460
+ const sink = sinkRef.current;
1461
+ const pauseRef = (0, react.useRef)(() => {});
1462
+ pauseRef.current = sink.pause;
1463
+ (0, react.useEffect)(() => registerAudioPauser(token, () => {
1464
+ pauseRef.current();
1465
+ }), [token]);
1466
+ (0, react.useEffect)(() => {
1467
+ sink.revive();
1468
+ return () => {
1469
+ sink.dispose();
1470
+ };
1471
+ }, [sink]);
1472
+ return {
1473
+ state,
1474
+ feed: sink.feed,
1475
+ finish: sink.finish,
1476
+ clear: sink.clear,
1477
+ toggle: sink.toggle,
1478
+ pause: sink.pause,
1479
+ scheduled: sink.scheduled
1480
+ };
1481
+ }
1482
+ // src/client/SpeakAction.tsx
1483
+ /**
1484
+ * The speak entry in the finalized assistant message's action strip: a volume
1485
+ * button that synthesizes the message with MiMo TTS, and — once audio exists —
1486
+ * a floating mini player with a draggable progress bar.
1487
+ *
1488
+ * Long replies are synthesized as a pipeline: the text is split at sentence
1489
+ * boundaries into small chunks, the first chunk starts playing as soon as it
1490
+ * lands, and the remaining chunks synthesize in the background while audio
1491
+ * plays, so the first sound arrives in seconds regardless of length.
1492
+ *
1493
+ * The button lives exactly where the platform keeps per-message actions
1494
+ * (between copy and branch). The player floats below the icon row so the row's
1495
+ * 28px chrome never reflows; while a player is open the strip stops fading on
1496
+ * hover-out (`styles.ts`), so audio stays visible wherever the pointer goes.
1497
+ * @module dsh-mimo-speak/client/SpeakAction
1498
+ */
1499
+ /**
1500
+ * Map a failure onto the dictionary key the entry shows.
1501
+ * @param failure - the synthesis failure, or `empty` for a text-less message.
1502
+ * @returns the localized copy key.
1503
+ */
1504
+ function errorKeyFor(failure) {
1505
+ if (failure === "empty") return "emptyText";
1506
+ if (failure === "unconfigured") return "error.notConfigured";
1507
+ switch (failure.code) {
1508
+ case "not-configured": return "error.notConfigured";
1509
+ case "bad-request": return "error.badRequest";
1510
+ case "text-too-long": return "error.badRequest";
1511
+ case "timeout": return "error.timeout";
1512
+ case "upstream-error": return "error.upstream";
1513
+ case "invalid-audio": return "error.invalidAudio";
1514
+ case "voice-sample-unreadable": return "error.voiceSample";
1515
+ default: return "error.generic";
1516
+ }
1517
+ }
1518
+ /** Whether a session snapshot is still producing the reply. */
1519
+ function sessionRunning(session) {
1520
+ try {
1521
+ if (session === null || typeof session !== "object") return false;
1522
+ const value = session;
1523
+ if (value.running === true) return true;
1524
+ return value.status === "running" || value.status === "busy";
1525
+ } catch {
1526
+ return false;
1527
+ }
1528
+ }
1529
+ /**
1530
+ * Call one slot-provided selector hook defensively: an absent hook or a
1531
+ * throwing selector resolves to the fallback, so automatic reading silently
1532
+ * disables itself rather than crashing the action row.
1533
+ */
1534
+ function useHostHook(hook, selector, fallback) {
1535
+ if (typeof hook !== "function") return fallback;
1536
+ try {
1537
+ const value = hook(selector);
1538
+ return value === void 0 || value === null ? fallback : value;
1539
+ } catch {
1540
+ return fallback;
1541
+ }
1542
+ }
1543
+ /**
1544
+ * Message ids that automatic reading already handled. Client memory only: a
1545
+ * page reload may replay the newest reply once, which beats silently never
1546
+ * speaking, and re-renders can never start the same reply twice.
1547
+ */
1548
+ const autoReadLog = (() => {
1549
+ const seen = /* @__PURE__ */ new Set();
1550
+ const order = [];
1551
+ return {
1552
+ has(id) {
1553
+ return id !== "" && seen.has(id);
1554
+ },
1555
+ mark(id) {
1556
+ if (id === "" || seen.has(id)) return;
1557
+ seen.add(id);
1558
+ order.push(id);
1559
+ if (order.length > 200) {
1560
+ const oldest = order.shift();
1561
+ if (oldest !== void 0) seen.delete(oldest);
1562
+ }
1563
+ }
1564
+ };
1565
+ })();
1566
+ /**
1567
+ * Produce (or reuse) the object URL for one chunk.
1568
+ * @param text - one speakable chunk.
1569
+ * @param signature - how the current configuration sounds; part of the key, so
1570
+ * a voice/style change never replays the previous take.
1571
+ * @param signal - aborts the request when the reader stops.
1572
+ * @returns the object URL of the audio and the engine that produced it.
1573
+ */
1574
+ async function synthesizeChunkUrl(text, signature, signal) {
1575
+ const key = speechCacheKey(signature, text);
1576
+ const hit = cachedSpeech(key);
1577
+ if (hit !== void 0) return hit;
1578
+ const blob = await requestSpeech({ text }, signal);
1579
+ const chunk = {
1580
+ url: URL.createObjectURL(blob),
1581
+ engine: speechEngineOf(blob)
1582
+ };
1583
+ cacheSpeech(key, chunk);
1584
+ return chunk;
1585
+ }
1586
+ /** Keep only the chunks that fit inside the configured total budget. */
1587
+ function budgetChunks(chunks, maxChars) {
1588
+ const selected = [];
1589
+ let budget = Number.isFinite(maxChars) ? Math.max(0, Math.round(maxChars)) : 2e3;
1590
+ for (const chunk of chunks) {
1591
+ if (budget <= 0) break;
1592
+ selected.push(chunk);
1593
+ budget -= chunk.length;
1594
+ }
1595
+ return selected;
1596
+ }
1597
+ /**
1598
+ * Render one message's speak control and open player.
1599
+ * @param props - the message identity, the injected engine verbs, the Chat
1600
+ * selector hook, and localized copy.
1601
+ * @returns the volume button with its optional player and failure notice.
1602
+ */
1603
+ function SpeakAction(props) {
1604
+ const { messageId, useChat, useStatus, ensureStatus, t } = props;
1605
+ const useSession = props.useSession;
1606
+ const status = useStatus((snapshot) => snapshot);
1607
+ /**
1608
+ * Fingerprint of the current voice/model/endpoint. It is part of the replay
1609
+ * cache key, so a settings change can never replay the previous take.
1610
+ */
1611
+ const signatureRef = (0, react.useRef)({
1612
+ voice: "",
1613
+ model: "",
1614
+ style: "",
1615
+ baseUrl: "",
1616
+ edgeVoice: "",
1617
+ maxChars: 0
1618
+ });
1619
+ signatureRef.current = {
1620
+ voice: status.voice,
1621
+ model: status.model,
1622
+ style: "",
1623
+ baseUrl: status.baseUrl,
1624
+ edgeVoice: status.edgeVoice,
1625
+ maxChars: status.maxChars
1626
+ };
1627
+ /** The panel only exists to host the progress bar; without it the button is the control. */
1628
+ const showProgressBar = status.progressBar === true;
1629
+ const rawText = useChat((snapshot) => speakableTextFor(snapshot, messageId, status.readScope));
1630
+ const latestId = useHostHook(useChat, (snapshot) => latestAssistantMessageId(snapshot), "");
1631
+ const running = useHostHook(useSession, sessionRunning, false);
1632
+ const speakable = (0, react.useMemo)(() => rawText === void 0 ? void 0 : toSpeakableText(rawText), [rawText]);
1633
+ const [phase, setPhase] = (0, react.useState)("idle");
1634
+ const [failure, setFailure] = (0, react.useState)(null);
1635
+ /** The reply exceeded the character budget, so only its opening is spoken. */
1636
+ const [truncated, setTruncated] = (0, react.useState)(false);
1637
+ const { state: playerState, enqueue: playerEnqueue, clear: playerClear, toggle: playerToggle, seek: playerSeek, pause: playerPause, finish: playerFinish } = useAudioQueue();
1638
+ const streamPlayer = useStreamPlayer();
1639
+ const [mode, setMode] = (0, react.useState)(null);
1640
+ /** Engine that actually answered this read; `edge` means MiMo failed. */
1641
+ const [engineUsed, setEngineUsed] = (0, react.useState)(null);
1642
+ const activeState = mode === "stream" ? streamPlayer.state : playerState;
1643
+ const queueWaiting = mode === "queue" && playerState.waiting === true;
1644
+ const activeToggle = (0, react.useCallback)(() => {
1645
+ if (mode === "stream") streamPlayer.toggle();
1646
+ else playerToggle();
1647
+ }, [
1648
+ mode,
1649
+ playerToggle,
1650
+ streamPlayer
1651
+ ]);
1652
+ const activePause = (0, react.useCallback)(() => {
1653
+ if (mode === "stream") streamPlayer.pause();
1654
+ else playerPause();
1655
+ }, [
1656
+ mode,
1657
+ playerPause,
1658
+ streamPlayer
1659
+ ]);
1660
+ const activeSeek = (0, react.useCallback)((seconds) => {
1661
+ if (mode === "stream") return;
1662
+ playerSeek(seconds);
1663
+ }, [mode, playerSeek]);
1664
+ const clearPlayers = (0, react.useCallback)(() => {
1665
+ playerClear();
1666
+ streamPlayer.clear();
1667
+ cuesRef.current = [];
1668
+ cueCursorRef.current = 0;
1669
+ keyOffsetRef.current = 0;
1670
+ setMode(null);
1671
+ }, [playerClear, streamPlayer]);
1672
+ /**
1673
+ * Stop the current read-aloud for good: abort the stream in flight, drop the
1674
+ * scheduled audio, and invalidate the run so no further sentence is asked
1675
+ * for. This is the control the speaker button offers while it is playing.
1676
+ */
1677
+ /**
1678
+ * Pause the current read-aloud and stop asking for the rest of the reply.
1679
+ * Whatever is already scheduled stays buffered, so resuming plays that much;
1680
+ * `finish()` lets the player report the end once the buffer drains instead of
1681
+ * waiting forever for sentences that will never arrive.
1682
+ */
1683
+ const pauseRun = (0, react.useCallback)(() => {
1684
+ abortRef.current?.abort();
1685
+ abortRef.current = null;
1686
+ if (mode === "stream") streamPlayer.finish();
1687
+ activePause();
1688
+ }, [
1689
+ activePause,
1690
+ mode,
1691
+ streamPlayer
1692
+ ]);
1693
+ /** The panel's transport: pause also aborts the sentences still to come. */
1694
+ const panelToggle = (0, react.useCallback)(() => {
1695
+ if (activeState.playing) pauseRun();
1696
+ else activeToggle();
1697
+ }, [
1698
+ activeState.playing,
1699
+ pauseRun,
1700
+ activeToggle
1701
+ ]);
1702
+ const stopRun = (0, react.useCallback)(() => {
1703
+ abortRef.current?.abort();
1704
+ abortRef.current = null;
1705
+ sessionRef.current += 1;
1706
+ clearPlayers();
1707
+ highlighterRef.current?.clear();
1708
+ highlighterRef.current = null;
1709
+ cuesRef.current = [];
1710
+ cueCursorRef.current = 0;
1711
+ keyOffsetRef.current = 0;
1712
+ setTruncated(false);
1713
+ setPhase("idle");
1714
+ setFailure(null);
1715
+ setPanelOpen(false);
1716
+ setEngineUsed(null);
1717
+ }, [clearPlayers]);
1718
+ const highlighterRef = (0, react.useRef)(null);
1719
+ /** Sentence cues: the audio second each chunk starts at, plus its text. */
1720
+ const cuesRef = (0, react.useRef)([]);
1721
+ /** How many cues the paint effect already consumed. */
1722
+ const cueCursorRef = (0, react.useRef)(0);
1723
+ /** Folded-key offset of the last painted sentence, so repeats pair up. */
1724
+ const keyOffsetRef = (0, react.useRef)(0);
1725
+ const [panelOpen, setPanelOpen] = (0, react.useState)(false);
1726
+ const [panelSide, setPanelSide] = (0, react.useState)("right");
1727
+ const rootRef = (0, react.useRef)(null);
1728
+ const buttonRef = (0, react.useRef)(null);
1729
+ const panelId = (0, react.useId)();
1730
+ const sessionRef = (0, react.useRef)(0);
1731
+ /**
1732
+ * In-flight synthesis of the current run. Aborting it is what actually stops
1733
+ * playback: suspending the AudioContext alone leaves the remaining sentences
1734
+ * streaming in behind the pause, and they all land on resume.
1735
+ */
1736
+ const abortRef = (0, react.useRef)(null);
1737
+ const streamClearRef = (0, react.useRef)(() => {});
1738
+ streamClearRef.current = streamPlayer.clear;
1739
+ const playerClearRef = (0, react.useRef)(() => {});
1740
+ playerClearRef.current = playerClear;
1741
+ (0, react.useEffect)(() => () => {
1742
+ abortRef.current?.abort();
1743
+ abortRef.current = null;
1744
+ sessionRef.current += 1;
1745
+ playerClearRef.current();
1746
+ streamClearRef.current();
1747
+ highlighterRef.current?.clear();
1748
+ highlighterRef.current = null;
1749
+ cuesRef.current = [];
1750
+ cueCursorRef.current = 0;
1751
+ keyOffsetRef.current = 0;
1752
+ }, []);
1753
+ (0, react.useEffect)(() => {
1754
+ if (!panelOpen) return;
1755
+ const root = rootRef.current;
1756
+ if (root === null) return;
1757
+ const bounds = root.getBoundingClientRect();
1758
+ setPanelSide(bounds.right + 288 > window.innerWidth ? "left" : "right");
1759
+ }, [panelOpen]);
1760
+ (0, react.useEffect)(() => {
1761
+ if (!panelOpen) return;
1762
+ const onPointerDown = (event) => {
1763
+ const root = rootRef.current;
1764
+ if (root !== null && root.contains(event.target)) return;
1765
+ setPanelOpen(false);
1766
+ };
1767
+ document.addEventListener("pointerdown", onPointerDown);
1768
+ return () => {
1769
+ document.removeEventListener("pointerdown", onPointerDown);
1770
+ };
1771
+ }, [panelOpen]);
1772
+ const muteWhileRecording = status.muteWhileRecording !== false;
1773
+ (0, react.useEffect)(() => {
1774
+ if (!muteWhileRecording) return;
1775
+ return onAudioCaptureStart(() => {
1776
+ stopRun();
1777
+ });
1778
+ }, [muteWhileRecording, stopRun]);
1779
+ (0, react.useEffect)(() => {
1780
+ if (!activeState.playing && phase !== "loading") return;
1781
+ const onKeyDown = (event) => {
1782
+ if (event.key !== "Escape") return;
1783
+ stopRun();
1784
+ buttonRef.current?.focus();
1785
+ };
1786
+ document.addEventListener("keydown", onKeyDown);
1787
+ return () => {
1788
+ document.removeEventListener("keydown", onKeyDown);
1789
+ };
1790
+ }, [
1791
+ activeState.playing,
1792
+ phase,
1793
+ stopRun
1794
+ ]);
1795
+ const chunkedRun = (0, react.useCallback)(async (gen, chunks, signal) => {
1796
+ setMode("queue");
1797
+ /** @returns whether this run was cancelled by the reader. */
1798
+ const cancelled = () => gen !== sessionRef.current || signal !== void 0 && signal.aborted;
1799
+ try {
1800
+ let first = true;
1801
+ for (let index = 0; index < chunks.length; index += 1) {
1802
+ if (cancelled()) return;
1803
+ const chunkAudio = await synthesizeChunkUrl(chunks[index], signatureRef.current, signal);
1804
+ if (gen !== sessionRef.current) return;
1805
+ if (chunkAudio.engine === "edge") setEngineUsed("edge");
1806
+ playerEnqueue(chunkAudio.url);
1807
+ if (first) {
1808
+ first = false;
1809
+ setPhase("ready");
1810
+ }
1811
+ }
1812
+ if (!cancelled()) playerFinish();
1813
+ } catch (error) {
1814
+ if (cancelled()) return;
1815
+ setPhase("error");
1816
+ setFailure(error instanceof TtsClientError ? error : new TtsClientError("generic", String(error)));
1817
+ }
1818
+ }, [playerEnqueue, playerFinish]);
1819
+ const streamRun = (0, react.useCallback)(async (gen, chunks, messageText, signal) => {
1820
+ setMode("stream");
1821
+ highlighterRef.current?.clear();
1822
+ highlighterRef.current = status.highlight ? new SentenceHighlighter(findMessageContainer(rootRef.current, messageText)) : null;
1823
+ cuesRef.current = [];
1824
+ cueCursorRef.current = 0;
1825
+ keyOffsetRef.current = 0;
1826
+ /** @returns whether this run was cancelled by the reader. */
1827
+ const cancelled = () => gen !== sessionRef.current || signal !== void 0 && signal.aborted;
1828
+ let gotFirst = false;
1829
+ for (let index = 0; index < chunks.length; index += 1) {
1830
+ if (cancelled()) return;
1831
+ const chunk = chunks[index];
1832
+ let chunkStarted = false;
1833
+ try {
1834
+ await requestSpeechStream({ text: chunk }, (pcm) => {
1835
+ if (gen !== sessionRef.current) return;
1836
+ if (!chunkStarted) {
1837
+ chunkStarted = true;
1838
+ if (!gotFirst) {
1839
+ gotFirst = true;
1840
+ setPhase("ready");
1841
+ }
1842
+ cuesRef.current.push({
1843
+ at: streamPlayer.scheduled(),
1844
+ text: chunk
1845
+ });
1846
+ }
1847
+ streamPlayer.feed(pcm);
1848
+ }, signal);
1849
+ if (gen !== sessionRef.current) return;
1850
+ } catch (error) {
1851
+ if (cancelled()) return;
1852
+ streamPlayer.clear();
1853
+ highlighterRef.current?.clear();
1854
+ highlighterRef.current = null;
1855
+ cuesRef.current = [];
1856
+ cueCursorRef.current = 0;
1857
+ await chunkedRun(gen, chunks.slice(chunkStarted ? index + 1 : index), signal);
1858
+ return;
1859
+ }
1860
+ }
1861
+ if (gen !== sessionRef.current) return;
1862
+ if (!gotFirst) {
1863
+ highlighterRef.current?.clear();
1864
+ highlighterRef.current = null;
1865
+ await chunkedRun(gen, chunks, signal);
1866
+ return;
1867
+ }
1868
+ streamPlayer.finish();
1869
+ }, [
1870
+ chunkedRun,
1871
+ status.highlight,
1872
+ streamPlayer
1873
+ ]);
1874
+ (0, react.useEffect)(() => {
1875
+ if (mode !== "stream") return;
1876
+ const highlighter = highlighterRef.current;
1877
+ if (highlighter === null || !highlighter.supported) return;
1878
+ const cues = cuesRef.current;
1879
+ const now = activeState.currentTime + .08;
1880
+ while (cueCursorRef.current < cues.length && cues[cueCursorRef.current].at <= now) {
1881
+ const cue = cues[cueCursorRef.current];
1882
+ cueCursorRef.current += 1;
1883
+ keyOffsetRef.current = highlighter.show(cue.text, keyOffsetRef.current);
1884
+ }
1885
+ }, [activeState.currentTime, mode]);
1886
+ const runSynthesis = (0, react.useCallback)(async (input) => {
1887
+ abortRef.current?.abort();
1888
+ const controller = new AbortController();
1889
+ abortRef.current = controller;
1890
+ const gen = ++sessionRef.current;
1891
+ setEngineUsed(null);
1892
+ clearPlayers();
1893
+ highlighterRef.current?.clear();
1894
+ highlighterRef.current = null;
1895
+ cuesRef.current = [];
1896
+ cueCursorRef.current = 0;
1897
+ keyOffsetRef.current = 0;
1898
+ setPhase("loading");
1899
+ setFailure(null);
1900
+ setTruncated(false);
1901
+ if (status.progressBar === true) setPanelOpen(true);
1902
+ let spoken = input;
1903
+ if (status.readScope === "brief") {
1904
+ const summarized = await requestSummary(input, controller.signal).catch(() => void 0);
1905
+ if (controller.signal.aborted || gen !== sessionRef.current) return;
1906
+ spoken = summarized ?? briefText(input, 260, 6, t("briefPrefix"));
1907
+ }
1908
+ const all = splitForSpeech(spoken, status.chunkChars);
1909
+ const chunks = budgetChunks(all, status.maxChars);
1910
+ setTruncated(chunks.length < all.length);
1911
+ if (chunks.length === 0) {
1912
+ setPhase("idle");
1913
+ setFailure("empty");
1914
+ return;
1915
+ }
1916
+ if (status.hasVoiceSample) {
1917
+ chunkedRun(gen, chunks, controller.signal);
1918
+ return;
1919
+ }
1920
+ streamRun(gen, chunks, spoken, controller.signal);
1921
+ }, [
1922
+ chunkedRun,
1923
+ clearPlayers,
1924
+ status.chunkChars,
1925
+ status.hasVoiceSample,
1926
+ status.maxChars,
1927
+ status.progressBar,
1928
+ status.readScope,
1929
+ streamRun,
1930
+ t
1931
+ ]);
1932
+ /**
1933
+ * Start a read-aloud. Kept stable for the effects: cancellation lives inside
1934
+ * `runSynthesis`, so callers can fire and forget.
1935
+ */
1936
+ const synthesize = (0, react.useCallback)((input) => {
1937
+ runSynthesis(input);
1938
+ }, [runSynthesis]);
1939
+ (0, react.useEffect)(() => {
1940
+ if (activeState.ended) {
1941
+ highlighterRef.current?.clear();
1942
+ highlighterRef.current = null;
1943
+ }
1944
+ }, [activeState.ended]);
1945
+ const hasAudio = phase === "ready";
1946
+ const autoplayBlocked = hasAudio && !activeState.playing && !activeState.ended && !queueWaiting && activeState.currentTime === 0;
1947
+ const onClick = (0, react.useCallback)(() => {
1948
+ if (phase === "loading") {
1949
+ stopRun();
1950
+ return;
1951
+ }
1952
+ if (hasAudio) {
1953
+ if (queueWaiting) {
1954
+ stopRun();
1955
+ return;
1956
+ }
1957
+ if (activeState.ended) {
1958
+ if (speakable !== void 0 && speakable !== "") synthesize(speakable);
1959
+ return;
1960
+ }
1961
+ if (!showProgressBar) {
1962
+ if (activeState.playing) stopRun();
1963
+ else activeToggle();
1964
+ return;
1965
+ }
1966
+ if (!panelOpen) setPanelOpen(true);
1967
+ panelToggle();
1968
+ return;
1969
+ }
1970
+ if (speakable === void 0 || speakable === "") {
1971
+ setFailure("empty");
1972
+ return;
1973
+ }
1974
+ if (!status.configured) {
1975
+ setFailure("unconfigured");
1976
+ return;
1977
+ }
1978
+ synthesize(speakable);
1979
+ }, [
1980
+ phase,
1981
+ hasAudio,
1982
+ activeState.playing,
1983
+ activeState.ended,
1984
+ queueWaiting,
1985
+ speakable,
1986
+ panelOpen,
1987
+ panelToggle,
1988
+ showProgressBar,
1989
+ status.configured,
1990
+ synthesize,
1991
+ stopRun
1992
+ ]);
1993
+ const autoRead = status.autoRead === true;
1994
+ (0, react.useEffect)(() => {
1995
+ if (!autoRead) return;
1996
+ if (messageId === "" || messageId !== latestId) return;
1997
+ if (running) return;
1998
+ if (speakable === void 0 || speakable === "") return;
1999
+ if (!status.configured) return;
2000
+ if (autoReadLog.has(messageId)) return;
2001
+ if (phase !== "idle") return;
2002
+ const timer = window.setTimeout(() => {
2003
+ if (autoReadLog.has(messageId)) return;
2004
+ autoReadLog.mark(messageId);
2005
+ synthesize(speakable);
2006
+ }, 400);
2007
+ return () => window.clearTimeout(timer);
2008
+ }, [
2009
+ autoRead,
2010
+ latestId,
2011
+ messageId,
2012
+ running,
2013
+ speakable,
2014
+ phase,
2015
+ status.configured,
2016
+ synthesize
2017
+ ]);
2018
+ const fallbackNote = engineUsed === "edge";
2019
+ const panelVisible = playerPanelVisible({
2020
+ progressBar: showProgressBar,
2021
+ panelOpen,
2022
+ hasAudio,
2023
+ loading: phase === "loading"
2024
+ });
2025
+ const hiddenStatus = (failure !== null ? [t(errorKeyFor(failure))] : [
2026
+ ...autoplayBlocked ? [t("autoplayHint")] : [],
2027
+ ...truncated ? [t("truncated")] : [],
2028
+ ...fallbackNote ? [t("fallbackUsed")] : []
2029
+ ]).join(" ");
2030
+ const buttonLabel = phase === "loading" ? t("synthesize") : activeState.playing ? showProgressBar ? t("pause") : t("stop") : queueWaiting ? t("stop") : hasAudio ? t("play") : t("speak");
2031
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
2032
+ ref: rootRef,
2033
+ className: hasAudio ? "mimo-speak-root mimo-speak-open" : "mimo-speak-root",
2034
+ children: [
2035
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tooltip, {
2036
+ label: buttonLabel,
2037
+ side: "bottom",
2038
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2039
+ ref: buttonRef,
2040
+ type: "button",
2041
+ className: phase === "loading" ? "mimo-speak-button mimo-speak-buttonBusy" : "mimo-speak-button",
2042
+ "aria-label": buttonLabel,
2043
+ "aria-busy": phase === "loading",
2044
+ "aria-pressed": activeState.playing,
2045
+ "aria-expanded": showProgressBar ? panelVisible : void 0,
2046
+ "aria-controls": showProgressBar ? panelId : void 0,
2047
+ onClick,
2048
+ onMouseEnter: ensureStatus,
2049
+ onFocus: ensureStatus,
2050
+ children: phase === "loading" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2051
+ className: "mimo-speak-spin",
2052
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconLoadingOutlineRegular, { size: 15 })
2053
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(IconVolumeOutlineRegular, { size: 15 })
2054
+ })
2055
+ }),
2056
+ failure !== null ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tooltip, {
2057
+ label: t(errorKeyFor(failure)),
2058
+ side: "bottom",
2059
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2060
+ className: "mimo-speak-failure",
2061
+ role: "img",
2062
+ tabIndex: 0,
2063
+ "aria-label": t(errorKeyFor(failure)),
2064
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconWarningTriangleOutlineRegular, { size: 14 })
2065
+ })
2066
+ }) : null,
2067
+ !panelVisible && hiddenStatus !== "" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2068
+ className: "mimo-speak-srOnly",
2069
+ role: "status",
2070
+ children: hiddenStatus
2071
+ }) : null,
2072
+ panelVisible ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
2073
+ id: panelId,
2074
+ className: panelSide === "left" ? "mimo-speak-panel mimo-speak-panelLeft" : "mimo-speak-panel",
2075
+ children: [
2076
+ phase === "loading" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2077
+ className: "mimo-speak-panelNote",
2078
+ role: "status",
2079
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.TextShimmer, {
2080
+ active: true,
2081
+ children: t("synthesize")
2082
+ })
2083
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(PlayerBar, {
2084
+ state: activeState,
2085
+ onToggle: panelToggle,
2086
+ onSeek: activeSeek,
2087
+ seekable: mode !== "stream",
2088
+ labels: {
2089
+ play: t("play"),
2090
+ pause: t("pause"),
2091
+ progress: t("progress")
2092
+ }
2093
+ }),
2094
+ failure !== null ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
2095
+ className: "mimo-speak-panelStatus",
2096
+ role: "status",
2097
+ children: t(errorKeyFor(failure))
2098
+ }) : null,
2099
+ failure === null && autoplayBlocked ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
2100
+ className: "mimo-speak-panelNote",
2101
+ role: "status",
2102
+ children: t("autoplayHint")
2103
+ }) : null,
2104
+ failure === null && truncated ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
2105
+ className: "mimo-speak-panelNote",
2106
+ role: "status",
2107
+ children: t("truncated")
2108
+ }) : null,
2109
+ failure === null && fallbackNote ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
2110
+ className: "mimo-speak-panelNote",
2111
+ role: "status",
2112
+ children: t("fallbackUsed")
2113
+ }) : null
2114
+ ]
2115
+ }) : null
2116
+ ]
2117
+ });
2118
+ }
2119
+ // src/client/use-audio-player.ts
2120
+ /**
2121
+ * The playback engine behind every player this plugin renders: one hidden
2122
+ * `HTMLAudioElement` per mounted player, mirrored into React state, with a
2123
+ * module-local registry so starting one player pauses the other.
2124
+ *
2125
+ * The registry is deliberately module-local mutable UI state: it coordinates
2126
+ * components of this one plugin bundle and lives in the browser only. Business
2127
+ * and transport state stay in the settings namespace and the Host routes.
2128
+ * @module dsh-mimo-speak/client/use-audio-player
2129
+ */
2130
+ const IDLE = {
2131
+ playing: false,
2132
+ currentTime: 0,
2133
+ duration: 0,
2134
+ ended: false
2135
+ };
2136
+ /**
2137
+ * Bind one audio source to playback state and controls.
2138
+ *
2139
+ * A new `source` replaces the element: the old one pauses and detaches, and
2140
+ * playback state returns to zero. Passing null keeps the hook idle.
2141
+ * @param source - object URL of the WAV to play, or null.
2142
+ * @returns playback state plus the toggle and seek controls.
2143
+ */
2144
+ function useAudioPlayer(source) {
2145
+ const [state, setState] = (0, react.useState)(IDLE);
2146
+ const elementRef = (0, react.useRef)(null);
2147
+ (0, react.useEffect)(() => {
2148
+ if (source === null) return;
2149
+ const audio = new Audio(source);
2150
+ elementRef.current = audio;
2151
+ const publish = (patch) => {
2152
+ setState((previous) => ({
2153
+ ...previous,
2154
+ ...patch
2155
+ }));
2156
+ };
2157
+ const onTime = () => {
2158
+ publish({ currentTime: audio.currentTime });
2159
+ };
2160
+ const onLoaded = () => {
2161
+ publish({ duration: Number.isFinite(audio.duration) ? audio.duration : 0 });
2162
+ };
2163
+ const onPlay = () => {
2164
+ pauseOtherAudio(audio);
2165
+ publish({
2166
+ playing: true,
2167
+ ended: false
2168
+ });
2169
+ };
2170
+ const onPause = () => {
2171
+ publish({ playing: false });
2172
+ };
2173
+ const onEnded = () => {
2174
+ publish({
2175
+ playing: false,
2176
+ ended: true,
2177
+ currentTime: 0
2178
+ });
2179
+ };
2180
+ audio.addEventListener("timeupdate", onTime);
2181
+ audio.addEventListener("loadedmetadata", onLoaded);
2182
+ audio.addEventListener("durationchange", onLoaded);
2183
+ audio.addEventListener("play", onPlay);
2184
+ audio.addEventListener("pause", onPause);
2185
+ audio.addEventListener("ended", onEnded);
2186
+ setState({
2187
+ playing: false,
2188
+ currentTime: 0,
2189
+ duration: 0,
2190
+ ended: false
2191
+ });
2192
+ const unregister = registerAudioPauser(audio, () => {
2193
+ audio.pause();
2194
+ });
2195
+ return () => {
2196
+ unregister();
2197
+ audio.pause();
2198
+ audio.removeAttribute("src");
2199
+ audio.load();
2200
+ audio.removeEventListener("timeupdate", onTime);
2201
+ audio.removeEventListener("loadedmetadata", onLoaded);
2202
+ audio.removeEventListener("durationchange", onLoaded);
2203
+ audio.removeEventListener("play", onPlay);
2204
+ audio.removeEventListener("pause", onPause);
2205
+ audio.removeEventListener("ended", onEnded);
2206
+ elementRef.current = null;
2207
+ };
2208
+ }, [source]);
2209
+ return {
2210
+ state,
2211
+ toggle: (0, react.useCallback)(() => {
2212
+ const audio = elementRef.current;
2213
+ if (audio === null) return;
2214
+ if (audio.paused) {
2215
+ pauseOtherAudio(audio);
2216
+ if (audio.ended) audio.currentTime = 0;
2217
+ audio.play().catch(() => {
2218
+ setState((previous) => ({
2219
+ ...previous,
2220
+ playing: false
2221
+ }));
2222
+ });
2223
+ } else audio.pause();
2224
+ }, []),
2225
+ seek: (0, react.useCallback)((seconds) => {
2226
+ const audio = elementRef.current;
2227
+ if (audio === null) return;
2228
+ const duration = Number.isFinite(audio.duration) ? audio.duration : 0;
2229
+ const target = Math.max(0, duration > 0 ? Math.min(seconds, duration) : seconds);
2230
+ audio.currentTime = target;
2231
+ setState((previous) => ({
2232
+ ...previous,
2233
+ currentTime: target,
2234
+ ended: false
2235
+ }));
2236
+ }, []),
2237
+ pause: (0, react.useCallback)(() => {
2238
+ const audio = elementRef.current;
2239
+ if (audio !== null) audio.pause();
2240
+ }, [])
2241
+ };
2242
+ }
2243
+ // src/client/TtsSettingsForm.tsx
2244
+ /**
2245
+ * Shared MiMo settings form body used by both surfaces: the Plugins-page
2246
+ * configuration card and the DSH global Settings section. The write-only API
2247
+ * key (host credentials store), endpoint, model, voice, style, budgets and the
2248
+ * sample player are identical; only the DOM id prefix changes so both surfaces
2249
+ * can stay mounted without duplicate control ids.
2250
+ *
2251
+ * The form frame follows the platform's configuration-form conventions for
2252
+ * saving, discarding, overrides and read-only/unavailable handling.
2253
+ * @module dsh-mimo-speak/client/TtsSettingsForm
2254
+ */
2255
+ /**
2256
+ * Map the staged draft text onto one of the segmented control's values.
2257
+ * @param text - current draft of the `readScope` field.
2258
+ * @returns the scope to render as selected.
2259
+ */
2260
+ function normalizeScope(text) {
2261
+ const value = text.trim();
2262
+ return value === "all" || value === "smart" || value === "brief" ? value : "text";
2263
+ }
2264
+ /**
2265
+ * The official preset voices of `mimo-v2.5-tts` (Xiaomi MiMo speech-synthesis
2266
+ * docs, 预置音色列表). The voice id is what the API's `audio.voice` takes;
2267
+ * the display name is the docs' naming.
2268
+ */
2269
+ const PRESET_VOICES = [
2270
+ {
2271
+ id: "mimo_default",
2272
+ name: "MiMo-默认"
2273
+ },
2274
+ {
2275
+ id: "冰糖",
2276
+ name: "冰糖"
2277
+ },
2278
+ {
2279
+ id: "茉莉",
2280
+ name: "茉莉"
2281
+ },
2282
+ {
2283
+ id: "苏打",
2284
+ name: "苏打"
2285
+ },
2286
+ {
2287
+ id: "白桦",
2288
+ name: "白桦"
2289
+ },
2290
+ {
2291
+ id: "Mia",
2292
+ name: "Mia"
2293
+ },
2294
+ {
2295
+ id: "Chloe",
2296
+ name: "Chloe"
2297
+ },
2298
+ {
2299
+ id: "Milo",
2300
+ name: "Milo"
2301
+ },
2302
+ {
2303
+ id: "Dean",
2304
+ name: "Dean"
2305
+ }
2306
+ ];
2307
+ /**
2308
+ * Common Edge TTS neural voices for Chinese. The voice id is what the
2309
+ * `edge-tts --voice` flag takes; the display name is the voice's familiar
2310
+ * name. A saved value outside this list stays selectable as a custom option.
2311
+ */
2312
+ const EDGE_VOICES = [
2313
+ {
2314
+ id: "zh-CN-XiaoxiaoNeural",
2315
+ name: "晓晓(女·默认)"
2316
+ },
2317
+ {
2318
+ id: "zh-CN-XiaoyiNeural",
2319
+ name: "晓伊(女)"
2320
+ },
2321
+ {
2322
+ id: "zh-CN-XiaoshuangNeural",
2323
+ name: "晓双(女·儿童)"
2324
+ },
2325
+ {
2326
+ id: "zh-CN-YunxiNeural",
2327
+ name: "云希(男)"
2328
+ },
2329
+ {
2330
+ id: "zh-CN-YunjianNeural",
2331
+ name: "云健(男)"
2332
+ },
2333
+ {
2334
+ id: "zh-CN-YunyangNeural",
2335
+ name: "云扬(男·新闻)"
2336
+ },
2337
+ {
2338
+ id: "zh-CN-YunxiaNeural",
2339
+ name: "云夏(男·少年)"
2340
+ },
2341
+ {
2342
+ id: "zh-CN-liaoning-XiaobeiNeural",
2343
+ name: "晓北(东北话)"
2344
+ },
2345
+ {
2346
+ id: "zh-CN-shaanxi-XiaoniNeural",
2347
+ name: "晓妮(陕西话)"
2348
+ },
2349
+ {
2350
+ id: "zh-TW-HsiaoChenNeural",
2351
+ name: "曉臻(台湾)"
2352
+ },
2353
+ {
2354
+ id: "zh-HK-HiuMaanNeural",
2355
+ name: "曉曼(香港)"
2356
+ }
2357
+ ];
2358
+ /**
2359
+ * Render the MiMo settings form.
2360
+ * @param props - injected form face, locale copy and the id prefix.
2361
+ * @returns the configuration form with its sample player.
2362
+ */
2363
+ function TtsSettingsForm({ t, idPrefix, useForm, edit, resetField, save, discard, synthesize, test }) {
2364
+ const state = useForm((snapshot) => snapshot);
2365
+ const [sampleUrl, setSampleUrl] = (0, react.useState)(null);
2366
+ const [busy, setBusy] = (0, react.useState)(false);
2367
+ const [failure, setFailure] = (0, react.useState)(null);
2368
+ const [testing, setTesting] = (0, react.useState)(false);
2369
+ const [testResult, setTestResult] = (0, react.useState)(null);
2370
+ const player = useAudioPlayer(sampleUrl);
2371
+ const toggle = player.toggle;
2372
+ const autoplay = (0, react.useRef)(false);
2373
+ const sampleRef = (0, react.useRef)(null);
2374
+ sampleRef.current = sampleUrl;
2375
+ (0, react.useEffect)(() => () => {
2376
+ if (sampleRef.current !== null) URL.revokeObjectURL(sampleRef.current);
2377
+ }, []);
2378
+ (0, react.useEffect)(() => {
2379
+ if (sampleUrl === null || !autoplay.current) return;
2380
+ autoplay.current = false;
2381
+ toggle();
2382
+ }, [sampleUrl, toggle]);
2383
+ const audition = (0, react.useCallback)(() => {
2384
+ if (busy) return;
2385
+ setBusy(true);
2386
+ setFailure(null);
2387
+ synthesize({
2388
+ text: AUDITION_TEXT,
2389
+ style: state.style.text.trim() === "" ? void 0 : state.style.text,
2390
+ voice: state.voice.text.trim() === "" ? void 0 : state.voice.text
2391
+ }).then((blob) => {
2392
+ autoplay.current = true;
2393
+ setBusy(false);
2394
+ setSampleUrl((previous) => {
2395
+ if (previous !== null) URL.revokeObjectURL(previous);
2396
+ return URL.createObjectURL(blob);
2397
+ });
2398
+ }).catch((error) => {
2399
+ setBusy(false);
2400
+ setFailure(error instanceof TtsClientError ? error : new TtsClientError("generic", String(error)));
2401
+ });
2402
+ }, [
2403
+ busy,
2404
+ state.style.text,
2405
+ state.voice.text,
2406
+ synthesize
2407
+ ]);
2408
+ const runTest = (0, react.useCallback)(() => {
2409
+ if (testing) return;
2410
+ setTesting(true);
2411
+ setTestResult(null);
2412
+ test().then((result) => {
2413
+ setTesting(false);
2414
+ const engine = result.engine === "edge" ? t("engineEdge") : t("engineMimo");
2415
+ setTestResult(t("testOk").replace("{engine}", engine).replace("{ms}", String(result.latencyMs)));
2416
+ }).catch((error) => {
2417
+ setTesting(false);
2418
+ setTestResult(`${t("testFailed")}: ${error instanceof TtsClientError ? error.message : String(error)}`);
2419
+ });
2420
+ }, [
2421
+ test,
2422
+ testing,
2423
+ t
2424
+ ]);
2425
+ const disabled = !state.writable;
2426
+ const id = (name) => `${idPrefix}-${name}`;
2427
+ const failureKey = failure === null ? null : errorKeyFor(failure);
2428
+ const voiceDraft = state.voice.text.trim() === "" ? DEFAULT_VOICE : state.voice.text;
2429
+ const customVoice = PRESET_VOICES.some((voice) => voice.id === voiceDraft) ? null : voiceDraft;
2430
+ const edgeVoiceDraft = state.edgeVoice.text.trim() === "" ? DEFAULT_EDGE_VOICE : state.edgeVoice.text;
2431
+ const customEdgeVoice = EDGE_VOICES.some((voice) => voice.id === edgeVoiceDraft) ? null : edgeVoiceDraft;
2432
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_deepseek_ai_dsh_client_ui_primitives.SettingsForm, {
2433
+ labels: {
2434
+ unavailable: t("unavailable"),
2435
+ readOnly: t("readOnly"),
2436
+ saveFailed: t("saveFailed"),
2437
+ save: t("save"),
2438
+ saving: t("saving")
2439
+ },
2440
+ state,
2441
+ onSave: save,
2442
+ onDiscard: discard,
2443
+ children: [
2444
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("h4", {
2445
+ className: "mimo-speak-sectionTitle",
2446
+ children: t("sectionConnection")
2447
+ }),
2448
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.SettingsSecretField, {
2449
+ id: id("api-key"),
2450
+ label: t("apiKey"),
2451
+ hint: t("apiKeyHint"),
2452
+ text: state.apiKey.text,
2453
+ disabled,
2454
+ configured: state.apiKeyConfigured,
2455
+ stateLabel: state.apiKeyConfigured ? t("apiKeySet") : t("apiKeyUnset"),
2456
+ onEdit: (text) => {
2457
+ edit("apiKey", text);
2458
+ }
2459
+ }),
2460
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
2461
+ className: "mimo-speak-auditionHint",
2462
+ role: "status",
2463
+ style: { marginTop: -6 },
2464
+ children: state.apiKeyEnv !== void 0 && state.apiKeyEnv.trim() !== "" ? `${t("apiKeyRef")} ${state.apiKeyEnv}` : t("apiKeyRefDefault")
2465
+ }),
2466
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.SettingsValueField, {
2467
+ id: id("base-url"),
2468
+ label: t("baseUrl"),
2469
+ hint: t("baseUrlHint"),
2470
+ overriddenLabel: t("overridden"),
2471
+ resetLabel: t("reset"),
2472
+ invalidLabel: t("invalidNumber"),
2473
+ disabled,
2474
+ ...state.baseUrl,
2475
+ onEdit: (text) => {
2476
+ edit("baseUrl", text);
2477
+ },
2478
+ onReset: () => {
2479
+ resetField("baseUrl");
2480
+ }
2481
+ }),
2482
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.SettingsValueField, {
2483
+ id: id("model"),
2484
+ label: t("model"),
2485
+ hint: t("modelHint"),
2486
+ overriddenLabel: t("overridden"),
2487
+ resetLabel: t("reset"),
2488
+ invalidLabel: t("invalidNumber"),
2489
+ disabled,
2490
+ ...state.model,
2491
+ onEdit: (text) => {
2492
+ edit("model", text);
2493
+ },
2494
+ onReset: () => {
2495
+ resetField("model");
2496
+ }
2497
+ }),
2498
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("h4", {
2499
+ className: "mimo-speak-sectionTitle",
2500
+ children: t("sectionVoice")
2501
+ }),
2502
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2503
+ className: "mimo-speak-selectField",
2504
+ children: [
2505
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("label", {
2506
+ className: "mimo-speak-selectLabel",
2507
+ htmlFor: id("voice-select"),
2508
+ children: t("voice")
2509
+ }),
2510
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("select", {
2511
+ id: id("voice-select"),
2512
+ className: "mimo-speak-select",
2513
+ disabled: disabled || state.voiceSamplePath.text.trim() !== "",
2514
+ title: state.voiceSamplePath.text.trim() !== "" ? t("voiceHint") : void 0,
2515
+ value: voiceDraft,
2516
+ onChange: (event) => {
2517
+ edit("voice", event.target.value);
2518
+ },
2519
+ children: [PRESET_VOICES.map((voice) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
2520
+ value: voice.id,
2521
+ children: voice.id === "mimo_default" ? `${voice.name}(默认)` : voice.name
2522
+ }, voice.id)), customVoice !== null ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
2523
+ value: customVoice,
2524
+ children: customVoice
2525
+ }) : null]
2526
+ }),
2527
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
2528
+ className: "mimo-speak-auditionHint",
2529
+ children: t("voiceHint")
2530
+ })
2531
+ ]
2532
+ }),
2533
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.SettingsValueField, {
2534
+ id: id("voice-sample"),
2535
+ label: t("voiceSamplePath"),
2536
+ hint: t("voiceSamplePathHint"),
2537
+ overriddenLabel: t("overridden"),
2538
+ resetLabel: t("reset"),
2539
+ invalidLabel: t("invalidNumber"),
2540
+ disabled,
2541
+ ...state.voiceSamplePath,
2542
+ onEdit: (text) => {
2543
+ edit("voiceSamplePath", text);
2544
+ },
2545
+ onReset: () => {
2546
+ resetField("voiceSamplePath");
2547
+ }
2548
+ }),
2549
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.SettingsValueField, {
2550
+ id: id("style"),
2551
+ label: t("style"),
2552
+ hint: t("styleHint"),
2553
+ overriddenLabel: t("overridden"),
2554
+ resetLabel: t("reset"),
2555
+ invalidLabel: t("invalidNumber"),
2556
+ disabled,
2557
+ ...state.style,
2558
+ onEdit: (text) => {
2559
+ edit("style", text);
2560
+ },
2561
+ onReset: () => {
2562
+ resetField("style");
2563
+ }
2564
+ }),
2565
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("h4", {
2566
+ className: "mimo-speak-sectionTitle",
2567
+ children: t("sectionBehavior")
2568
+ }),
2569
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2570
+ className: "mimo-speak-selectField",
2571
+ children: [
2572
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2573
+ className: "mimo-speak-selectLabel",
2574
+ children: t("autoRead")
2575
+ }),
2576
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Switch, {
2577
+ checked: state.autoRead.text.trim() === "true",
2578
+ onChange: (next) => {
2579
+ edit("autoRead", String(next));
2580
+ },
2581
+ label: t("autoRead"),
2582
+ disabled
2583
+ }),
2584
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
2585
+ className: "mimo-speak-auditionHint",
2586
+ children: t("autoReadHint")
2587
+ })
2588
+ ]
2589
+ }),
2590
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2591
+ className: "mimo-speak-selectField",
2592
+ children: [
2593
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2594
+ className: "mimo-speak-selectLabel",
2595
+ children: t("fallbackEngine")
2596
+ }),
2597
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.SegmentedControl, {
2598
+ id: id("fallback"),
2599
+ value: state.fallbackEngine.text.trim() === "edge" ? "edge" : "none",
2600
+ options: [{
2601
+ value: "none",
2602
+ label: t("fallbackEngineNone")
2603
+ }, {
2604
+ value: "edge",
2605
+ label: t("fallbackEngineEdge")
2606
+ }],
2607
+ onChange: (next) => {
2608
+ edit("fallbackEngine", next);
2609
+ },
2610
+ label: t("fallbackEngine"),
2611
+ disabled
2612
+ }),
2613
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
2614
+ className: "mimo-speak-auditionHint",
2615
+ children: t("fallbackEngineHint")
2616
+ })
2617
+ ]
2618
+ }),
2619
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2620
+ className: "mimo-speak-selectField",
2621
+ children: [
2622
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("label", {
2623
+ className: "mimo-speak-selectLabel",
2624
+ htmlFor: id("edge-voice-select"),
2625
+ children: t("edgeVoice")
2626
+ }),
2627
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("select", {
2628
+ id: id("edge-voice-select"),
2629
+ className: "mimo-speak-select",
2630
+ disabled: disabled || state.fallbackEngine.text.trim() !== "edge",
2631
+ title: state.fallbackEngine.text.trim() !== "edge" ? t("fallbackEngineHint") : void 0,
2632
+ value: edgeVoiceDraft,
2633
+ onChange: (event) => {
2634
+ edit("edgeVoice", event.target.value);
2635
+ },
2636
+ children: [
2637
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("optgroup", {
2638
+ label: "普通话",
2639
+ children: EDGE_VOICES.filter((voice) => voice.id.startsWith("zh-CN-")).map((voice) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
2640
+ value: voice.id,
2641
+ children: voice.name
2642
+ }, voice.id))
2643
+ }),
2644
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("optgroup", {
2645
+ label: "台湾",
2646
+ children: EDGE_VOICES.filter((voice) => voice.id.startsWith("zh-TW-")).map((voice) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
2647
+ value: voice.id,
2648
+ children: voice.name
2649
+ }, voice.id))
2650
+ }),
2651
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("optgroup", {
2652
+ label: "香港",
2653
+ children: EDGE_VOICES.filter((voice) => voice.id.startsWith("zh-HK-")).map((voice) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
2654
+ value: voice.id,
2655
+ children: voice.name
2656
+ }, voice.id))
2657
+ }),
2658
+ customEdgeVoice !== null ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
2659
+ value: customEdgeVoice,
2660
+ children: customEdgeVoice
2661
+ }) : null
2662
+ ]
2663
+ }),
2664
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
2665
+ className: "mimo-speak-auditionHint",
2666
+ children: t("edgeVoiceHint")
2667
+ })
2668
+ ]
2669
+ }),
2670
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2671
+ className: "mimo-speak-selectField",
2672
+ children: [
2673
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2674
+ className: "mimo-speak-selectLabel",
2675
+ children: t("readScope")
2676
+ }),
2677
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.SegmentedControl, {
2678
+ id: id("scope"),
2679
+ value: normalizeScope(state.readScope.text),
2680
+ options: [
2681
+ {
2682
+ value: "brief",
2683
+ label: t("readScopeBrief")
2684
+ },
2685
+ {
2686
+ value: "text",
2687
+ label: t("readScopeText")
2688
+ },
2689
+ {
2690
+ value: "smart",
2691
+ label: t("readScopeSmart")
2692
+ },
2693
+ {
2694
+ value: "all",
2695
+ label: t("readScopeAll")
2696
+ }
2697
+ ],
2698
+ onChange: (next) => {
2699
+ edit("readScope", next);
2700
+ },
2701
+ label: t("readScope"),
2702
+ disabled
2703
+ }),
2704
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
2705
+ className: "mimo-speak-auditionHint",
2706
+ children: t("readScopeHint")
2707
+ })
2708
+ ]
2709
+ }),
2710
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2711
+ className: "mimo-speak-selectField",
2712
+ children: [
2713
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2714
+ className: "mimo-speak-selectLabel",
2715
+ children: t("highlight")
2716
+ }),
2717
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Switch, {
2718
+ checked: state.highlight.text.trim() !== "false",
2719
+ onChange: (next) => {
2720
+ edit("highlight", String(next));
2721
+ },
2722
+ label: t("highlight"),
2723
+ disabled
2724
+ }),
2725
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
2726
+ className: "mimo-speak-auditionHint",
2727
+ children: t("highlightHint")
2728
+ })
2729
+ ]
2730
+ }),
2731
+ state.supportsMuteWhileRecording ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2732
+ className: "mimo-speak-selectField",
2733
+ children: [
2734
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2735
+ className: "mimo-speak-selectLabel",
2736
+ children: t("muteWhileRecording")
2737
+ }),
2738
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Switch, {
2739
+ checked: state.muteWhileRecording.text.trim() !== "false",
2740
+ onChange: (next) => {
2741
+ edit("muteWhileRecording", String(next));
2742
+ },
2743
+ label: t("muteWhileRecording"),
2744
+ disabled
2745
+ }),
2746
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
2747
+ className: "mimo-speak-auditionHint",
2748
+ children: t("muteWhileRecordingHint")
2749
+ })
2750
+ ]
2751
+ }) : null,
2752
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
2753
+ className: "mimo-speak-auditionHint",
2754
+ children: t("voiceInputNote")
2755
+ }),
2756
+ state.supportsProgressBar ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2757
+ className: "mimo-speak-selectField",
2758
+ children: [
2759
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2760
+ className: "mimo-speak-selectLabel",
2761
+ children: t("progressBar")
2762
+ }),
2763
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Switch, {
2764
+ checked: state.progressBar.text.trim() === "true",
2765
+ onChange: (next) => {
2766
+ edit("progressBar", String(next));
2767
+ },
2768
+ label: t("progressBar"),
2769
+ disabled
2770
+ }),
2771
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
2772
+ className: "mimo-speak-auditionHint",
2773
+ children: t("progressBarHint")
2774
+ })
2775
+ ]
2776
+ }) : null,
2777
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.SettingsValueField, {
2778
+ id: id("max-chars"),
2779
+ label: t("maxChars"),
2780
+ hint: t("maxCharsHint"),
2781
+ overriddenLabel: t("overridden"),
2782
+ resetLabel: t("reset"),
2783
+ invalidLabel: t("invalidNumber"),
2784
+ numeric: true,
2785
+ disabled,
2786
+ ...state.maxChars,
2787
+ onEdit: (text) => {
2788
+ edit("maxChars", text);
2789
+ },
2790
+ onReset: () => {
2791
+ resetField("maxChars");
2792
+ }
2793
+ }),
2794
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.SettingsValueField, {
2795
+ id: id("chunk-chars"),
2796
+ label: t("chunkChars"),
2797
+ hint: t("chunkCharsHint"),
2798
+ overriddenLabel: t("overridden"),
2799
+ resetLabel: t("reset"),
2800
+ invalidLabel: t("invalidNumber"),
2801
+ numeric: true,
2802
+ disabled,
2803
+ ...state.chunkChars,
2804
+ onEdit: (text) => {
2805
+ edit("chunkChars", text);
2806
+ },
2807
+ onReset: () => {
2808
+ resetField("chunkChars");
2809
+ }
2810
+ }),
2811
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.SettingsValueField, {
2812
+ id: id("timeout"),
2813
+ label: t("timeoutMs"),
2814
+ hint: t("timeoutMsHint"),
2815
+ overriddenLabel: t("overridden"),
2816
+ resetLabel: t("reset"),
2817
+ invalidLabel: t("invalidNumber"),
2818
+ numeric: true,
2819
+ disabled,
2820
+ ...state.timeoutMs,
2821
+ onEdit: (text) => {
2822
+ edit("timeoutMs", text);
2823
+ },
2824
+ onReset: () => {
2825
+ resetField("timeoutMs");
2826
+ }
2827
+ }),
2828
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("h4", {
2829
+ className: "mimo-speak-sectionTitle",
2830
+ children: t("sectionAudition")
2831
+ }),
2832
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2833
+ className: "mimo-speak-audition",
2834
+ children: [
2835
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
2836
+ className: "mimo-speak-auditionHint",
2837
+ children: t("auditionHint")
2838
+ }),
2839
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2840
+ className: "mimo-speak-auditionRow",
2841
+ children: [
2842
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2843
+ type: "button",
2844
+ className: "mimo-speak-auditionButton",
2845
+ disabled: busy,
2846
+ onClick: audition,
2847
+ children: busy ? t("auditioning") : t("audition")
2848
+ }),
2849
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2850
+ type: "button",
2851
+ className: "mimo-speak-auditionButton",
2852
+ disabled: testing,
2853
+ onClick: runTest,
2854
+ children: testing ? t("testing") : t("test")
2855
+ }),
2856
+ sampleUrl !== null ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(PlayerBar, {
2857
+ state: player.state,
2858
+ onToggle: player.toggle,
2859
+ onSeek: player.seek,
2860
+ labels: {
2861
+ play: t("play"),
2862
+ pause: t("pause"),
2863
+ progress: t("progress")
2864
+ }
2865
+ }) : null
2866
+ ]
2867
+ }),
2868
+ failureKey !== null ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
2869
+ className: "mimo-speak-fieldError",
2870
+ role: "status",
2871
+ children: t(failureKey)
2872
+ }) : null,
2873
+ testResult !== null ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
2874
+ className: "mimo-speak-auditionHint",
2875
+ role: "status",
2876
+ children: testResult
2877
+ }) : null
2878
+ ]
2879
+ })
2880
+ ]
2881
+ });
2882
+ }
2883
+ // src/client/BundleConfigCard.tsx
2884
+ /**
2885
+ * The plugin's configuration card on the Plugins page: registered into the
2886
+ * `plugins.bundle.config` keyed slot (key = the npm package name), it renders
2887
+ * inside the bundle's detail page between its description and its rows. The
2888
+ * form body lives in {@link TtsSettingsForm} so the DSH global Settings section
2889
+ * can render the same controls with its own form controller and DOM ids.
2890
+ * @module dsh-mimo-speak/client/BundleConfigCard
2891
+ */
2892
+ /**
2893
+ * Render the Plugins-page configuration card.
2894
+ * @param props - slot runtime props, injected form face and locale copy.
2895
+ * @returns the form on the page view, or null for a summary dispatch.
2896
+ */
2897
+ function BundleConfigCard({ view, ...form }) {
2898
+ if (view !== "page") return null;
2899
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TtsSettingsForm, {
2900
+ ...form,
2901
+ idPrefix: PLUGINS_FORM_ID_PREFIX
2902
+ });
2903
+ }
2904
+ // src/client/SettingsSectionCard.tsx
2905
+ /**
2906
+ * MiMo read-aloud page in the DSH global Settings panel. Registered into the
2907
+ * `settings.section` list slot; it reuses the exact same form body as the
2908
+ * Plugins-page card, with its own controller and DOM id prefix so both surfaces
2909
+ * can stay mounted without sharing drafts or duplicate control ids.
2910
+ * @module dsh-mimo-speak/client/SettingsSectionCard
2911
+ */
2912
+ /**
2913
+ * Render the MiMo settings page inside DSH Settings.
2914
+ * @param props - slot runtime props, injected form face and locale copy.
2915
+ * @returns the shared configuration form.
2916
+ */
2917
+ function SettingsSectionCard(props) {
2918
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TtsSettingsForm, {
2919
+ ...props,
2920
+ idPrefix: SETTINGS_FORM_ID_PREFIX
2921
+ });
2922
+ }
2923
+ // src/client/locales.ts
2924
+ /** Dictionary namespace owned by this plugin. */
2925
+ const NS = "settings.mimo-speak";
2926
+ /** English copy. */
2927
+ const en = {
2928
+ speak: "Read aloud",
2929
+ synthesize: "Synthesizing…",
2930
+ play: "Play",
2931
+ pause: "Pause",
2932
+ stop: "Stop reading",
2933
+ progress: "Playback position",
2934
+ emptyText: "This message carries no speakable text.",
2935
+ truncated: "The reply is long; only the opening is spoken.",
2936
+ "error.notConfigured": "Set the MiMo API key on the plugin card on the Plugins page first.",
2937
+ "error.badRequest": "The text could not be spoken as-is.",
2938
+ "error.timeout": "MiMo TTS did not answer in time.",
2939
+ "error.upstream": "MiMo TTS rejected the request.",
2940
+ "error.invalidAudio": "MiMo TTS returned audio that could not be played.",
2941
+ "error.voiceSample": "The voice-clone sample could not be read on the Host.",
2942
+ "error.generic": "Speech synthesis failed.",
2943
+ audition: "Play sample",
2944
+ auditioning: "Preparing sample…",
2945
+ auditionHint: "Speaks a sample sentence with the style and voice currently on this card (saved or not).",
2946
+ apiKey: "API Key",
2947
+ apiKeyHint: "Paste the MiMo API key here. It is stored in the host credentials store and never rides a page response; clearing the field and saving changes nothing.",
2948
+ apiKeyRef: "Credential reference:",
2949
+ apiKeyRefDefault: "Credential reference: MIMO_API_KEY (default).",
2950
+ apiKeySet: "A key is configured.",
2951
+ apiKeyUnset: "No key is configured.",
2952
+ baseUrl: "Endpoint base",
2953
+ baseUrlHint: "Leave blank to use https://api.xiaomimimo.com/v1; /chat/completions is appended.",
2954
+ model: "Model",
2955
+ modelHint: "Leave blank to use mimo-v2.5-tts.",
2956
+ voice: "Preset voice",
2957
+ voiceHint: "Pick a preset voice; ignored while a voice-clone sample is set.",
2958
+ voiceSamplePath: "Voice-clone sample (Host path)",
2959
+ voiceSamplePathHint: "A 5–15 s WAV (24 kHz / 16-bit / mono) on the Host. Leave blank to speak with the preset voice.",
2960
+ style: "Default speaking style",
2961
+ styleHint: "A natural-language phrase such as \"开心\", \"语速慢\", or \"东北话\". Leave blank to let the model judge for itself (recommended).",
2962
+ maxChars: "Max characters per request",
2963
+ maxCharsHint: "Longer replies are spoken from the beginning up to this budget, cut at a sentence boundary.",
2964
+ chunkChars: "Characters per playback chunk",
2965
+ chunkCharsHint: "Replies are split into chunks around this size and played back-to-back while the next chunk synthesizes, so the first sound starts in seconds. Smaller = faster start, more requests.",
2966
+ timeoutMs: "Request timeout (ms)",
2967
+ timeoutMsHint: "Upper bound on one synthesis round-trip to MiMo TTS.",
2968
+ autoRead: "Automatic read-aloud",
2969
+ autoReadHint: "Speak each newly finished assistant reply with the configured voice and style. Keep the conversation open; if the browser blocks autoplay, tap the speaker on the message.",
2970
+ fallbackEngine: "Fallback engine",
2971
+ fallbackEngineNone: "Off — MiMo only",
2972
+ fallbackEngineEdge: "Edge TTS (keyless)",
2973
+ fallbackEngineHint: "When MiMo fails or is unreachable, Edge TTS speaks the reply instead. Edge is keyless but uses a different voice.",
2974
+ edgeVoice: "Edge voice",
2975
+ edgeVoiceHint: "Any Edge neural voice, e.g. zh-CN-XiaoxiaoNeural (recommended) or zh-CN-YunxiNeural.",
2976
+ readScope: "Read scope",
2977
+ readScopeBrief: "Brief — summarize, then read",
2978
+ briefPrefix: "Brief summary. ",
2979
+ readScopeText: "Prose only — skip code and tables",
2980
+ readScopeAll: "Read everything — including code",
2981
+ readScopeSmart: "Smart — prose plus short code snippets",
2982
+ readScopeHint: "Which parts of a reply the speaker reads aloud. Brief first asks the model already configured in this conversation to condense the reply into one or two spoken sentences (about 80 characters), then reads only that summary — code and tables never reach it. When no model can answer, it falls back to the offline rule: the first sentence of every block, capped at 6 sentences / 260 characters. Smart skips long code listings but reads short snippets.",
2983
+ highlight: "Sentence highlight",
2984
+ highlightHint: "Tint the sentence being read inside the message. Streaming read-aloud only.",
2985
+ fallbackUsed: "MiMo did not answer — this read uses the Edge fallback voice.",
2986
+ muteWhileRecording: "Stop when the microphone opens",
2987
+ muteWhileRecordingHint: "Reading stops the moment a recorder starts, so the microphone never captures the assistant reading its own reply. Pairs with the official voice-input bundle.",
2988
+ voiceInputNote: "Voice input itself is the official @deepseek-ai/dsh-experimental-voice-input-bundle — install it from Plugins; this plugin only handles playback.",
2989
+ test: "Test connection",
2990
+ testing: "Testing…",
2991
+ testOk: "OK — {engine} answered in {ms} ms",
2992
+ testFailed: "Connection failed",
2993
+ engineMimo: "MiMo",
2994
+ engineEdge: "Edge",
2995
+ sectionConnection: "Connection",
2996
+ sectionVoice: "Voice",
2997
+ sectionBehavior: "Read-aloud behaviour",
2998
+ sectionAudition: "Sample and connection test",
2999
+ autoplayHint: "Autoplay was blocked — press play to start.",
3000
+ progressBar: "Progress bar",
3001
+ progressBarHint: "Show the scrub track in the floating player. Off keeps only play/pause.",
3002
+ overridden: "Overridden",
3003
+ reset: "Reset to default",
3004
+ invalidNumber: "Enter a number, or leave blank to use the default.",
3005
+ readOnly: "This deployment stores settings read-only.",
3006
+ unavailable: "This plugin is not loaded, so it cannot be configured right now.",
3007
+ save: "Save",
3008
+ saving: "Saving…",
3009
+ saveFailed: "The deployment did not accept these values; they were left for you to correct.",
3010
+ settingsTitle: "MiMo read-aloud"
3011
+ };
3012
+ /** Simplified Chinese copy. */
3013
+ const zh = {
3014
+ speak: "朗读",
3015
+ synthesize: "正在合成…",
3016
+ play: "播放",
3017
+ pause: "暂停",
3018
+ stop: "停止朗读",
3019
+ progress: "播放进度",
3020
+ emptyText: "这条消息没有可朗读的文本。",
3021
+ truncated: "回复较长,只朗读开头部分。",
3022
+ "error.notConfigured": "请先在「插件」页的本插件卡片里配置 MiMo API Key。",
3023
+ "error.badRequest": "这段文本无法直接朗读。",
3024
+ "error.timeout": "MiMo TTS 响应超时。",
3025
+ "error.upstream": "MiMo TTS 拒绝了这次请求。",
3026
+ "error.invalidAudio": "MiMo TTS 返回的音频无法播放。",
3027
+ "error.voiceSample": "宿主上的音色克隆样本无法读取。",
3028
+ "error.generic": "语音合成失败。",
3029
+ audition: "试听",
3030
+ auditioning: "正在准备试听…",
3031
+ auditionHint: "用卡片当前的风格与音色(含未保存的修改)朗读一句示例。",
3032
+ apiKey: "API Key",
3033
+ apiKeyHint: "在这里粘贴 MiMo API Key。密钥只存进宿主凭据存储,不会回传到页面;清空后保存不会改动已存的密钥。",
3034
+ apiKeyRef: "凭据引用名:",
3035
+ apiKeyRefDefault: "凭据引用名:MIMO_API_KEY(默认)。",
3036
+ apiKeySet: "已配置密钥。",
3037
+ apiKeyUnset: "未配置密钥。",
3038
+ baseUrl: "接口地址",
3039
+ baseUrlHint: "留空使用 https://api.xiaomimimo.com/v1,自动追加 /chat/completions。",
3040
+ model: "模型",
3041
+ modelHint: "留空使用 mimo-v2.5-tts。",
3042
+ voice: "预置音色",
3043
+ voiceHint: "从预置音色中选择;配置了克隆样本时忽略此项。",
3044
+ voiceSamplePath: "音色克隆样本(宿主路径)",
3045
+ voiceSamplePathHint: "宿主上的 5–15 秒 WAV(24kHz/16bit/单声道)。留空则使用预置音色。",
3046
+ style: "默认风格",
3047
+ styleHint: "自然语言描述,例如「开心」「语速慢」「东北话」。留空由模型自行判断(推荐)。",
3048
+ maxChars: "单次最大字符数",
3049
+ maxCharsHint: "超出预算的回复只朗读开头,并在句末截断。",
3050
+ chunkChars: "每块字符数",
3051
+ chunkCharsHint: "回复按这个大小切成块、块间连续播放,同时后台合成下一块,所以声音几秒内就起。越小起声越快,但请求次数越多。",
3052
+ timeoutMs: "请求超时(毫秒)",
3053
+ timeoutMsHint: "单次合成请求的最长等待时间。",
3054
+ autoRead: "自动朗读",
3055
+ autoReadHint: "助手每条新回复完成后,用配置的音色与风格自动朗读。需停留在对话页;若浏览器拦截自动播放,点消息上的喇叭即可。",
3056
+ fallbackEngine: "兜底引擎",
3057
+ fallbackEngineNone: "关闭 — 仅用 MiMo",
3058
+ fallbackEngineEdge: "Edge TTS(免 Key)",
3059
+ fallbackEngineHint: "MiMo 失败或不可达时,改用 Edge TTS 朗读。Edge 免 Key,但音色不同(默认晓晓)。",
3060
+ edgeVoice: "Edge 音色",
3061
+ edgeVoiceHint: "任意 Edge 神经语音,例如 zh-CN-XiaoxiaoNeural(推荐)或 zh-CN-YunxiNeural。",
3062
+ readScope: "朗读范围",
3063
+ readScopeBrief: "简要播报 — 先摘要再念",
3064
+ briefPrefix: "简要播报。",
3065
+ readScopeText: "只读正文 — 跳过代码和表格",
3066
+ readScopeAll: "全部朗读 — 含代码",
3067
+ readScopeSmart: "智能朗读 — 正文 + 短代码",
3068
+ readScopeHint: "决定朗读回复的哪些部分。简要播报会先把回复交给当前对话所用的模型,浓缩成一两句口播摘要(约 80 字)再朗读,代码和表格不会进入摘要;模型不可用时退回规则摘要:每段只取第一句,上限 6 句 / 260 字。智能模式跳过长代码列表,只读短片段。",
3069
+ highlight: "句子高亮",
3070
+ highlightHint: "朗读时在消息正文里高亮当前句子(仅流式朗读路径生效)。",
3071
+ fallbackUsed: "MiMo 这次没响应,已改用 Edge 兜底音色朗读。",
3072
+ muteWhileRecording: "开麦时停止朗读",
3073
+ muteWhileRecordingHint: "麦克风一打开就停止朗读,避免把自己的播报声录进去变成新的输入。配合官方语音输入插件使用。",
3074
+ voiceInputNote: "语音输入由官方 @deepseek-ai/dsh-experimental-voice-input-bundle 提供,在插件页安装即可;本插件只管播放。",
3075
+ test: "测试连接",
3076
+ testing: "测试中…",
3077
+ testOk: "正常 — {engine} 用时 {ms} 毫秒",
3078
+ testFailed: "连接失败",
3079
+ engineMimo: "MiMo",
3080
+ engineEdge: "Edge",
3081
+ sectionConnection: "连接",
3082
+ sectionVoice: "声音",
3083
+ sectionBehavior: "朗读行为",
3084
+ sectionAudition: "试听与测试",
3085
+ autoplayHint: "浏览器拦截了自动播放,点「播放」开始。",
3086
+ progressBar: "显示进度条",
3087
+ progressBarHint: "在悬浮播放器里显示可拖动的进度条;关闭后只保留播放/暂停按钮。",
3088
+ overridden: "已覆盖",
3089
+ reset: "恢复默认",
3090
+ invalidNumber: "请填数字;留空表示使用默认值。",
3091
+ readOnly: "本部署的设置为只读。",
3092
+ unavailable: "该插件当前未加载,暂时无法配置。",
3093
+ save: "保存",
3094
+ saving: "保存中…",
3095
+ saveFailed: "本部署没有接受这些值,已保留供你修改。",
3096
+ settingsTitle: "MiMo 朗读"
3097
+ };
3098
+ // src/client/status.ts
3099
+ /**
3100
+ * The engine-status mirror shared by the speak entries and the Plugins-page
3101
+ * card.
3102
+ *
3103
+ * One `GET /api/mimo-speak/status` answers every mounted control: entries lazy-
3104
+ * load it on first hover/focus, the Plugins-page card refreshes it after each
3105
+ * write that could change whether a key exists. Failures publish the
3106
+ * "unconfigured" view rather than an error state — a missing answer must not
3107
+ * claim a key exists.
3108
+ * @module dsh-mimo-speak/client/status
3109
+ */
3110
+ const store = (0, _deepseek_ai_dsh_client_store.createSnapshotStore)({
3111
+ configured: false,
3112
+ model: DEFAULT_MODEL,
3113
+ voice: DEFAULT_VOICE,
3114
+ hasVoiceSample: false,
3115
+ baseUrl: DEFAULT_BASE_URL,
3116
+ autoRead: false,
3117
+ maxChars: DEFAULT_MAX_CHARS,
3118
+ chunkChars: 120,
3119
+ fallbackEngine: DEFAULT_FALLBACK_ENGINE,
3120
+ edgeVoice: DEFAULT_EDGE_VOICE,
3121
+ readScope: DEFAULT_READ_SCOPE,
3122
+ highlight: true,
3123
+ progressBar: false,
3124
+ muteWhileRecording: true
3125
+ });
3126
+ let inflight = null;
3127
+ /**
3128
+ * @returns the shared status mirror every control derives from.
3129
+ */
3130
+ function ttsStatusStore() {
3131
+ return store;
3132
+ }
3133
+ /**
3134
+ * Ensure one status read is under way; concurrent callers share it.
3135
+ * @returns the read in flight, which never rejects.
3136
+ */
3137
+ function ensureTtsStatus() {
3138
+ if (inflight !== null) return inflight;
3139
+ inflight = fetchTtsStatus().then((view) => {
3140
+ store.set(view);
3141
+ }).catch(() => void 0).finally(() => {
3142
+ inflight = null;
3143
+ });
3144
+ return inflight;
3145
+ }
3146
+ /**
3147
+ * Re-read the status even when one is already under way; called after writes
3148
+ * that could add or remove the API key.
3149
+ * @returns the fresh read, which never rejects.
3150
+ */
3151
+ function refreshTtsStatus() {
3152
+ inflight = null;
3153
+ return ensureTtsStatus();
3154
+ }
3155
+ // src/client/settings-controller.ts
3156
+ /** Form field name of the write-only API key control (not a section field). */
3157
+ const API_KEY_CONTROL = "apiKey";
3158
+ /**
3159
+ * A numeric spec that clamps into the range the Host schema declares
3160
+ * (`chunkChars` 20–1000, the others at least 1). The shared
3161
+ * `settingsNumberField` accepts any finite number, and one out-of-range value
3162
+ * makes the Host reject the whole section — which the UI can only report as
3163
+ * 「本部署没有接受这些值」. Clamping here keeps every save valid.
3164
+ * @param field - section field name.
3165
+ * @param min - smallest value the Host accepts.
3166
+ * @param max - largest value the Host accepts, when it has one.
3167
+ * @returns the field's conversion spec.
3168
+ */
3169
+ function settingsClampedNumberField(field, min, max) {
3170
+ return {
3171
+ field,
3172
+ format: (value) => typeof value === "number" ? String(value) : "",
3173
+ parse: (text) => {
3174
+ const trimmed = text.trim();
3175
+ if (trimmed === "") return { kind: "clear" };
3176
+ const parsed = Number(trimmed);
3177
+ if (!Number.isFinite(parsed)) return void 0;
3178
+ return {
3179
+ kind: "set",
3180
+ value: Math.min(max ?? Number.POSITIVE_INFINITY, Math.max(min, Math.round(parsed)))
3181
+ };
3182
+ }
3183
+ };
3184
+ }
3185
+ /** Section fields the card edits; `apiKeyEnv` stays a read-only ref name. */
3186
+ const SECTION_SPECS = [
3187
+ (0, _deepseek_ai_dsh_client_ui_primitives.settingsTextField)("baseUrl"),
3188
+ (0, _deepseek_ai_dsh_client_ui_primitives.settingsTextField)("model"),
3189
+ (0, _deepseek_ai_dsh_client_ui_primitives.settingsTextField)("voice"),
3190
+ (0, _deepseek_ai_dsh_client_ui_primitives.settingsTextField)("voiceSamplePath"),
3191
+ (0, _deepseek_ai_dsh_client_ui_primitives.settingsTextField)("style"),
3192
+ settingsClampedNumberField("maxChars", 1),
3193
+ settingsClampedNumberField("chunkChars", 20, 1e3),
3194
+ settingsClampedNumberField("timeoutMs", 1),
3195
+ {
3196
+ field: "autoRead",
3197
+ format: (value) => value === true ? "true" : "false",
3198
+ parse: (text) => text === "true" ? {
3199
+ kind: "set",
3200
+ value: true
3201
+ } : text === "false" ? {
3202
+ kind: "set",
3203
+ value: false
3204
+ } : void 0
3205
+ },
3206
+ {
3207
+ field: "fallbackEngine",
3208
+ format: (value) => value === "edge" ? "edge" : "none",
3209
+ parse: (text) => text === "edge" || text === "none" ? {
3210
+ kind: "set",
3211
+ value: text
3212
+ } : void 0
3213
+ },
3214
+ (0, _deepseek_ai_dsh_client_ui_primitives.settingsTextField)("edgeVoice"),
3215
+ {
3216
+ field: "readScope",
3217
+ format: (value) => value === "all" || value === "smart" || value === "brief" ? value : "text",
3218
+ parse: (text) => text === "text" || text === "all" || text === "smart" || text === "brief" ? {
3219
+ kind: "set",
3220
+ value: text
3221
+ } : void 0
3222
+ },
3223
+ {
3224
+ field: "highlight",
3225
+ format: (value) => value === true ? "true" : "false",
3226
+ parse: (text) => text === "true" ? {
3227
+ kind: "set",
3228
+ value: true
3229
+ } : text === "false" ? {
3230
+ kind: "set",
3231
+ value: false
3232
+ } : void 0
3233
+ },
3234
+ {
3235
+ field: "muteWhileRecording",
3236
+ format: (value) => value === true ? "true" : "false",
3237
+ parse: (text) => text === "true" ? {
3238
+ kind: "set",
3239
+ value: true
3240
+ } : text === "false" ? {
3241
+ kind: "set",
3242
+ value: false
3243
+ } : void 0
3244
+ },
3245
+ {
3246
+ field: "progressBar",
3247
+ format: (value) => value === true ? "true" : "false",
3248
+ parse: (text) => text === "true" ? {
3249
+ kind: "set",
3250
+ value: true
3251
+ } : text === "false" ? {
3252
+ kind: "set",
3253
+ value: false
3254
+ } : void 0
3255
+ }
3256
+ ];
3257
+ /**
3258
+ * Bridges the `mimo-speak` configuration namespace onto the Plugins-page card.
3259
+ * @param scope - the bound settings scope for the `mimo-speak` namespace.
3260
+ * @param setCredential - stores a key in the host credentials store.
3261
+ */
3262
+ var TtsSettingsController = class {
3263
+ scope;
3264
+ setCredential;
3265
+ form;
3266
+ store;
3267
+ unsubscribeStatus;
3268
+ status = ttsStatusStore();
3269
+ constructor(scope, setCredential) {
3270
+ this.scope = scope;
3271
+ this.setCredential = setCredential;
3272
+ this.form = new _deepseek_ai_dsh_client_ui_primitives.SettingsFormModel(scope, SECTION_SPECS, [{
3273
+ field: API_KEY_CONTROL,
3274
+ write: (text) => this.writeApiKey(text)
3275
+ }]);
3276
+ this.store = this.form.bind(() => this.projection());
3277
+ this.unsubscribeStatus = this.status.subscribe(() => {
3278
+ this.store.set(this.projection());
3279
+ });
3280
+ refreshTtsStatus();
3281
+ }
3282
+ /**
3283
+ * Build the face the card's slot registration injects.
3284
+ * @returns the card's snapshot and its form actions.
3285
+ */
3286
+ inject() {
3287
+ const actions = this.form.actions();
3288
+ return {
3289
+ hooks: { form: this.store },
3290
+ edit: (field, text) => {
3291
+ actions.edit(field, text);
3292
+ },
3293
+ resetField: (field) => {
3294
+ actions.resetField(field);
3295
+ },
3296
+ save: () => {
3297
+ clearSpeechCache();
3298
+ actions.save();
3299
+ refreshTtsStatus();
3300
+ },
3301
+ discard: () => {
3302
+ actions.discard();
3303
+ },
3304
+ synthesize: (request) => requestSpeech(request),
3305
+ test: () => requestSpeechTest()
3306
+ };
3307
+ }
3308
+ /** Release form and status subscriptions. */
3309
+ dispose() {
3310
+ this.unsubscribeStatus();
3311
+ this.form.dispose();
3312
+ }
3313
+ /**
3314
+ * Store one typed key under the section's credential reference. A blank
3315
+ * draft never reaches here (the form model writes nothing for it); a
3316
+ * successful write refreshes the status mirror, so the configured flag
3317
+ * follows immediately.
3318
+ * @param text - the literal API key as typed.
3319
+ * @returns whether the host accepted the write.
3320
+ */
3321
+ async writeApiKey(text) {
3322
+ const ref = (this.scope.getSnapshot().value?.apiKeyEnv ?? "").trim();
3323
+ if (ref === "") return false;
3324
+ const ok = await this.setCredential(ref, text.trim());
3325
+ if (ok) refreshTtsStatus();
3326
+ return ok;
3327
+ }
3328
+ /** @returns the card projection rebuilt from the form and the status mirror. */
3329
+ projection() {
3330
+ return {
3331
+ ...this.form.shell(),
3332
+ apiKey: this.form.field(API_KEY_CONTROL),
3333
+ apiKeyConfigured: this.status.getSnapshot().configured,
3334
+ apiKeyEnv: this.scope.getSnapshot().value?.apiKeyEnv,
3335
+ baseUrl: this.form.field("baseUrl"),
3336
+ model: this.form.field("model"),
3337
+ voice: this.form.field("voice"),
3338
+ voiceSamplePath: this.form.field("voiceSamplePath"),
3339
+ style: this.form.field("style"),
3340
+ maxChars: this.form.field("maxChars"),
3341
+ chunkChars: this.form.field("chunkChars"),
3342
+ timeoutMs: this.form.field("timeoutMs"),
3343
+ autoRead: this.form.field("autoRead"),
3344
+ fallbackEngine: this.form.field("fallbackEngine"),
3345
+ edgeVoice: this.form.field("edgeVoice"),
3346
+ readScope: this.form.field("readScope"),
3347
+ highlight: this.form.field("highlight"),
3348
+ progressBar: this.form.field("progressBar"),
3349
+ supportsProgressBar: typeof this.status.getSnapshot().progressBar === "boolean",
3350
+ muteWhileRecording: this.form.field("muteWhileRecording"),
3351
+ supportsMuteWhileRecording: typeof this.status.getSnapshot().muteWhileRecording === "boolean"
3352
+ };
3353
+ }
3354
+ };
3355
+ // src/client/styles.ts
3356
+ /**
3357
+ * Plugin-owned stylesheet.
3358
+ *
3359
+ * The in-repo client bundles compile CSS Modules through their tsdown preset;
3360
+ * this out-of-tree plugin keeps one plain stylesheet and injects it with the
3361
+ * same shape the platform's own bundle loader uses (a `data-plugin-css` style
3362
+ * tag owned by the plugin's effect lifetime). Class names are namespaced
3363
+ * `mimo-speak-`, and colors/radii ride the shared `--dsw-*` design tokens so both
3364
+ * themes stay correct without owning theme state.
3365
+ * @module dsh-mimo-speak/client/styles
3366
+ */
3367
+ /** The plugin's stylesheet text. */
3368
+ const CSS = `
3369
+ .mimo-speak-root { position: relative; display: inline-flex; align-items: center; }
3370
+
3371
+ .mimo-speak-button {
3372
+ display: inline-flex; align-items: center; justify-content: center;
3373
+ width: 28px; height: 28px; padding: 6px;
3374
+ border: none; border-radius: var(--dsw-radius-sm);
3375
+ background: transparent; color: var(--dsw-alias-label-tertiary);
3376
+ cursor: pointer;
3377
+ }
3378
+ .mimo-speak-button:hover { background: var(--dsw-alias-interactive-bg-hover); }
3379
+ .mimo-speak-button:focus-visible { outline: var(--dsw-focus-ring-width) solid var(--dsw-alias-state-business-primary); outline-offset: 1px; }
3380
+ .mimo-speak-button[aria-pressed="true"] { color: var(--dsw-alias-brand-primary); }
3381
+
3382
+ .mimo-speak-failure {
3383
+ display: inline-flex; align-items: center; color: var(--dsw-alias-label-error);
3384
+ cursor: default;
3385
+ }
3386
+
3387
+ /* Status notes stay in the DOM for screen readers when no panel is shown. */
3388
+ .mimo-speak-srOnly {
3389
+ position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
3390
+ overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0;
3391
+ }
3392
+
3393
+ /* Synthesizing: the button itself pulses, so the wait is legible with no panel. */
3394
+ .mimo-speak-buttonBusy {
3395
+ color: var(--dsw-alias-brand-primary);
3396
+ background: var(--dsw-alias-interactive-bg-hover);
3397
+ animation: mimo-speak-pulse 1.4s ease-in-out infinite;
3398
+ }
3399
+ @keyframes mimo-speak-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.55; } }
3400
+
3401
+ .mimo-speak-spin { display: inline-flex; animation: mimo-speak-spin 1.1s linear infinite; }
3402
+ @keyframes mimo-speak-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
3403
+
3404
+ .mimo-speak-panel {
3405
+ position: absolute; top: 50%; left: 100%; transform: translateY(-50%); margin-left: 4px; z-index: 40;
3406
+ display: block; width: 280px; padding: 8px 10px;
3407
+ background: var(--dsw-alias-bg-layer-2);
3408
+ border: 1px solid var(--dsw-alias-border-l2);
3409
+ border-radius: var(--dsw-radius-md);
3410
+ box-shadow: 0 6px 24px rgba(0, 0, 0, 0.18);
3411
+ }
3412
+ .mimo-speak-panelLeft { left: auto; right: 100%; margin-left: 0; margin-right: 4px; }
3413
+
3414
+ .mimo-speak-bar { display: flex; align-items: center; gap: 8px; height: 24px; }
3415
+ /* Transport-only variant: no track and no clock, so the panel stays one control. */
3416
+ .mimo-speak-barCompact { gap: 0; justify-content: flex-start; }
3417
+
3418
+ .mimo-speak-barButton {
3419
+ display: inline-flex; align-items: center; justify-content: center;
3420
+ width: 22px; height: 22px; padding: 0;
3421
+ border: none; border-radius: var(--dsw-radius-xs);
3422
+ background: transparent; color: var(--dsw-alias-label-primary);
3423
+ cursor: pointer;
3424
+ }
3425
+ .mimo-speak-barButton:hover { background: var(--dsw-alias-interactive-bg-hover); }
3426
+
3427
+ .mimo-speak-track {
3428
+ position: relative; flex: 1 1 auto; height: 14px; cursor: pointer;
3429
+ display: flex; align-items: center; touch-action: none;
3430
+ }
3431
+ .mimo-speak-track::before {
3432
+ content: ""; position: absolute; left: 0; right: 0; height: 4px;
3433
+ background: var(--dsw-alias-border-l3); border-radius: 2px;
3434
+ }
3435
+ .mimo-speak-track:focus-visible { outline: var(--dsw-focus-ring-width) solid var(--dsw-alias-state-business-primary); outline-offset: 2px; border-radius: var(--dsw-radius-xs); }
3436
+
3437
+ /* Streaming playback cannot seek: the track becomes a progress readout with
3438
+ no thumb and no pointer affordance. */
3439
+ .mimo-speak-trackStatic { cursor: default; }
3440
+ .mimo-speak-trackStatic .mimo-speak-thumb { display: none; }
3441
+
3442
+ .mimo-speak-fill {
3443
+ position: absolute; left: 0; height: 4px; max-width: 100%;
3444
+ background: var(--dsw-alias-brand-primary); border-radius: 2px;
3445
+ }
3446
+
3447
+ .mimo-speak-thumb {
3448
+ position: absolute; width: 10px; height: 10px; margin-left: -5px;
3449
+ background: var(--dsw-alias-brand-primary); border-radius: 50%;
3450
+ box-shadow: 0 0 0 2px var(--dsw-alias-bg-layer-2);
3451
+ }
3452
+ .mimo-speak-trackDragging .mimo-speak-thumb { transform: scale(1.2); }
3453
+
3454
+ .mimo-speak-time {
3455
+ flex: 0 0 auto; font-size: 11px; line-height: 1;
3456
+ color: var(--dsw-alias-label-tertiary); font-variant-numeric: tabular-nums;
3457
+ white-space: nowrap;
3458
+ }
3459
+
3460
+ .mimo-speak-audition { display: flex; flex-direction: column; gap: 8px; margin-top: 4px; }
3461
+ .mimo-speak-auditionHint {
3462
+ margin: 0; font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-tertiary);
3463
+ }
3464
+ .mimo-speak-auditionRow { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
3465
+ .mimo-speak-auditionRow .mimo-speak-bar { flex: 1 1 220px; min-width: 180px; }
3466
+ .mimo-speak-auditionButton {
3467
+ height: 28px; padding: 0 14px;
3468
+ border: 1px solid var(--dsw-alias-border-l2);
3469
+ border-radius: var(--dsw-radius-sm);
3470
+ background: var(--dsw-alias-button-tool-bar-fill);
3471
+ color: var(--dsw-alias-label-primary);
3472
+ font-size: 12px; cursor: pointer;
3473
+ }
3474
+ .mimo-speak-auditionButton:hover:not(:disabled) { background: var(--dsw-alias-button-tool-bar-hover); }
3475
+ .mimo-speak-auditionButton:disabled { opacity: 0.6; cursor: default; }
3476
+
3477
+ .mimo-speak-fieldError { margin: 0; font-size: 12px; color: var(--dsw-alias-label-error); }
3478
+
3479
+ /* Preset-voice dropdown, styled to sit inside the shared settings form frame
3480
+ like the primitive text fields around it. */
3481
+ .mimo-speak-selectField { display: flex; flex-direction: column; gap: 6px; }
3482
+ .mimo-speak-selectLabel { font-size: 13px; font-weight: 500; line-height: 18px; color: var(--dsw-alias-label-primary); }
3483
+ .mimo-speak-select {
3484
+ height: 34px; padding: 0 10px;
3485
+ border: 0.5px solid var(--dsw-alias-border-l4);
3486
+ border-radius: var(--dsw-radius-md);
3487
+ background: var(--dsw-alias-bg-layer-3);
3488
+ color: var(--dsw-alias-label-primary);
3489
+ font-size: 13px;
3490
+ }
3491
+ .mimo-speak-select:focus-visible { outline: var(--dsw-focus-ring-width) solid var(--dsw-alias-state-business-primary); outline-offset: 1px; }
3492
+ .mimo-speak-select:disabled { opacity: 0.6; cursor: default; }
3493
+
3494
+ /* Section titles inside the configuration card. */
3495
+ .mimo-speak-sectionTitle {
3496
+ margin: 16px 0 0; padding-top: 12px;
3497
+ border-top: 0.5px solid var(--dsw-alias-border-l2);
3498
+ font-size: 12px; font-weight: 600; letter-spacing: 0.02em;
3499
+ color: var(--dsw-alias-label-secondary); text-transform: uppercase;
3500
+ }
3501
+ .mimo-speak-sectionTitle:first-child { margin-top: 0; padding-top: 0; border-top: none; }
3502
+
3503
+ /* Status lines inside the floating player panel. */
3504
+ .mimo-speak-panelStatus { margin: 0; font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-error); }
3505
+ .mimo-speak-panelNote { margin: 0; font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-tertiary); }
3506
+
3507
+ /* While a player is open, the message's action strip stays visible even when
3508
+ the pointer leaves the row — audio must not fade out mid-playback. The
3509
+ selector reads ui-chat's reveal attribute as a progressive enhancement: with
3510
+ the attribute absent the rule simply never matches. */
3511
+ @media (hover: hover) {
3512
+ [data-actions-reveal="hover"]:has(.mimo-speak-open) .actions { opacity: 1; }
3513
+ }
3514
+ `;
3515
+ /**
3516
+ * Inject the plugin stylesheet into the page.
3517
+ * @returns the disposer removing the style tag (HMR-safe: re-injection after a
3518
+ * rebuild replaces the tag by its data attribute).
3519
+ */
3520
+ function injectStyles() {
3521
+ const existing = document.querySelector("style[data-plugin-css=\"dsh-mimo-speak/styles\"]");
3522
+ if (existing !== null) return () => {
3523
+ existing.remove();
3524
+ };
3525
+ const tag = document.createElement("style");
3526
+ tag.dataset.plugin = "dsh-mimo-speak";
3527
+ tag.dataset.pluginCss = "dsh-mimo-speak/styles";
3528
+ tag.textContent = CSS;
3529
+ document.head.appendChild(tag);
3530
+ return () => {
3531
+ tag.remove();
3532
+ };
3533
+ }
3534
+ // src/client/index.ts
3535
+ /** Required services (cordis fiber inject); remote.credentials stores the API key. */
3536
+ const inject = [
3537
+ "slots",
3538
+ "locale",
3539
+ "configForms",
3540
+ "remote",
3541
+ "remote.credentials"
3542
+ ];
3543
+ /**
3544
+ * Mount the speak entry and the Plugins-page configuration card.
3545
+ * @param ctx - the browser plugin context.
3546
+ */
3547
+ function apply(ctx) {
3548
+ ctx.effect(() => injectStyles(), "dsh-mimo-speak: styles");
3549
+ ctx.effect(() => ctx.locale.register(NS, {
3550
+ zh,
3551
+ en
3552
+ }), "dsh-mimo-speak: dictionaries");
3553
+ const t = ctx.locale.bind(NS);
3554
+ const controller = new TtsSettingsController(ctx.configForms.get(MIMOSPEAK_NAMESPACE), async (ref, value) => (await ctx.remote.credentials.set(ref, value)).ok);
3555
+ ctx.effect(() => () => {
3556
+ controller.dispose();
3557
+ }, "dsh-mimo-speak: settings form");
3558
+ ctx.effect(() => ctx.configForms.whileServed([MIMOSPEAK_NAMESPACE], () => {
3559
+ const offCard = ctx.slots.inject("plugins.bundle.config", () => ctx.slots.register({
3560
+ name: "plugins.bundle.config",
3561
+ key: MIMOSPEAK_PACKAGE_KEY,
3562
+ locale: NS,
3563
+ inject: () => controller.inject()
3564
+ }, BundleConfigCard));
3565
+ return () => {
3566
+ offCard();
3567
+ };
3568
+ }), "dsh-mimo-speak: plugins-page card");
3569
+ const settingsController = new TtsSettingsController(ctx.configForms.get(MIMOSPEAK_NAMESPACE), async (ref, value) => (await ctx.remote.credentials.set(ref, value)).ok);
3570
+ ctx.effect(() => () => {
3571
+ settingsController.dispose();
3572
+ }, "dsh-mimo-speak: settings-section form");
3573
+ ctx.effect(() => ctx.configForms.whileServed([MIMOSPEAK_NAMESPACE], () => {
3574
+ const offSection = ctx.slots.inject("settings.section", () => ctx.slots.register({
3575
+ name: "settings.section",
3576
+ id: SETTINGS_SECTION_ID,
3577
+ order: 80,
3578
+ label: () => t("settingsTitle"),
3579
+ locale: NS,
3580
+ inject: () => settingsController.inject()
3581
+ }, SettingsSectionCard));
3582
+ return () => {
3583
+ offSection();
3584
+ };
3585
+ }), "dsh-mimo-speak: settings section");
3586
+ ensureTtsStatus();
3587
+ ctx.slots.inject("conversation.chat.assistant-actions", () => ctx.slots.register({
3588
+ name: "conversation.chat.assistant-actions",
3589
+ id: "mimo-speak",
3590
+ order: 20,
3591
+ locale: NS,
3592
+ inject: () => ({
3593
+ hooks: { status: ttsStatusStore() },
3594
+ ensureStatus: () => {
3595
+ ensureTtsStatus();
3596
+ },
3597
+ synthesize: requestSpeech
3598
+ })
3599
+ }, SpeakAction));
3600
+ }
3601
+ exports.apply = apply;
3602
+ exports.inject = inject;
3603
+ return module.exports;
3604
+ }
3605
+ });
3606
+
3607
+ //# sourceMappingURL=client.js.map