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
@@ -0,0 +1,651 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /**
3
+ * The speak entry in the finalized assistant message's action strip: a volume
4
+ * button that synthesizes the message with MiMo TTS, and — once audio exists —
5
+ * a floating mini player with a draggable progress bar.
6
+ *
7
+ * Long replies are synthesized as a pipeline: the text is split at sentence
8
+ * boundaries into small chunks, the first chunk starts playing as soon as it
9
+ * lands, and the remaining chunks synthesize in the background while audio
10
+ * plays, so the first sound arrives in seconds regardless of length.
11
+ *
12
+ * The button lives exactly where the platform keeps per-message actions
13
+ * (between copy and branch). The player floats below the icon row so the row's
14
+ * 28px chrome never reflows; while a player is open the strip stops fading on
15
+ * hover-out (`styles.ts`), so audio stays visible wherever the pointer goes.
16
+ * @module dsh-mimo-speak/client/SpeakAction
17
+ */
18
+ import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
19
+ import { IconLoadingOutlineRegular, IconWarningTriangleOutlineRegular, TextShimmer, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives';
20
+ import { briefText } from "../brief.js";
21
+ import { toSpeakableText } from "../normalize.js";
22
+ import { requestSpeech, requestSpeechStream, requestSummary, speechEngineOf, TtsClientError } from "./api.js";
23
+ import { onAudioCaptureStart } from "./audio-bus.js";
24
+ import { latestAssistantMessageId, speakableTextFor } from "./chat-text.js";
25
+ import { findMessageContainer, SentenceHighlighter } from "./highlight.js";
26
+ import { playerPanelVisible } from "./panel-visibility.js";
27
+ import { PlayerBar } from "./PlayerBar.js";
28
+ import { cachedSpeech, cacheSpeech, speechCacheKey } from "./speech-cache.js";
29
+ import { splitForSpeech } from "./split-speech.js";
30
+ import { IconVolumeOutlineRegular } from "./SpeakerIcon.js";
31
+ import { useAudioQueue } from "./use-audio-queue.js";
32
+ import { useStreamPlayer } from "./use-stream-player.js";
33
+ /**
34
+ * Map a failure onto the dictionary key the entry shows.
35
+ * @param failure - the synthesis failure, or `empty` for a text-less message.
36
+ * @returns the localized copy key.
37
+ */
38
+ export function errorKeyFor(failure) {
39
+ if (failure === 'empty')
40
+ return 'emptyText';
41
+ if (failure === 'unconfigured')
42
+ return 'error.notConfigured';
43
+ switch (failure.code) {
44
+ case 'not-configured': return 'error.notConfigured';
45
+ case 'bad-request': return 'error.badRequest';
46
+ case 'text-too-long': return 'error.badRequest';
47
+ case 'timeout': return 'error.timeout';
48
+ case 'upstream-error': return 'error.upstream';
49
+ case 'invalid-audio': return 'error.invalidAudio';
50
+ case 'voice-sample-unreadable': return 'error.voiceSample';
51
+ default: return 'error.generic';
52
+ }
53
+ }
54
+ /** Whether a session snapshot is still producing the reply. */
55
+ function sessionRunning(session) {
56
+ try {
57
+ if (session === null || typeof session !== 'object')
58
+ return false;
59
+ const value = session;
60
+ if (value.running === true)
61
+ return true;
62
+ return value.status === 'running' || value.status === 'busy';
63
+ }
64
+ catch {
65
+ return false;
66
+ }
67
+ }
68
+ /**
69
+ * Call one slot-provided selector hook defensively: an absent hook or a
70
+ * throwing selector resolves to the fallback, so automatic reading silently
71
+ * disables itself rather than crashing the action row.
72
+ */
73
+ function useHostHook(hook, selector, fallback) {
74
+ if (typeof hook !== 'function')
75
+ return fallback;
76
+ try {
77
+ const value = hook(selector);
78
+ return value === undefined || value === null ? fallback : value;
79
+ }
80
+ catch {
81
+ return fallback;
82
+ }
83
+ }
84
+ /**
85
+ * Message ids that automatic reading already handled. Client memory only: a
86
+ * page reload may replay the newest reply once, which beats silently never
87
+ * speaking, and re-renders can never start the same reply twice.
88
+ */
89
+ const autoReadLog = (() => {
90
+ const seen = new Set();
91
+ const order = [];
92
+ return {
93
+ has(id) {
94
+ return id !== '' && seen.has(id);
95
+ },
96
+ mark(id) {
97
+ if (id === '' || seen.has(id))
98
+ return;
99
+ seen.add(id);
100
+ order.push(id);
101
+ if (order.length > 200) {
102
+ const oldest = order.shift();
103
+ if (oldest !== undefined)
104
+ seen.delete(oldest);
105
+ }
106
+ },
107
+ };
108
+ })();
109
+ /**
110
+ * Produce (or reuse) the object URL for one chunk.
111
+ * @param text - one speakable chunk.
112
+ * @param signature - how the current configuration sounds; part of the key, so
113
+ * a voice/style change never replays the previous take.
114
+ * @param signal - aborts the request when the reader stops.
115
+ * @returns the object URL of the audio and the engine that produced it.
116
+ */
117
+ async function synthesizeChunkUrl(text, signature, signal) {
118
+ const key = speechCacheKey(signature, text);
119
+ const hit = cachedSpeech(key);
120
+ if (hit !== undefined)
121
+ return hit;
122
+ const blob = await requestSpeech({ text }, signal);
123
+ const chunk = { url: URL.createObjectURL(blob), engine: speechEngineOf(blob) };
124
+ cacheSpeech(key, chunk);
125
+ return chunk;
126
+ }
127
+ /** Keep only the chunks that fit inside the configured total budget. */
128
+ function budgetChunks(chunks, maxChars) {
129
+ const selected = [];
130
+ let budget = Number.isFinite(maxChars) ? Math.max(0, Math.round(maxChars)) : 2000;
131
+ for (const chunk of chunks) {
132
+ if (budget <= 0)
133
+ break;
134
+ selected.push(chunk);
135
+ budget -= chunk.length;
136
+ }
137
+ return selected;
138
+ }
139
+ /**
140
+ * Render one message's speak control and open player.
141
+ * @param props - the message identity, the injected engine verbs, the Chat
142
+ * selector hook, and localized copy.
143
+ * @returns the volume button with its optional player and failure notice.
144
+ */
145
+ export function SpeakAction(props) {
146
+ const { messageId, useChat, useStatus, ensureStatus, t } = props;
147
+ // The assistant-actions seat also carries a session hook, but its presence
148
+ // varies across surface versions, so it is read defensively.
149
+ const useSession = props.useSession;
150
+ const status = useStatus(snapshot => snapshot);
151
+ /**
152
+ * Fingerprint of the current voice/model/endpoint. It is part of the replay
153
+ * cache key, so a settings change can never replay the previous take.
154
+ */
155
+ const signatureRef = useRef({
156
+ voice: '', model: '', style: '', baseUrl: '', edgeVoice: '', maxChars: 0,
157
+ });
158
+ signatureRef.current = {
159
+ voice: status.voice,
160
+ model: status.model,
161
+ // Style is not part of the status payload; a settings save clears the cache.
162
+ style: '',
163
+ baseUrl: status.baseUrl,
164
+ edgeVoice: status.edgeVoice,
165
+ maxChars: status.maxChars,
166
+ };
167
+ /** The panel only exists to host the progress bar; without it the button is the control. */
168
+ const showProgressBar = status.progressBar === true;
169
+ const rawText = useChat(snapshot => speakableTextFor(snapshot, messageId, status.readScope));
170
+ const latestId = useHostHook(useChat, (snapshot) => latestAssistantMessageId(snapshot), '');
171
+ const running = useHostHook(useSession, sessionRunning, false);
172
+ const speakable = useMemo(() => (rawText === undefined ? undefined : toSpeakableText(rawText)), [rawText]);
173
+ const [phase, setPhase] = useState('idle');
174
+ const [failure, setFailure] = useState(null);
175
+ /** The reply exceeded the character budget, so only its opening is spoken. */
176
+ const [truncated, setTruncated] = useState(false);
177
+ const { state: playerState, enqueue: playerEnqueue, clear: playerClear, toggle: playerToggle, seek: playerSeek, pause: playerPause, finish: playerFinish, } = useAudioQueue();
178
+ const streamPlayer = useStreamPlayer();
179
+ // Which engine is driving the open player: the chunked WAV queue or the
180
+ // progressive PCM stream. The stream is the fast path; the queue is the
181
+ // fallback for clone voices and for streams the provider refuses.
182
+ const [mode, setMode] = useState(null);
183
+ /** Engine that actually answered this read; `edge` means MiMo failed. */
184
+ const [engineUsed, setEngineUsed] = useState(null);
185
+ const activeState = mode === 'stream' ? streamPlayer.state : playerState;
186
+ const queueWaiting = mode === 'queue' && playerState.waiting === true;
187
+ const activeToggle = useCallback(() => {
188
+ if (mode === 'stream')
189
+ streamPlayer.toggle();
190
+ else
191
+ playerToggle();
192
+ }, [mode, playerToggle, streamPlayer]);
193
+ const activePause = useCallback(() => {
194
+ if (mode === 'stream')
195
+ streamPlayer.pause();
196
+ else
197
+ playerPause();
198
+ }, [mode, playerPause, streamPlayer]);
199
+ const activeSeek = useCallback((seconds) => {
200
+ if (mode === 'stream')
201
+ return;
202
+ playerSeek(seconds);
203
+ }, [mode, playerSeek]);
204
+ const clearPlayers = useCallback(() => {
205
+ playerClear();
206
+ streamPlayer.clear();
207
+ cuesRef.current = [];
208
+ cueCursorRef.current = 0;
209
+ keyOffsetRef.current = 0;
210
+ setMode(null);
211
+ }, [playerClear, streamPlayer]);
212
+ /**
213
+ * Stop the current read-aloud for good: abort the stream in flight, drop the
214
+ * scheduled audio, and invalidate the run so no further sentence is asked
215
+ * for. This is the control the speaker button offers while it is playing.
216
+ */
217
+ /**
218
+ * Pause the current read-aloud and stop asking for the rest of the reply.
219
+ * Whatever is already scheduled stays buffered, so resuming plays that much;
220
+ * `finish()` lets the player report the end once the buffer drains instead of
221
+ * waiting forever for sentences that will never arrive.
222
+ */
223
+ const pauseRun = useCallback(() => {
224
+ abortRef.current?.abort();
225
+ abortRef.current = null;
226
+ if (mode === 'stream')
227
+ streamPlayer.finish();
228
+ activePause();
229
+ }, [activePause, mode, streamPlayer]);
230
+ /** The panel's transport: pause also aborts the sentences still to come. */
231
+ const panelToggle = useCallback(() => {
232
+ if (activeState.playing)
233
+ pauseRun();
234
+ else
235
+ activeToggle();
236
+ }, [activeState.playing, pauseRun, activeToggle]);
237
+ const stopRun = useCallback(() => {
238
+ abortRef.current?.abort();
239
+ abortRef.current = null;
240
+ // Invalidate the run: every loop checks this before its next request.
241
+ sessionRef.current += 1;
242
+ clearPlayers();
243
+ highlighterRef.current?.clear();
244
+ highlighterRef.current = null;
245
+ cuesRef.current = [];
246
+ cueCursorRef.current = 0;
247
+ keyOffsetRef.current = 0;
248
+ setTruncated(false);
249
+ setPhase('idle');
250
+ setFailure(null);
251
+ setPanelOpen(false);
252
+ setEngineUsed(null);
253
+ }, [clearPlayers]);
254
+ // The highlighter in use while the current message plays, if any.
255
+ const highlighterRef = useRef(null);
256
+ /** Sentence cues: the audio second each chunk starts at, plus its text. */
257
+ const cuesRef = useRef([]);
258
+ /** How many cues the paint effect already consumed. */
259
+ const cueCursorRef = useRef(0);
260
+ /** Folded-key offset of the last painted sentence, so repeats pair up. */
261
+ const keyOffsetRef = useRef(0);
262
+ // Panel visibility is decoupled from whether audio exists, so it can be
263
+ // dismissed (click-outside / Esc) without discarding the audio source.
264
+ const [panelOpen, setPanelOpen] = useState(false);
265
+ const [panelSide, setPanelSide] = useState('right');
266
+ const rootRef = useRef(null);
267
+ const buttonRef = useRef(null);
268
+ const panelId = useId();
269
+ // Bumped on every fresh synthesis so a stale run stops enqueueing chunks.
270
+ const sessionRef = useRef(0);
271
+ /**
272
+ * In-flight synthesis of the current run. Aborting it is what actually stops
273
+ * playback: suspending the AudioContext alone leaves the remaining sentences
274
+ * streaming in behind the pause, and they all land on resume.
275
+ */
276
+ const abortRef = useRef(null);
277
+ // Page switches unmount every chat entry mid-read. Nothing else stops the
278
+ // in-flight run on unmount, so abort it, invalidate the session, and stop both
279
+ // engines; the stream player's own dispose guard then keeps any late SSE
280
+ // chunk from rebuilding its AudioContext. `playerClear`/`streamPlayer.clear`
281
+ // are reached through refs so an unmount-only effect never re-runs when a
282
+ // player identity changes. They may publish state in other call paths, but
283
+ // on unmount their hooks' own cleanups run first and make them no-op.
284
+ const streamClearRef = useRef(() => { });
285
+ streamClearRef.current = streamPlayer.clear;
286
+ const playerClearRef = useRef(() => { });
287
+ playerClearRef.current = playerClear;
288
+ useEffect(() => () => {
289
+ abortRef.current?.abort();
290
+ abortRef.current = null;
291
+ sessionRef.current += 1;
292
+ playerClearRef.current();
293
+ streamClearRef.current();
294
+ highlighterRef.current?.clear();
295
+ highlighterRef.current = null;
296
+ cuesRef.current = [];
297
+ cueCursorRef.current = 0;
298
+ keyOffsetRef.current = 0;
299
+ }, []);
300
+ // When the panel opens, flip it left when the speaker sits near the right
301
+ // edge of the viewport, so the floating bar never overflows the window.
302
+ useEffect(() => {
303
+ if (!panelOpen)
304
+ return;
305
+ const root = rootRef.current;
306
+ if (root === null)
307
+ return;
308
+ const bounds = root.getBoundingClientRect();
309
+ setPanelSide(bounds.right + 288 > window.innerWidth ? 'left' : 'right');
310
+ }, [panelOpen]);
311
+ // Dismiss the floating panel on outside click; it only ever wraps the
312
+ // progress bar, so folding it away leaves playback alone.
313
+ useEffect(() => {
314
+ if (!panelOpen)
315
+ return;
316
+ const onPointerDown = (event) => {
317
+ const root = rootRef.current;
318
+ if (root !== null && root.contains(event.target))
319
+ return;
320
+ setPanelOpen(false);
321
+ };
322
+ document.addEventListener('pointerdown', onPointerDown);
323
+ return () => {
324
+ document.removeEventListener('pointerdown', onPointerDown);
325
+ };
326
+ }, [panelOpen]);
327
+ // Talking over the reader: the moment the microphone opens (the official
328
+ // voice-input bundle records through getUserMedia) the read-aloud stops, so
329
+ // the recorder never captures the assistant's own voice.
330
+ const muteWhileRecording = status.muteWhileRecording !== false;
331
+ useEffect(() => {
332
+ if (!muteWhileRecording)
333
+ return;
334
+ return onAudioCaptureStart(() => { stopRun(); });
335
+ }, [muteWhileRecording, stopRun]);
336
+ // Escape is an explicit cancel and works with or without the panel: only the
337
+ // entry that is actually speaking reacts, and focus returns to its button so
338
+ // keyboard users are not dropped into the void.
339
+ useEffect(() => {
340
+ if (!activeState.playing && phase !== 'loading')
341
+ return;
342
+ const onKeyDown = (event) => {
343
+ if (event.key !== 'Escape')
344
+ return;
345
+ stopRun();
346
+ buttonRef.current?.focus();
347
+ };
348
+ document.addEventListener('keydown', onKeyDown);
349
+ return () => {
350
+ document.removeEventListener('keydown', onKeyDown);
351
+ };
352
+ }, [activeState.playing, phase, stopRun]);
353
+ // Chunked fallback: split the reply, then synthesize chunks sequentially
354
+ // while the queue keeps playing them back-to-back. The first chunk gates the
355
+ // visible "ready" transition; later chunks just keep the queue stocked.
356
+ const chunkedRun = useCallback(async (gen, chunks, signal) => {
357
+ setMode('queue');
358
+ /** @returns whether this run was cancelled by the reader. */
359
+ const cancelled = () => gen !== sessionRef.current || (signal !== undefined && signal.aborted);
360
+ try {
361
+ let first = true;
362
+ for (let index = 0; index < chunks.length; index += 1) {
363
+ // Stop between chunks: a cancelled run must not keep synthesizing.
364
+ if (cancelled())
365
+ return;
366
+ const chunkAudio = await synthesizeChunkUrl(chunks[index], signatureRef.current, signal);
367
+ if (gen !== sessionRef.current)
368
+ return;
369
+ if (chunkAudio.engine === 'edge')
370
+ setEngineUsed('edge');
371
+ playerEnqueue(chunkAudio.url);
372
+ if (first) {
373
+ first = false;
374
+ setPhase('ready');
375
+ }
376
+ }
377
+ if (!cancelled())
378
+ playerFinish();
379
+ }
380
+ catch (error) {
381
+ // A cancelled run is not a failure: the reader asked it to stop.
382
+ if (cancelled())
383
+ return;
384
+ setPhase('error');
385
+ setFailure(error instanceof TtsClientError ? error : new TtsClientError('generic', String(error)));
386
+ }
387
+ }, [playerEnqueue, playerFinish]);
388
+ // Sentence-level streaming: each sentence is one PCM stream, so its first
389
+ // chunk is audible within a second while later sentences stream in the
390
+ // background. Sentence boundaries also drive the highlight. When streaming
391
+ // is refused (clone voice, provider, mid-sentence failure) the chunked
392
+ // pipeline takes over, which carries the Edge fallback.
393
+ const streamRun = useCallback(async (gen, chunks, messageText, signal) => {
394
+ setMode('stream');
395
+ highlighterRef.current?.clear();
396
+ highlighterRef.current = status.highlight
397
+ ? new SentenceHighlighter(findMessageContainer(rootRef.current, messageText))
398
+ : null;
399
+ cuesRef.current = [];
400
+ cueCursorRef.current = 0;
401
+ keyOffsetRef.current = 0;
402
+ /** @returns whether this run was cancelled by the reader. */
403
+ const cancelled = () => gen !== sessionRef.current || (signal !== undefined && signal.aborted);
404
+ let gotFirst = false;
405
+ for (let index = 0; index < chunks.length; index += 1) {
406
+ // Every sentence asks for its own stream: a cancelled run stops here
407
+ // instead of synthesizing the rest of the reply in the background.
408
+ if (cancelled())
409
+ return;
410
+ const chunk = chunks[index];
411
+ let chunkStarted = false;
412
+ try {
413
+ await requestSpeechStream({ text: chunk }, (pcm) => {
414
+ if (gen !== sessionRef.current)
415
+ return;
416
+ if (!chunkStarted) {
417
+ chunkStarted = true;
418
+ if (!gotFirst) {
419
+ gotFirst = true;
420
+ setPhase('ready');
421
+ }
422
+ // Record when this sentence will actually be heard, so the
423
+ // highlight follows playback rather than synthesis arrival.
424
+ cuesRef.current.push({ at: streamPlayer.scheduled(), text: chunk });
425
+ }
426
+ streamPlayer.feed(pcm);
427
+ }, signal);
428
+ if (gen !== sessionRef.current)
429
+ return;
430
+ }
431
+ catch (error) {
432
+ // Cancellation is the reader stopping, not an upstream failure: drop
433
+ // the run without falling back to another engine.
434
+ if (cancelled())
435
+ return;
436
+ // The rest of the reply falls back to the chunked pipeline.
437
+ streamPlayer.clear();
438
+ highlighterRef.current?.clear();
439
+ highlighterRef.current = null;
440
+ cuesRef.current = [];
441
+ cueCursorRef.current = 0;
442
+ await chunkedRun(gen, chunks.slice(chunkStarted ? index + 1 : index), signal);
443
+ return;
444
+ }
445
+ }
446
+ if (gen !== sessionRef.current)
447
+ return;
448
+ if (!gotFirst) {
449
+ highlighterRef.current?.clear();
450
+ highlighterRef.current = null;
451
+ await chunkedRun(gen, chunks, signal);
452
+ return;
453
+ }
454
+ streamPlayer.finish();
455
+ }, [chunkedRun, status.highlight, streamPlayer]);
456
+ // Paint each sentence when playback reaches it, not when it was synthesized:
457
+ // the streamer synthesizes ahead of playback, so arrival-time painting runs
458
+ // ahead of the voice and looks chaotic.
459
+ useEffect(() => {
460
+ if (mode !== 'stream')
461
+ return;
462
+ const highlighter = highlighterRef.current;
463
+ if (highlighter === null || !highlighter.supported)
464
+ return;
465
+ const cues = cuesRef.current;
466
+ const now = activeState.currentTime + 0.08;
467
+ while (cueCursorRef.current < cues.length && cues[cueCursorRef.current].at <= now) {
468
+ const cue = cues[cueCursorRef.current];
469
+ cueCursorRef.current += 1;
470
+ keyOffsetRef.current = highlighter.show(cue.text, keyOffsetRef.current);
471
+ }
472
+ }, [activeState.currentTime, mode]);
473
+ const runSynthesis = useCallback(async (input) => {
474
+ abortRef.current?.abort();
475
+ const controller = new AbortController();
476
+ abortRef.current = controller;
477
+ const gen = ++sessionRef.current;
478
+ setEngineUsed(null);
479
+ clearPlayers();
480
+ highlighterRef.current?.clear();
481
+ highlighterRef.current = null;
482
+ cuesRef.current = [];
483
+ cueCursorRef.current = 0;
484
+ keyOffsetRef.current = 0;
485
+ setPhase('loading');
486
+ setFailure(null);
487
+ setTruncated(false);
488
+ // With no progress bar there is nothing to put in a panel: keep it shut.
489
+ if (status.progressBar === true)
490
+ setPanelOpen(true);
491
+ // Brief read-aloud is a summary, not a selection: ask the configured model
492
+ // to condense the reply, and fall back to the offline extractive rule when
493
+ // no model answers. Everything downstream (chunking, highlight, cache)
494
+ // then works on the summary like on any other text.
495
+ let spoken = input;
496
+ if (status.readScope === 'brief') {
497
+ const summarized = await requestSummary(input, controller.signal).catch(() => undefined);
498
+ if (controller.signal.aborted || gen !== sessionRef.current)
499
+ return;
500
+ spoken = summarized ?? briefText(input, 260, 6, t('briefPrefix'));
501
+ }
502
+ const all = splitForSpeech(spoken, status.chunkChars);
503
+ const chunks = budgetChunks(all, status.maxChars);
504
+ // Never drop content silently: the panel says the reply was cut short.
505
+ setTruncated(chunks.length < all.length);
506
+ if (chunks.length === 0) {
507
+ setPhase('idle');
508
+ setFailure('empty');
509
+ return;
510
+ }
511
+ if (status.hasVoiceSample) {
512
+ void chunkedRun(gen, chunks, controller.signal);
513
+ return;
514
+ }
515
+ void streamRun(gen, chunks, spoken, controller.signal);
516
+ }, [chunkedRun, clearPlayers, status.chunkChars, status.hasVoiceSample, status.maxChars, status.progressBar, status.readScope, streamRun, t]);
517
+ /**
518
+ * Start a read-aloud. Kept stable for the effects: cancellation lives inside
519
+ * `runSynthesis`, so callers can fire and forget.
520
+ */
521
+ const synthesize = useCallback((input) => { void runSynthesis(input); }, [runSynthesis]);
522
+ // The highlight belongs to the playback: clear it when the stream ends.
523
+ useEffect(() => {
524
+ if (activeState.ended) {
525
+ highlighterRef.current?.clear();
526
+ highlighterRef.current = null;
527
+ }
528
+ }, [activeState.ended]);
529
+ const hasAudio = phase === 'ready';
530
+ // Ready, not ended, still at 0:00 and not playing: autoplay was refused.
531
+ const autoplayBlocked = hasAudio && !activeState.playing && !activeState.ended && !queueWaiting && activeState.currentTime === 0;
532
+ const onClick = useCallback(() => {
533
+ if (phase === 'loading') {
534
+ // Second press while synthesizing is a cancel, not a no-op.
535
+ stopRun();
536
+ return;
537
+ }
538
+ if (hasAudio) {
539
+ if (queueWaiting) {
540
+ // The next chunk is still synthesizing; a click means stop, not replay.
541
+ stopRun();
542
+ return;
543
+ }
544
+ if (activeState.ended) {
545
+ // Replay: the chunked path replays from cache; the stream re-synthesizes.
546
+ if (speakable !== undefined && speakable !== '')
547
+ void synthesize(speakable);
548
+ return;
549
+ }
550
+ if (!showProgressBar) {
551
+ // No panel: the button itself reads play/stop. Stopping cancels the
552
+ // run, so the rest of the reply is never synthesized behind it.
553
+ if (activeState.playing)
554
+ stopRun();
555
+ else
556
+ activeToggle();
557
+ return;
558
+ }
559
+ if (!panelOpen)
560
+ setPanelOpen(true);
561
+ panelToggle();
562
+ return;
563
+ }
564
+ if (speakable === undefined || speakable === '') {
565
+ setFailure('empty');
566
+ return;
567
+ }
568
+ if (!status.configured) {
569
+ setFailure('unconfigured');
570
+ return;
571
+ }
572
+ void synthesize(speakable);
573
+ }, [phase, hasAudio, activeState.playing, activeState.ended, queueWaiting, speakable, panelOpen, panelToggle, showProgressBar, status.configured, synthesize, stopRun]);
574
+ // Automatic read-aloud: the newest finished reply speaks once, and only
575
+ // while this entry is idle, so a manual read or an older reply is never
576
+ // interrupted. The browser may still block audible autoplay without a prior
577
+ // user gesture — the audio lands ready, and one tap on the speaker plays it.
578
+ const autoRead = status.autoRead === true;
579
+ useEffect(() => {
580
+ if (!autoRead)
581
+ return;
582
+ if (messageId === '' || messageId !== latestId)
583
+ return;
584
+ if (running)
585
+ return;
586
+ if (speakable === undefined || speakable === '')
587
+ return;
588
+ if (!status.configured)
589
+ return;
590
+ if (autoReadLog.has(messageId))
591
+ return;
592
+ if (phase !== 'idle')
593
+ return;
594
+ const timer = window.setTimeout(() => {
595
+ if (autoReadLog.has(messageId))
596
+ return;
597
+ autoReadLog.mark(messageId);
598
+ void synthesize(speakable);
599
+ }, 400);
600
+ return () => window.clearTimeout(timer);
601
+ }, [autoRead, latestId, messageId, running, speakable, phase, status.configured, synthesize]);
602
+ // The panel is the progress bar's home. With the bar off the speaker button
603
+ // is the whole control, so neither the panel nor its notes may appear.
604
+ const fallbackNote = engineUsed === 'edge';
605
+ const panelVisible = playerPanelVisible({
606
+ progressBar: showProgressBar,
607
+ panelOpen,
608
+ hasAudio,
609
+ loading: phase === 'loading',
610
+ });
611
+ /** Spoken-only status for the no-panel mode: the note stays off-screen. */
612
+ const statusNotes = failure !== null
613
+ ? [t(errorKeyFor(failure))]
614
+ : [
615
+ ...(autoplayBlocked ? [t('autoplayHint')] : []),
616
+ ...(truncated ? [t('truncated')] : []),
617
+ ...(fallbackNote ? [t('fallbackUsed')] : []),
618
+ ];
619
+ const hiddenStatus = statusNotes.join(' ');
620
+ const buttonLabel = phase === 'loading'
621
+ ? t('synthesize')
622
+ : activeState.playing
623
+ // Without the progress bar the button stops the read-aloud outright.
624
+ ? (showProgressBar ? t('pause') : t('stop'))
625
+ : queueWaiting
626
+ // Still synthesizing the next chunk; a click cancels the run.
627
+ ? t('stop')
628
+ : hasAudio
629
+ ? t('play')
630
+ : t('speak');
631
+ return (_jsxs("span", { ref: rootRef, className: hasAudio ? 'mimo-speak-root mimo-speak-open' : 'mimo-speak-root', children: [_jsx(Tooltip, { label: buttonLabel, side: "bottom", children: _jsx("button", { ref: buttonRef, type: "button", className: phase === 'loading' ? 'mimo-speak-button mimo-speak-buttonBusy' : 'mimo-speak-button', "aria-label": buttonLabel, "aria-busy": phase === 'loading', "aria-pressed": activeState.playing, "aria-expanded": showProgressBar ? panelVisible : undefined, "aria-controls": showProgressBar ? panelId : undefined, onClick: onClick, onMouseEnter: ensureStatus, onFocus: ensureStatus, children: phase === 'loading'
632
+ ? _jsx("span", { className: "mimo-speak-spin", children: _jsx(IconLoadingOutlineRegular, { size: 15 }) })
633
+ : _jsx(IconVolumeOutlineRegular, { size: 15 }) }) }), failure !== null
634
+ ? (_jsx(Tooltip, { label: t(errorKeyFor(failure)), side: "bottom", children: _jsx("span", { className: "mimo-speak-failure", role: "img", tabIndex: 0, "aria-label": t(errorKeyFor(failure)), children: _jsx(IconWarningTriangleOutlineRegular, { size: 14 }) }) }))
635
+ : null, !panelVisible && hiddenStatus !== ''
636
+ ? (_jsx("span", { className: "mimo-speak-srOnly", role: "status", children: hiddenStatus }))
637
+ : null, panelVisible
638
+ ? (_jsxs("span", { id: panelId, className: panelSide === 'left' ? 'mimo-speak-panel mimo-speak-panelLeft' : 'mimo-speak-panel', children: [phase === 'loading'
639
+ ? (_jsx("span", { className: "mimo-speak-panelNote", role: "status", children: _jsx(TextShimmer, { active: true, children: t('synthesize') }) }))
640
+ : (_jsx(PlayerBar, { state: activeState, onToggle: panelToggle, onSeek: activeSeek, seekable: mode !== 'stream', labels: { play: t('play'), pause: t('pause'), progress: t('progress') } })), failure !== null
641
+ ? _jsx("p", { className: "mimo-speak-panelStatus", role: "status", children: t(errorKeyFor(failure)) })
642
+ : null, failure === null && autoplayBlocked
643
+ ? _jsx("p", { className: "mimo-speak-panelNote", role: "status", children: t('autoplayHint') })
644
+ : null, failure === null && truncated
645
+ ? _jsx("p", { className: "mimo-speak-panelNote", role: "status", children: t('truncated') })
646
+ : null, failure === null && fallbackNote
647
+ ? _jsx("p", { className: "mimo-speak-panelNote", role: "status", children: t('fallbackUsed') })
648
+ : null] }))
649
+ : null] }));
650
+ }
651
+ //# sourceMappingURL=SpeakAction.js.map