@ds-hu/dsh-bvi-input 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js ADDED
@@ -0,0 +1,2669 @@
1
+ /**
2
+ * Better voice input — browser half.
3
+ *
4
+ * One long-press gesture on the composer card starts speech capture, a full-screen
5
+ * overlay reproduces the DeepSeek App recording surface, and the transcript is written
6
+ * back through the composer's public `inputActions`. Audio and policy come from our own
7
+ * service component over same-origin HTTP; no Harness client package is imported.
8
+ *
9
+ * v0.2 adds three behaviours on top of the original batch hold-to-talk:
10
+ * - a focused-editor / virtual-keyboard guard so a touch long-press never starts while
11
+ * the user is typing (the desktop mouse gesture keeps working);
12
+ * - an optional configurable keyboard shortcut that drives the very same hold state
13
+ * machine (`preferences.shortcut`);
14
+ * - live streaming transcription for providers that declare `streaming: true`: an
15
+ * AudioWorklet (ScriptProcessor fallback) taps the microphone, PCM16LE 16 kHz chunks
16
+ * are POSTed every ~200 ms, the cumulative partial is rendered above the waveform and
17
+ * the final line flies from the overlay into the composer before it is inserted.
18
+ * The whole-WAV `MediaRecorder` batch path is unchanged when streaming is unavailable.
19
+ */
20
+ window.__ModuleLoader__.load({
21
+ id: '@ds-hu/dsh-bvi-input',
22
+ factory: (require) => {
23
+ var module = { exports: {} };
24
+ var exports = module.exports;
25
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
26
+
27
+ const react = require('react');
28
+ const reactDom = require('react-dom');
29
+ const { useCallback, useEffect, useRef, useState } = react;
30
+ const h = react.createElement;
31
+ const createPortal = reactDom.createPortal;
32
+
33
+ const NS = 'betterVoiceInput';
34
+ const API_BASE = '/api/better-voice-input';
35
+ const CSS_ID = '@ds-hu/dsh-bvi-input';
36
+ const OVERLAY_CLASS = 'bvi-overlay';
37
+ const HOLD_CLASS = 'bvi-holding';
38
+ const HINT_ATTR = 'data-bvi-hint';
39
+
40
+ /** The suggested shortcut echoed by the settings page when the user has not chosen one. */
41
+ const DEFAULT_SHORTCUT = {
42
+ enabled: false,
43
+ code: 'Space',
44
+ ctrl: true,
45
+ alt: false,
46
+ shift: true,
47
+ meta: false,
48
+ };
49
+
50
+ /** Gesture defaults mirror the service preference defaults in the host contract. */
51
+ const DEFAULTS = {
52
+ releaseAction: 'insert',
53
+ holdDelayMs: 280,
54
+ cancelDistancePx: 72,
55
+ hintDismissed: false,
56
+ composerHint: true,
57
+ streaming: true,
58
+ shortcut: DEFAULT_SHORTCUT,
59
+ };
60
+ const MOVE_TOLERANCE_PX = 8;
61
+ const CANCEL_RELEASE_RATIO = 0.6;
62
+ const MIN_RECORDING_MS = 300;
63
+ const STATE_TTL_MS = 4_000;
64
+ const PREPARE_POLL_MS = 800;
65
+ const TOAST_MS = 5_200;
66
+ const WAVE_PITCH_PX = 22;
67
+ const WAVE_MAX_BARS = 56;
68
+
69
+ /** Keyboard guard: a viewport at least 25 % shorter than the window means a keyboard is up. */
70
+ const VIRTUAL_KEYBOARD_RATIO = 0.75;
71
+
72
+ /** Canonical streaming audio: PCM16LE, mono, 16 kHz, ~200 ms per chunk. */
73
+ const LIVE_SAMPLE_RATE = 16_000;
74
+ const STREAM_CHUNK_MS = 200;
75
+ const MAX_STREAM_CHUNK_BYTES = 1024 * 1024;
76
+ const LIVE_TEXT_MAX_CHARS = 600;
77
+ const LIVE_WORKLET_NAME = 'bvi-live-capture';
78
+ const LIVE_WORKLET_SOURCE = [
79
+ 'class BviLiveCaptureProcessor extends AudioWorkletProcessor {',
80
+ ' process(inputs) {',
81
+ ' const channel = inputs[0] && inputs[0][0];',
82
+ ' if (channel && channel.length) this.port.postMessage(channel.slice(0));',
83
+ ' return true;',
84
+ ' }',
85
+ '}',
86
+ 'registerProcessor("' + LIVE_WORKLET_NAME + '", BviLiveCaptureProcessor);',
87
+ ].join('\n');
88
+
89
+ /** Final-line flight into the composer (DOM only; skipped for reduced motion). */
90
+ const FLIGHT_MS = 360;
91
+ const FLIGHT_SCALE = 0.6;
92
+ const FLIGHT_EASING = 'cubic-bezier(.2,.8,.2,1)';
93
+ const FLIGHT_TIMEOUT_MS = FLIGHT_MS + 160;
94
+
95
+ /** Keyboard codes that may end a shortcut hold and may never be a bare shortcut. */
96
+ const MODIFIER_KEY_CODES = [
97
+ 'AltLeft', 'AltRight', 'ControlLeft', 'ControlRight',
98
+ 'MetaLeft', 'MetaRight', 'ShiftLeft', 'ShiftRight', 'OSLeft', 'OSRight',
99
+ ];
100
+
101
+ /* ================================================================ */
102
+ /* dictionaries */
103
+ /* ================================================================ */
104
+
105
+ const zh = {
106
+ 'status.insert': '松手插入,上滑取消',
107
+ 'status.send': '松手发送,上滑取消',
108
+ 'status.insertKeyboard': '松开按键插入,按 Esc 取消',
109
+ 'status.sendKeyboard': '松开按键发送,按 Esc 取消',
110
+ 'status.streaming': '实时识别中…',
111
+ 'status.cancel': '松手取消',
112
+ 'status.preparing': '正在准备模型…',
113
+ 'status.transcribing': '正在转写…',
114
+ 'status.tooShort': '说话时间太短',
115
+ 'preparing.hint': '首次使用需要下载,本轮结束后会自动开始识别',
116
+ 'preparing.percent': '已完成 {percent}%',
117
+ 'cancelPrepare': '取消准备',
118
+ 'cancelTranscribe': '取消转写',
119
+ 'composerHint': '发消息或按住说话',
120
+ 'feedback.unavailable': '语音服务不可用:请确认「更好的语音输入」插件已启用。',
121
+ 'feedback.missingDependency': '语音转写尚未就绪:请先启用官方「语音输入」插件。',
122
+ 'feedback.noProvider': '尚未选择语音识别服务:请到插件设置里选择。',
123
+ 'feedback.empty': '没有识别到内容,请再说一次。',
124
+ 'feedback.tooLarge': '录音太长了,请缩短后重试。',
125
+ 'feedback.tooShort': '说话时间太短,请按住多说一会儿。',
126
+ 'feedback.failed': '转写失败:{message}',
127
+ 'feedback.streamFallback': '实时识别已中断,本轮改用整段识别。',
128
+ 'feedback.keyboardGuard': '键盘打开时长按不会录音,请先收起键盘再按住说话。',
129
+ 'feedback.conflict': '草稿已更新,识别结果没有插入。',
130
+ 'feedback.permission': '麦克风权限被拒绝:请在浏览器地址栏允许后重试。',
131
+ 'feedback.deviceMissing': '没有找到可用的麦克风。',
132
+ 'feedback.microphone': '无法使用麦克风:{message}',
133
+ 'feedback.prepareFailed': '模型准备失败:{message}',
134
+ 'feedback.cancelled': '已取消。',
135
+ 'feedback.ready': '本地模型已就绪,现在可以按住输入框说话。',
136
+ 'feedback.preparing': '本地模型正在准备,请稍候…',
137
+ 'feedback.recordingFailed': '录音失败:{message}',
138
+ };
139
+
140
+ const en = {
141
+ 'status.insert': 'Release to insert · slide up to cancel',
142
+ 'status.send': 'Release to send · slide up to cancel',
143
+ 'status.insertKeyboard': 'Release to insert · Esc to cancel',
144
+ 'status.sendKeyboard': 'Release to send · Esc to cancel',
145
+ 'status.streaming': 'Listening live…',
146
+ 'status.cancel': 'Release to cancel',
147
+ 'status.preparing': 'Preparing model…',
148
+ 'status.transcribing': 'Transcribing…',
149
+ 'status.tooShort': 'Too short',
150
+ 'preparing.hint': 'The first run downloads the model; recognition starts afterwards',
151
+ 'preparing.percent': '{percent}% complete',
152
+ 'cancelPrepare': 'Cancel preparation',
153
+ 'cancelTranscribe': 'Cancel transcription',
154
+ 'composerHint': 'Message, or hold to talk',
155
+ 'feedback.unavailable': 'Voice service unavailable: enable the “Better voice input” plugin.',
156
+ 'feedback.missingDependency': 'Speech-to-text is offline: enable the official Voice input plugin first.',
157
+ 'feedback.noProvider': 'No speech service selected yet: choose one in the plugin settings.',
158
+ 'feedback.empty': 'No speech detected. Please try again.',
159
+ 'feedback.tooLarge': 'The recording is too long. Please shorten it and retry.',
160
+ 'feedback.tooShort': 'Recording too short. Hold and speak a little longer.',
161
+ 'feedback.failed': 'Transcription failed: {message}',
162
+ 'feedback.streamFallback': 'Live recognition stopped; the whole take is being transcribed instead.',
163
+ 'feedback.keyboardGuard': 'Long-press stays quiet while the keyboard is open. Close it, then hold to talk.',
164
+ 'feedback.conflict': 'The draft changed, so the transcript was not inserted.',
165
+ 'feedback.permission': 'Microphone permission denied. Allow it in the address bar and retry.',
166
+ 'feedback.deviceMissing': 'No microphone was found.',
167
+ 'feedback.microphone': 'The microphone is unavailable: {message}',
168
+ 'feedback.prepareFailed': 'Model preparation failed: {message}',
169
+ 'feedback.cancelled': 'Cancelled.',
170
+ 'feedback.ready': 'The local model is ready. Hold the composer to talk.',
171
+ 'feedback.preparing': 'The local model is still preparing…',
172
+ 'feedback.recordingFailed': 'Recording failed: {message}',
173
+ };
174
+
175
+ /* ================================================================ */
176
+ /* small utilities */
177
+ /* ================================================================ */
178
+
179
+ function clamp(value, min, max) {
180
+ if (!Number.isFinite(value)) return min;
181
+ if (value < min) return min;
182
+ if (value > max) return max;
183
+ return value;
184
+ }
185
+
186
+ function isAbort(failure) {
187
+ return Boolean(failure && (failure.name === 'AbortError' || failure.code === 20));
188
+ }
189
+
190
+ function now() {
191
+ return typeof performance !== 'undefined' && typeof performance.now === 'function' ? performance.now() : Date.now();
192
+ }
193
+
194
+ function clampInteger(value, min, max, fallback) {
195
+ return Number.isInteger(value) ? clamp(value, min, max) : fallback;
196
+ }
197
+
198
+ /* ================================================================ */
199
+ /* preferences + optional keyboard shortcut */
200
+ /* ================================================================ */
201
+
202
+ /**
203
+ * A shortcut is exactly `{ enabled, code, ctrl, alt, shift, meta }` where `code` is a
204
+ * `KeyboardEvent.code` of 1–32 alphanumerics, never a bare modifier, and the combination
205
+ * carries ctrl/alt/meta (or is a function key) so a plain letter can never hijack typing.
206
+ * This tolerant normalizer mirrors the host's strict `sanitizePreferences` reader.
207
+ * @param {any} value - the `preferences.shortcut` value from `/state`.
208
+ * @returns {{enabled: boolean, code: string, ctrl: boolean, alt: boolean, shift: boolean, meta: boolean}} normalized shortcut.
209
+ */
210
+ function normalizeShortcut(value) {
211
+ if (!value || typeof value !== 'object') return { ...DEFAULT_SHORTCUT };
212
+ const rawCode = typeof value.code === 'string' ? value.code : '';
213
+ const validCode = /^[A-Za-z0-9]{1,32}$/u.test(rawCode) && !MODIFIER_KEY_CODES.includes(rawCode);
214
+ if (!validCode) return { ...DEFAULT_SHORTCUT };
215
+ const modifiers = {
216
+ ctrl: value.ctrl === true,
217
+ alt: value.alt === true,
218
+ shift: value.shift === true,
219
+ meta: value.meta === true,
220
+ };
221
+ return {
222
+ enabled: value.enabled === true && shortcutComboAllowed(rawCode, modifiers),
223
+ code: rawCode,
224
+ ...modifiers,
225
+ };
226
+ }
227
+
228
+ /** @returns {boolean} whether a code+modifier combination may ever be saved as a shortcut. */
229
+ function shortcutComboAllowed(code, modifiers) {
230
+ if (typeof code !== 'string' || !/^[A-Za-z0-9]{1,32}$/u.test(code)) return false;
231
+ if (MODIFIER_KEY_CODES.includes(code)) return false;
232
+ if (modifiers.ctrl || modifiers.alt || modifiers.meta) return true;
233
+ return /^F([1-9]|1[0-2])$/u.test(code);
234
+ }
235
+
236
+ /**
237
+ * Compare one keyboard event against a normalized shortcut. Repeats and IME composition
238
+ * events never match; modifiers are compared exactly so `Ctrl+Shift+Space` is not
239
+ * triggered by `Ctrl+Space`.
240
+ * @param {any} event - a `KeyboardEvent`.
241
+ * @param {any} shortcut - normalized shortcut.
242
+ * @returns {boolean} whether this event is the configured shortcut.
243
+ */
244
+ function matchesShortcut(event, shortcut) {
245
+ if (!event || !shortcut || shortcut.enabled !== true) return false;
246
+ if (event.repeat === true || event.isComposing === true) return false;
247
+ if (typeof event.code !== 'string' || event.code !== shortcut.code) return false;
248
+ if (Boolean(event.ctrlKey) !== shortcut.ctrl) return false;
249
+ if (Boolean(event.altKey) !== shortcut.alt) return false;
250
+ if (Boolean(event.shiftKey) !== shortcut.shift) return false;
251
+ if (Boolean(event.metaKey) !== shortcut.meta) return false;
252
+ return true;
253
+ }
254
+
255
+ /** @returns {boolean} whether a key code is a modifier key (used to end a shortcut hold). */
256
+ function isModifierCode(code) {
257
+ return typeof code === 'string' && MODIFIER_KEY_CODES.includes(code);
258
+ }
259
+
260
+ /**
261
+ * Shortcut events only fire while focus sits on the composer editor, the composer card
262
+ * itself or the document body — settings forms and other inputs keep typing normally.
263
+ * @param {{hasComposer: boolean, activeIsComposer: boolean, activeIsCard: boolean, activeIsBody: boolean}} input - focus facts.
264
+ * @returns {boolean} whether the shortcut may start a hold.
265
+ */
266
+ function shortcutAllowed(input) {
267
+ if (!input || input.hasComposer !== true) return false;
268
+ return input.activeIsComposer === true || input.activeIsCard === true || input.activeIsBody === true;
269
+ }
270
+
271
+ /**
272
+ * Normalize the service preferences document (tolerant reads; each invalid field falls
273
+ * back to its default). v0.2 adds `composerHint`, `streaming` and `shortcut`.
274
+ * @param {any} state - the `/state` payload.
275
+ * @returns {typeof DEFAULTS} normalized preferences.
276
+ */
277
+ function readPreferences(state) {
278
+ const preferences = state && typeof state === 'object' && state.preferences && typeof state.preferences === 'object' ? state.preferences : {};
279
+ return {
280
+ releaseAction: preferences.releaseAction === 'send' ? 'send' : 'insert',
281
+ holdDelayMs: clampInteger(preferences.holdDelayMs, 150, 1000, DEFAULTS.holdDelayMs),
282
+ cancelDistancePx: clampInteger(preferences.cancelDistancePx, 40, 200, DEFAULTS.cancelDistancePx),
283
+ hintDismissed: preferences.hintDismissed === true,
284
+ composerHint: preferences.composerHint !== false,
285
+ streaming: preferences.streaming !== false,
286
+ shortcut: normalizeShortcut(preferences.shortcut),
287
+ };
288
+ }
289
+
290
+ /** @returns {{maxAudioBytes: number, maxDurationSeconds: number}} service limits with safe fallbacks. */
291
+ function readLimits(state) {
292
+ const limits = state && typeof state === 'object' && state.limits && typeof state.limits === 'object' ? state.limits : {};
293
+ return {
294
+ maxAudioBytes: clampInteger(limits.maxAudioBytes, 64 * 1024, 16 * 1024 * 1024, 4 * 1024 * 1024),
295
+ maxDurationSeconds: clampInteger(limits.maxDurationSeconds, 5, 600, 120),
296
+ };
297
+ }
298
+
299
+ /* ================================================================ */
300
+ /* trigger guards + capture mode selection */
301
+ /* ================================================================ */
302
+
303
+ /**
304
+ * @param {number|undefined} viewportHeight - `visualViewport.height`.
305
+ * @param {number|undefined} windowHeight - `innerHeight`.
306
+ * @returns {boolean} whether the visual viewport shrank enough to be a software keyboard.
307
+ */
308
+ function isVirtualKeyboardOpen(viewportHeight, windowHeight) {
309
+ if (!Number.isFinite(viewportHeight) || !Number.isFinite(windowHeight)) return false;
310
+ if (viewportHeight <= 0 || windowHeight <= 0) return false;
311
+ return viewportHeight < windowHeight * VIRTUAL_KEYBOARD_RATIO;
312
+ }
313
+
314
+ /**
315
+ * Touch and pen long-presses never start while the composer editor owns focus or the
316
+ * virtual keyboard is open: the keyboard would be pushed away mid-gesture and the
317
+ * overlay would move the user's cursor. The desktop mouse keeps the gesture.
318
+ * @param {{pointerType?: string, editorFocused?: boolean, keyboardOpen?: boolean}} input - guard facts.
319
+ * @returns {boolean} whether the pointer hold may start.
320
+ */
321
+ function shouldStartPointerHold(input) {
322
+ const pointerType = input && typeof input.pointerType === 'string' && input.pointerType !== '' ? input.pointerType : 'mouse';
323
+ if (pointerType === 'mouse') return true;
324
+ if (input && input.editorFocused === true) return false;
325
+ if (input && input.keyboardOpen === true) return false;
326
+ return true;
327
+ }
328
+
329
+ /**
330
+ * Per-recording capture mode. Streaming only when the preference is on, the selected
331
+ * provider declares `streaming: true` in `/state` and live PCM capture is available.
332
+ * @param {{preferences?: any, state?: any, liveSupported?: boolean}} input - selection facts.
333
+ * @returns {'stream'|'batch'} capture mode for the next take.
334
+ */
335
+ function captureModeFor(input) {
336
+ const preferences = input && input.preferences && typeof input.preferences === 'object' ? input.preferences : {};
337
+ if (preferences.streaming !== true) return 'batch';
338
+ if (input && input.liveSupported === false) return 'batch';
339
+ const state = input ? input.state : undefined;
340
+ const providerId = state && state.selection && typeof state.selection.providerId === 'string' ? state.selection.providerId : undefined;
341
+ const provider = state && Array.isArray(state.providers) ? state.providers.find((entry) => entry && entry.id === providerId) : undefined;
342
+ return provider && provider.streaming === true ? 'stream' : 'batch';
343
+ }
344
+
345
+ /**
346
+ * Hold-gesture state machine. Pure so the gesture rules are unit-testable without
347
+ * a browser: `event.time` is only carried for diagnostics, callers own the timer.
348
+ *
349
+ * Phases: idle -> pressing -> recording <-> cancel -> (finished | cancelled)
350
+ */
351
+ function holdStart() {
352
+ return { phase: 'idle', pointerId: null, startX: 0, startY: 0, armed: false };
353
+ }
354
+
355
+ /**
356
+ * Advance the gesture state.
357
+ * @param {ReturnType<typeof holdStart>} state - current state.
358
+ * @param {{ type: string, pointerId?: number, x?: number, y?: number }} event - input event.
359
+ * @param {{ cancelDistancePx: number, moveTolerancePx?: number }} options - thresholds.
360
+ * @returns {{ state: ReturnType<typeof holdStart>, action: string }} next state and side effect.
361
+ */
362
+ function holdStep(state, event, options) {
363
+ const tolerance = options && Number.isFinite(options.moveTolerancePx) ? options.moveTolerancePx : MOVE_TOLERANCE_PX;
364
+ const cancelDistance = options && Number.isFinite(options.cancelDistancePx) ? options.cancelDistancePx : DEFAULTS.cancelDistancePx;
365
+ switch (event.type) {
366
+ case 'press': {
367
+ if (state.phase !== 'idle') return { state, action: 'ignore' };
368
+ return { state: { phase: 'pressing', pointerId: event.pointerId, startX: event.x, startY: event.y, armed: false }, action: 'none' };
369
+ }
370
+ case 'hold': {
371
+ if (state.phase !== 'pressing') return { state, action: 'ignore' };
372
+ return { state: { ...state, phase: 'recording', armed: false }, action: 'start' };
373
+ }
374
+ case 'move': {
375
+ if (state.phase === 'pressing') {
376
+ const moved = Math.hypot(event.x - state.startX, event.y - state.startY);
377
+ if (moved > tolerance) return { state: holdStart(), action: 'abort' };
378
+ return { state, action: 'none' };
379
+ }
380
+ if (state.phase === 'recording' || state.phase === 'cancel') {
381
+ const risen = state.startY - event.y;
382
+ if (state.phase === 'recording' && risen >= cancelDistance) return { state: { ...state, phase: 'cancel', armed: true }, action: 'arm' };
383
+ if (state.phase === 'cancel' && risen < cancelDistance * CANCEL_RELEASE_RATIO) return { state: { ...state, phase: 'recording', armed: false }, action: 'disarm' };
384
+ return { state, action: 'none' };
385
+ }
386
+ return { state, action: 'ignore' };
387
+ }
388
+ case 'release': {
389
+ if (state.phase === 'recording') return { state: holdStart(), action: 'finish' };
390
+ if (state.phase === 'cancel') return { state: holdStart(), action: 'cancel' };
391
+ if (state.phase === 'pressing') return { state: holdStart(), action: 'abort' };
392
+ return { state, action: 'ignore' };
393
+ }
394
+ case 'cancel': {
395
+ if (state.phase === 'recording' || state.phase === 'cancel') return { state: holdStart(), action: 'cancel' };
396
+ if (state.phase === 'pressing') return { state: holdStart(), action: 'abort' };
397
+ return { state, action: 'ignore' };
398
+ }
399
+ default:
400
+ return { state, action: 'ignore' };
401
+ }
402
+ }
403
+
404
+ /** @returns {boolean} whether the keyboard event should cancel the current overlay. */
405
+ function isEscape(event) {
406
+ return Boolean(event && event.key === 'Escape');
407
+ }
408
+
409
+ /** @returns {number} waveform bar count for a viewport width. */
410
+ function barCountFor(viewportWidth) {
411
+ const width = Number.isFinite(viewportWidth) && viewportWidth > 0 ? viewportWidth : 1024;
412
+ return clampInteger(Math.round(width / WAVE_PITCH_PX), 16, WAVE_MAX_BARS, 40);
413
+ }
414
+
415
+ /** @returns {number} bar height in px for one level sample. */
416
+ function barHeight(level) {
417
+ const safe = Number.isFinite(level) ? clamp(level, 0, 1) : 0;
418
+ return Math.round(6 + safe * 34);
419
+ }
420
+
421
+ /* ================================================================ */
422
+ /* PCM / WAV helpers */
423
+ /* ================================================================ */
424
+
425
+ /** @returns {number} the canonical PCM16 value of a float sample in [-1, 1]. */
426
+ function sampleToInt16(sample) {
427
+ const value = clamp(sample, -1, 1);
428
+ return Math.round(value * (value < 0 ? 32768 : 32767));
429
+ }
430
+
431
+ /** Write the canonical 44-byte mono PCM16 RIFF header. */
432
+ function writeWavHeader(bytes, dataBytes, sampleRate) {
433
+ const rate = Number.isFinite(sampleRate) && sampleRate > 0 ? Math.round(sampleRate) : 16000;
434
+ const view = new DataView(bytes.buffer);
435
+ const text = (at, value) => {
436
+ for (let index = 0; index < value.length; index += 1) bytes[at + index] = value.charCodeAt(index);
437
+ };
438
+ text(0, 'RIFF');
439
+ view.setUint32(4, bytes.length - 8, true);
440
+ text(8, 'WAVE');
441
+ text(12, 'fmt ');
442
+ view.setUint32(16, 16, true);
443
+ view.setUint16(20, 1, true);
444
+ view.setUint16(22, 1, true);
445
+ view.setUint32(24, rate, true);
446
+ view.setUint32(28, rate * 2, true);
447
+ view.setUint16(32, 2, true);
448
+ view.setUint16(34, 16, true);
449
+ text(36, 'data');
450
+ view.setUint32(40, dataBytes, true);
451
+ }
452
+
453
+ /**
454
+ * Encode mono float samples as a canonical 16 kHz PCM16 WAV.
455
+ * @param {Float32Array} samples - mono samples in [-1, 1].
456
+ * @param {number} sampleRate - sample rate of `samples` (must already be 16000 for uploads).
457
+ * @returns {Uint8Array} complete little-endian WAV bytes.
458
+ */
459
+ function encodeWav(samples, sampleRate) {
460
+ const bytes = new Uint8Array(44 + samples.length * 2);
461
+ writeWavHeader(bytes, samples.length * 2, sampleRate);
462
+ const view = new DataView(bytes.buffer);
463
+ for (let index = 0; index < samples.length; index += 1) {
464
+ view.setInt16(44 + index * 2, sampleToInt16(samples[index]), true);
465
+ }
466
+ return bytes;
467
+ }
468
+
469
+ /**
470
+ * Wrap already-16 kHz PCM16LE bytes in a canonical WAV container (batch fallback after
471
+ * a broken live stream keeps the take without re-resampling).
472
+ * @param {Uint8Array} pcm - PCM16LE mono 16 kHz bytes.
473
+ * @returns {Uint8Array} complete little-endian WAV bytes.
474
+ */
475
+ function encodeWavFromPcm16(pcm) {
476
+ const samples = pcm && typeof pcm.byteLength === 'number' ? pcm : new Uint8Array(0);
477
+ const bytes = new Uint8Array(44 + samples.byteLength);
478
+ writeWavHeader(bytes, samples.byteLength, LIVE_SAMPLE_RATE);
479
+ bytes.set(samples, 44);
480
+ return bytes;
481
+ }
482
+
483
+ /**
484
+ * Linear-interpolation resampler used by the live streaming path (the batch path keeps
485
+ * using OfflineAudioContext, which is already exact for whole recordings).
486
+ * @param {ArrayLike<number>} samples - input mono samples.
487
+ * @param {number} fromRate - input sample rate.
488
+ * @param {number} toRate - output sample rate.
489
+ * @returns {Float32Array} resampled mono samples.
490
+ */
491
+ function resampleFloat32(samples, fromRate, toRate) {
492
+ const input = samples && Number.isFinite(samples.length) ? samples : new Float32Array(0);
493
+ const from = Number.isFinite(fromRate) && fromRate > 0 ? fromRate : LIVE_SAMPLE_RATE;
494
+ const to = Number.isFinite(toRate) && toRate > 0 ? toRate : LIVE_SAMPLE_RATE;
495
+ if (input.length === 0) return new Float32Array(0);
496
+ const ratio = from / to;
497
+ const length = Math.max(1, Math.round(input.length / ratio));
498
+ const output = new Float32Array(length);
499
+ for (let index = 0; index < length; index += 1) {
500
+ const position = index * ratio;
501
+ const low = Math.floor(position);
502
+ const fraction = position - low;
503
+ const a = input[Math.min(low, input.length - 1)];
504
+ const b = input[Math.min(low + 1, input.length - 1)];
505
+ output[index] = a + (b - a) * fraction;
506
+ }
507
+ return output;
508
+ }
509
+
510
+ /** @returns {Float32Array} samples downsampled to the 16 kHz streaming rate. */
511
+ function downsampleTo16k(samples, sampleRate) {
512
+ return resampleFloat32(samples, sampleRate, LIVE_SAMPLE_RATE);
513
+ }
514
+
515
+ /** @returns {Uint8Array} PCM16LE bytes for float samples in [-1, 1]. */
516
+ function floatToPcm16(samples) {
517
+ const input = samples && Number.isFinite(samples.length) ? samples : new Float32Array(0);
518
+ const bytes = new Uint8Array(input.length * 2);
519
+ const view = new DataView(bytes.buffer);
520
+ for (let index = 0; index < input.length; index += 1) {
521
+ view.setInt16(index * 2, sampleToInt16(input[index]), true);
522
+ }
523
+ return bytes;
524
+ }
525
+
526
+ /** @returns {Float32Array} mono float samples decoded from PCM16LE bytes. */
527
+ function pcm16ToFloat32(pcm) {
528
+ const bytes = pcm && typeof pcm.byteLength === 'number' ? pcm : new Uint8Array(0);
529
+ const length = Math.floor(bytes.byteLength / 2);
530
+ const output = new Float32Array(length);
531
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
532
+ for (let index = 0; index < length; index += 1) {
533
+ const sample = view.getInt16(index * 2, true);
534
+ output[index] = sample < 0 ? sample / 32768 : sample / 32767;
535
+ }
536
+ return output;
537
+ }
538
+
539
+ /** Concatenate byte parts, optionally trusting a precomputed total length. */
540
+ function concatBytes(parts, totalLength) {
541
+ const list = Array.isArray(parts) ? parts : [];
542
+ let length = Number.isFinite(totalLength) ? Math.max(0, Math.floor(totalLength)) : 0;
543
+ if (!Number.isFinite(totalLength)) {
544
+ for (const part of list) length += part && typeof part.byteLength === 'number' ? part.byteLength : 0;
545
+ }
546
+ const output = new Uint8Array(length);
547
+ let offset = 0;
548
+ for (const part of list) {
549
+ if (!part || part.byteLength === 0 || offset >= length) continue;
550
+ const view = part instanceof Uint8Array ? part : new Uint8Array(part);
551
+ output.set(view.subarray(0, Math.max(0, length - offset)), offset);
552
+ offset += view.byteLength;
553
+ }
554
+ return output;
555
+ }
556
+
557
+ /**
558
+ * Take at most `maxBytes` whole PCM16 frames off the front of a stream buffer. Keeping
559
+ * the cut on an even byte keeps every chunk a valid PCM16LE payload.
560
+ * @param {Uint8Array} buffer - pending PCM16LE bytes.
561
+ * @param {number} [maxBytes] - hard chunk ceiling (defaults to the service's 1 MiB cap).
562
+ * @returns {{chunk: Uint8Array, rest: Uint8Array}} one chunk and the remaining bytes.
563
+ */
564
+ function splitStreamingChunk(buffer, maxBytes) {
565
+ const source = buffer && typeof buffer.subarray === 'function' ? buffer : new Uint8Array(0);
566
+ const limit = Number.isFinite(maxBytes) && maxBytes >= 2 ? Math.floor(maxBytes / 2) * 2 : MAX_STREAM_CHUNK_BYTES;
567
+ if (source.byteLength < 2) return { chunk: new Uint8Array(0), rest: new Uint8Array(source) };
568
+ const size = Math.min(source.byteLength, limit);
569
+ const even = size % 2 === 0 ? size : size - 1;
570
+ if (even < 2) return { chunk: new Uint8Array(0), rest: new Uint8Array(source) };
571
+ return { chunk: source.subarray(0, even), rest: source.subarray(even) };
572
+ }
573
+
574
+ /**
575
+ * Keep the live overlay line small: the newest {@link LIVE_TEXT_MAX_CHARS} characters of
576
+ * the cumulative partial (the overlay itself clamps to three visual lines).
577
+ * @param {string} text - cumulative partial.
578
+ * @returns {string} the display text.
579
+ */
580
+ function trimLiveText(text) {
581
+ const value = typeof text === 'string' ? text : '';
582
+ if (value.length <= LIVE_TEXT_MAX_CHARS) return value;
583
+ return '…' + value.slice(value.length - LIVE_TEXT_MAX_CHARS);
584
+ }
585
+
586
+ /* ================================================================ */
587
+ /* final-line flight animation (pure planning) */
588
+ /* ================================================================ */
589
+
590
+ /** @returns {{left: number, top: number, width: number, height: number}|null} a usable viewport rect. */
591
+ function usableRect(rect) {
592
+ if (!rect || typeof rect !== 'object') return null;
593
+ const left = Number(rect.left);
594
+ const top = Number(rect.top);
595
+ const width = Number(rect.width);
596
+ const height = Number(rect.height);
597
+ if (!Number.isFinite(left) || !Number.isFinite(top) || !Number.isFinite(width) || !Number.isFinite(height)) return null;
598
+ if (width <= 0 || height <= 0) return null;
599
+ return { left, top, width, height };
600
+ }
601
+
602
+ /**
603
+ * Plan the DOM-only flight of the final transcript from the overlay line to the composer
604
+ * target. A `null` plan means "insert immediately": reduced motion, empty text or a
605
+ * missing rect all skip the animation.
606
+ * @param {{text?: string, from?: any, to?: any, reducedMotion?: boolean}} input - flight facts.
607
+ * @returns {{text: string, left: number, top: number, width: number, height: number, dx: number, dy: number, scale: number, durationMs: number, easing: string, transform: string, opacity: number}|null} plan.
608
+ */
609
+ function planFlight(input) {
610
+ const source = input && typeof input === 'object' ? input : {};
611
+ const text = typeof source.text === 'string' ? source.text.trim() : '';
612
+ if (text === '' || source.reducedMotion === true) return null;
613
+ const from = usableRect(source.from);
614
+ const to = usableRect(source.to);
615
+ if (!from || !to) return null;
616
+ const dx = Math.round((to.left + to.width / 2) - (from.left + from.width / 2));
617
+ const dy = Math.round((to.top + to.height / 2) - (from.top + from.height / 2));
618
+ return {
619
+ text,
620
+ left: from.left,
621
+ top: from.top,
622
+ width: from.width,
623
+ height: from.height,
624
+ dx,
625
+ dy,
626
+ scale: FLIGHT_SCALE,
627
+ durationMs: FLIGHT_MS,
628
+ easing: FLIGHT_EASING,
629
+ transform: 'translate(' + dx + 'px,' + dy + 'px) scale(' + FLIGHT_SCALE + ')',
630
+ opacity: 0,
631
+ };
632
+ }
633
+
634
+ /* ================================================================ */
635
+ /* microphone capture */
636
+ /* ================================================================ */
637
+
638
+ /** Capture failures whose kind is localized by the caller. */
639
+ class CaptureError extends Error {
640
+ constructor(kind) {
641
+ super(kind);
642
+ this.name = 'CaptureError';
643
+ this.kind = kind;
644
+ }
645
+ }
646
+
647
+ /** @returns {'permission'|'deviceMissing'|'unavailable'} localized kind of a media failure. */
648
+ function classifyMediaError(failure) {
649
+ if (failure instanceof DOMException) {
650
+ if (failure.name === 'NotAllowedError' || failure.name === 'SecurityError') return 'permission';
651
+ if (failure.name === 'NotFoundError' || failure.name === 'OverconstrainedError') return 'deviceMissing';
652
+ }
653
+ return 'unavailable';
654
+ }
655
+
656
+ /** @returns {any} the platform AudioContext constructor, if any. */
657
+ function audioContextConstructor() {
658
+ if (typeof window === 'undefined') return null;
659
+ if (typeof window.AudioContext === 'function') return window.AudioContext;
660
+ if (typeof window.webkitAudioContext === 'function') return window.webkitAudioContext;
661
+ return null;
662
+ }
663
+
664
+ /**
665
+ * @returns {boolean} whether live PCM capture (AudioWorklet or ScriptProcessor) can run
666
+ * in this browser. Authored as a pure capability check so the capture mode decision is
667
+ * testable without a microphone.
668
+ */
669
+ function liveCaptureSupported() {
670
+ if (typeof window === 'undefined') return false;
671
+ const hasWorklet = typeof window.AudioWorkletNode === 'function';
672
+ const hasProcessor = typeof window.ScriptProcessorNode === 'function';
673
+ if (!hasWorklet && !hasProcessor) return false;
674
+ if (typeof window.AudioContext !== 'function' && typeof window.webkitAudioContext !== 'function') return false;
675
+ const devices = typeof navigator !== 'undefined' ? navigator.mediaDevices : undefined;
676
+ return Boolean(devices && typeof devices.getUserMedia === 'function');
677
+ }
678
+
679
+ /**
680
+ * One microphone acquisition: MediaRecorder for the payload, an AnalyserNode for
681
+ * the live waveform, and an OfflineAudioContext to resample to 16 kHz mono WAV.
682
+ * The batch path is unchanged from v0.1; streaming uses {@link LivePcmCapture}.
683
+ */
684
+ class MicrophoneCapture {
685
+ constructor() {
686
+ this.stream = undefined;
687
+ this.recorder = undefined;
688
+ this.context = undefined;
689
+ this.analyser = undefined;
690
+ this.chunks = [];
691
+ this.samples = new Float32Array(256);
692
+ this.stopped = false;
693
+ this.disposal = undefined;
694
+ this.onInterrupted = undefined;
695
+ }
696
+
697
+ /**
698
+ * Acquire the microphone and start recording.
699
+ * @param {() => void} onInterrupted - fired when the device disappears mid-capture.
700
+ * @returns {Promise<void>} resolves once frames are flowing.
701
+ */
702
+ async start(onInterrupted) {
703
+ if (typeof MediaRecorder === 'undefined') throw new CaptureError('unavailable');
704
+ const devices = typeof navigator !== 'undefined' ? navigator.mediaDevices : undefined;
705
+ if (!devices || typeof devices.getUserMedia !== 'function') throw new CaptureError('unavailable');
706
+ this.onInterrupted = onInterrupted;
707
+ let stream;
708
+ try {
709
+ stream = await devices.getUserMedia({
710
+ audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true, autoGainControl: true },
711
+ video: false,
712
+ });
713
+ } catch (failure) {
714
+ throw new CaptureError(classifyMediaError(failure));
715
+ }
716
+ if (this.stopped) {
717
+ stream.getTracks().forEach((track) => track.stop());
718
+ throw new CaptureError('cancelled');
719
+ }
720
+ this.stream = stream;
721
+ try {
722
+ this.context = new AudioContext();
723
+ if (this.context.state === 'suspended') await this.context.resume();
724
+ this.analyser = this.context.createAnalyser();
725
+ this.analyser.fftSize = this.samples.length;
726
+ this.context.createMediaStreamSource(stream).connect(this.analyser);
727
+ for (const track of stream.getTracks()) {
728
+ track.addEventListener('ended', () => {
729
+ if (!this.stopped) this.onInterrupted?.();
730
+ });
731
+ }
732
+ this.recorder = new MediaRecorder(stream);
733
+ this.recorder.ondataavailable = (event) => {
734
+ if (!this.stopped && event.data && event.data.size > 0) this.chunks.push(event.data);
735
+ };
736
+ this.recorder.onerror = () => {
737
+ if (!this.stopped) this.onInterrupted?.();
738
+ };
739
+ this.recorder.start();
740
+ } catch (failure) {
741
+ await this.dispose();
742
+ if (failure instanceof CaptureError) throw failure;
743
+ throw new CaptureError('unavailable');
744
+ }
745
+ }
746
+
747
+ /** @returns {number} current RMS level in [0, 1]. */
748
+ amplitude() {
749
+ if (!this.analyser) return 0;
750
+ this.analyser.getFloatTimeDomainData(this.samples);
751
+ let sum = 0;
752
+ for (const sample of this.samples) sum += sample * sample;
753
+ return Math.min(1, Math.sqrt(sum / this.samples.length) * 4);
754
+ }
755
+
756
+ /**
757
+ * Stop capture and return canonical 16 kHz mono PCM16 WAV bytes.
758
+ * @param {number} maxDurationSeconds - hard truncation limit.
759
+ * @returns {Promise<Uint8Array>} the complete WAV payload.
760
+ */
761
+ async stop(maxDurationSeconds) {
762
+ const recorder = this.recorder;
763
+ const context = this.context;
764
+ if (!recorder || !context || recorder.state !== 'recording') {
765
+ await this.dispose();
766
+ throw new CaptureError('empty');
767
+ }
768
+ try {
769
+ await new Promise((resolve, reject) => {
770
+ recorder.onstop = () => resolve();
771
+ recorder.onerror = () => reject(new CaptureError('empty'));
772
+ recorder.stop();
773
+ });
774
+ this.stream?.getTracks().forEach((track) => track.stop());
775
+ const blob = new Blob(this.chunks, { type: recorder.mimeType });
776
+ if (blob.size === 0) throw new CaptureError('empty');
777
+ const decoded = await context.decodeAudioData(await blob.arrayBuffer());
778
+ const seconds = Math.max(0.05, Math.min(decoded.duration, maxDurationSeconds));
779
+ const frames = Math.max(1, Math.floor(seconds * 16000));
780
+ const offline = new OfflineAudioContext(1, frames, 16000);
781
+ const source = offline.createBufferSource();
782
+ source.buffer = decoded;
783
+ source.connect(offline.destination);
784
+ source.start();
785
+ const rendered = await offline.startRendering();
786
+ return encodeWav(rendered.getChannelData(0), 16000);
787
+ } finally {
788
+ await this.dispose();
789
+ }
790
+ }
791
+
792
+ /** @returns {Promise<void>} idempotent resource release. */
793
+ dispose() {
794
+ if (!this.disposal) {
795
+ this.disposal = this.release();
796
+ }
797
+ return this.disposal;
798
+ }
799
+
800
+ async release() {
801
+ this.stopped = true;
802
+ try {
803
+ if (this.recorder && this.recorder.state === 'recording') this.recorder.stop();
804
+ } catch {
805
+ /* a stopped recorder is already silent */
806
+ }
807
+ this.stream?.getTracks().forEach((track) => track.stop());
808
+ this.stream = undefined;
809
+ this.analyser = undefined;
810
+ const context = this.context;
811
+ this.context = undefined;
812
+ this.chunks = [];
813
+ try {
814
+ if (context && context.state !== 'closed') await context.close();
815
+ } catch {
816
+ /* closing an already interrupted context is harmless */
817
+ }
818
+ }
819
+ }
820
+
821
+ /**
822
+ * Live PCM capture for the streaming path: the same microphone acquisition and analyser
823
+ * meter as {@link MicrophoneCapture}, but Float32 frames flow to `onFrames` instead of into
824
+ * a MediaRecorder. AudioWorklet first (inline blob module), ScriptProcessor fallback.
825
+ */
826
+ class LivePcmCapture {
827
+ constructor() {
828
+ this.stream = undefined;
829
+ this.context = undefined;
830
+ this.analyser = undefined;
831
+ this.worklet = undefined;
832
+ this.processor = undefined;
833
+ this.mute = undefined;
834
+ this.source = undefined;
835
+ this.samples = new Float32Array(256);
836
+ this.stopped = false;
837
+ this.disposal = undefined;
838
+ this.onInterrupted = undefined;
839
+ this.onFrames = undefined;
840
+ this.usingWorklet = false;
841
+ }
842
+
843
+ /**
844
+ * Acquire the microphone and start producing Float32 frames.
845
+ * @param {() => void} onInterrupted - fired when the device disappears mid-capture.
846
+ * @param {(samples: Float32Array, sampleRate: number) => void} onFrames - frame sink.
847
+ * @returns {Promise<void>} resolves once frames are flowing.
848
+ */
849
+ async start(onInterrupted, onFrames) {
850
+ const Context = audioContextConstructor();
851
+ const devices = typeof navigator !== 'undefined' ? navigator.mediaDevices : undefined;
852
+ if (!Context || !devices || typeof devices.getUserMedia !== 'function') throw new CaptureError('unavailable');
853
+ this.onInterrupted = onInterrupted;
854
+ this.onFrames = onFrames;
855
+ let stream;
856
+ try {
857
+ stream = await devices.getUserMedia({
858
+ audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true, autoGainControl: true },
859
+ video: false,
860
+ });
861
+ } catch (failure) {
862
+ throw new CaptureError(classifyMediaError(failure));
863
+ }
864
+ if (this.stopped) {
865
+ stream.getTracks().forEach((track) => track.stop());
866
+ throw new CaptureError('cancelled');
867
+ }
868
+ this.stream = stream;
869
+ try {
870
+ this.context = new Context();
871
+ if (this.context.state === 'suspended') await this.context.resume();
872
+ this.analyser = this.context.createAnalyser();
873
+ this.analyser.fftSize = this.samples.length;
874
+ this.source = this.context.createMediaStreamSource(stream);
875
+ this.source.connect(this.analyser);
876
+ this.mute = this.context.createGain();
877
+ this.mute.gain.value = 0;
878
+ this.mute.connect(this.context.destination);
879
+ for (const track of stream.getTracks()) {
880
+ track.addEventListener('ended', () => {
881
+ if (!this.stopped) this.onInterrupted?.();
882
+ });
883
+ }
884
+ const emit = (frames) => {
885
+ if (this.stopped || !this.onFrames || !frames) return;
886
+ this.onFrames(frames, this.context ? this.context.sampleRate : LIVE_SAMPLE_RATE);
887
+ };
888
+ const canWorklet = typeof window !== 'undefined'
889
+ && typeof window.AudioWorkletNode === 'function'
890
+ && this.context.audioWorklet
891
+ && typeof this.context.audioWorklet.addModule === 'function'
892
+ && typeof Blob !== 'undefined'
893
+ && typeof URL !== 'undefined'
894
+ && typeof URL.createObjectURL === 'function';
895
+ if (canWorklet) {
896
+ try {
897
+ const objectUrl = URL.createObjectURL(new Blob([LIVE_WORKLET_SOURCE], { type: 'application/javascript' }));
898
+ try {
899
+ await this.context.audioWorklet.addModule(objectUrl);
900
+ } finally {
901
+ URL.revokeObjectURL(objectUrl);
902
+ }
903
+ this.worklet = new window.AudioWorkletNode(this.context, LIVE_WORKLET_NAME);
904
+ this.worklet.port.onmessage = (event) => {
905
+ const frames = event && event.data;
906
+ if (frames && typeof frames.length === 'number') emit(frames);
907
+ };
908
+ this.source.connect(this.worklet);
909
+ this.worklet.connect(this.mute);
910
+ this.usingWorklet = true;
911
+ } catch {
912
+ /* insecure context or a rejected worklet module: reuse the ScriptProcessor below */
913
+ }
914
+ }
915
+ const canProcessor = typeof window !== 'undefined' && typeof window.ScriptProcessorNode === 'function';
916
+ if (!this.usingWorklet && canProcessor) {
917
+ this.processor = this.context.createScriptProcessor(4096, 1, 1);
918
+ this.processor.onaudioprocess = (event) => {
919
+ const channel = event && event.inputBuffer ? event.inputBuffer.getChannelData(0) : null;
920
+ if (channel) emit(new Float32Array(channel));
921
+ };
922
+ this.source.connect(this.processor);
923
+ this.processor.connect(this.mute);
924
+ }
925
+ if (!this.usingWorklet && !this.processor) throw new CaptureError('unavailable');
926
+ } catch (failure) {
927
+ await this.dispose();
928
+ if (failure instanceof CaptureError) throw failure;
929
+ throw new CaptureError('unavailable');
930
+ }
931
+ }
932
+
933
+ /** @returns {number} current RMS level in [0, 1]. */
934
+ amplitude() {
935
+ if (!this.analyser) return 0;
936
+ this.analyser.getFloatTimeDomainData(this.samples);
937
+ let sum = 0;
938
+ for (const sample of this.samples) sum += sample * sample;
939
+ return Math.min(1, Math.sqrt(sum / this.samples.length) * 4);
940
+ }
941
+
942
+ /** @returns {Promise<void>} stop and release the microphone (no payload is built here). */
943
+ async stop() {
944
+ await this.dispose();
945
+ }
946
+
947
+ /** @returns {Promise<void>} idempotent resource release. */
948
+ dispose() {
949
+ if (!this.disposal) {
950
+ this.disposal = this.release();
951
+ }
952
+ return this.disposal;
953
+ }
954
+
955
+ async release() {
956
+ this.stopped = true;
957
+ try {
958
+ if (this.worklet) {
959
+ this.worklet.port.onmessage = null;
960
+ this.worklet.disconnect();
961
+ }
962
+ } catch {
963
+ /* disconnecting an interrupted node is harmless */
964
+ }
965
+ try {
966
+ if (this.processor) {
967
+ this.processor.onaudioprocess = null;
968
+ this.processor.disconnect();
969
+ }
970
+ } catch {
971
+ /* disconnecting an interrupted node is harmless */
972
+ }
973
+ try { if (this.source) this.source.disconnect(); } catch { /* optional */ }
974
+ try { if (this.analyser) this.analyser.disconnect(); } catch { /* optional */ }
975
+ try { if (this.mute) this.mute.disconnect(); } catch { /* optional */ }
976
+ this.stream?.getTracks().forEach((track) => track.stop());
977
+ this.stream = undefined;
978
+ this.analyser = undefined;
979
+ this.worklet = undefined;
980
+ this.processor = undefined;
981
+ this.mute = undefined;
982
+ this.source = undefined;
983
+ this.onFrames = undefined;
984
+ const context = this.context;
985
+ this.context = undefined;
986
+ try {
987
+ if (context && context.state !== 'closed') await context.close();
988
+ } catch {
989
+ /* closing an already interrupted context is harmless */
990
+ }
991
+ }
992
+ }
993
+
994
+ /* ================================================================ */
995
+ /* service HTTP client */
996
+ /* ================================================================ */
997
+
998
+ class ServiceError extends Error {
999
+ constructor(code, message) {
1000
+ super(message || code);
1001
+ this.name = 'ServiceError';
1002
+ this.code = code;
1003
+ }
1004
+ }
1005
+
1006
+ /** @returns {Promise<any>} decoded JSON of a service mutation; throws {@link ServiceError} on failure. */
1007
+ async function serviceJson(fetchImpl, path, init) {
1008
+ const response = await fetchImpl(API_BASE + path, init);
1009
+ const payload = await response.json().catch(() => null);
1010
+ if (!response.ok || !payload || payload.ok === false) {
1011
+ const detail = payload && typeof payload.message === 'string' ? payload.message : 'HTTP ' + response.status;
1012
+ const error = new ServiceError(payload && typeof payload.code === 'string' ? payload.code : 'http', detail);
1013
+ error.status = response.status;
1014
+ throw error;
1015
+ }
1016
+ return payload;
1017
+ }
1018
+
1019
+ /** Service request helper shared by the overlay runtime; no credentials are needed. */
1020
+ const service = {
1021
+ stateCache: null,
1022
+ stateAt: 0,
1023
+ pending: null,
1024
+ inflight: null,
1025
+
1026
+ /** @returns {Promise<any|null>} a fresh-enough `/state` payload, or null when unreachable. */
1027
+ async state(force) {
1028
+ const fresh = this.stateCache !== null && now() - this.stateAt < STATE_TTL_MS;
1029
+ if (fresh && !force) return this.stateCache;
1030
+ if (this.inflight) return this.inflight;
1031
+ this.inflight = (async () => {
1032
+ try {
1033
+ const response = await fetch(API_BASE + '/state', { credentials: 'same-origin', headers: { accept: 'application/json' } });
1034
+ if (!response.ok) return null;
1035
+ const payload = await response.json();
1036
+ this.stateCache = payload;
1037
+ this.stateAt = now();
1038
+ return payload;
1039
+ } catch {
1040
+ return null;
1041
+ } finally {
1042
+ this.inflight = null;
1043
+ }
1044
+ })();
1045
+ return this.inflight;
1046
+ },
1047
+
1048
+ /** @returns {Promise<any>} decoded JSON of a mutation. */
1049
+ async post(path, body, signal) {
1050
+ return serviceJson(fetch, path, {
1051
+ method: 'POST',
1052
+ credentials: 'same-origin',
1053
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
1054
+ body: JSON.stringify(body ?? {}),
1055
+ signal,
1056
+ });
1057
+ },
1058
+
1059
+ /**
1060
+ * Send one WAV payload for recognition.
1061
+ * @param {Uint8Array} wav - canonical WAV bytes.
1062
+ * @param {AbortSignal} signal - caller cancellation.
1063
+ * @param {string} language - selected recognition language.
1064
+ * @returns {Promise<any>} decoded transcript response.
1065
+ */
1066
+ async transcribe(wav, signal, language) {
1067
+ const query = language ? '?language=' + encodeURIComponent(language) : '';
1068
+ return serviceJson(fetch, '/transcribe' + query, {
1069
+ method: 'POST',
1070
+ credentials: 'same-origin',
1071
+ headers: { 'content-type': 'audio/wav', accept: 'application/json' },
1072
+ body: wav,
1073
+ signal,
1074
+ });
1075
+ },
1076
+ };
1077
+
1078
+ /**
1079
+ * One live streaming relay session owned by the browser. The overlay runtime drives the
1080
+ * ~200 ms cadence through {@link flush}; chunks never overlap (a second flush while one is
1081
+ * in flight reuses the same promise), partials are cumulative and every request carries the
1082
+ * caller's abort signal. `fetchImpl` is injectable so the HTTP contract is unit-testable.
1083
+ */
1084
+ class StreamingSession {
1085
+ constructor(options) {
1086
+ const settings = options && typeof options === 'object' ? options : {};
1087
+ const providedFetch = typeof settings.fetchImpl === 'function' ? settings.fetchImpl : null;
1088
+ this.fetchImpl = providedFetch || ((url, init) => fetch(url, init));
1089
+ this.providerId = typeof settings.providerId === 'string' && settings.providerId !== '' ? settings.providerId : undefined;
1090
+ this.language = typeof settings.language === 'string' && settings.language !== '' ? settings.language : undefined;
1091
+ this.signal = settings.signal;
1092
+ this.onPartial = typeof settings.onPartial === 'function' ? settings.onPartial : undefined;
1093
+ this.maxChunkBytes = Number.isFinite(settings.maxChunkBytes) && settings.maxChunkBytes >= 2 ? settings.maxChunkBytes : MAX_STREAM_CHUNK_BYTES;
1094
+ this.sessionId = null;
1095
+ this.sampleRate = null;
1096
+ this.pending = new Uint8Array(0);
1097
+ this.opening = null;
1098
+ this.flushing = null;
1099
+ this.failed = false;
1100
+ this.cancelled = false;
1101
+ this.finished = false;
1102
+ this.bytesSent = 0;
1103
+ this.lastPartial = '';
1104
+ this.lastError = null;
1105
+ }
1106
+
1107
+ /** @returns {number} bytes captured but not yet accepted by `/stream/chunk`. */
1108
+ get pendingBytes() {
1109
+ return this.pending.length;
1110
+ }
1111
+
1112
+ /** @returns {Promise<any>} open the relay session once; later calls share the same promise. */
1113
+ start() {
1114
+ if (this.opening === null) this.opening = this.open();
1115
+ return this.opening;
1116
+ }
1117
+
1118
+ /** @returns {Promise<any>} the actual `/stream/start` request. */
1119
+ async open() {
1120
+ const body = {};
1121
+ if (this.providerId) body.providerId = this.providerId;
1122
+ if (this.language) body.language = this.language;
1123
+ const payload = await serviceJson(this.fetchImpl, '/stream/start', {
1124
+ method: 'POST',
1125
+ credentials: 'same-origin',
1126
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
1127
+ body: JSON.stringify(body),
1128
+ signal: this.signal,
1129
+ });
1130
+ if (!payload || typeof payload.sessionId !== 'string' || payload.sessionId === '') {
1131
+ throw new ServiceError('invalid-session', 'The streaming service returned no session id');
1132
+ }
1133
+ this.sessionId = payload.sessionId;
1134
+ this.sampleRate = Number.isFinite(payload.sampleRate) ? payload.sampleRate : null;
1135
+ return payload;
1136
+ }
1137
+
1138
+ /**
1139
+ * Buffer one PCM16LE chunk for the next flush. Buffering starts as soon as capture
1140
+ * starts, so audio spoken while `/stream/start` is still opening (a cold local model can
1141
+ * take a moment to wake) is not lost: once the session id arrives, `flush()` sends it.
1142
+ */
1143
+ enqueuePcm(pcm) {
1144
+ if (this.failed || this.cancelled || this.finished) return;
1145
+ if (!pcm || pcm.byteLength < 2) return;
1146
+ this.pending = concatBytes([this.pending, pcm]);
1147
+ }
1148
+
1149
+ /**
1150
+ * Send at most one queued chunk (the runtime calls this every ~200 ms). Never runs two
1151
+ * requests at once: calls made while a chunk is in flight share that request, and newly
1152
+ * buffered bytes wait for the next tick (or for `finish`).
1153
+ * @returns {Promise<string|null>} the partial after this chunk, or null when nothing was sent.
1154
+ */
1155
+ flush() {
1156
+ if (this.flushing) return this.flushing;
1157
+ if (!this.sessionId || this.failed || this.cancelled || this.finished) return Promise.resolve(null);
1158
+ if (this.pending.length < 2) return Promise.resolve(null);
1159
+ const split = splitStreamingChunk(this.pending, this.maxChunkBytes);
1160
+ if (split.chunk.length < 2) return Promise.resolve(null);
1161
+ this.pending = new Uint8Array(split.rest);
1162
+ const chunk = new Uint8Array(split.chunk);
1163
+ this.flushing = (async () => {
1164
+ try {
1165
+ const payload = await serviceJson(this.fetchImpl, '/stream/chunk?session=' + encodeURIComponent(this.sessionId), {
1166
+ method: 'POST',
1167
+ credentials: 'same-origin',
1168
+ headers: { 'content-type': 'application/octet-stream', accept: 'application/json' },
1169
+ body: chunk,
1170
+ signal: this.signal,
1171
+ });
1172
+ this.bytesSent += chunk.byteLength;
1173
+ const partial = payload && typeof payload.partial === 'string' ? payload.partial : this.lastPartial;
1174
+ this.lastPartial = partial;
1175
+ if (this.onPartial) {
1176
+ try {
1177
+ this.onPartial(partial);
1178
+ } catch {
1179
+ /* a broken listener must not break the relay */
1180
+ }
1181
+ }
1182
+ return partial;
1183
+ } catch (failure) {
1184
+ this.failed = true;
1185
+ this.lastError = failure;
1186
+ throw failure;
1187
+ } finally {
1188
+ this.flushing = null;
1189
+ }
1190
+ })();
1191
+ return this.flushing;
1192
+ }
1193
+
1194
+ /** @returns {Promise<void>} keep flushing until the buffer is empty. */
1195
+ async flushAll() {
1196
+ while (!this.failed && !this.cancelled && this.pending.length >= 2) {
1197
+ await this.flush();
1198
+ }
1199
+ }
1200
+
1201
+ /**
1202
+ * Flush the tail and close the relay session.
1203
+ * @returns {Promise<any>} the final `{ text, audioSeconds, inferenceSeconds }` payload.
1204
+ */
1205
+ async finish() {
1206
+ if (this.cancelled) throw new ServiceError('cancelled', 'The streaming session was cancelled');
1207
+ // A fast release can reach finish() while `/stream/start` is still in flight; waiting
1208
+ // here keeps the whole take (including the buffered pre-start audio) in the relay.
1209
+ if (this.opening !== null) await this.opening;
1210
+ await this.flushAll();
1211
+ if (this.failed) throw this.lastError || new ServiceError('stream-failed', 'The streaming session failed');
1212
+ if (this.finished) return { ok: true, text: this.lastPartial };
1213
+ if (!this.sessionId) throw new ServiceError('not-started', 'The streaming session was not started');
1214
+ const payload = await serviceJson(this.fetchImpl, '/stream/finish?session=' + encodeURIComponent(this.sessionId), {
1215
+ method: 'POST',
1216
+ credentials: 'same-origin',
1217
+ headers: { accept: 'application/json' },
1218
+ signal: this.signal,
1219
+ });
1220
+ this.finished = true;
1221
+ return payload;
1222
+ }
1223
+
1224
+ /** Abort and dispose the relay session (idempotent, best effort). */
1225
+ async cancel() {
1226
+ if (this.cancelled) return;
1227
+ this.cancelled = true;
1228
+ this.pending = new Uint8Array(0);
1229
+ // Cancelling while `/stream/start` is in flight must still close the host session.
1230
+ if (this.opening !== null) {
1231
+ try {
1232
+ await this.opening;
1233
+ } catch {
1234
+ return;
1235
+ }
1236
+ }
1237
+ const sessionId = this.sessionId;
1238
+ if (!sessionId || this.finished) return;
1239
+ try {
1240
+ await serviceJson(this.fetchImpl, '/stream/cancel?session=' + encodeURIComponent(sessionId), {
1241
+ method: 'POST',
1242
+ credentials: 'same-origin',
1243
+ headers: { accept: 'application/json' },
1244
+ });
1245
+ } catch {
1246
+ /* the host expires abandoned sessions on its own */
1247
+ }
1248
+ }
1249
+ }
1250
+
1251
+ /* ================================================================ */
1252
+ /* overlay + toast rendering */
1253
+ /* ================================================================ */
1254
+
1255
+ /** @returns {string} the overlay sub-state used for styling. */
1256
+ function overlayState(phase, armed) {
1257
+ if (phase === 'preparing') return 'preparing';
1258
+ if (phase === 'transcribing') return 'transcribing';
1259
+ if (phase === 'settling') return 'settling';
1260
+ if (phase === 'cancel' || armed) return 'cancel';
1261
+ return 'recording';
1262
+ }
1263
+
1264
+ function Waveform(props) {
1265
+ const { live, getLevel } = props;
1266
+ const barsRef = useRef([]);
1267
+ const historyRef = useRef(new Float32Array(WAVE_MAX_BARS));
1268
+ const [count, setCount] = useState(() => barCountFor(typeof innerWidth === 'number' ? innerWidth : 1024));
1269
+
1270
+ useEffect(() => {
1271
+ const onResize = () => setCount(barCountFor(typeof innerWidth === 'number' ? innerWidth : 1024));
1272
+ window.addEventListener('resize', onResize, { passive: true });
1273
+ return () => window.removeEventListener('resize', onResize);
1274
+ }, []);
1275
+
1276
+ useEffect(() => {
1277
+ if (!live) {
1278
+ for (let index = 0; index < barsRef.current.length; index += 1) {
1279
+ const element = barsRef.current[index];
1280
+ if (element) element.style.height = barHeight(0.06 + (index % 5) * 0.03) + 'px';
1281
+ }
1282
+ return undefined;
1283
+ }
1284
+ let frame = 0;
1285
+ const step = () => {
1286
+ const level = typeof getLevel === 'function' ? clamp(getLevel(), 0, 1) * 9 : 0;
1287
+ const history = historyRef.current;
1288
+ for (let index = history.length - 1; index > 0; index -= 1) history[index] = history[index - 1];
1289
+ history[0] = level;
1290
+ const visible = Math.min(count, history.length);
1291
+ for (let index = 0; index < barsRef.current.length; index += 1) {
1292
+ const element = barsRef.current[index];
1293
+ if (!element) continue;
1294
+ const sample = index < visible ? history[Math.floor(index * (history.length / Math.max(1, count)))] : 0;
1295
+ element.style.height = barHeight(Math.min(1, sample * 1.2)) + 'px';
1296
+ }
1297
+ frame = requestAnimationFrame(step);
1298
+ };
1299
+ frame = requestAnimationFrame(step);
1300
+ return () => cancelAnimationFrame(frame);
1301
+ }, [live, count, getLevel]);
1302
+
1303
+ const bars = [];
1304
+ for (let index = 0; index < count; index += 1) {
1305
+ bars.push(h('span', {
1306
+ key: index,
1307
+ className: 'bvi-bar',
1308
+ ref: (element) => { barsRef.current[index] = element; },
1309
+ }));
1310
+ }
1311
+ return h('div', { className: 'bvi-wave', 'data-live': live ? 'true' : 'false', 'aria-hidden': 'true' }, bars);
1312
+ }
1313
+
1314
+ function Overlay(props) {
1315
+ const { phase, armed, progress, statusText, liveText, live, getLevel, onCancel, cancelLabel } = props;
1316
+ const state = overlayState(phase, armed);
1317
+ const showLive = Boolean(liveText) && (state === 'recording' || state === 'cancel');
1318
+ const layer = h('div', { className: OVERLAY_CLASS, 'data-state': state, role: 'dialog', 'aria-modal': 'true', 'aria-live': 'polite', 'aria-label': statusText },
1319
+ h('div', { className: 'bvi-overlay__blue', 'aria-hidden': 'true' }),
1320
+ h('div', { className: 'bvi-overlay__red', 'aria-hidden': 'true' }),
1321
+ h('div', { className: 'bvi-overlay__vignette', 'aria-hidden': 'true' }),
1322
+ h('div', { className: 'bvi-status' }, statusText),
1323
+ phase === 'preparing'
1324
+ ? h('div', { className: 'bvi-progress', 'aria-hidden': 'true' },
1325
+ h('div', { className: 'bvi-progress__track' }, h('div', { className: 'bvi-progress__fill', style: { width: (progress ?? 0) + '%' } })),
1326
+ typeof progress === 'number' ? h('div', { className: 'bvi-progress__label' }, progress + '%') : null)
1327
+ : null,
1328
+ h('div', { className: 'bvi-live', 'data-visible': showLive ? 'true' : 'false', 'aria-hidden': 'true' },
1329
+ showLive ? h('div', { className: 'bvi-live__text' }, liveText) : null),
1330
+ h(Waveform, { live, getLevel }),
1331
+ onCancel
1332
+ ? h('button', { type: 'button', className: 'bvi-cancel', onClick: onCancel }, cancelLabel)
1333
+ : null);
1334
+ return createPortal(layer, document.body);
1335
+ }
1336
+
1337
+ function ToastLayer(props) {
1338
+ const { toast } = props;
1339
+ if (!toast) return null;
1340
+ return createPortal(
1341
+ h('div', { className: 'bvi-toast', 'data-tone': toast.tone || 'info', role: 'status', 'aria-live': 'polite' }, toast.text),
1342
+ document.body,
1343
+ );
1344
+ }
1345
+
1346
+ /* ================================================================ */
1347
+ /* composer glue */
1348
+ /* ================================================================ */
1349
+
1350
+ /** @returns {boolean} whether the platform asks for reduced motion. */
1351
+ function prefersReducedMotion() {
1352
+ try {
1353
+ if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return false;
1354
+ const query = window.matchMedia('(prefers-reduced-motion: reduce)');
1355
+ return Boolean(query && query.matches === true);
1356
+ } catch {
1357
+ return false;
1358
+ }
1359
+ }
1360
+
1361
+ /**
1362
+ * One runtime owns every effect of one composer occurrence: gesture listeners, keyboard
1363
+ * shortcut, capture (batch or live PCM), HTTP, timers, the final-line flight and the
1364
+ * placeholder hint. React only re-renders the overlay and toast; the waveform updates
1365
+ * through DOM refs and live partials re-render through `setView`.
1366
+ */
1367
+ function createRuntime(deps) {
1368
+ const { propsRef, setView, setToast } = deps;
1369
+ const controller = {
1370
+ card: null,
1371
+ anchor: null,
1372
+ hintObserver: null,
1373
+ placeholderOriginal: null,
1374
+ disposed: false,
1375
+ finishing: false,
1376
+ generation: 0,
1377
+ pointerType: 'mouse',
1378
+ span: undefined,
1379
+ recordingStartedAt: 0,
1380
+ preferences: readPreferences(null),
1381
+ limits: readLimits(null),
1382
+ useStreaming: false,
1383
+ guardHintShown: false,
1384
+ releaseAnchorRect: null,
1385
+ };
1386
+ let hold = holdStart();
1387
+ let holdTimer = 0;
1388
+ let capture = null;
1389
+ let live = null;
1390
+ let streamSession = null;
1391
+ let streamTimer = 0;
1392
+ let streamBroken = false;
1393
+ let recordParts = [];
1394
+ let recordBytes = 0;
1395
+ let recordLimit = 0;
1396
+ let abort = null;
1397
+ let preparePoll = 0;
1398
+ let maxTimer = 0;
1399
+ let toastTimer = 0;
1400
+ let guardTimer = 0;
1401
+ let guardCandidate = false;
1402
+ let keyHeld = false;
1403
+ let shortcutCode = '';
1404
+ let liveText = '';
1405
+ let flightCancel = null;
1406
+ let busy = false;
1407
+ let pointerDown = false;
1408
+ let stopRequested = false;
1409
+ let hintText = '';
1410
+
1411
+ const translate = () => (propsRef.current && typeof propsRef.current.t === 'function' ? propsRef.current.t : (key) => key);
1412
+ const t = (key, params) => {
1413
+ let text = String(translate()(key));
1414
+ if (params) {
1415
+ for (const name of Object.keys(params)) text = text.split('{' + name + '}').join(String(params[name]));
1416
+ }
1417
+ if (text === key) text = String((zh[key] ?? en[key] ?? key));
1418
+ return text;
1419
+ };
1420
+
1421
+ function safeSetView(next) {
1422
+ if (!controller.disposed) setView(next);
1423
+ }
1424
+
1425
+ function showToast(text, tone) {
1426
+ if (controller.disposed) return;
1427
+ if (toastTimer) clearTimeout(toastTimer);
1428
+ setToast({ text, tone: tone || 'info', at: Date.now() });
1429
+ toastTimer = setTimeout(() => {
1430
+ toastTimer = 0;
1431
+ setToast(null);
1432
+ }, TOAST_MS);
1433
+ }
1434
+
1435
+ function releaseView() {
1436
+ liveText = '';
1437
+ controller.releaseAnchorRect = null;
1438
+ safeSetView({ visible: false, phase: 'idle', armed: false, progress: null, action: 'insert', statusText: '', cancelLabel: '', hint: '', liveText: '', onCancel: undefined });
1439
+ }
1440
+
1441
+ /** Merge a new live partial into the overlay without rebuilding the whole view. */
1442
+ function setLiveText(value) {
1443
+ const text = trimLiveText(value);
1444
+ if (text === liveText || controller.disposed) return;
1445
+ liveText = text;
1446
+ try {
1447
+ setView((previous) => ({ ...(previous && typeof previous === 'object' ? previous : {}), liveText }));
1448
+ } catch {
1449
+ /* a stale React setter while unmounting is harmless */
1450
+ }
1451
+ }
1452
+
1453
+ function recordingStatusText() {
1454
+ const send = controller.preferences.releaseAction === 'send';
1455
+ if (controller.pointerType === 'keyboard') return t(send ? 'status.sendKeyboard' : 'status.insertKeyboard');
1456
+ return t(send ? 'status.send' : 'status.insert');
1457
+ }
1458
+
1459
+ function overlayFor(phase, armed, progress) {
1460
+ const prefs = controller.preferences;
1461
+ let statusText = '';
1462
+ if (phase === 'cancel' || armed) statusText = t('status.cancel');
1463
+ else if (phase === 'recording') statusText = recordingStatusText();
1464
+ else if (phase === 'preparing') statusText = t('status.preparing');
1465
+ else if (phase === 'transcribing') statusText = t('status.transcribing');
1466
+ const cancelLabel = phase === 'preparing' ? t('cancelPrepare') : phase === 'transcribing' ? t('cancelTranscribe') : '';
1467
+ safeSetView({
1468
+ visible: true,
1469
+ phase: phase === 'cancel' ? 'cancel' : phase,
1470
+ armed: Boolean(armed),
1471
+ progress: typeof progress === 'number' ? Math.round(progress) : null,
1472
+ action: prefs.releaseAction,
1473
+ statusText,
1474
+ cancelLabel,
1475
+ hint: phase === 'preparing' ? t('preparing.hint') : '',
1476
+ liveText,
1477
+ onCancel: phase === 'preparing' || phase === 'transcribing' ? cancelCurrent : undefined,
1478
+ });
1479
+ }
1480
+
1481
+ function editor() {
1482
+ return controller.card ? controller.card.querySelector('[data-composer-input]') : null;
1483
+ }
1484
+
1485
+ function focusEditor() {
1486
+ const element = editor();
1487
+ if (element && typeof element.focus === 'function') {
1488
+ try {
1489
+ element.focus({ preventScroll: true });
1490
+ } catch {
1491
+ /* focusing is best effort */
1492
+ }
1493
+ }
1494
+ }
1495
+
1496
+ function editorFocused() {
1497
+ const element = editor();
1498
+ return Boolean(element && typeof document !== 'undefined' && document.activeElement === element);
1499
+ }
1500
+
1501
+ function keyboardOpen() {
1502
+ const viewport = typeof window !== 'undefined' ? window.visualViewport : undefined;
1503
+ const viewportHeight = viewport && Number.isFinite(viewport.height) ? viewport.height : undefined;
1504
+ const windowHeight = typeof window !== 'undefined' && Number.isFinite(window.innerHeight) ? window.innerHeight : undefined;
1505
+ return isVirtualKeyboardOpen(viewportHeight, windowHeight);
1506
+ }
1507
+
1508
+ function shortcutTargetFlags() {
1509
+ const active = typeof document !== 'undefined' ? document.activeElement : null;
1510
+ const element = editor();
1511
+ const card = controller.card;
1512
+ const body = typeof document !== 'undefined' ? document.body : null;
1513
+ const root = typeof document !== 'undefined' ? document.documentElement : null;
1514
+ return {
1515
+ hasComposer: Boolean(card),
1516
+ activeIsComposer: Boolean(active && element && (active === element || (typeof element.contains === 'function' && element.contains(active)))),
1517
+ activeIsCard: Boolean(active && card && active === card),
1518
+ activeIsBody: !active || active === body || Boolean(root && active === root),
1519
+ };
1520
+ }
1521
+
1522
+ function triggerActive() {
1523
+ return pointerDown || keyHeld;
1524
+ }
1525
+
1526
+ function setHolding(on) {
1527
+ if (!controller.card) return;
1528
+ controller.card.classList.toggle(HOLD_CLASS, on);
1529
+ }
1530
+
1531
+ function clearTimers() {
1532
+ if (holdTimer) { clearTimeout(holdTimer); holdTimer = 0; }
1533
+ if (maxTimer) { clearTimeout(maxTimer); maxTimer = 0; }
1534
+ if (preparePoll) { clearTimeout(preparePoll); preparePoll = 0; }
1535
+ if (streamTimer) { clearInterval(streamTimer); streamTimer = 0; }
1536
+ if (guardTimer) { clearTimeout(guardTimer); guardTimer = 0; }
1537
+ }
1538
+
1539
+ function abortInFlight() {
1540
+ if (abort) { abort.abort(); abort = null; }
1541
+ }
1542
+
1543
+ function disposeCapture() {
1544
+ const current = capture;
1545
+ capture = null;
1546
+ if (current) void current.dispose().catch(() => undefined);
1547
+ }
1548
+
1549
+ function disposeLive() {
1550
+ const current = live;
1551
+ live = null;
1552
+ if (current) void current.dispose().catch(() => undefined);
1553
+ }
1554
+
1555
+ function cancelFlight() {
1556
+ const cancel = flightCancel;
1557
+ flightCancel = null;
1558
+ if (typeof cancel === 'function') cancel();
1559
+ }
1560
+
1561
+ /** Release every live-streaming resource (session first so `/stream/cancel` is not aborted). */
1562
+ function resetStreamingTake() {
1563
+ if (streamTimer) { clearInterval(streamTimer); streamTimer = 0; }
1564
+ const session = streamSession;
1565
+ streamSession = null;
1566
+ if (session) void session.cancel().catch(() => undefined);
1567
+ disposeLive();
1568
+ recordParts = [];
1569
+ recordBytes = 0;
1570
+ recordLimit = 0;
1571
+ streamBroken = false;
1572
+ controller.useStreaming = false;
1573
+ }
1574
+
1575
+ function clearGuardHint() {
1576
+ guardCandidate = false;
1577
+ if (guardTimer) { clearTimeout(guardTimer); guardTimer = 0; }
1578
+ }
1579
+
1580
+ /** Show the one-time keyboard guard hint when a touch long-press is deliberately ignored. */
1581
+ function scheduleGuardHint() {
1582
+ if (controller.guardHintShown || guardCandidate || controller.disposed) return;
1583
+ guardCandidate = true;
1584
+ guardTimer = setTimeout(() => {
1585
+ guardTimer = 0;
1586
+ if (!guardCandidate || controller.disposed) return;
1587
+ guardCandidate = false;
1588
+ controller.guardHintShown = true;
1589
+ showToast(t('feedback.keyboardGuard'));
1590
+ }, controller.preferences.holdDelayMs);
1591
+ }
1592
+
1593
+ /** @returns {Promise<void>} cancel the current operation without transcribing. */
1594
+ async function cancelCurrent(options) {
1595
+ const silent = Boolean(options && options.silent);
1596
+ controller.generation += 1;
1597
+ if (typeof controller.disposePrepare === 'function') {
1598
+ controller.disposePrepare();
1599
+ controller.disposePrepare = undefined;
1600
+ }
1601
+ resetStreamingTake();
1602
+ abortInFlight();
1603
+ clearTimers();
1604
+ disposeCapture();
1605
+ cancelFlight();
1606
+ clearGuardHint();
1607
+ keyHeld = false;
1608
+ pointerDown = false;
1609
+ busy = false;
1610
+ controller.finishing = false;
1611
+ stopRequested = false;
1612
+ hold = holdStart();
1613
+ setHolding(false);
1614
+ releaseView();
1615
+ if (!silent) {
1616
+ const state = service.stateCache;
1617
+ const providerId = state && state.selection ? state.selection.providerId : undefined;
1618
+ if (state && providerId && state.local && Array.isArray(state.local)) {
1619
+ const local = state.local.find((entry) => entry.id === providerId);
1620
+ if (local && local.install && local.install.phase === 'preparing') {
1621
+ void service.post('/cancel-preparation', { providerId }).catch(() => undefined);
1622
+ }
1623
+ }
1624
+ }
1625
+ }
1626
+
1627
+ /** @returns {Promise<boolean>} whether the selected provider can recognize right now. */
1628
+ async function ensureReady(state) {
1629
+ const providerId = state && state.selection ? state.selection.providerId : undefined;
1630
+ const provider = state && Array.isArray(state.providers) ? state.providers.find((entry) => entry.id === providerId) : undefined;
1631
+ if (!provider) {
1632
+ showToast(t('feedback.noProvider'), 'error');
1633
+ return false;
1634
+ }
1635
+ const phase = provider.preparation && typeof provider.preparation.phase === 'string' ? provider.preparation.phase : 'ready';
1636
+ if (phase === 'ready' || phase === 'standby' || phase === 'waking') return true;
1637
+ if (phase === 'preparing') {
1638
+ showToast(t('feedback.preparing'));
1639
+ return false;
1640
+ }
1641
+ busy = true;
1642
+ overlayFor('preparing', false, 0);
1643
+ try {
1644
+ await service.post('/prepare', { providerId });
1645
+ } catch (failure) {
1646
+ busy = false;
1647
+ releaseView();
1648
+ showToast(t('feedback.prepareFailed', { message: failure && failure.message ? failure.message : String(failure) }), 'error');
1649
+ return false;
1650
+ }
1651
+ return await new Promise((resolve) => {
1652
+ const poll = async () => {
1653
+ preparePoll = 0;
1654
+ const latest = await service.state(true);
1655
+ const current = latest && Array.isArray(latest.providers) ? latest.providers.find((entry) => entry.id === providerId) : undefined;
1656
+ const currentPhase = current && current.preparation ? current.preparation.phase : 'ready';
1657
+ const progress = current && current.preparation && Number.isFinite(current.preparation.progress) ? current.preparation.progress : 0;
1658
+ if (currentPhase === 'ready' || currentPhase === 'standby' || currentPhase === 'waking') {
1659
+ busy = false;
1660
+ releaseView();
1661
+ showToast(t('feedback.ready'));
1662
+ resolve(true);
1663
+ return;
1664
+ }
1665
+ if (currentPhase === 'failed' || currentPhase === 'cancelled') {
1666
+ busy = false;
1667
+ releaseView();
1668
+ showToast(t('feedback.prepareFailed', { message: (current.preparation && current.preparation.error) || currentPhase }), 'error');
1669
+ resolve(false);
1670
+ return;
1671
+ }
1672
+ overlayFor('preparing', false, progress);
1673
+ preparePoll = setTimeout(() => { void poll(); }, PREPARE_POLL_MS);
1674
+ };
1675
+ void poll();
1676
+ controller.disposePrepare = () => {
1677
+ clearTimeout(preparePoll);
1678
+ preparePoll = 0;
1679
+ busy = false;
1680
+ resolve(false);
1681
+ };
1682
+ });
1683
+ }
1684
+
1685
+ function startMaxTimer() {
1686
+ if (maxTimer) clearTimeout(maxTimer);
1687
+ const seconds = controller.limits.maxDurationSeconds;
1688
+ maxTimer = setTimeout(() => {
1689
+ maxTimer = 0;
1690
+ if (hold.phase === 'recording' || hold.phase === 'cancel') void finish();
1691
+ }, Math.max(1000, seconds * 1000));
1692
+ }
1693
+
1694
+ /** @returns {string} the localized microphone failure sentence. */
1695
+ function microphoneFailureMessage(kind, failure) {
1696
+ if (kind === 'permission') return t('feedback.permission');
1697
+ if (kind === 'deviceMissing') return t('feedback.deviceMissing');
1698
+ return t('feedback.microphone', { message: failure && failure.message ? failure.message : String(failure) });
1699
+ }
1700
+
1701
+ async function startBatchCapture() {
1702
+ capture = new MicrophoneCapture();
1703
+ try {
1704
+ await capture.start(() => {
1705
+ showToast(t('feedback.recordingFailed', { message: 'device interrupted' }), 'error');
1706
+ void cancelCurrent({ silent: true });
1707
+ });
1708
+ } catch (failure) {
1709
+ busy = false;
1710
+ disposeCapture();
1711
+ setHolding(false);
1712
+ releaseView();
1713
+ if (failure && failure.kind === 'cancelled') return false;
1714
+ const kind = failure && failure.kind ? failure.kind : 'unavailable';
1715
+ showToast(microphoneFailureMessage(kind, failure), 'error');
1716
+ return false;
1717
+ }
1718
+ return true;
1719
+ }
1720
+
1721
+ async function startStreamingCapture() {
1722
+ const captureInstance = new LivePcmCapture();
1723
+ live = captureInstance;
1724
+ try {
1725
+ await captureInstance.start(
1726
+ () => {
1727
+ showToast(t('feedback.recordingFailed', { message: 'device interrupted' }), 'error');
1728
+ void cancelCurrent({ silent: true });
1729
+ },
1730
+ handleLiveFrames,
1731
+ );
1732
+ } catch (failure) {
1733
+ busy = false;
1734
+ resetStreamingTake();
1735
+ setHolding(false);
1736
+ releaseView();
1737
+ if (failure && failure.kind === 'cancelled') return false;
1738
+ const kind = failure && failure.kind ? failure.kind : 'unavailable';
1739
+ showToast(microphoneFailureMessage(kind, failure), 'error');
1740
+ return false;
1741
+ }
1742
+ recordParts = [];
1743
+ recordBytes = 0;
1744
+ recordLimit = controller.limits.maxAudioBytes;
1745
+ streamBroken = false;
1746
+ abort = new AbortController();
1747
+ const state = service.stateCache;
1748
+ const providerId = state && state.selection ? state.selection.providerId : undefined;
1749
+ const language = state && state.selection && typeof state.selection.language === 'string' ? state.selection.language : 'auto';
1750
+ const session = new StreamingSession({
1751
+ providerId: typeof providerId === 'string' ? providerId : undefined,
1752
+ language,
1753
+ signal: abort.signal,
1754
+ onPartial: handleStreamingPartial,
1755
+ });
1756
+ streamSession = session;
1757
+ try {
1758
+ await session.start();
1759
+ } catch (failure) {
1760
+ if (streamSession === session) streamSession = null;
1761
+ streamBroken = true;
1762
+ if (isAbort(failure) || controller.disposed) return true;
1763
+ showToast(t('feedback.streamFallback'));
1764
+ return true;
1765
+ }
1766
+ // A release/cancel may land while the session was opening; the finish/cancel path
1767
+ // already owns the teardown, so do not start pumping a relay nobody is listening to.
1768
+ if (controller.disposed || controller.finishing || streamSession !== session) return true;
1769
+ setLiveText(t('status.streaming'));
1770
+ streamTimer = setInterval(() => { void pumpStreamChunk(); }, STREAM_CHUNK_MS);
1771
+ return true;
1772
+ }
1773
+
1774
+ /** Convert one worklet block to 16 kHz PCM16, keep it for the batch fallback and relay it. */
1775
+ function handleLiveFrames(samples, sampleRate) {
1776
+ if (controller.disposed || !live) return;
1777
+ const pcm = floatToPcm16(downsampleTo16k(samples, sampleRate));
1778
+ if (pcm.byteLength === 0) return;
1779
+ if (recordLimit <= 0 || recordBytes + pcm.byteLength <= recordLimit) {
1780
+ recordParts.push(pcm);
1781
+ recordBytes += pcm.byteLength;
1782
+ }
1783
+ if (streamSession && !streamBroken) streamSession.enqueuePcm(pcm);
1784
+ }
1785
+
1786
+ function handleStreamingPartial(partial) {
1787
+ if (controller.disposed || !streamSession) return;
1788
+ const text = typeof partial === 'string' ? partial : '';
1789
+ if (text === '') return;
1790
+ setLiveText(text);
1791
+ }
1792
+
1793
+ async function pumpStreamChunk() {
1794
+ const session = streamSession;
1795
+ if (!session || streamBroken || controller.disposed) return;
1796
+ try {
1797
+ await session.flush();
1798
+ } catch (failure) {
1799
+ handleStreamFailure(failure);
1800
+ }
1801
+ }
1802
+
1803
+ /** A broken relay keeps the recording: the take is transcribed as one WAV at release. */
1804
+ function handleStreamFailure(failure) {
1805
+ if (streamBroken || controller.disposed) return;
1806
+ streamBroken = true;
1807
+ if (streamTimer) { clearInterval(streamTimer); streamTimer = 0; }
1808
+ const session = streamSession;
1809
+ streamSession = null;
1810
+ if (session) void session.cancel().catch(() => undefined);
1811
+ setLiveText('');
1812
+ if (!isAbort(failure)) showToast(t('feedback.streamFallback'));
1813
+ }
1814
+
1815
+ /** @returns {Promise<string>} transcribe the locally kept PCM16 as one canonical WAV. */
1816
+ async function transcribeRecordedPcm() {
1817
+ const pcm = concatBytes(recordParts, recordBytes);
1818
+ if (pcm.byteLength < 2) throw new ServiceError('empty-audio', 'No audio was captured');
1819
+ const wav = encodeWavFromPcm16(pcm);
1820
+ if (wav.byteLength > controller.limits.maxAudioBytes) throw new ServiceError('too-large', 'Recording too large');
1821
+ const state = service.stateCache;
1822
+ const language = state && state.selection && typeof state.selection.language === 'string' ? state.selection.language : 'auto';
1823
+ const payload = await service.transcribe(wav, abort ? abort.signal : undefined, language);
1824
+ return typeof payload.text === 'string' ? payload.text.trim() : '';
1825
+ }
1826
+
1827
+ async function startRecording(useStreaming) {
1828
+ if (busy || controller.disposed) return;
1829
+ const inputActions = propsRef.current && propsRef.current.inputActions;
1830
+ const span = inputActions && typeof inputActions.captureInsertion === 'function' ? inputActions.captureInsertion() : undefined;
1831
+ controller.span = span;
1832
+ controller.recordingStartedAt = now();
1833
+ busy = true;
1834
+ stopRequested = false;
1835
+ setHolding(true);
1836
+ try { editor()?.blur?.(); } catch { /* optional */ }
1837
+ overlayFor('recording', false, 0);
1838
+ const started = useStreaming === true ? await startStreamingCapture() : await startBatchCapture();
1839
+ if (!started) return;
1840
+ if (stopRequested) {
1841
+ stopRequested = false;
1842
+ if (now() - controller.recordingStartedAt < MIN_RECORDING_MS) {
1843
+ void cancelCurrent({ silent: true });
1844
+ showToast(t('feedback.tooShort'));
1845
+ return;
1846
+ }
1847
+ void finish();
1848
+ return;
1849
+ }
1850
+ if (controller.disposed || (hold.phase !== 'recording' && hold.phase !== 'cancel')) {
1851
+ void cancelCurrent({ silent: true });
1852
+ return;
1853
+ }
1854
+ startMaxTimer();
1855
+ overlayFor(hold.phase === 'cancel' ? 'cancel' : 'recording', hold.phase === 'cancel', 0);
1856
+ }
1857
+
1858
+ async function finish() {
1859
+ if (controller.finishing) return;
1860
+ const streamingMode = controller.useStreaming === true;
1861
+ if (!streamingMode && !capture) {
1862
+ busy = false;
1863
+ releaseView();
1864
+ return;
1865
+ }
1866
+ if (streamingMode && !live) {
1867
+ busy = false;
1868
+ releaseView();
1869
+ return;
1870
+ }
1871
+ controller.finishing = true;
1872
+ const generation = controller.generation;
1873
+ const inputActions = propsRef.current && propsRef.current.inputActions;
1874
+ const span = controller.span;
1875
+ const startedAt = controller.recordingStartedAt;
1876
+ // Snapshot where the live line sits before the overlay switches to `transcribing`;
1877
+ // the flight clone must start from the text the user was just reading.
1878
+ controller.releaseAnchorRect = overlayAnchorRect();
1879
+ setHolding(false);
1880
+ clearTimers();
1881
+ if (streamingMode) {
1882
+ await finishStreamingTake(generation, startedAt, inputActions, span);
1883
+ return;
1884
+ }
1885
+ await finishBatchTake(generation, startedAt, inputActions, span);
1886
+ }
1887
+
1888
+ async function finishBatchTake(generation, startedAt, inputActions, span) {
1889
+ abort = new AbortController();
1890
+ overlayFor('transcribing', false, 0);
1891
+ let bytes;
1892
+ try {
1893
+ bytes = await capture.stop(controller.limits.maxDurationSeconds);
1894
+ } catch (failure) {
1895
+ busy = false;
1896
+ controller.finishing = false;
1897
+ disposeCapture();
1898
+ releaseView();
1899
+ const kind = failure && failure.kind ? failure.kind : 'unknown';
1900
+ if (kind === 'cancelled') return;
1901
+ showToast(t('feedback.recordingFailed', { message: failure && failure.message ? failure.message : String(failure) }), 'error');
1902
+ return;
1903
+ }
1904
+ disposeCapture();
1905
+ if (controller.disposed || generation !== controller.generation) return;
1906
+ if (!bytes || bytes.byteLength <= 44) {
1907
+ busy = false;
1908
+ controller.finishing = false;
1909
+ releaseView();
1910
+ showToast(t('feedback.tooShort'));
1911
+ return;
1912
+ }
1913
+ if (bytes.byteLength > controller.limits.maxAudioBytes) {
1914
+ busy = false;
1915
+ controller.finishing = false;
1916
+ releaseView();
1917
+ showToast(t('feedback.tooLarge'), 'error');
1918
+ return;
1919
+ }
1920
+ if (now() - startedAt < MIN_RECORDING_MS) {
1921
+ busy = false;
1922
+ controller.finishing = false;
1923
+ releaseView();
1924
+ showToast(t('feedback.tooShort'));
1925
+ return;
1926
+ }
1927
+ let payload;
1928
+ try {
1929
+ const state = service.stateCache;
1930
+ const language = state && state.selection && typeof state.selection.language === 'string' ? state.selection.language : 'auto';
1931
+ payload = await service.transcribe(bytes, abort.signal, language);
1932
+ } catch (failure) {
1933
+ busy = false;
1934
+ controller.finishing = false;
1935
+ releaseView();
1936
+ if (isAbort(failure)) return;
1937
+ showToast(t('feedback.failed', { message: failure && failure.message ? failure.message : String(failure) }), 'error');
1938
+ return;
1939
+ } finally {
1940
+ abort = null;
1941
+ }
1942
+ if (controller.disposed || generation !== controller.generation) return;
1943
+ const text = typeof payload.text === 'string' ? payload.text.trim() : '';
1944
+ if (text === '') {
1945
+ busy = false;
1946
+ controller.finishing = false;
1947
+ releaseView();
1948
+ showToast(t('feedback.empty'));
1949
+ return;
1950
+ }
1951
+ await deliverTranscript(text, generation, inputActions, span, false);
1952
+ }
1953
+
1954
+ async function finishStreamingTake(generation, startedAt, inputActions, span) {
1955
+ const session = streamSession;
1956
+ if (now() - startedAt < MIN_RECORDING_MS) {
1957
+ resetStreamingTake();
1958
+ busy = false;
1959
+ controller.finishing = false;
1960
+ releaseView();
1961
+ showToast(t('feedback.tooShort'));
1962
+ return;
1963
+ }
1964
+ overlayFor('transcribing', false, 0);
1965
+ // Cut the microphone now: the relay only needs the frames captured during the hold.
1966
+ disposeLive();
1967
+ let text;
1968
+ try {
1969
+ if (session && !streamBroken) {
1970
+ const payload = await session.finish();
1971
+ text = typeof payload.text === 'string' ? payload.text.trim() : '';
1972
+ } else {
1973
+ text = await transcribeRecordedPcm();
1974
+ }
1975
+ } catch (failure) {
1976
+ if (isAbort(failure) || controller.disposed || generation !== controller.generation) {
1977
+ resetStreamingTake();
1978
+ if (controller.disposed || generation !== controller.generation) return;
1979
+ busy = false;
1980
+ controller.finishing = false;
1981
+ releaseView();
1982
+ return;
1983
+ }
1984
+ try {
1985
+ text = await transcribeRecordedPcm();
1986
+ } catch (fallbackFailure) {
1987
+ resetStreamingTake();
1988
+ busy = false;
1989
+ controller.finishing = false;
1990
+ releaseView();
1991
+ const code = fallbackFailure && fallbackFailure.code;
1992
+ if (code === 'too-large') showToast(t('feedback.tooLarge'), 'error');
1993
+ else if (code === 'empty-audio') showToast(t('feedback.tooShort'));
1994
+ else showToast(t('feedback.failed', { message: fallbackFailure && fallbackFailure.message ? fallbackFailure.message : String(fallbackFailure) }), 'error');
1995
+ return;
1996
+ }
1997
+ } finally {
1998
+ abort = null;
1999
+ }
2000
+ resetStreamingTake();
2001
+ if (controller.disposed || generation !== controller.generation) return;
2002
+ if (typeof text !== 'string' || text === '') {
2003
+ busy = false;
2004
+ controller.finishing = false;
2005
+ releaseView();
2006
+ showToast(t('feedback.empty'));
2007
+ return;
2008
+ }
2009
+ await deliverTranscript(text, generation, inputActions, span, true);
2010
+ }
2011
+
2012
+ async function deliverTranscript(text, generation, inputActions, span, withFlight) {
2013
+ if (generation !== controller.generation) return;
2014
+ if (withFlight) {
2015
+ const plan = planFlight({
2016
+ text,
2017
+ from: controller.releaseAnchorRect || overlayAnchorRect(),
2018
+ to: composerTargetRect(),
2019
+ reducedMotion: prefersReducedMotion(),
2020
+ });
2021
+ if (plan) {
2022
+ overlayFor('settling', false, 0);
2023
+ const completed = await playFlight(plan);
2024
+ if (!completed || controller.disposed || generation !== controller.generation) return;
2025
+ }
2026
+ }
2027
+ busy = false;
2028
+ controller.finishing = false;
2029
+ releaseView();
2030
+ if (generation !== controller.generation) return;
2031
+ const inserted = tryInsert(inputActions, text, span);
2032
+ if (inserted === 'failed') {
2033
+ showToast(t('feedback.conflict'), 'error');
2034
+ return;
2035
+ }
2036
+ if (controller.preferences.releaseAction === 'send') {
2037
+ await new Promise((resolve) => setTimeout(resolve, 0));
2038
+ try {
2039
+ if (inputActions && typeof inputActions.submit === 'function') inputActions.submit();
2040
+ } catch (failure) {
2041
+ showToast(t('feedback.failed', { message: failure && failure.message ? failure.message : String(failure) }), 'error');
2042
+ }
2043
+ }
2044
+ // Touch users expect the keyboard to stay hidden, like the App; a missed
2045
+ // insertion is a hard error, so mouse/keyboard users get the caret back.
2046
+ if (controller.pointerType !== 'touch') focusEditor();
2047
+ }
2048
+
2049
+ /**
2050
+ * Insert the transcript through the public input actions.
2051
+ * @returns {'inserted'|'fallback'|'failed'} outcome used for the follow-up behavior.
2052
+ */
2053
+ function tryInsert(inputActions, text, span) {
2054
+ if (!inputActions || typeof inputActions.insertText !== 'function') return 'failed';
2055
+ try {
2056
+ if (span !== undefined && inputActions.insertText(text, span)) return 'inserted';
2057
+ const fresh = typeof inputActions.captureInsertion === 'function' ? inputActions.captureInsertion() : undefined;
2058
+ if (fresh !== undefined && inputActions.insertText(text, fresh)) return 'inserted';
2059
+ } catch {
2060
+ /* fall through to the whole-draft fallback */
2061
+ }
2062
+ const draft = propsRef.current && typeof propsRef.current.getDraft === 'function' ? propsRef.current.getDraft() : '';
2063
+ try {
2064
+ if (typeof inputActions.setDraft === 'function') {
2065
+ inputActions.setDraft((draft ? draft + ' ' : '') + text);
2066
+ return 'fallback';
2067
+ }
2068
+ } catch {
2069
+ /* a rejected fallback is reported to the user */
2070
+ }
2071
+ return 'failed';
2072
+ }
2073
+
2074
+ function overlayAnchorRect() {
2075
+ if (typeof document === 'undefined' || typeof document.querySelector !== 'function') return null;
2076
+ const selectors = ['.bvi-overlay .bvi-live__text', '.bvi-overlay .bvi-live', '.bvi-overlay .bvi-status'];
2077
+ for (const selector of selectors) {
2078
+ let element;
2079
+ try {
2080
+ element = document.querySelector(selector);
2081
+ } catch {
2082
+ element = null;
2083
+ }
2084
+ if (!element || typeof element.getBoundingClientRect !== 'function') continue;
2085
+ const rect = usableRect(element.getBoundingClientRect());
2086
+ if (rect) return rect;
2087
+ }
2088
+ return null;
2089
+ }
2090
+
2091
+ function composerTargetRect() {
2092
+ const element = editor() || controller.card;
2093
+ if (!element || typeof element.getBoundingClientRect !== 'function') return null;
2094
+ return usableRect(element.getBoundingClientRect());
2095
+ }
2096
+
2097
+ /** Pin the final-line clone over the overlay and transform it onto the composer target. */
2098
+ function playFlight(plan) {
2099
+ return new Promise((resolve) => {
2100
+ if (!plan || controller.disposed || typeof document === 'undefined' || !document.body || typeof document.createElement !== 'function') {
2101
+ resolve(false);
2102
+ return;
2103
+ }
2104
+ let node;
2105
+ try {
2106
+ node = document.createElement('div');
2107
+ } catch {
2108
+ resolve(false);
2109
+ return;
2110
+ }
2111
+ node.className = 'bvi-flight';
2112
+ if (typeof node.setAttribute === 'function') node.setAttribute('aria-hidden', 'true');
2113
+ node.textContent = plan.text;
2114
+ node.style.position = 'fixed';
2115
+ node.style.left = plan.left + 'px';
2116
+ node.style.top = plan.top + 'px';
2117
+ node.style.width = plan.width + 'px';
2118
+ node.style.opacity = '1';
2119
+ let settled = false;
2120
+ let timer = 0;
2121
+ const settle = (completed) => {
2122
+ if (settled) return;
2123
+ settled = true;
2124
+ if (timer) { clearTimeout(timer); timer = 0; }
2125
+ flightCancel = null;
2126
+ try {
2127
+ if (typeof node.remove === 'function') node.remove();
2128
+ else if (node.parentNode && typeof node.parentNode.removeChild === 'function') node.parentNode.removeChild(node);
2129
+ } catch {
2130
+ /* the clone may already be detached */
2131
+ }
2132
+ resolve(completed);
2133
+ };
2134
+ const cancel = () => settle(false);
2135
+ flightCancel = cancel;
2136
+ try {
2137
+ document.body.appendChild(node);
2138
+ } catch {
2139
+ settle(false);
2140
+ return;
2141
+ }
2142
+ try { void node.offsetHeight; } catch { /* forcing a reflow is only a transition hint */ }
2143
+ node.style.transition = 'transform ' + plan.durationMs + 'ms ' + plan.easing + ', opacity ' + plan.durationMs + 'ms ' + plan.easing;
2144
+ node.style.transform = plan.transform;
2145
+ node.style.opacity = String(plan.opacity);
2146
+ if (typeof node.addEventListener === 'function') {
2147
+ node.addEventListener('transitionend', () => settle(true), { once: true });
2148
+ }
2149
+ timer = setTimeout(() => settle(true), FLIGHT_TIMEOUT_MS);
2150
+ });
2151
+ }
2152
+
2153
+ async function beginHoldAttempt() {
2154
+ if (busy || controller.disposed) return;
2155
+ const state = await service.state(false);
2156
+ if (controller.disposed) return;
2157
+ if (!triggerActive() || (hold.phase !== 'pressing' && hold.phase !== 'recording')) return;
2158
+ if (!state) {
2159
+ hold = holdStart();
2160
+ keyHeld = false;
2161
+ showToast(t('feedback.unavailable'), 'error');
2162
+ return;
2163
+ }
2164
+ controller.preferences = readPreferences(state);
2165
+ controller.limits = readLimits(state);
2166
+ controller.useStreaming = captureModeFor({
2167
+ preferences: controller.preferences,
2168
+ state,
2169
+ liveSupported: liveCaptureSupported(),
2170
+ }) === 'stream';
2171
+ if (state.dependency && state.dependency.speechToText === false) {
2172
+ hold = holdStart();
2173
+ keyHeld = false;
2174
+ showToast(t('feedback.missingDependency'), 'error');
2175
+ return;
2176
+ }
2177
+ const ready = await ensureReady(state);
2178
+ if (!ready || controller.disposed) return;
2179
+ if (!triggerActive()) {
2180
+ busy = false;
2181
+ setHolding(false);
2182
+ releaseView();
2183
+ return;
2184
+ }
2185
+ await startRecording(controller.useStreaming);
2186
+ }
2187
+
2188
+ /* ---------------- gesture + shortcut listeners ---------------- */
2189
+
2190
+ function onPointerDown(event) {
2191
+ if (controller.disposed || busy) return;
2192
+ if (event.pointerType === 'mouse' && event.button !== 0) return;
2193
+ const target = event.target;
2194
+ if (!target || typeof target.closest !== 'function') return;
2195
+ const card = controller.card;
2196
+ if (!card || !card.contains(target)) return;
2197
+ if (!target.closest('[data-input-scroll]')) return;
2198
+ if (target.closest('button, a, input, select, textarea, [role="button"], [contenteditable="false"]')) return;
2199
+ if (typeof window !== 'undefined' && window.getSelection && String(window.getSelection() || '').length > 0) return;
2200
+ const props = propsRef.current;
2201
+ if (props && typeof props.getPhase === 'function' && props.getPhase() !== 'plain') return;
2202
+ const pointerType = typeof event.pointerType === 'string' && event.pointerType !== '' ? event.pointerType : 'mouse';
2203
+ if (!shouldStartPointerHold({ pointerType, editorFocused: editorFocused(), keyboardOpen: keyboardOpen() })) {
2204
+ scheduleGuardHint();
2205
+ return;
2206
+ }
2207
+ clearGuardHint();
2208
+ const pressed = holdStep(hold, { type: 'press', pointerId: event.pointerId, x: event.clientX, y: event.clientY }, controller.preferences);
2209
+ if (pressed.action === 'ignore') return;
2210
+ hold = pressed.state;
2211
+ pointerDown = true;
2212
+ controller.pointerType = pointerType;
2213
+ if (holdTimer) clearTimeout(holdTimer);
2214
+ holdTimer = setTimeout(() => {
2215
+ holdTimer = 0;
2216
+ if (!pointerDown) return;
2217
+ const next = holdStep(hold, { type: 'hold' });
2218
+ hold = next.state;
2219
+ if (next.action === 'start') {
2220
+ setHolding(true);
2221
+ if (controller.card && typeof controller.card.setPointerCapture === 'function') {
2222
+ try { controller.card.setPointerCapture(event.pointerId); } catch { /* capture is an optimization */ }
2223
+ }
2224
+ void beginHoldAttempt();
2225
+ }
2226
+ }, controller.preferences.holdDelayMs);
2227
+ }
2228
+
2229
+ function onPointerMove(event) {
2230
+ if (guardCandidate) {
2231
+ clearGuardHint();
2232
+ return;
2233
+ }
2234
+ if (event.pointerId !== undefined && hold.pointerId !== null && event.pointerId !== hold.pointerId) return;
2235
+ const options = { cancelDistancePx: controller.preferences.cancelDistancePx, moveTolerancePx: MOVE_TOLERANCE_PX };
2236
+ const next = holdStep(hold, { type: 'move', x: event.clientX, y: event.clientY }, options);
2237
+ if (next.action === 'abort') {
2238
+ pointerDown = false;
2239
+ if (holdTimer) { clearTimeout(holdTimer); holdTimer = 0; }
2240
+ setHolding(false);
2241
+ }
2242
+ hold = next.state;
2243
+ if (next.action === 'arm' || next.action === 'disarm') {
2244
+ const phase = hold.phase === 'cancel' ? 'cancel' : 'recording';
2245
+ overlayFor(phase, hold.phase === 'cancel', 0);
2246
+ setHolding(true);
2247
+ try { event.preventDefault(); } catch { /* passive listeners cannot prevent */ }
2248
+ }
2249
+ if ((hold.phase === 'recording' || hold.phase === 'cancel') && event.cancelable) {
2250
+ try { event.preventDefault(); } catch { /* selection is already prevented by the CSS class */ }
2251
+ }
2252
+ }
2253
+
2254
+ function onPointerUp(event) {
2255
+ if (guardCandidate) {
2256
+ clearGuardHint();
2257
+ return;
2258
+ }
2259
+ if (event.pointerId !== undefined && hold.pointerId !== null && event.pointerId !== hold.pointerId) return;
2260
+ pointerDown = false;
2261
+ if (holdTimer) { clearTimeout(holdTimer); holdTimer = 0; }
2262
+ const next = holdStep(hold, { type: 'release' });
2263
+ hold = next.state;
2264
+ if (next.action === 'finish') {
2265
+ stopRequested = true;
2266
+ if ((capture || live) && busy) void finish();
2267
+ return;
2268
+ }
2269
+ if (next.action === 'cancel') {
2270
+ void cancelCurrent({ silent: true });
2271
+ return;
2272
+ }
2273
+ if (next.action === 'abort') {
2274
+ setHolding(false);
2275
+ }
2276
+ }
2277
+
2278
+ function onPointerCancel() {
2279
+ clearGuardHint();
2280
+ pointerDown = false;
2281
+ const next = holdStep(hold, { type: 'cancel' });
2282
+ hold = next.state;
2283
+ if (next.action === 'cancel') void cancelCurrent({ silent: true });
2284
+ else setHolding(false);
2285
+ }
2286
+
2287
+ function onKeyDown(event) {
2288
+ if (isEscape(event)) {
2289
+ if (keyHeld || (hold.phase === 'pressing' && holdTimer)) {
2290
+ if (typeof event.preventDefault === 'function') event.preventDefault();
2291
+ keyHeld = false;
2292
+ if (holdTimer) { clearTimeout(holdTimer); holdTimer = 0; }
2293
+ const next = holdStep(hold, { type: 'cancel' });
2294
+ hold = next.state;
2295
+ if (next.action === 'cancel') {
2296
+ void cancelCurrent();
2297
+ showToast(t('feedback.cancelled'));
2298
+ } else {
2299
+ setHolding(false);
2300
+ }
2301
+ return;
2302
+ }
2303
+ if (hold.phase === 'recording' || hold.phase === 'cancel' || busy) {
2304
+ if (typeof event.preventDefault === 'function') event.preventDefault();
2305
+ void cancelCurrent({ silent: true });
2306
+ showToast(t('feedback.cancelled'));
2307
+ }
2308
+ return;
2309
+ }
2310
+ if (matchesShortcut(event, controller.preferences.shortcut) !== true) return;
2311
+ if (shortcutAllowed(shortcutTargetFlags()) !== true) return;
2312
+ if (hold.phase !== 'idle' || busy || holdTimer) return;
2313
+ if (typeof event.preventDefault === 'function') event.preventDefault();
2314
+ const pressed = holdStep(hold, { type: 'press', pointerId: 0, x: 0, y: 0 }, controller.preferences);
2315
+ if (pressed.action === 'ignore') return;
2316
+ hold = pressed.state;
2317
+ keyHeld = true;
2318
+ shortcutCode = event.code;
2319
+ controller.pointerType = 'keyboard';
2320
+ holdTimer = setTimeout(() => {
2321
+ holdTimer = 0;
2322
+ if (!keyHeld) return;
2323
+ const next = holdStep(hold, { type: 'hold' });
2324
+ hold = next.state;
2325
+ if (next.action === 'start') {
2326
+ setHolding(true);
2327
+ void beginHoldAttempt();
2328
+ }
2329
+ }, controller.preferences.holdDelayMs);
2330
+ }
2331
+
2332
+ function onKeyUp(event) {
2333
+ if (!keyHeld) return;
2334
+ const code = typeof event.code === 'string' ? event.code : '';
2335
+ if (code !== shortcutCode && !isModifierCode(code)) return;
2336
+ keyHeld = false;
2337
+ if (holdTimer) { clearTimeout(holdTimer); holdTimer = 0; }
2338
+ const next = holdStep(hold, { type: 'release' });
2339
+ hold = next.state;
2340
+ if (next.action === 'finish') {
2341
+ stopRequested = true;
2342
+ if ((capture || live) && busy) void finish();
2343
+ return;
2344
+ }
2345
+ if (next.action === 'cancel') {
2346
+ void cancelCurrent({ silent: true });
2347
+ return;
2348
+ }
2349
+ if (next.action === 'abort') setHolding(false);
2350
+ }
2351
+
2352
+ function onDocumentHidden() {
2353
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden' && (hold.phase === 'recording' || hold.phase === 'cancel')) {
2354
+ void cancelCurrent({ silent: true });
2355
+ }
2356
+ }
2357
+
2358
+ function onWindowBlur() {
2359
+ if (hold.phase === 'recording' || hold.phase === 'cancel') {
2360
+ void cancelCurrent({ silent: true });
2361
+ return;
2362
+ }
2363
+ if (hold.phase === 'pressing') {
2364
+ keyHeld = false;
2365
+ pointerDown = false;
2366
+ if (holdTimer) { clearTimeout(holdTimer); holdTimer = 0; }
2367
+ clearGuardHint();
2368
+ hold = holdStart();
2369
+ setHolding(false);
2370
+ }
2371
+ }
2372
+
2373
+ function onContextMenu(event) {
2374
+ if (hold.phase === 'pressing' || hold.phase === 'recording' || hold.phase === 'cancel') event.preventDefault();
2375
+ }
2376
+
2377
+ /* ---------------- placeholder hint ---------------- */
2378
+
2379
+ function setPlaceholderHint(text) {
2380
+ if (!controller.card) return;
2381
+ const placeholder = controller.card.querySelector('[data-composer-placeholder]');
2382
+ if (!placeholder) return;
2383
+ if (controller.placeholderOriginal === null) controller.placeholderOriginal = placeholder.textContent;
2384
+ if (placeholder.textContent !== text) placeholder.textContent = text;
2385
+ placeholder.setAttribute(HINT_ATTR, 'true');
2386
+ }
2387
+
2388
+ function restorePlaceholderHint() {
2389
+ if (!controller.card) return;
2390
+ const placeholder = controller.card.querySelector('[data-composer-placeholder]');
2391
+ if (!placeholder) return;
2392
+ if (placeholder.hasAttribute(HINT_ATTR) && controller.placeholderOriginal !== null) {
2393
+ placeholder.textContent = controller.placeholderOriginal;
2394
+ placeholder.removeAttribute(HINT_ATTR);
2395
+ }
2396
+ controller.placeholderOriginal = null;
2397
+ }
2398
+
2399
+ function refreshHint() {
2400
+ if (!controller.card) return;
2401
+ const enabled = Boolean(controller.preferences && controller.preferences.composerHint !== false);
2402
+ const text = hintText || t('composerHint');
2403
+ if (enabled) setPlaceholderHint(text);
2404
+ else restorePlaceholderHint();
2405
+ }
2406
+
2407
+ /* ---------------- lifecycle ---------------- */
2408
+
2409
+ function attach(anchor) {
2410
+ controller.anchor = anchor;
2411
+ const card = anchor && typeof anchor.closest === 'function' ? anchor.closest('[data-composer-card]') : null;
2412
+ if (!card) return;
2413
+ controller.card = card;
2414
+ card.addEventListener('pointerdown', onPointerDown, { capture: true, passive: true });
2415
+ card.addEventListener('contextmenu', onContextMenu, { capture: true, passive: false });
2416
+ window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false });
2417
+ window.addEventListener('pointerup', onPointerUp, { capture: true, passive: true });
2418
+ window.addEventListener('pointercancel', onPointerCancel, { capture: true, passive: true });
2419
+ window.addEventListener('blur', onWindowBlur);
2420
+ document.addEventListener('keydown', onKeyDown, true);
2421
+ document.addEventListener('keyup', onKeyUp, true);
2422
+ document.addEventListener('visibilitychange', onDocumentHidden);
2423
+ controller.hintObserver = new MutationObserver(() => refreshHint());
2424
+ controller.hintObserver.observe(card, { childList: true, subtree: true, characterData: true });
2425
+ void service.state(false).then((state) => {
2426
+ if (controller.disposed) return;
2427
+ if (state) {
2428
+ controller.preferences = readPreferences(state);
2429
+ controller.limits = readLimits(state);
2430
+ }
2431
+ hintText = t('composerHint');
2432
+ refreshHint();
2433
+ });
2434
+ }
2435
+
2436
+ function dispose() {
2437
+ if (controller.disposed) return;
2438
+ controller.disposed = true;
2439
+ resetStreamingTake();
2440
+ abortInFlight();
2441
+ cancelFlight();
2442
+ disposeCapture();
2443
+ clearTimers();
2444
+ clearGuardHint();
2445
+ setHolding(false);
2446
+ restorePlaceholderHint();
2447
+ if (controller.hintObserver) controller.hintObserver.disconnect();
2448
+ const card = controller.card;
2449
+ if (card) {
2450
+ card.removeEventListener('pointerdown', onPointerDown, { capture: true });
2451
+ card.removeEventListener('contextmenu', onContextMenu, { capture: true });
2452
+ }
2453
+ window.removeEventListener('pointermove', onPointerMove, { capture: true });
2454
+ window.removeEventListener('pointerup', onPointerUp, { capture: true });
2455
+ window.removeEventListener('pointercancel', onPointerCancel, { capture: true });
2456
+ window.removeEventListener('blur', onWindowBlur);
2457
+ document.removeEventListener('keydown', onKeyDown, true);
2458
+ document.removeEventListener('keyup', onKeyUp, true);
2459
+ document.removeEventListener('visibilitychange', onDocumentHidden);
2460
+ if (toastTimer) { clearTimeout(toastTimer); toastTimer = 0; }
2461
+ releaseView();
2462
+ }
2463
+
2464
+ return {
2465
+ attach,
2466
+ dispose,
2467
+ getLevel: () => (live ? live.amplitude() : capture ? capture.amplitude() : 0),
2468
+ };
2469
+ }
2470
+
2471
+ /* ================================================================ */
2472
+ /* React component */
2473
+ /* ================================================================ */
2474
+
2475
+ function HoldToTalkOverlay(props) {
2476
+ const anchorRef = useRef(null);
2477
+ const propsRef = useRef(null);
2478
+ const inputActionsRef = useRef(props.inputActions);
2479
+ inputActionsRef.current = props.inputActions;
2480
+ const runtimeRef = useRef(null);
2481
+ const [view, setView] = useState({ visible: false, phase: 'idle', armed: false, progress: null, action: 'insert', statusText: '', cancelLabel: '', hint: '', liveText: '', onCancel: undefined });
2482
+ const [toast, setToast] = useState(null);
2483
+
2484
+ const useInput = props.useInput;
2485
+ const draft = useInput ? useInput((state) => state.draft) : '';
2486
+ const phase = useInput ? useInput((state) => state.phase) : 'plain';
2487
+ const draftRef = useRef(draft);
2488
+ draftRef.current = draft;
2489
+ const phaseRef = useRef(phase);
2490
+ phaseRef.current = phase;
2491
+
2492
+ const getDraft = useCallback(() => draftRef.current, []);
2493
+ const getPhase = useCallback(() => phaseRef.current, []);
2494
+ propsRef.current = { ...props, getDraft, getPhase };
2495
+
2496
+ useEffect(() => {
2497
+ const runtime = createRuntime({ propsRef, setView, setToast });
2498
+ runtimeRef.current = runtime;
2499
+ runtime.attach(anchorRef.current);
2500
+ return () => {
2501
+ runtimeRef.current = null;
2502
+ runtime.dispose();
2503
+ };
2504
+ }, []);
2505
+
2506
+ const live = view.phase === 'recording' || view.phase === 'cancel';
2507
+ return h(react.Fragment, null,
2508
+ h('span', { ref: anchorRef, className: 'bvi-anchor', 'aria-hidden': 'true' }),
2509
+ view.visible
2510
+ ? h(Overlay, {
2511
+ phase: view.phase,
2512
+ armed: view.armed,
2513
+ progress: view.progress,
2514
+ statusText: view.statusText,
2515
+ liveText: view.liveText,
2516
+ live,
2517
+ getLevel: () => (runtimeRef.current ? runtimeRef.current.getLevel() : 0),
2518
+ onCancel: view.onCancel,
2519
+ cancelLabel: view.cancelLabel,
2520
+ })
2521
+ : null,
2522
+ h(ToastLayer, { toast }));
2523
+ }
2524
+
2525
+ /* ================================================================ */
2526
+ /* styles */
2527
+ /* ================================================================ */
2528
+
2529
+ const CSS = [
2530
+ '.bvi-anchor{display:block;position:absolute;inset:0 auto auto 0;width:0;height:0;overflow:hidden;pointer-events:none}',
2531
+ '[data-composer-card].bvi-holding,[data-composer-card].bvi-holding [data-input-scroll],[data-composer-card].bvi-holding [contenteditable]{user-select:none!important;-webkit-user-select:none!important;-webkit-touch-callout:none!important}',
2532
+ '[data-composer-card].bvi-holding{cursor:default}',
2533
+ '.bvi-overlay{position:fixed;inset:0;z-index:9000;display:flex;flex-direction:column;align-items:center;justify-content:flex-start;overflow:hidden;touch-action:none;pointer-events:none;font-family:var(--dsw-font-family,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif)}',
2534
+ '.bvi-overlay__blue,.bvi-overlay__red,.bvi-overlay__vignette{position:absolute;inset:0;pointer-events:none;transition:opacity 160ms ease}',
2535
+ '.bvi-overlay__blue{background:linear-gradient(180deg,#0f1112 0%,#0c141d 8%,#0b223d 18%,#04376a 29%,#004992 38%,#005ec0 50%,#0066d3 60%,#0169dc 70%,#006bda 82%,#006bd8 100%)}',
2536
+ '.bvi-overlay__blue::after{content:"";position:absolute;inset:0;background:radial-gradient(ellipse 68% 42% at 50% 74%,rgba(0,116,235,.55) 0%,rgba(0,116,235,0) 70%)}',
2537
+ '.bvi-overlay__red{background:linear-gradient(180deg,#0f0f0f 0%,#0f0f0f 12%,#151011 20%,#1d1314 30%,#391b1a 45%,#602728 61%,#772d31 70%,#873235 80%,#903538 90%,#953535 100%);opacity:0}',
2538
+ '.bvi-overlay__red::after{content:"";position:absolute;inset:0;background:radial-gradient(ellipse 62% 40% at 50% 76%,rgba(190,45,50,.45) 0%,rgba(190,45,50,0) 72%)}',
2539
+ '.bvi-overlay__vignette{background:radial-gradient(ellipse 78% 70% at 50% 50%,rgba(0,0,0,0) 42%,rgba(0,0,0,.34) 100%);transition:opacity 160ms ease}',
2540
+ '.bvi-overlay[data-state="cancel"] .bvi-overlay__blue{opacity:0}',
2541
+ '.bvi-overlay[data-state="cancel"] .bvi-overlay__red{opacity:1}',
2542
+ '.bvi-status{position:absolute;left:50%;top:38%;transform:translate(-50%,-50%);margin:0;padding:0 4vw;max-width:92vw;color:#cfe6ff;font-size:clamp(21px,3.1vw,40px);font-weight:400;letter-spacing:.14em;line-height:1.4;text-align:center;white-space:nowrap;font-family:"Songti SC","Noto Serif SC","Source Han Serif SC","STSong",serif;text-shadow:0 0 22px rgba(120,180,255,.55),0 0 5px rgba(210,235,255,.45);transition:color 160ms ease,text-shadow 160ms ease}',
2543
+ '.bvi-overlay[data-state="cancel"] .bvi-status{color:#d4525e;text-shadow:0 0 22px rgba(255,80,90,.42),0 0 5px rgba(255,150,155,.35)}',
2544
+ '.bvi-live{position:absolute;left:50%;top:48.5%;transform:translate(-50%,-50%);display:flex;align-items:flex-end;justify-content:center;width:min(86vw,980px);max-height:4.2em;overflow:hidden;pointer-events:none;opacity:0;transition:opacity 180ms ease}',
2545
+ '.bvi-live[data-visible="true"]{opacity:1}',
2546
+ '.bvi-live__text{color:#e8f2ff;font-size:clamp(16px,2.2vw,28px);line-height:1.4;letter-spacing:.02em;text-align:center;white-space:pre-wrap;word-break:break-word;text-shadow:0 0 16px rgba(120,180,255,.5),0 0 4px rgba(210,235,255,.4)}',
2547
+ '.bvi-overlay[data-state="cancel"] .bvi-live__text{color:#ffd9dc;text-shadow:0 0 16px rgba(255,90,100,.45)}',
2548
+ '.bvi-wave{position:absolute;left:50%;top:61.5%;transform:translate(-50%,-50%);display:flex;align-items:center;justify-content:center;gap:9px;height:48px;width:min(72vw,900px);mask-image:linear-gradient(90deg,transparent 0%,#000 9%,#000 91%,transparent 100%);-webkit-mask-image:linear-gradient(90deg,transparent 0%,#000 9%,#000 91%,transparent 100%)}',
2549
+ '.bvi-wave[data-live="false"]{opacity:.9}',
2550
+ '.bvi-bar{display:block;width:4px;height:12px;border-radius:2px;background:#dde8ff;box-shadow:0 0 9px rgba(160,205,255,.85);transition:height 90ms linear,background 160ms ease,box-shadow 160ms ease;flex:0 0 auto}',
2551
+ '.bvi-overlay[data-state="cancel"] .bvi-bar{background:#e06770;box-shadow:0 0 9px rgba(255,95,105,.75)}',
2552
+ '.bvi-overlay[data-state="preparing"] .bvi-wave,.bvi-overlay[data-state="transcribing"] .bvi-wave{opacity:.55}',
2553
+ '.bvi-overlay[data-state="transcribing"] .bvi-bar{animation:bvi-pulse 1.15s ease-in-out infinite}',
2554
+ '.bvi-overlay[data-state="transcribing"] .bvi-bar:nth-child(3n){animation-delay:.18s}',
2555
+ '.bvi-overlay[data-state="transcribing"] .bvi-bar:nth-child(3n+1){animation-delay:.36s}',
2556
+ '.bvi-overlay[data-state="settling"] .bvi-status,.bvi-overlay[data-state="settling"] .bvi-live,.bvi-overlay[data-state="settling"] .bvi-wave{opacity:0}',
2557
+ '.bvi-flight{position:fixed;z-index:9002;pointer-events:none;transform-origin:50% 50%;color:#eaf3ff;font-size:clamp(17px,2.6vw,32px);line-height:1.4;letter-spacing:.02em;text-align:center;white-space:pre-wrap;word-break:break-word;text-shadow:0 0 18px rgba(120,180,255,.55),0 0 5px rgba(210,235,255,.45);transition:transform 360ms cubic-bezier(.2,.8,.2,1),opacity 360ms cubic-bezier(.2,.8,.2,1);will-change:transform,opacity}',
2558
+ '@keyframes bvi-pulse{0%,100%{opacity:.5}50%{opacity:1}}',
2559
+ '.bvi-progress{position:absolute;left:50%;top:calc(38% + 46px);transform:translateX(-50%);display:flex;flex-direction:column;align-items:center;gap:8px;width:min(360px,64vw)}',
2560
+ '.bvi-progress__track{width:100%;height:3px;border-radius:2px;background:rgba(207,230,255,.22);overflow:hidden}',
2561
+ '.bvi-progress__fill{height:100%;border-radius:2px;background:#cfe6ff;transition:width 300ms ease}',
2562
+ '.bvi-progress__label{color:rgba(207,230,255,.82);font-size:12px;letter-spacing:.08em}',
2563
+ '.bvi-cancel{position:absolute;left:50%;bottom:12vh;transform:translateX(-50%);pointer-events:auto;appearance:none;border:1px solid rgba(207,230,255,.28);background:rgba(8,18,38,.28);color:rgba(207,230,255,.9);font-size:13px;letter-spacing:.06em;padding:7px 16px;border-radius:999px;cursor:pointer;backdrop-filter:blur(6px);-webkit-backdrop-filter:blur(6px)}',
2564
+ '.bvi-overlay[data-state="cancel"] .bvi-cancel{border-color:rgba(255,160,165,.35);color:rgba(255,205,208,.92)}',
2565
+ '.bvi-toast{position:fixed;left:50%;bottom:calc(env(safe-area-inset-bottom,0px) + 108px);transform:translateX(-50%);z-index:9001;pointer-events:none;max-width:min(520px,86vw);padding:10px 16px;border-radius:12px;background:var(--dsw-alias-bg-layer-2,#242426);color:var(--dsw-alias-label-primary,#f2f2f2);border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.14));box-shadow:0 10px 30px rgba(0,0,0,.35);font-size:13px;line-height:1.5;text-align:center}',
2566
+ '.bvi-toast[data-tone="error"]{border-color:var(--dsw-alias-state-error-primary,#e5484d);color:var(--dsw-alias-label-primary,#f2f2f2)}',
2567
+ '@media (max-width:520px){.bvi-wave{gap:6px;width:84vw}.bvi-bar{width:3px}.bvi-status{letter-spacing:.1em}.bvi-cancel{bottom:14vh}.bvi-live{width:90vw;top:48%}.bvi-live__text{font-size:15px}}',
2568
+ '@media (prefers-reduced-motion:reduce){.bvi-overlay__blue,.bvi-overlay__red,.bvi-status,.bvi-bar{transition:none}.bvi-overlay[data-state="transcribing"] .bvi-bar{animation:none}.bvi-live,.bvi-flight{transition:none}}',
2569
+ ].join('\n');
2570
+
2571
+ function mountCss() {
2572
+ const existing = document.getElementById(CSS_ID);
2573
+ if (existing) existing.remove();
2574
+ const style = document.createElement('style');
2575
+ style.id = CSS_ID;
2576
+ style.setAttribute('data-plugin', '@ds-hu/dsh-bvi-input');
2577
+ style.textContent = CSS;
2578
+ document.head.appendChild(style);
2579
+ return () => style.remove();
2580
+ }
2581
+
2582
+ /* ================================================================ */
2583
+ /* plugin */
2584
+ /* ================================================================ */
2585
+
2586
+ let appCtx = null;
2587
+
2588
+ function currentLang() {
2589
+ try {
2590
+ const locale = appCtx && appCtx.locale;
2591
+ const snapshot = locale && typeof locale.getLocale === 'function' ? locale.getLocale() : undefined;
2592
+ const active = snapshot && typeof snapshot.active === 'string' ? snapshot.active : undefined;
2593
+ if (active !== undefined && active.toLowerCase().startsWith('en')) return 'en';
2594
+ } catch {
2595
+ /* fall back to the project default */
2596
+ }
2597
+ return 'zh';
2598
+ }
2599
+
2600
+ function apply(ctx) {
2601
+ appCtx = ctx;
2602
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'better-voice-input: dictionaries');
2603
+ ctx.effect(() => mountCss(), 'better-voice-input: stylesheet');
2604
+ ctx.effect(() => ctx.slots.inject('conversation.input.overlay', () => ctx.slots.register({
2605
+ name: 'conversation.input.overlay',
2606
+ id: 'bvi-input',
2607
+ locale: NS,
2608
+ }, HoldToTalkOverlay)), 'better-voice-input: composer hold-to-talk');
2609
+ }
2610
+
2611
+ exports.name = 'better-voice-input';
2612
+ exports.inject = ['slots', 'locale'];
2613
+ exports.apply = apply;
2614
+ exports.__bviTest = {
2615
+ // gesture state machine
2616
+ holdStart,
2617
+ holdStep,
2618
+ // presentation helpers
2619
+ barCountFor,
2620
+ barHeight,
2621
+ encodeWav,
2622
+ encodeWavFromPcm16,
2623
+ readPreferences,
2624
+ readLimits,
2625
+ overlayState,
2626
+ isEscape,
2627
+ clampInteger,
2628
+ DEFAULTS,
2629
+ API_BASE,
2630
+ NS,
2631
+ zh,
2632
+ en,
2633
+ currentLang,
2634
+ setTestRuntime(ctx) { appCtx = ctx; },
2635
+ HoldToTalkOverlay,
2636
+ createRuntime,
2637
+ // v0.2: trigger guards, shortcut, streaming capture/session, flight animation
2638
+ DEFAULT_SHORTCUT,
2639
+ normalizeShortcut,
2640
+ shortcutComboAllowed,
2641
+ matchesShortcut,
2642
+ shortcutAllowed,
2643
+ isModifierCode,
2644
+ isVirtualKeyboardOpen,
2645
+ shouldStartPointerHold,
2646
+ captureModeFor,
2647
+ liveCaptureSupported,
2648
+ resampleFloat32,
2649
+ downsampleTo16k,
2650
+ floatToPcm16,
2651
+ pcm16ToFloat32,
2652
+ concatBytes,
2653
+ splitStreamingChunk,
2654
+ trimLiveText,
2655
+ usableRect,
2656
+ planFlight,
2657
+ prefersReducedMotion,
2658
+ StreamingSession,
2659
+ LIVE_SAMPLE_RATE,
2660
+ STREAM_CHUNK_MS,
2661
+ MAX_STREAM_CHUNK_BYTES,
2662
+ LIVE_TEXT_MAX_CHARS,
2663
+ FLIGHT_MS,
2664
+ FLIGHT_SCALE,
2665
+ FLIGHT_EASING,
2666
+ };
2667
+ return module.exports;
2668
+ },
2669
+ });