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: CLOUD_SPEECH_LABELS[provider] }} via ${{ environment: environment.label }}`
155 : (environment?.label ?? null),
156 prepared: supported && canDictate ? connection : null,
157 };
158}
159
160export function useEnvironmentSpeechInput(input: HookInput) {
161 const navigate = useNavigate();
162 const destination = useVoiceTranscriptionDestination();
163 const prepared = destination.prepared;
164 const onDevice = destination.onDevice === true;
165 const grantId = destination.grantId;
166 const cloudProvider = destination.cloudProvider;
167 const cloudModel = destination.cloudModel;
168 const draftCapabilities = useEnvironment(input.environmentId)?.serverConfig?.environment
169 .capabilities;
170 const originatingConnection = Option.getOrNull(usePreparedConnection(input.environmentId));
171 const canCleanUp = useEnvironmentScope(input.environmentId, AuthOrchestrationOperateScope);
172 const cleanupPrepared =
173 canCleanUp &&
174 (draftCapabilities?.voiceTranscription || draftCapabilities?.cloudVoiceTranscription)
175 ? originatingConnection
176 : null;
177 const clientSettings = useClientSettings();
178 const projectId = input.projectId ?? null;
179 const projectWords = useEnvironmentSettings(
180 input.environmentId,
181 (settings) => resolveProjectSettings(settings, projectId).settings.speechProjectCustomWords,
182 );
183 const [status, setStatus] = useState<{
184 readonly prepared: PreparedConnection;
185 readonly value: EnvironmentSpeechStatus | null;
186 } | null>(null);
187 const [setup, setSetup] = useState(INITIAL_SETUP);
188 const [previousDestination, setPreviousDestination] = useState({ prepared, grantId });
189 const [previousOwner, setPreviousOwner] = useState({
190 key: input.ownerKey,
191 disabled: input.disabled,
192 });
193 if (previousDestination.prepared !== prepared || previousDestination.grantId !== grantId) {
194 setPreviousDestination({ prepared, grantId });
195 setSetup(INITIAL_SETUP);
196 }
197 if (previousOwner.key !== input.ownerKey || previousOwner.disabled !== input.disabled) {
198 setPreviousOwner({ key: input.ownerKey, disabled: input.disabled });
199 setSetup(INITIAL_SETUP);
200 }
201
202 const session = useRetainedVoiceInputSession({
203 prepared,
204 grantId,
205 onDevice,
206 cloudProvider,
207 cloudModel,
208 });
209 const snapshot = useVoiceInputSessionSnapshot(session);
210 const owns = snapshot.target?.ownerKey === input.ownerKey;
211 const activity = useVoiceInputSessionActivity(session, input.ownerKey);
212 const state = owns ? snapshot.state : IDLE_VOICE_STATE;
213 // One microphone: another draft's recording leaves this editor without voice input until it ends.
214 const busyElsewhere = !owns && voiceInputBlocksSubmission(snapshot.state);
215
216 const startRequestRef = useRef(0);
217 const latestRef = useRef({ input, clientSettings, cleanupPrepared, projectWords, session });
218 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes committed props before an async completion can read them through the session
219 useLayoutEffect(() => {
220 latestRef.current = { input, clientSettings, cleanupPrepared, projectWords, session };
221 });
222 const mountedRef = useRef(false);
223 // 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
224 useEffect(() => {
225 mountedRef.current = true;
226 return () => {
227 mountedRef.current = false;
228 startRequestRef.current += 1;
229 session?.ownerChanged(latestRef.current.input.ownerKey);
230 };
231 }, [session]);
232 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- tells the global indicator this draft is on screen
233 useEffect(
234 () => (input.presented === false ? undefined : presentVoiceOwner(input.ownerKey)),
235 [input.ownerKey, input.presented],
236 );
237
238 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- probes the chosen environment's speech status once its connection is available
239 useEffect(() => {
240 if (!prepared || cloudProvider) return;
241 let disposed = false;
242 void probeSpeechStatus(prepared)
243 .then((value) => {
244 if (!disposed) setStatus({ prepared, value });
245 })
246 .catch(() => {
247 if (!disposed) setStatus({ prepared, value: null });
248 });
249 return () => {
250 disposed = true;
251 };
252 }, [prepared, cloudProvider]);
253 const currentStatus = !cloudProvider && status?.prepared === prepared ? status.value : null;
254 const setupModelId = setup.model?.id;
255
256 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- polls download progress while the setup dialog owns an active model download
257 useEffect(() => {
258 if (!setup.open || !setup.downloading || !prepared || !setupModelId) return;
259 let disposed = false;
260 let refreshing = false;
261 const timer = window.setInterval(() => {
262 if (refreshing) return;
263 refreshing = true;
264 void runEnvironmentSpeech(getEnvironmentSpeechModels(prepared))
265 .then((result) => {
266 if (disposed) return;
267 const model = result.models.find((candidate) => candidate.id === setupModelId) ?? null;
268 if (model)
269 setSetup((current) => ({
270 ...current,
271 model: { ...model, recommended: current.model?.recommended ?? false },
272 }));
273 })
274 .catch(() => undefined)
275 .finally(() => {
276 refreshing = false;
277 });
278 }, 1_000);
279 return () => {
280 disposed = true;
281 window.clearInterval(timer);
282 };
283 }, [prepared, setup.downloading, setup.open, setupModelId]);
284
285 const previousOwnerRef = useRef(input.ownerKey);
286 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- abandons a recording that cannot outlive its editor when the draft's owner changes
287 useEffect(() => {
288 const previous = previousOwnerRef.current;
289 if (previous === input.ownerKey && !input.disabled) return;
290 previousOwnerRef.current = input.ownerKey;
291 startRequestRef.current += 1;
292 if (previous !== input.ownerKey) session?.ownerChanged(previous);
293 else if (session?.ownerKey === input.ownerKey) session.cancel();
294 }, [input.ownerKey, input.disabled, session]);
295
296 const submitAfterDictation = useStableCallback((submit: (text: string) => void) => {
297 if (latestRef.current.input.disabled || state.phase === "preparing") return;
298 if (!session || !voiceInputBlocksSubmission(state)) {
299 submit(latestRef.current.input.readDraft().text);
300 return;
301 }
302 session.queueSubmission(latestRef.current.input.ownerKey, submit);
303 });
304
305 const createTarget = useStableCallback((): VoiceInputTarget => {
306 const owner = latestRef.current.input.ownerKey;
307 const readContext = () => {
308 const current = latestRef.current;
309 return {
310 environmentId: current.input.environmentId,
311 projectName: current.input.projectName ?? null,
312 projectWords: current.projectWords,
313 clientSettings: current.clientSettings,
314 cleanup: current.input.cleanup !== false,
315 cleanupPrepared: current.cleanupPrepared,
316 };
317 };
318 // Once this editor shows another draft, its environment and cleanup must not see this one.
319 const startContext = readContext();
320 const persistent = latestRef.current.input.persistentDraft ?? null;
321 // While this editor shows the owner, the live editor is the draft; otherwise the stored one.
322 const live = () => mountedRef.current && latestRef.current.input.ownerKey === owner;
323 return {
324 ownerKey: owner,
325 label: latestRef.current.input.label ?? null,
326 persistent: persistent !== null,
327 open: persistent?.open ?? null,
328 readDraft: () => {
329 if (live()) return latestRef.current.input.readDraft();
330 const text = persistent?.readStoredText();
331 return text == null ? null : { text, selection: { start: text.length, end: text.length } };
332 },
333 commitDraft: (text, selection) => {
334 if (!live()) {
335 persistent?.commitStoredText(text);
336 return;
337 }
338 if (latestRef.current.input.disabled) return;
339 latestRef.current.input.commitDraft(text, selection);
340 },
341 readContext: () => (live() ? readContext() : startContext),
342 };
343 });
344
345 // 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
346 useEffect(() => {
347 if (session?.ownerKey === input.ownerKey && voiceInputBlocksSubmission(session.state))
348 session.adopt(createTarget());
349 }, [session, input.ownerKey, createTarget]);
350 const loadSetupCatalog = useStableCallback(
351 async (
352 connection: PreparedConnection,
353 selectedModelId: string,
354 benchmarkTier: SpeechBenchmarkTier,
355 request: number,
356 ) => {
357 setSetup({ ...INITIAL_SETUP, open: true });
358 const catalog = await runEnvironmentSpeech(
359 getEnvironmentSpeechModels(connection, true),
360 ).catch(() => null);
361 if (request !== startRequestRef.current) return;
362 const choice = chooseSetupSpeechModel(catalog?.models ?? [], {
363 selectedModelId,
364 intent: latestRef.current.clientSettings.speechLanguage,
365 preferred: preferredSpeechLanguages(),
366 benchmarkTier,
367 });
368 setSetup((current) => ({
369 ...current,
370 model: choice ? { ...choice.model, recommended: choice.recommended } : null,
371 language: choice?.language ?? null,
372 catalogFailed: catalog === null,
373 error: choice
374 ? null
375 : catalog
376 ? m(
377 msg(
378 "No model matches your language. Choose a model or change the language in Voice settings.",
379 ),
380 )
381 : m(msg("Could not load transcription models. Check the connection and try again.")),
382 }));
383 },
384 );
385
386 const start = useStableCallback(async () => {
387 if (latestRef.current.input.disabled || (setup.open && setup.downloading)) return;
388 if (!grantId) {
389 if (destination.offerFirstRunSetup && latestRef.current.input.offerSetup !== false)
390 await navigate({ to: "/settings/voice", hash: "voice-transcription-destination" });
391 return;
392 }
393 if (!session || voiceInputBlocksSubmission(session.state)) return;
394 const request = ++startRequestRef.current;
395 const owner = latestRef.current.input.ownerKey;
396 if (onDevice) {
397 await session.start(createTarget());
398 return;
399 }
400 if (!prepared) return;
401 if (cloudProvider) {
402 await session.start(createTarget());
403 return;
404 }
405 setSetup(INITIAL_SETUP);
406 const stillCurrent = () =>
407 request === startRequestRef.current &&
408 latestRef.current.session === session &&
409 latestRef.current.input.ownerKey === owner &&
410 !latestRef.current.input.disabled;
411 const handleStatus = async (latestStatus: EnvironmentSpeechStatus) => {
412 if (!stillCurrent()) return;
413 setStatus({ prepared, value: latestStatus });
414 if (!latestStatus.supported) {
415 session.cancel();
416 toastManager.add({
417 type: "error",
418 title: m(msg("Voice input is not available")),
419 description: latestStatus.reason,
420 });
421 } else if (latestStatus.state === "missing-model") {
422 session.cancel();
423 await loadSetupCatalog(prepared, latestStatus.modelId, latestStatus.benchmarkTier, request);
424 }
425 };
426
427 if (currentStatus?.supported && currentStatus.state === "missing-model") {
428 // Setup must remain usable without opening the microphone.
429 const latestStatus = await probeSpeechStatus(prepared, true).catch((error: unknown) => {
430 if (stillCurrent()) {
431 toastManager.add({
432 type: "error",
433 title: m(msg("Could not start voice input")),
434 description: error instanceof Error ? error.message : String(error),
435 });
436 }
437 return null;
438 });
439 if (!stillCurrent() || !latestStatus) return;
440 await handleStatus(latestStatus);
441 if (!latestStatus.supported || latestStatus.state === "missing-model" || !stillCurrent())
442 return;
443 }
444
445 await session.start(createTarget(), (latestStatus) => void handleStatus(latestStatus));
446 });
447
448 const downloadSetupModel = useStableCallback(async () => {
449 if (!prepared || !currentStatus?.supported || !setupModelId || setup.downloading) return;
450 const modelId = setupModelId;
451 const request = ++startRequestRef.current;
452 setSetup((current) => ({ ...current, downloading: true, error: null }));
453 try {
454 const downloaded = await runEnvironmentSpeech(
455 downloadEnvironmentSpeechModel(prepared, modelId),
456 );
457 if (request !== startRequestRef.current) return;
458 const outcome = getSpeechModelDownloadOutcome(downloaded, modelId);
459 if (outcome === "needs-selection") {
460 try {
461 await runEnvironmentSpeech(selectEnvironmentSpeechModel(prepared, modelId));
462 } catch {
463 if (request !== startRequestRef.current) return;
464 setSetup((current) => ({
465 ...current,
466 downloading: false,
467 error: m(
468 msg("The model downloaded, but this environment could not select it. Try again."),
469 ),
470 }));
471 return;
472 }
473 }
474 if (request !== startRequestRef.current) return;
475 const next = await probeSpeechStatus(prepared, true);
476 if (request !== startRequestRef.current) return;
477 setStatus({ prepared, value: next });
478 const ready =
479 outcome !== "incomplete" &&
480 next.supported &&
481 next.modelId === modelId &&
482 next.state !== "missing-model";
483 setSetup((current) => ({
484 ...current,
485 downloading: false,
486 step: ready ? 1 : current.step,
487 error: ready ? null : m(msg("The model is not ready. Try downloading it again.")),
488 }));
489 } catch {
490 if (request !== startRequestRef.current) return;
491 setSetup((current) => ({
492 ...current,
493 downloading: false,
494 error: m(
495 msg("Could not download the model. Check this environment's connection and try again."),
496 ),
497 }));
498 }
499 });
500
501 const cancelSetupDownload = useStableCallback(async () => {
502 if (!prepared || !setupModelId) return;
503 startRequestRef.current += 1;
504 setSetup((current) => ({ ...current, open: false, downloading: false }));
505 try {
506 await runEnvironmentSpeech(cancelEnvironmentSpeechModelDownload(prepared, setupModelId));
507 } catch (error) {
508 setSetup((current) => ({
509 ...current,
510 error: error instanceof Error ? error.message : String(error),
511 }));
512 }
513 });
514
515 const destinationReady =
516 grantId === null
517 ? Boolean(destination.offerFirstRunSetup) && input.offerSetup !== false
518 : onDevice ||
519 (prepared !== null &&
520 (cloudProvider !== undefined ||
521 (status?.prepared === prepared && status.value?.supported !== false)));
522 return {
523 available:
524 destinationReady &&
525 !busyElsewhere &&
526 typeof navigator !== "undefined" &&
527 Boolean(navigator.mediaDevices?.getUserMedia) &&
528 typeof AudioWorkletNode !== "undefined",
529 status: currentStatus,
530 transcriptionEnvironmentId: destination.environmentId,
531 transcriptionEnvironmentLabel: destination.label,
532 setup: {
533 ...setup,
534 setOpen: (open: boolean) => setSetup((current) => ({ ...current, open })),
535 retryCatalog:
536 setup.open && setup.catalogFailed && prepared && currentStatus?.supported
537 ? () =>
538 loadSetupCatalog(
539 prepared,
540 currentStatus.modelId,
541 currentStatus.benchmarkTier,
542 ++startRequestRef.current,
543 )
544 : null,
545 download: downloadSetupModel,
546 cancelDownload: cancelSetupDownload,
547 startRecording: async () => {
548 setSetup((current) => ({ ...current, open: false }));
549 await start();
550 },
551 },
552 state,
553 preview:
554 state.phase === "recording" || state.phase === "transcribing" ? activity.preview : null,
555 level: activity.level,
556 recordingStartedAt: owns ? snapshot.recordingStartedAt : null,
557 preparing: state.phase === "preparing",
558 blocksSubmission: voiceInputBlocksSubmission(state),
559 freezesEditor: voiceInputBlocksSubmission(state),
560 start,
561 submitAfterDictation,
562 stop: useStableCallback(() => (owns && session ? session.stop() : Promise.resolve())),
563 cancel: useStableCallback(() => {
564 startRequestRef.current += 1;
565 setSetup(INITIAL_SETUP);
566 if (owns) session?.cancel();
567 }),
568 skipPostProcessing: useStableCallback(() => {
569 if (owns) session?.skipPostProcessing();
570 }),
571 };
572}