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 assert from "node:assert/strict";
import test from "node:test";
import type { AudioModelContext } from "../src/features/audio/tools/types.ts";
import { readSrc, registerBundlerResolver } from "./helpers/kit.ts";
registerBundlerResolver();
const {
audioModelContextFor,
collectToolRequest,
panelApplies,
panelValue,
toolValueKey,
} = await import("../src/features/audio/tools/select.ts");
const {
CLONE_PANEL_LOGIC,
COSYVOICE_INSTRUCTION_MISSING,
EMOTION_AUDIO_MISSING,
SAVED_VOICE_DELETED,
SAVED_VOICE_MISSING,
SAVED_VOICE_NO_TRANSCRIPT,
chatterboxExpressivenessLogic,
cloneDescriptionLogic,
cosyVoiceModeLogic,
emotionSourceProblem,
f5SpeedDialectLogic,
indexTts2EmotionLogic,
qwen3TimbreLogic,
speakVoiceLogic,
speakVoiceStored,
supertonicLanguageLogic,
vibeVoiceDialogueLogic,
voiceOptionName,
} = await import("../src/features/audio/tools/panel-logic.ts");
const {
cloneBlocker,
emotionVectorString,
formatVibeVoiceScript,
referenceTextField,
} = await import("../src/features/audio/clone-policy.ts");
const ctx = (
overrides: Partial<AudioModelContext> = {},
): AudioModelContext => ({
audioType: "audiocpp_tts",
audioFamily: null,
musicGeneration: false,
cudaMusicGeneration: false,
musicNeedsDescription: false,
audioWorkflows: ["clone"],
requiredInputs: [],
referenceTextMode: null,
...overrides,
});
const shown = (
family: string,
workflow: "speak" | "clone" = "clone",
extra = {},
) =>
CLONE_PANEL_LOGIC.filter((panel) =>
panelApplies(panel, workflow, ctx({ audioFamily: family, ...extra })),
).map((panel) => panel.id);
test("each clone family gets its one panel, only on Clone", () => {
assert.deepEqual(shown("qwen3_tts"), ["qwen3-timbre"]);
assert.deepEqual(shown("index_tts2"), ["index-emotion"]);
assert.deepEqual(shown("chatterbox"), ["chatterbox-expressiveness"]);
assert.deepEqual(shown("cosyvoice3"), ["cosyvoice-mode"]);
assert.deepEqual(shown("f5_tts"), ["f5-speed-dialect"]);
assert.deepEqual(shown("voxcpm2"), []);
assert.deepEqual(shown("qwen3_tts", "speak"), []);
assert.deepEqual(shown("voxcpm2", "clone", { cloneDescription: true }), [
"clone-description",
]);
assert.deepEqual(shown("voxcpm2", "speak", { cloneDescription: true }), []);
});
test("Clone's description shows only when the model's clone path reads one", () => {
assert.equal(
panelApplies(
cloneDescriptionLogic,
"clone",
ctx({ cloneDescription: true }),
),
true,
);
assert.equal(
panelApplies(
cloneDescriptionLogic,
"clone",
ctx({ cloneDescription: false }),
),
false,
);
assert.equal(panelApplies(cloneDescriptionLogic, "clone", ctx()), false);
assert.equal(
panelApplies(
cloneDescriptionLogic,
"speak",
ctx({ cloneDescription: true }),
),
false,
);
});
test("Clone's description is trimmed and sent only when written", () => {
assert.deepEqual(cloneDescriptionLogic.initial([]), { instructions: "" });
assert.deepEqual(
cloneDescriptionLogic.toRequest({ instructions: " Calm and slow \n" }),
{ instructions: "Calm and slow" },
);
assert.deepEqual(cloneDescriptionLogic.toRequest({ instructions: "" }), {});
assert.deepEqual(
cloneDescriptionLogic.toRequest({ instructions: " \t\n " }),
{},
);
const { patch, error } = collectToolRequest(
[cloneDescriptionLogic] as never,
{ "clone-description": { instructions: " Warm and bright " } },
{ text: "hi" },
ctx({ cloneDescription: true }),
);
assert.deepEqual(patch, { instructions: "Warm and bright" });
assert.equal(error, null);
assert.deepEqual(
collectToolRequest(
[cloneDescriptionLogic] as never,
{},
{ text: "hi" },
ctx({ cloneDescription: true }),
).patch,
{},
);
});
test("Clone's description panel reuses the shared description field", () => {
const panels = readSrc("features/audio/tools/clone-panels.tsx");
assert.match(panels, /<InstructionsField\s+instructionsKind="voice"/);
assert.match(panels, /cloning=\{true\}\s+disabled=\{disabled\}/);
const field = readSrc("features/audio/components/instructions-fields.tsx");
// Locked while a clone runs, like the other Clone panels.
assert.match(field, /disabled=\{disabled\}/);
assert.ok(
field.includes(
"Optional. How the cloned voice should deliver the text, such as its mood, pace or tone.",
),
);
assert.ok(field.includes("Calm and warm, speaking a little slowly…"));
assert.doesNotMatch(field, /(?<!Unsloth )\bStudio\b/);
});
test("the Voice panel shows on Speak for models that clone or declare a voice", () => {
assert.equal(
panelApplies(
speakVoiceLogic,
"speak",
ctx({ audioWorkflows: ["speak", "clone"] }),
),
true,
);
assert.equal(
panelApplies(speakVoiceLogic, "speak", ctx({ audioWorkflows: ["speak"] })),
false,
);
assert.equal(
panelApplies(
speakVoiceLogic,
"speak",
ctx({ audioWorkflows: ["speak", "clone"], referenceTextMode: "required" }),
),
true,
);
assert.equal(
panelApplies(
speakVoiceLogic,
"speak",
ctx({ audioWorkflows: ["speak"], voiceOption: "voice_id" }),
),
true,
);
assert.equal(
panelApplies(
speakVoiceLogic,
"clone",
ctx({ audioWorkflows: ["speak", "clone"] }),
),
false,
);
assert.equal(
panelApplies(
vibeVoiceDialogueLogic,
"speak",
ctx({ audioFamily: "vibevoice" }),
),
true,
);
});
test("Supertonic's Language panel shows on Speak and sends only a code it reads", () => {
const supertonic = ctx({
audioFamily: "supertonic",
audioWorkflows: ["speak"],
});
assert.equal(
panelApplies(supertonicLanguageLogic, "speak", supertonic),
true,
);
assert.equal(
panelApplies(
supertonicLanguageLogic,
"speak",
ctx({ audioFamily: "kokoro_tts", audioWorkflows: ["speak"] }),
),
false,
);
const request = (stored: unknown) =>
collectToolRequest(
[{ ...supertonicLanguageLogic, Component: () => null }],
stored === undefined ? {} : { "supertonic-language": stored },
{ text: "Hallo" },
supertonic,
).patch;
assert.deepEqual(request("de"), { language: "de" });
assert.deepEqual(request(""), {});
assert.deepEqual(request(undefined), {});
assert.deepEqual(request("German"), {});
});
test("collectToolRequest merges every panel's part and returns the first error", () => {
const a = {
id: "a",
initial: () => ({ on: true }),
toRequest: () => ({ options: { x: 1 }, instructions: "first" }),
validate: () => "a is missing",
};
const b = {
id: "b",
initial: () => ({}),
toRequest: () => ({
options: { y: "z" },
speed: 1.5,
referenceTextMode: "hidden" as const,
}),
validate: () => "b is missing",
};
const { patch, error } = collectToolRequest(
[a, b] as never,
{},
{ text: "hi" },
ctx(),
);
assert.deepEqual(patch, {
options: { x: 1, y: "z" },
instructions: "first",
speed: 1.5,
referenceTextMode: "hidden",
});
assert.equal(error, "a is missing");
});
test("a kept value is laid over the panel's defaults", () => {
const value = panelValue(
indexTts2EmotionLogic,
{ "index-emotion": { mode: "mixer" } },
[],
);
assert.equal(value.mode, "mixer");
assert.equal(value.alpha, 0.7);
assert.equal(value.vector.length, 8);
assert.equal(
toolValueKey("repo/model", "clone", "index-emotion"),
"repo/model:clone:index-emotion",
);
});
test("clone panels start at the option defaults the server fills", () => {
const specs = [
{ name: "emotion_alpha", type: "float" as const, min: 0, max: 1, default: 1 },
{ name: "exaggeration", type: "float" as const, min: 0, max: 2, default: 0.8 },
{ name: "guidance_scale", type: "float" as const, min: 0, max: 5, default: 0.3 },
{ name: "x_vector_only_mode", type: "bool" as const, default: true },
];
assert.equal(indexTts2EmotionLogic.initial(specs).alpha, 1);
assert.deepEqual(chatterboxExpressivenessLogic.initial(specs), {
exaggeration: 0.8,
guidance: 0.3,
});
assert.deepEqual(qwen3TimbreLogic.initial(specs), { timbreOnly: true });
// Without a declared default each keeps its old starting point.
assert.equal(indexTts2EmotionLogic.initial([]).alpha, 0.7);
assert.deepEqual(chatterboxExpressivenessLogic.initial([]), {
exaggeration: 0.5,
guidance: 0.5,
});
assert.deepEqual(qwen3TimbreLogic.initial([]), { timbreOnly: false });
// A kept strength still wins over the default.
assert.equal(
panelValue(indexTts2EmotionLogic, { "index-emotion": { alpha: 0.4 } }, specs).alpha,
0.4,
);
});
test("the IndexTTS2 mixer sends eight weights and the strength", () => {
const vector = [0.8, 0, 0, 0, 0, 0, 0.2, 0];
assert.equal(emotionVectorString(vector), "0.8,0,0,0,0,0,0.2,0");
const patch = indexTts2EmotionLogic.toRequest({
...indexTts2EmotionLogic.initial([]),
mode: "mixer",
vector,
alpha: 0.6,
});
assert.deepEqual(patch, {
options: { emotion_vector: "0.8,0,0,0,0,0,0.2,0", emotion_alpha: 0.6 },
});
assert.deepEqual(
indexTts2EmotionLogic.toRequest({
...indexTts2EmotionLogic.initial([]),
mode: "mixer",
}),
{},
);
});
test("IndexTTS2 emotion from text and from audio", () => {
const base = indexTts2EmotionLogic.initial([]);
assert.deepEqual(
indexTts2EmotionLogic.toRequest({ ...base, text: " joyful " }),
{
options: {
use_emotion_text: true,
emotion_text: "joyful",
emotion_alpha: 0.7,
},
},
);
assert.deepEqual(indexTts2EmotionLogic.toRequest(base), {});
const source = { kind: "clip" as const, id: "c1", name: "x", durationS: 2 };
assert.deepEqual(
indexTts2EmotionLogic.toRequest({ ...base, mode: "audio", source }),
{
inputs: { emotion: { clip_id: "c1" } },
options: { emotion_alpha: 0.7 },
},
);
assert.equal(
indexTts2EmotionLogic.validate?.(
{ ...base, mode: "audio" },
{ text: "" },
ctx(),
),
EMOTION_AUDIO_MISSING,
);
for (const status of [
{ phase: "uploading" as const, name: "y", progress: 0.5 },
{ phase: "error" as const, message: "Upload failed." },
{ phase: "expired" as const },
]) {
const sourceProblem = emotionSourceProblem(status);
assert.ok(sourceProblem);
assert.equal(
indexTts2EmotionLogic.validate?.({ ...base, mode: "audio", source, sourceProblem }, { text: "" }, ctx()),
sourceProblem,
);
}
assert.equal(emotionSourceProblem({ phase: "ready" }), null);
});
test("Qwen3 Timbre only sends x_vector_only_mode and drops the transcript requirement", () => {
const required = ctx({
audioFamily: "qwen3_tts",
referenceTextMode: "required",
});
const on = qwen3TimbreLogic.toRequest({ timbreOnly: true });
assert.deepEqual(on.options, { x_vector_only_mode: true });
assert.equal(referenceTextField(required, on), "hidden");
assert.equal(
referenceTextField(
required,
qwen3TimbreLogic.toRequest({ timbreOnly: false }),
),
"required",
);
const blocked = cloneBlocker({
reference: { kind: "input", id: "i", name: "a.wav", durationS: 4 },
referenceBusy: false,
referenceExpired: false,
referenceError: null,
referenceText: "",
referenceTextField: referenceTextField(required, on),
text: "Hello",
panelError: null,
});
assert.equal(blocked, null);
const failed = cloneBlocker({
reference: { kind: "input", id: "i", name: "a.wav", durationS: 4 },
referenceBusy: false,
referenceExpired: false,
referenceError: "Upload failed.",
referenceText: "",
referenceTextField: referenceTextField(required, on),
text: "Hello",
panelError: null,
});
assert.equal(failed?.kind, "reference-error");
});
test("CosyVoice3 Cross-lingual needs no transcript; Instruct needs its instruction", () => {
const required = ctx({
audioFamily: "cosyvoice3",
referenceTextMode: "required",
});
const cross = cosyVoiceModeLogic.toRequest({
mode: "cross_lingual",
instruction: "",
});
assert.deepEqual(cross.options, { template_name: "cross_lingual" });
assert.equal(referenceTextField(required, cross), "hidden");
const same = cosyVoiceModeLogic.toRequest({
mode: "zero_shot",
instruction: "",
});
assert.equal(referenceTextField(required, same), "required");
assert.equal(
cosyVoiceModeLogic.validate?.(
{ mode: "instruct", instruction: " " },
{ text: "" },
required,
),
COSYVOICE_INSTRUCTION_MISSING,
);
assert.deepEqual(
cosyVoiceModeLogic.toRequest({ mode: "instruct", instruction: "Calm." }),
{
options: { template_name: "instruct" },
instructions: "Calm.",
referenceTextMode: "optional",
},
);
});
test("Chatterbox and F5 send their options, F5 speed top-level", () => {
assert.deepEqual(
chatterboxExpressivenessLogic.toRequest({ exaggeration: 3, guidance: 0.4 }),
{
options: { exaggeration: 2, guidance_scale: 0.4 },
},
);
assert.deepEqual(
f5SpeedDialectLogic.toRequest({ speed: 1, dialect: "UNK" }),
{},
);
assert.deepEqual(
f5SpeedDialectLogic.toRequest({ speed: 1.3, dialect: "EGY" }),
{
speed: 1.3,
options: { dialect: "EGY" },
},
);
});
test("Maya1's required voice description reaches the tool context", () => {
const maya = audioModelContextFor(
{
audio_type: "audiocpp_tts",
audio_family: "maya1",
audio_required_inputs: ["instruct"],
},
{
musicGeneration: false,
cudaMusicGeneration: false,
musicNeedsDescription: false,
},
);
assert.deepEqual(maya.requiredInputs, ["instruct"]);
});
test("a saved voice on Speak becomes the run's reference", () => {
const speak = ctx({ audioWorkflows: ["speak", "clone"], voiceOption: "voice" });
const request = (source: "saved" | "builtin", c = speak) =>
speakVoiceLogic.toRequest(
{ source, voiceId: "v1", builtin: source === "saved" ? "af_bella" : null },
c,
);
assert.deepEqual(request("saved"), {
inputs: { reference: { voice_id: "v1" } },
});
assert.deepEqual(request("builtin"), {});
assert.deepEqual(request("saved", ctx({ audioWorkflows: ["speak"] })), {});
assert.equal(
speakVoiceLogic.validate?.(
{ source: "saved", voiceId: null, builtin: null },
{ text: "" },
ctx(),
),
SAVED_VOICE_MISSING,
);
});
test("a saved voice deleted on Clone holds Speak's Generate", () => {
const saved = { source: "saved" as const, voiceId: "v1", builtin: null };
const check = (savedVoiceIds: readonly string[] | null) =>
speakVoiceLogic.validate?.(saved, { text: "hi" }, ctx({ savedVoiceIds }));
assert.equal(check(["v2"]), SAVED_VOICE_DELETED);
assert.equal(check(["v1", "v2"]), null);
assert.equal(check(null), null);
});
test("the built-in voice goes under the model's own option name", () => {
const builtin = { source: "builtin" as const, voiceId: null, builtin: "x" };
// Magpie and NeuTTS keep voice_id: top-level voice breaks them on audio.cpp v0.9.1.
for (const name of ["voice", "voice_id", "speaker", null]) {
assert.deepEqual(
speakVoiceLogic.toRequest(builtin, ctx({ voiceOption: name })),
name ? { options: { [name]: "x" } } : {},
);
}
assert.deepEqual([...speakVoiceLogic.claims], ["voice", "voice_id", "speaker"]);
const spec = (name: string, type: "enum" | "string" = "enum") =>
({ name, type, values: ["a"] }) as const;
assert.equal(voiceOptionName([spec("speaker"), spec("voice")]), "voice");
assert.equal(
voiceOptionName([spec("voice", "string"), spec("voice_id")]),
"voice_id",
);
assert.equal(voiceOptionName([spec("voice", "string")]), "voice");
assert.equal(voiceOptionName([spec("speaker_id")]), null);
});
test("a saved voice without a transcript holds Speak only when the model needs one", () => {
const check = (referenceTextMode: "required" | "optional", voiceId = "v1") =>
speakVoiceLogic.validate?.(
{ source: "saved", voiceId, builtin: null },
{ text: "hi" },
ctx({ referenceTextMode, voicesWithoutTranscript: ["v1"] }),
);
assert.equal(check("required"), SAVED_VOICE_NO_TRANSCRIPT);
assert.equal(check("optional"), null);
assert.equal(check("required", "v2"), null);
});
test("formatVibeVoiceScript prefixes plain text only", () => {
assert.equal(
formatVibeVoiceScript("Hello there."),
"Speaker 1: Hello there.",
);
assert.equal(
formatVibeVoiceScript("Speaker 2: Hi\nSpeaker 1: Yo"),
"Speaker 2: Hi\nSpeaker 1: Yo",
);
assert.equal(formatVibeVoiceScript(" speaker 3 : hey"), "speaker 3 : hey");
assert.equal(formatVibeVoiceScript(" "), "");
});
test("the status context reads the clone fields defensively", () => {
const page = {
musicGeneration: false,
cudaMusicGeneration: false,
musicNeedsDescription: false,
};
const none = audioModelContextFor(null, page);
assert.deepEqual(none.audioWorkflows, []);
assert.equal(none.referenceTextMode, null);
assert.equal(none.cloneDescription, false);
const cloneDescription = (audio_clone: unknown) =>
audioModelContextFor({ audio_clone }, page).cloneDescription;
assert.equal(
cloneDescription({ reference_text: "required", description: true }),
true,
);
assert.equal(cloneDescription({ description: "yes" }), false);
assert.equal(cloneDescription({ description: false }), false);
assert.equal(cloneDescription({}), false);
assert.equal(cloneDescription(null), false);
assert.equal(cloneDescription(true), false);
assert.equal(cloneDescription([{ description: true }]), false);
assert.equal(audioModelContextFor({}, page).cloneDescription, false);
assert.equal(
audioModelContextFor({ audio_reference_text: "bogus" }, page)
.referenceTextMode,
null,
);
assert.equal(
audioModelContextFor({ audio_reference_text: "unused" }, page)
.referenceTextMode,
"unused",
);
assert.equal(
referenceTextField({ referenceTextMode: "unused" }, {}),
"hidden",
);
assert.equal(referenceTextField({ referenceTextMode: null }, {}), "optional");
});
test("Clone's blockers come in rail order", () => {
const base = {
reference: null,
referenceBusy: false,
referenceExpired: false,
referenceError: null,
referenceText: "",
referenceTextField: "required" as const,
text: "",
panelError: "panel says no",
};
assert.equal(cloneBlocker(base)?.kind, "reference");
assert.equal(
cloneBlocker({ ...base, referenceExpired: true })?.reason,
"This reference expired.",
);
const reference = {
kind: "input" as const,
id: "i",
name: "a",
durationS: 3,
};
assert.equal(cloneBlocker({ ...base, reference })?.kind, "reference-text");
assert.equal(
cloneBlocker({ ...base, reference, referenceText: "hi" })?.kind,
"text",
);
assert.equal(
cloneBlocker({ ...base, reference, referenceText: "hi", text: "go" })?.kind,
"panel",
);
assert.equal(
cloneBlocker({
...base,
reference,
referenceText: "hi",
text: "go",
panelError: null,
}),
null,
);
});
test("panel labels are plain words, never option names", () => {
const panels = readSrc("features/audio/tools/clone-panels.tsx");
for (const label of [
"Timbre only",
"Emotion",
"Strength",
"Expressiveness",
"Same language",
"Cross-lingual",
"Instruct",
]) {
assert.ok(panels.includes(label), label);
}
assert.doesNotMatch(
panels,
/>\s*(x_vector_only_mode|emotion_alpha|guidance_scale|template_name)\s*</,
);
});
test("deleting the selected saved voice clears Speak's pick", () => {
const picker = readSrc("features/audio/components/voice-picker.tsx");
assert.match(picker, /if \(voice\.id === selectedId\) onDeselect\?\.\(\);/);
const speak = readSrc("features/audio/tools/speak-panels.tsx");
assert.match(
speak,
/onDeselect=\{\(\) => onChange\(\{ \.\.\.value, voiceId: null \}\)\}/,
);
});
test("reference transcription sends no language hint", () => {
const hook = readSrc("features/audio/hooks/use-reference-transcribe.ts");
assert.doesNotMatch(hook, /\blanguage\s*[:,}]/);
});
test("a run whose clips carry no output role still selects its first clip, except an edit", () => {
const clone = readSrc("features/audio/hooks/use-clone-generation.ts");
const body = clone.slice(clone.indexOf("export async function showRunResult("));
assert.match(
body,
/response\.clips\.find\(\(item\) => item\.role === "output"\) \?\?\s*\(workflow === "edit" \? undefined : response\.clips\[0\]\)/,
);
});
test("a run's inline fallback clip stays on the page that started it", () => {
const clone = readSrc("features/audio/hooks/use-clone-generation.ts");
const body = clone.slice(clone.indexOf("export async function showRunResult("));
assert.doesNotMatch(body.slice(0, body.indexOf("\n}\n")), /workflow: "clone"/);
assert.match(readSrc("features/audio/hooks/use-speech-generation.ts"), /showRunResult\(\{[^}]*workflow: "speak"/);
});
test("transcribing the reference holds the page busy until it ends", () => {
const hook = readSrc("features/audio/hooks/use-clone-generation.ts");
const body = hook.slice(hook.indexOf("const transcribeReference = useCallback("));
assert.match(body, /if \(!source \|\| busyRef\.current\) return;\s*busyRef\.current = "transcribing";\s*setBusy\("transcribing"\);/);
assert.match(body, /finally \{\s*if \(busyRef\.current === "transcribing"\) \{\s*busyRef\.current = null;\s*setBusy\(null\);/);
assert.match(body, /transcribe: transcribeReference/);
});
test("a voice chosen in Advanced before the picker carries into the picker", () => {
const send = (stored: unknown, saved: Record<string, unknown>, name: string) =>
speakVoiceLogic.toRequest(
panelValue(
speakVoiceLogic,
{ [speakVoiceLogic.id]: speakVoiceStored(stored, saved, name) },
[],
),
ctx({ voiceOption: name }),
);
// Kokoro's am_adam and Magpie's Jason were kept in Advanced, which the picker now claims.
assert.deepEqual(send(undefined, { voice: "am_adam" }, "voice"), {
options: { voice: "am_adam" },
});
assert.deepEqual(
send({ source: "builtin", voiceId: null }, { speaker: "Jason" }, "speaker"),
{ options: { speaker: "Jason" } },
);
// A choice made in the picker wins, including going back to the default.
const picked = { source: "builtin", voiceId: null, builtin: null };
assert.deepEqual(send(picked, { voice: "am_adam" }, "voice"), {});
assert.deepEqual(send(undefined, {}, "voice"), {});
assert.match(
readSrc("features/audio/hooks/use-speech-generation.ts"),
/speakVoiceStored\(stored, audioOptionValues, toolContext\.voiceOption\)/,
);
});