Open History to see the last commit
1import { replaceTextRange } from "@t3tools/shared/composerTrigger";
2
3import type { PreparedVoiceTranscription, VoiceTranscriber } from "./transcription.ts";
4
5export const VOICE_RECORDING_LIMIT_SECONDS = 5 * 60;
6
7export type VoiceInputPhase = "idle" | "preparing" | "recording" | "transcribing" | "error";
8
9export type VoiceInputState = {
10 readonly phase: VoiceInputPhase;
11 readonly error: string | null;
12 readonly errorAction: "retry" | "settings" | null;
13};
14
15export function voiceInputBlocksSubmission(state: VoiceInputState): boolean {
16 return (
17 state.phase === "preparing" || state.phase === "recording" || state.phase === "transcribing"
18 );
19}
20
21export type VoiceDraftSnapshot = {
22 readonly ownerKey: string;
23 readonly text: string;
24 readonly selection: { readonly start: number; readonly end: number };
25 readonly revision: number;
26};
27
28export type VoiceRecorderStatus = {
29 readonly isFinished: boolean;
30 readonly hasError: boolean;
31 readonly error: string | null;
32 readonly url: string | null;
33};
34
35export interface VoiceRecorder {
36 readonly uri: string | null;
37 prepareToRecordAsync(): Promise<void>;
38 record(options: { readonly forDuration: number }): void;
39 stop(): Promise<void>;
40}
41
42export type VoiceInputControllerDependencies = {
43 readonly recorder: VoiceRecorder;
44 readonly getTranscriber: () => VoiceTranscriber | null;
45 readonly requestPermission: () => Promise<{
46 readonly granted: boolean;
47 readonly canAskAgain: boolean;
48 }>;
49 readonly configureRecording: () => Promise<void>;
50 readonly releaseRecording: () => Promise<void>;
51 readonly deleteRecording: (uri: string) => void;
52 readonly readDraft: () => VoiceDraftSnapshot | null;
53 readonly commitDraft: (
54 text: string,
55 selection: { readonly start: number; readonly end: number },
56 ) => void;
57 readonly onStateChange: (state: VoiceInputState) => void;
58};
59
60type TranscriptCommitResult =
61 | {
62 readonly kind: "commit";
63 readonly text: string;
64 readonly selection: { readonly start: number; readonly end: number };
65 }
66 | { readonly kind: "stale" }
67 | { readonly kind: "empty" };
68
69export function resolveTranscriptCommit(
70 captured: VoiceDraftSnapshot,
71 current: VoiceDraftSnapshot | null,
72 transcript: string,
73 locale: string,
74): TranscriptCommitResult {
75 if (
76 !current ||
77 current.ownerKey !== captured.ownerKey ||
78 current.text !== captured.text ||
79 current.revision !== captured.revision
80 ) {
81 return { kind: "stale" };
82 }
83
84 const replacement = transcript.trim();
85 if (replacement.length === 0) {
86 return { kind: "empty" };
87 }
88
89 const isEmptySelection = captured.selection.start === captured.selection.end;
90 const normalizedLocale = locale.replaceAll("_", "-").toLowerCase();
91 const usesEnglishSpacing = normalizedLocale === "en" || normalizedLocale.startsWith("en-");
92 let insertion = replacement;
93 if (isEmptySelection && usesEnglishSpacing) {
94 const left = captured.text[captured.selection.start - 1];
95 const right = captured.text[captured.selection.start];
96 const leftNeedsBoundary =
97 left !== undefined &&
98 /[A-Za-z0-9.!?,:;)\]}'"]/.test(left) &&
99 (right === undefined || /\s/.test(right));
100 const rightNeedsBoundary =
101 right !== undefined &&
102 /[A-Za-z0-9([{'"]/.test(right) &&
103 (left === undefined || /\s/.test(left));
104 insertion = `${leftNeedsBoundary ? " " : ""}${replacement}${rightNeedsBoundary ? " " : ""}`;
105 }
106
107 const result = replaceTextRange(
108 captured.text,
109 captured.selection.start,
110 captured.selection.end,
111 insertion,
112 );
113 return {
114 kind: "commit",
115 text: result.text,
116 selection: { start: result.cursor, end: result.cursor },
117 };
118}
119
120type VoiceInputSession = {
121 abandoned: boolean;
122 readonly released: Promise<void>;
123 readonly release: () => void;
124};
125
126let activeSession: VoiceInputSession | null = null;
127let activeTranscriptionOperation: Promise<unknown> | null = null;
128
129function acquireSession(): VoiceInputSession | null {
130 if (activeSession) return null;
131 const { promise, resolve } = Promise.withResolvers<void>();
132 const token = { abandoned: false, released: promise, release: resolve };
133 activeSession = token;
134 return token;
135}
136
137function releaseSession(token: VoiceInputSession | null): void {
138 if (token && activeSession === token) {
139 activeSession = null;
140 token.release();
141 }
142}
143
144async function runTranscriptionOperation<T>(operation: () => Promise<T>): Promise<T> {
145 if (activeTranscriptionOperation) {
146 throw new Error("voice-operation-busy");
147 }
148
149 const promise = operation();
150 activeTranscriptionOperation = promise;
151 try {
152 return await promise;
153 } finally {
154 if (activeTranscriptionOperation === promise) activeTranscriptionOperation = null;
155 }
156}
157
158function errorCode(error: unknown): string | null {
159 if (typeof error !== "object" || error === null || !("code" in error)) return null;
160 return typeof error.code === "string" ? error.code : null;
161}
162
163function preparationErrorMessage(error: unknown): string {
164 if (error instanceof Error && error.message === "voice-operation-busy") {
165 return "Voice transcription is still finishing. Try again shortly.";
166 }
167 if (errorCode(error) === "unsupported-locale") {
168 return "Voice transcription is not available for this language.";
169 }
170 return "Could not prepare voice transcription.";
171}
172
173function transcriptionErrorMessage(error: unknown): string {
174 if (error instanceof Error && error.message === "voice-operation-busy") {
175 return "Voice transcription is still finishing. Try again shortly.";
176 }
177 return "Could not transcribe this recording.";
178}
179
180const IDLE_STATE: VoiceInputState = { phase: "idle", error: null, errorAction: null };
181
182export class VoiceInputController {
183 private readonly dependencies: VoiceInputControllerDependencies;
184 private state: VoiceInputState = IDLE_STATE;
185 private operationToken = 0;
186 private sessionToken: VoiceInputSession | null = null;
187 private transcription: PreparedVoiceTranscription | null = null;
188 private transcriptionAbortController: AbortController | null = null;
189 private capturedDraft: VoiceDraftSnapshot | null = null;
190 private recordingUri: string | null = null;
191 private readonly ownedRecordingUris = new Set<string>();
192 private recordingConfigured = false;
193 private finishing = false;
194
195 constructor(dependencies: VoiceInputControllerDependencies) {
196 this.dependencies = dependencies;
197 }
198
199 get currentState(): VoiceInputState {
200 return this.state;
201 }
202
203 async start(): Promise<void> {
204 if (this.state.phase !== "idle" && this.state.phase !== "error") return;
205 const initiatingDraft = this.dependencies.readDraft();
206 if (!initiatingDraft) {
207 this.setError("This draft is no longer available.", "retry");
208 return;
209 }
210 let sessionToken: VoiceInputSession | null = null;
211 const operationToken = ++this.operationToken;
212 this.setState({ phase: "preparing", error: null, errorAction: null });
213
214 try {
215 for (
216 let previousSession = activeSession;
217 previousSession?.abandoned;
218 previousSession = activeSession
219 ) {
220 await previousSession.released;
221 if (!this.isCurrent(operationToken)) return;
222 }
223 sessionToken = acquireSession();
224 if (!sessionToken) {
225 this.setError("Another voice recording is already active.", "retry");
226 return;
227 }
228 this.sessionToken = sessionToken;
229 const abortController = new AbortController();
230 this.transcriptionAbortController = abortController;
231
232 const transcriber = this.dependencies.getTranscriber();
233 if (!transcriber) {
234 this.setError("Voice transcription is not available.", null);
235 return;
236 }
237
238 const permission = await this.dependencies.requestPermission();
239 if (!this.isCurrent(operationToken)) return;
240 if (!permission.granted) {
241 this.setError(
242 "Microphone access is required for voice input.",
243 permission.canAskAgain ? "retry" : "settings",
244 );
245 return;
246 }
247
248 try {
249 this.transcription = await runTranscriptionOperation(() =>
250 transcriber.prepare({ signal: abortController.signal }),
251 );
252 } catch (error) {
253 if (this.isCurrent(operationToken)) this.setError(preparationErrorMessage(error), "retry");
254 return;
255 }
256 if (!this.isCurrent(operationToken)) return;
257
258 await this.dependencies.configureRecording();
259 this.recordingConfigured = true;
260 if (!this.isCurrent(operationToken)) return;
261 await this.dependencies.recorder.prepareToRecordAsync();
262 if (!this.isCurrent(operationToken)) return;
263 this.recordingUri = this.dependencies.recorder.uri;
264 this.rememberRecordingUri(this.recordingUri);
265
266 const capturedDraft = this.dependencies.readDraft();
267 if (!capturedDraft || capturedDraft.ownerKey !== initiatingDraft.ownerKey) {
268 this.setError("This draft is no longer available.", "retry");
269 return;
270 }
271 this.capturedDraft = capturedDraft;
272 this.dependencies.recorder.record({ forDuration: VOICE_RECORDING_LIMIT_SECONDS });
273 this.setState({ phase: "recording", error: null, errorAction: null });
274 } catch {
275 if (this.isCurrent(operationToken))
276 this.setError("Could not start voice recording.", "retry");
277 } finally {
278 if (sessionToken && this.sessionToken === sessionToken) {
279 if (this.isCurrent(operationToken) && this.state.phase === "error") {
280 await this.releaseResources();
281 } else if (!this.isCurrent(operationToken) && !this.finishing) {
282 await this.releaseResources();
283 }
284 }
285 }
286 }
287
288 stop(): Promise<void> {
289 if (this.state.phase !== "recording") return Promise.resolve();
290 return this.finishRecording(false, null);
291 }
292
293 cancel(): void {
294 switch (this.state.phase) {
295 case "idle":
296 return;
297 case "error":
298 this.setState(IDLE_STATE);
299 return;
300 case "preparing":
301 this.invalidateOperation();
302 this.setState(IDLE_STATE);
303 return;
304 case "recording":
305 this.discardRecording(null);
306 return;
307 case "transcribing":
308 this.invalidateOperation();
309 this.setState(IDLE_STATE);
310 return;
311 }
312 }
313
314 interruptRecording(
315 message = "Voice recording was interrupted.",
316 completedUri: string | null = null,
317 ): Promise<void> | void {
318 if (this.state.phase !== "recording") return;
319 this.rememberRecordingUri(completedUri);
320 this.recordingUri = completedUri ?? this.recordingUri;
321 return this.discardRecording(message);
322 }
323
324 appMovedToBackground(): Promise<void> | void {
325 if (this.state.phase === "preparing") {
326 this.invalidateOperation();
327 this.setError("Voice input stopped when the app moved to the background.", "retry");
328 return;
329 }
330 return this.interruptRecording();
331 }
332
333 handleRecorderStatus(status: VoiceRecorderStatus): Promise<void> | void {
334 if (this.state.phase !== "recording") return;
335 if (status.hasError) {
336 return this.interruptRecording(
337 status.error ?? "Voice recording was interrupted.",
338 status.url,
339 );
340 }
341 if (status.isFinished) {
342 if (!status.url) {
343 return this.interruptRecording();
344 }
345 return this.finishRecording(true, status.url);
346 }
347 }
348
349 ownerChanged(): void {
350 if (this.state.phase === "idle") return;
351 this.cancel();
352 }
353
354 dispose(): void {
355 if (this.state.phase === "recording") {
356 this.discardRecording(null);
357 return;
358 }
359 if (this.state.phase === "preparing" || this.state.phase === "transcribing") {
360 this.invalidateOperation();
361 this.setState(IDLE_STATE);
362 }
363 }
364
365 private async finishRecording(
366 alreadyStopped: boolean,
367 completedUri: string | null,
368 ): Promise<void> {
369 if (this.finishing || this.state.phase !== "recording") return;
370 this.finishing = true;
371 const operationToken = this.operationToken;
372 this.setState({ phase: "transcribing", error: null, errorAction: null });
373
374 try {
375 if (!alreadyStopped) await this.dependencies.recorder.stop();
376 await this.releaseAudioSession();
377 this.recordingUri = completedUri ?? this.dependencies.recorder.uri ?? this.recordingUri;
378 this.rememberRecordingUri(this.recordingUri);
379 if (!this.isCurrent(operationToken)) return;
380 if (
381 !this.recordingUri ||
382 !this.transcription ||
383 !this.transcriptionAbortController ||
384 !this.capturedDraft
385 ) {
386 this.setError("Could not finish voice recording.", "retry");
387 return;
388 }
389
390 const recordingUri = this.recordingUri;
391 const transcription = this.transcription;
392 const signal = this.transcriptionAbortController.signal;
393 const capturedDraft = this.capturedDraft;
394 let transcript: string;
395 try {
396 transcript = await runTranscriptionOperation(() =>
397 transcription.transcribe(recordingUri, { signal }),
398 );
399 } catch (error) {
400 if (this.isCurrent(operationToken)) {
401 this.setError(transcriptionErrorMessage(error), "retry");
402 }
403 return;
404 }
405 if (!this.isCurrent(operationToken)) return;
406
407 const result = resolveTranscriptCommit(
408 capturedDraft,
409 this.dependencies.readDraft(),
410 transcript,
411 transcription.locale,
412 );
413 if (result.kind === "stale") {
414 this.setError(
415 "The draft changed while voice input was running. The transcript was not added.",
416 "retry",
417 );
418 return;
419 }
420 if (result.kind === "empty") {
421 this.setError("No speech was detected.", "retry");
422 return;
423 }
424
425 this.dependencies.commitDraft(result.text, result.selection);
426 this.setState(IDLE_STATE);
427 } catch {
428 if (this.isCurrent(operationToken)) {
429 this.setError("Could not finish voice recording.", "retry");
430 }
431 } finally {
432 this.finishing = false;
433 await this.releaseResources();
434 }
435 }
436
437 private async discardRecording(error: string | null): Promise<void> {
438 this.invalidateOperation();
439 this.setState(
440 error
441 ? { phase: "error", error, errorAction: "retry" }
442 : { phase: "idle", error: null, errorAction: null },
443 );
444 try {
445 await this.dependencies.recorder.stop();
446 } catch {
447 } finally {
448 await this.releaseResources();
449 }
450 }
451
452 private async releaseResources(): Promise<void> {
453 this.rememberRecordingUri(this.recordingUri);
454 try {
455 this.rememberRecordingUri(this.dependencies.recorder.uri);
456 } catch {}
457 this.recordingUri = null;
458 for (const uri of this.ownedRecordingUris) {
459 try {
460 this.dependencies.deleteRecording(uri);
461 } catch {}
462 }
463 this.ownedRecordingUris.clear();
464 await this.releaseAudioSession();
465 releaseSession(this.sessionToken);
466 this.sessionToken = null;
467 this.capturedDraft = null;
468 this.transcription = null;
469 this.transcriptionAbortController = null;
470 }
471
472 private rememberRecordingUri(uri: string | null): void {
473 if (uri) this.ownedRecordingUris.add(uri);
474 }
475
476 private async releaseAudioSession(): Promise<void> {
477 if (!this.recordingConfigured) return;
478 try {
479 await this.dependencies.releaseRecording();
480 this.recordingConfigured = false;
481 } catch {}
482 }
483
484 private invalidateOperation(): void {
485 this.operationToken += 1;
486 if (this.sessionToken) this.sessionToken.abandoned = true;
487 this.transcriptionAbortController?.abort();
488 }
489
490 private isCurrent(operationToken: number): boolean {
491 return operationToken === this.operationToken;
492 }
493
494 private setError(error: string, errorAction: VoiceInputState["errorAction"]): void {
495 this.setState({ phase: "error", error, errorAction });
496 }
497
498 private setState(state: VoiceInputState): void {
499 this.state = state;
500 this.dependencies.onStateChange(state);
501 }
502}
503
504export function resetVoiceInputGlobalsForTests(): void {
505 activeSession = null;
506 activeTranscriptionOperation = null;
507}