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

VoiceSettingsPanel.tsx

1,371 lines53.3 KB

1import {
2 cancelEnvironmentSpeechModelDownload,
3 downloadEnvironmentSpeechModel,
4 getEnvironmentSpeechModels,
5 getEnvironmentSpeechStatus,
6 removeEnvironmentSpeechModel,
7 selectEnvironmentSpeechModel,
8 updateEnvironmentSpeechAcceleration,
9 updateEnvironmentSpeechModelUnloadTimeout,
10} from "@t3tools/client-runtime/voice-input";
11import type { PreparedConnection } from "@t3tools/client-runtime/connection";
12import {
13 AuthSettingsWriteScope,
14 DEFAULT_SPEECH_POST_PROCESSING_PROMPT,
15 type EnvironmentId,
16 type EnvironmentSpeechModel,
17 type EnvironmentSpeechStatus,
18 type ProjectId,
19 type SpeechAcceleration,
20 type SpeechCustomWords,
21 type SpeechModelUnloadTimeout,
22 type VoiceShortcutMode,
23} from "@t3tools/contracts";
24import { createModelSelection } from "@t3tools/shared/model";
25import { resolveSpeechPostProcessingModelSelection } from "@t3tools/shared/serverSettings";
26import {
27 AudioLinesIcon,
28 CheckIcon,
29 DownloadIcon,
30 LanguagesIcon,
31 MicIcon,
32 RefreshCwIcon,
33 StarIcon,
34 Trash2Icon,
35 XIcon,
36} from "lucide-react";
37import { useEffect, useRef, useState, type ReactNode } from "react";
38​
39import { useStableCallback } from "~/hooks/useStableCallback";
40import { listBrowserMicrophones, type BrowserMicrophone } from "../../speech/browserMicrophones";
41import {
42 chooseAudioDestination,
43 chooseTranscriptCleanup,
44 useCleanupGrant,
45} from "../../speech/voiceConsent";
46import { updateClientSettings, useClientSettings } from "../../hooks/useSettings";
47import { runtime } from "../../lib/runtime";
48import {
49 getCustomModelOptionsByInstance,
50 resolveAppModelSelectionState,
51} from "../../modelSelection";
52import { providerInstanceEntriesFor } from "../../providerInstances";
53import { useEnvironmentProviders, useEnvironments } from "../../state/environments";
54import { useEnvironmentScope } from "../../state/session";
55import { EMPTY_SERVER_PROVIDERS } from "../../state/server";
56import {
57 useEnvironmentSpeechInput,
58 useVoiceTranscriptionDestination,
59} from "../../speech/useEnvironmentSpeechInput";
60import { ComposerSpeechRecordingPill } from "../chat/ComposerSpeechButton";
61import { ProviderModelPicker } from "../chat/ProviderModelPicker";
62import { TraitsPicker } from "../chat/TraitsPicker";
63import { VoiceInputSetup } from "../chat/VoiceInputSetup";
64import { Badge } from "../ui/badge";
65import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
66import { Button } from "../ui/button";
67import { Input } from "../ui/input";
68import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
69import { Switch } from "../ui/switch";
70import { Textarea } from "../ui/textarea";
71import { toastManager } from "../ui/toast";
72import { MicrophoneTest } from "./MicrophoneTest";
73import { LanguageRow, ModelBenchmarks, orderSpeechLanguages } from "./SpeechModelComparison";
74import { languageLabel, SpeechLanguageSelect } from "./SpeechLanguageSelect";
75import { AdvancedSettings } from "./AdvancedSettings";
76import {
77 SETTINGS_PICKER_TRIGGER_CLASSNAME,
78 SettingResetButton,
79 SettingsPageContainer,
80 SettingsRow,
81 SettingsSearchTarget,
82 SettingsSection,
83} from "./settingsLayout";
84import { searchableSetting } from "./settingsSearch";
85import { useOptionalSettingsScope, useSettingsScope } from "./SettingsScopeContext";
86import { useScopedModelDisabledReason } from "./useScopedModelAvailability";
87import { useScopedSettings, useUpdateScopedSettings } from "./useScopedSettings";
88​
89const OFF = "off";
90const SYSTEM_DEFAULT = "system-default";
91const formatSize = (bytes: number) => `${Math.round(bytes / 1024 / 1024)} MB`;
92const SHORTCUT_MODE_LABELS: Record<VoiceShortcutMode, string> = {
93 auto: "Auto: press to toggle, hold to record",
94 hold: "Hold: record while held",
95 toggle: "Toggle: press to start, press again to stop",
96};
97const UNLOAD_LABELS: Record<SpeechModelUnloadTimeout, string> = {
98 never: "Never",
99 immediately: "Immediately",
100 min_2: "After 2 minutes",
101 min_5: "After 5 minutes",
102 min_10: "After 10 minutes",
103 min_15: "After 15 minutes",
104 hour_1: "After 1 hour",
105};
106const normalizeTerm = (value: string) => value.replace(/\s+/g, " ").trim().normalize("NFC");
107const spellingsOf = (words: SpeechCustomWords) =>
108 new Set(
109 words.flatMap(({ term, aliases }) =>
110 [term, ...aliases].map((spelling) => spelling.toLocaleLowerCase()),
111 ),
112 );
113const modelSortOrder = (model: EnvironmentSpeechModel) => {
114 if (model.active) return 0;
115 if (model.state === "installed") return 1;
116 if (model.state === "downloading" || model.state === "verifying") return 2;
117 return model.recommended ? 3 : 4;
118};
119​
120type ModelCardProps = {
121 readonly model: EnvironmentSpeechModel;
122 readonly comparisonLanguages: readonly string[];
123 readonly busy: boolean;
124 readonly canCancel: boolean;
125 readonly onDownload: () => void;
126 readonly onSelect: () => void;
127 readonly onCancel: () => void;
128 readonly onDelete: () => void;
129 readonly testControls?: ReactNode;
130 readonly children?: ReactNode;
131};
132​
133function ModelBadge(props: { icon: ReactNode; label: string; tooltip: string }) {
134 return (
135 <Tooltip>
136 <TooltipTrigger render={<Badge variant="outline" />}>
137 {props.icon}
138 {props.label}
139 </TooltipTrigger>
140 <TooltipPopup side="top">{props.tooltip}</TooltipPopup>
141 </Tooltip>
142 );
144​
145function ModelCard(props: ModelCardProps) {
146 const { model } = props;
147 const downloading = model.state === "downloading" || model.state === "verifying";
148 const progress = model.downloaded === undefined ? 0 : (model.downloaded / model.size) * 100;
149 return (
150 <div className="flex flex-wrap items-start gap-3 px-3 py-2.5 sm:px-4">
151 <div className="min-w-0 flex-1">
152 <div className="flex flex-wrap items-center gap-1.5">
153 <span className="text-sm font-medium leading-5">{model.name}</span>
154 {model.recommended ? (
155 <ModelBadge
156 icon={<StarIcon className="mr-1 size-3" />}
157 label="Recommended"
158 tooltip="A good default pick for the languages it covers."
159 />
160 ) : null}
161 {model.supportsStreaming ? (
162 <ModelBadge
163 icon={<AudioLinesIcon className="mr-1 size-3" />}
164 label="Live preview"
165 tooltip="Shows words in your draft as you speak, before the recording finishes."
166 />
167 ) : null}
168 {model.supportsTranslation ? (
169 <ModelBadge
170 icon={<LanguagesIcon className="mr-1 size-3" />}
171 label="Translate"
172 tooltip="Can write English text from speech in another language. Turn on Translate to English to use it."
173 />
174 ) : null}
175 </div>
176 <p className="mt-0.5 text-xs leading-relaxed text-muted-foreground">{model.description}</p>
177 <ModelBenchmarks
178 model={model}
179 languages={props.comparisonLanguages}
180 facts={[
181 ...(model.languages.length > 1
182 ? [`${model.languages.length} languages`]
183 : model.benchmark
184 ? []
185 : [languageLabel(model.languages[0] ?? "")]),
186 formatSize(model.size),
187 ]}
188 />
189 {downloading ? (
190 <div className="mt-2">
191 <div
192 role="progressbar"
193 aria-label={`${model.name} download progress`}
194 aria-valuemin={0}
195 aria-valuemax={100}
196 aria-valuenow={Math.round(progress)}
197 className="h-1 overflow-hidden rounded-full bg-muted"
198 >
199 <div
200 className="h-full bg-primary transition-[width] duration-200"
201 style={{ width: `${progress}%` }}
202 />
203 </div>
204 <p className="mt-1 text-2xs text-muted-foreground">
205 {model.state === "verifying"
206 ? "Verifying download…"
207 : `${Math.round(progress)}% downloaded`}
208 </p>
209 </div>
210 ) : null}
211 </div>
212 <div className="flex max-w-full flex-wrap items-center justify-end gap-1">
213 {props.testControls}
214 {downloading ? (
215 <Button
216 size="icon-sm"
217 variant="ghost"
218 aria-label={`Cancel ${model.name} download`}
219 disabled={!props.canCancel}
220 onClick={props.onCancel}
221 >
222 <XIcon className="size-3.5" />
223 </Button>
224 ) : model.state === "downloadable" ? (
225 <Button size="sm" variant="outline" disabled={props.busy} onClick={props.onDownload}>
226 <DownloadIcon className="mr-1.5 size-3.5" />
227 Download
228 </Button>
229 ) : model.active ? (
230 <Button size="sm" variant="secondary" disabled>
231 <CheckIcon className="mr-1.5 size-3.5" />
232 Selected
233 </Button>
234 ) : (
235 <Button size="sm" variant="outline" disabled={props.busy} onClick={props.onSelect}>
236 Use model
237 </Button>
238 )}
239 {model.state === "installed" ? (
240 <Button
241 size="icon-sm"
242 variant="ghost"
243 disabled={props.busy}
244 aria-label={`Delete ${model.name}`}
245 onClick={props.onDelete}
246 >
247 <Trash2Icon className="size-3.5" />
248 </Button>
249 ) : null}
250 </div>
251 {props.children}
252 </div>
253 );
255​
256function DictionaryEditor(props: {
257 readonly label: string;
258 readonly words: SpeechCustomWords;
259 readonly disabled?: boolean;
260 readonly onChange: (words: SpeechCustomWords) => void;
261}) {
262 const { words, label, disabled = false, onChange } = props;
263 const [termDraft, setTermDraft] = useState("");
264 const [aliasDraft, setAliasDraft] = useState<{ term: string; value: string } | null>(null);
265 const spellings = spellingsOf(words);
266 const seen = new Set(spellings);
267 const newTerms = termDraft
268 .split(/[,\n]/)
269 .map(normalizeTerm)
270 .filter((term) => {
271 const key = term.toLocaleLowerCase();
272 if (!key || seen.has(key)) return false;
273 seen.add(key);
274 return true;
275 });
276 const canAddTerm =
277 !disabled &&
278 newTerms.length > 0 &&
279 newTerms.every((term) => term.length <= 50) &&
280 words.length + newTerms.length <= 100;
281 const addTerm = () => {
282 if (!canAddTerm) return;
283 onChange([...words, ...newTerms.map((term) => ({ term, aliases: [] }))]);
284 setTermDraft("");
285 };
286 const addAlias = () => {
287 if (!aliasDraft) return;
288 const value = normalizeTerm(aliasDraft.value);
289 if (!value || value.length > 50 || spellings.has(value.toLocaleLowerCase())) return;
290 onChange(
291 words.map((entry) =>
292 entry.term === aliasDraft.term && entry.aliases.length < 8
293 ? { term: entry.term, aliases: [...entry.aliases, value] }
294 : entry,
295 ),
296 );
297 setAliasDraft(null);
298 };
299 return (
300 <>
301 <div className="flex items-start gap-1.5">
302 <Textarea
303 value={termDraft}
304 rows={1}
305 maxLength={5_100}
306 disabled={disabled}
307 placeholder="Add words or phrases, separated by commas or line breaks"
308 aria-label={`Add a word or phrase to the ${label}`}
309 onChange={(event) => setTermDraft(event.target.value)}
310 onKeyDown={(event) => {
311 if (event.key !== "Enter" || event.shiftKey) return;
312 event.preventDefault();
313 addTerm();
314 }}
315 />
316 <Button type="button" disabled={!canAddTerm} onClick={addTerm}>
317 Add
318 </Button>
319 </div>
320 {words.length > 0 ? (
321 <ul aria-label={`${label} entries`} className="mt-3 flex flex-wrap gap-1.5">
322 {words.map(({ term, aliases }) => (
323 <li
324 key={term}
325 className="flex items-center gap-1 rounded-md border border-border/60 bg-muted/30 py-0.5 pl-2 pr-0.5 text-xs"
326 >
327 <span className="font-medium">{term}</span>
328 {aliases.length > 0 ? (
329 <span className="text-muted-foreground">← {aliases.join(", ")}</span>
330 ) : null}
331 {aliasDraft?.term === term ? (
332 <Input
333 autoFocus
334 value={aliasDraft.value}
335 maxLength={50}
336 aria-label={`Alias for ${term}`}
337 placeholder="Misspelling"
338 className="w-32"
339 onChange={(event) => setAliasDraft({ term, value: event.target.value })}
340 onBlur={() => setAliasDraft(null)}
341 onKeyDown={(event) => {
342 if (event.key === "Escape") setAliasDraft(null);
343 if (event.key !== "Enter") return;
344 event.preventDefault();
345 addAlias();
346 }}
347 />
348 ) : (
349 <Button
350 type="button"
351 size="xs"
352 variant="ghost-muted"
353 disabled={disabled || aliases.length >= 8}
354 aria-label={`Add an alias for ${term}`}
355 onClick={() => setAliasDraft({ term, value: "" })}
356 >
357 Alias
358 </Button>
359 )}
360 <Button
361 type="button"
362 size="icon-xs"
363 variant="ghost-muted"
364 disabled={disabled}
365 aria-label={`Remove ${term}`}
366 onClick={() => onChange(words.filter((entry) => entry.term !== term))}
367 >
368 <XIcon />
369 </Button>
370 </li>
371 ))}
372 </ul>
373 ) : null}
374 </>
375 );
377​
378/** Vocabulary stored on the environment with the project, read by everyone who dictates there. */
379function ProjectDictionaryRow() {
380 const scope = useOptionalSettingsScope();
381 const words = useScopedSettings((settings) => settings.speechProjectCustomWords);
382 const updateScopedSettings = useUpdateScopedSettings();
383 if (scope === null) return null;
384 const isProjectScope = scope.scope.kind === "project" || scope.scope.kind === "checkout";
385 return (
386 <SettingsRow
387 serverScoped
388 settingKeys={["speechProjectCustomWords"]}
389 {...searchableSetting("speech-project-dictionary")}
390 title={isProjectScope ? "Project dictionary" : "Shared dictionary"}
391 description={
392 isProjectScope
393 ? `Saved with ${scope.scope.label} on its environment. Everyone who dictates in this project gets these spellings, along with their own dictionary. Project spellings win when the two overlap.`
394 : "Saved on the environment and used in every project there, along with each person’s own dictionary. Pick a project above to limit these words to one project."
395 }
396 control={
397 <span className="text-xs text-muted-foreground">
398 {words.length} {words.length === 1 ? "entry" : "entries"}
399 </span>
400 }
401 >
402 <div className="mt-2 pb-3.5">
403 <DictionaryEditor
404 label={isProjectScope ? "project dictionary" : "shared dictionary"}
405 words={words}
406 disabled={scope.connectedEnvironments.length === 0}
407 onChange={(next) => updateScopedSettings({ speechProjectCustomWords: next })}
408 />
409 </div>
410 </SettingsRow>
411 );
413​
414/** Cleanup runs on the draft's environment, so its model is an environment setting there. */
415function CleanupModelRow() {
416 const { environment, connectedEnvironments } = useSettingsScope();
417 const settings = useScopedSettings();
418 const updateSettings = useUpdateScopedSettings();
419 const providersByEnvironment = useEnvironmentProviders();
420 const providers =
421 (environment?.serverConfig
422 ? providersByEnvironment.get(environment.environmentId)
423 : undefined) ?? EMPTY_SERVER_PROVIDERS;
424 const textGenerationProviders = providers.filter(
425 (provider) => provider.supportsTextGeneration !== false,
426 );
427 const instanceEntries = providerInstanceEntriesFor(textGenerationProviders, settings, null);
428 const hasProvider = instanceEntries.some((entry) => entry.enabled && entry.isAvailable);
429 const dedicated = settings.speechPostProcessingModelSelection !== null;
430 const selection = resolveAppModelSelectionState(
431 {
432 ...settings,
433 textGenerationModelSelection: resolveSpeechPostProcessingModelSelection(
434 settings,
435 textGenerationProviders,
436 ),
437 },
438 textGenerationProviders,
439 );
440 const modelOptionsByInstance = getCustomModelOptionsByInstance(
441 settings,
442 textGenerationProviders,
443 selection.instanceId,
444 selection.model,
445 );
446 const instanceEntry = instanceEntries.find((entry) => entry.instanceId === selection.instanceId);
447 const modelDisabledReason = useScopedModelDisabledReason(settings, instanceEntries);
448 const setModel = (next: ReturnType<typeof createModelSelection>) => {
449 const reason = modelDisabledReason(next.instanceId, next.model);
450 if (reason) {
451 toastManager.add({ type: "error", title: "Cleanup model not saved", description: reason });
452 return;
453 }
454 updateSettings({ speechPostProcessingModelSelection: next });
455 };
456 return (
457 <SettingsRow
458 serverScoped
459 settingKeys={["speechPostProcessingModelSelection"]}
460 {...searchableSetting("speech-post-processing-model")}
461 title="Cleanup model"
462 description={
463 dedicated
464 ? `Drafts on ${environment?.label ?? "this environment"} use this model for cleanup instead of the environment’s text generation model.`
465 : `Cleanup currently uses the text generation model on ${environment?.label ?? "this environment"}. Pick another model if you want a cheaper or faster one.`
466 }
467 resetAction={
468 dedicated ? (
469 <SettingResetButton
470 label="cleanup model"
471 onClick={() => updateSettings({ speechPostProcessingModelSelection: null })}
472 />
473 ) : null
474 }
475 control={
476 connectedEnvironments.length === 0 ? (
477 <span className="text-sm text-muted-foreground">Connect an environment first.</span>
478 ) : !hasProvider || !instanceEntry ? (
479 <span className="text-sm text-muted-foreground">No providers available.</span>
480 ) : (
481 <div className="flex min-w-0 flex-wrap items-center justify-end gap-1.5">
482 <ProviderModelPicker
483 environmentId={environment?.environmentId ?? null}
484 activeInstanceId={selection.instanceId}
485 model={selection.model}
486 lockedProvider={null}
487 instanceEntries={instanceEntries}
488 modelOptionsByInstance={modelOptionsByInstance}
489 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
490 getModelDisabledReason={modelDisabledReason}
491 onInstanceModelChange={(instanceId, model) =>
492 setModel(createModelSelection(instanceId, model))
493 }
494 />
495 <TraitsPicker
496 provider={instanceEntry.driverKind}
497 models={instanceEntry.models}
498 model={selection.model}
499 modelOptions={selection.options ?? []}
500 allowPromptInjectedEffort={false}
501 planModeEnabled={settings.planModeEnabled}
502 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
503 onModelOptionsChange={(options) =>
504 setModel(createModelSelection(selection.instanceId, selection.model, options))
505 }
506 />
507 </div>
508 )
509 }
510 />
511 );
513​
514function useVoiceModels(prepared: PreparedConnection | null) {
515 const canManage = useEnvironmentScope(prepared?.environmentId ?? null, AuthSettingsWriteScope);
516 const [models, setModels] = useState<readonly EnvironmentSpeechModel[]>([]);
517 const [status, setStatus] = useState<EnvironmentSpeechStatus | null>(null);
518 const [busy, setBusy] = useState(false);
519 const [requestedDownload, setRequestedDownload] = useState<string | null>(null);
520 const [actionConnection, setActionConnection] = useState(prepared);
521 if (actionConnection !== prepared) {
522 setActionConnection(prepared);
523 setBusy(false);
524 setRequestedDownload(null);
525 setModels([]);
526 setStatus(null);
527 }
528 const epoch = useRef(0);
529 const refreshRevision = useRef(0);
530 const refresh = useStableCallback(
531 async (connection: PreparedConnection, mode: "foreground" | "progress") => {
532 const current = epoch.current;
533 const revision = ++refreshRevision.current;
534 try {
535 const [nextStatus, nextModels] = await Promise.all([
536 runtime.runPromise(getEnvironmentSpeechStatus(connection)),
537 runtime.runPromise(getEnvironmentSpeechModels(connection, mode === "foreground")),
538 ]);
539 if (current !== epoch.current || revision !== refreshRevision.current) return;
540 setStatus(nextStatus);
541 setModels((previous) => {
542 if (mode === "foreground") return nextModels.models;
543 const benchmarks = new Map(previous.map((model) => [model.id, model.benchmark]));
544 return nextModels.models.map((model) => {
545 const benchmark = benchmarks.get(model.id);
546 return benchmark ? { ...model, benchmark } : model;
547 });
548 });
549 } catch (error) {
550 if (mode === "progress") return;
551 if (current !== epoch.current || revision !== refreshRevision.current) return;
552 toastManager.add({
553 type: "error",
554 title: "Could not load transcription models",
555 description: error instanceof Error ? error.message : String(error),
556 });
557 }
558 },
559 );
560 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- loads the environment's model catalog when its connection becomes available
561 useEffect(() => {
562 epoch.current += 1;
563 if (prepared) void refresh(prepared, "foreground");
564 return () => {
565 epoch.current += 1;
566 };
567 }, [prepared, refresh]);
568 const downloading =
569 requestedDownload !== null ||
570 models.some((model) => model.state === "downloading" || model.state === "verifying");
571 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- polls progress while a local request or the environment reports an active download
572 useEffect(() => {
573 if (!prepared || !downloading) return;
574 let cancelled = false;
575 let timer: number | undefined;
576 const poll = async () => {
577 await refresh(prepared, "progress");
578 if (!cancelled) timer = window.setTimeout(() => void poll(), 1_000);
579 };
580 void poll();
581 return () => {
582 cancelled = true;
583 window.clearTimeout(timer);
584 };
585 }, [downloading, prepared, refresh]);
586​
587 const run = async (label: string, work: () => Promise<unknown>, downloadId?: string) => {
588 if (!prepared || !canManage) return;
589 const current = epoch.current;
590 if (downloadId) setRequestedDownload(downloadId);
591 else setBusy(true);
592 try {
593 await work();
594 } catch (error) {
595 if (current === epoch.current)
596 toastManager.add({
597 type: "error",
598 title: label,
599 description: error instanceof Error ? error.message : String(error),
600 });
601 }
602 if (current === epoch.current) {
603 if (downloadId) setRequestedDownload(null);
604 else setBusy(false);
605 await refresh(prepared, "foreground");
606 }
607 };
608 return {
609 models,
610 status,
611 run,
612 controlsDisabled: busy || downloading || !canManage,
613 canCancel: canManage && !busy,
614 requestedDownload,
615 };
617​
618type VoiceModels = ReturnType<typeof useVoiceModels>;
619​
620function AdvancedSpeechSettings({
621 prepared,
622 catalog,
623}: {
624 prepared: PreparedConnection;
625 catalog: VoiceModels;
626}) {
627 const { run, controlsDisabled, status } = catalog;
628 if (!status?.supported) return null;
629 const supported = status;
630 return (
631 <AdvancedSettings targetIds={[searchableSetting("speech-hardware").id]}>
632 <SettingsRow
633 {...searchableSetting("speech-hardware")}
634 title="Hardware"
635 description="Auto uses the environment’s GPU when it has one."
636 control={
637 <Select
638 value={supported.acceleration}
639 disabled={controlsDisabled}
640 onValueChange={(value) => {
641 if (value)
642 void run("Could not change transcription hardware", () =>
643 runtime.runPromise(
644 updateEnvironmentSpeechAcceleration(prepared, value as SpeechAcceleration),
645 ),
646 );
647 }}
648 >
649 <SelectTrigger size="sm" aria-label="Transcription hardware" className="max-w-72">
650 <SelectValue>
651 {supported.acceleration === "auto"
652 ? "Auto"
653 : supported.acceleration === "cpu"
654 ? "CPU"
655 : (supported.gpuDevices.find(
656 (device) => `gpu:${device.id}` === supported.acceleration,
657 )?.name ?? "Selected GPU")}
658 </SelectValue>
659 </SelectTrigger>
660 <SelectPopup align="end" alignItemWithTrigger={false}>
661 <SelectItem value="auto">Auto</SelectItem>
662 <SelectItem value="cpu">CPU</SelectItem>
663 {supported.gpuDevices.map((device) => (
664 <SelectItem key={device.id} value={`gpu:${device.id}`}>
665 {device.name}
666 </SelectItem>
667 ))}
668 </SelectPopup>
669 </Select>
670 }
671 />
672 <SettingsRow
673 title="Unload model"
674 description="Release the model’s memory on the environment after it sits idle."
675 control={
676 <Select
677 value={supported.modelUnloadTimeout}
678 disabled={controlsDisabled}
679 onValueChange={(value) => {
680 if (value)
681 void run("Could not change when the model unloads", () =>
682 runtime.runPromise(
683 updateEnvironmentSpeechModelUnloadTimeout(
684 prepared,
685 value as SpeechModelUnloadTimeout,
686 ),
687 ),
688 );
689 }}
690 >
691 <SelectTrigger size="sm" aria-label="Unload model" className="max-w-72">
692 <SelectValue>{UNLOAD_LABELS[supported.modelUnloadTimeout]}</SelectValue>
693 </SelectTrigger>
694 <SelectPopup align="end" alignItemWithTrigger={false}>
695 {(Object.keys(UNLOAD_LABELS) as SpeechModelUnloadTimeout[]).map((timeout) => (
696 <SelectItem key={timeout} value={timeout}>
697 {UNLOAD_LABELS[timeout]}
698 </SelectItem>
699 ))}
700 </SelectPopup>
701 </Select>
702 }
703 />
704 </AdvancedSettings>
705 );
707​
708function SpeechModelBrowser(props: {
709 prepared: PreparedConnection;
710 catalog: VoiceModels;
711 testEnvironmentId: EnvironmentId;
712 projectId: ProjectId | null;
713 projectName: string | null;
714}) {
715 const {
716 prepared,
717 catalog: { status, models, run, controlsDisabled, canCancel, requestedDownload },
718 } = props;
719 const [search, setSearch] = useState("");
720 const [languageSearch, setLanguageSearch] = useState("");
721 const [selection, setSelection] = useState<string[] | null>(null);
722 const preferred = navigator.languages.map((language) => language.toLowerCase().split("-")[0]!);
723 const supportedLanguages = [...new Set(models.flatMap((model) => model.languages))];
724 const defaultLanguage = preferred.find((code) => supportedLanguages.includes(code));
725 const selectedLanguages = selection ?? (defaultLanguage ? [defaultLanguage] : []);
726 const languages = orderSpeechLanguages(supportedLanguages, preferred);
727 const needle = languageSearch.trim().toLocaleLowerCase();
728 const visibleLanguages = languages.filter(
729 (code) =>
730 !needle || code.includes(needle) || languageLabel(code).toLocaleLowerCase().includes(needle),
731 );
732 const query = search.trim().toLocaleLowerCase();
733 const sortedModels = models
734 .filter(
735 (model) =>
736 selectedLanguages.every((language) => model.languages.includes(language)) &&
737 (!query || (model.name + " " + model.description).toLocaleLowerCase().includes(query)),
738 )
739 .toSorted((left, right) => modelSortOrder(left) - modelSortOrder(right));
740 const activeModel = models.find((model) => model.active);
741 const renderedModels =
742 activeModel && !sortedModels.includes(activeModel)
743 ? [activeModel, ...sortedModels]
744 : sortedModels;
745​
746 return (
747 <SettingsSearchTarget
748 {...searchableSetting("speech-models")}
749 className="@container/voice-models"
750 >
751 {status && !status.supported ? (
752 <p className="px-4 py-2 text-sm text-muted-foreground">
753 This environment can’t transcribe audio: {status.reason}.
754 </p>
755 ) : null}
756 {status?.supported ? (
757 <>
758 <p className="border-b border-border/60 px-3 py-2 text-xs text-muted-foreground sm:px-4">
759 Pick languages to see models that support all of them. Accuracy is word or character
760 error rate: lower is better. Speed is the time to transcribe 30 seconds of audio on
761 Handy’s benchmark GPU.
762 </p>
763 <div className="@min-[32rem]/voice-models:grid @min-[32rem]/voice-models:grid-cols-[11rem_minmax(0,1fr)]">
764 <div className="flex min-h-0 flex-col border-b border-border/60 bg-muted/10 @min-[32rem]/voice-models:border-r @min-[32rem]/voice-models:border-b-0">
765 <div className="space-y-2 p-3">
766 <p className="text-sm font-medium">Languages</p>
767 <Input
768 size="compact"
769 aria-label="Search languages"
770 placeholder="Search languages"
771 value={languageSearch}
772 onChange={(e) => setLanguageSearch(e.target.value)}
773 />
774 </div>
775 <div
776 role="group"
777 aria-label="Browse models by language"
778 className="flex gap-1 overflow-x-auto px-2 pb-2 @min-[32rem]/voice-models:h-72 @min-[32rem]/voice-models:flex-col @min-[32rem]/voice-models:overflow-y-auto"
779 >
780 <LanguageRow
781 label="All languages"
782 selected={selectedLanguages.length === 0}
783 onClick={() => setSelection([])}
784 />
785 {visibleLanguages.map((code) => (
786 <LanguageRow
787 key={code}
788 label={languageLabel(code)}
789 selected={selectedLanguages.includes(code)}
790 onClick={() =>
791 setSelection(
792 selectedLanguages.includes(code)
793 ? selectedLanguages.filter((language) => language !== code)
794 : [...selectedLanguages, code],
795 )
796 }
797 />
798 ))}
799 {visibleLanguages.length === 0 && (
800 <p className="px-2 py-1 text-xs text-muted-foreground">No languages match.</p>
801 )}
802 </div>
803 </div>
804 <div className="flex min-w-0 flex-col">
805 <div className="space-y-2 p-3">
806 <p className="text-sm font-medium">
807 {selectedLanguages.length
808 ? "Models for " + selectedLanguages.map(languageLabel).join(", ")
809 : "All models"}
810 </p>
811 <Input
812 size="compact"
813 aria-label="Search transcription models"
814 placeholder="Search models"
815 value={search}
816 onChange={(e) => setSearch(e.target.value)}
817 />
818 </div>
819 <div
820 className="h-72 overflow-y-auto divide-y divide-border/60"
821 role="region"
822 aria-label="Transcription models"
823 tabIndex={0}
824 >
825 {sortedModels.length === 0 && (
826 <p className="px-4 py-2 text-sm text-muted-foreground">No models match.</p>
827 )}
828 {renderedModels.map((model) => {
829 const card: ModelCardProps = {
830 model:
831 model.id === requestedDownload && model.state === "downloadable"
832 ? { ...model, state: "downloading" }
833 : model,
834 busy: controlsDisabled,
835 canCancel,
836 comparisonLanguages: selectedLanguages,
837 onDownload: () =>
838 void run(
839 "Could not download the model",
840 () =>
841 runtime.runPromise(downloadEnvironmentSpeechModel(prepared, model.id)),
842 model.id,
843 ),
844 onSelect: () =>
845 void run("Could not select the model", () =>
846 runtime.runPromise(selectEnvironmentSpeechModel(prepared, model.id)),
847 ),
848 onCancel: () =>
849 void run("Could not cancel the download", () =>
850 runtime.runPromise(
851 cancelEnvironmentSpeechModelDownload(prepared, model.id),
852 ),
853 ),
854 onDelete: () =>
855 void run("Could not delete the model", () =>
856 runtime.runPromise(removeEnvironmentSpeechModel(prepared, model.id)),
857 ),
858 };
859 return model.active ? (
860 <TranscriptionTest
861 key={model.id}
862 card={card}
863 hidden={!sortedModels.includes(model)}
864 environmentId={props.testEnvironmentId}
865 projectId={props.projectId}
866 projectName={props.projectName}
867 />
868 ) : (
869 <ModelCard key={model.id} {...card} />
870 );
871 })}
872 </div>
873 </div>
874 </div>
875 </>
876 ) : null}
877 </SettingsSearchTarget>
878 );
880​
881function TranscriptionTest(props: {
882 readonly card: ModelCardProps;
883 readonly hidden: boolean;
884 readonly environmentId: EnvironmentId;
885 readonly projectId: ProjectId | null;
886 readonly projectName: string | null;
887}) {
888 const [transcript, setTranscript] = useState<string | null>(null);
889 const draft = transcript ?? "";
890 const [showTranscript, setShowTranscript] = useState(false);
891 const draftRef = useRef(draft);
892 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the committed draft to the asynchronous transcription controller
893 useEffect(() => {
894 draftRef.current = draft;
895 }, [draft]);
896 const speech = useEnvironmentSpeechInput({
897 environmentId: props.environmentId,
898 projectId: props.projectId,
899 projectName: props.projectName,
900 ownerKey: JSON.stringify([props.environmentId, props.projectId]),
901 draftText: draft,
902 cleanup: false,
903 readDraft: () => ({
904 text: draftRef.current,
905 selection: { start: draftRef.current.length, end: draftRef.current.length },
906 }),
907 commitDraft: (text) => setTranscript(text),
908 });
909 return (
910 <SettingsSearchTarget {...searchableSetting("transcription-test")} hidden={props.hidden}>
911 <ModelCard
912 {...props.card}
913 testControls={
914 <div className="flex min-w-0 max-w-full items-center gap-1">
915 <ComposerSpeechRecordingPill
916 state={speech.state}
917 progress={null}
918 level={speech.level}
919 onStart={() => void speech.start()}
920 onStop={() => void speech.stop()}
921 onCancel={() => speech.cancel()}
922 onSkipPostProcessing={() => speech.skipPostProcessing()}
923 />
924 {speech.available ? (
925 speech.state.phase === "idle" ? (
926 <Button
927 size="sm"
928 variant="outline"
929 onClick={() => {
930 setShowTranscript(true);
931 void speech.start();
932 }}
933 >
934 <MicIcon />
935 Test model
936 </Button>
937 ) : null
938 ) : (
939 <span className="text-xs text-muted-foreground">
940 {speech.status?.supported === false
941 ? speech.status.reason
942 : "Waiting for the environment to connect"}
943 </span>
944 )}
945 </div>
946 }
947 >
948 {showTranscript ? (
949 <div className="w-full">
950 <div className="flex items-start gap-2">
951 <p className="min-w-0 flex-1 text-xs leading-relaxed text-muted-foreground">
952 Say a sentence in the language above. Cleanup is skipped, so you see exactly what
953 the model heard. The transcript stays on this page.
954 </p>
955 <Button
956 size="icon-sm"
957 variant="ghost"
958 aria-label="Close model test"
959 onClick={() => {
960 speech.cancel();
961 setShowTranscript(false);
962 }}
963 >
964 <XIcon />
965 </Button>
966 </div>
967 {speech.preview || transcript !== null ? (
968 <p
969 role="status"
970 aria-label="Test transcript"
971 className="mt-2 select-text whitespace-pre-wrap break-words text-sm leading-relaxed"
972 >
973 {speech.preview ? (
974 <>
975 {speech.preview.committed}
976 <span className="text-muted-foreground">{speech.preview.tentative}</span>
977 </>
978 ) : (
979 transcript || "No speech recognized. Try again."
980 )}
981 </p>
982 ) : null}
983 </div>
984 ) : null}
985 </ModelCard>
986 <VoiceInputSetup
987 environmentId={speech.transcriptionEnvironmentId}
988 open={speech.setup.open}
989 step={speech.setup.step}
990 status={speech.status}
991 model={speech.setup.model}
992 downloading={speech.setup.downloading}
993 error={speech.setup.error}
994 onOpenChange={speech.setup.setOpen}
995 onDownload={() => void speech.setup.download()}
996 onCancelDownload={() => void speech.setup.cancelDownload()}
997 onStartRecording={() => void speech.setup.startRecording()}
998 />
999 </SettingsSearchTarget>
1000 );
1002​
1003export function VoiceSettingsPanel() {
1004 const cleanupEnabled = useCleanupGrant() !== null;
1005 const settings = useClientSettings();
1006 const settingsScope = useOptionalSettingsScope();
1007 const destination = useVoiceTranscriptionDestination();
1008 const { environments } = useEnvironments();
1009 const [microphones, setMicrophones] = useState<BrowserMicrophone[]>([]);
1010 const prepared = destination.prepared;
1011 const catalog = useVoiceModels(prepared);
1012​
1013 const refreshMicrophones = useStableCallback(async () => {
1014 if (!navigator.mediaDevices?.enumerateDevices) return;
1015 try {
1016 setMicrophones(await listBrowserMicrophones());
1017 } catch {
1018 setMicrophones([]);
1020 });
1021 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to microphone device changes while settings are open
1022 useEffect(() => {
1023 queueMicrotask(() => void refreshMicrophones());
1024 const mediaDevices = navigator.mediaDevices;
1025 if (!mediaDevices?.addEventListener) return;
1026 const onChange = () => void refreshMicrophones();
1027 mediaDevices.addEventListener("devicechange", onChange);
1028 return () => mediaDevices.removeEventListener("devicechange", onChange);
1029 }, [refreshMicrophones]);
1030 const modelStatus = catalog.status;
1031 const target = settingsScope?.target;
1032 const members = settingsScope?.scope.members;
1033 const project =
1034 members?.find(
1035 (member) => member.environmentId === target?.environmentId && member.id === target.projectId,
1036 ) ?? members?.[0];
1037​
1038 const selectedMicrophone = settings.voiceMicrophone;
1039 const selectedMicrophoneLabel = selectedMicrophone
1040 ? (microphones.find((device) => device.deviceId === selectedMicrophone)?.label ??
1041 "Selected microphone (unavailable)")
1042 : "System default";
1043 const destinationValue = destination.environmentId ?? OFF;
1044 const chosenEnvironment = environments.find(
1045 (environment) => environment.environmentId === destination.environmentId,
1046 );
1047 const chosenUnsupported =
1048 chosenEnvironment?.serverConfig != null &&
1049 chosenEnvironment.serverConfig.environment.capabilities.voiceTranscription !== true;
1050 const model = prepared && modelStatus?.supported ? modelStatus : null;
1051​
1052 return (
1053 <SettingsPageContainer
1054 searchTargetFallbacks={{
1055 "speech-models": prepared ? undefined : "voice-transcription-destination",
1056 "speech-hardware": prepared && model ? undefined : "voice-transcription-destination",
1057 "transcription-test": !prepared
1058 ? "voice-transcription-destination"
1059 : !model || model.state === "missing-model"
1060 ? "speech-models"
1061 : undefined,
1062 "speech-post-processing-model":
1063 cleanupEnabled && settingsScope ? undefined : "speech-post-processing",
1064 "speech-correction-word": cleanupEnabled ? undefined : "speech-post-processing",
1065 }}
1067 <SettingsSection id="voice-input" title="Input">
1068 <SettingsRow
1069 {...searchableSetting("voice-microphone")}
1070 title="Microphone"
1071 description="System default follows your operating system. Record a ten-second test and play it back here. Test audio stays on this device and is never transcribed."
1072 control={
1073 <div className="flex min-w-0 flex-wrap items-center justify-end gap-1.5">
1074 <SettingsSearchTarget {...searchableSetting("microphone-test")}>
1075 <MicrophoneTest key={selectedMicrophone} microphoneId={selectedMicrophone} />
1076 </SettingsSearchTarget>
1077 <div className="flex min-w-0 items-center gap-1.5">
1078 <Select
1079 value={selectedMicrophone ? `device:${selectedMicrophone}` : SYSTEM_DEFAULT}
1080 onValueChange={(value) => {
1081 if (value)
1082 void updateClientSettings({
1083 voiceMicrophone:
1084 value === SYSTEM_DEFAULT ? "" : value.slice("device:".length),
1085 });
1086 }}
1088 <SelectTrigger size="sm" aria-label="Microphone" className="max-w-64">
1089 <SelectValue>{selectedMicrophoneLabel}</SelectValue>
1090 </SelectTrigger>
1091 <SelectPopup align="end" alignItemWithTrigger={false}>
1092 <SelectItem value={SYSTEM_DEFAULT}>System default</SelectItem>
1093 {microphones.map((device) => (
1094 <SelectItem key={device.deviceId} value={`device:${device.deviceId}`}>
1095 {device.label}
1096 </SelectItem>
1097 ))}
1098 </SelectPopup>
1099 </Select>
1100 <Button
1101 type="button"
1102 variant="ghost"
1103 size="icon-sm"
1104 aria-label="Refresh microphones"
1105 onClick={() => void refreshMicrophones()}
1107 <RefreshCwIcon className="size-3.5" />
1108 </Button>
1109 </div>
1110 </div>
1112 />
1113 <SettingsRow
1114 {...searchableSetting("dictation-shortcut-mode")}
1115 title="Dictation shortcut"
1116 description="How the dictation shortcut starts and stops recording."
1117 control={
1118 <Select
1119 value={settings.voiceShortcutMode}
1120 onValueChange={(value) => {
1121 if (value)
1122 void updateClientSettings({ voiceShortcutMode: value as VoiceShortcutMode });
1123 }}
1125 <SelectTrigger size="sm" aria-label="Dictation shortcut mode" className="max-w-72">
1126 <SelectValue>{SHORTCUT_MODE_LABELS[settings.voiceShortcutMode]}</SelectValue>
1127 </SelectTrigger>
1128 <SelectPopup align="end" alignItemWithTrigger={false}>
1129 {(Object.keys(SHORTCUT_MODE_LABELS) as VoiceShortcutMode[]).map((mode) => (
1130 <SelectItem key={mode} value={mode}>
1131 {SHORTCUT_MODE_LABELS[mode]}
1132 </SelectItem>
1133 ))}
1134 </SelectPopup>
1135 </Select>
1137 />
1138 </SettingsSection>
1139​
1140 <SettingsSection id="voice-transcription" title="Transcription">
1141 <SettingsRow
1142 {...searchableSetting("voice-transcription-destination")}
1143 title="Send microphone audio to"
1144 description={
1145 <>
1146 Microphone audio is sent to this environment to transcribe, then discarded. Choose Off
1147 to turn voice input off on this device. This choice is saved on this device only.
1148 </>
1150 control={
1151 <Select
1152 value={destinationValue}
1153 onValueChange={(value) => {
1154 if (!value) return;
1155 chooseAudioDestination(
1156 value === OFF
1157 ? null
1158 : { kind: "environment", environmentId: value as EnvironmentId },
1159 );
1160 }}
1162 <SelectTrigger size="sm" aria-label="Send microphone audio to" className="max-w-72">
1163 <SelectValue>
1164 {destinationValue === OFF
1165 ? "Off"
1166 : (chosenEnvironment?.label ?? "Chosen environment (unavailable)")}
1167 </SelectValue>
1168 </SelectTrigger>
1169 <SelectPopup align="end" alignItemWithTrigger={false}>
1170 <SelectItem value={OFF}>Off</SelectItem>
1171 {environments.map((environment) => (
1172 <SelectItem key={environment.environmentId} value={environment.environmentId}>
1173 {environment.label}
1174 </SelectItem>
1175 ))}
1176 {destination.environmentId && !chosenEnvironment ? (
1177 <SelectItem value={destination.environmentId}>
1178 Chosen environment (unavailable)
1179 </SelectItem>
1180 ) : null}
1181 </SelectPopup>
1182 </Select>
1185 {destination.environmentId && chosenUnsupported ? (
1186 <p className="mt-2 text-xs text-destructive">
1187 {chosenEnvironment.label} can’t transcribe audio. Pick an environment that can to use
1188 voice input.
1189 </p>
1190 ) : null}
1191 </SettingsRow>
1192​
1193 <SettingsRow
1194 {...searchableSetting("speech-language")}
1195 title="Language"
1196 description={
1197 model
1198 ? `${model.model} ${model.supportsLanguageDetection ? "detects the language automatically" : "uses one fixed language"}.`
1199 : "Choose an environment above to see the languages its transcription model supports."
1201 control={<SpeechLanguageSelect model={model} />}
1202 />
1203 {model?.supportsTranslation ? (
1204 <SettingsRow
1205 title="Translate to English"
1206 description="Speak any language and get English text."
1207 control={
1208 <Switch
1209 aria-label="Translate to English"
1210 checked={settings.speechTranslateToEnglish}
1211 onCheckedChange={(checked) =>
1212 void updateClientSettings({ speechTranslateToEnglish: checked })
1214 />
1216 />
1217 ) : null}
1218 {prepared ? (
1219 <SpeechModelBrowser
1220 key={prepared.environmentId}
1221 prepared={prepared}
1222 catalog={catalog}
1223 testEnvironmentId={
1224 project?.environmentId ?? target?.environmentId ?? prepared.environmentId
1226 projectId={project?.id ?? null}
1227 projectName={project?.title ?? null}
1228 />
1229 ) : null}
1230 {prepared && <AdvancedSpeechSettings prepared={prepared} catalog={catalog} />}
1231 </SettingsSection>
1232 <SettingsSection id="voice-recognition" title="Transcription options">
1233 <SettingsRow
1234 {...searchableSetting("speech-silence-filtering")}
1235 title="Silence filtering"
1236 description="Skip silence and other non-speech audio before transcription, keeping a short buffer so words aren’t cut off."
1237 control={
1238 <Switch
1239 aria-label="Silence filtering"
1240 checked={settings.speechSilenceFiltering}
1241 onCheckedChange={(checked) =>
1242 void updateClientSettings({ speechSilenceFiltering: checked })
1244 />
1246 />
1247 <SettingsRow
1248 {...searchableSetting("remove-filler-words")}
1249 title="Remove filler words"
1250 description="Remove filler words like “um” and “uh” from transcripts."
1251 control={
1252 <Switch
1253 aria-label="Remove filler words"
1254 checked={settings.speechRemoveFillerWords}
1255 onCheckedChange={(checked) =>
1256 void updateClientSettings({ speechRemoveFillerWords: checked })
1258 />
1260 />
1261 <SettingsRow
1262 {...searchableSetting("speech-dictionary")}
1263 title="Dictionary"
1264 description="Names and terms transcription should spell your way, saved on this device. Add an alias when it keeps hearing a term wrong. The name of the project you dictate in is also sent as a hint."
1265 control={
1266 <span className="text-xs text-muted-foreground">
1267 {settings.speechCustomWords.length}{" "}
1268 {settings.speechCustomWords.length === 1 ? "entry" : "entries"}
1269 </span>
1272 <div className="mt-2 pb-3.5">
1273 <DictionaryEditor
1274 label="dictionary"
1275 words={settings.speechCustomWords}
1276 onChange={(words) => void updateClientSettings({ speechCustomWords: words })}
1277 />
1278 </div>
1279 </SettingsRow>
1280 <ProjectDictionaryRow />
1281 </SettingsSection>
1282​
1283 <SettingsSection id={searchableSetting("speech-post-processing").id} title="Cleanup">
1284 <SettingsRow
1285 title="Clean up transcripts with a provider"
1286 description="Sends each transcript and the draft text around your cursor to the draft environment’s text generation provider to fix punctuation, numbers, and spoken corrections. Your audio is never sent."
1287 control={
1288 <Switch
1289 aria-label="Clean up transcripts with a provider"
1290 checked={cleanupEnabled}
1291 onCheckedChange={chooseTranscriptCleanup}
1292 />
1294 />
1295 {cleanupEnabled ? (
1296 <SettingsRow
1297 title="Cleanup instructions"
1298 description="Use the built-in instructions or write your own."
1299 control={
1300 <Select
1301 value={settings.speechPostProcessingPrompt.mode}
1302 onValueChange={(value) => {
1303 if (value === "default" || value === "custom")
1304 void updateClientSettings({
1305 speechPostProcessingPrompt: {
1306 ...settings.speechPostProcessingPrompt,
1307 mode: value,
1308 },
1309 });
1310 }}
1312 <SelectTrigger size="sm" aria-label="Cleanup instructions" className="max-w-64">
1313 <SelectValue>
1314 {settings.speechPostProcessingPrompt.mode === "custom" ? "Custom" : "Built-in"}
1315 </SelectValue>
1316 </SelectTrigger>
1317 <SelectPopup align="end" alignItemWithTrigger={false}>
1318 <SelectItem value="default">Built-in</SelectItem>
1319 <SelectItem value="custom">Custom</SelectItem>
1320 </SelectPopup>
1321 </Select>
1324 <Textarea
1325 aria-label="Custom cleanup instructions"
1326 className="mt-2"
1327 maxLength={10_000}
1328 disabled={settings.speechPostProcessingPrompt.mode !== "custom"}
1329 value={
1330 settings.speechPostProcessingPrompt.mode === "custom"
1331 ? settings.speechPostProcessingPrompt.customInstructions
1332 : DEFAULT_SPEECH_POST_PROCESSING_PROMPT
1334 onChange={(event) =>
1335 void updateClientSettings({
1336 speechPostProcessingPrompt: {
1337 mode: "custom",
1338 customInstructions: event.target.value,
1339 },
1340 })
1342 />
1343 </SettingsRow>
1344 ) : null}
1345 {cleanupEnabled && settingsScope !== null ? <CleanupModelRow /> : null}
1346 {cleanupEnabled ? (
1347 <SettingsRow
1348 {...searchableSetting("speech-correction-word")}
1349 title="Correction cue"
1350 description="The word or phrase you say to flag a correction, like “sorry” or “scratch that”. Cleanup applies the correction only where one is meant, and hears the cue as a hint."
1351 control={
1352 <Input
1353 key={settings.speechCorrectionWord}
1354 defaultValue={settings.speechCorrectionWord}
1355 maxLength={50}
1356 placeholder="sorry"
1357 aria-label="Correction cue"
1358 className="w-40"
1359 onBlur={(event) => {
1360 const next = event.target.value.trim();
1361 if (next !== settings.speechCorrectionWord)
1362 void updateClientSettings({ speechCorrectionWord: next });
1363 }}
1364 />
1366 />
1367 ) : null}
1368 </SettingsSection>
1369 </SettingsPageContainer>
1370 );