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