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

voiceInputSession.ts

454 lines16.7 KB

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 };
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 snapshot: VoiceInputSessionSnapshot = {
112 state: IDLE_VOICE_STATE,
113 target: null,
114 recordingStartedAt: null,
115 };
116 private activity = SILENT_ACTIVITY;
117 private readonly listeners = new Set<() => void>();
118 private readonly activityListeners = new Set<() => void>();
119 private disposed = false;
120 private onSpeechStatus: ((status: EnvironmentSpeechStatus) => void) | undefined;
121​
122 constructor(key: SessionKey) {
123 this.key = key;
124 const hasAudioConsent = bindAudioGrant(key.grantId);
125 let recordingPreferences:
126 | {
127 readonly cleanup: SpeechPostProcessingOptions | null;
128 readonly cleanupGrant: string | null;
129 readonly cleanupPrepared: PreparedConnection | null;
130 }
131 | undefined;
132 const platformInput = {
133 hasAudioConsent,
134 getStatusListener: () => this.onSpeechStatus,
135 getStreamingEnabled: () =>
136 this.target?.readContext().clientSettings.speechStreaming ??
137 DEFAULT_CLIENT_SETTINGS.speechStreaming,
138 getTranscriptionOptions: (): SpeechTranscriptionOptions => {
139 const context = this.target?.readContext();
140 if (!context) throw new Error(m(msg("Voice input has no draft to record into.")));
141 const settings = context.clientSettings;
142 const cleanupGrant = context.cleanup ? readCleanupGrant() : null;
143 const cleanupEnabled = cleanupGrant !== null;
144 const cue = cleanupEnabled && context.cleanupPrepared ? settings.speechCorrectionWord : "";
145 const { speechCustomWords, speechHints } = resolveSpeechVocabulary({
146 personal: settings.speechCustomWords,
147 project: context.projectWords,
148 hints: [cue, context.projectName ?? ""],
149 });
150 recordingPreferences = {
151 cleanupGrant,
152 cleanupPrepared: context.cleanupPrepared,
153 cleanup: cleanupEnabled
154 ? {
155 speechCustomWords,
156 speechPostProcessingPrompt: settings.speechPostProcessingPrompt,
157 ...(cue.trim() ? { speechCorrectionWord: cue } : {}),
158 }
159 : null,
160 };
161 return {
162 speechLanguage: settings.speechLanguage,
163 speechTranslateToEnglish: settings.speechTranslateToEnglish,
164 speechCustomWords,
165 ...(speechHints.length > 0 ? { speechHints } : {}),
166 speechRemoveFillerWords: settings.speechRemoveFillerWords,
167 ...(cue.trim() ? { speechCorrectionWord: cue } : {}),
168 speechSilenceFiltering: settings.speechSilenceFiltering,
169 };
170 },
171 getMicrophoneId: chooseRecordingMicrophone,
172 onLevel: (level: number) => this.publishActivity({ ...this.activity, level }),
173 onDurationLimit: () => void this.controller.stop(),
174 onError: (message: string, code?: VoiceInputErrorCode) => {
175 if (!this.disposed) void this.controller.interruptRecording(message, null, code);
176 },
177 };
178 const platform = key.prepared
179 ? createBrowserVoiceInputPlatform({
180 ...platformInput,
181 prepared: key.prepared,
182 cloudProvider: key.cloudProvider,
183 cloudModel: key.cloudModel,
184 onText: (preview) => {
185 if (!this.disposed) this.publishActivity({ ...this.activity, preview });
186 },
187 })
188 : createAppleSpeechVoiceInputPlatform(platformInput);
189 const postProcess: NonNullable<VoiceInputControllerDependencies["postProcess"]> = (
190 transcript,
191 options,
192 ) => {
193 const preferences = recordingPreferences;
194 if (
195 !preferences?.cleanup ||
196 !hasAudioConsent() ||
197 preferences.cleanupGrant !== readCleanupGrant() ||
198 this.target?.ownerKey !== options.draft.ownerKey
199 )
200 return null;
201 if (!preferences.cleanupPrepared)
202 return Promise.reject(
203 new Error(m(msg("The draft's environment is unavailable for transcript cleanup."))),
204 );
205 return runEnvironmentSpeech(
206 postProcessEnvironmentTranscript(
207 preferences.cleanupPrepared,
208 transcript,
209 cleanupContext(options.draft),
210 preferences.cleanup,
211 () => hasAudioConsent() && preferences.cleanupGrant === readCleanupGrant(),
212 ),
213 options,
214 ).then((result) => result.text);
215 };
216 this.controller = new VoiceInputController({
217 resolve: m,
218 retryFailedRecording: true,
219 recorder: platform.recorder,
220 getTranscriber: () => platform.transcriber,
221 requestPermission: async () => ({ granted: true, canAskAgain: true }),
222 configureRecording: async () => undefined,
223 releaseRecording: async () => platform.cancelRecording(),
224 deleteRecording: platform.deleteRecording,
225 postProcess,
226 onPostProcessingError: (error) => {
227 const added = m(msg("The original transcript was added."));
228 const detail = isEnvironmentInternalError(error) ? error.detail : undefined;
229 toastManager.add({
230 type: "warning",
231 title: m(msg("Transcript cleanup failed")),
232 description: detail ? `${detail} ${added}` : added,
233 });
234 },
235 readDraft: (): VoiceDraftSnapshot | null => {
236 const target = this.target;
237 const draft = target?.readDraft();
238 return target && draft ? { ownerKey: target.ownerKey, ...draft } : null;
239 },
240 commitDraft: (text, selection) => this.target?.commitDraft(text, selection),
241 onStateChange: (state) => {
242 if (this.disposed) return;
243 const recordingStartedAt =
244 state.phase !== "recording" ? null : (this.snapshot.recordingStartedAt ?? Date.now());
245 this.publish({ ...this.snapshot, state, recordingStartedAt });
246 if (state.phase !== "recording" && state.phase !== "transcribing")
247 this.publishActivity(SILENT_ACTIVITY);
248 },
249 });
250 }
251​
252 get state(): VoiceInputState {
253 return this.controller.currentState;
254 }
255​
256 get ownerKey(): string | null {
257 return this.target?.ownerKey ?? null;
258 }
259​
260 readonly subscribe = (listener: () => void): (() => void) => {
261 this.listeners.add(listener);
262 return () => this.listeners.delete(listener);
263 };
264​
265 readonly getSnapshot = (): VoiceInputSessionSnapshot => this.snapshot;
266​
267 readonly subscribeActivity = (listener: () => void): (() => void) => {
268 this.activityListeners.add(listener);
269 return () => this.activityListeners.delete(listener);
270 };
271​
272 readonly getActivity = (): VoiceInputSessionActivity => this.activity;
273​
274 /** Starts recording into `target`, or does nothing while another draft holds the microphone. */
275 start(
276 target: VoiceInputTarget,
277 onSpeechStatus?: (status: EnvironmentSpeechStatus) => void,
278 ): Promise<void> {
279 if (this.disposed) return Promise.resolve();
280 const busyElsewhere =
281 voiceInputBlocksSubmission(this.controller.currentState) &&
282 this.target?.ownerKey !== target.ownerKey;
283 if (busyElsewhere) return Promise.resolve();
284 this.target = target;
285 this.onSpeechStatus = onSpeechStatus;
286 this.publishActivity(SILENT_ACTIVITY);
287 this.publish({ ...this.snapshot, target });
288 return this.controller.start();
289 }
290​
291 /** A newly mounted editor for the recording's draft replaces the target that started it. */
292 adopt(target: VoiceInputTarget): void {
293 if (this.disposed || this.target?.ownerKey !== target.ownerKey) return;
294 this.target = target;
295 this.publish({ ...this.snapshot, target });
296 }
297​
298 stop(): Promise<void> {
299 return this.controller.stop();
300 }
301​
302 cancel(): void {
303 this.controller.cancel();
304 }
305​
306 skipPostProcessing(): void {
307 this.controller.skipPostProcessing();
308 }
309​
310 /** The editor for `ownerKey` now shows another draft; only a persistent target keeps going. */
311 ownerChanged(ownerKey: string): void {
312 if (this.target?.ownerKey !== ownerKey || this.target.persistent) return;
313 this.controller.ownerChanged();
314 }
315​
316 dispose(): void {
317 this.disposed = true;
318 this.controller.dispose();
319 this.listeners.clear();
320 this.activityListeners.clear();
321 }
322​
323 private publish(snapshot: VoiceInputSessionSnapshot): void {
324 this.snapshot = snapshot;
325 for (const listener of this.listeners) listener();
326 }
327​
328 private publishActivity(activity: VoiceInputSessionActivity): void {
329 if (activity.level === this.activity.level && activity.preview === this.activity.preview)
330 return;
331 this.activity = activity;
332 for (const listener of this.activityListeners) listener();
333 }
335​
336const sessions = new Map<VoiceInputSession, number>();
337const registryListeners = new Set<() => void>();
338​
339function sameKey(session: VoiceInputSession, key: SessionKey): boolean {
340 return (
341 session.key.prepared === key.prepared &&
342 session.key.grantId === key.grantId &&
343 session.key.cloudProvider === key.cloudProvider &&
344 session.key.cloudModel === key.cloudModel
345 );
347​
348function findSession(key: SessionKey): VoiceInputSession | null {
349 for (const session of sessions.keys()) if (sameKey(session, key)) return session;
350 return null;
352​
353/** Every holder of a destination shares one session; the last release disposes it. */
354function retainVoiceInputSession(key: SessionKey): () => void {
355 const session = findSession(key) ?? new VoiceInputSession(key);
356 sessions.set(session, (sessions.get(session) ?? 0) + 1);
357 for (const listener of registryListeners) listener();
358 let released = false;
359 return () => {
360 if (released) return;
361 released = true;
362 const count = (sessions.get(session) ?? 1) - 1;
363 if (count > 0) {
364 sessions.set(session, count);
365 return;
366 }
367 sessions.delete(session);
368 session.dispose();
369 for (const listener of registryListeners) listener();
370 };
372​
373function subscribeRegistry(listener: () => void): () => void {
374 registryListeners.add(listener);
375 return () => registryListeners.delete(listener);
377​
378/** Holds the destination's shared session while mounted; null until it is retained. */
379export function useRetainedVoiceInputSession(input: {
380 readonly prepared: PreparedConnection | null;
381 readonly grantId: string | null;
382 readonly onDevice?: boolean | undefined;
383 readonly cloudProvider?: CloudSpeechProvider | undefined;
384 readonly cloudModel?: CloudSpeechModelId | undefined;
385}): VoiceInputSession | null {
386 const { grantId, cloudProvider, cloudModel } = input;
387 const prepared = input.onDevice ? null : input.prepared;
388 const ready = (input.onDevice === true || prepared !== null) && grantId !== null;
389 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- retains the shared recording session for this destination while mounted
390 useEffect(() => {
391 if (!ready || !grantId || typeof navigator === "undefined") return;
392 return retainVoiceInputSession({ prepared, grantId, cloudProvider, cloudModel });
393 }, [ready, prepared, grantId, cloudProvider, cloudModel]);
394 return useSyncExternalStore(subscribeRegistry, () =>
395 ready && grantId ? findSession({ prepared, grantId, cloudProvider, cloudModel }) : null,
396 );
398​
399const IDLE_SNAPSHOT: VoiceInputSessionSnapshot = {
400 state: IDLE_VOICE_STATE,
401 target: null,
402 recordingStartedAt: null,
403};
404const noSubscription = () => () => {};
405​
406export function useVoiceInputSessionSnapshot(
407 session: VoiceInputSession | null,
408): VoiceInputSessionSnapshot {
409 return useSyncExternalStore(
410 session?.subscribe ?? noSubscription,
411 session ? session.getSnapshot : () => IDLE_SNAPSHOT,
412 );
414​
415export function useVoiceInputSessionActivity(
416 session: VoiceInputSession | null,
417 ownerKey: string | null,
418): VoiceInputSessionActivity {
419 // Activity changes many times a second, so only the owning editor reads it.
420 const owns = useSyncExternalStore(
421 session?.subscribe ?? noSubscription,
422 () => session !== null && ownerKey !== null && session.ownerKey === ownerKey,
423 );
424 return useSyncExternalStore(owns && session ? session.subscribeActivity : noSubscription, () =>
425 owns && session ? session.getActivity() : SILENT_ACTIVITY,
426 );
428​
429// Editors register the owner they show, so the indicator appears only while its draft is off screen.
430const presentedOwners = new Map<string, number>();
431const presentationListeners = new Set<() => void>();
432​
433export function presentVoiceOwner(ownerKey: string): () => void {
434 presentedOwners.set(ownerKey, (presentedOwners.get(ownerKey) ?? 0) + 1);
435 for (const listener of presentationListeners) listener();
436 return () => {
437 const count = (presentedOwners.get(ownerKey) ?? 1) - 1;
438 if (count > 0) presentedOwners.set(ownerKey, count);
439 else presentedOwners.delete(ownerKey);
440 for (const listener of presentationListeners) listener();
441 };
443​
444function subscribePresentation(listener: () => void): () => void {
445 presentationListeners.add(listener);
446 return () => presentationListeners.delete(listener);
448​
449export function useVoiceOwnerPresented(ownerKey: string | null): boolean {
450 return useSyncExternalStore(
451 subscribePresentation,
452 () => ownerKey !== null && presentedOwners.has(ownerKey),
453 );