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: stop chat from auto-loading a TTS model (#9813)

Nilay33525a0c07be
diff --git a/studio/backend/hub/schemas/inventory.py b/studio/backend/hub/schemas/inventory.py
index d787d6149a7..db8f95ad7f7 100644
--- a/studio/backend/hub/schemas/inventory.py
+++ b/studio/backend/hub/schemas/inventory.py
@@ -161,6 +161,10 @@ class LocalModelInfo(BaseModel):
"those lists."
),
)
+ audio_type: Optional[str] = Field(
+ None,
+ description = "Detected output-audio codec used to decide whether Audio can run the row",
+ )
base_model: Optional[str] = Field(
None,
description = "Base model from adapter_config.json when this is an adapter",
@@ -239,6 +243,7 @@ class CachedRepoBase(BaseModel):
# Inferred pipeline task ("text-to-image" / "text-to-video" / a chat task / None). The task-scoped pickers filter On
# Device rows on it and the chat picker routes a diffusion pick by it, so a row without one is dropped from those lists.
task: Optional[str] = None
+ audio_type: Optional[str] = None
class CachedGgufRepo(CachedRepoBase):
diff --git a/studio/backend/hub/services/models/cache_inventory.py b/studio/backend/hub/services/models/cache_inventory.py
index d2e27bd651c..512345a2274 100644
--- a/studio/backend/hub/services/models/cache_inventory.py
+++ b/studio/backend/hub/services/models/cache_inventory.py
@@ -46,7 +46,12 @@ from hub.services.models.common import (
# ``utils`` (not ``utils.models``) to avoid the eager model-config/checkpoint
# imports in ``utils/models/__init__.py``.
from utils.paths.path_utils import is_appledouble_metadata
-from utils.hidden_models import is_curated_stt_repo_id, is_hidden_model
+from utils.audio_tokens import detect_local_tts_audio_type
+from utils.hidden_models import (
+ is_curated_stt_repo_id,
+ is_curated_tts_repo_id,
+ is_hidden_model,
+)
logger = get_logger(__name__)
@@ -378,6 +383,7 @@ def _cache_inventory_fields(
hidden_infra: bool = False,
companion: bool = False,
stt_only: bool = False,
+ tts_only: bool = False,
) -> dict:
"""Load identity plus the capability block for one cache row.
@@ -426,6 +432,11 @@ def _cache_inventory_fields(
if stt_only or is_curated_stt_repo_id(repo_id):
capabilities["supports_vision"] = False
capabilities["can_chat"] = False
+ # Same rule for the speech-emitting half of the Audio page. The codec probe in
+ # _local_transformers_can_chat covers uncurated safetensors copies; a GGUF repo ships
+ # no tokenizer_config to probe, so the curated ids answer for those.
+ if tts_only or is_curated_tts_repo_id(repo_id):
+ 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
@@ -600,15 +611,26 @@ def _scan_cached_gguf(
key = repo_id.lower()
existing = seen_lower.get(key)
last_modified = _repo_gguf_last_modified(repo_info)
+ row_task = _cached_row_task(
+ repo_info,
+ gguf = True,
+ selected = gguf_identity.load_snapshot or gguf_snapshot,
+ )
+ row_audio_type = None
+ if row_task == "text-to-speech":
+ try:
+ from hub.services.models import catalog_classification
+ row_audio_type = catalog_classification._repo_gguf_audio_type(
+ repo_info, gguf_identity.load_snapshot or gguf_snapshot
+ )
+ except Exception:
+ pass
row = {
"repo_id": repo_id,
"size_bytes": max(total_size, variant_state_size),
"cache_path": str(repo_info.repo_path),
- "task": _cached_row_task(
- repo_info,
- gguf = True,
- selected = gguf_identity.load_snapshot or gguf_snapshot,
- ),
+ "task": row_task,
+ "audio_type": row_audio_type,
"partial": partial,
# A marker-only sibling moves neither size nor mtime.
"has_variant_state": has_variant_state,
@@ -637,6 +659,7 @@ def _scan_cached_gguf(
repo_info = repo_info,
# Visible infra variants remain management-only.
hidden_infra = is_hidden_infra,
+ tts_only = row_task == "text-to-speech",
)
)
# Only the winning cache root loads, so the loser's vision flag must not carry over.
@@ -973,6 +996,9 @@ def _cached_model_local_metadata(repo_path: Path, snapshot: Optional[Path] = Non
config = _read_json_object(snapshot / "config.json")
if _is_whisper_model_config(config):
result["_hidden_stt"] = True
+ tts_audio_type = detect_local_tts_audio_type(snapshot)
+ if tts_audio_type is not None:
+ result["_tts_audio_type"] = tts_audio_type
quant_method = (
config.get("quantization_config", {}).get("quant_method")
if isinstance(config.get("quantization_config"), dict)
@@ -1065,6 +1091,8 @@ def _scan_cached_models(
else _cached_model_local_metadata(repo_path, load_snapshot)
)
is_whisper_stt = local_metadata.pop("_hidden_stt", False)
+ tts_audio_type = local_metadata.pop("_tts_audio_type", None)
+ is_tts = tts_audio_type is not None
# Scoped to the row's snapshot, so an incomplete newer revision cannot flip can_chat.
download_partial = hf_cache_scan.is_snapshot_partial(
"model",
@@ -1096,7 +1124,9 @@ def _scan_cached_models(
if is_whisper_stt
else (
"text-to-speech"
- if local_metadata.get("pipeline_tag") == "text-to-speech"
+ # The probe answers for a repo whose card says nothing, so the
+ # Audio page, which selects by task, still lists it.
+ if is_tts or local_metadata.get("pipeline_tag") == "text-to-speech"
else _cached_row_task(repo_info, gguf = False, selected = load_snapshot)
)
)
@@ -1112,6 +1142,7 @@ def _scan_cached_models(
"size_bytes": payload.size_bytes,
"cache_path": str(repo_info.repo_path),
"task": row_task,
+ "audio_type": tts_audio_type,
"partial": snapshot_partial,
"partial_transport": (
hf_cache_scan.partial_transport_for(
@@ -1160,6 +1191,7 @@ def _scan_cached_models(
hidden_infra = is_hidden_infra,
companion = bool(row["companion"]),
stt_only = bool(is_whisper_stt),
+ tts_only = is_tts,
)
)
if _prefer_cache_row(row, existing):
diff --git a/studio/backend/hub/services/models/catalog_classification.py b/studio/backend/hub/services/models/catalog_classification.py
index cc592577774..792838006b2 100644
--- a/studio/backend/hub/services/models/catalog_classification.py
+++ b/studio/backend/hub/services/models/catalog_classification.py
@@ -43,6 +43,10 @@ _QWEN3_ASR_HINT = re.compile(
r"(?<![a-z0-9])qwen3[-_. ]*asr[-_. ]*(?:0[._]6|1[._]7)b(?![a-z0-9])",
re.IGNORECASE,
)
+_ORPHEUS_GGUF_HINT = re.compile(
+ r"(?<![a-z0-9])orpheus[-_. ]*3b(?![a-z0-9])",
+ re.IGNORECASE,
+)
def _is_h3_bundle_gguf_hint(hint: Optional[str]) -> bool:
@@ -96,6 +100,10 @@ def _arch_to_task(arch: Optional[str], name_hints: tuple[Optional[str], ...] = (
_QWEN3_ASR_HINT.search(str(hint)) for hint in name_hints if hint
):
return "automatic-speech-recognition"
+ if normalized == "llama" and any(
+ _ORPHEUS_GGUF_HINT.search(str(hint)) for hint in name_hints if hint
+ ):
+ return _SPEECH_TASK
if normalized in _PLACEHOLDER_DIFFUSION_GGUF_ARCHS:
from core.inference.video_families import detect_video_family
@@ -156,6 +164,22 @@ def _arch_to_task(arch: Optional[str], name_hints: tuple[Optional[str], ...] = (
return "text-generation"
+def _arch_to_audio_type(
+ arch: Optional[str], name_hints: tuple[Optional[str], ...] = ()
+) -> Optional[str]:
+ """Decoder provenance for a GGUF classified as speech."""
+ if arch is None:
+ return None
+ normalized = arch.strip().lower()
+ if normalized == "llama" and any(
+ _ORPHEUS_GGUF_HINT.search(str(hint)) for hint in name_hints if hint
+ ):
+ return "snac"
+ if is_speech_gguf_architecture(normalized):
+ return "csm"
+ return None
+
+
def _is_trailing_split_shard(name: str) -> bool:
try:
from utils.models.model_config import _GGUF_SPLIT_FILE_RE
@@ -246,6 +270,36 @@ def _repo_gguf_task(repo_info, selected: Optional[Path] = None) -> Optional[str]
return None
+def _gguf_path_audio_type(
+ path: str | Path, id_hints: tuple[Optional[str], ...] = ()
+) -> Optional[str]:
+ model_path = Path(path)
+ try:
+ paths = (
+ [model_path]
+ if model_path.suffix.lower() == ".gguf" and model_path.is_file()
+ else _iter_gguf_paths(model_path)
+ )
+ for gguf_path in paths:
+ audio_type = _arch_to_audio_type(
+ _gguf_architecture(str(gguf_path)),
+ name_hints = id_hints + (gguf_path.name,),
+ )
+ if audio_type is not None:
+ return audio_type
+ except Exception:
+ return None
+ return None
+
+
+def _repo_gguf_audio_type(repo_info, selected: Optional[Path] = None) -> Optional[str]:
+ repo_id = getattr(repo_info, "repo_id", None)
+ try:
+ return _gguf_path_audio_type(selected or Path(repo_info.repo_path), (repo_id,))
+ except Exception:
+ return None
+
+
def _gguf_path_task(path: str | Path, id_hints: tuple[Optional[str], ...] = ()) -> Optional[str]:
model_path = Path(path)
try:
@@ -327,6 +381,28 @@ def _local_model_task(model) -> Optional[str]:
return "text-to-image"
+def _local_model_audio_type(model) -> Optional[str]:
+ path = model.path
+ if model.model_format == "gguf" or Path(path).suffix.lower() == ".gguf":
+ return _gguf_path_audio_type(path, (model.model_id, model.display_name, model.id))
+ try:
+ from utils.audio_tokens import detect_local_tts_audio_type
+ return detect_local_tts_audio_type(path)
+ except Exception:
+ return None
+
+
+def _local_model_classification(model) -> tuple[Optional[str], Optional[str]]:
+ """Return picker task and decoder provenance from one local-row probe."""
+ task = _local_model_task(model)
+ audio_type = _local_model_audio_type(model) if task is None or task == _SPEECH_TASK else None
+ if task is None and audio_type is not None:
+ from utils.audio_tokens import is_tts_audio_type
+ if is_tts_audio_type(audio_type):
+ task = _SPEECH_TASK
+ return task, audio_type
+
+
def _local_is_diffusers(model) -> bool:
try:
path = Path(model.path)
diff --git a/studio/backend/hub/services/models/common.py b/studio/backend/hub/services/models/common.py
index 194b8febcc1..d50a5644515 100644
--- a/studio/backend/hub/services/models/common.py
+++ b/studio/backend/hub/services/models/common.py
@@ -26,6 +26,7 @@ from hub.utils.gguf import (
is_mtp_drafter_path as _is_mtp_drafter_path,
)
from hub.utils.paths import is_valid_repo_id as _is_valid_repo_id
+from utils.audio_tokens import detect_local_tts_audio_type
from utils.paths.path_utils import drop_appledouble_metadata, is_appledouble_metadata
ModelType = Literal["text", "vision", "audio", "embeddings"]
@@ -308,6 +309,12 @@ def _local_transformers_can_chat(path: Path) -> Optional[bool]:
if not _safe_is_dir(path):
return None
+ # Before every architecture test below: a TTS model is an ordinary causal LM wearing
+ # a codec vocabulary (Orpheus is LlamaForCausalLM), so the suffix rules answer True
+ # and auto-load, which prefers the smallest, then picks it.
+ if detect_local_tts_audio_type(path) is not None:
+ return False
+
# SentenceTransformers exports carry this even when the config names a
# broadly reusable encoder class.
try:
diff --git a/studio/backend/hub/services/models/local_inventory.py b/studio/backend/hub/services/models/local_inventory.py
index 9f30f0dbcde..21b5a458d9b 100644
--- a/studio/backend/hub/services/models/local_inventory.py
+++ b/studio/backend/hub/services/models/local_inventory.py
@@ -953,10 +953,18 @@ async def list_local_models_response(models_dir: str = "./models") -> LocalModel
# Module-qualified for the same reason as _cached_row_task: binding the bare
# name re-points a load that resolved to routes.models before the move.
from hub.services.models import catalog_classification
- models = [
- model.model_copy(update = {"task": catalog_classification._local_model_task(model)})
- for model in response.models
- ]
+
+ models = []
+ for model in response.models:
+ task, audio_type = catalog_classification._local_model_classification(model)
+ models.append(
+ model.model_copy(
+ update = {
+ "task": task,
+ "audio_type": audio_type,
+ }
+ )
+ )
return response.model_copy(update = {"models": models})
except Exception as e: # noqa: BLE001 -- classification never breaks the listing
logger.warning("Could not classify local model tasks: %s", e)
diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.py
index 2770bf57ef9..f4ffdcec854 100644
--- a/studio/backend/hub/tests/test_model_services.py
+++ b/studio/backend/hub/tests/test_model_services.py
@@ -7232,6 +7232,33 @@ def test_local_inventory_classifies_off_the_event_loop(monkeypatch):
assert idents and loop_ident not in idents, "classification ran on the event loop thread"
+def test_local_inventory_derives_speech_task_from_filesystem_codec(monkeypatch):
+ """A renamed non-GGUF TTS checkpoint has no family hint, so its tokenizer
+ decoder is the only evidence that can place it in the Audio picker."""
+ from hub.services.models import local_inventory
+
+ model = SimpleNamespace(id = "renamed-checkpoint")
+ model.model_copy = lambda update: SimpleNamespace(id = model.id, **update)
+ response = SimpleNamespace(models = [model])
+ response.model_copy = lambda update: SimpleNamespace(models = update["models"])
+
+ async def scan(*_args):
+ return response
+
+ async def no_folders():
+ return []
+
+ monkeypatch.setattr(catalog_classification, "_local_model_task", lambda _row: None)
+ monkeypatch.setattr(catalog_classification, "_local_model_audio_type", lambda _row: "snac")
+ monkeypatch.setattr(local_inventory, "_scan_local_models_response", scan)
+ monkeypatch.setattr(local_inventory, "_load_custom_folders", no_folders)
+ monkeypatch.setattr(local_inventory, "_local_inventory_sources", lambda: ("roots",))
+ monkeypatch.setattr(local_inventory.hf_cache_scan, "hf_cache_scans_epoch", lambda: 0)
+
+ listed = asyncio.run(local_inventory.list_local_models_response("./renamed-tts-models"))
+ assert [(row.task, row.audio_type) for row in listed.models] == [("text-to-speech", "snac")]
+
+
def test_local_inventory_classifies_a_superseded_result_off_the_event_loop(monkeypatch):
"""The give-up path serves the freshest scan it has, and classifies it the same way."""
from hub.services.models import local_inventory
@@ -7381,6 +7408,49 @@ def test_cached_gguf_task_describes_the_revision_the_load_id_resolves_to(tmp_pat
assert row["task"] == "text-generation"
+def test_cached_community_orpheus_gguf_is_not_chat_loadable(tmp_path):
+ hub_cache = tmp_path / "hub"
+ repo_path = hub_cache / "models--QuantFactory--orpheus-3b-0.1-ft-GGUF"
+ snapshot = repo_path / "snapshots" / "revision"
+ gguf = snapshot / "orpheus-3b-0.1-ft-Q4_K_M.gguf"
+ _gguf_with_architecture(gguf, "llama")
+ (repo_path / "refs").mkdir(parents = True, exist_ok = True)
+ (repo_path / "refs" / "main").write_text("revision")
+
+ revision = SimpleNamespace(
+ snapshot_path = snapshot,
+ files = [
+ SimpleNamespace(
+ file_name = gguf.name,
+ size_on_disk = 64,
+ file_path = gguf,
+ blob_path = gguf,
+ )
+ ],
+ refs = {"main"},
+ commit_hash = "revision",
+ last_modified = 1.0,
+ size_on_disk = 64,
+ )
+ repo_info = SimpleNamespace(
+ repo_id = "QuantFactory/orpheus-3b-0.1-ft-GGUF",
+ repo_type = "model",
+ repo_path = repo_path,
+ revisions = [revision],
+ size_on_disk = 64,
+ last_accessed = 1.0,
+ last_modified = 1.0,
+ nb_files = 1,
+ )
+
+ rows = cache_inventory._scan_cached_gguf(
+ cache_scans = [SimpleNamespace(repos = [repo_info])], active_hub_cache = hub_cache
+ )
+ row = next(row for row in rows if row["repo_id"] == repo_info.repo_id)
+ assert row["task"] == "text-to-speech"
+ assert row["capabilities"]["can_chat"] is False
+
+
def test_every_row_key_the_scanner_emits_survives_the_response_schema():
"""``response_model`` silently DROPS any key the schema does not declare.
diff --git a/studio/backend/models/models.py b/studio/backend/models/models.py
index 4ae90080557..594f1c4a7dc 100644
--- a/studio/backend/models/models.py
+++ b/studio/backend/models/models.py
@@ -251,6 +251,10 @@ class LocalModelInfo(BaseModel):
"('text-to-image' for diffusion, 'text-generation' otherwise). Lets the "
"Images picker show only diffusion GGUFs.",
)
+ audio_type: Optional[str] = Field(
+ None,
+ description = "Detected output-audio codec used to decide whether Audio can run the row",
+ )
class LocalModelListResponse(BaseModel):
diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.py
index 72c14c12b73..2607f31b6d7 100644
--- a/studio/backend/routes/models.py
+++ b/studio/backend/routes/models.py
@@ -83,6 +83,7 @@ class CachedModelRepo(BaseModel):
last_modified: Optional[float] = None
# "text-to-image" for cached diffusers image repos; declared here or response_model drops it.
task: Optional[str] = None
+ audio_type: Optional[str] = None
# Snapshot incomplete (cancelled/partial download): the picker must not treat it as usable.
partial: Optional[bool] = None
# Diffusion-tagged repo with NO top-level model_index.json: needs from_single_file + a filename.
@@ -1204,7 +1205,20 @@ async def _shared_compat_local_inventory_scan(
# Tag each model with its task so the Images picker can filter to diffusion.
# Inside the shared flight so overlapping callers reuse one classified result
# instead of each repeating the GGUF header reads.
- return [m.model_copy(update = {"task": _local_model_task(m)}) for m in models]
+ classified = []
+ for model in models:
+ task = _local_model_task(model)
+ classified.append(
+ model.model_copy(
+ update = {
+ "task": task,
+ "audio_type": _catalog_classification._local_model_audio_type(model)
+ if task == "text-to-speech"
+ else None,
+ }
+ )
+ )
+ return classified
async def collect(
expected_epoch: int, custom_folders: List[dict], scan_sources: _CompatLocalInventorySources
diff --git a/studio/backend/tests/test_audio_token_detection.py b/studio/backend/tests/test_audio_token_detection.py
index 8276fcc0f2a..89df02ddfe2 100644
--- a/studio/backend/tests/test_audio_token_detection.py
+++ b/studio/backend/tests/test_audio_token_detection.py
@@ -8,12 +8,13 @@ from __future__ import annotations
import json
-from utils.models.model_config import _AUDIO_TOKEN_PATTERNS, is_audio_input_type
+from utils.audio_tokens import AUDIO_TOKEN_PATTERNS
+from utils.models.model_config import is_audio_input_type
def _classify(tokens: list[str]) -> str | None:
"""Mirror _check_token_patterns: first match in dict order wins."""
- for audio_type, check in _AUDIO_TOKEN_PATTERNS.items():
+ for audio_type, check in AUDIO_TOKEN_PATTERNS.items():
if check(tokens):
return audio_type
return None
@@ -227,21 +228,10 @@ 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,
- )
+ from utils.audio_tokens import AUDIO_TOKEN_MARKERS, 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",
- }
+ 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 = {
@@ -254,14 +244,14 @@ def test_every_pattern_has_a_marker_so_the_parse_can_be_skipped():
}
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|>"]))
+ 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(
+ 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)
+ 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):
diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.py
index decf5fdd2fc..55642391b06 100644
--- a/studio/backend/tests/test_cached_gguf_routes.py
+++ b/studio/backend/tests/test_cached_gguf_routes.py
@@ -3559,7 +3559,7 @@ def test_hub_cached_row_task_never_hides_a_row_when_classification_fails(monkeyp
def test_hub_local_rows_are_tagged_with_their_task():
- """/api/hub/local feeds the same pickers, and its rows were untagged too."""
+ """/api/hub/local feeds the same pickers, including decoder provenance."""
import inspect
from hub.schemas.inventory import LocalModelInfo
@@ -3567,8 +3567,10 @@ def test_hub_local_rows_are_tagged_with_their_task():
assert "task" in LocalModelInfo.model_fields
src = inspect.getsource(local_inventory.list_local_models_response)
- assert "_local_model_task" in src
- assert 'model_copy(update = {"task"' in src
+ assert "_local_model_classification" in src
+ compact = "".join(src.split())
+ assert '"task":task' in compact
+ assert '"audio_type":audio_type' in compact
def test_pipeline_class_guard_fires_before_any_download():
@@ -5487,19 +5489,25 @@ def test_a_sibling_whose_header_will_not_read_keeps_speech_off_the_folder(tmp_pa
assert models_route._gguf_folder_task(speech_only, ("someone/csm-GGUF",)) == "text-to-speech"
-def test_only_a_read_architecture_ever_answers_speech():
- """The frontend gate is fail-CLOSED on a text-to-speech tag while every backend probe fails
- open, and that is only safe because the tag can come from nothing but ``general.architecture``.
- A name hint reaching this verdict would hide the runnable TTS GGUFs (Orpheus, OuteTTS) whose
- files are named for a family but declare a plain ``llama`` arch."""
+def test_speech_gguf_classification_preserves_decoder_provenance(tmp_path):
+ """CSM and Orpheus both stay out of Chat, while Audio can distinguish them."""
hints = ("unsloth/csm-1b-GGUF", "csm-1b-Q4_0.gguf", "sesame-csm", "text-to-speech")
assert models_route._arch_to_task("llama-csm") == models_route._SPEECH_TASK
for arch in (None, "", "llama", "qwen3", "flux"):
assert models_route._arch_to_task(arch, name_hints = hints) != models_route._SPEECH_TASK
- # Orpheus ships as a llama GGUF, so it must stay a chat row for the gate to leave it alone.
+ # Orpheus ships as a llama GGUF. Its family hint makes it speech-only, and the
+ # codec field is what lets Audio route it instead of mistaking it for CSM.
assert models_route._arch_to_task("llama", name_hints = ("unsloth/orpheus-3b-0.1-ft-GGUF",)) == (
- "text-generation"
+ models_route._SPEECH_TASK
+ )
+ assert _classification._arch_to_audio_type("llama-csm", hints) == "csm"
+ assert (
+ _classification._arch_to_audio_type("llama", ("unsloth/orpheus-3b-0.1-ft-GGUF",)) == "snac"
)
+ snapshot = tmp_path / "snapshot"
+ _arch_gguf(snapshot / "orpheus-3b-q4.gguf", "llama")
+ repo = SimpleNamespace(repo_id = "community/orpheus-3b-GGUF", repo_path = snapshot)
+ assert _classification._repo_gguf_audio_type(repo, snapshot) == "snac"
def test_a_buildable_denoiser_outranks_an_arch_the_backend_cannot_assemble(tmp_path):
diff --git a/studio/backend/tests/test_hf_cache_dangling_refs.py b/studio/backend/tests/test_hf_cache_dangling_refs.py
index 975f46db51a..ec94d855eec 100644
--- a/studio/backend/tests/test_hf_cache_dangling_refs.py
+++ b/studio/backend/tests/test_hf_cache_dangling_refs.py
@@ -1559,6 +1559,7 @@ _REPO_INFO_HELPERS = frozenset(
"_repo_gguf_size_bytes",
"_repo_has_gguf_files",
"_repo_non_gguf_model_payload",
+ "catalog_classification._repo_gguf_audio_type",
"getattr",
}
)
@@ -1710,7 +1711,7 @@ def test_task_inventory_exposes_cached_custom_whisper_as_non_chat_asr(tmp_path,
assert rows[0]["capabilities"]["can_chat"] is False
-def test_task_inventory_preserves_cached_community_tts_pipeline(tmp_path, monkeypatch):
+def test_task_inventory_preserves_cached_community_tts_codec(tmp_path, monkeypatch):
from types import SimpleNamespace
from hub.services.models import cache_inventory
@@ -1725,13 +1726,14 @@ def test_task_inventory_preserves_cached_community_tts_pipeline(tmp_path, monkey
}
},
refs = {"main": SNAPSHOT},
- name = "models--community--orpheus-tts",
+ name = "models--community--renamed-checkpoint",
)
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),
)
+ monkeypatch.setattr(cache_inventory, "detect_local_tts_audio_type", lambda _path: "snac")
inventory_scan.invalidate_hf_cache_scans()
try:
rows = cache_inventory._scan_cached_models()
@@ -1741,6 +1743,7 @@ def test_task_inventory_preserves_cached_community_tts_pipeline(tmp_path, monkey
assert len(rows) == 1
assert rows[0]["task"] == "text-to-speech"
assert rows[0]["pipeline_tag"] == "text-to-speech"
+ assert rows[0]["audio_type"] == "snac"
def test_a_secondary_dangling_ref_still_judges_the_recovered_snapshot(tmp_path, monkeypatch):
diff --git a/studio/backend/tests/test_tts_not_chattable.py b/studio/backend/tests/test_tts_not_chattable.py
new file mode 100644
index 00000000000..2443faeee29
--- /dev/null
+++ b/studio/backend/tests/test_tts_not_chattable.py
@@ -0,0 +1,208 @@
+# 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 TTS model must never be chat-loadable.
+
+The Audio page loads speech models into the single slot chat reads, and
+``openai_chat_completions`` answers a turn on one by SYNTHESIZING the prompt
+rather than refusing it. Auto-load picks the smallest downloaded model and TTS
+models are small, so one became the default chat model on a fresh install.
+
+Architecture cannot answer this -- Orpheus and OuteTTS are ``LlamaForCausalLM``,
+Spark is ``Qwen2ForCausalLM`` -- so the codec vocabulary in
+``tokenizer_config.json`` is the signal, with the curated ids covering the GGUF
+companions that ship no tokenizer at all.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+import types
+from pathlib import Path
+
+if "structlog" not in sys.modules:
+
+ class _DummyLogger:
+ def __getattr__(self, _name):
+ return lambda *args, **kwargs: None
+
+ sys.modules["structlog"] = types.SimpleNamespace(
+ BoundLogger = _DummyLogger,
+ get_logger = lambda *args, **kwargs: _DummyLogger(),
+ )
+
+from utils.audio_tokens import (
+ AUDIO_TOKEN_PATTERNS,
+ TTS_AUDIO_TYPES,
+ detect_local_tts_audio_type,
+ is_tts_audio_type,
+)
+from utils.hidden_models import is_curated_stt_repo_id, is_curated_tts_repo_id
+
+
+def _model_dir(tmp_path: Path, name: str, architectures, tokens) -> Path:
+ path = tmp_path / name
+ path.mkdir(parents = True, exist_ok = True)
+ (path / "config.json").write_text(
+ json.dumps({"model_type": "llama", "architectures": architectures}),
+ encoding = "utf-8",
+ )
+ (path / "tokenizer_config.json").write_text(
+ json.dumps(
+ {
+ "added_tokens_decoder": {
+ str(index): {"content": token} for index, token in enumerate(tokens)
+ }
+ }
+ ),
+ encoding = "utf-8",
+ )
+ return path
+
+
+def _snac_tokens() -> list[str]:
+ # Orpheus ships a stray <|audio|> beside its codebook; the codec must still win.
+ return ["<|audio|>"] + [f"<custom_token_{index}>" for index in range(10_002)]
+
+
+def test_orpheus_shaped_directory_is_detected_as_tts(tmp_path):
+ path = _model_dir(tmp_path, "orpheus", ["LlamaForCausalLM"], _snac_tokens())
+ assert detect_local_tts_audio_type(path) == "snac"
+
+
+def test_every_tts_codec_is_detected(tmp_path):
+ cases = {
+ "csm": ["<|AUDIO|>", "<|audio_eos|>"],
+ "bicodec": ["<|bicodec_semantic_0|>"],
+ "dac": ["<|audio_start|>", "<|audio_end|>", "<|text_start|>", "<|text_end|>"],
+ "snac": _snac_tokens(),
+ }
+ # Pinned against the source of truth so a codec added there without a case here fails.
+ assert set(cases) == set(TTS_AUDIO_TYPES)
+ for audio_type, tokens in cases.items():
+ path = _model_dir(tmp_path, audio_type, ["LlamaForCausalLM"], tokens)
+ assert detect_local_tts_audio_type(path) == audio_type
+
+
+def test_a_speech_model_is_not_chattable_despite_a_causal_lm_head(tmp_path):
+ """The whole point: the suffix rule below it answers True for this directory."""
+ from hub.services.models.common import _local_transformers_can_chat
+
+ path = _model_dir(tmp_path, "orpheus", ["LlamaForCausalLM"], _snac_tokens())
+ assert _local_transformers_can_chat(path) is False
+
+
+def test_an_ordinary_chat_model_stays_chattable(tmp_path):
+ from hub.services.models.common import _local_transformers_can_chat
+ path = _model_dir(tmp_path, "llama", ["LlamaForCausalLM"], ["<bos>", "<eos>"])
+ assert _local_transformers_can_chat(path) is True
+
+
+def test_an_audio_input_chat_model_stays_chattable(tmp_path):
+ """Gemma 3n takes audio IN and answers in text, so the probe must not claim it."""
+ from hub.services.models.common import _local_transformers_can_chat
+
+ path = _model_dir(
+ tmp_path, "gemma3n", ["Gemma3nForConditionalGeneration"], ["<audio_soft_token>"]
+ )
+ assert detect_local_tts_audio_type(path) is None
+ assert _local_transformers_can_chat(path) is True
+
+
+def test_whisper_is_not_claimed_by_the_tts_probe(tmp_path):
+ """STT has its own path (stt_only / is_curated_stt_repo_id); the two must not overlap."""
+ path = _model_dir(
+ tmp_path, "whisper", ["WhisperForConditionalGeneration"], ["<|startoftranscript|>"]
+ )
+ assert detect_local_tts_audio_type(path) is None
+
+
+def test_a_directory_without_a_tokenizer_is_not_tts(tmp_path):
+ path = tmp_path / "bare"
+ path.mkdir()
+ (path / "config.json").write_text('{"architectures":["LlamaForCausalLM"]}', encoding = "utf-8")
+ assert detect_local_tts_audio_type(path) is None
+
+
+def test_unreadable_targets_answer_none(tmp_path):
+ assert detect_local_tts_audio_type(tmp_path / "missing") is None
+ assert detect_local_tts_audio_type(tmp_path / "missing" / "config.json") is None
+
+
+def test_is_tts_audio_type_excludes_the_input_only_types():
+ for audio_type in TTS_AUDIO_TYPES:
+ assert is_tts_audio_type(audio_type)
+ assert not is_tts_audio_type("whisper")
+ assert not is_tts_audio_type("audio_vlm")
+ assert not is_tts_audio_type(None)
+
+
+def test_the_tts_set_is_a_subset_of_the_classifier():
+ # A type here that the patterns cannot produce would never fire.
+ assert TTS_AUDIO_TYPES <= set(AUDIO_TOKEN_PATTERNS)
+
+
+def test_curated_tts_repo_ids_cover_the_gguf_companion():
+ """A GGUF repo carries no tokenizer_config, so only the ids can answer."""
+ assert is_curated_tts_repo_id("unsloth/orpheus-3b-0.1-ft-GGUF")
+ assert is_curated_tts_repo_id("UNSLOTH/Orpheus-3B-0.1-FT-GGUF")
+ assert is_curated_tts_repo_id("unsloth/csm-1b")
+ assert is_curated_tts_repo_id("unsloth/Spark-TTS-0.5B")
+ assert is_curated_tts_repo_id("unsloth/Llama-OuteTTS-1.0-1B")
+ assert not is_curated_tts_repo_id("unsloth/gemma-4-E2B-it")
+ assert not is_curated_tts_repo_id(None)
+ # The two curated sets describe different halves of the Audio page.
+ assert not is_curated_tts_repo_id("unsloth/whisper-large-v3")
+ assert not is_curated_stt_repo_id("unsloth/orpheus-3b-0.1-ft")
+
+
+def test_a_curated_tts_repo_row_is_not_chat_loadable(tmp_path):
+ """can_chat is what auto-load filters on, and a GGUF row's capabilities come from
+ the file format alone."""
+ from hub.services.models.cache_inventory import _cache_inventory_fields
+
+ fields = _cache_inventory_fields(
+ "unsloth/orpheus-3b-0.1-ft-GGUF",
+ "gguf",
+ snapshot_path = tmp_path,
+ )
+ assert fields["capabilities"]["can_chat"] is False
+
+
+def test_an_ordinary_gguf_repo_row_still_chats(tmp_path):
+ from hub.services.models.cache_inventory import _cache_inventory_fields
+ fields = _cache_inventory_fields(
+ "unsloth/gemma-4-E2B-it-GGUF",
+ "gguf",
+ snapshot_path = tmp_path,
+ )
+ assert fields["capabilities"]["can_chat"] is True
+
+
+def test_a_lora_over_a_speech_base_is_not_chattable(tmp_path):
+ """Studio trains Orpheus LoRAs, and an adapter resolves its base to decide this, so
+ without the probe every voice fine-tune became chat-loadable too."""
+ from hub.services.models.common import _local_path_can_chat
+
+ base = _model_dir(tmp_path, "orpheus-base", ["LlamaForCausalLM"], _snac_tokens())
+ adapter = tmp_path / "my-voice-lora"
+ adapter.mkdir()
+ (adapter / "adapter_config.json").write_text(
+ json.dumps({"base_model_name_or_path": str(base)}), encoding = "utf-8"
+ )
+
+ assert _local_path_can_chat(adapter) is False
+
+
+def test_the_tts_only_flag_clears_can_chat(tmp_path):
+ """The probe's answer for an uncurated safetensors copy reaches the row."""
+ from hub.services.models.cache_inventory import _cache_inventory_fields
+
+ fields = _cache_inventory_fields(
+ "someone/my-finetuned-voice",
+ "gguf",
+ snapshot_path = tmp_path,
+ tts_only = True,
+ )
+ assert fields["capabilities"]["can_chat"] is False
diff --git a/studio/backend/utils/audio_tokens.py b/studio/backend/utils/audio_tokens.py
new file mode 100644
index 00000000000..174bdbd18f0
--- /dev/null
+++ b/studio/backend/utils/audio_tokens.py
@@ -0,0 +1,127 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Tokenizer-based audio_type classification.
+
+Directly under ``utils`` so the cache scanner can classify a snapshot without
+dragging in ``utils/models/__init__.py`` and the model-config stack.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Optional
+
+VALID_AUDIO_TYPES = ("snac", "csm", "bicodec", "dac", "whisper", "audio_vlm")
+
+# Emit speech; a chat turn sent to one comes back as audio, never as text.
+TTS_AUDIO_TYPES = frozenset({"snac", "csm", "bicodec", "dac"})
+
+
+def _count_prefix_exceeds(tokens, prefix: str, threshold: int) -> bool:
+ """``sum(...) > threshold``, but stopping at the answer: summing counted all 28k of
+ Orpheus's codes to settle a question the first 10,001 decide."""
+ count = 0
+ for token in tokens:
+ if token.startswith(prefix):
+ count += 1
+ if count > threshold:
+ return True
+ return False
+
+
+# ORDER MATTERS: first match wins, so codec fingerprints precede the generic audio_vlm
+# marker. Orpheus carries 28k <custom_token_N> SNAC codes AND a stray <|audio|>, and
+# audio_vlm first typed it as audio-input.
+AUDIO_TOKEN_PATTERNS = {
+ "csm": lambda tokens: "<|AUDIO|>" in tokens and "<|audio_eos|>" in tokens,
+ "whisper": lambda tokens: "<|startoftranscript|>" in tokens,
+ "bicodec": lambda tokens: any(t.startswith("<|bicodec_") for t in tokens),
+ "dac": lambda tokens: (
+ "<|audio_start|>" in tokens
+ and "<|audio_end|>" in tokens
+ and "<|text_start|>" in tokens
+ and "<|text_end|>" in tokens
+ ),
+ "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|>.
+ "audio_vlm": lambda tokens: "<audio_soft_token>" in tokens or "<|audio|>" in tokens,
+}
+
+# Every substring a pattern needs, so text holding none of them is settled without a
+# parse -- json.loads of an ordinary large tokenizer_config was the bulk of a cold /loras
+# scan. The patterns are lambdas, so this cannot be derived from them; a codec added
+# there without its marker here would silently stop being detected, and
+# test_audio_token_detection.py fails when 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)
+)
+
+AUDIO_TOKENIZER_CONFIG_PATHS = (
+ "tokenizer_config.json",
+ "LLM/tokenizer_config.json",
+)
+
+# A codebook tokenizer runs to a few MB, and the inventory scan reads one per repo.
+_MAX_TOKENIZER_CONFIG_BYTES = 32 * 1024 * 1024
+
+
+def may_hold_audio_tokens(raw: str) -> bool:
+ """Whether a tokenizer_config's raw text is worth parsing. A false True costs only
+ the parse that would have happened anyway; a false False misclassifies."""
+ return any(marker in raw for marker in AUDIO_TOKEN_MARKERS)
+
+
+def classify_audio_tokens(tok_config: dict) -> Optional[str]:
+ """The audio_type a parsed tokenizer_config fingerprints, or None."""
+ added = tok_config.get("added_tokens_decoder", {})
+ if not added:
+ return None
+ token_contents = [value.get("content", "") for value in added.values()]
+ for audio_type, check_fn in AUDIO_TOKEN_PATTERNS.items():
+ if check_fn(token_contents):
+ return audio_type
+ return None
+
+
+def is_audio_input_type(audio_type: Optional[str]) -> bool:
+ """True if an audio_type accepts audio input: whisper (ASR), audio_vlm (Gemma3n)."""
+ return audio_type in ("whisper", "audio_vlm")
+
+
+def is_tts_audio_type(audio_type: Optional[str]) -> bool:
+ """True for a speech-emitting codec. audio_vlm is absent on purpose: Gemma 3n takes
+ audio in and answers in text."""
+ return audio_type in TTS_AUDIO_TYPES
+
+
+def detect_local_tts_audio_type(directory) -> Optional[str]:
+ """The TTS codec a downloaded model directory fingerprints, or None. Local files
+ only. Whisper and audio_vlm answer None: both of those chat."""
+ try:
+ root = Path(directory)
+ if not root.is_dir():
+ return None
+ except OSError:
+ return None
+ for tok_path in AUDIO_TOKENIZER_CONFIG_PATHS:
+ tok_file = root / tok_path
+ try:
+ if not tok_file.is_file() or tok_file.stat().st_size > _MAX_TOKENIZER_CONFIG_BYTES:
+ continue
+ raw = tok_file.read_text(encoding = "utf-8-sig")
+ if not may_hold_audio_tokens(raw):
+ continue
+ audio_type = classify_audio_tokens(json.loads(raw))
+ except Exception:
+ continue
+ if is_tts_audio_type(audio_type):
+ return audio_type
+ return None
diff --git a/studio/backend/utils/hidden_models.py b/studio/backend/utils/hidden_models.py
index c94b8689b7e..13ae9c00390 100644
--- a/studio/backend/utils/hidden_models.py
+++ b/studio/backend/utils/hidden_models.py
@@ -57,6 +57,31 @@ _HIDDEN_STT_REPO_IDS = frozenset(
)
_HIDDEN_STT_REPO_IDS_LOWER = frozenset(repo_id.lower() for repo_id in _HIDDEN_STT_REPO_IDS)
+# Curated Audio-page TTS checkpoints. Unlike the STT set these stay VISIBLE -- the Audio
+# page is where they belong -- but a chat turn on one comes back as synthesized speech,
+# so they must not be chat-loadable. Config sniffing cannot catch them (Orpheus and
+# OuteTTS are LlamaForCausalLM, Spark is Qwen2ForCausalLM) and a GGUF companion carries
+# no tokenizer_config for the codec probe, so the ids answer for those.
+_CURATED_TTS_REPO_IDS = frozenset(
+ {
+ "unsloth/orpheus-3b-0.1-ft",
+ "unsloth/orpheus-3b-0.1-ft-bnb-4bit",
+ "unsloth/orpheus-3b-0.1-ft-unsloth-bnb-4bit",
+ "unsloth/orpheus-3b-0.1-ft-GGUF",
+ "canopylabs/orpheus-3b-0.1-ft",
+ "unsloth/csm-1b",
+ "sesame/csm-1b",
+ "unsloth/Spark-TTS-0.5B",
+ "unsloth/Llama-OuteTTS-1.0-1B",
+ }
+)
+_CURATED_TTS_REPO_IDS_LOWER = frozenset(repo_id.lower() for repo_id in _CURATED_TTS_REPO_IDS)
+
+
+def is_curated_tts_repo_id(value: str | None) -> bool:
+ """True only for Unsloth's exact curated TTS Hub repositories."""
+ return bool(value and value.strip().lower() in _CURATED_TTS_REPO_IDS_LOWER)
+
def is_curated_stt_repo_id(value: str | None) -> bool:
"""True only for Unsloth's exact curated STT Hub repositories.
diff --git a/studio/backend/utils/models/__init__.py b/studio/backend/utils/models/__init__.py
index 0a15861bf34..d7f6a366b0c 100644
--- a/studio/backend/utils/models/__init__.py
+++ b/studio/backend/utils/models/__init__.py
@@ -3,6 +3,7 @@
"""Model and LoRA configuration handling."""
+from utils.audio_tokens import VALID_AUDIO_TYPES
from .model_config import (
ModelConfig,
GgufVariantInfo,
@@ -11,7 +12,6 @@ from .model_config import (
detect_audio_type,
detect_audio_type_checked,
is_audio_input_type,
- VALID_AUDIO_TYPES,
scan_trained_models,
scan_exported_models,
get_base_model_from_checkpoint,
diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.py
index cf84aed14f1..b97c112cb02 100644
--- a/studio/backend/utils/models/model_config.py
+++ b/studio/backend/utils/models/model_config.py
@@ -20,6 +20,12 @@ from utils.utils import without_hf_auth
from utils.training_runs import (
base_model_from_run_dir_name as _base_model_from_dir_name,
)
+from utils.audio_tokens import (
+ AUDIO_TOKENIZER_CONFIG_PATHS as _AUDIO_TOKENIZER_CONFIG_PATHS,
+ classify_audio_tokens as _check_token_patterns,
+ is_audio_input_type,
+ may_hold_audio_tokens as _may_hold_audio_tokens,
+)
from utils.models.gguf_metadata import (
is_mmproj_by_metadata,
mmproj_accepts_image,
@@ -1145,8 +1151,6 @@ def _is_vision_model_uncached(
return None
-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]] = {}
@@ -1159,73 +1163,6 @@ _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,
- "bicodec": lambda tokens: any(t.startswith("<|bicodec_") for t in tokens),
- "dac": lambda tokens: (
- "<|audio_start|>" in tokens
- and "<|audio_end|>" in tokens
- and "<|text_start|>" in tokens
- and "<|text_end|>" in tokens
- ),
- "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",
-)
-
-
def detect_audio_type(
model_name: str,
hf_token: Optional[str] = None,
@@ -1349,16 +1286,6 @@ def _detect_audio_from_tokenizer(
retries; a successful read with no audio tokens is a definitive None.
"""
- def _check_token_patterns(tok_config: dict) -> Optional[str]:
- added = tok_config.get("added_tokens_decoder", {})
- if not added:
- return None
- token_contents = [v.get("content", "") for v in added.values()]
- for audio_type, check_fn in _AUDIO_TOKEN_PATTERNS.items():
- if check_fn(token_contents):
- return audio_type
- return None
-
read_any = False # parsed at least one tokenizer_config -> a None is definitive
# 1) Selected local directory or local HF cache first (works for gated/offline models)
@@ -1467,11 +1394,6 @@ def _detect_audio_from_tokenizer(
return None, (read_any or not transient)
-def is_audio_input_type(audio_type: Optional[str]) -> bool:
- """True if an audio_type accepts audio input: whisper (ASR), audio_vlm (Gemma3n)."""
- return audio_type in ("whisper", "audio_vlm")
-
-
def _is_mmproj(filename: str) -> bool:
"""Check if a GGUF filename is a vision projection (mmproj) file."""
return "mmproj" in filename.lower()
diff --git a/studio/frontend/src/features/audio/audio-page.tsx b/studio/frontend/src/features/audio/audio-page.tsx
index 249a7e8ae0b..45177ed75e9 100644
--- a/studio/frontend/src/features/audio/audio-page.tsx
+++ b/studio/frontend/src/features/audio/audio-page.tsx
@@ -808,6 +808,7 @@ export function AudioPage({
},
{
signal: controller.signal,
+ runtime: "tts",
onRequestStart: () => {
pending.requestStarted = true;
// Queued prompts would otherwise start on the model this load replaces.
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 10fb4f6d0b6..9705adf3e93 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -118,6 +118,7 @@ import {
resolveInferenceCheckpointId,
tryAdoptServerActiveModel,
} from "../lib/apply-inference-status-to-store";
+import { isSpeechOnlyStatus } from "../lib/speech-only-status";
import { syncModelCapabilities } from "../hooks/use-chat-model-runtime";
import {
clampReasoningEffortToLevels,
@@ -2370,19 +2371,23 @@ function isChattableCachedRepo(repo: {
// weights, so /load fetches the base from the Hub when it is not cached,
// and can_chat is reported true for the format on file layout alone.
repo.model_format !== "adapter" &&
- // Cached diffusion repos report can_chat true on file format alone.
- !IMAGE_OR_VIDEO_TASKS.has(repo.task ?? "")
+ // Cached diffusion and speech repos report can_chat true on file format alone.
+ !NON_CHAT_TASKS.has(repo.task ?? "")
);
}
-// Chat models are tagged "text-generation" or left null, so this is a list
-// rather than a "has a task" test. The picker routes these rows to the
-// Images/Video page on click; a background load has no routing step, so
-// without this the chat turn goes to a diffusion runtime.
-const IMAGE_OR_VIDEO_TASKS: ReadonlySet<string> = new Set([
+// Chat models are tagged "text-generation" or left null, so this is a list rather than
+// a "has a task" test. The picker routes these rows to their own page on click; a
+// background load has no routing step. For the audio tasks the backend answers a chat
+// completion with synthesized speech rather than refusing it.
+const NON_CHAT_TASKS: ReadonlySet<string> = new Set([
"text-to-image",
"text-to-video",
"image-diffusion-unsupported",
+ "text-to-speech",
+ "text-to-audio",
+ "audio-to-audio",
+ "automatic-speech-recognition",
]);
// Scan folders the picker exposes. hf_cache is already in the cached lists.
@@ -2422,7 +2427,7 @@ function isAutoLoadableLocalRow(
// safetensors one, so this has to fail closed; GGUF is still recognised by
// suffix, so an unclassified .gguf row keeps loading.
(isGgufLocalRow(row) || row.model_format === "safetensors") &&
- !IMAGE_OR_VIDEO_TASKS.has(row.task ?? "") &&
+ !NON_CHAT_TASKS.has(row.task ?? "") &&
runsOnThisPlatform(row) &&
!isHiddenModelId(row.model_id, row.id, row.path)
);
@@ -3798,7 +3803,12 @@ async function resolveQueuedEmptyLocalModel(
// model with the recorded/default auto-load candidate.
const status = await getInferenceStatus();
abortSignal.throwIfAborted();
- const checkpoint = resolveInferenceCheckpointId(status);
+ // The other door into adoption, bypassing tryAdoptServerActiveModel: a speech
+ // model is not one chat can queue against, so read the slot as empty and let the
+ // sweep below load a real chat model.
+ const checkpoint = isSpeechOnlyStatus(status)
+ ? null
+ : resolveInferenceCheckpointId(status);
if (checkpoint) {
return {
loaded: true,
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 7011c789a16..6eefe685cd4 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -16,7 +16,10 @@ import { isHuggingFaceOffline } from "@/features/hub/lib/network";
// eslint-disable-next-line no-restricted-imports
import { consumeNativePathToken } from "@/features/native-intents/api";
import { formatApiErrorBody } from "@/lib/format-fastapi-error";
-import { withModelLoadNotice } from "@/lib/model-lifecycle-events";
+import {
+ type ModelRuntime,
+ withModelLoadNotice,
+} from "@/lib/model-lifecycle-events";
import type {
MessageRecord,
ModelType,
@@ -261,6 +264,9 @@ export async function loadModel(
options?: {
signal?: AbortSignal;
onRequestStart?: () => void;
+ /** What is taking the slot. Chat ignores its own loads when reconciling, so an
+ * Audio load announced as "chat" left chat naming a model it had evicted. */
+ runtime?: ModelRuntime;
},
): Promise<LoadModelResponse> {
const preparedToken = await prepareHfTokenForUse(payload.hf_token);
@@ -275,20 +281,24 @@ export async function loadModel(
// 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.
- return withModelLoadNotice("chat", payload.model_path ?? null, async () => {
- const response = await authFetch("/api/inference/load", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- ...payload,
- hf_token: preparedToken.token,
- native_path_lease: payload.nativePathLease ?? null,
- nativePathLease: undefined,
- }),
- signal: options?.signal,
- });
- return parseJsonOrThrow<LoadModelResponse>(response, "Model load");
- });
+ return withModelLoadNotice(
+ options?.runtime ?? "chat",
+ payload.model_path ?? null,
+ async () => {
+ const response = await authFetch("/api/inference/load", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ ...payload,
+ hf_token: preparedToken.token,
+ native_path_lease: payload.nativePathLease ?? null,
+ nativePathLease: undefined,
+ }),
+ signal: options?.signal,
+ });
+ return parseJsonOrThrow<LoadModelResponse>(response, "Model load");
+ },
+ );
}
export async function countChatInputTokens(payload: {
@@ -467,6 +477,7 @@ export interface CachedGgufRepo {
has_vision?: boolean;
/** HF pipeline task inferred from the GGUF architecture ("text-to-image" for diffusion), so the Images picker can show only diffusion GGUFs. Optional for older backends. */
task?: string | null;
+ audio_type?: string | null;
/** True when some quant has a download manifest or cancel marker. Optional
* for older-backend compatibility. */
has_variant_state?: boolean;
@@ -569,6 +580,7 @@ export interface LocalModelInfo {
updated_at?: number | null;
// HF pipeline task inferred from the GGUF architecture, so the Images picker can filter to diffusion ("text-to-image"). Optional for older backends.
task?: string | null;
+ audio_type?: string | null;
}
interface LocalModelListResponse {
@@ -605,6 +617,7 @@ export interface CachedModelRepo {
last_modified?: number;
/** HF pipeline task: "text-to-image" for a cached diffusers pipeline repo (model_index.json present), so the chat picker can hide it. Absent = chat. */
task?: string | null;
+ audio_type?: string | null;
/** True when the snapshot is incomplete (a cancelled/partial download): such a repo must not count as downloaded, or a click re-downloads the full weights. */
partial?: boolean;
/** True for a diffusion repo with no model_index.json: a single-file checkpoint loadable only via from_single_file, so task pickers must not offer it as a pipeline load unless the curated catalog carries its artifact. */
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 ea40aee1d47..14bebf3e55a 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
@@ -25,6 +25,7 @@ import {
import { isSettingsRouteAbsent } from "@/features/settings/api/settings-route-absent";
import { loadModelMemorySettings } from "@/features/settings/api/model-memory";
import { loadVramBudgetSettings } from "@/features/settings/api/vram-budget";
+import { loadOpenAIAutoSwitchSettings } from "@/features/settings";
import {
confirmTransformersUpgradeIfNeeded,
useTransformersUpgradeDialogStore,
@@ -32,6 +33,8 @@ import {
import { consumeNativePathToken } from "@/features/native-intents/api";
// eslint-disable-next-line no-restricted-imports -- Avoid the hub barrel's React and download-manager exports.
import { modelDisplayName } from "@/features/hub/lib/model-identity";
+// eslint-disable-next-line no-restricted-imports -- Avoid the hub barrel's React and download-manager exports.
+import { subscribeResidentStatusRefresh } from "@/features/hub/lib/resident-status-refresh";
import { prepareHfTokenForUse } from "@/features/hf-auth";
import { ModelLoadDescription } from "../components/model-load-status";
import {
@@ -73,6 +76,10 @@ import {
normalizeSpeculativeType,
resolveInferenceCheckpointId,
} from "../lib/apply-inference-status-to-store";
+import {
+ isIdleUnloadedStatus,
+ isSpeechOnlyStatus,
+} from "../lib/speech-only-status";
import {
residentRuntimeMatchesConfig,
residentSpeculativeNeedsRepair,
@@ -376,10 +383,22 @@ function getTransformersUpgradeRequiredMessage(modelName: string): string {
// last and re-pin the model the newer one had just seen released, leaving chat
// claiming a model that 400s on send until the load finally settled.
let syncGeneration = 0;
+let lastIdleUnloadArmed = false;
+
+async function readIdleUnloadArmed(): Promise<boolean> {
+ try {
+ const settings = await loadOpenAIAutoSwitchSettings();
+ lastIdleUnloadArmed = settings.idleUnloadActive;
+ } catch {
+ // Preserve the last answer: treating a settings blip as disarmed would discard the pick.
+ }
+ return lastIdleUnloadArmed;
+}
async function syncInferenceStatusToStore(options?: {
signal?: AbortSignal;
includeLoras?: boolean;
+ preserveIdleUnloaded?: boolean;
}): Promise<void> {
const signal = options?.signal;
const includeLoras = options?.includeLoras ?? true;
@@ -390,10 +409,13 @@ async function syncInferenceStatusToStore(options?: {
useChatRuntimeStore.getState();
setModelsError(null);
try {
- const [listRes, statusRes, lorasRes] = await Promise.all([
+ const [listRes, statusRes, lorasRes, idleUnloadArmed] = await Promise.all([
listModels(),
getInferenceStatus(),
includeLoras ? listLoras() : Promise.resolve(null),
+ options?.preserveIdleUnloaded
+ ? readIdleUnloadArmed()
+ : Promise.resolve(false),
]);
// Cancellation can land while the requests above are in flight. Bail
@@ -409,7 +431,13 @@ async function syncInferenceStatusToStore(options?: {
const selectedCheckpoint = useChatRuntimeStore.getState().params.checkpoint;
const isExternalSelectionActive = isExternalModelId(selectedCheckpoint);
- if (statusRes.active_model && !isExternalSelectionActive) {
+ // The local selection is re-derived from this status on every mount, so adopting a
+ // TTS model made it the chat model without the user picking it. Read the slot as
+ // empty and the eviction branch below clears the stale pick, as it does for an
+ // image or video load.
+ const chatActiveModel =
+ statusRes.active_model && !isSpeechOnlyStatus(statusRes);
+ if (chatActiveModel && !isExternalSelectionActive) {
const checkpointId = resolveInferenceCheckpointId(statusRes);
if (checkpointId) {
const previousGgufVariant =
@@ -445,8 +473,9 @@ async function syncInferenceStatusToStore(options?: {
void refreshContextUsage({ threadId: hydrated.activeThreadId });
}
}
- } else if (!statusRes.active_model && !isExternalSelectionActive) {
- // Loading an image or video model evicts the chat one (the GPU arbiter
+ } else if (!chatActiveModel && !isExternalSelectionActive) {
+ if (isIdleUnloadedStatus(statusRes, idleUnloadArmed)) return;
+ // Loading an image, video or audio model evicts the chat one (the GPU arbiter
// allows a single owner), and nothing else here would say so: the picker
// keeps the selection, so the header would go on claiming it is loaded
// and the next prompt would come back a bare 400.
@@ -462,16 +491,22 @@ async function syncInferenceStatusToStore(options?: {
loadedVisionDisabledByUser: null,
loadedIsDiffusion: false,
});
- // Known resident a moment ago, and nothing loading now. Both matter: a
- // load in flight has no active model yet either, and clearing there would
- // wipe the pick the user just made.
- if (wasResident && selectedCheckpoint && !modelLoading) {
+ // A known prior resident or a definitive speech-only owner both prove the
+ // persisted Chat pick is stale. A load in flight has no active model yet
+ // either, so never clear while one is starting.
+ if (
+ (wasResident || isSpeechOnlyStatus(statusRes)) &&
+ selectedCheckpoint &&
+ !modelLoading
+ ) {
// Already the clean id the header shows: resolveInferenceCheckpointId
// put it there, not a load path.
- toast.info(`${wasResident} is no longer loaded`, {
- description:
- "The server released it, which loading an image or video model does. Pick it again to keep chatting.",
- });
+ if (wasResident) {
+ toast.info(`${wasResident} is no longer loaded`, {
+ description:
+ "The server released it, which loading an image, video or audio model does. Pick it again to keep chatting.",
+ });
+ }
// Drop the pick too, which is what a server-side unload already does.
// Dimming the tick was not enough: the name alone reads as "this is my
// model" whatever the tick does, and sending to it returns a bare 400.
@@ -599,7 +634,11 @@ export function useChatModelRuntime() {
);
const refresh = useCallback(
- (options?: { signal?: AbortSignal; includeLoras?: boolean }) =>
+ (options?: {
+ signal?: AbortSignal;
+ includeLoras?: boolean;
+ preserveIdleUnloaded?: boolean;
+ }) =>
syncInferenceStatusToStore(options),
[],
);
@@ -612,8 +651,9 @@ export function useChatModelRuntime() {
useEffect(
() =>
subscribeModelLifecycle(({ runtime }) => {
- // Dictation is a sidecar and takes no GPU ownership, so it evicts
- // nothing. Chat's own loads already reconcile themselves.
+ // Dictation is a sidecar and evicts nothing; chat's own loads reconcile
+ // themselves. A "tts" load does neither: it is the Audio page taking this very
+ // slot, so read it back like an image or video load.
if (runtime === "chat" || runtime === "stt") return;
// Both edges, not only the settle. The arbiter evicts chat inside the
// image or video load POST, before the download starts, so waiting for
@@ -624,6 +664,14 @@ export function useChatModelRuntime() {
[refresh],
);
+ useEffect(
+ () =>
+ subscribeResidentStatusRefresh(() => {
+ void refresh({ includeLoras: false, preserveIdleUnloaded: true });
+ }),
+ [refresh],
+ );
+
const cancelLoading = useCallback(() => {
const model = loadingModelRef.current;
if (!model) return;
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index e83627a5819..044ee12ecdc 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -43,6 +43,7 @@ export {
applyActiveModelStatusToStore,
resolveInferenceCheckpointId,
} from "./lib/apply-inference-status-to-store";
+export { isSpeechOnlyStatus } from "./lib/speech-only-status";
export {
ChatSettingsPanel,
ParamSlider,
diff --git a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
index 530eb06c729..ce976a1a294 100644
--- a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
+++ b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
@@ -7,6 +7,7 @@ import { resolveResidentInitialConfig } from "@/features/model-picker";
// eslint-disable-next-line no-restricted-imports -- Avoid the hub barrel's React and download-manager exports.
import { modelDisplayName } from "@/features/hub/lib/model-identity";
import { getInferenceStatus } from "../api/chat-api";
+import { isSpeechOnlyStatus } from "./speech-only-status";
import {
mergeBackendRecommendedInference,
resolveManualAutoCtxPin,
@@ -705,7 +706,9 @@ export async function tryAdoptServerActiveModel(): Promise<boolean> {
// Status endpoint unavailable: fall back to the normal auto-load path.
return false;
}
- if (!status.active_model) {
+ // Not something chat can adopt; the sweep below picks a real chat model, which evicts
+ // it exactly as an image load would.
+ if (!status.active_model || isSpeechOnlyStatus(status)) {
return false;
}
diff --git a/studio/frontend/src/features/chat/lib/speech-only-status.ts b/studio/frontend/src/features/chat/lib/speech-only-status.ts
new file mode 100644
index 00000000000..6b6a3906f95
--- /dev/null
+++ b/studio/frontend/src/features/chat/lib/speech-only-status.ts
@@ -0,0 +1,34 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Its own module so the node suite can drive it: apply-inference-status-to-store pulls
+// in the whole chat runtime store.
+
+export type SpeechOnlyStatusInput = {
+ active_model?: string | null;
+ is_audio?: boolean;
+ audio_type?: string | null;
+};
+
+/**
+ * Whether the resident model emits speech. The Audio page loads these into the single
+ * slot chat reads, and openai_chat_completions answers a turn on one by SYNTHESIZING
+ * the prompt, so chat must never adopt one.
+ *
+ * The same condition that route branches on, plus audio_vlm: Gemma 3n should never set
+ * `is_audio`, and misreading one would lock a real chat model out of chat.
+ */
+export function isSpeechOnlyStatus(status: SpeechOnlyStatusInput): boolean {
+ return (
+ Boolean(status.is_audio) &&
+ status.audio_type !== "whisper" &&
+ status.audio_type !== "audio_vlm"
+ );
+}
+
+export function isIdleUnloadedStatus(
+ status: SpeechOnlyStatusInput,
+ idleUnloadArmed: boolean,
+): boolean {
+ return idleUnloadArmed && !status.active_model;
+}
diff --git a/studio/frontend/src/features/hub/hub-page.tsx b/studio/frontend/src/features/hub/hub-page.tsx
index 14a893a9dbd..5750d64ed96 100644
--- a/studio/frontend/src/features/hub/hub-page.tsx
+++ b/studio/frontend/src/features/hub/hub-page.tsx
@@ -6,6 +6,7 @@ import {
applyActiveModelStatusToStore,
getInferenceStatus,
isExternalModelId,
+ isSpeechOnlyStatus,
listGgufVariants,
resolveInferenceCheckpointId,
useChatModelRuntime,
@@ -443,7 +444,12 @@ export function ModelsPage() {
adoptResidentModelStatus(
{
// The loadable identifier: a GGUF off disk loads by path, and two files sharing a stem collapse.
- checkpointId: resolveInferenceCheckpointId(status),
+ // Null for a speech model: this page is the other writer of params.checkpoint,
+ // so adopting one here made it the chat model just as the mount sync did.
+ checkpointId: isSpeechOnlyStatus(status)
+ ? null
+ : resolveInferenceCheckpointId(status),
+ speechOnly: isSpeechOnlyStatus(status),
ggufVariant: status.gguf_variant ?? null,
},
{
diff --git a/studio/frontend/src/features/hub/inventory/api.ts b/studio/frontend/src/features/hub/inventory/api.ts
index 132bd193bce..4cab0e03f9f 100644
--- a/studio/frontend/src/features/hub/inventory/api.ts
+++ b/studio/frontend/src/features/hub/inventory/api.ts
@@ -56,6 +56,7 @@ export interface CachedGgufRepo {
partial_resumable?: boolean;
pipeline_tag?: string | null;
task?: string | null;
+ audio_type?: string | null;
tags?: string[];
library_name?: string | null;
}
@@ -77,6 +78,7 @@ export interface CachedModelRepo {
partial_resumable?: boolean;
pipeline_tag?: string | null;
task?: string | null;
+ audio_type?: string | null;
tags?: string[];
library_name?: string | null;
quant_method?: string | null;
@@ -107,6 +109,7 @@ export interface LocalModelInfo {
partial_resumable?: boolean;
pipeline_tag?: string | null;
task?: string | null;
+ audio_type?: string | null;
tags?: string[];
library_name?: string | null;
quant_method?: string | null;
diff --git a/studio/frontend/src/features/hub/inventory/types.ts b/studio/frontend/src/features/hub/inventory/types.ts
index eaf5e776276..9cf0ca5cf7a 100644
--- a/studio/frontend/src/features/hub/inventory/types.ts
+++ b/studio/frontend/src/features/hub/inventory/types.ts
@@ -58,6 +58,7 @@ export interface CachedInventoryRow {
pipelineTag?: string | null;
// Inferred pipeline task from the backend. The task-scoped pickers filter On Device rows on it.
task?: string | null;
+ audioType?: string | null;
// Diffusion repo with no pipeline index: loadable only via from_single_file + a filename, so the task pickers must not offer it as a pipeline load.
singleFile?: boolean;
// sd.cpp companion mirror: VAE / text encoders with no denoiser. Still listed, because these
@@ -94,6 +95,7 @@ export interface LocalInventoryRow {
adapterType?: string | null;
trainingMethod?: string | null;
task?: string | null;
+ audioType?: string | null;
updatedAt: number | null;
partial?: boolean;
partialTransport?: string | null;
diff --git a/studio/frontend/src/features/hub/inventory/view-models.ts b/studio/frontend/src/features/hub/inventory/view-models.ts
index 22b1cbcfd6e..f6feec8717f 100644
--- a/studio/frontend/src/features/hub/inventory/view-models.ts
+++ b/studio/frontend/src/features/hub/inventory/view-models.ts
@@ -171,6 +171,7 @@ export function buildCachedInventoryRow(
has_variant_state?: boolean;
pipeline_tag?: string | null;
task?: string | null;
+ audio_type?: string | null;
single_file?: boolean;
companion?: boolean;
tags?: string[];
@@ -235,6 +236,7 @@ export function buildCachedInventoryRow(
hasVariantState: row.has_variant_state ?? false,
pipelineTag: row.pipeline_tag ?? null,
task: row.task ?? null,
+ audioType: row.audio_type ?? null,
singleFile: row.single_file ?? false,
companion: row.companion ?? false,
tags: row.tags,
@@ -317,6 +319,7 @@ export function buildLocalInventoryRows(
activeCache: model.active_cache ?? null,
pipelineTag: model.pipeline_tag ?? null,
task: model.task ?? null,
+ audioType: model.audio_type ?? null,
tags: model.tags,
libraryName: model.library_name ?? null,
quantMethod: model.quant_method ?? null,
diff --git a/studio/frontend/src/features/hub/lib/adopt-inference-status.ts b/studio/frontend/src/features/hub/lib/adopt-inference-status.ts
index 9f053ce3dff..dfe4502d06f 100644
--- a/studio/frontend/src/features/hub/lib/adopt-inference-status.ts
+++ b/studio/frontend/src/features/hub/lib/adopt-inference-status.ts
@@ -23,9 +23,14 @@ export interface ResidentAdoptionState {
/** What ``/api/inference/status`` says is resident, already resolved. */
export interface ResidentStatusFacts {
- /** ``resolveInferenceCheckpointId(status)``; null when nothing is loaded. */
+ /** ``resolveInferenceCheckpointId(status)``; null when nothing is loaded, and null
+ * for a speech model, which chat cannot adopt. ``speechOnly`` tells the two apart. */
checkpointId: string | null;
ggufVariant: string | null;
+ /** The slot holds a speech model rather than being empty. Chat cannot adopt one, but
+ * it is not the idle eviction the rule below is about either: an Audio load took the
+ * slot outright and no stash brings the chat model back. */
+ speechOnly?: boolean;
}
export interface ResidentAdoptionActions {
@@ -69,7 +74,9 @@ export function adoptResidentModelStatus(
// loop frees the model but keeps a stash the next request reloads, so clearing would drop
// a selection that is coming back. Disarmed, nothing brings it back, and leaving the row
// resident seeds the settings editor from a launch config nothing is running.
- if (state.idleUnloadArmed) {
+ // A speech model is neither: an Audio load took the slot, not the idle loop, and no
+ // stash reloads the chat model. Holding the pick left the Hub calling it Loaded.
+ if (state.idleUnloadArmed && !status.speechOnly) {
return false;
}
if (state.checkpoint) {
diff --git a/studio/frontend/src/features/loaded-models/use-loaded-models.ts b/studio/frontend/src/features/loaded-models/use-loaded-models.ts
index 10d2f34af57..384330a6aa7 100644
--- a/studio/frontend/src/features/loaded-models/use-loaded-models.ts
+++ b/studio/frontend/src/features/loaded-models/use-loaded-models.ts
@@ -3,7 +3,10 @@
import { toast } from "@/lib/toast";
import { useCallback, useEffect, useRef, useState } from "react";
-import { subscribeModelLifecycle } from "@/lib/model-lifecycle-events";
+import {
+ type ModelRuntime,
+ subscribeModelLifecycle,
+} from "@/lib/model-lifecycle-events";
import { ejectLoadedModel, readLoadedModels } from "./loaded-models-api";
import {
type LoadedModelEntry,
@@ -19,6 +22,12 @@ const NO_ENTRIES: LoadedModelEntry[] = [];
const ALL_SOURCES: LoadedModelSource[] = ["chat", "image", "video", "stt"];
+// A TTS load takes the chat slot and the chat unload releases it, so it folds into that
+// row rather than adding one.
+function sourceForRuntime(runtime: ModelRuntime): LoadedModelSource {
+ return runtime === "tts" ? "chat" : runtime;
+}
+
export type UseLoadedModels = {
entries: LoadedModelEntry[];
/** What the polls actually found, whether or not the card is showing it. The
@@ -173,15 +182,16 @@ export function useLoadedModels(
useEffect(() => {
if (!track) return;
return subscribeModelLifecycle(({ runtime, loading, model }) => {
+ const source = sourceForRuntime(runtime);
if (loading) {
- settledRef.current.delete(runtime);
- setPending((prev) => new Map(prev).set(runtime, model));
+ settledRef.current.delete(source);
+ setPending((prev) => new Map(prev).set(source, model));
return;
}
// Kept, not dropped: clearing here and waiting for the read to answer
// left the card with one row fewer for that gap, and with nothing at all
// when it was the only one, which read as the row randomly vanishing.
- settledRef.current.add(runtime);
+ settledRef.current.add(source);
refresh();
});
}, [track, refresh]);
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/audio-picker-policy.ts b/studio/frontend/src/features/model-picker/components/model-selector/audio-picker-policy.ts
index 6dda465e50d..737c3332f16 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/audio-picker-policy.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/audio-picker-policy.ts
@@ -29,6 +29,7 @@ export function communityAudioRowIsRunnable({
baseModel,
tags,
libraryName,
+ audioType,
}: {
isStt: boolean;
isTts: boolean;
@@ -37,6 +38,7 @@ export function communityAudioRowIsRunnable({
baseModel?: string | null;
tags?: readonly string[] | null;
libraryName?: string | null;
+ audioType?: string | null;
}): boolean {
if (!isStt && !isTts) {
return true;
@@ -57,6 +59,9 @@ export function communityAudioRowIsRunnable({
// 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 normalizedAudioType = (audioType ?? "").toLowerCase();
+ if (["snac", "bicodec", "dac"].includes(normalizedAudioType)) return true;
+ if (normalizedAudioType === "csm") return !isGguf;
const family = evidence.find((value) =>
/(?:^|[-_./])(orpheus|csm|spark-?tts|outetts|oute-?tts)(?:$|[-_./])/.test(value),
);
@@ -121,6 +126,7 @@ export function audioPickIsRoutable({
baseModel,
tags,
libraryName,
+ audioType,
}: {
id: string;
task: string | null | undefined;
@@ -133,12 +139,16 @@ export function audioPickIsRoutable({
baseModel?: string | null;
tags?: readonly string[] | null;
libraryName?: string | null;
+ audioType?: string | null;
}): boolean {
- // The backend tags text-to-speech ONLY for llama-csm (_SPEECH_GGUF_ARCHS), the one arch
- // llama.cpp has no decoder for, so that read outranks both the curated match and the
- // PATH-based heuristic below -- which clears a CSM file at /models/orpheus/custom.gguf
- // and routes it to Audio after the handoff already evicted the chat model.
- if (taskFromGgufArch && isGguf && task === "text-to-speech") return false;
+ // GGUF speech tasks have two provenances: Orpheus retains the ordinary llama
+ // architecture and is runnable by Audio's SNAC path; the dedicated CSM speech
+ // architectures remain unsupported. Unknown old-backend rows fail closed.
+ if (taskFromGgufArch && isGguf && task === "text-to-speech") {
+ const codec = (audioType ?? "").toLowerCase();
+ if (codec === "csm" || !codec) return false;
+ return ["snac", "bicodec", "dac"].includes(codec);
+ }
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
@@ -164,6 +174,7 @@ export function audioPickIsRoutable({
baseModel,
tags,
libraryName,
+ audioType,
});
}
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 b2d6198f73f..bf0ab9d85cf 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
@@ -3337,7 +3337,12 @@ export function HubModelPicker({
const hubEvidenceById = useMemo(() => {
const map = new Map<
string,
- { baseModel?: string | null; tags?: string[]; libraryName?: string | null }
+ {
+ baseModel?: string | null;
+ tags?: string[];
+ libraryName?: string | null;
+ audioType?: string | null;
+ }
>();
for (const r of [
...results,
@@ -3357,13 +3362,32 @@ export function HubModelPicker({
// 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;
+ const existing = map.get(c.repo_id);
+ if (existing) {
+ map.set(c.repo_id, {
+ ...existing,
+ audioType: existing.audioType ?? c.audio_type,
+ });
+ continue;
+ }
map.set(c.repo_id, {
baseModel: null,
tags: c.tags,
libraryName: c.library_name,
+ audioType: c.audio_type,
});
}
+ for (const c of cachedGguf) {
+ const existing = map.get(c.repo_id);
+ if (existing) {
+ map.set(c.repo_id, {
+ ...existing,
+ audioType: existing.audioType ?? c.audio_type,
+ });
+ continue;
+ }
+ map.set(c.repo_id, { audioType: c.audio_type });
+ }
return map;
}, [
results,
@@ -3371,6 +3395,7 @@ export function HubModelPicker({
communityQuerySearch.results,
communityBrowse.results,
cachedModels,
+ cachedGguf,
]);
// Tag-accurate capabilities keyed by repo id, pooled from both HF listings, then the
@@ -3446,10 +3471,11 @@ export function HubModelPicker({
audioPickIsRoutable({
id: c.repo_id,
task: c.task,
+ audioType: c.audio_type,
isGguf: true,
isCurated: artifactForRepoId(c.repo_id, AUDIO_CATALOG) !== null,
- // _repo_gguf_task reads these off the arch too, so the same rule holds: a
- // speech tag means llama-csm even when the repo id names another family.
+ // The task and codec both came from GGUF classification; codec provenance
+ // separates runnable Orpheus from unsupported CSM.
taskFromGgufArch: true,
}),
),
@@ -3493,6 +3519,7 @@ export function HubModelPicker({
id: c.repo_id,
tags: c.tags,
libraryName: c.library_name,
+ audioType: c.audio_type,
}) &&
macTtsHubRowIsRunnable({
isMac,
@@ -3550,10 +3577,11 @@ export function HubModelPicker({
audioPickIsRoutable({
id: m.model_id ?? m.id,
task: m.task,
+ audioType: m.audio_type,
isGguf: localModelIsGguf(m),
isCurated: artifactForRepoId(m.model_id ?? m.id, AUDIO_CATALOG) !== null,
- // These rows are tasked by _local_model_task reading the GGUF's own arch,
- // so a text-to-speech tag here means llama-csm, whatever the file is named.
+ // Task and codec came from the filesystem classifier, so a renamed CSM file
+ // cannot borrow an Orpheus-looking path to clear the gate.
taskFromGgufArch: true,
}) &&
// The backend tags every local model with its task for exactly this: on the Images/Video pages a chat GGUF must not be offered.
@@ -3596,10 +3624,11 @@ export function HubModelPicker({
audioPickIsRoutable({
id: m.model_id ?? m.id,
task: m.task,
+ audioType: m.audio_type,
isGguf: localModelIsGguf(m),
isCurated: artifactForRepoId(m.model_id ?? m.id, AUDIO_CATALOG) !== null,
- // These rows are tasked by _local_model_task reading the GGUF's own arch,
- // so a text-to-speech tag here means llama-csm, whatever the file is named.
+ // Task and codec came from the filesystem classifier, so a renamed CSM file
+ // cannot borrow an Orpheus-looking path to clear the gate.
taskFromGgufArch: true,
}) &&
passesTaskGate(
@@ -3645,10 +3674,11 @@ export function HubModelPicker({
audioPickIsRoutable({
id: m.model_id ?? m.id,
task: m.task,
+ audioType: m.audio_type,
isGguf: localModelIsGguf(m),
isCurated: artifactForRepoId(m.model_id ?? m.id, AUDIO_CATALOG) !== null,
- // These rows are tasked by _local_model_task reading the GGUF's own arch,
- // so a text-to-speech tag here means llama-csm, whatever the file is named.
+ // Task and codec came from the filesystem classifier, so a renamed CSM file
+ // cannot borrow an Orpheus-looking path to clear the gate.
taskFromGgufArch: true,
}) &&
passesTaskGate(
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 9823c796c0a..9f5b57a733d 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
@@ -38,6 +38,7 @@ function toCachedGgufRepo(row: CachedInventoryRow): CachedGgufRepo {
last_modified: row.lastModified ?? undefined,
has_vision: row.capabilities.supportsVision,
task: row.task ?? null,
+ audio_type: row.audioType ?? null,
has_variant_state: row.hasVariantState ?? false,
};
}
@@ -51,6 +52,7 @@ function toCachedModelRepo(row: CachedInventoryRow): CachedModelRepo {
size_bytes: row.bytes,
last_modified: row.lastModified ?? undefined,
task: row.task ?? null,
+ audio_type: row.audioType ?? 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".
@@ -68,6 +70,7 @@ function toLocalModelInfo(row: LocalInventoryRow): LocalModelInfo {
model_format: row.modelFormat,
updated_at: row.updatedAt,
task: row.task ?? null,
+ audio_type: row.audioType ?? null,
};
}
diff --git a/studio/frontend/src/lib/model-lifecycle-events.ts b/studio/frontend/src/lib/model-lifecycle-events.ts
index 2b41d1b3847..c850031c1f9 100644
--- a/studio/frontend/src/lib/model-lifecycle-events.ts
+++ b/studio/frontend/src/lib/model-lifecycle-events.ts
@@ -19,8 +19,10 @@ export const MODEL_LIFECYCLE_EVENT = "unsloth:model-lifecycle";
/** Which runtime was released. Only these two own a page holding its status. */
export type EjectedModelRuntime = "image" | "video";
-/** Every runtime the indicator lists. */
-export type ModelRuntime = "chat" | "image" | "video" | "stt";
+/** Every runtime the indicator lists. "tts" shares the chat slot rather than owning one,
+ * and is named apart from "chat" only so chat can tell a load it did not start from
+ * one it did. */
+export type ModelRuntime = "chat" | "image" | "video" | "stt" | "tts";
export type ModelLifecycle = {
runtime: ModelRuntime;
diff --git a/studio/frontend/tests/audio-picker-policy.test.ts b/studio/frontend/tests/audio-picker-policy.test.ts
index 6c596b9e4a5..8669c4ada0b 100644
--- a/studio/frontend/tests/audio-picker-policy.test.ts
+++ b/studio/frontend/tests/audio-picker-policy.test.ts
@@ -597,10 +597,7 @@ test("a local Whisper checkpoint is not advertised as a routable ASR row", () =>
assert.match(source, /pipelineTag: audioPipelineTagFor\(adapter\.audioType, true\)/);
});
-test("an arch-tasked speech GGUF is rejected however its path or repo id is named", () => {
- // text-to-speech is tagged on a GGUF only after reading a llama-csm arch. The family
- // heuristic re-infers from the NAME, so a CSM file parked under a runnable-looking
- // directory used to clear the gate and evict the chat model for a row Audio cannot show.
+test("an arch-tasked speech GGUF routes by detected codec", () => {
const parkedUnderOrpheus = {
id: "/models/orpheus/custom.gguf",
task: "text-to-speech",
@@ -609,20 +606,24 @@ test("an arch-tasked speech GGUF is rejected however its path or repo id is name
};
assert.equal(audioPickIsRoutable(parkedUnderOrpheus), true);
assert.equal(
- audioPickIsRoutable({ ...parkedUnderOrpheus, taskFromGgufArch: true }),
+ audioPickIsRoutable({
+ ...parkedUnderOrpheus,
+ taskFromGgufArch: true,
+ audioType: "csm",
+ }),
false,
);
- // The arch read outranks a curated name match too: llama.cpp has no CSM decoder, so
- // the file is undecodable no matter which catalog id its folder happens to echo.
assert.equal(
audioPickIsRoutable({
...parkedUnderOrpheus,
isCurated: true,
taskFromGgufArch: true,
+ audioType: "csm",
}),
false,
);
- // Same rule on the cached-repo side, where the task comes off the arch as well.
+ // The same speech task is runnable when the backend's GGUF classifier identifies
+ // the ordinary-llama Orpheus build and records its SNAC decoder.
assert.equal(
audioPickIsRoutable({
id: "someone/orpheus-3b-custom-GGUF",
@@ -630,20 +631,20 @@ test("an arch-tasked speech GGUF is rejected however its path or repo id is name
isGguf: true,
isCurated: false,
taskFromGgufArch: true,
+ audioType: "snac",
}),
- false,
+ true,
);
- // Orpheus GGUFs report a plain `llama` arch, so they arrive tagged text-generation and
- // the gate must leave them alone; a non-GGUF CSM still runs on the Transformers path.
+ // Older backends have no provenance field, so their speech GGUF rows remain fail-closed.
assert.equal(
audioPickIsRoutable({
id: "/models/orpheus/custom.gguf",
- task: "text-generation",
+ task: "text-to-speech",
isGguf: true,
isCurated: false,
taskFromGgufArch: true,
}),
- true,
+ false,
);
assert.equal(
audioPickIsRoutable({
@@ -657,6 +658,29 @@ test("an arch-tasked speech GGUF is rejected however its path or repo id is name
);
});
+test("a renamed cached TTS checkpoint routes on its detected codec", () => {
+ assert.equal(
+ communityAudioRowIsRunnable({
+ isStt: false,
+ isTts: true,
+ isGguf: false,
+ id: "someone/renamed-checkpoint",
+ audioType: "snac",
+ }),
+ true,
+ );
+ assert.equal(
+ communityAudioRowIsRunnable({
+ isStt: false,
+ isTts: true,
+ isGguf: true,
+ id: "someone/renamed-checkpoint",
+ audioType: "csm",
+ }),
+ false,
+ );
+});
+
test("every filesystem list passes the arch-tasked flag, not just the policy call", () => {
// The policy is only as good as its call sites: a list that asks without the flag gets
// the name heuristic back and re-opens the hole this gate exists to close.
diff --git a/studio/frontend/tests/chat-model-residency.test.ts b/studio/frontend/tests/chat-model-residency.test.ts
index f505091b515..5359cda6940 100644
--- a/studio/frontend/tests/chat-model-residency.test.ts
+++ b/studio/frontend/tests/chat-model-residency.test.ts
@@ -192,17 +192,18 @@ test("an eviction drops the pick, not just the loaded marks", () => {
"utf8",
);
// Anchored on the branch, not on the file: other catches sit above it now.
- const branchStart = hook.indexOf("} else if (!statusRes.active_model");
+ // chatActiveModel, not status.active_model: this branch owns the resident-TTS case too.
+ const branchStart = hook.indexOf("} else if (!chatActiveModel");
const branch = hook.slice(
branchStart,
hook.indexOf("} catch (error) {", branchStart),
);
assert.match(branch, /clearCheckpoint\(\)/);
- // Guarded twice: a model that was never confirmed resident has nothing to
- // lose, and a load in flight reports no active model either.
+ // A first speech-only status is definitive too: it must clear a persisted
+ // pick even before this tab has observed a resident Chat model.
assert.match(
branch,
- /if \(wasResident && selectedCheckpoint && !modelLoading\)/,
+ /\(wasResident \|\| isSpeechOnlyStatus\(statusRes\)\)[\s\S]*selectedCheckpoint[\s\S]*!modelLoading/,
);
});
diff --git a/studio/frontend/tests/chat-speech-model-not-adopted.test.ts b/studio/frontend/tests/chat-speech-model-not-adopted.test.ts
new file mode 100644
index 00000000000..b19fb586a86
--- /dev/null
+++ b/studio/frontend/tests/chat-speech-model-not-adopted.test.ts
@@ -0,0 +1,191 @@
+// 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 loads a TTS model into the single slot chat reads, and chat's local
+// selection is re-derived from /status on every mount, so picking a voice silently made
+// it the chat model and the next turn came back as SYNTHESIZED speech. Nothing refused
+// it anywhere. These pin the places that now do.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+import {
+ type SpeechOnlyStatusInput,
+ isIdleUnloadedStatus,
+ isSpeechOnlyStatus,
+} from "../src/features/chat/lib/speech-only-status.ts";
+
+const status = (fields: SpeechOnlyStatusInput): SpeechOnlyStatusInput => fields;
+
+const readSource = (path: string) =>
+ readFileSync(new URL(path, import.meta.url), "utf8");
+
+test("a resident TTS model reads as speech-only", () => {
+ for (const audioType of ["snac", "csm", "bicodec", "dac"]) {
+ assert.equal(
+ isSpeechOnlyStatus(status({ is_audio: true, audio_type: audioType })),
+ true,
+ audioType,
+ );
+ }
+});
+
+test("an ordinary chat model is not speech-only", () => {
+ assert.equal(isSpeechOnlyStatus(status({})), false);
+ assert.equal(isSpeechOnlyStatus(status({ is_audio: false })), false);
+});
+
+// Whisper answers with transcripts, and the chat route branches on it separately.
+test("whisper is not speech-only", () => {
+ assert.equal(
+ isSpeechOnlyStatus(status({ is_audio: true, audio_type: "whisper" })),
+ false,
+ );
+});
+
+// Gemma 3n takes audio IN and answers in text: treating it as speech-only would lock a
+// real chat model out of chat.
+test("an audio-input chat model is not speech-only", () => {
+ assert.equal(
+ isSpeechOnlyStatus(status({ is_audio: true, audio_type: "audio_vlm" })),
+ false,
+ );
+});
+
+test("only an armed idle unload preserves an empty resident slot", () => {
+ assert.equal(isIdleUnloadedStatus(status({ active_model: null }), true), true);
+ assert.equal(isIdleUnloadedStatus(status({ active_model: null }), false), false);
+ assert.equal(
+ isIdleUnloadedStatus(
+ status({ active_model: "my-voice", is_audio: true, audio_type: "snac" }),
+ true,
+ ),
+ false,
+ );
+});
+
+test("chat does not adopt the server's model when it only speaks", () => {
+ const source = readSource(
+ "../src/features/chat/lib/apply-inference-status-to-store.ts",
+ );
+ // In tryAdoptServerActiveModel, not resolveInferenceCheckpointId: the loaded-models
+ // indicator and the API monitor share that resolver and must go on naming one.
+ const adopt = source.slice(
+ source.indexOf("export async function tryAdoptServerActiveModel"),
+ );
+ assert.match(adopt, /isSpeechOnlyStatus\(status\)/);
+ const resolver = source.slice(
+ source.indexOf("export function resolveInferenceCheckpointId"),
+ source.indexOf("function ensureActiveModelInStoreList"),
+ );
+ assert.doesNotMatch(
+ resolver,
+ /isSpeechOnlyStatus/,
+ "the shared resolver must keep answering for a resident TTS model",
+ );
+});
+
+test("the mount-time status sync treats a speech model as an empty slot", () => {
+ const hook = readSource(
+ "../src/features/chat/hooks/use-chat-model-runtime.ts",
+ );
+ assert.match(
+ hook,
+ /const chatActiveModel =\s*\n?\s*statusRes\.active_model && !isSpeechOnlyStatus\(statusRes\);/,
+ );
+ // Both edges, or the eviction branch would stop clearing a stale pick.
+ assert.match(hook, /if \(chatActiveModel && !isExternalSelectionActive\)/);
+ assert.match(
+ hook,
+ /\} else if \(!chatActiveModel && !isExternalSelectionActive\)/,
+ );
+ assert.match(
+ hook,
+ /\(wasResident \|\| isSpeechOnlyStatus\(statusRes\)\)[\s\S]*selectedCheckpoint[\s\S]*!modelLoading/,
+ "the first speech-only status must clear a persisted Chat pick",
+ );
+});
+
+test("a TTS load announces its own runtime so chat re-reads the slot", () => {
+ const events = readSource("../src/lib/model-lifecycle-events.ts");
+ assert.match(events, /export type ModelRuntime =[^;]*"tts"/);
+
+ // Chat ignores its own loads when reconciling, so a TTS load announced as "chat" left
+ // chat naming a model the Audio page had evicted.
+ const audio = readSource("../src/features/audio/audio-page.tsx");
+ assert.match(audio, /runtime: "tts",/);
+ const hook = readSource(
+ "../src/features/chat/hooks/use-chat-model-runtime.ts",
+ );
+ assert.match(
+ hook,
+ /if \(runtime === "chat" \|\| runtime === "stt"\) return;/,
+ );
+ assert.doesNotMatch(hook, /runtime === "tts"\) return;/);
+});
+
+test("chat re-reads status when a different tab returns to the foreground", () => {
+ const hook = readSource(
+ "../src/features/chat/hooks/use-chat-model-runtime.ts",
+ );
+ assert.match(hook, /subscribeResidentStatusRefresh\(\(\) => \{/);
+ assert.match(
+ hook,
+ /void refresh\(\{ includeLoras: false, preserveIdleUnloaded: true \}\);/,
+ );
+});
+
+// tryAdoptServerActiveModel is not the only door into params.checkpoint: these two call
+// sites resolve a resident model into the chat store on their own.
+
+test("the Hub does not pin a speech model as the chat checkpoint", () => {
+ const hub = readSource("../src/features/hub/hub-page.tsx");
+ const adopt = hub.slice(
+ hub.indexOf("adoptResidentModelStatus("),
+ hub.indexOf("registerRefresh(", hub.indexOf("adoptResidentModelStatus(")),
+ );
+ assert.match(
+ adopt,
+ /checkpointId: isSpeechOnlyStatus\(status\)\s*\n?\s*\? null\s*\n?\s*: resolveInferenceCheckpointId\(status\),/,
+ );
+ // null, not an early return: the empty-slot branch clears the pick the Audio load
+ // evicted, and skipping the call would leave it pointing at a 400.
+ assert.doesNotMatch(adopt, /if \(isSpeechOnlyStatus\(status\)\) return/);
+ // And say WHY it is null: a bare null reads as an idle eviction, which the helper
+ // deliberately keeps. hub-resident-status pins that branch.
+ assert.match(adopt, /speechOnly: isSpeechOnlyStatus\(status\),/);
+});
+
+test("a queued local thread does not adopt a speech model either", () => {
+ const adapter = readSource("../src/features/chat/api/chat-adapter.ts");
+ const queued = adapter.slice(
+ adapter.indexOf("async function resolveQueuedEmptyLocalModel"),
+ adapter.indexOf("export function createOpenAIStreamAdapter"),
+ );
+ assert.match(
+ queued,
+ /const checkpoint = isSpeechOnlyStatus\(status\)\s*\n?\s*\? null\s*\n?\s*: resolveInferenceCheckpointId\(status\);/,
+ );
+});
+
+test("the auto-load sweep skips every task chat cannot answer", () => {
+ const adapter = readSource("../src/features/chat/api/chat-adapter.ts");
+ const set = adapter.slice(
+ adapter.indexOf("const NON_CHAT_TASKS"),
+ adapter.indexOf("]);", adapter.indexOf("const NON_CHAT_TASKS")),
+ );
+ for (const task of [
+ "text-to-image",
+ "text-to-video",
+ "image-diffusion-unsupported",
+ "text-to-speech",
+ "text-to-audio",
+ "audio-to-audio",
+ "automatic-speech-recognition",
+ ]) {
+ assert.ok(set.includes(`"${task}"`), task);
+ }
+ // Both the cached-repo and the on-disk filter, or one inventory still offers them.
+ assert.equal(adapter.match(/NON_CHAT_TASKS\.has\(/g)?.length, 2);
+});
diff --git a/studio/frontend/tests/hub-resident-status.test.ts b/studio/frontend/tests/hub-resident-status.test.ts
index 90d2045c594..9c201697476 100644
--- a/studio/frontend/tests/hub-resident-status.test.ts
+++ b/studio/frontend/tests/hub-resident-status.test.ts
@@ -173,6 +173,41 @@ test("an empty status leaves the checkpoint pinned while idle unload is armed",
assert.equal(adopted, false);
});
+test("a speech model in the slot clears the pick even while idle unload is armed", () => {
+ // Not the idle eviction the rule above is about: an Audio load took the single slot and
+ // no stash reloads the chat model, so holding the pick left the Hub calling it Loaded.
+ const cleared: string[] = [];
+ const adopted = adoptResidentModelStatus(
+ { checkpointId: null, ggufVariant: null, speechOnly: true },
+ emptyStore({
+ checkpoint: "/models/llama.gguf",
+ activeGgufVariant: "Q4_K_M",
+ idleUnloadArmed: true,
+ }),
+ {
+ ...refusing({
+ setCheckpoint: "a speech model is not something chat may be pinned to",
+ applyStatus: "its status describes a model chat is not talking to",
+ }),
+ clearCheckpoint: () => {
+ cleared.push("cleared");
+ },
+ },
+ );
+ assert.equal(adopted, true);
+ assert.deepEqual(cleared, ["cleared"]);
+});
+
+test("a speech model does not fight a load this tab started", () => {
+ // The load owns the store until it settles, speech or not.
+ const adopted = adoptResidentModelStatus(
+ { checkpointId: null, ggufVariant: null, speechOnly: true },
+ emptyStore({ checkpoint: "/models/llama.gguf", modelLoading: true }),
+ refusing({ clearCheckpoint: "the load owns the store until it settles" }),
+ );
+ assert.equal(adopted, false);
+});
+
test("an empty status leaves an external pick alone", () => {
const adopted = adoptResidentModelStatus(
{ checkpointId: null, ggufVariant: null },
diff --git a/tests/studio/playwright_chat_ui.py b/tests/studio/playwright_chat_ui.py
index 0ecd0c0e3c0..be3f30db5bc 100644
--- a/tests/studio/playwright_chat_ui.py
+++ b/tests/studio/playwright_chat_ui.py
@@ -1200,7 +1200,7 @@ with sync_playwright() as p:
"""(args) => {
const [secondPrompt, holdMs] = args;
window.__unslothRapid = {
- intercepted: false, submitted: false, queueSeen: false,
+ intercepted: false, preparing: false, submitted: false, queueSeen: false,
observed: false, error: null, seen: [], holdUntil: 0,
};
const state = window.__unslothRapid;
@@ -1208,7 +1208,11 @@ with sync_playwright() as p:
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const sendFollowUp = (deadline) => {
- if (state.submitted || state.error) return;
+ if (state.preparing || state.submitted || state.error) return;
+ if (deadline === undefined) deadline = Date.now() + 5000;
+ if (state.holdUntil) {
+ deadline = Math.min(deadline, state.holdUntil - 250);
+ }
// Re-query, and retry: this is the chat's first message, so
// sending it swaps the welcome composer for the dock composer.
// A node captured earlier is detached, and for a short window
@@ -1217,14 +1221,10 @@ with sync_playwright() as p:
'textarea[aria-label="Message input"]'
);
if (!composer || !composer.isConnected || !composer.form) {
- if (deadline === undefined) deadline = Date.now() + 5000;
// Never retry past the hold. The response is released when
// it expires, so a submit after that races a buffered reply
// finishing first and would report a queue failure for an
// application that behaved correctly.
- if (state.holdUntil) {
- deadline = Math.min(deadline, state.holdUntil - 250);
- }
if (Date.now() > deadline) {
state.error = "no connected composer for the follow-up";
return;
@@ -1239,8 +1239,32 @@ with sync_playwright() as p:
).set;
setValue.call(composer, secondPrompt);
composer.dispatchEvent(new Event("input", { bubbles: true }));
- composer.form.requestSubmit();
- state.submitted = true;
+ // Synthetic input and requestSubmit in the same JS turn can make
+ // the form callback read the previous controlled value. That is
+ // not how a user types, and it leaves the new text visible while
+ // the test incorrectly records a submit. Let React publish the
+ // input, then re-check the composer because the welcome bar can
+ // be replaced by the dock bar during this frame.
+ state.preparing = true;
+ requestAnimationFrame(() => {
+ state.preparing = false;
+ const current = document.querySelector(
+ 'textarea[aria-label="Message input"]'
+ );
+ if (
+ !current || !current.isConnected || !current.form ||
+ current.value !== secondPrompt
+ ) {
+ if (Date.now() > deadline) {
+ state.error = "follow-up composer did not settle";
+ return;
+ }
+ setTimeout(() => sendFollowUp(deadline), 25);
+ return;
+ }
+ current.form.requestSubmit();
+ state.submitted = true;
+ });
};
window.fetch = async (...a) => {
diff --git a/tests/studio/test_chat_autoload_failure_gate.py b/tests/studio/test_chat_autoload_failure_gate.py
index e8de4acba6e..26b05c181a9 100644
--- a/tests/studio/test_chat_autoload_failure_gate.py
+++ b/tests/studio/test_chat_autoload_failure_gate.py
@@ -525,6 +525,18 @@ async function loadModel(payload: any) {
if (result instanceof Error) throw result;
return result;
}
+
+// The speech-only verdict, mirroring
+// studio/frontend/src/features/chat/lib/speech-only-status.ts. Real logic rather than a
+// neutral stub: a stub that always answered false would keep every scenario green if the
+// queued path's guard were removed.
+export function isSpeechOnlyStatus(status: any): boolean {
+ return (
+ Boolean(status?.is_audio) &&
+ status?.audio_type !== "whisper" &&
+ status?.audio_type !== "audio_vlm"
+ );
+}
"""
SCENARIO_HELPERS = """
diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.py
index d48d4828aa8..7fef8190335 100644
--- a/tests/studio/test_model_picker_contracts.py
+++ b/tests/studio/test_model_picker_contracts.py
@@ -2868,8 +2868,14 @@ def test_the_hub_settings_page_matches_a_resident_path_loaded_model():
)
assert "loadedConfig={settingsTargetIsResident ? activeModelConfig : null}" in hub
assert "settingsTargetIsResident ? activeGgufContextLength : null" in hub
- # The loadable identifier, as every other status reader records it.
- assert "checkpointId: resolveInferenceCheckpointId(status)," in hub
+ # The loadable identifier, as every other status reader records it -- except for a
+ # speech model, which chat cannot adopt at all. speechOnly rides beside the null so
+ # the helper can tell it from the empty slot the idle-unload rule is about.
+ assert (
+ "checkpointId: isSpeechOnlyStatus(status) ? null "
+ ": resolveInferenceCheckpointId(status), "
+ "speechOnly: isSpeechOnlyStatus(status)," in hub
+ )
assert "setCheckpoint(status.active_model" not in hub
chat = " ".join(_read("features/chat/lib/apply-inference-status-to-store.ts").split())
assert "return status.model_identifier ?? status.active_model;" in chat, "the rule this mirrors"
@@ -3096,7 +3102,9 @@ def test_an_empty_status_is_read_against_the_idle_unload_setting():
# A failed read keeps the last answer. The default is disarmed, which is the side
# that clears the checkpoint, so falling back to it would drop a live selection.
assert ".catch(() => idleUnloadArmed.current)" in hub
- assert "if (state.idleUnloadArmed) { return false; }" in adopt
+ # An Audio load taking the single slot is not an idle eviction: nothing stashes the
+ # chat model, so the exemption must not swallow that case.
+ assert "if (state.idleUnloadArmed && !status.speechOnly) { return false; }" in adopt
assert "actions.clearCheckpoint?.();" in adopt
@@ -3441,16 +3449,22 @@ def test_indexed_local_loads_are_remembered_without_bypassing_leases():
assert "token" not in store.lower().replace("isPathLikeId", "")
-def test_autoload_skips_image_and_video_rows():
- """The backend tags a row with a task only for image/video models, and the
- picker routes those away on click. A background load has no routing step."""
+def test_autoload_skips_rows_chat_cannot_answer():
+ """The backend tags a row with a task only for the models that own another page,
+ and the picker routes those away on click. A background load has no routing step.
+ The audio tasks are here because the chat route answers a turn on a speech model by
+ synthesizing the prompt rather than refusing it, so nothing downstream catches it."""
src = _read("features/chat/api/chat-adapter.ts")
- tasks = src.split("const IMAGE_OR_VIDEO_TASKS", 1)[1].split("]", 1)[0]
+ tasks = src.split("const NON_CHAT_TASKS", 1)[1].split("]", 1)[0]
assert '"text-to-image"' in tasks
assert '"text-to-video"' in tasks
assert '"image-diffusion-unsupported"' in tasks
+ assert '"text-to-speech"' in tasks
+ assert '"text-to-audio"' in tasks
+ assert '"audio-to-audio"' in tasks
+ assert '"automatic-speech-recognition"' in tasks
policy = src.split("function isAutoLoadableLocalRow", 1)[1].split("\n}", 1)[0]
- assert 'IMAGE_OR_VIDEO_TASKS.has(row.task ?? "")' in policy
+ assert 'NON_CHAT_TASKS.has(row.task ?? "")' in policy
def test_remembered_matching_uses_the_same_case_rules_as_the_dedupe_key():
@@ -3559,6 +3573,16 @@ def test_cached_rows_classify_chat_capability_too():
assert "_local_transformers_can_chat(classify_snapshot)" in fields
+def test_cached_codec_evidence_enriches_an_existing_hub_result():
+ """Search results outrank cached metadata, but they must not erase a decoder
+ discovered from the local tokenizer files for the same repo."""
+ src = _read("features/model-picker/components/model-selector/pickers.tsx")
+ evidence = src.split("const hubEvidenceById = useMemo", 1)[1]
+ evidence = evidence.split("const capsById = useMemo", 1)[0]
+ assert evidence.count("const existing = map.get(c.repo_id);") == 2
+ assert evidence.count("audioType: existing.audioType ?? c.audio_type") == 2
+
+
def test_every_load_target_comparison_uses_the_same_case_rules():
"""Source dedupe, remembered matching, and tried-candidate keys all compare
load targets, so they must agree on POSIX case."""
@@ -3582,16 +3606,16 @@ def test_the_default_variant_lookup_takes_the_run_signal():
assert helper.index("} catch {") < helper.index("abortSignal?.throwIfAborted();")
-def test_cached_rows_get_the_same_image_and_video_gate_as_local_rows():
- """Cached diffusion repos carry their task on the row and report can_chat
- true on file format alone."""
+def test_cached_rows_get_the_same_non_chat_gate_as_local_rows():
+ """Cached diffusion and speech repos carry their task on the row and report can_chat
+ true on file format alone. Both inventories, or one of them still offers the row."""
src = _read("features/chat/api/chat-adapter.ts")
cached = src.split("function isChattableCachedRepo", 1)[1].split("\n}\n", 1)[0]
- assert 'IMAGE_OR_VIDEO_TASKS.has(repo.task ?? "")' in cached
+ assert 'NON_CHAT_TASKS.has(repo.task ?? "")' in cached
local = src.split("function isAutoLoadableLocalRow", 1)[1].split("\n}", 1)[0]
- assert 'IMAGE_OR_VIDEO_TASKS.has(row.task ?? "")' in local
+ assert 'NON_CHAT_TASKS.has(row.task ?? "")' in local
# A chat GGUF is tagged text-generation, so the gate is a list, not "has a task".
- tasks = src.split("const IMAGE_OR_VIDEO_TASKS", 1)[1].split("]", 1)[0]
+ tasks = src.split("const NON_CHAT_TASKS", 1)[1].split("]", 1)[0]
assert '"text-generation"' not in tasks