Skip to content

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.

Studio: audio.cpp models land on the right pages (#14072)

Etherldf9a01c7a11d
diff --git a/.github/workflows/model-catalog-network-check.yml b/.github/workflows/model-catalog-network-check.yml
index 2dab2aa0013..794e5b95c05 100644
--- a/.github/workflows/model-catalog-network-check.yml
+++ b/.github/workflows/model-catalog-network-check.yml
@@ -11,7 +11,10 @@
#
# This runs `catalog:check --network`, which HEADs every declared repo id and
# every declared filename anonymously (what a fresh install sees) and asserts
-# each `gated` flag matches what the Hub reports.
+# each `gated` flag matches what the Hub reports. A folder in the audio.cpp
+# umbrella repo that the bundled seed does not list is only a ::warning::,
+# since Unsloth Studio lists it from /api/inference/audio/catalog; a stale
+# AUDIO_CPP_UNOFFERED_FOLDERS entry still fails.
#
# Schedule + manual only, never on pull_request. The check is opt-in for the
# same reason it lives here: it depends on huggingface.co being up, and a Hub
diff --git a/studio/MCP.md b/studio/MCP.md
index 6b39c302a37..17f2f084ae2 100644
--- a/studio/MCP.md
+++ b/studio/MCP.md
@@ -235,14 +235,14 @@ api_key_format = "Bearer {token}"
| Tool | What it does |
|---|---|
| `studio_status` | What is loaded, loading and running: chat, image, video, speech-to-text and embedding models, training, export and GPUs. |
-| `list_models` | Models Unsloth Studio can serve, by kind. With `model`, its training defaults. |
+| `list_models` | Models Unsloth Studio can serve, by kind or by Audio page `workflow`. With `model`, its training defaults. |
| `load_model` | Load a chat, image, video or speech-to-text model, downloading it first if needed. Reports progress. |
| `unload_model` | Unload a model. |
| `chat` | Ask the loaded model, with optional images. Returns a `cancel_id`. |
| `embed` | Embed up to 2048 texts. |
| `system_one` | Ask the Decision API typed questions. The Decision API must be on. |
| `generate_image` | Text to image, image to image, inpaint, edit, outpaint and upscale. |
-| `generate_audio` | Clone, speak, edit, convert, music and separate. |
+| `generate_audio` | Clone, speak, edit, convert, music and separate, on the loaded model or a named `model`. |
| `transcribe` | Speech to text, or translation to English. |
| `generate_video` | Start a video. Poll it with `get_job`. |
| `get_job` | The state of a video, recipe or export job. |
diff --git a/studio/backend/core/inference/audio_cpp_catalog.py b/studio/backend/core/inference/audio_cpp_catalog.py
new file mode 100644
index 00000000000..ac31e2eff76
--- /dev/null
+++ b/studio/backend/core/inference/audio_cpp_catalog.py
@@ -0,0 +1,433 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The audio.cpp models Unsloth Studio can offer and the Audio pages each runs on: every umbrella
+folder, plus the Community repos the runtime's ``model_specs/`` download from. Public data only.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import threading
+import time
+from concurrent.futures import ThreadPoolExecutor, wait
+from pathlib import Path
+from typing import Any, Callable, Optional, Sequence
+
+from core.inference import audio_cpp_models as acm
+from core.inference.audio_cpp_models import AUDIO_CPP_REPO, RepoFile, recommended_gguf_files
+from core.inference.audio_workflows import AUDIO_WORKFLOW_IDS
+from hub.utils.state_dir import state_root
+from loggers import get_logger
+from models.inference import AudioCatalogModel, AudioCatalogResponse
+
+logger = get_logger(__name__)
+
+_SAVED_NAME = "audio_cpp_catalog.json"
+_MAX_SAVED_BYTES = 2 << 20
+_MAX_SPEC_FILES = 512
+_MAX_SPEC_BYTES = 1 << 20
+_MAX_PROBES = 24
+_WORKERS = 4
+_DEADLINE_SECONDS = 10.0
+_LIVE_TTL_SECONDS = 300.0
+# A saved or cache-only answer is retried sooner, but not on every call of an offline host.
+_DEGRADED_TTL_SECONDS = 30.0
+_FAMILY_RE = re.compile(r"^[a-z0-9_]+$")
+_STATUSES = frozenset(("supported", "community", "experimental", "testing", "wip"))
+_TASKS = frozenset(("tts", "music", "asr", "sep"))
+_NO_FAMILY = "Unsloth Studio could not tell which model family this is."
+_NO_PAGE = "Unsloth Studio has no Audio page for this model yet."
+_SIDECARS = "Unsloth Studio cannot download the extra files this model needs beside its GGUF yet."
+_NOT_AUDIO_CPP = "This repository's GGUF is not in the audio.cpp format Unsloth Studio loads."
+
+_cache_lock = threading.Lock()
+_build_lock = threading.Lock()
+_cache: dict[tuple, tuple[float, float, AudioCatalogResponse]] = {}
+
+
+def forget_audio_catalog() -> None:
+ with _cache_lock:
+ _cache.clear()
+
+
+def audio_catalog_payload(*, network: bool = True) -> AudioCatalogResponse:
+ """Every audio.cpp row, unfiltered: the route filters per account. Never raises for Hub/IO."""
+ specs_dir = _model_specs_dir()
+ try:
+ key = (bool(network), str(specs_dir), specs_dir.stat().st_mtime if specs_dir else None)
+ except OSError:
+ key = (bool(network), None, None)
+ # One build at a time: concurrent cold callers wait for it rather than each listing the Hub.
+ with _build_lock:
+ with _cache_lock:
+ hit = _cache.get(key)
+ if hit is not None and time.monotonic() - hit[0] < hit[1]:
+ payload = hit[2]
+ else:
+ payload, complete = _build(network, specs_dir)
+ live = payload.source == "hub" and complete
+ ttl = _LIVE_TTL_SECONDS if live else _DEGRADED_TTL_SECONDS
+ with _cache_lock:
+ _cache[key] = (time.monotonic(), ttl, payload)
+ # Downloads change faster than the listing; downloaded_models() keeps its own short cache.
+ try:
+ ids = {m.id.lower() for m in acm.downloaded_models()}
+ except Exception as exc: # noqa: BLE001 - an unreadable cache marks nothing downloaded
+ logger.debug("audio.cpp catalog: downloaded models unreadable: %s", exc)
+ ids = set()
+ models = [m.model_copy(update = {"downloaded": m.id.lower() in ids}) for m in payload.models]
+ return payload.model_copy(update = {"models": models})
+
+
+def _model_specs_dir() -> Optional[Path]:
+ """``model_specs/`` beside the installed runtime, found the way ``runtime_spec`` looks."""
+ try:
+ from core.inference.audio_cpp_server import find_audio_cpp_server_binary
+
+ binary = find_audio_cpp_server_binary()
+ parents = list(Path(binary).resolve().parents)[:3] if binary else []
+ return next((p / "model_specs" for p in parents if (p / "model_specs").is_dir()), None)
+ except Exception: # noqa: BLE001 - no runtime, no specs
+ return None
+
+
+def _spec_index(specs_dir: Optional[Path]) -> dict[str, dict]:
+ out: dict[str, dict] = {}
+ if specs_dir is None:
+ return out
+ try:
+ paths = sorted(specs_dir.glob("*.json"))[:_MAX_SPEC_FILES]
+ except OSError:
+ return out
+ for path in paths:
+ try:
+ if path.stat().st_size > _MAX_SPEC_BYTES:
+ continue
+ data = json.loads(path.read_text(encoding = "utf-8"))
+ except (OSError, ValueError):
+ continue
+ family = data.get("family", path.stem) if isinstance(data, dict) else None
+ if isinstance(family, str) and _FAMILY_RE.match(family):
+ out.setdefault(family, data)
+ return out
+
+
+def _spec_targets(index: dict[str, dict], folders: Sequence[str]) -> tuple[dict, dict]:
+ """``({umbrella folder: family}, {community repo: family})`` from the specs' gguf packages."""
+ by_lower = {f.lower(): f for f in folders}
+ umbrella: dict[str, str] = {}
+ # A repo several specs download from (mirek190/audio.cpp: GLM-TTS, Hviske, OuteTTS) is not one
+ # model: its bare id resolves to whichever GGUF ranks first, so only single-family repos list.
+ community: dict[str, tuple[str, set[str]]] = {}
+ for family, spec in index.items():
+ packages = spec.get("packages")
+ base = _dict(_dict(spec.get("package_defaults")).get("download"))
+ for package in packages if isinstance(packages, list) else ():
+ if not isinstance(package, dict) or package.get("format") != "gguf":
+ continue # other formats are conversion sources
+ repo = str({**base, **_dict(package.get("download"))}.get("repo") or "").strip()
+ if not repo or repo.lower() == AUDIO_CPP_REPO.lower():
+ files = package.get("files") if isinstance(package.get("files"), list) else []
+ where = str(package.get("target_directory") or (files[:1] or [""])[0] or "")
+ folder = by_lower.get(where.replace("\\", "/").strip("/").split("/")[0].lower())
+ if folder:
+ umbrella.setdefault(folder, family)
+ elif acm._REPO_ID_RE.match(repo):
+ community.setdefault(repo.lower(), (repo, set()))[1].add(family)
+ return umbrella, {repo: f.pop() for repo, f in community.values() if len(f) == 1}
+
+
+def _dict(value: Any) -> dict:
+ return value if isinstance(value, dict) else {}
+
+
+def _saved_path(create: bool = False) -> Optional[Path]:
+ root = state_root(create = create)
+ return root / _SAVED_NAME if root is not None else None
+
+
+def _read_saved() -> dict:
+ """The persisted listing; anything unreadable or malformed reads as none."""
+ try:
+ path = _saved_path()
+ if path is None or path.stat().st_size > _MAX_SAVED_BYTES:
+ return {}
+ data = json.loads(path.read_text(encoding = "utf-8"))
+ folders = {}
+ for name, entry in data["folders"].items():
+ files = [RepoFile(str(rel), int(size)) for rel, size in entry["files"]]
+ # Only repo paths under their own folder: a damaged file must not point at the host.
+ if not re.fullmatch(r"[\w.\-]+", name) or name in (".", ".."):
+ continue
+ files = [f for f in files if f.path.startswith(f"{name}/") and ".." not in f.path]
+ family = entry.get("family")
+ folders[name] = (files, family if isinstance(family, str) else None, entry.get("spec"))
+ if data.get("schema") != 1:
+ return {}
+ return {"fetched_at": float(data["fetched_at"]), "folders": folders}
+ except Exception: # noqa: BLE001 - missing, damaged or foreign: no saved listing
+ return {}
+
+
+def _write_saved(fetched_at: float, folders: dict, found: dict) -> None:
+ def dump(with_specs: bool) -> bytes:
+ rows = {
+ name: {
+ "files": [[f.path, f.size] for f in files],
+ "family": found.get(name, (None, None))[0],
+ "spec": found.get(name, (None, None))[1] if with_specs else None,
+ }
+ for name, files in folders.items()
+ }
+ data = {"schema": 1, "fetched_at": fetched_at, "folders": rows}
+ return json.dumps(data, separators = (",", ":")).encode("utf-8")
+
+ text = dump(True)
+ if len(text) > _MAX_SAVED_BYTES:
+ text = dump(False)
+ path = _saved_path(create = True)
+ if path is None or len(text) > _MAX_SAVED_BYTES:
+ return
+ tmp = path.with_name(f".{path.name}.{os.getpid()}.{threading.get_ident()}.tmp")
+ try:
+ tmp.write_bytes(text)
+ os.replace(tmp, path)
+ except OSError as exc:
+ logger.debug("audio.cpp catalog: could not save the listing: %s", exc)
+ try:
+ tmp.unlink(missing_ok = True)
+ except OSError:
+ pass
+
+
+def _group(files: Sequence[RepoFile]) -> dict[str, list[RepoFile]]:
+ out: dict[str, list[RepoFile]] = {}
+ for f in files:
+ head, sep, _rest = f.path.partition("/")
+ if sep and not acm._SKIP_FILE_RE.search(f.path):
+ out.setdefault(head, []).append(f)
+ return {k: v for k, v in out.items() if any(f.path.lower().endswith(".gguf") for f in v)}
+
+
+def _bounded(jobs: dict[str, Callable[[], Any]]) -> dict[str, Any]:
+ """Run ``jobs`` on a few workers under one deadline; a late or failed job is left out."""
+ out: dict[str, Any] = {}
+ if not jobs:
+ return out
+ pool = ThreadPoolExecutor(max_workers = _WORKERS, thread_name_prefix = "audio-catalog")
+ try:
+ futures = {pool.submit(job): name for name, job in jobs.items()}
+ done, _late = wait(futures, timeout = _DEADLINE_SECONDS)
+ for future in done:
+ try:
+ out[futures[future]] = future.result()
+ except Exception as exc: # noqa: BLE001 - one unreadable repo never hides the rest
+ logger.debug("audio.cpp catalog: %s: %s", futures[future], exc)
+ finally:
+ pool.shutdown(wait = False, cancel_futures = True)
+ return out
+
+
+def _ranked(
+ files: Sequence[RepoFile],
+ folder: str,
+ policy = None,
+) -> Optional[acm.AudioCppVariant]:
+ if policy is not None and policy.package:
+ variants = acm._package_variants(policy, files, folder)
+ else:
+ variants = sorted(acm._single_file_variants(files, folder), key = acm._variant_rank)
+ return variants[0] if variants else None
+
+
+# Licenses, notices, checksums and docs ship beside a GGUF but are never loaded by the runtime.
+_PACKAGING_FILE = re.compile(
+ r"(?i)(license|licence|notice|copying|readme|sha256sums|checksums)(\.[a-z0-9]+)?$|.*\.md$"
+)
+
+
+def _sidecars(spec: dict) -> list[str]:
+ """Non-GGUF files of the spec's recommended (else default) GGUF package, ``embeddings/`` aside."""
+ packages = [p for p in _list(spec.get("packages")) if isinstance(p, dict)]
+ packages = [p for p in packages if str(p.get("format") or "").lower() == "gguf"]
+ wanted = _dict(spec.get("ui")).get("recommended_package")
+ package = next((p for p in packages if wanted and p.get("id") == wanted), None) or next(
+ (p for p in packages if p.get("default") is True), None
+ )
+ files = [f.replace("\\", "/") for f in _list(_dict(package).get("files")) if isinstance(f, str)]
+ return [
+ f
+ for f in files
+ if not f.lower().endswith(".gguf")
+ and "/embeddings/" not in f"/{f}"
+ and not _PACKAGING_FILE.match(f.rsplit("/", 1)[-1])
+ ]
+
+
+def _list(value: Any) -> list:
+ return value if isinstance(value, list) else []
+
+
+def _text(value: Any, limit: int) -> Optional[str]:
+ if not isinstance(value, str) or not value.strip():
+ return None
+ value = value.strip()
+ return value if len(value) <= limit else value[: limit - 1].rstrip() + "…"
+
+
+def _row(
+ model_id: str,
+ repo_id: str,
+ folder: str,
+ family: Optional[str],
+ spec: Optional[dict],
+ files: Sequence[RepoFile],
+ header: Optional[acm.AudioCppHeader] = None,
+) -> AudioCatalogModel:
+ spec = spec if isinstance(spec, dict) else {}
+ display = _text(spec.get("display_name"), 120) or folder or repo_id.split("/")[-1]
+ names = (model_id, folder, *(Path(f.path).name for f in files if f.path.endswith(".gguf")))
+ workflows: list[str] = []
+ task, size, reason = "", None, _NO_FAMILY
+ if family:
+ try:
+ policy = acm.family_policy(family, spec or None, names, display)
+ bindings = policy.workflows
+ workflows = [w for w in AUDIO_WORKFLOW_IDS if w in bindings]
+ task = policy.task if policy.task in _TASKS else ""
+ reason = policy.unsupported or (None if workflows else _NO_PAGE)
+ if not folder and not policy.package and _sidecars(spec):
+ # A Community repo loads as one GGUF: files its package reads beside it never download.
+ reason = reason or _SIDECARS
+ if header is not None and not header.is_audio_cpp:
+ # resolve() returns None for it, so loading the row would fail.
+ reason = reason or _NOT_AUDIO_CPP
+ wanted = set(recommended_gguf_files(spec or None))
+ picked = [f for f in files if Path(f.path).name in wanted]
+ variant = None if picked else _ranked(files, folder, policy)
+ size = sum(f.size for f in picked) if picked else (variant and variant.size_bytes)
+ except Exception as exc: # noqa: BLE001 - a malformed spec refuses its row, not the list
+ logger.debug("audio.cpp catalog: policy of %s failed: %s", family, exc)
+ reason = "Unsloth Studio could not read this model's spec."
+ languages = spec.get("languages")
+ if isinstance(languages, list):
+ languages = [x for x in languages if isinstance(x, str) and x][:32] or None
+ else:
+ languages = None
+ status = spec.get("status")
+ return AudioCatalogModel(
+ id = model_id,
+ repo_id = repo_id,
+ folder = folder,
+ source = "umbrella" if folder else "community",
+ display_name = display,
+ family = family,
+ task = task,
+ workflows = [] if reason else workflows,
+ description = _text(spec.get("description"), 280),
+ languages = None if languages == ["auto"] else languages,
+ status = status if status in _STATUSES else None,
+ size_bytes = size or None,
+ unsupported_reason = reason or None,
+ )
+
+
+def _build(network: bool, specs_dir: Optional[Path]) -> tuple[AudioCatalogResponse, bool]:
+ """The catalog, and whether every family probe answered: a late one leaves a folder unplaced."""
+ index = _spec_index(specs_dir)
+ files: list[RepoFile] = []
+ from_hub = False
+ try:
+ # Anonymous (False): the repo is public, so neither cache nor saved file holds a token.
+ files, from_hub = acm.list_files(AUDIO_CPP_REPO, "", False, network = network)
+ except Exception as exc: # noqa: BLE001 - no listing at all degrades to the saved one
+ logger.debug("audio.cpp catalog: umbrella listing failed: %s", exc)
+ saved = _read_saved()
+ saved_folders = saved.get("folders", {})
+ if from_hub:
+ source, fetched_at, folders = "hub", time.time(), _group(files)
+ elif saved_folders:
+ source, fetched_at = "saved", saved["fetched_at"]
+ folders = {name: entry[0] for name, entry in saved_folders.items()}
+ else:
+ source, fetched_at, folders = "cache", time.time(), _group(files)
+ targets, community = _spec_targets(index, list(folders))
+ try:
+ snapshots = acm.snapshot_dirs(AUDIO_CPP_REPO)
+ except Exception: # noqa: BLE001 - no cache: nothing downloaded to read
+ snapshots = []
+ found: dict[str, tuple[Optional[str], Optional[dict]]] = {}
+ probes: dict[str, Callable[[], Any]] = {}
+ online = network and not acm.hub_offline()
+ # A family whose runtime spec places other folders but not this one: the name hint is wrong
+ # (Voxtral-4B-TTS reads as voxtral_realtime), so the header decides instead.
+ placed = set(targets.values())
+ for name, folder_files in folders.items():
+ if name in targets:
+ found[name] = (targets[name], None)
+ continue
+ local = [s / f.path for f in folder_files if f.path.endswith(".gguf") for s in snapshots]
+ local = next((p for p in local if p.is_file()), None)
+ header = acm.read_local_header(local) if local is not None else None
+ if header is not None and header.is_audio_cpp and header.family:
+ found[name] = (header.family, header.spec)
+ continue
+ family = acm.family_from_names((name, *(Path(f.path).name for f in folder_files)))
+ family = None if family in placed else family
+ _files, saved_family, saved_spec = saved_folders.get(name) or ((), None, None)
+ if family not in acm.FAMILIES and family not in index and saved_family:
+ found[name] = (saved_family, _dict(saved_spec) or None)
+ continue
+ found[name] = (family, None)
+ if family in acm.FAMILIES or family in index or not online or len(probes) >= _MAX_PROBES:
+ continue
+ main = _ranked(folder_files, name)
+ if main is not None:
+ size = next((f.size for f in main.files if f.path == main.main_file), 0)
+ probes[name] = lambda path = main.main_file, size = size: acm.read_remote_header(
+ AUDIO_CPP_REPO, path, False, size = size or None
+ )
+ answered = _bounded(probes)
+ for name, header in answered.items():
+ if header is not None and header.is_audio_cpp and header.family:
+ found[name] = (header.family, header.spec if isinstance(header.spec, dict) else None)
+ if source == "hub":
+ _write_saved(fetched_at, folders, found)
+ rows = []
+ for name in sorted(folders, key = str.lower):
+ family, spec = found.get(name, (None, None))
+ if family and not _FAMILY_RE.match(family):
+ family = None
+ spec = index.get(family or "") or spec
+ model_id = f"{AUDIO_CPP_REPO}/{name}"
+ rows.append(_row(model_id, AUDIO_CPP_REPO, name, family, spec, folders[name]))
+ listings = _bounded(
+ {
+ repo: (lambda repo = repo: acm.list_files(repo, "", False, network = network)[0])
+ for repo in community
+ }
+ )
+ header_probes = {}
+ for repo, repo_files in listings.items() if online else ():
+ ggufs = [f for f in repo_files or [] if f.path.lower().endswith(".gguf")]
+ wanted = set(recommended_gguf_files(index.get(community[repo])))
+ main = next((f for f in ggufs if Path(f.path).name in wanted), ggufs[0] if ggufs else None)
+ if main is not None:
+ header_probes[repo] = lambda repo = repo, f = main: acm.read_remote_header(
+ repo, f.path, False, size = f.size or None
+ )
+ headers = _bounded(header_probes)
+ for repo in sorted(community, key = str.lower):
+ family = community[repo]
+ files = listings.get(repo) or []
+ rows.append(_row(repo, repo, "", family, index.get(family), files, headers.get(repo)))
+ payload = AudioCatalogResponse(
+ source = source,
+ fetched_at = fetched_at,
+ runtime_specs = specs_dir is not None,
+ models = rows,
+ )
+ return payload, len(answered) == len(probes) and len(headers) == len(header_probes)
diff --git a/studio/backend/core/inference/audio_cpp_models.py b/studio/backend/core/inference/audio_cpp_models.py
index b3b017c97a9..f04745702c5 100644
--- a/studio/backend/core/inference/audio_cpp_models.py
+++ b/studio/backend/core/inference/audio_cpp_models.py
@@ -652,6 +652,9 @@ _CLONE_FAMILIES: tuple[AudioCppFamily, ...] = (
),
),
),
+ # Both need a reference clip on every run (mira_tts/session.cpp, sopro_tts/session.cpp).
+ AudioCppFamily("mira_tts", "tts", speaks = False, clone = CloneSpec("unused")),
+ AudioCppFamily("sopro_tts", "tts", speaks = False, clone = CloneSpec("unused")),
)
@@ -716,6 +719,12 @@ _SEPARATION_FAMILIES: tuple[AudioCppFamily, ...] = (
)
+# Table families newer than some runtimes, so the runtime check spec-derived families get still
+# applies to them.
+_RUNTIME_GATED_FAMILIES = frozenset(("mira_tts", "sopro_tts"))
+
+_MULTI_FILE_PACKAGE = "This model ships as a multi-file package Unsloth Studio cannot load yet."
+
_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.
@@ -951,7 +960,7 @@ _FAMILY_LIST: tuple[AudioCppFamily, ...] = (
AudioCppFamily(
name,
"",
- unsupported = "This model ships as a multi-file package Studio cannot load yet.",
+ unsupported = _MULTI_FILE_PACKAGE,
)
for name in ("minimax_h3", "auk", "liveavatar", "vibeasr")
),
@@ -962,7 +971,9 @@ _FAMILY_LIST: tuple[AudioCppFamily, ...] = (
),
# Tasks Studio has no page for.
*(
- AudioCppFamily(name, "", unsupported = f"{what} models are not supported in Studio yet.")
+ AudioCppFamily(
+ name, "", unsupported = f"{what} models are not supported in Unsloth Studio yet."
+ )
for names, what in (
(("qwen3_forced_aligner", "mms_forced_aligner"), "Forced-alignment"),
(("sortformer_diar", "sortformer_diar_v2", "nemotron_3_diar"), "Speaker diarization"),
@@ -976,8 +987,8 @@ _FAMILY_LIST: tuple[AudioCppFamily, ...] = (
AudioCppFamily(
"samsone",
"",
- unsupported = "SAMSONE describes audio rather than transcribing speech, so Studio does not "
- "offer it for transcription.",
+ unsupported = "SAMSONE describes audio rather than transcribing speech, so Unsloth Studio "
+ "does not offer it for transcription.",
),
)
@@ -997,15 +1008,12 @@ _SPEC_TO_SERVER_TASK = {
"design": "vdes",
"speaker": "spk",
}
-_SERVER_TO_STUDIO_TASK = {"tts": "tts", "gen": "music", "asr": "asr", "sep": "sep"}
_TASK_NAMES = {
"align": "Forced-alignment",
"diar": "Speaker diarization",
"sep": "Source separation",
"vad": "Voice activity detection",
"midi": "Music transcription",
- "vc": "Voice conversion",
- "svc": "Singing voice conversion",
"s2s": "Speech-to-speech",
"spk": "Speaker embedding",
"turn": "Turn detection",
@@ -1014,56 +1022,100 @@ _TASK_NAMES = {
}
+def recommended_gguf_files(spec: Optional[dict]) -> tuple[str, ...]:
+ """Base names of the GGUFs in the spec's recommended package, else its default GGUF package."""
+ packages = [p for p in (spec or {}).get("packages") or [] if isinstance(p, dict)]
+ packages = [p for p in packages if str(p.get("format") or "").lower() == "gguf"]
+ wanted = ((spec or {}).get("ui") or {}).get("recommended_package")
+ package = next((p for p in packages if wanted and p.get("id") == wanted), None) or next(
+ (p for p in packages if p.get("default") is True), None
+ )
+ files = (package or {}).get("files") or []
+ return tuple(
+ f.replace("\\", "/").rsplit("/", 1)[-1]
+ for f in files
+ if isinstance(f, str) and f.lower().endswith(".gguf")
+ )
+
+
+def _spec_music(tasks: Sequence[str], request: Optional[list]) -> MusicSpec:
+ """Music modes for a family the table does not list, from its spec tasks and options."""
+ names = {str(o.get("name")) for o in request or [] if isinstance(o, dict)}
+ sings = "lyrics" in names
+ modes = []
+ if "music" in tasks or "sfx" not in tasks:
+ modes.append(
+ MusicMode(
+ "song",
+ lyrics = "optional" if sings else "unused",
+ instrumental = "toggle" if sings else "always",
+ )
+ )
+ if "sfx" in tasks:
+ modes.append(MusicMode("sfx", duration = (1.0, 60.0, 8.0)))
+ # A declared request without ``seed`` refuses one, so it is never sent.
+ return MusicSpec(tuple(modes), fixed_seed = request is None or "seed" in names)
+
+
def _family_from_spec_tasks(
family: str,
spec: Optional[dict],
label: Optional[str] = None,
) -> AudioCppFamily:
- """Policy for a family Studio does not list, from the tasks its spec declares.
+ """Policy for a family Unsloth Studio does not list, from the tasks its spec declares.
The spec can be the one a GGUF embeds, newer than the installed runtime, so a family the
runtime does not load is refused here rather than failing at load with "unsupported model
family hint". ``label`` names the model in that refusal.
"""
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.
- # A clone-only family comes next: it loads as a cloning session and offers Clone alone.
+ # ``edit`` is a music edit for some families and a speech edit for others, so it names no page.
+ tokens = [_SPEC_TO_SERVER_TASK.get(t, t) for t in tasks if t != "edit"] or tasks
+ request = ((spec or {}).get("options") or {}).get("request") or None
+ request = request if isinstance(request, list) else None
+ # One page set per family. Speech first (with Clone when the spec clones), then music, then
+ # transcription; a clone-only family loads as a cloning session and offers Clone alone.
for token in ("tts", "vdes", "gen", "asr", "clon", "sep"):
- if token in tokens:
- if 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 not in tokens:
+ continue
+ if runtime_knows_family(family) is False:
+ return AudioCppFamily(
+ family,
+ "",
+ unsupported = f"{label or family} needs a newer audio runtime than the one installed.",
+ )
+ if len(recommended_gguf_files(spec)) > 1:
+ return AudioCppFamily(family, "", unsupported = _MULTI_FILE_PACKAGE)
+ if token in ("tts", "vdes", "clon"):
+ clone = None
+ if "clon" in tokens:
+ # Clone always sends a reference, and a family that declares reference_text then
+ # needs it (fish_drama3, kitten_tts2); an undeclared option is refused.
+ names = {str(o.get("name")) for o in request or [] if isinstance(o, dict)}
+ text = "optional" if request is None else "unused"
+ clone = CloneSpec("required" if "reference_text" in names else text)
if token == "clon":
- return AudioCppFamily(
- family,
- "tts",
- server_task = "clon",
- speaks = False,
- clone = CloneSpec("optional"),
- )
- if token == "sep":
- return AudioCppFamily(family, "sep", separation = SeparationSpec())
- studio = "tts" if token == "vdes" else _SERVER_TO_STUDIO_TASK[token]
- return AudioCppFamily(family, studio, server_task = token)
+ return AudioCppFamily(family, "tts", server_task = "clon", speaks = False, clone = clone)
+ return AudioCppFamily(family, "tts", server_task = token, clone = clone)
+ if token == "gen":
+ music = _spec_music(tasks, request)
+ return AudioCppFamily(family, "music", server_task = "gen", music = music)
+ if token == "sep":
+ return AudioCppFamily(family, "sep", separation = SeparationSpec())
+ return AudioCppFamily(family, "asr", server_task = "asr")
if tokens:
what = _TASK_NAMES.get(tokens[0])
- return AudioCppFamily(
- family,
- "",
- unsupported = (
- f"{what} models are not supported in Studio yet."
- if what
- else f"Studio does not support the '{tokens[0]}' task yet."
- ),
- )
+ if tokens[0] in ("vc", "svc"):
+ message = "Unsloth Studio doesn't support voice conversion models yet."
+ elif what:
+ message = f"{what} models are not supported in Unsloth Studio yet."
+ else:
+ message = f"Unsloth Studio does not support the '{tokens[0]}' task yet."
+ return AudioCppFamily(family, "", unsupported = message)
return AudioCppFamily(
family,
"",
- unsupported = f"Studio does not know what the model family '{family}' does.",
+ unsupported = f"Unsloth Studio does not know what the model family '{family}' does.",
)
@@ -1078,6 +1130,12 @@ def family_policy(
``names`` (repo, folder and file names) pick the Qwen3-TTS package kind, which the family
alone does not say: CustomVoice needs a speaker, VoiceDesign designs one, Base only clones.
"""
+ if family in _RUNTIME_GATED_FAMILIES and runtime_knows_family(family) is False:
+ return AudioCppFamily(
+ family,
+ "",
+ unsupported = f"{label or family} needs a newer audio runtime than the one installed.",
+ )
policy = FAMILIES.get(family) or _family_from_spec_tasks(family, spec, label)
if family == "qwen3_tts":
text = " ".join(names).lower()
@@ -1549,7 +1607,12 @@ def list_files(
_QUANT_RE = re.compile(
r"(?:^|[-_.])((?:i?q\d(?:_[a-z0-9]+)*)|bf16|f16|f32|fp16|fp32|orig)(?=$|[-_.])", re.IGNORECASE
)
-_QUANT_PREFERENCE = ("Q8_0", "F16", "BF16", "ORIG", "Q6_K", "Q5_K_M", "Q4_K_M", "Q4_0", "F32")
+# K and IQ quants come after F32 so the established order stays as it was.
+_QUANT_PREFERENCE = (
+ *("Q8_0", "F16", "BF16", "ORIG", "Q6_K", "Q5_K_M", "Q4_K_M", "Q4_0", "F32"),
+ *("Q5_K", "Q5_K_S", "Q4_K", "Q4_K_S", "IQ4_NL", "IQ4_XS", "Q3_K_L", "Q3_K_M", "Q3_K"),
+ *("Q3_K_S", "IQ3_M", "IQ3_S", "IQ3_XS", "IQ3_XXS", "Q2_K", "IQ2_M", "IQ2_XS", "IQ2_XXS"),
+)
_PREFERRED_SCOPES = ("turbo", "english", "tiny")
_SKIP_FILE_RE = re.compile(
r"(^|/)(readme[^/]*|license[^/]*|\.gitattributes|[^/]*\.(md|mp4|mp3|wav|png|jpe?g|gif))$", re.I
@@ -2516,7 +2579,7 @@ def _resolve_uncached(
(t for t in tags if _TAG_FAMILY_RE.match(t) and t in FAMILIES), None
) or family_from_names(names)
if not family:
- reason = "Studio could not tell which model family this audio GGUF is."
+ reason = "Unsloth Studio could not tell which model family this audio GGUF is."
variant = AudioCppVariant(quant_label(ggufs[0].path), (ggufs[0],), ggufs[0].path)
return AudioCppModel(
id = ref.id,
@@ -2553,6 +2616,10 @@ def _resolve_uncached(
AudioCppVariant(v.key, v.files, ref.local_path, label = v.label) for v in variants
]
variants.sort(key = _variant_rank)
+ # The spec's recommended package leads, so two files at one quant pick the right one.
+ recommended = {f.lower() for f in recommended_gguf_files(spec or embedded)}
+ if len(recommended) == 1:
+ variants.sort(key = lambda v: Path(v.main_file).name.lower() not in recommended)
unsupported = policy.unsupported
if not variants:
unsupported = (
diff --git a/studio/backend/core/inference/audio_workflows.py b/studio/backend/core/inference/audio_workflows.py
index c5dbfdae97f..b659deaefe7 100644
--- a/studio/backend/core/inference/audio_workflows.py
+++ b/studio/backend/core/inference/audio_workflows.py
@@ -20,6 +20,17 @@ from core.inference.audio_cpp_models import (
AUDIO_WORKFLOW_IDS = ("speak", "clone", "edit", "convert", "music", "separate", "transcribe")
+# The page names people see in the sidebar.
+AUDIO_WORKFLOW_LABELS = {
+ "speak": "Text to Speech",
+ "clone": "Clone",
+ "edit": "Edit",
+ "convert": "Convert",
+ "music": "Music",
+ "separate": "Separate",
+ "transcribe": "Transcribe",
+}
+
# Generation audio types that make music; every other generation audio type speaks.
MUSIC_AUDIO_TYPES = frozenset(("minimax_music3", AUDIO_CPP_MUSIC_AUDIO_TYPE))
@@ -62,3 +73,13 @@ def inventory_audio_workflows(
if task == HUB_TASKS["tts"]:
return [workflow_for_audio_type(audio_type)]
return None
+
+
+def pages_sentence(workflows) -> str:
+ """``It runs on Text to Speech (speak) and Clone (clone).``, for an error naming a model's pages."""
+ runs = set(workflows or ())
+ names = [f"{AUDIO_WORKFLOW_LABELS[wf]} ({wf})" for wf in AUDIO_WORKFLOW_IDS if wf in runs]
+ if not names:
+ return "Unsloth Studio has no Audio page for it yet."
+ pages = names[0] if len(names) == 1 else ", ".join(names[:-1]) + " and " + names[-1]
+ return f"It runs on {pages}."
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 189cd85b209..4272137079a 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -6100,6 +6100,36 @@ class AudioVoiceListResponse(BaseModel):
voices: List[AudioVoice] = Field(default_factory = list)
+class AudioCatalogModel(BaseModel):
+ """One audio.cpp model Unsloth Studio can offer: an umbrella folder or a Community repo."""
+
+ id: str
+ repo_id: str
+ folder: str = ""
+ source: Literal["umbrella", "community"]
+ display_name: str
+ family: Optional[str] = None
+ task: Literal["tts", "music", "asr", "sep", ""] = ""
+ workflows: List[
+ Literal["speak", "clone", "edit", "convert", "music", "separate", "transcribe"]
+ ] = Field(default_factory = list)
+ description: Optional[str] = None
+ languages: Optional[List[str]] = None
+ status: Optional[Literal["supported", "community", "experimental", "testing", "wip"]] = None
+ size_bytes: Optional[int] = None
+ downloaded: bool = False
+ unsupported_reason: Optional[str] = None
+
+
+class AudioCatalogResponse(BaseModel):
+ """The audio.cpp model catalog, with where its umbrella listing came from."""
+
+ source: Literal["hub", "saved", "cache"]
+ fetched_at: float
+ runtime_specs: bool = False
+ models: List[AudioCatalogModel] = Field(default_factory = list)
+
+
class AudioGalleryFlagsPatch(BaseModel):
pinned: Optional[bool] = Field(None, description = "Pin (True) or unpin (False) the clip")
archived: Optional[bool] = Field(None, description = "Archive (True) or restore (False) the clip")
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index f4d1a12ba81..8ae91c8ecf3 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -3813,6 +3813,8 @@ from models.inference import (
AudioVoiceCreate,
AudioVoiceListResponse,
AudioVoicePatch,
+ AudioCatalogModel,
+ AudioCatalogResponse,
TranscribeSourceRequest,
TranscriptPatch,
LoadResponse,
@@ -12000,21 +12002,26 @@ async def _maybe_auto_switch_model(
param = "instructions",
),
)
- if (
- require_audio_workflow
- and resolved is not None
- and require_audio_workflow
- not in await asyncio.to_thread(_target_audio_workflows, target_id, speech_type)
- ):
- raise HTTPException(
- status_code = 400,
- detail = openai_error_body(
- f"The requested model cannot run the {require_audio_workflow} workflow.",
- status = 400,
- code = "invalid_value",
- param = "model",
- ),
+ if require_audio_workflow and resolved is not None:
+ target_workflows = await asyncio.to_thread(
+ _target_audio_workflows, target_id, speech_type
)
+ if require_audio_workflow not in target_workflows:
+ from core.inference.audio_workflows import AUDIO_WORKFLOW_LABELS, pages_sentence
+
+ page = AUDIO_WORKFLOW_LABELS.get(require_audio_workflow, require_audio_workflow)
+ # Name the model as asked, never target_id: that can be a local path.
+ label = _audio_model_label(str(named_model or "").replace("\\", "/"))
+ raise HTTPException(
+ status_code = 400,
+ detail = openai_error_body(
+ f"{label} can't run {page} "
+ f"({require_audio_workflow}). {pages_sentence(target_workflows)}",
+ status = 400,
+ code = "invalid_value",
+ param = "model",
+ ),
+ )
# resolver branch only, like the probe above: a reload-stash restore changes no format.
if audio_preflight is not None and resolved is not None:
await _preflight_audio_for_switch(audio_preflight, target_is_gguf)
@@ -51360,6 +51367,26 @@ async def transcribe_audio_input(
)
+@studio_router.get("/audio/catalog", response_model = AudioCatalogResponse)
+async def audio_catalog(current_subject: str = Depends(get_current_subject)):
+ """The audio.cpp models Unsloth Studio can offer, filtered to what this account may see."""
+ from core.inference.audio_cpp_catalog import audio_catalog_payload
+
+ try:
+ payload = await asyncio.to_thread(audio_catalog_payload)
+ # Filter per request: the builder caches one unfiltered catalog for every account.
+ rows = await asyncio.to_thread(
+ account_access.filter_model_rows, [m.model_dump() for m in payload.models]
+ )
+ except Exception: # noqa: BLE001 - no exception text reaches the client
+ logger.debug("audio.cpp catalog failed", exc_info = True)
+ raise HTTPException(
+ status_code = 503,
+ detail = "Unsloth Studio could not list audio models right now.",
+ ) from None
+ return payload.model_copy(update = {"models": [AudioCatalogModel(**r) for r in rows]})
+
+
@router.get("/audio/voices", response_model = AudioVoiceListResponse)
async def list_audio_voices(request: Request, current_subject: str = Depends(get_current_subject)):
from core.inference import audio_voices
diff --git a/studio/backend/studio_mcp/tools/audio.py b/studio/backend/studio_mcp/tools/audio.py
index bdfcce230f1..00f6f35b010 100644
--- a/studio/backend/studio_mcp/tools/audio.py
+++ b/studio/backend/studio_mcp/tools/audio.py
@@ -47,12 +47,20 @@ async def _clip_contents(caller: Caller, clip: AudioClip) -> list[Any]:
async def _checked_options(
- caller: Caller, workflow: str, options: dict[str, Any]
+ caller: Caller,
+ workflow: str,
+ options: dict[str, Any],
+ model: Optional[str] = None,
) -> dict[str, Any]:
"""``options`` with each enum value spelled as the loaded model lists it; the route drops a value it does not list, so that is refused here instead."""
status = await try_json(caller, "/api/inference/status")
if not isinstance(status, dict):
return options
+ if model and model.split(":", 1)[0].lower() not in {
+ str(status.get(key) or "").lower() for key in ("model_identifier", "active_model")
+ }:
+ # Another model will run it, so the loaded model's choices say nothing about these.
+ return options
by_workflow = status.get("audio_options_by_workflow")
schema = (by_workflow.get(workflow) if isinstance(by_workflow, dict) else None) or status.get(
"audio_options"
@@ -78,6 +86,7 @@ async def _checked_options(
async def generate_audio(
workflow: Literal["clone", "speak", "edit", "convert", "music", "separate"],
+ model: Optional[str] = None,
text: Optional[str] = None,
language: Optional[str] = None,
instructions: Optional[str] = None,
@@ -99,7 +108,7 @@ async def generate_audio(
max_tokens: Optional[int] = None,
options: Optional[dict[str, Any]] = None,
) -> ToolResult:
- """Run an Audio page workflow with the audio model loaded in Unsloth Studio; clips are saved to Audio history and returned inline when small, else as links. clone: speak ``text`` in the voice of ``reference`` (a clip, or a saved voice as voice_id; ``reference_text`` is its transcript). speak: ``text`` in the loaded model's default voice, or a saved voice via ``reference``. edit: change the words or delivery of ``source`` per ``edit``. convert: make ``source`` sound like ``target``. music: ``mode`` song or sfx from ``text`` (the style) and ``lyrics``; ``variations`` up to 4 share a group_id. separate: split ``source`` into stems. ``options`` are the loaded model's ``audio_options`` that studio_status lists, such as a built-in ``voice``. Audio inputs are an Unsloth Studio id, inline base64 with a filename, or a path on the Unsloth Studio computer."""
+ """Run an Audio page workflow with the audio model loaded in Unsloth Studio, or with ``model`` (an id from list_models(workflow=...)), which Unsloth Studio loads first when "Switch model by request" is on in Settings > API; a model that cannot run the workflow is refused before anything is unloaded, and the refusal names the pages it runs on. Clips are saved to Audio history and returned inline when small, else as links. clone: speak ``text`` in the voice of ``reference`` (a clip, or a saved voice as voice_id; ``reference_text`` is its transcript). speak: ``text`` in the loaded model's default voice, or a saved voice via ``reference``. edit: change the words or delivery of ``source`` per ``edit``. convert: make ``source`` sound like ``target``. music: ``mode`` song or sfx from ``text`` (the style) and ``lyrics``; ``variations`` up to 4 share a group_id. separate: split ``source`` into stems. ``options`` are the loaded model's ``audio_options`` that studio_status lists, such as a built-in ``voice``. Audio inputs are an Unsloth Studio id, inline base64 with a filename, or a path on the Unsloth Studio computer."""
caller = current_caller()
inputs: dict[str, Any] = {}
for key, audio in (
@@ -112,10 +121,11 @@ async def generate_audio(
inputs[key] = await audio_ref(caller, audio)
inputs.update(present(reference_text = reference_text, source_text = source_text))
if options:
- options = await _checked_options(caller, workflow, options)
+ options = await _checked_options(caller, workflow, options, model)
body: dict[str, Any] = {"workflow": workflow, "inputs": inputs}
body.update(
present(
+ model = model,
text = text,
language = language,
instructions = instructions,
diff --git a/studio/backend/studio_mcp/tools/models.py b/studio/backend/studio_mcp/tools/models.py
index b81aae36517..a7c8bb9037c 100644
--- a/studio/backend/studio_mcp/tools/models.py
+++ b/studio/backend/studio_mcp/tools/models.py
@@ -17,6 +17,7 @@ from studio_mcp.tools import DESTRUCTIVE, READ_ONLY, WRITES, as_dict, opt_text,
# "tts" and "audio" are what list_models reports for audio models; they load in the llm slot.
ModelKind = Literal["llm", "image", "video", "stt", "tts", "audio"]
+AudioWorkflow = Literal["speak", "clone", "edit", "convert", "music", "separate", "transcribe"]
KIND_BY_TASK = {
"text-to-image": "image",
@@ -84,9 +85,10 @@ async def list_models(
kind: Optional[ModelKind] = None,
loaded_only: bool = False,
model: Optional[str] = None,
+ workflow: Optional[AudioWorkflow] = None,
) -> ModelList:
- """Models this Unsloth Studio can serve: loaded ones and those already downloaded. Each entry has the id to pass to load_model, its kind and whether it is loaded. ``kind`` is read from the model's task; a model with no task is reported as "llm", which also covers embedding models and unloaded text-to-speech models Unsloth Studio cannot classify yet, so pass the kind explicitly to load_model. ``loaded_only`` returns just the resident models. ``model`` narrows the list to that model (empty when it is not downloaded yet) and adds Unsloth Studio's training defaults for it, which also works for a Hugging Face repo id that is not downloaded (send X-Unsloth-HF-Token for a gated repo)."""
- if loaded_only and kind == "llm":
+ """Models this Unsloth Studio can serve: loaded ones and those already downloaded. Each entry has the id to pass to load_model, its kind and whether it is loaded. ``kind`` is read from the model's task; a model with no task is reported as "llm", which also covers embedding models and unloaded text-to-speech models Unsloth Studio cannot classify yet, so pass the kind explicitly to load_model. ``loaded_only`` returns just the resident models. ``model`` narrows the list to that model (empty when it is not downloaded yet) and adds Unsloth Studio's training defaults for it, which also works for a Hugging Face repo id that is not downloaded (send X-Unsloth-HF-Token for a gated repo). ``workflow`` keeps only audio models that run that Unsloth Studio Audio page (their ``audio_workflows``), such as the ids to pass to generate_audio as ``model``."""
+ if loaded_only and kind == "llm" and not workflow:
# Resident chat models without a scan of every model folder; it never lists image, video or STT.
listing = await route_json("GET", "/api/inference/loaded-models")
else:
@@ -99,6 +101,8 @@ async def list_models(
continue
if model and not _same_model_id(entry.id, model):
continue
+ if workflow and workflow not in (entry.audio_workflows or []):
+ continue
models.append(entry)
defaults = None
if model:
diff --git a/studio/backend/tests/test_audio_catalog_route.py b/studio/backend/tests/test_audio_catalog_route.py
new file mode 100644
index 00000000000..19a7cc046b5
--- /dev/null
+++ b/studio/backend/tests/test_audio_catalog_route.py
@@ -0,0 +1,81 @@
+# 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 sys
+from types import SimpleNamespace
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from auth.authentication import get_current_subject
+from hub.services.models import account_access
+from models.inference import AudioCatalogResponse
+from utils.api_errors import install_api_error_handlers
+
+UMBRELLA = "audio-cpp/audio.cpp-gguf"
+KOKORO = {"id": f"{UMBRELLA}/Kokoro-82M-GGUF", "repo_id": UMBRELLA, "folder": "Kokoro-82M-GGUF"}
+KOKORO.update(source = "umbrella", display_name = "Kokoro 82M", task = "tts", workflows = ["speak"])
+DRAMA = {"id": "Jmica/Drama-3-GGUF", "repo_id": "Jmica/Drama-3-GGUF", "source": "community"}
+DRAMA.update(display_name = "Drama 3", task = "tts", workflows = ["speak", "clone"])
+CATALOG = AudioCatalogResponse(
+ source = "hub", fetched_at = 1760720000.0, runtime_specs = True, models = [KOKORO, DRAMA]
+)
+
+
+def client():
+ from routes import inference
+
+ app = FastAPI()
+ install_api_error_handlers(app)
+ app.dependency_overrides[get_current_subject] = lambda: "tester"
+ app.include_router(inference.router, prefix = "/api/inference")
+ app.include_router(inference.studio_router, prefix = "/api/inference")
+ app.include_router(inference.router, prefix = "/v1")
+ yield TestClient(app)
+
+
+def _builder(monkeypatch, build):
+ # The route imports the builder at call time, so this stands in for the module.
+ module = SimpleNamespace(audio_catalog_payload = build)
+ monkeypatch.setitem(sys.modules, "core.inference.audio_cpp_catalog", module)
+
+
+def test_the_catalog_is_served_on_the_studio_router_only(client, monkeypatch):
+ _builder(monkeypatch, lambda: CATALOG)
+ response = client.get("/api/inference/audio/catalog")
+ assert response.status_code == 200
+ body = AudioCatalogResponse.model_validate(response.json())
+ assert body == CATALOG
+ assert not any("path" in row for row in response.json()["models"])
+ assert client.get("/v1/audio/catalog").status_code == 404
+
+
+def test_a_managed_account_sees_only_the_rows_it_may_use(client, monkeypatch):
+ _builder(monkeypatch, lambda: CATALOG)
+ seen = []
+ monkeypatch.setattr(account_access, "managed_account", lambda: True)
+ monkeypatch.setattr(account_access, "model_grants", lambda: set())
+ monkeypatch.setattr(account_access, "_warm_public_repos", lambda *a: None)
+ monkeypatch.setattr(
+ account_access,
+ "model_visible",
+ lambda reference, **_k: seen.append(reference) or reference != DRAMA["repo_id"],
+ )
+ response = client.get("/api/inference/audio/catalog")
+ assert [row["id"] for row in response.json()["models"]] == [KOKORO["id"]]
+ assert seen == [KOKORO["repo_id"], DRAMA["repo_id"]]
+ # The cached payload stays whole for the next account.
+ assert len(CATALOG.models) == 2
+
+
+def test_a_builder_failure_answers_503_without_its_text(client, monkeypatch):
+ def build():
+ raise RuntimeError("/home/me/.cache/huggingface exploded")
+
+ _builder(monkeypatch, build)
+ response = client.get("/api/inference/audio/catalog")
+ assert response.status_code == 503
+ assert "Unsloth Studio could not list audio models right now." in response.text
+ assert "exploded" not in response.text and "/home/me" not in response.text
diff --git a/studio/backend/tests/test_audio_cpp_catalog.py b/studio/backend/tests/test_audio_cpp_catalog.py
new file mode 100644
index 00000000000..afbe2778b1a
--- /dev/null
+++ b/studio/backend/tests/test_audio_cpp_catalog.py
@@ -0,0 +1,432 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The audio.cpp catalog builder: online, offline from the saved listing, cache-only, cached."""
+
+import json
+import re
+import threading
+import time
+
+import pytest
+
+from core.inference import audio_cpp_catalog as catalog
+from core.inference import audio_cpp_files, audio_cpp_server
+from core.inference import audio_cpp_models as acm
+from core.inference.audio_cpp_models import AUDIO_CPP_REPO, AudioCppHeader, RepoFile
+from hub.utils import state_dir
+
+DRAMA_SPEC = {
+ "family": "fish_drama3",
+ "display_name": "Fish Audio Drama 3",
+ "description": "Drama 3 speech generation and voice cloning.",
+ "status": "experimental",
+ "tasks": ["tts", "clone"],
+ "languages": ["auto"],
+ "ui": {"recommended_package": "q4"},
+ "package_defaults": {"download": {"repo": "Jmica/Drama-3-GGUF"}},
+ "packages": [
+ {"id": "q4", "default": True, "format": "gguf", "files": ["drama-3-Q4_K_S.gguf"]},
+ {"id": "src", "format": "safetensors", "files": ["model.safetensors"]},
+ ],
+}
+KOKORO_SPEC = {
+ "family": "kokoro_tts",
+ "display_name": "Kokoro 82M",
+ "status": "community",
+ "tasks": ["tts"],
+ "languages": ["en-us", "zh"],
+ "package_defaults": {"download": {"repo": AUDIO_CPP_REPO}},
+ "packages": [
+ {
+ "id": "kokoro_q8",
+ "default": True,
+ "format": "gguf",
+ "target_directory": "Kokoro-82M-GGUF",
+ "files": ["Kokoro-82M-GGUF/kokoro-82m-q8_0.gguf"],
+ }
+ ],
+}
+NEW_TTS = AudioCppHeader("audiocpp", "new_tts", {"family": "new_tts", "tasks": ["tts", "clone"]})
+UMBRELLA = [
+ RepoFile("Kokoro-82M-GGUF/kokoro-82m-q8_0.gguf", 100),
+ RepoFile("Kokoro-82M-GGUF/kokoro-82m-bf16.gguf", 200),
+ RepoFile("Kokoro-82M-GGUF/README.md", 5),
+ RepoFile("New-TTS-GGUF/new-tts-q8_0.gguf", 300),
+ RepoFile("HTDemucs-GGUF/htdemucs-f16.gguf", 400),
+ RepoFile("README.md", 1),
+]
+DRAMA = [RepoFile("drama-3-Q4_K_S.gguf", 7000), RepoFile("drama-3-Q2_K.gguf", 5000)]
+
+
+def env(tmp_path, monkeypatch):
+ hub_root = tmp_path / "hub"
+ hub_root.mkdir()
+ monkeypatch.setattr(acm, "_hub_cache", lambda: hub_root)
+ monkeypatch.setattr(audio_cpp_files, "_hub_cache", lambda: hub_root)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "studio-cache")
+ monkeypatch.setattr(acm, "runtime_knows_family", lambda family: None)
+ monkeypatch.setattr(acm, "_listing_cache", {})
+ monkeypatch.setenv("HF_HUB_OFFLINE", "0")
+ calls = {"hub": 0, "header": 0}
+ umbrella = list(UMBRELLA)
+
+ def listing(repo_id, folder, token):
+ calls["hub"] += 1
+ assert token is None and folder == ""
+ return list(umbrella if repo_id == AUDIO_CPP_REPO else DRAMA)
+
+ def header(
+ repo_id,
+ filename,
+ hf_token = None,
+ *,
+ size = None,
+ ):
+ calls["header"] += 1
+ assert hf_token is False
+ return NEW_TTS if filename.startswith("New-TTS-GGUF/") else None
+
+ monkeypatch.setattr(acm, "_hub_listing", listing)
+ monkeypatch.setattr(acm, "read_remote_header", header)
+ runtime = tmp_path / "runtime"
+ (runtime / "bin").mkdir(parents = True)
+ specs = runtime / "model_specs"
+ specs.mkdir()
+ (specs / "fish_drama3.json").write_text(json.dumps(DRAMA_SPEC))
+ (specs / "kokoro_tts.json").write_text(json.dumps(KOKORO_SPEC))
+ (specs / "Bad Name.json").write_text("{not json")
+ binary = str(runtime / "bin" / "audiocpp_server")
+ monkeypatch.setattr(audio_cpp_server, "find_audio_cpp_server_binary", lambda: binary)
+ catalog.forget_audio_catalog()
+ acm.forget()
+ yield {"tmp": tmp_path, "hub": hub_root, "specs": specs, "calls": calls, "umbrella": umbrella}
+ catalog.forget_audio_catalog()
+ acm.forget()
+
+
+def _rows(payload):
+ return {m.id: m for m in payload.models}
+
+
+def _saved_file(env):
+ return env["tmp"] / "studio-cache" / state_dir._HUB_STATE_DIRNAME / "audio_cpp_catalog.json"
+
+
+def _assert_safe(env, payload):
+ text = json.dumps(payload.model_dump())
+ assert str(env["tmp"]) not in text
+ assert not re.search(r'"(/|[A-Za-z]:\\\\)[^"]*"', text)
+ for m in payload.models:
+ assert not re.search(r"(?<!Unsloth )Studio", m.unsupported_reason or "")
+ assert (m.unsupported_reason is None) == bool(m.workflows)
+
+
+def test_online_lists_umbrella_folders_spec_families_and_community_repos(env):
+ payload = catalog.audio_catalog_payload()
+ assert payload.source == "hub" and payload.runtime_specs
+ rows = _rows(payload)
+ kokoro = rows[f"{AUDIO_CPP_REPO}/Kokoro-82M-GGUF"]
+ assert kokoro.workflows == ["speak"] and kokoro.display_name == "Kokoro 82M"
+ assert kokoro.languages == ["en-us", "zh"] and kokoro.status == "community"
+ assert kokoro.size_bytes == 100 and kokoro.source == "umbrella"
+ assert rows[f"{AUDIO_CPP_REPO}/New-TTS-GGUF"].workflows == ["speak", "clone"]
+ assert rows[f"{AUDIO_CPP_REPO}/HTDemucs-GGUF"].workflows == ["separate"]
+ drama = rows["Jmica/Drama-3-GGUF"]
+ assert drama.source == "community" and drama.folder == "" and drama.family == "fish_drama3"
+ assert drama.languages is None and drama.status == "experimental"
+ assert drama.size_bytes == 7000
+ assert [m.source for m in payload.models].count("community") == 1
+ saved = json.loads(_saved_file(env).read_text())
+ assert saved["schema"] == 1
+ assert saved["folders"]["New-TTS-GGUF"]["family"] == "new_tts"
+ assert "README.md" not in json.dumps(saved)
+ _assert_safe(env, payload)
+
+
+def test_offline_reads_the_saved_listing_without_the_hub(env, monkeypatch):
+ online = _rows(catalog.audio_catalog_payload())
+ catalog.forget_audio_catalog()
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ env["calls"].update(hub = 0, header = 0)
+ payload = catalog.audio_catalog_payload()
+ assert payload.source == "saved"
+ assert set(_rows(payload)) == set(online)
+ assert _rows(payload)[f"{AUDIO_CPP_REPO}/New-TTS-GGUF"].workflows == ["speak", "clone"]
+ assert env["calls"] == {"hub": 0, "header": 0}
+ _assert_safe(env, payload)
+
+
+def _kokoro_on_disk(env):
+ repo = env["hub"] / ("models--" + AUDIO_CPP_REPO.replace("/", "--"))
+ gguf = repo / "snapshots" / ("a" * 40) / "Kokoro-82M-GGUF" / "kokoro-82m-q8_0.gguf"
+ gguf.parent.mkdir(parents = True)
+ gguf.write_bytes(b"x")
+ (repo / "refs").mkdir()
+ (repo / "refs" / "main").write_text("a" * 40)
+
+
+def test_offline_without_a_saved_listing_lists_the_cached_folders(env, monkeypatch):
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ _kokoro_on_disk(env)
+ payload = catalog.audio_catalog_payload()
+ assert payload.source == "cache"
+ umbrella = [m for m in payload.models if m.source == "umbrella"]
+ assert [m.folder for m in umbrella] == ["Kokoro-82M-GGUF"]
+ assert umbrella[0].downloaded and umbrella[0].workflows == ["speak"]
+ assert env["calls"] == {"hub": 0, "header": 0}
+ _assert_safe(env, payload)
+
+
+def test_a_saved_listing_deleted_mid_run_degrades_to_the_cache(env, monkeypatch):
+ catalog.audio_catalog_payload()
+ catalog.forget_audio_catalog()
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ _kokoro_on_disk(env)
+ _saved_file(env).unlink()
+ assert catalog.audio_catalog_payload().source == "cache"
+ catalog.forget_audio_catalog()
+ _saved_file(env).write_text('{"schema": 1, "folders": {"X": {"files": "bad"}}}')
+ assert catalog.audio_catalog_payload().source == "cache"
+
+
+def test_the_catalog_is_cached_and_a_degraded_answer_is_retried_sooner(env, monkeypatch):
+ clock = [1000.0]
+ monkeypatch.setattr(catalog.time, "monotonic", lambda: clock[0])
+ catalog.audio_catalog_payload()
+ hub_calls = env["calls"]["hub"]
+ catalog.audio_catalog_payload()
+ clock[0] += 299
+ catalog.audio_catalog_payload()
+ assert env["calls"]["hub"] == hub_calls
+ catalog.forget_audio_catalog()
+ acm._listing_cache.clear()
+ catalog.audio_catalog_payload()
+ assert env["calls"]["hub"] > hub_calls
+
+ def down(repo_id, *_a):
+ env["calls"]["hub"] += repo_id == AUDIO_CPP_REPO
+ raise OSError("Hub down")
+
+ monkeypatch.setattr(acm, "_hub_listing", down)
+ catalog.forget_audio_catalog()
+ acm._listing_cache.clear()
+ env["calls"]["hub"] = 0
+ assert catalog.audio_catalog_payload().source == "saved"
+ clock[0] += 29
+ catalog.audio_catalog_payload()
+ assert env["calls"]["hub"] == 1
+ clock[0] += 2
+ catalog.audio_catalog_payload()
+ assert env["calls"]["hub"] == 2
+
+
+def test_without_runtime_specs_folders_resolve_by_bounded_header_probes(env, monkeypatch):
+ for f in env["specs"].iterdir():
+ f.unlink()
+ env["specs"].rmdir()
+ monkeypatch.setattr(acm, "runtime_spec", lambda family: None)
+ many = [RepoFile(f"Mystery-{i:02d}-GGUF/mystery-{i:02d}-q8_0.gguf", 10) for i in range(40)]
+ env["umbrella"].extend(many)
+ payload = catalog.audio_catalog_payload()
+ assert payload.runtime_specs is False
+ assert all(m.source == "umbrella" for m in payload.models)
+ assert env["calls"]["header"] <= catalog._MAX_PROBES
+ rows = _rows(payload)
+ assert rows[f"{AUDIO_CPP_REPO}/Kokoro-82M-GGUF"].workflows == ["speak"]
+ assert rows[f"{AUDIO_CPP_REPO}/Kokoro-82M-GGUF"].display_name == "Kokoro-82M-GGUF"
+ mystery = [m for m in payload.models if m.folder.startswith("Mystery-")]
+ assert len(mystery) == 40 and not mystery[0].workflows
+ assert mystery[0].unsupported_reason == catalog._NO_FAMILY
+ _assert_safe(env, payload)
+
+
+def test_a_name_hint_whose_spec_places_other_folders_falls_back_to_the_header(env, monkeypatch):
+ # "Kokoro" hints kokoro_tts, whose runtime spec places Kokoro-82M-GGUF only.
+ env["umbrella"].append(RepoFile("Kokoro-Next-GGUF/kokoro-next-q8_0.gguf", 50))
+ probe = acm.read_remote_header
+ other = AudioCppHeader("audiocpp", "other_tts", {"family": "other_tts", "tasks": ["tts"]})
+ monkeypatch.setattr(
+ acm,
+ "read_remote_header",
+ lambda repo_id, filename, hf_token = None, *, size = None: (
+ other
+ if filename.startswith("Kokoro-Next-GGUF/")
+ else probe(repo_id, filename, hf_token, size = size)
+ ),
+ )
+ monkeypatch.setattr(acm, "runtime_knows_family", lambda family: family != "other_tts")
+ rows = _rows(catalog.audio_catalog_payload())
+ assert acm.family_from_names(("Kokoro-Next-GGUF",)) == "kokoro_tts"
+ row = rows[f"{AUDIO_CPP_REPO}/Kokoro-Next-GGUF"]
+ assert row.family == "other_tts" and not row.workflows
+ assert "needs a newer audio runtime" in row.unsupported_reason
+ assert rows[f"{AUDIO_CPP_REPO}/Kokoro-82M-GGUF"].workflows == ["speak"]
+
+
+def test_a_header_family_a_spec_places_elsewhere_survives_offline(env, monkeypatch):
+ # Phonon-2-GGUF's header says parakeet_tdt, whose runtime spec places another folder only.
+ env["umbrella"].append(RepoFile("Phonon-GGUF/phonon-q8.gguf", 50))
+ probe = acm.read_remote_header
+ kokoro = AudioCppHeader("audiocpp", "kokoro_tts", {"family": "kokoro_tts", "tasks": ["tts"]})
+ monkeypatch.setattr(
+ acm,
+ "read_remote_header",
+ lambda repo_id, filename, hf_token = None, *, size = None: (
+ kokoro
+ if filename.startswith("Phonon-GGUF/")
+ else probe(repo_id, filename, hf_token, size = size)
+ ),
+ )
+ online = _rows(catalog.audio_catalog_payload())[f"{AUDIO_CPP_REPO}/Phonon-GGUF"]
+ assert online.family == "kokoro_tts" and online.workflows == ["speak"]
+ catalog.forget_audio_catalog()
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ env["calls"].update(hub = 0, header = 0)
+ payload = catalog.audio_catalog_payload()
+ assert payload.source == "saved" and env["calls"]["header"] == 0
+ offline = _rows(payload)[f"{AUDIO_CPP_REPO}/Phonon-GGUF"]
+ assert offline.family == "kokoro_tts" and offline.workflows == ["speak"]
+
+
+def test_a_community_repo_several_specs_download_from_is_not_listed(env):
+ # mirek190/audio.cpp holds GLM-TTS, Hviske and OuteTTS: its bare id resolves to one of them.
+ for family, files in (("glm_tts", ["GLM-TTS_Q8.gguf"]), ("hviske_asr", ["hviske_Q8.gguf"])):
+ spec = {
+ "family": family,
+ "tasks": ["tts" if family == "glm_tts" else "asr"],
+ "packages": [
+ {"format": "gguf", "files": files, "download": {"repo": "Mixed/audio.cpp"}}
+ ],
+ }
+ (env["specs"] / f"{family}.json").write_text(json.dumps(spec))
+ rows = _rows(catalog.audio_catalog_payload())
+ assert "Mixed/audio.cpp" not in rows
+ assert rows["Jmica/Drama-3-GGUF"].family == "fish_drama3"
+ targets = catalog._spec_targets(
+ {
+ "a": {"packages": [{"format": "gguf", "download": {"repo": "Same/Repo"}}]},
+ "b": {"packages": [{"format": "gguf", "download": {"repo": "same/repo"}}]},
+ "c": {"packages": [{"format": "gguf", "download": {"repo": "One/Repo"}}]},
+ },
+ [],
+ )
+ assert targets == ({}, {"One/Repo": "c"})
+
+
+def test_a_community_repo_whose_package_needs_sidecars_is_withheld(env):
+ # trklou/audio.cpp (F5/Habibi) reads vocab.txt beside its GGUF; ampixa/sanoTTS a config.json.
+ for family, repo, files in (
+ (
+ "f5_tts",
+ "trklou/audio.cpp",
+ ["habibi-unified/habibi-unified-orig.gguf", "habibi-unified/vocab.txt"],
+ ),
+ ("sanotts", "ampixa/sanoTTS", ["gguf/heart-nano-f32.gguf", "gguf/config.json"]),
+ ("voices_tts", "Voices/TTS", ["v-q8_0.gguf", "embeddings/alba.safetensors"]),
+ # Licenses and checksums ride along but are never loaded (Kitten TTS 2 is self-contained).
+ (
+ "kitten_tts2",
+ "dignome/kitten_tts2",
+ ["kitten.gguf", "LICENSE", "NOTICE", "native/LICENSE", "SHA256SUMS", "README.md"],
+ ),
+ ):
+ spec = {
+ "family": family,
+ "tasks": ["tts", "clone"],
+ "package_defaults": {"download": {"repo": repo}},
+ "packages": [{"id": "p", "default": True, "format": "gguf", "files": files}],
+ }
+ (env["specs"] / f"{family}.json").write_text(json.dumps(spec))
+ rows = _rows(catalog.audio_catalog_payload())
+ for repo in ("trklou/audio.cpp", "ampixa/sanoTTS"):
+ assert rows[repo].workflows == [] and rows[repo].unsupported_reason == catalog._SIDECARS
+ assert rows["Voices/TTS"].unsupported_reason is None and rows["Voices/TTS"].workflows
+ assert rows["dignome/kitten_tts2"].unsupported_reason is None
+ assert rows["Jmica/Drama-3-GGUF"].workflows == ["speak", "clone"]
+
+
+def test_a_community_repo_whose_gguf_is_not_audio_cpp_is_withheld(env, monkeypatch):
+ # SenseVoice and Echo-TTS publish GGUFs whose architecture is not "audiocpp": resolve() is None.
+ spec = {
+ "family": "sense_asr",
+ "tasks": ["asr"],
+ "package_defaults": {"download": {"repo": "FunAudioLLM/SenseVoiceSmall-GGUF-audiocpp"}},
+ "packages": [{"id": "q8", "default": True, "format": "gguf", "files": ["sv.gguf"]}],
+ }
+ (env["specs"] / "sense_asr.json").write_text(json.dumps(spec))
+ probe = acm.read_remote_header
+ seen = []
+
+ def header(
+ repo_id,
+ filename,
+ hf_token = None,
+ *,
+ size = None,
+ ):
+ seen.append((repo_id, filename))
+ if repo_id.startswith("FunAudioLLM/"):
+ return AudioCppHeader("sensevoice-small", "sense_asr")
+ if repo_id == "Jmica/Drama-3-GGUF":
+ return AudioCppHeader("audiocpp", "fish_drama3")
+ return probe(repo_id, filename, hf_token, size = size)
+
+ monkeypatch.setattr(acm, "read_remote_header", header)
+ rows = _rows(catalog.audio_catalog_payload())
+ sense = rows["FunAudioLLM/SenseVoiceSmall-GGUF-audiocpp"]
+ assert sense.workflows == [] and sense.unsupported_reason == catalog._NOT_AUDIO_CPP
+ assert rows["Jmica/Drama-3-GGUF"].workflows == ["speak", "clone"]
+ # The spec's recommended file is the one probed.
+ assert ("Jmica/Drama-3-GGUF", "drama-3-Q4_K_S.gguf") in seen
+
+
+def test_a_spec_dir_read_is_capped_and_ignores_bad_files(env, monkeypatch):
+ (env["specs"] / "huge.json").write_bytes(b" " * (catalog._MAX_SPEC_BYTES + 1))
+ (env["specs"] / "list.json").write_text("[]")
+ (env["specs"] / "evil.json").write_text(json.dumps({"family": "../x", "packages": []}))
+ index = catalog._spec_index(env["specs"])
+ assert set(index) == {"fish_drama3", "kokoro_tts"}
+
+
+def test_a_spec_with_an_empty_gguf_package_does_not_break_the_catalog(env):
+ bad = {"family": "empty_pkg", "tasks": ["tts"], "packages": [{"format": "gguf", "files": []}]}
+ (env["specs"] / "empty_pkg.json").write_text(json.dumps(bad))
+ payload = catalog.audio_catalog_payload()
+ assert payload.source == "hub"
+ assert _rows(payload)[f"{AUDIO_CPP_REPO}/Kokoro-82M-GGUF"].workflows == ["speak"]
+
+
+def test_concurrent_cold_callers_share_one_build(env, monkeypatch):
+ build, builds = catalog._build, []
+
+ def slow(*args):
+ builds.append(1)
+ time.sleep(0.2)
+ return build(*args)
+
+ monkeypatch.setattr(catalog, "_build", slow)
+ threads = [threading.Thread(target = catalog.audio_catalog_payload) for _ in range(4)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+ assert len(builds) == 1
+
+
+def test_a_build_with_a_late_family_probe_is_retried_sooner(env, monkeypatch):
+ clock = [1000.0]
+ monkeypatch.setattr(catalog.time, "monotonic", lambda: clock[0])
+ # Every probe misses the deadline, so New-TTS-GGUF stays unplaced in a Hub answer.
+ monkeypatch.setattr(catalog, "_bounded", lambda jobs: {})
+ for f in env["specs"].iterdir():
+ f.unlink()
+ payload = catalog.audio_catalog_payload()
+ assert payload.source == "hub"
+ assert not _rows(payload)[f"{AUDIO_CPP_REPO}/New-TTS-GGUF"].workflows
+ hub_calls = env["calls"]["hub"]
+ acm._listing_cache.clear()
+ clock[0] += catalog._DEGRADED_TTL_SECONDS + 1
+ catalog.audio_catalog_payload()
+ assert env["calls"]["hub"] == hub_calls + 1
diff --git a/studio/backend/tests/test_audio_cpp_models.py b/studio/backend/tests/test_audio_cpp_models.py
index 276c771619e..1de9bf1e4c9 100644
--- a/studio/backend/tests/test_audio_cpp_models.py
+++ b/studio/backend/tests/test_audio_cpp_models.py
@@ -334,14 +334,17 @@ def test_an_unknown_family_follows_its_spec_tasks_or_is_refused(hub):
assert "Voice activity detection" in vad.unsupported
clone_only = acm.resolve("someone/new_clone_only-GGUF", network = False)
assert list(clone_only.workflows) == ["clone"] and clone_only.clone.reference_text == "optional"
+ new_tts = acm.resolve("someone/new_tts-GGUF", network = False)
+ assert list(new_tts.workflows) == ["speak", "clone"]
+ assert new_tts.clone.reference_text == "optional"
def test_unsupported_task_tokens_are_refused_by_a_readable_name(hub):
for family, tasks, message in (
- ("smart_turn", ["turn"], "Turn detection models are not supported in Studio yet."),
- ("new_svc", ["svc"], "Singing voice conversion models are not supported in Studio yet."),
- ("new_s2s", ["s2s"], "Speech-to-speech models are not supported in Studio yet."),
- ("new_odd", ["odd_task"], "Studio does not support the 'odd_task' task yet."),
+ ("smart_turn", ["turn"], "Turn detection models are not supported in Unsloth Studio yet."),
+ ("new_svc", ["svc"], "Unsloth Studio doesn't support voice conversion models yet."),
+ ("new_s2s", ["s2s"], "Speech-to-speech models are not supported in Unsloth Studio yet."),
+ ("new_odd", ["odd_task"], "Unsloth Studio does not support the 'odd_task' task yet."),
):
repo = f"someone/{family}-GGUF"
_put(_snapshot(hub, repo), "m-q8_0.gguf", _gguf_bytes(family = family, spec = {"tasks": tasks}))
@@ -505,6 +508,8 @@ _CLONE_TABLE = {
"firered_audio": ("tts", False, "optional"),
"vevo2": ("tts", False, "unused"),
"miotts": ("tts", False, "unused"),
+ "mira_tts": ("tts", False, "unused"),
+ "sopro_tts": ("tts", False, "unused"),
"breeze_tts": ("tts", True, "required"),
"omnivoice": ("tts", True, "required"),
"voxcpm1": ("tts", True, "required"),
diff --git a/studio/backend/tests/test_audio_cpp_spec_placement.py b/studio/backend/tests/test_audio_cpp_spec_placement.py
new file mode 100644
index 00000000000..0c48a888d25
--- /dev/null
+++ b/studio/backend/tests/test_audio_cpp_spec_placement.py
@@ -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
+
+"""Which Audio pages a family lands on, from the FAMILIES table or its spec's tasks, and which of
+its GGUFs is the default."""
+
+from __future__ import annotations
+
+import re
+import sys
+from pathlib import Path
+
+import pytest
+
+from core.inference import audio_cpp_models as acm
+from core.inference.audio_cpp_models import AudioCppVariant, RepoFile
+
+_TESTS_DIR = str(Path(__file__).resolve().parent)
+if _TESTS_DIR not in sys.path:
+ sys.path.insert(0, _TESTS_DIR)
+
+from test_audio_cpp_clone_requests import REF, SPEECH, T, TEXT, _backend # noqa: E402
+from test_audio_cpp_models import _gguf_bytes, _put, _snapshot, hub # noqa: E402, F401
+
+
+def _req(*names: str) -> dict:
+ return {"request": [{"name": n, "type": "string", "required": False} for n in names]}
+
+
+# Trimmed from audio.cpp's model_specs (HEAD).
+DRAMA = {
+ "tasks": ["tts", "clone"],
+ "options": _req("reference_text", "references", "seed"),
+ "ui": {"recommended_package": "fish_drama3_q4_experts_q8_backbone"},
+ "packages": [
+ {
+ "id": f"fish_drama3_{p}",
+ "default": p == "q4_experts_q8_backbone",
+ "format": "gguf",
+ "files": [f"drama-3-backbone-{f}.gguf"],
+ }
+ for p, f in (
+ ("q4_experts_q8_backbone", "8bit-experts-Q4_K_S"),
+ ("q3_experts_q8_backbone", "8bit-experts-Q3_K_S"),
+ ("q2_experts_q8_backbone", "8bit-experts-Q2_K"),
+ ("q4_backbone", "4bit-experts-Q4_K_S"),
+ )
+ ],
+}
+KITTEN2 = {
+ "tasks": ["tts", "clone"],
+ "options": _req("voice_id", "seed", "reference_text"),
+ "ui": {"recommended_package": "kitten_tts2_q8_v2"},
+ "packages": [
+ {
+ "id": f"kitten_tts2_{q}",
+ "default": q == "q8_v2",
+ "format": "gguf",
+ "files": [f"kitten-tts2-{q.replace('_', '-')}-multilingual.gguf", "LICENSE"],
+ }
+ for q in ("bf16", "q8_v2", "q4")
+ ],
+}
+SOPRO = {
+ "tasks": ["tts", "clone"],
+ "ui": {"recommended_package": "sopro_v2_turbo_safetensors"},
+ "packages": [
+ {
+ "id": "sopro_v2_turbo_f16",
+ "default": True,
+ "format": "gguf",
+ "files": ["sopro-v2-turbo-f16.gguf"],
+ },
+ {
+ "id": "sopro_v2_turbo_safetensors",
+ "format": "safetensors",
+ "files": ["model.safetensors"],
+ },
+ ],
+}
+LFM2 = {
+ "tasks": ["asr", "tts", "s2s"],
+ "options": _req("language", "seed"),
+ "ui": {"recommended_package": "lfm2_audio_1_5b_q8_0"},
+ "packages": [
+ {
+ "id": "lfm2_audio_1_5b_q8_0",
+ "default": True,
+ "format": "gguf",
+ "files": [
+ f"{p}LFM2.5-Audio-1.5B-Q8_0.gguf" for p in ("", "mmproj-", "vocoder-", "tokenizer-")
+ ],
+ }
+ ],
+}
+MUSIC = {"tasks": ["music"], "options": _req("lyrics", "duration_sec")}
+SFX = {
+ "tasks": ["sfx"],
+ "options": {"request": [{"name": "duration_sec", "min": 0.64, "default": 8}, {"name": "seed"}]},
+}
+
+# family, spec, expected pages
+PLACEMENTS = [
+ ("fish_drama3", DRAMA, {"speak", "clone"}),
+ ("kitten_tts2", KITTEN2, {"speak", "clone"}),
+ ("new_tts_unused", {"tasks": ["tts", "clone"], "options": _req("seed")}, {"speak", "clone"}),
+ ("new_tts_legacy", {"tasks": ["tts", "clone"]}, {"speak", "clone"}),
+ ("mira_tts", {"tasks": ["tts", "clone"], "options": _req("seed")}, {"clone"}),
+ ("sopro_tts", SOPRO, {"clone"}),
+ ("lfm2_audio", LFM2, set()),
+ ("new_lfm2", {"tasks": ["asr", "tts", "s2s"]}, {"speak"}),
+ ("chatterbox", {"tasks": ["clone", "vc"]}, {"clone", "convert"}),
+ ("rvc", {"tasks": ["vc"]}, {"convert"}),
+ *((f, {"tasks": ["sep"]}, {"separate"}) for f in ("htdemucs", "htdemucs_6stems")),
+ *((f, {"tasks": ["sep"]}, {"separate"}) for f in ("bs_roformer", "mel_band_roformer")),
+ ("mossformer2", {"tasks": ["sep"]}, {"separate"}),
+ ("tf_gridnet", {"tasks": ["sep"]}, {"separate"}),
+ ("new_music", MUSIC, {"music"}),
+ ("new_sfx", SFX, {"music"}),
+ ("new_vc", {"tasks": ["vc"]}, set()),
+ ("new_speech_edit", {"tasks": ["edit"]}, set()),
+ ("new_tts_edit", {"tasks": ["tts", "edit"]}, {"speak"}),
+ ("new_design", {"tasks": ["design"]}, {"speak"}),
+ ("new_clone_music", {"tasks": ["clone", "music"]}, {"music"}),
+ ("new_clone_asr", {"tasks": ["clone", "asr"]}, {"transcribe"}),
+]
+
+
+def _resolve(
+ hub,
+ family,
+ spec,
+ files = ("m-q8_0.gguf",),
+):
+ repo = f"someone/{family}-GGUF"
+ snap = _snapshot(hub, repo)
+ for name in files:
+ _put(snap, name, _gguf_bytes(family = family, spec = spec))
+ return acm.resolve(repo, network = False)
+
+
[email protected]("family, spec, pages", PLACEMENTS, ids = [p[0] for p in PLACEMENTS])
+def test_spec_tasks_place_a_family_on_its_pages(hub, family, spec, pages):
+ model = _resolve(hub, family, spec)
+ assert set(model.workflows) == pages
+ assert (model.unsupported is None) == bool(pages)
+
+
+ "family, spec, reference_text",
+ [
+ ("fish_drama3", DRAMA, "required"),
+ ("kitten_tts2", KITTEN2, "required"),
+ ("new_tts_unused", {"tasks": ["tts", "clone"], "options": _req("seed")}, "unused"),
+ ("new_tts_legacy", {"tasks": ["tts", "clone"]}, "optional"),
+ ],
+)
+def test_a_spec_that_clones_speaks_and_clones_on_one_tts_session(hub, family, spec, reference_text):
+ model = _resolve(hub, family, spec)
+ assert model.speaks and model.server_task == "tts"
+ assert model.clone.reference_text == reference_text
+ assert model.workflows["clone"].server_task == "tts"
+
+
[email protected]("family", ["mira_tts", "sopro_tts"])
+def test_reference_only_families_offer_clone_alone(hub, family):
+ model = _resolve(hub, family, {"tasks": ["tts", "clone"]})
+ assert not model.speaks and model.clone.reference_text == "unused"
+ assert model.server_task == "tts"
+
+
+def test_a_spec_derived_clone_runs_on_the_speech_endpoint(hub):
+ model = _resolve(hub, "fish_drama3", DRAMA)
+ backend, server = _backend(model)
+ wav, _rate = backend.generate_audio_response(
+ TEXT, workflow = "clone", audio_inputs = {"reference": REF}, reference_text = T, seed = 7
+ )
+ assert wav[:4] == b"RIFF"
+ ((path, body),) = server.calls
+ assert path == SPEECH and body["voice_ref"] == REF and body["reference_text"] == T
+ assert {b.server_task for b in model.workflows.values()} == {"tts"}
+
+
+def test_spec_derived_music_and_sfx_get_modes(hub):
+ music = _resolve(hub, "new_music", MUSIC).music
+ song = music.mode("song")
+ assert song.lyrics == "optional" and music.fixed_seed is False and music.mode("sfx") is None
+ sfx = _resolve(hub, "new_sfx", SFX).music
+ assert [m.id for m in sfx.modes] == ["sfx"] and sfx.mode("sfx").duration == (1.0, 60.0, 8.0)
+ assert sfx.fixed_seed is True
+ sep = _resolve(hub, "tf_gridnet", {"tasks": ["sep"]})
+ assert sep.separation is not None
+
+
+def test_design_only_spec_runs_voice_design(hub):
+ model = _resolve(hub, "new_design", {"tasks": ["design"]})
+ assert model.server_task == "vdes" and model.clone is None
+
+
+def test_a_multi_file_package_spec_is_refused(hub):
+ model = _resolve(hub, "lfm2_audio", LFM2)
+ assert model.unsupported == acm._MULTI_FILE_PACKAGE
+ assert "multi-file package Unsloth Studio cannot load yet" in model.unsupported
+ assert acm.recommended_gguf_files(LFM2)[0] == "LFM2.5-Audio-1.5B-Q8_0.gguf"
+
+
+ "family, spec", [(f, s) for f, s, pages in PLACEMENTS if pages and f not in acm.FAMILIES]
+)
+def test_a_family_the_runtime_lacks_is_still_refused(hub, monkeypatch, family, spec):
+ monkeypatch.setattr(acm, "runtime_knows_family", lambda name: False)
+ model = _resolve(hub, family, spec)
+ assert model.workflows == {} and "needs a newer audio runtime" in model.unsupported
+
+
[email protected]("family", ["mira_tts", "sopro_tts"])
+def test_a_reference_only_table_family_the_runtime_lacks_is_refused(hub, monkeypatch, family):
+ monkeypatch.setattr(acm, "runtime_knows_family", lambda name: False)
+ model = _resolve(hub, family, {"tasks": ["tts", "clone"]})
+ assert model.workflows == {} and "needs a newer audio runtime" in model.unsupported
+ monkeypatch.setattr(acm, "runtime_knows_family", lambda name: None)
+ acm.forget()
+ assert set(_resolve(hub, family, {"tasks": ["tts", "clone"]}).workflows) == {"clone"}
+
+
+def test_unsupported_messages_say_unsloth_studio():
+ messages = [f.unsupported for f in acm.FAMILIES.values() if f.unsupported]
+ for spec in ({"tasks": t} for t in (["vc"], ["svc"], ["s2s"], ["turn"], ["odd"], [])):
+ messages.append(acm._family_from_spec_tasks("new_x", spec).unsupported)
+ messages.append(acm._family_from_spec_tasks("lfm2_audio", LFM2).unsupported)
+ assert "Unsloth Studio doesn't support voice conversion models yet." in messages
+ for message in messages:
+ assert message and re.search(r"(?<!Unsloth )Studio", message) is None, message
+
+
+def test_recommended_gguf_files():
+ assert acm.recommended_gguf_files(KITTEN2) == ("kitten-tts2-q8-v2-multilingual.gguf",)
+ # The recommended package is safetensors, so the default GGUF package stands in.
+ assert acm.recommended_gguf_files(SOPRO) == ("sopro-v2-turbo-f16.gguf",)
+ assert acm.recommended_gguf_files(None) == () == acm.recommended_gguf_files({"tasks": ["tts"]})
+
+
+def _rank(*files: str) -> list[str]:
+ variants = [AudioCppVariant(acm.quant_label(f), (RepoFile(f, 1),), f) for f in files]
+ return [v.primary for v in sorted(variants, key = acm._variant_rank)]
+
+
+def test_k_and_iq_quants_rank_after_the_established_order():
+ assert acm.quant_label("drama-3-backbone-8bit-experts-Q4_K_S.gguf") == "Q4_K_S"
+ assert _rank("m-Q2_K.gguf", "m-Q3_K_S.gguf", "m-Q4_K_S.gguf") == [
+ "m-Q4_K_S.gguf",
+ "m-Q3_K_S.gguf",
+ "m-Q2_K.gguf",
+ ]
+ assert _rank("m-Q3_K_M.gguf", "m-IQ4_XS.gguf") == ["m-IQ4_XS.gguf", "m-Q3_K_M.gguf"]
+ assert _rank("m-Q4_K.gguf", "m-F32.gguf")[0] == "m-F32.gguf"
+
+
+def test_the_recommended_package_is_the_default_variant(hub):
+ drama = [
+ f"drama-3-backbone-{b}bit-experts-{q}.gguf"
+ for b in (8, 4)
+ for q in ("Q4_K_S", "Q3_K_S", "Q2_K")
+ ]
+ model = _resolve(hub, "fish_drama3", DRAMA, drama)
+ assert len(model.variants) == 6
+ assert model.variant.primary == "drama-3-backbone-8bit-experts-Q4_K_S.gguf"
+ no_pick = _resolve(hub, "fish_drama3_bare", {"tasks": ["tts", "clone"]}, drama)
+ assert no_pick.variant.primary != "drama-3-backbone-8bit-experts-Q4_K_S.gguf"
+ kittens = [f"kitten-tts2-{q}-multilingual.gguf" for q in ("bf16", "q8-v2", "q4")]
+ kitten = _resolve(hub, "kitten_tts2", KITTEN2, kittens)
+ assert kitten.variant.primary == "kitten-tts2-q8-v2-multilingual.gguf"
+ sopros = ["sopro-v2-turbo-q8_0.gguf", "sopro-v2-turbo-f16.gguf"]
+ sopro = _resolve(hub, "sopro_tts", SOPRO, sopros)
+ assert sopro.variant.primary == "sopro-v2-turbo-f16.gguf"
diff --git a/studio/backend/tests/test_mcp_server.py b/studio/backend/tests/test_mcp_server.py
index 7d00c9b3b03..4fee71e1827 100644
--- a/studio/backend/tests/test_mcp_server.py
+++ b/studio/backend/tests/test_mcp_server.py
@@ -44,13 +44,13 @@ SCHEMA_FACTS = [
("generate_image", "output_schema/properties/images/type", "array"),
("generate_image", "output_schema/additionalProperties", False),
("generate_audio", "output_schema/additionalProperties", False),
- ("generate_audio", "parameters/properties", lambda props: "text" in props),
+ ("generate_audio", "parameters/properties", lambda props: {"text", "model"} <= set(props)),
("studio_status", "output_schema/additionalProperties", False),
("studio_status", "parameters", lambda params: params.get("properties", {}) == {}),
(
"list_models",
"parameters/properties",
- lambda props: set(props) == {"kind", "loaded_only", "model"},
+ lambda props: set(props) == {"kind", "loaded_only", "model", "workflow"},
),
(
"load_model",
diff --git a/studio/backend/tests/test_mcp_tools_audio.py b/studio/backend/tests/test_mcp_tools_audio.py
index d4df9a8b1ac..aa10cbc67c1 100644
--- a/studio/backend/tests/test_mcp_tools_audio.py
+++ b/studio/backend/tests/test_mcp_tools_audio.py
@@ -166,6 +166,32 @@ def test_an_enum_option_is_sent_as_the_model_lists_it(monkeypatch, voice, sent,
assert body["options"] == {"voice": sent, "temperature": 0.7}
+TARGET = "audio-cpp/audio.cpp-gguf/Kokoro-82M-GGUF"
+
+
+# ``model`` names the model to run; the loaded model's voices only bind when it is that model.
+ "active,sent,refusal",
+ [
+ ("unsloth/orpheus-3b", "Bob", None),
+ (TARGET, None, "'Bob' is not one of: vivian, ryan"),
+ (TARGET.lower() + "-other", "Bob", None),
+ ],
+)
+def test_a_named_model_skips_the_loaded_models_option_check(monkeypatch, active, sent, refusal):
+ args = {"workflow": "speak", "model": TARGET, "text": "Hi", "options": {"voice": "Bob"}}
+ status = {**CUSTOM_VOICE, "model_identifier": active}
+ routes = {("GET", "/api/inference/status"): status}
+ result, studio = _generate(monkeypatch, args, routes = routes)
+ if refusal:
+ assert result["isError"] is True and refusal in result["content"][0]["text"]
+ assert bodies(studio, "/v1/audio/run") == []
+ return
+ (body,) = bodies(studio, "/v1/audio/run")
+ AudioRunRequest.model_validate(body)
+ assert body["model"] == TARGET and body["options"] == {"voice": sent}
+
+
def test_short_clips_are_inline_and_long_ones_are_links_never_fetched(monkeypatch):
long_clip = _clip("long-1", duration_s = 600.0, sample_rate = 44100)
fetched = []
diff --git a/studio/backend/tests/test_mcp_tools_models.py b/studio/backend/tests/test_mcp_tools_models.py
index 111f034a48c..d605b1e7a33 100644
--- a/studio/backend/tests/test_mcp_tools_models.py
+++ b/studio/backend/tests/test_mcp_tools_models.py
@@ -129,6 +129,28 @@ def test_loaded_only_takes_the_fast_path_for_chat(monkeypatch, kind, expected, r
assert [(path, query) for _m, path, query in studio.state.queries] == [(route, "")]
+ "workflow,expected",
+ [
+ ("speak", ["unsloth/orpheus-3b"]),
+ ("clone", ["unsloth/orpheus-3b"]),
+ ("separate", ["audio-separator/htdemucs"]),
+ ("music", []),
+ ],
+)
+def test_workflow_keeps_the_models_that_run_that_audio_page(monkeypatch, workflow, expected):
+ result, _studio = _list(monkeypatch, {"workflow": workflow})
+ assert [model["id"] for model in result["structuredContent"]["models"]] == expected
+
+
+# Resident chat models carry no audio_workflows, so a workflow filter always reads /v1/models.
+def test_workflow_with_loaded_only_reads_every_model(monkeypatch):
+ args = {"workflow": "speak", "loaded_only": True, "kind": "llm"}
+ result, studio = _list(monkeypatch, args)
+ assert result["structuredContent"]["models"] == []
+ assert [path for _m, path, _q in studio.state.queries] == ["/v1/models"]
+
+
# ``model`` narrows the list to that model and adds its scalar training defaults.
@pytest.mark.parametrize(
"asked", ["unsloth/Qwen3-0.6B", "unsloth/qwen3-0.6b", "unsloth/Qwen3-0.6B:Q4_K_M"]
diff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.py
index 9d56113adf1..2c366326907 100644
--- a/studio/backend/tests/test_openai_auto_switch.py
+++ b/studio/backend/tests/test_openai_auto_switch.py
@@ -12058,22 +12058,25 @@ def test_speech_switch_admission(monkeypatch, audio_type, context, text, instruc
@pytest.mark.parametrize(
- "workflow, speech_type, workflows, admitted",
+ "workflow, speech_type, workflows, admitted, message",
[
- ("separate", None, ["separate"], True),
- ("separate", None, [], False),
- ("clone", "audiocpp_tts", ["speak"], False),
- ("clone", "audiocpp_tts", ["speak", "clone"], True),
+ ("separate", None, ["separate"], True, None),
+ ("separate", None, [], False, "Separate (separate). Unsloth Studio has no Audio page"),
+ ("clone", "audiocpp_tts", ["speak"], False, "Clone (clone). It runs on Text to Speech"),
+ ("clone", "audiocpp_tts", ["speak", "clone"], True, None),
],
)
-def test_audio_workflow_switch_admission(monkeypatch, workflow, speech_type, workflows, admitted):
[email protected]("requested", ["org/B-GGUF", "/srv/models/B-GGUF", r"C:\models\B-GGUF"])
+def test_audio_workflow_switch_admission(
+ monkeypatch, workflow, speech_type, workflows, admitted, message, requested
+):
backend, recorder = _speech_case(monkeypatch, speech_type, gguf = False)
seen = []
monkeypatch.setattr(
inference_route, "_target_audio_workflows", lambda *a: seen.append(a) or workflows
)
call = inference_route._maybe_auto_switch_model(
- "org/B-GGUF",
+ requested,
object(),
"tester",
require_speech = speech_type is not None,
@@ -12087,6 +12090,9 @@ def test_audio_workflow_switch_admission(monkeypatch, workflow, speech_type, wor
asyncio.run(call)
assert error.value.status_code == 400
assert error.value.detail["error"]["param"] == "model"
+ assert error.value.detail["error"]["code"] == "invalid_value"
+ # Names the pages by label and id, with no host path from the request or the target.
+ assert error.value.detail["error"]["message"].startswith(f"B can't run {message}")
# Refused before the resident model is evicted.
assert recorder.calls == [] and backend.model_identifier == "org/A-GGUF"
assert seen == [("/local/B", speech_type)]
diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.ts
index bc249e84c5a..c89c99260cf 100644
--- a/studio/frontend/scripts/check-bundle-budget.ts
+++ b/studio/frontend/scripts/check-bundle-budget.ts
@@ -210,8 +210,12 @@ export const BUDGET = {
// by that growth.
// The audio.cpp v0.9.2 picker rows (#14073) add 253 B raw / 59 B transfer to the eager audio catalog
// table (one machine and build, chunk count unchanged at 95). Raised by that.
- transferBytes: 2_047_608,
- rawBytes: 6_806_087,
+ // The audio "More models" group and catalog refresh (#14072) add 2,559 B raw / 911 B transfer (6,810,132 ->
+ // 6,812,691 B raw, 2,049,298 -> 2,050,209 B transfer against f2ed00705f, one machine and build, Node 24, chunk
+ // count unchanged at 95): the picker rows and catalog hook live in the audio picker the startup chunks load.
+ // Raised by that growth.
+ transferBytes: 2_048_519,
+ rawBytes: 6_808_646,
};
// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering the
diff --git a/studio/frontend/src/features/audio/api.ts b/studio/frontend/src/features/audio/api.ts
index 3a3c23f50ae..aca6453fd9a 100644
--- a/studio/frontend/src/features/audio/api.ts
+++ b/studio/frontend/src/features/audio/api.ts
@@ -8,6 +8,7 @@ import {
formatApiErrorBody,
readFastApiError,
} from "@/lib/format-fastapi-error";
+import type { AudioCatalogResponse } from "./audio-catalog-rows";
import {
type AudioRunRequest,
type AudioSourceRef,
@@ -74,6 +75,12 @@ export async function getAudioDownloadPlan(
return parseJson<AudioDownloadPlan>(response);
}
+/** Every audio.cpp model the backend can place: umbrella folders plus Community repos. */
+export async function fetchAudioCatalog(): Promise<AudioCatalogResponse> {
+ const response = await authFetch("/api/inference/audio/catalog");
+ return parseJson<AudioCatalogResponse>(response);
+}
+
export async function generateAudio(
text: string,
options: GenerateAudioOptions = {},
diff --git a/studio/frontend/src/features/audio/audio-catalog-rows.ts b/studio/frontend/src/features/audio/audio-catalog-rows.ts
new file mode 100644
index 00000000000..a9989525c05
--- /dev/null
+++ b/studio/frontend/src/features/audio/audio-catalog-rows.ts
@@ -0,0 +1,277 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Rows from GET /api/inference/audio/catalog. Relative imports only, so node --test and the
+// catalog check load it directly.
+
+import type { ModelOption } from "../model-picker/components/model-selector/types.ts";
+import {
+ AUDIO_CPP_MODELS,
+ AUDIO_CPP_REPO,
+ AUDIO_CPP_UNOFFERED_FOLDERS,
+ audioCppDisplayName,
+ isAudioCppFolderId,
+} from "./audio-cpp-catalog.ts";
+
+export type AudioCatalogStatus =
+ | "supported"
+ | "community"
+ | "experimental"
+ | "testing"
+ | "wip";
+
+export interface AudioCatalogRow {
+ id: string;
+ repo_id: string;
+ folder: string;
+ source: "umbrella" | "community";
+ display_name: string;
+ family: string | null;
+ task: string;
+ workflows: readonly string[];
+ description: string | null;
+ languages: readonly string[] | null;
+ status: AudioCatalogStatus | null;
+ size_bytes: number | null;
+ downloaded: boolean;
+ unsupported_reason: string | null;
+}
+
+export interface AudioCatalogResponse {
+ source: "hub" | "saved" | "cache";
+ fetched_at: number;
+ runtime_specs: boolean;
+ models: AudioCatalogRow[];
+}
+
+/** Same shape as page-models.ts declares; kept structural so neither file imports the other. */
+export interface PageCatalogEntry {
+ workflows: readonly string[];
+ supported: boolean;
+}
+
+export type AudioCatalogEntry = PageCatalogEntry & AudioCatalogRow;
+
+export function catalogById(
+ rows: readonly AudioCatalogRow[],
+): Map<string, AudioCatalogEntry> {
+ const map = new Map<string, AudioCatalogEntry>();
+ for (const row of rows) {
+ map.set(row.id.trim().toLowerCase(), {
+ ...row,
+ supported: row.unsupported_reason == null && row.workflows.length > 0,
+ });
+ }
+ return map;
+}
+
+/** A More row has no Hub pipeline tag, so a catalog ASR pick names its own: the page then loads
+ * it as speech-to-text instead of speech. */
+export function withCatalogPipelineTag<
+ M extends { pipelineTag?: string | null },
+>(byId: ReadonlyMap<string, { task?: string | null }>, id: string, meta: M): M {
+ if (meta.pipelineTag || byId.get(id.trim().toLowerCase())?.task !== "asr")
+ return meta;
+ return { ...meta, pipelineTag: "automatic-speech-recognition" };
+}
+
+const STATUS_ORDER: readonly string[] = [
+ "supported",
+ "community",
+ "testing",
+ "experimental",
+ "wip",
+];
+
+function statusRank(status: string | null): number {
+ const index = STATUS_ORDER.indexOf(status ?? "supported");
+ return index < 0 ? STATUS_ORDER.length : index;
+}
+
+const SEED_FOLDERS = new Set(
+ AUDIO_CPP_MODELS.filter((m) => isAudioCppFolderId(m.id)).map((m) =>
+ audioCppDisplayName(m.id),
+ ),
+);
+const SEED_IDS = new Set(AUDIO_CPP_MODELS.map((m) => m.id.toLowerCase()));
+
+/** Supported rows the bundled seed does not list: new umbrella folders and Community repos.
+ * With `runtimeSpecs` the backend judged each row against the installed runtime's own specs,
+ * so its verdict wins; without them the static unoffered list still applies. */
+export function catalogMoreRows(
+ rows: readonly AudioCatalogRow[],
+ runtimeSpecs = false,
+): AudioCatalogRow[] {
+ return rows
+ .filter((row) => row.unsupported_reason == null && row.workflows.length > 0)
+ .filter((row) =>
+ row.source === "community"
+ ? !SEED_IDS.has(row.id.toLowerCase())
+ : !SEED_FOLDERS.has(row.folder) &&
+ (runtimeSpecs ||
+ !Object.hasOwn(AUDIO_CPP_UNOFFERED_FOLDERS, row.folder)),
+ )
+ .sort(
+ (a, b) =>
+ statusRank(a.status) - statusRank(b.status) ||
+ a.display_name.localeCompare(b.display_name),
+ );
+}
+
+/** A "More models" row; the picker reads `sizeBytes` for its size column. */
+export function catalogModelOption(
+ row: AudioCatalogRow,
+): ModelOption & { sizeBytes: number | null } {
+ // Named by folder like the seed rows, and a Community repo by its full id: two repos can
+ // share one spec display name, or one repo name.
+ const name = row.folder || row.id;
+ const about = audioRowDescription(row);
+ return {
+ id: row.id,
+ name,
+ isGguf: true,
+ description:
+ row.display_name && row.display_name !== name
+ ? [row.display_name, about].filter(Boolean).join(" · ")
+ : about,
+ sizeBytes: row.size_bytes,
+ };
+}
+
+const WORKFLOW_LABELS: Readonly<Record<string, string>> = {
+ speak: "Text to Speech",
+ clone: "Clone",
+ edit: "Edit",
+ convert: "Convert",
+ music: "Music",
+ separate: "Separate",
+ transcribe: "Transcribe",
+};
+
+const STATUS_LABELS: Readonly<Record<string, string>> = {
+ community: "Community",
+ testing: "Testing",
+ experimental: "Experimental",
+ wip: "Work in progress",
+};
+
+let languageNames: Intl.DisplayNames | null | undefined;
+
+function languageName(code: string): string {
+ if (languageNames === undefined) {
+ try {
+ languageNames = new Intl.DisplayNames(["en"], { type: "language" });
+ } catch {
+ languageNames = null;
+ }
+ }
+ try {
+ const name = languageNames?.of(code);
+ if (name && name.toLowerCase() !== code.toLowerCase()) return name;
+ } catch {
+ // Not a valid BCP 47 tag; show the code.
+ }
+ return code.toUpperCase();
+}
+
+/** One line for the row tooltip, e.g. "Text to Speech, Clone · English, Chinese +3 · Experimental". */
+export function audioRowDescription(row: AudioCatalogRow): string {
+ const parts: string[] = [];
+ const pages = row.workflows.map((w) => WORKFLOW_LABELS[w]).filter(Boolean);
+ if (pages.length > 0) parts.push(pages.join(", "));
+ const codes = (row.languages ?? []).filter(
+ (code) => code && code.toLowerCase() !== "auto",
+ );
+ if (codes.length > 0) {
+ const names = codes.slice(0, 3).map(languageName).join(", ");
+ parts.push(codes.length > 3 ? `${names} +${codes.length - 3}` : names);
+ }
+ const status = row.status ? STATUS_LABELS[row.status] : undefined;
+ if (status) parts.push(status);
+ return parts.join(" · ");
+}
+
+/** Nightly check verdicts for the umbrella repo's folders. A folder in neither list is only a
+ * warning (the backend catalog lists it); a stale UNOFFERED entry is a failure. */
+export function umbrellaFolderFindings(
+ folders: ReadonlySet<string>,
+ seedFolders: ReadonlySet<string> = SEED_FOLDERS,
+ unoffered: Readonly<Record<string, string>> = AUDIO_CPP_UNOFFERED_FOLDERS,
+): { warnings: string[]; failures: string[] } {
+ const warnings: string[] = [];
+ const failures: string[] = [];
+ for (const folder of folders) {
+ if (!seedFolders.has(folder) && !Object.hasOwn(unoffered, folder)) {
+ warnings.push(
+ `${AUDIO_CPP_REPO}: '${folder}/' is not in the bundled seed; Unsloth lists it from /api/inference/audio/catalog`,
+ );
+ }
+ }
+ for (const folder of Object.keys(unoffered)) {
+ if (!folders.has(folder)) {
+ failures.push(
+ `${AUDIO_CPP_REPO}: AUDIO_CPP_UNOFFERED_FOLDERS lists '${folder}', which the repo no longer has`,
+ );
+ }
+ }
+ return { warnings, failures };
+}
+
+export interface AudioCatalogSnapshot {
+ rows: readonly AudioCatalogRow[];
+ byId: ReadonlyMap<string, AudioCatalogEntry>;
+ source: AudioCatalogResponse["source"] | "static";
+ runtimeSpecs: boolean;
+}
+
+const STATIC_SNAPSHOT: AudioCatalogSnapshot = {
+ rows: [],
+ byId: new Map(),
+ source: "static",
+ runtimeSpecs: false,
+};
+
+/** A module-level cache for `useSyncExternalStore`, refetched after `ttlMs` (the server's own
+ * TTL). A failed fetch keeps the last answer, which starts as the static seed, and retries
+ * after `retryMs`. */
+export function createAudioCatalogStore(
+ fetchCatalog: () => Promise<AudioCatalogResponse>,
+ { ttlMs = 300_000, retryMs = 30_000, now = () => Date.now() } = {},
+) {
+ let snapshot = STATIC_SNAPSHOT;
+ let nextFetchAt = 0;
+ let inflight: Promise<void> | null = null;
+ const listeners = new Set<() => void>();
+ return {
+ subscribe(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ },
+ getSnapshot: (): AudioCatalogSnapshot => snapshot,
+ refresh(): Promise<void> {
+ if (inflight || now() < nextFetchAt) return inflight ?? Promise.resolve();
+ inflight = fetchCatalog()
+ .then((response) => {
+ const rows = Array.isArray(response?.models) ? response.models : [];
+ snapshot = {
+ rows,
+ byId: catalogById(rows),
+ source: response.source,
+ runtimeSpecs: response.runtime_specs === true,
+ };
+ // Saved or cached answers are degraded: re-ask as soon as the backend's 30 s TTL lapses.
+ nextFetchAt = now() + (response.source === "hub" ? ttlMs : retryMs);
+ for (const listener of listeners) listener();
+ })
+ .catch(() => {
+ nextFetchAt = now() + retryMs;
+ })
+ .finally(() => {
+ inflight = null;
+ });
+ return inflight;
+ },
+ };
+}
diff --git a/studio/frontend/src/features/audio/audio-cpp-catalog.ts b/studio/frontend/src/features/audio/audio-cpp-catalog.ts
index 1b6eae3e242..830da3e7536 100644
--- a/studio/frontend/src/features/audio/audio-cpp-catalog.ts
+++ b/studio/frontend/src/features/audio/audio-cpp-catalog.ts
@@ -253,7 +253,7 @@ export const AUDIO_CPP_MODELS: readonly AudioCppModel[] = [
},
];
-/** Shared-repo folders the pickers leave out, and why; the nightly catalog check fails on an unclassified folder. */
+/** Shared-repo folders the pickers leave out, and why. The nightly catalog check warns on a folder in neither list (the backend catalog lists it). */
export const AUDIO_CPP_UNOFFERED_FOLDERS: Readonly<Record<string, string>> = {
"Sidon-GGUF": "needs a newer audio runtime",
// Offer it on Transcribe once the Hub's main branch carries it (only on spec-refresh-v0.9.2 for now).
@@ -269,7 +269,7 @@ export const AUDIO_CPP_UNOFFERED_FOLDERS: Readonly<Record<string, string>> = {
"TF-GridNet-GGUF": "needs a newer audio runtime",
"MioCodec-25Hz-44.1kHz-v2-GGUF": "the codec MioTTS downloads and loads with",
"Qwen3-ForcedAligner-0.6B-GGUF": "the aligner Transcribe uses for Qwen3-ASR timestamps",
- "MiniMax-H3-Q4-GGUF": "an audio and video package Studio cannot load yet",
+ "MiniMax-H3-Q4-GGUF": "an audio and video package Unsloth cannot load yet",
"Apollo-GGUF": "audio restoration has no page",
"AudioSR-GGUF": "audio super-resolution has no page",
"UniverSR-GGUF": "audio super-resolution has no page",
diff --git a/studio/frontend/src/features/audio/audio-page.tsx b/studio/frontend/src/features/audio/audio-page.tsx
index 69c075d5a3e..86051409ce5 100644
--- a/studio/frontend/src/features/audio/audio-page.tsx
+++ b/studio/frontend/src/features/audio/audio-page.tsx
@@ -86,29 +86,17 @@ import {
CloneOutput,
CloneRail,
adoptReference,
- clonePageModels,
} from "./pages/clone-page";
-import {
- ConvertFooter,
- ConvertOutput,
- ConvertRail,
- convertPageModels,
-} from "./pages/convert-page";
-import {
- EditFooter,
- EditOutput,
- EditRail,
- editPageModels,
-} from "./pages/edit-page";
+import { ConvertFooter, ConvertOutput, ConvertRail } from "./pages/convert-page";
+import { EditFooter, EditOutput, EditRail } from "./pages/edit-page";
import { useMusicGeneration } from "./hooks/use-music-generation";
-import { MusicOutput, MusicRail, musicPageModels } from "./pages/music-page";
+import { MusicOutput, MusicRail } from "./pages/music-page";
import {
SeparateFooter,
SeparateOutput,
SeparateRail,
- separatePageModels,
} from "./pages/separate-page";
-import { SpeakOutput, SpeakRail, speakPageModels } from "./pages/speak-page";
+import { SpeakOutput, SpeakRail } from "./pages/speak-page";
import { type GenerateBlocker, TtsFooter } from "./pages/tts-workspace";
import { TranscribeFooter, TranscribeOutput, TranscribeRail } from "./pages/transcribe-page";
import type { SendTarget } from "./components/stem-mixer-types";
@@ -124,7 +112,19 @@ import {
transcribeLanguageFor,
transcribeLanguagesFor,
} from "./transcribe-languages";
-import { type AudioPickerRow, audioRowMatchesWorkflow } from "./picker-filter";
+import {
+ type PageModelPrefs,
+ type PageModelRow,
+ pageModels,
+ recommendedPageModels,
+ rowOnPage,
+} from "./page-models";
+import {
+ catalogModelOption,
+ catalogMoreRows,
+ withCatalogPipelineTag,
+} from "./audio-catalog-rows";
+import { useAudioCatalog } from "./hooks/use-audio-catalog";
import {
referenceTranscript,
useAudioCloneStore,
@@ -162,8 +162,6 @@ const HUB_TASKS_BY_MODE = {
let reuseSeq = 0;
const EXPIRED_AT = new Date(0).toISOString();
-const RECOMMENDED_MUSIC_MODELS = ["ACE-Step1.5-GGUF", "Stable-Audio-3-Small-Music-GGUF"];
-
function reuseConvertInputs(clip: AudioGalleryClip) {
const store = useAudioConvertStore.getState();
const sourceId = clip.source_clip_id ?? clip.source_input_id ?? null;
@@ -326,6 +324,11 @@ export function AudioPage({
}, []);
const isMac = usePlatformStore((s) => s.deviceType) === "mac";
+ const audioCatalog = useAudioCatalog(active);
+ const pagePrefs = useMemo<PageModelPrefs>(
+ () => ({ isMac, catalog: audioCatalog.byId }),
+ [isMac, audioCatalog.byId],
+ );
const {
lastSttRepo,
@@ -1064,49 +1067,18 @@ export function AudioPage({
(id: string) => void pickRecommendedModel(id),
[pickRecommendedModel],
);
- const recommendedMusicActions = musicPageModels(MODELS_BY_MODE.speak, isMac)
- .filter((model) =>
- RECOMMENDED_MUSIC_MODELS.some((name) => model.id.endsWith(`/${name}`)),
- )
- .sort(
- (a, b) =>
- RECOMMENDED_MUSIC_MODELS.findIndex((name) => a.id.endsWith(`/${name}`)) -
- RECOMMENDED_MUSIC_MODELS.findIndex((name) => b.id.endsWith(`/${name}`)),
- )
- .map((model) => ({
- label: `use ${model.name}`,
- onClick: () => handlePickRecommended(model.id),
- }));
- const recommendedCloneActions = clonePageModels(MODELS_BY_MODE.speak, isMac)
- .slice(0, 2)
- .map((model) => ({
- label: `use ${model.name}`,
- onClick: () => void pickRecommendedModel(model.id),
- }));
- const recommendedConvertActions = convertPageModels(
- MODELS_BY_MODE.speak,
- isMac,
- )
- .slice(0, 2)
- .map((model) => ({
- label: `use ${model.name}`,
- onClick: () => void pickRecommendedModel(model.id),
- }));
- const recommendedEditActions = editPageModels(MODELS_BY_MODE.speak, isMac)
- .slice(0, 2)
- .map((model) => ({
- label: `use ${model.name}`,
- onClick: () => void pickRecommendedModel(model.id),
- }));
- const recommendedSeparateActions = separatePageModels(
- MODELS_BY_MODE.speak,
- isMac,
- )
- .slice(0, 2)
- .map((model) => ({
- label: `use ${model.name}`,
- onClick: () => void pickRecommendedModel(model.id),
- }));
+ const recommendedActions = (page: AudioWorkflowId) =>
+ recommendedPageModels(page, MODELS_BY_MODE.speak, pagePrefs).map(
+ (model) => ({
+ label: `use ${model.name}`,
+ onClick: () => handlePickRecommended(model.id),
+ }),
+ );
+ const recommendedMusicActions = recommendedActions("music");
+ const recommendedCloneActions = recommendedActions("clone");
+ const recommendedConvertActions = recommendedActions("convert");
+ const recommendedEditActions = recommendedActions("edit");
+ const recommendedSeparateActions = recommendedActions("separate");
// RVC, Seed-VC and MeanVC2 only convert; Speak must not send their users to Clone.
const loadedConvertsOnly =
!!status?.audio_workflows?.includes("convert") &&
@@ -1546,24 +1518,36 @@ export function AudioPage({
document.addEventListener("keydown", onKeyDown);
return () => document.removeEventListener("keydown", onKeyDown);
}, [active]);
+ // Transcribe lists its seed unfiltered; Edit has no spec task, so it gets no catalog rows.
const selectorModels =
mode === "speak"
- ? ttsWorkflow === "music"
- ? musicPageModels(MODELS_BY_MODE.speak, isMac)
- : ttsWorkflow === "clone"
- ? clonePageModels(MODELS_BY_MODE.speak, isMac)
- : ttsWorkflow === "edit"
- ? editPageModels(MODELS_BY_MODE.speak, isMac)
- : ttsWorkflow === "convert"
- ? convertPageModels(MODELS_BY_MODE.speak, isMac)
- : ttsWorkflow === "separate"
- ? separatePageModels(MODELS_BY_MODE.speak, isMac)
- : speakPageModels(MODELS_BY_MODE.speak, isMac)
+ ? pageModels(ttsWorkflow, MODELS_BY_MODE.speak, pagePrefs)
: MODELS_BY_MODE[mode];
+ const selectorMoreModels = useMemo(
+ () =>
+ pageWorkflow === "edit"
+ ? undefined
+ : {
+ label: "More models",
+ models: pageModels(
+ pageWorkflow,
+ catalogMoreRows(
+ audioCatalog.rows,
+ audioCatalog.runtimeSpecs,
+ ).map(catalogModelOption),
+ pagePrefs,
+ ),
+ },
+ [audioCatalog.rows, audioCatalog.runtimeSpecs, pageWorkflow, pagePrefs],
+ );
const selectorRowFilter = useCallback(
- (row: AudioPickerRow) =>
- audioRowMatchesWorkflow(row, pageWorkflow),
- [pageWorkflow],
+ (row: PageModelRow) => rowOnPage(pageWorkflow, row, pagePrefs),
+ [pageWorkflow, pagePrefs],
+ );
+ const selectModel = useCallback(
+ (id: string, meta: Parameters<typeof handleModelSelect>[1]) =>
+ handleModelSelect(id, withCatalogPipelineTag(audioCatalog.byId, id, meta)),
+ [audioCatalog.byId, handleModelSelect],
);
const sttOnDeviceModels = downloadedSttArtifacts.map((artifact) => {
const catalogModel = MODELS_BY_MODE.transcribe.find(
@@ -1716,6 +1700,7 @@ export function AudioPage({
)
}
rowFilter={selectorRowFilter}
+ moreModels={selectorMoreModels}
loadedModelIdOverride={
mode === "transcribe" && sttReady
? (selectedSttRepo ?? undefined)
@@ -1734,7 +1719,7 @@ export function AudioPage({
: undefined
}
value={selectorValue}
- onValueChange={handleModelSelect}
+ onValueChange={selectModel}
onEject={
audioEjectAvailable({
mode,
diff --git a/studio/frontend/src/features/audio/hooks/use-audio-catalog.ts b/studio/frontend/src/features/audio/hooks/use-audio-catalog.ts
new file mode 100644
index 00000000000..cdcadfa040f
--- /dev/null
+++ b/studio/frontend/src/features/audio/hooks/use-audio-catalog.ts
@@ -0,0 +1,25 @@
+// 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 { useEffect, useSyncExternalStore } from "react";
+import { fetchAudioCatalog } from "../api";
+import {
+ type AudioCatalogSnapshot,
+ createAudioCatalogStore,
+} from "../audio-catalog-rows";
+
+const store = createAudioCatalogStore(fetchAudioCatalog);
+const CATALOG_POLL_MS = 30_000;
+
+/** The backend's audio.cpp catalog, shared by every Audio page; the static seed until it lands. */
+export function useAudioCatalog(enabled: boolean): AudioCatalogSnapshot {
+ const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot);
+ useEffect(() => {
+ if (!enabled) return;
+ void store.refresh();
+ // The page stays mounted, so retries and TTL refreshes need a timer; refresh is a no-op until due.
+ const timer = setInterval(() => void store.refresh(), CATALOG_POLL_MS);
+ return () => clearInterval(timer);
+ }, [enabled]);
+ return snapshot;
+}
diff --git a/studio/frontend/src/features/audio/page-models.ts b/studio/frontend/src/features/audio/page-models.ts
new file mode 100644
index 00000000000..a227baa66ea
--- /dev/null
+++ b/studio/frontend/src/features/audio/page-models.ts
@@ -0,0 +1,204 @@
+// 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 lists a model. Free of React so the node test runner can load it directly.
+
+import {
+ AUDIO_CPP_SEP_AUDIO_TYPE,
+ audioCppModelFor,
+ isAudioRuntimeGguf,
+ isCloneAndConvertFamilyId,
+ isCloneOnlyFamilyId,
+ isConvertOnlyFamilyId,
+ isSpeakAndCloneFamilyId,
+} from "./audio-cpp-catalog";
+import {
+ audioTaskFor,
+ isMusicGenerationModel,
+ macTtsCatalogChoiceIsRunnable,
+} from "./catalog";
+import { CONVERT_MODEL_ORDER } from "./convert-policy";
+import {
+ type AudioWorkflowId,
+ audioWorkflowForAudioType,
+ audioWorkflowForTask,
+} from "./workflows";
+
+export interface PageModelRow {
+ id: string;
+ task?: string | null;
+ audioType?: string | null;
+ audioWorkflows?: readonly string[] | null;
+}
+
+export interface PageCatalogEntry {
+ workflows: readonly string[];
+ supported: boolean;
+}
+
+export interface PageModelPrefs {
+ isMac: boolean;
+ /** /api/inference/audio/catalog rows keyed by lower-case id. */
+ catalog?: ReadonlyMap<string, PageCatalogEntry>;
+}
+
+const PAGES: readonly AudioWorkflowId[] = [
+ "speak",
+ "clone",
+ "edit",
+ "convert",
+ "music",
+ "separate",
+ "transcribe",
+];
+
+// Only the audio runtime runs these, so their seed lists hold audio.cpp rows alone.
+const AUDIO_CPP_ONLY_PAGES: ReadonlySet<AudioWorkflowId> = new Set([
+ "clone",
+ "edit",
+ "convert",
+ "separate",
+]);
+
+/** Folder names in the order a page lists them; the rest keep their seed order. */
+export const PAGE_ORDER: Partial<Record<AudioWorkflowId, readonly string[]>> = {
+ clone: ["Qwen3-TTS-12Hz-0.6B-Base-GGUF", "VoxCPM2-GGUF", "Chatterbox-GGUF"],
+ convert: CONVERT_MODEL_ORDER,
+ edit: ["DotTTS-Edit-GGUF", "Vevo2-GGUF", "FireRedAudio-GGUF"],
+ separate: [
+ "HTDemucs-GGUF",
+ "BS-RoFormer-ep368-GGUF",
+ "HTDemucs-6stems-GGUF",
+ "Mel-Band-RoFormer-GGUF",
+ ],
+};
+
+// Music keeps its seed order in the picker; only the empty-state picks are named.
+const RECOMMENDED_MUSIC_MODELS = [
+ "ACE-Step1.5-GGUF",
+ "Stable-Audio-3-Small-Music-GGUF",
+];
+
+const known = (workflows: readonly string[]) =>
+ PAGES.filter((page) => workflows.includes(page));
+
+function catalogEntry(
+ id: string,
+ prefs: PageModelPrefs,
+): PageCatalogEntry | undefined {
+ return prefs.catalog?.get(id.trim().toLowerCase().replace(/\/+$/, ""));
+}
+
+// Hub rows carry no workflows before download, so the name hints and a permissive last step
+// apply to them; seed rows fall back to Speak, as every non-catalog seed is a speech model.
+function pagesFor(
+ row: PageModelRow,
+ prefs: PageModelPrefs,
+ hubRow: boolean,
+): readonly AudioWorkflowId[] {
+ if (row.audioWorkflows && row.audioWorkflows.length > 0) {
+ return known(row.audioWorkflows);
+ }
+ const entry = catalogEntry(row.id, prefs);
+ if (entry?.supported) return known(entry.workflows);
+ // An unsupported entry can mean the backend could not tell the family yet, so it hides only
+ // rows the bundled seed does not know.
+ if (entry && !audioCppModelFor(row.id) && !audioTaskFor(row.id)) return [];
+ if (row.audioType === AUDIO_CPP_SEP_AUDIO_TYPE) return ["separate"];
+ // MiniMax Music 3 is tagged text-to-speech on the Hub.
+ if (isMusicGenerationModel(row.id, row.audioType)) return ["music"];
+ const byTask = audioWorkflowForTask(row.task);
+ if (byTask === "transcribe" || byTask === "music") return [byTask];
+ const catalogModel = audioCppModelFor(row.id);
+ if (catalogModel?.workflows) return known(catalogModel.workflows);
+ if (hubRow) {
+ // Convert first: chatterbox and vevo2 are in the clone-only hint too.
+ if (isCloneAndConvertFamilyId(row.id)) return ["clone", "convert"];
+ if (isConvertOnlyFamilyId(row.id)) return ["convert"];
+ if (isCloneOnlyFamilyId(row.id)) return ["clone"];
+ if (isSpeakAndCloneFamilyId(row.id)) return ["speak", "clone"];
+ }
+ const catalogTask = catalogModel?.task;
+ if (catalogTask === "music") return ["music"];
+ if (catalogTask === "asr") return ["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)];
+ }
+ return hubRow ? PAGES.filter((page) => page !== "separate") : ["speak"];
+}
+
+/** The pages a row may list on: backend workflows, then the fetched catalog, then the seed. */
+export function allowedPages(
+ row: PageModelRow,
+ prefs: PageModelPrefs,
+): AudioWorkflowId[] {
+ return [...pagesFor(row, prefs, true)];
+}
+
+/** The picker's row filter for `page`. */
+export function rowOnPage(
+ page: AudioWorkflowId,
+ row: PageModelRow,
+ prefs: PageModelPrefs,
+): boolean {
+ return pagesFor(row, prefs, true).includes(page);
+}
+
+function runsOnMac(row: PageModelRow, prefs: PageModelPrefs): boolean {
+ return (
+ macTtsCatalogChoiceIsRunnable(row.id) ||
+ isAudioRuntimeGguf(row.id, row.audioType) ||
+ catalogEntry(row.id, prefs) !== undefined
+ );
+}
+
+function rankIn(order: readonly string[], id: string): number {
+ const index = order.findIndex((name) => id.endsWith(`/${name}`));
+ return index === -1 ? order.length : index;
+}
+
+/** The seed or catalog rows `page` lists, in its order. */
+export function pageModels<T extends PageModelRow>(
+ page: AudioWorkflowId,
+ rows: readonly T[],
+ prefs: PageModelPrefs,
+): T[] {
+ return rows
+ .filter(
+ (row) =>
+ pagesFor(row, prefs, false).includes(page) &&
+ (!AUDIO_CPP_ONLY_PAGES.has(page) ||
+ isAudioRuntimeGguf(row.id, row.audioType) ||
+ catalogEntry(row.id, prefs) !== undefined) &&
+ (!prefs.isMac || runsOnMac(row, prefs)),
+ )
+ .map((row, index) => ({ row, index }))
+ .sort(
+ (a, b) =>
+ rankIn(PAGE_ORDER[page] ?? [], a.row.id) -
+ rankIn(PAGE_ORDER[page] ?? [], b.row.id) || a.index - b.index,
+ )
+ .map(({ row }) => row);
+}
+
+/** The two models a page's empty state offers. */
+export function recommendedPageModels<T extends PageModelRow>(
+ page: AudioWorkflowId,
+ rows: readonly T[],
+ prefs: PageModelPrefs,
+): T[] {
+ const listed = pageModels(page, rows, prefs);
+ if (page !== "music") return listed.slice(0, 2);
+ return listed
+ .filter(
+ (row) =>
+ rankIn(RECOMMENDED_MUSIC_MODELS, row.id) <
+ RECOMMENDED_MUSIC_MODELS.length,
+ )
+ .sort(
+ (a, b) =>
+ rankIn(RECOMMENDED_MUSIC_MODELS, a.id) -
+ rankIn(RECOMMENDED_MUSIC_MODELS, b.id),
+ );
+}
diff --git a/studio/frontend/src/features/audio/pages/clone-page.tsx b/studio/frontend/src/features/audio/pages/clone-page.tsx
index 2a7fe95e159..761920536c7 100644
--- a/studio/frontend/src/features/audio/pages/clone-page.tsx
+++ b/studio/frontend/src/features/audio/pages/clone-page.tsx
@@ -9,9 +9,7 @@ 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,
@@ -29,33 +27,6 @@ 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"
diff --git a/studio/frontend/src/features/audio/pages/convert-page.tsx b/studio/frontend/src/features/audio/pages/convert-page.tsx
index 1fb00249b9d..505afb8d5a1 100644
--- a/studio/frontend/src/features/audio/pages/convert-page.tsx
+++ b/studio/frontend/src/features/audio/pages/convert-page.tsx
@@ -19,16 +19,13 @@ import { HugeiconsIcon } from "@hugeicons/react";
import { type ComponentProps, useEffect, useState } from "react";
import { type AudioGalleryClip, fetchAudioBlob } from "../api";
import { audioModelLabel } from "../audio-workspace-utils";
-import { audioCppModelFor, audioCppWorkflowsFor } from "../audio-cpp-catalog";
import { sourceFileUrl } from "../audio-run-request";
-import { macTtsCatalogChoiceIsRunnable } from "../catalog";
import { ABCompare } from "../components/convert-ab-compare";
import { Field } from "../components/field";
import {
AudioHistoryProvider,
AudioSourceInput,
} from "../components/audio-source-input";
-import { CONVERT_MODEL_ORDER } from "../convert-policy";
import {
CONVERT_SOURCE_TEXT_FIELD_ID,
type ConvertGeneration,
@@ -37,34 +34,6 @@ import { useAudioConvertStore } from "../stores/audio-convert-store";
import { AudioToolPanels } from "../tools/tool-panel-host";
import { TtsFooter, TtsOutput, TtsRailFields } from "./tts-workspace";
-function convertRank(id: string): number {
- const index = CONVERT_MODEL_ORDER.findIndex((name) =>
- id.endsWith(`/${name}`),
- );
- return index === -1 ? CONVERT_MODEL_ORDER.length : index;
-}
-
-export function convertPageModels(
- models: ModelOption[],
- isMac: boolean,
-): ModelOption[] {
- return models
- .filter((model) => {
- const entry = audioCppModelFor(model.id);
- return (
- entry !== null &&
- audioCppWorkflowsFor(entry).includes("convert") &&
- (!isMac || macTtsCatalogChoiceIsRunnable(model.id))
- );
- })
- .map((model, index) => ({ model, index }))
- .sort(
- (a, b) =>
- convertRank(a.model.id) - convertRank(b.model.id) || a.index - b.index,
- )
- .map(({ model }) => model);
-}
-
type RailProps = Omit<
ComponentProps<typeof TtsRailFields>,
| "musicGeneration"
diff --git a/studio/frontend/src/features/audio/pages/edit-page.tsx b/studio/frontend/src/features/audio/pages/edit-page.tsx
index bfd687a9f06..416fd8191a2 100644
--- a/studio/frontend/src/features/audio/pages/edit-page.tsx
+++ b/studio/frontend/src/features/audio/pages/edit-page.tsx
@@ -10,9 +10,7 @@ import { SpeechToTextIcon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { type ComponentProps, useEffect, useState } from "react";
import { type AudioGalleryClip, fetchAudioBlob } from "../api";
-import { audioCppModelFor, audioCppWorkflowsFor } from "../audio-cpp-catalog";
import { EDIT_SOURCE_MAX_SECONDS } from "../audio-run-request";
-import { macTtsCatalogChoiceIsRunnable } from "../catalog";
import { ABCompare } from "../components/ab-compare";
import {
AudioHistoryProvider,
@@ -30,38 +28,6 @@ import { useAudioEditStore } from "../stores/audio-edit-store";
import { AudioToolPanels } from "../tools/tool-panel-host";
import { TtsFooter, TtsOutput, TtsRailFields } from "./tts-workspace";
-const EDIT_MODEL_ORDER = [
- "DotTTS-Edit-GGUF",
- "Vevo2-GGUF",
- "FireRedAudio-GGUF",
-];
-
-function editRank(id: string): number {
- const index = EDIT_MODEL_ORDER.findIndex((name) => id.endsWith(`/${name}`));
- return index === -1 ? EDIT_MODEL_ORDER.length : index;
-}
-
-export function editPageModels(
- models: ModelOption[],
- isMac: boolean,
-): ModelOption[] {
- return models
- .filter((model) => {
- const entry = audioCppModelFor(model.id);
- return (
- entry !== null &&
- audioCppWorkflowsFor(entry).includes("edit") &&
- (!isMac || macTtsCatalogChoiceIsRunnable(model.id))
- );
- })
- .map((model, index) => ({ model, index }))
- .sort(
- (a, b) =>
- editRank(a.model.id) - editRank(b.model.id) || a.index - b.index,
- )
- .map(({ model }) => model);
-}
-
type RailProps = Omit<
ComponentProps<typeof TtsRailFields>,
| "musicGeneration"
diff --git a/studio/frontend/src/features/audio/pages/music-page.tsx b/studio/frontend/src/features/audio/pages/music-page.tsx
index 48088a2b78e..bf9a6f370cc 100644
--- a/studio/frontend/src/features/audio/pages/music-page.tsx
+++ b/studio/frontend/src/features/audio/pages/music-page.tsx
@@ -6,13 +6,8 @@ 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 { ModelOption } from "@/features/model-picker/components/model-selector/types";
import type { ComponentProps } from "react";
import type { AudioGalleryClip } from "../api";
-import {
- isMusicGenerationModel,
- macTtsCatalogChoiceIsRunnable,
-} from "../catalog";
import { AudioHistoryProvider } from "../components/audio-source-input";
import { Field } from "../components/field";
import { LyricsEditor } from "../components/lyrics-editor";
@@ -37,17 +32,6 @@ export const MUSIC_DESCRIPTION_FIELD_ID = "music-description";
export const MUSIC_LYRICS_FIELD_ID = "music-lyrics";
export const MUSIC_SFX_FIELD_ID = "music-sfx-prompt";
-export function musicPageModels(
- models: ModelOption[],
- isMac: boolean,
-): ModelOption[] {
- return models.filter(
- (model) =>
- isMusicGenerationModel(model.id, model.audioType) &&
- (!isMac || macTtsCatalogChoiceIsRunnable(model.id)),
- );
-}
-
/** One line under a prompt: example picks while it is empty, the hint once it has text. */
function ExamplesOrHint({
label,
diff --git a/studio/frontend/src/features/audio/pages/separate-page.tsx b/studio/frontend/src/features/audio/pages/separate-page.tsx
index 893a796ff46..b46190265af 100644
--- a/studio/frontend/src/features/audio/pages/separate-page.tsx
+++ b/studio/frontend/src/features/audio/pages/separate-page.tsx
@@ -19,9 +19,8 @@ import {
fetchAudioBlob,
setAudioClipFlags,
} from "../api";
-import { audioCppModelFor, audioCppWorkflowsFor } from "../audio-cpp-catalog";
+import { audioCppModelFor } from "../audio-cpp-catalog";
import { audioModelLabel, formatClipDuration } from "../audio-workspace-utils";
-import { macTtsCatalogChoiceIsRunnable } from "../catalog";
import {
AudioHistoryProvider,
AudioSourceInput,
@@ -52,42 +51,6 @@ import { useAudioSeparateStore } from "../stores/audio-separate-store";
import { AudioToolPanels } from "../tools/tool-panel-host";
import { TtsFooter, TtsRailFields } from "./tts-workspace";
-const SEPARATE_MODEL_ORDER = [
- "HTDemucs-GGUF",
- "BS-RoFormer-ep368-GGUF",
- "HTDemucs-6stems-GGUF",
- "Mel-Band-RoFormer-GGUF",
-];
-
-function separateRank(id: string): number {
- const index = SEPARATE_MODEL_ORDER.findIndex((name) =>
- id.endsWith(`/${name}`),
- );
- return index === -1 ? SEPARATE_MODEL_ORDER.length : index;
-}
-
-export function separatePageModels(
- models: ModelOption[],
- isMac: boolean,
-): ModelOption[] {
- return models
- .filter((model) => {
- const entry = audioCppModelFor(model.id);
- return (
- entry !== null &&
- audioCppWorkflowsFor(entry).includes("separate") &&
- (!isMac || macTtsCatalogChoiceIsRunnable(model.id))
- );
- })
- .map((model, index) => ({ model, index }))
- .sort(
- (a, b) =>
- separateRank(a.model.id) - separateRank(b.model.id) ||
- a.index - b.index,
- )
- .map(({ model }) => model);
-}
-
export function separateOutputStems(
family: string | null | undefined,
modelId: string | null | undefined,
diff --git a/studio/frontend/src/features/audio/pages/speak-page.tsx b/studio/frontend/src/features/audio/pages/speak-page.tsx
index 1233a0d8e60..78d28cbee17 100644
--- a/studio/frontend/src/features/audio/pages/speak-page.tsx
+++ b/studio/frontend/src/features/audio/pages/speak-page.tsx
@@ -2,23 +2,8 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
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";
-export function speakPageModels(
- models: ModelOption[],
- isMac: boolean,
-): ModelOption[] {
- return models.filter(
- (model) =>
- !isMusicGenerationModel(model.id, model.audioType) &&
- audioCppModelSpeaks(model.id) &&
- (!isMac || macTtsCatalogChoiceIsRunnable(model.id)),
- );
-}
-
export function SpeakRail(
props: Omit<ComponentProps<typeof TtsRailFields>, "musicGeneration">,
) {
diff --git a/studio/frontend/src/features/audio/picker-filter.ts b/studio/frontend/src/features/audio/picker-filter.ts
index c439cee5a40..1205c6f9915 100644
--- a/studio/frontend/src/features/audio/picker-filter.ts
+++ b/studio/frontend/src/features/audio/picker-filter.ts
@@ -3,20 +3,8 @@
// Free of app imports so the node test runner can load it directly.
-import {
- AUDIO_CPP_SEP_AUDIO_TYPE,
- audioCppModelFor,
- isCloneAndConvertFamilyId,
- isCloneOnlyFamilyId,
- isConvertOnlyFamilyId,
- isSpeakAndCloneFamilyId,
-} from "./audio-cpp-catalog";
-import { isMusicGenerationModel } from "./catalog";
-import {
- type AudioWorkflowId,
- audioWorkflowForAudioType,
- audioWorkflowForTask,
-} from "./workflows";
+import { rowOnPage } from "./page-models";
+import type { AudioWorkflowId } from "./workflows";
export interface AudioPickerRow {
id?: string | null;
@@ -29,49 +17,5 @@ export function audioRowMatchesWorkflow(
row: AudioPickerRow,
workflow: AudioWorkflowId,
): boolean {
- if (row.audioWorkflows && row.audioWorkflows.length > 0) {
- return row.audioWorkflows.includes(workflow);
- }
- if (row.audioType === AUDIO_CPP_SEP_AUDIO_TYPE) {
- return workflow === "separate";
- }
- // MiniMax Music 3 is tagged text-to-speech on the Hub.
- if (isMusicGenerationModel(row.id, row.audioType)) return workflow === "music";
- const byTask = audioWorkflowForTask(row.task);
- if (byTask === "transcribe" || byTask === "music") {
- return byTask === workflow;
- }
- const catalogModel = audioCppModelFor(row.id);
- if (catalogModel?.workflows) {
- return catalogModel.workflows.includes(workflow);
- }
- // Hub search rows carry no backend workflows before download: name the families by repo.
- // Convert first: chatterbox and vevo2 are in the clone-only hint too.
- if (isCloneAndConvertFamilyId(row.id)) {
- return workflow === "clone" || workflow === "convert";
- }
- if (isConvertOnlyFamilyId(row.id)) {
- return workflow === "convert";
- }
- 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";
- }
- if (catalogTask === "asr") {
- return workflow === "transcribe";
- }
- if (workflow === "separate") {
- return false;
- }
- 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;
+ return rowOnPage(workflow, { ...row, id: row.id ?? "" }, { isMac: false });
}
diff --git a/studio/frontend/src/features/model-picker/components/model-selector.tsx b/studio/frontend/src/features/model-picker/components/model-selector.tsx
index 8b4acbee377..24ea2d12fcf 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-selector.tsx
@@ -148,6 +148,11 @@ interface ModelSelectorProps {
/** The one opaque on-device artifact kind this task runtime may load. */
opaqueKind?: "diffusers_pipeline" | "diffusers_modular_pipeline";
rowFilter?: ModelPickerRowFilter;
+ /** A second Recommended group under its own label, e.g. "More models". */
+ moreModels?: {
+ label: string;
+ models: (ModelOption & { sizeBytes?: number | null })[];
+ };
/** Hub filter the Search Hub button opens with. Also shows Search Hub on curated task pickers. */
hubCapability?: HubCapabilityFilter;
/** Tasks the Search Hub link narrows the Audio filter to, when the page's runs differ from `task`. */
@@ -384,6 +389,7 @@ function ModelSelectorContent({
communityModelPolicy,
opaqueKind,
rowFilter,
+ moreModels,
}: {
open: boolean;
models: ModelOption[];
@@ -417,6 +423,10 @@ function ModelSelectorContent({
communityModelPolicy?: CommunityModelPolicy;
opaqueKind?: "diffusers_pipeline" | "diffusers_modular_pipeline";
rowFilter?: ModelPickerRowFilter;
+ moreModels?: {
+ label: string;
+ models: (ModelOption & { sizeBytes?: number | null })[];
+ };
}) {
const t = useT();
const hasSelection = Boolean(value);
@@ -697,6 +707,7 @@ function ModelSelectorContent({
communityModelPolicy={communityModelPolicy}
opaqueKind={opaqueKind}
rowFilter={rowFilter}
+ moreModels={moreModels}
npu={npu}
section={effectiveHubSection}
sectionToggle={
@@ -763,6 +774,7 @@ export function ModelSelector({
communityModelPolicy = "none",
opaqueKind,
rowFilter,
+ moreModels,
hubCapability,
hubTask,
placeholder,
@@ -783,6 +795,9 @@ export function ModelSelector({
const optionById = useMemo(() => {
const all = new Map<string, ModelOption>();
+ for (const model of moreModels?.models ?? []) {
+ all.set(model.id, model);
+ }
for (const model of models) {
all.set(model.id, model);
}
@@ -825,7 +840,7 @@ export function ModelSelector({
});
}
return all;
- }, [externalModels, loraModels, models]);
+ }, [externalModels, loraModels, models, moreModels]);
// A task-owned quant names the trigger only while the trigger shows that loaded model.
const triggerGgufVariant =
@@ -985,6 +1000,7 @@ export function ModelSelector({
communityModelPolicy={communityModelPolicy}
opaqueKind={opaqueKind}
rowFilter={rowFilter}
+ moreModels={moreModels}
/>
</Popover>
);
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/audio-picker-policy.ts b/studio/frontend/src/features/model-picker/components/model-selector/audio-picker-policy.ts
index 3a0d2f446a4..b485a51a24d 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/audio-picker-policy.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/audio-picker-policy.ts
@@ -362,6 +362,9 @@ export function curatedAudioInventoryMatches({
catalogTask: "tts" | "stt" | null | undefined;
pickerTask: string | readonly string[] | null | undefined;
}): boolean {
+ // An active id with no seed artifact is a fetched catalog row the page already scoped (a
+ // downloaded TF-GridNet reports audio-to-audio, which the Separate picker's tasks leave out).
+ if (isActiveCatalogArtifact && catalogScope == null && pickerTask?.length) return true;
if (
!isActiveCatalogArtifact ||
catalogScope !== "audio" ||
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.ts b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.ts
index 96a95df3fcc..313dc024289 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.ts
@@ -8,11 +8,9 @@
import assert from "node:assert/strict";
+import { umbrellaFolderFindings } from "../../../audio/audio-catalog-rows.ts";
import {
- AUDIO_CPP_MODELS,
AUDIO_CPP_REPO,
- AUDIO_CPP_UNOFFERED_FOLDERS,
- audioCppDisplayName,
isAudioCppFolderId,
} from "../../../audio/audio-cpp-catalog.ts";
@@ -1642,22 +1640,10 @@ async function checkCatalogAgainstTheHub(catalogs: CatalogGroup[][]): Promise<st
.filter((parts) => parts.length > 1)
.map((parts) => parts[0]),
);
- const offered = AUDIO_CPP_MODELS.filter((m) => isAudioCppFolderId(m.id)).map((m) =>
- audioCppDisplayName(m.id),
- );
- const unoffered = Object.keys(AUDIO_CPP_UNOFFERED_FOLDERS);
- for (const folder of folders) {
- if (!offered.includes(folder) && !unoffered.includes(folder)) {
- failures.push(
- `${repoId}: '${folder}/' is in neither AUDIO_CPP_MODELS nor AUDIO_CPP_UNOFFERED_FOLDERS -- classify it`,
- );
- }
- }
- for (const folder of unoffered) {
- if (!folders.has(folder)) {
- failures.push(`${repoId}: AUDIO_CPP_UNOFFERED_FOLDERS lists '${folder}', which the repo no longer has`);
- }
- }
+ // A new folder is only a warning: the backend catalog lists it without a seed edit.
+ const findings = umbrellaFolderFindings(folders);
+ for (const warning of findings.warnings) console.warn(`::warning::${warning}`);
+ failures.push(...findings.failures);
}
const declaredFiles = [
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.tsx
index e1b9d16f2ed..0171be53f14 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
@@ -3080,6 +3080,7 @@ export function HubModelPicker({
opaqueKind,
npu,
rowFilter,
+ moreModels,
}: {
models: ModelOption[];
/** Task-runtime downloads using a cache layout the shared Hub inventory cannot represent (for
@@ -3120,6 +3121,11 @@ export function HubModelPicker({
opaqueKind?: "diffusers_pipeline" | "diffusers_modular_pipeline";
npu?: NpuPickerSource;
rowFilter?: ModelPickerRowFilter;
+ /** A second Recommended group under its own ListLabel; rows reuse the recommended renderer. */
+ moreModels?: {
+ label: string;
+ models: (ModelOption & { sizeBytes?: number | null })[];
+ };
}) {
const gpu = useGpuInfo();
const inferenceGpu = useInferenceGpuInfo();
@@ -3277,11 +3283,11 @@ export function HubModelPicker({
// hasGgufSuffix is the fallback rather than conflating unknown with known-not-GGUF.
const modelGgufIds = useMemo(() => {
const ids = new Set<string>();
- for (const model of models) {
+ for (const model of [...models, ...(moreModels?.models ?? [])]) {
if (model.isGguf) ids.add(model.id.toLowerCase());
}
return ids;
- }, [models]);
+ }, [models, moreModels]);
// Both listings contribute GGUF hints so a tag-only GGUF still expands variants instead of loading as a checkpoint.
const resultGgufIds = useMemo(() => {
const ids = new Set<string>();
@@ -3455,12 +3461,16 @@ export function HubModelPicker({
() =>
new Set(
task && catalog
- ? models
- .filter((model) => artifactForRepoId(model.id, catalog) !== null)
- .map((model) => model.id.trim().toLowerCase())
+ ? [
+ ...models.filter(
+ (model) => artifactForRepoId(model.id, catalog) !== null,
+ ),
+ // Catalog rows the seed lacks, so a downloaded new folder still lists On Device.
+ ...(moreModels?.models ?? []),
+ ].map((model) => model.id.trim().toLowerCase())
: [],
),
- [catalog, models, task],
+ [catalog, models, moreModels, task],
);
const pickerInventory = useChatPickerInventory({
enabled: true,
@@ -4124,6 +4134,57 @@ export function HubModelPicker({
chatSupportedCheckpointQuant,
]);
+ const moreById = useMemo(
+ () =>
+ new Map(
+ (moreModels?.models ?? []).map((model) => [model.id.toLowerCase(), model]),
+ ),
+ [moreModels],
+ );
+ // The "More" group: page-filtered by the caller, then the row, format and fit filters the
+ // recommended rows above use, with no repeats.
+ const moreRows = useMemo<HfModelResult[]>(() => {
+ const above = new Set(recommendedRows.map((r) => r.id.toLowerCase()));
+ const source = loadScopedGpu(inferenceGpu, Boolean(task));
+ return (moreModels?.models ?? [])
+ .filter((model) => !above.has(model.id.toLowerCase()))
+ .filter((model) => !rowFilter || rowFilter({ id: model.id }))
+ .filter((model) => !isHiddenModelId(model.id))
+ .filter((model) =>
+ matchesFormatFilter(model.id, model.isGguf ?? true, formatFilter),
+ )
+ .map((model) => ({
+ id: model.id,
+ downloads: 0,
+ likes: 0,
+ isGguf: model.isGguf ?? true,
+ estimatedSizeBytes: model.sizeBytes ?? undefined,
+ }))
+ .filter(
+ (row) =>
+ !fitOnDeviceOnly ||
+ cachedIdFor(row.id) !== null ||
+ hfModelFitsDevice(row, source, {
+ budgetFraction,
+ mediaLoad: diffusionLoad,
+ hostPooledMemory: gpu.loadDeviceSharesHostMemory,
+ gpuCount: source.deviceCount,
+ }),
+ );
+ }, [
+ moreModels,
+ recommendedRows,
+ rowFilter,
+ formatFilter,
+ fitOnDeviceOnly,
+ cachedIdFor,
+ inferenceGpu,
+ gpu,
+ task,
+ budgetFraction,
+ diffusionLoad,
+ ]);
+
// Per-row meta and VRAM badge from the recommended listing's own metadata, with the curated
// seeds behind it: a listing row wins, and a curated row it never returns keeps its chip.
const recommendedMeta = useMemo(() => {
@@ -4187,6 +4248,7 @@ export function HubModelPicker({
...recommendedSearch.results,
...catalogSeedRows,
...communityBrowse.results,
+ ...moreRows,
]) {
if (map.has(r.id)) continue;
const isG = isKnownGgufRepo(r.id);
@@ -4262,6 +4324,7 @@ export function HubModelPicker({
recommendedSearch.results,
communityBrowse.results,
catalogSeedRows,
+ moreRows,
catalog,
catalogFit,
task,
@@ -5391,13 +5454,17 @@ export function HubModelPicker({
return (
// Seeds included: recommendedIds hides downloaded models, which the unfiltered Recommended
// list still paints, so without them a curated pick vanishes from search once on disk.
- searchableRecommendedIds(catalogSeedIds, recommendedIds)
+ dedupe([
+ ...searchableRecommendedIds(catalogSeedIds, recommendedIds),
+ ...moreRows.map((r) => r.id),
+ ])
// What the row shows, plus the vendor id a mirror row answers to.
.filter((id) =>
pickerSearchMatches(
id,
aliasesOf(id),
- catalog ? curatedRow(id).name : null,
+ moreById.get(id.toLowerCase())?.name ??
+ (catalog ? curatedRow(id).name : null),
q,
),
)
@@ -5411,13 +5478,20 @@ export function HubModelPicker({
!fitOnDeviceOnly ||
cachedIdFor(id) !== null ||
runsCheckpointQuant({ id }) ||
- searchRowFits({ id }),
+ // A More row's catalog size, as browse judged it: its id alone may be unsizable.
+ searchRowFits({
+ id,
+ estimatedSizeBytes:
+ moreById.get(id.toLowerCase())?.sizeBytes ?? undefined,
+ }),
)
);
}, [
showHfSection,
debouncedQuery,
catalogSeedIds,
+ moreRows,
+ moreById,
recommendedIds,
aliasesOf,
catalog,
@@ -5786,8 +5860,9 @@ export function HubModelPicker({
}
if (section === "recommended") {
+ // The More group renders right after the recommended rows, so it continues the same order.
keys.push(
- ...recommendedRows
+ ...[...recommendedRows, ...moreRows]
.filter((r) => !loadedRowIds.has(r.id.toLowerCase()))
.map((r) => makeModelOptionKey("recommended", r.id)),
);
@@ -5816,6 +5891,7 @@ export function HubModelPicker({
sortedLmStudio,
lmStudioCollapsed,
recommendedRows,
+ moreRows,
section,
showHfSection,
sortedLocalDir,
@@ -8402,7 +8478,8 @@ export function HubModelPicker({
{showNpuBrowse ? (
<ListLabel divider={!npuBrowseFolded}>Unsloth</ListLabel>
) : null}
- {recommendedRows.length === 0 &&
+ {/* Catalog rows already listed below stand in for a pending or failed Hub list. */}
+ {recommendedRows.length + moreRows.length === 0 &&
recommendedEmpty === "loading" ? (
<div className="flex items-center gap-2 px-5 py-3">
<Spinner className="size-3 text-muted-foreground" />
@@ -8410,33 +8487,53 @@ export function HubModelPicker({
Loading models…
</span>
</div>
- ) : recommendedRows.length === 0 &&
+ ) : recommendedRows.length + moreRows.length === 0 &&
recommendedEmpty === "failed" ? (
<HubFailureHint
message={recommendedSearch.error}
onRetry={recommendedSearch.retry}
/>
- ) : recommendedRows.length === 0 ? (
+ ) : recommendedRows.length + moreRows.length === 0 ? (
<div className="px-2.5 py-2 text-xs text-muted-foreground">
No models found.
</div>
) : (
- recommendedRows.map((r) => {
+ [...recommendedRows, ...moreRows].map((r, index) => {
const id = r.id;
- if (loadedRowIds.has(id.toLowerCase())) return null;
+ const more = moreById.get(id.toLowerCase());
+ const moreLabel =
+ index === recommendedRows.length && moreModels ? (
+ <ListLabel key="more-models" divider>
+ {moreModels.label}
+ </ListLabel>
+ ) : null;
+ if (loadedRowIds.has(id.toLowerCase())) return moreLabel;
const info = recommendedMeta.get(id);
const isG = isKnownGgufRepo(id);
const optionKey = makeModelOptionKey("recommended", id);
return (
<div key={id}>
+ {moreLabel}
{renderHubModelRow(
id,
<ModelRow
- label={curatedRow(id).name}
+ label={more?.name ?? curatedRow(id).name}
tags={curatedRow(id).tags}
hubUrl={hubRepoUrl(id)}
+ tooltipText={
+ more?.description ? (
+ <>
+ <span className="block break-words">
+ {more.name}
+ </span>
+ <span className="block text-ui-10 mt-1">
+ {more.description}
+ </span>
+ </>
+ ) : undefined
+ }
alignMeta="hub"
- showSize={hubRowsShowSize}
+ showSize={hubRowsShowSize || Boolean(more)}
// Without the owner a community row reads as an unsloth upload.
hideOwner={isUnslothOwned(id)}
downloaded={cachedIdFor(id) !== null}
@@ -8550,7 +8647,10 @@ export function HubModelPicker({
{renderHubModelRow(
id,
<ModelRow
- label={curatedRow(id).name}
+ label={
+ moreById.get(id.toLowerCase())?.name ??
+ curatedRow(id).name
+ }
tags={curatedRow(id).tags}
hubUrl={hubRepoUrl(id)}
alignMeta="hub"
diff --git a/studio/frontend/tests/audio-catalog-rows.test.ts b/studio/frontend/tests/audio-catalog-rows.test.ts
new file mode 100644
index 00000000000..bb89cd5e3f2
--- /dev/null
+++ b/studio/frontend/tests/audio-catalog-rows.test.ts
@@ -0,0 +1,284 @@
+// 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 {
+ audioRowDescription,
+ catalogById,
+ catalogModelOption,
+ catalogMoreRows,
+ createAudioCatalogStore,
+ umbrellaFolderFindings,
+ withCatalogPipelineTag,
+} = await import("../src/features/audio/audio-catalog-rows.ts");
+type Row = Parameters<typeof audioRowDescription>[0];
+
+const REPO = "audio-cpp/audio.cpp-gguf";
+
+function row(over: Partial<Row>): Row {
+ const folder = over.folder ?? "New-TTS-GGUF";
+ return {
+ id: `${REPO}/${folder}`,
+ repo_id: REPO,
+ folder,
+ source: "umbrella",
+ display_name: folder,
+ family: "new_tts",
+ task: "tts",
+ workflows: ["speak"],
+ description: null,
+ languages: null,
+ status: "supported",
+ size_bytes: 1024,
+ downloaded: false,
+ unsupported_reason: null,
+ ...over,
+ };
+}
+
+test("More rows skip the seed, UNOFFERED and unsupported rows, and keep Community rows in status order", () => {
+ const rows = [
+ row({ folder: "Kokoro-82M-GGUF" }),
+ row({ folder: "Sidon-GGUF" }),
+ row({
+ folder: "Broken-GGUF",
+ workflows: [],
+ unsupported_reason:
+ "Unsloth Studio could not tell which model family this is.",
+ }),
+ row({ folder: "Zeta-GGUF", display_name: "Zeta", status: "wip" }),
+ row({ folder: "Beta-GGUF", display_name: "Beta", status: "experimental" }),
+ row({ folder: "Alpha-GGUF", display_name: "Alpha" }),
+ row({
+ id: "Jmica/Drama-3-GGUF",
+ repo_id: "Jmica/Drama-3-GGUF",
+ folder: "",
+ source: "community",
+ display_name: "Drama 3",
+ status: "community",
+ workflows: ["speak", "clone"],
+ }),
+ ];
+ assert.deepEqual(
+ catalogMoreRows(rows).map((r) => r.display_name),
+ ["Alpha", "Drama 3", "Beta", "Zeta"],
+ );
+ // Judged against the installed runtime's specs, a supported UNOFFERED folder is listed.
+ assert.deepEqual(
+ catalogMoreRows(rows, true).map((r) => r.display_name),
+ ["Alpha", "Sidon-GGUF", "Drama 3", "Beta", "Zeta"],
+ );
+});
+
+test("catalogById keys by lower-case id; an option carries name, description and size", () => {
+ const byId = catalogById([
+ row({ folder: "A-GGUF" }),
+ row({ folder: "B-GGUF", workflows: [], unsupported_reason: "no" }),
+ ]);
+ assert.equal(byId.get(`${REPO}/a-gguf`)?.supported, true);
+ assert.equal(byId.get(`${REPO}/b-gguf`)?.supported, false);
+ const option = catalogModelOption(
+ row({ display_name: "New TTS", size_bytes: 2048 }),
+ );
+ assert.deepEqual(
+ [option.name, option.isGguf, option.sizeBytes, option.description],
+ ["New-TTS-GGUF", true, 2048, "New TTS · Text to Speech"],
+ );
+ const community = catalogModelOption(
+ row({
+ folder: "",
+ id: "Jmica/Drama-3-GGUF",
+ display_name: "Jmica/Drama-3-GGUF",
+ }),
+ );
+ assert.deepEqual(
+ [community.name, community.description],
+ ["Jmica/Drama-3-GGUF", "Text to Speech"],
+ );
+});
+
+test("audioRowDescription names pages, up to three languages and the status", () => {
+ assert.equal(
+ audioRowDescription(
+ row({
+ workflows: ["speak", "clone"],
+ languages: ["en", "zh", "ja", "ko", "de"],
+ status: "experimental",
+ }),
+ ),
+ "Text to Speech, Clone · English, Chinese, Japanese +2 · Experimental",
+ );
+ for (const languages of [["auto"], null]) {
+ assert.equal(
+ audioRowDescription(row({ languages, status: null })),
+ "Text to Speech",
+ );
+ }
+ assert.equal(
+ audioRowDescription(row({ languages: ["zz-not-a-tag-%"] })),
+ "Text to Speech · ZZ-NOT-A-TAG-%",
+ );
+});
+
+test("an unclassified umbrella folder warns; a stale UNOFFERED entry fails", () => {
+ const { warnings, failures } = umbrellaFolderFindings(
+ new Set(["Kokoro-82M-GGUF", "Brand-New-GGUF"]),
+ new Set(["Kokoro-82M-GGUF"]),
+ { "Gone-GGUF": "needs a newer audio runtime" },
+ );
+ assert.equal(warnings.length, 1);
+ assert.match(
+ warnings[0],
+ /'Brand-New-GGUF\/' is not in the bundled seed; Unsloth lists it/,
+ );
+ assert.deepEqual(failures, [
+ `${REPO}: AUDIO_CPP_UNOFFERED_FOLDERS lists 'Gone-GGUF', which the repo no longer has`,
+ ]);
+});
+
+test("a failed catalog fetch leaves the static seed, with no rows", async () => {
+ let calls = 0;
+ const store = createAudioCatalogStore(async () => {
+ calls += 1;
+ throw new Error("offline");
+ });
+ await store.refresh();
+ assert.deepEqual(store.getSnapshot().rows, []);
+ assert.equal(store.getSnapshot().source, "static");
+ assert.equal(store.getSnapshot().runtimeSpecs, false);
+ await store.refresh();
+ assert.equal(calls, 1, "a failure is not refetched on every render");
+});
+
+test("a fetched catalog notifies and is cached for the TTL", async () => {
+ let clock = 0;
+ let calls = 0;
+ const store = createAudioCatalogStore(
+ async () => {
+ calls += 1;
+ return {
+ source: "hub",
+ fetched_at: 1,
+ runtime_specs: true,
+ models: [row({})],
+ };
+ },
+ { now: () => clock },
+ );
+ let notified = 0;
+ store.subscribe(() => {
+ notified += 1;
+ });
+ await store.refresh();
+ assert.equal(store.getSnapshot().source, "hub");
+ assert.equal(store.getSnapshot().runtimeSpecs, true);
+ assert.equal(store.getSnapshot().byId.size, 1);
+ await store.refresh();
+ clock = 300_001;
+ await store.refresh();
+ assert.deepEqual([calls, notified], [2, 2]);
+});
+
+test("the picker renders the More group with ListLabel through the row filter", () => {
+ const src = readSrc(
+ "features/model-picker/components/model-selector/pickers.tsx",
+ );
+ assert.match(
+ src,
+ /<ListLabel key="more-models" divider>\s*\{moreModels\.label\}/,
+ );
+ assert.match(src, /\[\.\.\.recommendedRows, \.\.\.moreRows\]\.map/);
+ // More rows join the roving option list in drawn order, so each gets its own option id.
+ const keys = src.slice(
+ src.indexOf("const hubOptionKeys"),
+ src.indexOf("const selectedHubOptionKey"),
+ );
+ assert.match(
+ keys,
+ /\.\.\.\[\.\.\.recommendedRows, \.\.\.moreRows\]\s*\.filter\(\(r\) => !loadedRowIds\.has/,
+ );
+ assert.match(
+ src,
+ /\.filter\(\(model\) => !rowFilter \|\| rowFilter\(\{ id: model\.id \}\)\)/,
+ );
+ // The format and fit filters the Recommended rows obey apply to More rows too.
+ const more = src.slice(
+ src.indexOf("const moreRows"),
+ src.indexOf("const recommendedMeta"),
+ );
+ assert.match(
+ more,
+ /matchesFormatFilter\(model\.id, model\.isGguf \?\? true, formatFilter\)/,
+ );
+ assert.match(
+ more,
+ /!fitOnDeviceOnly \|\|\s*cachedIdFor\(row\.id\) !== null \|\|\s*hfModelFitsDevice\(/,
+ );
+ // An empty, loading or failed Recommended list still shows the More group.
+ assert.match(
+ src,
+ /recommendedRows\.length \+ moreRows\.length === 0 &&\s*recommendedEmpty === "loading"/,
+ );
+ assert.match(
+ src,
+ /recommendedRows\.length \+ moreRows\.length === 0 &&\s*recommendedEmpty === "failed"/,
+ );
+ assert.match(src, /recommendedRows\.length \+ moreRows\.length === 0 \?/);
+ const selector = readSrc(
+ "features/model-picker/components/model-selector.tsx",
+ );
+ assert.equal(selector.match(/moreModels=\{moreModels\}/g)?.length, 2);
+ assert.match(
+ readSrc("features/audio/hooks/use-audio-catalog.ts"),
+ /createAudioCatalogStore\(fetchAudioCatalog\)/,
+ );
+});
+
+test("a catalog ASR pick carries the speech-recognition tag so it loads on Transcribe", () => {
+ const asr = row({
+ folder: "New-ASR-GGUF",
+ task: "asr",
+ workflows: ["transcribe"],
+ });
+ const tts = row({ folder: "New-TTS-GGUF" });
+ const byId = catalogById([asr, tts]);
+ const meta = { pipelineTag: null as string | null, isGguf: true };
+ assert.equal(
+ withCatalogPipelineTag(byId, asr.id.toUpperCase(), meta).pipelineTag,
+ "automatic-speech-recognition",
+ );
+ assert.equal(withCatalogPipelineTag(byId, tts.id, meta), meta);
+ const tagged = { ...meta, pipelineTag: "text-to-speech" };
+ assert.equal(withCatalogPipelineTag(byId, asr.id, tagged), tagged);
+ assert.match(
+ readSrc("features/audio/audio-page.tsx"),
+ /handleModelSelect\(id, withCatalogPipelineTag\(audioCatalog\.byId, id, meta\)\)/,
+ );
+});
+
+test("the persistent Audio page keeps retrying and refreshing the catalog while it is active", () => {
+ const hook = readSrc("features/audio/hooks/use-audio-catalog.ts");
+ assert.match(hook, /setInterval\(\(\) => void store\.refresh\(\), CATALOG_POLL_MS\)/);
+ assert.match(hook, /return \(\) => clearInterval\(timer\)/);
+ assert.match(readSrc("features/audio/audio-page.tsx"), /useAudioCatalog\(active\)/);
+});
+
+test("a saved or cached catalog is re-asked after the retry interval, not the TTL", async () => {
+ let clock = 0;
+ let calls = 0;
+ const store = createAudioCatalogStore(
+ async () => {
+ calls += 1;
+ return { source: "saved", fetched_at: 1, runtime_specs: false, models: [row({})] };
+ },
+ { now: () => clock },
+ );
+ await store.refresh();
+ clock = 30_001;
+ await store.refresh();
+ assert.equal(calls, 2);
+});
diff --git a/studio/frontend/tests/audio-page-models.test.ts b/studio/frontend/tests/audio-page-models.test.ts
new file mode 100644
index 00000000000..335a87da623
--- /dev/null
+++ b/studio/frontend/tests/audio-page-models.test.ts
@@ -0,0 +1,222 @@
+// 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 { allowedPages, pageModels, recommendedPageModels, rowOnPage } =
+ await import("../src/features/audio/page-models.ts");
+const { audioModelsForTask } = await import("../src/features/audio/catalog.ts");
+const { AUDIO_CPP_MODELS, audioCppWorkflowsFor } = await import(
+ "../src/features/audio/audio-cpp-catalog.ts"
+);
+
+type Prefs = Parameters<typeof pageModels>[2];
+const SEED = audioModelsForTask("tts");
+const NEW_ID = "audio-cpp/audio.cpp-gguf/New-TTS-GGUF";
+const catalog = (
+ entries: Record<string, { workflows: string[]; supported?: boolean }>,
+) =>
+ new Map(
+ Object.entries(entries).map(([id, e]) => [
+ id.toLowerCase(),
+ {
+ workflows: e.workflows,
+ supported: e.supported ?? e.workflows.length > 0,
+ },
+ ]),
+ );
+const ids = (
+ page: Parameters<typeof pageModels>[0],
+ prefs: Prefs,
+ rows = SEED,
+) => pageModels(page, rows, prefs).map((row) => row.id);
+const folder = (id: string) => id.split("/").pop();
+
+test("each page lists the seed models whose catalog entry runs there, in the page's order", () => {
+ for (const page of ["clone", "edit", "convert", "separate"] as const) {
+ const expected = SEED.filter((row) => {
+ const entry = AUDIO_CPP_MODELS.find(
+ (m) => m.id.toLowerCase() === row.id.toLowerCase(),
+ );
+ return entry && audioCppWorkflowsFor(entry).includes(page);
+ }).map((row) => row.id);
+ assert.deepEqual(
+ [...ids(page, { isMac: false })].sort(),
+ [...expected].sort(),
+ page,
+ );
+ }
+ assert.deepEqual(ids("clone", { isMac: false }).slice(0, 3).map(folder), [
+ "Qwen3-TTS-12Hz-0.6B-Base-GGUF",
+ "VoxCPM2-GGUF",
+ "Chatterbox-GGUF",
+ ]);
+ assert.equal(folder(ids("separate", { isMac: false })[0]), "HTDemucs-GGUF");
+ assert.equal(folder(ids("edit", { isMac: false })[0]), "DotTTS-Edit-GGUF");
+ // Music keeps its seed order; only the empty state names its two picks.
+ const music = ids("music", { isMac: false });
+ assert.deepEqual(
+ music,
+ SEED.filter((row) => music.includes(row.id)).map((row) => row.id),
+ );
+ assert.deepEqual(
+ recommendedPageModels("music", SEED, { isMac: false }).map((r) =>
+ folder(r.id),
+ ),
+ ["ACE-Step1.5-GGUF", "Stable-Audio-3-Small-Music-GGUF"],
+ );
+ assert.equal(
+ recommendedPageModels("clone", SEED, { isMac: false }).length,
+ 2,
+ );
+});
+
+test("a catalog model outside the seed lands on the pages the backend names", () => {
+ const prefs = {
+ isMac: false,
+ catalog: catalog({ [NEW_ID]: { workflows: ["speak", "clone"] } }),
+ };
+ const rows = [...SEED, { id: NEW_ID, name: "New TTS" }];
+ assert.ok(ids("speak", prefs, rows).includes(NEW_ID));
+ assert.ok(ids("clone", prefs, rows).includes(NEW_ID));
+ assert.ok(!ids("convert", prefs, rows).includes(NEW_ID));
+ assert.ok(rowOnPage("clone", { id: NEW_ID, task: "text-to-speech" }, prefs));
+ assert.ok(
+ !rowOnPage("convert", { id: NEW_ID, task: "text-to-speech" }, prefs),
+ );
+ // Ids match whatever their case.
+ assert.ok(rowOnPage("clone", { id: NEW_ID.toUpperCase() }, prefs));
+});
+
+test("Speak keeps the curated non-GGUF models and Clone stays audio.cpp-only", () => {
+ const speak = ids("speak", { isMac: false });
+ const clone = ids("clone", { isMac: false });
+ const curated = speak.filter(
+ (id) => !id.toLowerCase().startsWith("audio-cpp/"),
+ );
+ assert.ok(curated.length > 0);
+ for (const id of curated) assert.ok(!clone.includes(id), id);
+ assert.ok(
+ speak.some((id) => /orpheus|csm/i.test(id)),
+ "a curated speech model is on Speak",
+ );
+});
+
+test("on a Mac a catalog model is runnable, an unknown non-audio.cpp model is not", () => {
+ const prefs = {
+ isMac: true,
+ catalog: catalog({
+ "jmica/drama-3-gguf": { workflows: ["speak", "clone"] },
+ }),
+ };
+ const rows = [
+ { id: "Jmica/Drama-3-GGUF", name: "Drama 3" },
+ { id: "someone/Unknown-TTS", name: "Unknown" },
+ ];
+ assert.deepEqual(ids("speak", prefs, rows), ["Jmica/Drama-3-GGUF"]);
+ assert.deepEqual(ids("speak", { isMac: false }, rows), [
+ "Jmica/Drama-3-GGUF",
+ "someone/Unknown-TTS",
+ ]);
+});
+
+test("backend workflows beat the catalog, which beats the seed, which beats the name hints", () => {
+ const kokoro =
+ AUDIO_CPP_MODELS.find((m) => m.id.endsWith("/Kokoro-82M-GGUF"))?.id ?? "";
+ const prefs = {
+ isMac: false,
+ catalog: catalog({ [kokoro]: { workflows: ["clone"] } }),
+ };
+ assert.deepEqual(
+ allowedPages({ id: kokoro, audioWorkflows: ["music"] }, prefs),
+ ["music"],
+ );
+ assert.deepEqual(allowedPages({ id: kokoro }, prefs), ["clone"]);
+ assert.deepEqual(
+ allowedPages({ id: kokoro, task: "text-to-speech" }, { isMac: false }),
+ ["speak"],
+ );
+ const mio = "x/MioTTS-GGUF";
+ assert.deepEqual(
+ allowedPages({ id: mio, task: "text-to-speech" }, { isMac: false }),
+ ["clone"],
+ );
+ assert.deepEqual(
+ allowedPages(
+ { id: mio, task: "text-to-speech" },
+ {
+ isMac: false,
+ catalog: catalog({ [mio]: { workflows: ["speak"] } }),
+ },
+ ),
+ ["speak"],
+ );
+});
+
+test("an unsupported catalog model lands on no page", () => {
+ const prefs = {
+ isMac: false,
+ catalog: catalog({ [NEW_ID]: { workflows: [] } }),
+ };
+ assert.deepEqual(
+ allowedPages({ id: NEW_ID, task: "text-to-speech" }, prefs),
+ [],
+ );
+ for (const page of ["speak", "clone", "music", "transcribe"] as const) {
+ assert.deepEqual(ids(page, prefs, [{ id: NEW_ID, name: "New" }]), [], page);
+ }
+});
+
+test("an unsupported catalog entry does not hide a model the seed knows", () => {
+ // A degraded catalog says "could not tell which model family this is" for seed folders.
+ const degraded = {
+ isMac: false,
+ catalog: catalog(
+ Object.fromEntries(SEED.map((m) => [m.id, { workflows: [] }])),
+ ),
+ };
+ for (const page of ["speak", "clone", "edit", "convert", "music"] as const) {
+ assert.deepEqual(ids(page, degraded), ids(page, { isMac: false }), page);
+ }
+ const stt = audioModelsForTask("stt");
+ const sttDegraded = {
+ isMac: false,
+ catalog: catalog(
+ Object.fromEntries(stt.map((m) => [m.id, { workflows: [] }])),
+ ),
+ };
+ for (const model of stt) {
+ assert.equal(
+ rowOnPage(
+ "transcribe",
+ { id: model.id, task: "automatic-speech-recognition" },
+ sttDegraded,
+ ),
+ true,
+ model.id,
+ );
+ }
+});
+
+test("the Audio page builds its picker lists from pageModels and the catalog hook", () => {
+ const page = readSrc("features/audio/audio-page.tsx");
+ assert.match(page, /const audioCatalog = useAudioCatalog\(active\);/);
+ assert.match(
+ page,
+ /pageModels\(ttsWorkflow, MODELS_BY_MODE\.speak, pagePrefs\)/,
+ );
+ assert.match(
+ page,
+ /rowOnPage\(pageWorkflow, row, pagePrefs\),\s*\[pageWorkflow, pagePrefs\]/,
+ );
+ assert.match(page, /pageWorkflow === "edit"\s*\?\s*undefined/);
+ assert.match(page, /moreModels=\{selectorMoreModels\}/);
+ assert.doesNotMatch(
+ page,
+ /\b(speak|clone|edit|convert|separate|music)PageModels\b/,
+ );
+});
diff --git a/studio/frontend/tests/audio-picker-filter.test.ts b/studio/frontend/tests/audio-picker-filter.test.ts
index 8113e1f0b2c..b9b34f6d5bb 100644
--- a/studio/frontend/tests/audio-picker-filter.test.ts
+++ b/studio/frontend/tests/audio-picker-filter.test.ts
@@ -16,6 +16,9 @@ const { audioModelsForTask, isMusicGenerationModel } = await import(
const { AUDIO_CPP_MODELS, audioCppModelSpeaks, audioCppWorkflowsFor } =
await import("../src/features/audio/audio-cpp-catalog.ts");
+const { searchRowFitsDevice } = await import(
+ "../src/features/model-picker/components/model-selector/recommended-fit.ts"
+);
type Workflow = "speak" | "clone" | "edit" | "convert" | "music" | "transcribe";
const WORKFLOWS: Workflow[] = [
@@ -376,3 +379,26 @@ test("the image edit-keyword hiding stays off audio pickers", () => {
const calls = pickers.match(/isImageEditModel\([^)]*\)/g) ?? [];
assert.equal(calls.length, 4);
});
+
+test("a More row keeps its catalog size when search judges its fit", () => {
+ // TF-GridNet: no seed metadata and no parameter count in its name, so only its size sizes it.
+ const id = "audio-cpp/audio.cpp-gguf/TF-GridNet-GGUF";
+ const gpu = {
+ available: true,
+ memoryTotalGb: 24,
+ maxDeviceMemoryGb: 24,
+ loadDeviceMemoryGb: 24,
+ systemRamAvailableGb: 0,
+ budgetKnown: true,
+ };
+ const opts = { isGguf: true, gpu, inferenceGpu: gpu, taskScoped: true };
+ assert.equal(searchRowFitsDevice({ id }, opts), false);
+ assert.equal(searchRowFitsDevice({ id, estimatedSizeBytes: 32_792_096 }, opts), true);
+ const pickers = readSrc("features/model-picker/components/model-selector/pickers.tsx");
+ const body = pickers.slice(pickers.indexOf("const filteredRecommendedIds = useMemo("));
+ const block = body.slice(0, body.indexOf("\n }, ["));
+ assert.match(
+ block,
+ /searchRowFits\(\{\s*id,\s*estimatedSizeBytes:\s*moreById\.get\(id\.toLowerCase\(\)\)\?\.sizeBytes/,
+ );
+});
diff --git a/studio/frontend/tests/audio-picker-policy.test.ts b/studio/frontend/tests/audio-picker-policy.test.ts
index e2bb7267534..1de8c68c95a 100644
--- a/studio/frontend/tests/audio-picker-policy.test.ts
+++ b/studio/frontend/tests/audio-picker-policy.test.ts
@@ -84,6 +84,38 @@ test("curated downloaded STT artifacts override generic metadata only in Transcr
);
});
+test("a page-scoped catalog row the seed lacks lists On Device in its Audio picker", () => {
+ assert.equal(
+ curatedAudioInventoryMatches({
+ isActiveCatalogArtifact: true,
+ catalogScope: undefined,
+ catalogTask: undefined,
+ pickerTask: ["text-to-speech", "text-to-audio"],
+ }),
+ true,
+ );
+ for (const pickerTask of [undefined, []]) {
+ assert.equal(
+ curatedAudioInventoryMatches({
+ isActiveCatalogArtifact: true,
+ catalogScope: undefined,
+ catalogTask: undefined,
+ pickerTask,
+ }),
+ false,
+ );
+ }
+ assert.equal(
+ curatedAudioInventoryMatches({
+ isActiveCatalogArtifact: false,
+ catalogScope: undefined,
+ catalogTask: undefined,
+ pickerTask: ["text-to-speech"],
+ }),
+ false,
+ );
+});
+
test("non-audio catalogs and unfiltered Chat get no downloaded-task exception", () => {
assert.equal(
curatedAudioInventoryMatches({
diff --git a/studio/frontend/tests/hub-recommended-format.test.ts b/studio/frontend/tests/hub-recommended-format.test.ts
index 5781054bbea..a9cb892dd81 100644
--- a/studio/frontend/tests/hub-recommended-format.test.ts
+++ b/studio/frontend/tests/hub-recommended-format.test.ts
@@ -156,7 +156,7 @@ test("the chat picker lists FP8 / NVFP4 checkpoints the GPU runs, whatever their
// The curated-search fit gate waives size for them too.
assert.match(
picker,
- /cachedIdFor\(id\) !== null \|\|\s*runsCheckpointQuant\(\{ id \}\) \|\|\s*searchRowFits\(\{ id \}\)/,
+ /cachedIdFor\(id\) !== null \|\|\s*runsCheckpointQuant\(\{ id \}\) \|\|[\s\S]{0,120}?searchRowFits\(\{\s*id\b/,
);
// Task pages (images, audio) keep their own formats.
assert.match(