Open History to see the last commit
1import { useAtomRefresh, useAtomValue } from "@effect/atom-react";
2import { useNavigation } from "@react-navigation/native";
3import {
4 cancelEnvironmentSpeechModelDownload,
5 downloadEnvironmentSpeechModel,
6 selectEnvironmentSpeechModel,
7} from "@t3tools/client-runtime/voice-input";
8import {
9 AuthSettingsWriteScope,
10 type EnvironmentId,
11 type EnvironmentSpeechModel,
12} from "@t3tools/contracts";
13import { AsyncResult } from "effect/reactivity";
14import { type ReactNode, useEffect, useState } from "react";
15import { Platform, Text as NativeText, View } from "react-native";
16
17import { SymbolView } from "../../components/ui/AppSymbol";
18import { AppText as Text } from "../../components/ui/AppText";
19import * as Dialog from "../../components/ui/Dialog";
20import { ListActionRow } from "../../components/ui/ListActionRow";
21import { ListChoiceRow } from "../../components/ui/ListChoiceRow";
22import { ListRow } from "../../components/ui/ListRow";
23import { Progress } from "../../components/ui/Progress";
24import { formatBytes } from "../../lib/formatBytes";
25import { useEnvironmentScope } from "../../state/session";
26import {
27 runSpeech,
28 voiceConnectionAtom,
29 voiceSpeechModelsAtom,
30 voiceSpeechStatusAtom,
31} from "../voice-input/voiceDestination";
32import { SettingsSection } from "./components/SettingsSection";
33
34const isDownloading = (model: EnvironmentSpeechModel) =>
35 model.state === "downloading" || model.state === "verifying";
36
37export function useVoiceModels(environmentId: EnvironmentId, label: string) {
38 const connection = useAtomValue(voiceConnectionAtom(environmentId));
39 const statusAtom = voiceSpeechStatusAtom(environmentId);
40 const modelsAtom = voiceSpeechModelsAtom(environmentId);
41 const status = AsyncResult.getOrElse(useAtomValue(statusAtom), () => null);
42 const modelsResult = useAtomValue(modelsAtom);
43 const refreshStatus = useAtomRefresh(statusAtom);
44 const refreshModels = useAtomRefresh(modelsAtom);
45 const canManage = useEnvironmentScope(environmentId, AuthSettingsWriteScope);
46 const [requested, setRequested] = useState<string | null>(null);
47 const [busy, setBusy] = useState(false);
48
49 const models = AsyncResult.getOrElse(modelsResult, () => null)?.models ?? [];
50 const downloading = requested !== null || models.some(isDownloading);
51
52 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- polls the environment's download progress while one runs
53 useEffect(() => {
54 if (!downloading) return;
55 const timer = setInterval(refreshModels, 1_000);
56 return () => clearInterval(timer);
57 }, [downloading, refreshModels]);
58
59 const run = async (title: string, work: () => Promise<unknown>, downloadId?: string) => {
60 if (downloadId) setRequested(downloadId);
61 else setBusy(true);
62 try {
63 await work();
64 } catch (error) {
65 Dialog.alert(title, error instanceof Error ? error.message : String(error));
66 }
67 if (downloadId) setRequested(null);
68 else setBusy(false);
69 refreshModels();
70 refreshStatus();
71 };
72 const ready = connection !== null && status?.supported === true;
73 return {
74 connection,
75 status,
76 models,
77 loading: modelsResult._tag === "Initial",
78 canManage,
79 requested,
80 busy,
81 downloading,
82 label,
83 download: (model: EnvironmentSpeechModel) => {
84 if (!ready) return;
85 Dialog.confirm({
86 title: `Download ${model.name}?`,
87 message: `${label} will download ${formatBytes(model.size)} and use it as its transcription model.`,
88 confirmText: "Download",
89 onConfirm: () =>
90 void run(
91 "Could not download the model",
92 async () => {
93 await runSpeech(downloadEnvironmentSpeechModel(connection, model.id));
94 if (model.id !== status.modelId)
95 await runSpeech(selectEnvironmentSpeechModel(connection, model.id));
96 },
97 model.id,
98 ),
99 });
100 },
101 select: (model: EnvironmentSpeechModel) => {
102 if (!ready || model.active) return;
103 void run("Could not select the model", () =>
104 runSpeech(selectEnvironmentSpeechModel(connection, model.id)),
105 );
106 },
107 cancel: (model: EnvironmentSpeechModel) => {
108 if (!ready) return;
109 void run("Could not cancel the download", () =>
110 runSpeech(cancelEnvironmentSpeechModelDownload(connection, model.id)),
111 );
112 },
113 };
114}
115
116export type VoiceModels = ReturnType<typeof useVoiceModels>;
117
118const languageNames =
119 typeof Intl.DisplayNames === "function"
120 ? new Intl.DisplayNames(undefined, { type: "language" })
121 : null;
122const languageLabel = (code: string) => languageNames?.of(code) ?? code.toUpperCase();
123
124function ModelStats(props: { readonly model: EnvironmentSpeechModel; readonly language: string }) {
125 const { model, language } = props;
126 const data = model.benchmark;
127 const code = !data
128 ? undefined
129 : data.accuracy[language]
130 ? language
131 : (model.languages.find((candidate) => data.accuracy[candidate]) ?? model.languages[0]);
132 const score = code ? data?.accuracy[code] : undefined;
133 const parts: ReadonlyArray<readonly [string, ReactNode]> = [
134 ...(code && score
135 ? ([
136 [
137 "score",
138 <>
139 {languageLabel(code)}{" "}
140 <Text className="font-t3-medium text-foreground">{score.grade}</Text> (
141 {score.errorPercent}% error)
142 </>,
143 ],
144 ] as const)
145 : []),
146 ...(data && data.secondsPer30s !== null
147 ? ([
148 [
149 "speed",
150 <>
151 <Text className="font-t3-medium text-foreground">{data.secondsPer30s} s</Text> / 30 s
152 </>,
153 ],
154 ] as const)
155 : []),
156 // A single-language model's score already names its language.
157 ...(model.languages.length > 1
158 ? ([
159 [
160 "languages",
161 <>
162 <SymbolView
163 name="globe"
164 size={13}
165 tintColorClassName="accent-icon-muted"
166 type="monochrome"
167 weight="regular"
168 />{" "}
169 {model.languages.length}
170 </>,
171 ],
172 ] as const)
173 : score
174 ? []
175 : ([["languages", languageLabel(model.languages[0] ?? "")]] as const)),
176 ["size", formatBytes(model.size)],
177 ];
178 return (
179 <Text textRole="footnote" className="text-foreground-muted tabular-nums">
180 {parts.map(([key, part], index) => (
181 // Plain Text inherits the muted footnote style; AppText would reset it.
182 <NativeText key={key}>
183 {index > 0 ? " · " : null}
184 {part}
185 </NativeText>
186 ))}
187 </Text>
188 );
189}
190
191function DownloadedGlyph() {
192 return (
193 <View className="size-6">
194 <SymbolView
195 name="tray.and.arrow.down"
196 size={Platform.OS === "android" ? 24 : 22}
197 tintColorClassName="accent-icon"
198 type="monochrome"
199 weight="regular"
200 />
201 <View className="absolute -right-1.5 -bottom-1 size-3.5 items-center justify-center rounded-full bg-primary ring-2 ring-grouped-card">
202 <SymbolView
203 name="checkmark"
204 size={9}
205 tintColorClassName="accent-primary-foreground"
206 type="monochrome"
207 weight="bold"
208 />
209 </View>
210 </View>
211 );
212}
213
214export function VoiceModelRow(props: {
215 readonly model: EnvironmentSpeechModel;
216 readonly voice: VoiceModels;
217 readonly separated: boolean;
218 /** The language whose benchmark score to show, when the model has one. */
219 readonly language: string;
220}) {
221 const { model, voice, separated } = props;
222 const meta = <ModelStats model={model} language={props.language} />;
223 if (model.state === "installed")
224 return (
225 <ListChoiceRow
226 leading={<DownloadedGlyph />}
227 label={model.name}
228 description={model.description}
229 meta={meta}
230 selected={model.active}
231 separated={separated}
232 disabled={!voice.canManage || voice.busy || voice.downloading}
233 onPress={() => voice.select(model)}
234 />
235 );
236 const progress = model.downloaded === undefined ? undefined : model.downloaded / model.size;
237 if (isDownloading(model) || voice.requested === model.id)
238 return (
239 <View className={separated ? "border-t border-border-subtle" : ""}>
240 <ListActionRow
241 icon="xmark"
242 label={model.name}
243 description={
244 model.state === "verifying"
245 ? "Verifying download…"
246 : `${Math.round((progress ?? 0) * 100)}% downloaded · Tap to cancel`
247 }
248 disabled={!voice.canManage || voice.busy}
249 onPress={() => voice.cancel(model)}
250 />
251 <Progress
252 className="bg-grouped-card px-4 pb-3"
253 value={model.state === "verifying" ? undefined : progress}
254 label={`${model.name} download progress`}
255 />
256 </View>
257 );
258 return (
259 <View className={separated ? "border-t border-border-subtle" : ""}>
260 <ListActionRow
261 icon="tray.and.arrow.down"
262 label={model.name}
263 description={model.description}
264 meta={meta}
265 disabled={!voice.canManage || voice.busy || voice.downloading}
266 onPress={() => voice.download(model)}
267 />
268 </View>
269 );
270}
271
272export function VoiceModelSection(props: {
273 readonly environmentId: EnvironmentId;
274 readonly label: string;
275}) {
276 const navigation = useNavigation();
277 const voice = useVoiceModels(props.environmentId, props.label);
278 const { status } = voice;
279 if (!voice.connection || !status) return null;
280 const title = `Transcription model on ${props.label}`;
281 if (!status.supported) {
282 return (
283 <SettingsSection title={title} footer={status.reason}>
284 {null}
285 </SettingsSection>
286 );
287 }
288
289 const active = status.state === "missing-model" ? null : status;
290 const pending = voice.models.find(isDownloading);
291 const progress =
292 pending?.downloaded === undefined ? undefined : pending.downloaded / pending.size;
293 return (
294 <SettingsSection
295 title={title}
296 footer={
297 voice.canManage
298 ? undefined
299 : `This connection can’t change settings on ${props.label}. Add a transcription model using T3 Code on that machine.`
300 }
301 >
302 <ListRow
303 label={active?.model ?? "No model selected"}
304 description={
305 pending
306 ? pending.state === "verifying"
307 ? `Verifying ${pending.name}…`
308 : `Downloading ${pending.name} · ${Math.round((progress ?? 0) * 100)}%`
309 : active
310 ? formatBytes(active.size)
311 : "Choose a transcription model to dictate on this environment."
312 }
313 onPress={() =>
314 navigation.navigate("SettingsVoiceModels", { environmentId: props.environmentId })
315 }
316 />
317 </SettingsSection>
318 );
319}