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 { TTS_MAX_TOKENS } from "@/features/audio/audio-workspace-constants";
import { authFetch } from "@/features/auth";
import { useVoiceSettingsStore } from "@/features/settings/stores/voice-settings-store";
import { formatApiErrorBody } from "@/lib/format-fastapi-error";
import { toast } from "@/lib/toast";
import type { SpeechSynthesisAdapter } from "@assistant-ui/react";
import {
audioModelsFromCatalog,
loadedSpeechModelId,
} from "../../settings/api/openai-model-catalog";
import { encryptProviderApiKey } from "../api/providers-api";
import { getExternalProviderApiKey } from "../external-providers";
import { stripSearchImageTokens } from "../search-images/search-images";
import { useExternalProvidersStore } from "../stores/external-providers-store";
import { markdownToSpeechText } from "../utils/speech-text";
import { splitIntoSentences } from "../voice/speech-text";
import { planTtsChunk } from "../voice/tts-chunk-plan";
/** "default" resolves to the platform's default voice; undefined lets the browser pick. */
export function findTtsVoice(
voiceURI: string,
): SpeechSynthesisVoice | undefined {
if (typeof window === "undefined" || !window.speechSynthesis) {
return undefined;
}
if (!voiceURI) return undefined;
const voices = window.speechSynthesis.getVoices();
if (voiceURI === "default") return voices.find((voice) => voice.default);
return voices.find((voice) => voice.voiceURI === voiceURI);
}
// macOS novelty and legacy Eloquence voices that sound robotic and flood the picker.
const LOW_QUALITY_VOICE_NAMES = new Set([
"albert",
"bad news",
"bahh",
"bells",
"boing",
"bubbles",
"cellos",
"deranged",
"eddy",
"flo",
"fred",
"good news",
"grandma",
"grandpa",
"hysterical",
"jester",
"junior",
"kathy",
"organ",
"princess",
"ralph",
"reed",
"rocko",
"sandy",
"shelley",
"superstar",
"trinoids",
"whisper",
"wobble",
"zarvox",
]);
function voiceBaseName(voice: SpeechSynthesisVoice): string {
const name = voice.name.split("(")[0]?.trim().toLowerCase() ?? "";
return name;
}
// Tie-breaker when the name has no quality hint, so basic voices are not just alphabetical.
const PREFERRED_VOICE_NAMES = [
"samantha",
"alex",
"ava",
"allison",
"susan",
"tom",
"daniel",
"serena",
"karen",
"moira",
"tessa",
"fiona",
];
function voiceQualityScore(voice: SpeechSynthesisVoice): number {
const name = voice.name.toLowerCase();
let score = 0;
if (name.includes("premium")) score += 100;
if (name.includes("siri")) score += 90;
if (name.includes("enhanced")) score += 80;
if (name.includes("natural") || name.includes("neural")) score += 70;
if (name.includes("google")) score += 40;
if (name.includes("microsoft")) score += 30;
return score;
}
function voiceLocaleScore(voice: SpeechSynthesisVoice): number {
const navLang =
typeof navigator !== "undefined" && navigator.language
? navigator.language.toLowerCase()
: "en-us";
const lang = voice.lang.toLowerCase().replace("_", "-");
if (lang === navLang) return 2;
if (langBase(lang) === langBase(navLang)) return 1;
return 0;
}
function voicePreferredRank(voice: SpeechSynthesisVoice): number {
const index = PREFERRED_VOICE_NAMES.indexOf(voiceBaseName(voice));
return index === -1 ? 0 : PREFERRED_VOICE_NAMES.length - index;
}
function langBase(tag: string): string {
return tag.toLowerCase().split(/[-_]/)[0] ?? "";
}
const MAX_CURATED_VOICES = 20;
export function curateSystemVoices(
voices: SpeechSynthesisVoice[],
selectedVoiceURI?: string,
dictationLanguage = useVoiceSettingsStore.getState().dictationLanguage,
): SpeechSynthesisVoice[] {
const wantedLangs = new Set<string>(["en"]);
if (typeof navigator !== "undefined" && navigator.language) {
wantedLangs.add(langBase(navigator.language));
}
if (dictationLanguage && dictationLanguage !== "auto") {
wantedLangs.add(langBase(dictationLanguage));
}
// WebKit and Linux report empty or duplicate voiceURIs, which break Radix Select.
const seenVoiceURIs = new Set<string>();
const kept = voices.filter((voice) => {
if (!voice.voiceURI || seenVoiceURIs.has(voice.voiceURI)) return false;
seenVoiceURIs.add(voice.voiceURI);
if (LOW_QUALITY_VOICE_NAMES.has(voiceBaseName(voice))) return false;
return wantedLangs.has(langBase(voice.lang));
});
kept.sort((a, b) => {
const quality = voiceQualityScore(b) - voiceQualityScore(a);
if (quality !== 0) return quality;
const locale = voiceLocaleScore(b) - voiceLocaleScore(a);
if (locale !== 0) return locale;
const preferred = voicePreferredRank(b) - voicePreferredRank(a);
if (preferred !== 0) return preferred;
const byDefault = Number(b.default) - Number(a.default);
if (byDefault !== 0) return byDefault;
return a.name.localeCompare(b.name);
});
// macOS lists some voices twice (compact + enhanced) under one name; keep one per name/language.
const keyOf = (voice: SpeechSynthesisVoice) =>
`${voiceBaseName(voice)}|${voice.lang.toLowerCase()}`;
const winners = new Map<string, string>();
for (const voice of kept) {
const key = keyOf(voice);
if (!winners.has(key)) winners.set(key, voice.voiceURI);
if (voice.voiceURI === selectedVoiceURI) winners.set(key, voice.voiceURI);
}
const deduped = kept.filter(
(voice) => winners.get(keyOf(voice)) === voice.voiceURI,
);
const curated = deduped.slice(0, MAX_CURATED_VOICES);
if (
selectedVoiceURI &&
selectedVoiceURI !== "default" &&
!curated.some((voice) => voice.voiceURI === selectedVoiceURI)
) {
const selected = voices.find(
(voice) => voice.voiceURI === selectedVoiceURI,
);
if (selected) curated.push(selected);
}
return curated;
}
/** The macOS browser default is often a robotic legacy voice; use the top curated one. */
function defaultTtsVoice(): SpeechSynthesisVoice | undefined {
if (typeof window === "undefined" || !window.speechSynthesis) {
return undefined;
}
const voices = window.speechSynthesis.getVoices();
return (
curateSystemVoices(voices)[0] ??
voices.find((voice) => voice.default) ??
voices[0]
);
}
export function createConfiguredUtterance(
text: string,
): SpeechSynthesisUtterance {
const { ttsVoiceURI, ttsRate, ttsPitch, ttsVolume } =
useVoiceSettingsStore.getState();
const utterance = new SpeechSynthesisUtterance(text);
const voice = findTtsVoice(ttsVoiceURI) ?? defaultTtsVoice();
if (voice) {
utterance.voice = voice;
utterance.lang = voice.lang;
}
utterance.rate = ttsRate;
utterance.pitch = ttsPitch;
utterance.volume = ttsVolume;
return utterance;
}
/** Named because an unnamed request reaches the active (chat) model; null leaves it unnamed.
* Lists loaded models only: /v1/models rescans every downloaded model once its cache expires. */
async function resolveReadAloudModel(
wantsClone: boolean,
signal?: AbortSignal,
): Promise<string | null> {
try {
const res = await authFetch("/api/inference/loaded-models", { signal });
if (!res.ok) return null;
return loadedSpeechModelId(
audioModelsFromCatalog(await res.json()),
wantsClone,
);
} catch (error) {
if (signal?.aborted) throw error;
return null;
}
}
function readAloudError(
detail: string,
model: string | null,
voiceId: string,
): Error {
if (/no model loaded|not an audio model/i.test(detail)) {
return new Error(
"No Unsloth speech model is loaded. Open Audio › Text to Speech and load one, then try again.",
);
}
// The named model was unloaded after the listing (an image or video load, or idle unload).
if (model && /downloaded but not loaded|is not loaded/i.test(detail)) {
return new Error(
"The Unsloth speech model for read aloud is no longer loaded. Load it again in Audio › Text to Speech.",
);
}
// Only this 404 is about the voice; another one (a model hidden from the account) must not
// drop the user's choice.
if (voiceId && /saved voice no longer exists/i.test(detail)) {
useVoiceSettingsStore.getState().setTtsStudioVoiceId("");
return new Error(
"The saved voice for read aloud no longer exists. Read aloud now uses the model's own voice.",
);
}
if (voiceId && /can clone a voice/i.test(detail)) {
return new Error(
"The loaded model can't use saved voices. Load a voice-cloning model in Audio › Text to Speech, or choose Model's own voice in Settings → Voice.",
);
}
return new Error(detail);
}
export async function generateStudioTtsAudio(
text: string,
signal?: AbortSignal,
): Promise<string> {
const { ttsStudioVoiceId } = useVoiceSettingsStore.getState();
const model = await resolveReadAloudModel(Boolean(ttsStudioVoiceId), signal);
const response = await authFetch("/api/inference/audio/generate", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
messages: [{ role: "user", content: text }],
stream: false,
// Read aloud is not a Speak run, so it stays out of Speak's history.
persist: false,
max_tokens: TTS_MAX_TOKENS,
...(model ? { model } : {}),
...(ttsStudioVoiceId ? { voice_id: ttsStudioVoiceId } : {}),
}),
signal,
});
if (!response.ok) {
// Some refusals nest the message ({detail: {error: {message}}}), so read it like other routes.
const body: unknown = await response.json().catch(() => null);
throw readAloudError(
formatApiErrorBody(body) ?? `HTTP ${response.status}`,
model,
ttsStudioVoiceId,
);
}
const data = (await response.json()) as {
audio?: { data?: string };
choices?: { finish_reason?: string }[];
};
if (!data.audio?.data) {
throw new Error("The TTS model returned no audio.");
}
if (data.choices?.[0]?.finish_reason === "length") {
toast.warning(
"Read aloud stopped at the speech model's length limit before the end of the reply.",
);
}
return `data:audio/wav;base64,${data.audio.data}`;
}
export async function generateCustomTtsAudio(
text: string,
signal?: AbortSignal,
): Promise<string> {
const providersState = useExternalProvidersStore.getState();
if (!providersState.connectionsEnabled) {
throw new Error(
"Connections are disabled. Turn on Enable connections in Settings → Connections to use a custom TTS endpoint.",
);
}
const { ttsProviderId, ttsProviderModel, ttsProviderVoice } =
useVoiceSettingsStore.getState();
const model = ttsProviderModel.trim();
const voice = ttsProviderVoice.trim() || "alloy";
if (!ttsProviderId || !model) {
throw new Error(
"Custom TTS is not configured. Pick a connection and model in Settings → Voice.",
);
}
// A failed key migration leaves a legacy key; send it like chat and STT, or this is unauthenticated.
const provider = providersState.providers.find(
(candidate) => candidate.id === ttsProviderId,
);
if (!provider) {
useVoiceSettingsStore.getState().setTtsProviderId("");
throw new Error(
"The custom TTS connection no longer exists. Pick another connection in Settings → Voice.",
);
}
const legacyApiKey = provider.hasApiKey
? ""
: getExternalProviderApiKey(ttsProviderId).trim();
const encryptedApiKey = legacyApiKey
? await encryptProviderApiKey(legacyApiKey)
: "";
// Both encryption and auth refresh yield; re-check before each request so a policy change
// cannot release text or a retained key.
const assertConnectionSnapshot = () => {
const currentProvidersState = useExternalProvidersStore.getState();
if (!currentProvidersState.connectionsEnabled) {
throw new Error(
"Connections are disabled. Turn on Enable connections in Settings → Connections to use a custom TTS endpoint.",
);
}
const currentProvider = currentProvidersState.providers.find(
(candidate) => candidate.id === ttsProviderId,
);
if (!currentProvider) {
useVoiceSettingsStore.getState().setTtsProviderId("");
throw new Error(
"The custom TTS connection no longer exists. Pick another connection in Settings → Voice.",
);
}
if (
currentProvider.baseUrl !== provider.baseUrl ||
currentProvider.providerType !== provider.providerType ||
currentProvider.backendProviderType !== provider.backendProviderType ||
currentProvider.hasApiKey !== provider.hasApiKey ||
currentProvider.updatedAt !== provider.updatedAt
) {
throw new Error(
"The custom TTS connection changed while the request was starting. Try again.",
);
}
};
assertConnectionSnapshot();
const response = await authFetch(
"/api/inference/audio/speech",
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
input: text,
provider_id: ttsProviderId,
provider_base_url: provider.baseUrl,
model,
voice,
...(encryptedApiKey ? { encrypted_api_key: encryptedApiKey } : {}),
}),
signal,
},
{ beforeRetry: assertConnectionSnapshot },
);
if (!response.ok) {
const body = (await response.json().catch(() => null)) as {
detail?: string;
} | null;
throw new Error(body?.detail ?? `HTTP ${response.status}`);
}
const bytes = await response.arrayBuffer();
const contentType =
response.headers.get("content-type")?.split(";")[0]?.trim() || "audio/wav";
return URL.createObjectURL(new Blob([bytes], { type: contentType }));
}
export function releaseTtsAudioUrl(url: string): void {
if (url.startsWith("blob:")) URL.revokeObjectURL(url);
}
/** Read-aloud chunks: one sentence first for a fast start, then sentences merged to a budget. */
export function readAloudChunks(text: string): string[] {
const pending = splitIntoSentences(text);
const chunks: string[] = [];
while (pending.length > 0) {
const take = Math.max(
1,
planTtsChunk({ pending, first: chunks.length === 0, final: true, playing: false, waitedMs: 0 }),
);
chunks.push(pending.splice(0, take).join(" "));
}
return chunks;
}
function speakWithBackendAudio(
generate: (text: string, signal?: AbortSignal) => Promise<string>,
text: string,
handleEnd: (
reason: "finished" | "error" | "cancelled",
error?: unknown,
) => void,
markRunning: () => void,
): { cancel: () => void } {
const { ttsRate, ttsVolume } = useVoiceSettingsStore.getState();
const controller = new AbortController();
const chunks = readAloudChunks(text);
let audio: HTMLAudioElement | null = null;
let audioUrl: string | null = null;
let next: Promise<string> | null = null;
let cancelled = false;
const cleanup = () => {
if (audio) {
audio.pause();
audio.removeAttribute("src");
audio = null;
}
if (audioUrl) {
releaseTtsAudioUrl(audioUrl);
audioUrl = null;
}
};
const synth = (index: number): Promise<string> => {
const pending = generate(chunks[index] ?? "", controller.signal);
// Awaited later; a chunk dropped by cancel must not reject unhandled.
pending.catch(() => {});
return pending;
};
const play = (url: string) =>
new Promise<void>((resolve, reject) => {
audioUrl = url;
audio = new Audio(url);
audio.playbackRate = ttsRate;
audio.volume = ttsVolume;
// Some browsers reset playbackRate on load, so reapply it on loadedmetadata.
audio.addEventListener("loadedmetadata", () => {
if (audio) audio.playbackRate = ttsRate;
});
audio.addEventListener("ended", () => {
cleanup();
resolve();
});
audio.addEventListener("error", () => {
cleanup();
reject(new Error("Audio playback failed."));
});
audio.play().catch(reject);
});
void (async () => {
try {
let pendingChunk = synth(0);
next = pendingChunk;
for (let i = 0; i < chunks.length; i++) {
const url = await pendingChunk;
next = null;
if (cancelled) {
releaseTtsAudioUrl(url);
return;
}
if (i + 1 < chunks.length) {
pendingChunk = synth(i + 1);
next = pendingChunk;
}
if (i === 0) markRunning();
// A subscriber may cancel on the running notification.
if (cancelled) {
releaseTtsAudioUrl(url);
return;
}
await play(url);
if (cancelled) return;
}
handleEnd("finished");
} catch (error) {
if (cancelled || controller.signal.aborted) return;
cleanup();
controller.abort();
next?.then(releaseTtsAudioUrl, () => {});
handleEnd("error", error);
}
})();
return {
cancel: () => {
cancelled = true;
controller.abort();
next?.then(releaseTtsAudioUrl, () => {});
cleanup();
handleEnd("cancelled");
},
};
}
export class StudioSpeechSynthesisAdapter implements SpeechSynthesisAdapter {
static systemVoicesSupported(): boolean {
return (
typeof window !== "undefined" &&
"speechSynthesis" in window &&
typeof window.SpeechSynthesisUtterance !== "undefined"
);
}
// The studio engine needs only fetch and Audio, so WebViews without Web Speech still work.
static isSupported(): boolean {
return (
StudioSpeechSynthesisAdapter.systemVoicesSupported() ||
(typeof window !== "undefined" && typeof window.Audio !== "undefined")
);
}
speak(spokenText: string): SpeechSynthesisAdapter.Utterance {
const text = markdownToSpeechText(stripSearchImageTokens(spokenText));
const subscribers = new Set<() => void>();
const handleEnd = (
reason: "finished" | "error" | "cancelled",
error?: unknown,
) => {
if (res.status.type === "ended") return;
if (
reason === "error" &&
error !== "interrupted" &&
error !== "canceled"
) {
toast.error(
error instanceof Error ? error.message : "Read aloud failed.",
);
}
res.status = { type: "ended", reason, error };
for (const handler of subscribers) handler();
};
let cancelImpl: () => void;
const { ttsEngine } = useVoiceSettingsStore.getState();
const res: SpeechSynthesisAdapter.Utterance = {
status: { type: "starting" },
cancel: () => cancelImpl(),
subscribe: (callback) => {
if (res.status.type === "ended") {
let cancelled = false;
queueMicrotask(() => {
if (!cancelled) callback();
});
return () => {
cancelled = true;
};
}
subscribers.add(callback);
return () => {
subscribers.delete(callback);
};
},
};
if (!text.trim()) {
cancelImpl = () => {};
handleEnd("finished");
return res;
}
if (
ttsEngine !== "system" ||
!StudioSpeechSynthesisAdapter.systemVoicesSupported()
) {
const generate =
ttsEngine === "custom"
? generateCustomTtsAudio
: generateStudioTtsAudio;
const session = speakWithBackendAudio(generate, text, handleEnd, () => {
if (res.status.type === "ended") return;
// The adapter contract drives UI state off these subscribe callbacks.
res.status = { type: "running" };
for (const handler of subscribers) handler();
});
cancelImpl = session.cancel;
return res;
}
const utterance = createConfiguredUtterance(text);
utterance.addEventListener("end", () => handleEnd("finished"));
utterance.addEventListener("error", (e) => handleEnd("error", e.error));
// Chrome silently drops speak() while a cancelled run's utterance is queued.
window.speechSynthesis.cancel();
window.speechSynthesis.speak(utterance);
res.status = { type: "running" };
cancelImpl = () => {
window.speechSynthesis.cancel();
handleEnd("cancelled");
};
return res;
}
}