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