Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

voiceInputSession.ts

427 lines15.5 KB

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