Open History to see the last commit
1import {
2 cancelEnvironmentSpeechModelDownload,
3 downloadEnvironmentSpeechModel,
4 getEnvironmentSpeechModels,
5 getEnvironmentSpeechStatus,
6 postProcessEnvironmentTranscript,
7 selectEnvironmentSpeechModel,
8 VoiceInputController,
9 voiceInputBlocksSubmission,
10 type VoiceDraftSnapshot,
11 type VoiceInputControllerDependencies,
12 type VoiceInputState,
13} from "@t3tools/client-runtime/voice-input";
14import type { PreparedConnection } from "@t3tools/client-runtime/connection";
15import { AuthOrchestrationOperateScope, CLOUD_SPEECH_LABELS } from "@t3tools/contracts";
16import type {
17 EnvironmentId,
18 EnvironmentSpeechModel,
19 EnvironmentSpeechStatus,
20 ProjectId,
21 SpeechPostProcessingOptions,
22 SpeechStreamText,
23 SpeechTranscriptionOptions,
24} from "@t3tools/contracts";
25import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
26import { chooseSetupSpeechModel, resolveSpeechVocabulary } from "@t3tools/shared/speech";
27import { useNavigate } from "@tanstack/react-router";
28import * as Option from "effect/Option";
29import { useEffect, useRef, useState } from "react";
30
31import { useStableCallback } from "~/hooks/useStableCallback";
32import { toastManager } from "../components/ui/toast";
33import {
34 useClientSettings,
35 useClientSettingsHydrated,
36 useEnvironmentSettings,
37} from "../hooks/useSettings";
38import { useEnvironment } from "../state/environments";
39import { useEnvironmentScope, usePreparedConnection } from "../state/session";
40import { createBrowserVoiceInputPlatform } from "./browserVoiceInput";
41import { preferredSpeechLanguages } from "./preferredSpeechLanguages";
42import { runEnvironmentSpeech } from "./runEnvironmentSpeech";
43import { bindAudioGrant, readCleanupGrant, useAudioChoice } from "./voiceConsent";
44
45const INITIAL_STATE: VoiceInputState = { phase: "idle", error: null, errorAction: null };
46const WAITING_STATE: VoiceInputState = { phase: "preparing", error: null, errorAction: null };
47const INITIAL_SETUP = {
48 open: false,
49 step: 0,
50 model: null as EnvironmentSpeechModel | null,
51 language: null as string | null,
52 downloading: false,
53 catalogFailed: false,
54 error: null as string | null,
55};
56
57// Every mounted editor shares one status probe per destination; starting a recording refreshes it.
58const statusProbes = new WeakMap<PreparedConnection, Promise<EnvironmentSpeechStatus>>();
59function probeSpeechStatus(prepared: PreparedConnection, refresh = false) {
60 const cached = refresh ? undefined : statusProbes.get(prepared);
61 if (cached) return cached;
62 const probe = runEnvironmentSpeech(getEnvironmentSpeechStatus(prepared));
63 statusProbes.set(prepared, probe);
64 probe.catch(() => {
65 if (statusProbes.get(prepared) === probe) statusProbes.delete(prepared);
66 });
67 return probe;
68}
69
70type DraftInput = {
71 readonly text: string;
72 readonly selection: { readonly start: number; readonly end: number };
73};
74
75function cleanupContext({ text, selection }: DraftInput): DraftInput {
76 const limit = 1_024;
77 const start = Math.max(0, Math.min(selection.start, text.length));
78 const end = Math.max(start, Math.min(selection.end, text.length));
79 const before = text.slice(Math.max(0, start - limit), start);
80 const selected = text.slice(start, Math.min(end, start + limit));
81 return {
82 text: before + selected + text.slice(end, end + limit),
83 selection: { start: before.length, end: before.length + selected.length },
84 };
85}
86
87type HookInput = {
88 /** The draft's own environment. Optional transcript cleanup runs there, never on the audio destination. */
89 readonly environmentId: EnvironmentId;
90 /** The draft's project: its vocabulary on that environment and its name become recognition hints. */
91 readonly projectId?: ProjectId | null | undefined;
92 readonly projectName?: string | null | undefined;
93 readonly ownerKey: string;
94 readonly draftText: string;
95 readonly disabled?: boolean | undefined;
96 /**
97 * Until a destination is chosen, voice input is offered and its first gesture opens Voice
98 * settings. False hides it instead, for editors whose draft would not survive the navigation.
99 */
100 readonly offerSetup?: boolean | undefined;
101 /** False keeps the transcript off the cleanup provider even when cleanup is on; the model test uses it. */
102 readonly cleanup?: boolean | undefined;
103 readonly readDraft: () => DraftInput;
104 readonly commitDraft: (
105 text: string,
106 selection: { readonly start: number; readonly end: number },
107 ) => void;
108};
109
110/**
111 * Microphone audio leaves this device only for the environment the person chose in
112 * Voice settings. Nothing is inferred from the primary or the draft's environment, and
113 * the recording is abandoned the moment that choice changes or its connection drops.
114 */
115export function useVoiceTranscriptionDestination() {
116 const hydrated = useClientSettingsHydrated();
117 const choice = useAudioChoice();
118 const grant = choice === "off" ? null : choice;
119 const environmentId = hydrated && grant ? grant.destination.environmentId : null;
120 const environment = useEnvironment(environmentId);
121 const connection = Option.getOrNull(usePreparedConnection(environmentId));
122 const canDictate = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
123 const cloud = grant?.destination.kind === "cloud" ? grant.destination : undefined;
124 const provider = cloud?.provider;
125 const model = cloud?.provider === "openrouter" ? cloud.model : undefined;
126 const supported =
127 environment?.serverConfig?.environment.capabilities[
128 provider ? "cloudVoiceTranscription" : "voiceTranscription"
129 ] === true;
130 return {
131 ...(hydrated && choice === null ? { offerFirstRunSetup: true } : {}),
132 environmentId,
133 ...(provider ? { cloudProvider: provider } : {}),
134 ...(model ? { cloudModel: model } : {}),
135 grantId: grant?.id ?? null,
136 label:
137 provider && environment
138 ? `${CLOUD_SPEECH_LABELS[provider]} via ${environment.label}`
139 : (environment?.label ?? null),
140 prepared: supported && canDictate ? connection : null,
141 };
142}
143
144export function useEnvironmentSpeechInput(input: HookInput) {
145 const navigate = useNavigate();
146 const destination = useVoiceTranscriptionDestination();
147 const prepared = destination.prepared;
148 const grantId = destination.grantId;
149 const cloudProvider = destination.cloudProvider;
150 const cloudModel = destination.cloudModel;
151 const draftCapabilities = useEnvironment(input.environmentId)?.serverConfig?.environment
152 .capabilities;
153 const originatingConnection = Option.getOrNull(usePreparedConnection(input.environmentId));
154 const canCleanUp = useEnvironmentScope(input.environmentId, AuthOrchestrationOperateScope);
155 const cleanupPrepared =
156 canCleanUp &&
157 (draftCapabilities?.voiceTranscription || draftCapabilities?.cloudVoiceTranscription)
158 ? originatingConnection
159 : null;
160 const clientSettings = useClientSettings();
161 const projectId = input.projectId ?? null;
162 const projectWords = useEnvironmentSettings(
163 input.environmentId,
164 (settings) => resolveProjectSettings(settings, projectId).settings.speechProjectCustomWords,
165 );
166 const [status, setStatus] = useState<{
167 readonly prepared: PreparedConnection;
168 readonly value: EnvironmentSpeechStatus | null;
169 } | null>(null);
170 const [controllerState, setControllerState] = useState({
171 prepared,
172 grantId,
173 value: INITIAL_STATE,
174 });
175 const [queuedStart, setQueuedStart] = useState<PreparedConnection | null>(null);
176 const [level, setLevel] = useState(0);
177 const [preview, setPreview] = useState<SpeechStreamText | null>(null);
178 const [setup, setSetup] = useState(INITIAL_SETUP);
179 const [previousOwner, setPreviousOwner] = useState({
180 key: input.ownerKey,
181 disabled: input.disabled,
182 });
183 if (controllerState.prepared !== prepared || controllerState.grantId !== grantId) {
184 setControllerState({ prepared, grantId, value: INITIAL_STATE });
185 setSetup(INITIAL_SETUP);
186 setQueuedStart(null);
187 setPreview(null);
188 setLevel(0);
189 }
190 if (previousOwner.key !== input.ownerKey || previousOwner.disabled !== input.disabled) {
191 setPreviousOwner({ key: input.ownerKey, disabled: input.disabled });
192 setQueuedStart(null);
193 setSetup(INITIAL_SETUP);
194 }
195 const state: VoiceInputState =
196 queuedStart === prepared && prepared
197 ? WAITING_STATE
198 : controllerState.prepared === prepared
199 ? controllerState.value
200 : INITIAL_STATE;
201
202 const controllerRef = useRef<VoiceInputController | null>(null);
203 const startRequestRef = useRef(0);
204 const pendingSubmissionRef = useRef<{
205 ownerKey: string;
206 submit: (text: string) => void;
207 text?: string;
208 } | null>(null);
209 const latestRef = useRef({ input, clientSettings, cleanupPrepared, projectWords });
210 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes committed props and settings to the asynchronous recording controller
211 useEffect(() => {
212 latestRef.current = { input, clientSettings, cleanupPrepared, projectWords };
213 });
214 const draftRevisionRef = useRef({ ownerKey: input.ownerKey, text: input.draftText, revision: 0 });
215 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- tracks committed draft revisions so a late transcript cannot overwrite an edited draft
216 useEffect(() => {
217 const revision = draftRevisionRef.current;
218 if (revision.ownerKey !== input.ownerKey || revision.text !== input.draftText) {
219 draftRevisionRef.current = {
220 ownerKey: input.ownerKey,
221 text: input.draftText,
222 revision: revision.revision + 1,
223 };
224 }
225 }, [input.ownerKey, input.draftText]);
226
227 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- owns the recording controller bound to the consented destination; it is disposed with the consent
228 useEffect(() => {
229 if (!prepared || !grantId || typeof navigator === "undefined") return;
230 const hasAudioConsent = bindAudioGrant(grantId);
231 let disposed = false;
232 let controller: VoiceInputController;
233 let recordingPreferences:
234 | {
235 readonly cleanup: SpeechPostProcessingOptions | null;
236 readonly cleanupGrant: string | null;
237 readonly environmentId: EnvironmentId;
238 }
239 | undefined;
240
241 const readDraft = (): VoiceDraftSnapshot => {
242 const current = latestRef.current.input;
243 const draft = current.readDraft();
244 const revision = draftRevisionRef.current;
245 if (revision.ownerKey !== current.ownerKey || revision.text !== draft.text) {
246 draftRevisionRef.current = {
247 ownerKey: current.ownerKey,
248 text: draft.text,
249 revision: revision.revision + 1,
250 };
251 }
252 return {
253 ownerKey: current.ownerKey,
254 text: draft.text,
255 selection: draft.selection,
256 revision: draftRevisionRef.current.revision,
257 };
258 };
259 const platform = createBrowserVoiceInputPlatform({
260 prepared,
261 cloudProvider,
262 cloudModel,
263 hasAudioConsent,
264 getTranscriptionOptions: (): SpeechTranscriptionOptions => {
265 const {
266 clientSettings: settings,
267 projectWords: project,
268 input: current,
269 } = latestRef.current;
270 const cleanupGrant = current.cleanup === false ? null : readCleanupGrant();
271 const cleanupEnabled = cleanupGrant !== null;
272 const cue =
273 cleanupEnabled && latestRef.current.cleanupPrepared ? settings.speechCorrectionWord : "";
274 const speechCustomWords = resolveSpeechVocabulary({
275 personal: settings.speechCustomWords,
276 project,
277 hints: [cue, current.projectName ?? ""],
278 });
279 recordingPreferences = {
280 cleanupGrant,
281 environmentId: current.environmentId,
282 cleanup: cleanupEnabled
283 ? {
284 speechCustomWords,
285 speechPostProcessingPrompt: settings.speechPostProcessingPrompt,
286 ...(cue.trim() ? { speechCorrectionWord: cue } : {}),
287 }
288 : null,
289 };
290 return {
291 speechLanguage: settings.speechLanguage,
292 speechTranslateToEnglish: settings.speechTranslateToEnglish,
293 speechCustomWords,
294 speechRemoveFillerWords: settings.speechRemoveFillerWords,
295 ...(cue.trim() ? { speechCorrectionWord: cue } : {}),
296 speechSilenceFiltering: settings.speechSilenceFiltering,
297 };
298 },
299 getMicrophoneId: () => latestRef.current.clientSettings.voiceMicrophone,
300 onLevel: setLevel,
301 onDurationLimit: () => void controller.stop(),
302 onText: (text) => {
303 if (!disposed) setPreview(text);
304 },
305 onError: (message) => {
306 if (!disposed) void controller.interruptRecording(message);
307 },
308 });
309 const postProcess: NonNullable<VoiceInputControllerDependencies["postProcess"]> = (
310 transcript,
311 options,
312 ) => {
313 const preferences = recordingPreferences;
314 const { input: current, cleanupPrepared: target } = latestRef.current;
315 if (
316 !preferences?.cleanup ||
317 !hasAudioConsent() ||
318 preferences.cleanupGrant !== readCleanupGrant() ||
319 current.cleanup === false ||
320 current.environmentId !== preferences.environmentId ||
321 current.ownerKey !== options.draft.ownerKey
322 )
323 return null;
324 if (!target)
325 return Promise.reject(
326 new Error("The draft's environment is unavailable for transcript cleanup."),
327 );
328 return runEnvironmentSpeech(
329 postProcessEnvironmentTranscript(
330 target,
331 transcript,
332 cleanupContext(options.draft),
333 preferences.cleanup,
334 () => hasAudioConsent() && preferences.cleanupGrant === readCleanupGrant(),
335 ),
336 options,
337 ).then((result) => result.text);
338 };
339 controller = new VoiceInputController({
340 retryFailedRecording: true,
341 recorder: platform.recorder,
342 getTranscriber: () => platform.transcriber,
343 requestPermission: async () => ({ granted: true, canAskAgain: true }),
344 configureRecording: async () => undefined,
345 releaseRecording: async () => platform.cancelRecording(),
346 deleteRecording: platform.deleteRecording,
347 postProcess,
348 onPostProcessingError: () =>
349 toastManager.add({
350 type: "warning",
351 title: "Transcript cleanup failed",
352 description: "The original transcript was added.",
353 }),
354 readDraft,
355 commitDraft: (text, selection) => {
356 if (latestRef.current.input.disabled) return;
357 latestRef.current.input.commitDraft(text, selection);
358 if (pendingSubmissionRef.current) pendingSubmissionRef.current.text = text;
359 },
360 onStateChange: (value) => {
361 if (disposed) return;
362 if (value.phase === "error") pendingSubmissionRef.current = null;
363 setControllerState({ prepared, grantId, value });
364 if (value.phase !== "recording" && value.phase !== "transcribing") setPreview(null);
365 },
366 });
367 controllerRef.current = controller;
368 return () => {
369 disposed = true;
370 pendingSubmissionRef.current = null;
371 startRequestRef.current += 1;
372 setQueuedStart(null);
373 controller.dispose();
374 if (controllerRef.current === controller) controllerRef.current = null;
375 };
376 }, [prepared, grantId, cloudProvider, cloudModel]);
377
378 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- probes the chosen environment's speech status once its connection is available
379 useEffect(() => {
380 if (!prepared || cloudProvider) return;
381 let disposed = false;
382 void probeSpeechStatus(prepared)
383 .then((value) => {
384 if (!disposed) setStatus({ prepared, value });
385 })
386 .catch(() => {
387 if (!disposed) setStatus({ prepared, value: null });
388 });
389 return () => {
390 disposed = true;
391 };
392 }, [prepared, cloudProvider]);
393 const currentStatus = !cloudProvider && status?.prepared === prepared ? status.value : null;
394 const setupModelId = setup.model?.id;
395
396 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- polls download progress while the setup dialog owns an active model download
397 useEffect(() => {
398 if (!setup.open || !setup.downloading || !prepared || !setupModelId) return;
399 let disposed = false;
400 let refreshing = false;
401 const timer = window.setInterval(() => {
402 if (refreshing) return;
403 refreshing = true;
404 void runEnvironmentSpeech(getEnvironmentSpeechModels(prepared))
405 .then((result) => {
406 if (disposed) return;
407 const model = result.models.find((candidate) => candidate.id === setupModelId) ?? null;
408 if (model) setSetup((current) => ({ ...current, model }));
409 })
410 .catch(() => undefined)
411 .finally(() => {
412 refreshing = false;
413 });
414 }, 1_000);
415 return () => {
416 disposed = true;
417 window.clearInterval(timer);
418 };
419 }, [prepared, setup.downloading, setup.open, setupModelId]);
420
421 const previousOwnerRef = useRef(input.ownerKey);
422 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- abandons the recording and any queued submission when the draft's owner changes
423 useEffect(() => {
424 if (previousOwnerRef.current === input.ownerKey && !input.disabled) return;
425 previousOwnerRef.current = input.ownerKey;
426 pendingSubmissionRef.current = null;
427 startRequestRef.current += 1;
428 controllerRef.current?.ownerChanged();
429 }, [input.ownerKey, input.disabled]);
430
431 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- delivers a queued submission only after the transcript has committed to the draft
432 useEffect(() => {
433 const pending = pendingSubmissionRef.current;
434 if (state.phase !== "idle" || !pending) return;
435 pendingSubmissionRef.current = null;
436 if (!input.disabled && pending.ownerKey === input.ownerKey && pending.text !== undefined)
437 pending.submit(pending.text);
438 }, [state, input.ownerKey, input.disabled]);
439
440 const submitAfterDictation = useStableCallback((submit: (text: string) => void) => {
441 if (latestRef.current.input.disabled || state.phase === "preparing") return;
442 const controller = controllerRef.current;
443 if (!controller || !voiceInputBlocksSubmission(state)) {
444 submit(latestRef.current.input.readDraft().text);
445 return;
446 }
447 if (pendingSubmissionRef.current) return;
448 pendingSubmissionRef.current = { ownerKey: latestRef.current.input.ownerKey, submit };
449 if (controller.currentState.phase === "recording") void controller.stop();
450 });
451
452 const loadSetupCatalog = useStableCallback(
453 async (connection: PreparedConnection, selectedModelId: string, request: number) => {
454 setSetup({ ...INITIAL_SETUP, open: true });
455 const catalog = await runEnvironmentSpeech(getEnvironmentSpeechModels(connection)).catch(
456 () => null,
457 );
458 if (request !== startRequestRef.current) return;
459 const choice = chooseSetupSpeechModel(catalog?.models ?? [], {
460 selectedModelId,
461 intent: latestRef.current.clientSettings.speechLanguage,
462 preferred: preferredSpeechLanguages(),
463 });
464 setSetup((current) => ({
465 ...current,
466 model: choice?.model ?? null,
467 language: choice?.language ?? null,
468 catalogFailed: catalog === null,
469 error: choice
470 ? null
471 : catalog
472 ? "No model matches your language. Choose a model or change the language in Voice settings."
473 : "Could not load transcription models. Check the connection and try again.",
474 }));
475 },
476 );
477
478 const start = useStableCallback(async () => {
479 if (latestRef.current.input.disabled || (setup.open && setup.downloading)) return;
480 if (!grantId) {
481 if (destination.offerFirstRunSetup && latestRef.current.input.offerSetup !== false)
482 await navigate({ to: "/settings/voice", hash: "voice-transcription-destination" });
483 return;
484 }
485 const request = ++startRequestRef.current;
486 const controller = controllerRef.current;
487 const owner = latestRef.current.input.ownerKey;
488 if (!controller || !prepared) return;
489 if (cloudProvider) {
490 setLevel(0);
491 await controller.start();
492 return;
493 }
494 const stillCurrent = () =>
495 request === startRequestRef.current &&
496 controllerRef.current === controller &&
497 latestRef.current.input.ownerKey === owner &&
498 !latestRef.current.input.disabled;
499 setSetup(INITIAL_SETUP);
500 setQueuedStart(prepared);
501 let latestStatus: EnvironmentSpeechStatus;
502 try {
503 latestStatus = await probeSpeechStatus(prepared, true);
504 } catch (error) {
505 if (!stillCurrent()) return;
506 setQueuedStart(null);
507 toastManager.add({
508 type: "error",
509 title: "Could not start voice input",
510 description: error instanceof Error ? error.message : String(error),
511 });
512 return;
513 }
514 if (!stillCurrent()) return;
515 setStatus({ prepared, value: latestStatus });
516 setQueuedStart(null);
517 if (latestStatus.supported && latestStatus.state === "missing-model") {
518 return loadSetupCatalog(prepared, latestStatus.modelId, request);
519 }
520 if (!latestStatus.supported) {
521 toastManager.add({
522 type: "error",
523 title: "Voice input is not available",
524 description: latestStatus.reason,
525 });
526 return;
527 }
528 setLevel(0);
529 await controller.start();
530 });
531
532 const downloadSetupModel = useStableCallback(async () => {
533 if (!prepared || !currentStatus?.supported || !setupModelId || setup.downloading) return;
534 const modelId = setupModelId;
535 const request = ++startRequestRef.current;
536 setSetup((current) => ({ ...current, downloading: true, error: null }));
537 try {
538 const { models } = await runEnvironmentSpeech(
539 downloadEnvironmentSpeechModel(prepared, modelId),
540 );
541 if (request !== startRequestRef.current) return;
542 // A download cancelled from elsewhere still resolves, so select the model only once it landed.
543 const installed = models.some(({ id, state }) => id === modelId && state === "installed");
544 if (installed && modelId !== currentStatus.modelId) {
545 try {
546 await runEnvironmentSpeech(selectEnvironmentSpeechModel(prepared, modelId));
547 } catch {
548 if (request !== startRequestRef.current) return;
549 setSetup((current) => ({
550 ...current,
551 downloading: false,
552 error: "The model downloaded, but this environment could not select it. Try again.",
553 }));
554 return;
555 }
556 }
557 if (request !== startRequestRef.current) return;
558 const next = await probeSpeechStatus(prepared, true);
559 if (request !== startRequestRef.current) return;
560 setStatus({ prepared, value: next });
561 const ready =
562 installed && next.supported && next.modelId === modelId && next.state !== "missing-model";
563 setSetup((current) => ({
564 ...current,
565 downloading: false,
566 step: ready ? 1 : current.step,
567 error: ready ? null : "The model is not ready. Try downloading it again.",
568 }));
569 } catch {
570 if (request !== startRequestRef.current) return;
571 setSetup((current) => ({
572 ...current,
573 downloading: false,
574 error: "Could not download the model. Check this environment's connection and try again.",
575 }));
576 }
577 });
578
579 const cancelSetupDownload = useStableCallback(async () => {
580 if (!prepared || !setupModelId) return;
581 startRequestRef.current += 1;
582 setSetup((current) => ({ ...current, open: false, downloading: false }));
583 try {
584 await runEnvironmentSpeech(cancelEnvironmentSpeechModelDownload(prepared, setupModelId));
585 } catch (error) {
586 setSetup((current) => ({
587 ...current,
588 error: error instanceof Error ? error.message : String(error),
589 }));
590 }
591 });
592
593 const destinationReady =
594 grantId === null
595 ? Boolean(destination.offerFirstRunSetup) && input.offerSetup !== false
596 : prepared !== null &&
597 (cloudProvider !== undefined ||
598 (status?.prepared === prepared && status.value?.supported !== false));
599 return {
600 available:
601 destinationReady &&
602 typeof navigator !== "undefined" &&
603 Boolean(navigator.mediaDevices?.getUserMedia) &&
604 typeof AudioWorkletNode !== "undefined",
605 status: currentStatus,
606 transcriptionEnvironmentId: destination.environmentId,
607 transcriptionEnvironmentLabel: destination.label,
608 setup: {
609 ...setup,
610 setOpen: (open: boolean) => setSetup((current) => ({ ...current, open })),
611 retryCatalog:
612 setup.open && setup.catalogFailed && prepared && currentStatus?.supported
613 ? () => loadSetupCatalog(prepared, currentStatus.modelId, ++startRequestRef.current)
614 : null,
615 download: downloadSetupModel,
616 cancelDownload: cancelSetupDownload,
617 startRecording: async () => {
618 setSetup((current) => ({ ...current, open: false }));
619 await start();
620 },
621 },
622 state,
623 preview: state.phase === "recording" || state.phase === "transcribing" ? preview : null,
624 level,
625 preparing: state.phase === "preparing",
626 blocksSubmission: voiceInputBlocksSubmission(state),
627 freezesEditor: voiceInputBlocksSubmission(state),
628 start,
629 submitAfterDictation,
630 stop: useStableCallback(() => controllerRef.current?.stop() ?? Promise.resolve()),
631 cancel: useStableCallback(() => {
632 pendingSubmissionRef.current = null;
633 startRequestRef.current += 1;
634 setQueuedStart(null);
635 setSetup(INITIAL_SETUP);
636 controllerRef.current?.cancel();
637 }),
638 skipPostProcessing: useStableCallback(() => controllerRef.current?.skipPostProcessing()),
639 };
640}