Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import {
Select,
SelectContent,
SelectItem,
SelectSeparator,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Slider } from "@/components/ui/slider";
import { Spinner } from "@/components/ui/spinner";
import { Switch } from "@/components/ui/switch";
import {
audioCppSizeLabel,
isAudioCppFolderId,
} from "@/features/audio/audio-cpp-catalog";
import { useAudioVoicesStore } from "@/features/audio/stores/audio-voices-store";
import { useIsAccountOwner } from "@/features/auth";
import { audioModelLabel } from "../../audio/audio-workspace-utils";
import {
type SttDownloadStatus,
StudioModelDictationAdapter,
StudioSpeechSynthesisAdapter,
createConfiguredUtterance,
curateSystemVoices,
fetchSttStatus,
generateCustomTtsAudio,
generateStudioTtsAudio,
isDecisionConnection,
loadSttModel,
syncKeepModelsLoaded,
releaseTtsAudioUrl,
startSttDownload,
sttEngineFor,
sttEngineStatusFor,
unloadSttModel,
useChatRuntimeStore,
useExternalProvidersStore,
validateSttModel,
} from "@/features/chat";
import {
type GgufVariantsResponse,
ggufVariantDisplayLabel,
hfApiToken,
invalidateGgufVariantsCache,
listGgufVariants,
useHfTokenStore,
useHubModelSearch,
} from "@/features/hub";
import { useDebouncedValue, useWheelScrollRef } from "@/hooks";
import { useT } from "@/i18n";
import { isTauri } from "@/lib/api-base";
import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
import { MicIcon } from "@/lib/mic-icon";
import { toast } from "@/lib/toast";
import {
Search01Icon,
} from "@hugeicons/core-free-icons";
import { StopIcon } from "@/lib/media-control-icons";
import { AiSpeechIcon } from "@/lib/hugeicons-derived";
import { Volume02Icon } from "@/lib/volume-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { useNavigate } from "@tanstack/react-router";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { resetMicrophonePermission } from "../api/microphone-permission";
import {
type MultiModelMode,
loadMultiModelMode,
updateMultiModelMode,
} from "../api/multi-model";
import {
type AudioApiModel,
loadedSpeechModelId,
watchAudioModels,
} from "../api/openai-model-catalog";
import { listOpenAIAudioModels } from "../api/openai-models";
import { DictationDictionaryView } from "../components/dictation-dictionary-view";
import { RecentDictationsView } from "../components/recent-dictations-view";
import { SettingsRow } from "../components/settings-row";
import { SettingsSection } from "../components/settings-section";
import {
isTrackingSttDownload,
trackSttDownload,
} from "../lib/stt-download-mirror";
import { useSettingsDialogStore } from "../stores/settings-dialog-store";
import {
AUDIO_CPP_STT_FOLDER_IDS,
AUDIO_CPP_STT_MODELS,
MTMD_STT_MODELS,
RECOMMENDED_STT_MODELS,
STT_CONTEXT_LENGTHS,
STT_PICKER_MODELS,
type SttModel,
getSttModelRepo,
isCuratedSttModel,
isSttModelId,
isSttModelLanguageCompatible,
normalizeSttContextLength,
sttModelName,
sttModelSize,
sttListedQuantDownloaded,
sttModelVariant,
sttShownVariant,
type TtsEngine,
useVoiceSettingsStore,
} from "../stores/voice-settings-store";
const STT_RUNTIME_NAMES = new Set(["whisper.cpp", "llama.cpp"]);
const DICTATION_LANGUAGES: { value: string; label: string }[] = [
{ value: "auto", label: "" },
{ value: "en-US", label: "English (US)" },
{ value: "en-GB", label: "English (UK)" },
{ value: "zh-CN", label: "中文 (简体)" },
{ value: "ja-JP", label: "日本語" },
{ value: "ko-KR", label: "한국어" },
{ value: "es-ES", label: "Español" },
{ value: "fr-FR", label: "Français" },
{ value: "de-DE", label: "Deutsch" },
{ value: "it-IT", label: "Italiano" },
{ value: "pt-BR", label: "Português (Brasil)" },
{ value: "ru-RU", label: "Русский" },
{ value: "sv-SE", label: "Svenska" },
{ value: "da-DK", label: "Dansk" },
{ value: "hi-IN", label: "हिन्दी" },
{ value: "ar-SA", label: "العربية" },
{ value: "he-IL", label: "עברית" },
];
// Independent of UI locale: the voice or model may not support that language.
const TTS_PREVIEW_TEXT =
"Hello from Unsloth! This is a preview of the selected voice.";
/** Curated Whisper models come from the Unsloth GGUF repos (stt_ggml_sidecar.py). */
function sttModelSource(model: SttModel): string {
if (AUDIO_CPP_STT_MODELS.has(model) || isAudioCppFolderId(model)) {
return sttModelName(model);
}
return isCuratedSttModel(model) && !MTMD_STT_MODELS.has(model)
? `unslothai/whisper-${model}-GGUF`
: getSttModelRepo(model);
}
/**
* Lists curated and other ASR models and searches Hugging Face for Whisper repos (safetensors via
* Transformers); a plain button trigger keeps the value out of text inputs.
*/
function SttModelPicker({
value,
language,
downloadedModels,
onChange,
}: {
value: SttModel;
language: string;
downloadedModels: ReadonlySet<string>;
onChange: (model: SttModel) => void;
}) {
const t = useT();
const hfToken = useHfTokenStore((state) => state.token);
const [open, setOpen] = useState(false);
// Folder rows have no curated size: read the default quant's from the same
// cached listing the Transcribe picker uses. A row stays blank until it lands.
const [folderSizes, setFolderSizes] = useState<ReadonlyMap<string, string>>(
() => new Map(),
);
useEffect(() => {
if (!open) return;
let cancelled = false;
for (const id of AUDIO_CPP_STT_FOLDER_IDS) {
if (!isSttModelLanguageCompatible(id, language)) continue;
listGgufVariants(id, hfApiToken(hfToken))
.then((listing) => {
const variant =
listing.variants.find(
(row) => row.quant === listing.default_variant,
) ?? listing.variants[0];
if (cancelled || !variant) return;
const size = audioCppSizeLabel(
variant.download_size_bytes ?? variant.size_bytes,
);
setFolderSizes((sizes) =>
sizes.get(id) === size ? sizes : new Map(sizes).set(id, size),
);
})
.catch(() => {});
}
return () => {
cancelled = true;
};
}, [open, language, hfToken]);
const [query, setQuery] = useState("");
const [validating, setValidating] = useState(false);
const resultsRef = useWheelScrollRef<HTMLDivElement>();
const debouncedQuery = useDebouncedValue(query.trim());
const { results, isLoading } = useHubModelSearch(debouncedQuery, {
task: "automatic-speech-recognition",
accessToken: hfApiToken(hfToken),
excludeGguf: true,
enabled: debouncedQuery.length >= 2,
keepUnsupportedTags: true,
ownerScope: "all",
});
const items = useMemo(() => {
if (!debouncedQuery) {
const defaults: string[] = STT_PICKER_MODELS.filter((model) =>
isSttModelLanguageCompatible(model, language),
);
if (!defaults.includes(value)) {
defaults.push(value);
}
return defaults;
}
// Listed models match by name; the Hub search below only finds Whisper repos.
const needle = debouncedQuery.toLowerCase();
const ids: string[] = STT_PICKER_MODELS.filter(
(model) =>
(sttModelName(model).toLowerCase().includes(needle) ||
model.toLowerCase().includes(needle)) &&
isSttModelLanguageCompatible(model, language),
);
for (const result of results) {
const tags = result.tags?.map((tag) => tag.toLowerCase()) ?? [];
const isWhisper =
result.id.toLowerCase().includes("whisper") || tags.includes("whisper");
const isExactMatch =
result.id.toLowerCase() === debouncedQuery.toLowerCase();
if (
(isExactMatch ||
(isWhisper &&
result.pipelineTag === "automatic-speech-recognition")) &&
isSttModelLanguageCompatible(result.id, language) &&
!ids.includes(result.id)
) {
ids.push(result.id);
}
}
return ids;
}, [debouncedQuery, language, results, value]);
const selectModel = async (model: string) => {
if (!isSttModelId(model) || validating) {
return;
}
// The validator checks Transformers checkpoints; a GGUF audio runtime repo is checked on load.
if (!isCuratedSttModel(model) && sttEngineFor(model) !== "audiocpp") {
setValidating(true);
try {
await validateSttModel(model, hfApiToken(hfToken));
} catch (error) {
toast.error(t("settings.voice.dictation.sttModelInvalid"), {
description: error instanceof Error ? error.message : undefined,
});
return;
} finally {
setValidating(false);
}
}
onChange(model);
setOpen(false);
setQuery("");
};
return (
<Popover
open={open}
onOpenChange={(next) => {
setOpen(next);
if (!next) setQuery("");
}}
>
<PopoverTrigger asChild={true}>
<button
type="button"
data-testid="stt-model-trigger"
aria-label={t("settings.voice.dictation.sttModelLabel")}
className="border-border bg-background hover:bg-accent/50 dark:border-transparent dark:bg-[rgb(255_255_255_/_calc(0.06*var(--contrast-wash-gain,1)))] dark:hover:bg-[rgb(255_255_255_/_calc(0.1*var(--contrast-wash-gain,1)))] focus-visible:border-ring flex h-8 w-full cursor-pointer items-center justify-between gap-1.5 rounded-full border px-3.5 text-sm outline-none transition-colors"
>
<span className="truncate">{sttModelName(value)}</span>
<HugeiconsIcon
icon={ChevronDownStandardIcon}
strokeWidth={2}
className="text-muted-foreground pointer-events-none size-4 shrink-0"
/>
</button>
</PopoverTrigger>
<PopoverContent align="start" sideOffset={4} className="w-72 gap-0 p-0">
<div className="relative p-1.5 pb-0.5">
<HugeiconsIcon
icon={Search01Icon}
strokeWidth={2}
className="text-muted-foreground pointer-events-none absolute top-[calc(50%+2px)] left-4 size-3.5 -translate-y-1/2"
/>
<Input
value={query}
onChange={(event) => setQuery(event.target.value)}
data-testid="stt-model-search"
placeholder={t(
"settings.voice.dictation.sttModelSearchPlaceholder",
)}
className="h-8 pl-8 text-sm"
autoFocus={true}
onKeyDown={(event) => {
if (event.key === "Enter" && items.length > 0) {
event.preventDefault();
void selectModel(items[0]);
}
}}
/>
</div>
<div
ref={resultsRef}
data-testid="stt-model-results"
className="max-h-64 overflow-y-auto p-1"
>
{(isLoading && debouncedQuery && items.length === 0) ||
validating ? (
<div className="flex items-center gap-2 px-3 py-3 text-xs text-muted-foreground">
<Spinner className="size-3.5" />
{validating
? t("settings.voice.dictation.sttModelValidating")
: t("settings.voice.dictation.sttModelSearching")}
</div>
) : items.length === 0 ? (
<div className="px-3 py-3 text-xs text-muted-foreground">
{t("settings.voice.dictation.sttModelNoResults")}
</div>
) : (
items.map((model) => {
// A custom repo's name is its id: one-line rows keep a pill
// shape, two-line rows use the row radius.
const twoLines = sttModelSource(model) !== sttModelName(model);
const size = sttModelSize(model) || folderSizes.get(model);
return (
<button
key={model}
type="button"
onClick={() => void selectModel(model)}
aria-selected={model === value}
className={`flex w-full items-center justify-between gap-3 px-2.5 py-1.5 text-left transition-colors hover:bg-muted ${
twoLines ? "rounded-md" : "rounded-full"
} ${model === value ? "bg-accent font-medium" : ""}`}
>
<span className="min-w-0 flex-1 truncate">
<span className="flex items-center gap-1.5 truncate text-xs">
{/* Same green dot the Hub marks an on-device row with. */}
{downloadedModels.has(model) ? (
<span
role="img"
aria-label={t("picker.onDevice")}
className="size-[calc(5px*var(--ui-space-scale,1))] shrink-0 rounded-full bg-status-success"
/>
) : null}
<span className="truncate" title={sttModelName(model)}>
{sttModelName(model)}
</span>
{RECOMMENDED_STT_MODELS.has(model) ? (
<span className="shrink-0 rounded-full bg-emerald-500/12 px-1.5 py-px text-ui-9 font-medium text-emerald-600 dark:bg-emerald-400/15 dark:text-emerald-400">
{t("settings.voice.dictation.sttRecommended")}
</span>
) : null}
</span>
{twoLines ? (
<span className="mt-0.5 block truncate font-mono text-ui-9 leading-tight text-muted-foreground">
{sttModelSource(model)}
</span>
) : null}
</span>
{size ? (
<span className="shrink-0 text-ui-10 tabular-nums text-muted-foreground">
{size}
</span>
) : null}
</button>
);
})
)}
</div>
</PopoverContent>
</Popover>
);
}
function useAudioInputDevices() {
const t = useT();
const [devices, setDevices] = useState<MediaDeviceInfo[]>([]);
const [hasLabels, setHasLabels] = useState(false);
const refresh = useCallback(async () => {
if (!navigator.mediaDevices?.enumerateDevices) return;
try {
const all = await navigator.mediaDevices.enumerateDevices();
const inputs = all.filter((d) => d.kind === "audioinput");
setDevices(inputs);
setHasLabels(inputs.some((d) => d.label));
} catch {
// Enumeration can fail in insecure contexts.
}
}, []);
useEffect(() => {
const media = navigator.mediaDevices;
if (!media?.addEventListener) {
return;
}
let cancelled = false;
media
.enumerateDevices()
.then((all) => {
if (cancelled) {
return;
}
const inputs = all.filter((device) => device.kind === "audioinput");
setDevices(inputs);
setHasLabels(inputs.some((device) => device.label));
})
.catch(() => {
// Enumeration can fail in insecure contexts.
});
media.addEventListener("devicechange", refresh);
return () => {
cancelled = true;
media.removeEventListener("devicechange", refresh);
};
}, [refresh]);
// Labels are hidden until mic permission; a short stream unlocks them.
const requestAccess = useCallback(async () => {
// Insecure contexts (plain http on a LAN address) have no mediaDevices.
if (!navigator.mediaDevices?.getUserMedia) {
toast.error(t("settings.voice.dictation.micAccessUnsupported"));
return;
}
// Clear a saved deny first, or WebView2 rejects without prompting.
await resetMicrophonePermission();
try {
const stream = await navigator.mediaDevices.getUserMedia({
audio: true,
});
for (const track of stream.getTracks()) {
track.stop();
}
await refresh();
} catch {
// resetMicrophonePermission cannot clear a browser's deny, so only desktop can promise a prompt.
toast.error(
t(
isTauri
? "settings.voice.dictation.micAccessBlockedDesktop"
: "settings.voice.dictation.micAccessBlocked",
),
);
}
}, [refresh, t]);
return { devices, hasLabels, requestAccess };
}
function useSystemVoices() {
const [voices, setVoices] = useState<SpeechSynthesisVoice[]>([]);
useEffect(() => {
if (typeof window === "undefined" || !window.speechSynthesis) return;
const synth = window.speechSynthesis;
const load = () => setVoices(synth.getVoices());
load();
synth.addEventListener?.("voiceschanged", load);
return () => synth.removeEventListener?.("voiceschanged", load);
}, []);
return voices;
}
export function VoiceTab() {
const t = useT();
const isOwner = useIsAccountOwner();
const micDeviceId = useVoiceSettingsStore((s) => s.micDeviceId);
const setMicDeviceId = useVoiceSettingsStore((s) => s.setMicDeviceId);
const dictationEngine = useVoiceSettingsStore((s) => s.dictationEngine);
const micTarget = useVoiceSettingsStore((s) => s.micTarget);
const setMicTarget = useVoiceSettingsStore((s) => s.setMicTarget);
const modelHearsAudio = useChatRuntimeStore(
(s) =>
!s.modelLoading &&
s.models.find((model) => model.id === s.params.checkpoint)
?.hasAudioInput === true,
);
const setDictationEngine = useVoiceSettingsStore((s) => s.setDictationEngine);
const sttModel = useVoiceSettingsStore((s) => s.sttModel);
const setSttModel = useVoiceSettingsStore((s) => s.setSttModel);
const sttGgufVariant = useVoiceSettingsStore((s) => s.sttGgufVariant);
const setSttGgufVariant = useVoiceSettingsStore((s) => s.setSttGgufVariant);
// The quant a pinned package folder row runs; null leaves the row's resident or default one.
const sttVariant = sttModelVariant(sttModel, sttGgufVariant);
// Named apart from the `sttDevice` state below, which the sidecar reports back.
const sttDevicePreference = useVoiceSettingsStore((s) => s.sttDevice);
const setSttDevicePreference = useVoiceSettingsStore((s) => s.setSttDevice);
const sttContextLength = useVoiceSettingsStore((s) => s.sttContextLength);
const setSttContextLength = useVoiceSettingsStore((s) => s.setSttContextLength);
const sttProviderId = useVoiceSettingsStore((s) => s.sttProviderId);
const setSttProviderId = useVoiceSettingsStore((s) => s.setSttProviderId);
const sttProviderModel = useVoiceSettingsStore((s) => s.sttProviderModel);
const setSttProviderModel = useVoiceSettingsStore(
(s) => s.setSttProviderModel,
);
const dictationLanguage = useVoiceSettingsStore((s) => s.dictationLanguage);
const setDictationLanguage = useVoiceSettingsStore(
(s) => s.setDictationLanguage,
);
const ttsEnabled = useVoiceSettingsStore((s) => s.ttsEnabled);
const setTtsEnabled = useVoiceSettingsStore((s) => s.setTtsEnabled);
const autoReadAloud = useVoiceSettingsStore((s) => s.autoReadAloud);
const setAutoReadAloud = useVoiceSettingsStore((s) => s.setAutoReadAloud);
const ttsEngine = useVoiceSettingsStore((s) => s.ttsEngine);
const setTtsEngine = useVoiceSettingsStore((s) => s.setTtsEngine);
const ttsVoiceURI = useVoiceSettingsStore((s) => s.ttsVoiceURI);
const setTtsVoiceURI = useVoiceSettingsStore((s) => s.setTtsVoiceURI);
const ttsStudioVoiceId = useVoiceSettingsStore((s) => s.ttsStudioVoiceId);
const setTtsStudioVoiceId = useVoiceSettingsStore(
(s) => s.setTtsStudioVoiceId,
);
const savedVoices = useAudioVoicesStore((s) => s.voices);
const savedVoicesListed = useAudioVoicesStore((s) => s.loaded && !s.error);
const ttsProviderId = useVoiceSettingsStore((s) => s.ttsProviderId);
const setTtsProviderId = useVoiceSettingsStore((s) => s.setTtsProviderId);
const ttsProviderModel = useVoiceSettingsStore((s) => s.ttsProviderModel);
const setTtsProviderModel = useVoiceSettingsStore(
(s) => s.setTtsProviderModel,
);
const ttsProviderVoice = useVoiceSettingsStore((s) => s.ttsProviderVoice);
const setTtsProviderVoice = useVoiceSettingsStore(
(s) => s.setTtsProviderVoice,
);
const connections = useExternalProvidersStore((s) => s.providers);
const ttsConnections = useMemo(
() =>
connections.filter((connection) => !isDecisionConnection(connection)),
[connections],
);
const hasSelectedTtsConnection = ttsConnections.some(
(connection) => connection.id === ttsProviderId,
);
const ttsRate = useVoiceSettingsStore((s) => s.ttsRate);
const setTtsRate = useVoiceSettingsStore((s) => s.setTtsRate);
const ttsPitch = useVoiceSettingsStore((s) => s.ttsPitch);
const setTtsPitch = useVoiceSettingsStore((s) => s.setTtsPitch);
const ttsVolume = useVoiceSettingsStore((s) => s.ttsVolume);
const setTtsVolume = useVoiceSettingsStore((s) => s.setTtsVolume);
const sttConnections = ttsConnections;
const connectionsEnabled = useExternalProvidersStore(
(s) => s.connectionsEnabled,
);
const hasSttConnections = sttConnections.length > 0;
const hasSelectedSttConnection = sttConnections.some(
(connection) => connection.id === sttProviderId,
);
const navigate = useNavigate();
const { devices, hasLabels, requestAccess } = useAudioInputDevices();
const rawVoices = useSystemVoices();
const voices = useMemo(
() => curateSystemVoices(rawVoices, ttsVoiceURI, dictationLanguage),
[rawVoices, ttsVoiceURI, dictationLanguage],
);
const [previewing, setPreviewing] = useState(false);
// A studio preview generates the whole clip first; shown as work.
const [preparingPreview, setPreparingPreview] = useState(false);
const [subpage, setSubpage] = useState<"main" | "recents" | "dictionary">(
"main",
);
const [selectedDictationId, setSelectedDictationId] = useState<string | null>(
null,
);
useEffect(() => {
if (sttProviderId && !hasSelectedSttConnection) {
setSttProviderId("");
}
}, [hasSelectedSttConnection, setSttProviderId, sttProviderId]);
// Drop a deleted connection, or every read aloud posts the stale id.
useEffect(() => {
if (ttsProviderId && !hasSelectedTtsConnection) {
setTtsProviderId("");
}
}, [hasSelectedTtsConnection, setTtsProviderId, ttsProviderId]);
const modelSttSupported = StudioModelDictationAdapter.isSupported();
const ttsSupported = StudioSpeechSynthesisAdapter.isSupported();
const systemTtsSupported =
StudioSpeechSynthesisAdapter.systemVoicesSupported();
const effectiveTtsEngine: TtsEngine =
ttsEngine === "system" && !systemTtsSupported ? "studio" : ttsEngine;
// Voices saved on the Audio page since the last visit show up without a reload.
useEffect(() => {
if (effectiveTtsEngine === "studio") {
void useAudioVoicesStore.getState().refresh();
}
}, [effectiveTtsEngine]);
// Which speech model read aloud would use, and whether loading one unloads the chat model.
const [audioModels, setAudioModels] = useState<AudioApiModel[]>([]);
const [multiModelMode, setMultiModelMode] = useState<MultiModelMode | null>(
null,
);
const [savingMultiModel, setSavingMultiModel] = useState(false);
useEffect(() => {
if (effectiveTtsEngine !== "studio") return;
let stale = false;
loadMultiModelMode(t("settings.resources.modelMemory.loadError")).then(
(mode) => {
if (!stale) setMultiModelMode(mode);
},
() => {},
);
const stop = watchAudioModels(listOpenAIAudioModels, setAudioModels);
return () => {
stale = true;
stop();
};
}, [effectiveTtsEngine, t]);
const loadedTtsModel = loadedSpeechModelId(
audioModels,
Boolean(ttsStudioVoiceId),
);
const keepBothLoaded = async () => {
setSavingMultiModel(true);
try {
const mode = await updateMultiModelMode(
"fit",
t("settings.resources.modelMemory.saveError"),
);
setMultiModelMode(mode);
syncKeepModelsLoaded(mode);
} catch (error) {
toast.error(
error instanceof Error
? error.message
: t("settings.resources.modelMemory.saveError"),
);
} finally {
setSavingMultiModel(false);
}
};
// A deleted voice would otherwise stay selected and every read aloud would fail on it.
const hasSelectedStudioVoice = savedVoices.some(
(voice) => voice.id === ttsStudioVoiceId,
);
useEffect(() => {
if (!ttsStudioVoiceId || !savedVoicesListed || hasSelectedStudioVoice) {
return;
}
let cancelled = false;
void useAudioVoicesStore
.getState()
.confirmGone(ttsStudioVoiceId)
.then((gone) => {
if (gone && !cancelled) setTtsStudioVoiceId("");
});
return () => {
cancelled = true;
};
}, [
hasSelectedStudioVoice,
savedVoicesListed,
setTtsStudioVoiceId,
ttsStudioVoiceId,
]);
// Local STT stays on-demand. Track its phase without fetching model weights.
type SttPhase =
| "idle"
| "checking"
| "on-demand"
| "unavailable"
| "loading"
| "ready"
| "error";
type SttDownloadAvailability =
"checking" | "missing" | "downloaded" | "error";
const [sttPhase, setSttPhase] = useState<SttPhase>("idle");
const [sttDevice, setSttDevice] = useState<string | null>(null);
const [statusNonce, setStatusNonce] = useState(0);
const [sttUnloading, setSttUnloading] = useState(false);
const isLocalEngine = dictationEngine === "model";
const isCustomEngine = dictationEngine === "custom";
const [sttDownload, setSttDownload] = useState<SttDownloadStatus | null>(
null,
);
// Every engine's downloaded models, for the picker's on-device dots.
const [downloadedSttModels, setDownloadedSttModels] = useState<
ReadonlySet<string>
>(() => new Set());
// Was a bare two-sample delta over ~800ms with no window or stability gate,
// so one throttled timer or bursty poll set the displayed speed outright.
// Model whose download this tab watched; completion auto-loads it.
const watchedDownloadRef = useRef<string | null>(null);
// The quant this tab started downloading; an adopted transfer's quant is unknown.
const startedDownloadRef = useRef<{
model: string;
variant: string | null;
} | null>(null);
// Quant resident for the selected row, so an unpinned Select shows what dictation would run.
const [sttLoadedVariant, setSttLoadedVariant] = useState<string | null>(null);
// The selected package folder's quants, from the same cached listing the Transcribe picker reads.
const [sttVariantListing, setSttVariantListing] = useState<{
model: string;
listing: GgufVariantsResponse;
} | null>(null);
const [sttListingNonce, setSttListingNonce] = useState(0);
// Selecting a model (or finishing its download) loads it without a Load
// click. A model that is not downloaded fails quietly and stays on demand.
const autoLoadSttModel = useCallback(
async (model: string, variant: string | null = null) => {
setSttPhase("loading");
try {
await loadSttModel(model, undefined, undefined, undefined, variant);
} catch {
// Not downloaded (or the engine is busy): the status poll resets the phase
// and the user still sees the Download button.
} finally {
setStatusNonce((nonce) => nonce + 1);
}
},
[],
);
const sttRepoId = getSttModelRepo(sttModel);
const hfToken = useHfTokenStore((state) => state.token);
// biome-ignore lint/correctness/useExhaustiveDependencies: sttListingNonce is the refetch trigger once a quant lands.
useEffect(() => {
if (!isLocalEngine || !isAudioCppFolderId(sttModel)) return;
let cancelled = false;
listGgufVariants(sttModel, hfApiToken(hfToken))
.then((listing) => {
if (!cancelled) setSttVariantListing({ model: sttModel, listing });
})
.catch(() => {});
return () => {
cancelled = true;
};
}, [isLocalEngine, sttModel, hfToken, sttListingNonce]);
const sttVariants =
sttVariantListing?.model === sttModel
? sttVariantListing.listing.variants
: [];
const shownSttVariant = sttShownVariant(
sttVariant,
sttLoadedVariant,
sttVariantListing?.model === sttModel ? sttVariantListing.listing : null,
);
const shownSttLabel = ggufVariantDisplayLabel(
sttVariants.find((variant) => variant.quant === shownSttVariant) ?? {
quant: shownSttVariant ?? "",
},
);
const [sttDownloadStarting, setSttDownloadStarting] = useState(false);
const [sttDownloadAvailability, setSttDownloadAvailability] = useState<{
repoId: string;
state: SttDownloadAvailability;
}>({ repoId: "", state: "checking" });
const rowSttDownloadAvailability =
sttDownloadAvailability.repoId === sttRepoId
? sttDownloadAvailability.state
: "checking";
// Status knows rows, not quants: a pinned quant of a row with another one cached is missing, or
// failed when its download did, as a row's would.
const effectiveSttDownloadAvailability =
rowSttDownloadAvailability === "downloaded" &&
sttVariant &&
sttVariantListing?.model === sttModel &&
!sttListedQuantDownloaded(sttVariantListing.listing, sttVariant)
? sttDownload?.error
? "error"
: "missing"
: rowSttDownloadAvailability;
useEffect(() => {
if (!isLocalEngine || !modelSttSupported) {
return;
}
let cancelled = false;
void (async () => {
// Only the first poll shows "checking" so polling does not flicker.
setSttPhase((phase) => (phase === "idle" ? "checking" : phase));
try {
const status = await fetchSttStatus(statusNonce, sttModel);
if (cancelled) return;
setDownloadedSttModels(
new Set(
[
status.transformers,
status.gguf,
status.mtmd,
status.audiocpp,
].flatMap((engine) => engine?.downloaded_models ?? []),
),
);
// A curated model prefers the GGUF (whisper.cpp) engine, but without whisper-server the
// backend serves it through Transformers instead of failing. Fall back to the Transformers
// status here too, or the model shows as unavailable and download is blocked even though it
// works. mtmd and audio.cpp models run nowhere else, so they never fall back.
const engineStatus = sttEngineStatusFor(status, sttModel);
if (!engineStatus?.available) {
setSttPhase("unavailable");
return;
}
const rowLoaded = engineStatus.loaded_model === sttModel;
setSttLoadedVariant(
rowLoaded ? (engineStatus.loaded_variant ?? null) : null,
);
// A pinned quant is ready only when that quant is the resident one.
const loaded =
rowLoaded &&
(!sttVariant || engineStatus.loaded_variant === sttVariant);
const download = engineStatus.download;
setSttDownload(download);
setSttDownloadAvailability({
repoId: sttRepoId,
state: engineStatus.downloaded_models.includes(sttModel)
? "downloaded"
: download.error
? "error"
: "missing",
});
if (download.downloading) {
// Adopt a transfer that outlived the page that started it, so it
// still shows in the download panel.
if (
download.model &&
!isTrackingSttDownload(
download.model,
undefined,
download.download_id,
)
) {
trackSttDownload(download.model, {
// Saved keys already encode their quant; only folder rows carry one.
ggufVariant: sttModelVariant(
download.model,
download.variant ?? "",
),
downloadId: download.download_id,
});
}
watchedDownloadRef.current = download.model;
window.setTimeout(() => {
if (!cancelled) setStatusNonce((n) => n + 1);
}, 800);
} else {
const finished = watchedDownloadRef.current;
watchedDownloadRef.current = null;
const started = startedDownloadRef.current;
startedDownloadRef.current = null;
// Only the quant that landed may load: a quant picked meanwhile is not on disk.
const landedPinned =
started?.model === finished
? started.variant === sttVariant
: sttVariant === null;
if (finished === sttModel && isAudioCppFolderId(sttModel)) {
// The cached listing still has this quant as not downloaded.
invalidateGgufVariantsCache(sttModel);
setSttListingNonce((nonce) => nonce + 1);
}
if (
finished === sttModel &&
engineStatus.downloaded_models.includes(sttModel) &&
!loaded &&
landedPinned
) {
// The download this tab watched just finished; load the model.
void autoLoadSttModel(sttModel, sttVariant);
return;
}
}
if (engineStatus.loading) {
setSttPhase("loading");
window.setTimeout(() => {
if (!cancelled) setStatusNonce((n) => n + 1);
}, 600);
return;
}
if (loaded && !engineStatus.loading) {
setSttDevice(engineStatus.device);
setSttPhase("ready");
window.setTimeout(
() => {
if (!cancelled) setStatusNonce((n) => n + 1);
},
Math.max(
1000,
Math.min(engineStatus.keep_alive_seconds * 1000, 15_000),
),
);
return;
}
// Opening settings never downloads or loads a model; Load or recording does.
setSttDevice(null);
setSttPhase("on-demand");
} catch {
if (!cancelled) setSttPhase("error");
}
})();
return () => {
cancelled = true;
};
}, [
isLocalEngine,
sttModel,
sttVariant,
sttRepoId,
modelSttSupported,
statusNonce,
autoLoadSttModel,
]);
const sttStatusText = (() => {
switch (sttPhase) {
case "checking":
return t("settings.voice.dictation.sttChecking");
case "loading":
return t("settings.voice.dictation.sttLoadingModel");
case "on-demand":
return t("settings.voice.dictation.sttOnDemand");
case "ready":
// These runtimes report their own name, not a device.
return sttDevice &&
!STT_RUNTIME_NAMES.has(sttDevice) &&
!sttDevice.startsWith("audio.cpp")
? t("settings.voice.dictation.sttReady", {
device: sttDevice.toUpperCase(),
})
: t("settings.voice.dictation.sttLoaded");
case "unavailable":
return t("settings.voice.dictation.sttUnavailable");
case "error":
return t("settings.voice.dictation.sttModelFailed");
default:
return "";
}
})();
const downloadingThisModel =
isLocalEngine &&
sttDownload?.downloading === true &&
sttDownload.model === sttModel;
const sttModelStatusText = (() => {
if (downloadingThisModel) {
const total = sttDownload?.bytes_total ?? 0;
const done = sttDownload?.bytes_done ?? 0;
return t("settings.voice.dictation.sttDownloading", {
progress:
total > 0 ? Math.min(99, Math.round((done / total) * 100)) : 0,
});
}
if (sttPhase === "unavailable") {
return sttStatusText;
}
switch (effectiveSttDownloadAvailability) {
case "checking":
return t("settings.voice.dictation.sttDownloadChecking");
case "missing":
return t("settings.voice.dictation.sttNotDownloaded");
case "error":
return t("settings.voice.dictation.sttDownloadFailed");
case "downloaded":
return sttStatusText;
default:
return "";
}
})();
// Pressing Download is the confirmation; the prompt is for paths that never asked.
const beginSttDownload = async () => {
setSttDownloadStarting(true);
try {
const download = await startSttDownload(
sttModel,
hfApiToken(hfToken),
undefined,
sttVariant,
);
trackSttDownload(sttModel, {
ggufVariant: sttVariant,
downloadId: download.download_id,
});
startedDownloadRef.current = { model: sttModel, variant: sttVariant };
// The status effect only re-polls while it can see a download. Its last read was before this
// one existed, and the on-demand branch schedules nothing, so without a nudge the tab shows
// Download for the whole transfer.
setStatusNonce((nonce) => nonce + 1);
} catch (error) {
toast.error(t("settings.voice.dictation.sttDownloadFailed"), {
description: error instanceof Error ? error.message : undefined,
});
} finally {
setSttDownloadStarting(false);
}
};
const warmSttModel = async () => {
setSttPhase("loading");
try {
await loadSttModel(sttModel, undefined, undefined, undefined, sttVariant);
setStatusNonce((nonce) => nonce + 1);
} catch (error) {
setSttPhase("error");
toast.error(t("settings.voice.dictation.sttModelFailed"), {
description: error instanceof Error ? error.message : undefined,
});
}
};
const releaseSttModel = async () => {
setSttUnloading(true);
try {
await unloadSttModel();
setStatusNonce((nonce) => nonce + 1);
} catch (error) {
toast.error(t("settings.voice.dictation.sttModelFailed"), {
description: error instanceof Error ? error.message : undefined,
});
} finally {
setSttUnloading(false);
}
};
// Keep an item for an unplugged saved mic so the value stays visible.
const knownMic = devices.some((d) => d.deviceId === micDeviceId);
const previewAudioRef = useRef<HTMLAudioElement | null>(null);
const previewAbortRef = useRef<AbortController | null>(null);
// Read-aloud shares the global synthesizer; only cancel an utterance this tab owns.
const previewingRef = useRef(false);
// A studio preview must not cancel an unrelated chat read-aloud.
const ownsSystemPreviewRef = useRef(false);
const markPreviewing = useCallback((value: boolean) => {
previewingRef.current = value;
setPreviewing(value);
if (!value) setPreparingPreview(false);
}, []);
const releasePreviewAudio = useCallback(() => {
if (previewAudioRef.current) {
previewAudioRef.current.pause();
releaseTtsAudioUrl(previewAudioRef.current.src);
// removeAttribute, not `src = ""`: an empty src fires a media error toast.
previewAudioRef.current.removeAttribute("src");
previewAudioRef.current = null;
}
}, []);
const stopPreview = useCallback(() => {
if (!previewingRef.current) return;
if (ownsSystemPreviewRef.current) {
window.speechSynthesis?.cancel();
ownsSystemPreviewRef.current = false;
}
previewAbortRef.current?.abort();
previewAbortRef.current = null;
releasePreviewAudio();
markPreviewing(false);
}, [markPreviewing, releasePreviewAudio]);
const previewTts = async () => {
if (!ttsSupported) return;
// A ref so a double-click before rerender cannot start a second request.
if (previewingRef.current) {
stopPreview();
return;
}
if (effectiveTtsEngine !== "system") {
const controller = new AbortController();
previewAbortRef.current = controller;
ownsSystemPreviewRef.current = false;
markPreviewing(true);
setPreparingPreview(true);
try {
const generate =
effectiveTtsEngine === "custom"
? generateCustomTtsAudio
: generateStudioTtsAudio;
const url = await generate(TTS_PREVIEW_TEXT, controller.signal);
if (controller.signal.aborted) {
releaseTtsAudioUrl(url);
return;
}
setPreparingPreview(false);
const audio = new Audio(url);
audio.playbackRate = ttsRate;
audio.volume = ttsVolume;
// Some browsers reset playbackRate once metadata loads.
audio.addEventListener("loadedmetadata", () => {
audio.playbackRate = ttsRate;
});
audio.addEventListener("ended", () => {
releasePreviewAudio();
markPreviewing(false);
});
audio.addEventListener("error", () => {
releasePreviewAudio();
markPreviewing(false);
toast.error(t("settings.voice.readAloud.previewFailed"));
});
previewAudioRef.current = audio;
await audio.play();
} catch (error) {
if (!controller.signal.aborted) {
toast.error(
error instanceof Error
? error.message
: t("settings.voice.readAloud.previewFailed"),
);
}
releasePreviewAudio();
markPreviewing(false);
}
return;
}
if (!StudioSpeechSynthesisAdapter.systemVoicesSupported()) {
toast.error(t("settings.voice.readAloud.notSupported"));
return;
}
const utterance = createConfiguredUtterance(TTS_PREVIEW_TEXT);
utterance.addEventListener("end", () => {
ownsSystemPreviewRef.current = false;
markPreviewing(false);
});
utterance.addEventListener("error", () => {
ownsSystemPreviewRef.current = false;
markPreviewing(false);
});
ownsSystemPreviewRef.current = true;
window.speechSynthesis.cancel();
window.speechSynthesis.speak(utterance);
markPreviewing(true);
};
useEffect(() => stopPreview, [stopPreview]);
if (subpage === "recents") {
return (
<RecentDictationsView
selectedId={selectedDictationId}
onSelect={setSelectedDictationId}
onBack={() => {
setSelectedDictationId(null);
setSubpage("main");
}}
/>
);
}
if (subpage === "dictionary") {
return <DictationDictionaryView onBack={() => setSubpage("main")} />;
}
return (
<div className="settings-page">
<header className="flex flex-col gap-1">
<h1 className="text-xl font-semibold font-heading">
{t("settings.voice.title")}
</h1>
<p className="text-xs text-muted-foreground">
{t("settings.voice.description")}
</p>
</header>
<SettingsSection title={t("settings.voice.dictation.sectionTitle")}>
<SettingsRow
label={t("settings.voice.dictation.micTargetLabel")}
description={
!modelHearsAudio
? t("settings.voice.dictation.micTargetModelUnavailable")
: micTarget === "model"
? t("settings.voice.dictation.micTargetModelDescription")
: t("settings.voice.dictation.micTargetAsrDescription")
}
>
<Select
value={micTarget}
onValueChange={(value) =>
setMicTarget(value === "model" ? "model" : "asr")
}
>
<SelectTrigger
data-testid="mic-target-trigger"
aria-label={t("settings.voice.dictation.micTargetLabel")}
className="w-56"
size="sm"
>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="asr">
{t("settings.voice.dictation.micTargetAsr")}
</SelectItem>
<SelectItem
value="model"
data-testid="mic-target-model"
disabled={!modelHearsAudio && micTarget !== "model"}
>
{t("settings.voice.dictation.micTargetModel")}
</SelectItem>
</SelectContent>
</Select>
</SettingsRow>
<SettingsRow
label={t("settings.voice.dictation.engineLabel")}
description={
dictationEngine === "model"
? t("settings.voice.dictation.engineModelDescription")
: dictationEngine === "custom"
? t("settings.voice.dictation.engineCustomDescription")
: t("settings.voice.dictation.engineBrowserDescription")
}
>
<Select
value={dictationEngine}
onValueChange={(value) => {
const next =
value === "model"
? "model"
: value === "custom"
? "custom"
: "browser";
if (next !== dictationEngine) {
if (dictationEngine === "model") {
void unloadSttModel().catch(() => {});
}
if (next === "model") {
setSttPhase("checking");
setSttDevice(null);
setSttDownload(null);
}
}
setDictationEngine(next);
}}
>
<SelectTrigger
data-testid="dictation-engine-trigger"
aria-label={t("settings.voice.dictation.engineLabel")}
className="w-56"
size="sm"
>
<SelectValue />
</SelectTrigger>
<SelectContent>
{isTauri ? null : (
<SelectItem value="browser">
{t("settings.voice.dictation.engineBrowser")}
</SelectItem>
)}
<SelectItem value="model" data-testid="dictation-engine-model">
{t("settings.voice.dictation.engineModel")}
</SelectItem>
<SelectItem
value="custom"
data-testid="dictation-engine-custom"
disabled={!connectionsEnabled}
>
{t("settings.voice.dictation.engineCustom")}
</SelectItem>
</SelectContent>
</Select>
</SettingsRow>
{isCustomEngine ? (
<>
<SettingsRow
label={t("settings.voice.dictation.connectionLabel")}
description={t("settings.voice.dictation.connectionDescription")}
>
<Select
value={hasSelectedSttConnection ? sttProviderId : undefined}
onValueChange={setSttProviderId}
disabled={!connectionsEnabled || !hasSttConnections}
>
<SelectTrigger
aria-label={t("settings.voice.dictation.connectionLabel")}
className="w-56"
size="sm"
>
<SelectValue
placeholder={t(
hasSttConnections
? "settings.voice.dictation.connectionPlaceholder"
: "settings.voice.dictation.connectionEmpty",
)}
/>
</SelectTrigger>
<SelectContent>
{sttConnections.map((connection) => (
<SelectItem key={connection.id} value={connection.id}>
{connection.name}
</SelectItem>
))}
</SelectContent>
</Select>
</SettingsRow>
<SettingsRow
label={t("settings.voice.dictation.customModelLabel")}
description={t("settings.voice.dictation.customModelDescription")}
>
<Input
value={sttProviderModel}
onChange={(event) => setSttProviderModel(event.target.value)}
placeholder="whisper-1"
aria-label={t("settings.voice.dictation.customModelLabel")}
className="w-56"
/>
</SettingsRow>
</>
) : null}
{isLocalEngine ? (
modelSttSupported ? (
<SettingsRow
label={t("settings.voice.dictation.sttModelLabel")}
description={
sttVariants.length > 1
? t("settings.voice.dictation.sttQuantDescription")
: t("settings.voice.dictation.sttModelDescription")
}
// Progress lives in the shared downloads panel; a second bar here
// said the same thing twice.
below={
<div className="flex min-h-7 w-56 items-center justify-between gap-3">
<span className="flex min-w-0 items-center gap-2 text-xs text-muted-foreground">
{effectiveSttDownloadAvailability === "checking" ||
sttPhase === "loading" ||
sttPhase === "checking" ? (
<span className="size-1.5 shrink-0 animate-pulse rounded-full bg-current" />
) : sttPhase === "ready" ||
(effectiveSttDownloadAvailability === "downloaded" &&
sttPhase === "on-demand") ? (
<span className="size-1.5 shrink-0 rounded-full bg-emerald-500" />
) : effectiveSttDownloadAvailability === "error" ||
sttPhase === "error" ? (
<span className="size-1.5 shrink-0 rounded-full bg-destructive" />
) : null}
<span>{sttModelStatusText}</span>
</span>
{sttPhase === "unavailable" ? (
<Button
variant="ghost"
size="sm"
className="h-7 px-2 text-xs"
onClick={() => setStatusNonce((nonce) => nonce + 1)}
>
{t("settings.voice.dictation.sttRetry")}
</Button>
) : effectiveSttDownloadAvailability === "error" ? (
<Button
variant="ghost"
size="sm"
className="h-7 px-2 text-xs"
disabled={downloadingThisModel || sttDownloadStarting}
// The sidecar error is sticky until a new start().
onClick={() => void beginSttDownload()}
>
{t("settings.voice.dictation.sttRetry")}
</Button>
) : effectiveSttDownloadAvailability === "missing" ? (
<Button
variant="outline"
size="sm"
className="text-xs"
disabled={downloadingThisModel || sttDownloadStarting}
onClick={() => void beginSttDownload()}
>
{downloadingThisModel || sttDownloadStarting ? (
<Spinner className="mr-1.5" />
) : null}
{t("settings.voice.dictation.sttDownload")}
</Button>
) : effectiveSttDownloadAvailability === "downloaded" ? (
sttPhase === "ready" ? (
<Button
variant="outline"
size="sm"
className="text-xs"
disabled={sttUnloading}
onClick={releaseSttModel}
>
{sttUnloading ? <Spinner className="mr-1.5" /> : null}
{sttUnloading
? t("settings.voice.dictation.sttUnloading")
: t("settings.voice.dictation.sttUnload")}
</Button>
) : sttPhase === "loading" || sttPhase === "checking" ? (
<Button
variant="outline"
size="icon-sm"
className="size-7"
disabled={true}
aria-label={t(
"settings.voice.dictation.sttLoadingModel",
)}
>
<Spinner />
</Button>
) : (
<Button
variant="outline"
size="sm"
className="text-xs"
onClick={warmSttModel}
>
{sttPhase === "error"
? t("settings.voice.dictation.sttRetry")
: t("settings.voice.dictation.sttLoad")}
</Button>
)
) : null}
</div>
}
>
<div className="flex w-56 flex-col gap-1.5">
<SttModelPicker
value={sttModel}
language={dictationLanguage}
downloadedModels={downloadedSttModels}
onChange={(next) => {
if (next !== sttModel) {
void unloadSttModel().catch(() => {});
void autoLoadSttModel(next);
}
setSttModel(next);
}}
/>
{/* A saved key names its own quant, so only package folder rows offer one. */}
{sttVariants.length > 1 ? (
// Bound to the pin, not the shown quant: picking the quant that runs now
// must still save it, or an idle unload drops back to another one.
<Select
value={sttVariant ?? ""}
onValueChange={(next) => {
setSttGgufVariant(next);
if (next === shownSttVariant) return;
void unloadSttModel().catch(() => {});
void autoLoadSttModel(sttModel, next);
}}
>
<SelectTrigger
data-testid="stt-quant-trigger"
aria-label={t("settings.voice.dictation.sttQuantLabel")}
className="w-full font-mono text-xs"
size="sm"
>
{/* Unpinned, the value is "" and Radix renders the placeholder. */}
<SelectValue placeholder={shownSttLabel}>
{shownSttLabel}
</SelectValue>
</SelectTrigger>
<SelectContent align="end">
{sttVariants.map((variant) => (
<SelectItem
key={variant.quant}
value={variant.quant}
// Size flush right, as in the Agents quant list.
className="[&>span:last-child]:w-full [&>span:last-child]:justify-between"
>
<span className="flex items-center gap-1.5 font-mono text-xs whitespace-nowrap">
{/* The slot stays when empty, so the labels share a column. */}
{variant.downloaded ? (
<span
role="img"
aria-label={t("picker.onDevice")}
className="size-[calc(5px*var(--ui-space-scale,1))] shrink-0 rounded-full bg-status-success"
/>
) : (
<span className="size-[calc(5px*var(--ui-space-scale,1))] shrink-0" />
)}
{ggufVariantDisplayLabel(variant)}
</span>
<span className="text-ui-10 tabular-nums whitespace-nowrap text-muted-foreground">
{audioCppSizeLabel(
variant.download_size_bytes ?? variant.size_bytes,
)}
</span>
</SelectItem>
))}
</SelectContent>
</Select>
) : null}
</div>
</SettingsRow>
) : (
<SettingsRow
label={t("settings.voice.dictation.sttModelLabel")}
description={t("settings.voice.dictation.sttModelUnsupported")}
/>
)
) : null}
{isLocalEngine && modelSttSupported ? (
<SettingsRow
label={t("settings.voice.dictation.sttDeviceLabel")}
description={
sttDevicePreference === "cpu"
? t("settings.voice.dictation.sttDeviceCpuDescription")
: t("settings.voice.dictation.sttDeviceAutoDescription")
}
>
<Select
value={sttDevicePreference}
onValueChange={(value) => {
const next = value === "cpu" ? "cpu" : "auto";
if (next === sttDevicePreference) return;
// Scoped so another surface's model is not evicted; wait:false spares a decoding
// dictation.
void unloadSttModel(sttEngineFor(sttModel), sttModel, {
wait: false,
}).catch(() => {});
setSttPhase("on-demand");
setSttDevice(null);
setSttDevicePreference(next);
}}
>
<SelectTrigger
data-testid="stt-device-trigger"
aria-label={t("settings.voice.dictation.sttDeviceLabel")}
className="w-56"
size="sm"
>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="auto" data-testid="stt-device-auto">
{t("settings.voice.dictation.sttDeviceAuto")}
</SelectItem>
<SelectItem value="cpu" data-testid="stt-device-cpu">
{t("settings.voice.dictation.sttDeviceCpu")}
</SelectItem>
</SelectContent>
</Select>
</SettingsRow>
) : null}
{isLocalEngine && modelSttSupported && MTMD_STT_MODELS.has(sttModel) ? (
<SettingsRow
label={t("settings.voice.dictation.sttContextLabel")}
description={
sttContextLength === 0
? t("settings.voice.dictation.sttContextAutoDescription")
: t("settings.voice.dictation.sttContextFixedDescription")
}
>
<Select
value={String(sttContextLength)}
onValueChange={(value) => {
const next = normalizeSttContextLength(Number(value));
if (next === sttContextLength) return;
// Keep an active transcription; the next request applies the new preference.
void unloadSttModel(sttEngineFor(sttModel), sttModel, {
wait: false,
}).catch(() => {});
setSttPhase("on-demand");
setSttDevice(null);
setSttContextLength(next);
}}
>
<SelectTrigger
data-testid="stt-context-trigger"
aria-label={t("settings.voice.dictation.sttContextLabel")}
className="w-56"
size="sm"
>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="0" data-testid="stt-context-auto">
{t("settings.voice.dictation.sttContextAuto")}
</SelectItem>
{STT_CONTEXT_LENGTHS.map((length) => (
<SelectItem key={length} value={String(length)}>
{t("settings.voice.dictation.sttContextTokens", {
count: length.toLocaleString(),
})}
</SelectItem>
))}
{sttContextLength > 0 &&
!STT_CONTEXT_LENGTHS.some((length) => length === sttContextLength) ? (
<SelectItem value={String(sttContextLength)}>
{t("settings.voice.dictation.sttContextTokens", {
count: sttContextLength.toLocaleString(),
})}
</SelectItem>
) : null}
</SelectContent>
</Select>
</SettingsRow>
) : null}
<SettingsRow
label={t("settings.voice.dictation.microphoneLabel")}
description={
hasLabels
? micDeviceId !== "default"
? t("settings.voice.dictation.microphoneFallbackHint")
: t("settings.voice.dictation.microphoneDescription")
: t("settings.voice.dictation.microphoneGrantDescription")
}
>
{hasLabels ? (
<Select value={micDeviceId} onValueChange={setMicDeviceId}>
<SelectTrigger
aria-label={t("settings.voice.dictation.microphoneLabel")}
className="min-w-56 max-w-72"
size="sm"
>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="default">
{t("settings.voice.dictation.systemDefault")}
</SelectItem>
{devices
.filter((d) => d.deviceId && d.deviceId !== "default")
.map((d, i) => (
<SelectItem key={d.deviceId} value={d.deviceId}>
{d.label ||
t("settings.voice.dictation.microphoneFallbackName", {
index: i + 1,
})}
</SelectItem>
))}
{!knownMic && micDeviceId !== "default" ? (
<SelectItem value={micDeviceId}>
{t("settings.voice.dictation.savedMicDisconnected")}
</SelectItem>
) : null}
</SelectContent>
</Select>
) : (
<Button variant="outline" size="sm" onClick={requestAccess}>
<MicIcon className="mr-1.5 size-3.5" />
{t("settings.voice.dictation.allowMicrophone")}
</Button>
)}
</SettingsRow>
<SettingsRow
label={t("settings.voice.dictation.languageLabel")}
description={t("settings.voice.dictation.languageDescription")}
>
<Select
value={dictationLanguage}
onValueChange={setDictationLanguage}
>
<SelectTrigger
aria-label={t("settings.voice.dictation.languageLabel")}
className="min-w-56 max-w-72"
size="sm"
>
<SelectValue />
</SelectTrigger>
<SelectContent>
{DICTATION_LANGUAGES.map(({ value, label }) => (
<SelectItem key={value} value={value}>
{value === "auto"
? t(
isCustomEngine
? "settings.voice.dictation.languageAutoDetect"
: "settings.voice.dictation.languageAuto",
)
: label}
</SelectItem>
))}
</SelectContent>
</Select>
</SettingsRow>
<SettingsRow
label={t("settings.voice.dictionary.manageLabel")}
description={t("settings.voice.dictionary.sectionDescription")}
>
<Button
variant="outline"
size="sm"
onClick={() => setSubpage("dictionary")}
>
{t("settings.voice.dictionary.manage")}
</Button>
</SettingsRow>
<SettingsRow
label={t("settings.voice.recents.manageLabel")}
description={t("settings.voice.recents.sectionDescription")}
>
<Button
variant="outline"
size="sm"
onClick={() => {
setSelectedDictationId(null);
setSubpage("recents");
}}
>
{t("settings.voice.recents.manage")}
</Button>
</SettingsRow>
</SettingsSection>
<SettingsSection title={t("settings.voice.readAloud.sectionTitle")}>
{ttsSupported ? (
<>
<SettingsRow
label={t("settings.voice.readAloud.buttonLabel")}
description={t("settings.voice.readAloud.buttonDescription")}
>
<Switch checked={ttsEnabled} onCheckedChange={setTtsEnabled} />
</SettingsRow>
<SettingsRow
label={t("settings.voice.readAloud.autoLabel")}
description={t("settings.voice.readAloud.autoDescription")}
>
<Switch
checked={autoReadAloud}
onCheckedChange={setAutoReadAloud}
/>
</SettingsRow>
<SettingsRow
label={t("settings.voice.readAloud.engineLabel")}
description={
effectiveTtsEngine === "studio"
? t("settings.voice.readAloud.engineStudioDescription")
: effectiveTtsEngine === "custom"
? t("settings.voice.readAloud.engineCustomDescription")
: t("settings.voice.readAloud.engineSystemDescription")
}
>
<Select
value={effectiveTtsEngine}
onValueChange={(value) =>
setTtsEngine(
value === "studio" || value === "custom" ? value : "system",
)
}
>
<SelectTrigger
aria-label={t("settings.voice.readAloud.engineLabel")}
className="min-w-56 max-w-72"
size="sm"
>
<SelectValue />
</SelectTrigger>
<SelectContent>
{systemTtsSupported ? (
<SelectItem value="system">
{t("settings.voice.readAloud.engineSystem")}
</SelectItem>
) : null}
<SelectItem value="studio">
{t("settings.voice.readAloud.engineStudio")}
</SelectItem>
<SelectItem value="custom">
{t("settings.voice.readAloud.engineCustom")}
</SelectItem>
</SelectContent>
</Select>
</SettingsRow>
{effectiveTtsEngine === "custom" ? (
<>
<SettingsRow
label={t("settings.voice.readAloud.connectionLabel")}
description={t(
"settings.voice.readAloud.connectionDescription",
)}
>
<Select
value={hasSelectedTtsConnection ? ttsProviderId : ""}
onValueChange={setTtsProviderId}
disabled={ttsConnections.length === 0}
>
<SelectTrigger
aria-label={t("settings.voice.readAloud.connectionLabel")}
className="min-w-56 max-w-72"
size="sm"
>
<SelectValue
placeholder={t(
"settings.voice.readAloud.connectionPlaceholder",
)}
/>
</SelectTrigger>
<SelectContent>
{ttsConnections.map((connection) => (
<SelectItem key={connection.id} value={connection.id}>
{connection.name}
</SelectItem>
))}
</SelectContent>
</Select>
</SettingsRow>
<SettingsRow
label={t("settings.voice.readAloud.customModelLabel")}
>
<Input
value={ttsProviderModel}
onChange={(e) => setTtsProviderModel(e.target.value)}
placeholder="kokoro"
className="h-8 w-56 max-w-72"
aria-label={t("settings.voice.readAloud.customModelLabel")}
/>
</SettingsRow>
<SettingsRow
label={t("settings.voice.readAloud.voiceLabel")}
description={t(
"settings.voice.readAloud.customVoiceDescription",
)}
>
<Input
value={ttsProviderVoice}
onChange={(e) => setTtsProviderVoice(e.target.value)}
placeholder="alloy"
className="h-8 w-56 max-w-72"
aria-label={t("settings.voice.readAloud.voiceLabel")}
/>
</SettingsRow>
</>
) : effectiveTtsEngine === "studio" ? (
<>
<SettingsRow
label={t("settings.voice.readAloud.modelLabel")}
description={
loadedTtsModel
? t("settings.voice.readAloud.modelLoaded", {
model: audioModelLabel(loadedTtsModel),
})
: t("settings.voice.readAloud.modelDescription")
}
>
{/* The row named the model selector but offered no way to reach it. */}
<Button
variant="outline"
size="sm"
onClick={() => {
useSettingsDialogStore.getState().closeDialog();
// Audio keeps the mode it was left in, so name the TTS task.
void navigate({
to: "/audio",
search: { task: "text-to-speech" },
});
}}
>
<HugeiconsIcon
icon={AiSpeechIcon}
className="mr-1.5 size-3.5"
/>
{t("settings.voice.readAloud.openAudioAction")}
</Button>
</SettingsRow>
{/* Owner only, like Resources: a managed account's save is refused. */}
{multiModelMode === "off" && isOwner ? (
<SettingsRow
label={t("settings.voice.readAloud.keepBothLabel")}
description={t(
"settings.voice.readAloud.keepBothDescription",
)}
>
<Button
variant="outline"
size="sm"
disabled={savingMultiModel}
onClick={() => void keepBothLoaded()}
>
{t("settings.voice.readAloud.keepBothAction")}
</Button>
</SettingsRow>
) : null}
<SettingsRow
label={t("settings.voice.readAloud.voiceLabel")}
description={t(
"settings.voice.readAloud.studioVoiceDescription",
)}
>
<Select
value={ttsStudioVoiceId || "model"}
onValueChange={(value) =>
setTtsStudioVoiceId(value === "model" ? "" : value)
}
>
<SelectTrigger
aria-label={t("settings.voice.readAloud.voiceLabel")}
className="min-w-56 max-w-72"
size="sm"
>
<SelectValue />
</SelectTrigger>
<SelectContent className="max-h-[min(--spacing(72),var(--radix-select-content-available-height))]">
<SelectItem value="model">
{t("settings.voice.readAloud.studioVoiceDefault")}
</SelectItem>
{savedVoices.length > 0 ? <SelectSeparator /> : null}
{savedVoices.map((voice) => (
<SelectItem key={voice.id} value={voice.id}>
{voice.name}
</SelectItem>
))}
{/* Until the list loads, or if it fails, keep the stored choice visible. */}
{ttsStudioVoiceId && !hasSelectedStudioVoice ? (
<SelectItem value={ttsStudioVoiceId}>
{t("settings.voice.readAloud.studioVoiceSaved")}
</SelectItem>
) : null}
</SelectContent>
</Select>
</SettingsRow>
</>
) : (
<SettingsRow
label={t("settings.voice.readAloud.voiceLabel")}
description={t("settings.voice.readAloud.voiceDescription")}
>
<Select value={ttsVoiceURI} onValueChange={setTtsVoiceURI}>
<SelectTrigger
aria-label={t("settings.voice.readAloud.voiceLabel")}
className="min-w-56 max-w-72"
size="sm"
>
<SelectValue />
</SelectTrigger>
<SelectContent className="max-h-[min(--spacing(72),var(--radix-select-content-available-height))]">
<SelectItem value="default">
{t("settings.voice.dictation.systemDefault")}
</SelectItem>
{voices.map((voice) => (
<SelectItem key={voice.voiceURI} value={voice.voiceURI}>
{voice.name} ({voice.lang})
</SelectItem>
))}
</SelectContent>
</Select>
</SettingsRow>
)}
<SettingsRow
label={t("settings.voice.readAloud.speedLabel")}
description={`${ttsRate.toFixed(2)}x`}
>
<Slider
value={[ttsRate]}
min={0.5}
max={2}
step={0.05}
onValueChange={([v]) => v !== undefined && setTtsRate(v)}
className="w-48"
aria-label={t("settings.voice.readAloud.speedLabel")}
/>
</SettingsRow>
{effectiveTtsEngine === "system" && (
<SettingsRow
label={t("settings.voice.readAloud.pitchLabel")}
description={`${ttsPitch.toFixed(2)}`}
>
<Slider
value={[ttsPitch]}
min={0}
max={2}
step={0.05}
onValueChange={([v]) => v !== undefined && setTtsPitch(v)}
className="w-48"
aria-label={t("settings.voice.readAloud.pitchLabel")}
/>
</SettingsRow>
)}
<SettingsRow
label={t("settings.voice.readAloud.volumeLabel")}
description={`${Math.round(ttsVolume * 100)}%`}
>
<Slider
value={[ttsVolume]}
min={0}
max={1}
step={0.05}
onValueChange={([v]) => v !== undefined && setTtsVolume(v)}
className="w-48"
aria-label={t("settings.voice.readAloud.volumeLabel")}
/>
</SettingsRow>
<SettingsRow
label={t("settings.voice.readAloud.previewLabel")}
description={t("settings.voice.readAloud.previewDescription")}
>
<Button
variant="outline"
size="sm"
onClick={() => void previewTts()}
>
{preparingPreview ? (
<>
<Spinner
className="mr-1.5 size-3.5"
label={t("settings.voice.readAloud.preparingAction")}
/>
{t("settings.voice.readAloud.preparingAction")}
</>
) : previewing ? (
<>
<HugeiconsIcon icon={StopIcon} className="mr-1.5 size-3 animate-pulse fill-current text-destructive" />
{t("settings.voice.readAloud.stopAction")}
</>
) : (
<>
<HugeiconsIcon
icon={Volume02Icon}
className="mr-1.5 size-3.5"
/>
{t("settings.voice.readAloud.previewAction")}
</>
)}
</Button>
</SettingsRow>
</>
) : (
<SettingsRow
label={t("settings.voice.readAloud.ttsLabel")}
description={t("settings.voice.readAloud.notSupported")}
/>
)}
</SettingsSection>
</div>
);
}