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: add audio page with tts/stt create tab, train tab, and openai audio endpoints (#7984)

Maheswar Kumard20db3f1f09d
diff --git a/.github/workflows/studio-backend-ci.yml b/.github/workflows/studio-backend-ci.yml
index eb3a24d5209..22bd7f2cdb8 100644
--- a/.github/workflows/studio-backend-ci.yml
+++ b/.github/workflows/studio-backend-ci.yml
@@ -88,7 +88,10 @@ jobs:
pip install \
python-multipart aiofiles sqlalchemy cryptography psutil \
pyyaml jinja2 mammoth unpdf requests \
- 'numpy<3' pytest pytest-asyncio httpx
+ 'numpy<3' pytest pytest-asyncio httpx \
+ soundfile librosa
+ # soundfile + librosa: test_audio_dataset_decode importorskips both, so without
+ # them the no-torchcodec decode path is silently untested here.
# Torch CPU + transformers are required by a chunk of the backend test
# suite (gpu_selection, kv_cache_estimation, utils). CPU-only torch
# keeps the install ~250 MB / ~1 min on a clean runner.
diff --git a/studio/backend/core/inference/audio_errors.py b/studio/backend/core/inference/audio_errors.py
new file mode 100644
index 00000000000..3c708677375
--- /dev/null
+++ b/studio/backend/core/inference/audio_errors.py
@@ -0,0 +1,45 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Audio errors that are safe to show a client verbatim.
+
+``safe_error_detail`` flattens everything to "An internal error occurred", right for a
+failure but wrong for a capability answer, where the reason is the whole reply. These
+carry no path or user input, so the route passes them straight through.
+"""
+
+from __future__ import annotations
+
+
+# Tagged on the worker's audio_error payload so the parent recognises the case
+# without matching on prose.
+AUDIO_UNSUPPORTED_CODE = "audio_unsupported_backend"
+
+
+class AudioGenerationCancelledError(RuntimeError):
+ """The generation was stopped rather than failing.
+
+ A bare RuntimeError hit the route's generic handler, so an idle auto-unload
+ interrupting a Speak reported HTTP 500 instead of a retryable cancellation.
+ """
+
+
+class AudioBackendUnsupportedError(RuntimeError):
+ """The model loaded fine; this backend cannot do this audio task.
+
+ No retry, shorter input or freed memory helps.
+ """
+
+ def __init__(
+ self,
+ detail: str,
+ *,
+ hint: str | None = None,
+ ):
+ self.detail = detail
+ self.hint = hint
+ super().__init__(detail if not hint else f"{detail} {hint}")
+
+ @property
+ def message(self) -> str:
+ return self.args[0] if self.args else self.detail
diff --git a/studio/backend/core/inference/audio_gallery.py b/studio/backend/core/inference/audio_gallery.py
new file mode 100644
index 00000000000..9f6b99d3698
--- /dev/null
+++ b/studio/backend/core/inference/audio_gallery.py
@@ -0,0 +1,325 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Disk-backed persistence for generated TTS audio clips.
+
+Each clip is a pair under ``studio_root()/audio``: ``{id}.wav`` holds the bytes and
+``{id}.json`` the recipe (a WAV has no portable text chunk). A lone file is not a
+valid record. Dumb storage: the route owns the schema, this reads, writes and sorts.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import uuid
+from collections.abc import Callable
+from pathlib import Path
+from typing import Any, Optional
+
+from loggers import get_logger
+from utils.paths import ensure_dir, studio_root
+
+logger = get_logger(__name__)
+
+# ids are file stems; restrict to safe chars so a crafted id cannot escape the directory
+_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,128}$")
+
+
+def gallery_dir() -> Path:
+ return ensure_dir(studio_root() / "audio")
+
+
+def save(wav_bytes: bytes, meta: dict[str, Any]) -> dict[str, Any]:
+ """Persist WAV bytes plus their recipe sidecar; return the record.
+
+ Staged then renamed in, wav first: the sidecar is the pair's commit marker. On any
+ failure every artifact is removed, so no invisible orphan wav is left behind.
+ """
+ audio_id = uuid.uuid4().hex
+ directory = gallery_dir()
+ wav_path = directory / f"{audio_id}.wav"
+ wav_tmp = directory / f".{audio_id}.wav.tmp"
+ sidecar = directory / f"{audio_id}.json"
+ sidecar_tmp = directory / f".{audio_id}.json.tmp"
+ try:
+ wav_tmp.write_bytes(wav_bytes)
+ sidecar_tmp.write_text(json.dumps(meta), encoding = "utf-8")
+ os.replace(wav_tmp, wav_path)
+ os.replace(sidecar_tmp, sidecar)
+ except BaseException:
+ for path in (wav_tmp, sidecar_tmp, wav_path, sidecar):
+ try:
+ path.unlink(missing_ok = True)
+ except OSError:
+ pass
+ raise
+ _prune_to_cap()
+ return _record(audio_id, meta)
+
+
+# The OpenAI-compatible /v1/audio/speech route persists every call, so an automated client
+# can grow the gallery until the disk fills. Bounded here rather than at that route so the
+# UI's own runaway is covered too. Generous by default: this is a convenience gallery, and
+# the clip is returned to the caller either way.
+_MAX_CLIPS_ENV = "UNSLOTH_AUDIO_GALLERY_MAX_CLIPS"
+_DEFAULT_MAX_CLIPS = 2000
+
+# A count alone does not bound the disk: 2000 clips of maximum-length speech is tens of
+# gigabytes, and the cap exists to stop /v1/audio/speech filling the disk. Whichever limit
+# binds first wins.
+_MAX_BYTES_ENV = "UNSLOTH_AUDIO_GALLERY_MAX_BYTES"
+_DEFAULT_MAX_BYTES = 5 * 1024 * 1024 * 1024
+
+
+def _max_clips() -> int:
+ """0, or any non-numeric value such as "off", disables pruning.
+
+ An unset variable is the only case that takes the default: restoring it for a value the
+ operator did set would delete recordings they had asked to keep.
+ """
+ return _env_limit(_MAX_CLIPS_ENV, _DEFAULT_MAX_CLIPS)
+
+
+def _max_bytes() -> int:
+ return _env_limit(_MAX_BYTES_ENV, _DEFAULT_MAX_BYTES)
+
+
+def _env_limit(name: str, default: int) -> int:
+ raw = os.environ.get(name)
+ if raw is None:
+ return default
+ try:
+ return max(0, int(raw.strip()))
+ except (AttributeError, ValueError):
+ return 0
+
+
+def _clip_bytes(audio_id: str) -> int:
+ try:
+ return (gallery_dir() / f"{audio_id}.wav").stat().st_size
+ except OSError:
+ return 0
+
+
+def _prune_to_cap() -> int:
+ """Drop the oldest owned pairs beyond the count or byte cap; return the count removed.
+
+ Best-effort: a save must not fail because housekeeping did. Only Studio-owned pairs are
+ considered, so a foreign or orphan wav is never destroyed.
+ """
+ cap = _max_clips()
+ byte_cap = _max_bytes()
+ if cap <= 0 and byte_cap <= 0:
+ return 0
+ try:
+ entries = _list_audio_entries()
+ except Exception: # noqa: BLE001 - never fail the save that triggered this
+ return 0
+
+ # Newest first, so the index where either budget runs out is the cut point. The newest
+ # clip is always kept: it is the one the caller just generated, and dropping it would
+ # make a single oversized request look like a silent failure.
+ keep = len(entries) if cap <= 0 else min(cap, len(entries))
+ if byte_cap > 0:
+ running = 0
+ for index, (record, _cursor) in enumerate(entries[:keep]):
+ running += _clip_bytes(record["id"])
+ if running > byte_cap and index > 0:
+ keep = index
+ break
+ if keep >= len(entries):
+ return 0
+
+ removed = 0
+ for record, _cursor in entries[keep:]:
+ try:
+ if delete(record["id"]):
+ removed += 1
+ except Exception: # noqa: BLE001
+ continue
+ if removed:
+ logger.info(
+ "audio_gallery.pruned: removed %d clip(s) over the %d clip / %d byte cap",
+ removed,
+ cap,
+ byte_cap,
+ )
+ return removed
+
+
+def _record(audio_id: str, meta: dict[str, Any]) -> dict[str, Any]:
+ return {
+ **meta,
+ "id": audio_id,
+ "url": f"/api/inference/audio/gallery/{audio_id}/file",
+ }
+
+
+def audio_path(audio_id: str) -> Optional[Path]:
+ """Resolve an id to its on-disk WAV, or None if missing or unsafe."""
+ if not _ID_RE.match(audio_id):
+ return None
+ path = gallery_dir() / f"{audio_id}.wav"
+ # defence in depth: confirm the resolved path is still inside the gallery
+ try:
+ path.resolve().relative_to(gallery_dir().resolve())
+ except ValueError:
+ return None
+ return path if path.is_file() else None
+
+
+def _sidecar_path(audio_id: str) -> Path:
+ return gallery_dir() / f"{audio_id}.json"
+
+
+# key-presence ownership test: a hand-dropped wav with a partial sidecar is never counted as ours nor destroyed
+_REQUIRED_META = (
+ "prompt",
+ "model",
+ "audio_type",
+ "sample_rate",
+ "duration_s",
+ "created_at",
+)
+
+
+def _read_meta(sidecar: Path) -> Optional[dict[str, Any]]:
+ try:
+ raw = sidecar.read_text(encoding = "utf-8")
+ except (OSError, UnicodeError):
+ return None
+ try:
+ meta = json.loads(raw)
+ except (ValueError, TypeError):
+ return None
+ # a parseable dict is not enough: a foreign or different-schema sidecar lacks the required keys
+ if not isinstance(meta, dict) or any(k not in meta for k in _REQUIRED_META):
+ return None
+ return meta
+
+
+def owned_audio_path(audio_id: str) -> Optional[Path]:
+ """Resolve an id to its WAV only for a Studio-owned clip (readable sidecar).
+
+ The serve route uses this rather than audio_path() so a guessed stem for a
+ hand-dropped or orphan WAV cannot be streamed out."""
+ path = audio_path(audio_id)
+ if path is None or _read_meta(_sidecar_path(audio_id)) is None:
+ return None
+ return path
+
+
+def _mtime(path: Path) -> float:
+ try:
+ return path.stat().st_mtime
+ except OSError:
+ return 0.0
+
+
+GalleryCursor = tuple[float, str]
+
+
+def _list_audio_entries(
+ limit: Optional[int] = None,
+ offset: int = 0,
+ *,
+ before: Optional[GalleryCursor] = None,
+ valid: Optional[Callable[[dict[str, Any]], bool]] = None,
+) -> list[tuple[dict[str, Any], GalleryCursor]]:
+ try:
+ paths = list(gallery_dir().glob("*.wav"))
+ except OSError:
+ return []
+ keyed_paths = [((_mtime(path), path.stem), path) for path in paths]
+ keyed_paths.sort(key = lambda item: item[0], reverse = True)
+ want = None if limit is None else offset + limit
+ entries = []
+ for cursor, path in keyed_paths:
+ if before is not None and cursor >= before:
+ continue
+ meta = _read_meta(_sidecar_path(path.stem))
+ if meta is None:
+ continue
+ record = _record(path.stem, meta)
+ if valid is not None and not valid(record):
+ continue
+ entries.append((record, cursor))
+ if want is not None and len(entries) >= want:
+ break
+ return entries[offset:] if limit is None else entries[offset : offset + limit]
+
+
+def list_audio(
+ limit: Optional[int] = None,
+ offset: int = 0,
+ *,
+ before: Optional[GalleryCursor] = None,
+ valid: Optional[Callable[[dict[str, Any]], bool]] = None,
+) -> list[dict[str, Any]]:
+ """A newest-first window of clips for infinite scroll.
+
+ Ordered by WAV mtime; only the window's sidecars are read, and a file without its
+ pair is skipped. ``valid`` filters BEFORE pagination, so offset, limit and has_more
+ all count over the accepted-record domain. ``before`` is an exclusive, stable cursor
+ for callers that must tolerate deletions between pages."""
+ return [record for record, _ in _list_audio_entries(limit, offset, before = before, valid = valid)]
+
+
+def list_audio_page(
+ limit: int,
+ offset: int = 0,
+ *,
+ before: Optional[GalleryCursor] = None,
+ valid: Optional[Callable[[dict[str, Any]], bool]] = None,
+) -> list[tuple[dict[str, Any], GalleryCursor]]:
+ """Return records with their stable pagination keys for the HTTP route."""
+ return _list_audio_entries(limit, offset, before = before, valid = valid)
+
+
+def delete(audio_id: str) -> bool:
+ """Remove both files of an owned pair; True if the WAV existed and was ours.
+
+ WAV first: sidecar-first then failing would lose a clip with no retry, while this
+ leaves at worst an orphan sidecar list_audio ignores."""
+ path = audio_path(audio_id)
+ if path is None:
+ return False
+ # only delete a pair we own; a foreign or orphan wav must not be destroyed by a guessed id
+ if _read_meta(_sidecar_path(audio_id)) is None:
+ return False
+ try:
+ path.unlink()
+ except OSError as exc:
+ logger.warning("audio_gallery.delete_failed: %s", exc)
+ return False
+ try:
+ _sidecar_path(audio_id).unlink()
+ except OSError:
+ pass
+ return True
+
+
+def clear() -> int:
+ """Delete every Studio-owned pair (readable sidecar); return the count removed.
+ Foreign and orphan WAVs are preserved, since list_audio already hides them."""
+ removed = 0
+ try:
+ paths = list(gallery_dir().glob("*.wav"))
+ except OSError:
+ return 0
+ for path in paths:
+ if _read_meta(_sidecar_path(path.stem)) is None:
+ continue
+ # wav first; if it cannot be unlinked, leave the sidecar so the clip stays listable
+ try:
+ path.unlink()
+ except OSError:
+ continue
+ removed += 1
+ try:
+ _sidecar_path(path.stem).unlink()
+ except OSError:
+ pass
+ return removed
diff --git a/studio/backend/core/inference/inference.py b/studio/backend/core/inference/inference.py
index e73b441d7d8..4495b318bc4 100644
--- a/studio/backend/core/inference/inference.py
+++ b/studio/backend/core/inference/inference.py
@@ -416,9 +416,7 @@ class InferenceBackend:
else:
# base_model is an HF ID — download it.
from huggingface_hub import snapshot_download
-
- local_dir = base_path.split("/")[-1]
- repo_path = snapshot_download(base_path, local_dir = local_dir)
+ repo_path = snapshot_download(base_path)
abs_repo_path = os.path.abspath(repo_path)
logger.info(
@@ -432,19 +430,70 @@ class InferenceBackend:
token = hf_token if hf_token and hf_token.strip() else None,
trust_remote_code = trust_remote_code,
)
+ elif config.is_local and os.path.isdir(config.path):
+ # A merged export saves the LLM straight into the export directory, so
+ # there is no repo to download and no LLM/ child. snapshot_download on
+ # an absolute path is not a repo id and fails outright. BiCodec weights
+ # are not exported alongside it, so resolve those from the base model
+ # recorded at export time, as the processor fallback below does.
+ llm_path = os.path.join(config.path, "LLM")
+ if not os.path.isdir(llm_path):
+ llm_path = config.path
+ base_repo = None
+ try:
+ meta_path = Path(config.path) / "export_metadata.json"
+ if meta_path.exists():
+ base_repo = json.loads(
+ meta_path.read_text(encoding = "utf-8-sig")
+ ).get("base_model")
+ except Exception:
+ base_repo = None
+ if base_repo and os.path.isdir(base_repo):
+ # A base recorded as .../Spark-TTS-0.5B/LLM keeps BiCodec in its parent.
+ abs_repo_path = os.path.abspath(
+ os.path.dirname(base_repo)
+ if os.path.basename(base_repo.rstrip("/\\")) == "LLM"
+ else base_repo
+ )
+ elif base_repo:
+ from huggingface_hub import snapshot_download
+
+ # Registry alias ("Spark-TTS-0.5B/LLM") names a load
+ # subdirectory, not a repo, so snapshot_download rejects it.
+ # Same resolver the capability probe and the trainer preflight
+ # use, rather than a second copy of the mapping.
+ from utils.security import load_scan_target
+ from utils.utils import canonical_model_repo_id
+
+ hf_repo, _load_subdirs = load_scan_target(
+ canonical_model_repo_id(base_repo), ()
+ )
+ hf_repo = hf_repo or base_repo
+ # Same token as the load below: a private or gated base would
+ # otherwise 401 here while resolving the BiCodec assets.
+ abs_repo_path = os.path.abspath(
+ snapshot_download(
+ hf_repo,
+ token = hf_token if hf_token and hf_token.strip() else None,
+ )
+ )
+ else:
+ abs_repo_path = os.path.abspath(config.path)
+ logger.info(
+ f"Spark-TTS merged export: LLM from {llm_path}, BiCodec from {abs_repo_path}"
+ )
else:
# Base model: download full HF repo, load from /LLM subfolder
from huggingface_hub import snapshot_download
- hf_repo = config.path
- local_dir = hf_repo.split("/")[-1]
- repo_path = snapshot_download(hf_repo, local_dir = local_dir)
+ repo_path = snapshot_download(config.path)
abs_repo_path = os.path.abspath(repo_path)
llm_path = os.path.join(abs_repo_path, "LLM")
- logger.info(
- f"Spark-TTS: downloaded repo to {repo_path}, loading LLM from {llm_path}"
- )
+ logger.info(f"Spark-TTS: repo at {repo_path}, loading LLM from {llm_path}")
+ if not (config.is_lora and config.base_model):
+ # Shared by the merged-export and repo-root branches above: both resolve
+ # an llm_path and then load it the same way.
model, tokenizer = FastModel.from_pretrained(
llm_path,
dtype = torch.float32,
@@ -1971,6 +2020,7 @@ class InferenceBackend:
max_new_tokens: int = 2048,
repetition_penalty: float = 1.0,
use_adapter: Optional[Union[bool, str]] = None,
+ cancel_event = None,
) -> Tuple[bytes, int]:
"""Generate audio from text for TTS models.
Returns (wav_bytes, sample_rate). Blocking — full audio before return.
@@ -1991,12 +2041,17 @@ class InferenceBackend:
# is the one choke point for all four (#7066).
text = neutralize_tts_prompt_text(text, audio_type)
+ if cancel_event is not None and cancel_event.is_set():
+ raise RuntimeError("Audio generation cancelled")
with self._generation_lock:
+ if cancel_event is not None and cancel_event.is_set():
+ raise RuntimeError("Audio generation cancelled")
if use_adapter is not None:
self._apply_adapter_state(use_adapter)
+ stopping_criteria = self._cancel_stopping_criteria(cancel_event)
if audio_type == "snac":
- return self._generate_snac(
+ result = self._generate_snac(
model,
tokenizer,
text,
@@ -2004,16 +2059,32 @@ class InferenceBackend:
top_p,
max_new_tokens,
repetition_penalty,
+ stopping_criteria = stopping_criteria,
+ cancel_event = cancel_event,
)
elif audio_type == "csm":
processor = model_info.get("processor", tokenizer)
- return self._generate_csm(model, processor, text, max_new_tokens)
+ result = self._generate_csm(
+ model,
+ processor,
+ text,
+ max_new_tokens,
+ stopping_criteria = stopping_criteria,
+ cancel_event = cancel_event,
+ )
elif audio_type == "bicodec":
- return self._generate_bicodec(
- model, tokenizer, text, temperature, top_k, max_new_tokens
+ result = self._generate_bicodec(
+ model,
+ tokenizer,
+ text,
+ temperature,
+ top_k,
+ max_new_tokens,
+ stopping_criteria = stopping_criteria,
+ cancel_event = cancel_event,
)
elif audio_type == "dac":
- return self._generate_dac(
+ result = self._generate_dac(
model,
tokenizer,
text,
@@ -2023,12 +2094,27 @@ class InferenceBackend:
min_p,
max_new_tokens,
repetition_penalty,
+ stopping_criteria = stopping_criteria,
+ cancel_event = cancel_event,
)
else:
raise RuntimeError(f"Unknown audio_type: {audio_type}")
+ if cancel_event is not None and cancel_event.is_set():
+ raise RuntimeError("Audio generation cancelled")
+ return result
def _generate_snac(
- self, model, tokenizer, text, temperature, top_p, max_new_tokens, repetition_penalty
+ self,
+ model,
+ tokenizer,
+ text,
+ temperature,
+ top_p,
+ max_new_tokens,
+ repetition_penalty,
+ *,
+ stopping_criteria = None,
+ cancel_event = None,
):
"""Generate audio using SNAC codec (Orpheus)."""
device = model.device
@@ -2048,19 +2134,49 @@ class InferenceBackend:
repetition_penalty = repetition_penalty,
eos_token_id = 128258, # END_OF_SPEECH
use_cache = True,
+ **({"stopping_criteria": stopping_criteria} if stopping_criteria is not None else {}),
)
+ if cancel_event is not None and cancel_event.is_set():
+ raise RuntimeError("Audio generation cancelled")
return self._audio_codec_manager.decode_snac(generated, str(device))
- def _generate_csm(self, model, processor, text, max_new_tokens):
+ def _generate_csm(
+ self,
+ model,
+ processor,
+ text,
+ max_new_tokens,
+ *,
+ stopping_criteria = None,
+ cancel_event = None,
+ ):
"""Generate audio using CSM (Sesame)."""
speaker_id = 0
inputs = processor(
f"[{speaker_id}]{text}", add_special_tokens = True, return_tensors = "pt"
).to(model.device)
- audio_values = model.generate(**inputs, max_new_tokens = max_new_tokens, output_audio = True)
+ audio_values = model.generate(
+ **inputs,
+ max_new_tokens = max_new_tokens,
+ output_audio = True,
+ **({"stopping_criteria": stopping_criteria} if stopping_criteria is not None else {}),
+ )
+ if cancel_event is not None and cancel_event.is_set():
+ raise RuntimeError("Audio generation cancelled")
return self._audio_codec_manager.decode_csm(audio_values)
- def _generate_bicodec(self, model, tokenizer, text, temperature, top_k, max_new_tokens):
+ def _generate_bicodec(
+ self,
+ model,
+ tokenizer,
+ text,
+ temperature,
+ top_k,
+ max_new_tokens,
+ *,
+ stopping_criteria = None,
+ cancel_event = None,
+ ):
"""Generate audio using BiCodec (Spark-TTS)."""
prompt = "<|task_tts|><|start_content|>" + text + "<|end_content|><|start_global_token|>"
inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)
@@ -2072,7 +2188,10 @@ class InferenceBackend:
top_k = top_k,
eos_token_id = tokenizer.eos_token_id,
pad_token_id = tokenizer.pad_token_id,
+ **({"stopping_criteria": stopping_criteria} if stopping_criteria is not None else {}),
)
+ if cancel_event is not None and cancel_event.is_set():
+ raise RuntimeError("Audio generation cancelled")
new_tokens = generated[:, inputs.input_ids.shape[1] :]
decoded_text = tokenizer.batch_decode(new_tokens, skip_special_tokens = False)[0]
return self._audio_codec_manager.decode_bicodec(decoded_text, str(model.device))
@@ -2088,6 +2207,9 @@ class InferenceBackend:
min_p,
max_new_tokens,
repetition_penalty,
+ *,
+ stopping_criteria = None,
+ cancel_event = None,
):
"""Generate audio using DAC (OuteTTS). Follows Oute_TTS_(1B).ipynb exactly."""
# Monkey-patch RepetitionPenaltyLogitsProcessor with a 64-token window
@@ -2132,7 +2254,14 @@ class InferenceBackend:
min_p = min_p,
repetition_penalty = repetition_penalty,
max_new_tokens = max_new_tokens,
+ **(
+ {"stopping_criteria": stopping_criteria}
+ if stopping_criteria is not None
+ else {}
+ ),
)
+ if cancel_event is not None and cancel_event.is_set():
+ raise RuntimeError("Audio generation cancelled")
decoded_text = tokenizer.batch_decode(generated, skip_special_tokens = False)[0]
return self._audio_codec_manager.decode_dac(decoded_text, str(model.device))
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 2ceb0672809..0dee67c54e3 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -131,6 +131,10 @@ from state.tool_approvals import (
logger = get_logger(__name__)
+# Floor for a GGUF TTS read, scaled by requested tokens at the call site. This backend
+# decodes in seconds; the subprocess one needs minutes, so they do not share a base.
+_GGUF_AUDIO_READ_TIMEOUT = 300.0
+
class LlamaServerNotFoundError(RuntimeError):
"""GGUF model needs the llama.cpp runtime but no llama-server is installed.
@@ -1691,7 +1695,11 @@ def _with_gguf_load_marker(load: Callable):
"""Keep an HF repo marked for the full synchronous load call."""
@functools.wraps(load)
- def wrapped(self, intent: GgufLoadIntent):
+ def wrapped(
+ self,
+ intent: GgufLoadIntent,
+ load_cancel_event: Optional[threading.Event] = None,
+ ):
hf_repo = intent.hf_repo
with gguf_load_in_flight(hf_repo):
if hf_repo and _hub_download_blocks_gguf_load(
@@ -1705,7 +1713,7 @@ def _with_gguf_load_marker(load: Callable):
raise RuntimeError(
f"'{hf_repo}' is currently being downloaded by the download manager"
)
- return load(self, intent)
+ return load(self, intent, load_cancel_event = load_cancel_event)
return wrapped
@@ -9359,8 +9367,18 @@ class LlamaCppBackend:
self._stdout_thread.start()
@_with_gguf_load_marker
- def load_model(self, intent: GgufLoadIntent) -> bool:
+ def load_model(
+ self,
+ intent: GgufLoadIntent,
+ load_cancel_event: Optional[threading.Event] = None,
+ ) -> bool:
"""Start llama-server from one immutable load intent."""
+
+ def _load_cancelled() -> bool:
+ return self._cancel_event.is_set() or bool(
+ load_cancel_event is not None and load_cancel_event.is_set()
+ )
+
gguf_path = intent.gguf_path
mmproj_path = intent.mmproj_path
mtp_draft_path = intent.mtp_draft_path
@@ -9490,6 +9508,9 @@ class LlamaCppBackend:
return True
self._cancel_event.clear()
+ if _load_cancelled():
+ logger.info("Load cancelled before GGUF resolution")
+ return False
# Resolve llama-server now but defer a not-found error: a block-diffusion
# GGUF uses the diffusion runner, and its arch is only known after the header.
@@ -9730,7 +9751,7 @@ class LlamaCppBackend:
# Read GGUF metadata (context_length, chat_template); header-only.
self._read_gguf_metadata(model_path)
- if self._cancel_event.is_set():
+ if _load_cancelled():
logger.info("Load cancelled after download phase")
return False
@@ -9751,7 +9772,7 @@ class LlamaCppBackend:
self._mtp_draft_path = None
self._mtp_draft_suppressed_path = None
with self._lock:
- if self._cancel_event.is_set():
+ if _load_cancelled():
logger.info("Load cancelled before diffusion server start")
return False
return self._start_diffusion_server(
@@ -9794,7 +9815,7 @@ class LlamaCppBackend:
# ── Phase 3: start llama-server (under lock) ──────────────
with self._lock:
# Re-check cancel inside lock
- if self._cancel_event.is_set():
+ if _load_cancelled():
logger.info("Load cancelled before server start")
return False
@@ -12143,7 +12164,7 @@ class LlamaCppBackend:
_crashed = self._is_signal_crash(failed_rc) or (
sys.platform == "win32" and self._is_abort_exit(failed_rc)
)
- if not _crashed or not _cpu_fallback_eligible or self._cancel_event.is_set():
+ if not _crashed or not _cpu_fallback_eligible or _load_cancelled():
return False
fallback_has_mmproj = self._launch_has_mmproj(failed_cmd, env)
prepared = self._prepare_cpu_fallback_launch(
@@ -12155,7 +12176,7 @@ class LlamaCppBackend:
)
if prepared is None:
return False
- if self._cancel_event.is_set():
+ if _load_cancelled():
# Staging copies a whole runtime, so an /unload can land after
# the gate above with no runtime yet for unload_model() to
# remove; take it back here.
@@ -12296,7 +12317,7 @@ class LlamaCppBackend:
# so its output drops the marker and recording later would miss it,
# looping every load. Record and raise to the route's layer fallback,
# skipping the futile flash-attn/MTP retries.
- if not healthy and self._tensor_parallel and not self._cancel_event.is_set():
+ if not healthy and self._tensor_parallel and not _load_cancelled():
_ts_out = "\n".join(self._stdout_lines[-50:])
_ts_rc = self._process.poll() if self._process is not None else None
if self._should_record_tensor_split_abort(_ts_rc, _ts_out):
@@ -12310,7 +12331,7 @@ class LlamaCppBackend:
# builds (frequently inside the vision tower). Disabling FA keeps
# both vision and MTP, so retry that way before dropping either.
# Only on a hard fault with FA on; a cancel/unload stops respawn.
- if not healthy and not self._cancel_event.is_set():
+ if not healthy and not _load_cancelled():
_fa_rc = self._process.poll() if self._process is not None else None
_fa_cmd = (
self._with_flash_attn_off(_last_spawn_cmd)
@@ -12358,7 +12379,7 @@ class LlamaCppBackend:
healthy
and self._tensor_parallel
and _spec_requested_mtp
- and not self._cancel_event.is_set()
+ and not _load_cancelled()
and not self._probe_mtp_decode()
):
# A first-decode hard fault is usually the FA kernel: retry
@@ -12410,7 +12431,7 @@ class LlamaCppBackend:
if (
not healthy
and (_spec_requested_mtp or _spec_requested_dspark)
- and not self._cancel_event.is_set()
+ and not _load_cancelled()
):
_spec_cpu_replay_cmd = list(_last_spawn_cmd)
# Blame the binary only when the output shows MTP itself
@@ -12513,7 +12534,7 @@ class LlamaCppBackend:
) and not self._output_has_nonprojector_diagnostic(out)
if (
launched_with_mmproj
- and not self._cancel_event.is_set()
+ and not _load_cancelled()
and (_projector_msg or _signal_mmproj_guess)
):
_vision_cpu_replay_cmd = list(_last_spawn_cmd)
@@ -17081,7 +17102,7 @@ class LlamaCppBackend:
from huggingface_hub import snapshot_download
import os
- repo_path = snapshot_download("unsloth/Spark-TTS-0.5B", local_dir = "Spark-TTS-0.5B")
+ repo_path = snapshot_download("unsloth/Spark-TTS-0.5B")
model_repo_path = os.path.abspath(repo_path)
LlamaCppBackend._codec_mgr.load_codec(audio_type, device, model_repo_path = model_repo_path)
@@ -17132,8 +17153,18 @@ class LlamaCppBackend:
if cancel_event is not None and cancel_event.is_set():
raise RuntimeError("Audio generation cancelled")
+ # Scale with the request the way the subprocess path does: a flat 300s aborts a
+ # legitimate long generation on a CPU-only or slow host now that the page offers
+ # more tokens than the old ceiling. Scaled from this backend's own 300s floor,
+ # not the subprocess one: llama.cpp answers in seconds, and /audio/speech is in
+ # _INFERENCE_SUFFIXES, so a wedged server holds other_inference_request_count()
+ # up for the whole window, blocking idle auto-unload and 409-ing a training start.
+ # Imported here to keep the module import acyclic.
+ from core.inference.orchestrator import _audio_generation_timeout
+
+ read_timeout = _audio_generation_timeout(max_new_tokens, base = _GGUF_AUDIO_READ_TIMEOUT)
with httpx.Client(
- timeout = httpx.Timeout(300, connect = 10),
+ timeout = httpx.Timeout(read_timeout, connect = 10),
headers = self._auth_headers,
trust_env = False,
) as client:
diff --git a/studio/backend/core/inference/llama_keepwarm.py b/studio/backend/core/inference/llama_keepwarm.py
index b150b8f653f..cd338acc628 100644
--- a/studio/backend/core/inference/llama_keepwarm.py
+++ b/studio/backend/core/inference/llama_keepwarm.py
@@ -65,6 +65,7 @@ _INFERENCE_SUFFIXES = (
"/responses",
"/generate/stream", # Unsloth's own streaming route on the same llama-server
"/audio/generate", # direct GGUF TTS; can outlive the idle TTL
+ "/audio/speech", # /v1/audio/speech (+ /api/inference/audio/speech); same TTS core as /audio/generate
# Image generation holds a multi-GB pipeline for the whole request; tracking it lets other_inference_request_count() see
# an in-flight generation so an API-key training start is refused (409). endswith avoids matching *-progress / */cancel.
"/images/generate", # /api/inference/images/generate
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.py
index a0890fa2c33..c66e23ec07a 100644
--- a/studio/backend/core/inference/orchestrator.py
+++ b/studio/backend/core/inference/orchestrator.py
@@ -27,6 +27,11 @@ import uuid
from io import BytesIO
from pathlib import Path
from typing import Any, Generator, Optional, Sequence, Tuple, Union
+from core.inference.audio_errors import (
+ AUDIO_UNSUPPORTED_CODE,
+ AudioBackendUnsupportedError,
+ AudioGenerationCancelledError,
+)
from utils.hardware import get_device, prepare_gpu_selection
from utils.utils import hf_env_offline
@@ -56,11 +61,43 @@ _DISPATCH_STOP_TIMEOUT = 5.0
_DISPATCH_IDLE_TIMEOUT = 30.0
_DISPATCH_DRAIN_TIMEOUT = 5.0
+# Only bounds the Transformers subprocess path; llama.cpp TTS never reaches here.
+# 120s was tuned against GGUF speeds and killed real work: a safetensors LoRA on a
+# mid-range GPU needs minutes for the same clip a GGUF returns in seconds. A dead
+# worker is already caught every second by _ensure_subprocess_alive, so this only
+# has to bound one that is alive and wedged, and a generous value costs nothing.
+_AUDIO_GENERATION_TIMEOUT = 900.0
+_AUDIO_GENERATION_BASE_TOKENS = 2048
+AUDIO_GENERATION_MAX_TOKENS = 8192
+_AUDIO_CANCEL_DRAIN_TIMEOUT = 5.0
+# Before audio_started there is nobody to receive the cancel, and a prefill pass (a 3B TTS
+# model on CPU, or OuteTTS's per-token Python repetition penalty) routinely outlasts the
+# drain window. Tearing down on that budget unloads the model the user just loaded.
+_AUDIO_CANCEL_TEARDOWN_TIMEOUT = 30.0
+
# Max wait for a cancelled generation to release _gen_lock before unload_model
# tears the subprocess down. Only bounds a wedged worker.
_UNLOAD_GEN_LOCK_TIMEOUT = 15.0
+def _audio_generation_timeout(max_new_tokens: int, base: Optional[float] = None) -> float:
+ """Scale a floor by the requested token count.
+
+ ``base`` differs per backend by an order of magnitude: the Transformers subprocess
+ needs minutes for a clip llama.cpp returns in seconds, so llama_cpp.py passes its
+ own. Sharing one base silently gave every GGUF read the Transformers budget, which
+ holds other_inference_request_count() up and blocks idle auto-unload for that long.
+
+ Resolved at call time, not bound as a default: a default is evaluated once at import,
+ so reassigning the module constant afterwards had no effect.
+ """
+ if base is None:
+ base = _AUDIO_GENERATION_TIMEOUT
+ max_new_tokens = min(AUDIO_GENERATION_MAX_TOKENS, max(1, int(max_new_tokens)))
+ token_scale = max(1.0, max_new_tokens / _AUDIO_GENERATION_BASE_TOKENS)
+ return base * token_scale
+
+
_MLX_RUNTIME_MIRROR_FIELDS = (
"mlx_kv_bits",
"mlx_kv_bits_requested",
@@ -147,6 +184,11 @@ class InferenceOrchestrator:
# Set during a switch so a generation winning the _gen_lock handoff bails
# instead of starting on the outgoing model.
self._unload_pending = False
+ # Blocking TTS has no token response that can safely establish worker ownership
+ # while it is queued behind compare-mode work. Reserve the dispatcher admission
+ # lane for the whole TTS request so its shared cancel event cannot hit a sibling.
+ # Mutated under _dispatcher_lifecycle_lock while holding _gen_lock.
+ self._exclusive_tts_pending = False
# Dispatcher state for compare mode (adapter-controlled requests):
# bypass _gen_lock, send commands directly, read from per-request
@@ -636,17 +678,23 @@ class InferenceOrchestrator:
return None
return resp
- def drain(timeout: float = 5.0) -> None:
+ def drain(timeout: float = 5.0) -> bool:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
resp = read_one(timeout = min(0.5, deadline - time.monotonic()))
if resp is None:
if not self._ensure_subprocess_alive():
- return
+ return True
continue
- if resp.get("type", "") in ("gen_done", "gen_error"):
- return
- logger.warning("Timed out waiting for gen_done after cancel")
+ if resp.get("type", "") in (
+ "gen_done",
+ "gen_error",
+ "audio_done",
+ "audio_error",
+ ):
+ return True
+ logger.warning("Timed out waiting for terminal response after cancel")
+ return False
def release() -> None:
with self._mailbox_lock:
@@ -829,7 +877,7 @@ class InferenceOrchestrator:
# after the stop, become the resp_queue reader, and consume the
# worker's "unloaded" reply (unroutable, so dropped) before
# unload_model's _wait_response sees it -- hanging the unload 300s.
- if self._unload_pending:
+ if self._unload_pending or self._exclusive_tts_pending:
return False
if self._dispatcher_thread is not None and self._dispatcher_thread.is_alive():
return False
@@ -956,6 +1004,9 @@ class InferenceOrchestrator:
if self._unload_pending:
yield GenStreamError("Error: model is being unloaded", public = True)
return
+ if self._exclusive_tts_pending:
+ yield GenStreamError("Error: audio generation is in progress", public = True)
+ return
# Ensure the dispatcher runs. _start_dispatcher serializes concurrent starters under
# _dispatcher_lifecycle_lock and returns True only for the caller that actually spawned
@@ -1013,14 +1064,16 @@ class InferenceOrchestrator:
or self.active_model_name != expected_model
or not dispatcher_alive
)
- if not unloading:
+ tts_reserved = self._exclusive_tts_pending
+ blocked = unloading or tts_reserved
+ if not blocked:
self._mailboxes[request_id] = mailbox
if cancel_event is not None:
self._request_cancel_events[request_id] = cancel_event
# When bailing without a mailbox, note whether any OTHER compare request still
# routes through the dispatcher; if none and this call started it, stop it below.
- orphaned_dispatcher = unloading and not dispatcher_preexisting and not self._mailboxes
- if unloading:
+ orphaned_dispatcher = blocked and not dispatcher_preexisting and not self._mailboxes
+ if blocked:
# A racing unload can pass its _wait_dispatcher_idle() while the dispatcher was
# stopped, then set _unload_pending. The one we just started would otherwise
# linger with no mailboxes, race unload_model's _wait_response for the "unloaded"
@@ -1029,7 +1082,12 @@ class InferenceOrchestrator:
# _stop_dispatcher joins the dispatcher, which itself takes that lock.
if orphaned_dispatcher:
self._stop_dispatcher()
- yield GenStreamError("Error: model is being unloaded", public = True)
+ detail = (
+ "Error: audio generation is in progress"
+ if tts_reserved
+ else "Error: model is being unloaded"
+ )
+ yield GenStreamError(detail, public = True)
return
# Claim before sending, like the locked path: dispatched runs are concurrent by design,
@@ -1092,15 +1150,15 @@ class InferenceOrchestrator:
return
logger.warning("Timed out draining mailbox after cancel")
- def _wait_dispatcher_idle(self) -> bool:
+ def _wait_dispatcher_idle(self, cancel_event = None) -> bool:
"""Wait for all dispatched requests to complete, then stop dispatcher.
Returns True if the dispatcher was stopped (all mailboxes drained, or no
dispatcher was running), and False if it was left running because compare
requests were still active after _DISPATCH_IDLE_TIMEOUT.
- Called before the _gen_lock path so the dispatcher thread isn't competing
- for resp_queue reads.
+ Callers must reserve admission before using this as an exclusive handoff;
+ TTS does so under _gen_lock, while older direct paths call it before the lock.
"""
if self._dispatcher_thread is None or not self._dispatcher_thread.is_alive():
return True
@@ -1108,11 +1166,16 @@ class InferenceOrchestrator:
# Wait for all mailboxes to be emptied (dispatched requests complete)
deadline = time.monotonic() + _DISPATCH_IDLE_TIMEOUT
while time.monotonic() < deadline:
+ if cancel_event is not None and cancel_event.is_set():
+ return False
with self._mailbox_lock:
if not self._mailboxes:
break
time.sleep(0.1)
+ if cancel_event is not None and cancel_event.is_set():
+ return False
+
# Only stop dispatcher if all mailboxes drained. If compare requests
# are still active, leave it running so their token routing isn't
# killed mid-stream.
@@ -1207,6 +1270,7 @@ class InferenceOrchestrator:
mlx_distributed: bool = False,
mlx_kv_bits: Optional[int] = None,
chat_template_override: Optional[str] = None,
+ load_cancel_event: Optional[threading.Event] = None,
) -> bool:
"""Load a model for inference.
@@ -1220,6 +1284,10 @@ class InferenceOrchestrator:
model_name = config.identifier
self.loading_models.add(model_name)
+ if load_cancel_event is not None and load_cancel_event.is_set():
+ self.loading_models.discard(model_name)
+ logger.info("Load cancelled before worker start: %s", model_name)
+ return False
try:
needed_major = "5" if needs_transformers_5(model_name) else "4"
@@ -1471,15 +1539,27 @@ class InferenceOrchestrator:
# the same, so one object knows everything that is resident and Voice
# settings and Model Hub cannot report different things about one model.
- def load_stt_model(self, model: Optional[str], engine: str) -> None:
+ def load_stt_model(
+ self,
+ model: Optional[str],
+ engine: str,
+ request_cancel_event: Optional[threading.Event] = None,
+ ) -> None:
"""Make a dictation model resident on its sidecar."""
from core.inference import stt_registry
- stt_registry.load(model, engine)
+ stt_registry.load(model, engine, request_cancel_event)
+
+ def unload_stt_model(
+ self,
+ engines: Optional[Sequence[str]] = None,
+ expected_model: Optional[str] = None,
+ ) -> list:
+ """Release dictation models (all engines by default); returns refusals.
- def unload_stt_model(self, engines: Optional[Sequence[str]] = None) -> list:
- """Release dictation models (all engines by default); returns refusals."""
+ ``expected_model`` scopes the release to a sidecar still holding that model.
+ """
from core.inference import stt_registry
- return stt_registry.unload(engines)
+ return stt_registry.unload(engines, expected_model = expected_model)
def resident_stt_model(self) -> dict:
"""What dictation holds, alongside active_model_name for chat."""
@@ -2020,6 +2100,7 @@ class InferenceOrchestrator:
max_new_tokens: int = 2048,
repetition_penalty: float = 1.0,
use_adapter: Optional[Union[bool, str]] = None,
+ cancel_event = None,
) -> Tuple[bytes, int]:
"""Generate TTS audio. Returns (wav_bytes, sample_rate).
@@ -2031,65 +2112,156 @@ class InferenceOrchestrator:
raise RuntimeError("No active model")
expected_model = self.active_model_name
- # Serialize under _gen_lock (sole resp_queue reader) and refuse to start on the
- # outgoing model once an unload is pending, like the text and audio-input paths.
- # Without this a concurrent /audio/generate could run TTS on a model being switched.
+ # Serialize under _gen_lock and reserve dispatcher admission before waiting for
+ # compare work to drain. A bare idle wait is racy: a compare request can register
+ # between the wait and this command, leaving TTS queued without safe ownership of
+ # the worker's single shared cancel event.
with self._gen_lock:
- # Recheck under the lock (see _generate_inner): a raced unload/switch may have
- # cleared or swapped the model while we waited.
- if self._unload_pending or self.active_model_name != expected_model:
- raise RuntimeError("model is being unloaded")
-
- request_id = str(uuid.uuid4())
-
- cmd = {
- "type": "generate_audio",
- "request_id": request_id,
- "text": text,
- "temperature": temperature,
- "top_p": top_p,
- "top_k": top_k,
- "min_p": min_p,
- "max_new_tokens": max_new_tokens,
- "repetition_penalty": repetition_penalty,
- }
- if use_adapter is not None:
- cmd["use_adapter"] = use_adapter
-
- # Same shared-queue hazard as _generate_inner: see _direct_reader.
- read_one, _drain, release_mailbox = self._direct_reader(request_id)
+ with self._dispatcher_lifecycle_lock:
+ self._exclusive_tts_pending = True
try:
- self._send_cmd(cmd)
-
- deadline = time.monotonic() + 120.0
- while time.monotonic() < deadline:
- remaining = max(0.1, deadline - time.monotonic())
- resp = read_one(timeout = min(remaining, 1.0))
-
- if resp is None:
- if not self._ensure_subprocess_alive():
- raise RuntimeError(self._subprocess_crash_message("audio generation"))
- continue
-
- rtype = resp.get("type", "")
-
- if rtype == "audio_done":
- wav_bytes = base64.b64decode(resp["wav_base64"])
- sample_rate = resp["sample_rate"]
- return wav_bytes, sample_rate
-
- if rtype == "audio_error":
- raise RuntimeError(resp.get("error", "Audio generation failed"))
+ dispatcher_idle = self._wait_dispatcher_idle(cancel_event = cancel_event)
+ if cancel_event is not None and cancel_event.is_set():
+ raise AudioGenerationCancelledError("Audio generation cancelled")
+ if not dispatcher_idle:
+ raise RuntimeError(
+ "Cannot start audio generation while compare requests are active"
+ )
- if rtype == "error":
- raise RuntimeError(resp.get("error", "Unknown error"))
+ # Recheck after the dispatcher wait: unload can set its flag without
+ # _gen_lock, and a switch may have completed while this call was queued.
+ if self._unload_pending or self.active_model_name != expected_model:
+ raise AudioGenerationCancelledError("model is being unloaded")
- if rtype == "status":
- continue
+ # Bound public API integers before either enqueuing work or
+ # calculating the floating-point watchdog deadline.
+ max_new_tokens = min(
+ AUDIO_GENERATION_MAX_TOKENS,
+ max(1, int(max_new_tokens)),
+ )
+ generation_timeout = _audio_generation_timeout(max_new_tokens)
+ request_id = str(uuid.uuid4())
+
+ cmd = {
+ "type": "generate_audio",
+ "request_id": request_id,
+ "text": text,
+ "temperature": temperature,
+ "top_p": top_p,
+ "top_k": top_k,
+ "min_p": min_p,
+ "max_new_tokens": max_new_tokens,
+ "repetition_penalty": repetition_penalty,
+ }
+ if use_adapter is not None:
+ cmd["use_adapter"] = use_adapter
+
+ # Same shared-queue hazard as _generate_inner: see _direct_reader.
+ read_one, _drain, release_mailbox = self._direct_reader(request_id)
+ try:
+ # Claim before enqueueing so request-scoped reset ownership follows the same
+ # discipline as text and audio-input generation.
+ with self._send_order_lock:
+ self._claim_worker(cancel_event)
+ self._send_cmd(cmd)
- raise RuntimeError("Timeout waiting for audio generation (120s)")
+ deadline = time.monotonic() + generation_timeout
+ cancel_signalled = False
+ cancel_deadline = None
+ worker_started = False
+ while time.monotonic() < deadline:
+ if (
+ cancel_event is not None
+ and cancel_event.is_set()
+ and cancel_deadline is None
+ ):
+ cancel_deadline = time.monotonic() + _AUDIO_CANCEL_TEARDOWN_TIMEOUT
+ deadline = min(deadline, cancel_deadline)
+ if (
+ worker_started
+ and cancel_event is not None
+ and cancel_event.is_set()
+ and not cancel_signalled
+ and self._owns_worker(cancel_event)
+ ):
+ # audio_started is emitted after the worker clears stale state,
+ # so this signal cannot be erased or hit an earlier request.
+ self._cancel_generation()
+ cancel_signalled = True
+ # The cancel is delivered now, so hold the worker to the drain
+ # window from here rather than from when the caller asked.
+ cancel_deadline = time.monotonic() + _AUDIO_CANCEL_DRAIN_TIMEOUT
+ deadline = min(deadline, cancel_deadline)
+ remaining = max(0.1, deadline - time.monotonic())
+ resp = read_one(timeout = min(remaining, 1.0))
+
+ if resp is None:
+ if not self._ensure_subprocess_alive():
+ raise RuntimeError(
+ self._subprocess_crash_message("audio generation")
+ )
+ continue
+
+ rtype = resp.get("type", "")
+ if rtype == "audio_started":
+ self._mark_worker_started(cancel_event)
+ worker_started = True
+ continue
+
+ if rtype == "audio_done":
+ if cancel_event is not None and cancel_event.is_set():
+ raise AudioGenerationCancelledError("Audio generation cancelled")
+ wav_bytes = base64.b64decode(resp["wav_base64"])
+ sample_rate = resp["sample_rate"]
+ return wav_bytes, sample_rate
+
+ if rtype == "audio_error":
+ if resp.get("cancelled") or (
+ cancel_event is not None and cancel_event.is_set()
+ ):
+ raise AudioGenerationCancelledError("Audio generation cancelled")
+ # Tagged code = no path for this task, not a failure.
+ if resp.get("code") == AUDIO_UNSUPPORTED_CODE:
+ raise AudioBackendUnsupportedError(
+ resp.get("error", "This backend cannot generate audio."),
+ hint = resp.get("hint"),
+ )
+ raise RuntimeError(resp.get("error", "Audio generation failed"))
+
+ if rtype == "error":
+ if cancel_event is not None and cancel_event.is_set():
+ raise AudioGenerationCancelledError("Audio generation cancelled")
+ raise RuntimeError(resp.get("error", "Unknown error"))
+
+ if rtype == "status":
+ continue
+
+ # A caller cancellation already spent the drain window polling this
+ # request's mailbox. Tear down an unresponsive worker now instead of
+ # waiting out the much longer generation watchdog or draining twice.
+ if cancel_deadline is not None:
+ if self._shutdown_subprocess(timeout = _AUDIO_CANCEL_DRAIN_TIMEOUT):
+ self.active_model_name = None
+ self.models.clear()
+ raise AudioGenerationCancelledError("Audio generation cancelled")
+
+ # Do not release worker ownership or dispatcher exclusivity over a
+ # command that may still be generating. Cancel, consume its terminal
+ # response, and tear down a worker that does not acknowledge promptly.
+ self._cancel_generation()
+ if not _drain(timeout = _AUDIO_CANCEL_DRAIN_TIMEOUT):
+ if self._shutdown_subprocess(timeout = _AUDIO_CANCEL_DRAIN_TIMEOUT):
+ self.active_model_name = None
+ self.models.clear()
+ raise RuntimeError(
+ f"Timeout waiting for audio generation ({generation_timeout:g}s)"
+ )
+ finally:
+ self._release_worker(cancel_event)
+ release_mailbox()
finally:
- release_mailbox()
+ with self._dispatcher_lifecycle_lock:
+ self._exclusive_tts_pending = False
def generate_whisper_response(
self,
diff --git a/studio/backend/core/inference/stt_ggml_sidecar.py b/studio/backend/core/inference/stt_ggml_sidecar.py
index 383f06b740c..bedd216de88 100644
--- a/studio/backend/core/inference/stt_ggml_sidecar.py
+++ b/studio/backend/core/inference/stt_ggml_sidecar.py
@@ -23,6 +23,7 @@ the binary.
from __future__ import annotations
+import http.client
import io
import json
import os
@@ -50,8 +51,10 @@ from core.inference.stt_sidecar import (
SttModelIdError,
SttModelNotDownloadedError,
SttUnavailableError,
+ SttTranscriptionCancelledError,
_capture_stt_hub_cache,
_claim_stt_repository,
+ _close_connection_on_cancel,
_decode_audio_bounded,
_downloaded_file_bytes,
_fallback_revisions,
@@ -261,12 +264,48 @@ def slim_runtime_intact(binary: str) -> bool:
return intact
+# A runtime that starts, answers GET /, and then dies on the first actual inference.
+# Reported on Windows with ROCm on gfx1200, where rocBLAS is missing its TensileLibrary:
+# the marker and the linked libraries are all present, so slim_runtime_intact() is happy
+# and is_available() said yes, which meant _resolve_serving_stt_engine never fell back and
+# every recording 501'd while the UI showed the model as loaded. Only inference can prove
+# this, so it is recorded when inference fails and cleared when one succeeds. Process
+# lifetime by design: a reinstall restarts Studio.
+_runtime_inference_failure: Optional[str] = None
+_runtime_failure_lock = threading.Lock()
+
+
+def note_runtime_inference_failure(reason: str) -> None:
+ global _runtime_inference_failure
+ with _runtime_failure_lock:
+ if _runtime_inference_failure is None:
+ logger.warning(
+ "whisper.cpp runtime failed to serve a transcription (%s); "
+ "treating the engine as unavailable and using Transformers instead",
+ reason,
+ )
+ _runtime_inference_failure = reason
+
+
+def clear_runtime_inference_failure() -> None:
+ global _runtime_inference_failure
+ with _runtime_failure_lock:
+ _runtime_inference_failure = None
+
+
+def runtime_inference_failure() -> Optional[str]:
+ with _runtime_failure_lock:
+ return _runtime_inference_failure
+
+
def is_available() -> bool:
binary = find_whisper_server_binary()
if binary is None:
return False
if not slim_runtime_intact(binary):
return False
+ if runtime_inference_failure() is not None:
+ return False
try:
import av # noqa: F401
except Exception:
@@ -418,6 +457,10 @@ class _GgmlDownloadState:
"model": self._model_id if downloading else None,
"error": self._error,
"cancelled": self._cancelled,
+ # Which model the cancel applies to. "model" goes None once the worker
+ # thread stops, so a settled cancellation was indistinguishable from an
+ # unrelated one and a deferred load restarted the whole download.
+ "cancelled_model": self._model_id if self._cancelled else None,
"bytes_total": self._total_bytes if downloading else None,
}
captured = (
@@ -666,6 +709,7 @@ class GgmlSttSidecar:
def __init__(self, keep_alive_seconds: float = STT_KEEP_ALIVE_SECONDS) -> None:
self._lock = threading.RLock()
+ self._load_state_lock = threading.Lock()
self._process: Optional[subprocess.Popen] = None
self._port: Optional[int] = None
self._model_id: Optional[str] = None
@@ -681,6 +725,7 @@ class GgmlSttSidecar:
# lock, so the event is the source of truth and terminating the process
# is a best-effort fast path.
self._load_cancel_event: Optional[threading.Event] = None
+ self._load_owner_cancel_event: Optional[threading.Event] = None
self._starting_process: Optional[subprocess.Popen] = None
# Set before the updater waits for _lock, then kept set while it owns
# the lock and atomically replaces the managed install tree. New loads
@@ -704,7 +749,8 @@ class GgmlSttSidecar:
def is_loading(self) -> bool:
# True only while whisper-server is starting (seconds to bind its GPU
# backend); load() sets and clears the flag around that window.
- return self._loading
+ with self._load_state_lock:
+ return self._loading
@property
def keep_alive_seconds(self) -> float:
@@ -760,9 +806,44 @@ class GgmlSttSidecar:
if process is not None:
forget_pid(process.pid)
- def unload(self) -> None:
- with self._lock:
+ def _holds_expected_model(self, expected: Optional[str]) -> bool:
+ """Whether the resident model is the one the caller claimed. Call under ``_lock``.
+
+ A caller that owns a specific model must not release whatever happens to be
+ resident: another surface can switch the engine between the ownership check and
+ the request reaching the sidecar.
+ """
+ if expected is None:
+ return True
+ current = self._model_id
+ if current is None:
+ return False
+ if current == expected:
+ return True
+ try:
+ return current == resolve_ggml_model_id(expected)
+ except Exception: # noqa: BLE001 - an unresolvable name is not this model
+ return False
+
+ def unload(
+ self,
+ wait: bool = True,
+ expected_model: Optional[str] = None,
+ ) -> None:
+ """Release the resident model. ``wait=False`` skips a sidecar mid-request.
+
+ `transcribe` holds ``_lock`` across the whole round trip, so a caller releasing
+ engines it does not own must not block behind one. ``expected_model`` scopes the
+ release to one model, compared under the lock.
+ """
+ if not self._lock.acquire(blocking = wait):
+ return
+ try:
+ if not self._holds_expected_model(expected_model):
+ return
self._release_locked()
+ finally:
+ self._lock.release()
def _raise_if_update_in_progress(self) -> None:
if self._update_in_progress:
@@ -795,13 +876,27 @@ class GgmlSttSidecar:
# so act without the lock: signal abort and terminate the starting
# process. _wait_for_server observes the event and raises, then load()
# reaps the process and releases the lock.
- if not self._loading:
- return False
- event = self._load_cancel_event
- if event is None:
- return False
- event.set()
- process = self._starting_process
+ with self._load_state_lock:
+ event = self._load_cancel_event
+ if not self._loading or event is None:
+ return False
+ event.set()
+ process = self._starting_process
+ if process is not None and process.poll() is None:
+ try:
+ process.terminate()
+ except Exception:
+ pass
+ return True
+
+ def _cancel_owned_load(self, owner: threading.Event) -> bool:
+ """Cancel startup only when it belongs to this transcription."""
+ with self._load_state_lock:
+ event = self._load_cancel_event
+ if not self._loading or event is None or self._load_owner_cancel_event is not owner:
+ return False
+ event.set()
+ process = self._starting_process
if process is not None and process.poll() is None:
try:
process.terminate()
@@ -838,18 +933,25 @@ class GgmlSttSidecar:
)
return path
- def load(self, model: Optional[str] = None) -> None:
+ def load(
+ self,
+ model: Optional[str] = None,
+ request_cancel_event: Optional[threading.Event] = None,
+ ) -> None:
"""Start (or switch) whisper-server for the requested curated model."""
+ if request_cancel_event is not None and request_cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
self._raise_if_update_in_progress()
model_id = resolve_ggml_model_id(model)
with self._lock:
+ if request_cancel_event is not None and request_cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
self._raise_if_update_in_progress()
binary = ensure_engine_available()
if self._process_alive() and self._model_id == model_id:
self._schedule_idle_unload_locked()
return
model_path = self._ensure_model_downloaded(model_id)
- self._release_locked()
reservation, port = self._reserve_free_port()
command = [binary, "-m", model_path, "--host", "127.0.0.1", "--port", str(port)]
marker = _whisper_install_marker(binary)
@@ -868,10 +970,17 @@ class GgmlSttSidecar:
model_id,
port,
)
- cancel_event = threading.Event()
- self._load_cancel_event = cancel_event
- self._loading = True
+ cancel_event = (
+ request_cancel_event if request_cancel_event is not None else threading.Event()
+ )
+ with self._load_state_lock:
+ self._load_cancel_event = cancel_event
+ self._load_owner_cancel_event = request_cancel_event
+ self._loading = True
try:
+ if cancel_event.is_set():
+ raise SttLoadCancelledError("GGUF STT model loading was cancelled.")
+ self._release_locked()
# Release the reservation as late as possible: whisper-server
# binds the port moments after this close.
reservation.close()
@@ -887,7 +996,8 @@ class GgmlSttSidecar:
# never orphans a server holding the model.
**child_popen_kwargs(),
)
- self._starting_process = process
+ with self._load_state_lock:
+ self._starting_process = process
adopt_pid(process.pid) # terminate_all backstop for graceful exits
try:
self._wait_for_server(process, port, cancel_event)
@@ -903,9 +1013,11 @@ class GgmlSttSidecar:
self._schedule_idle_unload_locked()
finally:
reservation.close() # no-op when already released before spawn
- self._loading = False
- self._load_cancel_event = None
- self._starting_process = None
+ with self._load_state_lock:
+ self._loading = False
+ self._load_cancel_event = None
+ self._load_owner_cancel_event = None
+ self._starting_process = None
@staticmethod
def _wait_for_server(
@@ -959,6 +1071,7 @@ class GgmlSttSidecar:
model: Optional[str] = None,
language: Optional[str] = None,
fast: bool = False,
+ cancel_event: Optional[threading.Event] = None,
) -> dict:
"""Transcribe encoded audio bytes via whisper-server.
@@ -969,6 +1082,8 @@ class GgmlSttSidecar:
ensure_engine_available()
model_id = resolve_ggml_model_id(model)
lang = normalize_whisper_language(language)
+ if cancel_event is not None and cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
known_languages = _known_whisper_languages()
if lang is not None and known_languages is not None and lang not in known_languages:
raise SttLanguageError(
@@ -977,12 +1092,23 @@ class GgmlSttSidecar:
# Reject a missing model before decoding so a long clip does not burn CPU
# only to 409 (matches the Transformers sidecar's preflight).
self._ensure_model_downloaded(model_id)
- decoded_audio = _decode_audio_bounded(audio)
+ decoded_audio = _decode_audio_bounded(audio, cancel_event)
+ if cancel_event is not None and cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
wav_bytes = _pcm_to_wav_bytes(decoded_audio)
with self._lock:
try:
- self.load(model_id)
- text = self._post_inference(wav_bytes, lang, fast)
+ if cancel_event is None:
+ self.load(model_id)
+ else:
+ self.load(model_id, request_cancel_event = cancel_event)
+ text = self._post_inference(wav_bytes, lang, fast, cancel_event)
+ if cancel_event is not None and cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
+ except Exception:
+ if cancel_event is not None and cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
+ raise
finally:
self._schedule_idle_unload_locked()
duration = (len(decoded_audio) / _TARGET_SAMPLE_RATE) if len(decoded_audio) else None
@@ -993,7 +1119,18 @@ class GgmlSttSidecar:
"model": model_id,
}
- def _post_inference(self, wav_bytes: bytes, lang: Optional[str], fast: bool) -> str:
+ def cancel_transcription(self, cancel_event: threading.Event) -> bool:
+ already_cancelled = cancel_event.is_set()
+ cancel_event.set()
+ return self._cancel_owned_load(cancel_event) or not already_cancelled
+
+ def _post_inference(
+ self,
+ wav_bytes: bytes,
+ lang: Optional[str],
+ fast: bool,
+ cancel_event: Optional[threading.Event] = None,
+ ) -> str:
boundary = uuid.uuid4().hex
fields = {
"temperature": "0.0",
@@ -1021,23 +1158,49 @@ class GgmlSttSidecar:
)
parts.append(f"--{boundary}--\r\n".encode())
body = b"".join(parts)
- req = urllib.request.Request(
- f"http://127.0.0.1:{self._port}/inference",
- data = body,
- headers = {"Content-Type": f"multipart/form-data; boundary={boundary}"},
+ # http.client, not urllib: a cancel needs the socket, and urlopen exposes none.
+ connection = http.client.HTTPConnection(
+ "127.0.0.1", self._port, timeout = _TRANSCRIBE_TIMEOUT_SECONDS
)
+ cancel_done = threading.Event()
+ if cancel_event is not None:
+ threading.Thread(
+ target = _close_connection_on_cancel,
+ args = (connection, cancel_event, cancel_done),
+ daemon = True,
+ ).start()
try:
- with urllib.request.urlopen(req, timeout = _TRANSCRIBE_TIMEOUT_SECONDS) as resp:
- payload = json.load(resp)
- except SttAudioDecodeError:
+ connection.request(
+ "POST",
+ "/inference",
+ body = body,
+ headers = {"Content-Type": f"multipart/form-data; boundary={boundary}"},
+ )
+ with connection.getresponse() as response:
+ if not 200 <= response.status < 300:
+ raise SttEngineUnavailableError(
+ f"The local transcription runtime returned HTTP {response.status}."
+ )
+ payload = json.loads(response.read().decode("utf-8"))
+ except (SttAudioDecodeError, SttEngineUnavailableError):
raise
except Exception as exc:
+ # A cancel closes this socket deliberately, so it is not evidence of a broken
+ # runtime and must not disable the engine.
+ if cancel_event is None or not cancel_event.is_set():
+ note_runtime_inference_failure(f"{type(exc).__name__}: {exc}")
raise SttEngineUnavailableError(
- "The local transcription runtime did not answer the request."
+ "The local transcription runtime did not answer the request. "
+ "Transcription will use the Transformers engine from now on."
) from exc
+ finally:
+ cancel_done.set()
+ connection.close()
text = payload.get("text")
if not isinstance(text, str):
raise SttAudioDecodeError("Could not decode the audio.")
+ # It served a transcription, so whatever failed earlier was transient.
+ clear_runtime_inference_failure()
# whisper.cpp joins segments with newlines; dictation wants one line.
return " ".join(part.strip() for part in text.splitlines() if part.strip()).strip()
diff --git a/studio/backend/core/inference/stt_mtmd_sidecar.py b/studio/backend/core/inference/stt_mtmd_sidecar.py
index 8dda0438b85..7665f7cd8cd 100644
--- a/studio/backend/core/inference/stt_mtmd_sidecar.py
+++ b/studio/backend/core/inference/stt_mtmd_sidecar.py
@@ -15,6 +15,7 @@ files, so downloads run the shared worker twice.
from __future__ import annotations
import base64
+import http.client
import json
import socket
import subprocess
@@ -38,9 +39,11 @@ from core.inference.stt_sidecar import (
SttModelIdError,
SttModelNotDownloadedError,
SttUnavailableError,
+ SttTranscriptionCancelledError,
_SelectedHubFile,
_capture_stt_hub_cache,
_claim_stt_repository,
+ _close_connection_on_cancel,
_decode_audio_bounded,
_downloaded_file_bytes,
_fallback_revisions,
@@ -55,6 +58,10 @@ from core.inference.stt_sidecar import (
logger = get_logger(__name__)
+# A blocking unload comes from training claiming the VRAM. Bounded so training is not
+# stalled by a long recording, but long enough that a normal transcription finishes.
+_ACTIVE_REQUEST_DRAIN_TIMEOUT = 30.0
+
@dataclass(frozen = True)
class MtmdSttModel:
@@ -314,6 +321,10 @@ class _MtmdDownloadState:
"model": model_id if downloading else None,
"error": self._error,
"cancelled": self._cancelled,
+ # Which model the cancel applies to. "model" goes None once the worker
+ # thread stops, so a settled cancellation was indistinguishable from an
+ # unrelated one and a deferred load restarted the whole download.
+ "cancelled_model": self._model_id if self._cancelled else None,
"bytes_total": self._total_bytes if downloading else None,
}
captured = (
@@ -548,6 +559,7 @@ class MtmdSttSidecar:
# training. Kept so a dictation after the run does not stay on CPU.
self._gpu_disabled = False
self._load_cancel_event: Optional[threading.Event] = None
+ self._load_owner_cancel_event: Optional[threading.Event] = None
self._update_in_progress = False
self._keep_alive_seconds = keep_alive_seconds
self._idle_timer: Optional[threading.Timer] = None
@@ -615,15 +627,87 @@ class MtmdSttSidecar:
self._port = None
self._model_id = None
- def unload(self) -> None:
+ def _drain_active_requests(self, deadline: float) -> None:
+ """Wait, bounded, for in-flight transcriptions to finish.
+
+ Never called while holding ``_lock``: `transcribe` claims ``_active_requests``
+ under that lock, so waiting there would block the very request being waited on.
+ """
+ while self._active_requests and time.monotonic() < deadline:
+ time.sleep(0.1)
+
+ def _holds_expected_model(self, expected: Optional[str]) -> bool:
+ """Whether the resident model is the one the caller claimed. Call under ``_lock``.
+
+ A caller that owns a specific model must not release whatever happens to be
+ resident: another surface can switch the engine between the ownership check and
+ the request reaching the sidecar.
+ """
+ if expected is None:
+ return True
+ current = self._model_id
+ if current is None:
+ return False
+ if current == expected:
+ return True
+ try:
+ return current == resolve_mtmd_model_id(expected)
+ except Exception: # noqa: BLE001 - an unresolvable name is not this model
+ return False
+
+ def unload(
+ self,
+ wait: bool = True,
+ expected_model: Optional[str] = None,
+ ) -> None:
+ """Release the resident model. ``wait=False`` skips a sidecar mid-request.
+
+ `transcribe` runs outside ``_lock`` and counts itself in ``_active_requests``, so
+ that, not the lock, is what says busy here. ``expected_model`` scopes the release
+ to one model, compared under the lock.
+ """
+ if not wait and (self.is_loading() or self._active_requests):
+ return
+ # A blocking caller is training claiming the VRAM, so this cannot wait forever, but
+ # `wait=True` still must not kill llama-server under a live transcription and throw
+ # the recording away. Bounded window, then proceed.
+ drain_deadline = time.monotonic() + _ACTIVE_REQUEST_DRAIN_TIMEOUT
+ if wait:
+ self._drain_active_requests(drain_deadline)
# A startup has not assigned _process yet, so releasing alone would let
# it finish and republish the model that was just unloaded. Cancel and
# settle outside _lock: load() holds _start_lock across startup and
# takes _lock inside it, so holding _lock here would invert them.
self.cancel_pending_load()
self.wait_for_load_to_settle()
- with self._lock:
- self._release_locked()
+ while True:
+ if not self._lock.acquire(blocking = wait):
+ return
+ try:
+ # Recheck under the lock. `transcribe` claims _active_requests while holding
+ # it, so a request starting between the drain above and this acquire would
+ # otherwise have llama-server killed underneath it and lose the recording.
+ if not self._holds_expected_model(expected_model):
+ return
+ busy = bool(self._active_requests)
+ if busy and not wait:
+ return
+ if not busy or time.monotonic() >= drain_deadline:
+ if busy:
+ logger.warning(
+ "mtmd STT still had %d active request(s) after %.0fs; "
+ "releasing anyway",
+ self._active_requests,
+ _ACTIVE_REQUEST_DRAIN_TIMEOUT,
+ )
+ self._release_locked()
+ return
+ finally:
+ self._lock.release()
+ # Drained outside the lock, then the release is retried under it. A blocking
+ # unload that found the sidecar busy only after acquiring cannot drain in
+ # place without deadlocking the request it is draining.
+ self._drain_active_requests(drain_deadline)
def cancel_pending_load(self) -> bool:
"""Preempt a starting llama-server so training is not raced for VRAM.
@@ -647,6 +731,21 @@ class MtmdSttSidecar:
pass
return True
+ def _cancel_owned_load(self, owner: threading.Event) -> bool:
+ """Cancel startup only when it belongs to this transcription."""
+ with self._lock:
+ event = self._load_cancel_event
+ if not self._loading or event is None or self._load_owner_cancel_event is not owner:
+ return False
+ event.set()
+ process = self._starting_process
+ if process is not None and process.poll() is None:
+ try:
+ process.terminate()
+ except Exception:
+ pass
+ return True
+
def wait_for_load_to_settle(self) -> None:
"""Block until a cancelled startup has been reaped and its VRAM freed.
@@ -696,17 +795,30 @@ class MtmdSttSidecar:
)
return paths
- def load(self, model: Optional[str] = None) -> None:
+ def load(
+ self,
+ model: Optional[str] = None,
+ request_cancel_event: Optional[threading.Event] = None,
+ ) -> None:
+ if request_cancel_event is not None and request_cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
self._raise_if_update_in_progress()
model_id = resolve_mtmd_model_id(model)
binary = ensure_engine_available()
# Startup happens outside _lock (it is slow), so this keeps two callers
# from each spawning a server and orphaning the first.
with self._start_lock:
+ if request_cancel_event is not None and request_cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
self._raise_if_update_in_progress()
- self._load_locked(model_id, binary)
+ self._load_locked(model_id, binary, request_cancel_event)
- def _load_locked(self, model_id: str, binary: str) -> None:
+ def _load_locked(
+ self,
+ model_id: str,
+ binary: str,
+ request_cancel_event: Optional[threading.Event] = None,
+ ) -> None:
with self._lock:
training = _training_active()
if self._process_alive() and self._model_id == model_id:
@@ -722,11 +834,16 @@ class MtmdSttSidecar:
# Announced before the slow probe and reap: is_loading() is read lock-free,
# so a training start would otherwise see False and wait out the startup in
# unload() instead of cancelling this load.
- cancel_event = threading.Event()
+ cancel_event = (
+ request_cancel_event if request_cancel_event is not None else threading.Event()
+ )
self._load_cancel_event = cancel_event
+ self._load_owner_cancel_event = request_cancel_event
self._loading = True
released = False
try:
+ if cancel_event.is_set():
+ raise SttLoadCancelledError("Dictation model loading was cancelled.")
# Before the release: a 409 for a model that is not downloaded
# must not cost the user the server they were already using.
model_path, mmproj_path = self._ensure_model_downloaded(model_id)
@@ -744,6 +861,7 @@ class MtmdSttSidecar:
if not released:
self._loading = False
self._load_cancel_event = None
+ self._load_owner_cancel_event = None
# Re-read last: _release_locked() reaps the old server, which can
# take seconds, and training admission that already passed its own
# check cannot come back to cancel this load. Publishing _loading
@@ -818,6 +936,7 @@ class MtmdSttSidecar:
with self._lock:
self._loading = False
self._load_cancel_event = None
+ self._load_owner_cancel_event = None
self._starting_process = None
@staticmethod
@@ -849,6 +968,7 @@ class MtmdSttSidecar:
model: Optional[str] = None,
language: Optional[str] = None,
fast: bool = False,
+ cancel_event: Optional[threading.Event] = None,
) -> dict:
"""Transcribe encoded audio bytes, as the other sidecars do.
@@ -857,16 +977,20 @@ class MtmdSttSidecar:
"""
ensure_engine_available()
model_id = resolve_mtmd_model_id(model)
+ if cancel_event is not None and cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
# No training guard here on purpose: load() starts the server with
# -ngl 0 --no-mmproj-offload while a run is active, so this transcribes
# on CPU exactly as whisper.cpp and Transformers do. Refusing after a
# preload that succeeded only discarded the user's recording.
# Reject a missing model before decoding, matching the other sidecars.
self._ensure_model_downloaded(model_id)
- decoded_audio = _decode_audio_bounded(audio)
+ decoded_audio = _decode_audio_bounded(audio, cancel_event)
+ if cancel_event is not None and cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
wav_bytes = _pcm_to_wav_bytes(decoded_audio)
audio_seconds = (len(decoded_audio) / _TARGET_SAMPLE_RATE) if len(decoded_audio) else None
- self.load(model_id)
+ self.load(model_id, request_cancel_event = cancel_event)
with self._lock:
port = self._port
if port is None or not self._process_alive():
@@ -887,7 +1011,15 @@ class MtmdSttSidecar:
try:
# Outside the lock: a held lock would block unload, including the
# one a training run performs, for the whole request timeout.
- text = self._post_transcribe(port, model_id, wav_bytes, audio_seconds)
+ text = self._post_transcribe(
+ port, model_id, wav_bytes, audio_seconds, cancel_event = cancel_event
+ )
+ if cancel_event is not None and cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
+ except Exception:
+ if cancel_event is not None and cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
+ raise
finally:
with self._lock:
self._active_requests -= 1
@@ -899,12 +1031,19 @@ class MtmdSttSidecar:
"model": model_id,
}
+ def cancel_transcription(self, cancel_event: threading.Event) -> bool:
+ already_cancelled = cancel_event.is_set()
+ cancel_event.set()
+ return self._cancel_owned_load(cancel_event) or not already_cancelled
+
def _post_transcribe(
self,
port: int,
model_id: str,
wav_bytes: bytes,
audio_seconds: Optional[float] = None,
+ *,
+ cancel_event: Optional[threading.Event] = None,
) -> str:
spec = MTMD_STT_MODELS[model_id]
payload = {
@@ -927,13 +1066,35 @@ class MtmdSttSidecar:
"temperature": 0,
"max_tokens": _transcript_token_budget(audio_seconds),
}
- request = urllib.request.Request(
- f"http://127.0.0.1:{port}/v1/chat/completions",
- data = json.dumps(payload).encode("utf-8"),
- headers = {"Content-Type": "application/json"},
+ connection = http.client.HTTPConnection(
+ "127.0.0.1", port, timeout = _TRANSCRIBE_TIMEOUT_SECONDS
)
- with urllib.request.urlopen(request, timeout = _TRANSCRIBE_TIMEOUT_SECONDS) as response:
- body = json.loads(response.read().decode("utf-8"))
+ cancel_done = threading.Event()
+ if cancel_event is not None:
+ threading.Thread(
+ target = _close_connection_on_cancel,
+ args = (connection, cancel_event, cancel_done),
+ daemon = True,
+ ).start()
+ try:
+ if cancel_event is not None and cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
+ connection.request(
+ "POST",
+ "/v1/chat/completions",
+ body = json.dumps(payload).encode("utf-8"),
+ headers = {"Content-Type": "application/json"},
+ )
+ with connection.getresponse() as response:
+ response_body = response.read()
+ if not 200 <= response.status < 300:
+ raise RuntimeError(
+ f"MTMD transcription server returned HTTP {response.status}."
+ )
+ body = json.loads(response_body.decode("utf-8"))
+ finally:
+ cancel_done.set()
+ connection.close()
choices = body.get("choices") or []
text = (choices[0].get("message", {}).get("content") or "") if choices else ""
return _clean_transcript(text, spec.transcript_marker)
diff --git a/studio/backend/core/inference/stt_registry.py b/studio/backend/core/inference/stt_registry.py
index 5549ce31e7f..f6f0deab682 100644
--- a/studio/backend/core/inference/stt_registry.py
+++ b/studio/backend/core/inference/stt_registry.py
@@ -12,6 +12,7 @@ Model Hub cannot report different things about the same model.
from __future__ import annotations
+import threading
from typing import Any, Optional, Sequence
from loggers import get_logger
@@ -22,6 +23,9 @@ logger = get_logger(__name__)
# unload sweeps them, which matters only for logging.
STT_ENGINES = ("transformers", "gguf", "mtmd")
+# Serialises load-then-release so two loads on different engines cannot leave both resident.
+_load_lock = threading.Lock()
+
def sidecar_for(engine: str) -> Any:
"""The sidecar serving ``engine``. Transformers is the catch-all."""
@@ -36,21 +40,77 @@ def sidecar_for(engine: str) -> Any:
return get_stt_sidecar()
-def load(model: Optional[str], engine: str) -> None:
- """Make ``model`` resident on ``engine``. Raises what the sidecar raises."""
- sidecar_for(engine).load(model)
-
+def load(
+ model: Optional[str],
+ engine: str,
+ request_cancel_event: Optional[threading.Event] = None,
+) -> None:
+ """Make ``model`` resident on ``engine``, then release every idle other engine.
-def unload(engines: Optional[Sequence[str]] = None) -> list[str]:
+ Dictation is one user-visible choice, so engines are alternatives, not slots:
+ holding two at once doubles VRAM for the whole keep-alive window. An engine serving
+ a request keeps its model and releases it on its own idle timer. Raises what the
+ sidecar raises, before anything is released: a 409 for a model that is not
+ downloaded must not cost the user the engine they were already using.
+ """
+ others = [name for name in STT_ENGINES if name != engine]
+ with _load_lock:
+ # Release the other engines BEFORE allocating, but only once the checkpoint is known
+ # to be on disk. Holding two engines across the load is what makes a switch OOM on a
+ # device that fits either alone; releasing blind would let a 409 for a model that was
+ # never downloaded cost the user the engine they were already using. When the answer
+ # is not certain, keep the old order and accept the peak.
+ if _model_is_downloaded(engine, model):
+ unload(others, wait = False)
+ sidecar_for(engine).load(model, request_cancel_event = request_cancel_event)
+ else:
+ sidecar_for(engine).load(model, request_cancel_event = request_cancel_event)
+ unload(others, wait = False)
+
+
+def _model_is_downloaded(engine: str, model: str) -> bool:
+ """True only when the load is certain not to be turned away for a missing checkpoint.
+
+ Deliberately conservative: any doubt, including an import or lookup failure, answers
+ False so the caller keeps the ordering that cannot lose a resident engine.
+ """
+ try:
+ if engine == "mtmd":
+ from core.inference import stt_mtmd_sidecar
+ return bool(stt_mtmd_sidecar.is_model_downloaded(model))
+ if engine == "gguf":
+ from core.inference import stt_ggml_sidecar
+ return stt_ggml_sidecar._cached_model_path(model) is not None
+ from core.inference import stt_sidecar
+
+ return (
+ stt_sidecar._find_complete_cached_snapshot(stt_sidecar.resolve_model_id(model))
+ is not None
+ )
+ except Exception: # noqa: BLE001 - a probe must never fail the load it precedes
+ return False
+
+
+def unload(
+ engines: Optional[Sequence[str]] = None,
+ *,
+ wait: bool = True,
+ expected_model: Optional[str] = None,
+) -> list[str]:
"""Release every named engine (all of them by default), reporting refusals.
Each is attempted even after a failure: more than one can hold memory at
once after an engine switch, so stopping early would strand the rest.
+ ``wait=False`` leaves a sidecar that is mid-request resident instead of
+ blocking on it, for callers releasing engines they do not own.
+ ``expected_model`` releases only a sidecar still holding that model, compared
+ under its own lock, so a caller that owns one model cannot tear down another
+ surface's newer one.
"""
failed: list[str] = []
for name in STT_ENGINES if engines is None else engines:
try:
- sidecar_for(name).unload()
+ sidecar_for(name).unload(wait = wait, expected_model = expected_model)
except Exception as exc: # noqa: BLE001 - report after attempting all
logger.warning("Failed to unload STT engine '%s': %s", name, exc)
failed.append(name)
diff --git a/studio/backend/core/inference/stt_sidecar.py b/studio/backend/core/inference/stt_sidecar.py
index bcb2477e111..3f379c94047 100644
--- a/studio/backend/core/inference/stt_sidecar.py
+++ b/studio/backend/core/inference/stt_sidecar.py
@@ -19,8 +19,10 @@ import io
import json
import os
import re
+import socket
import subprocess
import threading
+import time
import uuid
from dataclasses import dataclass
from pathlib import Path
@@ -179,6 +181,10 @@ class SttLoadCancelledError(RuntimeError):
"""An in-flight STT model load was cancelled for training."""
+class SttTranscriptionCancelledError(RuntimeError):
+ """An in-flight transcription was cancelled by its client."""
+
+
class SttModelNotDownloadedError(RuntimeError):
"""The selected model is not complete in the shared Hub cache."""
@@ -207,6 +213,29 @@ class SttLanguageError(ValueError):
"""The requested language is not supported by the selected STT model."""
+def _close_connection_on_cancel(connection, cancel_event, done_event) -> None:
+ """Abandon one blocked sidecar HTTP request, leaving its server resident.
+
+ Shutting the socket unblocks the read without touching the process, so a cancelled
+ dictation does not cost the next one a server relaunch and model load. Shared by the
+ whisper.cpp and llama.cpp sidecars.
+ """
+ while not done_event.is_set():
+ if not cancel_event.wait(0.05):
+ continue
+ while not done_event.is_set():
+ sock = connection.sock
+ if sock is not None:
+ try:
+ sock.shutdown(socket.SHUT_RDWR)
+ except OSError:
+ pass
+ connection.close()
+ return
+ time.sleep(0.01)
+ return
+
+
_WHISPER_LANGUAGE_ALIASES = {
# Legacy/browser BCP-47 primaries whose Whisper code differs.
"cmn": "zh",
@@ -651,6 +680,10 @@ class _SnapshotDownloadState:
"model": self._model_id if downloading else None,
"error": self._error,
"cancelled": self._cancelled,
+ # Which model the cancel applies to. "model" goes None once the worker
+ # thread stops, so a settled cancellation was indistinguishable from an
+ # unrelated one and a deferred load restarted the whole download.
+ "cancelled_model": self._model_id if self._cancelled else None,
"bytes_total": self._total_bytes if show_progress else None,
}
captured = (
@@ -907,6 +940,20 @@ def _clear_device_cache(device: Optional[str]) -> None:
pass
+def _reported_device(device: Optional[str]) -> Optional[str]:
+ """Device name for status. Torch calls the HIP device "cuda", which is right for the
+ API and wrong on screen: an AMD card reported as cuda reads like a bug."""
+ if device != "cuda":
+ return device
+ try:
+ import torch
+ if getattr(torch.version, "hip", None):
+ return "rocm"
+ except Exception: # noqa: BLE001 - a label must never fail a status call
+ pass
+ return device
+
+
def _pick_device():
"""Return (device, torch_dtype) for the Whisper model.
@@ -934,12 +981,16 @@ def _pick_device():
return "cpu", torch.float32
-def _decode_audio_bounded(audio: bytes):
+def _decode_audio_bounded(audio: bytes, cancel_event = None):
"""Decode to 16 kHz mono PCM without buffering unbounded audio.
A small, highly-compressed upload can expand far past the encoded request
limit once decoded, so decode frame-by-frame and enforce the sample cap as
frames arrive, then hand the array straight to Whisper.
+
+ ``cancel_event`` is polled inside the frame loop: checking only after the decode
+ returned let an abandoned upload run to EOF or the sample cap, and several of them
+ could do that at once.
"""
try:
import av
@@ -986,6 +1037,8 @@ def _decode_audio_bounded(audio: bytes):
except InvalidDataError:
# Skip a corrupt frame rather than fail the whole transcription.
continue
+ if cancel_event is not None and cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
frame.pts = None
fifo.write(frame)
if fifo.samples >= 500000:
@@ -996,7 +1049,7 @@ def _decode_audio_bounded(audio: bytes):
write_frame(resampled)
for resampled in resampler.resample(None):
write_frame(resampled)
- except (SttAudioDecodeError, SttAudioTooLongError):
+ except (SttAudioDecodeError, SttAudioTooLongError, SttTranscriptionCancelledError):
raise
except (FFmpegError, ValueError, RuntimeError) as exc:
raise SttAudioDecodeError("Could not decode the audio.") from exc
@@ -1021,6 +1074,7 @@ class WhisperSttSidecar:
self._load_state_lock = threading.Lock()
self._loading = False
self._load_cancel_event: Optional[threading.Event] = None
+ self._load_owner_cancel_event: Optional[threading.Event] = None
self._keep_alive_seconds = max(0.0, keep_alive_seconds)
self._idle_timer: Optional[threading.Timer] = None
self._idle_generation = 0
@@ -1031,7 +1085,9 @@ class WhisperSttSidecar:
@property
def device(self) -> Optional[str]:
- return self._device
+ # Reported, so name the backend a user recognises. Torch's ROCm build keeps the
+ # "cuda" device name for HIP, which made an AMD box report "Transformers - cuda".
+ return _reported_device(self._device)
def is_loading(self) -> bool:
with self._load_state_lock:
@@ -1046,6 +1102,15 @@ class WhisperSttSidecar:
event.set()
return True
+ def _cancel_owned_load(self, owner: threading.Event) -> bool:
+ """Cancel startup only when it belongs to this transcription."""
+ with self._load_state_lock:
+ event = self._load_cancel_event
+ if not self._loading or event is None or self._load_owner_cancel_event is not owner:
+ return False
+ event.set()
+ return True
+
def wait_for_load_to_settle(self) -> None:
"""Block until any in-flight load() has exited and freed its memory.
@@ -1056,10 +1121,11 @@ class WhisperSttSidecar:
with self._lock:
pass
- def _begin_load(self) -> threading.Event:
- event = threading.Event()
+ def _begin_load(self, owner: Optional[threading.Event] = None) -> threading.Event:
+ event = owner if owner is not None else threading.Event()
with self._load_state_lock:
self._load_cancel_event = event
+ self._load_owner_cancel_event = owner
self._loading = True
return event
@@ -1067,6 +1133,7 @@ class WhisperSttSidecar:
with self._load_state_lock:
if self._load_cancel_event is event:
self._load_cancel_event = None
+ self._load_owner_cancel_event = None
self._loading = False
@staticmethod
@@ -1187,23 +1254,33 @@ class WhisperSttSidecar:
return _CachedSttSnapshot(path = snapshot_path, is_multilingual = False)
return _CachedSttSnapshot(path = snapshot_path, is_multilingual = None)
- def load(self, model: Optional[str] = None):
+ def load(
+ self,
+ model: Optional[str] = None,
+ request_cancel_event: Optional[threading.Event] = None,
+ ):
"""Load (or switch to) a model, reusing it if already resident.
Returns a ``(model, processor)`` pair.
"""
+ if request_cancel_event is not None and request_cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
model_id = resolve_model_id(model)
with self._lock:
+ if request_cancel_event is not None and request_cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
ensure_stt_available()
if self._engine is not None and self._model_id == model_id:
self._schedule_idle_unload_locked()
return self._engine
import torch
- cancel_event = self._begin_load()
+ cancel_event = self._begin_load(request_cancel_event)
candidate = None
device: Optional[str] = None
+ resident_released = False
try:
+ self._raise_if_load_cancelled(cancel_event)
cached = self._ensure_model_downloaded(model_id)
snapshot_path = cached.path
if snapshot_path is None:
@@ -1214,6 +1291,7 @@ class WhisperSttSidecar:
self._raise_if_load_cancelled(cancel_event)
device, dtype = _pick_device()
self._release_engine_locked()
+ resident_released = True
logger.info("Loading STT model %s (%s) on %s", model_id, snapshot_path, device)
def not_downloaded(cause: BaseException) -> SttModelNotDownloadedError:
@@ -1261,19 +1339,27 @@ class WhisperSttSidecar:
self._model_id = model_id
self._device = device
self._load_cancel_event = None
+ self._load_owner_cancel_event = None
self._loading = False
self._schedule_idle_unload_locked()
logger.info("STT model %s ready on %s", model_id, device)
return self._engine
except SttLoadCancelledError:
candidate = None
- self._release_engine_locked()
+ if resident_released:
+ self._release_engine_locked()
_clear_device_cache(device)
raise
finally:
self._end_load(cancel_event)
- def _transcribe_decoded(self, model_id: str, decoded_audio, generate_kwargs: dict) -> str:
+ def _transcribe_decoded(
+ self,
+ model_id: str,
+ decoded_audio,
+ generate_kwargs: dict,
+ cancel_event: Optional[threading.Event] = None,
+ ) -> str:
"""Run Whisper on already-decoded 16 kHz mono PCM and return text.
Feeds a pre-decoded array so nothing here touches the Transformers audio
@@ -1282,8 +1368,22 @@ class WhisperSttSidecar:
"""
import torch
- model, processor = self.load(model_id)
+ if cancel_event is not None and cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
+ if cancel_event is None:
+ model, processor = self.load(model_id)
+ else:
+ model, processor = self.load(model_id, request_cancel_event = cancel_event)
effective_generate_kwargs = dict(generate_kwargs)
+ if cancel_event is not None:
+ from transformers import StoppingCriteriaList
+ class _CancelCriteria:
+ def __call__(self, *_args, **_kwargs):
+ return cancel_event.is_set()
+
+ effective_generate_kwargs["stopping_criteria"] = StoppingCriteriaList(
+ [_CancelCriteria()]
+ )
generation_config = getattr(model, "generation_config", None)
if getattr(generation_config, "is_multilingual", None) is False:
# English-only checkpoints fix language and task in their generation
@@ -1295,6 +1395,8 @@ class WhisperSttSidecar:
parts: list[str] = []
with torch.no_grad():
for start in range(0, max(len(decoded_audio), 1), window):
+ if cancel_event is not None and cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
segment = decoded_audio[start : start + window]
if segment.size == 0:
continue
@@ -1307,6 +1409,8 @@ class WhisperSttSidecar:
if target_dtype is not None:
features = features.to(target_dtype)
generated = model.generate(features, **effective_generate_kwargs)
+ if cancel_event is not None and cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
text = processor.batch_decode(generated, skip_special_tokens = True)
parts.append(text[0] if text else "")
return " ".join(part.strip() for part in parts if part.strip()).strip()
@@ -1317,6 +1421,7 @@ class WhisperSttSidecar:
model: Optional[str] = None,
language: Optional[str] = None,
fast: bool = False,
+ cancel_event: Optional[threading.Event] = None,
) -> dict:
"""Transcribe encoded audio bytes to text.
@@ -1325,6 +1430,8 @@ class WhisperSttSidecar:
"""
# Reject a missing runtime up front, before the cache and bounded decode.
ensure_stt_available()
+ if cancel_event is not None and cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
# A set language beats auto-detect. API takes BCP-47; Whisper wants short
# codes like en or fr.
lang = normalize_whisper_language(language)
@@ -1341,7 +1448,9 @@ class WhisperSttSidecar:
raise SttLanguageError(
f"Language '{language}' is not supported by English-only STT model '{model_id}'."
)
- decoded_audio = _decode_audio_bounded(audio)
+ decoded_audio = _decode_audio_bounded(audio, cancel_event)
+ if cancel_event is not None and cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
# condition_on_prev_tokens=False stops a fresh clip inheriting prior
# context, which causes runaway repeats.
generate_kwargs = {
@@ -1357,7 +1466,15 @@ class WhisperSttSidecar:
# Serialize inference with model switches and unloads.
with self._lock:
try:
- text = self._transcribe_decoded(model_id, decoded_audio, generate_kwargs)
+ if cancel_event is None:
+ text = self._transcribe_decoded(model_id, decoded_audio, generate_kwargs)
+ else:
+ text = self._transcribe_decoded(
+ model_id,
+ decoded_audio,
+ generate_kwargs,
+ cancel_event,
+ )
finally:
self._schedule_idle_unload_locked()
duration = (len(decoded_audio) / _TARGET_SAMPLE_RATE) if len(decoded_audio) else None
@@ -1368,9 +1485,51 @@ class WhisperSttSidecar:
"model": model_id,
}
- def unload(self) -> None:
- with self._lock:
+ def cancel_transcription(self, cancel_event: threading.Event) -> bool:
+ """Ask this request's Transformers generation or load to stop."""
+ already_cancelled = cancel_event.is_set()
+ cancel_event.set()
+ return self._cancel_owned_load(cancel_event) or not already_cancelled
+
+ def _holds_expected_model(self, expected: Optional[str]) -> bool:
+ """Whether the resident model is the one the caller claimed. Call under ``_lock``.
+
+ A caller that owns a specific model must not release whatever happens to be
+ resident: another surface can switch the engine between the ownership check and
+ the request reaching the sidecar, and the queued unload then tears down a model
+ it never owned.
+ """
+ if expected is None:
+ return True
+ current = self._model_id
+ if current is None:
+ return False
+ if current == expected:
+ return True
+ try:
+ return current == resolve_model_id(expected)
+ except Exception: # noqa: BLE001 - an unresolvable name is not this model
+ return False
+
+ def unload(
+ self,
+ wait: bool = True,
+ expected_model: Optional[str] = None,
+ ) -> None:
+ """Release the resident model. ``wait=False`` skips a sidecar mid-request.
+
+ A transcription holds ``_lock`` throughout, so a caller releasing engines it does
+ not own must be able to leave a busy one alone. ``expected_model`` scopes the
+ release to one model, compared under the lock.
+ """
+ if not self._lock.acquire(blocking = wait):
+ return
+ try:
+ if not self._holds_expected_model(expected_model):
+ return
self._release_engine_locked()
+ finally:
+ self._lock.release()
_sidecar: Optional[WhisperSttSidecar] = None
diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.py
index 0c2c3beed85..559af125a03 100644
--- a/studio/backend/core/inference/worker.py
+++ b/studio/backend/core/inference/worker.py
@@ -25,6 +25,7 @@ from pathlib import Path
from typing import Any
logger = get_logger(__name__)
+from core.inference.audio_errors import AUDIO_UNSUPPORTED_CODE
from utils.hardware import apply_gpu_ids, is_apple_silicon
# Fresh spawned interpreter: re-apply the OS-trust-store injection.
@@ -515,27 +516,57 @@ def _handle_load(backend, config: dict, resp_queue: Any) -> None:
)
-def _drain_skip_generate(cmd: dict, resp_queue: Any, drain_event) -> bool:
+def _drain_skip_generate(
+ cmd: dict,
+ resp_queue: Any,
+ drain_event,
+ *,
+ audio: bool = False,
+) -> bool:
"""Skip a generate queued behind a cancelled one during an unload.
The parent sets ``drain_event`` for the whole unload. Because the parent's
per-token ``cancel_event`` is cleared at the start of every generate, a cancel
set while this generate was still queued would otherwise be lost when it is
- dequeued. If the drain is in effect, emit an immediate (empty) ``gen_done`` so
- the parent's stream/mailbox drains fast and the switch stays fast, and report
- the generate was skipped so the caller does not clear the cancel or run it.
+ dequeued. If the drain is in effect, emit an immediate terminal response
+ (``gen_done`` or ``audio_error``) so the parent's mailbox drains fast and the
+ switch stays fast, and report the generate was skipped so the caller does not
+ clear the cancel or run it.
"""
if drain_event is None or not drain_event.is_set():
return False
request_id = cmd.get("request_id", "")
logger.info("Skipping generate for request %s: unload draining", request_id)
+ response = {
+ "type": "audio_error" if audio else "gen_done",
+ "request_id": request_id,
+ "cancelled": True,
+ }
+ if audio:
+ response["error"] = "Audio generation cancelled"
+ else:
+ response["stats"] = None
+ _send_response(resp_queue, response)
+ return True
+
+
+def _prepare_generate_audio(cmd, resp_queue: Any, cancel_event, drain_event) -> bool:
+ """Clear stale cancellation and acknowledge when this TTS command owns the worker.
+
+ The durable unload drain is checked on both sides of the clear so an unload
+ landing in that window skips TTS instead of having its shared cancel erased.
+ The parent does not signal request cancellation until it receives audio_started.
+ """
+ if _drain_skip_generate(cmd, resp_queue, drain_event, audio = True):
+ return False
+ cancel_event.clear()
+ if _drain_skip_generate(cmd, resp_queue, drain_event, audio = True):
+ return False
_send_response(
resp_queue,
{
- "type": "gen_done",
- "request_id": request_id,
- "cancelled": True,
- "stats": None,
+ "type": "audio_started",
+ "request_id": cmd.get("request_id", ""),
},
)
return True
@@ -698,7 +729,7 @@ def _handle_share_object(backend, cmd: dict, resp_queue: Any) -> None:
)
-def _handle_generate_audio(backend, cmd: dict, resp_queue: Any) -> None:
+def _handle_generate_audio(backend, cmd: dict, resp_queue: Any, cancel_event) -> None:
"""Handle TTS audio generation — returns WAV bytes + sample_rate."""
request_id = cmd.get("request_id", "")
try:
@@ -712,6 +743,7 @@ def _handle_generate_audio(backend, cmd: dict, resp_queue: Any) -> None:
max_new_tokens = cmd.get("max_new_tokens", 2048),
repetition_penalty = cmd.get("repetition_penalty", 1.0),
use_adapter = cmd.get("use_adapter"),
+ cancel_event = cancel_event,
)
# Send WAV bytes as base64 (bytes can't go through mp.Queue directly).
@@ -734,6 +766,11 @@ def _handle_generate_audio(backend, cmd: dict, resp_queue: Any) -> None:
"type": "audio_error",
"request_id": request_id,
"error": str(exc),
+ # The route's own cancel event is not set when the worker's shared event is
+ # (an unload, a training admission, the GPU arbiter), so without this flag the
+ # orchestrator reports a cancellation as HTTP 500. Matching on the message text
+ # is what AudioGenerationCancelledError exists to avoid.
+ "cancelled": bool(cancel_event is not None and cancel_event.is_set()),
"stack": traceback.format_exc(limit = 20),
},
)
@@ -1030,6 +1067,15 @@ def run_inference_process(
"type": "audio_error",
"request_id": cmd.get("request_id"),
"error": "Text-to-speech is not supported on the MLX backend yet.",
+ # Lets the parent raise a typed error, not a generic 500.
+ "code": AUDIO_UNSUPPORTED_CODE,
+ # Only some TTS families publish a GGUF build, so name the
+ # host as the general fix and GGUF as the conditional one.
+ "hint": (
+ "Run it on a non-MLX host, or load a GGUF build of it "
+ "if one is published -- llama.cpp carries the "
+ "snac/bicodec/dac decoders."
+ ),
},
)
elif cmd_type == "share_object":
@@ -1282,8 +1328,9 @@ def run_inference_process(
_handle_load(backend, cmd, resp_queue)
elif cmd_type == "generate_audio":
- cancel_event.clear()
- _handle_generate_audio(backend, cmd, resp_queue)
+ if not _prepare_generate_audio(cmd, resp_queue, cancel_event, drain_event):
+ continue
+ _handle_generate_audio(backend, cmd, resp_queue, cancel_event)
elif cmd_type == "generate_audio_input":
cancel_event.clear()
diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.py
index 559192f917f..e40e7fc7c43 100644
--- a/studio/backend/core/training/trainer.py
+++ b/studio/backend/core/training/trainer.py
@@ -60,6 +60,7 @@ from pathlib import Path
from typing import Any, Dict, List, Optional, Callable
import pandas as pd
from datasets import Dataset
+from utils.datasets.audio_decode import ensure_audio_decoding
from utils.datasets.cache_safe import load_dataset_cache_safe as load_dataset
from utils.hf_dataset_options import hf_dataset_split_instruction_names
from utils.third_party_source import (
@@ -174,6 +175,28 @@ def _drop_hf_stdout_callbacks(trainer) -> None:
pass
+def _spark_tts_tokenizer_kwargs(audio_type: Optional[str], lookup_name: str) -> dict:
+ """``subfolder`` for a Spark-TTS repo root, empty for anything else.
+
+ Only the canonical repo layout needs it: a local checkpoint or an alias that already
+ names LLM/ points at the tokenizer directly.
+ """
+ if audio_type != "bicodec":
+ return {}
+ name = str(lookup_name).replace("\\", "/").rstrip("/")
+ if name.endswith("/LLM"):
+ return {}
+ # An LLM/ child is the canonical layout, and a cache-pinned or offline snapshot root has
+ # one too. Treating that as "already at the tokenizer" sent AutoTokenizer at the root,
+ # which holds no tokenizer, and failed the very case this helper exists for.
+ if os.path.isdir(os.path.join(lookup_name, "LLM")):
+ return {"subfolder": "LLM"}
+ # A local checkpoint that carries its own tokenizer is already the right directory.
+ if os.path.isfile(os.path.join(lookup_name, "tokenizer_config.json")):
+ return {}
+ return {"subfolder": "LLM"}
+
+
class UnslothTrainer:
"""
Unsloth Training Backend
@@ -308,6 +331,11 @@ class UnslothTrainer:
token = hf_token,
local_files_only = local_files_only,
revision = model_revision,
+ # Spark-TTS keeps only BiCodec, config.yaml and the source tree at its repo
+ # root; the tokenizer lives under LLM/, the same subfolder _load_model loads
+ # weights from. Reading the root finds no vocab and fails to build a backend
+ # tokenizer, blaming a missing sentencepiece that is installed and irrelevant.
+ **_spark_tts_tokenizer_kwargs(self._audio_type, lookup_name),
)
logger.info("Pre-loaded tokenizer for %s", model_name)
@@ -892,22 +920,16 @@ class UnslothTrainer:
from huggingface_hub import snapshot_download
if model_name.endswith("/LLM"):
- # "Spark-TTS-0.5B/LLM" → parent="Spark-TTS-0.5B"
- local_dir = model_name.rsplit("/", 1)[0]
- hf_repo = f"unsloth/{local_dir}"
- llm_path = model_name
+ # "Spark-TTS-0.5B/LLM" → repo "unsloth/Spark-TTS-0.5B"
+ hf_repo = f"unsloth/{model_name.rsplit('/', 1)[0]}"
else:
- # "unsloth/Spark-TTS-0.5B" → local_dir="Spark-TTS-0.5B"
hf_repo = model_name
- local_dir = model_name.split("/")[-1]
- llm_path = f"{local_dir}/LLM"
if local_files_only:
repo_path = lookup_name
else:
repo_path = snapshot_download(
hf_repo,
- local_dir = local_dir,
revision = model_revision,
)
self._spark_tts_repo_dir = os.path.abspath(repo_path) # Absolute for sys.path
@@ -2850,6 +2872,14 @@ class UnslothTrainer:
return None
# ========== AUDIO MODELS: custom preprocessing ==========
+ # Every audio branch below, and the VLM path, casts an Audio column and reads its array.
+ if self._audio_type or self.is_audio_vlm:
+ if not ensure_audio_decoding():
+ raise RuntimeError(
+ "This host cannot decode audio datasets: torchcodec cannot load its "
+ "FFmpeg libraries, and the soundfile fallback needs soundfile and "
+ "librosa. Install an FFmpeg full-shared build, or install both."
+ )
if self._audio_type == "csm":
processed = self._preprocess_csm_dataset(dataset, custom_format_mapping)
return (processed, None)
diff --git a/studio/backend/hub/services/datasets/formatting.py b/studio/backend/hub/services/datasets/formatting.py
index 7ce00bcf92f..c60b5b502b1 100644
--- a/studio/backend/hub/services/datasets/formatting.py
+++ b/studio/backend/hub/services/datasets/formatting.py
@@ -43,6 +43,7 @@ from hub.utils.paths import (
normalize_path,
resolve_dataset_path,
)
+from utils.datasets.audio_decode import ensure_audio_decoding
logger = get_logger(__name__)
@@ -119,6 +120,22 @@ def _serialize_binary_value(data):
return f"<binary data, {len(data)} bytes>"
+def _serialize_decoded_audio(value):
+ """Summarise a decoded Audio cell the way binary cells are summarised."""
+ samples = value.get("array") or []
+ rate = value.get("sampling_rate")
+ try:
+ seconds = len(samples) / rate if rate else None
+ except (TypeError, ZeroDivisionError):
+ seconds = None
+ detail = f"{len(samples)} samples"
+ if rate:
+ detail += f" @ {rate} Hz"
+ if seconds is not None:
+ detail += f", {seconds:.1f}s"
+ return f"<audio, {detail}>"
+
+
def _serialize_preview_value(value):
if value is None or isinstance(value, (str, int, float, bool)):
return value
@@ -140,6 +157,13 @@ def _serialize_preview_value(value):
value.keys() - {"bytes", "path"}
):
return _serialize_binary_value(raw)
+ # A decoded Audio cell is {"array", "sampling_rate", "path"}. torchcodec hands back
+ # an AudioDecoder, which falls through to str() below, but the soundfile fallback
+ # returns the waveform and the dataset formatter turns it into a plain list -- one
+ # float per sample, so ten preview rows of a few seconds each is tens of MB of JSON
+ # and the client dies rendering it.
+ if "sampling_rate" in value and isinstance(value.get("array"), (list, tuple)):
+ return _serialize_decoded_audio(value)
return {str(key): _serialize_preview_value(item) for key, item in value.items()}
if isinstance(value, (list, tuple)):
@@ -315,6 +339,9 @@ def check_format_response(
logger.info(f"Checking format for dataset: {request.dataset_name}")
+ # An audio column decodes on the first preview row, so this precedes every tier.
+ ensure_audio_decoding()
+
try:
dataset_path = resolve_dataset_path(request.dataset_name)
except ValueError as e:
diff --git a/studio/backend/hub/services/models/cache_inventory.py b/studio/backend/hub/services/models/cache_inventory.py
index 14e2706e80d..72acc2e2c6d 100644
--- a/studio/backend/hub/services/models/cache_inventory.py
+++ b/studio/backend/hub/services/models/cache_inventory.py
@@ -45,7 +45,7 @@ from hub.services.models.common import (
# scan loop swallows per-repo exceptions and would drop every repo. Lives under
# ``utils`` (not ``utils.models``) to avoid the eager model-config/checkpoint
# imports in ``utils/models/__init__.py``.
-from utils.hidden_models import is_hidden_model
+from utils.hidden_models import is_curated_stt_repo_id, is_hidden_model
logger = get_logger(__name__)
@@ -361,6 +361,7 @@ def _cache_inventory_fields(
repo_info = None,
hidden_infra: bool = False,
companion: bool = False,
+ stt_only: bool = False,
) -> dict:
"""Load identity plus the capability block for one cache row.
@@ -399,6 +400,15 @@ def _cache_inventory_fields(
else repo_info is not None and _repo_has_mmproj(repo_info)
):
capabilities["supports_vision"] = True
+ # Qwen3-ASR's required mmproj is an audio projector, not a vision
+ # projector. Curated STT rows are visible only to task-scoped consumers and
+ # must never become eligible for chat auto-load.
+ # ``stt_only`` covers any repo whose config sniffs as Whisper, curated or not: a
+ # third-party checkpoint or a user's own fine-tune is just as unchattable, and can_chat
+ # is what auto-load and the chat picker filter on, neither of which looks at the task.
+ if stt_only or is_curated_stt_repo_id(repo_id):
+ capabilities["supports_vision"] = False
+ capabilities["can_chat"] = False
if hidden_infra:
capabilities["can_chat"] = False
# A VAE / text-encoder mirror holds no language model, so it cannot chat whatever its weight
@@ -523,9 +533,12 @@ def _scan_cached_gguf(
str(repo_path),
str(snapshot_path) if snapshot_path is not None else None,
)
+ is_curated_stt = is_curated_stt_repo_id(repo_id)
# Hide infra repos unless the user downloaded a variant via
- # the Hub; variant state only exists for user downloads.
- if is_hidden_infra and not has_variant_state:
+ # the Hub; variant state only exists for user downloads. Exact
+ # curated STT repos are still emitted as management rows and
+ # the frontend's task allowlist keeps them out of Chat.
+ if is_hidden_infra and not is_curated_stt and not has_variant_state:
continue
if total_size == 0 and not has_variant_state:
continue
@@ -950,7 +963,6 @@ def _scan_cached_models(
inspected = 0
skipped_gguf = 0
skipped_no_weights = 0
- skipped_stt = 0
for hf_cache in cache_scans:
for repo_info in hf_cache.repos:
inspected += 1
@@ -961,11 +973,15 @@ def _scan_cached_models(
repo_path = Path(repo_info.repo_path)
snapshot_path = _cached_model_snapshot_path(repo_path)
# The non-GGUF embedder has no variant downloads; always hide.
- if _is_hidden_infra_repo(
+ is_hidden_infra = _is_hidden_infra_repo(
repo_id,
str(repo_path),
str(snapshot_path) if snapshot_path is not None else None,
- ):
+ )
+ is_curated_stt = is_curated_stt_repo_id(repo_id)
+ snapshot_metadata = _cached_model_local_metadata(repo_path, snapshot_path)
+ is_whisper_stt = bool(snapshot_metadata.get("_hidden_stt"))
+ if is_hidden_infra and not is_curated_stt and not is_whisper_stt:
continue
has_main_gguf = _repo_has_gguf_files(repo_info)
payload = _repo_non_gguf_model_payload(repo_info)
@@ -987,10 +1003,13 @@ def _scan_cached_models(
payload_snapshots = payload.payload_snapshots,
)
load_snapshot = identity.load_snapshot
- local_metadata = _cached_model_local_metadata(repo_path, load_snapshot)
- if local_metadata.pop("_hidden_stt", False):
- skipped_stt += 1
- continue
+ # Reused when the row hands out the snapshot probed above: each call rereads two files.
+ local_metadata = (
+ snapshot_metadata
+ if load_snapshot == snapshot_path
+ else _cached_model_local_metadata(repo_path, load_snapshot)
+ )
+ is_whisper_stt = local_metadata.pop("_hidden_stt", False)
# Scoped to the row's snapshot, so an incomplete newer revision cannot flip can_chat.
download_partial = hf_cache_scan.is_snapshot_partial(
"model",
@@ -1017,7 +1036,22 @@ def _scan_cached_models(
# serves the row and it would reach for the Hub.
if not payload.payload_snapshots:
snapshot_partial = True
- row_task = _cached_row_task(repo_info, gguf = False)
+ row_task = (
+ "automatic-speech-recognition"
+ if is_whisper_stt
+ else (
+ "text-to-speech"
+ if local_metadata.get("pipeline_tag") == "text-to-speech"
+ else _cached_row_task(repo_info, gguf = False)
+ )
+ )
+ if is_whisper_stt:
+ local_metadata["pipeline_tag"] = "automatic-speech-recognition"
+ local_metadata["library_name"] = "transformers"
+ tags = list(local_metadata.get("tags", []))
+ if not any(tag.lower() == "whisper" for tag in tags):
+ tags.append("whisper")
+ local_metadata["tags"] = tags
row = {
"repo_id": repo_id,
"size_bytes": payload.size_bytes,
@@ -1058,7 +1092,9 @@ def _scan_cached_models(
payload.model_format,
identity = identity,
partial = bool(row["partial"]),
+ hidden_infra = is_hidden_infra,
companion = bool(row["companion"]),
+ stt_only = bool(is_whisper_stt),
)
)
if _prefer_cache_row(row, existing):
@@ -1071,12 +1107,10 @@ def _scan_cached_models(
continue
cached = sorted(seen_lower.values(), key = lambda c: c["repo_id"])
logger.info(
- "Cached model scan: inspected=%d skipped_gguf=%d skipped_no_weights=%d "
- "skipped_stt=%d returned=%d",
+ "Cached model scan: inspected=%d skipped_gguf=%d skipped_no_weights=%d returned=%d",
inspected,
skipped_gguf,
skipped_no_weights,
- skipped_stt,
len(cached),
)
return cached
diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.py
index f7f57f97520..6c746b3e711 100644
--- a/studio/backend/hub/tests/test_model_services.py
+++ b/studio/backend/hub/tests/test_model_services.py
@@ -1717,6 +1717,34 @@ def test_cached_gguf_scan_hides_infra_repos_without_user_downloads(monkeypatch,
assert [row["repo_id"] for row in result["cached"]] == ["Org/Chat-GGUF"]
+def test_cached_gguf_scan_emits_curated_asr_as_non_chat_audio_inventory(monkeypatch, tmp_path):
+ asr = _repo(
+ "unslothai/Qwen3-ASR-0.6B-GGUF",
+ [
+ _file("Qwen3-ASR-0.6B-Q8_0.gguf", 800_000_000),
+ _file("mmproj-Qwen3-ASR-0.6B-Q8_0.gguf", 200_000_000),
+ ],
+ tmp_path / "asr",
+ )
+ monkeypatch.setattr(
+ cache_inventory,
+ "all_hf_cache_scans",
+ lambda: [SimpleNamespace(repos = [asr])],
+ )
+ monkeypatch.setattr(
+ cache_inventory.hf_cache_scan,
+ "is_gguf_repo_partial",
+ lambda _repo_id, _path, **_kw: False,
+ )
+
+ [row] = cache_inventory._scan_cached_gguf()
+
+ assert row["repo_id"] == "unslothai/Qwen3-ASR-0.6B-GGUF"
+ assert row["size_bytes"] == 800_000_000
+ assert row["capabilities"]["can_chat"] is False
+ assert row["capabilities"]["supports_vision"] is False
+
+
def test_cached_gguf_scan_keeps_infra_repo_with_user_downloaded_variant(monkeypatch, tmp_path):
monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
embedder = _repo(
@@ -1783,6 +1811,45 @@ def test_cached_models_scan_hides_non_gguf_embedder(monkeypatch, tmp_path):
assert [row["repo_id"] for row in result["cached"]] == ["Org/Chat"]
+def test_cached_models_scan_emits_curated_and_custom_whisper_as_stt(monkeypatch, tmp_path):
+ curated_path = tmp_path / "hub" / "models--unsloth--whisper-tiny"
+ curated_path.mkdir(parents = True)
+ curated = _repo(
+ "unsloth/whisper-tiny",
+ [_file("config.json", 12), _file("model.safetensors", 80_000_000)],
+ curated_path,
+ )
+ custom_path = tmp_path / "hub" / "models--Org--custom-whisper"
+ custom_path.mkdir(parents = True)
+ custom = _repo(
+ "Org/custom-whisper",
+ [_file("config.json", 12), _file("model.safetensors", 90_000_000)],
+ custom_path,
+ )
+ monkeypatch.setattr(
+ cache_inventory,
+ "all_hf_cache_scans",
+ lambda: [SimpleNamespace(repos = [curated, custom])],
+ )
+ monkeypatch.setattr(
+ cache_inventory.hf_cache_scan,
+ "is_snapshot_partial",
+ lambda _kind, _repo_id, _path, **_kw: False,
+ )
+ monkeypatch.setattr(
+ cache_inventory,
+ "_cached_model_local_metadata",
+ lambda repo_path, _snapshot = None: {"_hidden_stt": "custom-whisper" in str(repo_path)},
+ )
+
+ rows = cache_inventory._scan_cached_models()
+
+ rows_by_repo = {row["repo_id"]: row for row in rows}
+ assert set(rows_by_repo) == {"unsloth/whisper-tiny", "Org/custom-whisper"}
+ assert rows_by_repo["Org/custom-whisper"]["task"] == "automatic-speech-recognition"
+ assert all(row["capabilities"]["can_chat"] is False for row in rows_by_repo.values())
+
+
_SNAPSHOT_SHA = "a" * 40
diff --git a/studio/backend/hub/utils/dataset_format.py b/studio/backend/hub/utils/dataset_format.py
index df020353654..f6d92ea581e 100644
--- a/studio/backend/hub/utils/dataset_format.py
+++ b/studio/backend/hub/utils/dataset_format.py
@@ -403,15 +403,20 @@ def detect_multimodal_dataset(dataset):
detected_text_col = None
if audio_columns:
- for col_name in column_names:
- if col_name.lower() in [
- "text",
- "sentence",
- "transcript",
- "transcription",
- "label",
- ]:
- detected_text_col = col_name
+ # Two passes, not one list: a set carrying both an instruction-like "prompt" and a
+ # real "transcript" would otherwise be mapped by schema order, and training an ASR
+ # set against its instructions instead of its ground truth fails silently.
+ transcript_names = ("text", "sentence", "transcript", "transcription", "label")
+ # TTS corpora name the line to speak rather than a transcript of it: every
+ # svjack/SparkTTS_* set uses "prompt", LJSpeech derivatives use "normalized_text".
+ # Without these the set needs a manual mapping it cannot satisfy.
+ fallback_names = ("prompt", "normalized_text")
+ for candidates in (transcript_names, fallback_names):
+ for col_name in column_names:
+ if col_name.lower() in candidates:
+ detected_text_col = col_name
+ break
+ if detected_text_col:
break
detected_speaker_col = None
if audio_columns:
diff --git a/studio/backend/main.py b/studio/backend/main.py
index cbd2baee0b5..b0d48ce620c 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -997,17 +997,26 @@ _DATA_RECIPE_UNSTRUCTURED_UPLOAD_PASSTHROUGH_PREFIX = (
# The diffusion dataset upload (POST /api/train/diffusion/dataset) is a multipart upload
# under /api/train; like /api/datasets/upload it enforces its own cap. EXACT path.
_DIFFUSION_DATASET_UPLOAD_PATH = "/api/train/diffusion/dataset"
+_STT_MULTIPART_UPLOAD_PATHS = (
+ "/v1/audio/transcriptions",
+ "/api/inference/audio/transcriptions",
+)
_BODY_UPLOAD_PASSTHROUGH_PREFIXES = (
*_DATASET_UPLOAD_PASSTHROUGH_PREFIXES,
_DATA_RECIPE_UNSTRUCTURED_UPLOAD_PASSTHROUGH_PREFIX,
)
-# Matched by EXACT path (the multipart upload only), so sibling JSON sub-routes keep the normal cap.
-_BODY_UPLOAD_PASSTHROUGH_EXACT_PATHS = (_DIFFUSION_DATASET_UPLOAD_PATH,)
+# Matched by EXACT path (multipart uploads only), so sibling JSON sub-routes keep the normal cap.
+_BODY_UPLOAD_PASSTHROUGH_EXACT_PATHS = (
+ _DIFFUSION_DATASET_UPLOAD_PATH,
+ *_STT_MULTIPART_UPLOAD_PATHS,
+)
def _get_upload_passthrough_request_max_bytes(path: str) -> int:
if path.startswith(_DATA_RECIPE_UNSTRUCTURED_UPLOAD_PASSTHROUGH_PREFIX):
return upload_request_limit_bytes(UNSTRUCTURED_RECIPE_UPLOAD_MAX_BYTES)
+ if path.rstrip("/") in _STT_MULTIPART_UPLOAD_PATHS:
+ return upload_request_limit_bytes(STT_AUDIO_RAW_MAX_BYTES)
# The trailing-slash variant reaches this middleware BEFORE the router's redirect_slashes
# 307, so it must resolve to the same cap. JSON sub-routes keep extra path components.
if (
@@ -1023,6 +1032,9 @@ def _get_request_body_max_bytes(path: str) -> int:
return STT_AUDIO_RAW_MAX_BYTES
if path.startswith("/api/inference/audio/transcribe"):
return STT_AUDIO_JSON_MAX_BYTES
+ # multipart headroom over the raw stt cap for the openai transcription route on both mounts
+ if path.rstrip("/") in _STT_MULTIPART_UPLOAD_PATHS:
+ return upload_request_limit_bytes(STT_AUDIO_RAW_MAX_BYTES)
return default_request_body_limit_bytes()
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 568bfeb9be3..9674437a6c8 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -27,6 +27,13 @@ class LoadRequest(BaseModel):
"""Request to load a model for inference"""
model_path: str = Field(..., description = "Model identifier or local path")
+ load_request_id: Optional[str] = Field(
+ None,
+ min_length = 1,
+ max_length = 128,
+ pattern = r"^[A-Za-z0-9][A-Za-z0-9._:-]*$",
+ description = "Opaque client attempt ID for scoped in-flight cancellation",
+ )
native_path_lease: Optional[str] = Field(
None, description = "Frontend-visible signed native path grant"
)
@@ -273,6 +280,13 @@ class UnloadRequest(BaseModel):
"""Request to unload a model"""
model_path: str = Field(..., description = "Model identifier to unload")
+ cancel_load_request_id: Optional[str] = Field(
+ None,
+ min_length = 1,
+ max_length = 128,
+ pattern = r"^[A-Za-z0-9][A-Za-z0-9._:-]*$",
+ description = ("Cancel only this in-flight load attempt; never unload a resident model"),
+ )
force_cancel_active: bool = Field(
False,
description = (
@@ -3163,6 +3177,54 @@ class ImageGenerationResponse(BaseModel):
data: list[ImageGenerationData] = Field(..., description = "The generated images.")
+# ── OpenAI-compatible audio API (POST /v1/audio/speech) ──
+
+
+class AudioSpeechRequest(BaseModel):
+ """OpenAI ``CreateSpeechRequest`` for ``POST /v1/audio/speech``.
+
+ ``voice`` and ``speed`` are accepted for client compatibility but unused: no loaded
+ TTS backend has voice or rate plumbing (CSM is fixed to speaker 0)."""
+
+ input: str = Field(..., min_length = 1, description = "The text to synthesize.")
+ model: Optional[str] = Field(
+ None, description = "Model id (informational; the loaded audio model is used)."
+ )
+ voice: Optional[str] = Field(None, description = "Voice name (accepted, unused).")
+ response_format: Optional[str] = Field(
+ "wav", description = "Output container. Only 'wav' is supported."
+ )
+ speed: Optional[float] = Field(None, description = "Speech rate (accepted, unused).")
+
+ @field_validator("response_format", mode = "before")
+ @classmethod
+ def _null_format_means_default(cls, value):
+ # openai marks response_format nullable with a default, so an explicit null means wav
+ return "wav" if value is None else value
+
+
+class AudioGalleryItem(BaseModel):
+ """One persisted TTS clip. ``url`` serves the WAV bytes (auth required)."""
+
+ id: str
+ url: str
+ prompt: str
+ model: str
+ audio_type: str
+ sample_rate: int
+ duration_s: float
+ created_at: str
+
+
+class AudioGalleryListResponse(BaseModel):
+ """A newest-first window of the audio gallery for infinite scroll."""
+
+ audio: List[AudioGalleryItem] = Field(default_factory = list)
+ has_more: bool = False
+ next_before_mtime: Optional[float] = None
+ next_before_id: Optional[str] = None
+
+
# ── Video (local text-to-video) ──
diff --git a/studio/backend/models/models.py b/studio/backend/models/models.py
index be2da4f0498..b4adf0614d0 100644
--- a/studio/backend/models/models.py
+++ b/studio/backend/models/models.py
@@ -91,6 +91,15 @@ class ModelDetails(BaseModel):
)
is_audio: bool = Field(False, description = "Whether model is a TTS audio model")
audio_type: Optional[str] = Field(None, description = "Audio codec type: snac, csm, bicodec, dac")
+ audio_type_known: bool = Field(
+ True,
+ description = (
+ "Whether audio_type is a definitive answer. False means the repo's "
+ "tokenizer_config.json could not be read (gated, offline, upstream error), so a "
+ "null audio_type means unknown rather than 'not an audio model'. Defaults True "
+ "so callers that never set it keep the old meaning."
+ ),
+ )
has_audio_input: bool = Field(False, description = "Whether model accepts audio input (ASR)")
model_type: Optional[ModelType] = Field(
None, description = "Collapsed model modality: text, vision, audio, or embeddings"
@@ -114,6 +123,15 @@ class LoRAInfo(BaseModel):
export_type: Optional[str] = Field(
None, description = "'lora', 'merged', or 'gguf' (for exports)"
)
+ audio_type: Optional[str] = Field(
+ None,
+ description = (
+ "Codec of the adapter's base model ('snac', 'bicodec', 'dac', 'csm', "
+ "'whisper', 'audio_vlm') when it fine-tunes an audio model, else null. "
+ "The Audio page needs this to offer a trained checkpoint: a scan row "
+ "carries no modality otherwise, so an audio adapter reads as a text one."
+ ),
+ )
class LoRAScanResponse(BaseModel):
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 88d579a8890..d33f51b7e47 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -13,9 +13,19 @@ from pathlib import Path
import hashlib as _hashlib
import hmac as _hmac
import secrets as _secrets
-from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
+from fastapi import (
+ APIRouter,
+ Depends,
+ File,
+ Form,
+ HTTPException,
+ Query,
+ Request,
+ UploadFile,
+ status,
+)
from fastapi.encoders import jsonable_encoder
-from fastapi.responses import StreamingResponse, JSONResponse, Response
+from fastapi.responses import StreamingResponse, JSONResponse, PlainTextResponse, Response
from starlette.requests import ClientDisconnect
from typing import Any, Callable, Collection, List, NamedTuple, Optional, Union
import json
@@ -39,7 +49,15 @@ from utils.models import extract_model_size_b as _extract_model_size_b
from utils.api_errors import openai_error_body, anthropic_error_body, error_body_for_path
from utils.upload_limits import STT_AUDIO_B64_MAX_CHARS, STT_AUDIO_RAW_MAX_BYTES
from hub.dependencies import get_hf_token
-from core.inference.orchestrator import GenStreamError, GenStreamErrorRaised
+from core.inference.audio_errors import (
+ AudioBackendUnsupportedError,
+ AudioGenerationCancelledError,
+)
+from core.inference.orchestrator import (
+ AUDIO_GENERATION_MAX_TOKENS,
+ GenStreamError,
+ GenStreamErrorRaised,
+)
from core.inference.llama_admission import (
LlamaAdmissionCancelled,
LlamaAdmissionConfig,
@@ -359,6 +377,91 @@ def _effective_max_tokens(payload):
)
+# Below this there is no room for speech worth returning, so an over-context prompt is a
+# client error rather than a one-token generation.
+_MIN_SPEECH_OUTPUT_TOKENS = 64
+
+# The backends do not generate from the raw text: each wraps it in codec delimiters
+# (llama_cpp.py:_TTS_PROMPTS, and the model-specific prompts the Transformers generators
+# build), so the real prompt is longer than what the estimate below sees. Budgeting the
+# whole remainder left zero headroom and those few tokens pushed prompt + max_new_tokens
+# back over the context. Generous rather than exact, since the wrapper is chosen deeper
+# than this and 32 tokens off a 2048 context is not worth threading it up here.
+_TTS_PROMPT_FORMAT_RESERVE = 32
+
+
+def _tts_max_new_tokens(payload, prompt: Optional[str] = None) -> int:
+ """Bound TTS work consistently across llama.cpp and subprocess backends.
+
+ ``prompt`` shares the loaded context with the output, so a Max tokens slider near the
+ ceiling plus a long prompt overflowed the context the page loaded with. Capped here so
+ both the Studio and OpenAI routes inherit it.
+ """
+ budget = min(
+ AUDIO_GENERATION_MAX_TOKENS,
+ max(1, int(_effective_max_tokens(payload) or 2048)),
+ )
+ if prompt:
+ context_length = _monitor_context_length()
+ if context_length:
+ budget = min(
+ budget,
+ context_length - _prompt_token_estimate(prompt) - _TTS_PROMPT_FORMAT_RESERVE,
+ )
+ # A caller that reached generation with no budget left gets one token and a useless
+ # clip; the routes reject that case up front instead.
+ return max(1, budget)
+
+
+def _raise_if_prompt_leaves_no_speech_budget(text: str) -> None:
+ """400 when the prompt alone consumes the loaded context.
+
+ Shared by both TTS routes: the budget helper floors at one token so generation always
+ has something to ask for, which on its own would send an over-context prompt into the
+ backend to fail there or return a clip too short to hold codec tokens.
+ """
+ context_length = _monitor_context_length()
+ if not context_length:
+ return
+ remaining = context_length - _prompt_token_estimate(text) - _TTS_PROMPT_FORMAT_RESERVE
+ if remaining < _MIN_SPEECH_OUTPUT_TOKENS:
+ raise HTTPException(
+ status_code = 400,
+ detail = (
+ f"Input is too long for the loaded model's {context_length}-token context. "
+ "Shorten it, or load the model with a larger context."
+ ),
+ )
+
+
+def _prompt_token_estimate(prompt: str) -> int:
+ """Tokens the prompt will occupy, from the loaded tokenizer where one is reachable.
+
+ The len//3 fallback under-counts CJK and emoji badly, which is exactly the input that
+ then overflows the context, so ask the tokenizer first and only guess when it is absent.
+ """
+ try:
+ backend = _peek_inference_backend()
+ if backend is not None and backend.active_model_name:
+ models = getattr(backend, "models", {}) or {}
+ info = models.get(backend.active_model_name, {}) if isinstance(models, dict) else {}
+ tokenizer = info.get("tokenizer") if isinstance(info, dict) else None
+ if tokenizer is not None and hasattr(tokenizer, "encode"):
+ count = len(tokenizer.encode(prompt))
+ if count > 0:
+ return count
+ except Exception: # noqa: BLE001 - an estimate must never fail the request
+ pass
+ # llama-server holds its own tokenizer, so estimate by character class instead of a
+ # flat ratio. Everything outside ASCII counts as a token: the earlier cut at U+2E7F
+ # only caught CJK and emoji, so Arabic, Cyrillic, Hebrew and the Indic scripts were
+ # billed at the Latin third-of-a-token rate and a long prompt in any of them passed
+ # the guard, then overflowed the context during generation. Over-counting accented
+ # Latin is the safe direction for a budget: it shortens the clip rather than failing.
+ dense = sum(1 for ch in prompt if ord(ch) > 0x7F)
+ return max(1, dense + (len(prompt) - dense) // 3)
+
+
_OPENAI_COMPAT_STREAM_STALL_TIMEOUT_ENV = "UNSLOTH_OPENAI_COMPAT_STREAM_STALL_TIMEOUT"
@@ -2076,6 +2179,9 @@ from models.inference import (
ImageGenerationRequest,
ImageGenerationData,
ImageGenerationResponse,
+ AudioSpeechRequest,
+ AudioGalleryItem,
+ AudioGalleryListResponse,
LoadResponse,
LoadProgressResponse,
UnloadResponse,
@@ -2829,6 +2935,16 @@ async def _await_disconnect_then_cancel(request, cancel_event) -> None:
return
+async def _await_stt_disconnect_then_cancel(request, sidecar, cancel_event) -> None:
+ """Cancel this sidecar request, including a model load still starting."""
+ try:
+ while not await request.is_disconnected():
+ await asyncio.sleep(0.1)
+ await asyncio.to_thread(sidecar.cancel_transcription, cancel_event)
+ except asyncio.CancelledError:
+ return
+
+
def _cancelable_nonstreaming_client() -> httpx.AsyncClient:
return httpx.AsyncClient(
limits = httpx.Limits(max_connections = 1, max_keepalive_connections = 0),
@@ -6830,6 +6946,159 @@ def _mlx_runtime_settings_match(backend, request) -> bool:
) == (request.chat_template_override or None)
+class _ScopedLoadAttempt(NamedTuple):
+ token: str
+ request_id: Optional[str]
+ model_path: str
+ subject: str
+ cancel_event: threading.Event
+ cancel_complete: threading.Event
+
+
+_scoped_load_attempts_lock = threading.Lock()
+_scoped_load_attempts: dict[tuple[str, str], _ScopedLoadAttempt] = {}
+_scoped_load_cancel_tombstones: dict[tuple[str, str], tuple[str, float]] = {}
+_running_load_attempt: Optional[_ScopedLoadAttempt] = None
+_SCOPED_LOAD_CANCEL_TOMBSTONE_TTL_S = 60.0
+# Bound on waiting for a cancel's teardown to report back. Only the /unload
+# handler sets cancel_complete for a running attempt, so a disconnect or a
+# shutdown between the cancel and its finally leaves nobody to set it. An
+# unbounded wait there parks /load under inference_lifecycle_gate forever, and
+# to_thread's executor threads are non-daemon, so it also blocks process exit.
+_SCOPED_LOAD_CANCEL_HANDSHAKE_TIMEOUT_S = 15.0
+_SCOPED_LOAD_CANCEL_TOMBSTONE_LIMIT_PER_SUBJECT = 256
+
+
+def _prune_scoped_load_cancel_tombstones(now: float) -> None:
+ expired = [
+ key for key, (_, expires_at) in _scoped_load_cancel_tombstones.items() if expires_at <= now
+ ]
+ for key in expired:
+ _scoped_load_cancel_tombstones.pop(key, None)
+
+
+def _begin_load_attempt(request: LoadRequest, current_subject: str) -> _ScopedLoadAttempt:
+ attempt = _ScopedLoadAttempt(
+ token = uuid.uuid4().hex,
+ request_id = request.load_request_id,
+ model_path = request.model_path,
+ subject = current_subject,
+ cancel_event = threading.Event(),
+ cancel_complete = threading.Event(),
+ )
+ if attempt.request_id is None:
+ return attempt
+ key = (current_subject, attempt.request_id)
+ with _scoped_load_attempts_lock:
+ now = time.monotonic()
+ _prune_scoped_load_cancel_tombstones(now)
+ if key in _scoped_load_attempts:
+ raise HTTPException(
+ status_code = 409,
+ detail = "A load with this request ID is already in progress",
+ )
+ tombstone = _scoped_load_cancel_tombstones.pop(key, None)
+ if (
+ tombstone is not None
+ and tombstone[0].strip().casefold() == attempt.model_path.strip().casefold()
+ ):
+ attempt.cancel_event.set()
+ attempt.cancel_complete.set()
+ _scoped_load_attempts[key] = attempt
+ return attempt
+
+
+def _finish_load_attempt(attempt: _ScopedLoadAttempt) -> None:
+ if attempt.request_id is None:
+ return
+ key = (attempt.subject, attempt.request_id)
+ with _scoped_load_attempts_lock:
+ if _scoped_load_attempts.get(key) is attempt:
+ _scoped_load_attempts.pop(key, None)
+
+
+def _cancel_scoped_load_attempt(
+ request: UnloadRequest, current_subject: str
+) -> tuple[Optional[_ScopedLoadAttempt], bool]:
+ request_id = request.cancel_load_request_id
+ if request_id is None:
+ return None, False
+ key = (current_subject, request_id)
+ with _scoped_load_attempts_lock:
+ now = time.monotonic()
+ _prune_scoped_load_cancel_tombstones(now)
+ attempt = _scoped_load_attempts.get(key)
+ if attempt is None:
+ subject_tombstones = [
+ tombstone_key
+ for tombstone_key in _scoped_load_cancel_tombstones
+ if tombstone_key[0] == current_subject
+ ]
+ if len(subject_tombstones) >= _SCOPED_LOAD_CANCEL_TOMBSTONE_LIMIT_PER_SUBJECT:
+ oldest = min(
+ subject_tombstones,
+ key = lambda item: _scoped_load_cancel_tombstones[item][1],
+ )
+ _scoped_load_cancel_tombstones.pop(oldest, None)
+ _scoped_load_cancel_tombstones[key] = (
+ request.model_path,
+ now + _SCOPED_LOAD_CANCEL_TOMBSTONE_TTL_S,
+ )
+ return None, False
+ if attempt.model_path.strip().casefold() != request.model_path.strip().casefold():
+ return None, False
+ attempt.cancel_event.set()
+ is_running = _running_load_attempt is attempt
+ if not is_running:
+ # Queued/completed attempts have no backend teardown handler to signal
+ # completion. Let a queued attempt fail immediately once it gets the gate.
+ attempt.cancel_complete.set()
+ return attempt, is_running
+
+
+async def _run_tracked_load_model_impl(
+ request: LoadRequest,
+ fastapi_request: Request,
+ current_subject: str,
+ *,
+ attempt: Optional[_ScopedLoadAttempt] = None,
+ current_request_counted: bool = False,
+ on_reload_confirmed = None,
+):
+ global _running_load_attempt
+
+ owned_attempt = attempt is None
+ attempt = attempt or _begin_load_attempt(request, current_subject)
+ with _scoped_load_attempts_lock:
+ _running_load_attempt = attempt
+ try:
+ if attempt.cancel_event.is_set():
+ raise HTTPException(status_code = 409, detail = "Model load cancelled")
+ return await _load_model_impl(
+ request,
+ fastapi_request,
+ current_subject,
+ current_request_counted = current_request_counted,
+ on_reload_confirmed = on_reload_confirmed,
+ load_cancel_event = attempt.cancel_event,
+ )
+ finally:
+ if attempt.cancel_event.is_set() and not attempt.cancel_complete.is_set():
+ if not await asyncio.to_thread(
+ attempt.cancel_complete.wait, _SCOPED_LOAD_CANCEL_HANDSHAKE_TIMEOUT_S
+ ):
+ logger.warning(
+ "Scoped load cancel did not report back in %.0fs; releasing the load: %s",
+ _SCOPED_LOAD_CANCEL_HANDSHAKE_TIMEOUT_S,
+ request.model_path,
+ )
+ with _scoped_load_attempts_lock:
+ if _running_load_attempt is attempt:
+ _running_load_attempt = None
+ if owned_attempt:
+ _finish_load_attempt(attempt)
+
+
@router.post("/load", response_model = LoadResponse)
async def load_model(
request: LoadRequest,
@@ -6871,29 +7140,36 @@ async def load_model_gated(
# check alone is only a fast path.
from core.inference.llama_keepwarm import inference_lifecycle_gate
- _raise_if_sidecar_swap_in_progress()
- # Hold the lifecycle gate across the load so idle auto-unload can't unload the
- # model mid-load. Auto-switch calls _load_model_impl directly since it already
- # holds this gate.
- async with inference_lifecycle_gate():
+ attempt = _begin_load_attempt(request, current_subject)
+ try:
_raise_if_sidecar_swap_in_progress()
- # The active-generation gate runs inside _load_model_impl, once it knows this is a real
- # reload, and still under the lifecycle gate so the check stays atomic with the teardown.
- response = await _load_model_impl(
- request,
- fastapi_request,
- current_subject,
- on_reload_confirmed = lambda *, cancel: _raise_or_cancel_active_generations(
- force = request.force_cancel_active,
- action = "Loading a model",
- cancel = cancel,
- ),
- )
+ # Hold the lifecycle gate across the load so idle auto-unload can't unload the
+ # model mid-load. Auto-switch calls the tracked impl directly since it already
+ # holds this gate.
+ async with inference_lifecycle_gate():
+ _raise_if_sidecar_swap_in_progress()
+ # The active-generation gate runs inside _load_model_impl, once it knows this is a real
+ # reload, and still under the lifecycle gate so the check stays atomic with the teardown.
+ response = await _run_tracked_load_model_impl(
+ request,
+ fastapi_request,
+ current_subject,
+ attempt = attempt,
+ on_reload_confirmed = lambda *, cancel: _raise_or_cancel_active_generations(
+ force = request.force_cancel_active,
+ action = "Loading a model",
+ cancel = cancel,
+ ),
+ )
# Record provenance only once the model is resident, and here rather than
# inside the impl so the already-loaded fast paths are covered too. Preview
- # keeps the False default: only an explicit UI load pins.
+ # keeps the False default: only an explicit UI load pins. Outside the gate:
+ # it is a plain attribute write and holding the gate for it would only widen
+ # the window that blocks unload.
get_llama_cpp_backend()._loaded_by_user_action = user_initiated
return response
+ finally:
+ _finish_load_attempt(attempt)
async def _load_model_impl(
@@ -6903,9 +7179,14 @@ async def _load_model_impl(
*,
current_request_counted: bool = False,
on_reload_confirmed = None,
+ load_cancel_event: Optional[threading.Event] = None,
):
from core.inference.llama_cpp import LlamaServerNotFoundError
+ def _raise_if_scoped_load_cancelled() -> None:
+ if load_cancel_event is not None and load_cancel_event.is_set():
+ raise HTTPException(status_code = 409, detail = "Model load cancelled")
+
# A new load starts here; arm the progress throttle so this load's first
# sampled step logs even if it reports 100% immediately (cached/small load).
_reset_load_progress_step()
@@ -7306,6 +7587,7 @@ async def _load_model_impl(
# Point of no return for the GGUF path: nothing left can reject this load, so stop the
# chats the swap interrupts (or refuse, if the caller never opted in).
+ _raise_if_scoped_load_cancelled()
if on_reload_confirmed is not None:
on_reload_confirmed(cancel = True)
@@ -7351,6 +7633,7 @@ async def _load_model_impl(
return await asyncio.to_thread(
llama_backend.load_model,
intent = attempt,
+ load_cancel_event = load_cancel_event,
)
# Tensor parallelism is arch-gated in llama.cpp and crashes some loads
@@ -7363,7 +7646,10 @@ async def _load_model_impl(
requested_tensor = request.tensor_parallel,
extra_args = extra_llama_args,
label = config.identifier,
- cancelled = llama_backend.load_cancelled,
+ cancelled = lambda: (
+ llama_backend.load_cancelled()
+ or bool(load_cancel_event and load_cancel_event.is_set())
+ ),
)
if not success:
@@ -7441,6 +7727,7 @@ async def _load_model_impl(
_raise_if_sidecar_swap_in_progress()
# Point of no return for the Unsloth path: cancel only once nothing can still reject the load.
+ _raise_if_scoped_load_cancelled()
if on_reload_confirmed is not None:
on_reload_confirmed(cancel = True)
@@ -7486,6 +7773,7 @@ async def _load_model_impl(
subject = current_subject,
mlx_kv_bits = request.mlx_kv_bits,
chat_template_override = request.chat_template_override,
+ load_cancel_event = load_cancel_event,
)
if not success:
@@ -8340,6 +8628,47 @@ async def _unload_model_impl(request: UnloadRequest, current_subject: str):
# backend directly (not this route), so clearing here never fights keep-warm.
from core.inference.llama_keepwarm import inference_lifecycle_gate, note_model_unloaded
try:
+ # Hidden Audio cleanup is cancellation, not a manual eject. Bind it to the
+ # exact client load attempt so a delayed request can never stop a newer
+ # same-model load or unload a model that has already become resident.
+ if request.cancel_load_request_id is not None:
+ attempt, is_running = _cancel_scoped_load_attempt(request, current_subject)
+ if attempt is None or not is_running:
+ return UnloadResponse(status = "unloaded", model = request.model_path)
+ try:
+ backend = await asyncio.to_thread(get_inference_backend)
+ loading = getattr(backend, "get_loading_model", lambda: None)()
+ if (
+ loading is not None
+ and hasattr(backend, "cancel_load")
+ and _names_the_loading_model(loading, attempt.model_path)
+ and await asyncio.to_thread(backend.cancel_load, loading)
+ ):
+ note_model_unloaded()
+ logger.info("Cancelled scoped in-flight load: %s", request.model_path)
+ return UnloadResponse(status = "unloaded", model = request.model_path)
+
+ llama_backend = get_llama_cpp_backend()
+ if (
+ llama_backend.is_active
+ and not llama_backend.is_loaded
+ and (
+ llama_backend.model_identifier == attempt.model_path
+ or is_registered_native_path_label(
+ llama_backend.model_identifier, attempt.model_path
+ )
+ or _names_the_resident_model(
+ llama_backend.model_identifier, attempt.model_path
+ )
+ )
+ ):
+ await asyncio.to_thread(llama_backend.unload_model)
+ note_model_unloaded()
+ logger.info("Cancelled scoped in-flight GGUF load: %s", request.model_path)
+ return UnloadResponse(status = "unloaded", model = request.model_path)
+ finally:
+ attempt.cancel_complete.set()
+
# "Stop loading" (frontend cancelLoading -> /unload) must abort a still-loading
# model promptly, and /load holds the lifecycle gate for the whole load. cancel_load only
# tears the loading subprocess down, so it is safe off-gate -- and ahead of the
@@ -8957,29 +9286,16 @@ async def get_load_progress(current_subject: str = Depends(get_current_subject))
# Audio (TTS) Generation (/audio/generate)
# =====================================================================
+_TRANSFORMERS_TTS_AUDIO_TYPES = frozenset(("snac", "csm", "bicodec", "dac"))
+_GGUF_TTS_AUDIO_TYPES = frozenset(("snac", "bicodec", "dac"))
[email protected]("/audio/generate")
-async def generate_audio(
- payload: ChatCompletionRequest,
- request: Request,
- current_subject: str = Depends(get_current_subject),
-):
- """
- Generate audio (TTS) from the latest user message.
- Returns JSON with base64-encoded WAV audio.
- Works with both GGUF (llama-server) and Unsloth/transformers backends.
- """
- import base64
-
- # Extract text from the last user message
- _, chat_messages, _ = _extract_content_parts(payload.messages)
- if not chat_messages:
- raise HTTPException(status_code = 400, detail = "No messages provided.")
- last_user_msg = next((m for m in reversed(chat_messages) if m["role"] == "user"), None)
- if not last_user_msg:
- raise HTTPException(status_code = 400, detail = "No user message found.")
- text = last_user_msg["content"]
+async def _generate_tts_wav(
+ text: str, payload: ChatCompletionRequest, request: Request, current_subject: str
+) -> tuple[bytes, int, str, Optional[str]]:
+ """Shared core of /audio/generate and /audio/speech. Returns
+ (wav_bytes, sample_rate, model_name, audio_type)."""
+ _raise_if_prompt_leaves_no_speech_budget(text)
# Restore an idle-evicted GGUF before selecting a backend: this path is
# keep-warm-tracked but had no reload hook, so a standalone idle TTL could
# unload an audio GGUF the next request then failed to restore. Validation
@@ -8992,6 +9308,11 @@ async def generate_audio(
# and evict the working audio model before the audio backend check fails. Only
# the idle-stash restore runs here; switching TTS models is an explicit /load.
await _maybe_auto_switch_model(_RELOAD_ONLY_MODEL, request, current_subject)
+ # Again, now that a context exists to measure against. The check above runs before the
+ # restore so an invalid request never triggers a reload, but with nothing loaded it has
+ # no context length and passes everything, so the first request after an idle eviction
+ # would reach generation over-context and come back as a one-token clip.
+ _raise_if_prompt_leaves_no_speech_budget(text)
# Created before the backend pick so the GGUF lambda can close over it; the registration
# that arms it is below, once the model name is known.
@@ -9006,6 +9327,8 @@ async def generate_audio(
# Advertised repo id after an auto-switch load, else a clean public id,
# never the absolute .gguf path.
model_name = _llama_public_model_id(llama_backend)
+ audio_type = getattr(llama_backend, "_audio_type", None)
+ supported_audio_types = _GGUF_TTS_AUDIO_TYPES
_audio_model_id = getattr(llama_backend, "model_identifier", None) or model_name
gen = lambda: llama_backend.generate_audio_response(
text = text,
@@ -9014,7 +9337,7 @@ async def generate_audio(
top_p = payload.top_p,
top_k = payload.top_k,
min_p = payload.min_p,
- max_new_tokens = _effective_max_tokens(payload) or 2048,
+ max_new_tokens = _tts_max_new_tokens(payload, text),
repetition_penalty = payload.repetition_penalty,
cancel_event = _audio_cancel,
)
@@ -9026,6 +9349,8 @@ async def generate_audio(
if not model_info.get("is_audio"):
raise HTTPException(status_code = 400, detail = "Active model is not an audio model.")
model_name = public_model_id(backend.active_model_name)
+ audio_type = model_info.get("audio_type")
+ supported_audio_types = _TRANSFORMERS_TTS_AUDIO_TYPES
_audio_model_id = getattr(backend, "active_model_name", None) or model_name
gen = lambda: backend.generate_audio_response(
text = text,
@@ -9033,9 +9358,16 @@ async def generate_audio(
top_p = payload.top_p,
top_k = payload.top_k,
min_p = payload.min_p,
- max_new_tokens = _effective_max_tokens(payload) or 2048,
+ max_new_tokens = _tts_max_new_tokens(payload, text),
repetition_penalty = payload.repetition_penalty,
use_adapter = payload.use_adapter,
+ cancel_event = _audio_cancel,
+ )
+
+ if audio_type not in supported_audio_types:
+ raise HTTPException(
+ status_code = 400,
+ detail = f"Active model does not support text-to-speech (audio_type={audio_type or 'unknown'}).",
)
# Apply per-model recommended sampling + any operator UNSLOTH_SAMPLING_* pin before
@@ -9046,10 +9378,9 @@ async def generate_audio(
_fill_recommended_sampling_openai(payload, _audio_model_id)
# TTS holds the model for the whole request, so unregistered a non-forced swap counted zero
- # generations and tore the model down mid-generation. The GGUF path observes the event; the
- # subprocess backend blocks on its response queue with no cancel plumbing, so there it is
- # only advisory -- which is why the swap drains are bounded. No cancel keys: /cancel
- # addresses streams, and this route has none.
+ # generations and tore the model down mid-generation. Both GGUF and subprocess paths observe
+ # the request event. No cancel keys: /cancel addresses streams, and this route has none; the
+ # disconnect watcher below is the cancellation source.
with _TrackedCancel(
_audio_cancel,
thread_id = getattr(payload, "thread_id", None),
@@ -9064,19 +9395,92 @@ async def generate_audio(
with _direct_llama_request(_direct_llama_tts):
wav_bytes, sample_rate = await asyncio.to_thread(gen)
except Exception as e:
- if _audio_cancel.is_set():
+ # An idle auto-unload cancels through the backend without setting this route's event.
+ if _audio_cancel.is_set() or isinstance(e, AudioGenerationCancelledError):
raise HTTPException(status_code = 499, detail = "Audio generation cancelled")
+ # Missing capability, not a failure: no retry helps, and the message
+ # carries no path or user input, so send it as written.
+ if isinstance(e, AudioBackendUnsupportedError):
+ logger.info("Audio generation unsupported on this backend: %s", e.detail)
+ raise HTTPException(status_code = 501, detail = e.message)
logger.error(f"Audio generation error: {e}", exc_info = True)
raise HTTPException(status_code = 500, detail = safe_error_detail(e))
finally:
await _stop_local_disconnect_cancel_watcher(_audio_watcher)
+ return wav_bytes, sample_rate, model_name, audio_type
+
+
+def _wav_duration_seconds(wav_bytes: bytes, sample_rate: int) -> float:
+ """Duration of an in-memory WAV, from its own header when readable."""
+ import io
+ import wave
+
+ try:
+ with wave.open(io.BytesIO(wav_bytes)) as wav:
+ rate = wav.getframerate() or sample_rate
+ return round(wav.getnframes() / rate, 3) if rate else 0.0
+ except Exception: # noqa: BLE001 - fall back to the 16-bit mono pcm the codecs emit
+ payload_bytes = max(0, len(wav_bytes) - 44)
+ return round(payload_bytes / (2 * sample_rate), 3) if sample_rate else 0.0
+
+
+def _persist_tts_clip(
+ wav_bytes: bytes, sample_rate: int, text: str, model_name: str, audio_type: Optional[str]
+) -> Optional[dict[str, Any]]:
+ """Best-effort gallery save: persistence never fails the request that produced
+ the audio. Blocking, so callers run it off the event loop."""
+ from core.inference import audio_gallery
+ try:
+ return audio_gallery.save(
+ wav_bytes,
+ {
+ "prompt": text,
+ "model": model_name,
+ "audio_type": audio_type or "unknown",
+ "sample_rate": sample_rate,
+ "duration_s": _wav_duration_seconds(wav_bytes, sample_rate),
+ "created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
+ },
+ )
+ except Exception as exc: # noqa: BLE001 - log and serve the audio anyway
+ logger.warning("audio_gallery.persist_failed: %s", exc)
+ return None
+
+
[email protected]("/audio/generate")
+async def generate_audio(
+ payload: ChatCompletionRequest,
+ request: Request,
+ current_subject: str = Depends(get_current_subject),
+):
+ """Generate audio (TTS) from the latest user message, as base64 WAV.
+ Works with both GGUF (llama-server) and Unsloth/transformers backends."""
+ import base64
+
+ # Extract text from the last user message
+ _, chat_messages, _ = _extract_content_parts(payload.messages)
+ if not chat_messages:
+ raise HTTPException(status_code = 400, detail = "No messages provided.")
+ last_user_msg = next((m for m in reversed(chat_messages) if m["role"] == "user"), None)
+ if not last_user_msg:
+ raise HTTPException(status_code = 400, detail = "No user message found.")
+ text = last_user_msg["content"]
+
+ wav_bytes, sample_rate, model_name, audio_type = await _generate_tts_wav(
+ text, payload, request, current_subject
+ )
+ persisted_clip = await asyncio.to_thread(
+ _persist_tts_clip, wav_bytes, sample_rate, text, model_name, audio_type
+ )
+
audio_b64 = base64.b64encode(wav_bytes).decode("ascii")
return JSONResponse(
content = {
"id": f"chatcmpl-{uuid.uuid4().hex[:12]}",
"object": "chat.completion.audio",
"model": model_name,
+ "clip_id": persisted_clip.get("id") if persisted_clip else None,
"audio": {"data": audio_b64, "format": "wav", "sample_rate": sample_rate},
"choices": [
{
@@ -9092,11 +9496,104 @@ async def generate_audio(
)
+# openai-compatible speech api: the router's dual mount also answers /v1/audio/speech
[email protected]("/audio/speech")
+async def openai_audio_speech(
+ body: AudioSpeechRequest,
+ request: Request,
+ current_subject: str = Depends(get_current_subject),
+) -> Response:
+ """OpenAI-compatible text-to-speech (POST /v1/audio/speech).
+
+ ``model`` is informational (the loaded audio model is used); ``voice`` and ``speed``
+ are ignored. Only WAV exists, so another ``response_format`` is a 400 rather than a
+ silent container mismatch."""
+ fmt = (body.response_format or "wav").strip().lower()
+ if fmt != "wav":
+ raise HTTPException(
+ status_code = 400,
+ detail = f"Unsupported response_format '{body.response_format}'. Only 'wav' is supported.",
+ )
+ # The tts core reads its sampling knobs from a chat request shape; defaults apply here.
+ # max_tokens is set explicitly because the OpenAI CreateSpeech shape has no field for it,
+ # so the chat default of 2048 would silently truncate any input past ~30s of speech and
+ # still return HTTP 200 with a short WAV.
+ # Unlike the Audio page, which loads with headroom for both, this route is reachable
+ # after any /api/inference/load, including the default max_seq_length=0 that becomes
+ # 2048. Asking for the full ceiling against that context overflows or truncates, so
+ # cap to what is actually left once the prompt is accounted for.
+ # The over-context check lives in _generate_tts_wav, so both routes share it.
+ payload = ChatCompletionRequest(
+ messages = [{"role": "user", "content": body.input}],
+ max_tokens = AUDIO_GENERATION_MAX_TOKENS,
+ )
+ wav_bytes, sample_rate, model_name, audio_type = await _generate_tts_wav(
+ body.input, payload, request, current_subject
+ )
+ await asyncio.to_thread(
+ _persist_tts_clip, wav_bytes, sample_rate, body.input, model_name, audio_type
+ )
+ return Response(content = wav_bytes, media_type = "audio/wav")
+
+
+# openai-compatible transcription api, dual-mounted like /audio/speech; runs on the stt sidecar, not the main gpu slot
[email protected]("/audio/transcriptions")
+async def openai_audio_transcriptions(
+ request: Request,
+ file: UploadFile = File(...),
+ model: Optional[str] = Form(None),
+ language: Optional[str] = Form(None),
+ response_format: str = Form("json"),
+ current_subject: str = Depends(get_current_subject),
+):
+ """OpenAI-compatible speech-to-text (POST /v1/audio/transcriptions).
+
+ ``model`` maps to a sidecar model id, with ``whisper-1`` or nothing selecting the
+ default. ``response_format`` supports ``json`` and ``text``."""
+ fmt = (response_format or "json").strip().lower()
+ if fmt not in ("json", "text"):
+ raise HTTPException(
+ status_code = 400,
+ detail = f"Unsupported response_format '{response_format}'. Use 'json' or 'text'.",
+ )
+ # UploadFile spools to disk, but an unbounded read materializes the whole upload in
+ # memory before the shared size check. One byte past the limit is enough to reject it.
+ raw = await file.read(_MAX_AUDIO_RAW_BYTES + 1)
+ # openai's whisper-1 placeholder means the default transcription model, not a sidecar id
+ sidecar_model = None if model in (None, "", "whisper-1") else model
+ result = await _transcribe_audio_result(
+ raw,
+ sidecar_model,
+ language,
+ fast = False,
+ engine = _stt_engine_for_model(sidecar_model),
+ request = request,
+ )
+ if fmt == "text":
+ return PlainTextResponse(content = str(result.get("text", "")))
+ return JSONResponse(content = {"text": result.get("text", "")})
+
+
# =====================================================================
# Speech-to-text (STT) sidecar (/audio/transcribe, /audio/stt/*)
# =====================================================================
+def _stt_engine_for_model(model: Optional[str]) -> Optional[str]:
+ """The engine an STT id *requires*, or None to leave the default alone.
+
+ Qwen3-ASR only runs on the mtmd sidecar; without this an explicit id fell through to
+ the Transformers Whisper sidecar, which rejects it.
+ """
+ if not model:
+ return None
+ from core.inference.stt_mtmd_sidecar import is_mtmd_model
+
+ # Only the mtmd ids are forced. Whisper ids are shared with the Transformers
+ # sidecar and work there, so leaving them alone keeps the default behaviour.
+ return "mtmd" if is_mtmd_model(model.strip()) else None
+
+
def _resolve_stt_engine(engine: Optional[str]) -> str:
"""Normalize the requested STT engine name; default is Transformers."""
normalized = (engine or "transformers").strip().lower()
@@ -9130,6 +9627,42 @@ def _resolve_serving_stt_engine(engine: Optional[str]) -> str:
return resolved
+def _prepare_runtime_fallback_checkpoint(
+ requested_engine: Optional[str],
+ serving_engine: str,
+ model: Optional[str],
+ hf_token: Optional[str] = None,
+) -> None:
+ """Fetch the Transformers snapshot a broken whisper.cpp runtime now falls back to.
+
+ A GGUF pick downloads one .bin file, so when the runtime turns out to be broken at
+ inference time the Transformers engine it is redirected to has no snapshot and every
+ retry raises SttModelNotDownloadedError instead of the promised fallback. The two
+ engines share curated ids, so the equivalent snapshot is known and is fetched in the
+ background here; /audio/stt/status reports its progress and the next attempt lands on
+ a usable checkpoint. Only for a runtime that broke: whisper-server simply not being
+ installed already routes the download itself through Transformers.
+ """
+ if serving_engine != "transformers" or _resolve_stt_engine(requested_engine) != "gguf":
+ return
+ from core.inference import stt_ggml_sidecar, stt_sidecar
+
+ if stt_ggml_sidecar.runtime_inference_failure() is None:
+ return
+ if stt_sidecar.is_model_downloaded(model):
+ return
+ try:
+ stt_sidecar.start_model_download(model, hf_token)
+ except Exception as exc: # noqa: BLE001 - preparation is best effort, never fatal
+ # Another dictation model already downloading is the common case, and the caller
+ # is about to report "not downloaded" anyway.
+ logger.info(
+ "Could not start the Transformers fallback download for STT model %r: %s",
+ model,
+ exc,
+ )
+
+
def _stt_download_module(engine: str):
"""Module owning download/status for an engine."""
if engine == "mtmd":
@@ -9314,7 +9847,11 @@ async def stt_download_cancel(
@studio_router.post("/audio/stt/load")
-async def stt_load(payload: SttLoadRequest, current_subject: str = Depends(get_current_subject)):
+async def stt_load(
+ payload: SttLoadRequest,
+ request: Request,
+ current_subject: str = Depends(get_current_subject),
+):
"""Load the selected STT model after the user starts local dictation."""
from core.inference.stt_sidecar import (
SttLoadCancelledError,
@@ -9322,20 +9859,31 @@ async def stt_load(payload: SttLoadRequest, current_subject: str = Depends(get_c
SttModelCompatibilityError,
SttModelIdError,
SttModelNotDownloadedError,
+ SttTranscriptionCancelledError,
SttUnavailableError,
get_stt_sidecar,
)
engine = _resolve_serving_stt_engine(payload.engine)
+ await asyncio.to_thread(
+ _prepare_runtime_fallback_checkpoint,
+ payload.engine,
+ engine,
+ payload.model,
+ )
sidecar = _stt_sidecar_for(engine)
load_stt, _ = _stt_lifecycle()
+ cancel_event = threading.Event()
+ disconnect_watcher = asyncio.create_task(
+ _await_stt_disconnect_then_cancel(request, sidecar, cancel_event)
+ )
try:
- await asyncio.to_thread(load_stt, payload.model, engine)
+ await asyncio.to_thread(load_stt, payload.model, engine, cancel_event)
except SttModelNotDownloadedError as e:
raise HTTPException(status_code = 409, detail = str(e))
except SttUnavailableError as e:
raise HTTPException(status_code = 501, detail = str(e))
- except SttLoadCancelledError as e:
+ except (SttLoadCancelledError, SttTranscriptionCancelledError) as e:
raise HTTPException(status_code = 409, detail = str(e))
except SttModelBusyError as e:
raise HTTPException(status_code = 409, detail = str(e))
@@ -9346,6 +9894,8 @@ async def stt_load(payload: SttLoadRequest, current_subject: str = Depends(get_c
except Exception as e:
logger.error(f"STT load error: {e}", exc_info = True)
raise HTTPException(status_code = 500, detail = safe_error_detail(e))
+ finally:
+ await _stop_local_disconnect_cancel_watcher(disconnect_watcher)
return JSONResponse(content = {"loaded_model": sidecar.loaded_model, "device": sidecar.device})
@@ -9371,12 +9921,18 @@ async def stt_validate(
@studio_router.post("/audio/stt/unload")
async def stt_unload(
- engine: Optional[str] = None, current_subject: str = Depends(get_current_subject)
+ engine: Optional[str] = None,
+ model: Optional[str] = None,
+ current_subject: str = Depends(get_current_subject),
):
"""Release the local STT model when dictation is idle.
Without an engine, both sidecars unload so an engine switch in Voice
- settings always frees whichever backend was resident.
+ settings always frees whichever backend was resident. ``model`` scopes the
+ release to the model the caller claims: a surface owns one model, and another
+ can switch the same engine between that ownership check and this request
+ arriving, so the sidecar re-checks under its own lock rather than releasing
+ whatever happens to be resident by then.
"""
if engine is None:
engines = None
@@ -9388,7 +9944,7 @@ async def stt_unload(
# Every engine is attempted even if one raises, so failing to free one never
# skips the other (both can be resident after a switch).
_, unload_stt = _stt_lifecycle()
- failed: list[str] = await asyncio.to_thread(unload_stt, engines)
+ failed: list[str] = await asyncio.to_thread(unload_stt, engines, model)
if failed:
raise HTTPException(
status_code = 500,
@@ -9403,8 +9959,24 @@ async def _transcribe_audio_bytes(
language: Optional[str],
fast: bool,
engine: Optional[str] = None,
+ request: Optional[Request] = None,
) -> JSONResponse:
"""Run STT for already-decoded request bytes."""
+ return JSONResponse(
+ content = await _transcribe_audio_result(raw, model, language, fast, engine, request)
+ )
+
+
+async def _transcribe_audio_result(
+ raw: bytes,
+ model: Optional[str],
+ language: Optional[str],
+ fast: bool,
+ engine: Optional[str] = None,
+ request: Optional[Request] = None,
+) -> dict:
+ """STT for already-decoded bytes, sidecar errors mapped to HTTP statuses.
+ Returns the sidecar's result dict so callers own the response shape."""
from core.inference.stt_sidecar import (
SttAudioDecodeError,
SttAudioTooLongError,
@@ -9415,6 +9987,7 @@ async def _transcribe_audio_bytes(
SttModelIdError,
SttModelNotDownloadedError,
SttUnavailableError,
+ SttTranscriptionCancelledError,
)
if not raw:
@@ -9422,15 +9995,51 @@ async def _transcribe_audio_bytes(
if len(raw) > _MAX_AUDIO_RAW_BYTES:
raise HTTPException(status_code = 413, detail = "Audio is too large.")
- sidecar = _stt_sidecar_for(_resolve_serving_stt_engine(engine))
+ serving_engine = _resolve_serving_stt_engine(engine)
+ await asyncio.to_thread(
+ _prepare_runtime_fallback_checkpoint,
+ engine,
+ serving_engine,
+ model,
+ )
+ sidecar = _stt_sidecar_for(serving_engine)
+ cancel_event = threading.Event() if request is not None else None
+ disconnect_watcher = (
+ asyncio.create_task(_await_stt_disconnect_then_cancel(request, sidecar, cancel_event))
+ if request is not None and cancel_event is not None
+ else None
+ )
try:
- result = await asyncio.to_thread(
- sidecar.transcribe,
- raw,
- model,
- language,
- fast,
- )
+ # An implicit load has to go through the registry, not the sidecar: each sidecar
+ # loads its own model happily, but only the registry releases the other engines.
+ # An API client alternating between engines (Qwen3-ASR then Whisper through
+ # /v1/audio/transcriptions) therefore held both until their independent idle
+ # timers fired, which is what OOMs a device that fits either alone. A no-op once
+ # the model is resident, so the steady state costs a residency check.
+ load_stt, _ = _stt_lifecycle()
+ await asyncio.to_thread(load_stt, model, serving_engine, cancel_event)
+ if cancel_event is None:
+ result = await asyncio.to_thread(sidecar.transcribe, raw, model, language, fast)
+ else:
+ result = await asyncio.to_thread(
+ sidecar.transcribe,
+ raw,
+ model,
+ language,
+ fast,
+ cancel_event,
+ )
+ except asyncio.CancelledError:
+ if cancel_event is not None:
+ # cancel_transcription takes a lock a load can hold, so inline would stall the loop.
+ threading.Thread(
+ target = sidecar.cancel_transcription,
+ args = (cancel_event,),
+ daemon = True,
+ ).start()
+ raise
+ except SttTranscriptionCancelledError as e:
+ raise HTTPException(status_code = 499, detail = str(e))
except SttUnavailableError as e:
raise HTTPException(status_code = 501, detail = str(e))
except SttLoadCancelledError as e:
@@ -9454,12 +10063,17 @@ async def _transcribe_audio_bytes(
except Exception as e:
logger.error(f"Transcription error: {e}", exc_info = True)
raise HTTPException(status_code = 500, detail = safe_error_detail(e))
- return JSONResponse(content = result)
+ finally:
+ if disconnect_watcher is not None:
+ await _stop_local_disconnect_cancel_watcher(disconnect_watcher)
+ return result
@studio_router.post("/audio/transcribe")
async def transcribe_audio(
- payload: TranscribeRequest, current_subject: str = Depends(get_current_subject)
+ payload: TranscribeRequest,
+ request: Request,
+ current_subject: str = Depends(get_current_subject),
):
"""Transcribe dictation audio to text via the STT sidecar.
@@ -9475,8 +10089,10 @@ async def transcribe_audio(
raw = base64.b64decode(b64, validate = True)
except Exception:
raise HTTPException(status_code = 400, detail = "Audio is not valid base64.")
+ # Same disconnect cancellation as the raw and OpenAI routes: without the request
+ # a client that goes away leaves the sidecar transcribing under its lock.
return await _transcribe_audio_bytes(
- raw, payload.model, payload.language, payload.fast, payload.engine
+ raw, payload.model, payload.language, payload.fast, payload.engine, request
)
@@ -9497,7 +10113,11 @@ async def transcribe_audio_raw(
if size > _MAX_AUDIO_RAW_BYTES:
raise HTTPException(status_code = 413, detail = "Audio is too large.")
chunks.append(chunk)
- return await _transcribe_audio_bytes(b"".join(chunks), model, language, fast, engine)
+ return JSONResponse(
+ content = await _transcribe_audio_result(
+ b"".join(chunks), model, language, fast, engine, request
+ )
+ )
# =====================================================================
@@ -21121,6 +21741,91 @@ async def clear_gallery_images(current_subject: str = Depends(get_current_subjec
return {"removed": removed}
+@studio_router.get("/audio/gallery", response_model = AudioGalleryListResponse)
+async def list_gallery_audio(
+ limit: int = 50,
+ offset: int = 0,
+ before_mtime: Optional[float] = None,
+ before_id: Optional[str] = None,
+ current_subject: str = Depends(get_current_subject),
+):
+ from pydantic import ValidationError
+
+ from core.inference import audio_gallery
+
+ limit = max(1, min(limit, 200))
+ offset = max(0, offset)
+ if (before_mtime is None) != (before_id is None):
+ raise HTTPException(status_code = 400, detail = "Incomplete audio gallery cursor.")
+ before = (
+ (before_mtime, before_id) if before_mtime is not None and before_id is not None else None
+ )
+
+ # validate inside the pager so offset, limit and has_more count over the accepted domain
+ def _valid_gallery_audio(record: dict) -> bool:
+ try:
+ AudioGalleryItem(**record)
+ except ValidationError:
+ return False
+ return True
+
+ # fetch one extra to learn whether more remain, without a second scan
+ entries = await asyncio.to_thread(
+ audio_gallery.list_audio_page,
+ limit + 1,
+ offset,
+ before = before,
+ valid = _valid_gallery_audio,
+ )
+ has_more = len(entries) > limit
+ visible = entries[:limit]
+ audio = [AudioGalleryItem(**record) for record, _ in visible]
+ next_cursor = visible[-1][1] if has_more and visible else None
+ return AudioGalleryListResponse(
+ audio = audio,
+ has_more = has_more,
+ next_before_mtime = next_cursor[0] if next_cursor else None,
+ next_before_id = next_cursor[1] if next_cursor else None,
+ )
+
+
+@studio_router.get("/audio/gallery/{audio_id}/file")
+async def get_gallery_audio_file(
+ audio_id: str, current_subject: str = Depends(get_current_subject)
+):
+ from core.inference import audio_gallery
+
+ # ownership-gate the serve like delete/clear, so a guessed stem cannot stream out a foreign file
+ path = await asyncio.to_thread(audio_gallery.owned_audio_path, audio_id)
+ if path is None:
+ raise HTTPException(status_code = 404, detail = "Audio not found.")
+ from fastapi.responses import FileResponse
+
+ # immutable content (id is unique per clip), so let the browser cache it
+ return FileResponse(
+ path,
+ media_type = "audio/wav",
+ headers = {"Cache-Control": "private, max-age=31536000, immutable"},
+ )
+
+
+@studio_router.delete("/audio/gallery/{audio_id}")
+async def delete_gallery_audio(audio_id: str, current_subject: str = Depends(get_current_subject)):
+ from core.inference import audio_gallery
+
+ deleted = await asyncio.to_thread(audio_gallery.delete, audio_id)
+ if not deleted:
+ raise HTTPException(status_code = 404, detail = "Audio not found.")
+ return {"deleted": True}
+
+
+@studio_router.delete("/audio/gallery")
+async def clear_gallery_audio(current_subject: str = Depends(get_current_subject)):
+ from core.inference import audio_gallery
+ removed = await asyncio.to_thread(audio_gallery.clear)
+ return {"removed": removed}
+
+
@studio_router.post("/images/unload", response_model = DiffusionStatusResponse)
async def unload_diffusion_model(current_subject: str = Depends(get_current_subject)):
from core.inference.diffusion_engine_router import annotate_status, get_active_diffusion_engine
diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.py
index 0a71029ccc2..2b2e124b4d1 100644
--- a/studio/backend/routes/models.py
+++ b/studio/backend/routes/models.py
@@ -2163,7 +2163,7 @@ async def get_model_config(
model_name = resolved
logger.info(f"Getting model config for: {model_name}")
- from utils.models.model_config import detect_audio_type
+ from utils.models.model_config import detect_audio_type_checked
inspection_target = _model_config_inspection_target(
model_name,
@@ -2178,8 +2178,8 @@ async def get_model_config(
local_files_only = prefer_local_cache,
)
is_embedding = is_embedding_model(inspection_target, hf_token = hf_token)
- audio_type = detect_audio_type(
- inspection_target,
+ audio_type, audio_type_definitive = detect_audio_type_checked(
+ _audio_probe_target(inspection_target),
hf_token = hf_token,
local_files_only = prefer_local_cache,
)
@@ -2217,7 +2217,7 @@ async def get_model_config(
pass
logger.info(
- f"Model config result for {model_name}: is_vision={is_vision}, is_embedding={is_embedding}, audio_type={audio_type}, is_lora={is_lora}, max_position_embeddings={max_position_embeddings}"
+ f"Model config result for {model_name}: is_vision={is_vision}, is_embedding={is_embedding}, audio_type={audio_type}, audio_type_known={audio_type_definitive}, is_lora={is_lora}, max_position_embeddings={max_position_embeddings}"
)
return ModelDetails(
id = model_name,
@@ -2228,6 +2228,7 @@ async def get_model_config(
is_lora = is_lora,
is_audio = audio_type is not None,
audio_type = audio_type,
+ audio_type_known = audio_type_definitive,
has_audio_input = is_audio_input_type(audio_type),
model_type = derive_model_type(is_vision, audio_type, is_embedding),
base_model = base_model,
@@ -2548,6 +2549,59 @@ async def discard_remote_code_download(
return {"deleted": False, "reason": "error"}
+def _audio_probe_target(inspection_target: str) -> str:
+ """Repo to ask about audio capability, resolving a registry alias first.
+
+ A curated entry like "Spark-TTS-0.5B/LLM" names a load subdirectory, not a repo, so
+ the probe fetched a repo that does not exist, got a 404 on every path, and read that
+ as "definitely not an audio model" rather than "not a repo id". Spark-TTS then looked
+ like a text model, and picking it with an audio dataset hit the modality gate. Same
+ resolution routes/training.py already uses for the trainer's own preflight.
+ """
+ if is_local_path(inspection_target):
+ return inspection_target
+ try:
+ from utils.security import load_scan_target
+ repo_id, _load_subdirs = load_scan_target(canonical_model_repo_id(inspection_target), ())
+ return repo_id or inspection_target
+ except Exception: # noqa: BLE001 - a probe target must never fail the handler
+ return inspection_target
+
+
+def _audio_type_of_checkpoint(
+ model_path: str,
+ base_model: Optional[str],
+ hf_token: Optional[str] = None,
+) -> Optional[str]:
+ """Codec a trained checkpoint speaks, or None for a text one.
+
+ A scan row carries no modality, so without this every trained audio model reads
+ as text: the Audio page filters it out and chat routes it to the GGUF auto-switch,
+ which cannot resolve a local adapter directory. Detection reads the checkpoint
+ itself first (a merged export has its own tokenizer) and falls back to the base
+ repo an adapter names. Cached per model, so the scan stays one pass.
+ """
+ from utils.models.model_config import detect_audio_type
+
+ for candidate in (model_path, base_model):
+ if not candidate:
+ continue
+ try:
+ # local_files_only: this route was a filesystem scan. A trained checkpoint's
+ # base is already cached, and a non-definitive miss is deliberately not cached,
+ # so a gated or offline base would re-fetch on every poll.
+ # hf_token even under local_files_only: a gated base resolves through the same
+ # hub helpers, and the capability caches are keyed by token fingerprint, so a
+ # token-less probe would both misclassify and poison the cache for the rest.
+ audio_type = detect_audio_type(candidate, hf_token = hf_token, local_files_only = True)
+ except Exception as exc: # never let a scan row fail the whole listing
+ logger.debug("audio detection failed for %r: %s", candidate, exc)
+ continue
+ if audio_type:
+ return audio_type
+ return None
+
+
@router.get("/loras")
async def scan_loras(
outputs_dir: str = Query(
@@ -2556,6 +2610,7 @@ async def scan_loras(
exports_dir: str = Query(
default = str(exports_root()), description = "Directory to scan for exported models"
),
+ hf_token: Optional[str] = Depends(get_hf_token),
current_subject: str = Depends(get_current_subject),
):
"""Scan for trained LoRA adapters and exported models.
@@ -2566,33 +2621,12 @@ async def scan_loras(
try:
resolved_outputs_dir = str(resolve_output_dir(outputs_dir))
resolved_exports_dir = str(resolve_export_dir(exports_dir))
- lora_list = []
-
- trained_models = scan_trained_models(outputs_dir = resolved_outputs_dir)
- for display_name, model_path, model_type in trained_models:
- base_model = get_base_model_from_checkpoint(model_path)
- lora_list.append(
- LoRAInfo(
- display_name = display_name,
- adapter_path = model_path,
- base_model = base_model,
- source = "training",
- export_type = model_type,
- )
- )
-
- # Scan exported models (merged, LoRA, base — skips GGUF)
- exported = scan_exported_models(exports_dir = resolved_exports_dir)
- for display_name, model_path, export_type, base_model in exported:
- lora_list.append(
- LoRAInfo(
- display_name = display_name,
- adapter_path = model_path,
- base_model = base_model,
- source = "exported",
- export_type = export_type,
- )
- )
+ # Off the event loop: this is a directory walk plus, per checkpoint, a tokenizer
+ # read. It was already blocking before the audio probe was added; the probe made
+ # the block long enough to delay unrelated requests, streamed tokens included.
+ lora_list = await asyncio.to_thread(
+ _scan_loras_sync, resolved_outputs_dir, resolved_exports_dir, hf_token
+ )
return LoRAScanResponse(loras = lora_list, outputs_dir = resolved_outputs_dir)
@@ -2606,6 +2640,43 @@ async def scan_loras(
)
+def _scan_loras_sync(
+ resolved_outputs_dir: str, resolved_exports_dir: str, hf_token: Optional[str]
+) -> List[LoRAInfo]:
+ """The filesystem half of scan_loras, so it can run in a worker thread."""
+ lora_list: List[LoRAInfo] = []
+
+ trained_models = scan_trained_models(outputs_dir = resolved_outputs_dir)
+ for display_name, model_path, model_type in trained_models:
+ base_model = get_base_model_from_checkpoint(model_path)
+ lora_list.append(
+ LoRAInfo(
+ display_name = display_name,
+ adapter_path = model_path,
+ base_model = base_model,
+ source = "training",
+ export_type = model_type,
+ audio_type = _audio_type_of_checkpoint(model_path, base_model, hf_token),
+ )
+ )
+
+ # Scan exported models (merged, LoRA, base — skips GGUF)
+ exported = scan_exported_models(exports_dir = resolved_exports_dir)
+ for display_name, model_path, export_type, base_model in exported:
+ lora_list.append(
+ LoRAInfo(
+ display_name = display_name,
+ adapter_path = model_path,
+ base_model = base_model,
+ source = "exported",
+ export_type = export_type,
+ audio_type = _audio_type_of_checkpoint(model_path, base_model, hf_token),
+ )
+ )
+
+ return lora_list
+
+
@router.get("/diffusion-loras")
async def scan_diffusion_loras(
family: Optional[str] = Query(
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index e1f3aeb24b2..046387195ec 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -1401,6 +1401,7 @@ SIDEBAR_NAV_ITEM_DEFAULTS = {
"projects": True,
"images": True,
"video": False,
+ "audio": False,
"train": True,
"recipes": False,
"export": False,
@@ -1449,6 +1450,7 @@ class PersonalizationSidebarNavItem(BaseModel):
"projects",
"images",
"video",
+ "audio",
"train",
"recipes",
"export",
diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.py
index 70d9f628835..ff7e637ed6f 100644
--- a/studio/backend/tests/conftest.py
+++ b/studio/backend/tests/conftest.py
@@ -157,6 +157,20 @@ def _isolate_xet_health_state():
hf_xet_health.clear_xet_health()
[email protected](autouse = True)
+def _isolate_audio_gallery(monkeypatch, tmp_path):
+ """Keep generated-clip persistence out of the developer's real gallery.
+
+ /audio/generate persists every clip, so a route test with a fake TTS core left silent
+ wavs in ``studio_root()/audio`` for the Audio page to list. Here, not per-suite, so
+ no test can leak.
+ """
+ from core.inference import audio_gallery
+
+ monkeypatch.setattr(audio_gallery, "studio_root", lambda: tmp_path)
+ yield
+
+
@pytest.fixture(autouse = True)
def _no_background_model_scan(monkeypatch):
"""Keep the /v1 admission hook from scanning the real HF cache during tests.
diff --git a/studio/backend/tests/test_active_generations.py b/studio/backend/tests/test_active_generations.py
index 3b74a0a8799..d089e9ccf7e 100644
--- a/studio/backend/tests/test_active_generations.py
+++ b/studio/backend/tests/test_active_generations.py
@@ -1815,7 +1815,7 @@ def test_audio_generation_is_visible_to_the_swap_gate(monkeypatch):
class _TtsBackend:
active_model_name = "org/TTS"
- models = {"org/TTS": {"is_audio": True}}
+ models = {"org/TTS": {"is_audio": True, "audio_type": "snac"}}
def generate_audio_response(self, **kwargs):
# Sampled mid-generation: the window a concurrent swap would tear down in.
@@ -2235,7 +2235,7 @@ def test_audio_generation_unregisters_when_it_fails(monkeypatch):
class _BrokenTtsBackend:
active_model_name = "org/TTS"
- models = {"org/TTS": {"is_audio": True}}
+ models = {"org/TTS": {"is_audio": True, "audio_type": "snac"}}
def generate_audio_response(self, **kwargs):
raise RuntimeError("codec exploded")
diff --git a/studio/backend/tests/test_api_monitor.py b/studio/backend/tests/test_api_monitor.py
index b761e892400..f7089cb420b 100644
--- a/studio/backend/tests/test_api_monitor.py
+++ b/studio/backend/tests/test_api_monitor.py
@@ -1055,7 +1055,8 @@ def _llama_slot_readout(
context_length = 4096,
model_identifier = "some/tts-GGUF",
_is_audio = is_audio,
- _audio_type = "codec",
+ # A real GGUF TTS codec: /audio/generate rejects anything llama.cpp cannot decode.
+ _audio_type = "snac",
_auth_headers = None,
)
monkeypatch.setattr(inf, "get_llama_cpp_backend", lambda: backend)
diff --git a/studio/backend/tests/test_audio_dataset_decode.py b/studio/backend/tests/test_audio_dataset_decode.py
new file mode 100644
index 00000000000..d4306a05e70
--- /dev/null
+++ b/studio/backend/tests/test_audio_dataset_decode.py
@@ -0,0 +1,248 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Audio datasets stay readable when torchcodec cannot load its FFmpeg libraries."""
+
+from __future__ import annotations
+
+import io
+
+import pytest
+
+from utils.datasets import audio_decode
+
+np = pytest.importorskip("numpy")
+sf = pytest.importorskip("soundfile")
+# The shim needs both: it resamples through librosa, so without it every
+# ensure_audio_decoding() below correctly returns False and the tests fail.
+pytest.importorskip("librosa")
+datasets = pytest.importorskip("datasets")
+
+
+def _wav_bytes(samples = 1600, sampling_rate = 16000):
+ buf = io.BytesIO()
+ sf.write(
+ buf,
+ np.linspace(-0.5, 0.5, samples, dtype = "float32"),
+ sampling_rate,
+ format = "WAV",
+ )
+ return buf.getvalue()
+
+
+def broken_torchcodec(monkeypatch):
+ """What disable_torchcodec_if_broken leaves behind on a host with no FFmpeg."""
+ from datasets import config
+ from datasets.features.audio import Audio
+
+ monkeypatch.setattr(config, "TORCHCODEC_AVAILABLE", False)
+ monkeypatch.setattr(Audio, "decode_example", Audio.decode_example)
+ # encode_example is patched too, so it needs restoring as well: leaving the
+ # shim installed made the next test capture it as _ORIGINAL_ENCODE.
+ monkeypatch.setattr(Audio, "encode_example", Audio.encode_example)
+ monkeypatch.setattr(audio_decode, "_installed", False)
+ monkeypatch.setattr(audio_decode, "_ORIGINAL_ENCODE", None)
+
+
+def test_a_broken_torchcodec_makes_datasets_refuse_the_column(broken_torchcodec):
+ from datasets import Audio, Dataset
+
+ ds = Dataset.from_dict({"audio": [{"path": "a.wav", "bytes": _wav_bytes()}]})
+ ds = ds.cast_column("audio", Audio(sampling_rate = 24000))
+ with pytest.raises(ImportError, match = "torchcodec"):
+ ds[0]["audio"]
+
+
+def test_the_soundfile_decoder_resamples_to_the_cast_rate(broken_torchcodec):
+ from datasets import Audio, Dataset
+
+ assert audio_decode.ensure_audio_decoding() is True
+ ds = Dataset.from_dict({"audio": [{"path": "a.wav", "bytes": _wav_bytes()}]})
+ ds = ds.cast_column("audio", Audio(sampling_rate = 24000))
+ decoded = ds[0]["audio"]
+
+ assert decoded["sampling_rate"] == 24000
+ # 1600 samples at 16 kHz is 0.1 s, so 24 kHz gives 2400 back.
+ assert len(decoded["array"]) == pytest.approx(2400, abs = 4)
+ assert decoded["path"] == "a.wav"
+
+
+def test_a_stereo_source_is_averaged_to_mono(broken_torchcodec):
+ from datasets import Audio, Dataset
+
+ buf = io.BytesIO()
+ sf.write(buf, np.zeros((800, 2), dtype = "float32"), 16000, format = "WAV")
+ audio_decode.ensure_audio_decoding()
+ ds = Dataset.from_dict({"audio": [{"path": "s.wav", "bytes": buf.getvalue()}]})
+ ds = ds.cast_column("audio", Audio())
+
+ assert np.asarray(ds[0]["audio"]["array"]).ndim == 1
+
+
+def test_ensure_audio_decoding_reports_failure_without_soundfile(monkeypatch, broken_torchcodec):
+ import builtins
+
+ real_import = builtins.__import__
+
+ def no_soundfile(name, *args, **kwargs):
+ if name == "soundfile":
+ raise OSError("libsndfile not found")
+ return real_import(name, *args, **kwargs)
+
+ monkeypatch.setattr(builtins, "__import__", no_soundfile)
+ assert audio_decode.ensure_audio_decoding() is False
+
+
+def test_a_working_torchcodec_is_left_alone(monkeypatch):
+ import sys
+ import types
+
+ from datasets import config
+ from datasets.features.audio import Audio
+
+ # Stub the decoder the guard probes for, so the assertion holds on hosts
+ # that have no torchcodec installed at all rather than a broken one.
+ module = sys.modules.get("datasets.features._torchcodec")
+ if module is None:
+ module = types.ModuleType("datasets.features._torchcodec")
+ module.AudioDecoder = object
+ monkeypatch.setitem(sys.modules, "datasets.features._torchcodec", module)
+ monkeypatch.setattr(config, "TORCHCODEC_AVAILABLE", True)
+ monkeypatch.setattr(audio_decode, "_installed", False)
+ before = Audio.decode_example
+ assert audio_decode.ensure_audio_decoding() is True
+ assert Audio.decode_example is before
+
+
+def test_a_stereo_source_keeps_its_frames(broken_torchcodec):
+ """soundfile returns (frames, channels), torchcodec (channels, frames): the wrong
+ axis collapsed a clip to one sample per channel and trained on near-silence."""
+ from datasets import Audio, Dataset
+
+ buf = io.BytesIO()
+ sf.write(buf, np.zeros((800, 2), dtype = "float32"), 16000, format = "WAV")
+ audio_decode.ensure_audio_decoding()
+ ds = Dataset.from_dict({"audio": [{"path": "s.wav", "bytes": buf.getvalue()}]})
+ ds = ds.cast_column("audio", Audio())
+
+ assert len(ds[0]["audio"]["array"]) == 800
+
+
+def test_a_decoder_that_cannot_resample_reports_unusable(monkeypatch, broken_torchcodec):
+ """Every trainer cast names a target rate, so soundfile alone is not enough."""
+ import builtins
+
+ real_import = builtins.__import__
+
+ def no_librosa(name, *args, **kwargs):
+ if name == "librosa":
+ raise ImportError("no librosa in no-torch mode")
+ return real_import(name, *args, **kwargs)
+
+ monkeypatch.setattr(builtins, "__import__", no_librosa)
+ assert audio_decode.ensure_audio_decoding() is False
+
+
+def test_the_dataset_format_check_installs_the_decoder():
+ """The preview reads audio rows, so the wiring is the fix, not the module."""
+ import inspect
+
+ from hub.services.datasets import formatting
+
+ source = inspect.getsource(formatting.check_format_response)
+ assert "ensure_audio_decoding()" in source
+
+
+def test_the_audio_trainer_paths_install_the_decoder():
+ # Read the source rather than import it: this asserts a wiring contract, and
+ # importing the trainer drags in the whole torch/unsloth stack for it.
+ from pathlib import Path
+
+ source = (Path(__file__).resolve().parents[1] / "core" / "training" / "trainer.py").read_text(
+ encoding = "utf-8"
+ )
+ assert "ensure_audio_decoding()" in source
+ # Guarded so a text-only run never pays for the probe.
+ assert "if self._audio_type or self.is_audio_vlm:" in source
+
+
+def test_a_concurrent_first_install_captures_the_original_encode_once(
+ monkeypatch, broken_torchcodec
+):
+ """Two first-time callers must not both capture Audio.encode_example.
+
+ The loser captured the already-installed shim as _ORIGINAL_ENCODE, so its fallback
+ branch recursed into itself until RecursionError.
+ """
+ import threading
+
+ from datasets.features.audio import Audio
+
+ from utils.datasets import audio_decode
+
+ original = Audio.encode_example
+ monkeypatch.setattr(audio_decode, "_installed", False, raising = False)
+ monkeypatch.setattr(audio_decode, "_ORIGINAL_ENCODE", None, raising = False)
+
+ start = threading.Barrier(4)
+ errors: list[BaseException] = []
+
+ def install():
+ try:
+ start.wait(timeout = 10)
+ audio_decode.ensure_audio_decoding()
+ except BaseException as exc: # noqa: BLE001
+ errors.append(exc)
+
+ threads = [threading.Thread(target = install) for _ in range(4)]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join(timeout = 30)
+
+ assert not errors, errors[:2]
+ assert audio_decode._ORIGINAL_ENCODE is original
+ assert audio_decode._ORIGINAL_ENCODE is not audio_decode._encode_with_soundfile
+
+
+def test_a_multi_repo_mapping_picks_the_token_of_the_source_repo():
+ """Interleaved or concatenated streaming splits carry one token per source repo.
+
+ Handing an arbitrary one to xopen sends a private repo's credential to a different
+ repo's host, so the repo id has to come from the URL being opened.
+ """
+ from datasets import config
+
+ tokens = {"org/first": "token-first", "org/second": "token-second"}
+ url = "hf://datasets/org/second@main/data/train-00000.wav"
+ assert audio_decode._token_for_url(url, tokens) == "token-second"
+
+ resolve = f"{config.HF_ENDPOINT}/datasets/org/first/resolve/main/data/train-00000.wav"
+ assert audio_decode._token_for_url(resolve, tokens) == "token-first"
+
+
+def test_a_chained_url_is_keyed_on_the_repo_it_actually_fetches():
+ """Compressed streaming shards arrive as "zip://inner::https://outer" chains."""
+ from datasets import config
+
+ tokens = {"org/first": "token-first", "org/second": "token-second"}
+ outer = f"{config.HF_ENDPOINT}/datasets/org/second/resolve/main/audio.zip"
+ assert audio_decode._token_for_url(f"zip://clip.wav::{outer}", tokens) == "token-second"
+
+
+def test_an_unknown_host_gets_no_token_when_the_mapping_is_ambiguous():
+ tokens = {"org/first": "token-first", "org/second": "token-second"}
+ assert audio_decode._token_for_url("https://example.com/clip.wav", tokens) is None
+ # The single-repo mapping every caller in this codebase passes still works, which is
+ # what the previous next(iter(...)) did for all of them.
+ assert audio_decode._token_for_url("https://example.com/clip.wav", {"org/x": "t"}) == "t"
+ assert audio_decode._token_for_url("https://example.com/clip.wav", {}) is None
+ assert audio_decode._token_for_url("https://example.com/clip.wav", None) is None
+
+
+def test_a_repo_absent_from_the_mapping_sends_no_credential():
+ """A public repo mixed in with private ones must not borrow their token."""
+ tokens = {"org/private": "token-private"}
+ url = "hf://datasets/org/public@main/data/clip.wav"
+ assert audio_decode._token_for_url(url, tokens) is None
diff --git a/studio/backend/tests/test_audio_gallery.py b/studio/backend/tests/test_audio_gallery.py
new file mode 100644
index 00000000000..eff48fedb34
--- /dev/null
+++ b/studio/backend/tests/test_audio_gallery.py
@@ -0,0 +1,321 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Unit tests for the disk-backed audio gallery: WAV + JSON-sidecar round-trips,
+listing order, safe id handling, orphan-pair skipping, and delete/clear."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+from pathlib import Path
+
+import core.inference.audio_gallery as gallery
+
+import pytest
+
+
[email protected](autouse = True)
+def _tmp_gallery(monkeypatch, tmp_path):
+ # Point the gallery at a throwaway root instead of ~/.unsloth/studio.
+ monkeypatch.setattr(gallery, "studio_root", lambda: tmp_path)
+
+
+def _wav(tag = b"RIFF\x24\x00\x00\x00WAVEfmt "):
+ # Not a real container; the gallery treats the bytes as opaque payload.
+ return tag
+
+
+def _meta(**over):
+ base = {
+ "prompt": "hello from a sloth",
+ "model": "unsloth/orpheus-3b-0.1-ft",
+ "audio_type": "snac",
+ "sample_rate": 24000,
+ "duration_s": 1.5,
+ "created_at": "2026-08-06T00:00:00Z",
+ }
+ base.update(over)
+ return base
+
+
+def test_save_writes_pair_and_round_trips():
+ record = gallery.save(_wav(), _meta())
+ assert record["id"] and record["url"].endswith(f"{record['id']}/file")
+
+ # Both files of the pair exist: the wav payload and the json recipe sidecar.
+ directory = gallery.gallery_dir()
+ assert (directory / f"{record['id']}.wav").is_file()
+ sidecar = directory / f"{record['id']}.json"
+ assert json.loads(sidecar.read_text(encoding = "utf-8"))["prompt"] == "hello from a sloth"
+
+ listed = gallery.list_audio()
+ assert len(listed) == 1
+ assert listed[0]["prompt"] == "hello from a sloth"
+ # Meta fields survive the sidecar round-trip untouched.
+ assert listed[0]["sample_rate"] == 24000 and listed[0]["audio_type"] == "snac"
+
+
+def test_url_shape():
+ record = gallery.save(_wav(), _meta())
+ assert record["url"] == f"/api/inference/audio/gallery/{record['id']}/file"
+
+
+def _save_with_mtime(prompt: str, t: float) -> dict:
+ record = gallery.save(_wav(), _meta(prompt = prompt))
+ # Listing orders by wav mtime; set it explicitly so a tight test loop can't tie it.
+ os.utime(gallery.gallery_dir() / f"{record['id']}.wav", (t, t))
+ return record
+
+
+def test_list_is_newest_first():
+ old = _save_with_mtime("old", 100.0)
+ new = _save_with_mtime("new", 200.0)
+ assert [r["id"] for r in gallery.list_audio()] == [new["id"], old["id"]]
+
+
+def test_list_paginates_with_limit_offset():
+ for i in range(5):
+ _save_with_mtime(f"p{i}", float(i))
+ page1 = gallery.list_audio(limit = 2, offset = 0)
+ page2 = gallery.list_audio(limit = 2, offset = 2)
+ assert [r["prompt"] for r in page1] == ["p4", "p3"]
+ assert [r["prompt"] for r in page2] == ["p2", "p1"]
+ # limit=None still returns everything from the offset.
+ assert len(gallery.list_audio()) == 5
+ assert len(gallery.list_audio(offset = 4)) == 1
+
+
+def test_cursor_pagination_does_not_skip_after_earlier_clip_is_deleted():
+ records = [_save_with_mtime(prompt, float(i)) for i, prompt in enumerate("DCBA", 1)]
+ page1 = gallery.list_audio_page(limit = 3)
+ visible1 = page1[:2]
+ assert [record["prompt"] for record, _ in visible1] == ["A", "B"]
+
+ # Removing A shifts every offset, but the exclusive B cursor still starts at C.
+ assert gallery.delete(records[-1]["id"]) is True
+ page2 = gallery.list_audio(limit = 2, before = visible1[-1][1])
+ assert [record["prompt"] for record in page2] == ["C", "D"]
+
+
+def test_audio_path_rejects_unsafe_ids():
+ # Traversal / bad chars / absolute paths never resolve to a path.
+ assert gallery.audio_path("../../etc/passwd") is None
+ assert gallery.audio_path("/etc/passwd") is None
+ assert gallery.audio_path("a/b") is None
+ assert gallery.audio_path("missing") is None
+
+
+def test_audio_path_returns_wav_for_saved_id():
+ record = gallery.save(_wav(), _meta())
+ path = gallery.audio_path(record["id"])
+ assert path is not None and path.name == f"{record['id']}.wav"
+
+
+def test_owned_audio_path_serves_only_owned_clips():
+ # A hand-dropped orphan WAV resolves via audio_path (safe stem, on disk) but must NOT be
+ # served: owned_audio_path applies the same sidecar check as delete/clear.
+ orphan = gallery.gallery_dir() / "recording.wav"
+ orphan.write_bytes(_wav())
+ assert gallery.audio_path("recording") is not None # resolvable...
+ assert gallery.owned_audio_path("recording") is None # ...but not ours to serve
+
+ ours = gallery.save(_wav(), _meta(prompt = "ours"))
+ assert gallery.owned_audio_path(ours["id"]) is not None
+ assert gallery.owned_audio_path("../../etc/passwd") is None
+ assert gallery.owned_audio_path("missing") is None
+
+
+def test_gallery_file_route_streams_the_owned_wav(monkeypatch):
+ from fastapi.responses import FileResponse
+ from routes.inference import get_gallery_audio_file
+
+ record = gallery.save(_wav(), _meta())
+ monkeypatch.setattr(
+ Path,
+ "read_bytes",
+ lambda self: pytest.fail("the route must not buffer the WAV before responding"),
+ )
+ response = asyncio.run(get_gallery_audio_file(record["id"], current_subject = "tester"))
+
+ assert isinstance(response, FileResponse)
+ assert Path(response.path) == gallery.gallery_dir() / f"{record['id']}.wav"
+ assert response.media_type == "audio/wav"
+ assert response.headers["cache-control"] == "private, max-age=31536000, immutable"
+
+
+def test_delete_removes_both_files():
+ record = gallery.save(_wav(), _meta(prompt = "a"))
+ gallery.save(_wav(), _meta(prompt = "b"))
+ directory = gallery.gallery_dir()
+ assert gallery.delete(record["id"]) is True
+ # Both halves of the pair are gone.
+ assert not (directory / f"{record['id']}.wav").exists()
+ assert not (directory / f"{record['id']}.json").exists()
+ assert gallery.delete(record["id"]) is False # already gone
+ assert len(gallery.list_audio()) == 1
+
+
+def test_delete_keeps_sidecar_listable_when_wav_unlink_fails(monkeypatch):
+ # delete() must remove the WAV FIRST: list_audio globs *.wav but needs a readable sidecar,
+ # so dropping the sidecar first and then failing the wav unlink would hide a still-present
+ # wav with no way to retry.
+ record = gallery.save(_wav(), _meta(prompt = "keep"))
+ directory = gallery.gallery_dir()
+ wav = directory / f"{record['id']}.wav"
+ sidecar = directory / f"{record['id']}.json"
+
+ real_unlink = Path.unlink
+
+ def _fail_on_wav(self, *a, **k):
+ if self.suffix == ".wav":
+ raise PermissionError("wav locked")
+ return real_unlink(self, *a, **k)
+
+ # Scoped so undoing it does not revert the autouse fixture's studio_root redirect.
+ with pytest.MonkeyPatch.context() as m:
+ m.setattr(Path, "unlink", _fail_on_wav)
+ assert gallery.delete(record["id"]) is False # wav unlink failed
+ # The sidecar was NOT dropped, so the record is still listable and the user can retry.
+ assert sidecar.exists() and wav.exists()
+ assert [r["prompt"] for r in gallery.list_audio()] == ["keep"]
+ assert gallery.delete(record["id"]) is True # retry now succeeds
+
+
+def test_clear_returns_count():
+ gallery.save(_wav(), _meta(prompt = "a"))
+ gallery.save(_wav(), _meta(prompt = "b"))
+ assert gallery.clear() == 2
+ assert gallery.list_audio() == []
+ # No stray sidecars left behind after a clear.
+ assert list(gallery.gallery_dir().glob("*.json")) == []
+
+
+def test_clear_preserves_orphan_wav():
+ # An orphan / foreign WAV is invisible to list_audio; clear must remove the owned pair without destroying it.
+ foreign = gallery.gallery_dir() / "recording.wav"
+ foreign.write_bytes(_wav())
+ gallery.save(_wav(), _meta(prompt = "ours"))
+ assert gallery.clear() == 1
+ assert foreign.exists()
+ assert gallery.list_audio() == []
+
+
+def test_delete_ignores_orphan_wav():
+ # A per-id delete must refuse a WAV we do not own (no readable sidecar).
+ foreign = gallery.gallery_dir() / "recording.wav"
+ foreign.write_bytes(_wav())
+ assert gallery.delete("recording") is False
+ assert foreign.exists()
+
+
+def test_list_skips_orphan_wav_without_sidecar():
+ orphan = gallery.gallery_dir() / "orphan.wav"
+ orphan.write_bytes(_wav())
+ gallery.save(_wav(), _meta(prompt = "ours"))
+ assert [r["prompt"] for r in gallery.list_audio()] == ["ours"]
+
+
+def test_list_skips_orphan_sidecar_without_wav():
+ orphan = gallery.gallery_dir() / "lonely.json"
+ orphan.write_text(json.dumps(_meta(prompt = "no audio")), encoding = "utf-8")
+ gallery.save(_wav(), _meta(prompt = "ours"))
+ assert [r["prompt"] for r in gallery.list_audio()] == ["ours"]
+
+
+def test_orphan_wav_in_window_does_not_drop_valid_clips():
+ # An orphan WAV sorting INTO the requested page must not consume a window slot: paging is over readable records.
+ _save_with_mtime("p2", 100.0)
+ orphan = gallery.gallery_dir() / "zzz_orphan.wav"
+ orphan.write_bytes(_wav())
+ os.utime(orphan, (300.0, 300.0))
+ _save_with_mtime("p1", 200.0)
+ page1 = gallery.list_audio(limit = 2, offset = 0)
+ assert [r["prompt"] for r in page1] == ["p1", "p2"]
+
+
+def test_list_skips_corrupt_sidecar():
+ directory = gallery.gallery_dir()
+ (directory / "broken.wav").write_bytes(_wav())
+ (directory / "broken.json").write_text("{not json", encoding = "utf-8")
+ gallery.save(_wav(), _meta(prompt = "ours"))
+ assert [r["prompt"] for r in gallery.list_audio()] == ["ours"]
+
+
+def test_list_skips_invalid_utf8_sidecar():
+ # Invalid UTF-8 raises UnicodeDecodeError, not an OSError: one corrupt sidecar is skipped, it does not 500 the listing.
+ directory = gallery.gallery_dir()
+ (directory / "badbytes.wav").write_bytes(_wav())
+ (directory / "badbytes.json").write_bytes(b"\xff\xfe{}")
+ gallery.save(_wav(), _meta(prompt = "ours"))
+ assert [r["prompt"] for r in gallery.list_audio()] == ["ours"]
+
+
+def test_clear_preserves_wav_with_present_but_invalid_sidecar():
+ # A hand-dropped WAV whose sidecar parses but lacks the required recipe keys is hidden by list_audio, so clear must spare it.
+ directory = gallery.gallery_dir()
+ (directory / "foreign.wav").write_bytes(_wav())
+ (directory / "foreign.json").write_text("{}", encoding = "utf-8")
+ gallery.save(_wav(), _meta(prompt = "ours"))
+ assert gallery.clear() == 1
+ assert (directory / "foreign.wav").exists()
+
+
+def test_delete_refuses_wav_with_present_but_invalid_sidecar():
+ # The gallery never surfaced a record missing required keys, so a guessed id must not destroy it.
+ directory = gallery.gallery_dir()
+ (directory / "foreign.wav").write_bytes(_wav())
+ (directory / "foreign.json").write_text(
+ json.dumps({"prompt": "x"}), encoding = "utf-8"
+ ) # partial sidecar (no model/sample_rate/...)
+ assert gallery.delete("foreign") is False
+ assert (directory / "foreign.wav").exists()
+
+
+def test_valid_callback_paginates_over_accepted_records():
+ # ``valid`` must filter before pagination, else a leading bad record returns a short page and stalls scroll.
+ _save_with_mtime("BAD", 300.0) # newest, sorts first
+ _save_with_mtime("g1", 200.0)
+ _save_with_mtime("g2", 100.0)
+
+ def _valid(rec):
+ return rec.get("prompt") != "BAD"
+
+ page = gallery.list_audio(limit = 2, offset = 0, valid = _valid)
+ assert [r["prompt"] for r in page] == ["g1", "g2"]
+ assert len(gallery.list_audio(limit = 3, offset = 0, valid = _valid)) == 2
+
+
+def test_save_leaves_no_orphan_wav_when_sidecar_publish_fails(monkeypatch):
+ # If the sidecar (the pair's commit marker) fails to publish, the WAV must not be stranded as an invisible orphan.
+ real_replace = gallery.os.replace
+ calls = {"n": 0}
+
+ def _replace(src, dst, *a, **k):
+ calls["n"] += 1
+ if calls["n"] == 2: # the sidecar publish
+ raise OSError("simulated sidecar failure")
+ return real_replace(src, dst, *a, **k)
+
+ monkeypatch.setattr(gallery.os, "replace", _replace)
+ with pytest.raises(OSError, match = "simulated sidecar failure"):
+ gallery.save(_wav(), _meta())
+ # No wav, no sidecar, no temp files: the whole record was rolled back.
+ assert list(gallery.gallery_dir().iterdir()) == []
+ assert gallery.list_audio() == []
+
+
+def test_a_nonnumeric_cap_disables_pruning(monkeypatch):
+ """The documented contract: "off" means off. Restoring the default for a value the
+ operator did set would delete recordings they had asked to keep."""
+ from core.inference import audio_gallery
+
+ monkeypatch.setenv("UNSLOTH_AUDIO_GALLERY_MAX_CLIPS", "off")
+ assert audio_gallery._max_clips() == 0
+ monkeypatch.setenv("UNSLOTH_AUDIO_GALLERY_MAX_CLIPS", "0")
+ assert audio_gallery._max_clips() == 0
+ monkeypatch.setenv("UNSLOTH_AUDIO_GALLERY_MAX_CLIPS", "5")
+ assert audio_gallery._max_clips() == 5
+ monkeypatch.delenv("UNSLOTH_AUDIO_GALLERY_MAX_CLIPS")
+ assert audio_gallery._max_clips() == audio_gallery._DEFAULT_MAX_CLIPS
diff --git a/studio/backend/tests/test_audio_probe_target.py b/studio/backend/tests/test_audio_probe_target.py
new file mode 100644
index 00000000000..111c278d6a0
--- /dev/null
+++ b/studio/backend/tests/test_audio_probe_target.py
@@ -0,0 +1,61 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A curated registry alias must be resolved before asking whether it is an audio model.
+
+"Spark-TTS-0.5B/LLM" names a load subdirectory, not a repository. Probing it fetched a
+repo that does not exist, got a 404 on every candidate path, and read that as a
+DEFINITIVE "not an audio model" rather than "not a repo id". Spark-TTS then presented as
+a text model, so choosing it with an audio dataset hit the modality gate and Start
+Training stayed disabled (reported on Windows against PR 7984).
+"""
+
+from __future__ import annotations
+
+import pytest
+
+pytest.importorskip("torch")
+
+from routes.models import _audio_probe_target # noqa: E402
+
+
+def test_a_registry_alias_resolves_to_the_repo_that_exists():
+ assert _audio_probe_target("Spark-TTS-0.5B/LLM") == "unsloth/Spark-TTS-0.5B"
+
+
+def test_a_plain_repo_id_is_unchanged():
+ assert _audio_probe_target("unsloth/Spark-TTS-0.5B") == "unsloth/Spark-TTS-0.5B"
+ assert _audio_probe_target("unsloth/gemma-3-270m-it") == "unsloth/gemma-3-270m-it"
+
+
+def test_a_local_path_is_never_rewritten(tmp_path):
+ # A trained checkpoint is a directory, and the registry knows nothing about it.
+ assert _audio_probe_target(str(tmp_path)) == str(tmp_path)
+
+
+def test_an_unresolvable_name_falls_through_rather_than_failing():
+ assert _audio_probe_target("nobody/not-in-any-registry") == "nobody/not-in-any-registry"
+
+
+def test_the_merged_export_load_path_resolves_the_alias_the_same_way():
+ """One resolver, not two. The BiCodec export path used to carry its own copy of the
+ "Spark-TTS-0.5B/LLM" -> "unsloth/Spark-TTS-0.5B" mapping; it now shares load_scan_target
+ with the capability probe here and with the trainer preflight in routes/training.py, so
+ the three cannot drift."""
+ # Read rather than import: core.inference.inference pulls the whole Unsloth stack,
+ # which is what made a second, dependency-light copy of this mapping tempting.
+ from pathlib import Path
+
+ source = (
+ Path(__file__).resolve().parents[1] / "core" / "inference" / "inference.py"
+ ).read_text(encoding = "utf-8")
+ assert "load_scan_target(" in source
+ assert "spark_tts_base_repo" not in source
+
+ from utils.security import load_scan_target
+ from utils.utils import canonical_model_repo_id
+
+ repo, subdirs = load_scan_target(canonical_model_repo_id("Spark-TTS-0.5B/LLM"), ())
+ assert repo == "unsloth/Spark-TTS-0.5B"
+ # BiCodec lives at the repo root; LLM is where the language model half sits.
+ assert subdirs == ("LLM",)
diff --git a/studio/backend/tests/test_audio_sampling_fill.py b/studio/backend/tests/test_audio_sampling_fill.py
index efea18b83e2..11bb65f9e05 100644
--- a/studio/backend/tests/test_audio_sampling_fill.py
+++ b/studio/backend/tests/test_audio_sampling_fill.py
@@ -11,11 +11,13 @@ generation. These exercise the transformers TTS path of ``generate_audio`` (the
"""
import asyncio
+import json
import pytest
import routes.inference as inference_route
-from models.inference import ChatCompletionRequest
+from fastapi import HTTPException
+from models.inference import AudioSpeechRequest, ChatCompletionRequest
from utils.inference import inference_config as ic
@@ -26,9 +28,9 @@ class _FakeLlama:
class _FakeTransformersBackend:
- def __init__(self):
+ def __init__(self, audio_type = "snac"):
self.active_model_name = "some/custom-tts"
- self.models = {"some/custom-tts": {"is_audio": True}}
+ self.models = {"some/custom-tts": {"is_audio": True, "audio_type": audio_type}}
self.captured = {}
def generate_audio_response(self, **kwargs):
@@ -88,3 +90,47 @@ def test_audio_operator_pin_overrides_client(monkeypatch):
def test_audio_client_explicit_preserved(monkeypatch):
captured = _run_generate_audio(monkeypatch, recommended = {"temperature": 1.0}, temperature = 0.2)
assert captured["temperature"] == 0.2 # explicit client value preserved over recommendation
+
+
+def test_audio_generate_returns_the_exact_persisted_clip_id(monkeypatch):
+ backend = _FakeTransformersBackend()
+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: _FakeLlama())
+ monkeypatch.setattr(inference_route, "get_inference_backend", lambda: backend)
+
+ async def _noop_switch(*a, **k):
+ return None
+
+ monkeypatch.setattr(inference_route, "_maybe_auto_switch_model", _noop_switch)
+ payload = ChatCompletionRequest(
+ model = "some/custom-tts", messages = [{"role": "user", "content": "hi"}]
+ )
+ response = asyncio.run(
+ inference_route.generate_audio(payload, request = None, current_subject = "t")
+ )
+ body = json.loads(response.body)
+ assert body["clip_id"]
+ assert len(body["clip_id"]) == 32
+
+
+def test_whisper_is_rejected_cleanly_by_both_tts_endpoints(monkeypatch):
+ backend = _FakeTransformersBackend(audio_type = "whisper")
+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: _FakeLlama())
+ monkeypatch.setattr(inference_route, "get_inference_backend", lambda: backend)
+
+ async def _noop_switch(*a, **k):
+ return None
+
+ monkeypatch.setattr(inference_route, "_maybe_auto_switch_model", _noop_switch)
+ payload = ChatCompletionRequest(
+ model = "some/custom-tts", messages = [{"role": "user", "content": "hi"}]
+ )
+ speech = AudioSpeechRequest(input = "hi", model = "some/custom-tts")
+ for request in (
+ inference_route.generate_audio(payload, request = None, current_subject = "t"),
+ inference_route.openai_audio_speech(speech, request = None, current_subject = "t"),
+ ):
+ with pytest.raises(HTTPException) as exc:
+ asyncio.run(request)
+ assert exc.value.status_code == 400
+ assert "does not support text-to-speech" in exc.value.detail
+ assert backend.captured == {}
diff --git a/studio/backend/tests/test_audio_token_detection.py b/studio/backend/tests/test_audio_token_detection.py
index 02d47905192..8a31cf86432 100644
--- a/studio/backend/tests/test_audio_token_detection.py
+++ b/studio/backend/tests/test_audio_token_detection.py
@@ -6,6 +6,8 @@
from __future__ import annotations
+import json
+
from utils.models.model_config import _AUDIO_TOKEN_PATTERNS, is_audio_input_type
@@ -41,3 +43,280 @@ def test_audio_vlm_and_whisper_accept_audio_input():
def test_non_audio_tokens_classify_none():
assert _classify(["<bos>", "<eos>", "<pad>"]) is None
+
+
+def test_orpheus_snac_codebook_beats_a_stray_audio_marker():
+ """Orpheus ships 28k <custom_token_N> SNAC codes AND a lone <|audio|>.
+
+ audio_vlm was tested first and won, so a TTS model came back as audio-INPUT:
+ is_audio stayed False and the Audio page refused it.
+ """
+ tokens = ["<|audio|>"] + [f"<custom_token_{i}>" for i in range(28683)]
+ assert _classify(tokens) == "snac"
+ assert is_audio_input_type(_classify(tokens)) is False
+
+
+def test_a_codec_family_is_not_shadowed_by_a_stray_audio_marker():
+ """The same precedence has to hold for every output codec, not just snac."""
+ assert _classify(["<|audio|>", "<|bicodec_semantic_0|>"]) == "bicodec"
+ assert (
+ _classify(
+ [
+ "<|audio|>",
+ "<|audio_start|>",
+ "<|audio_end|>",
+ "<|text_start|>",
+ "<|text_end|>",
+ ]
+ )
+ == "dac"
+ )
+
+
+class _Resp:
+ def __init__(
+ self,
+ status_code: int,
+ payload = None,
+ ):
+ self.status_code = status_code
+ self.ok = 200 <= status_code < 300
+ self._payload = payload
+
+ def json(self):
+ if self._payload is None:
+ raise ValueError("no body")
+ return self._payload
+
+
+def _detect_checked(
+ monkeypatch,
+ responses,
+ model = "acme/tts-model",
+):
+ """Drive detect_audio_type_checked with a faked Hub, no local cache."""
+ from utils.models import model_config as mc
+
+ monkeypatch.setattr(mc, "_audio_detection_cache", {})
+ monkeypatch.setattr(mc, "get_cache_path", lambda *a, **k: None)
+ monkeypatch.setattr(mc, "_env_offline", lambda: False)
+
+ import requests
+
+ monkeypatch.setattr(requests, "get", lambda url, **kw: responses.pop(0))
+ return mc.detect_audio_type_checked(model)
+
+
+def test_a_gated_repo_is_not_reported_as_definitively_non_audio(monkeypatch):
+ # 401 on every tokenizer_config path: nothing was read, so None means unknown.
+ audio_type, definitive = _detect_checked(monkeypatch, [_Resp(401), _Resp(401)])
+ assert audio_type is None
+ assert definitive is False
+
+
+def test_a_readable_repo_without_audio_tokens_is_definitive(monkeypatch):
+ # 200 with a plain tokenizer, then a 404 for the LLM/ variant: a real negative.
+ plain = {"added_tokens_decoder": {"0": {"content": "<bos>"}}}
+ audio_type, definitive = _detect_checked(monkeypatch, [_Resp(200, plain), _Resp(404)])
+ assert audio_type is None
+ assert definitive is True
+
+
+def test_a_detected_codec_is_definitive(monkeypatch):
+ snac = {
+ "added_tokens_decoder": {str(i): {"content": f"<custom_token_{i}>"} for i in range(10_001)}
+ }
+ audio_type, definitive = _detect_checked(monkeypatch, [_Resp(200, snac)])
+ assert audio_type == "snac"
+ assert definitive is True
+
+
+def test_a_local_path_never_reaches_the_hub(monkeypatch, tmp_path):
+ """A filesystem path is not a repo id, so the Hub URL would be nonsense.
+
+ /loras hits this for every adapter directory without its own tokenizer, and a transient
+ failure is never cached, so it paid two 15s timeouts per checkpoint on every scan while
+ blocking the event loop that called it.
+ """
+ from utils.models import model_config
+
+ # Recorded rather than raised: the fetch loop catches every exception and treats it as
+ # a transient failure, so a raising stub would be swallowed and the test would pass
+ # against the unfixed code.
+ fetched = []
+
+ import requests
+
+ monkeypatch.setattr(requests, "get", lambda url, **kwargs: fetched.append(url))
+ adapter = tmp_path / "adapter"
+ adapter.mkdir()
+ (adapter / "adapter_config.json").write_text("{}", encoding = "utf-8")
+
+ result, definitive = model_config._detect_audio_from_tokenizer(str(adapter))
+ assert fetched == [], fetched
+ assert result is None
+ # Nothing was read, so the answer is not definitive and must not be cached.
+ assert definitive is False
+
+
+def test_an_offline_miss_is_not_reprobed_on_every_poll(monkeypatch, tmp_path):
+ """/loras probes every checkpoint and its base. Neither answers offline, and a
+ non-definitive result is never cached, so the walk repeated on every poll: with 50
+ checkpoints that measured 6ms -> 26ms per call, on the event loop."""
+ from utils.models import model_config
+
+ monkeypatch.setattr(model_config, "_audio_detection_cache", {})
+ monkeypatch.setattr(model_config, "_audio_offline_miss_cache", {})
+ probes = []
+ monkeypatch.setattr(
+ model_config,
+ "_detect_audio_from_tokenizer",
+ lambda name, token = None, **kw: (probes.append(name), (None, False))[1],
+ )
+
+ for _ in range(5):
+ assert model_config.detect_audio_type_checked(
+ "org/not-downloaded", local_files_only = True
+ ) == (None, False)
+ assert probes == ["org/not-downloaded"], probes
+
+
+def test_the_offline_miss_expires_so_a_later_download_is_seen(monkeypatch):
+ """Bounded, not permanent: the base may be downloaded, or a training run may finish
+ writing the tokenizer it was missing, and neither restarts Studio."""
+ from utils.models import model_config
+
+ monkeypatch.setattr(model_config, "_audio_detection_cache", {})
+ monkeypatch.setattr(model_config, "_audio_offline_miss_cache", {})
+ answers = iter([(None, False), ("snac", True)])
+ monkeypatch.setattr(
+ model_config,
+ "_detect_audio_from_tokenizer",
+ lambda name, token = None, **kw: next(answers),
+ )
+ clock = [1000.0]
+ monkeypatch.setattr(model_config.time, "monotonic", lambda: clock[0])
+
+ assert model_config.detect_audio_type_checked("org/m", local_files_only = True)[0] is None
+ clock[0] += model_config._AUDIO_OFFLINE_MISS_TTL_S + 1
+ assert model_config.detect_audio_type_checked("org/m", local_files_only = True) == ("snac", True)
+ # Definitive now, so it is in the real cache and the miss entry is gone.
+ assert model_config._audio_offline_miss_cache == {}
+
+
+def test_an_online_transient_failure_still_retries_immediately(monkeypatch):
+ """The bound is deliberately only for probes that touched no network. A gated repo or
+ a 5xx must not be remembered, or fixing the token would take a minute to take."""
+ from utils.models import model_config
+
+ monkeypatch.setattr(model_config, "_audio_detection_cache", {})
+ monkeypatch.setattr(model_config, "_audio_offline_miss_cache", {})
+ probes = []
+ monkeypatch.setattr(
+ model_config,
+ "_detect_audio_from_tokenizer",
+ lambda name, token = None, **kw: (probes.append(name), (None, False))[1],
+ )
+
+ for _ in range(3):
+ model_config.detect_audio_type_checked("org/gated", local_files_only = False)
+ assert len(probes) == 3, probes
+
+
+def test_every_pattern_has_a_marker_so_the_parse_can_be_skipped():
+ """The marker list is what lets a large text tokenizer_config be settled without
+ parsing it. It cannot be derived from the patterns, which are lambdas, so a codec
+ added there without a marker here would silently stop being detected."""
+ from utils.models.model_config import (
+ _AUDIO_TOKEN_MARKERS,
+ _AUDIO_TOKEN_PATTERNS,
+ _may_hold_audio_tokens,
+ )
+
+ # Fails when a codec is added, which is the point: add its marker too.
+ assert set(_AUDIO_TOKEN_PATTERNS) == {
+ "csm",
+ "whisper",
+ "bicodec",
+ "dac",
+ "snac",
+ "audio_vlm",
+ }
+
+ # Whatever each pattern matches, the marker scan must let it through to the parse.
+ samples = {
+ "csm": ["<|AUDIO|>", "<|audio_eos|>"],
+ "whisper": ["<|startoftranscript|>"],
+ "bicodec": ["<|bicodec_semantic_0|>"],
+ "dac": ["<|audio_start|>", "<|audio_end|>", "<|text_start|>", "<|text_end|>"],
+ "snac": [f"<custom_token_{i}>" for i in range(10001)],
+ "audio_vlm": ["<audio_soft_token>"],
+ }
+ for audio_type, tokens in samples.items():
+ assert _classify(tokens) == audio_type, audio_type
+ assert _may_hold_audio_tokens(json.dumps(tokens)), audio_type
+ assert _may_hold_audio_tokens(json.dumps(["<|image|>", "<|audio|>"]))
+
+ # And an ordinary text tokenizer is settled without a parse.
+ assert not _may_hold_audio_tokens(
+ json.dumps([f"<|extra_token_{i}|>" for i in range(500)] + ["<bos>", "<eos>"])
+ )
+ assert all(marker in "".join(_AUDIO_TOKEN_MARKERS) for marker in _AUDIO_TOKEN_MARKERS)
+
+
+def test_a_large_text_tokenizer_is_not_parsed(monkeypatch, tmp_path):
+ """The saving, pinned: an ordinary checkpoint's tokenizer_config is read but never
+ handed to json.loads, which was the bulk of a cold /loras scan."""
+ import json as json_module
+
+ from utils.models import model_config
+
+ config = {
+ "added_tokens_decoder": {
+ str(i): {"content": f"<|extra_token_{i}|>", "special": True} for i in range(5000)
+ }
+ }
+ checkpoint = tmp_path / "run"
+ checkpoint.mkdir()
+ (checkpoint / "tokenizer_config.json").write_text(json_module.dumps(config))
+
+ parsed = []
+ real_loads = model_config.json.loads
+ monkeypatch.setattr(
+ model_config.json,
+ "loads",
+ lambda raw, *a, **kw: (parsed.append(len(raw)), real_loads(raw, *a, **kw))[1],
+ )
+
+ result, definitive = model_config._detect_audio_from_tokenizer(
+ str(checkpoint), local_files_only = True
+ )
+
+ assert result is None
+ # Read successfully, so "not audio" is a definitive answer, not an unknown.
+ assert definitive is True
+ assert parsed == [], parsed
+
+
+def test_a_half_written_tokenizer_stays_unknown(tmp_path):
+ """The skip-the-parse path must not turn a training run's part-written tokenizer into
+ a definitive "not audio", which would be cached for the life of the process. It stays
+ unknown, exactly as it did when json.loads raised on the truncated text."""
+ from utils.models import model_config
+
+ checkpoint = tmp_path / "mid_write"
+ checkpoint.mkdir()
+ whole = json.dumps({"added_tokens_decoder": {"0": {"content": "<|plain|>"}}})
+ (checkpoint / "tokenizer_config.json").write_text(whole[: len(whole) // 2])
+
+ result, definitive = model_config._detect_audio_from_tokenizer(
+ str(checkpoint), local_files_only = True
+ )
+ assert result is None
+ assert definitive is False
+
+ (checkpoint / "tokenizer_config.json").write_text(whole)
+ assert model_config._detect_audio_from_tokenizer(str(checkpoint), local_files_only = True) == (
+ None,
+ True,
+ )
diff --git a/studio/backend/tests/test_audio_tts_cancellation.py b/studio/backend/tests/test_audio_tts_cancellation.py
new file mode 100644
index 00000000000..263fa21818f
--- /dev/null
+++ b/studio/backend/tests/test_audio_tts_cancellation.py
@@ -0,0 +1,600 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+"""Request-scoped cancellation for blocking Transformers TTS generation."""
+
+import asyncio
+import base64
+import queue
+import threading
+import time
+
+import pytest
+
+import routes.inference as inference_route
+from core.inference import orchestrator as orchestrator_module
+from core.inference.orchestrator import InferenceOrchestrator
+from core.inference.worker import _handle_generate_audio, _prepare_generate_audio
+from models.inference import ChatCompletionRequest
+
+
+def _bare_orchestrator():
+ orchestrator = InferenceOrchestrator.__new__(InferenceOrchestrator)
+ orchestrator._gen_lock = threading.Lock()
+ orchestrator._send_order_lock = threading.Lock()
+ orchestrator._active_cancel_lock = threading.Lock()
+ orchestrator._active_cancel_events = []
+ orchestrator._executing_cancel_events = []
+ orchestrator._cancel_event = threading.Event()
+ orchestrator._drain_event = threading.Event()
+ orchestrator._proc = object()
+ orchestrator._cmd_queue = object()
+ orchestrator._resp_queue = object()
+ orchestrator._dispatcher_thread = None
+ orchestrator._dispatcher_stop = threading.Event()
+ orchestrator._dispatcher_lifecycle_lock = threading.Lock()
+ orchestrator._mailbox_lock = threading.Lock()
+ orchestrator._mailboxes = {}
+ orchestrator._direct_mailboxes = {}
+ orchestrator._request_cancel_events = {}
+ orchestrator._unload_pending = False
+ orchestrator._exclusive_tts_pending = False
+ orchestrator.active_model_name = "model"
+ orchestrator.models = {"model": {}}
+ orchestrator.loading_models = set()
+ return orchestrator
+
+
+def test_route_passes_request_cancel_event_to_transformers_backend(monkeypatch):
+ captured = {}
+
+ class _Llama:
+ is_loaded = False
+ _is_audio = False
+
+ class _Backend:
+ active_model_name = "some/custom-tts"
+ models = {"some/custom-tts": {"is_audio": True, "audio_type": "snac"}}
+
+ def generate_audio_response(self, **kwargs):
+ captured.update(kwargs)
+ return b"RIFFfake", 24000
+
+ async def _noop_switch(*_args, **_kwargs):
+ return None
+
+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: _Llama())
+ monkeypatch.setattr(inference_route, "get_inference_backend", lambda: _Backend())
+ monkeypatch.setattr(inference_route, "_maybe_auto_switch_model", _noop_switch)
+ payload = ChatCompletionRequest(
+ model = "some/custom-tts",
+ messages = [{"role": "user", "content": "hello"}],
+ )
+
+ asyncio.run(
+ inference_route._generate_tts_wav("hello", payload, request = None, current_subject = "t")
+ )
+
+ assert "cancel_event" in captured
+ assert captured["cancel_event"].is_set() is False
+
+
+def test_audio_response_stopped_while_queued_is_never_sent(monkeypatch):
+ orchestrator = _bare_orchestrator()
+ monkeypatch.setattr(orchestrator, "_ensure_subprocess_alive", lambda: True)
+ monkeypatch.setattr(
+ orchestrator,
+ "_send_cmd",
+ lambda _cmd: pytest.fail("must not send TTS already stopped"),
+ )
+ stopped = threading.Event()
+ stopped.set()
+
+ with pytest.raises(RuntimeError, match = "cancel"):
+ orchestrator.generate_audio_response("hello", cancel_event = stopped)
+
+ assert orchestrator._active_cancel_events == []
+
+
+def test_audio_response_cancellation_signals_worker_and_drains_terminal_response(monkeypatch):
+ orchestrator = _bare_orchestrator()
+ monkeypatch.setattr(orchestrator, "_ensure_subprocess_alive", lambda: True)
+ sent = []
+ monkeypatch.setattr(orchestrator, "_send_cmd", lambda cmd: sent.append(cmd))
+ caller_cancel = threading.Event()
+ released = []
+ reads = 0
+
+ def read_one(*, timeout):
+ nonlocal reads
+ reads += 1
+ if reads == 1:
+ caller_cancel.set()
+ assert orchestrator._cancel_event.is_set() is False
+ return None
+ if reads == 2:
+ # The worker acknowledges only after clearing stale shared state. The
+ # parent must not signal while the TTS command is merely queued.
+ assert orchestrator._cancel_event.is_set() is False
+ return {
+ "type": "audio_started",
+ "request_id": sent[0]["request_id"],
+ }
+ assert orchestrator._cancel_event.is_set() is True
+ return {
+ "type": "audio_error",
+ "request_id": sent[0]["request_id"],
+ "error": "cancelled",
+ }
+
+ monkeypatch.setattr(
+ orchestrator,
+ "_direct_reader",
+ lambda _request_id: (read_one, lambda **_kwargs: None, lambda: released.append(True)),
+ )
+
+ with pytest.raises(RuntimeError, match = "cancel"):
+ orchestrator.generate_audio_response("hello", cancel_event = caller_cancel)
+
+ assert sent and sent[0]["type"] == "generate_audio"
+ assert reads == 3
+ assert released == [True]
+ assert orchestrator._active_cancel_events == []
+ assert orchestrator._executing_cancel_events == []
+
+
+def test_audio_response_cancellation_bounds_an_unresponsive_worker(monkeypatch):
+ orchestrator = _bare_orchestrator()
+ monkeypatch.setattr(orchestrator, "_ensure_subprocess_alive", lambda: True)
+ monkeypatch.setattr(orchestrator_module, "_AUDIO_GENERATION_TIMEOUT", 100.0)
+ monkeypatch.setattr(orchestrator_module, "_AUDIO_CANCEL_DRAIN_TIMEOUT", 0.03)
+ caller_cancel = threading.Event()
+ sent = []
+
+ def read_one(*, timeout):
+ if not caller_cancel.is_set():
+ caller_cancel.set()
+ return {
+ "type": "audio_started",
+ "request_id": sent[0]["request_id"],
+ }
+ time.sleep(timeout)
+ return None
+
+ monkeypatch.setattr(orchestrator, "_send_cmd", lambda cmd: sent.append(cmd))
+ cancel_signals = []
+ monkeypatch.setattr(orchestrator, "_cancel_generation", lambda: cancel_signals.append(True))
+ monkeypatch.setattr(
+ orchestrator,
+ "_direct_reader",
+ lambda _request_id: (
+ read_one,
+ lambda **_kwargs: pytest.fail("the cancellation drain window was already spent"),
+ lambda: None,
+ ),
+ )
+ shutdown_state = []
+
+ def shutdown(*, timeout):
+ shutdown_state.append((orchestrator._exclusive_tts_pending, timeout))
+ return True
+
+ monkeypatch.setattr(orchestrator, "_shutdown_subprocess", shutdown)
+
+ started = time.monotonic()
+ with pytest.raises(RuntimeError, match = "Audio generation cancelled"):
+ orchestrator.generate_audio_response("hello", cancel_event = caller_cancel)
+
+ assert time.monotonic() - started < 0.5
+ assert cancel_signals == [True]
+ assert shutdown_state == [(True, 0.03)]
+ assert orchestrator.active_model_name is None
+ assert orchestrator.models == {}
+ assert orchestrator._exclusive_tts_pending is False
+
+
+def test_audio_response_cancellation_before_worker_start_is_still_bounded(monkeypatch):
+ orchestrator = _bare_orchestrator()
+ monkeypatch.setattr(orchestrator, "_ensure_subprocess_alive", lambda: True)
+ monkeypatch.setattr(orchestrator_module, "_AUDIO_GENERATION_TIMEOUT", 100.0)
+ monkeypatch.setattr(orchestrator_module, "_AUDIO_CANCEL_DRAIN_TIMEOUT", 0.03)
+ # Before audio_started there is nobody to receive the cancel, so this window is the
+ # teardown budget, not the drain: a prefill pass is slow, not unresponsive. Still bounded.
+ monkeypatch.setattr(orchestrator_module, "_AUDIO_CANCEL_TEARDOWN_TIMEOUT", 0.05)
+ caller_cancel = threading.Event()
+
+ def send(_cmd):
+ caller_cancel.set()
+
+ def read_one(*, timeout):
+ time.sleep(timeout)
+ return None
+
+ monkeypatch.setattr(orchestrator, "_send_cmd", send)
+ monkeypatch.setattr(
+ orchestrator,
+ "_cancel_generation",
+ lambda: pytest.fail("must not signal shared cancellation before audio_started"),
+ )
+ monkeypatch.setattr(
+ orchestrator,
+ "_direct_reader",
+ lambda _request_id: (
+ read_one,
+ lambda **_kwargs: pytest.fail("the cancellation drain window was already spent"),
+ lambda: None,
+ ),
+ )
+ shutdown_state = []
+ monkeypatch.setattr(
+ orchestrator,
+ "_shutdown_subprocess",
+ lambda *, timeout: shutdown_state.append(timeout) or True,
+ )
+
+ started = time.monotonic()
+ with pytest.raises(RuntimeError, match = "Audio generation cancelled"):
+ orchestrator.generate_audio_response("hello", cancel_event = caller_cancel)
+
+ assert time.monotonic() - started < 0.5
+ assert shutdown_state == [0.03]
+ assert orchestrator._exclusive_tts_pending is False
+
+
+def test_audio_generation_timeout_scales_with_requested_tokens(monkeypatch):
+ monkeypatch.setattr(orchestrator_module, "_AUDIO_GENERATION_TIMEOUT", 10.0)
+
+ assert orchestrator_module._audio_generation_timeout(512) == 10.0
+ assert orchestrator_module._audio_generation_timeout(2048) == 10.0
+ assert orchestrator_module._audio_generation_timeout(8192) == 40.0
+ assert orchestrator_module._audio_generation_timeout(10**310) == 40.0
+
+
+def test_tts_route_bounds_public_token_budget():
+ payload = ChatCompletionRequest(
+ messages = [{"role": "user", "content": "hello"}],
+ max_tokens = 10**310,
+ )
+
+ assert inference_route._tts_max_new_tokens(payload) == 8192
+
+
+def test_audio_worker_command_uses_the_bounded_token_budget(monkeypatch):
+ orchestrator = _bare_orchestrator()
+ monkeypatch.setattr(orchestrator, "_ensure_subprocess_alive", lambda: True)
+ sent = []
+ monkeypatch.setattr(orchestrator, "_send_cmd", lambda cmd: sent.append(cmd))
+
+ def direct_reader(request_id):
+ responses = queue.Queue()
+ responses.put(
+ {
+ "type": "audio_done",
+ "request_id": request_id,
+ "wav_base64": base64.b64encode(b"RIFFfake").decode("ascii"),
+ "sample_rate": 24000,
+ }
+ )
+ return (
+ lambda *, timeout: responses.get(timeout = timeout),
+ lambda **_kwargs: None,
+ lambda: None,
+ )
+
+ monkeypatch.setattr(orchestrator, "_direct_reader", direct_reader)
+
+ assert orchestrator.generate_audio_response("hello", max_new_tokens = 10**310) == (
+ b"RIFFfake",
+ 24000,
+ )
+ assert sent[0]["max_new_tokens"] == 8192
+
+
+def test_audio_response_timeout_cancels_and_drains_before_releasing(monkeypatch):
+ orchestrator = _bare_orchestrator()
+ orchestrator._resp_queue = queue.Queue()
+ monkeypatch.setattr(orchestrator, "_ensure_subprocess_alive", lambda: True)
+ monkeypatch.setattr(orchestrator_module, "_AUDIO_GENERATION_TIMEOUT", 0.05)
+ monkeypatch.setattr(orchestrator_module, "_AUDIO_CANCEL_DRAIN_TIMEOUT", 0.2)
+ monkeypatch.setattr(
+ orchestrator,
+ "_shutdown_subprocess",
+ lambda **_kwargs: pytest.fail("a drained timeout must not tear the worker down"),
+ )
+
+ sent = []
+
+ def send(cmd):
+ sent.append(cmd)
+ orchestrator._resp_queue.put({"type": "audio_started", "request_id": cmd["request_id"]})
+
+ monkeypatch.setattr(orchestrator, "_send_cmd", send)
+ cancel_state = []
+
+ def cancel_generation():
+ cancel_state.append(orchestrator._exclusive_tts_pending)
+ orchestrator._cancel_event.set()
+ orchestrator._resp_queue.put(
+ {
+ "type": "audio_error",
+ "request_id": sent[0]["request_id"],
+ "error": "cancelled",
+ }
+ )
+
+ monkeypatch.setattr(orchestrator, "_cancel_generation", cancel_generation)
+
+ with pytest.raises(RuntimeError, match = "Timeout waiting for audio generation"):
+ orchestrator.generate_audio_response("hello")
+
+ assert cancel_state == [True], "timeout cancellation must occur under TTS exclusivity"
+ assert orchestrator._exclusive_tts_pending is False
+ assert orchestrator._active_cancel_events == []
+ assert orchestrator._executing_cancel_events == []
+
+
+def test_audio_response_timeout_tears_down_unresponsive_worker_before_release(monkeypatch):
+ orchestrator = _bare_orchestrator()
+ orchestrator._resp_queue = queue.Queue()
+ monkeypatch.setattr(orchestrator, "_ensure_subprocess_alive", lambda: True)
+ monkeypatch.setattr(orchestrator_module, "_AUDIO_GENERATION_TIMEOUT", 0.03)
+ monkeypatch.setattr(orchestrator_module, "_AUDIO_CANCEL_DRAIN_TIMEOUT", 0.03)
+
+ sent = []
+
+ def send(cmd):
+ sent.append(cmd)
+ orchestrator._resp_queue.put({"type": "audio_started", "request_id": cmd["request_id"]})
+
+ monkeypatch.setattr(orchestrator, "_send_cmd", send)
+ monkeypatch.setattr(orchestrator, "_cancel_generation", lambda: None)
+ shutdown_state = []
+
+ def shutdown(*, timeout):
+ shutdown_state.append((orchestrator._exclusive_tts_pending, timeout))
+ return True
+
+ monkeypatch.setattr(orchestrator, "_shutdown_subprocess", shutdown)
+
+ with pytest.raises(RuntimeError, match = "Timeout waiting for audio generation"):
+ orchestrator.generate_audio_response("hello")
+
+ assert shutdown_state == [(True, 0.03)]
+ assert orchestrator._exclusive_tts_pending is False
+ assert orchestrator.active_model_name is None
+ assert orchestrator.models == {}
+
+
+def test_worker_audio_prepare_rechecks_unload_drain_after_clear():
+ drain = threading.Event()
+
+ class _Cancel:
+ def clear(self):
+ # Exact race: unload lands after the first drain check but before the
+ # worker clear would otherwise erase its shared cancel.
+ drain.set()
+
+ responses = queue.Queue()
+ ready = _prepare_generate_audio(
+ {"type": "generate_audio", "request_id": "audio-1"},
+ responses,
+ _Cancel(),
+ drain,
+ )
+
+ assert ready is False
+ response = responses.get_nowait()
+ assert response["type"] == "audio_error"
+ assert response["request_id"] == "audio-1"
+ assert response["cancelled"] is True
+ assert response["error"] == "Audio generation cancelled"
+ assert responses.empty(), "audio_started must not be emitted for a drained request"
+
+
+def test_worker_audio_prepare_acknowledges_only_after_cancel_clear():
+ operations = []
+
+ class _Cancel:
+ def clear(self):
+ operations.append("clear")
+
+ class _Responses:
+ def put(self, response):
+ operations.append(response["type"])
+
+ assert _prepare_generate_audio(
+ {"type": "generate_audio", "request_id": "audio-1"},
+ _Responses(),
+ _Cancel(),
+ threading.Event(),
+ )
+ assert operations == ["clear", "audio_started"]
+
+
+class _AliveDispatcher:
+ def is_alive(self):
+ return True
+
+
+def test_dispatcher_refuses_during_exclusive_tts_and_resumes_after():
+ orchestrator = _bare_orchestrator()
+ orchestrator._resp_queue = queue.Queue()
+ orchestrator._exclusive_tts_pending = True
+
+ assert orchestrator._start_dispatcher() is False
+ assert orchestrator._dispatcher_thread is None
+
+ orchestrator._exclusive_tts_pending = False
+ try:
+ assert orchestrator._start_dispatcher() is True
+ assert orchestrator._dispatcher_thread is not None
+ assert orchestrator._dispatcher_thread.is_alive()
+ finally:
+ orchestrator._stop_dispatcher()
+
+
+def test_tts_waits_for_existing_compare_before_send(monkeypatch):
+ orchestrator = _bare_orchestrator()
+ orchestrator._dispatcher_thread = _AliveDispatcher()
+ orchestrator._mailboxes["compare"] = queue.Queue()
+ monkeypatch.setattr(orchestrator, "_ensure_subprocess_alive", lambda: True)
+
+ sent = []
+ monkeypatch.setattr(orchestrator, "_send_cmd", lambda cmd: sent.append(cmd))
+ monkeypatch.setattr(
+ orchestrator,
+ "_stop_dispatcher",
+ lambda: setattr(orchestrator, "_dispatcher_thread", None),
+ )
+
+ responses = queue.Queue()
+
+ def direct_reader(request_id):
+ responses.put({"type": "audio_started", "request_id": request_id})
+ responses.put(
+ {
+ "type": "audio_done",
+ "request_id": request_id,
+ "wav_base64": base64.b64encode(b"RIFFfake").decode("ascii"),
+ "sample_rate": 24000,
+ }
+ )
+ return (
+ lambda *, timeout: responses.get(timeout = timeout),
+ lambda **_kwargs: None,
+ lambda: None,
+ )
+
+ monkeypatch.setattr(orchestrator, "_direct_reader", direct_reader)
+ result = {}
+ thread = threading.Thread(
+ target = lambda: result.setdefault("value", orchestrator.generate_audio_response("hello"))
+ )
+ thread.start()
+
+ deadline = time.monotonic() + 2
+ while not orchestrator._exclusive_tts_pending and time.monotonic() < deadline:
+ time.sleep(0.01)
+ assert orchestrator._exclusive_tts_pending is True
+ assert sent == [], "TTS must not enqueue behind the active compare request"
+
+ with orchestrator._mailbox_lock:
+ orchestrator._mailboxes.pop("compare")
+ thread.join(timeout = 3)
+
+ assert thread.is_alive() is False
+ assert result["value"] == (b"RIFFfake", 24000)
+ assert sent and sent[0]["type"] == "generate_audio"
+ assert orchestrator._exclusive_tts_pending is False
+
+
+def test_tts_cancel_while_waiting_does_not_signal_active_compare(monkeypatch):
+ orchestrator = _bare_orchestrator()
+ orchestrator._dispatcher_thread = _AliveDispatcher()
+ orchestrator._mailboxes["compare"] = queue.Queue()
+ monkeypatch.setattr(orchestrator, "_ensure_subprocess_alive", lambda: True)
+ monkeypatch.setattr(
+ orchestrator,
+ "_send_cmd",
+ lambda _cmd: pytest.fail("cancelled queued TTS must not be sent"),
+ )
+ cancel_calls = []
+ monkeypatch.setattr(orchestrator, "_cancel_generation", lambda: cancel_calls.append(True))
+ caller_cancel = threading.Event()
+ error = {}
+
+ def run():
+ try:
+ orchestrator.generate_audio_response("hello", cancel_event = caller_cancel)
+ except Exception as exc: # noqa: BLE001 - assertion captures the thread result
+ error["value"] = exc
+
+ thread = threading.Thread(target = run)
+ thread.start()
+ deadline = time.monotonic() + 2
+ while not orchestrator._exclusive_tts_pending and time.monotonic() < deadline:
+ time.sleep(0.01)
+ assert orchestrator._exclusive_tts_pending is True
+
+ caller_cancel.set()
+ thread.join(timeout = 2)
+
+ assert thread.is_alive() is False
+ assert "cancel" in str(error["value"]).lower()
+ assert cancel_calls == []
+ assert set(orchestrator._mailboxes) == {"compare"}
+ assert orchestrator._exclusive_tts_pending is False
+
+
+def test_dispatched_generation_rechecks_tts_reservation_before_registration(monkeypatch):
+ orchestrator = _bare_orchestrator()
+ orchestrator._dispatcher_thread = _AliveDispatcher()
+ monkeypatch.setattr(orchestrator, "_ensure_subprocess_alive", lambda: True)
+ monkeypatch.setattr(orchestrator, "_start_dispatcher", lambda: False)
+
+ def reserve_tts(*_args, **_kwargs):
+ orchestrator._exclusive_tts_pending = True
+ return {"type": "generate", "request_id": "compare-1"}
+
+ monkeypatch.setattr(orchestrator, "_build_generate_cmd", reserve_tts)
+ monkeypatch.setattr(
+ orchestrator,
+ "_send_cmd",
+ lambda _cmd: pytest.fail("compare must not enqueue after TTS reservation"),
+ )
+
+ output = list(orchestrator._generate_dispatched(messages = [{"role": "user", "content": "x"}]))
+
+ assert any("audio generation" in str(chunk).lower() for chunk in output)
+ assert orchestrator._mailboxes == {}
+
+
+def test_worker_audio_forwards_shared_cancel_event():
+ cancel = threading.Event()
+ captured = {}
+
+ class _Backend:
+ def generate_audio_response(self, **kwargs):
+ captured.update(kwargs)
+ return b"RIFFfake", 24000
+
+ responses = queue.Queue()
+ _handle_generate_audio(
+ _Backend(),
+ {"request_id": "audio-1", "text": "hello"},
+ responses,
+ cancel,
+ )
+
+ assert captured["cancel_event"] is cancel
+ assert responses.get_nowait()["type"] == "audio_done"
+
+
+def test_backend_tts_generation_uses_cancel_stopping_criteria(monkeypatch):
+ # core.inference.inference pulls the training stack in, which the backend-test job does
+ # not install; without this the whole job fails on ModuleNotFoundError rather than
+ # reporting a skip for a test that cannot run there.
+ pytest.importorskip("peft")
+ from core.inference.inference import InferenceBackend
+
+ backend = InferenceBackend.__new__(InferenceBackend)
+ backend.active_model_name = "tts"
+ backend._generation_lock = threading.Lock()
+ backend.models = {
+ "tts": {
+ "audio_type": "bicodec",
+ "model": object(),
+ "tokenizer": object(),
+ }
+ }
+ criteria = object()
+ monkeypatch.setattr(backend, "_cancel_stopping_criteria", lambda event: criteria)
+ captured = {}
+
+ def _fake_generate(*_args, **kwargs):
+ captured.update(kwargs)
+ return b"RIFFfake", 24000
+
+ monkeypatch.setattr(backend, "_generate_bicodec", _fake_generate)
+ cancel = threading.Event()
+
+ assert backend.generate_audio_response("hello", cancel_event = cancel) == (b"RIFFfake", 24000)
+ assert captured["stopping_criteria"] is criteria
diff --git a/studio/backend/tests/test_audio_unsupported_backend_error.py b/studio/backend/tests/test_audio_unsupported_backend_error.py
new file mode 100644
index 00000000000..8f0494b1555
--- /dev/null
+++ b/studio/backend/tests/test_audio_unsupported_backend_error.py
@@ -0,0 +1,67 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A backend without a TTS path must say so, not "an internal error occurred".
+
+The MLX worker has no text-to-speech branch, so a safetensors Orpheus (what loads on
+Apple Silicon) always fails. ``safe_error_detail`` flattened the message, so the Audio
+page reported an internal error for a model that had loaded fine.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from core.inference.audio_errors import (
+ AUDIO_UNSUPPORTED_CODE,
+ AudioBackendUnsupportedError,
+)
+from utils.utils import safe_error_detail
+
+
+def test_the_capability_message_survives_the_leak_guard():
+ """safe_error_detail is why the reason was lost; the route must bypass it."""
+ error = AudioBackendUnsupportedError(
+ "Text-to-speech is not supported on the MLX backend yet.",
+ hint = "Load this model's GGUF build instead.",
+ )
+ assert safe_error_detail(error) == "An internal error occurred"
+ # What the route sends instead: reason plus the way out, no path, no input.
+ assert "MLX" in error.message
+ assert "GGUF" in error.message
+
+
+def test_the_hint_is_optional():
+ error = AudioBackendUnsupportedError("No TTS on this backend.")
+ assert error.message == "No TTS on this backend."
+ assert error.hint is None
+
+
+def test_it_is_a_runtime_error_so_existing_handlers_still_catch_it():
+ """The generate path catches Exception; narrowing the type must not escape it."""
+ assert issubclass(AudioBackendUnsupportedError, RuntimeError)
+
+
+def test_the_worker_tags_the_payload_with_the_shared_code():
+ """Parent and worker agree on the code, so neither matches on prose."""
+ from pathlib import Path
+
+ worker = Path(__file__).resolve().parents[1] / "core/inference/worker.py"
+ source = worker.read_text(encoding = "utf-8")
+ assert "AUDIO_UNSUPPORTED_CODE" in source
+ # The literal lives in one place only.
+ assert AUDIO_UNSUPPORTED_CODE == "audio_unsupported_backend"
+ assert f'"{AUDIO_UNSUPPORTED_CODE}"' not in source
+
+
+ "code,expected",
+ [(AUDIO_UNSUPPORTED_CODE, True), ("something_else", False), (None, False)],
+)
+def test_only_the_tagged_payload_becomes_the_typed_error(code, expected):
+ """Mirrors the orchestrator's audio_error branch."""
+ resp = {"type": "audio_error", "error": "boom"}
+ if code is not None:
+ resp["code"] = code
+ is_capability = resp.get("code") == AUDIO_UNSUPPORTED_CODE
+ assert is_capability is expected
diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.py
index 02f9aeadc7b..d45656feeec 100644
--- a/studio/backend/tests/test_cached_gguf_routes.py
+++ b/studio/backend/tests/test_cached_gguf_routes.py
@@ -1322,9 +1322,6 @@ def test_is_hidden_model_hides_dictation_models(tmp_path):
def test_list_cached_models_hides_custom_whisper_by_config(monkeypatch, tmp_path):
- # Regression: the legacy /cached-models picker must pass the snapshot path so
- # the config check hides a custom (non-curated) Whisper checkpoint; a bare
- # repo id cannot ("user/whisper-finetune" is not in the curated set).
repo_path = tmp_path / "models--user--whisper-finetune"
snap = repo_path / "snapshots" / "abc"
snap.mkdir(parents = True)
@@ -1355,7 +1352,7 @@ def test_list_cached_models_hides_custom_whisper_by_config(monkeypatch, tmp_path
)
# The route passed the snapshot path (not just the repo id) ...
assert any(str(repo_path) in values for values in captured)
- # ... so the custom Whisper checkpoint is hidden from the chat picker.
+ # ... so the legacy chat inventory keeps hiding the custom checkpoint.
assert result["cached"] == []
diff --git a/studio/backend/tests/test_dataset_preview_audio_cells.py b/studio/backend/tests/test_dataset_preview_audio_cells.py
new file mode 100644
index 00000000000..58d5db2aa73
--- /dev/null
+++ b/studio/backend/tests/test_dataset_preview_audio_cells.py
@@ -0,0 +1,45 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A decoded Audio cell must be summarised, not serialised sample by sample.
+
+The dataset preview compressed the undecoded {"bytes", "path"} shape only. When
+torchcodec cannot load its FFmpeg libraries the soundfile fallback decodes instead,
+and the dataset formatter hands back {"path", "array", "sampling_rate"} with the
+waveform as a plain list. Ten preview rows of a few seconds each then serialised to
+tens of MB of floats, and the client died with "Maximum call stack size exceeded"
+before it could POST /api/train/start.
+"""
+
+from __future__ import annotations
+
+from hub.services.datasets.formatting import _serialize_preview_value
+
+
+def test_a_decoded_audio_cell_collapses_to_a_summary():
+ cell = {"path": "a.wav", "array": [0.0] * 240_000, "sampling_rate": 24_000}
+ out = _serialize_preview_value({"audio": cell})
+ assert out == {"audio": "<audio, 240000 samples @ 24000 Hz, 10.0s>"}
+ assert len(str(out)) < 200
+
+
+def test_the_undecoded_shape_still_reports_bytes():
+ out = _serialize_preview_value({"bytes": b"RIFFxxxx", "path": "a.wav"})
+ assert out == "<binary data, 8 bytes>"
+
+
+def test_a_decoder_object_is_left_to_repr():
+ class _Decoder:
+ def __repr__(self):
+ return "<AudioDecoder>"
+
+ assert _serialize_preview_value({"audio": _Decoder()}) == {"audio": "<AudioDecoder>"}
+
+
+def test_an_ordinary_list_column_is_untouched():
+ assert _serialize_preview_value({"ids": [1, 2, 3]}) == {"ids": [1, 2, 3]}
+
+
+def test_a_missing_rate_does_not_raise():
+ out = _serialize_preview_value({"array": [0.0, 0.1], "sampling_rate": None})
+ assert out.startswith("<audio, 2 samples")
diff --git a/studio/backend/tests/test_gguf_load_cache_reuse.py b/studio/backend/tests/test_gguf_load_cache_reuse.py
index 84cea1d754a..193aaea66eb 100644
--- a/studio/backend/tests/test_gguf_load_cache_reuse.py
+++ b/studio/backend/tests/test_gguf_load_cache_reuse.py
@@ -1026,7 +1026,12 @@ class TestLoadHubDownloadExclusion:
class FakeBackend:
@_with_gguf_load_marker
- def load_model(self, intent):
+ # The marker forwards the scoped cancel event, so a loader must accept it.
+ def load_model(
+ self,
+ intent,
+ load_cancel_event = None,
+ ):
started.set()
release.wait(timeout = 2)
finished.set()
diff --git a/studio/backend/tests/test_gpu_init_crash_message.py b/studio/backend/tests/test_gpu_init_crash_message.py
index 0eab14b266d..79ea1229a00 100644
--- a/studio/backend/tests/test_gpu_init_crash_message.py
+++ b/studio/backend/tests/test_gpu_init_crash_message.py
@@ -1272,7 +1272,8 @@ def test_empty_probe_cpu_recovery_releases_chat_ownership(monkeypatch):
backend = LlamaCppBackend()
backend.matches_load_source = lambda _intent: False
- def _recover_on_cpu(*, intent):
+ # /load now hands the loader its scoped cancel event alongside the intent.
+ def _recover_on_cpu(*, intent, load_cancel_event = None):
backend._gpu_memory_mode = "manual"
backend._gpu_layers = 0
backend._gpu_offload_active = backend._zero_offload_gpu_flag(
diff --git a/studio/backend/tests/test_hf_cache_dangling_refs.py b/studio/backend/tests/test_hf_cache_dangling_refs.py
index e3ea58a52cb..5c748eadd6c 100644
--- a/studio/backend/tests/test_hf_cache_dangling_refs.py
+++ b/studio/backend/tests/test_hf_cache_dangling_refs.py
@@ -769,9 +769,9 @@ def test_a_companion_only_snapshot_is_not_a_gguf_payload(tmp_path, monkeypatch):
assert [row["repo_id"] for row in rows] == ["Org/Model"]
load_dir = Path(rows[0]["load_id"])
variants, _has_vision = list_local_gguf_variants(str(load_dir))
- assert [v.quant for v in variants], (
- f"load_id {load_dir.name[:8]} offers no quant at all; it holds only a " "companion drafter"
- )
+ assert [
+ v.quant for v in variants
+ ], f"load_id {load_dir.name[:8]} offers no quant at all; it holds only a companion drafter"
assert load_dir == repo_dir / "snapshots" / OLDER
@@ -1630,6 +1630,73 @@ def _repo_with(
return repo_dir
+def test_task_inventory_exposes_cached_custom_whisper_as_non_chat_asr(tmp_path, monkeypatch):
+ from types import SimpleNamespace
+
+ from hub.services.models import cache_inventory
+
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ SNAPSHOT: {
+ "config.json": b'{"model_type":"whisper","architectures":["WhisperForConditionalGeneration"]}',
+ "model.safetensors": b"\0" * 256,
+ }
+ },
+ refs = {"main": SNAPSHOT},
+ name = "models--user--speech-finetune",
+ )
+ monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda: [tmp_path])
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = tmp_path),
+ )
+ inventory_scan.invalidate_hf_cache_scans()
+ try:
+ rows = cache_inventory._scan_cached_models()
+ finally:
+ inventory_scan.invalidate_hf_cache_scans()
+ assert len(rows) == 1
+ assert rows[0]["task"] == "automatic-speech-recognition"
+ assert rows[0]["pipeline_tag"] == "automatic-speech-recognition"
+ assert rows[0]["library_name"] == "transformers"
+ assert "whisper" in rows[0]["tags"]
+ assert rows[0]["capabilities"]["can_chat"] is False
+
+
+def test_task_inventory_preserves_cached_community_tts_pipeline(tmp_path, monkeypatch):
+ from types import SimpleNamespace
+
+ from hub.services.models import cache_inventory
+
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ SNAPSHOT: {
+ "config.json": b'{"model_type":"llama"}',
+ "model.safetensors": b"\0" * 256,
+ "README.md": b"---\npipeline_tag: text-to-speech\nlibrary_name: transformers\n---\n",
+ }
+ },
+ refs = {"main": SNAPSHOT},
+ name = "models--community--orpheus-tts",
+ )
+ monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda: [tmp_path])
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = tmp_path),
+ )
+ inventory_scan.invalidate_hf_cache_scans()
+ try:
+ rows = cache_inventory._scan_cached_models()
+ finally:
+ inventory_scan.invalidate_hf_cache_scans()
+
+ assert len(rows) == 1
+ assert rows[0]["task"] == "text-to-speech"
+ assert rows[0]["pipeline_tag"] == "text-to-speech"
+
+
def test_a_secondary_dangling_ref_still_judges_the_recovered_snapshot(tmp_path, monkeypatch):
"""refs/main resolves while refs/stale dangles, so recovery fires but the default-ref test does
not. The pinned snapshot is short a shard with no marker, manifest or .incomplete blob, so its
diff --git a/studio/backend/tests/test_middleware.py b/studio/backend/tests/test_middleware.py
index 768c9e66de8..eae20587c8e 100644
--- a/studio/backend/tests/test_middleware.py
+++ b/studio/backend/tests/test_middleware.py
@@ -114,9 +114,7 @@ class TestMaxBodyMiddleware:
app = _make_protected_app(
4096,
main_module,
- request_max_bytes_getter = lambda path: (
- 128 if path.endswith("/transcribe/raw") else 4096
- ),
+ request_max_bytes_getter = lambda path: 128 if path.endswith("/transcribe/raw") else 4096,
)
c = TestClient(app)
@@ -137,7 +135,9 @@ class TestMaxBodyMiddleware:
from utils.upload_limits import (
STT_AUDIO_JSON_MAX_BYTES,
STT_AUDIO_RAW_MAX_BYTES,
+ upload_request_limit_bytes,
)
+
assert (
main_module._get_request_body_max_bytes("/api/inference/audio/transcribe/raw")
== STT_AUDIO_RAW_MAX_BYTES
@@ -146,6 +146,18 @@ class TestMaxBodyMiddleware:
main_module._get_request_body_max_bytes("/api/inference/audio/transcribe")
== STT_AUDIO_JSON_MAX_BYTES
)
+ # The OpenAI transcriptions route is multipart, so it gets headroom over the raw cap, on both mounts.
+ for path in ("/v1/audio/transcriptions", "/api/inference/audio/transcriptions"):
+ assert main_module._get_request_body_max_bytes(path) == upload_request_limit_bytes(
+ STT_AUDIO_RAW_MAX_BYTES
+ ), path
+ assert path in main_module._BODY_UPLOAD_PASSTHROUGH_EXACT_PATHS, path
+ assert main_module._get_upload_passthrough_request_max_bytes(path) == (
+ upload_request_limit_bytes(STT_AUDIO_RAW_MAX_BYTES)
+ ), path
+ assert main_module._get_upload_passthrough_request_max_bytes(path + "/") == (
+ upload_request_limit_bytes(STT_AUDIO_RAW_MAX_BYTES)
+ ), path
def test_settings_put_body_over_cap_rejected(self, main_module):
app = _make_protected_app(1024, main_module)
@@ -301,6 +313,8 @@ class TestMaxBodyMiddleware:
for path in (
"/v1/images/generations",
"/v1/audio/generate",
+ "/v1/audio/speech",
+ "/v1/audio/transcriptions",
"/v1/embeddings",
"/v1/responses",
"/v1/messages",
@@ -839,6 +853,11 @@ def health_app(tmp_path, monkeypatch):
import main as _main
+ # This fixture exercises bearer redaction, not hardware startup. Keep the
+ # payload settled even on macOS while MLX self-repair holds the live verdict.
+ # (chat_only, chat_only_reason, chat_only_detail): health_check reads all three, so a
+ # two-tuple here raised IndexError once main added the detail field.
+ monkeypatch.setattr(_main, "_hardware_snapshot", lambda: (False, None, None))
app = FastAPI()
app.add_api_route("/api/health", _main.health_check, methods = ["GET"])
diff --git a/studio/backend/tests/test_model_update_robustness.py b/studio/backend/tests/test_model_update_robustness.py
index d84f8c94a70..4c0baf984d2 100644
--- a/studio/backend/tests/test_model_update_robustness.py
+++ b/studio/backend/tests/test_model_update_robustness.py
@@ -400,7 +400,9 @@ def test_cached_gguf_scan_keeps_download_timestamp(monkeypatch, tmp_path):
assert rows[0]["last_modified"] == 5_000.0
-def test_cached_model_scan_hides_custom_whisper_repo(monkeypatch, tmp_path):
+def test_cached_model_scan_surfaces_custom_whisper_repo_as_asr(monkeypatch, tmp_path):
+ """The Audio page manages STT downloads off the same inventory, so a cached Whisper repo
+ is emitted as an ASR row. Chat never offers it: the row carries can_chat False."""
repo_path = tmp_path / "models--Org--CustomWhisper"
snapshot = repo_path / "snapshots" / ("a" * 40)
snapshot.mkdir(parents = True)
@@ -444,7 +446,10 @@ def test_cached_model_scan_hides_custom_whisper_repo(monkeypatch, tmp_path):
lambda *args, **kwargs: False,
)
- assert CI._scan_cached_models() == []
+ rows = CI._scan_cached_models()
+ assert [row["repo_id"] for row in rows] == ["Org/CustomWhisper"]
+ assert rows[0]["task"] == "automatic-speech-recognition"
+ assert rows[0]["capabilities"]["can_chat"] is False
# ── hf_hub_download_with_xet_fallback force_download bypass (X2/F2) ───
diff --git a/studio/backend/tests/test_models_get_model_config_case_resolution.py b/studio/backend/tests/test_models_get_model_config_case_resolution.py
index 2227a0af15d..d586bbe78b1 100644
--- a/studio/backend/tests/test_models_get_model_config_case_resolution.py
+++ b/studio/backend/tests/test_models_get_model_config_case_resolution.py
@@ -53,7 +53,7 @@ def test_get_model_config_resolves_cached_case_before_model_checks(monkeypatch):
local_files_only = False,
):
calls["detect_audio_type"] = model_name
- return None
+ return None, True
def _record_from_identifier(
cls,
@@ -72,7 +72,7 @@ def test_get_model_config_resolves_cached_case_before_model_checks(monkeypatch):
monkeypatch.setattr(models_route, "load_model_defaults", _record_load)
monkeypatch.setattr(models_route, "is_vision_model", _record_vision)
monkeypatch.setattr(models_route, "is_embedding_model", _record_embedding)
- monkeypatch.setattr(model_config_module, "detect_audio_type", _record_audio)
+ monkeypatch.setattr(model_config_module, "detect_audio_type_checked", _record_audio)
monkeypatch.setattr(
models_route.ModelConfig,
"from_identifier",
diff --git a/studio/backend/tests/test_openai_audio_speech_route.py b/studio/backend/tests/test_openai_audio_speech_route.py
new file mode 100644
index 00000000000..85277f3bedf
--- /dev/null
+++ b/studio/backend/tests/test_openai_audio_speech_route.py
@@ -0,0 +1,312 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""FastAPI round-trip tests for the OpenAI-compatible POST /v1/audio/speech.
+
+The TTS core (_generate_tts_wav) is faked, so these cover route wiring, validation,
+gallery persistence and the raw-WAV response without torch, weights or a GPU."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+from fastapi import FastAPI, HTTPException
+from fastapi.testclient import TestClient
+
+import core.inference.audio_gallery as gallery_module
+import routes.inference as routes_module
+from auth.authentication import get_current_subject
+from routes.inference import router
+from utils.api_errors import install_api_error_handlers
+
+_WAV = b"RIFF\x24\x00\x00\x00WAVEfmt fake-payload"
+
+
+def _make_client(monkeypatch, generate = None):
+ calls = []
+
+ async def _fake_generate(text, payload, request, current_subject):
+ calls.append({"text": text, "payload": payload})
+ if generate is not None:
+ return await generate(text)
+ return _WAV, 24000, "unsloth/orpheus-3b-0.1-ft", "snac"
+
+ saved = []
+
+ def _save(wav_bytes, meta):
+ saved.append({"bytes": wav_bytes, "meta": meta})
+ return {**meta, "id": "aud0", "url": "/api/inference/audio/gallery/aud0/file"}
+
+ monkeypatch.setattr(routes_module, "_generate_tts_wav", _fake_generate)
+ monkeypatch.setattr(gallery_module, "save", _save)
+
+ app = FastAPI()
+ install_api_error_handlers(app)
+ app.include_router(router, prefix = "/v1")
+ app.dependency_overrides[get_current_subject] = lambda: "test-user"
+ return TestClient(app), calls, saved
+
+
+def test_returns_raw_wav_bytes(monkeypatch):
+ cli, calls, saved = _make_client(monkeypatch)
+ resp = cli.post("/v1/audio/speech", json = {"input": "hello sloth"})
+ assert resp.status_code == 200
+ assert resp.headers["content-type"].startswith("audio/wav")
+ assert resp.content == _WAV
+ assert calls[0]["text"] == "hello sloth"
+
+
+def test_persists_clip_to_gallery(monkeypatch):
+ cli, calls, saved = _make_client(monkeypatch)
+ resp = cli.post("/v1/audio/speech", json = {"input": "persist me"})
+ assert resp.status_code == 200
+ assert len(saved) == 1
+ meta = saved[0]["meta"]
+ assert meta["prompt"] == "persist me"
+ assert meta["model"] == "unsloth/orpheus-3b-0.1-ft"
+ assert meta["audio_type"] == "snac"
+ assert meta["sample_rate"] == 24000
+ assert isinstance(meta["duration_s"], float)
+ assert meta["created_at"]
+
+
+def test_gallery_persist_failure_still_serves_audio(monkeypatch):
+ # Persistence is best-effort: a full disk must not fail the request that produced the audio.
+ cli, calls, saved = _make_client(monkeypatch)
+
+ def _boom(wav_bytes, meta):
+ raise OSError("disk full")
+
+ monkeypatch.setattr(gallery_module, "save", _boom)
+ resp = cli.post("/v1/audio/speech", json = {"input": "still speaks"})
+ assert resp.status_code == 200
+ assert resp.content == _WAV
+
+
+def test_voice_and_speed_accepted_and_ignored(monkeypatch):
+ cli, calls, saved = _make_client(monkeypatch)
+ resp = cli.post(
+ "/v1/audio/speech",
+ json = {"input": "hi", "voice": "alloy", "speed": 1.25, "model": "tts-1"},
+ )
+ assert resp.status_code == 200
+
+
+def test_non_wav_response_format_is_400(monkeypatch):
+ cli, calls, saved = _make_client(monkeypatch)
+ resp = cli.post("/v1/audio/speech", json = {"input": "hi", "response_format": "mp3"})
+ assert resp.status_code == 400
+ assert "mp3" in resp.json()["error"]["message"]
+ assert calls == [] # rejected before any generation
+
+
+def test_null_response_format_means_wav(monkeypatch):
+ cli, calls, saved = _make_client(monkeypatch)
+ resp = cli.post("/v1/audio/speech", json = {"input": "hi", "response_format": None})
+ assert resp.status_code == 200
+
+
+def test_empty_input_is_rejected(monkeypatch):
+ # install_api_error_handlers maps validation errors to a 400 OpenAI envelope on /v1.
+ cli, calls, saved = _make_client(monkeypatch)
+ resp = cli.post("/v1/audio/speech", json = {"input": ""})
+ assert resp.status_code == 400
+ assert calls == []
+
+
+def test_core_error_propagates(monkeypatch):
+ # "No model loaded" from the TTS core keeps its status through the route.
+ async def _no_model(text):
+ raise HTTPException(status_code = 400, detail = "No model loaded.")
+
+ cli, calls, saved = _make_client(monkeypatch, generate = _no_model)
+ resp = cli.post("/v1/audio/speech", json = {"input": "hi"})
+ assert resp.status_code == 400
+ assert saved == []
+
+
+def test_wav_duration_seconds_reads_header():
+ # A real 1-second 24 kHz mono WAV reports ~1.0s.
+ import io
+ import wave
+
+ buf = io.BytesIO()
+ with wave.open(buf, "wb") as out:
+ out.setnchannels(1)
+ out.setsampwidth(2)
+ out.setframerate(24000)
+ out.writeframes(b"\x00\x00" * 24000)
+ assert routes_module._wav_duration_seconds(buf.getvalue(), 24000) == 1.0
+ # Unreadable bytes fall back to the 16-bit mono PCM estimate.
+ fallback = routes_module._wav_duration_seconds(b"\x00" * (44 + 48000), 24000)
+ assert fallback == 1.0
+
+
+def test_the_speech_route_asks_for_the_full_audio_token_budget(monkeypatch):
+ """CreateSpeech has no field for it, so the chat default of 2048 silently truncated
+ any input past roughly half a minute and still returned HTTP 200 with a short WAV."""
+ from core.inference.orchestrator import AUDIO_GENERATION_MAX_TOKENS
+
+ cli, calls, _saved = _make_client(monkeypatch)
+ monkeypatch.setattr(routes_module, "_monitor_context_length", lambda: None)
+ assert cli.post("/v1/audio/speech", json = {"input": "a long script"}).status_code == 200
+ payload = calls[0]["payload"]
+ assert payload.max_tokens == AUDIO_GENERATION_MAX_TOKENS
+
+
+def test_the_budget_leaves_room_for_the_prompt(monkeypatch):
+ """The cap now lives in _tts_max_new_tokens, which both TTS routes share, rather than
+ being computed at the speech route. Exercised directly since the route tests fake the
+ shared core that applies it."""
+ from core.inference.orchestrator import AUDIO_GENERATION_MAX_TOKENS
+ from models.inference import ChatCompletionRequest
+
+ monkeypatch.setattr(routes_module, "_monitor_context_length", lambda: 2048)
+ payload = ChatCompletionRequest(
+ messages = [{"role": "user", "content": "x"}],
+ max_tokens = AUDIO_GENERATION_MAX_TOKENS,
+ )
+ text = "x" * 300
+
+ budget = routes_module._tts_max_new_tokens(payload, text)
+
+ assert budget < 2048
+ # Minus the codec wrapper too: the backends generate from a formatted prompt, not the
+ # raw text, so budgeting the whole remainder left the few delimiter tokens to overflow.
+ assert budget == (
+ 2048 - routes_module._prompt_token_estimate(text) - routes_module._TTS_PROMPT_FORMAT_RESERVE
+ )
+
+
+def test_an_over_context_prompt_is_a_client_error(monkeypatch):
+ """Flooring at one token forwarded the whole over-context prompt anyway and failed deep
+ in generation. Both routes share this guard through _generate_tts_wav."""
+ from fastapi import HTTPException
+
+ monkeypatch.setattr(routes_module, "_monitor_context_length", lambda: 2048)
+
+ with pytest.raises(HTTPException) as excinfo:
+ routes_module._raise_if_prompt_leaves_no_speech_budget("x" * 8000)
+
+ assert excinfo.value.status_code == 400
+ assert "too long" in str(excinfo.value.detail).lower()
+ # A normal line is untouched.
+ routes_module._raise_if_prompt_leaves_no_speech_budget("A short line.")
+
+
+def test_the_shared_core_guards_before_generating():
+ """Wired in _generate_tts_wav so /audio/generate inherits it, not only /audio/speech."""
+ import inspect
+
+ source = inspect.getsource(routes_module._generate_tts_wav)
+ assert "_raise_if_prompt_leaves_no_speech_budget(text)" in source
+
+
+def test_the_budget_is_rechecked_after_an_idle_model_is_restored():
+ """With nothing loaded there is no context to measure, so the guard passes everything.
+ Idle auto-unload leaves exactly that state, and the restore below it brings the context
+ back, so the first request after an eviction reached generation over-context and came
+ back as a one-token clip."""
+ import inspect
+
+ source = inspect.getsource(routes_module._generate_tts_wav)
+ guards = [
+ i
+ for i, line in enumerate(source.splitlines())
+ if "_raise_if_prompt_leaves_no_speech_budget(text)" in line
+ ]
+ restore = next(
+ i
+ for i, line in enumerate(source.splitlines())
+ if "_maybe_auto_switch_model(_RELOAD_ONLY_MODEL" in line
+ )
+ assert len(guards) == 2, "one check before the restore, one after"
+ assert guards[0] < restore < guards[1]
+
+
+def test_the_gallery_is_bounded_so_an_api_client_cannot_fill_the_disk(monkeypatch, tmp_path):
+ import core.inference.audio_gallery as gallery
+
+ monkeypatch.setattr(gallery, "gallery_dir", lambda: tmp_path)
+ monkeypatch.setenv("UNSLOTH_AUDIO_GALLERY_MAX_CLIPS", "3")
+ meta = {
+ "prompt": "p",
+ "model": "m",
+ "audio_type": "snac",
+ "sample_rate": 24000,
+ "duration_s": 0.1,
+ "created_at": "2026-01-01T00:00:00Z",
+ }
+ ids = [gallery.save(b"RIFFfake", meta)["id"] for _ in range(6)]
+
+ remaining = {clip["id"] for clip in gallery.list_audio()}
+ assert len(remaining) == 3
+ # Newest kept, oldest dropped.
+ assert set(ids[-3:]) == remaining
+
+
+def test_the_gallery_is_bounded_by_bytes_not_only_by_count(monkeypatch, tmp_path):
+ """A count alone does not bound the disk: 2000 clips of maximum-length speech is tens
+ of gigabytes, and stopping /v1/audio/speech filling the disk is what the cap is for."""
+ import core.inference.audio_gallery as gallery
+
+ monkeypatch.setattr(gallery, "gallery_dir", lambda: tmp_path)
+ monkeypatch.setenv("UNSLOTH_AUDIO_GALLERY_MAX_CLIPS", "1000")
+ monkeypatch.setenv("UNSLOTH_AUDIO_GALLERY_MAX_BYTES", str(4 * 1024))
+ meta = {
+ "prompt": "p",
+ "model": "m",
+ "audio_type": "snac",
+ "sample_rate": 24000,
+ "duration_s": 0.1,
+ "created_at": "2026-01-01T00:00:00Z",
+ }
+ ids = [gallery.save(b"R" * 1024, meta)["id"] for _ in range(10)]
+
+ remaining = [clip["id"] for clip in gallery.list_audio()]
+ assert len(remaining) == 4, remaining
+ assert set(ids[-4:]) == set(remaining)
+
+
+def test_one_oversized_clip_is_still_returned_rather_than_pruned_immediately(monkeypatch, tmp_path):
+ """The newest clip is the one the caller just generated. Pruning it because it alone
+ exceeds the quota would read as a silent failure."""
+ import core.inference.audio_gallery as gallery
+
+ monkeypatch.setattr(gallery, "gallery_dir", lambda: tmp_path)
+ monkeypatch.setenv("UNSLOTH_AUDIO_GALLERY_MAX_BYTES", "64")
+ meta = {
+ "prompt": "p",
+ "model": "m",
+ "audio_type": "snac",
+ "sample_rate": 24000,
+ "duration_s": 0.1,
+ "created_at": "2026-01-01T00:00:00Z",
+ }
+ saved = gallery.save(b"R" * 4096, meta)
+
+ assert [clip["id"] for clip in gallery.list_audio()] == [saved["id"]]
+
+
+def test_non_latin_prompts_are_not_billed_at_the_latin_rate():
+ """Without a Python tokenizer (GGUF TTS), the estimate is by character class. Cutting
+ at U+2E7F caught CJK and emoji but billed Arabic, Cyrillic, Hebrew and the Indic
+ scripts at a third of a token each, so a long prompt in any of them passed the guard
+ and then overflowed the loaded context during generation."""
+ estimate = routes_module._prompt_token_estimate
+
+ for label, text in (
+ ("arabic", "مرحبا بالعالم " * 40),
+ ("cyrillic", "Привет мир " * 40),
+ ("hebrew", "שלום עולם " * 40),
+ ("devanagari", "नमस्ते दुनिया " * 40),
+ ):
+ assert estimate(text) >= len(text.replace(" ", "")), label
+
+ # Latin is still counted at the cheaper rate, so ordinary English is not rejected.
+ english = "the quick brown fox jumps over the lazy dog " * 40
+ assert estimate(english) < len(english) // 2
+
+ # And CJK, which already worked, is unchanged.
+ assert estimate("你好世界" * 50) >= 200
diff --git a/studio/backend/tests/test_openai_audio_transcriptions_route.py b/studio/backend/tests/test_openai_audio_transcriptions_route.py
new file mode 100644
index 00000000000..c3fbc625112
--- /dev/null
+++ b/studio/backend/tests/test_openai_audio_transcriptions_route.py
@@ -0,0 +1,171 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""FastAPI round-trip tests for the OpenAI-compatible POST /v1/audio/transcriptions.
+
+The sidecar call (_transcribe_audio_result) is faked, so these cover multipart wiring,
+model-id mapping, response formats and error propagation without whisper or a GPU."""
+
+from __future__ import annotations
+
+import pytest
+from fastapi import FastAPI, HTTPException
+from fastapi.testclient import TestClient
+
+import routes.inference as routes_module
+from auth.authentication import get_current_subject
+from routes.inference import router
+from utils.api_errors import install_api_error_handlers
+
+
+def _make_client(monkeypatch, transcribe = None):
+ calls = []
+
+ async def _fake_transcribe(
+ raw,
+ model,
+ language,
+ fast,
+ engine = None,
+ request = None,
+ ):
+ calls.append(
+ {
+ "raw": raw,
+ "model": model,
+ "language": language,
+ "fast": fast,
+ "engine": engine,
+ "request": request,
+ }
+ )
+ if transcribe is not None:
+ return await transcribe(raw)
+ return {"text": "hello sloth", "language": "en", "duration": 1.2, "model": "small"}
+
+ monkeypatch.setattr(routes_module, "_transcribe_audio_result", _fake_transcribe)
+
+ app = FastAPI()
+ install_api_error_handlers(app)
+ app.include_router(router, prefix = "/v1")
+ app.dependency_overrides[get_current_subject] = lambda: "test-user"
+ return TestClient(app), calls
+
+
+def _post(
+ cli,
+ data = None,
+ filename = "clip.wav",
+ content = b"RIFFfake",
+):
+ return cli.post(
+ "/v1/audio/transcriptions",
+ files = {"file": (filename, content, "audio/wav")},
+ data = data or {},
+ )
+
+
+def test_json_response_is_text_only(monkeypatch):
+ # OpenAI's json shape carries only the text; the sidecar's extra fields stay internal.
+ cli, calls = _make_client(monkeypatch)
+ resp = _post(cli)
+ assert resp.status_code == 200
+ assert resp.json() == {"text": "hello sloth"}
+ assert calls[0]["raw"] == b"RIFFfake"
+ assert calls[0]["fast"] is False
+ assert calls[0]["request"] is not None
+
+
+def test_text_response_is_plain_body(monkeypatch):
+ cli, calls = _make_client(monkeypatch)
+ resp = _post(cli, data = {"response_format": "text"})
+ assert resp.status_code == 200
+ assert resp.headers["content-type"].startswith("text/plain")
+ assert resp.text == "hello sloth"
+
+
+def test_whisper1_and_missing_model_map_to_sidecar_default(monkeypatch):
+ cli, calls = _make_client(monkeypatch)
+ assert _post(cli, data = {"model": "whisper-1"}).status_code == 200
+ assert _post(cli).status_code == 200
+ assert [c["model"] for c in calls] == [None, None]
+
+
+def test_explicit_model_passes_through(monkeypatch):
+ cli, calls = _make_client(monkeypatch)
+ resp = _post(cli, data = {"model": "large-v3-turbo", "language": "de"})
+ assert resp.status_code == 200
+ assert calls[0]["model"] == "large-v3-turbo"
+ assert calls[0]["language"] == "de"
+
+
+def test_unknown_response_format_is_400(monkeypatch):
+ cli, calls = _make_client(monkeypatch)
+ resp = _post(cli, data = {"response_format": "srt"})
+ assert resp.status_code == 400
+ assert "srt" in resp.json()["error"]["message"]
+ assert calls == []
+
+
+def test_missing_file_is_rejected(monkeypatch):
+ # install_api_error_handlers maps validation errors to a 400 OpenAI envelope on /v1.
+ cli, calls = _make_client(monkeypatch)
+ resp = cli.post("/v1/audio/transcriptions", data = {"model": "whisper-1"})
+ assert resp.status_code == 400
+ assert calls == []
+
+
+def test_sidecar_errors_keep_their_status(monkeypatch):
+ # The shared error mapping (SttModelIdError -> 422, empty audio -> 400, ...) sits inside
+ # _transcribe_audio_result; the route must not swallow or rewrap what it raises.
+ async def _bad_model(raw):
+ raise HTTPException(status_code = 422, detail = "Unknown STT model id.")
+
+ cli, calls = _make_client(monkeypatch, transcribe = _bad_model)
+ resp = _post(cli, data = {"model": "not-a-model"})
+ assert resp.status_code == 422
+ assert "Unknown STT model id." in resp.json()["error"]["message"]
+
+
+def test_an_mtmd_only_model_forces_its_engine():
+ """Qwen3-ASR only runs on the mtmd sidecar.
+
+ The route passed no engine, so _resolve_stt_engine defaulted to Transformers and the
+ Whisper sidecar rejected the model.
+ """
+ from routes.inference import _stt_engine_for_model
+
+ assert _stt_engine_for_model("qwen3-asr-0.6b") == "mtmd"
+ assert _stt_engine_for_model("qwen3-asr-1.7b") == "mtmd"
+
+
+def test_whisper_ids_keep_the_default_engine():
+ """Whisper ids are shared with the Transformers sidecar, so nothing is forced."""
+ from routes.inference import _stt_engine_for_model
+ for model in (None, "", "whisper-1", "small", "large-v3-turbo", "openai/whisper-tiny"):
+ assert _stt_engine_for_model(model) is None, model
+
+
+def test_the_studio_json_route_also_forwards_the_request(monkeypatch):
+ """The raw and OpenAI routes always passed the request; the base64 JSON route did not,
+ so a client that goes away left the sidecar transcribing under its lock."""
+ import base64
+
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+ from routes.inference import studio_router
+
+ cli, calls = _make_client(monkeypatch)
+ app = FastAPI()
+ install_api_error_handlers(app)
+ app.include_router(studio_router)
+ app.dependency_overrides[get_current_subject] = lambda: "test-user"
+ cli = TestClient(app)
+ resp = cli.post(
+ "/audio/transcribe",
+ json = {"audio": base64.b64encode(b"RIFFfake").decode()},
+ )
+ assert resp.status_code == 200
+ assert calls[0]["raw"] == b"RIFFfake"
+ assert calls[0]["request"] is not None
diff --git a/studio/backend/tests/test_openai_audio_upload_bound.py b/studio/backend/tests/test_openai_audio_upload_bound.py
new file mode 100644
index 00000000000..68de04d5e7c
--- /dev/null
+++ b/studio/backend/tests/test_openai_audio_upload_bound.py
@@ -0,0 +1,35 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+"""The multipart transcription route must not materialize an unbounded upload."""
+
+import asyncio
+
+import pytest
+from fastapi import HTTPException
+
+import routes.inference as inference_route
+
+
+def test_openai_transcription_reads_only_one_byte_past_limit(monkeypatch):
+ sizes = []
+
+ class _Upload:
+ async def read(self, size = -1):
+ sizes.append(size)
+ return b"x" * size
+
+ monkeypatch.setattr(inference_route, "_MAX_AUDIO_RAW_BYTES", 4)
+
+ with pytest.raises(HTTPException) as exc:
+ asyncio.run(
+ inference_route.openai_audio_transcriptions(
+ request = None,
+ file = _Upload(),
+ model = None,
+ language = None,
+ response_format = "json",
+ current_subject = "tester",
+ )
+ )
+
+ assert sizes == [5]
+ assert exc.value.status_code == 413
diff --git a/studio/backend/tests/test_orchestrator_unload_cancel.py b/studio/backend/tests/test_orchestrator_unload_cancel.py
index 54f6f2bde99..22e35a87d4e 100644
--- a/studio/backend/tests/test_orchestrator_unload_cancel.py
+++ b/studio/backend/tests/test_orchestrator_unload_cancel.py
@@ -32,6 +32,7 @@ def _bare_orchestrator():
o._dispatcher_stop = threading.Event()
o._dispatcher_lifecycle_lock = threading.Lock()
o._unload_pending = False
+ o._exclusive_tts_pending = False
o.active_model_name = "m"
o.models = {"m": {}}
o.loading_models = set()
@@ -349,14 +350,16 @@ def test_worker_drain_skip_emits_cancelled_gen_done_when_draining():
def test_worker_generate_branches_check_drain_before_clearing_cancel():
# Guarded branches check the drain skip before clearing cancel_event and
- # again after, so a queued command can't erase an unload's cancel. Three
- # today: MLX generate + generate_audio_input, and GPU generate.
+ # again after, so a queued command can't erase an unload's cancel. Four
+ # today: MLX generate + generate_audio_input, GPU generate, and GPU TTS.
import inspect
from core.inference import worker
src = inspect.getsource(worker.run_inference_process)
- assert src.count("_drain_skip_generate(cmd, resp_queue, drain_event)") == 6
+ audio_prepare = inspect.getsource(worker._prepare_generate_audio)
+ assert src.count("_drain_skip_generate(cmd, resp_queue, drain_event") == 6
+ assert audio_prepare.count("_drain_skip_generate(cmd, resp_queue, drain_event") == 2
def test_worker_generate_rechecks_drain_after_clearing_cancel():
@@ -762,6 +765,319 @@ def test_unload_route_cancels_in_flight_load_without_waiting_on_gate(monkeypatch
asyncio.run(scenario())
+def test_scoped_unload_cancels_only_its_running_standard_load(monkeypatch):
+ import asyncio
+
+ import routes.inference as inference_route
+ from models.inference import LoadRequest, UnloadRequest
+
+ cancelled = []
+
+ class _Backend:
+ def get_loading_model(self):
+ return "m"
+
+ def cancel_load(self, name):
+ cancelled.append(name)
+ return True
+
+ class _Llama:
+ is_active = False
+ is_loaded = False
+ model_identifier = None
+
+ monkeypatch.setattr(inference_route, "get_inference_backend", lambda: _Backend())
+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: _Llama())
+ attempt = inference_route._begin_load_attempt(
+ LoadRequest(model_path = "m", load_request_id = "audio-load-1"), "tester"
+ )
+ with inference_route._scoped_load_attempts_lock:
+ inference_route._running_load_attempt = attempt
+ try:
+ response = asyncio.run(
+ inference_route._unload_model_impl(
+ UnloadRequest(model_path = "m", cancel_load_request_id = "audio-load-1"),
+ "tester",
+ )
+ )
+ assert response.status == "unloaded"
+ assert cancelled == ["m"]
+ assert attempt.cancel_event.is_set()
+ finally:
+ with inference_route._scoped_load_attempts_lock:
+ inference_route._running_load_attempt = None
+ inference_route._finish_load_attempt(attempt)
+
+
+def test_scoped_unload_cannot_cancel_a_newer_same_model_load(monkeypatch):
+ import asyncio
+
+ import routes.inference as inference_route
+ from models.inference import LoadRequest, UnloadRequest
+
+ def _unexpected_backend():
+ pytest.fail("a stale scoped cancel must not inspect or mutate any backend")
+
+ monkeypatch.setattr(inference_route, "get_inference_backend", _unexpected_backend)
+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", _unexpected_backend)
+ newer = inference_route._begin_load_attempt(
+ LoadRequest(model_path = "m", load_request_id = "audio-load-new"), "tester"
+ )
+ with inference_route._scoped_load_attempts_lock:
+ inference_route._running_load_attempt = newer
+ try:
+ response = asyncio.run(
+ inference_route._unload_model_impl(
+ UnloadRequest(model_path = "m", cancel_load_request_id = "audio-load-old"),
+ "tester",
+ )
+ )
+ assert response.status == "unloaded"
+ assert not newer.cancel_event.is_set()
+ finally:
+ with inference_route._scoped_load_attempts_lock:
+ inference_route._running_load_attempt = None
+ inference_route._finish_load_attempt(newer)
+
+
+def test_scoped_cancel_before_load_registration_is_consumed(monkeypatch):
+ import asyncio
+
+ import routes.inference as inference_route
+ from fastapi import HTTPException
+ from models.inference import LoadRequest, UnloadRequest
+
+ def _unexpected_backend():
+ pytest.fail("cancel-first cleanup must not inspect a backend")
+
+ async def _unexpected_load(*_args, **_kwargs):
+ pytest.fail("a tombstoned load must not reach the load implementation")
+
+ monkeypatch.setattr(inference_route, "get_inference_backend", _unexpected_backend)
+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", _unexpected_backend)
+ monkeypatch.setattr(inference_route, "_load_model_impl", _unexpected_load)
+ response = asyncio.run(
+ inference_route._unload_model_impl(
+ UnloadRequest(model_path = "m", cancel_load_request_id = "audio-cancel-first"),
+ "tester",
+ )
+ )
+ assert response.status == "unloaded"
+
+ request = LoadRequest(model_path = "m", load_request_id = "audio-cancel-first")
+ attempt = inference_route._begin_load_attempt(request, "tester")
+ try:
+ assert attempt.cancel_event.is_set()
+ assert attempt.cancel_complete.is_set()
+ with pytest.raises(HTTPException, match = "cancelled"):
+ asyncio.run(
+ inference_route._run_tracked_load_model_impl(
+ request, object(), "tester", attempt = attempt
+ )
+ )
+ finally:
+ inference_route._finish_load_attempt(attempt)
+
+
+def test_scoped_cancel_holds_load_ownership_until_backend_cancel_finishes(monkeypatch):
+ import asyncio
+
+ import routes.inference as inference_route
+ from core.inference import llama_keepwarm
+ from fastapi import HTTPException
+ from models.inference import LoadRequest, UnloadRequest
+
+ backend_cancel_entered = threading.Event()
+ release_backend_cancel = threading.Event()
+
+ class _Backend:
+ def get_loading_model(self):
+ return None
+
+ class _Llama:
+ is_active = False
+ is_loaded = False
+ model_identifier = None
+
+ def _get_backend():
+ backend_cancel_entered.set()
+ assert release_backend_cancel.wait(timeout = 5)
+ return _Backend()
+
+ monkeypatch.setattr(inference_route, "get_inference_backend", _get_backend)
+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: _Llama())
+ monkeypatch.setattr(inference_route, "_raise_if_sidecar_swap_in_progress", lambda: None)
+
+ async def scenario():
+ gate = asyncio.Lock()
+ first_started = asyncio.Event()
+ second_started = asyncio.Event()
+
+ class _Gate:
+ async def __aenter__(self):
+ await gate.acquire()
+
+ async def __aexit__(self, *_args):
+ gate.release()
+
+ monkeypatch.setattr(llama_keepwarm, "inference_lifecycle_gate", lambda: _Gate())
+
+ async def _fake_load(
+ request,
+ *_args,
+ load_cancel_event = None,
+ **_kwargs,
+ ):
+ if request.load_request_id == "audio-race-a":
+ first_started.set()
+ await asyncio.to_thread(load_cancel_event.wait)
+ raise HTTPException(status_code = 409, detail = "Model load cancelled")
+ second_started.set()
+ return {"status": "loaded", "model": request.model_path}
+
+ monkeypatch.setattr(inference_route, "_load_model_impl", _fake_load)
+ first = asyncio.create_task(
+ inference_route.load_model_gated(
+ LoadRequest(model_path = "m", load_request_id = "audio-race-a"),
+ object(),
+ "tester",
+ )
+ )
+ await first_started.wait()
+ cancel = asyncio.create_task(
+ inference_route._unload_model_impl(
+ UnloadRequest(model_path = "m", cancel_load_request_id = "audio-race-a"),
+ "tester",
+ )
+ )
+ await asyncio.to_thread(backend_cancel_entered.wait, 5)
+
+ second = asyncio.create_task(
+ inference_route.load_model_gated(
+ LoadRequest(model_path = "m", load_request_id = "audio-race-b"),
+ object(),
+ "tester",
+ )
+ )
+ await asyncio.sleep(0.05)
+ assert not second_started.is_set(), "newer load entered before A's cancel completed"
+
+ release_backend_cancel.set()
+ assert (await cancel).status == "unloaded"
+ with pytest.raises(HTTPException, match = "cancelled"):
+ await first
+ assert (await second)["status"] == "loaded"
+
+ asyncio.run(scenario())
+
+
+def test_scoped_unload_of_queued_attempt_never_unloads_or_deadlocks(monkeypatch):
+ import asyncio
+
+ import routes.inference as inference_route
+ from fastapi import HTTPException
+ from models.inference import LoadRequest, UnloadRequest
+
+ def _unexpected_backend():
+ pytest.fail("cancel-only cleanup must never unload a resident model")
+
+ monkeypatch.setattr(inference_route, "get_inference_backend", _unexpected_backend)
+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", _unexpected_backend)
+
+ async def _unexpected_load(*_args, **_kwargs):
+ pytest.fail("a cancelled queued attempt must not reach backend load work")
+
+ monkeypatch.setattr(inference_route, "_load_model_impl", _unexpected_load)
+ attempt = inference_route._begin_load_attempt(
+ LoadRequest(model_path = "m", load_request_id = "audio-load-done"), "tester"
+ )
+ try:
+ response = asyncio.run(
+ inference_route._unload_model_impl(
+ UnloadRequest(model_path = "m", cancel_load_request_id = "audio-load-done"),
+ "tester",
+ )
+ )
+ assert response.status == "unloaded"
+ assert attempt.cancel_event.is_set()
+ assert attempt.cancel_complete.is_set()
+ with pytest.raises(HTTPException, match = "cancelled"):
+ asyncio.run(
+ asyncio.wait_for(
+ inference_route._run_tracked_load_model_impl(
+ LoadRequest(model_path = "m", load_request_id = "audio-load-done"),
+ object(),
+ "tester",
+ attempt = attempt,
+ ),
+ timeout = 1,
+ )
+ )
+ finally:
+ inference_route._finish_load_attempt(attempt)
+
+
+def test_scoped_unload_cancels_only_its_running_gguf_load(monkeypatch):
+ import asyncio
+
+ import routes.inference as inference_route
+ from models.inference import LoadRequest, UnloadRequest
+
+ class _Backend:
+ def get_loading_model(self):
+ return None
+
+ class _Llama:
+ is_active = True
+ is_loaded = False
+ model_identifier = "m"
+
+ def __init__(self):
+ self.unloaded = False
+
+ def unload_model(self):
+ self.unloaded = True
+
+ llama = _Llama()
+ monkeypatch.setattr(inference_route, "get_inference_backend", lambda: _Backend())
+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: llama)
+ monkeypatch.setattr(inference_route, "is_registered_native_path_label", lambda *a: False)
+ attempt = inference_route._begin_load_attempt(
+ LoadRequest(model_path = "m", load_request_id = "audio-gguf-1"), "tester"
+ )
+ with inference_route._scoped_load_attempts_lock:
+ inference_route._running_load_attempt = attempt
+ try:
+ response = asyncio.run(
+ inference_route._unload_model_impl(
+ UnloadRequest(model_path = "m", cancel_load_request_id = "audio-gguf-1"),
+ "tester",
+ )
+ )
+ assert response.status == "unloaded"
+ assert llama.unloaded is True
+ finally:
+ with inference_route._scoped_load_attempts_lock:
+ inference_route._running_load_attempt = None
+ inference_route._finish_load_attempt(attempt)
+
+
+def test_standard_load_honors_scoped_cancel_before_worker_start():
+ from types import SimpleNamespace
+
+ attempt_cancelled = threading.Event()
+ attempt_cancelled.set()
+ orchestrator = _bare_orchestrator()
+
+ assert (
+ orchestrator.load_model(
+ SimpleNamespace(identifier = "m"), load_cancel_event = attempt_cancelled
+ )
+ is False
+ )
+ assert orchestrator.loading_models == set()
+
+
# ----------------------------------------------------------------------------
# A dispatched (compare-mode) request that races an unload must not orphan its
# mailbox after _wait_dispatcher_idle stops the dispatcher.
@@ -2031,3 +2347,39 @@ def test_audio_input_stopped_while_queued_is_never_sent(monkeypatch):
assert o._active_cancel_events == []
assert o._gen_lock.acquire(blocking = False)
o._gen_lock.release()
+
+
+def test_a_scoped_load_cancel_that_never_reports_back_releases_the_load():
+ """Only /unload's finally sets cancel_complete, so a disconnect or shutdown between the
+ two leaves nobody to set it. An unbounded wait parks the load under
+ inference_lifecycle_gate for the process lifetime, and asyncio.to_thread's executor
+ threads are non-daemon, so it also blocks exit."""
+ import asyncio
+
+ import routes.inference as inf
+ from models.inference import LoadRequest, UnloadRequest
+
+ request = LoadRequest(model_path = "org/a", load_request_id = "handshake-drop")
+ original_impl = inf._load_model_impl
+ original_timeout = inf._SCOPED_LOAD_CANCEL_HANDSHAKE_TIMEOUT_S
+
+ async def cancel_then_die(*args, **kwargs):
+ attempt, is_running = inf._cancel_scoped_load_attempt(
+ UnloadRequest(model_path = "org/a", cancel_load_request_id = "handshake-drop"), "s"
+ )
+ assert attempt is not None and is_running
+ attempt.cancel_complete.clear() # the teardown never reached its finally
+ return {"status": "loaded"}
+
+ inf._load_model_impl = cancel_then_die
+ inf._SCOPED_LOAD_CANCEL_HANDSHAKE_TIMEOUT_S = 0.25
+ try:
+ asyncio.run(
+ asyncio.wait_for(inf._run_tracked_load_model_impl(request, None, "s"), timeout = 30)
+ )
+ finally:
+ inf._load_model_impl = original_impl
+ inf._SCOPED_LOAD_CANCEL_HANDSHAKE_TIMEOUT_S = original_timeout
+ with inf._scoped_load_attempts_lock:
+ inf._scoped_load_attempts.clear()
+ inf._scoped_load_cancel_tombstones.clear()
diff --git a/studio/backend/tests/test_personalization_settings.py b/studio/backend/tests/test_personalization_settings.py
index 70339dc7409..e145a653ea4 100644
--- a/studio/backend/tests/test_personalization_settings.py
+++ b/studio/backend/tests/test_personalization_settings.py
@@ -158,6 +158,7 @@ FRONTEND_SHIPPED_SIDEBAR_NAV = [
("projects", True),
("images", True),
("video", False),
+ ("audio", False),
("train", True),
("recipes", False),
("export", False),
@@ -197,6 +198,7 @@ def test_customization_sidebar_nav_preserves_order_and_normalizes():
("hub", False),
("projects", True),
("images", True),
+ ("audio", False),
("train", True),
("recipes", False),
("export", False),
@@ -463,6 +465,7 @@ def test_personalization_route_roundtrip_real_shape(monkeypatch):
"sidebarNav": [
{"id": "images", "pinned": True},
{"id": "video", "pinned": True},
+ {"id": "audio", "pinned": False},
{"id": "hub", "pinned": True},
{"id": "train", "pinned": True},
{"id": "projects", "pinned": False},
diff --git a/studio/backend/tests/test_stt_broken_runtime_falls_back.py b/studio/backend/tests/test_stt_broken_runtime_falls_back.py
new file mode 100644
index 00000000000..7e5f28e4e90
--- /dev/null
+++ b/studio/backend/tests/test_stt_broken_runtime_falls_back.py
@@ -0,0 +1,160 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A whisper.cpp build that starts but cannot infer must stop reporting as available.
+
+Reported on Windows with ROCm on gfx1200: rocBLAS was missing its TensileLibrary, so
+whisper-server started, answered GET /, and died on the first inference. The binary and
+every linked library were present, so slim_runtime_intact() was satisfied, is_available()
+said yes, and _resolve_serving_stt_engine never fell back. Every recording returned 501
+while the UI showed the model loaded. Only an actual inference can distinguish this case.
+"""
+
+from __future__ import annotations
+
+import threading
+
+import pytest
+
+from core.inference import stt_ggml_sidecar
+
+
[email protected](autouse = True)
+def _clean_runtime_state():
+ stt_ggml_sidecar.clear_runtime_inference_failure()
+ yield
+ stt_ggml_sidecar.clear_runtime_inference_failure()
+
+
+def test_a_runtime_that_cannot_infer_reports_unavailable(monkeypatch):
+ monkeypatch.setattr(stt_ggml_sidecar, "find_whisper_server_binary", lambda: "whisper-server")
+ monkeypatch.setattr(stt_ggml_sidecar, "slim_runtime_intact", lambda binary: True)
+
+ assert stt_ggml_sidecar.is_available() is True
+ stt_ggml_sidecar.note_runtime_inference_failure("RemoteDisconnected")
+ assert stt_ggml_sidecar.is_available() is False
+ assert "RemoteDisconnected" in (stt_ggml_sidecar.runtime_inference_failure() or "")
+
+
+def test_the_serving_engine_then_falls_back_to_transformers(monkeypatch):
+ from routes import inference as inference_routes
+
+ monkeypatch.setattr(stt_ggml_sidecar, "find_whisper_server_binary", lambda: "whisper-server")
+ monkeypatch.setattr(stt_ggml_sidecar, "slim_runtime_intact", lambda binary: True)
+
+ assert inference_routes._resolve_serving_stt_engine("gguf") == "gguf"
+ stt_ggml_sidecar.note_runtime_inference_failure("RemoteDisconnected")
+ # The fallback exists to avoid 501-ing on every recording; this is that case.
+ assert inference_routes._resolve_serving_stt_engine("gguf") == "transformers"
+
+
+def test_a_cancelled_transcription_does_not_disable_the_engine():
+ """A cancel closes the socket deliberately. Treating that as a broken runtime would
+ disable whisper.cpp for the rest of the session every time someone stops a recording."""
+ cancel_event = threading.Event()
+ cancel_event.set()
+
+ # Mirrors the guard at the call site rather than driving a live server.
+ if cancel_event is None or not cancel_event.is_set():
+ stt_ggml_sidecar.note_runtime_inference_failure("should not happen")
+ assert stt_ggml_sidecar.runtime_inference_failure() is None
+
+
+def test_a_later_success_clears_the_failure():
+ stt_ggml_sidecar.note_runtime_inference_failure("RemoteDisconnected")
+ stt_ggml_sidecar.clear_runtime_inference_failure()
+ assert stt_ggml_sidecar.runtime_inference_failure() is None
+
+
+def test_an_amd_box_does_not_report_its_dictation_device_as_cuda(monkeypatch):
+ """Torch's ROCm build keeps the "cuda" device name for HIP, which is correct for the
+ API and misleading on screen: the Loaded models entry read "Transformers - cuda" on a
+ Radeon card (reported on Windows against PR 7984)."""
+ torch = pytest.importorskip("torch")
+
+ from core.inference.stt_sidecar import _reported_device
+
+ monkeypatch.setattr(torch.version, "hip", "7.1", raising = False)
+ assert _reported_device("cuda") == "rocm"
+ assert _reported_device("cpu") == "cpu"
+ assert _reported_device(None) is None
+
+ monkeypatch.setattr(torch.version, "hip", None, raising = False)
+ assert _reported_device("cuda") == "cuda"
+
+
+def test_the_fallback_fetches_the_transformers_snapshot_it_needs(monkeypatch):
+ """The GGUF pick downloaded one .bin, so Transformers has no snapshot to serve.
+
+ Without this the fallback swaps a 501 for a 409 "not downloaded" on every retry while
+ the Audio page still shows the selection as ready.
+ """
+ from core.inference import stt_sidecar
+ from routes import inference as inference_routes
+
+ monkeypatch.setattr(stt_ggml_sidecar, "find_whisper_server_binary", lambda: "whisper-server")
+ monkeypatch.setattr(stt_ggml_sidecar, "slim_runtime_intact", lambda binary: True)
+ monkeypatch.setattr(stt_sidecar, "is_model_downloaded", lambda model: False)
+ started: list[tuple] = []
+ monkeypatch.setattr(
+ stt_sidecar,
+ "start_model_download",
+ lambda model, token = None, revision = None: started.append((model, token)),
+ )
+
+ # A healthy runtime serves the GGUF itself, so nothing is fetched.
+ inference_routes._prepare_runtime_fallback_checkpoint("gguf", "gguf", "small")
+ assert started == []
+
+ stt_ggml_sidecar.note_runtime_inference_failure("RemoteDisconnected")
+ engine = inference_routes._resolve_serving_stt_engine("gguf")
+ inference_routes._prepare_runtime_fallback_checkpoint("gguf", engine, "small")
+ assert started == [("small", None)]
+
+
+def test_an_already_downloaded_snapshot_is_not_fetched_again(monkeypatch):
+ from core.inference import stt_sidecar
+ from routes import inference as inference_routes
+
+ monkeypatch.setattr(stt_sidecar, "is_model_downloaded", lambda model: True)
+ started: list[tuple] = []
+ monkeypatch.setattr(
+ stt_sidecar,
+ "start_model_download",
+ lambda model, token = None, revision = None: started.append((model, token)),
+ )
+ stt_ggml_sidecar.note_runtime_inference_failure("RemoteDisconnected")
+ inference_routes._prepare_runtime_fallback_checkpoint("gguf", "transformers", "small")
+ assert started == []
+
+
+def test_a_plain_transformers_pick_is_left_alone(monkeypatch):
+ """Only a GGUF selection redirected by a broken runtime needs preparing. An engine
+ that was never installed already routes its own download through Transformers."""
+ from core.inference import stt_sidecar
+ from routes import inference as inference_routes
+
+ monkeypatch.setattr(stt_sidecar, "is_model_downloaded", lambda model: False)
+ started: list[tuple] = []
+ monkeypatch.setattr(
+ stt_sidecar,
+ "start_model_download",
+ lambda model, token = None, revision = None: started.append((model, token)),
+ )
+ stt_ggml_sidecar.note_runtime_inference_failure("RemoteDisconnected")
+ inference_routes._prepare_runtime_fallback_checkpoint("transformers", "transformers", "small")
+ inference_routes._prepare_runtime_fallback_checkpoint("mtmd", "mtmd", "small")
+ assert started == []
+
+ # And a download that cannot start (another model is in flight) is not fatal: the
+ # caller still reports "not downloaded" rather than a 500.
+ def refuse(
+ model,
+ token = None,
+ revision = None,
+ ):
+ from core.inference.stt_sidecar import SttModelIdError
+ raise SttModelIdError("Another dictation model is still downloading; wait for it.")
+
+ monkeypatch.setattr(stt_sidecar, "start_model_download", refuse)
+ inference_routes._prepare_runtime_fallback_checkpoint("gguf", "transformers", "small")
diff --git a/studio/backend/tests/test_stt_ggml_sidecar.py b/studio/backend/tests/test_stt_ggml_sidecar.py
index b2cf43e5cd9..dc6dfa58d4c 100644
--- a/studio/backend/tests/test_stt_ggml_sidecar.py
+++ b/studio/backend/tests/test_stt_ggml_sidecar.py
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import asyncio
import http.server
import io
import json
@@ -13,6 +14,7 @@ from pathlib import Path
import numpy as np
import pytest
+from fastapi import HTTPException
import core.inference.stt_ggml_sidecar as ggml_module
from core.inference.stt_ggml_sidecar import (
@@ -43,7 +45,7 @@ def isolate_runtime_and_stub_audio_decoder(monkeypatch, tmp_path):
monkeypatch.setattr(
ggml_module,
"_decode_audio_bounded",
- lambda audio: np.zeros(16000, dtype = np.float32),
+ lambda audio, cancel_event = None: np.zeros(16000, dtype = np.float32),
)
@@ -86,9 +88,21 @@ def test_curated_filenames_match_repo_naming():
# Binary discovery
# ---------------------------------------------------------------------------
+# The launcher looks for whisper-server.exe on Windows, and the slim guard checks the
+# libraries the marker names verbatim, so a fixture hardcoding the Unix spellings is
+# invisible to both and the tests fail for the filename rather than the behaviour.
+_SERVER_NAME = "whisper-server.exe" if sys.platform == "win32" else "whisper-server"
+
+
+def _core_ggml_names() -> list[str]:
+ """The two core ggml libraries _slim_install writes for this platform."""
+ if sys.platform == "win32":
+ return ["ggml.dll", "ggml-base.dll"]
+ return ["libggml.so.0", "libggml-base.so.0"]
+
def test_env_binary_override_wins(monkeypatch, tmp_path):
- binary = tmp_path / "whisper-server"
+ binary = tmp_path / _SERVER_NAME
binary.write_text("#!/bin/sh\n")
binary.chmod(0o755) # find_whisper_server_binary requires an executable
monkeypatch.setenv("WHISPER_SERVER_PATH", str(binary))
@@ -99,7 +113,7 @@ def test_env_dir_override_scans_layouts(monkeypatch, tmp_path):
monkeypatch.delenv("WHISPER_SERVER_PATH", raising = False)
build_bin = tmp_path / "build" / "bin"
build_bin.mkdir(parents = True)
- binary = build_bin / "whisper-server"
+ binary = build_bin / _SERVER_NAME
binary.write_text("#!/bin/sh\n")
binary.chmod(0o755) # find_whisper_server_binary requires an executable
monkeypatch.setenv("UNSLOTH_WHISPER_CPP_PATH", str(tmp_path))
@@ -120,7 +134,7 @@ def test_missing_binary_reports_unavailable(monkeypatch, tmp_path):
def test_non_executable_binary_is_not_runnable(monkeypatch, tmp_path):
if sys.platform == "win32":
pytest.skip("X_OK is an existence check on Windows")
- binary = tmp_path / "whisper-server"
+ binary = tmp_path / _SERVER_NAME
binary.write_text("#!/bin/sh\n") # written but not chmod +x
monkeypatch.setenv("WHISPER_SERVER_PATH", str(binary))
monkeypatch.setattr(ggml_module.shutil, "which", lambda name: None)
@@ -146,7 +160,7 @@ def _slim_install(
install_dir = tmp_path / "whisper.cpp"
bin_dir = install_dir / "build" / "bin"
bin_dir.mkdir(parents = True)
- binary = bin_dir / "whisper-server"
+ binary = bin_dir / _SERVER_NAME
binary.write_text("#!/bin/sh\n")
binary.chmod(0o755)
marker: dict = {
@@ -192,7 +206,7 @@ def test_slim_guard_flags_missing_ggml_links(monkeypatch, tmp_path):
def test_slim_guard_passes_with_links_in_place(monkeypatch, tmp_path):
- names = ["libggml.so.0", "libggml-base.so.0"]
+ names = _core_ggml_names()
binary = _slim_install(tmp_path, with_ggml = True, linked_libraries = names)
assert ggml_module.slim_runtime_intact(binary) is True
monkeypatch.setattr(ggml_module, "find_whisper_server_binary", lambda: binary)
@@ -223,7 +237,7 @@ def test_slim_guard_malformed_authoritative_marker_fails_closed(tmp_path):
def test_slim_guard_prefers_authoritative_root_marker(tmp_path):
- names = ["libggml.so.0", "libggml-base.so.0"]
+ names = _core_ggml_names()
binary = _slim_install(tmp_path, with_ggml = True, linked_libraries = names)
packaging_marker = Path(binary).parent / "UNSLOTH_WHISPER_PREBUILT_INFO.json"
packaging_marker.write_text(json.dumps({"backend": "slim", "release_tag": "packaging"}))
@@ -240,7 +254,7 @@ def test_slim_guard_rejects_invalid_root_even_with_inner_marker(tmp_path):
def test_slim_guard_rejects_missing_rocm_catalog(tmp_path):
- names = ["libggml.so.0", "libggml-base.so.0", "libggml-hip.so"]
+ names = [*_core_ggml_names(), "libggml-hip.so"]
binary = _slim_install(
tmp_path,
linked_libraries = names,
@@ -258,7 +272,7 @@ def test_slim_guard_rejects_missing_rocm_catalog(tmp_path):
def test_slim_guard_accepts_newer_rocm_wiring_version(tmp_path):
# The guard pins a floor, not one version: an installer bump must not strand
# ROCm installs as unavailable when every wired library is present.
- names = ["libggml.so.0", "libggml-base.so.0", "libggml-hip.so"]
+ names = [*_core_ggml_names(), "libggml-hip.so"]
binary = _slim_install(
tmp_path,
linked_libraries = names,
@@ -272,7 +286,7 @@ def test_slim_guard_accepts_newer_rocm_wiring_version(tmp_path):
def test_slim_guard_rejects_pre_catalog_rocm_wiring_version(tmp_path):
# Version 1 predates linked_runtime_directories, so it stays rejected.
- names = ["libggml.so.0", "libggml-base.so.0", "libggml-hip.so"]
+ names = [*_core_ggml_names(), "libggml-hip.so"]
binary = _slim_install(
tmp_path,
linked_libraries = names,
@@ -303,7 +317,7 @@ def test_slim_guard_ignores_fat_and_markerless_installs(tmp_path):
# Fat installs carry their own ggml; no marker means source/custom build.
fat = _slim_install(tmp_path / "fat", install_kind = None, with_ggml = False)
assert ggml_module.slim_runtime_intact(fat) is True
- bare = tmp_path / "bare" / "whisper-server"
+ bare = tmp_path / "bare" / _SERVER_NAME
bare.parent.mkdir(parents = True)
bare.write_text("#!/bin/sh\n")
assert ggml_module.slim_runtime_intact(str(bare)) is True
@@ -324,7 +338,7 @@ def test_child_env_scrubs_secrets_and_adds_lib_dir(monkeypatch, tmp_path):
monkeypatch.setenv("HTTPS_PROXY", "http://u:p@px:8080") # url-name
monkeypatch.setenv("SOME_REMOTE", "https://u:pw@host/repo") # url-userinfo value
monkeypatch.setenv("STT_KEEPME", "keep") # benign
- binary = tmp_path / "whisper-server"
+ binary = tmp_path / _SERVER_NAME
binary.write_text("#!/bin/sh\n")
env = ggml_module._whisper_server_child_env(str(binary))
for scrubbed in ("HF_TOKEN", "MY_API_KEY", "HTTPS_PROXY", "SOME_REMOTE"):
@@ -340,7 +354,7 @@ def test_child_env_isolates_home_and_cred_locations(monkeypatch, tmp_path):
monkeypatch.setenv("HF_HOME", "/real/hf")
monkeypatch.setenv("NETRC", "/real/.netrc")
monkeypatch.setattr(ggml_module, "_managed_whisper_cpp_dir", lambda: tmp_path / "managed")
- binary = tmp_path / "whisper-server"
+ binary = tmp_path / _SERVER_NAME
binary.write_text("#!/bin/sh\n")
env = ggml_module._whisper_server_child_env(str(binary))
assert env["HOME"] == str(tmp_path / "managed" / ".child_home")
@@ -356,7 +370,7 @@ def test_child_env_wsl_rocm_prepends_system_hip(monkeypatch, tmp_path):
rocm.mkdir()
bindir = tmp_path / "bin"
bindir.mkdir()
- binary = bindir / "whisper-server"
+ binary = bindir / _SERVER_NAME
binary.write_text("#!/bin/sh\n")
monkeypatch.setattr(ggml_module, "_wsl_system_rocm_lib_dirs", lambda: [str(rocm)])
env = ggml_module._whisper_server_child_env(str(binary))
@@ -375,13 +389,13 @@ def test_child_env_adds_cuda_runtime_dirs_for_cuda_bundle(monkeypatch, tmp_path)
bindir = tmp_path / "bin"
bindir.mkdir()
- (bindir / "whisper-server").write_text("#!/bin/sh\n")
+ (bindir / _SERVER_NAME).write_text("#!/bin/sh\n")
module_name = "ggml-cuda.dll" if sys.platform == "win32" else "libggml-cuda.so.0"
(bindir / module_name).write_text("")
cuda_dir = tmp_path / "nvidia" / "cuda_runtime" / "lib"
cuda_dir.mkdir(parents = True)
monkeypatch.setattr(rl, "python_runtime_dirs", lambda: [str(cuda_dir)])
- env = ggml_module._whisper_server_child_env(str(bindir / "whisper-server"))
+ env = ggml_module._whisper_server_child_env(str(bindir / _SERVER_NAME))
parts = env[_loader_path_var()].split(os.pathsep)
assert str(bindir.resolve()) in parts
assert str(cuda_dir.resolve()) in parts
@@ -397,7 +411,7 @@ def test_child_env_omits_cuda_runtime_dirs_for_cpu_bundle(monkeypatch, tmp_path)
bindir = tmp_path / "bin"
bindir.mkdir()
- (bindir / "whisper-server").write_text("#!/bin/sh\n")
+ (bindir / _SERVER_NAME).write_text("#!/bin/sh\n")
cuda_dir = tmp_path / "nvidia" / "cuda_runtime" / "lib"
cuda_dir.mkdir(parents = True)
called = {"n": 0}
@@ -407,7 +421,7 @@ def test_child_env_omits_cuda_runtime_dirs_for_cpu_bundle(monkeypatch, tmp_path)
return [str(cuda_dir)]
monkeypatch.setattr(rl, "python_runtime_dirs", _fake_dirs)
- env = ggml_module._whisper_server_child_env(str(bindir / "whisper-server"))
+ env = ggml_module._whisper_server_child_env(str(bindir / _SERVER_NAME))
parts = env[_loader_path_var()].split(os.pathsep)
assert str(cuda_dir.resolve()) not in parts
assert called["n"] == 0
@@ -460,6 +474,10 @@ def test_transcribe_requires_engine(monkeypatch):
def test_transcribe_rejects_unknown_language(monkeypatch):
_available(monkeypatch)
+ # The real list comes from Transformers, and without it the helper returns None and
+ # the check is skipped, so the request fell through to the download guard instead and
+ # the assertion below silently stopped testing anything.
+ monkeypatch.setattr(ggml_module, "_known_whisper_languages", lambda: frozenset({"en", "fr"}))
sidecar = GgmlSttSidecar()
with pytest.raises(SttLanguageError):
sidecar.transcribe(b"RIFF", model = "small", language = "xx-QQ")
@@ -595,7 +613,7 @@ def test_training_forces_whisper_server_off_gpu(monkeypatch):
def test_cpu_root_marker_forces_no_gpu_despite_inner_packaging_marker(monkeypatch, tmp_path):
- names = ["libggml.so.0", "libggml-base.so.0"]
+ names = _core_ggml_names()
binary = _slim_install(tmp_path, with_ggml = True, linked_libraries = names)
(Path(binary).parent / "UNSLOTH_WHISPER_PREBUILT_INFO.json").write_text(
json.dumps({"backend": "slim"})
@@ -807,3 +825,232 @@ def test_download_rejects_custom_ids():
def test_download_status_idle_shape():
status = ggml_module.download_status()
assert set(status) >= {"downloading", "model", "error"}
+
+
+# Follow-ups from review of the GGUF dictation path: curated GGUF repos stay out
+# of the chat pickers, the status accessors never block behind a transcription, and a
+# "gguf" unload on a host without whisper-server targets the fallback that served it.
+
+
+# 1. Hidden-model GGUF companions ------------------------------------------------
+def test_curated_gguf_dictation_repos_are_hidden():
+ from utils.hidden_models import (
+ _HIDDEN_STT_REPO_IDS,
+ is_curated_stt_repo_id,
+ is_hidden_model,
+ )
+
+ for repo in (
+ "unslothai/whisper-tiny-GGUF",
+ "unslothai/whisper-base-GGUF",
+ "unslothai/whisper-small-GGUF",
+ "unslothai/whisper-large-v3-turbo-GGUF",
+ "unslothai/whisper-large-v3-GGUF",
+ ):
+ assert repo in _HIDDEN_STT_REPO_IDS
+ assert is_hidden_model(repo) is True
+ assert is_curated_stt_repo_id(repo.lower()) is True
+ # Case-insensitive, matching how the cache stores the repo id.
+ assert is_hidden_model(repo.lower()) is True
+
+ # A same-prefix but genuinely different repo is NOT hidden.
+ assert is_hidden_model("unslothai/whisper-large-v3-GGUF-finetune") is False
+ assert is_curated_stt_repo_id("unslothai/whisper-large-v3-GGUF-finetune") is False
+
+
+def test_stt_load_has_no_engine_wide_cancel_endpoint():
+ import routes.inference as inference_route
+ assert not hasattr(inference_route, "stt_load_cancel")
+ assert all(route.path != "/audio/stt/load/cancel" for route in inference_route.router.routes)
+
+
+# 2. GGUF status accessors are lock-free ----------------------------------------
+def test_gguf_status_accessors_do_not_block_on_the_inference_lock():
+ from core.inference.stt_ggml_sidecar import GgmlSttSidecar
+
+ sidecar = GgmlSttSidecar()
+
+ class _AliveProc:
+ pid = 4321
+
+ def poll(self):
+ return None # still running
+
+ sidecar._process = _AliveProc()
+ sidecar._model_id = "small"
+
+ holder_has_lock = threading.Event()
+ release = threading.Event()
+
+ def _hold_inference_lock():
+ # Mimic transcribe() holding self._lock across the whole HTTP call.
+ with sidecar._lock:
+ holder_has_lock.set()
+ release.wait(timeout = 5)
+
+ holder = threading.Thread(target = _hold_inference_lock)
+ holder.start()
+ assert holder_has_lock.wait(timeout = 5)
+
+ result: dict = {}
+
+ def _read_status():
+ result["model"] = sidecar.loaded_model
+ result["device"] = sidecar.device
+
+ reader = threading.Thread(target = _read_status)
+ reader.start()
+ reader.join(timeout = 2)
+ blocked = reader.is_alive()
+
+ release.set()
+ holder.join(timeout = 5)
+ reader.join(timeout = 5)
+
+ assert not blocked, "loaded_model/device blocked on self._lock (should be lock-free)"
+ assert result == {"model": "small", "device": "whisper.cpp"}
+
+
+def test_process_alive_snapshots_process_against_concurrent_unload():
+ # _process_alive() must read self._process exactly once. The lock-free
+ # readers (loaded_model/device) can run while unload() nulls self._process;
+ # the old `self._process is not None and self._process.poll() is None` read it
+ # twice, so a null landing between the two reads called None.poll(). A
+ # property that yields the live process on the first read and None afterwards
+ # reproduces that interleaving deterministically.
+ from core.inference.stt_ggml_sidecar import GgmlSttSidecar
+
+ class _AliveProc:
+ def poll(self):
+ return None # still running
+
+ live = _AliveProc()
+ reads = {"n": 0}
+
+ class _RacingSidecar(GgmlSttSidecar):
+ @property
+ def _process(self):
+ reads["n"] += 1
+ return live if reads["n"] == 1 else None
+
+ @_process.setter
+ def _process(self, value):
+ pass # __init__ assigns None; the property drives the read
+
+ sidecar = GgmlSttSidecar()
+ sidecar.__class__ = _RacingSidecar # data descriptor wins over the instance attr
+
+ # Snapshot fix: exactly one read, no AttributeError from a second None read.
+ assert sidecar._process_alive() is True
+ assert reads["n"] == 1
+
+
+# 3. Unload resolves through the serving engine + attempts every backend ---------
+def test_gguf_unload_targets_transformers_fallback_without_whisper_server(monkeypatch):
+ import core.inference.stt_ggml_sidecar as ggml_module
+ import routes.inference as ri
+
+ monkeypatch.setattr(ggml_module, "is_available", lambda: False) # no whisper-server
+
+ calls: list = []
+
+ class _Sidecar:
+ def __init__(self, name):
+ self.name = name
+
+ def unload(
+ self,
+ wait = True,
+ expected_model = None,
+ ):
+ calls.append(self.name)
+
+ from core.inference import stt_registry
+
+ monkeypatch.setattr(stt_registry, "sidecar_for", lambda name: _Sidecar(name))
+
+ resp = asyncio.run(ri.stt_unload(engine = "gguf", current_subject = "tester"))
+ assert resp.status_code == 200
+ # gguf is served by the Transformers fallback here, so that is what unloads.
+ assert calls == ["transformers"]
+
+
+def test_unload_all_attempts_every_backend_even_when_one_fails(monkeypatch):
+ import routes.inference as ri
+
+ attempted: list = []
+
+ class _Sidecar:
+ def __init__(self, name):
+ self.name = name
+
+ def unload(
+ self,
+ wait = True,
+ expected_model = None,
+ ):
+ attempted.append(self.name)
+ if self.name == "transformers":
+ raise RuntimeError("boom")
+
+ from core.inference import stt_registry
+
+ monkeypatch.setattr(stt_registry, "sidecar_for", lambda name: _Sidecar(name))
+
+ with pytest.raises(HTTPException) as excinfo:
+ asyncio.run(ri.stt_unload(engine = None, current_subject = "tester"))
+
+ assert excinfo.value.status_code == 500
+ # The later engines are still attempted after transformers raised. mtmd is
+ # included so an Unload with no engine frees a resident llama-server too.
+ assert attempted == ["transformers", "gguf", "mtmd"]
+
+
+# 4. free_stt_model_for_training isolates the two backends -----------------------
+def test_free_stt_frees_gguf_even_when_transformers_unload_raises(monkeypatch):
+ import routes.training_vram as tv
+
+ class _TransformersSidecar:
+ def is_loading(self):
+ return False
+
+ @property
+ def loaded_model(self):
+ return "whisper-small"
+
+ def unload(
+ self,
+ wait = True,
+ expected_model = None,
+ ):
+ raise RuntimeError("transformers unload failed")
+
+ class _GgmlSidecar:
+ def __init__(self):
+ self.unloaded = False
+
+ def is_loading(self):
+ return False
+
+ @property
+ def loaded_model(self):
+ return None if self.unloaded else "small"
+
+ def unload(
+ self,
+ wait = True,
+ expected_model = None,
+ ):
+ self.unloaded = True
+
+ ggml = _GgmlSidecar()
+ monkeypatch.setattr(
+ "core.inference.stt_sidecar.get_stt_sidecar", lambda: _TransformersSidecar()
+ )
+ monkeypatch.setattr("core.inference.stt_ggml_sidecar.get_ggml_stt_sidecar", lambda: ggml)
+
+ freed = tv.free_stt_model_for_training("test")
+
+ # The Transformers failure must not skip GGUF eviction.
+ assert ggml.unloaded is True
+ assert any("small" in entry for entry in freed)
diff --git a/studio/backend/tests/test_stt_review_fixes_2.py b/studio/backend/tests/test_stt_install_and_snapshot_validation.py
similarity index 100%
rename from studio/backend/tests/test_stt_review_fixes_2.py
rename to studio/backend/tests/test_stt_install_and_snapshot_validation.py
diff --git a/studio/backend/tests/test_stt_review_fixes_3.py b/studio/backend/tests/test_stt_mtmd_sidecar.py
similarity index 51%
rename from studio/backend/tests/test_stt_review_fixes_3.py
rename to studio/backend/tests/test_stt_mtmd_sidecar.py
index 4fffd82a608..9241c4160f9 100644
--- a/studio/backend/tests/test_stt_review_fixes_3.py
+++ b/studio/backend/tests/test_stt_mtmd_sidecar.py
@@ -1,16 +1,19 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Third review pass: mtmd startup preemption, reaping and idle-timer safety."""
+"""The mtmd STT sidecar (Qwen3-ASR): load, unload, cancellation and residency.
+
+Was split across two files named after the review rounds that produced them, which said
+when the tests were written rather than what they cover. Same tests, one subject.
+"""
import subprocess
import threading
import time
-
import pytest
-
from core.inference import stt_mtmd_sidecar as mtmd_mod
from core.inference.stt_mtmd_sidecar import MtmdSttSidecar
+from core.inference import stt_ggml_sidecar as ggml_mod
class _FakeProcess:
@@ -440,17 +443,24 @@ def test_audio_is_never_sent_to_a_server_another_client_swapped_in(spawned, monk
in between and the port read would be the other server's."""
sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
monkeypatch.setattr(MtmdSttSidecar, "_wait_for_server", staticmethod(lambda *a, **k: True))
- monkeypatch.setattr(mtmd_mod, "_decode_audio_bounded", lambda audio: b"\x00\x00" * 16000)
+ monkeypatch.setattr(
+ mtmd_mod, "_decode_audio_bounded", lambda audio, cancel_event = None: b"\x00\x00" * 16000
+ )
monkeypatch.setattr(mtmd_mod, "_pcm_to_wav_bytes", lambda pcm: b"RIFFwav")
posted = []
monkeypatch.setattr(
MtmdSttSidecar,
"_post_transcribe",
- lambda self, port, model_id, wav, seconds = None: posted.append((port, model_id)) or "hi",
+ lambda self, port, model_id, wav, seconds = None, **kwargs: posted.append((port, model_id))
+ or "hi",
)
- def swap_after_load(self, model = None):
+ def swap_after_load(
+ self,
+ model = None,
+ request_cancel_event = None,
+ ):
# Stands in for another client switching the singleton in the gap.
with self._lock:
self._process = _FakeProcess()
@@ -479,6 +489,9 @@ def test_a_busy_transcription_is_a_retry_not_a_server_error(monkeypatch):
ri, "_stt_sidecar_for", lambda engine: type("S", (), {"transcribe": busy})()
)
monkeypatch.setattr(ri, "_resolve_serving_stt_engine", lambda engine: "mtmd")
+ # The route makes the model resident through the registry before transcribing, which
+ # would reach the real llama.cpp sidecar here. This test is about the error mapping.
+ monkeypatch.setattr(ri, "_stt_lifecycle", lambda: (lambda *a, **k: None, lambda *a: []))
with pytest.raises(HTTPException) as excinfo:
asyncio.run(
@@ -499,12 +512,14 @@ def test_dictation_still_works_on_cpu_during_training(spawned, monkeypatch):
threw away a recording the preload had said was fine."""
monkeypatch.setattr(MtmdSttSidecar, "_wait_for_server", staticmethod(lambda *a, **k: True))
monkeypatch.setattr(mtmd_mod, "_training_active", lambda: True)
- monkeypatch.setattr(mtmd_mod, "_decode_audio_bounded", lambda audio: b"\x00\x00" * 16000)
+ monkeypatch.setattr(
+ mtmd_mod, "_decode_audio_bounded", lambda audio, cancel_event = None: b"\x00\x00" * 16000
+ )
monkeypatch.setattr(mtmd_mod, "_pcm_to_wav_bytes", lambda pcm: b"RIFFwav")
monkeypatch.setattr(
MtmdSttSidecar,
"_post_transcribe",
- lambda self, port, model_id, wav, seconds = None: "on cpu",
+ lambda self, port, model_id, wav, seconds = None, **kwargs: "on cpu",
)
sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
@@ -513,6 +528,203 @@ def test_dictation_still_works_on_cpu_during_training(spawned, monkeypatch):
sidecar.unload()
+def test_disconnecting_one_mtmd_request_does_not_kill_its_sibling(monkeypatch):
+ monkeypatch.setattr(mtmd_mod, "ensure_engine_available", lambda: None)
+ monkeypatch.setattr(MtmdSttSidecar, "_ensure_model_downloaded", lambda *args: None)
+ monkeypatch.setattr(
+ mtmd_mod, "_decode_audio_bounded", lambda audio, cancel_event = None: b"\x00\x00" * 16000
+ )
+ monkeypatch.setattr(mtmd_mod, "_pcm_to_wav_bytes", lambda pcm: b"RIFFwav")
+
+ class _AliveProcess:
+ terminated = False
+
+ def poll(self):
+ return None
+
+ def terminate(self):
+ self.terminated = True
+
+ process = _AliveProcess()
+ sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
+ sidecar._process = process
+ sidecar._port = 65000
+ sidecar._model_id = "qwen3-asr-0.6b"
+ monkeypatch.setattr(sidecar, "load", lambda model, **kwargs: None)
+
+ first_cancel = threading.Event()
+ second_cancel = threading.Event()
+ both_started = threading.Event()
+ started_lock = threading.Lock()
+ started = 0
+ release_second = threading.Event()
+
+ def post(
+ _port,
+ _model,
+ _wav,
+ _seconds = None,
+ *,
+ cancel_event = None,
+ ):
+ nonlocal started
+ with started_lock:
+ started += 1
+ if started == 2:
+ both_started.set()
+ assert both_started.wait(timeout = 5)
+ if cancel_event is first_cancel:
+ assert first_cancel.wait(timeout = 5)
+ raise mtmd_mod.SttTranscriptionCancelledError("Transcription cancelled.")
+ assert release_second.wait(timeout = 5)
+ return "sibling survived"
+
+ monkeypatch.setattr(sidecar, "_post_transcribe", post)
+ results = []
+ errors = []
+
+ def run(cancel_event):
+ try:
+ results.append(
+ sidecar.transcribe(b"audio", model = "qwen3-asr-0.6b", cancel_event = cancel_event)[
+ "text"
+ ]
+ )
+ except Exception as exc:
+ errors.append(exc)
+
+ first = threading.Thread(target = run, args = (first_cancel,))
+ second = threading.Thread(target = run, args = (second_cancel,))
+ first.start()
+ second.start()
+ assert both_started.wait(timeout = 5)
+ sidecar.cancel_transcription(first_cancel)
+ release_second.set()
+ first.join(timeout = 5)
+ second.join(timeout = 5)
+
+ assert results == ["sibling survived"]
+ assert len(errors) == 1 and isinstance(errors[0], mtmd_mod.SttTranscriptionCancelledError)
+ assert process.terminated is False
+ assert sidecar._active_requests == 0
+
+
+def test_mtmd_disconnect_closes_the_request_connection(monkeypatch):
+ requested = threading.Event()
+ shutdown = threading.Event()
+
+ class _Socket:
+ def shutdown(self, _how):
+ shutdown.set()
+
+ class _Connection:
+ def __init__(self, *args, **kwargs):
+ self.sock = _Socket()
+
+ def request(self, *args, **kwargs):
+ requested.set()
+
+ def getresponse(self):
+ assert shutdown.wait(timeout = 5)
+ raise OSError("request connection closed")
+
+ def close(self):
+ pass
+
+ monkeypatch.setattr(mtmd_mod.http.client, "HTTPConnection", _Connection)
+ sidecar = MtmdSttSidecar()
+ cancelled = threading.Event()
+ errors = []
+
+ def post():
+ try:
+ sidecar._post_transcribe(
+ 65000,
+ "qwen3-asr-0.6b",
+ b"RIFFwav",
+ cancel_event = cancelled,
+ )
+ except Exception as exc:
+ errors.append(exc)
+
+ worker = threading.Thread(target = post)
+ worker.start()
+ assert requested.wait(timeout = 5)
+ cancelled.set()
+ worker.join(timeout = 5)
+
+ assert shutdown.is_set()
+ assert len(errors) == 1 and isinstance(errors[0], OSError)
+
+
+def test_mtmd_transcription_rejects_non_success_server_response(monkeypatch):
+ class _Response:
+ status = 500
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return False
+
+ def read(self):
+ return b'{"error":{"message":"decode failed"}}'
+
+ class _Connection:
+ sock = None
+
+ def __init__(self, *args, **kwargs):
+ pass
+
+ def request(self, *args, **kwargs):
+ pass
+
+ def getresponse(self):
+ return _Response()
+
+ def close(self):
+ pass
+
+ monkeypatch.setattr(mtmd_mod.http.client, "HTTPConnection", _Connection)
+
+ with pytest.raises(RuntimeError, match = "returned HTTP 500"):
+ MtmdSttSidecar()._post_transcribe(
+ 65000,
+ "qwen3-asr-0.6b",
+ b"RIFFwav",
+ )
+
+
+def test_mtmd_disconnect_cancels_only_its_owned_startup():
+ class _StartingProcess:
+ terminated = False
+
+ def poll(self):
+ return None
+
+ def terminate(self):
+ self.terminated = True
+
+ sidecar = MtmdSttSidecar()
+ owner = threading.Event()
+ sibling = threading.Event()
+ load_cancel = threading.Event()
+ process = _StartingProcess()
+ sidecar._loading = True
+ sidecar._load_cancel_event = load_cancel
+ sidecar._load_owner_cancel_event = owner
+ sidecar._starting_process = process
+
+ assert sidecar.cancel_transcription(sibling) is True
+ assert sibling.is_set()
+ assert not load_cancel.is_set()
+ assert process.terminated is False
+
+ assert sidecar.cancel_transcription(owner) is True
+ assert owner.is_set() and load_cancel.is_set()
+ assert process.terminated is True
+
+
def test_a_startup_cancelled_for_training_is_retryable_not_unavailable(spawned, monkeypatch):
"""501 reads as a broken runtime; this is ordinary preemption, so 409."""
sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
@@ -603,3 +815,378 @@ def test_a_load_is_cancellable_before_it_decides_where_to_run(spawned, monkeypat
assert seen[-1] is True, "the deciding read happened while nothing could cancel the load"
sidecar.unload()
+
+
+class _SlowlyDyingProcess:
+ """A child whose reap blocks, like a llama-server that is slow to exit."""
+
+ def __init__(self, release: threading.Event):
+ self.pid = 4242
+ self._release = release
+ self._returncode = None
+
+ def poll(self):
+ return self._returncode
+
+ def terminate(self):
+ pass
+
+ def wait(self, timeout = None):
+ # Blocks until the test lets go, like a server slow to release its port and VRAM.
+ if not self._release.wait(timeout = timeout):
+ raise subprocess.TimeoutExpired("llama-server", timeout)
+ self._returncode = -15
+ return self._returncode
+
+ def kill(self):
+ self._returncode = -9
+
+
+def _resident(sidecar: MtmdSttSidecar, process) -> None:
+ """Publish `process` as the loaded server, as a finished load would."""
+ sidecar._process = process
+ sidecar._port = 12345
+ sidecar._model_id = "qwen3-asr-0.6b"
+
+
+def test_status_reads_do_not_block_behind_a_reap(monkeypatch):
+ """loaded_model/device/is_loading answer while unload() reaps under _lock.
+
+ The event loop and training admission both read these, so neither can wait
+ on a dying server.
+ """
+ monkeypatch.setattr(mtmd_mod, "forget_pid", lambda pid: None)
+ sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
+ release = threading.Event()
+ _resident(sidecar, _SlowlyDyingProcess(release))
+
+ unloading = threading.Thread(target = sidecar.unload, daemon = True)
+ unloading.start()
+ try:
+ # Give unload() time to take _lock and block inside _reap().
+ time.sleep(0.2)
+ answered = threading.Event()
+
+ def read_status():
+ sidecar.loaded_model
+ sidecar.device
+ sidecar.is_loading()
+ answered.set()
+
+ threading.Thread(target = read_status, daemon = True).start()
+ assert answered.wait(
+ timeout = 5
+ ), "a status read blocked behind the reap; the event loop would stall with it"
+ finally:
+ release.set()
+ unloading.join(timeout = 10)
+
+
+def test_a_reaping_server_stays_visible_to_training_admission(monkeypatch):
+ """A dying llama-server still holds VRAM, so it must still read as resident.
+
+ Clearing the fields before the reap would let summarize_resident_stt() report
+ nothing while the process is alive, and training would start into its memory.
+ """
+ monkeypatch.setattr(mtmd_mod, "forget_pid", lambda pid: None)
+ sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
+ release = threading.Event()
+ _resident(sidecar, _SlowlyDyingProcess(release))
+
+ seen = {}
+
+ def unload():
+ sidecar.unload()
+
+ unloading = threading.Thread(target = unload, daemon = True)
+ unloading.start()
+ try:
+ time.sleep(0.2) # inside the reap
+ seen["model"] = sidecar.loaded_model
+ seen["device"] = sidecar.device
+ finally:
+ release.set()
+ unloading.join(timeout = 10)
+
+ assert (
+ seen["model"] == "qwen3-asr-0.6b"
+ ), "the reaping server read as gone; training admission would miss its VRAM"
+ assert seen["device"] == "llama.cpp"
+ # Once the reap is done the fields are cleared, so it reads as gone.
+ assert sidecar.loaded_model is None
+ assert sidecar._process is None
+
+
+def test_a_starting_load_is_announced_before_the_probe_and_the_reap():
+ """is_loading() has to be true across the cache probe and the old reap.
+
+ Training admission reads it lock-free, so a False there sends it to unload(),
+ which waits out the whole startup instead of cancelling the load.
+ """
+ sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
+ probing = threading.Event()
+ release = threading.Event()
+
+ def slow_probe(model_id):
+ probing.set()
+ release.wait(timeout = 10)
+ raise RuntimeError("the probe is where the test stops")
+
+ sidecar._ensure_model_downloaded = slow_probe
+
+ def load():
+ try:
+ sidecar._load_locked("qwen3-asr-0.6b", "llama-server")
+ except Exception:
+ pass
+
+ loading = threading.Thread(target = load, daemon = True)
+ loading.start()
+ try:
+ assert probing.wait(timeout = 5)
+ assert sidecar.is_loading() is True, "the load was not announced before the probe"
+ assert sidecar.cancel_pending_load() is True, "training could not cancel this load"
+ finally:
+ release.set()
+ loading.join(timeout = 10)
+ # The load never started a server, so it must not leave _loading set.
+ assert sidecar.is_loading() is False
+ assert sidecar._load_cancel_event is None
+
+
+def test_device_never_contradicts_the_loaded_model():
+ """Mid-publish _process is set and _model_id is not; the two must agree."""
+ sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
+ sidecar._process = _SlowlyDyingProcess(threading.Event())
+ sidecar._port = 12345
+ sidecar._model_id = None
+ assert sidecar.loaded_model is None
+ assert sidecar.device is None, "the status route would ship a device with no model"
+
+
+def test_status_reads_do_not_block_during_a_llama_cpp_update():
+ """update_maintenance() holds _lock for the whole install; polls continue."""
+ sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
+ with sidecar.update_maintenance():
+ answered = threading.Event()
+
+ def read_status():
+ sidecar.loaded_model
+ sidecar.is_loading()
+ answered.set()
+
+ threading.Thread(target = read_status, daemon = True).start()
+ assert answered.wait(
+ timeout = 5
+ ), "a status read blocked for the length of the llama.cpp install"
+
+
+def test_ggml_download_drops_its_adopted_pid(monkeypatch, tmp_path):
+ """spawn_download() adopts a PID; left adopted it can be reused, and
+ terminate_all would then signal whatever inherited it.
+ """
+ forgotten = []
+
+ # Once metadata resolves, _run() prepares the repo's cache for HTTP before it
+ # reaches the stubbed worker, and that writes: it creates the repo directory and
+ # a .transport marker. The session conftest deliberately pins HF_HUB_CACHE to the
+ # developer's real cache, so without a cache of its own this test edits it.
+ monkeypatch.setenv("HF_HUB_CACHE", str(tmp_path / "hub"))
+
+ class _Finished:
+ pid = 7777
+ returncode = 0
+
+ def poll(self):
+ return 0
+
+ monkeypatch.setattr(ggml_mod, "_cached_model_path", lambda model_id: None)
+ # _run() opens with a HEAD to the Hub for the size and etag. It is best-effort and
+ # swallows its own errors, but leaving it live makes this test depend on a network
+ # round trip it does not care about, so answer it locally.
+ import huggingface_hub
+
+ class _Metadata:
+ """Stands in for HfFileMetadata; unset fields read as None, as they may on the Hub.
+
+ ``commit_hash`` has to be a real-looking sha: _run() pins the download to an
+ immutable revision and refuses anything that is not one.
+ """
+
+ size = 1
+ etag = "stub"
+ commit_hash = "0" * 40
+
+ def __getattr__(self, _name):
+ return None
+
+ monkeypatch.setattr(
+ huggingface_hub, "get_hf_file_metadata", lambda *a, **k: _Metadata(), raising = False
+ )
+ import core.inference.stt_download_worker as worker_mod
+
+ monkeypatch.setattr(worker_mod, "spawn_download", lambda *a, **k: _Finished())
+ monkeypatch.setattr(
+ worker_mod, "reap_download", lambda process: forgotten.append(process.pid) or b""
+ )
+ state = ggml_mod._GgmlDownloadState()
+ state._run("tiny", None)
+
+ assert forgotten == [7777], "the GGUF download never dropped its adopted PID"
+
+
+def test_wait_for_server_sleeps_on_a_non_200_success(monkeypatch):
+ """A 2xx that is not 200 must not spin the readiness loop with no delay."""
+
+ class _Response:
+ status = 204
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ return False
+
+ slept = []
+ monkeypatch.setattr(mtmd_mod.urllib.request, "urlopen", lambda *a, **k: _Response())
+ monkeypatch.setattr(mtmd_mod.time, "sleep", slept.append)
+ monkeypatch.setattr(mtmd_mod, "_SERVER_START_TIMEOUT_SECONDS", 0.5)
+
+ class _Alive:
+ def poll(self):
+ return None
+
+ assert MtmdSttSidecar._wait_for_server(_Alive(), 1234) is False
+ assert slept, "the readiness loop spun without sleeping on a non-200 response"
+
+
+def test_download_probe_is_memoised_then_dropped_when_a_download_ends(monkeypatch):
+ """The status poll asks four times a second; the cache walk runs once."""
+ mtmd_mod._forget_downloaded_probe()
+ calls = []
+
+ def fake_paths(model_id):
+ calls.append(model_id)
+ return ("m.gguf", "p.gguf")
+
+ monkeypatch.setattr(mtmd_mod, "_cached_model_paths", fake_paths)
+ assert mtmd_mod.is_model_downloaded("qwen3-asr-0.6b") is True
+ assert mtmd_mod.is_model_downloaded("qwen3-asr-0.6b") is True
+ assert len(calls) == 1, "the memo did not spare the second probe"
+
+ # A finished download changes the disk, so the answer is dropped, not left to expire.
+ mtmd_mod._forget_downloaded_probe("qwen3-asr-0.6b")
+ assert mtmd_mod.is_model_downloaded("qwen3-asr-0.6b") is True
+ assert len(calls) == 2
+
+ mtmd_mod._forget_downloaded_probe()
+
+
+def test_download_probe_expires(monkeypatch):
+ """A cache emptied outside Studio is noticed without a restart."""
+ mtmd_mod._forget_downloaded_probe()
+ monkeypatch.setattr(mtmd_mod, "_DOWNLOADED_PROBE_TTL_SECONDS", 0.0)
+ calls = []
+
+ def fake_paths(model_id):
+ calls.append(model_id)
+ return None
+
+ monkeypatch.setattr(mtmd_mod, "_cached_model_paths", fake_paths)
+ assert mtmd_mod.is_model_downloaded("qwen3-asr-0.6b") is False
+ assert mtmd_mod.is_model_downloaded("qwen3-asr-0.6b") is False
+ assert len(calls) == 2, "an expired entry was still served"
+
+ mtmd_mod._forget_downloaded_probe()
+
+
+def test_an_invalidation_mid_probe_discards_the_stale_answer(monkeypatch):
+ """A download finishing under a probe must not be undone by that probe.
+
+ The probe runs outside the lock, so it can write a stale False back over the
+ download's invalidation, and the model then reads as missing for a whole TTL.
+ """
+ mtmd_mod._forget_downloaded_probe()
+
+ def probe_then_invalidate(model_id):
+ # The download completing while this probe is in flight.
+ mtmd_mod._forget_downloaded_probe(model_id)
+ return None
+
+ monkeypatch.setattr(mtmd_mod, "_cached_model_paths", probe_then_invalidate)
+ assert mtmd_mod.is_model_downloaded("qwen3-asr-0.6b") is False
+ with mtmd_mod._downloaded_probe_lock:
+ assert (
+ "qwen3-asr-0.6b" not in mtmd_mod._downloaded_probe
+ ), "a stale answer was written back over the invalidation"
+
+ # The next poll sees the finished download rather than waiting out the TTL.
+ monkeypatch.setattr(mtmd_mod, "_cached_model_paths", lambda mid: ("m.gguf", "p.gguf"))
+ assert mtmd_mod.is_model_downloaded("qwen3-asr-0.6b") is True
+ mtmd_mod._forget_downloaded_probe()
+
+
+def test_the_entry_is_timestamped_after_the_probe(monkeypatch):
+ """A slow cache must not store an entry that is already near expiry."""
+ mtmd_mod._forget_downloaded_probe()
+ clock = {"t": 1000.0}
+ monkeypatch.setattr(mtmd_mod.time, "monotonic", lambda: clock["t"])
+
+ def slow_probe(model_id):
+ clock["t"] += 1.5 # probe takes most of the TTL
+ return ("m.gguf", "p.gguf")
+
+ monkeypatch.setattr(mtmd_mod, "_cached_model_paths", slow_probe)
+ assert mtmd_mod.is_model_downloaded("qwen3-asr-0.6b") is True
+
+ with mtmd_mod._downloaded_probe_lock:
+ stored_at = mtmd_mod._downloaded_probe["qwen3-asr-0.6b"][0]
+ assert stored_at == 1001.5, "the entry was timestamped before the probe ran"
+
+ # The panel's next poll, 750ms later, is still served from the memo.
+ clock["t"] += 0.75
+ called = []
+ monkeypatch.setattr(mtmd_mod, "_cached_model_paths", lambda mid: called.append(mid))
+ assert mtmd_mod.is_model_downloaded("qwen3-asr-0.6b") is True
+ assert called == [], "the entry expired early and the probe ran again"
+ mtmd_mod._forget_downloaded_probe()
+
+
+def test_unknown_model_is_never_memoised(monkeypatch):
+ called = []
+ monkeypatch.setattr(mtmd_mod, "_cached_model_paths", lambda model_id: called.append(model_id))
+ assert mtmd_mod.is_model_downloaded("not-a-model") is False
+ assert called == []
+
+
+def test_download_status_reports_progress_without_holding_the_lock():
+ """_downloaded_bytes() stats the cache; a cancel must not queue behind it."""
+ state = mtmd_mod._MtmdDownloadState()
+ observed = []
+
+ def slow_downloaded_bytes(*_args, **_kwargs):
+ # The lock must be free while this runs.
+ observed.append(state._lock.acquire(blocking = False))
+ if observed[-1]:
+ state._lock.release()
+ return 1
+
+ state._downloaded_bytes = slow_downloaded_bytes
+ state._model_id = "qwen3-asr-0.6b"
+ state._thread = threading.Thread(target = lambda: time.sleep(0.5), daemon = True)
+ state._thread.start()
+ try:
+ status = state.status()
+ finally:
+ state._thread.join(timeout = 5)
+
+ assert status["bytes_done"] == 1
+ assert observed == [True], "progress was computed while holding the download lock"
+
+
[email protected]("model_id", sorted(mtmd_mod.MTMD_STT_MODELS))
+def test_catalogue_probes_stay_answerable(model_id):
+ """is_model_downloaded() never raises for a curated id, cache or no cache."""
+ mtmd_mod._forget_downloaded_probe()
+ assert isinstance(mtmd_mod.is_model_downloaded(model_id), bool)
+ mtmd_mod._forget_downloaded_probe()
diff --git a/studio/backend/tests/test_stt_registry.py b/studio/backend/tests/test_stt_registry.py
index 351afd5bb44..483a729cb2b 100644
--- a/studio/backend/tests/test_stt_registry.py
+++ b/studio/backend/tests/test_stt_registry.py
@@ -4,6 +4,7 @@
"""Dictation lifecycle goes through one place, shared with the orchestrator."""
import pytest
+import threading
from core.inference import stt_registry
@@ -22,17 +23,31 @@ class _Sidecar:
self._loading = loading
self._fail = fail
self.unloaded = False
+ self.unload_waits = []
+ self.unload_expected = []
self.loaded_with = None
+ self.load_cancel_event = None
def is_loading(self):
return self._loading
- def load(self, model):
+ def load(
+ self,
+ model,
+ request_cancel_event = None,
+ ):
self.loaded_with = model
+ self.load_cancel_event = request_cancel_event
- def unload(self):
+ def unload(
+ self,
+ wait = True,
+ expected_model = None,
+ ):
if self._fail:
raise RuntimeError("boom")
+ self.unload_waits.append(wait)
+ self.unload_expected.append(expected_model)
self.unloaded = True
@@ -54,10 +69,39 @@ def test_unload_attempts_every_engine_even_after_one_raises(monkeypatch):
def test_load_delegates_to_the_engines_sidecar(monkeypatch):
sidecar = _Sidecar("mtmd")
+ cancel_event = threading.Event()
monkeypatch.setattr(stt_registry, "sidecar_for", lambda name: sidecar)
- stt_registry.load("qwen3-asr-0.6b", "mtmd")
+ stt_registry.load("qwen3-asr-0.6b", "mtmd", cancel_event)
assert sidecar.loaded_with == "qwen3-asr-0.6b"
+ assert sidecar.load_cancel_event is cancel_event
+
+
+def test_load_releases_the_other_engines_after_the_target_loads(monkeypatch):
+ order = []
+ sidecars = {name: _Sidecar(name) for name in stt_registry.STT_ENGINES}
+ for name, sidecar in sidecars.items():
+ sidecar.unload = lambda wait = True, expected_model = None, name = name: order.append(
+ f"unload:{name}"
+ )
+ target = sidecars["mtmd"]
+ target.load = lambda model, request_cancel_event = None: order.append("load:mtmd")
+ monkeypatch.setattr(stt_registry, "sidecar_for", lambda name: sidecars[name])
+
+ stt_registry.load("qwen3-asr-0.6b", "mtmd")
+
+ # Two engines resident at once doubles VRAM for the whole keep-alive window, but the
+ # release follows the load: a 409 must not cost the user the engine they were using.
+ assert order == ["load:mtmd", "unload:transformers", "unload:gguf"]
+
+
+def test_load_still_succeeds_when_another_engine_refuses_to_release(monkeypatch):
+ sidecars = {name: _Sidecar(name, fail = name == "gguf") for name in stt_registry.STT_ENGINES}
+ monkeypatch.setattr(stt_registry, "sidecar_for", lambda name: sidecars[name])
+
+ stt_registry.load("small", "transformers")
+ assert sidecars["transformers"].loaded_with == "small"
+ assert sidecars["mtmd"].unloaded
def test_resident_reports_whichever_engine_holds_a_model(monkeypatch):
@@ -134,3 +178,364 @@ def test_a_cold_process_loads_without_building_an_orchestrator(monkeypatch):
# Same functions the orchestrator's methods forward to, so neither path
# can drift from the other.
assert ri._stt_lifecycle() == (stt_registry.load, stt_registry.unload)
+
+
+def test_load_never_blocks_on_an_engine_that_is_serving_a_request(monkeypatch):
+ """A transcription holds the sidecar lock for minutes; the new load must not wait."""
+ sidecars = {name: _Sidecar(name) for name in stt_registry.STT_ENGINES}
+ monkeypatch.setattr(stt_registry, "sidecar_for", lambda name: sidecars[name])
+
+ stt_registry.load("qwen3-asr-0.6b", "mtmd")
+
+ assert sidecars["transformers"].unload_waits == [False]
+ assert sidecars["gguf"].unload_waits == [False]
+ # A caller releasing every engine on purpose still waits for each one.
+ stt_registry.unload()
+ assert sidecars["mtmd"].unload_waits == [True]
+
+
+def test_a_busy_sidecar_keeps_its_model_and_an_idle_one_releases_it():
+ """Against the real sidecars: `wait=False` must decline a live request, not block.
+
+ RLock.locked() is 3.14-only and the mtmd sidecar drops _lock before its HTTP call, so
+ the busy probe cannot be either.
+ """
+ from core.inference.stt_ggml_sidecar import get_ggml_stt_sidecar
+ from core.inference.stt_mtmd_sidecar import get_mtmd_stt_sidecar
+
+ ggml = get_ggml_stt_sidecar()
+ released = []
+ ggml._release_locked = lambda: released.append("ggml")
+ with ggml._lock:
+ blocker = threading.Thread(target = ggml.unload, kwargs = {"wait": False})
+ blocker.start()
+ blocker.join(timeout = 2)
+ assert not blocker.is_alive(), "unload(wait=False) blocked on a held lock"
+ assert released == []
+
+ ggml.unload(wait = False)
+ assert released == ["ggml"]
+
+ mtmd = get_mtmd_stt_sidecar()
+ mtmd_released = []
+ mtmd._release_locked = lambda: mtmd_released.append("mtmd")
+ mtmd._active_requests = 1
+ mtmd.unload(wait = False)
+ assert mtmd_released == [], "a transcription outside _lock still counts as busy"
+ mtmd._active_requests = 0
+ mtmd.unload(wait = False)
+ assert mtmd_released == ["mtmd"]
+
+
+def test_a_failed_load_leaves_the_engine_the_user_was_using(monkeypatch):
+ """The sidecars order preflight before release for this reason; so does the registry."""
+ sidecars = {name: _Sidecar(name) for name in stt_registry.STT_ENGINES}
+
+ def refuse(model, request_cancel_event = None):
+ raise RuntimeError("STT model 'x' is not downloaded.")
+
+ sidecars["mtmd"].load = refuse
+ monkeypatch.setattr(stt_registry, "sidecar_for", lambda name: sidecars[name])
+
+ with pytest.raises(RuntimeError, match = "not downloaded"):
+ stt_registry.load("x", "mtmd")
+
+ assert not sidecars["transformers"].unloaded
+ assert not sidecars["gguf"].unloaded
+
+
+def test_a_non_curated_whisper_cache_row_cannot_chat():
+ """`_hidden_stt` comes from the config sniff, so it covers distil-whisper and a user's own
+ fine-tune, not just the seven curated ids. can_chat is what auto-load and the chat picker
+ filter on, and neither looks at the task."""
+ from hub.services.models.cache_inventory import _cache_inventory_fields
+
+ fields = _cache_inventory_fields(
+ "distil-whisper/distil-large-v3",
+ "safetensors",
+ stt_only = True,
+ )
+ assert fields["capabilities"]["can_chat"] is False
+ assert fields["capabilities"]["supports_vision"] is False
+
+
+def test_a_wait_false_unload_rechecks_active_requests_under_the_lock():
+ """transcribe claims _active_requests while holding _lock, so a request starting between
+ the unlocked probe and the acquire would have llama-server killed underneath it."""
+ import threading
+
+ from core.inference.stt_mtmd_sidecar import MtmdSttSidecar
+
+ sidecar = MtmdSttSidecar.__new__(MtmdSttSidecar)
+ sidecar._lock = threading.RLock()
+ sidecar._active_requests = 0
+ sidecar._loading = False
+ sidecar.is_loading = lambda: False
+ sidecar.cancel_pending_load = lambda: False
+ sidecar.wait_for_load_to_settle = lambda: None
+ released = []
+ sidecar._release_locked = lambda: released.append(True)
+
+ # The racing transcription claims the slot after the unlocked probe has already passed.
+ real_lock = sidecar._lock
+
+ class _RacingLock:
+ def acquire(
+ self,
+ blocking = True,
+ *args,
+ **kwargs,
+ ):
+ sidecar._active_requests = 1
+ return real_lock.acquire(blocking, *args, **kwargs)
+
+ def release(self):
+ return real_lock.release()
+
+ sidecar._lock = _RacingLock()
+ MtmdSttSidecar.unload(sidecar, wait = False)
+ assert released == []
+
+
+def test_a_downloaded_switch_releases_the_old_engine_before_allocating(monkeypatch):
+ """Holding two engines across the load is what OOMs a device that fits either alone."""
+ from core.inference import stt_registry
+
+ order = []
+ monkeypatch.setattr(stt_registry, "_model_is_downloaded", lambda _e, _m: True)
+ monkeypatch.setattr(
+ stt_registry,
+ "unload",
+ lambda engines = None, wait = True: order.append(("unload", tuple(engines or ()))) or [],
+ )
+
+ class _Fake:
+ def load(
+ self,
+ model,
+ request_cancel_event = None,
+ ):
+ order.append(("load", model))
+
+ monkeypatch.setattr(stt_registry, "sidecar_for", lambda _engine: _Fake())
+ stt_registry.load("mtmd", "some/asr-model")
+
+ assert [step for step, _ in order] == ["unload", "load"]
+
+
+def test_an_undownloaded_switch_keeps_the_resident_engine_until_the_load_succeeds(monkeypatch):
+ """A 409 for a model that was never downloaded must not cost the engine in use."""
+ from core.inference import stt_registry
+
+ order = []
+ monkeypatch.setattr(stt_registry, "_model_is_downloaded", lambda _e, _m: False)
+ monkeypatch.setattr(
+ stt_registry,
+ "unload",
+ lambda engines = None, wait = True: order.append(("unload", tuple(engines or ()))) or [],
+ )
+
+ class _Fake:
+ def load(
+ self,
+ model,
+ request_cancel_event = None,
+ ):
+ order.append(("load", model))
+
+ monkeypatch.setattr(stt_registry, "sidecar_for", lambda _engine: _Fake())
+ stt_registry.load("mtmd", "some/asr-model")
+
+ assert [step for step, _ in order] == ["load", "unload"]
+
+
+def _racing_sidecar():
+ """An MtmdSttSidecar stripped to the fields unload() touches."""
+ import threading
+
+ from core.inference.stt_mtmd_sidecar import MtmdSttSidecar
+
+ sidecar = MtmdSttSidecar.__new__(MtmdSttSidecar)
+ sidecar._lock = threading.RLock()
+ sidecar._active_requests = 0
+ sidecar._loading = False
+ sidecar.is_loading = lambda: False
+ sidecar.cancel_pending_load = lambda: False
+ sidecar.wait_for_load_to_settle = lambda: None
+ sidecar.released = []
+ sidecar._release_locked = lambda: sidecar.released.append(True)
+ return sidecar
+
+
+def test_a_blocking_unload_drains_a_request_that_started_during_the_acquire():
+ """The under-lock recheck only guarded wait=False, so the blocking unload training
+ uses could reap llama-server underneath a transcription that had just started, losing
+ the recording rather than honoring the drain window."""
+ import threading
+
+ from core.inference.stt_mtmd_sidecar import MtmdSttSidecar
+
+ sidecar = _racing_sidecar()
+ real_lock = sidecar._lock
+ acquires = []
+
+ class _RacingLock:
+ def acquire(
+ self,
+ blocking = True,
+ *args,
+ **kwargs,
+ ):
+ acquires.append(True)
+ if len(acquires) == 1:
+ # Claimed after the unlocked drain has already passed.
+ sidecar._active_requests = 1
+ threading.Timer(0.15, lambda: setattr(sidecar, "_active_requests", 0)).start()
+ return real_lock.acquire(blocking, *args, **kwargs)
+
+ def release(self):
+ return real_lock.release()
+
+ sidecar._lock = _RacingLock()
+ MtmdSttSidecar.unload(sidecar, wait = True)
+ # Released, but only once the transcription that raced in had finished.
+ assert sidecar.released == [True]
+ assert len(acquires) >= 2
+ assert sidecar._active_requests == 0
+
+
+def test_a_blocking_unload_still_gives_up_after_the_drain_window(monkeypatch):
+ """Training claiming the VRAM cannot wait forever, so a request that never finishes
+ must not turn the bounded window into a permanent block."""
+ from core.inference import stt_mtmd_sidecar
+ from core.inference.stt_mtmd_sidecar import MtmdSttSidecar
+
+ monkeypatch.setattr(stt_mtmd_sidecar, "_ACTIVE_REQUEST_DRAIN_TIMEOUT", 0.3)
+ sidecar = _racing_sidecar()
+ sidecar._active_requests = 1
+ MtmdSttSidecar.unload(sidecar, wait = True)
+ assert sidecar.released == [True]
+
+
+def test_an_implicit_transcribe_load_releases_the_other_engines(monkeypatch):
+ """Each sidecar loads its own model, but only the registry frees the others.
+
+ An API client alternating between engines through /v1/audio/transcriptions never
+ calls /audio/stt/load, so without this both models stayed resident until their
+ independent idle timers fired, which OOMs a device that fits either alone.
+ """
+ import asyncio
+
+ import routes.inference as ri
+
+ loaded: list[tuple] = []
+ monkeypatch.setattr(ri, "_resolve_serving_stt_engine", lambda engine: "mtmd")
+ monkeypatch.setattr(
+ ri,
+ "_stt_sidecar_for",
+ lambda engine: type(
+ "S",
+ (),
+ {"transcribe": staticmethod(lambda *a, **k: {"text": "hi", "model": "qwen3-asr-0.6b"})},
+ )(),
+ )
+ monkeypatch.setattr(
+ ri,
+ "_stt_lifecycle",
+ lambda: (lambda model, engine, cancel = None: loaded.append((model, engine)), lambda *a: []),
+ )
+
+ result = asyncio.run(
+ ri._transcribe_audio_result(
+ b"audio",
+ model = "qwen3-asr-0.6b",
+ language = None,
+ fast = True,
+ engine = "mtmd",
+ )
+ )
+ assert result["text"] == "hi"
+ assert loaded == [("qwen3-asr-0.6b", "mtmd")]
+
+
+def test_the_registry_load_is_what_frees_the_other_engines(monkeypatch):
+ """The lifecycle the route calls is the registry's, whose contract is single
+ residency; this pins that it releases the others rather than only allocating."""
+ from core.inference import stt_registry
+
+ released: list = []
+ monkeypatch.setattr(stt_registry, "_model_is_downloaded", lambda engine, model: True)
+ monkeypatch.setattr(
+ stt_registry, "unload", lambda engines, wait = True: released.append(list(engines))
+ )
+ monkeypatch.setattr(
+ stt_registry,
+ "sidecar_for",
+ lambda engine: type("S", (), {"load": staticmethod(lambda *a, **k: None)})(),
+ )
+
+ stt_registry.load("qwen3-asr-0.6b", "mtmd")
+ assert released and "mtmd" not in released[0]
+ assert set(released[0]) == {e for e in stt_registry.STT_ENGINES if e != "mtmd"}
+
+
+def test_a_scoped_unload_leaves_another_surfaces_newer_model_alone():
+ """Ownership is decided by the caller, so a queued Eject can arrive after another
+ surface switched the same engine. The comparison happens under the sidecar's own
+ lock, which is the only place the answer cannot go stale."""
+ import threading
+
+ from core.inference.stt_sidecar import WhisperSttSidecar
+
+ sidecar = WhisperSttSidecar.__new__(WhisperSttSidecar)
+ sidecar._lock = threading.RLock()
+ sidecar._model_id = "base"
+ released = []
+ sidecar._release_engine_locked = lambda: released.append(True)
+
+ # The caller owned "small"; "base" belongs to whoever loaded it after.
+ WhisperSttSidecar.unload(sidecar, expected_model = "small")
+ assert released == []
+
+ # Its own model still goes, and so does an unscoped release.
+ WhisperSttSidecar.unload(sidecar, expected_model = "base")
+ assert released == [True]
+ WhisperSttSidecar.unload(sidecar)
+ assert released == [True, True]
+
+
+def test_a_scoped_unload_accepts_the_short_key_the_client_sends():
+ """Clients name the sidecar key ("small"), which the sidecar stores resolved."""
+ import threading
+
+ from core.inference.stt_sidecar import WhisperSttSidecar, resolve_model_id
+
+ sidecar = WhisperSttSidecar.__new__(WhisperSttSidecar)
+ sidecar._lock = threading.RLock()
+ sidecar._model_id = resolve_model_id("small")
+ released = []
+ sidecar._release_engine_locked = lambda: released.append(True)
+
+ WhisperSttSidecar.unload(sidecar, expected_model = "small")
+ assert released == [True]
+
+
+def test_the_registry_passes_the_claimed_model_to_each_sidecar(monkeypatch):
+ from core.inference import stt_registry
+
+ seen: list[tuple] = []
+ monkeypatch.setattr(
+ stt_registry,
+ "sidecar_for",
+ lambda engine: type(
+ "S",
+ (),
+ {
+ "unload": staticmethod(
+ lambda wait = True, expected_model = None: seen.append((engine, expected_model))
+ )
+ },
+ )(),
+ )
+ stt_registry.unload(["gguf"], expected_model = "small")
+ assert seen == [("gguf", "small")]
diff --git a/studio/backend/tests/test_stt_review_fixes.py b/studio/backend/tests/test_stt_review_fixes.py
deleted file mode 100644
index 2376b25c6a6..00000000000
--- a/studio/backend/tests/test_stt_review_fixes.py
+++ /dev/null
@@ -1,224 +0,0 @@
-# SPDX-License-Identifier: AGPL-3.0-only
-# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-
-"""Regressions for a fresh review pass on the local STT dictation feature:
-
-1. Curated GGUF dictation repos (unslothai/whisper-*-GGUF) must be hidden from
- chat pickers, not just their Transformers safetensors companions.
-2. The GGUF sidecar's loaded_model/device status accessors must be lock-free so
- they never block behind an in-flight transcription (which holds self._lock).
-3. A "gguf" unload on a host without whisper-server must target the Transformers
- fallback that actually served it, and unload-all must attempt both backends
- even if one raises.
-4. free_stt_model_for_training must free the GGUF sidecar even when the
- Transformers unload raises (independent exception boundaries).
-"""
-
-from __future__ import annotations
-
-import asyncio
-import sys
-import threading
-from pathlib import Path
-
-import pytest
-from fastapi import HTTPException
-
-_BACKEND_ROOT = Path(__file__).resolve().parents[1]
-if str(_BACKEND_ROOT) not in sys.path:
- sys.path.insert(0, str(_BACKEND_ROOT))
-
-
-# 1. Hidden-model GGUF companions ------------------------------------------------
-def test_curated_gguf_dictation_repos_are_hidden():
- from utils.hidden_models import _HIDDEN_STT_REPO_IDS, is_hidden_model
- for repo in (
- "unslothai/whisper-tiny-GGUF",
- "unslothai/whisper-base-GGUF",
- "unslothai/whisper-small-GGUF",
- "unslothai/whisper-large-v3-turbo-GGUF",
- "unslothai/whisper-large-v3-GGUF",
- ):
- assert repo in _HIDDEN_STT_REPO_IDS
- assert is_hidden_model(repo) is True
- # Case-insensitive, matching how the cache stores the repo id.
- assert is_hidden_model(repo.lower()) is True
-
- # A same-prefix but genuinely different repo is NOT hidden.
- assert is_hidden_model("unslothai/whisper-large-v3-GGUF-finetune") is False
-
-
-# 2. GGUF status accessors are lock-free ----------------------------------------
-def test_gguf_status_accessors_do_not_block_on_the_inference_lock():
- from core.inference.stt_ggml_sidecar import GgmlSttSidecar
-
- sidecar = GgmlSttSidecar()
-
- class _AliveProc:
- pid = 4321
-
- def poll(self):
- return None # still running
-
- sidecar._process = _AliveProc()
- sidecar._model_id = "small"
-
- holder_has_lock = threading.Event()
- release = threading.Event()
-
- def _hold_inference_lock():
- # Mimic transcribe() holding self._lock across the whole HTTP call.
- with sidecar._lock:
- holder_has_lock.set()
- release.wait(timeout = 5)
-
- holder = threading.Thread(target = _hold_inference_lock)
- holder.start()
- assert holder_has_lock.wait(timeout = 5)
-
- result: dict = {}
-
- def _read_status():
- result["model"] = sidecar.loaded_model
- result["device"] = sidecar.device
-
- reader = threading.Thread(target = _read_status)
- reader.start()
- reader.join(timeout = 2)
- blocked = reader.is_alive()
-
- release.set()
- holder.join(timeout = 5)
- reader.join(timeout = 5)
-
- assert not blocked, "loaded_model/device blocked on self._lock (should be lock-free)"
- assert result == {"model": "small", "device": "whisper.cpp"}
-
-
-def test_process_alive_snapshots_process_against_concurrent_unload():
- # _process_alive() must read self._process exactly once. The lock-free
- # readers (loaded_model/device) can run while unload() nulls self._process;
- # the old `self._process is not None and self._process.poll() is None` read it
- # twice, so a null landing between the two reads called None.poll(). A
- # property that yields the live process on the first read and None afterwards
- # reproduces that interleaving deterministically.
- from core.inference.stt_ggml_sidecar import GgmlSttSidecar
-
- class _AliveProc:
- def poll(self):
- return None # still running
-
- live = _AliveProc()
- reads = {"n": 0}
-
- class _RacingSidecar(GgmlSttSidecar):
- @property
- def _process(self):
- reads["n"] += 1
- return live if reads["n"] == 1 else None
-
- @_process.setter
- def _process(self, value):
- pass # __init__ assigns None; the property drives the read
-
- sidecar = GgmlSttSidecar()
- sidecar.__class__ = _RacingSidecar # data descriptor wins over the instance attr
-
- # Snapshot fix: exactly one read, no AttributeError from a second None read.
- assert sidecar._process_alive() is True
- assert reads["n"] == 1
-
-
-# 3. Unload resolves through the serving engine + attempts every backend ---------
-def test_gguf_unload_targets_transformers_fallback_without_whisper_server(monkeypatch):
- import core.inference.stt_ggml_sidecar as ggml_module
- import routes.inference as ri
-
- monkeypatch.setattr(ggml_module, "is_available", lambda: False) # no whisper-server
-
- calls: list = []
-
- class _Sidecar:
- def __init__(self, name):
- self.name = name
-
- def unload(self):
- calls.append(self.name)
-
- from core.inference import stt_registry
-
- monkeypatch.setattr(stt_registry, "sidecar_for", lambda name: _Sidecar(name))
-
- resp = asyncio.run(ri.stt_unload(engine = "gguf", current_subject = "tester"))
- assert resp.status_code == 200
- # gguf is served by the Transformers fallback here, so that is what unloads.
- assert calls == ["transformers"]
-
-
-def test_unload_all_attempts_every_backend_even_when_one_fails(monkeypatch):
- import routes.inference as ri
-
- attempted: list = []
-
- class _Sidecar:
- def __init__(self, name):
- self.name = name
-
- def unload(self):
- attempted.append(self.name)
- if self.name == "transformers":
- raise RuntimeError("boom")
-
- from core.inference import stt_registry
-
- monkeypatch.setattr(stt_registry, "sidecar_for", lambda name: _Sidecar(name))
-
- with pytest.raises(HTTPException) as excinfo:
- asyncio.run(ri.stt_unload(engine = None, current_subject = "tester"))
-
- assert excinfo.value.status_code == 500
- # The later engines are still attempted after transformers raised. mtmd is
- # included so an Unload with no engine frees a resident llama-server too.
- assert attempted == ["transformers", "gguf", "mtmd"]
-
-
-# 4. free_stt_model_for_training isolates the two backends -----------------------
-def test_free_stt_frees_gguf_even_when_transformers_unload_raises(monkeypatch):
- import routes.training_vram as tv
-
- class _TransformersSidecar:
- def is_loading(self):
- return False
-
- @property
- def loaded_model(self):
- return "whisper-small"
-
- def unload(self):
- raise RuntimeError("transformers unload failed")
-
- class _GgmlSidecar:
- def __init__(self):
- self.unloaded = False
-
- def is_loading(self):
- return False
-
- @property
- def loaded_model(self):
- return None if self.unloaded else "small"
-
- def unload(self):
- self.unloaded = True
-
- ggml = _GgmlSidecar()
- monkeypatch.setattr(
- "core.inference.stt_sidecar.get_stt_sidecar", lambda: _TransformersSidecar()
- )
- monkeypatch.setattr("core.inference.stt_ggml_sidecar.get_ggml_stt_sidecar", lambda: ggml)
-
- freed = tv.free_stt_model_for_training("test")
-
- # The Transformers failure must not skip GGUF eviction.
- assert ggml.unloaded is True
- assert any("small" in entry for entry in freed)
diff --git a/studio/backend/tests/test_stt_review_fixes_4.py b/studio/backend/tests/test_stt_review_fixes_4.py
deleted file mode 100644
index 3853138d18b..00000000000
--- a/studio/backend/tests/test_stt_review_fixes_4.py
+++ /dev/null
@@ -1,393 +0,0 @@
-# SPDX-License-Identifier: AGPL-3.0-only
-# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-
-"""Fourth review pass: status reads that must never block, and the PID registry.
-
-The status route reads these sidecars on the event loop, so everything it touches
-has to answer while a lifecycle operation holds the sidecar's lock.
-"""
-
-import subprocess
-import threading
-import time
-
-import pytest
-
-from core.inference import stt_ggml_sidecar as ggml_mod
-from core.inference import stt_mtmd_sidecar as mtmd_mod
-from core.inference.stt_mtmd_sidecar import MtmdSttSidecar
-
-
-class _SlowlyDyingProcess:
- """A child whose reap blocks, like a llama-server that is slow to exit."""
-
- def __init__(self, release: threading.Event):
- self.pid = 4242
- self._release = release
- self._returncode = None
-
- def poll(self):
- return self._returncode
-
- def terminate(self):
- pass
-
- def wait(self, timeout = None):
- # Blocks until the test lets go, like a server slow to release its port and VRAM.
- if not self._release.wait(timeout = timeout):
- raise subprocess.TimeoutExpired("llama-server", timeout)
- self._returncode = -15
- return self._returncode
-
- def kill(self):
- self._returncode = -9
-
-
-def _resident(sidecar: MtmdSttSidecar, process) -> None:
- """Publish `process` as the loaded server, as a finished load would."""
- sidecar._process = process
- sidecar._port = 12345
- sidecar._model_id = "qwen3-asr-0.6b"
-
-
-def test_status_reads_do_not_block_behind_a_reap(monkeypatch):
- """loaded_model/device/is_loading answer while unload() reaps under _lock.
-
- The event loop and training admission both read these, so neither can wait
- on a dying server.
- """
- monkeypatch.setattr(mtmd_mod, "forget_pid", lambda pid: None)
- sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
- release = threading.Event()
- _resident(sidecar, _SlowlyDyingProcess(release))
-
- unloading = threading.Thread(target = sidecar.unload, daemon = True)
- unloading.start()
- try:
- # Give unload() time to take _lock and block inside _reap().
- time.sleep(0.2)
- answered = threading.Event()
-
- def read_status():
- sidecar.loaded_model
- sidecar.device
- sidecar.is_loading()
- answered.set()
-
- threading.Thread(target = read_status, daemon = True).start()
- assert answered.wait(
- timeout = 5
- ), "a status read blocked behind the reap; the event loop would stall with it"
- finally:
- release.set()
- unloading.join(timeout = 10)
-
-
-def test_a_reaping_server_stays_visible_to_training_admission(monkeypatch):
- """A dying llama-server still holds VRAM, so it must still read as resident.
-
- Clearing the fields before the reap would let summarize_resident_stt() report
- nothing while the process is alive, and training would start into its memory.
- """
- monkeypatch.setattr(mtmd_mod, "forget_pid", lambda pid: None)
- sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
- release = threading.Event()
- _resident(sidecar, _SlowlyDyingProcess(release))
-
- seen = {}
-
- def unload():
- sidecar.unload()
-
- unloading = threading.Thread(target = unload, daemon = True)
- unloading.start()
- try:
- time.sleep(0.2) # inside the reap
- seen["model"] = sidecar.loaded_model
- seen["device"] = sidecar.device
- finally:
- release.set()
- unloading.join(timeout = 10)
-
- assert (
- seen["model"] == "qwen3-asr-0.6b"
- ), "the reaping server read as gone; training admission would miss its VRAM"
- assert seen["device"] == "llama.cpp"
- # Once the reap is done the fields are cleared, so it reads as gone.
- assert sidecar.loaded_model is None
- assert sidecar._process is None
-
-
-def test_a_starting_load_is_announced_before_the_probe_and_the_reap():
- """is_loading() has to be true across the cache probe and the old reap.
-
- Training admission reads it lock-free, so a False there sends it to unload(),
- which waits out the whole startup instead of cancelling the load.
- """
- sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
- probing = threading.Event()
- release = threading.Event()
-
- def slow_probe(model_id):
- probing.set()
- release.wait(timeout = 10)
- raise RuntimeError("the probe is where the test stops")
-
- sidecar._ensure_model_downloaded = slow_probe
-
- def load():
- try:
- sidecar._load_locked("qwen3-asr-0.6b", "llama-server")
- except Exception:
- pass
-
- loading = threading.Thread(target = load, daemon = True)
- loading.start()
- try:
- assert probing.wait(timeout = 5)
- assert sidecar.is_loading() is True, "the load was not announced before the probe"
- assert sidecar.cancel_pending_load() is True, "training could not cancel this load"
- finally:
- release.set()
- loading.join(timeout = 10)
- # The load never started a server, so it must not leave _loading set.
- assert sidecar.is_loading() is False
- assert sidecar._load_cancel_event is None
-
-
-def test_device_never_contradicts_the_loaded_model():
- """Mid-publish _process is set and _model_id is not; the two must agree."""
- sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
- sidecar._process = _SlowlyDyingProcess(threading.Event())
- sidecar._port = 12345
- sidecar._model_id = None
- assert sidecar.loaded_model is None
- assert sidecar.device is None, "the status route would ship a device with no model"
-
-
-def test_status_reads_do_not_block_during_a_llama_cpp_update():
- """update_maintenance() holds _lock for the whole install; polls continue."""
- sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
- with sidecar.update_maintenance():
- answered = threading.Event()
-
- def read_status():
- sidecar.loaded_model
- sidecar.is_loading()
- answered.set()
-
- threading.Thread(target = read_status, daemon = True).start()
- assert answered.wait(
- timeout = 5
- ), "a status read blocked for the length of the llama.cpp install"
-
-
-def test_ggml_download_drops_its_adopted_pid(monkeypatch, tmp_path):
- """spawn_download() adopts a PID; left adopted it can be reused, and
- terminate_all would then signal whatever inherited it.
- """
- forgotten = []
-
- # Once metadata resolves, _run() prepares the repo's cache for HTTP before it
- # reaches the stubbed worker, and that writes: it creates the repo directory and
- # a .transport marker. The session conftest deliberately pins HF_HUB_CACHE to the
- # developer's real cache, so without a cache of its own this test edits it.
- monkeypatch.setenv("HF_HUB_CACHE", str(tmp_path / "hub"))
-
- class _Finished:
- pid = 7777
- returncode = 0
-
- def poll(self):
- return 0
-
- monkeypatch.setattr(ggml_mod, "_cached_model_path", lambda model_id: None)
- # _run() opens with a HEAD to the Hub for the size and etag. It is best-effort and
- # swallows its own errors, but leaving it live makes this test depend on a network
- # round trip it does not care about, so answer it locally.
- import huggingface_hub
-
- class _Metadata:
- """Stands in for HfFileMetadata; unset fields read as None, as they may on the Hub.
-
- ``commit_hash`` has to be a real-looking sha: _run() pins the download to an
- immutable revision and refuses anything that is not one.
- """
-
- size = 1
- etag = "stub"
- commit_hash = "0" * 40
-
- def __getattr__(self, _name):
- return None
-
- monkeypatch.setattr(
- huggingface_hub, "get_hf_file_metadata", lambda *a, **k: _Metadata(), raising = False
- )
- import core.inference.stt_download_worker as worker_mod
-
- monkeypatch.setattr(worker_mod, "spawn_download", lambda *a, **k: _Finished())
- monkeypatch.setattr(
- worker_mod, "reap_download", lambda process: forgotten.append(process.pid) or b""
- )
- state = ggml_mod._GgmlDownloadState()
- state._run("tiny", None)
-
- assert forgotten == [7777], "the GGUF download never dropped its adopted PID"
-
-
-def test_wait_for_server_sleeps_on_a_non_200_success(monkeypatch):
- """A 2xx that is not 200 must not spin the readiness loop with no delay."""
-
- class _Response:
- status = 204
-
- def __enter__(self):
- return self
-
- def __exit__(self, *exc):
- return False
-
- slept = []
- monkeypatch.setattr(mtmd_mod.urllib.request, "urlopen", lambda *a, **k: _Response())
- monkeypatch.setattr(mtmd_mod.time, "sleep", slept.append)
- monkeypatch.setattr(mtmd_mod, "_SERVER_START_TIMEOUT_SECONDS", 0.5)
-
- class _Alive:
- def poll(self):
- return None
-
- assert MtmdSttSidecar._wait_for_server(_Alive(), 1234) is False
- assert slept, "the readiness loop spun without sleeping on a non-200 response"
-
-
-def test_download_probe_is_memoised_then_dropped_when_a_download_ends(monkeypatch):
- """The status poll asks four times a second; the cache walk runs once."""
- mtmd_mod._forget_downloaded_probe()
- calls = []
-
- def fake_paths(model_id):
- calls.append(model_id)
- return ("m.gguf", "p.gguf")
-
- monkeypatch.setattr(mtmd_mod, "_cached_model_paths", fake_paths)
- assert mtmd_mod.is_model_downloaded("qwen3-asr-0.6b") is True
- assert mtmd_mod.is_model_downloaded("qwen3-asr-0.6b") is True
- assert len(calls) == 1, "the memo did not spare the second probe"
-
- # A finished download changes the disk, so the answer is dropped, not left to expire.
- mtmd_mod._forget_downloaded_probe("qwen3-asr-0.6b")
- assert mtmd_mod.is_model_downloaded("qwen3-asr-0.6b") is True
- assert len(calls) == 2
-
- mtmd_mod._forget_downloaded_probe()
-
-
-def test_download_probe_expires(monkeypatch):
- """A cache emptied outside Studio is noticed without a restart."""
- mtmd_mod._forget_downloaded_probe()
- monkeypatch.setattr(mtmd_mod, "_DOWNLOADED_PROBE_TTL_SECONDS", 0.0)
- calls = []
-
- def fake_paths(model_id):
- calls.append(model_id)
- return None
-
- monkeypatch.setattr(mtmd_mod, "_cached_model_paths", fake_paths)
- assert mtmd_mod.is_model_downloaded("qwen3-asr-0.6b") is False
- assert mtmd_mod.is_model_downloaded("qwen3-asr-0.6b") is False
- assert len(calls) == 2, "an expired entry was still served"
-
- mtmd_mod._forget_downloaded_probe()
-
-
-def test_an_invalidation_mid_probe_discards_the_stale_answer(monkeypatch):
- """A download finishing under a probe must not be undone by that probe.
-
- The probe runs outside the lock, so it can write a stale False back over the
- download's invalidation, and the model then reads as missing for a whole TTL.
- """
- mtmd_mod._forget_downloaded_probe()
-
- def probe_then_invalidate(model_id):
- # The download completing while this probe is in flight.
- mtmd_mod._forget_downloaded_probe(model_id)
- return None
-
- monkeypatch.setattr(mtmd_mod, "_cached_model_paths", probe_then_invalidate)
- assert mtmd_mod.is_model_downloaded("qwen3-asr-0.6b") is False
- with mtmd_mod._downloaded_probe_lock:
- assert (
- "qwen3-asr-0.6b" not in mtmd_mod._downloaded_probe
- ), "a stale answer was written back over the invalidation"
-
- # The next poll sees the finished download rather than waiting out the TTL.
- monkeypatch.setattr(mtmd_mod, "_cached_model_paths", lambda mid: ("m.gguf", "p.gguf"))
- assert mtmd_mod.is_model_downloaded("qwen3-asr-0.6b") is True
- mtmd_mod._forget_downloaded_probe()
-
-
-def test_the_entry_is_timestamped_after_the_probe(monkeypatch):
- """A slow cache must not store an entry that is already near expiry."""
- mtmd_mod._forget_downloaded_probe()
- clock = {"t": 1000.0}
- monkeypatch.setattr(mtmd_mod.time, "monotonic", lambda: clock["t"])
-
- def slow_probe(model_id):
- clock["t"] += 1.5 # probe takes most of the TTL
- return ("m.gguf", "p.gguf")
-
- monkeypatch.setattr(mtmd_mod, "_cached_model_paths", slow_probe)
- assert mtmd_mod.is_model_downloaded("qwen3-asr-0.6b") is True
-
- with mtmd_mod._downloaded_probe_lock:
- stored_at = mtmd_mod._downloaded_probe["qwen3-asr-0.6b"][0]
- assert stored_at == 1001.5, "the entry was timestamped before the probe ran"
-
- # The panel's next poll, 750ms later, is still served from the memo.
- clock["t"] += 0.75
- called = []
- monkeypatch.setattr(mtmd_mod, "_cached_model_paths", lambda mid: called.append(mid))
- assert mtmd_mod.is_model_downloaded("qwen3-asr-0.6b") is True
- assert called == [], "the entry expired early and the probe ran again"
- mtmd_mod._forget_downloaded_probe()
-
-
-def test_unknown_model_is_never_memoised(monkeypatch):
- called = []
- monkeypatch.setattr(mtmd_mod, "_cached_model_paths", lambda model_id: called.append(model_id))
- assert mtmd_mod.is_model_downloaded("not-a-model") is False
- assert called == []
-
-
-def test_download_status_reports_progress_without_holding_the_lock():
- """_downloaded_bytes() stats the cache; a cancel must not queue behind it."""
- state = mtmd_mod._MtmdDownloadState()
- observed = []
-
- def slow_downloaded_bytes(*_args, **_kwargs):
- # The lock must be free while this runs.
- observed.append(state._lock.acquire(blocking = False))
- if observed[-1]:
- state._lock.release()
- return 1
-
- state._downloaded_bytes = slow_downloaded_bytes
- state._model_id = "qwen3-asr-0.6b"
- state._thread = threading.Thread(target = lambda: time.sleep(0.5), daemon = True)
- state._thread.start()
- try:
- status = state.status()
- finally:
- state._thread.join(timeout = 5)
-
- assert status["bytes_done"] == 1
- assert observed == [True], "progress was computed while holding the download lock"
-
-
[email protected]("model_id", sorted(mtmd_mod.MTMD_STT_MODELS))
-def test_catalogue_probes_stay_answerable(model_id):
- """is_model_downloaded() never raises for a curated id, cache or no cache."""
- mtmd_mod._forget_downloaded_probe()
- assert isinstance(mtmd_mod.is_model_downloaded(model_id), bool)
- mtmd_mod._forget_downloaded_probe()
diff --git a/studio/backend/tests/test_stt_sidecar.py b/studio/backend/tests/test_stt_sidecar.py
index f6ab3abd07f..36094d536e1 100644
--- a/studio/backend/tests/test_stt_sidecar.py
+++ b/studio/backend/tests/test_stt_sidecar.py
@@ -46,7 +46,8 @@ def stub_audio_decoder(monkeypatch):
monkeypatch.setattr(
stt_sidecar_module,
"_decode_audio_bounded",
- lambda _audio: np.zeros(8000, dtype = np.float32),
+ # Second arg is the cancel event the real decoder polls in its frame loop.
+ lambda _audio, _cancel_event = None: np.zeros(8000, dtype = np.float32),
)
monkeypatch.setattr(
"huggingface_hub.snapshot_download",
@@ -1199,6 +1200,9 @@ def test_download_status_is_idle_before_any_download():
"model": None,
"error": None,
"cancelled": False,
+ # Only set alongside cancelled: "model" goes None once the download thread stops, so
+ # this is what tells a settled cancellation from an unrelated one.
+ "cancelled_model": None,
"bytes_total": None,
"bytes_done": None,
}
@@ -1336,3 +1340,22 @@ def test_cpu_retry_releases_failed_accelerator_load(monkeypatch):
# its accelerator memory stays stranded for the whole retry.
assert seen["alive_during_retry"] is False
assert sidecar.device == "cpu"
+
+
+def test_decoding_stops_as_soon_as_the_request_is_cancelled(monkeypatch):
+ """Checking only after the decode returned let an abandoned upload run to EOF or the
+ 30-minute cap, and several could do that at once."""
+ import threading
+
+ monkeypatch.setattr(stt_sidecar_module, "_decode_audio_bounded", _REAL_DECODE_AUDIO_BOUNDED)
+ buf = io.BytesIO()
+ with wave.open(buf, "wb") as w:
+ w.setnchannels(1)
+ w.setsampwidth(2)
+ w.setframerate(16000)
+ w.writeframes((np.zeros(16000 * 5, dtype = np.int16)).tobytes())
+
+ cancelled = threading.Event()
+ cancelled.set()
+ with pytest.raises(stt_sidecar_module.SttTranscriptionCancelledError):
+ stt_sidecar_module._decode_audio_bounded(buf.getvalue(), cancelled)
diff --git a/studio/backend/tests/test_stt_transcription_cancellation.py b/studio/backend/tests/test_stt_transcription_cancellation.py
new file mode 100644
index 00000000000..34160f8329f
--- /dev/null
+++ b/studio/backend/tests/test_stt_transcription_cancellation.py
@@ -0,0 +1,280 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+import asyncio
+import socket
+import threading
+
+import pytest
+from fastapi import HTTPException
+
+import routes.inference as inference_route
+from core.inference import stt_ggml_sidecar as ggml_module
+from core.inference import stt_mtmd_sidecar as mtmd_module
+from core.inference import stt_sidecar as stt_module
+from core.inference.stt_ggml_sidecar import GgmlSttSidecar
+from core.inference.stt_mtmd_sidecar import MtmdSttSidecar
+from core.inference.stt_sidecar import (
+ SttLoadCancelledError,
+ SttTranscriptionCancelledError,
+ WhisperSttSidecar,
+)
+
+
+def test_transformers_load_inherits_disconnect_before_registration(monkeypatch):
+ # The load reaches `import torch` before it registers, so a runner without torch
+ # cannot exercise this at all (the cross-platform jobs have no torch wheel).
+ pytest.importorskip("torch")
+ owner = threading.Event()
+ sidecar = WhisperSttSidecar()
+ resident = object()
+ sidecar._engine = resident
+ sidecar._model_id = "tiny"
+ sidecar._device = "cpu"
+ monkeypatch.setattr(
+ stt_module,
+ "ensure_stt_available",
+ lambda: sidecar.cancel_transcription(owner),
+ )
+ monkeypatch.setattr(
+ sidecar,
+ "_ensure_model_downloaded",
+ lambda _model: pytest.fail("cancelled load reached its cached checkpoint"),
+ )
+
+ with pytest.raises(SttLoadCancelledError):
+ sidecar.load("small", owner)
+ assert sidecar.is_loading() is False
+ assert sidecar._engine is resident
+ assert sidecar.loaded_model == "tiny"
+
+
+def test_ggml_load_inherits_disconnect_before_registration(monkeypatch):
+ class _Reservation:
+ def close(self):
+ pass
+
+ owner = threading.Event()
+ sidecar = GgmlSttSidecar()
+ sidecar._model_id = "base"
+
+ def disconnect_during_engine_probe():
+ sidecar.cancel_transcription(owner)
+ return "whisper-server"
+
+ monkeypatch.setattr(ggml_module, "ensure_engine_available", disconnect_during_engine_probe)
+ monkeypatch.setattr(sidecar, "_process_alive", lambda: True)
+ monkeypatch.setattr(sidecar, "_ensure_model_downloaded", lambda _model: "model.gguf")
+ monkeypatch.setattr(
+ sidecar,
+ "_release_locked",
+ lambda: pytest.fail("cancelled load evicted the resident GGUF model"),
+ )
+ monkeypatch.setattr(sidecar, "_reserve_free_port", lambda: (_Reservation(), 12345))
+ monkeypatch.setattr(ggml_module, "_whisper_install_marker", lambda _binary: None)
+ monkeypatch.setattr(
+ ggml_module.subprocess,
+ "Popen",
+ lambda *_args, **_kwargs: pytest.fail("cancelled load spawned whisper-server"),
+ )
+
+ with pytest.raises(SttLoadCancelledError):
+ sidecar.load("tiny", owner)
+ assert sidecar.is_loading() is False
+
+
+def test_mtmd_load_inherits_disconnect_before_registration(monkeypatch):
+ owner = threading.Event()
+ sidecar = MtmdSttSidecar()
+
+ def disconnect_during_training_check():
+ sidecar.cancel_transcription(owner)
+ return False
+
+ monkeypatch.setattr(mtmd_module, "ensure_engine_available", lambda: "llama-server")
+ monkeypatch.setattr(mtmd_module, "_training_active", disconnect_during_training_check)
+ monkeypatch.setattr(sidecar, "_process_alive", lambda: False)
+ monkeypatch.setattr(
+ sidecar,
+ "_ensure_model_downloaded",
+ lambda _model: pytest.fail("cancelled load reached its cached checkpoint"),
+ )
+
+ with pytest.raises(SttLoadCancelledError):
+ sidecar.load("qwen3-asr-0.6b", owner)
+ assert sidecar.is_loading() is False
+
+
+def test_disconnected_load_cancels_only_its_request_event(monkeypatch):
+ class _DisconnectedRequest:
+ async def is_disconnected(self):
+ return True
+
+ sidecar = WhisperSttSidecar()
+ sibling_owner = threading.Event()
+ sibling_load_cancel = threading.Event()
+ with sidecar._load_state_lock:
+ sidecar._loading = True
+ sidecar._load_cancel_event = sibling_load_cancel
+ sidecar._load_owner_cancel_event = sibling_owner
+ cancelled_request = None
+
+ def load(_model, _engine, request_cancel_event):
+ nonlocal cancelled_request
+ cancelled_request = request_cancel_event
+ assert request_cancel_event.wait(1), "disconnect must cancel this load request"
+ assert not sibling_load_cancel.is_set(), "another caller's startup was cancelled"
+ raise SttLoadCancelledError("STT load cancelled.")
+
+ monkeypatch.setattr(inference_route, "_stt_sidecar_for", lambda _engine: sidecar)
+ monkeypatch.setattr(inference_route, "_stt_lifecycle", lambda: (load, None))
+ monkeypatch.setattr(
+ inference_route,
+ "_resolve_serving_stt_engine",
+ lambda _engine: "transformers",
+ )
+
+ with pytest.raises(HTTPException) as raised:
+ asyncio.run(
+ inference_route.stt_load(
+ inference_route.SttLoadRequest(model = "small", engine = "transformers"),
+ _DisconnectedRequest(),
+ "test-subject",
+ )
+ )
+
+ assert raised.value.status_code == 409
+ assert cancelled_request is not None and cancelled_request.is_set()
+ assert not sibling_load_cancel.is_set()
+
+
+def test_disconnected_raw_transcription_cancels_its_sidecar(monkeypatch):
+ class _DisconnectedRequest:
+ async def is_disconnected(self):
+ return True
+
+ class _Sidecar:
+ cancelled = False
+
+ def cancel_transcription(self, cancel_event):
+ self.cancelled = True
+ cancel_event.set()
+ return True
+
+ def transcribe(self, _raw, _model, _language, _fast, cancel_event):
+ assert cancel_event.wait(1), "disconnect must reach the sidecar"
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
+
+ sidecar = _Sidecar()
+ monkeypatch.setattr(inference_route, "_stt_sidecar_for", lambda _engine: sidecar)
+ monkeypatch.setattr(
+ inference_route,
+ "_resolve_serving_stt_engine",
+ lambda _engine: "transformers",
+ )
+
+ with pytest.raises(HTTPException) as raised:
+ asyncio.run(
+ inference_route._transcribe_audio_result(
+ b"RIFFfake",
+ "small",
+ None,
+ True,
+ "transformers",
+ _DisconnectedRequest(),
+ )
+ )
+
+ assert raised.value.status_code == 499
+ assert sidecar.cancelled is True
+
+
+def test_server_cancel_watcher_abandons_the_request_and_keeps_the_server():
+ """A cancel used to SIGTERM whisper-server, so the next dictation paid a full relaunch."""
+ from core.inference.stt_sidecar import _close_connection_on_cancel
+
+ class _Socket:
+ shutdown_with = None
+
+ def shutdown(self, how):
+ self.shutdown_with = how
+
+ class _Connection:
+ closed = False
+
+ def __init__(self):
+ self.sock = _Socket()
+
+ def close(self):
+ self.closed = True
+
+ connection = _Connection()
+ sock = connection.sock
+ cancelled = threading.Event()
+ cancelled.set()
+
+ _close_connection_on_cancel(connection, cancelled, threading.Event())
+
+ assert sock.shutdown_with == socket.SHUT_RDWR
+ assert connection.closed is True
+
+
+def test_the_gguf_sidecar_cancels_through_its_connection():
+ """Both HTTP sidecars share one watcher, so neither can drift back to a process kill."""
+ import inspect
+
+ from core.inference import stt_ggml_sidecar
+
+ source = inspect.getsource(stt_ggml_sidecar)
+ assert "_close_connection_on_cancel" in source
+ assert "_terminate_process_on_cancel" not in source
+ assert "http.client.HTTPConnection" in source
+
+
+def test_transformers_disconnect_cancels_only_its_owned_startup():
+ sidecar = WhisperSttSidecar()
+ owner = threading.Event()
+ sibling = threading.Event()
+ load_cancel = threading.Event()
+ with sidecar._load_state_lock:
+ sidecar._loading = True
+ sidecar._load_cancel_event = load_cancel
+ sidecar._load_owner_cancel_event = owner
+
+ assert sidecar.cancel_transcription(sibling) is True
+ assert sibling.is_set() and not load_cancel.is_set()
+
+ assert sidecar.cancel_transcription(owner) is True
+ assert owner.is_set() and load_cancel.is_set()
+
+
+def test_ggml_disconnect_cancels_only_its_owned_startup():
+ class _StartingProcess:
+ terminated = False
+
+ def poll(self):
+ return None
+
+ def terminate(self):
+ self.terminated = True
+
+ sidecar = GgmlSttSidecar()
+ owner = threading.Event()
+ sibling = threading.Event()
+ load_cancel = threading.Event()
+ process = _StartingProcess()
+ with sidecar._load_state_lock:
+ sidecar._loading = True
+ sidecar._load_cancel_event = load_cancel
+ sidecar._load_owner_cancel_event = owner
+ sidecar._starting_process = process
+
+ assert sidecar.cancel_transcription(sibling) is True
+ assert sibling.is_set() and not load_cancel.is_set()
+ assert process.terminated is False
+
+ assert sidecar.cancel_transcription(owner) is True
+ assert owner.is_set() and load_cancel.is_set()
+ assert process.terminated is True
diff --git a/studio/backend/tests/test_training_preflight.py b/studio/backend/tests/test_training_preflight.py
index d02299c0a86..eaa19985460 100644
--- a/studio/backend/tests/test_training_preflight.py
+++ b/studio/backend/tests/test_training_preflight.py
@@ -1020,3 +1020,24 @@ def test_mlx_worker_callsites_select_config_validation_policy(monkeypatch):
if __name__ == "__main__":
unittest.main()
+
+
+def test_a_cached_spark_snapshot_root_still_gets_the_llm_subfolder(tmp_path):
+ """An offline or cache-pinned snapshot root has an LLM/ child, which the previous check
+ read as "already at the tokenizer" and sent AutoTokenizer at the root, which has none."""
+ from core.training.trainer import _spark_tts_tokenizer_kwargs
+
+ snapshot = tmp_path / "snapshots" / "abc123"
+ (snapshot / "LLM").mkdir(parents = True)
+
+ assert _spark_tts_tokenizer_kwargs("bicodec", str(snapshot)) == {"subfolder": "LLM"}
+ assert _spark_tts_tokenizer_kwargs("bicodec", "unsloth/Spark-TTS-0.5B") == {"subfolder": "LLM"}
+ # Already pointed at the tokenizer directory.
+ assert _spark_tts_tokenizer_kwargs("bicodec", str(snapshot / "LLM")) == {}
+ # A local checkpoint holding its own tokenizer.
+ local = tmp_path / "my-ft"
+ local.mkdir()
+ (local / "tokenizer_config.json").write_text("{}", encoding = "utf-8")
+ assert _spark_tts_tokenizer_kwargs("bicodec", str(local)) == {}
+ # Not Spark at all.
+ assert _spark_tts_tokenizer_kwargs("snac", str(snapshot)) == {}
diff --git a/studio/backend/utils/datasets/audio_decode.py b/studio/backend/utils/datasets/audio_decode.py
new file mode 100644
index 00000000000..044bcd8f3f7
--- /dev/null
+++ b/studio/backend/utils/datasets/audio_decode.py
@@ -0,0 +1,188 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Decode `datasets` Audio columns with soundfile when torchcodec cannot load.
+
+`datasets` 4.x decodes audio only through torchcodec, which needs an FFmpeg full-shared
+install to dlopen its native libraries. Windows has none by default, so
+`disable_torchcodec_if_broken` clears `datasets.config.TORCHCODEC_AVAILABLE` and every
+audio column raises, blocking the dataset format check and all six audio trainer paths
+on an otherwise working host. A soundfile decoder restores the pre-4.0 output contract,
+`{"path", "array", "sampling_rate"}`, which is what those callers already read.
+"""
+
+from __future__ import annotations
+
+import threading
+from typing import Any, Optional
+
+from loggers import get_logger
+
+logger = get_logger(__name__)
+
+_installed = False
+_ORIGINAL_ENCODE = None
+# The read-and-patch below must happen once. Two first-time callers (two dataset
+# format checks land on the threadpool together) can both pass the _installed
+# check, and the second then captures the already-installed shim as
+# _ORIGINAL_ENCODE, so its fallback branch recurses into itself until
+# RecursionError.
+_install_lock = threading.Lock()
+
+
+def _token_for_url(path: str, token_per_repo_id: Optional[dict]) -> Any:
+ """Pick the credential belonging to the repository this URL points at.
+
+ A mapping holds one entry per source repo, and `concatenate_datasets` or
+ `interleave_datasets` over streaming splits puts several in it at once, so taking an
+ arbitrary value would send one repo's token to another repo's host. Resolved the way
+ `datasets.Audio.decode_example` does it, from the repo id embedded in the URL.
+ """
+ if not token_per_repo_id:
+ return None
+ from datasets import config
+ from datasets.utils.py_utils import string_to_dict
+
+ # A chained URL ("zip://inner::https://outer") names its host in the last segment.
+ source_url = path.split("::")[-1]
+ pattern = (
+ config.HUB_DATASETS_URL
+ if source_url.startswith(config.HF_ENDPOINT)
+ else config.HUB_DATASETS_HFFS_URL
+ )
+ try:
+ fields = string_to_dict(source_url, pattern)
+ except ValueError:
+ # Older `datasets` raise here instead of returning None.
+ fields = None
+ if fields is None:
+ # Not a Hub URL, so no repo id to key on. One entry is unambiguous and is the
+ # shape every caller in this codebase passes; more than one is not guessable.
+ values = list(token_per_repo_id.values())
+ return values[0] if len(values) == 1 else None
+ return token_per_repo_id.get(fields["repo_id"])
+
+
+def _decode_with_soundfile(
+ self,
+ value: dict,
+ token_per_repo_id: Optional[dict] = None,
+) -> dict:
+ """Stand-in for `datasets.Audio.decode_example` that never needs FFmpeg."""
+ import io
+
+ import numpy as np
+ import soundfile as sf
+ from datasets.download.download_config import DownloadConfig
+ from datasets.utils.file_utils import is_local_path, xopen
+
+ if not self.decode:
+ raise RuntimeError(
+ "Decoding is disabled for this feature. Please use Audio(decode=True) instead."
+ )
+ path, raw = value["path"], value["bytes"]
+ if path is None and raw is None:
+ raise ValueError(
+ f"An audio sample should have one of 'path' or 'bytes' but both are None in {value}."
+ )
+
+ if raw is not None:
+ source: Any = io.BytesIO(raw)
+ elif is_local_path(path):
+ source = path
+ else:
+ source = xopen(
+ path,
+ "rb",
+ download_config = DownloadConfig(token = _token_for_url(path, token_per_repo_id)),
+ )
+
+ array, sampling_rate = sf.read(source, dtype = "float32", always_2d = False)
+ if array.ndim > 1:
+ # soundfile returns (frames, channels); torchcodec returns (channels, frames).
+ array = np.mean(array, axis = -1)
+ target = self.sampling_rate
+ if target and sampling_rate != target:
+ import librosa
+ array = librosa.resample(array, orig_sr = sampling_rate, target_sr = target)
+ sampling_rate = target
+ return {"path": path, "array": array, "sampling_rate": sampling_rate}
+
+
+def _encode_with_soundfile(self, value) -> dict:
+ """Stand-in for `datasets.Audio.encode_example` that never needs FFmpeg.
+
+ The audio VLM path maps without `remove_columns`, so reading `["array"]` writes the
+ decoded value back and `cast_storage` re-encodes it through torchcodec's encoder,
+ failing a run the decoder above had just unblocked.
+
+ The plain path/bytes forms need no encoder at all, but `datasets` imports
+ `torchcodec.encoders` at the top of `encode_example` before it looks at the value, so
+ casting a column of file paths raises on a broken host too. Those are handled here
+ rather than delegated. Only an `AudioDecoder` value falls through, which genuinely
+ needs torchcodec and cannot arrive while this shim is installed.
+ """
+ import io
+ from pathlib import Path
+
+ import soundfile as sf
+
+ if isinstance(value, str):
+ return {"bytes": None, "path": value}
+ if isinstance(value, Path):
+ return {"bytes": None, "path": str(value.absolute())}
+ if isinstance(value, (bytes, bytearray)):
+ return {"bytes": bytes(value), "path": None}
+ if isinstance(value, dict) and value.get("array") is not None:
+ buf = io.BytesIO()
+ sf.write(buf, value["array"], value["sampling_rate"], format = "WAV")
+ return {"bytes": buf.getvalue(), "path": value.get("path")}
+ if isinstance(value, dict) and ("bytes" in value or "path" in value):
+ return {"bytes": value.get("bytes"), "path": value.get("path")}
+ return _ORIGINAL_ENCODE(self, value)
+
+
+def ensure_audio_decoding() -> bool:
+ """Install the soundfile decoder when torchcodec is unusable. Idempotent.
+
+ False means neither backend is importable, and the caller should report that rather
+ than let a decode raise deep inside `datasets`.
+ """
+ global _installed
+ try:
+ from datasets import config
+ from datasets.features.audio import Audio
+ except ImportError:
+ return False
+ if config.TORCHCODEC_AVAILABLE and not _installed:
+ try:
+ # config only ran find_spec, and an installed torchcodec whose native libraries
+ # cannot dlopen still passes that. The API process never imports unsloth, so
+ # disable_torchcodec_if_broken has not corrected the flag here.
+ from datasets.features._torchcodec import AudioDecoder # noqa: F401
+ except (ImportError, OSError, RuntimeError) as exc:
+ logger.info("torchcodec is installed but unusable (%s)", exc)
+ config.TORCHCODEC_AVAILABLE = False
+ if config.TORCHCODEC_AVAILABLE:
+ return True
+ if _installed:
+ return True
+ try:
+ # librosa too: every trainer path casts to a target rate, so a decoder that cannot
+ # resample would raise from inside `datasets` exactly where this returns False.
+ import librosa # noqa: F401
+ import soundfile # noqa: F401
+ except (ImportError, OSError) as exc:
+ logger.warning("No usable audio decoder: torchcodec is broken and %s", exc)
+ return False
+ global _ORIGINAL_ENCODE
+ with _install_lock:
+ # Re-check under the lock: the loser of the race must not re-capture.
+ if _installed:
+ return True
+ _ORIGINAL_ENCODE = Audio.encode_example
+ Audio.decode_example = _decode_with_soundfile
+ Audio.encode_example = _encode_with_soundfile
+ _installed = True
+ logger.info("torchcodec is unusable; decoding dataset audio with soundfile")
+ return True
diff --git a/studio/backend/utils/hidden_models.py b/studio/backend/utils/hidden_models.py
index 22a9b349680..c5e5a00762e 100644
--- a/studio/backend/utils/hidden_models.py
+++ b/studio/backend/utils/hidden_models.py
@@ -55,6 +55,16 @@ _HIDDEN_STT_REPO_IDS = frozenset(
"unslothai/Qwen3-ASR-1.7B-GGUF",
}
)
+_HIDDEN_STT_REPO_IDS_LOWER = frozenset(repo_id.lower() for repo_id in _HIDDEN_STT_REPO_IDS)
+
+
+def is_curated_stt_repo_id(value: str | None) -> bool:
+ """True only for Studio's exact curated STT Hub repositories.
+
+ Still hidden from chat, but task-scoped inventory consumers need the real cache rows
+ so the Audio page need not reimplement size, format, variants and lifecycle.
+ """
+ return bool(value and value.strip().lower() in _HIDDEN_STT_REPO_IDS_LOWER)
def _config_is_whisper(path: Path) -> bool:
@@ -157,7 +167,7 @@ def is_hidden_model(*values: str | None) -> bool:
hidden_repo_ids = {
_PROBE_REPO_ID.lower(),
*(repo_id.lower() for repo_id in _DEFAULT_EMBEDDING_REPO_IDS),
- *(repo_id.lower() for repo_id in _HIDDEN_STT_REPO_IDS),
+ *_HIDDEN_STT_REPO_IDS_LOWER,
}
exact_paths: list[str] = []
for model in {
diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.py
index e4a42ce0572..0598432c75b 100644
--- a/studio/backend/utils/models/model_config.py
+++ b/studio/backend/utils/models/model_config.py
@@ -34,6 +34,7 @@ from typing import Callable, List, Tuple, Union
import hashlib
import json
import threading
+import time
import yaml
@@ -1107,12 +1108,37 @@ VALID_AUDIO_TYPES = ("snac", "csm", "bicodec", "dac", "whisper", "audio_vlm")
# Keyed like the vision cache so an unauthenticated/offline/other-revision miss can't poison.
_audio_detection_cache: Dict[_CapabilityCacheKey, Optional[str]] = {}
-# Tokenizer token patterns → audio_type (all 6 types from tokenizer_config.json)
+# An offline probe cannot answer for an adapter directory without its own tokenizer, nor
+# for a base repo that is not downloaded, and a non-definitive answer is deliberately
+# never cached, so /loras redid both for every checkpoint on every poll. Remembered for a
+# short while rather than permanently, because both can become answerable without a
+# restart: the base gets downloaded, or a training run finishes writing its output.
+_AUDIO_OFFLINE_MISS_TTL_S = 60.0
+_audio_offline_miss_cache: Dict[_CapabilityCacheKey, float] = {}
+
+
+def _count_prefix_exceeds(tokens, prefix: str, threshold: int) -> bool:
+ """Whether more than ``threshold`` tokens start with ``prefix``.
+
+ Equivalent to ``sum(...) > threshold`` but stops at the answer. Summing counted every
+ one of Orpheus's 28k codes to decide a question settled by the first 10,001.
+ """
+ count = 0
+ for token in tokens:
+ if token.startswith(prefix):
+ count += 1
+ if count > threshold:
+ return True
+ return False
+
+
+# Tokenizer token patterns → audio_type (all 6 types from tokenizer_config.json).
+# ORDER MATTERS: first match wins, so the specific codec fingerprints go before the
+# generic audio_vlm marker. Orpheus carries 28k <custom_token_N> SNAC codes AND a
+# stray <|audio|>; audio_vlm first typed it as audio-input, leaving is_audio False.
_AUDIO_TOKEN_PATTERNS = {
"csm": lambda tokens: "<|AUDIO|>" in tokens and "<|audio_eos|>" in tokens,
"whisper": lambda tokens: "<|startoftranscript|>" in tokens,
- # Gemma 3n: <audio_soft_token>; Gemma 4: <|audio|> (not csm's <|AUDIO|>).
- "audio_vlm": lambda tokens: "<audio_soft_token>" in tokens or "<|audio|>" in tokens,
"bicodec": lambda tokens: any(t.startswith("<|bicodec_") for t in tokens),
"dac": lambda tokens: (
"<|audio_start|>" in tokens
@@ -1120,8 +1146,38 @@ _AUDIO_TOKEN_PATTERNS = {
and "<|text_start|>" in tokens
and "<|text_end|>" in tokens
),
- "snac": lambda tokens: (sum(1 for t in tokens if t.startswith("<custom_token_")) > 10000),
+ "snac": lambda tokens: _count_prefix_exceeds(tokens, "<custom_token_", 10000),
+ # Generic, so last. Gemma 3n <audio_soft_token>; Gemma 4 <|audio|> (not csm's
+ # <|AUDIO|>). Neither carries a codebook, so nothing above shadows them.
+ "audio_vlm": lambda tokens: "<audio_soft_token>" in tokens or "<|audio|>" in tokens,
}
+# Every substring a pattern above needs. A tokenizer_config whose text contains NONE of
+# these cannot match any pattern, whatever it holds, so the answer is settled without
+# parsing it. That matters because an ordinary text checkpoint carries a large
+# tokenizer_config and json.loads of it was the bulk of a cold /loras scan.
+# MUST cover every pattern: _AUDIO_TOKEN_PATTERNS is lambdas, so this cannot be derived
+# from them, and a codec added there without its marker here would silently stop being
+# detected. test_audio_token_detection.py fails if the two drift.
+_AUDIO_TOKEN_MARKERS = (
+ "<|AUDIO|>", # csm
+ "<|startoftranscript|>", # whisper
+ "<|bicodec_", # bicodec
+ "<|audio_start|>", # dac
+ "<custom_token_", # snac
+ "<audio_soft_token>", # audio_vlm (Gemma 3n)
+ "<|audio|>", # audio_vlm (Gemma 4)
+)
+
+
+def _may_hold_audio_tokens(raw: str) -> bool:
+ """Whether a tokenizer_config's raw text is worth parsing.
+
+ Conservative: a false True only costs the parse that would have happened anyway.
+ A false False would misclassify, which is why the markers are pinned by a test.
+ """
+ return any(marker in raw for marker in _AUDIO_TOKEN_MARKERS)
+
+
_AUDIO_TOKENIZER_CONFIG_PATHS = (
"tokenizer_config.json",
"LLM/tokenizer_config.json",
@@ -1140,10 +1196,58 @@ def detect_audio_type(
Returns an audio_type string ('snac', 'csm', 'bicodec', 'dac', 'whisper',
'audio_vlm') or None.
+ A None here is ambiguous: it covers both "not an audio model" and "the repo
+ could not be read". Callers that gate a user action on the answer want
+ detect_audio_type_checked instead, so a gated or offline repo is not reported
+ as a definitively non-audio one.
+
When local_files_only is True (offline export) the remote HuggingFace fetch
is skipped so detection never blocks on a network read; only the local HF
cache is consulted.
"""
+ return detect_audio_type_checked(
+ model_name,
+ hf_token = hf_token,
+ local_files_only = local_files_only,
+ revision = revision,
+ )[0]
+
+
+def detect_audio_type_checked(
+ model_name: str,
+ hf_token: Optional[str] = None,
+ local_files_only: bool = False,
+ revision: Optional[str] = None,
+) -> Tuple[Optional[str], bool]:
+ """detect_audio_type, plus whether the answer is definitive.
+
+ Returns (audio_type_or_None, definitive). definitive is False when every read
+ failed for a reason that is not "the file is absent" -- a 401 on a gated repo,
+ a 5xx, a timeout -- so a None means unknown rather than "not audio".
+ """
+ # No model is definitively not an audio model. Without this the name is
+ # interpolated into the Hub URL and every poll fetches /None/resolve/main/...
+ if not model_name:
+ return None, True
+
+ # Key on effective offline (kwarg OR env) so an offline negative can't poison a later probe.
+ effective_offline = bool(local_files_only or _env_offline())
+ # Checked on the RAW name, before the casing resolution below, because resolving a
+ # repo id that is not in the cache walks every cache directory, and that walk is the
+ # cost this cache exists to avoid. A casing variant just takes its own entry, which
+ # for a short-lived negative is harmless.
+ miss_key: _CapabilityCacheKey = (
+ model_name,
+ _token_fingerprint(hf_token),
+ effective_offline,
+ )
+ if revision is not None:
+ miss_key += (revision,)
+ if effective_offline:
+ seen_at = _audio_offline_miss_cache.get(miss_key)
+ if seen_at is not None and time.monotonic() - seen_at < _AUDIO_OFFLINE_MISS_TTL_S:
+ return None, False
+
# Normalize casing + include the token fingerprint (mirrors is_vision_model).
try:
if is_local_path(model_name):
@@ -1152,8 +1256,6 @@ def detect_audio_type(
resolved_name = resolve_cached_repo_id_case(model_name)
except Exception:
resolved_name = model_name
- # Key on effective offline (kwarg OR env) so an offline negative can't poison a later probe.
- effective_offline = bool(local_files_only or _env_offline())
cache_key: _CapabilityCacheKey = (
resolved_name,
_token_fingerprint(hf_token),
@@ -1162,7 +1264,8 @@ def detect_audio_type(
if revision is not None:
cache_key += (revision,)
if cache_key in _audio_detection_cache:
- return _audio_detection_cache[cache_key]
+ # Only definitive results are cached, so a hit is definitive by construction.
+ return _audio_detection_cache[cache_key], True
tokenizer_kwargs = {"local_files_only": effective_offline}
if revision is not None:
@@ -1171,9 +1274,20 @@ def detect_audio_type(
# Cache only definitive results; a transient read failure stays None and retries.
if definitive:
_audio_detection_cache[cache_key] = result
+ _audio_offline_miss_cache.pop(miss_key, None)
+ elif effective_offline:
+ _audio_offline_miss_cache[miss_key] = time.monotonic()
if result:
logger.info(f"Model {model_name} detected as audio model: audio_type={result}")
- return result
+ elif not definitive:
+ # Offline, this is the ordinary answer for any base that is not downloaded, and
+ # /loras asks once per checkpoint, so info level made it one log line per row per
+ # poll. Online it is worth surfacing: it means gated or an upstream error.
+ (logger.debug if effective_offline else logger.info)(
+ f"Could not determine whether {model_name} is an audio model: "
+ f"tokenizer_config.json was unreadable (gated, offline or upstream error)"
+ )
+ return result, definitive
def _detect_audio_from_tokenizer(
@@ -1238,7 +1352,17 @@ def _detect_audio_from_tokenizer(
try:
if not tok_file.is_file():
continue
- tok_config = json.loads(tok_file.read_text(encoding = "utf-8-sig"))
+ raw = tok_file.read_text(encoding = "utf-8-sig")
+ if not _may_hold_audio_tokens(raw):
+ # No marker anywhere, so no pattern can match. Counted as read
+ # only when the file looks whole: a training run part-way through
+ # writing its tokenizer would otherwise be a definitive "not
+ # audio" and cached for the life of the process. A truncated file
+ # stays unknown, exactly as it did when json.loads raised on it.
+ if raw.rstrip().endswith("}"):
+ read_any = True
+ continue
+ tok_config = json.loads(raw)
read_any = True
result = _check_token_patterns(tok_config)
if result:
@@ -1253,6 +1377,13 @@ def _detect_audio_from_tokenizer(
if local_files_only or _env_offline():
return None, read_any
+ # A filesystem path is not a repo id, so the URL below would be nonsense. The /loras scan
+ # reaches here for every adapter directory without its own tokenizer, and since a transient
+ # failure is never cached it paid two 15s timeouts per checkpoint on every pass, blocking
+ # the event loop that calls it. The local read above is the whole answer for a local path.
+ if is_local_path(model_name):
+ return None, read_any
+
try:
import requests
import os
diff --git a/studio/frontend/src/app/router.tsx b/studio/frontend/src/app/router.tsx
index db39a2dcc28..0f4f98fa046 100644
--- a/studio/frontend/src/app/router.tsx
+++ b/studio/frontend/src/app/router.tsx
@@ -13,6 +13,7 @@ import { Route as chatRoute } from "./routes/chat";
import { Route as exportRoute } from "./routes/export";
import { Route as imagesRoute } from "./routes/images";
import { Route as videoRoute } from "./routes/video";
+import { Route as audioRoute } from "./routes/audio";
import { Route as indexRoute } from "./routes/index";
import { Route as loginRoute } from "./routes/login";
import { Route as hubRoute } from "./routes/hub";
@@ -35,6 +36,7 @@ const routeTree = rootRoute.addChildren([
exportRoute,
imagesRoute,
videoRoute,
+ audioRoute,
dataRecipesRoute,
dataRecipeRoute,
apiMonitorRoute,
diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsx
index eda5e2e8f33..bea33808190 100644
--- a/studio/frontend/src/app/routes/__root.tsx
+++ b/studio/frontend/src/app/routes/__root.tsx
@@ -81,6 +81,11 @@ const VideoPage = lazy(() =>
import("@/features/video").then((m) => ({ default: m.VideoPage })),
);
+// AudioPage gets the same persistent mount so an in-flight generation keeps its UI state; still lazy on first /audio visit.
+const AudioPage = lazy(() =>
+ import("@/features/audio").then((m) => ({ default: m.AudioPage })),
+);
+
function PersonalizationSyncMount() {
usePersonalizationSync(hasAuthToken());
return null;
@@ -159,6 +164,8 @@ function isChatOnlyAllowed(pathname: string): boolean {
return true;
// Images runs on CPU/MPS via the native sd.cpp engine, the very no-GPU setup it was added for. The chat-only flag is about training/export, so it must not redirect /images.
if (pathname === "/images" || pathname.startsWith("/images/")) return true;
+ // Audio inference is CPU-capable too: GGUF TTS through llama.cpp and STT through the whisper.cpp / mtmd sidecars.
+ if (pathname === "/audio" || pathname.startsWith("/audio/")) return true;
// Video follows /export: the page explains an unsupported host itself from the backend's video
// verdict, and on Apple Silicon a chat-only host is where video works anyway. So a direct link
// or a reload must reach VideoPage's gate, which self-gates on videoSupported.
@@ -253,9 +260,17 @@ function RootLayout() {
setVideoMounted(true);
}
const shouldMountVideo = isVideoRoute || videoMounted;
- // Chat, Images and Video each render their own full-height shell, so all three want the chat-style layout: no outer pt-14 inset, no outer
+
+ // Same persistent mount for /audio so generation UI state survives leaving the tab.
+ const isAudioRoute = pathname === "/audio";
+ const [audioMounted, setAudioMounted] = useState(isAudioRoute);
+ if (isAudioRoute && !audioMounted) {
+ setAudioMounted(true);
+ }
+ const shouldMountAudio = isAudioRoute || audioMounted;
+ // Chat, Images, Video and Audio each render their own full-height shell, so all four want the chat-style layout: no outer pt-14 inset, no outer
// scroll. Keying off isChatRoute alone pushed the picker down and clipped the gallery. Container padding/overflow only; keep-alive stays per route.
- const isChatLike = isChatRoute || isImagesRoute || isVideoRoute;
+ const isChatLike = isChatRoute || isImagesRoute || isVideoRoute || isAudioRoute;
useTrainingUnloadGuard();
// Global export driver: streams worker logs and tracks status from any route
@@ -414,12 +429,27 @@ function RootLayout() {
</Suspense>
</div>
)}
+ {/* Same keep-alive treatment for Audio so generation and training UI state survive off-tab; `active` force-closes its body-portaled overlays so none bleed over another tab while hidden. */}
+ {shouldMountAudio && (
+ <div
+ className={
+ isAudioRoute
+ ? "flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-hidden"
+ : "hidden"
+ }
+ inert={!isAudioRoute || undefined}
+ >
+ <Suspense fallback={<RouteFallback />}>
+ <AudioPage active={isAudioRoute} />
+ </Suspense>
+ </div>
+ )}
{/* Use mode="popLayout" instead of "wait" to prevent UI freezes when
switching from heavy pages (like Export with many checkpoints).
"popLayout" allows the new route to mount immediately while the
old one animates out, avoiding blocking on expensive exit renders.
See issue #5850. */}
- {!isChatRoute && !isImagesRoute && !isVideoRoute && (
+ {!isChatRoute && !isImagesRoute && !isVideoRoute && !isAudioRoute && (
<AnimatePresence initial={false} mode="popLayout">
<motion.div
key={pathname}
diff --git a/studio/frontend/src/app/routes/audio.tsx b/studio/frontend/src/app/routes/audio.tsx
new file mode 100644
index 00000000000..4569ef222db
--- /dev/null
+++ b/studio/frontend/src/app/routes/audio.tsx
@@ -0,0 +1,29 @@
+// 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 { createRoute } from "@tanstack/react-router";
+import { requireAuth } from "../auth-guards";
+import { Route as rootRoute } from "./__root";
+
+// RootLayout renders AudioPage persistently (so an in-flight generation is not cancelled when leaving the tab); this route only owns the URL + auth gate.
+export const Route = createRoute({
+ getParentRoute: () => rootRoute,
+ path: "/audio",
+ staticData: { title: "Audio" },
+ // An audio pick made from the chat picker arrives here as ?model= (+ ?quant=, ?ggufQuant=, and task), which the page loads and then clears.
+ validateSearch: (
+ search: Record<string, unknown>,
+ ): { model?: string; quant?: string; ggufQuant?: string; task?: string } => ({
+ ...(typeof search.model === "string" ? { model: search.model } : {}),
+ ...(typeof search.quant === "string" ? { quant: search.quant } : {}),
+ ...(typeof search.ggufQuant === "string"
+ ? { ggufQuant: search.ggufQuant }
+ : {}),
+ ...(search.task === "automatic-speech-recognition" ||
+ search.task === "text-to-speech"
+ ? { task: search.task }
+ : {}),
+ }),
+ beforeLoad: () => requireAuth(),
+ component: () => null,
+});
diff --git a/studio/frontend/src/components/advanced-disclosure.tsx b/studio/frontend/src/components/advanced-disclosure.tsx
index e98e211fc24..2d7a05aa34d 100644
--- a/studio/frontend/src/components/advanced-disclosure.tsx
+++ b/studio/frontend/src/components/advanced-disclosure.tsx
@@ -15,10 +15,17 @@ import { cn } from "@/lib/utils";
export function AdvancedDisclosure({
open,
onOpenChange,
+ description = (
+ <>
+ Load-time tuning. Changes apply on the next load; Reapply reloads the
+ current model.
+ </>
+ ),
children,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
+ description?: ReactNode;
children: ReactNode;
}) {
return (
@@ -48,8 +55,7 @@ export function AdvancedDisclosure({
{open && (
<div className="flex flex-col gap-3">
<p className="text-ui-11 leading-snug text-muted-foreground">
- Load-time tuning. Changes apply on the next load; Reapply reloads
- the current model.
+ {description}
</p>
{children}
</div>
diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsx
index c3c5cfe2694..61b3e164da6 100644
--- a/studio/frontend/src/components/app-sidebar.tsx
+++ b/studio/frontend/src/components/app-sidebar.tsx
@@ -71,6 +71,7 @@ import {
CpuIcon,
CursorInfo02Icon,
DashboardCircleIcon,
+ AudioWave01Icon,
Delete02Icon,
Download01Icon,
DownloadSquare01Icon,
@@ -1134,6 +1135,18 @@ export function AppSidebar() {
preloadSilently(router.preloadRoute({ to: "/video" }));
},
},
+ audio: {
+ icon: AudioWave01Icon,
+ label: t("shell.navigation.audio"),
+ active: pathname === "/audio" || pathname.startsWith("/audio/"),
+ onClick: () => {
+ navigate({ to: "/audio" });
+ closeMobileIfOpen();
+ },
+ onIntent: () => {
+ preloadSilently(router.preloadRoute({ to: "/audio" }));
+ },
+ },
recipes: {
icon: ChefHatIcon,
label: t("shell.navigation.recipes"),
diff --git a/studio/frontend/src/components/media-page-link.tsx b/studio/frontend/src/components/media-page-link.tsx
index 6be5fd42b23..b25f23617a3 100644
--- a/studio/frontend/src/components/media-page-link.tsx
+++ b/studio/frontend/src/components/media-page-link.tsx
@@ -13,9 +13,8 @@ import {
} from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
-/** The link out to another page's workspace (Images, Video, image training). Kept out of the
- * page's mode strip, which switches modes within a page, and parked at the far right past a
- * divider so it reads as leaving rather than as another mode. */
+/** The link out to another page's workspace (Images, Video, Audio, image training).
+ * Kept out of the mode strip and parked past a divider so it reads as leaving. */
export function MediaPageLink({
to,
label,
@@ -25,7 +24,7 @@ export function MediaPageLink({
labelClassName,
arrowClassName,
}: {
- to: "/images" | "/video";
+ to: "/images" | "/video" | "/audio";
label: string;
icon: IconSvgElement;
/** Needed on a translated page: the default prefix below is English. */
diff --git a/studio/frontend/src/features/audio/api.ts b/studio/frontend/src/features/audio/api.ts
new file mode 100644
index 00000000000..b09bf3f92b7
--- /dev/null
+++ b/studio/frontend/src/features/audio/api.ts
@@ -0,0 +1,106 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { authFetch } from "@/features/auth";
+import { readFastApiError } from "@/lib/format-fastapi-error";
+
+async function parseJson<T>(response: Response): Promise<T> {
+ if (!response.ok) {
+ throw new Error(await readFastApiError(response));
+ }
+ return (await response.json()) as T;
+}
+
+export interface GeneratedAudio {
+ data: string;
+ format: string;
+ sample_rate: number;
+}
+
+export interface GenerateAudioResponse {
+ model: string;
+ audio: GeneratedAudio;
+ clip_id?: string | null;
+}
+
+export interface GenerateAudioOptions {
+ temperature?: number;
+ top_p?: number;
+ max_tokens?: number;
+ signal?: AbortSignal;
+}
+
+export async function generateAudio(
+ text: string,
+ options: GenerateAudioOptions = {},
+): Promise<GenerateAudioResponse> {
+ const { signal, ...sampling } = options;
+ const response = await authFetch("/api/inference/audio/generate", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ messages: [{ role: "user", content: text }],
+ stream: false,
+ ...sampling,
+ }),
+ signal,
+ });
+ return parseJson<GenerateAudioResponse>(response);
+}
+
+export interface AudioGalleryClip {
+ id: string;
+ url: string;
+ prompt: string;
+ model: string;
+ audio_type: string;
+ sample_rate: number;
+ duration_s: number;
+ created_at: string;
+}
+
+export interface AudioGalleryListResponse {
+ audio: AudioGalleryClip[];
+ has_more: boolean;
+ next_before_mtime: number | null;
+ next_before_id: string | null;
+}
+
+export async function listAudioGallery(
+ offset: number,
+ limit: number,
+ before?: { mtime: number; id: string } | null,
+): Promise<AudioGalleryListResponse> {
+ const cursor = before
+ ? `&before_mtime=${encodeURIComponent(before.mtime)}&before_id=${encodeURIComponent(before.id)}`
+ : "";
+ const response = await authFetch(
+ `/api/inference/audio/gallery?offset=${offset}&limit=${limit}${cursor}`,
+ );
+ return parseJson<AudioGalleryListResponse>(response);
+}
+
+export async function deleteAudioClip(id: string): Promise<void> {
+ const response = await authFetch(
+ `/api/inference/audio/gallery/${encodeURIComponent(id)}`,
+ { method: "DELETE" },
+ );
+ if (!response.ok) throw new Error(await readFastApiError(response));
+}
+
+export async function clearAudioGallery(): Promise<number> {
+ const response = await authFetch("/api/inference/audio/gallery", {
+ method: "DELETE",
+ });
+ const body = await parseJson<{ removed: number }>(response);
+ return body.removed;
+}
+
+export async function fetchClipObjectUrl(
+ url: string,
+): Promise<{ url: string; bytes: number }> {
+ const response = await authFetch(url);
+ if (!response.ok) throw new Error(await readFastApiError(response));
+ const blob = await response.blob();
+ return { url: URL.createObjectURL(blob), bytes: blob.size };
+}
diff --git a/studio/frontend/src/features/audio/audio-page-policy.ts b/studio/frontend/src/features/audio/audio-page-policy.ts
new file mode 100644
index 00000000000..481164592d1
--- /dev/null
+++ b/studio/frontend/src/features/audio/audio-page-policy.ts
@@ -0,0 +1,351 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import type { ModelSelectorChangeMeta } from "@/features/model-picker/components/model-selector/types";
+
+export type AudioBusy =
+ | "loading"
+ | "unloading"
+ | "generating"
+ | "transcribing"
+ | null;
+
+export type AudioPickTask = "tts" | "stt" | null;
+export type AudioCreateMode = "speak" | "transcribe";
+export type SttEngine = "transformers" | "gguf" | "mtmd";
+
+const TTS_AUDIO_TYPES = new Set(["snac", "csm", "bicodec", "dac"]);
+const GGUF_TTS_AUDIO_TYPES = new Set(["snac", "bicodec", "dac"]);
+
+export function isTtsAudioType(
+ audioType?: string | null,
+ isGguf = false,
+): boolean {
+ return Boolean(
+ audioType &&
+ (isGguf
+ ? GGUF_TTS_AUDIO_TYPES.has(audioType)
+ : TTS_AUDIO_TYPES.has(audioType)),
+ );
+}
+
+type SttDownloadedStatus = {
+ downloaded_models?: readonly string[];
+ transformers?: { downloaded_models?: readonly string[] };
+ gguf?: { downloaded_models?: readonly string[] };
+ mtmd?: { downloaded_models?: readonly string[] };
+};
+
+export interface SttDownloadedArtifact {
+ repoId: string;
+ sidecarKey: string;
+ engine: SttEngine;
+}
+
+/** Engine-qualified picker artifacts for every locally loadable checkpoint. Whisper
+ * uses one short key for distinct Transformers and whisper.cpp downloads, so engine
+ * provenance must survive this boundary. */
+export function sttDownloadedArtifacts(
+ status: SttDownloadedStatus,
+ repoIdForSidecarKey: (sidecarKey: string, engine: SttEngine) => string,
+): SttDownloadedArtifact[] {
+ const seen = new Set<string>();
+ const artifacts: SttDownloadedArtifact[] = [];
+ const blocks: readonly [SttEngine, SttDownloadedStatus | undefined][] = [
+ ["transformers", status],
+ ["transformers", status.transformers],
+ ["gguf", status.gguf],
+ ["mtmd", status.mtmd],
+ ];
+ for (const [engine, block] of blocks) {
+ for (const sidecarKey of block?.downloaded_models ?? []) {
+ const repoId = repoIdForSidecarKey(sidecarKey, engine);
+ const normalized = repoId.trim().toLowerCase();
+ if (!normalized || seen.has(normalized)) continue;
+ seen.add(normalized);
+ artifacts.push({ repoId, sidecarKey, engine });
+ }
+ }
+ return artifacts;
+}
+
+/** Catalog contracts win; uncurated ASR rows route from the inventory task in picker
+ * metadata. Unknown and TTS-tagged community repos keep the main-slot path for
+ * load-time capability validation. */
+export function resolveAudioPickTask(
+ catalogTask: AudioPickTask,
+ pipelineTag?: string | null,
+): AudioPickTask {
+ return (
+ catalogTask ??
+ (pipelineTag === "automatic-speech-recognition" ? "stt" : null)
+ );
+}
+
+/** Generation can be cancelled as part of a mode transition. Model lifecycle
+ * and transcription operations must settle before their controls disappear. */
+export function canTransitionAudioMode(busy: AudioBusy): boolean {
+ return busy === null || busy === "generating";
+}
+
+/** A managed TTS completion owns auto-load only while the same staging generation is
+ * selected in Speak. Downloads continue globally after ownership changes, but their
+ * completion must not mutate the main slot. */
+export function stagedTtsLoadIsOwned(
+ pendingGeneration: number | null,
+ currentGeneration: number,
+ mode: AudioCreateMode,
+): boolean {
+ return (
+ pendingGeneration !== null &&
+ pendingGeneration === currentGeneration &&
+ mode === "speak"
+ );
+}
+
+/** Cached rows sometimes know only the quant label; remote staging always
+ * supplies the exact filename. Both are valid backend GGUF selectors. */
+export function exactGgufLoadSelector(
+ meta: Pick<ModelSelectorChangeMeta, "ggufFilename" | "ggufVariant">,
+): string | null {
+ return meta.ggufFilename ?? meta.ggufVariant ?? null;
+}
+
+export type MacTtsPickAction = "allow" | "use-gguf-sibling" | "reject";
+
+/** MLX has no TTS decoder. A Mac TTS pick is runnable only when it already is
+ * GGUF or its curated family publishes a GGUF sibling. */
+export function macTtsPickAction({
+ isMac,
+ isGguf,
+ ggufSibling,
+}: {
+ isMac: boolean;
+ isGguf: boolean;
+ ggufSibling: string | null;
+}): MacTtsPickAction {
+ if (!isMac || isGguf) return "allow";
+ return ggufSibling ? "use-gguf-sibling" : "reject";
+}
+
+export interface AutoGgufVariant {
+ filename: string;
+ quant: string;
+ size_bytes: number;
+ download_size_bytes?: number;
+ downloaded?: boolean;
+ partial?: boolean;
+}
+
+/** Prefer a complete cached quant, then the repo's declared default, then the first
+ * exact file: instant Mac fallback when a runnable sibling is present, deterministic
+ * otherwise. */
+export function selectAutoGgufVariant<T extends AutoGgufVariant>(
+ variants: readonly T[],
+ defaultVariant: string | null | undefined,
+): T | null {
+ const exact = variants.filter(
+ (variant) => variant.filename.trim().length > 0,
+ );
+ if (exact.length === 0) return null;
+ const downloaded = exact.find(
+ (variant) => variant.downloaded === true && variant.partial !== true,
+ );
+ if (downloaded) return downloaded;
+ const normalizedDefault = defaultVariant?.trim().toLowerCase();
+ if (normalizedDefault) {
+ const preferred = exact.find(
+ (variant) =>
+ variant.quant.trim().toLowerCase() === normalizedDefault ||
+ variant.filename.trim().toLowerCase() === normalizedDefault,
+ );
+ if (preferred) return preferred;
+ }
+ return exact[0];
+}
+
+export function expectedGgufDownloadBytes(variant: AutoGgufVariant): number {
+ const downloadBytes = variant.download_size_bytes;
+ return typeof downloadBytes === "number" &&
+ Number.isFinite(downloadBytes) &&
+ downloadBytes > 0
+ ? downloadBytes
+ : variant.size_bytes;
+}
+
+/** Fold a freshly fetched first page into the list already on screen.
+ *
+ * The page is authoritative for the newest `page.length` clips and any scrollback below
+ * it is kept; replacing outright collapsed a paginated History on every delete and
+ * generate, and reselected a different clip. `removedId` drops a clip this client just
+ * deleted, which the page can no longer report. `hasMore` is the page's own report of
+ * whether the server holds anything older. */
+export function mergeGalleryPage<T extends { id: string }>(
+ page: readonly T[],
+ cached: readonly T[],
+ removedId?: string,
+ hasMore?: boolean,
+): { clips: T[]; stitched: boolean } {
+ const inPage = new Set(page.map((clip) => clip.id));
+ // An empty page means the server holds nothing: a clear from anywhere, not scrollback.
+ if (page.length === 0) return { clips: [], stitched: false };
+ // A complete first page IS everything the server holds, so there is no scrollback to
+ // keep: a cached clip below it was deleted by another client or pruned by the size cap,
+ // and stitching it back rendered a row that could never be played again.
+ if (hasMore === false) return { clips: [...page], stitched: false };
+ // The page is authoritative over the window it covers, so a cached clip inside that
+ // window and absent from the page was deleted by another client and must go. Only what
+ // sits BELOW the page's oldest entry is scrollback. Keying on the position of that
+ // entry, since a clip record carries no cursor of its own.
+ const oldestInPage = cached.findIndex(
+ (clip) => clip.id === page[page.length - 1].id,
+ );
+ // No overlap with a non-empty cache means the page has moved past everything held, so
+ // stitching would render a gap as contiguous and no cursor could ever reach it.
+ if (oldestInPage === -1) {
+ const overlaps = cached.some((clip) => inPage.has(clip.id));
+ if (!overlaps && cached.length > 0) return { clips: [...page], stitched: false };
+ }
+ const scrollback = oldestInPage === -1 ? cached : cached.slice(oldestInPage + 1);
+ const tail = scrollback.filter(
+ (clip) => !inPage.has(clip.id) && clip.id !== removedId,
+ );
+ return { clips: [...page, ...tail], stitched: tail.length > 0 };
+}
+
+/** Match the gallery record returned by this generation, never another
+ * client's concurrently persisted clip. */
+export function persistedClipForGeneration<T extends { id: string }>(
+ clipId: string | null | undefined,
+ refreshed: readonly T[],
+): T | null {
+ return clipId ? (refreshed.find((clip) => clip.id === clipId) ?? null) : null;
+}
+
+export function sttSelectionReady(
+ selectedRepo: string | null,
+ loadedModel: string | null,
+ sidecarKeyFor: (repoId: string) => string,
+ selectedEngine?: SttEngine | null,
+ loadedEngine?: SttEngine | null,
+): boolean {
+ return Boolean(
+ selectedRepo &&
+ loadedModel === sidecarKeyFor(selectedRepo) &&
+ (!selectedEngine || !loadedEngine || selectedEngine === loadedEngine),
+ );
+}
+
+type SttEngineResidency = {
+ loaded_model?: string | null;
+ loading?: boolean;
+ available?: boolean;
+};
+
+type SttResidencyStatus = SttEngineResidency & {
+ transformers?: SttEngineResidency;
+ gguf?: SttEngineResidency;
+ mtmd?: SttEngineResidency;
+};
+
+/** Resolve the resident model from the engine-aware status shape. The legacy top-level
+ * fields mirror Transformers only, so reading them for Qwen3-ASR or whisper.cpp clears a
+ * model that is actually ready. While the selected engine is pending, do not let an
+ * older model on another engine steal the selector. */
+export function resolveSttLoadedModel(
+ status: SttResidencyStatus,
+ selectedEngine: SttEngine | null,
+ preserveSelected: boolean,
+): string | null {
+ return (
+ resolveSttResidency(status, selectedEngine, preserveSelected)?.model ?? null
+ );
+}
+
+export interface SttResidency {
+ model: string;
+ engine: SttEngine;
+}
+
+/** Resolve model and owning engine together; equal Whisper short keys do not
+ * identify which runtime is resident. */
+export function resolveSttResidency(
+ status: SttResidencyStatus,
+ selectedEngine: SttEngine | null,
+ preserveSelected: boolean,
+): SttResidency | null {
+ // A whisper.cpp pick on a host without whisper-server is deliberately served, and
+ // loaded, through Transformers, so its residency lives in that block. Same fallback
+ // sttEngineStatusFor applies; the engine reported stays the selected one, because that
+ // is what the user picked and what the backend routes. Without this the refresh that
+ // completes the load found nothing (it runs while preserveSelected is true) and the
+ // Transcribe controls stayed disabled until the page was left and revisited.
+ const selectedStatus =
+ selectedEngine === "transformers" ||
+ (selectedEngine === "gguf" && status.gguf?.available === false)
+ ? (status.transformers ?? status)
+ : selectedEngine
+ ? status[selectedEngine]
+ : undefined;
+ if (selectedStatus?.loaded_model && selectedEngine) {
+ return { model: selectedStatus.loaded_model, engine: selectedEngine };
+ }
+ if (selectedEngine && (preserveSelected || selectedStatus?.loading)) {
+ return null;
+ }
+ const transformersModel =
+ status.transformers?.loaded_model ?? status.loaded_model;
+ if (transformersModel)
+ return { model: transformersModel, engine: "transformers" };
+ if (status.gguf?.loaded_model) {
+ return { model: status.gguf.loaded_model, engine: "gguf" };
+ }
+ if (status.mtmd?.loaded_model) {
+ return { model: status.mtmd.loaded_model, engine: "mtmd" };
+ }
+ return null;
+}
+
+/** Reconcile the picker selection with the sidecar's authoritative status.
+ * Preserve a selection only while its load/download is genuinely pending. */
+export function reconcileSttSelection({
+ selectedRepo,
+ loadedModel,
+ loadedEngine,
+ preservePending,
+ sidecarKeyFor,
+ repoIdForSidecarKey,
+ engineForRepo,
+}: {
+ selectedRepo: string | null;
+ loadedModel: string | null;
+ loadedEngine?: SttEngine | null;
+ preservePending: boolean;
+ sidecarKeyFor: (repoId: string) => string;
+ repoIdForSidecarKey: (sidecarKey: string, engine?: SttEngine) => string;
+ engineForRepo?: (repoId: string) => SttEngine;
+}): string | null {
+ if (loadedModel) {
+ if (
+ selectedRepo &&
+ sidecarKeyFor(selectedRepo) === loadedModel &&
+ (!loadedEngine ||
+ !engineForRepo ||
+ engineForRepo(selectedRepo) === loadedEngine)
+ ) {
+ return selectedRepo;
+ }
+ return repoIdForSidecarKey(loadedModel, loadedEngine ?? "transformers");
+ }
+ return preservePending ? selectedRepo : null;
+}
+
+/** Permission prompts cannot be aborted, so freshness is checked immediately
+ * after getUserMedia resolves and stale streams are stopped before recording. */
+export function micStreamRequestIsCurrent(
+ requestGeneration: number,
+ currentGeneration: number,
+ active: boolean,
+): boolean {
+ return active && requestGeneration === currentGeneration;
+}
diff --git a/studio/frontend/src/features/audio/audio-page.tsx b/studio/frontend/src/features/audio/audio-page.tsx
new file mode 100644
index 00000000000..f5361f8836d
--- /dev/null
+++ b/studio/frontend/src/features/audio/audio-page.tsx
@@ -0,0 +1,2260 @@
+// 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 page: Generate (TTS via the main inference slot) and Transcribe (STT
+// via the dictation sidecar). Training lives on the Train page. The page stays
+// mounted across tab switches (see __root.tsx), so `active` gates polling,
+// popovers and the recorder rather than lifecycle.
+
+import { TestTubeOutlineIcon } from "@/lib/hugeicons-derived";
+import {
+ AudioWave01Icon,
+ Copy01Icon,
+ Delete02Icon,
+ Download01Icon,
+ Mic01Icon,
+ MoreVerticalIcon,
+ SparklesIcon,
+ StopIcon,
+} from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import {
+ type ReactNode,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+
+import { AdvancedDisclosure } from "@/components/advanced-disclosure";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Spinner } from "@/components/ui/spinner";
+import { Textarea } from "@/components/ui/textarea";
+import { usePlatformStore } from "@/config/env";
+import {
+ type InferenceStatusResponse,
+ ParamSlider,
+ getInferenceStatus,
+ listGgufVariants,
+ listLoras,
+ loadModel,
+ unloadModel,
+} from "@/features/chat";
+import {
+ SttModelNotDownloadedError,
+ StudioModelDictationAdapter,
+ fetchSttStatus,
+ loadSttModel,
+ startSttDownload,
+ sttEngineStatusFor,
+ transcribeAudioBlob,
+ unloadSttModel,
+} from "@/features/chat/adapters/studio-model-dictation-adapter";
+import { useStagedDownload } from "@/features/hub/download-manager";
+import { getHfToken, hfApiToken } from "@/features/hub/stores/hf-token-store";
+import { ModelSelector } from "@/features/model-picker/components/model-selector";
+import { AUDIO_CATALOG } from "@/features/model-picker/components/model-selector/model-catalog";
+import { PillTabs } from "@/features/model-picker/components/model-selector/pill-tabs";
+import type {
+ ModelOption,
+ ModelSelectorChangeMeta,
+} from "@/features/model-picker/components/model-selector/types";
+import {
+ isTrackingSttDownload,
+ trackSttDownload,
+} from "@/features/settings/lib/stt-download-mirror";
+import { sttModelSize } from "@/features/settings/stores/stt-model-catalog";
+import { usePersistedToggle } from "@/hooks/use-persisted-toggle";
+import { useScrollFades } from "@/hooks/use-scroll-fades";
+import { BlobUrlCache } from "@/lib/blob-url-cache";
+import { subscribeModelLifecycle } from "@/lib/model-lifecycle-events";
+import { toast } from "@/lib/toast";
+import { cn } from "@/lib/utils";
+import { useNavigate, useSearch } from "@tanstack/react-router";
+
+import {
+ type AudioGalleryClip,
+ clearAudioGallery,
+ deleteAudioClip,
+ fetchClipObjectUrl,
+ generateAudio,
+ listAudioGallery,
+} from "./api";
+import {
+ type AudioBusy,
+ type SttDownloadedArtifact,
+ canTransitionAudioMode,
+ exactGgufLoadSelector,
+ expectedGgufDownloadBytes,
+ isTtsAudioType,
+ macTtsPickAction,
+ mergeGalleryPage,
+ micStreamRequestIsCurrent,
+ persistedClipForGeneration,
+ reconcileSttSelection,
+ resolveAudioPickTask,
+ resolveSttResidency,
+ selectAutoGgufVariant,
+ stagedTtsLoadIsOwned,
+ sttDownloadedArtifacts,
+ sttSelectionReady,
+} from "./audio-page-policy";
+import {
+ audioCapabilityLine,
+ audioModelsForTask,
+ audioTaskFor,
+ ggufSiblingFor,
+ macTtsCatalogChoiceIsRunnable,
+ sttEngineForRepoId,
+ sttRepoIdForSidecarKey,
+ sttSidecarKeyFor,
+} from "./catalog";
+
+const MODELS_BY_MODE: Record<CreateMode, ModelOption[]> = {
+ speak: audioModelsForTask("tts"),
+ transcribe: audioModelsForTask("stt"),
+};
+
+/** What to call a model on screen. A Hub repo is its id; a checkpoint trained here
+ * is an output directory, and the full path in a toast reads as a bug. */
+function audioModelLabel(id: string): string {
+ if (!/^(?:[a-zA-Z]:[\\/]|[\\/]|~)/.test(id)) return id;
+ const leaf = id.split(/[\\/]/).filter(Boolean).pop() ?? id;
+ // Training stamps the output directory with an epoch; it means nothing to a reader.
+ return leaf.replace(/_\d{10,}$/, "");
+}
+
+function deviceSizeBytes(label: string): number {
+ const match = label.trim().match(/^(\d+(?:\.\d+)?)\s*(MB|GB)$/i);
+ if (!match) return 0;
+ const value = Number(match[1]);
+ return value * (match[2].toUpperCase() === "GB" ? 1024 ** 3 : 1024 ** 2);
+}
+const HUB_TASKS_BY_MODE = {
+ speak: ["text-to-speech"],
+ transcribe: ["automatic-speech-recognition"],
+} as const;
+
+const PAGE_SIZE = 50;
+// Mirrors the STT sidecar's own limits (_MAX_AUDIO_SECONDS, STT_AUDIO_B64_MAX_CHARS), so a
+// recording is stopped at the boundary rather than uploaded and refused.
+const RECORDING_MAX_SECONDS = 30 * 60;
+// STT_AUDIO_RAW_MAX_BYTES in utils/upload_limits.py. A larger client cap let a dense codec
+// build a recording the raw route then refused with 413.
+const RECORDING_MAX_BYTES = 25 * 1024 * 1024;
+const RECORDING_CHUNK_MS = 1000;
+const TTS_MAX_TOKENS = 8192;
+// Max tokens caps the OUTPUT, and the prompt's own tokens sit in the same context window, so
+// loading at exactly TTS_MAX_TOKENS made the advertised maximum unreachable for any nonempty
+// prompt. Load with room for both.
+const TTS_PROMPT_CONTEXT_RESERVE = 2048;
+// WAV clips run a few MB a minute; 64 MB keeps a healthy scrollback resident.
+const CLIP_BLOB_BUDGET_BYTES = 64 * 1024 * 1024;
+
+// Module scope so a tab switch re-renders the gallery instantly (the page stays mounted, but a
+// remount after an unlikely unmount still reuses fetched clips).
+const galleryCache: {
+ clips: AudioGalleryClip[];
+ hasMore: boolean;
+ nextCursor: { mtime: number; id: string } | null;
+ selectedId: string | null;
+ srcById: BlobUrlCache;
+} = {
+ clips: [],
+ hasMore: false,
+ nextCursor: null,
+ selectedId: null,
+ srcById: new BlobUrlCache(CLIP_BLOB_BUDGET_BYTES),
+};
+
+type CreateMode = "speak" | "transcribe";
+
+function Field({
+ label,
+ hint,
+ children,
+}: {
+ label: string;
+ hint?: string;
+ children: ReactNode;
+}) {
+ return (
+ <div className="grid gap-1.5">
+ <span className="text-ui-13 font-medium text-foreground">{label}</span>
+ {children}
+ {hint ? (
+ <p className="text-ui-11p5 leading-snug text-muted-foreground">
+ {hint}
+ </p>
+ ) : null}
+ </div>
+ );
+}
+
+/** Per-row actions for a history clip, in a dots menu so rows keep one line.
+ * Mirrors the model rows' MoreVertical pattern. */
+function ClipRowMenu({
+ clip,
+ onDownload,
+ onCopyPrompt,
+ onUseAsText,
+ onDelete,
+}: {
+ clip: AudioGalleryClip;
+ onDownload: () => void;
+ onCopyPrompt: () => void;
+ onUseAsText: () => void;
+ onDelete: () => void;
+}) {
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild={true}>
+ <button
+ type="button"
+ onClick={(event) => event.stopPropagation()}
+ aria-label={`Actions for ${clip.prompt || "clip"}`}
+ // Hidden until the row is hovered or the menu is open, so a long list
+ // stays quiet; keyboard focus reveals it too.
+ className="flex size-5 shrink-0 items-center justify-center rounded-md text-muted-foreground/60 opacity-0 transition-colors hover:bg-black/5 hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100 data-[state=open]:opacity-100 dark:hover:bg-white/10"
+ >
+ <HugeiconsIcon
+ icon={MoreVerticalIcon}
+ strokeWidth={1.75}
+ className="size-3.5"
+ />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-48">
+ <DropdownMenuItem onSelect={onUseAsText}>
+ <HugeiconsIcon icon={SparklesIcon} className="size-4" />
+ Use text again
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={onCopyPrompt}>
+ <HugeiconsIcon icon={Copy01Icon} className="size-4" />
+ Copy text
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={onDownload}>
+ <HugeiconsIcon icon={Download01Icon} className="size-4" />
+ Download WAV
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="destructive" onSelect={onDelete}>
+ <HugeiconsIcon icon={Delete02Icon} className="size-4" />
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+function formatClipDuration(seconds: number): string {
+ if (!Number.isFinite(seconds) || seconds <= 0) return "0:00";
+ const whole = Math.round(seconds);
+ const minutes = Math.floor(whole / 60);
+ const rest = whole % 60;
+ return `${minutes}:${String(rest).padStart(2, "0")}`;
+}
+
+export function AudioPage({ active = true }: { active?: boolean }) {
+ const [mode, setMode] = useState<CreateMode>("speak");
+ const [selectorOpen, setSelectorOpen] = useState(false);
+ const [busy, setBusy] = useState<AudioBusy>(null);
+ const busyRef = useRef<AudioBusy>(busy);
+ busyRef.current = busy;
+
+ // --- TTS (main inference slot) -----------------------------------------
+ const [status, setStatus] = useState<InferenceStatusResponse | null>(null);
+ const [prompt, setPrompt] = useState("");
+ const [temperature, setTemperature] = useState(0.6);
+ // Sending temperature unconditionally puts it in the request's model_fields_set, which the
+ // backend reads as an explicit client override and which then beats the per-model
+ // recommendation (Spark-TTS wants 0.8, OuteTTS 0.4). Only send it once the user has moved
+ // the slider, so an untouched page gets the model's own sampling.
+ const [temperatureEdited, setTemperatureEdited] = useState(false);
+ const handleTemperatureChange = useCallback((value: number) => {
+ setTemperatureEdited(true);
+ setTemperature(value);
+ }, []);
+ const [maxTokens, setMaxTokens] = useState(2048);
+ const generateAbort = useRef<AbortController | null>(null);
+ const ttsLoadInFlight = useRef(false);
+ // A pick that lost the race with a load still settling. Replayed once it does.
+ const pendingRoutedTtsPick = useRef<{
+ repoId: string;
+ ggufFilename?: string | null;
+ loadId?: string | null;
+ } | null>(null);
+ const ttsStatusRefreshGeneration = useRef(0);
+ const ttsLoadGeneration = useRef(0);
+ const pendingTtsLoad = useRef<{
+ generation: number;
+ repoId: string;
+ /** What the load request actually sent, which is what a cancel has to name. */
+ loadTarget: string;
+ loadRequestId: string;
+ controller: AbortController;
+ requestStarted: boolean;
+ } | null>(null);
+
+ // --- STT (dictation sidecar) -------------------------------------------
+ const [selectedSttRepo, setSelectedSttRepo] = useState<string | null>(null);
+ const [sttLoadedModel, setSttLoadedModel] = useState<string | null>(null);
+ const [sttLoadedEngine, setSttLoadedEngine] = useState<
+ "transformers" | "gguf" | "mtmd" | null
+ >(null);
+ const [downloadedSttArtifacts, setDownloadedSttArtifacts] = useState<
+ SttDownloadedArtifact[]
+ >([]);
+ const [transcript, setTranscript] = useState("");
+ const [transcribedName, setTranscribedName] = useState<string | null>(null);
+ const [isRecording, setIsRecording] = useState(false);
+ const [micRequestPending, setMicRequestPending] = useState(false);
+ /** Safari and other WebKit builds ship no MediaRecorder, and an http LAN origin
+ * (`-H 0.0.0.0`) is not a secure context, so navigator.mediaDevices is undefined.
+ * Same check the chat composer gates its microphone on. */
+ const recordingSupported = useMemo(
+ () => StudioModelDictationAdapter.isSupported(),
+ [],
+ );
+ /** Audio the server produced that the gallery is not showing yet: either it could not
+ * be persisted at all, or it was persisted and this refresh missed it. Kept so the
+ * generation is playable either way. Cleared once its real clip lands. */
+ const [fallbackClip, setFallbackClip] = useState<{
+ url: string;
+ prompt: string;
+ model: string;
+ saved: boolean;
+ } | null>(null);
+ const fallbackClipRef = useRef(fallbackClip);
+ fallbackClipRef.current = fallbackClip;
+ const loadingMoreRef = useRef(false);
+ const galleryRefreshGeneration = useRef(0);
+ const recorderRef = useRef<MediaRecorder | null>(null);
+ const recordStreamRef = useRef<MediaStream | null>(null);
+ const discardRecordingRef = useRef(false);
+ const selectedSttRepoRef = useRef<string | null>(selectedSttRepo);
+ selectedSttRepoRef.current = selectedSttRepo;
+ const activeRef = useRef(active);
+ activeRef.current = active;
+ const modeRef = useRef(mode);
+ modeRef.current = mode;
+ const sttStatusRefreshGeneration = useRef(0);
+ const sttLoadGeneration = useRef(0);
+ const sttLoadingGeneration = useRef<number | null>(null);
+ // Residency is not ownership: the activation resync adopts whatever a sidecar already
+ // holds, including a model chat dictation loaded, and that must survive a mode switch.
+ // The identity, not a boolean: another surface can replace the sidecar's model while
+ // Audio is inactive, and a bare flag then claimed that replacement too, so Eject
+ // unloaded a model this page never loaded. Keyed on the model alone, deliberately: a
+ // "gguf" pick on a host without whisper-server is served by the Transformers fallback
+ // and comes back resident under that engine, so comparing the REQUESTED engine never
+ // matched and leaked the sidecar instead. The registry keeps one model resident, so the
+ // model id identifies it; the unload call resolves the serving engine server-side.
+ const sttLoadedByThisPage = useRef<string | null>(null);
+ const sttLoadAbort = useRef<AbortController | null>(null);
+ const deferredSttLoad = useRef<{
+ repoId: string;
+ sidecarKey: string;
+ engine: "transformers" | "gguf" | "mtmd";
+ } | null>(null);
+ const ttsPickGeneration = useRef(0);
+ const ttsInspectionGeneration = useRef<number | null>(null);
+ const stagedTtsGeneration = useRef(0);
+ const pendingStagedTtsLoad = useRef<{
+ repoId: string;
+ ggufFilename: string;
+ generation: number;
+ } | null>(null);
+ const stagedTtsLoadDeferred = useRef(false);
+ const micRequestGeneration = useRef(0);
+ const micPendingGeneration = useRef<number | null>(null);
+ const transcriptionAbort = useRef<AbortController | null>(null);
+
+ const stopRecordStream = useCallback(() => {
+ for (const track of recordStreamRef.current?.getTracks() ?? [])
+ track.stop();
+ recordStreamRef.current = null;
+ }, []);
+ const stopAndDiscardRecording = useCallback(() => {
+ // Also invalidates a getUserMedia request that has not resolved yet. Its
+ // eventual stream is stopped before a MediaRecorder can be created.
+ micRequestGeneration.current += 1;
+ micPendingGeneration.current = null;
+ setMicRequestPending(false);
+ const recorder = recorderRef.current;
+ if (recorder) {
+ discardRecordingRef.current = true;
+ if (recorder.state !== "inactive") recorder.stop();
+ recorderRef.current = null;
+ setIsRecording(false);
+ }
+ stopRecordStream();
+ }, [stopRecordStream]);
+
+ // --- Gallery ------------------------------------------------------------
+ const [clips, setClips] = useState<AudioGalleryClip[]>(galleryCache.clips);
+ const [hasMore, setHasMore] = useState(galleryCache.hasMore);
+ const [selectedId, setSelectedId] = useState<string | null>(
+ galleryCache.selectedId,
+ );
+ const [srcById, setSrcById] = useState<Record<string, string>>(
+ galleryCache.srcById.toRecord(),
+ );
+
+ const {
+ attach: attachSettingsScroll,
+ onScroll: onSettingsScroll,
+ className: settingsFadeClass,
+ } = useScrollFades();
+ const [advancedOpen, setAdvancedOpen] = usePersistedToggle(
+ "unsloth_audio_advanced_open",
+ );
+
+ const refreshStatus = useCallback(async () => {
+ const generation = ++ttsStatusRefreshGeneration.current;
+ try {
+ const next = await getInferenceStatus();
+ if (generation !== ttsStatusRefreshGeneration.current) return;
+ setStatus(next);
+ } catch {
+ if (generation !== ttsStatusRefreshGeneration.current) return;
+ // Do not leave Generate enabled against residency the backend can no
+ // longer confirm. A later refresh adopts the recovered runtime.
+ setStatus(null);
+ }
+ }, []);
+
+ const refreshSttStatus = useCallback(async () => {
+ const generation = ++sttStatusRefreshGeneration.current;
+ try {
+ const selectedRepo = selectedSttRepoRef.current;
+ const selectedKey = selectedRepo ? sttSidecarKeyFor(selectedRepo) : null;
+ const selectedEngine = selectedRepo
+ ? sttEngineForRepoId(selectedRepo)
+ : null;
+ const stt = await fetchSttStatus(
+ undefined,
+ selectedEngine === "transformers"
+ ? (selectedKey ?? undefined)
+ : undefined,
+ );
+ if (generation !== sttStatusRefreshGeneration.current) return;
+ const nextDownloadedArtifacts = sttDownloadedArtifacts(
+ stt,
+ sttRepoIdForSidecarKey,
+ );
+ setDownloadedSttArtifacts((current) =>
+ current.length === nextDownloadedArtifacts.length &&
+ current.every(
+ (artifact, index) =>
+ artifact.repoId === nextDownloadedArtifacts[index].repoId &&
+ artifact.sidecarKey === nextDownloadedArtifacts[index].sidecarKey &&
+ artifact.engine === nextDownloadedArtifacts[index].engine,
+ )
+ ? current
+ : nextDownloadedArtifacts,
+ );
+ const selectedBlock = selectedKey
+ ? (sttEngineStatusFor(stt, selectedKey, selectedEngine ?? undefined) ??
+ (selectedEngine === "transformers" ? stt : undefined))
+ : undefined;
+ const preservePending = Boolean(
+ selectedBlock?.loading ||
+ sttLoadingGeneration.current !== null ||
+ deferredSttLoad.current !== null,
+ );
+ const residency = resolveSttResidency(
+ stt,
+ selectedEngine,
+ preservePending,
+ );
+ const loadedModel = residency?.model ?? null;
+ setSttLoadedModel(loadedModel);
+ setSttLoadedEngine(residency?.engine ?? null);
+ const reconciled = reconcileSttSelection({
+ selectedRepo,
+ loadedModel,
+ loadedEngine: residency?.engine,
+ preservePending,
+ sidecarKeyFor: sttSidecarKeyFor,
+ repoIdForSidecarKey: sttRepoIdForSidecarKey,
+ engineForRepo: sttEngineForRepoId,
+ });
+ selectedSttRepoRef.current = reconciled;
+ setSelectedSttRepo(reconciled);
+ } catch {
+ if (generation !== sttStatusRefreshGeneration.current) return;
+ setSttLoadedModel(null);
+ setSttLoadedEngine(null);
+ }
+ }, []);
+
+ const sttSelected = selectedSttRepo !== null;
+ const sttReady = sttSelectionReady(
+ selectedSttRepo,
+ sttLoadedModel,
+ sttSidecarKeyFor,
+ selectedSttRepo ? sttEngineForRepoId(selectedSttRepo) : null,
+ sttLoadedEngine,
+ );
+
+ /** Forget the Transcribe pick, releasing its sidecar when this page owns it. */
+ const releaseTranscribeSelection = useCallback(async () => {
+ const selected = selectedSttRepoRef.current;
+ const claim = sttLoadedByThisPage.current;
+ const owned =
+ sttReady && selected !== null && claim !== null && claim === sttLoadedModel;
+ const forget = () => {
+ deferredSttLoad.current = null;
+ selectedSttRepoRef.current = null;
+ sttLoadGeneration.current += 1;
+ sttLoadedByThisPage.current = null;
+ setSelectedSttRepo(null);
+ };
+ if (!owned) {
+ forget();
+ return;
+ }
+ // Forget only once the sidecar is actually released: clearing first left a failed
+ // unload with the model in VRAM, no selection, and no Eject to retry with.
+ // Scoped to the model this page claimed: `owned` was decided here, and another
+ // surface can switch the same engine before the request lands, so an unscoped
+ // unload would tear down a model this page never owned.
+ await unloadSttModel(sttEngineForRepoId(selected), claim);
+ forget();
+ await refreshSttStatus();
+ }, [refreshSttStatus, sttReady, sttLoadedModel]);
+
+ const ensureClipSrc = useCallback(async (clip: AudioGalleryClip) => {
+ const cached = galleryCache.srcById.get(clip.id);
+ if (cached) {
+ galleryCache.srcById.touch(clip.id);
+ return;
+ }
+ try {
+ const fetched = await fetchClipObjectUrl(clip.url);
+ galleryCache.srcById.set(clip.id, fetched.url, fetched.bytes);
+ galleryCache.srcById.prune(
+ galleryCache.selectedId ? [galleryCache.selectedId] : [],
+ );
+ setSrcById(galleryCache.srcById.toRecord());
+ } catch {
+ // Clip may have been deleted server-side; the next gallery refresh drops it.
+ }
+ }, []);
+
+ const refreshGallery = useCallback(
+ async (removedId?: string): Promise<AudioGalleryClip[]> => {
+ const generation = ++galleryRefreshGeneration.current;
+ try {
+ const page = await listAudioGallery(0, PAGE_SIZE);
+ // The caller's own fetch: a generation whose clip persisted must not be told otherwise.
+ if (generation !== galleryRefreshGeneration.current) return page.audio;
+ const { clips: merged, stitched } = mergeGalleryPage(
+ page.audio,
+ galleryCache.clips,
+ removedId,
+ page.has_more,
+ );
+ galleryCache.clips = merged;
+ // A clip record carries no mtime, so kept scrollback has no cursor; keep the deeper one.
+ if (!stitched) {
+ galleryCache.hasMore = page.has_more;
+ galleryCache.nextCursor =
+ page.next_before_mtime !== null && page.next_before_id !== null
+ ? { mtime: page.next_before_mtime, id: page.next_before_id }
+ : null;
+ }
+ setClips(merged);
+ setHasMore(galleryCache.hasMore);
+ // The response audio was kept only until its record showed up. Left mounted, deleting
+ // the now-visible clip made the "saved, waiting for the gallery" copy reappear from a
+ // stale data URL as though the delete had not happened.
+ if (
+ fallbackClipRef.current &&
+ galleryCache.selectedId &&
+ merged.some((c) => c.id === galleryCache.selectedId)
+ ) {
+ setFallbackClip(null);
+ }
+ if (
+ galleryCache.selectedId &&
+ !merged.some((c) => c.id === galleryCache.selectedId)
+ ) {
+ galleryCache.selectedId = merged[0]?.id ?? null;
+ setSelectedId(galleryCache.selectedId);
+ }
+ if (
+ !galleryCache.selectedId &&
+ !fallbackClipRef.current &&
+ merged.length > 0
+ ) {
+ galleryCache.selectedId = merged[0].id;
+ setSelectedId(galleryCache.selectedId);
+ }
+ return merged;
+ } catch {
+ // Same recoverable-poll stance as status.
+ return galleryCache.clips;
+ }
+ },
+ [],
+ );
+
+ const loadMore = useCallback(async () => {
+ // Repeated scroll events near the bottom would otherwise each fire with the
+ // same offset and append the same page, duplicating clips and React keys.
+ if (loadingMoreRef.current) return;
+ loadingMoreRef.current = true;
+ const refreshGeneration = galleryRefreshGeneration.current;
+ try {
+ const page = await listAudioGallery(
+ 0,
+ PAGE_SIZE,
+ galleryCache.nextCursor,
+ );
+ if (refreshGeneration !== galleryRefreshGeneration.current) return;
+ galleryCache.nextCursor =
+ page.next_before_mtime !== null && page.next_before_id !== null
+ ? { mtime: page.next_before_mtime, id: page.next_before_id }
+ : null;
+ const known = new Set(galleryCache.clips.map((clip) => clip.id));
+ galleryCache.clips = [
+ ...galleryCache.clips,
+ ...page.audio.filter((clip) => !known.has(clip.id)),
+ ];
+ galleryCache.hasMore = page.has_more;
+ setClips(galleryCache.clips);
+ setHasMore(page.has_more);
+ } catch {
+ // Retry on the next scroll.
+ } finally {
+ loadingMoreRef.current = false;
+ }
+ }, []);
+
+ // Resync on activation: another tab may have loaded/unloaded models meanwhile.
+ useEffect(() => {
+ if (!active) return;
+ void refreshStatus();
+ void refreshSttStatus();
+ void refreshGallery();
+ }, [active, refreshStatus, refreshSttStatus, refreshGallery]);
+
+ // Activation alone is not enough: the loaded-models indicator can eject the TTS model
+ // out from under a page that stays active, leaving Generate enabled against an empty
+ // slot. Same reason Images and Video listen here.
+ useEffect(() => {
+ if (!active) return;
+ return subscribeModelLifecycle(({ runtime, loading }) => {
+ if (loading) return;
+ if (runtime === "chat") void refreshStatus();
+ if (runtime === "stt") void refreshSttStatus();
+ });
+ }, [active, refreshStatus, refreshSttStatus]);
+
+ // The selected clip needs its bytes before the player can play it.
+ useEffect(() => {
+ const clip = clips.find((c) => c.id === selectedId);
+ if (clip) void ensureClipSrc(clip);
+ }, [clips, selectedId, ensureClipSrc]);
+
+ /** `keepFallback` is for the one case where the id is not in `clips` yet: the server
+ * persisted the clip but this refresh missed it, so the response audio has to stay
+ * mounted or the player falls through to the empty state. */
+ const selectClip = useCallback((id: string, keepFallback = false) => {
+ galleryCache.selectedId = id;
+ setSelectedId(id);
+ if (!keepFallback) setFallbackClip(null);
+ }, []);
+
+ // --- Model selection ----------------------------------------------------
+
+ const loadTtsModel = useCallback(
+ async (
+ repoId: string,
+ ggufFilename?: string | null,
+ // Where the weights actually are. A row cached in a NON-ACTIVE HF cache is loadable
+ // only by its snapshot path, which the picker supplies as meta.loadId; sending the
+ // display repo id instead failed offline, or re-downloaded into the active cache.
+ // Chat threads the same field (chat-page.tsx).
+ loadId?: string | null,
+ ) => {
+ // A routed pick that arrives while a previous load is still tearing down would
+ // otherwise be dropped here, and the route effect has already cleared ?model=, so
+ // nothing retries it. Remembered and replayed from the finally below instead.
+ if (ttsLoadInFlight.current) {
+ pendingRoutedTtsPick.current = { repoId, ggufFilename, loadId };
+ return;
+ }
+ const generation = ++ttsLoadGeneration.current;
+ const controller = new AbortController();
+ const loadRequestId = crypto.randomUUID();
+ const pending = {
+ generation,
+ repoId,
+ // What the request actually sent. Cancelling under the display id works only when
+ // the load target is a standard HF cache snapshot, because the backend can map
+ // models--org--name back to a repo id; a pinned directory elsewhere does not match
+ // and _cancel_scoped_load_attempt then refuses, leaving the load running.
+ loadTarget: loadId || repoId,
+ loadRequestId,
+ controller,
+ requestStarted: false,
+ };
+ pendingTtsLoad.current = pending;
+ const isCurrent = () =>
+ generation === ttsLoadGeneration.current && activeRef.current;
+ ttsLoadInFlight.current = true;
+ busyRef.current = "loading";
+ setBusy("loading");
+ const toastId = toast.loading(`Loading ${audioModelLabel(repoId)}…`);
+ try {
+ const res = await loadModel(
+ {
+ model_path: loadId || repoId,
+ load_request_id: loadRequestId,
+ hf_token: hfApiToken(getHfToken()) ?? null,
+ max_seq_length: TTS_MAX_TOKENS + TTS_PROMPT_CONTEXT_RESERVE,
+ load_in_4bit: false,
+ is_lora: false,
+ gguf_variant: ggufFilename ?? null,
+ },
+ {
+ signal: controller.signal,
+ onRequestStart: () => {
+ pending.requestStarted = true;
+ },
+ },
+ );
+ if (!isCurrent()) return;
+ if (res.is_audio && isTtsAudioType(res.audio_type)) {
+ toast.success(`Model loaded (${res.audio_type ?? "audio"})`, {
+ id: toastId,
+ });
+ } else {
+ toast.error(`${repoId} loaded but is not a supported TTS model.`, {
+ id: toastId,
+ });
+ }
+ } catch (error) {
+ if (isCurrent()) {
+ toast.error(
+ error instanceof Error ? error.message : "Model load failed.",
+ { id: toastId },
+ );
+ } else {
+ toast.dismiss(toastId);
+ }
+ } finally {
+ if (pendingTtsLoad.current?.generation === generation)
+ pendingTtsLoad.current = null;
+ ttsLoadInFlight.current = false;
+ busyRef.current = null;
+ setBusy(null);
+ if (activeRef.current) void refreshStatus();
+ // Only while Audio is visible. Replaying unconditionally started a load with
+ // activeRef already false, and since the deactivation effect had run it never saw
+ // that attempt to cancel it, so a hidden page could replace the model Chat had
+ // loaded. The pick stays queued instead and the activation effect replays it.
+ if (activeRef.current) replayQueuedTtsPick();
+ }
+ },
+ [refreshStatus],
+ );
+
+ // Stage uncached Hub GGUFs through the shared manager so Audio gets the same
+ // progress, cancellation, resume and disk preflight behavior as Chat/Images/Video.
+ const loadTtsModelRef = useRef(loadTtsModel);
+ loadTtsModelRef.current = loadTtsModel;
+ /** Start a pick that lost the race with a load still settling. Visible pages only:
+ * a load started while hidden outlives the deactivation effect that would cancel it. */
+ const replayQueuedTtsPick = useCallback(() => {
+ const queued = pendingRoutedTtsPick.current;
+ if (!queued) return;
+ pendingRoutedTtsPick.current = null;
+ void loadTtsModelRef.current(queued.repoId, queued.ggufFilename, queued.loadId);
+ }, []);
+ const invalidatePendingStagedTts = useCallback(() => {
+ stagedTtsGeneration.current += 1;
+ pendingStagedTtsLoad.current = null;
+ stagedTtsLoadDeferred.current = false;
+ }, []);
+ const transitionMode = useCallback(
+ (nextMode: CreateMode) => {
+ if (nextMode === mode) {
+ if (nextMode === "transcribe") invalidatePendingStagedTts();
+ return true;
+ }
+ if (!canTransitionAudioMode(busyRef.current)) {
+ toast.info(
+ "Wait for the active audio task to finish before switching modes.",
+ );
+ return false;
+ }
+
+ if (nextMode === "transcribe") invalidatePendingStagedTts();
+ if (busyRef.current === "generating") generateAbort.current?.abort();
+ stopAndDiscardRecording();
+ setMode(nextMode);
+ // Held through Generate, the sidecar keeps a dictation model in VRAM beside the speech one.
+ if (mode === "transcribe") {
+ // Resolves to whether the sidecar is actually gone. Swallowing the rejection made
+ // a failed unload look like a successful release, so the speech load went ahead
+ // with the dictation model still resident, which OOMs a device that fits one.
+ const release = releaseTranscribeSelection().then(
+ () => true,
+ (error) => {
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : "Failed to release the transcription model.",
+ );
+ return false;
+ },
+ );
+ // Recorded so a TTS load can wait for the teardown: allocating while the sidecar
+ // still holds its model is what OOMs a device that fits either one alone.
+ pendingTranscribeRelease.current = release;
+ void release.then((released) => {
+ if (pendingTranscribeRelease.current !== release) return;
+ pendingTranscribeRelease.current = null;
+ // The sidecar is still holding its model, so the page must not sit in Speak
+ // claiming otherwise: back to Transcribe, where Eject can retry the unload.
+ // Only if nothing has moved on since, so a user who switched again wins.
+ if (!released && modeRef.current === "speak") setMode("transcribe");
+ });
+ }
+ return true;
+ },
+ [
+ invalidatePendingStagedTts,
+ mode,
+ releaseTranscribeSelection,
+ stopAndDiscardRecording,
+ ],
+ );
+ const { stage: stageTtsDownload } = useStagedDownload({
+ scopeId: "audio",
+ onReady: () => {
+ const pending = pendingStagedTtsLoad.current;
+ if (
+ !pending ||
+ !stagedTtsLoadIsOwned(
+ pending.generation,
+ stagedTtsGeneration.current,
+ modeRef.current,
+ )
+ ) {
+ pendingStagedTtsLoad.current = null;
+ stagedTtsLoadDeferred.current = false;
+ return;
+ }
+ // Audio stays mounted across tabs. Loading from a hidden page would evict
+ // the visible page's model; likewise, wait for an active generation to end.
+ if (!active || busyRef.current !== null) {
+ stagedTtsLoadDeferred.current = true;
+ return;
+ }
+ pendingStagedTtsLoad.current = null;
+ void loadTtsModelRef.current(pending.repoId, pending.ggufFilename);
+ },
+ });
+
+ useEffect(() => {
+ if (!active || busy !== null || !stagedTtsLoadDeferred.current) return;
+ stagedTtsLoadDeferred.current = false;
+ const pending = pendingStagedTtsLoad.current;
+ if (
+ !pending ||
+ !stagedTtsLoadIsOwned(
+ pending.generation,
+ stagedTtsGeneration.current,
+ modeRef.current,
+ )
+ ) {
+ pendingStagedTtsLoad.current = null;
+ return;
+ }
+ pendingStagedTtsLoad.current = null;
+ void loadTtsModelRef.current(pending.repoId, pending.ggufFilename);
+ }, [active, busy]);
+
+ const loadOrStageTtsModel = useCallback(
+ (
+ repoId: string,
+ ggufFilename: string | null,
+ meta: ModelSelectorChangeMeta,
+ ) => {
+ if (
+ meta.source === "hub" &&
+ meta.isDownloaded === false &&
+ ggufFilename
+ ) {
+ const generation = ++stagedTtsGeneration.current;
+ pendingStagedTtsLoad.current = { repoId, ggufFilename, generation };
+ stagedTtsLoadDeferred.current = false;
+ stageTtsDownload([
+ {
+ repoId,
+ files: [ggufFilename],
+ bytes: meta.expectedBytes ?? 0,
+ ggufFilename,
+ },
+ ]);
+ return;
+ }
+
+ // A cached/local/direct pick supersedes any staged auto-load. The manager
+ // may keep downloading globally, but its old completion cannot load here.
+ invalidatePendingStagedTts();
+ stageTtsDownload([]);
+ void loadTtsModelRef.current(repoId, ggufFilename, meta.loadId);
+ },
+ [invalidatePendingStagedTts, stageTtsDownload],
+ );
+
+ const ensureSttLoaded = useCallback(
+ async (
+ repoId: string,
+ sidecarKey: string,
+ engine: "transformers" | "gguf" | "mtmd",
+ ) => {
+ const generation = ++sttLoadGeneration.current;
+ const controller = new AbortController();
+ sttLoadingGeneration.current = generation;
+ sttLoadAbort.current = controller;
+ const isCurrent = () =>
+ generation === sttLoadGeneration.current &&
+ activeRef.current &&
+ selectedSttRepoRef.current === repoId;
+
+ setBusy("loading");
+ // Ownership is claimed only once the requested model is actually resident. Claiming it
+ // up front meant a cancelled or failed download left the flag set while the backend kept
+ // the previous resident model, so leaving Transcribe then unloaded another surface's
+ // model. A failure leaves the previous value alone, which is what it should be.
+ const toastId = toast.loading(`Preparing ${sidecarKey}…`);
+ try {
+ try {
+ await loadSttModel(sidecarKey, engine, controller.signal);
+ sttLoadedByThisPage.current = sidecarKey;
+ } catch (error) {
+ if (!(error instanceof SttModelNotDownloadedError)) throw error;
+ if (!isCurrent()) return;
+ await startSttDownload(sidecarKey, hfApiToken(getHfToken()), engine);
+ // STT owns its specialized transfer, but the existing mirror gives
+ // it the same global Downloads row, progress and Cancel action as
+ // every other Studio model download. Do not reset an adopted row.
+ if (!isTrackingSttDownload(sidecarKey, engine)) {
+ trackSttDownload(sidecarKey, {
+ // Audio owns the final load through its active/selection
+ // generation guards. The Voice-settings mirror must not warm a
+ // stale sidecar behind those guards when this transfer lands.
+ warmSelectedVoiceModelOnComplete: false,
+ engine,
+ repoId,
+ });
+ }
+ // The shared Downloads panel now owns transfer progress. Keep this
+ // toast for the short model-load phase after the bytes land.
+ toast.dismiss(toastId);
+ // A completed download may outlive this page or selection. Re-check
+ // ownership around every await so an old pick cannot replace a newer
+ // sidecar when its poll finally finishes.
+ for (;;) {
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ if (!isCurrent()) return;
+ const stt = await fetchSttStatus(
+ undefined,
+ engine === "transformers" ? sidecarKey : undefined,
+ );
+ if (!isCurrent()) return;
+ const block = sttEngineStatusFor(stt, sidecarKey, engine);
+ const download = block?.download;
+ // Cancel comes from the shared Downloads row. It is terminal for
+ // this preparation attempt, not permission to try loading a
+ // partial checkpoint.
+ if (download?.cancelled) return;
+ if (download?.error) throw new Error(download.error);
+ if (!download?.downloading) break;
+ }
+ if (!isCurrent()) return;
+ toast.loading(`Loading ${sidecarKey}…`, { id: toastId });
+ await loadSttModel(sidecarKey, engine, controller.signal);
+ sttLoadedByThisPage.current = sidecarKey;
+ }
+ if (isCurrent())
+ toast.success("Transcription model ready", { id: toastId });
+ } catch (error) {
+ if (isCurrent()) {
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : "Transcription model failed.",
+ { id: toastId },
+ );
+ }
+ } finally {
+ if (sttLoadingGeneration.current === generation) {
+ sttLoadingGeneration.current = null;
+ await refreshSttStatus();
+ if (
+ generation === sttLoadGeneration.current &&
+ sttLoadingGeneration.current === null
+ ) {
+ setBusy(null);
+ }
+ } else {
+ toast.dismiss(toastId);
+ }
+ if (sttLoadAbort.current === controller) sttLoadAbort.current = null;
+ }
+ },
+ [refreshSttStatus],
+ );
+
+ // A hidden page may let the shared download continue, but it must not load
+ // the sidecar. Returning to the same still-selected repo resumes preparation
+ // once; a different selection/eject clears this deferred ownership.
+ useEffect(() => {
+ if (!active) {
+ ttsPickGeneration.current += 1;
+ const pending = pendingTtsLoad.current;
+ if (pending) {
+ ttsLoadGeneration.current += 1;
+ pendingTtsLoad.current = null;
+ pending.controller.abort();
+ if (pending.requestStarted)
+ void unloadModel({
+ model_path: pending.loadTarget,
+ cancel_load_request_id: pending.loadRequestId,
+ }).catch(() => {});
+ }
+ if (ttsInspectionGeneration.current !== null) {
+ ttsInspectionGeneration.current = null;
+ busyRef.current = null;
+ setBusy(null);
+ }
+
+ if (sttLoadingGeneration.current !== null) {
+ const repoId = selectedSttRepoRef.current;
+ deferredSttLoad.current = repoId
+ ? {
+ repoId,
+ sidecarKey: sttSidecarKeyFor(repoId),
+ engine: sttEngineForRepoId(repoId),
+ }
+ : null;
+ sttLoadGeneration.current += 1;
+ sttLoadingGeneration.current = null;
+ sttLoadAbort.current?.abort();
+ sttLoadAbort.current = null;
+ busyRef.current = null;
+ setBusy(null);
+ }
+ return;
+ }
+
+ // A pick queued behind a settling load, held back because the page went away before
+ // the load finished. Now that Audio is visible again the attempt is cancellable.
+ replayQueuedTtsPick();
+
+ const deferred = deferredSttLoad.current;
+ deferredSttLoad.current = null;
+ if (deferred && selectedSttRepoRef.current === deferred.repoId) {
+ void (async () => {
+ try {
+ const status = await fetchSttStatus(
+ undefined,
+ deferred.engine === "transformers"
+ ? deferred.sidecarKey
+ : undefined,
+ );
+ const download = sttEngineStatusFor(
+ status,
+ deferred.sidecarKey,
+ deferred.engine,
+ )?.download;
+ // `model` is null once the download thread has stopped, so a cancellation the
+ // user made while this page was hidden matched nothing here and the deferred
+ // load restarted the whole multi-GB download.
+ if (
+ download?.cancelled &&
+ (download.model ?? download.cancelled_model) === deferred.sidecarKey
+ )
+ return;
+ } catch {
+ // Status is advisory here; the normal preparation path reports errors.
+ }
+ if (activeRef.current && selectedSttRepoRef.current === deferred.repoId)
+ void ensureSttLoaded(
+ deferred.repoId,
+ deferred.sidecarKey,
+ deferred.engine,
+ );
+ })();
+ }
+ }, [active, ensureSttLoaded]);
+
+ const isMac = usePlatformStore((s) => s.deviceType) === "mac";
+ /** An in-flight Transcribe teardown a following TTS load has to wait behind. */
+ const pendingTranscribeRelease = useRef<Promise<boolean> | null>(null);
+
+ const handleModelSelect = useCallback(
+ async (id: string, meta: ModelSelectorChangeMeta) => {
+ if (busyRef.current !== null) return;
+ // Selecting a different artifact while recording is a lifecycle change
+ // even when it stays in Transcribe mode; never let the old capture submit
+ // against a sidecar that this pick is replacing.
+ stopAndDiscardRecording();
+ deferredSttLoad.current = null;
+ const selectionGeneration = ++ttsPickGeneration.current;
+ // Catalog first; an uncurated Hub pick falls back to its pipeline tag, or
+ // every community ASR repo would load into the TTS slot.
+ const task = resolveAudioPickTask(audioTaskFor(id), meta.pipelineTag);
+ if (task === "stt") {
+ // An STT pick owns Transcribe: it runs on the sidecar, not the main slot.
+ if (!transitionMode("transcribe")) return;
+ const sidecarKey = sttSidecarKeyFor(id);
+ const engine = sttEngineForRepoId(id);
+ deferredSttLoad.current = null;
+ selectedSttRepoRef.current = id;
+ setSelectedSttRepo(id);
+ void ensureSttLoaded(id, sidecarKey, engine);
+ return;
+ }
+ // TTS (or an uncurated repo the user pasted, which /load will validate).
+ if (!transitionMode("speak")) return;
+ // Serialize against a Transcribe release started by that transition.
+ const releaseInFlight = pendingTranscribeRelease.current;
+ // A release that failed leaves the sidecar resident, so do not stack a speech model
+ // on top of it. Back to Transcribe, where Eject can retry the unload.
+ if (releaseInFlight && !(await releaseInFlight)) {
+ setMode("transcribe");
+ return;
+ }
+ if (ttsPickGeneration.current !== selectionGeneration) return;
+ const exactGguf = exactGgufLoadSelector(meta);
+ const isGguf = Boolean(
+ meta.isGguf ||
+ exactGguf ||
+ /(?:^|[-/])gguf(?:$|[-/])/i.test(id) ||
+ id.toLowerCase().endsWith(".gguf"),
+ );
+ const ggufSibling = isGguf ? null : ggufSiblingFor(id);
+ const macAction = macTtsPickAction({ isMac, isGguf, ggufSibling });
+ if (macAction === "reject") {
+ toast.error(
+ `${id} has no runnable GGUF TTS build. MLX cannot generate text-to-speech from its safetensors checkpoint on this Mac.`,
+ { duration: 7000 },
+ );
+ return;
+ }
+ if (macAction === "use-gguf-sibling" && ggufSibling) {
+ toast.info(
+ `Loading the GGUF build of ${id}. MLX has no text-to-speech decoder, so the safetensors build cannot generate on this Mac.`,
+ { duration: 7000 },
+ );
+ // Resolving the sibling is part of the model load lifecycle. Reserve
+ // the slot so Generate cannot run the old resident model and then be
+ // evicted by this inspection's eventual completion.
+ ttsInspectionGeneration.current = selectionGeneration;
+ busyRef.current = "loading";
+ setBusy("loading");
+ try {
+ const listing = await listGgufVariants(
+ ggufSibling,
+ hfApiToken(getHfToken()),
+ );
+ if (selectionGeneration !== ttsPickGeneration.current) return;
+ const variant = selectAutoGgufVariant(
+ listing.variants,
+ listing.default_variant,
+ );
+ if (!variant) {
+ toast.error(
+ `${ggufSibling} does not publish a runnable GGUF file.`,
+ );
+ return;
+ }
+ if (ttsInspectionGeneration.current === selectionGeneration) {
+ ttsInspectionGeneration.current = null;
+ busyRef.current = null;
+ setBusy(null);
+ }
+ loadOrStageTtsModel(ggufSibling, variant.filename, {
+ ...meta,
+ source: "hub",
+ isGguf: true,
+ ggufFilename: variant.filename,
+ ggufVariant: variant.quant,
+ isDownloaded: variant.downloaded === true && !variant.partial,
+ expectedBytes: expectedGgufDownloadBytes(variant),
+ });
+ } catch (error) {
+ if (selectionGeneration !== ttsPickGeneration.current) return;
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : `Could not inspect ${ggufSibling}.`,
+ );
+ } finally {
+ if (ttsInspectionGeneration.current === selectionGeneration) {
+ ttsInspectionGeneration.current = null;
+ busyRef.current = null;
+ setBusy(null);
+ }
+ }
+ return;
+ }
+ loadOrStageTtsModel(id, exactGguf, meta);
+ },
+ [
+ ensureSttLoaded,
+ isMac,
+ loadOrStageTtsModel,
+ stopAndDiscardRecording,
+ transitionMode,
+ ],
+ );
+
+ // A pick handed over from the chat model selector arrives as ?model= (+ ?quant= and task).
+ const navigateSelf = useNavigate();
+ const routeSearch = useSearch({ strict: false }) as {
+ model?: string;
+ quant?: string;
+ ggufQuant?: string;
+ task?: string;
+ };
+ const handledRouteModel = useRef<string | null>(null);
+ useEffect(() => {
+ if (!active) return;
+ const wanted = routeSearch.model;
+ if (!wanted) {
+ handledRouteModel.current = null;
+ return;
+ }
+ const key = `${wanted}|${routeSearch.quant ?? ""}|${routeSearch.ggufQuant ?? ""}|${routeSearch.task ?? ""}`;
+ if (handledRouteModel.current === key) return;
+ // The persistent Audio page may still be finishing hidden work. Keep the
+ // handoff in the URL and retry it when that work releases the lifecycle.
+ if (busyRef.current !== null) return;
+ handledRouteModel.current = key;
+ handleModelSelect(wanted, {
+ source: "hub",
+ isLora: false,
+ ggufFilename: routeSearch.quant ?? undefined,
+ ggufVariant: routeSearch.ggufQuant ?? undefined,
+ // Chat-to-Audio routing cannot preserve the inventory flag, so stage the
+ // exact forwarded GGUF. An already-cached job completes immediately.
+ isDownloaded: routeSearch.quant ? false : undefined,
+ pipelineTag: routeSearch.task ?? null,
+ });
+ void navigateSelf({ to: "/audio", search: {}, replace: true });
+ }, [
+ active,
+ busy,
+ routeSearch.model,
+ routeSearch.quant,
+ routeSearch.ggufQuant,
+ routeSearch.task,
+ handleModelSelect,
+ navigateSelf,
+ ]);
+
+ // --- Speak --------------------------------------------------------------
+
+ const ttsLoaded = Boolean(
+ status?.active_model &&
+ isTtsAudioType(status.audio_type, status.is_gguf === true),
+ );
+ const handleEject = useCallback(() => {
+ if (busy !== null || isRecording) {
+ toast.info("Stop the active audio task before ejecting its model.");
+ return;
+ }
+
+ // Eject also owns unresolved permission requests. Invalidating here makes
+ // their eventual streams self-discard instead of recording for an old STT pick.
+ stopAndDiscardRecording();
+
+ if (mode === "transcribe") {
+ if (!selectedSttRepo) return;
+ // A selection can exist before its sidecar is resident, so an unowned pick is only forgotten.
+ if (!sttReady) {
+ sttStatusRefreshGeneration.current += 1;
+ void releaseTranscribeSelection();
+ return;
+ }
+
+ setBusy("unloading");
+ const toastId = toast.loading("Unloading transcription model…");
+ void (async () => {
+ try {
+ await releaseTranscribeSelection();
+ toast.success("Transcription model unloaded", {
+ id: toastId,
+ duration: 1200,
+ });
+ } catch (error) {
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : "Failed to unload transcription model.",
+ { id: toastId },
+ );
+ } finally {
+ setBusy(null);
+ }
+ })();
+ return;
+ }
+
+ const activeModel = status?.active_model;
+ if (!activeModel) return;
+
+ // An old managed completion must not immediately replace the model the
+ // user just ejected. The global download may continue for later use.
+ invalidatePendingStagedTts();
+ stageTtsDownload([]);
+
+ setBusy("unloading");
+ const toastId = toast.loading("Unloading model…");
+ void (async () => {
+ try {
+ // Non-forced unload is deliberate: the backend refuses rather than
+ // killing an active Chat or API generation owned by another surface.
+ await unloadModel({ model_path: activeModel });
+ await refreshStatus();
+ toast.success("Model unloaded", { id: toastId, duration: 1200 });
+ } catch (error) {
+ toast.error(
+ error instanceof Error ? error.message : "Failed to unload model.",
+ { id: toastId },
+ );
+ } finally {
+ setBusy(null);
+ }
+ })();
+ }, [
+ busy,
+ isRecording,
+ mode,
+ refreshStatus,
+ releaseTranscribeSelection,
+ selectedSttRepo,
+ invalidatePendingStagedTts,
+ stageTtsDownload,
+ status?.active_model,
+ sttReady,
+ stopAndDiscardRecording,
+ ]);
+
+ const handleGenerate = useCallback(async () => {
+ const text = prompt.trim();
+ if (!text) return;
+ // Same gate the TTS load path uses. Switching straight from Transcribe with a speech
+ // model already resident needs no load, so nothing else waits for the sidecar
+ // teardown, and generating beside a dictation model OOMs a device that fits either
+ // one alone. A release that failed leaves it resident, so go back to Transcribe,
+ // where Eject can retry the unload.
+ // Claimed before the await below, not after: the button only disables on `busy`, so
+ // a slow release let several clicks through and each resumed into its own
+ // generateAudio while generateAbort tracked only the last, and either finally
+ // cleared the busy state out from under the other.
+ if (busyRef.current) return;
+ busyRef.current = "generating";
+ setBusy("generating");
+ const releaseInFlight = pendingTranscribeRelease.current;
+ if (releaseInFlight && !(await releaseInFlight)) {
+ busyRef.current = null;
+ setBusy(null);
+ setMode("transcribe");
+ return;
+ }
+ const controller = new AbortController();
+ generateAbort.current = controller;
+ try {
+ const generated = await generateAudio(text, {
+ ...(temperatureEdited ? { temperature } : {}),
+ max_tokens: maxTokens,
+ signal: controller.signal,
+ });
+ const refreshed = await refreshGallery();
+ const generatedClip = persistedClipForGeneration(
+ generated.clip_id,
+ refreshed,
+ );
+ if (generatedClip) {
+ setFallbackClip(null);
+ selectClip(generatedClip.id);
+ } else if (generated.clip_id) {
+ // The server did persist it; only this refresh missed it (refreshGallery swallows a
+ // transient failure and returns the stale cache). Select the id so a later refresh
+ // shows the real record, but keep the response audio too: selectedClip resolves
+ // against `clips`, so an id that is not there yet would render the empty state and
+ // strand a generation the user just paid for.
+ setFallbackClip({
+ url: `data:audio/wav;base64,${generated.audio.data}`,
+ prompt: text,
+ model: generated.model,
+ saved: true,
+ });
+ selectClip(generated.clip_id, true);
+ } else {
+ // Gallery persistence is best-effort server-side, so a full or unwritable
+ // disk still returns the audio. Play it from the response rather than
+ // dropping an expensive generation on the floor.
+ galleryCache.selectedId = null;
+ setSelectedId(null);
+ setFallbackClip({
+ url: `data:audio/wav;base64,${generated.audio.data}`,
+ prompt: text,
+ model: generated.model,
+ saved: false,
+ });
+ }
+ } catch (error) {
+ if (!controller.signal.aborted) {
+ toast.error(
+ error instanceof Error ? error.message : "Audio generation failed.",
+ );
+ await refreshStatus();
+ }
+ } finally {
+ generateAbort.current = null;
+ setBusy(null);
+ }
+ }, [
+ prompt,
+ temperature,
+ temperatureEdited,
+ maxTokens,
+ refreshGallery,
+ refreshStatus,
+ selectClip,
+ ]);
+
+ const handleStopGeneration = useCallback(() => {
+ generateAbort.current?.abort();
+ }, []);
+
+ // Only unmount aborts. RootLayout keeps this page mounted precisely so leaving
+ // the tab does not cancel synthesis, and the clip is persisted server-side, so
+ // it is still waiting in the gallery on return.
+ useEffect(() => () => generateAbort.current?.abort(), []);
+
+ // --- Transcribe ---------------------------------------------------------
+
+ const runTranscription = useCallback(
+ async (blob: Blob, name: string) => {
+ if (!selectedSttRepo) return;
+ const key = sttSidecarKeyFor(selectedSttRepo);
+ const engine = sttEngineForRepoId(selectedSttRepo);
+ if (sttLoadedModel !== key || sttLoadedEngine !== engine) {
+ toast.info("Wait for the transcription model to finish loading.");
+ return;
+ }
+ transcriptionAbort.current?.abort();
+ const controller = new AbortController();
+ transcriptionAbort.current = controller;
+ setBusy("transcribing");
+ setTranscribedName(name);
+ try {
+ const text = await transcribeAudioBlob(blob, {
+ model: key,
+ engine,
+ language: "",
+ signal: controller.signal,
+ });
+ if (controller.signal.aborted || !activeRef.current) return;
+ setTranscript(text);
+ if (!text) toast.info("The model heard no speech in that audio.");
+ } catch (error) {
+ if (controller.signal.aborted) return;
+ toast.error(
+ error instanceof Error ? error.message : "Transcription failed.",
+ );
+ } finally {
+ if (transcriptionAbort.current === controller) {
+ transcriptionAbort.current = null;
+ setBusy(null);
+ if (activeRef.current) void refreshSttStatus();
+ }
+ }
+ },
+ [selectedSttRepo, sttLoadedModel, sttLoadedEngine, refreshSttStatus],
+ );
+
+ const handleRecordToggle = useCallback(async () => {
+ if (isRecording) {
+ const recorder = recorderRef.current;
+ if (recorder && recorder.state !== "inactive") recorder.stop();
+ return;
+ }
+ if (micPendingGeneration.current !== null) return;
+ const requestGeneration = ++micRequestGeneration.current;
+ micPendingGeneration.current = requestGeneration;
+ setMicRequestPending(true);
+ try {
+ const stream = await navigator.mediaDevices.getUserMedia({
+ audio: { echoCancellation: true, noiseSuppression: true },
+ });
+ if (
+ !micStreamRequestIsCurrent(
+ requestGeneration,
+ micRequestGeneration.current,
+ activeRef.current,
+ )
+ ) {
+ for (const track of stream.getTracks()) track.stop();
+ return;
+ }
+ recordStreamRef.current = stream;
+ const recorder = new MediaRecorder(stream);
+ const chunks: Blob[] = [];
+ let recordedBytes = 0;
+ let limitHit: "duration" | "size" | null = null;
+ // The sidecar rejects anything past 30 minutes, and a timeslice keeps the chunks in
+ // our array rather than inside the browser, so an over-long recording can be stopped
+ // at the limit instead of being buffered whole and refused after the upload.
+ const stopAtLimit = (reason: "duration" | "size") => {
+ if (limitHit) return;
+ limitHit = reason;
+ toast.warning(
+ reason === "duration"
+ ? `Recording stopped at the ${RECORDING_MAX_SECONDS / 60} minute limit.`
+ : "Recording stopped: it reached the maximum upload size.",
+ );
+ try {
+ recorder.stop();
+ } catch {
+ // Already stopping; the stop handler still runs.
+ }
+ };
+ const durationTimer = window.setTimeout(
+ () => stopAtLimit("duration"),
+ RECORDING_MAX_SECONDS * 1000,
+ );
+ recorder.addEventListener("dataavailable", (event) => {
+ if (event.data.size > 0) {
+ // Stop before appending the chunk that crosses the limit, so what is uploaded is
+ // always inside it rather than one chunk over.
+ if (recordedBytes + event.data.size > RECORDING_MAX_BYTES) {
+ stopAtLimit("size");
+ return;
+ }
+ chunks.push(event.data);
+ recordedBytes += event.data.size;
+ }
+ });
+ recorder.addEventListener("stop", () => {
+ window.clearTimeout(durationTimer);
+ const discard = discardRecordingRef.current;
+ discardRecordingRef.current = false;
+ setIsRecording(false);
+ stopRecordStream();
+ recorderRef.current = null;
+ const blob = new Blob(chunks, {
+ type: recorder.mimeType || "audio/webm",
+ });
+ if (!discard && blob.size > 0) void runTranscription(blob, "Recording");
+ });
+ recorderRef.current = recorder;
+ // A timeslice is what makes the byte cap observable: with none, some browsers hold
+ // the whole recording internally and only emit it on stop.
+ recorder.start(RECORDING_CHUNK_MS);
+ setIsRecording(true);
+ } catch {
+ // getUserMedia may have succeeded even if MediaRecorder construction or
+ // start failed. Release that acquired stream instead of leaving the mic
+ // live with no recorder UI capable of stopping it.
+ recorderRef.current = null;
+ setIsRecording(false);
+ stopRecordStream();
+ if (
+ micStreamRequestIsCurrent(
+ requestGeneration,
+ micRequestGeneration.current,
+ activeRef.current,
+ )
+ )
+ toast.error("Could not access the microphone.");
+ } finally {
+ if (micPendingGeneration.current === requestGeneration) {
+ micPendingGeneration.current = null;
+ setMicRequestPending(false);
+ }
+ }
+ }, [isRecording, runTranscription, stopRecordStream]);
+
+ // Release the microphone on unmount AND whenever the page goes inactive: the
+ // page stays mounted across tab switches, so unmount alone left a hidden
+ // recorder capturing until the user came back and stopped it.
+ useEffect(() => {
+ if (!active) {
+ stopAndDiscardRecording();
+ transcriptionAbort.current?.abort();
+ }
+ return () => {
+ stopAndDiscardRecording();
+ transcriptionAbort.current?.abort();
+ };
+ }, [active, stopAndDiscardRecording]);
+
+ const handleTranscribeFile = useCallback(
+ (file: File | undefined) => {
+ if (!file) return;
+ void runTranscription(file, file.name);
+ },
+ [runTranscription],
+ );
+
+ const handleCopyTranscript = useCallback(() => {
+ void navigator.clipboard.writeText(transcript).then(
+ () => toast.success("Transcript copied"),
+ () => toast.error("Could not copy the transcript."),
+ );
+ }, [transcript]);
+
+ const handleDownloadTranscript = useCallback(() => {
+ const blob = new Blob([transcript], { type: "text/plain" });
+ const url = URL.createObjectURL(blob);
+ const anchor = document.createElement("a");
+ anchor.href = url;
+ anchor.download = `${(transcribedName ?? "transcript").replace(/\.[^.]+$/, "")}.txt`;
+ anchor.click();
+ // Deferred like the gallery download below: browsers that resolve the synthetic
+ // navigation asynchronously were left with a revoked URL and no file.
+ window.setTimeout(() => URL.revokeObjectURL(url), 0);
+ }, [transcript, transcribedName]);
+
+ // --- Gallery actions ----------------------------------------------------
+
+ const handleDeleteClip = useCallback(
+ async (id: string) => {
+ try {
+ await deleteAudioClip(id);
+ galleryCache.srcById.delete(id);
+ setSrcById(galleryCache.srcById.toRecord());
+ // Drop the row now, as the clear-all path does: refreshGallery swallows a failed
+ // GET and returns the cache without calling setClips, which left the deleted clip
+ // on screen against an object URL that has already been revoked.
+ galleryCache.clips = galleryCache.clips.filter((clip) => clip.id !== id);
+ setClips(galleryCache.clips);
+ if (galleryCache.selectedId === id) {
+ galleryCache.selectedId = null;
+ setSelectedId(null);
+ }
+ await refreshGallery(id);
+ } catch (error) {
+ toast.error(
+ error instanceof Error ? error.message : "Could not delete the clip.",
+ );
+ }
+ },
+ [refreshGallery],
+ );
+
+ const handleClearGallery = useCallback(async () => {
+ try {
+ await clearAudioGallery();
+ galleryCache.srcById.clear();
+ galleryCache.selectedId = null;
+ // Drop the cached list first: refreshGallery merges the fetched page into it, so an
+ // empty page would otherwise leave every cleared row on screen.
+ galleryCache.clips = [];
+ // React state too, not just the cache: refreshGallery swallows a failed GET and
+ // returns the cache without calling setClips, which left every cleared row rendered
+ // against a revoked object URL until some later refresh.
+ setClips([]);
+ setSrcById({});
+ setSelectedId(null);
+ await refreshGallery();
+ } catch (error) {
+ toast.error(
+ error instanceof Error ? error.message : "Could not clear the gallery.",
+ );
+ }
+ }, [refreshGallery]);
+
+ const handleDownloadClip = useCallback(
+ (clip: AudioGalleryClip) => {
+ const src = srcById[clip.id];
+ if (!src) return;
+ const anchor = document.createElement("a");
+ anchor.href = src;
+ anchor.download = `${clip.id}.wav`;
+ anchor.click();
+ },
+ [srcById],
+ );
+
+ const handleDownloadFallbackClip = useCallback(() => {
+ if (!fallbackClip) return;
+ const anchor = document.createElement("a");
+ anchor.href = fallbackClip.url;
+ anchor.download = "generated-audio.wav";
+ anchor.click();
+ }, [fallbackClip]);
+
+ /** Download from a history row, whose bytes are only fetched once selected. */
+ const handleDownloadClipById = useCallback(async (clip: AudioGalleryClip) => {
+ let temporaryUrl: string | null = null;
+ try {
+ let src = galleryCache.srcById.get(clip.id);
+ if (!src) {
+ const fetched = await fetchClipObjectUrl(clip.url);
+ src = fetched.url;
+ temporaryUrl = fetched.url;
+ }
+ const anchor = document.createElement("a");
+ anchor.href = src;
+ anchor.download = `${clip.id}.wav`;
+ anchor.click();
+ } catch {
+ toast.error("Could not download the clip.");
+ } finally {
+ // A history-row download does not need to become resident playback state.
+ // Revoke it after the browser has consumed the synthetic click instead of
+ // bypassing the persistent gallery cache's 64 MB budget.
+ if (temporaryUrl) {
+ const url = temporaryUrl;
+ window.setTimeout(() => URL.revokeObjectURL(url), 0);
+ }
+ }
+ }, []);
+
+ const handleCopyPrompt = useCallback(async (text: string) => {
+ try {
+ await navigator.clipboard.writeText(text);
+ toast.success("Text copied");
+ } catch {
+ toast.error("Could not copy the text.");
+ }
+ }, []);
+
+ // Trained TTS checkpoints. A scan row carries no modality until the backend tags
+ // it, so without this the Audio page offers only catalog models and a checkpoint
+ // you just fine-tuned here is unreachable.
+ const [trainedTtsModels, setTrainedTtsModels] = useState<ModelOption[]>([]);
+ useEffect(() => {
+ if (!active) return;
+ let cancelled = false;
+ listLoras()
+ .then((res) => {
+ if (cancelled) return;
+ setTrainedTtsModels(
+ res.loras
+ // MLX has no TTS decoder, so a trained LoRA or merged safetensors checkpoint
+ // deterministically fails with "not supported on the MLX backend yet" on Mac.
+ // The catalog rows are already filtered to families with a GGUF sibling; these
+ // have none, so offering them only produces that error.
+ .filter((lora) => !isMac || lora.export_type === "gguf")
+ .filter((lora) => isTtsAudioType(lora.audio_type))
+ .map((lora) => ({
+ id: lora.adapter_path,
+ name: audioModelLabel(lora.adapter_path),
+ description:
+ lora.export_type === "merged"
+ ? `Fine-tuned - ${lora.base_model || "unknown base"}`
+ : `LoRA - ${lora.base_model || "unknown base"}`,
+ })),
+ );
+ })
+ .catch(() => {
+ // Listing trained models is additive; the catalog rows still work without it.
+ if (!cancelled) setTrainedTtsModels([]);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [active, isMac]);
+
+ // --- Render -------------------------------------------------------------
+
+ const selectedClip = clips.find((c) => c.id === selectedId) ?? null;
+ const selectorModels =
+ mode === "speak" && isMac
+ ? MODELS_BY_MODE.speak.filter((model) =>
+ macTtsCatalogChoiceIsRunnable(model.id),
+ )
+ : MODELS_BY_MODE[mode];
+ const sttOnDeviceModels = downloadedSttArtifacts.map((artifact) => {
+ const catalogModel = MODELS_BY_MODE.transcribe.find(
+ (model) => model.id.toLowerCase() === artifact.repoId.toLowerCase(),
+ );
+ const size = sttModelSize(artifact.sidecarKey);
+ return {
+ ...(catalogModel ?? {
+ id: artifact.repoId,
+ name: artifact.repoId.split("/").pop() || artifact.repoId,
+ description: "Speech-to-text",
+ }),
+ isGguf: artifact.engine !== "transformers",
+ deviceQuant:
+ artifact.engine === "mtmd"
+ ? "Q8_0"
+ : artifact.engine === "gguf"
+ ? "F16"
+ : undefined,
+ deviceSize: size || undefined,
+ deviceSizeBytes: size ? deviceSizeBytes(size) : undefined,
+ deviceLoaded:
+ artifact.sidecarKey === sttLoadedModel &&
+ artifact.engine === sttLoadedEngine,
+ } satisfies ModelOption;
+ });
+ const selectorValue =
+ mode === "speak"
+ ? (status?.active_model ?? undefined)
+ : (selectedSttRepo ?? undefined);
+
+ const capabilityLine =
+ mode === "speak"
+ ? ttsLoaded
+ ? audioCapabilityLine("tts", status?.audio_type)
+ : status?.active_model
+ ? "The loaded model is not a TTS audio model."
+ : "No TTS model loaded."
+ : sttSelected
+ ? audioCapabilityLine("stt", sttReady ? "ready" : "loading")
+ : "No transcription model selected.";
+
+ return (
+ <div className="@container flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-hidden pt-[var(--studio-content-top-inset,0px)]">
+ <div className="relative flex h-[48px] shrink-0 items-start justify-between gap-2 pl-[var(--studio-media-header-left-inset,1.5rem)] pr-2 pt-[var(--studio-chat-header-padding-top,11px)]">
+ {/* min-w-0: a long resident model name would otherwise push the mode pill off a narrow window. */}
+ <div className="flex min-w-0 items-center gap-2">
+ <ModelSelector
+ models={selectorModels}
+ additionalOnDeviceModels={
+ mode === "transcribe" ? sttOnDeviceModels : trainedTtsModels
+ }
+ loadedModelIdOverride={
+ mode === "transcribe" && sttReady
+ ? (selectedSttRepo ?? undefined)
+ : undefined
+ }
+ loaded={mode === "transcribe" ? sttReady : undefined}
+ value={selectorValue}
+ onValueChange={handleModelSelect}
+ onEject={busy === null && selectorValue ? handleEject : undefined}
+ variant="ghost"
+ className="!h-[34px]"
+ task={HUB_TASKS_BY_MODE[mode]}
+ catalog={AUDIO_CATALOG}
+ // TTS/ASR come from the checkpoint's own tokenizer, not a curated
+ // recipe, so any publisher's audio repo loads here.
+ communityModelPolicy="search-only"
+ placeholder="Select audio model"
+ open={active && selectorOpen}
+ onOpenChange={(o) => setSelectorOpen(active && o)}
+ />
+ </div>
+ <div className="pointer-events-none absolute inset-x-0 top-[var(--studio-chat-header-padding-top,11px)] flex justify-center">
+ <PillTabs
+ ariaLabel="Page mode"
+ // Always "create": Train navigates away, so the pill never latches.
+ value="create"
+ onValueChange={(v) => {
+ if (v !== "train") return;
+ toast.info(
+ "Audio fine-tuning lives on the Train page. Unsloth trains TTS and STT models there. Pick an audio model and appropriate dataset.",
+ { duration: 8000 },
+ );
+ void navigateSelf({ to: "/studio" });
+ }}
+ fit={true}
+ className="pointer-events-auto h-[34px] [&>button]:h-[34px] [&>button]:px-3 @[68rem]:[&>button]:px-11"
+ tabs={[
+ {
+ value: "create",
+ label: "Create",
+ icon: (
+ <HugeiconsIcon icon={SparklesIcon} className="size-3.5" />
+ ),
+ },
+ {
+ value: "train",
+ label: "Train",
+ icon: (
+ <HugeiconsIcon
+ icon={TestTubeOutlineIcon}
+ className="size-3.5"
+ />
+ ),
+ },
+ ]}
+ />
+ </div>
+ </div>
+ {/* Below 50rem the panes stack and the page scrolls as one column, matching Images and
+ Video: side by side, the 408px rail plus a usable preview needs more width than that. */}
+ <div className="flex min-h-0 w-full min-w-0 flex-1 flex-col overflow-y-auto overflow-x-hidden pl-2 pr-5 pt-9 sm:pr-8 @[50rem]:flex-row @[50rem]:overflow-hidden">
+ <div className="relative flex w-full shrink-0 flex-col border-b border-border/60 pl-8 @[50rem]:w-[408px] @[50rem]:overflow-hidden @[50rem]:border-r @[50rem]:border-b-0">
+ <div
+ ref={attachSettingsScroll}
+ onScroll={onSettingsScroll}
+ className={cn(
+ "hover-scrollbar panel-scroll-fade flex min-h-0 flex-1 flex-col gap-4 pb-20 pl-0.5 pr-8 @[50rem]:overflow-y-auto",
+ settingsFadeClass,
+ )}
+ >
+ {/* Same heading treatment as the Images and Video Create panes, so
+ the media panes stay level (#7986). */}
+ <div className="mb-2 grid gap-1.5">
+ <h2 className="flex items-center gap-2 font-heading text-xl font-medium leading-none text-foreground">
+ <HugeiconsIcon
+ icon={mode === "speak" ? AudioWave01Icon : Mic01Icon}
+ className="size-[18px] shrink-0"
+ />
+ {mode === "speak" ? "Generate audio" : "Transcribe"}
+ </h2>
+ {/* The always-on capability line: which task the selected model actually does. */}
+ <p className="text-xs leading-snug text-muted-foreground">
+ {capabilityLine}
+ </p>
+ </div>
+
+ <PillTabs
+ ariaLabel="Create mode"
+ value={mode}
+ onValueChange={(v) => transitionMode(v as CreateMode)}
+ fit={true}
+ className="h-[30px] self-start [&>button]:h-[30px] [&>button]:px-6"
+ tabs={[
+ { value: "speak", label: "Generate" },
+ { value: "transcribe", label: "Transcribe" },
+ ]}
+ />
+
+ {mode === "speak" ? (
+ <>
+ <Field
+ label="Text"
+ hint="What the model should say. Generation runs on the loaded TTS model and lands in the gallery on the right."
+ >
+ <Textarea
+ value={prompt}
+ onChange={(event) => setPrompt(event.target.value)}
+ placeholder="Type the sentence to speak…"
+ className="min-h-28"
+ />
+ </Field>
+ <AdvancedDisclosure
+ open={advancedOpen}
+ onOpenChange={setAdvancedOpen}
+ description="Generation sampling. Changes apply to the next audio clip."
+ >
+ <ParamSlider
+ label="Temperature"
+ value={temperature}
+ min={0}
+ max={1.5}
+ step={0.05}
+ onChange={handleTemperatureChange}
+ />
+ <ParamSlider
+ label="Max tokens"
+ value={maxTokens}
+ min={256}
+ max={TTS_MAX_TOKENS}
+ step={256}
+ onChange={setMaxTokens}
+ />
+ </AdvancedDisclosure>
+ </>
+ ) : (
+ <>
+ <Field
+ label="Microphone"
+ hint={
+ recordingSupported
+ ? "Record a clip and it is transcribed when you stop."
+ : "This browser cannot record. Open Studio over https or on localhost, or upload a file below."
+ }
+ >
+ <Button
+ variant={isRecording ? "destructive" : "secondary"}
+ disabled={
+ !recordingSupported ||
+ (!isRecording && (!sttReady || busy !== null)) ||
+ micRequestPending
+ }
+ onClick={handleRecordToggle}
+ >
+ <HugeiconsIcon
+ icon={isRecording ? StopIcon : Mic01Icon}
+ className="mr-2 size-4"
+ />
+ {isRecording
+ ? "Stop recording"
+ : micRequestPending
+ ? "Waiting for microphone…"
+ : "Record"}
+ </Button>
+ </Field>
+ <Field
+ label="Audio file"
+ hint="Or transcribe an existing recording (wav, mp3, m4a, webm…)."
+ >
+ <input
+ type="file"
+ accept="audio/*"
+ disabled={
+ !sttReady ||
+ busy !== null ||
+ isRecording ||
+ micRequestPending
+ }
+ onChange={(event) => {
+ handleTranscribeFile(event.target.files?.[0]);
+ event.target.value = "";
+ }}
+ className="text-ui-13 file:mr-3 file:rounded-md file:border-0 file:bg-muted file:px-3 file:py-1.5 file:text-ui-13 file:font-medium"
+ />
+ </Field>
+ {sttSelected ? null : (
+ <p className="text-ui-11p5 leading-snug text-muted-foreground">
+ Pick a speech-to-text model (Whisper or Qwen3-ASR) from the
+ selector above to transcribe.
+ </p>
+ )}
+ </>
+ )}
+ </div>
+ {mode === "speak" ? (
+ <div className="pointer-events-none absolute inset-x-0 bottom-0 flex justify-center pb-7 pl-8 pr-8">
+ <Button
+ className="btn-float-action pointer-events-auto h-11 px-8 disabled:bg-muted disabled:text-muted-foreground disabled:opacity-100"
+ onClick={
+ busy === "generating" ? handleStopGeneration : handleGenerate
+ }
+ disabled={
+ busy === "generating"
+ ? false
+ : busy !== null || !ttsLoaded || !prompt.trim()
+ }
+ variant={busy === "generating" ? "destructive" : "default"}
+ >
+ {busy === "generating" ? (
+ <>
+ <HugeiconsIcon icon={StopIcon} className="mr-2 size-4" />
+ Stop
+ </>
+ ) : (
+ "Generate"
+ )}
+ </Button>
+ </div>
+ ) : null}
+ </div>
+
+ <div className="relative flex min-h-[60dvh] min-w-0 flex-1 flex-col overflow-hidden pl-2 @[50rem]:min-h-0">
+ {mode === "transcribe" ? (
+ <div className="hover-scrollbar flex flex-1 flex-col gap-3 overflow-auto p-6 pl-8">
+ {busy === "transcribing" ? (
+ <div className="flex items-center gap-2 text-ui-13 text-muted-foreground">
+ <Spinner className="size-4" />
+ Transcribing {transcribedName ?? "audio"}…
+ </div>
+ ) : null}
+ {transcript ? (
+ <>
+ <div className="flex items-center gap-2">
+ <Button
+ variant="secondary"
+ size="sm"
+ onClick={handleCopyTranscript}
+ >
+ Copy
+ </Button>
+ <Button
+ variant="secondary"
+ size="sm"
+ onClick={handleDownloadTranscript}
+ >
+ <HugeiconsIcon
+ icon={Download01Icon}
+ className="mr-2 size-3.5"
+ />
+ Download .txt
+ </Button>
+ </div>
+ <p className="whitespace-pre-wrap text-sm leading-relaxed text-foreground">
+ {transcript}
+ </p>
+ </>
+ ) : busy !== "transcribing" ? (
+ <p className="text-ui-13 text-muted-foreground">
+ The transcript appears here. It is not stored: copy or
+ download what you want to keep.
+ </p>
+ ) : null}
+ </div>
+ ) : (
+ <div className="flex min-h-0 flex-1 flex-col gap-4 p-6 pl-8">
+ <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-4">
+ {selectedClip ? (
+ <div className="flex w-full max-w-xl flex-col gap-3">
+ <p className="line-clamp-2 text-ui-13 text-muted-foreground">
+ {selectedClip.prompt}
+ </p>
+ {/* Auth-protected bytes, so the element plays the fetched object URL. */}
+ <audio
+ controls={true}
+ src={srcById[selectedClip.id]}
+ className="w-full"
+ />
+ <div className="flex items-center gap-2 text-ui-11p5 text-muted-foreground">
+ <span>{selectedClip.model}</span>
+ <span>·</span>
+ <span>{formatClipDuration(selectedClip.duration_s)}</span>
+ <span className="flex-1" />
+ <Button
+ variant="ghost"
+ size="sm"
+ aria-label="Download audio clip"
+ disabled={!srcById[selectedClip.id]}
+ onClick={() => handleDownloadClip(selectedClip)}
+ >
+ <HugeiconsIcon
+ icon={Download01Icon}
+ className="size-3.5"
+ />
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ aria-label="Delete audio clip"
+ onClick={() => void handleDeleteClip(selectedClip.id)}
+ >
+ <HugeiconsIcon
+ icon={Delete02Icon}
+ className="size-3.5"
+ />
+ </Button>
+ </div>
+ </div>
+ ) : fallbackClip ? (
+ <div className="flex w-full max-w-xl flex-col gap-3">
+ <p className="line-clamp-2 text-ui-13 text-muted-foreground">
+ {fallbackClip.prompt}
+ </p>
+ <audio
+ controls={true}
+ src={fallbackClip.url}
+ className="w-full"
+ />
+ <div className="flex items-center gap-2 text-ui-11p5 text-muted-foreground">
+ <span>
+ {fallbackClip.model}
+ {fallbackClip.saved
+ ? " · saved, waiting for the gallery"
+ : " · not saved to the gallery"}
+ </span>
+ <span className="flex-1" />
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={handleDownloadFallbackClip}
+ >
+ <HugeiconsIcon
+ icon={Download01Icon}
+ className="size-3.5"
+ />
+ Download WAV
+ </Button>
+ </div>
+ </div>
+ ) : (
+ <p className="text-ui-13 text-muted-foreground">
+ Generated speech lands here. Load a TTS model, type a
+ sentence, and press Generate.
+ </p>
+ )}
+ </div>
+ {clips.length > 0 ? (
+ <div className="flex shrink-0 flex-col gap-2">
+ <div className="flex items-center justify-between">
+ <span className="text-ui-11p5 font-medium text-muted-foreground">
+ History
+ </span>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => void handleClearGallery()}
+ >
+ Clear all
+ </Button>
+ </div>
+ <div
+ className="hover-scrollbar flex max-h-40 flex-col gap-1 overflow-y-auto"
+ onScroll={(event) => {
+ const el = event.currentTarget;
+ if (
+ hasMore &&
+ el.scrollTop + el.clientHeight >= el.scrollHeight - 40
+ ) {
+ void loadMore();
+ }
+ }}
+ >
+ {clips.map((clip) => (
+ // Shell, not a button: the dots menu is a button and cannot nest.
+ <div
+ key={clip.id}
+ className={cn(
+ "group flex items-center rounded-md pr-1 transition-colors hover:bg-muted",
+ clip.id === selectedId && "bg-muted",
+ )}
+ >
+ <button
+ type="button"
+ onClick={() => selectClip(clip.id)}
+ className="flex min-w-0 flex-1 items-center gap-2 px-2 py-1.5 text-left text-ui-13"
+ >
+ <HugeiconsIcon
+ icon={AudioWave01Icon}
+ className="size-3.5 shrink-0 text-muted-foreground"
+ />
+ <span className="min-w-0 flex-1 truncate">
+ {clip.prompt}
+ </span>
+ <span className="shrink-0 text-ui-11p5 text-muted-foreground">
+ {formatClipDuration(clip.duration_s)}
+ </span>
+ </button>
+ <ClipRowMenu
+ clip={clip}
+ onDownload={() => void handleDownloadClipById(clip)}
+ onCopyPrompt={() =>
+ void handleCopyPrompt(clip.prompt)
+ }
+ onUseAsText={() => {
+ if (transitionMode("speak")) setPrompt(clip.prompt);
+ }}
+ onDelete={() => void handleDeleteClip(clip.id)}
+ />
+ </div>
+ ))}
+ </div>
+ </div>
+ ) : null}
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/audio/catalog.ts b/studio/frontend/src/features/audio/catalog.ts
new file mode 100644
index 00000000000..6063d927ae6
--- /dev/null
+++ b/studio/frontend/src/features/audio/catalog.ts
@@ -0,0 +1,59 @@
+// 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 {
+ AUDIO_CATALOG,
+ catalogToModelOptions,
+ groupForRepoId,
+} from "@/features/model-picker/components/model-selector/model-catalog";
+import type { ModelOption } from "@/features/model-picker/components/model-selector/types";
+import {
+ type AudioSttEngine,
+ isKnownSttArtifactRepoId,
+ sttEngineForRepoId,
+ sttRepoIdForSidecarKey,
+ sttSidecarKeyFor,
+} from "./stt-artifacts";
+
+export {
+ sttEngineForRepoId,
+ sttRepoIdForSidecarKey,
+ sttSidecarKeyFor,
+ type AudioSttEngine,
+};
+
+export type AudioTask = "tts" | "stt";
+
+export function audioTaskFor(repoId: string): AudioTask | null {
+ if (isKnownSttArtifactRepoId(repoId)) return "stt";
+ return groupForRepoId(repoId, AUDIO_CATALOG)?.task ?? null;
+}
+
+export function ggufSiblingFor(repoId: string): string | null {
+ const group = groupForRepoId(repoId, AUDIO_CATALOG);
+ if (!group || group.task !== "tts") return null;
+ const gguf = group.artifacts.find((a) => a.format === "gguf");
+ return gguf && gguf.repoId !== repoId ? gguf.repoId : null;
+}
+
+export function macTtsCatalogChoiceIsRunnable(repoId: string): boolean {
+ const group = groupForRepoId(repoId, AUDIO_CATALOG);
+ if (!group || group.task !== "tts") return false;
+ return group.artifacts.some((artifact) => artifact.format === "gguf");
+}
+
+export const AUDIO_MODEL_OPTIONS: ModelOption[] =
+ catalogToModelOptions(AUDIO_CATALOG);
+
+export function audioModelsForTask(task: AudioTask): ModelOption[] {
+ const matches = (option: ModelOption) => audioTaskFor(option.id) === task;
+ return AUDIO_MODEL_OPTIONS.filter(matches);
+}
+
+export function audioCapabilityLine(
+ task: AudioTask,
+ detail?: string | null,
+): string {
+ const base = task === "tts" ? "Text-to-speech" : "Speech-to-text";
+ return detail ? `${base} · ${detail}` : base;
+}
diff --git a/studio/frontend/src/features/audio/index.ts b/studio/frontend/src/features/audio/index.ts
new file mode 100644
index 00000000000..eb695057269
--- /dev/null
+++ b/studio/frontend/src/features/audio/index.ts
@@ -0,0 +1,4 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export { AudioPage } from "./audio-page";
diff --git a/studio/frontend/src/features/audio/stt-artifacts.ts b/studio/frontend/src/features/audio/stt-artifacts.ts
new file mode 100644
index 00000000000..71cd2ceaca7
--- /dev/null
+++ b/studio/frontend/src/features/audio/stt-artifacts.ts
@@ -0,0 +1,69 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export type AudioSttEngine = "transformers" | "gguf" | "mtmd";
+
+const TRANSFORMERS_REPO_BY_KEY: Record<string, string> = {
+ tiny: "unsloth/whisper-tiny",
+ base: "unsloth/whisper-base",
+ small: "unsloth/whisper-small",
+ "large-v3-turbo": "unsloth/whisper-large-v3-turbo",
+ "large-v3": "unsloth/whisper-large-v3",
+};
+
+const MTMD_REPO_BY_KEY: Record<string, string> = {
+ "qwen3-asr-0.6b": "unslothai/Qwen3-ASR-0.6B-GGUF",
+ "qwen3-asr-1.7b": "unslothai/Qwen3-ASR-1.7B-GGUF",
+};
+
+const GGUF_REPO_BY_KEY: Record<string, string> = {
+ tiny: "unslothai/whisper-tiny-GGUF",
+ base: "unslothai/whisper-base-GGUF",
+ small: "unslothai/whisper-small-GGUF",
+ "large-v3-turbo": "unslothai/whisper-large-v3-turbo-GGUF",
+ "large-v3": "unslothai/whisper-large-v3-GGUF",
+};
+
+const KEY_BY_REPO = new Map<string, string>(
+ [
+ ...Object.entries(TRANSFORMERS_REPO_BY_KEY),
+ ...Object.entries(GGUF_REPO_BY_KEY),
+ ...Object.entries(MTMD_REPO_BY_KEY),
+ ].map(([key, repoId]) => [repoId.toLowerCase(), key]),
+);
+
+const ENGINE_BY_REPO = new Map<string, AudioSttEngine>([
+ ...Object.values(TRANSFORMERS_REPO_BY_KEY).map(
+ (repoId) => [repoId.toLowerCase(), "transformers"] as const,
+ ),
+ ...Object.values(GGUF_REPO_BY_KEY).map(
+ (repoId) => [repoId.toLowerCase(), "gguf"] as const,
+ ),
+ ...Object.values(MTMD_REPO_BY_KEY).map(
+ (repoId) => [repoId.toLowerCase(), "mtmd"] as const,
+ ),
+]);
+
+export function isKnownSttArtifactRepoId(repoId: string): boolean {
+ return KEY_BY_REPO.has(repoId.trim().toLowerCase());
+}
+
+export function sttSidecarKeyFor(repoId: string): string {
+ return KEY_BY_REPO.get(repoId.trim().toLowerCase()) ?? repoId;
+}
+
+export function sttRepoIdForSidecarKey(
+ sidecarKey: string,
+ engine: AudioSttEngine = "transformers",
+): string {
+ const normalized = sidecarKey.trim().toLowerCase();
+ if (engine === "gguf") return GGUF_REPO_BY_KEY[normalized] ?? sidecarKey;
+ if (engine === "mtmd") return MTMD_REPO_BY_KEY[normalized] ?? sidecarKey;
+ return TRANSFORMERS_REPO_BY_KEY[normalized] ?? sidecarKey;
+}
+
+/** Resolve from the picker artifact, not the shared short sidecar key. */
+export function sttEngineForRepoId(repoId: string): AudioSttEngine {
+ const normalized = repoId.trim().toLowerCase();
+ return ENGINE_BY_REPO.get(normalized) ?? "transformers";
+}
diff --git a/studio/frontend/src/features/chat/adapters/studio-model-dictation-adapter.ts b/studio/frontend/src/features/chat/adapters/studio-model-dictation-adapter.ts
index 8dfb549e67f..f25c027ee26 100644
--- a/studio/frontend/src/features/chat/adapters/studio-model-dictation-adapter.ts
+++ b/studio/frontend/src/features/chat/adapters/studio-model-dictation-adapter.ts
@@ -126,6 +126,9 @@ export interface SttDownloadStatus {
error: string | null;
/** The last download was stopped by the user rather than failing. */
cancelled?: boolean;
+ /** Which model that cancellation applies to. `model` goes null once the worker thread
+ * stops, so this is the only way to tell a settled cancellation from an unrelated one. */
+ cancelled_model?: string | null;
bytes_total: number | null;
bytes_done: number | null;
}
@@ -189,8 +192,9 @@ export async function fetchSttStatus(
export function sttEngineStatusFor(
status: SttStatus,
model: string,
+ engineOverride?: SttEngine,
): SttEngineStatus | undefined {
- const engine = sttEngineFor(model);
+ const engine = engineOverride ?? sttEngineFor(model);
if (engine === "mtmd") return status.mtmd;
if (engine === "gguf" && status.gguf?.available) return status.gguf;
return status.transformers;
@@ -218,7 +222,11 @@ export async function validateSttModel(
}
/** Load a selected model that is already downloaded. */
-export function loadSttModel(model: string, engine?: SttEngine): Promise<void> {
+export function loadSttModel(
+ model: string,
+ engine?: SttEngine,
+ signal?: AbortSignal,
+): Promise<void> {
const resolvedEngine = engine ?? sttEngineFor(model);
// Announced so the indicator shows the load immediately, as the toast does.
return queueSttLifecycle(() =>
@@ -227,6 +235,7 @@ export function loadSttModel(model: string, engine?: SttEngine): Promise<void> {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model, engine: resolvedEngine }),
+ signal,
});
if (!response.ok) {
const body = (await response.json().catch(() => null)) as {
@@ -243,6 +252,7 @@ export function loadSttModel(model: string, engine?: SttEngine): Promise<void> {
export async function startSttDownload(
model: string,
hfToken?: string,
+ engine?: SttEngine,
): Promise<void> {
const response = await authFetch("/api/inference/audio/stt/download", {
method: "POST",
@@ -250,7 +260,7 @@ export async function startSttDownload(
"Content-Type": "application/json",
...hubTokenHeader(hfToken),
},
- body: JSON.stringify({ model, engine: sttEngineFor(model) }),
+ body: JSON.stringify({ model, engine: engine ?? sttEngineFor(model) }),
});
if (!response.ok) {
const body = (await response.json().catch(() => null)) as {
@@ -262,11 +272,14 @@ export async function startSttDownload(
/** Stop an in-flight model download. Partial files stay cached, so starting the
* same download again resumes from where it stopped. */
-export async function cancelSttDownload(model: string): Promise<void> {
+export async function cancelSttDownload(
+ model: string,
+ engine?: SttEngine,
+): Promise<void> {
const response = await authFetch("/api/inference/audio/stt/download/cancel", {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ model, engine: sttEngineFor(model) }),
+ body: JSON.stringify({ model, engine: engine ?? sttEngineFor(model) }),
});
if (!response.ok) {
const body = (await response.json().catch(() => null)) as {
@@ -277,11 +290,23 @@ export async function cancelSttDownload(model: string): Promise<void> {
}
/** Release the local STT model and its RAM/VRAM allocations. */
-export function unloadSttModel(): Promise<void> {
+/** Release the dictation sidecar. `model` scopes the release to the model the caller
+ * claims: another surface can switch the same engine between the ownership check and
+ * this request arriving, and the backend compares under the sidecar's own lock rather
+ * than releasing whatever is resident by then. */
+export function unloadSttModel(
+ engine?: SttEngine,
+ model?: string,
+): Promise<void> {
return queueSttLifecycle(async () => {
- const response = await authFetch("/api/inference/audio/stt/unload", {
- method: "POST",
- });
+ const params = new URLSearchParams();
+ if (engine) params.set("engine", engine);
+ if (model) params.set("model", model);
+ const query = params.size ? `?${params}` : "";
+ const response = await authFetch(
+ `/api/inference/audio/stt/unload${query}`,
+ { method: "POST" },
+ );
if (!response.ok) {
const body = (await response.json().catch(() => null)) as {
detail?: string;
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 3348e667f6a..2b28df20b47 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -214,6 +214,10 @@ export async function getActiveGenerations(): Promise<ActiveGenerationsResponse>
export async function loadModel(
payload: LoadModelRequest,
+ options?: {
+ signal?: AbortSignal;
+ onRequestStart?: () => void;
+ },
): Promise<LoadModelResponse> {
const preparedToken = await prepareHfTokenForUse(payload.hf_token);
// Tagged so auto-load can tell a user cancellation from a backend rejection.
@@ -221,6 +225,9 @@ export async function loadModel(
throw Object.assign(new Error("Model load cancelled."), {
unslothUserCancelled: true,
});
+ if (options?.signal?.aborted)
+ throw options.signal.reason ?? new DOMException("Aborted", "AbortError");
+ options?.onRequestStart?.();
// Announced after the token prompt, so a cancelled load never shows a row.
// The indicator otherwise had nothing to show until its next 5s poll, while
// the toast reported the load immediately.
@@ -234,6 +241,7 @@ export async function loadModel(
native_path_lease: payload.nativePathLease ?? null,
nativePathLease: undefined,
}),
+ signal: options?.signal,
});
return parseJsonOrThrow<LoadModelResponse>(response, "Model load");
});
@@ -552,6 +560,8 @@ export interface CachedModelRepo {
* cache. Optional for older-backend compatibility. */
cache_path?: string | null;
capabilities?: CachedRepoCapabilities | null;
+ tags?: string[];
+ library_name?: string | null;
}
export async function listCachedModels(
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index 3c06ba56880..400fe277577 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -3099,6 +3099,7 @@ export function ChatPage({
updatedAt: lora.updatedAt,
source: lora.source,
exportType: lora.exportType,
+ audioType: lora.audioType,
}));
return [...fromLoras, ...localModels];
}, [lorasFromStore, localModels]);
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
index 284764bae1d..ce5a95d9bf8 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
@@ -255,6 +255,7 @@ function toLoraSummary(lora: {
base_model?: string | null;
source?: "training" | "exported" | null;
export_type?: "lora" | "merged" | "gguf" | null;
+ audio_type?: string | null;
}): ChatLoraSummary {
const idTail = lora.adapter_path.split("/").filter(Boolean).at(-1) ?? "";
const updatedAt =
@@ -267,6 +268,7 @@ function toLoraSummary(lora: {
updatedAt,
source: lora.source ?? undefined,
exportType: lora.export_type ?? undefined,
+ audioType: lora.audio_type ?? null,
};
}
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index 4d42153b287..476100bdada 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -16,14 +16,15 @@ export {
listChatAttachments,
listGgufVariants,
listLocalModels,
+ listLoras,
listModels,
listRecommendedFolders,
listScanFolders,
loadModel,
+ unloadModel,
notifyChatHistoryUpdated,
removeScanFolder,
revealCachedModel,
- unloadModel,
type BrowseFoldersResponse,
type CachedGgufRepo,
type CachedModelRepo,
@@ -229,10 +230,12 @@ export {
fetchSttStatus,
loadSttModel,
startSttDownload,
+ sttEngineFor,
sttEngineStatusFor,
unloadSttModel,
validateSttModel,
type SttDownloadStatus,
+ type SttEngine,
} from "./adapters/studio-model-dictation-adapter";
export {
StudioSpeechSynthesisAdapter,
diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.ts
index cd84d8678b9..dbfeec3f9c7 100644
--- a/studio/frontend/src/features/chat/types/api.ts
+++ b/studio/frontend/src/features/chat/types/api.ts
@@ -28,6 +28,8 @@ export interface BackendLoraInfo {
base_model?: string | null;
source?: "training" | "exported" | null;
export_type?: "lora" | "merged" | "gguf" | null;
+ /** Codec of the checkpoint's base model when it fine-tunes an audio model, else null. */
+ audio_type?: string | null;
}
export interface ListLorasResponse {
@@ -37,6 +39,8 @@ export interface ListLorasResponse {
export interface LoadModelRequest {
model_path: string;
+ /** Opaque client attempt ID used to cancel only this in-flight load. */
+ load_request_id?: string | null;
/**
* Stop any chats still generating instead of getting a 409: a load replaces the single
* llama-server they all decode on. Set only after the user confirms.
@@ -257,6 +261,8 @@ export interface LoadModelResponse {
export interface UnloadModelRequest {
model_path: string;
+ /** Cancel this exact in-flight load; never unload an already-resident model. */
+ cancel_load_request_id?: string | null;
/** Stop any chats still generating instead of getting a 409: the unload takes down the
* llama-server they all decode on. */
force_cancel_active?: boolean;
diff --git a/studio/frontend/src/features/chat/types/runtime.ts b/studio/frontend/src/features/chat/types/runtime.ts
index 7600d7085b4..1021e461b6e 100644
--- a/studio/frontend/src/features/chat/types/runtime.ts
+++ b/studio/frontend/src/features/chat/types/runtime.ts
@@ -59,4 +59,6 @@ export interface ChatLoraSummary {
updatedAt?: number;
source?: "training" | "exported";
exportType?: "lora" | "merged" | "gguf";
+ /** Codec when the checkpoint fine-tunes an audio model, else null. */
+ audioType?: string | null;
}
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 05d0ec95e35..8a5c0dd9ce3 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-selector.tsx
@@ -46,6 +46,7 @@ import {
} from "../model-config/per-model-config";
import { ModelConfigPage } from "./model-config-page";
import { HubModelPicker, hasDownloadedModels } from "./model-selector/pickers";
+import type { CommunityModelPolicy } from "./model-selector/audio-picker-policy";
import type { CatalogGroup } from "./model-selector/model-catalog";
import { PillTabs } from "./model-selector/pill-tabs";
import {
@@ -131,6 +132,11 @@ export type {
interface ModelSelectorProps {
models: ModelOption[];
+ /** Models a task-specific runtime confirms are locally loadable even when
+ * their specialized cache layout is absent from the generic Hub inventory. */
+ additionalOnDeviceModels?: ModelOption[];
+ /** Task-owned runtime residency when it is separate from Chat's main slot. */
+ loadedModelIdOverride?: string;
loraModels?: LoraModelOption[];
externalModels?: ExternalModelOption[];
value?: string;
@@ -167,6 +173,9 @@ interface ModelSelectorProps {
task?: HfTaskFilter;
/** Canonical model groups (Images / Video pages): collapses a model's artifact repos into one row with a format second level and device-aware routing. Undefined (chat) changes nothing. */
catalog?: CatalogGroup[];
+ /** Also list community (non-unsloth) models for `task`. Opt-in: only pages
+ * whose runtime loads arbitrary publishers. */
+ communityModelPolicy?: CommunityModelPolicy;
/** Trigger text when nothing is loaded. Defaults to "Select model"; task pages name what they pick so it reads as separate from the chat model. */
placeholder?: string;
}
@@ -308,10 +317,12 @@ function saveLastHubSection(section: HubSection): void {
}
}
// Default the Hub section: the last tab clicked; first time, On Device with downloads else Recommended.
-function defaultHubSection(): HubSection {
+function defaultHubSection(hasAdditionalOnDeviceModels = false): HubSection {
return (
loadLastHubSection() ??
- (hasDownloadedModels() ? "downloaded" : "recommended")
+ (hasDownloadedModels() || hasAdditionalOnDeviceModels
+ ? "downloaded"
+ : "recommended")
);
}
@@ -331,6 +342,8 @@ const HUB_SECTION_TABS: { value: string; label: string; icon?: ReactNode }[] = [
function ModelSelectorContent({
open,
models,
+ additionalOnDeviceModels,
+ loadedModelIdOverride,
loraModels,
externalModels,
value,
@@ -351,9 +364,12 @@ function ModelSelectorContent({
dataTour,
task,
catalog,
+ communityModelPolicy,
}: {
open: boolean;
models: ModelOption[];
+ additionalOnDeviceModels?: ModelOption[];
+ loadedModelIdOverride?: string;
loraModels: LoraModelOption[];
externalModels: ExternalModelOption[];
value?: string;
@@ -374,6 +390,7 @@ function ModelSelectorContent({
dataTour?: string;
task?: HfTaskFilter;
catalog?: CatalogGroup[];
+ communityModelPolicy?: CommunityModelPolicy;
}) {
const t = useT();
const hasSelection = Boolean(value);
@@ -427,8 +444,12 @@ function ModelSelectorContent({
// Open on Connected when the active model comes from a connected provider.
const wantsConnectedDefault =
(chatOnly ? chatOnlyTabsDefault : studioTabsDefault) === "external";
+ const hasAdditionalOnDeviceModels =
+ (additionalOnDeviceModels?.length ?? 0) > 0;
const [hubSection, setHubSection] = useState<HubSection>(() =>
- wantsConnectedDefault ? "connected" : defaultHubSection(),
+ wantsConnectedDefault
+ ? "connected"
+ : defaultHubSection(hasAdditionalOnDeviceModels),
);
// Connected is only valid while external providers exist; fall back otherwise.
const effectiveHubSection: HubSection =
@@ -445,7 +466,11 @@ function ModelSelectorContent({
if (open && !wasOpen.current) {
setActiveTab(chatOnly ? chatOnlyTabsDefault : studioTabsDefault);
// Connected when an external model is active, else On Device with downloads, else their last section.
- setHubSection(wantsConnectedDefault ? "connected" : defaultHubSection());
+ setHubSection(
+ wantsConnectedDefault
+ ? "connected"
+ : defaultHubSection(hasAdditionalOnDeviceModels),
+ );
}
if (!open && wasOpen.current) {
setConfigTarget(null);
@@ -457,6 +482,7 @@ function ModelSelectorContent({
chatOnlyTabsDefault,
studioTabsDefault,
wantsConnectedDefault,
+ hasAdditionalOnDeviceModels,
]);
function focusActiveModelOption(root: HTMLElement): boolean {
@@ -607,6 +633,8 @@ function ModelSelectorContent({
{effectiveTab === "hub" ? (
<HubModelPicker
models={models}
+ additionalOnDeviceModels={additionalOnDeviceModels}
+ loadedModelIdOverride={loadedModelIdOverride}
loraModels={fineTunedModels}
externalModels={externalModels}
value={value}
@@ -620,6 +648,7 @@ function ModelSelectorContent({
onEject={hasSelection && onEject ? onEject : undefined}
task={task}
catalog={catalog}
+ communityModelPolicy={communityModelPolicy}
section={effectiveHubSection}
sectionToggle={
<PillTabs
@@ -680,6 +709,8 @@ function ModelSelectorContent({
export function ModelSelector({
models,
+ additionalOnDeviceModels = [],
+ loadedModelIdOverride,
loraModels = [],
externalModels = [],
value,
@@ -707,6 +738,7 @@ export function ModelSelector({
showCloudIndicator = false,
task,
catalog,
+ communityModelPolicy = "none",
placeholder,
loaded,
}: ModelSelectorProps) {
@@ -826,6 +858,8 @@ export function ModelSelector({
<ModelSelectorContent
open={open}
models={models}
+ additionalOnDeviceModels={additionalOnDeviceModels}
+ loadedModelIdOverride={loadedModelIdOverride}
loraModels={loraModels}
externalModels={externalModels}
value={selected}
@@ -839,14 +873,18 @@ export function ModelSelector({
onEject={onEject ? handleEject : undefined}
onFoldersChange={onFoldersChange}
onPickLocalModel={onPickLocalModel ? handlePickLocalModel : undefined}
- // The image tab (the only caller passing `task`) is a self-contained curated + on-device picker, so it omits the "Search Hub" button.
- onBrowseHub={task ? undefined : handleBrowseHub}
+ // A curated task picker (Images / Video) is self-contained, so it omits this.
+ // A community-enabled one (Audio) already lists past unsloth, so it keeps it.
+ onBrowseHub={
+ task && communityModelPolicy === "none" ? undefined : handleBrowseHub
+ }
onModelsChange={onModelsChange}
deleteDisabled={deleteDisabled}
className={contentClassName}
dataTour={contentDataTour}
task={task}
catalog={catalog}
+ communityModelPolicy={communityModelPolicy}
/>
</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
new file mode 100644
index 00000000000..93c4606b9fd
--- /dev/null
+++ b/studio/frontend/src/features/model-picker/components/model-selector/audio-picker-policy.ts
@@ -0,0 +1,268 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import type { FormatFilter } from "./recommended-fit";
+import type { ModelSelectorChangeMeta } from "./types";
+
+export type CommunityModelPolicy = "none" | "search-only" | "recommended";
+
+export function shouldDiscoverCommunityModels(
+ policy: CommunityModelPolicy,
+): boolean {
+ return policy !== "none";
+}
+
+export function shouldRecommendCommunityModels(
+ policy: CommunityModelPolicy,
+): boolean {
+ return policy === "recommended";
+}
+
+/** Community ASR runs through the Transformers Whisper sidecar. Curated GGUF/MTMD
+ * artifacts are handled by the catalog before this gate, so an uncurated row must
+ * identify a non-GGUF Whisper checkpoint. */
+export function communityAudioRowIsRunnable({
+ isStt,
+ isTts,
+ isGguf,
+ id,
+ baseModel,
+ tags,
+ libraryName,
+}: {
+ isStt: boolean;
+ isTts: boolean;
+ isGguf: boolean;
+ id: string;
+ baseModel?: string | null;
+ tags?: readonly string[] | null;
+ libraryName?: string | null;
+}): boolean {
+ if (!isStt && !isTts) {
+ return true;
+ }
+ const evidence = [id, baseModel ?? "", ...(tags ?? [])].map((value) =>
+ value.toLowerCase(),
+ );
+ if (isStt) {
+ if (isGguf) return false;
+ if (libraryName && libraryName.toLowerCase() !== "transformers")
+ return false;
+ return evidence.some((value) => value.includes("whisper"));
+ }
+
+ // The main-slot TTS backend decodes only the four codec families below.
+ // Hub's text-to-speech tag also covers Bark, VITS, SpeechT5, and many other
+ // architectures that can load as language models but cannot emit a WAV here.
+ // Llasa is NOT here despite being a well-known TTS family: it speaks XCodec2, which
+ // AudioCodecManager cannot decode, so admitting it produced a row that loaded and then
+ // failed at generation. The list and the comment above must stay in step.
+ const family = evidence.find((value) =>
+ /(?:^|[-_./])(orpheus|csm|spark-?tts|outetts|oute-?tts)(?:$|[-_./])/.test(value),
+ );
+ if (!family) return false;
+ // llama.cpp intentionally has no CSM decoder; CSM is Transformers-only.
+ return !(isGguf && /(?:^|[-_./])csm(?:$|[-_./])/.test(family));
+}
+
+/** Whether an audio pick from the chat picker may be routed to the Audio page.
+ *
+ * The page's own lists apply `communityAudioRowIsRunnable`, so routing a repo that fails
+ * it lands on a page that cannot show the row, and its `?model=` handoff evicts the chat
+ * model before reporting the repo unsupported. Curated ids always route: the catalog,
+ * not the tag, is their runtime contract. */
+export function audioPickIsRoutable({
+ id,
+ task,
+ isGguf,
+ isCurated,
+ isLocalCheckpoint = false,
+ baseModel,
+ tags,
+ libraryName,
+}: {
+ id: string;
+ task: string | null | undefined;
+ isGguf: boolean;
+ isCurated: boolean;
+ /** Trained or exported here, so its codec was read off the checkpoint itself. */
+ isLocalCheckpoint?: boolean;
+ baseModel?: string | null;
+ tags?: readonly string[] | null;
+ libraryName?: string | null;
+}): boolean {
+ if (isCurated) return true;
+ // A checkpoint from outputs/ has no Hub identity for communityAudioRowIsRunnable to
+ // judge, and the family-name heuristic it applies would reject it on its directory
+ // name. Its task came from the backend reading the checkpoint, which is the stronger
+ // signal, and the Audio page lists it off that same tag.
+ if (isLocalCheckpoint) {
+ return (
+ task === "text-to-speech" || task === "automatic-speech-recognition"
+ );
+ }
+ // The same Hub evidence the Audio page's own lists judge on. Passing the id alone
+ // rejected a checkpoint whose family is in its tags or base model rather than its
+ // name, so the page listed it but the chat picker refused to route to it.
+ return communityAudioRowIsRunnable({
+ isStt: task === "automatic-speech-recognition",
+ isTts: task === "text-to-speech",
+ isGguf,
+ id,
+ baseModel,
+ tags,
+ libraryName,
+ });
+}
+
+/** The macOS audio runtime can execute TTS only through llama.cpp GGUF. Curated
+ * families may expose a non-GGUF canonical row because Audio resolves it to a published
+ * GGUF sibling before loading. */
+export function macTtsHubRowIsRunnable({
+ isMac,
+ isTts,
+ isGguf,
+ hasRunnableGgufSibling,
+}: {
+ isMac: boolean;
+ isTts: boolean;
+ isGguf: boolean;
+ hasRunnableGgufSibling: boolean;
+}): boolean {
+ return !isMac || !isTts || isGguf || hasRunnableGgufSibling;
+}
+
+export function taskCatalogFormatMatches(
+ format: FormatFilter,
+ matchesFormat: boolean,
+): boolean {
+ return format === "all" || matchesFormat;
+}
+
+export function taskPickerRowMatches({
+ isCatalogSeed,
+ isHidden = false,
+ format,
+ matchesFormat,
+ matchesTask,
+ isRecommendable,
+}: {
+ isCatalogSeed: boolean;
+ isHidden?: boolean;
+ format: FormatFilter;
+ matchesFormat: boolean;
+ matchesTask: boolean;
+ isRecommendable: boolean;
+}): boolean {
+ if (isHidden && !isCatalogSeed) {
+ return false;
+ }
+ if (isCatalogSeed) {
+ return taskCatalogFormatMatches(format, matchesFormat);
+ }
+ if (!matchesTask) {
+ return false;
+ }
+ return format === "all" ? isRecommendable : matchesFormat;
+}
+
+/** A downloaded GGUF often exposes only its base architecture (Orpheus reports
+ * `llama`), so generic inventory correctly calls it chat. An exact curated Audio
+ * artifact is a stronger contract, but only for its own active Audio mode. */
+export function curatedAudioInventoryMatches({
+ isActiveCatalogArtifact,
+ catalogScope,
+ catalogTask,
+ pickerTask,
+}: {
+ isActiveCatalogArtifact: boolean;
+ catalogScope: string | null | undefined;
+ catalogTask: "tts" | "stt" | null | undefined;
+ pickerTask: string | readonly string[] | null | undefined;
+}): boolean {
+ if (
+ !isActiveCatalogArtifact ||
+ catalogScope !== "audio" ||
+ !catalogTask ||
+ !pickerTask
+ )
+ return false;
+ const expected =
+ catalogTask === "tts" ? "text-to-speech" : "automatic-speech-recognition";
+ return Array.isArray(pickerTask)
+ ? pickerTask.includes(expected)
+ : pickerTask === expected;
+}
+
+/** A cached Audio GGUF can be classified from its base architecture as text-generation.
+ * Only an exact catalog artifact may replace that fallback when Chat decides which task
+ * page owns the pick. */
+export function curatedAudioInventoryTask({
+ inventoryTask,
+ isExactCatalogArtifact,
+ catalogScope,
+ catalogTask,
+}: {
+ inventoryTask: string | null | undefined;
+ isExactCatalogArtifact: boolean;
+ catalogScope: string | null | undefined;
+ catalogTask: "tts" | "stt" | null | undefined;
+}): string | null {
+ if (
+ inventoryTask !== "text-generation" ||
+ !isExactCatalogArtifact ||
+ catalogScope !== "audio" ||
+ !catalogTask
+ ) {
+ return inventoryTask ?? null;
+ }
+ return catalogTask === "tts"
+ ? "text-to-speech"
+ : "automatic-speech-recognition";
+}
+
+/** Hidden infrastructure rows remain hidden unless the active task page passed
+ * their exact normalized artifact id as an explicit runtime contract. */
+export function allowedHiddenModelIdMatches(
+ allowedHiddenModelIds: ReadonlySet<string> | undefined,
+ ...modelIds: (string | null | undefined)[]
+): boolean {
+ return modelIds.some(
+ (modelId) =>
+ typeof modelId === "string" &&
+ allowedHiddenModelIds?.has(modelId.trim().toLowerCase()),
+ );
+}
+
+/** Fresh Hub rows carry their authoritative task in selection metadata, while
+ * downloaded/local rows retain their inventory task as a fallback. */
+export function taskForMediaPick(
+ pipelineTag: string | null | undefined,
+ inventoryTask: string | null | undefined,
+): string | null {
+ // Cache inventory commonly reports Audio GGUFs as generic text-generation;
+ // an exact catalog task is the stronger runtime contract in that case.
+ return pipelineTag && pipelineTag !== "text-generation"
+ ? pipelineTag
+ : (inventoryTask ?? pipelineTag ?? null);
+}
+
+/** Filesystem checkpoints cannot be served by the STT sidecars yet. Keep cached Hub
+ * snapshots and curated artifacts visible, but not local-directory rows that would send
+ * an absolute path to the Hub-only API. */
+export function filesystemRowsSupportedForTask(
+ pickerTask: string | readonly string[] | null | undefined,
+ rowTask?: string | null,
+): boolean {
+ const pickerIncludesStt = Array.isArray(pickerTask)
+ ? pickerTask.includes("automatic-speech-recognition")
+ : pickerTask === "automatic-speech-recognition";
+ return !pickerIncludesStt && rowTask !== "automatic-speech-recognition";
+}
+
+export function withPipelineTag(
+ meta: ModelSelectorChangeMeta,
+ pipelineTag: string | null | undefined,
+): ModelSelectorChangeMeta {
+ return pipelineTag ? { ...meta, pipelineTag } : meta;
+}
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/model-capabilities.ts b/studio/frontend/src/features/model-picker/components/model-selector/model-capabilities.ts
index 62ecac831b5..14bc2c03cab 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/model-capabilities.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/model-capabilities.ts
@@ -43,7 +43,7 @@ const REASONING_NAME_RE = new RegExp(
"i",
);
const AUDIO_NAME_RE = new RegExp(
- `${SEP}(?:whisper|tts|parakeet|parler|musicgen|bark|orpheus|csm|voice|speech|audio)${END}`,
+ `${SEP}(?:whisper|asr|tts|parakeet|parler|musicgen|bark|orpheus|csm|voice|speech|audio)${END}`,
"i",
);
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 ab14cde3888..d0ddfb19597 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
@@ -13,6 +13,7 @@ import assert from "node:assert/strict";
import type { CatalogGroup, ModelArtifact } from "./model-catalog.ts";
import {
+ AUDIO_CATALOG,
IMAGE_CATALOG,
VIDEO_CATALOG,
canonicalKeyFor,
@@ -137,7 +138,7 @@ assert.equal(
// ── catalog integrity: unique ids, artifacts resolve to exactly one group ──────
-for (const catalog of [IMAGE_CATALOG, VIDEO_CATALOG]) {
+for (const catalog of [IMAGE_CATALOG, VIDEO_CATALOG, AUDIO_CATALOG]) {
const seen = new Set<string>();
for (const group of catalog) {
for (const artifact of group.artifacts) {
@@ -607,6 +608,31 @@ assert.equal(
true,
);
+// ── audio catalog: task tags, grouping, load specs ─────────────────────────────
+
+// Every audio group carries a task tag; the other catalogs carry none.
+for (const group of AUDIO_CATALOG) {
+ assert.ok(group.task === "tts" || group.task === "stt", `audio group ${group.canonicalId} needs a task`);
+ assert.equal(group.scope, "audio");
+}
+for (const catalog of [IMAGE_CATALOG, VIDEO_CATALOG]) {
+ for (const group of catalog) {
+ assert.equal(group.task, undefined, `non-audio group ${group.canonicalId} must not carry a task`);
+ }
+}
+// The Orpheus GGUF groups with its safetensors base and reports the gguf load kind.
+const orpheus = groupForRepoId("unsloth/orpheus-3b-0.1-ft-GGUF", AUDIO_CATALOG);
+assert.ok(orpheus);
+assert.equal(orpheus.canonicalId, "unsloth/orpheus-3b-0.1-ft");
+assert.equal(orpheus.task, "tts");
+assert.equal(loadSpecFor("unsloth/orpheus-3b-0.1-ft-GGUF", AUDIO_CATALOG)?.kind, "gguf");
+assert.equal(loadSpecFor("unsloth/csm-1b", AUDIO_CATALOG)?.kind, "pipeline");
+// The whisper sidecar repos resolve as stt groups.
+assert.equal(groupForRepoId("unsloth/whisper-large-v3-turbo", AUDIO_CATALOG)?.task, "stt");
+assert.equal(groupForRepoId("unslothai/Qwen3-ASR-0.6B-GGUF", AUDIO_CATALOG)?.task, "stt");
+// A chat model stays unknown to the audio catalog.
+assert.equal(groupForRepoId("unsloth/Llama-3.3-70B-GGUF", AUDIO_CATALOG), null);
+
// ── groupMatchesQuery ──────────────────────────────────────────────────────────
assert.ok(groupMatchesQuery(qwenGroup, "qwen"));
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts
index 68f8b25b4b1..b4f56c7619f 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts
@@ -34,6 +34,8 @@ export interface ModelArtifact {
totalParams?: number;
/** Gated on the Hub (license + token). A bare group click skips it when not downloaded and falls through to an open artifact (e.g. the GGUF); an already-downloaded gated artifact is still returned. */
gated?: boolean;
+ /** Fixed quant when a specialized runtime pins one exact GGUF file. */
+ deviceQuant?: string;
}
export interface CatalogGroup {
@@ -42,7 +44,9 @@ export interface CatalogGroup {
displayName: string;
/** Row meta line ("Text-to-image", "Image editing", "Text-to-video with audio"). */
description: string;
- scope: "image" | "video";
+ scope: "image" | "video" | "audio";
+ /** Audio-only task tag driving the Audio page's Speak/Transcribe mode interlock. */
+ task?: "tts" | "stt";
/** Descending quality order: bf16, fp8, bnb-4bit, gguf. The router walks it. */
artifacts: ModelArtifact[];
/** Cross-owner ids that resolve to this group. Suffix stripping never merges two owners on its own. */
@@ -445,6 +449,121 @@ export const VIDEO_CATALOG: CatalogGroup[] = [
},
];
+// The Audio page's curated list. tts groups load into the main slot via /api/inference/load
+// (Orpheus is the only family the llama.cpp TTS path also serves as GGUF); stt groups map to
+// the dictation sidecar models in stt-model-catalog.ts, so their sizes are informational only.
+export const AUDIO_CATALOG: CatalogGroup[] = [
+ {
+ canonicalId: "unsloth/orpheus-3b-0.1-ft",
+ displayName: "Orpheus TTS 3B",
+ description: "Text-to-speech",
+ scope: "audio",
+ task: "tts",
+ artifacts: [
+ bf16Pipeline("unsloth/orpheus-3b-0.1-ft", 7, { label: "Safetensors" }),
+ gguf("unsloth/orpheus-3b-0.1-ft-GGUF"),
+ ],
+ },
+ {
+ canonicalId: "unsloth/csm-1b",
+ displayName: "Sesame CSM 1B",
+ description: "Text-to-speech",
+ scope: "audio",
+ task: "tts",
+ // No GGUF artifact: the llama.cpp TTS path has no csm decode, so CSM runs transformers-only.
+ artifacts: [bf16Pipeline("unsloth/csm-1b", 6, { label: "Safetensors" })],
+ },
+ {
+ canonicalId: "unsloth/Spark-TTS-0.5B",
+ displayName: "Spark TTS 0.5B",
+ description: "Text-to-speech",
+ scope: "audio",
+ task: "tts",
+ artifacts: [bf16Pipeline("unsloth/Spark-TTS-0.5B", 3, { label: "Safetensors" })],
+ },
+ {
+ canonicalId: "unsloth/Llama-OuteTTS-1.0-1B",
+ displayName: "Oute TTS 1B",
+ description: "Text-to-speech",
+ scope: "audio",
+ task: "tts",
+ artifacts: [
+ bf16Pipeline("unsloth/Llama-OuteTTS-1.0-1B", 4, { label: "Safetensors" }),
+ ],
+ },
+ // Llasa is deliberately absent. It speaks XCodec2 (65,536 <|s_N|> tokens), which is
+ // neither in _AUDIO_TOKEN_PATTERNS nor in AudioCodecManager, so a curated row here
+ // loaded and then failed at generation with "not a supported TTS model". Studio can
+ // still TRAIN Llasa (unsloth_Llasa-3B.yaml); this catalog only feeds the Generate
+ // picker. Re-add both rows together with an xcodec2 decoder.
+ {
+ canonicalId: "unslothai/Qwen3-ASR-0.6B-GGUF",
+ displayName: "Qwen3-ASR 0.6B",
+ description: "Speech-to-text",
+ scope: "audio",
+ task: "stt",
+ artifacts: [
+ gguf("unslothai/Qwen3-ASR-0.6B-GGUF", { deviceQuant: "Q8_0" }),
+ ],
+ },
+ {
+ canonicalId: "unslothai/Qwen3-ASR-1.7B-GGUF",
+ displayName: "Qwen3-ASR 1.7B",
+ description: "Speech-to-text",
+ scope: "audio",
+ task: "stt",
+ artifacts: [
+ gguf("unslothai/Qwen3-ASR-1.7B-GGUF", { deviceQuant: "Q8_0" }),
+ ],
+ },
+ {
+ canonicalId: "unsloth/whisper-large-v3-turbo",
+ displayName: "Whisper Large v3 Turbo",
+ description: "Speech-to-text",
+ scope: "audio",
+ task: "stt",
+ artifacts: [
+ bf16Pipeline("unsloth/whisper-large-v3-turbo", 2, { label: "Safetensors" }),
+ ],
+ },
+ {
+ canonicalId: "unsloth/whisper-large-v3",
+ displayName: "Whisper Large v3",
+ description: "Speech-to-text",
+ scope: "audio",
+ task: "stt",
+ artifacts: [
+ bf16Pipeline("unsloth/whisper-large-v3", 4, { label: "Safetensors" }),
+ ],
+ },
+ {
+ canonicalId: "unsloth/whisper-small",
+ displayName: "Whisper Small",
+ description: "Speech-to-text",
+ scope: "audio",
+ task: "stt",
+ artifacts: [bf16Pipeline("unsloth/whisper-small", 1, { label: "Safetensors" })],
+ },
+ // Both sidecars carry tiny/base (GGML_STT_REPOS, STT_MODEL_REPOS) and Voice
+ // settings lists them; only this picker was missing them.
+ {
+ canonicalId: "unsloth/whisper-base",
+ displayName: "Whisper Base",
+ description: "Speech-to-text",
+ scope: "audio",
+ task: "stt",
+ artifacts: [bf16Pipeline("unsloth/whisper-base", 1, { label: "Safetensors" })],
+ },
+ {
+ canonicalId: "unsloth/whisper-tiny",
+ displayName: "Whisper Tiny",
+ description: "Speech-to-text",
+ scope: "audio",
+ task: "stt",
+ artifacts: [bf16Pipeline("unsloth/whisper-tiny", 1, { label: "Safetensors" })],
+ },
+];
+
// ── canonical keys and lookups ──────────────────────────────────────────────────
// Artifact/format suffixes stripped (repeatedly, longest-first) off the NAME part of a repo id. Owner is preserved: cross-owner merges happen only via the alias tables above.
@@ -514,7 +633,7 @@ interface CatalogIndex {
artifactById: Map<string, ModelArtifact>;
}
-// Rebuilt only on a new catalog array identity; the curated arrays are module constants, so in practice twice (images + video).
+// Rebuilt only on a new catalog array identity; the curated arrays are module constants, so in practice once per catalog (images, video, audio).
const indexCache = new WeakMap<CatalogGroup[], CatalogIndex>();
function indexFor(catalog: CatalogGroup[]): CatalogIndex {
@@ -626,6 +745,7 @@ export function catalogToModelOptions(catalog: CatalogGroup[]): ModelOption[] {
name: curatedDisplayNameFor(artifact.repoId, catalog) ?? group.displayName,
description: `${group.description} - ${artifact.label}`,
isGguf: artifact.format === "gguf",
+ deviceQuant: artifact.deviceQuant,
});
}
}
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 4aee383cfc9..a0b8752e90f 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
@@ -1,7 +1,6 @@
// 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 { useNavigate } from "@tanstack/react-router";
import { shouldRefreshPickerInventoryOnMount } from "@/components/resource-picker/picker-tab-policy";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
@@ -52,7 +51,6 @@ import {
type HfSortKey,
useHubModelSearch,
} from "@/features/hub";
-import type { HfTaskFilter } from "@/features/hub/hooks/use-hub-model-search";
import {
classifyUnslothSupport,
downloadManager,
@@ -63,6 +61,7 @@ import {
useHfTokenStore,
useOnlineStatus,
} from "@/features/hub";
+import type { HfTaskFilter } from "@/features/hub/hooks/use-hub-model-search";
import { useDebouncedValue, useGpuInfo, useInferenceGpuInfo } from "@/hooks";
import { diffusionRouteSearch } from "@/lib/diffusion-route-search";
import { extractParamLabel } from "@/lib/model-size";
@@ -86,6 +85,7 @@ import {
ViewIcon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
+import { useNavigate } from "@tanstack/react-router";
import { ChevronDownIcon, ChevronRightIcon } from "lucide-react";
import {
type Dispatch,
@@ -100,12 +100,37 @@ import {
useState,
} from "react";
import { useChatPickerInventory } from "../../inventory/use-chat-picker-inventory";
+import {
+ type CommunityModelPolicy,
+ allowedHiddenModelIdMatches,
+ audioPickIsRoutable,
+ communityAudioRowIsRunnable,
+ curatedAudioInventoryMatches,
+ curatedAudioInventoryTask,
+ filesystemRowsSupportedForTask,
+ macTtsHubRowIsRunnable,
+ shouldDiscoverCommunityModels,
+ shouldRecommendCommunityModels,
+ taskCatalogFormatMatches,
+ taskForMediaPick,
+ taskPickerRowMatches,
+} from "./audio-picker-policy";
import { FolderBrowser } from "./folder-browser";
import {
type ModelCapabilities,
detectCapabilities,
hasAnyCapability,
} from "./model-capabilities";
+import {
+ AUDIO_CATALOG,
+ type CatalogGroup,
+ artifactForRepoId,
+ curatedCapabilitiesFor,
+ curatedDisplayNameFor,
+ curatedSizeBytesFor,
+ curatedTotalParamsFor,
+ groupForRepoId,
+} from "./model-catalog";
import { ModelDeleteAction } from "./model-delete-action";
import { ModelLoadSettingsAction } from "./model-load-settings-action";
import { ModelRowMenu } from "./model-row-menu";
@@ -163,14 +188,6 @@ import type {
ModelDownloadFootprintResolver,
ModelSelectorChangeMeta,
} from "./types";
-import {
- type CatalogGroup,
- artifactForRepoId,
- curatedCapabilitiesFor,
- curatedDisplayNameFor,
- curatedSizeBytesFor,
- curatedTotalParamsFor,
-} from "./model-catalog";
import { describeVariantListingError } from "./variant-listing-error";
import {
shouldMountVariantExpander,
@@ -182,11 +199,16 @@ function dedupe(values: string[]): string[] {
return [...new Set(values.filter(Boolean))];
}
-/** Repos published by Unsloth; the rest group under the "Other models" section. */
+/** The primary namespace used by runtime trust gates. */
function isUnslothRepoId(repoId: string): boolean {
return repoId.toLowerCase().startsWith("unsloth/");
}
+/** Official publisher namespaces used only for visual On Device grouping. */
+function isUnslothPublisherRepoId(repoId: string): boolean {
+ return isUnslothOwner(splitRepoLabel(repoId).owner);
+}
+
/** Lowercase and strip separators for fuzzy search. */
function normalizeForSearch(s: string): string {
return s.toLowerCase().replace(/[\s_.-]/g, "");
@@ -1103,10 +1125,9 @@ function useSoleDownloadedQuants(
});
}, [repos, variantsVersion]);
- const [entries, setEntries] =
- useState<ReadonlyMap<string, SoleQuantEntry<SoleDownloadedQuant>>>(
- EMPTY_SOLE_QUANT_ENTRIES,
- );
+ const [entries, setEntries] = useState<
+ ReadonlyMap<string, SoleQuantEntry<SoleDownloadedQuant>>
+ >(EMPTY_SOLE_QUANT_ENTRIES);
const { quants, pending, stale } = useMemo(
() => partitionSoleQuants(targets, entries, { enabled }),
[targets, entries, enabled],
@@ -1163,6 +1184,7 @@ function useSoleDownloadedQuants(
function GgufVariantExpander({
repoId,
+ pipelineTag,
loadId,
cachePath,
onSelect,
@@ -1182,6 +1204,7 @@ function GgufVariantExpander({
onHasVision,
}: {
repoId: string;
+ pipelineTag?: string | null;
/** Snapshot the cached listing pinned this repo to, if any. */
loadId?: string | null;
/** Cache directory this downloaded row represents, if any. */
@@ -1306,7 +1329,12 @@ function GgufVariantExpander({
const handleVariantClick = useCallback(
// ``filename`` is required, not decorative: the diffusion pages load a quant with {kind: "gguf", filename} and gate that branch on meta.ggufFilename, so a quant label alone made every Images/Video GGUF pick a dead click.
- (quant: string, filename: string, downloaded?: boolean, sizeBytes?: number) => {
+ (
+ quant: string,
+ filename: string,
+ downloaded?: boolean,
+ sizeBytes?: number,
+ ) => {
const isAvailable = isLocalPath || downloaded === true;
onSelect(repoId, {
source: sourceOverride ?? (isLocalPath ? "local" : "hub"),
@@ -1319,9 +1347,18 @@ function GgufVariantExpander({
expectedBytes: sizeBytes,
contextLength: isAvailable ? nativeContext : undefined,
isGguf: true,
+ pipelineTag,
});
},
- [repoId, loadId, isLocalPath, onSelect, sourceOverride, nativeContext],
+ [
+ repoId,
+ loadId,
+ isLocalPath,
+ onSelect,
+ sourceOverride,
+ nativeContext,
+ pipelineTag,
+ ],
);
// GGUF fit classification matching llama-server's _select_gpus logic:
@@ -1826,19 +1863,32 @@ export const IMAGE_GEN_TASKS = [
// image-to-video is included because HF gives the LTX-2 family that pipeline_tag, so a text-to-video-only filter dropped it out of Video Hub search.
export const VIDEO_GEN_TASKS = ["text-to-video", "image-to-video"] as const;
+// Speech pipeline tasks: owned by the Audio page. TTS picks load there rather than into chat; ASR picks map to the dictation sidecar.
+export const AUDIO_GEN_TASKS = [
+ "text-to-speech",
+ "automatic-speech-recognition",
+] as const;
+
// Diffusion GGUF archs the Images backend cannot assemble yet (SD/SDXL/PixArt/Wan/...). The backend tags them with this task so the chat picker hides them and the Images picker leaves them out (they would 400 on load).
const UNSUPPORTED_DIFFUSION_TASK = "image-diffusion-unsupported";
-// Generation tasks the Images / Video pages own. Not chat-loadable, so an on-device pick routes to its page instead.
-const DIFFUSION_PAGE_TASKS: readonly string[] = [
+// Generation tasks the Images / Video / Audio pages own. Not chat-loadable, so an on-device pick routes to its page instead.
+const MEDIA_PAGE_TASKS: readonly string[] = [
...IMAGE_GEN_TASKS,
...VIDEO_GEN_TASKS,
+ ...AUDIO_GEN_TASKS,
];
/** The page that runs this task, or null when chat should handle the pick. */
-function diffusionPageForTask(task: string | null | undefined): "images" | "video" | null {
- if (!task || !DIFFUSION_PAGE_TASKS.includes(task)) return null;
- return (VIDEO_GEN_TASKS as readonly string[]).includes(task) ? "video" : "images";
+const TTS_CODECS = new Set(["snac", "csm", "bicodec", "dac"]);
+
+function mediaPageForTask(
+ task: string | null | undefined,
+): "images" | "video" | "audio" | null {
+ if (!task || !MEDIA_PAGE_TASKS.includes(task)) return null;
+ if ((VIDEO_GEN_TASKS as readonly string[]).includes(task)) return "video";
+ if ((AUDIO_GEN_TASKS as readonly string[]).includes(task)) return "audio";
+ return "images";
}
// Editing/inpaint checkpoints are tagged image-to-image but need an input image the text-to-image backend rejects (mirrors
@@ -1863,9 +1913,26 @@ function passesTaskGate(
repoTask: string | null | undefined,
repoId: string | null | undefined,
filter: HfTaskFilter,
+ catalog?: CatalogGroup[],
+ activeCatalogArtifactIds?: ReadonlySet<string>,
): boolean {
- if (filter)
- return taskMatchesFilter(repoTask, filter) && !isImageEditModel(repoId);
+ if (filter) {
+ const exactArtifact =
+ repoId && catalog ? artifactForRepoId(repoId, catalog) : null;
+ return (
+ (taskMatchesFilter(repoTask, filter) ||
+ curatedAudioInventoryMatches({
+ isActiveCatalogArtifact: Boolean(
+ repoId &&
+ activeCatalogArtifactIds?.has(repoId.trim().toLowerCase()),
+ ),
+ catalogScope: exactArtifact?.group.scope,
+ catalogTask: exactArtifact?.group.task,
+ pickerTask: filter,
+ })) &&
+ !isImageEditModel(repoId)
+ );
+ }
// Unfiltered (chat) picker: an on-device diffusion model stays listed and routes to the Images/Video page on click; only the never-loadable tag is hidden.
return repoTask !== UNSUPPORTED_DIFFUSION_TASK;
}
@@ -2029,17 +2096,23 @@ function localPathTooltip(name: string, path: string): ReactNode {
);
}
-function localModelMeta(isGguf = false): ModelSelectorChangeMeta {
+function localModelMeta(
+ isGguf = false,
+ pipelineTag?: string | null,
+): ModelSelectorChangeMeta {
return {
source: "local",
isLora: false,
isDownloaded: true,
...(isGguf ? { isGguf: true } : {}),
+ pipelineTag: pipelineTag ?? null,
};
}
-function localDirectGgufMeta(): ModelSelectorChangeMeta {
- return localModelMeta(true);
+function localDirectGgufMeta(
+ pipelineTag?: string | null,
+): ModelSelectorChangeMeta {
+ return localModelMeta(true, pipelineTag);
}
/** Hugging Face address for an online/Hub row, or undefined when the repo id is
@@ -2069,6 +2142,8 @@ function localModelMatchesFormat(
export function HubModelPicker({
models,
+ additionalOnDeviceModels = [],
+ loadedModelIdOverride,
loraModels = [],
externalModels = [],
value,
@@ -2084,8 +2159,13 @@ export function HubModelPicker({
onEject,
task,
catalog,
+ communityModelPolicy = "none",
}: {
models: ModelOption[];
+ /** Task-runtime downloads that use a cache layout the shared Hub inventory
+ * cannot represent (for example the two-file STT sidecars). */
+ additionalOnDeviceModels?: ModelOption[];
+ loadedModelIdOverride?: string;
/** Fine-tuned models, shown as a section in the On Device view. */
loraModels?: LoraModelOption[];
/** Connected provider models, shown in the Connected section. */
@@ -2108,6 +2188,10 @@ export function HubModelPicker({
task?: HfTaskFilter;
/** Curated catalog for a task-scoped picker: one canonical row per model, with its published formats as the second level. */
catalog?: CatalogGroup[];
+ /** Also surface community (non-unsloth) models carrying `task`'s pipeline tags, below
+ * the unsloth rows and in search. Opt-in, since the runtime has to load an arbitrary
+ * publisher's checkpoint: true of audio, not of the curated pages. */
+ communityModelPolicy?: CommunityModelPolicy;
}) {
const gpu = useGpuInfo();
const inferenceGpu = useInferenceGpuInfo();
@@ -2118,13 +2202,14 @@ export function HubModelPicker({
// cannot disagree.
const selectedCheckpoint = useChatRuntimeStore((s) => s.params.checkpoint);
const residentCheckpoint = useChatRuntimeStore((s) => s.residentCheckpoint);
- const loadedModelId = chatModelLoaded({
+ const chatLoadedModelId = chatModelLoaded({
checkpoint: selectedCheckpoint,
isExternalModel: isExternalModelId(selectedCheckpoint),
residentCheckpoint,
})
? selectedCheckpoint
: undefined;
+ const loadedModelId = loadedModelIdOverride ?? chatLoadedModelId;
// Loaded GGUF quant of the active model; marks the matching pinned row.
const activeGgufVariant = useChatRuntimeStore((s) => s.activeGgufVariant);
// Last-loaded timestamps power the "Recent" sort (vs "Downloaded" = file date).
@@ -2176,6 +2261,36 @@ export function HubModelPicker({
enabled: online && section === "recommended",
});
+ // Two hooks for the same reason the unsloth pair exists: browse must not refetch
+ // per keystroke, search must not be pinned to the empty query. pinUnslothFirst is
+ // off since the unsloth rows already sit above these.
+ const communityDiscoveryEnabled =
+ shouldDiscoverCommunityModels(communityModelPolicy) &&
+ Boolean(task) &&
+ online &&
+ section === "recommended";
+ const communityRecommendedEnabled =
+ shouldRecommendCommunityModels(communityModelPolicy) &&
+ communityDiscoveryEnabled;
+ const communityQuerySearch = useHubModelSearch(debouncedQuery, {
+ task,
+ ownerScope: "all",
+ sortBy: recommendedSortBy,
+ sortDirection: "desc",
+ pinUnslothFirst: false,
+ accessToken,
+ enabled: communityDiscoveryEnabled && debouncedQuery.trim().length > 0,
+ });
+ const communityBrowse = useHubModelSearch("", {
+ task,
+ ownerScope: "all",
+ sortBy: recommendedSortBy,
+ sortDirection: "desc",
+ pinUnslothFirst: false,
+ accessToken,
+ enabled: communityRecommendedEnabled && debouncedQuery.trim().length === 0,
+ });
+
// Lowercased repo ids confirmed GGUF by the store or HF search. Absence means
// "no hint" -> hasGgufSuffix is the fallback (don't conflate unknown with
// known-not-GGUF). Lowercased so store and HF IDs match regardless of casing.
@@ -2190,11 +2305,21 @@ export function HubModelPicker({
// in Recommended still expands variants instead of loading as a checkpoint.
const resultGgufIds = useMemo(() => {
const ids = new Set<string>();
- for (const result of [...results, ...recommendedSearch.results]) {
+ for (const result of [
+ ...results,
+ ...recommendedSearch.results,
+ ...communityQuerySearch.results,
+ ...communityBrowse.results,
+ ]) {
if (result.isGguf) ids.add(result.id.toLowerCase());
}
return ids;
- }, [results, recommendedSearch.results]);
+ }, [
+ results,
+ recommendedSearch.results,
+ communityQuerySearch.results,
+ communityBrowse.results,
+ ]);
const isKnownGgufRepo = useCallback(
(id: string): boolean => {
const key = id.toLowerCase();
@@ -2326,7 +2451,24 @@ export function HubModelPicker({
});
}, []);
- const pickerInventory = useChatPickerInventory({ enabled: true });
+ // `models` is already narrowed to this Audio mode and platform (notably the
+ // macOS TTS runtime). Use only exact artifacts from that active contract for
+ // downloaded-task and hidden-chat-sidecar exceptions.
+ const activeCatalogArtifactIds = useMemo(
+ () =>
+ new Set(
+ task && catalog
+ ? models
+ .filter((model) => artifactForRepoId(model.id, catalog) !== null)
+ .map((model) => model.id.trim().toLowerCase())
+ : [],
+ ),
+ [catalog, models, task],
+ );
+ const pickerInventory = useChatPickerInventory({
+ enabled: true,
+ allowedHiddenModelIds: activeCatalogArtifactIds,
+ });
const {
cachedGguf,
cachedModels,
@@ -2545,28 +2687,78 @@ export function HubModelPicker({
const isChatSupported = useCallback(
(r: HfModelResult) => {
// Image/Video tab (task set): only task-matching, non-editing results.
- if (task) return taskMatchesFilter(r.pipelineTag, task) && !isImageEditModel(r.id);
- return classifyUnslothSupport({
- modelId: r.id,
- pipelineTag: r.pipelineTag,
- tags: r.tags,
- libraryName: r.libraryName,
- quantMethod: r.quantMethod,
- deviceType,
- }).status !== "unsupported";
+ if (task)
+ return (
+ taskMatchesFilter(r.pipelineTag, task) && !isImageEditModel(r.id)
+ );
+ return (
+ classifyUnslothSupport({
+ modelId: r.id,
+ pipelineTag: r.pipelineTag,
+ tags: r.tags,
+ libraryName: r.libraryName,
+ quantMethod: r.quantMethod,
+ deviceType,
+ }).status !== "unsupported"
+ );
},
[deviceType, task],
);
+ const isTaskRuntimeSupported = useCallback(
+ (result: HfModelResult) => {
+ const isStt = Boolean(
+ task && taskMatchesFilter("automatic-speech-recognition", task),
+ );
+ const isTts = Boolean(task && taskMatchesFilter("text-to-speech", task));
+ return (
+ communityAudioRowIsRunnable({
+ isStt,
+ isTts,
+ isGguf: result.isGguf,
+ id: result.id,
+ baseModel: result.baseModel,
+ tags: result.tags,
+ libraryName: result.libraryName,
+ }) &&
+ macTtsHubRowIsRunnable({
+ isMac,
+ isTts,
+ isGguf: result.isGguf,
+ hasRunnableGgufSibling: Boolean(
+ catalog &&
+ groupForRepoId(result.id, catalog)?.artifacts.some(
+ (artifact) => artifact.format === "gguf",
+ ),
+ ),
+ })
+ );
+ },
+ [catalog, isMac, task],
+ );
+
+ const taskCatalogSeedIds = useMemo(
+ () =>
+ task
+ ? new Set(models.map((model) => model.id.trim().toLowerCase()))
+ : undefined,
+ [models, task],
+ );
+
const recommendedIds = useMemo(() => {
const all = dedupe([...models.map((model) => model.id), value ?? ""])
- .filter((id) => !isHiddenModelId(id))
+ .filter(
+ (id) =>
+ !isHiddenModelId(id) ||
+ allowedHiddenModelIdMatches(taskCatalogSeedIds, id),
+ )
.filter((id) => !downloadedSet.has(id.toLowerCase()))
// Task-scoped pages load single-file GGUF only; chat-only keeps runnable formats (GGUF anywhere, plus MLX/safetensors on Mac).
// A curated artifact stays listed whatever its format: loadSpecFor knows how to load each, and a GGUF-only rule hid every non-GGUF curated model.
.filter((id) =>
task
- ? isKnownGgufRepo(id) || Boolean(catalog && artifactForRepoId(id, catalog))
+ ? isKnownGgufRepo(id) ||
+ Boolean(catalog && artifactForRepoId(id, catalog))
: !chatOnly || isRecommendableFormat(id, isKnownGgufRepo(id), isMac),
)
// Member repos of a catalog group would collapse into the canonical group row, but nothing renders those rows yet and a
@@ -2589,6 +2781,7 @@ export function HubModelPicker({
isMac,
task,
catalog,
+ taskCatalogSeedIds,
]);
const showHfSection = debouncedQuery.trim().length > 0;
@@ -2607,14 +2800,14 @@ export function HubModelPicker({
const catalogSeedRows = useMemo<HfModelResult[]>(() => {
if (!task) return [];
return dedupe(models.map((model) => model.id))
- .filter((id) => !isHiddenModelId(id))
.filter((id) => !isMobileVariant(id))
.filter((id) => !isImageEditModel(id))
.filter((id) => {
const isG = isKnownGgufRepo(id);
- return formatFilter === "all"
- ? isRecommendableFormat(id, isG, isMac)
- : matchesFormatFilter(id, isG, formatFilter);
+ return taskCatalogFormatMatches(
+ formatFilter,
+ matchesFormatFilter(id, isG, formatFilter),
+ );
})
.map((id) => ({
id,
@@ -2629,7 +2822,21 @@ export function HubModelPicker({
// other source for its param chip, and most curated ids carry no "<n>B" token.
totalParams: catalog ? curatedTotalParamsFor(id, catalog) : undefined,
}));
- }, [catalog, models, formatFilter, isKnownGgufRepo, isMac, task]);
+ }, [catalog, models, formatFilter, isKnownGgufRepo, task]);
+
+ const isUnslothOwned = useCallback(
+ (id: string) => id.toLowerCase().startsWith("unsloth/"),
+ [],
+ );
+
+ /** Pipeline tag is the Hub's only signal, since the real test is the checkpoint's
+ * tokenizer and that needs the download first. Exports in another serialization are
+ * never loadable, so drop those by name (as FP8 does above). */
+ const isLoadableCommunityRepo = useCallback(
+ (id: string) =>
+ !/(^|[-_/.])(onnx|openvino|tflite|coreml)([-_./]|$)/i.test(id),
+ [],
+ );
const catalogSeedIds = useMemo(
() => catalogSeedRows.map((row) => row.id),
@@ -2640,16 +2847,33 @@ export function HubModelPicker({
// "recommended" sort also drops models too big for the device. Already-
// downloaded models stay visible (badged), never hidden.
const recommendedRows = useMemo(() => {
+ const catalogSeedIds = new Set(
+ catalogSeedRows.map((row) => row.id.toLowerCase()),
+ );
+ const keepCommon = (r: HfModelResult) => {
+ const isCatalogSeed = catalogSeedIds.has(r.id.toLowerCase());
+ return (
+ !isMobileVariant(r.id) &&
+ taskPickerRowMatches({
+ isCatalogSeed,
+ isHidden: isHiddenModelId(r.id),
+ format: formatFilter,
+ matchesFormat: matchesFormatFilter(r.id, r.isGguf, formatFilter),
+ matchesTask: isChatSupported(r),
+ isRecommendable: isRecommendableFormat(r.id, r.isGguf, isMac),
+ })
+ );
+ };
const keep = (r: HfModelResult) =>
- !isHiddenModelId(r.id) &&
- !isMobileVariant(r.id) &&
- isChatSupported(r) &&
- // No pick: device-recommended formats (GGUF, plus MLX on Mac). A pick wins.
- (formatFilter === "all"
- ? isRecommendableFormat(r.id, r.isGguf, isMac)
- : matchesFormatFilter(r.id, r.isGguf, formatFilter)) &&
+ keepCommon(r) &&
// Task pages load single-file GGUF, plus curated artifacts in any format.
- (!task || r.isGguf || Boolean(catalog && artifactForRepoId(r.id, catalog)));
+ (!task ||
+ r.isGguf ||
+ Boolean(catalog && artifactForRepoId(r.id, catalog)));
+ // A community row has no catalog artifact by definition, so the curated clause
+ // above would drop every third-party safetensors checkpoint. The rest applies.
+ const keepCommunity = (r: HfModelResult) =>
+ keepCommon(r) && isTaskRuntimeSupported(r);
// Members are not filtered here (see recommendedIds): it dropped them from
// Hub search too. "recommended" always device-filters; the "Fits on device"
// tick extends that to the other sorts.
@@ -2661,13 +2885,24 @@ export function HubModelPicker({
// Downloaded models show regardless of fit.
downloadedSet.has(r.id.toLowerCase()) ||
hfModelFitsDevice(r, r.isGguf ? rowInferenceGpu : rowGpu);
- return orderRecommendedRows({
+ const unslothRows = orderRecommendedRows({
seeds: catalogSeedRows,
results: recommendedSearch.results,
keep,
deviceFiltered,
fits,
});
+ if (!communityRecommendedEnabled) return unslothRows;
+ // Appended below everything unsloth publishes, so scrolling past the unsloth
+ // uploads continues into the wider Hub. Same keep/fits gates.
+ const above = new Set(unslothRows.map((r) => r.id.toLowerCase()));
+ const communityRows = communityBrowse.results
+ .filter((r) => !r.id.toLowerCase().startsWith("unsloth/"))
+ .filter((r) => isLoadableCommunityRepo(r.id))
+ .filter((r) => !above.has(r.id.toLowerCase()))
+ .filter(keepCommunity)
+ .filter((r) => !deviceFiltered || fits(r));
+ return [...unslothRows, ...communityRows];
}, [
recommendedSearch.results,
catalogSeedRows,
@@ -2676,11 +2911,15 @@ export function HubModelPicker({
fitOnDeviceOnly,
formatFilter,
isMac,
+ isTaskRuntimeSupported,
gpu,
inferenceGpu,
isChatSupported,
task,
catalog,
+ communityRecommendedEnabled,
+ communityBrowse.results,
+ isLoadableCommunityRepo,
]);
// Per-row meta + VRAM badge from the recommended listing's own metadata, with the
@@ -2691,7 +2930,13 @@ export function HubModelPicker({
string,
{ meta: string | null; status: VramFitStatus | null; est: number }
>();
- for (const r of [...recommendedSearch.results, ...catalogSeedRows]) {
+ // Community rows come from their own listing; without them folded in here
+ // they render with no size or VRAM chip.
+ for (const r of [
+ ...recommendedSearch.results,
+ ...catalogSeedRows,
+ ...communityBrowse.results,
+ ]) {
if (map.has(r.id)) continue;
const isG = isKnownGgufRepo(r.id);
// GGUF param count comes from the repo name or the GGUF metadata, so even
@@ -2752,19 +2997,87 @@ export function HubModelPicker({
return map;
}, [
recommendedSearch.results,
+ communityBrowse.results,
catalogSeedRows,
isKnownGgufRepo,
gpu,
inferenceGpu,
]);
+ // Hub pipeline tag per repo id, handed to the page on pick so a task page can
+ // classify an uncurated repo it has no catalog entry for.
+ const pipelineTagById = useMemo(() => {
+ const map = new Map<string, string>();
+ for (const r of [
+ ...results,
+ ...recommendedSearch.results,
+ ...communityQuerySearch.results,
+ ...communityBrowse.results,
+ ]) {
+ if (r.pipelineTag && !map.has(r.id)) map.set(r.id, r.pipelineTag);
+ }
+ return map;
+ }, [
+ results,
+ recommendedSearch.results,
+ communityQuerySearch.results,
+ communityBrowse.results,
+ ]);
+
+ // The rest of the Hub evidence the Audio page judges a community row on. Keyed the
+ // same way, so a chat pick is routed on what the page would have listed it on rather
+ // than on its repo name alone.
+ const hubEvidenceById = useMemo(() => {
+ const map = new Map<
+ string,
+ { baseModel?: string | null; tags?: string[]; libraryName?: string | null }
+ >();
+ for (const r of [
+ ...results,
+ ...recommendedSearch.results,
+ ...communityQuerySearch.results,
+ ...communityBrowse.results,
+ ]) {
+ if (map.has(r.id)) continue;
+ map.set(r.id, {
+ baseModel: r.baseModel,
+ tags: r.tags,
+ libraryName: r.libraryName,
+ });
+ }
+ // Downloaded rows too. The backend tags a cached Whisper checkpoint as ASR even when
+ // its repo name says nothing, and the Audio page lists it on those tags; without them
+ // here the same row picked from the unscoped Chat picker was judged on its id alone
+ // and refused routing to the page that does list it.
+ for (const c of cachedModels) {
+ if (map.has(c.repo_id)) continue;
+ map.set(c.repo_id, {
+ baseModel: null,
+ tags: c.tags,
+ libraryName: c.library_name,
+ });
+ }
+ return map;
+ }, [
+ results,
+ recommendedSearch.results,
+ communityQuerySearch.results,
+ communityBrowse.results,
+ cachedModels,
+ ]);
+
// Tag-accurate capabilities keyed by repo id, pooled from both HF listings, then the
// catalog for curated ids neither listing returned. Rows look it up by id and fall
// back to repo-name detection when absent, which cannot see an audio track a name
// does not mention. Listings first: real tags outrank curated data.
const capsById = useMemo(() => {
const map = new Map<string, ModelCapabilities>();
- for (const r of [...results, ...recommendedSearch.results]) {
+ for (const r of [
+ ...results,
+ ...recommendedSearch.results,
+ ...communityQuerySearch.results,
+ ...communityBrowse.results,
+ ]) {
if (map.has(r.id)) continue;
map.set(
r.id,
@@ -2783,17 +3096,39 @@ export function HubModelPicker({
}
}
return map;
- }, [results, recommendedSearch.results, catalog, catalogSeedRows]);
+ }, [
+ results,
+ recommendedSearch.results,
+ communityQuerySearch.results,
+ communityBrowse.results,
+ catalog,
+ catalogSeedRows,
+ ]);
// Ordered by the On Device dropdown (recent/download date/size/name). The gate keeps diffusion GGUFs in the Images/Video picker and out of chat.
const sortedCachedGguf = useMemo(
() =>
sortCachedRepos(
- cachedGguf.filter((c) => passesTaskGate(c.task, c.repo_id, task)),
+ cachedGguf.filter((c) =>
+ passesTaskGate(
+ c.task,
+ c.repo_id,
+ task,
+ catalog,
+ activeCatalogArtifactIds,
+ ),
+ ),
downloadedSort,
loadTimes,
),
- [cachedGguf, downloadedSort, loadTimes, task],
+ [
+ cachedGguf,
+ downloadedSort,
+ loadTimes,
+ task,
+ catalog,
+ activeCatalogArtifactIds,
+ ],
);
// Cached non-GGUF repos. In chat, passesTaskGate drops diffusers image repos; the Images picker keeps them, but only unsloth-hosted ones this backend can load. Base repos are cached as dependencies and fail the trust gate.
const sortedCachedModels = useMemo(
@@ -2803,22 +3138,61 @@ export function HubModelPicker({
(c) =>
// A partially-downloaded snapshot is not on-device: listing it as loadable errors or triggers a silent multi-GB re-fetch.
!c.partial &&
- passesTaskGate(c.task, c.repo_id, task) &&
+ passesTaskGate(
+ c.task,
+ c.repo_id,
+ task,
+ catalog,
+ activeCatalogArtifactIds,
+ ) &&
// Diffusion pickers: unsloth repos plus any repo the backend can LOAD. Gate on a curated ARTIFACT (what loadSpecFor resolves), not a group-key match: a base / uncurated-quant sibling matches the group by key but dead-ends at the trust gate.
// An unsloth repo must also be a full pipeline: the fall-through loads uncataloged rows as "pipeline", and from_pretrained on a single-file checkpoint repo fails. Curated single-file artifacts stay, since loadSpecFor carries their filename.
(!task ||
(isUnslothRepoId(c.repo_id) && !c.single_file) ||
- (catalog ? artifactForRepoId(c.repo_id, catalog) !== null : false)),
+ ((c.task === "automatic-speech-recognition" ||
+ c.task === "text-to-speech") &&
+ communityAudioRowIsRunnable({
+ isStt: c.task === "automatic-speech-recognition",
+ isTts: c.task === "text-to-speech",
+ isGguf: false,
+ id: c.repo_id,
+ tags: c.tags,
+ libraryName: c.library_name,
+ }) &&
+ macTtsHubRowIsRunnable({
+ isMac,
+ isTts: c.task === "text-to-speech",
+ isGguf: false,
+ hasRunnableGgufSibling: Boolean(
+ catalog &&
+ groupForRepoId(c.repo_id, catalog)?.artifacts.some(
+ (artifact) => artifact.format === "gguf",
+ ),
+ ),
+ })) ||
+ (catalog
+ ? artifactForRepoId(c.repo_id, catalog) !== null
+ : false)),
),
downloadedSort,
loadTimes,
),
- [cachedModels, downloadedSort, loadTimes, task, catalog],
+ [
+ cachedModels,
+ downloadedSort,
+ loadTimes,
+ task,
+ catalog,
+ activeCatalogArtifactIds,
+ isMac,
+ ],
);
// Task-scoped loads put the whole pipeline on ONE device, so quant fit uses the device the load lands on (the lowest visible ordinal), not the multi-GPU sum or the largest card: sizing against the bigger card OOMs the smaller one. Chat keeps the sum.
// The source is picked per row (a GGUF row sizes against the inference GPU, anything else against the system view); this only decides how much of it a row may claim.
const expanderGpuGbFrom = (info: typeof inferenceGpu) =>
- info.available ? loadScopedGpu(info, Boolean(task)).memoryTotalGb : undefined;
+ info.available
+ ? loadScopedGpu(info, Boolean(task)).memoryTotalGb
+ : undefined;
const expanderGpuGb = expanderGpuGbFrom(inferenceGpu);
const expanderSystemGpuGb = expanderGpuGbFrom(gpu);
@@ -2834,15 +3208,32 @@ export function HubModelPicker({
sortLocalModels(
lmStudioModels.filter(
(m) =>
+ filesystemRowsSupportedForTask(task, m.task) &&
// The backend tags every local model with its task for exactly this: on the Images/Video pages a chat GGUF must not be offered.
- passesTaskGate(m.task, m.model_id ?? m.id, task) &&
- localModelMatchesFormat(m, formatFilter) && matchesLocalQuery(m),
+ passesTaskGate(
+ m.task,
+ m.model_id ?? m.id,
+ task,
+ catalog,
+ activeCatalogArtifactIds,
+ ) &&
+ localModelMatchesFormat(m, formatFilter) &&
+ matchesLocalQuery(m),
),
downloadedSort,
loadTimes,
),
// eslint-disable-next-line react-hooks/exhaustive-deps
- [lmStudioModels, downloadedSort, formatFilter, loadTimes, localQuery, task],
+ [
+ lmStudioModels,
+ downloadedSort,
+ formatFilter,
+ loadTimes,
+ localQuery,
+ task,
+ catalog,
+ activeCatalogArtifactIds,
+ ],
);
// Local ./models entries. Chat-only Unsloth runs GGUF (any host) and MLX (Mac only), so raw checkpoints there are hidden (mirrors the cached
// non-GGUF rule); an MLX build a Mac user dropped in stays selectable. A task-scoped picker (Images) is exempt: the image backend loads local pipelines even there.
@@ -2851,7 +3242,14 @@ export function HubModelPicker({
sortLocalModels(
localDirModels.filter(
(m) =>
- passesTaskGate(m.task, m.model_id ?? m.id, task) &&
+ filesystemRowsSupportedForTask(task, m.task) &&
+ passesTaskGate(
+ m.task,
+ m.model_id ?? m.id,
+ task,
+ catalog,
+ activeCatalogArtifactIds,
+ ) &&
(!chatOnly ||
Boolean(task) ||
localModelIsGguf(m) ||
@@ -2872,6 +3270,8 @@ export function HubModelPicker({
localQuery,
chatOnly,
task,
+ catalog,
+ activeCatalogArtifactIds,
],
);
const sortedCustomFolderModels = useMemo(
@@ -2879,53 +3279,125 @@ export function HubModelPicker({
sortLocalModels(
customFolderModels.filter(
(m) =>
- passesTaskGate(m.task, m.model_id ?? m.id, task) &&
- localModelMatchesFormat(m, formatFilter) && matchesLocalQuery(m),
+ filesystemRowsSupportedForTask(task, m.task) &&
+ passesTaskGate(
+ m.task,
+ m.model_id ?? m.id,
+ task,
+ catalog,
+ activeCatalogArtifactIds,
+ ) &&
+ localModelMatchesFormat(m, formatFilter) &&
+ matchesLocalQuery(m),
),
customSort,
loadTimes,
),
// eslint-disable-next-line react-hooks/exhaustive-deps
- [customFolderModels, customSort, formatFilter, loadTimes, localQuery, task],
+ [
+ customFolderModels,
+ customSort,
+ formatFilter,
+ loadTimes,
+ localQuery,
+ task,
+ catalog,
+ activeCatalogArtifactIds,
+ ],
);
// Chat cannot load a diffusion model but the Images/Video pages can, so a pick routes to the page that runs it instead of hiding it or letting it 400. Task-scoped pickers select normally.
const navigateToPage = useNavigate();
const diffusionTaskById = useMemo(() => {
const byId = new Map<string, string>();
- const put = (id: string | null | undefined, t: string | null | undefined) => {
- if (id && t) byId.set(id.toLowerCase(), t);
+ const put = (
+ id: string | null | undefined,
+ t: string | null | undefined,
+ exactAudioArtifact = id ? artifactForRepoId(id, AUDIO_CATALOG) : null,
+ ) => {
+ const task = curatedAudioInventoryTask({
+ inventoryTask: t,
+ isExactCatalogArtifact: Boolean(exactAudioArtifact),
+ catalogScope: exactAudioArtifact?.group.scope,
+ catalogTask: exactAudioArtifact?.group.task,
+ });
+ if (id && task) byId.set(id.toLowerCase(), task);
};
for (const c of cachedGguf) put(c.repo_id, c.task);
for (const c of cachedModels) put(c.repo_id, c.task);
// Both ids: a local row's click passes m.id (a filesystem path for models_dir / LM Studio entries) while m.model_id is its HF-style name, so keying on one alone makes the lookup below miss.
const putLocal = (m: LocalModelInfo) => {
- put(m.id, m.task);
- put(m.model_id, m.task);
+ const exactAudioArtifact = m.model_id
+ ? artifactForRepoId(m.model_id, AUDIO_CATALOG)
+ : null;
+ put(m.id, m.task, exactAudioArtifact);
+ put(m.model_id, m.task, exactAudioArtifact);
};
for (const m of lmStudioModels) putLocal(m);
for (const m of localDirModels) putLocal(m);
for (const m of customFolderModels) putLocal(m);
return byId;
- }, [cachedGguf, cachedModels, lmStudioModels, localDirModels, customFolderModels]);
+ }, [
+ cachedGguf,
+ cachedModels,
+ lmStudioModels,
+ localDirModels,
+ customFolderModels,
+ ]);
const onSelect = useCallback(
(id: string, meta: ModelSelectorChangeMeta) => {
if (!task) {
- const page = diffusionPageForTask(diffusionTaskById.get(id.toLowerCase()));
+ const pickedTask = taskForMediaPick(
+ meta.pipelineTag,
+ diffusionTaskById.get(id.toLowerCase()),
+ );
+ const page = mediaPageForTask(pickedTask);
+ if (
+ page === "audio" &&
+ !audioPickIsRoutable({
+ id,
+ task: pickedTask,
+ isGguf: Boolean(meta.isGguf || meta.ggufFilename),
+ isCurated: artifactForRepoId(id, AUDIO_CATALOG) !== null,
+ isLocalCheckpoint:
+ meta.source === "lora" ||
+ meta.source === "exported" ||
+ meta.source === "local",
+ ...(hubEvidenceById.get(id) ?? {}),
+ })
+ ) {
+ // Loading it here would evict the chat model for a repo neither surface can run.
+ toast.error(
+ `${id} is not a speech model Unsloth can run yet. The Audio page lists the families it supports.`,
+ { duration: 7000 },
+ );
+ return;
+ }
if (page) {
void navigateToPage({
to: `/${page}`,
// `quant` is used verbatim as the gguf filename, so a label like "Q4_K_M" rides ggufQuant instead; dropping it
// made every non-curated GGUF repo arrive as a bare repo id.
- search: diffusionRouteSearch(id, meta),
+ search:
+ page === "audio"
+ ? {
+ model: id,
+ quant: meta.ggufFilename ?? undefined,
+ ggufQuant: meta.ggufFilename
+ ? undefined
+ : (meta.ggufVariant ?? undefined),
+ // pickedTask, not meta.pipelineTag: a cached row carries no tag to forward.
+ task: pickedTask ?? undefined,
+ }
+ : diffusionRouteSearch(id, meta),
});
return;
}
}
onSelectProp(id, meta);
},
- [task, diffusionTaskById, navigateToPage, onSelectProp],
+ [task, diffusionTaskById, hubEvidenceById, navigateToPage, onSelectProp],
);
// Fine-tuned models for the On Device "Fine-tuned" section: flat, query-
@@ -2982,6 +3454,59 @@ export function HubModelPicker({
// blank. A task-scoped picker (Images) is exempt: the image backend loads local diffusers/safetensors pipelines even on chat-only hosts.
const visibleCachedModelRows = chatOnly && !task ? [] : visibleCachedModels;
+ const visibleAdditionalOnDeviceModels = useMemo(() => {
+ const alreadyListed = new Set(
+ [...visibleCachedGguf, ...visibleCachedModels].map((model) =>
+ model.repo_id.trim().toLowerCase(),
+ ),
+ );
+ const seen = new Set<string>();
+ const needle = normalizeForSearch(debouncedQuery.trim());
+ const filtered = additionalOnDeviceModels.filter((model) => {
+ const id = model.id.trim().toLowerCase();
+ if (!id || alreadyListed.has(id) || seen.has(id)) return false;
+ seen.add(id);
+ return (
+ matchesFormatFilter(model.id, model.isGguf === true, formatFilter) &&
+ (!needle ||
+ normalizeForSearch(
+ `${model.id} ${model.name} ${model.description ?? ""}`,
+ ).includes(needle))
+ );
+ });
+ return sortCachedRepos(
+ filtered.map((model) => ({
+ repo_id: model.id,
+ size_bytes: model.deviceSizeBytes ?? 0,
+ model,
+ })),
+ downloadedSort,
+ loadTimes,
+ ).map(({ model }) => model);
+ }, [
+ additionalOnDeviceModels,
+ visibleCachedGguf,
+ visibleCachedModels,
+ debouncedQuery,
+ downloadedSort,
+ formatFilter,
+ loadTimes,
+ ]);
+ const unslothAdditionalOnDeviceModels = useMemo(
+ () =>
+ visibleAdditionalOnDeviceModels.filter((model) =>
+ isUnslothPublisherRepoId(model.id),
+ ),
+ [visibleAdditionalOnDeviceModels],
+ );
+ const otherAdditionalOnDeviceModels = useMemo(
+ () =>
+ visibleAdditionalOnDeviceModels.filter(
+ (model) => !isUnslothPublisherRepoId(model.id),
+ ),
+ [visibleAdditionalOnDeviceModels],
+ );
+
// Unfiltered list, so typing a query doesn't re-run resolution.
const soleQuants = useSoleDownloadedQuants(sortedCachedGguf, {
enabled: section === "downloaded" && !showAllQuantizations,
@@ -3110,24 +3635,28 @@ export function HubModelPicker({
// Split downloaded models so non-Unsloth repos get their own "Other models"
// section above Fine-tuned.
const unslothCachedGguf = useMemo(
- () => visibleCachedGguf.filter((c) => isUnslothRepoId(c.repo_id)),
+ () => visibleCachedGguf.filter((c) => isUnslothPublisherRepoId(c.repo_id)),
[visibleCachedGguf],
);
const otherCachedGguf = useMemo(
- () => visibleCachedGguf.filter((c) => !isUnslothRepoId(c.repo_id)),
+ () => visibleCachedGguf.filter((c) => !isUnslothPublisherRepoId(c.repo_id)),
[visibleCachedGguf],
);
const unslothCachedModelRows = useMemo(
() =>
visibleCachedModelRows.filter(
- (c) => isUnslothRepoId(c.repo_id) && !pinnedSet.has(pinKey(c.repo_id)),
+ (c) =>
+ isUnslothPublisherRepoId(c.repo_id) &&
+ !pinnedSet.has(pinKey(c.repo_id)),
),
[visibleCachedModelRows, pinnedSet],
);
const otherCachedModelRows = useMemo(
() =>
visibleCachedModelRows.filter(
- (c) => !isUnslothRepoId(c.repo_id) && !pinnedSet.has(pinKey(c.repo_id)),
+ (c) =>
+ !isUnslothPublisherRepoId(c.repo_id) &&
+ !pinnedSet.has(pinKey(c.repo_id)),
),
[visibleCachedModelRows, pinnedSet],
);
@@ -3222,12 +3751,13 @@ export function HubModelPicker({
[filteredRecommendedIds],
);
- const hfIds = useMemo(() => {
- // Only the Unsloth tab searches the HF listing, and only Unsloth models.
- if (!showHfSection || section !== "recommended") return [];
- return (
- results
+ // One pipeline for both listings, so community rows clear the same gates;
+ // `owned` is the only difference.
+ const searchIdsFrom = useCallback(
+ (rows: readonly HfModelResult[], owned: (id: string) => boolean) =>
+ rows
.filter(isChatSupported)
+ .filter(isTaskRuntimeSupported)
.filter(
(r) =>
!fitOnDeviceOnly ||
@@ -3236,7 +3766,7 @@ export function HubModelPicker({
)
.map((result) => result.id)
.filter((id) => !isHiddenModelId(id))
- .filter((id) => id.toLowerCase().startsWith("unsloth/"))
+ .filter(owned)
.filter((id) => !recommendedSet.has(id))
// Chat-only keeps runnable formats: GGUF anywhere, plus MLX/safetensors
// on Mac (matches the empty Recommended view so search stays consistent).
@@ -3247,23 +3777,62 @@ export function HubModelPicker({
.filter((id) => !/-FP8[-.]|FP8-Dynamic/i.test(id))
.filter((id) =>
matchesFormatFilter(id, isKnownGgufRepo(id), formatFilter),
- )
+ ),
+ [
+ recommendedSet,
+ chatOnly,
+ isKnownGgufRepo,
+ isChatSupported,
+ isTaskRuntimeSupported,
+ formatFilter,
+ fitOnDeviceOnly,
+ downloadedSet,
+ searchRowFits,
+ isMac,
+ ],
+ );
+
+ const hfIds = useMemo(() => {
+ // Only the Unsloth tab searches the HF listing.
+ if (!showHfSection || section !== "recommended") return [];
+ return searchIdsFrom(results, isUnslothOwned);
+ }, [results, showHfSection, section, searchIdsFrom, isUnslothOwned]);
+
+ // Community search hits, listed after the unsloth ones. Deduped against them so
+ // a repo the unsloth listing already returned is not shown twice.
+ const communitySearchIds = useMemo(() => {
+ if (!communityDiscoveryEnabled || !showHfSection) return [];
+ const above = new Set(hfIds.map((id) => id.toLowerCase()));
+ const runnable = new Set(
+ communityQuerySearch.results
+ .filter(isTaskRuntimeSupported)
+ .map((result) => result.id.toLowerCase()),
);
+ return searchIdsFrom(
+ communityQuerySearch.results,
+ (id) =>
+ !isUnslothOwned(id) &&
+ isLoadableCommunityRepo(id) &&
+ runnable.has(id.toLowerCase()),
+ ).filter((id) => !above.has(id.toLowerCase()));
}, [
- recommendedSet,
- results,
+ communityDiscoveryEnabled,
showHfSection,
- section,
- chatOnly,
- isKnownGgufRepo,
- isChatSupported,
- formatFilter,
- fitOnDeviceOnly,
- downloadedSet,
- searchRowFits,
- isMac,
+ communityQuerySearch.results,
+ hfIds,
+ searchIdsFrom,
+ isUnslothOwned,
+ isLoadableCommunityRepo,
+ isTaskRuntimeSupported,
]);
+ /** Unsloth first, then community: one list so rows, keyboard order and the
+ * empty state cannot drift apart. */
+ const searchRowIds = useMemo(
+ () => [...hfIds, ...communitySearchIds],
+ [hfIds, communitySearchIds],
+ );
+
const hubOptionKeys = useMemo(() => {
const keys: string[] = [];
@@ -3286,9 +3855,11 @@ export function HubModelPicker({
// Downloaded (Unsloth) rows (query-filtered) on the On Device tab only.
if (
section === "downloaded" &&
- cachedReady &&
+ (cachedReady || unslothAdditionalOnDeviceModels.length > 0) &&
!downloadedCollapsed &&
- (unslothCachedGguf.length > 0 || unslothCachedModelRows.length > 0)
+ (unslothCachedGguf.length > 0 ||
+ unslothCachedModelRows.length > 0 ||
+ unslothAdditionalOnDeviceModels.length > 0)
) {
keys.push(
...unslothCachedGguf.map((model) =>
@@ -3300,6 +3871,11 @@ export function HubModelPicker({
makeModelOptionKey("downloaded-model", model.repo_id),
),
);
+ keys.push(
+ ...unslothAdditionalOnDeviceModels.map((model) =>
+ makeModelOptionKey("additional-on-device", model.id),
+ ),
+ );
}
// Unsloth-tab search keys (curated matches + HF unsloth results).
@@ -3309,16 +3885,20 @@ export function HubModelPicker({
makeModelOptionKey("search-recommended", id),
),
);
- keys.push(...hfIds.map((id) => makeModelOptionKey("search-hf", id)));
+ keys.push(
+ ...searchRowIds.map((id) => makeModelOptionKey("search-hf", id)),
+ );
return keys;
}
// Other (non-Unsloth) downloaded rows sit just above Fine-tuned.
if (
section === "downloaded" &&
- cachedReady &&
+ (cachedReady || otherAdditionalOnDeviceModels.length > 0) &&
!otherModelsCollapsed &&
- (otherCachedGguf.length > 0 || otherCachedModelRows.length > 0)
+ (otherCachedGguf.length > 0 ||
+ otherCachedModelRows.length > 0 ||
+ otherAdditionalOnDeviceModels.length > 0)
) {
keys.push(
...otherCachedGguf.map((model) =>
@@ -3330,6 +3910,11 @@ export function HubModelPicker({
makeModelOptionKey("downloaded-model", model.repo_id),
),
);
+ keys.push(
+ ...otherAdditionalOnDeviceModels.map((model) =>
+ makeModelOptionKey("additional-on-device", model.id),
+ ),
+ );
}
// Fine-tuned models sit below downloaded, above custom folders.
@@ -3380,7 +3965,7 @@ export function HubModelPicker({
fineTunedRows,
fineTunedCollapsed,
filteredRecommendedIds,
- hfIds,
+ searchRowIds,
sortedLmStudio,
lmStudioCollapsed,
recommendedRows,
@@ -3390,8 +3975,10 @@ export function HubModelPicker({
localDirCollapsed,
unslothCachedGguf,
unslothCachedModelRows,
+ unslothAdditionalOnDeviceModels,
otherCachedGguf,
otherCachedModelRows,
+ otherAdditionalOnDeviceModels,
otherModelsCollapsed,
]);
@@ -3464,13 +4051,33 @@ export function HubModelPicker({
return map;
}, [filteredRecommendedIds, recommendedParamCountById, isKnownGgufRepo, gpu]);
- const { scrollRef, sentinelRef } = useHubInfiniteScroll(
+ const searchHasMore =
+ hasMore || (communityDiscoveryEnabled && communityQuerySearch.hasMore);
+ const searchIsLoadingMore =
+ isLoadingMore || communityQuerySearch.isLoadingMore;
+ const fetchSearchMore = useCallback((): boolean | undefined => {
+ const unslothRequested = hasMore ? fetchMore() : false;
+ const communityRequested =
+ communityDiscoveryEnabled && communityQuerySearch.hasMore
+ ? communityQuerySearch.fetchMore()
+ : false;
+ if (unslothRequested || communityRequested) return true;
+ return undefined;
+ }, [
+ hasMore,
fetchMore,
- scannedCount,
+ communityDiscoveryEnabled,
+ communityQuerySearch.hasMore,
+ communityQuerySearch.fetchMore,
+ ]);
+ const { scrollRef, sentinelRef } = useHubInfiniteScroll(
+ fetchSearchMore,
+ scannedCount + communityQuerySearch.scannedCount,
{
- enabled: online && hasMore,
- isFetching: isLoading || isLoadingMore,
- resultCount: results.length,
+ enabled: online && searchHasMore,
+ isFetching:
+ isLoading || communityQuerySearch.isLoading || searchIsLoadingMore,
+ resultCount: results.length + communityQuerySearch.results.length,
resetKey: debouncedQuery,
},
);
@@ -3502,13 +4109,33 @@ export function HubModelPicker({
const recommendedSentinelRef = useCallback((node: HTMLDivElement | null) => {
setRecommendedSentinel(node);
}, []);
+ const recommendedHasMore =
+ recommendedSearch.hasMore ||
+ (communityRecommendedEnabled && communityBrowse.hasMore);
+ const recommendedIsLoadingMore =
+ recommendedSearch.isLoadingMore || communityBrowse.isLoadingMore;
+ const fetchRecommendedMore = useCallback(() => {
+ if (recommendedSearch.hasMore) {
+ recommendedSearch.fetchMore();
+ return;
+ }
+ if (communityRecommendedEnabled && communityBrowse.hasMore) {
+ communityBrowse.fetchMore();
+ }
+ }, [
+ recommendedSearch.hasMore,
+ recommendedSearch.fetchMore,
+ communityRecommendedEnabled,
+ communityBrowse.hasMore,
+ communityBrowse.fetchMore,
+ ]);
useEffect(() => {
- if (!recommendedSentinel || !recommendedSearch.hasMore) return;
+ if (!recommendedSentinel || !recommendedHasMore) return;
const root = scrollRef.current;
if (!root) return;
const obs = new IntersectionObserver(
([e]) => {
- if (e.isIntersecting) recommendedSearch.fetchMore();
+ if (e.isIntersecting) fetchRecommendedMore();
},
{ threshold: 0, root },
);
@@ -3516,9 +4143,10 @@ export function HubModelPicker({
return () => obs.disconnect();
}, [
recommendedSentinel,
- recommendedSearch.hasMore,
- recommendedSearch.fetchMore,
+ recommendedHasMore,
+ fetchRecommendedMore,
recommendedSearch.results.length,
+ communityBrowse.results.length,
scrollRef,
]);
@@ -3534,10 +4162,11 @@ export function HubModelPicker({
source: "hub",
isLora: false,
isDownloaded: downloadedSet.has(id.toLowerCase()),
+ pipelineTag: pipelineTagById.get(id) ?? null,
});
}
},
- [onSelect, isKnownGgufRepo, downloadedSet],
+ [onSelect, isKnownGgufRepo, downloadedSet, pipelineTagById],
);
// On Device owns the downloaded and custom-folder models; the Unsloth tab
@@ -3549,6 +4178,7 @@ export function HubModelPicker({
pinnedRows.length === 0 &&
visibleCachedGguf.length === 0 &&
visibleCachedModelRows.length === 0 &&
+ visibleAdditionalOnDeviceModels.length === 0 &&
sortedLmStudio.length === 0 &&
sortedLocalDir.length === 0 &&
// Fine-tuned models are on-device too: don't show the empty state above a
@@ -3693,7 +4323,9 @@ export function HubModelPicker({
const hasConnected = externalModels.length > 0;
// The Other models section and its shortcut only show with non-Unsloth downloads.
const hasOtherModels =
- otherCachedGguf.length > 0 || otherCachedModelRows.length > 0;
+ otherCachedGguf.length > 0 ||
+ otherCachedModelRows.length > 0 ||
+ otherAdditionalOnDeviceModels.length > 0;
const downloadedRowButtonClassName =
"bg-transparent pr-1 hover:bg-transparent focus-visible:bg-transparent dark:bg-transparent dark:hover:bg-transparent dark:focus-visible:bg-transparent";
@@ -3742,6 +4374,8 @@ export function HubModelPicker({
// The row loads one quant, so it is a GGUF pick like the expander's; without this the pages asked for a
// pipeline, which a GGUF repo rejects. No filename: the pin stores a label, resolved against the listing.
isGguf: true,
+ pipelineTag:
+ diffusionTaskById.get(entry.repoId.toLowerCase()) ?? null,
})
}
vramStatus={null}
@@ -3759,6 +4393,8 @@ export function HubModelPicker({
ggufVariant: entry.quant,
isDownloaded: true,
isGguf: true,
+ pipelineTag:
+ diffusionTaskById.get(entry.repoId.toLowerCase()) ?? null,
})
}
/>
@@ -3835,6 +4471,7 @@ export function HubModelPicker({
isDownloaded: true,
expectedBytes,
isGguf: true,
+ pipelineTag: c.task ?? null,
};
return (
<div key={c.repo_id} className={downloadedRowShellClassName(isSelected)}>
@@ -3950,6 +4587,7 @@ export function HubModelPicker({
{expanderOpen && (
<GgufVariantExpander
repoId={c.repo_id}
+ pipelineTag={c.task ?? null}
loadId={c.load_id}
cachePath={c.cache_path}
onDevice={true}
@@ -4014,6 +4652,7 @@ export function HubModelPicker({
isLora: false,
loadId: c.load_id,
isDownloaded: true,
+ pipelineTag: c.task ?? null,
})
}
vramStatus={null}
@@ -4031,6 +4670,7 @@ export function HubModelPicker({
loadId: c.load_id,
isDownloaded: true,
isGguf: false,
+ pipelineTag: c.task ?? null,
})
}
/>
@@ -4077,6 +4717,51 @@ export function HubModelPicker({
);
};
+ const renderAdditionalOnDeviceModelRow = (model: ModelOption) => {
+ const optionKey = makeModelOptionKey("additional-on-device", model.id);
+ const isSelected = value === model.id;
+ const pipelineTag = typeof task === "string" ? task : (task?.[0] ?? null);
+ // A checkpoint trained here is identified by its directory, not a repo id, so
+ // show the name and drop the Hub link -- the raw path reads as neither.
+ const isLocalPath = /^(?:[a-zA-Z]:[\\/]|[\\/]|~)/.test(model.id);
+ return (
+ <div key={model.id} className={downloadedRowShellClassName(isSelected)}>
+ <div className="min-w-0 flex-1">
+ <ModelRow
+ label={isLocalPath ? model.name : model.id}
+ hubUrl={isLocalPath ? undefined : hubRepoUrl(model.id)}
+ meta={
+ isLocalPath
+ ? (model.description ?? "Trained here")
+ : `${model.isGguf === true ? "GGUF" : "Safetensors"}${model.deviceSize ? ` · ${model.deviceSize}` : ""}`
+ }
+ quantChip={model.deviceQuant}
+ selected={isSelected}
+ loaded={model.deviceLoaded === true}
+ capabilities={detectCapabilities({
+ id: model.id,
+ pipelineTag: pipelineTag ?? undefined,
+ })}
+ alignMeta="device"
+ optionProps={hubModelList.getOptionProps(optionKey, isSelected)}
+ onClick={() =>
+ onSelect(model.id, {
+ source: "hub",
+ isLora: false,
+ isDownloaded: true,
+ isGguf: model.isGguf === true,
+ pipelineTag,
+ })
+ }
+ vramStatus={null}
+ className={downloadedRowButtonClassName}
+ />
+ </div>
+ <span aria-hidden="true" className={cn(ROW_ACTIONS_CLASS, "h-6")} />
+ </div>
+ );
+ };
+
return (
<>
<div className="relative space-y-2">
@@ -4278,7 +4963,8 @@ export function HubModelPicker({
{/* Downloaded (Unsloth) stays visible (filtered) while searching. */}
{showDownloaded &&
(unslothCachedGguf.length > 0 ||
- unslothCachedModelRows.length > 0) ? (
+ unslothCachedModelRows.length > 0 ||
+ unslothAdditionalOnDeviceModels.length > 0) ? (
<>
<ListLabel
divider={pinnedRows.length > 0}
@@ -4364,6 +5050,10 @@ export function HubModelPicker({
unslothCachedGguf.map(renderDownloadedGgufRow)}
{!downloadedCollapsed &&
unslothCachedModelRows.map(renderDownloadedModelRow)}
+ {!downloadedCollapsed &&
+ unslothAdditionalOnDeviceModels.map(
+ renderAdditionalOnDeviceModelRow,
+ )}
</>
) : null}
@@ -4385,6 +5075,10 @@ export function HubModelPicker({
otherCachedGguf.map(renderDownloadedGgufRow)}
{!otherModelsCollapsed &&
otherCachedModelRows.map(renderDownloadedModelRow)}
+ {!otherModelsCollapsed &&
+ otherAdditionalOnDeviceModels.map(
+ renderAdditionalOnDeviceModelRow,
+ )}
</div>
) : null}
@@ -4701,11 +5395,17 @@ export function HubModelPicker({
)}
onClick={() => {
if (isDirectGguf) {
- onSelect(m.id, localDirectGgufMeta());
+ onSelect(
+ m.id,
+ localDirectGgufMeta(m.task),
+ );
} else if (isGguf) {
toggleGgufExpanded(m.id);
} else {
- onSelect(m.id, localModelMeta());
+ onSelect(
+ m.id,
+ localModelMeta(false, m.task),
+ );
}
}}
onArrowDownIntoChildren={
@@ -4730,7 +5430,10 @@ export function HubModelPicker({
m.model_id ?? m.display_name
}`}
onConfigure={() =>
- onConfigure(m.id, localDirectGgufMeta())
+ onConfigure(
+ m.id,
+ localDirectGgufMeta(m.task),
+ )
}
/>
)}
@@ -4740,7 +5443,10 @@ export function HubModelPicker({
m.model_id ?? m.display_name
}`}
onConfigure={() =>
- onConfigure(m.id, localModelMeta())
+ onConfigure(
+ m.id,
+ localModelMeta(false, m.task),
+ )
}
/>
)}
@@ -4768,7 +5474,8 @@ export function HubModelPicker({
: undefined
}
systemRamGb={
- inferenceGpu.systemRamAvailableGb || undefined
+ inferenceGpu.systemRamAvailableGb ||
+ undefined
}
budgetKnown={inferenceGpu.budgetKnown}
/>
@@ -4833,11 +5540,17 @@ export function HubModelPicker({
)}
onClick={() => {
if (isGgufFile) {
- onSelect(m.id, localDirectGgufMeta());
+ onSelect(
+ m.id,
+ localDirectGgufMeta(m.task),
+ );
} else if (isGguf) {
toggleGgufExpanded(m.id);
} else {
- onSelect(m.id, localModelMeta());
+ onSelect(
+ m.id,
+ localModelMeta(false, m.task),
+ );
}
}}
onArrowDownIntoChildren={
@@ -4862,7 +5575,10 @@ export function HubModelPicker({
m.model_id ?? m.display_name
}`}
onConfigure={() =>
- onConfigure(m.id, localDirectGgufMeta())
+ onConfigure(
+ m.id,
+ localDirectGgufMeta(m.task),
+ )
}
/>
)}
@@ -4872,7 +5588,10 @@ export function HubModelPicker({
m.model_id ?? m.display_name
}`}
onConfigure={() =>
- onConfigure(m.id, localModelMeta())
+ onConfigure(
+ m.id,
+ localModelMeta(false, m.task),
+ )
}
/>
)}
@@ -4953,11 +5672,17 @@ export function HubModelPicker({
)}
onClick={() => {
if (isGgufFile) {
- onSelect(m.id, localDirectGgufMeta());
+ onSelect(
+ m.id,
+ localDirectGgufMeta(m.task),
+ );
} else if (isGguf) {
toggleGgufExpanded(m.id);
} else {
- onSelect(m.id, localModelMeta());
+ onSelect(
+ m.id,
+ localModelMeta(false, m.task),
+ );
}
}}
onArrowDownIntoChildren={
@@ -4978,7 +5703,10 @@ export function HubModelPicker({
m.model_id ?? m.display_name
}`}
onConfigure={() =>
- onConfigure(m.id, localDirectGgufMeta())
+ onConfigure(
+ m.id,
+ localDirectGgufMeta(m.task),
+ )
}
/>
)}
@@ -4988,7 +5716,10 @@ export function HubModelPicker({
m.model_id ?? m.display_name
}`}
onConfigure={() =>
- onConfigure(m.id, localModelMeta())
+ onConfigure(
+ m.id,
+ localModelMeta(false, m.task),
+ )
}
/>
)}
@@ -5050,7 +5781,9 @@ export function HubModelPicker({
hubUrl={hubRepoUrl(id)}
alignMeta="hub"
showSize={hubRowsShowSize}
- hideOwner={true}
+ // A community row without its owner reads as an
+ // unsloth upload, and two publishers would collide.
+ hideOwner={isUnslothOwned(id)}
downloaded={downloadedSet.has(id.toLowerCase())}
capabilities={capsById.get(id)}
meta={
@@ -5079,9 +5812,7 @@ export function HubModelPicker({
}}
vramStatus={info?.status ?? null}
vramEst={info?.est}
- gpuGb={
- isG ? expanderGpuGb : expanderSystemGpuGb
- }
+ gpuGb={isG ? expanderGpuGb : expanderSystemGpuGb}
onArrowDownIntoChildren={
expandedGguf === id
? () => focusFirstChildOption(optionKey)
@@ -5091,6 +5822,7 @@ export function HubModelPicker({
{expandedGguf === id && (
<GgufVariantExpander
repoId={id}
+ pipelineTag={pipelineTagById.get(id) ?? null}
onSelect={onSelect}
resolveDownloadFootprint={resolveDownloadFootprint}
onConfigure={onConfigure}
@@ -5124,11 +5856,11 @@ export function HubModelPicker({
);
})
)}
- {recommendedSearch.hasMore && (
+ {recommendedHasMore && (
<>
<div ref={recommendedSentinelRef} className="h-px" />
{/* Only while a page is in flight; on hasMore it sat under a usable list. */}
- {recommendedSearch.isLoadingMore ? (
+ {recommendedIsLoadingMore ? (
<div className="flex items-center justify-center py-2">
<Spinner className="size-3.5 text-muted-foreground" />
</div>
@@ -5196,7 +5928,9 @@ export function HubModelPicker({
isKnownGgufRepo(id) ? undefined : vram?.est
}
gpuGb={
- isKnownGgufRepo(id) ? expanderGpuGb : expanderSystemGpuGb
+ isKnownGgufRepo(id)
+ ? expanderGpuGb
+ : expanderSystemGpuGb
}
onArrowDownIntoChildren={
expandedGguf === id
@@ -5211,6 +5945,7 @@ export function HubModelPicker({
{expandedGguf === id && (
<GgufVariantExpander
repoId={id}
+ pipelineTag={pipelineTagById.get(id) ?? null}
onSelect={onSelect}
resolveDownloadFootprint={resolveDownloadFootprint}
onConfigure={onConfigure}
@@ -5248,14 +5983,16 @@ export function HubModelPicker({
{showHfSection && section === "recommended" ? (
<>
- {hfIds.length === 0 && !isLoading ? (
+ {searchRowIds.length === 0 && !isLoading ? (
filteredRecommendedIds.length === 0 ? (
<div className="px-2.5 py-2 text-xs text-muted-foreground">
- No matching Unsloth models.
+ {communityDiscoveryEnabled
+ ? "No matching models."
+ : "No matching Unsloth models."}
</div>
) : null
) : (
- hfIds.map((id) => {
+ searchRowIds.map((id) => {
const vram = vramMap.get(id);
const isSearchGguf = isKnownGgufRepo(id);
const optionKey = makeModelOptionKey("search-hf", id);
@@ -5305,7 +6042,9 @@ export function HubModelPicker({
}
vramEst={isSearchGguf ? undefined : vram?.est}
gpuGb={
- isSearchGguf ? expanderGpuGb : expanderSystemGpuGb
+ isSearchGguf
+ ? expanderGpuGb
+ : expanderSystemGpuGb
}
onArrowDownIntoChildren={
expandedGguf === id
@@ -5320,6 +6059,7 @@ export function HubModelPicker({
{expandedGguf === id && (
<GgufVariantExpander
repoId={id}
+ pipelineTag={pipelineTagById.get(id) ?? null}
onSelect={onSelect}
resolveDownloadFootprint={resolveDownloadFootprint}
onConfigure={onConfigure}
@@ -5354,7 +6094,7 @@ export function HubModelPicker({
})
)}
<div ref={sentinelRef} className="h-px" />
- {isLoadingMore ? (
+ {searchIsLoadingMore ? (
<div className="flex items-center justify-center py-2">
<Spinner className="size-3.5 text-muted-foreground" />
</div>
@@ -5391,6 +6131,22 @@ export function HubModelPicker({
/** Fine-tuned model rows for the On Device tab's Fine-tuned section. Plugs into
* that section's roving list and shared GGUF-expand state. */
+/** Codec -> the Hub pipeline tag the media routing understands, else undefined.
+ *
+ * A local checkpoint never gets the ASR tag: it would route to the Audio page, which hands
+ * the filesystem path to /audio/stt/load, and the sidecar's resolve_model_id takes only a
+ * curated key or an `owner/model` Hub id, so the row is advertised and then 422s. TTS is
+ * fine, since that loads through the main slot, which does accept a local path. */
+function audioPipelineTagFor(
+ audioType?: string | null,
+ isLocalCheckpoint = false,
+): string | undefined {
+ if (!audioType) return undefined;
+ if (audioType === "whisper")
+ return isLocalCheckpoint ? undefined : "automatic-speech-recognition";
+ return TTS_CODECS.has(audioType) ? "text-to-speech" : undefined;
+}
+
function FineTunedRows({
adapters,
value,
@@ -5436,11 +6192,15 @@ function FineTunedRows({
const isTrainingFull = isTraining && isMerged;
const isLocalGgufDir =
isLocal && (isGgufRepo(adapter.id) || isGgufRepo(adapter.name));
+ // A checkpoint that fine-tunes a TTS/STT model has to reach the Audio page:
+ // chat/completions cannot serve it and reports the adapter as "not downloaded".
+ // The pipeline tag is what onSelect routes on, so carry the detected codec as one.
const selectionMeta: ModelSelectorChangeMeta = {
source: isLocal ? "local" : isExported ? "exported" : "lora",
isLora: !isLocal && !isMerged && !isGguf,
isDownloaded: true,
isGguf: false,
+ pipelineTag: audioPipelineTagFor(adapter.audioType, true),
};
const canConfigure = !(isLocalGgufDir || isExportedGguf);
const optionKey = makeModelOptionKey("lora", adapter.id);
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/row-meta.ts b/studio/frontend/src/features/model-picker/components/model-selector/row-meta.ts
index 9e65dca6dc1..96e4cdeca35 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/row-meta.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/row-meta.ts
@@ -33,10 +33,11 @@ export function splitRepoLabel(label: string): {
return { owner: label.slice(0, slash), name: label.slice(slash + 1) };
}
-/** Our own repos. Rows drop the "unsloth/" prefix, since nearly every model
- * listed is ours; the full repo id stays in the row tooltip. */
+/** Our official Hub owners. Rows drop the owner prefix, since the Unsloth
+ * section already carries it; the full repo id stays in the row tooltip. */
export function isUnslothOwner(owner: string | null | undefined): boolean {
- return owner?.toLowerCase() === "unsloth";
+ const normalized = owner?.toLowerCase();
+ return normalized === "unsloth" || normalized === "unslothai";
}
export type MetaToken =
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/types.ts b/studio/frontend/src/features/model-picker/components/model-selector/types.ts
index 15a827bdf00..18b5bc006ab 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/types.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/types.ts
@@ -10,6 +10,14 @@ export interface ModelOption {
description?: string;
icon?: ReactNode;
isGguf?: boolean;
+ /** Fixed quant used by a specialized on-device runtime. Generic Hub GGUF
+ * rows discover their variants dynamically instead. */
+ deviceQuant?: string;
+ /** Fallback metadata for task-owned caches that an older generic inventory
+ * cannot describe. Current servers normally provide a full cached row. */
+ deviceSize?: string;
+ deviceSizeBytes?: number;
+ deviceLoaded?: boolean;
}
export interface LoraModelOption extends ModelOption {
@@ -17,6 +25,8 @@ export interface LoraModelOption extends ModelOption {
updatedAt?: number;
source?: "training" | "exported" | "local";
exportType?: "lora" | "merged" | "gguf";
+ /** Codec when the checkpoint fine-tunes an audio model, else null. */
+ audioType?: string | null;
}
export interface ExternalModelOption extends ModelOption {
@@ -47,6 +57,9 @@ export interface ModelSelectorChangeMeta {
loadId?: string | null;
/** Native path token so an active-model reload can reopen a file-picked GGUF. */
nativePathToken?: string;
+ /** Hub pipeline tag for an uncurated pick, so a task page can tell which task
+ * the repo does when it is not in the page's catalog. */
+ pipelineTag?: string | null;
nativePathExpiresAtMs?: number | null;
}
diff --git a/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts b/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts
index 96c9556d243..663d6528999 100644
--- a/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts
+++ b/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts
@@ -15,6 +15,7 @@ import {
useHubInventory,
} from "@/features/hub";
import { useMemo } from "react";
+import { allowedHiddenModelIdMatches } from "../components/model-selector/audio-picker-policy";
const PICKER_LOCAL_SOURCES: ReadonlySet<LocalSource> = new Set([
"lmstudio",
@@ -49,6 +50,8 @@ function toCachedModelRepo(row: CachedInventoryRow): CachedModelRepo {
size_bytes: row.bytes,
last_modified: row.lastModified ?? undefined,
task: row.task ?? null,
+ tags: row.tags,
+ library_name: row.libraryName,
// Carried through: the diffusion picker drops single-file checkpoint repos (loading one as a pipeline fails after the handoff), and undefined reads as "full pipeline".
single_file: row.singleFile ?? false,
};
@@ -77,7 +80,11 @@ export interface ChatPickerInventory {
}
export function useChatPickerInventory(
- options: { enabled?: boolean } = {},
+ options: {
+ enabled?: boolean;
+ /** Exact task-page artifacts that may bypass chat's hidden-model list. */
+ allowedHiddenModelIds?: ReadonlySet<string>;
+ } = {},
): ChatPickerInventory {
const inventory = useHubInventory({
kind: "models",
@@ -92,10 +99,14 @@ export function useChatPickerInventory(
(row) =>
row.modelFormat === "gguf" &&
isCompleteCachedRow(row) &&
- !isHiddenModelId(row.repoId),
+ (!isHiddenModelId(row.repoId) ||
+ allowedHiddenModelIdMatches(
+ options.allowedHiddenModelIds,
+ row.repoId,
+ )),
)
.map(toCachedGgufRepo),
- [inventory.cachedRows],
+ [inventory.cachedRows, options.allowedHiddenModelIds],
);
const cachedModels = useMemo(
() =>
@@ -108,10 +119,14 @@ export function useChatPickerInventory(
// task, and a task of null is what every unclassified CHAT repo carries, so without
// this it lands in the chat On Device list as a load that cannot succeed.
!row.companion &&
- !isHiddenModelId(row.repoId),
+ (!isHiddenModelId(row.repoId) ||
+ allowedHiddenModelIdMatches(
+ options.allowedHiddenModelIds,
+ row.repoId,
+ )),
)
.map(toCachedModelRepo),
- [inventory.cachedRows],
+ [inventory.cachedRows, options.allowedHiddenModelIds],
);
const localModels = useMemo(
() =>
@@ -122,11 +137,17 @@ export function useChatPickerInventory(
// Skip non-chat rows (a folder with only config.json classifies "unknown" -> canChat false); selecting one would load a weightless path.
// toLocalModelInfo drops capabilities, so this is the only place the guard can live. A row the backend classified as a generation task is
// exempt: canChat is about the chat loader, and dropping it here hid every on-device diffusion model from the pickers that CAN load it.
- (row.capabilities.canChat || studioPageForTask(row.task) !== undefined) &&
- !isHiddenModelId(row.modelId, row.repoId, row.path),
+ (row.capabilities.canChat ||
+ studioPageForTask(row.task) !== undefined) &&
+ (!isHiddenModelId(row.modelId, row.repoId, row.path) ||
+ allowedHiddenModelIdMatches(
+ options.allowedHiddenModelIds,
+ row.modelId,
+ row.repoId,
+ )),
)
.map(toLocalModelInfo),
- [inventory.localRows],
+ [inventory.localRows, options.allowedHiddenModelIds],
);
return {
diff --git a/studio/frontend/src/features/settings/components/sidebar-nav-customizer.tsx b/studio/frontend/src/features/settings/components/sidebar-nav-customizer.tsx
index b769be20cfa..19f26805b10 100644
--- a/studio/frontend/src/features/settings/components/sidebar-nav-customizer.tsx
+++ b/studio/frontend/src/features/settings/components/sidebar-nav-customizer.tsx
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import {
+ AudioWave01Icon,
ChefHatIcon,
DashboardCircleIcon,
DownloadSquare01Icon,
@@ -32,6 +33,7 @@ const ITEM_META: Record<
images: { icon: Image03Icon, labelKey: "shell.navigation.images" },
train: { icon: TestTubeOutlineIcon, labelKey: "shell.navigation.train" },
video: { icon: FlimSlateIcon, labelKey: "shell.navigation.video" },
+ audio: { icon: AudioWave01Icon, labelKey: "shell.navigation.audio" },
recipes: { icon: ChefHatIcon, labelKey: "shell.navigation.recipes" },
export: { icon: DownloadSquare01Icon, labelKey: "shell.navigation.export" },
api: { icon: Globe02Icon, labelKey: "shell.navigation.api" },
diff --git a/studio/frontend/src/features/settings/lib/stt-download-mirror.ts b/studio/frontend/src/features/settings/lib/stt-download-mirror.ts
index bf090708ec9..41d5750c5e5 100644
--- a/studio/frontend/src/features/settings/lib/stt-download-mirror.ts
+++ b/studio/frontend/src/features/settings/lib/stt-download-mirror.ts
@@ -2,9 +2,11 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import {
+ type SttEngine,
cancelSttDownload,
fetchSttStatus,
loadSttModel,
+ sttEngineFor,
sttEngineStatusFor,
} from "@/features/chat";
import {
@@ -34,14 +36,24 @@ const POLL_MS = 750;
const START_GRACE_MS = 8_000;
const trackers = new SttDownloadTrackers();
+const warmSelectedVoiceModelOnComplete = new Map<string, boolean>();
-function jobKey(model: SttModel): string {
- return `stt:${model}`;
+function trackerKey(model: SttModel, engine?: SttEngine): string {
+ return engine && engine !== "transformers" ? `${engine}:${model}` : model;
}
-async function loadAndAnnounce(model: SttModel): Promise<void> {
+function jobKey(model: SttModel, engine?: SttEngine): string {
+ return engine && engine !== "transformers"
+ ? `stt:${engine}:${model}`
+ : `stt:${model}`;
+}
+
+async function loadAndAnnounce(
+ model: SttModel,
+ engine?: SttEngine,
+): Promise<void> {
try {
- await loadSttModel(model);
+ await loadSttModel(model, engine);
toast.success(
translate("settings.voice.dictation.sttModelReady", {
model: sttModelName(model),
@@ -58,53 +70,67 @@ function settle(
model: SttModel,
outcome: "complete" | "cancelled" | "error",
error?: string | null,
+ engine?: SttEngine,
): void {
- finishExternalJob(jobKey(model), outcome, error);
- trackers.stop(model);
+ const key = trackerKey(model, engine);
+ finishExternalJob(jobKey(model, engine), outcome, error);
+ trackers.stop(key);
+ const shouldWarmVoiceModel =
+ warmSelectedVoiceModelOnComplete.get(key) ?? true;
+ warmSelectedVoiceModelOnComplete.delete(key);
// Only warm what the user is still pointed at. Selecting another model, or
// leaving local dictation, during the download means this one is not wanted
// and loading it would undo the unload that switch performed.
const { sttModel, dictationEngine } = useVoiceSettingsStore.getState();
if (
+ shouldWarmVoiceModel &&
outcome === "complete" &&
dictationEngine === "model" &&
sttModel === model
) {
- void loadAndAnnounce(model);
+ void loadAndAnnounce(model, engine);
}
}
-async function poll(model: SttModel, startedAt: number): Promise<void> {
+async function poll(
+ model: SttModel,
+ startedAt: number,
+ engine?: SttEngine,
+): Promise<void> {
let status: Awaited<ReturnType<typeof fetchSttStatus>>;
try {
- status = await fetchSttStatus(undefined, model);
+ status = await fetchSttStatus(
+ undefined,
+ engine === undefined || engine === "transformers" ? model : undefined,
+ );
} catch {
// A dropped poll is not a failed download; the next one decides.
return;
}
- if (!trackers.has(model)) return;
+ const key = trackerKey(model, engine);
+ if (!trackers.has(key)) return;
- const engine = sttEngineStatusFor(status, model);
- const download = engine?.download;
+ const engineStatus = sttEngineStatusFor(status, model, engine);
+ const download = engineStatus?.download;
if (download?.downloading && download.model === model) {
- updateExternalJob(jobKey(model), {
+ updateExternalJob(jobKey(model, engine), {
downloadedBytes: download.bytes_done ?? 0,
expectedBytes: download.bytes_total ?? 0,
});
return;
}
- if (engine?.downloaded_models.includes(model)) {
- settle(model, "complete");
+ if (engineStatus?.downloaded_models.includes(model)) {
+ settle(model, "complete", undefined, engine);
return;
}
if (download?.cancelled) {
- settle(model, "cancelled");
+ settle(model, "cancelled", undefined, engine);
return;
}
if (download?.error) {
- settle(model, "error", download.error);
+ settle(model, "error", download.error, engine);
return;
}
if (Date.now() - startedAt > START_GRACE_MS) {
@@ -112,29 +138,53 @@ async function poll(model: SttModel, startedAt: number): Promise<void> {
model,
"error",
translate("settings.voice.dictation.sttDownloadFailed"),
+ engine,
);
}
}
/** Whether a download is already mirrored, so a poller can adopt one that
* started before this page load without duplicating the row. */
-export function isTrackingSttDownload(model: SttModel): boolean {
- return trackers.has(model);
+export function isTrackingSttDownload(
+ model: SttModel,
+ engine?: SttEngine,
+): boolean {
+ return trackers.has(trackerKey(model, engine ?? sttEngineFor(model)));
}
/**
* Mirror an already-started download of `model` into the panel. Any other
* model's download keeps its own row: switching models does not stop it.
*/
-export function trackSttDownload(model: SttModel): void {
+export function trackSttDownload(
+ model: SttModel,
+ options: {
+ warmSelectedVoiceModelOnComplete?: boolean;
+ engine?: SttEngine;
+ repoId?: string;
+ } = {},
+): void {
+ const resolvedEngine = options.engine ?? sttEngineFor(model);
+ const key = trackerKey(model, resolvedEngine);
+ // Starting/adopting the same transfer from another surface must not reset
+ // its visible progress or replace its poller/completion policy.
+ if (trackers.has(key)) {
+ if (options.warmSelectedVoiceModelOnComplete !== false)
+ warmSelectedVoiceModelOnComplete.set(key, true);
+ return;
+ }
+ warmSelectedVoiceModelOnComplete.set(
+ key,
+ options.warmSelectedVoiceModelOnComplete ?? true,
+ );
startExternalJob({
- key: jobKey(model),
- repoId: getSttModelRepo(model),
+ key: jobKey(model, resolvedEngine),
+ repoId: options.repoId ?? getSttModelRepo(model),
variant: sttModelName(model),
expectedBytes: 0,
cancel: async () => {
try {
- await cancelSttDownload(model);
+ await cancelSttDownload(model, resolvedEngine);
} catch (error) {
toast.error(
translate("settings.voice.dictation.sttCancelDownloadFailed"),
@@ -148,8 +198,8 @@ export function trackSttDownload(model: SttModel): void {
});
const startedAt = Date.now();
const timer = window.setInterval(() => {
- void poll(model, startedAt);
+ void poll(model, startedAt, resolvedEngine);
}, POLL_MS);
- trackers.start(model, () => window.clearInterval(timer));
- void poll(model, startedAt);
+ trackers.start(key, () => window.clearInterval(timer));
+ void poll(model, startedAt, resolvedEngine);
}
diff --git a/studio/frontend/src/features/settings/stores/appearance-custom-store.ts b/studio/frontend/src/features/settings/stores/appearance-custom-store.ts
index 80977cf4378..0aa52a956c2 100644
--- a/studio/frontend/src/features/settings/stores/appearance-custom-store.ts
+++ b/studio/frontend/src/features/settings/stores/appearance-custom-store.ts
@@ -92,8 +92,9 @@ export const SIDEBAR_NAV_ITEM_IDS = [
"hub",
"projects",
"images",
- // Video sits directly under Images: the two media tabs read as one pair.
+ // Video and Audio sit directly under Images: the media tabs read as one group.
"video",
+ "audio",
"train",
"recipes",
"export",
@@ -115,6 +116,7 @@ export const SIDEBAR_NAV_DEFAULT_PINNED: Record<SidebarNavItemId, boolean> = {
images: true,
// Under "More" until a user pins it.
video: false,
+ audio: false,
train: true,
recipes: false,
export: false,
@@ -123,7 +125,7 @@ export const SIDEBAR_NAV_DEFAULT_PINNED: Record<SidebarNavItemId, boolean> = {
/** Every previously shipped layout, so a migration can tell an untouched install from one the
* user arranged themselves. v3 pinned Video under Images; v4 moved Model hub above Projects;
- * v5 put Video back under "More". */
+ * v5 put Video back under "More" and later added API before Audio shipped. */
const SHIPPED_SIDEBAR_NAV_DEFAULTS: SidebarNavItemPref[][] = [
[
{ id: "projects", pinned: true },
@@ -152,6 +154,16 @@ const SHIPPED_SIDEBAR_NAV_DEFAULTS: SidebarNavItemPref[][] = [
{ id: "recipes", pinned: false },
{ id: "export", pinned: false },
],
+ [
+ { id: "hub", pinned: true },
+ { id: "projects", pinned: true },
+ { id: "images", pinned: true },
+ { id: "video", pinned: false },
+ { id: "train", pinned: true },
+ { id: "recipes", pinned: false },
+ { id: "export", pinned: false },
+ { id: "api", pinned: false },
+ ],
];
export const MAX_IMPORTED_FONTS = 3;
@@ -475,14 +487,14 @@ export const useAppearanceCustomStore = create<AppearanceCustomState>()(
}),
{
name: "unsloth_appearance_customization",
- version: 5,
+ version: 6,
storage: createJSONStorage(() => guardedLocalStorage),
migrate: (persisted, version) => {
const state = (persisted ?? {}) as Partial<AppearanceCustomState>;
const customization = migrateShippedSidebarNavDefault(
sanitizeCustomization(state.customization),
version,
- 5,
+ 6,
);
return { customization } as AppearanceCustomState;
},
diff --git a/studio/frontend/src/features/training/api/models-api.ts b/studio/frontend/src/features/training/api/models-api.ts
index d85acbe9490..c764bd780cf 100644
--- a/studio/frontend/src/features/training/api/models-api.ts
+++ b/studio/frontend/src/features/training/api/models-api.ts
@@ -73,6 +73,9 @@ export interface ModelConfigResponse {
is_vision: boolean;
is_embedding?: boolean;
is_audio: boolean;
+ // False when the repo's tokenizer_config.json was unreadable (gated, offline,
+ // upstream error), so is_audio false means unknown rather than "not audio".
+ audio_type_known?: boolean;
is_lora: boolean;
base_model?: string | null;
model_type?: "text" | "vision" | "audio" | "embeddings" | null;
diff --git a/studio/frontend/src/features/training/lib/validation.ts b/studio/frontend/src/features/training/lib/validation.ts
index 4f1017515b2..ec2e2951e6a 100644
--- a/studio/frontend/src/features/training/lib/validation.ts
+++ b/studio/frontend/src/features/training/lib/validation.ts
@@ -51,7 +51,13 @@ export function hasIncompatibleTrainingModalities(
): boolean {
return (
(!config.isVisionModel && config.isDatasetImage === true) ||
- (!config.isAudioModel && config.isDatasetAudio === true)
+ // audioCapabilityUnknown means the repo's tokenizer_config.json was unreadable
+ // (gated, offline, upstream error), not that the model lacks audio. Blocking there
+ // reports a token problem as a capability one; let the run start and fail on the
+ // real download error, which is what a gated text model already does.
+ (!config.audioCapabilityUnknown &&
+ !config.isAudioModel &&
+ config.isDatasetAudio === true)
);
}
diff --git a/studio/frontend/src/features/training/stores/training-config-policy.ts b/studio/frontend/src/features/training/stores/training-config-policy.ts
index b07b8d1c543..12304d7e60d 100644
--- a/studio/frontend/src/features/training/stores/training-config-policy.ts
+++ b/studio/frontend/src/features/training/stores/training-config-policy.ts
@@ -96,6 +96,7 @@ export const initialTrainingConfigState: TrainingConfigState = {
isVisionModel: false,
isEmbeddingModel: false,
isAudioModel: false,
+ audioCapabilityUnknown: false,
isLoadingModelDefaults: false,
modelDefaultsError: null,
modelDefaultsAppliedFor: null,
diff --git a/studio/frontend/src/features/training/stores/training-config-store.ts b/studio/frontend/src/features/training/stores/training-config-store.ts
index 359b817ff17..84b1f3a68f0 100644
--- a/studio/frontend/src/features/training/stores/training-config-store.ts
+++ b/studio/frontend/src/features/training/stores/training-config-store.ts
@@ -221,6 +221,7 @@ export const useTrainingConfigStore = create<TrainingConfigStore>()(
isVisionModel: false,
isEmbeddingModel: false,
isAudioModel: false,
+ audioCapabilityUnknown: false,
isLoadingModelDefaults: false,
isCheckingVision: false,
modelDefaultsError: null,
@@ -335,6 +336,7 @@ export const useTrainingConfigStore = create<TrainingConfigStore>()(
isVisionModel: modelDetails.is_vision,
isEmbeddingModel: isEmbedding,
isAudioModel: isAudio,
+ audioCapabilityUnknown: modelDetails.audio_type_known === false,
isLoadingModelDefaults: autoSelectionPromise !== null,
isCheckingVision: false,
modelDefaultsError: null,
@@ -751,6 +753,7 @@ export const useTrainingConfigStore = create<TrainingConfigStore>()(
approvedRemoteCodeFingerprint?: string | null;
isVisionModel?: boolean;
isAudioModel?: boolean;
+ audioCapabilityUnknown?: boolean;
isEmbeddingModel?: boolean;
modelDefaultsAppliedFor?: string | null;
advancedSettingsBaseline?: null;
@@ -773,6 +776,7 @@ export const useTrainingConfigStore = create<TrainingConfigStore>()(
patch.approvedRemoteCodeFingerprint = null;
patch.isVisionModel =
options?.isVision ?? effectiveModelType === "vision";
+ patch.audioCapabilityUnknown = false;
patch.isAudioModel =
options?.isAudio ?? effectiveModelType === "audio";
patch.isEmbeddingModel =
@@ -791,6 +795,7 @@ export const useTrainingConfigStore = create<TrainingConfigStore>()(
isVisionModel: false,
isEmbeddingModel: false,
isAudioModel: false,
+ audioCapabilityUnknown: false,
isDatasetAudio: false,
isLoadingModelDefaults: false,
modelDefaultsError: null,
@@ -829,6 +834,7 @@ export const useTrainingConfigStore = create<TrainingConfigStore>()(
isVisionModel: false,
isEmbeddingModel: false,
isAudioModel: false,
+ audioCapabilityUnknown: false,
isDatasetAudio: false,
isLoadingModelDefaults: false,
modelDefaultsError: null,
diff --git a/studio/frontend/src/features/training/types/config.ts b/studio/frontend/src/features/training/types/config.ts
index f0cbf3dbc5a..9c9292045e3 100644
--- a/studio/frontend/src/features/training/types/config.ts
+++ b/studio/frontend/src/features/training/types/config.ts
@@ -116,6 +116,7 @@ export interface TrainingConfigState {
isVisionModel: boolean;
isEmbeddingModel: boolean;
isAudioModel: boolean;
+ audioCapabilityUnknown: boolean;
isLoadingModelDefaults: boolean;
modelDefaultsError: string | null;
modelDefaultsAppliedFor: string | null;
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 0760a6f316c..ab671afa667 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -83,6 +83,7 @@ export const ar = {
recipes: "الوصفات",
images: "الصور",
video: "الفيديو",
+ audio: "الصوت",
trainChecking: "جارٍ التحقق من دعم هذا الجهاز للتدريب...",
videoChecking: "جارٍ التحقق من دعم هذا الجهاز للفيديو...",
more: "المزيد",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index cbd7b54756d..0ab0eaecede 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -86,6 +86,7 @@ export const de = {
recipes: "Rezepte",
images: "Bilder",
video: "Video",
+ audio: "Audio",
trainChecking: "Dieser Rechner wird auf Trainingsunterstützung geprüft...",
videoChecking: "Dieser Rechner wird auf Video-Unterstützung geprüft...",
more: "Mehr",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 9c79bd8861a..542042e3bbf 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -78,6 +78,7 @@ export const en = {
recipes: "Recipes",
images: "Images",
video: "Video",
+ audio: "Audio",
// Hover text while the row spins, before this machine's capability is measured.
trainChecking: "Checking this machine for training support...",
videoChecking: "Checking this machine for video support...",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 7da367d09ab..1f32a3e3270 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -85,6 +85,7 @@ export const es = {
recipes: "Recetas",
images: "Imágenes",
video: "Vídeo",
+ audio: "Audio",
trainChecking: "Comprobando si este equipo admite entrenamiento...",
videoChecking: "Comprobando si este equipo admite vídeo...",
more: "Más",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index b85b0a13bb6..1bd751b3356 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -86,6 +86,7 @@ export const fr = {
recipes: "Recettes",
images: "Images",
video: "Vidéo",
+ audio: "Audio",
trainChecking: "Vérification de la prise en charge de l'entraînement sur cette machine...",
videoChecking: "Vérification de la prise en charge de la vidéo sur cette machine...",
more: "Plus",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 2fe220669c3..ecbb898c30c 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -86,6 +86,7 @@ export const hi = {
recipes: "रेसिपी",
images: "इमेज",
video: "वीडियो",
+ audio: "ऑडियो",
trainChecking: "इस मशीन पर ट्रेनिंग सपोर्ट की जाँच हो रही है...",
videoChecking: "इस मशीन पर वीडियो सपोर्ट की जाँच हो रही है...",
more: "अधिक",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index c2271eed04d..ee15375ed1c 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -52,6 +52,7 @@ export const it = {
recipes: "Ricette",
images: "Immagini",
video: "Video",
+ audio: "Audio",
trainChecking: "Verifica del supporto all'addestramento su questa macchina...",
videoChecking: "Verifica del supporto video su questa macchina...",
more: "Altro",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 18bbb04b024..3ed7fc790e1 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -85,6 +85,7 @@ export const ja = {
recipes: "レシピ",
images: "画像",
video: "動画",
+ audio: "音声",
trainChecking: "このマシンのトレーニング対応を確認しています...",
videoChecking: "このマシンの動画生成対応を確認しています...",
more: "その他",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 148179e0bda..36394c6dc28 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -83,6 +83,7 @@ export const ko = {
recipes: "레시피",
images: "이미지",
video: "동영상",
+ audio: "오디오",
trainChecking: "이 컴퓨터의 학습 지원 여부를 확인하는 중...",
videoChecking: "이 컴퓨터의 비디오 지원 여부를 확인하는 중...",
more: "더 보기",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index ee8da9090a2..b17607ff74d 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -85,6 +85,7 @@ export const ptBR = {
recipes: "Receitas",
images: "Imagens",
video: "Vídeo",
+ audio: "Áudio",
trainChecking: "Verificando se esta máquina oferece suporte a treino...",
videoChecking: "Verificando se esta máquina oferece suporte a vídeo...",
more: "Mais",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 88b2d233b0f..48f6089e5ab 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -85,6 +85,7 @@ export const ru = {
recipes: "Рецепты",
images: "Изображения",
video: "Видео",
+ audio: "Аудио",
trainChecking: "Проверка поддержки обучения на этой машине...",
videoChecking: "Проверка поддержки видео на этой машине...",
more: "Ещё",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index d1ad1436cdd..4e4091e60d0 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -81,6 +81,7 @@ export const zhCN = {
recipes: "配方",
images: "图像",
video: "视频",
+ audio: "音频",
trainChecking: "正在检查此设备是否支持训练...",
videoChecking: "正在检查此设备是否支持视频生成...",
more: "更多",
diff --git a/studio/frontend/src/lib/model-lifecycle-events.ts b/studio/frontend/src/lib/model-lifecycle-events.ts
index a1a9588eb2c..2b41d1b3847 100644
--- a/studio/frontend/src/lib/model-lifecycle-events.ts
+++ b/studio/frontend/src/lib/model-lifecycle-events.ts
@@ -211,4 +211,3 @@ async function boundedRead(
clearTimeout(timer);
}
}
-
diff --git a/studio/frontend/tests/audio-catalog-decodable.test.ts b/studio/frontend/tests/audio-catalog-decodable.test.ts
new file mode 100644
index 00000000000..88f5309119a
--- /dev/null
+++ b/studio/frontend/tests/audio-catalog-decodable.test.ts
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Every model the Generate picker offers must be one the backend can actually decode.
+// Llasa was offered and could not be: it speaks XCodec2 (65,536 <|s_N|> tokens), which is
+// in neither _AUDIO_TOKEN_PATTERNS nor AudioCodecManager, so selecting it loaded the model
+// and then failed with "not a supported TTS model". Probed live against a running Studio,
+// unsloth/Llasa-1B reports is_audio=false while every other curated TTS row reports its
+// codec, which is the same shape as the Orpheus defect this PR was opened to fix.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+const catalog = readFileSync(
+ new URL(
+ "../src/features/model-picker/components/model-selector/model-catalog.ts",
+ import.meta.url,
+ ),
+ "utf8",
+);
+const policy = readFileSync(
+ new URL(
+ "../src/features/model-picker/components/model-selector/audio-picker-policy.ts",
+ import.meta.url,
+ ),
+ "utf8",
+);
+
+// The four the main-slot TTS backend decodes: snac, csm, bicodec, dac.
+const DECODABLE = ["orpheus", "csm", "spark", "outetts"];
+
+test("the curated audio catalog offers no model the backend cannot decode", () => {
+ const audio = catalog.slice(catalog.indexOf("export const AUDIO_CATALOG"));
+ const body = audio.slice(0, audio.indexOf("\n];"));
+ assert.doesNotMatch(body, /canonicalId: "[^"]*Llasa[^"]*"/i);
+ // The rows that remain are still there, so this cannot pass by emptying the catalog.
+ for (const family of ["orpheus", "csm-1b", "Spark-TTS", "OuteTTS", "whisper"]) {
+ assert.match(body, new RegExp(family, "i"), family);
+ }
+});
+
+test("the community TTS family list matches what can be decoded", () => {
+ const match = policy.match(/\/\(\?:\^\|\[-_\.\/\]\)\(([^)]+)\)/);
+ assert.ok(match, "could not find the family regex");
+ const families = match[1].split("|");
+ assert.ok(!families.some((f) => /llasa/i.test(f)), families.join("|"));
+ for (const decodable of DECODABLE) {
+ assert.ok(
+ families.some((f) => f.replace(/[-?]/g, "").includes(decodable.replace(/[-?]/g, ""))),
+ `${decodable} missing from ${families.join("|")}`,
+ );
+ }
+});
diff --git a/studio/frontend/tests/audio-community-pick-routing.test.ts b/studio/frontend/tests/audio-community-pick-routing.test.ts
new file mode 100644
index 00000000000..314a92d148a
--- /dev/null
+++ b/studio/frontend/tests/audio-community-pick-routing.test.ts
@@ -0,0 +1,50 @@
+// 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 {
+ AUDIO_CATALOG,
+ groupForRepoId,
+} from "../src/features/model-picker/components/model-selector/model-catalog.ts";
+import { resolveAudioPickTask } from "../src/features/audio/audio-page-policy.ts";
+
+type Task = "tts" | "stt" | null;
+
+const routeFor = (repoId: string, pipelineTag?: string | null): Task =>
+ resolveAudioPickTask(
+ (groupForRepoId(repoId, AUDIO_CATALOG)?.task as Task) ?? null,
+ pipelineTag,
+ );
+
+test("an uncurated ASR repo routes to the STT sidecar, not the TTS slot", () => {
+ assert.equal(
+ routeFor("openai/whisper-large-v3", "automatic-speech-recognition"),
+ "stt",
+ );
+ assert.equal(
+ routeFor("nvidia/parakeet-tdt", "automatic-speech-recognition"),
+ "stt",
+ );
+});
+
+test("an uncurated TTS repo still takes the main slot", () => {
+ assert.equal(routeFor("hexgrad/Kokoro-82M", "text-to-speech"), null);
+ assert.equal(routeFor("someone/mystery-model", null), null);
+});
+
+test("the catalog still wins over the tag", () => {
+ assert.equal(routeFor("unsloth/whisper-small", null), "stt");
+ assert.equal(routeFor("unslothai/Qwen3-ASR-0.6B-GGUF", null), "stt");
+ assert.equal(routeFor("unsloth/orpheus-3b-0.1-ft", null), "tts");
+});
+
+const curatedArtifactGate = (repoId: string, isGguf: boolean) =>
+ isGguf || Boolean(groupForRepoId(repoId, AUDIO_CATALOG));
+
+test("the curated-artifact gate would hide community safetensors", () => {
+ assert.equal(curatedArtifactGate("hexgrad/Kokoro-82M", false), false);
+ assert.equal(curatedArtifactGate("openai/whisper-large-v3", false), false);
+ assert.equal(curatedArtifactGate("some/community-GGUF", true), true);
+});
diff --git a/studio/frontend/tests/audio-generation-stop.test.ts b/studio/frontend/tests/audio-generation-stop.test.ts
new file mode 100644
index 00000000000..dc592546677
--- /dev/null
+++ b/studio/frontend/tests/audio-generation-stop.test.ts
@@ -0,0 +1,100 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+const source = readFileSync(
+ new URL("../src/features/audio/audio-page.tsx", import.meta.url),
+ "utf8",
+);
+
+test("generation exposes a clickable Stop action wired to the request abort", () => {
+ assert.match(
+ source,
+ /const handleStopGeneration[\s\S]*generateAbort\.current\?\.abort\(\)/,
+ );
+ assert.match(
+ source,
+ /onClick=\{\s*busy === "generating"\s*\?\s*handleStopGeneration\s*:\s*handleGenerate\s*\}/,
+ );
+ assert.match(
+ source,
+ /busy === "generating"[\s\S]*icon=\{StopIcon\}[\s\S]*Stop/,
+ );
+});
+
+test("leaving the audio page does NOT abort an in-flight generation", () => {
+ // RootLayout keeps this page mounted precisely so synthesis survives a tab
+ // switch (see the note in routes/audio.tsx), the clip is persisted server-side
+ // so it is waiting in the gallery on return, and neither Images nor Video
+ // cancels on deactivation either. Only unmount aborts.
+ assert.doesNotMatch(
+ source,
+ /if \(!active\) generateAbort\.current\?\.abort\(\)/,
+ );
+ assert.match(
+ source,
+ /useEffect\(\(\) => \(\) => generateAbort\.current\?\.abort\(\), \[\]\)/,
+ );
+});
+
+test("leaving the audio page aborts an in-flight transcription", () => {
+ assert.match(
+ source,
+ /const transcriptionAbort = useRef<AbortController \| null>\(null\)/,
+ );
+ assert.match(
+ source,
+ /transcribeAudioBlob\(blob, \{[\s\S]*signal: controller\.signal/,
+ );
+ assert.match(
+ source,
+ /if \(!active\) \{[\s\S]*transcriptionAbort\.current\?\.abort\(\)/,
+ );
+ assert.match(
+ source,
+ /if \(controller\.signal\.aborted \|\| !activeRef\.current\) return/,
+ );
+});
+
+test("a non-abort generation failure refreshes authoritative residency", () => {
+ assert.match(
+ source,
+ /catch \(error\) \{[\s\S]*if \(!controller\.signal\.aborted\)[\s\S]*await refreshStatus\(\)/,
+ );
+ assert.match(
+ source,
+ /const refreshStatus[\s\S]*catch \{[\s\S]*setStatus\(null\)/,
+ );
+});
+
+test("a saved clip the refresh missed keeps its response audio mounted", () => {
+ // selectClip nulls the fallback by default, which undid the setFallbackClip immediately
+ // before it and left selectedId pointing at a clip that is not in `clips` yet, so the
+ // player rendered the empty state.
+ assert.match(
+ source,
+ /const selectClip = useCallback\(\(id: string, keepFallback = false\) => \{[\s\S]*if \(!keepFallback\) setFallbackClip\(null\);/,
+ );
+ assert.match(source, /saved: true,\s*\}\);\s*selectClip\(generated\.clip_id, true\);/);
+});
+
+test("deleting a clip drops the row without waiting on the refresh", () => {
+ // refreshGallery swallows a failed GET and returns the cache without setClips, which left
+ // the deleted row on screen against an already-revoked object URL.
+ assert.match(
+ source,
+ /await deleteAudioClip\(id\);[\s\S]*galleryCache\.clips = galleryCache\.clips\.filter\([\s\S]*setClips\(galleryCache\.clips\);/,
+ );
+});
+
+test("the response fallback is dropped once its gallery record arrives", () => {
+ // Kept past that point, deleting the now-visible clip made the fallback reappear from a
+ // stale data URL, labelled as saved, as though the delete had not happened.
+ assert.match(
+ source,
+ /fallbackClipRef\.current &&\s*galleryCache\.selectedId &&\s*merged\.some\(\(c\) => c\.id === galleryCache\.selectedId\)\s*\)\s*\{\s*setFallbackClip\(null\);/,
+ );
+});
diff --git a/studio/frontend/tests/audio-hidden-stt-seed.test.ts b/studio/frontend/tests/audio-hidden-stt-seed.test.ts
new file mode 100644
index 00000000000..3ae76083cfd
--- /dev/null
+++ b/studio/frontend/tests/audio-hidden-stt-seed.test.ts
@@ -0,0 +1,62 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+import {
+ allowedHiddenModelIdMatches,
+ taskPickerRowMatches,
+} from "../src/features/model-picker/components/model-selector/audio-picker-policy.ts";
+
+const pickerSource = readFileSync(
+ new URL(
+ "../src/features/model-picker/components/model-selector/pickers.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+);
+
+const row = {
+ isHidden: true,
+ format: "all" as const,
+ matchesFormat: false,
+ matchesTask: false,
+ isRecommendable: false,
+};
+
+test("a hidden chat-sidecar repo remains visible when explicitly curated by its task page", () => {
+ assert.equal(taskPickerRowMatches({ ...row, isCatalogSeed: true }), true);
+});
+
+test("the same hidden repo remains suppressed outside a curated task contract", () => {
+ assert.equal(taskPickerRowMatches({ ...row, isCatalogSeed: false }), false);
+});
+
+test("curated hidden task ids survive the query-mode recommended filter", () => {
+ assert.match(
+ pickerSource,
+ /const recommendedIds = useMemo[\s\S]*allowedHiddenModelIdMatches\(taskCatalogSeedIds, id\)/,
+ );
+});
+
+test("an allowed hidden Audio id survives local source matching without allowing siblings", () => {
+ const allowed = new Set(["unsloth/whisper-tiny"]);
+ assert.equal(
+ allowedHiddenModelIdMatches(
+ allowed,
+ "unsloth/whisper-tiny",
+ "E:/models/whisper-tiny",
+ ),
+ true,
+ );
+ assert.equal(
+ allowedHiddenModelIdMatches(
+ allowed,
+ "unsloth/whisper-base",
+ "E:/models/whisper-tiny",
+ ),
+ false,
+ );
+});
diff --git a/studio/frontend/tests/audio-mode-task-filter.test.ts b/studio/frontend/tests/audio-mode-task-filter.test.ts
new file mode 100644
index 00000000000..0a20cb8a206
--- /dev/null
+++ b/studio/frontend/tests/audio-mode-task-filter.test.ts
@@ -0,0 +1,59 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import {
+ sttEngineForRepoId,
+ sttRepoIdForSidecarKey,
+ sttSidecarKeyFor,
+} from "../src/features/audio/stt-artifacts.ts";
+import { detectCapabilities } from "../src/features/model-picker/components/model-selector/model-capabilities.ts";
+
+const pageSource = readFileSync(
+ new URL("../src/features/audio/audio-page.tsx", import.meta.url),
+ "utf8",
+);
+const catalogSource = readFileSync(
+ new URL("../src/features/audio/catalog.ts", import.meta.url),
+ "utf8",
+);
+
+test("Hub discovery follows the active audio mode", () => {
+ assert.match(
+ pageSource,
+ /speak: \["text-to-speech"\],[\s\S]*transcribe: \["automatic-speech-recognition"\]/,
+ );
+ assert.match(pageSource, /task=\{HUB_TASKS_BY_MODE\[mode\]\}/);
+});
+
+test("resident sidecar keys restore canonical repo casing", () => {
+ assert.equal(
+ sttRepoIdForSidecarKey("qwen3-asr-0.6b", "mtmd"),
+ "unslothai/Qwen3-ASR-0.6B-GGUF",
+ );
+});
+
+test("Whisper artifacts retain distinct runtime identities", () => {
+ assert.equal(
+ sttRepoIdForSidecarKey("small", "transformers"),
+ "unsloth/whisper-small",
+ );
+ assert.equal(
+ sttRepoIdForSidecarKey("small", "gguf"),
+ "unslothai/whisper-small-GGUF",
+ );
+ assert.equal(sttEngineForRepoId("unsloth/whisper-small"), "transformers");
+ assert.equal(sttEngineForRepoId("unslothai/whisper-small-GGUF"), "gguf");
+ assert.equal(sttEngineForRepoId("unslothai/Qwen3-ASR-0.6B-GGUF"), "mtmd");
+ assert.equal(sttSidecarKeyFor("unslothai/whisper-small-GGUF"), "small");
+ assert.match(catalogSource, /isKnownSttArtifactRepoId\(repoId\)/);
+});
+
+test("ASR names carry the audio capability badge", () => {
+ assert.equal(
+ detectCapabilities({ id: "unslothai/Qwen3-ASR-0.6B-GGUF" }).audio,
+ true,
+ );
+});
diff --git a/studio/frontend/tests/audio-model-eject.test.ts b/studio/frontend/tests/audio-model-eject.test.ts
new file mode 100644
index 00000000000..7094169cdd7
--- /dev/null
+++ b/studio/frontend/tests/audio-model-eject.test.ts
@@ -0,0 +1,139 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+const source = readFileSync(
+ new URL("../src/features/audio/audio-page.tsx", import.meta.url),
+ "utf8",
+);
+const adapterSource = readFileSync(
+ new URL(
+ "../src/features/chat/adapters/studio-model-dictation-adapter.ts",
+ import.meta.url,
+ ),
+ "utf8",
+);
+
+test("Audio exposes the shared picker eject action only while idle", () => {
+ assert.match(
+ source,
+ /onEject=\{busy === null && selectorValue \? handleEject : undefined\}/,
+ );
+ assert.match(source, /if \(busy !== null \|\| isRecording\)/);
+ assert.match(
+ source,
+ /loaded=\{mode === "transcribe" \? sttReady : undefined\}/,
+ );
+});
+
+test("Speak eject unloads the live main model and cancels stale auto-load", () => {
+ assert.match(
+ source,
+ /const activeModel = status\?\.active_model;[\s\S]*unloadModel\(\{ model_path: activeModel \}\)/,
+ );
+ assert.match(
+ source,
+ /pendingStagedTtsLoad\.current = null;[\s\S]*stagedTtsLoadDeferred\.current = false;[\s\S]*stageTtsDownload\(\[\]\)/,
+ );
+ assert.match(source, /await unloadModel[\s\S]*await refreshStatus\(\)/);
+});
+
+test("Transcribe eject only unloads a sidecar owned by the current selection", () => {
+ assert.match(
+ source,
+ /const handleEject[\s\S]*stopAndDiscardRecording\(\);[\s\S]*if \(mode === "transcribe"\)/,
+ );
+ // One release path, shared with the Generate-mode transition, so both stay owned.
+ // The selection is forgotten only after the unload lands, so a 500 leaves Eject usable.
+ assert.match(
+ source,
+ /const releaseTranscribeSelection = useCallback\([\s\S]*await unloadSttModel\(sttEngineForRepoId\(selected\), claim\);\s*forget\(\);\s*await refreshSttStatus\(\)/,
+ );
+ assert.match(
+ source,
+ /const forget = \(\) => \{[\s\S]*setSelectedSttRepo\(null\);\s*\};[\s\S]*if \(!owned\) \{\s*forget\(\);/,
+ );
+ assert.match(
+ source,
+ /if \(mode === "transcribe"\)[\s\S]*await releaseTranscribeSelection\(\)/,
+ );
+ assert.match(
+ adapterSource,
+ /unloadSttModel\(\s*engine\?: SttEngine,[\s\S]*params\.set\("engine", engine\)/,
+ );
+ assert.match(
+ source,
+ /if \(!sttReady\) \{[\s\S]*sttStatusRefreshGeneration\.current \+= 1;[\s\S]*void releaseTranscribeSelection\(\)/,
+ );
+});
+
+test("leaving Transcribe releases the sidecar it loaded", () => {
+ // Holding it through Generate doubled VRAM for the whole keep-alive window (PR 7984 report).
+ // Anchored inside transitionMode: an unanchored [\s\S]* matched handleEject instead, so
+ // deleting the release from the mode switch still passed.
+ // The release is now captured rather than fire-and-forget, so a following TTS load can
+ // wait behind the teardown instead of allocating alongside it.
+ assert.match(
+ source,
+ /setMode\(nextMode\);[\s\S]*?if \(mode === "transcribe"\) \{[\s\S]*?const release = releaseTranscribeSelection\(\)\.then\(/,
+ );
+ assert.match(source, /pendingTranscribeRelease\.current = release;/);
+ assert.match(
+ source,
+ // The release resolves to whether the sidecar is gone. A failure must not hand off to
+ // a speech load on top of a still-resident dictation model.
+ /const releaseInFlight = pendingTranscribeRelease\.current;[\s\S]*?if \(releaseInFlight && !\(await releaseInFlight\)\) \{\s*setMode\("transcribe"\);\s*return;/,
+ );
+});
+
+test("selected and fallback clip actions remain named and downloadable", () => {
+ assert.match(source, /aria-label="Download audio clip"/);
+ assert.match(source, /aria-label="Delete audio clip"/);
+ assert.match(
+ source,
+ /const handleDownloadFallbackClip[\s\S]*anchor\.download = "generated-audio\.wav"/,
+ );
+ assert.match(
+ source,
+ /onClick=\{handleDownloadFallbackClip\}[\s\S]*Download WAV/,
+ );
+});
+
+test("a dictation model this page did not load survives a mode switch", () => {
+ // The activation resync adopts whatever a sidecar holds, including chat dictation's model.
+ // The identity, not a boolean. Another surface can swap the sidecar's model while Audio
+ // is inactive; the activation resync then adopts it, and a bare flag claimed it too, so
+ // Eject unloaded a model this page never loaded. Model only, not model plus engine: a
+ // "gguf" pick without whisper-server is served by the Transformers fallback and reports
+ // residency under that engine, so requiring the requested engine leaked the sidecar.
+ assert.match(source, /claim !== null && claim === sttLoadedModel;/);
+ // Ownership is claimed after a successful load, not before it: claiming up front left the
+ // flag set when a download was cancelled while the backend kept the previous resident
+ // model, so leaving Transcribe unloaded another surface's model.
+ assert.doesNotMatch(
+ source,
+ /setBusy\("loading"\);\s*sttLoadedByThisPage\.current = sidecarKey;/,
+ );
+ assert.match(
+ source,
+ /await loadSttModel\(sidecarKey, engine, controller\.signal\);\s*sttLoadedByThisPage\.current = sidecarKey;/,
+ );
+});
+
+test("the eject unload names the model this page claimed", () => {
+ // `owned` is decided locally, so another surface can switch the same engine before the
+ // request lands; an unscoped unload then tore down a model this page never owned.
+ assert.match(
+ source,
+ /await unloadSttModel\(sttEngineForRepoId\(selected\), claim\);/,
+ );
+});
+
+test("the unload request carries the claimed model to the backend", () => {
+ const adapter = adapterSource;
+ assert.match(adapter, /export function unloadSttModel\(\s*engine\?: SttEngine,\s*model\?: string,/);
+ assert.match(adapter, /if \(model\) params\.set\("model", model\);/);
+});
diff --git a/studio/frontend/tests/audio-page-policy.test.ts b/studio/frontend/tests/audio-page-policy.test.ts
new file mode 100644
index 00000000000..85879561d87
--- /dev/null
+++ b/studio/frontend/tests/audio-page-policy.test.ts
@@ -0,0 +1,556 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+import {
+ canTransitionAudioMode,
+ exactGgufLoadSelector,
+ expectedGgufDownloadBytes,
+ isTtsAudioType,
+ macTtsPickAction,
+ mergeGalleryPage,
+ micStreamRequestIsCurrent,
+ persistedClipForGeneration,
+ reconcileSttSelection,
+ resolveSttLoadedModel,
+ resolveSttResidency,
+ selectAutoGgufVariant,
+ stagedTtsLoadIsOwned,
+ sttSelectionReady,
+} from "../src/features/audio/audio-page-policy.ts";
+
+const audioPageSource = readFileSync(
+ new URL("../src/features/audio/audio-page.tsx", import.meta.url),
+ "utf8",
+);
+const chatApiSource = readFileSync(
+ new URL("../src/features/chat/api/chat-api.ts", import.meta.url),
+ "utf8",
+);
+
+test("mode transitions cancel generation but wait for non-cancellable work", () => {
+ assert.equal(canTransitionAudioMode(null), true);
+ assert.equal(canTransitionAudioMode("generating"), true);
+ assert.equal(canTransitionAudioMode("loading"), false);
+ assert.equal(canTransitionAudioMode("unloading"), false);
+ assert.equal(canTransitionAudioMode("transcribing"), false);
+});
+
+test("staged TTS completion requires the same Speak ownership generation", () => {
+ assert.equal(stagedTtsLoadIsOwned(4, 4, "speak"), true);
+ assert.equal(stagedTtsLoadIsOwned(4, 5, "speak"), false);
+ assert.equal(stagedTtsLoadIsOwned(4, 4, "transcribe"), false);
+ assert.equal(stagedTtsLoadIsOwned(null, 4, "speak"), false);
+});
+
+test("cached GGUF quant labels remain exact when no filename is present", () => {
+ assert.equal(exactGgufLoadSelector({ ggufVariant: "Q4_K_M" }), "Q4_K_M");
+ assert.equal(
+ exactGgufLoadSelector({
+ ggufVariant: "Q4_K_M",
+ ggufFilename: "model-q4_k_m.gguf",
+ }),
+ "model-q4_k_m.gguf",
+ );
+});
+
+test("TTS load context matches the advertised generation ceiling", () => {
+ assert.match(audioPageSource, /const TTS_MAX_TOKENS = 8192/);
+ assert.match(audioPageSource, /max_seq_length: TTS_MAX_TOKENS/);
+ assert.match(audioPageSource, /label="Max tokens"[\s\S]*max=\{TTS_MAX_TOKENS\}/);
+});
+
+test("Mac rejects safetensors-only TTS and redirects sibling families", () => {
+ assert.equal(
+ macTtsPickAction({ isMac: true, isGguf: false, ggufSibling: null }),
+ "reject",
+ );
+ assert.equal(
+ macTtsPickAction({
+ isMac: true,
+ isGguf: false,
+ ggufSibling: "org/model-GGUF",
+ }),
+ "use-gguf-sibling",
+ );
+ assert.equal(
+ macTtsPickAction({ isMac: true, isGguf: true, ggufSibling: null }),
+ "allow",
+ );
+});
+
+test("Mac sibling resolution returns an exact managed-download file", () => {
+ const variants = [
+ {
+ filename: "model-q4.gguf",
+ quant: "Q4_K_M",
+ size_bytes: 4_000,
+ download_size_bytes: 3_500,
+ downloaded: false,
+ },
+ {
+ filename: "model-q8.gguf",
+ quant: "Q8_0",
+ size_bytes: 8_000,
+ downloaded: true,
+ },
+ ];
+ const cached = selectAutoGgufVariant(variants, "Q4_K_M");
+ assert.equal(cached?.filename, "model-q8.gguf");
+
+ const remote = selectAutoGgufVariant(
+ variants.map((variant) => ({ ...variant, downloaded: false })),
+ "Q4_K_M",
+ );
+ assert.equal(remote?.filename, "model-q4.gguf");
+ assert.equal(remote && expectedGgufDownloadBytes(remote), 3_500);
+});
+
+test("only the generation's persisted gallery id is selected", () => {
+ const refreshed = [{ id: "other-client" }, { id: "ours" }];
+ assert.deepEqual(persistedClipForGeneration("ours", refreshed), {
+ id: "ours",
+ });
+ assert.equal(persistedClipForGeneration(null, refreshed), null);
+ assert.equal(persistedClipForGeneration("missing", refreshed), null);
+});
+
+test("Speak requires a supported TTS codec, not any audio model", () => {
+ for (const codec of ["snac", "csm", "bicodec", "dac"])
+ assert.equal(isTtsAudioType(codec), true);
+ assert.equal(isTtsAudioType("csm", true), false);
+ for (const codec of ["snac", "bicodec", "dac"])
+ assert.equal(isTtsAudioType(codec, true), true);
+ for (const codec of ["whisper", "audio_vlm", "", null])
+ assert.equal(isTtsAudioType(codec), false);
+});
+
+test("STT controls require the selected sidecar to be resident", () => {
+ const keyFor = (repo: string) => (repo === "org/asr" ? "asr" : repo);
+ assert.equal(sttSelectionReady("org/asr", "asr", keyFor), true);
+ assert.equal(sttSelectionReady("org/asr", null, keyFor), false);
+ assert.equal(sttSelectionReady("org/asr", "other", keyFor), false);
+ assert.equal(
+ sttSelectionReady("org/asr", "asr", keyFor, "transformers", "gguf"),
+ false,
+ );
+});
+
+test("STT activation adopts resident sidecars and preserves only pending selections", () => {
+ const sidecarKeyFor = (repo: string) =>
+ repo === "org/asr-a" ? "asr-a" : repo === "org/asr-b" ? "asr-b" : repo;
+ const repoIdForSidecarKey = (key: string) =>
+ key === "asr-a" ? "org/asr-a" : key === "asr-b" ? "org/asr-b" : key;
+
+ assert.equal(
+ reconcileSttSelection({
+ selectedRepo: null,
+ loadedModel: "asr-b",
+ preservePending: false,
+ sidecarKeyFor,
+ repoIdForSidecarKey,
+ }),
+ "org/asr-b",
+ );
+ assert.equal(
+ reconcileSttSelection({
+ selectedRepo: "org/asr-a",
+ loadedModel: "asr-b",
+ preservePending: false,
+ sidecarKeyFor,
+ repoIdForSidecarKey,
+ }),
+ "org/asr-b",
+ );
+ assert.equal(
+ reconcileSttSelection({
+ selectedRepo: "org/asr-a",
+ loadedModel: null,
+ preservePending: true,
+ sidecarKeyFor,
+ repoIdForSidecarKey,
+ }),
+ "org/asr-a",
+ );
+ assert.equal(
+ reconcileSttSelection({
+ selectedRepo: "org/asr-a",
+ loadedModel: null,
+ preservePending: false,
+ sidecarKeyFor,
+ repoIdForSidecarKey,
+ }),
+ null,
+ );
+
+ assert.equal(
+ reconcileSttSelection({
+ selectedRepo: "unsloth/whisper-small",
+ loadedModel: "small",
+ loadedEngine: "gguf",
+ preservePending: false,
+ sidecarKeyFor: () => "small",
+ repoIdForSidecarKey: (_key, engine) =>
+ engine === "gguf"
+ ? "unslothai/whisper-small-GGUF"
+ : "unsloth/whisper-small",
+ engineForRepo: (repo) =>
+ repo.endsWith("-GGUF") ? "gguf" : "transformers",
+ }),
+ "unslothai/whisper-small-GGUF",
+ );
+});
+
+test("STT residency reads the selected engine instead of Transformers-only legacy fields", () => {
+ const qwenStatus = {
+ loaded_model: null,
+ loading: false,
+ transformers: { loaded_model: null, loading: false },
+ gguf: { loaded_model: null, loading: false },
+ mtmd: { loaded_model: "qwen3-asr-0.6b", loading: false },
+ };
+ assert.equal(
+ resolveSttLoadedModel(qwenStatus, "mtmd", false),
+ "qwen3-asr-0.6b",
+ );
+
+ const whisperStatus = {
+ ...qwenStatus,
+ mtmd: { loaded_model: null, loading: false },
+ gguf: { loaded_model: "small", loading: false },
+ };
+ assert.equal(resolveSttLoadedModel(whisperStatus, null, false), "small");
+ assert.deepEqual(resolveSttResidency(whisperStatus, "gguf", false), {
+ model: "small",
+ engine: "gguf",
+ });
+});
+
+test("a pending engine selection is not replaced by an older resident sidecar", () => {
+ const status = {
+ loaded_model: "small",
+ loading: false,
+ transformers: { loaded_model: "small", loading: false },
+ mtmd: { loaded_model: null, loading: false },
+ };
+ assert.equal(resolveSttLoadedModel(status, "mtmd", true), null);
+ assert.equal(resolveSttLoadedModel(status, "mtmd", false), "small");
+});
+
+test("a resolved microphone permission stream is accepted only by its live request", () => {
+ assert.equal(micStreamRequestIsCurrent(4, 4, true), true);
+ assert.equal(micStreamRequestIsCurrent(4, 5, true), false);
+ assert.equal(micStreamRequestIsCurrent(4, 4, false), false);
+});
+
+test("MediaRecorder setup failures release the acquired microphone stream", () => {
+ // start() now takes a timeslice so the byte cap is observable; the release on failure
+ // is what this test is about and is unchanged.
+ assert.match(
+ audioPageSource,
+ /recorder\.start\(RECORDING_CHUNK_MS\);[\s\S]*?catch \{[\s\S]*?stopRecordStream\(\);/,
+ );
+});
+
+test("leaving Audio clears an unresolved microphone permission wait", () => {
+ assert.match(
+ audioPageSource,
+ /const stopAndDiscardRecording[\s\S]*micRequestGeneration\.current \+= 1;[\s\S]*micPendingGeneration\.current = null;[\s\S]*setMicRequestPending\(false\)/,
+ );
+});
+
+test("routed picks wait in the URL until Audio is idle", () => {
+ assert.match(
+ audioPageSource,
+ /if \(busyRef\.current !== null\) return;[\s\S]*handledRouteModel\.current = key;[\s\S]*handleModelSelect\(wanted/,
+ );
+ assert.match(audioPageSource, /\[\s*active,\s*busy,/);
+});
+
+test("file transcription cannot overlap a pending microphone permission", () => {
+ assert.match(
+ audioPageSource,
+ /type="file"[\s\S]*disabled=\{[\s\S]*micRequestPending[\s\S]*onChange=/,
+ );
+});
+
+test("gallery refresh preserves fallback selection and pagination identity", () => {
+ assert.match(
+ audioPageSource,
+ /const generation = \+\+galleryRefreshGeneration\.current;[\s\S]*listAudioGallery\(0, PAGE_SIZE\);[\s\S]*if \(generation !== galleryRefreshGeneration\.current\) return/,
+ );
+ assert.match(
+ audioPageSource,
+ /!fallbackClipRef\.current[\s\S]*merged\.length > 0/,
+ );
+ assert.match(
+ audioPageSource,
+ /listAudioGallery\([\s\S]*galleryCache\.nextCursor[\s\S]*galleryCache\.nextCursor =[\s\S]*page\.next_before_mtime[\s\S]*new Set\(galleryCache\.clips\.map[\s\S]*filter\(\(clip\) => !known\.has\(clip\.id\)\)/,
+ );
+});
+
+test("Audio transcription uses backend language auto-detection", () => {
+ assert.match(
+ audioPageSource,
+ /transcribeAudioBlob\(blob, \{[\s\S]*model: key,[\s\S]*engine,[\s\S]*language: ""/,
+ );
+});
+
+test("older STT status requests cannot overwrite newer residency", () => {
+ assert.match(
+ audioPageSource,
+ /const generation = \+\+sttStatusRefreshGeneration\.current;[\s\S]*await fetchSttStatus[\s\S]*generation !== sttStatusRefreshGeneration\.current\) return;[\s\S]*catch \{[\s\S]*generation !== sttStatusRefreshGeneration\.current\) return;/,
+ );
+});
+
+test("older TTS status requests cannot overwrite newer residency", () => {
+ assert.match(
+ audioPageSource,
+ /const generation = \+\+ttsStatusRefreshGeneration\.current;[\s\S]*await getInferenceStatus\(\)[\s\S]*generation !== ttsStatusRefreshGeneration\.current\) return;[\s\S]*catch \{[\s\S]*generation !== ttsStatusRefreshGeneration\.current\) return;/,
+ );
+});
+
+test("leaving Audio cancels an owned TTS load without touching a pre-request prompt", () => {
+ assert.match(
+ audioPageSource,
+ /const loadRequestId = crypto\.randomUUID\(\);[\s\S]*load_request_id: loadRequestId/,
+ );
+ assert.match(
+ audioPageSource,
+ // Cancels under the target the request actually sent. The display id only maps back
+ // to the load for a standard HF cache snapshot; a pinned directory elsewhere does not,
+ // and the backend then refuses the cancellation and keeps loading.
+ /const pending = pendingTtsLoad\.current;[\s\S]*pending\.controller\.abort\(\);[\s\S]*if \(pending\.requestStarted\)[\s\S]*unloadModel\(\{[\s\S]*model_path: pending\.loadTarget,[\s\S]*cancel_load_request_id: pending\.loadRequestId/,
+ );
+ assert.match(
+ chatApiSource,
+ /if \(options\?\.signal\?\.aborted\)[\s\S]*options\?\.onRequestStart\?\.\(\);[\s\S]*authFetch\("\/api\/inference\/load", \{[\s\S]*signal: options\?\.signal/,
+ );
+});
+
+test("history-only downloads revoke their temporary blob URL", () => {
+ assert.match(
+ audioPageSource,
+ /handleDownloadClipById[\s\S]*temporaryUrl = fetched\.url;[\s\S]*anchor\.click\(\);[\s\S]*URL\.revokeObjectURL\(url\)/,
+ );
+ assert.doesNotMatch(
+ audioPageSource,
+ /handleDownloadClipById[\s\S]{0,500}galleryCache\.srcById\.set/,
+ );
+});
+
+test("a gallery refresh keeps the loaded scrollback instead of collapsing it", () => {
+ const page = [{ id: "e" }, { id: "d" }, { id: "c" }];
+ const cached = [
+ { id: "d" },
+ { id: "c" },
+ { id: "b" },
+ { id: "a" },
+ ];
+
+ // Newest page first, then the pages the user scrolled to.
+ assert.deepEqual(mergeGalleryPage(page, cached), {
+ clips: [{ id: "e" }, { id: "d" }, { id: "c" }, { id: "b" }, { id: "a" }],
+ stitched: true,
+ });
+});
+
+test("a clip this client deleted leaves the merged gallery", () => {
+ const merged = mergeGalleryPage(
+ [{ id: "c" }, { id: "a" }],
+ [{ id: "b" }, { id: "a" }],
+ "b",
+ );
+ assert.deepEqual(merged.clips, [{ id: "c" }, { id: "a" }]);
+});
+
+test("the selection only moves when its clip left the merged gallery", () => {
+ assert.match(
+ audioPageSource,
+ /const \{ clips: merged, stitched \} = mergeGalleryPage\([\s\S]*!merged\.some\(\(c\) => c\.id === galleryCache\.selectedId\)/,
+ );
+ // Play an older clip, delete another, and the player must not jump to the newest.
+ assert.doesNotMatch(
+ audioPageSource,
+ /galleryCache\.clips = page\.audio/,
+ );
+});
+
+test("a superseded refresh still reports the clips its own fetch saw", () => {
+ // Otherwise a generation whose clip really persisted was told it was not saved.
+ assert.match(
+ audioPageSource,
+ /if \(generation !== galleryRefreshGeneration\.current\) return page\.audio;/,
+ );
+ assert.match(
+ audioPageSource,
+ /const refreshed = await refreshGallery\(\);[\s\S]*persistedClipForGeneration\(\s*generated\.clip_id,\s*refreshed,/,
+ );
+});
+
+test("keeping the scrollback keeps the deeper pagination cursor", () => {
+ // A clip carries no mtime, so adopting the page-0 cursor made loadMore re-walk loaded pages.
+ assert.match(
+ audioPageSource,
+ /if \(!stitched\) \{[\s\S]*galleryCache\.hasMore = page\.has_more;[\s\S]*galleryCache\.nextCursor =/,
+ );
+ assert.match(audioPageSource, /setHasMore\(galleryCache\.hasMore\);/);
+});
+
+test("a cache with nothing in common with the page is dropped, not stitched", () => {
+ // Another client can write a full page between two refreshes; stitching would render the
+ // gap as contiguous and the preserved cursor could never fetch it.
+ const merged = mergeGalleryPage(
+ [{ id: "z" }, { id: "y" }],
+ [{ id: "c" }, { id: "b" }],
+ );
+ assert.deepEqual(merged, { clips: [{ id: "z" }, { id: "y" }], stitched: false });
+});
+
+test("the recorder is gated on the same capability check the composer uses", () => {
+ // Safari ships no MediaRecorder, and an http LAN origin (-H 0.0.0.0) is not a
+ // secure context, so navigator.mediaDevices is undefined there. Without this
+ // gate Record is enabled and its only outcome is "Could not access the
+ // microphone", which blames the wrong thing.
+ assert.match(
+ audioPageSource,
+ /StudioModelDictationAdapter\.isSupported\(\)/,
+ "the audio page must reuse the dictation capability check",
+ );
+ assert.match(
+ audioPageSource,
+ /disabled=\{\s*!recordingSupported/,
+ "Record must be disabled when recording is unsupported",
+ );
+ // File upload stays available, so transcription still works on those hosts.
+ assert.match(audioPageSource, /accept="audio\/\*"/);
+});
+
+test("a recording is stopped at the sidecar's duration and size limits", () => {
+ // Without a cap the page buffered an over-long recording in memory and uploaded it only
+ // for the backend to refuse it. Mirrors _MAX_AUDIO_SECONDS and the b64 upload ceiling.
+ assert.match(audioPageSource, /const RECORDING_MAX_SECONDS = 30 \* 60;/);
+ assert.match(audioPageSource, /const RECORDING_MAX_BYTES = /);
+ assert.match(audioPageSource, /const RECORDING_MAX_BYTES = 25 \* 1024 \* 1024;/);
+ assert.match(
+ audioPageSource,
+ /if \(recordedBytes \+ event\.data\.size > RECORDING_MAX_BYTES\) \{\s*stopAtLimit\("size"\);/,
+ );
+ assert.match(
+ audioPageSource,
+ /window\.setTimeout\(\s*\(\) => stopAtLimit\("duration"\),\s*RECORDING_MAX_SECONDS \* 1000,/,
+ );
+ assert.match(audioPageSource, /window\.clearTimeout\(durationTimer\);/);
+});
+
+test("macOS hides trained TTS checkpoints that are not GGUF", () => {
+ // MLX has no TTS decoder, so a LoRA or merged safetensors row deterministically fails
+ // with "not supported on the MLX backend yet". The catalog rows are already filtered to
+ // families with a GGUF sibling; these have none.
+ assert.match(
+ audioPageSource,
+ /\.filter\(\(lora\) => !isMac \|\| lora\.export_type === "gguf"\)/,
+ );
+});
+
+test("the transcript download revokes its URL only after the click is consumed", () => {
+ // Immediate revocation raced browsers that resolve a synthetic download navigation
+ // asynchronously, leaving the action with no file.
+ assert.match(
+ audioPageSource,
+ /anchor\.download = `\$\{\(transcribedName[\s\S]*?anchor\.click\(\);[\s\S]*?window\.setTimeout\(\(\) => URL\.revokeObjectURL\(url\), 0\);/,
+ );
+});
+
+test("a complete first page drops cached rows the server no longer holds", () => {
+ // has_more=false means the page IS everything on the server, so a cached clip below it
+ // was deleted by another client or pruned by the size cap. Stitching it back rendered a
+ // row that stayed on screen across every refresh and failed to play.
+ const merged = mergeGalleryPage(
+ [{ id: "c" }, { id: "b" }],
+ [{ id: "c" }, { id: "b" }, { id: "a" }],
+ undefined,
+ false,
+ );
+ assert.deepEqual(merged, { clips: [{ id: "c" }, { id: "b" }], stitched: false });
+
+ // With more on the server the scrollback is still real and is kept.
+ const stitched = mergeGalleryPage(
+ [{ id: "c" }, { id: "b" }],
+ [{ id: "c" }, { id: "b" }, { id: "a" }],
+ undefined,
+ true,
+ );
+ assert.deepEqual(stitched.clips, [{ id: "c" }, { id: "b" }, { id: "a" }]);
+ assert.equal(stitched.stitched, true);
+});
+
+test("the refresh passes the page's completeness into the merge", () => {
+ assert.match(
+ audioPageSource,
+ /mergeGalleryPage\(\s*page\.audio,\s*galleryCache\.clips,\s*removedId,\s*page\.has_more,/,
+ );
+});
+
+test("generating waits for the transcribe release the mode switch started", () => {
+ // Switching straight from Transcribe to Speak with a speech model already resident needs
+ // no load, so the load path's gate never runs and Generate could allocate beside the
+ // dictation model, which OOMs a device that fits either one alone.
+ assert.match(
+ audioPageSource,
+ /const handleGenerate = useCallback\(async \(\) => \{[\s\S]{0,900}?const releaseInFlight = pendingTranscribeRelease\.current;[\s\S]{0,200}?if \(releaseInFlight && !\(await releaseInFlight\)\) \{[\s\S]{0,80}?setMode\("transcribe"\);/,
+ );
+});
+
+test("a failed transcribe release puts the page back in Transcribe", () => {
+ // Otherwise the pill reads Speak while the sidecar still holds its model, and nothing
+ // on screen offers the Eject that would retry the unload.
+ assert.match(
+ audioPageSource,
+ /void release\.then\(\(released\) => \{[\s\S]{0,600}?if \(!released && modeRef\.current === "speak"\) setMode\("transcribe"\);/,
+ );
+});
+
+test("a gguf selection served by Transformers still reads as resident", () => {
+ // Without whisper-server the backend serves and loads the equivalent Transformers
+ // model, so residency for the pick lives in that block. Reading only the gguf block
+ // returned nothing on the refresh that completes the load (preserveSelected is true
+ // there) and the Transcribe controls stayed disabled until the page was revisited.
+ const status = {
+ transformers: { loaded_model: "small", available: true },
+ gguf: { loaded_model: null, available: false },
+ };
+ assert.deepEqual(resolveSttResidency(status, "gguf", true), {
+ model: "small",
+ engine: "gguf",
+ });
+ assert.equal(resolveSttLoadedModel(status, "gguf", true), "small");
+
+ // whisper.cpp present: its own block still answers, and an empty one is still empty.
+ const live = {
+ transformers: { loaded_model: "small", available: true },
+ gguf: { loaded_model: "base", available: true },
+ };
+ assert.deepEqual(resolveSttResidency(live, "gguf", true), {
+ model: "base",
+ engine: "gguf",
+ });
+ assert.equal(resolveSttResidency({ gguf: { loaded_model: null } }, "gguf", true), null);
+});
+
+test("generation is claimed before the transcribe release is awaited", () => {
+ // The button only disables on `busy`, so awaiting first let several clicks through and
+ // each resumed into its own generateAudio while generateAbort tracked only the last.
+ assert.match(
+ audioPageSource,
+ /if \(busyRef\.current\) return;\s*busyRef\.current = "generating";\s*setBusy\("generating"\);\s*const releaseInFlight = pendingTranscribeRelease\.current;\s*if \(releaseInFlight/,
+ );
+ // And a release that failed hands the slot back rather than wedging the button.
+ assert.match(
+ audioPageSource,
+ /if \(releaseInFlight && !\(await releaseInFlight\)\) \{\s*busyRef\.current = null;\s*setBusy\(null\);\s*setMode\("transcribe"\);/,
+ );
+});
diff --git a/studio/frontend/tests/audio-picker-policy.test.ts b/studio/frontend/tests/audio-picker-policy.test.ts
new file mode 100644
index 00000000000..878b10b1ba0
--- /dev/null
+++ b/studio/frontend/tests/audio-picker-policy.test.ts
@@ -0,0 +1,518 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+import {
+ audioPickIsRoutable,
+ communityAudioRowIsRunnable,
+ curatedAudioInventoryMatches,
+ curatedAudioInventoryTask,
+ filesystemRowsSupportedForTask,
+ macTtsHubRowIsRunnable,
+ shouldDiscoverCommunityModels,
+ shouldRecommendCommunityModels,
+ taskCatalogFormatMatches,
+ taskForMediaPick,
+ withPipelineTag,
+} from "../src/features/model-picker/components/model-selector/audio-picker-policy.ts";
+
+test("filesystem rows stay out of Transcribe while cached Hub ASR remains supported", () => {
+ assert.equal(
+ filesystemRowsSupportedForTask(["automatic-speech-recognition"]),
+ false,
+ );
+ assert.equal(filesystemRowsSupportedForTask("automatic-speech-recognition"), false);
+ assert.equal(filesystemRowsSupportedForTask(["text-to-speech"]), true);
+ assert.equal(filesystemRowsSupportedForTask(undefined), true);
+ assert.equal(
+ filesystemRowsSupportedForTask(undefined, "automatic-speech-recognition"),
+ false,
+ );
+ assert.equal(
+ filesystemRowsSupportedForTask(undefined, "text-generation"),
+ true,
+ );
+});
+
+test("curated downloaded TTS artifacts override generic GGUF task metadata only in Speak", () => {
+ assert.equal(
+ curatedAudioInventoryMatches({
+ isActiveCatalogArtifact: true,
+ catalogScope: "audio",
+ catalogTask: "tts",
+ pickerTask: ["text-to-speech"],
+ }),
+ true,
+ );
+ assert.equal(
+ curatedAudioInventoryMatches({
+ isActiveCatalogArtifact: true,
+ catalogScope: "audio",
+ catalogTask: "tts",
+ pickerTask: ["automatic-speech-recognition"],
+ }),
+ false,
+ );
+});
+
+test("curated downloaded STT artifacts override generic metadata only in Transcribe", () => {
+ assert.equal(
+ curatedAudioInventoryMatches({
+ isActiveCatalogArtifact: true,
+ catalogScope: "audio",
+ catalogTask: "stt",
+ pickerTask: ["automatic-speech-recognition"],
+ }),
+ true,
+ );
+ assert.equal(
+ curatedAudioInventoryMatches({
+ isActiveCatalogArtifact: true,
+ catalogScope: "audio",
+ catalogTask: "stt",
+ pickerTask: ["text-to-speech"],
+ }),
+ false,
+ );
+});
+
+test("non-audio catalogs and unfiltered Chat get no downloaded-task exception", () => {
+ assert.equal(
+ curatedAudioInventoryMatches({
+ isActiveCatalogArtifact: true,
+ catalogScope: "image",
+ catalogTask: "tts",
+ pickerTask: ["text-to-speech"],
+ }),
+ false,
+ );
+ assert.equal(
+ curatedAudioInventoryMatches({
+ isActiveCatalogArtifact: true,
+ catalogScope: "audio",
+ catalogTask: "tts",
+ pickerTask: undefined,
+ }),
+ false,
+ );
+ assert.equal(
+ curatedAudioInventoryMatches({
+ isActiveCatalogArtifact: false,
+ catalogScope: "audio",
+ catalogTask: "tts",
+ pickerTask: ["text-to-speech"],
+ }),
+ false,
+ );
+});
+import {
+ AUDIO_CATALOG,
+ artifactForRepoId,
+ groupForRepoId,
+} from "../src/features/model-picker/components/model-selector/model-catalog.ts";
+
+const pickerSource = readFileSync(
+ new URL(
+ "../src/features/model-picker/components/model-selector/pickers.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+);
+
+test("fresh Hub pipeline metadata routes media picks before stale inventory", () => {
+ assert.equal(
+ taskForMediaPick("automatic-speech-recognition", "text-to-speech"),
+ "automatic-speech-recognition",
+ );
+ assert.equal(taskForMediaPick(null, "text-to-speech"), "text-to-speech");
+});
+
+test("generic cached GGUF metadata yields to the curated Audio task", () => {
+ assert.equal(
+ taskForMediaPick("text-generation", "automatic-speech-recognition"),
+ "automatic-speech-recognition",
+ );
+ assert.equal(
+ taskForMediaPick("text-generation", "text-to-speech"),
+ "text-to-speech",
+ );
+});
+
+test("exact cached Audio artifacts route from generic inventory to their Audio task", () => {
+ const orpheus = artifactForRepoId(
+ "unsloth/orpheus-3b-0.1-ft-GGUF",
+ AUDIO_CATALOG,
+ );
+ assert.ok(orpheus);
+ assert.equal(
+ taskForMediaPick(
+ null,
+ curatedAudioInventoryTask({
+ inventoryTask: "text-generation",
+ isExactCatalogArtifact: true,
+ catalogScope: orpheus.group.scope,
+ catalogTask: orpheus.group.task,
+ }),
+ ),
+ "text-to-speech",
+ );
+
+ const asr = artifactForRepoId("unslothai/Qwen3-ASR-0.6B-GGUF", AUDIO_CATALOG);
+ assert.ok(asr);
+ assert.equal(
+ taskForMediaPick(
+ null,
+ curatedAudioInventoryTask({
+ inventoryTask: "text-generation",
+ isExactCatalogArtifact: true,
+ catalogScope: asr.group.scope,
+ catalogTask: asr.group.task,
+ }),
+ ),
+ "automatic-speech-recognition",
+ );
+});
+
+test("generic LLM and non-Audio artifacts keep their inventory task", () => {
+ assert.equal(
+ curatedAudioInventoryTask({
+ inventoryTask: "text-generation",
+ isExactCatalogArtifact: false,
+ catalogScope: "audio",
+ catalogTask: "tts",
+ }),
+ "text-generation",
+ );
+ assert.equal(
+ curatedAudioInventoryTask({
+ inventoryTask: "text-generation",
+ isExactCatalogArtifact: true,
+ catalogScope: "image",
+ catalogTask: "tts",
+ }),
+ "text-generation",
+ );
+});
+
+test("local Audio rows copy the curated task onto their clickable path alias", () => {
+ assert.match(
+ pickerSource,
+ /const exactAudioArtifact = m\.model_id[\s\S]*artifactForRepoId\(m\.model_id, AUDIO_CATALOG\)[\s\S]*put\(m\.id, m\.task, exactAudioArtifact\)/,
+ );
+});
+
+test("every filesystem inventory applies the runtime task gate", () => {
+ for (const inventory of [
+ "lmStudioModels",
+ "localDirModels",
+ "customFolderModels",
+ ]) {
+ assert.match(
+ pickerSource,
+ new RegExp(
+ `${inventory}\\.filter\\([\\s\\S]*?filesystemRowsSupportedForTask\\(task, m\\.task\\)`,
+ ),
+ );
+ }
+});
+
+test("curated task artifacts remain in All while explicit formats still filter", () => {
+ assert.equal(taskCatalogFormatMatches("all", false), true);
+ assert.equal(taskCatalogFormatMatches("safetensors", true), true);
+ assert.equal(taskCatalogFormatMatches("gguf", false), false);
+});
+
+test("search-only Audio policy discovers community rows without recommending them", () => {
+ assert.equal(shouldDiscoverCommunityModels("search-only"), true);
+ assert.equal(shouldRecommendCommunityModels("search-only"), false);
+ assert.equal(shouldRecommendCommunityModels("recommended"), true);
+});
+
+test("community ASR only offers checkpoints the Transformers Whisper sidecar can load", () => {
+ assert.equal(
+ communityAudioRowIsRunnable({
+ isStt: true,
+ isTts: false,
+ isGguf: false,
+ id: "openai/whisper-large-v3",
+ tags: ["transformers", "whisper", "automatic-speech-recognition"],
+ libraryName: "transformers",
+ }),
+ true,
+ );
+ assert.equal(
+ communityAudioRowIsRunnable({
+ isStt: true,
+ isTts: false,
+ isGguf: false,
+ id: "community/speech-finetune",
+ tags: ["whisper"],
+ libraryName: "transformers",
+ }),
+ true,
+ );
+ assert.equal(
+ communityAudioRowIsRunnable({
+ isStt: true,
+ isTts: false,
+ isGguf: false,
+ id: "nvidia/parakeet-tdt-0.6b-v2",
+ tags: ["automatic-speech-recognition"],
+ libraryName: "transformers",
+ }),
+ false,
+ );
+ assert.equal(
+ communityAudioRowIsRunnable({
+ isStt: true,
+ isTts: false,
+ isGguf: true,
+ id: "community/whisper-GGUF",
+ }),
+ false,
+ );
+ // Llasa was in this list and should not have been. It speaks XCodec2, which
+ // AudioCodecManager cannot decode and _AUDIO_TOKEN_PATTERNS cannot even recognise, so
+ // probing a running Studio reports unsloth/Llasa-1B as is_audio=false. Admitting the row
+ // produced a model that loaded and then failed at generation.
+ assert.equal(
+ communityAudioRowIsRunnable({
+ isStt: false,
+ isTts: true,
+ isGguf: false,
+ id: "HKUSTAudio/Llasa-1B",
+ }),
+ false,
+ );
+ for (const id of [
+ "canopylabs/orpheus-3b-0.1-ft",
+ "sesame/csm-1b",
+ "SparkAudio/Spark-TTS-0.5B",
+ "OuteAI/Llama-OuteTTS-1.0-1B",
+ ]) {
+ assert.equal(
+ communityAudioRowIsRunnable({
+ isStt: false,
+ isTts: true,
+ isGguf: false,
+ id,
+ }),
+ true,
+ );
+ }
+ for (const id of [
+ "suno/bark",
+ "microsoft/speecht5_tts",
+ "facebook/mms-tts-eng",
+ "hexgrad/Kokoro-82M",
+ ]) {
+ assert.equal(
+ communityAudioRowIsRunnable({
+ isStt: false,
+ isTts: true,
+ isGguf: false,
+ id,
+ }),
+ false,
+ );
+ }
+ assert.equal(
+ communityAudioRowIsRunnable({
+ isStt: false,
+ isTts: true,
+ isGguf: true,
+ id: "community/csm-1b-GGUF",
+ }),
+ false,
+ );
+});
+
+test("cached runnable community audio survives the Audio on-device trust gate", () => {
+ assert.match(
+ pickerSource,
+ /c\.task === "automatic-speech-recognition" \|\|[\s\S]*c\.task === "text-to-speech"[\s\S]*communityAudioRowIsRunnable\(\{[\s\S]*isStt: c\.task === "automatic-speech-recognition",[\s\S]*isTts: c\.task === "text-to-speech",[\s\S]*id: c\.repo_id,[\s\S]*tags: c\.tags,[\s\S]*libraryName: c\.library_name/,
+ );
+ assert.match(
+ pickerSource,
+ /communityAudioRowIsRunnable\(\{[\s\S]*macTtsHubRowIsRunnable\(\{[\s\S]*isMac,[\s\S]*isTts: c\.task === "text-to-speech",[\s\S]*hasRunnableGgufSibling/,
+ );
+});
+
+test("Chat-to-Audio handoff preserves the live Hub task", () => {
+ // pickedTask, not meta.pipelineTag: a cached row carries no tag, so ASR would read as TTS.
+ assert.match(
+ pickerSource,
+ /page === "audio"[\s\S]*task:\s*pickedTask \?\? undefined/,
+ );
+ assert.match(
+ pickerSource,
+ /page === "audio" &&\s*!audioPickIsRoutable\(\{[\s\S]*isCurated: artifactForRepoId\(id, AUDIO_CATALOG\) !== null/,
+ );
+ assert.match(
+ pickerSource,
+ /page === "audio"[\s\S]*ggufQuant:\s*meta\.ggufFilename[\s\S]*meta\.ggufVariant/,
+ );
+ assert.match(
+ pickerSource,
+ /const alreadyListed = new Set\([\s\S]*visibleCachedGguf[\s\S]*visibleCachedModels/,
+ );
+});
+
+test("community Audio feeds participate in both infinite-scroll paths", () => {
+ assert.match(pickerSource, /communityQuerySearch\.fetchMore\(\)/);
+ assert.match(pickerSource, /communityBrowse\.fetchMore\(\)/);
+ assert.match(pickerSource, /recommendedHasMore/);
+ assert.match(
+ pickerSource,
+ /const unslothRequested = hasMore \? fetchMore\(\) : false;[\s\S]*const communityRequested =[\s\S]*communityQuerySearch\.fetchMore\(\)/,
+ );
+});
+
+test("macOS TTS search only offers directly runnable or curated GGUF-backed rows", () => {
+ assert.equal(
+ macTtsHubRowIsRunnable({
+ isMac: true,
+ isTts: true,
+ isGguf: false,
+ hasRunnableGgufSibling: false,
+ }),
+ false,
+ );
+ assert.equal(
+ macTtsHubRowIsRunnable({
+ isMac: true,
+ isTts: true,
+ isGguf: true,
+ hasRunnableGgufSibling: false,
+ }),
+ true,
+ );
+ assert.equal(
+ macTtsHubRowIsRunnable({
+ isMac: true,
+ isTts: true,
+ isGguf: false,
+ hasRunnableGgufSibling: true,
+ }),
+ true,
+ );
+ assert.equal(
+ macTtsHubRowIsRunnable({
+ isMac: false,
+ isTts: true,
+ isGguf: false,
+ hasRunnableGgufSibling: false,
+ }),
+ true,
+ );
+ const csmHasGguf = Boolean(
+ groupForRepoId("unsloth/csm-1b", AUDIO_CATALOG)?.artifacts.some(
+ (artifact) => artifact.format === "gguf",
+ ),
+ );
+ assert.equal(csmHasGguf, false);
+ assert.equal(
+ macTtsHubRowIsRunnable({
+ isMac: true,
+ isTts: true,
+ isGguf: false,
+ hasRunnableGgufSibling: csmHasGguf,
+ }),
+ false,
+ );
+});
+
+test("GGUF variant picks retain their Hub pipeline tag", () => {
+ assert.deepEqual(
+ withPipelineTag(
+ { source: "hub", isLora: false, isGguf: true, ggufVariant: "Q4_K_M" },
+ "automatic-speech-recognition",
+ ),
+ {
+ source: "hub",
+ isLora: false,
+ isGguf: true,
+ ggufVariant: "Q4_K_M",
+ pipelineTag: "automatic-speech-recognition",
+ },
+ );
+});
+
+test("only speech repos the runtime can serve are routed to the Audio page", () => {
+ const curated = {
+ id: "unsloth/orpheus-3b-0.1-ft",
+ task: "text-to-speech",
+ isGguf: false,
+ isCurated: true,
+ };
+ assert.equal(audioPickIsRoutable(curated), true);
+ // The catalog, not the tag, is a curated id's runtime contract.
+ assert.equal(audioPickIsRoutable({ ...curated, isCurated: false }), true);
+
+ // Hub tags text-to-speech onto families the main-slot backend has no decoder for.
+ assert.equal(
+ audioPickIsRoutable({
+ id: "suno/bark",
+ task: "text-to-speech",
+ isGguf: false,
+ isCurated: false,
+ }),
+ false,
+ );
+ // Community ASR runs on the Transformers Whisper sidecar only.
+ assert.equal(
+ audioPickIsRoutable({
+ id: "someone/whisper-small-fi",
+ task: "automatic-speech-recognition",
+ isGguf: false,
+ isCurated: false,
+ }),
+ true,
+ );
+ assert.equal(
+ audioPickIsRoutable({
+ id: "someone/parakeet-tdt",
+ task: "automatic-speech-recognition",
+ isGguf: false,
+ isCurated: false,
+ }),
+ false,
+ );
+ // A chat pick is not an audio pick, so the gate must not claim it.
+ assert.equal(
+ audioPickIsRoutable({
+ id: "unsloth/Qwen3-8B",
+ task: "text-generation",
+ isGguf: false,
+ isCurated: false,
+ }),
+ true,
+ );
+});
+
+test("an unroutable speech pick is refused instead of loaded into chat", () => {
+ assert.match(
+ pickerSource,
+ /!audioPickIsRoutable\(\{[\s\S]*\}\)\s*\) \{[\s\S]*toast\.error\([\s\S]*return;/,
+ );
+});
+
+test("a local Whisper checkpoint is not advertised as a routable ASR row", () => {
+ // The STT sidecar's resolve_model_id takes a curated key or an owner/model Hub id, so a
+ // filesystem path 422s. Routing one from the picker advertised a row that cannot load.
+ const source = readFileSync(
+ new URL(
+ "../src/features/model-picker/components/model-selector/pickers.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(
+ source,
+ /if \(audioType === "whisper"\)\s*\n?\s*return isLocalCheckpoint \? undefined : "automatic-speech-recognition";/,
+ );
+ assert.match(source, /pipelineTag: audioPipelineTagFor\(adapter\.audioType, true\)/);
+});
diff --git a/studio/frontend/tests/audio-recommended-mode-order.test.ts b/studio/frontend/tests/audio-recommended-mode-order.test.ts
new file mode 100644
index 00000000000..04bf0d8115c
--- /dev/null
+++ b/studio/frontend/tests/audio-recommended-mode-order.test.ts
@@ -0,0 +1,95 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Each mode advertises only checkpoints it can execute, while the curated STT
+// set still covers every dictation sidecar id.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ AUDIO_CATALOG,
+ catalogToModelOptions,
+ groupForRepoId,
+} from "../src/features/model-picker/components/model-selector/model-catalog.ts";
+
+type AudioTask = "tts" | "stt";
+
+const taskFor = (repoId: string): AudioTask | null =>
+ (groupForRepoId(repoId, AUDIO_CATALOG)?.task as AudioTask | undefined) ??
+ null;
+
+// Mirrors audioModelsForTask in src/features/audio/catalog.ts, which cannot be
+// imported here: it resolves through the "@/" alias.
+const modelsForTask = (task: AudioTask) => {
+ const all = catalogToModelOptions(AUDIO_CATALOG);
+ const matches = (id: string) => taskFor(id) === task;
+ return all.filter((o) => matches(o.id)).map((o) => o.id);
+};
+
+test("Transcribe offers only STT, with Qwen3-ASR above the fold", () => {
+ const rows = modelsForTask("stt");
+ assert.ok(rows.every((id) => taskFor(id) === "stt"));
+ // The regression: both unslothai models sat at 8 and 9 behind every TTS row.
+ const qwen = rows.filter((id) => id.startsWith("unslothai/Qwen3-ASR"));
+ assert.equal(qwen.length, 2);
+ for (const id of qwen) assert.ok(rows.indexOf(id) < 3, `${id} buried`);
+});
+
+test("Qwen3-ASR rows retain the fixed sidecar quant", () => {
+ const qwen = catalogToModelOptions(AUDIO_CATALOG).filter((option) =>
+ option.id.startsWith("unslothai/Qwen3-ASR"),
+ );
+ assert.equal(qwen.length, 2);
+ assert.ok(qwen.every((option) => option.deviceQuant === "Q8_0"));
+});
+
+test("Generate offers only TTS", () => {
+ const rows = modelsForTask("tts");
+ assert.ok(rows.every((id) => taskFor(id) === "tts"));
+ assert.ok(rows.indexOf("unsloth/orpheus-3b-0.1-ft") < 2);
+});
+
+test("the two modes partition every curated model", () => {
+ const all = catalogToModelOptions(AUDIO_CATALOG).map((o) => o.id);
+ const tts = modelsForTask("tts");
+ const stt = modelsForTask("stt");
+ assert.equal(
+ tts.some((id) => stt.includes(id)),
+ false,
+ );
+ assert.deepEqual([...tts, ...stt].sort(), [...all].sort());
+});
+
+test("the curated STT rows cover every dictation sidecar model", () => {
+ // GGML_STT_REPOS / STT_MODEL_REPOS carry tiny and base too; the picker used to
+ // stop at small, so two supported sizes were unreachable from this page.
+ const stt = modelsForTask("stt").filter((id) => taskFor(id) === "stt");
+ for (const size of ["tiny", "base", "small", "large-v3", "large-v3-turbo"]) {
+ assert.ok(
+ stt.includes(`unsloth/whisper-${size}`),
+ `whisper-${size} missing from the audio picker`,
+ );
+ }
+});
+
+test("a TTS group's GGUF sibling is what resolves for a safetensors pick", () => {
+ // On a Mac the safetensors build loads through MLX, which has no TTS decoder,
+ // so the page swaps in the GGUF build rather than letting generation 501.
+ const ggufSibling = (repoId: string) => {
+ const group = groupForRepoId(repoId, AUDIO_CATALOG);
+ if (!group || group.task !== "tts") return null;
+ const gguf = group.artifacts.find((a) => a.format === "gguf");
+ return gguf && gguf.repoId !== repoId ? gguf.repoId : null;
+ };
+ assert.equal(
+ ggufSibling("unsloth/orpheus-3b-0.1-ft"),
+ "unsloth/orpheus-3b-0.1-ft-GGUF",
+ );
+ // Already GGUF: nothing to swap.
+ assert.equal(ggufSibling("unsloth/orpheus-3b-0.1-ft-GGUF"), null);
+ // No GGUF published, so the pick stands and the 501 explains why.
+ assert.equal(ggufSibling("unsloth/csm-1b"), null);
+ // STT never swaps: it runs on the sidecar, not the main slot.
+ assert.equal(ggufSibling("unsloth/whisper-small"), null);
+});
diff --git a/studio/frontend/tests/audio-stt-download-fallback.test.ts b/studio/frontend/tests/audio-stt-download-fallback.test.ts
new file mode 100644
index 00000000000..4463219c913
--- /dev/null
+++ b/studio/frontend/tests/audio-stt-download-fallback.test.ts
@@ -0,0 +1,94 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+const source = readFileSync(
+ new URL("../src/features/audio/audio-page.tsx", import.meta.url),
+ "utf8",
+);
+const mirrorSource = readFileSync(
+ new URL(
+ "../src/features/settings/lib/stt-download-mirror.ts",
+ import.meta.url,
+ ),
+ "utf8",
+);
+
+test("STT download polling uses the available engine fallback", () => {
+ assert.match(
+ source,
+ /const block = sttEngineStatusFor\(stt, sidecarKey, engine\)/,
+ );
+ assert.doesNotMatch(
+ source,
+ /engine === "gguf"[\s\S]*\? stt\.gguf[\s\S]*: stt\.transformers/,
+ );
+});
+
+test("Audio mirrors an STT transfer into Downloads without resetting an adopted job", () => {
+ assert.match(
+ source,
+ /await startSttDownload\(sidecarKey,[\s\S]*engine\);[\s\S]*if \(!isTrackingSttDownload\(sidecarKey, engine\)\) \{[\s\S]*trackSttDownload\(sidecarKey, \{[\s\S]*warmSelectedVoiceModelOnComplete: false,[\s\S]*engine,[\s\S]*repoId,[\s\S]*\}\);[\s\S]*\}[\s\S]*for \(;;\)/,
+ );
+ assert.doesNotMatch(source, /`Downloading \$\{sidecarKey\}:/);
+});
+
+test("cancelling the shared STT download never loads a partial checkpoint", () => {
+ assert.match(
+ source,
+ /if \(download\?\.cancelled\) return;[\s\S]*if \(download\?\.error\)[\s\S]*if \(!download\?\.downloading\) break;[\s\S]*await loadSttModel\(sidecarKey, engine, controller\.signal\)/,
+ );
+});
+
+test("hidden STT preparation resumes once only for the same selected repo", () => {
+ assert.match(
+ source,
+ /deferredSttLoad\.current = repoId[\s\S]*sttLoadGeneration\.current \+= 1/,
+ );
+ assert.match(
+ source,
+ /const deferred = deferredSttLoad\.current;[\s\S]*deferredSttLoad\.current = null;[\s\S]*selectedSttRepoRef\.current === deferred\.repoId[\s\S]*ensureSttLoaded\([\s\S]*deferred\.repoId,[\s\S]*deferred\.sidecarKey,[\s\S]*deferred\.engine/,
+ );
+});
+
+test("resolved Transformers transfers share one tracker identity", () => {
+ assert.match(
+ mirrorSource,
+ /engine && engine !== "transformers" \? `\$\{engine\}:\$\{model\}` : model/,
+ );
+ assert.match(
+ mirrorSource,
+ /const resolvedEngine = options\.engine \?\? sttEngineFor\(model\);[\s\S]*trackerKey\(model, resolvedEngine\)/,
+ );
+ assert.match(
+ mirrorSource,
+ /if \(trackers\.has\(key\)\)[\s\S]*warmSelectedVoiceModelOnComplete\.set\(key, true\)/,
+ );
+});
+
+test("hidden Audio cancels only an active sidecar load", () => {
+ assert.match(
+ source,
+ /if \(sttLoadingGeneration\.current !== null\)[\s\S]*sttLoadAbort\.current\?\.abort\(\)/,
+ );
+ assert.doesNotMatch(source, /cancelSttLoad/);
+});
+
+test("STT loading stays busy until authoritative residency refresh completes", () => {
+ assert.match(
+ source,
+ /if \(sttLoadingGeneration\.current === generation\) \{[\s\S]*sttLoadingGeneration\.current = null;[\s\S]*await refreshSttStatus\(\);[\s\S]*generation === sttLoadGeneration\.current[\s\S]*sttLoadingGeneration\.current === null[\s\S]*setBusy\(null\)/,
+ );
+});
+
+test("cancelled deferred downloads remain cancelled on return", () => {
+ // `model` is null once the download thread has stopped, so the cancelled model id has to
+ // come from cancelled_model for a cancellation the user made while this page was hidden.
+ assert.match(
+ source,
+ /const download = sttEngineStatusFor[\s\S]*download\?\.cancelled[\s\S]*\(download\.model \?\? download\.cancelled_model\) === deferred\.sidecarKey[\s\S]*return/,
+ );
+});
diff --git a/studio/frontend/tests/audio-stt-on-device.test.ts b/studio/frontend/tests/audio-stt-on-device.test.ts
new file mode 100644
index 00000000000..9c1092e9893
--- /dev/null
+++ b/studio/frontend/tests/audio-stt-on-device.test.ts
@@ -0,0 +1,102 @@
+// 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 { sttDownloadedArtifacts } from "../src/features/audio/audio-page-policy.ts";
+import {
+ sttEngineForRepoId,
+ sttRepoIdForSidecarKey,
+} from "../src/features/audio/stt-artifacts.ts";
+
+const repoIdForSidecarKey = (
+ key: string,
+ engine: "transformers" | "gguf" | "mtmd",
+) => {
+ const repos: Record<string, string> =
+ engine === "gguf"
+ ? {
+ tiny: "unslothai/whisper-tiny-GGUF",
+ base: "unslothai/whisper-base-GGUF",
+ small: "unslothai/whisper-small-GGUF",
+ }
+ : {
+ tiny: "unsloth/whisper-tiny",
+ base: "unsloth/whisper-base",
+ small: "unsloth/whisper-small",
+ "qwen3-asr-0.6b": "unslothai/Qwen3-ASR-0.6B-GGUF",
+ };
+ return repos[key] ?? key;
+};
+
+test("STT On Device inventory follows all sidecar download engines", () => {
+ assert.deepEqual(
+ sttDownloadedArtifacts(
+ {
+ transformers: {
+ downloaded_models: ["small", "org/custom-whisper"],
+ },
+ gguf: { downloaded_models: ["small"] },
+ mtmd: { downloaded_models: ["qwen3-asr-0.6b"] },
+ },
+ repoIdForSidecarKey,
+ ),
+ [
+ {
+ repoId: "unsloth/whisper-small",
+ sidecarKey: "small",
+ engine: "transformers",
+ },
+ {
+ repoId: "org/custom-whisper",
+ sidecarKey: "org/custom-whisper",
+ engine: "transformers",
+ },
+ {
+ repoId: "unslothai/whisper-small-GGUF",
+ sidecarKey: "small",
+ engine: "gguf",
+ },
+ {
+ repoId: "unslothai/Qwen3-ASR-0.6B-GGUF",
+ sidecarKey: "qwen3-asr-0.6b",
+ engine: "mtmd",
+ },
+ ],
+ );
+});
+
+test("legacy top-level downloads are retained without duplicate rows", () => {
+ assert.deepEqual(
+ sttDownloadedArtifacts(
+ {
+ downloaded_models: ["tiny"],
+ transformers: { downloaded_models: ["tiny", "base"] },
+ },
+ repoIdForSidecarKey,
+ ),
+ [
+ {
+ repoId: "unsloth/whisper-tiny",
+ sidecarKey: "tiny",
+ engine: "transformers",
+ },
+ {
+ repoId: "unsloth/whisper-base",
+ sidecarKey: "base",
+ engine: "transformers",
+ },
+ ],
+ );
+});
+
+test("only exact curated Qwen artifacts use the finite MTMD runtime", () => {
+ assert.equal(sttEngineForRepoId("unslothai/Qwen3-ASR-0.6B-GGUF"), "mtmd");
+ assert.equal(sttEngineForRepoId("Qwen/Qwen3-ASR-0.6B"), "transformers");
+ assert.equal(sttEngineForRepoId("community/Qwen3-ASR-finetune"), "transformers");
+ assert.equal(
+ sttRepoIdForSidecarKey("qwen3-asr-0.6b", "mtmd"),
+ "unslothai/Qwen3-ASR-0.6B-GGUF",
+ );
+});
diff --git a/studio/frontend/tests/audio-task-picker-row-policy.test.ts b/studio/frontend/tests/audio-task-picker-row-policy.test.ts
new file mode 100644
index 00000000000..2cbc50267f7
--- /dev/null
+++ b/studio/frontend/tests/audio-task-picker-row-policy.test.ts
@@ -0,0 +1,56 @@
+// 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 { taskPickerRowMatches } from "../src/features/model-picker/components/model-selector/audio-picker-policy.ts";
+
+test("curated task seeds survive missing Hub metadata and device format gates", () => {
+ assert.equal(
+ taskPickerRowMatches({
+ isCatalogSeed: true,
+ format: "all",
+ matchesFormat: false,
+ matchesTask: false,
+ isRecommendable: false,
+ }),
+ true,
+ );
+});
+
+test("explicit format choices still filter curated task seeds", () => {
+ assert.equal(
+ taskPickerRowMatches({
+ isCatalogSeed: true,
+ format: "gguf",
+ matchesFormat: false,
+ matchesTask: false,
+ isRecommendable: false,
+ }),
+ false,
+ );
+});
+
+test("non-curated rows still require task and format compatibility", () => {
+ assert.equal(
+ taskPickerRowMatches({
+ isCatalogSeed: false,
+ format: "all",
+ matchesFormat: true,
+ matchesTask: false,
+ isRecommendable: true,
+ }),
+ false,
+ );
+ assert.equal(
+ taskPickerRowMatches({
+ isCatalogSeed: false,
+ format: "all",
+ matchesFormat: true,
+ matchesTask: true,
+ isRecommendable: false,
+ }),
+ false,
+ );
+});
diff --git a/studio/frontend/tests/audio-tts-download-manager.test.ts b/studio/frontend/tests/audio-tts-download-manager.test.ts
new file mode 100644
index 00000000000..7e3e3251633
--- /dev/null
+++ b/studio/frontend/tests/audio-tts-download-manager.test.ts
@@ -0,0 +1,100 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+const source = readFileSync(
+ new URL("../src/features/audio/audio-page.tsx", import.meta.url),
+ "utf8",
+);
+
+test("uncached remote TTS GGUFs stage the exact file through the shared manager", () => {
+ assert.match(source, /useStagedDownload\(\{\s*scopeId: "audio"/);
+ assert.match(
+ source,
+ /meta\.source === "hub"[\s\S]*meta\.isDownloaded === false[\s\S]*ggufFilename/,
+ );
+ assert.match(
+ source,
+ /stageTtsDownload\(\[\s*\{[\s\S]*repoId,[\s\S]*files: \[ggufFilename\],[\s\S]*bytes: meta\.expectedBytes \?\? 0/,
+ );
+ assert.match(
+ source,
+ /const exactGguf = exactGgufLoadSelector\(meta\)[\s\S]*loadOrStageTtsModel\(id, exactGguf, meta\)/,
+ );
+});
+
+test("cached and local TTS picks keep the direct load path and supersede stale staging", () => {
+ assert.match(
+ source,
+ // meta.loadId is the load target for a row cached in a non-active HF cache; sending
+ // the display repo id instead failed offline or re-downloaded into the active cache.
+ /pendingStagedTtsLoad\.current = null;[\s\S]*stageTtsDownload\(\[\]\);[\s\S]*loadTtsModelRef\.current\(repoId, ggufFilename, meta\.loadId\)/,
+ );
+ assert.match(source, /if \(busyRef\.current !== null\) return;/);
+ assert.match(
+ source,
+ /\/\*\* Start a pick that lost the race[\s\S]*?const replayQueuedTtsPick = useCallback/,
+ );
+ // Still single-flight, but the loser is queued rather than dropped: a pick arriving
+ // while a cancelled load settles used to vanish, and the route effect had already
+ // cleared ?model=, so nothing retried it.
+ assert.match(
+ source,
+ /if \(ttsLoadInFlight\.current\) \{\s*pendingRoutedTtsPick\.current = \{ repoId, ggufFilename, loadId \};\s*return;\s*\}/,
+ );
+ assert.match(
+ source,
+ // Replayed only while Audio is visible, and again when it becomes visible. Replaying
+ // unconditionally started a load with activeRef already false, which the deactivation
+ // effect had already stopped watching, so a hidden page could replace Chat's model.
+ /if \(activeRef\.current\) replayQueuedTtsPick\(\);/,
+ );
+});
+
+test("managed completion loads the exact GGUF only when Audio is active and idle", () => {
+ assert.match(
+ source,
+ /onReady: \(\) => \{[\s\S]*if \(!active \|\| busyRef\.current !== null\)[\s\S]*stagedTtsLoadDeferred\.current = true/,
+ );
+ assert.match(
+ source,
+ /loadTtsModelRef\.current\(pending\.repoId, pending\.ggufFilename\)/,
+ );
+ assert.match(
+ source,
+ /!active \|\|[\s\S]*busy !== null \|\|[\s\S]*!stagedTtsLoadDeferred\.current/,
+ );
+});
+
+test("switching to Transcribe invalidates a pending staged TTS auto-load", () => {
+ assert.match(
+ source,
+ /if \(nextMode === "transcribe"\) invalidatePendingStagedTts\(\)/,
+ );
+ assert.match(
+ source,
+ /stagedTtsLoadIsOwned\([\s\S]*pending\.generation[\s\S]*stagedTtsGeneration\.current[\s\S]*modeRef\.current/,
+ );
+ assert.match(
+ source,
+ /if \(nextMode === mode\)[\s\S]*return true;[\s\S]*if \(!canTransitionAudioMode\(busyRef\.current\)\)[\s\S]*return false;[\s\S]*if \(nextMode === "transcribe"\) invalidatePendingStagedTts\(\)/,
+ "a rejected mode switch must not discard the still-owned staged load",
+ );
+});
+
+test("a GGUF forwarded from Chat enters the managed staging path", () => {
+ assert.match(
+ source,
+ /ggufFilename: routeSearch\.quant \?\? undefined,[\s\S]*isDownloaded: routeSearch\.quant \? false : undefined/,
+ );
+});
+
+test("Mac sibling inspection reserves the lifecycle slot before awaiting inventory", () => {
+ assert.match(
+ source,
+ /ttsInspectionGeneration\.current = selectionGeneration;[\s\S]*busyRef\.current = "loading";[\s\S]*setBusy\("loading"\);[\s\S]*await listGgufVariants/,
+ );
+});
diff --git a/studio/frontend/tests/chat-model-residency.test.ts b/studio/frontend/tests/chat-model-residency.test.ts
index 0042de30cfa..e7f3891a3bb 100644
--- a/studio/frontend/tests/chat-model-residency.test.ts
+++ b/studio/frontend/tests/chat-model-residency.test.ts
@@ -128,7 +128,11 @@ test("the picker's Loaded badge asks residency, not the selection", () => {
),
"utf8",
);
- assert.match(pickers, /const loadedModelId = chatModelLoaded\(\{/);
+ assert.match(pickers, /const chatLoadedModelId = chatModelLoaded\(\{/);
+ assert.match(
+ pickers,
+ /const loadedModelId = loadedModelIdOverride \?\? chatLoadedModelId/,
+ );
assert.match(pickers, /residentCheckpoint,/);
assert.doesNotMatch(
pickers,
diff --git a/studio/frontend/tests/model-row-owner.test.ts b/studio/frontend/tests/model-row-owner.test.ts
index ba6c26e0b6a..ea5fc299064 100644
--- a/studio/frontend/tests/model-row-owner.test.ts
+++ b/studio/frontend/tests/model-row-owner.test.ts
@@ -18,6 +18,7 @@ test("unsloth is the owner whose prefix rows hide", () => {
);
// Case as the Hub listing returns it.
assert.equal(isUnslothOwner("Unsloth"), true);
+ assert.equal(isUnslothOwner("unslothai"), true);
});
test("other owners keep their prefix", () => {
diff --git a/studio/frontend/tests/recommended-curated-row-metadata.test.ts b/studio/frontend/tests/recommended-curated-row-metadata.test.ts
index 26ae9d24451..fb018d7f8bd 100644
--- a/studio/frontend/tests/recommended-curated-row-metadata.test.ts
+++ b/studio/frontend/tests/recommended-curated-row-metadata.test.ts
@@ -184,7 +184,12 @@ test("the search list is built from the seeds as well as the listing pool", () =
test("row meta falls back to the curated seeds", () => {
const text = declarationText("recommendedMeta");
- assert.match(text, /recommendedSearch\.results\s*,\s*\.\.\.catalogSeedRows/);
+ // Ordered: seeds behind the listing, community last. A community row ahead of the seeds
+ // would let a metadata-poor listing row shadow a curated one, and the map keeps the first.
+ assert.match(
+ text,
+ /recommendedSearch\.results\s*,\s*\.\.\.catalogSeedRows\s*,\s*\.\.\.communityBrowse\.results/,
+ );
// Listing first, and the first entry per id wins.
assert.match(text, /if\s*\(map\.has\(r\.id\)\)\s*continue;/);
});
diff --git a/studio/frontend/tests/sidebar-nav-migration.test.ts b/studio/frontend/tests/sidebar-nav-migration.test.ts
index eb766cb49ee..5b6bf09987e 100644
--- a/studio/frontend/tests/sidebar-nav-migration.test.ts
+++ b/studio/frontend/tests/sidebar-nav-migration.test.ts
@@ -38,18 +38,62 @@ const shippedLayouts: SidebarNavItemPref[][] = [
{ id: "recipes", pinned: false },
{ id: "export", pinned: false },
],
+ [
+ { id: "hub", pinned: true },
+ { id: "projects", pinned: true },
+ { id: "images", pinned: true },
+ { id: "video", pinned: false },
+ { id: "train", pinned: true },
+ { id: "recipes", pinned: false },
+ { id: "export", pinned: false },
+ { id: "api", pinned: false },
+ ],
];
test("every previously shipped sidebar adopts the current default", () => {
for (const sidebarNav of shippedLayouts) {
const customization = sanitizeCustomization({ sidebarNav });
assert.deepEqual(
- migrateShippedSidebarNavDefault(customization, 4, 5).sidebarNav,
+ migrateShippedSidebarNavDefault(customization, 4, 6).sidebarNav,
DEFAULT_CUSTOMIZATION.sidebarNav,
);
}
});
+test("the untouched pre-Audio version-5 sidebar adopts the Audio-aware default", () => {
+ const customization = sanitizeCustomization({
+ sidebarNav: shippedLayouts[3],
+ });
+ assert.deepEqual(
+ migrateShippedSidebarNavDefault(customization, 5, 6).sidebarNav,
+ DEFAULT_CUSTOMIZATION.sidebarNav,
+ );
+});
+
+test("a customized version-5 sidebar keeps its order and only gains Audio", () => {
+ const customizedV5: SidebarNavItemPref[] = [
+ { id: "projects", pinned: true },
+ { id: "hub", pinned: true },
+ { id: "train", pinned: true },
+ { id: "images", pinned: true },
+ { id: "video", pinned: false },
+ { id: "recipes", pinned: true },
+ { id: "export", pinned: false },
+ { id: "api", pinned: false },
+ ];
+ const customization = sanitizeCustomization({ sidebarNav: customizedV5 });
+
+ assert.strictEqual(
+ migrateShippedSidebarNavDefault(customization, 5, 6),
+ customization,
+ );
+ assert.deepEqual(
+ customization.sidebarNav.map((item) => item.id),
+ [...customizedV5.map((item) => item.id), "audio"],
+ );
+ assert.equal(customization.sidebarNav.at(-1)?.pinned, false);
+});
+
test("a user-arranged sidebar survives the migration", () => {
const customization = sanitizeCustomization({
sidebarNav: DEFAULT_CUSTOMIZATION.sidebarNav.map((item) =>
@@ -57,7 +101,7 @@ test("a user-arranged sidebar survives the migration", () => {
),
});
assert.strictEqual(
- migrateShippedSidebarNavDefault(customization, 4, 5),
+ migrateShippedSidebarNavDefault(customization, 4, 6),
customization,
);
});
@@ -67,7 +111,7 @@ test("a shipped-looking layout chosen after migration is preserved", () => {
sidebarNav: shippedLayouts[2],
});
assert.strictEqual(
- migrateShippedSidebarNavDefault(customization, 5, 5),
+ migrateShippedSidebarNavDefault(customization, 6, 6),
customization,
);
});
diff --git a/studio/frontend/tests/stt-download-mirror-policy.test.ts b/studio/frontend/tests/stt-download-mirror-policy.test.ts
new file mode 100644
index 00000000000..2687e00292c
--- /dev/null
+++ b/studio/frontend/tests/stt-download-mirror-policy.test.ts
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+const source = readFileSync(
+ new URL(
+ "../src/features/settings/lib/stt-download-mirror.ts",
+ import.meta.url,
+ ),
+ "utf8",
+);
+
+test("an adopted STT transfer keeps progress and merges its Voice owner", () => {
+ assert.match(
+ source,
+ /const resolvedEngine = options\.engine \?\? sttEngineFor\(model\);[\s\S]*const key = trackerKey\(model, resolvedEngine\);[\s\S]*if \(trackers\.has\(key\)\) \{[\s\S]*warmSelectedVoiceModelOnComplete\.set\(key, true\);[\s\S]*return;[\s\S]*\}/,
+ );
+});
+
+test("tracking-only STT jobs never invoke the Voice-owned completion load", () => {
+ assert.match(
+ source,
+ /const key = trackerKey\(model, engine\);[\s\S]*const shouldWarmVoiceModel =[\s\S]*warmSelectedVoiceModelOnComplete\.get\(key\) \?\? true;[\s\S]*warmSelectedVoiceModelOnComplete\.delete\(key\);[\s\S]*shouldWarmVoiceModel &&[\s\S]*outcome === "complete"/,
+ );
+});
+
+test("non-default STT engines have independent jobs", () => {
+ assert.match(
+ source,
+ /engine && engine !== "transformers" \? `\$\{engine\}:\$\{model\}` : model/,
+ );
+ assert.match(source, /cancelSttDownload\(model, resolvedEngine\)/);
+ assert.match(
+ source,
+ /engine === undefined \|\| engine === "transformers" \? model : undefined/,
+ );
+ assert.match(source, /sttEngineStatusFor\(status, model, engine\)/);
+});
+
+test("an explicit Transformers transfer keeps its serving engine", () => {
+ assert.match(
+ source,
+ /const resolvedEngine = options\.engine \?\? sttEngineFor\(model\)/,
+ );
+ assert.match(source, /cancelSttDownload\(model, resolvedEngine\)/);
+ assert.match(source, /poll\(model, startedAt, resolvedEngine\)/);
+ assert.doesNotMatch(
+ source,
+ /options\.engine === "transformers" \? undefined/,
+ );
+});
diff --git a/tests/studio/test_audio_snapshot_download_targets.py b/tests/studio/test_audio_snapshot_download_targets.py
new file mode 100644
index 00000000000..674496920d0
--- /dev/null
+++ b/tests/studio/test_audio_snapshot_download_targets.py
@@ -0,0 +1,126 @@
+# 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 paths must fetch Spark-TTS into the shared HF cache, never a relative dir.
+
+``snapshot_download(repo, local_dir = "Spark-TTS-0.5B")`` resolves against the process
+CWD. Under the desktop shell that is ``studio/src-tauri``, so ~1.5 GB of model landed
+inside the Tauri crate, the dev watcher rebuilt on every downloaded file and killed the
+backend mid-load. It also bypasses hf_cache_settings, so the copy is invisible to the
+inventory and re-downloads once per CWD -- while the cached-start path (``local_files_only``)
+was already reading the cache.
+
+Parsed rather than string-matched: reformatting this call should not fail the suite,
+only reintroducing a download target outside the cache should.
+"""
+
+from __future__ import annotations
+
+import ast
+import os
+from pathlib import Path
+
+import pytest
+
+
+def _find_repo_root() -> Path | None:
+ env = os.environ.get("UNSLOTH_REPO_ROOT")
+ if env:
+ p = Path(env).resolve()
+ if (p / "studio" / "backend").is_dir():
+ return p
+ here = Path(__file__).resolve()
+ for parent in (here, *here.parents):
+ if (parent / "studio" / "backend").is_dir():
+ return parent
+ return None
+
+
+_REPO_ROOT = _find_repo_root()
+if _REPO_ROOT is None:
+ pytest.skip(
+ "Could not locate studio/backend. Set UNSLOTH_REPO_ROOT or run from "
+ "the repository checkout.",
+ allow_module_level = True,
+ )
+
+# Every module that fetches a Spark-TTS repo: TTS inference, the GGUF BiCodec decoder
+# and the trainer.
+_AUDIO_SOURCES = (
+ "studio/backend/core/inference/inference.py",
+ "studio/backend/core/inference/llama_cpp.py",
+ "studio/backend/core/training/trainer.py",
+)
+
+
+def _snapshot_download_calls(path: Path) -> list[ast.Call]:
+ tree = ast.parse(path.read_text(encoding = "utf-8"))
+ return [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Call)
+ and (
+ (isinstance(node.func, ast.Name) and node.func.id == "snapshot_download")
+ or (isinstance(node.func, ast.Attribute) and node.func.attr == "snapshot_download")
+ )
+ ]
+
+
+def _local_dir_arg(call: ast.Call) -> ast.expr | None:
+ for kw in call.keywords:
+ if kw.arg == "local_dir":
+ return kw.value
+ return None
+
+
+def _assignments(tree: ast.Module) -> dict[str, ast.expr]:
+ out: dict[str, ast.expr] = {}
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Assign):
+ for target in node.targets:
+ if isinstance(target, ast.Name):
+ out[target.id] = node.value
+ return out
+
+
+def _is_anchored(
+ expr: ast.expr,
+ assigned: dict[str, ast.expr],
+ depth: int = 0,
+) -> bool:
+ """True when the target is built from an explicit base rather than the CWD."""
+ if depth > 3:
+ return False
+ if isinstance(expr, ast.Name):
+ source = assigned.get(expr.id)
+ return source is not None and _is_anchored(source, assigned, depth + 1)
+ if isinstance(expr, ast.Call):
+ func = expr.func
+ # os.path.join(base, ...) / Path(base) / str(base) anchor to something named.
+ if isinstance(func, ast.Attribute):
+ # ...but a repo id sliced into a bare name does not.
+ return func.attr not in ("split", "rsplit")
+ return True
+ return False
+
+
[email protected]("rel", _AUDIO_SOURCES)
+def test_audio_snapshot_downloads_target_the_hf_cache(rel: str) -> None:
+ path = _REPO_ROOT / rel
+ assert path.is_file(), f"missing {rel}"
+
+ tree = ast.parse(path.read_text(encoding = "utf-8"))
+ assigned = _assignments(tree)
+
+ offenders = []
+ for call in _snapshot_download_calls(path):
+ local_dir = _local_dir_arg(call)
+ if local_dir is None:
+ continue
+ if not _is_anchored(local_dir, assigned):
+ offenders.append(local_dir.lineno)
+
+ assert not offenders, (
+ f"{rel} passes a CWD-relative local_dir to snapshot_download at line(s) "
+ f"{offenders}. Drop local_dir so the repo lands in the shared HF cache."
+ )
diff --git a/tests/studio/test_desktop_reliability_frontend_contract.py b/tests/studio/test_desktop_reliability_frontend_contract.py
index a63c8860214..ed89f132b97 100644
--- a/tests/studio/test_desktop_reliability_frontend_contract.py
+++ b/tests/studio/test_desktop_reliability_frontend_contract.py
@@ -737,7 +737,9 @@ def test_media_pages_clear_the_custom_titlebar():
"""The chat-style layout gives the media pages no outer inset, so each applies its own."""
root = ROOT_ROUTE.read_text(encoding = "utf-8")
- assert "const isChatLike = isChatRoute || isImagesRoute || isVideoRoute;" in root
+ assert (
+ "const isChatLike = isChatRoute || isImagesRoute || isVideoRoute || isAudioRoute;" in root
+ )
for page in (IMAGES_PAGE, VIDEO_PAGE):
shell = page.read_text(encoding = "utf-8").split('"diffusion-surface', 1)[1].split(">", 1)[0]
assert "pt-[var(--studio-content-top-inset,0px)]" in shell, page.name
diff --git a/tests/studio/test_model_picker_catalog_first_paint.py b/tests/studio/test_model_picker_catalog_first_paint.py
index 2e8956e9628..d39b34e2ac1 100644
--- a/tests/studio/test_model_picker_catalog_first_paint.py
+++ b/tests/studio/test_model_picker_catalog_first_paint.py
@@ -34,8 +34,10 @@ def test_curated_catalog_becomes_rows_without_a_request():
# Chat has no catalog: leave it on the listing.
assert "if (!task) return [];" in seed
# Same format policy as the listing rows, so nothing vanishes when one lands.
- assert "isRecommendableFormat(id, isG, isMac)" in seed
+ assert "taskCatalogFormatMatches(" in seed
assert "matchesFormatFilter(id, isG, formatFilter)" in seed
+ # The recommendable gate now runs in `keep`, over seeds and listing rows alike.
+ assert "isRecommendable: isRecommendableFormat(r.id, r.isGguf, isMac)," in source
# Device fit reads the catalog size, not an id "<n>B" guess.
assert "curatedSizeBytes: catalog ? curatedSizeBytesFor(id, catalog) : undefined," in seed
@@ -48,7 +50,7 @@ def test_listing_takes_over_each_id_once_it_reports_it():
# orderRecommendedRows hands a seed over only to a row that survived `keep`:
# keying on the raw result set dropped curated rows the filters rejected.
- assert "return orderRecommendedRows({" in rows
+ assert "orderRecommendedRows({" in rows
assert "seeds: catalogSeedRows," in rows
assert "results: recommendedSearch.results," in rows
assert "keep,\n deviceFiltered,\n fits,\n });" in rows
@@ -57,10 +59,10 @@ def test_listing_takes_over_each_id_once_it_reports_it():
def test_bottom_spinner_shows_only_while_a_page_is_in_flight():
source = _source()
- start = source.index("{recommendedSearch.hasMore && (")
+ start = source.index("{recommendedHasMore && (")
block = source[start : start + 700]
# The sentinel still mounts on hasMore, so paging continues...
assert '<div ref={recommendedSentinelRef} className="h-px" />' in block
# ...but the spinner is gated on the in-flight flag.
- assert "{recommendedSearch.isLoadingMore ? (" in block
+ assert "{recommendedIsLoadingMore ? (" in block
diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.py
index 8a4fd5ca7a2..1602c90d1e0 100644
--- a/tests/studio/test_model_picker_contracts.py
+++ b/tests/studio/test_model_picker_contracts.py
@@ -407,7 +407,7 @@ def test_variant_expander_refreshes_after_delete():
def test_local_picker_rows_require_chat_capability():
"""Local inventory rows can be classified non-chat (canChat false, e.g."""
src = _read("features/model-picker/inventory/use-chat-picker-inventory.ts")
- memo = re.search(r"const localModels = useMemo\(.*?\[inventory\.localRows\]", src, re.S)
+ memo = re.search(r"const localModels = useMemo\(.*?\[inventory\.localRows", src, re.S)
assert memo, "localModels memo not found"
assert "row.capabilities.canChat" in memo.group(0)
@@ -1564,12 +1564,14 @@ def test_local_model_sections_respect_the_task_filter():
for memo in ("sortedLmStudio", "sortedLocalDir", "sortedCustomFolderModels"):
block = re.search(rf"const {memo} = useMemo\(.*?\n \);", src, re.S)
assert block, f"{memo} not found"
- assert "passesTaskGate(m.task" in block.group(0), f"{memo} does not apply the task gate"
+ assert re.search(
+ r"passesTaskGate\(\s*m\.task", block.group(0)
+ ), f"{memo} does not apply the task gate"
def test_chat_picker_routes_diffusion_picks_to_their_page():
- """Chat cannot load a diffusion model. Rather than hiding an on-device one or letting
- it 400, the unfiltered picker routes the pick to the Images/Video page, which loads it."""
+ """Chat cannot load a diffusion or audio model. Rather than hiding an on-device one or
+ letting it 400, the unfiltered picker routes the pick to the page that loads it."""
src = _read("features/model-picker/components/model-selector/pickers.tsx")
gate = re.search(r"function passesTaskGate\(.*?\n\}", src, re.S)
assert gate, "passesTaskGate not found"
@@ -1578,7 +1580,7 @@ def test_chat_picker_routes_diffusion_picks_to_their_page():
wrapper = re.search(r"const onSelect = useCallback\(.*?\n \);", src, re.S)
assert wrapper, "the routing wrapper around onSelect is missing"
body = wrapper.group(0)
- assert "diffusionPageForTask" in body and "navigateToPage" in body
+ assert "mediaPageForTask" in body and "navigateToPage" in body
# Task-scoped pickers (already on those pages) must select normally.
assert "if (!task)" in body
@@ -1637,7 +1639,9 @@ def test_on_device_rows_carry_the_task_the_pickers_filter_on():
conv = _read("features/model-picker/inventory/use-chat-picker-inventory.ts")
assert conv.count("task: row.task ?? null,") == 3, "a picker converter drops the task"
# A generation-task row is not a chat row, so the chat-only guard must not hide it from the pickers that can load it.
- assert "row.capabilities.canChat || studioPageForTask(row.task) !== undefined" in conv
+ assert re.search(
+ r"row\.capabilities\.canChat \|\|\s*studioPageForTask\(row\.task\) !== undefined", conv
+ )
def test_local_diffusion_routing_is_keyed_by_the_id_the_row_selects():
@@ -1648,7 +1652,9 @@ def test_local_diffusion_routing_is_keyed_by_the_id_the_row_selects():
block = re.search(r"const diffusionTaskById = useMemo\(.*?\n \}, \[", src, re.S)
assert block, "diffusionTaskById not found"
body = block.group(0)
- assert "put(m.id, m.task);" in body and "put(m.model_id, m.task);" in body
+ assert re.search(r"put\(m\.id, m\.task[,)]", body) and re.search(
+ r"put\(m\.model_id, m\.task[,)]", body
+ )
def test_a_staged_download_that_never_starts_clears_the_queue():
diff --git a/tests/studio/test_spark_tts_tokenizer_subfolder.py b/tests/studio/test_spark_tts_tokenizer_subfolder.py
new file mode 100644
index 00000000000..9b861840200
--- /dev/null
+++ b/tests/studio/test_spark_tts_tokenizer_subfolder.py
@@ -0,0 +1,66 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Spark-TTS's tokenizer lives under LLM/, so the pre-detect load needs the subfolder.
+
+unsloth/Spark-TTS-0.5B keeps only BiCodec/, config.yaml, src/ and wav2vec2-* at its repo
+root. AutoTokenizer on the root finds no vocab and raises "Couldn't instantiate the
+backend tokenizer ... You need to have sentencepiece or tiktoken installed", which sends
+the reader after a dependency that is installed and irrelevant. _load_model already reads
+weights from LLM/; the tokenizer pre-detect has to agree.
+
+Source-level: the real call needs the network and a 2 GB download.
+"""
+
+from __future__ import annotations
+
+import os
+import typing
+from pathlib import Path
+
+import pytest
+
+
+def _find_repo_root() -> Path | None:
+ env = os.environ.get("UNSLOTH_REPO_ROOT")
+ if env:
+ p = Path(env).resolve()
+ if (p / "studio" / "backend").is_dir():
+ return p
+ here = Path(__file__).resolve()
+ for parent in (here, *here.parents):
+ if (parent / "studio" / "backend").is_dir():
+ return parent
+ return None
+
+
+_REPO_ROOT = _find_repo_root()
+if _REPO_ROOT is None:
+ pytest.skip("Could not locate studio/backend.", allow_module_level = True)
+
+
+def _helper():
+ """Exec just the helper: importing trainer.py pulls in the whole torch stack."""
+ src = (_REPO_ROOT / "studio/backend/core/training/trainer.py").read_text(encoding = "utf-8")
+ start = src.index("def _spark_tts_tokenizer_kwargs")
+ end = src.index("class UnslothTrainer:")
+ namespace: dict = {"os": os, "Optional": typing.Optional}
+ exec(src[start:end], namespace)
+ return namespace["_spark_tts_tokenizer_kwargs"]
+
+
+def test_a_spark_repo_root_reads_the_llm_subfolder():
+ assert _helper()("bicodec", "unsloth/Spark-TTS-0.5B") == {"subfolder": "LLM"}
+
+
+ "lookup_name",
+ ["Spark-TTS-0.5B/LLM", r"C:\models\Spark-TTS-0.5B\LLM", "/srv/Spark-TTS-0.5B/LLM"],
+)
+def test_a_name_already_pointing_at_llm_is_left_alone(lookup_name: str):
+ assert _helper()("bicodec", lookup_name) == {}
+
+
[email protected]("audio_type", ["snac", "csm", "dac", "whisper", "audio_vlm", None])
+def test_every_other_codec_is_untouched(audio_type):
+ assert _helper()(audio_type, "unsloth/orpheus-3b-0.1-ft") == {}