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

voiceDestination.ts

181 lines6.6 KB

1import {
2 AuthOrchestrationOperateScope,
3 type EnvironmentId,
4 DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS,
5} from "@t3tools/contracts";
6import {
7 getEnvironmentSpeechModels,
8 getEnvironmentSpeechStatus,
9 transcribeEnvironmentPcm,
10 VoiceTranscriptionError,
11} from "@t3tools/client-runtime/voice-input";
12import { FetchHttpClient, type HttpClient } from "effect/http";
13import type { PreparedConnection } from "@t3tools/client-runtime/connection";
14import { effectiveSpeechLanguage } from "@t3tools/shared/speech";
15import * as Effect from "effect/Effect";
16import * as Option from "effect/Option";
17import { Atom, AsyncResult, AtomRegistry } from "effect/reactivity";
18import { requireOptionalNativeModule } from "expo";
19import { fetch as expoFetch } from "expo/fetch";
20​
21import { appAtomRegistry } from "../../state/atom-registry";
22import { environmentPresentations } from "../../state/presentation";
23import { environmentSession, sessionHasScope } from "../../state/session";
24import { connectionAtomRuntime } from "../../connection/runtime";
25import { uuidv4 } from "../../lib/uuid";
26import { createEnvironmentTranscriber } from "./environmentTranscriber";
27import { readVoiceGrant, writeVoiceGrant, type VoiceGrant } from "./voiceGrantStorage";
28​
29const storedGrant = Atom.make(Effect.promise(readVoiceGrant)).pipe(Atom.keepAlive);
30const choice = Atom.make<VoiceGrant | null | undefined>(undefined).pipe(Atom.keepAlive);
31export const voiceGrantAtom = Atom.make((get) => {
32 const chosen = get(choice);
33 if (chosen !== undefined) return chosen;
34 return AsyncResult.getOrElse(get(storedGrant), () => null);
35});
36​
37export function chooseVoiceDestination(environmentId: EnvironmentId | null) {
38 // A failed change must not leave the old destination armed in this session.
39 appAtomRegistry.set(choice, null);
40 const grant: VoiceGrant | null =
41 environmentId === null
42 ? null
43 : {
44 id: uuidv4(),
45 destination: { kind: "environment", environmentId },
46 };
47 writeVoiceGrant(grant);
48 appAtomRegistry.set(choice, grant);
50​
51const native = requireOptionalNativeModule<{
52 decodeRecording?: (uri: string) => Promise<Uint8Array>;
53}>("T3VoiceTranscription");
54export const hasEnvironmentVoiceCapture = typeof native?.decodeRecording === "function";
55​
56export const voiceConnectionAtom = Atom.family((id: EnvironmentId) =>
57 Atom.make((get) => {
58 const environment = get(environmentPresentations.presentationAtom(id));
59 if (
60 !hasEnvironmentVoiceCapture ||
61 environment?.connection.phase !== "connected" ||
62 !environment.serverConfig?.environment.capabilities.voiceTranscription ||
63 !sessionHasScope(get(environmentSession.sessionStateAtom(id)), AuthOrchestrationOperateScope)
64 )
65 return null;
66 return Option.getOrNull(get(environmentSession.preparedConnectionValueAtom(id)));
67 }),
68);
69​
70// React Native's XMLHttpRequest fetch follows redirects. Expo's native transport honors redirect: "error".
71export function runSpeech<A, E>(
72 effect: Effect.Effect<A, E, HttpClient.HttpClient>,
73 signal?: AbortSignal,
74 canSend: () => boolean = () => true,
75) {
76 return Effect.runPromise(
77 AtomRegistry.getResult(appAtomRegistry, connectionAtomRuntime).pipe(
78 Effect.flatMap((context) =>
79 effect.pipe(
80 Effect.provideService(FetchHttpClient.Fetch, async (url, options) => {
81 if (signal?.aborted || !canSend())
82 throw new VoiceTranscriptionError({
83 code: "cancelled",
84 message: "Your transcription choice changed.",
85 });
86 return expoFetch(url, { ...options, redirect: "error" });
87 }),
88 Effect.provide(context),
89 ),
90 ),
91 ),
92 { signal },
93 );
95function environmentTranscriber(prepared: PreparedConnection, canSend: () => boolean) {
96 return createEnvironmentTranscriber({
97 canSend,
98 prepare: async (signal) => {
99 const status = await runSpeech(getEnvironmentSpeechStatus(prepared), signal, canSend);
100 if (!status.supported)
101 throw new VoiceTranscriptionError({ code: "unavailable", message: status.reason });
102 if (status.state === "missing-model")
103 throw new VoiceTranscriptionError({
104 code: "unavailable",
105 message:
106 "Install a transcription model for this environment in Settings → Voice, then try again.",
107 });
108 return status.languages
109 ? effectiveSpeechLanguage(
110 {
111 languages: status.languages,
112 supportsLanguageDetection: status.supportsLanguageDetection ?? false,
113 },
114 "auto",
115 )
116 : "auto";
117 },
118 decode: (uri) => {
119 if (!native?.decodeRecording)
120 throw new VoiceTranscriptionError({
121 code: "unavailable",
122 message: "Update T3 Code to transcribe on an environment.",
123 });
124 return native.decodeRecording(uri);
125 },
126 upload: async (pcm, signal) =>
127 (
128 await runSpeech(
129 transcribeEnvironmentPcm(prepared, pcm, DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS, canSend),
130 signal,
131 canSend,
132 )
133 ).text,
134 });
136​
137const speechAtom = <A, E>(
138 id: EnvironmentId,
139 read: (prepared: PreparedConnection) => Effect.Effect<A, E, HttpClient.HttpClient>,
140) =>
141 Atom.make((get) => {
142 const prepared = get(voiceConnectionAtom(id));
143 return prepared
144 ? Effect.tryPromise({
145 try: (signal) => runSpeech(read(prepared), signal),
146 catch: (cause) =>
147 new VoiceTranscriptionError({
148 code: "unavailable",
149 message: cause instanceof Error ? cause.message : String(cause),
150 }),
151 })
152 : Effect.succeed(null);
153 });
154​
155export const voiceSpeechStatusAtom = Atom.family((id: EnvironmentId) =>
156 speechAtom(id, getEnvironmentSpeechStatus),
157);
158export const voiceSpeechModelsAtom = Atom.family((id: EnvironmentId) =>
159 speechAtom(id, (prepared) => getEnvironmentSpeechModels(prepared)),
160);
161// Fetched once for the model sheet; download progress polls the lighter list above.
162export const voiceSpeechBenchmarksAtom = Atom.family((id: EnvironmentId) =>
163 speechAtom(id, (prepared) => getEnvironmentSpeechModels(prepared, true)),
164);
165​
166// null selects on-device; a grant with no usable transcriber must never fall back.
167export const voiceRouteAtom = Atom.make((get) => {
168 const grant = get(voiceGrantAtom);
169 if (!grant) return null;
170 const connectionAtom = voiceConnectionAtom(grant.destination.environmentId);
171 const connection = get(connectionAtom);
172 const registry = get.registry;
173 return {
174 transcriber:
175 connection &&
176 environmentTranscriber(
177 connection,
178 () => registry.get(voiceGrantAtom) === grant && registry.get(connectionAtom) === connection,
179 ),
180 };
181});