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