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