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

main
tsx 299 lines 12.3 KB
Raw
1 import { T, Var, msg, useGT, useLocale } from "gt-react";
2 import { m } from "~/i18n/messages";
3 import { useStableCallback } from "~/hooks/useStableCallback";
4 import {
5 listBrowserMicrophones,
6 updateMicrophoneOrder,
7 type BrowserMicrophone,
8 } from "../../speech/browserMicrophones";
9 import type {
10 EnvironmentId,
11 EnvironmentSpeechModel,
12 EnvironmentSpeechStatus,
13 } from "@t3tools/contracts";
14 import { useNavigate } from "@tanstack/react-router";
15 import { CircleAlertIcon, MicIcon, RefreshCwIcon } from "lucide-react";
16 import { useEffect, useRef, useState } from "react";
17
18 import { useClientSettings } from "../../hooks/useSettings";
19 import {
20 isSystemDefaultDeviceId,
21 microphoneOrder,
22 preferMicrophone,
23 preferredMicrophoneId,
24 } from "../../speech/microphoneOrder";
25 import { useEnvironment } from "../../state/environments";
26 import { AuthSettingsWriteScope } from "@t3tools/contracts";
27 import { useEnvironmentScope } from "../../state/session";
28 import { languageLabel } from "../settings/SpeechLanguageSelect";
29 import { Button } from "../ui/button";
30 import { Dialog } from "../ui/dialog";
31 import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
32 import { WizardFooter, WizardHeader, WizardPanel, WizardPopup } from "../ui/wizard";
33
34 export function VoiceInputSetup(props: {
35 environmentId: EnvironmentId | null;
36 open: boolean;
37 step: number;
38 status: EnvironmentSpeechStatus | null;
39 model: EnvironmentSpeechModel | null;
40 /** The language the offered model was chosen for. */
41 language: string | null;
42 downloading: boolean;
43 error: string | null;
44 onOpenChange(open: boolean): void;
45 onRetryCatalog: (() => void) | null;
46 onDownload(): void;
47 onCancelDownload(): void;
48 onStartRecording(): void;
49 }) {
50 const gt = useGT();
51 const locale = useLocale();
52 const navigate = useNavigate();
53 const environment = useEnvironment(props.environmentId);
54 const languageName = props.language ? languageLabel(props.language, locale) : null;
55 const canManage = useEnvironmentScope(props.environmentId, AuthSettingsWriteScope);
56 const order = useClientSettings(microphoneOrder);
57 const [microphones, setMicrophones] = useState<BrowserMicrophone[]>([]);
58 const selectedMicrophone = preferredMicrophoneId(order, microphones);
59 const [loadingMicrophones, setLoadingMicrophones] = useState(false);
60 const [microphoneError, setMicrophoneError] = useState<string | null>(null);
61 const microphoneRefreshId = useRef(0);
62 const refreshMicrophones = useStableCallback(async () => {
63 if (!navigator.mediaDevices?.enumerateDevices) return;
64 const requestId = ++microphoneRefreshId.current;
65 setLoadingMicrophones(true);
66 const devices = await listBrowserMicrophones().catch(() => null);
67 if (requestId !== microphoneRefreshId.current) return;
68
69 if (devices === null) {
70 setMicrophoneError(m(msg("Couldn’t list microphones. The system default still works.")));
71 } else {
72 setMicrophones(devices);
73 setMicrophoneError(null);
74 }
75 setLoadingMicrophones(false);
76 });
77 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to native microphone changes while the device setup step is visible
78 useEffect(() => {
79 if (!props.open || props.step !== 1) return;
80 queueMicrotask(() => void refreshMicrophones());
81 const mediaDevices = navigator.mediaDevices;
82 mediaDevices?.addEventListener?.("devicechange", refreshMicrophones);
83 return () => mediaDevices?.removeEventListener?.("devicechange", refreshMicrophones);
84 }, [props.open, props.step, refreshMicrophones]);
85 const selectedIsUnavailable = Boolean(
86 selectedMicrophone && !microphones.some((device) => device.deviceId === selectedMicrophone),
87 );
88 const selectedMicrophoneLabel = selectedMicrophone
89 ? (microphones.find((device) => device.deviceId === selectedMicrophone)?.label ??
90 gt("Selected microphone (Unavailable)"))
91 : gt("System default");
92 const status = props.status?.supported ? props.status : null;
93 const model = props.model;
94 const progress =
95 model?.downloaded === undefined ? null : Math.round((model.downloaded / model.size) * 100);
96 const openSettings = (hash: string) => {
97 props.onOpenChange(false);
98 void navigate({ to: "/settings/voice", hash });
99 };
100
101 return (
102 <Dialog open={props.open} onOpenChange={props.onOpenChange}>
103 <WizardPopup>
104 <WizardHeader
105 title={props.step === 0 ? gt("Set up voice input") : gt("Voice input is ready")}
106 description={
107 props.step === 0
108 ? environment?.label != null
109 ? gt("Download a speech model once. Your audio is transcribed on {destination}.", {
110 destination: environment.label,
111 })
112 : gt(
113 "Download a speech model once. Your audio is transcribed on your transcription environment.",
114 )
115 : gt("Pick a microphone, then start talking.")
116 }
117 />
118 <WizardPanel>
119 {props.step === 0 ? (
120 <section className="space-y-3 text-sm">
121 {model ? (
122 <div className="space-y-3 rounded-lg border border-border/70 bg-card/60 p-3">
123 <div className="flex items-baseline justify-between gap-3">
124 <h3 className="min-w-0 truncate font-medium">{model.name}</h3>
125 <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
126 {gt("{size} MB", { size: Math.round(model.size / 1024 / 1024) })}
127 </span>
128 </div>
129 <p className="text-xs text-muted-foreground">
130 {model.recommended && props.language ? (
131 <T>
132 Recommended for <Var>{languageName}</Var>. Includes a 1.2 MB silence
133 detector.
134 </T>
135 ) : (
136 <T>Includes a 1.2 MB silence detector.</T>
137 )}
138 </p>
139 {props.downloading ? (
140 <div role="status" className="space-y-1.5">
141 <div
142 role="progressbar"
143 aria-label={gt("Speech model download progress")}
144 aria-valuemin={0}
145 aria-valuemax={100}
146 aria-valuenow={progress ?? undefined}
147 className="h-1 overflow-hidden rounded-full bg-muted"
148 >
149 <div
150 className="h-full bg-primary transition-[width] duration-200"
151 style={{ width: `${progress ?? 0}%` }}
152 />
153 </div>
154 <p className="text-xs text-muted-foreground tabular-nums">
155 {model.state === "verifying"
156 ? gt("Verifying…")
157 : progress === null
158 ? gt("Starting download…")
159 : gt("{progress}% downloaded", { progress })}
160 </p>
161 </div>
162 ) : null}
163 </div>
164 ) : !props.error ? (
165 <p role="status" className="text-muted-foreground">
166 <T>Loading transcription models…</T>
167 </p>
168 ) : null}
169 {props.error ? (
170 <p role="alert" className="flex items-start gap-1.5 text-destructive">
171 <CircleAlertIcon aria-hidden className="mt-0.5 size-3.5 shrink-0" />
172 {props.error}
173 </p>
174 ) : null}
175 </section>
176 ) : (
177 <section className="space-y-2 text-sm">
178 <label className="sr-only" htmlFor="voice-setup-microphone">
179 <T>Microphone</T>
180 </label>
181 <div className="flex items-center gap-2">
182 <Select
183 value={selectedMicrophone ? `device:${selectedMicrophone}` : "system-default"}
184 disabled={loadingMicrophones}
185 onValueChange={(value) => {
186 if (!value) return;
187 const deviceId = value.slice("device:".length);
188 const label =
189 microphones.find((device) => device.deviceId === deviceId)?.label ?? "";
190 updateMicrophoneOrder((order) =>
191 preferMicrophone(
192 order,
193 value === "system-default" || isSystemDefaultDeviceId(deviceId)
194 ? { kind: "default" }
195 : { kind: "device", deviceId, label },
196 ),
197 );
198 }}
199 >
200 <SelectTrigger
201 id="voice-setup-microphone"
202 size="sm"
203 aria-label={gt("Microphone")}
204 className="min-w-0 flex-1"
205 >
206 <MicIcon aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
207 <SelectValue>{selectedMicrophoneLabel}</SelectValue>
208 </SelectTrigger>
209 <SelectPopup align="end" alignItemWithTrigger={false}>
210 <SelectItem value="system-default">
211 <T>System default</T>
212 </SelectItem>
213 {selectedIsUnavailable ? (
214 <SelectItem value={`device:${selectedMicrophone}`}>
215 <T>Selected microphone (Unavailable)</T>
216 </SelectItem>
217 ) : null}
218 {microphones.map((device) => (
219 <SelectItem key={device.deviceId} value={`device:${device.deviceId}`}>
220 {device.label}
221 </SelectItem>
222 ))}
223 </SelectPopup>
224 </Select>
225 <Button
226 type="button"
227 variant="ghost"
228 size="icon-sm"
229 disabled={loadingMicrophones}
230 aria-label={gt("Refresh microphones")}
231 onClick={() => void refreshMicrophones()}
232 >
233 <RefreshCwIcon className="size-3.5" />
234 </Button>
235 </div>
236 {selectedIsUnavailable ? (
237 <p className="text-xs text-destructive">
238 <T>That microphone is unplugged. Pick another one.</T>
239 </p>
240 ) : null}
241 {microphoneError ? (
242 <p role="alert" className="text-xs text-muted-foreground">
243 {microphoneError}
244 </p>
245 ) : null}
246 </section>
247 )}
248 </WizardPanel>
249 {props.step === 0 ? (
250 <WizardFooter
251 leading={
252 <Button variant="ghost" onClick={() => openSettings("speech-models")}>
253 {model ? gt("Other models") : gt("Choose a model")}
254 </Button>
255 }
256 >
257 {props.onRetryCatalog ? (
258 <Button onClick={props.onRetryCatalog}>
259 <T>Retry loading models</T>
260 </Button>
261 ) : null}
262 {props.downloading ? (
263 <Button variant="outline" disabled={!canManage} onClick={props.onCancelDownload}>
264 <T>Cancel download</T>
265 </Button>
266 ) : null}
267 {model ? (
268 <Button
269 disabled={!canManage || props.downloading || !status}
270 onClick={props.onDownload}
271 >
272 {props.downloading
273 ? gt("Downloading…")
274 : props.error
275 ? gt("Try again")
276 : canManage
277 ? gt("Download model")
278 : gt("Needs an admin to download")}
279 </Button>
280 ) : null}
281 </WizardFooter>
282 ) : (
283 <WizardFooter
284 leading={
285 <Button variant="ghost" onClick={() => openSettings("")}>
286 <T>Voice settings</T>
287 </Button>
288 }
289 >
290 <Button onClick={props.onStartRecording}>
291 <MicIcon />
292 <T>Start dictating</T>
293 </Button>
294 </WizardFooter>
295 )}
296 </WizardPopup>
297 </Dialog>
298 );
299 }