Open History to see the last commit
1import { errorDisplayMessage } from "../errors/translatable.ts";
2import * as Schema from "effect/Schema";
3import { replaceTextRange } from "@t3tools/shared/composerTrigger";
4
5import {
6 VoiceTranscriptionError,
7 type PreparedVoiceTranscription,
8 type VoiceTranscriber,
9} from "./transcription.ts";
10import { mFallback, msg } from "gt-i18n";
11import type { M } from "gt-i18n";
12
13const isVoiceTranscriptionError = Schema.is(VoiceTranscriptionError);
14
15export const VOICE_RECORDING_LIMIT_SECONDS = 5 * 60;
16
17export const MICROPHONE_PERMISSION_ERROR = msg(
18 "Microphone access is required for voice input. Allow access in your browser or system settings and try again.",
19);
20
21function isMicrophonePermissionError(error: unknown): boolean {
22 return (
23 typeof error === "object" &&
24 error !== null &&
25 "name" in error &&
26 error.name === "NotAllowedError"
27 );
28}
29
30export type VoiceInputPhase =
31 | "idle"
32 | "preparing"
33 | "recording"
34 | "transcribing"
35 | "post-processing"
36 | "error";
37
38/** Which known failure `error` describes, so clients label it without reading the text. */
39export type VoiceInputErrorCode =
40 | "microphone-blocked"
41 | "draft-unavailable"
42 | "already-recording"
43 | "unavailable"
44 | "still-transcribing"
45 | "language-unsupported"
46 | "start-failed"
47 | "interrupted"
48 | "finish-failed"
49 | "transcription-failed"
50 | "draft-changed"
51 | "no-speech"
52 | "microphone-failed"
53 | "microphone-disconnected";
54
55export type VoiceInputState = {
56 readonly phase: VoiceInputPhase;
57 readonly error: string | null;
58 readonly errorAction: "retry" | "settings" | null;
59 readonly errorCode?: VoiceInputErrorCode;
60};
61
62type VoiceInputFailure = { readonly message: string; readonly code?: VoiceInputErrorCode };
63
64export function voiceInputBlocksSubmission(state: VoiceInputState): boolean {
65 return (
66 state.phase === "preparing" ||
67 state.phase === "recording" ||
68 state.phase === "transcribing" ||
69 state.phase === "post-processing"
70 );
71}
72
73export type VoiceDraftSnapshot = {
74 readonly ownerKey: string;
75 readonly text: string;
76 readonly selection: { readonly start: number; readonly end: number };
77};
78
79export type VoiceRecorderStatus = {
80 readonly isFinished: boolean;
81 readonly hasError: boolean;
82 readonly error: string | null;
83 readonly url: string | null;
84};
85
86export interface VoiceRecorder {
87 readonly uri: string | null;
88 prepareToRecordAsync(signal?: AbortSignal): Promise<void>;
89 record(options: { readonly forDuration: number }): void;
90 stop(): Promise<void>;
91}
92
93export type VoiceInputControllerDependencies = {
94 readonly recorder: VoiceRecorder;
95 readonly getTranscriber: () => VoiceTranscriber | null;
96 readonly requestPermission: () => Promise<{
97 readonly granted: boolean;
98 readonly canAskAgain: boolean;
99 }>;
100 readonly configureRecording: () => Promise<void>;
101 readonly releaseRecording: () => Promise<void>;
102 readonly deleteRecording: (uri: string) => void;
103 /** Keep a recording whose transcription failed so the next start retries it without recording again. */
104 readonly retryFailedRecording?: boolean;
105 /**
106 * Optional cleanup of the transcript before insertion. Returning null skips it for this
107 * recording; a failure falls back to the raw transcript.
108 */
109 readonly postProcess?:
110 | ((
111 transcript: string,
112 options: { readonly signal: AbortSignal; readonly draft: VoiceDraftSnapshot },
113 ) => Promise<string> | null)
114 | undefined;
115 readonly onPostProcessingError?: (error: unknown) => void;
116 readonly readDraft: () => VoiceDraftSnapshot | null;
117 readonly commitDraft: (
118 text: string,
119 selection: { readonly start: number; readonly end: number },
120 ) => void;
121 readonly onStateChange: (state: VoiceInputState) => void;
122 /** Resolves error copy in the UI language; English when omitted. */
123 readonly resolve?: M;
124};
125
126type TranscriptCommitResult =
127 | {
128 readonly kind: "commit";
129 readonly text: string;
130 readonly selection: { readonly start: number; readonly end: number };
131 }
132 | { readonly kind: "stale" }
133 | { readonly kind: "empty" };
134
135const WORD_SPACELESS_LANGUAGES = new Set(["ja", "zh", "cmn", "yue", "th", "lo", "km", "my"]);
136
137const isHighSurrogate = (code: number) => code >= 0xd800 && code <= 0xdbff;
138const isLowSurrogate = (code: number) => code >= 0xdc00 && code <= 0xdfff;
139
140// Where `position` in `before` lands in `text`, placed after anything inserted at it.
141function mapPosition(before: string, text: string, position: number, suffixFirst: boolean) {
142 const shared = Math.min(before.length, text.length);
143 const matchesFromEnd = (offset: number) =>
144 before[before.length - 1 - offset] === text[text.length - 1 - offset];
145 let prefix = 0;
146 let suffix = 0;
147 // Matching is per UTF-16 unit; never let a boundary split a surrogate pair.
148 const scanSuffix = (limit: number) => {
149 while (suffix < limit && matchesFromEnd(suffix)) suffix += 1;
150 if (suffix > 0 && isLowSurrogate(before.charCodeAt(before.length - suffix))) suffix -= 1;
151 };
152 if (suffixFirst) scanSuffix(shared);
153 while (prefix < shared - suffix && before[prefix] === text[prefix]) prefix += 1;
154 if (prefix > 0 && isHighSurrogate(before.charCodeAt(prefix - 1))) prefix -= 1;
155 if (!suffixFirst) scanSuffix(shared - prefix);
156 if (position < prefix) return position;
157 if (position >= before.length - suffix) return position + text.length - before.length;
158 return text.length - suffix;
159}
160
161export function resolveTranscriptCommit(
162 captured: VoiceDraftSnapshot,
163 current: VoiceDraftSnapshot | null,
164 transcript: string,
165 locale: string,
166): TranscriptCommitResult {
167 if (!current || current.ownerKey !== captured.ownerKey) {
168 return { kind: "stale" };
169 }
170
171 const replacement = transcript.trim();
172 if (replacement.length === 0) {
173 return { kind: "empty" };
174 }
175
176 const { text } = current;
177 // An edit made while recording (a citation, a paste) is never replaced. The edit's position is
178 // ambiguous over repeated text, so insert after the selection under both extreme alignments.
179 const unchanged = text === captured.text;
180 const end = unchanged
181 ? captured.selection.end
182 : Math.max(
183 mapPosition(captured.text, text, captured.selection.end, false),
184 mapPosition(captured.text, text, captured.selection.end, true),
185 );
186 const start = unchanged ? captured.selection.start : end;
187 const isEmptySelection = start === end;
188 const language = locale.split(/[-_]/)[0]!.toLowerCase();
189 let insertion = replacement;
190 if (isEmptySelection && !WORD_SPACELESS_LANGUAGES.has(language)) {
191 const auto = language === "auto";
192 let leftBase = start;
193 while (leftBase > 0 && /\p{M}/u.test(text[leftBase - 1]!)) leftBase -= 1;
194 const left = text.slice(Math.max(0, leftBase - 2), start);
195 const right = text.slice(start, start + 2);
196 const leftEdge = auto
197 ? /(?:[\p{Script=Latin}0-9]\p{M}*|[.!?,:;)\]}'"])$/u
198 : /(?:\p{L}|\p{M}|\p{N}|[.!?,:;)\]}'"])$/u;
199 const rightEdge = auto ? /^[\p{Script=Latin}0-9([{'"]/u : /^[\p{L}\p{M}\p{N}([{'"]/u;
200 const leftNeedsBoundary =
201 (!auto || /^[\p{Script=Latin}\p{N}]/u.test(replacement)) &&
202 leftEdge.test(left) &&
203 (!right || /^\s/.test(right));
204 const rightNeedsBoundary =
205 (!auto || /[\p{Script=Latin}\p{N}]\p{M}*$/u.test(replacement)) &&
206 rightEdge.test(right) &&
207 (!left || /\s$/.test(left));
208 insertion = `${leftNeedsBoundary ? " " : ""}${replacement}${rightNeedsBoundary ? " " : ""}`;
209 }
210
211 const result = replaceTextRange(text, start, end, insertion);
212 return {
213 kind: "commit",
214 text: result.text,
215 selection: { start: result.cursor, end: result.cursor },
216 };
217}
218
219type VoiceInputSession = {
220 abandoned: boolean;
221 readonly released: Promise<void>;
222 readonly release: () => void;
223};
224
225let activeSession: VoiceInputSession | null = null;
226let activeTranscriptionOperation: Promise<unknown> | null = null;
227
228function acquireSession(): VoiceInputSession | null {
229 if (activeSession) return null;
230 let release!: () => void;
231 const released = new Promise<void>((resolve) => {
232 release = resolve;
233 });
234 const token = { abandoned: false, released, release };
235 activeSession = token;
236 return token;
237}
238
239function releaseSession(token: VoiceInputSession | null): void {
240 if (token && activeSession === token) {
241 activeSession = null;
242 token.release();
243 }
244}
245
246async function runTranscriptionOperation<T>(operation: () => Promise<T>): Promise<T> {
247 if (activeTranscriptionOperation) {
248 throw new Error("voice-operation-busy");
249 }
250
251 const promise = operation();
252 activeTranscriptionOperation = promise;
253 try {
254 return await promise;
255 } finally {
256 if (activeTranscriptionOperation === promise) activeTranscriptionOperation = null;
257 }
258}
259
260function errorCode(error: unknown): string | null {
261 if (typeof error !== "object" || error === null || !("code" in error)) return null;
262 return typeof error.code === "string" ? error.code : null;
263}
264
265function preparationFailure(error: unknown, resolve: M): VoiceInputFailure {
266 if (error instanceof Error && error.message === "voice-operation-busy") {
267 return {
268 message: resolve(msg("Voice transcription is still finishing. Try again shortly.")),
269 code: "still-transcribing",
270 };
271 }
272 if (errorCode(error) === "unsupported-locale") {
273 return {
274 message: resolve(msg("Voice transcription is not available for this language.")),
275 code: "language-unsupported",
276 };
277 }
278 return isVoiceTranscriptionError(error) && error.message.trim()
279 ? { message: errorDisplayMessage(error, resolve) ?? error.message }
280 : { message: resolve(msg("Could not prepare voice transcription.")), code: "start-failed" };
281}
282
283function transcriptionFailure(error: unknown, resolve: M): VoiceInputFailure {
284 if (error instanceof Error && error.message === "voice-operation-busy") {
285 return {
286 message: resolve(msg("Voice transcription is still finishing. Try again shortly.")),
287 code: "still-transcribing",
288 };
289 }
290 return isVoiceTranscriptionError(error)
291 ? { message: errorDisplayMessage(error, resolve) ?? error.message }
292 : {
293 message: resolve(msg("Could not transcribe this recording.")),
294 code: "transcription-failed",
295 };
296}
297
298const IDLE_STATE: VoiceInputState = { phase: "idle", error: null, errorAction: null };
299
300export class VoiceInputController {
301 private readonly dependencies: VoiceInputControllerDependencies;
302 private state: VoiceInputState = IDLE_STATE;
303 private operationToken = 0;
304 private sessionToken: VoiceInputSession | null = null;
305 private transcription: PreparedVoiceTranscription | null = null;
306 private liveTranscription: Promise<{ text: string | null } | { error: unknown }> | null = null;
307 private transcriptionAbortController: AbortController | null = null;
308 private postProcessingAbortController: AbortController | null = null;
309 private skipPostProcessingRequested = false;
310 private capturedDraft: VoiceDraftSnapshot | null = null;
311 private recordingUri: string | null = null;
312 private readonly ownedRecordingUris = new Set<string>();
313 private recordingConfigured = false;
314 private finishing = false;
315 private retryRecording: {
316 uri: string;
317 ownerKey: string;
318 transcription: PreparedVoiceTranscription;
319 } | null = null;
320
321 constructor(dependencies: VoiceInputControllerDependencies) {
322 this.dependencies = dependencies;
323 }
324
325 private get resolve(): M {
326 return this.dependencies.resolve ?? mFallback;
327 }
328
329 private text(message: string): string {
330 return this.resolve(message);
331 }
332
333 get currentState(): VoiceInputState {
334 return this.state;
335 }
336
337 async start(): Promise<void> {
338 if (this.state.phase !== "idle" && this.state.phase !== "error") return;
339 const initiatingDraft = this.dependencies.readDraft();
340 if (!initiatingDraft) {
341 this.setError(
342 this.text(msg("This draft is no longer available.")),
343 "retry",
344 "draft-unavailable",
345 );
346 return;
347 }
348 let sessionToken: VoiceInputSession | null = null;
349 const operationToken = ++this.operationToken;
350 this.setState({ phase: "preparing", error: null, errorAction: null });
351
352 try {
353 for (
354 let previousSession = activeSession;
355 previousSession?.abandoned;
356 previousSession = activeSession
357 ) {
358 await previousSession.released;
359 if (!this.isCurrent(operationToken)) return;
360 }
361 sessionToken = acquireSession();
362 if (!sessionToken) {
363 this.setError(
364 this.text(msg("Another voice recording is already active.")),
365 "retry",
366 "already-recording",
367 );
368 return;
369 }
370 this.sessionToken = sessionToken;
371 const abortController = new AbortController();
372 this.transcriptionAbortController = abortController;
373
374 if (this.retryRecording && this.retryRecording.ownerKey !== initiatingDraft.ownerKey) {
375 this.retryRecording = null;
376 this.deleteOwnedRecordings();
377 }
378 if (this.retryRecording) {
379 this.recordingUri = this.retryRecording.uri;
380 this.capturedDraft = initiatingDraft;
381 this.transcription = this.retryRecording.transcription;
382 this.retryRecording = null;
383 await this.finishRecording(true, this.recordingUri);
384 return;
385 }
386 const transcriber = this.dependencies.getTranscriber();
387 if (!transcriber) {
388 this.setError(this.text(msg("Voice transcription is not available.")), null, "unavailable");
389 return;
390 }
391
392 const permission = await this.dependencies.requestPermission();
393 if (!this.isCurrent(operationToken)) return;
394 if (!permission.granted) {
395 this.setError(
396 this.text(msg("Microphone access is required for voice input.")),
397 permission.canAskAgain ? "retry" : "settings",
398 "microphone-blocked",
399 );
400 return;
401 }
402
403 try {
404 this.transcription = await runTranscriptionOperation(() =>
405 transcriber.prepare({ signal: abortController.signal }),
406 );
407 } catch (error) {
408 if (this.isCurrent(operationToken))
409 this.setFailure(preparationFailure(error, this.resolve), "retry");
410 return;
411 }
412 if (!this.isCurrent(operationToken)) return;
413
414 await this.dependencies.configureRecording();
415 this.recordingConfigured = true;
416 if (!this.isCurrent(operationToken)) return;
417 await this.dependencies.recorder.prepareToRecordAsync(abortController.signal);
418 if (!this.isCurrent(operationToken)) return;
419 this.recordingUri = this.dependencies.recorder.uri;
420 this.rememberRecordingUri(this.recordingUri);
421
422 const capturedDraft = this.dependencies.readDraft();
423 if (!capturedDraft || capturedDraft.ownerKey !== initiatingDraft.ownerKey) {
424 this.setError(
425 this.text(msg("This draft is no longer available.")),
426 "retry",
427 "draft-unavailable",
428 );
429 return;
430 }
431 this.capturedDraft = capturedDraft;
432 if (this.transcription.start && this.recordingUri) {
433 const start = this.transcription.start;
434 const uri = this.recordingUri;
435 this.liveTranscription = runTranscriptionOperation(() =>
436 start(uri, { signal: abortController.signal }),
437 ).then(
438 (text) => ({ text }),
439 (error: unknown) => {
440 if (this.isCurrent(operationToken) && this.state.phase === "recording") {
441 const failure = transcriptionFailure(error, this.resolve);
442 void this.discardRecording(failure.message, failure.code);
443 }
444 return { error };
445 },
446 );
447 }
448 this.dependencies.recorder.record({ forDuration: VOICE_RECORDING_LIMIT_SECONDS });
449 this.setState({ phase: "recording", error: null, errorAction: null });
450 } catch (error) {
451 if (this.isCurrent(operationToken))
452 this.setError(
453 isMicrophonePermissionError(error)
454 ? this.text(MICROPHONE_PERMISSION_ERROR)
455 : this.text(msg("Could not start voice recording.")),
456 "retry",
457 isMicrophonePermissionError(error) ? "microphone-blocked" : "start-failed",
458 );
459 } finally {
460 if (sessionToken && this.sessionToken === sessionToken) {
461 if (this.isCurrent(operationToken) && this.state.phase === "error") {
462 await this.releaseResources();
463 } else if (!this.isCurrent(operationToken) && !this.finishing) {
464 await this.releaseResources();
465 }
466 }
467 }
468 }
469
470 stop(): Promise<void> {
471 if (this.state.phase !== "recording") return Promise.resolve();
472 return this.finishRecording(false, null);
473 }
474
475 cancel(): void {
476 switch (this.state.phase) {
477 case "idle":
478 return;
479 case "error":
480 this.retryRecording = null;
481 this.deleteOwnedRecordings();
482 this.setState(IDLE_STATE);
483 return;
484 case "preparing":
485 this.invalidateOperation();
486 this.setState(IDLE_STATE);
487 return;
488 case "recording":
489 this.discardRecording(null);
490 return;
491 case "transcribing":
492 case "post-processing":
493 this.invalidateOperation();
494 this.setState(IDLE_STATE);
495 return;
496 }
497 }
498
499 skipPostProcessing(): void {
500 if (this.state.phase !== "post-processing") return;
501 this.skipPostProcessingRequested = true;
502 this.postProcessingAbortController?.abort();
503 }
504
505 interruptRecording(
506 message?: string,
507 completedUri: string | null = null,
508 code?: VoiceInputErrorCode,
509 ): Promise<void> | void {
510 const failure: VoiceInputFailure =
511 message === undefined
512 ? { message: this.text(msg("Voice recording was interrupted.")), code: "interrupted" }
513 : code === undefined
514 ? { message }
515 : { message, code };
516 if (this.state.phase === "preparing") {
517 this.invalidateOperation();
518 this.setFailure(failure, "retry");
519 return;
520 }
521 if (this.state.phase !== "recording") return;
522 this.rememberRecordingUri(completedUri);
523 this.recordingUri = completedUri ?? this.recordingUri;
524 return this.discardRecording(failure.message, failure.code);
525 }
526
527 appMovedToBackground(): Promise<void> | void {
528 return this.interruptRecording(
529 this.state.phase === "preparing"
530 ? this.text(msg("Voice input stopped when the app moved to the background."))
531 : undefined,
532 );
533 }
534
535 handleRecorderStatus(status: VoiceRecorderStatus): Promise<void> | void {
536 if (this.state.phase !== "recording") return;
537 if (status.url && this.recordingUri && status.url !== this.recordingUri) return;
538 if (status.hasError) {
539 return this.interruptRecording(status.error ?? undefined, status.url);
540 }
541 if (status.isFinished) {
542 if (!status.url) {
543 return this.interruptRecording();
544 }
545 return this.finishRecording(true, status.url);
546 }
547 }
548
549 ownerChanged(): void {
550 if (this.state.phase === "idle") return;
551 this.cancel();
552 }
553
554 dispose(): void {
555 switch (this.state.phase) {
556 case "idle":
557 return;
558 case "error":
559 this.cancel();
560 return;
561 case "recording":
562 this.discardRecording(null);
563 return;
564 default:
565 this.invalidateOperation();
566 this.setState(IDLE_STATE);
567 }
568 }
569
570 private async finishRecording(
571 alreadyStopped: boolean,
572 completedUri: string | null,
573 ): Promise<void> {
574 if (this.finishing || (this.state.phase !== "recording" && this.state.phase !== "preparing"))
575 return;
576 this.finishing = true;
577 const operationToken = this.operationToken;
578 this.setState({ phase: "transcribing", error: null, errorAction: null });
579
580 try {
581 if (!alreadyStopped) await this.dependencies.recorder.stop();
582 await this.releaseAudioSession();
583 this.recordingUri = completedUri ?? this.dependencies.recorder.uri ?? this.recordingUri;
584 this.rememberRecordingUri(this.recordingUri);
585 if (!this.isCurrent(operationToken)) return;
586 const transcription = this.transcription;
587 const recordingUri = this.recordingUri;
588 if (
589 !transcription ||
590 (!transcription.streaming && !recordingUri) ||
591 !this.transcriptionAbortController ||
592 !this.capturedDraft
593 ) {
594 this.setError(
595 this.text(msg("Could not finish voice recording.")),
596 "retry",
597 "finish-failed",
598 );
599 return;
600 }
601
602 const signal = this.transcriptionAbortController.signal;
603 const capturedDraft = this.capturedDraft;
604 let transcript: string;
605 try {
606 const live = this.liveTranscription ? await this.liveTranscription : null;
607 if (live && "error" in live) throw live.error;
608 transcript =
609 live?.text ??
610 (await runTranscriptionOperation(() =>
611 transcription.streaming
612 ? transcription.streaming.finish({ signal })
613 : transcription.transcribe(recordingUri!, { signal }),
614 ));
615 } catch (error) {
616 if (this.isCurrent(operationToken)) {
617 if (
618 this.dependencies.retryFailedRecording &&
619 errorCode(error) !== "preparation-failed" &&
620 !this.liveTranscription &&
621 !transcription.streaming &&
622 recordingUri
623 ) {
624 this.retryRecording = {
625 uri: recordingUri,
626 ownerKey: capturedDraft.ownerKey,
627 transcription,
628 };
629 }
630 this.setFailure(transcriptionFailure(error, this.resolve), "retry");
631 }
632 return;
633 }
634 if (!this.isCurrent(operationToken)) return;
635
636 const postProcessingAbortController = new AbortController();
637 const cleanup =
638 transcript.trim().length > 0
639 ? this.dependencies.postProcess?.(transcript, {
640 signal: postProcessingAbortController.signal,
641 draft: capturedDraft,
642 })
643 : null;
644 if (cleanup) {
645 this.setState({ phase: "post-processing", error: null, errorAction: null });
646 this.postProcessingAbortController = postProcessingAbortController;
647 this.skipPostProcessingRequested = false;
648 const rawTranscript = transcript;
649 try {
650 // Skip resolves immediately with the raw transcript; the abort signal tells the
651 // provider request to stop but its settlement is not awaited.
652 transcript = await Promise.race([
653 cleanup,
654 new Promise<string>((resolve) =>
655 postProcessingAbortController.signal.addEventListener(
656 "abort",
657 () => resolve(rawTranscript),
658 { once: true },
659 ),
660 ),
661 ]);
662 } catch (error) {
663 if (!this.skipPostProcessingRequested) {
664 this.dependencies.onPostProcessingError?.(error);
665 }
666 }
667 if (!this.isCurrent(operationToken)) return;
668 }
669
670 const result = resolveTranscriptCommit(
671 capturedDraft,
672 this.dependencies.readDraft(),
673 transcript,
674 transcription.locale,
675 );
676 if (result.kind === "stale") {
677 this.setError(
678 this.text(
679 msg("The draft changed while voice input was running. The transcript was not added."),
680 ),
681 "retry",
682 "draft-changed",
683 );
684 return;
685 }
686 if (result.kind === "empty") {
687 this.setError(this.text(msg("No speech was detected.")), "retry", "no-speech");
688 return;
689 }
690
691 this.dependencies.commitDraft(result.text, result.selection);
692 this.setState(IDLE_STATE);
693 } catch {
694 if (this.isCurrent(operationToken)) {
695 this.setError(
696 this.text(msg("Could not finish voice recording.")),
697 "retry",
698 "finish-failed",
699 );
700 }
701 } finally {
702 this.finishing = false;
703 await this.releaseResources();
704 }
705 }
706
707 private async discardRecording(
708 error: string | null,
709 errorCode?: VoiceInputErrorCode,
710 ): Promise<void> {
711 this.invalidateOperation();
712 this.setState(
713 error
714 ? errorCode === undefined
715 ? { phase: "error", error, errorAction: "retry" }
716 : { phase: "error", error, errorAction: "retry", errorCode }
717 : { phase: "idle", error: null, errorAction: null },
718 );
719 await this.releaseResources();
720 }
721
722 private async releaseResources(): Promise<void> {
723 this.transcriptionAbortController?.abort();
724 this.postProcessingAbortController?.abort();
725 this.rememberRecordingUri(this.recordingUri);
726 try {
727 this.rememberRecordingUri(this.dependencies.recorder.uri);
728 } catch {}
729 if (this.recordingConfigured) {
730 try {
731 await this.dependencies.recorder.stop();
732 } catch {}
733 }
734 await this.liveTranscription;
735 this.liveTranscription = null;
736 this.recordingUri = null;
737 this.deleteOwnedRecordings();
738 await this.releaseAudioSession();
739 releaseSession(this.sessionToken);
740 this.sessionToken = null;
741 this.capturedDraft = null;
742 this.transcription = null;
743 this.transcriptionAbortController = null;
744 this.postProcessingAbortController = null;
745 this.skipPostProcessingRequested = false;
746 }
747
748 private deleteOwnedRecordings(): void {
749 for (const uri of this.ownedRecordingUris) {
750 if (uri === this.retryRecording?.uri) continue;
751 try {
752 this.dependencies.deleteRecording(uri);
753 } catch {}
754 }
755 this.ownedRecordingUris.clear();
756 if (this.retryRecording) this.ownedRecordingUris.add(this.retryRecording.uri);
757 }
758
759 private rememberRecordingUri(uri: string | null): void {
760 if (uri) this.ownedRecordingUris.add(uri);
761 }
762
763 private async releaseAudioSession(): Promise<void> {
764 if (!this.recordingConfigured) return;
765 try {
766 await this.dependencies.releaseRecording();
767 this.recordingConfigured = false;
768 } catch {}
769 }
770
771 private invalidateOperation(): void {
772 this.operationToken += 1;
773 if (this.sessionToken) this.sessionToken.abandoned = true;
774 this.transcriptionAbortController?.abort();
775 this.postProcessingAbortController?.abort();
776 }
777
778 private isCurrent(operationToken: number): boolean {
779 return operationToken === this.operationToken;
780 }
781
782 private setError(
783 error: string,
784 errorAction: VoiceInputState["errorAction"],
785 errorCode?: VoiceInputErrorCode,
786 ): void {
787 this.setState(
788 errorCode === undefined
789 ? { phase: "error", error, errorAction }
790 : { phase: "error", error, errorAction, errorCode },
791 );
792 }
793
794 private setFailure(failure: VoiceInputFailure, errorAction: VoiceInputState["errorAction"]) {
795 this.setError(failure.message, errorAction, failure.code);
796 }
797
798 private setState(state: VoiceInputState): void {
799 this.state = state;
800 this.dependencies.onStateChange(state);
801 }
802}
803
804export function resetVoiceInputGlobalsForTests(): void {
805 activeSession = null;
806 activeTranscriptionOperation = null;
807}