Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

VoiceInputSetup.tsx

243 lines10.6 KB

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