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
Studio: add the Clone page, audio inputs and saved voices (#12602)
Etherl846989dae8f0
diff --git a/studio/backend/core/inference/audio_cpp_backend.py b/studio/backend/core/inference/audio_cpp_backend.pyindex ac8a7eb6df4..19e801bcd9d 100644--- a/studio/backend/core/inference/audio_cpp_backend.py+++ b/studio/backend/core/inference/audio_cpp_backend.py@@ -19,14 +19,19 @@ from __future__ import annotationsimport base64import ioimport json+import reimport threadingimport wave+from dataclasses import replacefrom typing import Any, Optional, Tuplefrom core.inference import audio_cpp_filesfrom core.inference.audio_cpp_models import (AudioCppModel,AudioCppModelError,+ CloneSpec,+ forget,+ option_matches,require_runnable,resolve,validate_options,@@ -75,15 +80,80 @@ def _music_seconds(max_new_tokens: Optional[int]) -> float:return max(5.0, min(_MAX_MUSIC_SECONDS, frames / 25.0))+# Qwen3-TTS answers "unsupported language: en"; it wants the language's English name.+_LANGUAGE_NAMES = {+ "zh": "Chinese",+ "en": "English",+ "ja": "Japanese",+ "ko": "Korean",+ "de": "German",+ "fr": "French",+ "ru": "Russian",+ "pt": "Portuguese",+ "es": "Spanish",+ "it": "Italian",+}+_SPEAKER_LINE_RE = re.compile(r"^\s*Speaker\s*\d+\s*:", re.IGNORECASE | re.MULTILINE)+# F5's usable speed range.+_MIN_SPEED, _MAX_SPEED = 0.5, 2.0++def model_info_fields(model: AudioCppModel) -> dict[str, Any]:"""What status reports for a loaded audio.cpp model, beyond the common audio fields."""return {"audio_family": model.family,"audio_options": [dict(option) for option in model.options],"gguf_variant": model.variant.key,+ "audio_workflows": list(model.workflows),+ "audio_reference_text": model.clone.reference_text if model.clone else None,+ "audio_required_inputs": list(model.required_inputs),+ "audio_clone": clone_rules(model),+ }+++def clone_rules(model: AudioCppModel) -> Optional[dict[str, Any]]:+ clone = model.clone+ if clone is None:+ return None+ return {+ "reference_text": clone.reference_text,+ "reference_text_waived": [+ [name, list(values)] for name, values in clone.reference_text_waived+ ],+ "emotion_audio": clone.emotion_audio,}+def language_name(language: Optional[str]) -> Optional[str]:+ """``en`` -> ``English``; None for Auto or an unknown code."""+ text = str(language or "").strip()+ if not text or text.lower() == "auto":+ return None+ code = text.lower().replace("_", "-").split("-", 1)[0]+ if code in _LANGUAGE_NAMES:+ return _LANGUAGE_NAMES[code]+ for name in _LANGUAGE_NAMES.values():+ if name.lower() == text.lower():+ return name+ logger.info("audio.cpp: no language name for %r; sending Auto", text)+ return None+++def speech_input(model: AudioCppModel, text: str) -> str:+ """VibeVoice refuses a script with no ``Speaker N:`` line."""+ if model.family == "vibevoice" and not _SPEAKER_LINE_RE.search(text or ""):+ return f"Speaker 1: {text}"+ return text+++def _option_string(value: Any) -> str:+ if isinstance(value, bool):+ return "true" if value else "false"+ if isinstance(value, float) and value.is_integer():+ return str(int(value)) if abs(value) < 1e15 else repr(value)+ return str(value)++class AudioCppBackend:"""One-model backend proxying to an ``audiocpp_server`` child."""@@ -166,9 +236,17 @@ class AudioCppBackend:self.loading_models.discard(model_name)def _ensure_downloaded(self, model: AudioCppModel, hf_token: Optional[str]) -> None:+ self._download_missing(model, hf_token)+ for companion in model.companions:+ companion_model = _resolve_companion(model, companion, hf_token, network = True)+ if self._download_missing(companion_model, hf_token):+ forget(companion.id)++ @staticmethod+ def _download_missing(model: AudioCppModel, hf_token: Optional[str]) -> bool:missing = audio_cpp_files.missing_files(model)if not missing:- return+ return Falsefrom huggingface_hub import hf_hub_downloadfrom utils.hf_cache_settings import active_hf_hub_cache@@ -182,6 +260,7 @@ class AudioCppBackend:token = hf_token or None,cache_dir = cache_dir,)+ return Truedef _start_server(self,@@ -191,9 +270,10 @@ class AudioCppBackend:with self._server_lock:self._stop_server_locked()model_path = audio_cpp_files.materialize(model)+ served = _with_companions(model)try:self._server = AudioCppServer.start(- model, model_path, force_cpu = self._force_cpu, cancel_event = cancel_event+ served, model_path, force_cpu = self._force_cpu, cancel_event = cancel_event)except AudioCppStartCancelledError as exc:_raise_if_cancelled(cancel_event)@@ -230,6 +310,10 @@ class AudioCppBackend:language: Optional[str] = None,seed: Optional[int] = None,audio_options: Optional[dict] = None,+ workflow: Optional[str] = None,+ audio_inputs: Optional[dict] = None,+ reference_text: Optional[str] = None,+ speed: Optional[float] = None,) -> Tuple[bytes, int]:del top_k, min_p, repetition_penalty, use_adapterif not self.active_model_name or self.active_model_name not in self.models:@@ -238,10 +322,27 @@ class AudioCppBackend:if model is None:raise RuntimeError("No active audio model")_raise_if_cancelled(cancel_event)- options = validate_options(model.options, audio_options)+ cloning = workflow == "clone" or bool(audio_inputs)+ if cloning and model.clone is None:+ raise RuntimeError(f"{model.display_name} cannot clone a voice.")+ options = validate_options(model.clone_options if cloning else model.options, audio_options)server = self._running_server(model, cancel_event)try:- if model.task == "music":+ if cloning:+ wav = self._generate_clone(+ server,+ model,+ text,+ audio_inputs or {},+ reference_text = reference_text,+ instructions = instructions,+ language = language,+ speed = speed,+ seed = seed,+ options = options,+ cancel_event = cancel_event,+ )+ elif model.task == "music":wav = self._generate_music(server, model, text, instructions, max_new_tokens, seed, options, cancel_event)@@ -291,7 +392,11 @@ class AudioCppBackend:) -> bytes:defaults = dict(model.request_defaults)default_options = dict(defaults.pop("options", None) or {})- body: dict[str, Any] = {"model": server.model_id, "input": text, **defaults}+ body: dict[str, Any] = {+ "model": server.model_id,+ "input": speech_input(model, text),+ **defaults,+ }# Family defaults win: Studio's generic temperature can stop one emitting its stop token (MOSS-TTS-Nano).del temperature, top_pchosen = dict(options)@@ -342,6 +447,75 @@ class AudioCppBackend:)return data+ @staticmethod+ def _generate_clone(+ server: AudioCppServer,+ model: AudioCppModel,+ text: str,+ audio_inputs: dict,+ *,+ reference_text: Optional[str],+ instructions: Optional[str],+ language: Optional[str],+ speed: Optional[float],+ seed: Optional[int],+ options: dict,+ cancel_event,+ ) -> bytes:+ """Speak ``text`` in the voice of ``audio_inputs["reference"]`` (a server-local WAV path).++ An emotion clip has no field on the speech endpoint, so that request goes to /v1/tasks/run+ with the clip as top-level ``audio``."""+ clone = model.clone or CloneSpec()+ reference = audio_inputs.get("reference")+ if not reference:+ raise RuntimeError(f"{model.display_name} needs a reference clip to clone.")+ emotion = audio_inputs.get("emotion") if clone.emotion_audio else None+ request_options = {name: _option_string(value) for name, value in options.items()}+ body: dict[str, Any] = {"model": server.model_id}+ spoken = speech_input(model, text)+ if emotion:+ body["text"] = spoken+ else:+ body["input"] = spoken+ body["voice_ref"] = str(reference)+ if emotion:+ body["audio"] = str(emotion)+ transcript = str(reference_text or "").strip()+ if (+ transcript+ and clone.reference_text != "unused"+ and not option_matches(clone.reference_text_dropped, options)+ ):+ body["reference_text"] = transcript+ if language and str(language).strip():+ chosen = language_name(language) if clone.language_names else str(language).strip()+ if chosen:+ body["language"] = chosen+ if clone.speed and speed is not None:+ body["speed"] = max(_MIN_SPEED, min(_MAX_SPEED, float(speed)))+ if clone.instructions and instructions and str(instructions).strip():+ body["instructions"] = str(instructions).strip()+ if request_options:+ body["options"] = request_options+ if seed is not None:+ body["seed"] = str(int(seed))+ if emotion:+ ctype, data = server.post_json(+ "/v1/tasks/run",+ body,+ timeout = _GENERATE_TIMEOUT_SECONDS,+ cancel_event = cancel_event,+ )+ return _audio_from_task_response(ctype, data)+ _ctype, data = server.post_json(+ "/v1/audio/speech",+ body,+ timeout = _GENERATE_TIMEOUT_SECONDS,+ cancel_event = cancel_event,+ )+ return data+@staticmethoddef _generate_music(server: AudioCppServer,@@ -417,6 +591,31 @@ class AudioCppBackend:del caller_cancel_event+def _resolve_companion(+ model: AudioCppModel,+ companion,+ hf_token: Optional[str] = None,+ *,+ network: bool = True,+) -> AudioCppModel:+ found = resolve(companion.id, companion.variant, hf_token, network = network)+ if found is None:+ name = companion.id.rsplit("/", 1)[-1]+ raise RuntimeError(f"{model.display_name} needs {name}, which Studio could not find.")+ return found+++def _with_companions(model: AudioCppModel) -> AudioCppModel:+ """``model`` with each companion's served path in its session options (MioTTS's codec)."""+ if not model.companions:+ return model+ session = dict((model.model_options or {}).get("session_options") or {})+ for companion in model.companions:+ companion_model = _resolve_companion(model, companion, network = False)+ session[companion.session_option] = audio_cpp_files.materialize(companion_model)+ return replace(model, model_options = {**model.model_options, "session_options": session})++def _audio_from_task_response(content_type: str, data: bytes) -> bytes:"""WAV bytes from ``/v1/tasks/run``: raw audio, or JSON carrying base64 audio."""if content_type.startswith("audio/") or data[:4] == b"RIFF":diff --git a/studio/backend/core/inference/audio_cpp_models.py b/studio/backend/core/inference/audio_cpp_models.pyindex 5f6e2555d95..de5b28e36d5 100644--- a/studio/backend/core/inference/audio_cpp_models.py+++ b/studio/backend/core/inference/audio_cpp_models.py@@ -30,7 +30,7 @@ import reimport structimport threadingimport time-from dataclasses import dataclass, field+from dataclasses import dataclass, field, replacefrom pathlib import Pathfrom typing import Any, BinaryIO, Iterable, Optional, Sequence@@ -66,6 +66,86 @@ class AudioCppPackageVariant:session_options: dict = field(default_factory = dict, hash = False, compare = False)+@dataclass(frozen = True)+class WorkflowBinding:+ """How a Studio audio workflow reaches audiocpp_server: the task token, the endpoint and the+ request fields the workflow sends."""++ server_task: str+ # ``speech`` (/v1/audio/speech), ``tasks`` (/v1/tasks/run) or ``transcriptions``+ # (/v1/audio/transcriptions).+ endpoint: str+ route: Optional[str] = None+ inputs: tuple[str, ...] = ()+++@dataclass(frozen = True)+class CloneSpec:+ """How a family clones a voice from a reference clip (``voice_ref``) on the speech endpoint."""++ # Transcript of the clip: ``required``, ``optional`` or ``unused``.+ reference_text: str = "optional"+ # Options the runtime spec omits but the family reads; validated like spec options.+ tool_options: tuple[dict, ...] = field(default = (), hash = False)+ # ``(option, values)`` under which a required transcript is not needed; under ``dropped`` (a+ # subset) a given one is not even sent.+ reference_text_waived: tuple[tuple[str, tuple[str, ...]], ...] = ()+ reference_text_dropped: tuple[tuple[str, tuple[str, ...]], ...] = ()+ emotion_audio: bool = False+ language_names: bool = False+ speed: bool = False+ instructions: bool = False+++@dataclass(frozen = True)+class CompanionModel:+ """A second model a family loads beside its own (MioTTS's MioCodec), by session option."""++ id: str+ variant: str+ session_option: str+++_CLONE_INPUTS = ("text", "reference", "reference_text", "language")+++def option_matches(pairs: Iterable[tuple[str, Iterable[str]]], options: Optional[dict]) -> bool:+ """Whether ``options`` sets any ``(option, values)`` pair, bools read as ``true``/``false``."""+ options = options or {}+ for name, values in pairs:+ if name in options:+ value = options[name]+ text = ("true" if value else "false") if isinstance(value, bool) else str(value)+ if text.strip().lower() in values:+ return True+ return False+++def _bindings_for(+ task: str,+ server_task: Optional[str],+ family: Any = None,+) -> dict[str, WorkflowBinding]:+ """The workflows a Studio task offers, keyed by workflow id; empty when Studio has none."""+ if task == "tts":+ bindings: dict[str, WorkflowBinding] = {}+ if getattr(family, "speaks", True):+ bindings["speak"] = WorkflowBinding(+ server_task or "tts", "speech", None, ("text", "instruct", "language", "voice")+ )+ clone = getattr(family, "clone", None)+ if clone is not None:+ bindings["clone"] = WorkflowBinding(server_task or "tts", "speech", None, _CLONE_INPUTS)+ return bindings+ if task == "music":+ return {+ "music": WorkflowBinding("gen", "tasks", None, ("text", "lyrics", "duration_seconds"))+ }+ if task == "asr":+ return {"transcribe": WorkflowBinding("asr", "transcriptions", None, ("audio",))}+ return {}++@dataclass(frozen = True)class AudioCppFamily:family: str@@ -88,6 +168,9 @@ class AudioCppFamily:voices: tuple[str, ...] = ()# Why Studio refuses this family, when it does.unsupported: Optional[str] = None+ speaks: bool = True+ clone: Optional[CloneSpec] = None+ companions: tuple[CompanionModel, ...] = ()@propertydef default_server_task(self) -> str:@@ -95,6 +178,10 @@ class AudioCppFamily:return self.server_taskreturn "gen" if self.task == "music" else self.task+ @property+ def workflows(self) -> dict[str, WorkflowBinding]:+ return _bindings_for(self.task, self.default_server_task, self)+def _minimax_package(key: str, lm: str, rvq: str, flow: str) -> AudioCppPackageVariant:files = (@@ -143,6 +230,128 @@ def _opt(name: str, type_: str, description: str, **kw) -> dict:return {"name": name, "type": type_, "description": description, **kw}+def _tool(name: str, type_: str, description: str, **kw) -> dict:+ """A clone tool option in ``_clean_option``'s shape."""+ return {+ "name": name,+ "type": type_,+ "description": description,+ "required": False,+ "default": kw.get("default"),+ "min": kw.get("min"),+ "max": kw.get("max"),+ "values": kw.get("values"),+ }+++MIOCODEC_FOLDER = "MioCodec-25Hz-44.1kHz-v2-GGUF"++_QWEN3_BASE = AudioCppFamily(+ "qwen3_tts",+ "tts",+ speaks = False,+ clone = CloneSpec(+ "required",+ tool_options = (+ _tool(+ "x_vector_only_mode",+ "bool",+ "Clone the timbre only; the clip's transcript is not needed.",+ default = False,+ ),+ ),+ reference_text_waived = (("x_vector_only_mode", ("true",)),),+ reference_text_dropped = (("x_vector_only_mode", ("true",)),),+ language_names = True,+ ),+)+_CLONE_FAMILIES: tuple[AudioCppFamily, ...] = (+ # Loads only as a cloning session: "Chatterbox supports VoiceCloning and VoiceConversion".+ # Chatterbox-Turbo is its own family and still speaks.+ AudioCppFamily(+ "chatterbox",+ "tts",+ server_task = "clon",+ speaks = False,+ clone = CloneSpec(+ "unused",+ tool_options = (+ _tool(+ "exaggeration", "float", "Emotion exaggeration.", min = 0.0, max = 2.0, default = 0.5+ ),+ _tool(+ "guidance_scale",+ "float",+ "Classifier-free guidance.",+ min = 0.0,+ max = 5.0,+ default = 0.5,+ ),+ ),+ ),+ ),+ AudioCppFamily("f5_tts", "tts", speaks = False, clone = CloneSpec("required", speed = True)),+ AudioCppFamily(+ "index_tts2",+ "tts",+ speaks = False,+ clone = CloneSpec(+ "unused",+ tool_options = (+ _tool(+ "emotion_vector",+ "string",+ "Eight comma-separated weights: happy, angry, sad, afraid, disgusted, "+ "melancholic, surprised, calm.",+ ),+ _tool("emotion_alpha", "float", "Emotion strength.", min = 0.0, max = 1.0, default = 1.0),+ _tool(+ "use_emotion_text", "bool", "Take the emotion from emotion_text.", default = False+ ),+ _tool("emotion_text", "string", "A description of the emotion."),+ ),+ emotion_audio = True,+ ),+ ),+ AudioCppFamily(+ "cosyvoice3",+ "tts",+ speaks = False,+ clone = CloneSpec(+ "required",+ # Required for the default zero_shot template only.+ reference_text_waived = (("template_name", ("cross_lingual", "instruct")),),+ reference_text_dropped = (("template_name", ("cross_lingual",)),),+ instructions = True,+ ),+ ),+ AudioCppFamily("voxcpm2", "tts", clone = CloneSpec("optional")),+ AudioCppFamily("fish_audio", "tts", clone = CloneSpec("required")),+ AudioCppFamily("echo_tts", "tts", server_task = "clon", speaks = False, clone = CloneSpec("unused")),+ AudioCppFamily(+ "confucius4_tts", "tts", server_task = "clon", speaks = False, clone = CloneSpec("unused")+ ),+ # Instruct under tts defaults to instruct_tts, which needs reference audio.+ AudioCppFamily("fireredtts3", "tts", speaks = False, clone = CloneSpec("optional")),+ # "FireRedAce": under tts it defaults to tts_clone, which needs reference audio.+ AudioCppFamily("firered_audio", "tts", speaks = False, clone = CloneSpec("optional")),+ # Vevo2 reads a sent transcript as text to speak, so it never gets one.+ AudioCppFamily("vevo2", "tts", speaks = False, clone = CloneSpec("unused")),+ # MioCodec's sibling-folder default never matches the umbrella layout: pass it by session option.+ AudioCppFamily(+ "miotts",+ "tts",+ speaks = False,+ clone = CloneSpec("unused"),+ companions = (+ CompanionModel(+ f"{AUDIO_CPP_REPO}/{MIOCODEC_FOLDER}", "Q8_0", "miotts.codec_model_path"+ ),+ ),+ ),+)++_FAMILY_LIST: tuple[AudioCppFamily, ...] = (# Text to speech. Kokoro, KittenTTS, Piper and Inflect phonemize with eSpeak-ng, which the Unsloth# bundles link statically (GPL-3.0-or-later) with its data file beside the server.@@ -153,6 +362,7 @@ _FAMILY_LIST: tuple[AudioCppFamily, ...] = (AudioCppFamily("pocket_tts", "tts", request_defaults = {"voice": "alba"}),AudioCppFamily("supertonic", "tts", request_defaults = {"voice": "F1"}),AudioCppFamily("qwen3_tts", "tts"),+ *_CLONE_FAMILIES,*(AudioCppFamily(name, "tts")for name in (@@ -160,29 +370,17 @@ _FAMILY_LIST: tuple[AudioCppFamily, ...] = ("moss_tts_local","moss_tts_v15","moss_ttsd",- "chatterbox","chatterbox_turbo","voxcpm1",- "voxcpm2","neutts","magpie_tts",- "miotts",- "cosyvoice3",- "fish_audio","higgs_audio_tts",- "index_tts2","irodori_tts","breeze_tts","dots_tts","dramabox",- "fireredtts3",- "firered_audio","omnivoice",- "confucius4_tts","vibevoice",- "vevo2",- "echo_tts",- "f5_tts","glm_tts","outetts","sanotts",@@ -324,6 +522,11 @@ _FAMILY_LIST: tuple[AudioCppFamily, ...] = ()for name in ("minimax_h3", "auk", "liveavatar", "vibeasr")),+ AudioCppFamily(+ "miocodec",+ "",+ unsupported = "MioCodec is the codec MioTTS loads with; pick MioTTS to use it.",+ ),# Tasks Studio has no page for.*(AudioCppFamily(name, "", unsupported = f"{what} models are not supported in Studio yet.")@@ -333,7 +536,7 @@ _FAMILY_LIST: tuple[AudioCppFamily, ...] = ((("htdemucs", "bs_roformer", "mel_band_roformer"), "Source separation"),(("pulsevad", "silero_vad", "marblenet_vad"), "Voice activity detection"),(("muscriptor", "sheetsage2"), "Music transcription"),- (("meanvc2", "rvc", "seed_vc", "miocodec"), "Voice conversion"),+ (("meanvc2", "rvc", "seed_vc"), "Voice conversion"),(("apollo", "audiosr", "universr", "personaplex"), "Speech-to-speech"),)for name in names@@ -382,24 +585,25 @@ def _family_from_spec_tasks(tasks = [str(t).lower() for t in (spec or {}).get("tasks") or [] if isinstance(t, str)]tokens = [_SPEC_TO_SERVER_TASK.get(t, t) for t in tasks]# Speech first, then music, then transcription: a model that speaks is most useful spoken.- for token in ("tts", "vdes", "clon", "gen", "asr"):+ # A clone-only family comes last: it loads as a cloning session and offers Clone alone.+ for token in ("tts", "vdes", "gen", "asr", "clon"):if token in tokens:- if token == "clon":- continueif runtime_knows_family(family) is False:return AudioCppFamily(family,"",unsupported = f"{label or family} needs a newer audio runtime than the one installed.",)+ if token == "clon":+ return AudioCppFamily(+ family,+ "tts",+ server_task = "clon",+ speaks = False,+ clone = CloneSpec("optional"),+ )studio = "tts" if token == "vdes" else _SERVER_TO_STUDIO_TASK[token]return AudioCppFamily(family, studio, server_task = token)- if "clon" in tokens:- return AudioCppFamily(- family,- "",- unsupported = "This model only clones a reference voice, which Studio does not send yet.",- )if tokens:what = _TASK_NAMES.get(tokens[0])return AudioCppFamily(@@ -462,11 +666,9 @@ def family_policy(),)if "base" in text:- return AudioCppFamily(- family,- "",- unsupported = "Qwen3-TTS Base only clones a reference voice, which Studio does not send yet.",- )+ return _QWEN3_BASE+ if family == "fireredtts3" and re.search(r"(^|[-_ /])base([-_ ./]|$)", " ".join(names).lower()):+ return replace(policy, server_task = "clon")return policy@@ -1334,6 +1536,10 @@ class AudioCppModel:unsupported: Optional[str] = Nonelocal_path: Optional[str] = Nonetags: tuple[str, ...] = ()+ speaks: bool = True+ clone: Optional[CloneSpec] = None+ companions: tuple[CompanionModel, ...] = ()+ required_inputs: tuple[str, ...] = ()@propertydef is_package(self) -> bool:@@ -1363,6 +1569,18 @@ class AudioCppModel:def hub_task(self) -> Optional[str]:return HUB_TASKS.get(self.task)+ @property+ def workflows(self) -> dict[str, WorkflowBinding]:+ return _bindings_for(self.task, self.server_task, self)++ @property+ def clone_options(self) -> tuple[dict, ...]:+ """Spec options plus the clone tool options the spec omits."""+ if self.clone is None or not self.clone.tool_options:+ return self.options+ names = {o["name"] for o in self.options}+ return (*self.options, *(o for o in self.clone.tool_options if o["name"] not in names))+@propertydef key(self) -> str:"""A short name, unique per model and variant, for the link farm."""@@ -1405,7 +1623,9 @@ _TAG_FAMILY_RE = re.compile(r"^[a-z0-9_]+$")def family_from_names(names: Iterable[str]) -> Optional[str]:text = " ".join(names).lower().replace(".", "")for family in sorted(FAMILIES, key = len, reverse = True):- pattern = re.escape(family).replace(r"\_", "[-_]?")+ # re.escape leaves "_" alone, so the separator is matched loosely here: "Chatterbox-Turbo"+ # is chatterbox_turbo, not chatterbox.+ pattern = re.escape(family).replace("_", "[-_]?")if re.search(pattern, text):return familyhints = (@@ -1664,10 +1884,40 @@ def _resolve_uncached(unsupported = unsupported,local_path = ref.local_path,tags = tuple(tags),+ speaks = policy.speaks,+ clone = policy.clone,+ companions = policy.companions,+ required_inputs = _required_inputs(spec, embedded, policy),)return model.with_variant(chosen)+# Spec options Studio fills from request fields, so a required one is a field the user must give.+_REQUIRED_INPUT_NAMES = ("instruct", "reference_text")+++def _required_inputs(+ spec: Optional[dict],+ embedded: Optional[dict],+ policy: Optional[AudioCppFamily] = None,+) -> tuple[str, ...]:+ """Names in ``_REQUIRED_INPUT_NAMES`` the raw spec marks ``required`` (``_clean_option`` hides+ them), minus those the family's defaults fill."""+ defaulted = set(((policy.request_defaults if policy else {}) or {}).get("options") or {})+ source = spec+ if source is None or not ((source.get("options") or {}).get("request")):+ source = embedded+ raw = ((source or {}).get("options") or {}).get("request") or []+ found = []+ for item in raw:+ if not isinstance(item, dict) or not item.get("required"):+ continue+ name = str(item.get("name") or "").strip()+ if name in _REQUIRED_INPUT_NAMES and name not in found and name not in defaulted:+ found.append(name)+ return tuple(found)++def _size(path: str) -> int:try:return os.stat(path).st_sizediff --git a/studio/backend/core/inference/audio_gallery.py b/studio/backend/core/inference/audio_gallery.pyindex a8831e65c5d..614216c68dd 100644--- a/studio/backend/core/inference/audio_gallery.py+++ b/studio/backend/core/inference/audio_gallery.py@@ -207,7 +207,7 @@ def _record(def _workflow(meta: dict[str, Any]) -> str:workflow = meta.get("workflow")- if workflow in ("speak", "music"):+ if workflow in ("speak", "clone", "music"):return workflowreturn workflow_for_audio_type(meta.get("audio_type"))@@ -430,8 +430,8 @@ def clear(include_archived: bool = False, workflow: Optional[str] = None) -> intorphan WAVs are preserved, since list_audio already hides them.Archived clips are spared unless ``include_archived``, and sparing them raises- FlagsUnavailable when the flag store cannot be read. A ``workflow`` (speak or music) spares- the other workflow's clips."""+ FlagsUnavailable when the flag store cannot be read. A ``workflow`` (speak, clone or music)+ spares the other workflows' clips."""removed = 0directory = gallery_dir()with gallery_flags.exclusive(directory, require_file_lock = not include_archived):diff --git a/studio/backend/core/inference/audio_inputs.py b/studio/backend/core/inference/audio_inputs.pynew file mode 100644index 00000000000..f004844e166--- /dev/null+++ b/studio/backend/core/inference/audio_inputs.py@@ -0,0 +1,512 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Audio the user gives the Audio page, kept for a day under the account's ``<gallery_dir>/inputs``.++Requests name an input, a gallery clip or a saved voice by id only; this module resolves the id+inside the current account, so no client ever names a file."""++from __future__ import annotations++import hashlib+import json+import os+import threading+import time+import uuid+import wave+from dataclasses import dataclass+from pathlib import Path+from typing import Any, AsyncIterable, Optional++from core.inference import audio_gallery+from loggers import get_logger+from utils.account_context import OWNER, AccountContext, is_owner_context, run_as+from utils.paths.storage_roots import account_path+from utils.upload_limits import AUDIO_INPUT_MAX_BYTES++logger = get_logger(__name__)++MAX_SECONDS = 30 * 60+TTL_SECONDS = 24 * 60 * 60+BYTE_CAP = 2 * 1024 * 1024 * 1024+REFERENCE_MAX_SECONDS = 30.0+REFERENCE_RATE = 24000+_MAX_CHANNELS = 2+# Caps the stored rate so a 30 minute upload stays under ~350 MB however it was encoded.+MAX_RATE = 48000+_NAME_MAX = 255+_STALE_TMP_SECONDS = 60 * 60+++class AudioInputError(ValueError):+ """A refusal with the HTTP status and plain reason the route sends."""++ def __init__(self, status: int, detail: str):+ super().__init__(detail)+ self.status = status+ self.detail = detail+++def inputs_dir() -> Path:+ """``<gallery_dir>/inputs``, which ``gallery_dir`` scopes to the account for a non-owner."""+ directory = audio_gallery.gallery_dir() / "inputs"+ directory.mkdir(parents = True, exist_ok = True)+ return directory+++def _valid_id(input_id: Optional[str]) -> bool:+ return bool(input_id) and bool(audio_gallery._ID_RE.match(str(input_id)))+++def _now() -> float:+ return time.time()+++def _iso(epoch: float) -> str:+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(epoch))+++def _clean_name(name: Optional[str]) -> str:+ """The file's own name: no folders, no control characters, bounded."""+ text = str(name or "").replace("\\", "/").rsplit("/", 1)[-1]+ text = "".join(ch for ch in text if ch.isprintable()).strip()+ return text[:_NAME_MAX] or "audio"+++def _sidecar(directory: Path, input_id: str) -> Path:+ return directory / f"{input_id}.json"+++def _read_sidecar(path: Path) -> Optional[dict[str, Any]]:+ try:+ meta = json.loads(path.read_text(encoding = "utf-8"))+ except (OSError, ValueError, UnicodeError):+ return None+ required = ("name", "duration_s", "sample_rate", "channels", "sha256", "created_at")+ if not isinstance(meta, dict) or any(k not in meta for k in required):+ return None+ return meta+++def _touched(meta: dict[str, Any]) -> float:+ try:+ return float(meta.get("touched_at") or meta.get("created_at_epoch") or 0.0)+ except (TypeError, ValueError):+ return 0.0+++def _expired(meta: dict[str, Any], now: Optional[float] = None) -> bool:+ return _touched(meta) + TTL_SECONDS <= (now if now is not None else _now())+++def _record(input_id: str, meta: dict[str, Any]) -> dict[str, Any]:+ return {+ "id": input_id,+ "name": meta["name"],+ "duration_s": meta["duration_s"],+ "sample_rate": meta["sample_rate"],+ "channels": meta["channels"],+ "url": f"/api/inference/audio/inputs/{input_id}/file",+ "expires_at": _iso(_touched(meta) + TTL_SECONDS),+ }+++def _write_json(path: Path, meta: dict[str, Any]) -> None:+ tmp = path.with_name(f".{path.name}.{uuid.uuid4().hex[:8]}.tmp")+ try:+ tmp.write_text(json.dumps(meta), encoding = "utf-8")+ os.replace(tmp, path)+ except BaseException:+ tmp.unlink(missing_ok = True)+ raise+++def _av_open(av, source: str):+ try:+ return av.open(source, mode = "r", metadata_errors = "ignore")+ except TypeError as exc:+ if "metadata_errors" not in str(exc):+ raise+ return av.open(source, mode = "r", format = None)+++def transcode(+ src: Path,+ dst: Path,+ *,+ rate: Optional[int] = None,+ mono: bool = False,+ max_seconds: Optional[float] = None,+ cut: bool = False,+) -> dict[str, Any]:+ """Decode ``src`` into a 16-bit WAV at ``dst``: at ``rate`` (default the source's), mono or at+ most two channels. Past ``max_seconds`` it is cut when ``cut``, else refused with 413.++ Streams frame by frame through FFmpeg's resampler (a voice reference must not alias) into a+ temporary file renamed in at the end."""+ import av++ max_seconds = MAX_SECONDS if max_seconds is None else max_seconds+ tmp = dst.with_name(f".{dst.name}.{uuid.uuid4().hex[:8]}.tmp")+ frames = channels = ceiling = 0+ out = resampler = None++ def write(blocks) -> bool:+ nonlocal frames+ for block in blocks:+ take = min(block.samples, ceiling - frames)+ if take < block.samples and not cut:+ raise AudioInputError(+ 413, f"Audio is longer than {int(max_seconds // 60)} minutes."+ )+ out.writeframes(block.to_ndarray().reshape(-1)[: take * channels].tobytes())+ frames += take+ if cut and frames >= ceiling:+ return True+ return False++ try:+ try:+ container = _av_open(av, str(src))+ except Exception as exc: # noqa: BLE001 - not a container PyAV knows+ raise AudioInputError(400, "This file is not audio Studio can read.") from exc+ with container:+ if not container.streams.audio:+ raise AudioInputError(400, "This file has no audio stream.")+ try:+ for frame in container.decode(container.streams.audio[0]):+ if resampler is None:+ rate = rate or min(int(frame.sample_rate or 0), MAX_RATE)+ if rate <= 0:+ raise AudioInputError(400, "This audio has no sample rate.")+ channels = (+ 1 if mono else max(1, min(_MAX_CHANNELS, len(frame.layout.channels)))+ )+ layout = "stereo" if channels == 2 else "mono"+ resampler = av.AudioResampler(format = "s16", layout = layout, rate = rate)+ ceiling = int(max_seconds * rate)+ out = wave.open(str(tmp), "wb")+ out.setnchannels(channels)+ out.setsampwidth(2)+ out.setframerate(rate)+ if write(resampler.resample(frame)):+ break+ else:+ if resampler is not None:+ write(resampler.resample(None))+ except AudioInputError:+ raise+ except Exception as exc: # noqa: BLE001 - a corrupt stream mid-file keeps what decoded+ if not frames:+ raise AudioInputError(400, "This file is not audio Studio can read.") from exc+ logger.info("audio_inputs: decode stopped early after %d frames: %s", frames, exc)+ if out is not None:+ out.close()+ out = None+ if not frames:+ raise AudioInputError(400, "This file has no audio in it.")+ os.replace(tmp, dst)+ finally:+ if out is not None:+ out.close()+ tmp.unlink(missing_ok = True)+ return {"duration_s": round(frames / rate, 3), "sample_rate": rate, "channels": channels}+++async def save_stream(+ chunks: AsyncIterable[bytes],+ name: Optional[str],+ *,+ max_bytes: Optional[int] = None,+) -> tuple[dict[str, Any], bool]:+ """Stream an upload to disk, then decode it; ``(record, created)``.++ The byte cap is checked as each chunk lands, so an oversize body is refused without being read+ whole. The same audio (sha256) uploaded again within the TTL returns the existing record."""+ import asyncio++ cap = AUDIO_INPUT_MAX_BYTES if max_bytes is None else max_bytes+ directory = inputs_dir()+ tmp = directory / f".{uuid.uuid4().hex}.upload.tmp"+ digest = hashlib.sha256()+ size = 0+ try:+ with open(tmp, "wb") as f:+ async for chunk in chunks:+ if not chunk:+ continue+ size += len(chunk)+ if size > cap:+ raise AudioInputError(413, "Audio is too large.")+ digest.update(chunk)+ f.write(chunk)+ if not size:+ raise AudioInputError(400, "Audio is empty.")+ return await asyncio.to_thread(+ _finish_upload, directory, tmp, digest.hexdigest(), _clean_name(name), size+ )+ finally:+ tmp.unlink(missing_ok = True)+++def _find_by_sha(directory: Path, sha: str) -> Optional[tuple[str, dict[str, Any]]]:+ now = _now()+ for sidecar in directory.glob("*.json"):+ meta = _read_sidecar(sidecar)+ if meta is None or meta.get("sha256") != sha or _expired(meta, now):+ continue+ if (directory / f"{sidecar.stem}.wav").is_file():+ return sidecar.stem, meta+ return None+++def _finish_upload(+ directory: Path, tmp: Path, sha: str, name: str, size: int+) -> tuple[dict[str, Any], bool]:+ existing = _find_by_sha(directory, sha)+ if existing is not None:+ input_id, meta = existing+ meta["touched_at"] = _now()+ _write_json(_sidecar(directory, input_id), meta)+ return _record(input_id, meta), False+ input_id = uuid.uuid4().hex+ wav = directory / f"{input_id}.wav"+ try:+ info = transcode(tmp, wav)+ now = _now()+ meta = {+ "name": name,+ **info,+ "sha256": sha,+ "bytes": size,+ "created_at": _iso(now),+ "created_at_epoch": now,+ "touched_at": now,+ }+ # The sidecar is the record's commit marker, so it lands last.+ _write_json(_sidecar(directory, input_id), meta)+ except BaseException:+ wav.unlink(missing_ok = True)+ raise+ sweep(keep = input_id)+ return _record(input_id, meta), True+++def _has_inputs() -> bool:+ """Whether the acting account has an inputs folder, checked without creating one."""+ if is_owner_context():+ return (audio_gallery.gallery_dir() / "inputs").is_dir()+ return (account_path("audio") / "inputs").is_dir()+++def sweep_all_accounts() -> int:+ """``sweep`` for the owner and every account with inputs; otherwise an account's expired+ inputs would wait on disk for its next upload."""+ from auth.storage import list_accounts++ accounts = [OWNER] + [+ AccountContext(row["account_id"], row["username"], row["role"])+ for row in list_accounts()+ if row["account_id"] != OWNER.account_id and row["role"] != OWNER.role+ ]+ removed = 0+ for account in accounts:+ try:+ removed += run_as(account, lambda: sweep() if _has_inputs() else 0)+ except Exception as exc: # noqa: BLE001 - housekeeping never fails the server+ logger.debug("audio input sweep skipped for an account: %s", exc)+ return removed+++def start_sweeper(interval_seconds: float = 3600.0) -> None:+ """Sweep every account at startup and then hourly, on a daemon thread."""++ def loop() -> None:+ while True:+ try:+ sweep_all_accounts()+ except Exception as exc: # noqa: BLE001 - e.g. the auth database is not ready yet+ logger.debug("audio input sweep failed: %s", exc)+ time.sleep(interval_seconds)++ threading.Thread(target = loop, daemon = True, name = "audio-inputs-sweep").start()+++def _derived(directory: Path, stem: str) -> list[Path]:+ """Prepared copies made from one input (``{id}.24000.mono....wav``)."""+ try:+ return [p for p in directory.glob(f"{stem}.*.wav") if p.name != f"{stem}.wav"]+ except OSError:+ return []+++def _remove(directory: Path, input_id: str) -> bool:+ wav = directory / f"{input_id}.wav"+ existed = wav.is_file()+ for path in (wav, *_derived(directory, input_id)):+ try:+ path.unlink(missing_ok = True)+ except OSError as exc:+ logger.warning("audio_inputs.delete_failed: %s", exc)+ try:+ _sidecar(directory, input_id).unlink(missing_ok = True)+ except OSError:+ pass+ return existed+++def _size(path: Path) -> int:+ try:+ return path.stat().st_size+ except OSError:+ return 0+++def _mtime(path: Path) -> float:+ try:+ return path.stat().st_mtime+ except OSError:+ return 0.0+++def sweep(+ *,+ keep: Optional[str] = None,+ ttl: Optional[float] = None,+ byte_cap: Optional[int] = None,+) -> int:+ """Remove expired inputs, then the oldest beyond the byte cap; prepared copies of clips and+ voices past the TTL; stale partial uploads. ``keep`` (the input just saved) is never removed.+ Best-effort; returns the number of inputs removed."""+ ttl = TTL_SECONDS if ttl is None else ttl+ byte_cap = BYTE_CAP if byte_cap is None else byte_cap+ try:+ directory = inputs_dir()+ now = _now()+ removed = 0+ live: list[tuple[float, str, int]] = []+ for sidecar in directory.glob("*.json"):+ input_id = sidecar.stem+ meta = _read_sidecar(sidecar)+ if meta is None:+ continue+ if input_id != keep and _touched(meta) + ttl <= now:+ removed += _remove(directory, input_id)+ continue+ size = _size(directory / f"{input_id}.wav") + sum(+ _size(p) for p in _derived(directory, input_id)+ )+ live.append((_touched(meta), input_id, size))+ live.sort(reverse = True)+ running = 0+ for index, (_touched_at, input_id, size) in enumerate(live):+ # Only kept inputs count toward the cap, so one eviction does not doom every older one.+ if running + size > byte_cap and index > 0 and input_id != keep:+ removed += _remove(directory, input_id)+ continue+ running += size+ for path in directory.iterdir():+ name = path.name+ age = now - _mtime(path)+ if name.startswith(".") and name.endswith(".tmp") and age > _STALE_TMP_SECONDS:+ path.unlink(missing_ok = True)+ elif name.startswith(("c-", "v-")) and name.endswith(".wav") and age > ttl:+ path.unlink(missing_ok = True)+ return removed+ except Exception as exc: # noqa: BLE001 - housekeeping never fails a request+ logger.warning("audio_inputs.sweep_failed: %s", exc)+ return 0+++def input_path(input_id: str) -> Optional[Path]:+ """The canonical WAV of a live input in this account, else None."""+ if not _valid_id(input_id):+ return None+ directory = inputs_dir()+ meta = _read_sidecar(_sidecar(directory, input_id))+ if meta is None or _expired(meta):+ return None+ path = directory / f"{input_id}.wav"+ try:+ path.resolve().relative_to(directory.resolve())+ except (OSError, ValueError):+ return None+ return path if path.is_file() else None+++def delete(input_id: str) -> bool:+ if not _valid_id(input_id):+ return False+ directory = inputs_dir()+ if _read_sidecar(_sidecar(directory, input_id)) is None:+ return False+ return _remove(directory, input_id)+++@dataclass(frozen = True)+class Source:+ kind: str # "input" | "clip" | "voice"+ id: str+ path: Path+ name: str+++def resolve_source(ref: dict[str, Any]) -> Source:+ """The canonical file behind ``{"input_id"|"clip_id"|"voice_id": id}`` in this account.++ 404 for an id that is unknown, expired, unsafe or another account's."""+ kinds = [k for k in ("input_id", "clip_id", "voice_id") if ref.get(k)]+ if len(kinds) != 1:+ raise AudioInputError(400, "Name exactly one of input_id, clip_id or voice_id.")+ key = kinds[0]+ source_id = str(ref[key])+ if key == "input_id":+ path = input_path(source_id)+ if path is None:+ raise AudioInputError(404, "This reference expired. Add it again.")+ meta = _read_sidecar(_sidecar(path.parent, source_id)) or {}+ return Source("input", source_id, path, meta.get("name") or "audio")+ if key == "clip_id":+ path = audio_gallery.owned_audio_path(source_id) if _valid_id(source_id) else None+ if path is None:+ raise AudioInputError(404, "That clip is no longer in your history.")+ meta = audio_gallery._read_meta(audio_gallery._sidecar_path(source_id)) or {}+ prompt = " ".join(str(meta.get("prompt") or "").split())+ return Source("clip", source_id, path, (prompt[:60] or "Clip"))+ from core.inference import audio_voices++ path = audio_voices.voice_path(source_id)+ if path is None:+ raise AudioInputError(404, "That saved voice no longer exists.")+ voice = audio_voices.get(source_id) or {}+ return Source("voice", source_id, path, str(voice.get("name") or "Saved voice"))+++def prepared_path(+ source: Source,+ rate: int,+ max_seconds: Optional[float] = None,+) -> Path:+ """A cached mono copy of ``source`` at ``rate``, cut to ``max_seconds``, in this account's inputs.++ An input's copies sit beside it as ``{id}.{rate}.mono[.m{n}].wav`` and go when it goes; a+ clip's or voice's as ``c-``/``v-`` files the sweep removes after the TTL."""+ prefix = {"input": "", "clip": "c-", "voice": "v-"}[source.kind]+ cap = f".m{max_seconds:g}" if max_seconds is not None else ""+ dst = inputs_dir() / f"{prefix}{source.id}.{int(rate)}.mono{cap}.wav"+ if dst.is_file() and _mtime(dst) >= _mtime(source.path):+ if source.kind != "input":+ os.utime(dst)+ return dst+ transcode(source.path, dst, rate = rate, mono = True, max_seconds = max_seconds, cut = True)+ if source.kind != "input":+ # Cloning from history or a saved voice may never upload, so expired copies go here too.+ sweep()+ return dst+++def prepare_reference(ref: dict[str, Any]) -> tuple[Source, Path]:+ """A voice reference ready for the runtime: 24 kHz mono, at most 30 s."""+ source = resolve_source(ref)+ return source, prepared_path(source, REFERENCE_RATE, REFERENCE_MAX_SECONDS)diff --git a/studio/backend/core/inference/audio_voices.py b/studio/backend/core/inference/audio_voices.pynew file mode 100644index 00000000000..6e11f962e4c--- /dev/null+++ b/studio/backend/core/inference/audio_voices.py@@ -0,0 +1,193 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Saved voices: ``{id}.wav`` (24 kHz mono, at most 30 s) plus ``{id}.json`` under the account's+``<gallery_dir>/voices``, kept until deleted. As in the gallery the sidecar is written last and is+what makes a pair a voice, so a lone WAV is never listed, served or deleted."""++from __future__ import annotations++import json+import time+import uuid+from pathlib import Path+from typing import Any, Optional++from core.inference import audio_gallery+from core.inference.audio_inputs import (+ REFERENCE_MAX_SECONDS,+ REFERENCE_RATE,+ AudioInputError,+ _valid_id,+ _write_json,+ inputs_dir,+ transcode,+)+from loggers import get_logger++logger = get_logger(__name__)++MAX_VOICES = 200+NAME_MAX = 80+TRANSCRIPT_MAX = 4000+LANGUAGE_MAX = 64+_REQUIRED = ("name", "duration_s", "sample_rate", "created_at")+++def voices_dir() -> Path:+ directory = audio_gallery.gallery_dir() / "voices"+ directory.mkdir(parents = True, exist_ok = True)+ return directory+++def _sidecar(voice_id: str) -> Path:+ return voices_dir() / f"{voice_id}.json"+++def _read(voice_id: str) -> Optional[dict[str, Any]]:+ if not _valid_id(voice_id):+ return None+ try:+ meta = json.loads(_sidecar(voice_id).read_text(encoding = "utf-8"))+ except (OSError, ValueError, UnicodeError):+ return None+ if not isinstance(meta, dict) or any(k not in meta for k in _REQUIRED):+ return None+ return meta+++def _record(voice_id: str, meta: dict[str, Any]) -> dict[str, Any]:+ return {+ "id": voice_id,+ "name": meta["name"],+ "transcript": meta.get("transcript"),+ "language": meta.get("language"),+ "duration_s": meta["duration_s"],+ "sample_rate": meta["sample_rate"],+ "created_at": meta["created_at"],+ "url": f"/api/inference/audio/voices/{voice_id}/file",+ }+++def _clean_text(value: Optional[str], limit: int) -> Optional[str]:+ if value is None:+ return None+ text = str(value).strip()+ return text[:limit] if text else None+++def _clean_name(value: Optional[str]) -> str:+ text = " ".join(str(value or "").split())[:NAME_MAX]+ if not text:+ raise AudioInputError(400, "Give the voice a name.")+ return text+++def _ids() -> list[str]:+ try:+ return [p.stem for p in voices_dir().glob("*.json") if _read(p.stem) is not None]+ except OSError:+ return []+++def create(src_path: Path, meta: dict[str, Any]) -> dict[str, Any]:+ """Save the first 30 s of ``src_path`` as a voice; 400 past 200 voices."""+ name = _clean_name(meta.get("name"))+ if len(_ids()) >= MAX_VOICES:+ raise AudioInputError(+ 400, f"You have {MAX_VOICES} saved voices. Delete one to save another."+ )+ voice_id = uuid.uuid4().hex+ wav_path = voices_dir() / f"{voice_id}.wav"+ try:+ info = transcode(+ src_path,+ wav_path,+ rate = REFERENCE_RATE,+ mono = True,+ max_seconds = REFERENCE_MAX_SECONDS,+ cut = True,+ )+ record_meta = {+ "name": name,+ "transcript": _clean_text(meta.get("transcript"), TRANSCRIPT_MAX),+ "language": _clean_text(meta.get("language"), LANGUAGE_MAX),+ "duration_s": info["duration_s"],+ "sample_rate": info["sample_rate"],+ "created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),+ "created_at_epoch": time.time(),+ }+ _write_json(_sidecar(voice_id), record_meta)+ except BaseException:+ wav_path.unlink(missing_ok = True)+ raise+ return _record(voice_id, record_meta)+++def list_voices() -> list[dict[str, Any]]:+ """Every saved voice in this account, newest first."""+ entries = []+ for voice_id in _ids():+ meta = _read(voice_id)+ if meta is None or not (voices_dir() / f"{voice_id}.wav").is_file():+ continue+ created = float(meta.get("created_at_epoch") or 0.0)+ entries.append((created, meta["created_at"], voice_id, meta))+ entries.sort(key = lambda e: (e[0], e[1], e[2]), reverse = True)+ return [_record(voice_id, meta) for _e, _c, voice_id, meta in entries]+++def get(voice_id: str) -> Optional[dict[str, Any]]:+ meta = _read(voice_id)+ if meta is None or voice_path(voice_id) is None:+ return None+ return _record(voice_id, meta)+++def voice_path(voice_id: str) -> Optional[Path]:+ """The WAV of a saved voice in this account; None if unknown, unsafe or another account's."""+ if _read(voice_id) is None:+ return None+ directory = voices_dir()+ path = directory / f"{voice_id}.wav"+ try:+ path.resolve().relative_to(directory.resolve())+ except (OSError, ValueError):+ return None+ return path if path.is_file() else None+++def update(voice_id: str, patch: dict[str, Any]) -> Optional[dict[str, Any]]:+ meta = _read(voice_id)+ if meta is None or voice_path(voice_id) is None:+ return None+ if "name" in patch and patch["name"] is not None:+ meta["name"] = _clean_name(patch["name"])+ if "transcript" in patch:+ meta["transcript"] = _clean_text(patch["transcript"], TRANSCRIPT_MAX)+ if "language" in patch:+ meta["language"] = _clean_text(patch["language"], LANGUAGE_MAX)+ _write_json(_sidecar(voice_id), meta)+ return _record(voice_id, meta)+++def delete(voice_id: str) -> bool:+ """Remove an owned voice; WAV first, as the gallery does."""+ path = voice_path(voice_id)+ if path is None:+ return False+ try:+ path.unlink()+ except OSError as exc:+ logger.warning("audio_voices.delete_failed: %s", exc)+ return False+ try:+ _sidecar(voice_id).unlink(missing_ok = True)+ except OSError:+ pass+ try:+ for copy in inputs_dir().glob(f"v-{voice_id}.*.wav"):+ copy.unlink(missing_ok = True)+ except OSError:+ pass+ return Truediff --git a/studio/backend/core/inference/audio_workflows.py b/studio/backend/core/inference/audio_workflows.pyindex a3d3f1f02d5..c9adc8e569b 100644--- a/studio/backend/core/inference/audio_workflows.py+++ b/studio/backend/core/inference/audio_workflows.py@@ -1,7 +1,7 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""Which Audio page workflows (Speak, Music, Transcribe) a model or a clip belongs to.+"""Which Audio page workflows (Speak, Clone, Music, Transcribe) a model or a clip belongs to.Mirrors ``studio/frontend/src/features/audio/workflows.ts``. This module reads the audio.cppconstants; ``audio_cpp_models`` never imports it.@@ -13,14 +13,29 @@ from typing import Optionalfrom core.inference.audio_cpp_models import AUDIO_CPP_MUSIC_AUDIO_TYPE, HUB_TASKS+AUDIO_WORKFLOW_IDS = ("speak", "clone", "music", "transcribe")++# Generation audio types that make music; every other generation audio type speaks.MUSIC_AUDIO_TYPES = frozenset(("minimax_music3", AUDIO_CPP_MUSIC_AUDIO_TYPE))+# Audio types of a loaded model that transcribes rather than generates.+_TRANSCRIBE_AUDIO_TYPES = frozenset(("whisper",))+def workflow_for_audio_type(audio_type: Optional[str]) -> str:"""The generation workflow (``speak`` or ``music``) that a model or clip of this type serves."""return "music" if audio_type in MUSIC_AUDIO_TYPES else "speak"+def status_audio_workflows(is_audio: bool, audio_type: Optional[str]) -> list[str]:+ """Workflows the loaded model serves; empty for a model that is not an audio model."""+ if not is_audio:+ return []+ if audio_type in _TRANSCRIBE_AUDIO_TYPES:+ return ["transcribe"]+ return [workflow_for_audio_type(audio_type)]++def inventory_audio_workflows(task: Optional[str], audio_type: Optional[str]) -> Optional[list[str]]:diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.pyindex cf0209b4373..5ec55b8e033 100644--- a/studio/backend/core/inference/orchestrator.py+++ b/studio/backend/core/inference/orchestrator.py@@ -387,6 +387,10 @@ def _mirrored_model_entry(model_info: dict, model_name: str) -> dict:"audio_family": model_info.get("audio_family"),"audio_options": model_info.get("audio_options"),"gguf_variant": model_info.get("gguf_variant"),+ "audio_workflows": model_info.get("audio_workflows"),+ "audio_reference_text": model_info.get("audio_reference_text"),+ "audio_required_inputs": model_info.get("audio_required_inputs"),+ "audio_clone": model_info.get("audio_clone"),}@@ -3342,10 +3346,15 @@ class InferenceOrchestrator:language: Optional[str] = None,seed: Optional[int] = None,audio_options: Optional[dict] = None,+ workflow: Optional[str] = None,+ audio_inputs: Optional[dict[str, str]] = None,+ reference_text: Optional[str] = None,+ speed: Optional[float] = None,stats_holder: Optional[dict] = None,) -> Tuple[bytes, int]:"""Generate TTS audio. Returns (wav_bytes, sample_rate). Blocking: sends the command and- waits for the full audio response."""+ waits for the full audio response. ``audio_inputs`` maps a role (reference, emotion) to a+ server-local WAV path; audio bytes never cross the queue."""if not self._ensure_subprocess_alive():raise RuntimeError("Inference subprocess is not running")if not self.active_model_name:@@ -3414,6 +3423,14 @@ class InferenceOrchestrator:cmd["seed"] = int(seed)if audio_options:cmd["audio_options"] = dict(audio_options)+ if workflow is not None:+ cmd["workflow"] = workflow+ if audio_inputs is not None:+ cmd["audio_inputs"] = {str(k): str(v) for k, v in audio_inputs.items()}+ if reference_text is not None:+ cmd["reference_text"] = reference_text+ if speed is not None:+ cmd["speed"] = float(speed)# Same shared-queue hazard as _generate_inner: see _direct_reader.read_one, _drain, release_mailbox = self._direct_reader(request_id, cancel_event)diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.pyindex 6a7fa6bc0bb..926bd5f4279 100644--- a/studio/backend/core/inference/worker.py+++ b/studio/backend/core/inference/worker.py@@ -790,6 +790,10 @@ def _handle_load(backend, config: dict, resp_queue: Any) -> None:"audio_family","audio_options","gguf_variant",+ "audio_workflows",+ "audio_reference_text",+ "audio_required_inputs",+ "audio_clone",)if k in _entry}@@ -1597,6 +1601,17 @@ def _handle_generate_audio(backend, cmd: dict, resp_queue: Any, cancel_event) ->logger.info("Starting audio generation for request_id=%s", request_id)# Only audio.cpp models take per-model options; other backends never see the keyword.extra = {"audio_options": cmd["audio_options"]} if cmd.get("audio_options") else {}+ # Run fields reach only a backend that takes them: a Speak run on a native TTS model carries a+ # workflow its backend has no keyword for.+ params = inspect.signature(backend.generate_audio_response).parameters+ takes_any = any(p.kind is inspect.Parameter.VAR_KEYWORD for p in params.values())+ for key in ("workflow", "audio_inputs", "reference_text", "speed"):+ if cmd.get(key) is None:+ continue+ if takes_any or key in params:+ extra[key] = cmd[key]+ elif key == "audio_inputs":+ raise AudioRuntimeError("This model cannot clone a voice.", status = 400)wav_bytes, sample_rate = backend.generate_audio_response(text = cmd["text"],temperature = cmd.get("temperature", 0.6),diff --git a/studio/backend/hub/schemas/inventory.py b/studio/backend/hub/schemas/inventory.pyindex a2959fa2c69..686f88eb4f1 100644--- a/studio/backend/hub/schemas/inventory.py+++ b/studio/backend/hub/schemas/inventory.py@@ -209,7 +209,7 @@ class LocalModelInfo(BaseModel):)audio_workflows: Optional[List[str]] = Field(None,- description = "Audio page workflows (speak, music, transcribe) this row serves; null when not audio",+ description = "Audio page workflows (speak, clone, music, transcribe) this row serves; null when not audio",)base_model: Optional[str] = Field(None,diff --git a/studio/backend/hub/services/models/cache_inventory.py b/studio/backend/hub/services/models/cache_inventory.pyindex 0c67d427926..9e1435f6678 100644--- a/studio/backend/hub/services/models/cache_inventory.py+++ b/studio/backend/hub/services/models/cache_inventory.py@@ -669,12 +669,20 @@ def _scan_cached_gguf(selected = gguf_identity.load_snapshot or gguf_snapshot,)row_audio_type = None+ row_audio_workflows = Noneif row_task == "text-to-speech":try:from hub.services.models import catalog_classificationrow_audio_type = catalog_classification._repo_gguf_audio_type(repo_info, gguf_identity.load_snapshot or gguf_snapshot)+ if row_audio_type == "audiocpp_tts":+ row_audio_workflows = catalog_classification._gguf_path_audio_workflows(+ gguf_identity.load_snapshot+ or gguf_snapshot+ or Path(repo_info.repo_path),+ (repo_id,),+ )except Exception:passrow = {@@ -689,6 +697,8 @@ def _scan_cached_gguf("partial_transport": None,"partial_resumable": False,}+ if row_audio_workflows is not None:+ row["audio_workflows"] = row_audio_workflowslast_modified = max(last_modified, (existing or {}).get("last_modified", 0.0))if last_modified > 0:row["last_modified"] = last_modifieddiff --git a/studio/backend/hub/services/models/catalog_classification.py b/studio/backend/hub/services/models/catalog_classification.pyindex 08e717b9ff3..38df93f8a78 100644--- a/studio/backend/hub/services/models/catalog_classification.py+++ b/studio/backend/hub/services/models/catalog_classification.py@@ -206,6 +206,45 @@ def _audio_cpp_classification(return task, audio_type+def _audio_cpp_workflows(+ path: Optional[str | Path], name_hints: tuple[Optional[str], ...]+) -> Optional[list[str]]:+ """The Audio page workflows an audio.cpp GGUF serves (a clone-only family lists ``clone``+ alone), from the same family policy the loader uses; None when it is not a runnable one."""+ try:+ from core.inference import audio_cpp_models as acm+ except Exception:+ return None+ header = acm.read_local_header(path) if path is not None else None+ names = tuple(str(hint) for hint in name_hints if hint)+ family = (header.family if header is not None else None) or acm.family_from_names(names)+ if not family:+ return None+ policy = acm.family_policy(family, header.spec if header is not None else None, names)+ if policy.unsupported or not policy.task:+ return None+ return list(policy.workflows) or None+++def _gguf_path_audio_workflows(+ path: str | Path, id_hints: tuple[Optional[str], ...] = ()+) -> Optional[list[str]]:+ """The union of ``_audio_cpp_workflows`` over the audio.cpp GGUFs at ``path`` (a file or a+ folder): the umbrella repo is one row holding every downloaded family."""+ from core.inference.audio_workflows import AUDIO_WORKFLOW_IDS++ model_path = Path(path)+ found: set[str] = set()+ try:+ paths = [model_path] if model_path.is_file() else _iter_gguf_paths(model_path)+ for gguf_path in paths:+ if is_audio_cpp_gguf_architecture(_gguf_architecture(str(gguf_path))):+ found.update(_audio_cpp_workflows(gguf_path, id_hints + (gguf_path.name,)) or ())+ except Exception:+ return None+ return [w for w in AUDIO_WORKFLOW_IDS if w in found] or None++def _gguf_file_task(path: str | Path, name_hints: tuple[Optional[str], ...]) -> Optional[str]:"""``_arch_to_task`` for a file on disk, which can also read an audio.cpp family."""arch = _gguf_architecture(str(path))@@ -537,6 +576,15 @@ def _local_model_classification_for_task(return task, audio_type+def local_audio_workflows(model, audio_type: Optional[str]) -> Optional[list[str]]:+ """The audio.cpp family's own workflows for a local speech row (a clone-only one is not+ Speak); None keeps the task-derived default."""+ if audio_type != "audiocpp_tts":+ return None+ model = _local_probe_model(model)+ return _gguf_path_audio_workflows(model.path, (model.model_id, model.display_name, model.id))++def _local_model_classification(model) -> tuple[Optional[str], Optional[str]]:"""Return picker task and decoder provenance from one local-row probe."""return _local_model_classification_for_task(model, _local_model_task(model))diff --git a/studio/backend/hub/services/models/local_inventory.py b/studio/backend/hub/services/models/local_inventory.pyindex b820378a037..b4cfb34dc47 100644--- a/studio/backend/hub/services/models/local_inventory.py+++ b/studio/backend/hub/services/models/local_inventory.py@@ -1144,11 +1144,13 @@ async def list_local_models_response(models_dir: str = "./models") -> LocalModelmodels = []for model in response.models:task, audio_type = catalog_classification._local_model_classification(model)+ workflows = catalog_classification.local_audio_workflows(model, audio_type)models.append(model.model_copy(update = {"task": task,"audio_type": audio_type,+ **({"audio_workflows": workflows} if workflows else {}),}))diff --git a/studio/backend/main.py b/studio/backend/main.pyindex 06963b79c6d..7af217d63ab 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -870,6 +870,10 @@ async def lifespan(app: FastAPI):# Embeddings stay cold until ingestion or retrieval actually requests vectors._start_helper_precache_if_enabled()+ from core.inference.audio_inputs import start_sweeper as _start_audio_input_sweeper++ _start_audio_input_sweeper()+from core.research_runs import ResearchSupervisorapp.state.research_supervisor = ResearchSupervisor(app)@@ -1320,6 +1324,7 @@ if _DOCS_ASSETS_DIR.is_dir():# Cap request bodies on protected POSTs; upload routes get explicit multipart headroom.import json as _json_for_413 # noqa: E402from utils.upload_limits import ( # noqa: E402+ AUDIO_INPUT_MAX_BYTES,STT_AUDIO_JSON_MAX_BYTES,STT_AUDIO_RAW_MAX_BYTES,LIBRARY_UPLOAD_MAX_BYTES,@@ -1366,6 +1371,8 @@ _VIDEO_MULTIPART_UPLOAD_PATHS = ("/api/inference/videos",)_LIBRARY_UPLOAD_PATH = "/api/library/uploads"+# Streamed to disk and capped by the route itself; buffering here would hold 200 MiB in memory.+_AUDIO_INPUT_UPLOAD_PATH = "/api/inference/audio/inputs"_BODY_UPLOAD_PASSTHROUGH_PREFIXES = (*_DATASET_UPLOAD_PASSTHROUGH_PREFIXES,_DATA_RECIPE_UNSTRUCTURED_UPLOAD_PASSTHROUGH_PREFIX,@@ -1373,6 +1380,7 @@ _BODY_UPLOAD_PASSTHROUGH_PREFIXES = (# Matched by EXACT path (multipart uploads only), so sibling JSON sub-routes keep the normal cap._BODY_UPLOAD_PASSTHROUGH_EXACT_PATHS = (_DIFFUSION_DATASET_UPLOAD_PATH,+ _AUDIO_INPUT_UPLOAD_PATH,*_STT_MULTIPART_UPLOAD_PATHS,*_VIDEO_MULTIPART_UPLOAD_PATHS,_LIBRARY_UPLOAD_PATH,@@ -1396,6 +1404,8 @@ def _get_upload_passthrough_request_max_bytes(path: str) -> int:)if path.rstrip("/") == _LIBRARY_UPLOAD_PATH:return upload_request_limit_bytes(LIBRARY_UPLOAD_MAX_BYTES)+ if path.rstrip("/") == _AUDIO_INPUT_UPLOAD_PATH:+ return AUDIO_INPUT_MAX_BYTES# The trailing-slash variant reaches this middleware BEFORE the router's redirect_slashes# 307, so it must resolve to the same cap. JSON sub-routes keep extra path components.if (diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex ae4e35840f6..6c2f46436a5 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -5,6 +5,7 @@from __future__ import annotations+import reimport timeimport uuidfrom collections import deque@@ -12,6 +13,7 @@ from typing import Annotated, Any, Dict, Literal, Optional, List, Unionfrom pydantic import (BaseModel,+ ConfigDict,Discriminator,Field,PrivateAttr,@@ -20,6 +22,7 @@ from pydantic import (model_validator,)+from core.inference.audio_workflows import status_audio_workflowsfrom core.inference.llama_server_args import (BATCH_MAX,BATCH_MIN,@@ -1362,6 +1365,35 @@ class _InferenceRuntimeFields(BaseModel):"description, default, min, max, values, required}. Send chosen values as audio_options."),)+ audio_workflows: Optional[List[str]] = Field(+ None,+ description = (+ "Audio page workflows (speak, clone, music, transcribe) the loaded model serves; [] "+ "for a model that is not an audio model. Derived from is_audio and audio_type when "+ "not given."+ ),+ )+ audio_reference_text: Optional[Literal["required", "optional", "unused"]] = Field(+ None,+ description = (+ "For a model that clones: whether a request needs the reference clip's transcript. "+ "None for a model that does not clone."+ ),+ )+ audio_required_inputs: Optional[List[str]] = Field(+ None,+ description = (+ "Request fields the model refuses to run without (Maya1: ['instruct'], a voice "+ "description sent as instructions)."+ ),+ )++ @model_validator(mode = "after")+ def derive_audio_workflows(self):+ if self.audio_workflows is None:+ self.audio_workflows = status_audio_workflows(self.is_audio, self.audio_type)+ return self+has_video_input: bool = Field(False,description = (@@ -5108,12 +5140,178 @@ class AudioGalleryItem(BaseModel):pinned: bool = Field(False, description = "Pinned to the top of history")archived: bool = Field(False, description = "Moved to the archived shelf, hidden from history")workflow: Optional[str] = Field(- None, description = "Audio page workflow that made the clip: speak or music"+ None, description = "Audio page workflow that made the clip: speak, clone or music")order_at: Optional[float] = Field(None,description = "Unpinned sort key (epoch-second scale): the manual key once dragged, else the file mtime",)+ role: Optional[str] = Field(None, description = "The clip's part in its run, e.g. output")+ source_clip_id: Optional[str] = Field(+ None, description = "History clip the run took its reference from"+ )+ voice_id: Optional[str] = Field(None, description = "Saved voice the run spoke in")+ settings: Optional[Dict[str, Any]] = Field(+ None, description = "Language, options, speed and whether a transcript was used"+ )+ reference_name: Optional[str] = Field(None, description = "Name of the reference clip or voice")+++_AUDIO_ID_PATTERN = r"^[A-Za-z0-9_-]{1,128}$"+# A run names audio by id only. Option names with these words carry a location...+_AUDIO_FILE_OPTION_WORDS = frozenset({"path", "paths", "file", "files", "dir", "url", "uri"})+# ...and a text value under a name ending in these is a clip (source_audio, voice_ref), while+# min_new_audio_steps, audio_chunk_mode or a boolean no_ref are settings.+# Other media too: ControlFoley's string ``video`` option is a file the runtime would open.+_AUDIO_CLIP_OPTION_ENDINGS = frozenset({"audio", "wav", "ref", "video", "image", "img", "midi"})+++def _names_a_file(name: str, value: Any) -> bool:+ words = re.split(r"[^a-z0-9]+", name.lower())+ if any(word in _AUDIO_FILE_OPTION_WORDS for word in words):+ return True+ return isinstance(value, str) and words[-1] in _AUDIO_CLIP_OPTION_ENDINGS+++class AudioSourceRef(BaseModel):+ """Audio named by id: an uploaded input, a history clip or a saved voice. Exactly one."""++ model_config = ConfigDict(extra = "forbid")++ input_id: Optional[str] = Field(None, pattern = _AUDIO_ID_PATTERN)+ clip_id: Optional[str] = Field(None, pattern = _AUDIO_ID_PATTERN)+ voice_id: Optional[str] = Field(None, pattern = _AUDIO_ID_PATTERN)++ @model_validator(mode = "after")+ def _exactly_one(self):+ named = [v for v in (self.input_id, self.clip_id, self.voice_id) if v]+ if len(named) != 1:+ raise ValueError("Name exactly one of input_id, clip_id or voice_id.")+ return self+++class AudioRunInputs(BaseModel):+ model_config = ConfigDict(extra = "forbid")++ reference: Optional[AudioSourceRef] = None+ reference_text: Optional[str] = Field(None, max_length = 4000)+ emotion: Optional[AudioSourceRef] = None+++class AudioRunRequest(BaseModel):+ """``POST /audio/run``: one Audio page run. Audio is named by id; the server picks the files."""++ model_config = ConfigDict(extra = "forbid")++ workflow: Literal["clone", "speak"]+ text: str = Field(..., min_length = 1)+ language: Optional[str] = Field(None, max_length = 64)+ instructions: Optional[str] = Field(None, max_length = 4000)+ inputs: AudioRunInputs = Field(default_factory = AudioRunInputs)+ options: Optional[Dict[str, Any]] = Field(+ None, description = "Per-model options, as listed in audio_options or by a tool panel"+ )+ speed: Optional[float] = Field(None, ge = 0.25, le = 4.0)+ seed: Optional[int] = Field(None, ge = -(2**63), le = 2**64 - 1)+ max_tokens: Optional[int] = Field(None, ge = 1)++ @field_validator("options")+ @classmethod+ def _no_file_options(cls, value):+ if value is None:+ return value+ for name, option in value.items():+ if _names_a_file(str(name), option):+ raise ValueError(f"Option '{name}' is not accepted; name audio by id in inputs.")+ if isinstance(option, (dict, list)):+ raise ValueError(f"Option '{name}' must be a single value.")+ return value+++class AudioRunClip(BaseModel):+ id: str+ role: str = "output"+ url: str+ sample_rate: int+ duration_s: float+ workflow: str+++class AudioRunAudio(BaseModel):+ data: str+ format: str = "wav"+ sample_rate: int+++class AudioRunResponse(BaseModel):+ clips: List[AudioRunClip] = Field(default_factory = list)+ model: str+ audio: Optional[AudioRunAudio] = Field(+ None, description = "The audio inline, only when saving it to history failed"+ )+++class AudioInputRecord(BaseModel):+ id: str+ name: str+ duration_s: float+ sample_rate: int+ channels: int+ url: str+ expires_at: str+++class AudioInputTranscribeRequest(BaseModel):+ model_config = ConfigDict(extra = "forbid")++ model: str = Field(..., min_length = 1, max_length = 512)+ engine: Optional[str] = Field(None, max_length = 64)+ device: Optional[Literal["auto", "cpu", "gpu"]] = None+ language: Optional[str] = Field(None, max_length = 64)+++class AudioInputTranscript(BaseModel):+ text: str+ language: Optional[str] = None+ model: str+++class AudioVoice(BaseModel):+ id: str+ name: str+ transcript: Optional[str] = None+ language: Optional[str] = None+ duration_s: float+ sample_rate: int+ created_at: str+ url: str+++class AudioVoiceCreate(BaseModel):+ model_config = ConfigDict(extra = "forbid")++ source: AudioSourceRef+ name: str = Field(..., min_length = 1, max_length = 80)+ transcript: Optional[str] = Field(None, max_length = 4000)+ language: Optional[str] = Field(None, max_length = 64)++ @model_validator(mode = "after")+ def _from_input_or_clip(self):+ if self.source.voice_id:+ raise ValueError("A voice is saved from an input or a history clip.")+ return self+++class AudioVoicePatch(BaseModel):+ model_config = ConfigDict(extra = "forbid")++ name: Optional[str] = Field(None, min_length = 1, max_length = 80)+ transcript: Optional[str] = Field(None, max_length = 4000)+ language: Optional[str] = Field(None, max_length = 64)+++class AudioVoiceListResponse(BaseModel):+ voices: List[AudioVoice] = Field(default_factory = list)class AudioGalleryFlagsPatch(BaseModel):diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 8573ddc6f9d..a827ef50653 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -3697,6 +3697,15 @@ from models.inference import (AudioGalleryFlagsPatch,AudioGalleryItem,AudioGalleryListResponse,+ AudioInputRecord,+ AudioInputTranscribeRequest,+ AudioInputTranscript,+ AudioRunRequest,+ AudioRunResponse,+ AudioVoice,+ AudioVoiceCreate,+ AudioVoiceListResponse,+ AudioVoicePatch,LoadResponse,LoadProgressResponse,UnloadResponse,@@ -8238,6 +8247,9 @@ def _llama_runtime_fields(llama_backend: LlamaCppBackend) -> dict:# llama-server never serves an audio GGUF; those load through the audio worker.audio_family = None,audio_options = None,+ audio_workflows = None,+ audio_reference_text = None,+ audio_required_inputs = None,# Older/custom backend doubles predate this additive runtime field.preserve_thinking_default = bool(getattr(llama_backend, "preserve_thinking_default", False)),speculative_type = llama_backend.requested_spec_mode,@@ -19149,6 +19161,9 @@ async def _load_model_impl(has_video_input = _model_info.get("has_video_input", False),audio_family = _model_info.get("audio_family"),audio_options = _model_info.get("audio_options"),+ audio_workflows = _model_info.get("audio_workflows"),+ audio_reference_text = _model_info.get("audio_reference_text"),+ audio_required_inputs = _model_info.get("audio_required_inputs"),is_mlx = bool(_model_info.get("is_mlx", False)),mlx_kv_quant = _model_info.get("mlx_kv_quant"),mlx_kv_quant_requested = _model_info.get("mlx_kv_quant_requested"),@@ -21828,6 +21843,9 @@ async def _slot_status(current_subject: str):has_video_input = has_video_input,audio_family = model_info.get("audio_family"),audio_options = model_info.get("audio_options"),+ audio_workflows = model_info.get("audio_workflows"),+ audio_reference_text = model_info.get("audio_reference_text"),+ audio_required_inputs = model_info.get("audio_required_inputs"),gguf_variant = model_info.get("gguf_variant"),is_mlx = bool(model_info.get("is_mlx", False)),mlx_kv_quant = model_info.get("mlx_kv_quant"),@@ -21980,6 +21998,55 @@ def _audio_cpp_music_request_problem(return None+def _audio_model_label(model_name: Optional[str]) -> str:+ """``audio-cpp/audio.cpp-gguf/Maya1-GGUF`` -> ``Maya1``, for a sentence naming the model."""+ label = str(model_name or "").rstrip("/").rsplit("/", 1)[-1]+ label = re.sub(r"[-_.]gguf$", "", label, flags = re.IGNORECASE)+ return label or "This model"+++def _audio_request_problem(+ model_info: dict,+ model_name: Optional[str],+ audio_type: Optional[str],+ payload: ChatCompletionRequest,+ run_inputs: Optional[dict],+) -> Optional[str]:+ """Why the loaded model cannot serve this request, in words for the user; else None."""+ workflows = model_info.get("audio_workflows")+ label = _audio_model_label(model_name)+ inputs = (run_inputs or {}).get("audio_inputs") or {}+ cloning = bool(run_inputs) and (run_inputs.get("workflow") == "clone" or bool(inputs))+ if cloning:+ if not workflows or "clone" not in workflows:+ return "Load a model that can clone a voice."+ if not inputs.get("reference"):+ return "Add a reference clip to clone."+ rules = model_info.get("audio_clone") or {}+ if inputs.get("emotion") and not rules.get("emotion_audio"):+ return f"{label} does not take an emotion clip."+ if (+ rules.get("reference_text") == "required"+ and not str((run_inputs or {}).get("reference_text") or "").strip()+ ):+ from core.inference.audio_cpp_models import option_matches+ if not option_matches(rules.get("reference_text_waived") or [], payload.audio_options):+ return "Type what's said in the reference clip."+ elif (+ workflows is not None+ and audio_type == "audiocpp_tts"+ and "speak" not in workflows+ and "clone" in workflows+ ):+ return f"{label} speaks in a voice cloned from a recording. Open Clone and add one."+ if (+ "instruct" in (model_info.get("audio_required_inputs") or [])+ and not str(payload.audio_instructions or "").strip()+ ):+ return f"{label} needs a voice description."+ return None++async def _generate_tts_wav(text: str,payload: ChatCompletionRequest,@@ -21988,10 +22055,12 @@ async def _generate_tts_wav(*,speech_api_default_max_tokens: bool = False,requested_model: str = _RELOAD_ONLY_MODEL,+ run_inputs: Optional[dict] = None,stats_holder: Optional[dict] = None,) -> tuple[bytes, int, str, Optional[str]]:- """Shared core of /audio/generate and /audio/speech. Returns- (wav_bytes, sample_rate, model_name, audio_type)."""+ """Shared core of /audio/generate, /audio/speech and /audio/run. Returns+ (wav_bytes, sample_rate, model_name, audio_type). ``run_inputs`` is /audio/run's ``workflow``,+ ``audio_inputs`` (role -> server-local WAV path), ``reference_text`` and ``speed``."""# A named target must be budgeted against its own context after preflight.if requested_model == _RELOAD_ONLY_MODEL:_raise_if_prompt_leaves_no_speech_budget(text)@@ -22024,6 +22093,7 @@ async def _generate_tts_wav(# Pick backend - both return (wav_bytes, sample_rate)audio_family = None+ model_info: dict = {}llama_backend = get_llama_cpp_backend()# GGUF TTS goes straight to llama-server /completion, holding a slot with no# admission lease, so only the direct counter can show it in the slot readout.@@ -22083,6 +22153,12 @@ async def _generate_tts_wav(language = payload.audio_language,seed = payload.seed,**({"audio_options": payload.audio_options} if payload.audio_options else {}),+ **{+ key: value+ for key, value in (run_inputs or {}).items()+ if key in ("workflow", "audio_inputs", "reference_text", "speed")+ and value is not None+ },stats_holder = stats_holder,)@@ -22091,6 +22167,11 @@ async def _generate_tts_wav(status_code = 400,detail = f"Active model does not support text-to-speech (audio_type={audio_type or 'unknown'}).",)+ _request_problem = _audio_request_problem(+ model_info, model_name, audio_type, payload, run_inputs+ )+ if _request_problem:+ raise HTTPException(status_code = 400, detail = _request_problem)if audio_type == "minimax_music3" and not str(payload.audio_instructions or "").strip():raise HTTPException(status_code = 400, detail = _MINIMAX_NEEDS_DESCRIPTION)if audio_type == "audiocpp_music":@@ -22173,26 +22254,31 @@ def _wav_duration_seconds(wav_bytes: bytes, sample_rate: int) -> float:def _persist_tts_clip(- wav_bytes: bytes, sample_rate: int, text: str, model_name: str, audio_type: Optional[str]+ wav_bytes: bytes,+ sample_rate: int,+ text: str,+ model_name: str,+ audio_type: Optional[str],+ extra_meta: Optional[dict] = None,+ workflow: Optional[str] = None,) -> Optional[dict[str, Any]]:"""Best-effort gallery save: persistence never fails the request that producedthe audio. Blocking, so callers run it off the event loop."""from core.inference import audio_galleryfrom core.inference.audio_workflows import workflow_for_audio_type+ meta = {+ "prompt": text,+ "model": model_name,+ "audio_type": audio_type or "unknown",+ "workflow": workflow or workflow_for_audio_type(audio_type),+ "sample_rate": sample_rate,+ "duration_s": _wav_duration_seconds(wav_bytes, sample_rate),+ "created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),+ }+ meta.update({k: v for k, v in (extra_meta or {}).items() if v is not None})try:- return audio_gallery.save(- wav_bytes,- {- "prompt": text,- "model": model_name,- "audio_type": audio_type or "unknown",- "workflow": workflow_for_audio_type(audio_type),- "sample_rate": sample_rate,- "duration_s": _wav_duration_seconds(wav_bytes, sample_rate),- "created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),- },- )+ return audio_gallery.save(wav_bytes, meta)except Exception as exc: # noqa: BLE001 - log and serve the audio anywaylogger.warning("audio_gallery.persist_failed: %s", exc)return None@@ -22307,6 +22393,110 @@ async def generate_audio()+def _audio_source_error(exc) -> HTTPException:+ return HTTPException(status_code = exc.status, detail = exc.detail)+++def _audio_run_settings(body: AudioRunRequest, reference_text_used: bool) -> dict[str, Any]:+ """The run's recipe for history: scalar options only."""+ options = {+ str(name): value+ for name, value in (body.options or {}).items()+ if isinstance(value, (bool, int, float)) or (isinstance(value, str) and len(value) <= 4000)+ }+ return {+ "language": body.language,+ "instructions": body.instructions,+ "options": options,+ "reference_text_used": reference_text_used,+ "speed": body.speed,+ }++[email protected]("/audio/run", response_model = AudioRunResponse)+async def run_audio_workflow(+ body: AudioRunRequest,+ request: Request,+ current_subject: str = Depends(get_current_subject),+):+ """Clone, or Speak in a saved voice, and save the clip to history. Audio is named by id and+ resolved here in the caller's account; the worker gets a prepared copy's path, never bytes."""+ import base64++ from core.inference import audio_inputs++ if body.workflow == "clone" and body.inputs.reference is None:+ raise HTTPException(status_code = 400, detail = "Add a reference clip to clone.")+ prepared = {}+ try:+ for role in ("reference", "emotion"):+ ref = getattr(body.inputs, role)+ if ref is not None:+ prepared[role] = await asyncio.to_thread(+ audio_inputs.prepare_reference, ref.model_dump(exclude_none = True)+ )+ except audio_inputs.AudioInputError as exc:+ raise _audio_source_error(exc) from None+ paths = {role: str(path) for role, (_source, path) in prepared.items()}+ reference_source = prepared["reference"][0] if "reference" in prepared else None+ reference_text = (body.inputs.reference_text or "").strip() or None+ # An omitted transcript falls back to the saved voice's; a sent blank one was cleared on purpose.+ if (+ body.inputs.reference_text is None+ and reference_source is not None+ and reference_source.kind == "voice"+ ):+ from core.inference import audio_voices+ voice = await asyncio.to_thread(audio_voices.get, reference_source.id)+ reference_text = ((voice or {}).get("transcript") or "").strip() or None++ payload = ChatCompletionRequest(+ messages = [{"role": "user", "content": body.text}],+ max_tokens = body.max_tokens,+ audio_instructions = body.instructions,+ audio_language = body.language,+ audio_options = body.options,+ seed = body.seed,+ )+ wav_bytes, sample_rate, model_name, audio_type = await _generate_tts_wav(+ body.text,+ payload,+ request,+ current_subject,+ run_inputs = {+ "workflow": body.workflow,+ "audio_inputs": paths or None,+ "reference_text": reference_text,+ "speed": body.speed,+ },+ )+ extra_meta: dict[str, Any] = {+ "role": "output",+ "settings": _audio_run_settings(body, reference_text is not None),+ }+ if reference_source is not None:+ extra_meta["reference_name"] = reference_source.name+ if reference_source.kind == "clip":+ extra_meta["source_clip_id"] = reference_source.id+ elif reference_source.kind == "voice":+ extra_meta["voice_id"] = reference_source.id+ record = await asyncio.to_thread(+ _persist_tts_clip,+ wav_bytes,+ sample_rate,+ body.text,+ model_name,+ audio_type,+ extra_meta,+ body.workflow,+ )+ if record is None:+ audio = {"data": base64.b64encode(wav_bytes).decode("ascii"), "sample_rate": sample_rate}+ return AudioRunResponse(model = model_name, audio = audio)+ clip = {k: record[k] for k in ("id", "url", "sample_rate", "duration_s", "workflow")}+ return AudioRunResponse(clips = [clip], model = model_name)++def _refuse_decision_connection(provider_type: Optional[str], api_type: Optional[str]) -> None:if answers_decisions_only(provider_type, api_type):raise HTTPException(@@ -44509,7 +44699,7 @@ async def delete_gallery_audio(audio_id: str, current_subject: str = Depends(get@studio_router.delete("/audio/gallery")async def clear_gallery_audio(- workflow: Optional[Literal["speak", "music"]] = None,+ workflow: Optional[Literal["speak", "clone", "music"]] = None,current_subject: str = Depends(get_current_subject),):from core.inference import audio_gallery@@ -44527,6 +44717,159 @@ async def clear_gallery_audio(return {"removed": removed}+@studio_router.post("/audio/inputs", status_code = 201, response_model = AudioInputRecord)+async def upload_audio_input(+ request: Request,+ response: Response,+ name: str = Query("audio", max_length = 255),+ current_subject: str = Depends(get_current_subject),+):+ """Store a raw audio body (any container), decoded once to WAV; a re-upload of the same audio+ returns the existing record with 200."""+ from core.inference import audio_inputs+ from utils.upload_limits import AUDIO_INPUT_MAX_BYTES++ declared = request.headers.get("content-length")+ try:+ if declared is not None and int(declared) > AUDIO_INPUT_MAX_BYTES:+ raise HTTPException(status_code = 413, detail = "Audio is too large.")+ except ValueError:+ pass+ try:+ record, created = await audio_inputs.save_stream(request.stream(), name)+ except audio_inputs.AudioInputError as exc:+ raise _audio_source_error(exc) from None+ if not created:+ response.status_code = 200+ return AudioInputRecord(**record)+++@studio_router.get("/audio/inputs/{input_id}/file")+async def get_audio_input_file(input_id: str, current_subject: str = Depends(get_current_subject)):+ from core.inference import audio_inputs+ from fastapi.responses import FileResponse++ path = await asyncio.to_thread(audio_inputs.input_path, input_id)+ if path is None:+ raise HTTPException(status_code = 404, detail = "This reference expired. Add it again.")+ return FileResponse(+ path, media_type = "audio/wav", headers = {"Cache-Control": "private, max-age=3600"}+ )+++@studio_router.delete("/audio/inputs/{input_id}")+async def delete_audio_input(input_id: str, current_subject: str = Depends(get_current_subject)):+ from core.inference import audio_inputs+ if not await asyncio.to_thread(audio_inputs.delete, input_id):+ raise HTTPException(status_code = 404, detail = "Audio not found.")+ return {"removed": True}+++@studio_router.post("/audio/inputs/{input_id}/transcribe", response_model = AudioInputTranscript)+async def transcribe_audio_input(+ input_id: str,+ body: AudioInputTranscribeRequest,+ request: Request,+ clip_id: Optional[str] = Query(None, max_length = 128),+ voice_id: Optional[str] = Query(None, max_length = 128),+ current_subject: str = Depends(get_current_subject),+):+ """What is said in an input (or, with the path id ``source``, a history clip or saved voice),+ over the first 30 s a clone uses. Saves nothing to the transcript history."""+ from core.inference import audio_inputs++ ref = {+ # ``source`` (or ``-``) stands for "the clip_id or voice_id in the query". A real input id+ # together with one of those names two sources and is refused.+ "input_id": None if input_id in ("source", "-") else input_id,+ "clip_id": clip_id,+ "voice_id": voice_id,+ }++ def _prepare() -> bytes:+ source = audio_inputs.resolve_source(ref)+ cap = None if source.kind == "voice" else audio_inputs.REFERENCE_MAX_SECONDS+ path = audio_inputs.prepared_path(source, 16000, max_seconds = cap)+ return path.read_bytes()++ try:+ raw = await asyncio.to_thread(_prepare)+ except audio_inputs.AudioInputError as exc:+ raise _audio_source_error(exc) from None+ result = await _transcribe_audio_result(+ raw, body.model, body.language, False, body.engine, request, body.device+ )+ return AudioInputTranscript(+ text = str(result.get("text") or "").strip(),+ language = result.get("language") or None,+ model = body.model,+ )+++@studio_router.get("/audio/voices", response_model = AudioVoiceListResponse)+async def list_audio_voices(current_subject: str = Depends(get_current_subject)):+ from core.inference import audio_voices+ return AudioVoiceListResponse(voices = await asyncio.to_thread(audio_voices.list_voices))+++@studio_router.post("/audio/voices", status_code = 201, response_model = AudioVoice)+async def create_audio_voice(+ body: AudioVoiceCreate, current_subject: str = Depends(get_current_subject)+):+ from core.inference import audio_inputs, audio_voices+ def _create() -> dict:+ source = audio_inputs.resolve_source(body.source.model_dump(exclude_none = True))+ return audio_voices.create(+ source.path,+ {"name": body.name, "transcript": body.transcript, "language": body.language},+ )++ try:+ return AudioVoice(**await asyncio.to_thread(_create))+ except audio_inputs.AudioInputError as exc:+ raise _audio_source_error(exc) from None+++@studio_router.patch("/audio/voices/{voice_id}", response_model = AudioVoice)+async def update_audio_voice(+ voice_id: str,+ body: AudioVoicePatch,+ current_subject: str = Depends(get_current_subject),+):+ from core.inference import audio_inputs, audio_voices++ try:+ record = await asyncio.to_thread(+ audio_voices.update, voice_id, body.model_dump(exclude_unset = True)+ )+ except audio_inputs.AudioInputError as exc:+ raise _audio_source_error(exc) from None+ if record is None:+ raise HTTPException(status_code = 404, detail = "Voice not found.")+ return AudioVoice(**record)+++@studio_router.delete("/audio/voices/{voice_id}")+async def delete_audio_voice(voice_id: str, current_subject: str = Depends(get_current_subject)):+ from core.inference import audio_voices+ if not await asyncio.to_thread(audio_voices.delete, voice_id):+ raise HTTPException(status_code = 404, detail = "Voice not found.")+ return {"removed": True}+++@studio_router.get("/audio/voices/{voice_id}/file")+async def get_audio_voice_file(voice_id: str, current_subject: str = Depends(get_current_subject)):+ from core.inference import audio_voices+ from fastapi.responses import FileResponse++ path = await asyncio.to_thread(audio_voices.voice_path, voice_id)+ if path is None:+ raise HTTPException(status_code = 404, detail = "Voice not found.")+ return FileResponse(+ path, media_type = "audio/wav", headers = {"Cache-Control": "private, max-age=3600"}+ )++@studio_router.get("/audio/transcripts")async def list_gallery_transcripts(limit: int = Query(50, ge = 1, le = 200),diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.pyindex 63067fa81ee..c138c046100 100644--- a/studio/backend/routes/models.py+++ b/studio/backend/routes/models.py@@ -1091,11 +1091,13 @@ async def _shared_compat_local_inventory_scan(task, audio_type = _catalog_classification._local_model_classification_for_task(model, _local_model_task(model))+ workflows = _catalog_classification.local_audio_workflows(model, audio_type)classified.append(model.model_copy(update = {"task": task,"audio_type": audio_type,+ **({"audio_workflows": workflows} if workflows else {}),}))diff --git a/studio/backend/tests/multi_account/factories_media.py b/studio/backend/tests/multi_account/factories_media.pyindex db98cee9879..a7acb16fb48 100644--- a/studio/backend/tests/multi_account/factories_media.py+++ b/studio/backend/tests/multi_account/factories_media.py@@ -120,6 +120,45 @@ def seed_audio_and_project(account, actor: str = "right") -> dict[str, str]:return params+@seeder("media-audio-input")+def seed_audio_input(account) -> dict[str, str]:+ import hashlib++ from core.inference import audio_inputs+ from utils.account_context import run_as++ data = _wav_bytes()++ def save() -> dict:+ directory = audio_inputs.inputs_dir()+ upload = directory / ".matrix.upload.tmp"+ upload.write_bytes(data)+ try:+ record, _ = audio_inputs._finish_upload(+ directory, upload, hashlib.sha256(data).hexdigest(), SENTINEL, len(data)+ )+ finally:+ upload.unlink(missing_ok = True)+ return record++ return {"input_id": run_as(account, save)["id"]}+++@seeder("media-audio-voice")+def seed_audio_voice(account) -> dict[str, str]:+ import tempfile+ from pathlib import Path++ from core.inference import audio_voices+ from utils.account_context import run_as++ with tempfile.TemporaryDirectory() as scratch:+ source = Path(scratch) / "voice.wav"+ source.write_bytes(_wav_bytes())+ record = run_as(account, audio_voices.create, source, {"name": SENTINEL})+ return {"voice_id": record["id"]}++@seeder("media-transcript")def seed_transcript(account) -> dict[str, str]:from core.inference import transcript_gallery@@ -301,6 +340,22 @@ FACTORIES = {"routes.inference:POST:/audio/gallery/{audio_id}/project": Factory("media-audio-project", {"project_id": MEDIA_PROJECT_ID}, fragment = "sandbox"),+ "routes.inference:GET:/audio/inputs/{input_id}/file": Factory("media-audio-input"),+ "routes.inference:DELETE:/audio/inputs/{input_id}": Factory("media-audio-input"),+ "routes.inference:POST:/audio/inputs/{input_id}/transcribe": Factory(+ "media-audio-input",+ {"model": "media/none"},+ # Past the source lookup the model check refuses: no speech-to-text model exists here.+ right = (404,),+ fragment = "Model not found",+ self_expected = (409,),+ reason = "no speech-to-text model is available, so transcription itself refuses",+ ),+ "routes.inference:PATCH:/audio/voices/{voice_id}": Factory(+ "media-audio-voice", {"name": "renamed"}, fragment = "renamed"+ ),+ "routes.inference:DELETE:/audio/voices/{voice_id}": Factory("media-audio-voice"),+ "routes.inference:GET:/audio/voices/{voice_id}/file": Factory("media-audio-voice"),"routes.inference:PATCH:/audio/transcripts/{transcript_id}": Factory("media-transcript", {"archived": True}, fragment = SENTINEL),diff --git a/studio/backend/tests/test_account_media_isolation.py b/studio/backend/tests/test_account_media_isolation.pyindex c9966c83550..441c8abb061 100644--- a/studio/backend/tests/test_account_media_isolation.py+++ b/studio/backend/tests/test_account_media_isolation.py@@ -239,3 +239,68 @@ def test_a_failed_replacement_load_leaves_residency_with_the_resident_model(monkassert unloaded == []with _client(ALICE) as client:assert client.get("/api/inference/video/status").json()["repo_id"] == "alice/private-video"+++def _save_input(account):+ import asyncio+ import io+ import wave++ from core.inference import audio_inputs++ buf = io.BytesIO()+ with wave.open(buf, "wb") as w:+ w.setparams((1, 2, 16000, 0, "NONE", "not compressed"))+ w.writeframes(b"\x01\x00" * 16000)++ async def chunks():+ yield buf.getvalue()++ return run_as(account, lambda: asyncio.run(audio_inputs.save_stream(chunks(), "me.wav"))[0])++[email protected]("account,other", [(ALICE, BOB), (BOB, ALICE)])+def test_audio_inputs_voices_and_clips_do_not_resolve_another_accounts_ids(+ account, other, monkeypatch+):+ from core.inference import audio_inputs, audio_voices++ async def fake_transcribe(*_args, **_kwargs):+ return {"text": "private words", "language": None}++ monkeypatch.setattr(inference, "_transcribe_audio_result", fake_transcribe)+ record = _save_input(account)+ path = run_as(account, audio_inputs.input_path, record["id"])+ voice = run_as(account, audio_voices.create, path, {"name": "p"})+ clip = run_as(account, _save, "audio")+ inputs = f"/api/inference/audio/inputs/{record['id']}"+ voices = "/api/inference/audio/voices"+ source = "/api/inference/audio/inputs/source/transcribe"+ model = {"model": "m"}+ with _client(other) as client:+ assert client.get(f"{inputs}/file").status_code == 404+ assert client.post(f"{inputs}/transcribe", json = model).status_code == 404+ assert client.delete(inputs).status_code == 404+ assert voice["id"] not in client.get(voices).text+ assert client.get(f"{voices}/{voice['id']}/file").status_code == 404+ assert client.patch(f"{voices}/{voice['id']}", json = {"name": "x"}).status_code == 404+ assert client.delete(f"{voices}/{voice['id']}").status_code == 404+ for params in ({"voice_id": voice["id"]}, {"clip_id": clip["id"]}):+ assert client.post(source, params = params, json = model).status_code == 404+ stolen = {"source": {"clip_id": clip["id"]}, "name": "stolen"}+ assert client.post(voices, json = stolen).status_code == 404+ with _client(account) as client:+ assert [v["id"] for v in client.get(voices).json()["voices"]] == [voice["id"]]+ assert client.get(f"{voices}/{voice['id']}/file").status_code == 200+ assert client.get(f"{inputs}/file").status_code == 200+ assert client.post(f"{inputs}/transcribe", json = model).json()["text"] == "private words"+ assert client.delete(inputs).json() == {"removed": True}+++def test_inputs_and_voices_live_in_the_accounts_audio_folder(tmp_path):+ from core.inference import audio_inputs, audio_voices++ bob = tmp_path / "accounts" / BOB.account_id / "audio"+ assert run_as(BOB, audio_inputs.inputs_dir) == bob / "inputs"+ assert run_as(BOB, audio_voices.voices_dir) == bob / "voices"+ assert run_as(OWNER, audio_inputs.inputs_dir) == tmp_path / "audio" / "inputs"diff --git a/studio/backend/tests/test_audio_cpp_clone_requests.py b/studio/backend/tests/test_audio_cpp_clone_requests.pynew file mode 100644index 00000000000..2a57bba500c--- /dev/null+++ b/studio/backend/tests/test_audio_cpp_clone_requests.py@@ -0,0 +1,276 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from __future__ import annotations++import base64+import io+import json+import wave+from dataclasses import replace++import huggingface_hub+import pytest++from core.inference import audio_cpp_backend as acb+from core.inference import audio_cpp_files+from core.inference import audio_cpp_models as acm+from core.inference import audio_cpp_server as srv+from core.inference.audio_cpp_models import AUDIO_CPP_REPO, AudioCppModel, AudioCppVariant, RepoFile++REF = "/srv/accounts/a/audio/inputs/0123.24000.mono.m30.wav"+EMOTION = "/srv/accounts/a/audio/inputs/4567.24000.mono.m30.wav"+TEXT = "The quick brown fox jumps over the lazy dog near the river bank."+T = "Okay, I'm Cemo and what you just heard wasn't a human voice."+ABSENT = object()+# Bound before any test swaps it for a recorder.+_REAL_START = srv.AudioCppServer.start+++def _wav(rate = 24000) -> bytes:+ with wave.open(buf := io.BytesIO(), "wb") as w:+ w.setparams((1, 2, rate, 0, "NONE", "not compressed"))+ w.writeframes(b"\x00\x00" * 240)+ return buf.getvalue()+++# fmt: off+def _bare(display, family, variant, **fields) -> AudioCppModel:+ return AudioCppModel(+ id = f"{AUDIO_CPP_REPO}/{display}", repo_id = AUDIO_CPP_REPO, folder = display,+ display_name = display, family = family, variant = variant, variants = (variant,),+ default_variant = "Q8_0", **fields,+ )+++def _model(family, display = None, spec = None, **kw,) -> AudioCppModel:+ policy = acm.family_policy(family, spec, kw.get("names", ()))+ variant = AudioCppVariant("Q8_0", (RepoFile("m-q8_0.gguf", 1),), "m-q8_0.gguf")+ return _bare(+ display or family, family, variant, task = policy.task, server_task = policy.default_server_task,+ request_defaults = dict(policy.request_defaults), model_options = dict(policy.model_options),+ options = tuple(kw.get("options", ())), speaks = policy.speaks, clone = policy.clone,+ companions = policy.companions, required_inputs = acm._required_inputs(spec, None, policy),+ )+++COSY_OPTIONS = ({+ "name": "template_name", "type": "enum", "description": "", "required": False, "default": None,+ "min": None, "max": None, "values": ["zero_shot", "cross_lingual", "instruct"],+},)+# fmt: on+QWEN = "Qwen3-TTS-12Hz-0.6B-Base-GGUF"+MODELS = {+ "qwen3": lambda: _model("qwen3_tts", QWEN, names = [QWEN, "qwen3-tts-12hz-0.6b-base-q8_0.gguf"]),+ "chatterbox": lambda: _model("chatterbox", "Chatterbox-GGUF"),+ "index": lambda: _model("index_tts2", "IndexTTS2-GGUF"),+ "vox": lambda: _model("voxcpm2", "VoxCPM2-GGUF"),+ "cosy": lambda: _model("cosyvoice3", "CosyVoice3-GGUF", options = COSY_OPTIONS),+ "f5": lambda: _model("f5_tts", "F5-TTS-GGUF"),+ "kokoro": lambda: _model("kokoro_tts", "Kokoro-82M-GGUF"),+ "vibevoice": lambda: _model("vibevoice", "VibeVoice-1.5B-GGUF"),+}+++class _Recorder:+ model_id, backend = "studio-test", "cpu"+ alive = staticmethod(lambda: True)+ stop = staticmethod(lambda: None)++ def __init__(self, model):+ self.model, self.calls = model, []++ def post_json(self, path, payload, **_kwargs):+ self.calls.append((path, json.loads(json.dumps(payload))))+ if path == "/v1/tasks/run":+ body = {"audio": base64.b64encode(_wav(22050)).decode(), "sample_rate": 22050}+ return "application/json", json.dumps(body).encode()+ return "audio/wav", _wav()+++def _backend(model):+ backend = acb.AudioCppBackend()+ server = _Recorder(model)+ backend._server, backend._model = server, model+ backend.models, backend.active_model_name = {model.id: {"is_audio": True}}, model.id+ return backend, server+++def _clone(key, **kwargs):+ backend, server = _backend(MODELS[key]())+ inputs = kwargs.pop("audio_inputs", {"reference": REF})+ wav, rate = backend.generate_audio_response(+ TEXT, workflow = "clone", audio_inputs = inputs, seed = 7, **kwargs+ )+ assert wav[:4] == b"RIFF" and rate > 0+ (call,) = server.calls+ return call+++BASE = {"model": "studio-test", "input": TEXT, "voice_ref": REF, "seed": "7"}+SPEECH, TASKS = "/v1/audio/speech", "/v1/tasks/run"+++# fmt: off[email protected]("key, kwargs, expect", [+ ("qwen3", {"reference_text": T, "language": "en"}, {**BASE, "reference_text": T, "language": "English"}),+ ("chatterbox", {"reference_text": T, "audio_options": {"exaggeration": 0.7, "guidance_scale": 9, "temperature": 0.1}},+ {**BASE, "options": {"exaggeration": "0.7", "guidance_scale": "5"}}),+ # Emotion audio switches to the tasks endpoint with top-level audio.+ ("index", {"audio_inputs": {"reference": REF, "emotion": EMOTION}, "audio_options": {"emotion_alpha": 0.7}},+ {"path": TASKS, "model": "studio-test", "text": TEXT, "voice_ref": REF, "audio": EMOTION,+ "options": {"emotion_alpha": "0.7"}, "seed": "7"}),+ ("qwen3", {"language": "Japanese"}, {"language": "Japanese"}),+ ("qwen3", {"language": "pt-BR"}, {"language": "Portuguese"}),+ # Auto and unknown codes are left out rather than refused at runtime.+ ("qwen3", {"language": "auto"}, {"language": ABSENT}),+ ("qwen3", {"language": "xx"}, {"language": ABSENT}),+ ("qwen3", {"reference_text": T, "audio_options": {"x_vector_only_mode": True, "bogus_key": "1"}},+ {"options": {"x_vector_only_mode": "true"}, "reference_text": ABSENT}),+ ("qwen3", {"reference_text": T, "speed": 1.3}, {"speed": ABSENT}),+ ("index", {"reference_text": T, "audio_options": {"emotion_vector": "0.8,0,0,0,0,0,0.2,0", "emotion_alpha": 0.7}},+ {"options": {"emotion_vector": "0.8,0,0,0,0,0,0.2,0", "emotion_alpha": "0.7"}, "reference_text": ABSENT}),+ ("index", {"audio_options": {"use_emotion_text": True, "emotion_text": "Excited."}},+ {"options": {"use_emotion_text": "true", "emotion_text": "Excited."}}),+ ("vox", {"audio_inputs": {"reference": REF, "emotion": EMOTION}}, {"audio": ABSENT}),+ ("cosy", {"instructions": "Sadly.", "audio_options": {"template_name": "instruct", "bogus_key": "x"}},+ {"options": {"template_name": "instruct"}, "instructions": "Sadly."}),+ ("cosy", {"reference_text": T}, {"reference_text": T, "instructions": ABSENT}),+ ("cosy", {"reference_text": T, "audio_options": {"template_name": "cross_lingual"}}, {"reference_text": ABSENT}),+ ("cosy", {"reference_text": T, "instructions": "Whisper.", "audio_options": {"template_name": "instruct"}},+ {"reference_text": T}),+ ("f5", {"reference_text": T, "speed": 1.3}, {"speed": 1.3, "reference_text": T, "options": ABSENT}),+ ("f5", {"reference_text": T, "speed": 9}, {"speed": 2.0}),+])+# fmt: on+def test_clone_request_body(key, kwargs, expect):+ path, body = _clone(key, **kwargs)+ expect = dict(expect)+ assert path == expect.pop("path", SPEECH)+ assert {k: body.get(k, ABSENT) for k in expect} == expect+ if "model" in expect: # full-body rows+ assert body.keys() == expect.keys()+++def test_voxcpm2_speak_body_is_unchanged_by_clone_support():+ backend, server = _backend(MODELS["vox"]())+ backend.generate_audio_response(TEXT, seed = 7, language = "en", instructions = "warm")+ body = {"model": "studio-test", "input": TEXT, "options": {"instruct": "warm", "language": "en"}}+ assert server.calls == [(SPEECH, {**body, "seed": "7"})]+++# fmt: off[email protected]("key, text, sent", [+ ("vibevoice", "Hello there.", "Speaker 1: Hello there."),+ ("vibevoice", "Speaker 1: Hi.\nSpeaker 2: Hello.", "Speaker 1: Hi.\nSpeaker 2: Hello."),+ ("vibevoice", " speaker 2 : already labelled", " speaker 2 : already labelled"),+ ("kokoro", "Hello there.", "Hello there."),+])+# fmt: on+def test_speaker_label_added_only_for_unlabelled_vibevoice(key, text, sent):+ backend, server = _backend(MODELS[key]())+ backend.generate_audio_response(text)+ assert server.calls[0][1]["input"] == sent+++def test_a_speak_only_model_refuses_a_clone_request():+ backend, server = _backend(MODELS["kokoro"]())+ with pytest.raises(RuntimeError, match = "cannot clone"):+ backend.generate_audio_response(TEXT, workflow = "clone", audio_inputs = {"reference": REF})+ assert server.calls == []+++def test_status_fields_name_the_clone_workflow_and_transcript_rule():+ f = acb.model_info_fields(MODELS["qwen3"]())+ assert (f["audio_workflows"], f["audio_reference_text"]) == (["clone"], "required")+ assert f["audio_required_inputs"] == []+ assert f["audio_clone"]["reference_text_waived"] == [["x_vector_only_mode", ["true"]]]+ for key, workflows, rt in (("vox", ["speak", "clone"], "optional"), ("kokoro", ["speak"], None)):+ f = acb.model_info_fields(MODELS[key]())+ assert (f["audio_workflows"], f["audio_reference_text"]) == (workflows, rt)+ cosy = acb.model_info_fields(MODELS["cosy"]())["audio_clone"]+ assert cosy["reference_text_waived"] == [["template_name", ["cross_lingual", "instruct"]]]+ instruct = {"name": "instruct", "type": "string", "required": True}+ maya = _model("maya1", "Maya1-GGUF", {"tasks": ["tts"], "options": {"request": [instruct]}})+ assert acb.model_info_fields(maya)["audio_required_inputs"] == ["instruct"]+ # Models are cache keys; tool option dicts must stay out of the hash.+ for model in (MODELS["qwen3"](), _model("chatterbox"), _model("index_tts2"), _model("miotts")):+ hash(model)+ hash(acm.FAMILIES["chatterbox"])+ for model in (MODELS["qwen3"](), _model("chatterbox"), _model("index_tts2"), _model("miotts")):+ hash(model)+ hash(acm.FAMILIES["chatterbox"])+++def _server_entry(monkeypatch, tmp_path, model):+ seen = {}+ (binary := tmp_path / srv.BINARY_NAME).write_bytes(b"")++ def spy(command, *_args, **_kwargs):+ with open(command[command.index("--config") + 1], encoding = "utf-8") as f:+ seen.update(json.load(f))+ raise OSError("not launched in tests")++ monkeypatch.setattr(srv, "ensure_binary", lambda: str(binary))+ monkeypatch.setattr(srv, "model_runtime_problem", lambda model, binary = None: None)+ monkeypatch.setattr(srv, "select_backend", lambda binary, force_cpu: "cpu")+ monkeypatch.setattr(srv.subprocess, "Popen", spy)+ with pytest.raises(srv.AudioCppUnavailableError):+ _REAL_START(model, "/models/m-q8_0.gguf")+ (entry,) = seen["models"]+ return entry+++# fmt: off[email protected]("family, display, task", [+ ("chatterbox", "Chatterbox-GGUF", "clon"), ("chatterbox_turbo", "Chatterbox-Turbo-GGUF", "tts"),+])+# fmt: on+def test_chatterbox_server_task(monkeypatch, tmp_path, family, display, task):+ model = _model(family, display)+ assert model.server_task == task+ if task == "tts":+ assert list(model.workflows) == ["speak"]+ entry = _server_entry(monkeypatch, tmp_path, model)+ assert (entry["family"], entry["task"]) == (family, task)+++def test_miotts_downloads_mio_codec_and_starts_with_its_path(monkeypatch, tmp_path):+ model = _model("miotts", "MioTTS-1.7B-GGUF")+ assert list(model.workflows) == ["clone"]+ codec_file = "MioCodec-25Hz-44.1kHz-v2-GGUF/miocodec-25hz-44khz-v2-q8_0.gguf"+ codec_variant = AudioCppVariant("Q8_0", (RepoFile(codec_file, 299),), codec_file)+ codec = _bare(+ "MioCodec-25Hz-44.1kHz-v2-GGUF", "miocodec", codec_variant, task = "", server_task = "",+ unsupported = "MioCodec is the codec MioTTS loads with; pick MioTTS to use it.",+ )+ resolved, downloads, started = [], [], []++ def resolve(identifier, *args, **_kw):+ resolved.append((identifier, *args[:1]))+ return codec if identifier == codec.id else None++ codec_path = str(tmp_path / "farm" / "miocodec-25hz-44khz-v2-q8_0.gguf")+ is_codec = lambda m: m.family == "miocodec"+ monkeypatch.setattr(acb, "resolve", resolve)+ monkeypatch.setattr(audio_cpp_files, "missing_files", lambda m: [(codec_file, 1)] * is_codec(m))+ monkeypatch.setattr(huggingface_hub, "hf_hub_download", lambda r, p, **kw: downloads.append((r, p)))+ tts_path = str(tmp_path / "farm" / "miotts.gguf")+ monkeypatch.setattr(audio_cpp_files, "materialize", lambda m: codec_path if is_codec(m) else tts_path)+ start = lambda served, path, **_kw: started.append((served, path)) or _Recorder(served)+ monkeypatch.setattr(acb.AudioCppServer, "start", start)+ backend = acb.AudioCppBackend()+ backend._ensure_downloaded(model, None)+ assert downloads == [(AUDIO_CPP_REPO, codec_file)]+ assert (codec.id, "Q8_0") in resolved+ backend._start_server(model)+ ((served, path),) = started+ assert path.endswith("miotts.gguf")+ assert served.model_options["session_options"] == {"miotts.codec_model_path": codec_path}+ # Equal to the requested model, so the next request does not restart the server.+ assert served == model+ entry = _server_entry(monkeypatch, tmp_path, replace(model, model_options = served.model_options))+ assert entry["session_options"] == {"miotts.codec_model_path": codec_path}+ assert entry["task"] == "tts"+ kokoro = MODELS["kokoro"]()+ assert acb._with_companions(kokoro) is kokorodiff --git a/studio/backend/tests/test_audio_cpp_models.py b/studio/backend/tests/test_audio_cpp_models.pyindex 3e43dca324f..64753081e6e 100644--- a/studio/backend/tests/test_audio_cpp_models.py+++ b/studio/backend/tests/test_audio_cpp_models.py@@ -317,7 +317,7 @@ def test_an_unknown_family_follows_its_spec_tasks_or_is_refused(hub):("new_music", ["music"], "music", "gen"),("new_clone_music", ["clone", "music"], "music", "gen"),("new_clone_asr", ["clone", "asr"], "asr", "asr"),- ("new_clone_only", ["clone"], "", ""),+ ("new_clone_only", ["clone"], "tts", "clon"),("new_sep", ["sep"], "", ""),):repo = f"someone/{family}-GGUF"@@ -328,7 +328,7 @@ def test_an_unknown_family_follows_its_spec_tasks_or_is_refused(hub):sep = acm.resolve("someone/new_sep-GGUF", network = False)assert "Source separation" in sep.unsupportedclone_only = acm.resolve("someone/new_clone_only-GGUF", network = False)- assert "only clones a reference voice" in clone_only.unsupported+ assert list(clone_only.workflows) == ["clone"] and clone_only.clone.reference_text == "optional"def test_unsupported_task_tokens_are_refused_by_a_readable_name(hub):@@ -430,7 +430,7 @@ def test_a_spec_fallback_family_the_runtime_lacks_is_refused(hub, monkeypatch, tsamsone = acm.resolve(f"{AUDIO_CPP_REPO}/Samsone-GGUF", network = False)assert (samsone.task, samsone.unsupported) == ("asr", None)crisper = acm.resolve(f"{AUDIO_CPP_REPO}/CrisperWhisper2.0-GGUF", network = False)- assert crisper.task == ""+ assert crisper.task == "" and crisper.workflows == {}assert crisper.unsupported == ("CrisperWhisper2.0-GGUF needs a newer audio runtime than the one installed.")@@ -472,7 +472,80 @@ def test_qwen3_tts_package_kind_comes_from_its_name(hub):voice["default"] == "vivian" and len(voice["values"]) == 9 and "uncle_fu" in voice["values"])assert not any(o["name"] == "voice" for o in design.options)- assert "reference voice" in base.unsupported+ assert base.unsupported is None and list(base.workflows) == ["clone"]+ assert base.clone.reference_text == "required" and base.clone.language_names+ assert [o["name"] for o in base.clone.tool_options] == ["x_vector_only_mode"]+ assert list(custom.workflows) == ["speak"] and list(design.workflows) == ["speak"]+++# family -> (server task, speaks, reference_text), from the audio.cpp sources.+_CLONE_TABLE = {+ "chatterbox": ("clon", False, "unused"),+ "f5_tts": ("tts", False, "required"),+ "index_tts2": ("tts", False, "unused"),+ "cosyvoice3": ("tts", False, "required"),+ "voxcpm2": ("tts", True, "optional"),+ "fish_audio": ("tts", True, "required"),+ "echo_tts": ("clon", False, "unused"),+ "confucius4_tts": ("clon", False, "unused"),+ "fireredtts3": ("tts", False, "optional"),+ "firered_audio": ("tts", False, "optional"),+ "vevo2": ("tts", False, "unused"),+ "miotts": ("tts", False, "unused"),+}+++def test_every_task_family_binds_its_workflows():+ workflow_for = {"tts": "speak", "music": "music", "asr": "transcribe"}+ endpoint_for = {"speak": "speech", "music": "tasks", "transcribe": "transcriptions"}+ for family in acm.FAMILIES.values():+ bindings = family.workflows+ if not family.task:+ assert bindings == {}, family.family+ continue+ if family.clone is not None:+ server_task, speaks, reference_text = _CLONE_TABLE[family.family]+ expected = (["speak"] if speaks else []) + ["clone"]+ assert list(bindings) == expected, family.family+ assert family.default_server_task == server_task, family.family+ assert family.clone.reference_text == reference_text, family.family+ clone = bindings["clone"]+ assert (clone.endpoint, clone.server_task) == ("speech", server_task)+ continue+ assert family.family not in _CLONE_TABLE+ ((workflow, binding),) = bindings.items()+ assert workflow == workflow_for[family.task], family.family+ assert binding.endpoint == endpoint_for[workflow]+ assert binding.server_task == family.default_server_task+ assert set(_CLONE_TABLE) == {f.family for f in acm.FAMILIES.values() if f.clone is not None}+ assert acm.family_from_names(["Chatterbox-Turbo-GGUF", "chatterbox-turbo-q8_0.gguf"]) == (+ "chatterbox_turbo"+ )+ base = acm.family_policy("fireredtts3", names = ["FireRedTTS3-Base-GGUF"])+ assert base.default_server_task == "clon" and list(base.workflows) == ["clone"]+ (codec,) = acm.FAMILIES["miotts"].companions+ assert codec.id == f"{AUDIO_CPP_REPO}/MioCodec-25Hz-44.1kHz-v2-GGUF"+ assert (codec.variant, codec.session_option) == ("Q8_0", "miotts.codec_model_path")+ assert "pick MioTTS" in acm.family_policy("miocodec").unsupported+ assert acm.FAMILIES["kokoro_tts"].workflows["speak"].server_task == "tts"+ assert acm.FAMILIES["moss_voicegen"].workflows["speak"].server_task == "vdes"+ assert acm.FAMILIES["ace_step"].workflows["music"] == acm.WorkflowBinding(+ "gen", "tasks", None, ("text", "lyrics", "duration_seconds")+ )+ assert acm.FAMILIES["moonshine_asr"].workflows["transcribe"].inputs == ("audio",)+ design = acm.family_policy("qwen3_tts", names = ["Qwen3-TTS-12Hz-1.7B-VoiceDesign-GGUF"])+ assert design.workflows["speak"].server_task == "vdes"+ assert acm.family_policy("htdemucs").workflows == {}+++def test_a_resolved_model_carries_its_workflow_binding(hub):+ snap = _snapshot(hub)+ folder = "Qwen3-TTS-12Hz-1.7B-VoiceDesign-GGUF"+ _put(snap, f"{folder}/{folder.lower()}-q8_0.gguf", _gguf_bytes(family = "qwen3_tts"))+ model = acm.resolve(f"{AUDIO_CPP_REPO}/{folder}", network = False)+ assert list(model.workflows) == ["speak"] and model.workflows["speak"].server_task == "vdes"+ _put(snap, "HTDemucs-GGUF/htdemucs-q8_0.gguf", _gguf_bytes(family = "htdemucs"))+ assert acm.resolve(f"{AUDIO_CPP_REPO}/HTDemucs-GGUF", network = False).workflows == {}def test_sub_folders_and_same_quant_files_become_named_variants(hub):@@ -1976,3 +2049,27 @@ def test_missing_files_are_counted_in_the_snapshot_downloads_land_in(hub):_put(main, gguf.path, b"GGUF")_put(main, voice.path, b"v")assert audio_cpp_files.missing_files(model, hub_cache = hub) == []+++def test_required_inputs_come_from_the_raw_spec(hub):+ snap = _snapshot(hub)+ maya_spec = {+ "family": "maya1",+ "tasks": ["tts"],+ "options": {+ "request": [+ {"name": "instruct", "type": "string", "required": True},+ {"name": "temperature", "type": "float"},+ ]+ },+ }+ _put(snap, "Maya1-GGUF/maya1-q8_0.gguf", _gguf_bytes(family = "maya1", spec = maya_spec))+ maya = acm.resolve(f"{AUDIO_CPP_REPO}/Maya1-GGUF", network = False)+ # instruct travels as the request's description, not as an option.+ assert maya.required_inputs == ("instruct",)+ assert [o["name"] for o in maya.options] == ["temperature"]+ # A voice-design package fills instruct itself.+ folder = "Qwen3-TTS-12Hz-1.7B-VoiceDesign-GGUF"+ design_spec = {**maya_spec, "family": "qwen3_tts"}+ _put(snap, f"{folder}/m-q8_0.gguf", _gguf_bytes(family = "qwen3_tts", spec = design_spec))+ assert acm.resolve(f"{AUDIO_CPP_REPO}/{folder}", network = False).required_inputs == ()diff --git a/studio/backend/tests/test_audio_gallery.py b/studio/backend/tests/test_audio_gallery.pyindex 32691d01146..5cb0115281a 100644--- a/studio/backend/tests/test_audio_gallery.py+++ b/studio/backend/tests/test_audio_gallery.py@@ -759,3 +759,37 @@ def test_the_clear_route_scopes_to_a_workflow():}assert [r["id"] for r in gallery.list_audio()] == [song["id"]]assert asyncio.run(clear_gallery_audio(current_subject = "tester")) == {"removed": 1}+++def test_a_clone_clip_keeps_its_workflow_and_run_fields_and_survives_a_speak_clear():+ from models.inference import AudioGalleryItem+ from routes.inference import _persist_tts_clip++ run = {"voice_id": "v" * 32, "settings": {"reference_text_used": True}, "source_clip_id": None}+ speech = gallery.save(_wav(), _meta())+ clone = _persist_tts_clip(_wav(), 24000, "hi", "qwen3-base", "audiocpp_tts", run, "clone")+ meta = json.loads((gallery.gallery_dir() / f"{clone['id']}.json").read_text(encoding = "utf-8"))+ assert meta["workflow"] == "clone" and "source_clip_id" not in meta+ (item,) = [AudioGalleryItem(**r) for r in gallery.list_audio() if r["id"] == clone["id"]]+ assert (+ item.workflow == "clone"+ and item.voice_id == "v" * 32+ and item.settings["reference_text_used"] is True+ )+ # Its audio type alone would read as speak.+ assert gallery.set_flags(clone["id"], pinned = True)["workflow"] == "clone"+ assert gallery.clear(workflow = "speak") == 1+ assert gallery.audio_path(speech["id"]) is None+ assert [r["id"] for r in gallery.list_audio()] == [clone["id"]]+++def test_the_inputs_and_voices_folders_never_list_as_clips():+ gallery.save(_wav(), _meta())+ for folder in ("inputs", "voices"):+ directory = gallery.gallery_dir() / folder+ directory.mkdir(exist_ok = True)+ (directory / "abc.wav").write_bytes(_wav())+ (directory / "abc.json").write_text(json.dumps(_meta()), encoding = "utf-8")+ assert len(gallery.list_audio()) == 1+ assert gallery.clear() == 1+ assert (gallery.gallery_dir() / "inputs" / "abc.wav").is_file()diff --git a/studio/backend/tests/test_audio_inputs.py b/studio/backend/tests/test_audio_inputs.pynew file mode 100644index 00000000000..7112feeadf6--- /dev/null+++ b/studio/backend/tests/test_audio_inputs.py@@ -0,0 +1,303 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from __future__ import annotations++import asyncio+import io+import math+import os+import time+import wave+from urllib.parse import quote++import av+import numpy as np+import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++import core.inference.audio_gallery as gallery+import utils.upload_limits as limits+from auth.authentication import get_current_subject+from core.inference import audio_inputs++INPUTS = "/api/inference/audio/inputs"++[email protected](autouse = True)+def _tmp_gallery(monkeypatch, tmp_path):+ monkeypatch.setattr(gallery, "studio_root", lambda: tmp_path)+++def encode(+ fmt: str,+ codec: str,+ rate: int,+ layout: str,+ seconds: float,+ freq: float = 440.0,+) -> bytes:+ channels = {"stereo": 2, "5.1": 6}.get(layout, 1)+ count = int(round(rate * seconds))+ tone = (0.3 * np.sin(2 * math.pi * freq * np.arange(count) / rate) * 32767).astype(np.int16)+ packed = np.repeat(tone, channels).reshape(1, -1)+ buf = io.BytesIO()+ with av.open(buf, mode = "w", format = fmt) as out:+ stream = out.add_stream(codec, rate = rate, layout = layout)+ step = rate // 50 # 20 ms frames, as a recorder delivers them+ for start in range(0, count, step):+ chunk = packed[:, start * channels : min(count, start + step) * channels]+ arr = np.ascontiguousarray(chunk)+ frame = av.AudioFrame.from_ndarray(arr, format = "s16", layout = layout)+ frame.sample_rate, frame.pts = rate, start+ for packet in stream.encode(frame):+ out.mux(packet)+ for packet in stream.encode(None):+ out.mux(packet)+ return buf.getvalue()+++def wav_bytes(seconds = 1.0, rate = 16000) -> bytes:+ return encode("wav", "pcm_s16le", rate, "mono", seconds)+++async def _chunks(parts, seen = None):+ for part in parts:+ if seen is not None:+ seen.append(len(part))+ yield part+++def _save(data: bytes, name = "clip.wav") -> dict:+ return asyncio.run(audio_inputs.save_stream(_chunks([data]), name))[0]+++def _clip(rate = 16000, audio_type = "snac") -> dict:+ meta = {"prompt": "p", "model": "m", "audio_type": audio_type, "sample_rate": rate}+ meta.update(duration_s = 1.0, created_at = "2026-10-02T00:00:00Z")+ return gallery.save(wav_bytes(rate = rate), meta)+++def _frames(path) -> tuple[int, int, int]:+ with wave.open(str(path)) as w:+ return w.getframerate(), w.getnchannels(), w.getnframes()+++def client():+ from routes import inference++ app = FastAPI()+ app.dependency_overrides[get_current_subject] = lambda: "tester"+ app.include_router(inference.studio_router, prefix = "/api/inference")+ yield TestClient(app)+++def _upload(client, data: bytes, name: str):+ headers = {"Content-Type": "application/octet-stream"}+ return client.post(INPUTS, params = {"name": name}, content = data, headers = headers)+++def _video_without_audio() -> bytes:+ buf = io.BytesIO()+ with av.open(buf, mode = "w", format = "matroska") as out:+ stream = out.add_stream("ffv1", rate = 1)+ stream.width = stream.height = 16+ stream.pix_fmt = "yuv420p"+ frame = av.VideoFrame.from_ndarray(np.zeros((16, 16, 3), dtype = np.uint8), format = "rgb24")+ for packet in [*stream.encode(frame), *stream.encode(None)]:+ out.mux(packet)+ return buf.getvalue()+++ "fmt, codec, rate, layout, name, channels",+ [+ ("webm", "libopus", 48000, "stereo", "recording.webm", 2),+ ("mp3", "libmp3lame", 44100, "mono", "voice.mp3", 1),+ ("wav", "pcm_s16le", 16000, "mono", "voice.wav", 1),+ ("wav", "pcm_s16le", 24000, "5.1", "surround.wav", 2),+ ("flac", "flac", 96000, "stereo", "hires.flac", 2),+ ],+)+def test_an_upload_decodes_dedupes_and_deletes(client, fmt, codec, rate, layout, name, channels):+ data = encode(fmt, codec, rate, layout, 2.0)+ response = _upload(client, data, f"C:\\Users\\me\\{name}")+ assert response.status_code == 201, response.text+ record = response.json()+ assert set(record) == set("id name duration_s sample_rate channels url expires_at".split())+ got = (record["name"], record["sample_rate"], record["channels"], round(record["duration_s"]))+ rate = min(rate, audio_inputs.MAX_RATE)+ assert got == (name, rate, channels, 2)+ assert record["url"] == f"{INPUTS}/{record['id']}/file"+ served = client.get(record["url"])+ assert served.status_code == 200 and served.headers["content-type"] == "audio/wav"+ with wave.open(io.BytesIO(served.content)) as w:+ assert (w.getframerate(), w.getnchannels(), w.getsampwidth()) == (rate, channels, 2)+ assert (directory := audio_inputs.inputs_dir()) == gallery.gallery_dir() / "inputs"+ again = _upload(client, data, "other.wav")+ assert again.status_code == 200+ # A re-upload refreshes the expiry, which can cross a second boundary.+ reused = again.json()+ assert reused.pop("expires_at") >= record["expires_at"]+ assert reused == {k: v for k, v in record.items() if k != "expires_at"}+ assert len(list(directory.glob("*.json"))) == 1+ assert audio_inputs.prepare_reference({"input_id": record["id"]})[1].is_file()+ assert client.delete(f"{INPUTS}/{record['id']}").json() == {"removed": True}+ assert client.get(record["url"]).status_code == 404+ assert client.delete(f"{INPUTS}/{record['id']}").status_code == 404+ assert not list(directory.iterdir())+++def test_an_oversize_body_is_refused_while_streaming():+ seen: list[int] = []+ with pytest.raises(audio_inputs.AudioInputError) as refused:+ body = _chunks([b"\x00" * 1024] * 100, seen)+ asyncio.run(audio_inputs.save_stream(body, "big.wav", max_bytes = 4096))+ assert (refused.value.status, refused.value.detail) == (413, "Audio is too large.")+ # Refused at the chunk that crossed the cap: the rest of the body was never read.+ assert len(seen) == 5+ assert not list(audio_inputs.inputs_dir().iterdir())+++ "patches, make, status, detail",+ [+ ({"AUDIO_INPUT_MAX_BYTES": 2048}, lambda: wav_bytes(2.0), 413, "Audio is too large."),+ ({"MAX_SECONDS": 1}, lambda: wav_bytes(2.0), 413, "Audio is longer than 0 minutes."),+ ({}, lambda: b"", 400, "Audio is empty."),+ ({}, lambda: b"not audio " * 120, 400, "This file is not audio Studio can read."),+ ({}, _video_without_audio, 400, "This file has no audio stream."),+ ],+)+def test_bad_or_over_cap_uploads_are_refused(client, monkeypatch, patches, make, status, detail):+ for attr, value in patches.items():+ monkeypatch.setattr(audio_inputs, attr, value)+ monkeypatch.setattr(limits, attr, value, raising = False)+ response = _upload(client, make(), "clip.mkv")+ assert response.status_code == status and response.json()["detail"] == detail+ assert not list(audio_inputs.inputs_dir().glob("*.wav"))+++def test_the_body_middleware_passes_the_upload_through_at_its_own_cap():+ import main++ assert limits.AUDIO_INPUT_MAX_BYTES == 200 * 1024 * 1024+ for path in (INPUTS, f"{INPUTS}/"):+ assert main._get_upload_passthrough_request_max_bytes(path) == limits.AUDIO_INPUT_MAX_BYTES+ assert f"{INPUTS}/x/transcribe" not in main._BODY_UPLOAD_PASSTHROUGH_EXACT_PATHS+++def test_the_sweep_drops_the_oldest_past_the_byte_cap_then_all_past_the_ttl(client, monkeypatch):+ clock = [1_000_000.0]+ monkeypatch.setattr(audio_inputs, "_now", lambda: clock[0])+ ids = []+ for freq in (300.0, 500.0, 700.0):+ ids.append(_save(encode("wav", "pcm_s16le", 16000, "mono", 0.5, freq), "a.wav")["id"])+ clock[0] += 10+ one = (audio_inputs.inputs_dir() / f"{ids[0]}.wav").stat().st_size+ assert audio_inputs.sweep(byte_cap = int(one * 2.5)) == 1+ assert [audio_inputs.input_path(i) is not None for i in ids] == [False, True, True]+ assert audio_inputs.prepare_reference({"input_id": ids[1]})[1].is_file()+ clock[0] += audio_inputs.TTL_SECONDS + 1+ assert client.get(f"{INPUTS}/{ids[2]}/file").status_code == 404+ assert audio_inputs.sweep() == 2+ assert not list(audio_inputs.inputs_dir().iterdir())+++def test_expired_inputs_are_swept_without_waiting_for_another_upload(monkeypatch, tmp_path):+ from auth import storage++ clock = [1_000_000.0]+ monkeypatch.setattr(audio_inputs, "_now", lambda: clock[0])+ input_id = _save(wav_bytes(0.5), "a.wav")["id"]+ clock[0] += audio_inputs.TTL_SECONDS + 1+ # An account that never uploaded gets no inputs folder from the sweep.+ other = {"account_id": "acct-b", "username": "bob", "role": "user"}+ monkeypatch.setattr(storage, "list_accounts", lambda: [other])+ monkeypatch.setattr(audio_inputs, "account_path", lambda rel: tmp_path / "acct-b" / rel)+ assert audio_inputs.sweep_all_accounts() == 1+ assert audio_inputs.input_path(input_id) is None+ assert not (tmp_path / "acct-b").exists()+++def test_a_prepared_reference_is_24k_mono_cut_to_thirty_seconds_and_cached():+ record = _save(wav_bytes(seconds = 31.0, rate = 8000), "long.wav")+ source, path = audio_inputs.prepare_reference({"input_id": record["id"]})+ assert (source.kind, source.name) == ("input", "long.wav")+ assert _frames(path) == (24000, 1, 30 * 24000)+ assert path.parent == audio_inputs.inputs_dir() and path.name.startswith(record["id"])+ mtime = path.stat().st_mtime_ns+ assert audio_inputs.prepare_reference({"input_id": record["id"]})[1].stat().st_mtime_ns == mtime+ assert _frames(audio_inputs.prepared_path(source, 24000, max_seconds = 1.0))[2] == 24000+++def test_preparing_a_clip_copy_sweeps_expired_copies_without_an_upload(tmp_path):+ # Cloning from history never uploads, so the sweep has to run from here too.+ directory = audio_inputs.inputs_dir()+ stale = directory / "c-old.24000.mono.m30.wav"+ stale.write_bytes(wav_bytes(0.2))+ old = time.time() - audio_inputs.TTL_SECONDS - 60+ os.utime(stale, (old, old))+ clip = tmp_path / "clip.wav"+ clip.write_bytes(wav_bytes(0.5))+ source = audio_inputs.Source(kind = "clip", id = "fresh", path = clip, name = "clip.wav")+ fresh = audio_inputs.prepared_path(source, 24000, max_seconds = 30.0)+ assert fresh.is_file() and not stale.exists()++[email protected]("bad", ["../escape", "a/b", "..", "x" * 129, "name.wav", ""])+def test_unsafe_ids_resolve_to_nothing(client, bad):+ assert audio_inputs.input_path(bad) is None+ assert audio_inputs.delete(bad) is False+ with pytest.raises(audio_inputs.AudioInputError) as refused:+ audio_inputs.resolve_source({"input_id": bad or None})+ assert refused.value.status in (400, 404)+ if bad:+ assert client.get(f"{INPUTS}/{quote(bad, safe = '')}/file").status_code == 404+ assert client.delete(f"{INPUTS}/{quote(bad, safe = '')}").status_code == 404+++def test_transcribe_sends_a_16k_mono_copy_and_saves_nothing(client, monkeypatch):+ from routes import inference++ calls, model = [], "audio-cpp/audio.cpp-gguf/Qwen3-ASR-0.6B-GGUF"++ async def fake_transcribe(raw, model, language, fast, engine, request, device):+ with wave.open(io.BytesIO(raw)) as w:+ calls.append((w.getframerate(), w.getnchannels(), model, language, engine, device))+ return {"text": " Okay, I'm Cemo. ", "language": "English"}++ monkeypatch.setattr(inference, "_transcribe_audio_result", fake_transcribe)+ record = _upload(client, encode("webm", "libopus", 48000, "stereo", 1.0), "r.webm").json()+ url = f"{INPUTS}/{record['id']}/transcribe"+ response = client.post(url, json = {"model": model, "device": "cpu"})+ assert response.json() == {"text": "Okay, I'm Cemo.", "language": "English", "model": model}+ assert calls == [(16000, 1, model, None, None, "cpu")]+ source, clip_q = f"{INPUTS}/source/transcribe", {"clip_id": _clip()["id"]}+ assert client.post(source, params = clip_q, json = {"model": "m"}).status_code == 200+ # Two sources, or none, are refused; a path is not a field.+ assert client.post(url, params = clip_q, json = {"model": "m"}).status_code == 400+ assert client.post(source, json = {"model": "m"}).status_code == 400+ assert client.post(url, json = {"model": "m", "path": "/etc/passwd"}).status_code == 422+ assert [r["id"] for r in gallery.list_audio()] == [clip_q["clip_id"]]+++def test_the_byte_cap_counts_only_kept_inputs(client, monkeypatch):+ clock = [1_000_000.0]+ monkeypatch.setattr(audio_inputs, "_now", lambda: clock[0])+ small = _save(encode("wav", "pcm_s16le", 16000, "mono", 0.5, 300.0), "s.wav")["id"]+ clock[0] += 10+ big = _save(encode("wav", "pcm_s16le", 16000, "mono", 2.0, 500.0), "b.wav")["id"]+ clock[0] += 10+ new = _save(encode("wav", "pcm_s16le", 16000, "mono", 0.5, 700.0), "n.wav")["id"]+ size = lambda i: (audio_inputs.inputs_dir() / f"{i}.wav").stat().st_size+ # Newest + small fit; the big one in the middle does not, and evicting it frees its bytes.+ cap = size(new) + size(small) + 10+ assert audio_inputs.sweep(byte_cap = cap) == 1+ assert [audio_inputs.input_path(i) is not None for i in (small, big, new)] == [+ True,+ False,+ True,+ ]diff --git a/studio/backend/tests/test_audio_run_route.py b/studio/backend/tests/test_audio_run_route.pynew file mode 100644index 00000000000..e3dd4cb6e94--- /dev/null+++ b/studio/backend/tests/test_audio_run_route.py@@ -0,0 +1,506 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""POST /audio/run: ids in, server-chosen account paths out, never a client path or audio bytes."""++from __future__ import annotations++import asyncio+import contextlib+import base64+import io+import json+import queue+import sys+import threading+import wave+from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from auth.authentication import authenticated_via_api_key, get_current_subject+from core.inference import audio_gallery, audio_inputs, audio_voices+from routes import inference+from utils.account_context import bind_account, reset_account, run_as++_TESTS_DIR = str(Path(__file__).resolve().parent)+if _TESTS_DIR not in sys.path:+ sys.path.insert(0, _TESTS_DIR)++from test_account_media_isolation import ALICE, BOB, isolated # noqa: E402,F401+from test_audio_inputs import _chunks, encode # noqa: E402++QWEN3_BASE = "audio-cpp/audio.cpp-gguf/Qwen3-TTS-12Hz-0.6B-Base-GGUF"+CLONE_FIELDS = {"workflow", "audio_inputs", "reference_text", "speed"}+++def _wav(rate = 24000, frames = 2400) -> bytes:+ buf = io.BytesIO()+ with wave.open(buf, "wb") as w:+ w.setnchannels(1)+ w.setsampwidth(2)+ w.setframerate(rate)+ w.writeframes(b"\x01\x00" * frames)+ return buf.getvalue()+++def _clone_info(+ workflows = ("clone",),+ reference_text = "required",+ emotion = False,+ waived = None,+):+ return {+ "is_audio": True,+ "audio_type": "audiocpp_tts",+ "audio_family": "qwen3_tts",+ "audio_workflows": list(workflows),+ "audio_reference_text": reference_text,+ "audio_required_inputs": [],+ "audio_clone": {+ "reference_text": reference_text,+ "reference_text_waived": waived or [["x_vector_only_mode", ["true"]]],+ "emotion_audio": emotion,+ },+ }+++def _speak_info(required = ()):+ return {+ "is_audio": True,+ "audio_type": "audiocpp_tts",+ "audio_workflows": ["speak"],+ "audio_reference_text": None,+ "audio_required_inputs": list(required),+ }+++class _Backend:+ def __init__(self, name, info):+ self.active_model_name = name+ self.models = {name: info}+ self.calls: list[dict] = []++ def generate_audio_response(self, **kwargs):+ self.calls.append(kwargs)+ return _wav(), 24000+++def stub(monkeypatch):+ class _Llama:+ is_loaded = False+ _is_audio = False++ async def _noop_switch(*_args, **_kwargs):+ return None++ holder = {"backend": _Backend(QWEN3_BASE, _clone_info())}+ monkeypatch.setattr(inference, "get_llama_cpp_backend", lambda: _Llama())+ monkeypatch.setattr(inference, "get_inference_backend", lambda: holder["backend"])+ monkeypatch.setattr(inference, "_maybe_auto_switch_model", _noop_switch)++ def use(name, info):+ holder["backend"] = _Backend(name, info)+ return holder["backend"]++ holder["use"] = use+ return holder+++def _client(account):+ app = FastAPI()++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[get_current_subject] = subject+ app.dependency_overrides[authenticated_via_api_key] = lambda: False+ app.include_router(inference.router, prefix = "/api/inference")+ app.include_router(inference.studio_router, prefix = "/api/inference")+ return TestClient(app)+++def _input(account, seconds = 1.0) -> str:+ data = encode("webm", "libopus", 48000, "stereo", seconds)+ save = lambda: asyncio.run(audio_inputs.save_stream(_chunks([data]), "me.webm"))[0]["id"]+ return run_as(account, save)+++def _voice(account, input_id, **meta):+ path = audio_inputs.input_path+ return run_as(account, lambda: audio_voices.create(path(input_id), {"name": "Alice", **meta}))+++def _run(client, **body):+ payload = {"workflow": "clone", "text": "Hello in my voice.", **body}+ return client.post("/api/inference/audio/run", json = payload)+++def _sidecar(tmp_path, clip_id) -> str:+ path = tmp_path / "accounts" / ALICE.account_id / "audio" / f"{clip_id}.json"+ return path.read_text(encoding = "utf-8")+++def _inputs_root(tmp_path):+ return tmp_path / "accounts" / ALICE.account_id / "audio" / "inputs"+++def test_a_clone_run_hands_the_worker_an_account_path_and_saves_the_clip(stub, tmp_path):+ input_id = _input(ALICE)+ with _client(ALICE) as client:+ response = _run(+ client,+ language = "en",+ inputs = {"reference": {"input_id": input_id}, "reference_text": "Okay, I'm Cemo."},+ options = {"x_vector_only_mode": False},+ seed = 7,+ )+ assert response.status_code == 200, response.text+ body = response.json()+ assert client.get(body["clips"][0]["url"]).status_code == 200+ (call,) = stub["backend"].calls+ reference = Path(call["audio_inputs"]["reference"])+ assert reference.parent == _inputs_root(tmp_path)+ assert reference.name.startswith(f"{input_id}.24000.mono")+ with wave.open(str(reference)) as w:+ assert (w.getframerate(), w.getnchannels()) == (24000, 1)+ assert (call["workflow"], call["reference_text"], call["language"], call["seed"]) == (+ "clone",+ "Okay, I'm Cemo.",+ "en",+ 7,+ )+ assert "speed" not in call+ assert all(not isinstance(v, (bytes, bytearray)) for v in call.values())+ assert body["audio"] is None+ (clip,) = body["clips"]+ assert set(clip) == {"id", "role", "url", "sample_rate", "duration_s", "workflow"}+ assert (clip["role"], clip["workflow"], clip["sample_rate"]) == ("output", "clone", 24000)+ sidecar = _sidecar(tmp_path, clip["id"])+ meta = json.loads(sidecar)+ assert meta["reference_name"] == "me.webm"+ assert meta["settings"] == {+ "language": "en",+ "instructions": None,+ "options": {"x_vector_only_mode": False},+ "reference_text_used": True,+ "speed": None,+ }+ assert str(tmp_path) not in sidecar and "inputs" not in sidecar+++ "body",+ [+ {"path": "/etc/passwd"},+ {"voice_ref": "/etc/passwd"},+ {"file": "x.wav"},+ {"url": "http://x"},+ {"model": "other/model"},+ {"inputs": {"reference": {"path": "/etc/passwd"}}},+ {"inputs": {"reference": {"input_id": "a" * 32, "voice_ref": "/etc/passwd"}}},+ {"inputs": {"reference": {"input_id": "a" * 32}, "voice_ref": "/x.wav"}},+ {"inputs": {"reference": {"input_id": "a" * 32, "clip_id": "b" * 32}}},+ {"inputs": {"reference": {}}},+ {"inputs": {"reference": {"input_id": "../../etc/passwd"}}},+ {"inputs": {"reference": {"input_id": "a" * 32}, "emotion": {"url": "http://x"}}},+ {"options": {"voice_ref": "/etc/passwd"}},+ {"options": {"source_audio": "/etc/passwd"}},+ {"options": {"codec_model_path": "/etc/passwd"}},+ {"options": {"video": "/etc/passwd"}}, # ControlFoley+ {"options": {"reference_image": "/etc/passwd"}},+ {"options": {"nested": {"a": 1}}},+ {"workflow": "music"},+ {"workflow": "transcribe"},+ {"text": ""},+ ],+)+def test_client_paths_and_unknown_fields_are_422(stub, body):+ with _client(ALICE) as client:+ assert _run(client, **body).status_code == 422+ assert stub["backend"].calls == []+++ "options",+ [+ {"min_new_audio_steps": 10, "max_new_audio_steps": 900}, # FireRedAudio+ {"no_ref": True}, # Irodori+ {"audio_chunk_threshold_sec": 30, "audio_chunk_duration_sec": 20}, # DramaBox+ {"use_video": True},+ ],+)+def test_settings_named_after_audio_are_not_file_options(options):+ from models.inference import AudioRunRequest+ request = AudioRunRequest(workflow = "speak", text = "hi", options = options)+ assert request.options == options++[email protected]("kind", ["input_id", "clip_id", "voice_id"])+def test_another_accounts_ids_are_404(stub, kind):+ input_id = _input(ALICE)+ meta = {+ "prompt": "alice said",+ "model": "m",+ "audio_type": "audiocpp_tts",+ "sample_rate": 24000,+ "duration_s": 0.1,+ "created_at": "2026-10-02T00:00:00Z",+ }+ ids = {+ "input_id": input_id,+ "clip_id": run_as(ALICE, audio_gallery.save, _wav(), meta)["id"],+ "voice_id": _voice(ALICE, input_id)["id"],+ }+ source = {kind: ids[kind]}+ with _client(BOB) as client:+ assert _run(client, inputs = {"reference": source, "reference_text": "hi"}).status_code == 404+ emotion = {"reference": source, "emotion": source, "reference_text": "hi"}+ assert _run(client, inputs = emotion).status_code == 404+ assert stub["backend"].calls == []+ with _client(ALICE) as client:+ assert _run(client, inputs = {"reference": source, "reference_text": "hi"}).status_code == 200+++ "model, info, workflow, transcript",+ [+ (QWEN3_BASE, _clone_info(), "clone", "Okay, I'm Cemo."),+ (+ "audio-cpp/audio.cpp-gguf/VoxCPM2-GGUF",+ _clone_info(workflows = ("speak", "clone"), reference_text = "optional"),+ "speak",+ None,+ ),+ ],+)+def test_a_saved_voice_resolves_to_an_account_path_and_is_recorded(+ stub, tmp_path, model, info, workflow, transcript+):+ backend = stub["use"](model, info)+ voice = _voice(ALICE, _input(ALICE), **({"transcript": transcript} if transcript else {}))+ with _client(ALICE) as client:+ response = _run(client, workflow = workflow, inputs = {"reference": {"voice_id": voice["id"]}})+ assert response.status_code == 200, response.text+ (call,) = backend.calls+ assert call["workflow"] == workflow and call.get("reference_text") == transcript+ reference = Path(call["audio_inputs"]["reference"])+ assert reference.parent == _inputs_root(tmp_path)+ assert reference.name.startswith(f"v-{voice['id']}.")+ meta = json.loads(_sidecar(tmp_path, response.json()["clips"][0]["id"]))+ assert (meta["voice_id"], meta["workflow"], meta["reference_name"]) == (+ voice["id"],+ workflow,+ "Alice",+ )+++def test_a_cleared_transcript_is_not_refilled_from_the_saved_voice(stub):+ backend = stub["use"](+ "audio-cpp/audio.cpp-gguf/VoxCPM2-GGUF",+ _clone_info(workflows = ("speak", "clone"), reference_text = "optional"),+ )+ voice = _voice(ALICE, _input(ALICE), transcript = "Okay, I'm Cemo.")+ with _client(ALICE) as client:+ response = _run(+ client, inputs = {"reference": {"voice_id": voice["id"]}, "reference_text": ""}+ )+ assert response.status_code == 200, response.text+ (call,) = backend.calls+ assert call.get("reference_text") is None+++_COSY = _clone_info(waived = [["template_name", ["cross_lingual", "instruct"]]])+++ "info, options, status",+ [+ (_clone_info(), None, 400),+ (_clone_info(), {"x_vector_only_mode": True}, 200),+ (_clone_info(reference_text = "unused"), None, 200),+ (_COSY, None, 400),+ (_COSY, {"template_name": "zero_shot"}, 400),+ (_COSY, {"template_name": "cross_lingual"}, 200),+ (_COSY, {"template_name": "instruct"}, 200),+ ],+)+def test_a_missing_transcript_is_a_400_unless_the_family_waives_it(stub, info, options, status):+ stub["use"]("x/Model-GGUF", info)+ input_id = _input(ALICE)+ with _client(ALICE) as client:+ response = _run(client, inputs = {"reference": {"input_id": input_id}}, options = options)+ assert response.status_code == status, response.text+ if status == 400:+ assert response.json()["detail"] == "Type what's said in the reference clip."+++_GENERATE = ("/api/inference/audio/generate", {"messages": [{"role": "user", "content": "hi"}]})+_SPEECH = ("/api/inference/audio/speech", {"input": "hi"})+_KOKORO = ("audio-cpp/audio.cpp-gguf/Kokoro-82M-GGUF", _speak_info())+_MAYA1 = ("audio-cpp/audio.cpp-gguf/Maya1-GGUF", _speak_info(["instruct"]))+_REF = {"reference": {"input_id": "REF"}, "reference_text": "x"}+_MAYA1_DETAIL = "Maya1 needs a voice description."+++ "model, request_, detail",+ [+ (_KOKORO, {"inputs": _REF}, "Load a model that can clone a voice."),+ (_KOKORO, {"workflow": "speak", "inputs": _REF}, "Load a model that can clone a voice."),+ (_KOKORO, {"workflow": "speak"}, None),+ (None, {}, "Add a reference clip to clone."),+ (None, {"inputs": {**_REF, "emotion": {"input_id": "REF"}}}, "does not take an emotion"),+ (None, _GENERATE, "Open Clone"),+ (_MAYA1, {"workflow": "speak"}, _MAYA1_DETAIL),+ (_MAYA1, _GENERATE, _MAYA1_DETAIL),+ (_MAYA1, _SPEECH, _MAYA1_DETAIL),+ (_MAYA1, {"workflow": "speak", "instructions": "A calm, low male voice."}, None),+ ],+)+def test_requests_the_loaded_model_cannot_serve_are_400(stub, model, request_, detail):+ if model:+ stub["use"](*model)+ input_id = _input(ALICE)+ with _client(ALICE) as client:+ if isinstance(request_, tuple):+ response = client.post(request_[0], json = request_[1])+ else:+ body = json.loads(json.dumps(request_).replace('"REF"', json.dumps(input_id)))+ response = _run(client, **body)+ if detail is None:+ assert response.status_code == 200 and len(stub["backend"].calls) == 1+ else:+ assert response.status_code == 400 and detail in response.json()["detail"]+ assert stub["backend"].calls == []+++def test_an_emotion_clip_reaches_a_family_that_takes_one(stub):+ first, second = _input(ALICE, 0.5), _input(ALICE, 0.7)+ backend = stub["use"](+ "audio-cpp/audio.cpp-gguf/IndexTTS2-GGUF",+ _clone_info(reference_text = "unused", emotion = True),+ )+ with _client(ALICE) as client:+ ok = _run(+ client, inputs = {"reference": {"input_id": first}, "emotion": {"input_id": second}}+ )+ assert ok.status_code == 200, ok.text+ (call,) = backend.calls+ assert set(call["audio_inputs"]) == {"reference", "emotion"}+ assert Path(call["audio_inputs"]["emotion"]).name.startswith(f"{second}.24000.mono")+++def test_a_failed_gallery_save_returns_the_audio_inline(stub, monkeypatch):+ input_id = _input(ALICE)+ monkeypatch.setattr(inference, "_persist_tts_clip", lambda *a, **k: None)+ with _client(ALICE) as client:+ response = _run(client, inputs = {"reference": {"input_id": input_id}, "reference_text": "x"})+ body = response.json()+ assert response.status_code == 200 and body["clips"] == []+ assert body["audio"]["sample_rate"] == 24000+ assert base64.b64decode(body["audio"]["data"])[:4] == b"RIFF"+++def test_the_orchestrator_command_carries_paths_not_bytes(monkeypatch):+ from core.inference.orchestrator import InferenceOrchestrator++ orchestrator = InferenceOrchestrator.__new__(InferenceOrchestrator)+ sent = []+ wav = base64.b64encode(_wav()).decode()++ def read_one(*, timeout):+ rid = sent[-1]["request_id"]+ return {"type": "audio_done", "request_id": rid, "wav_base64": wav, "sample_rate": 24000}++ for name, value in {+ "_ensure_subprocess_alive": lambda: True,+ "_send_cmd": sent.append,+ "_direct_reader": lambda _rid, _cancel = None: (read_one, lambda **_k: None, lambda: None),+ "_reserve_worker": lambda _why: contextlib.nullcontext(),+ "_wait_worker_idle": lambda **_k: True,+ "_claim_worker": lambda _cancel: None,+ "_release_worker": lambda *_a, **_k: None,+ }.items():+ monkeypatch.setattr(orchestrator, name, value, raising = False)+ orchestrator.active_model_name = "m"+ orchestrator.models = {"m": {}}+ orchestrator._gen_lock = threading.Lock()+ orchestrator._send_order_lock = threading.Lock()+ orchestrator._unload_pending = False+ reference = "/home/x/.unsloth/studio/accounts/a/audio/inputs/abc.24000.mono.m30.wav"+ fields = {+ "workflow": "clone",+ "audio_inputs": {"reference": reference},+ "reference_text": "hi",+ "speed": 1.2,+ }+ orchestrator.generate_audio_response("hello", **fields)+ orchestrator.generate_audio_response("plain")+ assert {k: sent[0][k] for k in fields} == fields+ assert all(not isinstance(v, (bytes, bytearray)) for v in sent[0].values())+ assert not CLONE_FIELDS & set(sent[1])+++def test_the_worker_forwards_clone_fields_only_when_present():+ from core.inference.worker import _handle_generate_audio++ seen = []++ class _Recorder:+ def generate_audio_response(self, **kwargs):+ seen.append(kwargs)+ return _wav(), 24000++ fields = {+ "workflow": "clone",+ "audio_inputs": {"reference": "/abs/ref.wav"},+ "reference_text": "x",+ "speed": 1.1,+ }+ for cmd in ({"request_id": "r1", "text": "hi", **fields}, {"request_id": "r2", "text": "hi"}):+ _handle_generate_audio(_Recorder(), cmd, queue.Queue(), threading.Event())+ assert {k: seen[0][k] for k in fields} == fields+ assert not CLONE_FIELDS & set(seen[1])+++def test_the_worker_keeps_run_fields_off_a_backend_without_them():+ from core.inference.worker import _handle_generate_audio++ seen = []++ class _Native:+ def generate_audio_response(+ self,+ text,+ temperature = 0.6,+ top_p = 0.95,+ top_k = 50,+ min_p = 0.0,+ max_new_tokens = 2048,+ repetition_penalty = 1.0,+ use_adapter = None,+ cancel_event = None,+ instructions = None,+ language = None,+ seed = None,+ ):+ seen.append(text)+ return _wav(), 24000++ replies = queue.Queue()+ speak = {"request_id": "r1", "text": "hi", "workflow": "speak", "speed": 1.1}+ _handle_generate_audio(_Native(), speak, replies, threading.Event())+ assert replies.get_nowait()["type"] == "audio_done" and seen == ["hi"]+ clone = {"request_id": "r2", "text": "hi", "audio_inputs": {"reference": "/abs/ref.wav"}}+ _handle_generate_audio(_Native(), clone, replies, threading.Event())+ error = replies.get_nowait()+ assert error["type"] == "audio_error" and error["status"] == 400+ assert seen == ["hi"]diff --git a/studio/backend/tests/test_audio_voices.py b/studio/backend/tests/test_audio_voices.pynew file mode 100644index 00000000000..27e39b58454--- /dev/null+++ b/studio/backend/tests/test_audio_voices.py@@ -0,0 +1,128 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from __future__ import annotations++import json+import sys+import wave+from pathlib import Path++import pytest++import core.inference.audio_gallery as gallery+from core.inference import audio_inputs, audio_voices++# pytest inserts rootdir, not this dir, so sibling imports need it on the path.+sys.path.insert(0, str(Path(__file__).resolve().parent))++from test_audio_inputs import _clip, _save, _tmp_gallery, client, encode, wav_bytes # noqa: E402,F401++VOICES = "/api/inference/audio/voices"+++def _input(seconds = 2.0, rate = 48000) -> str:+ return _save(encode("wav", "pcm_s16le", rate, "stereo", seconds), "me.wav")["id"]+++def test_save_list_rename_and_delete_a_voice(client):+ input_id = _input()+ body = {"source": {"input_id": input_id}, "name": " My voice "}+ created = client.post(+ VOICES, json = {**body, "transcript": "Okay, I'm Cemo.", "language": "English"}+ )+ assert created.status_code == 201, created.text+ voice = created.json()+ keys = "id name transcript language duration_s sample_rate created_at url"+ assert set(voice) == set(keys.split())+ assert (voice["name"], voice["transcript"]) == ("My voice", "Okay, I'm Cemo.")+ assert (voice["sample_rate"], voice["duration_s"]) == (24000, 2.0)+ path = audio_voices.voice_path(voice["id"])+ with wave.open(str(path)) as w:+ assert w.getnchannels() == 1+ assert path.parent == gallery.gallery_dir() / "voices"+ assert voice["url"] == f"{VOICES}/{voice['id']}/file"+ served = client.get(voice["url"])+ assert served.status_code == 200 and served.headers["content-type"] == "audio/wav"++ second = client.post(VOICES, json = {**body, "name": "Second"}).json()+ assert [v["id"] for v in client.get(VOICES).json()["voices"]] == [second["id"], voice["id"]]++ url = f"{VOICES}/{voice['id']}"+ patched = client.patch(url, json = {"name": "Renamed", "transcript": None})+ assert patched.status_code == 200+ p = patched.json()+ assert (p["name"], p["transcript"], p["language"]) == ("Renamed", None, "English")++ assert client.delete(url).json() == {"removed": True}+ assert client.get(voice["url"]).status_code == 404+ assert client.delete(url).status_code == 404+ assert client.patch(url, json = {"name": "x"}).status_code == 404+++ "make_source, duration",+ [+ (lambda: {"input_id": _input(45.0, rate = 8000)}, 30.0),+ (lambda: {"clip_id": _clip(rate = 22050, audio_type = "audiocpp_tts")["id"]}, 1.0),+ ],+)+def test_a_voice_is_24k_and_keeps_the_first_30_seconds(client, make_source, duration):+ response = client.post(VOICES, json = {"source": make_source(), "name": "v"})+ assert response.status_code == 201, response.text+ assert (response.json()["sample_rate"], response.json()["duration_s"]) == (24000, duration)+ assert not [p for p in audio_voices.voices_dir().iterdir() if p.name.startswith(".")]+++def test_the_voice_cap_is_enforced(client, monkeypatch):+ monkeypatch.setattr(audio_voices, "MAX_VOICES", 2)+ source = {"input_id": _input(0.5)}+ codes = [client.post(VOICES, json = {"source": source, "name": n}).status_code for n in "ab"]+ assert codes == [201, 201]+ full = client.post(VOICES, json = {"source": source, "name": "c"})+ assert full.status_code == 400 and "2 saved voices" in full.json()["detail"]+ assert len(audio_voices.list_voices()) == 2+++ "body, status",+ [+ ({"source": {"input_id": "x" * 32}, "name": ""}, 422),+ ({"source": {"input_id": "x" * 32, "clip_id": "y" * 32}, "name": "two"}, 422),+ ({"source": {"voice_id": "x" * 32}, "name": "from a voice"}, 422),+ ({"source": {"path": "/etc/passwd"}, "name": "path"}, 422),+ ({"source": {"input_id": "../../etc"}, "name": "escape"}, 422),+ ({"source": {"input_id": "x" * 32}, "name": "n", "file": "/tmp/x.wav"}, 422),+ ({"source": {"input_id": "f" * 32}, "name": "gone"}, 404),+ ],+)+def test_a_voice_names_its_source_by_one_safe_known_id(client, body, status):+ assert client.post(VOICES, json = body).status_code == status++[email protected]("bad", ["../x", "a/b", "..", "x" * 129])+def test_unsafe_voice_ids_resolve_to_nothing(bad):+ assert audio_voices.voice_path(bad) is None+ assert audio_voices.get(bad) is None+ assert audio_voices.update(bad, {"name": "x"}) is None+ assert audio_voices.delete(bad) is False+++def test_a_lone_wav_or_foreign_sidecar_is_not_a_voice():+ directory = audio_voices.voices_dir()+ (directory / "orphan.wav").write_bytes(wav_bytes())+ (directory / "foreign.wav").write_bytes(wav_bytes())+ (directory / "foreign.json").write_text(json.dumps({"title": "not ours"}), encoding = "utf-8")+ assert audio_voices.list_voices() == []+ for voice_id in ("orphan", "foreign"):+ assert audio_voices.voice_path(voice_id) is None+ assert audio_voices.delete(voice_id) is False+ assert (directory / "orphan.wav").is_file() and (directory / "foreign.wav").is_file()+++def test_deleting_a_voice_drops_its_prepared_copies():+ voice = audio_voices.create(audio_inputs.input_path(_input(1.0)), {"name": "v"})+ _source, prepared = audio_inputs.prepare_reference({"voice_id": voice["id"]})+ assert prepared.is_file() and prepared.name.startswith(f"v-{voice['id']}.")+ assert audio_voices.delete(voice["id"])+ assert not prepared.exists()diff --git a/studio/backend/tests/test_audio_workflows.py b/studio/backend/tests/test_audio_workflows.pyindex bbfdda052c5..79c26eb673a 100644--- a/studio/backend/tests/test_audio_workflows.py+++ b/studio/backend/tests/test_audio_workflows.py@@ -1,7 +1,7 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""Which Audio page workflows an inventory row or a gallery clip belongs to."""+"""Which Audio page workflows a loaded model, an inventory row or a gallery clip belongs to."""from __future__ import annotations@@ -13,6 +13,7 @@ import pytestfrom core.inference import audio_workflows as awfrom core.inference.audio_cpp_models import AUDIO_CPP_MUSIC_AUDIO_TYPE, AUDIO_CPP_TTS_AUDIO_TYPEfrom hub.schemas.inventory import CachedGgufRepo, CachedModelRepo, LocalModelInfo+from models.inference import InferenceStatusResponse, LoadResponsedef test_music_audio_types_match_the_frontend_set():@@ -29,6 +30,44 @@ def test_music_audio_types_match_the_frontend_set():assert frontend == set(aw.MUSIC_AUDIO_TYPES) == {"minimax_music3", "audiocpp_music"}+def test_a_status_reports_no_workflows_for_a_model_that_is_not_audio():+ status = InferenceStatusResponse(active_model = "unsloth/Qwen3-0.6B-GGUF")+ assert status.audio_workflows == []+ assert InferenceStatusResponse().audio_workflows == []+++ "audio_type, workflows",+ [+ (AUDIO_CPP_TTS_AUDIO_TYPE, ["speak"]),+ (AUDIO_CPP_MUSIC_AUDIO_TYPE, ["music"]),+ ("minimax_music3", ["music"]),+ ("snac", ["speak"]),+ ("higgs_tts2", ["speak"]),+ ("whisper", ["transcribe"]),+ (None, ["speak"]),+ ],+)+def test_a_status_reports_the_workflow_of_its_audio_type(audio_type, workflows):+ status = InferenceStatusResponse(is_audio = True, audio_type = audio_type)+ assert status.audio_workflows == workflows+ assert status.model_dump()["audio_workflows"] == workflows+++def test_a_load_response_derives_workflows_and_keeps_an_explicit_value():+ load = LoadResponse(+ status = "loaded",+ model = "audio-cpp/audio.cpp-gguf/Kokoro-82M-GGUF",+ display_name = "Kokoro",+ inference = {},+ is_audio = True,+ audio_type = AUDIO_CPP_TTS_AUDIO_TYPE,+ )+ assert load.audio_workflows == ["speak"]+ explicit = InferenceStatusResponse(is_audio = True, audio_workflows = ["music"])+ assert explicit.audio_workflows == ["music"]++@pytest.mark.parametrize("task, audio_type, workflows",[@@ -59,3 +98,66 @@ def test_workflow_for_audio_type_is_speak_or_music():assert aw.workflow_for_audio_type("snac") == "speak"assert aw.workflow_for_audio_type("unknown") == "speak"assert aw.workflow_for_audio_type(None) == "speak"+ assert aw.AUDIO_WORKFLOW_IDS == ("speak", "clone", "music", "transcribe")+++def test_workflow_ids_match_the_frontend_order():+ source = (+ Path(__file__).resolve().parents[2] / "frontend/src/features/audio/workflows.ts"+ ).read_text(encoding = "utf-8")+ block = source.split("export const AUDIO_WORKFLOWS", 1)[1]+ assert tuple(re.findall(r'^\s*id: "(\w+)"', block, re.M)) == aw.AUDIO_WORKFLOW_IDS+++def test_status_carries_the_clone_fields():+ clone = {"audio_workflows": ["clone"], "audio_reference_text": "required"}+ status = InferenceStatusResponse(is_audio = True, audio_type = "audiocpp_tts", **clone)+ assert status.model_dump().items() >= clone.items()+++ "folder, family, workflows",+ [+ ("Chatterbox-GGUF", "chatterbox", ["clone"]),+ ("Chatterbox-Turbo-GGUF", "chatterbox_turbo", ["speak"]),+ ("VoxCPM2-GGUF", "voxcpm2", ["speak", "clone"]),+ ("Qwen3-TTS-12Hz-0.6B-Base-GGUF", "qwen3_tts", ["clone"]),+ ("Kokoro-82M-GGUF", "kokoro_tts", ["speak"]),+ ],+)+def test_inventory_rows_of_clone_families_list_clone(tmp_path, folder, family, workflows):+ from hub.services.models import catalog_classification as cc++ from .test_audio_cpp_models import _gguf_bytes++ path = tmp_path / folder / f"{folder.lower().removesuffix('-gguf')}-q8_0.gguf"+ path.parent.mkdir(parents = True)+ path.write_bytes(_gguf_bytes(family = family))+ found = cc._gguf_path_audio_workflows(path.parent, (f"someone/{folder}",))+ row = CachedGgufRepo(repo_id = "r", task = "text-to-speech", audio_workflows = found)+ assert found == row.audio_workflows == workflows+ # A local folder row (models dir, LM Studio, custom folder) gets the same answer.+ local = LocalModelInfo(+ id = str(path.parent), display_name = folder, path = str(path.parent), source = "models_dir"+ )+ assert cc.local_audio_workflows(local, "audiocpp_tts") == workflows+ assert cc.local_audio_workflows(local, "orpheus") is None+++def test_an_umbrella_snapshot_lists_every_downloaded_familys_workflows(tmp_path):+ # audio-cpp/audio.cpp-gguf is one cached row: its workflows were the first GGUF's alone.+ from hub.services.models import catalog_classification as cc++ from .test_audio_cpp_models import _gguf_bytes++ for folder, family in (+ ("Qwen3-TTS-12Hz-0.6B-Base-GGUF", "qwen3_tts"),+ ("Kokoro-82M-GGUF", "kokoro_tts"),+ ):+ path = tmp_path / folder / f"{folder.lower()}-q8_0.gguf"+ path.parent.mkdir(parents = True)+ path.write_bytes(_gguf_bytes(family = family))+ assert cc._gguf_path_audio_workflows(tmp_path, ("audio-cpp/audio.cpp-gguf",)) == [+ "speak",+ "clone",+ ]diff --git a/studio/backend/tests/test_gguf_load_cache_reuse.py b/studio/backend/tests/test_gguf_load_cache_reuse.pyindex 7cd85e1bc74..7a507df87ca 100644--- a/studio/backend/tests/test_gguf_load_cache_reuse.py+++ b/studio/backend/tests/test_gguf_load_cache_reuse.py@@ -1076,6 +1076,10 @@ class TestLoadHubDownloadExclusion:# Constant None: llama-server never serves an audio GGUF."audio_family","audio_options",+ # None for the response validator to derive from is_audio and audio_type.+ "audio_workflows",+ "audio_reference_text",+ "audio_required_inputs",}unresolved = sorted(namediff --git a/studio/backend/tests/test_pr7699_worker_audio_mirror.py b/studio/backend/tests/test_pr7699_worker_audio_mirror.pyindex c9927129c38..9e7d1068e9c 100644--- a/studio/backend/tests/test_pr7699_worker_audio_mirror.py+++ b/studio/backend/tests/test_pr7699_worker_audio_mirror.py@@ -48,12 +48,17 @@ def _mlx_entry_for(mc):}-def _drive_handle_load(monkeypatch, mc):+def _drive_handle_load(+ monkeypatch,+ mc,+ entry = None,+ device = "mlx",+):"""Run _handle_load against a stub MLX backend, return the emitted model_info."""backend = SimpleNamespace(- device = "mlx",+ device = device,active_model_name = mc.identifier,- models = {mc.identifier: _mlx_entry_for(mc)},+ models = {mc.identifier: entry or _mlx_entry_for(mc)},load_model = lambda **kw: True,)@@ -109,3 +114,21 @@ def test_whisper_classification_survives_the_mlx_post_load_mirror(monkeypatch):assert info["audio_type"] == "whisper"assert info["has_audio_input"] is True+++def test_audio_cpp_workflow_fields_cross_the_worker_and_the_parent(monkeypatch):+ """Dropped at either hop, status falls back to "speak" from audio_type and offers+ Speak for a clone-only model."""+ from core.inference.orchestrator import _mirrored_model_entry++ mc = _mc("audiocpp_tts", is_audio = True, has_audio_input = False)+ fields = {+ "audio_workflows": ["clone"],+ "audio_reference_text": "required",+ "audio_required_inputs": ["instruct"],+ "audio_clone": {"reference_text": "required", "emotion_audio": False},+ }+ entry = {"is_audio": True, "audio_type": "audiocpp_tts", "has_audio_input": False, **fields}+ info = _drive_handle_load(monkeypatch, mc, entry, device = "cuda")+ entry = _mirrored_model_entry(info, mc.identifier)+ assert {k: info[k] for k in fields} == {k: entry[k] for k in fields} == fieldsdiff --git a/studio/backend/utils/upload_limits.py b/studio/backend/utils/upload_limits.pyindex a849f31c70a..8c0d5dc9448 100644--- a/studio/backend/utils/upload_limits.py+++ b/studio/backend/utils/upload_limits.py@@ -15,6 +15,7 @@ MAX_UPLOAD_LIMIT_MB = 8192_BYTES_PER_MB = 1024 * 1024MULTIPART_OVERHEAD_BYTES = 10 * _BYTES_PER_MBSTT_AUDIO_RAW_MAX_BYTES = 25 * _BYTES_PER_MB+AUDIO_INPUT_MAX_BYTES = 200 * _BYTES_PER_MBVIDEO_INPUT_REFERENCE_MAX_BYTES = 32 * _BYTES_PER_MBSTT_AUDIO_B64_MAX_CHARS = ((STT_AUDIO_RAW_MAX_BYTES + 2) // 3) * 4STT_AUDIO_JSON_MAX_BYTES = STT_AUDIO_B64_MAX_CHARS + 64 * 1024diff --git a/studio/frontend/src/features/audio/api.ts b/studio/frontend/src/features/audio/api.tsindex 8f8e482ec6b..a5f9d79b635 100644--- a/studio/frontend/src/features/audio/api.ts+++ b/studio/frontend/src/features/audio/api.ts@@ -1,8 +1,21 @@// 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 { authFetch } from "@/features/auth";-import { readFastApiError } from "@/lib/format-fastapi-error";+import { authFetch, getAuthToken } from "@/features/auth";+import { accountTransitionPending } from "@/lib/account-transition";+import { apiUrl } from "@/lib/api-base";+import {+ formatApiErrorBody,+ readFastApiError,+} from "@/lib/format-fastapi-error";+import {+ type AudioRunRequest,+ type AudioSourceRef,+ type AudioVoiceCreateRequest,+ buildAudioRunBody,+ buildVoiceCreateBody,+ transcribeUrl,+} from "./audio-run-request";async function parseJson<T>(response: Response): Promise<T> {if (!response.ok) {@@ -94,6 +107,7 @@ export interface AudioGalleryClip {order_at?: number | null;/** The Audio workflow that made the clip. Older servers omit it; read it through clipWorkflow. */workflow?: string | null;+ reference_name?: string | null;}export interface AudioGalleryListResponse {@@ -198,7 +212,7 @@ export async function deleteAudioClip(id: string): Promise<void> {}export async function clearAudioGallery(- workflow?: "speak" | "music",+ workflow?: "speak" | "clone" | "music",): Promise<number> {const query = workflow ? `?workflow=${workflow}` : "";const response = await authFetch(`/api/inference/audio/gallery${query}`, {@@ -300,3 +314,216 @@ export async function deleteTranscript(id?: string): Promise<void> {),);}++/** Carries the status so callers can tell an expired upload (404) from a refusal. */+export class AudioApiError extends Error {+ readonly status: number;+ constructor(message: string, status: number) {+ super(message);+ this.name = "AudioApiError";+ this.status = status;+ }+}++async function parseAudioJson<T>(response: Response): Promise<T> {+ if (!response.ok) {+ throw new AudioApiError(await readFastApiError(response), response.status);+ }+ return (await response.json()) as T;+}++interface AudioInputRecord {+ id: string;+ name: string;+ duration_s: number;+ sample_rate: number;+ channels: number;+ url: string;+ expires_at: string;+}++/** XHR is the only browser API with upload progress; the caller retries a 401 via authFetch to refresh the token. */+function uploadWithProgress(+ url: string,+ blob: Blob,+ onProgress: (fraction: number | null) => void,+ signal?: AbortSignal,+): Promise<{ status: number; body: unknown }> {+ return new Promise((resolve, reject) => {+ // Same fence as authFetch: mid-switch, this tab's file would be stored under the next account.+ if (accountTransitionPending()) {+ reject(new Error("Another tab is switching accounts; this tab will reload."));+ return;+ }+ const xhr = new XMLHttpRequest();+ xhr.open("POST", apiUrl(url));+ const token = getAuthToken();+ if (token) xhr.setRequestHeader("Authorization", `Bearer ${token}`);+ xhr.setRequestHeader(+ "Content-Type",+ blob.type || "application/octet-stream",+ );+ xhr.responseType = "json";+ xhr.upload.onprogress = (event) =>+ onProgress(event.lengthComputable ? event.loaded / event.total : null);+ xhr.onload = () => resolve({ status: xhr.status, body: xhr.response });+ xhr.onerror = () =>+ reject(+ new Error("The upload failed. Check the connection and try again."),+ );+ xhr.onabort = () => reject(new DOMException("Aborted", "AbortError"));+ if (signal) {+ if (signal.aborted) {+ reject(new DOMException("Aborted", "AbortError"));+ return;+ }+ signal.addEventListener("abort", () => xhr.abort(), { once: true });+ }+ xhr.send(blob);+ });+}++export async function uploadAudioInput(+ blob: Blob,+ name: string,+ options: {+ onProgress?: (fraction: number | null) => void;+ signal?: AbortSignal;+ } = {},+): Promise<AudioInputRecord> {+ const url = `/api/inference/audio/inputs?name=${encodeURIComponent(name.slice(0, 255))}`;+ if (options.onProgress && typeof XMLHttpRequest !== "undefined") {+ const { status, body } = await uploadWithProgress(+ url,+ blob,+ options.onProgress,+ options.signal,+ );+ if (status >= 200 && status < 300) return body as AudioInputRecord;+ if (status !== 401) {+ throw new AudioApiError(+ formatApiErrorBody(body) ?? `Upload failed (${status})`,+ status,+ );+ }+ }+ const response = await authFetch(url, {+ method: "POST",+ headers: { "Content-Type": blob.type || "application/octet-stream" },+ body: blob,+ signal: options.signal,+ });+ return parseAudioJson<AudioInputRecord>(response);+}++export async function fetchAudioBlob(+ url: string,+ signal?: AbortSignal,+): Promise<Blob> {+ const response = await authFetch(url, { signal });+ if (!response.ok) {+ throw new AudioApiError(await readFastApiError(response), response.status);+ }+ return response.blob();+}++interface TranscribeInputResponse {+ text: string;+ language: string | null;+ model: string;+}++export async function transcribeAudioInput(+ ref: AudioSourceRef,+ body: { model: string; engine?: string; device?: string; language?: string },+ signal?: AbortSignal,+): Promise<TranscribeInputResponse> {+ const response = await authFetch(transcribeUrl(ref), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ signal,+ });+ return parseAudioJson<TranscribeInputResponse>(response);+}++export interface AudioRunResponse {+ clips: {+ id: string;+ role: string;+ url: string;+ sample_rate: number;+ duration_s: number;+ workflow: string;+ }[];+ model: string;+ audio: GeneratedAudio | null;+}++export async function runAudio(+ request: AudioRunRequest,+ signal?: AbortSignal,+): Promise<AudioRunResponse> {+ const response = await authFetch("/api/inference/audio/run", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(buildAudioRunBody(request)),+ signal,+ });+ return parseAudioJson<AudioRunResponse>(response);+}++export interface AudioVoice {+ id: string;+ name: string;+ transcript: string | null;+ language: string | null;+ duration_s: number;+ sample_rate: number;+ created_at: string;+ url: string;+}++export async function listVoices(): Promise<AudioVoice[]> {+ const body = await parseAudioJson<{ voices: AudioVoice[] }>(+ await authFetch("/api/inference/audio/voices"),+ );+ return body.voices;+}++export async function createVoice(+ request: AudioVoiceCreateRequest,+): Promise<AudioVoice> {+ return parseAudioJson<AudioVoice>(+ await authFetch("/api/inference/audio/voices", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(buildVoiceCreateBody(request)),+ }),+ );+}++export async function updateVoice(+ id: string,+ patch: {+ name?: string;+ transcript?: string | null;+ language?: string | null;+ },+): Promise<AudioVoice> {+ return parseAudioJson<AudioVoice>(+ await authFetch(`/api/inference/audio/voices/${encodeURIComponent(id)}`, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(patch),+ }),+ );+}++export async function deleteVoice(id: string): Promise<void> {+ await parseAudioJson(+ await authFetch(`/api/inference/audio/voices/${encodeURIComponent(id)}`, {+ method: "DELETE",+ }),+ );+}diff --git a/studio/frontend/src/features/audio/audio-cpp-catalog.ts b/studio/frontend/src/features/audio/audio-cpp-catalog.tsindex d53e8834796..9f76b469b40 100644--- a/studio/frontend/src/features/audio/audio-cpp-catalog.ts+++ b/studio/frontend/src/features/audio/audio-cpp-catalog.ts@@ -15,10 +15,14 @@ export const AUDIO_CPP_AUDIO_TYPES: ReadonlySet<string> = new Set([export type AudioCppTask = "tts" | "music" | "asr";+/** Mirrors AudioWorkflowId; spelled out to keep this file import-free. */+export type AudioCppWorkflow = "speak" | "clone" | "music" | "transcribe";+export interface AudioCppModel {/** Hub repo id, or `${AUDIO_CPP_REPO}/<folder>` for a package in the shared repo. */id: string;task: AudioCppTask;+ workflows?: readonly AudioCppWorkflow[];/** ASR only: the primary language codes the model transcribes. Absent = multilingual. */languages?: readonly string[];/** Phonemizes with eSpeak-ng, which upstream runtime bundles lack (backend needs_espeak). */@@ -47,7 +51,11 @@ export const AUDIO_CPP_MODELS: readonly AudioCppModel[] = [{ id: folder("MOSS-TTS-Nano-100M-GGUF"), task: "tts" },{ id: folder("Supertonic-3-GGUF"), task: "tts" },{ id: folder("Chatterbox-Turbo-GGUF"), task: "tts" },- { id: folder("VoxCPM2-GGUF"), task: "tts" },+ { id: folder("VoxCPM2-GGUF"), task: "tts", workflows: ["speak", "clone"] },+ { id: folder("Qwen3-TTS-12Hz-0.6B-Base-GGUF"), task: "tts", workflows: ["clone"] },+ { id: folder("Chatterbox-GGUF"), task: "tts", workflows: ["clone"] },+ { id: folder("IndexTTS2-GGUF"), task: "tts", workflows: ["clone"] },+ { id: folder("CosyVoice3-GGUF"), task: "tts", workflows: ["clone"] },{ id: folder("Qwen3-TTS-12Hz-1.7B-CustomVoice-GGUF"), task: "tts" },{ id: folder("Qwen3-TTS-12Hz-1.7B-VoiceDesign-GGUF"), task: "tts" },{ id: "audio-cpp/MiniMax-Music3-GGUF", task: "music" },@@ -62,6 +70,22 @@ export const AUDIO_CPP_MODELS: readonly AudioCppModel[] = [{ id: folder("Nemotron-3.5-ASR-Streaming-0.6B-GGUF"), task: "asr", languages: ENGLISH },];+// Families the backend marks speaks=False (audio_cpp_models.FAMILIES), by repo name: Hub rows+// carry no backend workflows before download. Chatterbox-Turbo is its own family and speaks.+const CLONE_ONLY_FAMILY_HINT =+ /miotts|vevo-?2|fireredtts-?3|firered-?audio|indextts-?2|cosyvoice-?3|confucius-?4|echo-?tts|f5-?tts|chatterbox(?!-?turbo)|qwen3-?tts[^/]*-base/i;++export function isCloneOnlyFamilyId(id: string | null | undefined): boolean {+ return CLONE_ONLY_FAMILY_HINT.test(id ?? "");+}++// Families that both speak and clone (fish_audio), likewise by repo name.+const SPEAK_AND_CLONE_FAMILY_HINT = /fish-?(audio|speech)|openaudio/i;++export function isSpeakAndCloneFamilyId(id: string | null | undefined): boolean {+ return SPEAK_AND_CLONE_FAMILY_HINT.test(id ?? "");+}+/** Legacy Settings > Voice keys; the backend still maps each to its folder id (and variant). */export interface AudioCppDictationModel {key: string;@@ -153,6 +177,23 @@ export function isAudioRuntimeGguf();}+const TASK_WORKFLOW: Record<AudioCppTask, AudioCppWorkflow> = {+ tts: "speak",+ music: "music",+ asr: "transcribe",+};++export function audioCppWorkflowsFor(+ model: AudioCppModel,+): readonly AudioCppWorkflow[] {+ return model.workflows ?? [TASK_WORKFLOW[model.task]];+}++export function audioCppModelSpeaks(id: string | null | undefined): boolean {+ const model = audioCppModelFor(id);+ return !model || audioCppWorkflowsFor(model).includes("speak");+}+export function audioCppModelsForTask(task: AudioCppTask): AudioCppModel[] {return AUDIO_CPP_MODELS.filter((model) => model.task === task);}diff --git a/studio/frontend/src/features/audio/audio-page-policy.ts b/studio/frontend/src/features/audio/audio-page-policy.tsindex b88247fd233..1160cc59673 100644--- a/studio/frontend/src/features/audio/audio-page-policy.ts+++ b/studio/frontend/src/features/audio/audio-page-policy.ts@@ -183,15 +183,6 @@ export function nativeAudioInstructionsKind(return null;}-export function instructionsFieldKind(- workflow: "speak" | "music",- audioType?: string | null,-): NativeAudioInstructionsKind | null {- if (workflow === "music") return "music";- const kind = nativeAudioInstructionsKind(audioType);- return kind === "music" ? null : kind;-}-/** The music length range the loaded model honours. The GGUF runtime clamps tighter than the* MiniMax Music 3 pipeline; both take the same 25 frames per second. */export function musicDurationRange(requiresCuda: boolean): {diff --git a/studio/frontend/src/features/audio/audio-page.tsx b/studio/frontend/src/features/audio/audio-page.tsxindex e3d505cbeed..8987bb98d4d 100644--- a/studio/frontend/src/features/audio/audio-page.tsx+++ b/studio/frontend/src/features/audio/audio-page.tsx@@ -35,8 +35,9 @@ import {type AudioBusy,type AudioGenerationPhase,audioGenerationPresentation,- instructionsFieldKind,} from "./audio-page-policy";+import { clipReference } from "./audio-run-request";+import { AudioActiveProvider } from "./components/audio-source-input";import { type CreateMode, deviceSizeBytes } from "./audio-workspace-utils";import {audioCapabilityLine,@@ -48,21 +49,32 @@ import { WorkflowTitleMenu } from "./components/workflow-title-menu";import { galleryCache, useAudioGallery, useWorkflowHistory } from "./hooks/use-audio-gallery";import { useAudioHandoff } from "./hooks/use-audio-handoff";import { useAudioModelSlot } from "./hooks/use-audio-model-slot";+import { useCloneGeneration } from "./hooks/use-clone-generation";import { useSpeechGeneration } from "./hooks/use-speech-generation";import { useSttSidecar } from "./hooks/use-stt-sidecar";import { useTranscription } from "./hooks/use-transcription";+import {+ CloneFooter,+ CloneOutput,+ CloneRail,+ adoptReference,+ clonePageModels,+} from "./pages/clone-page";import { MusicOutput, MusicRail, musicPageModels } from "./pages/music-page";import { SpeakOutput, SpeakRail, speakPageModels } from "./pages/speak-page";import { type GenerateBlocker, TtsFooter } from "./pages/tts-workspace";import { TranscribeOutput, TranscribeRail } from "./pages/transcribe-page";import { type AudioPickerRow, audioRowMatchesWorkflow } from "./picker-filter";+import { useAudioCloneStore } from "./stores/audio-clone-store";import { useAudioWorkspaceStore } from "./stores/audio-workspace-store";-import { InstructionsField, MossLanguageField } from "./components/instructions-fields";+import { AudioToolPanels } from "./tools/tool-panel-host";import {type AudioWorkflowId,audioWorkflowTab,clipWorkflow,+ loadedModelRunsWorkflow,slotForWorkflow,+ workflowForLoadedModel,} from "./workflows";const MODELS_BY_MODE: Record<CreateMode, ModelOption[]> = {@@ -95,8 +107,7 @@ export function AudioPage({: mode === "transcribe"? "transcribe": "speak";- const ttsWorkflow: "speak" | "music" =- pageWorkflow === "music" ? "music" : "speak";+ const ttsWorkflow = pageWorkflow === "transcribe" ? "speak" : pageWorkflow;const workflowTab = audioWorkflowTab(pageWorkflow);const { rootStyle: railRootStyle } = useMediaRailWidth("audio");const tourSteps = useMemo(@@ -315,6 +326,7 @@ export function AudioPage({transitionWorkflow,pendingTranscribeRelease,handleModelSelect,+ pickRecommendedModel,handleEject,trainedTtsModels,} = useAudioModelSlot({@@ -368,9 +380,6 @@ export function AudioPage({prompt,setPrompt,audioInstructions,- setAudioInstructions,- audioLanguage,- setAudioLanguage,temperature,handleTemperatureChange,maxTokens,@@ -395,8 +404,44 @@ export function AudioPage({handleGenerate,generationError,setGenerationError,+ toolContext,+ toolValues,+ handleToolValueChange,+ toolBlocker,+ claimedOptions,} = useSpeechGeneration({- workflow: ttsWorkflow,+ workflow: ttsWorkflow === "music" ? "music" : "speak",+ status,+ busyRef,+ setBusy,+ updateGenerationPhase,+ generateAbort,+ setMode,+ setAdvancedOpen,+ refreshStatus,+ activeRef,+ modeRef,+ refreshGallery,+ selectClip: selectGeneratedClip,+ setFallbackClip,+ setSelectedId,+ pendingTranscribeRelease,+ replayQueuedTtsPick,+ });++ // Clone's Transcribe uses Transcribe's model, else one on disk, so it works without Settings.+ const lastSttDownloaded =+ lastSttRepo !== null &&+ downloadedSttArtifacts.some(+ (artifact) => artifact.repoId.toLowerCase() === lastSttRepo.toLowerCase(),+ );+ const cloneSttRepo =+ selectedSttRepo ??+ (lastSttDownloaded ? lastSttRepo : null) ??+ downloadedSttArtifacts[0]?.repoId ??+ lastSttRepo ??+ null;+ const clone = useCloneGeneration({status,busyRef,setBusy,@@ -413,6 +458,9 @@ export function AudioPage({setSelectedId,pendingTranscribeRelease,replayQueuedTtsPick,+ audioOptionSpecs,+ audioOptionValues,+ sttRepo: cloneSttRepo,});const { navigateSelf } = useAudioHandoff({@@ -452,9 +500,15 @@ export function AudioPage({useEffect(() => {if (adoptedLoadedModel.current || status === null) return;adoptedLoadedModel.current = true;- if (modeRef.current === "speak" && ttsLoaded && musicGeneration) {- useAudioWorkspaceStore.getState().adoptWorkflow("music");- }+ if (modeRef.current !== "speak" || !ttsLoaded) return;+ // A model already resident on mount (reload, another client) opens the page it runs on.+ const store = useAudioWorkspaceStore.getState();+ const next = workflowForLoadedModel({+ current: store.workflow,+ audioWorkflows: status.audio_workflows,+ music: musicGeneration,+ });+ if (next !== "speak" && next !== store.workflow) store.adoptWorkflow(next);}, [status, ttsLoaded, musicGeneration]);const {@@ -482,6 +536,9 @@ export function AudioPage({// Send to: only pages that can take a finished clip today. Bytes first, so a failed fetch leaves the page.const sendHandlersFor = useCallback((clip: AudioGalleryClip): ClipSendHandlers => ({+ clone: () => {+ if (transitionWorkflow("clone")) adoptReference(clipReference(clip));+ },transcribe: () => {// Switching mid-run stops the run, and the stopped run still holds the page busy, so the// transcription would be refused and the clip silently dropped.@@ -515,15 +572,32 @@ export function AudioPage({);const handleUseTextAgain = useCallback((clip: AudioGalleryClip) => {- if (transitionWorkflow(clipWorkflow(clip))) setPrompt(clip.prompt);+ const target = clipWorkflow(clip);+ if (!transitionWorkflow(target)) return;+ if (target === "clone") useAudioCloneStore.getState().setText(clip.prompt);+ else setPrompt(clip.prompt);},[transitionWorkflow, setPrompt],);const pageModelLoaded =- ttsLoaded && (ttsWorkflow === "music") === musicGeneration;+ ttsLoaded &&+ loadedModelRunsWorkflow({+ workflow: ttsWorkflow,+ audioWorkflows: status?.audio_workflows,+ music: musicGeneration,+ });+ const lastPageModel = useAudioWorkspaceStore(+ (state) => state.lastModelByWorkflow[pageWorkflow] ?? null,+ );const openSelector = useCallback(() => setSelectorOpen(true), []);const chooseModelAction = { label: "Choose a model", onClick: openSelector };+ const recommendedCloneActions = clonePageModels(MODELS_BY_MODE.speak, isMac)+ .slice(0, 2)+ .map((model) => ({+ label: `use ${model.name}`,+ onClick: () => void pickRecommendedModel(model.id),+ }));const generateBlocker: GenerateBlocker | null =busy === "loading"? { reason: "Waiting for the model to finish loading." }@@ -534,10 +608,27 @@ export function AudioPage({reason:ttsWorkflow === "music"? "Load a music model to generate."- : "Load a speech model to generate.",- actions: [chooseModelAction],+ : ttsWorkflow === "clone"+ ? "Load a model that can clone a voice."+ : "Load a speech model to generate.",+ actions:+ ttsWorkflow === "clone"+ ? [chooseModelAction, ...recommendedCloneActions]+ : [chooseModelAction],}- : !pageModelLoaded+ : !pageModelLoaded && ttsWorkflow === "clone"+ ? {+ reason: "The loaded model cannot clone a voice.",+ actions: [+ { label: "Choose a model that can clone", onClick: openSelector },+ ...recommendedCloneActions,+ {+ label: "open Speak",+ onClick: () => transitionWorkflow("speak"),+ },+ ],+ }+ : !pageModelLoaded? musicGeneration? {reason: "The loaded model makes music.",@@ -549,17 +640,30 @@ export function AudioPage({},],}- : {- reason: "The loaded model makes speech.",- actions: [- { label: "Choose a music model", onClick: openSelector },- {- label: "open Speak",- onClick: () => transitionWorkflow("speak"),- },- ],- }- : !prompt.trim() && !lyricsOptional+ : ttsWorkflow === "speak"+ ? {+ reason: "The loaded model needs a voice to clone.",+ actions: [+ { label: "Choose a speech model", onClick: openSelector },+ {+ label: "open Clone",+ onClick: () => transitionWorkflow("clone"),+ },+ ],+ }+ : {+ reason: "The loaded model makes speech.",+ actions: [+ { label: "Choose a music model", onClick: openSelector },+ {+ label: "open Speak",+ onClick: () => transitionWorkflow("speak"),+ },+ ],+ }+ : ttsWorkflow === "clone"+ ? clone.blocker+ : !prompt.trim() && !lyricsOptional? {reason:ttsWorkflow === "music"@@ -571,19 +675,28 @@ export function AudioPage({reason:"Add a music description. This model needs one beside the lyrics.",}- : null;- const generateFailure: GenerateBlocker | null = generationError+ : toolBlocker+ ? { reason: toolBlocker }+ : null;+ const pageGenerationError =+ ttsWorkflow === "clone" ? clone.generationError : generationError;+ const generateFailure: GenerateBlocker | null = pageGenerationError? {- reason: /[.!?]$/.test(generationError) ? generationError : `${generationError}.`,+ reason: /[.!?]$/.test(pageGenerationError)+ ? pageGenerationError+ : `${pageGenerationError}.`,actions: [{ label: "Choose a different model", onClick: openSelector }],}: null;+ const setCloneGenerationError = clone.setGenerationError;useEffect(() => {setGenerationError(null);- }, [status?.active_model, setGenerationError]);+ setCloneGenerationError(null);+ }, [status?.active_model, setGenerationError, setCloneGenerationError]);useEffect(() => {if (busy === "generating") setGenerationError(null);- }, [busy, setGenerationError]);+ if (busy === "generating") setCloneGenerationError(null);+ }, [busy, setGenerationError, setCloneGenerationError]);const [elapsedSeconds, setElapsedSeconds] = useState<number | null>(null);useEffect(() => {if (busy !== "generating") {@@ -607,8 +720,10 @@ export function AudioPage({const shortcutLabel = isMac ? "⌘ Enter" : "Ctrl+Enter";const pageRootRef = useRef<HTMLDivElement | null>(null);const generateShortcut = useRef<() => void>(() => {});+ const handlePageGenerate =+ ttsWorkflow === "clone" ? clone.handleGenerate : handleGenerate;generateShortcut.current = () => {- if (canGenerate) void handleGenerate();+ if (canGenerate) void handlePageGenerate();};useEffect(() => {if (!active) return;@@ -627,13 +742,13 @@ export function AudioPage({document.addEventListener("keydown", onKeyDown);return () => document.removeEventListener("keydown", onKeyDown);}, [active]);- const instructionsKind = instructionsFieldKind(ttsWorkflow, status?.audio_type);-const selectorModels =mode === "speak"? ttsWorkflow === "music"? musicPageModels(MODELS_BY_MODE.speak, isMac)- : speakPageModels(MODELS_BY_MODE.speak, isMac)+ : ttsWorkflow === "clone"+ ? clonePageModels(MODELS_BY_MODE.speak, isMac)+ : speakPageModels(MODELS_BY_MODE.speak, isMac): MODELS_BY_MODE[mode];const selectorRowFilter = useCallback((row: AudioPickerRow) =>@@ -665,24 +780,40 @@ export function AudioPage({artifact.engine === sttLoadedEngine,} satisfies ModelOption;});+ // Arriving on a page never loads: the picker shows the page's last model, unloaded, to re-pick.+ const showLastPageModel =+ mode === "speak" && !pageModelLoaded && lastPageModel !== null;const selectorValue =mode === "speak"- ? (status?.active_model ?? undefined)+ ? showLastPageModel+ ? lastPageModel+ : (status?.active_model ?? undefined): (selectedSttRepo ?? undefined);const capabilityLine =mode === "speak"- ? ttsLoaded+ ? showLastPageModel+ ? `${lastPageModel.split("/").pop()} is not loaded. Pick it above to load it.`+ : ttsLoaded? pageModelLoaded- ? audioCapabilityLine(musicGeneration ? "music" : "tts", status?.audio_type)- : musicGeneration+ ? audioCapabilityLine(+ musicGeneration ? "music" : ttsWorkflow === "clone" ? "clone" : "tts",+ status?.audio_type,+ )+ : ttsWorkflow === "clone"+ ? "The loaded model cannot clone a voice."+ : musicGeneration? "The loaded model makes music. Pick a speech model."- : "The loaded model is not a music model."+ : ttsWorkflow === "speak"+ ? "The loaded model needs a voice to clone. Pick a speech model."+ : "The loaded model is not a music model.": status?.active_model? "The loaded model is not a TTS audio model.": ttsWorkflow === "music"? "No music model loaded."- : "No TTS model loaded."+ : ttsWorkflow === "clone"+ ? "No voice cloning model loaded."+ : "No TTS model loaded.": sttSelected? audioCapabilityLine("stt", sttReady ? "ready" : "loading"): "No transcription model selected.";@@ -720,7 +851,9 @@ export function AudioPage({additionalOnDeviceModels={mode === "transcribe"? sttOnDeviceModels- : trainedTtsModels.filter(+ : ttsWorkflow === "clone"+ ? []+ : trainedTtsModels.filter((model) =>isMusicGenerationModel(model.id, model.audioType) ===(ttsWorkflow === "music"),@@ -732,10 +865,20 @@ export function AudioPage({? (selectedSttRepo ?? undefined): undefined}- loaded={mode === "transcribe" ? sttReady : undefined}+ loaded={+ mode === "transcribe"+ ? sttReady+ : showLastPageModel+ ? false+ : undefined+ }value={selectorValue}onValueChange={handleModelSelect}- onEject={busy === null && selectorValue ? handleEject : undefined}+ onEject={+ busy === null && selectorValue && !showLastPageModel+ ? handleEject+ : undefined+ }variant="ghost"className="!h-[calc(34px*var(--ui-space-scale,1))] max-w-full gap-1 overflow-hidden pl-3 pr-1 @[68rem]:gap-2 @[68rem]:pl-4 @[68rem]:pr-2"triggerLabelClassName="text-ui-14 @[68rem]:text-ui-16"@@ -843,22 +986,17 @@ export function AudioPage({const railProps = {prompt,setPrompt,- toolPanels: instructionsKind ? (- <>- <InstructionsField- instructionsKind={instructionsKind}- musicNeedsDescription={musicNeedsDescription}- audioInstructions={audioInstructions}- setAudioInstructions={setAudioInstructions}- />- {instructionsKind === "style" ? (- <MossLanguageField- audioLanguage={audioLanguage}- setAudioLanguage={setAudioLanguage}- />- ) : null}- </>- ) : null,+ toolPanels: (+ <AudioToolPanels+ workflow={ttsWorkflow === "music" ? "music" : "speak"}+ ctx={toolContext}+ values={toolValues}+ onChange={handleToolValueChange}+ specs={audioOptionSpecs}+ disabled={busy === "generating"}+ core={{ text: prompt }}+ />+ ),audioDevice,busy,isRecording,@@ -868,6 +1006,7 @@ export function AudioPage({handleEject,samplingControls,audioOptionSpecs,+ claimedOptions,advancedOpen,setAdvancedOpen,temperature,@@ -888,6 +1027,14 @@ export function AudioPage({};return ttsWorkflow === "music" ? (<MusicRail {...railProps} />+ ) : ttsWorkflow === "clone" ? (+ <AudioActiveProvider value={active}>+ <CloneRail+ {...railProps}+ clone={clone}+ historyClips={clips}+ />+ </AudioActiveProvider>) : (<SpeakRail {...railProps} />);@@ -909,21 +1056,35 @@ export function AudioPage({{mode === "speak" ? (/* The scroll mask provides the fade; leave the footer unpainted to avoid dark-mode banding. */<div className="relative z-10 flex shrink-0 justify-center px-10 pt-0.5 pb-4">- <TtsFooter- busy={busy}- generationPresentation={generationPresentation}- handleStopGeneration={handleStopGeneration}- handleGenerate={handleGenerate}- ttsLoaded={pageModelLoaded}- prompt={prompt}- lyricsOptional={lyricsOptional}- musicNeedsDescription={musicNeedsDescription}- audioInstructions={audioInstructions}- blocker={generateBlocker}- shortcutLabel={shortcutLabel}- error={generateFailure}- elapsedSeconds={elapsedSeconds}- />+ {ttsWorkflow === "clone" ? (+ <CloneFooter+ busy={busy}+ generationPresentation={generationPresentation}+ handleStopGeneration={handleStopGeneration}+ ttsLoaded={pageModelLoaded}+ blocker={generateBlocker}+ shortcutLabel={shortcutLabel}+ error={generateFailure}+ elapsedSeconds={elapsedSeconds}+ clone={clone}+ />+ ) : (+ <TtsFooter+ busy={busy}+ generationPresentation={generationPresentation}+ handleStopGeneration={handleStopGeneration}+ handleGenerate={handleGenerate}+ ttsLoaded={pageModelLoaded}+ prompt={prompt}+ lyricsOptional={lyricsOptional}+ musicNeedsDescription={musicNeedsDescription}+ audioInstructions={audioInstructions}+ blocker={generateBlocker}+ shortcutLabel={shortcutLabel}+ error={generateFailure}+ elapsedSeconds={elapsedSeconds}+ />+ )}</div>) : null}</div>@@ -1015,6 +1176,13 @@ export function AudioPage({};return ttsWorkflow === "music" ? (<MusicOutput {...outputProps} modelReady={pageModelLoaded} />+ ) : ttsWorkflow === "clone" ? (+ <CloneOutput+ {...outputProps}+ modelReady={pageModelLoaded}+ recommendedModels={selectorModels}+ onPickModel={pickRecommendedModel}+ />) : (<SpeakOutput {...outputProps} modelReady={pageModelLoaded} />);diff --git a/studio/frontend/src/features/audio/audio-run-request.ts b/studio/frontend/src/features/audio/audio-run-request.tsnew file mode 100644index 00000000000..55e48b8d62f--- /dev/null+++ b/studio/frontend/src/features/audio/audio-run-request.ts@@ -0,0 +1,179 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// No app imports: the node test runner loads this directly. Clients send ids only, never paths or audio.++/** Mirrors AUDIO_INPUT_MAX_BYTES in studio/backend/utils/upload_limits.py. */+export const AUDIO_INPUT_MAX_BYTES = 200 * 1024 * 1024;++export const REFERENCE_MAX_SECONDS = 30;++export type AudioSourceRef =+ | { input_id: string }+ | { clip_id: string }+ | { voice_id: string };++export interface AudioSourceSelection {+ kind: "input" | "clip" | "voice";+ id: string;+ name: string;+ durationS: number | null;+ expiresAt?: string | null;+ transcript?: string | null;+ language?: string | null;+}++/** A gallery clip as a source: its text doubles as the transcript. */+export function clipReference(clip: {+ id: string;+ prompt: string;+ duration_s: number | null;+}): AudioSourceSelection {+ return {+ kind: "clip",+ id: clip.id,+ name: clip.prompt || "Generated clip",+ durationS: clip.duration_s,+ transcript: clip.prompt || null,+ language: null,+ };+}++export function sourceRefOf(selection: AudioSourceSelection): AudioSourceRef {+ switch (selection.kind) {+ case "input":+ return { input_id: selection.id };+ case "clip":+ return { clip_id: selection.id };+ default:+ return { voice_id: selection.id };+ }+}++export function sourceFileUrl(selection: AudioSourceSelection): string {+ const id = encodeURIComponent(selection.id);+ switch (selection.kind) {+ case "input":+ return `/api/inference/audio/inputs/${id}/file`;+ case "clip":+ return `/api/inference/audio/gallery/${id}/file`;+ default:+ return `/api/inference/audio/voices/${id}/file`;+ }+}++export function transcribeUrl(ref: AudioSourceRef): string {+ if ("input_id" in ref) {+ return `/api/inference/audio/inputs/${encodeURIComponent(ref.input_id)}/transcribe`;+ }+ const query =+ "clip_id" in ref+ ? `clip_id=${encodeURIComponent(ref.clip_id)}`+ : `voice_id=${encodeURIComponent(ref.voice_id)}`;+ return `/api/inference/audio/inputs/source/transcribe?${query}`;+}++export function selectionExpired(+ selection: AudioSourceSelection | null,+ nowMs: number,+): boolean {+ if (!selection || selection.kind !== "input" || !selection.expiresAt)+ return false;+ const expires = Date.parse(selection.expiresAt);+ return Number.isFinite(expires) && expires <= nowMs;+}++export interface AudioRunRequest {+ workflow: "clone" | "speak";+ text: string;+ language?: string | null;+ instructions?: string | null;+ inputs?: {+ reference?: AudioSourceRef | null;+ reference_text?: string | null;+ emotion?: AudioSourceRef | null;+ };+ options?: Record<string, boolean | number | string>;+ speed?: number | null;+ seed?: number | null;+ max_tokens?: number | null;+}++function cleanRef(+ ref: AudioSourceRef | null | undefined,+): Record<string, unknown> | null {+ if (!ref) return null;+ const out: Record<string, unknown> = {};+ for (const key of ["input_id", "clip_id", "voice_id"] as const) {+ const value = (ref as Record<string, unknown>)[key];+ if (typeof value === "string" && value) out[key] = value;+ }+ return Object.keys(out).length === 1 ? out : null;+}++/** Allowed keys only, empty values dropped: the route 422s on extra keys. */+export function buildAudioRunBody(+ request: AudioRunRequest,+): Record<string, unknown> {+ const body: Record<string, unknown> = {+ workflow: request.workflow,+ text: request.text,+ };+ const language = request.language?.trim();+ if (language) body.language = language;+ const instructions = request.instructions?.trim();+ if (instructions) body.instructions = instructions;+ const inputs: Record<string, unknown> = {};+ const reference = cleanRef(request.inputs?.reference);+ if (reference) inputs.reference = reference;+ const rawReferenceText = request.inputs?.reference_text;+ // A cleared field is sent blank, so the server does not refill it from a saved voice.+ if (typeof rawReferenceText === "string") {+ inputs.reference_text = rawReferenceText.trim();+ }+ const emotion = cleanRef(request.inputs?.emotion);+ if (emotion) inputs.emotion = emotion;+ if (Object.keys(inputs).length > 0) body.inputs = inputs;+ const options = Object.fromEntries(+ Object.entries(request.options ?? {}).filter(+ ([name, value]) =>+ name &&+ (typeof value === "boolean" ||+ typeof value === "string" ||+ (typeof value === "number" && Number.isFinite(value))),+ ),+ );+ if (Object.keys(options).length > 0) body.options = options;+ if (typeof request.speed === "number" && Number.isFinite(request.speed))+ body.speed = request.speed;+ if (typeof request.seed === "number" && Number.isInteger(request.seed))+ body.seed = request.seed;+ if (typeof request.max_tokens === "number" && request.max_tokens > 0)+ body.max_tokens = request.max_tokens;+ return body;+}++export interface AudioVoiceCreateRequest {+ source: AudioSourceRef;+ name: string;+ transcript?: string | null;+ language?: string | null;+}++export function buildVoiceCreateBody(+ request: AudioVoiceCreateRequest,+): Record<string, unknown> {+ const source = cleanRef(request.source);+ if (!source || "voice_id" in source) {+ throw new Error("A saved voice is made from an upload or a history clip.");+ }+ const body: Record<string, unknown> = {+ source,+ name: request.name.trim().slice(0, 80),+ };+ const transcript = request.transcript?.trim();+ if (transcript) body.transcript = transcript.slice(0, 4000);+ const language = request.language?.trim();+ if (language) body.language = language.slice(0, 64);+ return body;+}diff --git a/studio/frontend/src/features/audio/catalog.ts b/studio/frontend/src/features/audio/catalog.tsindex 04fbca20378..11d30e56061 100644--- a/studio/frontend/src/features/audio/catalog.ts+++ b/studio/frontend/src/features/audio/catalog.ts@@ -147,16 +147,18 @@ export function audioModelsForTask(task: AudioTask): ModelOption[] {return AUDIO_MODEL_OPTIONS.filter(matches);}+const CAPABILITY_LABEL: Record<AudioTask | "music" | "clone", string> = {+ music: "Music generation",+ clone: "Voice cloning",+ tts: "Text-to-speech",+ stt: "Speech-to-text",+};+export function audioCapabilityLine(- task: AudioTask | "music",+ task: AudioTask | "music" | "clone",detail?: string | null,): string {- const base =- task === "music"- ? "Music generation"- : task === "tts"- ? "Text-to-speech"- : "Speech-to-text";+ const base = CAPABILITY_LABEL[task];// GGUF audio models report one runtime-wide type; the internal name means nothing to a user.const shown = detail && AUDIO_CPP_AUDIO_TYPES.has(detail) ? "GGUF" : detail;return shown ? `${base} · ${shown}` : base;diff --git a/studio/frontend/src/features/audio/clone-policy.ts b/studio/frontend/src/features/audio/clone-policy.tsnew file mode 100644index 00000000000..0d216677d03--- /dev/null+++ b/studio/frontend/src/features/audio/clone-policy.ts@@ -0,0 +1,134 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// No app imports: the node test runner loads this directly.++import type { AudioSourceSelection } from "./audio-run-request";+import type { AudioModelContext, AudioRunPatch } from "./tools/types";++type ReferenceTextField = "required" | "optional" | "hidden";++export function referenceTextField(+ ctx: Pick<AudioModelContext, "referenceTextMode">,+ patch: Pick<AudioRunPatch, "referenceTextMode">,+): ReferenceTextField {+ if (patch.referenceTextMode) return patch.referenceTextMode;+ switch (ctx.referenceTextMode) {+ case "required":+ return "required";+ case "unused":+ return "hidden";+ default:+ return "optional";+ }+}++/** Qwen3-TTS spellings; the backend maps them for other clone families. */+export const QWEN3_LANGUAGE_NAMES = [+ "Chinese",+ "English",+ "Japanese",+ "Korean",+ "German",+ "French",+ "Russian",+ "Portuguese",+ "Spanish",+ "Italian",+] as const;++export const CLONE_TEXT_EXAMPLES = [+ "Thanks for calling. How can I help you today?",+ "The quick brown fox jumps over the lazy dog near the river bank.",+ "Welcome back. Here is a short summary of what changed this week.",+] as const;++const SPEAKER_LINE = /^\s*Speaker\s*\d+\s*:/im;++export function formatVibeVoiceScript(text: string): string {+ const trimmed = text.trim();+ if (!trimmed || SPEAKER_LINE.test(trimmed)) return trimmed;+ return `Speaker 1: ${trimmed}`;+}++/** Order matters: it is the runtime's vector order. */+export const INDEX_TTS2_EMOTIONS = [+ { key: "happy", label: "Happy" },+ { key: "angry", label: "Angry" },+ { key: "sad", label: "Sad" },+ { key: "afraid", label: "Afraid" },+ { key: "disgusted", label: "Disgusted" },+ { key: "melancholic", label: "Melancholic" },+ { key: "surprised", label: "Surprised" },+ { key: "calm", label: "Calm" },+] as const;++export function emotionVectorString(vector: readonly number[]): string {+ return INDEX_TTS2_EMOTIONS.map((_, index) => {+ const value = vector[index];+ const clamped =+ typeof value === "number" && Number.isFinite(value)+ ? Math.min(1, Math.max(0, value))+ : 0;+ return String(Number(clamped.toFixed(2)));+ }).join(",");+}++type CloneBlockerKind =+ | "reference"+ | "reference-busy"+ | "reference-expired"+ | "reference-error"+ | "reference-text"+ | "text"+ | "panel";++interface CloneBlockerInput {+ reference: AudioSourceSelection | null;+ referenceBusy: boolean;+ referenceExpired: boolean;+ referenceError: string | null;+ referenceText: string;+ referenceTextField: ReferenceTextField;+ text: string;+ panelError: string | null;+}++export function cloneBlocker(+ input: CloneBlockerInput,+): { kind: CloneBlockerKind; reason: string } | null {+ if (input.referenceExpired) {+ return {+ kind: "reference-expired",+ // The "Add it again" action follows the reason under Generate.+ reason: "This reference expired.",+ };+ }+ if (input.referenceBusy) {+ return {+ kind: "reference-busy",+ reason: "Waiting for the reference to finish uploading.",+ };+ }+ // A failed replacement hides the kept clip, so Generate waits until it is dismissed.+ if (input.referenceError) {+ return { kind: "reference-error", reason: input.referenceError };+ }+ if (!input.reference) {+ return {+ kind: "reference",+ reason: "Needs a short clip of the voice to copy.",+ };+ }+ if (input.referenceTextField === "required" && !input.referenceText.trim()) {+ return {+ kind: "reference-text",+ reason: "This model needs what's said in the clip.",+ };+ }+ if (!input.text.trim()) {+ return { kind: "text", reason: "Type the text to speak." };+ }+ if (input.panelError) return { kind: "panel", reason: input.panelError };+ return null;+}diff --git a/studio/frontend/src/features/audio/components/audio-source-input.tsx b/studio/frontend/src/features/audio/components/audio-source-input.tsxnew file mode 100644index 00000000000..fb25488046b--- /dev/null+++ b/studio/frontend/src/features/audio/components/audio-source-input.tsx@@ -0,0 +1,446 @@+// 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 { Progress } from "@/components/ui/progress";+import { PillTabs } from "@/features/model-picker/components/model-selector/pill-tabs";+import {+ nativeAttachmentIntentToFile,+ registerNativeAttachmentPath,+ useNativeDropTarget,+} from "@/features/native-intents";+import { cn } from "@/lib/utils";+import {+ Alert02Icon,+ AudioWave01Icon,+ Cancel01Icon,+ Mic01Icon,+ StopIcon,+ Upload04Icon,+} from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import {+ type ReactNode,+ type Ref,+ createContext,+ useContext,+ useEffect,+ useImperativeHandle,+ useRef,+ useState,+} from "react";+import type { AudioGalleryClip } from "../api";+import {+ type AudioSourceSelection,+ REFERENCE_MAX_SECONDS,+ clipReference,+} from "../audio-run-request";+import {+ type AudioSourceStatus,+ REFERENCE_EXPIRED_MESSAGE,+} from "../hooks/audio-source-state";+import { recordingSupported, useAudioSource } from "../hooks/use-audio-source";+import { VoicePicker } from "./voice-picker";+import { Waveform } from "./waveform";+import { formatSeconds } from "./waveform-peaks";++const AudioHistoryContext = createContext<readonly AudioGalleryClip[]>([]);+export const AudioHistoryProvider = AudioHistoryContext.Provider;+// False while the persistently mounted Audio page is hidden, so no card keeps the mic.+const AudioActiveContext = createContext(true);+export const AudioActiveProvider = AudioActiveContext.Provider;++type SourceTab = "upload" | "record" | "history" | "voice";++const AUDIO_EXTS = "wav mp3 flac ogg oga opus m4a aac webm mp4".split(" ");+const AUDIO_ACCEPT = `audio/*,${AUDIO_EXTS.map((ext) => `.${ext}`).join(",")}`;++const SOURCE_LABEL: Record<AudioSourceSelection["kind"], string> = {+ input: "Upload",+ clip: "From history",+ voice: "Saved voice",+};++export interface AudioSourceInputHandle {+ focus: () => void;+ browse: () => void;+ markExpired: () => void;+}++function AlertLine({ children }: { children: ReactNode }) {+ return (+ <p+ role="alert"+ className="flex items-start gap-1.5 text-ui-12 leading-snug text-foreground"+ >+ <HugeiconsIcon+ icon={Alert02Icon}+ className="mt-0.5 size-3.5 shrink-0 text-destructive"+ />+ {children}+ </p>+ );+}++export function AudioSourceInput({+ id,+ label,+ hint,+ value,+ onChange,+ disabled = false,+ allowHistory = true,+ allowSavedVoice = true,+ handleRef,+ onStatusChange,+ maxRecordSeconds,+ expiredMessage = REFERENCE_EXPIRED_MESSAGE,+ usesFirstSeconds = REFERENCE_MAX_SECONDS,+ recordHint = "Read a sentence or two in a quiet room.",+}: {+ id: string;+ label: string;+ hint?: string;+ value: AudioSourceSelection | null;+ onChange: (next: AudioSourceSelection | null) => void;+ disabled?: boolean;+ allowHistory?: boolean;+ allowSavedVoice?: boolean;+ handleRef?: Ref<AudioSourceInputHandle>;+ onStatusChange?: (status: AudioSourceStatus) => void;+ maxRecordSeconds?: number;+ /** The card's copy defaults to a clone reference; other pages pass their own. */+ expiredMessage?: string;+ usesFirstSeconds?: number | null;+ recordHint?: string;+}) {+ const active = useContext(AudioActiveContext);+ const source = useAudioSource({ value, onChange, maxRecordSeconds, active });+ const history = useContext(AudioHistoryContext);+ const [tab, setTab] = useState<SourceTab>("upload");+ const [dragging, setDragging] = useState(false);+ const cardRef = useRef<HTMLDivElement | null>(null);+ const fileRef = useRef<HTMLInputElement | null>(null);+ const { status, preview } = source;+ const recording = status.phase === "recording";+ const uploading = status.phase === "uploading";+ const showSelected = value !== null || uploading;++ const onStatusChangeRef = useRef(onStatusChange);+ onStatusChangeRef.current = onStatusChange;+ useEffect(() => {+ onStatusChangeRef.current?.(status);+ }, [status]);++ useImperativeHandle(handleRef, () => ({+ focus: () => cardRef.current?.focus(),+ browse: () => fileRef.current?.click(),+ markExpired: source.expire,+ }));++ // Tauri hands drops over as paths.+ const nativeDropRef = useNativeDropTarget({+ enabled: !disabled,+ onDragOver: setDragging,+ onDrop: (paths) => {+ setDragging(false);+ const path = paths[0];+ if (!path) return;+ const extension = path.split(".").pop()?.toLowerCase() ?? "";+ if (!AUDIO_EXTS.includes(extension)) {+ source.fail(+ "This is not an audio file. Pick a WAV, MP3, FLAC, OGG or M4A file.",+ );+ return;+ }+ void registerNativeAttachmentPath(path)+ .then(nativeAttachmentIntentToFile)+ .then((file) => source.pickFile(file))+ .catch(() => source.fail("Could not read the dropped file."));+ },+ });++ const tabs = [+ { value: "upload", label: "Upload" },+ ...(recordingSupported() ? [{ value: "record", label: "Record" }] : []),+ ...(allowHistory ? [{ value: "history", label: "From history" }] : []),+ ...(allowSavedVoice ? [{ value: "voice", label: "Saved voice" }] : []),+ ];++ const durationS = preview.durationS ?? value?.durationS ?? null;+ const name = status.phase === "uploading" ? status.name : (value?.name ?? "");++ return (+ // biome-ignore lint/a11y/noNoninteractiveTabindex: the card takes focus so "Add reference audio" can bring the user to it.+ <section+ ref={(element) => {+ cardRef.current = element as HTMLDivElement | null;+ nativeDropRef(element);+ }}+ tabIndex={-1}+ aria-labelledby={`${id}-label`}+ aria-busy={uploading || status.phase === "loading"}+ onDragOver={(event) => {+ if (disabled || !event.dataTransfer.types.includes("Files")) return;+ event.preventDefault();+ setDragging(true);+ }}+ onDragLeave={(event) => {+ if (!event.currentTarget.contains(event.relatedTarget as Node | null))+ setDragging(false);+ }}+ onDrop={(event) => {+ if (disabled) return;+ event.preventDefault();+ setDragging(false);+ const file = event.dataTransfer.files?.[0];+ if (file) void source.pickFile(file);+ }}+ className={cn(+ "corner-squircle grid gap-3 rounded-4xl bg-card p-4 ring-1 outline-none transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-ring",+ dragging+ ? "bg-accent ring-[color-mix(in_oklab,var(--foreground)_calc(40%*var(--contrast-edge-gain,1)),transparent)]"+ : "ring-[color-mix(in_oklab,var(--foreground)_calc(10%*var(--contrast-edge-gain,1)),transparent)]",+ )}+ >+ <div className="flex items-center justify-between gap-2">+ <span+ id={`${id}-label`}+ className="text-ui-13 font-medium text-foreground"+ >+ {label}+ </span>+ {showSelected ? (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="h-auto px-2 py-1 text-ui-11p5"+ disabled={disabled}+ onClick={source.clear}+ >+ <HugeiconsIcon icon={Cancel01Icon} className="size-3" />+ Remove+ </Button>+ ) : null}+ </div>++ <input+ ref={fileRef}+ id={`${id}-file`}+ type="file"+ accept={AUDIO_ACCEPT}+ className="hidden"+ onChange={(event) => {+ const file = event.target.files?.[0];+ event.target.value = "";+ if (file) void source.pickFile(file);+ }}+ />++ {status.phase === "expired" ? (+ <div className="grid gap-2">+ <AlertLine>{expiredMessage}</AlertLine>+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="self-start"+ onClick={() => {+ source.clear();+ fileRef.current?.click();+ }}+ >+ Add it again+ </Button>+ </div>+ ) : showSelected && status.phase !== "error" ? (+ <div className="grid gap-2">+ <div className="flex min-w-0 items-center gap-2 text-ui-12">+ <HugeiconsIcon+ icon={AudioWave01Icon}+ className="size-3.5 shrink-0 text-muted-foreground"+ />+ <span+ className="min-w-0 flex-1 truncate text-foreground"+ title={name}+ >+ {name}+ </span>+ {value ? (+ <span className="shrink-0 rounded-4xl bg-muted px-2 py-0.5 text-ui-11 text-muted-foreground">+ {SOURCE_LABEL[value.kind]}+ </span>+ ) : null}+ </div>+ <Waveform+ peaks={preview.peaks}+ durationS={durationS}+ src={preview.url}+ label={name || label}+ />+ {status.phase === "uploading" ? (+ <div className="grid gap-1">+ <Progress+ value={+ status.progress === null ? undefined : status.progress * 100+ }+ indeterminate={status.progress === null}+ aria-label="Upload progress"+ className="h-1"+ />+ <output+ aria-live="polite"+ className="text-ui-11p5 text-muted-foreground"+ >+ {status.progress === null+ ? "Uploading…"+ : `Uploading ${Math.round(status.progress * 100)} %`}+ </output>+ </div>+ ) : status.phase === "loading" ? (+ <output className="text-ui-11p5 text-muted-foreground">+ Loading the clip…+ </output>+ ) : usesFirstSeconds !== null &&+ durationS !== null &&+ durationS > usesFirstSeconds ? (+ <p className="text-ui-11p5 leading-snug text-muted-foreground">+ Uses the first {usesFirstSeconds} s.+ </p>+ ) : null}+ </div>+ ) : (+ <div className="grid gap-3">+ {status.phase === "error" ? (+ <div className="grid gap-2">+ <AlertLine>{status.message}</AlertLine>+ <div className="flex flex-wrap gap-2">+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => {+ source.dismissError();+ fileRef.current?.click();+ }}+ >+ Try another file+ </Button>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={source.dismissError}+ >+ Dismiss+ </Button>+ </div>+ </div>+ ) : null}+ {tabs.length > 1 ? (+ <PillTabs+ ariaLabel={`${label} source`}+ value={recording ? "record" : tab}+ onValueChange={(next) => setTab(next as SourceTab)}+ disabled={disabled || recording}+ fit={true}+ compact={true}+ className="[&>button]:px-3"+ tabs={tabs}+ />+ ) : null}+ {tab === "upload" && !recording ? (+ <button+ type="button"+ disabled={disabled}+ onClick={() => fileRef.current?.click()}+ className="flex min-h-[calc(88px*var(--ui-space-scale,1))] flex-col items-center justify-center gap-1 rounded-xl border border-dashed border-border px-3 text-ui-12 text-muted-foreground transition-colors hover:border-[color-mix(in_oklab,var(--foreground)_calc(30%*var(--contrast-edge-gain,1)),transparent)] hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <HugeiconsIcon icon={Upload04Icon} className="size-5" />+ <span>Drop an audio file here, or choose one</span>+ {hint ? <span className="text-ui-11p5">{hint}</span> : null}+ </button>+ ) : null}+ {tab === "record" || recording ? (+ <div className="flex items-center gap-3">+ <Button+ type="button"+ variant={recording ? "destructive" : "outline"}+ disabled={disabled}+ onClick={() =>+ recording+ ? source.stopRecording()+ : void source.startRecording()+ }+ >+ <HugeiconsIcon+ icon={recording ? StopIcon : Mic01Icon}+ className="size-4"+ />+ {recording ? "Stop" : "Record"}+ </Button>+ <output+ aria-live="polite"+ className="text-ui-12 text-muted-foreground"+ >+ {recording ? (+ <>+ Recording{" "}+ <span className="font-mono tabular-nums">+ {formatSeconds(source.elapsed)}+ </span>+ </>+ ) : (+ recordHint+ )}+ </output>+ </div>+ ) : null}+ {tab === "history" && !recording ? (+ history.length === 0 ? (+ <p className="text-ui-12 leading-snug text-muted-foreground">+ Clips you make in Audio show up here.+ </p>+ ) : (+ <ul className="hover-scrollbar grid min-w-0 max-h-[calc(196px*var(--ui-space-scale,1))] grid-cols-[minmax(0,1fr)] gap-0.5 overflow-y-auto">+ {history.map((clip) => (+ <li key={clip.id} className="min-w-0">+ <button+ type="button"+ disabled={disabled}+ onClick={() => onChange(clipReference(clip))}+ className="flex w-full min-w-0 items-center gap-2 rounded-full px-3 py-1.5 text-left text-ui-13 transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <span className="min-w-0 flex-1 truncate">+ {clip.prompt}+ </span>+ <span className="shrink-0 font-mono text-ui-11p5 tabular-nums text-muted-foreground">+ {formatSeconds(clip.duration_s)}+ </span>+ </button>+ </li>+ ))}+ </ul>+ )+ ) : null}+ {tab === "voice" && !recording ? (+ <VoicePicker+ disabled={disabled}+ onSelect={(voice) =>+ onChange({+ kind: "voice",+ id: voice.id,+ name: voice.name,+ durationS: voice.duration_s,+ transcript: voice.transcript,+ language: voice.language,+ })+ }+ />+ ) : null}+ </div>+ )}+ </section>+ );+}diff --git a/studio/frontend/src/features/audio/components/instructions-fields.tsx b/studio/frontend/src/features/audio/components/instructions-fields.tsxindex 525f2f5c7cc..5f103b93112 100644--- a/studio/frontend/src/features/audio/components/instructions-fields.tsx+++ b/studio/frontend/src/features/audio/components/instructions-fields.tsx@@ -9,11 +9,13 @@ import { Field } from "./field";export function InstructionsField({instructionsKind,musicNeedsDescription,+ voiceRequired = false,audioInstructions,setAudioInstructions,}: {instructionsKind: NativeAudioInstructionsKind;musicNeedsDescription: boolean;+ voiceRequired?: boolean;audioInstructions: string;setAudioInstructions: (value: string) => void;}) {@@ -36,7 +38,9 @@ export function InstructionsField({: instructionsKind === "scene"? "Optional Higgs TTS 2 scene guidance such as room acoustics, recording conditions, or background ambience.": instructionsKind === "voice"- ? "Optional. Used by Qwen3-TTS VoiceDesign, Qwen3-TTS CustomVoice and VoxCPM2; other models ignore it."+ ? voiceRequired+ ? "Required by this model. Describe the voice, accent, age and delivery."+ : "Optional. Used by Qwen3-TTS VoiceDesign, Qwen3-TTS CustomVoice and VoxCPM2; other models ignore it.": "Optional MOSS Local guidance such as speaking style, emotion, pace, or delivery."}htmlFor="audio-instructions"diff --git a/studio/frontend/src/features/audio/components/language-select.tsx b/studio/frontend/src/features/audio/components/language-select.tsxnew file mode 100644index 00000000000..da2f86a42cf--- /dev/null+++ b/studio/frontend/src/features/audio/components/language-select.tsx@@ -0,0 +1,64 @@+// 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 {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { QWEN3_LANGUAGE_NAMES } from "../clone-policy";++// Radix Select cannot hold an empty value, so "no language" travels as this.+const AUTO = "__auto__";++export function LanguageSelect({+ id,+ label,+ value,+ onChange,+ emptyLabel = "Auto",+ hint,+ disabled,+}: {+ id: string;+ label: string;+ value: string;+ onChange: (value: string) => void;+ emptyLabel?: string;+ hint?: string;+ disabled?: boolean;+}) {+ const names: string[] = [...QWEN3_LANGUAGE_NAMES];+ if (value && !names.includes(value)) names.push(value);+ return (+ <div className="grid gap-1.5">+ <label className="text-ui-13 font-medium text-foreground" htmlFor={id}>+ {label}+ </label>+ <Select+ value={value || AUTO}+ onValueChange={(next) => onChange(next === AUTO ? "" : next)}+ disabled={disabled}+ >+ <SelectTrigger id={id} size="sm" className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value={AUTO}>{emptyLabel}</SelectItem>+ {names.map((name) => (+ <SelectItem key={name} value={name}>+ {name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ {hint ? (+ <p className="text-ui-11p5 leading-snug text-muted-foreground">+ {hint}+ </p>+ ) : null}+ </div>+ );+}diff --git a/studio/frontend/src/features/audio/components/save-voice-dialog.tsx b/studio/frontend/src/features/audio/components/save-voice-dialog.tsxnew file mode 100644index 00000000000..82d1e5e95e8--- /dev/null+++ b/studio/frontend/src/features/audio/components/save-voice-dialog.tsx@@ -0,0 +1,178 @@+// 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 {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { Textarea } from "@/components/ui/textarea";+import { useEffect, useState } from "react";+import { useAudioVoicesStore } from "../stores/audio-voices-store";+import { Field } from "./field";+import { LanguageSelect } from "./language-select";++export interface VoiceDetails {+ name: string;+ transcript: string;+ language: string;+}++export function SaveVoiceDialog({+ open,+ onOpenChange,+ mode,+ initial,+ voiceId,+ onSubmit,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ mode: "create" | "edit";+ initial: VoiceDetails;+ /** The voice being edited, which may keep its own name. */+ voiceId?: string;+ onSubmit: (details: VoiceDetails) => Promise<void>;+}) {+ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="corner-squircle dialog-soft-surface gap-5 sm:max-w-md">+ {/* Content unmounts on close, so each open starts from its own values. */}+ <SaveVoiceForm+ mode={mode}+ initial={initial}+ voiceId={voiceId}+ onCancel={() => onOpenChange(false)}+ onSubmit={async (details) => {+ await onSubmit(details);+ onOpenChange(false);+ }}+ />+ </DialogContent>+ </Dialog>+ );+}++function SaveVoiceForm({+ mode,+ initial,+ voiceId,+ onCancel,+ onSubmit,+}: {+ mode: "create" | "edit";+ initial: VoiceDetails;+ voiceId?: string;+ onCancel: () => void;+ onSubmit: (details: VoiceDetails) => Promise<void>;+}) {+ const [name, setName] = useState(initial.name.slice(0, 80));+ const [transcript, setTranscript] = useState(initial.transcript);+ const [language, setLanguage] = useState(initial.language);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const clean = name.trim();+ // Voices are picked by name, so two with the same name could not be told apart.+ // The list loads with the voice picker, which this dialog can open without.+ useEffect(() => {+ const voices = useAudioVoicesStore.getState();+ if (!voices.loaded) void voices.refresh();+ }, []);+ const taken = useAudioVoicesStore((state) =>+ state.voices.some(+ (voice) =>+ voice.id !== voiceId &&+ voice.name.trim().toLowerCase() === clean.toLowerCase(),+ ),+ );++ const submit = async () => {+ if (!clean || taken || saving) return;+ setSaving(true);+ setError(null);+ try {+ await onSubmit({ name: clean, transcript: transcript.trim(), language });+ } catch (reason) {+ setError(+ reason instanceof Error ? reason.message : "Could not save the voice.",+ );+ setSaving(false);+ }+ };++ return (+ <form+ className="grid gap-5"+ onSubmit={(event) => {+ event.preventDefault();+ void submit();+ }}+ >+ <DialogHeader>+ <DialogTitle className="text-ui-21">+ {mode === "create" ? "Save voice" : "Edit voice"}+ </DialogTitle>+ <DialogDescription>+ {mode === "create"+ ? "Keep this reference to use again on Clone and Speak. Its first 30 seconds are saved."+ : "Change how this voice is listed and what its clip says."}+ </DialogDescription>+ </DialogHeader>+ <Field label="Name" htmlFor="save-voice-name">+ <Input+ id="save-voice-name"+ value={name}+ maxLength={80}+ // biome-ignore lint/a11y/noAutofocus: the dialog opens to name the voice.+ autoFocus={true}+ onFocus={(event) => event.currentTarget.select()}+ onChange={(event) => setName(event.target.value)}+ placeholder="Narrator"+ />+ </Field>+ <Field+ label="What's said in the clip"+ htmlFor="save-voice-transcript"+ hint="Optional. Saves transcribing the clip again next time."+ >+ <Textarea+ id="save-voice-transcript"+ value={transcript}+ maxLength={4000}+ onChange={(event) => setTranscript(event.target.value)}+ className="min-h-20"+ />+ </Field>+ <LanguageSelect+ id="save-voice-language"+ label="Language"+ value={language}+ onChange={setLanguage}+ emptyLabel="Not set"+ />+ {taken ? (+ <p className="text-ui-11p5 leading-snug text-muted-foreground">+ You already have a voice named {clean}. Pick another name.+ </p>+ ) : null}+ {error ? (+ <p role="alert" className="text-ui-11p5 leading-snug text-destructive">+ {error}+ </p>+ ) : null}+ <DialogFooter className="flex-wrap gap-2 sm:justify-end">+ <Button type="button" variant="ghost" onClick={onCancel}>+ Cancel+ </Button>+ <Button type="submit" disabled={!clean || taken || saving}>+ {saving ? "Saving…" : mode === "create" ? "Save voice" : "Save"}+ </Button>+ </DialogFooter>+ </form>+ );+}diff --git a/studio/frontend/src/features/audio/components/voice-picker.tsx b/studio/frontend/src/features/audio/components/voice-picker.tsxnew file mode 100644index 00000000000..03f31d845f6--- /dev/null+++ b/studio/frontend/src/features/audio/components/voice-picker.tsx@@ -0,0 +1,275 @@+// 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 {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { toast } from "@/lib/toast";+import { cn } from "@/lib/utils";+import {+ Delete02Icon,+ MoreHorizontalIcon,+ PauseIcon,+ PencilEdit02Icon,+ PlayIcon,+ Tick02Icon,+} from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import { BlobUrlCache } from "@/lib/blob-url-cache";+import { useEffect, useRef, useState } from "react";+import { type AudioVoice, fetchAudioBlob } from "../api";+import { useAudioVoicesStore } from "../stores/audio-voices-store";+import { SaveVoiceDialog } from "./save-voice-dialog";+import { formatSeconds } from "./waveform-peaks";++// About 20 saved voices (30 s of 24 kHz mono each); older previews re-fetch.+const voiceUrls = new BlobUrlCache(32 * 1024 * 1024);++export function VoicePicker({+ selectedId,+ onSelect,+ onDeselect,+ disabled,+ className,+}: {+ selectedId?: string | null;+ onSelect?: (voice: AudioVoice) => void;+ onDeselect?: () => void;+ disabled?: boolean;+ className?: string;+}) {+ const voices = useAudioVoicesStore((state) => state.voices);+ const loaded = useAudioVoicesStore((state) => state.loaded);+ const loading = useAudioVoicesStore((state) => state.loading);+ const error = useAudioVoicesStore((state) => state.error);+ const refresh = useAudioVoicesStore((state) => state.refresh);+ const rename = useAudioVoicesStore((state) => state.rename);+ const remove = useAudioVoicesStore((state) => state.remove);+ const audioRef = useRef<HTMLAudioElement | null>(null);+ const previewRequest = useRef(0);+ const [playingId, setPlayingId] = useState<string | null>(null);+ const [editing, setEditing] = useState<AudioVoice | null>(null);++ useEffect(() => {+ if (!(loaded || loading)) void refresh();+ }, [loaded, loading, refresh]);++ useEffect(+ () => () => {+ audioRef.current?.pause();+ },+ [],+ );++ const togglePlay = async (voice: AudioVoice) => {+ const audio = audioRef.current;+ if (!audio) return;+ if (playingId === voice.id) {+ audio.pause();+ setPlayingId(null);+ return;+ }+ const request = ++previewRequest.current;+ try {+ let url = voiceUrls.get(voice.id);+ if (url) {+ voiceUrls.touch(voice.id);+ } else {+ const blob = await fetchAudioBlob(voice.url);+ url = URL.createObjectURL(blob);+ voiceUrls.set(voice.id, url, blob.size);+ voiceUrls.prune([voice.id]);+ }+ // A later preview click wins over this one's slower fetch.+ if (request !== previewRequest.current) return;+ audio.src = url;+ await audio.play();+ setPlayingId(voice.id);+ } catch {+ if (request !== previewRequest.current) return;+ setPlayingId(null);+ toast.error(`Could not play ${voice.name}.`);+ }+ };++ const handleDelete = async (voice: AudioVoice) => {+ if (playingId === voice.id) {+ audioRef.current?.pause();+ setPlayingId(null);+ }+ try {+ await remove(voice.id);+ voiceUrls.delete(voice.id);+ if (voice.id === selectedId) onDeselect?.();+ toast.success(`Deleted ${voice.name}.`);+ } catch (reason) {+ toast.error(+ reason instanceof Error+ ? reason.message+ : "Could not delete the voice.",+ );+ }+ };++ return (+ <div className={cn("grid gap-1", className)}>+ {/* biome-ignore lint/a11y/useMediaCaption: short voice samples with their names listed beside them. */}+ <audio+ ref={audioRef}+ className="hidden"+ onEnded={() => setPlayingId(null)}+ onPause={() => setPlayingId(null)}+ />+ {voices.length === 0 ? (+ <p className="px-1 py-2 text-ui-12 leading-snug text-muted-foreground">+ {error ? (+ <>+ {error}{" "}+ <Button+ type="button"+ variant="link"+ className="h-auto p-0 text-ui-12 font-medium text-foreground"+ onClick={() => void refresh()}+ >+ Try again+ </Button>+ </>+ ) : loading || !loaded ? (+ "Loading saved voices…"+ ) : (+ "No saved voices yet. Add a reference on Clone, then press Save voice."+ )}+ </p>+ ) : (+ <ul className="hover-scrollbar grid min-w-0 max-h-[calc(196px*var(--ui-space-scale,1))] grid-cols-[minmax(0,1fr)] gap-0.5 overflow-y-auto">+ {voices.map((voice) => {+ const selected = voice.id === selectedId;+ const playing = voice.id === playingId;+ return (+ <li+ key={voice.id}+ className={cn(+ "group flex min-w-0 items-center gap-1 rounded-full pr-1 transition-colors hover:bg-accent",+ selected && "bg-muted",+ )}+ >+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className="size-[calc(28px*var(--ui-space-scale,1))] shrink-0"+ aria-label={+ playing ? `Pause ${voice.name}` : `Play ${voice.name}`+ }+ onClick={() => void togglePlay(voice)}+ >+ <HugeiconsIcon+ icon={playing ? PauseIcon : PlayIcon}+ className="size-3.5"+ />+ </Button>+ <button+ type="button"+ disabled={disabled || !onSelect}+ aria-pressed={onSelect ? selected : undefined}+ className="flex min-w-0 flex-1 items-center gap-2 rounded-full py-1.5 text-left text-ui-13 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-default"+ onClick={() => onSelect?.(voice)}+ onKeyDown={(event) => {+ // Space plays, as on every clip; Enter picks.+ if (event.key === " ") {+ event.preventDefault();+ void togglePlay(voice);+ }+ }}+ onKeyUp={(event) => {+ if (event.key === " ") event.preventDefault();+ }}+ >+ <span className="min-w-0 flex-1 truncate">{voice.name}</span>+ {voice.language ? (+ <span className="shrink-0 text-ui-11p5 text-muted-foreground">+ {voice.language}+ </span>+ ) : null}+ <span className="shrink-0 font-mono text-ui-11p5 tabular-nums text-muted-foreground">+ {formatSeconds(voice.duration_s)}+ </span>+ {selected ? (+ <HugeiconsIcon+ icon={Tick02Icon}+ className="size-3.5 shrink-0 text-foreground"+ aria-label="Selected"+ />+ ) : null}+ </button>+ <DropdownMenu>+ <DropdownMenuTrigger asChild={true}>+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className="size-[calc(28px*var(--ui-space-scale,1))] shrink-0"+ aria-label={`More for ${voice.name}`}+ disabled={disabled}+ >+ <HugeiconsIcon+ icon={MoreHorizontalIcon}+ className="size-3.5"+ />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={() => setEditing(voice)}>+ <HugeiconsIcon+ icon={PencilEdit02Icon}+ strokeWidth={1.75}+ className="size-icon"+ />+ Rename…+ </DropdownMenuItem>+ <DropdownMenuItem+ variant="destructive"+ onClick={() => void handleDelete(voice)}+ >+ <HugeiconsIcon+ icon={Delete02Icon}+ strokeWidth={1.75}+ className="size-icon"+ />+ Delete+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </li>+ );+ })}+ </ul>+ )}+ <SaveVoiceDialog+ open={editing !== null}+ onOpenChange={(open) => {+ if (!open) setEditing(null);+ }}+ mode="edit"+ voiceId={editing?.id}+ initial={{+ name: editing?.name ?? "",+ transcript: editing?.transcript ?? "",+ language: editing?.language ?? "",+ }}+ onSubmit={async (details) => {+ if (!editing) return;+ await rename(editing.id, {+ name: details.name,+ transcript: details.transcript || null,+ language: details.language || null,+ });+ }}+ />+ </div>+ );+}diff --git a/studio/frontend/src/features/audio/hooks/audio-source-state.ts b/studio/frontend/src/features/audio/hooks/audio-source-state.tsnew file mode 100644index 00000000000..347d2f4a019--- /dev/null+++ b/studio/frontend/src/features/audio/hooks/audio-source-state.ts@@ -0,0 +1,163 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Free of app imports so the node test runner can load it directly.++import { AUDIO_INPUT_MAX_BYTES } from "../audio-run-request";++export type AudioSourceStatus =+ | { phase: "idle" }+ | { phase: "recording"; startedAt: number }+ | { phase: "uploading"; name: string; progress: number | null }+ | { phase: "loading" }+ | { phase: "ready" }+ | { phase: "error"; message: string }+ | { phase: "expired" };++interface AudioSourcePreview {+ /** Selection key drawn, or "local:<n>" for a file still uploading. */+ key: string | null;+ /** The local key of the upload that just got an id, so its late decode still lands. */+ localKey?: string | null;+ peaks: number[] | null;+ durationS: number | null;+ url: string | null;+}++interface AudioSourceState {+ status: AudioSourceStatus;+ preview: AudioSourcePreview;+}++type AudioSourceAction =+ | { type: "record-start"; now: number }+ | { type: "record-stop" }+ | { type: "upload-start"; name: string; key: string }+ | { type: "upload-progress"; progress: number | null }+ | { type: "upload-done"; key: string }+ | { type: "load-start"; key: string }+ | { type: "load-done" }+ | {+ type: "preview";+ key: string;+ peaks: number[] | null;+ durationS: number | null;+ url: string | null;+ }+ | { type: "fail"; message: string }+ | { type: "expire" }+ | { type: "reset" };++const EMPTY_PREVIEW: AudioSourcePreview = {+ key: null,+ peaks: null,+ durationS: null,+ url: null,+};++export const INITIAL_AUDIO_SOURCE_STATE: AudioSourceState = {+ status: { phase: "idle" },+ preview: EMPTY_PREVIEW,+};++export const REFERENCE_EXPIRED_MESSAGE =+ "This reference expired. Add it again.";++export function audioSourceReducer(+ state: AudioSourceState,+ action: AudioSourceAction,+): AudioSourceState {+ switch (action.type) {+ case "record-start":+ return {+ ...state,+ status: { phase: "recording", startedAt: action.now },+ };+ case "record-stop":+ return state.status.phase === "recording"+ ? { ...state, status: { phase: "idle" } }+ : state;+ case "upload-start":+ return {+ status: { phase: "uploading", name: action.name, progress: 0 },+ preview: { ...EMPTY_PREVIEW, key: action.key },+ };+ case "upload-progress":+ if (state.status.phase !== "uploading") return state;+ return {+ ...state,+ status: {+ ...state.status,+ progress:+ action.progress === null+ ? null+ : Math.min(1, Math.max(0, action.progress)),+ },+ };+ case "upload-done":+ return {+ status: { phase: "ready" },+ preview: {+ ...state.preview,+ key: action.key,+ localKey: state.preview.key?.startsWith("local:")+ ? state.preview.key+ : null,+ },+ };+ case "load-start":+ return {+ status: { phase: "loading" },+ preview: { ...EMPTY_PREVIEW, key: action.key },+ };+ case "load-done":+ return state.status.phase === "loading"+ ? { ...state, status: { phase: "ready" } }+ : state;+ case "preview":+ if (+ state.preview.key !== action.key &&+ state.preview.localKey !== action.key+ )+ return state;+ return {+ ...state,+ preview: {+ ...state.preview,+ peaks: action.peaks,+ durationS: action.durationS ?? state.preview.durationS,+ url: action.url ?? state.preview.url,+ },+ };+ case "fail":+ return { ...state, status: { phase: "error", message: action.message } };+ case "expire":+ return { status: { phase: "expired" }, preview: EMPTY_PREVIEW };+ case "reset":+ return INITIAL_AUDIO_SOURCE_STATE;+ default:+ return state;+ }+}++export function audioFileProblem(file: {+ size: number;+ type?: string;+ name?: string;+}): string | null {+ if (file.size <= 0) return "This file is empty.";+ if (file.size > AUDIO_INPUT_MAX_BYTES)+ return "Audio is too large. Keep it under 200 MB.";+ const type = file.type ?? "";+ const name = (file.name ?? "").toLowerCase();+ if (+ type &&+ !type.startsWith("audio/") &&+ !type.startsWith("video/") &&+ type !== "application/octet-stream" &&+ !/\.(wav|mp3|flac|ogg|oga|opus|m4a|aac|webm|mp4)$/.test(name)+ ) {+ return "This is not an audio file. Pick a WAV, MP3, FLAC, OGG or M4A file.";+ }+ return null;+}diff --git a/studio/frontend/src/features/audio/hooks/use-audio-gallery.tsx b/studio/frontend/src/features/audio/hooks/use-audio-gallery.tsxindex 436a9a17886..07247b7e01b 100644--- a/studio/frontend/src/features/audio/hooks/use-audio-gallery.tsx+++ b/studio/frontend/src/features/audio/hooks/use-audio-gallery.tsx@@ -64,7 +64,7 @@ export function useAudioGallery({prompt: string;model: string;saved: boolean;- workflow: "speak" | "music";+ workflow: "speak" | "music" | "clone";} | null>(null);const fallbackClipRef = useRef(fallbackClip);fallbackClipRef.current = fallbackClip;@@ -425,7 +425,7 @@ export function useAudioGallery({[refreshGallery],);- const handleClearGallery = useCallback(async (workflow?: "speak" | "music") => {+ const handleClearGallery = useCallback(async (workflow?: "speak" | "clone" | "music") => {try {await clearAudioGallery(workflow);if (workflow) {@@ -554,7 +554,7 @@ export function useWorkflowHistory({loadMore,loadingMoreRef,selectClip,-}: { workflow: "speak" | "music"; enabled: boolean } & Pick<+}: { workflow: "speak" | "clone" | "music"; enabled: boolean } & Pick<AudioGallery,| "clips"| "hasMore"diff --git a/studio/frontend/src/features/audio/hooks/use-audio-model-slot.ts b/studio/frontend/src/features/audio/hooks/use-audio-model-slot.tsindex 23ce76a266a..78a790f695f 100644--- a/studio/frontend/src/features/audio/hooks/use-audio-model-slot.ts+++ b/studio/frontend/src/features/audio/hooks/use-audio-model-slot.ts@@ -63,7 +63,11 @@ import {usesNativeAudioRuntime,} from "../catalog";import { useAudioWorkspaceStore } from "../stores/audio-workspace-store";-import { type AudioWorkflowId, slotForWorkflow } from "../workflows";+import {+ type AudioWorkflowId,+ slotForWorkflow,+ workflowForLoadedModel,+} from "../workflows";import type { AudioHostState } from "./audio-host-state";import type { SttSidecar } from "./use-stt-sidecar";import type { Transcription } from "./use-transcription";@@ -311,12 +315,14 @@ export function useAudioModelSlot({duration: offloadNotice ? 8000 : undefined,},);- const loadedWorkflow = isMusicGenerationModel(repoId, res.audio_type)- ? "music"- : "speak";- if (modeRef.current === "speak") {- useAudioWorkspaceStore.getState().commitWorkflow(loadedWorkflow);- }+ const loadedWorkflow = workflowForLoadedModel({+ current: useAudioWorkspaceStore.getState().workflow,+ audioWorkflows: res.audio_workflows,+ music: isMusicGenerationModel(repoId, res.audio_type),+ });+ const workspace = useAudioWorkspaceStore.getState();+ workspace.rememberModel(loadedWorkflow, repoId);+ if (modeRef.current === "speak") workspace.commitWorkflow(loadedWorkflow);if (wantsCpu &&!isGgufLoad &&@@ -1037,12 +1043,44 @@ export function useAudioModelSlot({};}, [active, isMac]);+ const pickRecommendedModel = useCallback(+ async (id: string) => {+ if (busyRef.current !== null) return;+ try {+ const listing = await listGgufVariants(id, hfApiToken(getHfToken()));+ const variant = selectAutoGgufVariant(+ listing.variants,+ listing.default_variant,+ );+ if (!variant) {+ toast.error(`${id} does not publish a runnable GGUF file.`);+ return;+ }+ await handleModelSelect(id, {+ source: "hub",+ isLora: false,+ isGguf: true,+ ggufFilename: variant.filename,+ ggufVariant: variant.quant,+ isDownloaded: variant.downloaded === true && !variant.partial,+ expectedBytes: expectedGgufDownloadBytes(variant),+ });+ } catch (error) {+ toast.error(+ error instanceof Error ? error.message : `Could not inspect ${id}.`,+ );+ }+ },+ [busyRef, handleModelSelect],+ );+return {replayQueuedTtsPick,transitionMode,transitionWorkflow,pendingTranscribeRelease,handleModelSelect,+ pickRecommendedModel,handleEject,trainedTtsModels,};diff --git a/studio/frontend/src/features/audio/hooks/use-audio-source.ts b/studio/frontend/src/features/audio/hooks/use-audio-source.tsnew file mode 100644index 00000000000..4f88067ab14--- /dev/null+++ b/studio/frontend/src/features/audio/hooks/use-audio-source.ts@@ -0,0 +1,382 @@+// 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 {+ type SegmentRecorder,+ createAudioRecorder,+} from "@/features/chat/adapters/pcm-recorder";+import { useCallback, useEffect, useReducer, useRef, useState } from "react";+import { AudioApiError, fetchAudioBlob, uploadAudioInput } from "../api";+import {+ type AudioSourceSelection,+ selectionExpired,+ sourceFileUrl,+} from "../audio-run-request";+import { decodePeaks } from "../components/waveform-decode";+import {+ INITIAL_AUDIO_SOURCE_STATE,+ audioFileProblem,+ audioSourceReducer,+} from "./audio-source-state";++// A reference only needs seconds; a long take is still usable, the server keeps the first 30 s.+const DEFAULT_RECORD_MAX_SECONDS = 5 * 60;+const RECORDING_CHUNK_MS = 1000;++// Some containers decode in a media element but not in Web Audio, so the length falls back to one.+async function readSource(+ blob: Blob,+): Promise<{ peaks: number[] | null; durationS: number | null }> {+ const decoded = await decodePeaks(blob);+ return decoded.durationS === null+ ? { peaks: null, durationS: await mediaDuration(blob) }+ : decoded;+}++function mediaDuration(blob: Blob): Promise<number | null> {+ return new Promise((resolve) => {+ const url = URL.createObjectURL(blob);+ const audio = new Audio();+ const done = (value: number | null) => {+ URL.revokeObjectURL(url);+ resolve(value);+ };+ audio.preload = "metadata";+ audio.onloadedmetadata = () =>+ done(Number.isFinite(audio.duration) ? audio.duration : null);+ audio.onerror = () => done(null);+ audio.src = url;+ });+}++function errorText(error: unknown, fallback: string): string {+ return error instanceof Error && error.message ? error.message : fallback;+}++export function recordingSupported(): boolean {+ return (+ typeof navigator !== "undefined" &&+ typeof navigator.mediaDevices?.getUserMedia === "function"+ );+}++export function useAudioSource({+ value,+ onChange,+ maxRecordSeconds = DEFAULT_RECORD_MAX_SECONDS,+ active = true,+}: {+ value: AudioSourceSelection | null;+ onChange: (next: AudioSourceSelection | null) => void;+ maxRecordSeconds?: number;+ active?: boolean;+}) {+ const [state, dispatch] = useReducer(+ audioSourceReducer,+ INITIAL_AUDIO_SOURCE_STATE,+ );+ const [elapsed, setElapsed] = useState(0);+ const onChangeRef = useRef(onChange);+ onChangeRef.current = onChange;+ const uploadAbort = useRef<AbortController | null>(null);+ const loadAbort = useRef<AbortController | null>(null);+ const recorderRef = useRef<SegmentRecorder | null>(null);+ const streamRef = useRef<MediaStream | null>(null);+ const discardRecording = useRef(false);+ const activeRef = useRef(active);+ const pickCount = useRef(0);+ const acquiring = useRef(false);+ const acquisition = useRef(0);+ const objectUrl = useRef<string | null>(null);+ const setObjectUrl = useCallback((blob: Blob | null) => {+ if (objectUrl.current) URL.revokeObjectURL(objectUrl.current);+ objectUrl.current = blob ? URL.createObjectURL(blob) : null;+ return objectUrl.current;+ }, []);++ const drawBlob = useCallback(+ async (key: string, blob: Blob) => {+ const url = setObjectUrl(blob);+ dispatch({ type: "preview", key, peaks: null, durationS: null, url });+ const { peaks, durationS } = await readSource(blob);+ dispatch({ type: "preview", key, peaks, durationS, url });+ },+ [setObjectUrl],+ );++ const valueKey = value ? `${value.kind}:${value.id}` : null;+ const previewKey = state.preview.key;+ const phase = state.status.phase;+ // A new pick replaces an error or expiry about an earlier one (a failed upload, then a history clip).+ const seenKey = useRef(valueKey);+ useEffect(() => {+ if (seenKey.current === valueKey) return;+ seenKey.current = valueKey;+ if (valueKey && (phase === "error" || phase === "expired")) {+ dispatch({ type: "reset" });+ }+ }, [valueKey, phase]);+ useEffect(() => {+ if (!(value && valueKey)) return;+ if (+ previewKey === valueKey ||+ phase === "uploading" ||+ phase === "recording" ||+ phase === "expired" ||+ phase === "error"+ )+ return;+ if (selectionExpired(value, Date.now())) {+ dispatch({ type: "expire" });+ return;+ }+ loadAbort.current?.abort();+ const controller = new AbortController();+ loadAbort.current = controller;+ // Not aborted by this effect's cleanup: load-start changes its deps. A new selection or+ // unmount aborts it instead.+ dispatch({ type: "load-start", key: valueKey });+ fetchAudioBlob(sourceFileUrl(value), controller.signal)+ .then(async (blob) => {+ if (controller.signal.aborted) return;+ dispatch({ type: "load-done" });+ await drawBlob(valueKey, blob);+ })+ .catch((error: unknown) => {+ if (controller.signal.aborted) return;+ if (error instanceof AudioApiError && error.status === 404) {+ if (value.kind === "input") {+ dispatch({ type: "expire" });+ } else {+ dispatch({+ type: "fail",+ message:+ value.kind === "voice"+ ? "This saved voice was deleted. Pick another one."+ : "This clip was deleted. Pick another one.",+ });+ }+ return;+ }+ // The audio could not be drawn, but the server still has it; the run can go ahead.+ dispatch({ type: "load-done" });+ });+ }, [value, valueKey, previewKey, phase, drawBlob]);+ useEffect(() => () => loadAbort.current?.abort(), [valueKey]);++ useEffect(() => {+ if (+ value ||+ phase === "recording" ||+ phase === "error" ||+ phase === "uploading"+ )+ return;+ if (phase !== "idle" || previewKey !== null) {+ setObjectUrl(null);+ dispatch({ type: "reset" });+ }+ }, [value, phase, previewKey, setObjectUrl]);++ const pickFile = useCallback(+ async (file: File | Blob, name?: string) => {+ const fileName =+ name ?? ("name" in file && file.name ? file.name : "Recording");+ const problem = audioFileProblem({+ size: file.size,+ type: file.type,+ name: fileName,+ });+ if (problem) {+ dispatch({ type: "fail", message: problem });+ return;+ }+ uploadAbort.current?.abort();+ loadAbort.current?.abort();+ const controller = new AbortController();+ uploadAbort.current = controller;+ // Each pick draws under its own key, so a slow decode of an earlier file cannot land on this one.+ const localKey = `local:${++pickCount.current}`;+ dispatch({ type: "upload-start", name: fileName, key: localKey });+ void drawBlob(localKey, file);+ try {+ const record = await uploadAudioInput(file, fileName, {+ signal: controller.signal,+ onProgress: (progress) =>+ dispatch({ type: "upload-progress", progress }),+ });+ if (controller.signal.aborted) return;+ dispatch({ type: "upload-done", key: `input:${record.id}` });+ onChangeRef.current({+ kind: "input",+ id: record.id,+ name: record.name || fileName,+ durationS: record.duration_s,+ expiresAt: record.expires_at,+ transcript: null,+ language: null,+ });+ } catch (error) {+ if (controller.signal.aborted) return;+ dispatch({+ type: "fail",+ message: errorText(error, "The upload failed. Try another file."),+ });+ } finally {+ if (uploadAbort.current === controller) uploadAbort.current = null;+ }+ },+ [drawBlob],+ );++ const stopStream = useCallback(() => {+ for (const track of streamRef.current?.getTracks() ?? []) track.stop();+ streamRef.current = null;+ }, []);++ const startRecording = useCallback(async () => {+ if (recorderRef.current || acquiring.current) return;+ acquiring.current = true;+ const ticket = ++acquisition.current;+ let stream: MediaStream;+ try {+ stream = await navigator.mediaDevices.getUserMedia({+ audio: { echoCancellation: true, noiseSuppression: true },+ });+ } catch {+ acquiring.current = false;+ if (ticket !== acquisition.current) return;+ dispatch({+ type: "fail",+ message:+ "Could not use the microphone. Allow access, or upload a file instead.",+ });+ return;+ }+ acquiring.current = false;+ // Cleared, unmounted or hidden while the permission prompt was open: release the mic at once.+ if (ticket !== acquisition.current || !activeRef.current) {+ for (const track of stream.getTracks()) track.stop();+ return;+ }+ streamRef.current = stream;+ let recorder: SegmentRecorder;+ try {+ recorder = createAudioRecorder(stream);+ } catch {+ stopStream();+ dispatch({+ type: "fail",+ message:+ "This browser cannot record audio here. Upload a file instead.",+ });+ return;+ }+ const chunks: Blob[] = [];+ const limit = window.setTimeout(() => {+ if (recorder.state !== "inactive") recorder.stop();+ }, maxRecordSeconds * 1000);+ recorder.addEventListener("dataavailable", (event) => {+ if (event.data.size > 0) chunks.push(event.data);+ });+ recorder.addEventListener("stop", () => {+ window.clearTimeout(limit);+ recorderRef.current = null;+ stopStream();+ dispatch({ type: "record-stop" });+ if (discardRecording.current) {+ discardRecording.current = false;+ return;+ }+ const type = recorder.mimeType || "audio/webm";+ const blob = new Blob(chunks, { type });+ const extension = type.includes("wav")+ ? "wav"+ : type.includes("mp4")+ ? "m4a"+ : type.includes("ogg")+ ? "ogg"+ : "webm";+ if (blob.size > 0) void pickFile(blob, `Recording.${extension}`);+ });+ recorderRef.current = recorder;+ discardRecording.current = false;+ recorder.start(RECORDING_CHUNK_MS);+ dispatch({ type: "record-start", now: Date.now() });+ }, [pickFile, stopStream, maxRecordSeconds]);++ const stopRecording = useCallback(() => {+ const recorder = recorderRef.current;+ if (recorder && recorder.state !== "inactive") recorder.stop();+ }, []);++ // Leaving the Audio page ends a recording; what was captured is kept.+ useEffect(() => {+ activeRef.current = active;+ if (!active) stopRecording();+ }, [active, stopRecording]);++ const recordingStartedAt =+ state.status.phase === "recording" ? state.status.startedAt : null;+ useEffect(() => {+ if (recordingStartedAt === null) {+ setElapsed(0);+ return;+ }+ const timer = window.setInterval(+ () => setElapsed(Math.floor((Date.now() - recordingStartedAt) / 1000)),+ 250,+ );+ return () => window.clearInterval(timer);+ }, [recordingStartedAt]);++ const abortAll = useCallback(() => {+ acquisition.current += 1;+ uploadAbort.current?.abort();+ loadAbort.current?.abort();+ if (recorderRef.current) {+ discardRecording.current = true;+ recorderRef.current.stop();+ }+ }, []);++ const dismissError = useCallback(() => {+ setObjectUrl(null);+ dispatch({ type: "reset" });+ }, [setObjectUrl]);++ const clear = useCallback(() => {+ abortAll();+ dismissError();+ onChangeRef.current(null);+ }, [abortAll, dismissError]);++ useEffect(+ () => () => {+ abortAll();+ for (const track of streamRef.current?.getTracks() ?? []) track.stop();+ if (objectUrl.current) URL.revokeObjectURL(objectUrl.current);+ },+ [abortAll],+ );++ const fail = useCallback(+ (message: string) => dispatch({ type: "fail", message }),+ [],+ );++ const expire = useCallback(() => dispatch({ type: "expire" }), []);++ return {+ status: state.status,+ preview: state.preview,+ elapsed,+ expire,+ pickFile,+ startRecording,+ stopRecording,+ clear,+ dismissError,+ fail,+ };+}diff --git a/studio/frontend/src/features/audio/hooks/use-clone-generation.ts b/studio/frontend/src/features/audio/hooks/use-clone-generation.tsnew file mode 100644index 00000000000..e8b81b0ea7d--- /dev/null+++ b/studio/frontend/src/features/audio/hooks/use-clone-generation.ts@@ -0,0 +1,450 @@+// 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 { toast } from "@/lib/toast";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import {+ AudioApiError,+ type AudioRunResponse,+ fetchAudioBlob,+ runAudio,+} from "../api";+import {+ type AudioOptionSpec,+ type AudioOptionValues,+ audioOptionLabel,+ audioOptionsForRequest,+ missingRequiredAudioOptions,+} from "../audio-options";+import { persistedClipForGeneration } from "../audio-page-policy";+import {+ type AudioSourceSelection,+ selectionExpired,+ sourceRefOf,+} from "../audio-run-request";+import { cloneBlocker, referenceTextField } from "../clone-policy";+import type { AudioSourceInputHandle } from "../components/audio-source-input";+import type { GenerateBlocker } from "../pages/tts-workspace";+import { useAudioCloneStore } from "../stores/audio-clone-store";+import { audioToolPanelsFor } from "../tools/registry";+import {+ audioModelContextFor,+ claimedOptionNames,+ collectToolRequest,+ toolValueKey,+} from "../tools/select";+import type { AudioHostState } from "./audio-host-state";+import type { AudioSourceStatus } from "./audio-source-state";+import { REFERENCE_EXPIRED_MESSAGE } from "./audio-source-state";+import type { AudioGallery } from "./use-audio-gallery";+import { galleryCache } from "./use-audio-gallery";+import type { AudioModelSlot } from "./use-audio-model-slot";+import { useReferenceTranscribe } from "./use-reference-transcribe";++export const CLONE_TEXT_FIELD_ID = "clone-text";+export const CLONE_REFERENCE_TEXT_FIELD_ID = "clone-reference-text";++export async function showRunResult({+ response,+ text,+ workflow,+ refreshGallery,+ selectClip,+ setFallbackClip,+ setSelectedId,+}: {+ response: AudioRunResponse;+ text: string;+ workflow: "speak" | "clone";+} & Pick<+ AudioGallery,+ "refreshGallery" | "selectClip" | "setFallbackClip" | "setSelectedId"+>): Promise<void> {+ const clip =+ response.clips.find((item) => item.role === "output") ?? response.clips[0];+ const refreshed = await refreshGallery();+ if (clip) {+ const listed = persistedClipForGeneration(clip.id, refreshed);+ if (listed) {+ setFallbackClip(null);+ selectClip(listed.id);+ return;+ }+ // Saved, but this refresh missed it: play the saved file until a later refresh lists it.+ try {+ const blob = await fetchAudioBlob(clip.url);+ setFallbackClip({+ url: URL.createObjectURL(blob),+ prompt: text,+ model: response.model,+ saved: true,+ workflow,+ });+ } catch {}+ selectClip(clip.id, true);+ return;+ }+ if (response.audio) {+ galleryCache.selectedId = null;+ setSelectedId(null);+ setFallbackClip({+ url: `data:audio/${response.audio.format || "wav"};base64,${response.audio.data}`,+ prompt: text,+ model: response.model,+ saved: false,+ workflow,+ });+ }+}++/** Mirrors useSpeechGeneration's flow so Stop, phases and errors behave the same. */+export function useCloneGeneration({+ status,+ busyRef,+ setBusy,+ updateGenerationPhase,+ generateAbort,+ setMode,+ setAdvancedOpen,+ refreshStatus,+ activeRef,+ modeRef,+ refreshGallery,+ selectClip,+ setFallbackClip,+ setSelectedId,+ pendingTranscribeRelease,+ replayQueuedTtsPick,+ audioOptionSpecs,+ audioOptionValues,+ sttRepo,+}: Pick<+ AudioHostState,+ | "status"+ | "busyRef"+ | "setBusy"+ | "updateGenerationPhase"+ | "generateAbort"+ | "setMode"+ | "setAdvancedOpen"+ | "refreshStatus"+ | "activeRef"+ | "modeRef"+> &+ Pick<+ AudioGallery,+ "refreshGallery" | "selectClip" | "setFallbackClip" | "setSelectedId"+ > &+ Pick<AudioModelSlot, "pendingTranscribeRelease" | "replayQueuedTtsPick"> & {+ audioOptionSpecs: AudioOptionSpec[];+ audioOptionValues: AudioOptionValues;+ sttRepo: string | null;+ }) {+ const reference = useAudioCloneStore((state) => state.reference);+ const referenceText = useAudioCloneStore((state) => state.referenceText);+ const text = useAudioCloneStore((state) => state.text);+ const language = useAudioCloneStore((state) => state.language);+ const storedToolValues = useAudioCloneStore((state) => state.toolValues);+ const model = status?.active_model ?? null;+ const [generationError, setGenerationError] = useState<string | null>(null);+ const [referenceStatus, setReferenceStatus] = useState<AudioSourceStatus>({+ phase: "idle",+ });+ const referenceHandle = useRef<AudioSourceInputHandle | null>(null);+ const [expiredReferenceId, setExpiredReferenceId] = useState<string | null>(+ null,+ );++ const referenceTranscriber = useReferenceTranscribe({+ sttRepo,+ onText: (next, source) =>+ useAudioCloneStore.getState().applyTranscript(source, next),+ });+ // Holds the page busy like the Transcribe page does, so Generate and model swaps wait for the STT run.+ const transcribeReference = useCallback(+ async (source: AudioSourceSelection | null) => {+ if (!source || busyRef.current) return;+ busyRef.current = "transcribing";+ setBusy("transcribing");+ try {+ await referenceTranscriber.transcribe(source);+ } finally {+ if (busyRef.current === "transcribing") {+ busyRef.current = null;+ setBusy(null);+ }+ }+ },+ [busyRef, setBusy, referenceTranscriber.transcribe],+ );+ const transcriber = {+ ...referenceTranscriber,+ transcribe: transcribeReference,+ };++ const toolContext = useMemo(+ () =>+ audioModelContextFor(status, {+ musicGeneration: false,+ cudaMusicGeneration: false,+ musicNeedsDescription: false,+ }),+ [status],+ );+ const toolPanels = useMemo(+ () => audioToolPanelsFor("clone", toolContext),+ [toolContext],+ );+ const toolValues = useMemo(() => {+ const values: Record<string, unknown> = {};+ for (const panel of toolPanels) {+ values[panel.id] =+ storedToolValues[toolValueKey(model, "clone", panel.id)];+ }+ return values;+ }, [toolPanels, storedToolValues, model]);+ const handleToolValueChange = useCallback(+ (panelId: string, value: unknown) =>+ useAudioCloneStore+ .getState()+ .setToolValue(toolValueKey(model, "clone", panelId), value),+ [model],+ );+ const toolRequest = useMemo(+ () =>+ collectToolRequest(+ toolPanels,+ toolValues,+ { text, referenceText, hasReference: reference !== null },+ toolContext,+ audioOptionSpecs,+ ),+ [+ toolPanels,+ toolValues,+ text,+ referenceText,+ reference,+ toolContext,+ audioOptionSpecs,+ ],+ );+ const claimedOptions = useMemo(+ () => claimedOptionNames(toolPanels),+ [toolPanels],+ );+ const advancedOptionSpecs = useMemo(+ () => audioOptionSpecs.filter((spec) => !claimedOptions.has(spec.name)),+ [audioOptionSpecs, claimedOptions],+ );+ const transcriptField = referenceTextField(toolContext, toolRequest.patch);++ const [now, setNow] = useState(() => Date.now());+ useEffect(() => {+ if (reference?.kind !== "input" || !reference.expiresAt) return;+ const timer = window.setInterval(() => setNow(Date.now()), 60_000);+ return () => window.clearInterval(timer);+ }, [reference]);+ const referenceExpired =+ referenceStatus.phase === "expired" ||+ selectionExpired(reference, now) ||+ (reference !== null && reference.id === expiredReferenceId);++ const inputBlocker = cloneBlocker({+ reference,+ referenceBusy:+ referenceStatus.phase === "uploading" ||+ referenceStatus.phase === "recording",+ referenceExpired,+ referenceError:+ referenceStatus.phase === "error" ? referenceStatus.message : null,+ referenceText,+ referenceTextField: transcriptField,+ text,+ panelError: toolRequest.error,+ });+ const focusField = (id: string) => () => document.getElementById(id)?.focus();+ const addReference = {+ label: "Add reference audio",+ onClick: () => referenceHandle.current?.focus(),+ };+ // Model blockers (none loaded, cannot clone) are the host's and come first.+ const blockerActions: Record<string, GenerateBlocker["actions"]> = {+ reference: [addReference],+ "reference-error": [addReference],+ "reference-expired": [+ {+ label: "Add it again",+ onClick: () => {+ // Like Remove: the expired clip's transcript goes with it.+ useAudioCloneStore.getState().adoptReference(null);+ referenceHandle.current?.browse();+ },+ },+ ],+ "reference-text": [+ {+ label: "Transcribe it",+ onClick: () => void transcriber.transcribe(reference),+ },+ { label: "type it", onClick: focusField(CLONE_REFERENCE_TEXT_FIELD_ID) },+ ],+ text: [{ label: "Write it", onClick: focusField(CLONE_TEXT_FIELD_ID) }],+ };+ const blocker: GenerateBlocker | null = inputBlocker+ ? {+ reason: inputBlocker.reason,+ actions: blockerActions[inputBlocker.kind],+ }+ : null;++ const handleGenerate = useCallback(async () => {+ const state = useAudioCloneStore.getState();+ const draftText = state.text.trim();+ if (!(draftText && state.reference) || inputBlocker) return;+ if (busyRef.current) return;+ busyRef.current = "generating";+ setBusy("generating");+ updateGenerationPhase("preparing");+ const finishEarly = () => {+ updateGenerationPhase(null);+ busyRef.current = null;+ setBusy(null);+ };+ const releaseInFlight = pendingTranscribeRelease.current;+ if (releaseInFlight && !(await releaseInFlight)) {+ finishEarly();+ setMode("transcribe");+ return;+ }+ const missingOptions = missingRequiredAudioOptions(+ advancedOptionSpecs,+ audioOptionValues,+ );+ if (missingOptions.length > 0) {+ finishEarly();+ setAdvancedOpen(true);+ toast.error(+ `Set ${missingOptions.map((spec) => audioOptionLabel(spec.name)).join(", ")} in Advanced before generating.`,+ );+ return;+ }+ const patch = toolRequest.patch;+ const controller = new AbortController();+ generateAbort.current = controller;+ updateGenerationPhase("generating");+ try {+ const response = await runAudio(+ {+ workflow: "clone",+ text: draftText,+ language: state.language || null,+ instructions: patch.instructions ?? null,+ inputs: {+ reference: sourceRefOf(state.reference),+ reference_text:+ transcriptField === "hidden" ? null : state.referenceText,+ emotion: patch.inputs?.emotion ?? null,+ },+ options: {+ ...audioOptionsForRequest(advancedOptionSpecs, audioOptionValues),+ ...patch.options,+ },+ speed: patch.speed ?? null,+ },+ controller.signal,+ );+ updateGenerationPhase("finishing");+ await showRunResult({+ response,+ text: draftText,+ workflow: "clone",+ refreshGallery,+ selectClip,+ setFallbackClip,+ setSelectedId,+ });+ } catch (error) {+ if (!controller.signal.aborted) {+ updateGenerationPhase("finishing");+ const expired =+ error instanceof AudioApiError &&+ error.status === 404 &&+ state.reference.kind === "input" &&+ // With an emotion clip too, the 404 may be that clip's: keep the server's message.+ !patch.inputs?.emotion;+ if (expired) {+ setExpiredReferenceId(state.reference.id);+ referenceHandle.current?.markExpired();+ }+ const message = expired+ ? REFERENCE_EXPIRED_MESSAGE+ : error instanceof Error+ ? error.message+ : "Voice cloning failed.";+ // Kept under Generate so the reason outlives the toast; expiry is already on the card.+ setGenerationError(message);+ if (!expired) toast.error(message);+ await refreshStatus();+ }+ } finally {+ generateAbort.current = null;+ updateGenerationPhase(null);+ busyRef.current = null;+ setBusy(null);+ if (activeRef.current && modeRef.current === "speak")+ replayQueuedTtsPick();+ }+ }, [+ inputBlocker,+ busyRef,+ setBusy,+ updateGenerationPhase,+ pendingTranscribeRelease,+ setMode,+ advancedOptionSpecs,+ audioOptionValues,+ setAdvancedOpen,+ toolRequest,+ generateAbort,+ transcriptField,+ refreshGallery,+ selectClip,+ setFallbackClip,+ setSelectedId,+ refreshStatus,+ activeRef,+ modeRef,+ replayQueuedTtsPick,+ ]);++ useEffect(() => {+ if (reference) setGenerationError(null);+ }, [reference]);++ return {+ reference,+ referenceText,+ text,+ language,+ referenceHandle,+ referenceStatus,+ setReferenceStatus,+ referenceExpired,+ transcriptField,+ transcriber,+ toolContext,+ toolPanels,+ toolValues,+ handleToolValueChange,+ claimedOptions,+ advancedOptionSpecs,+ blocker,+ inputsReady: inputBlocker === null,+ handleGenerate,+ generationError,+ setGenerationError,+ };+}++export type CloneGeneration = ReturnType<typeof useCloneGeneration>;diff --git a/studio/frontend/src/features/audio/hooks/use-reference-transcribe.ts b/studio/frontend/src/features/audio/hooks/use-reference-transcribe.tsnew file mode 100644index 00000000000..8c212d0ab3a--- /dev/null+++ b/studio/frontend/src/features/audio/hooks/use-reference-transcribe.ts@@ -0,0 +1,72 @@+// 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 { sttEngineFor } from "@/features/chat/adapters/studio-model-dictation-adapter";+import { useVoiceSettingsStore } from "@/features/settings";+import { useCallback, useEffect, useRef, useState } from "react";+import { transcribeAudioInput } from "../api";+import { type AudioSourceSelection, sourceRefOf } from "../audio-run-request";+import { sttEngineForRepoId, sttSidecarKeyFor } from "../catalog";++/** Fills "What's said in the clip" without adding it to the transcript list. No language hint:+ * the page's language is the output's, and a cross-lingual reference is not in it. */+export function useReferenceTranscribe({+ sttRepo,+ onText,+}: {+ sttRepo: string | null;+ onText: (text: string, reference: AudioSourceSelection) => void;+}) {+ const [transcribing, setTranscribing] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const abort = useRef<AbortController | null>(null);+ const onTextRef = useRef(onText);+ onTextRef.current = onText;++ const transcribe = useCallback(+ async (reference: AudioSourceSelection | null) => {+ if (!reference || abort.current) return;+ const controller = new AbortController();+ abort.current = controller;+ setTranscribing(true);+ setError(null);+ try {+ const voice = useVoiceSettingsStore.getState();+ const model = sttRepo ? sttSidecarKeyFor(sttRepo) : voice.sttModel;+ const result = await transcribeAudioInput(+ sourceRefOf(reference),+ {+ model,+ engine: sttRepo ? sttEngineForRepoId(sttRepo) : sttEngineFor(model),+ device: voice.sttDevice,+ },+ controller.signal,+ );+ if (controller.signal.aborted) return;+ const text = result.text.trim();+ if (text) {+ onTextRef.current(text, reference);+ } else {+ setError(+ "No speech was heard in the clip. Type what's said instead.",+ );+ }+ } catch (reason) {+ if (controller.signal.aborted) return;+ setError(+ reason instanceof Error && reason.message+ ? reason.message+ : "Could not transcribe the clip.",+ );+ } finally {+ if (abort.current === controller) abort.current = null;+ setTranscribing(false);+ }+ },+ [sttRepo],+ );++ useEffect(() => () => abort.current?.abort(), []);++ return { transcribe, transcribing, error };+}diff --git a/studio/frontend/src/features/audio/hooks/use-speech-generation.ts b/studio/frontend/src/features/audio/hooks/use-speech-generation.tsindex 9bb6a0bb7eb..61914b217d1 100644--- a/studio/frontend/src/features/audio/hooks/use-speech-generation.ts+++ b/studio/frontend/src/features/audio/hooks/use-speech-generation.ts@@ -4,7 +4,7 @@import { useCallback, useEffect, useMemo, useState } from "react";import { readLastPrompt, saveLastPrompt } from "@/lib/last-prompt";import { toast } from "@/lib/toast";-import { generateAudio } from "../api";+import { generateAudio, runAudio } from "../api";import {audioOptionLabel,audioOptionsForRequest,@@ -38,7 +38,17 @@ import {import { TTS_MAX_TOKENS } from "../audio-workspace-constants";import type { AudioHostState } from "./audio-host-state";import { galleryCache } from "./use-audio-gallery";+import { useAudioCloneStore } from "../stores/audio-clone-store";+import { useAudioVoicesStore } from "../stores/audio-voices-store";import { useAudioWorkspaceStore } from "../stores/audio-workspace-store";+import { audioToolPanelsFor, isInstructionPanel } from "../tools/registry";+import {+ audioModelContextFor,+ claimedOptionNames,+ collectToolRequest,+ toolValueKey,+} from "../tools/select";+import { showRunResult } from "./use-clone-generation";import type { AudioWorkflowId } from "../workflows";import type { AudioGallery } from "./use-audio-gallery";import type { AudioModelSlot } from "./use-audio-model-slot";@@ -213,6 +223,81 @@ export function useSpeechGeneration({? "music": nativeAudioInstructionsKind(status?.audio_type);+ // Instruction panels edit the page's instruction draft; other panels keep a value per model.+ const voices = useAudioVoicesStore((state) => state.voices);+ const voicesLoaded = useAudioVoicesStore(+ (state) => state.loaded && !state.error,+ );+ const toolContext = useMemo(+ () => ({+ ...audioModelContextFor(status, {+ musicGeneration: workflow === "music",+ cudaMusicGeneration,+ musicNeedsDescription,+ }),+ savedVoiceIds: voicesLoaded ? voices.map((voice) => voice.id) : null,+ }),+ [status, workflow, cudaMusicGeneration, musicNeedsDescription, voices, voicesLoaded],+ );+ const toolPanels = useMemo(+ () => audioToolPanelsFor(workflow, toolContext),+ [workflow, toolContext],+ );+ const storedToolValues = useAudioCloneStore((state) => state.toolValues);+ const toolValues = useMemo(() => {+ const values: Record<string, unknown> = {};+ for (const panel of toolPanels) {+ values[panel.id] = isInstructionPanel(panel.id)+ ? { instructions: audioInstructions, language: audioLanguage }+ : storedToolValues[toolValueKey(audioOptionsModel, workflow, panel.id)];+ }+ return values;+ }, [+ toolPanels,+ audioInstructions,+ audioLanguage,+ storedToolValues,+ audioOptionsModel,+ workflow,+ ]);+ const handleToolValueChange = useCallback(+ (panelId: string, value: unknown) => {+ if (isInstructionPanel(panelId)) {+ const next = value as { instructions?: string; language?: string };+ if (typeof next.instructions === "string")+ setAudioInstructions(next.instructions);+ if (typeof next.language === "string") setAudioLanguage(next.language);+ return;+ }+ useAudioCloneStore+ .getState()+ .setToolValue(+ toolValueKey(audioOptionsModel, workflow, panelId),+ value,+ );+ },+ [setAudioInstructions, audioOptionsModel, workflow],+ );+ const toolRequest = useMemo(+ () =>+ collectToolRequest(+ toolPanels,+ toolValues,+ { text: prompt },+ toolContext,+ audioOptionSpecs,+ ),+ [toolPanels, toolValues, prompt, toolContext, audioOptionSpecs],+ );+ const claimedOptions = useMemo(+ () => claimedOptionNames(toolPanels),+ [toolPanels],+ );+ const advancedOptionSpecs = useMemo(+ () => audioOptionSpecs.filter((spec) => !claimedOptions.has(spec.name)),+ [audioOptionSpecs, claimedOptions],+ );+const handleGenerate = useCallback(async () => {const text = prompt.trim();if (!text && !lyricsOptional) return;@@ -234,11 +319,20 @@ export function useSpeechGeneration({updateGenerationPhase(null);busyRef.current = null;setBusy(null);- toast.error("Add a music description. This model needs one beside the lyrics.");+ toast.error(+ "Add a music description. This model needs one beside the lyrics.",+ );+ return;+ }+ if (toolRequest.error) {+ updateGenerationPhase(null);+ busyRef.current = null;+ setBusy(null);+ toast.error(toolRequest.error);return;}const missingOptions = missingRequiredAudioOptions(- audioOptionSpecs,+ advancedOptionSpecs,audioOptionValues,);if (missingOptions.length > 0) {@@ -251,12 +345,61 @@ export function useSpeechGeneration({);return;}- const requestOptions = audioOptionsForRequest(- audioOptionSpecs,- audioOptionValues,- );+ const requestOptions = {+ ...audioOptionsForRequest(advancedOptionSpecs, audioOptionValues),+ ...toolRequest.patch.options,+ };+ const savedVoice =+ workflow === "speak" ? toolRequest.patch.inputs?.reference : undefined;const language = audioLanguage.trim();saveLastPrompt(ttsDraftKey("prompt", workflow), prompt);+ if (savedVoice) {+ const voiceController = new AbortController();+ generateAbort.current = voiceController;+ updateGenerationPhase("generating");+ try {+ const response = await runAudio(+ {+ workflow: "speak",+ text,+ instructions:+ instructionsKind !== null && instructions ? instructions : null,+ language: mossLocalGeneration && language ? language : null,+ inputs: { reference: savedVoice },+ options: requestOptions,+ speed: toolRequest.patch.speed ?? null,+ },+ voiceController.signal,+ );+ updateGenerationPhase("finishing");+ await showRunResult({+ response,+ text,+ workflow: "speak",+ refreshGallery,+ selectClip,+ setFallbackClip,+ setSelectedId,+ });+ } catch (error) {+ if (!voiceController.signal.aborted) {+ updateGenerationPhase("finishing");+ const message =+ error instanceof Error ? error.message : "Audio generation failed.";+ setGenerationError(message);+ toast.error(message);+ await refreshStatus();+ }+ } finally {+ generateAbort.current = null;+ updateGenerationPhase(null);+ busyRef.current = null;+ setBusy(null);+ if (activeRef.current && modeRef.current === "speak")+ replayQueuedTtsPick();+ }+ return;+ }const controller = new AbortController();generateAbort.current = controller;updateGenerationPhase("generating");@@ -344,8 +487,9 @@ export function useSpeechGeneration({musicGeneration,musicNeedsDescription,lyricsOptional,- audioOptionSpecs,+ advancedOptionSpecs,audioOptionValues,+ toolRequest,setAdvancedOpen,mossLocalGeneration,mossFrameLimit,@@ -399,6 +543,13 @@ export function useSpeechGeneration({handleGenerate,generationError,setGenerationError,+ toolContext,+ toolPanels,+ toolValues,+ handleToolValueChange,+ toolBlocker: toolRequest.error,+ claimedOptions,+ advancedOptionSpecs,};}diff --git a/studio/frontend/src/features/audio/pages/clone-page.tsx b/studio/frontend/src/features/audio/pages/clone-page.tsxnew file mode 100644index 00000000000..502078fd612--- /dev/null+++ b/studio/frontend/src/features/audio/pages/clone-page.tsx@@ -0,0 +1,379 @@+// 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 { Textarea } from "@/components/ui/textarea";+import type { ModelOption } from "@/features/model-picker/components/model-selector/types";+import { toast } from "@/lib/toast";+import { FloppyDiskIcon, SpeechToTextIcon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import { type ComponentProps, useState } from "react";+import type { AudioGalleryClip } from "../api";+import { audioCppModelFor, audioCppWorkflowsFor } from "../audio-cpp-catalog";+import type { AudioSourceSelection } from "../audio-run-request";+import { macTtsCatalogChoiceIsRunnable } from "../catalog";+import { CLONE_TEXT_EXAMPLES } from "../clone-policy";+import {+ AudioHistoryProvider,+ AudioSourceInput,+} from "../components/audio-source-input";+import { LanguageSelect } from "../components/language-select";+import { SaveVoiceDialog } from "../components/save-voice-dialog";+import {+ CLONE_REFERENCE_TEXT_FIELD_ID,+ CLONE_TEXT_FIELD_ID,+ type CloneGeneration,+} from "../hooks/use-clone-generation";+import { useAudioCloneStore } from "../stores/audio-clone-store";+import { useAudioVoicesStore } from "../stores/audio-voices-store";+import { AudioToolPanels } from "../tools/tool-panel-host";+import { TtsFooter, TtsOutput, TtsRailFields } from "./tts-workspace";++const CLONE_MODEL_ORDER = [+ "Qwen3-TTS-12Hz-0.6B-Base-GGUF",+ "VoxCPM2-GGUF",+ "Chatterbox-GGUF",+];++function cloneRank(id: string): number {+ const index = CLONE_MODEL_ORDER.findIndex((name) => id.endsWith(`/${name}`));+ return index === -1 ? CLONE_MODEL_ORDER.length : index;+}++export function clonePageModels(+ models: ModelOption[],+ isMac: boolean,+): ModelOption[] {+ return models+ .filter((model) => {+ const entry = audioCppModelFor(model.id);+ return (+ entry !== null &&+ audioCppWorkflowsFor(entry).includes("clone") &&+ (!isMac || macTtsCatalogChoiceIsRunnable(model.id))+ );+ })+ .sort((a, b) => cloneRank(a.id) - cloneRank(b.id));+}++type RailProps = Omit<+ ComponentProps<typeof TtsRailFields>,+ | "musicGeneration"+ | "prompt"+ | "setPrompt"+ | "toolPanels"+ | "inputs"+ | "claimedOptions"+>;++export function adoptReference(next: AudioSourceSelection | null) {+ useAudioCloneStore.getState().adoptReference(next);+}++function CloneInputs({+ clone,+ historyClips,+ disabled,+}: {+ clone: CloneGeneration;+ historyClips: readonly AudioGalleryClip[];+ disabled: boolean;+}) {+ const setReferenceText = useAudioCloneStore(+ (state) => state.setReferenceText,+ );+ const setText = useAudioCloneStore((state) => state.setText);+ const setLanguage = useAudioCloneStore((state) => state.setLanguage);+ const { transcriber, transcriptField, reference } = clone;+ const referenceUsable =+ reference !== null &&+ !clone.referenceExpired &&+ clone.referenceStatus.phase !== "uploading";+ return (+ <AudioHistoryProvider value={historyClips}>+ <div data-tour="audio-clone-reference">+ <AudioSourceInput+ id="clone-reference"+ label="Reference"+ hint="5 to 15 s of one clear voice works best."+ value={reference}+ onChange={adoptReference}+ disabled={disabled}+ handleRef={clone.referenceHandle}+ onStatusChange={clone.setReferenceStatus}+ />+ </div>++ {transcriptField === "hidden" ? null : (+ <div className="grid gap-1.5" data-tour="audio-clone-transcript">+ <div className="flex items-center justify-between gap-2">+ <label+ htmlFor={CLONE_REFERENCE_TEXT_FIELD_ID}+ className="text-ui-13 font-medium text-foreground"+ >+ What's said in the clip+ <span className="ml-1.5 font-normal text-muted-foreground">+ {transcriptField === "required" ? "Required" : "Optional"}+ </span>+ </label>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="h-auto px-2 py-1 text-ui-11p5"+ disabled={+ !referenceUsable || transcriber.transcribing || disabled+ }+ onClick={() => void transcriber.transcribe(reference)}+ >+ <HugeiconsIcon icon={SpeechToTextIcon} className="size-3.5" />+ {transcriber.transcribing ? "Transcribing…" : "Transcribe"}+ </Button>+ </div>+ <Textarea+ id={CLONE_REFERENCE_TEXT_FIELD_ID}+ value={clone.referenceText}+ disabled={transcriber.transcribing}+ aria-busy={transcriber.transcribing}+ onChange={(event) => setReferenceText(event.target.value)}+ placeholder="Type the words in the clip exactly, or press Transcribe."+ className="min-h-16"+ />+ {transcriber.error ? (+ <p+ role="alert"+ className="text-ui-11p5 leading-snug text-destructive"+ >+ {transcriber.error}{" "}+ <Button+ type="button"+ variant="link"+ className="h-auto p-0 text-ui-11p5 font-medium text-foreground"+ onClick={() => void transcriber.transcribe(reference)}+ >+ Try again+ </Button>+ </p>+ ) : (+ <p className="text-ui-11p5 leading-snug text-muted-foreground">+ {transcriptField === "required"+ ? "This model matches the voice using the clip's words."+ : "Helps the model match the voice."}+ </p>+ )}+ </div>+ )}++ <div+ className="grid min-w-0 grid-cols-[minmax(0,1fr)] gap-1.5"+ data-tour="audio-clone-text"+ >+ <label+ htmlFor={CLONE_TEXT_FIELD_ID}+ className="text-ui-13 font-medium text-foreground"+ >+ Text to speak+ </label>+ <Textarea+ id={CLONE_TEXT_FIELD_ID}+ value={clone.text}+ onChange={(event) => setText(event.target.value)}+ placeholder="Type what the voice should say…"+ className="min-h-28"+ />+ {clone.text.trim() ? null : (+ <div+ className="flex flex-wrap gap-1.5"+ aria-label="Example sentences"+ >+ {CLONE_TEXT_EXAMPLES.map((example) => (+ <Button+ key={example}+ type="button"+ variant="outline"+ size="sm"+ className="h-auto max-w-full px-3 py-1 text-ui-11p5 font-normal"+ title={example}+ onClick={() => setText(example)}+ >+ <span className="truncate">{example}</span>+ </Button>+ ))}+ </div>+ )}+ </div>+ <LanguageSelect+ id="clone-language"+ label="Language"+ value={clone.language}+ onChange={setLanguage}+ hint="The language of the text to speak. Auto lets the model tell."+ />+ </AudioHistoryProvider>+ );+}++export function CloneRail({+ clone,+ historyClips,+ ...props+}: RailProps & {+ clone: CloneGeneration;+ historyClips: readonly AudioGalleryClip[];+}) {+ const disabled = props.busy === "generating";+ return (+ <TtsRailFields+ {...props}+ musicGeneration={false}+ prompt={clone.text}+ setPrompt={useAudioCloneStore.getState().setText}+ claimedOptions={clone.claimedOptions}+ inputs={+ <CloneInputs+ clone={clone}+ historyClips={historyClips}+ disabled={disabled}+ />+ }+ toolPanels={+ <AudioHistoryProvider value={historyClips}>+ <AudioToolPanels+ workflow="clone"+ ctx={clone.toolContext}+ values={clone.toolValues}+ onChange={clone.handleToolValueChange}+ specs={props.audioOptionSpecs}+ disabled={disabled}+ core={{+ text: clone.text,+ referenceText: clone.referenceText,+ hasReference: clone.reference !== null,+ }}+ />+ </AudioHistoryProvider>+ }+ />+ );+}++export function CloneFooter({+ clone,+ ...props+}: Omit<+ ComponentProps<typeof TtsFooter>,+ | "prompt"+ | "lyricsOptional"+ | "musicNeedsDescription"+ | "audioInstructions"+ | "handleGenerate"+ | "secondaryAction"+> & { clone: CloneGeneration }) {+ const [saving, setSaving] = useState(false);+ const save = useAudioVoicesStore((state) => state.save);+ const { reference } = clone;+ const canSave =+ reference !== null &&+ reference.kind !== "voice" &&+ !clone.referenceExpired &&+ clone.referenceStatus.phase !== "uploading" &&+ props.busy === null;+ return (+ <>+ <TtsFooter+ {...props}+ prompt={clone.text}+ lyricsOptional={false}+ musicNeedsDescription={false}+ audioInstructions=""+ handleGenerate={clone.handleGenerate}+ secondaryAction={+ reference?.kind === "voice" ? null : (+ <Button+ type="button"+ variant="outline"+ className="h-11 px-5"+ disabled={!canSave}+ onClick={() => setSaving(true)}+ >+ <HugeiconsIcon icon={FloppyDiskIcon} className="size-4" />+ Save voice…+ </Button>+ )+ }+ />+ <SaveVoiceDialog+ open={saving}+ onOpenChange={setSaving}+ mode="create"+ initial={{+ name: (reference?.name ?? "").replace(/\.[a-z0-9]{2,4}$/i, ""),+ transcript: clone.referenceText,+ language: clone.language,+ }}+ onSubmit={async (details) => {+ if (!reference || reference.kind === "voice") return;+ const voice = await save({+ source:+ reference.kind === "input"+ ? { input_id: reference.id }+ : { clip_id: reference.id },+ name: details.name,+ transcript: details.transcript || null,+ language: details.language || null,+ });+ toast.success(+ `Saved ${voice.name}. Pick it under Saved voice next time.`,+ );+ }}+ />+ </>+ );+}++export function CloneOutput({+ modelReady,+ recommendedModels = [],+ onPickModel,+ ...props+}: Omit<+ ComponentProps<typeof TtsOutput>,+ "emptyText" | "clipBadge" | "emptyActions"+> & {+ modelReady: boolean;+ recommendedModels?: readonly ModelOption[];+ onPickModel?: (id: string) => void;+}) {+ const picks = modelReady || !onPickModel ? [] : recommendedModels.slice(0, 3);+ return (+ <TtsOutput+ {...props}+ clipBadge={(clip) => clip.reference_name ?? null}+ emptyActions={+ picks.length > 0 ? (+ <div+ className="flex flex-wrap justify-center gap-2"+ aria-label="Recommended models"+ >+ {picks.map((model) => (+ <Button+ key={model.id}+ type="button"+ variant="outline"+ size="sm"+ onClick={() => onPickModel?.(model.id)}+ >+ Use {model.name}+ </Button>+ ))}+ </div>+ ) : null+ }+ emptyText={+ modelReady+ ? "Cloned speech lands here. Add a reference, type the text, and press Generate."+ : "Cloned speech lands here. Load a model that can clone, add a reference, and press Generate."+ }+ />+ );+}diff --git a/studio/frontend/src/features/audio/pages/speak-page.tsx b/studio/frontend/src/features/audio/pages/speak-page.tsxindex af0a9293414..1233a0d8e60 100644--- a/studio/frontend/src/features/audio/pages/speak-page.tsx+++ b/studio/frontend/src/features/audio/pages/speak-page.tsx@@ -3,6 +3,7 @@import type { ComponentProps } from "react";import type { ModelOption } from "@/features/model-picker/components/model-selector/types";+import { audioCppModelSpeaks } from "../audio-cpp-catalog";import { isMusicGenerationModel, macTtsCatalogChoiceIsRunnable } from "../catalog";import { TtsOutput, TtsRailFields } from "./tts-workspace";@@ -13,6 +14,7 @@ export function speakPageModels(return models.filter((model) =>!isMusicGenerationModel(model.id, model.audioType) &&+ audioCppModelSpeaks(model.id) &&(!isMac || macTtsCatalogChoiceIsRunnable(model.id)),);}diff --git a/studio/frontend/src/features/audio/pages/tts-workspace.tsx b/studio/frontend/src/features/audio/pages/tts-workspace.tsxindex 418d8d14b76..3a2970cf5ba 100644--- a/studio/frontend/src/features/audio/pages/tts-workspace.tsx+++ b/studio/frontend/src/features/audio/pages/tts-workspace.tsx@@ -93,7 +93,7 @@ export function TtsRailFields({ttsLoaded,handleEject,samplingControls,- audioOptionSpecs,+ audioOptionSpecs: allAudioOptionSpecs,advancedOpen,setAdvancedOpen,temperature,@@ -111,6 +111,8 @@ export function TtsRailFields({audioOptionValues,handleAudioOptionChange,handleAudioOptionsReset,+ inputs,+ claimedOptions,}: Pick<SpeechGeneration,| "prompt"@@ -141,7 +143,12 @@ export function TtsRailFields({isRecording: boolean;setAudioDeviceState: (next: string) => void;advancedOpen: boolean;+ inputs?: ReactNode;+ claimedOptions?: ReadonlySet<string>;}) {+ const audioOptionSpecs = claimedOptions?.size+ ? allAudioOptionSpecs.filter((spec) => !claimedOptions.has(spec.name))+ : allAudioOptionSpecs;return (<>{/* Field inlined: its label needs a form control to point@@ -183,27 +190,29 @@ export function TtsRailFields({: "New loads use the GPU when there is one, and the CPU otherwise."}</p></div>- <Field- label={musicGeneration ? "Lyrics" : "Text"}- htmlFor="audio-prompt"- hint={- musicGeneration- ? "Lyrics may use sections such as [verse] and [chorus]. The completed song lands in the gallery."- : "What the model should say. Generation runs on the loaded TTS model and lands in the gallery."- }- >- <Textarea- id="audio-prompt"- value={prompt}- onChange={(event) => setPrompt(event.target.value)}- placeholder={+ {inputs ?? (+ <Field+ label={musicGeneration ? "Lyrics" : "Text"}+ htmlFor="audio-prompt"+ hint={musicGeneration- ? "[verse]\nMorning light through the pines…\n\n[chorus]\n…"- : "Type the sentence to speak…"+ ? "Lyrics may use sections such as [verse] and [chorus]. The completed song lands in the gallery."+ : "What the model should say. Generation runs on the loaded TTS model and lands in the gallery."}- className="min-h-28"- />- </Field>+ >+ <Textarea+ id="audio-prompt"+ value={prompt}+ onChange={(event) => setPrompt(event.target.value)}+ placeholder={+ musicGeneration+ ? "[verse]\nMorning light through the pines…\n\n[chorus]\n…"+ : "Type the sentence to speak…"+ }+ className="min-h-28"+ />+ </Field>+ )}{toolPanels}{musicGeneration || samplingControls || audioOptionSpecs.length > 0 ? (<AdvancedDisclosure@@ -305,6 +314,7 @@ export function TtsFooter({shortcutLabel,error,elapsedSeconds,+ secondaryAction,loadNote = null,}: Pick<SpeechGeneration,@@ -321,6 +331,7 @@ export function TtsFooter({shortcutLabel: string;error: GenerateBlocker | null;elapsedSeconds: number | null;+ secondaryAction?: ReactNode;loadNote?: string | null;}) {return (@@ -351,46 +362,50 @@ export function TtsFooter({{loadNote}</p>) : null}- <Button- className={cn(- "relative z-10 mx-auto h-11 px-8 disabled:bg-muted disabled:text-muted-foreground disabled:opacity-100",- // Same Stop as Images: outline, neutral hover. Destructive is for deleting, not for stopping.- generationPresentation && "hover:bg-muted dark:hover:bg-muted",- )}- onClick={- generationPresentation?.canStop- ? handleStopGeneration- : handleGenerate- }- disabled={- generationPresentation- ? !generationPresentation.canStop- : busy !== null ||- !ttsLoaded ||- (!prompt.trim() && !lyricsOptional) ||- (musicNeedsDescription && !audioInstructions.trim())- }- variant={generationPresentation ? "outline" : "default"}- aria-describedby={blocker ? "audio-generate-blocker" : undefined}- aria-keyshortcuts="Control+Enter Meta+Enter"- title={- generationPresentation ? undefined : `Generate (${shortcutLabel})`- }- >- {generationPresentation?.canStop ? (- <>- <HugeiconsIcon icon={StopIcon} className="mr-2 size-4" />- Stop- </>- ) : generationPresentation ? (- <>- <Spinner className="mr-2 size-4" />- {generationPresentation.actionLabel}- </>- ) : (- "Generate"- )}- </Button>+ <div className="flex flex-wrap items-center justify-center gap-2">+ {secondaryAction}+ <Button+ className={cn(+ "relative z-10 mx-auto h-11 px-8 disabled:bg-muted disabled:text-muted-foreground disabled:opacity-100",+ // Same Stop as Images: outline, neutral hover. Destructive is for deleting, not for stopping.+ generationPresentation && "hover:bg-muted dark:hover:bg-muted",+ )}+ onClick={+ generationPresentation?.canStop+ ? handleStopGeneration+ : handleGenerate+ }+ disabled={+ generationPresentation+ ? !generationPresentation.canStop+ : busy !== null ||+ !ttsLoaded ||+ (!prompt.trim() && !lyricsOptional) ||+ (musicNeedsDescription && !audioInstructions.trim()) ||+ blocker !== null+ }+ variant={generationPresentation ? "outline" : "default"}+ aria-describedby={blocker ? "audio-generate-blocker" : undefined}+ aria-keyshortcuts="Control+Enter Meta+Enter"+ title={+ generationPresentation ? undefined : `Generate (${shortcutLabel})`+ }+ >+ {generationPresentation?.canStop ? (+ <>+ <HugeiconsIcon icon={StopIcon} className="mr-2 size-4" />+ Stop+ </>+ ) : generationPresentation ? (+ <>+ <Spinner className="mr-2 size-4" />+ {generationPresentation.actionLabel}+ </>+ ) : (+ "Generate"+ )}+ </Button>+ </div>{blocker && !generationPresentation ? (<pid="audio-generate-blocker"@@ -412,6 +427,18 @@ export function TtsFooter({);}+function ClipBadge({ text }: { text: string | null | undefined }) {+ if (!text) return null;+ return (+ <span+ title={text}+ className="max-w-[40%] shrink-0 truncate rounded-4xl bg-muted px-2 py-0.5 text-ui-11 text-muted-foreground"+ >+ {text}+ </span>+ );+}+export function TtsOutput({workflow,clips,@@ -424,6 +451,7 @@ export function TtsOutput({fallbackClip,handleDownloadFallbackClip,emptyText,+ emptyActions,handleClearGallery,historyReorder,hasMore,@@ -441,6 +469,7 @@ export function TtsOutput({freshClipId,onFreshClipFocused,announcement,+ clipBadge,}: Pick<AudioGallery,| "srcById"@@ -475,9 +504,11 @@ export function TtsOutput({onStop: () => void;} | null;emptyText: string;+ emptyActions?: ReactNode;freshClipId: string | null;onFreshClipFocused: () => void;announcement: string;+ clipBadge?: (clip: AudioGalleryClip) => string | null;}) {const clipMenu = (clip: AudioGalleryClip, variant: "row" | "toolbar") => (<GalleryItemMenu@@ -538,6 +569,7 @@ export function TtsOutput({: null}menu={clipMenu(selectedClip, "row")}+ status={clipBadge?.(selectedClip) ?? undefined}focusOnMount={selectedClip.id === freshClipId}onFocused={onFreshClipFocused}/>@@ -556,7 +588,10 @@ export function TtsOutput({}/>) : (- <p className="text-ui-13 text-muted-foreground">{emptyText}</p>+ <div className="grid justify-items-center gap-3">+ <p className="text-ui-13 text-muted-foreground">{emptyText}</p>+ {emptyActions}+ </div>)}</div>{clips.length > 0 ? (@@ -611,6 +646,7 @@ export function TtsOutput({className="size-3.5 shrink-0 text-muted-foreground"/><span className="min-w-0 flex-1 truncate">{clip.prompt}</span>+ <ClipBadge text={clipBadge?.(clip)} /><span className="hidden min-w-0 max-w-[45%] shrink truncate text-ui-11p5 text-muted-foreground @[30rem]:block">{audioModelLabel(clip.model)} ·{" "}{formatRelativeShort(clip.created_at)}diff --git a/studio/frontend/src/features/audio/picker-filter.ts b/studio/frontend/src/features/audio/picker-filter.tsindex c7c586c86f7..ba3b196248e 100644--- a/studio/frontend/src/features/audio/picker-filter.ts+++ b/studio/frontend/src/features/audio/picker-filter.ts@@ -3,7 +3,11 @@// Free of app imports so the node test runner can load it directly.-import { audioCppModelFor } from "./audio-cpp-catalog";+import {+ audioCppModelFor,+ isCloneOnlyFamilyId,+ isSpeakAndCloneFamilyId,+} from "./audio-cpp-catalog";import { isMusicGenerationModel } from "./catalog";import {type AudioWorkflowId,@@ -31,7 +35,18 @@ export function audioRowMatchesWorkflow(if (byTask === "transcribe" || byTask === "music") {return byTask === workflow;}- const catalogTask = audioCppModelFor(row.id)?.task;+ const catalogModel = audioCppModelFor(row.id);+ if (catalogModel?.workflows) {+ return catalogModel.workflows.includes(workflow);+ }+ // Hub search rows carry no backend workflows before download: name the clone-only families.+ if (isCloneOnlyFamilyId(row.id)) {+ return workflow === "clone";+ }+ if (isSpeakAndCloneFamilyId(row.id)) {+ return workflow === "speak" || workflow === "clone";+ }+ const catalogTask = catalogModel?.task;if (catalogTask === "music") {return workflow === "music";}@@ -39,6 +54,7 @@ export function audioRowMatchesWorkflow(return workflow === "transcribe";}if (byTask === "speak" || catalogTask === "tts" || row.audioType) {+ // Speech models clone only when the backend says so; an older row stays on Speak.return audioWorkflowForAudioType(row.audioType) === workflow;}return true;diff --git a/studio/frontend/src/features/audio/route-search.ts b/studio/frontend/src/features/audio/route-search.tsindex 21c69073fe6..f58aad80f70 100644--- a/studio/frontend/src/features/audio/route-search.ts+++ b/studio/frontend/src/features/audio/route-search.ts@@ -3,7 +3,11 @@// Free of app imports so the node test runner can load it directly.-import { AUDIO_CPP_AUDIO_TYPES, audioCppModelFor } from "./audio-cpp-catalog";+import {+ AUDIO_CPP_AUDIO_TYPES,+ audioCppModelFor,+ isCloneOnlyFamilyId,+} from "./audio-cpp-catalog";import {type AudioWorkflowId,MUSIC_AUDIO_TYPES,@@ -82,9 +86,15 @@ export function audioWorkflowForPick(pick: {if (workflow !== null && workflow !== "speak") {return workflow;}- // No task (or a speech one): the audio type or catalog entry can still say it makes music.- const music =- MUSIC_AUDIO_TYPES.has(pick.audioType ?? "") ||- audioCppModelFor(pick.id)?.task === "music";- return music ? "music" : workflow;+ // No task (or a speech one): the audio type or catalog entry can still name the page.+ const catalog = audioCppModelFor(pick.id);+ if (MUSIC_AUDIO_TYPES.has(pick.audioType ?? "") || catalog?.task === "music") {+ return "music";+ }+ if (catalog?.workflows) {+ return catalog.workflows.includes("speak")+ ? workflow+ : (catalog.workflows[0] ?? workflow);+ }+ return workflow === "speak" && isCloneOnlyFamilyId(pick.id) ? "clone" : workflow;}diff --git a/studio/frontend/src/features/audio/stores/audio-clone-store.ts b/studio/frontend/src/features/audio/stores/audio-clone-store.tsnew file mode 100644index 00000000000..e2ccdf988bc--- /dev/null+++ b/studio/frontend/src/features/audio/stores/audio-clone-store.ts@@ -0,0 +1,97 @@+// 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 { create } from "zustand";+import { persist } from "zustand/middleware";+import {+ type AudioSourceSelection,+ REFERENCE_MAX_SECONDS,+} from "../audio-run-request";++const AUDIO_CLONE_STORAGE_KEY = "unsloth_audio_clone_v1";++// Clone sends the reference's first 30 s, so a longer clip's full text would not match it.+function referenceTranscript(next: AudioSourceSelection | null): string {+ if (!next || (next.durationS ?? 0) > REFERENCE_MAX_SECONDS) return "";+ return next.transcript || "";+}++/** Also holds every page's tool values, not just Clone's. */+interface AudioCloneState {+ reference: AudioSourceSelection | null;+ referenceText: string;+ text: string;+ language: string;+ toolValues: Record<string, unknown>;+ setReference: (reference: AudioSourceSelection | null) => void;+ adoptReference: (next: AudioSourceSelection | null) => void;+ setReferenceText: (referenceText: string) => void;+ applyTranscript: (source: AudioSourceSelection, text: string) => void;+ setText: (text: string) => void;+ setLanguage: (language: string) => void;+ setToolValue: (key: string, value: unknown) => void;+}++const MAX_TOOL_VALUES = 200;++export const useAudioCloneStore = create<AudioCloneState>()(+ persist(+ (set) => ({+ reference: null,+ referenceText: "",+ text: "",+ language: "",+ toolValues: {},+ setReference: (reference) => set({ reference }),+ // Typed text survives a new pick; text that came from the old clip goes with it.+ adoptReference: (next) =>+ set((state) => {+ const typed =+ state.referenceText.trim() !== "" &&+ state.referenceText !== (state.reference?.transcript ?? "");+ return {+ reference: next,+ referenceText: typed ? state.referenceText : referenceTranscript(next),+ language: (!state.language && next?.language) || state.language,+ };+ }),+ setReferenceText: (referenceText) => set({ referenceText }),+ // Kept on the source too, so a new pick replaces it like the clip's own; a result for a clip+ // no longer picked is dropped.+ applyTranscript: (source, text) =>+ set((state) =>+ state.reference?.kind === source.kind &&+ state.reference.id === source.id+ ? {+ reference: { ...state.reference, transcript: text },+ referenceText: text,+ }+ : {},+ ),+ setText: (text) => set({ text }),+ setLanguage: (language) => set({ language }),+ setToolValue: (key, value) =>+ set((state) => {+ const entries = Object.entries(state.toolValues).filter(+ ([existing]) => existing !== key,+ );+ const kept =+ entries.length >= MAX_TOOL_VALUES+ ? entries.slice(entries.length - MAX_TOOL_VALUES + 1)+ : entries;+ return { toolValues: { ...Object.fromEntries(kept), [key]: value } };+ }),+ }),+ {+ name: AUDIO_CLONE_STORAGE_KEY,+ version: 1,+ partialize: (state) => ({+ reference: state.reference,+ referenceText: state.referenceText,+ text: state.text,+ language: state.language,+ toolValues: state.toolValues,+ }),+ },+ ),+);diff --git a/studio/frontend/src/features/audio/stores/audio-voices-store.ts b/studio/frontend/src/features/audio/stores/audio-voices-store.tsnew file mode 100644index 00000000000..175b8160884--- /dev/null+++ b/studio/frontend/src/features/audio/stores/audio-voices-store.ts@@ -0,0 +1,112 @@+// 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 { create } from "zustand";+import {+ type AudioVoice,+ createVoice,+ deleteVoice,+ listVoices,+ updateVoice,+} from "../api";+import type { AudioVoiceCreateRequest } from "../audio-run-request";++interface AudioVoicesState {+ voices: AudioVoice[];+ loaded: boolean;+ loading: boolean;+ error: string | null;+ refresh: () => Promise<void>;+ save: (request: AudioVoiceCreateRequest) => Promise<AudioVoice>;+ rename: (+ id: string,+ patch: Pick<AudioVoice, "name" | "transcript" | "language">,+ ) => Promise<void>;+ remove: (id: string) => Promise<void>;+}++// Bumped by each save, rename and delete: a list fetched across one is stale and is fetched again.+let mutations = 0;++const message = (error: unknown, fallback: string) =>+ error instanceof Error ? error.message : fallback;++export const useAudioVoicesStore = create<AudioVoicesState>()((set, get) => ({+ voices: [],+ loaded: false,+ loading: false,+ error: null,+ refresh: async () => {+ if (get().loading) return;+ set({ loading: true });+ const started = mutations;+ try {+ const voices = await listVoices();+ if (started !== mutations) {+ set({ loading: false });+ return get().refresh();+ }+ set({ voices, loaded: true, loading: false, error: null });+ } catch (error) {+ set({+ loading: false,+ loaded: true,+ error: message(error, "Could not list saved voices."),+ });+ }+ },+ save: async (request) => {+ const voice = await createVoice(request);+ mutations += 1;+ set((state) => ({+ voices: [voice, ...state.voices.filter((item) => item.id !== voice.id)],+ }));+ return voice;+ },+ rename: async (id, patch) => {+ const previous = get().voices.find((voice) => voice.id === id);+ set((state) => ({+ voices: state.voices.map((voice) =>+ voice.id === id ? { ...voice, ...patch } : voice,+ ),+ }));+ try {+ const saved = await updateVoice(id, patch);+ mutations += 1;+ set((state) => ({+ voices: state.voices.map((voice) => (voice.id === id ? saved : voice)),+ }));+ } catch (error) {+ // Put back only this voice: a save or deletion may have finished meanwhile.+ if (previous) {+ set((state) => ({+ voices: state.voices.map((voice) =>+ voice.id === id ? previous : voice,+ ),+ }));+ }+ throw error;+ }+ },+ remove: async (id) => {+ const before = get().voices;+ const index = before.findIndex((voice) => voice.id === id);+ set({ voices: before.filter((voice) => voice.id !== id) });+ try {+ await deleteVoice(id);+ mutations += 1;+ } catch (error) {+ // Put back only this voice: another deletion may have finished meanwhile.+ const failed = before[index];+ if (failed) {+ set((state) => {+ if (state.voices.some((voice) => voice.id === id)) return {};+ const voices = [...state.voices];+ voices.splice(Math.min(index, voices.length), 0, failed);+ return { voices };+ });+ }+ throw error;+ }+ },+}));diff --git a/studio/frontend/src/features/audio/stores/audio-workspace-store.ts b/studio/frontend/src/features/audio/stores/audio-workspace-store.tsindex fd701cf5355..82c1c5ca95e 100644--- a/studio/frontend/src/features/audio/stores/audio-workspace-store.ts+++ b/studio/frontend/src/features/audio/stores/audio-workspace-store.ts@@ -2,8 +2,11 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { create } from "zustand";+import { persist } from "zustand/middleware";import type { AudioWorkflowId } from "../workflows";+export const AUDIO_WORKSPACE_STORAGE_KEY = "unsloth_audio_workspace";+/** Only the page commits `workflow`; the sidebar and deep links put a request in* `requestedWorkflow`, which the page takes once it is free to switch, like an in-page tab click. */interface AudioWorkspaceState {@@ -11,24 +14,49 @@ interface AudioWorkspaceState {workflowChosen: boolean;requestedWorkflow: AudioWorkflowId | null;navExpanded: boolean;+ lastModelByWorkflow: Partial<Record<AudioWorkflowId, string>>;commitWorkflow: (workflow: AudioWorkflowId) => void;adoptWorkflow: (workflow: AudioWorkflowId) => void;requestWorkflow: (workflow: AudioWorkflowId) => void;clearRequestedWorkflow: () => void;setNavExpanded: (expanded: boolean) => void;+ rememberModel: (workflow: AudioWorkflowId, id: string) => void;}-export const useAudioWorkspaceStore = create<AudioWorkspaceState>()((set) => ({- workflow: "speak",- workflowChosen: false,- requestedWorkflow: null,- navExpanded: false,- // Any committed switch settles a pending request, so a stale one never fires later.- commitWorkflow: (workflow) =>- set({ workflow, workflowChosen: true, requestedWorkflow: null }),- adoptWorkflow: (workflow) =>- set((state) => (state.workflowChosen ? state : { workflow })),- requestWorkflow: (requestedWorkflow) => set({ requestedWorkflow }),- clearRequestedWorkflow: () => set({ requestedWorkflow: null }),- setNavExpanded: (navExpanded) => set({ navExpanded }),-}));+export const useAudioWorkspaceStore = create<AudioWorkspaceState>()(+ persist(+ (set) => ({+ workflow: "speak",+ workflowChosen: false,+ requestedWorkflow: null,+ navExpanded: false,+ lastModelByWorkflow: {},+ // Any committed switch settles a pending request, so a stale one never fires later.+ commitWorkflow: (workflow) =>+ set({ workflow, workflowChosen: true, requestedWorkflow: null }),+ adoptWorkflow: (workflow) =>+ set((state) => (state.workflowChosen ? state : { workflow })),+ requestWorkflow: (requestedWorkflow) => set({ requestedWorkflow }),+ clearRequestedWorkflow: () => set({ requestedWorkflow: null }),+ setNavExpanded: (navExpanded) => set({ navExpanded }),+ rememberModel: (workflow, id) =>+ set((state) =>+ state.lastModelByWorkflow[workflow] === id+ ? state+ : {+ lastModelByWorkflow: {+ ...state.lastModelByWorkflow,+ [workflow]: id,+ },+ },+ ),+ }),+ {+ name: AUDIO_WORKSPACE_STORAGE_KEY,+ version: 1,+ partialize: (state) => ({+ lastModelByWorkflow: state.lastModelByWorkflow,+ }),+ },+ ),+);diff --git a/studio/frontend/src/features/audio/tools/clone-panels.tsx b/studio/frontend/src/features/audio/tools/clone-panels.tsxnew file mode 100644index 00000000000..1d64d614b55--- /dev/null+++ b/studio/frontend/src/features/audio/tools/clone-panels.tsx@@ -0,0 +1,304 @@+// 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 {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { Switch } from "@/components/ui/switch";+import { Textarea } from "@/components/ui/textarea";+import { ParamSlider } from "@/features/chat";+import { PillTabs } from "@/features/model-picker/components/model-selector/pill-tabs";+import type { ReactNode } from "react";+import { INDEX_TTS2_EMOTIONS } from "../clone-policy";+import { AudioSourceInput } from "../components/audio-source-input";+import { Field } from "../components/field";+import {+ type CosyVoiceMode,+ type CosyVoiceModeValue,+ type EmotionMode,+ type EmotionValue,+ type ExpressivenessValue,+ F5_DIALECTS,+ type SpeedDialectValue,+ type TimbreOnlyValue,+ chatterboxExpressivenessLogic,+ cosyVoiceModeLogic,+ emotionSourceProblem,+ f5SpeedDialectLogic,+ indexTts2EmotionLogic,+ qwen3TimbreLogic,+} from "./panel-logic";+import type { AudioToolPanel } from "./types";++function PanelSection({+ title,+ hint,+ children,+}: {+ title: string;+ hint?: string;+ children: ReactNode;+}) {+ return (+ <section className="grid gap-3" aria-label={title}>+ <div className="grid gap-0.5">+ <h3 className="text-ui-13 font-medium text-foreground">{title}</h3>+ {hint ? (+ <p className="text-ui-11p5 leading-snug text-muted-foreground">+ {hint}+ </p>+ ) : null}+ </div>+ {children}+ </section>+ );+}++const qwen3TimbrePanel: AudioToolPanel<TimbreOnlyValue> = {+ ...qwen3TimbreLogic,+ Component: ({ value, onChange, disabled }) => (+ <div className="grid gap-1.5">+ <label+ htmlFor="clone-timbre-only"+ className="flex items-center justify-between gap-3 text-ui-13 font-medium text-foreground"+ >+ Timbre only+ <Switch+ id="clone-timbre-only"+ checked={value.timbreOnly}+ disabled={disabled}+ onCheckedChange={(timbreOnly) => onChange({ timbreOnly })}+ />+ </label>+ <p className="text-ui-11p5 leading-snug text-muted-foreground">+ Copies the sound of the voice without the clip's words, so no transcript+ is needed. Usually a little less close to the original.+ </p>+ </div>+ ),+};++const indexTts2EmotionPanel: AudioToolPanel<EmotionValue> = {+ ...indexTts2EmotionLogic,+ Component: ({ value, onChange, disabled }) => (+ <PanelSection+ title="Emotion"+ hint="Optional. Leave it empty for the reference's own delivery."+ >+ <PillTabs+ ariaLabel="Emotion source"+ value={value.mode}+ onValueChange={(mode) =>+ onChange({ ...value, mode: mode as EmotionMode })+ }+ disabled={disabled}+ fit={true}+ compact={true}+ className="[&>button]:px-3"+ tabs={[+ { value: "text", label: "From text" },+ { value: "audio", label: "From audio" },+ { value: "mixer", label: "Mixer" },+ ]}+ />+ {value.mode === "text" ? (+ <Field+ label="Describe the emotion"+ htmlFor="clone-emotion-text"+ hint="A few words, such as “excited and a little nervous”."+ >+ <Textarea+ id="clone-emotion-text"+ value={value.text}+ disabled={disabled}+ onChange={(event) =>+ onChange({ ...value, text: event.target.value })+ }+ className="min-h-16"+ />+ </Field>+ ) : value.mode === "audio" ? (+ <AudioSourceInput+ id="clone-emotion-audio"+ label="Emotion clip"+ hint="Its mood is copied, not its voice."+ value={value.source}+ onChange={(source) => onChange({ ...value, source })}+ onStatusChange={(status) => {+ const sourceProblem = emotionSourceProblem(status);+ if (sourceProblem !== (value.sourceProblem ?? null)) {+ onChange({ ...value, sourceProblem });+ }+ }}+ disabled={disabled}+ allowSavedVoice={false}+ />+ ) : (+ <div className="grid gap-2">+ {INDEX_TTS2_EMOTIONS.map((emotion, index) => (+ <ParamSlider+ key={emotion.key}+ label={emotion.label}+ value={value.vector[index] ?? 0}+ min={0}+ max={1}+ step={0.05}+ disabled={disabled}+ inline={true}+ onChange={(next) => {+ const vector = INDEX_TTS2_EMOTIONS.map((_, i) =>+ i === index ? next : (value.vector[i] ?? 0),+ );+ onChange({ ...value, vector });+ }}+ />+ ))}+ </div>+ )}+ <ParamSlider+ label="Strength"+ value={value.alpha}+ min={0}+ max={1}+ step={0.05}+ disabled={disabled}+ info="How strongly the emotion colours the voice."+ onChange={(alpha) => onChange({ ...value, alpha })}+ />+ </PanelSection>+ ),+};++const chatterboxExpressivenessPanel: AudioToolPanel<ExpressivenessValue> = {+ ...chatterboxExpressivenessLogic,+ Component: ({ value, onChange, disabled }) => (+ <PanelSection+ title="Expressiveness"+ hint="The first run with a new voice or setting takes 5 to 15 s while the model studies it."+ >+ <ParamSlider+ label="Intensity"+ value={value.exaggeration}+ min={0}+ max={2}+ step={0.05}+ disabled={disabled}+ info="Higher is more dramatic; 0.5 is natural."+ onChange={(exaggeration) => onChange({ ...value, exaggeration })}+ />+ <ParamSlider+ label="Guidance"+ value={value.guidance}+ min={0}+ max={5}+ step={0.05}+ disabled={disabled}+ info="How closely the delivery follows the reference. Lower suits fast speakers."+ onChange={(guidance) => onChange({ ...value, guidance })}+ />+ </PanelSection>+ ),+};++const cosyVoiceModePanel: AudioToolPanel<CosyVoiceModeValue> = {+ ...cosyVoiceModeLogic,+ Component: ({ value, onChange, disabled }) => (+ <PanelSection+ title="Mode"+ hint={+ value.mode === "zero_shot"+ ? "Same language: speaks in the clip's language, using what's said in it."+ : value.mode === "cross_lingual"+ ? "Cross-lingual: speaks another language in the same voice. No transcript needed."+ : "Instruct: the same voice, delivered the way you describe."+ }+ >+ <PillTabs+ ariaLabel="Mode"+ value={value.mode}+ onValueChange={(mode) =>+ onChange({ ...value, mode: mode as CosyVoiceMode })+ }+ disabled={disabled}+ fit={true}+ compact={true}+ className="[&>button]:px-3"+ tabs={[+ { value: "zero_shot", label: "Same language" },+ { value: "cross_lingual", label: "Cross-lingual" },+ { value: "instruct", label: "Instruct" },+ ]}+ />+ {value.mode === "instruct" ? (+ <Field label="Instruction" htmlFor="clone-instruction">+ <Textarea+ id="clone-instruction"+ value={value.instruction}+ disabled={disabled}+ placeholder="Speak slowly, in a calm and warm tone."+ onChange={(event) =>+ onChange({ ...value, instruction: event.target.value })+ }+ className="min-h-16"+ />+ </Field>+ ) : null}+ </PanelSection>+ ),+};++const f5SpeedDialectPanel: AudioToolPanel<SpeedDialectValue> = {+ ...f5SpeedDialectLogic,+ Component: ({ value, onChange, disabled, specs }) => (+ <PanelSection title="Speed and dialect">+ <ParamSlider+ label="Speed"+ value={value.speed}+ min={0.5}+ max={2}+ step={0.05}+ disabled={disabled}+ displayValue={`${value.speed.toFixed(2)}×`}+ onChange={(speed) => onChange({ ...value, speed })}+ />+ {specs.some((spec) => spec.name === "dialect") ? (+ <div className="grid gap-1.5">+ <label+ htmlFor="clone-dialect"+ className="text-ui-13 font-medium text-foreground"+ >+ Dialect+ </label>+ <Select+ value={value.dialect}+ onValueChange={(dialect) => onChange({ ...value, dialect })}+ disabled={disabled}+ >+ <SelectTrigger id="clone-dialect" size="sm" className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {F5_DIALECTS.map((dialect) => (+ <SelectItem key={dialect.value} value={dialect.value}>+ {dialect.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ ) : null}+ </PanelSection>+ ),+};++export const CLONE_TOOL_PANELS = [+ qwen3TimbrePanel,+ indexTts2EmotionPanel,+ chatterboxExpressivenessPanel,+ cosyVoiceModePanel,+ f5SpeedDialectPanel,+] as const;diff --git a/studio/frontend/src/features/audio/tools/panel-logic.ts b/studio/frontend/src/features/audio/tools/panel-logic.tsnew file mode 100644index 00000000000..3183a54cb34--- /dev/null+++ b/studio/frontend/src/features/audio/tools/panel-logic.ts@@ -0,0 +1,269 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// JSX-free so the node test runner can load it; clone-panels.tsx / speak-panels.tsx add Components.++import { type AudioSourceSelection, sourceRefOf } from "../audio-run-request";+import { INDEX_TTS2_EMOTIONS, emotionVectorString } from "../clone-policy";+import type { AudioSourceStatus } from "../hooks/audio-source-state";+import type { AudioRunPatch, AudioToolPanel } from "./types";++type AudioToolPanelLogic<V> = Omit<AudioToolPanel<V>, "Component">;++const clamp = (x: number, lo: number, hi: number) =>+ Math.min(hi, Math.max(lo, x));++export interface TimbreOnlyValue {+ timbreOnly: boolean;+}++export const qwen3TimbreLogic: AudioToolPanelLogic<TimbreOnlyValue> = {+ id: "qwen3-timbre",+ families: ["qwen3_tts"],+ workflows: ["clone"],+ title: "Timbre only",+ claims: ["x_vector_only_mode"],+ initial: () => ({ timbreOnly: false }),+ toRequest: (value) =>+ value.timbreOnly+ ? {+ options: { x_vector_only_mode: true },+ referenceTextMode: "hidden",+ }+ : {},+};++export type EmotionMode = "text" | "audio" | "mixer";++export interface EmotionValue {+ mode: EmotionMode;+ text: string;+ vector: number[];+ alpha: number;+ source: AudioSourceSelection | null;+ /** Why the emotion clip cannot be sent yet (uploading, failed, expired); set by its input. */+ sourceProblem?: string | null;+}++export function emotionSourceProblem(status: AudioSourceStatus): string | null {+ if (status.phase === "uploading" || status.phase === "recording") {+ return "Waiting for the emotion clip to finish uploading.";+ }+ if (status.phase === "error") return status.message;+ if (status.phase === "expired") return "The emotion clip expired. Add it again.";+ return null;+}++export const EMOTION_AUDIO_MISSING =+ "Add the clip whose emotion to copy, or switch Emotion to From text.";++export const indexTts2EmotionLogic: AudioToolPanelLogic<EmotionValue> = {+ id: "index-emotion",+ families: ["index_tts2"],+ workflows: ["clone"],+ title: "Emotion",+ claims: [+ "emotion_vector",+ "emotion_alpha",+ "use_emotion_text",+ "emotion_text",+ ],+ initial: () => ({+ mode: "text",+ text: "",+ vector: INDEX_TTS2_EMOTIONS.map(() => 0),+ alpha: 0.7,+ source: null,+ }),+ toRequest: (value): AudioRunPatch => {+ const alpha = clamp(value.alpha, 0, 1);+ if (value.mode === "text") {+ const text = value.text.trim();+ return text+ ? {+ options: {+ use_emotion_text: true,+ emotion_text: text,+ emotion_alpha: alpha,+ },+ }+ : {};+ }+ if (value.mode === "audio") {+ return value.source+ ? {+ inputs: { emotion: sourceRefOf(value.source) },+ options: { emotion_alpha: alpha },+ }+ : {};+ }+ return value.vector.some((weight) => weight > 0)+ ? {+ options: {+ emotion_vector: emotionVectorString(value.vector),+ emotion_alpha: alpha,+ },+ }+ : {};+ },+ validate: (value) =>+ value.mode !== "audio"+ ? null+ : (value.sourceProblem ?? (value.source ? null : EMOTION_AUDIO_MISSING)),+};++export interface ExpressivenessValue {+ exaggeration: number;+ guidance: number;+}++export const chatterboxExpressivenessLogic: AudioToolPanelLogic<ExpressivenessValue> =+ {+ id: "chatterbox-expressiveness",+ families: ["chatterbox"],+ workflows: ["clone"],+ title: "Expressiveness",+ claims: ["exaggeration", "guidance_scale"],+ initial: () => ({ exaggeration: 0.5, guidance: 0.5 }),+ toRequest: (value) => ({+ options: {+ exaggeration: clamp(value.exaggeration, 0, 2),+ guidance_scale: clamp(value.guidance, 0, 5),+ },+ }),+ };++export type CosyVoiceMode = "zero_shot" | "cross_lingual" | "instruct";++export interface CosyVoiceModeValue {+ mode: CosyVoiceMode;+ instruction: string;+}++export const COSYVOICE_INSTRUCTION_MISSING =+ "Write the instruction for Instruct, or pick another mode.";++export const cosyVoiceModeLogic: AudioToolPanelLogic<CosyVoiceModeValue> = {+ id: "cosyvoice-mode",+ families: ["cosyvoice3"],+ workflows: ["clone"],+ title: "Mode",+ claims: ["template_name", "instruction"],+ initial: () => ({ mode: "zero_shot", instruction: "" }),+ toRequest: (value) => {+ if (value.mode === "cross_lingual") {+ return {+ options: { template_name: "cross_lingual" },+ referenceTextMode: "hidden",+ };+ }+ if (value.mode === "instruct") {+ const instruction = value.instruction.trim();+ return {+ options: { template_name: "instruct" },+ ...(instruction ? { instructions: instruction } : {}),+ referenceTextMode: "optional",+ };+ }+ return { options: { template_name: "zero_shot" } };+ },+ validate: (value) =>+ value.mode === "instruct" && !value.instruction.trim()+ ? COSYVOICE_INSTRUCTION_MISSING+ : null,+};++export interface SpeedDialectValue {+ speed: number;+ dialect: string;+}++export const F5_DIALECTS: readonly { value: string; label: string }[] = [+ { value: "UNK", label: "Auto" },+ { value: "MSA", label: "Modern Standard Arabic" },+ { value: "SAU", label: "Saudi" },+ { value: "UAE", label: "Emirati" },+ { value: "ALG", label: "Algerian" },+ { value: "IRQ", label: "Iraqi" },+ { value: "EGY", label: "Egyptian" },+ { value: "MAR", label: "Moroccan" },+ { value: "OMN", label: "Omani" },+ { value: "TUN", label: "Tunisian" },+ { value: "LEV", label: "Levantine" },+ { value: "SDN", label: "Sudanese" },+ { value: "LBY", label: "Libyan" },+];++export const f5SpeedDialectLogic: AudioToolPanelLogic<SpeedDialectValue> = {+ id: "f5-speed-dialect",+ families: ["f5_tts"],+ workflows: ["clone"],+ title: "Speed and dialect",+ claims: ["speed", "dialect"],+ initial: () => ({ speed: 1, dialect: "UNK" }),+ toRequest: (value) => ({+ ...(Math.abs(value.speed - 1) > 1e-6+ ? { speed: clamp(value.speed, 0.5, 2) }+ : {}),+ ...(value.dialect && value.dialect !== "UNK"+ ? { options: { dialect: value.dialect } }+ : {}),+ }),+};++export interface SpeakVoiceValue {+ source: "builtin" | "saved";+ voiceId: string | null;+}++export const SAVED_VOICE_MISSING =+ "Pick a saved voice, or switch Voice to Built-in.";+export const SAVED_VOICE_DELETED =+ "That saved voice was deleted. Pick another one, or switch Voice to Built-in.";++export const speakVoiceLogic: AudioToolPanelLogic<SpeakVoiceValue> = {+ id: "speak-voice",+ families: [],+ workflows: ["speak"],+ title: "Voice",+ claims: [],+ // Speak sends no transcript, so a model that needs one (Fish Audio) clones only on Clone.+ appliesTo: (ctx) =>+ Boolean(+ ctx.audioWorkflows?.includes("speak") &&+ ctx.audioWorkflows.includes("clone") &&+ ctx.referenceTextMode !== "required",+ ),+ initial: () => ({ source: "builtin", voiceId: null }),+ toRequest: (value) =>+ value.source === "saved" && value.voiceId+ ? { inputs: { reference: { voice_id: value.voiceId } } }+ : {},+ validate: (value, _core, ctx) => {+ if (value.source !== "saved") return null;+ if (!value.voiceId) return SAVED_VOICE_MISSING;+ // Deleting a voice on Clone does not reach the choice kept here.+ return ctx.savedVoiceIds && !ctx.savedVoiceIds.includes(value.voiceId)+ ? SAVED_VOICE_DELETED+ : null;+ },+};++// The backend formats plain text into `Speaker N:` lines, so nothing is sent.+export const vibeVoiceDialogueLogic: AudioToolPanelLogic<null> = {+ id: "vibevoice-dialogue",+ families: ["vibevoice"],+ workflows: ["speak"],+ title: "Dialogue",+ claims: [],+ initial: () => null,+ toRequest: () => ({}),+};++export const CLONE_PANEL_LOGIC = [+ qwen3TimbreLogic,+ indexTts2EmotionLogic,+ chatterboxExpressivenessLogic,+ cosyVoiceModeLogic,+ f5SpeedDialectLogic,+] as const;diff --git a/studio/frontend/src/features/audio/tools/registry.tsx b/studio/frontend/src/features/audio/tools/registry.tsxnew file mode 100644index 00000000000..1f59e8665ae--- /dev/null+++ b/studio/frontend/src/features/audio/tools/registry.tsx@@ -0,0 +1,119 @@+// 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 type { NativeAudioInstructionsKind } from "../audio-page-policy";+import {+ InstructionsField,+ MossLanguageField,+} from "../components/instructions-fields";+import type { AudioWorkflowId } from "../workflows";+import { CLONE_TOOL_PANELS } from "./clone-panels";+import { instructionsKindFor, panelApplies } from "./select";+import { SPEAK_TOOL_PANELS } from "./speak-panels";+import type {+ AnyAudioToolPanel,+ AudioModelContext,+ AudioToolPanel,+} from "./types";++export interface InstructionsValue {+ instructions: string;+ language: string;+}++export const MUSIC_DESCRIPTION_REQUIRED =+ "Add a music description. This model needs one beside the lyrics.";++const VOICE_DESCRIPTION_REQUIRED =+ "Describe the voice. This model needs a voice description.";++function needsVoiceDescription(ctx: AudioModelContext): boolean {+ return ctx.requiredInputs?.includes("instruct") === true;+}++function instructionsPanel(+ id: string,+ kind: NativeAudioInstructionsKind,+ title: string,+ workflows: readonly AudioWorkflowId[],+): AudioToolPanel<InstructionsValue> {+ return {+ id,+ families: [],+ workflows,+ title,+ // Request fields, not spec options, so Advanced keeps every option.+ claims: [],+ appliesTo: (ctx) => instructionsKindFor(ctx) === kind,+ initial: () => ({ instructions: "", language: "" }),+ Component: ({ value, onChange, ctx }) => (+ <>+ <InstructionsField+ instructionsKind={kind}+ musicNeedsDescription={ctx.musicNeedsDescription}+ voiceRequired={kind === "voice" && needsVoiceDescription(ctx)}+ audioInstructions={value.instructions}+ setAudioInstructions={(instructions) =>+ onChange({ ...value, instructions })+ }+ />+ {kind === "style" ? (+ <MossLanguageField+ audioLanguage={value.language}+ setAudioLanguage={(language) => onChange({ ...value, language })}+ />+ ) : null}+ </>+ ),+ toRequest: (value) => {+ const instructions = value.instructions.trim();+ const language = value.language.trim();+ return {+ ...(instructions ? { instructions } : {}),+ ...(kind === "style" && language ? { language } : {}),+ };+ },+ validate: (value, _core, ctx) =>+ kind === "music" && ctx.musicNeedsDescription && !value.instructions.trim()+ ? MUSIC_DESCRIPTION_REQUIRED+ : kind === "voice" &&+ needsVoiceDescription(ctx) &&+ !value.instructions.trim()+ ? VOICE_DESCRIPTION_REQUIRED+ : null,+ };+}++const INSTRUCTION_PANELS: readonly AudioToolPanel<InstructionsValue>[] =+ [+ // Qwen3-TTS VoiceDesign and CustomVoice and VoxCPM2 read it; other GGUF speech models ignore it.+ instructionsPanel("voice-design", "voice", "Voice design", ["speak"]),+ instructionsPanel("higgs-scene", "scene", "Scene", ["speak"]),+ instructionsPanel("moss-style", "style", "Style", ["speak"]),+ // MiniMax Music 3 and YuE2 require it; other music models fall back to the lyrics.+ instructionsPanel("music-description", "music", "Description", ["music"]),+ ];++const INSTRUCTION_PANEL_IDS: ReadonlySet<string> = new Set(+ INSTRUCTION_PANELS.map((panel) => panel.id),+);++export function isInstructionPanel(id: string): boolean {+ return INSTRUCTION_PANEL_IDS.has(id);+}++export const AUDIO_TOOL_PANELS: readonly AnyAudioToolPanel[] = [+ SPEAK_TOOL_PANELS[0],+ ...INSTRUCTION_PANELS,+ ...SPEAK_TOOL_PANELS.slice(1),+ ...CLONE_TOOL_PANELS,+];++export function audioToolPanelsFor(+ workflow: AudioWorkflowId,+ ctx: AudioModelContext,+): readonly AnyAudioToolPanel[] {+ return AUDIO_TOOL_PANELS.filter((panel) =>+ panelApplies(panel, workflow, ctx),+ );+}diff --git a/studio/frontend/src/features/audio/tools/select.ts b/studio/frontend/src/features/audio/tools/select.tsnew file mode 100644index 00000000000..b1be0df12a5--- /dev/null+++ b/studio/frontend/src/features/audio/tools/select.ts@@ -0,0 +1,142 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Which tool panels a model gets. Free of JSX so the node test runner can load it.++import type { AudioOptionSpec } from "../audio-options";+import {+ type NativeAudioInstructionsKind,+ nativeAudioInstructionsKind,+} from "../audio-page-policy";+import type { AudioWorkflowId } from "../workflows";+import type {+ AnyAudioToolPanel,+ AudioModelContext,+ AudioReferenceTextMode,+ AudioRunPatch,+ AudioToolPanel,+ CoreInputs,+} from "./types";++export function instructionsKindFor(+ ctx: AudioModelContext,+): NativeAudioInstructionsKind | null {+ return ctx.musicGeneration+ ? "music"+ : nativeAudioInstructionsKind(ctx.audioType);+}++export function panelApplies(+ panel: Pick<AudioToolPanel<unknown>, "workflows" | "families" | "appliesTo">,+ workflow: AudioWorkflowId,+ ctx: AudioModelContext,+): boolean {+ if (!panel.workflows.includes(workflow)) return false;+ return panel.appliesTo+ ? panel.appliesTo(ctx)+ : panel.families.includes(ctx.audioFamily ?? "");+}++export function claimedOptionNames(+ panels: readonly Pick<AudioToolPanel<unknown>, "claims">[],+): Set<string> {+ return new Set(panels.flatMap((panel) => panel.claims));+}++const REFERENCE_TEXT_MODES: ReadonlySet<string> = new Set([+ "required",+ "optional",+ "unused",+]);++export function audioModelContextFor(+ status: {+ audio_type?: string | null;+ audio_family?: string | null;+ audio_workflows?: readonly string[] | null;+ audio_required_inputs?: readonly string[] | null;+ audio_reference_text?: string | null;+ } | null,+ page: {+ musicGeneration: boolean;+ cudaMusicGeneration: boolean;+ musicNeedsDescription: boolean;+ },+): AudioModelContext {+ const referenceText = status?.audio_reference_text;+ return {+ audioType: status?.audio_type ?? null,+ audioFamily: status?.audio_family ?? null,+ musicGeneration: page.musicGeneration,+ cudaMusicGeneration: page.cudaMusicGeneration,+ musicNeedsDescription: page.musicNeedsDescription,+ audioWorkflows: Array.isArray(status?.audio_workflows)+ ? status.audio_workflows+ : [],+ requiredInputs: Array.isArray(status?.audio_required_inputs)+ ? status.audio_required_inputs+ : [],+ referenceTextMode:+ typeof referenceText === "string" &&+ REFERENCE_TEXT_MODES.has(referenceText)+ ? (referenceText as AudioReferenceTextMode)+ : null,+ };+}++export function toolValueKey(+ model: string | null | undefined,+ workflow: AudioWorkflowId,+ panelId: string,+): string {+ return `${model ?? ""}:${workflow}:${panelId}`;+}++const isPlainObject = (value: unknown): value is Record<string, unknown> =>+ typeof value === "object" && value !== null && !Array.isArray(value);++// Kept value over defaults, so a value saved by an older build still has every field.+export function panelValue<V>(+ panel: Pick<AudioToolPanel<V>, "id" | "initial">,+ values: Readonly<Record<string, unknown>>,+ specs: AudioOptionSpec[],+): V {+ const initial = panel.initial(specs);+ const stored = values[panel.id];+ if (stored === undefined) return initial;+ if (isPlainObject(initial) && isPlainObject(stored)) {+ return { ...initial, ...stored } as V;+ }+ return stored as V;+}++export function collectToolRequest(+ panels: readonly AnyAudioToolPanel[],+ values: Readonly<Record<string, unknown>>,+ core: CoreInputs,+ ctx: AudioModelContext,+ specs: AudioOptionSpec[] = [],+): { patch: AudioRunPatch; error: string | null } {+ const patch: AudioRunPatch = {};+ let error: string | null = null;+ for (const panel of panels) {+ const value = panelValue(panel, values, specs);+ error ??= panel.validate?.(value, core, ctx) ?? null;+ const part = panel.toRequest(value);+ if (part.options) patch.options = { ...patch.options, ...part.options };+ if (part.inputs) patch.inputs = { ...patch.inputs, ...part.inputs };+ for (const key of [+ "instructions",+ "language",+ "route",+ "text",+ "speed",+ "referenceTextMode",+ ] as const) {+ if (part[key] !== undefined) {+ (patch as Record<string, unknown>)[key] = part[key];+ }+ }+ }+ return { patch, error };+}diff --git a/studio/frontend/src/features/audio/tools/speak-panels.tsx b/studio/frontend/src/features/audio/tools/speak-panels.tsxnew file mode 100644index 00000000000..90eb45c7c12--- /dev/null+++ b/studio/frontend/src/features/audio/tools/speak-panels.tsx@@ -0,0 +1,79 @@+// 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 { PillTabs } from "@/features/model-picker/components/model-selector/pill-tabs";+import { formatVibeVoiceScript } from "../clone-policy";+import { VoicePicker } from "../components/voice-picker";+import {+ type SpeakVoiceValue,+ speakVoiceLogic,+ vibeVoiceDialogueLogic,+} from "./panel-logic";+import type { AudioToolPanel } from "./types";++const speakVoicePanel: AudioToolPanel<SpeakVoiceValue> = {+ ...speakVoiceLogic,+ Component: ({ value, onChange, disabled }) => (+ <div className="grid gap-2">+ <span className="text-ui-13 font-medium text-foreground">Voice</span>+ <PillTabs+ ariaLabel="Voice"+ value={value.source}+ onValueChange={(source) =>+ onChange({+ ...value,+ source: source === "saved" ? "saved" : "builtin",+ })+ }+ disabled={disabled}+ fit={true}+ compact={true}+ className="[&>button]:px-3"+ tabs={[+ { value: "builtin", label: "Built-in" },+ { value: "saved", label: "Saved" },+ ]}+ />+ {value.source === "saved" ? (+ <VoicePicker+ selectedId={value.voiceId}+ disabled={disabled}+ onSelect={(voice) => onChange({ ...value, voiceId: voice.id })}+ onDeselect={() => onChange({ ...value, voiceId: null })}+ />+ ) : (+ <p className="text-ui-11p5 leading-snug text-muted-foreground">+ The model's own voice, shaped by a voice description when you give+ one.+ </p>+ )}+ </div>+ ),+};++const vibeVoiceDialoguePanel: AudioToolPanel<null> = {+ ...vibeVoiceDialogueLogic,+ Component: ({ core }) => {+ const text = core?.text.trim() ?? "";+ const script = formatVibeVoiceScript(text);+ return (+ <div className="grid gap-1.5">+ <span className="text-ui-13 font-medium text-foreground">Dialogue</span>+ <p className="text-ui-11p5 leading-snug text-muted-foreground">+ This model reads a script with one line per speaker, such as “Speaker+ 1: Hello.” Plain text is read by Speaker 1.+ </p>+ {text && script !== text ? (+ <pre className="max-h-24 overflow-auto whitespace-pre-wrap rounded-xl bg-muted px-3 py-2 font-mono text-ui-11p5 text-muted-foreground">+ {script}+ </pre>+ ) : null}+ </div>+ );+ },+};++export const SPEAK_TOOL_PANELS = [+ speakVoicePanel,+ vibeVoiceDialoguePanel,+] as const;diff --git a/studio/frontend/src/features/audio/tools/tool-panel-host.tsx b/studio/frontend/src/features/audio/tools/tool-panel-host.tsxnew file mode 100644index 00000000000..991033c7cc8--- /dev/null+++ b/studio/frontend/src/features/audio/tools/tool-panel-host.tsx@@ -0,0 +1,42 @@+// 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 type { AudioOptionSpec } from "../audio-options";+import type { AudioWorkflowId } from "../workflows";+import { audioToolPanelsFor } from "./registry";+import { panelValue } from "./select";+import type { AudioModelContext, CoreInputs } from "./types";++export function AudioToolPanels({+ workflow,+ ctx,+ values,+ onChange,+ specs,+ disabled,+ core,+}: {+ workflow: AudioWorkflowId;+ ctx: AudioModelContext;+ values: Readonly<Record<string, unknown>>;+ onChange: (panelId: string, value: unknown) => void;+ specs: AudioOptionSpec[];+ disabled: boolean;+ core?: CoreInputs;+}) {+ return (+ <>+ {audioToolPanelsFor(workflow, ctx).map((panel) => (+ <panel.Component+ key={panel.id}+ value={panelValue(panel, values, specs)}+ onChange={(value: unknown) => onChange(panel.id, value)}+ specs={specs}+ disabled={disabled}+ ctx={ctx}+ core={core}+ />+ ))}+ </>+ );+}diff --git a/studio/frontend/src/features/audio/tools/types.ts b/studio/frontend/src/features/audio/tools/types.tsnew file mode 100644index 00000000000..e1c8167edd0--- /dev/null+++ b/studio/frontend/src/features/audio/tools/types.ts@@ -0,0 +1,71 @@+// 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 type { ComponentType } from "react";+import type { AudioOptionSpec, AudioOptionValues } from "../audio-options";+import type { AudioSourceRef } from "../audio-run-request";+import type { AudioWorkflowId } from "../workflows";++export type AudioReferenceTextMode = "required" | "optional" | "unused";++export interface AudioModelContext {+ audioType: string | null;+ audioFamily: string | null;+ musicGeneration: boolean;+ cudaMusicGeneration: boolean;+ /** MiniMax Music 3 and YuE2 need a description beside the lyrics. */+ musicNeedsDescription: boolean;+ audioWorkflows?: readonly string[];+ requiredInputs?: readonly string[];+ referenceTextMode?: AudioReferenceTextMode | null;+ /** Ids of the saved voices, once the list has loaded. */+ savedVoiceIds?: readonly string[] | null;+}++export interface AudioRunPatch {+ instructions?: string;+ language?: string;+ options?: AudioOptionValues;+ inputs?: { reference?: AudioSourceRef; emotion?: AudioSourceRef };+ route?: string;+ text?: string;+ speed?: number;+ referenceTextMode?: "required" | "optional" | "hidden";+}++export interface CoreInputs {+ text: string;+ referenceText?: string;+ hasReference?: boolean;+}++export interface AudioToolPanelProps<V> {+ value: V;+ onChange: (value: V) => void;+ specs: AudioOptionSpec[];+ disabled: boolean;+ ctx: AudioModelContext;+ core?: CoreInputs;+}++export interface AudioToolPanel<V> {+ id: string;+ /** Runtime families the panel serves. Ignored when `appliesTo` is given. */+ families: readonly string[];+ workflows: readonly AudioWorkflowId[];+ title: string;+ claims: readonly string[];+ /** Matches on more than the family, e.g. on audio_type for native runtimes. */+ appliesTo?: (ctx: AudioModelContext) => boolean;+ initial: (specs: AudioOptionSpec[]) => V;+ Component: ComponentType<AudioToolPanelProps<V>>;+ toRequest: (value: V) => AudioRunPatch;+ validate?: (+ value: V,+ core: CoreInputs,+ ctx: AudioModelContext,+ ) => string | null;+}++// biome-ignore lint/suspicious/noExplicitAny: each panel owns its value shape; the host only passes it through.+export type AnyAudioToolPanel = AudioToolPanel<any>;diff --git a/studio/frontend/src/features/audio/tour/steps.tsx b/studio/frontend/src/features/audio/tour/steps.tsxindex db969633a18..73294c1db45 100644--- a/studio/frontend/src/features/audio/tour/steps.tsx+++ b/studio/frontend/src/features/audio/tour/steps.tsx@@ -7,13 +7,13 @@ import type { AudioWorkflowId } from "../workflows";const modeStep: TourStep = {id: "mode",target: "audio-mode",- title: "Speak, Music or Transcribe",+ title: "Pick a page",body: (<>- Open the page title to switch pages. Speak turns text into speech, Music- makes songs and sound effects, and Transcribe turns a recording into text.- Each lists only the models that can do it, so the picker above follows the- page.+ Open the page title to switch pages. Speak turns text into speech, Clone+ speaks in the voice from a short recording, Music makes songs and sound+ effects, and Transcribe turns a recording into text. Each lists only the+ models that can do it, so the picker above follows the page.</>),};@@ -21,6 +21,8 @@ const modeStep: TourStep = {const MODEL_STEP_BODY: Record<AudioWorkflowId, string> = {speak:"Text-to-speech models, including voices you fine-tuned under On Device.",+ clone:+ "Models that can speak in the voice of a short recording you give them.",music: "Music models. Loading one replaces the model in the main slot.",transcribe:"Speech recognition models. They run beside your chat model, not in its place.",@@ -71,6 +73,42 @@ export function buildAudioTourSteps({];}+ if (workflow === "clone") {+ return [+ modeStep,+ modelStep(workflow),+ {+ id: "reference",+ target: "audio-clone-reference",+ title: "Reference clip",+ body: (+ <>+ Upload, record or pick a few seconds of the voice to copy. A saved+ voice works too.+ </>+ ),+ },+ {+ id: "transcript",+ target: "audio-clone-transcript",+ title: "What's said in the clip",+ body: (+ <>+ Some models need the clip's words to match its voice. Type them or+ press Transcribe.+ </>+ ),+ },+ {+ id: "text",+ target: "audio-clone-text",+ title: "Text to speak",+ body: <>What the cloned voice should say.</>,+ },+ outputStep,+ ];+ }+return [modeStep,modelStep(workflow),diff --git a/studio/frontend/src/features/audio/workflows.ts b/studio/frontend/src/features/audio/workflows.tsindex 01aabd3527f..c8607f4b59a 100644--- a/studio/frontend/src/features/audio/workflows.ts+++ b/studio/frontend/src/features/audio/workflows.ts@@ -7,11 +7,12 @@ import {AiVoiceIcon,MusicNote03Icon,SpeechToTextIcon,+ VoiceIdIcon,} from "@hugeicons/core-free-icons";import type { IconSvgElement } from "@hugeicons/react";import { AUDIO_CPP_MUSIC_AUDIO_TYPE } from "./audio-cpp-catalog";-export type AudioWorkflowId = "speak" | "music" | "transcribe";+export type AudioWorkflowId = "speak" | "clone" | "music" | "transcribe";export type AudioWorkflowSlot = "speak" | "transcribe";@@ -33,6 +34,15 @@ export const AUDIO_WORKFLOWS: ReadonlyArray<{slot: "speak",createTrain: true,},+ {+ id: "clone",+ label: "Clone",+ heading: "Clone a voice",+ icon: VoiceIdIcon,+ hint: "Speak in the voice from a short recording",+ slot: "speak",+ createTrain: true,+ },{id: "music",label: "Music",@@ -95,9 +105,47 @@ export function audioWorkflowForAudioType(export function clipWorkflow(clip: {workflow?: string | null;audio_type?: string | null;-}): "speak" | "music" {- if (clip.workflow === "speak" || clip.workflow === "music") {+}): "speak" | "clone" | "music" {+ if (+ clip.workflow === "speak" ||+ clip.workflow === "clone" ||+ clip.workflow === "music"+ ) {return clip.workflow;}return audioWorkflowForAudioType(clip.audio_type);}++export function workflowForLoadedModel({+ current,+ audioWorkflows,+ music,+}: {+ current: AudioWorkflowId;+ audioWorkflows: readonly string[] | null | undefined;+ music: boolean;+}): AudioWorkflowId {+ const runnable = (audioWorkflows ?? []).filter(+ (id): id is AudioWorkflowId =>+ isAudioWorkflowId(id) && slotForWorkflow(id) === "speak",+ );+ if (runnable.includes(current)) return current;+ if (runnable.length > 0) return runnable[0];+ return music ? "music" : "speak";+}++/** Older backends send no list: the audio type picks Music or Speak, and nothing clones. */+export function loadedModelRunsWorkflow({+ workflow,+ audioWorkflows,+ music,+}: {+ workflow: AudioWorkflowId;+ audioWorkflows: readonly string[] | null | undefined;+ music: boolean;+}): boolean {+ if (audioWorkflows && audioWorkflows.length > 0) {+ return audioWorkflows.includes(workflow);+ }+ return workflow === (music ? "music" : "speak");+}diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.tsindex a6491e5844e..1833086d2d4 100644--- a/studio/frontend/src/features/chat/types/api.ts+++ b/studio/frontend/src/features/chat/types/api.ts@@ -254,6 +254,7 @@ export interface LoadModelResponse {diffusion_requested_ngl?: number | null;is_audio?: boolean;audio_type?: string | null;+ audio_workflows?: string[] | null;has_audio_input?: boolean;has_video_input?: boolean;inference?: {@@ -378,6 +379,11 @@ export interface InferenceStatusResponse {/** The loaded GGUF audio model's generation options, as its spec declares them. Unknown-shaped* on purpose: the Audio page validates it with parseAudioOptions. */audio_options?: unknown;+ /** Audio page workflows the loaded model can run ("speak", "clone", "music", "transcribe"); empty when it is not an audio model. */+ audio_workflows?: string[] | null;+ audio_reference_text?: "required" | "optional" | "unused" | null;+ /** e.g. Maya1: "instruct" (its voice description). */+ audio_required_inputs?: string[] | null;has_audio_input?: boolean;has_video_input?: boolean;loading: string[];diff --git a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.tsindex 383867d2c1e..096dd9b80d2 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts+++ b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts@@ -186,7 +186,10 @@ const audioGgufGroups = (tasks: readonly AudioCppTask[]): CatalogGroup[] =>AUDIO_CPP_MODELS.filter((model) => tasks.includes(model.task)).map((model) => ({canonicalId: model.id,displayName: audioCppDisplayName(model.id),- description: AUDIO_GGUF_DESCRIPTIONS[model.task],+ description:+ model.workflows && !model.workflows.includes("speak")+ ? "Voice cloning"+ : AUDIO_GGUF_DESCRIPTIONS[model.task],scope: "audio",task: model.task === "asr" ? "stt" : "tts",artifacts: [gguf(model.id)],diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsxindex aa46132f570..97abf6d0b92 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx+++ b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx@@ -3822,6 +3822,8 @@ export function HubModelPicker({// Recommended suggests GGUF anywhere, plus MLX and safetensors on Mac; the "Fits on device"// tick also drops models too big for the device. Downloaded models stay visible.+ const hubRowAllowed = (r: HfModelResult) =>+ !rowFilter || rowFilter({ id: r.id, task: r.pipelineTag });const recommendedRows = useMemo(() => {const catalogSeedIds = new Set(catalogSeedRows.map((row) => row.id.toLowerCase()),@@ -3830,6 +3832,7 @@ export function HubModelPicker({const isCatalogSeed = catalogSeedIds.has(r.id.toLowerCase());return (!isMobileVariant(r.id) &&+ hubRowAllowed(r) &&taskPickerRowMatches({isCatalogSeed,isHidden: isHiddenModelId(r.id),@@ -3904,6 +3907,7 @@ export function HubModelPicker({.filter((r) => !deviceFiltered || fits(r));return [...unslothRows, ...communityRows];}, [+ rowFilter,budgetFraction,diffusionLoad,recommendedSearch.results,diff --git a/studio/frontend/tests/audio-clone-panels.test.ts b/studio/frontend/tests/audio-clone-panels.test.tsnew file mode 100644index 00000000000..a2f0b970f7c--- /dev/null+++ b/studio/frontend/tests/audio-clone-panels.test.ts@@ -0,0 +1,495 @@+// 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,+ chatterboxExpressivenessLogic,+ cosyVoiceModeLogic,+ emotionSourceProblem,+ f5SpeedDialectLogic,+ indexTts2EmotionLogic,+ qwen3TimbreLogic,+ speakVoiceLogic,+ vibeVoiceDialogueLogic,+} = 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"), []);+});++test("the saved-voice choice shows on Speak only for models that also clone", () => {+ 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" }),+ ),+ false,+ );+ assert.equal(+ panelApplies(+ speakVoiceLogic,+ "clone",+ ctx({ audioWorkflows: ["speak", "clone"] }),+ ),+ false,+ );+ assert.equal(+ panelApplies(+ vibeVoiceDialogueLogic,+ "speak",+ ctx({ audioFamily: "vibevoice" }),+ ),+ true,+ );+});++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("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,+ );+ // A replacement still uploading, a failed one, or an expired clip blocks the run.+ 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);+ // A failed replacement hides the kept clip, so it blocks until dismissed.+ 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", () => {+ assert.deepEqual(+ speakVoiceLogic.toRequest({ source: "saved", voiceId: "v1" }),+ {+ inputs: { reference: { voice_id: "v1" } },+ },+ );+ assert.deepEqual(+ speakVoiceLogic.toRequest({ source: "builtin", voiceId: "v1" }),+ {},+ );+ assert.equal(+ speakVoiceLogic.validate?.(+ { source: "saved", voiceId: 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" };+ 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);+ // Not loaded yet, or the list failed: nothing to compare against.+ assert.equal(check(null), 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(+ 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'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/);+});diff --git a/studio/frontend/tests/audio-clone-store.test.ts b/studio/frontend/tests/audio-clone-store.test.tsnew file mode 100644index 00000000000..5a4e1f00e2a--- /dev/null+++ b/studio/frontend/tests/audio-clone-store.test.ts@@ -0,0 +1,230 @@+// 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 { readFileSync } from "node:fs";+import test from "node:test";++import {+ installLocalStorageFake,+ readSrc,+ registerBundlerResolver,+} from "./helpers/kit.ts";++const { store } = installLocalStorageFake();+registerBundlerResolver();++const SAVED = {+ state: {+ reference: { kind: "voice", id: "v1", name: "Narrator", durationS: 6 },+ referenceText: "Hello there.",+ text: "Read this.",+ language: "English",+ toolValues: { "m:clone:qwen3-timbre": { timbreOnly: true } },+ },+ version: 1,+};+const KEY = "unsloth_audio_clone_v1";+store.set(KEY, JSON.stringify(SAVED));++const { useAudioCloneStore } = await import(+ "../src/features/audio/stores/audio-clone-store.ts"+);+const { toolValueKey } = await import("../src/features/audio/tools/select.ts");++test("the draft comes back after a reload", () => {+ const state = useAudioCloneStore.getState();+ assert.deepEqual(state.reference, SAVED.state.reference);+ assert.equal(state.referenceText, "Hello there.");+ assert.equal(state.text, "Read this.");+ assert.equal(state.language, "English");+ assert.deepEqual(state.toolValues["m:clone:qwen3-timbre"], {+ timbreOnly: true,+ });+});++test("edits are written through, actions are not", () => {+ const state = useAudioCloneStore.getState();+ state.setText("New line.");+ state.setReference({+ kind: "input",+ id: "abc",+ name: "take.webm",+ durationS: 4,+ expiresAt: "2026-10-04T00:00:00Z",+ });+ const saved = JSON.parse(store.get(KEY) ?? "{}");+ assert.equal(saved.state.text, "New line.");+ assert.equal(saved.state.reference.id, "abc");+ assert.deepEqual(Object.keys(saved.state).sort(), [+ "language",+ "reference",+ "referenceText",+ "text",+ "toolValues",+ ]);+});++test("tool values are kept per model, page and panel", () => {+ const state = useAudioCloneStore.getState();+ state.setToolValue(toolValueKey("a/one", "clone", "index-emotion"), {+ mode: "mixer",+ });+ state.setToolValue(toolValueKey("b/two", "clone", "index-emotion"), {+ mode: "text",+ });+ state.setToolValue(toolValueKey("a/one", "speak", "speak-voice"), {+ source: "saved",+ voiceId: "v",+ });+ const values = useAudioCloneStore.getState().toolValues;+ assert.deepEqual(values["a/one:clone:index-emotion"], { mode: "mixer" });+ assert.deepEqual(values["b/two:clone:index-emotion"], { mode: "text" });+ assert.deepEqual(values["a/one:speak:speak-voice"], {+ source: "saved",+ voiceId: "v",+ });+});++test("tool values stay bounded, oldest first", () => {+ const state = useAudioCloneStore.getState();+ for (let i = 0; i < 260; i += 1) state.setToolValue(`m${i}:clone:p`, i);+ const keys = Object.keys(useAudioCloneStore.getState().toolValues);+ assert.equal(keys.length, 200);+ assert.equal(keys.at(-1), "m259:clone:p");+ assert.ok(!keys.includes("m0:clone:p"));+});++test("a transcript lands only on the clip it was made from, and stays with it", () => {+ const state = useAudioCloneStore.getState();+ const a = { kind: "input" as const, id: "a", name: "a.wav", durationS: 3 };+ const b = { kind: "input" as const, id: "b", name: "b.wav", durationS: 3 };+ state.setReference(a);+ state.setReferenceText("");+ useAudioCloneStore.getState().applyTranscript(b, "stale words");+ assert.equal(useAudioCloneStore.getState().referenceText, "");+ useAudioCloneStore.getState().applyTranscript(a, "clip a words");+ const after = useAudioCloneStore.getState();+ assert.equal(after.referenceText, "clip a words");+ assert.equal(after.reference?.transcript, "clip a words");+});++test("removing a clip drops its transcript but keeps typed words", () => {+ const a = {+ kind: "input" as const,+ id: "a2",+ name: "a.wav",+ durationS: 3,+ transcript: "clip a words",+ };+ const b = {+ kind: "input" as const,+ id: "b2",+ name: "b.wav",+ durationS: 3,+ transcript: "clip b words",+ };+ const store = () => useAudioCloneStore.getState();+ store().setReferenceText("");+ store().adoptReference(a);+ assert.equal(store().referenceText, "clip a words");+ store().adoptReference(null);+ store().adoptReference(b);+ assert.equal(store().referenceText, "clip b words");+ store().setReferenceText("my own words");+ store().adoptReference(null);+ store().adoptReference(a);+ assert.equal(store().referenceText, "my own words");+});++test("Add it again under Generate drops the expired clip's transcript too", () => {+ const a = {+ kind: "input" as const,+ id: "a3",+ name: "a.wav",+ durationS: 3,+ transcript: null,+ };+ const b = {+ kind: "input" as const,+ id: "b3",+ name: "b.wav",+ durationS: 3,+ transcript: null,+ };+ const store = () => useAudioCloneStore.getState();+ store().setReferenceText("");+ store().adoptReference(a);+ store().applyTranscript(a, "clip a words");+ // What the reference-expired action does before opening the file picker.+ const generation = readFileSync(+ new URL(+ "../src/features/audio/hooks/use-clone-generation.ts",+ import.meta.url,+ ),+ "utf8",+ );+ const action = generation.slice(generation.indexOf('"reference-expired": ['));+ assert.match(+ action.slice(0, 400),+ /getState\(\)\.adoptReference\(null\);\s*referenceHandle\.current\?\.browse\(\);/,+ );+ store().adoptReference(null);+ store().adoptReference(b);+ assert.equal(store().referenceText, "");+});++test("a failed voice deletion puts back only that voice", () => {+ const src = readSrc("features/audio/stores/audio-voices-store.ts");+ const body = src.slice(src.indexOf("remove: async (id) => {"));+ const handler = body.slice(0, body.indexOf("\n },"));+ assert.doesNotMatch(handler, /set\(\{ voices: before \}\)/);+ assert.match(handler, /voices\.splice\(Math\.min\(index, voices\.length\), 0, failed\)/);+});++test("a failed voice rename puts back only that voice", () => {+ const src = readSrc("features/audio/stores/audio-voices-store.ts");+ const body = src.slice(src.indexOf("rename: async (id, patch) => {"));+ const handler = body.slice(0, body.indexOf("\n },"));+ assert.doesNotMatch(handler, /set\(\{ voices: before \}\)/);+ assert.match(handler, /voice\.id === id \? previous : voice/);+});++test("voice previews are bounded, stale ones dropped, and the menu follows disabled", () => {+ const src = readSrc("features/audio/components/voice-picker.tsx");+ assert.match(src, /const voiceUrls = new BlobUrlCache\(/);+ assert.match(src, /voiceUrls\.prune\(\[voice\.id\]\)/);+ assert.match(src, /if \(request !== previewRequest\.current\) return;\s*audio\.src = url;/);+ assert.match(src, /await remove\(voice\.id\);\s*voiceUrls\.delete\(voice\.id\);/);+ assert.match(src, /aria-label=\{`More for \$\{voice\.name\}`\}\s*disabled=\{disabled\}/);+});++test("a voice list fetched across a save, rename or delete is fetched again", () => {+ const src = readSrc("features/audio/stores/audio-voices-store.ts");+ assert.match(src, /const started = mutations;[\s\S]*?if \(started !== mutations\) \{\s*set\(\{ loading: false \}\);\s*return get\(\)\.refresh\(\);/);+ for (const call of ["createVoice\\(request\\)", "updateVoice\\(id, patch\\)", "deleteVoice\\(id\\)"]) {+ assert.match(src, new RegExp(`await ${call};\\s*mutations \\+= 1;`), call);+ }+});++test("a reference longer than the 30 s cut brings no transcript, since only 30 s is sent", () => {+ const store = () => useAudioCloneStore.getState();+ store().adoptReference(null);+ store().setReferenceText("");+ store().adoptReference({+ kind: "clip" as const,+ id: "long",+ name: "A long story.",+ durationS: 45,+ transcript: "A long story.",+ });+ assert.equal(store().referenceText, "");+ store().adoptReference({+ kind: "clip" as const,+ id: "short",+ name: "Hi.",+ durationS: 4,+ transcript: "Hi.",+ });+ assert.equal(store().referenceText, "Hi.");+});diff --git a/studio/frontend/tests/audio-cpp-catalog.test.ts b/studio/frontend/tests/audio-cpp-catalog.test.tsindex 8b5325c6c38..2523a8a420b 100644--- a/studio/frontend/tests/audio-cpp-catalog.test.ts+++ b/studio/frontend/tests/audio-cpp-catalog.test.ts@@ -524,6 +524,7 @@ test("recommended speech and music picks are refused when the runtime cannot runtest("the capability line names GGUF audio and music, never the runtime's internal type", () => {assert.equal(audioCapabilityLine("tts", "audiocpp_tts"), "Text-to-speech · GGUF");assert.equal(audioCapabilityLine("music", "audiocpp_music"), "Music generation · GGUF");+ assert.equal(audioCapabilityLine("clone", "audiocpp_tts"), "Voice cloning · GGUF");assert.equal(audioCapabilityLine("tts", "higgs_tts2"), "Text-to-speech · higgs_tts2");assert.equal(audioCapabilityLine("stt", "ready"), "Speech-to-text · ready");});diff --git a/studio/frontend/tests/audio-handoff-intent.test.ts b/studio/frontend/tests/audio-handoff-intent.test.tsindex 2d6a55438f9..a88f7574f93 100644--- a/studio/frontend/tests/audio-handoff-intent.test.ts+++ b/studio/frontend/tests/audio-handoff-intent.test.ts@@ -24,7 +24,7 @@ test("unknown tasks, workflows and audio types are dropped", () => {assert.deepEqual(validateAudioSearch({task: "text-to-image",- workflow: "clone",+ workflow: "separate",audioType: "not-a-type",loadId: " ",}),@@ -53,7 +53,7 @@ test("the params the route accepted before pass through unchanged", () => {});test("a workflow param is kept when it names a workflow", () => {- for (const workflow of ["speak", "music", "transcribe"]) {+ for (const workflow of ["speak", "clone", "music", "transcribe"]) {assert.deepEqual(validateAudioSearch({ workflow }), { workflow });}});@@ -108,6 +108,10 @@ test("a chat pick opens on the workflow its model runs in", () => {"music",);assert.equal(audioWorkflowForPick({ id: "x/y", task: null }), null);+ const clone = (folder: string) =>+ audioWorkflowForPick({ id: `audio-cpp/audio.cpp-gguf/${folder}`, task: "text-to-speech" });+ assert.equal(clone("Qwen3-TTS-12Hz-0.6B-Base-GGUF"), "clone");+ assert.equal(clone("VoxCPM2-GGUF"), "speak");});test("the route validates through the shared helper", () => {@@ -159,3 +163,14 @@ test("a model deep link without a workflow opens the page its task names before"music",);});++test("a chat pick of an uncatalogued clone-only family opens Clone", () => {+ assert.equal(+ audioWorkflowForPick({ id: "x/MioTTS-GGUF", task: "text-to-speech" }),+ "clone",+ );+ assert.equal(+ audioWorkflowForPick({ id: "x/Kokoro-82M-GGUF", task: "text-to-speech" }),+ "speak",+ );+});diff --git a/studio/frontend/tests/audio-instructions-field.test.ts b/studio/frontend/tests/audio-instructions-field.test.tsdeleted file mode 100644index 1b0836ca6c9..00000000000--- a/studio/frontend/tests/audio-instructions-field.test.ts+++ /dev/null@@ -1,32 +0,0 @@-// 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 { readSrc, registerBundlerResolver } from "./helpers/kit.ts";--registerBundlerResolver();-const { instructionsFieldKind } = await import("../src/features/audio/audio-page-policy.ts");--const fields = readSrc("features/audio/components/instructions-fields.tsx");-const host = readSrc("features/audio/audio-page.tsx");--test("a model gets the instruction field it always got, on its own page", () => {- assert.equal(instructionsFieldKind("speak", "audiocpp_tts"), "voice");- assert.equal(instructionsFieldKind("speak", "higgs_tts2"), "scene");- assert.equal(instructionsFieldKind("speak", "moss_tts_local"), "style");- assert.equal(instructionsFieldKind("music", "minimax_music3"), "music");- assert.equal(instructionsFieldKind("speak", "snac"), null);- assert.equal(instructionsFieldKind("speak", "csm"), null);- assert.equal(instructionsFieldKind("speak", "audiocpp_music"), null);-});--test("the fields keep the rail's exact copy", () => {- assert.match(fields, /\? "Scene description"/);- assert.match(fields, /"Voice or style description"/);- assert.match(fields, /instructionsKind === "music"\s*\? musicNeedsDescription/);- assert.match(fields, /id="audio-instructions"/);- assert.match(fields, /id="audio-language"/);- assert.match(host, /instructionsKind === "style" \? \(\s*<MossLanguageField/);-});diff --git a/studio/frontend/tests/audio-model-eject.test.ts b/studio/frontend/tests/audio-model-eject.test.tsindex 6238c7cf593..e04823547f2 100644--- a/studio/frontend/tests/audio-model-eject.test.ts+++ b/studio/frontend/tests/audio-model-eject.test.ts@@ -13,12 +13,12 @@ const adapterSource = readSrc("features/chat/adapters/studio-model-dictation-adatest("Audio exposes the shared picker eject action only while idle", () => {assert.match(source,- /onEject=\{busy === null && selectorValue \? handleEject : undefined\}/,+ /onEject=\{\s*busy === null && selectorValue && !showLastPageModel\s*\? handleEject\s*: undefined\s*\}/,);assert.match(source, /if \(busy !== null \|\| isRecording\)/);assert.match(source,- /loaded=\{mode === "transcribe" \? sttReady : undefined\}/,+ /loaded=\{\s*mode === "transcribe"\s*\? sttReady\s*: showLastPageModel\s*\? false\s*: undefined\s*\}/,);});diff --git a/studio/frontend/tests/audio-picker-filter.test.ts b/studio/frontend/tests/audio-picker-filter.test.tsindex 422af0fca47..52737cbeb3b 100644--- a/studio/frontend/tests/audio-picker-filter.test.ts+++ b/studio/frontend/tests/audio-picker-filter.test.ts@@ -14,8 +14,12 @@ const { audioModelsForTask, isMusicGenerationModel } = await import("../src/features/audio/catalog.ts");-type Workflow = "speak" | "music" | "transcribe";-const WORKFLOWS: Workflow[] = ["speak", "music", "transcribe"];+const { audioCppModelSpeaks } = await import(+ "../src/features/audio/audio-cpp-catalog.ts"+);++type Workflow = "speak" | "clone" | "music" | "transcribe";+const WORKFLOWS: Workflow[] = ["speak", "clone", "music", "transcribe"];function workflowsFor(row: Parameters<typeof audioRowMatchesWorkflow>[0]) {return WORKFLOWS.filter((workflow) => audioRowMatchesWorkflow(row, workflow));@@ -47,6 +51,48 @@ test("a speech row lists only on Speak", () => {);});+test("a clone-only speech model lists only on Clone", () => {+ assert.deepEqual(+ workflowsFor({+ id: "audio-cpp/audio.cpp-gguf/Chatterbox-GGUF",+ task: "text-to-speech",+ audioWorkflows: ["clone"],+ }),+ ["clone"],+ );+ assert.deepEqual(+ workflowsFor({+ id: "audio-cpp/audio.cpp-gguf/Qwen3-TTS-12Hz-0.6B-Base-GGUF",+ task: "text-to-speech",+ audioType: "audiocpp_tts",+ }),+ ["clone"],+ );+ assert.deepEqual(+ workflowsFor({+ id: "audio-cpp/audio.cpp-gguf/VoxCPM2-GGUF",+ task: "text-to-speech",+ }),+ ["speak", "clone"],+ );+});++test("Speak's catalog rows leave out the clone-only models", () => {+ const speakIds = audioModelsForTask("tts")+ .map((model) => model.id)+ .filter((id) => audioCppModelSpeaks(id));+ assert.ok(speakIds.includes("audio-cpp/audio.cpp-gguf/VoxCPM2-GGUF"));+ assert.ok(speakIds.includes("audio-cpp/audio.cpp-gguf/Kokoro-82M-GGUF"));+ for (const cloneOnly of [+ "audio-cpp/audio.cpp-gguf/Chatterbox-GGUF",+ "audio-cpp/audio.cpp-gguf/Qwen3-TTS-12Hz-0.6B-Base-GGUF",+ "audio-cpp/audio.cpp-gguf/IndexTTS2-GGUF",+ "audio-cpp/audio.cpp-gguf/CosyVoice3-GGUF",+ ]) {+ assert.ok(!speakIds.includes(cloneOnly), cloneOnly);+ }+});+test("a music GGUF (text-to-audio, no audio type) lists only on Music", () => {assert.deepEqual(workflowsFor({@@ -130,6 +176,8 @@ test("typed Hub search results are scoped to the page too", () => {const block = body.slice(0, body.indexOf("\n ],") + 1);assert.match(block, /\.filter\(\(r\) => !rowFilter \|\| rowFilter\(\{ id: r\.id, task: r\.pipelineTag \}\)\)/);assert.match(block, /\n\s+rowFilter,\n/);+ const recommended = pickers.slice(pickers.indexOf("const keepCommon = "));+ assert.match(recommended.slice(0, 400), /hubRowAllowed\(r\) &&/);});test("a Hub music model tagged text-to-speech stays on Music", () => {@@ -138,3 +186,52 @@ test("a Hub music model tagged text-to-speech stays on Music", () => {assert.equal(audioRowMatchesWorkflow(row, "music"), true);assert.equal(audioRowMatchesWorkflow({ id: "hexgrad/Kokoro-82M", task: "text-to-speech" }, "speak"), true);});++test("Hub search rows for clone-only families outside the catalog list on Clone, not Speak", () => {+ for (const id of [+ "audio-cpp/audio.cpp-gguf/MioTTS-GGUF",+ "audio-cpp/audio.cpp-gguf/Vevo2-GGUF",+ "audio-cpp/audio.cpp-gguf/FireRedTTS3-Base-GGUF",+ "audio-cpp/audio.cpp-gguf/IndexTTS2.5-GGUF",+ ]) {+ const row = { id, task: "text-to-speech" };+ assert.equal(audioRowMatchesWorkflow(row, "clone"), true, id);+ assert.equal(audioRowMatchesWorkflow(row, "speak"), false, id);+ }+ // Backend workflows still win once the row is downloaded.+ assert.equal(+ audioRowMatchesWorkflow(+ { id: "x/MioTTS-GGUF", task: "text-to-speech", audioWorkflows: ["speak"] },+ "speak",+ ),+ true,+ );+});++test("the clone-only name hint follows the backend's speaks=False families", async () => {+ const { isCloneOnlyFamilyId } = await import(+ "../src/features/audio/audio-cpp-catalog.ts"+ );+ for (const id of [+ "ResembleAI/chatterbox",+ "someone/F5-TTS-GGUF",+ "x/Echo-TTS-GGUF",+ "x/Qwen3-TTS-12Hz-1.7B-Base-GGUF",+ ]) {+ assert.equal(isCloneOnlyFamilyId(id), true, id);+ }+ for (const id of [+ "audio-cpp/audio.cpp-gguf/Chatterbox-Turbo-GGUF",+ "x/Qwen3-TTS-12Hz-1.7B-CustomVoice-GGUF",+ "x/Kokoro-82M-GGUF",+ ]) {+ assert.equal(isCloneOnlyFamilyId(id), false, id);+ }+});++test("a Fish Audio Hub row lists on both Speak and Clone before download", () => {+ const row = { id: "fishaudio/fish-speech-1.5-GGUF", task: "text-to-speech" };+ assert.equal(audioRowMatchesWorkflow(row, "speak"), true);+ assert.equal(audioRowMatchesWorkflow(row, "clone"), true);+ assert.equal(audioRowMatchesWorkflow(row, "music"), false);+});diff --git a/studio/frontend/tests/audio-run-api.test.ts b/studio/frontend/tests/audio-run-api.test.tsnew file mode 100644index 00000000000..07bd3e620eb--- /dev/null+++ b/studio/frontend/tests/audio-run-api.test.ts@@ -0,0 +1,142 @@+// 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 { readSrc } from "./helpers/kit.ts";++const {+ buildAudioRunBody,+ buildVoiceCreateBody,+ sourceFileUrl,+ sourceRefOf,+ transcribeUrl,+} = await import("../src/features/audio/audio-run-request.ts");++const api = readSrc("features/audio/api.ts");++const PATHLIKE = /"(path|voice_ref|file|url|audio_path)"\s*:/;++test("a clone run sends ids only, with the contract's keys", () => {+ const body = buildAudioRunBody({+ workflow: "clone",+ text: "Hello",+ language: "English",+ instructions: " ",+ inputs: {+ reference: { input_id: "a".repeat(32) },+ reference_text: " Okay, I'm Cemo. ",+ emotion: { clip_id: "c1" },+ },+ options: { x_vector_only_mode: true, bad: Number.NaN },+ speed: 1.3,+ seed: 7,+ });+ assert.deepEqual(body, {+ workflow: "clone",+ text: "Hello",+ language: "English",+ inputs: {+ reference: { input_id: "a".repeat(32) },+ reference_text: "Okay, I'm Cemo.",+ emotion: { clip_id: "c1" },+ },+ options: { x_vector_only_mode: true },+ speed: 1.3,+ seed: 7,+ });+ assert.doesNotMatch(JSON.stringify(body), PATHLIKE);+});++test("a cleared transcript is sent blank, an omitted one is left out", () => {+ const cleared = buildAudioRunBody({+ workflow: "clone",+ text: "Hi",+ inputs: { reference: { voice_id: "v1" }, reference_text: " " },+ });+ assert.deepEqual(cleared.inputs, {+ reference: { voice_id: "v1" },+ reference_text: "",+ });+ const omitted = buildAudioRunBody({+ workflow: "clone",+ text: "Hi",+ inputs: { reference: { voice_id: "v1" }, reference_text: null },+ });+ assert.deepEqual(omitted.inputs, { reference: { voice_id: "v1" } });+});++test("whatever a caller spreads in, no path or bytes reach the body", () => {+ const sneaky = {+ workflow: "speak" as const,+ text: "Hi",+ path: "/etc/passwd",+ voice_ref: "/abs/ref.wav",+ inputs: {+ reference: { voice_id: "v1", path: "/x.wav", url: "/y" } as never,+ emotion: { input_id: "i", clip_id: "c" } as never,+ },+ };+ const body = buildAudioRunBody(sneaky);+ assert.deepEqual(body, {+ workflow: "speak",+ text: "Hi",+ inputs: { reference: { voice_id: "v1" } },+ });+ assert.doesNotMatch(JSON.stringify(body), PATHLIKE);+});++test("selections become one-id refs and server URLs", () => {+ assert.deepEqual(+ sourceRefOf({ kind: "input", id: "i1", name: "a", durationS: 1 }),+ { input_id: "i1" },+ );+ assert.deepEqual(+ sourceRefOf({ kind: "clip", id: "c1", name: "a", durationS: 1 }),+ { clip_id: "c1" },+ );+ assert.deepEqual(+ sourceRefOf({ kind: "voice", id: "v1", name: "a", durationS: 1 }),+ { voice_id: "v1" },+ );+ assert.equal(+ sourceFileUrl({ kind: "input", id: "i1", name: "", durationS: null }),+ "/api/inference/audio/inputs/i1/file",+ );+ assert.equal(+ sourceFileUrl({ kind: "voice", id: "v1", name: "", durationS: null }),+ "/api/inference/audio/voices/v1/file",+ );+ assert.equal(+ transcribeUrl({ input_id: "i1" }),+ "/api/inference/audio/inputs/i1/transcribe",+ );+ assert.match(transcribeUrl({ clip_id: "c 1" }), /\?clip_id=c%201$/);+});++test("a saved voice is made from an upload or a clip, within the limits", () => {+ const body = buildVoiceCreateBody({+ source: { clip_id: "c1" },+ name: ` ${"n".repeat(100)} `,+ transcript: "",+ language: "English",+ });+ assert.deepEqual(body, {+ source: { clip_id: "c1" },+ name: "n".repeat(80),+ language: "English",+ });+ assert.throws(() =>+ buildVoiceCreateBody({ source: { voice_id: "v" }, name: "x" }),+ );+});++test("api.ts sends run and voice bodies only through the builders", () => {+ assert.match(api, /body: JSON\.stringify\(buildAudioRunBody\(request\)\)/);+ assert.match(api, /body: JSON\.stringify\(buildVoiceCreateBody\(request\)\)/);+ assert.match(api, /"\/api\/inference\/audio\/run"/);+ assert.match(api, /xhr\.send\(blob\)/);+ assert.match(api, /body: blob,/);+ assert.doesNotMatch(api, /voice_ref/);+});diff --git a/studio/frontend/tests/audio-source-input.test.ts b/studio/frontend/tests/audio-source-input.test.tsnew file mode 100644index 00000000000..3d33e920386--- /dev/null+++ b/studio/frontend/tests/audio-source-input.test.ts@@ -0,0 +1,310 @@+// 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 { readSrc, registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();+const {+ audioFileProblem,+ audioSourceReducer,+ INITIAL_AUDIO_SOURCE_STATE,+ REFERENCE_EXPIRED_MESSAGE,+} = await import("../src/features/audio/hooks/audio-source-state.ts");+const { AUDIO_INPUT_MAX_BYTES, selectionExpired } = await import(+ "../src/features/audio/audio-run-request.ts"+);++const card = readSrc("features/audio/components/audio-source-input.tsx");+const hook = readSrc("features/audio/hooks/use-audio-source.ts");++test("a picked file uploads with progress, draws at once, then is ready", () => {+ let state = audioSourceReducer(INITIAL_AUDIO_SOURCE_STATE, {+ type: "upload-start",+ name: "voice.wav",+ key: "local:1",+ });+ assert.deepEqual(state.status, {+ phase: "uploading",+ name: "voice.wav",+ progress: 0,+ });+ state = audioSourceReducer(state, {+ type: "preview",+ key: "local:1",+ peaks: [0.2, 1],+ durationS: 4.7,+ url: "blob:x",+ });+ assert.equal(state.status.phase, "uploading");+ assert.equal(state.preview.durationS, 4.7);+ state = audioSourceReducer(state, { type: "upload-progress", progress: 0.4 });+ assert.deepEqual(state.status, {+ phase: "uploading",+ name: "voice.wav",+ progress: 0.4,+ });+ state = audioSourceReducer(state, { type: "upload-progress", progress: 7 });+ assert.equal(state.status.phase === "uploading" && state.status.progress, 1);+ state = audioSourceReducer(state, { type: "upload-done", key: "input:abc" });+ assert.equal(state.status.phase, "ready");+ assert.equal(state.preview.key, "input:abc");+ assert.deepEqual(state.preview.peaks, [0.2, 1]);+});++test("a local decode that finishes after a fast upload still draws the card", () => {+ let state = audioSourceReducer(INITIAL_AUDIO_SOURCE_STATE, {+ type: "upload-start",+ name: "voice.wav",+ key: "local:1",+ });+ state = audioSourceReducer(state, { type: "upload-done", key: "input:abc" });+ state = audioSourceReducer(state, {+ type: "preview",+ key: "local:1",+ peaks: [0.5, 1],+ durationS: 4.7,+ url: "blob:x",+ });+ assert.equal(state.preview.key, "input:abc");+ assert.deepEqual(state.preview.peaks, [0.5, 1]);+ assert.equal(state.preview.durationS, 4.7);+ state = audioSourceReducer(state, { type: "load-start", key: "voice:v1" });+ state = audioSourceReducer(state, {+ type: "preview",+ key: "local:1",+ peaks: [0.1],+ durationS: 1,+ url: "blob:y",+ });+ assert.equal(state.preview.key, "voice:v1");+ assert.equal(state.preview.peaks, null);+});++test("a slow decode of an earlier pick does not draw on the next one", () => {+ let state = audioSourceReducer(INITIAL_AUDIO_SOURCE_STATE, {+ type: "upload-start",+ name: "first.wav",+ key: "local:1",+ });+ state = audioSourceReducer(state, { type: "upload-done", key: "input:a" });+ state = audioSourceReducer(state, {+ type: "upload-start",+ name: "second.wav",+ key: "local:2",+ });+ state = audioSourceReducer(state, {+ type: "preview",+ key: "local:1",+ peaks: [0.9],+ durationS: 9,+ url: "blob:first",+ });+ assert.equal(state.preview.key, "local:2");+ assert.equal(state.preview.peaks, null);+ assert.equal(state.preview.url, null);+});++test("a failed upload shows its reason; an expired one says so", () => {+ const uploading = audioSourceReducer(INITIAL_AUDIO_SOURCE_STATE, {+ type: "upload-start",+ name: "a.mp3",+ key: "local:1",+ });+ assert.deepEqual(+ audioSourceReducer(uploading, {+ type: "fail",+ message: "Audio is too large.",+ }).status,+ {+ phase: "error",+ message: "Audio is too large.",+ },+ );+ const expired = audioSourceReducer(uploading, { type: "expire" });+ assert.equal(expired.status.phase, "expired");+ assert.equal(+ REFERENCE_EXPIRED_MESSAGE,+ "This reference expired. Add it again.",+ );+ assert.match(card, /REFERENCE_EXPIRED_MESSAGE/);+ assert.match(card, /Add it again/);+ assert.match(card, /Try another file/);+});++test("a decode that lands after the card moved on draws nothing", () => {+ const loading = audioSourceReducer(INITIAL_AUDIO_SOURCE_STATE, {+ type: "load-start",+ key: "clip:1",+ });+ const stale = audioSourceReducer(loading, {+ type: "preview",+ key: "clip:0",+ peaks: [1],+ durationS: 1,+ url: "blob:old",+ });+ assert.equal(stale, loading);+});++test("recording starts and stops back to the empty card", () => {+ const recording = audioSourceReducer(INITIAL_AUDIO_SOURCE_STATE, {+ type: "record-start",+ now: 5,+ });+ assert.deepEqual(recording.status, { phase: "recording", startedAt: 5 });+ assert.equal(+ audioSourceReducer(recording, { type: "record-stop" }).status.phase,+ "idle",+ );+ assert.match(hook, /createAudioRecorder\(stream\)/);+});++test("a too-large or empty file is refused before any upload, at the server's 200 MiB", () => {+ assert.equal(AUDIO_INPUT_MAX_BYTES, 200 * 1024 * 1024);+ assert.equal(+ audioFileProblem({ size: AUDIO_INPUT_MAX_BYTES, type: "audio/wav" }),+ null,+ );+ assert.equal(+ audioFileProblem({ size: AUDIO_INPUT_MAX_BYTES + 1, type: "audio/wav" }),+ "Audio is too large. Keep it under 200 MB.",+ );+ assert.equal(+ audioFileProblem({ size: 0, type: "audio/wav" }),+ "This file is empty.",+ );+ assert.match(+ audioFileProblem({ size: 10, type: "image/png", name: "a.png" }) ?? "",+ /not an audio file/,+ );+ assert.equal(+ audioFileProblem({ size: 10, type: "", name: "take.m4a" }),+ null,+ );+ assert.ok(+ hook.indexOf("audioFileProblem(") < hook.indexOf("uploadAudioInput(file"),+ );+});++test("an upload past its keep-until time is expired", () => {+ const reference = {+ kind: "input" as const,+ id: "i",+ name: "a",+ durationS: 1,+ expiresAt: "2026-10-01T00:00:00Z",+ };+ assert.equal(+ selectionExpired(reference, Date.parse("2026-10-02T00:00:00Z")),+ true,+ );+ assert.equal(+ selectionExpired(reference, Date.parse("2026-09-30T00:00:00Z")),+ false,+ );+ assert.equal(+ selectionExpired(+ { ...reference, kind: "voice" },+ Date.parse("2027-01-01T00:00:00Z"),+ ),+ false,+ );+});++test("the whole card is the drop target, with every way in", () => {+ const section = card.slice(card.indexOf("<section"), card.indexOf("<input"));+ assert.match(section, /onDragOver=/);+ assert.match(section, /onDrop=/);+ assert.match(section, /nativeDropRef\(element\)/);+ assert.match(card, /type="file"/);+ for (const tab of ["Upload", "Record", "From history", "Saved voice"]) {+ assert.ok(card.includes(`label: "${tab}"`), tab);+ }+ assert.match(+ card,+ /corner-squircle grid gap-3 rounded-4xl bg-card p-4 ring-1/,+ );+ assert.doesNotMatch(card, /shadow-/);+ assert.ok(+ hook.indexOf('void drawBlob("local", file)') <+ hook.indexOf("await uploadAudioInput("),+ );+ assert.match(hook, /await decodePeaks\(blob\)/);+});++test("a superseded microphone request releases its stream", () => {+ const hook = readSrc("features/audio/hooks/use-audio-source.ts");+ assert.match(+ hook,+ /if \(recorderRef\.current \|\| acquiring\.current\) return;/,+ );+ assert.match(+ hook,+ /if \(ticket !== acquisition\.current \|\| !activeRef\.current\) \{\s*for \(const track of stream\.getTracks\(\)\) track\.stop\(\);/,+ );+ // Leaving the Audio page ends a recording.+ assert.match(+ hook,+ /activeRef\.current = active;\s*if \(!active\) stopRecording\(\);/,+ );+ assert.match(card, /useAudioSource\(\{ value, onChange, maxRecordSeconds, active \}\)/);+ assert.match(+ hook,+ /const abortAll = useCallback\(\(\) => \{\s*acquisition\.current \+= 1;/,+ );+});++test("the chooser accepts MP4 like the drop check does", () => {+ const input = readSrc("features/audio/components/audio-source-input.tsx");+ assert.match(input, /const AUDIO_EXTS = "[^"]*\bmp4\b/);+});++test("picking a new source clears an earlier error", () => {+ const hook = readSrc("features/audio/hooks/use-audio-source.ts");+ assert.match(+ hook,+ /seenKey\.current = valueKey;\s*if \(valueKey && \(phase === "error" \|\| phase === "expired"\)\) \{\s*dispatch\(\{ type: "reset" \}\);\s*\}/,+ );+});++test("a long history prompt or voice name truncates and keeps the duration visible", () => {+ // Grid items default to min-width: auto; without a minmax(0, 1fr) column one long prompt+ // made its row thousands of pixels wide and pushed the duration off the card.+ const historyList = card.slice(card.indexOf('tab === "history"'));+ assert.match(historyList, /<ul className="[^"]*\bmin-w-0\b[^"]*grid-cols-\[minmax\(0,1fr\)\]/);+ assert.match(historyList, /<li key=\{clip\.id\} className="min-w-0">/);+ assert.match(historyList, /"min-w-0 flex-1 truncate"/);+ assert.match(historyList, /"shrink-0 font-mono[^"]*"/);+ const voices = readSrc("features/audio/components/voice-picker.tsx");+ assert.match(voices, /<ul className="[^"]*\bmin-w-0\b[^"]*grid-cols-\[minmax\(0,1fr\)\]/);+ assert.match(voices, /"group flex min-w-0 items-center/);+});++test("a saved voice cannot take a name another voice already has", () => {+ const dialog = readSrc("features/audio/components/save-voice-dialog.tsx");+ // Case-insensitive, and the voice being edited may keep its own name.+ assert.match(+ dialog,+ /voice\.id !== voiceId &&\s*voice\.name\.trim\(\)\.toLowerCase\(\) === clean\.toLowerCase\(\)/,+ );+ assert.match(dialog, /disabled=\{!clean \|\| taken \|\| saving\}/);+ assert.match(dialog, /You already have a voice named \{clean\}/);+ const picker = readSrc("features/audio/components/voice-picker.tsx");+ assert.match(picker, /mode="edit"\s*voiceId=\{editing\?\.id\}/);+});++test("a deleted clip or voice keeps the card in error, which holds Clone's Generate", () => {+ // A 404 for a history clip or saved voice fails the card instead of marking it loaded, and the+ // card refetches (and fails again) after Dismiss while the stale selection stays.+ assert.match(hook, /"This saved voice was deleted\. Pick another one\."/);+ assert.match(hook, /"This clip was deleted\. Pick another one\."/);+ const generation = readSrc("features/audio/hooks/use-clone-generation.ts");+ assert.match(+ generation,+ /referenceError:\s*referenceStatus\.phase === "error" \? referenceStatus\.message : null/,+ );+ assert.match(generation, /"reference-error": \[addReference\]/);+});diff --git a/studio/frontend/tests/audio-tool-panels.test.ts b/studio/frontend/tests/audio-tool-panels.test.tsnew file mode 100644index 00000000000..aab098e61aa--- /dev/null+++ b/studio/frontend/tests/audio-tool-panels.test.ts@@ -0,0 +1,144 @@+// 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 type { AudioWorkflowId } from "../src/features/audio/workflows.ts";+import { readSrc, registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();+const { claimedOptionNames, instructionsKindFor, panelApplies } = await import(+ "../src/features/audio/tools/select.ts"+);++const registry = readSrc("features/audio/tools/registry.tsx");+const panels = readSrc("features/audio/components/instructions-fields.tsx");++const ctx = (+ overrides: Partial<AudioModelContext> = {},+): AudioModelContext => ({+ audioType: null,+ audioFamily: null,+ musicGeneration: false,+ cudaMusicGeneration: false,+ musicNeedsDescription: false,+ ...overrides,+});++// The panels the rail used to inline, in order, each with the kind and workflow it serves.+const PANELS = [+ ...registry.matchAll(+ /instructionsPanel\("([^"]+)", "([^"]+)", "[^"]+", \[([^\]]*)\]\)/g,+ ),+].map(([, id, kind, workflows]) => ({+ id,+ kind,+ families: [] as string[],+ workflows: [...workflows.matchAll(/"([^"]+)"/g)].map(+ (m) => m[1] as AudioWorkflowId,+ ),+ appliesTo: (c: AudioModelContext) => instructionsKindFor(c) === kind,+}));++test("each of today's special cases is one panel, in rail order", () => {+ assert.deepEqual(+ PANELS.map(({ id, kind, workflows }) => [id, kind, workflows.join()]),+ [+ ["voice-design", "voice", "speak"],+ ["higgs-scene", "scene", "speak"],+ ["moss-style", "style", "speak"],+ ["music-description", "music", "music"],+ ],+ );+});++test("a model gets the instruction field it always got, and nothing else", () => {+ const shown = (workflow: AudioWorkflowId, c: AudioModelContext) =>+ PANELS.filter((panel) => panelApplies(panel, workflow, c)).map((p) => p.id);+ assert.deepEqual(shown("speak", ctx({ audioType: "audiocpp_tts" })), [+ "voice-design",+ ]);+ assert.deepEqual(shown("speak", ctx({ audioType: "higgs_tts2" })), [+ "higgs-scene",+ ]);+ assert.deepEqual(shown("speak", ctx({ audioType: "moss_tts_local" })), [+ "moss-style",+ ]);+ assert.deepEqual(+ shown("music", ctx({ musicGeneration: true, audioType: "minimax_music3" })),+ ["music-description"],+ );+ assert.deepEqual(shown("speak", ctx({ audioType: "snac" })), []);+ assert.deepEqual(shown("speak", ctx({ audioType: "csm" })), []);+ // A music model resident while Speak is open does not put its description on Speak.+ assert.deepEqual(shown("speak", ctx({ audioType: "audiocpp_music" })), []);+});++test("the panels keep the rail's exact copy", () => {+ assert.match(panels, /\? "Scene description"/);+ assert.match(panels, /"Voice or style description"/);+ assert.match(+ panels,+ /instructionsKind === "music"\s*\? musicNeedsDescription/,+ );+ assert.match(panels, /id="audio-instructions"/);+ assert.match(panels, /id="audio-language"/);+ assert.match(registry, /kind === "style" \? \(\s*<MossLanguageField/);+});++test("a model that needs a voice description (Maya1) is held back without one", () => {+ assert.match(+ registry,+ /kind === "voice" &&\s+needsVoiceDescription\(ctx\) &&\s+!value\.instructions\.trim\(\)/,+ );+ assert.match(registry, /ctx\.requiredInputs\?\.includes\("instruct"\)/);+ assert.match(+ registry,+ /"Describe the voice\. This model needs a voice description\."/,+ );+});++test("a model that needs a description is held back without one", () => {+ assert.match(+ registry,+ /kind === "music" &&\s+ctx\.musicNeedsDescription &&\s+!value\.instructions\.trim\(\)/,+ );+ assert.match(+ registry,+ /"Add a music description\. This model needs one beside the lyrics\."/,+ );+});++test("instruction panels claim no spec option; clone panels claim theirs", async () => {+ assert.match(registry, /claims: \[\],/);+ const { CLONE_PANEL_LOGIC } = await import(+ "../src/features/audio/tools/panel-logic.ts"+ );+ assert.deepEqual(+ Object.fromEntries(+ CLONE_PANEL_LOGIC.map((panel) => [panel.id, [...panel.claims]]),+ ),+ {+ "qwen3-timbre": ["x_vector_only_mode"],+ "index-emotion": [+ "emotion_vector",+ "emotion_alpha",+ "use_emotion_text",+ "emotion_text",+ ],+ "chatterbox-expressiveness": ["exaggeration", "guidance_scale"],+ "cosyvoice-mode": ["template_name", "instruction"],+ "f5-speed-dialect": ["speed", "dialect"],+ },+ );+ assert.deepEqual(+ [...claimedOptionNames([{ claims: [] }, { claims: [] }])],+ [],+ );+ assert.deepEqual(+ [...claimedOptionNames([{ claims: ["a"] }, { claims: ["b", "a"] }])],+ ["a", "b"],+ );+});diff --git a/studio/frontend/tests/audio-upload-fence.test.ts b/studio/frontend/tests/audio-upload-fence.test.tsnew file mode 100644index 00000000000..20e99344bf4--- /dev/null+++ b/studio/frontend/tests/audio-upload-fence.test.ts@@ -0,0 +1,65 @@+// 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 { loadWithStubs } from "./helpers/module-stubs.ts";++// A peer tab has written the fence and published the next account's token.+const sent: string[] = [];+class FakeXhr {+ upload = { onprogress: null as unknown };+ status = 201;+ response = { id: "in1" };+ responseType = "";+ onload: (() => void) | null = null;+ onerror: (() => void) | null = null;+ onabort: (() => void) | null = null;+ open(_method: string, url: string) {+ sent.push(url);+ }+ setRequestHeader() {}+ send() {+ this.onload?.();+ }+ abort() {}+}+(globalThis as Record<string, unknown>).XMLHttpRequest = FakeXhr;++const { uploadAudioInput } = loadWithStubs<{+ uploadAudioInput: (+ blob: Blob,+ name: string,+ options?: { onProgress?: (fraction: number | null) => void },+ ) => Promise<{ id: string }>;+}>(new URL("../src/features/audio/api.ts", import.meta.url), {+ "@/features/auth": {+ authFetch: async () => {+ throw new Error(+ "Another tab is switching accounts; this tab will reload.",+ );+ },+ getAuthToken: () => "next-account-token",+ },+ "@/lib/account-transition": { accountTransitionPending: () => true },+ "@/lib/api-base": { apiUrl: (path: string) => path },+ "@/lib/format-fastapi-error": {+ formatApiErrorBody: () => null,+ readFastApiError: async () => "error",+ },+ "./audio-run-request": {+ buildAudioRunBody: () => ({}),+ buildVoiceCreateBody: () => ({}),+ transcribeUrl: () => "/t",+ },+});++test("a reference upload with progress waits out another tab's account switch", async () => {+ await assert.rejects(+ uploadAudioInput(new Blob(["x"], { type: "audio/wav" }), "a.wav", {+ onProgress: () => {},+ }),+ /switching accounts/,+ );+ assert.deepEqual(sent, []);+});diff --git a/studio/frontend/tests/audio-workflows.test.ts b/studio/frontend/tests/audio-workflows.test.tsindex 983e5f9ad1c..885d9996835 100644--- a/studio/frontend/tests/audio-workflows.test.ts+++ b/studio/frontend/tests/audio-workflows.test.ts@@ -14,28 +14,33 @@ const {audioWorkflowTab,clipWorkflow,isAudioWorkflowId,+ loadedModelRunsWorkflow,MUSIC_AUDIO_TYPES,slotForWorkflow,+ workflowForLoadedModel,} = await import("../src/features/audio/workflows.ts");-test("the Audio page offers Speak, Music and Transcribe in that order", () => {+test("the Audio page offers Speak, Clone, Music and Transcribe in that order", () => {assert.deepEqual(AUDIO_WORKFLOWS.map((tab) => tab.id),- ["speak", "music", "transcribe"],+ ["speak", "clone", "music", "transcribe"],);assert.equal(audioWorkflowTab("speak").heading, "Text to speech");+ assert.equal(audioWorkflowTab("clone").heading, "Clone a voice");assert.equal(audioWorkflowTab("music").heading, "Create music");assert.equal(audioWorkflowTab("transcribe").heading, "Transcribe");});-test("Speak and Music share the main slot; only Transcribe uses the sidecar", () => {+test("Speak, Clone and Music share the main slot; only Transcribe uses the sidecar", () => {assert.equal(slotForWorkflow("speak"), "speak");+ assert.equal(slotForWorkflow("clone"), "speak");assert.equal(slotForWorkflow("music"), "speak");assert.equal(slotForWorkflow("transcribe"), "transcribe");});-test("Create|Train is offered on Speak and Transcribe, not Music", () => {+test("Create|Train is offered on Speak, Clone and Transcribe, not Music", () => {assert.equal(audioWorkflowTab("speak").createTrain, true);+ assert.equal(audioWorkflowTab("clone").createTrain, true);assert.equal(audioWorkflowTab("music").createTrain, false);assert.equal(audioWorkflowTab("transcribe").createTrain, true);});@@ -56,6 +61,7 @@ test("a clip without a workflow falls back to its audio type", () => {assert.equal(clipWorkflow({ audio_type: "audiocpp_tts" }), "speak");assert.equal(clipWorkflow({ audio_type: "snac" }), "speak");assert.equal(clipWorkflow({ workflow: "music", audio_type: "snac" }), "music");+ assert.equal(clipWorkflow({ workflow: "clone", audio_type: "audiocpp_tts" }), "clone");assert.equal(clipWorkflow({ workflow: "edit", audio_type: "audiocpp_music" }), "music");assert.equal(audioWorkflowForAudioType(null), "speak");});@@ -71,3 +77,28 @@ test("the music audio types match the backend's list", () => {);assert.deepEqual(names, new Set(MUSIC_AUDIO_TYPES));});++test("a loaded model keeps the open page when it can run it, else opens its own", () => {+ assert.equal(+ workflowForLoadedModel({ current: "clone", audioWorkflows: ["speak", "clone"], music: false }),+ "clone",+ );+ assert.equal(+ workflowForLoadedModel({ current: "speak", audioWorkflows: ["clone"], music: false }),+ "clone",+ );+ assert.equal(+ workflowForLoadedModel({ current: "speak", audioWorkflows: ["transcribe"], music: true }),+ "music",+ );+ assert.equal(workflowForLoadedModel({ current: "clone", audioWorkflows: null, music: false }), "speak");+ assert.equal(workflowForLoadedModel({ current: "speak", audioWorkflows: [], music: true }), "music");+});++test("only a model that lists Clone can run the Clone page", () => {+ assert.equal(loadedModelRunsWorkflow({ workflow: "clone", audioWorkflows: ["speak"], music: false }), false);+ assert.equal(loadedModelRunsWorkflow({ workflow: "clone", audioWorkflows: ["speak", "clone"], music: false }), true);+ assert.equal(loadedModelRunsWorkflow({ workflow: "speak", audioWorkflows: ["clone"], music: false }), false);+ assert.equal(loadedModelRunsWorkflow({ workflow: "clone", audioWorkflows: undefined, music: false }), false);+ assert.equal(loadedModelRunsWorkflow({ workflow: "music", audioWorkflows: undefined, music: true }), true);+});diff --git a/studio/frontend/tests/audio-workspace-split.test.ts b/studio/frontend/tests/audio-workspace-split.test.tsindex c129df02a9a..11eb4c583db 100644--- a/studio/frontend/tests/audio-workspace-split.test.ts+++ b/studio/frontend/tests/audio-workspace-split.test.ts@@ -44,9 +44,13 @@ test("only the page commits a workflow; the sidebar's request goes through the stest("a loaded model opens the page that fits it", () => {assert.match(slot,- /const loadedWorkflow = isMusicGenerationModel\(repoId, res\.audio_type\)\s*\? "music"\s*: "speak";[\s\S]{0,200}?if \(modeRef\.current === "speak"\) \{\s*useAudioWorkspaceStore\.getState\(\)\.commitWorkflow\(loadedWorkflow\);/,+ /const loadedWorkflow = workflowForLoadedModel\(\{\s*current: useAudioWorkspaceStore\.getState\(\)\.workflow,\s*audioWorkflows: res\.audio_workflows,\s*music: isMusicGenerationModel\(repoId, res\.audio_type\),\s*\}\);[\s\S]{0,200}?rememberModel\(loadedWorkflow, repoId\);\s*if \(modeRef\.current === "speak"\) workspace\.commitWorkflow\(loadedWorkflow\);/,+ );+ // A model already resident on mount uses the same rule, so a clone-only one opens Clone.+ assert.match(+ host,+ /workflowForLoadedModel\(\{\s*current: store\.workflow,\s*audioWorkflows: status\.audio_workflows,\s*music: musicGeneration,\s*\}\);\s*if \(next !== "speak" && next !== store\.workflow\) store\.adoptWorkflow\(next\);/,);- assert.match(host, /adoptWorkflow\("music"\)/);});test("?workflow= names the page ahead of ?task=, and both go through the workflow gate", () => {@@ -92,7 +96,11 @@ test("Generate says why it is off and runs from Mod+Enter anywhere on the page",assert.match(host, /\{ label: "Choose a music model", onClick: openSelector \}/);assert.match(host, /if \(busy === "generating"\) setGenerationError\(null\);/);assert.match(host, /!pageRootRef\.current\?\.contains\(event\.target\)/);- assert.match(host, /if \(canGenerate\) void handleGenerate\(\);/);+ assert.match(+ host,+ /const handlePageGenerate =\s*ttsWorkflow === "clone" \? clone\.handleGenerate : handleGenerate;/,+ );+ assert.match(host, /if \(canGenerate\) void handlePageGenerate\(\);/);});test("each page tours its own model and settings", () => {diff --git a/studio/frontend/tests/audio-workspace-store.test.ts b/studio/frontend/tests/audio-workspace-store.test.tsindex 4806f93b352..493d087557c 100644--- a/studio/frontend/tests/audio-workspace-store.test.ts+++ b/studio/frontend/tests/audio-workspace-store.test.ts@@ -4,7 +4,10 @@import assert from "node:assert/strict";import test from "node:test";-const { useAudioWorkspaceStore } = await import(+import { installLocalStorageFake } from "./helpers/kit.ts";++const { store } = installLocalStorageFake();+const { AUDIO_WORKSPACE_STORAGE_KEY, useAudioWorkspaceStore } = await import("../src/features/audio/stores/audio-workspace-store.ts");@@ -13,6 +16,7 @@ test("the workspace opens on Speak with nothing requested", () => {assert.equal(state.workflow, "speak");assert.equal(state.requestedWorkflow, null);assert.equal(state.navExpanded, false);+ assert.deepEqual(state.lastModelByWorkflow, {});});test("a first look at the loaded model opens its page only until something chooses one", () => {@@ -36,10 +40,30 @@ test("a request does not move the committed workflow until the page takes it", (store.getState().commitWorkflow("speak");});+test("only the last model per workflow is persisted", () => {+ const state = useAudioWorkspaceStore.getState();+ state.rememberModel("transcribe", "moonshine/tiny");+ state.rememberModel("speak", "kokoro");+ state.setNavExpanded(true);+ state.commitWorkflow("transcribe");+ const saved = JSON.parse(store.get(AUDIO_WORKSPACE_STORAGE_KEY) ?? "{}");+ assert.equal(AUDIO_WORKSPACE_STORAGE_KEY, "unsloth_audio_workspace");+ assert.equal(saved.version, 1);+ assert.deepEqual(saved.state, {+ lastModelByWorkflow: { transcribe: "moonshine/tiny", speak: "kokoro" },+ });+});++test("remembering the same model again leaves the state untouched", () => {+ const before = useAudioWorkspaceStore.getState().lastModelByWorkflow;+ useAudioWorkspaceStore.getState().rememberModel("speak", "kokoro");+ assert.equal(useAudioWorkspaceStore.getState().lastModelByWorkflow, before);+});+test("any committed switch settles a pending request, so it never fires later", () => {- const store = useAudioWorkspaceStore;- store.getState().requestWorkflow("music");- store.getState().commitWorkflow("transcribe");- assert.equal(store.getState().requestedWorkflow, null);- store.getState().commitWorkflow("speak");+ const ws = useAudioWorkspaceStore;+ ws.getState().requestWorkflow("music");+ ws.getState().commitWorkflow("transcribe");+ assert.equal(ws.getState().requestedWorkflow, null);+ ws.getState().commitWorkflow("speak");});diff --git a/studio/frontend/tests/helpers/audio-workspace.ts b/studio/frontend/tests/helpers/audio-workspace.tsindex b1c47052cff..8fed0285bd7 100644--- a/studio/frontend/tests/helpers/audio-workspace.ts+++ b/studio/frontend/tests/helpers/audio-workspace.ts@@ -17,6 +17,8 @@ export const AUDIO_WORKSPACE_FILES = ["features/audio/pages/music-page.tsx","features/audio/pages/transcribe-page.tsx","features/audio/components/instructions-fields.tsx",+ "features/audio/tools/registry.tsx",+ "features/audio/tools/tool-panel-host.tsx","features/audio/audio-workspace-constants.ts","features/audio/audio-workspace-utils.ts","features/audio/components/field.tsx",