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