Open History to see the last commit
1import {
2 postProcessEnvironmentTranscript,
3 VoiceInputController,
4 voiceInputBlocksSubmission,
5 type VoiceDraftSnapshot,
6 type VoiceInputControllerDependencies,
7 type VoiceInputErrorCode,
8 type VoiceInputState,
9} from "@t3tools/client-runtime/voice-input";
10import type { PreparedConnection } from "@t3tools/client-runtime/connection";
11import type {
12 CloudSpeechModelId,
13 CloudSpeechProvider,
14 ClientSettings,
15 EnvironmentId,
16 EnvironmentSpeechStatus,
17 SpeechCustomWords,
18 SpeechPostProcessingOptions,
19 SpeechStreamText,
20 SpeechTranscriptionOptions,
21} from "@t3tools/contracts";
22import { DEFAULT_CLIENT_SETTINGS, EnvironmentInternalError } from "@t3tools/contracts";
23import { resolveSpeechVocabulary } from "@t3tools/shared/speech";
24import * as Schema from "effect/Schema";
25import { useEffect, useSyncExternalStore } from "react";
26
27import { toastManager } from "../components/ui/toast";
28import { chooseRecordingMicrophone } from "./browserMicrophones";
29import {
30 createAppleSpeechVoiceInputPlatform,
31 createBrowserVoiceInputPlatform,
32} from "./browserVoiceInput";
33import { runEnvironmentSpeech } from "./runEnvironmentSpeech";
34import { bindAudioGrant, readCleanupGrant } from "./voiceConsent";
35import { msg } from "gt-react";
36import { m } from "../i18n/messages";
37
38const isEnvironmentInternalError = Schema.is(EnvironmentInternalError);
39
40export const IDLE_VOICE_STATE: VoiceInputState = { phase: "idle", error: null, errorAction: null };
41
42type DraftInput = {
43 readonly text: string;
44 readonly selection: { readonly start: number; readonly end: number };
45};
46
47/** What a recording needs from its editor, read once when it starts. */
48export type VoiceRecordingContext = {
49 readonly environmentId: EnvironmentId;
50 readonly projectName: string | null;
51 readonly projectWords: SpeechCustomWords;
52 readonly clientSettings: ClientSettings;
53 readonly cleanup: boolean;
54 readonly cleanupPrepared: PreparedConnection | null;
55};
56
57export type VoiceInputTarget = {
58 readonly ownerKey: string;
59 /** Names the draft in the indicator shown while its editor is off screen. */
60 readonly label: string | null;
61 /** A target that can outlive its editor (a thread draft) keeps recording when the owner changes. */
62 readonly persistent: boolean;
63 readonly open: (() => void) | null;
64 readonly readDraft: () => DraftInput | null;
65 readonly commitDraft: (text: string, selection: DraftInput["selection"]) => void;
66 readonly readContext: () => VoiceRecordingContext;
67};
68
69export type VoiceInputSessionSnapshot = {
70 readonly state: VoiceInputState;
71 readonly target: VoiceInputTarget | null;
72 /** Wall-clock start of the current recording, so every view shows the same elapsed time. */
73 readonly recordingStartedAt: number | null;
74};
75
76export type VoiceInputSessionActivity = {
77 readonly level: number;
78 readonly preview: SpeechStreamText | null;
79};
80
81type SessionKey = {
82 /** Null is Apple Speech, which transcribes on this Mac without an environment. */
83 readonly prepared: PreparedConnection | null;
84 readonly grantId: string;
85 readonly cloudProvider: CloudSpeechProvider | undefined;
86 readonly cloudModel: CloudSpeechModelId | undefined;
87};
88
89const SILENT_ACTIVITY: VoiceInputSessionActivity = { level: 0, preview: null };
90
91function cleanupContext({ text, selection }: DraftInput): DraftInput {
92 const limit = 1_024;
93 const start = Math.max(0, Math.min(selection.start, text.length));
94 const end = Math.max(start, Math.min(selection.end, text.length));
95 const before = text.slice(Math.max(0, start - limit), start);
96 const selected = text.slice(start, Math.min(end, start + limit));
97 return {
98 text: before + selected + text.slice(end, end + limit),
99 selection: { start: before.length, end: before.length + selected.length },
100 };
101}
102
103/**
104 * The browser has one microphone, so every editor shares one dictation per destination. The
105 * recording belongs to the target that started it, not to whichever editor is mounted now.
106 */
107export class VoiceInputSession {
108 readonly key: SessionKey;
109 private readonly controller: VoiceInputController;
110 private target: VoiceInputTarget | null = null;
111 private pendingSubmission: {
112 readonly ownerKey: string;
113 readonly submit: (text: string) => void;
114 text?: string;
115 } | null = null;
116 private snapshot: VoiceInputSessionSnapshot = {
117 state: IDLE_VOICE_STATE,
118 target: null,
119 recordingStartedAt: null,
120 };
121 private activity = SILENT_ACTIVITY;
122 private readonly listeners = new Set<() => void>();
123 private readonly activityListeners = new Set<() => void>();
124 private disposed = false;
125 private onSpeechStatus: ((status: EnvironmentSpeechStatus) => void) | undefined;
126
127 constructor(key: SessionKey) {
128 this.key = key;
129 const hasAudioConsent = bindAudioGrant(key.grantId);
130 let recordingPreferences:
131 | {
132 readonly cleanup: SpeechPostProcessingOptions | null;
133 readonly cleanupGrant: string | null;
134 readonly cleanupPrepared: PreparedConnection | null;
135 }
136 | undefined;
137 const platformInput = {
138 hasAudioConsent,
139 getStatusListener: () => this.onSpeechStatus,
140 getStreamingEnabled: () =>
141 this.target?.readContext().clientSettings.speechStreaming ??
142 DEFAULT_CLIENT_SETTINGS.speechStreaming,
143 getTranscriptionOptions: (): SpeechTranscriptionOptions => {
144 const context = this.target?.readContext();
145 if (!context) throw new Error(m(msg("Voice input has no draft to record into.")));
146 const settings = context.clientSettings;
147 const cleanupGrant = context.cleanup ? readCleanupGrant() : null;
148 const cleanupEnabled = cleanupGrant !== null;
149 const cue = cleanupEnabled && context.cleanupPrepared ? settings.speechCorrectionWord : "";
150 const { speechCustomWords, speechHints } = resolveSpeechVocabulary({
151 personal: settings.speechCustomWords,
152 project: context.projectWords,
153 hints: [cue, context.projectName ?? ""],
154 });
155 recordingPreferences = {
156 cleanupGrant,
157 cleanupPrepared: context.cleanupPrepared,
158 cleanup: cleanupEnabled
159 ? {
160 speechCustomWords,
161 speechPostProcessingPrompt: settings.speechPostProcessingPrompt,
162 ...(cue.trim() ? { speechCorrectionWord: cue } : {}),
163 }
164 : null,
165 };
166 return {
167 speechLanguage: settings.speechLanguage,
168 speechTranslateToEnglish: settings.speechTranslateToEnglish,
169 speechCustomWords,
170 ...(speechHints.length > 0 ? { speechHints } : {}),
171 speechRemoveFillerWords: settings.speechRemoveFillerWords,
172 ...(cue.trim() ? { speechCorrectionWord: cue } : {}),
173 speechSilenceFiltering: settings.speechSilenceFiltering,
174 };
175 },
176 getMicrophoneId: chooseRecordingMicrophone,
177 onLevel: (level: number) => this.publishActivity({ ...this.activity, level }),
178 onDurationLimit: () => void this.controller.stop(),
179 onError: (message: string, code?: VoiceInputErrorCode) => {
180 if (!this.disposed) void this.controller.interruptRecording(message, null, code);
181 },
182 };
183 const platform = key.prepared
184 ? createBrowserVoiceInputPlatform({
185 ...platformInput,
186 prepared: key.prepared,
187 cloudProvider: key.cloudProvider,
188 cloudModel: key.cloudModel,
189 onText: (preview) => {
190 if (!this.disposed) this.publishActivity({ ...this.activity, preview });
191 },
192 })
193 : createAppleSpeechVoiceInputPlatform(platformInput);
194 const postProcess: NonNullable<VoiceInputControllerDependencies["postProcess"]> = (
195 transcript,
196 options,
197 ) => {
198 const preferences = recordingPreferences;
199 if (
200 !preferences?.cleanup ||
201 !hasAudioConsent() ||
202 preferences.cleanupGrant !== readCleanupGrant() ||
203 this.target?.ownerKey !== options.draft.ownerKey
204 )
205 return null;
206 if (!preferences.cleanupPrepared)
207 return Promise.reject(
208 new Error(m(msg("The draft's environment is unavailable for transcript cleanup."))),
209 );
210 return runEnvironmentSpeech(
211 postProcessEnvironmentTranscript(
212 preferences.cleanupPrepared,
213 transcript,
214 cleanupContext(options.draft),
215 preferences.cleanup,
216 () => hasAudioConsent() && preferences.cleanupGrant === readCleanupGrant(),
217 ),
218 options,
219 ).then((result) => result.text);
220 };
221 this.controller = new VoiceInputController({
222 resolve: m,
223 retryFailedRecording: true,
224 recorder: platform.recorder,
225 getTranscriber: () => platform.transcriber,
226 requestPermission: async () => ({ granted: true, canAskAgain: true }),
227 configureRecording: async () => undefined,
228 releaseRecording: async () => platform.cancelRecording(),
229 deleteRecording: platform.deleteRecording,
230 postProcess,
231 onPostProcessingError: (error) => {
232 const added = m(msg("The original transcript was added."));
233 const detail = isEnvironmentInternalError(error) ? error.detail : undefined;
234 toastManager.add({
235 type: "warning",
236 title: m(msg("Transcript cleanup failed")),
237 description: detail ? `${detail} ${added}` : added,
238 });
239 },
240 readDraft: (): VoiceDraftSnapshot | null => {
241 const target = this.target;
242 const draft = target?.readDraft();
243 return target && draft ? { ownerKey: target.ownerKey, ...draft } : null;
244 },
245 commitDraft: (text, selection) => {
246 const ownerKey = this.target?.ownerKey ?? null;
247 this.target?.commitDraft(text, selection);
248 if (ownerKey !== null && this.pendingSubmission?.ownerKey === ownerKey) {
249 this.pendingSubmission.text = text;
250 }
251 },
252 onStateChange: (state) => {
253 if (this.disposed) return;
254 const recordingStartedAt =
255 state.phase !== "recording" ? null : (this.snapshot.recordingStartedAt ?? Date.now());
256 this.publish({ ...this.snapshot, state, recordingStartedAt });
257 if (state.phase !== "recording" && state.phase !== "transcribing")
258 this.publishActivity(SILENT_ACTIVITY);
259 if (state.phase === "error") {
260 this.pendingSubmission = null;
261 return;
262 }
263 if (state.phase === "idle" && this.pendingSubmission !== null) {
264 const pending = this.pendingSubmission;
265 this.pendingSubmission = null;
266 if (pending.text !== undefined) pending.submit(pending.text);
267 }
268 },
269 });
270 }
271
272 get state(): VoiceInputState {
273 return this.controller.currentState;
274 }
275
276 get ownerKey(): string | null {
277 return this.target?.ownerKey ?? null;
278 }
279
280 readonly subscribe = (listener: () => void): (() => void) => {
281 this.listeners.add(listener);
282 return () => this.listeners.delete(listener);
283 };
284
285 readonly getSnapshot = (): VoiceInputSessionSnapshot => this.snapshot;
286
287 readonly subscribeActivity = (listener: () => void): (() => void) => {
288 this.activityListeners.add(listener);
289 return () => this.activityListeners.delete(listener);
290 };
291
292 readonly getActivity = (): VoiceInputSessionActivity => this.activity;
293
294 /** Starts recording into `target`, or does nothing while another draft holds the microphone. */
295 start(
296 target: VoiceInputTarget,
297 onSpeechStatus?: (status: EnvironmentSpeechStatus) => void,
298 ): Promise<void> {
299 if (this.disposed) return Promise.resolve();
300 const busyElsewhere =
301 voiceInputBlocksSubmission(this.controller.currentState) &&
302 this.target?.ownerKey !== target.ownerKey;
303 if (busyElsewhere) return Promise.resolve();
304 this.pendingSubmission = null;
305 this.target = target;
306 this.onSpeechStatus = onSpeechStatus;
307 this.publishActivity(SILENT_ACTIVITY);
308 this.publish({ ...this.snapshot, target });
309 return this.controller.start();
310 }
311
312 /** A newly mounted editor for the recording's draft replaces the target that started it. */
313 adopt(target: VoiceInputTarget): void {
314 if (this.disposed || this.target?.ownerKey !== target.ownerKey) return;
315 this.target = target;
316 this.publish({ ...this.snapshot, target });
317 }
318
319 /** Queues a submission to run once the active dictation commits its transcript. */
320 queueSubmission(ownerKey: string, submit: (text: string) => void): boolean {
321 if (
322 this.disposed ||
323 this.target?.ownerKey !== ownerKey ||
324 !voiceInputBlocksSubmission(this.controller.currentState) ||
325 this.pendingSubmission !== null
326 ) {
327 return false;
328 }
329 this.pendingSubmission = { ownerKey, submit };
330 if (this.controller.currentState.phase === "recording") {
331 void this.controller.stop();
332 }
333 return true;
334 }
335
336 stop(): Promise<void> {
337 return this.controller.stop();
338 }
339
340 cancel(): void {
341 this.pendingSubmission = null;
342 this.controller.cancel();
343 }
344
345 skipPostProcessing(): void {
346 this.controller.skipPostProcessing();
347 }
348
349 /** The editor for `ownerKey` now shows another draft; only a persistent target keeps going. */
350 ownerChanged(ownerKey: string): void {
351 if (this.target?.ownerKey !== ownerKey || this.target.persistent) return;
352 this.pendingSubmission = null;
353 this.controller.ownerChanged();
354 }
355
356 dispose(): void {
357 this.disposed = true;
358 this.pendingSubmission = null;
359 this.controller.dispose();
360 this.listeners.clear();
361 this.activityListeners.clear();
362 }
363
364 private publish(snapshot: VoiceInputSessionSnapshot): void {
365 this.snapshot = snapshot;
366 for (const listener of this.listeners) listener();
367 }
368
369 private publishActivity(activity: VoiceInputSessionActivity): void {
370 if (activity.level === this.activity.level && activity.preview === this.activity.preview)
371 return;
372 this.activity = activity;
373 for (const listener of this.activityListeners) listener();
374 }
375}
376
377const sessions = new Map<VoiceInputSession, number>();
378const registryListeners = new Set<() => void>();
379
380function sameKey(session: VoiceInputSession, key: SessionKey): boolean {
381 return (
382 session.key.prepared === key.prepared &&
383 session.key.grantId === key.grantId &&
384 session.key.cloudProvider === key.cloudProvider &&
385 session.key.cloudModel === key.cloudModel
386 );
387}
388
389function findSession(key: SessionKey): VoiceInputSession | null {
390 for (const session of sessions.keys()) if (sameKey(session, key)) return session;
391 return null;
392}
393
394/** Every holder of a destination shares one session; the last release disposes it. */
395function retainVoiceInputSession(key: SessionKey): () => void {
396 const session = findSession(key) ?? new VoiceInputSession(key);
397 sessions.set(session, (sessions.get(session) ?? 0) + 1);
398 for (const listener of registryListeners) listener();
399 let released = false;
400 return () => {
401 if (released) return;
402 released = true;
403 const count = (sessions.get(session) ?? 1) - 1;
404 if (count > 0) {
405 sessions.set(session, count);
406 return;
407 }
408 sessions.delete(session);
409 session.dispose();
410 for (const listener of registryListeners) listener();
411 };
412}
413
414function subscribeRegistry(listener: () => void): () => void {
415 registryListeners.add(listener);
416 return () => registryListeners.delete(listener);
417}
418
419/** Holds the destination's shared session while mounted; null until it is retained. */
420export function useRetainedVoiceInputSession(input: {
421 readonly prepared: PreparedConnection | null;
422 readonly grantId: string | null;
423 readonly onDevice?: boolean | undefined;
424 readonly cloudProvider?: CloudSpeechProvider | undefined;
425 readonly cloudModel?: CloudSpeechModelId | undefined;
426}): VoiceInputSession | null {
427 const { grantId, cloudProvider, cloudModel } = input;
428 const prepared = input.onDevice ? null : input.prepared;
429 const ready = (input.onDevice === true || prepared !== null) && grantId !== null;
430 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- retains the shared recording session for this destination while mounted
431 useEffect(() => {
432 if (!ready || !grantId || typeof navigator === "undefined") return;
433 return retainVoiceInputSession({ prepared, grantId, cloudProvider, cloudModel });
434 }, [ready, prepared, grantId, cloudProvider, cloudModel]);
435 return useSyncExternalStore(subscribeRegistry, () =>
436 ready && grantId ? findSession({ prepared, grantId, cloudProvider, cloudModel }) : null,
437 );
438}
439
440const IDLE_SNAPSHOT: VoiceInputSessionSnapshot = {
441 state: IDLE_VOICE_STATE,
442 target: null,
443 recordingStartedAt: null,
444};
445const noSubscription = () => () => {};
446
447export function useVoiceInputSessionSnapshot(
448 session: VoiceInputSession | null,
449): VoiceInputSessionSnapshot {
450 return useSyncExternalStore(
451 session?.subscribe ?? noSubscription,
452 session ? session.getSnapshot : () => IDLE_SNAPSHOT,
453 );
454}
455
456export function useVoiceInputSessionActivity(
457 session: VoiceInputSession | null,
458 ownerKey: string | null,
459): VoiceInputSessionActivity {
460 // Activity changes many times a second, so only the owning editor reads it.
461 const owns = useSyncExternalStore(
462 session?.subscribe ?? noSubscription,
463 () => session !== null && ownerKey !== null && session.ownerKey === ownerKey,
464 );
465 return useSyncExternalStore(owns && session ? session.subscribeActivity : noSubscription, () =>
466 owns && session ? session.getActivity() : SILENT_ACTIVITY,
467 );
468}
469
470// Editors register the owner they show, so the indicator appears only while its draft is off screen.
471const presentedOwners = new Map<string, number>();
472const presentationListeners = new Set<() => void>();
473
474export function presentVoiceOwner(ownerKey: string): () => void {
475 presentedOwners.set(ownerKey, (presentedOwners.get(ownerKey) ?? 0) + 1);
476 for (const listener of presentationListeners) listener();
477 return () => {
478 const count = (presentedOwners.get(ownerKey) ?? 1) - 1;
479 if (count > 0) presentedOwners.set(ownerKey, count);
480 else presentedOwners.delete(ownerKey);
481 for (const listener of presentationListeners) listener();
482 };
483}
484
485function subscribePresentation(listener: () => void): () => void {
486 presentationListeners.add(listener);
487 return () => presentationListeners.delete(listener);
488}
489
490export function useVoiceOwnerPresented(ownerKey: string | null): boolean {
491 return useSyncExternalStore(
492 subscribePresentation,
493 () => ownerKey !== null && presentedOwners.has(ownerKey),
494 );
495}