Open History to see the last commit
1import {
2 cancelEnvironmentSpeechModelDownload,
3 downloadEnvironmentSpeechModel,
4 getEnvironmentSpeechModels,
5 getEnvironmentSpeechStatus,
6 getSpeechModelDownloadOutcome,
7 selectEnvironmentSpeechModel,
8 voiceInputBlocksSubmission,
9} from "@t3tools/client-runtime/voice-input";
10import type { PreparedConnection } from "@t3tools/client-runtime/connection";
11import { AuthOrchestrationOperateScope, CLOUD_SPEECH_LABELS } from "@t3tools/contracts";
12import type {
13 EnvironmentId,
14 EnvironmentSpeechModel,
15 EnvironmentSpeechStatus,
16 ProjectId,
17 SpeechBenchmarkTier,
18} from "@t3tools/contracts";
19import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
20import { chooseSetupSpeechModel } from "@t3tools/shared/speech";
21import { useNavigate } from "@tanstack/react-router";
22import * as Option from "effect/Option";
23import { msg, useGT } from "gt-react";
24import { useEffect, useLayoutEffect, useRef, useState } from "react";
25
26import { useStableCallback } from "~/hooks/useStableCallback";
27import { toastManager } from "../components/ui/toast";
28import { m } from "../i18n/messages";
29import {
30 useClientSettings,
31 useClientSettingsHydrated,
32 useEnvironmentSettings,
33} from "../hooks/useSettings";
34import { useEnvironment } from "../state/environments";
35import { useEnvironmentScope, usePreparedConnection } from "../state/session";
36import { useAppleSpeechLocales } from "./appleSpeech";
37import { preferredSpeechLanguages } from "./preferredSpeechLanguages";
38import { runEnvironmentSpeech } from "./runEnvironmentSpeech";
39import { useAudioChoice } from "./voiceConsent";
40import {
41 IDLE_VOICE_STATE,
42 presentVoiceOwner,
43 useRetainedVoiceInputSession,
44 useVoiceInputSessionActivity,
45 useVoiceInputSessionSnapshot,
46 type VoiceInputTarget,
47} from "./voiceInputSession";
48
49/** A product name, shown untranslated. */
50export const APPLE_SPEECH_LABEL = "Apple Speech";
51
52const INITIAL_SETUP = {
53 open: false,
54 step: 0,
55 model: null as EnvironmentSpeechModel | null,
56 language: null as string | null,
57 downloading: false,
58 catalogFailed: false,
59 error: null as string | null,
60};
61
62// Every mounted editor shares one status probe per destination; starting a recording refreshes it.
63const statusProbes = new WeakMap<PreparedConnection, Promise<EnvironmentSpeechStatus>>();
64function probeSpeechStatus(prepared: PreparedConnection, refresh = false) {
65 const cached = refresh ? undefined : statusProbes.get(prepared);
66 if (cached) return cached;
67 const probe = runEnvironmentSpeech(getEnvironmentSpeechStatus(prepared));
68 statusProbes.set(prepared, probe);
69 probe.catch(() => {
70 if (statusProbes.get(prepared) === probe) statusProbes.delete(prepared);
71 });
72 return probe;
73}
74
75type DraftInput = {
76 readonly text: string;
77 readonly selection: { readonly start: number; readonly end: number };
78};
79
80type HookInput = {
81 /** The draft's own environment. Optional transcript cleanup runs there, never on the audio destination. */
82 readonly environmentId: EnvironmentId;
83 /** The draft's project: its vocabulary on that environment and its name become recognition hints. */
84 readonly projectId?: ProjectId | null | undefined;
85 readonly projectName?: string | null | undefined;
86 readonly ownerKey: string;
87 readonly disabled?: boolean | undefined;
88 /**
89 * Until a destination is chosen, voice input is offered and its first gesture opens Voice
90 * settings. False hides it instead, for editors whose draft would not survive the navigation.
91 */
92 readonly offerSetup?: boolean | undefined;
93 /** False keeps the transcript off the cleanup provider even when cleanup is on; the model test uses it. */
94 readonly cleanup?: boolean | undefined;
95 readonly readDraft: () => DraftInput;
96 readonly commitDraft: (
97 text: string,
98 selection: { readonly start: number; readonly end: number },
99 ) => void;
100 /** Names the draft in the indicator shown while a recording's editor is off screen. */
101 readonly label?: string | null | undefined;
102 /** False while the editor stays mounted out of sight, so the indicator still shows. */
103 readonly presented?: boolean | undefined;
104 /**
105 * A draft that is stored outside its editor keeps recording when the editor shows another
106 * owner or unmounts; the transcript lands in the stored draft instead.
107 */
108 readonly persistentDraft?:
109 | {
110 readonly readStoredText: () => string | null;
111 readonly commitStoredText: (text: string) => void;
112 readonly open: () => void;
113 }
114 | undefined;
115};
116
117/**
118 * Microphone audio leaves this device only for the environment the person chose in
119 * Voice settings. Nothing is inferred from the primary or the draft's environment, and
120 * the recording is abandoned the moment that choice changes or its connection drops.
121 * Apple Speech ("device") keeps audio on this Mac and needs no environment.
122 */
123export function useVoiceTranscriptionDestination() {
124 const gt = useGT();
125 const hydrated = useClientSettingsHydrated();
126 const choice = useAudioChoice();
127 const grant = choice === "off" ? null : choice;
128 const appleSpeechAvailable = useAppleSpeechLocales().length > 0;
129 const device = hydrated && grant?.destination.kind === "device";
130 const environmentId =
131 hydrated && grant && grant.destination.kind !== "device"
132 ? grant.destination.environmentId
133 : null;
134 const environment = useEnvironment(environmentId);
135 const connection = Option.getOrNull(usePreparedConnection(environmentId));
136 const canDictate = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
137 const cloud = grant?.destination.kind === "cloud" ? grant.destination : undefined;
138 const provider = cloud?.provider;
139 const model = cloud?.provider === "openrouter" ? cloud.model : undefined;
140 const supported =
141 environment?.serverConfig?.environment.capabilities[
142 provider ? "cloudVoiceTranscription" : "voiceTranscription"
143 ] === true;
144 return {
145 ...(hydrated && choice === null ? { offerFirstRunSetup: true } : {}),
146 environmentId,
147 ...(device ? { device: true, onDevice: appleSpeechAvailable } : {}),
148 ...(provider ? { cloudProvider: provider } : {}),
149 ...(model ? { cloudModel: model } : {}),
150 grantId: grant?.id ?? null,
151 label: device
152 ? APPLE_SPEECH_LABEL
153 : provider && environment
154 ? gt("{provider} via {environment}", {
155 provider: CLOUD_SPEECH_LABELS[provider],
156 environment: environment.label,
157 })
158 : (environment?.label ?? null),
159 prepared: supported && canDictate ? connection : null,
160 };
161}
162
163export function useEnvironmentSpeechInput(input: HookInput) {
164 const navigate = useNavigate();
165 const destination = useVoiceTranscriptionDestination();
166 const prepared = destination.prepared;
167 const onDevice = destination.onDevice === true;
168 const grantId = destination.grantId;
169 const cloudProvider = destination.cloudProvider;
170 const cloudModel = destination.cloudModel;
171 const draftCapabilities = useEnvironment(input.environmentId)?.serverConfig?.environment
172 .capabilities;
173 const originatingConnection = Option.getOrNull(usePreparedConnection(input.environmentId));
174 const canCleanUp = useEnvironmentScope(input.environmentId, AuthOrchestrationOperateScope);
175 const cleanupPrepared =
176 canCleanUp &&
177 (draftCapabilities?.voiceTranscription || draftCapabilities?.cloudVoiceTranscription)
178 ? originatingConnection
179 : null;
180 const clientSettings = useClientSettings();
181 const projectId = input.projectId ?? null;
182 const projectWords = useEnvironmentSettings(
183 input.environmentId,
184 (settings) => resolveProjectSettings(settings, projectId).settings.speechProjectCustomWords,
185 );
186 const [status, setStatus] = useState<{
187 readonly prepared: PreparedConnection;
188 readonly value: EnvironmentSpeechStatus | null;
189 } | null>(null);
190 const [setup, setSetup] = useState(INITIAL_SETUP);
191 const [previousDestination, setPreviousDestination] = useState({ prepared, grantId });
192 const [previousOwner, setPreviousOwner] = useState({
193 key: input.ownerKey,
194 disabled: input.disabled,
195 });
196 if (previousDestination.prepared !== prepared || previousDestination.grantId !== grantId) {
197 setPreviousDestination({ prepared, grantId });
198 setSetup(INITIAL_SETUP);
199 }
200 if (previousOwner.key !== input.ownerKey || previousOwner.disabled !== input.disabled) {
201 setPreviousOwner({ key: input.ownerKey, disabled: input.disabled });
202 setSetup(INITIAL_SETUP);
203 }
204
205 const session = useRetainedVoiceInputSession({
206 prepared,
207 grantId,
208 onDevice,
209 cloudProvider,
210 cloudModel,
211 });
212 const snapshot = useVoiceInputSessionSnapshot(session);
213 const owns = snapshot.target?.ownerKey === input.ownerKey;
214 const activity = useVoiceInputSessionActivity(session, input.ownerKey);
215 const state = owns ? snapshot.state : IDLE_VOICE_STATE;
216 // One microphone: another draft's recording leaves this editor without voice input until it ends.
217 const busyElsewhere = !owns && voiceInputBlocksSubmission(snapshot.state);
218
219 const startRequestRef = useRef(0);
220 const latestRef = useRef({ input, clientSettings, cleanupPrepared, projectWords, session });
221 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes committed props before an async completion can read them through the session
222 useLayoutEffect(() => {
223 latestRef.current = { input, clientSettings, cleanupPrepared, projectWords, session };
224 });
225 const mountedRef = useRef(false);
226 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- abandons this editor's pending work, and a recording that cannot outlive it, on unmount or a destination change
227 useEffect(() => {
228 mountedRef.current = true;
229 return () => {
230 mountedRef.current = false;
231 startRequestRef.current += 1;
232 session?.ownerChanged(latestRef.current.input.ownerKey);
233 };
234 }, [session]);
235 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- tells the global indicator this draft is on screen
236 useEffect(
237 () => (input.presented === false ? undefined : presentVoiceOwner(input.ownerKey)),
238 [input.ownerKey, input.presented],
239 );
240
241 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- probes the chosen environment's speech status once its connection is available
242 useEffect(() => {
243 if (!prepared || cloudProvider) return;
244 let disposed = false;
245 void probeSpeechStatus(prepared)
246 .then((value) => {
247 if (!disposed) setStatus({ prepared, value });
248 })
249 .catch(() => {
250 if (!disposed) setStatus({ prepared, value: null });
251 });
252 return () => {
253 disposed = true;
254 };
255 }, [prepared, cloudProvider]);
256 const currentStatus = !cloudProvider && status?.prepared === prepared ? status.value : null;
257 const setupModelId = setup.model?.id;
258
259 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- polls download progress while the setup dialog owns an active model download
260 useEffect(() => {
261 if (!setup.open || !setup.downloading || !prepared || !setupModelId) return;
262 let disposed = false;
263 let refreshing = false;
264 const timer = window.setInterval(() => {
265 if (refreshing) return;
266 refreshing = true;
267 void runEnvironmentSpeech(getEnvironmentSpeechModels(prepared))
268 .then((result) => {
269 if (disposed) return;
270 const model = result.models.find((candidate) => candidate.id === setupModelId) ?? null;
271 if (model)
272 setSetup((current) => ({
273 ...current,
274 model: { ...model, recommended: current.model?.recommended ?? false },
275 }));
276 })
277 .catch(() => undefined)
278 .finally(() => {
279 refreshing = false;
280 });
281 }, 1_000);
282 return () => {
283 disposed = true;
284 window.clearInterval(timer);
285 };
286 }, [prepared, setup.downloading, setup.open, setupModelId]);
287
288 const previousOwnerRef = useRef(input.ownerKey);
289 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- abandons a recording that cannot outlive its editor when the draft's owner changes
290 useEffect(() => {
291 const previous = previousOwnerRef.current;
292 if (previous === input.ownerKey && !input.disabled) return;
293 previousOwnerRef.current = input.ownerKey;
294 startRequestRef.current += 1;
295 if (previous !== input.ownerKey) session?.ownerChanged(previous);
296 else if (session?.ownerKey === input.ownerKey) session.cancel();
297 }, [input.ownerKey, input.disabled, session]);
298
299 const submitAfterDictation = useStableCallback((submit: (text: string) => void) => {
300 if (latestRef.current.input.disabled || state.phase === "preparing") return;
301 if (!session || !voiceInputBlocksSubmission(state)) {
302 submit(latestRef.current.input.readDraft().text);
303 return;
304 }
305 session.queueSubmission(latestRef.current.input.ownerKey, submit);
306 });
307
308 const createTarget = useStableCallback((): VoiceInputTarget => {
309 const owner = latestRef.current.input.ownerKey;
310 const readContext = () => {
311 const current = latestRef.current;
312 return {
313 environmentId: current.input.environmentId,
314 projectName: current.input.projectName ?? null,
315 projectWords: current.projectWords,
316 clientSettings: current.clientSettings,
317 cleanup: current.input.cleanup !== false,
318 cleanupPrepared: current.cleanupPrepared,
319 };
320 };
321 // Once this editor shows another draft, its environment and cleanup must not see this one.
322 const startContext = readContext();
323 const persistent = latestRef.current.input.persistentDraft ?? null;
324 // While this editor shows the owner, the live editor is the draft; otherwise the stored one.
325 const live = () => mountedRef.current && latestRef.current.input.ownerKey === owner;
326 return {
327 ownerKey: owner,
328 label: latestRef.current.input.label ?? null,
329 persistent: persistent !== null,
330 open: persistent?.open ?? null,
331 readDraft: () => {
332 if (live()) return latestRef.current.input.readDraft();
333 const text = persistent?.readStoredText();
334 return text == null ? null : { text, selection: { start: text.length, end: text.length } };
335 },
336 commitDraft: (text, selection) => {
337 if (!live()) {
338 persistent?.commitStoredText(text);
339 return;
340 }
341 if (latestRef.current.input.disabled) return;
342 latestRef.current.input.commitDraft(text, selection);
343 },
344 readContext: () => (live() ? readContext() : startContext),
345 };
346 });
347
348 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a remounted editor takes over its draft's running recording so a queued Send still sees the transcript
349 useEffect(() => {
350 if (session?.ownerKey === input.ownerKey && voiceInputBlocksSubmission(session.state))
351 session.adopt(createTarget());
352 }, [session, input.ownerKey, createTarget]);
353 const loadSetupCatalog = useStableCallback(
354 async (
355 connection: PreparedConnection,
356 selectedModelId: string,
357 benchmarkTier: SpeechBenchmarkTier,
358 request: number,
359 ) => {
360 setSetup({ ...INITIAL_SETUP, open: true });
361 const catalog = await runEnvironmentSpeech(
362 getEnvironmentSpeechModels(connection, true),
363 ).catch(() => null);
364 if (request !== startRequestRef.current) return;
365 const choice = chooseSetupSpeechModel(catalog?.models ?? [], {
366 selectedModelId,
367 intent: latestRef.current.clientSettings.speechLanguage,
368 preferred: preferredSpeechLanguages(),
369 benchmarkTier,
370 });
371 setSetup((current) => ({
372 ...current,
373 model: choice ? { ...choice.model, recommended: choice.recommended } : null,
374 language: choice?.language ?? null,
375 catalogFailed: catalog === null,
376 error: choice
377 ? null
378 : catalog
379 ? m(
380 msg(
381 "No model matches your language. Choose a model or change the language in Voice settings.",
382 ),
383 )
384 : m(msg("Could not load transcription models. Check the connection and try again.")),
385 }));
386 },
387 );
388
389 const start = useStableCallback(async () => {
390 if (latestRef.current.input.disabled || (setup.open && setup.downloading)) return;
391 if (!grantId) {
392 if (destination.offerFirstRunSetup && latestRef.current.input.offerSetup !== false)
393 await navigate({ to: "/settings/voice", hash: "voice-transcription-destination" });
394 return;
395 }
396 if (!session || voiceInputBlocksSubmission(session.state)) return;
397 const request = ++startRequestRef.current;
398 const owner = latestRef.current.input.ownerKey;
399 if (onDevice) {
400 await session.start(createTarget());
401 return;
402 }
403 if (!prepared) return;
404 if (cloudProvider) {
405 await session.start(createTarget());
406 return;
407 }
408 setSetup(INITIAL_SETUP);
409 const stillCurrent = () =>
410 request === startRequestRef.current &&
411 latestRef.current.session === session &&
412 latestRef.current.input.ownerKey === owner &&
413 !latestRef.current.input.disabled;
414 const handleStatus = async (latestStatus: EnvironmentSpeechStatus) => {
415 if (!stillCurrent()) return;
416 setStatus({ prepared, value: latestStatus });
417 if (!latestStatus.supported) {
418 session.cancel();
419 toastManager.add({
420 type: "error",
421 title: m(msg("Voice input is not available")),
422 description: latestStatus.reason,
423 });
424 } else if (latestStatus.state === "missing-model") {
425 session.cancel();
426 await loadSetupCatalog(prepared, latestStatus.modelId, latestStatus.benchmarkTier, request);
427 }
428 };
429
430 if (currentStatus?.supported && currentStatus.state === "missing-model") {
431 // Setup must remain usable without opening the microphone.
432 const latestStatus = await probeSpeechStatus(prepared, true).catch((error: unknown) => {
433 if (stillCurrent()) {
434 toastManager.add({
435 type: "error",
436 title: m(msg("Could not start voice input")),
437 description: error instanceof Error ? error.message : String(error),
438 });
439 }
440 return null;
441 });
442 if (!stillCurrent() || !latestStatus) return;
443 await handleStatus(latestStatus);
444 if (!latestStatus.supported || latestStatus.state === "missing-model" || !stillCurrent())
445 return;
446 }
447
448 await session.start(createTarget(), (latestStatus) => void handleStatus(latestStatus));
449 });
450
451 const downloadSetupModel = useStableCallback(async () => {
452 if (!prepared || !currentStatus?.supported || !setupModelId || setup.downloading) return;
453 const modelId = setupModelId;
454 const request = ++startRequestRef.current;
455 setSetup((current) => ({ ...current, downloading: true, error: null }));
456 try {
457 const downloaded = await runEnvironmentSpeech(
458 downloadEnvironmentSpeechModel(prepared, modelId),
459 );
460 if (request !== startRequestRef.current) return;
461 const outcome = getSpeechModelDownloadOutcome(downloaded, modelId);
462 if (outcome === "needs-selection") {
463 try {
464 await runEnvironmentSpeech(selectEnvironmentSpeechModel(prepared, modelId));
465 } catch {
466 if (request !== startRequestRef.current) return;
467 setSetup((current) => ({
468 ...current,
469 downloading: false,
470 error: m(
471 msg("The model downloaded, but this environment could not select it. Try again."),
472 ),
473 }));
474 return;
475 }
476 }
477 if (request !== startRequestRef.current) return;
478 const next = await probeSpeechStatus(prepared, true);
479 if (request !== startRequestRef.current) return;
480 setStatus({ prepared, value: next });
481 const ready =
482 outcome !== "incomplete" &&
483 next.supported &&
484 next.modelId === modelId &&
485 next.state !== "missing-model";
486 setSetup((current) => ({
487 ...current,
488 downloading: false,
489 step: ready ? 1 : current.step,
490 error: ready ? null : m(msg("The model is not ready. Try downloading it again.")),
491 }));
492 } catch {
493 if (request !== startRequestRef.current) return;
494 setSetup((current) => ({
495 ...current,
496 downloading: false,
497 error: m(
498 msg("Could not download the model. Check this environment's connection and try again."),
499 ),
500 }));
501 }
502 });
503
504 const cancelSetupDownload = useStableCallback(async () => {
505 if (!prepared || !setupModelId) return;
506 startRequestRef.current += 1;
507 setSetup((current) => ({ ...current, open: false, downloading: false }));
508 try {
509 await runEnvironmentSpeech(cancelEnvironmentSpeechModelDownload(prepared, setupModelId));
510 } catch (error) {
511 setSetup((current) => ({
512 ...current,
513 error: error instanceof Error ? error.message : String(error),
514 }));
515 }
516 });
517
518 const destinationReady =
519 grantId === null
520 ? Boolean(destination.offerFirstRunSetup) && input.offerSetup !== false
521 : onDevice ||
522 (prepared !== null &&
523 (cloudProvider !== undefined ||
524 (status?.prepared === prepared && status.value?.supported !== false)));
525 return {
526 available:
527 destinationReady &&
528 !busyElsewhere &&
529 typeof navigator !== "undefined" &&
530 Boolean(navigator.mediaDevices?.getUserMedia) &&
531 typeof AudioWorkletNode !== "undefined",
532 status: currentStatus,
533 transcriptionEnvironmentId: destination.environmentId,
534 transcriptionEnvironmentLabel: destination.label,
535 setup: {
536 ...setup,
537 setOpen: (open: boolean) => setSetup((current) => ({ ...current, open })),
538 retryCatalog:
539 setup.open && setup.catalogFailed && prepared && currentStatus?.supported
540 ? () =>
541 loadSetupCatalog(
542 prepared,
543 currentStatus.modelId,
544 currentStatus.benchmarkTier,
545 ++startRequestRef.current,
546 )
547 : null,
548 download: downloadSetupModel,
549 cancelDownload: cancelSetupDownload,
550 startRecording: async () => {
551 setSetup((current) => ({ ...current, open: false }));
552 await start();
553 },
554 },
555 state,
556 preview:
557 state.phase === "recording" || state.phase === "transcribing" ? activity.preview : null,
558 level: activity.level,
559 recordingStartedAt: owns ? snapshot.recordingStartedAt : null,
560 preparing: state.phase === "preparing",
561 blocksSubmission: voiceInputBlocksSubmission(state),
562 freezesEditor: voiceInputBlocksSubmission(state),
563 start,
564 submitAfterDictation,
565 stop: useStableCallback(() => (owns && session ? session.stop() : Promise.resolve())),
566 cancel: useStableCallback(() => {
567 startRequestRef.current += 1;
568 setSetup(INITIAL_SETUP);
569 if (owns) session?.cancel();
570 }),
571 skipPostProcessing: useStableCallback(() => {
572 if (owns) session?.skipPostProcessing();
573 }),
574 };
575}