Open History to see the last commit
1import { useStableCallback } from "~/hooks/useStableCallback";
2import { listBrowserMicrophones, type BrowserMicrophone } from "../../speech/browserMicrophones";
3import type {
4 EnvironmentId,
5 EnvironmentSpeechModel,
6 EnvironmentSpeechStatus,
7} from "@t3tools/contracts";
8import { useNavigate } from "@tanstack/react-router";
9import { RefreshCwIcon } from "lucide-react";
10import { useEffect, useState } from "react";
11
12import { useClientSettings, updateClientSettings } from "../../hooks/useSettings";
13import { useEnvironment } from "../../state/environments";
14import { AuthSettingsWriteScope } from "@t3tools/contracts";
15import { useEnvironmentScope } from "../../state/session";
16import { languageLabel } from "../settings/SpeechLanguageSelect";
17import { Button } from "../ui/button";
18import { Dialog } from "../ui/dialog";
19import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
20import { WizardFooter, WizardHeader, WizardPanel, WizardPopup, WizardSteps } from "../ui/wizard";
21
22export function VoiceInputSetup(props: {
23 environmentId: EnvironmentId | null;
24 open: boolean;
25 step: number;
26 status: EnvironmentSpeechStatus | null;
27 model: EnvironmentSpeechModel | null;
28 /** The language the offered model was chosen for. */
29 language: string | null;
30 downloading: boolean;
31 error: string | null;
32 onOpenChange(open: boolean): void;
33 onRetryCatalog: (() => void) | null;
34 onDownload(): void;
35 onCancelDownload(): void;
36 onStartRecording(): void;
37}) {
38 const navigate = useNavigate();
39 const environment = useEnvironment(props.environmentId);
40 const canManage = useEnvironmentScope(props.environmentId, AuthSettingsWriteScope);
41 const selectedMicrophone = useClientSettings((settings) => settings.voiceMicrophone);
42 const [microphones, setMicrophones] = useState<BrowserMicrophone[]>([]);
43 const [loadingMicrophones, setLoadingMicrophones] = useState(false);
44 const [microphoneError, setMicrophoneError] = useState<string | null>(null);
45 const refreshMicrophones = useStableCallback(async () => {
46 if (!navigator.mediaDevices?.enumerateDevices) return;
47 setLoadingMicrophones(true);
48 try {
49 setMicrophones(await listBrowserMicrophones());
50 setMicrophoneError(null);
51 } catch {
52 setMicrophoneError("Could not list microphones. You can still use the system default.");
53 }
54 setLoadingMicrophones(false);
55 });
56 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to native microphone changes while the device setup step is visible
57 useEffect(() => {
58 if (!props.open || props.step !== 1) return;
59 queueMicrotask(() => void refreshMicrophones());
60 const mediaDevices = navigator.mediaDevices;
61 mediaDevices?.addEventListener?.("devicechange", refreshMicrophones);
62 return () => mediaDevices?.removeEventListener?.("devicechange", refreshMicrophones);
63 }, [props.open, props.step, refreshMicrophones]);
64 const selectedIsUnavailable = Boolean(
65 selectedMicrophone && !microphones.some((device) => device.deviceId === selectedMicrophone),
66 );
67 const selectedMicrophoneLabel = selectedMicrophone
68 ? (microphones.find((device) => device.deviceId === selectedMicrophone)?.label ??
69 "Selected microphone (Unavailable)")
70 : "System default";
71 const status = props.status?.supported ? props.status : null;
72 const model = props.model;
73 const progress =
74 model?.downloaded === undefined ? null : Math.round((model.downloaded / model.size) * 100);
75 const openSettings = (hash: string) => {
76 props.onOpenChange(false);
77 void navigate({ to: "/settings/voice", hash });
78 };
79
80 return (
81 <Dialog open={props.open} onOpenChange={props.onOpenChange}>
82 <WizardPopup>
83 <WizardHeader
84 title="Set up voice input"
85 description={`Transcribe speech on ${environment?.label ?? "your transcription environment"} and use voice input across environments.`}
86 >
87 <WizardSteps steps={["Model", "Ready to dictate"]} currentStep={props.step} />
88 </WizardHeader>
89 <WizardPanel>
90 {props.step === 0 ? (
91 <section className="space-y-3 text-sm">
92 {model ? (
93 <div className="rounded-lg border border-border/70 bg-card/60 p-4">
94 <div className="flex items-center justify-between gap-2">
95 <h3 className="font-medium">{model.name}</h3>
96 {model?.recommended && props.language ? (
97 <span className="text-xs font-medium text-primary">
98 Recommended for {languageLabel(props.language)}
99 </span>
100 ) : null}
101 </div>
102 <p className="mt-2 text-muted-foreground">
103 Download the {Math.round(model.size / 1024 / 1024)} MB model to{" "}
104 {environment?.label ?? "your transcription environment"}. Microphone audio is
105 sent there for transcription, as chosen in Voice settings.
106 </p>
107 <p className="mt-2 text-muted-foreground">
108 Silero (1.2 MB), used for silence filtering and pause detection, downloads
109 alongside the speech model. An installed copy is reused.
110 </p>
111 {props.downloading ? (
112 <div role="status" className="mt-4 space-y-1 text-muted-foreground">
113 <div
114 role="progressbar"
115 aria-label="Speech model download progress"
116 aria-valuemin={0}
117 aria-valuemax={100}
118 aria-valuenow={progress ?? undefined}
119 className="h-1 overflow-hidden rounded-full bg-muted"
120 >
121 <div
122 className="h-full bg-primary transition-[width] duration-200"
123 style={{ width: `${progress ?? 0}%` }}
124 />
125 </div>
126 <p className="text-xs">
127 {model?.state === "verifying"
128 ? "Verifying download…"
129 : progress === null
130 ? "Starting download…"
131 : `${progress}% downloaded`}
132 </p>
133 </div>
134 ) : null}
135 </div>
136 ) : !props.error ? (
137 <p role="status" className="text-muted-foreground">
138 Loading transcription models…
139 </p>
140 ) : null}
141 {props.error ? (
142 <p role="alert" className="text-destructive">
143 {props.error}
144 </p>
145 ) : null}
146 </section>
147 ) : (
148 <section className="space-y-4 text-sm">
149 <div className="space-y-2">
150 <label className="font-medium" htmlFor="voice-setup-microphone">
151 Microphone
152 </label>
153 <div className="flex items-center gap-2">
154 <Select
155 value={selectedMicrophone ? `device:${selectedMicrophone}` : "system-default"}
156 disabled={loadingMicrophones}
157 onValueChange={(value) => {
158 if (value)
159 void updateClientSettings({
160 voiceMicrophone:
161 value === "system-default" ? "" : value.slice("device:".length),
162 });
163 }}
164 >
165 <SelectTrigger
166 id="voice-setup-microphone"
167 size="sm"
168 aria-label="Microphone"
169 className="min-w-0 flex-1"
170 >
171 <SelectValue>{selectedMicrophoneLabel}</SelectValue>
172 </SelectTrigger>
173 <SelectPopup align="end" alignItemWithTrigger={false}>
174 <SelectItem value="system-default">System default</SelectItem>
175 {selectedIsUnavailable ? (
176 <SelectItem value={`device:${selectedMicrophone}`}>
177 Selected microphone (Unavailable)
178 </SelectItem>
179 ) : null}
180 {microphones.map((device) => (
181 <SelectItem key={device.deviceId} value={`device:${device.deviceId}`}>
182 {device.label}
183 </SelectItem>
184 ))}
185 </SelectPopup>
186 </Select>
187 <Button
188 type="button"
189 variant="ghost"
190 size="icon-sm"
191 disabled={loadingMicrophones}
192 aria-label="Refresh microphones"
193 onClick={() => void refreshMicrophones()}
194 >
195 <RefreshCwIcon className="size-3.5" />
196 </Button>
197 </div>
198 {selectedIsUnavailable ? (
199 <p className="text-xs text-destructive">
200 The selected microphone is unavailable. Choose another or use the system
201 default.
202 </p>
203 ) : null}
204 {microphoneError ? (
205 <p role="alert" className="text-xs text-muted-foreground">
206 {microphoneError}
207 </p>
208 ) : null}
209 </div>
210 <p className="text-muted-foreground">
211 Speak and transcribe in multiple languages or translate into English, and get names
212 and technical terms right with the dictionary in Voice settings.
213 </p>
214 </section>
215 )}
216 </WizardPanel>
217 <WizardFooter>
218 {props.step === 0 ? (
219 <>
220 <Button variant="outline" onClick={() => openSettings("speech-models")}>
221 {model ? "Choose another model or language" : "Choose a model or language"}
222 </Button>
223 {props.onRetryCatalog ? (
224 <Button onClick={props.onRetryCatalog}>Retry loading models</Button>
225 ) : null}
226 {props.downloading ? (
227 <Button variant="outline" disabled={!canManage} onClick={props.onCancelDownload}>
228 Cancel download
229 </Button>
230 ) : null}
231 {model ? (
232 <Button
233 disabled={!canManage || props.downloading || !status}
234 onClick={props.onDownload}
235 >
236 {props.downloading
237 ? "Downloading…"
238 : props.error
239 ? "Try again"
240 : canManage
241 ? "Download model"
242 : "Ask an environment admin to download"}
243 </Button>
244 ) : null}
245 </>
246 ) : (
247 <>
248 <Button variant="outline" onClick={() => openSettings("")}>
249 Customize in Voice settings
250 </Button>
251 <Button onClick={props.onStartRecording}>Start dictating</Button>
252 </>
253 )}
254 </WizardFooter>
255 </WizardPopup>
256 </Dialog>
257 );
258}