@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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