Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

controller.ts

811 lines26.6 KB

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 );
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 );
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>;
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;
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 };
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;
238​
239function releaseSession(token: VoiceInputSession | null): void {
240 if (token && activeSession === token) {
241 activeSession = null;
242 token.release();
243 }
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 }
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;
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" };
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 if (isVoiceTranscriptionError(error)) {
291 const message = errorDisplayMessage(error, resolve) ?? error.message;
292 return error.code === "transcription-failed"
293 ? { message, code: "transcription-failed" }
294 : { message };
295 }
296 return {
297 message: resolve(msg("Could not transcribe this recording.")),
298 code: "transcription-failed",
299 };
301​
302const IDLE_STATE: VoiceInputState = { phase: "idle", error: null, errorAction: null };
303​
304export class VoiceInputController {
305 private readonly dependencies: VoiceInputControllerDependencies;
306 private state: VoiceInputState = IDLE_STATE;
307 private operationToken = 0;
308 private sessionToken: VoiceInputSession | null = null;
309 private transcription: PreparedVoiceTranscription | null = null;
310 private liveTranscription: Promise<{ text: string | null } | { error: unknown }> | null = null;
311 private transcriptionAbortController: AbortController | null = null;
312 private postProcessingAbortController: AbortController | null = null;
313 private skipPostProcessingRequested = false;
314 private capturedDraft: VoiceDraftSnapshot | null = null;
315 private recordingUri: string | null = null;
316 private readonly ownedRecordingUris = new Set<string>();
317 private recordingConfigured = false;
318 private finishing = false;
319 private retryRecording: {
320 uri: string;
321 ownerKey: string;
322 transcription: PreparedVoiceTranscription;
323 } | null = null;
324​
325 constructor(dependencies: VoiceInputControllerDependencies) {
326 this.dependencies = dependencies;
327 }
328​
329 private get resolve(): M {
330 return this.dependencies.resolve ?? mFallback;
331 }
332​
333 private text(message: string): string {
334 return this.resolve(message);
335 }
336​
337 get currentState(): VoiceInputState {
338 return this.state;
339 }
340​
341 async start(): Promise<void> {
342 if (this.state.phase !== "idle" && this.state.phase !== "error") return;
343 const initiatingDraft = this.dependencies.readDraft();
344 if (!initiatingDraft) {
345 this.setError(
346 this.text(msg("This draft is no longer available.")),
347 "retry",
348 "draft-unavailable",
349 );
350 return;
351 }
352 let sessionToken: VoiceInputSession | null = null;
353 const operationToken = ++this.operationToken;
354 this.setState({ phase: "preparing", error: null, errorAction: null });
355​
356 try {
357 for (
358 let previousSession = activeSession;
359 previousSession?.abandoned;
360 previousSession = activeSession
361 ) {
362 await previousSession.released;
363 if (!this.isCurrent(operationToken)) return;
364 }
365 sessionToken = acquireSession();
366 if (!sessionToken) {
367 this.setError(
368 this.text(msg("Another voice recording is already active.")),
369 "retry",
370 "already-recording",
371 );
372 return;
373 }
374 this.sessionToken = sessionToken;
375 const abortController = new AbortController();
376 this.transcriptionAbortController = abortController;
377​
378 if (this.retryRecording && this.retryRecording.ownerKey !== initiatingDraft.ownerKey) {
379 this.retryRecording = null;
380 this.deleteOwnedRecordings();
381 }
382 if (this.retryRecording) {
383 this.recordingUri = this.retryRecording.uri;
384 this.capturedDraft = initiatingDraft;
385 this.transcription = this.retryRecording.transcription;
386 this.retryRecording = null;
387 await this.finishRecording(true, this.recordingUri);
388 return;
389 }
390 const transcriber = this.dependencies.getTranscriber();
391 if (!transcriber) {
392 this.setError(this.text(msg("Voice transcription is not available.")), null, "unavailable");
393 return;
394 }
395​
396 const permission = await this.dependencies.requestPermission();
397 if (!this.isCurrent(operationToken)) return;
398 if (!permission.granted) {
399 this.setError(
400 this.text(msg("Microphone access is required for voice input.")),
401 permission.canAskAgain ? "retry" : "settings",
402 "microphone-blocked",
403 );
404 return;
405 }
406​
407 try {
408 this.transcription = await runTranscriptionOperation(() =>
409 transcriber.prepare({ signal: abortController.signal }),
410 );
411 } catch (error) {
412 if (this.isCurrent(operationToken))
413 this.setFailure(preparationFailure(error, this.resolve), "retry");
414 return;
415 }
416 if (!this.isCurrent(operationToken)) return;
417​
418 await this.dependencies.configureRecording();
419 this.recordingConfigured = true;
420 if (!this.isCurrent(operationToken)) return;
421 await this.dependencies.recorder.prepareToRecordAsync(abortController.signal);
422 if (!this.isCurrent(operationToken)) return;
423 this.recordingUri = this.dependencies.recorder.uri;
424 this.rememberRecordingUri(this.recordingUri);
425​
426 const capturedDraft = this.dependencies.readDraft();
427 if (!capturedDraft || capturedDraft.ownerKey !== initiatingDraft.ownerKey) {
428 this.setError(
429 this.text(msg("This draft is no longer available.")),
430 "retry",
431 "draft-unavailable",
432 );
433 return;
434 }
435 this.capturedDraft = capturedDraft;
436 if (this.transcription.start && this.recordingUri) {
437 const start = this.transcription.start;
438 const uri = this.recordingUri;
439 this.liveTranscription = runTranscriptionOperation(() =>
440 start(uri, { signal: abortController.signal }),
441 ).then(
442 (text) => ({ text }),
443 (error: unknown) => {
444 if (this.isCurrent(operationToken) && this.state.phase === "recording") {
445 const failure = transcriptionFailure(error, this.resolve);
446 void this.discardRecording(failure.message, failure.code);
447 }
448 return { error };
449 },
450 );
451 }
452 this.dependencies.recorder.record({ forDuration: VOICE_RECORDING_LIMIT_SECONDS });
453 this.setState({ phase: "recording", error: null, errorAction: null });
454 } catch (error) {
455 if (this.isCurrent(operationToken))
456 this.setError(
457 isMicrophonePermissionError(error)
458 ? this.text(MICROPHONE_PERMISSION_ERROR)
459 : this.text(msg("Could not start voice recording.")),
460 "retry",
461 isMicrophonePermissionError(error) ? "microphone-blocked" : "start-failed",
462 );
463 } finally {
464 if (sessionToken && this.sessionToken === sessionToken) {
465 if (this.isCurrent(operationToken) && this.state.phase === "error") {
466 await this.releaseResources();
467 } else if (!this.isCurrent(operationToken) && !this.finishing) {
468 await this.releaseResources();
469 }
470 }
471 }
472 }
473​
474 stop(): Promise<void> {
475 if (this.state.phase !== "recording") return Promise.resolve();
476 return this.finishRecording(false, null);
477 }
478​
479 cancel(): void {
480 switch (this.state.phase) {
481 case "idle":
482 return;
483 case "error":
484 this.retryRecording = null;
485 this.deleteOwnedRecordings();
486 this.setState(IDLE_STATE);
487 return;
488 case "preparing":
489 this.invalidateOperation();
490 this.setState(IDLE_STATE);
491 return;
492 case "recording":
493 this.discardRecording(null);
494 return;
495 case "transcribing":
496 case "post-processing":
497 this.invalidateOperation();
498 this.setState(IDLE_STATE);
499 return;
500 }
501 }
502​
503 skipPostProcessing(): void {
504 if (this.state.phase !== "post-processing") return;
505 this.skipPostProcessingRequested = true;
506 this.postProcessingAbortController?.abort();
507 }
508​
509 interruptRecording(
510 message?: string,
511 completedUri: string | null = null,
512 code?: VoiceInputErrorCode,
513 ): Promise<void> | void {
514 const failure: VoiceInputFailure =
515 message === undefined
516 ? { message: this.text(msg("Voice recording was interrupted.")), code: "interrupted" }
517 : code === undefined
518 ? { message }
519 : { message, code };
520 if (this.state.phase === "preparing") {
521 this.invalidateOperation();
522 this.setFailure(failure, "retry");
523 return;
524 }
525 if (this.state.phase !== "recording") return;
526 this.rememberRecordingUri(completedUri);
527 this.recordingUri = completedUri ?? this.recordingUri;
528 return this.discardRecording(failure.message, failure.code);
529 }
530​
531 appMovedToBackground(): Promise<void> | void {
532 return this.interruptRecording(
533 this.state.phase === "preparing"
534 ? this.text(msg("Voice input stopped when the app moved to the background."))
535 : undefined,
536 );
537 }
538​
539 handleRecorderStatus(status: VoiceRecorderStatus): Promise<void> | void {
540 if (this.state.phase !== "recording") return;
541 if (status.url && this.recordingUri && status.url !== this.recordingUri) return;
542 if (status.hasError) {
543 return this.interruptRecording(status.error ?? undefined, status.url);
544 }
545 if (status.isFinished) {
546 if (!status.url) {
547 return this.interruptRecording();
548 }
549 return this.finishRecording(true, status.url);
550 }
551 }
552​
553 ownerChanged(): void {
554 if (this.state.phase === "idle") return;
555 this.cancel();
556 }
557​
558 dispose(): void {
559 switch (this.state.phase) {
560 case "idle":
561 return;
562 case "error":
563 this.cancel();
564 return;
565 case "recording":
566 this.discardRecording(null);
567 return;
568 default:
569 this.invalidateOperation();
570 this.setState(IDLE_STATE);
571 }
572 }
573​
574 private async finishRecording(
575 alreadyStopped: boolean,
576 completedUri: string | null,
577 ): Promise<void> {
578 if (this.finishing || (this.state.phase !== "recording" && this.state.phase !== "preparing"))
579 return;
580 this.finishing = true;
581 const operationToken = this.operationToken;
582 this.setState({ phase: "transcribing", error: null, errorAction: null });
583​
584 try {
585 if (!alreadyStopped) await this.dependencies.recorder.stop();
586 await this.releaseAudioSession();
587 this.recordingUri = completedUri ?? this.dependencies.recorder.uri ?? this.recordingUri;
588 this.rememberRecordingUri(this.recordingUri);
589 if (!this.isCurrent(operationToken)) return;
590 const transcription = this.transcription;
591 const recordingUri = this.recordingUri;
592 if (
593 !transcription ||
594 (!transcription.streaming && !recordingUri) ||
595 !this.transcriptionAbortController ||
596 !this.capturedDraft
597 ) {
598 this.setError(
599 this.text(msg("Could not finish voice recording.")),
600 "retry",
601 "finish-failed",
602 );
603 return;
604 }
605​
606 const signal = this.transcriptionAbortController.signal;
607 const capturedDraft = this.capturedDraft;
608 let transcript: string;
609 try {
610 const live = this.liveTranscription ? await this.liveTranscription : null;
611 if (live && "error" in live) throw live.error;
612 transcript =
613 live?.text ??
614 (await runTranscriptionOperation(() =>
615 transcription.streaming
616 ? transcription.streaming.finish({ signal })
617 : transcription.transcribe(recordingUri!, { signal }),
618 ));
619 } catch (error) {
620 if (this.isCurrent(operationToken)) {
621 if (
622 this.dependencies.retryFailedRecording &&
623 errorCode(error) !== "preparation-failed" &&
624 !this.liveTranscription &&
625 !transcription.streaming &&
626 recordingUri
627 ) {
628 this.retryRecording = {
629 uri: recordingUri,
630 ownerKey: capturedDraft.ownerKey,
631 transcription,
632 };
633 }
634 this.setFailure(transcriptionFailure(error, this.resolve), "retry");
635 }
636 return;
637 }
638 if (!this.isCurrent(operationToken)) return;
639​
640 const postProcessingAbortController = new AbortController();
641 const cleanup =
642 transcript.trim().length > 0
643 ? this.dependencies.postProcess?.(transcript, {
644 signal: postProcessingAbortController.signal,
645 draft: capturedDraft,
646 })
647 : null;
648 if (cleanup) {
649 this.setState({ phase: "post-processing", error: null, errorAction: null });
650 this.postProcessingAbortController = postProcessingAbortController;
651 this.skipPostProcessingRequested = false;
652 const rawTranscript = transcript;
653 try {
654 // Skip resolves immediately with the raw transcript; the abort signal tells the
655 // provider request to stop but its settlement is not awaited.
656 transcript = await Promise.race([
657 cleanup,
658 new Promise<string>((resolve) =>
659 postProcessingAbortController.signal.addEventListener(
660 "abort",
661 () => resolve(rawTranscript),
662 { once: true },
663 ),
664 ),
665 ]);
666 } catch (error) {
667 if (!this.skipPostProcessingRequested) {
668 this.dependencies.onPostProcessingError?.(error);
669 }
670 }
671 if (!this.isCurrent(operationToken)) return;
672 }
673​
674 const result = resolveTranscriptCommit(
675 capturedDraft,
676 this.dependencies.readDraft(),
677 transcript,
678 transcription.locale,
679 );
680 if (result.kind === "stale") {
681 this.setError(
682 this.text(
683 msg("The draft changed while voice input was running. The transcript was not added."),
684 ),
685 "retry",
686 "draft-changed",
687 );
688 return;
689 }
690 if (result.kind === "empty") {
691 this.setError(this.text(msg("No speech was detected.")), "retry", "no-speech");
692 return;
693 }
694​
695 this.dependencies.commitDraft(result.text, result.selection);
696 this.setState(IDLE_STATE);
697 } catch {
698 if (this.isCurrent(operationToken)) {
699 this.setError(
700 this.text(msg("Could not finish voice recording.")),
701 "retry",
702 "finish-failed",
703 );
704 }
705 } finally {
706 this.finishing = false;
707 await this.releaseResources();
708 }
709 }
710​
711 private async discardRecording(
712 error: string | null,
713 errorCode?: VoiceInputErrorCode,
714 ): Promise<void> {
715 this.invalidateOperation();
716 this.setState(
717 error
718 ? errorCode === undefined
719 ? { phase: "error", error, errorAction: "retry" }
720 : { phase: "error", error, errorAction: "retry", errorCode }
721 : { phase: "idle", error: null, errorAction: null },
722 );
723 await this.releaseResources();
724 }
725​
726 private async releaseResources(): Promise<void> {
727 this.transcriptionAbortController?.abort();
728 this.postProcessingAbortController?.abort();
729 this.rememberRecordingUri(this.recordingUri);
730 try {
731 this.rememberRecordingUri(this.dependencies.recorder.uri);
732 } catch {}
733 if (this.recordingConfigured) {
734 try {
735 await this.dependencies.recorder.stop();
736 } catch {}
737 }
738 await this.liveTranscription;
739 this.liveTranscription = null;
740 this.recordingUri = null;
741 this.deleteOwnedRecordings();
742 await this.releaseAudioSession();
743 releaseSession(this.sessionToken);
744 this.sessionToken = null;
745 this.capturedDraft = null;
746 this.transcription = null;
747 this.transcriptionAbortController = null;
748 this.postProcessingAbortController = null;
749 this.skipPostProcessingRequested = false;
750 }
751​
752 private deleteOwnedRecordings(): void {
753 for (const uri of this.ownedRecordingUris) {
754 if (uri === this.retryRecording?.uri) continue;
755 try {
756 this.dependencies.deleteRecording(uri);
757 } catch {}
758 }
759 this.ownedRecordingUris.clear();
760 if (this.retryRecording) this.ownedRecordingUris.add(this.retryRecording.uri);
761 }
762​
763 private rememberRecordingUri(uri: string | null): void {
764 if (uri) this.ownedRecordingUris.add(uri);
765 }
766​
767 private async releaseAudioSession(): Promise<void> {
768 if (!this.recordingConfigured) return;
769 try {
770 await this.dependencies.releaseRecording();
771 this.recordingConfigured = false;
772 } catch {}
773 }
774​
775 private invalidateOperation(): void {
776 this.operationToken += 1;
777 if (this.sessionToken) this.sessionToken.abandoned = true;
778 this.transcriptionAbortController?.abort();
779 this.postProcessingAbortController?.abort();
780 }
781​
782 private isCurrent(operationToken: number): boolean {
783 return operationToken === this.operationToken;
784 }
785​
786 private setError(
787 error: string,
788 errorAction: VoiceInputState["errorAction"],
789 errorCode?: VoiceInputErrorCode,
790 ): void {
791 this.setState(
792 errorCode === undefined
793 ? { phase: "error", error, errorAction }
794 : { phase: "error", error, errorAction, errorCode },
795 );
796 }
797​
798 private setFailure(failure: VoiceInputFailure, errorAction: VoiceInputState["errorAction"]) {
799 this.setError(failure.message, errorAction, failure.code);
800 }
801​
802 private setState(state: VoiceInputState): void {
803 this.state = state;
804 this.dependencies.onStateChange(state);
805 }
807​
808export function resetVoiceInputGlobalsForTests(): void {
809 activeSession = null;
810 activeTranscriptionOperation = null;