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

controller.ts

515 lines15.9 KB

1import { replaceTextRange } from "@t3tools/shared/composerTrigger";
2​
3import {
4 VoiceTranscriptionError,
5 type PreparedVoiceTranscription,
6 type VoiceTranscriber,
7} from "./transcription.ts";
8​
9export const VOICE_RECORDING_LIMIT_SECONDS = 5 * 60;
10​
11export type VoiceInputPhase = "idle" | "preparing" | "recording" | "transcribing" | "error";
12​
13export type VoiceInputState = {
14 readonly phase: VoiceInputPhase;
15 readonly error: string | null;
16 readonly errorAction: "retry" | "settings" | null;
17};
18​
19export function voiceInputBlocksSubmission(state: VoiceInputState): boolean {
20 return (
21 state.phase === "preparing" || state.phase === "recording" || state.phase === "transcribing"
22 );
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(signal?: AbortSignal): Promise<void>;
42 record(options: { readonly forDuration: number }): void;
43 stop(): Promise<void>;
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 };
123​
124type VoiceInputSession = {
125 abandoned: boolean;
126 readonly released: Promise<void>;
127 readonly release: () => void;
128};
129​
130let activeSession: VoiceInputSession | null = null;
131let activeTranscriptionOperation: Promise<unknown> | null = null;
132​
133function acquireSession(): VoiceInputSession | null {
134 if (activeSession) return null;
135 const { promise, resolve } = Promise.withResolvers<void>();
136 const token = { abandoned: false, released: promise, release: resolve };
137 activeSession = token;
138 return token;
140​
141function releaseSession(token: VoiceInputSession | null): void {
142 if (token && activeSession === token) {
143 activeSession = null;
144 token.release();
145 }
147​
148async function runTranscriptionOperation<T>(operation: () => Promise<T>): Promise<T> {
149 if (activeTranscriptionOperation) {
150 throw new Error("voice-operation-busy");
151 }
152​
153 const promise = operation();
154 activeTranscriptionOperation = promise;
155 try {
156 return await promise;
157 } finally {
158 if (activeTranscriptionOperation === promise) activeTranscriptionOperation = null;
159 }
161​
162function errorCode(error: unknown): string | null {
163 if (typeof error !== "object" || error === null || !("code" in error)) return null;
164 return typeof error.code === "string" ? error.code : null;
166​
167function preparationErrorMessage(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 if (errorCode(error) === "unsupported-locale") {
172 return "Voice transcription is not available for this language.";
173 }
174 return error instanceof VoiceTranscriptionError
175 ? error.message
176 : "Could not prepare voice transcription.";
178​
179function transcriptionErrorMessage(error: unknown): string {
180 if (error instanceof Error && error.message === "voice-operation-busy") {
181 return "Voice transcription is still finishing. Try again shortly.";
182 }
183 return error instanceof VoiceTranscriptionError
184 ? error.message
185 : "Could not transcribe this recording.";
187​
188const IDLE_STATE: VoiceInputState = { phase: "idle", error: null, errorAction: null };
189​
190export class VoiceInputController {
191 private readonly dependencies: VoiceInputControllerDependencies;
192 private state: VoiceInputState = IDLE_STATE;
193 private operationToken = 0;
194 private sessionToken: VoiceInputSession | null = null;
195 private transcription: PreparedVoiceTranscription | null = null;
196 private transcriptionAbortController: AbortController | null = null;
197 private capturedDraft: VoiceDraftSnapshot | null = null;
198 private recordingUri: string | null = null;
199 private readonly ownedRecordingUris = new Set<string>();
200 private recordingConfigured = false;
201 private finishing = false;
202​
203 constructor(dependencies: VoiceInputControllerDependencies) {
204 this.dependencies = dependencies;
205 }
206​
207 get currentState(): VoiceInputState {
208 return this.state;
209 }
210​
211 async start(): Promise<void> {
212 if (this.state.phase !== "idle" && this.state.phase !== "error") return;
213 const initiatingDraft = this.dependencies.readDraft();
214 if (!initiatingDraft) {
215 this.setError("This draft is no longer available.", "retry");
216 return;
217 }
218 let sessionToken: VoiceInputSession | null = null;
219 const operationToken = ++this.operationToken;
220 this.setState({ phase: "preparing", error: null, errorAction: null });
221​
222 try {
223 for (
224 let previousSession = activeSession;
225 previousSession?.abandoned;
226 previousSession = activeSession
227 ) {
228 await previousSession.released;
229 if (!this.isCurrent(operationToken)) return;
230 }
231 sessionToken = acquireSession();
232 if (!sessionToken) {
233 this.setError("Another voice recording is already active.", "retry");
234 return;
235 }
236 this.sessionToken = sessionToken;
237 const abortController = new AbortController();
238 this.transcriptionAbortController = abortController;
239​
240 const transcriber = this.dependencies.getTranscriber();
241 if (!transcriber) {
242 this.setError("Voice transcription is not available.", null);
243 return;
244 }
245​
246 const permission = await this.dependencies.requestPermission();
247 if (!this.isCurrent(operationToken)) return;
248 if (!permission.granted) {
249 this.setError(
250 "Microphone access is required for voice input.",
251 permission.canAskAgain ? "retry" : "settings",
252 );
253 return;
254 }
255​
256 try {
257 this.transcription = await runTranscriptionOperation(() =>
258 transcriber.prepare({ signal: abortController.signal }),
259 );
260 } catch (error) {
261 if (this.isCurrent(operationToken)) this.setError(preparationErrorMessage(error), "retry");
262 return;
263 }
264 if (!this.isCurrent(operationToken)) return;
265​
266 await this.dependencies.configureRecording();
267 this.recordingConfigured = true;
268 if (!this.isCurrent(operationToken)) return;
269 await this.dependencies.recorder.prepareToRecordAsync(abortController.signal);
270 if (!this.isCurrent(operationToken)) return;
271 this.recordingUri = this.dependencies.recorder.uri;
272 this.rememberRecordingUri(this.recordingUri);
273​
274 const capturedDraft = this.dependencies.readDraft();
275 if (!capturedDraft || capturedDraft.ownerKey !== initiatingDraft.ownerKey) {
276 this.setError("This draft is no longer available.", "retry");
277 return;
278 }
279 this.capturedDraft = capturedDraft;
280 this.dependencies.recorder.record({ forDuration: VOICE_RECORDING_LIMIT_SECONDS });
281 this.setState({ phase: "recording", error: null, errorAction: null });
282 } catch {
283 if (this.isCurrent(operationToken))
284 this.setError("Could not start voice recording.", "retry");
285 } finally {
286 if (sessionToken && this.sessionToken === sessionToken) {
287 if (this.isCurrent(operationToken) && this.state.phase === "error") {
288 await this.releaseResources();
289 } else if (!this.isCurrent(operationToken) && !this.finishing) {
290 await this.releaseResources();
291 }
292 }
293 }
294 }
295​
296 stop(): Promise<void> {
297 if (this.state.phase !== "recording") return Promise.resolve();
298 return this.finishRecording(false, null);
299 }
300​
301 cancel(): void {
302 switch (this.state.phase) {
303 case "idle":
304 return;
305 case "error":
306 this.setState(IDLE_STATE);
307 return;
308 case "preparing":
309 this.invalidateOperation();
310 this.setState(IDLE_STATE);
311 return;
312 case "recording":
313 this.discardRecording(null);
314 return;
315 case "transcribing":
316 this.invalidateOperation();
317 this.setState(IDLE_STATE);
318 return;
319 }
320 }
321​
322 interruptRecording(
323 message = "Voice recording was interrupted.",
324 completedUri: string | null = null,
325 ): Promise<void> | void {
326 if (this.state.phase !== "recording") return;
327 this.rememberRecordingUri(completedUri);
328 this.recordingUri = completedUri ?? this.recordingUri;
329 return this.discardRecording(message);
330 }
331​
332 appMovedToBackground(): Promise<void> | void {
333 if (this.state.phase === "preparing") {
334 this.invalidateOperation();
335 this.setError("Voice input stopped when the app moved to the background.", "retry");
336 return;
337 }
338 return this.interruptRecording();
339 }
340​
341 handleRecorderStatus(status: VoiceRecorderStatus): Promise<void> | void {
342 if (this.state.phase !== "recording") return;
343 if (status.hasError) {
344 return this.interruptRecording(
345 status.error ?? "Voice recording was interrupted.",
346 status.url,
347 );
348 }
349 if (status.isFinished) {
350 if (!status.url) {
351 return this.interruptRecording();
352 }
353 return this.finishRecording(true, status.url);
354 }
355 }
356​
357 ownerChanged(): void {
358 if (this.state.phase === "idle") return;
359 this.cancel();
360 }
361​
362 dispose(): void {
363 if (this.state.phase === "recording") {
364 this.discardRecording(null);
365 return;
366 }
367 if (this.state.phase === "preparing" || this.state.phase === "transcribing") {
368 this.invalidateOperation();
369 this.setState(IDLE_STATE);
370 }
371 }
372​
373 private async finishRecording(
374 alreadyStopped: boolean,
375 completedUri: string | null,
376 ): Promise<void> {
377 if (this.finishing || this.state.phase !== "recording") return;
378 this.finishing = true;
379 const operationToken = this.operationToken;
380 this.setState({ phase: "transcribing", error: null, errorAction: null });
381​
382 try {
383 if (!alreadyStopped) await this.dependencies.recorder.stop();
384 await this.releaseAudioSession();
385 this.recordingUri = completedUri ?? this.dependencies.recorder.uri ?? this.recordingUri;
386 this.rememberRecordingUri(this.recordingUri);
387 if (!this.isCurrent(operationToken)) return;
388 if (
389 !this.recordingUri ||
390 !this.transcription ||
391 !this.transcriptionAbortController ||
392 !this.capturedDraft
393 ) {
394 this.setError("Could not finish voice recording.", "retry");
395 return;
396 }
397​
398 const recordingUri = this.recordingUri;
399 const transcription = this.transcription;
400 const signal = this.transcriptionAbortController.signal;
401 const capturedDraft = this.capturedDraft;
402 let transcript: string;
403 try {
404 transcript = await runTranscriptionOperation(() =>
405 transcription.transcribe(recordingUri, { signal }),
406 );
407 } catch (error) {
408 if (this.isCurrent(operationToken)) {
409 this.setError(transcriptionErrorMessage(error), "retry");
410 }
411 return;
412 }
413 if (!this.isCurrent(operationToken)) return;
414​
415 const result = resolveTranscriptCommit(
416 capturedDraft,
417 this.dependencies.readDraft(),
418 transcript,
419 transcription.locale,
420 );
421 if (result.kind === "stale") {
422 this.setError(
423 "The draft changed while voice input was running. The transcript was not added.",
424 "retry",
425 );
426 return;
427 }
428 if (result.kind === "empty") {
429 this.setError("No speech was detected.", "retry");
430 return;
431 }
432​
433 this.dependencies.commitDraft(result.text, result.selection);
434 this.setState(IDLE_STATE);
435 } catch {
436 if (this.isCurrent(operationToken)) {
437 this.setError("Could not finish voice recording.", "retry");
438 }
439 } finally {
440 this.finishing = false;
441 await this.releaseResources();
442 }
443 }
444​
445 private async discardRecording(error: string | null): Promise<void> {
446 this.invalidateOperation();
447 this.setState(
448 error
449 ? { phase: "error", error, errorAction: "retry" }
450 : { phase: "idle", error: null, errorAction: null },
451 );
452 await this.releaseResources();
453 }
454​
455 private async releaseResources(): Promise<void> {
456 this.rememberRecordingUri(this.recordingUri);
457 try {
458 this.rememberRecordingUri(this.dependencies.recorder.uri);
459 } catch {}
460 if (this.recordingConfigured) {
461 try {
462 await this.dependencies.recorder.stop();
463 } catch {}
464 }
465 this.recordingUri = null;
466 for (const uri of this.ownedRecordingUris) {
467 try {
468 this.dependencies.deleteRecording(uri);
469 } catch {}
470 }
471 this.ownedRecordingUris.clear();
472 await this.releaseAudioSession();
473 releaseSession(this.sessionToken);
474 this.sessionToken = null;
475 this.capturedDraft = null;
476 this.transcription = null;
477 this.transcriptionAbortController = null;
478 }
479​
480 private rememberRecordingUri(uri: string | null): void {
481 if (uri) this.ownedRecordingUris.add(uri);
482 }
483​
484 private async releaseAudioSession(): Promise<void> {
485 if (!this.recordingConfigured) return;
486 try {
487 await this.dependencies.releaseRecording();
488 this.recordingConfigured = false;
489 } catch {}
490 }
491​
492 private invalidateOperation(): void {
493 this.operationToken += 1;
494 if (this.sessionToken) this.sessionToken.abandoned = true;
495 this.transcriptionAbortController?.abort();
496 }
497​
498 private isCurrent(operationToken: number): boolean {
499 return operationToken === this.operationToken;
500 }
501​
502 private setError(error: string, errorAction: VoiceInputState["errorAction"]): void {
503 this.setState({ phase: "error", error, errorAction });
504 }
505​
506 private setState(state: VoiceInputState): void {
507 this.state = state;
508 this.dependencies.onStateChange(state);
509 }
511​
512export function resetVoiceInputGlobalsForTests(): void {
513 activeSession = null;
514 activeTranscriptionOperation = null;