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