Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: add Qwen3-ASR dictation, cancellable downloads, and a download prompt (#7835)

Michael Hanf61103d411fc
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.py
index b33cbd49207..2ee827ee181 100644
--- a/studio/backend/core/inference/orchestrator.py
+++ b/studio/backend/core/inference/orchestrator.py
@@ -26,7 +26,7 @@ import time
import uuid
from io import BytesIO
from pathlib import Path
-from typing import Any, Generator, Optional, Tuple, Union
+from typing import Any, Generator, Optional, Sequence, Tuple, Union
from utils.hardware import get_device, prepare_gpu_selection
from utils.utils import hf_env_offline
@@ -1432,6 +1432,27 @@ class InferenceOrchestrator:
self.models.clear()
return True
+ # --- Dictation models -------------------------------------------------
+ # These run in the STT sidecars (whisper-server, llama-server, Transformers
+ # in process), not the chat worker. Their lifecycle goes through here all
+ # the same, so one object knows everything that is resident and Voice
+ # settings and Model Hub cannot report different things about one model.
+
+ def load_stt_model(self, model: Optional[str], engine: str) -> None:
+ """Make a dictation model resident on its sidecar."""
+ from core.inference import stt_registry
+ stt_registry.load(model, engine)
+
+ def unload_stt_model(self, engines: Optional[Sequence[str]] = None) -> list:
+ """Release dictation models (all engines by default); returns refusals."""
+ from core.inference import stt_registry
+ return stt_registry.unload(engines)
+
+ def resident_stt_model(self) -> dict:
+ """What dictation holds, alongside active_model_name for chat."""
+ from core.inference import stt_registry
+ return stt_registry.resident()
+
def unload_model(self, model_name: str) -> bool:
"""Unload a model from the subprocess."""
# active_model_name can differ in case from the client's raw /unload name (the
diff --git a/studio/backend/core/inference/stt_download_worker.py b/studio/backend/core/inference/stt_download_worker.py
new file mode 100644
index 00000000000..9555c319059
--- /dev/null
+++ b/studio/backend/core/inference/stt_download_worker.py
@@ -0,0 +1,122 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Out-of-process byte transfer for one dictation model download.
+
+The sidecars plan the download in-process and run only the transfer here. A
+thread cannot be interrupted, so cancelling means terminating a process: like
+``hub.workers.hf_download``, cancel is a SIGTERM and the negative returncode is
+what the caller reads as cancelled rather than failed. HF partials resume
+byte-exact, so a SIGTERM costs only the chunk in flight.
+"""
+
+from __future__ import annotations
+
+import argparse
+import os
+import subprocess
+import sys
+from pathlib import Path
+from typing import Optional, Sequence
+
+
+def backend_dir() -> Path:
+ return Path(__file__).resolve().parent.parent.parent
+
+
+def spawn_download(args: Sequence[str], hf_token: Optional[str] = None) -> subprocess.Popen:
+ """Run this module as a child process performing ``args``' download.
+
+ The token travels in the environment, never argv, so it stays out of ``ps``.
+ """
+ cwd = backend_dir()
+ from utils.hf_cache_settings import get_hf_cache_paths
+
+ env = get_hf_cache_paths().child_env()
+ env["HF_HUB_DISABLE_PROGRESS_BARS"] = "1"
+ env["HF_HUB_DISABLE_TELEMETRY"] = "1"
+ # Parallel Range chunks leave sparse partials a resumed sequential writer
+ # cannot reuse, which defeats the point of cancelling.
+ env["HF_HUB_ENABLE_HF_TRANSFER"] = "0"
+ # Replace the inherited credentials only when the caller supplied one. With
+ # no token, leave the ambient login alone: the parent plans the download
+ # with it, so scrubbing here would fail gated repos that used to work.
+ if hf_token:
+ env["HF_HUB_DISABLE_IMPLICIT_TOKEN"] = "0"
+ for token_key in (
+ "HF_TOKEN",
+ "HF_HUB_TOKEN",
+ "HUGGING_FACE_HUB_TOKEN",
+ "HUGGINGFACE_HUB_TOKEN",
+ "HUGGINGFACEHUB_API_TOKEN",
+ ):
+ env.pop(token_key, None)
+ env["HF_TOKEN"] = hf_token
+ existing_path = env.get("PYTHONPATH", "")
+ env["PYTHONPATH"] = f"{cwd}{os.pathsep}{existing_path}" if existing_path else str(cwd)
+ from utils.process_lifetime import adopt_pid, child_popen_kwargs
+
+ process = subprocess.Popen(
+ [sys.executable, "-m", "core.inference.stt_download_worker", *args],
+ env = env,
+ cwd = str(cwd),
+ stdout = subprocess.DEVNULL,
+ stderr = subprocess.PIPE,
+ # Die with Studio: a detached worker would keep pulling gigabytes after
+ # the app closed, with nothing left able to stop it.
+ **child_popen_kwargs(),
+ )
+ adopt_pid(process.pid) # terminate_all backstop for graceful exits
+ return process
+
+
+def reap_download(process: subprocess.Popen) -> bytes:
+ """Wait for a worker and drop its PID. Returns its stderr.
+
+ Callers pair every spawn with this: an adopted PID that outlives the process
+ can be reused by something unrelated, which terminate_all would then signal
+ (macOS and Windows cannot pin a PID to an identity the way /proc does).
+ """
+ from utils.process_lifetime import forget_pid
+
+ try:
+ _, stderr = process.communicate()
+ finally:
+ forget_pid(process.pid)
+ return stderr or b""
+
+
+def main(argv: Optional[Sequence[str]] = None) -> int:
+ parser = argparse.ArgumentParser(description = "Download one dictation model.")
+ parser.add_argument("--repo-id", required = True)
+ # GGML is a single file; Transformers is a snapshot pinned to the revision
+ # the sidecar already validated.
+ parser.add_argument("--filename")
+ parser.add_argument("--revision")
+ parser.add_argument("--allow-pattern", action = "append", default = [])
+ args = parser.parse_args(argv)
+
+ token = os.environ.get("HF_TOKEN") or None
+ if args.filename:
+ from huggingface_hub import hf_hub_download
+ hf_hub_download(
+ repo_id = args.repo_id,
+ filename = args.filename,
+ revision = args.revision,
+ token = token,
+ )
+ return 0
+
+ from huggingface_hub import snapshot_download
+
+ snapshot_download(
+ repo_id = args.repo_id,
+ revision = args.revision,
+ allow_patterns = list(args.allow_pattern) or None,
+ token = token,
+ )
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/studio/backend/core/inference/stt_ggml_sidecar.py b/studio/backend/core/inference/stt_ggml_sidecar.py
index 89e8cf1d05d..2ae522071f3 100644
--- a/studio/backend/core/inference/stt_ggml_sidecar.py
+++ b/studio/backend/core/inference/stt_ggml_sidecar.py
@@ -342,11 +342,17 @@ def _whisper_server_child_env(binary: str) -> dict[str, str]:
def _cached_model_path(model_id: str) -> Optional[str]:
"""Path of a fully downloaded GGML file in the shared HF cache, else None."""
from huggingface_hub import hf_hub_download
+
+ from core.inference.stt_sidecar import _active_hf_hub_cache
+
try:
return hf_hub_download(
repo_id = GGML_STT_REPOS[model_id],
filename = GGML_STT_MODELS[model_id],
local_files_only = True,
+ # The worker spawns with get_hf_cache_paths(), so a cache relocated
+ # in Studio settings is written there and has to be read there too.
+ cache_dir = str(_active_hf_hub_cache()),
)
except Exception:
return None
@@ -358,10 +364,12 @@ class _GgmlDownloadState:
def __init__(self) -> None:
self._lock = threading.Lock()
self._thread: Optional[threading.Thread] = None
+ self._process: Optional[subprocess.Popen] = None
self._model_id: Optional[str] = None
self._error: Optional[str] = None
self._total_bytes: Optional[int] = None
self._etag: Optional[str] = None
+ self._cancelled = False
def status(self) -> dict:
with self._lock:
@@ -370,10 +378,25 @@ class _GgmlDownloadState:
"downloading": downloading,
"model": self._model_id if downloading else None,
"error": self._error,
+ "cancelled": self._cancelled,
"bytes_total": self._total_bytes if downloading else None,
"bytes_done": self._incomplete_bytes() if downloading else None,
}
+ def cancel(self) -> bool:
+ """Stop an in-flight download. False when none was running.
+
+ The partial blob stays cached, so a restart resumes from it.
+ """
+ with self._lock:
+ if self._thread is None or not self._thread.is_alive():
+ return False
+ self._cancelled = True
+ process = self._process
+ if process is not None and process.poll() is None:
+ process.terminate()
+ return True
+
def _incomplete_bytes(self) -> Optional[int]:
"""Best-effort progress: size of the in-flight blob in the HF cache.
@@ -381,17 +404,15 @@ class _GgmlDownloadState:
etag, else the largest in-flight blob.
"""
try:
- from huggingface_hub.constants import HF_HUB_CACHE
+ from core.inference.stt_sidecar import _repo_cache_dir
# Caller may hold the non-reentrant self._lock; bare reads are safe.
model_id = self._model_id
if not model_id:
return None
- repo_dir = (
- Path(HF_HUB_CACHE)
- / f"models--{GGML_STT_REPOS[model_id].replace('/', '--')}"
- / "blobs"
- )
+ # The active cache, not the import-time constant: the worker writes
+ # to whichever one Studio settings point at.
+ repo_dir = _repo_cache_dir(GGML_STT_REPOS[model_id]) / "blobs"
if not repo_dir.is_dir():
return None
etag = self._etag
@@ -422,6 +443,8 @@ class _GgmlDownloadState:
self._error = None
self._total_bytes = None
self._etag = None
+ self._cancelled = False
+ self._process = None
thread = threading.Thread(target = self._run, args = (model_id, hf_token), daemon = True)
self._thread = thread
thread.start()
@@ -430,11 +453,8 @@ class _GgmlDownloadState:
repo_id = GGML_STT_REPOS[model_id]
filename = GGML_STT_MODELS[model_id]
try:
- from huggingface_hub import (
- get_hf_file_metadata,
- hf_hub_download,
- hf_hub_url,
- )
+ from huggingface_hub import get_hf_file_metadata, hf_hub_url
+
try:
# One HEAD request for the total and etag.
meta = get_hf_file_metadata(hf_hub_url(repo_id, filename), token = hf_token or None)
@@ -443,11 +463,30 @@ class _GgmlDownloadState:
self._etag = meta.etag
except Exception:
pass
- hf_hub_download(
- repo_id = repo_id,
- filename = filename,
- token = hf_token or None,
+ # Out of process so cancel() can terminate it; a thread blocked in
+ # hf_hub_download could not be interrupted.
+ from core.inference.stt_download_worker import spawn_download
+
+ process = spawn_download(
+ ["--repo-id", repo_id, "--filename", filename],
+ hf_token = hf_token or None,
)
+ with self._lock:
+ if self._cancelled:
+ # cancel() landed between start() and the spawn.
+ process.terminate()
+ self._process = process
+ _, stderr = process.communicate()
+ if process.returncode == 0:
+ return
+ with self._lock:
+ if self._cancelled or process.returncode < 0:
+ self._cancelled = True
+ return
+ detail = (stderr or b"").decode("utf-8", "replace").strip()
+ logger.warning("GGUF STT download failed for %s: %s", model_id, detail)
+ with self._lock:
+ self._error = f"Download failed for '{model_id}'."
except Exception as exc:
logger.warning("GGUF STT download failed for %s: %s", model_id, exc)
with self._lock:
@@ -465,6 +504,10 @@ def download_status() -> dict:
return _download_state.status()
+def cancel_model_download() -> bool:
+ return _download_state.cancel()
+
+
# ---------------------------------------------------------------------------
# WAV packaging
# ---------------------------------------------------------------------------
diff --git a/studio/backend/core/inference/stt_mtmd_sidecar.py b/studio/backend/core/inference/stt_mtmd_sidecar.py
new file mode 100644
index 00000000000..7f7885e0d7c
--- /dev/null
+++ b/studio/backend/core/inference/stt_mtmd_sidecar.py
@@ -0,0 +1,766 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""llama.cpp multimodal (mtmd) speech-to-text sidecar for Studio dictation.
+
+whisper.cpp loads only the Whisper architecture, so newer ASR models run through
+llama.cpp instead: a text model plus an audio mmproj, served by `llama-server`
+and driven by the OpenAI audio content part.
+
+Owns one `llama-server` on an ephemeral 127.0.0.1 port, loaded on demand and
+unloaded after the same keep-alive as the other sidecars. Each model is two GGUF
+files, so downloads run the shared worker twice.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import socket
+import subprocess
+import threading
+import time
+import urllib.request
+from contextlib import contextmanager
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Iterator, Optional
+
+from loggers import get_logger
+
+from utils.process_lifetime import adopt_pid, child_popen_kwargs, forget_pid
+
+from core.inference.stt_ggml_sidecar import _pcm_to_wav_bytes
+from core.inference.stt_sidecar import (
+ STT_KEEP_ALIVE_SECONDS,
+ SttLoadCancelledError,
+ SttModelBusyError,
+ SttModelIdError,
+ SttModelNotDownloadedError,
+ SttUnavailableError,
+ _decode_audio_bounded,
+ _TARGET_SAMPLE_RATE,
+ _training_active,
+ normalize_whisper_language,
+)
+
+logger = get_logger(__name__)
+
+
+@dataclass(frozen = True)
+class MtmdSttModel:
+ repo: str
+ model_file: str
+ mmproj_file: str
+ label: str
+ # Qwen3-ASR emits "language English<asr_text>" before the transcript.
+ transcript_marker: Optional[str] = None
+
+
+MTMD_STT_MODELS: dict[str, MtmdSttModel] = {
+ "qwen3-asr-0.6b": MtmdSttModel(
+ repo = "unslothai/Qwen3-ASR-0.6B-GGUF",
+ model_file = "Qwen3-ASR-0.6B-Q8_0.gguf",
+ mmproj_file = "mmproj-Qwen3-ASR-0.6B-Q8_0.gguf",
+ label = "Qwen3-ASR 0.6B",
+ transcript_marker = "<asr_text>",
+ ),
+ "qwen3-asr-1.7b": MtmdSttModel(
+ repo = "unslothai/Qwen3-ASR-1.7B-GGUF",
+ model_file = "Qwen3-ASR-1.7B-Q8_0.gguf",
+ mmproj_file = "mmproj-Qwen3-ASR-1.7B-Q8_0.gguf",
+ label = "Qwen3-ASR 1.7B",
+ transcript_marker = "<asr_text>",
+ ),
+}
+# Voxtral Mini is left out: in chat mode it answers the audio instead of
+# transcribing it, and drops sentences when it complies. Parakeet and Nemotron
+# ASR are too: llama.cpp has the audio graphs but not the text architectures.
+
+_TRANSCRIBE_PROMPT = "Transcribe the audio."
+# Output cap per second of audio. Speech runs about 3 tokens a second in
+# English and more in scripts with no word boundaries, so this is deliberately
+# generous: generation stops at EOS long before it, and the cap only exists so
+# a looping model cannot run to the request timeout.
+_TRANSCRIPT_TOKENS_PER_SECOND = 30
+_MIN_TRANSCRIPT_TOKENS = 512
+# Well under any of these models' trained context, which also has to hold the
+# audio. llama-server is left on its default context (loaded from the model).
+_MAX_TRANSCRIPT_TOKENS = 16384
+
+
+def _transcript_token_budget(audio_seconds: Optional[float]) -> int:
+ """Output cap for a clip. A fixed one silently truncated long audio."""
+ if not audio_seconds or audio_seconds <= 0:
+ return _MIN_TRANSCRIPT_TOKENS
+ scaled = int(audio_seconds * _TRANSCRIPT_TOKENS_PER_SECOND)
+ return max(_MIN_TRANSCRIPT_TOKENS, min(scaled, _MAX_TRANSCRIPT_TOKENS))
+
+
+_SERVER_START_TIMEOUT_SECONDS = 180.0
+_TRANSCRIBE_TIMEOUT_SECONDS = 600.0
+
+
+def resolve_mtmd_model_id(model: Optional[str]) -> str:
+ """Validate a curated mtmd model id. Custom repos are not supported here."""
+ normalized = (model or "").strip()
+ if normalized in MTMD_STT_MODELS:
+ return normalized
+ raise SttModelIdError(
+ f"STT model '{model}' is not a curated llama.cpp dictation model. "
+ f"Choose one of: {', '.join(MTMD_STT_MODELS)}."
+ )
+
+
+def is_mtmd_model(model: Optional[str]) -> bool:
+ return (model or "").strip() in MTMD_STT_MODELS
+
+
+def find_llama_server_binary() -> Optional[str]:
+ from core.inference.llama_cpp import LlamaCppBackend
+ return LlamaCppBackend._find_llama_server_binary()
+
+
+def is_available() -> bool:
+ """True when llama-server is installed and audio can be decoded."""
+ if find_llama_server_binary() is None:
+ return False
+ try:
+ import av # noqa: F401
+ except Exception:
+ # No PyAV means every transcription 501s on decode, so offering a
+ # multi-gigabyte download here would be a waste.
+ return False
+ return True
+
+
+def _llama_server_child_env(binary: str) -> dict:
+ """The chat backend's llama-server environment, for the same binary."""
+ from core.inference.llama_cpp import LlamaCppBackend
+ return LlamaCppBackend._llama_server_env_for_binary(binary)
+
+
+def ensure_engine_available() -> str:
+ binary = find_llama_server_binary()
+ if not binary:
+ raise SttUnavailableError(
+ "llama.cpp is not installed, so these dictation models cannot run. "
+ "Run `unsloth studio update` to install it."
+ )
+ return binary
+
+
+def _reap(process: Optional[subprocess.Popen]) -> None:
+ """Stop a child and wait for it, so its port and VRAM are actually free.
+
+ terminate() alone returns before the process has gone, and a child that
+ ignores SIGTERM would hold both until Studio exits.
+ """
+ if process is None:
+ return
+ try:
+ if process.poll() is None:
+ process.terminate()
+ try:
+ process.wait(timeout = 10)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout = 10)
+ except Exception as exc: # noqa: BLE001 - shutdown must not raise
+ logger.warning("Could not reap llama-server (pid %s): %s", process.pid, exc)
+ finally:
+ # The PID is dead, so drop it before it can be reused by something else
+ # that terminate_all would then signal.
+ forget_pid(process.pid)
+
+
+def _cached_main_revision(repo: str) -> Optional[str]:
+ """The commit `main` currently points at in the cache, if it is recorded."""
+ from core.inference.stt_sidecar import _repo_cache_dir
+
+ try:
+ revision = (_repo_cache_dir(repo) / "refs" / "main").read_text(encoding = "utf-8").strip()
+ except OSError:
+ return None
+ return revision or None
+
+
+def _cached_file(model_id: str, filename: str) -> Optional[str]:
+ from huggingface_hub import hf_hub_download
+
+ from core.inference.stt_sidecar import _active_hf_hub_cache
+ try:
+ return hf_hub_download(
+ repo_id = MTMD_STT_MODELS[model_id].repo,
+ filename = filename,
+ local_files_only = True,
+ # The worker spawns with get_hf_cache_paths(), so a cache relocated
+ # in Studio settings is written there and has to be read there too.
+ cache_dir = str(_active_hf_hub_cache()),
+ )
+ except Exception:
+ return None
+
+
+def _cached_model_paths(model_id: str) -> Optional[tuple[str, str]]:
+ """Both cached files, or None when either is missing."""
+ spec = MTMD_STT_MODELS[model_id]
+ model = _cached_file(model_id, spec.model_file)
+ mmproj = _cached_file(model_id, spec.mmproj_file)
+ if model is None or mmproj is None:
+ return None
+ return model, mmproj
+
+
+def is_model_downloaded(model_id: str) -> bool:
+ return model_id in MTMD_STT_MODELS and _cached_model_paths(model_id) is not None
+
+
+class _MtmdDownloadState:
+ """Tracks the two-file download of one mtmd dictation model."""
+
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self._thread: Optional[threading.Thread] = None
+ self._process: Optional[subprocess.Popen] = None
+ self._model_id: Optional[str] = None
+ self._error: Optional[str] = None
+ self._total_bytes: Optional[int] = None
+ self._cancelled = False
+
+ def status(self) -> dict:
+ with self._lock:
+ downloading = self._thread is not None and self._thread.is_alive()
+ return {
+ "downloading": downloading,
+ "model": self._model_id if downloading else None,
+ "error": self._error,
+ "cancelled": self._cancelled,
+ "bytes_total": self._total_bytes if downloading else None,
+ "bytes_done": self._cache_bytes() if downloading else None,
+ }
+
+ def cancel(self) -> bool:
+ """Stop an in-flight download. False when none was running."""
+ with self._lock:
+ if self._thread is None or not self._thread.is_alive():
+ return False
+ self._cancelled = True
+ process = self._process
+ if process is not None and process.poll() is None:
+ process.terminate()
+ return True
+
+ def _cache_bytes(self) -> Optional[int]:
+ """Best-effort progress: bytes in this repo's cache blobs."""
+ try:
+ from core.inference.stt_sidecar import _repo_cache_dir
+
+ model_id = self._model_id
+ if not model_id:
+ return None
+ blobs = _repo_cache_dir(MTMD_STT_MODELS[model_id].repo) / "blobs"
+ if not blobs.is_dir():
+ return 0
+ return sum(p.stat().st_size for p in blobs.iterdir() if p.is_file())
+ except Exception:
+ return None
+
+ def start(
+ self,
+ model_id: str,
+ hf_token: Optional[str] = None,
+ ) -> None:
+ model_id = resolve_mtmd_model_id(model_id)
+ with self._lock:
+ if self._thread is not None and self._thread.is_alive():
+ if self._model_id == model_id:
+ return
+ raise SttModelIdError(
+ f"Another dictation model ('{self._model_id}') is still "
+ "downloading; wait for it to finish."
+ )
+ self._model_id = model_id
+ self._error = None
+ self._total_bytes = None
+ self._cancelled = False
+ self._process = None
+ thread = threading.Thread(target = self._run, args = (model_id, hf_token), daemon = True)
+ self._thread = thread
+ thread.start()
+
+ def _run(self, model_id: str, hf_token: Optional[str]) -> None:
+ spec = MTMD_STT_MODELS[model_id]
+ try:
+ from huggingface_hub import get_hf_file_metadata, hf_hub_url
+
+ total = 0
+ for filename in (spec.model_file, spec.mmproj_file):
+ try:
+ meta = get_hf_file_metadata(
+ hf_hub_url(spec.repo, filename), token = hf_token or None
+ )
+ total += int(meta.size or 0)
+ except Exception:
+ pass
+ with self._lock:
+ self._total_bytes = total or None
+
+ from core.inference.stt_download_worker import reap_download, spawn_download
+
+ # One worker per file. Both are required, so a cancel between them
+ # leaves the model not downloaded. The first resolves "main" and the
+ # second is pinned to whatever it landed on, so a repo update
+ # mid-download cannot mix two commits. The first stays unpinned
+ # because hf_hub_download only writes refs/main for a named
+ # revision, and _cached_file() resolves through that ref.
+ revision: Optional[str] = None
+ for filename in (spec.model_file, spec.mmproj_file):
+ process = spawn_download(
+ ["--repo-id", spec.repo, "--filename", filename]
+ + (["--revision", revision] if revision else []),
+ hf_token = hf_token or None,
+ )
+ with self._lock:
+ if self._cancelled:
+ process.terminate()
+ self._process = process
+ stderr = reap_download(process)
+ if process.returncode == 0:
+ revision = revision or _cached_main_revision(spec.repo)
+ continue
+ with self._lock:
+ if self._cancelled or process.returncode < 0:
+ self._cancelled = True
+ return
+ detail = (stderr or b"").decode("utf-8", "replace").strip()
+ logger.warning("mtmd STT download failed for %s: %s", model_id, detail)
+ with self._lock:
+ self._error = f"Download failed for '{model_id}'."
+ return
+ except Exception as exc:
+ logger.warning("mtmd STT download failed for %s: %s", model_id, exc)
+ with self._lock:
+ self._error = f"Download failed for '{model_id}'."
+
+
+_download_state = _MtmdDownloadState()
+
+
+def start_model_download(model: Optional[str], hf_token: Optional[str] = None) -> None:
+ _download_state.start(resolve_mtmd_model_id(model), hf_token)
+
+
+def download_status() -> dict:
+ return _download_state.status()
+
+
+def cancel_model_download() -> bool:
+ return _download_state.cancel()
+
+
+class MtmdSttSidecar:
+ """One llama-server process serving the selected mtmd dictation model."""
+
+ def __init__(self, keep_alive_seconds: float = STT_KEEP_ALIVE_SECONDS) -> None:
+ self._lock = threading.RLock()
+ # Held across a whole startup; _lock is released while llama-server boots.
+ self._start_lock = threading.Lock()
+ self._process: Optional[subprocess.Popen] = None
+ self._port: Optional[int] = None
+ self._model_id: Optional[str] = None
+ self._loading = False
+ # Published as soon as Popen returns, so a startup can be preempted
+ # before _process is assigned (readiness takes up to three minutes).
+ self._starting_process: Optional[subprocess.Popen] = None
+ # Whether the resident server was launched with the GPU pinned off for
+ # training. Kept so a dictation after the run does not stay on CPU.
+ self._gpu_disabled = False
+ self._load_cancel_event: Optional[threading.Event] = None
+ self._update_in_progress = False
+ self._keep_alive_seconds = keep_alive_seconds
+ self._idle_timer: Optional[threading.Timer] = None
+ self._generation = 0
+ # Transcription runs outside _lock and can outlast the keep-alive, so
+ # the idle timer stays disarmed while any request is in flight.
+ self._active_requests = 0
+
+ @property
+ def loaded_model(self) -> Optional[str]:
+ with self._lock:
+ return self._model_id if self._process_alive() else None
+
+ @property
+ def device(self) -> Optional[str]:
+ return "llama.cpp" if self.loaded_model else None
+
+ def is_loading(self) -> bool:
+ with self._lock:
+ return self._loading
+
+ @property
+ def keep_alive_seconds(self) -> float:
+ return self._keep_alive_seconds
+
+ def _process_alive(self) -> bool:
+ process = self._process
+ return process is not None and process.poll() is None
+
+ def _cancel_idle_unload_locked(self) -> None:
+ if self._idle_timer is not None:
+ self._idle_timer.cancel()
+ self._idle_timer = None
+
+ def _schedule_idle_unload_locked(self) -> None:
+ self._cancel_idle_unload_locked()
+ if self._keep_alive_seconds <= 0 or self._active_requests:
+ return
+ generation = self._generation
+ timer = threading.Timer(self._keep_alive_seconds, self._idle_unload, args = (generation,))
+ timer.daemon = True
+ self._idle_timer = timer
+ timer.start()
+
+ def _idle_unload(self, generation: int) -> None:
+ with self._lock:
+ if generation != self._generation:
+ return
+ self._release_locked()
+
+ def _release_locked(self) -> None:
+ self._cancel_idle_unload_locked()
+ self._generation += 1
+ process = self._process
+ self._process = None
+ self._port = None
+ self._model_id = None
+ _reap(process)
+
+ def unload(self) -> None:
+ # A startup has not assigned _process yet, so releasing alone would let
+ # it finish and republish the model that was just unloaded. Cancel and
+ # settle outside _lock: load() holds _start_lock across startup and
+ # takes _lock inside it, so holding _lock here would invert them.
+ self.cancel_pending_load()
+ self.wait_for_load_to_settle()
+ with self._lock:
+ self._release_locked()
+
+ def cancel_pending_load(self) -> bool:
+ """Preempt a starting llama-server so training is not raced for VRAM.
+
+ _process is only assigned once the server answers /health, so unload()
+ cannot reach a child that is still allocating. Startup runs outside
+ _lock, so this acts without it: the event makes _wait_for_server give
+ up, and load() then reaps the child.
+ """
+ if not self._loading:
+ return False
+ event = self._load_cancel_event
+ if event is None:
+ return False
+ event.set()
+ process = self._starting_process
+ if process is not None and process.poll() is None:
+ try:
+ process.terminate()
+ except Exception:
+ pass
+ return True
+
+ def wait_for_load_to_settle(self) -> None:
+ """Block until a cancelled startup has been reaped and its VRAM freed.
+
+ load() holds _start_lock across startup and its cleanup, so taking it
+ is the wait.
+ """
+ with self._start_lock:
+ pass
+
+ def _raise_if_update_in_progress(self) -> None:
+ if self._update_in_progress:
+ raise SttUnavailableError(
+ "The local transcription runtime is being updated. Try dictation again shortly."
+ )
+
+ @contextmanager
+ def update_maintenance(self) -> Iterator[bool]:
+ """Block new loads while the llama.cpp tree this binary lives in is
+ replaced. The chat backend coordinates its own server; this sidecar runs
+ the same executable, so on Windows a live one blocks the swap.
+
+ The guard is published before waiting for the locks, so a load already
+ past its own check still cannot start a process against a half-swapped
+ tree. Yields whether a warm server had to be unloaded.
+ """
+ self._update_in_progress = True
+ try:
+ with self._start_lock, self._lock:
+ model_was_active = self._process_alive()
+ self._release_locked()
+ yield model_was_active
+ finally:
+ self._update_in_progress = False
+
+ @staticmethod
+ def _reserve_free_port() -> tuple[socket.socket, int]:
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ sock.bind(("127.0.0.1", 0))
+ return sock, sock.getsockname()[1]
+
+ def _ensure_model_downloaded(self, model_id: str) -> tuple[str, str]:
+ paths = _cached_model_paths(model_id)
+ if paths is None:
+ raise SttModelNotDownloadedError(
+ f"STT model '{model_id}' is not downloaded. "
+ "Download it in Settings, then Voice, before loading it."
+ )
+ return paths
+
+ def load(self, model: Optional[str] = None) -> None:
+ self._raise_if_update_in_progress()
+ model_id = resolve_mtmd_model_id(model)
+ binary = ensure_engine_available()
+ # Startup happens outside _lock (it is slow), so this keeps two callers
+ # from each spawning a server and orphaning the first.
+ with self._start_lock:
+ self._raise_if_update_in_progress()
+ self._load_locked(model_id, binary)
+
+ def _load_locked(self, model_id: str, binary: str) -> None:
+ with self._lock:
+ training = _training_active()
+ if self._process_alive() and self._model_id == model_id:
+ # Same model, so only the offload mode can differ: a server
+ # started at -ngl 0 during training would otherwise serve every
+ # later dictation on CPU. Restarting for that is an
+ # optimisation, never worth killing a running transcription
+ # for, so an in-flight request keeps the server it has and the
+ # next idle load picks the GPU back up.
+ if self._gpu_disabled == training or self._active_requests:
+ self._schedule_idle_unload_locked()
+ return
+ # Before the release: a 409 for a model that is not downloaded
+ # must not cost the user the server they were already using.
+ model_path, mmproj_path = self._ensure_model_downloaded(model_id)
+ # Only when there is a live server to protect: a request against a
+ # server that already died must not block recovery.
+ if self._active_requests and self._process_alive():
+ raise SttModelBusyError(
+ "A transcription is still running on the current dictation model. "
+ "Try again in a moment."
+ )
+ self._release_locked()
+ cancel_event = threading.Event()
+ self._load_cancel_event = cancel_event
+ self._loading = True
+ # Re-read last: _release_locked() reaps the old server, which can
+ # take seconds, and training admission that already passed its own
+ # check cannot come back to cancel this load. Publishing _loading
+ # first covers the other order, so between them every training start
+ # either cancels this load or is seen by it.
+ training = _training_active()
+ try:
+ sock, port = self._reserve_free_port()
+ cmd = [
+ binary,
+ "-m",
+ model_path,
+ "--mmproj",
+ mmproj_path,
+ "--host",
+ "127.0.0.1",
+ "--port",
+ str(port),
+ # One short request at a time, so one slot keeps the footprint
+ # down next to a loaded chat model.
+ "--parallel",
+ "1",
+ # Keep off the accelerator during training (as whisper.cpp does)
+ # so a dictation load cannot reclaim VRAM training just freed.
+ "-ngl",
+ "0" if training else "99",
+ ]
+ if training:
+ # -ngl 0 covers the main model only. clip.cpp offloads the
+ # projector on its own flag, which is what the chat backend's
+ # _cmd_has_gpu_companion() treats as a GPU companion whatever
+ # --gpu-layers says.
+ cmd.append("--no-mmproj-offload")
+ sock.close()
+ process = subprocess.Popen(
+ cmd,
+ # Nothing reads these, and an undrained pipe blocks llama-server
+ # mid-startup once its logs fill the buffer.
+ stdout = subprocess.DEVNULL,
+ stderr = subprocess.DEVNULL,
+ stdin = subprocess.DEVNULL,
+ # Bundled libs and pip CUDA runtimes on the loader path, secrets
+ # scrubbed, as the chat backend spawns the same binary.
+ env = _llama_server_child_env(binary),
+ # Die with Studio, so a crash never orphans a server on the GPU.
+ **child_popen_kwargs(),
+ )
+ # Published before the wait, so training can preempt a startup that
+ # is already allocating; _process is not set for another 180s.
+ with self._lock:
+ self._starting_process = process
+ adopt_pid(process.pid) # terminate_all backstop for graceful exits
+ if not self._wait_for_server(process, port, cancel_event):
+ # Reap it here: _process was never assigned, so unload() cannot
+ # reach a child that ignores SIGTERM and keeps port and VRAM.
+ _reap(process)
+ if cancel_event.is_set():
+ # 409 through the route, like the other sidecars: expected
+ # preemption, not a broken or missing runtime (501).
+ raise SttLoadCancelledError(
+ "Dictation model loading was cancelled so training could start."
+ )
+ raise SttUnavailableError(f"llama-server did not become ready for '{model_id}'.")
+ with self._lock:
+ self._process = process
+ self._port = port
+ self._model_id = model_id
+ self._gpu_disabled = training
+ self._generation += 1
+ self._schedule_idle_unload_locked()
+ finally:
+ with self._lock:
+ self._loading = False
+ self._load_cancel_event = None
+ self._starting_process = None
+
+ @staticmethod
+ def _wait_for_server(
+ process: subprocess.Popen,
+ port: int,
+ cancel_event: Optional[threading.Event] = None,
+ ) -> bool:
+ deadline = time.monotonic() + _SERVER_START_TIMEOUT_SECONDS
+ url = f"http://127.0.0.1:{port}/health"
+ while time.monotonic() < deadline:
+ if cancel_event is not None and cancel_event.is_set():
+ return False
+ if process.poll() is not None:
+ return False
+ try:
+ with urllib.request.urlopen(url, timeout = 2) as response:
+ if response.status == 200:
+ return True
+ except Exception:
+ time.sleep(0.25)
+ return False
+
+ def transcribe(
+ self,
+ audio: bytes,
+ model: Optional[str] = None,
+ language: Optional[str] = None,
+ fast: bool = False,
+ ) -> dict:
+ """Transcribe encoded audio bytes, as the other sidecars do.
+
+ ``fast`` has no effect: decoding is greedy and the model picks the
+ language itself.
+ """
+ ensure_engine_available()
+ model_id = resolve_mtmd_model_id(model)
+ # No training guard here on purpose: load() starts the server with
+ # -ngl 0 --no-mmproj-offload while a run is active, so this transcribes
+ # on CPU exactly as whisper.cpp and Transformers do. Refusing after a
+ # preload that succeeded only discarded the user's recording.
+ # Reject a missing model before decoding, matching the other sidecars.
+ self._ensure_model_downloaded(model_id)
+ decoded_audio = _decode_audio_bounded(audio)
+ wav_bytes = _pcm_to_wav_bytes(decoded_audio)
+ audio_seconds = (len(decoded_audio) / _TARGET_SAMPLE_RATE) if len(decoded_audio) else None
+ self.load(model_id)
+ with self._lock:
+ port = self._port
+ if port is None or not self._process_alive():
+ raise SttUnavailableError("The dictation server is not running.")
+ # Another client can switch models in the gap between that load
+ # returning and this lock, and the port read here would then be its
+ # server. Refuse rather than transcribe on the wrong model.
+ if self._model_id != model_id:
+ raise SttModelBusyError(
+ "The dictation model changed while this recording was being "
+ "prepared. Try again."
+ )
+ # Long audio can outlast the keep-alive, and _post_transcribe runs
+ # outside the lock, so disarm the timer rather than let it kill
+ # llama-server mid-request and throw the dictation away.
+ self._active_requests += 1
+ self._cancel_idle_unload_locked()
+ try:
+ # Outside the lock: a held lock would block unload, including the
+ # one a training run performs, for the whole request timeout.
+ text = self._post_transcribe(port, model_id, wav_bytes, audio_seconds)
+ finally:
+ with self._lock:
+ self._active_requests -= 1
+ self._schedule_idle_unload_locked()
+ return {
+ "text": text,
+ "language": normalize_whisper_language(language),
+ "duration": audio_seconds,
+ "model": model_id,
+ }
+
+ def _post_transcribe(
+ self,
+ port: int,
+ model_id: str,
+ wav_bytes: bytes,
+ audio_seconds: Optional[float] = None,
+ ) -> str:
+ spec = MTMD_STT_MODELS[model_id]
+ payload = {
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "input_audio",
+ "input_audio": {
+ "data": base64.b64encode(wav_bytes).decode("ascii"),
+ "format": "wav",
+ },
+ },
+ {"type": "text", "text": _TRANSCRIBE_PROMPT},
+ ],
+ }
+ ],
+ # Greedy: a transcript, not a sampled paraphrase.
+ "temperature": 0,
+ "max_tokens": _transcript_token_budget(audio_seconds),
+ }
+ request = urllib.request.Request(
+ f"http://127.0.0.1:{port}/v1/chat/completions",
+ data = json.dumps(payload).encode("utf-8"),
+ headers = {"Content-Type": "application/json"},
+ )
+ with urllib.request.urlopen(request, timeout = _TRANSCRIBE_TIMEOUT_SECONDS) as response:
+ body = json.loads(response.read().decode("utf-8"))
+ choices = body.get("choices") or []
+ text = (choices[0].get("message", {}).get("content") or "") if choices else ""
+ return _clean_transcript(text, spec.transcript_marker)
+
+
+def _clean_transcript(text: str, marker: Optional[str]) -> str:
+ """Drop the model's leading metadata, keeping only the transcript."""
+ if marker and marker in text:
+ text = text.rsplit(marker, 1)[1]
+ return text.strip()
+
+
+_sidecar: Optional[MtmdSttSidecar] = None
+_sidecar_lock = threading.Lock()
+
+
+def get_mtmd_stt_sidecar() -> MtmdSttSidecar:
+ global _sidecar
+ with _sidecar_lock:
+ if _sidecar is None:
+ _sidecar = MtmdSttSidecar()
+ return _sidecar
diff --git a/studio/backend/core/inference/stt_registry.py b/studio/backend/core/inference/stt_registry.py
new file mode 100644
index 00000000000..5549ce31e7f
--- /dev/null
+++ b/studio/backend/core/inference/stt_registry.py
@@ -0,0 +1,86 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""One place that knows which dictation models are resident, and loads them.
+
+The sidecars still own their processes: whisper.cpp serves GGML through
+whisper-server, llama.cpp serves mtmd models, and Transformers loads in
+process. What lives here is the lifecycle above them, so the orchestrator has a
+single view of dictation the way it has one of chat, and Voice settings and
+Model Hub cannot report different things about the same model.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Optional, Sequence
+
+from loggers import get_logger
+
+logger = get_logger(__name__)
+
+# Every engine a dictation model can be resident on. Order is the order an
+# unload sweeps them, which matters only for logging.
+STT_ENGINES = ("transformers", "gguf", "mtmd")
+
+
+def sidecar_for(engine: str) -> Any:
+ """The sidecar serving ``engine``. Transformers is the catch-all."""
+ if engine == "mtmd":
+ from core.inference.stt_mtmd_sidecar import get_mtmd_stt_sidecar
+ return get_mtmd_stt_sidecar()
+ if engine == "gguf":
+ from core.inference.stt_ggml_sidecar import get_ggml_stt_sidecar
+ return get_ggml_stt_sidecar()
+ from core.inference.stt_sidecar import get_stt_sidecar
+
+ return get_stt_sidecar()
+
+
+def load(model: Optional[str], engine: str) -> None:
+ """Make ``model`` resident on ``engine``. Raises what the sidecar raises."""
+ sidecar_for(engine).load(model)
+
+
+def unload(engines: Optional[Sequence[str]] = None) -> list[str]:
+ """Release every named engine (all of them by default), reporting refusals.
+
+ Each is attempted even after a failure: more than one can hold memory at
+ once after an engine switch, so stopping early would strand the rest.
+ """
+ failed: list[str] = []
+ for name in STT_ENGINES if engines is None else engines:
+ try:
+ sidecar_for(name).unload()
+ except Exception as exc: # noqa: BLE001 - report after attempting all
+ logger.warning("Failed to unload STT engine '%s': %s", name, exc)
+ failed.append(name)
+ return failed
+
+
+def resident() -> dict:
+ """What dictation currently holds, for the shared inference status.
+
+ Never raises: a sidecar that cannot even be imported reports nothing rather
+ than taking the status endpoint down with it.
+ """
+ for engine in STT_ENGINES:
+ try:
+ sidecar = sidecar_for(engine)
+ model = sidecar.loaded_model
+ if model:
+ return {
+ "model": model,
+ "engine": engine,
+ "device": sidecar.device,
+ "loading": False,
+ }
+ if sidecar.is_loading():
+ return {
+ "model": None,
+ "engine": engine,
+ "device": None,
+ "loading": True,
+ }
+ except Exception as exc: # noqa: BLE001 - one engine must not hide the rest
+ logger.debug("Could not inspect STT engine '%s': %s", engine, exc)
+ return {"model": None, "engine": None, "device": None, "loading": False}
diff --git a/studio/backend/core/inference/stt_sidecar.py b/studio/backend/core/inference/stt_sidecar.py
index edf57c16e37..f97df9d3671 100644
--- a/studio/backend/core/inference/stt_sidecar.py
+++ b/studio/backend/core/inference/stt_sidecar.py
@@ -19,6 +19,7 @@ import io
import json
import os
import re
+import subprocess
import threading
import uuid
from dataclasses import dataclass
@@ -97,6 +98,10 @@ class SttModelNotDownloadedError(RuntimeError):
"""The selected model is not complete in the shared Hub cache."""
+class SttModelBusyError(RuntimeError):
+ """A switch was asked for while the current model is mid-transcription."""
+
+
class SttModelIdError(ValueError):
"""The requested custom model is not a valid Hugging Face repository id."""
@@ -224,9 +229,15 @@ def _active_hf_hub_cache() -> Path:
hf_home = (os.environ.get("HF_HOME") or "").strip()
if hf_home:
return Path(hf_home).expanduser() / "hub"
- from huggingface_hub.constants import HF_HUB_CACHE
-
- return Path(HF_HUB_CACHE)
+ # The download workers spawn with get_hf_cache_paths(), which also honours a
+ # cache location set in Studio. Read the same source, or a relocated cache
+ # is written by the worker and looked for here in the old place.
+ try:
+ from utils.hf_cache_settings import get_hf_cache_paths
+ return Path(get_hf_cache_paths().hub_cache)
+ except Exception:
+ from huggingface_hub.constants import HF_HUB_CACHE
+ return Path(HF_HUB_CACHE)
def _repo_cache_dir(repo: str) -> Path:
@@ -499,12 +510,14 @@ class _SnapshotDownloadState:
def __init__(self) -> None:
self._lock = threading.Lock()
self._thread: Optional[threading.Thread] = None
+ self._process: Optional[subprocess.Popen] = None
self._model_id: Optional[str] = None
self._repo: Optional[str] = None
self._error: Optional[str] = None
self._total_bytes: Optional[int] = None
self._selected_files: tuple[_SelectedHubFile, ...] = ()
self._complete = False
+ self._cancelled = False
def status(self) -> dict:
with self._lock:
@@ -514,10 +527,25 @@ class _SnapshotDownloadState:
"downloading": downloading,
"model": self._model_id if downloading else None,
"error": self._error,
+ "cancelled": self._cancelled,
"bytes_total": self._total_bytes if show_progress else None,
"bytes_done": self._blob_bytes() if show_progress else None,
}
+ def cancel(self) -> bool:
+ """Stop an in-flight download. False when none was running.
+
+ Partial blobs stay cached, so a restart resumes from them.
+ """
+ with self._lock:
+ if self._thread is None or not self._thread.is_alive():
+ return False
+ self._cancelled = True
+ process = self._process
+ if process is not None and process.poll() is None:
+ process.terminate()
+ return True
+
def _blob_bytes(self) -> Optional[int]:
"""Best-effort progress: bytes in the repo's HF cache blobs.
@@ -568,6 +596,8 @@ class _SnapshotDownloadState:
self._total_bytes = None
self._selected_files = ()
self._complete = False
+ self._cancelled = False
+ self._process = None
thread = threading.Thread(
target = self._run, args = (self._repo, hf_token, revision), daemon = True
)
@@ -581,7 +611,7 @@ class _SnapshotDownloadState:
revision: Optional[str] = None,
) -> None:
try:
- from huggingface_hub import HfApi, hf_hub_download, snapshot_download
+ from huggingface_hub import HfApi, hf_hub_download
info = HfApi(token = hf_token or None).model_info(
repo,
@@ -610,14 +640,29 @@ class _SnapshotDownloadState:
with self._lock:
self._selected_files = selected_files
self._total_bytes = total or None
- snapshot = Path(
- snapshot_download(
- repo_id = repo,
- revision = revision,
- allow_patterns = [selected.path for selected in selected_files],
- token = hf_token or None,
- )
- )
+ # Out of process so cancel() can terminate it; a thread blocked in
+ # snapshot_download could not be interrupted.
+ from core.inference.stt_download_worker import reap_download, spawn_download
+
+ args = ["--repo-id", repo, "--revision", revision]
+ for selected in selected_files:
+ args += ["--allow-pattern", selected.path]
+ process = spawn_download(args, hf_token = hf_token or None)
+ with self._lock:
+ if self._cancelled:
+ # cancel() landed between start() and the spawn.
+ process.terminate()
+ self._process = process
+ stderr = reap_download(process)
+ if process.returncode != 0:
+ with self._lock:
+ if self._cancelled or process.returncode < 0:
+ self._cancelled = True
+ return
+ detail = (stderr or b"").decode("utf-8", "replace").strip()
+ raise SttModelCompatibilityError(f"Download worker failed for '{repo}': {detail}")
+ # The worker writes the same cache layout snapshot_download did.
+ snapshot = _repo_cache_dir(repo) / "snapshots" / revision
if not _snapshot_is_complete(snapshot):
raise SttModelCompatibilityError(
f"Downloaded STT snapshot for '{repo}' is incomplete."
@@ -646,6 +691,10 @@ def download_status() -> dict:
return _download_state.status()
+def cancel_model_download() -> bool:
+ return _download_state.cancel()
+
+
def _training_active() -> bool:
try:
from core.training import get_training_backend
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 64ee2d6e368..31d2d380a95 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -8057,9 +8057,11 @@ def _resolve_stt_engine(engine: Optional[str]) -> str:
return "transformers"
if normalized in ("gguf", "ggml", "whisper_cpp", "whisper.cpp"):
return "gguf"
+ if normalized in ("mtmd", "llama_cpp", "llama.cpp"):
+ return "mtmd"
raise HTTPException(
status_code = 422,
- detail = f"Unknown STT engine '{engine}'. Use 'transformers' or 'gguf'.",
+ detail = f"Unknown STT engine '{engine}'. Use 'transformers', 'gguf', or 'mtmd'.",
)
@@ -8077,15 +8079,44 @@ def _resolve_serving_stt_engine(engine: Optional[str]) -> str:
from core.inference import stt_ggml_sidecar
if not stt_ggml_sidecar.is_available():
return "transformers"
+ # mtmd models exist in no other engine, so there is nothing to fall back to.
return resolved
-def _stt_sidecar_for(engine: str):
+def _stt_download_module(engine: str):
+ """Module owning download/status for an engine."""
+ if engine == "mtmd":
+ from core.inference import stt_mtmd_sidecar
+ return stt_mtmd_sidecar
if engine == "gguf":
- from core.inference.stt_ggml_sidecar import get_ggml_stt_sidecar
- return get_ggml_stt_sidecar()
- from core.inference.stt_sidecar import get_stt_sidecar
- return get_stt_sidecar()
+ from core.inference import stt_ggml_sidecar
+ return stt_ggml_sidecar
+ from core.inference import stt_sidecar
+
+ return stt_sidecar
+
+
+def _stt_sidecar_for(engine: str):
+ """The sidecar serving an engine. One resolver, shared with the orchestrator."""
+ from core.inference import stt_registry
+ return stt_registry.sidecar_for(engine)
+
+
+def _stt_lifecycle() -> tuple:
+ """(load, unload) for dictation models, off the orchestrator when it exists.
+
+ Same object Model Hub loads a chat model with, so one thing knows everything
+ resident. Its methods only forward to `stt_registry`, so a cold process
+ calls that directly rather than constructing an orchestrator (which blocks
+ on hardware detection) to load a model that never touches the chat worker.
+ """
+ from core.inference import stt_registry
+ from core.inference.orchestrator import peek_inference_backend
+
+ backend = peek_inference_backend()
+ if backend is None:
+ return stt_registry.load, stt_registry.unload
+ return backend.load_stt_model, backend.unload_stt_model
@studio_router.get("/audio/stt/status")
@@ -8097,7 +8128,7 @@ async def stt_status(
``model`` extends the Transformers ``downloaded_models`` check to a
custom Hugging Face repository beyond the curated defaults.
"""
- from core.inference import stt_ggml_sidecar, stt_sidecar
+ from core.inference import stt_ggml_sidecar, stt_mtmd_sidecar, stt_sidecar
from core.inference.stt_sidecar import (
DEFAULT_STT_MODEL,
STT_MODELS,
@@ -8107,6 +8138,7 @@ async def stt_status(
sidecar = get_stt_sidecar()
ggml = stt_ggml_sidecar.get_ggml_stt_sidecar()
+ mtmd = stt_mtmd_sidecar.get_mtmd_stt_sidecar()
transformers_downloaded = [
model_id for model_id in STT_MODELS if stt_sidecar.is_model_downloaded(model_id)
]
@@ -8134,6 +8166,22 @@ async def stt_status(
"downloaded_models": transformers_downloaded,
"download": stt_sidecar.download_status(),
},
+ # llama.cpp (mtmd) engine: non-Whisper ASR models.
+ "mtmd": {
+ "available": stt_mtmd_sidecar.is_available(),
+ "loaded_model": mtmd.loaded_model,
+ "loading": mtmd.is_loading(),
+ "device": mtmd.device,
+ "keep_alive_seconds": mtmd.keep_alive_seconds,
+ "default_model": None,
+ "models": list(stt_mtmd_sidecar.MTMD_STT_MODELS),
+ "downloaded_models": [
+ model_id
+ for model_id in stt_mtmd_sidecar.MTMD_STT_MODELS
+ if stt_mtmd_sidecar.is_model_downloaded(model_id)
+ ],
+ "download": stt_mtmd_sidecar.download_status(),
+ },
# whisper.cpp (GGUF) engine.
"gguf": {
"available": stt_ggml_sidecar.is_available(),
@@ -8174,13 +8222,13 @@ async def stt_download(
)
engine = _resolve_serving_stt_engine(payload.engine)
- module = stt_ggml_sidecar if engine == "gguf" else stt_sidecar
+ module = _stt_download_module(engine)
try:
# Transformers accepts custom `owner/model` repos, so confirm the repo is
# a Whisper checkpoint (metadata-only) before snapshot_download pulls a
# possibly-large non-STT repo into the shared cache. Curated ids
- # short-circuit; GGUF only accepts curated ids, so it needs no check.
- if engine != "gguf":
+ # short-circuit; GGUF and mtmd accept curated ids only, so they skip it.
+ if engine == "transformers":
validated = await asyncio.to_thread(validate_remote_model, payload.model, hf_token)
# Pin the download to the commit that was just validated so the
# repo cannot be swapped between validation and snapshot_download.
@@ -8199,11 +8247,31 @@ async def stt_download(
return JSONResponse(content = module.download_status())
+@studio_router.post("/audio/stt/download/cancel")
+async def stt_download_cancel(
+ payload: Optional[SttLoadRequest] = None, current_subject: str = Depends(get_current_subject)
+):
+ """Stop an in-flight dictation model download.
+
+ Partial files stay cached, so the same download resumes. Cancelling when
+ nothing is downloading is a no-op, so a double click cannot fail.
+ """
+ from core.inference import stt_ggml_sidecar, stt_sidecar
+
+ engine = _resolve_serving_stt_engine(payload.engine if payload else None)
+ module = _stt_download_module(engine)
+ cancelled = await asyncio.to_thread(module.cancel_model_download)
+ # This request's result last: download_status() carries its own historical
+ # "cancelled", which would otherwise report a no-op as a cancellation.
+ return JSONResponse(content = {**module.download_status(), "cancelled": cancelled})
+
+
@studio_router.post("/audio/stt/load")
async def stt_load(payload: SttLoadRequest, current_subject: str = Depends(get_current_subject)):
"""Load the selected STT model after the user starts local dictation."""
from core.inference.stt_sidecar import (
SttLoadCancelledError,
+ SttModelBusyError,
SttModelCompatibilityError,
SttModelIdError,
SttModelNotDownloadedError,
@@ -8211,15 +8279,19 @@ async def stt_load(payload: SttLoadRequest, current_subject: str = Depends(get_c
get_stt_sidecar,
)
- sidecar = _stt_sidecar_for(_resolve_serving_stt_engine(payload.engine))
+ engine = _resolve_serving_stt_engine(payload.engine)
+ sidecar = _stt_sidecar_for(engine)
+ load_stt, _ = _stt_lifecycle()
try:
- await asyncio.to_thread(sidecar.load, payload.model)
+ await asyncio.to_thread(load_stt, payload.model, engine)
except SttModelNotDownloadedError as e:
raise HTTPException(status_code = 409, detail = str(e))
except SttUnavailableError as e:
raise HTTPException(status_code = 501, detail = str(e))
except SttLoadCancelledError as e:
raise HTTPException(status_code = 409, detail = str(e))
+ except SttModelBusyError as e:
+ raise HTTPException(status_code = 409, detail = str(e))
except SttModelIdError as e:
raise HTTPException(status_code = 422, detail = str(e))
except SttModelCompatibilityError as e:
@@ -8260,21 +8332,16 @@ async def stt_unload(
settings always frees whichever backend was resident.
"""
if engine is None:
- engines = ["transformers", "gguf"]
+ engines = None
else:
# Use the serving resolver: a "gguf" pick without whisper-server is
# actually served by the Transformers fallback, so unload must target
# that same engine or the resident model is never freed.
engines = [_resolve_serving_stt_engine(engine)]
- # Attempt every engine even if one raises, so failing to unload one never
- # skips freeing the other (both can be resident after a switch).
- failed: list[str] = []
- for name in engines:
- try:
- await asyncio.to_thread(_stt_sidecar_for(name).unload)
- except Exception as exc: # noqa: BLE001 - report after attempting all engines
- logger.warning("Failed to unload STT engine '%s': %s", name, exc)
- failed.append(name)
+ # Every engine is attempted even if one raises, so failing to free one never
+ # skips the other (both can be resident after a switch).
+ _, unload_stt = _stt_lifecycle()
+ failed: list[str] = await asyncio.to_thread(unload_stt, engines)
if failed:
raise HTTPException(
status_code = 500,
@@ -8296,6 +8363,7 @@ async def _transcribe_audio_bytes(
SttAudioTooLongError,
SttLanguageError,
SttLoadCancelledError,
+ SttModelBusyError,
SttModelCompatibilityError,
SttModelIdError,
SttModelNotDownloadedError,
@@ -8322,6 +8390,10 @@ async def _transcribe_audio_bytes(
raise HTTPException(status_code = 409, detail = str(e))
except SttModelNotDownloadedError as e:
raise HTTPException(status_code = 409, detail = str(e))
+ except SttModelBusyError as e:
+ # Another client switching the dictation model is ordinary concurrency,
+ # so say retry rather than report a server failure.
+ raise HTTPException(status_code = 409, detail = str(e))
except SttModelIdError as e:
raise HTTPException(status_code = 422, detail = str(e))
except SttModelCompatibilityError as e:
diff --git a/studio/backend/routes/training_vram.py b/studio/backend/routes/training_vram.py
index fe5f9ac07a7..d687e92f205 100644
--- a/studio/backend/routes/training_vram.py
+++ b/studio/backend/routes/training_vram.py
@@ -95,16 +95,31 @@ def summarize_resident_stt() -> Dict[str, Any]:
model = ggml.loaded_model
device = device or ggml.device
loading = loading or ggml.is_loading()
- return {
- "model": model,
- "device": device,
- "loading": loading,
- "any": bool(model or loading),
- }
except Exception as e:
logger.warning("Could not inspect STT sidecar: %s", e)
return {"model": None, "device": None, "loading": False, "any": False}
+ # Same reasoning for mtmd: its llama-server holds VRAM too, so admission has
+ # to see it. Its own boundary, so an mtmd import failure cannot discard what
+ # the other two engines just reported.
+ try:
+ from core.inference.stt_mtmd_sidecar import get_mtmd_stt_sidecar
+
+ mtmd = get_mtmd_stt_sidecar()
+ if not model:
+ model = mtmd.loaded_model
+ device = device or mtmd.device
+ loading = loading or mtmd.is_loading()
+ except Exception as e:
+ logger.warning("Could not inspect mtmd STT sidecar: %s", e)
+
+ return {
+ "model": model,
+ "device": device,
+ "loading": loading,
+ "any": bool(model or loading),
+ }
+
def can_keep_chat_during_training(
*,
@@ -469,6 +484,29 @@ def free_stt_model_for_training(reason: str) -> List[str]:
except Exception as e:
logger.warning("Could not unload GGUF STT model: %s", e)
+ # The mtmd sidecar serves Qwen3-ASR through llama-server at -ngl 99, so it
+ # holds VRAM exactly like the other two and has to be freed as well.
+ try:
+ from core.inference.stt_mtmd_sidecar import get_mtmd_stt_sidecar
+ mtmd = get_mtmd_stt_sidecar()
+ if mtmd.is_loading() and mtmd.cancel_pending_load():
+ logger.info("Cancelling mtmd STT model load for training (%s)", reason)
+ # llama-server only becomes reachable through unload() once it is
+ # ready, so a startup has to be cancelled and reaped instead. Wait
+ # for that before training claims the memory it is allocating.
+ mtmd.wait_for_load_to_settle()
+ if mtmd.loaded_model:
+ mtmd.unload()
+ freed.append("stt:mtmd-loading")
+ else:
+ mtmd_model = mtmd.loaded_model
+ if mtmd_model:
+ logger.info("Unloading mtmd STT model '%s' for training (%s)", mtmd_model, reason)
+ mtmd.unload()
+ freed.append(f"stt:{mtmd_model}")
+ except Exception as e:
+ logger.warning("Could not unload mtmd STT model: %s", e)
+
return freed
diff --git a/studio/backend/tests/test_stt_registry.py b/studio/backend/tests/test_stt_registry.py
new file mode 100644
index 00000000000..351afd5bb44
--- /dev/null
+++ b/studio/backend/tests/test_stt_registry.py
@@ -0,0 +1,136 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Dictation lifecycle goes through one place, shared with the orchestrator."""
+
+import pytest
+
+from core.inference import stt_registry
+
+
+class _Sidecar:
+ def __init__(
+ self,
+ name,
+ model = None,
+ loading = False,
+ fail = False,
+ ):
+ self.name = name
+ self.loaded_model = model
+ self.device = f"{name}-device" if model else None
+ self._loading = loading
+ self._fail = fail
+ self.unloaded = False
+ self.loaded_with = None
+
+ def is_loading(self):
+ return self._loading
+
+ def load(self, model):
+ self.loaded_with = model
+
+ def unload(self):
+ if self._fail:
+ raise RuntimeError("boom")
+ self.unloaded = True
+
+
+def test_unload_attempts_every_engine_even_after_one_raises(monkeypatch):
+ made = {}
+
+ def make(name):
+ made.setdefault(name, _Sidecar(name, fail = name == "transformers"))
+ return made[name]
+
+ monkeypatch.setattr(stt_registry, "sidecar_for", make)
+ failed = stt_registry.unload()
+
+ assert list(made) == list(stt_registry.STT_ENGINES)
+ assert failed == ["transformers"]
+ # The engines after the failure still released.
+ assert made["gguf"].unloaded and made["mtmd"].unloaded
+
+
+def test_load_delegates_to_the_engines_sidecar(monkeypatch):
+ sidecar = _Sidecar("mtmd")
+ monkeypatch.setattr(stt_registry, "sidecar_for", lambda name: sidecar)
+
+ stt_registry.load("qwen3-asr-0.6b", "mtmd")
+ assert sidecar.loaded_with == "qwen3-asr-0.6b"
+
+
+def test_resident_reports_whichever_engine_holds_a_model(monkeypatch):
+ sidecars = {
+ "transformers": _Sidecar("transformers"),
+ "gguf": _Sidecar("gguf"),
+ "mtmd": _Sidecar("mtmd", model = "qwen3-asr-0.6b"),
+ }
+ monkeypatch.setattr(stt_registry, "sidecar_for", lambda name: sidecars[name])
+
+ assert stt_registry.resident() == {
+ "model": "qwen3-asr-0.6b",
+ "engine": "mtmd",
+ "device": "mtmd-device",
+ "loading": False,
+ }
+
+
+def test_resident_reports_an_in_flight_load(monkeypatch):
+ sidecars = {
+ "transformers": _Sidecar("transformers"),
+ "gguf": _Sidecar("gguf", loading = True),
+ "mtmd": _Sidecar("mtmd"),
+ }
+ monkeypatch.setattr(stt_registry, "sidecar_for", lambda name: sidecars[name])
+
+ resident = stt_registry.resident()
+ assert resident["loading"] is True and resident["engine"] == "gguf"
+
+
+def test_resident_reports_nothing_when_every_engine_is_idle(monkeypatch):
+ monkeypatch.setattr(stt_registry, "sidecar_for", lambda name: _Sidecar(name))
+ assert stt_registry.resident()["model"] is None
+
+
+def test_an_unimportable_engine_never_takes_the_status_down(monkeypatch):
+ def make(name):
+ if name == "gguf":
+ raise ImportError("whisper.cpp bindings missing")
+ return _Sidecar(name, model = "small" if name == "mtmd" else None)
+
+ monkeypatch.setattr(stt_registry, "sidecar_for", make)
+ # gguf raising must not hide the model mtmd is holding.
+ assert stt_registry.resident()["model"] == "small"
+
+
+def test_the_orchestrator_exposes_the_same_lifecycle(monkeypatch):
+ from core.inference.orchestrator import InferenceOrchestrator
+ for name in ("load_stt_model", "unload_stt_model", "resident_stt_model"):
+ assert callable(getattr(InferenceOrchestrator, name, None)), name
+
+
+def test_the_route_loads_through_the_orchestrator_when_one_exists(monkeypatch):
+ import routes.inference as ri
+ from core.inference import orchestrator as orch
+
+ class _Backend:
+ load_stt_model = "orchestrator-load"
+ unload_stt_model = "orchestrator-unload"
+
+ monkeypatch.setattr(orch, "peek_inference_backend", lambda: _Backend())
+ assert ri._stt_lifecycle() == ("orchestrator-load", "orchestrator-unload")
+
+
+def test_a_cold_process_loads_without_building_an_orchestrator(monkeypatch):
+ import routes.inference as ri
+ from core.inference import orchestrator as orch
+
+ def _never():
+ raise AssertionError("dictation must not construct the chat orchestrator")
+
+ monkeypatch.setattr(orch, "peek_inference_backend", lambda: None)
+ monkeypatch.setattr(orch, "get_inference_backend", _never)
+ # Same functions the orchestrator's methods forward to, so neither path
+ # can drift from the other.
+ assert ri._stt_lifecycle() == (stt_registry.load, stt_registry.unload)
diff --git a/studio/backend/tests/test_stt_review_fixes.py b/studio/backend/tests/test_stt_review_fixes.py
index e4495506a35..2376b25c6a6 100644
--- a/studio/backend/tests/test_stt_review_fixes.py
+++ b/studio/backend/tests/test_stt_review_fixes.py
@@ -145,7 +145,9 @@ def test_gguf_unload_targets_transformers_fallback_without_whisper_server(monkey
def unload(self):
calls.append(self.name)
- monkeypatch.setattr(ri, "_stt_sidecar_for", lambda name: _Sidecar(name))
+ from core.inference import stt_registry
+
+ monkeypatch.setattr(stt_registry, "sidecar_for", lambda name: _Sidecar(name))
resp = asyncio.run(ri.stt_unload(engine = "gguf", current_subject = "tester"))
assert resp.status_code == 200
@@ -153,7 +155,7 @@ def test_gguf_unload_targets_transformers_fallback_without_whisper_server(monkey
assert calls == ["transformers"]
-def test_unload_all_attempts_both_backends_even_when_one_fails(monkeypatch):
+def test_unload_all_attempts_every_backend_even_when_one_fails(monkeypatch):
import routes.inference as ri
attempted: list = []
@@ -167,14 +169,17 @@ def test_unload_all_attempts_both_backends_even_when_one_fails(monkeypatch):
if self.name == "transformers":
raise RuntimeError("boom")
- monkeypatch.setattr(ri, "_stt_sidecar_for", lambda name: _Sidecar(name))
+ from core.inference import stt_registry
+
+ monkeypatch.setattr(stt_registry, "sidecar_for", lambda name: _Sidecar(name))
with pytest.raises(HTTPException) as excinfo:
asyncio.run(ri.stt_unload(engine = None, current_subject = "tester"))
assert excinfo.value.status_code == 500
- # gguf is still attempted after the transformers unload raised.
- assert attempted == ["transformers", "gguf"]
+ # The later engines are still attempted after transformers raised. mtmd is
+ # included so an Unload with no engine frees a resident llama-server too.
+ assert attempted == ["transformers", "gguf", "mtmd"]
# 4. free_stt_model_for_training isolates the two backends -----------------------
diff --git a/studio/backend/tests/test_stt_review_fixes_2.py b/studio/backend/tests/test_stt_review_fixes_2.py
index f0bdab42b5c..8dfa6d61cff 100644
--- a/studio/backend/tests/test_stt_review_fixes_2.py
+++ b/studio/backend/tests/test_stt_review_fixes_2.py
@@ -225,9 +225,27 @@ def test_download_pins_revision_and_limits_patterns(monkeypatch):
validated_revision = "a" * 40
head_revision = "b" * 40
- def fake_snapshot_download(**kwargs):
- captured.update(kwargs)
- return "/cached"
+ class _FakeProcess:
+ returncode = 0
+
+ def poll(self):
+ return 0
+
+ def communicate(self):
+ return (None, b"")
+
+ def fake_spawn_download(args, hf_token = None):
+ # The transfer moved to a worker process; pinning is now in its argv.
+ remaining = iter(args)
+ patterns: list[str] = []
+ for flag in remaining:
+ value = next(remaining)
+ if flag == "--revision":
+ captured["revision"] = value
+ elif flag == "--allow-pattern":
+ patterns.append(value)
+ captured["allow_patterns"] = patterns
+ return _FakeProcess()
class _FakeApi:
def __init__(self, token = None):
@@ -254,7 +272,7 @@ def test_download_pins_revision_and_limits_patterns(monkeypatch):
import huggingface_hub
monkeypatch.setattr(huggingface_hub, "HfApi", _FakeApi)
- monkeypatch.setattr(huggingface_hub, "snapshot_download", fake_snapshot_download)
+ monkeypatch.setattr("core.inference.stt_download_worker.spawn_download", fake_spawn_download)
state = stt_sidecar_module._SnapshotDownloadState()
# The revision resolved at validation time wins over the current head.
diff --git a/studio/backend/tests/test_stt_review_fixes_3.py b/studio/backend/tests/test_stt_review_fixes_3.py
new file mode 100644
index 00000000000..4fffd82a608
--- /dev/null
+++ b/studio/backend/tests/test_stt_review_fixes_3.py
@@ -0,0 +1,605 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Third review pass: mtmd startup preemption, reaping and idle-timer safety."""
+
+import subprocess
+import threading
+import time
+
+import pytest
+
+from core.inference import stt_mtmd_sidecar as mtmd_mod
+from core.inference.stt_mtmd_sidecar import MtmdSttSidecar
+
+
+class _FakeProcess:
+ """A child that stays alive until terminated, and can refuse SIGTERM."""
+
+ _next_pid = 9000
+
+ def __init__(self, ignores_sigterm = False):
+ _FakeProcess._next_pid += 1
+ self.pid = _FakeProcess._next_pid
+ self._returncode = None
+ self.terminated = False
+ self.killed = False
+ self.waited = False
+ self._ignores_sigterm = ignores_sigterm
+
+ def poll(self):
+ return self._returncode
+
+ def terminate(self):
+ self.terminated = True
+ if not self._ignores_sigterm:
+ self._returncode = -15
+
+ def kill(self):
+ self.killed = True
+ self._returncode = -9
+
+ def wait(self, timeout = None):
+ self.waited = True
+ if self._returncode is None:
+ raise subprocess.TimeoutExpired("llama-server", timeout)
+ return self._returncode
+
+
+def spawned(monkeypatch):
+ """Capture the child a load spawns, with the PID registry stubbed out."""
+ made = []
+ adopted, forgotten = [], []
+
+ def fake_popen(cmd, **kwargs):
+ process = _FakeProcess()
+ made.append(process)
+ return process
+
+ monkeypatch.setattr(mtmd_mod.subprocess, "Popen", fake_popen)
+ monkeypatch.setattr(mtmd_mod, "adopt_pid", adopted.append)
+ monkeypatch.setattr(mtmd_mod, "forget_pid", forgotten.append)
+ monkeypatch.setattr(mtmd_mod, "ensure_engine_available", lambda: "/bin/llama-server")
+ monkeypatch.setattr(mtmd_mod, "_llama_server_child_env", lambda binary: {})
+ monkeypatch.setattr(mtmd_mod, "_training_active", lambda: False)
+ monkeypatch.setattr(
+ MtmdSttSidecar, "_ensure_model_downloaded", lambda self, model_id: ("m.gguf", "p.gguf")
+ )
+ return made, adopted, forgotten
+
+
+def test_training_preempts_a_startup_before_it_can_publish(spawned, monkeypatch):
+ """_process is only set once the server is ready, so training had nothing to
+ act on for the whole startup and raced a child that was still allocating."""
+ made, _, forgotten = spawned
+ sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
+ started = threading.Event()
+
+ def never_ready(
+ process,
+ port,
+ cancel_event = None,
+ ):
+ started.set()
+ while not (cancel_event is not None and cancel_event.is_set()):
+ time.sleep(0.01)
+ return False
+
+ monkeypatch.setattr(MtmdSttSidecar, "_wait_for_server", staticmethod(never_ready))
+ loader = threading.Thread(target = lambda: _swallow(sidecar, "qwen3-asr-0.6b"))
+ loader.start()
+ try:
+ assert started.wait(2), "startup never began"
+ assert sidecar.is_loading()
+ assert sidecar.cancel_pending_load() is True
+ sidecar.wait_for_load_to_settle()
+ finally:
+ loader.join(timeout = 5)
+
+ assert made[0].terminated, "the starting llama-server was left allocating"
+ assert forgotten == [made[0].pid], "a reaped PID must leave the registry"
+
+
+def test_cancel_pending_load_reports_when_there_is_nothing_to_cancel():
+ sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
+ assert sidecar.cancel_pending_load() is False
+
+
+def test_a_child_that_ignores_sigterm_is_killed_not_abandoned(monkeypatch):
+ forgotten = []
+ monkeypatch.setattr(mtmd_mod, "forget_pid", forgotten.append)
+ process = _FakeProcess(ignores_sigterm = True)
+
+ mtmd_mod._reap(process)
+
+ assert process.terminated and process.killed, "SIGTERM alone leaves it holding the GPU"
+ assert forgotten == [process.pid]
+
+
+def test_the_idle_timer_cannot_fire_during_a_long_transcription():
+ """Audio may run longer than the keep-alive, and posting happens outside the
+ lock, so an armed timer would kill llama-server mid-request."""
+ sidecar = MtmdSttSidecar(keep_alive_seconds = 300)
+ with sidecar._lock:
+ sidecar._active_requests = 1
+ sidecar._schedule_idle_unload_locked()
+ assert sidecar._idle_timer is None
+
+ sidecar._active_requests = 0
+ sidecar._schedule_idle_unload_locked()
+ assert sidecar._idle_timer is not None
+ sidecar._cancel_idle_unload_locked()
+
+
+def test_an_update_blocks_new_dictation_loads(spawned):
+ sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
+ with sidecar.update_maintenance() as was_active:
+ assert was_active is False
+ with pytest.raises(mtmd_mod.SttUnavailableError, match = "being updated"):
+ sidecar.load("qwen3-asr-0.6b")
+ # Released again once the install finishes.
+ assert sidecar._update_in_progress is False
+
+
+def test_the_llama_updater_holds_the_dictation_guard(monkeypatch):
+ from contextlib import ExitStack, contextmanager
+
+ from utils import llama_cpp_update
+
+ entered, exited = [], []
+
+ class _Sidecar:
+ @contextmanager
+ def update_maintenance(self):
+ entered.append(True)
+ try:
+ yield True
+ finally:
+ exited.append(True)
+
+ monkeypatch.setattr("core.inference.stt_mtmd_sidecar.get_mtmd_stt_sidecar", lambda: _Sidecar())
+ stack = ExitStack()
+ assert llama_cpp_update._block_mtmd_sidecar(stack) is True
+ assert entered and not exited, "the guard must be held across the install"
+ stack.close()
+ assert exited
+
+
+def test_an_unimportable_sidecar_never_blocks_a_llama_update(monkeypatch):
+ from contextlib import ExitStack
+
+ from utils import llama_cpp_update
+
+ def boom():
+ raise ImportError("no dictation on this host")
+
+ monkeypatch.setattr("core.inference.stt_mtmd_sidecar.get_mtmd_stt_sidecar", boom)
+ assert llama_cpp_update._block_mtmd_sidecar(ExitStack()) is False
+
+
+def test_a_reaped_download_worker_leaves_the_shutdown_registry(monkeypatch):
+ from core.inference import stt_download_worker
+
+ forgotten = []
+ monkeypatch.setattr("utils.process_lifetime.forget_pid", forgotten.append)
+
+ class _Worker:
+ pid = 4242
+
+ def communicate(self):
+ return b"", b"boom"
+
+ assert stt_download_worker.reap_download(_Worker()) == b"boom"
+ assert forgotten == [4242], "a PID left adopted can be reused and then signalled"
+
+
+def _swallow(sidecar, model_id):
+ try:
+ sidecar.load(model_id)
+ except Exception:
+ pass
+
+
+def test_a_switch_to_a_missing_model_keeps_the_working_one(spawned, monkeypatch):
+ """Releasing before the cache check cost a usable server on a 409."""
+ made, _, _ = spawned
+ sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
+ monkeypatch.setattr(MtmdSttSidecar, "_wait_for_server", staticmethod(lambda *a, **k: True))
+ sidecar.load("qwen3-asr-0.6b")
+ assert sidecar.loaded_model == "qwen3-asr-0.6b"
+
+ def missing(self, model_id):
+ raise mtmd_mod.SttModelNotDownloadedError(f"'{model_id}' is not downloaded.")
+
+ monkeypatch.setattr(MtmdSttSidecar, "_ensure_model_downloaded", missing)
+ with pytest.raises(mtmd_mod.SttModelNotDownloadedError):
+ sidecar.load("qwen3-asr-1.7b")
+
+ assert sidecar.loaded_model == "qwen3-asr-0.6b", "the working server was torn down"
+ assert made[0].poll() is None
+ sidecar.unload()
+
+
+def test_a_model_switch_never_kills_a_running_transcription(spawned, monkeypatch):
+ made, _, _ = spawned
+ sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
+ monkeypatch.setattr(MtmdSttSidecar, "_wait_for_server", staticmethod(lambda *a, **k: True))
+ sidecar.load("qwen3-asr-0.6b")
+ with sidecar._lock:
+ sidecar._active_requests = 1 # mid _post_transcribe, outside the lock
+
+ with pytest.raises(mtmd_mod.SttModelBusyError):
+ sidecar.load("qwen3-asr-1.7b")
+ assert made[0].poll() is None, "the in-flight request's server was killed"
+
+ # The same model is a no-op, so a concurrent transcribe is never refused.
+ sidecar.load("qwen3-asr-0.6b")
+ with sidecar._lock:
+ sidecar._active_requests = 0
+ sidecar.unload()
+
+
+def test_a_dead_server_can_still_be_replaced_while_a_request_is_pending(spawned, monkeypatch):
+ made, _, _ = spawned
+ sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
+ monkeypatch.setattr(MtmdSttSidecar, "_wait_for_server", staticmethod(lambda *a, **k: True))
+ sidecar.load("qwen3-asr-0.6b")
+ made[0]._returncode = 1 # crashed under the request
+ with sidecar._lock:
+ sidecar._active_requests = 1
+
+ sidecar.load("qwen3-asr-1.7b")
+ assert sidecar.loaded_model == "qwen3-asr-1.7b"
+ with sidecar._lock:
+ sidecar._active_requests = 0
+ sidecar.unload()
+
+
+def test_the_output_cap_follows_the_length_of_the_audio():
+ budget = mtmd_mod._transcript_token_budget
+ # A fixed 2048 truncated anything past roughly ten minutes of speech.
+ assert budget(30 * 60) > 2048
+ assert budget(1.0) == mtmd_mod._MIN_TRANSCRIPT_TOKENS
+ assert budget(None) == mtmd_mod._MIN_TRANSCRIPT_TOKENS
+ assert budget(0) == mtmd_mod._MIN_TRANSCRIPT_TOKENS
+ assert budget(-5) == mtmd_mod._MIN_TRANSCRIPT_TOKENS
+ # Bounded, so it stays inside the context that also holds the audio.
+ assert budget(10**6) == mtmd_mod._MAX_TRANSCRIPT_TOKENS
+ assert budget(120) > budget(60)
+
+
+def test_the_engine_is_unavailable_without_pyav(monkeypatch):
+ """whisper.cpp already refuses here; every transcription 501s on decode."""
+ import builtins
+
+ monkeypatch.setattr(mtmd_mod, "find_llama_server_binary", lambda: "/bin/llama-server")
+ assert mtmd_mod.is_available() is True
+
+ real_import = builtins.__import__
+
+ def no_av(name, *args, **kwargs):
+ if name == "av":
+ raise ImportError("No module named 'av'")
+ return real_import(name, *args, **kwargs)
+
+ monkeypatch.setattr(builtins, "__import__", no_av)
+ assert mtmd_mod.is_available() is False
+
+
+def test_a_training_load_pins_the_projector_off_the_gpu_too(spawned, monkeypatch):
+ """-ngl 0 covers the main model only; clip.cpp offloads on its own flag."""
+ commands = []
+
+ def capture(cmd, **kwargs):
+ commands.append([str(a) for a in cmd])
+ return _FakeProcess()
+
+ monkeypatch.setattr(mtmd_mod.subprocess, "Popen", capture)
+ monkeypatch.setattr(MtmdSttSidecar, "_wait_for_server", staticmethod(lambda *a, **k: True))
+ monkeypatch.setattr(mtmd_mod, "_training_active", lambda: True)
+
+ sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
+ sidecar.load("qwen3-asr-0.6b")
+
+ cmd = commands[0]
+ assert cmd[cmd.index("-ngl") + 1] == "0"
+ assert "--mmproj" in cmd, "the projector is what needs pinning"
+ assert cmd[-1] == "--no-mmproj-offload", "last flag wins, so it must be last"
+ sidecar.unload()
+
+
+def test_an_ordinary_load_keeps_the_gpu(spawned, monkeypatch):
+ commands = []
+
+ def capture(cmd, **kwargs):
+ commands.append([str(a) for a in cmd])
+ return _FakeProcess()
+
+ monkeypatch.setattr(mtmd_mod.subprocess, "Popen", capture)
+ monkeypatch.setattr(MtmdSttSidecar, "_wait_for_server", staticmethod(lambda *a, **k: True))
+ monkeypatch.setattr(mtmd_mod, "_training_active", lambda: False)
+
+ sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
+ sidecar.load("qwen3-asr-0.6b")
+
+ cmd = commands[0]
+ assert cmd[cmd.index("-ngl") + 1] == "99"
+ assert "--no-mmproj-offload" not in cmd
+ sidecar.unload()
+
+
+def test_unload_stops_a_startup_instead_of_letting_it_publish(spawned, monkeypatch):
+ """_process is unset during startup, so a plain release was a no-op and the
+ model came back resident moments after the user unloaded it."""
+ made, _, forgotten = spawned
+ sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
+ started = threading.Event()
+
+ def never_ready(
+ process,
+ port,
+ cancel_event = None,
+ ):
+ started.set()
+ while not (cancel_event is not None and cancel_event.is_set()):
+ time.sleep(0.01)
+ return False
+
+ monkeypatch.setattr(MtmdSttSidecar, "_wait_for_server", staticmethod(never_ready))
+ loader = threading.Thread(target = lambda: _swallow(sidecar, "qwen3-asr-0.6b"))
+ loader.start()
+ try:
+ assert started.wait(2), "startup never began"
+ sidecar.unload()
+ finally:
+ loader.join(timeout = 5)
+
+ assert made[0].terminated, "the starting server survived an explicit unload"
+ assert sidecar.loaded_model is None
+ assert forgotten == [made[0].pid]
+
+
+def test_the_cached_lookup_uses_studios_configured_cache(monkeypatch, tmp_path):
+ """A relocated cache is written by the worker and must be read there too."""
+ seen = {}
+
+ def fake_download(**kwargs):
+ seen.update(kwargs)
+ return "/cached/model.gguf"
+
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", fake_download)
+ monkeypatch.setattr("core.inference.stt_sidecar._active_hf_hub_cache", lambda: tmp_path)
+
+ assert mtmd_mod._cached_file("qwen3-asr-0.6b", "Qwen3-ASR-0.6B-Q8_0.gguf")
+ assert seen["cache_dir"] == str(tmp_path)
+ assert seen["local_files_only"] is True
+
+
+def test_a_server_started_for_training_goes_back_to_the_gpu_after(spawned, monkeypatch):
+ """-ngl 0 was sticky: the same model matched, so dictation stayed on CPU
+ until the keep-alive expired."""
+ commands = []
+
+ def capture(cmd, **kwargs):
+ commands.append([str(a) for a in cmd])
+ return _FakeProcess()
+
+ monkeypatch.setattr(mtmd_mod.subprocess, "Popen", capture)
+ monkeypatch.setattr(MtmdSttSidecar, "_wait_for_server", staticmethod(lambda *a, **k: True))
+
+ training = {"active": True}
+ monkeypatch.setattr(mtmd_mod, "_training_active", lambda: training["active"])
+ sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
+ sidecar.load("qwen3-asr-0.6b")
+ assert commands[0][commands[0].index("-ngl") + 1] == "0"
+
+ # Still training: the same server is reused, no restart.
+ sidecar.load("qwen3-asr-0.6b")
+ assert len(commands) == 1
+
+ training["active"] = False
+ sidecar.load("qwen3-asr-0.6b")
+ assert len(commands) == 2, "the CPU-only server was never replaced"
+ assert commands[1][commands[1].index("-ngl") + 1] == "99"
+ assert "--no-mmproj-offload" not in commands[1]
+ sidecar.unload()
+
+
+def test_a_running_transcription_outranks_the_offload_upgrade(spawned, monkeypatch):
+ """Swapping to the GPU is an optimisation; it must not kill a request."""
+ commands = []
+
+ def capture(cmd, **kwargs):
+ commands.append([str(a) for a in cmd])
+ return _FakeProcess()
+
+ monkeypatch.setattr(mtmd_mod.subprocess, "Popen", capture)
+ monkeypatch.setattr(MtmdSttSidecar, "_wait_for_server", staticmethod(lambda *a, **k: True))
+
+ training = {"active": True}
+ monkeypatch.setattr(mtmd_mod, "_training_active", lambda: training["active"])
+ sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
+ sidecar.load("qwen3-asr-0.6b")
+
+ training["active"] = False
+ with sidecar._lock:
+ sidecar._active_requests = 1
+ sidecar.load("qwen3-asr-0.6b")
+ assert len(commands) == 1, "an in-flight transcription was torn down for -ngl"
+
+ with sidecar._lock:
+ sidecar._active_requests = 0
+ sidecar.load("qwen3-asr-0.6b")
+ assert len(commands) == 2, "the upgrade should happen once the request is done"
+ sidecar.unload()
+
+
+def test_audio_is_never_sent_to_a_server_another_client_swapped_in(spawned, monkeypatch):
+ """load() returns before the request slot is taken, so the model can change
+ in between and the port read would be the other server's."""
+ sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
+ monkeypatch.setattr(MtmdSttSidecar, "_wait_for_server", staticmethod(lambda *a, **k: True))
+ monkeypatch.setattr(mtmd_mod, "_decode_audio_bounded", lambda audio: b"\x00\x00" * 16000)
+ monkeypatch.setattr(mtmd_mod, "_pcm_to_wav_bytes", lambda pcm: b"RIFFwav")
+
+ posted = []
+ monkeypatch.setattr(
+ MtmdSttSidecar,
+ "_post_transcribe",
+ lambda self, port, model_id, wav, seconds = None: posted.append((port, model_id)) or "hi",
+ )
+
+ def swap_after_load(self, model = None):
+ # Stands in for another client switching the singleton in the gap.
+ with self._lock:
+ self._process = _FakeProcess()
+ self._port = 65000
+ self._model_id = "qwen3-asr-1.7b"
+
+ monkeypatch.setattr(MtmdSttSidecar, "load", swap_after_load)
+ with pytest.raises(mtmd_mod.SttModelBusyError):
+ sidecar.transcribe(b"audio", model = "qwen3-asr-0.6b")
+ assert posted == [], "audio went to the model the other client loaded"
+
+
+def test_a_busy_transcription_is_a_retry_not_a_server_error(monkeypatch):
+ """The model-switch race is ordinary concurrency, so the client is told to
+ try again rather than shown a 500."""
+ import asyncio
+
+ import routes.inference as ri
+ from core.inference.stt_sidecar import SttModelBusyError
+ from fastapi import HTTPException
+
+ def busy(*args, **kwargs):
+ raise SttModelBusyError("The dictation model changed. Try again.")
+
+ monkeypatch.setattr(
+ ri, "_stt_sidecar_for", lambda engine: type("S", (), {"transcribe": busy})()
+ )
+ monkeypatch.setattr(ri, "_resolve_serving_stt_engine", lambda engine: "mtmd")
+
+ with pytest.raises(HTTPException) as excinfo:
+ asyncio.run(
+ ri._transcribe_audio_bytes(
+ b"audio",
+ model = "qwen3-asr-0.6b",
+ language = None,
+ fast = True,
+ engine = "mtmd",
+ )
+ )
+ assert excinfo.value.status_code == 409
+ assert "Try again" in str(excinfo.value.detail)
+
+
+def test_dictation_still_works_on_cpu_during_training(spawned, monkeypatch):
+ """load() starts at -ngl 0 while a run is active, so refusing here only
+ threw away a recording the preload had said was fine."""
+ monkeypatch.setattr(MtmdSttSidecar, "_wait_for_server", staticmethod(lambda *a, **k: True))
+ monkeypatch.setattr(mtmd_mod, "_training_active", lambda: True)
+ monkeypatch.setattr(mtmd_mod, "_decode_audio_bounded", lambda audio: b"\x00\x00" * 16000)
+ monkeypatch.setattr(mtmd_mod, "_pcm_to_wav_bytes", lambda pcm: b"RIFFwav")
+ monkeypatch.setattr(
+ MtmdSttSidecar,
+ "_post_transcribe",
+ lambda self, port, model_id, wav, seconds = None: "on cpu",
+ )
+
+ sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
+ result = sidecar.transcribe(b"audio", model = "qwen3-asr-0.6b")
+ assert result["text"] == "on cpu"
+ sidecar.unload()
+
+
+def test_a_startup_cancelled_for_training_is_retryable_not_unavailable(spawned, monkeypatch):
+ """501 reads as a broken runtime; this is ordinary preemption, so 409."""
+ sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
+ started = threading.Event()
+ raised = []
+
+ def never_ready(
+ process,
+ port,
+ cancel_event = None,
+ ):
+ started.set()
+ while not (cancel_event is not None and cancel_event.is_set()):
+ time.sleep(0.01)
+ return False
+
+ monkeypatch.setattr(MtmdSttSidecar, "_wait_for_server", staticmethod(never_ready))
+
+ def load_and_record():
+ try:
+ sidecar.load("qwen3-asr-0.6b")
+ except Exception as exc:
+ raised.append(exc)
+
+ loader = threading.Thread(target = load_and_record)
+ loader.start()
+ try:
+ assert started.wait(2), "startup never began"
+ sidecar.cancel_pending_load()
+ finally:
+ loader.join(timeout = 5)
+
+ assert raised and isinstance(raised[0], mtmd_mod.SttLoadCancelledError)
+ # Not the 501 class: the route separates them by exception type.
+ assert not isinstance(raised[0], mtmd_mod.SttUnavailableError)
+
+
+def test_training_that_starts_while_the_old_server_is_reaped_still_pins_the_cpu(
+ spawned, monkeypatch
+):
+ """Reaping the previous server can take seconds, and training admission that
+ already ran cannot come back to cancel this load, so the offload flags have
+ to read training last rather than from the snapshot taken before the reap."""
+ commands = []
+ training = {"active": False}
+ real_reap = mtmd_mod._reap
+
+ def capture(cmd, **kwargs):
+ commands.append([str(a) for a in cmd])
+ return _FakeProcess()
+
+ def reap_then_train(process):
+ # The run that was admitted while this load waited on the reap.
+ training["active"] = True
+ real_reap(process)
+
+ monkeypatch.setattr(mtmd_mod.subprocess, "Popen", capture)
+ monkeypatch.setattr(MtmdSttSidecar, "_wait_for_server", staticmethod(lambda *a, **k: True))
+ monkeypatch.setattr(mtmd_mod, "_training_active", lambda: training["active"])
+
+ sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
+ sidecar.load("qwen3-asr-0.6b")
+ assert commands[0][commands[0].index("-ngl") + 1] == "99", "nothing was training yet"
+
+ monkeypatch.setattr(mtmd_mod, "_reap", reap_then_train)
+ sidecar.load("qwen3-asr-1.7b")
+
+ cmd = commands[1]
+ assert cmd[cmd.index("-ngl") + 1] == "0", "spawned onto VRAM the training run had claimed"
+ assert "--no-mmproj-offload" in cmd, "the projector would still have been offloaded"
+ sidecar.unload()
+
+
+def test_a_load_is_cancellable_before_it_decides_where_to_run(spawned, monkeypatch):
+ """The other order: admission arriving after the snapshot must find a load
+ it can cancel, so _loading is published before training is read."""
+ seen = []
+ sidecar = MtmdSttSidecar(keep_alive_seconds = 0)
+
+ def training_active():
+ seen.append(sidecar.is_loading())
+ return False
+
+ monkeypatch.setattr(MtmdSttSidecar, "_wait_for_server", staticmethod(lambda *a, **k: True))
+ monkeypatch.setattr(mtmd_mod, "_training_active", training_active)
+
+ sidecar.load("qwen3-asr-0.6b")
+
+ assert seen[-1] is True, "the deciding read happened while nothing could cancel the load"
+ sidecar.unload()
diff --git a/studio/backend/tests/test_stt_sidecar.py b/studio/backend/tests/test_stt_sidecar.py
index b138f463317..477ba018bea 100644
--- a/studio/backend/tests/test_stt_sidecar.py
+++ b/studio/backend/tests/test_stt_sidecar.py
@@ -1108,6 +1108,35 @@ def test_progress_counts_only_selected_blobs_and_caps_incomplete_files(monkeypat
assert status["bytes_done"] == 30
+class _FakeDownloadProcess:
+ """Stands in for the worker subprocess: immediate success."""
+
+ returncode = 0
+
+ def poll(self):
+ return 0
+
+ def communicate(self):
+ return (None, b"")
+
+
+def _worker_args(args) -> dict:
+ """Parse the download worker's argv into the fields tests assert on."""
+ parsed: dict = {"allow_patterns": []}
+ remaining = iter(args)
+ for flag in remaining:
+ value = next(remaining)
+ if flag == "--repo-id":
+ parsed["repo_id"] = value
+ elif flag == "--revision":
+ parsed["revision"] = value
+ elif flag == "--filename":
+ parsed["filename"] = value
+ elif flag == "--allow-pattern":
+ parsed["allow_patterns"].append(value)
+ return parsed
+
+
def test_download_metadata_and_snapshot_use_the_same_revision(monkeypatch, tmp_path):
revision = "e" * 40
calls = []
@@ -1127,12 +1156,13 @@ def test_download_metadata_and_snapshot_use_the_same_revision(monkeypatch, tmp_p
calls.append(("info", repo, kwargs))
return SimpleNamespace(sha = revision, siblings = siblings)
- def fake_snapshot_download(**kwargs):
- calls.append(("snapshot", kwargs))
- return str(tmp_path)
+ def fake_spawn_download(args, hf_token = None):
+ calls.append(("snapshot", _worker_args(args)))
+ return _FakeDownloadProcess()
monkeypatch.setattr("huggingface_hub.HfApi", FakeApi)
- monkeypatch.setattr("huggingface_hub.snapshot_download", fake_snapshot_download)
+ # The transfer runs in a worker process, so assert on its argv.
+ monkeypatch.setattr("core.inference.stt_download_worker.spawn_download", fake_spawn_download)
monkeypatch.setattr(
"huggingface_hub.hf_hub_download",
lambda **_kwargs: pytest.fail("unsharded selection must not load an index"),
@@ -1163,6 +1193,7 @@ def test_download_status_is_idle_before_any_download():
"downloading": False,
"model": None,
"error": None,
+ "cancelled": False,
"bytes_total": None,
"bytes_done": None,
}
diff --git a/studio/backend/utils/hidden_models.py b/studio/backend/utils/hidden_models.py
index e7c3181d718..22a9b349680 100644
--- a/studio/backend/utils/hidden_models.py
+++ b/studio/backend/utils/hidden_models.py
@@ -32,11 +32,13 @@ _DEFAULT_EMBEDDING_REPO_IDS = {
# fallback for Studio's static default embedder only; configured custom repos
# remain exact-match-only.
_DEFAULT_EMBEDDING_PATH_BASENAMES = {"bge-small-en-v1.5"}
-# Curated Whisper dictation checkpoints (STT, never chat), hidden from the chat
+# Curated dictation checkpoints (STT, never chat), hidden from the chat
# inventory and pickers: Transformers safetensors repos (unsloth/whisper-*) and
# their GGUF companions (unslothai/whisper-*-GGUF). Custom checkpoints are caught
# by config below, but the GGUF companions carry a raw .bin (no config.json), so
-# they must be listed here by id or they leak into chat pickers.
+# they must be listed here by id or they leak into chat pickers. The Qwen3-ASR
+# GGUFs are listed for the same reason: llama.cpp will happily load one as a
+# chat model, where it only answers with transcripts.
_HIDDEN_STT_REPO_IDS = frozenset(
{
"unsloth/whisper-tiny",
@@ -49,6 +51,8 @@ _HIDDEN_STT_REPO_IDS = frozenset(
"unslothai/whisper-small-GGUF",
"unslothai/whisper-large-v3-turbo-GGUF",
"unslothai/whisper-large-v3-GGUF",
+ "unslothai/Qwen3-ASR-0.6B-GGUF",
+ "unslothai/Qwen3-ASR-1.7B-GGUF",
}
)
diff --git a/studio/backend/utils/llama_cpp_update.py b/studio/backend/utils/llama_cpp_update.py
index 45c26d1b02f..f5e373fcff0 100644
--- a/studio/backend/utils/llama_cpp_update.py
+++ b/studio/backend/utils/llama_cpp_update.py
@@ -33,6 +33,7 @@ import re
import subprocess
import sys
import threading
+from contextlib import ExitStack
from pathlib import Path
from typing import Optional
@@ -421,6 +422,7 @@ def _run_llama_phase(
of letting it re-resolve "latest" itself (see start_update for why)."""
backend = None
model_was_active = False
+ mtmd_guard = ExitStack()
try:
# Block loads and free the binary while the installer swaps it.
try:
@@ -443,6 +445,11 @@ def _run_llama_phase(
except Exception as exc:
logger.debug("llama update: load coordination failed", error = str(exc))
+ # The mtmd dictation sidecar serves Qwen3-ASR from this same llama-server
+ # out of this same tree, so a live one locks the exe on Windows and a
+ # concurrent load would start against a half-swapped install.
+ model_was_active = _block_mtmd_sidecar(mtmd_guard) or model_was_active
+
cmd = [
sys.executable,
str(script),
@@ -522,6 +529,7 @@ def _run_llama_phase(
raise
finally:
# Always clear maintenance state.
+ mtmd_guard.close()
if backend is not None:
try:
backend._llama_update_in_progress = False
@@ -529,6 +537,21 @@ def _run_llama_phase(
pass
+def _block_mtmd_sidecar(stack: ExitStack) -> bool:
+ """Hold the mtmd sidecar's maintenance guard for the install, if it exists.
+
+ Unlike whisper.cpp this is not fail-closed: llama.cpp updates predate this
+ sidecar and must keep working where dictation cannot even be imported.
+ Returns whether a warm dictation server had to be unloaded.
+ """
+ try:
+ from core.inference.stt_mtmd_sidecar import get_mtmd_stt_sidecar
+ return stack.enter_context(get_mtmd_stt_sidecar().update_maintenance())
+ except Exception as exc: # noqa: BLE001 - the update proceeds without it
+ logger.debug("llama update: mtmd coordination failed", error = str(exc))
+ return False
+
+
# Combined-job progress split when both phases run (download sizes: the llama
# bundle dwarfs the whisper one); normalized to 0..1 when a phase is skipped.
_LLAMA_PHASE_WEIGHT = 0.7
diff --git a/studio/frontend/src/app/provider.tsx b/studio/frontend/src/app/provider.tsx
index f7385faab82..c97ecef9be5 100644
--- a/studio/frontend/src/app/provider.tsx
+++ b/studio/frontend/src/app/provider.tsx
@@ -23,6 +23,7 @@ import {
useAppearanceCustomStore,
useTheme,
} from "@/features/settings";
+import { SttDownloadPrompt } from "@/features/settings/components/stt-download-prompt";
import { TauriUpdateContext } from "@/hooks/tauri-update-context";
import { type BackendStatus, useTauriBackend } from "@/hooks/use-tauri-backend";
import { useTauriUpdate } from "@/hooks/use-tauri-update";
@@ -544,6 +545,7 @@ export function AppProvider({ children }: AppProviderProps) {
<AppearanceCustomizationEffect />
<DeepLinkHandler />
<TauriWrapper>{children}</TauriWrapper>
+ <SttDownloadPrompt />
<Toaster
position="top-right"
visibleToasts={2}
diff --git a/studio/frontend/src/features/chat/adapters/stt-errors.ts b/studio/frontend/src/features/chat/adapters/stt-errors.ts
new file mode 100644
index 00000000000..197a2c9043e
--- /dev/null
+++ b/studio/frontend/src/features/chat/adapters/stt-errors.ts
@@ -0,0 +1,24 @@
+// 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 selected local model has not been downloaded yet. */
+export class SttModelNotDownloadedError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "SttModelNotDownloadedError";
+ }
+}
+
+/** The error for a failed STT response, typed by what its status and detail say.
+ *
+ * Shared by the load and transcribe calls: a segment can be the first thing to
+ * learn the model is missing, when a short recording ends before the
+ * fire-and-forget preload rejects, and it has to open the download prompt just
+ * as the preload would. 409 also covers a load cancelled for training and a
+ * model switch mid-request, so the detail is what separates them.
+ */
+export function sttRequestError(status: number, detail: string): Error {
+ return status === 409 && /not downloaded/i.test(detail)
+ ? new SttModelNotDownloadedError(detail)
+ : new Error(detail);
+}
diff --git a/studio/frontend/src/features/chat/adapters/studio-dictation-adapter.tsx b/studio/frontend/src/features/chat/adapters/studio-dictation-adapter.tsx
index 4a077f14ff9..037db816d05 100644
--- a/studio/frontend/src/features/chat/adapters/studio-dictation-adapter.tsx
+++ b/studio/frontend/src/features/chat/adapters/studio-dictation-adapter.tsx
@@ -1,14 +1,18 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-import { useSettingsDialogStore } from "@/features/settings/stores/settings-dialog-store";
+import { requestSttDownload } from "@/features/settings/stores/stt-download-prompt-store";
import {
type DictationEngine,
useVoiceSettingsStore,
} from "@/features/settings/stores/voice-settings-store";
import { toast } from "@/lib/toast";
import type { DictationAdapter } from "@assistant-ui/react";
-import { StudioModelDictationAdapter } from "./studio-model-dictation-adapter";
+import {
+ StudioModelDictationAdapter,
+ fetchSttStatus,
+ sttEngineStatusFor,
+} from "./studio-model-dictation-adapter";
import {
type StudioDictationSession,
StudioWebSpeechDictationAdapter,
@@ -114,13 +118,40 @@ export function notifyStudioDictationUnavailable(
toast.error("Voice recording isn't available in this browser.");
return;
}
- // Browser Web Speech is missing (e.g. Firefox).
- toast.error("Voice typing isn't available in this browser.", {
- description:
- "Choose the local speech-to-text model in Voice settings to dictate here.",
- action: {
- label: "Open Voice settings",
- onClick: () => useSettingsDialogStore.getState().openDialog("voice"),
- },
- });
+ // Browser Web Speech is missing (e.g. Firefox). Local dictation is the only
+ // way to type by voice here, so offer it rather than describing it.
+ void offerLocalDictation();
+}
+
+/**
+ * Move a browser with no speech service onto local dictation. Already
+ * downloaded means one switch; otherwise the same confirmation the mic raises,
+ * which flips the engine only if it is accepted.
+ */
+async function offerLocalDictation(): Promise<void> {
+ const { sttModel, setDictationEngine } = useVoiceSettingsStore.getState();
+ try {
+ const status = await fetchSttStatus(undefined, sttModel);
+ const engine = sttEngineStatusFor(status, sttModel);
+ // An engine with no runtime installed cannot load what it downloads, so
+ // say what is missing rather than asking for gigabytes first.
+ if (engine && !engine.available) {
+ toast.error("Local transcription isn't installed on this server.", {
+ description:
+ "Run `unsloth studio update` to install it, then choose a model in Voice settings.",
+ });
+ return;
+ }
+ if (engine?.downloaded_models.includes(sttModel)) {
+ setDictationEngine("model");
+ toast.success("Switched to local transcription.", {
+ description:
+ "Voice typing isn't available in this browser. Press the mic again to dictate.",
+ });
+ return;
+ }
+ } catch {
+ // Status is unreachable; the download path reports its own failure.
+ }
+ requestSttDownload(sttModel, { selectLocalEngine: true });
}
diff --git a/studio/frontend/src/features/chat/adapters/studio-model-dictation-adapter.ts b/studio/frontend/src/features/chat/adapters/studio-model-dictation-adapter.ts
index e525323f21c..830052b5fb8 100644
--- a/studio/frontend/src/features/chat/adapters/studio-model-dictation-adapter.ts
+++ b/studio/frontend/src/features/chat/adapters/studio-model-dictation-adapter.ts
@@ -4,7 +4,9 @@
import { authFetch } from "@/features/auth";
import { hubTokenHeader } from "@/features/hub/lib/hub-token-header";
import { useSettingsDialogStore } from "@/features/settings/stores/settings-dialog-store";
+import { requestSttDownload } from "@/features/settings/stores/stt-download-prompt-store";
import {
+ MTMD_STT_MODELS,
applyDictationDictionary,
isCuratedSttModel,
recordRecentDictation,
@@ -14,6 +16,9 @@ import {
import type { DictationAdapter } from "@assistant-ui/react";
import { toast } from "sonner";
import { startDictationLevelMeter } from "./dictation-level";
+import { SttModelNotDownloadedError, sttRequestError } from "./stt-errors";
+// Re-exported so the one public entry point for dictation is unchanged.
+export { SttModelNotDownloadedError } from "./stt-errors";
import {
beginDictationSession,
markDictationFailed,
@@ -59,11 +64,14 @@ const stopStream = (stream: MediaStream | null) => {
}
};
-/** Backend STT engine, decided by the model: curated ids run GGML through
- * whisper.cpp; a custom HF repo is safetensors and runs through Transformers. */
-export type SttEngine = "transformers" | "gguf";
+/** Backend STT engine, decided by the model: Whisper ids run GGML through
+ * whisper.cpp, mtmd ids run through llama.cpp, and a custom HF repo is
+ * safetensors on Transformers. */
+export type SttEngine = "transformers" | "gguf" | "mtmd";
export function sttEngineFor(model: string): SttEngine {
+ // whisper.cpp is Whisper-only, so the newer ASR models go to llama.cpp.
+ if (MTMD_STT_MODELS.has(model.trim())) return "mtmd";
return isCuratedSttModel(model) ? "gguf" : "transformers";
}
@@ -105,7 +113,7 @@ export async function transcribeAudioBlob(
"Speech-to-text is not available on this server. Run `unsloth studio update` to install it.",
);
}
- throw new Error(detail);
+ throw sttRequestError(response.status, detail);
}
const data = (await response.json()) as { text?: string };
return (data.text ?? "").trim();
@@ -115,6 +123,8 @@ export interface SttDownloadStatus {
downloading: boolean;
model: string | null;
error: string | null;
+ /** The last download was stopped by the user rather than failing. */
+ cancelled?: boolean;
bytes_total: number | null;
bytes_done: number | null;
}
@@ -125,7 +135,7 @@ export interface SttEngineStatus {
loading: boolean;
device: string | null;
keep_alive_seconds: number;
- default_model: string;
+ default_model: string | null;
models: string[];
downloaded_models: string[];
download: SttDownloadStatus;
@@ -142,6 +152,7 @@ export interface SttStatus {
/** Per-engine state; absent on servers predating the engine split. */
transformers?: SttEngineStatus;
gguf?: SttEngineStatus;
+ mtmd?: SttEngineStatus;
}
// Keep load/unload requests ordered so a new recording cannot race an unload
@@ -171,6 +182,19 @@ export async function fetchSttStatus(
return (await response.json()) as SttStatus;
}
+/** The engine block that owns `model`. A curated Whisper prefers whisper.cpp,
+ * but without whisper-server the backend serves it through Transformers, so
+ * that is the fallback. mtmd models run nowhere else. */
+export function sttEngineStatusFor(
+ status: SttStatus,
+ model: string,
+): SttEngineStatus | undefined {
+ const engine = sttEngineFor(model);
+ if (engine === "mtmd") return status.mtmd;
+ if (engine === "gguf" && status.gguf?.available) return status.gguf;
+ return status.transformers;
+}
+
/** Verify a custom Hub repository is a Transformers Whisper checkpoint. */
export async function validateSttModel(
model: string,
@@ -205,7 +229,8 @@ export function loadSttModel(model: string, engine?: SttEngine): Promise<void> {
const body = (await response.json().catch(() => null)) as {
detail?: string;
} | null;
- throw new Error(body?.detail ?? `HTTP ${response.status}`);
+ const detail = body?.detail ?? `HTTP ${response.status}`;
+ throw sttRequestError(response.status, detail);
}
});
}
@@ -231,6 +256,22 @@ export async function startSttDownload(
}
}
+/** Stop an in-flight model download. Partial files stay cached, so starting the
+ * same download again resumes from where it stopped. */
+export async function cancelSttDownload(model: string): Promise<void> {
+ const response = await authFetch("/api/inference/audio/stt/download/cancel", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ model, engine: sttEngineFor(model) }),
+ });
+ if (!response.ok) {
+ const body = (await response.json().catch(() => null)) as {
+ detail?: string;
+ } | null;
+ throw new Error(body?.detail ?? `HTTP ${response.status}`);
+ }
+}
+
/** Release the local STT model and its RAM/VRAM allocations. */
export function unloadSttModel(): Promise<void> {
return queueSttLifecycle(async () => {
@@ -333,20 +374,35 @@ export class StudioModelDictationAdapter implements DictationAdapter {
let finalCutDone = false;
let reportedTranscriptionError = false;
- const reportTranscriptionError = (error: unknown) => {
+ const reportTranscriptionError = (
+ error: unknown,
+ stage: "preload" | "segment" = "segment",
+ ) => {
if (reportedTranscriptionError || cancelled || ended) return;
reportedTranscriptionError = true;
+ console.error("STT transcription error:", error);
+ // An undownloaded model is the ordinary first-run state, not a failure.
+ // Point at the download; never start it here.
+ if (error instanceof SttModelNotDownloadedError) {
+ requestSttDownload(sessionModel);
+ finishSession("cancelled");
+ return;
+ }
const message =
error instanceof Error && error.message
? error.message
: "A recorded segment could not be transcribed.";
- console.error("STT transcription error:", error);
toast.error(message, {
action: {
label: "Open Voice settings",
onClick: () => useSettingsDialogStore.getState().openDialog("voice"),
},
});
+ // The preload runs cache-only, so nothing it reports is transient: a
+ // missing runtime or a load refused for training means no segment of
+ // this session can be transcribed. End it rather than let the user keep
+ // speaking into a recorder whose audio is already lost.
+ if (stage === "preload") finishSession("cancelled");
};
const buildTranscript = () =>
@@ -629,8 +685,8 @@ export class StudioModelDictationAdapter implements DictationAdapter {
}
// Warm the model only after mic access. The backend loads cache-only
// and never downloads here.
- void loadSttModel(sessionModel, sessionEngine).catch(
- reportTranscriptionError,
+ void loadSttModel(sessionModel, sessionEngine).catch((error: unknown) =>
+ reportTranscriptionError(error, "preload"),
);
stopLevelMeter = startDictationLevelMeter(stream, (rawRms, now) => {
onAudioFrame(rawRms, now);
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index e304fc397b5..c67f0f9ad6c 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -202,9 +202,12 @@ export {
} from "./adapters/studio-dictation-adapter";
export {
StudioModelDictationAdapter,
+ SttModelNotDownloadedError,
+ cancelSttDownload,
fetchSttStatus,
loadSttModel,
startSttDownload,
+ sttEngineStatusFor,
unloadSttModel,
validateSttModel,
type SttDownloadStatus,
diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-state.ts b/studio/frontend/src/features/hub/download-manager/download-manager-state.ts
index c78839b30f8..1f129ac895e 100644
--- a/studio/frontend/src/features/hub/download-manager/download-manager-state.ts
+++ b/studio/frontend/src/features/hub/download-manager/download-manager-state.ts
@@ -172,6 +172,10 @@ function collectCompletedInventoryHints(
): InventoryHint[] {
return Object.values(jobs).flatMap((job) => {
if (job.state !== "complete") return [];
+ // A dictation download is not a chat model arriving. A custom Whisper repo
+ // is only hidden once the backend has scanned its config, so an optimistic
+ // hint would surface it in the chat inventory for the hint's whole TTL.
+ if (job.external) return [];
const kind = completedInventoryHintKind(job.kind, job.variant);
if (
runtimeRegistry.suppressedCompletedInventoryHints.has(
@@ -224,7 +228,8 @@ export const useDownloadManagerStore = create<DownloadManagerState>()(
partialize: (state) => ({
jobs: Object.fromEntries(
Object.entries(state.jobs)
- .filter(([, job]) => ACTIVE_STATES.has(job.state))
+ // External jobs have no hub job to resume into, so they are not saved.
+ .filter(([, job]) => !job.external && ACTIVE_STATES.has(job.state))
.map(([key, job]) => [key, toPersistedJob(job)] as const),
),
conflicts: {},
diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-types.ts b/studio/frontend/src/features/hub/download-manager/download-manager-types.ts
index 0aa604c842c..b1474ea3681 100644
--- a/studio/frontend/src/features/hub/download-manager/download-manager-types.ts
+++ b/studio/frontend/src/features/hub/download-manager/download-manager-types.ts
@@ -28,6 +28,10 @@ export interface ManagedDownload {
serverGeneration?: number;
/** Files a scoped job is fetching, when known. Every file set of one repo rides the same scope slot (see `scopedVariant`), so this separates "my transfer is already running" from "a different quant of this repo is running": adopting the latter would report ready for files nobody fetched. Unknown stays adoptable only for an UNSCOPED job. */
scopedFiles?: string[];
+ // Driven by another subsystem (see external-jobs.ts), not the poll loop. Such
+ // a job is never persisted, probed against the hub API, or published as a
+ // chat-inventory hint when it completes.
+ external?: boolean;
}
export interface DownloadRequest {
diff --git a/studio/frontend/src/features/hub/download-manager/external-jobs.ts b/studio/frontend/src/features/hub/download-manager/external-jobs.ts
new file mode 100644
index 00000000000..c4070ad66e0
--- /dev/null
+++ b/studio/frontend/src/features/hub/download-manager/external-jobs.ts
@@ -0,0 +1,105 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import {
+ type TransferSample,
+ appendSample,
+ computeTransferStats,
+} from "@/lib/transfer-stats";
+import { DOWNLOAD_KIND } from "./constants";
+import { patchJob, putJob, scheduleRemoval } from "./download-manager-state";
+
+/**
+ * Downloads owned by another subsystem that still belong in the shared panel.
+ * Dictation models are fetched by the STT sidecars, not the hub API, so the
+ * poll loop cannot drive them; they report progress through here instead.
+ */
+
+const TERMINAL_LINGER_MS = 4_000;
+
+interface ExternalJob {
+ cancel: () => Promise<void> | void;
+ samples: TransferSample[];
+}
+
+const externalJobs = new Map<string, ExternalJob>();
+
+export function isExternalJob(key: string): boolean {
+ return externalJobs.has(key);
+}
+
+export async function cancelExternalJob(key: string): Promise<void> {
+ const job = externalJobs.get(key);
+ if (!job) return;
+ patchJob(key, { state: "cancelling" });
+ try {
+ await job.cancel();
+ } catch {
+ // The transfer is still running and progress updates do not reset state,
+ // so put the row back rather than leaving it stuck on "cancelling".
+ if (externalJobs.has(key)) patchJob(key, { state: "running" });
+ }
+}
+
+/** Register a job and show it in the panel. Re-registering keeps the row. */
+export function startExternalJob(init: {
+ key: string;
+ repoId: string;
+ variant: string | null;
+ expectedBytes: number;
+ cancel: () => Promise<void> | void;
+}): void {
+ externalJobs.set(init.key, { cancel: init.cancel, samples: [] });
+ putJob({
+ key: init.key,
+ kind: DOWNLOAD_KIND.MODEL,
+ repoId: init.repoId,
+ variant: init.variant,
+ state: "running",
+ downloadedBytes: 0,
+ completedBytes: 0,
+ completeOnDisk: false,
+ expectedBytes: Math.max(0, init.expectedBytes),
+ fraction: 0,
+ bytesPerSec: 0,
+ error: null,
+ startedAt: Date.now(),
+ external: true,
+ });
+}
+
+export function updateExternalJob(
+ key: string,
+ progress: { downloadedBytes: number; expectedBytes: number },
+): void {
+ const job = externalJobs.get(key);
+ if (!job) return;
+ const downloadedBytes = Math.max(0, progress.downloadedBytes);
+ const expectedBytes = Math.max(0, progress.expectedBytes);
+ appendSample(job.samples, Date.now() / 1000, downloadedBytes);
+ const stats = computeTransferStats(job.samples, expectedBytes);
+ patchJob(key, {
+ downloadedBytes,
+ expectedBytes,
+ fraction:
+ expectedBytes > 0 ? Math.min(1, downloadedBytes / expectedBytes) : 0,
+ // Unstable early samples read as absurd rates; show nothing until settled.
+ bytesPerSec: stats.stable ? stats.rateBytesPerSecond : 0,
+ });
+}
+
+/** Settle the row, then drop it the way a hub job does. */
+export function finishExternalJob(
+ key: string,
+ outcome: "complete" | "cancelled" | "error",
+ error?: string | null,
+): void {
+ if (!externalJobs.delete(key)) return;
+ patchJob(key, {
+ state: outcome,
+ bytesPerSec: 0,
+ error: outcome === "error" ? (error ?? "Download failed.") : null,
+ ...(outcome === "complete" ? { fraction: 1, completeOnDisk: true } : {}),
+ });
+ scheduleRemoval(key, TERMINAL_LINGER_MS);
+}
diff --git a/studio/frontend/src/features/hub/download-manager/hydration.ts b/studio/frontend/src/features/hub/download-manager/hydration.ts
index eb5fdee74ca..e33aefbfff2 100644
--- a/studio/frontend/src/features/hub/download-manager/hydration.ts
+++ b/studio/frontend/src/features/hub/download-manager/hydration.ts
@@ -65,6 +65,7 @@ function removeLocalActivePeers(
const activeJobKey = jobKeyOf(kind, repoId, variant);
const snapshotJobKey = jobKeyOf(kind, repoId, null);
for (const job of Object.values(getState().jobs)) {
+ if (job.external) continue;
if (!ACTIVE_STATES.has(job.state)) continue;
if (repoKeyOf(job.kind, job.repoId) !== activeRepoKey) continue;
if (variant !== null && kind === DOWNLOAD_KIND.MODEL) {
@@ -262,6 +263,8 @@ export function hydrateDownloadManager(): void {
void hydrateBackendActiveDownloads();
const jobs = Object.values(getState().jobs);
for (const job of jobs) {
+ // External jobs are live in memory and have no hub job to probe.
+ if (job.external) continue;
if (!ACTIVE_STATES.has(job.state)) {
removeJob(job.key);
continue;
diff --git a/studio/frontend/src/features/hub/download-manager/index.ts b/studio/frontend/src/features/hub/download-manager/index.ts
index 36c312e1cb2..ab92ee275af 100644
--- a/studio/frontend/src/features/hub/download-manager/index.ts
+++ b/studio/frontend/src/features/hub/download-manager/index.ts
@@ -3,6 +3,11 @@
export * from "./api";
export { DownloadManagerPanel } from "./download-manager-panel";
+export {
+ finishExternalJob,
+ startExternalJob,
+ updateExternalJob,
+} from "./external-jobs";
export {
DownloadProgressBar,
type DownloadProgress,
diff --git a/studio/frontend/src/features/hub/download-manager/poll-loop.ts b/studio/frontend/src/features/hub/download-manager/poll-loop.ts
index a50cec021cb..1a755ec7ee7 100644
--- a/studio/frontend/src/features/hub/download-manager/poll-loop.ts
+++ b/studio/frontend/src/features/hub/download-manager/poll-loop.ts
@@ -12,6 +12,7 @@ import {
type ActiveModelDownload,
type DownloadJobState,
} from "./api";
+import { cancelExternalJob, isExternalJob } from "./external-jobs";
import {
CANCELLED_LINGER_MS,
CANCEL_WATCHDOG_MS,
@@ -841,6 +842,11 @@ async function probeCancelOutcome(
export async function cancelJob(key: string): Promise<void> {
const job = getState().jobs[key];
if (!job) return;
+ // Another subsystem owns this transfer; it does the cancelling.
+ if (isExternalJob(key)) {
+ await cancelExternalJob(key);
+ return;
+ }
const rt = runtimeRegistry.runtimes.get(key);
const cancelEpoch = rt?.epoch ?? 0;
if (rt) rt.cancelRequested = true;
diff --git a/studio/frontend/src/features/hub/index.ts b/studio/frontend/src/features/hub/index.ts
index 9e079af87b7..ece33bc2ec9 100644
--- a/studio/frontend/src/features/hub/index.ts
+++ b/studio/frontend/src/features/hub/index.ts
@@ -4,8 +4,11 @@
export {
DownloadProgressBar,
downloadManager,
+ finishExternalJob,
jobKeyOf,
+ startExternalJob,
subscribeJobListeners,
+ updateExternalJob,
useDownloadManagerStore,
} from "./download-manager";
export {
diff --git a/studio/frontend/src/features/hub/lib/hidden-models.ts b/studio/frontend/src/features/hub/lib/hidden-models.ts
index c5c72aea659..f13c38cb3f1 100644
--- a/studio/frontend/src/features/hub/lib/hidden-models.ts
+++ b/studio/frontend/src/features/hub/lib/hidden-models.ts
@@ -21,7 +21,9 @@ const HIDDEN_NEEDLES = [
];
const HIDDEN_STT_REPOS = new Set([
// Transformers safetensors repos and their whisper.cpp GGUF companions
- // (unslothai/whisper-*-GGUF): STT-only, never chat models.
+ // (unslothai/whisper-*-GGUF): STT-only, never chat models. The Qwen3-ASR
+ // GGUFs are here for the same reason: llama.cpp will load one as a chat
+ // model, where it only answers with transcripts.
"unsloth/whisper-tiny",
"unsloth/whisper-base",
"unsloth/whisper-small",
@@ -32,6 +34,8 @@ const HIDDEN_STT_REPOS = new Set([
"unslothai/whisper-small-gguf",
"unslothai/whisper-large-v3-turbo-gguf",
"unslothai/whisper-large-v3-gguf",
+ "unslothai/qwen3-asr-0.6b-gguf",
+ "unslothai/qwen3-asr-1.7b-gguf",
]);
const HIDDEN_STT_CACHE_NAMES = [...HIDDEN_STT_REPOS].map((repo) =>
repo.replace("/", "--"),
diff --git a/studio/frontend/src/features/settings/components/stt-download-prompt.tsx b/studio/frontend/src/features/settings/components/stt-download-prompt.tsx
new file mode 100644
index 00000000000..7bee7c37d09
--- /dev/null
+++ b/studio/frontend/src/features/settings/components/stt-download-prompt.tsx
@@ -0,0 +1,123 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogMedia,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { startSttDownload } from "@/features/chat";
+import { hfApiToken, useHfTokenStore } from "@/features/hub";
+import { useT } from "@/i18n";
+import { MicIcon } from "@/lib/mic-icon";
+import { toast } from "@/lib/toast";
+import type { ReactNode } from "react";
+import { trackSttDownload } from "../lib/stt-download-mirror";
+import {
+ type SttDownloadRequest,
+ useSttDownloadPromptStore,
+} from "../stores/stt-download-prompt-store";
+import {
+ sttModelName,
+ sttModelSize,
+ useVoiceSettingsStore,
+} from "../stores/voice-settings-store";
+
+/** Emphasise the model name in translated copy; plain text if absent. */
+function highlightModel(text: string, model: string): ReactNode {
+ const at = model ? text.indexOf(model) : -1;
+ if (at === -1) return text;
+ return (
+ <>
+ {text.slice(0, at)}
+ <span className="font-medium text-foreground">{model}</span>
+ {text.slice(at + model.length)}
+ </>
+ );
+}
+
+/**
+ * App-level confirmation for a dictation model download. Mounted once so the
+ * mic can raise it before Voice settings is ever opened.
+ */
+export function SttDownloadPrompt() {
+ const t = useT();
+ const pending = useSttDownloadPromptStore((s) => s.pending);
+ const dismiss = useSttDownloadPromptStore((s) => s.dismiss);
+ const hfToken = useHfTokenStore((state) => state.token);
+
+ const confirm = async (request: SttDownloadRequest) => {
+ // Only on accept: a cancel must not leave the engine changed.
+ if (request.selectLocalEngine) {
+ useVoiceSettingsStore.getState().setDictationEngine("model");
+ }
+ try {
+ await startSttDownload(request.model, hfApiToken(hfToken));
+ // Progress goes to the shared download panel; the model loads itself
+ // when it lands.
+ trackSttDownload(request.model);
+ } catch (error) {
+ toast.error(t("settings.voice.dictation.sttDownloadFailed"), {
+ description: error instanceof Error ? error.message : undefined,
+ });
+ }
+ };
+
+ const pendingModel = pending?.model ?? null;
+ const size = pendingModel ? sttModelSize(pendingModel) : "";
+ return (
+ <AlertDialog
+ open={pending !== null}
+ onOpenChange={(open) => {
+ if (!open) dismiss();
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ {/* The glyph fills its viewBox, unlike the padded hugeicons the
+ default circle is sized for, so both come down together. */}
+ <AlertDialogMedia className="size-12">
+ <MicIcon className="text-muted-foreground size-5" />
+ </AlertDialogMedia>
+ <AlertDialogTitle>
+ {t("settings.voice.dictation.sttDownloadConfirmTitle", {
+ model: sttModelName(pendingModel ?? ""),
+ })}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {highlightModel(
+ pendingModel && size
+ ? t("settings.voice.dictation.sttDownloadConfirmBody", {
+ model: sttModelName(pendingModel),
+ size,
+ })
+ : t("settings.voice.dictation.sttDownloadConfirmBodyUnsized", {
+ model: sttModelName(pendingModel ?? ""),
+ }),
+ sttModelName(pendingModel ?? ""),
+ )}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={(event) => {
+ event.preventDefault();
+ const request = pending;
+ dismiss();
+ if (request) void confirm(request);
+ }}
+ >
+ {t("settings.voice.dictation.sttDownload")}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
diff --git a/studio/frontend/src/features/settings/lib/stt-download-mirror.ts b/studio/frontend/src/features/settings/lib/stt-download-mirror.ts
new file mode 100644
index 00000000000..bf090708ec9
--- /dev/null
+++ b/studio/frontend/src/features/settings/lib/stt-download-mirror.ts
@@ -0,0 +1,155 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import {
+ cancelSttDownload,
+ fetchSttStatus,
+ loadSttModel,
+ sttEngineStatusFor,
+} from "@/features/chat";
+import {
+ finishExternalJob,
+ startExternalJob,
+ updateExternalJob,
+} from "@/features/hub";
+import { translate } from "@/i18n";
+import { toast } from "@/lib/toast";
+import {
+ type SttModel,
+ getSttModelRepo,
+ sttModelName,
+ useVoiceSettingsStore,
+} from "../stores/voice-settings-store";
+import { SttDownloadTrackers } from "./stt-download-trackers";
+
+/**
+ * Shows a dictation model download in the shared download panel, and loads the
+ * model once it lands. The STT sidecars own the transfer, so progress is
+ * polled from their status rather than driven by the hub poll loop.
+ */
+
+const POLL_MS = 750;
+// A download reports nothing for a moment while the worker starts. Without this
+// the first poll would read "not downloading" and call it finished.
+const START_GRACE_MS = 8_000;
+
+const trackers = new SttDownloadTrackers();
+
+function jobKey(model: SttModel): string {
+ return `stt:${model}`;
+}
+
+async function loadAndAnnounce(model: SttModel): Promise<void> {
+ try {
+ await loadSttModel(model);
+ toast.success(
+ translate("settings.voice.dictation.sttModelReady", {
+ model: sttModelName(model),
+ }),
+ );
+ } catch (error) {
+ toast.error(translate("settings.voice.dictation.sttModelFailed"), {
+ description: error instanceof Error ? error.message : undefined,
+ });
+ }
+}
+
+function settle(
+ model: SttModel,
+ outcome: "complete" | "cancelled" | "error",
+ error?: string | null,
+): void {
+ finishExternalJob(jobKey(model), outcome, error);
+ trackers.stop(model);
+ // Only warm what the user is still pointed at. Selecting another model, or
+ // leaving local dictation, during the download means this one is not wanted
+ // and loading it would undo the unload that switch performed.
+ const { sttModel, dictationEngine } = useVoiceSettingsStore.getState();
+ if (
+ outcome === "complete" &&
+ dictationEngine === "model" &&
+ sttModel === model
+ ) {
+ void loadAndAnnounce(model);
+ }
+}
+
+async function poll(model: SttModel, startedAt: number): Promise<void> {
+ let status: Awaited<ReturnType<typeof fetchSttStatus>>;
+ try {
+ status = await fetchSttStatus(undefined, model);
+ } catch {
+ // A dropped poll is not a failed download; the next one decides.
+ return;
+ }
+ if (!trackers.has(model)) return;
+
+ const engine = sttEngineStatusFor(status, model);
+ const download = engine?.download;
+
+ if (download?.downloading && download.model === model) {
+ updateExternalJob(jobKey(model), {
+ downloadedBytes: download.bytes_done ?? 0,
+ expectedBytes: download.bytes_total ?? 0,
+ });
+ return;
+ }
+
+ if (engine?.downloaded_models.includes(model)) {
+ settle(model, "complete");
+ return;
+ }
+ if (download?.cancelled) {
+ settle(model, "cancelled");
+ return;
+ }
+ if (download?.error) {
+ settle(model, "error", download.error);
+ return;
+ }
+ if (Date.now() - startedAt > START_GRACE_MS) {
+ settle(
+ model,
+ "error",
+ translate("settings.voice.dictation.sttDownloadFailed"),
+ );
+ }
+}
+
+/** Whether a download is already mirrored, so a poller can adopt one that
+ * started before this page load without duplicating the row. */
+export function isTrackingSttDownload(model: SttModel): boolean {
+ return trackers.has(model);
+}
+
+/**
+ * Mirror an already-started download of `model` into the panel. Any other
+ * model's download keeps its own row: switching models does not stop it.
+ */
+export function trackSttDownload(model: SttModel): void {
+ startExternalJob({
+ key: jobKey(model),
+ repoId: getSttModelRepo(model),
+ variant: sttModelName(model),
+ expectedBytes: 0,
+ cancel: async () => {
+ try {
+ await cancelSttDownload(model);
+ } catch (error) {
+ toast.error(
+ translate("settings.voice.dictation.sttCancelDownloadFailed"),
+ { description: error instanceof Error ? error.message : undefined },
+ );
+ // The row is already showing "cancelling" and progress updates never
+ // reset state, so put it back or it stays there for the whole transfer.
+ throw error;
+ }
+ },
+ });
+ const startedAt = Date.now();
+ const timer = window.setInterval(() => {
+ void poll(model, startedAt);
+ }, POLL_MS);
+ trackers.start(model, () => window.clearInterval(timer));
+ void poll(model, startedAt);
+}
diff --git a/studio/frontend/src/features/settings/lib/stt-download-trackers.ts b/studio/frontend/src/features/settings/lib/stt-download-trackers.ts
new file mode 100644
index 00000000000..479a3f85a66
--- /dev/null
+++ b/studio/frontend/src/features/settings/lib/stt-download-trackers.ts
@@ -0,0 +1,27 @@
+// 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 live download pollers, one per dictation model. Each STT engine owns its
+ * own download state, so a Qwen transfer and a Whisper one really do run at the
+ * same time, and starting one must not drop the other's panel row.
+ */
+export class SttDownloadTrackers {
+ private readonly running = new Map<string, () => void>();
+
+ has(model: string): boolean {
+ return this.running.has(model);
+ }
+
+ /** Stops this model's previous poller, if any, and registers the new one. */
+ start(model: string, stop: () => void): void {
+ this.stop(model);
+ this.running.set(model, stop);
+ }
+
+ stop(model: string): void {
+ const stop = this.running.get(model);
+ this.running.delete(model);
+ stop?.();
+ }
+}
diff --git a/studio/frontend/src/features/settings/stores/stt-download-prompt-store.ts b/studio/frontend/src/features/settings/stores/stt-download-prompt-store.ts
new file mode 100644
index 00000000000..8196d1b396c
--- /dev/null
+++ b/studio/frontend/src/features/settings/stores/stt-download-prompt-store.ts
@@ -0,0 +1,41 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { create } from "zustand";
+import type { SttModel } from "./voice-settings-store";
+
+export interface SttDownloadRequest {
+ model: SttModel;
+ /** Also switch dictation to local on confirm, for a browser whose speech
+ * service cannot work at all. Left alone if the user cancels. */
+ selectLocalEngine?: boolean;
+}
+
+/**
+ * The one pending "download this dictation model?" confirmation.
+ *
+ * A store, not local state, so the mic can raise the dialog without Voice
+ * settings being open.
+ */
+interface SttDownloadPromptState {
+ /** Request awaiting a yes/no, or null when nothing is asked. */
+ pending: SttDownloadRequest | null;
+ requestDownload: (request: SttDownloadRequest) => void;
+ dismiss: () => void;
+}
+
+export const useSttDownloadPromptStore = create<SttDownloadPromptState>(
+ (set) => ({
+ pending: null,
+ requestDownload: (pending) => set({ pending }),
+ dismiss: () => set({ pending: null }),
+ }),
+);
+
+/** Ask the user to download `model`. Safe to call from non-React code. */
+export function requestSttDownload(
+ model: SttModel,
+ options?: Omit<SttDownloadRequest, "model">,
+): void {
+ useSttDownloadPromptStore.getState().requestDownload({ model, ...options });
+}
diff --git a/studio/frontend/src/features/settings/stores/stt-model-catalog.ts b/studio/frontend/src/features/settings/stores/stt-model-catalog.ts
new file mode 100644
index 00000000000..152d94e9c75
--- /dev/null
+++ b/studio/frontend/src/features/settings/stores/stt-model-catalog.ts
@@ -0,0 +1,96 @@
+// 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 curated dictation model list and its persisted-settings migration. Split
+// out of voice-settings-store so it stays free of app imports and can be tested
+// directly by the node runner.
+
+/** Curated dictation models, mirrored by the backend sidecars. Listed in the
+ * order the picker shows them: the recommended models lead. */
+export const STT_MODELS = [
+ "qwen3-asr-0.6b",
+ "qwen3-asr-1.7b",
+ "tiny",
+ "base",
+ "small",
+ "large-v3-turbo",
+ "large-v3",
+] as const;
+
+/** Models the picker marks as recommended. Qwen3-ASR is more accurate than
+ * Whisper at a comparable size and covers more languages. */
+export const RECOMMENDED_STT_MODELS: ReadonlySet<SttModel> = new Set([
+ "qwen3-asr-0.6b",
+ "qwen3-asr-1.7b",
+]);
+
+/** Models served by llama.cpp mtmd rather than whisper.cpp, which is
+ * Whisper-only. Each is a GGUF plus an audio mmproj. */
+export const MTMD_STT_MODELS: ReadonlySet<SttModel> = new Set([
+ "qwen3-asr-0.6b",
+ "qwen3-asr-1.7b",
+]);
+export type DefaultSttModel = (typeof STT_MODELS)[number];
+/** A curated id or a user-selected Hugging Face `owner/model` repository. */
+export type SttModel = string;
+/** Whisper repos downloaded through Studio's existing Model Hub manager. */
+export const STT_MODEL_REPOS: Record<DefaultSttModel, string> = {
+ tiny: "unsloth/whisper-tiny",
+ base: "unsloth/whisper-base",
+ small: "unsloth/whisper-small",
+ "large-v3-turbo": "unsloth/whisper-large-v3-turbo",
+ "large-v3": "unsloth/whisper-large-v3",
+ "qwen3-asr-0.6b": "unslothai/Qwen3-ASR-0.6B-GGUF",
+ "qwen3-asr-1.7b": "unslothai/Qwen3-ASR-1.7B-GGUF",
+};
+export const DEFAULT_STT_MODEL: DefaultSttModel = "qwen3-asr-0.6b";
+/** The default before Qwen3-ASR, used only by the v1 migration. */
+const LEGACY_DEFAULT_STT_MODEL = "small";
+
+/**
+ * v0's default was Whisper Small, so a stored "small" is far more often a
+ * default nobody touched than a deliberate pick. Move those to the recommended
+ * model; choosing Small again persists at v1 and sticks. Any other saved model
+ * was chosen on purpose and is left alone.
+ */
+export function migrateVoiceSettings(
+ persisted: unknown,
+ fromVersion: number,
+): Record<string, unknown> | undefined {
+ const saved = persisted as Record<string, unknown> | undefined;
+ if (fromVersion < 1 && saved?.sttModel === LEGACY_DEFAULT_STT_MODEL) {
+ return { ...saved, sttModel: DEFAULT_STT_MODEL };
+ }
+ return saved;
+}
+
+// Speech-recognition models, not voices. Name and size are separate so lists can
+// right-align the size; the download confirmation reads both.
+export const STT_MODEL_NAMES: Record<DefaultSttModel, string> = {
+ tiny: "Whisper Tiny",
+ base: "Whisper Base",
+ small: "Whisper Small",
+ "large-v3-turbo": "Whisper Large v3 Turbo",
+ "large-v3": "Whisper Large v3",
+ "qwen3-asr-0.6b": "Qwen3-ASR 0.6B",
+ "qwen3-asr-1.7b": "Qwen3-ASR 1.7B",
+};
+// Whisper sizes are f16 GGML for whisper.cpp; the mtmd entries cover the model
+// plus its mmproj, which is why they are larger than the weights alone.
+export const STT_MODEL_SIZES: Record<DefaultSttModel, string> = {
+ tiny: "78 MB",
+ base: "148 MB",
+ small: "488 MB",
+ "large-v3-turbo": "1.6 GB",
+ "large-v3": "3.1 GB",
+ "qwen3-asr-0.6b": "1.0 GB",
+ "qwen3-asr-1.7b": "2.5 GB",
+};
+
+export function sttModelName(model: SttModel): string {
+ return STT_MODEL_NAMES[model as DefaultSttModel] ?? model;
+}
+
+export function sttModelSize(model: SttModel): string {
+ return STT_MODEL_SIZES[model as DefaultSttModel] ?? "";
+}
diff --git a/studio/frontend/src/features/settings/stores/voice-settings-store.ts b/studio/frontend/src/features/settings/stores/voice-settings-store.ts
index f402b71c301..57e27983f77 100644
--- a/studio/frontend/src/features/settings/stores/voice-settings-store.ts
+++ b/studio/frontend/src/features/settings/stores/voice-settings-store.ts
@@ -4,6 +4,16 @@
import { isTauri } from "@/lib/api-base";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
+import {
+ DEFAULT_STT_MODEL,
+ type DefaultSttModel,
+ STT_MODELS,
+ STT_MODEL_REPOS,
+ type SttModel,
+ migrateVoiceSettings,
+} from "./stt-model-catalog";
+
+export * from "./stt-model-catalog";
// Voice preferences in localStorage. Adapters read them at call time so
// changes apply without reloading the chat runtime.
@@ -25,26 +35,6 @@ const MAX_RECENT_DICTATION_LENGTH = 2000;
const MAX_DICTIONARY_ENTRIES = 100;
const MAX_DICTIONARY_ENTRY_LENGTH = 120;
-/** Five curated Whisper choices, mirrored by the backend (stt_sidecar.py). */
-export const STT_MODELS = [
- "tiny",
- "base",
- "small",
- "large-v3-turbo",
- "large-v3",
-] as const;
-export type DefaultSttModel = (typeof STT_MODELS)[number];
-/** A curated id or a user-selected Hugging Face `owner/model` repository. */
-export type SttModel = string;
-/** Whisper repos downloaded through Studio's existing Model Hub manager. */
-export const STT_MODEL_REPOS: Record<DefaultSttModel, string> = {
- tiny: "unsloth/whisper-tiny",
- base: "unsloth/whisper-base",
- small: "unsloth/whisper-small",
- "large-v3-turbo": "unsloth/whisper-large-v3-turbo",
- "large-v3": "unsloth/whisper-large-v3",
-};
-export const DEFAULT_STT_MODEL: DefaultSttModel = "small";
const HF_REPO_ID =
/^[A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95}$/;
@@ -91,8 +81,8 @@ export function isSttModelLanguageCompatible(
export type DictationEngine = "browser" | "model";
/**
- * Whether a model id is one of the five curated Whisper choices. Curated models
- * run GGML through whisper.cpp; custom repos are safetensors and run through
+ * Whether a model id is curated. Whisper ids run GGML through whisper.cpp,
+ * mtmd ids run through llama.cpp, and custom repos are safetensors on
* Transformers.
*/
export function isCuratedSttModel(model: SttModel): boolean {
@@ -316,6 +306,8 @@ export const useVoiceSettingsStore = create<VoiceSettingsState>()(
{
name: "unsloth_voice_settings",
storage: createJSONStorage(() => quotaSafeLocalStorage),
+ version: 1,
+ migrate: migrateVoiceSettings,
merge: (persisted, current) => {
const saved = persisted as Partial<VoiceSettingsState> | undefined;
const dictationLanguage = asString(saved?.dictationLanguage, "auto");
diff --git a/studio/frontend/src/features/settings/tabs/voice-tab.tsx b/studio/frontend/src/features/settings/tabs/voice-tab.tsx
index 01aaf0cb476..627c257b0d7 100644
--- a/studio/frontend/src/features/settings/tabs/voice-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/voice-tab.tsx
@@ -19,17 +19,18 @@ import { Slider } from "@/components/ui/slider";
import { Spinner } from "@/components/ui/spinner";
import { Switch } from "@/components/ui/switch";
import {
- StudioModelDictationAdapter,
type SttDownloadStatus,
+ StudioModelDictationAdapter,
+ StudioSpeechSynthesisAdapter,
+ cancelSttDownload,
+ createConfiguredUtterance,
+ curateSystemVoices,
fetchSttStatus,
+ generateStudioTtsAudio,
loadSttModel,
startSttDownload,
unloadSttModel,
validateSttModel,
- StudioSpeechSynthesisAdapter,
- createConfiguredUtterance,
- curateSystemVoices,
- generateStudioTtsAudio,
} from "@/features/chat";
import {
DownloadProgressBar,
@@ -52,16 +53,26 @@ import { RecentDictationsView } from "../components/recent-dictations-view";
import { SettingsRow } from "../components/settings-row";
import { SettingsSection } from "../components/settings-section";
import {
- type DefaultSttModel,
+ isTrackingSttDownload,
+ trackSttDownload,
+} from "../lib/stt-download-mirror";
+import {
+ MTMD_STT_MODELS,
+ RECOMMENDED_STT_MODELS,
STT_MODELS,
type SttModel,
getSttModelRepo,
isCuratedSttModel,
isSttModelId,
isSttModelLanguageCompatible,
+ sttModelName,
+ sttModelSize,
useVoiceSettingsStore,
} from "../stores/voice-settings-store";
+/** Backends that report a runtime name where a device would go. */
+const STT_RUNTIME_NAMES = new Set(["whisper.cpp", "llama.cpp"]);
+
// Languages shared by browser speech recognition and local STT.
const DICTATION_LANGUAGES: { value: string; label: string }[] = [
{ value: "auto", label: "" }, // label rendered via i18n
@@ -85,36 +96,10 @@ const DICTATION_LANGUAGES: { value: string; label: string }[] = [
const TTS_PREVIEW_TEXT =
"Hello from Unsloth! This is a preview of the selected voice.";
-// Speech-recognition models, not voices. Name and size are separate so the list
-// can right-align the size; the speed/accuracy note lives in the row description.
-const STT_MODEL_NAMES: Record<DefaultSttModel, string> = {
- tiny: "Whisper Tiny",
- base: "Whisper Base",
- small: "Whisper Small",
- "large-v3-turbo": "Whisper Large v3 Turbo",
- "large-v3": "Whisper Large v3",
-};
-// Curated models run as f16 GGML files through whisper.cpp.
-const STT_MODEL_SIZES: Record<DefaultSttModel, string> = {
- tiny: "78 MB",
- base: "148 MB",
- small: "488 MB",
- "large-v3-turbo": "1.6 GB",
- "large-v3": "3.1 GB",
-};
-
-function sttModelName(model: SttModel): string {
- return STT_MODEL_NAMES[model as DefaultSttModel] ?? model;
-}
-
-function sttModelSize(model: SttModel): string {
- return STT_MODEL_SIZES[model as DefaultSttModel] ?? "";
-}
-
/** Source repository shown under a model row. Curated models download from
* the Unsloth GGUF repos, mirrored by the backend (stt_ggml_sidecar.py). */
function sttModelSource(model: SttModel): string {
- return isCuratedSttModel(model)
+ return isCuratedSttModel(model) && !MTMD_STT_MODELS.has(model)
? `unslothai/whisper-${model}-GGUF`
: getSttModelRepo(model);
}
@@ -266,8 +251,9 @@ function SttModelPicker({
</div>
) : (
items.map((model) => {
- // A custom repo's name is its id: one-line rows keep a pill shape,
- // two-line rows use a subtler radius.
+ // A custom repo's name is its id: one-line rows keep a pill
+ // shape, two-line rows use a squarer radius. Not rounded-sm: the
+ // theme's --radius makes that 13.6px, too round at this height.
const twoLines = sttModelSource(model) !== sttModelName(model);
return (
<button
@@ -276,12 +262,17 @@ function SttModelPicker({
onClick={() => void selectModel(model)}
aria-selected={model === value}
className={`flex w-full items-center justify-between gap-3 px-2.5 py-1.5 text-left transition-colors hover:bg-muted ${
- twoLines ? "rounded-sm" : "rounded-full"
+ twoLines ? "rounded-[10px]" : "rounded-full"
} ${model === value ? "bg-accent font-medium" : ""}`}
>
<span className="min-w-0 flex-1 truncate">
- <span className="block truncate text-xs">
- {sttModelName(model)}
+ <span className="flex items-center gap-1.5 truncate text-xs">
+ <span className="truncate">{sttModelName(model)}</span>
+ {RECOMMENDED_STT_MODELS.has(model) ? (
+ <span className="shrink-0 rounded-full bg-emerald-500/12 px-1.5 py-px text-ui-9 font-medium text-emerald-600 dark:bg-emerald-400/15 dark:text-emerald-400">
+ {t("settings.voice.dictation.sttRecommended")}
+ </span>
+ ) : null}
</span>
{twoLines ? (
<span className="mt-0.5 block truncate font-mono text-ui-9 leading-tight text-muted-foreground">
@@ -447,12 +438,13 @@ export function VoiceTab() {
const [sttPhase, setSttPhase] = useState<SttPhase>("idle");
const [sttDevice, setSttDevice] = useState<string | null>(null);
const [statusNonce, setStatusNonce] = useState(0);
- const [sttDownloadStarting, setSttDownloadStarting] = useState(false);
+ const [sttDownloadCancelling, setSttDownloadCancelling] = useState(false);
const [sttUnloading, setSttUnloading] = useState(false);
const isLocalEngine = dictationEngine === "model";
// The model decides the backend: curated ids run GGML through whisper.cpp,
// custom repos run through Transformers.
- const isGgufModel = isCuratedSttModel(sttModel);
+ const isMtmdModel = MTMD_STT_MODELS.has(sttModel);
+ const isGgufModel = isCuratedSttModel(sttModel) && !isMtmdModel;
// Progress of the selected engine's model download, from /stt/status.
const [sttDownload, setSttDownload] = useState<SttDownloadStatus | null>(
null,
@@ -480,6 +472,7 @@ export function VoiceTab() {
}, []);
const sttRepoId = getSttModelRepo(sttModel);
const hfToken = useHfTokenStore((state) => state.token);
+ const [sttDownloadStarting, setSttDownloadStarting] = useState(false);
const [sttDownloadAvailability, setSttDownloadAvailability] = useState<{
repoId: string;
state: SttDownloadAvailability;
@@ -504,8 +497,10 @@ export function VoiceTab() {
// whisper-server the backend serves it through Transformers instead of
// failing. Fall back to the Transformers status here too, or the model
// shows as unavailable and download is blocked even though it works.
- const engineStatus =
- isGgufModel && status.gguf?.available
+ // mtmd models run nowhere else, so they never fall back.
+ const engineStatus = isMtmdModel
+ ? status.mtmd
+ : isGgufModel && status.gguf?.available
? status.gguf
: status.transformers;
if (!engineStatus?.available) {
@@ -523,6 +518,11 @@ export function VoiceTab() {
: "missing",
});
if (download.downloading) {
+ // Adopt a transfer that outlived the page that started it, so it
+ // still shows in the download panel.
+ if (download.model && !isTrackingSttDownload(download.model)) {
+ trackSttDownload(download.model);
+ }
watchedDownloadRef.current = download.model;
const bytes = download.bytes_done ?? 0;
const sample = downloadRateSampleRef.current;
@@ -587,6 +587,7 @@ export function VoiceTab() {
}, [
isLocalEngine,
isGgufModel,
+ isMtmdModel,
sttModel,
sttRepoId,
modelSttSupported,
@@ -603,9 +604,9 @@ export function VoiceTab() {
case "on-demand":
return t("settings.voice.dictation.sttOnDemand");
case "ready":
- // The GGML backend reports its runtime name, not a device; show a plain
- // "Loaded" rather than surfacing it.
- return sttDevice && sttDevice !== "whisper.cpp"
+ // whisper.cpp and llama.cpp report a runtime name, not a device; show a
+ // plain "Loaded" rather than surfacing it.
+ return sttDevice && !STT_RUNTIME_NAMES.has(sttDevice)
? t("settings.voice.dictation.sttReady", {
device: sttDevice.toUpperCase(),
})
@@ -642,7 +643,8 @@ export function VoiceTab() {
case "missing":
return t("settings.voice.dictation.sttNotDownloaded");
case "error":
- return t("settings.voice.dictation.sttDownloadStatusFailed");
+ // This state means the download itself failed, not the status check.
+ return t("settings.voice.dictation.sttDownloadFailed");
case "downloaded":
return sttStatusText;
default:
@@ -650,11 +652,17 @@ export function VoiceTab() {
}
})();
+ // Pressing Download is the confirmation. The prompt is for the paths that
+ // never asked for one, like the mic finding nothing on disk.
const beginSttDownload = async () => {
setSttDownloadStarting(true);
try {
- // Engine-managed download; progress arrives via /stt/status.
await startSttDownload(sttModel, hfApiToken(hfToken));
+ trackSttDownload(sttModel);
+ // The status effect only re-polls while it can see a download. Its last
+ // read was before this one existed, and the on-demand branch schedules
+ // nothing, so without a nudge the tab shows Download for the whole
+ // transfer.
setStatusNonce((nonce) => nonce + 1);
} catch (error) {
toast.error(t("settings.voice.dictation.sttDownloadFailed"), {
@@ -665,6 +673,21 @@ export function VoiceTab() {
}
};
+ const stopSttDownload = async () => {
+ setSttDownloadCancelling(true);
+ try {
+ await cancelSttDownload(sttDownload?.model ?? sttModel);
+ setSttDownload(null);
+ setStatusNonce((nonce) => nonce + 1);
+ } catch (error) {
+ toast.error(t("settings.voice.dictation.sttCancelDownloadFailed"), {
+ description: error instanceof Error ? error.message : undefined,
+ });
+ } finally {
+ setSttDownloadCancelling(false);
+ }
+ };
+
const warmSttModel = async () => {
setSttPhase("loading");
try {
@@ -902,6 +925,17 @@ export function VoiceTab() {
<span className="text-xs text-muted-foreground">
{sttModelStatusText}
</span>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="-mr-1.5 h-7 shrink-0 px-2 text-xs"
+ disabled={sttDownloadCancelling}
+ onClick={() => void stopSttDownload()}
+ >
+ {sttDownloadCancelling
+ ? t("settings.voice.dictation.sttCancellingDownload")
+ : t("settings.voice.dictation.sttCancelDownload")}
+ </Button>
</div>
<DownloadProgressBar
progress={{
@@ -948,10 +982,10 @@ export function VoiceTab() {
variant="ghost"
size="sm"
className="h-7 px-2 text-xs"
- disabled={sttDownloadStarting || downloadingThisModel}
+ disabled={downloadingThisModel || sttDownloadStarting}
// Restart the download; the sidecar error is sticky until
// a new start(), so re-polling alone never clears it.
- onClick={beginSttDownload}
+ onClick={() => void beginSttDownload()}
>
{t("settings.voice.dictation.sttRetry")}
</Button>
@@ -960,10 +994,10 @@ export function VoiceTab() {
variant="outline"
size="sm"
className="h-7 px-2.5 text-xs"
- disabled={sttDownloadStarting || downloadingThisModel}
- onClick={beginSttDownload}
+ disabled={downloadingThisModel || sttDownloadStarting}
+ onClick={() => void beginSttDownload()}
>
- {sttDownloadStarting || downloadingThisModel ? (
+ {downloadingThisModel || sttDownloadStarting ? (
<Spinner className="mr-1.5" />
) : null}
{t("settings.voice.dictation.sttDownload")}
@@ -987,8 +1021,8 @@ export function VoiceTab() {
// button only needs the spinner.
<Button
variant="outline"
- size="sm"
- className="h-7 px-2.5 text-xs"
+ size="icon-sm"
+ className="size-7"
disabled={true}
aria-label={t(
"settings.voice.dictation.sttLoadingModel",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index c7e6527636c..ee3e2d248b8 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -136,7 +136,7 @@ export const en = {
"Runs a speech-to-text (STT) model locally and works offline. Download, load, then unloads after inactivity.",
sttModelLabel: "Speech recognition model",
sttModelDescription: "Choose or search a STT model to run locally.",
- sttModelSearchPlaceholder: "Search model",
+ sttModelSearchPlaceholder: "Search any model on HF",
sttModelSearching: "Searching Hugging Face…",
sttModelValidating: "Checking Whisper compatibility…",
sttModelNoResults: "No Whisper models found",
@@ -155,10 +155,20 @@ export const en = {
sttNotDownloaded: "Not downloaded",
sttDownloadStatusFailed: "Could not check download status",
sttDownload: "Download",
+ sttDownloadConfirmTitle: "Download {model}?",
+ sttDownloadConfirmBody:
+ "Local dictation runs entirely offline, but it needs the {model} speech model first. About {size}, fetched once into your Hugging Face cache.",
+ sttDownloadConfirmBodyUnsized:
+ "Local dictation runs entirely offline, but it needs the {model} speech model first. It is fetched once into your Hugging Face cache.",
+ sttOpenVoiceSettings: "Open Voice settings",
+ sttDownloadStarted: "Downloading {model}",
sttDownloading: "Downloading… {progress}%",
sttCancelDownload: "Cancel",
sttCancellingDownload: "Cancelling…",
+ sttCancelDownloadFailed: "Could not cancel the download",
sttDownloadComplete: "Speech recognition model downloaded",
+ sttModelReady: "{model} is ready for dictation",
+ sttRecommended: "Recommended",
sttDownloadFailed: "Could not download the speech recognition model",
sttLoad: "Load",
sttUnload: "Unload",
diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.css
index 7b3a57ecd76..28f554d44ec 100644
--- a/studio/frontend/src/index.css
+++ b/studio/frontend/src/index.css
@@ -2516,6 +2516,11 @@ html[data-chat-font] .aui-root {
padding-right: 48px !important;
}
+/* Toast buttons are pills, matching the dialog actions they stand in for. */
+[data-sonner-toast] [data-button] {
+ border-radius: 9999px !important;
+}
+
/* Loading toast keeps its own vertical padding from #7683. */
[data-sonner-toast][data-styled='true'].chat-model-load-toast {
display: flex !important;
diff --git a/studio/frontend/tests/stt-download-trackers.test.ts b/studio/frontend/tests/stt-download-trackers.test.ts
new file mode 100644
index 00000000000..b689ed8d0e7
--- /dev/null
+++ b/studio/frontend/tests/stt-download-trackers.test.ts
@@ -0,0 +1,50 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { SttDownloadTrackers } from "../src/features/settings/lib/stt-download-trackers.ts";
+
+test("a second model's download does not stop the first", () => {
+ const trackers = new SttDownloadTrackers();
+ const stopped: string[] = [];
+
+ trackers.start("qwen3-asr-0.6b", () => stopped.push("qwen3-asr-0.6b"));
+ trackers.start("whisper-small", () => stopped.push("whisper-small"));
+
+ // Each engine has its own download state, so both transfers are still live.
+ assert.deepEqual(stopped, []);
+ assert.equal(trackers.has("qwen3-asr-0.6b"), true);
+ assert.equal(trackers.has("whisper-small"), true);
+});
+
+test("restarting the same model replaces its poller", () => {
+ const trackers = new SttDownloadTrackers();
+ const stopped: string[] = [];
+
+ trackers.start("whisper-small", () => stopped.push("first"));
+ trackers.start("whisper-small", () => stopped.push("second"));
+
+ assert.deepEqual(stopped, ["first"], "the old interval would keep polling");
+ assert.equal(trackers.has("whisper-small"), true);
+});
+
+test("stopping one model leaves the others tracked", () => {
+ const trackers = new SttDownloadTrackers();
+ const stopped: string[] = [];
+
+ trackers.start("qwen3-asr-0.6b", () => stopped.push("qwen3-asr-0.6b"));
+ trackers.start("whisper-small", () => stopped.push("whisper-small"));
+ trackers.stop("whisper-small");
+
+ assert.deepEqual(stopped, ["whisper-small"]);
+ assert.equal(trackers.has("whisper-small"), false);
+ assert.equal(trackers.has("qwen3-asr-0.6b"), true);
+});
+
+test("stopping an untracked model is a no-op", () => {
+ const trackers = new SttDownloadTrackers();
+ trackers.stop("whisper-small");
+ assert.equal(trackers.has("whisper-small"), false);
+});
diff --git a/studio/frontend/tests/stt-request-error.test.ts b/studio/frontend/tests/stt-request-error.test.ts
new file mode 100644
index 00000000000..c4bc7ec7eab
--- /dev/null
+++ b/studio/frontend/tests/stt-request-error.test.ts
@@ -0,0 +1,38 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ SttModelNotDownloadedError,
+ sttRequestError,
+} from "../src/features/chat/adapters/stt-errors.ts";
+
+test("a not-downloaded 409 asks for the download, from either call", () => {
+ // A segment can be the first to see this, when a short recording ends before
+ // the fire-and-forget preload rejects.
+ const error = sttRequestError(409, "STT model 'small' is not downloaded.");
+ assert.ok(error instanceof SttModelNotDownloadedError);
+});
+
+test("the other 409s stay ordinary errors", () => {
+ // A load cancelled for training, and a model switch mid-request.
+ for (const detail of [
+ "Dictation model loading was cancelled so training could start.",
+ "The dictation model changed while this recording was being prepared.",
+ ]) {
+ const error = sttRequestError(409, detail);
+ assert.ok(!(error instanceof SttModelNotDownloadedError));
+ assert.equal(error.message, detail);
+ }
+});
+
+test("another status is never mistaken for it", () => {
+ assert.ok(
+ !(
+ sttRequestError(500, "something is not downloaded") instanceof
+ SttModelNotDownloadedError
+ ),
+ );
+});
diff --git a/studio/frontend/tests/voice-settings-stt-migration.test.ts b/studio/frontend/tests/voice-settings-stt-migration.test.ts
new file mode 100644
index 00000000000..cf8e4a3731b
--- /dev/null
+++ b/studio/frontend/tests/voice-settings-stt-migration.test.ts
@@ -0,0 +1,50 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ DEFAULT_STT_MODEL,
+ RECOMMENDED_STT_MODELS,
+ STT_MODELS,
+ migrateVoiceSettings,
+} from "../src/features/settings/stores/stt-model-catalog.ts";
+
+test("the default dictation model is a recommended one", () => {
+ assert.ok(RECOMMENDED_STT_MODELS.has(DEFAULT_STT_MODEL));
+});
+
+test("recommended models are listed before the rest", () => {
+ const firstOther = STT_MODELS.findIndex(
+ (model) => !RECOMMENDED_STT_MODELS.has(model),
+ );
+ const lastRecommended = STT_MODELS.reduce(
+ (last, model, index) => (RECOMMENDED_STT_MODELS.has(model) ? index : last),
+ -1,
+ );
+ assert.ok(lastRecommended < firstOther);
+});
+
+test("a save still on the old default moves to the recommended model", () => {
+ const migrated = migrateVoiceSettings({ sttModel: "small" }, 0);
+ assert.equal(migrated?.sttModel, DEFAULT_STT_MODEL);
+});
+
+test("a deliberately chosen model is left alone", () => {
+ const migrated = migrateVoiceSettings({ sttModel: "large-v3" }, 0);
+ assert.equal(migrated?.sttModel, "large-v3");
+});
+
+test("choosing Whisper Small again survives, because v1 does not re-migrate", () => {
+ const migrated = migrateVoiceSettings({ sttModel: "small" }, 1);
+ assert.equal(migrated?.sttModel, "small");
+});
+
+test("migration keeps the rest of the save intact", () => {
+ const migrated = migrateVoiceSettings(
+ { sttModel: "small", dictationLanguage: "ja-JP" },
+ 0,
+ );
+ assert.equal(migrated?.dictationLanguage, "ja-JP");
+});