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 local speech-to-text dictation engine (#7095)

Michael Hand5cf96d6286a
diff --git a/scripts/build_whisper_cpp.sh b/scripts/build_whisper_cpp.sh
new file mode 100755
index 00000000000..9f7e4d4ef32
--- /dev/null
+++ b/scripts/build_whisper_cpp.sh
@@ -0,0 +1,71 @@
+#!/bin/sh
+# Build whisper.cpp's whisper-server for Studio's GGUF dictation engine.
+#
+# Installs into the managed Studio home so the backend's binary discovery
+# (core/inference/stt_ggml_sidecar.py::find_whisper_server_binary) picks it up:
+# <UNSLOTH_STUDIO_HOME>/whisper.cpp/build/bin/whisper-server (custom home)
+# ~/.unsloth/whisper.cpp/build/bin/whisper-server (default)
+#
+# Usage:
+# ./scripts/build_whisper_cpp.sh # build the pinned tag
+# WHISPER_CPP_TAG=v1.9.0 ./scripts/build_whisper_cpp.sh
+#
+# Requires: git, cmake, a C/C++ toolchain (the same prerequisites as a
+# llama.cpp source build). GPU backends are auto-detected by whisper.cpp's
+# CMake (Metal on macOS; set GGML_CUDA=1 to force a CUDA build on Linux).
+
+set -eu
+
+WHISPER_CPP_SOURCE="${WHISPER_CPP_SOURCE:-https://github.com/ggml-org/whisper.cpp}"
+WHISPER_CPP_TAG="${WHISPER_CPP_TAG:-v1.9.1}"
+
+STUDIO_HOME="${UNSLOTH_STUDIO_HOME:-${STUDIO_HOME:-}}"
+CUSTOM_STUDIO_HOME=false
+if [ -n "$STUDIO_HOME" ]; then
+ CUSTOM_STUDIO_HOME=true
+ INSTALL_DIR="$STUDIO_HOME/whisper.cpp"
+else
+ INSTALL_DIR="$HOME/.unsloth/whisper.cpp"
+fi
+
+command -v git >/dev/null 2>&1 || { echo "ERROR: git is required" >&2; exit 1; }
+command -v cmake >/dev/null 2>&1 || { echo "ERROR: cmake is required" >&2; exit 1; }
+
+# Same policy as studio/setup.sh's _assert_studio_owned_or_absent: never delete
+# a directory under a custom Studio home unless Studio itself created it (the
+# marker file below). Protects a user-managed whisper.cpp/src from rm -rf.
+STUDIO_OWNED_MARKER=".unsloth-studio-owned"
+if [ "$CUSTOM_STUDIO_HOME" = true ] && [ -e "$INSTALL_DIR" ] && \
+ [ ! -f "$INSTALL_DIR/$STUDIO_OWNED_MARKER" ]; then
+ echo "ERROR: $INSTALL_DIR already exists and is not marked as an Unsloth-owned whisper.cpp build tree." >&2
+ echo " Move it aside or choose an empty UNSLOTH_STUDIO_HOME before re-running." >&2
+ exit 1
+fi
+
+echo "==> Building whisper.cpp ($WHISPER_CPP_TAG) into $INSTALL_DIR"
+mkdir -p "$INSTALL_DIR"
+: > "$INSTALL_DIR/$STUDIO_OWNED_MARKER"
+
+if [ ! -d "$INSTALL_DIR/src/.git" ]; then
+ rm -rf "$INSTALL_DIR/src"
+ git clone --depth 1 --branch "$WHISPER_CPP_TAG" "$WHISPER_CPP_SOURCE" "$INSTALL_DIR/src"
+else
+ git -C "$INSTALL_DIR/src" fetch --depth 1 origin "$WHISPER_CPP_TAG"
+ git -C "$INSTALL_DIR/src" checkout FETCH_HEAD
+fi
+
+CMAKE_FLAGS="-DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=OFF"
+if [ "${GGML_CUDA:-0}" = "1" ]; then
+ CMAKE_FLAGS="$CMAKE_FLAGS -DGGML_CUDA=ON"
+fi
+
+# shellcheck disable=SC2086
+cmake -S "$INSTALL_DIR/src" -B "$INSTALL_DIR/src/build" $CMAKE_FLAGS
+NCPU="$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 4)"
+cmake --build "$INSTALL_DIR/src/build" --config Release --target whisper-server -j"$NCPU"
+
+mkdir -p "$INSTALL_DIR/build/bin"
+cp "$INSTALL_DIR/src/build/bin/whisper-server" "$INSTALL_DIR/build/bin/whisper-server"
+
+echo "==> Installed $INSTALL_DIR/build/bin/whisper-server"
+"$INSTALL_DIR/build/bin/whisper-server" --help >/dev/null 2>&1 && echo "==> Binary runs OK"
diff --git a/studio/backend/core/inference/stt_ggml_sidecar.py b/studio/backend/core/inference/stt_ggml_sidecar.py
new file mode 100644
index 00000000000..02b376dea51
--- /dev/null
+++ b/studio/backend/core/inference/stt_ggml_sidecar.py
@@ -0,0 +1,876 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""whisper.cpp (GGML/GGUF) speech-to-text sidecar for Studio dictation.
+
+Runs the same curated Whisper checkpoints as the Transformers sidecar
+(stt_sidecar.py) through whisper.cpp's `whisper-server`, ~2.5x faster at
+identical quality on Apple Silicon and CPU because its Metal/CPU kernels run
+the weights in f16 where PyTorch MPS requires fp32.
+
+Owns a single `whisper-server` subprocess bound to 127.0.0.1 on an ephemeral
+port; the model loads on demand, stays warm between dictations, and unloads
+after the same keep-alive as the Transformers sidecar. Curated GGML checkpoints
+are single files from `unslothai/whisper-*-GGUF`, downloaded directly rather
+than through the Model Hub (whose variant planner only handles `.gguf` chat
+layouts).
+
+Binary discovery mirrors `_find_llama_server_binary`: env override, then managed
+Studio home, then PATH. With no binary the engine is unavailable and dictation
+falls back to the Transformers sidecar; `scripts/build_whisper_cpp.sh` installs
+the binary.
+"""
+
+from __future__ import annotations
+
+import io
+import json
+import os
+import re
+import shutil
+import socket
+import subprocess
+import sys
+import threading
+import time
+import urllib.request
+import uuid
+import wave
+from contextlib import contextmanager
+from pathlib import Path
+from typing import Iterator, Optional
+
+from loggers import get_logger
+
+from core.inference.stt_sidecar import (
+ STT_KEEP_ALIVE_SECONDS,
+ SttAudioDecodeError,
+ SttLanguageError,
+ SttLoadCancelledError,
+ SttModelIdError,
+ SttModelNotDownloadedError,
+ SttUnavailableError,
+ _decode_audio_bounded,
+ _known_whisper_languages,
+ _TARGET_SAMPLE_RATE,
+ _training_active,
+ normalize_whisper_language,
+)
+from utils.prebuilt.child_env import isolate_home, scrub_env, wsl_system_rocm_lib_dirs
+from utils.prebuilt.runtime_libs import dedupe_existing_dirs
+from utils.prebuilt.whisper_layout import lookup_marker
+from utils.process_lifetime import adopt_pid, child_popen_kwargs, forget_pid
+
+logger = get_logger(__name__)
+
+# Curated GGML checkpoints, one repo per model. Keys match the Transformers
+# sidecar's ids so the frontend reuses one picker; values are the single file
+# inside each repo.
+GGML_STT_REPOS: dict[str, str] = {
+ "tiny": "unslothai/whisper-tiny-GGUF",
+ "base": "unslothai/whisper-base-GGUF",
+ "small": "unslothai/whisper-small-GGUF",
+ "large-v3-turbo": "unslothai/whisper-large-v3-turbo-GGUF",
+ "large-v3": "unslothai/whisper-large-v3-GGUF",
+}
+GGML_STT_MODELS: dict[str, str] = {
+ "tiny": "whisper-tiny.bin",
+ "base": "whisper-base.bin",
+ "small": "whisper-small.bin",
+ "large-v3-turbo": "whisper-large-v3-turbo.bin",
+ "large-v3": "whisper-large-v3.bin",
+}
+DEFAULT_GGML_STT_MODEL = "small"
+
+_SERVER_START_TIMEOUT_SECONDS = 120.0
+_TRANSCRIBE_TIMEOUT_SECONDS = 600.0
+
+
+class SttEngineUnavailableError(SttUnavailableError):
+ """whisper-server is not installed; the GGUF dictation engine is off."""
+
+
+def resolve_ggml_model_id(model: Optional[str]) -> str:
+ """Validate a curated GGML model id. Custom repos are not supported here."""
+ if model is None or not str(model).strip():
+ return DEFAULT_GGML_STT_MODEL
+ normalized = str(model).strip()
+ if normalized in GGML_STT_MODELS:
+ return normalized
+ raise SttModelIdError(
+ f"STT model '{model}' is not a curated GGUF dictation model. "
+ f"Choose one of: {', '.join(GGML_STT_MODELS)}."
+ )
+
+
+def _managed_whisper_cpp_dir() -> Path:
+ """`<STUDIO_HOME>/whisper.cpp` in custom mode, else `~/.unsloth/whisper.cpp`.
+
+ Mirrors `managed_node_dir` / `_find_llama_server_binary` so managed runtimes
+ share one parent directory.
+ """
+ legacy = Path.home() / ".unsloth" / "whisper.cpp"
+ try:
+ from utils.paths.storage_roots import studio_root
+
+ resolved = studio_root()
+ legacy_studio = Path.home() / ".unsloth" / "studio"
+ try:
+ is_legacy = resolved.resolve() == legacy_studio.resolve()
+ except (OSError, ValueError):
+ is_legacy = resolved == legacy_studio
+ return legacy if is_legacy else (resolved / "whisper.cpp")
+ except (ImportError, OSError, ValueError):
+ override = (
+ os.environ.get("UNSLOTH_STUDIO_HOME") or os.environ.get("STUDIO_HOME") or ""
+ ).strip()
+ if override:
+ try:
+ return Path(override).expanduser().resolve() / "whisper.cpp"
+ except (OSError, ValueError):
+ return Path(override).expanduser() / "whisper.cpp"
+ return legacy
+
+
+def find_whisper_server_binary() -> Optional[str]:
+ """Locate the whisper-server binary.
+
+ Search order:
+ 1. WHISPER_SERVER_PATH environment variable (direct path to binary)
+ 2. UNSLOTH_WHISPER_CPP_PATH env var (custom whisper.cpp install dir)
+ 3. managed dir: <STUDIO_HOME or ~/.unsloth>/whisper.cpp/{,build/bin/}whisper-server
+ 4. whisper-server on PATH
+ """
+ binary_name = "whisper-server.exe" if sys.platform == "win32" else "whisper-server"
+
+ def _layout_candidates(d: Path) -> list[Path]:
+ cands = [d / binary_name, d / "build" / "bin" / binary_name]
+ if sys.platform == "win32":
+ cands.append(d / "build" / "bin" / "Release" / binary_name)
+ return cands
+
+ env_path = os.environ.get("WHISPER_SERVER_PATH")
+ if env_path:
+ p = Path(env_path)
+ if _is_runnable(p):
+ return str(p)
+
+ custom_dir = os.environ.get("UNSLOTH_WHISPER_CPP_PATH")
+ if custom_dir:
+ for p in _layout_candidates(Path(custom_dir)):
+ if _is_runnable(p):
+ return str(p)
+
+ for p in _layout_candidates(_managed_whisper_cpp_dir()):
+ if _is_runnable(p):
+ return str(p)
+
+ return shutil.which(binary_name)
+
+
+def _is_runnable(p: Path) -> bool:
+ """A real whisper-server is an executable file. On Windows os.access(X_OK) is
+ effectively an existence check; on Unix it rejects a non-executable stub so a
+ half-written or wrong-mode file isn't mistaken for the server."""
+ return p.is_file() and (sys.platform == "win32" or os.access(p, os.X_OK))
+
+
+def _whisper_install_marker(binary: str) -> Optional[dict]:
+ """The prebuilt install marker above ``binary``, or None (source/custom builds)."""
+ return lookup_marker(binary).marker
+
+
+def slim_runtime_intact(binary: str) -> bool:
+ """True unless the marker says slim and the linked ggml runtime is missing
+ beside the server. New markers record the exact wired filenames
+ (linked_libraries), all of which must be present; legacy markers without the
+ field fall back to the per-OS core ggml name globs. A broken slim install
+ reads as engine-unavailable (reinstall via `unsloth studio update`), never a
+ crash at load."""
+ lookup = lookup_marker(binary)
+ marker = lookup.marker
+ if lookup.invalid or marker is None:
+ return not lookup.slim_collision
+ if not marker or marker.get("install_kind") != "slim":
+ return True
+ if lookup.authoritative:
+ valid = marker.get("component") == "whisper.cpp"
+ valid = valid and isinstance(marker.get("schema_version"), int)
+ valid = valid and all(
+ isinstance(marker.get(key), str) and marker[key]
+ for key in ("release_tag", "backend", "paired_llama_tag")
+ )
+ valid = valid and isinstance(marker.get("linked_libraries"), list)
+ valid = valid and bool(marker.get("linked_libraries"))
+ valid = valid and all(
+ isinstance(name, str) and name and Path(name).name == name
+ for name in marker["linked_libraries"]
+ )
+ if not valid:
+ return False
+ bin_dir = Path(binary).parent
+ linked = marker.get("linked_libraries")
+ if isinstance(linked, list) and linked and all(isinstance(name, str) for name in linked):
+ intact = all((bin_dir / name).is_file() for name in linked)
+ else:
+ if sys.platform == "win32":
+ required = ("ggml.dll", "ggml-base.dll")
+ elif sys.platform == "darwin":
+ required = ("libggml*.dylib", "libggml-base*.dylib")
+ else:
+ required = ("libggml.so*", "libggml-base.so*")
+ intact = all(any(p.is_file() for p in bin_dir.glob(pattern)) for pattern in required)
+ runtime_dirs = marker.get("linked_runtime_directories")
+ if intact and isinstance(runtime_dirs, list) and runtime_dirs:
+ intact = all(
+ isinstance(name, str)
+ and name
+ and (bin_dir / name).is_dir()
+ and any(path.is_file() for path in (bin_dir / name).rglob("*"))
+ for name in runtime_dirs
+ )
+ if intact and marker.get("backend") == "rocm":
+ expected_runtime_dirs = set() if sys.platform == "win32" else {"hipblaslt", "rocblas"}
+ intact = (
+ marker.get("runtime_wiring_version") == 2
+ and isinstance(runtime_dirs, list)
+ and set(runtime_dirs) == expected_runtime_dirs
+ )
+ if not intact:
+ logger.warning(
+ "slim whisper install is missing its linked ggml runtime at "
+ f"{bin_dir}; run `unsloth studio update` to reinstall it"
+ )
+ return intact
+
+
+def is_available() -> bool:
+ binary = find_whisper_server_binary()
+ if binary is None:
+ return False
+ if not slim_runtime_intact(binary):
+ return False
+ try:
+ import av # noqa: F401
+ except Exception:
+ # No PyAV means every transcription 501s on decode.
+ return False
+ return True
+
+
+def ensure_engine_available() -> str:
+ binary = find_whisper_server_binary()
+ if binary is None:
+ raise SttEngineUnavailableError(
+ "The local transcription runtime is not installed. Run "
+ "`unsloth studio update` to install it."
+ )
+ if not slim_runtime_intact(binary):
+ raise SttEngineUnavailableError(
+ "The local transcription runtime is missing its paired ggml "
+ "libraries. Run `unsloth studio update` to reinstall it."
+ )
+ return binary
+
+
+# ---------------------------------------------------------------------------
+# whisper-server child-process environment
+# ---------------------------------------------------------------------------
+# Build the whisper-server env: prepend the binary dir (co-located libs win, and
+# a backstop where the loader ignores the rpath) and scrub secret-bearing vars the
+# binary never needs. On WSL2 ROCm the system HIP libs go first, since a bundle's
+# bare-metal HIP cannot drive /dev/dxg. A CUDA bundle ships libggml-cuda.so but not
+# libcudart/libcublas (paired with the user's PyTorch), so add the
+# CUDA-from-PyTorch runtime dirs the selection gated on, else the backend cannot
+# resolve a runtime that lives only in wheels. Mirrors llama's binary_env(); the
+# scrub/WSL/dedupe helpers live in utils.prebuilt.
+
+# Module-level aliases keep the historical patch points for tests and callers.
+_wsl_system_rocm_lib_dirs = wsl_system_rocm_lib_dirs
+_dedupe_existing_dirs = dedupe_existing_dirs
+
+
+def _whisper_server_child_env(binary: str) -> dict[str, str]:
+ """Env for the whisper-server subprocess: secrets scrubbed, home/profile vars
+ repointed at a managed scratch dir (a downloaded binary must not see the real
+ home's token caches), co-located libs on the loader path, WSL system HIP first
+ on WSL2 ROCm."""
+ env = scrub_env(os.environ)
+ isolate_home(env, str(_managed_whisper_cpp_dir() / ".child_home"))
+ bin_dir = str(Path(binary).parent)
+ # A CUDA bundle needs the CUDA-from-PyTorch wheel dirs so libcudart/libcublas
+ # resolve at launch when they live only in site-packages/nvidia/*/lib. Placed
+ # after bin_dir so co-located libs still win; empty for other bundles.
+ cuda_runtime_dirs: list[str] = []
+ bundle_dir = Path(bin_dir)
+ has_cuda_module = any(
+ path.is_file()
+ for pattern in ("libggml-cuda.so*", "ggml-cuda*.dll")
+ for path in bundle_dir.glob(pattern)
+ )
+ if has_cuda_module:
+ try:
+ from utils.prebuilt.runtime_libs import python_runtime_dirs
+ cuda_runtime_dirs = python_runtime_dirs()
+ except Exception:
+ cuda_runtime_dirs = []
+ if sys.platform == "win32":
+ var, lead = "PATH", [bin_dir, *cuda_runtime_dirs]
+ elif sys.platform == "darwin":
+ var, lead = "DYLD_LIBRARY_PATH", [bin_dir]
+ else:
+ var, lead = "LD_LIBRARY_PATH", [bin_dir, *cuda_runtime_dirs]
+ wsl_rocm = _wsl_system_rocm_lib_dirs()
+ if wsl_rocm:
+ lead = [*wsl_rocm, bin_dir, *cuda_runtime_dirs]
+ env.setdefault("HSA_ENABLE_DXG_DETECTION", "1")
+ existing = [p for p in env.get(var, "").split(os.pathsep) if p]
+ env[var] = os.pathsep.join(_dedupe_existing_dirs([*lead, *existing]))
+ return env
+
+
+# ---------------------------------------------------------------------------
+# Model file download (single files; deliberately outside the Model Hub flow)
+# ---------------------------------------------------------------------------
+
+
+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
+ try:
+ return hf_hub_download(
+ repo_id = GGML_STT_REPOS[model_id],
+ filename = GGML_STT_MODELS[model_id],
+ local_files_only = True,
+ )
+ except Exception:
+ return None
+
+
+class _GgmlDownloadState:
+ """Tracks one background hf_hub_download of a curated GGML file."""
+
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self._thread: Optional[threading.Thread] = None
+ self._model_id: Optional[str] = None
+ self._error: Optional[str] = None
+ self._total_bytes: Optional[int] = None
+ self._etag: Optional[str] = None
+
+ 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,
+ "bytes_total": self._total_bytes if downloading else None,
+ "bytes_done": self._incomplete_bytes() if downloading else None,
+ }
+
+ def _incomplete_bytes(self) -> Optional[int]:
+ """Best-effort progress: size of the in-flight blob in the HF cache.
+
+ hf_hub_download writes ``blobs/<etag>.incomplete``; prefer this file's
+ etag, else the largest in-flight blob.
+ """
+ try:
+ from huggingface_hub.constants import HF_HUB_CACHE
+
+ # 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"
+ )
+ if not repo_dir.is_dir():
+ return None
+ etag = self._etag
+ if etag:
+ target = repo_dir / f"{etag}.incomplete"
+ if target.is_file():
+ return target.stat().st_size
+ sizes = [p.stat().st_size for p in repo_dir.glob("*.incomplete") if p.is_file()]
+ return max(sizes) if sizes else None
+ except Exception:
+ return None
+
+ def start(
+ self,
+ model_id: str,
+ hf_token: Optional[str] = None,
+ ) -> None:
+ model_id = resolve_ggml_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 GGUF 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._etag = 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:
+ 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,
+ )
+ 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)
+ with self._lock:
+ self._total_bytes = meta.size
+ self._etag = meta.etag
+ except Exception:
+ pass
+ hf_hub_download(
+ repo_id = repo_id,
+ filename = filename,
+ token = hf_token or None,
+ )
+ except Exception as exc:
+ logger.warning("GGUF STT download failed for %s: %s", model_id, exc)
+ with self._lock:
+ self._error = f"Download failed for '{model_id}'."
+
+
+_download_state = _GgmlDownloadState()
+
+
+def start_model_download(model: Optional[str], hf_token: Optional[str] = None) -> None:
+ _download_state.start(resolve_ggml_model_id(model), hf_token)
+
+
+def download_status() -> dict:
+ return _download_state.status()
+
+
+# ---------------------------------------------------------------------------
+# WAV packaging
+# ---------------------------------------------------------------------------
+
+
+def _pcm_to_wav_bytes(decoded_audio) -> bytes:
+ """Wrap decoded float32 mono 16 kHz PCM into an in-memory 16-bit WAV."""
+ import numpy as np
+
+ clipped = np.clip(decoded_audio, -1.0, 1.0)
+ pcm16 = (clipped * 32767.0).astype("<i2")
+ buf = io.BytesIO()
+ with wave.open(buf, "wb") as w:
+ w.setnchannels(1)
+ w.setsampwidth(2)
+ w.setframerate(_TARGET_SAMPLE_RATE)
+ w.writeframes(pcm16.tobytes())
+ return buf.getvalue()
+
+
+# ---------------------------------------------------------------------------
+# Sidecar
+# ---------------------------------------------------------------------------
+
+
+class GgmlSttSidecar:
+ """Owns one whisper-server subprocess and proxies dictation to it."""
+
+ def __init__(self, keep_alive_seconds: float = STT_KEEP_ALIVE_SECONDS) -> None:
+ self._lock = threading.RLock()
+ self._process: Optional[subprocess.Popen] = None
+ self._port: Optional[int] = None
+ self._model_id: Optional[str] = None
+ self._idle_timer: Optional[threading.Timer] = None
+ self._idle_generation = 0
+ self._keep_alive_seconds = keep_alive_seconds
+ # Set while whisper-server starts so training admission can account for
+ # the accelerator memory it is about to bind. Read without the lock.
+ self._loading = False
+ # A still-starting whisper-server is cancellable so training can preempt
+ # it before it binds accelerator memory. Assigned inside self._lock but
+ # acted on without it: cancel_pending_load() runs while load() holds the
+ # lock, so the event is the source of truth and terminating the process
+ # is a best-effort fast path.
+ self._load_cancel_event: Optional[threading.Event] = None
+ self._starting_process: Optional[subprocess.Popen] = None
+ # Set before the updater waits for _lock, then kept set while it owns
+ # the lock and atomically replaces the managed install tree. New loads
+ # fail fast instead of starting a process from files being swapped.
+ self._update_in_progress = False
+
+ @property
+ def loaded_model(self) -> Optional[str]:
+ # Lock-free status read (like stt_sidecar.py): transcribe() holds
+ # self._lock for the whole inference call (up to
+ # _TRANSCRIBE_TIMEOUT_SECONDS), and status polls plus training admission
+ # must not block behind it. _process_alive() snapshots self._process
+ # before poll(), which subprocess guards with _waitpid_lock, so a
+ # concurrent unload is safe.
+ return self._model_id if self._process_alive() else None
+
+ @property
+ def device(self) -> Optional[str]:
+ return "whisper.cpp" if self._process_alive() else None
+
+ def is_loading(self) -> bool:
+ # True only while whisper-server is starting (seconds to bind its GPU
+ # backend); load() sets and clears the flag around that window.
+ return self._loading
+
+ @property
+ def keep_alive_seconds(self) -> float:
+ return self._keep_alive_seconds
+
+ def _process_alive(self) -> bool:
+ # Snapshot self._process once: a concurrent unload() nulls it under the
+ # lock, so lock-free readers would otherwise re-read None between the
+ # truthiness check and .poll().
+ process = self._process
+ return process is not None and process.poll() is None
+
+ # -- idle unload ------------------------------------------------------
+
+ def _cancel_idle_unload_locked(self) -> None:
+ self._idle_generation += 1
+ 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 not self._process_alive():
+ return
+ generation = self._idle_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._idle_generation:
+ return
+ logger.info("Unloading idle GGUF STT model %s", self._model_id)
+ self._release_locked()
+
+ # -- process lifecycle -------------------------------------------------
+
+ def _release_locked(self) -> None:
+ self._cancel_idle_unload_locked()
+ process = self._process
+ self._process = None
+ self._port = None
+ self._model_id = None
+ if process is not None and process.poll() is None:
+ process.terminate()
+ try:
+ process.wait(timeout = 10)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout = 10)
+ if process is not None:
+ forget_pid(process.pid)
+
+ def unload(self) -> None:
+ with self._lock:
+ self._release_locked()
+
+ def _raise_if_update_in_progress(self) -> None:
+ if self._update_in_progress:
+ raise SttEngineUnavailableError(
+ "The local transcription runtime is being updated. Try dictation again shortly."
+ )
+
+ @contextmanager
+ def update_maintenance(self) -> Iterator[bool]:
+ """Block new loads while the managed whisper.cpp tree is replaced.
+
+ The flag is published before waiting for an existing transcription to
+ release ``_lock``. Holding that lock across the yielded installer phase
+ prevents Windows from relocking the executable and prevents every host
+ from starting a process against a partially swapped tree. The yielded
+ value records whether a warm model had to be unloaded.
+ """
+ self._update_in_progress = True
+ try:
+ with self._lock:
+ model_was_active = self._process_alive()
+ self._release_locked()
+ yield model_was_active
+ finally:
+ self._update_in_progress = False
+
+ def cancel_pending_load(self) -> bool:
+ # Preempt a starting whisper-server so training does not launch while it
+ # binds accelerator memory. load() holds self._lock for the whole startup,
+ # so act without the lock: signal abort and terminate the starting
+ # process. _wait_for_server observes the event and raises, then load()
+ # reaps the process and releases the lock.
+ if not self._loading:
+ return False
+ event = self._load_cancel_event
+ if event is None:
+ return False
+ event.set()
+ process = self._starting_process
+ 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:
+ # load() holds self._lock across startup and cancel cleanup, so acquiring
+ # it blocks until a cancelled server is killed, reaped, and its
+ # accelerator memory released.
+ with self._lock:
+ pass
+
+ @staticmethod
+ def _reserve_free_port() -> tuple[socket.socket, int]:
+ """Bind an ephemeral port and keep the socket held.
+
+ The caller closes the reservation immediately before spawning
+ whisper-server, shrinking the window in which another local process
+ could bind the port. SO_REUSEADDR lets the child rebind right after.
+ """
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ s.bind(("127.0.0.1", 0))
+ return s, s.getsockname()[1]
+
+ def _ensure_model_downloaded(self, model_id: str) -> str:
+ path = _cached_model_path(model_id)
+ if path is None:
+ raise SttModelNotDownloadedError(
+ f"STT model '{model_id}' (GGUF) is not downloaded. "
+ "Download it in Settings, then Voice, before loading it."
+ )
+ return path
+
+ def load(self, model: Optional[str] = None) -> None:
+ """Start (or switch) whisper-server for the requested curated model."""
+ self._raise_if_update_in_progress()
+ model_id = resolve_ggml_model_id(model)
+ with self._lock:
+ self._raise_if_update_in_progress()
+ binary = ensure_engine_available()
+ if self._process_alive() and self._model_id == model_id:
+ self._schedule_idle_unload_locked()
+ return
+ model_path = self._ensure_model_downloaded(model_id)
+ self._release_locked()
+ reservation, port = self._reserve_free_port()
+ command = [binary, "-m", model_path, "--host", "127.0.0.1", "--port", str(port)]
+ marker = _whisper_install_marker(binary)
+ if _training_active():
+ # Keep whisper.cpp off the accelerator during training (like the
+ # Transformers sidecar's CPU choice) so a mid-training dictation
+ # cannot reclaim the VRAM training just freed.
+ command.append("--no-gpu")
+ elif marker is not None and marker.get("backend") == "cpu":
+ # A deliberate CPU install must stay CPU: the slim wiring links
+ # every llama ggml backend (including CUDA/ROCm), so without
+ # this flag a cpu-selected install would still grab the GPU.
+ command.append("--no-gpu")
+ logger.info(
+ "Starting whisper-server for STT model %s on 127.0.0.1:%s",
+ model_id,
+ port,
+ )
+ cancel_event = threading.Event()
+ self._load_cancel_event = cancel_event
+ self._loading = True
+ try:
+ # Release the reservation as late as possible: whisper-server
+ # binds the port moments after this close.
+ reservation.close()
+ process = subprocess.Popen(
+ command,
+ stdout = subprocess.DEVNULL,
+ stderr = subprocess.DEVNULL,
+ stdin = subprocess.DEVNULL,
+ # Co-located GPU libs on the loader path (WSL system HIP first),
+ # secrets scrubbed from the downloaded binary's env.
+ env = _whisper_server_child_env(binary),
+ # Die with Studio (Linux PDEATHSIG, Windows job) so a crash
+ # never orphans a server holding the model.
+ **child_popen_kwargs(),
+ )
+ self._starting_process = process
+ adopt_pid(process.pid) # terminate_all backstop for graceful exits
+ try:
+ self._wait_for_server(process, port, cancel_event)
+ except Exception:
+ if process.poll() is None:
+ process.kill()
+ process.wait(timeout = 10)
+ forget_pid(process.pid)
+ raise
+ self._process = process
+ self._port = port
+ self._model_id = model_id
+ self._schedule_idle_unload_locked()
+ finally:
+ reservation.close() # no-op when already released before spawn
+ self._loading = False
+ self._load_cancel_event = None
+ self._starting_process = None
+
+ @staticmethod
+ def _wait_for_server(
+ process: subprocess.Popen,
+ port: int,
+ cancel_event: Optional[threading.Event] = None,
+ ) -> None:
+ deadline = time.monotonic() + _SERVER_START_TIMEOUT_SECONDS
+ while time.monotonic() < deadline:
+ if cancel_event is not None and cancel_event.is_set():
+ raise SttLoadCancelledError(
+ "GGUF STT model loading was cancelled so training could start."
+ )
+ if process.poll() is not None:
+ raise SttEngineUnavailableError(
+ "The local transcription runtime exited before becoming "
+ "ready; the model file may be corrupt or unsupported."
+ )
+ # Require a whisper-server-specific response twice, with the managed
+ # child alive around each probe. An arbitrary local process that won
+ # the bind race would otherwise be mistaken for the sidecar and
+ # receive the user's microphone audio.
+ if GgmlSttSidecar._probe_is_whisper_server(process, port) and (
+ GgmlSttSidecar._probe_is_whisper_server(process, port)
+ ):
+ return
+ time.sleep(0.2)
+ raise SttEngineUnavailableError("The local transcription runtime did not start in time.")
+
+ @staticmethod
+ def _probe_is_whisper_server(process: subprocess.Popen, port: int) -> bool:
+ """One readiness probe: our child is alive and the responder looks like
+ whisper.cpp's server (its index page and errors identify whisper)."""
+ if process.poll() is not None:
+ return False
+ try:
+ req = urllib.request.Request(f"http://127.0.0.1:{port}/", method = "GET")
+ with urllib.request.urlopen(req, timeout = 2) as response:
+ body = response.read(65536)
+ except Exception:
+ return False
+ if process.poll() is not None:
+ return False
+ return b"whisper" in body.lower()
+
+ # -- transcription ------------------------------------------------------
+
+ def transcribe(
+ self,
+ audio: bytes,
+ model: Optional[str] = None,
+ language: Optional[str] = None,
+ fast: bool = False,
+ ) -> dict:
+ """Transcribe encoded audio bytes via whisper-server.
+
+ Accepts any container PyAV can decode (same validation and caps as the
+ Transformers sidecar). Returns {text, language, duration, model}.
+ """
+ self._raise_if_update_in_progress()
+ ensure_engine_available()
+ model_id = resolve_ggml_model_id(model)
+ lang = normalize_whisper_language(language)
+ known_languages = _known_whisper_languages()
+ if lang is not None and known_languages is not None and lang not in known_languages:
+ raise SttLanguageError(
+ f"Language '{language}' is not supported by STT model '{model_id}'."
+ )
+ # Reject a missing model before decoding so a long clip does not burn CPU
+ # only to 409 (matches the Transformers sidecar's preflight).
+ self._ensure_model_downloaded(model_id)
+ decoded_audio = _decode_audio_bounded(audio)
+ wav_bytes = _pcm_to_wav_bytes(decoded_audio)
+ with self._lock:
+ try:
+ self.load(model_id)
+ text = self._post_inference(wav_bytes, lang, fast)
+ finally:
+ self._schedule_idle_unload_locked()
+ duration = (len(decoded_audio) / _TARGET_SAMPLE_RATE) if len(decoded_audio) else None
+ return {
+ "text": text,
+ "language": lang,
+ "duration": duration,
+ "model": model_id,
+ }
+
+ def _post_inference(self, wav_bytes: bytes, lang: Optional[str], fast: bool) -> str:
+ boundary = uuid.uuid4().hex
+ fields = {
+ "temperature": "0.0",
+ "response_format": "json",
+ # Match the Transformers sidecar: 5-way beam search, greedy for fast.
+ "beam_size": "1" if fast else "5",
+ "language": lang or "auto",
+ }
+ parts: list[bytes] = []
+ for name, value in fields.items():
+ parts.append(
+ (
+ f"--{boundary}\r\nContent-Disposition: form-data; "
+ f'name="{name}"\r\n\r\n{value}\r\n'
+ ).encode()
+ )
+ parts.append(
+ (
+ f"--{boundary}\r\nContent-Disposition: form-data; "
+ 'name="file"; filename="dictation.wav"\r\n'
+ "Content-Type: audio/wav\r\n\r\n"
+ ).encode()
+ + wav_bytes
+ + b"\r\n"
+ )
+ parts.append(f"--{boundary}--\r\n".encode())
+ body = b"".join(parts)
+ req = urllib.request.Request(
+ f"http://127.0.0.1:{self._port}/inference",
+ data = body,
+ headers = {"Content-Type": f"multipart/form-data; boundary={boundary}"},
+ )
+ try:
+ with urllib.request.urlopen(req, timeout = _TRANSCRIBE_TIMEOUT_SECONDS) as resp:
+ payload = json.load(resp)
+ except SttAudioDecodeError:
+ raise
+ except Exception as exc:
+ raise SttEngineUnavailableError(
+ "The local transcription runtime did not answer the request."
+ ) from exc
+ text = payload.get("text")
+ if not isinstance(text, str):
+ raise SttAudioDecodeError("Could not decode the audio.")
+ # whisper.cpp joins segments with newlines; dictation wants one line.
+ return " ".join(part.strip() for part in text.splitlines() if part.strip()).strip()
+
+
+_sidecar: Optional[GgmlSttSidecar] = None
+
+
+def get_ggml_stt_sidecar() -> GgmlSttSidecar:
+ global _sidecar
+ if _sidecar is None:
+ _sidecar = GgmlSttSidecar()
+ return _sidecar
diff --git a/studio/backend/core/inference/stt_sidecar.py b/studio/backend/core/inference/stt_sidecar.py
new file mode 100644
index 00000000000..7ac7e93c876
--- /dev/null
+++ b/studio/backend/core/inference/stt_sidecar.py
@@ -0,0 +1,1130 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""
+Standalone speech-to-text (STT) sidecar for dictation.
+
+Loads a Whisper model (via Transformers) in the backend process, separate from
+the chat model's inference subprocess, so dictation works with any chat model
+without evicting it. Curated defaults plus any Transformers-compatible Whisper
+repo; weights come through Studio's Model Hub and stay warm briefly between
+dictations. CUDA runs float16; MPS and CPU run float32.
+"""
+
+from __future__ import annotations
+
+import gc
+import hashlib
+import io
+import json
+import os
+import re
+import threading
+import uuid
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Optional
+
+from loggers import get_logger
+
+logger = get_logger(__name__)
+
+# Multilingual Whisper defaults: stable API/UI id -> Hub repository. A request
+# may instead pass a validated Hugging Face `owner/model` id.
+STT_MODELS: dict[str, str] = {
+ "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",
+}
+DEFAULT_STT_MODEL = "small"
+STT_KEEP_ALIVE_SECONDS = 5 * 60
+_HF_REPO_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,95}/[A-Za-z0-9][A-Za-z0-9._-]{0,95}$")
+_HF_COMMIT_SHA = re.compile(r"^[0-9a-f]{40}$")
+
+# Bound decoded PCM length so a crafted upload cannot exhaust memory (callers
+# also cap the encoded bytes).
+_MAX_AUDIO_SECONDS = 30 * 60
+_TARGET_SAMPLE_RATE = 16000
+
+# Non-weight files WhisperProcessor/WhisperForConditionalGeneration may load.
+# Weight selection is built from pinned Hub metadata so repositories publishing
+# both formats do not download the same checkpoint twice.
+_STT_SNAPSHOT_SUPPORT_FILES = (
+ "config.json",
+ "generation_config.json",
+ "preprocessor_config.json",
+ "processor_config.json",
+ "tokenizer.json",
+ "tokenizer_config.json",
+ "vocab.json",
+ "merges.txt",
+ "normalizer.json",
+ "special_tokens_map.json",
+ "added_tokens.json",
+)
+_STT_SAFETENSORS_INDEX = "model.safetensors.index.json"
+_STT_PYTORCH_INDEX = "pytorch_model.bin.index.json"
+_STT_SAFETENSORS_WEIGHTS = "model.safetensors"
+_STT_PYTORCH_WEIGHTS = "pytorch_model.bin"
+_STT_REVISION_RECORD_VERSION = 1
+
+
+@dataclass(frozen = True)
+class _SelectedHubFile:
+ path: str
+ size: int
+ blob_key: Optional[str]
+
+
+@dataclass(frozen = True)
+class _CachedSttSnapshot:
+ path: Optional[Path]
+ is_multilingual: Optional[bool]
+
+
+class SttUnavailableError(RuntimeError):
+ """The STT backend (PyTorch/Transformers or PyAV) is not installed."""
+
+
+class SttLoadCancelledError(RuntimeError):
+ """An in-flight STT model load was cancelled for training."""
+
+
+class SttModelNotDownloadedError(RuntimeError):
+ """The selected model is not complete in the shared Hub cache."""
+
+
+class SttModelIdError(ValueError):
+ """The requested custom model is not a valid Hugging Face repository id."""
+
+
+class SttModelCompatibilityError(ValueError):
+ """The requested repository is not a Transformers Whisper checkpoint."""
+
+
+class SttAudioDecodeError(ValueError):
+ """The uploaded bytes could not be decoded as audio."""
+
+
+class SttAudioTooLongError(ValueError):
+ """The decoded audio exceeds the bounded transcription duration."""
+
+
+class SttLanguageError(ValueError):
+ """The requested language is not supported by the selected STT model."""
+
+
+_WHISPER_LANGUAGE_ALIASES = {
+ # Legacy/browser BCP-47 primaries whose Whisper code differs.
+ "cmn": "zh",
+ "fil": "tl",
+ "in": "id",
+ "iw": "he",
+ "ji": "yi",
+ "nb": "no",
+ "nn": "no",
+}
+
+
+def normalize_whisper_language(language: Optional[str]) -> Optional[str]:
+ """Convert a BCP-47 locale into the short code Whisper expects."""
+ if not language:
+ return None
+ normalized = language.strip().replace("_", "-").lower()
+ if not normalized or normalized == "auto":
+ return None
+ primary = normalized.split("-", 1)[0]
+ return _WHISPER_LANGUAGE_ALIASES.get(primary, primary)
+
+
+def _known_whisper_languages() -> Optional[frozenset[str]]:
+ """Return Whisper's language codes without constructing/loading a model."""
+ try:
+ from transformers.models.whisper.tokenization_whisper import LANGUAGES
+ except Exception:
+ # Transformers unavailable or the constant moved: skip the check.
+ return None
+ return frozenset(LANGUAGES)
+
+
+def ensure_stt_available() -> None:
+ """Raise when the complete local Whisper backend cannot be imported."""
+ try:
+ import av # noqa: F401
+ import torch # noqa: F401
+ import transformers # noqa: F401
+ except Exception as exc:
+ raise SttUnavailableError(
+ "Speech-to-text needs PyTorch, Transformers, and PyAV. "
+ "Run `unsloth studio update` to install them."
+ ) from exc
+
+
+def is_available() -> bool:
+ """True when the complete local Whisper backend can be imported."""
+ try:
+ ensure_stt_available()
+ except SttUnavailableError:
+ return False
+ return True
+
+
+def resolve_model_id(model: Optional[str]) -> str:
+ """Resolve a curated id or validate a custom Hugging Face repository."""
+ if not model:
+ return DEFAULT_STT_MODEL
+ normalized = model.strip()
+ if normalized in STT_MODELS:
+ return normalized
+ if _HF_REPO_ID.fullmatch(normalized):
+ return normalized
+ raise SttModelIdError(
+ "STT model must be one of Studio's defaults or a Hugging Face "
+ "repository in 'owner/model' form."
+ )
+
+
+def resolve_model_repo(model_id: str) -> str:
+ """Return the Hub repository for a curated or custom model id."""
+ resolved = resolve_model_id(model_id)
+ return STT_MODELS.get(resolved, resolved)
+
+
+def _is_whisper_config(config: object) -> bool:
+ """True when Hub/local config metadata identifies a Whisper ASR model."""
+ if not isinstance(config, dict):
+ return False
+ model_type = config.get("model_type")
+ if isinstance(model_type, str) and model_type.strip().lower() == "whisper":
+ return True
+ architectures = config.get("architectures")
+ return isinstance(architectures, list) and any(
+ isinstance(name, str) and name == "WhisperForConditionalGeneration"
+ for name in architectures
+ )
+
+
+def _read_json_object(path: Path) -> dict:
+ try:
+ with open(path, "r", encoding = "utf-8") as file:
+ value = json.load(file)
+ return value if isinstance(value, dict) else {}
+ except Exception:
+ return {}
+
+
+def _active_hf_hub_cache() -> Path:
+ """Return the active Hub cache while respecting runtime test overrides."""
+ explicit = (os.environ.get("HF_HUB_CACHE") or "").strip()
+ if explicit:
+ return Path(explicit).expanduser()
+ 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)
+
+
+def _repo_cache_dir(repo: str) -> Path:
+ return _active_hf_hub_cache() / f"models--{repo.replace('/', '--')}"
+
+
+def _revision_record_path(repo: str) -> Path:
+ from utils.paths.storage_roots import cache_root
+ digest = hashlib.sha256(repo.encode("utf-8")).hexdigest()
+ return cache_root() / "stt-revisions" / f"{digest}.json"
+
+
+def _write_revision_record(repo: str, revision: str) -> None:
+ """Persist immutable identity only, never an HF-cache absolute path."""
+ if not _HF_COMMIT_SHA.fullmatch(revision):
+ return
+ path = _revision_record_path(repo)
+ tmp = path.with_name(f".{path.name}.tmp-{uuid.uuid4().hex[:8]}")
+ try:
+ path.parent.mkdir(parents = True, exist_ok = True)
+ with tmp.open("w", encoding = "utf-8") as handle:
+ json.dump(
+ {
+ "version": _STT_REVISION_RECORD_VERSION,
+ "repo": repo,
+ "revision": revision,
+ },
+ handle,
+ )
+ handle.flush()
+ os.fsync(handle.fileno())
+ os.replace(tmp, path)
+ except OSError as exc:
+ logger.debug("Could not persist STT revision for %s: %s", repo, exc)
+ try:
+ tmp.unlink(missing_ok = True)
+ except OSError:
+ pass
+
+
+def _read_revision_record(repo: str) -> Optional[str]:
+ payload = _read_json_object(_revision_record_path(repo))
+ if payload.get("version") != _STT_REVISION_RECORD_VERSION or payload.get("repo") != repo:
+ return None
+ revision = payload.get("revision")
+ return revision if isinstance(revision, str) and _HF_COMMIT_SHA.fullmatch(revision) else None
+
+
+def _safe_snapshot_for_revision(repo: str, revision: str) -> Optional[Path]:
+ """Resolve a canonical SHA below this repository's active snapshots dir."""
+ if not _HF_COMMIT_SHA.fullmatch(revision):
+ return None
+ snapshots = _repo_cache_dir(repo) / "snapshots"
+ candidate = snapshots / revision
+ try:
+ snapshots_resolved = snapshots.resolve()
+ candidate_resolved = candidate.resolve()
+ except (OSError, RuntimeError):
+ return None
+ if snapshots_resolved not in candidate_resolved.parents or not candidate_resolved.is_dir():
+ return None
+ return candidate_resolved
+
+
+def _snapshot_usable(model_id: str, snapshot: Path) -> bool:
+ if not _snapshot_is_complete(snapshot):
+ return False
+ if model_id not in STT_MODELS:
+ return _is_whisper_config(_read_json_object(snapshot / "config.json"))
+ return True
+
+
+def _find_complete_cached_snapshot(model: Optional[str]) -> Optional[Path]:
+ """Find one complete local snapshot without contacting the Hub."""
+ model_id = resolve_model_id(model)
+ repo = resolve_model_repo(model_id)
+
+ recorded = _read_revision_record(repo)
+ if recorded:
+ snapshot = _safe_snapshot_for_revision(repo, recorded)
+ if snapshot is not None and _snapshot_usable(model_id, snapshot):
+ return snapshot
+
+ ref = _repo_cache_dir(repo) / "refs" / "main"
+ try:
+ revision = ref.read_text(encoding = "utf-8").strip()
+ except OSError:
+ revision = ""
+ snapshot = _safe_snapshot_for_revision(repo, revision)
+ if snapshot is not None and _snapshot_usable(model_id, snapshot):
+ _write_revision_record(repo, revision)
+ return snapshot
+
+ snapshots = _repo_cache_dir(repo) / "snapshots"
+ try:
+ revisions = sorted(
+ (
+ (path.stat().st_mtime_ns, path.name)
+ for path in snapshots.iterdir()
+ if path.is_dir() and _HF_COMMIT_SHA.fullmatch(path.name)
+ ),
+ reverse = True,
+ )
+ except OSError:
+ return None
+ for _mtime, revision in revisions:
+ snapshot = _safe_snapshot_for_revision(repo, revision)
+ if snapshot is not None and _snapshot_usable(model_id, snapshot):
+ _write_revision_record(repo, revision)
+ return snapshot
+ return None
+
+
+def _selected_file_from_sibling(sibling) -> _SelectedHubFile:
+ lfs = getattr(sibling, "lfs", None)
+ blob_key = getattr(lfs, "sha256", None) or getattr(sibling, "blob_id", None)
+ return _SelectedHubFile(
+ path = sibling.rfilename,
+ size = max(0, int(getattr(sibling, "size", 0) or 0)),
+ blob_key = blob_key if isinstance(blob_key, str) and blob_key else None,
+ )
+
+
+def _select_snapshot_files(info, load_index) -> tuple[_SelectedHubFile, ...]:
+ """Select support files and exactly one complete Transformers weight format."""
+ siblings = {
+ sibling.rfilename: sibling
+ for sibling in (getattr(info, "siblings", None) or [])
+ if isinstance(getattr(sibling, "rfilename", None), str)
+ }
+ selected = {name for name in _STT_SNAPSHOT_SUPPORT_FILES if name in siblings}
+
+ index_name: Optional[str] = None
+ if _STT_SAFETENSORS_INDEX in siblings:
+ index_name = _STT_SAFETENSORS_INDEX
+ elif _STT_SAFETENSORS_WEIGHTS in siblings:
+ selected.add(_STT_SAFETENSORS_WEIGHTS)
+ elif _STT_PYTORCH_INDEX in siblings:
+ index_name = _STT_PYTORCH_INDEX
+ elif _STT_PYTORCH_WEIGHTS in siblings:
+ selected.add(_STT_PYTORCH_WEIGHTS)
+ else:
+ raise SttModelCompatibilityError("The STT repository has no complete model weights.")
+
+ if index_name is not None:
+ weight_map = load_index(index_name).get("weight_map")
+ if not isinstance(weight_map, dict) or not weight_map:
+ raise SttModelCompatibilityError(f"Invalid checkpoint index '{index_name}'.")
+ shards = set(weight_map.values())
+ if not all(isinstance(shard, str) and shard in siblings for shard in shards):
+ raise SttModelCompatibilityError(f"Checkpoint index '{index_name}' has missing shards.")
+ selected.add(index_name)
+ selected.update(shards)
+
+ return tuple(_selected_file_from_sibling(siblings[name]) for name in sorted(selected))
+
+
+def validate_remote_model(model: Optional[str], hf_token: Optional[str] = None) -> dict:
+ """Verify a custom Hub repository is Whisper-compatible without downloading weights."""
+ model_id = resolve_model_id(model)
+ repo = resolve_model_repo(model_id)
+ if model_id in STT_MODELS:
+ return {"model": model_id, "repo": repo}
+
+ try:
+ from huggingface_hub import HfApi
+ info = HfApi(token = hf_token or False).model_info(
+ repo,
+ expand = ["config", "sha"],
+ timeout = 10,
+ )
+ except Exception as exc:
+ raise SttModelCompatibilityError(
+ f"Could not verify STT model '{model_id}'. "
+ "Check that the repository exists and your Hugging Face token can access it."
+ ) from exc
+
+ if not _is_whisper_config(getattr(info, "config", None)):
+ raise SttModelCompatibilityError(
+ f"STT model '{model_id}' is not a compatible Transformers Whisper model."
+ )
+ revision = getattr(info, "sha", None)
+ if not isinstance(revision, str) or not _HF_COMMIT_SHA.fullmatch(revision):
+ raise SttModelCompatibilityError(
+ f"Could not resolve an immutable revision for STT model '{model_id}'."
+ )
+ # The commit that was validated; the download pins to it so the repo cannot
+ # be swapped between validation and snapshot_download (TOCTOU).
+ return {"model": model_id, "repo": repo, "revision": revision}
+
+
+def _is_missing_local_model_error(exc: BaseException) -> bool:
+ """Recognize a local-cache-only miss by name/message, without importing HF
+ internals (tolerates huggingface_hub/Transformers moving the exception)."""
+ current: Optional[BaseException] = exc
+ seen: set[int] = set()
+ while current is not None and id(current) not in seen:
+ seen.add(id(current))
+ if type(current).__name__ in ("LocalEntryNotFoundError", "EntryNotFoundError"):
+ return True
+ message = str(current).lower()
+ if "local_files_only" in message or "does not appear to have a file" in message:
+ return True
+ current = current.__cause__ or current.__context__
+ return False
+
+
+def _snapshot_is_complete(snapshot: Path) -> bool:
+ """True when a cached snapshot holds every file loading needs.
+
+ An aborted download can leave only metadata behind, and an offline lookup
+ cannot know the repo's full file list, so verify config, preprocessor,
+ tokenizer, and weights directly. is_file() follows cache symlinks, so a
+ link from an interrupted blob download does not count.
+ """
+ index = next(
+ (
+ snapshot / name
+ for name in ("model.safetensors.index.json", "pytorch_model.bin.index.json")
+ if (snapshot / name).is_file()
+ ),
+ None,
+ )
+ if index is not None:
+ # Sharded checkpoint (safetensors or PyTorch): every shard must exist.
+ weight_map = _read_json_object(index).get("weight_map")
+ if not isinstance(weight_map, dict) or not weight_map:
+ return False
+ has_weights = all((snapshot / shard).is_file() for shard in set(weight_map.values()))
+ else:
+ has_weights = any(
+ (snapshot / name).is_file() for name in (_STT_SAFETENSORS_WEIGHTS, _STT_PYTORCH_WEIGHTS)
+ )
+ # WhisperProcessor needs the tokenizer: either the fast tokenizer.json or
+ # the slow vocab.json + merges.txt pair.
+ has_tokenizer = (snapshot / "tokenizer.json").is_file() or (
+ (snapshot / "vocab.json").is_file() and (snapshot / "merges.txt").is_file()
+ )
+ return (
+ has_weights
+ and has_tokenizer
+ and (snapshot / "config.json").is_file()
+ and (snapshot / "preprocessor_config.json").is_file()
+ )
+
+
+def is_model_downloaded(model: Optional[str]) -> bool:
+ """True when a usable Whisper snapshot exists in the local HF cache."""
+ try:
+ return _find_complete_cached_snapshot(model) is not None
+ except Exception:
+ return False
+
+
+class _SnapshotDownloadState:
+ """Tracks one background snapshot_download of a dictation repository.
+
+ Like stt_ggml_sidecar's tracker, but a Transformers checkpoint is a whole
+ repo, so progress is the byte count of its cache blobs.
+ """
+
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self._thread: Optional[threading.Thread] = 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
+
+ def status(self) -> dict:
+ with self._lock:
+ downloading = self._thread is not None and self._thread.is_alive()
+ show_progress = downloading or self._complete
+ return {
+ "downloading": downloading,
+ "model": self._model_id if downloading else None,
+ "error": self._error,
+ "bytes_total": self._total_bytes if show_progress else None,
+ "bytes_done": self._blob_bytes() if show_progress else None,
+ }
+
+ def _blob_bytes(self) -> Optional[int]:
+ """Best-effort progress: bytes in the repo's HF cache blobs.
+
+ Counts only the selected support files and one selected weight format,
+ including in-progress ``.incomplete`` blobs.
+ """
+ try:
+ # Caller may hold the non-reentrant self._lock; a bare read is safe.
+ repo = self._repo
+ selected_files = self._selected_files
+ if not repo or not selected_files:
+ return None
+ blobs = _repo_cache_dir(repo) / "blobs"
+ if not blobs.is_dir():
+ return 0
+ done = 0
+ for selected in selected_files:
+ if not selected.blob_key:
+ continue
+ complete = blobs / selected.blob_key
+ incomplete = blobs / f"{selected.blob_key}.incomplete"
+ candidate = complete if complete.is_file() else incomplete
+ if candidate.is_file():
+ done += min(candidate.stat().st_size, selected.size)
+ total = self._total_bytes
+ return min(done, total) if total is not None else done
+ except Exception:
+ return None
+
+ def start(
+ self,
+ model_id: str,
+ hf_token: Optional[str] = None,
+ revision: Optional[str] = None,
+ ) -> None:
+ model_id = resolve_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._repo = resolve_model_repo(model_id)
+ self._error = None
+ self._total_bytes = None
+ self._selected_files = ()
+ self._complete = False
+ thread = threading.Thread(
+ target = self._run, args = (self._repo, hf_token, revision), daemon = True
+ )
+ self._thread = thread
+ thread.start()
+
+ def _run(
+ self,
+ repo: str,
+ hf_token: Optional[str],
+ revision: Optional[str] = None,
+ ) -> None:
+ try:
+ from huggingface_hub import HfApi, hf_hub_download, snapshot_download
+
+ info = HfApi(token = hf_token or None).model_info(
+ repo,
+ revision = revision,
+ files_metadata = True,
+ timeout = 30,
+ )
+ if not revision:
+ revision = getattr(info, "sha", None)
+ if not isinstance(revision, str) or not _HF_COMMIT_SHA.fullmatch(revision):
+ raise SttModelCompatibilityError(
+ f"Could not resolve an immutable revision for STT model '{repo}'."
+ )
+
+ def load_index(filename: str) -> dict:
+ path = hf_hub_download(
+ repo_id = repo,
+ filename = filename,
+ revision = revision,
+ token = hf_token or None,
+ )
+ return _read_json_object(Path(path))
+
+ selected_files = _select_snapshot_files(info, load_index)
+ total = sum(selected.size for selected in selected_files)
+ 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,
+ )
+ )
+ if not _snapshot_is_complete(snapshot):
+ raise SttModelCompatibilityError(
+ f"Downloaded STT snapshot for '{repo}' is incomplete."
+ )
+ _write_revision_record(repo, revision)
+ with self._lock:
+ self._complete = True
+ except Exception as exc:
+ logger.warning("STT snapshot download failed for %s: %s", repo, exc)
+ with self._lock:
+ self._error = f"Download failed for '{repo}'."
+
+
+_download_state = _SnapshotDownloadState()
+
+
+def start_model_download(
+ model: Optional[str],
+ hf_token: Optional[str] = None,
+ revision: Optional[str] = None,
+) -> None:
+ _download_state.start(resolve_model_id(model), hf_token, revision = revision)
+
+
+def download_status() -> dict:
+ return _download_state.status()
+
+
+def _training_active() -> bool:
+ try:
+ from core.training import get_training_backend
+ return bool(get_training_backend().is_training_active())
+ except Exception:
+ return False
+
+
+def _clear_device_cache(device: Optional[str]) -> None:
+ gc.collect()
+ try:
+ import torch
+ if device == "cuda":
+ torch.cuda.empty_cache()
+ elif device == "mps":
+ torch.mps.empty_cache()
+ except Exception:
+ pass
+
+
+def _pick_device():
+ """Return (device, torch_dtype) for the Whisper model.
+
+ CUDA uses float16. MPS and CPU use float32: Whisper's decoder is unstable in
+ float16 on MPS and degenerates into repeated tokens.
+ """
+ try:
+ import torch
+
+ # New loads use CPU during training; a resident GPU model may stay put
+ # when the training admission check confirms enough headroom.
+ training_active = _training_active()
+ if not training_active and torch.cuda.is_available():
+ return "cuda", torch.float16
+ if (
+ not training_active
+ and getattr(torch.backends, "mps", None) is not None
+ and torch.backends.mps.is_available()
+ ):
+ return "mps", torch.float32
+ return "cpu", torch.float32
+ except Exception as exc:
+ logger.debug("STT device detection failed, using CPU: %s", exc)
+ import torch
+ return "cpu", torch.float32
+
+
+def _decode_audio_bounded(audio: bytes):
+ """Decode to 16 kHz mono PCM without buffering unbounded audio.
+
+ A small, highly-compressed upload can expand far past the encoded request
+ limit once decoded, so decode frame-by-frame and enforce the sample cap as
+ frames arrive, then hand the array straight to Whisper.
+ """
+ try:
+ import av
+ import numpy as np
+ from av.error import FFmpegError, InvalidDataError
+ except ImportError as exc:
+ raise SttUnavailableError(
+ "Speech-to-text needs the PyAV package to decode audio. "
+ "Run `unsloth studio update` to install it."
+ ) from exc
+
+ max_samples = _MAX_AUDIO_SECONDS * _TARGET_SAMPLE_RATE
+ sample_count = 0
+ raw_buffer = io.BytesIO()
+ resampler = av.audio.resampler.AudioResampler(
+ format = "s16",
+ layout = "mono",
+ rate = _TARGET_SAMPLE_RATE,
+ )
+ # Group frames before resampling so short clips need one resampler call
+ # rather than one per codec frame.
+ fifo = av.audio.fifo.AudioFifo()
+
+ def write_frame(frame) -> None:
+ nonlocal sample_count
+ array = frame.to_ndarray()
+ sample_count += array.size
+ if sample_count > max_samples:
+ max_minutes = _MAX_AUDIO_SECONDS // 60
+ unit = "minute" if max_minutes == 1 else "minutes"
+ raise SttAudioTooLongError(f"Audio must be {max_minutes} {unit} or shorter.")
+ raw_buffer.write(array)
+
+ try:
+ with av.open(io.BytesIO(audio), mode = "r", metadata_errors = "ignore") as container:
+ if not container.streams.audio:
+ raise SttAudioDecodeError("Could not decode the audio.")
+ frames = iter(container.decode(audio = 0))
+ while True:
+ try:
+ frame = next(frames)
+ except StopIteration:
+ break
+ except InvalidDataError:
+ # Skip a corrupt frame rather than fail the whole transcription.
+ continue
+ frame.pts = None
+ fifo.write(frame)
+ if fifo.samples >= 500000:
+ for resampled in resampler.resample(fifo.read()):
+ write_frame(resampled)
+ if fifo.samples > 0:
+ for resampled in resampler.resample(fifo.read()):
+ write_frame(resampled)
+ for resampled in resampler.resample(None):
+ write_frame(resampled)
+ except (SttAudioDecodeError, SttAudioTooLongError):
+ raise
+ except (FFmpegError, ValueError, RuntimeError) as exc:
+ raise SttAudioDecodeError("Could not decode the audio.") from exc
+ finally:
+ del fifo, resampler
+
+ if sample_count == 0:
+ raise SttAudioDecodeError("Could not decode the audio.")
+ decoded = np.frombuffer(raw_buffer.getbuffer(), dtype = np.int16).astype(np.float32)
+ decoded /= 32768.0
+ return decoded
+
+
+class WhisperSttSidecar:
+ """Lazily loaded Whisper model with idle eviction. Thread-safe."""
+
+ def __init__(self, keep_alive_seconds: float = STT_KEEP_ALIVE_SECONDS) -> None:
+ self._engine = None
+ self._model_id: Optional[str] = None
+ self._device: Optional[str] = None
+ self._lock = threading.RLock()
+ self._load_state_lock = threading.Lock()
+ self._loading = False
+ self._load_cancel_event: Optional[threading.Event] = None
+ self._keep_alive_seconds = max(0.0, keep_alive_seconds)
+ self._idle_timer: Optional[threading.Timer] = None
+ self._idle_generation = 0
+
+ @property
+ def loaded_model(self) -> Optional[str]:
+ return self._model_id
+
+ @property
+ def device(self) -> Optional[str]:
+ return self._device
+
+ def is_loading(self) -> bool:
+ with self._load_state_lock:
+ return self._loading
+
+ def cancel_pending_load(self) -> bool:
+ """Cancel a model load without waiting for the model lock."""
+ with self._load_state_lock:
+ event = self._load_cancel_event
+ if not self._loading or event is None:
+ return False
+ event.set()
+ return True
+
+ def wait_for_load_to_settle(self) -> None:
+ """Block until any in-flight load() has exited and freed its memory.
+
+ load() holds self._lock throughout, including the from_pretrained()/
+ .to(device) allocation and cancel cleanup, so acquiring the lock here
+ waits for that memory to be freed.
+ """
+ with self._lock:
+ pass
+
+ def _begin_load(self) -> threading.Event:
+ event = threading.Event()
+ with self._load_state_lock:
+ self._load_cancel_event = event
+ self._loading = True
+ return event
+
+ def _end_load(self, event: threading.Event) -> None:
+ with self._load_state_lock:
+ if self._load_cancel_event is event:
+ self._load_cancel_event = None
+ self._loading = False
+
+ @staticmethod
+ def _raise_if_load_cancelled(event: threading.Event) -> None:
+ if event.is_set():
+ raise SttLoadCancelledError("STT model loading was cancelled so training could start.")
+
+ @property
+ def keep_alive_seconds(self) -> float:
+ return self._keep_alive_seconds
+
+ def _cancel_idle_unload_locked(self) -> None:
+ self._idle_generation += 1
+ timer = self._idle_timer
+ self._idle_timer = None
+ if timer is not None:
+ timer.cancel()
+
+ def _schedule_idle_unload_locked(self) -> None:
+ self._cancel_idle_unload_locked()
+ if self._engine is None or self._keep_alive_seconds <= 0:
+ return
+ generation = self._idle_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._idle_generation or self._engine is None:
+ return
+ logger.info("Unloading idle STT model %s", self._model_id)
+ self._release_engine_locked()
+
+ def _release_engine_locked(self) -> None:
+ self._cancel_idle_unload_locked()
+ engine = self._engine
+ device = self._device
+ self._engine = None
+ self._model_id = None
+ self._device = None
+ del engine
+ _clear_device_cache(device)
+
+ def _build_model(self, snapshot_path: str, device: str, dtype, cancel_event: threading.Event):
+ """Load a Whisper model + processor from the local Hub cache.
+
+ local_files_only keeps the Model Hub the only download path; a cache
+ miss raises so the caller can surface SttModelNotDownloadedError.
+ """
+ import torch
+ from transformers import WhisperForConditionalGeneration, WhisperProcessor
+
+ processor = None
+ model = None
+ try:
+ processor = WhisperProcessor.from_pretrained(snapshot_path, local_files_only = True)
+ self._raise_if_load_cancelled(cancel_event)
+ model = WhisperForConditionalGeneration.from_pretrained(
+ snapshot_path, torch_dtype = dtype, local_files_only = True
+ )
+ self._raise_if_load_cancelled(cancel_event)
+ model.to(torch.device(device))
+ self._raise_if_load_cancelled(cancel_event)
+ model.eval()
+ return model, processor
+ except SttLoadCancelledError:
+ model = None
+ processor = None
+ _clear_device_cache(device)
+ raise
+
+ def _ensure_model_downloaded(self, model_id: str) -> _CachedSttSnapshot:
+ """Validate the local snapshot before decode or model replacement.
+
+ Returns the checkpoint's multilingual flag when local metadata provides
+ it. Curated defaults are known multilingual.
+ """
+ model_id = resolve_model_id(model_id)
+ with self._lock:
+ if self._engine is not None and self._model_id == model_id:
+ resident_model = (
+ self._engine[0] if isinstance(self._engine, (tuple, list)) else self._engine
+ )
+ generation_config = getattr(resident_model, "generation_config", None)
+ is_multilingual = getattr(generation_config, "is_multilingual", None)
+ return _CachedSttSnapshot(
+ path = None,
+ is_multilingual = is_multilingual if isinstance(is_multilingual, bool) else None,
+ )
+ snapshot_path = _find_complete_cached_snapshot(model_id)
+ if snapshot_path is None:
+ raise SttModelNotDownloadedError(
+ f"STT model '{model_id}' is not downloaded. "
+ "Download it in Settings, then Voice, before loading it."
+ )
+
+ if model_id in STT_MODELS:
+ return _CachedSttSnapshot(path = snapshot_path, is_multilingual = True)
+
+ if not _is_whisper_config(_read_json_object(snapshot_path / "config.json")):
+ raise SttModelCompatibilityError(
+ f"STT model '{model_id}' is not a compatible Transformers Whisper model."
+ )
+ generation_config = _read_json_object(snapshot_path / "generation_config.json")
+ is_multilingual = generation_config.get("is_multilingual")
+ if isinstance(is_multilingual, bool):
+ return _CachedSttSnapshot(path = snapshot_path, is_multilingual = is_multilingual)
+ if resolve_model_repo(model_id).lower().endswith(".en"):
+ return _CachedSttSnapshot(path = snapshot_path, is_multilingual = False)
+ return _CachedSttSnapshot(path = snapshot_path, is_multilingual = None)
+
+ def load(self, model: Optional[str] = None):
+ """Load (or switch to) a model, reusing it if already resident.
+
+ Returns a ``(model, processor)`` pair.
+ """
+ model_id = resolve_model_id(model)
+ with self._lock:
+ ensure_stt_available()
+ if self._engine is not None and self._model_id == model_id:
+ self._schedule_idle_unload_locked()
+ return self._engine
+ import torch
+
+ cancel_event = self._begin_load()
+ candidate = None
+ device: Optional[str] = None
+ try:
+ cached = self._ensure_model_downloaded(model_id)
+ snapshot_path = cached.path
+ if snapshot_path is None:
+ raise SttModelNotDownloadedError(
+ f"STT model '{model_id}' is not downloaded. "
+ "Download it in Settings, then Voice, before loading it."
+ )
+ self._raise_if_load_cancelled(cancel_event)
+ device, dtype = _pick_device()
+ self._release_engine_locked()
+ logger.info("Loading STT model %s (%s) on %s", model_id, snapshot_path, device)
+
+ def not_downloaded(cause: BaseException) -> SttModelNotDownloadedError:
+ return SttModelNotDownloadedError(
+ f"STT model '{model_id}' is not downloaded. "
+ "Download it in Settings, then Voice, before loading it."
+ )
+
+ retry_on_cpu = False
+ try:
+ candidate = self._build_model(str(snapshot_path), device, dtype, cancel_event)
+ self._raise_if_load_cancelled(cancel_event)
+ except SttLoadCancelledError:
+ raise
+ except Exception as exc:
+ if _is_missing_local_model_error(exc):
+ raise not_downloaded(exc) from exc
+ if device == "cpu":
+ raise
+ logger.warning("STT load on %s failed (%s); retrying on CPU", device, exc)
+ retry_on_cpu = True
+ if retry_on_cpu:
+ # Retry outside the handler: live exception state pins frames
+ # referencing the partly loaded model, so leave it before
+ # clearing the cache to release that memory.
+ _clear_device_cache(device)
+ try:
+ candidate = self._build_model(
+ str(snapshot_path),
+ "cpu",
+ torch.float32,
+ cancel_event,
+ )
+ self._raise_if_load_cancelled(cancel_event)
+ except SttLoadCancelledError:
+ raise
+ except Exception as cpu_exc:
+ if _is_missing_local_model_error(cpu_exc):
+ raise not_downloaded(cpu_exc) from cpu_exc
+ raise
+ device = "cpu"
+ with self._load_state_lock:
+ self._raise_if_load_cancelled(cancel_event)
+ self._engine = candidate
+ self._model_id = model_id
+ self._device = device
+ self._load_cancel_event = None
+ self._loading = False
+ self._schedule_idle_unload_locked()
+ logger.info("STT model %s ready on %s", model_id, device)
+ return self._engine
+ except SttLoadCancelledError:
+ candidate = None
+ self._release_engine_locked()
+ _clear_device_cache(device)
+ raise
+ finally:
+ self._end_load(cancel_event)
+
+ def _transcribe_decoded(self, model_id: str, decoded_audio, generate_kwargs: dict) -> str:
+ """Run Whisper on already-decoded 16 kHz mono PCM and return text.
+
+ Feeds a pre-decoded array so nothing here touches the Transformers audio
+ path (torchcodec/ffmpeg). Splits into 30s windows (Whisper's receptive
+ field); short clips take one pass.
+ """
+ import torch
+
+ model, processor = self.load(model_id)
+ effective_generate_kwargs = dict(generate_kwargs)
+ generation_config = getattr(model, "generation_config", None)
+ if getattr(generation_config, "is_multilingual", None) is False:
+ # English-only checkpoints fix language and task in their generation
+ # config, and Transformers rejects passing them here.
+ effective_generate_kwargs.pop("task", None)
+ effective_generate_kwargs.pop("language", None)
+ window = 30 * _TARGET_SAMPLE_RATE
+ target_dtype = getattr(model, "dtype", None)
+ parts: list[str] = []
+ with torch.no_grad():
+ for start in range(0, max(len(decoded_audio), 1), window):
+ segment = decoded_audio[start : start + window]
+ if segment.size == 0:
+ continue
+ inputs = processor(
+ segment,
+ sampling_rate = _TARGET_SAMPLE_RATE,
+ return_tensors = "pt",
+ )
+ features = inputs.input_features.to(model.device)
+ if target_dtype is not None:
+ features = features.to(target_dtype)
+ generated = model.generate(features, **effective_generate_kwargs)
+ text = processor.batch_decode(generated, skip_special_tokens = True)
+ parts.append(text[0] if text else "")
+ return " ".join(part.strip() for part in parts if part.strip()).strip()
+
+ def transcribe(
+ self,
+ audio: bytes,
+ model: Optional[str] = None,
+ language: Optional[str] = None,
+ fast: bool = False,
+ ) -> dict:
+ """Transcribe encoded audio bytes to text.
+
+ Accepts any container PyAV can decode: wav, mp3, opus/webm, ogg,
+ m4a/aac. Returns {text, language, duration, model}.
+ """
+ # Reject a missing runtime up front, before the cache and bounded decode.
+ ensure_stt_available()
+ # A set language beats auto-detect. API takes BCP-47; Whisper wants short
+ # codes like en or fr.
+ lang = normalize_whisper_language(language)
+ # Pin the requested id: another request may switch the resident model
+ # mid-transcription, so sidecar state is not this request's identity.
+ model_id = resolve_model_id(model)
+ known_languages = _known_whisper_languages()
+ if lang is not None and known_languages is not None and lang not in known_languages:
+ raise SttLanguageError(
+ f"Language '{language}' is not supported by STT model '{model_id}'."
+ )
+ cached = self._ensure_model_downloaded(model_id)
+ if cached.is_multilingual is False and lang not in (None, "en"):
+ raise SttLanguageError(
+ f"Language '{language}' is not supported by English-only STT model '{model_id}'."
+ )
+ decoded_audio = _decode_audio_bounded(audio)
+ # condition_on_prev_tokens=False stops a fresh clip inheriting prior
+ # context, which causes runaway repeats.
+ generate_kwargs = {
+ "task": "transcribe",
+ "condition_on_prev_tokens": False,
+ "num_beams": 5,
+ }
+ if lang is not None:
+ generate_kwargs["language"] = lang
+ if fast:
+ # Short voiced clips: greedy decoding drops beam search for latency.
+ generate_kwargs["num_beams"] = 1
+ # Serialize inference with model switches and unloads.
+ with self._lock:
+ try:
+ text = self._transcribe_decoded(model_id, decoded_audio, generate_kwargs)
+ finally:
+ self._schedule_idle_unload_locked()
+ duration = (len(decoded_audio) / _TARGET_SAMPLE_RATE) if len(decoded_audio) else None
+ return {
+ "text": text,
+ "language": lang,
+ "duration": duration,
+ "model": model_id,
+ }
+
+ def unload(self) -> None:
+ with self._lock:
+ self._release_engine_locked()
+
+
+_sidecar: Optional[WhisperSttSidecar] = None
+
+
+def get_stt_sidecar() -> WhisperSttSidecar:
+ global _sidecar
+ if _sidecar is None:
+ _sidecar = WhisperSttSidecar()
+ return _sidecar
diff --git a/studio/backend/core/training/training.py b/studio/backend/core/training/training.py
index 7cfa61d60f4..bfbd11a427e 100644
--- a/studio/backend/core/training/training.py
+++ b/studio/backend/core/training/training.py
@@ -754,6 +754,9 @@ class TrainingBackend:
def __init__(self):
# Subprocess state
self._proc: Optional[mp.Process] = None
+ # True from the sidecar-swap handshake until the worker is recorded, so
+ # installs and STT loads treat the startup window as active.
+ self._spawn_in_progress: bool = False
self._event_queue: Any = None
self._stop_queue: Any = None
self._pump_thread: Optional[threading.Thread] = None
diff --git a/studio/backend/hub/services/models/cache_inventory.py b/studio/backend/hub/services/models/cache_inventory.py
index 76dd2337aa3..807ec709912 100644
--- a/studio/backend/hub/services/models/cache_inventory.py
+++ b/studio/backend/hub/services/models/cache_inventory.py
@@ -517,6 +517,19 @@ def _read_json_object(path: Path) -> dict:
return {}
+def _is_whisper_model_config(config: object) -> bool:
+ if not isinstance(config, dict):
+ return False
+ model_type = config.get("model_type")
+ if isinstance(model_type, str) and model_type.strip().lower() == "whisper":
+ return True
+ architectures = config.get("architectures")
+ return isinstance(architectures, list) and any(
+ isinstance(name, str) and name == "WhisperForConditionalGeneration"
+ for name in architectures
+ )
+
+
def _read_model_card_frontmatter(path: Path) -> dict:
try:
text = path.read_text(encoding = "utf-8")
@@ -547,6 +560,8 @@ def _cached_model_local_metadata(repo_path: Path) -> dict:
result: dict = {}
config = _read_json_object(snapshot / "config.json")
+ if _is_whisper_model_config(config):
+ result["_hidden_stt"] = True
quant_method = (
config.get("quantization_config", {}).get("quant_method")
if isinstance(config.get("quantization_config"), dict)
@@ -581,6 +596,7 @@ def _scan_cached_models() -> list[dict]:
inspected = 0
skipped_gguf = 0
skipped_no_weights = 0
+ skipped_stt = 0
for hf_cache in cache_scans:
for repo_info in hf_cache.repos:
inspected += 1
@@ -608,6 +624,10 @@ def _scan_cached_models() -> list[dict]:
continue
key = repo_id.lower()
existing = seen_lower.get(key)
+ local_metadata = _cached_model_local_metadata(repo_path)
+ if local_metadata.pop("_hidden_stt", False):
+ skipped_stt += 1
+ continue
snapshot_partial = hf_cache_scan.is_snapshot_partial(
"model",
repo_id,
@@ -627,7 +647,7 @@ def _scan_cached_models() -> list[dict]:
if snapshot_partial
else None
),
- **_cached_model_local_metadata(repo_path),
+ **local_metadata,
}
last_modified = max(
payload.last_modified,
@@ -655,10 +675,12 @@ def _scan_cached_models() -> list[dict]:
continue
cached = sorted(seen_lower.values(), key = lambda c: c["repo_id"])
logger.info(
- "Cached model scan: inspected=%d skipped_gguf=%d skipped_no_weights=%d returned=%d",
+ "Cached model scan: inspected=%d skipped_gguf=%d skipped_no_weights=%d "
+ "skipped_stt=%d returned=%d",
inspected,
skipped_gguf,
skipped_no_weights,
+ skipped_stt,
len(cached),
)
return cached
diff --git a/studio/backend/main.py b/studio/backend/main.py
index 3f244dc22e1..a538f935ff1 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -309,6 +309,7 @@ from routes import (
training_router,
)
from routes.llama import router as llama_router
+from routes.whisper import router as whisper_router
from routes.preview import router as preview_router
from hub.routes import (
inventory_router as hub_inventory_router,
@@ -755,6 +756,8 @@ app.add_middleware(SecurityHeadersMiddleware)
# headroom; non-upload routes keep the default body cap.
import json as _json_for_413 # noqa: E402
from utils.upload_limits import ( # noqa: E402
+ STT_AUDIO_JSON_MAX_BYTES,
+ STT_AUDIO_RAW_MAX_BYTES,
UNSTRUCTURED_RECIPE_UPLOAD_MAX_BYTES,
default_request_body_limit_bytes,
upload_request_limit_bytes,
@@ -793,6 +796,14 @@ def _get_upload_passthrough_request_max_bytes(path: str) -> int:
return default_request_body_limit_bytes()
+def _get_request_body_max_bytes(path: str) -> int:
+ if path.startswith("/api/inference/audio/transcribe/raw"):
+ return STT_AUDIO_RAW_MAX_BYTES
+ if path.startswith("/api/inference/audio/transcribe"):
+ return STT_AUDIO_JSON_MAX_BYTES
+ return default_request_body_limit_bytes()
+
+
async def _send_411(send) -> None:
payload = _json_for_413.dumps(
{"detail": "Content-Length required for upload requests."},
@@ -835,12 +846,14 @@ class MaxBodyMiddleware:
app,
max_bytes_getter,
protected_prefixes: tuple,
+ request_max_bytes_getter = None,
upload_passthrough_prefixes: tuple = (),
upload_passthrough_max_bytes_getter = None,
):
self.app = app
self.max_bytes_getter = max_bytes_getter
self.protected_prefixes = protected_prefixes
+ self.request_max_bytes_getter = request_max_bytes_getter
self.upload_passthrough_prefixes = upload_passthrough_prefixes
self.upload_passthrough_max_bytes_getter = upload_passthrough_max_bytes_getter
@@ -857,6 +870,14 @@ class MaxBodyMiddleware:
except Exception:
return int(self.max_bytes_getter())
+ def _request_max_bytes(self, path: str) -> int:
+ if self.request_max_bytes_getter is None:
+ return int(self.max_bytes_getter())
+ try:
+ return int(self.request_max_bytes_getter(path))
+ except Exception:
+ return int(self.max_bytes_getter())
+
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
await self.app(scope, receive, send)
@@ -869,7 +890,7 @@ class MaxBodyMiddleware:
await self.app(scope, receive, send)
return
- max_bytes = int(self.max_bytes_getter())
+ max_bytes = self._request_max_bytes(path)
declared = None
for name, value in scope.get("headers", []):
if name == b"content-length":
@@ -934,6 +955,7 @@ app.add_middleware(
MaxBodyMiddleware,
max_bytes_getter = default_request_body_limit_bytes,
protected_prefixes = _BODY_PROTECTED_PREFIXES,
+ request_max_bytes_getter = _get_request_body_max_bytes,
upload_passthrough_prefixes = _BODY_UPLOAD_PASSTHROUGH_PREFIXES,
upload_passthrough_max_bytes_getter = _get_upload_passthrough_request_max_bytes,
)
@@ -992,6 +1014,7 @@ app.include_router(prompts_router, prefix = "/api/prompts", tags = ["prompts"])
app.include_router(datasets_router, prefix = "/api/datasets", tags = ["datasets"])
app.include_router(data_recipe_router, prefix = "/api/data-recipe", tags = ["data-recipe"])
app.include_router(llama_router, prefix = "/api/llama", tags = ["llama"])
+app.include_router(whisper_router, prefix = "/api/whisper", tags = ["whisper"])
app.include_router(export_router, prefix = "/api/export", tags = ["export"])
app.include_router(rag_router, prefix = "/api/rag", tags = ["rag"])
app.include_router(training_history_router, prefix = "/api/train", tags = ["training-history"])
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 580a74dddf1..c7e5ffa36bf 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -187,6 +187,32 @@ class UnloadRequest(BaseModel):
model_path: str = Field(..., description = "Model identifier to unload")
+class TranscribeRequest(BaseModel):
+ """Speech-to-text request for the dictation STT sidecar."""
+
+ audio: str = Field(..., description = "Base64-encoded audio (any common format)")
+ model: Optional[str] = Field(None, description = "STT model id; defaults server-side")
+ language: Optional[str] = Field(None, description = "BCP-47 language, or 'auto'/None to detect")
+ fast: bool = Field(
+ False,
+ description = "Use low-latency single-candidate decoding for dictation",
+ )
+ engine: Optional[str] = Field(
+ None,
+ description = "STT engine: 'transformers' (default) or 'gguf' (whisper.cpp)",
+ )
+
+
+class SttLoadRequest(BaseModel):
+ """Warm the STT sidecar with a model without transcribing."""
+
+ model: Optional[str] = Field(None, description = "STT model id; defaults server-side")
+ engine: Optional[str] = Field(
+ None,
+ description = "STT engine: 'transformers' (default) or 'gguf' (whisper.cpp)",
+ )
+
+
class ValidateModelRequest(BaseModel):
"""Check whether an identifier resolves to a ModelConfig; does NOT load weights."""
diff --git a/studio/backend/requirements/extras.txt b/studio/backend/requirements/extras.txt
index 1baf2b6f2d8..1601ccbfae3 100644
--- a/studio/backend/requirements/extras.txt
+++ b/studio/backend/requirements/extras.txt
@@ -10,6 +10,7 @@ omegaconf
einx
pyloudnorm
openai-whisper
+av # PyAV: decode dictation audio (webm/opus/mp3/…) for the Whisper STT sidecar
uroman # 4.0 MB - used for Outetts.
MeCab # 19.9 MB - used for Outetts.
inflect # number-to-words, required by OuteTTS
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 41e1fc55895..b6bbbdfb5f8 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -29,6 +29,8 @@ import re as _re
from utils.models import extract_model_size_b as _extract_model_size_b
from utils.api_errors import openai_error_body, anthropic_error_body
+from utils.upload_limits import STT_AUDIO_B64_MAX_CHARS, STT_AUDIO_RAW_MAX_BYTES
+from hub.dependencies import get_hf_token
from core.inference.orchestrator import GenStreamError, GenStreamErrorRaised
from core.inference.llama_admission import (
LlamaAdmissionCancelled,
@@ -1692,6 +1694,8 @@ async def _aiter_llama_stream_items(
from models.inference import (
LoadRequest,
UnloadRequest,
+ TranscribeRequest,
+ SttLoadRequest,
GenerateRequest,
LoadResponse,
LoadProgressResponse,
@@ -6113,6 +6117,342 @@ async def generate_audio(
)
+# =====================================================================
+# Speech-to-text (STT) sidecar (/audio/transcribe, /audio/stt/*)
+# =====================================================================
+
+
+def _resolve_stt_engine(engine: Optional[str]) -> str:
+ """Normalize the requested STT engine name; default is Transformers."""
+ normalized = (engine or "transformers").strip().lower()
+ if normalized in ("", "transformers", "whisper"):
+ return "transformers"
+ if normalized in ("gguf", "ggml", "whisper_cpp", "whisper.cpp"):
+ return "gguf"
+ raise HTTPException(
+ status_code = 422,
+ detail = f"Unknown STT engine '{engine}'. Use 'transformers' or 'gguf'.",
+ )
+
+
+def _resolve_serving_stt_engine(engine: Optional[str]) -> str:
+ """Resolve the engine that will actually serve a model.
+
+ whisper.cpp (gguf) only accepts curated ids, which Transformers serves too,
+ so when whisper-server is not installed (the common case: `unsloth studio
+ update` does not yet build it) fall back to Transformers instead of 501-ing
+ on every recording. Used for download/load/transcribe; unload targets a
+ specific engine via _resolve_stt_engine.
+ """
+ resolved = _resolve_stt_engine(engine)
+ if resolved == "gguf":
+ from core.inference import stt_ggml_sidecar
+ if not stt_ggml_sidecar.is_available():
+ return "transformers"
+ return resolved
+
+
+def _stt_sidecar_for(engine: str):
+ 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()
+
+
+@studio_router.get("/audio/stt/status")
+async def stt_status(
+ model: Optional[str] = None, current_subject: str = Depends(get_current_subject)
+):
+ """Report STT availability and which model, if any, is resident.
+
+ ``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.stt_sidecar import (
+ DEFAULT_STT_MODEL,
+ STT_MODELS,
+ get_stt_sidecar,
+ is_available,
+ )
+
+ sidecar = get_stt_sidecar()
+ ggml = stt_ggml_sidecar.get_ggml_stt_sidecar()
+ transformers_downloaded = [
+ model_id for model_id in STT_MODELS if stt_sidecar.is_model_downloaded(model_id)
+ ]
+ if model and model not in STT_MODELS and stt_sidecar.is_model_downloaded(model):
+ transformers_downloaded.append(model)
+ return JSONResponse(
+ content = {
+ "available": is_available(),
+ "loaded_model": sidecar.loaded_model,
+ "loading": sidecar.is_loading(),
+ "device": sidecar.device,
+ "keep_alive_seconds": sidecar.keep_alive_seconds,
+ "default_model": DEFAULT_STT_MODEL,
+ "models": list(STT_MODELS.keys()),
+ # Transformers engine, same shape as "gguf" below so clients read
+ # either generically. Top-level fields above kept for old clients.
+ "transformers": {
+ "available": is_available(),
+ "loaded_model": sidecar.loaded_model,
+ "loading": sidecar.is_loading(),
+ "device": sidecar.device,
+ "keep_alive_seconds": sidecar.keep_alive_seconds,
+ "default_model": DEFAULT_STT_MODEL,
+ "models": list(STT_MODELS.keys()),
+ "downloaded_models": transformers_downloaded,
+ "download": stt_sidecar.download_status(),
+ },
+ # whisper.cpp (GGUF) engine.
+ "gguf": {
+ "available": stt_ggml_sidecar.is_available(),
+ "loaded_model": ggml.loaded_model,
+ "loading": ggml.is_loading(),
+ "device": ggml.device,
+ "keep_alive_seconds": ggml.keep_alive_seconds,
+ "default_model": stt_ggml_sidecar.DEFAULT_GGML_STT_MODEL,
+ "models": list(stt_ggml_sidecar.GGML_STT_MODELS.keys()),
+ "downloaded_models": [
+ model_id
+ for model_id in stt_ggml_sidecar.GGML_STT_MODELS
+ if stt_ggml_sidecar._cached_model_path(model_id) is not None
+ ],
+ "download": stt_ggml_sidecar.download_status(),
+ },
+ }
+ )
+
+
+@studio_router.post("/audio/stt/download")
+async def stt_download(
+ payload: SttLoadRequest,
+ current_subject: str = Depends(get_current_subject),
+ hf_token: Optional[str] = Depends(get_hf_token),
+):
+ """Start a background download of a dictation model.
+
+ Both engines download directly (a GGML checkpoint is a single file the Model
+ Hub's GGUF variant planner cannot express; a Transformers checkpoint is a
+ whole snapshot). Progress is reported by /audio/stt/status.
+ """
+ from core.inference import stt_ggml_sidecar, stt_sidecar
+ from core.inference.stt_sidecar import (
+ SttModelCompatibilityError,
+ SttModelIdError,
+ validate_remote_model,
+ )
+
+ engine = _resolve_serving_stt_engine(payload.engine)
+ module = stt_ggml_sidecar if engine == "gguf" else stt_sidecar
+ 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":
+ 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.
+ await asyncio.to_thread(
+ module.start_model_download,
+ payload.model,
+ hf_token,
+ validated.get("revision"),
+ )
+ else:
+ await asyncio.to_thread(module.start_model_download, payload.model, hf_token)
+ except SttModelIdError as e:
+ raise HTTPException(status_code = 422, detail = str(e))
+ except SttModelCompatibilityError as e:
+ raise HTTPException(status_code = 422, detail = str(e))
+ return JSONResponse(content = module.download_status())
+
+
+@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,
+ SttModelCompatibilityError,
+ SttModelIdError,
+ SttModelNotDownloadedError,
+ SttUnavailableError,
+ get_stt_sidecar,
+ )
+
+ sidecar = _stt_sidecar_for(_resolve_serving_stt_engine(payload.engine))
+ try:
+ await asyncio.to_thread(sidecar.load, payload.model)
+ 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 SttModelIdError as e:
+ raise HTTPException(status_code = 422, detail = str(e))
+ except SttModelCompatibilityError as e:
+ raise HTTPException(status_code = 422, detail = str(e))
+ except Exception as e:
+ logger.error(f"STT load error: {e}", exc_info = True)
+ raise HTTPException(status_code = 500, detail = safe_error_detail(e))
+ return JSONResponse(content = {"loaded_model": sidecar.loaded_model, "device": sidecar.device})
+
+
+@studio_router.post("/audio/stt/validate")
+async def stt_validate(
+ payload: SttLoadRequest,
+ current_subject: str = Depends(get_current_subject),
+ hf_token: Optional[str] = Depends(get_hf_token),
+):
+ """Verify a Hub repository is a Whisper checkpoint before downloading it."""
+ from core.inference.stt_sidecar import (
+ SttModelCompatibilityError,
+ SttModelIdError,
+ validate_remote_model,
+ )
+
+ try:
+ result = await asyncio.to_thread(validate_remote_model, payload.model, hf_token)
+ except (SttModelIdError, SttModelCompatibilityError) as e:
+ raise HTTPException(status_code = 422, detail = str(e))
+ return JSONResponse(content = result)
+
+
+@studio_router.post("/audio/stt/unload")
+async def stt_unload(
+ engine: Optional[str] = None, current_subject: str = Depends(get_current_subject)
+):
+ """Release the local STT model when dictation is idle.
+
+ Without an engine, both sidecars unload so an engine switch in Voice
+ settings always frees whichever backend was resident.
+ """
+ if engine is None:
+ engines = ["transformers", "gguf"]
+ 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)
+ if failed:
+ raise HTTPException(
+ status_code = 500,
+ detail = f"Failed to unload STT engine(s): {', '.join(failed)}",
+ )
+ return JSONResponse(content = {"loaded_model": None, "device": None})
+
+
+async def _transcribe_audio_bytes(
+ raw: bytes,
+ model: Optional[str],
+ language: Optional[str],
+ fast: bool,
+ engine: Optional[str] = None,
+) -> JSONResponse:
+ """Run STT for already-decoded request bytes."""
+ from core.inference.stt_sidecar import (
+ SttAudioDecodeError,
+ SttAudioTooLongError,
+ SttLanguageError,
+ SttLoadCancelledError,
+ SttModelCompatibilityError,
+ SttModelIdError,
+ SttModelNotDownloadedError,
+ SttUnavailableError,
+ )
+
+ if not raw:
+ raise HTTPException(status_code = 400, detail = "Audio is empty.")
+ if len(raw) > _MAX_AUDIO_RAW_BYTES:
+ raise HTTPException(status_code = 413, detail = "Audio is too large.")
+
+ sidecar = _stt_sidecar_for(_resolve_serving_stt_engine(engine))
+ try:
+ result = await asyncio.to_thread(
+ sidecar.transcribe,
+ raw,
+ model,
+ language,
+ fast,
+ )
+ 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 SttModelNotDownloadedError 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:
+ raise HTTPException(status_code = 422, detail = str(e))
+ except SttLanguageError as e:
+ raise HTTPException(status_code = 422, detail = str(e))
+ except SttAudioTooLongError as e:
+ raise HTTPException(status_code = 413, detail = str(e))
+ except SttAudioDecodeError as e:
+ raise HTTPException(status_code = 400, detail = str(e))
+ except Exception as e:
+ logger.error(f"Transcription error: {e}", exc_info = True)
+ raise HTTPException(status_code = 500, detail = safe_error_detail(e))
+ return JSONResponse(content = result)
+
+
+@studio_router.post("/audio/transcribe")
+async def transcribe_audio(
+ payload: TranscribeRequest, current_subject: str = Depends(get_current_subject)
+):
+ """Transcribe dictation audio to text via the STT sidecar.
+
+ Runs alongside the chat model without evicting it, so any model (including
+ text-only ones) can be driven by voice.
+ """
+ b64 = payload.audio or ""
+ if not b64:
+ raise HTTPException(status_code = 400, detail = "No audio provided.")
+ if len(b64) > _MAX_AUDIO_B64_CHARS:
+ raise HTTPException(status_code = 413, detail = "Audio is too large.")
+ try:
+ raw = base64.b64decode(b64, validate = True)
+ except Exception:
+ raise HTTPException(status_code = 400, detail = "Audio is not valid base64.")
+ return await _transcribe_audio_bytes(
+ raw, payload.model, payload.language, payload.fast, payload.engine
+ )
+
+
+@studio_router.post("/audio/transcribe/raw")
+async def transcribe_audio_raw(
+ request: Request,
+ model: Optional[str] = None,
+ language: Optional[str] = None,
+ fast: bool = False,
+ engine: Optional[str] = None,
+ current_subject: str = Depends(get_current_subject),
+):
+ """Transcribe a raw audio body without base64 or JSON conversion overhead."""
+ chunks: list[bytes] = []
+ size = 0
+ async for chunk in request.stream():
+ size += len(chunk)
+ if size > _MAX_AUDIO_RAW_BYTES:
+ raise HTTPException(status_code = 413, detail = "Audio is too large.")
+ chunks.append(chunk)
+ return await _transcribe_audio_bytes(b"".join(chunks), model, language, fast, engine)
+
+
# =====================================================================
# OpenAI-Compatible Chat Completions (/chat/completions)
# =====================================================================
@@ -6154,8 +6494,8 @@ def _decode_audio_base64(b64: str) -> np.ndarray:
# cap the encoded length to bound the upload. _MAX_AUDIO_SECONDS additionally
# bounds the *decoded* length, since a small compressed file (opus/flac/etc.)
# can expand to a far larger PCM array than the encoded-size cap implies.
-_MAX_AUDIO_RAW_BYTES = 25 * 1024 * 1024
-_MAX_AUDIO_B64_CHARS = _MAX_AUDIO_RAW_BYTES * 4 // 3
+_MAX_AUDIO_RAW_BYTES = STT_AUDIO_RAW_MAX_BYTES
+_MAX_AUDIO_B64_CHARS = STT_AUDIO_B64_MAX_CHARS
_MAX_AUDIO_SECONDS = 30 * 60
_WAV_HEADER_BYTES = 44
_MIN_TRANSCODE_AUDIO_SAMPLE_RATE = 8000
diff --git a/studio/backend/routes/llama.py b/studio/backend/routes/llama.py
index 540647e3bc5..84b89ad7d5f 100644
--- a/studio/backend/routes/llama.py
+++ b/studio/backend/routes/llama.py
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""llama.cpp prebuilt update endpoints.
+"""llama.cpp prebuilt update endpoints -- the single main update item.
GET /api/llama/update-status -> is a newer prebuilt available + job state
POST /api/llama/update -> download + atomically swap to the latest
@@ -9,13 +9,19 @@ POST /api/llama/update -> download + atomically swap to the latest
Detection reuses utils.llama_cpp_freshness; the swap reuses
install_llama_prebuilt.py via utils.llama_cpp_update. Both fail open so the UI
never blocks on a missing marker / offline GitHub.
+
+whisper.cpp updates piggyback here: the status payload carries a whisper
+sub-status (update_available is the llama OR whisper union) and the apply job
+chains a whisper phase after the llama phase when whisper is behind, with a
+per-phase breakdown in job.phases. All pre-existing top-level fields keep
+their shape, so older clients keep working unchanged.
"""
from __future__ import annotations
import asyncio
import threading
-from typing import Optional
+from typing import Literal, Optional
from fastapi import APIRouter, Depends, Query
from pydantic import BaseModel, Field
@@ -38,6 +44,31 @@ class LlamaUpdateJob(BaseModel):
progress: Optional[float] = Field(None, description = "0..1 while running, 1 on success.")
started_at: Optional[str] = None
finished_at: Optional[str] = None
+ phases: Optional[dict] = Field(
+ None,
+ description = (
+ "Per-phase breakdown of a chained llama+whisper job "
+ "(name -> state/progress/to_tag/...); None for pre-chaining jobs."
+ ),
+ )
+
+
+class WhisperSubStatus(BaseModel):
+ """The whisper piggyback inside the llama update item."""
+
+ update_available: bool = Field(
+ False, description = "True when the chained apply would run a whisper phase."
+ )
+ installed_tag: Optional[str] = None
+ latest_tag: Optional[str] = None
+ update_size_bytes: Optional[int] = None
+ skip_reason: Optional[str] = Field(
+ None,
+ description = (
+ "Why the whisper phase would be skipped "
+ "(up_to_date | local_link | source_build | not_installed | ...)."
+ ),
+ )
class LlamaUpdateStatusResponse(BaseModel):
@@ -46,7 +77,18 @@ class LlamaUpdateStatusResponse(BaseModel):
description = "True when the install came from an Unsloth prebuilt (has a marker).",
)
update_available: bool = Field(
- False, description = "True when the latest release is genuinely newer than the install."
+ False,
+ description = (
+ "True when an update would do something: llama.cpp is behind OR the "
+ "whisper piggyback is behind."
+ ),
+ )
+ llama_update_available: bool = Field(
+ False, description = "True when the latest llama.cpp release is newer than the install."
+ )
+ update_component: Optional[Literal["llama", "whisper"]] = Field(
+ None,
+ description = "Component whose versions the combined update banner should display.",
)
stale: bool = Field(
False, description = "Update available AND install older than the staleness threshold."
@@ -62,6 +104,9 @@ class LlamaUpdateStatusResponse(BaseModel):
update_size_bytes: Optional[int] = Field(
None, description = "Download size of the prebuilt Update would fetch, in bytes."
)
+ whisper: Optional[WhisperSubStatus] = Field(
+ None, description = "Whisper piggyback sub-status; None when the probe is unavailable."
+ )
job: LlamaUpdateJob = Field(default_factory = LlamaUpdateJob)
diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.py
index c225483acf4..3c0d6ff4ba4 100644
--- a/studio/backend/routes/models.py
+++ b/studio/backend/routes/models.py
@@ -3026,7 +3026,9 @@ async def list_cached_gguf(current_subject: str = Depends(get_current_subject)):
if repo_info.repo_type != "model":
continue
repo_id = repo_info.repo_id
- if _is_hidden_model(repo_id):
+ # Pass the snapshot path too so the config check also hides
+ # custom Whisper checkpoints, not just curated repo ids.
+ if _is_hidden_model(repo_id, str(repo_info.repo_path)):
continue
total_size = _repo_gguf_size_bytes(repo_info)
if total_size == 0:
@@ -3083,7 +3085,9 @@ async def list_cached_models(
if repo_info.repo_type != "model":
continue
repo_id = repo_info.repo_id
- if _is_hidden_model(repo_id):
+ # Pass the snapshot path too so the config check also hides
+ # custom Whisper checkpoints, not just curated repo ids.
+ if _is_hidden_model(repo_id, str(repo_info.repo_path)):
continue
if _repo_has_gguf_files(repo_info):
continue
diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.py
index 9176f1a8dae..5b10652fdd8 100644
--- a/studio/backend/routes/training.py
+++ b/studio/backend/routes/training.py
@@ -415,46 +415,29 @@ async def start_training(
try:
from routes.training_vram import (
can_keep_chat_during_training,
- free_chat_models_for_training,
- summarize_resident_chat,
+ coordinate_models_for_training,
)
- resident = summarize_resident_chat()
- if not resident["any"]:
- return
- if resident.get("loading"):
- # In-flight load can't be sized -> free rather than risk OOM.
- freed = free_chat_models_for_training(reason = "chat model still loading")
- logger.info("Freed in-flight chat load for training: %s", freed)
- return
- keep, info = can_keep_chat_during_training(
- model_name = training_kwargs["model_name"],
- hf_token = training_kwargs["hf_token"],
- training_type = training_kwargs["training_type"],
- load_in_4bit = training_kwargs["load_in_4bit"],
- batch_size = training_kwargs["batch_size"],
- max_seq_length = training_kwargs["max_seq_length"],
- lora_rank = training_kwargs["lora_r"],
- target_modules = training_kwargs["target_modules"],
- gradient_checkpointing = training_kwargs["gradient_checkpointing"],
- optimizer = training_kwargs["optim"],
- gpu_ids = training_kwargs["gpu_ids"],
- )
- if keep:
- logger.info(
- "Keeping chat model(s) loaded during training "
- "(free ~%s GB, needs ~%s GB): %s",
- info.get("usable_gb"),
- info.get("required_gb"),
- resident,
- )
- else:
- freed = free_chat_models_for_training(
- reason = "insufficient VRAM to run training alongside chat",
+ def _can_keep_resident_models():
+ return can_keep_chat_during_training(
+ model_name = training_kwargs["model_name"],
+ hf_token = training_kwargs["hf_token"],
+ training_type = training_kwargs["training_type"],
+ load_in_4bit = training_kwargs["load_in_4bit"],
+ batch_size = training_kwargs["batch_size"],
+ max_seq_length = training_kwargs["max_seq_length"],
+ lora_rank = training_kwargs["lora_r"],
+ target_modules = training_kwargs["target_modules"],
+ gradient_checkpointing = training_kwargs["gradient_checkpointing"],
+ optimizer = training_kwargs["optim"],
+ gpu_ids = training_kwargs["gpu_ids"],
)
- logger.info("Freed chat model(s) for training: %s", freed)
+
+ freed = coordinate_models_for_training(_can_keep_resident_models)
+ if freed:
+ logger.info("Freed models for training: %s", freed)
except Exception as e:
- logger.warning("Chat/training VRAM coordination failed; proceeding: %s", e)
+ logger.warning("Inference/training memory coordination failed; proceeding: %s", e)
# The hook runs only once start guards pass -> VRAM freed iff training starts.
from utils.transformers_version import SidecarSwapInProgress
diff --git a/studio/backend/routes/training_vram.py b/studio/backend/routes/training_vram.py
index fd96fe21759..83bce8b7721 100644
--- a/studio/backend/routes/training_vram.py
+++ b/studio/backend/routes/training_vram.py
@@ -1,15 +1,13 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""VRAM coordination between chat/inference and training.
+"""Memory coordination between inference and training.
-Decides, from live free VRAM, whether a resident chat model can stay loaded
-during training or must be unloaded, and unloads it across all backends
-(HF/MLX orchestrator + llama.cpp GGUF server). In the route layer because the
-GGUF accessor lives in routes/inference.py; backends are imported lazily.
+Uses live free VRAM to keep resident chat and STT models when they fit. STT is
+evicted before chat when training needs memory.
"""
-from typing import Any, Dict, List, Optional, Tuple
+from typing import Any, Callable, Dict, List, Optional, Tuple
from loggers import get_logger
@@ -77,6 +75,37 @@ def summarize_resident_chat() -> Dict[str, Any]:
}
+def summarize_resident_stt() -> Dict[str, Any]:
+ """Report the resident dictation model (either engine). Never raises."""
+ try:
+ from core.inference.stt_ggml_sidecar import get_ggml_stt_sidecar
+ from core.inference.stt_sidecar import get_stt_sidecar
+
+ sidecar = get_stt_sidecar()
+ model = sidecar.loaded_model
+ device = sidecar.device
+ loading = sidecar.is_loading()
+ # whisper.cpp holds GPU memory via its subprocess, and both engines can be
+ # live at once (engine switch or direct /audio/stt/load). Always fold the
+ # GGUF sidecar in: a resident Transformers model must not mask a GGUF
+ # server still binding its backend, or admission lets training launch into
+ # that startup and OOM.
+ ggml = get_ggml_stt_sidecar()
+ if not model:
+ 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}
+
+
def can_keep_chat_during_training(
*,
model_name: str,
@@ -366,3 +395,110 @@ def free_chat_models_for_training(reason: str) -> List[str]:
logger.warning("Could not unload GGUF chat model: %s", e)
return freed
+
+
+def free_stt_model_for_training(reason: str) -> List[str]:
+ """Unload the dictation model(s) before training. Never raises.
+
+ The Transformers and GGUF sidecars are freed under independent exception
+ boundaries so a failure unloading one backend never skips freeing the other
+ (both can hold accelerator memory at once after an engine switch).
+ """
+ freed: List[str] = []
+ try:
+ from core.inference.stt_sidecar import get_stt_sidecar
+ sidecar = get_stt_sidecar()
+ if sidecar.is_loading() and sidecar.cancel_pending_load():
+ logger.info("Cancelling STT model load for training (%s)", reason)
+ # The loader may still be in from_pretrained()/.to(device) holding
+ # VRAM; wait for it to observe the cancel and release first.
+ sidecar.wait_for_load_to_settle()
+ # A load that finished before seeing the cancel leaves a resident
+ # model; unload it so training gets the memory back.
+ if sidecar.loaded_model:
+ sidecar.unload()
+ freed.append("stt:loading")
+ else:
+ model = sidecar.loaded_model
+ if model:
+ logger.info("Unloading STT model '%s' for training (%s)", model, reason)
+ sidecar.unload()
+ freed.append(f"stt:{model}")
+ except Exception as e:
+ logger.warning("Could not unload Transformers STT model: %s", e)
+
+ # Check the GGUF sidecar even after a cancelled/failed Transformers unload;
+ # both engines can hold memory at once (engine switch or direct load).
+ try:
+ from core.inference.stt_ggml_sidecar import get_ggml_stt_sidecar
+ ggml = get_ggml_stt_sidecar()
+ if ggml.is_loading() and ggml.cancel_pending_load():
+ logger.info("Cancelling GGUF STT model load for training (%s)", reason)
+ # whisper-server may still be binding its backend; wait for the
+ # cancelled startup to be killed and reaped before training claims
+ # the memory (loaded_model stays unset until it is ready).
+ ggml.wait_for_load_to_settle()
+ if ggml.loaded_model:
+ ggml.unload()
+ freed.append("stt:gguf-loading")
+ else:
+ ggml_model = ggml.loaded_model
+ if ggml_model:
+ logger.info("Unloading GGUF STT model '%s' for training (%s)", ggml_model, reason)
+ ggml.unload()
+ freed.append(f"stt:{ggml_model}")
+ except Exception as e:
+ logger.warning("Could not unload GGUF STT model: %s", e)
+
+ return freed
+
+
+def coordinate_models_for_training(
+ can_keep: Callable[[], Tuple[bool, Dict[str, Any]]],
+) -> List[str]:
+ """Keep resident models when they fit, evicting STT before chat."""
+ resident_chat = summarize_resident_chat()
+ resident_stt = summarize_resident_stt()
+ if not resident_chat["any"] and not resident_stt["any"]:
+ return []
+
+ if resident_chat.get("loading"):
+ freed = free_stt_model_for_training(reason = "chat model still loading")
+ freed += free_chat_models_for_training(reason = "chat model still loading")
+ return freed
+
+ freed: List[str] = []
+ if resident_stt.get("loading"):
+ released_stt = free_stt_model_for_training(reason = "STT model still loading")
+ freed += released_stt
+ resident_stt = (
+ {"model": None, "device": None, "loading": False, "any": False}
+ if released_stt
+ else summarize_resident_stt()
+ )
+ if not resident_chat["any"] and not resident_stt["any"]:
+ return freed
+
+ keep, info = can_keep()
+ if keep:
+ logger.info(
+ "Keeping resident models loaded during training (free ~%s GB, needs ~%s GB): %s",
+ info.get("usable_gb"),
+ info.get("required_gb"),
+ {"chat": resident_chat, "stt": resident_stt},
+ )
+ return freed
+
+ if resident_stt["any"]:
+ freed += free_stt_model_for_training(reason = "insufficient training memory")
+ if not resident_chat["any"]:
+ return freed
+ keep, _info = can_keep()
+ if keep:
+ logger.info("Keeping chat model loaded after freeing STT: %s", resident_chat)
+ return freed
+
+ freed += free_chat_models_for_training(
+ reason = "insufficient VRAM to run training alongside chat",
+ )
+ return freed
diff --git a/studio/backend/routes/whisper.py b/studio/backend/routes/whisper.py
new file mode 100644
index 00000000000..08a8f269ec7
--- /dev/null
+++ b/studio/backend/routes/whisper.py
@@ -0,0 +1,74 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""whisper.cpp prebuilt status endpoint.
+
+GET /api/whisper/update-status -> is a newer prebuilt available + job state
+
+Detection reuses utils.whisper_cpp_freshness and fails open so the UI never
+blocks on a missing marker / offline GitHub. There is no whisper-only update
+trigger: whisper updates piggyback on the single main update item
+(POST /api/llama/update chains a whisper phase when whisper is behind).
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Optional
+
+from fastapi import APIRouter, Depends, Query
+from pydantic import BaseModel, Field
+
+from auth.authentication import get_current_subject
+from utils.whisper_cpp_update import get_update_status
+
+router = APIRouter()
+
+
+class WhisperUpdateJob(BaseModel):
+ state: str = Field("idle", description = "idle | running | success | error")
+ message: str = ""
+ from_tag: Optional[str] = None
+ to_tag: Optional[str] = None
+ reload_required: Optional[bool] = None
+ error: Optional[str] = None
+ progress: Optional[float] = Field(None, description = "0..1 while running, 1 on success.")
+ started_at: Optional[str] = None
+ finished_at: Optional[str] = None
+
+
+class WhisperUpdateStatusResponse(BaseModel):
+ supported: bool = Field(
+ False,
+ description = "True when the install came from an Unsloth prebuilt (has a marker).",
+ )
+ update_available: bool = Field(
+ False, description = "True when the latest release is genuinely newer than the install."
+ )
+ stale: bool = Field(
+ False, description = "Update available AND install older than the staleness threshold."
+ )
+ installed_tag: Optional[str] = None
+ latest_tag: Optional[str] = None
+ published_repo: Optional[str] = None
+ installed_at_utc: Optional[str] = None
+ age_days: Optional[int] = None
+ source_build: bool = Field(
+ False, description = "True when there is no marker (source build) but a prebuilt is offered."
+ )
+ update_size_bytes: Optional[int] = Field(
+ None, description = "Download size of the prebuilt an update would fetch, in bytes."
+ )
+ job: WhisperUpdateJob = Field(default_factory = WhisperUpdateJob)
+
+
[email protected]("/update-status", response_model = WhisperUpdateStatusResponse)
+async def whisper_update_status(
+ force_refresh: bool = Query(
+ False, description = "Bypass the 24h release cache for an explicit check."
+ ),
+ current_subject: str = Depends(get_current_subject),
+) -> WhisperUpdateStatusResponse:
+ # Off the event loop: detection may probe the host and read GitHub.
+ status = await asyncio.to_thread(get_update_status, force_refresh = force_refresh)
+ return WhisperUpdateStatusResponse(**status)
diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.py
index 8ee72259f41..6f2c6720023 100644
--- a/studio/backend/tests/test_cached_gguf_routes.py
+++ b/studio/backend/tests/test_cached_gguf_routes.py
@@ -191,6 +191,72 @@ def test_is_hidden_model_hides_validation_probe_everywhere():
assert not models_route._is_hidden_model("user/stories260K-finetune-GGUF")
+def test_is_hidden_model_hides_dictation_models(tmp_path):
+ assert models_route._is_hidden_model("unsloth/whisper-tiny")
+ assert models_route._is_hidden_model("unsloth/whisper-base")
+ assert models_route._is_hidden_model("unsloth/whisper-small")
+ assert models_route._is_hidden_model("unsloth/whisper-large-v3-turbo")
+ assert models_route._is_hidden_model(
+ "/hf/models--unsloth--whisper-large-v3/snapshots/abc/model.safetensors"
+ )
+ assert not models_route._is_hidden_model("user/whisper-finetune")
+ assert not models_route._is_hidden_model(
+ "C:\\cache\\models--unsloth--whisper-small-finetune\\model.safetensors"
+ )
+ custom = tmp_path / "custom-whisper"
+ custom.mkdir()
+ (custom / "config.json").write_text(
+ '{"model_type": "whisper", "architectures": ["WhisperForConditionalGeneration"]}'
+ )
+ (custom / "model.safetensors").write_bytes(b"weights")
+ assert models_route._is_hidden_model(
+ "user/custom-checkpoint",
+ str(custom / "model.safetensors"),
+ )
+ named_only = tmp_path / "whisper-finetune"
+ named_only.mkdir()
+ (named_only / "config.json").write_text('{"model_type": "llama"}')
+ assert not models_route._is_hidden_model("user/whisper-finetune", str(named_only))
+
+
+def test_list_cached_models_hides_custom_whisper_by_config(monkeypatch, tmp_path):
+ # Regression: the legacy /cached-models picker must pass the snapshot path so
+ # the config check hides a custom (non-curated) Whisper checkpoint; a bare
+ # repo id cannot ("user/whisper-finetune" is not in the curated set).
+ repo_path = tmp_path / "models--user--whisper-finetune"
+ snap = repo_path / "snapshots" / "abc"
+ snap.mkdir(parents = True)
+ (snap / "config.json").write_text(
+ '{"model_type": "whisper", "architectures": ["WhisperForConditionalGeneration"]}'
+ )
+ (snap / "model.safetensors").write_bytes(b"weights")
+
+ captured: list = []
+ real_hidden = models_route._is_hidden_model
+
+ def spy(*values):
+ captured.append(values)
+ return real_hidden(*values)
+
+ monkeypatch.setattr(models_route, "_is_hidden_model", spy)
+ repo = _repo(
+ "user/whisper-finetune",
+ [SimpleNamespace(file_name = "model.safetensors", size_on_disk = 10)],
+ repo_path,
+ )
+ monkeypatch.setattr(
+ models_route, "_all_hf_cache_scans", lambda: [SimpleNamespace(repos = [repo])]
+ )
+
+ result = asyncio.run(
+ models_route.list_cached_models(current_subject = "test-user", hf_token = None)
+ )
+ # The route passed the snapshot path (not just the repo id) ...
+ assert any(str(repo_path) in values for values in captured)
+ # ... so the custom Whisper checkpoint is hidden from the chat picker.
+ assert result["cached"] == []
+
+
def test_is_hidden_model_matches_repo_ids_exactly(monkeypatch):
"""A custom embedder with a generic basename is hidden by EXACT repo-id
match only, so unrelated cached repos that merely contain the basename stay
diff --git a/studio/backend/tests/test_combined_update.py b/studio/backend/tests/test_combined_update.py
new file mode 100644
index 00000000000..b96d3d030c7
--- /dev/null
+++ b/studio/backend/tests/test_combined_update.py
@@ -0,0 +1,735 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Hermetic tests for the combined llama+whisper update item.
+
+llama.cpp is the single main update item; whisper.cpp piggybacks on it. These
+pin the union status (update_available = llama behind OR whisper behind), the
+chained apply (llama phase first, whisper phase only when behind), the failure
+policy (llama failure aborts; whisper failure keeps the llama partial success),
+the silent whisper skips, and the backward-compatible payload shape.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+import time
+from pathlib import Path
+
+import pytest
+
+_BACKEND = Path(__file__).resolve().parents[1]
+if str(_BACKEND) not in sys.path:
+ sys.path.insert(0, str(_BACKEND))
+
+import utils.llama_cpp_freshness as freshness # noqa: E402
+import utils.llama_cpp_update as upd # noqa: E402
+import utils.whisper_cpp_freshness as wfresh # noqa: E402
+import utils.whisper_cpp_update as wupd # noqa: E402
+
+MARKER = "UNSLOTH_PREBUILT_INFO.json"
+WHISPER_MARKER = "UNSLOTH_WHISPER_PREBUILT_INFO.json"
+
+# The top-level status and job fields that predate the whisper piggyback; the
+# combined payload must stay an exact superset so current UI code keeps working.
+LEGACY_STATUS_FIELDS = {
+ "supported",
+ "update_available",
+ "stale",
+ "installed_tag",
+ "latest_tag",
+ "published_repo",
+ "installed_at_utc",
+ "age_days",
+ "source_build",
+ "update_size_bytes",
+ "job",
+}
+LEGACY_JOB_FIELDS = {
+ "state",
+ "message",
+ "from_tag",
+ "to_tag",
+ "reload_required",
+ "error",
+ "progress",
+ "started_at",
+ "finished_at",
+}
+
+
+class _FakeInstallerPopen:
+ """Stands in for the streamed llama installer process."""
+
+ def __init__(
+ self,
+ cmd,
+ *,
+ returncode = 0,
+ lines = None,
+ on_start = None,
+ **kwargs,
+ ):
+ if on_start is not None:
+ on_start(list(cmd))
+ self.returncode = returncode
+ self.stdout = iter(lines or [])
+
+ def wait(self):
+ return self.returncode
+
+ def kill(self):
+ pass
+
+
+def _patch_llama_installer(
+ monkeypatch,
+ *,
+ returncode = 0,
+ lines = None,
+ on_start = None,
+):
+ # Only intercept the installer invocation: importing routes.inference inside
+ # the worker can Popen unrelated host probes (ldconfig etc).
+ def _popen(cmd, **kw):
+ is_installer = any("install_llama_prebuilt" in str(part) for part in cmd)
+ return _FakeInstallerPopen(
+ cmd,
+ returncode = returncode if is_installer else 0,
+ lines = lines if is_installer else None,
+ on_start = on_start if is_installer else None,
+ )
+
+ monkeypatch.setattr(upd.subprocess, "Popen", _popen)
+
+
+def _write_llama_install(dir_: Path, tag: str) -> str:
+ """Create a fake llama prebuilt install and return the llama-server path."""
+ bin_dir = dir_ / "build" / "bin"
+ bin_dir.mkdir(parents = True, exist_ok = True)
+ binary = bin_dir / "llama-server"
+ binary.write_text("stub")
+ (dir_ / MARKER).write_text(
+ json.dumps(
+ {
+ "tag": tag,
+ "release_tag": tag,
+ "published_repo": "unslothai/llama.cpp",
+ "installed_at_utc": "2020-01-01T00:00:00Z",
+ }
+ )
+ )
+ return str(binary)
+
+
+def _write_whisper_install(
+ dir_: Path,
+ tag: str,
+ backend: str = "cpu",
+) -> str:
+ """Create a fake whisper prebuilt install and return the whisper-server path."""
+ bin_dir = dir_ / "build" / "bin"
+ bin_dir.mkdir(parents = True, exist_ok = True)
+ binary = bin_dir / "whisper-server"
+ binary.write_text("stub")
+ (dir_ / WHISPER_MARKER).write_text(
+ json.dumps(
+ {
+ "release_tag": tag,
+ "upstream_tag": tag.split("-")[0],
+ "published_repo": "unslothai/whisper.cpp",
+ "backend": backend,
+ "installed_at_utc": "2020-01-01T00:00:00Z",
+ }
+ )
+ )
+ return str(binary)
+
+
[email protected](autouse = True)
+def _clean_state(monkeypatch, tmp_path):
+ freshness.reset_caches()
+ wfresh.reset_caches()
+ upd._reset_job_for_tests()
+ upd._resolve_memo.clear()
+ wupd._resolve_memo.clear()
+ monkeypatch.setattr(freshness, "_cache_dir", lambda: tmp_path / ".llama_cache")
+ monkeypatch.setattr(wfresh, "_cache_dir", lambda: tmp_path / ".whisper_cache")
+ for var in (
+ "LLAMA_SERVER_PATH",
+ "UNSLOTH_LLAMA_CPP_PATH",
+ "WHISPER_SERVER_PATH",
+ "UNSLOTH_WHISPER_CPP_PATH",
+ ):
+ monkeypatch.delenv(var, raising = False)
+ # Never hit the network in these tests.
+ monkeypatch.setattr(freshness, "_fetch_latest_release_tag", lambda repo, timeout = 5.0: None)
+ monkeypatch.setattr(wfresh, "_fetch_latest_release_tag", lambda repo, timeout = 5.0: None)
+ yield
+ freshness.reset_caches()
+ wfresh.reset_caches()
+ upd._reset_job_for_tests()
+ upd._resolve_memo.clear()
+ wupd._resolve_memo.clear()
+
+
+def _setup_llama(
+ monkeypatch,
+ tmp_path,
+ *,
+ installed = "b9493",
+ latest = "b9518",
+):
+ """Marker-managed llama install; behind when installed != latest."""
+ install_dir = tmp_path / "llama.cpp"
+ binary = _write_llama_install(install_dir, installed)
+ monkeypatch.setattr(upd, "_find_binary", lambda: binary)
+ monkeypatch.setattr(upd, "_installer_script", lambda: tmp_path / "install_llama_prebuilt.py")
+ monkeypatch.setattr(freshness, "_fetch_latest_release_tag", lambda repo, timeout = 5.0: latest)
+ return install_dir
+
+
+def _setup_whisper(
+ monkeypatch,
+ tmp_path,
+ *,
+ installed = "v1.9.1-unsloth.1",
+ latest = "v1.9.2-unsloth.1",
+):
+ """Marker-managed whisper install; behind when latest is newer."""
+ install_dir = tmp_path / "whisper.cpp"
+ binary = _write_whisper_install(install_dir, installed)
+ monkeypatch.setattr(wupd, "_find_binary", lambda: binary)
+ monkeypatch.setattr(wupd, "_installer_script", lambda: tmp_path / "install_whisper_prebuilt.py")
+ monkeypatch.setattr(wfresh, "_fetch_latest_release_tag", lambda repo, timeout = 5.0: latest)
+ return install_dir
+
+
+def _patch_whisper_phase(
+ monkeypatch,
+ events,
+ *,
+ to_tag = "v1.9.2-unsloth.1",
+ error = None,
+):
+ """Record whisper phase runs without touching a real installer."""
+
+ def _run(phase, set_progress):
+ events.append("whisper")
+ if error is not None:
+ raise RuntimeError(error)
+ set_progress(0.5)
+ return {
+ "to_tag": to_tag,
+ "reload_required": False,
+ "message": f"Updated whisper.cpp to {to_tag}.",
+ }
+
+ monkeypatch.setattr(wupd, "run_chained_phase", _run)
+
+
+def _wait_for_job():
+ deadline = time.time() + 10
+ while time.time() < deadline:
+ with upd._job_lock:
+ job = dict(upd._job)
+ if job["state"] in ("success", "error"):
+ return job
+ time.sleep(0.05)
+ with upd._job_lock:
+ return dict(upd._job)
+
+
+# --- status: the single item folds whisper in ---
+
+
+def test_status_payload_is_exact_superset_of_legacy_fields(monkeypatch, tmp_path):
+ _setup_llama(monkeypatch, tmp_path)
+ _setup_whisper(monkeypatch, tmp_path)
+ st = upd.get_update_status(force_refresh = True)
+ assert LEGACY_STATUS_FIELDS <= set(st)
+ assert LEGACY_JOB_FIELDS <= set(st["job"])
+ # The new fields ride alongside, never replacing the legacy ones.
+ assert st["llama_update_available"] is True
+ assert st["whisper"]["update_available"] is True
+ assert st["whisper"]["latest_tag"] == "v1.9.2-unsloth.1"
+ assert st["update_component"] == "llama"
+
+
+def test_status_union_whisper_only_surfaces_update(monkeypatch, tmp_path):
+ # llama current, whisper behind: the single item still shows an update.
+ _setup_llama(monkeypatch, tmp_path, installed = "b9518", latest = "b9518")
+ _setup_whisper(monkeypatch, tmp_path)
+ st = upd.get_update_status(force_refresh = True)
+ assert st["llama_update_available"] is False
+ assert st["whisper"]["update_available"] is True
+ assert st["update_available"] is True
+ assert st["update_component"] == "whisper"
+ assert st["installed_tag"] == "b9518"
+ assert st["latest_tag"] == "b9518"
+ assert st["whisper"]["installed_tag"] == "v1.9.1-unsloth.1"
+ assert st["whisper"]["latest_tag"] == "v1.9.2-unsloth.1"
+
+
+def test_status_whisper_current_does_not_flip_union(monkeypatch, tmp_path):
+ _setup_llama(monkeypatch, tmp_path, installed = "b9518", latest = "b9518")
+ _setup_whisper(monkeypatch, tmp_path, installed = "v1.9.2-unsloth.1", latest = "v1.9.2-unsloth.1")
+ st = upd.get_update_status(force_refresh = True)
+ assert st["update_available"] is False
+ assert st["whisper"]["skip_reason"] == "up_to_date"
+ assert st["update_component"] is None
+
+
+def test_status_survives_whisper_probe_failure(monkeypatch, tmp_path):
+ # The piggyback fails open: llama status still works without a whisper probe.
+ _setup_llama(monkeypatch, tmp_path)
+
+ def _boom(*, force_refresh = False):
+ raise RuntimeError("probe exploded")
+
+ monkeypatch.setattr(wupd, "chained_phase_plan", _boom)
+ st = upd.get_update_status(force_refresh = True)
+ assert st["update_available"] is True
+ assert st["whisper"] is None
+
+
+# --- whisper chained_phase_plan: silent skips ---
+
+
+def test_whisper_plan_skips_local_link(monkeypatch, tmp_path):
+ monkeypatch.setattr(wupd, "_find_binary", lambda: str(tmp_path / "whisper-server"))
+ monkeypatch.setattr(wupd, "_active_install_is_local_link", lambda b: True)
+ plan = wupd.chained_phase_plan()
+ assert plan["update_available"] is False
+ assert plan["skip_reason"] == "local_link"
+ assert plan["phase"] is None
+
+
+def test_whisper_plan_skips_source_build(monkeypatch, tmp_path):
+ binary = tmp_path / "whisper.cpp" / "build" / "bin" / "whisper-server"
+ binary.parent.mkdir(parents = True)
+ binary.write_text("stub") # no marker
+ monkeypatch.setattr(wupd, "_find_binary", lambda: str(binary))
+ plan = wupd.chained_phase_plan()
+ assert plan["skip_reason"] == "source_build"
+ assert plan["phase"] is None
+
+
+def test_whisper_update_targets_canonical_root_when_inner_marker_exists(tmp_path):
+ install_dir = tmp_path / "whisper.cpp"
+ binary = install_dir / "build" / "bin" / "whisper-server"
+ binary.parent.mkdir(parents = True)
+ binary.write_text("stub")
+ (install_dir / WHISPER_MARKER).write_text("{}")
+ (binary.parent / WHISPER_MARKER).write_text("{}")
+ assert wupd._install_dir_for(str(binary)) == install_dir
+
+
+def test_whisper_plan_skips_when_not_installed(monkeypatch):
+ monkeypatch.setattr(wupd, "_find_binary", lambda: None)
+ plan = wupd.chained_phase_plan()
+ assert plan["skip_reason"] == "not_installed"
+ assert plan["phase"] is None
+
+
+def test_whisper_plan_eligible_when_behind(monkeypatch, tmp_path):
+ install_dir = _setup_whisper(monkeypatch, tmp_path)
+ script = tmp_path / "install_whisper_prebuilt.py"
+ script.write_text("stub")
+ plan = wupd.chained_phase_plan(force_refresh = True)
+ assert plan["update_available"] is True
+ assert plan["skip_reason"] is None
+ assert plan["phase"]["install_dir"] == install_dir
+ assert plan["phase"]["repo"] == "unslothai/whisper.cpp"
+ assert plan["phase"]["backend"] == "cpu"
+ # Pin to the exact release the freshness check offered: unpinned, the
+ # installer's download-host /releases/latest pointer can lag published_at
+ # and reinstall an older build in a loop.
+ assert plan["phase"]["pin_release_tag"] == "v1.9.2-unsloth.1"
+
+
+def test_whisper_plan_requires_a_repairable_pair_for_slim_installs(monkeypatch, tmp_path):
+ install_dir = _setup_whisper(monkeypatch, tmp_path)
+ marker_path = install_dir / WHISPER_MARKER
+ marker = json.loads(marker_path.read_text())
+ marker["install_kind"] = "slim"
+ marker_path.write_text(json.dumps(marker))
+ wfresh.reset_caches()
+ monkeypatch.setattr(
+ wupd,
+ "_resolve_prebuilt_for_host",
+ lambda **kwargs: {"prebuilt_available": False},
+ )
+
+ plan = wupd.chained_phase_plan(force_refresh = True)
+ assert plan["update_available"] is False
+ assert plan["skip_reason"] == "paired_llama_unavailable"
+
+ repaired = wupd.chained_phase_plan(
+ force_refresh = True,
+ paired_llama_will_update = True,
+ )
+ assert repaired["update_available"] is True
+ assert repaired["phase"] is not None
+
+
+def test_whisper_phase_pins_installer_to_checked_release(monkeypatch, tmp_path):
+ calls = []
+ monkeypatch.setattr(
+ wupd._flow,
+ "stream_installer",
+ lambda cmd, env, **kw: calls.append(cmd),
+ )
+ monkeypatch.setattr(wupd, "reset_caches", lambda **kw: None)
+ monkeypatch.setattr(wupd, "latest_published_release", lambda repo, **kw: "v9")
+ install_dir = tmp_path / "whisper.cpp"
+ binary = _write_whisper_install(install_dir, "v9")
+ monkeypatch.setattr(wupd, "_find_binary", lambda: binary)
+ wupd.run_chained_phase(
+ {
+ "install_dir": install_dir,
+ "repo": "unslothai/whisper.cpp",
+ "asset": None,
+ "backend": "cpu",
+ "script": tmp_path / "install_whisper_prebuilt.py",
+ "pin_release_tag": "v9",
+ },
+ lambda f: None,
+ )
+ cmd = calls[0]
+ assert "--published-release-tag" in cmd
+ assert cmd[cmd.index("--published-release-tag") + 1] == "v9"
+
+
+def test_whisper_phase_exit_2_is_a_failed_phase(monkeypatch, tmp_path):
+ # No install occurred, so incompatibility must remain an actionable job
+ # error instead of producing a false success toast and hiding the banner.
+ def _raise_exit_2(cmd, env, **kw):
+ raise wupd._flow.InstallerExit(2, "installer exited 2: incompatible release")
+
+ monkeypatch.setattr(wupd._flow, "stream_installer", _raise_exit_2)
+ install_dir = tmp_path / "whisper.cpp"
+ binary = _write_whisper_install(install_dir, "v1")
+ monkeypatch.setattr(wupd, "_find_binary", lambda: binary)
+ with pytest.raises(wupd._flow.InstallerExit) as exc_info:
+ wupd.run_chained_phase(
+ {
+ "install_dir": install_dir,
+ "repo": "unslothai/whisper.cpp",
+ "asset": None,
+ "backend": "cpu",
+ "script": tmp_path / "install_whisper_prebuilt.py",
+ "pin_release_tag": None,
+ },
+ lambda f: None,
+ )
+ assert exc_info.value.returncode == 2
+
+
+def test_llama_update_survives_unavailable_whisper_module(monkeypatch, tmp_path):
+ import builtins
+
+ llama_dir = _setup_llama(monkeypatch, tmp_path)
+ monkeypatch.setattr(upd, "_whisper_chain_status", lambda **kw: None)
+ _patch_llama_installer(
+ monkeypatch,
+ on_start = lambda cmd: _write_llama_install(llama_dir, "b9518"),
+ )
+ real_import = builtins.__import__
+
+ def guarded_import(
+ name,
+ globals = None,
+ locals = None,
+ fromlist = (),
+ level = 0,
+ ):
+ if name == "utils" and "whisper_cpp_update" in fromlist:
+ raise AssertionError("whisper module was re-imported after its failed probe")
+ return real_import(name, globals, locals, fromlist, level)
+
+ monkeypatch.setattr(builtins, "__import__", guarded_import)
+
+ # A failed optional whisper probe must not be followed by an unconditional
+ # import. The valid llama phase still starts and completes.
+ assert upd.start_update()["started"] is True
+ job = _wait_for_job()
+ assert job["state"] == "success", job
+ assert job["phases"]["llama"]["state"] == "success"
+ assert job["phases"]["whisper"]["state"] == "skipped"
+ assert job["phases"]["whisper"]["reason"] == "unavailable"
+
+
+def test_macos_status_uses_compatible_resolver_release(monkeypatch, tmp_path):
+ _setup_whisper(
+ monkeypatch,
+ tmp_path,
+ installed = "v1.9.1-unsloth.1",
+ latest = "v1.9.2-unsloth.1",
+ )
+ monkeypatch.setattr(wupd.sys, "platform", "darwin")
+ monkeypatch.setattr(
+ wupd,
+ "_resolve_prebuilt_for_host",
+ lambda **kw: {
+ "prebuilt_available": True,
+ "release_tag": "v1.9.1-unsloth.1",
+ },
+ )
+
+ status = wupd.get_update_status(force_refresh = True)
+ assert status["latest_tag"] == "v1.9.1-unsloth.1"
+ assert status["update_available"] is False
+ assert status["stale"] is False
+
+
+def test_whisper_phase_integrity_failure_is_not_swallowed(monkeypatch, tmp_path):
+ def _raise_exit_1(cmd, env, **kw):
+ raise wupd._flow.InstallerExit(1, "installer exited 1: checksum mismatch")
+
+ monkeypatch.setattr(wupd._flow, "stream_installer", _raise_exit_1)
+ install_dir = tmp_path / "whisper.cpp"
+ binary = _write_whisper_install(install_dir, "v1")
+ monkeypatch.setattr(wupd, "_find_binary", lambda: binary)
+ with pytest.raises(wupd._flow.InstallerExit, match = "checksum mismatch"):
+ wupd.run_chained_phase(
+ {
+ "install_dir": install_dir,
+ "repo": "unslothai/whisper.cpp",
+ "asset": None,
+ "backend": "cpu",
+ "script": tmp_path / "install_whisper_prebuilt.py",
+ "pin_release_tag": None,
+ },
+ lambda f: None,
+ )
+
+
+# --- apply: the chained job ---
+
+
+def test_apply_runs_llama_then_whisper(monkeypatch, tmp_path):
+ llama_dir = _setup_llama(monkeypatch, tmp_path)
+ _setup_whisper(monkeypatch, tmp_path)
+ (tmp_path / "install_whisper_prebuilt.py").write_text("stub")
+
+ events = []
+ _patch_llama_installer(
+ monkeypatch,
+ on_start = lambda cmd: (events.append("llama"), _write_llama_install(llama_dir, "b9518")),
+ )
+ _patch_whisper_phase(monkeypatch, events)
+
+ res = upd.start_update()
+ assert res["started"] is True, res
+ job = _wait_for_job()
+ assert job["state"] == "success", job
+ assert events == ["llama", "whisper"] # llama phase strictly first
+ assert job["phases"]["llama"]["state"] == "success"
+ assert job["phases"]["llama"]["to_tag"] == "b9518"
+ assert job["phases"]["whisper"]["state"] == "success"
+ assert job["phases"]["whisper"]["to_tag"] == "v1.9.2-unsloth.1"
+ # Legacy top-level fields keep their llama meaning.
+ assert job["from_tag"] == "b9493"
+ assert job["to_tag"] == "b9518"
+ assert "Updated llama.cpp to b9518." in job["message"]
+ assert "Updated whisper.cpp to v1.9.2-unsloth.1." in job["message"]
+ assert job["progress"] == 1.0
+ assert LEGACY_JOB_FIELDS <= set(job)
+
+
+def test_apply_llama_only_when_whisper_current(monkeypatch, tmp_path):
+ llama_dir = _setup_llama(monkeypatch, tmp_path)
+ _setup_whisper(monkeypatch, tmp_path, installed = "v1.9.2-unsloth.1", latest = "v1.9.2-unsloth.1")
+
+ events = []
+ _patch_llama_installer(
+ monkeypatch,
+ on_start = lambda cmd: (events.append("llama"), _write_llama_install(llama_dir, "b9518")),
+ )
+ _patch_whisper_phase(monkeypatch, events)
+
+ assert upd.start_update()["started"] is True
+ job = _wait_for_job()
+ assert job["state"] == "success", job
+ assert events == ["llama"]
+ assert job["phases"]["whisper"]["state"] == "skipped"
+ assert job["phases"]["whisper"]["reason"] == "up_to_date"
+
+
+def test_apply_whisper_only_noops_llama(monkeypatch, tmp_path):
+ # llama current + whisper behind: the same single apply runs, with the llama
+ # phase a cheap already-matches no-op and the whisper phase doing the work.
+ _setup_llama(monkeypatch, tmp_path, installed = "b9518", latest = "b9518")
+ _setup_whisper(monkeypatch, tmp_path)
+ (tmp_path / "install_whisper_prebuilt.py").write_text("stub")
+
+ events = []
+ _patch_llama_installer(monkeypatch, on_start = lambda cmd: events.append("llama"))
+ _patch_whisper_phase(monkeypatch, events)
+
+ res = upd.start_update()
+ assert res["started"] is True, res
+ job = _wait_for_job()
+ assert job["state"] == "success", job
+ assert events == ["whisper"] # the llama installer never ran
+ # The legacy job-level to_tag means "llama tag"; a whisper-only round
+ # leaves it unset so the UI never reports a llama update that never ran.
+ assert job["to_tag"] is None
+ assert job["phases"]["llama"]["state"] == "skipped"
+ assert job["phases"]["llama"]["reason"] == "up_to_date"
+ assert job["phases"]["whisper"]["state"] == "success"
+ assert "Updated whisper.cpp to v1.9.2-unsloth.1." in job["message"]
+
+
+def test_whisper_reload_never_raises_job_reload_flag(monkeypatch, tmp_path):
+ # A whisper-only update that had to unload a warm sidecar reports
+ # reload_required on its phase, but the JOB flag stays down: the chat
+ # frontend resyncs (and clears the local checkpoint) off the job flag,
+ # which must mean "the llama server changed", not "the sidecar restarted".
+ _setup_llama(monkeypatch, tmp_path, installed = "b9518", latest = "b9518")
+ _setup_whisper(monkeypatch, tmp_path)
+ (tmp_path / "install_whisper_prebuilt.py").write_text("stub")
+
+ def _whisper_phase(phase, set_progress):
+ return {
+ "to_tag": "v1.9.2-unsloth.1",
+ "reload_required": True,
+ "message": "Updated whisper.cpp to v1.9.2-unsloth.1.",
+ }
+
+ monkeypatch.setattr(wupd, "run_chained_phase", _whisper_phase)
+ assert upd.start_update()["started"] is True
+ job = _wait_for_job()
+ assert job["state"] == "success", job
+ assert job["phases"]["whisper"]["reload_required"] is True
+ assert not job["reload_required"]
+
+
+def test_apply_refuses_when_both_current(monkeypatch, tmp_path):
+ _setup_llama(monkeypatch, tmp_path, installed = "b9518", latest = "b9518")
+ _setup_whisper(monkeypatch, tmp_path, installed = "v1.9.2-unsloth.1", latest = "v1.9.2-unsloth.1")
+ res = upd.start_update()
+ assert res["started"] is False
+ assert res["reason"] == "up_to_date"
+
+
+def test_apply_llama_failure_aborts_before_whisper(monkeypatch, tmp_path):
+ _setup_llama(monkeypatch, tmp_path)
+ _setup_whisper(monkeypatch, tmp_path)
+ (tmp_path / "install_whisper_prebuilt.py").write_text("stub")
+
+ events = []
+ _patch_llama_installer(monkeypatch, returncode = 2, lines = ["boom: disk full\n"])
+ _patch_whisper_phase(monkeypatch, events)
+
+ assert upd.start_update()["started"] is True
+ job = _wait_for_job()
+ assert job["state"] == "error", job
+ assert "boom" in (job["error"] or "")
+ assert events == [] # whisper never attempted
+ assert job["phases"]["llama"]["state"] == "error"
+ assert job["phases"]["whisper"]["state"] == "skipped"
+ assert job["phases"]["whisper"]["reason"] == "aborted"
+ assert job["message"] == "llama.cpp update failed."
+
+
+def test_apply_whisper_failure_keeps_llama_partial_success(monkeypatch, tmp_path):
+ llama_dir = _setup_llama(monkeypatch, tmp_path)
+ _setup_whisper(monkeypatch, tmp_path)
+ (tmp_path / "install_whisper_prebuilt.py").write_text("stub")
+
+ # An active model makes the llama phase report reload_required.
+ import threading
+ from types import ModuleType
+
+ class _FakeBackend:
+ def __init__(self):
+ self._serial_load_lock = threading.Lock()
+ self._llama_update_in_progress = False
+ self.is_active = True
+
+ def unload_model(self):
+ self.is_active = False
+
+ backend = _FakeBackend()
+ routes_pkg = ModuleType("routes")
+ routes_pkg.__path__ = []
+ inference_mod = ModuleType("routes.inference")
+ inference_mod.get_llama_cpp_backend = lambda: backend
+ monkeypatch.setitem(sys.modules, "routes", routes_pkg)
+ monkeypatch.setitem(sys.modules, "routes.inference", inference_mod)
+
+ events = []
+ _patch_llama_installer(
+ monkeypatch,
+ on_start = lambda cmd: (events.append("llama"), _write_llama_install(llama_dir, "b9518")),
+ )
+ _patch_whisper_phase(monkeypatch, events, error = "whisper installer exploded")
+
+ assert upd.start_update()["started"] is True
+ job = _wait_for_job()
+ assert job["state"] == "error", job
+ assert events == ["llama", "whisper"]
+ # The message says both halves: llama landed, whisper did not.
+ assert "Updated llama.cpp to b9518." in job["message"]
+ assert "whisper.cpp update failed." in job["message"]
+ assert "whisper installer exploded" in (job["error"] or "")
+ # The llama phase's reload_required survives the whisper failure.
+ assert job["reload_required"] is True
+ assert job["to_tag"] == "b9518"
+ assert job["phases"]["llama"]["state"] == "success"
+ assert job["phases"]["whisper"]["state"] == "error"
+
+
+def test_apply_skips_whisper_local_link_silently(monkeypatch, tmp_path):
+ llama_dir = _setup_llama(monkeypatch, tmp_path)
+ _setup_whisper(monkeypatch, tmp_path)
+ monkeypatch.setattr(wupd, "_active_install_is_local_link", lambda b: True)
+
+ events = []
+ _patch_llama_installer(
+ monkeypatch,
+ on_start = lambda cmd: (events.append("llama"), _write_llama_install(llama_dir, "b9518")),
+ )
+ _patch_whisper_phase(monkeypatch, events)
+
+ assert upd.start_update()["started"] is True
+ job = _wait_for_job()
+ assert job["state"] == "success", job
+ assert events == ["llama"]
+ assert job["phases"]["whisper"]["state"] == "skipped"
+ assert job["phases"]["whisper"]["reason"] == "local_link"
+ assert job["message"] == "Updated llama.cpp to b9518."
+
+
+def test_chained_progress_windows(monkeypatch, tmp_path):
+ # The llama phase fills roughly the first 0.7 slice and whisper the rest.
+ llama_dir = _setup_llama(monkeypatch, tmp_path)
+ _setup_whisper(monkeypatch, tmp_path)
+ (tmp_path / "install_whisper_prebuilt.py").write_text("stub")
+
+ seen = {}
+
+ def _whisper_phase(phase, set_progress):
+ with upd._job_lock:
+ seen["at_whisper_start"] = upd._job["progress"]
+ set_progress(0.5)
+ with upd._job_lock:
+ seen["mid_whisper"] = upd._job["progress"]
+ return {"to_tag": "v1.9.2-unsloth.1", "reload_required": False, "message": "ok"}
+
+ monkeypatch.setattr(wupd, "run_chained_phase", _whisper_phase)
+ _patch_llama_installer(
+ monkeypatch,
+ lines = ["Downloading app.tar.gz: 100.0% (35.0 MiB/35.0 MiB) at 9.0 MiB/s\n"],
+ on_start = lambda cmd: _write_llama_install(llama_dir, "b9518"),
+ )
+
+ assert upd.start_update()["started"] is True
+ job = _wait_for_job()
+ assert job["state"] == "success", job
+ assert seen["at_whisper_start"] == pytest.approx(0.7)
+ assert seen["mid_whisper"] == pytest.approx(0.7 + 0.5 * 0.3)
+ assert job["progress"] == 1.0
diff --git a/studio/backend/tests/test_install_resolve_prebuilt.py b/studio/backend/tests/test_install_resolve_prebuilt.py
index 3ebad861ad9..02ccc68b114 100644
--- a/studio/backend/tests/test_install_resolve_prebuilt.py
+++ b/studio/backend/tests/test_install_resolve_prebuilt.py
@@ -200,14 +200,9 @@ def _gpu_linux_host(caps):
)
-def test_host_is_blackwell_includes_datacenter_parts():
- assert ilp._host_is_blackwell(_gpu_linux_host(["10.0"])) is True # B200 sm_100
- assert ilp._host_is_blackwell(_gpu_linux_host(["10.3"])) is True # B300 sm_103
- assert ilp._host_is_blackwell(_gpu_linux_host(["12.0"])) is True # RTX 50 sm_120
- assert ilp._host_is_blackwell(_gpu_linux_host(["12.1"])) is True # DGX Spark sm_121
- assert ilp._host_is_blackwell(_gpu_linux_host(["9.0"])) is False # Hopper
- assert ilp._host_is_blackwell(_gpu_linux_host(["8.0"])) is False # Ampere
- assert ilp._host_is_blackwell(_gpu_linux_host(["9.0", "10.0"])) is True # highest cap wins
+# _host_is_blackwell / _blackwell_min_toolkit_for_host are prebuilt_core
+# re-exports; their value tables moved verbatim to
+# tests/studio/install/test_prebuilt_core.py.
def _linux_cuda_artifact(runtime_line, supported_sms, min_sm, max_sm, profile):
@@ -285,16 +280,6 @@ def test_drop_blackwell_incapable_windows_cuda_applies_to_datacenter():
assert [a.name for a in kept] == [cuda13.name]
-def test_blackwell_min_toolkit_is_sm_aware():
- # Family floor is 12.8; sm_103/sm_121 (no native target before 12.9) lift it.
- f = ilp._blackwell_min_toolkit_for_host
- assert f(_gpu_linux_host(["10.0"])) == (12, 8) # B200
- assert f(_gpu_linux_host(["12.0"])) == (12, 8) # RTX 50
- assert f(_gpu_linux_host(["10.3"])) == (12, 9) # B300
- assert f(_gpu_linux_host(["12.1"])) == (12, 9) # DGX Spark
- assert f(_gpu_linux_host(["10.0", "10.3"])) == (12, 9) # max across SMs wins
-
-
def test_sm103_host_drops_cuda128_windows_build():
# B300 (sm_103) needs cuda-12.9: a legacy win-cuda-12.8 build must be dropped.
host = _host(
diff --git a/studio/backend/tests/test_install_whisper_prebuilt_checksums.py b/studio/backend/tests/test_install_whisper_prebuilt_checksums.py
new file mode 100644
index 00000000000..19bece9d0c2
--- /dev/null
+++ b/studio/backend/tests/test_install_whisper_prebuilt_checksums.py
@@ -0,0 +1,231 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Trust-anchor tests for install_whisper_prebuilt.py.
+
+Whisper verifies each download against the release's own
+whisper-prebuilt-sha256.json checksum index (the same model as
+install_llama_prebuilt.py), not a committed pins file. These pin the index
+parser, the fail-closed behaviour when an asset is not covered, the
+tampered-manifest guard, and the newest-release resolution.
+"""
+
+from __future__ import annotations
+
+import importlib
+import sys
+from pathlib import Path
+
+import pytest
+
+_studio = Path(__file__).resolve().parent.parent.parent
+if str(_studio) not in sys.path:
+ sys.path.insert(0, str(_studio))
+
+iwp = importlib.import_module("install_whisper_prebuilt")
+
+if not hasattr(iwp, "parse_release_checksums"):
+ pytest.skip("checksum-model symbols not present - check branch", allow_module_level = True)
+
+_A = "0" * 64
+_B = "1" * 64
+_TAG = "v1.9.1-unsloth.1"
+_REPO = "unslothai/whisper.cpp"
+
+
+def _index(**overrides) -> dict:
+ payload = {
+ "schema_version": 1,
+ "component": "whisper.cpp",
+ "release_tag": _TAG,
+ "upstream_tag": "v1.9.1",
+ "artifacts": {
+ "whisper-v1.9.1-unsloth.1-linux-x64-cpu.tar.gz": {"sha256": _A},
+ "whisper-v1.9.1-unsloth.1-linux-x64-cuda12-portable.tar.gz": {"sha256": _B},
+ },
+ }
+ payload.update(overrides)
+ return payload
+
+
+# parse_release_checksums / expected_sha256_for are prebuilt_core re-exports;
+# their valid/fail-closed matrix is asserted against the real whisper
+# descriptor in tests/studio/install/test_prebuilt_core.py. The download-host
+# fast-path tests below still route through this module's parse wrapper.
+
+# release tag resolution.
+
+
+def test_resolve_release_tag_explicit_override_passthrough():
+ assert iwp.resolve_release_tag(_REPO, published_release_tag = "v1.9.1-unsloth.2") == (
+ "v1.9.1-unsloth.2"
+ )
+
+
+def test_resolve_release_tag_resolves_newest_when_no_override(monkeypatch):
+ monkeypatch.setattr(iwp, "resolve_newest_release_tag", lambda repo: "v9.9.9-unsloth.9")
+ assert iwp.resolve_release_tag(_REPO, published_release_tag = None) == "v9.9.9-unsloth.9"
+
+
+def test_resolve_newest_release_tag_picks_latest_published(monkeypatch):
+ releases = [
+ {"tag_name": "v1.9.1-unsloth.1", "published_at": "2026-01-01T00:00:00Z"},
+ {"tag_name": "v1.9.1-unsloth.3", "published_at": "2026-03-01T00:00:00Z"},
+ {"tag_name": "v1.9.1-unsloth.2", "published_at": "2026-02-01T00:00:00Z"},
+ {"tag_name": "draft", "published_at": "2026-09-01T00:00:00Z", "draft": True},
+ {"tag_name": "pre", "published_at": "2026-09-01T00:00:00Z", "prerelease": True},
+ ]
+ monkeypatch.setattr(iwp, "fetch_json", lambda url: releases)
+ assert iwp.resolve_newest_release_tag(_REPO) == "v1.9.1-unsloth.3"
+
+
+def test_resolve_newest_release_tag_none_published_fails_closed(monkeypatch):
+ monkeypatch.setattr(iwp, "fetch_json", lambda url: [{"tag_name": "d", "draft": True}])
+ with pytest.raises(iwp.PrebuiltFallback):
+ iwp.resolve_newest_release_tag(_REPO)
+
+
+def test_pins_symbols_are_gone():
+ # The committed-pins trust model was removed in favour of llama's runtime index.
+ for gone in ("load_pins", "pins_path", "resolve_expected_sha256", "PINS_FILENAME"):
+ assert not hasattr(iwp, gone), f"{gone} should have been removed"
+
+
+# Download-host fast path (resolve + fetch the JSON assets with no GitHub API).
+
+_CPU_ASSET = "whisper-v1.9.1-unsloth.1-linux-x64-cpu.tar.gz"
+
+
+def _manifest() -> dict:
+ return {
+ "schema_version": 1,
+ "component": "whisper.cpp",
+ "upstream_tag": "v1.9.1",
+ "artifacts": [{"asset": _CPU_ASSET, "os": "linux", "arch": "x64", "backend": "cpu"}],
+ }
+
+
+def _no_api(monkeypatch):
+ """Fail loudly if any code path touches api.github.com."""
+
+ def _boom(*a, **k):
+ raise AssertionError("api.github.com was used on the fast path")
+
+ monkeypatch.setattr(iwp, "fetch_json", _boom)
+ monkeypatch.setattr(iwp, "github_release", _boom)
+ monkeypatch.setattr(iwp, "fetch_release_bundle", _boom)
+
+
+def test_fetch_release_for_install_prefers_download_host(monkeypatch):
+ _no_api(monkeypatch)
+ monkeypatch.setattr(iwp, "_download_host_latest_release_tag", lambda repo: _TAG)
+
+ def _dhj(url):
+ if url.endswith(iwp.SHA256_ASSET_NAME):
+ return _index()
+ if url.endswith(iwp.MANIFEST_ASSET_NAME):
+ return _manifest()
+ raise AssertionError(f"unexpected url {url}")
+
+ monkeypatch.setattr(iwp, "_download_host_json", _dhj)
+ bundle, checks = iwp.fetch_release_for_install(_REPO, published_release_tag = None)
+ assert bundle.release_tag == _TAG
+ assert checks[_CPU_ASSET] == _A
+ # asset_urls point at the download host (github.com), not the API.
+ assert bundle.asset_urls[iwp.SHA256_ASSET_NAME].startswith(
+ f"https://github.com/{_REPO}/releases/"
+ )
+ assert bundle.asset_urls[_CPU_ASSET].startswith(
+ f"https://github.com/{_REPO}/releases/download/"
+ )
+ walked = iwp._fetch_release_candidate(_REPO, _TAG)
+ assert iwp.SHA256_ASSET_NAME in walked.asset_urls
+ assert _CPU_ASSET in walked.asset_urls
+
+
+def test_fetch_release_for_install_explicit_tag_skips_the_head(monkeypatch):
+ # An explicit tag needs no /releases/latest HEAD: resolving it must not call it.
+ monkeypatch.setattr(
+ iwp,
+ "_download_host_latest_release_tag",
+ lambda repo: (_ for _ in ()).throw(AssertionError("HEAD used for an explicit tag")),
+ )
+ monkeypatch.setattr(
+ iwp,
+ "_download_host_json",
+ lambda url: _index() if url.endswith(iwp.SHA256_ASSET_NAME) else _manifest(),
+ )
+ _no_api(monkeypatch)
+ bundle, checks = iwp.fetch_release_for_install(_REPO, published_release_tag = _TAG)
+ assert bundle.release_tag == _TAG
+
+
+def test_fetch_release_for_install_falls_back_to_api(monkeypatch):
+ # Fast path returns None (e.g. a 404) -> the API path resolves the release.
+ monkeypatch.setattr(iwp, "_resolve_release_via_download_host", lambda repo, tag: None)
+ sentinel = iwp.ReleaseBundle(repo = _REPO, release_tag = _TAG, manifest = _manifest(), asset_urls = {})
+ monkeypatch.setattr(iwp, "resolve_release_tag", lambda repo, *, published_release_tag: _TAG)
+ monkeypatch.setattr(iwp, "fetch_release_bundle", lambda repo, tag: sentinel)
+ monkeypatch.setattr(iwp, "fetch_release_checksums", lambda bundle: {_CPU_ASSET: _A})
+ bundle, checks = iwp.fetch_release_for_install(_REPO, published_release_tag = None)
+ assert bundle is sentinel
+ assert checks == {_CPU_ASSET: _A}
+
+
+def test_resolve_via_download_host_sha_404_returns_none(monkeypatch):
+ import urllib.error
+
+ monkeypatch.setattr(iwp, "_download_host_latest_release_tag", lambda repo: _TAG)
+
+ def _dhj(url):
+ raise urllib.error.HTTPError(url, 404, "not found", {}, None)
+
+ monkeypatch.setattr(iwp, "_download_host_json", _dhj)
+ assert iwp._resolve_release_via_download_host(_REPO, None) is None
+
+
+def test_resolve_via_download_host_tag_mismatch_returns_none(monkeypatch):
+ # A checksum index whose self-reported release_tag disagrees is rejected (None).
+ monkeypatch.setattr(iwp, "_download_host_latest_release_tag", lambda repo: _TAG)
+ monkeypatch.setattr(
+ iwp, "_download_host_json", lambda url: _index(release_tag = "v1.9.1-unsloth.2")
+ )
+ assert iwp._resolve_release_via_download_host(_REPO, None) is None
+
+
+def test_download_host_latest_release_tag_parses_redirect(monkeypatch):
+ class _Resp:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *a):
+ return False
+
+ def geturl(self):
+ return f"https://github.com/{_REPO}/releases/tag/{_TAG}"
+
+ class _Opener:
+ def open(
+ self,
+ req,
+ timeout = None,
+ ):
+ return _Resp()
+
+ monkeypatch.setattr(iwp, "_URL_OPENER", _Opener())
+ assert iwp._download_host_latest_release_tag(_REPO) == _TAG
+
+
+def test_download_host_latest_release_tag_404_returns_none(monkeypatch):
+ import urllib.error
+
+ class _Opener:
+ def open(
+ self,
+ req,
+ timeout = None,
+ ):
+ raise urllib.error.HTTPError(req.full_url, 404, "nf", {}, None)
+
+ monkeypatch.setattr(iwp, "_URL_OPENER", _Opener())
+ assert iwp._download_host_latest_release_tag(_REPO) is None
diff --git a/studio/backend/tests/test_llama_cpp_update.py b/studio/backend/tests/test_llama_cpp_update.py
index f12384231f4..9e23242b97e 100644
--- a/studio/backend/tests/test_llama_cpp_update.py
+++ b/studio/backend/tests/test_llama_cpp_update.py
@@ -119,6 +119,9 @@ def _clean_state(monkeypatch, tmp_path):
monkeypatch.delenv("UNSLOTH_LLAMA_CPP_PATH", raising = False)
# Never hit the network in these tests.
monkeypatch.setattr(freshness, "_fetch_latest_release_tag", lambda repo, timeout = 5.0: None)
+ # Keep the whisper piggyback out of the llama-only tests: no host probe, no
+ # whisper phase (test_combined_update.py covers the chained flow).
+ monkeypatch.setattr(upd, "_whisper_chain_status", lambda **kwargs: None)
yield
freshness.reset_caches()
upd._reset_job_for_tests()
diff --git a/studio/backend/tests/test_llama_route.py b/studio/backend/tests/test_llama_route.py
index 0ecfeee0180..cc450d55cc0 100644
--- a/studio/backend/tests/test_llama_route.py
+++ b/studio/backend/tests/test_llama_route.py
@@ -100,6 +100,21 @@ def test_status_response_exposes_update_size_bytes():
assert rl.LlamaUpdateStatusResponse(**without).model_dump()["update_size_bytes"] is None
+def test_status_response_exposes_update_component():
+ model = rl.LlamaUpdateStatusResponse(
+ supported = True,
+ update_available = True,
+ llama_update_available = False,
+ update_component = "whisper",
+ whisper = {
+ "update_available": True,
+ "installed_tag": "v1",
+ "latest_tag": "v2",
+ },
+ )
+ assert model.model_dump()["update_component"] == "whisper"
+
+
def test_status_handler_runs_off_event_loop(monkeypatch):
seen = {}
diff --git a/studio/backend/tests/test_local_llama_cpp_link.py b/studio/backend/tests/test_local_llama_cpp_link.py
index 6b44f61972a..79c9977c843 100644
--- a/studio/backend/tests/test_local_llama_cpp_link.py
+++ b/studio/backend/tests/test_local_llama_cpp_link.py
@@ -21,6 +21,13 @@ from utils import llama_cpp_update as u
from core.inference.llama_cpp import LlamaCppBackend
[email protected](autouse = True)
+def _no_whisper_piggyback(monkeypatch):
+ # Keep the whisper piggyback probe off the host: these tests exercise the
+ # llama local-link contract only.
+ monkeypatch.setattr(u, "_whisper_chain_status", lambda **kwargs: None)
+
+
def _make_link(link: Path, target: Path) -> None:
"""Create a directory junction (Windows) / symlink (POSIX); neither needs
elevation."""
diff --git a/studio/backend/tests/test_middleware.py b/studio/backend/tests/test_middleware.py
index 209c6cb90a4..36061b5375e 100644
--- a/studio/backend/tests/test_middleware.py
+++ b/studio/backend/tests/test_middleware.py
@@ -34,6 +34,7 @@ def main_module():
def _make_protected_app(
max_bytes: int,
main_module,
+ request_max_bytes_getter = None,
upload_passthrough_prefixes: tuple = (),
upload_passthrough_max_bytes_getter = None,
):
@@ -41,7 +42,13 @@ def _make_protected_app(
app.add_middleware(
main_module.MaxBodyMiddleware,
max_bytes_getter = lambda: max_bytes,
- protected_prefixes = ("/v1/chat/completions", "/api/settings", "/api/train"),
+ protected_prefixes = (
+ "/v1/chat/completions",
+ "/api/inference",
+ "/api/settings",
+ "/api/train",
+ ),
+ request_max_bytes_getter = request_max_bytes_getter,
upload_passthrough_prefixes = upload_passthrough_prefixes,
upload_passthrough_max_bytes_getter = upload_passthrough_max_bytes_getter,
)
@@ -68,6 +75,10 @@ def _make_protected_app(
total += len(chunk)
return {"ok": True, "chunks": chunks, "total": total}
+ @app.post("/api/inference/audio/transcribe/raw")
+ async def transcribe_raw(request: Request):
+ return {"ok": True, "total": len(await request.body())}
+
@app.get("/api/train/status")
async def status_get():
return {"ok": True, "get": True}
@@ -97,6 +108,43 @@ class TestMaxBodyMiddleware:
assert r.status_code == 200
assert r.json()["unprotected"] is True
+ def test_route_specific_cap_overrides_default(self, main_module):
+ app = _make_protected_app(
+ 4096,
+ main_module,
+ request_max_bytes_getter = lambda path: (
+ 128 if path.endswith("/transcribe/raw") else 4096
+ ),
+ )
+ c = TestClient(app)
+
+ rejected = c.post(
+ "/api/inference/audio/transcribe/raw",
+ content = b"x" * 129,
+ )
+ accepted = c.post(
+ "/api/inference/audio/transcribe/raw",
+ content = b"x" * 128,
+ )
+
+ assert rejected.status_code == 413
+ assert accepted.status_code == 200
+ assert accepted.json()["total"] == 128
+
+ def test_stt_routes_use_audio_specific_caps(self, main_module):
+ from utils.upload_limits import (
+ STT_AUDIO_JSON_MAX_BYTES,
+ STT_AUDIO_RAW_MAX_BYTES,
+ )
+ assert (
+ main_module._get_request_body_max_bytes("/api/inference/audio/transcribe/raw")
+ == STT_AUDIO_RAW_MAX_BYTES
+ )
+ assert (
+ main_module._get_request_body_max_bytes("/api/inference/audio/transcribe")
+ == STT_AUDIO_JSON_MAX_BYTES
+ )
+
def test_settings_put_body_over_cap_rejected(self, main_module):
app = _make_protected_app(1024, main_module)
c = TestClient(app)
diff --git a/studio/backend/tests/test_model_update_robustness.py b/studio/backend/tests/test_model_update_robustness.py
index 7e5d7937408..d84f8c94a70 100644
--- a/studio/backend/tests/test_model_update_robustness.py
+++ b/studio/backend/tests/test_model_update_robustness.py
@@ -400,6 +400,53 @@ def test_cached_gguf_scan_keeps_download_timestamp(monkeypatch, tmp_path):
assert rows[0]["last_modified"] == 5_000.0
+def test_cached_model_scan_hides_custom_whisper_repo(monkeypatch, tmp_path):
+ repo_path = tmp_path / "models--Org--CustomWhisper"
+ snapshot = repo_path / "snapshots" / ("a" * 40)
+ snapshot.mkdir(parents = True)
+ (snapshot / "config.json").write_text(
+ '{"model_type": "whisper", "architectures": ["WhisperForConditionalGeneration"]}'
+ )
+ repo = SimpleNamespace(
+ repo_id = "Org/CustomWhisper",
+ repo_type = "model",
+ repo_path = repo_path,
+ revisions = [
+ SimpleNamespace(
+ files = [
+ SimpleNamespace(
+ file_name = "config.json",
+ size_on_disk = 10,
+ blob_path = None,
+ ),
+ SimpleNamespace(
+ file_name = "model.safetensors",
+ size_on_disk = 100,
+ blob_path = str(repo_path / "blobs" / "modelsha"),
+ ),
+ ]
+ )
+ ],
+ )
+ monkeypatch.setattr(
+ CI,
+ "all_hf_cache_scans",
+ lambda: [SimpleNamespace(repos = [repo])],
+ )
+ monkeypatch.setattr(
+ CI,
+ "_cached_model_snapshot_path",
+ lambda _repo_path: snapshot,
+ )
+ monkeypatch.setattr(
+ CI.hf_cache_scan,
+ "is_snapshot_partial",
+ lambda *args, **kwargs: False,
+ )
+
+ assert CI._scan_cached_models() == []
+
+
# ── hf_hub_download_with_xet_fallback force_download bypass (X2/F2) ───
diff --git a/studio/backend/tests/test_stt_download_validation.py b/studio/backend/tests/test_stt_download_validation.py
new file mode 100644
index 00000000000..a612b145310
--- /dev/null
+++ b/studio/backend/tests/test_stt_download_validation.py
@@ -0,0 +1,168 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The /audio/stt/download route must validate a custom Transformers repo before
+snapshot_download pulls it into the shared HF cache.
+
+Regression for a Codex finding: the Transformers engine accepts arbitrary
+`owner/model` repos, so an authenticated caller could make Studio download a
+large non-STT repository before load-time validation ever ran. Whisper-
+compatibility is now enforced (metadata-only, no weights) before the background
+download starts. The GGUF engine only accepts curated ids, so it is not gated.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import sys
+from pathlib import Path
+
+import pytest
+from fastapi import HTTPException
+
+_BACKEND_ROOT = Path(__file__).resolve().parents[1]
+if str(_BACKEND_ROOT) not in sys.path:
+ sys.path.insert(0, str(_BACKEND_ROOT))
+
+import core.inference.stt_ggml_sidecar as ggml_module # noqa: E402
+import core.inference.stt_sidecar as stt_module # noqa: E402
+import routes.inference as ri # noqa: E402
+from core.inference.stt_sidecar import SttModelCompatibilityError # noqa: E402
+from models.inference import SttLoadRequest # noqa: E402
+
+
+def _run(coro):
+ return asyncio.run(coro)
+
+
+def test_custom_non_whisper_repo_is_rejected_before_download(monkeypatch):
+ started: list = []
+ validated: list = []
+
+ def fake_validate(model, hf_token = None):
+ validated.append(model)
+ raise SttModelCompatibilityError(
+ f"STT model '{model}' is not a compatible Transformers Whisper model."
+ )
+
+ def fake_download(model, hf_token = None):
+ started.append(model)
+
+ monkeypatch.setattr(stt_module, "validate_remote_model", fake_validate)
+ monkeypatch.setattr(stt_module, "start_model_download", fake_download)
+
+ with pytest.raises(HTTPException) as excinfo:
+ _run(
+ ri.stt_download(
+ SttLoadRequest(model = "owner/chat-model", engine = "transformers"),
+ current_subject = "tester",
+ hf_token = None,
+ )
+ )
+
+ assert excinfo.value.status_code == 422
+ assert validated == ["owner/chat-model"]
+ # The download never starts for a repo that failed the Whisper check.
+ assert started == []
+
+
+def test_validated_transformers_repo_downloads(monkeypatch):
+ started: list = []
+ revision = "a" * 40
+
+ monkeypatch.setattr(
+ stt_module,
+ "validate_remote_model",
+ lambda model, hf_token = None: {"model": model, "revision": revision},
+ )
+ monkeypatch.setattr(
+ stt_module,
+ "start_model_download",
+ lambda model, hf_token = None, revision = None: started.append((model, revision)),
+ )
+ monkeypatch.setattr(stt_module, "download_status", lambda: {"downloading": True})
+
+ resp = _run(
+ ri.stt_download(
+ SttLoadRequest(model = "owner/real-whisper", engine = "transformers"),
+ current_subject = "tester",
+ hf_token = None,
+ )
+ )
+
+ assert resp.status_code == 200
+ assert started == [("owner/real-whisper", revision)]
+
+
+def test_gguf_engine_skips_the_transformers_repo_check(monkeypatch):
+ started: list = []
+
+ def fail_if_called(model, hf_token = None):
+ raise AssertionError("GGUF downloads must not run the Transformers repo check")
+
+ # whisper-server present, so the GGUF request stays on the GGUF engine.
+ monkeypatch.setattr(ggml_module, "is_available", lambda: True)
+ monkeypatch.setattr(stt_module, "validate_remote_model", fail_if_called)
+ monkeypatch.setattr(
+ ggml_module, "start_model_download", lambda model, hf_token = None: started.append(model)
+ )
+ monkeypatch.setattr(ggml_module, "download_status", lambda: {"downloading": True})
+
+ resp = _run(
+ ri.stt_download(
+ SttLoadRequest(model = "small", engine = "gguf"),
+ current_subject = "tester",
+ hf_token = None,
+ )
+ )
+
+ assert resp.status_code == 200
+ assert started == ["small"]
+
+
+def test_resolve_serving_stt_engine_falls_back_when_whisper_server_absent(monkeypatch):
+ # A curated GGUF request downgrades to Transformers when whisper-server is not
+ # installed (both engines serve curated ids), but stays GGUF when it is.
+ monkeypatch.setattr(ggml_module, "is_available", lambda: False)
+ assert ri._resolve_serving_stt_engine("gguf") == "transformers"
+ monkeypatch.setattr(ggml_module, "is_available", lambda: True)
+ assert ri._resolve_serving_stt_engine("gguf") == "gguf"
+ # Transformers is unaffected by whisper-server availability.
+ monkeypatch.setattr(ggml_module, "is_available", lambda: False)
+ assert ri._resolve_serving_stt_engine("transformers") == "transformers"
+
+
+def test_gguf_download_falls_back_to_transformers_when_server_absent(monkeypatch):
+ """Selecting the default curated model on a host without whisper-server must
+ download through the Transformers engine, not 501/dead-end on GGUF."""
+ gguf_started: list = []
+ tf_started: list = []
+
+ monkeypatch.setattr(ggml_module, "is_available", lambda: False) # no whisper-server
+ # validate_remote_model no-ops curated ids in production; keep it a no-op here.
+ monkeypatch.setattr(
+ stt_module, "validate_remote_model", lambda model, hf_token = None: {"model": model}
+ )
+ monkeypatch.setattr(
+ stt_module,
+ "start_model_download",
+ lambda model, hf_token = None, revision = None: tf_started.append(model),
+ )
+ monkeypatch.setattr(stt_module, "download_status", lambda: {"downloading": True})
+ monkeypatch.setattr(
+ ggml_module,
+ "start_model_download",
+ lambda model, hf_token = None: gguf_started.append(model),
+ )
+
+ resp = _run(
+ ri.stt_download(
+ SttLoadRequest(model = "small", engine = "gguf"),
+ current_subject = "tester",
+ hf_token = None,
+ )
+ )
+
+ assert resp.status_code == 200
+ assert tf_started == ["small"] # served by Transformers instead of dead-ending on GGUF
+ assert gguf_started == []
diff --git a/studio/backend/tests/test_stt_ggml_sidecar.py b/studio/backend/tests/test_stt_ggml_sidecar.py
new file mode 100644
index 00000000000..686fd8f546f
--- /dev/null
+++ b/studio/backend/tests/test_stt_ggml_sidecar.py
@@ -0,0 +1,780 @@
+# 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 http.server
+import io
+import json
+import os
+import sys
+import threading
+import time
+import wave
+from pathlib import Path
+
+import numpy as np
+import pytest
+
+import core.inference.stt_ggml_sidecar as ggml_module
+from core.inference.stt_ggml_sidecar import (
+ DEFAULT_GGML_STT_MODEL,
+ GGML_STT_MODELS,
+ GGML_STT_REPOS,
+ GgmlSttSidecar,
+ SttEngineUnavailableError,
+ find_whisper_server_binary,
+ resolve_ggml_model_id,
+)
+from core.inference.stt_sidecar import (
+ SttLanguageError,
+ SttLoadCancelledError,
+ SttModelIdError,
+ SttModelNotDownloadedError,
+ SttUnavailableError,
+)
+
+
[email protected](autouse = True)
+def isolate_runtime_and_stub_audio_decoder(monkeypatch, tmp_path):
+ """Unit tests exercise orchestration, not PyAV container parsing."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))
+ monkeypatch.delenv("WHISPER_SERVER_PATH", raising = False)
+ monkeypatch.delenv("UNSLOTH_WHISPER_CPP_PATH", raising = False)
+ monkeypatch.setenv("PATH", "")
+ monkeypatch.setattr(
+ ggml_module,
+ "_decode_audio_bounded",
+ lambda audio: np.zeros(16000, dtype = np.float32),
+ )
+
+
+# ---------------------------------------------------------------------------
+# Model id resolution
+# ---------------------------------------------------------------------------
+
+
+def test_curated_ids_resolve():
+ for model_id in GGML_STT_MODELS:
+ assert resolve_ggml_model_id(model_id) == model_id
+
+
+def test_default_model_resolves_from_none_and_blank():
+ assert resolve_ggml_model_id(None) == DEFAULT_GGML_STT_MODEL
+ assert resolve_ggml_model_id(" ") == DEFAULT_GGML_STT_MODEL
+
+
+def test_custom_repo_ids_are_rejected():
+ with pytest.raises(SttModelIdError):
+ resolve_ggml_model_id("owner/model")
+ with pytest.raises(SttModelIdError):
+ resolve_ggml_model_id("large-v2")
+
+
+def test_curated_ids_mirror_transformers_sidecar():
+ from core.inference.stt_sidecar import STT_MODELS
+ assert list(GGML_STT_MODELS.keys()) == list(STT_MODELS.keys())
+
+
+def test_curated_filenames_match_repo_naming():
+ # unslothai/whisper-<id>-GGUF hosts whisper-<id>.bin; keep the download
+ # filename in lockstep with the repo so it resolves instead of 404ing.
+ for model_id, repo in GGML_STT_REPOS.items():
+ expected = repo.split("/", 1)[1].removesuffix("-GGUF") + ".bin"
+ assert GGML_STT_MODELS[model_id] == expected
+
+
+# ---------------------------------------------------------------------------
+# Binary discovery
+# ---------------------------------------------------------------------------
+
+
+def test_env_binary_override_wins(monkeypatch, tmp_path):
+ binary = tmp_path / "whisper-server"
+ binary.write_text("#!/bin/sh\n")
+ binary.chmod(0o755) # find_whisper_server_binary requires an executable
+ monkeypatch.setenv("WHISPER_SERVER_PATH", str(binary))
+ assert find_whisper_server_binary() == str(binary)
+
+
+def test_env_dir_override_scans_layouts(monkeypatch, tmp_path):
+ monkeypatch.delenv("WHISPER_SERVER_PATH", raising = False)
+ build_bin = tmp_path / "build" / "bin"
+ build_bin.mkdir(parents = True)
+ binary = build_bin / "whisper-server"
+ binary.write_text("#!/bin/sh\n")
+ binary.chmod(0o755) # find_whisper_server_binary requires an executable
+ monkeypatch.setenv("UNSLOTH_WHISPER_CPP_PATH", str(tmp_path))
+ assert find_whisper_server_binary() == str(binary)
+
+
+def test_missing_binary_reports_unavailable(monkeypatch, tmp_path):
+ monkeypatch.delenv("WHISPER_SERVER_PATH", raising = False)
+ monkeypatch.setenv("UNSLOTH_WHISPER_CPP_PATH", str(tmp_path / "nope"))
+ monkeypatch.setattr(ggml_module, "_managed_whisper_cpp_dir", lambda: tmp_path / "gone")
+ monkeypatch.setattr(ggml_module.shutil, "which", lambda name: None)
+ assert find_whisper_server_binary() is None
+ assert not ggml_module.is_available()
+ with pytest.raises(SttEngineUnavailableError):
+ ggml_module.ensure_engine_available()
+
+
+def test_non_executable_binary_is_not_runnable(monkeypatch, tmp_path):
+ if sys.platform == "win32":
+ pytest.skip("X_OK is an existence check on Windows")
+ binary = tmp_path / "whisper-server"
+ binary.write_text("#!/bin/sh\n") # written but not chmod +x
+ monkeypatch.setenv("WHISPER_SERVER_PATH", str(binary))
+ monkeypatch.setattr(ggml_module.shutil, "which", lambda name: None)
+ assert find_whisper_server_binary() is None
+
+
+# ---------------------------------------------------------------------------
+# Slim-install launch guard
+# ---------------------------------------------------------------------------
+
+
+def _slim_install(
+ tmp_path,
+ *,
+ install_kind = "slim",
+ with_ggml = True,
+ linked_libraries = None,
+ backend = "cpu",
+ linked_runtime_directories = None,
+ runtime_wiring_version = None,
+) -> str:
+ """A managed-looking install tree: marker at the root, server in build/bin."""
+ install_dir = tmp_path / "whisper.cpp"
+ bin_dir = install_dir / "build" / "bin"
+ bin_dir.mkdir(parents = True)
+ binary = bin_dir / "whisper-server"
+ binary.write_text("#!/bin/sh\n")
+ binary.chmod(0o755)
+ marker: dict = {
+ "schema_version": 1,
+ "component": "whisper.cpp",
+ "release_tag": "v1.9.1-unsloth.1",
+ "backend": backend,
+ "paired_llama_tag": "b10069-mix-fb3d4ca",
+ }
+ if install_kind is not None:
+ marker["install_kind"] = install_kind
+ if linked_libraries is not None:
+ marker["linked_libraries"] = linked_libraries
+ if linked_runtime_directories is not None:
+ marker["linked_runtime_directories"] = linked_runtime_directories
+ for name in linked_runtime_directories:
+ catalog = bin_dir / name
+ catalog.mkdir()
+ (catalog / "kernel.dat").write_bytes(b"kernel")
+ if runtime_wiring_version is not None:
+ marker["runtime_wiring_version"] = runtime_wiring_version
+ (install_dir / "UNSLOTH_WHISPER_PREBUILT_INFO.json").write_text(json.dumps(marker))
+ if with_ggml:
+ names = (
+ ("ggml.dll", "ggml-base.dll")
+ if sys.platform == "win32"
+ else ("libggml.so.0", "libggml-base.so.0")
+ )
+ for name in names:
+ (bin_dir / name).write_bytes(b"ggml")
+ return str(binary)
+
+
+def test_slim_guard_flags_missing_ggml_links(monkeypatch, tmp_path):
+ # A slim marker whose linked ggml runtime is gone must read as engine
+ # unavailable (reinstall), never crash into a server launch.
+ binary = _slim_install(tmp_path, with_ggml = False)
+ assert ggml_module.slim_runtime_intact(binary) is False
+ monkeypatch.setattr(ggml_module, "find_whisper_server_binary", lambda: binary)
+ assert not ggml_module.is_available()
+ with pytest.raises(SttEngineUnavailableError, match = "ggml"):
+ ggml_module.ensure_engine_available()
+
+
+def test_slim_guard_passes_with_links_in_place(monkeypatch, tmp_path):
+ names = ["libggml.so.0", "libggml-base.so.0"]
+ binary = _slim_install(tmp_path, with_ggml = True, linked_libraries = names)
+ assert ggml_module.slim_runtime_intact(binary) is True
+ monkeypatch.setattr(ggml_module, "find_whisper_server_binary", lambda: binary)
+ assert ggml_module.ensure_engine_available() == binary
+
+
+def test_slim_guard_verifies_the_marker_linked_libraries(monkeypatch, tmp_path):
+ # New markers record the exact wired filenames; one missing name flips the
+ # install to unavailable even when the legacy core ggml names are present.
+ names = ["libggml.dylib", "libggml-base.dylib", "libggml-metal.dylib"]
+ binary = _slim_install(tmp_path, with_ggml = True, linked_libraries = names)
+ bin_dir = Path(binary).parent
+ for name in names[:-1]:
+ (bin_dir / name).write_bytes(b"ggml")
+ assert ggml_module.slim_runtime_intact(binary) is False # metal dylib absent
+ (bin_dir / names[-1]).write_bytes(b"ggml")
+ assert ggml_module.slim_runtime_intact(binary) is True
+ monkeypatch.setattr(ggml_module, "find_whisper_server_binary", lambda: binary)
+ assert ggml_module.ensure_engine_available() == binary
+
+
+def test_slim_guard_malformed_authoritative_marker_fails_closed(tmp_path):
+ for bad in ("not-a-list", [], [1, 2]):
+ root = tmp_path / f"case_{type(bad).__name__}_{len(str(bad))}"
+ root.mkdir()
+ binary = _slim_install(root, with_ggml = True, linked_libraries = bad)
+ assert ggml_module.slim_runtime_intact(binary) is False
+
+
+def test_slim_guard_prefers_authoritative_root_marker(tmp_path):
+ names = ["libggml.so.0", "libggml-base.so.0"]
+ binary = _slim_install(tmp_path, with_ggml = True, linked_libraries = names)
+ packaging_marker = Path(binary).parent / "UNSLOTH_WHISPER_PREBUILT_INFO.json"
+ packaging_marker.write_text(json.dumps({"backend": "slim", "release_tag": "packaging"}))
+ assert ggml_module._whisper_install_marker(binary)["install_kind"] == "slim"
+ assert ggml_module.slim_runtime_intact(binary) is True
+
+
+def test_slim_guard_rejects_invalid_root_even_with_inner_marker(tmp_path):
+ binary = _slim_install(tmp_path, with_ggml = True, linked_libraries = ["libggml.so.0"])
+ root_marker = Path(binary).parents[2] / "UNSLOTH_WHISPER_PREBUILT_INFO.json"
+ root_marker.write_text("not json")
+ (Path(binary).parent / root_marker.name).write_text(json.dumps({"backend": "slim"}))
+ assert ggml_module.slim_runtime_intact(binary) is False
+
+
+def test_slim_guard_rejects_missing_rocm_catalog(tmp_path):
+ names = ["libggml.so.0", "libggml-base.so.0", "libggml-hip.so"]
+ binary = _slim_install(
+ tmp_path,
+ linked_libraries = names,
+ backend = "rocm",
+ linked_runtime_directories = ["hipblaslt", "rocblas"],
+ runtime_wiring_version = 2,
+ )
+ bin_dir = Path(binary).parent
+ (bin_dir / "libggml-hip.so").write_bytes(b"ggml")
+ assert ggml_module.slim_runtime_intact(binary) is True
+ (bin_dir / "rocblas" / "kernel.dat").unlink()
+ assert ggml_module.slim_runtime_intact(binary) is False
+
+
+def test_slim_guard_accepts_windows_rocm_dll_overlay(monkeypatch, tmp_path):
+ monkeypatch.setattr(ggml_module.sys, "platform", "win32")
+ names = ["ggml.dll", "ggml-base.dll", "ggml-hip.dll", "amdhip64.dll"]
+ binary = _slim_install(
+ tmp_path,
+ linked_libraries = names,
+ backend = "rocm",
+ linked_runtime_directories = [],
+ runtime_wiring_version = 2,
+ )
+ for name in names:
+ (Path(binary).parent / name).write_bytes(b"dll")
+ assert ggml_module.slim_runtime_intact(binary) is True
+
+
+def test_slim_guard_ignores_fat_and_markerless_installs(tmp_path):
+ # Fat installs carry their own ggml; no marker means source/custom build.
+ fat = _slim_install(tmp_path / "fat", install_kind = None, with_ggml = False)
+ assert ggml_module.slim_runtime_intact(fat) is True
+ bare = tmp_path / "bare" / "whisper-server"
+ bare.parent.mkdir(parents = True)
+ bare.write_text("#!/bin/sh\n")
+ assert ggml_module.slim_runtime_intact(str(bare)) is True
+
+
+# ---------------------------------------------------------------------------
+# whisper-server child-process environment
+# ---------------------------------------------------------------------------
+
+
+def _loader_path_var() -> str:
+ return {"win32": "PATH", "darwin": "DYLD_LIBRARY_PATH"}.get(sys.platform, "LD_LIBRARY_PATH")
+
+
+def test_child_env_scrubs_secrets_and_adds_lib_dir(monkeypatch, tmp_path):
+ monkeypatch.setenv("HF_TOKEN", "secret-token") # exact name
+ monkeypatch.setenv("MY_API_KEY", "nope") # marker substring
+ monkeypatch.setenv("HTTPS_PROXY", "http://u:p@px:8080") # url-name
+ monkeypatch.setenv("SOME_REMOTE", "https://u:pw@host/repo") # url-userinfo value
+ monkeypatch.setenv("STT_KEEPME", "keep") # benign
+ binary = tmp_path / "whisper-server"
+ binary.write_text("#!/bin/sh\n")
+ env = ggml_module._whisper_server_child_env(str(binary))
+ for scrubbed in ("HF_TOKEN", "MY_API_KEY", "HTTPS_PROXY", "SOME_REMOTE"):
+ assert scrubbed not in env
+ assert env.get("STT_KEEPME") == "keep"
+ assert str(tmp_path.resolve()) in env[_loader_path_var()].split(os.pathsep)
+
+
+def test_child_env_isolates_home_and_cred_locations(monkeypatch, tmp_path):
+ # The downloaded server must not see the real home (token caches live
+ # there) nor explicit cred-store pointers like HF_HOME / NETRC.
+ monkeypatch.setenv("HOME", "/real/home")
+ monkeypatch.setenv("HF_HOME", "/real/hf")
+ monkeypatch.setenv("NETRC", "/real/.netrc")
+ monkeypatch.setattr(ggml_module, "_managed_whisper_cpp_dir", lambda: tmp_path / "managed")
+ binary = tmp_path / "whisper-server"
+ binary.write_text("#!/bin/sh\n")
+ env = ggml_module._whisper_server_child_env(str(binary))
+ assert env["HOME"] == str(tmp_path / "managed" / ".child_home")
+ assert "HF_HOME" not in env
+ assert "NETRC" not in env
+ assert (tmp_path / "managed" / ".child_home").is_dir()
+
+
+def test_child_env_wsl_rocm_prepends_system_hip(monkeypatch, tmp_path):
+ if sys.platform != "linux":
+ pytest.skip("WSL ROCm library precedence is Linux-only")
+ rocm = tmp_path / "rocm-lib"
+ rocm.mkdir()
+ bindir = tmp_path / "bin"
+ bindir.mkdir()
+ binary = bindir / "whisper-server"
+ binary.write_text("#!/bin/sh\n")
+ monkeypatch.setattr(ggml_module, "_wsl_system_rocm_lib_dirs", lambda: [str(rocm)])
+ env = ggml_module._whisper_server_child_env(str(binary))
+ parts = env["LD_LIBRARY_PATH"].split(os.pathsep)
+ assert parts[0] == str(rocm.resolve()) # system HIP wins
+ assert str(bindir.resolve()) in parts # bundle libs still present
+ assert env.get("HSA_ENABLE_DXG_DETECTION") == "1"
+
+
+def test_child_env_adds_cuda_runtime_dirs_for_cuda_bundle(monkeypatch, tmp_path):
+ # Versioned CUDA backend modules are valid too. They still need the
+ # CUDA-from-PyTorch wheel dirs for libcudart/libcublas at launch.
+ if sys.platform == "darwin":
+ pytest.skip("no CUDA on macOS")
+ import utils.prebuilt.runtime_libs as rl
+
+ bindir = tmp_path / "bin"
+ bindir.mkdir()
+ (bindir / "whisper-server").write_text("#!/bin/sh\n")
+ module_name = "ggml-cuda.dll" if sys.platform == "win32" else "libggml-cuda.so.0"
+ (bindir / module_name).write_text("")
+ cuda_dir = tmp_path / "nvidia" / "cuda_runtime" / "lib"
+ cuda_dir.mkdir(parents = True)
+ monkeypatch.setattr(rl, "python_runtime_dirs", lambda: [str(cuda_dir)])
+ env = ggml_module._whisper_server_child_env(str(bindir / "whisper-server"))
+ parts = env[_loader_path_var()].split(os.pathsep)
+ assert str(bindir.resolve()) in parts
+ assert str(cuda_dir.resolve()) in parts
+ assert parts.index(str(bindir.resolve())) < parts.index(str(cuda_dir.resolve()))
+
+
+def test_child_env_omits_cuda_runtime_dirs_for_cpu_bundle(monkeypatch, tmp_path):
+ # No libggml-cuda.so beside the binary -> a static CPU/Metal bundle -> the CUDA
+ # wheel discovery must not run and must not touch the loader path.
+ if sys.platform == "darwin":
+ pytest.skip("no CUDA on macOS")
+ import utils.prebuilt.runtime_libs as rl
+
+ bindir = tmp_path / "bin"
+ bindir.mkdir()
+ (bindir / "whisper-server").write_text("#!/bin/sh\n")
+ cuda_dir = tmp_path / "nvidia" / "cuda_runtime" / "lib"
+ cuda_dir.mkdir(parents = True)
+ called = {"n": 0}
+
+ def _fake_dirs():
+ called["n"] += 1
+ return [str(cuda_dir)]
+
+ monkeypatch.setattr(rl, "python_runtime_dirs", _fake_dirs)
+ env = ggml_module._whisper_server_child_env(str(bindir / "whisper-server"))
+ parts = env[_loader_path_var()].split(os.pathsep)
+ assert str(cuda_dir.resolve()) not in parts
+ assert called["n"] == 0
+
+
+def test_engine_unavailable_is_stt_unavailable():
+ # Routes map SttUnavailableError to HTTP 501; the engine error must share it.
+ assert issubclass(SttEngineUnavailableError, SttUnavailableError)
+
+
+# ---------------------------------------------------------------------------
+# WAV packaging
+# ---------------------------------------------------------------------------
+
+
+def test_pcm_to_wav_bytes_shape_and_rate():
+ pcm = np.zeros(3200, dtype = np.float32)
+ data = ggml_module._pcm_to_wav_bytes(pcm)
+ with wave.open(io.BytesIO(data)) as w:
+ assert w.getnchannels() == 1
+ assert w.getsampwidth() == 2
+ assert w.getframerate() == 16000
+ assert w.getnframes() == 3200
+
+
+def test_pcm_to_wav_bytes_clips_out_of_range():
+ pcm = np.array([2.0, -2.0], dtype = np.float32)
+ data = ggml_module._pcm_to_wav_bytes(pcm)
+ with wave.open(io.BytesIO(data)) as w:
+ frames = np.frombuffer(w.readframes(2), dtype = "<i2")
+ assert frames[0] == 32767
+ assert frames[1] == -32767
+
+
+# ---------------------------------------------------------------------------
+# Sidecar orchestration
+# ---------------------------------------------------------------------------
+
+
+def _available(monkeypatch):
+ monkeypatch.setattr(ggml_module, "find_whisper_server_binary", lambda: "/bin/echo")
+
+
+def test_transcribe_requires_engine(monkeypatch):
+ monkeypatch.setattr(ggml_module, "find_whisper_server_binary", lambda: None)
+ sidecar = GgmlSttSidecar()
+ with pytest.raises(SttEngineUnavailableError):
+ sidecar.transcribe(b"RIFF")
+
+
+def test_transcribe_rejects_unknown_language(monkeypatch):
+ _available(monkeypatch)
+ sidecar = GgmlSttSidecar()
+ with pytest.raises(SttLanguageError):
+ sidecar.transcribe(b"RIFF", model = "small", language = "xx-QQ")
+
+
+def test_load_requires_downloaded_model(monkeypatch):
+ _available(monkeypatch)
+ monkeypatch.setattr(ggml_module, "_cached_model_path", lambda model_id: None)
+ sidecar = GgmlSttSidecar()
+ with pytest.raises(SttModelNotDownloadedError):
+ sidecar.load("small")
+
+
+def test_unloaded_sidecar_reports_nothing_resident():
+ sidecar = GgmlSttSidecar()
+ assert sidecar.loaded_model is None
+ assert sidecar.device is None
+ assert sidecar.is_loading() is False
+ sidecar.unload() # no-op, must not raise
+
+
+def test_update_maintenance_unloads_and_blocks_new_loads(monkeypatch):
+ class FakeProcess:
+ pid = 4242
+
+ def __init__(self):
+ self.running = True
+
+ def poll(self):
+ return None if self.running else 0
+
+ def terminate(self):
+ self.running = False
+
+ def wait(self, timeout = None):
+ return 0
+
+ monkeypatch.setattr(ggml_module, "forget_pid", lambda _pid: None)
+ sidecar = GgmlSttSidecar()
+ sidecar._process = FakeProcess()
+ sidecar._model_id = "small"
+
+ with sidecar.update_maintenance() as model_was_active:
+ assert model_was_active is True
+ assert sidecar.loaded_model is None
+ with pytest.raises(SttEngineUnavailableError, match = "being updated"):
+ sidecar.load("small")
+
+ assert sidecar._update_in_progress is False
+
+
+def test_server_pid_is_tracked_for_parent_lifetime(monkeypatch):
+ # The spawned server must be adopted for the terminate_all backstop and
+ # forgotten once this sidecar has reaped it.
+ _available(monkeypatch)
+ monkeypatch.setattr(ggml_module, "_cached_model_path", lambda model_id: "/tmp/ggml.bin")
+
+ class FakeProcess:
+ pid = 4242
+
+ def __init__(self, *args, **kwargs):
+ self.terminated = False
+
+ def poll(self):
+ return 1 if self.terminated else None
+
+ def terminate(self):
+ self.terminated = True
+
+ def wait(self, timeout = None):
+ return 0
+
+ events = []
+ monkeypatch.setattr(ggml_module.subprocess, "Popen", FakeProcess)
+ monkeypatch.setattr(ggml_module, "adopt_pid", lambda pid: events.append(("adopt", pid)))
+ monkeypatch.setattr(ggml_module, "forget_pid", lambda pid: events.append(("forget", pid)))
+ monkeypatch.setattr(
+ GgmlSttSidecar,
+ "_wait_for_server",
+ staticmethod(lambda process, port, cancel_event = None: None),
+ )
+
+ sidecar = GgmlSttSidecar()
+ sidecar.load("small")
+ assert events == [("adopt", 4242)]
+ sidecar.unload()
+ assert events == [("adopt", 4242), ("forget", 4242)]
+
+
+def test_training_forces_whisper_server_off_gpu(monkeypatch):
+ # Mirror the Transformers sidecar: keep whisper.cpp on CPU during training
+ # so a mid-training dictation cannot reclaim the VRAM training just freed.
+ _available(monkeypatch)
+ monkeypatch.setattr(ggml_module, "_cached_model_path", lambda model_id: "/tmp/ggml.bin")
+ commands: list[list[str]] = []
+
+ class FakeProcess:
+ pid = 4242
+
+ def __init__(self, command, *args, **kwargs):
+ commands.append(command)
+
+ def poll(self):
+ return None
+
+ def terminate(self):
+ pass
+
+ def wait(self, timeout = None):
+ return 0
+
+ monkeypatch.setattr(ggml_module.subprocess, "Popen", FakeProcess)
+ monkeypatch.setattr(ggml_module, "adopt_pid", lambda pid: None)
+ monkeypatch.setattr(ggml_module, "forget_pid", lambda pid: None)
+ monkeypatch.setattr(
+ GgmlSttSidecar,
+ "_wait_for_server",
+ staticmethod(lambda process, port, cancel_event = None: None),
+ )
+
+ monkeypatch.setattr(ggml_module, "_training_active", lambda: False)
+ idle = GgmlSttSidecar()
+ idle.load("small")
+ assert "--no-gpu" not in commands[0]
+ assert idle.is_loading() is False
+ idle.unload()
+
+ monkeypatch.setattr(ggml_module, "_training_active", lambda: True)
+ training = GgmlSttSidecar()
+ training.load("small")
+ assert "--no-gpu" in commands[1]
+ training.unload()
+
+
+def test_cpu_root_marker_forces_no_gpu_despite_inner_packaging_marker(monkeypatch, tmp_path):
+ names = ["libggml.so.0", "libggml-base.so.0"]
+ binary = _slim_install(tmp_path, with_ggml = True, linked_libraries = names)
+ (Path(binary).parent / "UNSLOTH_WHISPER_PREBUILT_INFO.json").write_text(
+ json.dumps({"backend": "slim"})
+ )
+ monkeypatch.setattr(ggml_module, "find_whisper_server_binary", lambda: binary)
+ monkeypatch.setattr(ggml_module, "_cached_model_path", lambda model_id: "/tmp/ggml.bin")
+ commands: list[list[str]] = []
+
+ class FakeProcess:
+ pid = 4244
+
+ def __init__(self, command, *args, **kwargs):
+ commands.append(command)
+
+ def poll(self):
+ return None
+
+ def terminate(self):
+ pass
+
+ def wait(self, timeout = None):
+ return 0
+
+ monkeypatch.setattr(ggml_module.subprocess, "Popen", FakeProcess)
+ monkeypatch.setattr(ggml_module, "adopt_pid", lambda pid: None)
+ monkeypatch.setattr(ggml_module, "forget_pid", lambda pid: None)
+ monkeypatch.setattr(ggml_module, "_training_active", lambda: False)
+ monkeypatch.setattr(
+ GgmlSttSidecar,
+ "_wait_for_server",
+ staticmethod(lambda process, port, cancel_event = None: None),
+ )
+
+ sidecar = GgmlSttSidecar()
+ sidecar.load("small")
+ assert "--no-gpu" in commands[0]
+ sidecar.unload()
+
+
+def test_startup_is_cancellable_before_training(monkeypatch):
+ # A whisper-server still binding its (Metal/CUDA) backend must be preemptible
+ # so training coordination can stop it before admitting the run, instead of
+ # racing an allocating subprocess.
+ _available(monkeypatch)
+ monkeypatch.setattr(ggml_module, "_cached_model_path", lambda model_id: "/tmp/ggml.bin")
+
+ class FakeProcess:
+ pid = 4243
+
+ def __init__(self, *args, **kwargs):
+ self.terminated = False
+ self.killed = False
+
+ def poll(self):
+ return -15 if (self.terminated or self.killed) else None
+
+ def terminate(self):
+ self.terminated = True
+
+ def kill(self):
+ self.killed = True
+
+ def wait(self, timeout = None):
+ return 0
+
+ monkeypatch.setattr(ggml_module.subprocess, "Popen", FakeProcess)
+ monkeypatch.setattr(ggml_module, "adopt_pid", lambda pid: None)
+ monkeypatch.setattr(ggml_module, "forget_pid", lambda pid: None)
+
+ # The server never reports ready, so _wait_for_server loops until cancelled.
+ def never_ready(req, timeout = None):
+ raise OSError("connection refused")
+
+ monkeypatch.setattr(ggml_module.urllib.request, "urlopen", never_ready)
+
+ sidecar = GgmlSttSidecar()
+ result: dict = {}
+
+ def _load():
+ try:
+ sidecar.load("small")
+ result["ok"] = True
+ except Exception as exc: # noqa: BLE001 - recorded for the assertion below
+ result["error"] = exc
+
+ thread = threading.Thread(target = _load)
+ thread.start()
+ try:
+ deadline = time.monotonic() + 5
+ while time.monotonic() < deadline and not sidecar.is_loading():
+ time.sleep(0.01)
+ assert sidecar.is_loading() is True
+ assert sidecar.cancel_pending_load() is True
+ # Blocks until the cancelled startup has been reaped and the lock freed.
+ sidecar.wait_for_load_to_settle()
+ finally:
+ thread.join(timeout = 5)
+
+ assert thread.is_alive() is False
+ assert isinstance(result.get("error"), SttLoadCancelledError)
+ assert sidecar.is_loading() is False
+ assert sidecar.loaded_model is None
+
+
+class _FakeWhisperHandler(http.server.BaseHTTPRequestHandler):
+ """Stands in for whisper-server's /inference endpoint."""
+
+ response_text = "Hello world.\n Second line."
+
+ def do_POST(self):
+ length = int(self.headers.get("Content-Length", "0"))
+ self.rfile.read(length)
+ body = json.dumps({"text": self.response_text}).encode()
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *args):
+ pass
+
+
+def fake_whisper_server():
+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _FakeWhisperHandler)
+ thread = threading.Thread(target = server.serve_forever, daemon = True)
+ thread.start()
+ yield server.server_address[1]
+ server.shutdown()
+
+
+def test_transcribe_joins_segments_one_line(monkeypatch, fake_whisper_server):
+ _available(monkeypatch)
+ monkeypatch.setattr(ggml_module, "_cached_model_path", lambda model_id: "/tmp/ggml.bin")
+ sidecar = GgmlSttSidecar()
+
+ def fake_load(model = None):
+ sidecar._port = fake_whisper_server
+ sidecar._model_id = ggml_module.resolve_ggml_model_id(model)
+
+ monkeypatch.setattr(sidecar, "load", fake_load)
+ result = sidecar.transcribe(b"RIFF", model = "small", language = "en", fast = True)
+ assert result["text"] == "Hello world. Second line."
+ assert result["language"] == "en"
+ assert result["model"] == "small"
+ assert result["duration"] == pytest.approx(1.0)
+
+
+def test_transcribe_maps_bad_payload_to_decode_error(monkeypatch, fake_whisper_server):
+ _available(monkeypatch)
+ monkeypatch.setattr(ggml_module, "_cached_model_path", lambda model_id: "/tmp/ggml.bin")
+ monkeypatch.setattr(_FakeWhisperHandler, "response_text", None)
+ sidecar = GgmlSttSidecar()
+
+ def fake_load(model = None):
+ sidecar._port = fake_whisper_server
+ sidecar._model_id = ggml_module.resolve_ggml_model_id(model)
+
+ monkeypatch.setattr(sidecar, "load", fake_load)
+ from core.inference.stt_sidecar import SttAudioDecodeError
+
+ with pytest.raises(SttAudioDecodeError):
+ sidecar.transcribe(b"RIFF", model = "small")
+
+
+def test_beam_size_matches_fast_flag(monkeypatch, fake_whisper_server):
+ _available(monkeypatch)
+ monkeypatch.setattr(ggml_module, "_cached_model_path", lambda model_id: "/tmp/ggml.bin")
+ seen: list[bytes] = []
+
+ orig_post = _FakeWhisperHandler.do_POST
+
+ def capture_post(handler):
+ length = int(handler.headers.get("Content-Length", "0"))
+ body = handler.rfile.read(length)
+ seen.append(body)
+ payload = json.dumps({"text": "ok"}).encode()
+ handler.send_response(200)
+ handler.send_header("Content-Type", "application/json")
+ handler.send_header("Content-Length", str(len(payload)))
+ handler.end_headers()
+ handler.wfile.write(payload)
+
+ monkeypatch.setattr(_FakeWhisperHandler, "do_POST", capture_post)
+ try:
+ sidecar = GgmlSttSidecar()
+
+ def fake_load(model = None):
+ sidecar._port = fake_whisper_server
+ sidecar._model_id = ggml_module.resolve_ggml_model_id(model)
+
+ monkeypatch.setattr(sidecar, "load", fake_load)
+ sidecar.transcribe(b"RIFF", model = "small", fast = True)
+ sidecar.transcribe(b"RIFF", model = "small", fast = False)
+ finally:
+ _FakeWhisperHandler.do_POST = orig_post
+ assert b'name="beam_size"\r\n\r\n1' in seen[0]
+ assert b'name="beam_size"\r\n\r\n5' in seen[1]
+ # Dictation defaults to deterministic decoding.
+ assert b'name="temperature"\r\n\r\n0.0' in seen[0]
+
+
+def test_download_rejects_custom_ids():
+ with pytest.raises(SttModelIdError):
+ ggml_module.start_model_download("owner/model")
+
+
+def test_download_status_idle_shape():
+ status = ggml_module.download_status()
+ assert set(status) >= {"downloading", "model", "error"}
diff --git a/studio/backend/tests/test_stt_review_fixes.py b/studio/backend/tests/test_stt_review_fixes.py
new file mode 100644
index 00000000000..e4495506a35
--- /dev/null
+++ b/studio/backend/tests/test_stt_review_fixes.py
@@ -0,0 +1,219 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Regressions for a fresh review pass on the local STT dictation feature:
+
+1. Curated GGUF dictation repos (unslothai/whisper-*-GGUF) must be hidden from
+ chat pickers, not just their Transformers safetensors companions.
+2. The GGUF sidecar's loaded_model/device status accessors must be lock-free so
+ they never block behind an in-flight transcription (which holds self._lock).
+3. A "gguf" unload on a host without whisper-server must target the Transformers
+ fallback that actually served it, and unload-all must attempt both backends
+ even if one raises.
+4. free_stt_model_for_training must free the GGUF sidecar even when the
+ Transformers unload raises (independent exception boundaries).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import sys
+import threading
+from pathlib import Path
+
+import pytest
+from fastapi import HTTPException
+
+_BACKEND_ROOT = Path(__file__).resolve().parents[1]
+if str(_BACKEND_ROOT) not in sys.path:
+ sys.path.insert(0, str(_BACKEND_ROOT))
+
+
+# 1. Hidden-model GGUF companions ------------------------------------------------
+def test_curated_gguf_dictation_repos_are_hidden():
+ from utils.hidden_models import _HIDDEN_STT_REPO_IDS, is_hidden_model
+ for repo in (
+ "unslothai/whisper-tiny-GGUF",
+ "unslothai/whisper-base-GGUF",
+ "unslothai/whisper-small-GGUF",
+ "unslothai/whisper-large-v3-turbo-GGUF",
+ "unslothai/whisper-large-v3-GGUF",
+ ):
+ assert repo in _HIDDEN_STT_REPO_IDS
+ assert is_hidden_model(repo) is True
+ # Case-insensitive, matching how the cache stores the repo id.
+ assert is_hidden_model(repo.lower()) is True
+
+ # A same-prefix but genuinely different repo is NOT hidden.
+ assert is_hidden_model("unslothai/whisper-large-v3-GGUF-finetune") is False
+
+
+# 2. GGUF status accessors are lock-free ----------------------------------------
+def test_gguf_status_accessors_do_not_block_on_the_inference_lock():
+ from core.inference.stt_ggml_sidecar import GgmlSttSidecar
+
+ sidecar = GgmlSttSidecar()
+
+ class _AliveProc:
+ pid = 4321
+
+ def poll(self):
+ return None # still running
+
+ sidecar._process = _AliveProc()
+ sidecar._model_id = "small"
+
+ holder_has_lock = threading.Event()
+ release = threading.Event()
+
+ def _hold_inference_lock():
+ # Mimic transcribe() holding self._lock across the whole HTTP call.
+ with sidecar._lock:
+ holder_has_lock.set()
+ release.wait(timeout = 5)
+
+ holder = threading.Thread(target = _hold_inference_lock)
+ holder.start()
+ assert holder_has_lock.wait(timeout = 5)
+
+ result: dict = {}
+
+ def _read_status():
+ result["model"] = sidecar.loaded_model
+ result["device"] = sidecar.device
+
+ reader = threading.Thread(target = _read_status)
+ reader.start()
+ reader.join(timeout = 2)
+ blocked = reader.is_alive()
+
+ release.set()
+ holder.join(timeout = 5)
+ reader.join(timeout = 5)
+
+ assert not blocked, "loaded_model/device blocked on self._lock (should be lock-free)"
+ assert result == {"model": "small", "device": "whisper.cpp"}
+
+
+def test_process_alive_snapshots_process_against_concurrent_unload():
+ # _process_alive() must read self._process exactly once. The lock-free
+ # readers (loaded_model/device) can run while unload() nulls self._process;
+ # the old `self._process is not None and self._process.poll() is None` read it
+ # twice, so a null landing between the two reads called None.poll(). A
+ # property that yields the live process on the first read and None afterwards
+ # reproduces that interleaving deterministically.
+ from core.inference.stt_ggml_sidecar import GgmlSttSidecar
+
+ class _AliveProc:
+ def poll(self):
+ return None # still running
+
+ live = _AliveProc()
+ reads = {"n": 0}
+
+ class _RacingSidecar(GgmlSttSidecar):
+ @property
+ def _process(self):
+ reads["n"] += 1
+ return live if reads["n"] == 1 else None
+
+ @_process.setter
+ def _process(self, value):
+ pass # __init__ assigns None; the property drives the read
+
+ sidecar = GgmlSttSidecar()
+ sidecar.__class__ = _RacingSidecar # data descriptor wins over the instance attr
+
+ # Snapshot fix: exactly one read, no AttributeError from a second None read.
+ assert sidecar._process_alive() is True
+ assert reads["n"] == 1
+
+
+# 3. Unload resolves through the serving engine + attempts every backend ---------
+def test_gguf_unload_targets_transformers_fallback_without_whisper_server(monkeypatch):
+ import core.inference.stt_ggml_sidecar as ggml_module
+ import routes.inference as ri
+
+ monkeypatch.setattr(ggml_module, "is_available", lambda: False) # no whisper-server
+
+ calls: list = []
+
+ class _Sidecar:
+ def __init__(self, name):
+ self.name = name
+
+ def unload(self):
+ calls.append(self.name)
+
+ monkeypatch.setattr(ri, "_stt_sidecar_for", lambda name: _Sidecar(name))
+
+ resp = asyncio.run(ri.stt_unload(engine = "gguf", current_subject = "tester"))
+ assert resp.status_code == 200
+ # gguf is served by the Transformers fallback here, so that is what unloads.
+ assert calls == ["transformers"]
+
+
+def test_unload_all_attempts_both_backends_even_when_one_fails(monkeypatch):
+ import routes.inference as ri
+
+ attempted: list = []
+
+ class _Sidecar:
+ def __init__(self, name):
+ self.name = name
+
+ def unload(self):
+ attempted.append(self.name)
+ if self.name == "transformers":
+ raise RuntimeError("boom")
+
+ monkeypatch.setattr(ri, "_stt_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"]
+
+
+# 4. free_stt_model_for_training isolates the two backends -----------------------
+def test_free_stt_frees_gguf_even_when_transformers_unload_raises(monkeypatch):
+ import routes.training_vram as tv
+
+ class _TransformersSidecar:
+ def is_loading(self):
+ return False
+
+ @property
+ def loaded_model(self):
+ return "whisper-small"
+
+ def unload(self):
+ raise RuntimeError("transformers unload failed")
+
+ class _GgmlSidecar:
+ def __init__(self):
+ self.unloaded = False
+
+ def is_loading(self):
+ return False
+
+ @property
+ def loaded_model(self):
+ return None if self.unloaded else "small"
+
+ def unload(self):
+ self.unloaded = True
+
+ ggml = _GgmlSidecar()
+ monkeypatch.setattr(
+ "core.inference.stt_sidecar.get_stt_sidecar", lambda: _TransformersSidecar()
+ )
+ monkeypatch.setattr("core.inference.stt_ggml_sidecar.get_ggml_stt_sidecar", lambda: ggml)
+
+ freed = tv.free_stt_model_for_training("test")
+
+ # The Transformers failure must not skip GGUF eviction.
+ assert ggml.unloaded is True
+ assert any("small" in entry for entry in freed)
diff --git a/studio/backend/tests/test_stt_review_fixes_2.py b/studio/backend/tests/test_stt_review_fixes_2.py
new file mode 100644
index 00000000000..130c43c9566
--- /dev/null
+++ b/studio/backend/tests/test_stt_review_fixes_2.py
@@ -0,0 +1,332 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Regressions for the second review pass on the local STT dictation feature:
+
+1. scripts/build_whisper_cpp.sh must not rm -rf a whisper.cpp/src tree under a
+ custom Studio home unless Studio itself created it (ownership marker), the
+ same policy studio/setup.sh applies before its destructive replacements.
+2. _snapshot_is_complete must validate every shard of a sharded PyTorch
+ (pytorch_model.bin.index.json) checkpoint, like the safetensors path.
+3. _snapshot_is_complete must require tokenizer assets (tokenizer.json or
+ vocab.json + merges.txt); weights + config alone decode to blank text.
+4. Custom-repo downloads must pin the revision validated beforehand and
+ restrict snapshot_download to the model/tokenizer/config/preprocessor file
+ classes (TOCTOU + unbounded-download hardening).
+5. The GGML sidecar's readiness probe must not treat an arbitrary local HTTP
+ responder as whisper-server (mic audio would be posted to it), and the port
+ reservation must stay held until just before spawn.
+"""
+
+from __future__ import annotations
+
+import http.server
+import json
+import os
+import socket
+import stat
+import subprocess
+import sys
+import threading
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+_BACKEND_ROOT = Path(__file__).resolve().parents[1]
+if str(_BACKEND_ROOT) not in sys.path:
+ sys.path.insert(0, str(_BACKEND_ROOT))
+
+import core.inference.stt_ggml_sidecar as ggml_module
+import core.inference.stt_sidecar as stt_sidecar_module
+from core.inference.stt_ggml_sidecar import GgmlSttSidecar, SttEngineUnavailableError
+from core.inference.stt_sidecar import validate_remote_model
+
+_BUILD_SCRIPT = _BACKEND_ROOT.parents[1] / "scripts" / "build_whisper_cpp.sh"
+
+
+# 1. build_whisper_cpp.sh ownership gate ----------------------------------------
+
+
+def _stub_tools(tmp_path: Path) -> dict:
+ """PATH with git/cmake stubs so the script never reaches a real build."""
+ bin_dir = tmp_path / "stub-bin"
+ bin_dir.mkdir(exist_ok = True)
+ for tool in ("git", "cmake"):
+ stub = bin_dir / tool
+ stub.write_text("#!/bin/sh\necho stub-%s-invoked >&2\nexit 1\n" % tool)
+ stub.chmod(stub.stat().st_mode | stat.S_IEXEC)
+ env = dict(os.environ)
+ env["PATH"] = f"{bin_dir}:{env['PATH']}"
+ return env
+
+
+def _run_build_script(env: dict) -> subprocess.CompletedProcess:
+ return subprocess.run(
+ ["sh", str(_BUILD_SCRIPT)],
+ env = env,
+ capture_output = True,
+ text = True,
+ timeout = 60,
+ )
+
+
+def test_build_script_refuses_unowned_dir_in_custom_studio_home(tmp_path):
+ home = tmp_path / "studio-home"
+ src = home / "whisper.cpp" / "src"
+ src.mkdir(parents = True)
+ user_file = src / "user-data.txt"
+ user_file.write_text("precious")
+
+ env = _stub_tools(tmp_path)
+ env["UNSLOTH_STUDIO_HOME"] = str(home)
+ result = _run_build_script(env)
+
+ assert result.returncode != 0
+ assert "not marked as an Unsloth-owned" in result.stderr
+ # The unowned tree, and the user's file inside it, survived untouched.
+ assert user_file.read_text() == "precious"
+
+
+def test_build_script_proceeds_when_marker_present(tmp_path):
+ home = tmp_path / "studio-home"
+ install = home / "whisper.cpp"
+ (install / "src").mkdir(parents = True)
+ (install / ".unsloth-studio-owned").write_text("")
+
+ env = _stub_tools(tmp_path)
+ env["UNSLOTH_STUDIO_HOME"] = str(home)
+ result = _run_build_script(env)
+
+ # Past the guard: it fails later at the stubbed git clone, not the gate.
+ assert "not marked as an Unsloth-owned" not in result.stderr
+ assert "stub-git-invoked" in result.stderr
+
+
+def test_build_script_marks_fresh_custom_install_dir(tmp_path):
+ home = tmp_path / "studio-home"
+ home.mkdir()
+
+ env = _stub_tools(tmp_path)
+ env["UNSLOTH_STUDIO_HOME"] = str(home)
+ _run_build_script(env)
+
+ # A directory the script creates is marked so re-runs stay allowed.
+ assert (home / "whisper.cpp" / ".unsloth-studio-owned").is_file()
+
+
+def test_build_script_keeps_legacy_home_behavior(tmp_path):
+ fake_home = tmp_path / "user-home"
+ src = fake_home / ".unsloth" / "whisper.cpp" / "src"
+ src.mkdir(parents = True)
+
+ env = _stub_tools(tmp_path)
+ env.pop("UNSLOTH_STUDIO_HOME", None)
+ env.pop("STUDIO_HOME", None)
+ env["HOME"] = str(fake_home)
+ result = _run_build_script(env)
+
+ # The legacy managed dir is always Studio-owned; no gate, straight to git.
+ assert "not marked as an Unsloth-owned" not in result.stderr
+ assert "stub-git-invoked" in result.stderr
+
+
+# 2 + 3. _snapshot_is_complete --------------------------------------------------
+
+
+def _base_snapshot(tmp_path: Path) -> Path:
+ snap = tmp_path / "snap"
+ snap.mkdir()
+ (snap / "config.json").write_text("{}")
+ (snap / "preprocessor_config.json").write_text("{}")
+ (snap / "tokenizer.json").write_text("{}")
+ return snap
+
+
+def test_sharded_pytorch_snapshot_requires_every_shard(tmp_path):
+ snap = _base_snapshot(tmp_path)
+ index = {
+ "weight_map": {
+ "a": "pytorch_model-00001-of-00002.bin",
+ "b": "pytorch_model-00002-of-00002.bin",
+ }
+ }
+ (snap / "pytorch_model.bin.index.json").write_text(json.dumps(index))
+ (snap / "pytorch_model-00001-of-00002.bin").write_bytes(b"w" * 8)
+
+ # One missing .bin shard must read as incomplete, like the safetensors path.
+ assert stt_sidecar_module._snapshot_is_complete(snap) is False
+
+ (snap / "pytorch_model-00002-of-00002.bin").write_bytes(b"w" * 8)
+ assert stt_sidecar_module._snapshot_is_complete(snap) is True
+
+
+def test_snapshot_without_tokenizer_assets_is_incomplete(tmp_path):
+ snap = _base_snapshot(tmp_path)
+ (snap / "model.safetensors").write_bytes(b"w" * 8)
+ assert stt_sidecar_module._snapshot_is_complete(snap) is True
+
+ # Weights + config but no tokenizer decodes to blank text; not complete.
+ (snap / "tokenizer.json").unlink()
+ assert stt_sidecar_module._snapshot_is_complete(snap) is False
+
+ # The slow vocab.json + merges.txt pair is an accepted alternative.
+ (snap / "vocab.json").write_text("{}")
+ assert stt_sidecar_module._snapshot_is_complete(snap) is False
+ (snap / "merges.txt").write_text("")
+ assert stt_sidecar_module._snapshot_is_complete(snap) is True
+
+
+# 4. Revision pinning and allow_patterns ----------------------------------------
+
+
+def test_validate_remote_model_returns_the_validated_revision(monkeypatch):
+ revision = "a" * 40
+
+ class _FakeApi:
+ def __init__(self, token = None):
+ pass
+
+ def model_info(
+ self,
+ repo,
+ expand = None,
+ timeout = None,
+ ):
+ return SimpleNamespace(config = {"model_type": "whisper"}, sha = revision)
+
+ import huggingface_hub
+
+ monkeypatch.setattr(huggingface_hub, "HfApi", _FakeApi)
+ result = validate_remote_model("someone/custom-whisper")
+ assert result["revision"] == revision
+
+
+def test_download_pins_revision_and_limits_patterns(monkeypatch):
+ captured = {}
+ validated_revision = "a" * 40
+ head_revision = "b" * 40
+
+ def fake_snapshot_download(**kwargs):
+ captured.update(kwargs)
+ return "/cached"
+
+ class _FakeApi:
+ def __init__(self, token = None):
+ pass
+
+ def model_info(
+ self,
+ repo,
+ revision = None,
+ files_metadata = None,
+ timeout = None,
+ ):
+ names = (
+ "config.json",
+ "preprocessor_config.json",
+ "tokenizer.json",
+ "model.safetensors",
+ )
+ siblings = [
+ SimpleNamespace(rfilename = name, size = 10, blob_id = name, lfs = None) for name in names
+ ]
+ return SimpleNamespace(siblings = siblings, sha = head_revision)
+
+ import huggingface_hub
+
+ monkeypatch.setattr(huggingface_hub, "HfApi", _FakeApi)
+ monkeypatch.setattr(huggingface_hub, "snapshot_download", fake_snapshot_download)
+
+ state = stt_sidecar_module._SnapshotDownloadState()
+ # The revision resolved at validation time wins over the current head.
+ state._run("someone/custom-whisper", None, revision = validated_revision)
+ assert captured["revision"] == validated_revision
+ patterns = captured["allow_patterns"]
+ assert "model.safetensors" in patterns and "tokenizer.json" in patterns
+ # No wildcard that would admit arbitrary repo contents.
+ assert "*" not in patterns
+
+ # Without a validated revision (curated repos), pin to the metadata head.
+ captured.clear()
+ state._run("someone/custom-whisper", None)
+ assert captured["revision"] == head_revision
+ assert captured["allow_patterns"]
+
+
+# 5. GGML readiness must identify whisper-server --------------------------------
+
+
+class _CannedHandler(http.server.BaseHTTPRequestHandler):
+ body = b""
+
+ def do_GET(self): # noqa: N802
+ payload = type(self).body
+ self.send_response(200)
+ self.send_header("Content-Length", str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+
+ def log_message(self, *args):
+ pass
+
+
+def _serve(body: bytes):
+ handler = type("Handler", (_CannedHandler,), {"body": body})
+ server = http.server.HTTPServer(("127.0.0.1", 0), handler)
+ thread = threading.Thread(target = server.serve_forever, daemon = True)
+ thread.start()
+ return server, server.server_address[1]
+
+
+def _fake_alive_process():
+ return SimpleNamespace(poll = lambda: None, pid = 999999)
+
+
+def test_wait_for_server_rejects_a_foreign_http_responder(monkeypatch):
+ server, port = _serve(b"<html>hello from some other local app</html>")
+ try:
+ monkeypatch.setattr(ggml_module, "_SERVER_START_TIMEOUT_SECONDS", 1.0)
+ with pytest.raises(SttEngineUnavailableError, match = "did not start in time"):
+ GgmlSttSidecar._wait_for_server(_fake_alive_process(), port)
+ finally:
+ server.shutdown()
+
+
+def test_wait_for_server_accepts_the_whisper_server_page(monkeypatch):
+ server, port = _serve(b"<html><title>Whisper.cpp Server</title></html>")
+ try:
+ monkeypatch.setattr(ggml_module, "_SERVER_START_TIMEOUT_SECONDS", 5.0)
+ GgmlSttSidecar._wait_for_server(_fake_alive_process(), port)
+ finally:
+ server.shutdown()
+
+
+def test_probe_requires_the_managed_child_to_be_alive():
+ server, port = _serve(b"whisper")
+ try:
+ dead = SimpleNamespace(poll = lambda: 0, pid = 999999)
+ assert GgmlSttSidecar._probe_is_whisper_server(dead, port) is False
+ assert GgmlSttSidecar._probe_is_whisper_server(_fake_alive_process(), port) is True
+ finally:
+ server.shutdown()
+
+
+def test_port_reservation_is_held_until_released():
+ reservation, port = GgmlSttSidecar._reserve_free_port()
+ try:
+ probe = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ try:
+ with pytest.raises(OSError):
+ probe.bind(("127.0.0.1", port))
+ finally:
+ probe.close()
+ finally:
+ reservation.close()
+ # Released right before spawn: the port becomes bindable for the child.
+ child = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ child.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ try:
+ child.bind(("127.0.0.1", port))
+ finally:
+ child.close()
diff --git a/studio/backend/tests/test_stt_sidecar.py b/studio/backend/tests/test_stt_sidecar.py
new file mode 100644
index 00000000000..3f78845ac75
--- /dev/null
+++ b/studio/backend/tests/test_stt_sidecar.py
@@ -0,0 +1,1262 @@
+# 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 gc
+import io
+import json
+import sys
+import threading
+import time
+import wave
+import weakref
+from pathlib import Path
+from types import SimpleNamespace
+
+import numpy as np
+import pytest
+
+import core.inference.stt_sidecar as stt_sidecar_module
+from core.inference.stt_sidecar import (
+ DEFAULT_STT_MODEL,
+ STT_MODELS,
+ SttAudioDecodeError,
+ SttAudioTooLongError,
+ SttLanguageError,
+ SttLoadCancelledError,
+ SttModelCompatibilityError,
+ SttModelIdError,
+ SttModelNotDownloadedError,
+ SttUnavailableError,
+ WhisperSttSidecar,
+ normalize_whisper_language,
+ resolve_model_id,
+ resolve_model_repo,
+ validate_remote_model,
+)
+
+_REAL_DECODE_AUDIO_BOUNDED = stt_sidecar_module._decode_audio_bounded
+_REAL_ENSURE_STT_AVAILABLE = stt_sidecar_module.ensure_stt_available
+_REAL_SNAPSHOT_IS_COMPLETE = stt_sidecar_module._snapshot_is_complete
+_REAL_FIND_COMPLETE_CACHED_SNAPSHOT = stt_sidecar_module._find_complete_cached_snapshot
+
+
[email protected](autouse = True)
+def stub_audio_decoder(monkeypatch):
+ """Unit tests below exercise orchestration, not PyAV container parsing."""
+ monkeypatch.setattr(
+ stt_sidecar_module,
+ "_decode_audio_bounded",
+ lambda _audio: np.zeros(8000, dtype = np.float32),
+ )
+ monkeypatch.setattr(
+ "huggingface_hub.snapshot_download",
+ lambda **_kwargs: "/cached/model",
+ )
+ monkeypatch.setattr(
+ stt_sidecar_module,
+ "_find_complete_cached_snapshot",
+ lambda _model: Path("/cached/model"),
+ )
+ # The stubbed snapshot path holds no files; snapshot-integrity tests
+ # restore the real check.
+ monkeypatch.setattr(stt_sidecar_module, "_snapshot_is_complete", lambda _snapshot: True)
+ # transcribe() gates on the runtime up front; treat it as present so these
+ # orchestration tests run without PyTorch/Transformers/PyAV installed.
+ # The runtime-specific tests restore the real check.
+ monkeypatch.setattr(stt_sidecar_module, "ensure_stt_available", lambda: None)
+
+
+class _CaptureInference:
+ """Stand-in for the model inference step; records how it was called."""
+
+ def __init__(
+ self,
+ text = "hello",
+ mutate = None,
+ ) -> None:
+ self.text = text
+ self.mutate = mutate
+ self.generate_kwargs = None
+
+ def __call__(self, model_id, decoded, generate_kwargs):
+ self.generate_kwargs = generate_kwargs
+ if self.mutate is not None:
+ self.mutate()
+ return self.text
+
+
+def test_five_curated_whisper_models_are_offered():
+ assert STT_MODELS == {
+ "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",
+ }
+ assert all(repo.startswith(("unsloth/", "unslothai/")) for repo in STT_MODELS.values())
+ assert DEFAULT_STT_MODEL in STT_MODELS
+
+
+def test_av_is_required_for_stt_availability(monkeypatch):
+ monkeypatch.setattr(stt_sidecar_module, "ensure_stt_available", _REAL_ENSURE_STT_AVAILABLE)
+ monkeypatch.setitem(sys.modules, "torch", SimpleNamespace())
+ monkeypatch.setitem(sys.modules, "transformers", SimpleNamespace())
+ monkeypatch.setitem(sys.modules, "av", None)
+
+ assert stt_sidecar_module.is_available() is False
+
+
+def test_transformers_is_required_for_stt_availability(monkeypatch):
+ monkeypatch.setattr(stt_sidecar_module, "ensure_stt_available", _REAL_ENSURE_STT_AVAILABLE)
+ monkeypatch.setitem(sys.modules, "torch", SimpleNamespace())
+ monkeypatch.setitem(sys.modules, "av", SimpleNamespace())
+ monkeypatch.setitem(sys.modules, "transformers", None)
+
+ assert stt_sidecar_module.is_available() is False
+
+
[email protected]("missing", ["transformers", "av"])
+def test_load_rejects_an_incomplete_stt_runtime(monkeypatch, missing):
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 0)
+ monkeypatch.setattr(stt_sidecar_module, "ensure_stt_available", _REAL_ENSURE_STT_AVAILABLE)
+ for module in ("torch", "transformers", "av"):
+ monkeypatch.setitem(sys.modules, module, SimpleNamespace())
+ monkeypatch.setitem(sys.modules, missing, None)
+ monkeypatch.setattr(
+ sidecar,
+ "_ensure_model_downloaded",
+ lambda _model: pytest.fail("runtime must be checked before the model cache"),
+ )
+
+ with pytest.raises(SttUnavailableError, match = "needs PyTorch, Transformers, and PyAV"):
+ sidecar.load("small")
+
+
+def test_model_id_accepts_defaults_and_custom_hub_repositories():
+ assert resolve_model_id("tiny") == "tiny"
+ assert resolve_model_id(None) == DEFAULT_STT_MODEL
+ assert resolve_model_id("large-v3") == "large-v3"
+ assert resolve_model_id("openai/whisper-medium") == "openai/whisper-medium"
+ assert resolve_model_repo("tiny") == "unsloth/whisper-tiny"
+ assert resolve_model_repo("openai/whisper-medium") == "openai/whisper-medium"
+
+
[email protected]("model", ["tiny-ish", "owner/model/extra", "../model", "owner/"])
+def test_invalid_custom_model_id_is_rejected(model):
+ with pytest.raises(SttModelIdError, match = "owner/model"):
+ resolve_model_id(model)
+
+
+def test_remote_custom_model_validation_requires_whisper_config(monkeypatch):
+ calls = []
+
+ class FakeApi:
+ def __init__(self, token):
+ calls.append(("token", token))
+
+ def model_info(self, repo, **kwargs):
+ calls.append(("model_info", repo, kwargs))
+ return SimpleNamespace(
+ sha = "a" * 40,
+ config = {
+ "model_type": "whisper",
+ "architectures": ["WhisperForConditionalGeneration"],
+ },
+ )
+
+ monkeypatch.setattr("huggingface_hub.HfApi", FakeApi)
+
+ result = validate_remote_model("owner/custom-whisper", "hf_private")
+
+ assert result == {
+ "model": "owner/custom-whisper",
+ "repo": "owner/custom-whisper",
+ "revision": "a" * 40,
+ }
+ assert calls == [
+ ("token", "hf_private"),
+ (
+ "model_info",
+ "owner/custom-whisper",
+ {"expand": ["config", "sha"], "timeout": 10},
+ ),
+ ]
+
+
+def test_remote_custom_model_validation_rejects_non_whisper(monkeypatch):
+ class FakeApi:
+ def __init__(self, token):
+ assert token is False
+
+ def model_info(self, _repo, **_kwargs):
+ return SimpleNamespace(
+ config = {
+ "model_type": "llama",
+ "architectures": ["LlamaForCausalLM"],
+ }
+ )
+
+ monkeypatch.setattr("huggingface_hub.HfApi", FakeApi)
+
+ with pytest.raises(SttModelCompatibilityError, match = "not a compatible"):
+ validate_remote_model("owner/chat-model")
+
+
+def test_remote_custom_model_validation_requires_an_immutable_sha(monkeypatch):
+ class FakeApi:
+ def __init__(self, token):
+ pass
+
+ def model_info(self, _repo, **_kwargs):
+ return SimpleNamespace(sha = None, config = {"model_type": "whisper"})
+
+ monkeypatch.setattr("huggingface_hub.HfApi", FakeApi)
+
+ with pytest.raises(SttModelCompatibilityError, match = "immutable revision"):
+ validate_remote_model("owner/custom-whisper")
+
+
+def test_fast_transcription_uses_greedy_decoding(monkeypatch):
+ sidecar = WhisperSttSidecar()
+ infer = _CaptureInference()
+ monkeypatch.setattr(sidecar, "_transcribe_decoded", infer)
+
+ result = sidecar.transcribe(b"encoded audio", language = "en", fast = True)
+
+ assert result["text"] == "hello"
+ assert result["duration"] == 0.5
+ assert result["model"] == DEFAULT_STT_MODEL
+ assert infer.generate_kwargs == {
+ "task": "transcribe",
+ "condition_on_prev_tokens": False,
+ "num_beams": 1,
+ "language": "en",
+ }
+
+
+def test_accurate_transcription_keeps_beam_search_default(monkeypatch):
+ sidecar = WhisperSttSidecar()
+ infer = _CaptureInference()
+ monkeypatch.setattr(sidecar, "_transcribe_decoded", infer)
+
+ sidecar.transcribe(b"encoded audio")
+
+ assert infer.generate_kwargs == {
+ "task": "transcribe",
+ "condition_on_prev_tokens": False,
+ "num_beams": 5,
+ }
+
+
+ ("language", "expected"),
+ [
+ (None, None),
+ ("auto", None),
+ ("en-US", "en"),
+ ("en-GB", "en"),
+ ("zh-CN", "zh"),
+ ("ja-JP", "ja"),
+ ("ko-KR", "ko"),
+ ("es-ES", "es"),
+ ("fr-FR", "fr"),
+ ("de-DE", "de"),
+ ("it-IT", "it"),
+ ("pt_BR", "pt"),
+ ("ru-RU", "ru"),
+ ("hi-IN", "hi"),
+ ("ar-SA", "ar"),
+ ("iw-IL", "he"),
+ ("nb-NO", "no"),
+ ],
+)
+def test_normalize_whisper_language_accepts_bcp47(language, expected):
+ assert normalize_whisper_language(language) == expected
+
+
+def test_transcription_normalizes_region_qualified_language(monkeypatch):
+ sidecar = WhisperSttSidecar()
+ infer = _CaptureInference()
+ monkeypatch.setattr(sidecar, "_transcribe_decoded", infer)
+
+ sidecar.transcribe(b"encoded audio", language = "fr-FR")
+
+ assert infer.generate_kwargs["language"] == "fr"
+
+
+def test_english_only_model_rejects_non_english_before_decode(monkeypatch, tmp_path):
+ (tmp_path / "config.json").write_text('{"model_type": "whisper"}')
+ (tmp_path / "generation_config.json").write_text('{"is_multilingual": false}')
+ sidecar = WhisperSttSidecar()
+
+ def should_not_decode(_audio):
+ pytest.fail("English-only language mismatch must be rejected before decode")
+
+ monkeypatch.setattr(
+ stt_sidecar_module,
+ "_find_complete_cached_snapshot",
+ lambda _model: tmp_path,
+ )
+ monkeypatch.setattr(stt_sidecar_module, "_decode_audio_bounded", should_not_decode)
+
+ with pytest.raises(SttLanguageError, match = "English-only"):
+ sidecar.transcribe(
+ b"encoded audio",
+ model = "owner/whisper-small.en",
+ language = "fr-FR",
+ )
+
+
+def test_english_only_model_omits_forbidden_generation_controls(monkeypatch):
+ calls = []
+
+ class FakeTensor:
+ def to(self, *_args):
+ return self
+
+ class FakeProcessor:
+ def __call__(self, *_args, **_kwargs):
+ return SimpleNamespace(input_features = FakeTensor())
+
+ def batch_decode(self, *_args, **_kwargs):
+ return ["hello"]
+
+ class FakeModel:
+ dtype = None
+ device = "cpu"
+ generation_config = SimpleNamespace(is_multilingual = False)
+
+ def generate(self, _features, **kwargs):
+ calls.append(kwargs)
+ return [[1]]
+
+ class NoGrad:
+ def __enter__(self):
+ return None
+
+ def __exit__(self, *_args):
+ return False
+
+ monkeypatch.setitem(sys.modules, "torch", SimpleNamespace(no_grad = NoGrad))
+ sidecar = WhisperSttSidecar()
+ monkeypatch.setattr(sidecar, "load", lambda _model: (FakeModel(), FakeProcessor()))
+
+ text = sidecar._transcribe_decoded(
+ "owner/whisper-small.en",
+ np.zeros(160, dtype = np.float32),
+ {
+ "task": "transcribe",
+ "language": "en",
+ "condition_on_prev_tokens": False,
+ "num_beams": 1,
+ },
+ )
+
+ assert text == "hello"
+ assert calls == [{"condition_on_prev_tokens": False, "num_beams": 1}]
+
+
+def test_unknown_language_is_rejected_before_decode_or_model_load(monkeypatch):
+ sidecar = WhisperSttSidecar()
+
+ def should_not_run(*_args, **_kwargs):
+ pytest.fail("unknown language must be rejected before expensive work")
+
+ monkeypatch.setattr(stt_sidecar_module, "_known_whisper_languages", lambda: frozenset({"en"}))
+ monkeypatch.setattr(stt_sidecar_module, "_decode_audio_bounded", should_not_run)
+ monkeypatch.setattr(sidecar, "_transcribe_decoded", should_not_run)
+
+ with pytest.raises(SttLanguageError, match = "is not supported"):
+ sidecar.transcribe(b"encoded audio", language = "xx-YY")
+
+
+def test_unknown_language_is_not_reported_as_bad_audio(monkeypatch):
+ sidecar = WhisperSttSidecar()
+ infer = _CaptureInference()
+ monkeypatch.setattr(sidecar, "_transcribe_decoded", infer)
+ monkeypatch.setattr(stt_sidecar_module, "_known_whisper_languages", lambda: frozenset({"en"}))
+
+ with pytest.raises(SttLanguageError, match = "is not supported"):
+ sidecar.transcribe(b"encoded audio", language = "xx-YY")
+
+
+def test_transcription_result_keeps_requested_model_id_during_switch(monkeypatch):
+ sidecar = WhisperSttSidecar()
+
+ # Simulate another request changing the mutable resident-model state after
+ # this request pinned its own model id.
+ infer = _CaptureInference(mutate = lambda: setattr(sidecar, "_model_id", "large-v3"))
+ monkeypatch.setattr(sidecar, "_transcribe_decoded", infer)
+
+ result = sidecar.transcribe(b"encoded audio", model = "small")
+
+ assert result["model"] == "small"
+
+
+def test_inference_failure_propagates(monkeypatch):
+ sidecar = WhisperSttSidecar()
+
+ def boom(*_args, **_kwargs):
+ raise RuntimeError("inference failed")
+
+ monkeypatch.setattr(sidecar, "_transcribe_decoded", boom)
+
+ with pytest.raises(RuntimeError, match = "inference failed"):
+ sidecar.transcribe(b"encoded audio")
+
+
+class _FakeModel:
+ def to(self, *_args, **_kwargs):
+ return self
+
+ def eval(self):
+ return self
+
+
+class _FakeTimer:
+ def __init__(
+ self,
+ interval,
+ function,
+ args = (),
+ kwargs = None,
+ ):
+ self.interval = interval
+ self.function = function
+ self.args = args
+ self.kwargs = kwargs or {}
+ self.cancelled = False
+ self.daemon = False
+ self.started = False
+
+ def start(self):
+ self.started = True
+
+ def cancel(self):
+ self.cancelled = True
+
+ def fire(self):
+ self.function(*self.args, **self.kwargs)
+
+
+def _install_fake_torch(monkeypatch):
+ fake_torch = SimpleNamespace(
+ float16 = "float16",
+ float32 = "float32",
+ device = lambda value: value,
+ cuda = SimpleNamespace(is_available = lambda: False),
+ backends = SimpleNamespace(mps = SimpleNamespace(is_available = lambda: False)),
+ )
+ monkeypatch.setitem(sys.modules, "torch", fake_torch)
+ monkeypatch.setitem(sys.modules, "av", SimpleNamespace())
+ return fake_torch
+
+
+def test_load_uses_model_hub_cache_without_implicit_download(monkeypatch):
+ calls = []
+ _install_fake_torch(monkeypatch)
+
+ class FakeWhisperForConditionalGeneration:
+ @classmethod
+ def from_pretrained(cls, repo, **kwargs):
+ calls.append(("model", repo, kwargs))
+ return _FakeModel()
+
+ class FakeWhisperProcessor:
+ @classmethod
+ def from_pretrained(cls, repo, **kwargs):
+ calls.append(("processor", repo, kwargs))
+ return object()
+
+ monkeypatch.setitem(
+ sys.modules,
+ "transformers",
+ SimpleNamespace(
+ WhisperForConditionalGeneration = FakeWhisperForConditionalGeneration,
+ WhisperProcessor = FakeWhisperProcessor,
+ ),
+ )
+ monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda: ("cpu", "float32"))
+
+ WhisperSttSidecar(keep_alive_seconds = 0).load("small")
+
+ assert {(kind, repo) for kind, repo, _ in calls} == {
+ ("processor", "/cached/model"),
+ ("model", "/cached/model"),
+ }
+ # Never fetch weights implicitly; the Model Hub owns downloads.
+ assert all(kwargs.get("local_files_only") is True for _, _, kwargs in calls)
+
+
+def test_model_cache_preflight_uses_shared_offline_resolver(monkeypatch):
+ seen = []
+ monkeypatch.setattr(
+ stt_sidecar_module,
+ "_find_complete_cached_snapshot",
+ lambda model: seen.append(model) or Path("/cached/model"),
+ )
+
+ WhisperSttSidecar(keep_alive_seconds = 0)._ensure_model_downloaded("small")
+
+ assert seen == ["small"]
+
+
+def test_model_cache_preflight_reports_missing_snapshot(monkeypatch):
+ monkeypatch.setattr(stt_sidecar_module, "_find_complete_cached_snapshot", lambda _model: None)
+
+ with pytest.raises(SttModelNotDownloadedError, match = "not downloaded"):
+ WhisperSttSidecar(keep_alive_seconds = 0)._ensure_model_downloaded("large-v3")
+
+
+def test_load_reports_model_hub_cache_miss(monkeypatch):
+ _install_fake_torch(monkeypatch)
+
+ class LocalEntryNotFoundError(RuntimeError):
+ pass
+
+ class MissingWhisperProcessor:
+ @classmethod
+ def from_pretrained(cls, *_args, **_kwargs):
+ raise LocalEntryNotFoundError("not cached")
+
+ monkeypatch.setitem(
+ sys.modules,
+ "transformers",
+ SimpleNamespace(
+ WhisperForConditionalGeneration = object,
+ WhisperProcessor = MissingWhisperProcessor,
+ ),
+ )
+ monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda: ("cpu", "float32"))
+
+ with pytest.raises(SttModelNotDownloadedError, match = "not downloaded"):
+ WhisperSttSidecar(keep_alive_seconds = 0).load("large-v3")
+
+
+def test_unavailable_runtime_is_rejected_before_audio_decode(monkeypatch):
+ sidecar = WhisperSttSidecar()
+
+ def unavailable() -> None:
+ raise SttUnavailableError("needs PyTorch, Transformers, and PyAV")
+
+ def should_not_decode(_audio):
+ pytest.fail("runtime must be checked before audio decode")
+
+ monkeypatch.setattr(stt_sidecar_module, "ensure_stt_available", unavailable)
+ monkeypatch.setattr(stt_sidecar_module, "_decode_audio_bounded", should_not_decode)
+
+ with pytest.raises(SttUnavailableError, match = "needs PyTorch"):
+ sidecar.transcribe(b"encoded audio", model = "small")
+
+
+def test_missing_model_is_rejected_before_audio_decode(monkeypatch):
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 0)
+
+ def missing(_model_id):
+ raise SttModelNotDownloadedError("not downloaded")
+
+ def should_not_decode(_audio):
+ pytest.fail("missing models must be rejected before audio decode")
+
+ monkeypatch.setattr(sidecar, "_ensure_model_downloaded", missing, raising = False)
+ monkeypatch.setattr(stt_sidecar_module, "_decode_audio_bounded", should_not_decode)
+
+ with pytest.raises(SttModelNotDownloadedError, match = "not downloaded"):
+ sidecar.transcribe(b"encoded audio", model = "large-v3")
+
+
+def test_missing_model_switch_keeps_resident_model(monkeypatch):
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 0)
+ resident = object()
+ sidecar._engine = resident
+ sidecar._model_id = "small"
+ sidecar._device = "cpu"
+
+ def missing(_model_id):
+ raise SttModelNotDownloadedError("not downloaded")
+
+ monkeypatch.setattr(sidecar, "_ensure_model_downloaded", missing, raising = False)
+ monkeypatch.setattr(stt_sidecar_module, "ensure_stt_available", lambda: None)
+ monkeypatch.setattr(
+ sidecar,
+ "_build_model",
+ lambda *_args: pytest.fail("cache miss must be detected before model replacement"),
+ )
+ _install_fake_torch(monkeypatch)
+
+ with pytest.raises(SttModelNotDownloadedError, match = "not downloaded"):
+ sidecar.load("large-v3")
+
+ assert sidecar._engine is resident
+ assert sidecar.loaded_model == "small"
+
+
+def test_incompatible_custom_model_switch_keeps_resident_model(monkeypatch, tmp_path):
+ (tmp_path / "config.json").write_text(
+ '{"model_type": "llama", "architectures": ["LlamaForCausalLM"]}'
+ )
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 0)
+ resident = (object(), object())
+ sidecar._engine = resident
+ sidecar._model_id = "small"
+ sidecar._device = "cpu"
+ _install_fake_torch(monkeypatch)
+ monkeypatch.setattr(
+ stt_sidecar_module,
+ "_find_complete_cached_snapshot",
+ lambda _model: tmp_path,
+ )
+
+ with pytest.raises(SttModelCompatibilityError, match = "not a compatible"):
+ sidecar.load("owner/chat-model")
+
+ assert sidecar._engine is resident
+ assert sidecar.loaded_model == "small"
+
+
+def test_loaded_model_stays_warm_until_idle_timer_fires(monkeypatch):
+ timers = []
+ _install_fake_torch(monkeypatch)
+
+ def make_timer(*args, **kwargs):
+ timer = _FakeTimer(*args, **kwargs)
+ timers.append(timer)
+ return timer
+
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 300)
+ monkeypatch.setattr(stt_sidecar_module, "ensure_stt_available", lambda: None)
+ monkeypatch.setattr(stt_sidecar_module.threading, "Timer", make_timer)
+ monkeypatch.setattr(sidecar, "_build_model", lambda *_args: (object(), object()))
+ monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda: ("cpu", "float32"))
+
+ sidecar.load("small")
+
+ assert sidecar.loaded_model == "small"
+ assert timers[-1].interval == 300
+ assert timers[-1].started
+
+ timers[-1].fire()
+
+ assert sidecar.loaded_model is None
+
+
+def test_reusing_loaded_model_refreshes_idle_timer(monkeypatch):
+ timers = []
+ _install_fake_torch(monkeypatch)
+
+ def make_timer(*args, **kwargs):
+ timer = _FakeTimer(*args, **kwargs)
+ timers.append(timer)
+ return timer
+
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 300)
+ monkeypatch.setattr(stt_sidecar_module, "ensure_stt_available", lambda: None)
+ monkeypatch.setattr(stt_sidecar_module.threading, "Timer", make_timer)
+ monkeypatch.setattr(sidecar, "_build_model", lambda *_args: (object(), object()))
+ monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda: ("cpu", "float32"))
+
+ sidecar.load("small")
+ first = timers[-1]
+ sidecar.load("small")
+
+ assert first.cancelled
+ assert timers[-1] is not first
+
+ first.fire()
+
+ assert sidecar.loaded_model == "small"
+
+
+def test_unload_waits_for_inflight_transcription(monkeypatch):
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 0)
+ started = threading.Event()
+ release = threading.Event()
+
+ def transcribe(*_args):
+ started.set()
+ assert release.wait(timeout = 2)
+ return "hello"
+
+ monkeypatch.setattr(sidecar, "_transcribe_decoded", transcribe)
+ transcribe_thread = threading.Thread(target = lambda: sidecar.transcribe(b"audio"))
+ transcribe_thread.start()
+ assert started.wait(timeout = 2)
+
+ unload_thread = threading.Thread(target = sidecar.unload)
+ unload_thread.start()
+ time.sleep(0.02)
+ assert unload_thread.is_alive()
+
+ release.set()
+ transcribe_thread.join(timeout = 2)
+ unload_thread.join(timeout = 2)
+
+ assert not transcribe_thread.is_alive()
+ assert not unload_thread.is_alive()
+
+
+def test_new_stt_load_uses_cpu_while_training(monkeypatch):
+ fake_torch = SimpleNamespace(
+ float16 = "float16",
+ float32 = "float32",
+ cuda = SimpleNamespace(is_available = lambda: True),
+ backends = SimpleNamespace(mps = SimpleNamespace(is_available = lambda: True)),
+ )
+ monkeypatch.setitem(sys.modules, "torch", fake_torch)
+ monkeypatch.setattr(stt_sidecar_module, "_training_active", lambda: True)
+
+ assert stt_sidecar_module._pick_device() == ("cpu", "float32")
+
+
+def test_new_stt_load_prefers_cuda_when_training_is_idle(monkeypatch):
+ fake_torch = SimpleNamespace(
+ float16 = "float16",
+ float32 = "float32",
+ cuda = SimpleNamespace(is_available = lambda: True),
+ backends = SimpleNamespace(mps = SimpleNamespace(is_available = lambda: False)),
+ )
+ monkeypatch.setitem(sys.modules, "torch", fake_torch)
+ monkeypatch.setattr(stt_sidecar_module, "_training_active", lambda: False)
+
+ assert stt_sidecar_module._pick_device() == ("cuda", "float16")
+
+
+def test_new_stt_load_prefers_mps_when_cuda_is_unavailable(monkeypatch):
+ fake_torch = SimpleNamespace(
+ float16 = "float16",
+ float32 = "float32",
+ cuda = SimpleNamespace(is_available = lambda: False),
+ backends = SimpleNamespace(mps = SimpleNamespace(is_available = lambda: True)),
+ )
+ monkeypatch.setitem(sys.modules, "torch", fake_torch)
+ monkeypatch.setattr(stt_sidecar_module, "_training_active", lambda: False)
+
+ assert stt_sidecar_module._pick_device() == ("mps", "float32")
+
+
+def test_new_stt_load_uses_cpu_without_accelerators(monkeypatch):
+ fake_torch = SimpleNamespace(
+ float16 = "float16",
+ float32 = "float32",
+ cuda = SimpleNamespace(is_available = lambda: False),
+ backends = SimpleNamespace(mps = SimpleNamespace(is_available = lambda: False)),
+ )
+ monkeypatch.setitem(sys.modules, "torch", fake_torch)
+ monkeypatch.setattr(stt_sidecar_module, "_training_active", lambda: False)
+
+ assert stt_sidecar_module._pick_device() == ("cpu", "float32")
+
+
+def test_accelerator_load_failure_retries_on_cpu(monkeypatch):
+ fake_torch = _install_fake_torch(monkeypatch)
+ calls = []
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 0)
+ monkeypatch.setattr(stt_sidecar_module, "ensure_stt_available", lambda: None)
+
+ def build(_repo, device, dtype, _cancel_event):
+ calls.append((device, dtype))
+ if device == "cuda":
+ raise RuntimeError("accelerator allocation failed")
+ return object(), object()
+
+ monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda: ("cuda", "float16"))
+ monkeypatch.setattr(sidecar, "_build_model", build)
+
+ sidecar.load("small")
+
+ assert calls == [("cuda", "float16"), ("cpu", fake_torch.float32)]
+ assert sidecar.device == "cpu"
+
+
+def test_pending_load_can_be_cancelled_without_waiting_for_model_lock(monkeypatch):
+ _install_fake_torch(monkeypatch)
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 0)
+ build_started = threading.Event()
+ release_build = threading.Event()
+ errors = []
+
+ def build(_repo, _device, _dtype, _cancel_event):
+ build_started.set()
+ assert release_build.wait(timeout = 2)
+ return object(), object()
+
+ def run_load():
+ try:
+ sidecar.load("small")
+ except Exception as exc:
+ errors.append(exc)
+
+ monkeypatch.setattr(stt_sidecar_module, "ensure_stt_available", lambda: None)
+ monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda: ("cpu", "float32"))
+ monkeypatch.setattr(sidecar, "_build_model", build)
+
+ load_thread = threading.Thread(target = run_load)
+ load_thread.start()
+ assert build_started.wait(timeout = 2)
+
+ result = []
+ cancel_thread = threading.Thread(target = lambda: result.append(sidecar.cancel_pending_load()))
+ cancel_thread.start()
+ cancel_thread.join(timeout = 2)
+
+ assert not cancel_thread.is_alive()
+ assert result == [True]
+ assert load_thread.is_alive()
+
+ release_build.set()
+ load_thread.join(timeout = 2)
+
+ assert not load_thread.is_alive()
+ assert len(errors) == 1
+ assert isinstance(errors[0], SttLoadCancelledError)
+ assert sidecar.loaded_model is None
+ assert sidecar.is_loading() is False
+
+
+def _wav_bytes(sample_count: int, sample_rate: int = 16000) -> bytes:
+ output = io.BytesIO()
+ with wave.open(output, "wb") as wav:
+ wav.setnchannels(1)
+ wav.setsampwidth(2)
+ wav.setframerate(sample_rate)
+ wav.writeframes(np.zeros(sample_count, dtype = np.int16).tobytes())
+ return output.getvalue()
+
+
+def test_bounded_decoder_returns_16khz_float_pcm():
+ pytest.importorskip("av")
+
+ decoded = _REAL_DECODE_AUDIO_BOUNDED(_wav_bytes(1600))
+
+ assert decoded.dtype == np.float32
+ assert decoded.shape == (1600,)
+
+
+def test_bounded_decoder_rejects_audio_as_soon_as_sample_cap_is_crossed(monkeypatch):
+ pytest.importorskip("av")
+ monkeypatch.setattr(stt_sidecar_module, "_MAX_AUDIO_SECONDS", 1)
+
+ with pytest.raises(SttAudioTooLongError, match = "Audio must"):
+ _REAL_DECODE_AUDIO_BOUNDED(_wav_bytes(16001))
+
+
+def test_bounded_decoder_resamples_stereo_48khz_to_mono_16khz():
+ pytest.importorskip("av")
+ output = io.BytesIO()
+ frames = np.zeros((4800, 2), dtype = np.int16)
+ with wave.open(output, "wb") as wav:
+ wav.setnchannels(2)
+ wav.setsampwidth(2)
+ wav.setframerate(48000)
+ wav.writeframes(frames.tobytes())
+
+ decoded = _REAL_DECODE_AUDIO_BOUNDED(output.getvalue())
+
+ assert decoded.dtype == np.float32
+ assert 1590 <= len(decoded) <= 1610
+
+
[email protected]("audio", [b"", b"not audio", b"RIFF\x00\x00"])
+def test_bounded_decoder_rejects_malformed_audio(audio):
+ pytest.importorskip("av")
+
+ with pytest.raises(SttAudioDecodeError, match = "Could not decode"):
+ _REAL_DECODE_AUDIO_BOUNDED(audio)
+
+
+def test_bounded_decoder_rejects_container_without_audio_stream(monkeypatch):
+ class FakeFFmpegError(Exception):
+ pass
+
+ class FakeResampler:
+ def __init__(self, **_kwargs):
+ pass
+
+ class FakeFifo:
+ samples = 0
+
+ class FakeContainer:
+ streams = SimpleNamespace(audio = [])
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return False
+
+ fake_av = SimpleNamespace(
+ audio = SimpleNamespace(
+ resampler = SimpleNamespace(AudioResampler = FakeResampler),
+ fifo = SimpleNamespace(AudioFifo = FakeFifo),
+ ),
+ open = lambda *_args, **_kwargs: FakeContainer(),
+ )
+ monkeypatch.setitem(sys.modules, "av", fake_av)
+ monkeypatch.setitem(
+ sys.modules,
+ "av.error",
+ SimpleNamespace(
+ FFmpegError = FakeFFmpegError,
+ InvalidDataError = FakeFFmpegError,
+ ),
+ )
+
+ with pytest.raises(SttAudioDecodeError, match = "Could not decode"):
+ _REAL_DECODE_AUDIO_BOUNDED(b"video-only")
+
+
+def test_unload_releases_model_and_device():
+ sidecar = WhisperSttSidecar()
+ sidecar._engine = object()
+ sidecar._model_id = "small"
+ sidecar._device = "cpu"
+
+ sidecar.unload()
+
+ assert sidecar.loaded_model is None
+ assert sidecar.device is None
+
+
+# ---------------------------------------------------------------------------
+# Snapshot download tracking
+# ---------------------------------------------------------------------------
+
+
+def _write_complete_snapshot(snapshot: Path, *, model_type: str = "whisper") -> None:
+ snapshot.mkdir(parents = True, exist_ok = True)
+ (snapshot / "config.json").write_text(json.dumps({"model_type": model_type}))
+ (snapshot / "preprocessor_config.json").write_text("{}")
+ (snapshot / "tokenizer.json").write_text("{}")
+ (snapshot / "model.safetensors").write_bytes(b"weights")
+
+
+def _sibling(name: str, size: int, key: str):
+ return SimpleNamespace(rfilename = name, size = size, blob_id = key, lfs = None)
+
+
+def test_sha_snapshot_without_main_ref_survives_restart_and_cache_relocation(monkeypatch, tmp_path):
+ repo = "openai/whisper-tiny.en"
+ revision = "c" * 40
+ studio_home = tmp_path / "studio"
+ first_cache = tmp_path / "first-hub"
+ second_cache = tmp_path / "second-hub"
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(studio_home))
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ monkeypatch.setattr(stt_sidecar_module, "_snapshot_is_complete", _REAL_SNAPSHOT_IS_COMPLETE)
+ monkeypatch.setattr(
+ stt_sidecar_module,
+ "_find_complete_cached_snapshot",
+ _REAL_FIND_COMPLETE_CACHED_SNAPSHOT,
+ )
+
+ first = first_cache / "models--openai--whisper-tiny.en" / "snapshots" / revision
+ _write_complete_snapshot(first)
+ monkeypatch.setenv("HF_HUB_CACHE", str(first_cache))
+ stt_sidecar_module._write_revision_record(repo, revision)
+ assert stt_sidecar_module._find_complete_cached_snapshot(repo) == first.resolve()
+
+ second = second_cache / "models--openai--whisper-tiny.en" / "snapshots" / revision
+ _write_complete_snapshot(second)
+ monkeypatch.setenv("HF_HUB_CACHE", str(second_cache))
+ assert stt_sidecar_module._find_complete_cached_snapshot(repo) == second.resolve()
+
+
+def test_corrupt_or_escaping_revision_record_is_ignored(monkeypatch, tmp_path):
+ repo = "openai/whisper-tiny.en"
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))
+ monkeypatch.setenv("HF_HUB_CACHE", str(tmp_path / "hub"))
+ monkeypatch.setattr(
+ stt_sidecar_module,
+ "_find_complete_cached_snapshot",
+ _REAL_FIND_COMPLETE_CACHED_SNAPSHOT,
+ )
+ record = stt_sidecar_module._revision_record_path(repo)
+ record.parent.mkdir(parents = True)
+ record.write_text(json.dumps({"version": 1, "repo": repo, "revision": "../../outside"}))
+ assert stt_sidecar_module._find_complete_cached_snapshot(repo) is None
+
+ outside = tmp_path / "outside"
+ _write_complete_snapshot(outside)
+ snapshots = tmp_path / "hub" / "models--openai--whisper-tiny.en" / "snapshots"
+ snapshots.mkdir(parents = True)
+ (snapshots / ("d" * 40)).symlink_to(outside, target_is_directory = True)
+ assert stt_sidecar_module._find_complete_cached_snapshot(repo) is None
+
+
+def test_adapter_only_snapshot_is_not_complete(tmp_path):
+ (tmp_path / "config.json").write_text('{"model_type": "whisper"}')
+ (tmp_path / "preprocessor_config.json").write_text("{}")
+ (tmp_path / "tokenizer.json").write_text("{}")
+ (tmp_path / "adapter_model.safetensors").write_bytes(b"adapter")
+
+ assert _REAL_SNAPSHOT_IS_COMPLETE(tmp_path) is False
+
+
+def test_snapshot_selection_prefers_safetensors_and_excludes_unrelated_files():
+ info = SimpleNamespace(
+ siblings = [
+ _sibling("config.json", 10, "config"),
+ _sibling("preprocessor_config.json", 20, "preprocessor"),
+ _sibling("tokenizer.json", 30, "tokenizer"),
+ _sibling("model.safetensors", 100, "safe"),
+ _sibling("pytorch_model.bin", 110, "torch"),
+ _sibling("README.md", 1000, "readme"),
+ ]
+ )
+
+ selected = stt_sidecar_module._select_snapshot_files(
+ info, lambda _name: pytest.fail("unsharded selection must not load an index")
+ )
+
+ assert {item.path for item in selected} == {
+ "config.json",
+ "preprocessor_config.json",
+ "tokenizer.json",
+ "model.safetensors",
+ }
+ assert sum(item.size for item in selected) == 160
+
+
+def test_snapshot_selection_includes_every_indexed_shard():
+ info = SimpleNamespace(
+ siblings = [
+ _sibling("config.json", 10, "config"),
+ _sibling("model.safetensors.index.json", 5, "index"),
+ _sibling("model-00001-of-00002.safetensors", 50, "shard1"),
+ _sibling("model-00002-of-00002.safetensors", 60, "shard2"),
+ _sibling("pytorch_model.bin", 120, "torch"),
+ ]
+ )
+
+ selected = stt_sidecar_module._select_snapshot_files(
+ info,
+ lambda name: {
+ "weight_map": {
+ "a": "model-00001-of-00002.safetensors",
+ "b": "model-00002-of-00002.safetensors",
+ }
+ },
+ )
+
+ assert {item.path for item in selected} == {
+ "config.json",
+ "model.safetensors.index.json",
+ "model-00001-of-00002.safetensors",
+ "model-00002-of-00002.safetensors",
+ }
+
+
+def test_progress_counts_only_selected_blobs_and_caps_incomplete_files(monkeypatch, tmp_path):
+ monkeypatch.setenv("HF_HUB_CACHE", str(tmp_path / "hub"))
+ blobs = tmp_path / "hub" / "models--owner--whisper" / "blobs"
+ blobs.mkdir(parents = True)
+ (blobs / "one").write_bytes(b"x" * 10)
+ (blobs / "two.incomplete").write_bytes(b"x" * 30)
+ (blobs / "unrelated").write_bytes(b"x" * 1000)
+ state = stt_sidecar_module._SnapshotDownloadState()
+ state._repo = "owner/whisper"
+ state._selected_files = (
+ stt_sidecar_module._SelectedHubFile("config.json", 10, "one"),
+ stt_sidecar_module._SelectedHubFile("model.safetensors", 20, "two"),
+ )
+ state._total_bytes = 30
+ state._complete = True
+
+ status = state.status()
+
+ assert status["bytes_total"] == 30
+ assert status["bytes_done"] == 30
+
+
+def test_download_metadata_and_snapshot_use_the_same_revision(monkeypatch, tmp_path):
+ revision = "e" * 40
+ calls = []
+ siblings = [
+ _sibling("config.json", 10, "config"),
+ _sibling("preprocessor_config.json", 20, "preprocessor"),
+ _sibling("tokenizer.json", 30, "tokenizer"),
+ _sibling("model.safetensors", 100, "safe"),
+ _sibling("pytorch_model.bin", 110, "torch"),
+ ]
+
+ class FakeApi:
+ def __init__(self, token):
+ pass
+
+ def model_info(self, repo, **kwargs):
+ calls.append(("info", repo, kwargs))
+ return SimpleNamespace(sha = revision, siblings = siblings)
+
+ def fake_snapshot_download(**kwargs):
+ calls.append(("snapshot", kwargs))
+ return str(tmp_path)
+
+ monkeypatch.setattr("huggingface_hub.HfApi", FakeApi)
+ monkeypatch.setattr("huggingface_hub.snapshot_download", fake_snapshot_download)
+ monkeypatch.setattr(
+ "huggingface_hub.hf_hub_download",
+ lambda **_kwargs: pytest.fail("unsharded selection must not load an index"),
+ )
+ monkeypatch.setattr(stt_sidecar_module, "_snapshot_is_complete", lambda _path: True)
+ monkeypatch.setattr(stt_sidecar_module, "_write_revision_record", lambda *_args: None)
+ state = stt_sidecar_module._SnapshotDownloadState()
+
+ state._run("owner/whisper", None, revision)
+
+ assert calls[0] == (
+ "info",
+ "owner/whisper",
+ {"revision": revision, "files_metadata": True, "timeout": 30},
+ )
+ assert calls[1][0] == "snapshot"
+ assert calls[1][1]["revision"] == revision
+ assert "model.safetensors" in calls[1][1]["allow_patterns"]
+ assert "pytorch_model.bin" not in calls[1][1]["allow_patterns"]
+
+
+def test_download_status_is_idle_before_any_download():
+ state = stt_sidecar_module._SnapshotDownloadState()
+
+ status = state.status()
+
+ assert status == {
+ "downloading": False,
+ "model": None,
+ "error": None,
+ "bytes_total": None,
+ "bytes_done": None,
+ }
+
+
+def test_download_rejects_a_second_model_while_one_is_in_flight(monkeypatch):
+ state = stt_sidecar_module._SnapshotDownloadState()
+ release = threading.Event()
+ monkeypatch.setattr(
+ state,
+ "_run",
+ lambda repo, token, revision: release.wait(timeout = 5),
+ )
+
+ state.start("small")
+ try:
+ # Re-requesting the in-flight model is a no-op, not an error.
+ state.start("small")
+ with pytest.raises(SttModelIdError, match = "still"):
+ state.start("tiny")
+ assert state.status()["downloading"] is True
+ assert state.status()["model"] == "small"
+ finally:
+ release.set()
+
+
+def test_download_failure_is_reported_in_status(monkeypatch):
+ state = stt_sidecar_module._SnapshotDownloadState()
+ # Mask huggingface_hub so the import inside _run fails fast.
+ monkeypatch.setitem(sys.modules, "huggingface_hub", None)
+
+ state.start("small")
+ state._thread.join(timeout = 5)
+
+ status = state.status()
+ assert status["downloading"] is False
+ assert "Download failed" in (status["error"] or "")
+
+
+def test_is_model_downloaded_is_false_for_a_cache_miss(monkeypatch):
+ monkeypatch.setattr(
+ stt_sidecar_module,
+ "_find_complete_cached_snapshot",
+ _REAL_FIND_COMPLETE_CACHED_SNAPSHOT,
+ )
+ monkeypatch.setenv("HF_HUB_CACHE", "/nonexistent/stt-test-cache")
+
+ assert stt_sidecar_module.is_model_downloaded("small") is False
+
+
+def test_sharded_snapshot_with_missing_shard_is_not_downloaded(monkeypatch, tmp_path):
+ import json
+
+ monkeypatch.setenv("HF_HUB_CACHE", str(tmp_path / "hub"))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))
+ monkeypatch.setattr(
+ stt_sidecar_module,
+ "_find_complete_cached_snapshot",
+ _REAL_FIND_COMPLETE_CACHED_SNAPSHOT,
+ )
+ monkeypatch.setattr(stt_sidecar_module, "_snapshot_is_complete", _REAL_SNAPSHOT_IS_COMPLETE)
+ snap = tmp_path / "hub" / "models--unsloth--whisper-small" / "snapshots" / ("a" * 40)
+ snap.mkdir(parents = True)
+ (snap / "config.json").write_bytes(b"{}")
+ (snap / "preprocessor_config.json").write_bytes(b"{}")
+ (snap / "tokenizer.json").write_bytes(b"{}")
+ index = {
+ "weight_map": {
+ "a": "model-00001-of-00002.safetensors",
+ "b": "model-00002-of-00002.safetensors",
+ }
+ }
+ (snap / "model.safetensors.index.json").write_text(json.dumps(index))
+ (snap / "model-00001-of-00002.safetensors").write_bytes(b"w" * 8)
+
+ assert stt_sidecar_module.is_model_downloaded("small") is False
+
+ # Completing the second shard flips the verdict.
+ (snap / "model-00002-of-00002.safetensors").write_bytes(b"w" * 8)
+ assert stt_sidecar_module.is_model_downloaded("small") is True
+
+
[email protected]("model_id", ["small", "openai/whisper-medium"])
+def test_preflight_rejects_partial_snapshot(monkeypatch, tmp_path, model_id):
+ # A resolvable snapshot with metadata but no weights must fail preflight,
+ # not survive until load() after the audio has already been decoded.
+ monkeypatch.setenv("HF_HUB_CACHE", str(tmp_path / "hub"))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))
+ monkeypatch.setattr(
+ stt_sidecar_module,
+ "_find_complete_cached_snapshot",
+ _REAL_FIND_COMPLETE_CACHED_SNAPSHOT,
+ )
+ monkeypatch.setattr(stt_sidecar_module, "_snapshot_is_complete", _REAL_SNAPSHOT_IS_COMPLETE)
+ repo = STT_MODELS.get(model_id, model_id)
+ snapshot = tmp_path / "hub" / f"models--{repo.replace('/', '--')}" / "snapshots" / ("b" * 40)
+ snapshot.mkdir(parents = True)
+ (snapshot / "config.json").write_text('{"model_type": "whisper"}')
+
+ with pytest.raises(SttModelNotDownloadedError, match = "not downloaded"):
+ WhisperSttSidecar(keep_alive_seconds = 0)._ensure_model_downloaded(model_id)
+
+ # Completing the snapshot clears the preflight.
+ (snapshot / "preprocessor_config.json").write_text("{}")
+ (snapshot / "tokenizer.json").write_text("{}")
+ (snapshot / "model.safetensors").write_bytes(b"w" * 8)
+ WhisperSttSidecar(keep_alive_seconds = 0)._ensure_model_downloaded(model_id)
+
+
+def test_cpu_retry_releases_failed_accelerator_load(monkeypatch):
+ _install_fake_torch(monkeypatch)
+ monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda: ("mps", "float16"))
+
+ class Marker:
+ pass
+
+ seen = {}
+
+ def fake_build(self, repo, device, dtype, cancel_event):
+ if device != "cpu":
+ # The frame local stands in for a partly loaded accelerator model
+ # kept alive only through the raised traceback.
+ marker = Marker()
+ seen["ref"] = weakref.ref(marker)
+ raise RuntimeError("accelerator load failed")
+ gc.collect()
+ seen["alive_during_retry"] = seen["ref"]() is not None
+ return (_FakeModel(), object())
+
+ monkeypatch.setattr(WhisperSttSidecar, "_build_model", fake_build)
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 0)
+ sidecar.load("small")
+
+ # The failed attempt must be collectable before the CPU model loads, or
+ # its accelerator memory stays stranded for the whole retry.
+ assert seen["alive_during_retry"] is False
+ assert sidecar.device == "cpu"
diff --git a/studio/backend/tests/test_training_pump_resilience.py b/studio/backend/tests/test_training_pump_resilience.py
index 5d2a218482d..e7e47478b51 100644
--- a/studio/backend/tests/test_training_pump_resilience.py
+++ b/studio/backend/tests/test_training_pump_resilience.py
@@ -566,3 +566,34 @@ def test_db_run_created_before_pump_consumes_events(monkeypatch):
# The pump observed an already-created run; it would be False if the pump
# were started before the eager create.
assert seen["db_created"] is True
+
+
+def test_startup_flag_reports_training_active_before_proc():
+ # Between freeing VRAM and _proc going live, a concurrent STT load must see
+ # training as active so it does not grab the just-freed GPU.
+ b = TrainingBackend()
+ b._spawn_in_progress = True
+ assert b.is_training_active() is True
+
+
+def test_before_spawn_runs_inside_active_window(monkeypatch):
+ # The VRAM-freeing hook must run while training already counts as active, or
+ # an STT load racing it would place Whisper back on the freed GPU.
+ b = TrainingBackend()
+ _stub_spawn(monkeypatch)
+ monkeypatch.setattr(b, "_ensure_db_run_created", lambda: None)
+ monkeypatch.setattr(b, "_pump_loop", lambda: setattr(b, "_pump_running", False))
+
+ active_during_free = {}
+
+ def before_spawn():
+ active_during_free["value"] = b.is_training_active()
+
+ assert b.start_training("job_active_window", model_name = "m", before_spawn = before_spawn) is True
+ if b._pump_thread is not None:
+ b._pump_thread.join(timeout = 2.0)
+
+ assert active_during_free["value"] is True
+ # The transient flag clears, but the live proc keeps training active.
+ assert b._spawn_in_progress is False
+ assert b.is_training_active() is True
diff --git a/studio/backend/tests/test_training_vram_coexistence.py b/studio/backend/tests/test_training_vram_coexistence.py
index 2bedc46d1fe..6683cb9aaa6 100644
--- a/studio/backend/tests/test_training_vram_coexistence.py
+++ b/studio/backend/tests/test_training_vram_coexistence.py
@@ -82,6 +82,63 @@ def _patch_backends(inf, llama):
return patch.dict(sys.modules, {"core.inference": core_inf, "routes.inference": routes_inf})
+def _fake_stt_sidecar(
+ *,
+ model = None,
+ device = None,
+ loading = False,
+):
+ sidecar = SimpleNamespace(
+ loaded_model = model,
+ device = device,
+ is_loading = lambda: loading,
+ )
+ sidecar.cancel_pending_load = MagicMock(return_value = loading)
+ sidecar.wait_for_load_to_settle = MagicMock()
+ sidecar.unload = MagicMock()
+ return sidecar
+
+
+def _fake_ggml_sidecar(
+ *,
+ model = None,
+ device = None,
+ loading = False,
+):
+ ggml = SimpleNamespace(
+ loaded_model = model,
+ device = device,
+ is_loading = lambda: loading,
+ )
+ ggml.cancel_pending_load = MagicMock(return_value = loading)
+ ggml.wait_for_load_to_settle = MagicMock()
+ ggml.unload = MagicMock()
+ return ggml
+
+
+def _patch_stt(sidecar):
+ stt_module = types.ModuleType("core.inference.stt_sidecar")
+ stt_module.get_stt_sidecar = lambda: sidecar
+ # A fresh import of the GGUF sidecar pulls names from the fake module
+ # above and fails; fake it too so test ordering cannot break that import.
+ ggml_module = types.ModuleType("core.inference.stt_ggml_sidecar")
+ empty_ggml = _fake_ggml_sidecar()
+ ggml_module.get_ggml_stt_sidecar = lambda: empty_ggml
+ return patch.dict(
+ sys.modules,
+ {
+ "core.inference.stt_sidecar": stt_module,
+ "core.inference.stt_ggml_sidecar": ggml_module,
+ },
+ )
+
+
+def _patch_ggml_stt(sidecar):
+ ggml_module = types.ModuleType("core.inference.stt_ggml_sidecar")
+ ggml_module.get_ggml_stt_sidecar = lambda: sidecar
+ return patch.dict(sys.modules, {"core.inference.stt_ggml_sidecar": ggml_module})
+
+
# ── summarize_resident_chat ──────────────────────────────────────────────────
@@ -169,6 +226,49 @@ class TestSummarizeResidentChat(_GpuCacheResetMixin, unittest.TestCase):
self.assertTrue(out["any"]) # GGUF still detected
+class TestSummarizeResidentStt(_GpuCacheResetMixin, unittest.TestCase):
+ def test_reports_resident_model(self):
+ sidecar = _fake_stt_sidecar(model = "small", device = "cuda")
+ with _patch_stt(sidecar):
+ out = tv.summarize_resident_stt()
+ self.assertEqual(out["model"], "small")
+ self.assertEqual(out["device"], "cuda")
+ self.assertTrue(out["any"])
+ self.assertFalse(out["loading"])
+
+ def test_reports_inflight_load(self):
+ sidecar = _fake_stt_sidecar(loading = True)
+ with _patch_stt(sidecar):
+ out = tv.summarize_resident_stt()
+ self.assertTrue(out["any"])
+ self.assertTrue(out["loading"])
+
+ def test_reports_empty_sidecar(self):
+ with _patch_stt(_fake_stt_sidecar()):
+ out = tv.summarize_resident_stt()
+ self.assertFalse(out["any"])
+
+ def test_reports_resident_gguf_when_transformers_idle(self):
+ ggml = _fake_ggml_sidecar(model = "small", device = "whisper.cpp")
+ with _patch_stt(_fake_stt_sidecar()), _patch_ggml_stt(ggml):
+ out = tv.summarize_resident_stt()
+ self.assertEqual(out["model"], "small")
+ self.assertEqual(out["device"], "whisper.cpp")
+ self.assertTrue(out["any"])
+
+ def test_resident_transformers_does_not_mask_loading_gguf(self):
+ # A Transformers model resident on CPU holds no VRAM, but a GGUF
+ # whisper-server still binding its accelerator backend does; the CPU
+ # model must not hide that in-flight startup from training admission.
+ sidecar = _fake_stt_sidecar(model = "small", device = "cpu")
+ ggml = _fake_ggml_sidecar(loading = True)
+ with _patch_stt(sidecar), _patch_ggml_stt(ggml):
+ out = tv.summarize_resident_stt()
+ self.assertEqual(out["model"], "small")
+ self.assertTrue(out["loading"])
+ self.assertTrue(out["any"])
+
+
# ── can_keep_during_training (auto mode) ─────────────────────────────────────
@@ -438,5 +538,151 @@ class TestFreeChatModels(_GpuCacheResetMixin, unittest.TestCase):
self.assertEqual(freed, ["gguf:gemma.gguf"])
+class TestFreeSttModel(_GpuCacheResetMixin, unittest.TestCase):
+ def test_unloads_resident_model(self):
+ sidecar = _fake_stt_sidecar(model = "small", device = "cuda")
+ with _patch_stt(sidecar):
+ freed = tv.free_stt_model_for_training(reason = "test")
+ sidecar.unload.assert_called_once()
+ self.assertEqual(freed, ["stt:small"])
+
+ def test_cancels_inflight_load_and_waits_to_settle(self):
+ sidecar = _fake_stt_sidecar(loading = True)
+ with _patch_stt(sidecar):
+ freed = tv.free_stt_model_for_training(reason = "test")
+ sidecar.cancel_pending_load.assert_called_once()
+ # The cancelled loader may still hold VRAM; we wait for it to release.
+ sidecar.wait_for_load_to_settle.assert_called_once()
+ # No model surfaced after the wait, so nothing to unload.
+ sidecar.unload.assert_not_called()
+ self.assertEqual(freed, ["stt:loading"])
+
+ def test_cancels_inflight_load_then_unloads_settled_model(self):
+ # A load that finished before observing the cancel leaves a resident
+ # model behind; it must be unloaded so training reclaims the memory.
+ sidecar = _fake_stt_sidecar(model = "small", loading = True)
+ with _patch_stt(sidecar):
+ freed = tv.free_stt_model_for_training(reason = "test")
+ sidecar.cancel_pending_load.assert_called_once()
+ sidecar.wait_for_load_to_settle.assert_called_once()
+ sidecar.unload.assert_called_once()
+ self.assertEqual(freed, ["stt:loading"])
+
+ def test_cancelled_load_still_unloads_gguf_sidecar(self):
+ # Cancelling a Transformers load must not skip the GGUF sidecar; both
+ # engines can hold memory at once (engine switch or direct load calls).
+ sidecar = _fake_stt_sidecar(loading = True)
+ ggml = _fake_ggml_sidecar(model = "small")
+ with _patch_stt(sidecar), _patch_ggml_stt(ggml):
+ freed = tv.free_stt_model_for_training(reason = "test")
+ sidecar.cancel_pending_load.assert_called_once()
+ ggml.unload.assert_called_once()
+ self.assertEqual(freed, ["stt:loading", "stt:small"])
+
+ def test_leaves_empty_sidecar_alone(self):
+ sidecar = _fake_stt_sidecar()
+ with _patch_stt(sidecar):
+ freed = tv.free_stt_model_for_training(reason = "test")
+ sidecar.unload.assert_not_called()
+ self.assertEqual(freed, [])
+
+ def test_cancels_inflight_gguf_load_and_waits_to_settle(self):
+ # A GGUF whisper-server still in startup has no loaded_model yet, so the
+ # coordinator must cancel and wait for it, not skip it, before training
+ # claims the accelerator memory it is binding.
+ sidecar = _fake_stt_sidecar() # Transformers idle
+ ggml = _fake_ggml_sidecar(loading = True)
+ with _patch_stt(sidecar), _patch_ggml_stt(ggml):
+ freed = tv.free_stt_model_for_training(reason = "test")
+ ggml.cancel_pending_load.assert_called_once()
+ ggml.wait_for_load_to_settle.assert_called_once()
+ ggml.unload.assert_not_called() # nothing surfaced after the wait
+ self.assertEqual(freed, ["stt:gguf-loading"])
+
+
+class TestCoordinateModels(_GpuCacheResetMixin, unittest.TestCase):
+ def _run(self, chat, stt, keep_results):
+ keep = MagicMock(side_effect = keep_results)
+ with (
+ patch.object(tv, "summarize_resident_chat", return_value = chat),
+ patch.object(tv, "summarize_resident_stt", return_value = stt),
+ patch.object(
+ tv,
+ "free_stt_model_for_training",
+ return_value = ["stt:small"],
+ ) as free_stt,
+ patch.object(
+ tv,
+ "free_chat_models_for_training",
+ return_value = ["hf:chat"],
+ ) as free_chat,
+ ):
+ freed = tv.coordinate_models_for_training(keep)
+ return freed, keep, free_stt, free_chat
+
+ def test_keeps_everything_when_training_fits(self):
+ chat = {"any": True, "loading": False}
+ stt = {"any": True, "loading": False}
+ freed, keep, free_stt, free_chat = self._run(
+ chat,
+ stt,
+ [(True, {"usable_gb": 40, "required_gb": 10})],
+ )
+ self.assertEqual(freed, [])
+ keep.assert_called_once()
+ free_stt.assert_not_called()
+ free_chat.assert_not_called()
+
+ def test_frees_stt_before_chat(self):
+ chat = {"any": True, "loading": False}
+ stt = {"any": True, "loading": False}
+ freed, keep, free_stt, free_chat = self._run(
+ chat,
+ stt,
+ [
+ (False, {"usable_gb": 8, "required_gb": 10}),
+ (True, {"usable_gb": 12, "required_gb": 10}),
+ ],
+ )
+ self.assertEqual(freed, ["stt:small"])
+ self.assertEqual(keep.call_count, 2)
+ free_stt.assert_called_once()
+ free_chat.assert_not_called()
+
+ def test_frees_chat_when_stt_is_not_enough(self):
+ chat = {"any": True, "loading": False}
+ stt = {"any": True, "loading": False}
+ freed, keep, free_stt, free_chat = self._run(
+ chat,
+ stt,
+ [
+ (False, {"usable_gb": 8, "required_gb": 10}),
+ (False, {"usable_gb": 9, "required_gb": 10}),
+ ],
+ )
+ self.assertEqual(freed, ["stt:small", "hf:chat"])
+ self.assertEqual(keep.call_count, 2)
+ free_stt.assert_called_once()
+ free_chat.assert_called_once()
+
+ def test_frees_loading_models_without_probe(self):
+ chat = {"any": True, "loading": True}
+ stt = {"any": True, "loading": True}
+ freed, keep, free_stt, free_chat = self._run(chat, stt, [])
+ self.assertEqual(freed, ["stt:small", "hf:chat"])
+ keep.assert_not_called()
+ free_stt.assert_called_once()
+ free_chat.assert_called_once()
+
+ def test_cancels_loading_stt_without_probe(self):
+ chat = {"any": False, "loading": False}
+ stt = {"any": True, "loading": True}
+ freed, keep, free_stt, free_chat = self._run(chat, stt, [])
+ self.assertEqual(freed, ["stt:small"])
+ keep.assert_not_called()
+ free_stt.assert_called_once()
+ free_chat.assert_not_called()
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/studio/backend/tests/test_whisper_cpp_freshness.py b/studio/backend/tests/test_whisper_cpp_freshness.py
new file mode 100644
index 00000000000..69f0c87cee2
--- /dev/null
+++ b/studio/backend/tests/test_whisper_cpp_freshness.py
@@ -0,0 +1,156 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Tests for the whisper.cpp prebuilt freshness check.
+
+Pins the whisper-specific version policy: the release-tag parser, the
+is_behind decision matrix (with its downgrade guard), and one end-to-end
+wiring smoke through the shared freshness flow. The shared marker-walk and
+fail-open mechanics are covered by test_llama_cpp_freshness.py.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+import types as _types
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+
+class _NoopLogger:
+ """structlog-style logger: every method swallows positional + kwargs."""
+
+ def __getattr__(self, _name):
+ return lambda *a, **k: None
+
+
+_loggers_stub = _types.ModuleType("loggers")
+_loggers_stub.get_logger = lambda *a, **k: _NoopLogger()
+sys.modules.setdefault("loggers", _loggers_stub)
+
+_structlog_stub = _types.ModuleType("structlog")
+_structlog_stub.get_logger = lambda *a, **k: _NoopLogger()
+sys.modules.setdefault("structlog", _structlog_stub)
+
+import pytest
+
+from utils import whisper_cpp_freshness as fr
+
+
+# Helpers.
+
+
+def _write_marker(install_dir: Path, **overrides) -> Path:
+ payload = {
+ "requested_tag": "latest",
+ "release_tag": "v1.9.1-unsloth.1",
+ "upstream_tag": "v1.9.1",
+ "published_repo": "unslothai/whisper.cpp",
+ "asset": "whisper-v1.9.1-unsloth.1-linux-x64-cpu.tar.gz",
+ "asset_sha256": None,
+ "source": "published",
+ "installed_at_utc": (datetime.now(tz = timezone.utc) - timedelta(days = 1))
+ .isoformat()
+ .replace("+00:00", "Z"),
+ }
+ payload.update(overrides)
+ install_dir.mkdir(parents = True, exist_ok = True)
+ marker = install_dir / "UNSLOTH_WHISPER_PREBUILT_INFO.json"
+ marker.write_text(json.dumps(payload))
+ return marker
+
+
+def _fake_binary(install_dir: Path) -> Path:
+ """Stub whisper-server under the canonical cmake install layout."""
+ bin_dir = install_dir / "build" / "bin"
+ bin_dir.mkdir(parents = True, exist_ok = True)
+ bin_path = bin_dir / "whisper-server"
+ bin_path.write_text("stub\n")
+ return bin_path
+
+
[email protected](autouse = True)
+def _reset(monkeypatch, tmp_path):
+ # Isolate disk cache per-test; never touch the real cache.
+ monkeypatch.setattr(fr, "_cache_dir", lambda: tmp_path / ".freshness")
+ fr.reset_caches()
+ yield
+ fr.reset_caches()
+
+
+# parse_release_version.
+
+
+def test_parse_release_version():
+ assert fr.parse_release_version("v1.9.1-unsloth.2") == (1, 9, 1, 2)
+ assert fr.parse_release_version("1.10.0") == (1, 10, 0, 0) # no v, no serial
+ assert fr.parse_release_version(" v2.0.0-unsloth.10 ") == (2, 0, 0, 10)
+ assert fr.parse_release_version("v1.9") == (1, 9, 0, 0) # padded
+ assert fr.parse_release_version("nightly") is None
+ assert fr.parse_release_version(None) is None
+ assert fr.parse_release_version("") is None
+
+
+# is_behind decision matrix + downgrade guard.
+
+
+def test_is_behind_serial_bump():
+ assert fr.is_behind("v1.9.1-unsloth.1", "v1.9.1-unsloth.2") is True
+
+
+def test_is_behind_downgrade_guard():
+ # A lower serial or version is never "behind".
+ assert fr.is_behind("v1.9.1-unsloth.2", "v1.9.1-unsloth.1") is False
+ assert fr.is_behind("v1.10.0-unsloth.1", "v1.9.1-unsloth.9") is False
+
+
+def test_is_behind_upstream_bump():
+ assert fr.is_behind("v1.9.1-unsloth.1", "v1.10.0-unsloth.1") is True
+
+
+def test_is_behind_identical_is_false():
+ assert fr.is_behind("v1.9.1-unsloth.1", "v1.9.1-unsloth.1") is False
+
+
+def test_is_behind_unparseable_differs_is_behind():
+ assert fr.is_behind("v1.9.1-unsloth.1", "nightly") is True
+
+
+def test_is_behind_missing_side_fails_open():
+ assert fr.is_behind(None, "v1.9.1-unsloth.2") is False
+ assert fr.is_behind("v1.9.1-unsloth.1", None) is False
+
+
+# check_prebuilt_freshness end-to-end.
+
+
+def test_check_prebuilt_freshness_reports_stale_when_old_and_behind(monkeypatch, tmp_path):
+ _write_marker(
+ tmp_path,
+ release_tag = "v1.9.1-unsloth.1",
+ installed_at_utc = (datetime.now(tz = timezone.utc) - timedelta(days = 10))
+ .isoformat()
+ .replace("+00:00", "Z"),
+ )
+ bin_path = _fake_binary(tmp_path)
+ monkeypatch.setattr(fr, "latest_published_release", lambda *a, **k: "v1.9.1-unsloth.3")
+ info = fr.check_prebuilt_freshness(str(bin_path))
+ assert info["has_marker"] is True
+ assert info["behind"] is True
+ assert info["stale"] is True
+ assert info["installed_tag"] == "v1.9.1-unsloth.1"
+ assert info["latest_tag"] == "v1.9.1-unsloth.3"
+
+
+def test_marker_reader_prefers_install_root_over_packaging_marker(tmp_path):
+ root_marker = _write_marker(tmp_path, release_tag = "v1.9.1-unsloth.2")
+ binary = _fake_binary(tmp_path)
+ (binary.parent / root_marker.name).write_text(
+ json.dumps({"backend": "slim", "release_tag": "archive-metadata"})
+ )
+ assert fr.read_install_marker(str(binary))["release_tag"] == "v1.9.1-unsloth.2"
diff --git a/studio/backend/utils/hidden_models.py b/studio/backend/utils/hidden_models.py
index 20d0bb966e5..e7c3181d718 100644
--- a/studio/backend/utils/hidden_models.py
+++ b/studio/backend/utils/hidden_models.py
@@ -9,6 +9,7 @@ which eagerly loads the model-config/checkpoint stack, and without importing
from __future__ import annotations
+import json
import re
from pathlib import Path
from typing import Optional
@@ -31,6 +32,61 @@ _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
+# 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.
+_HIDDEN_STT_REPO_IDS = frozenset(
+ {
+ "unsloth/whisper-tiny",
+ "unsloth/whisper-base",
+ "unsloth/whisper-small",
+ "unsloth/whisper-large-v3-turbo",
+ "unsloth/whisper-large-v3",
+ "unslothai/whisper-tiny-GGUF",
+ "unslothai/whisper-base-GGUF",
+ "unslothai/whisper-small-GGUF",
+ "unslothai/whisper-large-v3-turbo-GGUF",
+ "unslothai/whisper-large-v3-GGUF",
+ }
+)
+
+
+def _config_is_whisper(path: Path) -> bool:
+ """True if a config.json declares a Whisper model."""
+ try:
+ with open(path, "r", encoding = "utf-8") as file:
+ config = json.load(file)
+ except Exception:
+ return False
+ if not isinstance(config, dict):
+ return False
+ model_type = config.get("model_type")
+ if isinstance(model_type, str) and model_type.strip().lower() == "whisper":
+ return True
+ architectures = config.get("architectures")
+ return isinstance(architectures, list) and any(
+ isinstance(name, str) and name == "WhisperForConditionalGeneration"
+ for name in architectures
+ )
+
+
+def _path_is_whisper_model(value: str) -> bool:
+ """Inspect an existing local model path's config; never hides name-only matches."""
+ if _HF_REPO_ID_RE.fullmatch(value.strip()):
+ return False
+ path = Path(value).expanduser()
+ try:
+ if path.is_file():
+ path = path.parent
+ candidates = [path / "config.json"]
+ snapshots = path / "snapshots"
+ if snapshots.is_dir():
+ candidates.extend(child / "config.json" for child in snapshots.iterdir())
+ except OSError:
+ return False
+ return any(_config_is_whisper(candidate) for candidate in candidates)
def _safe_resolve(path: Path) -> Optional[str]:
@@ -79,11 +135,11 @@ def _path_basename_is_default_embedder(value: str) -> bool:
def is_hidden_model(*values: str | None) -> bool:
"""True if any id/path is the RAG embedding model (the effective embedder
- or its GGUF companion repo) or the llama.cpp install validation probe
- (ggml-org/models / stories260K), so pickers hide them (GGUF and non-GGUF).
- None are usable chat models; the probe can be cached as a side effect of
- installing the prebuilt llama-server and otherwise sorts smallest, so it
- would be auto-selected.
+ or its GGUF companion repo), the llama.cpp install validation probe
+ (ggml-org/models / stories260K), or a curated/custom Whisper dictation
+ model, so pickers hide them (GGUF and non-GGUF). None are usable chat
+ models; the probe can be cached as a side effect of installing the prebuilt
+ llama-server and otherwise sorts smallest, so it would be auto-selected.
Hub repo ids are matched EXACTLY (case-insensitive full "owner/name"), so a
custom embedder with a generic basename like "org/model" cannot substring
@@ -97,6 +153,7 @@ def is_hidden_model(*values: str | None) -> bool:
hidden_repo_ids = {
_PROBE_REPO_ID.lower(),
*(repo_id.lower() for repo_id in _DEFAULT_EMBEDDING_REPO_IDS),
+ *(repo_id.lower() for repo_id in _HIDDEN_STT_REPO_IDS),
}
exact_paths: list[str] = []
for model in {
@@ -135,6 +192,9 @@ def is_hidden_model(*values: str | None) -> bool:
return True
if _path_contains_repo_id(v, hidden_repo_ids):
return True
+ # Custom Whisper checkpoints keep no curated repo id, so match by config.
+ if _path_is_whisper_model(v):
+ return True
if exact_paths:
resolved = _safe_resolve(Path(v).expanduser())
if resolved and resolved.lower() in exact_paths:
diff --git a/studio/backend/utils/llama_cpp_freshness.py b/studio/backend/utils/llama_cpp_freshness.py
index 7d077bfa3bd..a184fdb3e97 100644
--- a/studio/backend/utils/llama_cpp_freshness.py
+++ b/studio/backend/utils/llama_cpp_freshness.py
@@ -7,28 +7,28 @@ Reads UNSLOTH_PREBUILT_INFO.json (written by install_llama_prebuilt.py)
and compares the installed release tag against the latest on GitHub.
Surfaced via main.py:lifespan() and /api/inference/status. Fails open
on any missing data so we never show a misleading banner.
+
+The mechanics (marker walk-up, GitHub fetch, memo + disk cache, report
+skeleton) live in utils.prebuilt.freshness_flow; this module keeps the
+llama version policy and the per-module caches its tests patch.
"""
from __future__ import annotations
-import json
-import os
import re
-import time
-from datetime import datetime, timezone
+from datetime import datetime
from pathlib import Path
from typing import Optional
import structlog
+from utils.prebuilt import freshness_flow as _flow
+
logger = structlog.get_logger(__name__)
# 3 days matches Unsloth's typical llama.cpp release cadence.
STALENESS_THRESHOLD_DAYS = 3
-# 24h TTL keeps the GitHub call off the hot path and within rate limits.
-_RELEASE_CACHE_TTL_SECONDS = 24 * 60 * 60
-
_INSTALL_MARKER_NAME = "UNSLOTH_PREBUILT_INFO.json"
_marker_cache: dict[str, Optional[dict]] = {}
@@ -49,203 +49,60 @@ def _cache_dir() -> Path:
def read_install_marker(binary_path: Optional[str]) -> Optional[dict]:
"""Walk up from binary_path to find UNSLOTH_PREBUILT_INFO.json.
None = no marker (source build / custom path) or invalid JSON."""
- if not binary_path:
- return None
- cached = _marker_cache.get(binary_path)
- if cached is not None or binary_path in _marker_cache:
- return cached
- p = Path(binary_path)
- marker: Optional[dict] = None
- # Cover all _find_llama_server_binary layouts (binary is 1-4 dirs deep):
- for parent in p.parents[:5]:
- candidate = parent / _INSTALL_MARKER_NAME
- if candidate.is_file():
- try:
- marker = json.loads(candidate.read_text(encoding = "utf-8"))
- except (OSError, json.JSONDecodeError) as exc:
- logger.debug(
- "failed to parse install marker",
- path = str(candidate),
- error = str(exc),
- )
- marker = None
- break
- _marker_cache[binary_path] = marker
- return marker
-
-
-def _cache_path_for(repo: str) -> Path:
- safe = repo.replace("/", "__")
- return _cache_dir() / f"{safe}.json"
+ return _flow.read_install_marker(
+ binary_path,
+ marker_name = _INSTALL_MARKER_NAME,
+ cache = _marker_cache,
+ log_message = "failed to parse install marker",
+ )
def _load_disk_cache(repo: str) -> Optional[tuple[float, Optional[str]]]:
- path = _cache_path_for(repo)
- try:
- payload = json.loads(path.read_text(encoding = "utf-8"))
- except (OSError, json.JSONDecodeError):
- return None
- ts = payload.get("fetched_at")
- tag = payload.get("latest_tag")
- if not isinstance(ts, (int, float)):
- return None
- return float(ts), tag if isinstance(tag, str) else None
+ return _flow.load_disk_cache(repo, _cache_dir())
def _save_disk_cache(repo: str, latest_tag: Optional[str]) -> None:
- path = _cache_path_for(repo)
- try:
- path.parent.mkdir(parents = True, exist_ok = True)
- tmp = path.with_suffix(".tmp")
- tmp.write_text(
- json.dumps({"fetched_at": time.time(), "latest_tag": latest_tag}),
- encoding = "utf-8",
- )
- tmp.replace(path)
- except OSError as exc:
- logger.debug("freshness cache write failed", repo = repo, error = str(exc))
+ _flow.save_disk_cache(
+ repo, latest_tag, _cache_dir(), log_message = "freshness cache write failed"
+ )
def _fetch_latest_release_tag(repo: str, timeout: float = 5.0) -> Optional[str]:
- """Newest published release tag for `repo`, by publish time.
-
- Resolves "latest" the way install_llama_prebuilt.py does (newest
- non-draft/non-prerelease by ``published_at``), NOT via GitHub's
- ``/releases/latest`` pointer. That pointer sorts by commit date and can lag
- behind the build the installer actually installs, so detection and apply
- disagreed -- the cause of the downgrade/sticky banner. None on any failure
- (offline, rate-limited, etc)."""
- import urllib.error
- import urllib.request
-
- url = f"https://api.github.com/repos/{repo}/releases?per_page=30"
- headers = {
- "Accept": "application/vnd.github+json",
- "User-Agent": "unsloth-studio-freshness-check",
- }
- token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
- if token:
- headers["Authorization"] = f"Bearer {token}"
- req = urllib.request.Request(url, headers = headers)
- try:
- with urllib.request.urlopen(req, timeout = timeout) as resp:
- data = json.loads(resp.read().decode("utf-8"))
- except (
- urllib.error.URLError,
- urllib.error.HTTPError,
- OSError,
- json.JSONDecodeError,
- ) as exc:
- logger.debug("freshness fetch failed", repo = repo, error = str(exc))
- return None
- if not isinstance(data, list):
- return None
- published = [
- r
- for r in data
- if isinstance(r, dict)
- and not r.get("draft")
- and not r.get("prerelease")
- and isinstance(r.get("tag_name"), str)
- and r.get("tag_name")
- ]
- if not published:
- return None
- newest = max(published, key = lambda r: r.get("published_at") or "")
- return newest["tag_name"]
+ """Newest published release tag for `repo`, by publish time (see
+ freshness_flow for why this is not GitHub's /releases/latest pointer)."""
+ return _flow.fetch_latest_release_tag(repo, timeout, log_message = "freshness fetch failed")
def latest_published_release(repo: str, *, force_refresh: bool = False) -> Optional[str]:
"""Latest release tag for `repo`. Memo + disk-cached (24h TTL).
None when offline and never previously cached."""
- if not repo:
- return None
- now = time.time()
- if not force_refresh:
- memo = _release_memo.get(repo)
- if memo and now - memo[0] < _RELEASE_CACHE_TTL_SECONDS:
- return memo[1]
- disk = _load_disk_cache(repo)
- if disk and now - disk[0] < _RELEASE_CACHE_TTL_SECONDS:
- _release_memo[repo] = disk
- return disk[1]
- latest = _fetch_latest_release_tag(repo)
- if latest is None:
- # Keep last-good disk value rather than poisoning with None.
- disk = _load_disk_cache(repo)
- if disk:
- _release_memo[repo] = disk
- return disk[1]
- return None
- _release_memo[repo] = (now, latest)
- _save_disk_cache(repo, latest)
- return latest
+ return _flow.latest_published_release(
+ repo,
+ force_refresh = force_refresh,
+ memo = _release_memo,
+ cache_dir = lambda: _cache_dir(),
+ fetch = lambda r: _fetch_latest_release_tag(r),
+ save = lambda r, tag: _save_disk_cache(r, tag),
+ )
def _fetch_latest_release_assets(repo: str, timeout: float = 5.0) -> Optional[dict[str, int]]:
"""Asset name -> size (bytes) for the newest published release of `repo`,
selected exactly like _fetch_latest_release_tag. None on any failure."""
- import urllib.error
- import urllib.request
-
- url = f"https://api.github.com/repos/{repo}/releases?per_page=30"
- headers = {
- "Accept": "application/vnd.github+json",
- "User-Agent": "unsloth-studio-freshness-check",
- }
- token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
- if token:
- headers["Authorization"] = f"Bearer {token}"
- req = urllib.request.Request(url, headers = headers)
- try:
- with urllib.request.urlopen(req, timeout = timeout) as resp:
- data = json.loads(resp.read().decode("utf-8"))
- except (
- urllib.error.URLError,
- urllib.error.HTTPError,
- OSError,
- json.JSONDecodeError,
- ) as exc:
- logger.debug("freshness asset fetch failed", repo = repo, error = str(exc))
- return None
- if not isinstance(data, list):
- return None
- published = [
- r
- for r in data
- if isinstance(r, dict)
- and not r.get("draft")
- and not r.get("prerelease")
- and isinstance(r.get("tag_name"), str)
- and r.get("tag_name")
- ]
- if not published:
- return None
- newest = max(published, key = lambda r: r.get("published_at") or "")
- assets: dict[str, int] = {}
- for a in newest.get("assets") or []:
- name, size = a.get("name"), a.get("size")
- if isinstance(name, str) and isinstance(size, int):
- assets[name] = size
- return assets
+ return _flow.fetch_latest_release_assets(
+ repo, timeout, log_message = "freshness asset fetch failed"
+ )
def latest_release_assets(repo: str, *, force_refresh: bool = False) -> Optional[dict[str, int]]:
"""Newest-release asset sizes for `repo`, memoized (24h TTL). None when
offline and never fetched. In-memory only -- a restart simply re-fetches."""
- if not repo:
- return None
- now = time.time()
- if not force_refresh:
- memo = _assets_memo.get(repo)
- if memo and now - memo[0] < _RELEASE_CACHE_TTL_SECONDS:
- return memo[1]
- assets = _fetch_latest_release_assets(repo)
- if assets is None:
- memo = _assets_memo.get(repo)
- return memo[1] if memo else None
- _assets_memo[repo] = (now, assets)
- return assets
+ return _flow.latest_release_assets(
+ repo,
+ force_refresh = force_refresh,
+ memo = _assets_memo,
+ fetch = lambda r: _fetch_latest_release_assets(r),
+ )
def update_download_size_bytes(
@@ -290,16 +147,7 @@ def update_download_size_bytes(
def _parse_installed_at(value: object) -> Optional[datetime]:
- if not isinstance(value, str) or not value:
- return None
- s = value.replace("Z", "+00:00") if value.endswith("Z") else value
- try:
- dt = datetime.fromisoformat(s)
- except ValueError:
- return None
- if dt.tzinfo is None:
- dt = dt.replace(tzinfo = timezone.utc)
- return dt
+ return _flow.parse_installed_at(value)
def parse_base_build(tag: object) -> Optional[int]:
@@ -350,64 +198,27 @@ def check_prebuilt_freshness(
behind = installed genuinely older than latest (see is_behind).
stale = behind AND age >= threshold.
Fails open on missing data (behind/stale stay False)."""
- out: dict = {
- "has_marker": False,
- "stale": False,
- "behind": False,
- "installed_tag": None,
- "latest_tag": None,
- "installed_at_utc": None,
- "age_days": None,
- "published_repo": None,
- "threshold_days": int(threshold_days),
- }
- marker = read_install_marker(binary_path)
- if not marker:
- return out
- out["has_marker"] = True
- # Display prefers the normalized base ("tag"); comparison below prefers the
- # full "release_tag" -- deliberately opposite fallbacks.
- out["installed_tag"] = marker.get("tag") or marker.get("release_tag")
- out["installed_at_utc"] = marker.get("installed_at_utc")
- out["published_repo"] = marker.get("published_repo")
-
# The marker records both a normalized base tag ("tag", e.g. b9596) and the
- # full release tag ("release_tag", e.g. b9596-mix-<sha>). Compare against the
- # FULL identity, since GitHub /releases/latest returns the full tag_name --
- # comparing the normalized base against the full latest is what produced the
- # permanent "downgrade" banner on every mix release.
- installed_full = marker.get("release_tag") or marker.get("tag")
- repo = out["published_repo"]
- if not repo or not installed_full:
- return out
- latest = latest_published_release(repo)
- out["latest_tag"] = latest
- out["behind"] = is_behind(installed_full, latest)
- if not out["behind"]:
- return out
-
- installed_at = _parse_installed_at(out["installed_at_utc"])
- if installed_at is None:
- return out
- now = now or datetime.now(tz = timezone.utc)
- age_seconds = (now - installed_at).total_seconds()
- out["age_days"] = max(0, int(age_seconds // 86400))
- if age_seconds >= threshold_days * 86400:
- out["stale"] = True
- return out
+ # full release tag ("release_tag", e.g. b9596-mix-<sha>). Display prefers the
+ # normalized base; comparison uses the FULL identity, since GitHub
+ # /releases/latest returns the full tag_name -- comparing the normalized base
+ # against the full latest is what produced the permanent "downgrade" banner
+ # on every mix release. Deliberately opposite fallbacks.
+ return _flow.check_freshness(
+ binary_path,
+ threshold_days = threshold_days,
+ now = now,
+ read_marker = lambda p: read_install_marker(p),
+ latest_release = lambda repo: latest_published_release(repo),
+ behind = lambda installed, latest: is_behind(installed, latest),
+ display_tag = lambda marker: marker.get("tag") or marker.get("release_tag"),
+ compare_tag = lambda marker: marker.get("release_tag") or marker.get("tag"),
+ )
def format_stale_warning(info: dict) -> str:
"""Human-readable one-liner for stale prebuilt info."""
- age = info.get("age_days")
- installed = info.get("installed_tag") or "unknown"
- latest = info.get("latest_tag") or "unknown"
- age_str = f"{age} day{'s' if age != 1 else ''}" if age is not None else "some time"
- return (
- f"llama.cpp prebuilt is {age_str} behind: installed "
- f"{installed}, latest {latest}. Run `unsloth studio update` "
- f"to refresh."
- )
+ return _flow.format_stale_warning(info, component = "llama.cpp")
def reset_caches(*, drop_disk: bool = False) -> None:
@@ -420,13 +231,8 @@ def reset_caches(*, drop_disk: bool = False) -> None:
(see its last-good fallback) and the banner could linger. Dropping the disk
cache makes latest read as None in that offline case, so the banner fails
open (off) instead of pointing at the just-replaced build."""
- _marker_cache.clear()
- _release_memo.clear()
- _assets_memo.clear()
- if drop_disk:
- import shutil
-
- # _cache_dir() is a dedicated freshness-only subdir; it is re-created on
- # the next _save_disk_cache. ignore_errors so a missing/locked dir is a
- # no-op rather than breaking an otherwise successful install.
- shutil.rmtree(_cache_dir(), ignore_errors = True)
+ _flow.reset_caches(
+ (_marker_cache, _release_memo, _assets_memo),
+ drop_disk = drop_disk,
+ cache_dir = lambda: _cache_dir(),
+ )
diff --git a/studio/backend/utils/llama_cpp_update.py b/studio/backend/utils/llama_cpp_update.py
index 67733bde35e..174e6ef4dce 100644
--- a/studio/backend/utils/llama_cpp_update.py
+++ b/studio/backend/utils/llama_cpp_update.py
@@ -17,17 +17,22 @@ Design notes:
thread; callers poll get_update_status() for the job state.
- Everything fails open: a missing marker / offline GitHub / source build just
reports update_available=False and never blocks the app.
+- The mechanics (managed-root resolution, local-link detection, the resolve
+ probe, the streamed installer run) live in utils.prebuilt.update_flow; this
+ module keeps the llama policy and the job dict its callers poll.
+- This is the single main update item: whisper.cpp piggybacks on it. Status
+ folds in a whisper sub-status (update_available becomes the union) and apply
+ chains a whisper phase after the llama phase when whisper is behind (see
+ update_flow.run_chained_update and whisper_cpp_update.chained_phase_plan).
"""
from __future__ import annotations
-import json
import os
import re
import subprocess
import sys
import threading
-import time
from pathlib import Path
from typing import Optional
@@ -43,7 +48,7 @@ from utils.llama_cpp_freshness import (
reset_caches,
update_download_size_bytes,
)
-from utils.process_lifetime import child_popen_kwargs
+from utils.prebuilt import update_flow as _flow
logger = structlog.get_logger(__name__)
@@ -51,33 +56,18 @@ DEFAULT_PUBLISHED_REPO = "unslothai/llama.cpp"
_INSTALL_TIMEOUT_SECONDS = 1800 # 30 min ceiling for download + build/validate
# Background job state. Single in-flight update at a time, guarded by _job_lock.
-_JOB_IDLE = "idle"
-_JOB_RUNNING = "running"
-_JOB_SUCCESS = "success"
-_JOB_ERROR = "error"
+_JOB_IDLE = _flow.JOB_IDLE
+_JOB_RUNNING = _flow.JOB_RUNNING
+_JOB_SUCCESS = _flow.JOB_SUCCESS
+_JOB_ERROR = _flow.JOB_ERROR
_job_lock = threading.Lock()
-_job: dict = {
- "state": _JOB_IDLE,
- "message": "",
- "from_tag": None,
- "to_tag": None,
- "reload_required": None,
- "error": None,
- "progress": None,
- "started_at": None,
- "finished_at": None,
-}
+_job: dict = _flow.new_job()
-# Matches the installer's download progress lines, e.g.
-# "Downloading x.zip: 35.0% (12.3 MiB/35.1 MiB) at 8.2 MiB/s".
-_PROGRESS_LINE_RE = re.compile(r"(\d+(?:\.\d+)?)%\s*\(")
-# The download dominates the update; extract/validate fill the last slice.
-_DOWNLOAD_PROGRESS_CEILING = 0.95
-
-
-def _utcnow() -> str:
- return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
+_utcnow = _flow.utcnow
+_is_under = _flow.is_under
+_is_external_link = _flow.is_external_link
+_rocm_install_args = _flow.rocm_install_args
def _find_binary() -> Optional[str]:
@@ -94,37 +84,19 @@ def _find_binary() -> Optional[str]:
def _install_dir_for(binary_path: Optional[str]) -> Optional[Path]:
"""The directory holding UNSLOTH_PREBUILT_INFO.json -- i.e. the install root
- install_llama_prebuilt.py wrote and the one we re-install into. Walks up from
- the binary the same way read_install_marker() does."""
- if not binary_path:
- return None
- p = Path(binary_path)
- for parent in p.parents[:5]:
- if (parent / _INSTALL_MARKER_NAME).is_file():
- return parent
- return None
+ install_llama_prebuilt.py wrote and the one we re-install into."""
+ return _flow.install_dir_for(binary_path, marker_name = _INSTALL_MARKER_NAME)
def _installer_script() -> Optional[Path]:
- """Locate install_llama_prebuilt.py. Honours UNSLOTH_LLAMA_INSTALLER, then
- searches up from this file for both ``<root>/install_llama_prebuilt.py`` and
- ``<root>/studio/install_llama_prebuilt.py`` so it works in the dev tree and
- in an installed Unsloth layout."""
- env = os.environ.get("UNSLOTH_LLAMA_INSTALLER")
- if env and Path(env).is_file():
- return Path(env)
- here = Path(__file__).resolve()
- for up in here.parents:
- for cand in (up / "install_llama_prebuilt.py", up / "studio" / "install_llama_prebuilt.py"):
- if cand.is_file():
- return cand
- return None
+ """Locate install_llama_prebuilt.py (UNSLOTH_LLAMA_INSTALLER wins)."""
+ return _flow.find_installer_script(
+ env_var = "UNSLOTH_LLAMA_INSTALLER", script_name = "install_llama_prebuilt.py"
+ )
# Markerless (source-build) installs have no UNSLOTH_PREBUILT_INFO.json, so we
-# ask the installer whether an official prebuilt now exists for this host. Memo
-# is 24h; only successful answers are cached so a network blip retries.
-_RESOLVE_TTL_SECONDS = 24 * 60 * 60
+# ask the installer whether an official prebuilt now exists for this host.
_resolve_memo: dict = {}
@@ -132,39 +104,12 @@ def _resolve_prebuilt_for_host(*, force_refresh: bool = False) -> Optional[dict]
"""Run install_llama_prebuilt.py --resolve-prebuilt (no download) and return
{prebuilt_available, repo, release_tag, llama_tag, asset, install_kind} or
None. Fail-open: any error -> None so a source build never blocks the app."""
- now = time.time()
- if not force_refresh and _resolve_memo:
- if now - _resolve_memo.get("at", 0.0) < _RESOLVE_TTL_SECONDS:
- return _resolve_memo.get("value")
- script = _installer_script()
- if script is None:
- return None
- value: Optional[dict] = None
- try:
- proc = subprocess.run(
- [
- sys.executable,
- str(script),
- "--resolve-prebuilt",
- "latest",
- "--output-format",
- "json",
- ],
- capture_output = True,
- text = True,
- timeout = 60,
- )
- out = (proc.stdout or "").strip()
- if proc.returncode == 0 and out:
- parsed = json.loads(out.splitlines()[-1])
- if isinstance(parsed, dict):
- value = parsed
- except Exception as exc: # pragma: no cover - subprocess/json defensive
- logger.debug("llama update: resolve-prebuilt failed", error = str(exc))
- value = None
- if value is not None: # cache real answers; let failures retry next poll
- _resolve_memo.update(at = now, value = value)
- return value
+ return _flow.resolve_prebuilt_for_host(
+ force_refresh = force_refresh,
+ memo = _resolve_memo,
+ installer_script = lambda: _installer_script(),
+ log_message = "llama update: resolve-prebuilt failed",
+ )
def _installed_build_number(binary: Optional[str]) -> Optional[int]:
@@ -218,38 +163,16 @@ def get_installed_llama_version() -> Optional[str]:
return f"b{n}" if n is not None else None
-def _is_under(path: Path, root: Path) -> bool:
- try:
- p, r = path.resolve(), root.resolve()
- except (OSError, ValueError):
- p, r = path, root
- return p == r or r in p.parents
-
-
def _llama_install_root(binary: Optional[str]) -> Optional[Path]:
"""The Unsloth-managed llama.cpp root the active binary lives under, or None
- when the binary is unmanaged. Installing anywhere the active binary is not
- would not replace what _find_llama_server_binary runs (which prefers a pinned
- LLAMA_SERVER_PATH, then UNSLOTH_LLAMA_CPP_PATH, then a llama.cpp tree), so we
- refuse rather than silently install into an inactive or foreign tree."""
- marked = _install_dir_for(binary)
- if marked is not None:
- return marked
- if not binary:
- return None
- # LLAMA_SERVER_PATH is an explicit user pin that always wins in discovery;
- # never auto-replace its tree (even a user's own llama.cpp checkout).
- if os.environ.get("LLAMA_SERVER_PATH"):
- return None
- p = Path(binary)
- env = os.environ.get("UNSLOTH_LLAMA_CPP_PATH")
- if env and _is_under(p, Path(env)):
- return Path(env)
- for parent in p.parents:
- if parent.name == "llama.cpp":
- return parent
- # PATH / system / custom install: not a managed tree, so do not offer.
- return None
+ when the binary is unmanaged (see update_flow.managed_install_root)."""
+ return _flow.managed_install_root(
+ binary,
+ marker_root = _install_dir_for(binary),
+ server_path_var = "LLAMA_SERVER_PATH",
+ cpp_path_var = "UNSLOTH_LLAMA_CPP_PATH",
+ dir_name = "llama.cpp",
+ )
def _source_build_status(binary: str, *, force_refresh: bool) -> Optional[dict]:
@@ -324,69 +247,83 @@ def _source_build_status(binary: str, *, force_refresh: bool) -> Optional[dict]:
}
-def _is_external_link(path: Optional[Path]) -> bool:
- """True when ``path`` is a --with-llama-cpp-dir local link: a POSIX symlink
- or a Windows directory junction / reparse point. Such a link resolves into
- the user's own llama.cpp checkout, so Unsloth must never auto-update it."""
- if path is None:
- return False
- try:
- if os.path.islink(path):
- return True
- except OSError:
- return False
- if os.name == "nt":
- try:
- import stat
- attrs = os.lstat(path).st_file_attributes # type: ignore[attr-defined]
- return bool(attrs & stat.FILE_ATTRIBUTE_REPARSE_POINT)
- except (OSError, AttributeError):
- return False
- return False
-
-
def _active_install_is_local_link(binary: Optional[str]) -> bool:
"""True when the active llama-server resolves through a --with-llama-cpp-dir
- local link at the canonical llama.cpp directory. An update would write
- through that link into the user's own checkout (or fail), so the install is
- treated as externally managed: no update is offered or applied. Checks only
- up to and including the ``llama.cpp`` dir so a symlinked HOME / studio root
- above it can't trip a false positive."""
- if not binary:
- return False
- for parent in Path(binary).parents:
- if _is_external_link(parent):
- return True
- if parent.name == "llama.cpp":
- break
- return False
+ local link at the canonical llama.cpp directory (see
+ update_flow.active_install_is_local_link)."""
+ return _flow.active_install_is_local_link(binary, dir_name = "llama.cpp")
def _local_link_status() -> dict:
"""Status payload for a local-link install: unmanaged, no update offered."""
- with _job_lock:
- job = dict(_job)
- return {
- "supported": False,
- "update_available": False,
- "stale": False,
- "installed_tag": None,
- "latest_tag": None,
- "published_repo": None,
- "installed_at_utc": None,
- "age_days": None,
- "source_build": False,
- "local_link": True,
- "update_size_bytes": None,
- "job": job,
+ return _flow.local_link_status(_job, _job_lock)
+
+
+def _whisper_chain_status(
+ *, force_refresh: bool = False, paired_llama_will_update: bool = False
+) -> Optional[dict]:
+ """Whisper's piggyback plan for the combined update item (see
+ whisper_cpp_update.chained_phase_plan). None disables the piggyback --
+ fail-open so whisper can never break the llama status or apply."""
+ try:
+ from utils import whisper_cpp_update
+ return whisper_cpp_update.chained_phase_plan(
+ force_refresh = force_refresh,
+ paired_llama_will_update = paired_llama_will_update,
+ )
+ except Exception as exc: # pragma: no cover - defensive
+ logger.debug("llama update: whisper piggyback probe failed", error = str(exc))
+ return None
+
+
+def _merge_whisper_status(status: dict, *, force_refresh: bool = False) -> dict:
+ """Fold the whisper sub-status into the llama status payload: the llama
+ update item is the single UI surface, so update_available becomes the union
+ (llama behind OR whisper behind) while llama_update_available keeps the
+ llama-only flag. All pre-existing top-level fields are preserved."""
+ status["llama_update_available"] = bool(status.get("update_available"))
+ plan = _whisper_chain_status(
+ force_refresh = force_refresh,
+ paired_llama_will_update = status["llama_update_available"],
+ )
+ if plan is None:
+ status["whisper"] = None
+ status["update_component"] = "llama" if status["llama_update_available"] else None
+ return status
+ sub = plan.get("status") or {}
+ status["whisper"] = {
+ "update_available": bool(plan.get("update_available")),
+ "installed_tag": sub.get("installed_tag"),
+ "latest_tag": sub.get("latest_tag"),
+ "update_size_bytes": sub.get("update_size_bytes"),
+ "skip_reason": plan.get("skip_reason"),
}
+ whisper_update_available = bool(plan.get("update_available"))
+ if whisper_update_available:
+ status["update_available"] = True
+ status["update_component"] = (
+ "llama"
+ if status["llama_update_available"]
+ else "whisper"
+ if whisper_update_available
+ else None
+ )
+ return status
def get_update_status(*, force_refresh: bool = False) -> dict:
- """Report whether a newer prebuilt exists plus the current job state.
+ """Report whether an update is available plus the current job state.
- force_refresh bypasses the 24h release cache for an explicit "check now".
+ This is the single main update item: llama.cpp drives it and the whisper
+ piggyback is folded in (see _merge_whisper_status). force_refresh bypasses
+ the 24h release cache for an explicit "check now".
"""
+ status = _llama_only_status(force_refresh = force_refresh)
+ return _merge_whisper_status(status, force_refresh = force_refresh)
+
+
+def _llama_only_status(*, force_refresh: bool = False) -> dict:
+ """The llama.cpp half of get_update_status (no whisper sub-status)."""
binary = _find_binary()
# A --with-llama-cpp-dir local link is the user's own tree; never offer to
# replace it. Bail before any network/freshness work.
@@ -456,33 +393,19 @@ def get_update_status(*, force_refresh: bool = False) -> dict:
}
-def _rocm_install_args(asset: Optional[str]) -> list[str]:
- """Forward --rocm-gfx/--has-rocm from the marker asset, mirroring setup.sh.
- The installer probe can miss the gfx arch on amd-smi-only hosts; per-gfx
- ROCm bundles carry the family in the name (rocm-gfx110X), version-tagged
- bundles only rocm/hip."""
- if not asset:
- return []
- low = asset.lower()
- if "rocm" not in low and "hip" not in low:
- return []
- gfx = re.search(r"-gfx[0-9a-z]+", low)
- if gfx:
- # _normalize_forwarded_gfx accepts the family form (gfx110x -> gfx110X).
- return ["--rocm-gfx", gfx.group(0).lstrip("-")]
- return ["--has-rocm"]
-
-
-def _run_update(
+def _run_llama_phase(
install_dir: Path,
repo: str,
asset: Optional[str],
script: Path,
- pin_release_tag: Optional[str] = None,
+ pin_release_tag: Optional[str],
+ set_progress,
force_cpu: bool = False,
-) -> None:
- """Worker: put the backend into a maintenance state, run the installer for
- the latest prebuilt, then refresh caches so the next load uses the new build.
+) -> dict:
+ """The llama phase of a chained update: put the backend into a maintenance
+ state, run the installer for the latest prebuilt, then refresh caches so the
+ next load uses the new build. Returns {to_tag, reload_required, message};
+ raises on failure.
pin_release_tag pins the installer to that exact published release instead
of letting it re-resolve "latest" itself (see start_update for why)."""
@@ -530,7 +453,6 @@ def _run_update(
if force_cpu:
cmd.append("--force-cpu")
logger.info("llama update: installing", cmd = " ".join(cmd))
- # Stream progress lines into job["progress"].
env = dict(os.environ, UNSLOTH_PROGRESS_PERCENT_STEP = "5")
# Preserve a Vulkan install across updates: detect_host on a CUDA/ROCm
# box would otherwise re-route and silently replace the Vulkan build.
@@ -538,44 +460,12 @@ def _run_update(
# _rocm_install_args).
if asset and "vulkan" in asset.lower():
env["UNSLOTH_FORCE_VULKAN"] = "1"
- proc = subprocess.Popen(
+ _flow.stream_installer(
cmd,
- stdout = subprocess.PIPE,
- stderr = subprocess.STDOUT,
- text = True,
- env = env,
- **child_popen_kwargs(),
+ env,
+ set_progress = set_progress,
+ timeout_seconds = _INSTALL_TIMEOUT_SECONDS,
)
- timed_out = threading.Event()
-
- def _kill_on_timeout() -> None:
- timed_out.set()
- proc.kill()
-
- watchdog = threading.Timer(_INSTALL_TIMEOUT_SECONDS, _kill_on_timeout)
- watchdog.daemon = True
- watchdog.start()
- tail_lines: list[str] = []
- try:
- assert proc.stdout is not None
- for line in proc.stdout:
- tail_lines.append(line)
- if len(tail_lines) > 80:
- del tail_lines[0]
- m = _PROGRESS_LINE_RE.search(line)
- if m is None:
- continue
- fraction = min(float(m.group(1)) / 100.0, 1.0) * _DOWNLOAD_PROGRESS_CEILING
- with _job_lock:
- _job["progress"] = max(_job.get("progress") or 0.0, fraction)
- returncode = proc.wait()
- finally:
- watchdog.cancel()
- if timed_out.is_set():
- raise RuntimeError(f"installer timed out after {_INSTALL_TIMEOUT_SECONDS}s")
- if returncode != 0:
- tail = "".join(tail_lines).strip()[-1500:]
- raise RuntimeError(f"installer exited {returncode}: {tail or 'no output'}")
# Drop stale caches so the banner re-checks the swapped marker.
# If GitHub is offline, latest stays unknown and the banner fails open.
@@ -597,29 +487,18 @@ def _run_update(
):
raise RuntimeError(f"pinned release {pin_release_tag} but installer produced {new_tag}")
- with _job_lock:
- _job.update(
- state = _JOB_SUCCESS,
- message = (
- f"Updated llama.cpp to {new_tag}."
- + (" Reload your model to use it." if model_was_active else "")
- ),
- to_tag = new_tag,
- reload_required = model_was_active,
- error = None,
- progress = 1.0,
- finished_at = _utcnow(),
- )
logger.info("llama update: success", to_tag = new_tag)
+ return {
+ "to_tag": new_tag,
+ "reload_required": model_was_active,
+ "message": (
+ f"Updated llama.cpp to {new_tag}."
+ + (" Reload your model to use it." if model_was_active else "")
+ ),
+ }
except Exception as exc:
logger.warning("llama update: failed", error = str(exc))
- with _job_lock:
- _job.update(
- state = _JOB_ERROR,
- message = "llama.cpp update failed.",
- error = str(exc),
- finished_at = _utcnow(),
- )
+ raise
finally:
# Always clear maintenance state.
if backend is not None:
@@ -629,50 +508,58 @@ def _run_update(
pass
-def start_update() -> dict:
- """Kick off a background update. Idempotent: a second call while one is
- running returns the in-flight job rather than starting another."""
+# 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
+_WHISPER_PHASE_WEIGHT = 0.3
+
+
+def _plan_llama_phase() -> dict:
+ """Decide how the llama phase of a combined update runs. Returns {"spec"}
+ when llama should install, else {"skip_reason", "refusal"}: skip_reason
+ marks the phase skipped inside a chained job, refusal is the started=False
+ response when the whisper phase has nothing to run either."""
binary = _find_binary()
# Refuse to update a --with-llama-cpp-dir local link: installing a prebuilt
# here would write through the link into the user's own checkout (or fail)
# and silently drop the link the flag created.
if _active_install_is_local_link(binary):
return {
- "started": False,
- "reason": "local_link",
- "message": (
- "llama.cpp is a local directory linked with --with-llama-cpp-dir; "
- "Unsloth won't replace it. Update your own llama.cpp checkout instead."
- ),
- "job": get_update_status()["job"],
+ "skip_reason": "local_link",
+ "refusal": {
+ "started": False,
+ "reason": "local_link",
+ "message": (
+ "llama.cpp is a local directory linked with --with-llama-cpp-dir; "
+ "Unsloth won't replace it. Update your own llama.cpp checkout instead."
+ ),
+ },
}
marker = read_install_marker(binary)
script = _installer_script()
if script is None:
return {
- "started": False,
- "reason": "installer_missing",
- "message": "install_llama_prebuilt.py could not be located.",
- "job": get_update_status()["job"],
+ "skip_reason": "installer_missing",
+ "refusal": {
+ "started": False,
+ "reason": "installer_missing",
+ "message": "install_llama_prebuilt.py could not be located.",
+ },
}
- # A job already in flight wins over any freshness re-check below (and skips
- # its network call). The final lock block re-checks to close the TOCTOU.
- with _job_lock:
- if _job["state"] == _JOB_RUNNING:
- return {"started": False, "reason": "already_running", "job": dict(_job)}
-
if marker:
# Mirror the detection guard: a direct POST or a stale banner must not
# start an install when the latest is not actually newer (force a fresh
# check so a stale 24h cache can't wrongly block a real update either).
- status = get_update_status(force_refresh = True)
+ status = _llama_only_status(force_refresh = True)
if not status.get("update_available"):
return {
- "started": False,
- "reason": "up_to_date",
- "message": "The installed llama.cpp build is already at the latest prebuilt.",
- "job": status["job"],
+ "skip_reason": "up_to_date",
+ "refusal": {
+ "started": False,
+ "reason": "up_to_date",
+ "message": "The installed llama.cpp build is already at the latest prebuilt.",
+ },
}
install_dir = _install_dir_for(binary)
repo = marker.get("published_repo") or DEFAULT_PUBLISHED_REPO
@@ -693,20 +580,27 @@ def start_update() -> dict:
src = _source_build_status(binary, force_refresh = True) if binary else None
if src is None:
return {
- "started": False,
- "reason": "no_prebuilt_available",
- "message": (
- "No official llama.cpp prebuilt is available for this host, "
- "so the source build cannot be swapped automatically."
- ),
- "job": get_update_status()["job"],
+ "skip_reason": "no_prebuilt_available",
+ "refusal": {
+ "started": False,
+ "reason": "no_prebuilt_available",
+ "message": (
+ "No official llama.cpp prebuilt is available for this host, "
+ "so the source build cannot be swapped automatically."
+ ),
+ },
}
if not src.get("update_available"):
return {
- "started": False,
- "reason": "up_to_date",
- "message": "The installed llama.cpp build is already at or newer than the latest prebuilt.",
- "job": get_update_status()["job"],
+ "skip_reason": "up_to_date",
+ "refusal": {
+ "started": False,
+ "reason": "up_to_date",
+ "message": (
+ "The installed llama.cpp build is already at or newer than the "
+ "latest prebuilt."
+ ),
+ },
}
res = _resolve_prebuilt_for_host()
install_dir = _llama_install_root(binary)
@@ -721,31 +615,116 @@ def start_update() -> dict:
if install_dir is None:
return {
- "started": False,
- "reason": "no_install_dir",
- "message": "Could not determine the llama.cpp install directory.",
- "job": get_update_status()["job"],
+ "skip_reason": "no_install_dir",
+ "refusal": {
+ "started": False,
+ "reason": "no_install_dir",
+ "message": "Could not determine the llama.cpp install directory.",
+ },
+ }
+ return {
+ "spec": {
+ "install_dir": install_dir,
+ "repo": repo,
+ "asset": asset,
+ "script": script,
+ "pin_release_tag": pin_release_tag,
+ "from_tag": from_tag,
+ "force_cpu": force_cpu,
}
+ }
+
+
+def start_update() -> dict:
+ """Kick off a background update job. The job chains the llama phase (the
+ existing flow) with a whisper phase that runs only when whisper is actually
+ behind; either phase no-ops cleanly when its component is current or
+ unmanaged. Idempotent: a second call while one is running returns the
+ in-flight job rather than starting another."""
+ # A job already in flight wins over any freshness re-check below (and skips
+ # its network calls). The final lock block re-checks to close the TOCTOU.
+ with _job_lock:
+ if _job["state"] == _JOB_RUNNING:
+ return {"started": False, "reason": "already_running", "job": dict(_job)}
+
+ llama_plan = _plan_llama_phase()
+ llama_spec = llama_plan.get("spec")
+ whisper_plan = _whisper_chain_status(
+ force_refresh = True,
+ paired_llama_will_update = llama_spec is not None,
+ )
+ whisper_spec = (whisper_plan or {}).get("phase")
+ if llama_spec is None and whisper_spec is None:
+ # Nothing to run in either phase: answer with the llama refusal so the
+ # existing reasons (local_link / up_to_date / ...) keep their meaning.
+ refusal = dict(llama_plan["refusal"])
+ with _job_lock:
+ refusal["job"] = dict(_job)
+ return refusal
+
+ whisper_run = None
+ if whisper_spec is not None:
+ from utils import whisper_cpp_update as _whisper
+ whisper_run = lambda set_progress: _whisper.run_chained_phase(whisper_spec, set_progress)
+
+ phases = [
+ {
+ "name": "llama",
+ "weight": _LLAMA_PHASE_WEIGHT,
+ "failure_message": "llama.cpp update failed.",
+ "skip_reason": llama_plan.get("skip_reason"),
+ "run": (
+ (
+ lambda set_progress: _run_llama_phase(
+ llama_spec["install_dir"],
+ llama_spec["repo"],
+ llama_spec["asset"],
+ llama_spec["script"],
+ llama_spec["pin_release_tag"],
+ set_progress,
+ force_cpu = llama_spec.get("force_cpu", False),
+ )
+ )
+ if llama_spec
+ else None
+ ),
+ },
+ {
+ "name": "whisper",
+ "weight": _WHISPER_PHASE_WEIGHT,
+ "failure_message": "whisper.cpp update failed.",
+ # The sidecar reload is whisper-internal; it must not trip the
+ # job-level reload flag the chat frontend resyncs on.
+ "affects_job_reload": False,
+ "skip_reason": (whisper_plan or {}).get("skip_reason") or "unavailable",
+ "run": whisper_run,
+ },
+ ]
+ running = " + ".join(
+ name for name, spec in (("llama.cpp", llama_spec), ("whisper.cpp", whisper_spec)) if spec
+ )
with _job_lock:
if _job["state"] == _JOB_RUNNING:
return {"started": False, "reason": "already_running", "job": dict(_job)}
_job.update(
state = _JOB_RUNNING,
- message = "Downloading and installing the latest llama.cpp prebuilt...",
- from_tag = from_tag,
+ message = f"Downloading and installing the latest {running} prebuilt...",
+ from_tag = (llama_spec or {}).get("from_tag"),
to_tag = None,
reload_required = None,
error = None,
progress = 0.0,
started_at = _utcnow(),
finished_at = None,
+ phases = None,
)
job_snapshot = dict(_job)
thread = threading.Thread(
- target = _run_update,
- args = (install_dir, repo, asset, script, pin_release_tag, force_cpu),
+ target = _flow.run_chained_update,
+ args = (phases,),
+ kwargs = {"job": _job, "job_lock": _job_lock},
name = "llama-cpp-update",
daemon = True,
)
@@ -755,15 +734,4 @@ def start_update() -> dict:
def _reset_job_for_tests() -> None:
"""Test-only: return the job tracker to idle."""
- with _job_lock:
- _job.update(
- state = _JOB_IDLE,
- message = "",
- from_tag = None,
- to_tag = None,
- reload_required = None,
- error = None,
- progress = None,
- started_at = None,
- finished_at = None,
- )
+ _flow.reset_job(_job, _job_lock)
diff --git a/studio/backend/utils/prebuilt/__init__.py b/studio/backend/utils/prebuilt/__init__.py
new file mode 100644
index 00000000000..c41cd1150d3
--- /dev/null
+++ b/studio/backend/utils/prebuilt/__init__.py
@@ -0,0 +1,11 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Backend-importable prebuilt helpers.
+
+The installers reuse install_llama_prebuilt.py directly; this package holds the
+backend-side shapes the studio/ scripts cannot provide (the backend runs with
+studio/backend as its sys.path root): runtime_libs (wheel CUDA dirs), child_env
+(secret scrubbing + WSL ROCm dirs), freshness_flow and update_flow (the shared
+mechanics behind the *_cpp_freshness / *_cpp_update twins).
+"""
diff --git a/studio/backend/utils/prebuilt/child_env.py b/studio/backend/utils/prebuilt/child_env.py
new file mode 100644
index 00000000000..b6b7a40df79
--- /dev/null
+++ b/studio/backend/utils/prebuilt/child_env.py
@@ -0,0 +1,145 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Child-process environment hygiene for the managed ggml servers.
+
+Secret-env scrubbing and the WSL2 ROCm library-dir probe, shared by the STT
+sidecar (and any future launcher of a downloaded binary). Kept in sync with
+install_llama_prebuilt.py's scrub_env / _wsl_system_rocm_lib_dirs; the backend
+cannot import the studio/ installer scripts, so this copy stays importable with
+only the backend root on sys.path.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+from typing import Mapping
+
+SECRET_ENV_EXACT = frozenset(
+ {
+ "HF_TOKEN",
+ "HUGGING_FACE_HUB_TOKEN",
+ "GH_TOKEN",
+ "GITHUB_TOKEN",
+ "WANDB_API_KEY",
+ "OPENAI_API_KEY",
+ "ANTHROPIC_API_KEY",
+ "AWS_ACCESS_KEY_ID",
+ "AWS_SECRET_ACCESS_KEY",
+ "AWS_SESSION_TOKEN",
+ "GOOGLE_APPLICATION_CREDENTIALS",
+ "AZURE_CLIENT_SECRET",
+ "KUBECONFIG",
+ "SSH_AUTH_SOCK",
+ }
+)
+# Case-insensitive substring markers for names we do not enumerate (no bare "KEY").
+SECRET_ENV_MARKERS = (
+ "TOKEN",
+ "SECRET",
+ "PASSWORD",
+ "PASSWD",
+ "PASSPHRASE",
+ "CREDENTIAL",
+ "PRIVATE_KEY",
+ "API_KEY",
+)
+# Proxy / index URLs embed creds in their value; the offline server never needs them.
+SECRET_ENV_URL_NAMES = frozenset(
+ {
+ "HTTP_PROXY",
+ "HTTPS_PROXY",
+ "ALL_PROXY",
+ "FTP_PROXY",
+ "RSYNC_PROXY",
+ "PIP_INDEX_URL",
+ "PIP_EXTRA_INDEX_URL",
+ "UV_INDEX_URL",
+ "UV_DEFAULT_INDEX",
+ "UV_EXTRA_INDEX_URL",
+ }
+)
+# Also drop values with URL userinfo creds (scheme://user:secret@host).
+URL_USERINFO_RE = re.compile(r"://[^/@\s]+@")
+
+
+def is_secret_env_name(name: str) -> bool:
+ upper = name.upper()
+ return (
+ upper in SECRET_ENV_EXACT
+ or upper in SECRET_ENV_URL_NAMES
+ or any(marker in upper for marker in SECRET_ENV_MARKERS)
+ )
+
+
+def scrub_env(env: Mapping[str, str]) -> dict[str, str]:
+ """Copy of ``env`` without secret-bearing names or URL-userinfo values."""
+ return {
+ k: v
+ for k, v in env.items()
+ if not is_secret_env_name(k) and not URL_USERINFO_RE.search(v or "")
+ }
+
+
+# Filesystem pointers a downloaded binary could follow to on-disk credential
+# stores (token caches under $HF_HOME, ~/.netrc, XDG config). Dropped, not
+# repointed; the offline inference server needs none. Mirrors the cred-location
+# list of the tools bypass env (core/inference/tools.py).
+CRED_LOCATION_ENV_NAMES = frozenset(
+ {
+ "HF_HOME",
+ "HF_HUB_CACHE",
+ "HUGGINGFACE_HUB_CACHE",
+ "HF_XET_CACHE",
+ "TRANSFORMERS_CACHE",
+ "HF_DATASETS_CACHE",
+ "XDG_CONFIG_HOME",
+ "XDG_CACHE_HOME",
+ "XDG_DATA_HOME",
+ "NETRC",
+ "BASH_ENV",
+ "GIT_CONFIG_GLOBAL",
+ "GIT_CONFIG_SYSTEM",
+ "GIT_ASKPASS",
+ "SSH_ASKPASS",
+ "HOMEDRIVE",
+ "HOMEPATH",
+ }
+)
+# Home dirs are repointed (not dropped): loaders and SDKs expect them present,
+# but they must not resolve to the user's real profile with its token caches.
+HOME_ENV_NAMES = ("HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA")
+
+
+def isolate_home(env: dict[str, str], scratch_dir: str) -> dict[str, str]:
+ """Repoint home/profile vars at ``scratch_dir`` and drop credential-store
+ pointers so a compromised downloaded server cannot read token caches or cred
+ files through the environment. Mutates and returns ``env``."""
+ os.makedirs(scratch_dir, exist_ok = True)
+ for name in HOME_ENV_NAMES:
+ if name in env:
+ env[name] = scratch_dir
+ for name in CRED_LOCATION_ENV_NAMES:
+ env.pop(name, None)
+ return env
+
+
+def wsl_system_rocm_lib_dirs() -> list[str]:
+ """System ROCm lib dir(s) to load before a bundle's HIP on WSL2. Strict no-op
+ off WSL (needs /dev/dxg, a "microsoft" /proc/version, and a librocdxg)."""
+ try:
+ if not os.path.exists("/dev/dxg"):
+ return []
+ with open("/proc/version", encoding = "utf-8", errors = "replace") as fh:
+ if "microsoft" not in fh.read().lower():
+ return []
+ except OSError:
+ return []
+ dirs: list[str] = []
+ for d in ("/opt/rocm/lib", "/opt/rocm/lib64"):
+ if os.path.exists(os.path.join(d, "librocdxg.so")) or os.path.exists(
+ os.path.join(d, "librocdxg.so.1")
+ ):
+ dirs.append(d)
+ return dirs
diff --git a/studio/backend/utils/prebuilt/freshness_flow.py b/studio/backend/utils/prebuilt/freshness_flow.py
new file mode 100644
index 00000000000..b90ebf776ce
--- /dev/null
+++ b/studio/backend/utils/prebuilt/freshness_flow.py
@@ -0,0 +1,325 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Shared mechanics of the llama.cpp / whisper.cpp prebuilt freshness checks.
+
+The component modules (utils.llama_cpp_freshness / utils.whisper_cpp_freshness)
+keep their public names, per-module caches, and version-comparison policy;
+everything mechanical (marker walk-up, GitHub release fetch, memo + disk cache,
+the freshness report skeleton) lives here, parameterized by call-time callables
+so the modules' monkeypatch seams keep working.
+"""
+
+from __future__ import annotations
+
+import json
+import time
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Callable, Optional
+
+import structlog
+
+logger = structlog.get_logger(__name__)
+
+# 24h TTL keeps the GitHub call off the hot path and within rate limits.
+RELEASE_CACHE_TTL_SECONDS = 24 * 60 * 60
+
+
+def read_install_marker(
+ binary_path: Optional[str],
+ *,
+ marker_name: str,
+ cache: dict[str, Optional[dict]],
+ log_message: str,
+) -> Optional[dict]:
+ """Walk up from binary_path to find the install marker JSON.
+ None = no marker (source build / custom path) or invalid JSON."""
+ if not binary_path:
+ return None
+ cached = cache.get(binary_path)
+ if cached is not None or binary_path in cache:
+ return cached
+ p = Path(binary_path)
+ marker: Optional[dict] = None
+ # Cover all managed binary layouts (binary is 1-4 dirs deep).
+ for parent in p.parents[:5]:
+ candidate = parent / marker_name
+ if candidate.is_file():
+ try:
+ marker = json.loads(candidate.read_text(encoding = "utf-8"))
+ except (OSError, json.JSONDecodeError) as exc:
+ logger.debug(log_message, path = str(candidate), error = str(exc))
+ marker = None
+ break
+ cache[binary_path] = marker
+ return marker
+
+
+def cache_path_for(repo: str, cache_dir: Path) -> Path:
+ safe = repo.replace("/", "__")
+ return cache_dir / f"{safe}.json"
+
+
+def load_disk_cache(repo: str, cache_dir: Path) -> Optional[tuple[float, Optional[str]]]:
+ path = cache_path_for(repo, cache_dir)
+ try:
+ payload = json.loads(path.read_text(encoding = "utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return None
+ ts = payload.get("fetched_at")
+ tag = payload.get("latest_tag")
+ if not isinstance(ts, (int, float)):
+ return None
+ return float(ts), tag if isinstance(tag, str) else None
+
+
+def save_disk_cache(
+ repo: str, latest_tag: Optional[str], cache_dir: Path, *, log_message: str
+) -> None:
+ path = cache_path_for(repo, cache_dir)
+ try:
+ path.parent.mkdir(parents = True, exist_ok = True)
+ tmp = path.with_suffix(".tmp")
+ tmp.write_text(
+ json.dumps({"fetched_at": time.time(), "latest_tag": latest_tag}),
+ encoding = "utf-8",
+ )
+ tmp.replace(path)
+ except OSError as exc:
+ logger.debug(log_message, repo = repo, error = str(exc))
+
+
+def _fetch_newest_published_release(
+ repo: str, timeout: float, *, log_message: str
+) -> Optional[dict]:
+ """Newest published (non-draft/non-prerelease) release object for `repo`, by
+ ``published_at``.
+
+ Resolves "latest" the way the installers do, NOT via GitHub's
+ ``/releases/latest`` pointer, which sorts by commit date and can lag the
+ build the installer installs (detection and apply then disagree -- the
+ downgrade/sticky-banner bug). None on any failure (offline, rate-limited)."""
+ import os
+ import urllib.error
+ import urllib.request
+
+ url = f"https://api.github.com/repos/{repo}/releases?per_page=30"
+ headers = {
+ "Accept": "application/vnd.github+json",
+ "User-Agent": "unsloth-studio-freshness-check",
+ }
+ token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
+ if token:
+ headers["Authorization"] = f"Bearer {token}"
+ req = urllib.request.Request(url, headers = headers)
+ try:
+ with urllib.request.urlopen(req, timeout = timeout) as resp:
+ data = json.loads(resp.read().decode("utf-8"))
+ except (
+ urllib.error.URLError,
+ urllib.error.HTTPError,
+ OSError,
+ json.JSONDecodeError,
+ ) as exc:
+ logger.debug(log_message, repo = repo, error = str(exc))
+ return None
+ if not isinstance(data, list):
+ return None
+ published = [
+ r
+ for r in data
+ if isinstance(r, dict)
+ and not r.get("draft")
+ and not r.get("prerelease")
+ and isinstance(r.get("tag_name"), str)
+ and r.get("tag_name")
+ ]
+ if not published:
+ return None
+ return max(published, key = lambda r: r.get("published_at") or "")
+
+
+def fetch_latest_release_tag(
+ repo: str,
+ timeout: float = 5.0,
+ *,
+ log_message: str,
+) -> Optional[str]:
+ """Newest published release tag for `repo`, by publish time. None on failure."""
+ newest = _fetch_newest_published_release(repo, timeout, log_message = log_message)
+ return newest["tag_name"] if newest else None
+
+
+def fetch_latest_release_assets(
+ repo: str,
+ timeout: float = 5.0,
+ *,
+ log_message: str,
+) -> Optional[dict[str, int]]:
+ """Asset name -> size (bytes) for the newest published release of `repo`,
+ selected exactly like fetch_latest_release_tag. None on any failure."""
+ newest = _fetch_newest_published_release(repo, timeout, log_message = log_message)
+ if newest is None:
+ return None
+ assets: dict[str, int] = {}
+ for a in newest.get("assets") or []:
+ name, size = a.get("name"), a.get("size")
+ if isinstance(name, str) and isinstance(size, int):
+ assets[name] = size
+ return assets
+
+
+def latest_published_release(
+ repo: str,
+ *,
+ force_refresh: bool,
+ memo: dict[str, tuple[float, Optional[str]]],
+ cache_dir: Callable[[], Path],
+ fetch: Callable[[str], Optional[str]],
+ save: Callable[[str, Optional[str]], None],
+) -> Optional[str]:
+ """Latest release tag for `repo`. Memo + disk-cached (24h TTL).
+ None when offline and never previously cached."""
+ if not repo:
+ return None
+ now = time.time()
+ if not force_refresh:
+ cached = memo.get(repo)
+ if cached and now - cached[0] < RELEASE_CACHE_TTL_SECONDS:
+ return cached[1]
+ disk = load_disk_cache(repo, cache_dir())
+ if disk and now - disk[0] < RELEASE_CACHE_TTL_SECONDS:
+ memo[repo] = disk
+ return disk[1]
+ latest = fetch(repo)
+ if latest is None:
+ # Keep the last-good disk value rather than poison it with None.
+ disk = load_disk_cache(repo, cache_dir())
+ if disk:
+ memo[repo] = disk
+ return disk[1]
+ return None
+ memo[repo] = (now, latest)
+ save(repo, latest)
+ return latest
+
+
+def latest_release_assets(
+ repo: str,
+ *,
+ force_refresh: bool,
+ memo: dict[str, tuple[float, dict[str, int]]],
+ fetch: Callable[[str], Optional[dict[str, int]]],
+) -> Optional[dict[str, int]]:
+ """Newest-release asset sizes for `repo`, memoized (24h TTL). None when
+ offline and never fetched. In-memory only -- a restart re-fetches."""
+ if not repo:
+ return None
+ now = time.time()
+ if not force_refresh:
+ cached = memo.get(repo)
+ if cached and now - cached[0] < RELEASE_CACHE_TTL_SECONDS:
+ return cached[1]
+ assets = fetch(repo)
+ if assets is None:
+ cached = memo.get(repo)
+ return cached[1] if cached else None
+ memo[repo] = (now, assets)
+ return assets
+
+
+def parse_installed_at(value: object) -> Optional[datetime]:
+ if not isinstance(value, str) or not value:
+ return None
+ s = value.replace("Z", "+00:00") if value.endswith("Z") else value
+ try:
+ dt = datetime.fromisoformat(s)
+ except ValueError:
+ return None
+ if dt.tzinfo is None:
+ dt = dt.replace(tzinfo = timezone.utc)
+ return dt
+
+
+def check_freshness(
+ binary_path: Optional[str],
+ *,
+ threshold_days: int,
+ now: Optional[datetime],
+ read_marker: Callable[[Optional[str]], Optional[dict]],
+ latest_release: Callable[[str], Optional[str]],
+ behind: Callable[[Optional[str], Optional[str]], bool],
+ display_tag: Callable[[dict], Any],
+ compare_tag: Callable[[dict], Any],
+) -> dict:
+ """Freshness report skeleton shared by both components; the component's
+ marker-tag choice and is_behind policy come in as callables. Fails open on
+ missing data (behind/stale stay False)."""
+ out: dict = {
+ "has_marker": False,
+ "stale": False,
+ "behind": False,
+ "installed_tag": None,
+ "latest_tag": None,
+ "installed_at_utc": None,
+ "age_days": None,
+ "published_repo": None,
+ "threshold_days": int(threshold_days),
+ }
+ marker = read_marker(binary_path)
+ if not marker:
+ return out
+ out["has_marker"] = True
+ out["installed_tag"] = display_tag(marker)
+ out["installed_at_utc"] = marker.get("installed_at_utc")
+ out["published_repo"] = marker.get("published_repo")
+
+ installed_full = compare_tag(marker)
+ repo = out["published_repo"]
+ if not repo or not installed_full:
+ return out
+ latest = latest_release(repo)
+ out["latest_tag"] = latest
+ out["behind"] = behind(installed_full, latest)
+ if not out["behind"]:
+ return out
+
+ installed_at = parse_installed_at(out["installed_at_utc"])
+ if installed_at is None:
+ return out
+ now = now or datetime.now(tz = timezone.utc)
+ age_seconds = (now - installed_at).total_seconds()
+ out["age_days"] = max(0, int(age_seconds // 86400))
+ if age_seconds >= threshold_days * 86400:
+ out["stale"] = True
+ return out
+
+
+def format_stale_warning(info: dict, *, component: str) -> str:
+ """Human-readable one-liner for stale prebuilt info."""
+ age = info.get("age_days")
+ installed = info.get("installed_tag") or "unknown"
+ latest = info.get("latest_tag") or "unknown"
+ age_str = f"{age} day{'s' if age != 1 else ''}" if age is not None else "some time"
+ return (
+ f"{component} prebuilt is {age_str} behind: installed "
+ f"{installed}, latest {latest}. Run `unsloth studio update` "
+ f"to refresh."
+ )
+
+
+def reset_caches(
+ caches: tuple[dict, ...], *, drop_disk: bool, cache_dir: Callable[[], Path]
+) -> None:
+ """Drop the in-memory freshness caches; with drop_disk also the on-disk 24h
+ release cache (see the component modules for why)."""
+ for cache in caches:
+ cache.clear()
+ if drop_disk:
+ import shutil
+
+ # cache_dir() is a dedicated freshness-only subdir, re-created on the next
+ # save_disk_cache. ignore_errors so a missing/locked dir is a no-op rather
+ # than breaking an otherwise successful install.
+ shutil.rmtree(cache_dir(), ignore_errors = True)
diff --git a/studio/backend/utils/prebuilt/runtime_libs.py b/studio/backend/utils/prebuilt/runtime_libs.py
new file mode 100644
index 00000000000..6e51fb82464
--- /dev/null
+++ b/studio/backend/utils/prebuilt/runtime_libs.py
@@ -0,0 +1,65 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""CUDA runtime dirs shipped inside Python wheels, for the STT sidecar's child env.
+
+Kept in sync with install_llama_prebuilt.py's python_runtime_dirs; the backend
+cannot import the studio/ installer scripts, so this small copy stays importable
+with only the backend root on sys.path.
+"""
+
+from __future__ import annotations
+
+import site
+import sys
+from pathlib import Path
+from typing import Iterable
+
+
+def dedupe_existing_dirs(paths: Iterable[str | Path]) -> list[str]:
+ unique: list[str] = []
+ seen: set[str] = set()
+ for raw in paths:
+ if not raw:
+ continue
+ try:
+ path = Path(raw).expanduser()
+ if not path.is_dir():
+ continue
+ resolved = str(path.resolve())
+ except (OSError, ValueError):
+ continue
+ if resolved in seen:
+ continue
+ seen.add(resolved)
+ unique.append(resolved)
+ return unique
+
+
+def python_runtime_dirs() -> list[str]:
+ """CUDA runtime dirs shipped inside Python wheels (torch + nvidia-* wheels)."""
+ candidates: list[Path] = []
+ search_roots = [Path(entry) for entry in sys.path if entry]
+ try:
+ search_roots.extend(Path(path) for path in site.getsitepackages())
+ except Exception:
+ pass
+ try:
+ user_site = site.getusersitepackages()
+ if user_site:
+ search_roots.append(Path(user_site))
+ except Exception:
+ pass
+
+ for root in search_roots:
+ if not root.is_dir():
+ continue
+ candidates.extend(root.glob("nvidia/*/lib")) # Linux convention
+ candidates.extend(root.glob("nvidia/*/bin")) # legacy modular Windows wheels
+ candidates.extend(root.glob("nvidia/*/bin/x86_64")) # CUDA 13 Windows wheel layout
+ candidates.extend(root.glob("nvidia/*/bin/x64"))
+ candidates.extend(root.glob("nvidia/*/Library/bin")) # conda-style repacks
+ candidates.extend(root.glob("nvidia/*/Library/bin/x86_64"))
+ candidates.extend(root.glob("nvidia/*/Library/bin/x64"))
+ candidates.extend(root.glob("torch/lib"))
+ return dedupe_existing_dirs(candidates)
diff --git a/studio/backend/utils/prebuilt/update_flow.py b/studio/backend/utils/prebuilt/update_flow.py
new file mode 100644
index 00000000000..74af0c18f9c
--- /dev/null
+++ b/studio/backend/utils/prebuilt/update_flow.py
@@ -0,0 +1,447 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Shared mechanics of the llama.cpp / whisper.cpp in-app prebuilt updates.
+
+The component modules (utils.llama_cpp_update / utils.whisper_cpp_update) keep
+their public names, job dicts, and update policy (version comparison, pinning,
+pre/post install steps); everything mechanical (managed-root resolution,
+local-link detection, the resolve probe, the streamed installer run) lives here,
+parameterized so the modules' monkeypatch seams keep working.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import subprocess
+import sys
+import threading
+import time
+from pathlib import Path
+from typing import Callable, Optional
+
+import structlog
+
+from utils.process_lifetime import child_popen_kwargs
+
+logger = structlog.get_logger(__name__)
+
+# Markerless (source-build) resolve answers are memoized for 24h; only
+# successful answers are cached so a network blip retries.
+RESOLVE_TTL_SECONDS = 24 * 60 * 60
+
+# Matches the installer's download progress lines, e.g.
+# "Downloading x.zip: 35.0% (12.3 MiB/35.1 MiB) at 8.2 MiB/s".
+PROGRESS_LINE_RE = re.compile(r"(\d+(?:\.\d+)?)%\s*\(")
+# The download dominates the update; extract/validate fill the last slice.
+DOWNLOAD_PROGRESS_CEILING = 0.95
+
+
+class InstallerExit(RuntimeError):
+ """Installer subprocess exited nonzero; carries the exit code so phase
+ runners can special-case contractual codes (whisper's 2 = unavailable)."""
+
+ def __init__(self, returncode: int, message: str) -> None:
+ super().__init__(message)
+ self.returncode = returncode
+
+
+JOB_IDLE = "idle"
+JOB_RUNNING = "running"
+JOB_SUCCESS = "success"
+JOB_ERROR = "error"
+
+# Per-phase states inside a chained job's "phases" breakdown.
+PHASE_PENDING = "pending"
+PHASE_RUNNING = "running"
+PHASE_SUCCESS = "success"
+PHASE_ERROR = "error"
+PHASE_SKIPPED = "skipped"
+
+_IDLE_JOB_FIELDS = dict(
+ state = JOB_IDLE,
+ message = "",
+ from_tag = None,
+ to_tag = None,
+ reload_required = None,
+ error = None,
+ progress = None,
+ started_at = None,
+ finished_at = None,
+ phases = None,
+)
+
+
+def new_job() -> dict:
+ """A fresh idle job-state dict (one per component module)."""
+ return dict(_IDLE_JOB_FIELDS)
+
+
+def reset_job(job: dict, job_lock: threading.Lock) -> None:
+ """Return a job tracker to idle (test seam)."""
+ with job_lock:
+ job.update(_IDLE_JOB_FIELDS)
+
+
+def utcnow() -> str:
+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
+
+
+def is_under(path: Path, root: Path) -> bool:
+ try:
+ p, r = path.resolve(), root.resolve()
+ except (OSError, ValueError):
+ p, r = path, root
+ return p == r or r in p.parents
+
+
+def install_dir_for(binary_path: Optional[str], *, marker_name: str) -> Optional[Path]:
+ """The directory holding the install marker: the install root the installer
+ wrote and the one we re-install into. Walks up from the binary like the
+ freshness marker reader does."""
+ if not binary_path:
+ return None
+ p = Path(binary_path)
+ for parent in p.parents[:5]:
+ if (parent / marker_name).is_file():
+ return parent
+ return None
+
+
+def find_installer_script(*, env_var: str, script_name: str) -> Optional[Path]:
+ """Locate the installer script. Honours the env override, then searches up
+ from this file for both ``<root>/<script>`` and ``<root>/studio/<script>`` so
+ it works in the dev tree and in an installed Unsloth layout."""
+ env = os.environ.get(env_var)
+ if env and Path(env).is_file():
+ return Path(env)
+ here = Path(__file__).resolve()
+ for up in here.parents:
+ for cand in (up / script_name, up / "studio" / script_name):
+ if cand.is_file():
+ return cand
+ return None
+
+
+def resolve_prebuilt_for_host(
+ *,
+ force_refresh: bool,
+ memo: dict,
+ installer_script: Callable[[], Optional[Path]],
+ log_message: str,
+ extra_args: tuple[str, ...] = (),
+) -> Optional[dict]:
+ """Run ``<installer> --resolve-prebuilt latest --output-format json`` (no
+ download); return the parsed payload or None. Fail-open: any error -> None so
+ a source build never blocks the app."""
+ now = time.time()
+ cache_key = tuple(extra_args)
+ if not force_refresh and memo.get("key") == cache_key:
+ if now - memo.get("at", 0.0) < RESOLVE_TTL_SECONDS:
+ return memo.get("value")
+ script = installer_script()
+ if script is None:
+ return None
+ value: Optional[dict] = None
+ try:
+ cmd = [
+ sys.executable,
+ str(script),
+ "--resolve-prebuilt",
+ "latest",
+ "--output-format",
+ "json",
+ *extra_args,
+ ]
+ proc = subprocess.run(
+ cmd,
+ capture_output = True,
+ text = True,
+ timeout = 60,
+ )
+ out = (proc.stdout or "").strip()
+ if proc.returncode == 0 and out:
+ parsed = json.loads(out.splitlines()[-1])
+ if isinstance(parsed, dict):
+ value = parsed
+ except Exception as exc: # pragma: no cover - subprocess/json defensive
+ logger.debug(log_message, error = str(exc))
+ value = None
+ if value is not None: # cache real answers; let failures retry next poll
+ memo.update(at = now, key = cache_key, value = value)
+ return value
+
+
+def is_external_link(path: Optional[Path]) -> bool:
+ """True when ``path`` is a locally-linked component dir: a POSIX symlink or a
+ Windows junction / reparse point. Such a link resolves into the user's own
+ checkout, so Unsloth must never auto-update it."""
+ if path is None:
+ return False
+ try:
+ if os.path.islink(path):
+ return True
+ except OSError:
+ return False
+ if os.name == "nt":
+ try:
+ import stat
+ attrs = os.lstat(path).st_file_attributes # type: ignore[attr-defined]
+ return bool(attrs & stat.FILE_ATTRIBUTE_REPARSE_POINT)
+ except (OSError, AttributeError):
+ return False
+ return False
+
+
+def active_install_is_local_link(binary: Optional[str], *, dir_name: str) -> bool:
+ """True when the active server binary resolves through a locally-linked
+ component directory. An update would write through that link into the user's
+ checkout (or fail), so the install is treated as externally managed: none is
+ offered or applied. Checks only up to and including the component dir so a
+ symlinked HOME / studio root above it can't trip a false positive."""
+ if not binary:
+ return False
+ for parent in Path(binary).parents:
+ if is_external_link(parent):
+ return True
+ if parent.name == dir_name:
+ break
+ return False
+
+
+def managed_install_root(
+ binary: Optional[str],
+ *,
+ marker_root: Optional[Path],
+ server_path_var: str,
+ cpp_path_var: str,
+ dir_name: str,
+) -> Optional[Path]:
+ """The Unsloth-managed component root the active binary lives under, or None
+ when unmanaged. Installing where the active binary is not would not replace
+ what discovery runs (a pinned server path, then the custom dir, then a
+ component tree), so we refuse rather than install into an inactive or foreign
+ tree."""
+ if marker_root is not None:
+ return marker_root
+ if not binary:
+ return None
+ # The server-path pin is an explicit user choice that wins in discovery; never
+ # auto-replace its tree (even the user's own checkout).
+ if os.environ.get(server_path_var):
+ return None
+ p = Path(binary)
+ env = os.environ.get(cpp_path_var)
+ if env and is_under(p, Path(env)):
+ return Path(env)
+ for parent in p.parents:
+ if parent.name == dir_name:
+ return parent
+ # PATH / system / custom install: not a managed tree, so do not offer.
+ return None
+
+
+def local_link_status(job: dict, job_lock: threading.Lock) -> dict:
+ """Status payload for a local-link install: unmanaged, no update offered."""
+ with job_lock:
+ snapshot = dict(job)
+ return {
+ "supported": False,
+ "update_available": False,
+ "stale": False,
+ "installed_tag": None,
+ "latest_tag": None,
+ "published_repo": None,
+ "installed_at_utc": None,
+ "age_days": None,
+ "source_build": False,
+ "local_link": True,
+ "update_size_bytes": None,
+ "job": snapshot,
+ }
+
+
+def rocm_install_args(asset: Optional[str]) -> list[str]:
+ """Forward --rocm-gfx/--has-rocm from the marker asset, mirroring setup.sh.
+ The installer probe can miss the gfx arch on amd-smi-only hosts; per-gfx ROCm
+ bundles carry the family in the name (rocm-gfx110X), version-tagged bundles
+ only rocm/hip."""
+ if not asset:
+ return []
+ low = asset.lower()
+ if "rocm" not in low and "hip" not in low:
+ return []
+ gfx = re.search(r"-gfx[0-9a-z]+", low)
+ if gfx:
+ return ["--rocm-gfx", gfx.group(0).lstrip("-")]
+ return ["--has-rocm"]
+
+
+def stream_installer(
+ cmd: list[str],
+ env: dict[str, str],
+ *,
+ timeout_seconds: int,
+ job: Optional[dict] = None,
+ job_lock: Optional[threading.Lock] = None,
+ set_progress: Optional[Callable[[float], None]] = None,
+) -> None:
+ """Run the installer, streaming its progress lines into job["progress"]
+ (or through set_progress when given, e.g. a chained-phase progress window).
+ Raises RuntimeError on timeout or a nonzero exit (with an output tail)."""
+ if set_progress is None:
+ assert job is not None and job_lock is not None
+
+ def set_progress(fraction: float) -> None:
+ with job_lock:
+ job["progress"] = max(job.get("progress") or 0.0, fraction)
+
+ proc = subprocess.Popen(
+ cmd,
+ stdout = subprocess.PIPE,
+ stderr = subprocess.STDOUT,
+ text = True,
+ env = env,
+ **child_popen_kwargs(),
+ )
+ timed_out = threading.Event()
+
+ def _kill_on_timeout() -> None:
+ timed_out.set()
+ proc.kill()
+
+ watchdog = threading.Timer(timeout_seconds, _kill_on_timeout)
+ watchdog.daemon = True
+ watchdog.start()
+ tail_lines: list[str] = []
+ try:
+ assert proc.stdout is not None
+ for line in proc.stdout:
+ tail_lines.append(line)
+ if len(tail_lines) > 80:
+ del tail_lines[0]
+ m = PROGRESS_LINE_RE.search(line)
+ if m is None:
+ continue
+ set_progress(min(float(m.group(1)) / 100.0, 1.0) * DOWNLOAD_PROGRESS_CEILING)
+ returncode = proc.wait()
+ finally:
+ watchdog.cancel()
+ if timed_out.is_set():
+ raise RuntimeError(f"installer timed out after {timeout_seconds}s")
+ if returncode != 0:
+ tail = "".join(tail_lines).strip()[-1500:]
+ raise InstallerExit(returncode, f"installer exited {returncode}: {tail or 'no output'}")
+
+
+def _new_phase_record(spec: dict) -> dict:
+ """Initial breakdown entry for one phase of a chained job."""
+ runnable = spec.get("run") is not None
+ return {
+ "state": PHASE_PENDING if runnable else PHASE_SKIPPED,
+ "reason": None if runnable else spec.get("skip_reason"),
+ "progress": None,
+ "to_tag": None,
+ "reload_required": None,
+ "message": "",
+ "error": None,
+ }
+
+
+def run_chained_update(phases: list[dict], *, job: dict, job_lock: threading.Lock) -> None:
+ """Run update phases in order into one shared job dict (the worker of a
+ combined llama+whisper apply).
+
+ Each phase spec: ``name`` (breakdown key), ``weight`` (progress slice,
+ normalized over runnable phases), ``run`` (callable(set_progress) -> result
+ dict with to_tag/reload_required/message, raises on failure; None = skipped)
+ and ``skip_reason`` / ``failure_message``. A failing phase aborts the chain:
+ later phases are marked skipped (reason "aborted") and the job goes to error,
+ keeping the reload_required and messages of already-succeeded phases so a
+ partial success stays visible."""
+ runnable = [p for p in phases if p.get("run") is not None]
+ total_weight = sum(float(p.get("weight") or 1.0) for p in runnable) or 1.0
+ with job_lock:
+ job["phases"] = {p["name"]: _new_phase_record(p) for p in phases}
+
+ offset = 0.0
+ done_messages: list[str] = []
+ reload_required = False
+ primary_to_tag: Optional[str] = None
+ for index, phase in enumerate(phases):
+ if phase.get("run") is None:
+ continue
+ name = phase["name"]
+ weight = float(phase.get("weight") or 1.0) / total_weight
+ with job_lock:
+ job["phases"][name].update(state = PHASE_RUNNING, progress = 0.0)
+
+ def set_progress(
+ fraction: float,
+ *,
+ _name: str = name,
+ _base: float = offset,
+ _slice: float = weight,
+ ) -> None:
+ f = max(0.0, min(float(fraction), 1.0))
+ with job_lock:
+ record = job["phases"][_name]
+ record["progress"] = max(record.get("progress") or 0.0, f)
+ job["progress"] = max(job.get("progress") or 0.0, _base + f * _slice)
+
+ try:
+ result = phase["run"](set_progress) or {}
+ except Exception as exc:
+ failure = phase.get("failure_message") or f"{name} update failed."
+ with job_lock:
+ job["phases"][name].update(state = PHASE_ERROR, error = str(exc))
+ for later in phases[index + 1 :]:
+ if later.get("run") is not None:
+ job["phases"][later["name"]].update(state = PHASE_SKIPPED, reason = "aborted")
+ # A partial success keeps its messages and reload_required so the
+ # caller sees the earlier phase did land.
+ job.update(
+ state = JOB_ERROR,
+ message = " ".join(done_messages + [failure]),
+ to_tag = primary_to_tag,
+ error = str(exc),
+ finished_at = utcnow(),
+ )
+ if done_messages:
+ job["reload_required"] = reload_required
+ return
+ set_progress(1.0)
+ offset += weight
+ with job_lock:
+ job["phases"][name].update(
+ state = PHASE_SUCCESS,
+ to_tag = result.get("to_tag"),
+ reload_required = result.get("reload_required"),
+ message = result.get("message") or "",
+ )
+ if result.get("message"):
+ done_messages.append(result["message"])
+ # Only phases affecting the primary (llama) server may raise the job-level
+ # reload flag: the frontend resyncs chat model state off it, and a
+ # whisper-only sidecar reload must not clear the chat checkpoint. Per-phase
+ # reload_required stays visible under job["phases"].
+ if phase.get("affects_job_reload", True):
+ reload_required = reload_required or bool(result.get("reload_required"))
+ # The legacy job-level to_tag means "the llama build now installed";
+ # a whisper-only round must leave it unset or the UI reports a llama
+ # update that never ran (per-phase to_tag remains under phases).
+ if primary_to_tag is None:
+ primary_to_tag = result.get("to_tag")
+
+ with job_lock:
+ job.update(
+ state = JOB_SUCCESS,
+ message = " ".join(done_messages) or "Already up to date.",
+ to_tag = primary_to_tag,
+ reload_required = reload_required,
+ error = None,
+ progress = 1.0,
+ finished_at = utcnow(),
+ )
diff --git a/studio/backend/utils/prebuilt/whisper_layout.py b/studio/backend/utils/prebuilt/whisper_layout.py
new file mode 100644
index 00000000000..7444e4e707e
--- /dev/null
+++ b/studio/backend/utils/prebuilt/whisper_layout.py
@@ -0,0 +1,74 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Canonical whisper.cpp install-root and marker lookup helpers."""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Optional
+
+MARKER_NAME = "UNSLOTH_WHISPER_PREBUILT_INFO.json"
+
+
+@dataclass(frozen = True)
+class MarkerLookup:
+ marker: Optional[dict]
+ root: Optional[Path]
+ authoritative: bool
+ invalid: bool = False
+ slim_collision: bool = False
+
+
+def canonical_install_root(binary_path: Optional[str]) -> Optional[Path]:
+ """Return the managed root for the two supported CMake binary layouts."""
+ if not binary_path:
+ return None
+ parent = Path(binary_path).parent
+ if parent.name == "bin" and parent.parent.name == "build":
+ return parent.parent.parent
+ if (
+ parent.name == "Release"
+ and parent.parent.name == "bin"
+ and parent.parent.parent.name == "build"
+ ):
+ return parent.parent.parent.parent
+ return None
+
+
+def _parse_marker(path: Path) -> tuple[Optional[dict], bool]:
+ try:
+ payload = json.loads(path.read_text(encoding = "utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return None, True
+ return (payload, False) if isinstance(payload, dict) else (None, True)
+
+
+def lookup_marker(binary_path: Optional[str]) -> MarkerLookup:
+ """Prefer the install-root marker over archive metadata beside the binary."""
+ if not binary_path:
+ return MarkerLookup(None, None, False)
+ binary = Path(binary_path)
+ root = canonical_install_root(binary_path)
+ inner_marker = binary.parent / MARKER_NAME
+ inner_payload, _ = _parse_marker(inner_marker) if inner_marker.is_file() else (None, False)
+ slim_collision = bool(
+ inner_payload
+ and (inner_payload.get("install_kind") == "slim" or inner_payload.get("backend") == "slim")
+ )
+ if root is not None:
+ root_marker = root / MARKER_NAME
+ if root_marker.is_file():
+ marker, invalid = _parse_marker(root_marker)
+ return MarkerLookup(marker, root, True, invalid, slim_collision)
+ if slim_collision:
+ return MarkerLookup(None, root, False, True, True)
+
+ for parent in binary.parents[:5]:
+ candidate = parent / MARKER_NAME
+ if candidate.is_file():
+ marker, invalid = _parse_marker(candidate)
+ return MarkerLookup(marker, parent, False, invalid, slim_collision)
+ return MarkerLookup(None, None, False)
diff --git a/studio/backend/utils/upload_limits.py b/studio/backend/utils/upload_limits.py
index fff0ac423f9..662af0f1dd2 100644
--- a/studio/backend/utils/upload_limits.py
+++ b/studio/backend/utils/upload_limits.py
@@ -14,6 +14,9 @@ MIN_UPLOAD_LIMIT_MB = 1
MAX_UPLOAD_LIMIT_MB = 8192
_BYTES_PER_MB = 1024 * 1024
MULTIPART_OVERHEAD_BYTES = 10 * _BYTES_PER_MB
+STT_AUDIO_RAW_MAX_BYTES = 25 * _BYTES_PER_MB
+STT_AUDIO_B64_MAX_CHARS = ((STT_AUDIO_RAW_MAX_BYTES + 2) // 3) * 4
+STT_AUDIO_JSON_MAX_BYTES = STT_AUDIO_B64_MAX_CHARS + 64 * 1024
LOCAL_SEED_UPLOAD_MAX_BYTES = 100 * _BYTES_PER_MB
LOCAL_SEED_UPLOAD_MAX_LABEL = "100MB"
diff --git a/studio/backend/utils/whisper_cpp_freshness.py b/studio/backend/utils/whisper_cpp_freshness.py
new file mode 100644
index 00000000000..59749455b16
--- /dev/null
+++ b/studio/backend/utils/whisper_cpp_freshness.py
@@ -0,0 +1,254 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""whisper.cpp prebuilt freshness check.
+
+Reads UNSLOTH_WHISPER_PREBUILT_INFO.json (written by install_whisper_prebuilt.py)
+and compares the installed release tag against the latest on GitHub. Surfaced via
+utils.whisper_cpp_update (GET /api/whisper/update-status and the combined
+llama+whisper update status). Fails open on any missing data so we never show a
+misleading banner.
+
+The mechanics (marker walk-up, GitHub fetch, memo + disk cache, report skeleton)
+live in utils.prebuilt.freshness_flow; this module keeps the whisper version
+policy and the per-module caches its tests patch.
+"""
+
+from __future__ import annotations
+
+import re
+from datetime import datetime
+from pathlib import Path
+from typing import Optional
+
+import structlog
+
+from utils.prebuilt import freshness_flow as _flow
+from utils.prebuilt.whisper_layout import lookup_marker
+
+logger = structlog.get_logger(__name__)
+
+# 3 days matches Unsloth's typical whisper.cpp release cadence.
+STALENESS_THRESHOLD_DAYS = 3
+
+_INSTALL_MARKER_NAME = "UNSLOTH_WHISPER_PREBUILT_INFO.json"
+
+_marker_cache: dict[str, Optional[dict]] = {}
+_release_memo: dict[str, tuple[float, Optional[str]]] = {}
+# Newest-release asset sizes (name -> bytes), memoized like the tag (24h TTL).
+_assets_memo: dict[str, tuple[float, dict[str, int]]] = {}
+
+
+def _cache_dir() -> Path:
+ """Lazy import so tests can stub storage_roots."""
+ try:
+ from utils.paths.storage_roots import cache_root
+ return cache_root() / "whisper_cpp_freshness"
+ except Exception:
+ return Path.home() / ".unsloth" / "studio" / "cache" / "whisper_cpp_freshness"
+
+
+def read_install_marker(binary_path: Optional[str]) -> Optional[dict]:
+ """Walk up from binary_path to find UNSLOTH_WHISPER_PREBUILT_INFO.json.
+ None = no marker (source build / custom path) or invalid JSON."""
+ if not binary_path:
+ return None
+ cached = _marker_cache.get(binary_path)
+ if cached is not None or binary_path in _marker_cache:
+ return cached
+ marker = lookup_marker(binary_path).marker
+ _marker_cache[binary_path] = marker
+ return marker
+
+
+def _load_disk_cache(repo: str) -> Optional[tuple[float, Optional[str]]]:
+ return _flow.load_disk_cache(repo, _cache_dir())
+
+
+def _save_disk_cache(repo: str, latest_tag: Optional[str]) -> None:
+ _flow.save_disk_cache(
+ repo, latest_tag, _cache_dir(), log_message = "whisper freshness cache write failed"
+ )
+
+
+def _fetch_latest_release_tag(repo: str, timeout: float = 5.0) -> Optional[str]:
+ """Newest published release tag for `repo`, by publish time (see
+ freshness_flow for why this is not GitHub's /releases/latest pointer)."""
+ return _flow.fetch_latest_release_tag(
+ repo, timeout, log_message = "whisper freshness fetch failed"
+ )
+
+
+def latest_published_release(repo: str, *, force_refresh: bool = False) -> Optional[str]:
+ """Latest release tag for `repo`. Memo + disk-cached (24h TTL).
+ None when offline and never previously cached."""
+ return _flow.latest_published_release(
+ repo,
+ force_refresh = force_refresh,
+ memo = _release_memo,
+ cache_dir = lambda: _cache_dir(),
+ fetch = lambda r: _fetch_latest_release_tag(r),
+ save = lambda r, tag: _save_disk_cache(r, tag),
+ )
+
+
+def _fetch_latest_release_assets(repo: str, timeout: float = 5.0) -> Optional[dict[str, int]]:
+ """Asset name -> size (bytes) for the newest published release of `repo`,
+ selected exactly like _fetch_latest_release_tag. None on any failure."""
+ return _flow.fetch_latest_release_assets(
+ repo, timeout, log_message = "whisper freshness asset fetch failed"
+ )
+
+
+def latest_release_assets(repo: str, *, force_refresh: bool = False) -> Optional[dict[str, int]]:
+ """Newest-release asset sizes for `repo`, memoized (24h TTL). None when
+ offline and never fetched. In-memory only -- a restart simply re-fetches."""
+ return _flow.latest_release_assets(
+ repo,
+ force_refresh = force_refresh,
+ memo = _assets_memo,
+ fetch = lambda r: _fetch_latest_release_assets(r),
+ )
+
+
+def _asset_platform_suffix(asset: str, installed_tag: Optional[str]) -> Optional[str]:
+ """The tag-independent ``<os>-<arch>-<accel>.<ext>`` suffix identifying this
+ host's bundle, from stripping the ``whisper-<tag>-`` prefix off the installed
+ asset name. Falls back to anchoring on the platform token when the marker tag
+ does not line up with the asset's embedded tag."""
+ if isinstance(installed_tag, str) and installed_tag:
+ tag = installed_tag if installed_tag.startswith("v") else f"v{installed_tag}"
+ prefix = f"whisper-{tag}-"
+ if asset.startswith(prefix):
+ return asset[len(prefix) :]
+ m = re.search(r"-((?:linux|macos|windows)-.*)$", asset)
+ return m.group(1) if m else None
+
+
+def update_download_size_bytes(
+ marker: Optional[dict],
+ latest_tag: Optional[str],
+ repo: Optional[str],
+ *,
+ force_refresh: bool = False,
+) -> Optional[int]:
+ """Download size of the latest-release asset matching this host's installed
+ bundle (same platform/arch/accel suffix). None when there is no marker asset,
+ the latest assets can't be read, or no match.
+
+ Assets are named ``whisper-<tag>-<os>-<arch>-<accel>.<ext>`` and the fork
+ builds every slice itself, so only the publish repo is consulted (no
+ upstream/binary_repo passthrough)."""
+ if not marker or not latest_tag or not repo:
+ return None
+ installed_asset = marker.get("asset")
+ if not isinstance(installed_asset, str) or not installed_asset:
+ return None
+ suffix = _asset_platform_suffix(installed_asset, marker.get("release_tag"))
+ if not suffix:
+ return None
+ assets = latest_release_assets(repo, force_refresh = force_refresh)
+ if not assets:
+ return None
+ latest_v = latest_tag if latest_tag.startswith("v") else f"v{latest_tag}"
+ want = f"whisper-{latest_v}-{suffix}"
+ if want in assets:
+ return assets[want]
+ # Tag formatting can vary; fall back to the platform+accel suffix.
+ for name, size in assets.items():
+ if name.endswith(suffix):
+ return size
+ return None
+
+
+def parse_release_version(tag: object) -> Optional[tuple]:
+ """Comparable key ``(upstream_major, upstream_minor, upstream_patch,
+ unsloth_serial)`` for a tag like ``v1.9.1-unsloth.2``.
+
+ Tolerant of a leading ``v`` and a missing ``-unsloth.N`` suffix (serial then
+ 0); the upstream version is padded to major/minor/patch. None when the version
+ component is not purely numeric."""
+ if not isinstance(tag, str):
+ return None
+ s = tag.strip()
+ if not s:
+ return None
+ if s[0] in ("v", "V"):
+ s = s[1:]
+ serial = 0
+ m = re.search(r"-unsloth\.(\d+)$", s)
+ if m:
+ serial = int(m.group(1))
+ s = s[: m.start()]
+ parts = s.split(".")
+ nums: list[int] = []
+ for part in parts:
+ if not part.isdigit():
+ return None
+ nums.append(int(part))
+ if not nums:
+ return None
+ while len(nums) < 3:
+ nums.append(0)
+ return (nums[0], nums[1], nums[2], serial)
+
+
+def is_behind(installed: Optional[str], latest: Optional[str]) -> bool:
+ """Whether `installed` is genuinely behind `latest`.
+
+ - identical tags -> not behind (clears the sticky banner post-update)
+ - both parse -> behind only when the latest version key is strictly greater
+ (a lower/equal version is never "behind" -> downgrade guard)
+ - either fails to parse and they differ -> behind (plain inequality)
+ """
+ if not installed or not latest:
+ return False
+ installed, latest = installed.strip(), latest.strip()
+ if installed == latest:
+ return False
+ installed_key, latest_key = parse_release_version(installed), parse_release_version(latest)
+ if installed_key is not None and latest_key is not None:
+ return latest_key > installed_key
+ # One side is unparseable and the tags already differ: treat as behind.
+ return True
+
+
+def check_prebuilt_freshness(
+ binary_path: Optional[str],
+ *,
+ threshold_days: int = STALENESS_THRESHOLD_DAYS,
+ now: Optional[datetime] = None,
+) -> dict:
+ """Returns {has_marker, stale, behind, installed_tag, latest_tag,
+ installed_at_utc, age_days, published_repo, threshold_days}.
+ behind = installed genuinely older than latest (see is_behind).
+ stale = behind AND age >= threshold.
+ Fails open on missing data (behind/stale stay False)."""
+ # The whisper marker records a single ``release_tag`` (e.g. v1.9.1-unsloth.2);
+ # both display and comparison use it directly.
+ return _flow.check_freshness(
+ binary_path,
+ threshold_days = threshold_days,
+ now = now,
+ read_marker = lambda p: read_install_marker(p),
+ latest_release = lambda repo: latest_published_release(repo),
+ behind = lambda installed, latest: is_behind(installed, latest),
+ display_tag = lambda marker: marker.get("release_tag"),
+ compare_tag = lambda marker: marker.get("release_tag"),
+ )
+
+
+def reset_caches(*, drop_disk: bool = False) -> None:
+ """Drop the in-memory freshness caches. The no-arg form is test-only.
+
+ With ``drop_disk = True`` also delete the on-disk 24h release cache. Used by
+ the post-install/update path: clearing memory alone leaves the stale
+ same-version value on disk, so an offline post-install GitHub refresh would
+ replay it (latest_published_release's last-good fallback) and the banner could
+ linger. Dropping the disk cache makes latest read None in that offline case,
+ so the banner fails open (off) rather than point at the just-replaced build."""
+ _flow.reset_caches(
+ (_marker_cache, _release_memo, _assets_memo),
+ drop_disk = drop_disk,
+ cache_dir = lambda: _cache_dir(),
+ )
diff --git a/studio/backend/utils/whisper_cpp_update.py b/studio/backend/utils/whisper_cpp_update.py
new file mode 100644
index 00000000000..cac37c25fc0
--- /dev/null
+++ b/studio/backend/utils/whisper_cpp_update.py
@@ -0,0 +1,490 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""In-app whisper.cpp prebuilt update.
+
+Builds on utils.whisper_cpp_freshness (which detects whether a newer prebuilt
+release exists) and adds the *apply* half: run install_whisper_prebuilt.py to
+download the newest bundle for this host and atomically swap it in, so the next
+model load uses it. Applies only run as the whisper phase of the combined
+llama+whisper update (utils.llama_cpp_update.start_update chains
+run_chained_phase); there is no standalone whisper update trigger.
+
+Design notes:
+- Detection is delegated to check_prebuilt_freshness(). We surface an
+ ``update_available`` flag (installed_tag != latest_tag), laxer than freshness'
+ ``stale`` (which also requires the install to be >= 3 days old). The UI shows
+ the single main update item on update_available.
+- Everything fails open: a missing marker / offline GitHub / source build just
+ reports update_available=False and never blocks the app.
+- The mechanics (managed-root resolution, local-link detection, the resolve
+ probe, the streamed installer run) live in utils.prebuilt.update_flow; this
+ module keeps the whisper policy. The ``job`` dict in the status payload stays
+ idle (kept for response-shape stability): chained applies report progress
+ through the llama job.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import subprocess
+import sys
+import threading
+from pathlib import Path
+from typing import Optional
+
+import structlog
+
+from utils.prebuilt import update_flow as _flow
+from utils.prebuilt.whisper_layout import canonical_install_root
+from utils.whisper_cpp_freshness import (
+ _INSTALL_MARKER_NAME,
+ check_prebuilt_freshness,
+ is_behind,
+ latest_published_release,
+ latest_release_assets,
+ parse_release_version,
+ read_install_marker,
+ reset_caches,
+ update_download_size_bytes,
+)
+
+logger = structlog.get_logger(__name__)
+
+DEFAULT_PUBLISHED_REPO = "unslothai/whisper.cpp"
+_INSTALL_TIMEOUT_SECONDS = 1800 # 30 min ceiling for download + extract/validate
+
+# Always-idle job payload: whisper applies run inside the chained llama job, so
+# nothing flips this to running. Kept so status payload shapes stay stable.
+_job_lock = threading.Lock()
+_job: dict = _flow.new_job()
+
+_rocm_install_args = _flow.rocm_install_args
+
+
+def _find_binary() -> Optional[str]:
+ """Locate the active whisper-server binary via the STT sidecar's own resolver
+ so update targets exactly what Unsloth runs. Lazy import keeps the heavy
+ inference module off this module's import path."""
+ try:
+ from core.inference.stt_ggml_sidecar import find_whisper_server_binary
+ return find_whisper_server_binary()
+ except Exception as exc: # pragma: no cover - defensive
+ logger.debug("whisper update: binary discovery failed", error = str(exc))
+ return None
+
+
+def _install_dir_for(binary_path: Optional[str]) -> Optional[Path]:
+ """The directory holding UNSLOTH_WHISPER_PREBUILT_INFO.json: the install root
+ install_whisper_prebuilt.py wrote (``<install-dir>`` whose canonical server is
+ ``build/bin/whisper-server``) and the one we re-install into."""
+ root = canonical_install_root(binary_path)
+ if root is not None and (root / _INSTALL_MARKER_NAME).is_file():
+ return root
+ return _flow.install_dir_for(binary_path, marker_name = _INSTALL_MARKER_NAME)
+
+
+def _installer_script() -> Optional[Path]:
+ """Locate install_whisper_prebuilt.py (UNSLOTH_WHISPER_INSTALLER wins)."""
+ return _flow.find_installer_script(
+ env_var = "UNSLOTH_WHISPER_INSTALLER", script_name = "install_whisper_prebuilt.py"
+ )
+
+
+# Markerless (source-build) installs have no UNSLOTH_WHISPER_PREBUILT_INFO.json,
+# so we ask the installer whether an official prebuilt now exists for this host.
+_resolve_memo: dict = {}
+
+
+def _resolve_prebuilt_for_host(
+ *, force_refresh: bool = False, backend: Optional[str] = None
+) -> Optional[dict]:
+ """Run install_whisper_prebuilt.py --resolve-prebuilt (no download); return
+ {prebuilt_available, repo, release_tag, upstream_tag, backend, asset, os,
+ arch, ...} or None. Fail-open: any error -> None so a source build never
+ blocks the app."""
+ extra_args = ("--backend", backend) if backend else ()
+ return _flow.resolve_prebuilt_for_host(
+ force_refresh = force_refresh,
+ memo = _resolve_memo,
+ installer_script = lambda: _installer_script(),
+ log_message = "whisper update: resolve-prebuilt failed",
+ extra_args = extra_args,
+ )
+
+
+def _installed_whisper_version(binary: Optional[str]) -> Optional[str]:
+ """Best-effort ``v<A.B.C>`` from ``whisper-server --version``. None when the
+ binary is missing, reports no version, or cannot run. Used only for the
+ markerless source-build downgrade guard, so it fails open to None."""
+ if not binary:
+ return None
+ try:
+ proc = subprocess.run([binary, "--version"], capture_output = True, text = True, timeout = 20)
+ except Exception: # pragma: no cover - defensive
+ return None
+ m = re.search(r"v?(\d+\.\d+\.\d+)", (proc.stderr or "") + (proc.stdout or ""))
+ if not m:
+ return None
+ return f"v{m.group(1)}"
+
+
+def _whisper_install_root(binary: Optional[str]) -> Optional[Path]:
+ """The Unsloth-managed whisper.cpp root the active binary lives under, or None
+ when the binary is unmanaged (see update_flow.managed_install_root)."""
+ return _flow.managed_install_root(
+ binary,
+ marker_root = _install_dir_for(binary),
+ server_path_var = "WHISPER_SERVER_PATH",
+ cpp_path_var = "UNSLOTH_WHISPER_CPP_PATH",
+ dir_name = "whisper.cpp",
+ )
+
+
+def _source_build_status(binary: str, *, force_refresh: bool) -> Optional[dict]:
+ """Update status for a markerless (source-build) install: offer the official
+ prebuilt when one exists for this host and is newer than the installed binary.
+ None -> caller falls through to the no-marker default (unsupported)."""
+ res = _resolve_prebuilt_for_host(force_refresh = force_refresh)
+ if not res or not res.get("prebuilt_available"):
+ return None
+ release_tag = res.get("release_tag")
+ if not release_tag:
+ return None
+ # No resolvable install root (e.g. a pinned WHISPER_SERVER_PATH we cannot
+ # manage) means an apply would not take effect, so do not offer it.
+ if _whisper_install_root(binary) is None:
+ return None
+ installed_tag = _installed_whisper_version(binary)
+ installed_key = parse_release_version(installed_tag) if installed_tag else None
+ latest_key = parse_release_version(release_tag)
+ if installed_key is None or latest_key is None:
+ # Unknown installed/latest version (involuntary source-build case): treat
+ # as behind so we still offer the prebuilt.
+ update_available = True
+ else:
+ # Same downgrade guard as is_behind: only a strictly newer key is behind.
+ update_available = latest_key > installed_key
+ latest = release_tag
+ # Size of the resolved prebuilt, so source builds show it like the marker
+ # path. Fails open to None (offline / asset absent from release).
+ update_size_bytes = None
+ if update_available:
+ asset_name = res.get("asset")
+ if isinstance(asset_name, str) and asset_name:
+ try:
+ assets = latest_release_assets(res.get("repo"), force_refresh = force_refresh)
+ if assets:
+ update_size_bytes = assets.get(asset_name)
+ except Exception as exc: # pragma: no cover - network defensive
+ logger.debug("whisper update: source-build size lookup failed", error = str(exc))
+ with _job_lock:
+ job = dict(_job)
+ return {
+ "supported": True,
+ "update_available": update_available,
+ "stale": False,
+ "installed_tag": installed_tag,
+ "latest_tag": latest,
+ "published_repo": res.get("repo"),
+ "installed_at_utc": None,
+ "age_days": None,
+ "source_build": True,
+ "update_size_bytes": update_size_bytes,
+ "job": job,
+ }
+
+
+def _active_install_is_local_link(binary: Optional[str]) -> bool:
+ """True when the active whisper-server resolves through a locally-linked
+ whisper.cpp directory (see update_flow.active_install_is_local_link)."""
+ return _flow.active_install_is_local_link(binary, dir_name = "whisper.cpp")
+
+
+def _local_link_status() -> dict:
+ """Status payload for a local-link install: unmanaged, no update offered."""
+ return _flow.local_link_status(_job, _job_lock)
+
+
+def get_update_status(*, force_refresh: bool = False) -> dict:
+ """Report whether a newer prebuilt exists plus the current job state.
+
+ force_refresh bypasses the 24h release cache for an explicit "check now".
+ """
+ binary = _find_binary()
+ # A locally-linked whisper.cpp dir is the user's own tree; never offer to
+ # replace it. Bail before any network/freshness work.
+ if _active_install_is_local_link(binary):
+ return _local_link_status()
+ marker = read_install_marker(binary)
+
+ # No marker = source build / custom path. Offer the official prebuilt if one
+ # exists for this host.
+ if marker is None and binary is not None:
+ src = _source_build_status(binary, force_refresh = force_refresh)
+ if src is not None:
+ return src
+
+ repo = (marker or {}).get("published_repo") or DEFAULT_PUBLISHED_REPO
+
+ if force_refresh and repo:
+ # Prime the cache so the freshness read below sees the newest tag.
+ try:
+ latest_published_release(repo, force_refresh = True)
+ except Exception as exc: # pragma: no cover - network defensive
+ logger.debug("whisper update: force refresh failed", error = str(exc))
+
+ freshness = check_prebuilt_freshness(binary)
+ installed = freshness.get("installed_tag")
+ latest = freshness.get("latest_tag")
+ compatible_override = False
+ if sys.platform == "darwin" and marker is not None:
+ # The newest published release may require a newer macOS. Ask the same
+ # host-aware resolver the installer uses so the banner compares against
+ # the newest release this host can actually install, avoiding a repeated
+ # offer of an incompatible release after walkback.
+ resolved = _resolve_prebuilt_for_host(
+ force_refresh = force_refresh,
+ backend = marker.get("backend") if isinstance(marker.get("backend"), str) else None,
+ )
+ compatible_latest = (resolved or {}).get("release_tag")
+ if (resolved or {}).get("prebuilt_available") and isinstance(compatible_latest, str):
+ compatible_override = compatible_latest != latest
+ latest = compatible_latest
+ # `behind` compares the release version with a downgrade guard, so a lagging
+ # /releases/latest or lower published tag can't show a false update
+ # (whisper_cpp_freshness.is_behind).
+ update_available = bool(
+ freshness.get("has_marker")
+ and (
+ is_behind(installed, latest)
+ if sys.platform == "darwin" and marker is not None
+ else freshness.get("behind")
+ )
+ )
+
+ # Size of the prebuilt Update would download, for the banner. Only when an
+ # update is offered; fails open to None (offline / no matching asset).
+ update_size_bytes = None
+ if update_available and not compatible_override:
+ try:
+ update_size_bytes = update_download_size_bytes(
+ marker,
+ latest,
+ freshness.get("published_repo") or repo,
+ force_refresh = force_refresh,
+ )
+ except Exception as exc: # pragma: no cover - network defensive
+ logger.debug("whisper update: size lookup failed", error = str(exc))
+
+ with _job_lock:
+ job = dict(_job)
+
+ return {
+ "supported": bool(freshness.get("has_marker")),
+ "update_available": update_available,
+ "stale": bool(update_available and freshness.get("stale")),
+ "installed_tag": installed,
+ "latest_tag": latest,
+ "published_repo": freshness.get("published_repo") or repo,
+ "installed_at_utc": freshness.get("installed_at_utc"),
+ "age_days": freshness.get("age_days"),
+ "source_build": False,
+ "update_size_bytes": update_size_bytes,
+ "job": job,
+ }
+
+
+def _install_latest(
+ install_dir: Path,
+ repo: str,
+ asset: Optional[str],
+ backend: Optional[str],
+ script: Path,
+ set_progress,
+ pin_release_tag: Optional[str] = None,
+) -> dict:
+ """Replace whisper.cpp while the sidecar blocks every new load."""
+ try:
+ from core.inference.stt_ggml_sidecar import get_ggml_stt_sidecar
+ sidecar = get_ggml_stt_sidecar()
+ except Exception as exc:
+ # Replacing the tree without the singleton's maintenance barrier would
+ # reopen the Windows executable-lock and stale-process races. Fail closed.
+ raise RuntimeError("could not coordinate the whisper.cpp sidecar update") from exc
+
+ # update_maintenance publishes its guard before waiting for an existing
+ # transcription, unloads the warm server, and holds the sidecar lock across
+ # the complete atomic install. No new process can relock or outlive the tree.
+ with sidecar.update_maintenance() as model_was_active:
+ return _install_latest_while_blocked(
+ install_dir,
+ repo,
+ asset,
+ backend,
+ script,
+ set_progress,
+ pin_release_tag = pin_release_tag,
+ model_was_active = model_was_active,
+ )
+
+
+def _install_latest_while_blocked(
+ install_dir: Path,
+ repo: str,
+ asset: Optional[str],
+ backend: Optional[str],
+ script: Path,
+ set_progress,
+ *,
+ pin_release_tag: Optional[str],
+ model_was_active: bool,
+) -> dict:
+ """Run the installer with the sidecar already in update maintenance."""
+
+ cmd = [
+ sys.executable,
+ str(script),
+ "--install-dir",
+ str(install_dir),
+ "--whisper-tag",
+ "latest",
+ "--published-repo",
+ repo,
+ ]
+ # Preserve the installed accelerator across updates. Left unpinned the
+ # installer re-detects the host, fine on unchanged hardware but able to
+ # reroute a deliberate choice (e.g. cpu on a GPU box); forwarding the marker's
+ # backend keeps the same slice.
+ if isinstance(backend, str) and backend:
+ cmd.extend(["--backend", backend])
+ if pin_release_tag:
+ cmd.extend(["--published-release-tag", pin_release_tag])
+ cmd.extend(_rocm_install_args(asset))
+ logger.info("whisper update: installing", cmd = " ".join(cmd))
+ env = dict(os.environ, UNSLOTH_PROGRESS_PERCENT_STEP = "5")
+ # Every nonzero exit is a failed phase. In particular, exit 2 means the
+ # requested release was incompatible and no install happened, so reporting
+ # success would hide the banner and toast an update that never landed.
+ _flow.stream_installer(
+ cmd,
+ env,
+ set_progress = set_progress,
+ timeout_seconds = _INSTALL_TIMEOUT_SECONDS,
+ )
+
+ # Drop stale caches so the banner re-checks the swapped marker. If GitHub is
+ # offline, latest stays unknown and the banner fails open.
+ reset_caches(drop_disk = True)
+ try:
+ latest_published_release(repo, force_refresh = True)
+ except Exception as exc: # pragma: no cover - network defensive
+ logger.debug("whisper update: post-install freshness refresh failed", error = str(exc))
+ new_marker = read_install_marker(_find_binary())
+ new_tag = (new_marker or {}).get("release_tag")
+ logger.info("whisper update: success", to_tag = new_tag)
+ return {
+ "to_tag": new_tag,
+ "reload_required": model_was_active,
+ "message": (
+ f"Updated whisper.cpp to {new_tag}."
+ + (" Reload your model to use it." if model_was_active else "")
+ ),
+ }
+
+
+def chained_phase_plan(
+ *, force_refresh: bool = False, paired_llama_will_update: bool = False
+) -> dict:
+ """Whisper's side of the combined llama+whisper update item.
+
+ Returns {status, update_available, skip_reason, phase}: `status` is the
+ marker-path status dict (or a minimal one when whisper is skipped),
+ `update_available` says the chained apply would run a whisper phase, and
+ `phase` carries what run_chained_phase needs. Only marker-managed installs are
+ chained: local links, source builds and unmanaged/pinned paths are silently
+ skipped so whisper can never block a llama update. Never raises; failures
+ degrade to a skip."""
+ binary = _find_binary()
+ if _active_install_is_local_link(binary):
+ return {
+ "status": _local_link_status(),
+ "update_available": False,
+ "skip_reason": "local_link",
+ "phase": None,
+ }
+ marker = read_install_marker(binary)
+ if marker is None:
+ # No marker: whisper is absent or a source/custom build. The standalone
+ # utils API can update source builds; the chain does not.
+ return {
+ "status": None,
+ "update_available": False,
+ "skip_reason": "source_build" if binary else "not_installed",
+ "phase": None,
+ }
+ status = get_update_status(force_refresh = force_refresh)
+ plan: dict = {"status": status, "update_available": False, "skip_reason": None, "phase": None}
+ if not status.get("update_available"):
+ # Skew note: when llama just updated but whisper is already latest, a slim
+ # install keeps hardlinks to the OLD llama ggml inodes -- still the exact
+ # build whisper was installed against, so skipping is correct and needs no
+ # re-wiring. A whisper phase that does run re-wires via the installer
+ # (prepare_runtime_payload).
+ plan["skip_reason"] = "up_to_date"
+ return plan
+ if marker.get("install_kind") == "slim" and not paired_llama_will_update:
+ # A slim install can only be refreshed from a completed managed llama
+ # prebuilt. Ask the installer through its read-only resolver so local
+ # links, markerless/current source builds, and incomplete managed trees
+ # never produce an Update button that can only fail. When the llama
+ # phase will run first, it supplies the repaired pairing instead.
+ resolved = _resolve_prebuilt_for_host(
+ force_refresh = force_refresh,
+ backend = marker.get("backend") if isinstance(marker.get("backend"), str) else None,
+ )
+ if not (resolved or {}).get("prebuilt_available"):
+ plan["skip_reason"] = "paired_llama_unavailable"
+ return plan
+ script = _installer_script()
+ if script is None:
+ plan["skip_reason"] = "installer_missing"
+ return plan
+ install_dir = _install_dir_for(binary)
+ if install_dir is None:
+ plan["skip_reason"] = "no_install_dir"
+ return plan
+ plan["update_available"] = True
+ plan["phase"] = {
+ "install_dir": install_dir,
+ "repo": marker.get("published_repo") or DEFAULT_PUBLISHED_REPO,
+ "asset": marker.get("asset"),
+ "backend": marker.get("backend"),
+ "script": script,
+ # Install exactly the release the check offered: the installer's unpinned
+ # "latest" prefers the download-host /releases/latest pointer, which sorts
+ # by commit date and can lag the published_at pick the freshness check
+ # used, reinstalling an older build in a loop (the #6219 class the llama
+ # phase pins against). Not on macOS: the llama phase is unpinned there
+ # (walk-back to an os-compatible release), so pinning whisper to the
+ # newest tag could be an impossible pairing (min_os / requires_llama_tag)
+ # on every retry.
+ "pin_release_tag": None if sys.platform == "darwin" else status.get("latest_tag"),
+ }
+ return plan
+
+
+def run_chained_phase(phase: dict, set_progress) -> dict:
+ """Run the whisper phase of a combined update (spec from chained_phase_plan):
+ same unload/install/cache-refresh path as the standalone job, reporting
+ progress through the chained job's window rather than whisper's own."""
+ return _install_latest(
+ phase["install_dir"],
+ phase["repo"],
+ phase["asset"],
+ phase["backend"],
+ phase["script"],
+ set_progress,
+ pin_release_tag = phase.get("pin_release_tag"),
+ )
diff --git a/studio/frontend/src/components/assistant-ui/chat-dictation-bar.tsx b/studio/frontend/src/components/assistant-ui/chat-dictation-bar.tsx
new file mode 100644
index 00000000000..64b0b467352
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/chat-dictation-bar.tsx
@@ -0,0 +1,231 @@
+// 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 { Spinner } from "@/components/ui/spinner";
+import {
+ cancelActiveStudioDictation,
+ subscribeDictationLevel,
+} from "@/features/chat";
+import { useAui, useAuiState } from "@assistant-ui/react";
+import { CheckIcon, XIcon } from "lucide-react";
+import { type FC, useEffect, useRef, useState } from "react";
+import { TooltipIconButton } from "./tooltip-icon-button";
+
+// Dense row of dots that rise into centered recording bars.
+const BAR_COUNT = 84;
+// Peak height multiple for the loudest audio (dot is 4px). Under the 40px pill
+// so bars don't touch the edges.
+const MAX_SCALE = 8;
+// Time for a sample to slide one bar-width left (drift speed). Bars interpolate
+// between samples each frame, so a slower interval stays smooth.
+const PUSH_INTERVAL_MS = 165;
+// If no real mic level arrives for this long (e.g. Web Audio unavailable), fall
+// back to a gentle idle shimmer so the bar stays alive.
+const IDLE_AFTER_MS = 450;
+const WAVE_BAR_IDS = Array.from(
+ { length: BAR_COUNT },
+ (_, index) => `wave-bar-${index}`,
+);
+
+function formatElapsed(ms: number): string {
+ const total = Math.floor(ms / 1000);
+ const m = Math.floor(total / 60);
+ const s = total % 60;
+ return `${m}:${s.toString().padStart(2, "0")}`;
+}
+
+/**
+ * Recording UI shown in place of the composer input: a live waveform with
+ * discard and confirm on the right. Confirm transcribes; discard keeps the
+ * existing composer text.
+ */
+export const ChatDictationBar: FC = () => {
+ const aui = useAui();
+ const isDictating = useAuiState((s) => s.composer.dictation != null);
+ const [transcribing, setTranscribing] = useState(false);
+ const [elapsed, setElapsed] = useState(0);
+ const transcribingRef = useRef(false);
+ // Extra slot: newest sample lands here; the last visible bar slides toward it.
+ const barsRef = useRef<number[]>(new Array(BAR_COUNT + 1).fill(0));
+ const rowRef = useRef<HTMLDivElement | null>(null);
+
+ useEffect(() => {
+ if (!isDictating) {
+ return;
+ }
+
+ const startedAt = Date.now();
+ let peak = 0; // loudest level seen since the last waveform advance
+ let smoothed = 0;
+ let lastLevelAt = 0;
+ const barEls = rowRef.current
+ ? Array.from(rowRef.current.children).filter(
+ (el): el is HTMLElement => el instanceof HTMLElement,
+ )
+ : [];
+ // Paint the bars imperatively (not via React state) so the waveform does not
+ // thrash renders. The spans carry no style prop, so React never overwrites
+ // these transforms on an elapsed-timer re-render. At rest each is a round dot
+ // (scaleY 1); louder audio scales it into a thin centered bar.
+ for (const el of barEls) {
+ el.style.transform = "scaleY(1)";
+ el.style.opacity = "0.62";
+ }
+
+ // Push one new sample, dropping the oldest.
+ const commitSample = () => {
+ const bars = barsRef.current;
+ let level = peak;
+ peak = 0;
+ if (Date.now() - lastLevelAt > IDLE_AFTER_MS) {
+ level = 0.075 + 0.055 * (1 + Math.sin(Date.now() / 360));
+ }
+ // Quiet speech needs a perceptual lift. Fast attack, slower release:
+ // removes twitching while preserving clear peaks.
+ const visual = Math.min(1, Math.max(0, level) ** 0.62 * 1.45);
+ smoothed =
+ visual >= smoothed
+ ? smoothed * 0.2 + visual * 0.8
+ : smoothed * 0.78 + visual * 0.22;
+ bars.push(smoothed);
+ while (bars.length > BAR_COUNT + 1) {
+ bars.shift();
+ }
+ };
+
+ // Keep the loudest mic level between advances so downsampling to
+ // PUSH_INTERVAL_MS doesn't swallow peaks in quiet gaps.
+ const unsub = subscribeDictationLevel((level) => {
+ if (level > peak) {
+ peak = level;
+ }
+ lastLevelAt = Date.now();
+ });
+
+ // Repaint every frame; bars interpolate between samples so the wave glides.
+ // Timer updates at most once per second.
+ let lastPushAt = performance.now();
+ let shownSecond = -1;
+ let raf = 0;
+
+ const frame = () => {
+ raf = requestAnimationFrame(frame);
+ if (transcribingRef.current) {
+ return;
+ }
+
+ const now = performance.now();
+ const bars = barsRef.current;
+ let steps = 0;
+ while (now - lastPushAt >= PUSH_INTERVAL_MS && steps < BAR_COUNT + 1) {
+ commitSample();
+ lastPushAt += PUSH_INTERVAL_MS;
+ steps++;
+ }
+ // Drop stale backlog if rAF was paused (tab backgrounded).
+ if (now - lastPushAt >= PUSH_INTERVAL_MS) {
+ lastPushAt = now;
+ }
+
+ const phase = Math.min(1, (now - lastPushAt) / PUSH_INTERVAL_MS);
+ for (let i = 0; i < barEls.length; i++) {
+ // Bar i drifts toward its right neighbour as phase goes 0 to 1.
+ const a = bars[i] ?? 0;
+ const b = bars[i + 1] ?? a;
+ const v = a + (b - a) * phase;
+ barEls[i].style.transform = `scaleY(${1 + v * (MAX_SCALE - 1)})`;
+ barEls[i].style.opacity = `${0.62 + v * 0.38}`;
+ }
+
+ const elapsedMs = Date.now() - startedAt;
+ const second = Math.floor(elapsedMs / 1000);
+ if (second !== shownSecond) {
+ shownSecond = second;
+ setElapsed(elapsedMs);
+ }
+ };
+ raf = requestAnimationFrame(frame);
+
+ // Reset in cleanup (dictation end or unmount) so the next session starts
+ // fresh, without a synchronous setState in the effect body.
+ return () => {
+ unsub();
+ cancelAnimationFrame(raf);
+ transcribingRef.current = false;
+ setTranscribing(false);
+ setElapsed(0);
+ barsRef.current = new Array(BAR_COUNT + 1).fill(0);
+ };
+ }, [isDictating]);
+
+ if (!isDictating) {
+ return null;
+ }
+
+ const discard = () => {
+ cancelActiveStudioDictation();
+ };
+
+ const confirm = () => {
+ // Freeze the timer + waveform before the transcription round trip completes
+ // and the session ends.
+ transcribingRef.current = true;
+ setTranscribing(true);
+ aui.composer().stopDictation();
+ };
+
+ return (
+ <fieldset
+ // order-2 places the bar in the input's slot after the left "+" tools.
+ className="unsloth-dictation-bar order-2 m-0 flex min-w-0 flex-1 items-center gap-2 border-0 p-0"
+ aria-label="Voice recording"
+ >
+ <div
+ ref={rowRef}
+ aria-hidden="true"
+ className="unsloth-dictation-wave grid h-10 min-w-0 flex-1 items-center overflow-hidden px-2"
+ style={{
+ gridTemplateColumns: `repeat(${BAR_COUNT}, minmax(1px, 3px))`,
+ justifyContent: "space-between",
+ }}
+ >
+ {WAVE_BAR_IDS.map((barId) => (
+ <span
+ key={barId}
+ className="h-1 w-full origin-center rounded-full bg-foreground opacity-[0.62] will-change-transform"
+ />
+ ))}
+ </div>
+ <span className="shrink-0 tabular-nums text-sm text-muted-foreground">
+ {formatElapsed(elapsed)}
+ </span>
+ <div className="flex shrink-0 items-center gap-1">
+ <TooltipIconButton
+ type="button"
+ tooltip="Discard recording"
+ aria-label="Discard recording"
+ variant="ghost"
+ onClick={discard}
+ className="size-8 rounded-full text-muted-foreground hover:text-foreground"
+ >
+ <XIcon className="size-5" />
+ </TooltipIconButton>
+ <TooltipIconButton
+ type="button"
+ tooltip={transcribing ? "Transcribing…" : "Stop and transcribe"}
+ aria-label="Stop and transcribe"
+ variant="default"
+ onClick={confirm}
+ disabled={transcribing}
+ className="size-8 rounded-full"
+ >
+ {transcribing ? (
+ <Spinner className="size-4" />
+ ) : (
+ <CheckIcon className="size-5" />
+ )}
+ </TooltipIconButton>
+ </div>
+ </fieldset>
+ );
+};
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index ff1b87873ab..43a0c439509 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -34,6 +34,11 @@ import { RenderHtmlToolUI } from "@/components/assistant-ui/tool-ui-render-html"
import { PythonToolUI } from "@/components/assistant-ui/tool-ui-python";
import { TerminalToolUI } from "@/components/assistant-ui/tool-ui-terminal";
import { WebSearchToolUI } from "@/components/assistant-ui/tool-ui-web-search";
+import { ChatDictationBar } from "@/components/assistant-ui/chat-dictation-bar";
+import {
+ isStudioDictationAvailable,
+ notifyStudioDictationUnavailable,
+} from "@/features/chat";
import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button";
import {
IntentAwareScrollProvider,
@@ -1435,6 +1440,7 @@ const Composer: FC<{
disableQueue?: boolean;
}> = ({ disabled, threadId, menuSide, disableQueue }) => {
const aui = useAui();
+ const isDictating = useAuiState((s) => s.composer.dictation != null);
const pageDragging = useContext(PageDragContext);
const { overlay, closeOverlay } = useGeneratedImageOverlay();
const setImageToolsEnabled = useChatRuntimeStore(
@@ -1856,79 +1862,101 @@ const Composer: FC<{
const composerContent = (
<>
- <ComposerAttachments />
- <PendingAudioChip />
- <ThreadDocumentsBar
- threadId={referenceThreadId}
- onIndexingChange={handleIndexingChange}
- />
- <ToolStatusDisplay />
+ {!isDictating ? (
+ <>
+ <ComposerAttachments />
+ <PendingAudioChip />
+ </>
+ ) : null}
+ {/* Keep indexing state subscribed while dictating, but hide its chips so
+ the waveform stays the composer's only status indicator. */}
+ <div className={isDictating ? "hidden" : "contents"}>
+ <ThreadDocumentsBar
+ threadId={referenceThreadId}
+ onIndexingChange={handleIndexingChange}
+ />
+ </div>
+ {!isDictating ? <ToolStatusDisplay /> : null}
<div
className="unsloth-composer-line"
// The permission pill is always visible, so keep the two-row layout
- // expanded and leave the primary tool toggles accessible in every mode.
- data-expanded="true"
+ // expanded whenever not dictating; dictation collapses to the bar.
+ data-expanded={!isDictating ? "true" : "false"}
+ data-dictating={isDictating ? "true" : undefined}
>
<div
className="unsloth-composer-left"
data-pill-compact={pillsCompact ? "true" : undefined}
>
<ComposerToolsMenu side={effectiveMenuSide} />
- {/* Permission-level pill: always visible and opens the permission
- level dropdown. */}
- <PermissionModeComposerPill side={effectiveMenuSide} />
- <WebSearchToggle />
- <CodeToolsToggle />
- <ImagesToggle />
- <KnowledgeBaseComposerButton side={effectiveMenuSide} />
- {artifactsEnabled ? <ArtifactsToggle /> : null}
- {mcpEnabledForChat ? (
- <McpComposerButton side={effectiveMenuSide} />
+ {/* While dictating, show only the "+"; hide the pill and tool toggles
+ so the waveform is the sole status indicator. */}
+ {!isDictating ? (
+ <>
+ {/* Permission-level pill: always visible, opens the level dropdown. */}
+ <PermissionModeComposerPill side={effectiveMenuSide} />
+ <WebSearchToggle />
+ <CodeToolsToggle />
+ <ImagesToggle />
+ <KnowledgeBaseComposerButton side={effectiveMenuSide} />
+ {artifactsEnabled ? <ArtifactsToggle /> : null}
+ {mcpEnabledForChat ? (
+ <McpComposerButton side={effectiveMenuSide} />
+ ) : null}
+ </>
) : null}
</div>
- <ComposerPrimitive.Input
- placeholder={
- overlay ? "Type your edits for your image" : "Ask anything"
- }
- ref={inputRef}
- className="aui-composer-input unsloth-composer-input"
- minRows={1}
- maxRows={12}
- autoFocus={!disabled}
- disabled={disabled}
- aria-label={overlay ? "Image edit instructions" : "Message input"}
- // dir="auto": browser picks LTR/RTL from the first strong char;
- // no effect on Latin / CJK / Devanagari.
- dir="auto"
- {...inputProps}
- />
- <ComposerRightControls
- disabled={
- disabled ||
- !hasSendableContent ||
- isComposing ||
- hasPendingAttachments
- }
- // disableQueue (project new-chat composer) also blocks the queue
- // button, so a running thread shows Stop instead of Queue.
- queueDisabled={disableQueue || !canQueueCurrentPrompt}
- onQueueClick={() => {
- if (disableQueue) return;
- const queuedPrompt = composerText.trim();
- if (queuedPrompt.length === 0) {
- return;
- }
- flushResourcesSync(() => {
- aui.composer().setText("");
- });
- startPromptQueue([queuedPrompt], createPromptQueueTarget(), true);
- }}
- onSendClick={interceptSend}
- onStopClick={stopQueue}
- pendingSend={pendingSend}
- menuSide={effectiveMenuSide}
- queueThreadIds={promptQueueThreadIds}
- />
+ {isDictating ? (
+ // The recording UI replaces the input and send controls; only the
+ // left plus stays visible alongside it.
+ <ChatDictationBar />
+ ) : (
+ <>
+ <ComposerPrimitive.Input
+ placeholder={
+ overlay ? "Type your edits for your image" : "Ask anything"
+ }
+ ref={inputRef}
+ className="aui-composer-input unsloth-composer-input"
+ minRows={1}
+ maxRows={12}
+ autoFocus={!disabled}
+ disabled={disabled}
+ aria-label={overlay ? "Image edit instructions" : "Message input"}
+ // dir="auto": browser picks LTR/RTL from the first strong char;
+ // no effect on Latin / CJK / Devanagari.
+ dir="auto"
+ {...inputProps}
+ />
+ <ComposerRightControls
+ disabled={
+ disabled ||
+ !hasSendableContent ||
+ isComposing ||
+ hasPendingAttachments
+ }
+ // disableQueue (project new-chat composer) also blocks the queue
+ // button, so a running thread shows Stop instead of Queue.
+ queueDisabled={disableQueue || !canQueueCurrentPrompt}
+ onQueueClick={() => {
+ if (disableQueue) return;
+ const queuedPrompt = composerText.trim();
+ if (queuedPrompt.length === 0) {
+ return;
+ }
+ flushResourcesSync(() => {
+ aui.composer().setText("");
+ });
+ startPromptQueue([queuedPrompt], createPromptQueueTarget(), true);
+ }}
+ onSendClick={interceptSend}
+ onStopClick={stopQueue}
+ pendingSend={pendingSend}
+ menuSide={effectiveMenuSide}
+ queueThreadIds={promptQueueThreadIds}
+ />
+ </>
+ )}
</div>
</>
);
@@ -3362,32 +3390,36 @@ const ComposerRightControls: FC<{
findPromptQueueEntry(s, queueThreadIds),
);
const isQueueRunning = Boolean(queueEntry);
+ const aui = useAui();
+ // Keep the mic clickable: if the engine can't run here, explain and point to
+ // the local model instead of disabling the button.
+ const startDictation = () => {
+ if (!isStudioDictationAvailable()) {
+ notifyStudioDictationUnavailable();
+ return;
+ }
+ try {
+ aui.composer().startDictation();
+ } catch {
+ notifyStudioDictationUnavailable();
+ }
+ };
return (
<div className="aui-composer-action-wrapper flex shrink-0 items-center gap-1.5">
<ReasoningToggle side={menuSide} />
+ {/* Starts dictation; the recording bar then covers the input row and owns
+ the stop and discard actions. */}
<ComposerPrimitive.If dictation={false}>
- <ComposerPrimitive.Dictate asChild={true}>
- <TooltipIconButton
- tooltip="Dictate"
- aria-label="Dictate"
- variant="ghost"
- className="size-8 rounded-full text-foreground"
- >
- <MicIcon className="size-5" />
- </TooltipIconButton>
- </ComposerPrimitive.Dictate>
- </ComposerPrimitive.If>
- <ComposerPrimitive.If dictation={true}>
- <ComposerPrimitive.StopDictation asChild={true}>
- <TooltipIconButton
- tooltip="Stop dictation"
- aria-label="Stop dictation"
- variant="ghost"
- className="size-8 rounded-full text-destructive"
- >
- <SquareIcon className="size-3 animate-pulse fill-current" />
- </TooltipIconButton>
- </ComposerPrimitive.StopDictation>
+ <TooltipIconButton
+ tooltip="Dictate"
+ aria-label="Dictate"
+ type="button"
+ variant="ghost"
+ className="size-8 rounded-full text-foreground"
+ onClick={startDictation}
+ >
+ <MicIcon className="size-5" />
+ </TooltipIconButton>
</ComposerPrimitive.If>
<AuiIf condition={({ thread }) => !thread.isRunning && !isQueueRunning}>
<ComposerPrimitive.Send asChild={true}>
diff --git a/studio/frontend/src/components/llama-update-banner.tsx b/studio/frontend/src/components/llama-update-banner.tsx
index 5baca8ffe2e..27295586300 100644
--- a/studio/frontend/src/components/llama-update-banner.tsx
+++ b/studio/frontend/src/components/llama-update-banner.tsx
@@ -93,16 +93,17 @@ export function LlamaUpdateBanner({
});
async function handleUpdate() {
+ const component = status?.component ?? "llama.cpp";
const result = await apply();
if (result?.ok) {
const updatedTag = result.tag ?? status?.latest_tag ?? "the latest build";
const reloadHint = result.reloadRequired
? " Reload your model to use it."
: "";
- toast.success(`llama.cpp updated to ${updatedTag}.${reloadHint}`);
+ toast.success(`${component} updated to ${updatedTag}.${reloadHint}`);
} else if (result) {
toast.error(
- `llama.cpp update failed: ${result.error ?? "unknown error"}`,
+ `${component} update failed: ${result.error ?? "unknown error"}`,
);
}
}
@@ -113,6 +114,7 @@ export function LlamaUpdateBanner({
status != null &&
(status.update_available || applying);
const sizeBytes = status?.update_size_bytes ?? null;
+ const component = status?.component ?? "llama.cpp";
const sizeLabel =
sizeBytes && sizeBytes > 0
? `${Math.round(sizeBytes / (1024 * 1024))} MB`
@@ -142,7 +144,7 @@ export function LlamaUpdateBanner({
type="button"
onClick={dismiss}
className="absolute top-2.5 right-3 flex size-6 items-center justify-center rounded-full text-muted-foreground/60 transition-colors hover:bg-muted hover:text-foreground"
- aria-label="Dismiss llama.cpp update notification"
+ aria-label={`Dismiss ${component} update notification`}
>
<svg
aria-hidden="true"
@@ -170,7 +172,7 @@ export function LlamaUpdateBanner({
/>
<div className="min-w-0">
<p className="font-heading text-base font-medium text-foreground">
- {applying ? "Updating llama.cpp..." : "New llama.cpp update"}
+ {applying ? `Updating ${component}...` : `New ${component} update`}
</p>
<p className="mt-0.5 text-xs text-muted-foreground">
{status?.installed_tag ?? "unknown"} &rarr;{" "}
@@ -189,7 +191,7 @@ export function LlamaUpdateBanner({
<div
className="mb-1.5 mt-4 h-1 overflow-hidden rounded-full bg-muted"
role="progressbar"
- aria-label="Updating llama.cpp"
+ aria-label={`Updating ${component}`}
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={
diff --git a/studio/frontend/src/components/ui/combobox.tsx b/studio/frontend/src/components/ui/combobox.tsx
index 11ba03a3e86..07202d30aee 100644
--- a/studio/frontend/src/components/ui/combobox.tsx
+++ b/studio/frontend/src/components/ui/combobox.tsx
@@ -7,6 +7,7 @@
import { Combobox as ComboboxPrimitive } from "@base-ui/react";
import * as React from "react";
+import { useWheelScrollRef } from "@/hooks";
import { createContext, useState } from "react";
import { Button } from "@/components/ui/button";
@@ -100,13 +101,19 @@ function ComboboxInput({
disabled = false,
showTrigger = true,
showClear = false,
+ startAddon,
...props
}: ComboboxPrimitive.Input.Props & {
showTrigger?: boolean;
showClear?: boolean;
+ /** Optional leading content (e.g. a search icon) rendered before the input. */
+ startAddon?: React.ReactNode;
}): React.ReactElement {
return (
<InputGroup className={cn("w-auto", className)}>
+ {startAddon && (
+ <InputGroupAddon align="inline-start">{startAddon}</InputGroupAddon>
+ )}
<ComboboxPrimitive.Input
render={<InputGroupInput disabled={disabled} />}
{...props}
@@ -195,8 +202,11 @@ function ComboboxList({
className,
...props
}: ComboboxPrimitive.List.Props): React.ReactElement {
+ const listRef = useWheelScrollRef<HTMLDivElement>();
+
return (
<ComboboxPrimitive.List
+ ref={listRef}
data-slot="combobox-list"
className={cn(
"no-scrollbar max-h-[min(calc(--spacing(72)---spacing(9)),calc(var(--available-height)---spacing(9)))] scroll-py-1 overflow-y-auto p-1 data-empty:p-0 overflow-y-auto overscroll-contain",
diff --git a/studio/frontend/src/features/chat/adapters/dictation-level.ts b/studio/frontend/src/features/chat/adapters/dictation-level.ts
new file mode 100644
index 00000000000..e38060ba0e1
--- /dev/null
+++ b/studio/frontend/src/features/chat/adapters/dictation-level.ts
@@ -0,0 +1,91 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+type LevelListener = (level: number) => void;
+type FrameListener = (rawRms: number, now: number) => void;
+
+const levelListeners = new Set<LevelListener>();
+
+/** Subscribe to the live microphone level (0..1) during dictation. */
+export function subscribeDictationLevel(listener: LevelListener): () => void {
+ levelListeners.add(listener);
+ return () => {
+ levelListeners.delete(listener);
+ };
+}
+
+function publishLevel(level: number): void {
+ for (const listener of levelListeners) {
+ listener(level);
+ }
+}
+
+/**
+ * Start a lightweight Web Audio meter for the shared recording waveform and
+ * optional voice-activity detection. Returns an idempotent cleanup function.
+ */
+export function startDictationLevelMeter(
+ source: MediaStream,
+ onFrame?: FrameListener,
+): () => void {
+ let audioContext: AudioContext | null = null;
+ let levelRaf = 0;
+ let stopped = false;
+
+ const stop = () => {
+ if (stopped) {
+ return;
+ }
+ stopped = true;
+ if (levelRaf) {
+ cancelAnimationFrame(levelRaf);
+ }
+ levelRaf = 0;
+ audioContext?.close().catch(() => {
+ // A closing or already-closed context is harmless.
+ });
+ audioContext = null;
+ publishLevel(0);
+ };
+
+ try {
+ const Ctx =
+ window.AudioContext ||
+ (window as unknown as { webkitAudioContext?: typeof AudioContext })
+ .webkitAudioContext;
+ if (!Ctx) {
+ return stop;
+ }
+ audioContext = new Ctx();
+ audioContext.resume().catch(() => {
+ // Some browsers resume automatically after microphone permission.
+ });
+ const node = audioContext.createMediaStreamSource(source);
+ const analyser = audioContext.createAnalyser();
+ analyser.fftSize = 512;
+ node.connect(analyser);
+ const data = new Uint8Array(analyser.frequencyBinCount);
+ const tick = () => {
+ if (stopped) {
+ return;
+ }
+ analyser.getByteTimeDomainData(data);
+ let sum = 0;
+ for (const sample of data) {
+ const value = (sample - 128) / 128;
+ sum += value * value;
+ }
+ const rms = Math.sqrt(sum / data.length);
+ onFrame?.(rms, performance.now());
+ // Perceptual boost so normal speech remains clearly visible.
+ publishLevel(Math.min(1, rms * 3.2));
+ levelRaf = requestAnimationFrame(tick);
+ };
+ levelRaf = requestAnimationFrame(tick);
+ } catch {
+ // The waveform is cosmetic; recording can continue without Web Audio.
+ stop();
+ }
+
+ return stop;
+}
diff --git a/studio/frontend/src/features/chat/adapters/studio-dictation-adapter.tsx b/studio/frontend/src/features/chat/adapters/studio-dictation-adapter.tsx
new file mode 100644
index 00000000000..d637a32b0d9
--- /dev/null
+++ b/studio/frontend/src/features/chat/adapters/studio-dictation-adapter.tsx
@@ -0,0 +1,139 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { useSettingsDialogStore } from "@/features/settings/stores/settings-dialog-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 {
+ type StudioDictationSession,
+ StudioWebSpeechDictationAdapter,
+} from "./studio-web-speech-dictation-adapter";
+
+// The one live dictation session, so the recording bar's discard (X) can cancel
+// it without going through assistant-ui (which only exposes stop, i.e.
+// transcribe). Cancelling emits no transcript, so composer text is untouched.
+let activeSession: StudioDictationSession | null = null;
+
+/** Discard the current dictation without transcribing. Safe to call when idle. */
+export function cancelActiveStudioDictation(): void {
+ const session = activeSession;
+ activeSession = null;
+ session?.cancel();
+}
+
+/**
+ * Routes dictation to the engine chosen in Voice settings, resolved at listen()
+ * time so switching engines applies without reloading the chat runtime.
+ */
+/** Both local engines (Transformers and GGUF) record via MediaRecorder. */
+function usesModelRecording(dictationEngine: DictationEngine): boolean {
+ return dictationEngine === "model";
+}
+
+export class StudioDictationAdapter implements DictationAdapter {
+ // Chat linked in Recent dictations. undefined follows the active single chat;
+ // null records no chat (composers outside it, e.g. Compare).
+ private readonly chatId: string | null | undefined;
+
+ constructor(options: { chatId?: string | null } = {}) {
+ this.chatId = options.chatId;
+ }
+
+ static isSupported(
+ dictationEngine: DictationEngine = useVoiceSettingsStore.getState()
+ .dictationEngine,
+ ): boolean {
+ return usesModelRecording(dictationEngine)
+ ? StudioModelDictationAdapter.isSupported()
+ : StudioWebSpeechDictationAdapter.isSupported();
+ }
+
+ listen(): StudioDictationSession {
+ const session = this.createSession();
+ // A second entry point (chat, Compare, settings test) replaces the active
+ // session; cancel the old one so it cannot keep the mic open or save a
+ // transcript with no discard button pointing at it.
+ cancelActiveStudioDictation();
+ activeSession = session;
+ // Forget the session once it ends so a later cancel is a no-op.
+ const clear = () => {
+ if (activeSession === session) {
+ activeSession = null;
+ }
+ };
+ session.onSpeechEnd(clear);
+ session.onEnd?.(clear);
+ return session;
+ }
+
+ private createSession(): StudioDictationSession {
+ const { dictationEngine } = useVoiceSettingsStore.getState();
+ if (usesModelRecording(dictationEngine)) {
+ if (StudioModelDictationAdapter.isSupported()) {
+ return new StudioModelDictationAdapter({ chatId: this.chatId }).listen();
+ }
+ throw new Error(
+ "Local model dictation is not supported in this browser.",
+ );
+ }
+ if (StudioWebSpeechDictationAdapter.isSupported()) {
+ return new StudioWebSpeechDictationAdapter({ chatId: this.chatId }).listen();
+ }
+ throw new Error("Browser dictation is not supported in this browser.");
+ }
+}
+
+/** Whether dictation can run now for the chosen engine. */
+export function isStudioDictationAvailable(
+ dictationEngine: DictationEngine = useVoiceSettingsStore.getState()
+ .dictationEngine,
+): boolean {
+ return StudioDictationAdapter.isSupported(dictationEngine);
+}
+
+/** Explain why dictation can't start and point the user to the local model. */
+export function notifyStudioDictationUnavailable(
+ dictationEngine: DictationEngine = useVoiceSettingsStore.getState()
+ .dictationEngine,
+): void {
+ // Both engines need a secure context (localhost or HTTPS).
+ if (typeof window !== "undefined" && !window.isSecureContext) {
+ toast.error("Voice typing needs a secure connection.", {
+ description:
+ "Open Studio at http://127.0.0.1 (localhost) or over HTTPS to dictate.",
+ });
+ return;
+ }
+ if (usesModelRecording(dictationEngine)) {
+ // Defensive: MediaRecorder is effectively always present here.
+ toast.error("Voice recording isn't available in this browser.");
+ return;
+ }
+ // Browser Web Speech is missing (e.g. Firefox). Stack text and button so the
+ // action sits below, not squeezed into a side column.
+ const toastId = toast.error("Voice typing isn't available in this browser.", {
+ description: (
+ <div className="mt-0.5 flex flex-col items-start gap-2 pb-1.5">
+ <span>
+ Choose the local speech-to-text model in Voice settings to dictate
+ here.
+ </span>
+ <button
+ type="button"
+ onClick={() => {
+ useSettingsDialogStore.getState().openDialog("voice");
+ toast.dismiss(toastId);
+ }}
+ className="rounded-full bg-foreground px-2.5 pt-1 pb-1.5 text-xs font-medium text-background transition-colors hover:bg-foreground/90"
+ >
+ Open Voice settings
+ </button>
+ </div>
+ ),
+ });
+}
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
new file mode 100644
index 00000000000..8546e3eeab1
--- /dev/null
+++ b/studio/frontend/src/features/chat/adapters/studio-model-dictation-adapter.ts
@@ -0,0 +1,637 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { authFetch } from "@/features/auth";
+import { hubTokenHeader } from "@/features/hub/lib/hub-token-header";
+import {
+ applyDictationDictionary,
+ isCuratedSttModel,
+ recordRecentDictation,
+ resolveModelDictationLanguage,
+ useVoiceSettingsStore,
+} from "@/features/settings/stores/voice-settings-store";
+import type { DictationAdapter } from "@assistant-ui/react";
+import { toast } from "sonner";
+import { startDictationLevelMeter } from "./dictation-level";
+import {
+ type StudioDictationSession,
+ isMissingDeviceError,
+ resolveDictationChatId,
+} from "./studio-web-speech-dictation-adapter";
+
+// Fine timeslice so the buffer is ready the moment a segment is cut or stopped.
+const SEGMENT_TIMESLICE_MS = 250;
+// Whisper pads input to 30s. Short dictation stays one clip; long dictation cuts
+// at the first pause after 20s or before the 30s boundary.
+const MIN_SEGMENT_MS = 20_000;
+const MAX_SEGMENT_MS = 28_000;
+const SILENCE_CUT_MS = 280;
+// Raw RMS (0..1) above which a frame counts as speech (well above the room floor
+// after noise suppression).
+const VOICE_RMS = 0.015;
+
+// Prefer Opus (small, widely supported); fall back to whatever the browser
+// records. The backend decodes any of these with PyAV.
+const PREFERRED_MIME_TYPES = [
+ "audio/webm;codecs=opus",
+ "audio/webm",
+ "audio/ogg;codecs=opus",
+ "audio/mp4",
+];
+
+function pickMimeType(): string | undefined {
+ if (typeof MediaRecorder === "undefined") return undefined;
+ for (const type of PREFERRED_MIME_TYPES) {
+ if (MediaRecorder.isTypeSupported(type)) return type;
+ }
+ return undefined;
+}
+
+const stopStream = (stream: MediaStream | null) => {
+ for (const track of stream?.getTracks() ?? []) {
+ track.stop();
+ }
+};
+
+/** 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";
+
+export function sttEngineFor(model: string): SttEngine {
+ return isCuratedSttModel(model) ? "gguf" : "transformers";
+}
+
+/** POST audio to the STT sidecar and return the transcript. */
+export async function transcribeAudioBlob(
+ blob: Blob,
+ options: {
+ model?: string;
+ language?: string;
+ engine?: SttEngine;
+ signal?: AbortSignal;
+ } = {},
+): Promise<string> {
+ const settings = useVoiceSettingsStore.getState();
+ const model = options.model ?? settings.sttModel;
+ const language = resolveModelDictationLanguage(
+ model,
+ options.language ?? settings.dictationLanguage,
+ );
+ const engine = options.engine ?? sttEngineFor(model);
+ const params = new URLSearchParams({ model, fast: "true", engine });
+ if (language) params.set("language", language);
+ const response = await authFetch(
+ `/api/inference/audio/transcribe/raw?${params.toString()}`,
+ {
+ method: "POST",
+ headers: { "Content-Type": blob.type || "application/octet-stream" },
+ body: blob,
+ signal: options.signal,
+ },
+ );
+ if (!response.ok) {
+ const body = (await response.json().catch(() => null)) as {
+ detail?: string;
+ } | null;
+ const detail = body?.detail ?? `HTTP ${response.status}`;
+ if (response.status === 501) {
+ throw new Error(
+ "Speech-to-text is not available on this server. Run `unsloth studio update` to install it.",
+ );
+ }
+ throw new Error(detail);
+ }
+ const data = (await response.json()) as { text?: string };
+ return (data.text ?? "").trim();
+}
+
+export interface SttDownloadStatus {
+ downloading: boolean;
+ model: string | null;
+ error: string | null;
+ bytes_total: number | null;
+ bytes_done: number | null;
+}
+
+export interface SttEngineStatus {
+ available: boolean;
+ loaded_model: string | null;
+ loading: boolean;
+ device: string | null;
+ keep_alive_seconds: number;
+ default_model: string;
+ models: string[];
+ downloaded_models: string[];
+ download: SttDownloadStatus;
+}
+
+export interface SttStatus {
+ available: boolean;
+ loaded_model: string | null;
+ loading: boolean;
+ device: string | null;
+ keep_alive_seconds: number;
+ default_model: string;
+ models: string[];
+ /** Per-engine state; absent on servers predating the engine split. */
+ transformers?: SttEngineStatus;
+ gguf?: SttEngineStatus;
+}
+
+// Keep load/unload requests ordered so a new recording cannot race an unload
+// still finishing for the previous one.
+let sttLifecycle: Promise<void> = Promise.resolve();
+
+function queueSttLifecycle(operation: () => Promise<void>): Promise<void> {
+ const result = sttLifecycle.catch(() => {}).then(operation);
+ sttLifecycle = result.catch(() => {});
+ return result;
+}
+
+/** Report whether STT is installed and which model, if any, is resident.
+ * Passing a model extends the downloaded check to custom repos. */
+export async function fetchSttStatus(
+ refreshKey?: number,
+ model?: string,
+): Promise<SttStatus> {
+ const params = new URLSearchParams();
+ if (refreshKey !== undefined) params.set("refresh", String(refreshKey));
+ if (model) params.set("model", model);
+ const query = params.toString();
+ const response = await authFetch(
+ `/api/inference/audio/stt/status${query ? `?${query}` : ""}`,
+ );
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
+ return (await response.json()) as SttStatus;
+}
+
+/** Verify a custom Hub repository is a Transformers Whisper checkpoint. */
+export async function validateSttModel(
+ model: string,
+ hfToken?: string,
+): Promise<void> {
+ const response = await authFetch("/api/inference/audio/stt/validate", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ ...hubTokenHeader(hfToken),
+ },
+ body: JSON.stringify({ model }),
+ });
+ if (!response.ok) {
+ const body = (await response.json().catch(() => null)) as {
+ detail?: string;
+ } | null;
+ throw new Error(body?.detail ?? `HTTP ${response.status}`);
+ }
+}
+
+/** Load a selected model that is already downloaded. */
+export function loadSttModel(model: string, engine?: SttEngine): Promise<void> {
+ const resolvedEngine = engine ?? sttEngineFor(model);
+ return queueSttLifecycle(async () => {
+ const response = await authFetch("/api/inference/audio/stt/load", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ model, engine: resolvedEngine }),
+ });
+ if (!response.ok) {
+ const body = (await response.json().catch(() => null)) as {
+ detail?: string;
+ } | null;
+ throw new Error(body?.detail ?? `HTTP ${response.status}`);
+ }
+ });
+}
+
+/** Start a background download of a dictation model. */
+export async function startSttDownload(
+ model: string,
+ hfToken?: string,
+): Promise<void> {
+ const response = await authFetch("/api/inference/audio/stt/download", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ ...hubTokenHeader(hfToken),
+ },
+ 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 () => {
+ const response = await authFetch("/api/inference/audio/stt/unload", {
+ method: "POST",
+ });
+ if (!response.ok) {
+ const body = (await response.json().catch(() => null)) as {
+ detail?: string;
+ } | null;
+ throw new Error(body?.detail ?? `HTTP ${response.status}`);
+ }
+ });
+}
+
+/**
+ * Local model dictation. Short recordings use one pass; long ones split near
+ * Whisper's 30s window. Confirm keeps text, discard removes it, and either
+ * releases the microphone immediately.
+ */
+export class StudioModelDictationAdapter implements DictationAdapter {
+ private readonly chatId: string | null | undefined;
+
+ constructor(options: { chatId?: string | null } = {}) {
+ this.chatId = options.chatId;
+ }
+
+ static isSupported(): boolean {
+ return (
+ typeof window !== "undefined" &&
+ window.isSecureContext &&
+ typeof MediaRecorder !== "undefined" &&
+ navigator.mediaDevices?.getUserMedia !== undefined
+ );
+ }
+
+ listen(): DictationAdapter.Session {
+ if (!StudioModelDictationAdapter.isSupported()) {
+ throw new Error("Recording is not supported in this browser.");
+ }
+
+ // Pin the model, language, and linked chat chosen when recording began, so a
+ // mid-session settings change or thread switch cannot affect later segments
+ // or relink the saved transcript.
+ const { sttModel: sessionModel, dictationLanguage } =
+ useVoiceSettingsStore.getState();
+ const sessionLanguage = resolveModelDictationLanguage(
+ sessionModel,
+ dictationLanguage,
+ );
+ const sessionEngine = sttEngineFor(sessionModel);
+ const sessionChatId = resolveDictationChatId(this.chatId);
+
+ const speechStartCallbacks = new Set<() => void>();
+ const speechEndCallbacks = new Set<
+ (result: DictationAdapter.Result) => void
+ >();
+ const speechCallbacks = new Set<
+ (result: DictationAdapter.Result) => void
+ >();
+ const endCallbacks = new Set<() => void>();
+
+ let stream: MediaStream | null = null;
+ let ended = false;
+ let cancelled = false;
+ let finalizing = false;
+ const abortController = new AbortController();
+ const mimeType = pickMimeType();
+ // Shared waveform meter also feeds this adapter's pause detector.
+ let stopLevelMeter = () => {
+ // Replaced after microphone access succeeds.
+ };
+ let onAudioFrame: (rawRms: number, now: number) => void = () => {};
+
+ let resolveEnded: (() => void) | null = null;
+ const endedPromise = new Promise<void>((resolve) => {
+ resolveEnded = resolve;
+ });
+
+ // --- Background transcription pipeline ---------------------------------
+ // Each segment is a self-contained clip transcribed on its own; results are
+ // stored by index so the final text keeps its order.
+ type Segment = {
+ index: number;
+ chunks: Blob[];
+ startedAt: number;
+ voiced: boolean;
+ recorder: MediaRecorder;
+ };
+ const results: string[] = [];
+ const queue: { index: number; blob: Blob }[] = [];
+ let worker = false;
+ let currentSeg: Segment | null = null;
+ let segCounter = 0;
+ let pendingRecorders = 0;
+ let silenceMs = 0;
+ let lastFrameAt = 0;
+ let cutting = false;
+ let finalCutDone = false;
+ let reportedTranscriptionError = false;
+
+ const reportTranscriptionError = (error: unknown) => {
+ if (reportedTranscriptionError || cancelled || ended) return;
+ reportedTranscriptionError = true;
+ 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);
+ };
+
+ const buildTranscript = () =>
+ results
+ .filter((part) => part?.trim())
+ .join(" ")
+ .trim();
+
+ const finishSession = (
+ reason: "stopped" | "cancelled" | "error",
+ transcript?: string,
+ ) => {
+ if (ended) return;
+ ended = true;
+ stopLevelMeter();
+ if (currentSeg && currentSeg.recorder.state !== "inactive") {
+ try {
+ currentSeg.recorder.stop();
+ } catch {
+ // ignore
+ }
+ }
+ session.status = { type: "ended", reason };
+ stopStream(stream);
+ stream = null;
+ const corrected = transcript ? applyDictationDictionary(transcript) : "";
+ if (reason !== "cancelled" && corrected) {
+ for (const callback of speechCallbacks) {
+ callback({ transcript: corrected, isFinal: true });
+ }
+ recordRecentDictation(corrected, sessionChatId);
+ }
+ for (const callback of speechEndCallbacks) {
+ callback({ transcript: corrected });
+ }
+ for (const callback of endCallbacks) callback();
+ resolveEnded?.();
+ };
+
+ // Finish once the final segment has been cut and the queue has drained.
+ const maybeComplete = () => {
+ if (ended || cancelled || !finalizing || !finalCutDone) return;
+ if (pendingRecorders === 0 && queue.length === 0 && !worker) {
+ finishSession("stopped", buildTranscript());
+ }
+ };
+
+ // Transcribe queued segments one at a time so the backend is never flooded.
+ const processQueue = () => {
+ if (worker || cancelled || ended) return;
+ const item = queue.shift();
+ if (!item) {
+ maybeComplete();
+ return;
+ }
+ worker = true;
+ void (async () => {
+ try {
+ const text = await transcribeAudioBlob(item.blob, {
+ model: sessionModel,
+ language: sessionLanguage,
+ engine: sessionEngine,
+ signal: abortController.signal,
+ });
+ if (!cancelled) results[item.index] = text;
+ } catch (error) {
+ if (!cancelled && !abortController.signal.aborted) {
+ // Keep transcribed segments, but never hide that part was lost.
+ reportTranscriptionError(error);
+ }
+ } finally {
+ worker = false;
+ processQueue();
+ }
+ })();
+ };
+
+ // Every non-empty recording is transcribed. The RMS meter only shapes
+ // segment boundaries; a quiet microphone or suspended AudioContext can keep
+ // it below VOICE_RMS for real speech, so it must never discard audio.
+ // Whisper returns an empty transcript for genuine silence.
+ const enqueueSegment = (index: number, blob: Blob) => {
+ if (blob.size > 0) {
+ queue.push({ index, blob });
+ processQueue();
+ } else {
+ results[index] = "";
+ maybeComplete();
+ }
+ };
+
+ // Start recording a fresh segment on the shared mic stream.
+ const startSegment = () => {
+ if (ended || cancelled || !stream) return;
+ const seg: Segment = {
+ index: segCounter++,
+ chunks: [],
+ startedAt: performance.now(),
+ voiced: false,
+ recorder: new MediaRecorder(
+ stream,
+ mimeType ? { mimeType } : undefined,
+ ),
+ };
+ currentSeg = seg;
+ silenceMs = 0;
+ seg.recorder.addEventListener("dataavailable", (event) => {
+ if (event.data.size > 0) seg.chunks.push(event.data);
+ });
+ seg.recorder.addEventListener("stop", () => {
+ pendingRecorders = Math.max(0, pendingRecorders - 1);
+ if (cancelled || ended) {
+ maybeComplete();
+ return;
+ }
+ const blob = new Blob(seg.chunks, {
+ type: seg.recorder.mimeType || "audio/webm",
+ });
+ enqueueSegment(seg.index, blob);
+ });
+ pendingRecorders += 1;
+ try {
+ seg.recorder.start(SEGMENT_TIMESLICE_MS);
+ } catch (error) {
+ pendingRecorders = Math.max(0, pendingRecorders - 1);
+ if (currentSeg === seg) currentSeg = null;
+ throw error;
+ }
+ };
+
+ // Close the current segment at a pause and open the next, so recording stays
+ // continuous while each clip is independently decodable.
+ const cutSegment = () => {
+ const seg = currentSeg;
+ if (cutting || !seg || finalizing) return;
+ cutting = true;
+ const rec = seg.recorder;
+ if (rec.state !== "inactive") {
+ rec.addEventListener(
+ "stop",
+ () => {
+ cutting = false;
+ },
+ { once: true },
+ );
+ try {
+ rec.stop();
+ } catch {
+ cutting = false;
+ }
+ } else {
+ cutting = false;
+ }
+ startSegment();
+ };
+
+ // Pause detector: mark voiced frames. Short dictations stay one segment; long
+ // ones cut at a pause after the target duration, or at the hard limit.
+ onAudioFrame = (rawRms, now) => {
+ const seg = currentSeg;
+ if (!seg || finalizing) {
+ lastFrameAt = now;
+ return;
+ }
+ if (rawRms > VOICE_RMS) {
+ seg.voiced = true;
+ silenceMs = 0;
+ } else if (lastFrameAt) {
+ silenceMs += now - lastFrameAt;
+ }
+ lastFrameAt = now;
+ const duration = now - seg.startedAt;
+ const pauseBreak =
+ seg.voiced && duration > MIN_SEGMENT_MS && silenceMs > SILENCE_CUT_MS;
+ if (!cutting && (pauseBreak || duration > MAX_SEGMENT_MS)) {
+ cutSegment();
+ }
+ };
+
+ const session: StudioDictationSession = {
+ status: { type: "starting" },
+ stop: async () => {
+ if (!ended && !finalizing) {
+ finalizing = true;
+ // Stop publishing zero-valued frames at once so the UI can switch to
+ // its transcription shimmer.
+ stopLevelMeter();
+ const seg = currentSeg;
+ // Cut the final segment (its buffer survives) so only the short tail is
+ // left to transcribe, then release the mic immediately.
+ if (seg && seg.recorder.state !== "inactive") {
+ seg.recorder.addEventListener(
+ "stop",
+ () => {
+ finalCutDone = true;
+ maybeComplete();
+ },
+ { once: true },
+ );
+ try {
+ seg.recorder.stop();
+ } catch {
+ finalCutDone = true;
+ maybeComplete();
+ }
+ } else {
+ finalCutDone = true;
+ maybeComplete();
+ }
+ stopStream(stream);
+ stream = null;
+ }
+ await endedPromise;
+ },
+ cancel: () => {
+ if (ended) return;
+ cancelled = true;
+ finalizing = true;
+ abortController.abort();
+ finishSession("cancelled");
+ },
+ onSpeechStart: (callback) => {
+ speechStartCallbacks.add(callback);
+ return () => {
+ speechStartCallbacks.delete(callback);
+ };
+ },
+ onSpeechEnd: (callback) => {
+ speechEndCallbacks.add(callback);
+ return () => {
+ speechEndCallbacks.delete(callback);
+ };
+ },
+ onSpeech: (callback) => {
+ speechCallbacks.add(callback);
+ return () => {
+ speechCallbacks.delete(callback);
+ };
+ },
+ onEnd: (callback: () => void) => {
+ endCallbacks.add(callback);
+ return () => {
+ endCallbacks.delete(callback);
+ };
+ },
+ };
+
+ void (async () => {
+ try {
+ const { micDeviceId } = useVoiceSettingsStore.getState();
+ const baseAudio: MediaTrackConstraints = {
+ echoCancellation: true,
+ noiseSuppression: true,
+ };
+ try {
+ stream = await navigator.mediaDevices.getUserMedia({
+ audio:
+ micDeviceId && micDeviceId !== "default"
+ ? { ...baseAudio, deviceId: { exact: micDeviceId } }
+ : baseAudio,
+ });
+ } catch (error) {
+ // Saved mic may be unplugged; fall back to the default.
+ if (micDeviceId !== "default" && isMissingDeviceError(error)) {
+ stream = await navigator.mediaDevices.getUserMedia({
+ audio: baseAudio,
+ });
+ } else {
+ throw error;
+ }
+ }
+ if (ended || cancelled) {
+ stopStream(stream);
+ stream = null;
+ return;
+ }
+ // Warm the model only after mic access. The backend loads cache-only
+ // and never downloads here.
+ void loadSttModel(sessionModel, sessionEngine).catch(
+ reportTranscriptionError,
+ );
+ stopLevelMeter = startDictationLevelMeter(stream, (rawRms, now) => {
+ onAudioFrame(rawRms, now);
+ });
+ startSegment();
+ session.status = { type: "running" };
+ for (const callback of speechStartCallbacks) callback();
+ } catch (error) {
+ const message = isMissingDeviceError(error)
+ ? "No microphone was found for dictation."
+ : "Dictation could not access the microphone.";
+ console.error("STT microphone error:", error);
+ toast.error(message);
+ finishSession("error");
+ }
+ })();
+
+ return session;
+ }
+}
diff --git a/studio/frontend/src/features/chat/adapters/studio-speech-synthesis-adapter.ts b/studio/frontend/src/features/chat/adapters/studio-speech-synthesis-adapter.ts
index 5e6a76e9499..3a5042f61dc 100644
--- a/studio/frontend/src/features/chat/adapters/studio-speech-synthesis-adapter.ts
+++ b/studio/frontend/src/features/chat/adapters/studio-speech-synthesis-adapter.ts
@@ -6,17 +6,19 @@ import { useVoiceSettingsStore } from "@/features/settings/stores/voice-settings
import { toast } from "@/lib/toast";
import type { SpeechSynthesisAdapter } from "@assistant-ui/react";
-/** Voice for a stored voiceURI; undefined lets the browser pick. */
+/** Voice for a stored voiceURI. "default" resolves to the voice the platform
+ * marks as its default, so the "System default" choice means what it says
+ * instead of falling back to a curated pick. Undefined lets the browser pick. */
export function findTtsVoice(
voiceURI: string,
): SpeechSynthesisVoice | undefined {
if (typeof window === "undefined" || !window.speechSynthesis) {
return undefined;
}
- if (!voiceURI || voiceURI === "default") return undefined;
- return window.speechSynthesis
- .getVoices()
- .find((voice) => voice.voiceURI === voiceURI);
+ if (!voiceURI) return undefined;
+ const voices = window.speechSynthesis.getVoices();
+ if (voiceURI === "default") return voices.find((voice) => voice.default);
+ return voices.find((voice) => voice.voiceURI === voiceURI);
}
// macOS novelty and legacy Eloquence voices that sound robotic and flood the picker.
@@ -59,19 +61,54 @@ function voiceBaseName(voice: SpeechSynthesisVoice): string {
return name;
}
+// Well-known natural English voices, best first. Breaks ties when the name
+// carries no quality hint, so basic voices are not just alphabetical.
+const PREFERRED_VOICE_NAMES = [
+ "samantha",
+ "alex",
+ "ava",
+ "allison",
+ "susan",
+ "tom",
+ "daniel",
+ "serena",
+ "karen",
+ "moira",
+ "tessa",
+ "fiona",
+];
+
+// Quality tier from vendor hints in the voice name.
function voiceQualityScore(voice: SpeechSynthesisVoice): number {
const name = voice.name.toLowerCase();
let score = 0;
- if (name.includes("premium")) score += 8;
- if (name.includes("enhanced")) score += 7;
- if (name.includes("natural") || name.includes("neural")) score += 6;
- if (name.includes("siri")) score += 6;
- if (name.includes("google")) score += 5;
- if (name.includes("microsoft")) score += 4;
- if (voice.default) score += 3;
+ if (name.includes("premium")) score += 100;
+ if (name.includes("siri")) score += 90;
+ if (name.includes("enhanced")) score += 80;
+ if (name.includes("natural") || name.includes("neural")) score += 70;
+ if (name.includes("google")) score += 40;
+ if (name.includes("microsoft")) score += 30;
return score;
}
+// Higher for voices in the user's exact region, then the same language.
+function voiceLocaleScore(voice: SpeechSynthesisVoice): number {
+ const navLang =
+ typeof navigator !== "undefined" && navigator.language
+ ? navigator.language.toLowerCase()
+ : "en-us";
+ const lang = voice.lang.toLowerCase().replace("_", "-");
+ if (lang === navLang) return 2;
+ if (langBase(lang) === langBase(navLang)) return 1;
+ return 0;
+}
+
+// Rank in the preferred list, best first; 0 when the voice is not listed.
+function voicePreferredRank(voice: SpeechSynthesisVoice): number {
+ const index = PREFERRED_VOICE_NAMES.indexOf(voiceBaseName(voice));
+ return index === -1 ? 0 : PREFERRED_VOICE_NAMES.length - index;
+}
+
function langBase(tag: string): string {
return tag.toLowerCase().split(/[-_]/)[0] ?? "";
}
@@ -86,8 +123,8 @@ const MAX_CURATED_VOICES = 20;
export function curateSystemVoices(
voices: SpeechSynthesisVoice[],
selectedVoiceURI?: string,
+ dictationLanguage = useVoiceSettingsStore.getState().dictationLanguage,
): SpeechSynthesisVoice[] {
- const { dictationLanguage } = useVoiceSettingsStore.getState();
const wantedLangs = new Set<string>(["en"]);
if (typeof navigator !== "undefined" && navigator.language) {
wantedLangs.add(langBase(navigator.language));
@@ -107,12 +144,33 @@ export function curateSystemVoices(
});
kept.sort((a, b) => {
- const scoreDiff = voiceQualityScore(b) - voiceQualityScore(a);
- if (scoreDiff !== 0) return scoreDiff;
+ const quality = voiceQualityScore(b) - voiceQualityScore(a);
+ if (quality !== 0) return quality;
+ const locale = voiceLocaleScore(b) - voiceLocaleScore(a);
+ if (locale !== 0) return locale;
+ const preferred = voicePreferredRank(b) - voicePreferredRank(a);
+ if (preferred !== 0) return preferred;
+ const byDefault = Number(b.default) - Number(a.default);
+ if (byDefault !== 0) return byDefault;
return a.name.localeCompare(b.name);
});
- const curated = kept.slice(0, MAX_CURATED_VOICES);
+ // macOS reports some voices twice (compact + enhanced) under one name. Keep
+ // one per name and language, preferring the selected voice then the best
+ // ranked, so no duplicates show.
+ const keyOf = (voice: SpeechSynthesisVoice) =>
+ `${voiceBaseName(voice)}|${voice.lang.toLowerCase()}`;
+ const winners = new Map<string, string>();
+ for (const voice of kept) {
+ const key = keyOf(voice);
+ if (!winners.has(key)) winners.set(key, voice.voiceURI);
+ if (voice.voiceURI === selectedVoiceURI) winners.set(key, voice.voiceURI);
+ }
+ const deduped = kept.filter(
+ (voice) => winners.get(keyOf(voice)) === voice.voiceURI,
+ );
+
+ const curated = deduped.slice(0, MAX_CURATED_VOICES);
if (
selectedVoiceURI &&
selectedVoiceURI !== "default" &&
@@ -126,6 +184,22 @@ export function curateSystemVoices(
return curated;
}
+/**
+ * Best voice when none is chosen. The browser default on macOS is often a
+ * robotic legacy voice, so fall back to the top curated voice instead.
+ */
+function defaultTtsVoice(): SpeechSynthesisVoice | undefined {
+ if (typeof window === "undefined" || !window.speechSynthesis) {
+ return undefined;
+ }
+ const voices = window.speechSynthesis.getVoices();
+ return (
+ curateSystemVoices(voices)[0] ??
+ voices.find((voice) => voice.default) ??
+ voices[0]
+ );
+}
+
/** Build an utterance from the current Voice settings. */
export function createConfiguredUtterance(
text: string,
@@ -133,7 +207,7 @@ export function createConfiguredUtterance(
const { ttsVoiceURI, ttsRate, ttsPitch, ttsVolume } =
useVoiceSettingsStore.getState();
const utterance = new SpeechSynthesisUtterance(text);
- const voice = findTtsVoice(ttsVoiceURI);
+ const voice = findTtsVoice(ttsVoiceURI) ?? defaultTtsVoice();
if (voice) {
utterance.voice = voice;
utterance.lang = voice.lang;
@@ -272,8 +346,14 @@ export class StudioSpeechSynthesisAdapter implements SpeechSynthesisAdapter {
if (res.status.type === "ended") return;
// Surface genuine read-aloud failures; a cancelled/interrupted utterance
// is a normal stop, not an error, and must not toast.
- if (reason === "error" && error !== "interrupted" && error !== "canceled") {
- toast.error(error instanceof Error ? error.message : "Read aloud failed.");
+ if (
+ reason === "error" &&
+ error !== "interrupted" &&
+ error !== "canceled"
+ ) {
+ toast.error(
+ error instanceof Error ? error.message : "Read aloud failed.",
+ );
}
res.status = { type: "ended", reason, error };
for (const handler of subscribers) handler();
diff --git a/studio/frontend/src/features/chat/adapters/studio-web-speech-dictation-adapter.ts b/studio/frontend/src/features/chat/adapters/studio-web-speech-dictation-adapter.ts
index b7a8e904ed9..fb0e4fc0ab7 100644
--- a/studio/frontend/src/features/chat/adapters/studio-web-speech-dictation-adapter.ts
+++ b/studio/frontend/src/features/chat/adapters/studio-web-speech-dictation-adapter.ts
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import { useSettingsDialogStore } from "@/features/settings/stores/settings-dialog-store";
import {
applyDictationDictionary,
recordRecentDictation,
@@ -9,6 +10,39 @@ import {
} from "@/features/settings/stores/voice-settings-store";
import type { DictationAdapter } from "@assistant-ui/react";
import { toast } from "sonner";
+import { useChatRuntimeStore } from "../stores/chat-runtime-store";
+import { startDictationLevelMeter } from "./dictation-level";
+
+/** Chat open while dictating, so the saved dictation can link back to it. */
+export function activeDictationChatId(): string | undefined {
+ return useChatRuntimeStore.getState().activeThreadId ?? undefined;
+}
+
+/**
+ * Resolve the chat a saved dictation links to. undefined falls back to the
+ * active single chat; null (composers without one, e.g. Compare) means none.
+ */
+export function resolveDictationChatId(
+ chatId: string | null | undefined,
+): string | undefined {
+ if (chatId === undefined) return activeDictationChatId();
+ return chatId ?? undefined;
+}
+
+// Reused id so repeated network failures replace, not stack, the same toast.
+const NETWORK_TOAST_ID = "dictation-network-offline";
+
+// Short grace for the browser to finalize its latest interim hypothesis. If it
+// doesn't, promote that text instead of stalling on a finalization spinner.
+const STOP_FINALIZATION_GRACE_MS = 350;
+
+/**
+ * A dictation session with an extra onEnd hook (not part of the assistant-ui
+ * interface) so non-runtime callers can reset when the session ends by itself.
+ */
+export type StudioDictationSession = DictationAdapter.Session & {
+ onEnd?: (callback: () => void) => () => void;
+};
const getSpeechRecognitionAPI = ():
| SpeechRecognitionConstructor
@@ -18,7 +52,9 @@ const getSpeechRecognitionAPI = ():
};
const stopStream = (stream: MediaStream | null) => {
- stream?.getTracks().forEach((track) => track.stop());
+ for (const track of stream?.getTracks() ?? []) {
+ track.stop();
+ }
};
const mediaErrorName = (error: unknown): unknown =>
@@ -48,7 +84,10 @@ export const describeMediaError = (error: unknown): string => {
: "Dictation could not access the microphone.";
};
-export const describeSpeechError = (error: string, message?: string): string => {
+export const describeSpeechError = (
+ error: string,
+ message?: string,
+): string => {
if (error === "not-allowed") {
return "Speech recognition was blocked by the browser. Check microphone permissions for this Unsloth page.";
}
@@ -68,18 +107,21 @@ export class StudioWebSpeechDictationAdapter implements DictationAdapter {
private readonly language: string | undefined;
private readonly continuous: boolean;
private readonly interimResults: boolean;
+ private readonly chatId: string | null | undefined;
constructor(
options: {
language?: string;
continuous?: boolean;
interimResults?: boolean;
+ chatId?: string | null;
} = {},
) {
// Resolved from Voice settings at listen() time unless overridden.
this.language = options.language;
this.continuous = options.continuous ?? true;
this.interimResults = options.interimResults ?? true;
+ this.chatId = options.chatId;
}
static isSupported(): boolean {
@@ -101,6 +143,9 @@ export class StudioWebSpeechDictationAdapter implements DictationAdapter {
recognition.lang = this.language ?? resolveDictationLanguage();
recognition.continuous = this.continuous;
recognition.interimResults = this.interimResults;
+ // Pin the linked chat now so a thread switch during finalization cannot
+ // relink the transcript to the newly opened chat.
+ const sessionChatId = resolveDictationChatId(this.chatId);
const speechStartCallbacks = new Set<() => void>();
const speechEndCallbacks = new Set<
@@ -109,22 +154,38 @@ export class StudioWebSpeechDictationAdapter implements DictationAdapter {
const speechCallbacks = new Set<
(result: DictationAdapter.Result) => void
>();
+ const endCallbacks = new Set<() => void>();
let stream: MediaStream | null = null;
let finalTranscript = "";
let ended = false;
let started = false;
+ let stopping = false;
+ let stopRequestedAt = 0;
+ let stopFallbackTimer = 0;
+ let stopLevelMeter = () => {
+ // Replaced after microphone access succeeds.
+ };
+ const interimParts = new Map<number, string>();
let resolveEnded: (() => void) | null = null;
const endedPromise = new Promise<void>((resolve) => {
resolveEnded = resolve;
});
- const session: DictationAdapter.Session = {
+ const session: StudioDictationSession = {
status: { type: "starting" },
stop: async () => {
if (!ended && started) {
+ stopping = true;
+ stopRequestedAt = performance.now();
recognition.stop();
+ // Ending the track now gives the browser an audio endpoint to finalize
+ // and releases the mic without waiting on its remote speech service.
+ stopLevelMeter();
+ stopStream(stream);
+ stream = null;
+ scheduleStopFallback();
} else if (!ended) {
finish("stopped");
}
@@ -132,11 +193,9 @@ export class StudioWebSpeechDictationAdapter implements DictationAdapter {
},
cancel: () => {
- if (!ended && started) {
- recognition.abort();
- } else if (!ended) {
- finish("cancelled");
- }
+ if (ended) return;
+ if (started) recognition.abort();
+ finish("cancelled");
},
onSpeechStart: (callback) => {
@@ -159,23 +218,75 @@ export class StudioWebSpeechDictationAdapter implements DictationAdapter {
speechCallbacks.delete(callback);
};
},
+
+ // Beyond DictationAdapter: lets callers reset UI when the session ends on
+ // its own (silence, error), not just via stop().
+ onEnd: (callback: () => void) => {
+ endCallbacks.add(callback);
+ return () => {
+ endCallbacks.delete(callback);
+ };
+ },
+ };
+
+ const currentInterimTranscript = () =>
+ [...interimParts.entries()]
+ .sort(([a], [b]) => a - b)
+ .map(([, transcript]) => transcript.trim())
+ .filter(Boolean)
+ .join(" ");
+
+ const promoteInterim = () => {
+ const interim = currentInterimTranscript();
+ interimParts.clear();
+ if (!interim) return false;
+ const corrected = applyDictationDictionary(interim).trim();
+ if (!corrected) return false;
+ finalTranscript = finalTranscript
+ ? `${finalTranscript} ${corrected}`
+ : corrected;
+ return true;
};
+ function scheduleStopFallback(): void {
+ if (!stopping || ended || stopFallbackTimer) return;
+ const elapsed = performance.now() - stopRequestedAt;
+ const delay = Math.max(0, STOP_FINALIZATION_GRACE_MS - elapsed);
+ stopFallbackTimer = window.setTimeout(() => {
+ stopFallbackTimer = 0;
+ if (!ended) {
+ promoteInterim();
+ finish("stopped");
+ recognition.abort();
+ }
+ }, delay);
+ }
+
const finish = (reason: "stopped" | "cancelled" | "error") => {
if (ended) return;
ended = true;
+ stopping = false;
+ if (stopFallbackTimer) window.clearTimeout(stopFallbackTimer);
+ stopFallbackTimer = 0;
session.status = { type: "ended", reason };
+ stopLevelMeter();
stopStream(stream);
stream = null;
- if (finalTranscript) {
- for (const callback of speechEndCallbacks) {
- callback({ transcript: finalTranscript });
- }
- if (reason !== "cancelled") {
- recordRecentDictation(finalTranscript);
+ const transcript = reason === "cancelled" ? "" : finalTranscript;
+ if (transcript) {
+ for (const callback of speechCallbacks) {
+ callback({ transcript, isFinal: true });
}
- finalTranscript = "";
+ recordRecentDictation(transcript, sessionChatId);
+ }
+ // assistant-ui uses this callback to leave dictation mode; required even
+ // for silence and cancelled recordings.
+ for (const callback of speechEndCallbacks) {
+ callback({ transcript });
}
+ finalTranscript = "";
+ interimParts.clear();
+ for (const callback of endCallbacks) callback();
resolveEnded?.();
};
@@ -188,6 +299,7 @@ export class StudioWebSpeechDictationAdapter implements DictationAdapter {
});
recognition.addEventListener("result", (event) => {
+ if (ended) return;
const speechEvent = event as SpeechRecognitionEvent;
for (
let i = speechEvent.resultIndex;
@@ -198,6 +310,7 @@ export class StudioWebSpeechDictationAdapter implements DictationAdapter {
if (!result) continue;
const transcript = result[0]?.transcript ?? "";
if (result.isFinal) {
+ interimParts.delete(i);
const corrected = applyDictationDictionary(transcript);
// Join final chunks with a single space so recorded transcripts do
// not merge words when a browser omits leading whitespace.
@@ -207,25 +320,34 @@ export class StudioWebSpeechDictationAdapter implements DictationAdapter {
? `${finalTranscript} ${trimmed}`
: trimmed;
}
- for (const callback of speechCallbacks) {
- callback({ transcript: corrected, isFinal: true });
- }
} else {
- for (const callback of speechCallbacks) {
- callback({ transcript, isFinal: false });
- }
+ interimParts.set(i, transcript);
}
}
+ const interim = currentInterimTranscript();
+ if (interim) {
+ scheduleStopFallback();
+ }
});
recognition.addEventListener("end", () => {
+ if (ended) {
+ return;
+ }
+ promoteInterim();
finish("stopped");
});
recognition.addEventListener("error", (event) => {
+ if (ended) return;
const errorEvent = event as SpeechRecognitionErrorEvent;
if (errorEvent.error === "aborted") {
- finish("cancelled");
+ if (stopping) {
+ promoteInterim();
+ finish("stopped");
+ } else {
+ finish("cancelled");
+ }
return;
}
const description = describeSpeechError(
@@ -233,7 +355,22 @@ export class StudioWebSpeechDictationAdapter implements DictationAdapter {
errorEvent.message,
);
console.error("Dictation error:", errorEvent.error, errorEvent.message);
- toast.error(description);
+ if (errorEvent.error === "network") {
+ // Online speech service unreachable; point the user to the offline
+ // local engine (the toast opens Voice settings).
+ toast.error("No internet connection", {
+ id: NETWORK_TOAST_ID,
+ description:
+ "Browser dictation needs the online speech service. Switch to Local in Voice settings and pick a local STT model to dictate offline.",
+ action: {
+ label: "Open Voice settings",
+ onClick: () =>
+ useSettingsDialogStore.getState().openDialog("voice"),
+ },
+ });
+ } else {
+ toast.error(description);
+ }
finish("error");
});
@@ -275,6 +412,7 @@ export class StudioWebSpeechDictationAdapter implements DictationAdapter {
"NotFoundError",
);
}
+ stopLevelMeter = startDictationLevelMeter(stream);
try {
recognition.start(audioTrack);
} catch (error) {
@@ -285,6 +423,7 @@ export class StudioWebSpeechDictationAdapter implements DictationAdapter {
"Dictation start(audioTrack) failed; retrying start().",
error,
);
+ stopLevelMeter();
stopStream(stream);
stream = null;
recognition.start();
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index 335421e1459..785212a2c47 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -119,3 +119,25 @@ export {
updateChatProjectInstructions,
useChatProjects,
} from "./hooks/use-chat-projects";
+export { subscribeDictationLevel } from "./adapters/dictation-level";
+export {
+ StudioDictationAdapter,
+ cancelActiveStudioDictation,
+ isStudioDictationAvailable,
+ notifyStudioDictationUnavailable,
+} from "./adapters/studio-dictation-adapter";
+export {
+ StudioModelDictationAdapter,
+ fetchSttStatus,
+ loadSttModel,
+ startSttDownload,
+ unloadSttModel,
+ validateSttModel,
+ type SttDownloadStatus,
+} from "./adapters/studio-model-dictation-adapter";
+export {
+ StudioSpeechSynthesisAdapter,
+ createConfiguredUtterance,
+ curateSystemVoices,
+ generateStudioTtsAudio,
+} from "./adapters/studio-speech-synthesis-adapter";
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsx
index 4a8740ac9b4..d9e407fd5ee 100644
--- a/studio/frontend/src/features/chat/runtime-provider.tsx
+++ b/studio/frontend/src/features/chat/runtime-provider.tsx
@@ -33,8 +33,8 @@ import {
useRef,
} from "react";
import { toast } from "sonner";
+import { StudioDictationAdapter } from "./adapters/studio-dictation-adapter";
import { StudioSpeechSynthesisAdapter } from "./adapters/studio-speech-synthesis-adapter";
-import { StudioWebSpeechDictationAdapter } from "./adapters/studio-web-speech-dictation-adapter";
import {
ThreadAutosaveHandle,
createOpenAIStreamAdapter,
@@ -1195,13 +1195,10 @@ function useStudioRuntimeAdapters(
[aui, modelType, pairId],
);
- const dictation = useMemo(
- () =>
- StudioWebSpeechDictationAdapter.isSupported()
- ? new StudioWebSpeechDictationAdapter()
- : undefined,
- [],
- );
+ // Always register the adapter so the mic stays clickable for any engine. The
+ // engine is resolved at listen() time and the composer shows guidance when it
+ // cannot run, so engine switches also work on an already-mounted thread.
+ const dictation = useMemo(() => new StudioDictationAdapter(), []);
const speech = useMemo(
() =>
StudioSpeechSynthesisAdapter.isSupported()
diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsx
index 3156a6411a4..3f89f70ef11 100644
--- a/studio/frontend/src/features/chat/shared-composer.tsx
+++ b/studio/frontend/src/features/chat/shared-composer.tsx
@@ -24,16 +24,12 @@ import {
} from "@/components/ui/dropdown-menu";
import { applyQwenThinkingParams } from "@/features/chat/utils/qwen-params";
import {
- describeMediaError,
- describeSpeechError,
- isMissingDeviceError,
-} from "@/features/chat/adapters/studio-web-speech-dictation-adapter";
-import {
- applyDictationDictionary,
- recordRecentDictation,
- resolveDictationLanguage,
- useVoiceSettingsStore,
-} from "@/features/settings/stores/voice-settings-store";
+ StudioDictationAdapter,
+ isStudioDictationAvailable,
+ notifyStudioDictationUnavailable,
+} from "@/features/chat/adapters/studio-dictation-adapter";
+import type { StudioDictationSession } from "@/features/chat/adapters/studio-web-speech-dictation-adapter";
+import { useVoiceSettingsStore } from "@/features/settings/stores/voice-settings-store";
import { AUDIO_ACCEPT, MAX_AUDIO_SIZE, fileToBase64 } from "@/lib/audio-utils";
import { isTauri } from "@/lib/api-base";
import { isDownloadCancelled } from "@/lib/native-files";
@@ -224,173 +220,95 @@ function formatReasoningDisabledLabel(
function useDictation(
setText: (value: string | ((prev: string) => string)) => void,
) {
+ // Re-render support state when the user switches recognition engines.
+ const dictationEngine = useVoiceSettingsStore((s) => s.dictationEngine);
const [isDictating, setIsDictating] = useState(false);
- const recognitionRef = useRef<SpeechRecognition | null>(null);
-
- const streamRef = useRef<MediaStream | null>(null);
+ // True while a stopped recording's final audio is still transcribing; a
+ // second click then cancels the pending transcription instead of re-stopping.
+ const [isFinalizing, setIsFinalizing] = useState(false);
+ const sessionRef = useRef<StudioDictationSession | null>(null);
const startingRef = useRef(false);
- // Guards the getUserMedia await so a mic opened after unmount is released.
- const disposedRef = useRef(false);
-
- const releaseStream = useCallback(() => {
- streamRef.current?.getTracks().forEach((track) => track.stop());
- streamRef.current = null;
- }, []);
+ const finalizingRef = useRef(false);
const start = useCallback(async () => {
- const SpeechRecognitionAPI =
- typeof window !== "undefined" &&
- (window.SpeechRecognition ??
- (
- window as unknown as {
- webkitSpeechRecognition?: typeof SpeechRecognition;
- }
- ).webkitSpeechRecognition);
- if (!SpeechRecognitionAPI) {
+ if (startingRef.current || sessionRef.current) return;
+ // Unsupported engine (e.g. Firefox): explain and steer to the local model.
+ if (!isStudioDictationAvailable()) {
+ notifyStudioDictationUnavailable();
return;
}
- if (startingRef.current || recognitionRef.current) return;
startingRef.current = true;
- // Open the microphone chosen in Voice settings, matching the main chat
- // adapter, so Compare dictation honors the same device selection.
- let audioTrack: MediaStreamTrack | undefined;
- const { micDeviceId } = useVoiceSettingsStore.getState();
- if (navigator.mediaDevices?.getUserMedia) {
- try {
- let stream: MediaStream;
- try {
- stream = await navigator.mediaDevices.getUserMedia({
- audio:
- micDeviceId && micDeviceId !== "default"
- ? { deviceId: { exact: micDeviceId } }
- : true,
- });
- } catch (error) {
- // Saved mic may be unplugged; fall back to the default device.
- if (micDeviceId !== "default" && isMissingDeviceError(error)) {
- stream = await navigator.mediaDevices.getUserMedia({
- audio: true,
- });
- } else {
- throw error;
- }
- }
- streamRef.current = stream;
- audioTrack = stream.getAudioTracks()[0];
- } catch (error) {
- // Permission/security failure: report it and stop instead of silently
- // recording from a different default device, matching the main adapter.
- startingRef.current = false;
- releaseStream();
- setIsDictating(false);
- toast.error(describeMediaError(error));
- return;
- }
- }
-
- if (disposedRef.current) {
- releaseStream();
+ let session: StudioDictationSession;
+ try {
+ // Routes to the engine chosen in Voice settings (browser or STT model),
+ // honoring the selected microphone, language, and dictionary. Compare
+ // feeds two panes, so recent dictations must not link the unrelated
+ // single-chat active thread.
+ session = new StudioDictationAdapter({ chatId: null }).listen();
+ } catch {
startingRef.current = false;
+ notifyStudioDictationUnavailable();
return;
}
+ sessionRef.current = session;
+ setIsDictating(true);
- const recognition = new SpeechRecognitionAPI() as SpeechRecognition;
- recognition.continuous = true;
- recognition.interimResults = true;
- recognition.lang = resolveDictationLanguage();
- let sessionTranscript = "";
- recognition.onresult = (event: SpeechRecognitionEvent) => {
- // Iterate every result from resultIndex; a single event can carry more
- // than one finalized phrase and dropping the rest loses dictated words.
- for (let i = event.resultIndex; i < event.results.length; i++) {
- const result = event.results[i];
- if (!result?.isFinal) continue;
- const transcript = applyDictationDictionary(
- result[0]?.transcript?.trim() ?? "",
- );
- if (!transcript) continue;
- sessionTranscript = sessionTranscript
- ? `${sessionTranscript} ${transcript}`
- : transcript;
+ // Append final transcripts; the adapter has already applied the dictionary
+ // and records the session in Recent dictations.
+ session.onSpeech((result) => {
+ if (!result.isFinal) return;
+ const transcript = result.transcript?.trim() ?? "";
+ if (transcript) {
setText((prev) => (prev ? `${prev} ${transcript}` : transcript));
}
- };
- recognition.onerror = (event) => {
- // Report speech-service failures like the main adapter; aborted is a
- // normal stop, not an error.
- const errorEvent = event as SpeechRecognitionErrorEvent;
- if (errorEvent.error !== "aborted") {
- toast.error(describeSpeechError(errorEvent.error, errorEvent.message));
- }
+ });
+ session.onEnd?.(() => {
+ if (sessionRef.current === session) sessionRef.current = null;
+ finalizingRef.current = false;
+ setIsFinalizing(false);
setIsDictating(false);
- };
- recognition.onend = () => {
- // A stop()+immediate restart can install a new recognizer before this
- // old one ends; only tear down shared refs when we are still current.
- if (recognitionRef.current === recognition) {
- releaseStream();
- recognitionRef.current = null;
- setIsDictating(false);
- }
- if (sessionTranscript) {
- recordRecentDictation(sessionTranscript);
- sessionTranscript = "";
- }
- };
- try {
- if (audioTrack) {
- try {
- recognition.start(audioTrack);
- } catch {
- // No start(track) overload: recognition captures from the default
- // device, so release the selected-device stream.
- releaseStream();
- recognition.start();
- }
- } else {
- recognition.start();
- }
- } catch {
- startingRef.current = false;
- releaseStream();
- return;
- }
- recognitionRef.current = recognition;
+ });
startingRef.current = false;
- setIsDictating(true);
- }, [setText, releaseStream]);
+ }, [setText]);
const stop = useCallback(() => {
- if (recognitionRef.current) {
- recognitionRef.current.stop();
- recognitionRef.current = null;
+ const session = sessionRef.current;
+ if (!session) return;
+ // A second click while the final segment is transcribing discards the
+ // pending transcription instead of leaving the pane stuck until timeout.
+ if (finalizingRef.current) {
+ session.cancel();
+ if (sessionRef.current === session) sessionRef.current = null;
+ finalizingRef.current = false;
+ setIsFinalizing(false);
+ setIsDictating(false);
+ return;
}
- releaseStream();
- setIsDictating(false);
- }, [releaseStream]);
+ finalizingRef.current = true;
+ setIsFinalizing(true);
+ // Keep the session and dictation state alive while its final audio segment
+ // is transcribed. onEnd clears both after the transcript callbacks run.
+ void session.stop().catch((error) => {
+ console.error("Could not stop dictation:", error);
+ session.cancel();
+ if (sessionRef.current === session) sessionRef.current = null;
+ finalizingRef.current = false;
+ setIsFinalizing(false);
+ setIsDictating(false);
+ });
+ }, []);
useEffect(() => {
- disposedRef.current = false;
return () => {
- disposedRef.current = true;
- if (recognitionRef.current) {
- recognitionRef.current.abort();
- }
- streamRef.current?.getTracks().forEach((track) => track.stop());
- streamRef.current = null;
+ sessionRef.current?.cancel();
+ sessionRef.current = null;
};
}, []);
- const supported =
- typeof window !== "undefined" &&
- !!(
- window.SpeechRecognition ??
- (window as unknown as { webkitSpeechRecognition?: unknown })
- .webkitSpeechRecognition
- );
+ const supported = StudioDictationAdapter.isSupported(dictationEngine);
- return { isDictating, start, stop, supported };
+ return { isDictating, isFinalizing, start, stop, supported };
}
export type CompareHandles = MutableRefObject<Record<string, CompareHandle>>;
@@ -835,9 +753,9 @@ export function SharedComposer({
const {
isDictating,
+ isFinalizing: isDictationFinalizing,
start: startDictation,
stop: stopDictation,
- supported: dictationSupported,
} = useDictation(setText);
useEffect(() => {
@@ -1483,7 +1401,7 @@ export function SharedComposer({
}
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
- if (!busy) {
+ if (!busy && !isDictating) {
send();
}
}
@@ -1494,7 +1412,8 @@ export function SharedComposer({
pendingImages.length > 0 ||
pendingAudio !== null) &&
!busy &&
- !isComposing;
+ !isComposing &&
+ !isDictating;
// Adjustable "+" menu items, keyed by id. Pinned ones render at the top
// level; the rest fall into the "More" overflow submenu. Core items (photos,
@@ -2269,7 +2188,7 @@ export function SharedComposer({
</button>
)
) : null}
- {dictationSupported && (
+ {
<>
{!isDictating ? (
<TooltipIconButton
@@ -2285,19 +2204,27 @@ export function SharedComposer({
</TooltipIconButton>
) : (
<TooltipIconButton
- tooltip="Stop dictation"
+ tooltip={
+ isDictationFinalizing
+ ? "Cancel transcription"
+ : "Stop dictation"
+ }
side="bottom"
variant="ghost"
size="icon"
className="size-8 rounded-full text-destructive"
onClick={stopDictation}
- aria-label="Stop dictation"
+ aria-label={
+ isDictationFinalizing
+ ? "Cancel transcription"
+ : "Stop dictation"
+ }
>
<SquareIcon className="size-3 animate-pulse fill-current" />
</TooltipIconButton>
)}
</>
- )}
+ }
{isQueueRunning ? (
<button
type="button"
diff --git a/studio/frontend/src/features/hub/index.ts b/studio/frontend/src/features/hub/index.ts
index b464ddf0cff..7d9e5b74aa6 100644
--- a/studio/frontend/src/features/hub/index.ts
+++ b/studio/frontend/src/features/hub/index.ts
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
export {
+ DownloadProgressBar,
downloadManager,
jobKeyOf,
subscribeJobListeners,
diff --git a/studio/frontend/src/features/hub/lib/hidden-models.ts b/studio/frontend/src/features/hub/lib/hidden-models.ts
index ce63832f996..c5c72aea659 100644
--- a/studio/frontend/src/features/hub/lib/hidden-models.ts
+++ b/studio/frontend/src/features/hub/lib/hidden-models.ts
@@ -6,18 +6,36 @@ import { getInventoryVersion } from "../stores/inventory-events";
// Infra models hidden from browse/preview lists (Hub Discover, the chat model
// selector, and local on-device rows). Mirrors the backend
-// `utils.hidden_models`: the RAG embedding model and the llama.cpp validation
-// probe are not usable chat models. Server-confirmed cache rows are trusted
-// because the backend applies variant-aware filtering. Optimistic cache rows
-// still use these needles until the server confirms them. The dynamic matchers
-// fetched from `/api/hub/hidden-models` add the user's configured embedder as
-// exact repo ids and exact resolved paths, never substring needles. Per-repo
-// views are not filtered, so reinstall flows still show downloaded files.
+// `utils.hidden_models`: the RAG embedding model, STT dictation models, and the
+// llama.cpp validation probe are not usable chat models. Server-confirmed cache
+// rows are trusted because the backend applies variant-aware filtering.
+// Optimistic cache rows still use these needles until the server confirms them.
+// The dynamic matchers fetched from `/api/hub/hidden-models` add the user's
+// configured embedder as exact repo ids and exact resolved paths, never
+// substring needles. Per-repo views are not filtered, so reinstall flows still
+// show downloaded files.
const HIDDEN_NEEDLES = [
"bge-small-en-v1.5", // RAG embedder: unsloth/bge-small-en-v1.5[-GGUF]
"ggml-org/models", // llama.cpp validation probe repo
"stories260k.gguf", // probe filename (carries .gguf so it stays specific)
];
+const HIDDEN_STT_REPOS = new Set([
+ // Transformers safetensors repos and their whisper.cpp GGUF companions
+ // (unslothai/whisper-*-GGUF): STT-only, never chat models.
+ "unsloth/whisper-tiny",
+ "unsloth/whisper-base",
+ "unsloth/whisper-small",
+ "unsloth/whisper-large-v3-turbo",
+ "unsloth/whisper-large-v3",
+ "unslothai/whisper-tiny-gguf",
+ "unslothai/whisper-base-gguf",
+ "unslothai/whisper-small-gguf",
+ "unslothai/whisper-large-v3-turbo-gguf",
+ "unslothai/whisper-large-v3-gguf",
+]);
+const HIDDEN_STT_CACHE_NAMES = [...HIDDEN_STT_REPOS].map((repo) =>
+ repo.replace("/", "--"),
+);
let dynamicNeedles: readonly string[] = [];
let dynamicExactIds: readonly string[] = [];
@@ -81,7 +99,13 @@ export function isHiddenModelId(
return false;
}
const lower = v.toLowerCase();
+ const normalized = lower.trim().replace(/^\/+|\/+$/g, "");
+ const pathParts = lower.split(/[\\/]/);
return (
+ HIDDEN_STT_REPOS.has(normalized) ||
+ HIDDEN_STT_CACHE_NAMES.some((name) =>
+ pathParts.includes(`models--${name}`),
+ ) ||
HIDDEN_NEEDLES.some((needle) => lower.includes(needle)) ||
dynamicNeedles.some((needle) => lower.includes(needle)) ||
dynamicExactIds.includes(lower) ||
diff --git a/studio/frontend/src/features/settings/components/archived-chats-dialog.tsx b/studio/frontend/src/features/settings/components/archived-chats-dialog.tsx
index c4932ccc5b3..43b2900fbed 100644
--- a/studio/frontend/src/features/settings/components/archived-chats-dialog.tsx
+++ b/studio/frontend/src/features/settings/components/archived-chats-dialog.tsx
@@ -22,10 +22,14 @@ import {
import { toast } from "@/lib/toast";
import { ArchiveRestoreIcon, Delete02Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
+import { Button } from "@/components/ui/button";
import { useNavigate, useRouterState } from "@tanstack/react-router";
import { useState } from "react";
import { useSettingsDialogStore } from "../stores/settings-dialog-store";
+/** Archived chats shown per page; "Show more" reveals the next page. */
+const ARCHIVED_PAGE_SIZE = 20;
+
function formatCreatedAt(ms: number): string {
return new Date(ms).toLocaleDateString(undefined, {
year: "numeric",
@@ -54,6 +58,9 @@ export function ArchivedChatsView() {
const [confirmingDelete, setConfirmingDelete] = useState<SidebarItem | null>(
null,
);
+ // Pagination: the view remounts with its settings tab, so plain state
+ // restarts from the first page on each visit.
+ const [visibleCount, setVisibleCount] = useState(ARCHIVED_PAGE_SIZE);
// Open an archived chat: leave it archived, just navigate to it.
function openChat(item: SidebarItem) {
@@ -113,7 +120,7 @@ export function ArchivedChatsView() {
<span className="w-32 shrink-0">Date created</span>
<span className="w-16 shrink-0" />
</div>
- {archivedItems.map((item) => (
+ {archivedItems.slice(0, visibleCount).map((item) => (
<div
key={item.id}
className="group flex items-center gap-4 border-b border-border/40 px-1 py-2.5 text-sm last:border-0"
@@ -159,6 +166,19 @@ export function ArchivedChatsView() {
</span>
</div>
))}
+ {archivedItems.length > visibleCount ? (
+ <div className="flex justify-center pt-3">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() =>
+ setVisibleCount(visibleCount + ARCHIVED_PAGE_SIZE)
+ }
+ >
+ Show more ({archivedItems.length - visibleCount})
+ </Button>
+ </div>
+ ) : null}
</div>
)}
diff --git a/studio/frontend/src/features/settings/components/dictation-dictionary-view.tsx b/studio/frontend/src/features/settings/components/dictation-dictionary-view.tsx
new file mode 100644
index 00000000000..41b8b211563
--- /dev/null
+++ b/studio/frontend/src/features/settings/components/dictation-dictionary-view.tsx
@@ -0,0 +1,132 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { useT } from "@/i18n";
+import {
+ ArrowLeft01Icon,
+ Delete02Icon,
+ PlusSignIcon,
+} from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useState } from "react";
+import { useVoiceSettingsStore } from "../stores/voice-settings-store";
+
+// Full-page editor for the dictation dictionary. Kept on its own subpage so a
+// long list of entries does not crowd the main Voice settings.
+export function DictationDictionaryView({ onBack }: { onBack: () => void }) {
+ const t = useT();
+ const dictionary = useVoiceSettingsStore((s) => s.dictionary);
+ const addDictionaryEntry = useVoiceSettingsStore((s) => s.addDictionaryEntry);
+ const updateDictionaryEntry = useVoiceSettingsStore(
+ (s) => s.updateDictionaryEntry,
+ );
+ const commitDictionaryEntry = useVoiceSettingsStore(
+ (s) => s.commitDictionaryEntry,
+ );
+ const removeDictionaryEntry = useVoiceSettingsStore(
+ (s) => s.removeDictionaryEntry,
+ );
+ const [newEntry, setNewEntry] = useState("");
+
+ const handleAddEntry = () => {
+ const trimmed = newEntry.trim();
+ if (!trimmed) return;
+ addDictionaryEntry(trimmed);
+ setNewEntry("");
+ };
+
+ return (
+ <div className="flex flex-col gap-6">
+ <header className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={onBack}
+ aria-label={t("settings.voice.dictionary.backToVoice")}
+ className="inline-flex size-7 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <HugeiconsIcon icon={ArrowLeft01Icon} className="size-4" />
+ </button>
+ <h1 className="font-heading text-xl font-semibold">
+ {t("settings.voice.title")}
+ </h1>
+ </header>
+
+ <div className="flex flex-col gap-1">
+ <h2 className="text-sm font-semibold">
+ {t("settings.voice.dictionary.sectionTitle")}
+ </h2>
+ <p className="text-xs text-muted-foreground">
+ {t("settings.voice.dictionary.sectionDescription")}
+ </p>
+ </div>
+
+ <div className="flex flex-col">
+ {dictionary.map((entry, index) => (
+ <div
+ // biome-ignore lint/suspicious/noArrayIndexKey: entries are editable in place
+ key={index}
+ className="flex items-center gap-2 py-1.5"
+ >
+ <Input
+ value={entry}
+ onChange={(e) => updateDictionaryEntry(index, e.target.value)}
+ // Tabbing to this row's remove button must not commit-splice the
+ // row first, which shifts indices and deletes the wrong entry.
+ onBlur={(e) => {
+ if (
+ e.relatedTarget instanceof HTMLElement &&
+ e.relatedTarget.dataset.removeIndex === String(index)
+ ) {
+ return;
+ }
+ commitDictionaryEntry(index);
+ }}
+ className="h-8 flex-1 text-sm"
+ aria-label={`Dictionary entry ${index + 1}`}
+ />
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-8 shrink-0 text-muted-foreground hover:text-destructive"
+ data-remove-index={index}
+ // Keep the click from blurring an empty input first, which would
+ // commit-splice this row and make onClick delete the next one.
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={() => removeDictionaryEntry(index)}
+ aria-label={`Remove dictionary entry ${index + 1}`}
+ >
+ <HugeiconsIcon icon={Delete02Icon} className="size-3.5" />
+ </Button>
+ </div>
+ ))}
+ <div className="flex items-center gap-2 py-1.5">
+ <Input
+ value={newEntry}
+ onChange={(e) => setNewEntry(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ handleAddEntry();
+ }
+ }}
+ placeholder="Jane Doe"
+ className="h-8 flex-1 text-sm"
+ aria-label="New dictionary entry"
+ />
+ <Button
+ variant="outline"
+ size="sm"
+ className="shrink-0"
+ onClick={handleAddEntry}
+ disabled={!newEntry.trim()}
+ >
+ <HugeiconsIcon icon={PlusSignIcon} className="mr-1.5 size-3.5" />
+ {t("settings.voice.dictionary.addEntry")}
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/settings/components/recent-dictations-view.tsx b/studio/frontend/src/features/settings/components/recent-dictations-view.tsx
new file mode 100644
index 00000000000..f4c58818bd4
--- /dev/null
+++ b/studio/frontend/src/features/settings/components/recent-dictations-view.tsx
@@ -0,0 +1,515 @@
+// 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,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { Button } from "@/components/ui/button";
+import {
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+} from "@/components/ui/input-group";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import {
+ deleteChatItem,
+ useChatRuntimeStore,
+ type SidebarItem,
+} from "@/features/chat";
+import { useT } from "@/i18n";
+import { copyToClipboard } from "@/lib/copy-to-clipboard";
+import { toast } from "@/lib/toast";
+import {
+ ArrowLeft01Icon,
+ Copy01Icon,
+ Delete02Icon,
+ Message01Icon,
+ Search01Icon,
+ ViewIcon,
+} from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useNavigate } from "@tanstack/react-router";
+import { useMemo, useState } from "react";
+import {
+ type RecentDictation,
+ useVoiceSettingsStore,
+} from "../stores/voice-settings-store";
+import { useSettingsDialogStore } from "../stores/settings-dialog-store";
+
+/** Dictations shown per page; "Show more" reveals the next page. */
+const PAGE_SIZE = 20;
+
+type PendingDelete =
+ | { kind: "one"; dictation: RecentDictation }
+ | { kind: "all" }
+ | null;
+
+type SortOrder = "newest" | "oldest" | "az";
+
+function formatDictationDate(ms: number): string {
+ return new Date(ms).toLocaleString(undefined, {
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ });
+}
+
+export function RecentDictationsView({
+ selectedId,
+ onSelect,
+ onBack,
+}: {
+ selectedId: string | null;
+ onSelect: (id: string | null) => void;
+ onBack: () => void;
+}) {
+ const t = useT();
+ const recentDictations = useVoiceSettingsStore((s) => s.recentDictations);
+ const removeRecentDictation = useVoiceSettingsStore(
+ (s) => s.removeRecentDictation,
+ );
+ const clearRecentDictations = useVoiceSettingsStore(
+ (s) => s.clearRecentDictations,
+ );
+ const [pendingDelete, setPendingDelete] = useState<PendingDelete>(null);
+ const [search, setSearch] = useState("");
+ const [sortOrder, setSortOrder] = useState<SortOrder>("newest");
+ // Pagination is keyed to the search/sort inputs so changing either restarts
+ // from the first page without an effect.
+ const pageKey = `${sortOrder}::${search}`;
+ const [page, setPage] = useState({ key: pageKey, count: PAGE_SIZE });
+ const visibleCount = page.key === pageKey ? page.count : PAGE_SIZE;
+ const navigate = useNavigate();
+ const closeSettings = useSettingsDialogStore((s) => s.closeDialog);
+ const selected =
+ recentDictations.find((dictation) => dictation.id === selectedId) ?? null;
+
+ function openChat(chatId: string) {
+ closeSettings();
+ void navigate({ to: "/chat", search: { thread: chatId } });
+ }
+
+ const visible = useMemo(() => {
+ const query = search.trim().toLowerCase();
+ const filtered = query
+ ? recentDictations.filter((d) => d.text.toLowerCase().includes(query))
+ : recentDictations;
+ const sorted = [...filtered];
+ if (sortOrder === "oldest") {
+ sorted.sort((a, b) => a.at - b.at);
+ } else if (sortOrder === "az") {
+ sorted.sort((a, b) => a.text.localeCompare(b.text));
+ } else {
+ sorted.sort((a, b) => b.at - a.at);
+ }
+ return sorted;
+ }, [recentDictations, search, sortOrder]);
+
+ async function handleCopy(text: string) {
+ if (await copyToClipboard(text)) {
+ toast.success(t("settings.voice.recents.copied"));
+ } else {
+ toast.error(t("settings.voice.recents.copyFailed"));
+ }
+ }
+
+ function confirmDelete() {
+ try {
+ if (pendingDelete?.kind === "one") {
+ removeRecentDictation(pendingDelete.dictation.id);
+ if (pendingDelete.dictation.id === selectedId) {
+ onSelect(null);
+ }
+ } else if (pendingDelete?.kind === "all") {
+ clearRecentDictations();
+ onSelect(null);
+ }
+ } finally {
+ setPendingDelete(null);
+ }
+ }
+
+ // Delete a linked dictation together with the chat it was used in.
+ async function confirmDeleteWithChat() {
+ if (pendingDelete?.kind !== "one") {
+ return;
+ }
+ const dictation = pendingDelete.dictation;
+ setPendingDelete(null);
+ if (dictation.chatId) {
+ const item: SidebarItem = {
+ type: "single",
+ id: dictation.chatId,
+ title: "",
+ createdAt: 0,
+ updatedAt: 0,
+ };
+ try {
+ await deleteChatItem(
+ item,
+ useChatRuntimeStore.getState().activeThreadId ?? undefined,
+ () => {
+ // The deleted chat was open; leave the user on a fresh chat.
+ void navigate({
+ to: "/chat",
+ search: { new: crypto.randomUUID() },
+ });
+ },
+ );
+ } catch (error) {
+ toast.error(t("settings.voice.recents.deleteWithChatFailed"), {
+ description: error instanceof Error ? error.message : undefined,
+ });
+ return;
+ }
+ }
+ removeRecentDictation(dictation.id);
+ if (dictation.id === selectedId) {
+ onSelect(null);
+ }
+ }
+
+ return (
+ <div className="flex flex-col gap-6">
+ <header className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={() => (selected ? onSelect(null) : onBack())}
+ aria-label={
+ selected
+ ? t("settings.voice.recents.backToRecents")
+ : t("settings.voice.recents.backToVoice")
+ }
+ className="inline-flex size-7 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <HugeiconsIcon icon={ArrowLeft01Icon} className="size-4" />
+ </button>
+ <h1 className="font-heading text-xl font-semibold">
+ {t("settings.voice.title")}
+ </h1>
+ </header>
+
+ <div className="flex flex-col gap-1">
+ <h2 className="text-sm font-semibold">
+ {selected
+ ? t("settings.voice.recents.detailTitle")
+ : t("settings.voice.recents.sectionTitle")}
+ </h2>
+ <p className="text-xs text-muted-foreground">
+ {selected
+ ? formatDictationDate(selected.at)
+ : t("settings.voice.recents.pageDescription")}
+ </p>
+ </div>
+
+ {selected ? (
+ <div className="flex min-h-0 flex-col gap-4">
+ <article className="rounded-lg border border-border/60 bg-muted/20 p-4">
+ <p className="whitespace-pre-wrap break-words text-sm leading-relaxed text-foreground select-text">
+ {selected.text}
+ </p>
+ </article>
+ <div className="flex justify-end gap-2">
+ {selected.chatId ? (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => openChat(selected.chatId as string)}
+ >
+ <HugeiconsIcon
+ icon={Message01Icon}
+ className="mr-1.5 size-3.5"
+ />
+ {t("settings.voice.recents.openChat")}
+ </Button>
+ ) : null}
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={async () => {
+ await handleCopy(selected.text);
+ }}
+ >
+ <HugeiconsIcon icon={Copy01Icon} className="mr-1.5 size-3.5" />
+ {t("settings.voice.recents.copy")}
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() =>
+ setPendingDelete({ kind: "one", dictation: selected })
+ }
+ className="text-destructive hover:border-destructive/60 hover:text-destructive"
+ >
+ <HugeiconsIcon icon={Delete02Icon} className="mr-1.5 size-3.5" />
+ {t("settings.voice.recents.delete")}
+ </Button>
+ </div>
+ </div>
+ ) : recentDictations.length === 0 ? (
+ <p className="py-8 text-center text-sm text-muted-foreground">
+ {t("settings.voice.recents.empty")}
+ </p>
+ ) : (
+ <div className="flex flex-col gap-3">
+ <div className="flex items-center gap-2">
+ <InputGroup className="h-8 flex-1">
+ <InputGroupAddon align="inline-start">
+ <HugeiconsIcon
+ icon={Search01Icon}
+ strokeWidth={2}
+ className="size-3.5 text-muted-foreground"
+ />
+ </InputGroupAddon>
+ <InputGroupInput
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder={t("settings.voice.recents.searchPlaceholder")}
+ aria-label={t("settings.voice.recents.searchPlaceholder")}
+ className="text-sm"
+ />
+ </InputGroup>
+ <Select
+ value={sortOrder}
+ onValueChange={(value) => setSortOrder(value as SortOrder)}
+ >
+ <SelectTrigger
+ size="sm"
+ className="w-36 shrink-0"
+ aria-label={t("settings.voice.recents.sortLabel")}
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="newest">
+ {t("settings.voice.recents.sortNewest")}
+ </SelectItem>
+ <SelectItem value="oldest">
+ {t("settings.voice.recents.sortOldest")}
+ </SelectItem>
+ <SelectItem value="az">
+ {t("settings.voice.recents.sortAlpha")}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setPendingDelete({ kind: "all" })}
+ className="shrink-0 text-destructive hover:border-destructive/60 hover:text-destructive"
+ >
+ <HugeiconsIcon icon={Delete02Icon} className="mr-1.5 size-3.5" />
+ {t("settings.voice.recents.clear")}
+ </Button>
+ </div>
+
+ {visible.length === 0 ? (
+ <p className="py-8 text-center text-sm text-muted-foreground">
+ {t("settings.voice.recents.noMatches")}
+ </p>
+ ) : (
+ <div className="flex flex-col">
+ <div className="flex items-center gap-4 border-b border-border/60 px-1 pb-2 text-xs font-semibold text-foreground">
+ <span className="min-w-0 flex-1">
+ {t("settings.voice.recents.dictationColumn")}
+ </span>
+ <span className="hidden w-40 shrink-0 items-center gap-1.5 sm:flex">
+ {/* Spacer matching the row's chat-link icon slot so the
+ header starts exactly where the dates start. */}
+ <span className="size-3.5 shrink-0" />
+ {t("settings.voice.recents.dateColumn")}
+ </span>
+ <span className="w-24 shrink-0" />
+ </div>
+ {visible.slice(0, visibleCount).map((dictation) => (
+ <div
+ key={dictation.id}
+ className="group flex items-stretch gap-2 border-b border-border/40 last:border-0"
+ >
+ <button
+ type="button"
+ onClick={() =>
+ dictation.chatId
+ ? openChat(dictation.chatId)
+ : onSelect(dictation.id)
+ }
+ aria-label={
+ dictation.chatId
+ ? t("settings.voice.recents.openChat")
+ : t("settings.voice.recents.view")
+ }
+ className="flex min-w-0 flex-1 items-start gap-4 rounded-md px-1 py-3 text-left transition-colors hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <span className="min-w-0 flex-1">
+ <span className="line-clamp-3 whitespace-pre-wrap break-words text-sm text-foreground">
+ {dictation.text}
+ </span>
+ <span className="mt-1 flex items-center gap-1.5 text-xs text-muted-foreground sm:hidden">
+ {dictation.chatId ? (
+ <HugeiconsIcon
+ icon={Message01Icon}
+ className="size-3"
+ />
+ ) : null}
+ {formatDictationDate(dictation.at)}
+ </span>
+ </span>
+ <span className="hidden w-40 shrink-0 items-center gap-1.5 text-left text-xs text-muted-foreground tabular-nums sm:flex">
+ {/* Fixed icon slot keeps every date starting at the
+ same column whether or not a chat is linked. */}
+ <span className="flex size-3.5 shrink-0 items-center justify-center">
+ {dictation.chatId ? (
+ <HugeiconsIcon
+ icon={Message01Icon}
+ className="size-3.5"
+ aria-label={t("settings.voice.recents.openChat")}
+ />
+ ) : null}
+ </span>
+ <span className="whitespace-nowrap">
+ {formatDictationDate(dictation.at)}
+ </span>
+ </span>
+ </button>
+ <span className="flex w-24 shrink-0 items-center justify-end gap-1">
+ {dictation.chatId ? (
+ <button
+ type="button"
+ onClick={() => onSelect(dictation.id)}
+ aria-label={t("settings.voice.recents.view")}
+ title={t("settings.voice.recents.view")}
+ className="inline-flex size-7 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <HugeiconsIcon
+ icon={ViewIcon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ </button>
+ ) : null}
+ <button
+ type="button"
+ onClick={async () => {
+ await handleCopy(dictation.text);
+ }}
+ aria-label={t("settings.voice.recents.copy")}
+ title={t("settings.voice.recents.copy")}
+ className="inline-flex size-7 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <HugeiconsIcon
+ icon={Copy01Icon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ </button>
+ <button
+ type="button"
+ onClick={() =>
+ setPendingDelete({ kind: "one", dictation })
+ }
+ aria-label={t("settings.voice.recents.delete")}
+ title={t("settings.voice.recents.delete")}
+ className="inline-flex size-7 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <HugeiconsIcon
+ icon={Delete02Icon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ </button>
+ </span>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {visible.length > visibleCount ? (
+ <div className="flex justify-center pt-1">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() =>
+ setPage({ key: pageKey, count: visibleCount + PAGE_SIZE })
+ }
+ >
+ {t("settings.voice.recents.showMore", {
+ count: visible.length - visibleCount,
+ })}
+ </Button>
+ </div>
+ ) : null}
+ </div>
+ )}
+
+ <AlertDialog
+ open={pendingDelete !== null}
+ onOpenChange={(open) => {
+ if (!open) {
+ setPendingDelete(null);
+ }
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {pendingDelete?.kind === "all"
+ ? t("settings.voice.recents.clearTitle")
+ : t("settings.voice.recents.deleteTitle")}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {pendingDelete?.kind === "all"
+ ? t("settings.voice.recents.clearDescription")
+ : pendingDelete?.kind === "one" &&
+ pendingDelete.dictation.chatId
+ ? t("settings.voice.recents.deleteLinkedDescription")
+ : t("settings.voice.recents.deleteDescription")}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>
+ {pendingDelete?.kind === "one" && pendingDelete.dictation.chatId ? (
+ <AlertDialogAction
+ variant="outline"
+ className="text-destructive hover:border-destructive/60 hover:text-destructive"
+ onClick={(event) => {
+ // Close only through state so the dismissal can't race a
+ // click on whatever ends up under the pointer.
+ event.preventDefault();
+ void confirmDeleteWithChat();
+ }}
+ >
+ {t("settings.voice.recents.deleteWithChat")}
+ </AlertDialogAction>
+ ) : null}
+ <AlertDialogAction
+ variant="destructive"
+ onClick={(event) => {
+ event.preventDefault();
+ confirmDelete();
+ }}
+ >
+ {pendingDelete?.kind === "all"
+ ? t("settings.voice.recents.clearConfirm")
+ : t("common.delete")}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.ts
index 380909e6968..63b492878f3 100644
--- a/studio/frontend/src/features/settings/settings-search.ts
+++ b/studio/frontend/src/features/settings/settings-search.ts
@@ -108,7 +108,6 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {
"settings.voice.dictation.sectionTitle",
"settings.voice.dictation.microphoneLabel",
"settings.voice.dictation.languageLabel",
- "settings.voice.dictation.testLabel",
"settings.voice.dictionary.sectionTitle",
"settings.voice.recents.sectionTitle",
"settings.voice.readAloud.sectionTitle",
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 9e38f4c6ce9..5f71085981d 100644
--- a/studio/frontend/src/features/settings/stores/voice-settings-store.ts
+++ b/studio/frontend/src/features/settings/stores/voice-settings-store.ts
@@ -2,28 +2,118 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { create } from "zustand";
-import { persist } from "zustand/middleware";
+import { createJSONStorage, persist } from "zustand/middleware";
// Voice preferences in localStorage. Adapters read them at call time so
// changes apply without reloading the chat runtime.
export interface RecentDictation {
+ id: string;
text: string;
at: number;
+ /** Chat the dictation was spoken into, when one was open at the time. */
+ chatId?: string;
}
-const MAX_RECENT_DICTATIONS = 20;
+// Dictation history is kept in full; the list view paginates. QUOTA_TRIM_KEEP is
+// the emergency floor if localStorage runs out of room (see persist wrapper).
+const QUOTA_TRIM_KEEP = 200;
// Cap stored transcript length so a few long dictations cannot bloat the
// persisted blob and trip a synchronous localStorage quota error on save.
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}$/;
+
+export function isSttModelId(value: string): boolean {
+ const normalized = value.trim();
+ return (
+ (STT_MODELS as readonly string[]).includes(normalized) ||
+ HF_REPO_ID.test(normalized)
+ );
+}
+
+export function normalizeSttModel(value: unknown): SttModel {
+ if (typeof value !== "string") {
+ return DEFAULT_STT_MODEL;
+ }
+ const normalized = value.trim();
+ return isSttModelId(normalized) ? normalized : DEFAULT_STT_MODEL;
+}
+
+export function getSttModelRepo(model: SttModel): string {
+ return STT_MODEL_REPOS[model as DefaultSttModel] ?? normalizeSttModel(model);
+}
+
+// All curated models are multilingual. Custom `.en` checkpoints are treated as
+// English-only so a later language change falls back safely.
+export const ENGLISH_ONLY_STT_MODELS: ReadonlySet<SttModel> = new Set([]);
+
+/** Whether a model can honor the selected dictation language. */
+export function isSttModelLanguageCompatible(
+ model: SttModel,
+ language: string,
+): boolean {
+ const isEnglishOnly =
+ ENGLISH_ONLY_STT_MODELS.has(model) ||
+ getSttModelRepo(model).toLowerCase().endsWith(".en");
+ if (!isEnglishOnly) {
+ return true;
+ }
+ const normalized = language.trim().replaceAll("_", "-").toLowerCase();
+ // Auto sends no forced language, which English-only checkpoints accept.
+ return normalized === "auto" || normalized.split("-", 1)[0] === "en";
+}
+
+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
+ * Transformers.
+ */
+export function isCuratedSttModel(model: SttModel): boolean {
+ return (STT_MODELS as readonly string[]).includes(model.trim());
+}
+
export interface VoiceSettingsState {
/** Input device for dictation. "default" = system default microphone. */
micDeviceId: string;
setMicDeviceId: (value: string) => void;
+ /**
+ * "browser": Web Speech API. "model": local transcription; the model decides
+ * the backend (whisper.cpp for curated GGML, Transformers for custom repos).
+ */
+ dictationEngine: DictationEngine;
+ setDictationEngine: (value: DictationEngine) => void;
+
+ /** STT model to use when dictationEngine is "model". */
+ sttModel: SttModel;
+ setSttModel: (value: SttModel) => void;
+
/** BCP 47 tag for speech recognition, or "auto" for the browser locale. */
dictationLanguage: string;
setDictationLanguage: (value: string) => void;
@@ -38,7 +128,8 @@ export interface VoiceSettingsState {
/** Final transcripts, newest first, so text can be recovered. */
recentDictations: RecentDictation[];
- addRecentDictation: (text: string) => void;
+ addRecentDictation: (text: string, chatId?: string) => void;
+ removeRecentDictation: (id: string) => void;
clearRecentDictations: () => void;
/** Show the read-aloud button on assistant responses. */
@@ -61,14 +152,81 @@ export interface VoiceSettingsState {
setTtsVolume: (value: number) => void;
}
+/**
+ * localStorage wrapper that keeps the full dictation history until the browser's
+ * quota is hit, then drops the oldest entries instead of losing the whole save.
+ */
+const quotaSafeLocalStorage = {
+ getItem: (key: string) => localStorage.getItem(key),
+ removeItem: (key: string) => localStorage.removeItem(key),
+ setItem: (key: string, value: string) => {
+ try {
+ localStorage.setItem(key, value);
+ return;
+ } catch {
+ // Quota exceeded: trim dictation history, oldest first, and retry.
+ }
+ let parsed: { state?: { recentDictations?: RecentDictation[] } };
+ try {
+ parsed = JSON.parse(value) as typeof parsed;
+ } catch {
+ return;
+ }
+ const state = parsed.state;
+ const recents = state?.recentDictations;
+ if (!state || !Array.isArray(recents)) return;
+ // Halve the history until the save fits, down to an empty history, so even
+ // a small history shrinks when another store already consumed the quota.
+ let keep = Math.min(QUOTA_TRIM_KEEP, recents.length);
+ for (;;) {
+ keep = keep >= recents.length ? Math.floor(recents.length / 2) : keep;
+ try {
+ state.recentDictations = recents.slice(0, keep);
+ localStorage.setItem(key, JSON.stringify(parsed));
+ return;
+ } catch {
+ // Still over quota: trim harder.
+ }
+ if (keep === 0) return;
+ keep = Math.floor(keep / 2);
+ }
+ },
+};
+
export const useVoiceSettingsStore = create<VoiceSettingsState>()(
persist(
(set) => ({
micDeviceId: "default",
setMicDeviceId: (micDeviceId) => set({ micDeviceId }),
+ dictationEngine: "browser",
+ setDictationEngine: (dictationEngine) => set({ dictationEngine }),
+
+ sttModel: DEFAULT_STT_MODEL,
+ setSttModel: (value) =>
+ set((state) => {
+ const sttModel = normalizeSttModel(value);
+ return {
+ sttModel: isSttModelLanguageCompatible(
+ sttModel,
+ state.dictationLanguage,
+ )
+ ? sttModel
+ : DEFAULT_STT_MODEL,
+ };
+ }),
+
dictationLanguage: "auto",
- setDictationLanguage: (dictationLanguage) => set({ dictationLanguage }),
+ setDictationLanguage: (dictationLanguage) =>
+ set((state) => ({
+ dictationLanguage,
+ sttModel: isSttModelLanguageCompatible(
+ state.sttModel,
+ dictationLanguage,
+ )
+ ? state.sttModel
+ : DEFAULT_STT_MODEL,
+ })),
dictionary: [],
addDictionaryEntry: (value) =>
@@ -111,17 +269,31 @@ export const useVoiceSettingsStore = create<VoiceSettingsState>()(
})),
recentDictations: [],
- addRecentDictation: (text) =>
+ addRecentDictation: (text, chatId) =>
set((state) => {
const trimmed = text.trim().slice(0, MAX_RECENT_DICTATION_LENGTH);
- if (!trimmed) return state;
+ if (!trimmed) {
+ return state;
+ }
+ const at = Date.now();
return {
recentDictations: [
- { text: trimmed, at: Date.now() },
+ {
+ id: `${at}-${Math.random().toString(36).slice(2, 10)}`,
+ text: trimmed,
+ at,
+ ...(chatId ? { chatId } : {}),
+ },
...state.recentDictations,
- ].slice(0, MAX_RECENT_DICTATIONS),
+ ],
};
}),
+ removeRecentDictation: (id) =>
+ set((state) => ({
+ recentDictations: state.recentDictations.filter(
+ (dictation) => dictation.id !== id,
+ ),
+ })),
clearRecentDictations: () => set({ recentDictations: [] }),
ttsEnabled: true,
@@ -142,30 +314,37 @@ export const useVoiceSettingsStore = create<VoiceSettingsState>()(
}),
{
name: "unsloth_voice_settings",
+ storage: createJSONStorage(() => quotaSafeLocalStorage),
merge: (persisted, current) => {
const saved = persisted as Partial<VoiceSettingsState> | undefined;
+ const dictationLanguage = asString(saved?.dictationLanguage, "auto");
+ // "gguf" was a short-lived separate engine choice; both local
+ // backends now live under "model".
+ const savedEngine = saved?.dictationEngine as string | undefined;
+ const dictationEngine: DictationEngine =
+ savedEngine === "model" || savedEngine === "gguf"
+ ? "model"
+ : "browser";
+ const savedSttModel = normalizeSttModel(saved?.sttModel);
+ const sttModel = isSttModelLanguageCompatible(
+ savedSttModel,
+ dictationLanguage,
+ )
+ ? savedSttModel
+ : DEFAULT_STT_MODEL;
return {
...current,
micDeviceId: asString(saved?.micDeviceId, "default"),
- dictationLanguage: asString(saved?.dictationLanguage, "auto"),
+ dictationEngine,
+ sttModel,
+ dictationLanguage,
dictionary: Array.isArray(saved?.dictionary)
? saved.dictionary
.filter((v): v is string => typeof v === "string" && !!v.trim())
.map((v) => v.trim().slice(0, MAX_DICTIONARY_ENTRY_LENGTH))
.slice(0, MAX_DICTIONARY_ENTRIES)
: [],
- recentDictations: Array.isArray(saved?.recentDictations)
- ? saved.recentDictations
- .filter(
- (v): v is RecentDictation =>
- typeof v?.text === "string" && typeof v?.at === "number",
- )
- .slice(0, MAX_RECENT_DICTATIONS)
- .map((v) => ({
- text: v.text.slice(0, MAX_RECENT_DICTATION_LENGTH),
- at: v.at,
- }))
- : [],
+ recentDictations: normalizeRecentDictations(saved?.recentDictations),
ttsEnabled:
typeof saved?.ttsEnabled === "boolean" ? saved.ttsEnabled : true,
ttsEngine: saved?.ttsEngine === "studio" ? "studio" : "system",
@@ -183,6 +362,40 @@ function asString(value: unknown, fallback: string): string {
return typeof value === "string" && value ? value : fallback;
}
+function normalizeRecentDictations(value: unknown): RecentDictation[] {
+ if (!Array.isArray(value)) {
+ return [];
+ }
+
+ const normalized: RecentDictation[] = [];
+ for (const [index, entry] of value.entries()) {
+ if (!entry || typeof entry !== "object") {
+ continue;
+ }
+ const candidate = entry as Partial<RecentDictation>;
+ if (
+ typeof candidate.text !== "string" ||
+ !candidate.text.trim() ||
+ typeof candidate.at !== "number" ||
+ !Number.isFinite(candidate.at)
+ ) {
+ continue;
+ }
+ normalized.push({
+ id:
+ typeof candidate.id === "string" && candidate.id
+ ? candidate.id
+ : `legacy-${candidate.at}-${index}`,
+ text: candidate.text.trim().slice(0, MAX_RECENT_DICTATION_LENGTH),
+ at: candidate.at,
+ ...(typeof candidate.chatId === "string" && candidate.chatId
+ ? { chatId: candidate.chatId }
+ : {}),
+ });
+ }
+ return normalized;
+}
+
function clampNumber(
value: unknown,
min: number,
@@ -202,6 +415,47 @@ export function resolveDictationLanguage(setting?: string): string {
: "en-US";
}
+// Whisper's language codes: transformers `LANGUAGES` keys plus the backend's
+// BCP-47 aliases (stt_sidecar.py `_WHISPER_LANGUAGE_ALIASES`). Keep in sync with
+// `_known_whisper_languages()`; Auto only resolves to a code in this set, so a
+// UI locale Whisper cannot honor stays on auto-detect.
+const WHISPER_DICTATION_LANGUAGES = new Set([
+ "af", "am", "ar", "as", "az", "ba", "be", "bg", "bn", "bo", "br", "bs",
+ "ca", "cmn", "cs", "cy", "da", "de", "el", "en", "es", "et", "eu", "fa",
+ "fi", "fil", "fo", "fr", "gl", "gu", "ha", "haw", "he", "hi", "hr", "ht",
+ "hu", "hy", "id", "in", "is", "it", "iw", "ja", "ji", "jw", "ka", "kk",
+ "km", "kn", "ko", "la", "lb", "ln", "lo", "lt", "lv", "mg", "mi", "mk",
+ "ml", "mn", "mr", "ms", "mt", "my", "nb", "ne", "nl", "nn", "no", "oc",
+ "pa", "pl", "ps", "pt", "ro", "ru", "sa", "sd", "si", "sk", "sl", "sn",
+ "so", "sq", "sr", "su", "sv", "sw", "ta", "te", "tg", "th", "tk", "tl",
+ "tr", "tt", "uk", "ur", "uz", "vi", "yi", "yo", "yue", "zh",
+]);
+
+/**
+ * Resolve Auto for the model STT engine (the browser engine resolves it via
+ * `resolveDictationLanguage`). Only the literal "auto" resolves to a concrete
+ * locale; an explicit or malformed setting passes through unchanged. Gated so
+ * Auto only becomes a language the model AND Whisper can honor, else it stays
+ * auto-detect rather than forcing a locale Whisper cannot handle (e.g. Irish)
+ * or 422ing every dictation.
+ */
+export function resolveModelDictationLanguage(
+ model: SttModel,
+ requested: string,
+): string {
+ if (requested !== "auto") return requested;
+ const resolved = resolveDictationLanguage(requested);
+ const primary = resolved
+ .trim()
+ .replaceAll("_", "-")
+ .toLowerCase()
+ .split("-", 1)[0];
+ return isSttModelLanguageCompatible(model, resolved) &&
+ WHISPER_DICTATION_LANGUAGES.has(primary)
+ ? resolved
+ : requested;
+}
+
function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
@@ -240,6 +494,6 @@ export function applyDictationDictionary(
}
/** Record a finished dictation so it can be recovered from settings. */
-export function recordRecentDictation(text: string): void {
- useVoiceSettingsStore.getState().addRecentDictation(text);
+export function recordRecentDictation(text: string, chatId?: string): void {
+ useVoiceSettingsStore.getState().addRecentDictation(text, chatId);
}
diff --git a/studio/frontend/src/features/settings/tabs/voice-tab.tsx b/studio/frontend/src/features/settings/tabs/voice-tab.tsx
index a223b680fdb..59c03bdf143 100644
--- a/studio/frontend/src/features/settings/tabs/voice-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/voice-tab.tsx
@@ -3,6 +3,11 @@
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
import {
Select,
SelectContent,
@@ -11,41 +16,52 @@ import {
SelectValue,
} from "@/components/ui/select";
import { Slider } from "@/components/ui/slider";
+import { Spinner } from "@/components/ui/spinner";
import { Switch } from "@/components/ui/switch";
import {
+ StudioModelDictationAdapter,
+ type SttDownloadStatus,
+ fetchSttStatus,
+ loadSttModel,
+ startSttDownload,
+ unloadSttModel,
+ validateSttModel,
StudioSpeechSynthesisAdapter,
createConfiguredUtterance,
curateSystemVoices,
generateStudioTtsAudio,
-} from "@/features/chat/adapters/studio-speech-synthesis-adapter";
+} from "@/features/chat";
import {
- StudioWebSpeechDictationAdapter,
- describeSpeechError,
- isMissingDeviceError,
-} from "@/features/chat/adapters/studio-web-speech-dictation-adapter";
+ DownloadProgressBar,
+ hfApiToken,
+ useHfTokenStore,
+ useHubModelSearch,
+} from "@/features/hub";
+import { useDebouncedValue, useWheelScrollRef } from "@/hooks";
import { useT } from "@/i18n";
-import { toast } from "@/lib/toast";
+import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
import { MicIcon } from "@/lib/mic-icon";
-import { copyToClipboard } from "@/lib/copy-to-clipboard";
-import {
- Copy01Icon,
- Delete02Icon,
- PlusSignIcon,
- VolumeHighIcon,
-} from "@hugeicons/core-free-icons";
+import { toast } from "@/lib/toast";
+import { Search01Icon, VolumeHighIcon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { SquareIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { DictationDictionaryView } from "../components/dictation-dictionary-view";
+import { RecentDictationsView } from "../components/recent-dictations-view";
import { SettingsRow } from "../components/settings-row";
import { SettingsSection } from "../components/settings-section";
import {
- applyDictationDictionary,
- recordRecentDictation,
- resolveDictationLanguage,
+ type DefaultSttModel,
+ STT_MODELS,
+ type SttModel,
+ getSttModelRepo,
+ isCuratedSttModel,
+ isSttModelId,
+ isSttModelLanguageCompatible,
useVoiceSettingsStore,
} from "../stores/voice-settings-store";
-// Languages offered for browser speech recognition.
+// Languages shared by browser speech recognition and local STT.
const DICTATION_LANGUAGES: { value: string; label: string }[] = [
{ value: "auto", label: "" }, // label rendered via i18n
{ value: "en-US", label: "English (US)" },
@@ -63,6 +79,225 @@ const DICTATION_LANGUAGES: { value: string; label: string }[] = [
{ value: "ar-SA", label: "العربية" },
];
+// 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)
+ ? `unslothai/whisper-${model}-GGUF`
+ : getSttModelRepo(model);
+}
+
+/**
+ * Model picker for local transcription. Lists the curated whisper.cpp
+ * checkpoints and searches Hugging Face for other Whisper repos (safetensors via
+ * Transformers). The trigger is a plain button so the selection never renders
+ * inside a text input.
+ */
+function SttModelPicker({
+ value,
+ language,
+ onChange,
+}: {
+ value: SttModel;
+ language: string;
+ onChange: (model: SttModel) => void;
+}) {
+ const t = useT();
+ const hfToken = useHfTokenStore((state) => state.token);
+ const [open, setOpen] = useState(false);
+ const [query, setQuery] = useState("");
+ const [validating, setValidating] = useState(false);
+ const resultsRef = useWheelScrollRef<HTMLDivElement>();
+ const debouncedQuery = useDebouncedValue(query.trim());
+
+ const { results, isLoading } = useHubModelSearch(debouncedQuery, {
+ task: "automatic-speech-recognition",
+ accessToken: hfApiToken(hfToken),
+ excludeGguf: true,
+ enabled: debouncedQuery.length >= 2,
+ keepUnsupportedTags: true,
+ ownerScope: "all",
+ });
+
+ const items = useMemo(() => {
+ if (!debouncedQuery) {
+ const defaults: string[] = STT_MODELS.filter((model) =>
+ isSttModelLanguageCompatible(model, language),
+ );
+ if (!defaults.includes(value)) {
+ defaults.push(value);
+ }
+ return defaults;
+ }
+ const ids: string[] = [];
+ for (const result of results) {
+ const tags = result.tags?.map((tag) => tag.toLowerCase()) ?? [];
+ const isWhisper =
+ result.id.toLowerCase().includes("whisper") || tags.includes("whisper");
+ const isExactMatch =
+ result.id.toLowerCase() === debouncedQuery.toLowerCase();
+ if (
+ (isExactMatch ||
+ (isWhisper &&
+ result.pipelineTag === "automatic-speech-recognition")) &&
+ isSttModelLanguageCompatible(result.id, language) &&
+ !ids.includes(result.id)
+ ) {
+ ids.push(result.id);
+ }
+ }
+ return ids;
+ }, [debouncedQuery, language, results, value]);
+
+ const selectModel = async (model: string) => {
+ if (!isSttModelId(model) || validating) {
+ return;
+ }
+ if (!isCuratedSttModel(model)) {
+ setValidating(true);
+ try {
+ await validateSttModel(model, hfApiToken(hfToken));
+ } catch (error) {
+ toast.error(t("settings.voice.dictation.sttModelInvalid"), {
+ description: error instanceof Error ? error.message : undefined,
+ });
+ return;
+ } finally {
+ setValidating(false);
+ }
+ }
+ onChange(model);
+ setOpen(false);
+ setQuery("");
+ };
+
+ return (
+ <Popover
+ open={open}
+ onOpenChange={(next) => {
+ setOpen(next);
+ if (!next) setQuery("");
+ }}
+ >
+ <PopoverTrigger asChild={true}>
+ <button
+ type="button"
+ aria-label="Speech recognition model"
+ className="border-border bg-background hover:bg-accent/50 dark:border-transparent dark:bg-white/[0.06] dark:hover:bg-white/10 focus-visible:border-ring flex h-8 w-full cursor-pointer items-center justify-between gap-1.5 rounded-full border px-3.5 text-sm outline-none transition-colors"
+ >
+ <span className="truncate">{sttModelName(value)}</span>
+ <HugeiconsIcon
+ icon={ChevronDownStandardIcon}
+ strokeWidth={2}
+ className="text-muted-foreground pointer-events-none size-4 shrink-0"
+ />
+ </button>
+ </PopoverTrigger>
+ <PopoverContent align="start" sideOffset={4} className="w-72 gap-0 p-0">
+ <div className="relative p-1.5 pb-0.5">
+ <HugeiconsIcon
+ icon={Search01Icon}
+ strokeWidth={2}
+ className="text-muted-foreground pointer-events-none absolute top-[calc(50%+2px)] left-4 size-3.5 -translate-y-1/2"
+ />
+ <Input
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ placeholder={t(
+ "settings.voice.dictation.sttModelSearchPlaceholder",
+ )}
+ className="h-8 pl-8 text-sm"
+ autoFocus={true}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" && items.length > 0) {
+ event.preventDefault();
+ void selectModel(items[0]);
+ }
+ }}
+ />
+ </div>
+ <div
+ ref={resultsRef}
+ data-testid="stt-model-results"
+ className="max-h-64 overflow-y-auto p-1"
+ >
+ {(isLoading && debouncedQuery) || validating ? (
+ <div className="flex items-center gap-2 px-3 py-3 text-xs text-muted-foreground">
+ <Spinner className="size-3.5" />
+ {validating
+ ? t("settings.voice.dictation.sttModelValidating")
+ : t("settings.voice.dictation.sttModelSearching")}
+ </div>
+ ) : items.length === 0 ? (
+ <div className="px-3 py-3 text-xs text-muted-foreground">
+ {t("settings.voice.dictation.sttModelNoResults")}
+ </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.
+ const twoLines = sttModelSource(model) !== sttModelName(model);
+ return (
+ <button
+ key={model}
+ type="button"
+ 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"
+ } ${model === value ? "bg-accent font-medium" : ""}`}
+ >
+ <span className="min-w-0 flex-1 truncate">
+ <span className="block truncate text-xs">
+ {sttModelName(model)}
+ </span>
+ {twoLines ? (
+ <span className="mt-0.5 block truncate font-mono text-[9px] leading-tight text-muted-foreground">
+ {sttModelSource(model)}
+ </span>
+ ) : null}
+ </span>
+ {sttModelSize(model) ? (
+ <span className="shrink-0 text-[10px] tabular-nums text-muted-foreground">
+ {sttModelSize(model)}
+ </span>
+ ) : null}
+ </button>
+ );
+ })
+ )}
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
+
const TTS_PREVIEW_TEXT =
"Hello from Unsloth Studio! This is a preview of the selected voice.";
@@ -84,11 +319,29 @@ function useAudioInputDevices() {
}, []);
useEffect(() => {
- void refresh();
const media = navigator.mediaDevices;
- if (!media?.addEventListener) return;
+ if (!media?.addEventListener) {
+ return;
+ }
+ let cancelled = false;
+ media
+ .enumerateDevices()
+ .then((all) => {
+ if (cancelled) {
+ return;
+ }
+ const inputs = all.filter((device) => device.kind === "audioinput");
+ setDevices(inputs);
+ setHasLabels(inputs.some((device) => device.label));
+ })
+ .catch(() => {
+ // Enumeration can fail in insecure contexts; leave the list empty.
+ });
media.addEventListener("devicechange", refresh);
- return () => media.removeEventListener("devicechange", refresh);
+ return () => {
+ cancelled = true;
+ media.removeEventListener("devicechange", refresh);
+ };
}, [refresh]);
// Labels are hidden until mic permission; open a short stream to get them.
@@ -102,7 +355,9 @@ function useAudioInputDevices() {
const stream = await navigator.mediaDevices.getUserMedia({
audio: true,
});
- stream.getTracks().forEach((track) => track.stop());
+ for (const track of stream.getTracks()) {
+ track.stop();
+ }
await refresh();
} catch {
toast.error(t("settings.voice.dictation.micAccessBlocked"));
@@ -127,234 +382,18 @@ function useSystemVoices() {
return voices;
}
-/** Inline mic test: runs speech recognition and shows the live transcript. */
-function DictationTest() {
- const t = useT();
- const [testing, setTesting] = useState(false);
- const [transcript, setTranscript] = useState("");
- const [interim, setInterim] = useState("");
- const recognitionRef = useRef<SpeechRecognition | null>(null);
- const streamRef = useRef<MediaStream | null>(null);
- // Guards the getUserMedia await so a mic opened after unmount is released.
- const disposedRef = useRef(false);
- // Mirrors the transcript state so onend can record it without stale closures.
- const transcriptRef = useRef("");
-
- // Single cleanup path: the browser can end recognition on its own (silence
- // timeout, service disconnect), so onend must release the mic and save the
- // transcript, not just the Stop button.
- const finalize = useCallback(() => {
- streamRef.current?.getTracks().forEach((track) => track.stop());
- streamRef.current = null;
- recognitionRef.current = null;
- if (transcriptRef.current) {
- recordRecentDictation(transcriptRef.current);
- transcriptRef.current = "";
- }
- setTesting(false);
- setInterim("");
- }, []);
-
- const stop = useCallback(() => {
- const recognition = recognitionRef.current;
- if (recognition) {
- // onend fires next and runs finalize()
- recognition.stop();
- } else {
- finalize();
- }
- }, [finalize]);
-
- useEffect(() => {
- disposedRef.current = false;
- return () => {
- disposedRef.current = true;
- recognitionRef.current?.abort();
- streamRef.current?.getTracks().forEach((track) => track.stop());
- streamRef.current = null;
- };
- }, []);
-
- // Set before the getUserMedia await so a double click or a slow
- // permission prompt cannot start a second recognizer over the first.
- const startingRef = useRef(false);
-
- const start = useCallback(async () => {
- const SpeechRecognitionAPI =
- window.SpeechRecognition ?? window.webkitSpeechRecognition;
- if (!SpeechRecognitionAPI) return;
- if (startingRef.current || recognitionRef.current) return;
- startingRef.current = true;
- setTranscript("");
- setInterim("");
- transcriptRef.current = "";
-
- const { micDeviceId } = useVoiceSettingsStore.getState();
- let audioTrack: MediaStreamTrack | undefined;
- try {
- let stream: MediaStream;
- try {
- stream = await navigator.mediaDevices.getUserMedia({
- audio:
- micDeviceId && micDeviceId !== "default"
- ? { deviceId: { exact: micDeviceId } }
- : true,
- });
- } catch (error) {
- // Saved mic may be unplugged; fall back to the default device.
- if (micDeviceId !== "default" && isMissingDeviceError(error)) {
- stream = await navigator.mediaDevices.getUserMedia({ audio: true });
- } else {
- throw error;
- }
- }
- if (disposedRef.current) {
- stream.getTracks().forEach((track) => track.stop());
- startingRef.current = false;
- return;
- }
- streamRef.current = stream;
- audioTrack = stream.getAudioTracks()[0];
- } catch {
- startingRef.current = false;
- toast.error(t("settings.voice.dictation.micOpenFailed"));
- return;
- }
-
- const recognition = new SpeechRecognitionAPI();
- recognition.lang = resolveDictationLanguage();
- recognition.continuous = true;
- recognition.interimResults = true;
- recognition.onresult = (event: SpeechRecognitionEvent) => {
- let interimText = "";
- for (let i = event.resultIndex; i < event.results.length; i++) {
- const result = event.results[i];
- const text = result?.[0]?.transcript ?? "";
- if (result?.isFinal) {
- const corrected = applyDictationDictionary(text.trim());
- setTranscript((prev) => {
- const next = prev ? `${prev} ${corrected}` : corrected;
- transcriptRef.current = next;
- return next;
- });
- } else {
- interimText += text;
- }
- }
- setInterim(interimText);
- };
- recognition.onerror = (event) => {
- // onend follows and runs finalize(); surface non-abort failures here.
- const errorEvent = event as SpeechRecognitionErrorEvent;
- if (errorEvent.error !== "aborted") {
- toast.error(describeSpeechError(errorEvent.error, errorEvent.message));
- }
- };
- recognition.onend = () => finalize();
- try {
- if (audioTrack) {
- try {
- recognition.start(audioTrack);
- } catch {
- // Engine has no start(track) overload: it will capture from the
- // default device, so release the selected-device stream.
- streamRef.current?.getTracks().forEach((track) => track.stop());
- streamRef.current = null;
- recognition.start();
- }
- } else {
- recognition.start();
- }
- } catch {
- startingRef.current = false;
- finalize();
- return;
- }
- recognitionRef.current = recognition;
- startingRef.current = false;
- setTesting(true);
- }, [finalize, t]);
-
- const finishedTest = !testing && transcript;
-
- return (
- <div className="flex flex-col gap-2">
- <SettingsRow
- label={t("settings.voice.dictation.testLabel")}
- description={t("settings.voice.dictation.testDescription")}
- >
- <Button
- variant="outline"
- size="sm"
- onClick={() => {
- if (testing) {
- stop();
- } else {
- void start();
- }
- }}
- >
- {testing ? (
- <>
- <SquareIcon className="mr-1.5 size-3 animate-pulse fill-current text-destructive" />
- {t("settings.voice.dictation.stopTest")}
- </>
- ) : (
- <>
- <MicIcon className="mr-1.5 size-3.5" />
- {t("settings.voice.dictation.startTest")}
- </>
- )}
- </Button>
- </SettingsRow>
- {(testing || transcript) && (
- <div className="rounded-lg border border-border/60 bg-muted/30 px-3 py-2 text-sm">
- {transcript || interim ? (
- <>
- <span className="text-foreground">{transcript}</span>
- {interim ? (
- <span className="text-muted-foreground"> {interim}</span>
- ) : null}
- </>
- ) : (
- <span className="text-muted-foreground">
- {testing ? t("settings.voice.dictation.listening") : ""}
- </span>
- )}
- {finishedTest ? (
- <div className="mt-1 text-xs text-muted-foreground">
- {t("settings.voice.dictation.testSaved")}
- </div>
- ) : null}
- </div>
- )}
- </div>
- );
-}
-
export function VoiceTab() {
const t = useT();
const micDeviceId = useVoiceSettingsStore((s) => s.micDeviceId);
const setMicDeviceId = useVoiceSettingsStore((s) => s.setMicDeviceId);
+ const dictationEngine = useVoiceSettingsStore((s) => s.dictationEngine);
+ const setDictationEngine = useVoiceSettingsStore((s) => s.setDictationEngine);
+ const sttModel = useVoiceSettingsStore((s) => s.sttModel);
+ const setSttModel = useVoiceSettingsStore((s) => s.setSttModel);
const dictationLanguage = useVoiceSettingsStore((s) => s.dictationLanguage);
const setDictationLanguage = useVoiceSettingsStore(
(s) => s.setDictationLanguage,
);
- const dictionary = useVoiceSettingsStore((s) => s.dictionary);
- const addDictionaryEntry = useVoiceSettingsStore((s) => s.addDictionaryEntry);
- const updateDictionaryEntry = useVoiceSettingsStore(
- (s) => s.updateDictionaryEntry,
- );
- const commitDictionaryEntry = useVoiceSettingsStore(
- (s) => s.commitDictionaryEntry,
- );
- const removeDictionaryEntry = useVoiceSettingsStore(
- (s) => s.removeDictionaryEntry,
- );
- const recentDictations = useVoiceSettingsStore((s) => s.recentDictations);
- const clearRecentDictations = useVoiceSettingsStore(
- (s) => s.clearRecentDictations,
- );
const ttsEnabled = useVoiceSettingsStore((s) => s.ttsEnabled);
const setTtsEnabled = useVoiceSettingsStore((s) => s.setTtsEnabled);
const ttsEngine = useVoiceSettingsStore((s) => s.ttsEngine);
@@ -371,29 +410,288 @@ export function VoiceTab() {
const { devices, hasLabels, requestAccess } = useAudioInputDevices();
const rawVoices = useSystemVoices();
const voices = useMemo(
- () => curateSystemVoices(rawVoices, ttsVoiceURI),
- // dictationLanguage feeds the curation language filter.
+ () => curateSystemVoices(rawVoices, ttsVoiceURI, dictationLanguage),
[rawVoices, ttsVoiceURI, dictationLanguage],
);
- const [newEntry, setNewEntry] = useState("");
const [previewing, setPreviewing] = useState(false);
+ const [subpage, setSubpage] = useState<"main" | "recents" | "dictionary">(
+ "main",
+ );
+ const [selectedDictationId, setSelectedDictationId] = useState<string | null>(
+ null,
+ );
- const dictationSupported = StudioWebSpeechDictationAdapter.isSupported();
+ const modelSttSupported = StudioModelDictationAdapter.isSupported();
const ttsSupported = StudioSpeechSynthesisAdapter.isSupported();
const systemTtsSupported =
StudioSpeechSynthesisAdapter.systemVoicesSupported();
const effectiveTtsEngine = systemTtsSupported ? ttsEngine : "studio";
- // Keep an item for an unplugged saved mic so the value stays visible.
- const knownMic = devices.some((d) => d.deviceId === micDeviceId);
+ // Local STT stays on-demand. Track its phase without fetching model weights.
+ type SttPhase =
+ | "idle"
+ | "checking"
+ | "on-demand"
+ | "unavailable"
+ | "loading"
+ | "ready"
+ | "error";
+ type SttDownloadAvailability =
+ | "checking"
+ | "missing"
+ | "downloaded"
+ | "error";
+ const [sttPhase, setSttPhase] = useState<SttPhase>("idle");
+ const [sttDevice, setSttDevice] = useState<string | null>(null);
+ const [statusNonce, setStatusNonce] = useState(0);
+ const [sttDownloadStarting, setSttDownloadStarting] = 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);
+ // Progress of the selected engine's model download, from /stt/status.
+ const [sttDownload, setSttDownload] = useState<SttDownloadStatus | null>(
+ null,
+ );
+ const [downloadBytesPerSec, setDownloadBytesPerSec] = useState(0);
+ // Last observed (bytes, time) so successive polls yield a transfer rate.
+ const downloadRateSampleRef = useRef<{ bytes: number; at: number } | null>(
+ null,
+ );
+ // Model whose download this tab watched; completion auto-loads it.
+ const watchedDownloadRef = useRef<string | null>(null);
- const handleAddEntry = () => {
- const trimmed = newEntry.trim();
- if (!trimmed) return;
- addDictionaryEntry(trimmed);
- setNewEntry("");
+ // Selecting a model (or finishing its download) loads it without a Load
+ // click. A model that is not downloaded fails quietly and stays on demand.
+ const autoLoadSttModel = useCallback(async (model: string) => {
+ setSttPhase("loading");
+ try {
+ await loadSttModel(model);
+ } catch {
+ // Not downloaded (or the engine is busy): the status poll resets the phase
+ // and the user still sees the Download button.
+ } finally {
+ setStatusNonce((nonce) => nonce + 1);
+ }
+ }, []);
+ const sttRepoId = getSttModelRepo(sttModel);
+ const hfToken = useHfTokenStore((state) => state.token);
+ const [sttDownloadAvailability, setSttDownloadAvailability] = useState<{
+ repoId: string;
+ state: SttDownloadAvailability;
+ }>({ repoId: "", state: "checking" });
+ const effectiveSttDownloadAvailability =
+ sttDownloadAvailability.repoId === sttRepoId
+ ? sttDownloadAvailability.state
+ : "checking";
+ useEffect(() => {
+ if (!isLocalEngine || !modelSttSupported) {
+ return;
+ }
+ let cancelled = false;
+ void (async () => {
+ // Only surface "checking" on the first poll; background refreshes keep
+ // the last phase so the status line doesn't flicker while polling.
+ setSttPhase((phase) => (phase === "idle" ? "checking" : phase));
+ try {
+ const status = await fetchSttStatus(statusNonce, sttModel);
+ if (cancelled) return;
+ // A curated model prefers the GGUF (whisper.cpp) engine, but without
+ // 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
+ ? status.gguf
+ : status.transformers;
+ if (!engineStatus?.available) {
+ setSttPhase("unavailable");
+ return;
+ }
+ const download = engineStatus.download;
+ setSttDownload(download);
+ setSttDownloadAvailability({
+ repoId: sttRepoId,
+ state: engineStatus.downloaded_models.includes(sttModel)
+ ? "downloaded"
+ : download.error
+ ? "error"
+ : "missing",
+ });
+ if (download.downloading) {
+ watchedDownloadRef.current = download.model;
+ const bytes = download.bytes_done ?? 0;
+ const sample = downloadRateSampleRef.current;
+ const now = Date.now();
+ if (sample && bytes > sample.bytes && now > sample.at) {
+ setDownloadBytesPerSec(
+ ((bytes - sample.bytes) * 1000) / (now - sample.at),
+ );
+ }
+ downloadRateSampleRef.current = { bytes, at: now };
+ // Keep the download progress fresh.
+ window.setTimeout(() => {
+ if (!cancelled) setStatusNonce((n) => n + 1);
+ }, 800);
+ } else {
+ const finished = watchedDownloadRef.current;
+ watchedDownloadRef.current = null;
+ downloadRateSampleRef.current = null;
+ setDownloadBytesPerSec(0);
+ if (
+ finished === sttModel &&
+ engineStatus.downloaded_models.includes(sttModel) &&
+ engineStatus.loaded_model !== sttModel
+ ) {
+ // The download this tab watched just finished; load the model.
+ void autoLoadSttModel(sttModel);
+ return;
+ }
+ }
+ if (engineStatus.loading) {
+ setSttPhase("loading");
+ window.setTimeout(() => {
+ if (!cancelled) setStatusNonce((n) => n + 1);
+ }, 600);
+ return;
+ }
+ if (engineStatus.loaded_model === sttModel && !engineStatus.loading) {
+ setSttDevice(engineStatus.device);
+ setSttPhase("ready");
+ window.setTimeout(
+ () => {
+ if (!cancelled) setStatusNonce((n) => n + 1);
+ },
+ Math.max(
+ 1000,
+ Math.min(engineStatus.keep_alive_seconds * 1000, 15_000),
+ ),
+ );
+ return;
+ }
+ // Merely opening settings or selecting local STT never downloads or
+ // loads a model. Loading begins from Load or when recording starts.
+ setSttDevice(null);
+ setSttPhase("on-demand");
+ } catch {
+ if (!cancelled) setSttPhase("error");
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [
+ isLocalEngine,
+ isGgufModel,
+ sttModel,
+ sttRepoId,
+ modelSttSupported,
+ statusNonce,
+ autoLoadSttModel,
+ ]);
+
+ const sttStatusText = (() => {
+ switch (sttPhase) {
+ case "checking":
+ return t("settings.voice.dictation.sttChecking");
+ case "loading":
+ return t("settings.voice.dictation.sttLoadingModel");
+ 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"
+ ? t("settings.voice.dictation.sttReady", {
+ device: sttDevice.toUpperCase(),
+ })
+ : t("settings.voice.dictation.sttLoaded");
+ case "unavailable":
+ return t("settings.voice.dictation.sttUnavailable");
+ case "error":
+ return t("settings.voice.dictation.sttModelFailed");
+ default:
+ return "";
+ }
+ })();
+
+ const downloadingThisModel =
+ isLocalEngine &&
+ sttDownload?.downloading === true &&
+ sttDownload.model === sttModel;
+
+ const sttModelStatusText = (() => {
+ if (downloadingThisModel) {
+ const total = sttDownload?.bytes_total ?? 0;
+ const done = sttDownload?.bytes_done ?? 0;
+ return t("settings.voice.dictation.sttDownloading", {
+ progress:
+ total > 0 ? Math.min(99, Math.round((done / total) * 100)) : 0,
+ });
+ }
+ if (sttPhase === "unavailable") {
+ return sttStatusText;
+ }
+ switch (effectiveSttDownloadAvailability) {
+ case "checking":
+ return t("settings.voice.dictation.sttDownloadChecking");
+ case "missing":
+ return t("settings.voice.dictation.sttNotDownloaded");
+ case "error":
+ return t("settings.voice.dictation.sttDownloadStatusFailed");
+ case "downloaded":
+ return sttStatusText;
+ default:
+ return "";
+ }
+ })();
+
+ const beginSttDownload = async () => {
+ setSttDownloadStarting(true);
+ try {
+ // Engine-managed download; progress arrives via /stt/status.
+ await startSttDownload(sttModel, hfApiToken(hfToken));
+ setStatusNonce((nonce) => nonce + 1);
+ } catch (error) {
+ toast.error(t("settings.voice.dictation.sttDownloadFailed"), {
+ description: error instanceof Error ? error.message : undefined,
+ });
+ } finally {
+ setSttDownloadStarting(false);
+ }
};
+ const warmSttModel = async () => {
+ setSttPhase("loading");
+ try {
+ await loadSttModel(sttModel);
+ setStatusNonce((nonce) => nonce + 1);
+ } catch (error) {
+ setSttPhase("error");
+ toast.error(t("settings.voice.dictation.sttModelFailed"), {
+ description: error instanceof Error ? error.message : undefined,
+ });
+ }
+ };
+
+ const releaseSttModel = async () => {
+ setSttUnloading(true);
+ try {
+ await unloadSttModel();
+ setStatusNonce((nonce) => nonce + 1);
+ } catch (error) {
+ toast.error(t("settings.voice.dictation.sttModelFailed"), {
+ description: error instanceof Error ? error.message : undefined,
+ });
+ } finally {
+ setSttUnloading(false);
+ }
+ };
+
+ // Keep an item for an unplugged saved mic so the value stays visible.
+ const knownMic = devices.some((d) => d.deviceId === micDeviceId);
+
const previewAudioRef = useRef<HTMLAudioElement | null>(null);
const previewAbortRef = useRef<AbortController | null>(null);
// Mirrors `previewing` so unmount cleanup can tell whether this tab owns
@@ -450,8 +748,7 @@ export function VoiceTab() {
const audio = new Audio(url);
audio.playbackRate = ttsRate;
audio.volume = ttsVolume;
- // Some browsers reset playbackRate to 1 once the source loads; reapply
- // it on loadedmetadata so the speed setting reliably takes effect.
+ // Some browsers reset playbackRate once metadata loads.
audio.addEventListener("loadedmetadata", () => {
audio.playbackRate = ttsRate;
});
@@ -462,8 +759,6 @@ export function VoiceTab() {
audio.addEventListener("error", () => {
releasePreviewAudio();
markPreviewing(false);
- // Surface playback failures like the catch below, instead of just
- // resetting the button with no explanation.
toast.error("TTS preview failed");
});
previewAudioRef.current = audio;
@@ -501,6 +796,23 @@ export function VoiceTab() {
// Stop any preview playback when the tab unmounts.
useEffect(() => stopPreview, [stopPreview]);
+ if (subpage === "recents") {
+ return (
+ <RecentDictationsView
+ selectedId={selectedDictationId}
+ onSelect={setSelectedDictationId}
+ onBack={() => {
+ setSelectedDictationId(null);
+ setSubpage("main");
+ }}
+ />
+ );
+ }
+
+ if (subpage === "dictionary") {
+ return <DictationDictionaryView onBack={() => setSubpage("main")} />;
+ }
+
return (
<div className="flex flex-col gap-6">
<header className="flex flex-col gap-1">
@@ -513,6 +825,191 @@ export function VoiceTab() {
</header>
<SettingsSection title={t("settings.voice.dictation.sectionTitle")}>
+ <SettingsRow
+ label={t("settings.voice.dictation.engineLabel")}
+ description={
+ dictationEngine === "model"
+ ? t("settings.voice.dictation.engineModelDescription")
+ : t("settings.voice.dictation.engineBrowserDescription")
+ }
+ >
+ <Select
+ value={dictationEngine}
+ onValueChange={(value) => {
+ const next = value === "model" ? "model" : "browser";
+ if (next !== dictationEngine) {
+ // Unload whichever backend was resident for the old engine.
+ void unloadSttModel().catch(() => {});
+ if (next === "model") {
+ setSttPhase("checking");
+ setSttDevice(null);
+ setSttDownload(null);
+ }
+ }
+ setDictationEngine(next);
+ }}
+ >
+ <SelectTrigger
+ aria-label="Dictation engine"
+ className="w-56"
+ size="sm"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="browser">
+ {t("settings.voice.dictation.engineBrowser")}
+ </SelectItem>
+ <SelectItem value="model">
+ {t("settings.voice.dictation.engineModel")}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </SettingsRow>
+
+ {isLocalEngine ? (
+ modelSttSupported ? (
+ <SettingsRow
+ label={t("settings.voice.dictation.sttModelLabel")}
+ description={t("settings.voice.dictation.sttModelDescription")}
+ >
+ <div className="flex w-56 flex-col items-stretch gap-2">
+ <SttModelPicker
+ value={sttModel}
+ language={dictationLanguage}
+ onChange={(next) => {
+ if (next !== sttModel) {
+ void unloadSttModel().catch(() => {});
+ void autoLoadSttModel(next);
+ }
+ setSttModel(next);
+ }}
+ />
+ {downloadingThisModel ? (
+ <div className="rounded-md border border-border/60 bg-muted/20 px-2.5 pt-2">
+ <div className="mb-1.5 flex items-center justify-between gap-3">
+ <span className="text-xs text-muted-foreground">
+ {sttModelStatusText}
+ </span>
+ </div>
+ <DownloadProgressBar
+ progress={{
+ expectedBytes: sttDownload?.bytes_total ?? 0,
+ downloadedBytes: sttDownload?.bytes_done ?? 0,
+ fraction:
+ sttDownload?.bytes_total &&
+ sttDownload.bytes_total > 0
+ ? (sttDownload.bytes_done ?? 0) /
+ sttDownload.bytes_total
+ : 0,
+ }}
+ bytesPerSec={downloadBytesPerSec}
+ />
+ </div>
+ ) : (
+ <div className="flex min-h-7 items-center justify-between gap-3">
+ <span className="flex min-w-0 items-center gap-2 text-xs text-muted-foreground">
+ {effectiveSttDownloadAvailability === "checking" ||
+ sttPhase === "loading" ||
+ sttPhase === "checking" ? (
+ <span className="size-1.5 shrink-0 animate-pulse rounded-full bg-current" />
+ ) : sttPhase === "ready" ||
+ (effectiveSttDownloadAvailability === "downloaded" &&
+ sttPhase === "on-demand") ? (
+ <span className="size-1.5 shrink-0 rounded-full bg-emerald-500" />
+ ) : effectiveSttDownloadAvailability === "error" ||
+ sttPhase === "error" ? (
+ <span className="size-1.5 shrink-0 rounded-full bg-destructive" />
+ ) : null}
+ <span>{sttModelStatusText}</span>
+ </span>
+ {sttPhase === "unavailable" ? (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7 px-2 text-xs"
+ onClick={() => setStatusNonce((nonce) => nonce + 1)}
+ >
+ {t("settings.voice.dictation.sttRetry")}
+ </Button>
+ ) : effectiveSttDownloadAvailability === "error" ? (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7 px-2 text-xs"
+ disabled={sttDownloadStarting || downloadingThisModel}
+ // Restart the download; the sidecar error is sticky until
+ // a new start(), so re-polling alone never clears it.
+ onClick={beginSttDownload}
+ >
+ {t("settings.voice.dictation.sttRetry")}
+ </Button>
+ ) : effectiveSttDownloadAvailability === "missing" ? (
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7 px-2.5 text-xs"
+ disabled={sttDownloadStarting || downloadingThisModel}
+ onClick={beginSttDownload}
+ >
+ {sttDownloadStarting || downloadingThisModel ? (
+ <Spinner className="mr-1.5" />
+ ) : null}
+ {t("settings.voice.dictation.sttDownload")}
+ </Button>
+ ) : effectiveSttDownloadAvailability === "downloaded" ? (
+ sttPhase === "ready" ? (
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7 px-2.5 text-xs"
+ disabled={sttUnloading}
+ onClick={releaseSttModel}
+ >
+ {sttUnloading ? <Spinner className="mr-1.5" /> : null}
+ {sttUnloading
+ ? t("settings.voice.dictation.sttUnloading")
+ : t("settings.voice.dictation.sttUnload")}
+ </Button>
+ ) : sttPhase === "loading" || sttPhase === "checking" ? (
+ // The status line already says "Loading model…"; the
+ // button only needs the spinner.
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7 px-2.5 text-xs"
+ disabled={true}
+ aria-label={t(
+ "settings.voice.dictation.sttLoadingModel",
+ )}
+ >
+ <Spinner />
+ </Button>
+ ) : (
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7 px-2.5 text-xs"
+ onClick={warmSttModel}
+ >
+ {sttPhase === "error"
+ ? t("settings.voice.dictation.sttRetry")
+ : t("settings.voice.dictation.sttLoad")}
+ </Button>
+ )
+ ) : null}
+ </div>
+ )}
+ </div>
+ </SettingsRow>
+ ) : (
+ <SettingsRow
+ label={t("settings.voice.dictation.sttModelLabel")}
+ description={t("settings.voice.dictation.sttModelUnsupported")}
+ />
+ )
+ ) : null}
+
<SettingsRow
label={t("settings.voice.dictation.microphoneLabel")}
description={
@@ -581,144 +1078,34 @@ export function VoiceTab() {
</Select>
</SettingsRow>
- {dictationSupported ? (
- <DictationTest />
- ) : (
- <SettingsRow
- label={t("settings.voice.dictation.testLabel")}
- description={t("settings.voice.dictation.notSupported")}
- />
- )}
- </SettingsSection>
-
- <SettingsSection
- title={t("settings.voice.dictionary.sectionTitle")}
- description={t("settings.voice.dictionary.sectionDescription")}
- >
- {dictionary.map((entry, index) => (
- <div
- // biome-ignore lint/suspicious/noArrayIndexKey: entries are editable in place
- key={index}
- className="flex items-center gap-2 py-1.5"
- >
- <Input
- value={entry}
- onChange={(e) => updateDictionaryEntry(index, e.target.value)}
- // Skip the empty-row commit-splice when focus moves to this row's
- // Remove button (keyboard Tab), so its index stays valid and its
- // activation deletes this row instead of the next one.
- onBlur={(e) => {
- if (
- (e.relatedTarget as HTMLElement | null)?.dataset.dictRemove ===
- String(index)
- ) {
- return;
- }
- commitDictionaryEntry(index);
- }}
- className="h-8 flex-1 text-sm"
- aria-label={`Dictionary entry ${index + 1}`}
- />
- <Button
- variant="ghost"
- size="icon"
- className="size-8 shrink-0 text-muted-foreground hover:text-destructive"
- data-dict-remove={index}
- // Mouse: keep the click from blurring an empty input first, which
- // would commit-splice this row and make onClick delete the next.
- onMouseDown={(e) => e.preventDefault()}
- onClick={() => removeDictionaryEntry(index)}
- aria-label={`Remove dictionary entry ${index + 1}`}
- >
- <HugeiconsIcon icon={Delete02Icon} className="size-3.5" />
- </Button>
- </div>
- ))}
- <div className="flex items-center gap-2 py-1.5">
- <Input
- value={newEntry}
- onChange={(e) => setNewEntry(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === "Enter") {
- e.preventDefault();
- handleAddEntry();
- }
- }}
- placeholder="Jane Doe"
- className="h-8 flex-1 text-sm"
- aria-label="New dictionary entry"
- />
+ <SettingsRow
+ label={t("settings.voice.dictionary.manageLabel")}
+ description={t("settings.voice.dictionary.sectionDescription")}
+ >
<Button
variant="outline"
size="sm"
- className="shrink-0"
- onClick={handleAddEntry}
- disabled={!newEntry.trim()}
+ onClick={() => setSubpage("dictionary")}
>
- <HugeiconsIcon icon={PlusSignIcon} className="mr-1.5 size-3.5" />
- {t("settings.voice.dictionary.addEntry")}
+ {t("settings.voice.dictionary.manage")}
</Button>
- </div>
- </SettingsSection>
+ </SettingsRow>
- <SettingsSection
- title={t("settings.voice.recents.sectionTitle")}
- description={t("settings.voice.recents.sectionDescription")}
- >
- {recentDictations.length === 0 ? (
- <p className="py-3 text-sm text-muted-foreground">
- {t("settings.voice.recents.empty")}
- </p>
- ) : (
- <>
- {recentDictations.map((item) => (
- <div
- key={`${item.at}-${item.text.slice(0, 24)}`}
- className="flex items-start justify-between gap-3 py-2.5"
- >
- <div className="min-w-0 flex-1">
- <p className="whitespace-pre-wrap break-words text-sm text-foreground">
- {item.text}
- </p>
- <p className="mt-0.5 text-xs text-muted-foreground">
- {new Date(item.at).toLocaleString()}
- </p>
- </div>
- <Button
- variant="ghost"
- size="icon"
- className="size-8 shrink-0 text-muted-foreground"
- aria-label="Copy dictation"
- onClick={async () => {
- // Helper falls back to execCommand where navigator.clipboard
- // is unavailable (Safari, insecure http LAN contexts).
- if (await copyToClipboard(item.text)) {
- toast.success(t("settings.voice.recents.copied"));
- } else {
- toast.error(t("settings.voice.recents.copyFailed"));
- }
- }}
- >
- <HugeiconsIcon icon={Copy01Icon} className="size-3.5" />
- </Button>
- </div>
- ))}
- <div className="flex justify-end py-2">
- <Button
- variant="outline"
- size="sm"
- onClick={clearRecentDictations}
- className="text-destructive hover:text-destructive hover:border-destructive/60"
- >
- <HugeiconsIcon
- icon={Delete02Icon}
- className="mr-1.5 size-3.5"
- />
- {t("settings.voice.recents.clear")}
- </Button>
- </div>
- </>
- )}
+ <SettingsRow
+ label={t("settings.voice.recents.manageLabel")}
+ description={t("settings.voice.recents.sectionDescription")}
+ >
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ setSelectedDictationId(null);
+ setSubpage("recents");
+ }}
+ >
+ {t("settings.voice.recents.manage")}
+ </Button>
+ </SettingsRow>
</SettingsSection>
<SettingsSection title={t("settings.voice.readAloud.sectionTitle")}>
diff --git a/studio/frontend/src/hooks/index.ts b/studio/frontend/src/hooks/index.ts
index 5b2fa43ae77..33289ffe9e8 100644
--- a/studio/frontend/src/hooks/index.ts
+++ b/studio/frontend/src/hooks/index.ts
@@ -1,7 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-
export { useDebouncedValue } from "./use-debounced-value";
export { useGpuInfo } from "./use-gpu-info";
export { useGpuUtilization } from "./use-gpu-utilization";
@@ -11,3 +10,4 @@ export { useHfTokenValidation } from "./use-hf-token-validation";
export { useTauriBackend } from "./use-tauri-backend";
export { useCollapseScrollLock } from "./use-collapse-scroll-lock";
export { useSystemInfo } from "./use-system";
+export { useWheelScrollRef } from "./use-wheel-scroll-ref";
diff --git a/studio/frontend/src/hooks/use-llama-update-check.ts b/studio/frontend/src/hooks/use-llama-update-check.ts
index e3a735ffde1..999700ae1f8 100644
--- a/studio/frontend/src/hooks/use-llama-update-check.ts
+++ b/studio/frontend/src/hooks/use-llama-update-check.ts
@@ -30,6 +30,7 @@ export interface LlamaUpdateJob {
export interface LlamaUpdateStatus {
supported: boolean;
update_available: boolean;
+ component: "llama.cpp" | "whisper.cpp";
installed_tag: string | null;
latest_tag: string | null;
// Prebuilt download size in bytes, if known.
@@ -55,13 +56,30 @@ function parseJob(value: unknown): LlamaUpdateJob {
function parseStatus(value: unknown): LlamaUpdateStatus | null {
if (!value || typeof value !== "object") return null;
const s = value as Record<string, unknown>;
+ const component =
+ s.update_component === "whisper" ? "whisper.cpp" : "llama.cpp";
+ const whisper =
+ s.whisper && typeof s.whisper === "object"
+ ? (s.whisper as Record<string, unknown>)
+ : null;
+ // Legacy top-level version fields intentionally retain their llama meaning.
+ // A whisper-only update must display the nested whisper release instead of
+ // presenting equal llama tags as a new llama update.
+ const details = component === "whisper.cpp" && whisper ? whisper : s;
return {
supported: s.supported === true,
update_available: s.update_available === true,
- installed_tag: typeof s.installed_tag === "string" ? s.installed_tag : null,
- latest_tag: typeof s.latest_tag === "string" ? s.latest_tag : null,
+ component,
+ installed_tag:
+ typeof details.installed_tag === "string"
+ ? details.installed_tag
+ : null,
+ latest_tag:
+ typeof details.latest_tag === "string" ? details.latest_tag : null,
update_size_bytes:
- typeof s.update_size_bytes === "number" ? s.update_size_bytes : null,
+ typeof details.update_size_bytes === "number"
+ ? details.update_size_bytes
+ : null,
job: parseJob(s.job),
};
}
@@ -163,8 +181,12 @@ export function useLlamaUpdateCheck({
// can drop or double-fire the notification.
const notifyReloadIfNeeded = useCallback(
(job: Pick<LlamaUpdateJob, "state" | "reload_required" | "finished_at">) => {
+ // "error" is included for partial chained updates: the llama phase can
+ // land (and unload the server) before a later phase fails, and the
+ // backend keeps reload_required set in exactly that case. Without the
+ // resync the chat UI would keep pointing at the unloaded model.
if (
- job.state === "success" &&
+ (job.state === "success" || job.state === "error") &&
job.reload_required &&
job.finished_at !== reloadNotifiedForRef.current
) {
@@ -202,7 +224,9 @@ export function useLlamaUpdateCheck({
reloadRequired: s.job.reload_required,
});
} else if (s.job.state === "error") {
- // Keep the banner visible so retry is available.
+ // Keep the banner visible so retry is available. A partial chained
+ // update can still have unloaded the llama server before failing.
+ notifyReloadIfNeeded(s.job);
onDone?.({ ok: false, error: s.job.error });
} else {
onDone?.({ ok: false, error: "update did not complete" });
diff --git a/studio/frontend/src/hooks/use-wheel-scroll-ref.ts b/studio/frontend/src/hooks/use-wheel-scroll-ref.ts
new file mode 100644
index 00000000000..09d0ea5a97a
--- /dev/null
+++ b/studio/frontend/src/hooks/use-wheel-scroll-ref.ts
@@ -0,0 +1,43 @@
+// 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 { useCallback, useRef } from "react";
+
+/**
+ * Callback ref for scroll containers inside modal scroll locks. The lock may
+ * cancel native wheel scrolling, so apply the delta before it reaches the
+ * portaled dialog boundary.
+ */
+export function useWheelScrollRef<T extends HTMLElement>() {
+ const detachRef = useRef<(() => void) | null>(null);
+
+ return useCallback((node: T | null) => {
+ detachRef.current?.();
+ detachRef.current = null;
+ if (!node) {
+ return;
+ }
+
+ const onWheel = (event: WheelEvent) => {
+ if (event.ctrlKey || node.scrollHeight <= node.clientHeight) {
+ return;
+ }
+ const multiplier =
+ event.deltaMode === WheelEvent.DOM_DELTA_LINE
+ ? 16
+ : event.deltaMode === WheelEvent.DOM_DELTA_PAGE
+ ? node.clientHeight
+ : 1;
+ const delta = event.deltaY * multiplier;
+ if (delta === 0) {
+ return;
+ }
+ node.scrollTop += delta;
+ event.preventDefault();
+ event.stopPropagation();
+ };
+
+ node.addEventListener("wheel", onWheel, { passive: false });
+ detachRef.current = () => node.removeEventListener("wheel", onWheel);
+ }, []);
+}
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index ace954373e0..57f06ceb7ec 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -105,9 +105,45 @@ export const en = {
},
voice: {
title: "Voice",
- description: "Microphone, dictation, and read-aloud",
+ description: "Microphone, dictation, speech-to-text and read-aloud",
dictation: {
sectionTitle: "Dictation",
+ engineLabel: "Dictation engine",
+ engineBrowser: "Browser",
+ engineBrowserDescription:
+ "Transcribes audio using your browser speech service. Select 'Local transcription' to use a STT model.",
+ engineModel: "Local transcription",
+ engineModelDescription:
+ "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",
+ sttModelSearching: "Searching Hugging Face…",
+ sttModelValidating: "Checking Whisper compatibility…",
+ sttModelNoResults: "No Whisper models found",
+ sttModelInvalid: "This repository cannot be used for dictation",
+ sttModelFailed: "Could not load the STT model",
+ sttModelUnsupported: "Recording is not supported in this browser",
+ sttChecking: "Checking…",
+ sttOnDemand: "Downloaded",
+ sttLoadingModel: "Loading model…",
+ sttReady: "Loaded on {device}",
+ sttLoaded: "Loaded",
+ sttUnavailable:
+ "Not installed on this server. Run `unsloth studio update` to enable local dictation.",
+ sttRetry: "Retry",
+ sttDownloadChecking: "Checking download status…",
+ sttNotDownloaded: "Not downloaded",
+ sttDownloadStatusFailed: "Could not check download status",
+ sttDownload: "Download",
+ sttDownloading: "Downloading… {progress}%",
+ sttCancelDownload: "Cancel",
+ sttCancellingDownload: "Cancelling…",
+ sttDownloadComplete: "Speech recognition model downloaded",
+ sttDownloadFailed: "Could not download the speech recognition model",
+ sttLoad: "Load",
+ sttUnload: "Unload",
+ sttUnloading: "Unloading…",
microphoneLabel: "Microphone",
microphoneDescription: "Used for dictation",
microphoneFallbackHint:
@@ -118,35 +154,58 @@ export const en = {
"Microphone access was blocked. Allow microphone access for this Unsloth page, then try again.",
micAccessUnsupported:
"Microphone access is not supported in this browser or context.",
- micOpenFailed:
- "Could not open the selected microphone. Check permissions or pick another device.",
systemDefault: "System default",
savedMicDisconnected: "Saved microphone (not connected)",
languageLabel: "Dictation language",
languageDescription: "Language to recognize",
languageAuto: "Auto (browser language)",
- testLabel: "Test dictation",
- testDescription: "Speak to check your mic and settings",
- startTest: "Start test",
- stopTest: "Stop test",
- listening: "Listening…",
- testSaved: "Saved to recent dictations",
- notSupported: "Not supported in this browser",
},
dictionary: {
sectionTitle: "Dictation dictionary",
- sectionDescription:
- "Apply the spelling entered here when dictation recognizes the same words or phrase",
+ sectionDescription: "Set how dictation spells specific words or phrases",
+ manageLabel: "Custom spellings",
+ manage: "Manage",
+ backToVoice: "Back to Voice",
addEntry: "Add entry",
},
recents: {
- sectionTitle: "Recent dictations",
+ sectionTitle: "Dictation history",
sectionDescription:
- "Your recent dictations will appear here so you can recover text",
+ "Every dictation is saved here so you can recover text",
+ manageLabel: "Dictation history",
+ manage: "Manage",
+ pageDescription:
+ "Every dictation is saved. View, copy, or delete them, or open the chat a dictation was used in.",
+ searchPlaceholder: "Search dictations",
+ sortLabel: "Sort dictations",
+ sortNewest: "Newest",
+ sortOldest: "Oldest",
+ sortAlpha: "A to Z",
+ noMatches: "No dictations match your search",
+ detailTitle: "Saved dictation",
+ backToVoice: "Back to Voice",
+ backToRecents: "Back to recent dictations",
+ view: "View full dictation",
empty: "No dictations yet",
+ dictationColumn: "Dictation",
+ dateColumn: "Date created",
+ copy: "Copy dictation",
copied: "Copied to clipboard",
copyFailed: "Could not copy to clipboard",
- clear: "Clear recent dictations",
+ delete: "Delete dictation",
+ deleteTitle: "Delete dictation",
+ deleteDescription:
+ "Delete this saved dictation? This cannot be undone.",
+ deleteLinkedDescription:
+ "Delete this saved dictation? You can also delete the chat it was used in. This cannot be undone.",
+ deleteWithChat: "Delete chat and dictation",
+ deleteWithChatFailed: "Could not delete the chat",
+ clear: "Clear history",
+ clearTitle: "Clear dictation history",
+ clearDescription: "Delete all saved dictations? This cannot be undone.",
+ clearConfirm: "Clear all",
+ showMore: "Show more ({count})",
+ openChat: "Open chat",
},
readAloud: {
sectionTitle: "Read aloud",
diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.css
index f4fa3cfb8dc..0cba3407fe4 100644
--- a/studio/frontend/src/index.css
+++ b/studio/frontend/src/index.css
@@ -1674,6 +1674,12 @@ html[data-chat-font] .aui-root {
@apply flex w-full flex-wrap items-center gap-0.5 px-1;
}
+ /* Recording is a dedicated one-line mode. Active tool pills must not force
+ the composer back into the normal two-row layout. */
+ .unsloth-composer-line[data-dictating="true"] {
+ @apply flex-nowrap;
+ }
+
.unsloth-composer-left {
@apply flex min-w-0 flex-wrap items-center gap-0.5;
order: 1;
diff --git a/studio/install_llama_prebuilt.py b/studio/install_llama_prebuilt.py
index 1093ae2fd05..60269624781 100644
--- a/studio/install_llama_prebuilt.py
+++ b/studio/install_llama_prebuilt.py
@@ -43,6 +43,21 @@ except ImportError:
from pathlib import Path
from typing import Any, Iterable, Iterator
+# Shared component-agnostic machinery lives in prebuilt_core (same directory);
+# put studio/ on sys.path so it resolves whether this file is run as a script
+# (from any cwd) or loaded via an importlib spec by the tests.
+_STUDIO_DIR = os.path.dirname(os.path.abspath(__file__))
+if _STUDIO_DIR not in sys.path:
+ sys.path.insert(0, _STUDIO_DIR)
+
+import prebuilt_core as _core # noqa: E402
+
+# Late-binding seam: core functions resolve collaborators (download_file,
+# fetch_json, ...) through this module's globals at call time, so tests that
+# monkeypatch names on this module keep working.
+_OPS = _core.ModuleOps(globals())
+USER_AGENT = "unsloth-studio-llama-prebuilt"
+
EXIT_SUCCESS = 0
EXIT_FALLBACK = 2
@@ -121,26 +136,7 @@ def _amd_smi_allowed() -> bool:
return False
-def windows_hidden_subprocess_kwargs() -> dict[str, object]:
- """Return Windows-only subprocess kwargs that suppress console windows."""
- if sys.platform != "win32":
- return {}
-
- kwargs: dict[str, object] = {}
- create_no_window = getattr(subprocess, "CREATE_NO_WINDOW", 0)
- if create_no_window:
- kwargs["creationflags"] = create_no_window
-
- startupinfo_factory = getattr(subprocess, "STARTUPINFO", None)
- startf_use_showwindow = getattr(subprocess, "STARTF_USESHOWWINDOW", 0)
- sw_hide = getattr(subprocess, "SW_HIDE", 0)
- if startupinfo_factory is not None and startf_use_showwindow:
- startupinfo = startupinfo_factory()
- startupinfo.dwFlags |= startf_use_showwindow
- startupinfo.wShowWindow = sw_hide
- kwargs["startupinfo"] = startupinfo
-
- return kwargs
+windows_hidden_subprocess_kwargs = _core.windows_hidden_subprocess_kwargs
def env_int(
@@ -347,10 +343,7 @@ class LinuxCudaSelection:
return self.attempts[0]
-@dataclass
-class CudaRuntimePreference:
- runtime_line: str | None
- selection_log: list[str]
+CudaRuntimePreference = _core.CudaRuntimePreference
@dataclass(frozen = True)
@@ -404,12 +397,8 @@ class InstallReleasePlan:
approved_checksums: ApprovedReleaseChecksums
-class PrebuiltFallback(RuntimeError):
- pass
-
-
-class BusyInstallConflict(RuntimeError):
- pass
+PrebuiltFallback = _core.PrebuiltFallback
+BusyInstallConflict = _core.BusyInstallConflict
class ExistingInstallSatisfied(RuntimeError):
@@ -419,51 +408,8 @@ class ExistingInstallSatisfied(RuntimeError):
self.used_fallback = used_fallback
-def _os_error_messages(exc: BaseException) -> list[str]:
- messages: list[str] = []
- if isinstance(exc, OSError):
- for value in (
- getattr(exc, "strerror", None),
- getattr(exc, "filename", None),
- getattr(exc, "filename2", None),
- ):
- if isinstance(value, str) and value:
- messages.append(value)
- text = str(exc)
- if text:
- messages.append(text)
- return [message.lower() for message in messages if message]
-
-
-def is_busy_lock_error(exc: BaseException) -> bool:
- if isinstance(exc, BusyInstallConflict):
- return True
- if isinstance(exc, OSError):
- if exc.errno in {
- errno.EACCES,
- errno.EBUSY,
- errno.EPERM,
- errno.ETXTBSY,
- }:
- return True
- if getattr(exc, "winerror", None) in {5, 32, 145}:
- return True
- for message in _os_error_messages(exc):
- if any(
- needle in message
- for needle in (
- "access is denied",
- "being used by another process",
- "device or resource busy",
- "permission denied",
- "text file busy",
- "file is in use",
- "process cannot access the file",
- "cannot create a file when that file already exists",
- )
- ):
- return True
- return False
+_os_error_messages = _core._os_error_messages
+is_busy_lock_error = _core.is_busy_lock_error
# Status logs default to stderr so resolver modes keep stdout machine-readable
@@ -481,153 +427,30 @@ def log_lines(lines: Iterable[str]) -> None:
log(line)
-def parsed_hostname(url: str | None) -> str | None:
- if not url:
- return None
- try:
- hostname = urllib.parse.urlparse(url).hostname
- except Exception:
- return None
- if not hostname:
- return None
- return hostname.lower()
-
-
-def should_send_github_auth(url: str | None) -> bool:
- return parsed_hostname(url) in GITHUB_AUTH_HOSTS
-
-
-def should_send_hf_auth(url: str | None) -> bool:
- return parsed_hostname(url) in HF_AUTH_HOSTS
+parsed_hostname = _core.parsed_hostname
+should_send_github_auth = _core.should_send_github_auth
+should_send_hf_auth = _core.should_send_hf_auth
def auth_headers(url: str | None = None) -> dict[str, str]:
- headers = {
- "User-Agent": "unsloth-studio-llama-prebuilt",
- }
- token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN")
- if token and should_send_github_auth(url):
- headers["Authorization"] = f"Bearer {token}"
- return headers
- # Anonymous huggingface.co fetches share a per-IP rate limit that CI
- # fleets exhaust (HTTP 429), sinking the prebuilt path into a source
- # build. Authenticate when a token is available.
- hf_token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
- if hf_token and should_send_hf_auth(url):
- headers["Authorization"] = f"Bearer {hf_token}"
- return headers
-
-
-class _CrossHostAuthStrippingRedirectHandler(urllib.request.HTTPRedirectHandler):
- """Drop Authorization when a redirect leaves the original host.
-
- huggingface.co redirects file downloads to CDN hosts whose signed URLs
- can reject foreign Authorization headers; urllib forwards headers to
- redirect targets by default (requests/huggingface_hub strip them).
- """
+ return _core.auth_headers(_OPS, url)
- def redirect_request(self, req, fp, code, msg, headers, newurl):
- new_request = super().redirect_request(req, fp, code, msg, headers, newurl)
- if new_request is not None and parsed_hostname(newurl) != parsed_hostname(req.full_url):
- new_request.headers.pop("Authorization", None)
- new_request.unredirected_hdrs.pop("Authorization", None)
- return new_request
-
-_URL_OPENER = urllib.request.build_opener(_CrossHostAuthStrippingRedirectHandler())
+_CrossHostAuthStrippingRedirectHandler = _core._CrossHostAuthStrippingRedirectHandler
+_URL_OPENER = _core._URL_OPENER
def github_api_headers(url: str | None = None) -> dict[str, str]:
- return {
- "Accept": "application/vnd.github+json",
- **auth_headers(url),
- }
-
-
-def is_github_api_url(url: str | None) -> bool:
- return parsed_hostname(url) == "api.github.com"
-
-
-def is_retryable_url_error(exc: Exception) -> bool:
- if isinstance(exc, urllib.error.HTTPError):
- # GitHub returns 403 (not the standard 429) when the API rate
- # limit is hit. Anonymous calls share a 60-req/hour bucket per
- # runner IP, which CI fleets can exhaust trivially. Treat 403
- # against api.github.com as retryable so we get one or two
- # backoff cycles before the source-build fallback fires; honour
- # Retry-After / X-RateLimit-Reset in sleep_backoff for accurate
- # waits. Real 403s on other hosts (private artefact downloads,
- # auth failures) stay non-retryable.
- if exc.code == 403:
- return is_github_api_url(getattr(exc, "url", None))
- return exc.code in RETRYABLE_HTTP_STATUS
- if isinstance(exc, urllib.error.URLError):
- return True
- if isinstance(exc, TimeoutError):
- return True
- if isinstance(exc, socket.timeout):
- return True
- return False
+ return _core.github_api_headers(_OPS, url)
+is_github_api_url = _core.is_github_api_url
+is_retryable_url_error = _core.is_retryable_url_error
_RATE_LIMIT_WAIT_CAP_SECONDS = 60.0
-
-
-def _http_error_retry_delay(exc: Exception) -> float | None:
- """Extract a recommended wait from rate-limit headers on a 403/429.
-
- Returns None when no header is present or the indicated wait is
- longer than _RATE_LIMIT_WAIT_CAP_SECONDS (in which case the caller
- should not block on it -- the source-build fallback is faster).
- """
- if not isinstance(exc, urllib.error.HTTPError):
- return None
- headers = getattr(exc, "headers", None)
- if headers is None:
- return None
- retry_after = headers.get("Retry-After")
- if retry_after and retry_after.strip().isdigit():
- wait = float(retry_after.strip())
- return wait if wait <= _RATE_LIMIT_WAIT_CAP_SECONDS else None
- rate_reset = headers.get("X-RateLimit-Reset")
- if rate_reset and rate_reset.strip().isdigit():
- wait = float(rate_reset.strip()) - time.time()
- if 0.0 < wait <= _RATE_LIMIT_WAIT_CAP_SECONDS:
- return wait + 1.0 # +1s of slack so the bucket is fresh
- return None
-
-
-def sleep_backoff(
- attempt: int,
- *,
- base_delay: float = HTTP_FETCH_BASE_DELAY_SECONDS,
- exc: Exception | None = None,
-) -> None:
- delay = base_delay * (2 ** max(attempt - 1, 0))
- header_delay = _http_error_retry_delay(exc) if exc is not None else None
- if header_delay is not None:
- delay = max(delay, header_delay)
- delay += random.uniform(0.0, 0.2)
- time.sleep(delay)
-
-
-def atomic_write_bytes(destination: Path, data: bytes) -> None:
- destination.parent.mkdir(parents = True, exist_ok = True)
- with tempfile.NamedTemporaryFile(
- prefix = destination.name + ".tmp-",
- dir = destination.parent,
- delete = False,
- ) as handle:
- tmp_path = Path(handle.name)
- handle.write(data)
- handle.flush()
- os.fsync(handle.fileno())
- os.replace(tmp_path, destination)
-
-
-def atomic_replace_from_tempfile(tmp_path: Path, destination: Path) -> None:
- destination.parent.mkdir(parents = True, exist_ok = True)
- os.replace(tmp_path, destination)
+_http_error_retry_delay = _core._http_error_retry_delay
+sleep_backoff = _core.sleep_backoff
+atomic_write_bytes = _core.atomic_write_bytes
+atomic_replace_from_tempfile = _core.atomic_replace_from_tempfile
def source_archive_logical_name(upstream_tag: str) -> str:
@@ -638,27 +461,9 @@ def exact_source_archive_logical_name(source_commit: str) -> str:
return f"llama.cpp-source-commit-{source_commit}.tar.gz"
-def sha256_file(path: Path) -> str:
- digest = hashlib.sha256()
- with path.open("rb") as handle:
- for chunk in iter(lambda: handle.read(1024 * 1024), b""):
- digest.update(chunk)
- return digest.hexdigest()
-
-
-def sha256_bytes(data: bytes) -> str:
- return hashlib.sha256(data).hexdigest()
-
-
-def normalize_sha256_digest(value: str | None) -> str | None:
- if not isinstance(value, str) or not value:
- return None
- lowered = value.lower()
- if lowered.startswith("sha256:"):
- lowered = lowered.split(":", 1)[1]
- if len(lowered) != 64 or any(ch not in "0123456789abcdef" for ch in lowered):
- return None
- return lowered
+sha256_file = _core.sha256_file
+sha256_bytes = _core.sha256_bytes
+normalize_sha256_digest = _core.normalize_sha256_digest
def normalize_source_ref_kind(value: str | None) -> str | None:
@@ -682,15 +487,7 @@ def normalize_source_commit(value: str | None) -> str | None:
def validate_schema_version(payload: dict[str, Any], *, label: str) -> None:
- schema_version = payload.get("schema_version")
- if schema_version is None:
- return
- try:
- normalized = int(schema_version)
- except (TypeError, ValueError) as exc:
- raise RuntimeError(f"{label} schema_version was not an integer") from exc
- if normalized != 1:
- raise RuntimeError(f"{label} schema_version={normalized} is unsupported")
+ _core.validate_schema_version(payload, label = label)
def repo_slug_from_source(value: str | None) -> str | None:
@@ -856,127 +653,10 @@ def _published_windows_cuda_runtime(
return f"{major}.{best}" if best is not None else None
-def format_byte_count(num_bytes: float) -> str:
- units = ["B", "KiB", "MiB", "GiB", "TiB"]
- value = float(num_bytes)
- for unit in units:
- if abs(value) < 1024.0 or unit == units[-1]:
- if unit == "B":
- return f"{int(value)} {unit}"
- return f"{value:.1f} {unit}"
- value /= 1024.0
- return f"{num_bytes:.1f} B"
-
-
-def _progress_percent_step() -> int:
- """Non-tty milestone granularity. The in-app updater sets
- UNSLOTH_PROGRESS_PERCENT_STEP=5 to stream finer progress lines."""
- try:
- step = int(os.environ.get("UNSLOTH_PROGRESS_PERCENT_STEP", "25"))
- except ValueError:
- return 25
- return min(max(step, 1), 50)
-
-
-class DownloadProgress:
- def __init__(self, label: str, total_bytes: int | None) -> None:
- self.label = label
- self.total_bytes = total_bytes if total_bytes and total_bytes > 0 else None
- self.start_time = time.monotonic()
- self.last_emit = 0.0
- term_ok = os.environ.get("TERM", "").lower() != "dumb"
- self.stream = (
- sys.stderr if sys.stderr.isatty() else sys.stdout if sys.stdout.isatty() else sys.stderr
- )
- self.is_tty = term_ok and self.stream.isatty()
- self.completed = False
- self.milestone_step = _progress_percent_step()
- self.last_milestone_percent = -1
- self.last_milestone_bytes = 0
- self.has_rendered_tty_progress = False
-
- def _render(
- self,
- downloaded_bytes: int,
- *,
- final: bool = False,
- ) -> str:
- elapsed = max(time.monotonic() - self.start_time, 1e-6)
- speed = downloaded_bytes / elapsed
- speed_text = f"{format_byte_count(speed)}/s"
- if self.total_bytes is not None:
- percent = min(100.0, (downloaded_bytes / self.total_bytes) * 100.0)
- return (
- f"{self.label}: {percent:5.1f}% "
- f"({format_byte_count(downloaded_bytes)}/{format_byte_count(self.total_bytes)}) "
- f"at {speed_text}"
- )
- if final:
- return f"{self.label}: {format_byte_count(downloaded_bytes)} downloaded at {speed_text}"
- return f"{self.label}: {format_byte_count(downloaded_bytes)} downloaded at {speed_text}"
-
- def update(self, downloaded_bytes: int) -> None:
- now = time.monotonic()
- if self.is_tty:
- elapsed = now - self.start_time
- if not self.has_rendered_tty_progress:
- if self.total_bytes is not None and downloaded_bytes >= self.total_bytes:
- return
- if elapsed < TTY_PROGRESS_START_DELAY_SECONDS:
- return
- min_interval = 0.2
- if (
- self.has_rendered_tty_progress
- and not self.completed
- and (now - self.last_emit) < min_interval
- ):
- return
- self.last_emit = now
- line = self._render(downloaded_bytes)
- self.stream.write("\r\033[K" + line)
- self.stream.flush()
- self.has_rendered_tty_progress = True
- return
-
- should_emit = False
- if self.total_bytes is not None:
- percent = int((downloaded_bytes * 100) / max(self.total_bytes, 1))
- step = self.milestone_step
- milestone_percent = min((percent // step) * step, 100)
- if milestone_percent > self.last_milestone_percent and milestone_percent < 100:
- self.last_milestone_percent = milestone_percent
- should_emit = True
- else:
- byte_step = 25 * 1024 * 1024
- if (
- downloaded_bytes - self.last_milestone_bytes >= byte_step
- and (now - self.last_emit) >= 5.0
- ):
- self.last_milestone_bytes = downloaded_bytes
- should_emit = True
-
- if not should_emit:
- return
-
- self.last_emit = now
- self.stream.write(self._render(downloaded_bytes) + "\n")
- self.stream.flush()
-
- def finish(self, downloaded_bytes: int) -> None:
- self.completed = True
- line = self._render(downloaded_bytes, final = True)
- if self.is_tty:
- if not self.has_rendered_tty_progress:
- return
- self.stream.write("\r\033[K")
- else:
- self.stream.write(line + "\n")
- self.stream.flush()
-
-
-def download_label_from_url(url: str) -> str:
- name = Path(urllib.parse.urlparse(url).path).name
- return name or url
+format_byte_count = _core.format_byte_count
+_progress_percent_step = _core._progress_percent_step
+DownloadProgress = _core.DownloadProgress
+download_label_from_url = _core.download_label_from_url
def download_bytes(
@@ -987,151 +667,30 @@ def download_bytes(
headers: dict[str, str] | None = None,
progress_label: str | None = None,
) -> bytes:
- last_exc: Exception | None = None
- for attempt in range(1, attempts + 1):
- try:
- request = urllib.request.Request(url, headers = headers or auth_headers(url))
- with _URL_OPENER.open(request, timeout = timeout) as response:
- total_bytes: int | None = None
- content_length = response.headers.get("Content-Length")
- if content_length and content_length.isdigit():
- total_bytes = int(content_length)
- progress = DownloadProgress(progress_label, total_bytes) if progress_label else None
- data = bytearray()
- while True:
- chunk = response.read(1024 * 1024)
- if not chunk:
- break
- data.extend(chunk)
- if progress is not None:
- progress.update(len(data))
- if progress is not None:
- progress.finish(len(data))
- return bytes(data)
- except Exception as exc:
- last_exc = exc
- if attempt >= attempts or not is_retryable_url_error(exc):
- raise
- log(f"fetch failed ({attempt}/{attempts}) for {url}: {exc}; retrying")
- sleep_backoff(attempt, exc = exc)
- assert last_exc is not None
- raise last_exc
+ return _core.download_bytes(
+ _OPS,
+ url,
+ timeout = timeout,
+ attempts = attempts,
+ headers = headers,
+ progress_label = progress_label,
+ )
def fetch_json(url: str) -> Any:
- attempts = JSON_FETCH_ATTEMPTS if is_github_api_url(url) else 1
- last_decode_exc: Exception | None = None
- for attempt in range(1, attempts + 1):
- try:
- data = download_bytes(
- url,
- timeout = 30,
- headers = github_api_headers(url) if is_github_api_url(url) else auth_headers(url),
- )
- except urllib.error.HTTPError as exc:
- if exc.code == 403 and is_github_api_url(url):
- hint = ""
- if not (os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN")):
- hint = "; set GH_TOKEN or GITHUB_TOKEN to avoid GitHub API rate limits"
- raise RuntimeError(f"GitHub API returned 403 for {url}{hint}") from exc
- raise
- if not data:
- last_decode_exc = RuntimeError(f"downloaded empty JSON payload from {url}")
- else:
- try:
- payload = json.loads(data.decode("utf-8"))
- except (UnicodeDecodeError, json.JSONDecodeError) as exc:
- last_decode_exc = RuntimeError(f"downloaded invalid JSON from {url}: {exc}")
- else:
- if not isinstance(payload, dict) and not isinstance(payload, list):
- raise RuntimeError(
- f"downloaded unexpected JSON type from {url}: {type(payload).__name__}"
- )
- return payload
- if attempt >= attempts:
- assert last_decode_exc is not None
- raise last_decode_exc
- log(f"json fetch failed ({attempt}/{attempts}) for {url}; retrying")
- sleep_backoff(attempt)
- assert last_decode_exc is not None
- raise last_decode_exc
+ return _core.fetch_json(_OPS, url)
def download_file(url: str, destination: Path) -> None:
- destination.parent.mkdir(parents = True, exist_ok = True)
- last_exc: Exception | None = None
- for attempt in range(1, HTTP_FETCH_ATTEMPTS + 1):
- tmp_path: Path | None = None
- try:
- request = urllib.request.Request(url, headers = auth_headers(url))
- with tempfile.NamedTemporaryFile(
- prefix = destination.name + ".tmp-",
- dir = destination.parent,
- delete = False,
- ) as handle:
- tmp_path = Path(handle.name)
- with _URL_OPENER.open(request, timeout = 120) as response:
- total_bytes: int | None = None
- content_length = response.headers.get("Content-Length")
- if content_length and content_length.isdigit():
- total_bytes = int(content_length)
- progress = DownloadProgress(f"Downloading {destination.name}", total_bytes)
- downloaded_bytes = 0
- while True:
- chunk = response.read(1024 * 1024)
- if not chunk:
- break
- handle.write(chunk)
- downloaded_bytes += len(chunk)
- progress.update(downloaded_bytes)
- progress.finish(downloaded_bytes)
- handle.flush()
- os.fsync(handle.fileno())
- if not tmp_path.exists() or tmp_path.stat().st_size == 0:
- raise RuntimeError(f"downloaded empty file from {url}")
- atomic_replace_from_tempfile(tmp_path, destination)
- return
- except Exception as exc:
- last_exc = exc
- if tmp_path is not None:
- try:
- tmp_path.unlink(missing_ok = True)
- except Exception:
- pass
- if attempt >= HTTP_FETCH_ATTEMPTS or not is_retryable_url_error(exc):
- raise
- log(f"download failed ({attempt}/{HTTP_FETCH_ATTEMPTS}) for {url}: {exc}; retrying")
- sleep_backoff(attempt, exc = exc)
- assert last_exc is not None
- raise last_exc
+ _core.download_file(_OPS, url, destination)
def download_file_verified(
url: str, destination: Path, *, expected_sha256: str | None, label: str
) -> None:
- normalized_expected = normalize_sha256_digest(expected_sha256)
- if not normalized_expected:
- download_file(url, destination)
- log(f"downloaded {label} without a published sha256; relying on install validation")
- return
-
- for attempt in range(1, 3):
- download_file(url, destination)
- actual_sha256 = sha256_file(destination)
- if actual_sha256 == normalized_expected:
- log(f"verified {label} sha256={actual_sha256}")
- return
-
- log(
- f"{label} checksum mismatch on attempt {attempt}/2: "
- f"expected={normalized_expected} actual={actual_sha256}"
- )
- destination.unlink(missing_ok = True)
- if attempt == 2:
- raise PrebuiltFallback(
- f"{label} checksum mismatch after retry: expected={normalized_expected} actual={actual_sha256}"
- )
- log(f"retrying {label} download after checksum mismatch")
+ _core.download_file_verified(
+ _OPS, url, destination, expected_sha256 = expected_sha256, label = label
+ )
def upstream_source_archive_urls(tag: str) -> list[str]:
@@ -1165,21 +724,11 @@ def release_asset_download_url(
def github_release_assets(repo: str, tag: str) -> dict[str, str]:
- payload = fetch_json(
- f"https://api.github.com/repos/{repo}/releases/tags/{urllib.parse.quote(tag, safe = '')}"
- )
- if not isinstance(payload, dict):
- raise RuntimeError(f"unexpected release payload for {repo}@{tag}")
- return release_asset_map(payload)
+ return _core.github_release_assets(_OPS, repo, tag)
def github_release(repo: str, tag: str) -> dict[str, Any]:
- payload = fetch_json(
- f"https://api.github.com/repos/{repo}/releases/tags/{urllib.parse.quote(tag, safe = '')}"
- )
- if not isinstance(payload, dict):
- raise RuntimeError(f"unexpected release payload for {repo}@{tag}")
- return payload
+ return _core.github_release(_OPS, repo, tag)
def github_releases(
@@ -1542,10 +1091,7 @@ def resolve_simple_install_release_plans(
if not allow_older_release_fallback:
raise
release_tag = release.get("tag_name") or "unknown"
- log(
- "published release skipped for install planning: "
- f"{repo}@{release_tag} ({exc})"
- )
+ log(f"published release skipped for install planning: {repo}@{release_tag} ({exc})")
continue
plans.append(plan)
@@ -1571,198 +1117,23 @@ def normalized_requested_llama_tag(requested_tag: str | None) -> str:
return "latest"
-def normalize_compute_cap(value: Any) -> str | None:
- raw = str(value).strip()
- if not raw:
- return None
- if "." in raw:
- parts = raw.split(".", 1)
- if len(parts) != 2:
- return None
- major, minor = parts
- if not major.isdigit() or not minor.isdigit():
- return None
- return f"{int(major)}{int(minor)}"
- if raw.isdigit():
- return str(int(raw))
- return None
-
-
-def normalize_compute_caps(compute_caps: Iterable[str]) -> list[str]:
- normalized: list[str] = []
- seen: set[str] = set()
- for raw in compute_caps:
- normalized_value = normalize_compute_cap(raw)
- if normalized_value is None:
- continue
- if normalized_value in seen:
- continue
- seen.add(normalized_value)
- normalized.append(normalized_value)
- normalized.sort(key = int)
- return normalized
-
-
-def parse_cuda_visible_devices(value: str | None) -> list[str] | None:
- if value is None:
- return None
- raw = value.strip()
- if not raw or raw == "-1":
- return []
- return [token.strip() for token in raw.split(",") if token.strip()]
-
-
-def supports_explicit_visible_device_matching(visible_devices: list[str] | None) -> bool:
- if not visible_devices:
- return False
- for token in visible_devices:
- lowered = token.lower()
- if token.isdigit() or lowered.startswith("gpu-"):
- continue
- return False
- return True
-
-
-def select_visible_gpu_rows(
- gpu_rows: Iterable[tuple[str, str, str]], visible_devices: list[str] | None
-) -> list[tuple[str, str, str]]:
- rows = list(gpu_rows)
- if visible_devices is None:
- return rows
- if not visible_devices:
- return []
-
- by_index = {index: (index, uuid, cap) for index, uuid, cap in rows}
- by_uuid = {uuid.lower(): (index, uuid, cap) for index, uuid, cap in rows}
- selected: list[tuple[str, str, str]] = []
- seen_indices: set[str] = set()
- for token in visible_devices:
- row = by_index.get(token)
- if row is None:
- normalized_token = token.lower()
- row = by_uuid.get(normalized_token)
- if row is None and normalized_token.startswith("gpu-"):
- row = by_uuid.get(normalized_token)
- if row is None and not normalized_token.startswith("gpu-"):
- row = by_uuid.get("gpu-" + normalized_token)
- if row is None:
- continue
- index = row[0]
- if index in seen_indices:
- continue
- seen_indices.add(index)
- selected.append(row)
- return selected
-
-
-def dir_provides_exact_library(directory: str | Path, library: str) -> bool:
- if not library:
- return False
- candidate = Path(directory) / library
- return candidate.exists() and (candidate.is_file() or candidate.is_symlink())
+normalize_compute_cap = _core.normalize_compute_cap
+normalize_compute_caps = _core.normalize_compute_caps
+parse_cuda_visible_devices = _core.parse_cuda_visible_devices
+supports_explicit_visible_device_matching = _core.supports_explicit_visible_device_matching
+select_visible_gpu_rows = _core.select_visible_gpu_rows
+dir_provides_exact_library = _core.dir_provides_exact_library
def linux_runtime_dirs_for_required_libraries(required_libraries: Iterable[str]) -> list[str]:
- required = [library for library in required_libraries if library]
- candidates: list[str | Path] = []
+ return _core.linux_runtime_dirs_for_required_libraries(_OPS, required_libraries)
- env_dirs = os.environ.get("CUDA_RUNTIME_LIB_DIR", "")
- if env_dirs:
- candidates.extend(part for part in env_dirs.split(os.pathsep) if part)
- ld_library_path = os.environ.get("LD_LIBRARY_PATH", "")
- if ld_library_path:
- candidates.extend(part for part in ld_library_path.split(os.pathsep) if part)
-
- cuda_roots: list[Path] = []
- for name in ("CUDA_HOME", "CUDA_PATH", "CUDA_ROOT"):
- value = os.environ.get(name)
- if value:
- cuda_roots.append(Path(value))
- cuda_roots.extend(Path(path) for path in glob_paths("/usr/local/cuda", "/usr/local/cuda-*"))
-
- for root in cuda_roots:
- candidates.extend(
- [
- root / "lib",
- root / "lib64",
- root / "targets" / "x86_64-linux" / "lib",
- ]
- )
-
- candidates.extend(
- Path(path)
- for path in glob_paths(
- "/lib",
- "/lib64",
- "/usr/lib",
- "/usr/lib64",
- "/usr/local/lib",
- "/usr/local/lib64",
- "/lib/x86_64-linux-gnu",
- "/usr/lib/x86_64-linux-gnu",
- )
- )
- candidates.extend(
- Path(path) for path in glob_paths("/usr/local/lib/ollama/cuda_v*", "/usr/lib/wsl/lib")
- )
- candidates.extend(Path(path) for path in python_runtime_dirs())
- candidates.extend(Path(path) for path in ldconfig_runtime_dirs(required))
-
- resolved = dedupe_existing_dirs(candidates)
- if not required:
- return resolved
-
- matched: list[tuple[int, str]] = []
- for directory in resolved:
- base = Path(directory)
- provided = sum(1 for library in required if dir_provides_exact_library(directory, library))
- if provided:
- matched.append((provided, directory))
- matched.sort(key = lambda item: item[0], reverse = True)
- return [directory for _, directory in matched]
+def detected_linux_runtime_lines() -> tuple[list[str], dict[str, list[str]]]:
+ return _core.detected_linux_runtime_lines(_OPS)
-def detected_linux_runtime_lines() -> tuple[list[str], dict[str, list[str]]]:
- line_requirements = {
- f"cuda{m}": [f"libcudart.so.{m}", f"libcublas.so.{m}"]
- for m in range(_MAX_PROBE_CUDA_MAJOR, _MIN_CUDA_MAJOR - 1, -1)
- }
- detected: list[str] = []
- runtime_dirs: dict[str, list[str]] = {}
- for line, required in line_requirements.items():
- dirs = linux_runtime_dirs_for_required_libraries(required)
- library_matches: dict[str, list[str]] = {}
- matching_dirs: list[str] = []
- for library in required:
- matched_dirs = [
- directory for directory in dirs if any(Path(directory).glob(f"{library}*"))
- ]
- if not matched_dirs:
- library_matches = {}
- matching_dirs = []
- break
- library_matches[library] = matched_dirs
- for directory in matched_dirs:
- if directory not in matching_dirs:
- matching_dirs.append(directory)
- if library_matches:
- detected.append(line)
- runtime_dirs[line] = matching_dirs
- return detected, runtime_dirs
-
-
-def release_asset_map(release: dict[str, Any]) -> dict[str, str]:
- assets = release.get("assets")
- if not isinstance(assets, list):
- return {}
- return {
- asset["name"]: asset.get("browser_download_url", "")
- for asset in assets
- if isinstance(asset, dict)
- and isinstance(asset.get("name"), str)
- and isinstance(asset.get("browser_download_url"), str)
- }
+release_asset_map = _core.release_asset_map
def parse_published_artifact(raw: Any) -> PublishedLlamaArtifact | None:
@@ -2067,47 +1438,9 @@ def iter_published_release_bundles(
yield bundle
-def _artifact_covers_sms(artifact: PublishedLlamaArtifact, host_sms: Iterable[str]) -> bool:
- """True when every host SM is listed in the artifact's supported_sms and
- falls within its [min_sm, max_sm] range."""
- if not artifact.supported_sms or artifact.min_sm is None or artifact.max_sm is None:
- return False
- supported = {str(value) for value in artifact.supported_sms}
- return all(sm in supported and artifact.min_sm <= int(sm) <= artifact.max_sm for sm in host_sms)
-
-
-def _sm_range(artifact: PublishedLlamaArtifact) -> int:
- """SM-coverage span used as a sort key, where a tighter (smaller) range wins.
- A bundle with no SM metadata (legacy/upstream-named) gets a max range so it
- sorts last and can't outrank a real targeted bundle whose tight range would
- otherwise sort first."""
- if artifact.min_sm is not None and artifact.max_sm is not None:
- return artifact.max_sm - artifact.min_sm
- return 9999
-
-
-def _blackwell_capable_linux_runtime_lines(
- host_sms: list[str], artifacts: list[PublishedLlamaArtifact]
-) -> list[str]:
- """CUDA runtime lines (highest major first) shipping a bundle that covers every
- visible host SM. Lets a Blackwell host prefer a native sm_120 line over torch's
- reported line, mirroring the Windows Blackwell preference."""
- lines: set[str] = set()
- for artifact in artifacts:
- line = artifact.runtime_line
- # Only rank "cuda<major>" lines; ignore malformed/future-format values
- # (e.g. "cuda13.1") so they are skipped, as pre-existing code does, rather
- # than crashing the major sort.
- if not (line and line.startswith("cuda") and line[len("cuda") :].isdigit()):
- continue
- if not artifact.supported_sms or artifact.min_sm is None or artifact.max_sm is None:
- continue
- supported = {str(value) for value in artifact.supported_sms}
- if all(
- sm in supported and artifact.min_sm <= int(sm) <= artifact.max_sm for sm in host_sms
- ):
- lines.add(line)
- return sorted(lines, key = lambda line: int(line[len("cuda") :]), reverse = True)
+_artifact_covers_sms = _core.artifact_covers_sms
+_sm_range = _core.sm_range
+_blackwell_capable_linux_runtime_lines = _core.blackwell_capable_linux_runtime_lines
def linux_cuda_choice_from_release(
@@ -2398,50 +1731,15 @@ def _download_host_resolve_enabled() -> bool:
def _release_asset_download_url(repo: str, tag: str, asset_name: str) -> str:
- """Tag-pinned asset URL on the release-assets CDN (not api.github.com, so no
- rate limit)."""
- return (
- f"https://github.com/{urllib.parse.quote(repo, safe = '/')}/releases/download/"
- f"{urllib.parse.quote(tag, safe = '')}/"
- f"{urllib.parse.quote(asset_name, safe = '')}"
- )
+ return _core.release_asset_download_url(repo, tag, asset_name)
def _download_host_latest_release_tag(repo: str) -> str | None:
- """Authoritative latest tag from GitHub's /releases/latest redirect target
- (github.com, no api.github.com rate limit); the fast path pins URLs to it rather
- than the checksum asset's self-reported release_tag. /releases/latest resolves by
- created_at/make_latest, which can lag the published_at newest the freshness
- detection uses. None on 404 so the caller falls back to the API."""
- url = f"https://github.com/{urllib.parse.quote(repo, safe = '/')}/releases/latest"
- request = urllib.request.Request(
- url,
- method = "HEAD",
- headers = {"User-Agent": "unsloth-studio-llama-prebuilt"},
- )
- try:
- with _URL_OPENER.open(request, timeout = 30) as response:
- final_url = response.geturl()
- except urllib.error.HTTPError as exc:
- if exc.code == 404:
- return None
- raise
- marker = "/releases/tag/"
- index = final_url.find(marker)
- if index == -1:
- return None
- tag = urllib.parse.unquote(final_url[index + len(marker) :]).strip("/")
- return tag or None
+ return _core.download_host_latest_release_tag(_OPS, repo)
def _fetch_download_host_json(url: str) -> Any:
- # Public CDN asset: plain unauthenticated GET, not the rate-limited API.
- data = download_bytes(
- url,
- timeout = 30,
- headers = {"User-Agent": "unsloth-studio-llama-prebuilt"},
- )
- return json.loads(data.decode("utf-8"))
+ return _core.fetch_download_host_json(_OPS, url)
def _download_host_resolved_release(repo: str) -> ResolvedPublishedRelease | None:
@@ -3292,38 +2590,14 @@ def pick_windows_cuda_runtime(host: HostInfo) -> str | None:
return None
-def compatible_linux_runtime_lines(host: HostInfo) -> list[str]:
- if not host.driver_cuda_version:
- return []
- major, _minor = host.driver_cuda_version
- if major < _MIN_CUDA_MAJOR:
- return []
- return _cuda_runtime_lines_for_major(major)
+compatible_linux_runtime_lines = _core.compatible_linux_runtime_lines
-def windows_runtime_line_info() -> dict[str, tuple[str, ...]]:
- # Generated per CUDA major (newest first) so a new toolkit is detected
- # without a code change while the cudart64_<major>.dll naming holds.
- return {
- f"cuda{m}": (
- f"cudart64_{m}*.dll",
- f"cublas64_{m}*.dll",
- f"cublasLt64_{m}*.dll",
- )
- for m in range(_MAX_PROBE_CUDA_MAJOR, _MIN_CUDA_MAJOR - 1, -1)
- }
+windows_runtime_line_info = _core.windows_runtime_line_info
def detected_windows_runtime_lines() -> tuple[list[str], dict[str, list[str]]]:
- dirs = windows_runtime_dirs()
- detected: list[str] = []
- runtime_dirs: dict[str, list[str]] = {}
- for runtime_line, required_patterns in windows_runtime_line_info().items():
- matching_dirs = windows_runtime_dirs_for_patterns(required_patterns, dirs)
- if matching_dirs:
- detected.append(runtime_line)
- runtime_dirs[runtime_line] = matching_dirs
- return detected, runtime_dirs
+ return _core.detected_windows_runtime_lines(_OPS)
def compatible_windows_runtime_lines(host: HostInfo) -> list[str]:
@@ -3337,68 +2611,8 @@ def compatible_windows_runtime_lines(host: HostInfo) -> list[str]:
return _cuda_runtime_lines_for_major(major)
-def runtime_line_from_cuda_version(cuda_version: str | None) -> str | None:
- if not cuda_version:
- return None
- raw = str(cuda_version).strip()
- if not raw:
- return None
- major, _, _ = raw.partition(".")
- if major == "12":
- return "cuda12"
- if major == "13":
- return "cuda13"
- return None
-
-
-def detect_torch_cuda_runtime_preference(host: HostInfo) -> CudaRuntimePreference:
- selection_log: list[str] = []
- if host.is_macos:
- selection_log.append("torch_cuda_preference: skipped on macOS")
- return CudaRuntimePreference(runtime_line = None, selection_log = selection_log)
- if not (host.has_usable_nvidia and (host.is_linux or host.is_windows)):
- selection_log.append(
- "torch_cuda_preference: skipped because CUDA host prerequisites were not met"
- )
- return CudaRuntimePreference(runtime_line = None, selection_log = selection_log)
-
- try:
- import torch
- except Exception as exc:
- selection_log.append(f"torch_cuda_preference: import failed: {exc}")
- return CudaRuntimePreference(runtime_line = None, selection_log = selection_log)
-
- cuda_version = getattr(getattr(torch, "version", None), "cuda", None)
- if not isinstance(cuda_version, str) or not cuda_version.strip():
- selection_log.append(
- "torch_cuda_preference: torch.version.cuda missing; skipping Torch shortcut"
- )
- return CudaRuntimePreference(runtime_line = None, selection_log = selection_log)
-
- try:
- cuda_available = bool(torch.cuda.is_available())
- except Exception as exc:
- selection_log.append(f"torch_cuda_preference: torch.cuda.is_available() failed: {exc}")
- return CudaRuntimePreference(runtime_line = None, selection_log = selection_log)
-
- if not cuda_available:
- selection_log.append(
- "torch_cuda_preference: torch.cuda.is_available() returned False; falling back to normal selection"
- )
- return CudaRuntimePreference(runtime_line = None, selection_log = selection_log)
-
- runtime_line = runtime_line_from_cuda_version(cuda_version)
- if runtime_line is None:
- selection_log.append(
- f"torch_cuda_preference: unsupported torch.version.cuda={cuda_version}; falling back to normal selection"
- )
- return CudaRuntimePreference(runtime_line = None, selection_log = selection_log)
-
- selection_log.append(
- "torch_cuda_preference: selected runtime_line="
- f"{runtime_line} from torch.version.cuda={cuda_version}"
- )
- return CudaRuntimePreference(runtime_line = runtime_line, selection_log = selection_log)
+runtime_line_from_cuda_version = _core.runtime_line_from_cuda_version
+detect_torch_cuda_runtime_preference = _core.detect_torch_cuda_runtime_preference
def windows_cuda_attempts(
@@ -3569,18 +2783,8 @@ def _windows_cuda_attempt_covers_blackwell(
return attempt.max_sm is not None and attempt.max_sm >= _BLACKWELL_MIN_SM
-def _host_is_blackwell(host: HostInfo) -> bool:
- caps = normalize_compute_caps(host.compute_caps)
- return bool(caps) and int(caps[-1]) >= _BLACKWELL_MIN_SM
-
-
-def _blackwell_min_toolkit_for_host(host: HostInfo) -> tuple[int, int]:
- """Minimum CUDA toolkit this Blackwell host needs: 12.8 for the family,
- 12.9 if any of its SMs is sm_103/sm_121 (no native target before 12.9)."""
- req = _BLACKWELL_MIN_TOOLKIT
- for sm in normalize_compute_caps(host.compute_caps):
- req = max(req, _BLACKWELL_SM_MIN_TOOLKIT.get(int(sm), _BLACKWELL_MIN_TOOLKIT))
- return req
+_host_is_blackwell = _core.host_is_blackwell
+_blackwell_min_toolkit_for_host = _core.blackwell_min_toolkit_for_host
def _drop_blackwell_incapable_windows_cuda(
@@ -4204,169 +3408,7 @@ def resolve_release_asset_choice(
)
-def extract_archive(archive_path: Path, destination: Path) -> None:
- def safe_extract_path(base: Path, member_name: str) -> Path:
- normalized = member_name.replace("\\", "/")
- member_path = Path(normalized)
- if member_path.is_absolute():
- raise PrebuiltFallback(f"archive member used an absolute path: {member_name}")
-
- target = (base / member_path).resolve()
- base_resolved = base.resolve()
- try:
- target.relative_to(base_resolved)
- except ValueError as exc:
- raise PrebuiltFallback(f"archive member escaped destination: {member_name}") from exc
- return target
-
- def _try_repair_missing_slash(
- member_name: str, link_name: str, archive_names: set[str]
- ) -> str | None:
- """Some upstream llama.cpp Mac releases (e.g. b9165, b9169) ship
- symlinks whose linkname is missing the directory separator AND
- the leading character of the file basename between the
- top-level dir and the rest of the path:
-
- llama-b9165/libggml-rpc.0.dylib -> llama-b9165ibggml-rpc.0.11.1.dylib
-
- That cannot be resolved as written. Detect the pattern
- (linkname starts with the top-level dir name but no following
- slash) and search archive entries under that dir for a real
- file whose basename ends with the mangled suffix. Only accept
- when the suffix uniquely identifies a real archive entry.
- Returns the corrected linkname expressed relative to the
- member's parent directory -- callers join it with
- `target.parent`, so a full `top/file` path would double the
- prefix into `top/top/file`."""
- if "/" not in member_name or "/" in link_name:
- return None
- top, _, _ = member_name.partition("/")
- if not link_name.startswith(top) or len(link_name) <= len(top):
- return None
- bad_suffix = link_name[len(top) :]
- if not bad_suffix or bad_suffix.startswith("/"):
- return None
- prefix = f"{top}/"
- candidates = [
- name
- for name in archive_names
- if name.startswith(prefix)
- and "/" not in name[len(prefix) :]
- and name[len(prefix) :].endswith(bad_suffix)
- ]
- if len(candidates) != 1:
- return None
- # Strip the top-level dir so the caller's `target.parent / Path(...)`
- # composition resolves inside the staging dir, not into a duplicate
- # `top/top/...` path.
- return candidates[0][len(prefix) :]
-
- def safe_link_target(
- base: Path, member_name: str, link_name: str, target: Path, archive_names: set[str]
- ) -> tuple[str, Path]:
- normalized = link_name.replace("\\", "/")
- repaired = _try_repair_missing_slash(member_name, normalized, archive_names)
- if repaired is not None:
- normalized = repaired
- link_path = Path(normalized)
- if link_path.is_absolute():
- raise PrebuiltFallback(
- f"archive link used an absolute target: {member_name} -> {link_name}"
- )
- if not normalized:
- raise PrebuiltFallback(f"archive link used an empty target: {member_name}")
-
- resolved = (target.parent / link_path).resolve()
- base_resolved = base.resolve()
- try:
- resolved.relative_to(base_resolved)
- except ValueError as exc:
- raise PrebuiltFallback(
- f"archive link escaped destination: {member_name} -> {link_name}"
- ) from exc
- return normalized, resolved
-
- def extract_zip_safely(source: Path, base: Path) -> None:
- with zipfile.ZipFile(source) as archive:
- for member in archive.infolist():
- target = safe_extract_path(base, member.filename)
- mode = (member.external_attr >> 16) & 0o170000
- if mode == 0o120000:
- raise PrebuiltFallback(
- f"zip archive contained a symlink entry: {member.filename}"
- )
- if member.is_dir():
- target.mkdir(parents = True, exist_ok = True)
- continue
- target.parent.mkdir(parents = True, exist_ok = True)
- with archive.open(member, "r") as src, target.open("wb") as dst:
- shutil.copyfileobj(src, dst)
-
- def extract_tar_safely(source: Path, base: Path) -> None:
- pending_links: list[tuple[tarfile.TarInfo, Path]] = []
- archive_names: set[str] = set()
- with tarfile.open(source, "r:gz") as archive:
- for member in archive.getmembers():
- archive_names.add(member.name)
- target = safe_extract_path(base, member.name)
- if member.isdir():
- target.mkdir(parents = True, exist_ok = True)
- continue
- if member.islnk() or member.issym():
- pending_links.append((member, target))
- continue
- if not member.isfile():
- raise PrebuiltFallback(
- f"tar archive contained an unsupported entry: {member.name}"
- )
- target.parent.mkdir(parents = True, exist_ok = True)
- extracted = archive.extractfile(member)
- if extracted is None:
- raise PrebuiltFallback(f"tar archive entry could not be read: {member.name}")
- with extracted, target.open("wb") as dst:
- shutil.copyfileobj(extracted, dst)
-
- unresolved = list(pending_links)
- while unresolved:
- next_round: list[tuple[tarfile.TarInfo, Path]] = []
- progressed = False
- for member, target in unresolved:
- normalized_link, resolved_target = safe_link_target(
- base, member.name, member.linkname, target, archive_names
- )
- if not resolved_target.exists() and not resolved_target.is_symlink():
- next_round.append((member, target))
- continue
- if resolved_target.is_dir():
- raise PrebuiltFallback(
- f"archive link targeted a directory: {member.name} -> {member.linkname}"
- )
-
- target.parent.mkdir(parents = True, exist_ok = True)
- if target.exists() or target.is_symlink():
- target.unlink()
-
- if member.issym():
- target.symlink_to(normalized_link)
- else:
- shutil.copy2(resolved_target, target)
- progressed = True
-
- if not progressed:
- details = ", ".join(
- f"{member.name} -> {member.linkname}" for member, _ in next_round
- )
- raise PrebuiltFallback(f"tar archive contained unresolved link entries: {details}")
- unresolved = next_round
-
- destination.mkdir(parents = True, exist_ok = True)
- if archive_path.name.endswith(".zip"):
- extract_zip_safely(archive_path, destination)
- return
- if archive_path.name.endswith(".tar.gz"):
- extract_tar_safely(archive_path, destination)
- return
- raise PrebuiltFallback(f"unsupported archive format: {archive_path.name}")
+extract_archive = _core.extract_archive
def copy_globs(
@@ -4778,83 +3820,8 @@ def metadata_patterns_for_choice(choice: AssetChoice) -> list[str]:
return patterns
-@contextmanager
-def install_lock(lock_path: Path) -> Iterator[None]:
- lock_path.parent.mkdir(parents = True, exist_ok = True)
-
- if FileLock is None:
- # Fallback: exclusive file creation as a simple lock.
- # Write our PID so stale locks from crashed processes can be detected.
- fd: int | None = None
- deadline = time.monotonic() + INSTALL_LOCK_TIMEOUT_SECONDS
- while True:
- try:
- fd = os.open(str(lock_path), os.O_CREAT | os.O_EXCL | os.O_RDWR)
- try:
- os.write(fd, f"{os.getpid()}\n".encode())
- os.fsync(fd)
- except Exception:
- os.close(fd)
- fd = None
- lock_path.unlink(missing_ok = True)
- raise
- break
- except FileExistsError:
- # Check if the holder process is still alive
- stale = False
- try:
- raw = lock_path.read_text().strip()
- except FileNotFoundError:
- # Lock vanished between our open attempt and read -- retry
- continue
- if not raw:
- # File exists but PID not yet written -- another process
- # just created it. Wait briefly for the write to land.
- if time.monotonic() >= deadline:
- raise BusyInstallConflict(
- f"timed out after {INSTALL_LOCK_TIMEOUT_SECONDS}s waiting for concurrent install lock: {lock_path}"
- )
- time.sleep(0.1)
- continue
- try:
- holder_pid = int(raw)
- os.kill(holder_pid, 0) # signal 0 = existence check
- except ValueError:
- # PID unreadable (corrupted file)
- stale = True
- except ProcessLookupError:
- # Process is dead
- stale = True
- except PermissionError:
- # Process is alive but owned by another user -- not stale
- pass
- if stale:
- lock_path.unlink(missing_ok = True)
- continue
- if time.monotonic() >= deadline:
- raise BusyInstallConflict(
- f"timed out after {INSTALL_LOCK_TIMEOUT_SECONDS}s waiting for concurrent install lock: {lock_path}"
- )
- time.sleep(0.5)
- try:
- yield
- finally:
- if fd is not None:
- os.close(fd)
- lock_path.unlink(missing_ok = True)
- return
-
- try:
- with FileLock(lock_path, timeout = INSTALL_LOCK_TIMEOUT_SECONDS):
- yield
- except FileLockTimeout as exc:
- raise BusyInstallConflict(
- f"timed out after {INSTALL_LOCK_TIMEOUT_SECONDS}s waiting for concurrent install lock: {lock_path}"
- ) from exc
-
-
-def install_lock_path(install_dir: Path) -> Path:
- return install_dir.parent / f".{install_dir.name}.install.lock"
+install_lock = _core.install_lock
+install_lock_path = _core.install_lock_path
def install_staging_root(install_dir: Path) -> Path:
@@ -5441,18 +4408,7 @@ _CPU_TYPE_X86_64 = 0x01000007
_CPU_TYPE_ARM64 = 0x0100000C
-def parse_macos_version(value: str | None) -> tuple[int, int] | None:
- """Parse a macOS product version string into (major, minor).
-
- Handles "14.7.1", "15.5", "26.0" and bare "26". Returns None when the
- value is empty or cannot be parsed (callers then defer to runtime
- validation rather than rejecting every prebuilt)."""
- if not value:
- return None
- match = re.match(r"\s*(\d+)(?:\.(\d+))?", str(value))
- if not match:
- return None
- return int(match.group(1)), int(match.group(2) or 0)
+parse_macos_version = _core.parse_macos_version
def host_supports_macos_minos(host: HostInfo, minos: tuple[int, int] | None) -> bool:
@@ -6623,6 +5579,52 @@ def load_prebuilt_metadata(install_dir: Path) -> dict[str, Any] | None:
return payload
+def default_managed_llama_dir() -> Path:
+ """The managed llama.cpp install root, mirroring setup.sh and the updater:
+ the UNSLOTH_LLAMA_CPP_PATH override, else <custom studio home>/llama.cpp,
+ else the legacy ~/.unsloth/llama.cpp."""
+ override = (os.environ.get("UNSLOTH_LLAMA_CPP_PATH") or "").strip()
+ if override:
+ return Path(override).expanduser()
+ home = (os.environ.get("UNSLOTH_STUDIO_HOME") or os.environ.get("STUDIO_HOME") or "").strip()
+ if home:
+ root = Path(home).expanduser()
+ legacy_studio = Path.home() / ".unsloth" / "studio"
+ try:
+ is_legacy = root.resolve() == legacy_studio.resolve()
+ except (OSError, ValueError):
+ is_legacy = root == legacy_studio
+ if not is_legacy:
+ return root / "llama.cpp"
+ return Path.home() / ".unsloth" / "llama.cpp"
+
+
+def installed_llama_runtime(install_dir: Path | None = None) -> tuple[Path, str, str] | None:
+ """The completed managed llama.cpp prebuilt install, or None.
+
+ Returns (runtime bin dir holding the ggml libraries, installed release tag,
+ bundle profile). install_whisper_prebuilt.py reads this to pair slim whisper
+ bundles with the ggml runtime the llama install already provides; tests pass
+ an explicit ``install_dir``.
+ """
+ root = install_dir if install_dir is not None else default_managed_llama_dir()
+ metadata = load_prebuilt_metadata(root)
+ if metadata is None:
+ return None
+ release_tag = metadata.get("release_tag")
+ if not isinstance(release_tag, str) or not release_tag:
+ return None
+ # Same layout install_runtime_dir() derives; a marker on disk always
+ # belongs to this host, so the running OS picks the variant.
+ bin_dir = root / "build" / "bin"
+ if os.name == "nt":
+ bin_dir = bin_dir / "Release"
+ if not bin_dir.is_dir():
+ return None
+ profile = metadata.get("bundle_profile")
+ return bin_dir, release_tag, profile if isinstance(profile, str) else ""
+
+
def runtime_payload_health_groups(choice: AssetChoice) -> list[list[str]]:
if choice.install_kind in {"linux-cpu", "linux-arm64"}:
return [
diff --git a/studio/install_whisper_prebuilt.py b/studio/install_whisper_prebuilt.py
new file mode 100644
index 00000000000..1c81ad61059
--- /dev/null
+++ b/studio/install_whisper_prebuilt.py
@@ -0,0 +1,1377 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Cross-platform whisper.cpp (whisper-server) prebuilt installer for Unsloth Studio.
+
+Downloads a per-platform whisper.cpp bundle published by the Unsloth fork
+(``unslothai/whisper.cpp``) into an isolated ``<UNSLOTH_HOME>/whisper.cpp``,
+never a system whisper.cpp. The canonical install target matches the
+sidecar/build-script contract in ``stt_ggml_sidecar.py``:
+
+ <install-dir>/build/bin/whisper-server (Unix)
+ <install-dir>/build/bin/Release/whisper-server.exe (Windows)
+
+Bundles are dynamically linked: ``whisper-server`` needs ``libwhisper``,
+``libggml*`` and any GPU backend libraries. The binaries carry ``RUNPATH=$ORIGIN``
+so the installer co-locates every shared library from the archive into the same
+``build/bin`` directory and marks the server executable on Unix.
+
+Archives are verified against the release's own ``whisper-prebuilt-sha256.json``
+checksum index (same model as ``install_llama_prebuilt.py``). An asset absent
+from the index, or a release without it, fails closed (setup reports the prebuilt
+unavailable and local dictation uses Transformers STT). Being a same-origin
+checksum it proves integrity, not authenticity; pair the release with GitHub
+artifact attestations for provenance.
+
+Release resolution prefers the download host (``github.com/<repo>/releases/...``),
+fetching the manifest + checksum index with zero ``api.github.com`` calls (that
+API is rate-limited to 60 req/hour unauthenticated); the GitHub API is only a
+fallback on a 404 / malformed asset.
+
+The whole component-agnostic flow (verified downloads, safe extraction, the
+install lock, release resolution, checksum-index handling, the install driver,
+the resolve probe) lives in ``prebuilt_core.py`` and is shared with
+``install_llama_prebuilt.py``. This module keeps only the whisper specifics: the
+host mapping, install-tree layout, slim pairing with the installed llama.cpp ggml
+runtime, the pinned-release CPU escape hatch, the marker filename, and the CLI.
+Every retained public name is a thin wrapper tests can monkeypatch so the core
+observes the patch.
+
+Selection is slim-only for current releases (v1.9.1-unsloth.2+): every published
+bundle is a slim (ggml-less) whisper paired to the llama.cpp prebuilt, which
+provides all ggml backends. The per-accelerator fat selection chain was deleted
+with the fat bundles; the one legacy shape still honored is the published fat CPU
+bundle of an explicitly pinned pre-slim release.
+
+Mirrors ``install_node_prebuilt.py`` / ``install_llama_prebuilt.py``. Exit codes:
+0 success (or already current), 1 error, 2 incompatible paired release, 3 busy. A re-run
+that already matches logs "already matches" and returns 0 without downloading
+(the scripts grep it).
+"""
+
+from __future__ import annotations
+
+import argparse
+import os
+import re
+import shutil
+import subprocess
+import sys
+from dataclasses import dataclass, replace
+from pathlib import Path
+from typing import Any
+
+# Put studio/ on sys.path so install_llama_prebuilt / prebuilt_core resolve
+# whether run as a script (from any cwd) or imported by the tests.
+_STUDIO_DIR = os.path.dirname(os.path.abspath(__file__))
+if _STUDIO_DIR not in sys.path:
+ sys.path.insert(0, _STUDIO_DIR)
+
+import install_llama_prebuilt as llama # noqa: E402
+import prebuilt_core as core # noqa: E402
+
+# Shared machinery re-exported as module globals; the wrappers below resolve
+# these by bare name at call time so tests can monkeypatch them here.
+PrebuiltFallback = core.PrebuiltFallback
+BusyInstallConflict = core.BusyInstallConflict
+auth_headers = llama.auth_headers
+download_bytes = llama.download_bytes
+download_file = llama.download_file
+fetch_json = llama.fetch_json
+sha256_file = core.sha256_file
+_URL_OPENER = core._URL_OPENER
+install_lock = core.install_lock
+install_lock_path = core.install_lock_path
+parse_macos_version = core.parse_macos_version
+release_asset_map = core.release_asset_map
+release_asset_download_url = core.release_asset_download_url
+compute_install_fingerprint = core.compute_install_fingerprint
+artifact_coverage = core.artifact_coverage
+emit_resolver_output = core.emit_resolver_output
+_valid_sha256 = core.valid_sha256
+_swap_into_place = core.swap_into_place
+InstallSelection = core.InstallSelection
+ReleaseBundle = core.ReleaseBundle
+llama_detect_host = llama.detect_host
+installed_llama_runtime = llama.installed_llama_runtime
+
+# Late-binding seam for prebuilt_core: name lookups hit this module's globals
+# first (so monkeypatches apply), then the core defaults.
+_OPS = core.ModuleOps(globals())
+
+
+# Resolver mode keeps stdout to the JSON payload only (setup.sh parses it);
+# main() flips this on for the install path so setup surfaces progress.
+_LOG_TO_STDOUT = False
+
+
+class ReleaseCompatibilityError(PrebuiltFallback):
+ """A valid slim release cannot pair with this host's installed runtime."""
+
+
+def log(message: str) -> None:
+ print(f"[whisper-prebuilt] {message}", file = sys.stdout if _LOG_TO_STDOUT else sys.stderr)
+
+
+EXIT_SUCCESS = 0
+EXIT_ERROR = 1
+EXIT_INCOMPATIBLE = 2
+EXIT_BUSY = 3
+
+COMPONENT = "whisper.cpp"
+SCHEMA_VERSION = 1
+USER_AGENT = "unsloth-studio-whisper-prebuilt"
+
+DEFAULT_PUBLISHED_REPO = "unslothai/whisper.cpp"
+# Release assets published by the fork's prebuilt CI.
+MANIFEST_ASSET_NAME = "whisper-prebuilt-manifest.json"
+SHA256_ASSET_NAME = "whisper-prebuilt-sha256.json"
+
+METADATA_FILENAME = "UNSLOTH_WHISPER_PREBUILT_INFO.json"
+
+# Backends the installer can select: accelerator identities for the slim pairing
+# (which llama ggml module must exist) and the marker. Only "cpu" can match a fat
+# artifact (the pinned pre-slim escape hatch).
+SUPPORTED_BACKENDS = ("cpu", "cuda", "metal", "vulkan", "rocm")
+
+# Fallback the core applies on a GPU-selection miss: retry with cpu so the slim
+# bundle can pair via the llama cpu modules, or -- on a pinned pre-slim release --
+# the published fat CPU bundle installs. A miss is an install error unless the
+# valid slim release specifically requires a different paired llama release.
+FALLBACK_BACKEND = "cpu"
+
+# Backends whose slim (ggml-less) whisper bundle can ride the installed llama.cpp
+# prebuilt's ggml runtime. All are eligible: the next whisper release ships only
+# slim bundles, so cpu and metal pair like the GPUs do.
+SLIM_ELIGIBLE_BACKENDS = ("cpu", "cuda", "metal", "rocm", "vulkan")
+
+# ggml backend module the llama bin dir must provide per accelerator, keyed by
+# asset os token, following llama's bundle layout / health globs. A backend with
+# no glob for the host os (metal off macOS) is never slim there. llama's x64 cpu
+# bundles ship per-arch libggml-cpu-<variant> modules, macOS a single
+# libggml-cpu; the cpu globs cover both.
+SLIM_BACKEND_MODULE_GLOBS = {
+ "cpu": {
+ "linux": "libggml-cpu*.so*",
+ "windows": "ggml-cpu*.dll",
+ "macos": "libggml-cpu*.dylib",
+ },
+ "cuda": {"linux": "libggml-cuda.so*", "windows": "ggml-cuda.dll"},
+ "metal": {"macos": "libggml-metal*.dylib"},
+ "rocm": {"linux": "libggml-hip.so*", "windows": "*hip*.dll"},
+ "vulkan": {"linux": "libggml-vulkan.so*", "windows": "ggml-vulkan.dll"},
+}
+
+# Everything the slim wiring mirrors from the llama bin dir: the core ggml
+# sonames plus every dlopen'd backend module (CPU variants included). libggml*
+# matches .so and .dylib alike; ggml*.dll covers Windows. libomp*.dll rides along
+# because llama's clang-built windows-arm64 ggml-base.dll imports
+# libomp140.aarch64.dll, shipped in the llama bundle but never a system DLL, so
+# the loader needs it next to whisper-server.exe (MSVC x64 uses System32
+# vcomp140.dll; Linux ggml needs system libgomp.so.1, which llama already requires).
+SLIM_GGML_LIBRARY_GLOBS = ("libggml*", "ggml*.dll", "libomp*.dll")
+SLIM_ROCM_LIBRARY_GLOBS = (
+ "libamd*.so*",
+ "libhip*.so*",
+ "libhsa*.so*",
+ "libroc*.so*",
+)
+SLIM_ROCM_RUNTIME_DIRS = ("hipblaslt", "rocblas")
+SLIM_RUNTIME_WIRING_VERSION = 2
+
+INSTALL_STAGING_ROOT_NAME = ".staging"
+
+# Master switch for the staged runtime smoke test (start whisper-server + a tiny
+# transcription) before the atomic activate. Off by default so a bundle whose GPU
+# forward pass JIT-compiles kernels does not stall every install; the check and
+# its CPU-asset retry stay intact -- set True to re-enable.
+_RUN_STAGED_PREBUILT_VALIDATION = False
+
+
+# ── Host detection (probes shared with install_llama_prebuilt) ──
+@dataclass(frozen = True)
+class HostInfo:
+ system: str # platform.system()
+ machine: str # lowered platform.machine()
+ whisper_os: str # asset token: linux | macos | windows
+ whisper_arch: str # asset token: x64 | arm64
+ archive_ext: str # .tar.gz | .zip
+ is_windows: bool
+ is_macos: bool
+ is_apple_silicon: bool
+ has_usable_nvidia: bool = False
+ has_rocm: bool = False
+ rocm_gfx: str | None = None
+ # (major, minor) from platform.mac_ver(); None off macOS or if unparseable.
+ # Enforces a macOS artifact's min_os so we never pick a bundle that cannot
+ # load on this OS version.
+ macos_version: tuple[int, int] | None = None
+
+
+def host_from_llama(base: Any) -> HostInfo:
+ """Map install_llama_prebuilt's detected host onto the whisper asset tokens.
+ Raises PrebuiltFallback on an unsupported OS/arch."""
+ system = base.system
+ machine = base.machine.lower()
+ if system == "Linux":
+ whisper_os = "linux"
+ elif system == "Darwin":
+ whisper_os = "macos"
+ elif system == "Windows":
+ whisper_os = "windows"
+ else:
+ raise PrebuiltFallback(f"unsupported operating system for whisper.cpp prebuilt: {system}")
+
+ if machine in {"x86_64", "amd64", "x64"}:
+ whisper_arch = "x64"
+ elif machine in {"arm64", "aarch64"}:
+ whisper_arch = "arm64"
+ else:
+ raise PrebuiltFallback(f"unsupported CPU architecture for whisper.cpp prebuilt: {machine}")
+
+ return HostInfo(
+ system = system,
+ machine = machine,
+ whisper_os = whisper_os,
+ whisper_arch = whisper_arch,
+ archive_ext = ".zip" if base.is_windows else ".tar.gz",
+ is_windows = base.is_windows,
+ is_macos = base.is_macos,
+ is_apple_silicon = base.is_macos and whisper_arch == "arm64",
+ has_usable_nvidia = base.has_usable_nvidia,
+ has_rocm = base.has_rocm,
+ rocm_gfx = base.rocm_gfx_target,
+ macos_version = base.macos_version,
+ )
+
+
+def detect_host() -> HostInfo:
+ return host_from_llama(llama_detect_host())
+
+
+def apply_host_overrides(
+ host: HostInfo,
+ *,
+ has_rocm: bool = False,
+ rocm_gfx: str | None = None,
+ force_cpu: bool = False,
+) -> HostInfo:
+ """Apply CLI overrides (setup forwards hardware hints) onto a detected host."""
+ if force_cpu:
+ return replace(
+ host,
+ has_usable_nvidia = False,
+ has_rocm = False,
+ rocm_gfx = None,
+ is_apple_silicon = False,
+ )
+ updates: dict[str, Any] = {}
+ if has_rocm or rocm_gfx:
+ # --rocm-gfx implies --has-rocm (llama parity); otherwise the host stays on
+ # its CUDA/CPU path and never picks the ROCm bundle. Drop CUDA detection too.
+ updates["has_rocm"] = True
+ updates["has_usable_nvidia"] = False
+ if rocm_gfx:
+ updates["rocm_gfx"] = rocm_gfx
+ return replace(host, **updates) if updates else host
+
+
+def host_platform_tokens(host: HostInfo) -> tuple[str, str]:
+ """Canonical (os, arch) asset tokens the core uses for matching/reporting."""
+ return host.whisper_os, host.whisper_arch
+
+
+# ── Backend selection ──
+def auto_detect_backend(host: HostInfo) -> str:
+ return core.auto_detect_backend(_OPS, host)
+
+
+def resolve_backend(host: HostInfo, requested: str | None, *, cpu_fallback: bool) -> str:
+ return core.resolve_backend(_OPS, host, requested, cpu_fallback = cpu_fallback)
+
+
+# ── Asset naming (pure, unit tested) ──
+def whisper_asset_name(release_tag: str, host: HostInfo, accel: str) -> str:
+ """e.g. whisper-v1.9.1-unsloth.1-linux-x64-cpu.tar.gz.
+
+ `accel` is the asset-filename accelerator token (cpu, metal, cuda12, ...),
+ finer-grained than the coarse backend. An install's authoritative asset name
+ comes from the release manifest; this constructor is for defaults/diagnostics.
+ """
+ tag = release_tag if release_tag.startswith("v") else f"v{release_tag}"
+ return f"whisper-{tag}-{host.whisper_os}-{host.whisper_arch}-{accel}{host.archive_ext}"
+
+
+# ── Manifest (release-side artifact catalogue; generic parser in the core) ──
+def validate_schema_version(payload: dict[str, Any], *, label: str) -> None:
+ core.validate_schema_version(
+ payload, label = label, schema_version = SCHEMA_VERSION, error = PrebuiltFallback
+ )
+
+
+def parse_manifest(payload: Any, *, label: str = MANIFEST_ASSET_NAME) -> dict[str, Any]:
+ return core.parse_manifest(_OPS, payload, label = label)
+
+
+def _macos_min_os_ok(host: HostInfo, min_os: Any) -> bool:
+ return core.macos_min_os_ok(_OPS, host, min_os)
+
+
+def macos_min_os_ok(host: HostInfo, min_os: Any) -> bool:
+ return _macos_min_os_ok(host, min_os)
+
+
+def _artifacts_for_host(
+ manifest: dict[str, Any], host: HostInfo, backend: str
+) -> list[dict[str, Any]]:
+ return core.artifacts_for_host(_OPS, manifest, host, backend)
+
+
+def artifacts_for_host(
+ manifest: dict[str, Any], host: HostInfo, backend: str
+) -> list[dict[str, Any]]:
+ return _artifacts_for_host(manifest, host, backend)
+
+
+# ── Slim selection (paired with the installed llama.cpp ggml runtime) ──
+def slim_pairing_for_artifact(
+ artifact: dict[str, Any], host: HostInfo, backend: str
+) -> tuple[Path, str] | None:
+ """(llama bin dir, llama release tag) when the installed llama runtime can
+ back this slim artifact, else None. Each failed gate logs why; the caller
+ then retries via CPU or reports the prebuilt unavailable."""
+ asset = artifact.get("asset")
+ runtime = installed_llama_runtime()
+ if runtime is None:
+ log(f"slim_selection: {asset} skipped: no managed llama.cpp prebuilt install")
+ return None
+ llama_bin_dir, llama_tag, _profile = runtime
+ requires_tag = artifact.get("requires_llama_tag")
+ if not isinstance(requires_tag, str) or requires_tag != llama_tag:
+ log(
+ f"slim_selection: {asset} skipped: installed llama tag {llama_tag!r} "
+ f"!= required {requires_tag!r}"
+ )
+ return None
+ sonames = artifact.get("requires_ggml_sonames")
+ if not isinstance(sonames, list) or not sonames:
+ log(f"slim_selection: {asset} skipped: manifest lists no requires_ggml_sonames")
+ return None
+ missing = [str(name) for name in sonames if not (llama_bin_dir / str(name)).is_file()]
+ if missing:
+ log(f"slim_selection: {asset} skipped: llama runtime missing {', '.join(missing)}")
+ return None
+ module_glob = SLIM_BACKEND_MODULE_GLOBS.get(backend, {}).get(host.whisper_os)
+ if module_glob is None:
+ log(f"slim_selection: {asset} skipped: no {backend} ggml module on {host.whisper_os}")
+ return None
+ if not any(path.is_file() for path in llama_bin_dir.glob(module_glob)):
+ log(f"slim_selection: {asset} skipped: llama runtime has no {module_glob} module")
+ return None
+ log(f"slim_selection: selected {asset} paired with llama {llama_tag} at {llama_bin_dir}")
+ return llama_bin_dir, llama_tag
+
+
+def select_slim_artifact(
+ manifest: dict[str, Any], host: HostInfo, backend: str
+) -> dict[str, Any] | None:
+ """The paired slim artifact for any backend (cpu and metal included), or None.
+ Slim assets carry backend "slim" so the CPU escape hatch's fat os/arch/backend
+ matching never sees them. When the release ships slim candidates but none
+ pair, log the actionable reason: on a slim-only release nothing else selects,
+ setup reports the prebuilt unavailable, and local dictation stays on
+ Transformers STT."""
+ if backend not in SLIM_ELIGIBLE_BACKENDS:
+ return None
+ os_token, arch_token = host_platform_tokens(host)
+ candidates = [
+ artifact
+ for artifact in manifest.get("artifacts", [])
+ if artifact.get("os") == os_token
+ and artifact.get("arch") == arch_token
+ and artifact.get("backend") == "slim"
+ and artifact.get("install_kind") == "slim"
+ and (not host.is_macos or _macos_min_os_ok(host, artifact.get("min_os")))
+ ]
+ for artifact in candidates:
+ if slim_pairing_for_artifact(artifact, host, backend) is not None:
+ return artifact
+ if candidates:
+ required_tag = candidates[0].get("requires_llama_tag")
+ log(f"slim bundle requires llama.cpp {required_tag}; install or update llama.cpp first")
+ return None
+
+
+def select_artifact(
+ manifest: dict[str, Any], host: HostInfo, backend: str
+) -> dict[str, Any] | None:
+ """Slim-only: every backend resolves to the paired slim artifact. The one
+ legacy shape still honored is the published fat CPU bundle of a pinned pre-slim
+ release, reached by a GPU-backend miss through the core's CPU fallback retry.
+ No other fat artifact is ever selected."""
+ slim = select_slim_artifact(manifest, host, backend)
+ if slim is not None:
+ return slim
+ if backend != "cpu":
+ return None
+ candidates = _artifacts_for_host(manifest, host, "cpu")
+ return candidates[0] if candidates else None
+
+
+def select_artifact_with_cpu_fallback(
+ manifest: dict[str, Any], host: HostInfo, backend: str
+) -> tuple[dict[str, Any], str, bool]:
+ try:
+ return core.select_artifact_with_fallback(_OPS, manifest, host, backend)
+ except PrebuiltFallback as exc:
+ reason = _slim_release_incompatibility(manifest, host)
+ if reason is not None:
+ raise ReleaseCompatibilityError(reason) from exc
+ raise
+
+
+def _slim_release_incompatibility(manifest: dict[str, Any], host: HostInfo) -> str | None:
+ """Explain a valid platform slim release that this runtime cannot pair.
+
+ This intentionally excludes missing files, malformed manifests, checksum
+ failures, and unsupported platforms. Those are operational errors and must
+ never be converted into the update path's kept-existing-runtime success.
+ """
+ os_token, arch_token = host_platform_tokens(host)
+ candidates = [
+ artifact
+ for artifact in manifest.get("artifacts", [])
+ if artifact.get("os") == os_token
+ and artifact.get("arch") == arch_token
+ and artifact.get("backend") == "slim"
+ and artifact.get("install_kind") == "slim"
+ ]
+ if not candidates:
+ return None
+ os_compatible = [
+ artifact
+ for artifact in candidates
+ if not host.is_macos or _macos_min_os_ok(host, artifact.get("min_os"))
+ ]
+ if not os_compatible:
+ required = candidates[0].get("min_os")
+ return f"slim bundle requires macOS {required}; this host is older"
+ runtime = installed_llama_runtime()
+ if runtime is None:
+ return None
+ installed_tag = runtime[1]
+ required_tags = {
+ artifact.get("requires_llama_tag")
+ for artifact in os_compatible
+ if isinstance(artifact.get("requires_llama_tag"), str)
+ }
+ if required_tags and installed_tag not in required_tags:
+ required_tag = sorted(required_tags)[0]
+ return (
+ f"slim bundle requires llama.cpp {required_tag}; "
+ f"installed llama.cpp is {installed_tag}"
+ )
+ return None
+
+
+def select_artifact_with_fallback(
+ manifest: dict[str, Any], host: HostInfo, backend: str
+) -> tuple[dict[str, Any], str, bool]:
+ return select_artifact_with_cpu_fallback(manifest, host, backend)
+
+
+# ── Release checksum index (trust anchor: the release's own sha256 asset) ──
+def parse_release_checksums(repo: str, release_tag: str, payload: Any) -> dict[str, str]:
+ return core.parse_release_checksums(_OPS, repo, release_tag, payload)
+
+
+def fetch_release_checksums(bundle: ReleaseBundle) -> dict[str, str]:
+ return core.fetch_release_checksums(_OPS, bundle)
+
+
+def expected_sha256_for(
+ checksums: dict[str, str],
+ asset_name: str,
+ *,
+ manifest_sha256: str | None = None,
+) -> str:
+ return core.expected_sha256_for(_OPS, checksums, asset_name, manifest_sha256 = manifest_sha256)
+
+
+# ── Verified download (retries once on checksum mismatch) ──
+def download_file_verified(
+ url: str, destination: Path, *, expected_sha256: str, label: str
+) -> None:
+ core.download_file_verified_strict(
+ _OPS, url, destination, expected_sha256 = expected_sha256, label = label
+ )
+
+
+# ── GitHub release resolution ──
+def github_release(repo: str, tag: str) -> dict[str, Any]:
+ return core.github_release(_OPS, repo, tag, error = PrebuiltFallback)
+
+
+def fetch_release_bundle(repo: str, release_tag: str) -> ReleaseBundle:
+ return core.fetch_release_bundle(_OPS, repo, release_tag)
+
+
+def asset_download_url(bundle: ReleaseBundle, asset_name: str) -> str:
+ return core.asset_download_url(_OPS, bundle, asset_name)
+
+
+# ── Download-host fast path (resolve + fetch the JSON assets with no GitHub API) ──
+def _download_host_latest_release_tag(repo: str) -> str | None:
+ return core.download_host_latest_release_tag(_OPS, repo)
+
+
+def _download_host_json(url: str) -> Any:
+ return core.fetch_download_host_json(_OPS, url)
+
+
+def _resolve_release_via_download_host(
+ repo: str, published_release_tag: str | None
+) -> tuple[ReleaseBundle, dict[str, str]] | None:
+ return core.resolve_release_via_download_host(_OPS, repo, published_release_tag)
+
+
+# ── Archive extraction (core's guarded extractor + tar exec-bit restore) ──
+def extract_archive(archive_path: Path, destination: Path) -> None:
+ """Shared guarded extraction, then restore tar exec bits (the extractor writes
+ plain files; whisper-server must stay executable)."""
+ core.extract_archive(archive_path, destination)
+ core.restore_tar_exec_bits(archive_path, destination)
+
+
+# ── Install layout ──
+def server_binary_name(host: HostInfo) -> str:
+ return "whisper-server.exe" if host.is_windows else "whisper-server"
+
+
+def runtime_bin_dir(install_dir: Path, host: HostInfo) -> Path:
+ """Canonical directory holding whisper-server + its co-located libs."""
+ if host.is_windows:
+ return install_dir / "build" / "bin" / "Release"
+ return install_dir / "build" / "bin"
+
+
+def whisper_server_path(install_dir: Path, host: HostInfo) -> Path:
+ return runtime_bin_dir(install_dir, host) / server_binary_name(host)
+
+
+def installed_server_path(install_dir: Path, host: HostInfo) -> Path:
+ return whisper_server_path(install_dir, host)
+
+
+def _locate_server_in_tree(root: Path, host: HostInfo) -> Path:
+ return core.locate_server_in_tree(_OPS, root, host)
+
+
+def locate_server_in_tree(root: Path, host: HostInfo) -> Path:
+ return _locate_server_in_tree(root, host)
+
+
+def _assemble_install_tree(bundle_root: Path, staged_root: Path, host: HostInfo) -> Path:
+ """Lay out staged_root as a full install: build/bin/<server + libs>.
+
+ Everything beside the server in the archive (shared libs, backend kernel
+ subdirs, license/build-info) is co-located into the canonical bin dir so the
+ server's RUNPATH=$ORIGIN resolves its libs.
+ """
+ bin_dir = runtime_bin_dir(staged_root, host)
+ bin_dir.mkdir(parents = True, exist_ok = True)
+ for entry in sorted(bundle_root.iterdir()):
+ if entry.name == METADATA_FILENAME:
+ continue
+ dest = bin_dir / entry.name
+ if entry.is_dir() and not entry.is_symlink():
+ shutil.copytree(entry, dest, symlinks = True)
+ else:
+ shutil.copy2(entry, dest, follow_symlinks = False)
+ server = bin_dir / server_binary_name(host)
+ if not server.exists():
+ raise PrebuiltFallback("staged install is missing the whisper-server binary")
+ if not host.is_windows:
+ os.chmod(server, server.stat().st_mode | 0o111)
+ return server
+
+
+def assemble_install_tree(bundle_root: Path, staged_root: Path, host: HostInfo) -> Path:
+ return _assemble_install_tree(bundle_root, staged_root, host)
+
+
+def _validate_staged_server(staged_root: Path, host: HostInfo) -> None:
+ """Optional pre-activate smoke test. Gated off by default (see the switch)."""
+ if not _RUN_STAGED_PREBUILT_VALIDATION:
+ return
+ server = whisper_server_path(staged_root, host)
+ env = os.environ.copy()
+ bin_dir = str(runtime_bin_dir(staged_root, host))
+ for var in ("LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH"):
+ env[var] = bin_dir + (os.pathsep + env[var] if env.get(var) else "")
+ try:
+ result = subprocess.run(
+ [str(server), "--help"],
+ capture_output = True,
+ text = True,
+ timeout = 60,
+ env = env,
+ **llama.windows_hidden_subprocess_kwargs(),
+ )
+ except (OSError, subprocess.SubprocessError) as exc:
+ raise PrebuiltFallback(f"staged whisper-server failed to launch: {exc}") from exc
+ if result.returncode != 0:
+ raise PrebuiltFallback(
+ f"staged whisper-server --help exited {result.returncode}: {result.stderr.strip()}"
+ )
+
+
+def validate_staged_server(staged_root: Path, host: HostInfo) -> None:
+ _validate_staged_server(staged_root, host)
+
+
+# ── Slim install wiring (llama ggml runtime into the whisper bin dir) ──
+def _elf_needed(path: Path) -> set[str] | None:
+ """Read ELF DT_NEEDED names when a standard inspection tool is available."""
+ commands = (("readelf", "-d"), ("objdump", "-p"))
+ for command in commands:
+ try:
+ result = subprocess.run(
+ [*command, str(path)], capture_output = True, text = True, timeout = 10
+ )
+ except (OSError, subprocess.SubprocessError):
+ continue
+ if result.returncode != 0:
+ continue
+ needed: set[str] = set()
+ for line in result.stdout.splitlines():
+ match = re.search(r"\(NEEDED\).*\[([^]]+)\]", line)
+ if match:
+ needed.add(match.group(1))
+ continue
+ match = re.match(r"\s*NEEDED\s+(\S+)", line)
+ if match:
+ needed.add(match.group(1))
+ return needed
+ return None
+
+
+def _runtime_library_sources(llama_bin_dir: Path, backend: str | None) -> list[Path]:
+ patterns = list(SLIM_GGML_LIBRARY_GLOBS)
+ sources = {
+ path for pattern in patterns for path in llama_bin_dir.glob(pattern) if path.is_file()
+ }
+ if backend == "rocm":
+ # Windows llama HIP/ROCm prebuilts use a flat *.dll runtime overlay.
+ # Mirror that complete no-SDK closure, not only filenames containing
+ # ggml, hip, or roc: transitive runtime DLLs can have unrelated names.
+ windows_dlls = {path for path in llama_bin_dir.glob("*.dll") if path.is_file()}
+ if windows_dlls:
+ sources.update(windows_dlls)
+ return sorted(sources)
+
+ # Linux can inspect DT_NEEDED and copy the exact packaged closure. Fall
+ # back to the ROCm globs only when standard ELF tools are unavailable.
+ by_name = {path.name: path for path in llama_bin_dir.iterdir() if path.is_file()}
+ pending = list(sources)
+ inspected_hip = False
+ system_libraries = {
+ "libc.so.6",
+ "libdl.so.2",
+ "libgcc_s.so.1",
+ "libm.so.6",
+ "libpthread.so.0",
+ "librt.so.1",
+ "libstdc++.so.6",
+ }
+ while pending:
+ source = pending.pop()
+ needed = _elf_needed(source)
+ if needed is None:
+ continue
+ if source.name.startswith("libggml-hip"):
+ inspected_hip = True
+ for name in needed - system_libraries:
+ dependency = by_name.get(name)
+ if dependency is not None and dependency not in sources:
+ sources.add(dependency)
+ pending.append(dependency)
+ if not inspected_hip:
+ sources.update(
+ path
+ for pattern in SLIM_ROCM_LIBRARY_GLOBS
+ for path in llama_bin_dir.glob(pattern)
+ if path.is_file()
+ )
+ return sorted(sources)
+
+
+def _link_or_copy(source: Path, destination: Path) -> None:
+ destination.parent.mkdir(parents = True, exist_ok = True)
+ if destination.exists() or destination.is_symlink():
+ destination.unlink()
+ try:
+ os.link(source, destination)
+ except OSError:
+ shutil.copy2(source, destination)
+
+
+def link_ggml_runtime(
+ llama_bin_dir: Path,
+ whisper_bin_dir: Path,
+ *,
+ backend: str | None = None,
+) -> list[str]:
+ """Hardlink every ggml library from the llama runtime into the whisper bin
+ dir; returns the wired filenames (sorted) for the marker / sidecar launch guard.
+
+ Hardlinks (not symlinks) on purpose: when the llama updater atomically swaps
+ its install dir, the old inodes stay alive under these links, so a
+ not-yet-updated whisper keeps running the exact ggml build it was installed
+ against. Falls back to a copy where linking is unsupported or crosses devices.
+ Re-run on every install/update so the links track the current pairing.
+ """
+ sources = _runtime_library_sources(llama_bin_dir, backend)
+ if not any(source.name.startswith(("libggml", "ggml")) for source in sources):
+ raise PrebuiltFallback(
+ f"no ggml libraries found in {llama_bin_dir} to pair the slim whisper install"
+ )
+ whisper_bin_dir.mkdir(parents = True, exist_ok = True)
+ for source in sources:
+ # Follows a libggml.so.0 -> libggml.so.0.x symlink to its inode, so every
+ # created name is a real hardlink surviving a dir swap.
+ _link_or_copy(source, whisper_bin_dir / source.name)
+ return [source.name for source in sources]
+
+
+def link_runtime_directories(
+ llama_bin_dir: Path, whisper_bin_dir: Path, *, backend: str, host: HostInfo
+) -> list[str]:
+ """Mirror GPU kernel catalogs that packaged ROCm libraries load at runtime."""
+ # Windows ROCm prebuilts are a flat DLL overlay. The hipblaslt/rocblas
+ # catalog directories are part of the Linux ROCm bundle layout only.
+ if backend != "rocm" or host.is_windows:
+ return []
+ linked: list[str] = []
+ for name in SLIM_ROCM_RUNTIME_DIRS:
+ source_root = llama_bin_dir / name
+ if not source_root.is_dir():
+ raise PrebuiltFallback(f"paired ROCm runtime is missing its {name} kernel catalog")
+ files = [path for path in source_root.rglob("*") if path.is_file()]
+ if not files:
+ raise PrebuiltFallback(f"paired ROCm runtime has an empty {name} kernel catalog")
+ for source in files:
+ _link_or_copy(source, whisper_bin_dir / name / source.relative_to(source_root))
+ linked.append(name)
+ return linked
+
+
+def prepare_runtime_payload(staged_root: Path, host: HostInfo, selection: Any) -> Any:
+ """Slim installs wire the paired llama ggml runtime into the staged bin dir
+ before validation so the activated tree is self-contained; the returned
+ selection carries the wired filenames for the marker. Fat installs need
+ nothing (the archive carries its ggml) and return None."""
+ if getattr(selection, "install_kind", None) != "slim" or not selection.linked_from:
+ return None
+ source = Path(selection.linked_from)
+ destination = runtime_bin_dir(staged_root, host)
+ linked = link_ggml_runtime(source, destination, backend = selection.backend)
+ linked_dirs = link_runtime_directories(
+ source,
+ destination,
+ backend = selection.backend,
+ host = host,
+ )
+ log(f"slim install: hardlinked {len(linked)} ggml libraries from {selection.linked_from}")
+ return replace(
+ selection,
+ linked_libraries = tuple(linked),
+ runtime_wiring_version = SLIM_RUNTIME_WIRING_VERSION,
+ linked_runtime_directories = tuple(linked_dirs),
+ )
+
+
+# ── Metadata / marker ──
+def metadata_path(install_dir: Path) -> Path:
+ return install_dir / METADATA_FILENAME
+
+
+def selection_from_artifact(
+ *,
+ published_repo: str,
+ release_tag: str,
+ manifest: dict[str, Any],
+ artifact: dict[str, Any],
+ backend: str,
+ asset_sha256: str,
+) -> InstallSelection:
+ selection = core.selection_from_artifact(
+ _OPS,
+ published_repo = published_repo,
+ release_tag = release_tag,
+ manifest = manifest,
+ artifact = artifact,
+ backend = backend,
+ asset_sha256 = asset_sha256,
+ )
+ if artifact.get("install_kind") != "slim":
+ return selection
+ # A slim selection carries its pairing so the install wiring and marker know
+ # which llama runtime provides the ggml libraries.
+ runtime = installed_llama_runtime()
+ if runtime is None or runtime[1] != artifact.get("requires_llama_tag"):
+ raise PrebuiltFallback(
+ "the paired llama.cpp runtime changed underneath the slim whisper selection"
+ )
+ llama_bin_dir, llama_tag, _profile = runtime
+ return replace(
+ selection,
+ install_kind = "slim",
+ paired_llama_tag = llama_tag,
+ linked_from = str(llama_bin_dir),
+ )
+
+
+def write_prebuilt_metadata(install_dir: Path, selection: InstallSelection) -> None:
+ core.write_prebuilt_metadata(_OPS, install_dir, selection)
+
+
+def load_whisper_prebuilt_metadata(install_dir: Path) -> dict[str, Any] | None:
+ return core.load_prebuilt_metadata(_OPS, install_dir)
+
+
+def load_prebuilt_metadata(install_dir: Path) -> dict[str, Any] | None:
+ return load_whisper_prebuilt_metadata(install_dir)
+
+
+def existing_install_matches(
+ install_dir: Path, host: HostInfo, selection: InstallSelection
+) -> bool:
+ """Core fingerprint match, hardened for repairability: a marker-matching
+ install is only "current" when the server is executable (the sidecar refuses
+ non-executable binaries, so setup must repair not skip) and, for slim
+ installs, every wired ggml library is still present (else a deleted/moved
+ llama dir leaves dictation broken while update reports up to date)."""
+ if not core.existing_install_matches(_OPS, install_dir, host, selection):
+ return False
+ server = installed_server_path(install_dir, host)
+ if not host.is_windows and not os.access(server, os.X_OK):
+ log(f"existing install at {install_dir} has a non-executable server; reinstalling")
+ return False
+ marker = load_prebuilt_metadata(install_dir) or {}
+ if marker.get("install_kind") == "slim":
+ bin_dir = server.parent
+ if marker.get("runtime_wiring_version") != SLIM_RUNTIME_WIRING_VERSION:
+ log(f"existing slim install at {install_dir} has stale runtime wiring; reinstalling")
+ return False
+ linked_libraries = marker.get("linked_libraries")
+ if (
+ not isinstance(linked_libraries, list)
+ or not linked_libraries
+ or not all(
+ isinstance(name, str) and name and Path(name).name == name
+ for name in linked_libraries
+ )
+ ):
+ log(f"existing slim install at {install_dir} has invalid runtime wiring; reinstalling")
+ return False
+ missing = [name for name in linked_libraries if not (bin_dir / name).is_file()]
+ if missing:
+ log(
+ f"existing slim install at {install_dir} is missing wired ggml "
+ f"libraries ({', '.join(missing[:4])}); reinstalling"
+ )
+ return False
+ runtime_dirs = marker.get("linked_runtime_directories")
+ if (
+ marker.get("backend") == "rocm"
+ and not host.is_windows
+ and (
+ not isinstance(runtime_dirs, list)
+ or set(runtime_dirs) != set(SLIM_ROCM_RUNTIME_DIRS)
+ )
+ ):
+ log(f"existing ROCm install at {install_dir} lacks kernel catalogs; reinstalling")
+ return False
+ missing_dirs = [
+ name
+ for name in runtime_dirs or []
+ if not isinstance(name, str)
+ or not (bin_dir / name).is_dir()
+ or not any(path.is_file() for path in (bin_dir / name).rglob("*"))
+ ]
+ if missing_dirs:
+ log(
+ f"existing slim install at {install_dir} is missing runtime directories "
+ f"({', '.join(str(name) for name in missing_dirs[:4])}); reinstalling"
+ )
+ return False
+ return True
+
+
+# ── Orchestration ──
+def resolve_newest_release_tag(repo: str) -> str:
+ return core.resolve_newest_release_tag(_OPS, repo)
+
+
+def resolve_release_tag(published_repo: str, *, published_release_tag: str | None) -> str:
+ return core.resolve_release_tag(
+ _OPS, published_repo, published_release_tag = published_release_tag
+ )
+
+
+def fetch_release_for_install(
+ repo: str, *, published_release_tag: str | None
+) -> tuple[ReleaseBundle, dict[str, str]]:
+ return core.fetch_release_for_install(_OPS, repo, published_release_tag = published_release_tag)
+
+
+@dataclass(frozen = True)
+class WhisperReleasePlan:
+ bundle: ReleaseBundle
+ selection: InstallSelection | None
+ artifact: dict[str, Any]
+ resolved_backend: str
+ used_fallback: bool
+
+
+def _normalized_upstream_tag(value: str) -> str:
+ value = value.strip()
+ return value[1:] if value[:1].lower() == "v" else value
+
+
+def _bundle_matches_whisper_tag(bundle: ReleaseBundle, whisper_tag: str) -> bool:
+ requested = whisper_tag.strip()
+ if not requested or requested.lower() == "latest":
+ return True
+ upstream = bundle.manifest.get("upstream_tag")
+ return isinstance(upstream, str) and _normalized_upstream_tag(
+ upstream
+ ) == _normalized_upstream_tag(requested)
+
+
+def _published_release_tags(repo: str) -> list[str]:
+ """Published release tags in newest-first order for compatibility search."""
+ payload = fetch_json(f"https://api.github.com/repos/{repo}/releases?per_page=100")
+ if not isinstance(payload, list):
+ raise PrebuiltFallback(f"unexpected releases payload for {repo}")
+ releases = [
+ release
+ for release in payload
+ if isinstance(release, dict)
+ and not release.get("draft")
+ and not release.get("prerelease")
+ and isinstance(release.get("tag_name"), str)
+ and release.get("tag_name")
+ ]
+ releases.sort(key = lambda release: release.get("published_at") or "", reverse = True)
+ return [str(release["tag_name"]) for release in releases]
+
+
+def _fetch_release_candidate(repo: str, release_tag: str) -> ReleaseBundle:
+ """Fetch one candidate manifest by its deterministic download-host URL."""
+ manifest_url = release_asset_download_url(repo, release_tag, MANIFEST_ASSET_NAME)
+ try:
+ payload = _download_host_json(manifest_url)
+ manifest = parse_manifest(payload, label = f"{MANIFEST_ASSET_NAME} in {repo}@{release_tag}")
+ except Exception as exc:
+ raise PrebuiltFallback(
+ f"could not read {MANIFEST_ASSET_NAME} from {repo}@{release_tag}: {exc}"
+ ) from exc
+ asset_names = {MANIFEST_ASSET_NAME, SHA256_ASSET_NAME}
+ asset_names.update(
+ str(artifact["asset"])
+ for artifact in manifest.get("artifacts", [])
+ if isinstance(artifact, dict) and artifact.get("asset")
+ )
+ asset_urls = {name: release_asset_download_url(repo, release_tag, name) for name in asset_names}
+ return ReleaseBundle(
+ repo = repo,
+ release_tag = release_tag,
+ manifest = manifest,
+ asset_urls = asset_urls,
+ )
+
+
+def _plan_bundle(
+ host: HostInfo,
+ bundle: ReleaseBundle,
+ checksums: dict[str, str],
+ *,
+ published_repo: str,
+ requested_backend: str,
+ verify_checksums: bool,
+) -> WhisperReleasePlan:
+ artifact, resolved_backend, used_fallback = select_artifact_with_cpu_fallback(
+ bundle.manifest, host, requested_backend
+ )
+ selection = (
+ plan_selection(
+ host,
+ bundle,
+ published_repo = published_repo,
+ backend = requested_backend,
+ checksums = checksums,
+ )
+ if verify_checksums
+ else None
+ )
+ return WhisperReleasePlan(
+ bundle = bundle,
+ selection = selection,
+ artifact = artifact,
+ resolved_backend = resolved_backend,
+ used_fallback = used_fallback,
+ )
+
+
+def _release_plan_for_host(
+ host: HostInfo,
+ *,
+ published_repo: str,
+ published_release_tag: str | None,
+ whisper_tag: str,
+ requested_backend: str,
+ verify_checksums: bool = True,
+) -> WhisperReleasePlan:
+ """Select the requested or newest host-compatible published release.
+
+ Explicit published release pins never walk. An upstream ``whisper_tag``
+ searches published manifests for that exact upstream version. An unpinned
+ macOS install may walk older published releases only when the newest
+ manifest has no host-compatible artifact. Checksum and archive failures are
+ outside this search and remain hard failures.
+ """
+ requested_specific_tag = whisper_tag.strip().lower() not in ("", "latest")
+ first_bundle: ReleaseBundle | None = None
+ first_error: PrebuiltFallback | None = None
+ # An upstream version pin searches manifests directly. It must not depend
+ # on the unrelated newest release or its checksum index being healthy.
+ if not requested_specific_tag or published_release_tag:
+ first_bundle, first_checksums = fetch_release_for_install(
+ published_repo, published_release_tag = published_release_tag
+ )
+ if not _bundle_matches_whisper_tag(first_bundle, whisper_tag):
+ first_error = PrebuiltFallback(
+ f"{published_repo}@{first_bundle.release_tag} targets whisper.cpp "
+ f"{first_bundle.manifest.get('upstream_tag')}, not requested {whisper_tag}"
+ )
+ else:
+ try:
+ select_artifact_with_cpu_fallback(first_bundle.manifest, host, requested_backend)
+ except PrebuiltFallback as exc:
+ first_error = exc
+ else:
+ # Integrity validation happens only after compatibility succeeds.
+ # Its failures are never eligible for release walkback.
+ return _plan_bundle(
+ host,
+ first_bundle,
+ first_checksums,
+ published_repo = published_repo,
+ requested_backend = requested_backend,
+ verify_checksums = verify_checksums,
+ )
+
+ if published_release_tag:
+ assert first_error is not None
+ raise first_error
+
+ if not requested_specific_tag and not host.is_macos:
+ assert first_error is not None
+ raise first_error
+
+ for release_tag in _published_release_tags(published_repo):
+ if first_bundle is not None and release_tag == first_bundle.release_tag:
+ continue
+ try:
+ bundle = _fetch_release_candidate(published_repo, release_tag)
+ except PrebuiltFallback:
+ continue
+ if not _bundle_matches_whisper_tag(bundle, whisper_tag):
+ continue
+ try:
+ # Establish host compatibility before fetching or trusting this
+ # candidate's checksum index. Once selected, integrity failures must
+ # stop the install rather than silently downgrade again.
+ select_artifact_with_cpu_fallback(bundle.manifest, host, requested_backend)
+ except PrebuiltFallback:
+ continue
+ checksums = fetch_release_checksums(bundle) if verify_checksums else {}
+ plan = _plan_bundle(
+ host,
+ bundle,
+ checksums,
+ published_repo = published_repo,
+ requested_backend = requested_backend,
+ verify_checksums = verify_checksums,
+ )
+ log(
+ f"selected compatible published release {bundle.release_tag} "
+ f"(upstream {bundle.manifest.get('upstream_tag')})"
+ )
+ return plan
+
+ if requested_specific_tag:
+ raise PrebuiltFallback(
+ f"no published {COMPONENT} release for upstream tag {whisper_tag} supports this host"
+ )
+ assert first_error is not None
+ raise first_error
+
+
+def _install_from_bundle(
+ install_dir: Path, host: HostInfo, bundle: ReleaseBundle, selection: InstallSelection
+) -> None:
+ core.install_from_bundle(_OPS, install_dir, host, bundle, selection)
+
+
+def plan_selection(
+ host: HostInfo,
+ bundle: ReleaseBundle,
+ *,
+ published_repo: str,
+ backend: str,
+ checksums: dict[str, str],
+) -> InstallSelection:
+ return core.plan_selection(
+ _OPS,
+ host,
+ bundle,
+ published_repo = published_repo,
+ backend = backend,
+ checksums = checksums,
+ )
+
+
+def install_prebuilt(
+ install_dir: Path,
+ *,
+ whisper_tag: str = "latest",
+ published_repo: str = DEFAULT_PUBLISHED_REPO,
+ published_release_tag: str | None = None,
+ backend: str | None = "auto",
+ has_rocm: bool = False,
+ rocm_gfx: str | None = None,
+ cpu_fallback: bool = False,
+ force: bool = False,
+) -> int:
+ host = apply_host_overrides(
+ detect_host(), has_rocm = has_rocm, rocm_gfx = rocm_gfx, force_cpu = cpu_fallback
+ )
+ requested_backend = resolve_backend(host, backend, cpu_fallback = cpu_fallback)
+ os_token, arch_token = host_platform_tokens(host)
+ log(
+ f"target {COMPONENT} from {published_repo} "
+ f"({os_token}-{arch_token}, backend {requested_backend})"
+ )
+ plan = _release_plan_for_host(
+ host,
+ published_repo = published_repo,
+ published_release_tag = published_release_tag,
+ whisper_tag = whisper_tag,
+ requested_backend = requested_backend,
+ )
+ if plan.selection is None: # pragma: no cover - install plans always verify
+ raise PrebuiltFallback("install plan did not validate its checksum entry")
+ return core.install_selected_prebuilt(
+ _OPS,
+ install_dir,
+ host = host,
+ bundle = plan.bundle,
+ selection = plan.selection,
+ force = force,
+ )
+
+
+def resolver_payload_extra(artifact: dict[str, Any]) -> dict[str, Any]:
+ """Additive --resolve-prebuilt field: whether the selected asset installs
+ slim (paired with the llama ggml runtime) or fat (self-contained)."""
+ return {"install_kind": "slim" if artifact.get("install_kind") == "slim" else "fat"}
+
+
+def resolve_prebuilt(
+ host: HostInfo,
+ *,
+ published_repo: str,
+ published_release_tag: str | None,
+ whisper_tag: str = "latest",
+ backend: str | None,
+ cpu_fallback: bool,
+) -> dict[str, Any]:
+ requested_backend = resolve_backend(host, backend, cpu_fallback = cpu_fallback)
+ try:
+ plan = _release_plan_for_host(
+ host,
+ published_repo = published_repo,
+ published_release_tag = published_release_tag,
+ whisper_tag = whisper_tag,
+ requested_backend = requested_backend,
+ verify_checksums = False,
+ )
+ except PrebuiltFallback:
+ return {"prebuilt_available": False, "repo": published_repo}
+ os_token, arch_token = host_platform_tokens(host)
+ payload = {
+ "prebuilt_available": True,
+ "repo": published_repo,
+ "release_tag": plan.bundle.release_tag,
+ "upstream_tag": plan.bundle.manifest.get("upstream_tag"),
+ "backend": plan.resolved_backend,
+ "requested_backend": requested_backend,
+ "cpu_fallback": plan.used_fallback,
+ "asset": str(plan.artifact.get("asset")),
+ "os": os_token,
+ "arch": arch_token,
+ "runtime_line": plan.artifact.get("runtime_line"),
+ }
+ payload.update(resolver_payload_extra(plan.artifact))
+ return payload
+
+
+# The whisper component descriptor: the declarative form of everything above,
+# for descriptor-driven consumers (shared tests, future tooling). The shipped CLI
+# runs through this module's wrappers so monkeypatch seams stay intact.
+DESCRIPTOR = core.ComponentDescriptor(
+ component = COMPONENT,
+ log_prefix = "whisper-prebuilt",
+ published_repo = DEFAULT_PUBLISHED_REPO,
+ manifest_asset_name = MANIFEST_ASSET_NAME,
+ sha256_asset_name = SHA256_ASSET_NAME,
+ metadata_filename = METADATA_FILENAME,
+ user_agent = USER_AGENT,
+ supported_backends = SUPPORTED_BACKENDS,
+ schema_version = SCHEMA_VERSION,
+ fallback_backend = FALLBACK_BACKEND,
+ detect_host = detect_host,
+ host_platform_tokens = host_platform_tokens,
+ server_binary_name = server_binary_name,
+ runtime_bin_dir = runtime_bin_dir,
+)
+
+
+def build_arg_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description = "Install a prebuilt whisper.cpp (whisper-server) for Unsloth Studio"
+ )
+ parser.add_argument(
+ "--install-dir",
+ default = None,
+ help = (
+ "managed whisper.cpp directory, e.g. <UNSLOTH_HOME>/whisper.cpp. Required for an "
+ "install; omit it only with --resolve-prebuilt (a read-only probe)."
+ ),
+ )
+ parser.add_argument(
+ "--whisper-tag",
+ default = os.environ.get("UNSLOTH_WHISPER_TAG", "latest"),
+ help = "upstream whisper.cpp tag hint (default 'latest' or $UNSLOTH_WHISPER_TAG)",
+ )
+ parser.add_argument(
+ "--published-repo",
+ default = DEFAULT_PUBLISHED_REPO,
+ help = f"GitHub repo publishing the prebuilt releases (default {DEFAULT_PUBLISHED_REPO})",
+ )
+ parser.add_argument(
+ "--published-release-tag",
+ default = os.environ.get("UNSLOTH_WHISPER_RELEASE_TAG") or None,
+ help = "explicit release tag to install (default: the newest published release)",
+ )
+ parser.add_argument(
+ "--backend",
+ default = os.environ.get("UNSLOTH_WHISPER_BACKEND", "auto"),
+ choices = ("auto", *SUPPORTED_BACKENDS),
+ help = "accelerator backend; 'auto' detects from hardware",
+ )
+ parser.add_argument("--has-rocm", action = "store_true", help = "treat this host as ROCm-capable")
+ parser.add_argument("--rocm-gfx", default = None, help = "ROCm gfx target override, e.g. gfx1100")
+ parser.add_argument(
+ "--cpu-fallback", action = "store_true", help = "force the CPU asset regardless of hardware"
+ )
+ parser.add_argument(
+ "--resolve-prebuilt",
+ nargs = "?",
+ const = "latest",
+ default = None,
+ help = "report whether a prebuilt exists for this host without downloading",
+ )
+ parser.add_argument(
+ "--output-format",
+ choices = ("plain", "json"),
+ default = "plain",
+ help = "resolver output format (default plain)",
+ )
+ parser.add_argument(
+ "--force", action = "store_true", help = "reinstall even if the install already matches"
+ )
+ return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+ global _LOG_TO_STDOUT
+ parser = build_arg_parser()
+ args = parser.parse_args(argv)
+
+ if args.resolve_prebuilt is not None:
+ # Read-only probe: stdout is only the JSON/asset line (setup.sh and
+ # whisper_cpp_update.py parse it), so force diagnostics to stderr and map
+ # any failure to "not available" rather than a traceback.
+ _LOG_TO_STDOUT = False
+ try:
+ host = apply_host_overrides(
+ detect_host(),
+ has_rocm = args.has_rocm,
+ rocm_gfx = args.rocm_gfx,
+ force_cpu = args.cpu_fallback,
+ )
+ payload = resolve_prebuilt(
+ host,
+ published_repo = args.published_repo,
+ published_release_tag = args.published_release_tag,
+ whisper_tag = args.resolve_prebuilt,
+ backend = args.backend,
+ cpu_fallback = args.cpu_fallback,
+ )
+ except PrebuiltFallback:
+ payload = {"prebuilt_available": False, "repo": args.published_repo}
+ except Exception as exc: # noqa: BLE001 - probe must never crash the caller
+ log(f"resolve failed: {exc}")
+ payload = {"prebuilt_available": False, "repo": args.published_repo}
+ emit_resolver_output(payload, output_format = args.output_format)
+ return EXIT_SUCCESS
+
+ # Install path: progress logs go to stdout so setup surfaces them.
+ _LOG_TO_STDOUT = True
+
+ if not args.install_dir:
+ parser.error("--install-dir is required unless --resolve-prebuilt is used")
+ install_dir = Path(args.install_dir).expanduser().resolve()
+ try:
+ return install_prebuilt(
+ install_dir,
+ whisper_tag = args.whisper_tag,
+ published_repo = args.published_repo,
+ published_release_tag = args.published_release_tag,
+ backend = args.backend,
+ has_rocm = args.has_rocm,
+ rocm_gfx = args.rocm_gfx,
+ cpu_fallback = args.cpu_fallback,
+ force = args.force,
+ )
+ except BusyInstallConflict as exc:
+ log(str(exc))
+ return EXIT_BUSY
+ except ReleaseCompatibilityError as exc:
+ log(f"incompatible release: {exc}")
+ return EXIT_INCOMPATIBLE
+ except PrebuiltFallback as exc:
+ log(f"prebuilt install failed: {exc}")
+ return EXIT_ERROR
+ except Exception as exc: # noqa: BLE001
+ log(f"unexpected error: {exc}")
+ return EXIT_ERROR
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/studio/prebuilt_core.py b/studio/prebuilt_core.py
new file mode 100644
index 00000000000..5dc85af1c26
--- /dev/null
+++ b/studio/prebuilt_core.py
@@ -0,0 +1,2427 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Component-agnostic machinery shared by the ggml-family prebuilt installers.
+
+``install_llama_prebuilt.py`` and ``install_whisper_prebuilt.py`` both run on
+this module, which owns two layers:
+
+1. Primitives: HTTP fetches with retries and token-safe redirects, verified
+ downloads, safe archive extraction, the install lock, sha256 helpers, and
+ CUDA runtime-line / compute-capability selection. Moved verbatim out of
+ ``install_llama_prebuilt.py``, which re-exports them under their old names.
+
+2. The generic descriptor-driven install flow: release resolution (download
+ host fast path, GitHub API fallback), checksum-index parsing, coverage-aware
+ artifact selection, verified download + extraction + staged atomic
+ activation, marker/fingerprint handling, and the resolve probe. Whisper runs
+ entirely on this flow; a third component plugs in with a ``ComponentDescriptor``.
+
+Seam rule: every function calling a collaborator tests monkeypatch takes an
+``ops`` handle first. ``ops`` resolves names in the calling installer module's
+globals first (so a ``monkeypatch.setattr`` still wins) and falls back to this
+module's defaults, letting a descriptor-only component work with no installer
+module behind it.
+"""
+
+from __future__ import annotations
+
+import errno
+import functools
+import hashlib
+import json
+import os
+import random
+import re
+import shutil
+import socket
+import subprocess
+import sys
+import tarfile
+import tempfile
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+import zipfile
+from contextlib import contextmanager
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Callable, Iterable, Iterator
+
+try:
+ from filelock import FileLock, Timeout as FileLockTimeout
+except ImportError:
+ FileLock = None
+ FileLockTimeout = None
+
+
+class PrebuiltFallback(RuntimeError):
+ pass
+
+
+class BusyInstallConflict(RuntimeError):
+ pass
+
+
+# ── Defaults a component module may override via its own globals ──
+USER_AGENT = "unsloth-studio-prebuilt"
+GITHUB_AUTH_HOSTS = {"api.github.com", "github.com"}
+HF_AUTH_HOSTS = {"huggingface.co", "www.huggingface.co"}
+RETRYABLE_HTTP_STATUS = {408, 429, 500, 502, 503, 504}
+HTTP_FETCH_ATTEMPTS = 4
+HTTP_FETCH_BASE_DELAY_SECONDS = 0.75
+JSON_FETCH_ATTEMPTS = 3
+TTY_PROGRESS_START_DELAY_SECONDS = 0.5
+INSTALL_LOCK_TIMEOUT_SECONDS = 300
+INSTALL_STAGING_ROOT_NAME = ".staging"
+SCHEMA_VERSION = 1
+# Backend to retry when the preferred one has no covering asset; None disables it.
+FALLBACK_BACKEND: str | None = "cpu"
+_RATE_LIMIT_WAIT_CAP_SECONDS = 60.0
+
+# Lowest CUDA major we ship prebuilts for, and highest we probe for installed
+# runtime libraries. Detection and runtime-line derivation are generated per
+# major, so a new toolkit (cuda14, ...) needs no code change while ggml keeps
+# the cudart64_<major>.dll / libcudart.so.<major> naming.
+_MIN_CUDA_MAJOR = 12
+_MAX_PROBE_CUDA_MAJOR = 19
+
+# Blackwell floor is sm_100 (B100/B200 sm_100, B300/GB300 sm_103 below consumer
+# RTX 50 sm_120); the family needs toolkit >= 12.8, sm_103/sm_121 need 12.9.
+_BLACKWELL_MIN_SM = 100
+_BLACKWELL_MIN_TOOLKIT = (12, 8)
+_BLACKWELL_SM_MIN_TOOLKIT = {103: (12, 9), 121: (12, 9)}
+
+
+def log(message: str) -> None:
+ print(f"[prebuilt-core] {message}", file = sys.stderr)
+
+
+def _cuda_runtime_lines_for_major(major: int) -> list[str]:
+ """Runtime lines a driver of this CUDA major can use (its own major and any
+ older one, newest first down to the minimum we ship)."""
+ return [f"cuda{m}" for m in range(major, _MIN_CUDA_MAJOR - 1, -1)]
+
+
+# ── The ops seam ──
+_MISSING = object()
+
+# Core functions expecting an ``ops`` first argument. ModuleOps binds itself when
+# a lookup falls back to the core default, so a descriptor-only component gets
+# working defaults while an installer wrapper (or a test monkeypatch) always wins.
+_OPS_FIRST_NAMES = {
+ "auth_headers",
+ "github_api_headers",
+ "download_bytes",
+ "fetch_json",
+ "download_file",
+ "download_file_verified",
+ "download_file_verified_strict",
+ "github_release",
+ "github_release_assets",
+ "download_host_latest_release_tag",
+ "fetch_download_host_json",
+ "linux_runtime_dirs_for_required_libraries",
+ "detected_linux_runtime_lines",
+ "detected_windows_runtime_lines",
+ "parse_manifest",
+ "parse_release_checksums",
+ "fetch_release_checksums",
+ "expected_sha256_for",
+ "macos_min_os_ok",
+ "artifacts_for_host",
+ "select_artifact",
+ "select_artifact_with_fallback",
+ "auto_detect_backend",
+ "resolve_backend",
+ "fetch_release_bundle",
+ "asset_download_url",
+ "resolve_newest_release_tag",
+ "resolve_release_tag",
+ "resolve_release_via_download_host",
+ "fetch_release_for_install",
+ "write_prebuilt_metadata",
+ "load_prebuilt_metadata",
+ "existing_install_matches",
+ "metadata_path",
+ "selection_from_artifact",
+ "plan_selection",
+ "install_from_bundle",
+ "install_prebuilt",
+ "resolve_prebuilt",
+ "installed_server_path",
+ "assemble_install_tree",
+ "validate_staged_server",
+ "locate_server_in_tree",
+ # Underscored aliases the installer modules expose for their tests.
+ "_download_host_latest_release_tag",
+ "_download_host_json",
+ "_resolve_release_via_download_host",
+ "_install_from_bundle",
+}
+
+
+class ModuleOps:
+ """Late-binding name resolver over an installer module's globals.
+
+ Lookup hits the wrapped globals first (so a ``monkeypatch.setattr`` is always
+ observed), then this module's defaults (ops-first defaults come back bound).
+ """
+
+ def __init__(self, module_globals: dict[str, Any]) -> None:
+ self._globals = module_globals
+
+ def __getattr__(self, name: str) -> Any:
+ value = self._globals.get(name, _MISSING)
+ if value is _MISSING:
+ value = globals().get(name, _MISSING)
+ if value is _MISSING:
+ raise AttributeError(f"prebuilt component namespace has no attribute {name!r}")
+ if name in _OPS_FIRST_NAMES:
+ return functools.partial(value, self)
+ return value
+
+
+@dataclass(frozen = True)
+class ComponentDescriptor:
+ """Everything the generic flow needs about one ggml-family component.
+
+ Hooks mirror the module-level names an installer defines; a descriptor-only
+ component supplies them here and ``component_ops`` builds a namespace with
+ core defaults behind them.
+ """
+
+ component: str # manifest "component" value, e.g. "whisper.cpp"
+ log_prefix: str # stderr prefix, e.g. "whisper-prebuilt"
+ published_repo: str # fork publishing the prebuilt releases
+ manifest_asset_name: str
+ sha256_asset_name: str
+ metadata_filename: str # marker written into the install dir
+ user_agent: str
+ supported_backends: tuple[str, ...] = ("cpu", "cuda", "metal", "vulkan", "rocm")
+ schema_version: int = SCHEMA_VERSION
+ # Backend to retry when the preferred one has no covering asset: "cpu"
+ # (whisper) ships a CPU bundle in every release; None (llama) reports "no
+ # prebuilt" so the caller falls back to a source build.
+ fallback_backend: str | None = "cpu"
+ staging_root_name: str = INSTALL_STAGING_ROOT_NAME
+ run_staged_validation: bool = False
+ # Hooks. Each mirrors the module-level function it replaces; None keeps the
+ # core default (which raises if truly required).
+ detect_host: Callable[[], Any] | None = None
+ host_platform_tokens: Callable[[Any], tuple[str, str]] | None = None
+ server_binary_name: Callable[[Any], str] | None = None
+ runtime_bin_dir: Callable[[Path, Any], Path] | None = None
+ auto_detect_backend: Callable[[Any], str] | None = None
+
+
+def component_namespace(descriptor: ComponentDescriptor) -> dict[str, Any]:
+ """Materialize a descriptor into the module-like namespace ``ModuleOps``
+ resolves against; core defaults cover anything not listed here."""
+ prefix = descriptor.log_prefix
+
+ def component_log(message: str) -> None:
+ print(f"[{prefix}] {message}", file = sys.stderr)
+
+ namespace: dict[str, Any] = {
+ "COMPONENT": descriptor.component,
+ "SCHEMA_VERSION": descriptor.schema_version,
+ "DEFAULT_PUBLISHED_REPO": descriptor.published_repo,
+ "MANIFEST_ASSET_NAME": descriptor.manifest_asset_name,
+ "SHA256_ASSET_NAME": descriptor.sha256_asset_name,
+ "METADATA_FILENAME": descriptor.metadata_filename,
+ "SUPPORTED_BACKENDS": descriptor.supported_backends,
+ "USER_AGENT": descriptor.user_agent,
+ "FALLBACK_BACKEND": descriptor.fallback_backend,
+ "INSTALL_STAGING_ROOT_NAME": descriptor.staging_root_name,
+ "_RUN_STAGED_PREBUILT_VALIDATION": descriptor.run_staged_validation,
+ "log": component_log,
+ }
+ for hook in (
+ "detect_host",
+ "host_platform_tokens",
+ "server_binary_name",
+ "runtime_bin_dir",
+ "auto_detect_backend",
+ ):
+ value = getattr(descriptor, hook)
+ if value is not None:
+ namespace[hook] = value
+ return namespace
+
+
+def component_ops(descriptor: ComponentDescriptor) -> ModuleOps:
+ return ModuleOps(component_namespace(descriptor))
+
+
+# ── Lock/busy classification ──
+def _os_error_messages(exc: BaseException) -> list[str]:
+ messages: list[str] = []
+ if isinstance(exc, OSError):
+ for value in (
+ getattr(exc, "strerror", None),
+ getattr(exc, "filename", None),
+ getattr(exc, "filename2", None),
+ ):
+ if isinstance(value, str) and value:
+ messages.append(value)
+ text = str(exc)
+ if text:
+ messages.append(text)
+ return [message.lower() for message in messages if message]
+
+
+def is_busy_lock_error(exc: BaseException) -> bool:
+ if isinstance(exc, BusyInstallConflict):
+ return True
+ if isinstance(exc, OSError):
+ if exc.errno in {
+ errno.EACCES,
+ errno.EBUSY,
+ errno.EPERM,
+ errno.ETXTBSY,
+ }:
+ return True
+ if getattr(exc, "winerror", None) in {5, 32, 145}:
+ return True
+ for message in _os_error_messages(exc):
+ if any(
+ needle in message
+ for needle in (
+ "access is denied",
+ "being used by another process",
+ "device or resource busy",
+ "permission denied",
+ "text file busy",
+ "file is in use",
+ "process cannot access the file",
+ "cannot create a file when that file already exists",
+ )
+ ):
+ return True
+ return False
+
+
+# ── HTTP: auth, redirects, retries ──
+def parsed_hostname(url: str | None) -> str | None:
+ if not url:
+ return None
+ try:
+ hostname = urllib.parse.urlparse(url).hostname
+ except Exception:
+ return None
+ if not hostname:
+ return None
+ return hostname.lower()
+
+
+def should_send_github_auth(url: str | None) -> bool:
+ return parsed_hostname(url) in GITHUB_AUTH_HOSTS
+
+
+def should_send_hf_auth(url: str | None) -> bool:
+ return parsed_hostname(url) in HF_AUTH_HOSTS
+
+
+def auth_headers(ops: ModuleOps, url: str | None = None) -> dict[str, str]:
+ headers = {
+ "User-Agent": ops.USER_AGENT,
+ }
+ token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN")
+ if token and should_send_github_auth(url):
+ headers["Authorization"] = f"Bearer {token}"
+ return headers
+ # Anonymous huggingface.co fetches share a per-IP rate limit CI fleets
+ # exhaust (HTTP 429); authenticate when a token is available.
+ hf_token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
+ if hf_token and should_send_hf_auth(url):
+ headers["Authorization"] = f"Bearer {hf_token}"
+ return headers
+
+
+class _CrossHostAuthStrippingRedirectHandler(urllib.request.HTTPRedirectHandler):
+ """Drop Authorization when a redirect leaves the original host.
+
+ huggingface.co redirects downloads to CDN hosts whose signed URLs can reject
+ a foreign Authorization header; urllib forwards headers across redirects by
+ default (requests/huggingface_hub strip them).
+ """
+
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
+ new_request = super().redirect_request(req, fp, code, msg, headers, newurl)
+ if new_request is not None and parsed_hostname(newurl) != parsed_hostname(req.full_url):
+ new_request.headers.pop("Authorization", None)
+ new_request.unredirected_hdrs.pop("Authorization", None)
+ return new_request
+
+
+_URL_OPENER = urllib.request.build_opener(_CrossHostAuthStrippingRedirectHandler())
+
+
+def github_api_headers(ops: ModuleOps, url: str | None = None) -> dict[str, str]:
+ return {
+ "Accept": "application/vnd.github+json",
+ **ops.auth_headers(url),
+ }
+
+
+def is_github_api_url(url: str | None) -> bool:
+ return parsed_hostname(url) == "api.github.com"
+
+
+def is_retryable_url_error(exc: Exception) -> bool:
+ if isinstance(exc, urllib.error.HTTPError):
+ # GitHub returns 403 (not 429) on API rate-limit; anonymous calls share a
+ # 60-req/hour bucket per runner IP that CI fleets exhaust. Treat 403
+ # against api.github.com as retryable so we get a backoff cycle or two
+ # (honouring Retry-After / X-RateLimit-Reset) before the source-build
+ # fallback fires. 403s on other hosts (private downloads, auth) stay non-retryable.
+ if exc.code == 403:
+ return is_github_api_url(getattr(exc, "url", None))
+ return exc.code in RETRYABLE_HTTP_STATUS
+ if isinstance(exc, urllib.error.URLError):
+ return True
+ if isinstance(exc, TimeoutError):
+ return True
+ if isinstance(exc, socket.timeout):
+ return True
+ return False
+
+
+def _http_error_retry_delay(exc: Exception) -> float | None:
+ """Recommended wait from rate-limit headers on a 403/429.
+
+ None when no header is present or the wait exceeds
+ _RATE_LIMIT_WAIT_CAP_SECONDS (the source-build fallback is faster).
+ """
+ if not isinstance(exc, urllib.error.HTTPError):
+ return None
+ headers = getattr(exc, "headers", None)
+ if headers is None:
+ return None
+ retry_after = headers.get("Retry-After")
+ if retry_after and retry_after.strip().isdigit():
+ wait = float(retry_after.strip())
+ return wait if wait <= _RATE_LIMIT_WAIT_CAP_SECONDS else None
+ rate_reset = headers.get("X-RateLimit-Reset")
+ if rate_reset and rate_reset.strip().isdigit():
+ wait = float(rate_reset.strip()) - time.time()
+ if 0.0 < wait <= _RATE_LIMIT_WAIT_CAP_SECONDS:
+ return wait + 1.0 # +1s of slack so the bucket is fresh
+ return None
+
+
+def sleep_backoff(
+ attempt: int,
+ *,
+ base_delay: float = HTTP_FETCH_BASE_DELAY_SECONDS,
+ exc: Exception | None = None,
+) -> None:
+ delay = base_delay * (2 ** max(attempt - 1, 0))
+ header_delay = _http_error_retry_delay(exc) if exc is not None else None
+ if header_delay is not None:
+ delay = max(delay, header_delay)
+ delay += random.uniform(0.0, 0.2)
+ time.sleep(delay)
+
+
+# ── Atomic writes and hashing ──
+def atomic_write_bytes(destination: Path, data: bytes) -> None:
+ destination.parent.mkdir(parents = True, exist_ok = True)
+ with tempfile.NamedTemporaryFile(
+ prefix = destination.name + ".tmp-",
+ dir = destination.parent,
+ delete = False,
+ ) as handle:
+ tmp_path = Path(handle.name)
+ handle.write(data)
+ handle.flush()
+ os.fsync(handle.fileno())
+ os.replace(tmp_path, destination)
+
+
+def atomic_replace_from_tempfile(tmp_path: Path, destination: Path) -> None:
+ destination.parent.mkdir(parents = True, exist_ok = True)
+ os.replace(tmp_path, destination)
+
+
+def sha256_file(path: Path) -> str:
+ digest = hashlib.sha256()
+ with path.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def sha256_bytes(data: bytes) -> str:
+ return hashlib.sha256(data).hexdigest()
+
+
+def normalize_sha256_digest(value: str | None) -> str | None:
+ if not isinstance(value, str) or not value:
+ return None
+ lowered = value.lower()
+ if lowered.startswith("sha256:"):
+ lowered = lowered.split(":", 1)[1]
+ if len(lowered) != 64 or any(ch not in "0123456789abcdef" for ch in lowered):
+ return None
+ return lowered
+
+
+def validate_schema_version(
+ payload: dict[str, Any],
+ *,
+ label: str,
+ schema_version: int = SCHEMA_VERSION,
+ error: type[Exception] = RuntimeError,
+) -> None:
+ value = payload.get("schema_version")
+ if value is None:
+ return
+ try:
+ normalized = int(value)
+ except (TypeError, ValueError) as exc:
+ raise error(f"{label} schema_version was not an integer") from exc
+ if normalized != schema_version:
+ raise error(f"{label} schema_version={normalized} is unsupported")
+
+
+# ── Download progress ──
+def format_byte_count(num_bytes: float) -> str:
+ units = ["B", "KiB", "MiB", "GiB", "TiB"]
+ value = float(num_bytes)
+ for unit in units:
+ if abs(value) < 1024.0 or unit == units[-1]:
+ if unit == "B":
+ return f"{int(value)} {unit}"
+ return f"{value:.1f} {unit}"
+ value /= 1024.0
+ return f"{num_bytes:.1f} B"
+
+
+def _progress_percent_step() -> int:
+ """Non-tty milestone granularity. The in-app updater sets
+ UNSLOTH_PROGRESS_PERCENT_STEP=5 for finer progress lines."""
+ try:
+ step = int(os.environ.get("UNSLOTH_PROGRESS_PERCENT_STEP", "25"))
+ except ValueError:
+ return 25
+ return min(max(step, 1), 50)
+
+
+class DownloadProgress:
+ def __init__(self, label: str, total_bytes: int | None) -> None:
+ self.label = label
+ self.total_bytes = total_bytes if total_bytes and total_bytes > 0 else None
+ self.start_time = time.monotonic()
+ self.last_emit = 0.0
+ term_ok = os.environ.get("TERM", "").lower() != "dumb"
+ self.stream = (
+ sys.stderr if sys.stderr.isatty() else sys.stdout if sys.stdout.isatty() else sys.stderr
+ )
+ self.is_tty = term_ok and self.stream.isatty()
+ self.completed = False
+ self.milestone_step = _progress_percent_step()
+ self.last_milestone_percent = -1
+ self.last_milestone_bytes = 0
+ self.has_rendered_tty_progress = False
+
+ def _render(
+ self,
+ downloaded_bytes: int,
+ *,
+ final: bool = False,
+ ) -> str:
+ elapsed = max(time.monotonic() - self.start_time, 1e-6)
+ speed = downloaded_bytes / elapsed
+ speed_text = f"{format_byte_count(speed)}/s"
+ if self.total_bytes is not None:
+ percent = min(100.0, (downloaded_bytes / self.total_bytes) * 100.0)
+ return (
+ f"{self.label}: {percent:5.1f}% "
+ f"({format_byte_count(downloaded_bytes)}/{format_byte_count(self.total_bytes)}) "
+ f"at {speed_text}"
+ )
+ if final:
+ return f"{self.label}: {format_byte_count(downloaded_bytes)} downloaded at {speed_text}"
+ return f"{self.label}: {format_byte_count(downloaded_bytes)} downloaded at {speed_text}"
+
+ def update(self, downloaded_bytes: int) -> None:
+ now = time.monotonic()
+ if self.is_tty:
+ elapsed = now - self.start_time
+ if not self.has_rendered_tty_progress:
+ if self.total_bytes is not None and downloaded_bytes >= self.total_bytes:
+ return
+ if elapsed < TTY_PROGRESS_START_DELAY_SECONDS:
+ return
+ min_interval = 0.2
+ if (
+ self.has_rendered_tty_progress
+ and not self.completed
+ and (now - self.last_emit) < min_interval
+ ):
+ return
+ self.last_emit = now
+ line = self._render(downloaded_bytes)
+ self.stream.write("\r\033[K" + line)
+ self.stream.flush()
+ self.has_rendered_tty_progress = True
+ return
+
+ should_emit = False
+ if self.total_bytes is not None:
+ percent = int((downloaded_bytes * 100) / max(self.total_bytes, 1))
+ step = self.milestone_step
+ milestone_percent = min((percent // step) * step, 100)
+ if milestone_percent > self.last_milestone_percent and milestone_percent < 100:
+ self.last_milestone_percent = milestone_percent
+ should_emit = True
+ else:
+ byte_step = 25 * 1024 * 1024
+ if (
+ downloaded_bytes - self.last_milestone_bytes >= byte_step
+ and (now - self.last_emit) >= 5.0
+ ):
+ self.last_milestone_bytes = downloaded_bytes
+ should_emit = True
+
+ if not should_emit:
+ return
+
+ self.last_emit = now
+ self.stream.write(self._render(downloaded_bytes) + "\n")
+ self.stream.flush()
+
+ def finish(self, downloaded_bytes: int) -> None:
+ self.completed = True
+ line = self._render(downloaded_bytes, final = True)
+ if self.is_tty:
+ if not self.has_rendered_tty_progress:
+ return
+ self.stream.write("\r\033[K")
+ else:
+ self.stream.write(line + "\n")
+ self.stream.flush()
+
+
+def download_label_from_url(url: str) -> str:
+ name = Path(urllib.parse.urlparse(url).path).name
+ return name or url
+
+
+# ── Downloads ──
+def download_bytes(
+ ops: ModuleOps,
+ url: str,
+ *,
+ timeout: int = 120,
+ attempts: int | None = None,
+ headers: dict[str, str] | None = None,
+ progress_label: str | None = None,
+) -> bytes:
+ if attempts is None:
+ attempts = ops.HTTP_FETCH_ATTEMPTS
+ last_exc: Exception | None = None
+ for attempt in range(1, attempts + 1):
+ try:
+ request = urllib.request.Request(url, headers = headers or ops.auth_headers(url))
+ with ops._URL_OPENER.open(request, timeout = timeout) as response:
+ total_bytes: int | None = None
+ content_length = response.headers.get("Content-Length")
+ if content_length and content_length.isdigit():
+ total_bytes = int(content_length)
+ progress = DownloadProgress(progress_label, total_bytes) if progress_label else None
+ data = bytearray()
+ while True:
+ chunk = response.read(1024 * 1024)
+ if not chunk:
+ break
+ data.extend(chunk)
+ if progress is not None:
+ progress.update(len(data))
+ if progress is not None:
+ progress.finish(len(data))
+ return bytes(data)
+ except Exception as exc:
+ last_exc = exc
+ if attempt >= attempts or not is_retryable_url_error(exc):
+ raise
+ ops.log(f"fetch failed ({attempt}/{attempts}) for {url}: {exc}; retrying")
+ sleep_backoff(attempt, exc = exc)
+ assert last_exc is not None
+ raise last_exc
+
+
+def fetch_json(ops: ModuleOps, url: str) -> Any:
+ attempts = ops.JSON_FETCH_ATTEMPTS if is_github_api_url(url) else 1
+ last_decode_exc: Exception | None = None
+ for attempt in range(1, attempts + 1):
+ try:
+ data = ops.download_bytes(
+ url,
+ timeout = 30,
+ headers = ops.github_api_headers(url)
+ if is_github_api_url(url)
+ else ops.auth_headers(url),
+ )
+ except urllib.error.HTTPError as exc:
+ if exc.code == 403 and is_github_api_url(url):
+ hint = ""
+ if not (os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN")):
+ hint = "; set GH_TOKEN or GITHUB_TOKEN to avoid GitHub API rate limits"
+ raise RuntimeError(f"GitHub API returned 403 for {url}{hint}") from exc
+ raise
+ if not data:
+ last_decode_exc = RuntimeError(f"downloaded empty JSON payload from {url}")
+ else:
+ try:
+ payload = json.loads(data.decode("utf-8"))
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
+ last_decode_exc = RuntimeError(f"downloaded invalid JSON from {url}: {exc}")
+ else:
+ if not isinstance(payload, dict) and not isinstance(payload, list):
+ raise RuntimeError(
+ f"downloaded unexpected JSON type from {url}: {type(payload).__name__}"
+ )
+ return payload
+ if attempt >= attempts:
+ assert last_decode_exc is not None
+ raise last_decode_exc
+ ops.log(f"json fetch failed ({attempt}/{attempts}) for {url}; retrying")
+ sleep_backoff(attempt)
+ assert last_decode_exc is not None
+ raise last_decode_exc
+
+
+def download_file(ops: ModuleOps, url: str, destination: Path) -> None:
+ destination.parent.mkdir(parents = True, exist_ok = True)
+ attempts = ops.HTTP_FETCH_ATTEMPTS
+ last_exc: Exception | None = None
+ for attempt in range(1, attempts + 1):
+ tmp_path: Path | None = None
+ try:
+ request = urllib.request.Request(url, headers = ops.auth_headers(url))
+ with tempfile.NamedTemporaryFile(
+ prefix = destination.name + ".tmp-",
+ dir = destination.parent,
+ delete = False,
+ ) as handle:
+ tmp_path = Path(handle.name)
+ with ops._URL_OPENER.open(request, timeout = 120) as response:
+ total_bytes: int | None = None
+ content_length = response.headers.get("Content-Length")
+ if content_length and content_length.isdigit():
+ total_bytes = int(content_length)
+ progress = DownloadProgress(f"Downloading {destination.name}", total_bytes)
+ downloaded_bytes = 0
+ while True:
+ chunk = response.read(1024 * 1024)
+ if not chunk:
+ break
+ handle.write(chunk)
+ downloaded_bytes += len(chunk)
+ progress.update(downloaded_bytes)
+ progress.finish(downloaded_bytes)
+ handle.flush()
+ os.fsync(handle.fileno())
+ if not tmp_path.exists() or tmp_path.stat().st_size == 0:
+ raise RuntimeError(f"downloaded empty file from {url}")
+ atomic_replace_from_tempfile(tmp_path, destination)
+ return
+ except Exception as exc:
+ last_exc = exc
+ if tmp_path is not None:
+ try:
+ tmp_path.unlink(missing_ok = True)
+ except Exception:
+ pass
+ if attempt >= attempts or not is_retryable_url_error(exc):
+ raise
+ ops.log(f"download failed ({attempt}/{attempts}) for {url}: {exc}; retrying")
+ sleep_backoff(attempt, exc = exc)
+ assert last_exc is not None
+ raise last_exc
+
+
+def download_file_verified(
+ ops: ModuleOps, url: str, destination: Path, *, expected_sha256: str | None, label: str
+) -> None:
+ normalized_expected = normalize_sha256_digest(expected_sha256)
+ if not normalized_expected:
+ ops.download_file(url, destination)
+ ops.log(f"downloaded {label} without a published sha256; relying on install validation")
+ return
+
+ for attempt in range(1, 3):
+ ops.download_file(url, destination)
+ actual_sha256 = ops.sha256_file(destination)
+ if actual_sha256 == normalized_expected:
+ ops.log(f"verified {label} sha256={actual_sha256}")
+ return
+
+ ops.log(
+ f"{label} checksum mismatch on attempt {attempt}/2: "
+ f"expected={normalized_expected} actual={actual_sha256}"
+ )
+ destination.unlink(missing_ok = True)
+ if attempt == 2:
+ raise PrebuiltFallback(
+ f"{label} checksum mismatch after retry: expected={normalized_expected} actual={actual_sha256}"
+ )
+ ops.log(f"retrying {label} download after checksum mismatch")
+
+
+def download_file_verified_strict(
+ ops: ModuleOps, url: str, destination: Path, *, expected_sha256: str, label: str
+) -> None:
+ """Verified download with a required digest (the generic flow fails closed on
+ a missing checksum, so None never reaches here)."""
+ for attempt in range(1, 3):
+ ops.download_file(url, destination)
+ actual = ops.sha256_file(destination)
+ if actual == expected_sha256:
+ ops.log(f"verified {label} sha256={actual}")
+ return
+ ops.log(
+ f"{label} checksum mismatch {attempt}/2: expected={expected_sha256} actual={actual}"
+ )
+ destination.unlink(missing_ok = True)
+ if attempt == 2:
+ raise PrebuiltFallback(f"{label} checksum mismatch after retry")
+
+
+# ── GitHub release primitives ──
+def release_asset_map(release: dict[str, Any]) -> dict[str, str]:
+ assets = release.get("assets")
+ if not isinstance(assets, list):
+ return {}
+ return {
+ asset["name"]: asset.get("browser_download_url", "")
+ for asset in assets
+ if isinstance(asset, dict)
+ and isinstance(asset.get("name"), str)
+ and isinstance(asset.get("browser_download_url"), str)
+ }
+
+
+def github_release(
+ ops: ModuleOps,
+ repo: str,
+ tag: str,
+ *,
+ error: type[Exception] = RuntimeError,
+) -> dict[str, Any]:
+ payload = ops.fetch_json(
+ f"https://api.github.com/repos/{repo}/releases/tags/{urllib.parse.quote(tag, safe = '')}"
+ )
+ if not isinstance(payload, dict):
+ raise error(f"unexpected release payload for {repo}@{tag}")
+ return payload
+
+
+def github_release_assets(ops: ModuleOps, repo: str, tag: str) -> dict[str, str]:
+ payload = ops.fetch_json(
+ f"https://api.github.com/repos/{repo}/releases/tags/{urllib.parse.quote(tag, safe = '')}"
+ )
+ if not isinstance(payload, dict):
+ raise RuntimeError(f"unexpected release payload for {repo}@{tag}")
+ return release_asset_map(payload)
+
+
+def release_asset_download_url(repo: str, release_tag: str, asset_name: str) -> str:
+ """Tag-pinned asset URL on the release-assets CDN (github.com redirect, NOT
+ api.github.com, so no 60-req/hour unauthenticated limit)."""
+ return (
+ f"https://github.com/{urllib.parse.quote(repo, safe = '/')}/releases/download/"
+ f"{urllib.parse.quote(release_tag, safe = '')}/"
+ f"{urllib.parse.quote(asset_name, safe = '')}"
+ )
+
+
+def download_host_latest_release_tag(ops: ModuleOps, repo: str) -> str | None:
+ """Latest release tag from github.com/<repo>/releases/latest via its redirect
+ target (no api.github.com call). None on 404 so the caller falls back to the
+ API. /releases/latest resolves by created_at/make_latest, which can lag the
+ published_at newest the freshness check uses -- acceptable for install."""
+ url = f"https://github.com/{urllib.parse.quote(repo, safe = '/')}/releases/latest"
+ request = urllib.request.Request(
+ url,
+ method = "HEAD",
+ headers = {"User-Agent": ops.USER_AGENT},
+ )
+ try:
+ with ops._URL_OPENER.open(request, timeout = 30) as response:
+ final_url = response.geturl()
+ except urllib.error.HTTPError as exc:
+ if exc.code == 404:
+ return None
+ raise
+ marker = "/releases/tag/"
+ index = final_url.find(marker)
+ if index == -1:
+ return None
+ tag = urllib.parse.unquote(final_url[index + len(marker) :]).strip("/")
+ return tag or None
+
+
+def fetch_download_host_json(ops: ModuleOps, url: str) -> Any:
+ # Public CDN asset: plain unauthenticated GET, not the rate-limited API.
+ data = ops.download_bytes(
+ url,
+ timeout = 30,
+ headers = {"User-Agent": ops.USER_AGENT},
+ )
+ return json.loads(data.decode("utf-8"))
+
+
+# ── Archive extraction (traversal/symlink guarded) ──
+def extract_archive(archive_path: Path, destination: Path) -> None:
+ def safe_extract_path(base: Path, member_name: str) -> Path:
+ normalized = member_name.replace("\\", "/")
+ member_path = Path(normalized)
+ if member_path.is_absolute():
+ raise PrebuiltFallback(f"archive member used an absolute path: {member_name}")
+
+ target = (base / member_path).resolve()
+ base_resolved = base.resolve()
+ try:
+ target.relative_to(base_resolved)
+ except ValueError as exc:
+ raise PrebuiltFallback(f"archive member escaped destination: {member_name}") from exc
+ return target
+
+ def _try_repair_missing_slash(
+ member_name: str, link_name: str, archive_names: set[str]
+ ) -> str | None:
+ """Repair a mangled symlink from some upstream llama.cpp Mac releases
+ (e.g. b9165, b9169) whose linkname drops the separator AND the file
+ basename's leading char between the top-level dir and the rest:
+
+ llama-b9165/libggml-rpc.0.dylib -> llama-b9165ibggml-rpc.0.11.1.dylib
+
+ Detect the pattern (linkname starts with the top-level dir but no
+ following slash), then find the archive entry under that dir whose
+ basename ends with the mangled suffix; only accept a unique match.
+ Returns the corrected linkname relative to the member's parent dir --
+ callers join it with `target.parent`, so a full `top/file` path would
+ double the prefix into `top/top/file`."""
+ if "/" not in member_name or "/" in link_name:
+ return None
+ top, _, _ = member_name.partition("/")
+ if not link_name.startswith(top) or len(link_name) <= len(top):
+ return None
+ bad_suffix = link_name[len(top) :]
+ if not bad_suffix or bad_suffix.startswith("/"):
+ return None
+ prefix = f"{top}/"
+ candidates = [
+ name
+ for name in archive_names
+ if name.startswith(prefix)
+ and "/" not in name[len(prefix) :]
+ and name[len(prefix) :].endswith(bad_suffix)
+ ]
+ if len(candidates) != 1:
+ return None
+ # Strip the top-level dir so the caller's `target.parent / Path(...)`
+ # resolves inside the staging dir, not a duplicate `top/top/...` path.
+ return candidates[0][len(prefix) :]
+
+ def safe_link_target(
+ base: Path, member_name: str, link_name: str, target: Path, archive_names: set[str]
+ ) -> tuple[str, Path]:
+ normalized = link_name.replace("\\", "/")
+ repaired = _try_repair_missing_slash(member_name, normalized, archive_names)
+ if repaired is not None:
+ normalized = repaired
+ link_path = Path(normalized)
+ if link_path.is_absolute():
+ raise PrebuiltFallback(
+ f"archive link used an absolute target: {member_name} -> {link_name}"
+ )
+ if not normalized:
+ raise PrebuiltFallback(f"archive link used an empty target: {member_name}")
+
+ resolved = (target.parent / link_path).resolve()
+ base_resolved = base.resolve()
+ try:
+ resolved.relative_to(base_resolved)
+ except ValueError as exc:
+ raise PrebuiltFallback(
+ f"archive link escaped destination: {member_name} -> {link_name}"
+ ) from exc
+ return normalized, resolved
+
+ def extract_zip_safely(source: Path, base: Path) -> None:
+ with zipfile.ZipFile(source) as archive:
+ for member in archive.infolist():
+ target = safe_extract_path(base, member.filename)
+ mode = (member.external_attr >> 16) & 0o170000
+ if mode == 0o120000:
+ raise PrebuiltFallback(
+ f"zip archive contained a symlink entry: {member.filename}"
+ )
+ if member.is_dir():
+ target.mkdir(parents = True, exist_ok = True)
+ continue
+ target.parent.mkdir(parents = True, exist_ok = True)
+ with archive.open(member, "r") as src, target.open("wb") as dst:
+ shutil.copyfileobj(src, dst)
+
+ def extract_tar_safely(source: Path, base: Path) -> None:
+ pending_links: list[tuple[tarfile.TarInfo, Path]] = []
+ archive_names: set[str] = set()
+ with tarfile.open(source, "r:gz") as archive:
+ for member in archive.getmembers():
+ archive_names.add(member.name)
+ target = safe_extract_path(base, member.name)
+ if member.isdir():
+ target.mkdir(parents = True, exist_ok = True)
+ continue
+ if member.islnk() or member.issym():
+ pending_links.append((member, target))
+ continue
+ if not member.isfile():
+ raise PrebuiltFallback(
+ f"tar archive contained an unsupported entry: {member.name}"
+ )
+ target.parent.mkdir(parents = True, exist_ok = True)
+ extracted = archive.extractfile(member)
+ if extracted is None:
+ raise PrebuiltFallback(f"tar archive entry could not be read: {member.name}")
+ with extracted, target.open("wb") as dst:
+ shutil.copyfileobj(extracted, dst)
+
+ unresolved = list(pending_links)
+ while unresolved:
+ next_round: list[tuple[tarfile.TarInfo, Path]] = []
+ progressed = False
+ for member, target in unresolved:
+ normalized_link, resolved_target = safe_link_target(
+ base, member.name, member.linkname, target, archive_names
+ )
+ if not resolved_target.exists() and not resolved_target.is_symlink():
+ next_round.append((member, target))
+ continue
+ if resolved_target.is_dir():
+ raise PrebuiltFallback(
+ f"archive link targeted a directory: {member.name} -> {member.linkname}"
+ )
+
+ target.parent.mkdir(parents = True, exist_ok = True)
+ if target.exists() or target.is_symlink():
+ target.unlink()
+
+ if member.issym():
+ target.symlink_to(normalized_link)
+ else:
+ shutil.copy2(resolved_target, target)
+ progressed = True
+
+ if not progressed:
+ details = ", ".join(
+ f"{member.name} -> {member.linkname}" for member, _ in next_round
+ )
+ raise PrebuiltFallback(f"tar archive contained unresolved link entries: {details}")
+ unresolved = next_round
+
+ destination.mkdir(parents = True, exist_ok = True)
+ if archive_path.name.endswith(".zip"):
+ extract_zip_safely(archive_path, destination)
+ return
+ if archive_path.name.endswith(".tar.gz"):
+ extract_tar_safely(archive_path, destination)
+ return
+ raise PrebuiltFallback(f"unsupported archive format: {archive_path.name}")
+
+
+def restore_tar_exec_bits(archive_path: Path, destination: Path) -> None:
+ """Re-apply tar exec bits after the guarded extraction writes plain files;
+ server binaries must stay executable on Unix."""
+ if os.name == "nt" or not archive_path.name.endswith(".tar.gz"):
+ return
+ with tarfile.open(archive_path, "r:gz") as archive:
+ for member in archive.getmembers():
+ if not (member.isfile() and member.mode & 0o111):
+ continue
+ # Paths were already traversal-validated by the extractor above.
+ target = destination / Path(member.name.replace("\\", "/"))
+ if target.is_file():
+ os.chmod(target, target.stat().st_mode | 0o111)
+
+
+# ── Install lock ──
+@contextmanager
+def install_lock(lock_path: Path) -> Iterator[None]:
+ lock_path.parent.mkdir(parents = True, exist_ok = True)
+
+ if FileLock is None:
+ # Fallback lock: exclusive file creation, writing our PID so stale locks
+ # from crashed processes can be detected.
+ fd: int | None = None
+ deadline = time.monotonic() + INSTALL_LOCK_TIMEOUT_SECONDS
+ while True:
+ try:
+ fd = os.open(str(lock_path), os.O_CREAT | os.O_EXCL | os.O_RDWR)
+ try:
+ os.write(fd, f"{os.getpid()}\n".encode())
+ os.fsync(fd)
+ except Exception:
+ os.close(fd)
+ fd = None
+ lock_path.unlink(missing_ok = True)
+ raise
+ break
+ except FileExistsError:
+ stale = False
+ try:
+ raw = lock_path.read_text().strip()
+ except FileNotFoundError:
+ # Lock vanished between our open and read -- retry
+ continue
+ if not raw:
+ # Exists but PID not yet written; wait for the write to land.
+ if time.monotonic() >= deadline:
+ raise BusyInstallConflict(
+ f"timed out after {INSTALL_LOCK_TIMEOUT_SECONDS}s waiting for concurrent install lock: {lock_path}"
+ )
+ time.sleep(0.1)
+ continue
+ try:
+ holder_pid = int(raw)
+ os.kill(holder_pid, 0) # signal 0 = existence check
+ except ValueError:
+ stale = True # PID unreadable (corrupted file)
+ except ProcessLookupError:
+ stale = True # holder is dead
+ except PermissionError:
+ pass # alive but owned by another user -- not stale
+ if stale:
+ lock_path.unlink(missing_ok = True)
+ continue
+ if time.monotonic() >= deadline:
+ raise BusyInstallConflict(
+ f"timed out after {INSTALL_LOCK_TIMEOUT_SECONDS}s waiting for concurrent install lock: {lock_path}"
+ )
+ time.sleep(0.5)
+ try:
+ yield
+ finally:
+ if fd is not None:
+ os.close(fd)
+ lock_path.unlink(missing_ok = True)
+ return
+
+ try:
+ with FileLock(lock_path, timeout = INSTALL_LOCK_TIMEOUT_SECONDS):
+ yield
+ except FileLockTimeout as exc:
+ raise BusyInstallConflict(
+ f"timed out after {INSTALL_LOCK_TIMEOUT_SECONDS}s waiting for concurrent install lock: {lock_path}"
+ ) from exc
+
+
+def install_lock_path(install_dir: Path) -> Path:
+ return install_dir.parent / f".{install_dir.name}.install.lock"
+
+
+# ── macOS version parsing ──
+def parse_macos_version(value: str | None) -> tuple[int, int] | None:
+ """Parse a macOS product version into (major, minor).
+
+ Handles "14.7.1", "15.5", "26.0", bare "26". None when empty/unparseable
+ (callers then defer to runtime validation rather than reject every prebuilt)."""
+ if not value:
+ return None
+ match = re.match(r"\s*(\d+)(?:\.(\d+))?", str(value))
+ if not match:
+ return None
+ return int(match.group(1)), int(match.group(2) or 0)
+
+
+# ── GPU and CUDA runtime-line selection primitives ──
+def normalize_compute_cap(value: Any) -> str | None:
+ raw = str(value).strip()
+ if not raw:
+ return None
+ if "." in raw:
+ parts = raw.split(".", 1)
+ if len(parts) != 2:
+ return None
+ major, minor = parts
+ if not major.isdigit() or not minor.isdigit():
+ return None
+ return f"{int(major)}{int(minor)}"
+ if raw.isdigit():
+ return str(int(raw))
+ return None
+
+
+def normalize_compute_caps(compute_caps: Iterable[str]) -> list[str]:
+ normalized: list[str] = []
+ seen: set[str] = set()
+ for raw in compute_caps:
+ normalized_value = normalize_compute_cap(raw)
+ if normalized_value is None:
+ continue
+ if normalized_value in seen:
+ continue
+ seen.add(normalized_value)
+ normalized.append(normalized_value)
+ normalized.sort(key = int)
+ return normalized
+
+
+def parse_cuda_visible_devices(value: str | None) -> list[str] | None:
+ if value is None:
+ return None
+ raw = value.strip()
+ if not raw or raw == "-1":
+ return []
+ return [token.strip() for token in raw.split(",") if token.strip()]
+
+
+def supports_explicit_visible_device_matching(visible_devices: list[str] | None) -> bool:
+ if not visible_devices:
+ return False
+ for token in visible_devices:
+ lowered = token.lower()
+ if token.isdigit() or lowered.startswith("gpu-"):
+ continue
+ return False
+ return True
+
+
+def select_visible_gpu_rows(
+ gpu_rows: Iterable[tuple[str, str, str]], visible_devices: list[str] | None
+) -> list[tuple[str, str, str]]:
+ rows = list(gpu_rows)
+ if visible_devices is None:
+ return rows
+ if not visible_devices:
+ return []
+
+ by_index = {index: (index, uuid, cap) for index, uuid, cap in rows}
+ by_uuid = {uuid.lower(): (index, uuid, cap) for index, uuid, cap in rows}
+ selected: list[tuple[str, str, str]] = []
+ seen_indices: set[str] = set()
+ for token in visible_devices:
+ row = by_index.get(token)
+ if row is None:
+ normalized_token = token.lower()
+ row = by_uuid.get(normalized_token)
+ if row is None and normalized_token.startswith("gpu-"):
+ row = by_uuid.get(normalized_token)
+ if row is None and not normalized_token.startswith("gpu-"):
+ row = by_uuid.get("gpu-" + normalized_token)
+ if row is None:
+ continue
+ index = row[0]
+ if index in seen_indices:
+ continue
+ seen_indices.add(index)
+ selected.append(row)
+ return selected
+
+
+def dir_provides_exact_library(directory: str | Path, library: str) -> bool:
+ if not library:
+ return False
+ candidate = Path(directory) / library
+ return candidate.exists() and (candidate.is_file() or candidate.is_symlink())
+
+
+def linux_runtime_dirs_for_required_libraries(
+ ops: ModuleOps, required_libraries: Iterable[str]
+) -> list[str]:
+ required = [library for library in required_libraries if library]
+ candidates: list[str | Path] = []
+
+ env_dirs = os.environ.get("CUDA_RUNTIME_LIB_DIR", "")
+ if env_dirs:
+ candidates.extend(part for part in env_dirs.split(os.pathsep) if part)
+ ld_library_path = os.environ.get("LD_LIBRARY_PATH", "")
+ if ld_library_path:
+ candidates.extend(part for part in ld_library_path.split(os.pathsep) if part)
+
+ cuda_roots: list[Path] = []
+ for name in ("CUDA_HOME", "CUDA_PATH", "CUDA_ROOT"):
+ value = os.environ.get(name)
+ if value:
+ cuda_roots.append(Path(value))
+ cuda_roots.extend(Path(path) for path in ops.glob_paths("/usr/local/cuda", "/usr/local/cuda-*"))
+
+ for root in cuda_roots:
+ candidates.extend(
+ [
+ root / "lib",
+ root / "lib64",
+ root / "targets" / "x86_64-linux" / "lib",
+ ]
+ )
+
+ candidates.extend(
+ Path(path)
+ for path in ops.glob_paths(
+ "/lib",
+ "/lib64",
+ "/usr/lib",
+ "/usr/lib64",
+ "/usr/local/lib",
+ "/usr/local/lib64",
+ "/lib/x86_64-linux-gnu",
+ "/usr/lib/x86_64-linux-gnu",
+ )
+ )
+ candidates.extend(
+ Path(path) for path in ops.glob_paths("/usr/local/lib/ollama/cuda_v*", "/usr/lib/wsl/lib")
+ )
+ candidates.extend(Path(path) for path in ops.python_runtime_dirs())
+ candidates.extend(Path(path) for path in ops.ldconfig_runtime_dirs(required))
+
+ resolved = ops.dedupe_existing_dirs(candidates)
+ if not required:
+ return resolved
+
+ matched: list[tuple[int, str]] = []
+ for directory in resolved:
+ provided = sum(1 for library in required if dir_provides_exact_library(directory, library))
+ if provided:
+ matched.append((provided, directory))
+
+ matched.sort(key = lambda item: item[0], reverse = True)
+ return [directory for _, directory in matched]
+
+
+def detected_linux_runtime_lines(ops: ModuleOps) -> tuple[list[str], dict[str, list[str]]]:
+ """`cuda<major>` lines with a matching libcudart/libcublas file on disk (glob
+ match, so a versioned-only file counts), plus the dirs that matched."""
+ line_requirements = {
+ f"cuda{m}": [f"libcudart.so.{m}", f"libcublas.so.{m}"]
+ for m in range(_MAX_PROBE_CUDA_MAJOR, _MIN_CUDA_MAJOR - 1, -1)
+ }
+ detected: list[str] = []
+ runtime_dirs: dict[str, list[str]] = {}
+ for line, required in line_requirements.items():
+ dirs = ops.linux_runtime_dirs_for_required_libraries(required)
+ library_matches: dict[str, list[str]] = {}
+ matching_dirs: list[str] = []
+ for library in required:
+ matched_dirs = [
+ directory for directory in dirs if any(Path(directory).glob(f"{library}*"))
+ ]
+ if not matched_dirs:
+ library_matches = {}
+ matching_dirs = []
+ break
+ library_matches[library] = matched_dirs
+ for directory in matched_dirs:
+ if directory not in matching_dirs:
+ matching_dirs.append(directory)
+ if library_matches:
+ detected.append(line)
+ runtime_dirs[line] = matching_dirs
+ return detected, runtime_dirs
+
+
+def windows_runtime_line_info() -> dict[str, tuple[str, ...]]:
+ # Generated per CUDA major (newest first) so a new toolkit is detected without
+ # a code change while the cudart64_<major>.dll naming holds.
+ return {
+ f"cuda{m}": (
+ f"cudart64_{m}*.dll",
+ f"cublas64_{m}*.dll",
+ f"cublasLt64_{m}*.dll",
+ )
+ for m in range(_MAX_PROBE_CUDA_MAJOR, _MIN_CUDA_MAJOR - 1, -1)
+ }
+
+
+def detected_windows_runtime_lines(ops: ModuleOps) -> tuple[list[str], dict[str, list[str]]]:
+ dirs = ops.windows_runtime_dirs()
+ detected: list[str] = []
+ runtime_dirs: dict[str, list[str]] = {}
+ for runtime_line, required_patterns in windows_runtime_line_info().items():
+ matching_dirs = ops.windows_runtime_dirs_for_patterns(required_patterns, dirs)
+ if matching_dirs:
+ detected.append(runtime_line)
+ runtime_dirs[runtime_line] = matching_dirs
+ return detected, runtime_dirs
+
+
+def compatible_linux_runtime_lines(host: Any) -> list[str]:
+ if not host.driver_cuda_version:
+ return []
+ major, _minor = host.driver_cuda_version
+ if major < _MIN_CUDA_MAJOR:
+ return []
+ return _cuda_runtime_lines_for_major(major)
+
+
+def runtime_line_from_cuda_version(cuda_version: str | None) -> str | None:
+ if not cuda_version:
+ return None
+ raw = str(cuda_version).strip()
+ if not raw:
+ return None
+ major, _, _ = raw.partition(".")
+ if major == "12":
+ return "cuda12"
+ if major == "13":
+ return "cuda13"
+ return None
+
+
+@dataclass
+class CudaRuntimePreference:
+ runtime_line: str | None
+ selection_log: list[str]
+
+
+def detect_torch_cuda_runtime_preference(host: Any) -> CudaRuntimePreference:
+ selection_log: list[str] = []
+ if host.is_macos:
+ selection_log.append("torch_cuda_preference: skipped on macOS")
+ return CudaRuntimePreference(runtime_line = None, selection_log = selection_log)
+ if not (host.has_usable_nvidia and (host.is_linux or host.is_windows)):
+ selection_log.append(
+ "torch_cuda_preference: skipped because CUDA host prerequisites were not met"
+ )
+ return CudaRuntimePreference(runtime_line = None, selection_log = selection_log)
+
+ try:
+ import torch
+ except Exception as exc:
+ selection_log.append(f"torch_cuda_preference: import failed: {exc}")
+ return CudaRuntimePreference(runtime_line = None, selection_log = selection_log)
+
+ cuda_version = getattr(getattr(torch, "version", None), "cuda", None)
+ if not isinstance(cuda_version, str) or not cuda_version.strip():
+ selection_log.append(
+ "torch_cuda_preference: torch.version.cuda missing; skipping Torch shortcut"
+ )
+ return CudaRuntimePreference(runtime_line = None, selection_log = selection_log)
+
+ try:
+ cuda_available = bool(torch.cuda.is_available())
+ except Exception as exc:
+ selection_log.append(f"torch_cuda_preference: torch.cuda.is_available() failed: {exc}")
+ return CudaRuntimePreference(runtime_line = None, selection_log = selection_log)
+
+ if not cuda_available:
+ selection_log.append(
+ "torch_cuda_preference: torch.cuda.is_available() returned False; falling back to normal selection"
+ )
+ return CudaRuntimePreference(runtime_line = None, selection_log = selection_log)
+
+ runtime_line = runtime_line_from_cuda_version(cuda_version)
+ if runtime_line is None:
+ selection_log.append(
+ f"torch_cuda_preference: unsupported torch.version.cuda={cuda_version}; falling back to normal selection"
+ )
+ return CudaRuntimePreference(runtime_line = None, selection_log = selection_log)
+
+ selection_log.append(
+ "torch_cuda_preference: selected runtime_line="
+ f"{runtime_line} from torch.version.cuda={cuda_version}"
+ )
+ return CudaRuntimePreference(runtime_line = runtime_line, selection_log = selection_log)
+
+
+def artifact_covers_sms(artifact: Any, host_sms: Iterable[str]) -> bool:
+ """True when every host SM is in the artifact's supported_sms and within its
+ [min_sm, max_sm] range."""
+ if not artifact.supported_sms or artifact.min_sm is None or artifact.max_sm is None:
+ return False
+ supported = {str(value) for value in artifact.supported_sms}
+ return all(sm in supported and artifact.min_sm <= int(sm) <= artifact.max_sm for sm in host_sms)
+
+
+def sm_range(artifact: Any) -> int:
+ """SM-coverage span as a sort key (tighter range wins). A bundle with no SM
+ metadata gets a max range so it sorts last, never outranking a targeted bundle."""
+ if artifact.min_sm is not None and artifact.max_sm is not None:
+ return artifact.max_sm - artifact.min_sm
+ return 9999
+
+
+def blackwell_capable_linux_runtime_lines(host_sms: list[str], artifacts: list[Any]) -> list[str]:
+ """CUDA runtime lines (highest major first) shipping a bundle covering every
+ visible host SM. Lets a Blackwell host prefer a native sm_120 line over torch's
+ reported line, mirroring the Windows Blackwell preference."""
+ lines: set[str] = set()
+ for artifact in artifacts:
+ line = artifact.runtime_line
+ # Only rank "cuda<major>" lines; skip malformed/future-format values
+ # (e.g. "cuda13.1") rather than crash the major sort.
+ if not (line and line.startswith("cuda") and line[len("cuda") :].isdigit()):
+ continue
+ if not artifact.supported_sms or artifact.min_sm is None or artifact.max_sm is None:
+ continue
+ supported = {str(value) for value in artifact.supported_sms}
+ if all(
+ sm in supported and artifact.min_sm <= int(sm) <= artifact.max_sm for sm in host_sms
+ ):
+ lines.add(line)
+ return sorted(lines, key = lambda line: int(line[len("cuda") :]), reverse = True)
+
+
+def host_is_blackwell(host: Any) -> bool:
+ caps = normalize_compute_caps(host.compute_caps)
+ return bool(caps) and int(caps[-1]) >= _BLACKWELL_MIN_SM
+
+
+def blackwell_min_toolkit_for_host(host: Any) -> tuple[int, int]:
+ """Minimum CUDA toolkit this Blackwell host needs: 12.8 for the family, 12.9
+ if any SM is sm_103/sm_121 (no native target before 12.9)."""
+ req = _BLACKWELL_MIN_TOOLKIT
+ for sm in normalize_compute_caps(host.compute_caps):
+ req = max(req, _BLACKWELL_SM_MIN_TOOLKIT.get(int(sm), _BLACKWELL_MIN_TOOLKIT))
+ return req
+
+
+# ════════════════════════════════════════════════════════════════════════════
+# Generic descriptor-driven install flow (whisper dialect: one release carries
+# a manifest of os/arch/backend artifacts plus a same-origin checksum index).
+# ════════════════════════════════════════════════════════════════════════════
+def host_platform_tokens(host: Any) -> tuple[str, str]:
+ """Default (os, arch) asset tokens; components with their own HostInfo field
+ names override this hook."""
+ return host.os_token, host.arch_token
+
+
+# ── Manifest parsing ──
+def parse_manifest(ops: ModuleOps, payload: Any, *, label: str) -> dict[str, Any]:
+ """Validate a component prebuilt manifest and return it normalized.
+
+ Rejects an unknown schema_version or wrong component. Returns keys:
+ schema_version, component, studio_protocol, upstream_tag, source_commit,
+ artifacts (list of dicts).
+ """
+ component = ops.COMPONENT
+ if not isinstance(payload, dict):
+ raise PrebuiltFallback(f"{label} was not a JSON object")
+ validate_schema_version(
+ payload, label = label, schema_version = ops.SCHEMA_VERSION, error = PrebuiltFallback
+ )
+ manifest_component = payload.get("component")
+ if manifest_component != component:
+ raise PrebuiltFallback(
+ f"{label} describes component {manifest_component!r}, expected {component!r}"
+ )
+
+ artifacts_raw = payload.get("artifacts")
+ if not isinstance(artifacts_raw, list):
+ raise PrebuiltFallback(f"{label} omitted an 'artifacts' list")
+ artifacts: list[dict[str, Any]] = []
+ for index, raw in enumerate(artifacts_raw):
+ if not isinstance(raw, dict):
+ ops.log(f"{label} artifact[{index}] ignored: not an object")
+ continue
+ asset = raw.get("asset")
+ if not isinstance(asset, str) or not asset:
+ ops.log(f"{label} artifact[{index}] ignored: missing asset name")
+ continue
+ artifacts.append(raw)
+
+ studio_protocol = payload.get("studio_protocol")
+ return {
+ "schema_version": ops.SCHEMA_VERSION,
+ "component": component,
+ "studio_protocol": studio_protocol if isinstance(studio_protocol, str) else None,
+ "upstream_tag": payload.get("upstream_tag")
+ if isinstance(payload.get("upstream_tag"), str)
+ else None,
+ "source_commit": payload.get("source_commit")
+ if isinstance(payload.get("source_commit"), str)
+ else None,
+ "artifacts": artifacts,
+ }
+
+
+def macos_min_os_ok(ops: ModuleOps, host: Any, min_os: Any) -> bool:
+ """True if a macOS artifact requiring `min_os` can load here. The manifest
+ labels it `macos-<version>` (e.g. `macos-14.0`); strip that prefix before
+ parsing or every entry parses as None and the guard no-ops. Unknown host or
+ min_os -> True (defer to runtime validation)."""
+ if not isinstance(min_os, str) or not min_os.strip():
+ return True
+ raw = min_os.strip()
+ if raw.lower().startswith("macos-"):
+ raw = raw[len("macos-") :]
+ required = ops.parse_macos_version(raw)
+ if required is None or host.macos_version is None:
+ return True
+ return host.macos_version >= required
+
+
+def artifacts_for_host(
+ ops: ModuleOps, manifest: dict[str, Any], host: Any, backend: str
+) -> list[dict[str, Any]]:
+ """Manifest artifacts matching this host os/arch/backend. On macOS, drop any
+ whose `min_os` exceeds the host version."""
+ os_token, arch_token = ops.host_platform_tokens(host)
+ return [
+ artifact
+ for artifact in manifest.get("artifacts", [])
+ if artifact.get("os") == os_token
+ and artifact.get("arch") == arch_token
+ and artifact.get("backend") == backend
+ and (not host.is_macos or ops.macos_min_os_ok(host, artifact.get("min_os")))
+ ]
+
+
+def select_artifact(
+ ops: ModuleOps, manifest: dict[str, Any], host: Any, backend: str
+) -> dict[str, Any] | None:
+ """First manifest artifact matching this host os/arch and backend, or None
+ (caller then applies the component's fallback policy). No accelerator
+ capability matching here: whisper bundles are slim per os/arch (the paired
+ llama.cpp installer already picked SM/gfx-appropriate ggml backends), and
+ llama keeps its own selection chain in install_llama_prebuilt.py."""
+ candidates = ops.artifacts_for_host(manifest, host, backend)
+ return candidates[0] if candidates else None
+
+
+def select_artifact_with_fallback(
+ ops: ModuleOps, manifest: dict[str, Any], host: Any, backend: str
+) -> tuple[dict[str, Any], str, bool]:
+ """Select the backend artifact, else the descriptor's fallback-backend
+ artifact of the same release (whisper: CPU; llama: none, so a GPU miss
+ surfaces as "no prebuilt" and the caller does a source build).
+
+ Returns (artifact, effective_backend, used_fallback). Raises PrebuiltFallback
+ when neither the requested backend nor the fallback has an asset."""
+ os_token, arch_token = ops.host_platform_tokens(host)
+ artifact = ops.select_artifact(manifest, host, backend)
+ if artifact is not None:
+ return artifact, backend, False
+ fallback_backend = ops.FALLBACK_BACKEND
+ if fallback_backend and backend != fallback_backend:
+ fallback_artifact = ops.select_artifact(manifest, host, fallback_backend)
+ if fallback_artifact is not None:
+ ops.log(
+ f"no '{backend}' asset for {os_token}-{arch_token}; "
+ f"falling back to the {fallback_backend.upper()} asset of the same release"
+ )
+ return fallback_artifact, fallback_backend, True
+ raise PrebuiltFallback(
+ f"no {ops.COMPONENT} prebuilt asset for {os_token}-{arch_token} (backend '{backend}')"
+ )
+
+
+def artifact_coverage(artifact: dict[str, Any]) -> dict[str, Any]:
+ """The sm/gfx/min_os coverage recorded for an artifact (marker/fingerprint)."""
+ coverage: dict[str, Any] = {}
+ for key in ("sm_coverage", "gfx_coverage", "min_os", "sm", "gfx"):
+ if key in artifact and artifact.get(key) is not None:
+ coverage[key] = artifact.get(key)
+ return coverage
+
+
+# ── Backend resolution ──
+def auto_detect_backend(ops: ModuleOps, host: Any) -> str:
+ """Host-preferred backend: Apple Silicon -> metal, usable NVIDIA -> cuda,
+ AMD gfx -> rocm, otherwise cpu."""
+ if host.is_apple_silicon:
+ return "metal"
+ if host.has_usable_nvidia:
+ return "cuda"
+ if host.has_rocm:
+ return "rocm"
+ return "cpu"
+
+
+def resolve_backend(ops: ModuleOps, host: Any, requested: str | None, *, cpu_fallback: bool) -> str:
+ """Resolve the effective backend from --backend / --cpu-fallback and detection."""
+ if cpu_fallback:
+ return "cpu"
+ value = (requested or "auto").strip().lower()
+ if value in {"", "auto"}:
+ return ops.auto_detect_backend(host)
+ if value in ops.SUPPORTED_BACKENDS:
+ return value
+ raise PrebuiltFallback(
+ f"unsupported --backend '{requested}'; choose from auto,{','.join(ops.SUPPORTED_BACKENDS)}"
+ )
+
+
+# ── Release checksum index (trust anchor: the release's own sha256 asset) ──
+def valid_sha256(value: Any) -> str | None:
+ if not isinstance(value, str):
+ return None
+ digest = value.strip().lower()
+ if digest.startswith("sha256:"):
+ digest = digest[len("sha256:") :]
+ if len(digest) == 64 and all(c in "0123456789abcdef" for c in digest):
+ return digest
+ return None
+
+
+def parse_release_checksums(
+ ops: ModuleOps, repo: str, release_tag: str, payload: Any
+) -> dict[str, str]:
+ """Asset name -> sha256 from a release's checksum-index asset.
+
+ That index is the authority for each asset's sha256. It is validated for
+ schema/component and that its ``release_tag`` matches the resolved release,
+ so a redirected or mismatched index is rejected; malformed fails closed."""
+ label = f"{ops.SHA256_ASSET_NAME} in {repo}@{release_tag}"
+ if not isinstance(payload, dict):
+ raise PrebuiltFallback(f"{label} was not a JSON object")
+ if payload.get("schema_version") != ops.SCHEMA_VERSION:
+ raise PrebuiltFallback(f"{label} has an unexpected schema_version")
+ if payload.get("component") != ops.COMPONENT:
+ raise PrebuiltFallback(f"{label} did not describe {ops.COMPONENT}")
+ payload_tag = payload.get("release_tag")
+ if not isinstance(payload_tag, str) or not payload_tag:
+ raise PrebuiltFallback(f"{label} omitted release_tag")
+ if payload_tag != release_tag:
+ raise PrebuiltFallback(
+ f"{label} release_tag={payload_tag} did not match the resolved release {release_tag}"
+ )
+ artifacts = payload.get("artifacts")
+ if not isinstance(artifacts, dict):
+ raise PrebuiltFallback(f"{label} omitted an 'artifacts' map")
+ checksums: dict[str, str] = {}
+ for asset_name, entry in artifacts.items():
+ if not isinstance(asset_name, str) or not asset_name or not isinstance(entry, dict):
+ continue
+ digest = valid_sha256(entry.get("sha256"))
+ if digest is not None:
+ checksums[asset_name] = digest
+ if not checksums:
+ raise PrebuiltFallback(f"{label} carried no usable sha256 entries")
+ return checksums
+
+
+def fetch_release_checksums(ops: ModuleOps, bundle: "ReleaseBundle") -> dict[str, str]:
+ """Download + parse the release's checksum-index asset; fails closed if the
+ release does not publish it."""
+ sha_asset = ops.SHA256_ASSET_NAME
+ url = bundle.asset_urls.get(sha_asset)
+ if not url:
+ raise PrebuiltFallback(
+ f"release {bundle.repo}@{bundle.release_tag} has no {sha_asset}; "
+ f"cannot verify a download"
+ )
+ try:
+ raw = ops.download_bytes(url, timeout = 30, headers = ops.auth_headers(url))
+ payload = json.loads(raw.decode("utf-8"))
+ except (urllib.error.URLError, OSError, socket.timeout) as exc:
+ raise PrebuiltFallback(
+ f"could not fetch {sha_asset} from {bundle.repo}@{bundle.release_tag}: {exc}"
+ ) from exc
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
+ raise PrebuiltFallback(
+ f"{sha_asset} in {bundle.repo}@{bundle.release_tag} was not valid JSON"
+ ) from exc
+ return ops.parse_release_checksums(bundle.repo, bundle.release_tag, payload)
+
+
+def expected_sha256_for(
+ ops: ModuleOps,
+ checksums: dict[str, str],
+ asset_name: str,
+ *,
+ manifest_sha256: str | None = None,
+) -> str:
+ """The sha256 the archive must match, from the release checksum-index entry.
+ An asset absent from the index fails closed. Any sha256 the manifest embeds
+ for the asset must agree with the index (a mismatch means a tampered manifest)."""
+ digest = checksums.get(asset_name)
+ if digest is None:
+ raise PrebuiltFallback(
+ f"{asset_name} is not covered by {ops.SHA256_ASSET_NAME}; "
+ f"refusing an unverifiable download"
+ )
+ embedded = valid_sha256(manifest_sha256)
+ if embedded is not None and embedded != digest:
+ raise PrebuiltFallback(
+ f"manifest sha256 for {asset_name} disagrees with {ops.SHA256_ASSET_NAME}; "
+ f"refusing a possibly tampered release"
+ )
+ ops.log(f"verifying {asset_name} against {ops.SHA256_ASSET_NAME} sha256={digest}")
+ return digest
+
+
+# ── Release resolution ──
+@dataclass
+class ReleaseBundle:
+ repo: str
+ release_tag: str
+ manifest: dict[str, Any]
+ asset_urls: dict[str, str]
+
+
+def fetch_release_bundle(ops: ModuleOps, repo: str, release_tag: str) -> ReleaseBundle:
+ """Fetch a fork release, download+validate its manifest, return the bundle.
+
+ The single network seam for API-path release resolution; tests inject a fake
+ to exercise selection/install offline. A missing or unreachable release (404,
+ rate limit, no network) surfaces as PrebuiltFallback so the caller does a
+ source build rather than error out.
+ """
+ manifest_asset = ops.MANIFEST_ASSET_NAME
+ try:
+ release = ops.github_release(repo, release_tag)
+ except PrebuiltFallback:
+ raise
+ except (urllib.error.URLError, OSError, socket.timeout) as exc:
+ raise PrebuiltFallback(f"could not fetch release {repo}@{release_tag}: {exc}") from exc
+ resolved_tag = release.get("tag_name")
+ resolved_tag = resolved_tag if isinstance(resolved_tag, str) and resolved_tag else release_tag
+ asset_urls = ops.release_asset_map(release)
+ manifest_url = asset_urls.get(manifest_asset)
+ if not manifest_url:
+ raise PrebuiltFallback(
+ f"release {repo}@{resolved_tag} has no {manifest_asset}; cannot select a prebuilt"
+ )
+ try:
+ manifest_bytes = ops.download_bytes(
+ manifest_url, timeout = 30, headers = ops.auth_headers(manifest_url)
+ )
+ except (urllib.error.URLError, OSError, socket.timeout) as exc:
+ raise PrebuiltFallback(
+ f"could not fetch {manifest_asset} from {repo}@{resolved_tag}: {exc}"
+ ) from exc
+ try:
+ manifest_payload = json.loads(manifest_bytes.decode("utf-8"))
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
+ raise PrebuiltFallback(
+ f"{manifest_asset} in {repo}@{resolved_tag} was not valid JSON"
+ ) from exc
+ manifest = ops.parse_manifest(
+ manifest_payload, label = f"{manifest_asset} in {repo}@{resolved_tag}"
+ )
+ return ReleaseBundle(
+ repo = repo, release_tag = resolved_tag, manifest = manifest, asset_urls = asset_urls
+ )
+
+
+def asset_download_url(ops: ModuleOps, bundle: ReleaseBundle, asset_name: str) -> str:
+ url = bundle.asset_urls.get(asset_name)
+ if url:
+ return url
+ # A manifest can list an asset the release JSON omitted; fall back to the
+ # deterministic release-download URL.
+ return ops.release_asset_download_url(bundle.repo, bundle.release_tag, asset_name)
+
+
+def resolve_newest_release_tag(ops: ModuleOps, repo: str) -> str:
+ """Newest published (non-draft/non-prerelease) release tag for `repo` by
+ ``published_at`` -- what the freshness checks use, NOT GitHub's
+ ``/releases/latest`` pointer (sorts by commit date, can lag the newest build)."""
+ payload = ops.fetch_json(f"https://api.github.com/repos/{repo}/releases?per_page=30")
+ if not isinstance(payload, list):
+ raise PrebuiltFallback(f"unexpected releases payload for {repo}")
+ published = [
+ r
+ for r in payload
+ if isinstance(r, dict)
+ and not r.get("draft")
+ and not r.get("prerelease")
+ and isinstance(r.get("tag_name"), str)
+ and r.get("tag_name")
+ ]
+ if not published:
+ raise PrebuiltFallback(f"{repo} has no published prebuilt release yet")
+ newest = max(published, key = lambda r: r.get("published_at") or "")
+ return newest["tag_name"]
+
+
+def resolve_release_tag(
+ ops: ModuleOps, published_repo: str, *, published_release_tag: str | None
+) -> str:
+ """The release tag to install: an explicit override, else the newest
+ published release resolved at runtime."""
+ override = (published_release_tag or "").strip()
+ if override:
+ return override
+ return ops.resolve_newest_release_tag(published_repo)
+
+
+def resolve_release_via_download_host(
+ ops: ModuleOps, repo: str, published_release_tag: str | None
+) -> tuple[ReleaseBundle, dict[str, str]] | None:
+ """Resolve the release + manifest + checksum index entirely from the download
+ host, with zero api.github.com calls. None (caller falls back to the API) on a
+ missing/renamed asset, a 404, or a tag mismatch. Fetches the checksum index
+ first (an in-progress release can publish it before the manifest)."""
+ manifest_asset = ops.MANIFEST_ASSET_NAME
+ sha_asset = ops.SHA256_ASSET_NAME
+ release_tag = (published_release_tag or "").strip() or ops._download_host_latest_release_tag(
+ repo
+ )
+ if not release_tag:
+ return None
+ sha_url = ops.release_asset_download_url(repo, release_tag, sha_asset)
+ try:
+ sha_payload = ops._download_host_json(sha_url)
+ except urllib.error.HTTPError as exc:
+ if exc.code == 404:
+ return None
+ raise
+ except (
+ urllib.error.URLError,
+ OSError,
+ socket.timeout,
+ UnicodeDecodeError,
+ json.JSONDecodeError,
+ ):
+ return None
+ try:
+ checksums = ops.parse_release_checksums(repo, release_tag, sha_payload)
+ except PrebuiltFallback:
+ return None # schema/component/tag mismatch -> let the API path decide
+ manifest_url = ops.release_asset_download_url(repo, release_tag, manifest_asset)
+ try:
+ manifest_payload = ops._download_host_json(manifest_url)
+ except urllib.error.HTTPError as exc:
+ if exc.code == 404:
+ return None
+ raise
+ except (
+ urllib.error.URLError,
+ OSError,
+ socket.timeout,
+ UnicodeDecodeError,
+ json.JSONDecodeError,
+ ):
+ return None
+ try:
+ manifest = ops.parse_manifest(
+ manifest_payload, label = f"{manifest_asset} in {repo}@{release_tag}"
+ )
+ except PrebuiltFallback:
+ return None
+ # Tag-pinned CDN URLs for every asset the install may fetch (asset_download_url
+ # reconstructs any missing one), keeping this a pure download-host path.
+ names = {
+ str(a.get("asset"))
+ for a in manifest.get("artifacts", [])
+ if isinstance(a, dict) and a.get("asset")
+ }
+ names |= {manifest_asset, sha_asset}
+ asset_urls = {name: ops.release_asset_download_url(repo, release_tag, name) for name in names}
+ bundle = ReleaseBundle(
+ repo = repo, release_tag = release_tag, manifest = manifest, asset_urls = asset_urls
+ )
+ return bundle, checksums
+
+
+def fetch_release_for_install(
+ ops: ModuleOps, repo: str, *, published_release_tag: str | None
+) -> tuple[ReleaseBundle, dict[str, str]]:
+ """Resolve the release + manifest + checksum index, preferring the download
+ host (no api.github.com rate limit) and falling back to the GitHub API. The
+ single network seam the install/probe paths use."""
+ fast = ops._resolve_release_via_download_host(repo, published_release_tag)
+ if fast is not None:
+ bundle, checksums = fast
+ ops.log(f"resolved {repo}@{bundle.release_tag} via the download host (no GitHub API)")
+ return bundle, checksums
+ release_tag = ops.resolve_release_tag(repo, published_release_tag = published_release_tag)
+ bundle = ops.fetch_release_bundle(repo, release_tag)
+ checksums = ops.fetch_release_checksums(bundle)
+ return bundle, checksums
+
+
+# ── Marker and fingerprint ──
+def compute_install_fingerprint(
+ *,
+ published_repo: str,
+ release_tag: str,
+ upstream_tag: str | None,
+ source_commit: str | None,
+ asset: str,
+ asset_sha256: str,
+ backend: str,
+ runtime_line: str | None,
+ coverage: dict[str, Any],
+) -> str:
+ payload = {
+ "published_repo": published_repo,
+ "release_tag": release_tag,
+ "upstream_tag": upstream_tag,
+ "source_commit": source_commit,
+ "asset": asset,
+ "asset_sha256": asset_sha256,
+ "backend": backend,
+ "runtime_line": runtime_line,
+ "coverage": coverage,
+ }
+ return hashlib.sha256(
+ json.dumps(payload, sort_keys = True, separators = (",", ":")).encode("utf-8")
+ ).hexdigest()
+
+
+@dataclass(frozen = True)
+class InstallSelection:
+ """The identity of a chosen prebuilt: everything the marker/fingerprint record."""
+
+ published_repo: str
+ release_tag: str
+ upstream_tag: str | None
+ source_commit: str | None
+ asset: str
+ asset_sha256: str
+ backend: str
+ runtime_line: str | None
+ coverage: dict[str, Any]
+ studio_protocol: str | None
+ # Slim pairing identity (whisper slim bundles ride the llama ggml runtime);
+ # all None for fat installs, never part of the fingerprint.
+ install_kind: str | None = None
+ paired_llama_tag: str | None = None
+ linked_from: str | None = None
+ # Filenames the slim wiring hardlinked beside the server; the sidecar launch
+ # guard verifies exactly these instead of hardcoded per-OS names.
+ linked_libraries: tuple[str, ...] | None = None
+ runtime_wiring_version: int | None = None
+ linked_runtime_directories: tuple[str, ...] | None = None
+
+ def fingerprint(self) -> str:
+ return compute_install_fingerprint(
+ published_repo = self.published_repo,
+ release_tag = self.release_tag,
+ upstream_tag = self.upstream_tag,
+ source_commit = self.source_commit,
+ asset = self.asset,
+ asset_sha256 = self.asset_sha256,
+ backend = self.backend,
+ runtime_line = self.runtime_line,
+ coverage = self.coverage,
+ )
+
+
+def selection_from_artifact(
+ ops: ModuleOps,
+ *,
+ published_repo: str,
+ release_tag: str,
+ manifest: dict[str, Any],
+ artifact: dict[str, Any],
+ backend: str,
+ asset_sha256: str,
+) -> InstallSelection:
+ return InstallSelection(
+ published_repo = published_repo,
+ release_tag = release_tag,
+ upstream_tag = manifest.get("upstream_tag"),
+ source_commit = manifest.get("source_commit"),
+ asset = str(artifact.get("asset")),
+ asset_sha256 = asset_sha256,
+ backend = backend,
+ runtime_line = artifact.get("runtime_line")
+ if isinstance(artifact.get("runtime_line"), str)
+ else None,
+ coverage = ops.artifact_coverage(artifact),
+ studio_protocol = manifest.get("studio_protocol"),
+ )
+
+
+def metadata_path(ops: ModuleOps, install_dir: Path) -> Path:
+ return install_dir / ops.METADATA_FILENAME
+
+
+def write_prebuilt_metadata(ops: ModuleOps, install_dir: Path, selection: InstallSelection) -> None:
+ coverage = selection.coverage
+ payload = {
+ "schema_version": ops.SCHEMA_VERSION,
+ "component": ops.COMPONENT,
+ "published_repo": selection.published_repo,
+ "release_tag": selection.release_tag,
+ "upstream_tag": selection.upstream_tag,
+ "source_commit": selection.source_commit,
+ "asset": selection.asset,
+ "asset_sha256": selection.asset_sha256,
+ "backend": selection.backend,
+ "runtime_line": selection.runtime_line,
+ "sm_coverage": coverage.get("sm_coverage") or coverage.get("sm"),
+ "gfx_coverage": coverage.get("gfx_coverage") or coverage.get("gfx"),
+ "min_os": coverage.get("min_os"),
+ "studio_protocol": selection.studio_protocol,
+ "install_fingerprint": selection.fingerprint(),
+ "installed_at_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
+ }
+ if selection.install_kind == "slim":
+ # Additive slim fields; fat markers keep the legacy payload exactly.
+ payload["install_kind"] = "slim"
+ payload["paired_llama_tag"] = selection.paired_llama_tag
+ payload["linked_from"] = selection.linked_from
+ if selection.linked_libraries is not None:
+ payload["linked_libraries"] = list(selection.linked_libraries)
+ if selection.runtime_wiring_version is not None:
+ payload["runtime_wiring_version"] = selection.runtime_wiring_version
+ if selection.linked_runtime_directories is not None:
+ payload["linked_runtime_directories"] = list(selection.linked_runtime_directories)
+ ops.metadata_path(install_dir).write_text(
+ json.dumps(payload, indent = 2) + "\n", encoding = "utf-8"
+ )
+
+
+def load_prebuilt_metadata(ops: ModuleOps, install_dir: Path) -> dict[str, Any] | None:
+ path = ops.metadata_path(install_dir)
+ if not path.is_file():
+ return None
+ try:
+ payload = json.loads(path.read_text(encoding = "utf-8"))
+ except (json.JSONDecodeError, OSError):
+ return None
+ return payload if isinstance(payload, dict) else None
+
+
+def existing_install_matches(
+ ops: ModuleOps, install_dir: Path, host: Any, selection: InstallSelection
+) -> bool:
+ """True iff the marker records this exact selection and the server binary is on disk."""
+ metadata = ops.load_prebuilt_metadata(install_dir)
+ if metadata is None:
+ return False
+ if not ops.installed_server_path(install_dir, host).is_file():
+ return False
+ recorded = metadata.get("install_fingerprint")
+ if not isinstance(recorded, str) or recorded != selection.fingerprint():
+ return False
+ ops.log(
+ f"existing {ops.COMPONENT} install already matches {selection.release_tag} "
+ f"({selection.backend}); nothing to do"
+ )
+ return True
+
+
+# ── Install tree assembly and staged activation ──
+def locate_server_in_tree(ops: ModuleOps, root: Path, host: Any) -> Path:
+ name = ops.server_binary_name(host)
+ matches = sorted(root.rglob(name))
+ if not matches:
+ raise PrebuiltFallback(f"archive did not contain a {name} binary")
+ return matches[0]
+
+
+def assemble_install_tree(ops: ModuleOps, bundle_root: Path, staged_root: Path, host: Any) -> Path:
+ """Lay out staged_root as a full install: <runtime bin dir>/<server + libs>.
+
+ Everything beside the server in the archive (shared libs, backend kernel
+ subdirs, license/build-info) is co-located into the canonical bin dir so the
+ server's RUNPATH=$ORIGIN resolves its libs.
+ """
+ bin_dir = ops.runtime_bin_dir(staged_root, host)
+ bin_dir.mkdir(parents = True, exist_ok = True)
+ for entry in sorted(bundle_root.iterdir()):
+ dest = bin_dir / entry.name
+ if entry.is_dir() and not entry.is_symlink():
+ shutil.copytree(entry, dest, symlinks = True)
+ else:
+ shutil.copy2(entry, dest, follow_symlinks = False)
+ server = bin_dir / ops.server_binary_name(host)
+ if not server.exists():
+ raise PrebuiltFallback(f"staged install is missing the {ops.COMPONENT} server binary")
+ if not host.is_windows:
+ os.chmod(server, server.stat().st_mode | 0o111)
+ return server
+
+
+def swap_into_place(staged_root: Path, install_dir: Path) -> None:
+ """Atomically replace install_dir with staged_root (same filesystem), with rollback."""
+ install_dir.parent.mkdir(parents = True, exist_ok = True)
+ backup: Path | None = None
+ try:
+ if install_dir.exists():
+ backup = install_dir.parent / f".{install_dir.name}.old-{os.getpid()}"
+ os.replace(install_dir, backup)
+ os.replace(staged_root, install_dir)
+ except OSError as exc:
+ restored = False
+ if backup is not None and backup.exists() and not install_dir.exists():
+ try:
+ os.replace(backup, install_dir)
+ restored = True
+ except OSError as rollback_exc:
+ raise PrebuiltFallback(
+ "prebuilt activation failed and the previous install could not be restored "
+ f"({exc}; rollback: {rollback_exc})"
+ ) from rollback_exc
+ if is_busy_lock_error(exc):
+ detail = "; restored the previous install" if restored else ""
+ raise BusyInstallConflict(
+ f"the existing install appears to still be in use{detail} ({exc})"
+ ) from exc
+ raise
+ if backup is not None:
+ shutil.rmtree(backup, ignore_errors = True)
+
+
+def validate_staged_server(ops: ModuleOps, staged_root: Path, host: Any) -> None:
+ """Optional pre-activate smoke test, gated off by default (the component's
+ _RUN_STAGED_PREBUILT_VALIDATION switch)."""
+ if not ops._RUN_STAGED_PREBUILT_VALIDATION:
+ return
+ server = ops.installed_server_path(staged_root, host)
+ env = os.environ.copy()
+ bin_dir = str(ops.runtime_bin_dir(staged_root, host))
+ for var in ("LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH"):
+ env[var] = bin_dir + (os.pathsep + env[var] if env.get(var) else "")
+ try:
+ result = subprocess.run(
+ [str(server), "--help"],
+ capture_output = True,
+ text = True,
+ timeout = 60,
+ env = env,
+ **ops.windows_hidden_subprocess_kwargs(),
+ )
+ except (OSError, subprocess.SubprocessError) as exc:
+ raise PrebuiltFallback(f"staged {ops.COMPONENT} server failed to launch: {exc}") from exc
+ if result.returncode != 0:
+ raise PrebuiltFallback(
+ f"staged {ops.COMPONENT} server --help exited {result.returncode}: "
+ f"{result.stderr.strip()}"
+ )
+
+
+def windows_hidden_subprocess_kwargs() -> dict[str, object]:
+ """Return Windows-only subprocess kwargs that suppress console windows."""
+ if sys.platform != "win32":
+ return {}
+
+ kwargs: dict[str, object] = {}
+ create_no_window = getattr(subprocess, "CREATE_NO_WINDOW", 0)
+ if create_no_window:
+ kwargs["creationflags"] = create_no_window
+
+ startupinfo_factory = getattr(subprocess, "STARTUPINFO", None)
+ startf_use_showwindow = getattr(subprocess, "STARTF_USESHOWWINDOW", 0)
+ sw_hide = getattr(subprocess, "SW_HIDE", 0)
+ if startupinfo_factory is not None and startf_use_showwindow:
+ startupinfo = startupinfo_factory()
+ startupinfo.dwFlags |= startf_use_showwindow
+ startupinfo.wShowWindow = sw_hide
+ kwargs["startupinfo"] = startupinfo
+
+ return kwargs
+
+
+def install_from_bundle(
+ ops: ModuleOps, install_dir: Path, host: Any, bundle: ReleaseBundle, selection: InstallSelection
+) -> None:
+ staging_root = install_dir.parent / ops.INSTALL_STAGING_ROOT_NAME
+ staging_root.mkdir(parents = True, exist_ok = True)
+ staging = Path(tempfile.mkdtemp(prefix = f"{install_dir.name}.staging-", dir = staging_root))
+ try:
+ archive_path = staging / selection.asset
+ url = ops.asset_download_url(bundle, selection.asset)
+ ops.log(f"downloading {url}")
+ ops.download_file_verified(
+ url, archive_path, expected_sha256 = selection.asset_sha256, label = selection.asset
+ )
+ extract_dir = staging / "extracted"
+ ops.extract_archive(archive_path, extract_dir)
+
+ server = ops.locate_server_in_tree(extract_dir, host)
+ bundle_root = server.parent
+
+ staged_root = staging / "staged"
+ ops.assemble_install_tree(bundle_root, staged_root, host)
+ # Component hook (default no-op): slim whisper wires the llama ggml
+ # runtime here so staged validation sees the final linked tree; a returned
+ # selection (with the wired filenames) supersedes the input so the marker
+ # records what was actually linked.
+ updated = ops.prepare_runtime_payload(staged_root, host, selection)
+ if updated is not None:
+ selection = updated
+ ops.validate_staged_server(staged_root, host)
+ ops.write_prebuilt_metadata(staged_root, selection)
+ ops._swap_into_place(staged_root, install_dir)
+ finally:
+ shutil.rmtree(staging, ignore_errors = True)
+ try:
+ staging_root.rmdir()
+ except OSError:
+ pass
+
+
+def plan_selection(
+ ops: ModuleOps,
+ host: Any,
+ bundle: ReleaseBundle,
+ *,
+ published_repo: str,
+ backend: str,
+ checksums: dict[str, str],
+) -> InstallSelection:
+ """Choose an artifact (with the component's fallback policy) and resolve its
+ trusted sha256 from the release checksum index."""
+ artifact, effective_backend, _used_fallback = ops.select_artifact_with_fallback(
+ bundle.manifest, host, backend
+ )
+ asset = str(artifact.get("asset"))
+ manifest_sha256 = artifact.get("sha256") if isinstance(artifact.get("sha256"), str) else None
+ expected_sha = ops.expected_sha256_for(
+ checksums,
+ asset,
+ manifest_sha256 = manifest_sha256,
+ )
+ return ops.selection_from_artifact(
+ published_repo = published_repo,
+ release_tag = bundle.release_tag,
+ manifest = bundle.manifest,
+ artifact = artifact,
+ backend = effective_backend,
+ asset_sha256 = expected_sha,
+ )
+
+
+def install_prebuilt(
+ ops: ModuleOps,
+ install_dir: Path,
+ *,
+ published_repo: str,
+ published_release_tag: str | None = None,
+ backend: str | None = "auto",
+ cpu_fallback: bool = False,
+ force: bool = False,
+ host: Any = None,
+) -> int:
+ if host is None:
+ host = ops.detect_host()
+ effective_backend = ops.resolve_backend(host, backend, cpu_fallback = cpu_fallback)
+ os_token, arch_token = ops.host_platform_tokens(host)
+ ops.log(
+ f"target {ops.COMPONENT} from {published_repo} "
+ f"({os_token}-{arch_token}, backend {effective_backend})"
+ )
+
+ bundle, checksums = ops.fetch_release_for_install(
+ published_repo, published_release_tag = published_release_tag
+ )
+ selection = ops.plan_selection(
+ host,
+ bundle,
+ published_repo = published_repo,
+ backend = effective_backend,
+ checksums = checksums,
+ )
+
+ return install_selected_prebuilt(
+ ops,
+ install_dir,
+ host = host,
+ bundle = bundle,
+ selection = selection,
+ force = force,
+ )
+
+
+def install_selected_prebuilt(
+ ops: ModuleOps,
+ install_dir: Path,
+ *,
+ host: Any,
+ bundle: ReleaseBundle,
+ selection: InstallSelection,
+ force: bool,
+) -> int:
+ """Validate and activate an already selected release plan.
+
+ Components that need to examine more than one published release can keep
+ release selection component-specific while sharing the lock, idempotency,
+ atomic activation, and post-install verification path.
+ """
+
+ if not force and ops.existing_install_matches(install_dir, host, selection):
+ return 0
+
+ with ops.install_lock(ops.install_lock_path(install_dir)):
+ # Re-check under the lock: a concurrent run may have just finished.
+ if not force and ops.existing_install_matches(install_dir, host, selection):
+ return 0
+ ops._install_from_bundle(install_dir, host, bundle, selection)
+
+ server = ops.installed_server_path(install_dir, host)
+ if not server.is_file():
+ raise PrebuiltFallback(f"post-install verification failed: {server} is missing")
+ ops.log(
+ f"installed {ops.COMPONENT} {bundle.release_tag} " f"({selection.backend}) at {install_dir}"
+ )
+ return 0
+
+
+def resolve_prebuilt(
+ ops: ModuleOps,
+ host: Any,
+ *,
+ published_repo: str,
+ published_release_tag: str | None,
+ backend: str | None,
+ cpu_fallback: bool,
+) -> dict[str, Any]:
+ """Host-aware "is a prebuilt available" probe. No archive download."""
+ effective_backend = ops.resolve_backend(host, backend, cpu_fallback = cpu_fallback)
+ try:
+ bundle, _checksums = ops.fetch_release_for_install(
+ published_repo, published_release_tag = published_release_tag
+ )
+ artifact, resolved_backend, used_fallback = ops.select_artifact_with_fallback(
+ bundle.manifest, host, effective_backend
+ )
+ except PrebuiltFallback:
+ return {"prebuilt_available": False, "repo": published_repo}
+ os_token, arch_token = ops.host_platform_tokens(host)
+ payload = {
+ "prebuilt_available": True,
+ "repo": published_repo,
+ "release_tag": bundle.release_tag,
+ "upstream_tag": bundle.manifest.get("upstream_tag"),
+ "backend": resolved_backend,
+ "requested_backend": effective_backend,
+ "cpu_fallback": used_fallback,
+ "asset": str(artifact.get("asset")),
+ "os": os_token,
+ "arch": arch_token,
+ "runtime_line": artifact.get("runtime_line"),
+ }
+ # Component hook (default none): whisper adds install_kind slim|fat. The JSON
+ # emitter sorts keys, so an appended field can't perturb the legacy key order.
+ payload.update(ops.resolver_payload_extra(artifact))
+ return payload
+
+
+def prepare_runtime_payload(staged_root: Path, host: Any, selection: InstallSelection) -> Any:
+ """Post-assemble hook; the core stages nothing extra. Components override it
+ to wire external runtime files into the staged bin dir (whisper slim hardlinks
+ the llama install's ggml libraries) before validation, and may return an
+ updated InstallSelection for the marker to record instead."""
+ return None
+
+
+def resolver_payload_extra(artifact: dict[str, Any]) -> dict[str, Any]:
+ """Additive --resolve-prebuilt payload fields; the core adds none."""
+ return {}
+
+
+def installed_server_path(ops: ModuleOps, install_dir: Path, host: Any) -> Path:
+ return ops.runtime_bin_dir(install_dir, host) / ops.server_binary_name(host)
+
+
+# Underscored aliases so ops lookups that mirror the installer modules' private
+# names still resolve for a descriptor-only component.
+_download_host_latest_release_tag = download_host_latest_release_tag
+_download_host_json = fetch_download_host_json
+_resolve_release_via_download_host = resolve_release_via_download_host
+_install_from_bundle = install_from_bundle
+_swap_into_place = swap_into_place
+
+
+def emit_resolver_output(payload: dict[str, Any], *, output_format: str) -> None:
+ if output_format == "json":
+ print(json.dumps(payload, sort_keys = True))
+ return
+ if "asset" in payload and payload.get("prebuilt_available"):
+ print(payload["asset"])
+ return
+ print(json.dumps(payload, sort_keys = True))
diff --git a/studio/setup.ps1 b/studio/setup.ps1
index 7bf6627578f..c6932121c90 100644
--- a/studio/setup.ps1
+++ b/studio/setup.ps1
@@ -2655,12 +2655,13 @@ if (Test-Path -LiteralPath $LegacyStudioHome -PathType Container) {
}
$StudioHomeIsCustom = ($_studioHomeCanon -ne $LegacyStudioHome)
# Directory-local evidence that Unsloth created $Path, used to adopt a custom-home
-# llama.cpp predating the .unsloth-studio-owned marker (see setup.sh). Only the
-# prebuilt UNSLOTH_PREBUILT_INFO.json counts; source builds are indistinguishable
-# from a user clone on Windows and stay under the strict guard.
+# llama.cpp or whisper.cpp predating the .unsloth-studio-owned marker (see
+# setup.sh). Only Unsloth prebuilt markers count; source builds are
+# indistinguishable from a user clone on Windows and stay under the strict guard.
function Test-StudioOwnedAdoptable {
param([Parameter(Mandatory = $true)][string]$Path)
if (Test-Path -LiteralPath (Join-Path $Path "UNSLOTH_PREBUILT_INFO.json") -PathType Leaf) { return $true }
+ if (Test-Path -LiteralPath (Join-Path $Path "UNSLOTH_WHISPER_PREBUILT_INFO.json") -PathType Leaf) { return $true }
return $false
}
function Assert-StudioOwnedOrAbsent {
@@ -3767,6 +3768,83 @@ if ($LocalLlamaCppLinked) {
}
}
+# ==========================================================================
+# PHASE 3.4: Install the whisper.cpp prebuilt (dictation runtime)
+# ==========================================================================
+# Mirrors the llama.cpp prebuilt install above; current whisper releases are
+# slim bundles that reuse the llama install's ggml runtime, so this runs after
+# llama. Failure is never fatal: local dictation falls back to Transformers STT.
+$WhisperCppDir = Join-Path $UnslothHome "whisper.cpp"
+$WhisperInstaller = Join-Path $PSScriptRoot "install_whisper_prebuilt.py"
+# Same opt-outs as setup.sh: a user-configured binary/dir or an explicit skip
+# disables the managed install entirely.
+if ($env:WHISPER_SERVER_PATH -or $env:UNSLOTH_WHISPER_CPP_PATH) {
+ substep "whisper.cpp: using a user-configured binary/dir; skipping managed install"
+} elseif ($env:UNSLOTH_SKIP_WHISPER_INSTALL -eq "1") {
+ substep "whisper.cpp: install skipped (UNSLOTH_SKIP_WHISPER_INSTALL=1)"
+} elseif (Test-Path -LiteralPath $WhisperInstaller) {
+ # The installer's atomic activation replaces the whole directory, so the
+ # custom-home ownership guard must run first (mirrors the llama block).
+ if ($StudioHomeIsCustom) {
+ Assert-StudioOwnedOrAbsent -Path $WhisperCppDir -Label "whisper.cpp install"
+ }
+ $whisperArgs = @($WhisperInstaller, "--install-dir", $WhisperCppDir)
+ if ($env:UNSLOTH_WHISPER_RELEASE_TAG) {
+ $whisperArgs += @("--published-release-tag", $env:UNSLOTH_WHISPER_RELEASE_TAG)
+ }
+ if ($script:ROCmGfxArch) {
+ $whisperArgs += @("--rocm-gfx", $script:ROCmGfxArch)
+ } elseif ($HasROCm) {
+ $whisperArgs += "--has-rocm"
+ }
+ $prevEAPWhisper = $ErrorActionPreference
+ $ErrorActionPreference = "Continue"
+ $previousNativeErrorPreferenceW = $null
+ $restoreNativeErrorPreferenceW = $false
+ if ($PSVersionTable.PSVersion.Major -ge 7) {
+ $previousNativeErrorPreferenceW = $PSNativeCommandUseErrorActionPreference
+ $PSNativeCommandUseErrorActionPreference = $false
+ $restoreNativeErrorPreferenceW = $true
+ }
+ try {
+ $whisperOutput = & python @whisperArgs 2>&1 | Out-String
+ $whisperExit = $LASTEXITCODE
+ } finally {
+ if ($restoreNativeErrorPreferenceW) {
+ $PSNativeCommandUseErrorActionPreference = $previousNativeErrorPreferenceW
+ }
+ }
+ $ErrorActionPreference = $prevEAPWhisper
+ if ($whisperExit -eq 0) {
+ if ($whisperOutput -match "already matches") {
+ step "whisper.cpp" "prebuilt up to date"
+ } else {
+ step "whisper.cpp" "prebuilt installed"
+ }
+ if ($StudioHomeIsCustom -and (Test-Path -LiteralPath $WhisperCppDir -PathType Container)) {
+ Mark-StudioOwned -Path $WhisperCppDir
+ }
+ } elseif ($whisperExit -eq 3) {
+ step "whisper.cpp" "install busy; keeping existing runtime" "Yellow"
+ } elseif ($whisperExit -eq 2) {
+ $requiredWhisperLlamaTag = "unknown"
+ if ($whisperOutput -match "slim bundle requires llama\.cpp ([^;\s]+)") {
+ $requiredWhisperLlamaTag = $Matches[1]
+ }
+ $installedWhisperLlamaTag = "unknown"
+ $llamaMarker = Join-Path $LlamaCppDir "UNSLOTH_PREBUILT_INFO.json"
+ if (Test-Path -LiteralPath $llamaMarker -PathType Leaf) {
+ try {
+ $markerPayload = Get-Content -LiteralPath $llamaMarker -Raw | ConvertFrom-Json
+ if ($markerPayload.release_tag) { $installedWhisperLlamaTag = $markerPayload.release_tag }
+ } catch {}
+ }
+ step "whisper.cpp" "no compatible prebuilt (installed llama.cpp $installedWhisperLlamaTag; whisper requires $requiredWhisperLlamaTag); curated whisper.cpp dictation is unavailable; publish paired releases in llama.cpp then whisper.cpp order; browser and Transformers dictation remain available" "Yellow"
+ } else {
+ step "whisper.cpp" "prebuilt install failed; curated whisper.cpp dictation is unavailable; retry setup or inspect verbose output; browser and Transformers dictation remain available" "Yellow"
+ }
+}
+
# ==========================================================================
# PHASE 3.5: Install OpenSSL dev (for HTTPS support in llama-server)
# ==========================================================================
diff --git a/studio/setup.sh b/studio/setup.sh
index 0183ef37763..3c97f770655 100755
--- a/studio/setup.sh
+++ b/studio/setup.sh
@@ -537,11 +537,13 @@ if [ "$_studio_home_canon" != "$_LEGACY_STUDIO_HOME" ]; then
fi
# Directory-local evidence Unsloth created "$1": only prebuilt-installer metadata
# counts (UNSLOTH_PREBUILT_INFO.json for llama.cpp, UNSLOTH_NODE_PREBUILT_INFO.json
-# for Node), both written only by our installers. Mirrors the setup.ps1 Node guard.
-# A markerless source build stays strict since this runs right before an rm -rf.
+# for Node, UNSLOTH_WHISPER_PREBUILT_INFO.json for whisper.cpp), all written only
+# by our installers. Mirrors the setup.ps1 Node guard. A markerless source build
+# stays strict since this runs right before an rm -rf.
_studio_owned_adoptable() {
[ -f "$1/UNSLOTH_PREBUILT_INFO.json" ] && return 0
[ -f "$1/UNSLOTH_NODE_PREBUILT_INFO.json" ] && return 0
+ [ -f "$1/UNSLOTH_WHISPER_PREBUILT_INFO.json" ] && return 0
return 1
}
_assert_studio_owned_or_absent() {
@@ -1965,6 +1967,99 @@ if [ ! -L "$LLAMA_CPP_DIR" ] && {
_remove_agent_instruction_files "$LLAMA_CPP_DIR"
fi
+# ── whisper.cpp (local speech-to-text dictation engine) ──
+# Optional runtime for local dictation. Fail-open: any failure leaves the
+# Transformers STT engine and browser dictation working, so it never aborts
+# setup (unlike llama.cpp). Runs in 'unsloth studio update' too so the runtime
+# installs/refreshes without a compiler. Installs beside llama.cpp under the
+# same managed home the sidecar's _managed_whisper_cpp_dir() resolves.
+WHISPER_CPP_DIR="$UNSLOTH_HOME/whisper.cpp"
+if [ -n "${WHISPER_SERVER_PATH:-}" ] || [ -n "${UNSLOTH_WHISPER_CPP_PATH:-}" ]; then
+ verbose_substep "whisper.cpp: using a user-configured binary/dir; skipping managed install"
+elif [ "${UNSLOTH_SKIP_WHISPER_INSTALL:-0}" = "1" ]; then
+ verbose_substep "whisper.cpp: install skipped (UNSLOTH_SKIP_WHISPER_INSTALL=1)"
+else
+ if [ "$_STUDIO_HOME_IS_CUSTOM" = true ]; then
+ _assert_studio_owned_or_absent "$WHISPER_CPP_DIR" "whisper.cpp install"
+ fi
+ _WHISPER_CMD=(python "$SCRIPT_DIR/install_whisper_prebuilt.py" --install-dir "$WHISPER_CPP_DIR")
+ if [ -n "${UNSLOTH_WHISPER_RELEASE_TAG:-}" ]; then
+ _WHISPER_CMD+=(--published-release-tag "$UNSLOTH_WHISPER_RELEASE_TAG")
+ fi
+ if [ -n "${_setup_gfx:-}" ]; then
+ _WHISPER_CMD+=(--rocm-gfx "$_setup_gfx")
+ elif [ "$_setup_amd_detected" = true ]; then
+ _WHISPER_CMD+=(--has-rocm)
+ fi
+ _WHISPER_LOG="$(mktemp)"
+ set +e
+ if _is_verbose; then
+ "${_WHISPER_CMD[@]}" 2>&1 | tee "$_WHISPER_LOG"
+ _WHISPER_STATUS=${PIPESTATUS[0]}
+ else
+ "${_WHISPER_CMD[@]}" >"$_WHISPER_LOG" 2>&1
+ _WHISPER_STATUS=$?
+ fi
+ set -e
+ if [ "$_WHISPER_STATUS" -eq 0 ]; then
+ if grep -Fq "already matches" "$_WHISPER_LOG"; then
+ step "whisper.cpp" "prebuilt up to date"
+ else
+ step "whisper.cpp" "prebuilt installed"
+ fi
+ if [ "$_STUDIO_HOME_IS_CUSTOM" = true ] && [ -d "$WHISPER_CPP_DIR" ]; then
+ : > "$WHISPER_CPP_DIR/$_STUDIO_OWNED_MARKER" 2>/dev/null || true
+ fi
+ rm -f "$_WHISPER_LOG"
+ elif [ "$_WHISPER_STATUS" -eq 3 ]; then
+ # A warm dictation server holds the binary; keep the old install.
+ step "whisper.cpp" "install busy; keeping existing runtime" "$C_WARN"
+ rm -f "$_WHISPER_LOG"
+ else
+ # A source build is opt-in. Keep the installer log until fallback has
+ # finished so setup can distinguish release skew from an operational
+ # installer failure and report the exact pairing when available.
+ _WHISPER_RECOVERED=false
+ _WHISPER_BUILD="$SCRIPT_DIR/../scripts/build_whisper_cpp.sh"
+ if [ "${UNSLOTH_WHISPER_FORCE_COMPILE:-0}" = "1" ] && [ -f "$_WHISPER_BUILD" ] \
+ && command -v cmake >/dev/null 2>&1 && command -v git >/dev/null 2>&1; then
+ substep "whisper.cpp prebuilt unavailable; building from source (UNSLOTH_WHISPER_FORCE_COMPILE=1)..."
+ # The source build overwrites whisper-server in the managed dir but
+ # knows nothing about the prebuilt marker; a stale marker would make
+ # a later setup run report "already matches" and skip repairing the
+ # prebuilt over the source binary. Drop it before building.
+ rm -f "$WHISPER_CPP_DIR/UNSLOTH_WHISPER_PREBUILT_INFO.json" 2>/dev/null || true
+ if run_quiet_no_exit "whisper.cpp source build" sh "$_WHISPER_BUILD"; then
+ _WHISPER_RECOVERED=true
+ step "whisper.cpp" "source build installed"
+ if [ "$_STUDIO_HOME_IS_CUSTOM" = true ] && [ -d "$WHISPER_CPP_DIR" ]; then
+ : > "$WHISPER_CPP_DIR/$_STUDIO_OWNED_MARKER" 2>/dev/null || true
+ fi
+ else
+ :
+ fi
+ fi
+ if [ "$_WHISPER_RECOVERED" != true ]; then
+ if [ "$_WHISPER_STATUS" -eq 2 ]; then
+ _WHISPER_REQUIRED_TAG="$(sed -n 's/.*slim bundle requires llama\.cpp \([^; ]*\).*/\1/p' "$_WHISPER_LOG" | tail -n 1)"
+ _WHISPER_INSTALLED_TAG="$(python - "$UNSLOTH_HOME/llama.cpp/UNSLOTH_PREBUILT_INFO.json" <<'PY' 2>/dev/null || true
+import json, sys
+try:
+ print(json.load(open(sys.argv[1], encoding="utf-8")).get("release_tag", ""))
+except Exception:
+ pass
+PY
+)"
+ _WHISPER_PAIRING="installed llama.cpp ${_WHISPER_INSTALLED_TAG:-unknown}; whisper requires ${_WHISPER_REQUIRED_TAG:-unknown}"
+ step "whisper.cpp" "no compatible prebuilt ($_WHISPER_PAIRING); curated whisper.cpp dictation is unavailable; publish the paired releases in llama.cpp then whisper.cpp order; browser and Transformers dictation remain available" "$C_WARN"
+ else
+ step "whisper.cpp" "prebuilt install failed; curated whisper.cpp dictation is unavailable; retry setup or inspect verbose output; browser and Transformers dictation remain available" "$C_WARN"
+ fi
+ fi
+ rm -f "$_WHISPER_LOG"
+ fi
+fi
+
# ── Footer ──
if [ "$_LLAMA_ONLY" = "1" ]; then
echo ""
diff --git a/tests/studio/install/test_install_llama_prebuilt_logic.py b/tests/studio/install/test_install_llama_prebuilt_logic.py
index 9a094ddc0e8..0964c047d57 100644
--- a/tests/studio/install/test_install_llama_prebuilt_logic.py
+++ b/tests/studio/install/test_install_llama_prebuilt_logic.py
@@ -22,7 +22,6 @@ sys.modules[SPEC.name] = INSTALL_LLAMA_PREBUILT
SPEC.loader.exec_module(INSTALL_LLAMA_PREBUILT)
PrebuiltFallback = INSTALL_LLAMA_PREBUILT.PrebuiltFallback
-extract_archive = INSTALL_LLAMA_PREBUILT.extract_archive
binary_env = INSTALL_LLAMA_PREBUILT.binary_env
is_secret_env_name = INSTALL_LLAMA_PREBUILT.is_secret_env_name
scrub_env = INSTALL_LLAMA_PREBUILT.scrub_env
@@ -105,105 +104,10 @@ def approved_checksums_for(
)
-def test_extract_archive_allows_safe_tar_symlink_chain(tmp_path: Path):
- archive_path = tmp_path / "bundle.tar.gz"
- payload = b"shared-object"
-
- with tarfile.open(archive_path, "w:gz") as archive:
- versioned = tarfile.TarInfo("libllama.so.0.0.1")
- versioned.size = len(payload)
- archive.addfile(versioned, io_bytes(payload))
-
- soname = tarfile.TarInfo("libllama.so.0")
- soname.type = tarfile.SYMTYPE
- soname.linkname = "libllama.so.0.0.1"
- archive.addfile(soname)
-
- linker_name = tarfile.TarInfo("libllama.so")
- linker_name.type = tarfile.SYMTYPE
- linker_name.linkname = "libllama.so.0"
- archive.addfile(linker_name)
-
- destination = tmp_path / "extract"
- extract_archive(archive_path, destination)
-
- assert (destination / "libllama.so.0.0.1").read_bytes() == payload
- assert (destination / "libllama.so.0").is_symlink()
- assert (destination / "libllama.so").is_symlink()
- assert (destination / "libllama.so").resolve().read_bytes() == payload
-
-
-def test_extract_archive_allows_safe_tar_hardlink(tmp_path: Path):
- archive_path = tmp_path / "bundle.tar.gz"
- payload = b"quantize"
-
- with tarfile.open(archive_path, "w:gz") as archive:
- target = tarfile.TarInfo("llama-quantize")
- target.size = len(payload)
- archive.addfile(target, io_bytes(payload))
-
- hardlink = tarfile.TarInfo("llama-quantize-copy")
- hardlink.type = tarfile.LNKTYPE
- hardlink.linkname = "llama-quantize"
- archive.addfile(hardlink)
-
- destination = tmp_path / "extract"
- extract_archive(archive_path, destination)
-
- assert (destination / "llama-quantize-copy").read_bytes() == payload
- assert not (destination / "llama-quantize-copy").is_symlink()
-
-
-def test_extract_archive_rejects_absolute_tar_symlink_target(tmp_path: Path):
- archive_path = tmp_path / "bundle.tar.gz"
-
- with tarfile.open(archive_path, "w:gz") as archive:
- entry = tarfile.TarInfo("libllama.so")
- entry.type = tarfile.SYMTYPE
- entry.linkname = "/tmp/libllama.so.0"
- archive.addfile(entry)
-
- with pytest.raises(PrebuiltFallback, match = "archive link used an absolute target"):
- extract_archive(archive_path, tmp_path / "extract")
-
-
-def test_extract_archive_rejects_escaping_tar_symlink_target(tmp_path: Path):
- archive_path = tmp_path / "bundle.tar.gz"
-
- with tarfile.open(archive_path, "w:gz") as archive:
- entry = tarfile.TarInfo("libllama.so")
- entry.type = tarfile.SYMTYPE
- entry.linkname = "../outside/libllama.so.0"
- archive.addfile(entry)
-
- with pytest.raises(PrebuiltFallback, match = "archive link escaped destination"):
- extract_archive(archive_path, tmp_path / "extract")
-
-
-def test_extract_archive_rejects_unresolved_tar_symlink_target(tmp_path: Path):
- archive_path = tmp_path / "bundle.tar.gz"
-
- with tarfile.open(archive_path, "w:gz") as archive:
- entry = tarfile.TarInfo("libllama.so")
- entry.type = tarfile.SYMTYPE
- entry.linkname = "libllama.so.0"
- archive.addfile(entry)
-
- with pytest.raises(PrebuiltFallback, match = "unresolved link entries"):
- extract_archive(archive_path, tmp_path / "extract")
-
-
-def test_extract_archive_rejects_zip_symlink_entry(tmp_path: Path):
- archive_path = tmp_path / "bundle.zip"
-
- with zipfile.ZipFile(archive_path, "w") as archive:
- info = zipfile.ZipInfo("libllama.so")
- info.create_system = 3
- info.external_attr = 0o120777 << 16
- archive.writestr(info, "libllama.so.0")
-
- with pytest.raises(PrebuiltFallback, match = "zip archive contained a symlink entry"):
- extract_archive(archive_path, tmp_path / "extract")
+# The extract_archive guard tests (safe symlink chain / hardlink, absolute or
+# escaping or unresolved symlink targets, zip symlink entries) moved verbatim
+# to tests/studio/install/test_prebuilt_core.py: extract_archive is the shared
+# prebuilt_core implementation, re-exported by this installer.
def test_remove_agent_instruction_files_does_not_follow_links(tmp_path: Path):
diff --git a/tests/studio/install/test_install_whisper_prebuilt_logic.py b/tests/studio/install/test_install_whisper_prebuilt_logic.py
new file mode 100644
index 00000000000..7364ea454d4
--- /dev/null
+++ b/tests/studio/install/test_install_whisper_prebuilt_logic.py
@@ -0,0 +1,1357 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Logic tests for studio/install_whisper_prebuilt.py -- the prebuilt whisper-server installer.
+# No network/GPU: release resolution is injected and archives are built on disk in a tmp dir.
+
+import importlib.util
+import io
+import json
+import sys
+import tarfile
+import zipfile
+from pathlib import Path
+
+import pytest
+
+
+PACKAGE_ROOT = Path(__file__).resolve().parents[3]
+MODULE_PATH = PACKAGE_ROOT / "studio" / "install_whisper_prebuilt.py"
+# The installer imports install_llama_prebuilt (same directory); make studio/
+# importable so that resolves under spec-based loading.
+_STUDIO_DIR = str(MODULE_PATH.parent)
+if _STUDIO_DIR not in sys.path:
+ sys.path.insert(0, _STUDIO_DIR)
+SPEC = importlib.util.spec_from_file_location("studio_install_whisper_prebuilt", MODULE_PATH)
+assert SPEC is not None and SPEC.loader is not None
+M = importlib.util.module_from_spec(SPEC)
+sys.modules[SPEC.name] = M
+SPEC.loader.exec_module(M)
+
+HostInfo = M.HostInfo
+PrebuiltFallback = M.PrebuiltFallback
+ReleaseCompatibilityError = M.ReleaseCompatibilityError
+BusyInstallConflict = M.BusyInstallConflict
+
+RELEASE_TAG = "v1.9.1-unsloth.1"
+UPSTREAM_TAG = "v1.9.1"
+SOURCE_COMMIT = "0" * 40
+STUDIO_PROTOCOL = "inference/multipart-v1"
+
+
+def _host(
+ whisper_os: str,
+ whisper_arch: str,
+ *,
+ has_usable_nvidia: bool = False,
+ has_rocm: bool = False,
+ rocm_gfx: str | None = None,
+ macos_version: tuple[int, int] | None = None,
+) -> HostInfo:
+ ext = ".zip" if whisper_os == "windows" else ".tar.gz"
+ return HostInfo(
+ system = {"linux": "Linux", "macos": "Darwin", "windows": "Windows"}[whisper_os],
+ machine = whisper_arch,
+ whisper_os = whisper_os,
+ whisper_arch = whisper_arch,
+ archive_ext = ext,
+ is_windows = whisper_os == "windows",
+ is_macos = whisper_os == "macos",
+ is_apple_silicon = whisper_os == "macos" and whisper_arch == "arm64",
+ has_usable_nvidia = has_usable_nvidia,
+ has_rocm = has_rocm,
+ rocm_gfx = rocm_gfx,
+ macos_version = macos_version,
+ )
+
+
+def _artifact(os_: str, arch: str, backend: str, asset: str, sha256: str, **extra) -> dict:
+ art = {
+ "os": os_,
+ "arch": arch,
+ "backend": backend,
+ "asset": asset,
+ "sha256": sha256,
+ "runtime_line": extra.get("runtime_line"),
+ }
+ art.update(extra)
+ return art
+
+
+def _manifest(
+ artifacts: list[dict],
+ *,
+ component: str = "whisper.cpp",
+ schema_version: int = 1,
+) -> dict:
+ return {
+ "schema_version": schema_version,
+ "component": component,
+ "studio_protocol": STUDIO_PROTOCOL,
+ "upstream_tag": UPSTREAM_TAG,
+ "source_commit": SOURCE_COMMIT,
+ "artifacts": artifacts,
+ }
+
+
+# ── Host detection (probes come from install_llama_prebuilt.detect_host) ──
+def _llama_host(
+ system: str,
+ machine: str,
+ *,
+ has_usable_nvidia: bool = False,
+ compute_caps: list[str] | None = None,
+ driver_cuda_version: tuple[int, int] | None = None,
+ has_rocm: bool = False,
+ rocm_gfx: str | None = None,
+ macos_version: tuple[int, int] | None = None,
+):
+ """A fake install_llama_prebuilt HostInfo, as llama_detect_host would return."""
+ lowered = machine.lower()
+ return M.llama.HostInfo(
+ system = system,
+ machine = machine,
+ is_windows = system == "Windows",
+ is_linux = system == "Linux",
+ is_macos = system == "Darwin",
+ is_x86_64 = lowered in {"x86_64", "amd64"},
+ is_arm64 = lowered in {"arm64", "aarch64"},
+ nvidia_smi = None,
+ driver_cuda_version = driver_cuda_version,
+ compute_caps = list(compute_caps or []),
+ visible_cuda_devices = None,
+ has_physical_nvidia = has_usable_nvidia,
+ has_usable_nvidia = has_usable_nvidia,
+ has_rocm = has_rocm,
+ rocm_gfx_target = rocm_gfx,
+ macos_version = macos_version,
+ )
+
+
+ "system,machine,exp_os,exp_arch,exp_ext",
+ [
+ ("Linux", "x86_64", "linux", "x64", ".tar.gz"),
+ ("Linux", "aarch64", "linux", "arm64", ".tar.gz"),
+ ("Darwin", "x86_64", "macos", "x64", ".tar.gz"),
+ ("Darwin", "arm64", "macos", "arm64", ".tar.gz"),
+ ("Windows", "AMD64", "windows", "x64", ".zip"),
+ ("Windows", "ARM64", "windows", "arm64", ".zip"),
+ ],
+)
+def test_detect_host(monkeypatch, system, machine, exp_os, exp_arch, exp_ext):
+ monkeypatch.setattr(M, "llama_detect_host", lambda: _llama_host(system, machine))
+ host = M.detect_host()
+ assert (host.whisper_os, host.whisper_arch, host.archive_ext) == (exp_os, exp_arch, exp_ext)
+ assert host.is_windows == (exp_os == "windows")
+ assert host.is_apple_silicon == (exp_os == "macos" and exp_arch == "arm64")
+
+
+def test_detect_host_maps_rocm_fields(monkeypatch):
+ monkeypatch.setattr(
+ M,
+ "llama_detect_host",
+ lambda: _llama_host("Linux", "x86_64", has_rocm = True, rocm_gfx = "gfx1100"),
+ )
+ host = M.detect_host()
+ assert host.has_rocm is True
+ assert host.rocm_gfx == "gfx1100"
+ assert host.has_usable_nvidia is False
+
+
+ "system,machine",
+ [("Plan9", "x86_64"), ("Linux", "sparc64"), ("Linux", "armv7l")],
+)
+def test_detect_host_unsupported(monkeypatch, system, machine):
+ monkeypatch.setattr(M, "llama_detect_host", lambda: _llama_host(system, machine))
+ with pytest.raises(PrebuiltFallback):
+ M.detect_host()
+
+
+# ── Asset naming (pure) ──
+def test_whisper_asset_name():
+ assert (
+ M.whisper_asset_name(RELEASE_TAG, _host("linux", "x64"), "cpu")
+ == "whisper-v1.9.1-unsloth.1-linux-x64-cpu.tar.gz"
+ )
+ assert (
+ M.whisper_asset_name(RELEASE_TAG, _host("macos", "arm64"), "metal")
+ == "whisper-v1.9.1-unsloth.1-macos-arm64-metal.tar.gz"
+ )
+ assert (
+ M.whisper_asset_name(RELEASE_TAG, _host("windows", "x64"), "cuda12")
+ == "whisper-v1.9.1-unsloth.1-windows-x64-cuda12.zip"
+ )
+
+
+# ── Install layout ──
+def test_whisper_server_path_layout():
+ nix = _host("linux", "x64")
+ win = _host("windows", "x64")
+ assert M.whisper_server_path(Path("/w"), nix) == Path("/w/build/bin/whisper-server")
+ assert M.whisper_server_path(Path("/w"), win) == Path("/w/build/bin/Release/whisper-server.exe")
+
+
+# ── Manifest parse + basic selection (wiring pin; the rejection matrix,
+# extraction guards, resolver payload shape and macOS min_os gating are
+# asserted against the real whisper descriptor in
+# tests/studio/install/test_prebuilt_core.py) ──
+def test_parse_manifest_ok_and_basic_selection():
+ cpu_asset = "whisper-v1.9.1-unsloth.1-linux-x64-cpu.tar.gz"
+ manifest = M.parse_manifest(_manifest([_artifact("linux", "x64", "cpu", cpu_asset, "a" * 64)]))
+ assert manifest["component"] == "whisper.cpp"
+ assert manifest["studio_protocol"] == STUDIO_PROTOCOL
+ host = _host("linux", "x64")
+ # The pinned pre-slim escape hatch: only the fat CPU bundle ever matches.
+ assert M.select_artifact(manifest, host, "cpu")["asset"] == cpu_asset
+ assert M.select_artifact(manifest, host, "metal") is None
+
+
+def test_select_artifact_never_picks_fat_gpu_bundles():
+ # A pinned pre-slim release's fat GPU bundles are dead shapes: a cuda/rocm
+ # backend selects nothing (the core then retries with cpu), never the fat
+ # per-accelerator artifact.
+ manifest = M.parse_manifest(
+ _manifest(
+ [
+ _artifact("linux", "x64", "cpu", "whisper-linux-x64-cpu.tar.gz", "a" * 64),
+ _artifact("linux", "x64", "cuda", "whisper-linux-x64-cuda13.tar.gz", "b" * 64),
+ _artifact("linux", "x64", "rocm", "whisper-linux-x64-rocm.tar.gz", "c" * 64),
+ ]
+ )
+ )
+ cuda_host = _host("linux", "x64", has_usable_nvidia = True)
+ assert M.select_artifact(manifest, cuda_host, "cuda") is None
+ rocm_host = _host("linux", "x64", has_rocm = True, rocm_gfx = "gfx1100")
+ assert M.select_artifact(manifest, rocm_host, "rocm") is None
+ artifact, backend, used_fallback = M.select_artifact_with_fallback(manifest, cuda_host, "cuda")
+ assert artifact["asset"] == "whisper-linux-x64-cpu.tar.gz"
+ assert backend == "cpu" and used_fallback is True
+
+
+# ── Traversal-safe extraction ──
+def _add_file(
+ tar: tarfile.TarFile,
+ name: str,
+ data: bytes,
+ mode: int = 0o644,
+):
+ info = tarfile.TarInfo(name)
+ info.size = len(data)
+ info.mode = mode
+ tar.addfile(info, io.BytesIO(data))
+
+
+# ── Fixture archive + full staging/activate install ──
+def _build_cpu_bundle(tmp_path: Path, host: HostInfo) -> tuple[Path, str, str]:
+ """Build a fake CPU bundle archive with a dummy server + lib; return (path, name, sha256)."""
+ asset = M.whisper_asset_name(RELEASE_TAG, host, "cpu")
+ archive = tmp_path / asset
+ server_name = M.server_binary_name(host)
+ with tarfile.open(archive, "w:gz") as tar:
+ _add_file(tar, server_name, b"#!/bin/sh\necho whisper\n", mode = 0o755)
+ _add_file(tar, "libwhisper.so", b"dummy-libwhisper")
+ _add_file(tar, "libggml-base.so", b"dummy-libggml")
+ return archive, asset, M.sha256_file(archive)
+
+
+def _install_env(
+ monkeypatch,
+ tmp_path,
+ host,
+ *,
+ asset,
+ sha256,
+ backend_in_manifest = "cpu",
+):
+ """Wire monkeypatches so install_prebuilt runs fully offline against a local
+ archive, injecting the release bundle + checksum index (the checksum trust
+ model) via the single fetch_release_for_install seam."""
+ manifest = M.parse_manifest(
+ _manifest(
+ [_artifact(host.whisper_os, host.whisper_arch, backend_in_manifest, asset, sha256)]
+ )
+ )
+ bundle = M.ReleaseBundle(
+ repo = "unslothai/whisper.cpp",
+ release_tag = RELEASE_TAG,
+ manifest = manifest,
+ asset_urls = {asset: f"https://example.invalid/{asset}"},
+ )
+ checksums = {asset: sha256}
+ monkeypatch.setattr(
+ M,
+ "fetch_release_for_install",
+ lambda repo, *, published_release_tag = None: (bundle, checksums),
+ )
+ return bundle
+
+
+def test_install_produces_colocated_layout_and_marker(tmp_path, monkeypatch):
+ host = _host("linux", "x64")
+ archive, asset, sha256 = _build_cpu_bundle(tmp_path, host)
+
+ def fake_download(url, destination):
+ destination.parent.mkdir(parents = True, exist_ok = True)
+ destination.write_bytes(archive.read_bytes())
+
+ monkeypatch.setattr(M, "detect_host", lambda: host)
+ monkeypatch.setattr(M, "download_file", fake_download)
+ _install_env(monkeypatch, tmp_path, host, asset = asset, sha256 = sha256)
+
+ install_dir = tmp_path / "whisper.cpp"
+ rc = M.install_prebuilt(install_dir, backend = "cpu")
+ assert rc == M.EXIT_SUCCESS
+
+ server = install_dir / "build" / "bin" / "whisper-server"
+ assert server.is_file()
+ assert server.stat().st_mode & 0o111 # +x set on unix
+ # every shared lib from the archive is co-located next to the server
+ assert (install_dir / "build" / "bin" / "libwhisper.so").is_file()
+ assert (install_dir / "build" / "bin" / "libggml-base.so").is_file()
+ # marker written at the component root
+ marker = json.loads((install_dir / M.METADATA_FILENAME).read_text())
+ assert marker["component"] == "whisper.cpp"
+ assert marker["release_tag"] == RELEASE_TAG
+ assert marker["backend"] == "cpu"
+ assert marker["studio_protocol"] == STUDIO_PROTOCOL
+ assert marker["install_fingerprint"]
+
+
+def test_install_is_idempotent(tmp_path, monkeypatch):
+ host = _host("linux", "x64")
+ archive, asset, sha256 = _build_cpu_bundle(tmp_path, host)
+
+ calls = {"n": 0}
+
+ def fake_download(url, destination):
+ calls["n"] += 1
+ destination.parent.mkdir(parents = True, exist_ok = True)
+ destination.write_bytes(archive.read_bytes())
+
+ monkeypatch.setattr(M, "detect_host", lambda: host)
+ monkeypatch.setattr(M, "download_file", fake_download)
+ _install_env(monkeypatch, tmp_path, host, asset = asset, sha256 = sha256)
+
+ install_dir = tmp_path / "whisper.cpp"
+ assert M.install_prebuilt(install_dir, backend = "cpu") == M.EXIT_SUCCESS
+ assert calls["n"] == 1
+ # Second run: marker + binary already match -> "already matches", no download.
+ assert M.install_prebuilt(install_dir, backend = "cpu") == M.EXIT_SUCCESS
+ assert calls["n"] == 1
+
+
+def test_install_sha_mismatch_then_retry_fails_closed(tmp_path, monkeypatch):
+ host = _host("linux", "x64")
+ archive, asset, _real_sha = _build_cpu_bundle(tmp_path, host)
+ wrong_sha = "f" * 64 # the checksum index claims a different sha than the archive
+
+ def fake_download(url, destination):
+ destination.parent.mkdir(parents = True, exist_ok = True)
+ destination.write_bytes(archive.read_bytes())
+
+ monkeypatch.setattr(M, "detect_host", lambda: host)
+ monkeypatch.setattr(M, "download_file", fake_download)
+ _install_env(monkeypatch, tmp_path, host, asset = asset, sha256 = wrong_sha)
+
+ install_dir = tmp_path / "whisper.cpp"
+ with pytest.raises(PrebuiltFallback):
+ M.install_prebuilt(install_dir, backend = "cpu")
+ # A failed verify never activates a binary.
+ assert not (install_dir / "build" / "bin" / "whisper-server").exists()
+
+
+# ── Busy lock -> exit 3 ──
+def test_busy_lock_maps_to_exit_busy(tmp_path, monkeypatch):
+ host = _host("linux", "x64")
+ archive, asset, sha256 = _build_cpu_bundle(tmp_path, host)
+ monkeypatch.setattr(M, "detect_host", lambda: host)
+ monkeypatch.setattr(M, "download_file", lambda u, d: None)
+ _install_env(monkeypatch, tmp_path, host, asset = asset, sha256 = sha256)
+
+ from contextlib import contextmanager
+
+ @contextmanager
+ def busy_lock(_path):
+ raise BusyInstallConflict("held by another process")
+ yield # pragma: no cover
+
+ monkeypatch.setattr(M, "install_lock", busy_lock)
+ rc = M.main(["--install-dir", str(tmp_path / "whisper.cpp"), "--backend", "cpu"])
+ assert rc == M.EXIT_BUSY
+
+
+# ── Resolver JSON shape ──
+def test_resolve_mode_keeps_stdout_json_only(tmp_path, monkeypatch, capsys):
+ # Even when the slim pairing emits diagnostics, --resolve-prebuilt must keep
+ # stdout to exactly the JSON line (setup.sh / whisper_cpp_update.py parse
+ # it); the slim_selection log noise belongs on stderr.
+ host = _cuda_host()
+ bin_dir = _fake_llama_bin(tmp_path)
+ monkeypatch.setattr(
+ M, "installed_llama_runtime", lambda: (bin_dir, SLIM_LLAMA_TAG, "cuda13-newer")
+ )
+ manifest = _slim_manifest()
+ bundle = M.ReleaseBundle(
+ repo = "unslothai/whisper.cpp",
+ release_tag = RELEASE_TAG,
+ manifest = manifest,
+ asset_urls = {
+ a["asset"]: f"https://example.invalid/{a['asset']}" for a in manifest["artifacts"]
+ },
+ )
+ monkeypatch.setattr(M, "detect_host", lambda: host)
+ monkeypatch.setattr(
+ M, "fetch_release_for_install", lambda repo, *, published_release_tag = None: (bundle, {})
+ )
+ # A prior install test may have left the module flag True; the resolver must
+ # force it back to stderr regardless.
+ monkeypatch.setattr(M, "_LOG_TO_STDOUT", True, raising = False)
+
+ rc = M.main(["--resolve-prebuilt", "--output-format", "json"])
+ assert rc == M.EXIT_SUCCESS
+ captured = capsys.readouterr()
+ payload = json.loads(captured.out.strip()) # exactly one JSON line, parseable
+ assert payload["asset"] == SLIM_ASSET
+ assert "[whisper-prebuilt]" not in captured.out # no log noise on stdout
+ assert "slim_selection:" in captured.err # diagnostics routed to stderr
+
+
+def test_main_maps_prebuilt_fallback_to_exit_error(tmp_path, monkeypatch):
+ def boom(*a, **kw):
+ raise PrebuiltFallback("no prebuilt")
+
+ monkeypatch.setattr(M, "install_prebuilt", boom)
+ rc = M.main(["--install-dir", str(tmp_path / "whisper.cpp"), "--backend", "cpu"])
+ assert rc == M.EXIT_ERROR
+
+
+def test_main_forwards_requested_whisper_tags(tmp_path, monkeypatch):
+ seen = {}
+
+ def install(*args, **kwargs):
+ seen.update(kwargs)
+ return M.EXIT_SUCCESS
+
+ monkeypatch.setattr(M, "install_prebuilt", install)
+ rc = M.main(["--install-dir", str(tmp_path / "whisper.cpp"), "--whisper-tag", "v1.9.0"])
+ assert rc == M.EXIT_SUCCESS
+ assert seen["whisper_tag"] == "v1.9.0"
+
+ monkeypatch.setattr(M, "detect_host", lambda: _host("linux", "x64"))
+ monkeypatch.setattr(
+ M,
+ "resolve_prebuilt",
+ lambda host, **kwargs: seen.update(kwargs)
+ or {"prebuilt_available": False, "repo": "unslothai/whisper.cpp"},
+ )
+ assert M.main(["--resolve-prebuilt", "v1.8.0", "--output-format", "json"]) == 0
+ assert seen["whisper_tag"] == "v1.8.0"
+
+
+def test_main_reserves_exit_2_for_release_incompatibility(tmp_path, monkeypatch):
+ def boom(*a, **kw):
+ raise ReleaseCompatibilityError("slim bundle requires llama.cpp b2; installed b1")
+
+ monkeypatch.setattr(M, "install_prebuilt", boom)
+ rc = M.main(["--install-dir", str(tmp_path / "whisper.cpp"), "--backend", "cpu"])
+ assert rc == M.EXIT_INCOMPATIBLE
+
+
+def test_main_maps_unexpected_error_to_exit_error(tmp_path, monkeypatch):
+ def boom(*a, **kw):
+ raise RuntimeError("kaboom")
+
+ monkeypatch.setattr(M, "install_prebuilt", boom)
+ rc = M.main(["--install-dir", str(tmp_path / "whisper.cpp"), "--backend", "cpu"])
+ assert rc == M.EXIT_ERROR
+
+
+def test_resolve_mode_unexpected_error_reports_unavailable(monkeypatch, capsys):
+ # An unexpected failure inside the probe maps to prebuilt_available=False, not
+ # a traceback, so the caller falls back cleanly.
+ host = _host("linux", "x64")
+ monkeypatch.setattr(M, "detect_host", lambda: host)
+
+ def boom(repo, *, published_release_tag = None):
+ raise RuntimeError("network down")
+
+ monkeypatch.setattr(M, "fetch_release_for_install", boom)
+ rc = M.main(["--resolve-prebuilt", "--output-format", "json"])
+ assert rc == M.EXIT_SUCCESS
+ payload = json.loads(capsys.readouterr().out.strip())
+ assert payload == {"prebuilt_available": False, "repo": "unslothai/whisper.cpp"}
+
+
+# ── --rocm-gfx / --has-rocm overrides (llama parity) ──
+def test_rocm_gfx_override_implies_has_rocm():
+ # --rocm-gfx alone (no --has-rocm) must enable ROCm and clear NVIDIA, else the
+ # host stays on its CUDA/CPU path and never picks the ROCm bundle.
+ base = _host("linux", "x64", has_usable_nvidia = True)
+ out = M.apply_host_overrides(base, rocm_gfx = "gfx1100")
+ assert out.has_rocm is True
+ assert out.rocm_gfx == "gfx1100"
+ assert out.has_usable_nvidia is False
+ assert M.auto_detect_backend(out) == "rocm"
+
+
+# ── Slim bundles paired with the installed llama.cpp ggml runtime ──
+SLIM_LLAMA_TAG = "b10069-mix-fb3d4ca"
+SLIM_ASSET = "whisper-v1.9.1-unsloth.1-linux-x64-slim.tar.gz"
+CPU_ASSET = "whisper-v1.9.1-unsloth.1-linux-x64-cpu.tar.gz"
+
+
+def _fake_llama_bin(
+ tmp_path: Path,
+ *,
+ backend_module: str | None = "libggml-cuda.so",
+ sonames: tuple[str, ...] = ("libggml.so.0", "libggml-base.so.0"),
+) -> Path:
+ bin_dir = tmp_path / "llama.cpp" / "build" / "bin"
+ bin_dir.mkdir(parents = True, exist_ok = True)
+ for name in sonames:
+ (bin_dir / name).write_bytes(b"ggml-old-" + name.encode())
+ if backend_module:
+ (bin_dir / backend_module).write_bytes(b"ggml-backend-old")
+ (bin_dir / "libggml-cpu-x64.so").write_bytes(b"ggml-cpu-old")
+ (bin_dir / "libllama.so").write_bytes(b"not-ggml") # must never be linked
+ return bin_dir
+
+
+def _slim_artifact(**extra) -> dict:
+ art = {
+ "os": "linux",
+ "arch": "x64",
+ "backend": "slim",
+ "asset": SLIM_ASSET,
+ "sha256": "c" * 64,
+ "install_kind": "slim",
+ "requires_llama_tag": SLIM_LLAMA_TAG,
+ "requires_ggml_version": "0.17.0",
+ "requires_ggml_sonames": ["libggml.so.0", "libggml-base.so.0"],
+ "min_os": None,
+ }
+ art.update(extra)
+ return art
+
+
+def _slim_manifest(slim_extra: dict | None = None) -> dict:
+ """The transition-release shape: a slim bundle beside the published fat CPU
+ bundle (the pinned pre-slim escape hatch)."""
+ artifacts = [
+ _artifact("linux", "x64", "cpu", CPU_ASSET, "a" * 64),
+ _slim_artifact(**(slim_extra or {})),
+ ]
+ return M.parse_manifest(_manifest(artifacts))
+
+
+def _cuda_host() -> HostInfo:
+ return _host("linux", "x64", has_usable_nvidia = True)
+
+
+def test_installed_llama_runtime_reads_marker(tmp_path):
+ root = tmp_path / "llama.cpp"
+ bin_dir = root / "build" / "bin"
+ bin_dir.mkdir(parents = True)
+ (root / "UNSLOTH_PREBUILT_INFO.json").write_text(
+ json.dumps({"release_tag": SLIM_LLAMA_TAG, "bundle_profile": "cuda13-newer"})
+ )
+ assert M.llama.installed_llama_runtime(root) == (bin_dir, SLIM_LLAMA_TAG, "cuda13-newer")
+
+
+ "prepare",
+ [
+ lambda root: None, # no marker at all
+ lambda root: (root / "UNSLOTH_PREBUILT_INFO.json").write_text("{}"), # no release_tag
+ lambda root: (root / "UNSLOTH_PREBUILT_INFO.json").write_text("not json"),
+ ],
+)
+def test_installed_llama_runtime_rejects_incomplete_installs(tmp_path, prepare):
+ root = tmp_path / "llama.cpp"
+ (root / "build" / "bin").mkdir(parents = True)
+ prepare(root)
+ assert M.llama.installed_llama_runtime(root) is None
+
+
+def test_installed_llama_runtime_requires_bin_dir(tmp_path):
+ root = tmp_path / "llama.cpp"
+ root.mkdir()
+ (root / "UNSLOTH_PREBUILT_INFO.json").write_text(json.dumps({"release_tag": SLIM_LLAMA_TAG}))
+ assert M.llama.installed_llama_runtime(root) is None # marker but no build/bin
+
+
+def test_slim_selected_when_all_pairing_checks_pass(tmp_path, monkeypatch):
+ bin_dir = _fake_llama_bin(tmp_path)
+ monkeypatch.setattr(
+ M, "installed_llama_runtime", lambda: (bin_dir, SLIM_LLAMA_TAG, "cuda13-newer")
+ )
+ artifact, backend, used_fallback = M.select_artifact_with_fallback(
+ _slim_manifest(), _cuda_host(), "cuda"
+ )
+ assert artifact["asset"] == SLIM_ASSET
+ assert backend == "cuda" and used_fallback is False
+
+
+ "runtime,slim_extra",
+ [
+ # No llama install at all.
+ (lambda bin_dir: None, None),
+ # Installed llama tag does not match requires_llama_tag.
+ (lambda bin_dir: (bin_dir, "b99999-mix-0000000", "cuda13-newer"), None),
+ # A required soname is missing from the llama bin dir.
+ (
+ lambda bin_dir: (bin_dir, SLIM_LLAMA_TAG, "cuda13-newer"),
+ {"requires_ggml_sonames": ["libggml.so.0", "libggml-base.so.0", "libggml-extra.so.9"]},
+ ),
+ # Manifest omits the soname contract entirely.
+ (lambda bin_dir: (bin_dir, SLIM_LLAMA_TAG, "cuda13-newer"), {"requires_ggml_sonames": []}),
+ ],
+)
+def test_slim_pairing_failure_falls_back_to_pinned_cpu(tmp_path, monkeypatch, runtime, slim_extra):
+ # With the fat per-accelerator chain gone, a failed pairing degrades to the
+ # one legacy shape: the release's published fat CPU bundle.
+ bin_dir = _fake_llama_bin(tmp_path)
+ monkeypatch.setattr(M, "installed_llama_runtime", lambda: runtime(bin_dir))
+ artifact, backend, used_fallback = M.select_artifact_with_fallback(
+ _slim_manifest(slim_extra), _cuda_host(), "cuda"
+ )
+ assert artifact["asset"] == CPU_ASSET
+ assert backend == "cpu" and used_fallback is True
+
+
+def test_slim_missing_accel_module_rides_the_cpu_module(tmp_path, monkeypatch):
+ # Sonames present but no libggml-cuda.so in the llama bin dir: the cuda
+ # pairing fails, and the cpu retry still serves the same slim bundle via
+ # the llama cpu modules.
+ bin_dir = _fake_llama_bin(tmp_path, backend_module = None)
+ monkeypatch.setattr(
+ M, "installed_llama_runtime", lambda: (bin_dir, SLIM_LLAMA_TAG, "cuda13-newer")
+ )
+ artifact, backend, used_fallback = M.select_artifact_with_fallback(
+ _slim_manifest(), _cuda_host(), "cuda"
+ )
+ assert artifact["asset"] == SLIM_ASSET
+ assert backend == "cpu" and used_fallback is True
+
+
+def test_slim_selected_for_cpu_backend_on_linux(tmp_path, monkeypatch):
+ # Slim-only releases must serve cpu too: with the llama cpu modules present
+ # the cpu backend rides the same slim bundle as the GPUs.
+ bin_dir = _fake_llama_bin(tmp_path)
+ monkeypatch.setattr(
+ M, "installed_llama_runtime", lambda: (bin_dir, SLIM_LLAMA_TAG, "cuda13-newer")
+ )
+ artifact, backend, _fb = M.select_artifact_with_fallback(
+ _slim_manifest(), _host("linux", "x64"), "cpu"
+ )
+ assert artifact["asset"] == SLIM_ASSET and backend == "cpu"
+
+
+def test_slim_cpu_requires_a_cpu_module(tmp_path, monkeypatch):
+ # Sonames present but no libggml-cpu* variant in the llama bin dir -> fat cpu.
+ bin_dir = tmp_path / "llama.cpp" / "build" / "bin"
+ bin_dir.mkdir(parents = True)
+ for name in ("libggml.so.0", "libggml-base.so.0"):
+ (bin_dir / name).write_bytes(b"ggml")
+ monkeypatch.setattr(
+ M, "installed_llama_runtime", lambda: (bin_dir, SLIM_LLAMA_TAG, "linux-cpu")
+ )
+ artifact, backend, _fb = M.select_artifact_with_fallback(
+ _slim_manifest(), _host("linux", "x64"), "cpu"
+ )
+ assert artifact["asset"] == CPU_ASSET and backend == "cpu"
+
+
+WIN_SLIM_ASSET = "whisper-v1.9.1-unsloth.1-windows-x64-slim.zip"
+
+
+def test_slim_selected_for_cpu_backend_on_windows(tmp_path, monkeypatch):
+ bin_dir = tmp_path / "llama.cpp" / "build" / "bin" / "Release"
+ bin_dir.mkdir(parents = True)
+ for name in ("ggml.dll", "ggml-base.dll", "ggml-cpu-haswell.dll"):
+ (bin_dir / name).write_bytes(b"ggml")
+ monkeypatch.setattr(
+ M, "installed_llama_runtime", lambda: (bin_dir, SLIM_LLAMA_TAG, "windows-cpu")
+ )
+ manifest = M.parse_manifest(
+ _manifest(
+ [
+ _slim_artifact(
+ os = "windows",
+ arch = "x64",
+ asset = WIN_SLIM_ASSET,
+ requires_ggml_sonames = ["ggml.dll", "ggml-base.dll"],
+ )
+ ]
+ )
+ )
+ artifact, backend, _fb = M.select_artifact_with_fallback(
+ manifest, _host("windows", "x64"), "cpu"
+ )
+ assert artifact["asset"] == WIN_SLIM_ASSET and backend == "cpu"
+
+
+MAC_SLIM_ASSET = "whisper-v1.9.1-unsloth.1-macos-arm64-slim.tar.gz"
+
+
+def _fake_llama_bin_macos(tmp_path: Path) -> Path:
+ """The dylib names the live llama macos bundle ships (core + cpu + metal)."""
+ bin_dir = tmp_path / "llama.cpp" / "build" / "bin"
+ bin_dir.mkdir(parents = True, exist_ok = True)
+ for name in (
+ "libggml.dylib",
+ "libggml-base.dylib",
+ "libggml-cpu.dylib",
+ "libggml-metal.dylib",
+ "libggml-blas.dylib",
+ ):
+ (bin_dir / name).write_bytes(b"ggml-" + name.encode())
+ (bin_dir / "libllama.dylib").write_bytes(b"not-ggml")
+ return bin_dir
+
+
+def _macos_slim_manifest(arch: str = "arm64") -> dict:
+ return M.parse_manifest(
+ _manifest(
+ [
+ _slim_artifact(
+ os = "macos",
+ arch = arch,
+ asset = MAC_SLIM_ASSET,
+ requires_ggml_sonames = ["libggml.dylib", "libggml-base.dylib"],
+ )
+ ]
+ )
+ )
+
+
[email protected]("backend", ["metal", "cpu"])
+def test_slim_selected_for_metal_and_cpu_on_macos(tmp_path, monkeypatch, backend):
+ bin_dir = _fake_llama_bin_macos(tmp_path)
+ monkeypatch.setattr(
+ M, "installed_llama_runtime", lambda: (bin_dir, SLIM_LLAMA_TAG, "macos-metal-arm64")
+ )
+ host = _host("macos", "arm64", macos_version = (14, 0))
+ artifact, effective, _fb = M.select_artifact_with_fallback(
+ _macos_slim_manifest(), host, backend
+ )
+ assert artifact["asset"] == MAC_SLIM_ASSET
+ assert effective == backend # the accel identity, never "slim"
+
+
+def test_macos_auto_backends_route_to_slim(tmp_path, monkeypatch):
+ # auto -> metal on Apple Silicon, cpu on Intel macs; both must pick slim.
+ bin_dir = _fake_llama_bin_macos(tmp_path)
+ monkeypatch.setattr(
+ M, "installed_llama_runtime", lambda: (bin_dir, SLIM_LLAMA_TAG, "macos-metal-arm64")
+ )
+ silicon = _host("macos", "arm64", macos_version = (14, 0))
+ assert M.resolve_backend(silicon, "auto", cpu_fallback = False) == "metal"
+ artifact, backend, _fb = M.select_artifact_with_fallback(
+ _macos_slim_manifest(), silicon, "metal"
+ )
+ assert artifact["asset"] == MAC_SLIM_ASSET and backend == "metal"
+
+ intel = _host("macos", "x64", macos_version = (14, 0))
+ assert M.resolve_backend(intel, "auto", cpu_fallback = False) == "cpu"
+ artifact, backend, _fb = M.select_artifact_with_fallback(
+ _macos_slim_manifest(arch = "x64"), intel, "cpu"
+ )
+ assert artifact["asset"] == MAC_SLIM_ASSET and backend == "cpu"
+
+
+def test_slim_metal_requires_the_metal_module(tmp_path, monkeypatch):
+ # A macos llama runtime without libggml-metal*.dylib cannot back metal; the
+ # cpu fallback still rides the same slim bundle via the cpu module.
+ bin_dir = tmp_path / "llama.cpp" / "build" / "bin"
+ bin_dir.mkdir(parents = True)
+ for name in ("libggml.dylib", "libggml-base.dylib", "libggml-cpu.dylib"):
+ (bin_dir / name).write_bytes(b"ggml")
+ monkeypatch.setattr(
+ M, "installed_llama_runtime", lambda: (bin_dir, SLIM_LLAMA_TAG, "macos-cpu-x64")
+ )
+ host = _host("macos", "arm64", macos_version = (14, 0))
+ artifact, backend, used_fallback = M.select_artifact_with_fallback(
+ _macos_slim_manifest(), host, "metal"
+ )
+ assert artifact["asset"] == MAC_SLIM_ASSET
+ assert backend == "cpu" and used_fallback is True
+
+
+def test_slim_only_release_pairing_failure_is_actionable(tmp_path, monkeypatch):
+ # A slim-only release with no llama install is an operational failure, not
+ # the narrowly handled installed-version skew.
+ lines: list[str] = []
+ monkeypatch.setattr(M, "log", lines.append)
+ monkeypatch.setattr(M, "installed_llama_runtime", lambda: None)
+ manifest = M.parse_manifest(_manifest([_slim_artifact()]))
+ with pytest.raises(PrebuiltFallback):
+ M.select_artifact_with_fallback(manifest, _cuda_host(), "cuda")
+ assert any(
+ f"slim bundle requires llama.cpp {SLIM_LLAMA_TAG}; "
+ "install or update llama.cpp first" in line
+ for line in lines
+ )
+
+
+def test_slim_release_tag_skew_has_distinct_compatibility_error(tmp_path, monkeypatch):
+ bin_dir = _fake_llama_bin(tmp_path)
+ monkeypatch.setattr(
+ M,
+ "installed_llama_runtime",
+ lambda: (bin_dir, "b10068-mix-old", "cuda13-newer"),
+ )
+ manifest = M.parse_manifest(_manifest([_slim_artifact()]))
+ with pytest.raises(ReleaseCompatibilityError, match = SLIM_LLAMA_TAG):
+ M.select_artifact_with_fallback(manifest, _cuda_host(), "cuda")
+
+
+def test_link_ggml_runtime_hardlinks_every_ggml_library(tmp_path):
+ bin_dir = _fake_llama_bin(tmp_path)
+ whisper_bin = tmp_path / "whisper.cpp" / "build" / "bin"
+ linked = M.link_ggml_runtime(bin_dir, whisper_bin)
+ assert linked == [
+ "libggml-base.so.0",
+ "libggml-cpu-x64.so",
+ "libggml-cuda.so",
+ "libggml.so.0",
+ ]
+ for name in ("libggml.so.0", "libggml-base.so.0", "libggml-cuda.so", "libggml-cpu-x64.so"):
+ source, dest = bin_dir / name, whisper_bin / name
+ assert dest.is_file() and not dest.is_symlink()
+ assert dest.stat().st_ino == source.stat().st_ino # a true hardlink
+ assert not (whisper_bin / "libllama.so").exists() # only ggml libraries wire over
+
+
+def test_link_ggml_runtime_copy_fallback(tmp_path, monkeypatch):
+ def no_link(src, dst, **kwargs):
+ raise OSError("cross-device link")
+
+ monkeypatch.setattr(M.os, "link", no_link)
+ bin_dir = _fake_llama_bin(tmp_path)
+ whisper_bin = tmp_path / "whisper.cpp" / "build" / "bin"
+ assert len(M.link_ggml_runtime(bin_dir, whisper_bin)) == 4
+ dest = whisper_bin / "libggml.so.0"
+ assert dest.read_bytes() == (bin_dir / "libggml.so.0").read_bytes()
+ assert dest.stat().st_nlink == 1 # a copy, not a link
+
+
+def test_link_ggml_runtime_hardlinks_dylibs(tmp_path):
+ # macOS wiring: the libggml* glob must take the .dylib names too.
+ bin_dir = _fake_llama_bin_macos(tmp_path)
+ whisper_bin = tmp_path / "whisper.cpp" / "build" / "bin"
+ linked = M.link_ggml_runtime(bin_dir, whisper_bin)
+ assert linked == [
+ "libggml-base.dylib",
+ "libggml-blas.dylib",
+ "libggml-cpu.dylib",
+ "libggml-metal.dylib",
+ "libggml.dylib",
+ ]
+ for name in linked:
+ source, dest = bin_dir / name, whisper_bin / name
+ assert dest.is_file() and not dest.is_symlink()
+ assert dest.stat().st_ino == source.stat().st_ino # a true hardlink
+ assert not (whisper_bin / "libllama.dylib").exists()
+
+
+def test_link_ggml_runtime_fails_closed_on_empty_runtime(tmp_path):
+ empty = tmp_path / "empty"
+ empty.mkdir()
+ with pytest.raises(PrebuiltFallback):
+ M.link_ggml_runtime(empty, tmp_path / "whisper_bin")
+
+
+def test_link_ggml_runtime_wires_windows_libomp(tmp_path):
+ # llama's clang-built windows-arm64 ggml-base.dll imports
+ # libomp140.aarch64.dll (bundled, not a system DLL): the wiring must place
+ # it next to whisper-server.exe or the loader dies with DLL_NOT_FOUND.
+ bin_dir = tmp_path / "llama_bin"
+ bin_dir.mkdir()
+ for name in ("ggml.dll", "ggml-base.dll", "ggml-cpu.dll", "libomp140.aarch64.dll"):
+ (bin_dir / name).write_bytes(b"x")
+ (bin_dir / "llama.dll").write_bytes(b"x") # never wired
+ whisper_bin = tmp_path / "whisper_bin"
+ linked = M.link_ggml_runtime(bin_dir, whisper_bin)
+ assert linked == ["ggml-base.dll", "ggml-cpu.dll", "ggml.dll", "libomp140.aarch64.dll"]
+ assert not (whisper_bin / "llama.dll").exists()
+
+
+def test_rocm_runtime_wires_complete_windows_dll_overlay(tmp_path):
+ bin_dir = tmp_path / "llama_bin"
+ bin_dir.mkdir()
+ dlls = {
+ "ggml.dll",
+ "ggml-base.dll",
+ "ggml-hip.dll",
+ "amdhip64.dll",
+ "rocblas.dll",
+ "hipblaslt.dll",
+ "hsa-runtime64.dll",
+ # The llama Windows ROCm archive can carry transitive DLLs whose names
+ # do not contain hip/roc/amd. Its installer overlays every DLL.
+ "runtime-support.dll",
+ }
+ for name in dlls:
+ (bin_dir / name).write_bytes(name.encode())
+ (bin_dir / "not-a-runtime.txt").write_text("ignored")
+
+ whisper_bin = tmp_path / "whisper_bin"
+ linked = M.link_ggml_runtime(bin_dir, whisper_bin, backend = "rocm")
+ linked_dirs = M.link_runtime_directories(
+ bin_dir,
+ whisper_bin,
+ backend = "rocm",
+ host = _host("windows", "x64"),
+ )
+
+ assert set(linked) == dlls
+ assert linked_dirs == []
+ assert all((whisper_bin / name).is_file() for name in dlls)
+ assert not (whisper_bin / "not-a-runtime.txt").exists()
+
+
+def test_assemble_does_not_copy_packaging_marker_beside_server(tmp_path):
+ host = _host("linux", "x64")
+ bundle = tmp_path / "bundle"
+ bundle.mkdir()
+ (bundle / "whisper-server").write_text("server")
+ (bundle / M.METADATA_FILENAME).write_text('{"backend":"slim"}')
+ staged = tmp_path / "staged"
+ M.assemble_install_tree(bundle, staged, host)
+ assert not (staged / "build" / "bin" / M.METADATA_FILENAME).exists()
+
+
+def test_rocm_runtime_wires_packaged_dependency_closure_and_catalogs(tmp_path, monkeypatch):
+ llama_bin = _fake_llama_bin(tmp_path, backend_module = "libggml-hip.so")
+ for name in ("libamdhip64.so.6", "libhipblas.so.2", "libcustomrocm.so.1"):
+ (llama_bin / name).write_bytes(name.encode())
+ for directory in M.SLIM_ROCM_RUNTIME_DIRS:
+ catalog = llama_bin / directory / "library" / "gfx1100"
+ catalog.mkdir(parents = True)
+ (catalog / "kernel.dat").write_bytes(directory.encode())
+
+ dependencies = {
+ "libggml-hip.so": {"libamdhip64.so.6", "libcustomrocm.so.1"},
+ "libamdhip64.so.6": {"libhipblas.so.2"},
+ }
+ monkeypatch.setattr(M, "_elf_needed", lambda path: dependencies.get(path.name, set()))
+ whisper_bin = tmp_path / "whisper-bin"
+ linked = M.link_ggml_runtime(llama_bin, whisper_bin, backend = "rocm")
+ linked_dirs = M.link_runtime_directories(
+ llama_bin,
+ whisper_bin,
+ backend = "rocm",
+ host = _host("linux", "x64"),
+ )
+
+ assert "libcustomrocm.so.1" in linked
+ assert "libhipblas.so.2" in linked
+ assert linked_dirs == ["hipblaslt", "rocblas"]
+ for directory in linked_dirs:
+ linked_catalog = whisper_bin / directory / "library" / "gfx1100" / "kernel.dat"
+ source_catalog = llama_bin / directory / "library" / "gfx1100" / "kernel.dat"
+ assert linked_catalog.stat().st_ino == source_catalog.stat().st_ino
+
+
+def test_rocm_runtime_requires_both_kernel_catalogs(tmp_path):
+ llama_bin = _fake_llama_bin(tmp_path, backend_module = "libggml-hip.so")
+ (llama_bin / "hipblaslt").mkdir()
+ (llama_bin / "hipblaslt" / "kernel.dat").write_bytes(b"kernel")
+ with pytest.raises(PrebuiltFallback, match = "rocblas"):
+ M.link_runtime_directories(
+ llama_bin,
+ tmp_path / "whisper-bin",
+ backend = "rocm",
+ host = _host("linux", "x64"),
+ )
+
+
+def test_rocm_runtime_catalog_copy_fallback(tmp_path, monkeypatch):
+ llama_bin = _fake_llama_bin(tmp_path, backend_module = "libggml-hip.so")
+ for directory in M.SLIM_ROCM_RUNTIME_DIRS:
+ catalog = llama_bin / directory
+ catalog.mkdir()
+ (catalog / "kernel.dat").write_bytes(directory.encode())
+ monkeypatch.setattr(M.os, "link", lambda *args: (_ for _ in ()).throw(OSError("xdev")))
+ whisper_bin = tmp_path / "whisper-bin"
+ M.link_runtime_directories(
+ llama_bin,
+ whisper_bin,
+ backend = "rocm",
+ host = _host("linux", "x64"),
+ )
+ for directory in M.SLIM_ROCM_RUNTIME_DIRS:
+ assert (whisper_bin / directory / "kernel.dat").read_bytes() == directory.encode()
+
+
+def test_existing_install_requires_executable_server(tmp_path, monkeypatch):
+ # A marker-matching install with a non-executable server must reinstall:
+ # the sidecar refuses it via os.access(X_OK), so "already matches" would
+ # otherwise leave dictation permanently broken.
+ host = _host("linux", "x64")
+ selection = object()
+ monkeypatch.setattr(M.core, "existing_install_matches", lambda *a: True)
+ server = tmp_path / "build" / "bin" / "whisper-server"
+ server.parent.mkdir(parents = True)
+ server.write_text("bin")
+ monkeypatch.setattr(M, "installed_server_path", lambda d, h: server)
+ monkeypatch.setattr(M, "load_prebuilt_metadata", lambda d: {})
+ server.chmod(0o644)
+ assert M.existing_install_matches(tmp_path, host, selection) is False
+ server.chmod(0o755)
+ assert M.existing_install_matches(tmp_path, host, selection) is True
+
+
+def test_existing_slim_install_requires_wired_libraries(tmp_path, monkeypatch):
+ # A slim install whose hardlinked ggml files vanished (llama dir deleted)
+ # must reinstall so update re-wires instead of reporting up to date.
+ host = _host("linux", "x64")
+ monkeypatch.setattr(M.core, "existing_install_matches", lambda *a: True)
+ server = tmp_path / "build" / "bin" / "whisper-server"
+ server.parent.mkdir(parents = True)
+ server.write_text("bin")
+ server.chmod(0o755)
+ monkeypatch.setattr(M, "installed_server_path", lambda d, h: server)
+ marker = {
+ "install_kind": "slim",
+ "runtime_wiring_version": M.SLIM_RUNTIME_WIRING_VERSION,
+ "linked_libraries": ["libggml.so.0"],
+ }
+ monkeypatch.setattr(M, "load_prebuilt_metadata", lambda d: marker)
+ marker.pop("runtime_wiring_version")
+ assert M.existing_install_matches(tmp_path, host, object()) is False
+ marker["runtime_wiring_version"] = M.SLIM_RUNTIME_WIRING_VERSION
+ assert M.existing_install_matches(tmp_path, host, object()) is False
+ (server.parent / "libggml.so.0").write_text("lib")
+ assert M.existing_install_matches(tmp_path, host, object()) is True
+ marker.update(backend = "rocm", linked_runtime_directories = [])
+ assert M.existing_install_matches(tmp_path, _host("windows", "x64"), object()) is True
+
+
+def test_link_ggml_runtime_libomp_alone_is_not_a_pairing(tmp_path):
+ # A libomp without any ggml library is not a usable llama runtime.
+ bin_dir = tmp_path / "llama_bin"
+ bin_dir.mkdir()
+ (bin_dir / "libomp140.aarch64.dll").write_bytes(b"x")
+ with pytest.raises(PrebuiltFallback):
+ M.link_ggml_runtime(bin_dir, tmp_path / "whisper_bin")
+
+
+def _build_slim_bundle(tmp_path: Path, host: HostInfo) -> tuple[Path, str]:
+ """Slim archive per the CI contract: whisper-server + libwhisper only."""
+ archive = tmp_path / SLIM_ASSET
+ with tarfile.open(archive, "w:gz") as tar:
+ _add_file(tar, M.server_binary_name(host), b"#!/bin/sh\necho whisper\n", mode = 0o755)
+ _add_file(tar, "libwhisper.so.1", b"dummy-libwhisper")
+ return archive, M.sha256_file(archive)
+
+
+def _slim_install_env(monkeypatch, tmp_path, host, *, sha256: str) -> Path:
+ llama_bin = _fake_llama_bin(tmp_path)
+ monkeypatch.setattr(
+ M,
+ "installed_llama_runtime",
+ lambda install_dir = None: (llama_bin, SLIM_LLAMA_TAG, "cuda13-newer"),
+ )
+ manifest = M.parse_manifest(
+ _manifest(
+ [
+ _artifact("linux", "x64", "cpu", CPU_ASSET, "a" * 64),
+ _slim_artifact(sha256 = sha256),
+ ]
+ )
+ )
+ bundle = M.ReleaseBundle(
+ repo = "unslothai/whisper.cpp",
+ release_tag = RELEASE_TAG,
+ manifest = manifest,
+ asset_urls = {SLIM_ASSET: f"https://example.invalid/{SLIM_ASSET}"},
+ )
+ checksums = {SLIM_ASSET: sha256, CPU_ASSET: "a" * 64}
+ monkeypatch.setattr(
+ M,
+ "fetch_release_for_install",
+ lambda repo, *, published_release_tag = None: (bundle, checksums),
+ )
+ return llama_bin
+
+
+def test_slim_install_wires_links_and_marker(tmp_path, monkeypatch):
+ host = _cuda_host()
+ archive, sha256 = _build_slim_bundle(tmp_path, host)
+
+ def fake_download(url, destination):
+ destination.parent.mkdir(parents = True, exist_ok = True)
+ destination.write_bytes(archive.read_bytes())
+
+ monkeypatch.setattr(M, "detect_host", lambda: host)
+ monkeypatch.setattr(M, "download_file", fake_download)
+ llama_bin = _slim_install_env(monkeypatch, tmp_path, host, sha256 = sha256)
+
+ install_dir = tmp_path / "whisper.cpp"
+ assert M.install_prebuilt(install_dir, backend = "cuda") == M.EXIT_SUCCESS
+
+ whisper_bin = install_dir / "build" / "bin"
+ assert (whisper_bin / "whisper-server").is_file()
+ assert (whisper_bin / "libwhisper.so.1").is_file()
+ for name in ("libggml.so.0", "libggml-base.so.0", "libggml-cuda.so", "libggml-cpu-x64.so"):
+ dest = whisper_bin / name
+ assert dest.is_file() and not dest.is_symlink()
+ assert dest.stat().st_ino == (llama_bin / name).stat().st_ino
+
+ marker = json.loads((install_dir / M.METADATA_FILENAME).read_text())
+ assert marker["backend"] == "cuda" # the accel identity, not "slim"
+ assert marker["asset"] == SLIM_ASSET
+ assert marker["install_kind"] == "slim"
+ assert marker["paired_llama_tag"] == SLIM_LLAMA_TAG
+ assert marker["linked_from"] == str(llama_bin)
+ # The wired filenames land in the marker; the sidecar launch guard
+ # verifies exactly these names instead of hardcoded per-OS globs.
+ assert marker["linked_libraries"] == [
+ "libggml-base.so.0",
+ "libggml-cpu-x64.so",
+ "libggml-cuda.so",
+ "libggml.so.0",
+ ]
+ assert marker["runtime_wiring_version"] == M.SLIM_RUNTIME_WIRING_VERSION
+ assert marker["linked_runtime_directories"] == []
+
+
+def test_slim_links_survive_a_llama_dir_swap(tmp_path, monkeypatch):
+ # The whole point of hardlinks: replace the llama dir contents after wiring
+ # and whisper's links must still hold the OLD inodes/content.
+ host = _cuda_host()
+ archive, sha256 = _build_slim_bundle(tmp_path, host)
+
+ def fake_download(url, destination):
+ destination.parent.mkdir(parents = True, exist_ok = True)
+ destination.write_bytes(archive.read_bytes())
+
+ monkeypatch.setattr(M, "detect_host", lambda: host)
+ monkeypatch.setattr(M, "download_file", fake_download)
+ llama_bin = _slim_install_env(monkeypatch, tmp_path, host, sha256 = sha256)
+
+ install_dir = tmp_path / "whisper.cpp"
+ assert M.install_prebuilt(install_dir, backend = "cuda") == M.EXIT_SUCCESS
+ whisper_lib = install_dir / "build" / "bin" / "libggml.so.0"
+ old_inode = whisper_lib.stat().st_ino
+ old_content = whisper_lib.read_bytes()
+
+ # Simulate the llama updater swapping in a new release's libraries.
+ for path in llama_bin.iterdir():
+ path.unlink()
+ (llama_bin / "libggml.so.0").write_bytes(b"ggml-NEW")
+
+ assert whisper_lib.stat().st_ino == old_inode # old inode survives the swap
+ assert whisper_lib.read_bytes() == old_content
+ assert whisper_lib.stat().st_nlink == 1 # the llama side is gone; ours remains
+
+
+# The exact resolver key set shipped before slim existed; install_kind is the
+# one additive field and must stay the only difference.
+_LEGACY_RESOLVER_KEYS = {
+ "prebuilt_available",
+ "repo",
+ "release_tag",
+ "upstream_tag",
+ "backend",
+ "requested_backend",
+ "cpu_fallback",
+ "asset",
+ "os",
+ "arch",
+ "runtime_line",
+}
+
+
+def _resolver_payload(monkeypatch, capsys, manifest, host) -> dict:
+ bundle = M.ReleaseBundle(
+ repo = "unslothai/whisper.cpp",
+ release_tag = RELEASE_TAG,
+ manifest = manifest,
+ asset_urls = {},
+ )
+ monkeypatch.setattr(M, "detect_host", lambda: host)
+ monkeypatch.setattr(
+ M, "fetch_release_for_install", lambda repo, *, published_release_tag = None: (bundle, {})
+ )
+ assert M.main(["--resolve-prebuilt", "--output-format", "json"]) == M.EXIT_SUCCESS
+ return json.loads(capsys.readouterr().out.strip())
+
+
+def test_resolver_reports_install_kind_fat_additively(monkeypatch, capsys):
+ # The pinned pre-slim escape hatch resolves the published fat CPU bundle.
+ manifest = M.parse_manifest(_manifest([_artifact("linux", "x64", "cpu", CPU_ASSET, "a" * 64)]))
+ payload = _resolver_payload(monkeypatch, capsys, manifest, _host("linux", "x64"))
+ assert set(payload) == _LEGACY_RESOLVER_KEYS | {"install_kind"}
+ assert payload["install_kind"] == "fat"
+ assert payload["asset"] == CPU_ASSET
+
+
+def _release_for_selection(release_tag: str, upstream_tag: str, artifact: dict) -> M.ReleaseBundle:
+ payload = _manifest([artifact])
+ payload["upstream_tag"] = upstream_tag
+ return M.ReleaseBundle(
+ repo = "unslothai/whisper.cpp",
+ release_tag = release_tag,
+ manifest = M.parse_manifest(payload),
+ asset_urls = {},
+ )
+
+
+def test_whisper_tag_selects_matching_published_upstream(monkeypatch):
+ latest_asset = "latest-linux-x64-cpu.tar.gz"
+ pinned_asset = "pinned-linux-x64-cpu.tar.gz"
+ latest = _release_for_selection(
+ "v1.9.2-unsloth.1",
+ "v1.9.2",
+ _artifact("linux", "x64", "cpu", latest_asset, "a" * 64),
+ )
+ pinned = _release_for_selection(
+ "v1.9.0-unsloth.3",
+ "v1.9.0",
+ _artifact("linux", "x64", "cpu", pinned_asset, "b" * 64),
+ )
+ monkeypatch.setattr(
+ M,
+ "fetch_release_for_install",
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ AssertionError("an upstream pin consulted the unrelated newest release")
+ ),
+ )
+ monkeypatch.setattr(
+ M,
+ "_published_release_tags",
+ lambda repo: [latest.release_tag, pinned.release_tag],
+ )
+ monkeypatch.setattr(
+ M,
+ "_fetch_release_candidate",
+ lambda repo, tag: latest if tag == latest.release_tag else pinned,
+ )
+ monkeypatch.setattr(M, "fetch_release_checksums", lambda bundle: {pinned_asset: "b" * 64})
+
+ payload = M.resolve_prebuilt(
+ _host("linux", "x64"),
+ published_repo = "unslothai/whisper.cpp",
+ published_release_tag = None,
+ whisper_tag = "v1.9.0",
+ backend = "cpu",
+ cpu_fallback = False,
+ )
+ assert payload["prebuilt_available"] is True
+ assert payload["release_tag"] == pinned.release_tag
+ assert payload["upstream_tag"] == "v1.9.0"
+
+
+def test_macos_walks_back_to_newest_compatible_release(monkeypatch):
+ latest_asset = "latest-macos-arm64-cpu.tar.gz"
+ compatible_asset = "compatible-macos-arm64-cpu.tar.gz"
+ latest = _release_for_selection(
+ "v1.9.2-unsloth.1",
+ "v1.9.2",
+ _artifact(
+ "macos",
+ "arm64",
+ "cpu",
+ latest_asset,
+ "a" * 64,
+ min_os = "macos-15.0",
+ ),
+ )
+ compatible = _release_for_selection(
+ "v1.9.1-unsloth.1",
+ "v1.9.1",
+ _artifact(
+ "macos",
+ "arm64",
+ "cpu",
+ compatible_asset,
+ "b" * 64,
+ min_os = "macos-13.0",
+ ),
+ )
+ monkeypatch.setattr(
+ M,
+ "fetch_release_for_install",
+ lambda repo, *, published_release_tag = None: (latest, {latest_asset: "a" * 64}),
+ )
+ monkeypatch.setattr(
+ M,
+ "_published_release_tags",
+ lambda repo: [latest.release_tag, compatible.release_tag],
+ )
+ monkeypatch.setattr(M, "_fetch_release_candidate", lambda repo, tag: compatible)
+ monkeypatch.setattr(
+ M,
+ "fetch_release_checksums",
+ lambda bundle: {compatible_asset: "b" * 64},
+ )
+
+ payload = M.resolve_prebuilt(
+ _host("macos", "arm64", macos_version = (14, 7)),
+ published_repo = "unslothai/whisper.cpp",
+ published_release_tag = None,
+ backend = "cpu",
+ cpu_fallback = False,
+ )
+ assert payload["prebuilt_available"] is True
+ assert payload["release_tag"] == compatible.release_tag
+
+
+def test_macos_walkback_never_masks_checksum_failure(monkeypatch):
+ asset = "latest-macos-arm64-cpu.tar.gz"
+ latest = _release_for_selection(
+ "v1.9.2-unsloth.1",
+ "v1.9.2",
+ _artifact("macos", "arm64", "cpu", asset, "a" * 64, min_os = "macos-13.0"),
+ )
+ monkeypatch.setattr(
+ M,
+ "fetch_release_for_install",
+ lambda repo, *, published_release_tag = None: (latest, {asset: "b" * 64}),
+ )
+ monkeypatch.setattr(
+ M,
+ "_published_release_tags",
+ lambda repo: (_ for _ in ()).throw(AssertionError("integrity failure walked back")),
+ )
+
+ with pytest.raises(PrebuiltFallback, match = "disagrees"):
+ M._release_plan_for_host(
+ _host("macos", "arm64", macos_version = (14, 7)),
+ published_repo = "unslothai/whisper.cpp",
+ published_release_tag = None,
+ whisper_tag = "latest",
+ requested_backend = "cpu",
+ )
+
+
+def test_resolver_reports_install_kind_slim_when_paired(tmp_path, monkeypatch, capsys):
+ bin_dir = _fake_llama_bin(tmp_path)
+ monkeypatch.setattr(
+ M, "installed_llama_runtime", lambda: (bin_dir, SLIM_LLAMA_TAG, "cuda13-newer")
+ )
+ payload = _resolver_payload(monkeypatch, capsys, _slim_manifest(), _cuda_host())
+ assert set(payload) == _LEGACY_RESOLVER_KEYS | {"install_kind"}
+ assert payload["install_kind"] == "slim"
+ assert payload["asset"] == SLIM_ASSET
+ assert payload["backend"] == "cuda"
+
+
+def test_resolver_reports_metal_slim_on_macos(tmp_path, monkeypatch, capsys):
+ # Same contract shape on macs: backend stays the accel (metal), the one
+ # additive field says the asset installs slim.
+ bin_dir = _fake_llama_bin_macos(tmp_path)
+ monkeypatch.setattr(
+ M, "installed_llama_runtime", lambda: (bin_dir, SLIM_LLAMA_TAG, "macos-metal-arm64")
+ )
+ host = _host("macos", "arm64", macos_version = (14, 0))
+ payload = _resolver_payload(monkeypatch, capsys, _macos_slim_manifest(), host)
+ assert set(payload) == _LEGACY_RESOLVER_KEYS | {"install_kind"}
+ assert payload["install_kind"] == "slim"
+ assert payload["asset"] == MAC_SLIM_ASSET
+ assert payload["backend"] == "metal"
+ assert payload["requested_backend"] == "metal"
diff --git a/tests/studio/install/test_prebuilt_core.py b/tests/studio/install/test_prebuilt_core.py
new file mode 100644
index 00000000000..4d1c37b8dae
--- /dev/null
+++ b/tests/studio/install/test_prebuilt_core.py
@@ -0,0 +1,918 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Shared descriptor-parameterized tests for studio/prebuilt_core.py.
+
+Runs the component-agnostic core against BOTH shipped descriptors -- the real
+whisper descriptor exported by install_whisper_prebuilt and a llama-flavored
+descriptor built here the way a hypothetical third ggml-family component would
+plug in (descriptor only, no installer module). Covers os/arch selection,
+checksum fail-closed behavior, extraction guards, the resolver payload, and the
+ops monkeypatch seam, so a new component gets this coverage for free.
+
+The llama installer's shipped release-plan machinery is intentionally NOT
+routed through the generic flow (its characterization suites pin it); the
+llama descriptor here exercises the canonical dialect a future migration
+would use, including the "no fallback backend -> report no prebuilt" policy.
+"""
+
+import importlib.util
+import io
+import json
+import sys
+import tarfile
+import zipfile
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+PACKAGE_ROOT = Path(__file__).resolve().parents[3]
+STUDIO_DIR = PACKAGE_ROOT / "studio"
+if str(STUDIO_DIR) not in sys.path:
+ sys.path.insert(0, str(STUDIO_DIR))
+
+SPEC = importlib.util.spec_from_file_location(
+ "studio_prebuilt_core", STUDIO_DIR / "prebuilt_core.py"
+)
+assert SPEC is not None and SPEC.loader is not None
+core = importlib.util.module_from_spec(SPEC)
+sys.modules[SPEC.name] = core
+SPEC.loader.exec_module(core)
+
+WSPEC = importlib.util.spec_from_file_location(
+ "studio_install_whisper_prebuilt_for_core", STUDIO_DIR / "install_whisper_prebuilt.py"
+)
+assert WSPEC is not None and WSPEC.loader is not None
+iwp = importlib.util.module_from_spec(WSPEC)
+sys.modules[WSPEC.name] = iwp
+WSPEC.loader.exec_module(iwp)
+
+
+LLAMA_DESCRIPTOR = core.ComponentDescriptor(
+ component = "llama.cpp",
+ log_prefix = "llama-prebuilt",
+ published_repo = "unslothai/llama.cpp",
+ manifest_asset_name = "llama-prebuilt-manifest.json",
+ sha256_asset_name = "llama-prebuilt-sha256.json",
+ metadata_filename = "UNSLOTH_LLAMA_PREBUILT_INFO.json",
+ user_agent = "unsloth-studio-llama-prebuilt",
+ # A GPU-selection miss reports "no prebuilt" so the caller can fall back to
+ # a source build instead of silently degrading to CPU.
+ fallback_backend = None,
+ server_binary_name = lambda host: "llama-server",
+ runtime_bin_dir = lambda install_dir, host: install_dir / "build" / "bin",
+)
+
+
+class Component:
+ """One descriptor under test plus the mutable namespace behind its ops."""
+
+ def __init__(self, descriptor):
+ self.descriptor = descriptor
+ self.namespace = core.component_namespace(descriptor)
+ self.namespace["log"] = lambda message: None # keep test output quiet
+ self.ops = core.ModuleOps(self.namespace)
+
+ @property
+ def falls_back_to_cpu(self):
+ return self.descriptor.fallback_backend == "cpu"
+
+
[email protected](params = ["whisper", "llama"])
+def component(request):
+ if request.param == "whisper":
+ return Component(iwp.DESCRIPTOR)
+ return Component(LLAMA_DESCRIPTOR)
+
+
+def make_host(
+ component,
+ *,
+ os_token = "linux",
+ arch_token = "x64",
+ is_windows = False,
+ is_macos = False,
+ is_apple_silicon = False,
+ has_usable_nvidia = False,
+ has_rocm = False,
+ rocm_gfx = None,
+ macos_version = None,
+):
+ if component.descriptor is iwp.DESCRIPTOR:
+ return iwp.HostInfo(
+ system = {"linux": "Linux", "macos": "Darwin", "windows": "Windows"}[os_token],
+ machine = "x86_64" if arch_token == "x64" else "arm64",
+ whisper_os = os_token,
+ whisper_arch = arch_token,
+ archive_ext = ".zip" if is_windows else ".tar.gz",
+ is_windows = is_windows,
+ is_macos = is_macos,
+ is_apple_silicon = is_apple_silicon,
+ has_usable_nvidia = has_usable_nvidia,
+ has_rocm = has_rocm,
+ rocm_gfx = rocm_gfx,
+ macos_version = macos_version,
+ )
+ # Descriptor-only component: the core default host_platform_tokens hook
+ # reads .os_token/.arch_token off a plain host object.
+ return SimpleNamespace(
+ os_token = os_token,
+ arch_token = arch_token,
+ is_windows = is_windows,
+ is_macos = is_macos,
+ is_apple_silicon = is_apple_silicon,
+ has_usable_nvidia = has_usable_nvidia,
+ has_rocm = has_rocm,
+ rocm_gfx = rocm_gfx,
+ macos_version = macos_version,
+ )
+
+
+def artifact(
+ os_ = "linux",
+ arch = "x64",
+ backend = "cpu",
+ asset = "bundle.tar.gz",
+ **extra,
+):
+ payload = {"os": os_, "arch": arch, "backend": backend, "asset": asset}
+ payload.update(extra)
+ return payload
+
+
+def manifest_for(component, artifacts, **extra):
+ payload = {
+ "schema_version": 1,
+ "component": extra.pop("component_name", component.descriptor.component),
+ "upstream_tag": "v1.0.0",
+ "source_commit": "a" * 40,
+ "artifacts": artifacts,
+ }
+ payload.update(extra)
+ return payload
+
+
+# ── Manifest parsing ──
+def test_parse_manifest_normalizes(component):
+ manifest = component.ops.parse_manifest(
+ manifest_for(component, [artifact(), "not-a-dict", {"os": "linux"}]), label = "m"
+ )
+ assert manifest["component"] == component.descriptor.component
+ assert manifest["upstream_tag"] == "v1.0.0"
+ # Non-dict entries and entries without an asset name are dropped.
+ assert [a["asset"] for a in manifest["artifacts"]] == ["bundle.tar.gz"]
+
+
+def test_parse_manifest_rejects_wrong_component(component):
+ with pytest.raises(core.PrebuiltFallback):
+ component.ops.parse_manifest(
+ manifest_for(component, [artifact()], component_name = "other.cpp"), label = "m"
+ )
+
+
+def test_parse_manifest_rejects_unknown_schema(component):
+ with pytest.raises(core.PrebuiltFallback):
+ component.ops.parse_manifest(
+ manifest_for(component, [artifact()], schema_version = 99), label = "m"
+ )
+
+
+def test_parse_manifest_rejects_non_object(component):
+ with pytest.raises(core.PrebuiltFallback):
+ component.ops.parse_manifest(["nope"], label = "m")
+ # An object without an 'artifacts' list is rejected too.
+ with pytest.raises(core.PrebuiltFallback):
+ component.ops.parse_manifest(
+ {"schema_version": 1, "component": component.descriptor.component}, label = "m"
+ )
+
+
+# ── Selection matrix ──
+def test_select_cpu_first_match(component):
+ manifest = component.ops.parse_manifest(
+ manifest_for(
+ component,
+ [
+ artifact(backend = "cpu", asset = "first-cpu.tar.gz"),
+ artifact(backend = "cpu", asset = "second-cpu.tar.gz"),
+ ],
+ ),
+ label = "m",
+ )
+ host = make_host(component)
+ chosen = component.ops.select_artifact(manifest, host, "cpu")
+ assert chosen["asset"] == "first-cpu.tar.gz"
+
+
+def test_select_respects_os_arch(component):
+ manifest = component.ops.parse_manifest(
+ manifest_for(component, [artifact(os_ = "windows", backend = "cpu")]), label = "m"
+ )
+ host = make_host(component)
+ assert component.ops.select_artifact(manifest, host, "cpu") is None
+
+
+def test_fallback_policy_differs_per_descriptor(component):
+ # No asset for the requested backend: whisper degrades to the CPU asset of
+ # the same release, the llama-flavored descriptor reports no prebuilt
+ # (source-build fallback).
+ manifest = component.ops.parse_manifest(
+ manifest_for(component, [artifact(backend = "cpu", asset = "cpu.tar.gz")]), label = "m"
+ )
+ host = make_host(component, has_usable_nvidia = True)
+ assert component.ops.select_artifact(manifest, host, "cuda") is None
+ if component.falls_back_to_cpu:
+ chosen, backend, used_fallback = component.ops.select_artifact_with_fallback(
+ manifest, host, "cuda"
+ )
+ assert (chosen["asset"], backend, used_fallback) == ("cpu.tar.gz", "cpu", True)
+ else:
+ with pytest.raises(core.PrebuiltFallback):
+ component.ops.select_artifact_with_fallback(manifest, host, "cuda")
+
+
+def test_macos_min_os_gate(component):
+ manifest = component.ops.parse_manifest(
+ manifest_for(
+ component,
+ [
+ artifact(
+ os_ = "macos",
+ arch = "arm64",
+ backend = "metal",
+ asset = "metal-new.tar.gz",
+ min_os = "macos-15.0",
+ )
+ ],
+ ),
+ label = "m",
+ )
+ old_host = make_host(
+ component,
+ os_token = "macos",
+ arch_token = "arm64",
+ is_macos = True,
+ is_apple_silicon = True,
+ macos_version = (14, 7),
+ )
+ new_host = make_host(
+ component,
+ os_token = "macos",
+ arch_token = "arm64",
+ is_macos = True,
+ is_apple_silicon = True,
+ macos_version = (15, 1),
+ )
+ assert component.ops.select_artifact(manifest, old_host, "metal") is None
+ chosen = component.ops.select_artifact(manifest, new_host, "metal")
+ assert chosen["asset"] == "metal-new.tar.gz"
+
+
+def _metal_artifact(asset, min_os):
+ return artifact(
+ os_ = "macos",
+ arch = "arm64",
+ backend = "metal",
+ asset = asset,
+ min_os = min_os,
+ )
+
+
+def _arm_mac_host(component, macos_version):
+ return make_host(
+ component,
+ os_token = "macos",
+ arch_token = "arm64",
+ is_macos = True,
+ is_apple_silicon = True,
+ macos_version = macos_version,
+ )
+
+
+def test_macos_min_os_filters_to_compatible_bundle(component):
+ # host 14.0 can't load the 15.0 bundle; the 13.0 bundle is picked instead.
+ manifest = component.ops.parse_manifest(
+ manifest_for(
+ component,
+ [
+ _metal_artifact("metal-new.tar.gz", "macos-15.0"),
+ _metal_artifact("metal.tar.gz", "macos-13.0"),
+ ],
+ ),
+ label = "m",
+ )
+ host = _arm_mac_host(component, (14, 0))
+ assert component.ops.select_artifact(manifest, host, "metal")["asset"] == "metal.tar.gz"
+
+
+def test_macos_min_os_unknown_host_version_keeps_artifact(component):
+ # Unknown host macOS version -> defer to runtime validation, don't reject.
+ manifest = component.ops.parse_manifest(
+ manifest_for(component, [_metal_artifact("metal-new.tar.gz", "macos-15.0")]), label = "m"
+ )
+ host = _arm_mac_host(component, None)
+ assert component.ops.select_artifact(manifest, host, "metal")["asset"] == "metal-new.tar.gz"
+
+
+def test_macos_min_os_accepts_bare_version_format(component):
+ # A bare "14.0" (no 'macos-' prefix) must still parse, for forward-compat.
+ manifest = component.ops.parse_manifest(
+ manifest_for(component, [_metal_artifact("metal.tar.gz", "14.0")]), label = "m"
+ )
+ host = _arm_mac_host(component, (13, 0))
+ assert component.ops.select_artifact(manifest, host, "metal") is None # 13.0 < 14.0
+
+
+def test_macos_min_os_ok_helper_handles_prefix_and_bare(component):
+ host14 = _arm_mac_host(component, (14, 0))
+ # The live manifest format is 'macos-<ver>'; the prefix must be stripped.
+ assert component.ops.macos_min_os_ok(host14, "macos-14.0") is True
+ assert component.ops.macos_min_os_ok(host14, "macos-15.0") is False
+ assert component.ops.macos_min_os_ok(host14, "13.3") is True # bare also parses
+ assert component.ops.macos_min_os_ok(host14, None) is True # unknown -> defer
+ host_unknown = _arm_mac_host(component, None)
+ assert component.ops.macos_min_os_ok(host_unknown, "macos-15.0") is True
+
+
+# ── Backend resolution ──
+def test_resolve_backend_auto_and_validation(component):
+ gpu_host = make_host(component, has_usable_nvidia = True)
+ assert component.ops.resolve_backend(gpu_host, "auto", cpu_fallback = False) == "cuda"
+ assert component.ops.resolve_backend(gpu_host, "auto", cpu_fallback = True) == "cpu"
+ # --cpu-fallback wins over an explicit backend too.
+ assert component.ops.resolve_backend(gpu_host, "cuda", cpu_fallback = True) == "cpu"
+ # An explicit supported backend passes through untouched.
+ assert component.ops.resolve_backend(gpu_host, "vulkan", cpu_fallback = False) == "vulkan"
+ mac_host = make_host(
+ component, os_token = "macos", arch_token = "arm64", is_macos = True, is_apple_silicon = True
+ )
+ assert component.ops.resolve_backend(mac_host, None, cpu_fallback = False) == "metal"
+ # Intel mac has no Metal bundle in the P0 matrix -> cpu.
+ intel_mac = make_host(component, os_token = "macos", arch_token = "x64", is_macos = True)
+ assert component.ops.resolve_backend(intel_mac, "auto", cpu_fallback = False) == "cpu"
+ rocm_host = make_host(component, has_rocm = True, rocm_gfx = "gfx1100")
+ assert component.ops.resolve_backend(rocm_host, "auto", cpu_fallback = False) == "rocm"
+ bare_host = make_host(component)
+ assert component.ops.resolve_backend(bare_host, None, cpu_fallback = False) == "cpu"
+ with pytest.raises(core.PrebuiltFallback):
+ component.ops.resolve_backend(gpu_host, "tpu", cpu_fallback = False)
+
+
+# ── Checksum index: fail closed ──
+def _index_for(
+ component,
+ tag = "v1",
+ artifacts = None,
+):
+ return {
+ "schema_version": 1,
+ "component": component.descriptor.component,
+ "release_tag": tag,
+ "artifacts": artifacts
+ if artifacts is not None
+ else {"bundle.tar.gz": {"sha256": "0" * 64}},
+ }
+
+
+def test_parse_release_checksums_valid(component):
+ out = component.ops.parse_release_checksums("r", "v1", _index_for(component))
+ assert out == {"bundle.tar.gz": "0" * 64}
+
+
+ "mutation",
+ [
+ {"component": "other.cpp"},
+ {"schema_version": 99},
+ {"release_tag": "v2"},
+ {"artifacts": {"bundle.tar.gz": {"sha256": "nope"}}},
+ {"artifacts": "not-a-map"},
+ ],
+)
+def test_parse_release_checksums_fails_closed(component, mutation):
+ payload = _index_for(component)
+ payload.update(mutation)
+ with pytest.raises(core.PrebuiltFallback):
+ component.ops.parse_release_checksums("r", "v1", payload)
+
+
+def test_parse_release_checksums_rejects_non_object(component):
+ with pytest.raises(core.PrebuiltFallback):
+ component.ops.parse_release_checksums("r", "v1", ["not", "a", "dict"])
+
+
+def test_expected_sha256_covered_asset_plain_lookup(component):
+ assert component.ops.expected_sha256_for({"a.tar.gz": "0" * 64}, "a.tar.gz") == "0" * 64
+
+
+def test_expected_sha256_missing_asset_fails_closed(component):
+ with pytest.raises(core.PrebuiltFallback):
+ component.ops.expected_sha256_for({"a.tar.gz": "0" * 64}, "b.tar.gz")
+
+
+def test_expected_sha256_manifest_disagreement_fails_closed(component):
+ with pytest.raises(core.PrebuiltFallback):
+ component.ops.expected_sha256_for(
+ {"a.tar.gz": "0" * 64}, "a.tar.gz", manifest_sha256 = "1" * 64
+ )
+ assert (
+ component.ops.expected_sha256_for(
+ {"a.tar.gz": "0" * 64}, "a.tar.gz", manifest_sha256 = "0" * 64
+ )
+ == "0" * 64
+ )
+
+
+# ── Extraction guards ──
+def test_extract_archive_rejects_traversal(tmp_path):
+ archive = tmp_path / "evil.tar.gz"
+ with tarfile.open(archive, "w:gz") as tar:
+ data = b"x"
+ info = tarfile.TarInfo("../escape.txt")
+ info.size = len(data)
+ tar.addfile(info, io.BytesIO(data))
+ with pytest.raises(core.PrebuiltFallback):
+ core.extract_archive(archive, tmp_path / "out")
+
+
+def test_extract_archive_rejects_absolute_member(tmp_path):
+ archive = tmp_path / "abs.tar.gz"
+ with tarfile.open(archive, "w:gz") as tar:
+ data = b"x"
+ info = tarfile.TarInfo("/abs.txt")
+ info.size = len(data)
+ tar.addfile(info, io.BytesIO(data))
+ with pytest.raises(core.PrebuiltFallback):
+ core.extract_archive(archive, tmp_path / "out")
+
+
+def test_extract_archive_rejects_zip_symlink(tmp_path):
+ archive = tmp_path / "link.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ info = zipfile.ZipInfo("link")
+ info.create_system = 3
+ info.external_attr = 0o120777 << 16
+ zf.writestr(info, "target")
+ with pytest.raises(core.PrebuiltFallback, match = "zip archive contained a symlink entry"):
+ core.extract_archive(archive, tmp_path / "out")
+
+
+def test_extract_archive_rejects_absolute_zip_member(tmp_path):
+ archive = tmp_path / "abs.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ zf.writestr("/etc/passwd", b"pwn")
+ with pytest.raises(core.PrebuiltFallback):
+ core.extract_archive(archive, tmp_path / "out")
+
+
+def test_extract_archive_allows_safe_tar_symlink_chain(tmp_path):
+ archive = tmp_path / "bundle.tar.gz"
+ payload = b"shared-object"
+ with tarfile.open(archive, "w:gz") as tar:
+ versioned = tarfile.TarInfo("libllama.so.0.0.1")
+ versioned.size = len(payload)
+ tar.addfile(versioned, io.BytesIO(payload))
+ soname = tarfile.TarInfo("libllama.so.0")
+ soname.type = tarfile.SYMTYPE
+ soname.linkname = "libllama.so.0.0.1"
+ tar.addfile(soname)
+ linker_name = tarfile.TarInfo("libllama.so")
+ linker_name.type = tarfile.SYMTYPE
+ linker_name.linkname = "libllama.so.0"
+ tar.addfile(linker_name)
+ destination = tmp_path / "extract"
+ core.extract_archive(archive, destination)
+ assert (destination / "libllama.so.0.0.1").read_bytes() == payload
+ assert (destination / "libllama.so.0").is_symlink()
+ assert (destination / "libllama.so").is_symlink()
+ assert (destination / "libllama.so").resolve().read_bytes() == payload
+
+
+def test_extract_archive_allows_safe_tar_hardlink(tmp_path):
+ archive = tmp_path / "bundle.tar.gz"
+ payload = b"quantize"
+ with tarfile.open(archive, "w:gz") as tar:
+ target = tarfile.TarInfo("llama-quantize")
+ target.size = len(payload)
+ tar.addfile(target, io.BytesIO(payload))
+ hardlink = tarfile.TarInfo("llama-quantize-copy")
+ hardlink.type = tarfile.LNKTYPE
+ hardlink.linkname = "llama-quantize"
+ tar.addfile(hardlink)
+ destination = tmp_path / "extract"
+ core.extract_archive(archive, destination)
+ assert (destination / "llama-quantize-copy").read_bytes() == payload
+ assert not (destination / "llama-quantize-copy").is_symlink()
+
+
+def test_extract_archive_rejects_absolute_tar_symlink_target(tmp_path):
+ archive = tmp_path / "bundle.tar.gz"
+ with tarfile.open(archive, "w:gz") as tar:
+ entry = tarfile.TarInfo("libllama.so")
+ entry.type = tarfile.SYMTYPE
+ entry.linkname = "/tmp/libllama.so.0"
+ tar.addfile(entry)
+ with pytest.raises(core.PrebuiltFallback, match = "archive link used an absolute target"):
+ core.extract_archive(archive, tmp_path / "extract")
+
+
+def test_extract_archive_rejects_escaping_tar_symlink_target(tmp_path):
+ archive = tmp_path / "bundle.tar.gz"
+ with tarfile.open(archive, "w:gz") as tar:
+ entry = tarfile.TarInfo("libllama.so")
+ entry.type = tarfile.SYMTYPE
+ entry.linkname = "../outside/libllama.so.0"
+ tar.addfile(entry)
+ with pytest.raises(core.PrebuiltFallback, match = "archive link escaped destination"):
+ core.extract_archive(archive, tmp_path / "extract")
+
+
+def test_extract_archive_rejects_unresolved_tar_symlink_target(tmp_path):
+ archive = tmp_path / "bundle.tar.gz"
+ with tarfile.open(archive, "w:gz") as tar:
+ entry = tarfile.TarInfo("libllama.so")
+ entry.type = tarfile.SYMTYPE
+ entry.linkname = "libllama.so.0"
+ tar.addfile(entry)
+ with pytest.raises(core.PrebuiltFallback, match = "unresolved link entries"):
+ core.extract_archive(archive, tmp_path / "extract")
+
+
+def test_extract_archive_rejects_unknown_format(tmp_path):
+ archive = tmp_path / "blob.xz"
+ archive.write_bytes(b"data")
+ with pytest.raises(core.PrebuiltFallback):
+ core.extract_archive(archive, tmp_path / "out")
+
+
+def test_restore_tar_exec_bits(tmp_path):
+ payload = tmp_path / "server"
+ payload.write_bytes(b"#!/bin/sh\n")
+ payload.chmod(0o755)
+ archive = tmp_path / "bundle.tar.gz"
+ with tarfile.open(archive, "w:gz") as tar:
+ tar.add(payload, arcname = "bundle/server")
+ out = tmp_path / "out"
+ core.extract_archive(archive, out)
+ extracted = out / "bundle" / "server"
+ assert extracted.is_file()
+ core.restore_tar_exec_bits(archive, out)
+ assert extracted.stat().st_mode & 0o111
+
+
+# ── Resolver payload ──
+def _fake_release(component, artifacts):
+ ns = component.namespace
+ manifest = component.ops.parse_manifest(manifest_for(component, artifacts), label = "m")
+ bundle = core.ReleaseBundle(
+ repo = component.descriptor.published_repo,
+ release_tag = "v1",
+ manifest = manifest,
+ asset_urls = {},
+ )
+ checksums = {str(a["asset"]): "0" * 64 for a in artifacts}
+ ns["fetch_release_for_install"] = lambda repo, *, published_release_tag: (bundle, checksums)
+ return bundle
+
+
+def test_resolve_prebuilt_payload_keys(component):
+ _fake_release(component, [artifact(backend = "cpu", asset = "cpu.tar.gz")])
+ host = make_host(component)
+ payload = component.ops.resolve_prebuilt(
+ host,
+ published_repo = component.descriptor.published_repo,
+ published_release_tag = None,
+ backend = "cpu",
+ cpu_fallback = True,
+ )
+ assert payload == {
+ "prebuilt_available": True,
+ "repo": component.descriptor.published_repo,
+ "release_tag": "v1",
+ "upstream_tag": "v1.0.0",
+ "backend": "cpu",
+ "requested_backend": "cpu",
+ "cpu_fallback": False,
+ "asset": "cpu.tar.gz",
+ "os": "linux",
+ "arch": "x64",
+ "runtime_line": None,
+ }
+
+
+def test_resolve_prebuilt_unavailable_payload(component):
+ ns = component.namespace
+
+ def boom(repo, *, published_release_tag):
+ raise core.PrebuiltFallback("no release")
+
+ ns["fetch_release_for_install"] = boom
+ host = make_host(component)
+ payload = component.ops.resolve_prebuilt(
+ host,
+ published_repo = component.descriptor.published_repo,
+ published_release_tag = None,
+ backend = "cpu",
+ cpu_fallback = True,
+ )
+ assert payload == {"prebuilt_available": False, "repo": component.descriptor.published_repo}
+
+
+def test_emit_resolver_output_formats(capsys):
+ payload = {"prebuilt_available": True, "asset": "a.tar.gz"}
+ core.emit_resolver_output(payload, output_format = "json")
+ assert json.loads(capsys.readouterr().out) == payload
+ core.emit_resolver_output(payload, output_format = "plain")
+ assert capsys.readouterr().out.strip() == "a.tar.gz"
+ core.emit_resolver_output({"prebuilt_available": False}, output_format = "plain")
+ assert json.loads(capsys.readouterr().out) == {"prebuilt_available": False}
+
+
+# ── Marker / fingerprint ──
+def test_install_fingerprint_is_stable_and_sensitive(component):
+ kwargs = dict(
+ published_repo = component.descriptor.published_repo,
+ release_tag = "v1",
+ upstream_tag = "v1.0.0",
+ source_commit = "a" * 40,
+ asset = "cpu.tar.gz",
+ asset_sha256 = "0" * 64,
+ backend = "cpu",
+ runtime_line = None,
+ coverage = {},
+ )
+ first = core.compute_install_fingerprint(**kwargs)
+ assert first == core.compute_install_fingerprint(**kwargs)
+ changed = core.compute_install_fingerprint(**{**kwargs, "asset_sha256": "1" * 64})
+ assert changed != first
+
+
+def test_write_and_match_marker(component, tmp_path):
+ host = make_host(component)
+ install_dir = tmp_path / "install"
+ manifest = component.ops.parse_manifest(
+ manifest_for(component, [artifact(backend = "cpu", asset = "cpu.tar.gz")]), label = "m"
+ )
+ selection = component.ops.selection_from_artifact(
+ published_repo = component.descriptor.published_repo,
+ release_tag = "v1",
+ manifest = manifest,
+ artifact = manifest["artifacts"][0],
+ backend = "cpu",
+ asset_sha256 = "0" * 64,
+ )
+ # No marker on disk yet -> not a match.
+ assert not component.ops.existing_install_matches(install_dir, host, selection)
+ bin_dir = component.ops.runtime_bin_dir(install_dir, host)
+ bin_dir.mkdir(parents = True)
+ component.ops.write_prebuilt_metadata(install_dir, selection)
+ # Marker alone is not enough: the server binary must exist too.
+ assert not component.ops.existing_install_matches(install_dir, host, selection)
+ (bin_dir / component.ops.server_binary_name(host)).write_bytes(b"bin")
+ marker = json.loads((install_dir / component.descriptor.metadata_filename).read_text())
+ assert marker["component"] == component.descriptor.component
+ assert marker["install_fingerprint"] == selection.fingerprint()
+ assert component.ops.existing_install_matches(install_dir, host, selection)
+ # A different selection (new sha) must force a reinstall.
+ other = core.InstallSelection(
+ **{
+ **selection.__dict__,
+ "asset_sha256": "1" * 64,
+ }
+ )
+ assert not component.ops.existing_install_matches(install_dir, host, other)
+
+
+def test_slim_selection_fields_are_additive(component, tmp_path):
+ """The slim pairing identity rides InstallSelection additively: it never
+ enters the fingerprint, and only a slim selection writes marker fields."""
+ manifest = component.ops.parse_manifest(
+ manifest_for(component, [artifact(backend = "cpu", asset = "cpu.tar.gz")]), label = "m"
+ )
+ selection = component.ops.selection_from_artifact(
+ published_repo = component.descriptor.published_repo,
+ release_tag = "v1",
+ manifest = manifest,
+ artifact = manifest["artifacts"][0],
+ backend = "cpu",
+ asset_sha256 = "0" * 64,
+ )
+ import dataclasses
+
+ slim = dataclasses.replace(
+ selection,
+ install_kind = "slim",
+ paired_llama_tag = "b10069-mix-fb3d4ca",
+ linked_from = "/llama/build/bin",
+ linked_libraries = ("libggml.so.0", "libggml-base.so.0"),
+ )
+ assert slim.fingerprint() == selection.fingerprint() # no change to the computation
+
+ fat_dir, slim_dir = tmp_path / "fat", tmp_path / "slim"
+ fat_dir.mkdir(), slim_dir.mkdir()
+ component.ops.write_prebuilt_metadata(fat_dir, selection)
+ fat_marker = json.loads((fat_dir / component.descriptor.metadata_filename).read_text())
+ for key in ("install_kind", "paired_llama_tag", "linked_from", "linked_libraries"):
+ assert key not in fat_marker
+ component.ops.write_prebuilt_metadata(slim_dir, slim)
+ slim_marker = json.loads((slim_dir / component.descriptor.metadata_filename).read_text())
+ assert slim_marker["install_kind"] == "slim"
+ assert slim_marker["paired_llama_tag"] == "b10069-mix-fb3d4ca"
+ assert slim_marker["linked_from"] == "/llama/build/bin"
+ assert slim_marker["linked_libraries"] == ["libggml.so.0", "libggml-base.so.0"]
+ assert set(slim_marker) == set(fat_marker) | {
+ "install_kind",
+ "paired_llama_tag",
+ "linked_from",
+ "linked_libraries",
+ }
+
+
+def test_core_slim_hooks_default_inert(component, tmp_path):
+ # A component without its own hooks stages nothing extra and adds no
+ # resolver fields (llama's probe output must stay byte-identical).
+ assert component.ops.resolver_payload_extra({"install_kind": "slim"}) == {}
+ host = make_host(component)
+ selection = object()
+ assert component.ops.prepare_runtime_payload(tmp_path, host, selection) is None
+
+
+def test_busy_activation_restores_previous_install(monkeypatch, tmp_path):
+ install_dir = tmp_path / "whisper.cpp"
+ staged_root = tmp_path / "staged"
+ install_dir.mkdir()
+ staged_root.mkdir()
+ (install_dir / "version").write_text("old")
+ (staged_root / "version").write_text("new")
+ real_replace = core.os.replace
+
+ def locked_activation(source, destination):
+ if Path(source) == staged_root:
+ raise PermissionError(13, "Permission denied")
+ return real_replace(source, destination)
+
+ monkeypatch.setattr(core.os, "replace", locked_activation)
+ with pytest.raises(core.BusyInstallConflict):
+ core.swap_into_place(staged_root, install_dir)
+
+ assert (install_dir / "version").read_text() == "old"
+ assert staged_root.is_dir()
+ assert not list(tmp_path.glob(".whisper.cpp.old-*"))
+
+
+# ── Host/GPU token helpers (component-independent core functions) ──
+# Value tables moved verbatim from the llama characterization suite; these are
+# pure functions with no descriptor sensitivity, so they run unparameterized.
+ "value,expected",
+ [
+ ("8.6", "86"),
+ ("07.05", "75"),
+ ("75", "75"),
+ (86, "86"),
+ ("", None),
+ (" ", None),
+ ("x.y", None),
+ ("8.6.0", None),
+ ("9.0", "90"),
+ ],
+)
+def test_normalize_compute_cap(value, expected):
+ assert core.normalize_compute_cap(value) == expected
+
+
+ "values,expected",
+ [
+ (["8.6", "86", "8.6"], ["86"]), # deduplication
+ (["9.0", "7.5", "8.6"], ["75", "86", "90"]), # numeric sort
+ (["8.6", "bad", "", "7.5"], ["75", "86"]), # drops invalid
+ ([], []),
+ ],
+)
+def test_normalize_compute_caps(values, expected):
+ assert core.normalize_compute_caps(values) == expected
+
+
+ "value,expected",
+ [
+ (None, None),
+ ("", []),
+ ("-1", []),
+ ("0", ["0"]),
+ ("0,1,2", ["0", "1", "2"]),
+ (" 0 , 1 ", ["0", "1"]),
+ ],
+)
+def test_parse_cuda_visible_devices(value, expected):
+ assert core.parse_cuda_visible_devices(value) == expected
+
+
+ "visible,expected",
+ [
+ (["0", "1", "2"], True),
+ (["GPU-abc123"], True),
+ (None, False),
+ ([], False),
+ (["0", "MIG-device"], False),
+ ],
+)
+def test_supports_explicit_visible_device_matching(visible, expected):
+ assert core.supports_explicit_visible_device_matching(visible) is expected
+
+
+_GPU_ROWS = [
+ ("0", "GPU-aaa", "8.6"),
+ ("1", "GPU-bbb", "7.5"),
+ ("2", "GPU-ccc", "8.9"),
+]
+
+
+ "visible,expected_indices",
+ [
+ (None, [0, 1, 2]), # no filter returns all
+ ([], []),
+ (["0", "2"], [0, 2]), # filter by index
+ (["gpu-bbb"], [1]), # UUID match is case insensitive
+ (["0", "0"], [0]), # same device requested twice is deduplicated
+ (["99"], []), # unknown token matches nothing
+ ],
+)
+def test_select_visible_gpu_rows(visible, expected_indices):
+ expected = [_GPU_ROWS[i] for i in expected_indices]
+ assert core.select_visible_gpu_rows(_GPU_ROWS, visible) == expected
+
+
+ "driver,expected",
+ [
+ (None, []),
+ ((11, 8), []),
+ ((12, 4), ["cuda12"]),
+ ((13, 0), ["cuda13", "cuda12"]),
+ ((14, 0), ["cuda14", "cuda13", "cuda12"]), # future major derives lines
+ ],
+)
+def test_compatible_linux_runtime_lines(driver, expected):
+ host = SimpleNamespace(driver_cuda_version = driver)
+ assert core.compatible_linux_runtime_lines(host) == expected
+
+
+ "value,expected",
+ [
+ ("12.6", "cuda12"),
+ ("13.0", "cuda13"),
+ ("11.8", None),
+ (None, None),
+ ("", None),
+ ],
+)
+def test_runtime_line_from_cuda_version(value, expected):
+ assert core.runtime_line_from_cuda_version(value) == expected
+
+
+def _caps_host(caps):
+ return SimpleNamespace(compute_caps = list(caps))
+
+
+def test_host_is_blackwell_includes_datacenter_parts():
+ assert core.host_is_blackwell(_caps_host(["10.0"])) is True # B200 sm_100
+ assert core.host_is_blackwell(_caps_host(["10.3"])) is True # B300 sm_103
+ assert core.host_is_blackwell(_caps_host(["12.0"])) is True # RTX 50 sm_120
+ assert core.host_is_blackwell(_caps_host(["12.1"])) is True # DGX Spark sm_121
+ assert core.host_is_blackwell(_caps_host(["9.0"])) is False # Hopper
+ assert core.host_is_blackwell(_caps_host(["8.0"])) is False # Ampere
+ assert core.host_is_blackwell(_caps_host(["9.0", "10.0"])) is True # highest cap wins
+
+
+def test_blackwell_min_toolkit_is_sm_aware():
+ # Family floor is 12.8; sm_103/sm_121 (no native target before 12.9) lift it.
+ f = core.blackwell_min_toolkit_for_host
+ assert f(_caps_host(["10.0"])) == (12, 8) # B200
+ assert f(_caps_host(["12.0"])) == (12, 8) # RTX 50
+ assert f(_caps_host(["10.3"])) == (12, 9) # B300
+ assert f(_caps_host(["12.1"])) == (12, 9) # DGX Spark
+ assert f(_caps_host(["10.0", "10.3"])) == (12, 9) # max across SMs wins
+
+
+# ── The ops seam ──
+def test_module_ops_prefers_module_globals_over_core_defaults(component):
+ ns = dict(component.namespace)
+ calls = []
+
+ def fake_download_file(url, destination):
+ calls.append(url)
+ destination.write_bytes(b"data")
+
+ ns["download_file"] = fake_download_file
+ ops = core.ModuleOps(ns)
+ assert ops.download_file is fake_download_file
+ # Core defaults still resolve (and come back bound) for everything else.
+ assert callable(ops.fetch_json)
+ with pytest.raises(AttributeError):
+ _ = ops.does_not_exist_anywhere
diff --git a/tests/studio/install/test_rocm_support.py b/tests/studio/install/test_rocm_support.py
index fa760110410..b919206120a 100644
--- a/tests/studio/install/test_rocm_support.py
+++ b/tests/studio/install/test_rocm_support.py
@@ -232,6 +232,10 @@ UPSTREAM_ASSETS = {
class TestResolveUpstreamAssetChoice:
"""Verify that the asset selection logic picks the right binary for each platform."""
+ # The plain cpu-linux / windows-cpu / macos-arm64 routing cases live in
+ # test_selection_logic.py::TestResolveUpstreamAssetChoice (exact-name pins);
+ # this class keeps the ROCm/NVIDIA-precedence dialect only.
+
@patch.object(prebuilt_mod, "github_release_assets", return_value = UPSTREAM_ASSETS)
def test_nvidia_linux_gets_cpu_asset(self, mock_assets):
"""NVIDIA host should NOT hit the ROCm path -- gets CPU asset (CUDA handled elsewhere)."""
@@ -249,30 +253,6 @@ class TestResolveUpstreamAssetChoice:
assert choice.install_kind == "linux-rocm"
assert "rocm" in choice.name
- @patch.object(prebuilt_mod, "github_release_assets", return_value = UPSTREAM_ASSETS)
- def test_cpu_linux_gets_cpu_asset(self, mock_assets):
- """CPU-only Linux host should get CPU asset."""
- host = cpu_host()
- choice = resolve_upstream_asset_choice(host, LLAMA_TAG)
- assert choice.install_kind == "linux-cpu"
- assert "ubuntu-x64" in choice.name
-
- @patch.object(prebuilt_mod, "github_release_assets", return_value = UPSTREAM_ASSETS)
- def test_macos_arm64_gets_macos_asset(self, mock_assets):
- """macOS arm64 host should get macOS asset."""
- host = macos_host()
- choice = resolve_upstream_asset_choice(host, LLAMA_TAG)
- assert choice.install_kind == "macos-arm64"
- assert "macos-arm64" in choice.name
-
- @patch.object(prebuilt_mod, "github_release_assets", return_value = UPSTREAM_ASSETS)
- def test_windows_cpu_gets_cpu_asset(self, mock_assets):
- """Windows CPU-only host should get Windows CPU asset."""
- host = windows_host()
- choice = resolve_upstream_asset_choice(host, LLAMA_TAG)
- assert choice.install_kind == "windows-cpu"
- assert "win-cpu" in choice.name
-
@patch.object(prebuilt_mod, "github_release_assets", return_value = UPSTREAM_ASSETS)
def test_windows_rocm_gets_hip_asset(self, mock_assets):
"""Windows ROCm host should get Windows HIP asset."""
diff --git a/tests/studio/install/test_selection_logic.py b/tests/studio/install/test_selection_logic.py
index e372a3bbeb2..8ebcd6cc863 100644
--- a/tests/studio/install/test_selection_logic.py
+++ b/tests/studio/install/test_selection_logic.py
@@ -31,17 +31,8 @@ PrebuiltFallback = INSTALL_LLAMA_PREBUILT.PrebuiltFallback
LinuxCudaSelection = INSTALL_LLAMA_PREBUILT.LinuxCudaSelection
UPSTREAM_REPO = INSTALL_LLAMA_PREBUILT.UPSTREAM_REPO
-normalize_compute_cap = INSTALL_LLAMA_PREBUILT.normalize_compute_cap
-normalize_compute_caps = INSTALL_LLAMA_PREBUILT.normalize_compute_caps
-parse_cuda_visible_devices = INSTALL_LLAMA_PREBUILT.parse_cuda_visible_devices
-supports_explicit_visible_device_matching = (
- INSTALL_LLAMA_PREBUILT.supports_explicit_visible_device_matching
-)
-select_visible_gpu_rows = INSTALL_LLAMA_PREBUILT.select_visible_gpu_rows
-compatible_linux_runtime_lines = INSTALL_LLAMA_PREBUILT.compatible_linux_runtime_lines
pick_windows_cuda_runtime = INSTALL_LLAMA_PREBUILT.pick_windows_cuda_runtime
compatible_windows_runtime_lines = INSTALL_LLAMA_PREBUILT.compatible_windows_runtime_lines
-runtime_line_from_cuda_version = INSTALL_LLAMA_PREBUILT.runtime_line_from_cuda_version
apply_approved_hashes = INSTALL_LLAMA_PREBUILT.apply_approved_hashes
linux_cuda_choice_from_release = INSTALL_LLAMA_PREBUILT.linux_cuda_choice_from_release
windows_cuda_attempts = INSTALL_LLAMA_PREBUILT.windows_cuda_attempts
@@ -452,165 +443,25 @@ class TestStudioLocalhostIpv6Warning:
# ===========================================================================
-# A. normalize_compute_cap
+# A-F, H. Component-independent GPU/token helpers: the behavior tables live in
+# tests/studio/install/test_prebuilt_core.py (they are pure prebuilt_core
+# functions). This pin proves the installer still re-exports them from core, so
+# the master tables keep covering the names this module and its callers use.
# ===========================================================================
-class TestNormalizeComputeCap:
- def test_dotted_86(self):
- assert normalize_compute_cap("8.6") == "86"
-
- def test_dotted_leading_zero(self):
- assert normalize_compute_cap("07.05") == "75"
-
- def test_already_normalized(self):
- assert normalize_compute_cap("75") == "75"
-
- def test_int_input(self):
- assert normalize_compute_cap(86) == "86"
-
- def test_empty_string(self):
- assert normalize_compute_cap("") is None
-
- def test_whitespace(self):
- assert normalize_compute_cap(" ") is None
-
- def test_non_numeric(self):
- assert normalize_compute_cap("x.y") is None
-
- def test_triple_part(self):
- assert normalize_compute_cap("8.6.0") is None
-
- def test_zero_minor(self):
- assert normalize_compute_cap("9.0") == "90"
-
-
-# ===========================================================================
-# B. normalize_compute_caps
-# ===========================================================================
-
-
-class TestNormalizeComputeCaps:
- def test_deduplication(self):
- assert normalize_compute_caps(["8.6", "86", "8.6"]) == ["86"]
-
- def test_numeric_sort(self):
- assert normalize_compute_caps(["9.0", "7.5", "8.6"]) == ["75", "86", "90"]
-
- def test_drops_invalid(self):
- assert normalize_compute_caps(["8.6", "bad", "", "7.5"]) == ["75", "86"]
-
- def test_empty_input(self):
- assert normalize_compute_caps([]) == []
-
-
-# ===========================================================================
-# C. parse_cuda_visible_devices
-# ===========================================================================
-
-
-class TestParseCudaVisibleDevices:
- def test_none(self):
- assert parse_cuda_visible_devices(None) is None
-
- def test_empty(self):
- assert parse_cuda_visible_devices("") == []
-
- def test_minus_one(self):
- assert parse_cuda_visible_devices("-1") == []
-
- def test_single(self):
- assert parse_cuda_visible_devices("0") == ["0"]
-
- def test_multi(self):
- assert parse_cuda_visible_devices("0,1,2") == ["0", "1", "2"]
-
- def test_whitespace_stripped(self):
- assert parse_cuda_visible_devices(" 0 , 1 ") == ["0", "1"]
-
-
-# ===========================================================================
-# D. supports_explicit_visible_device_matching
-# ===========================================================================
-
-
-class TestSupportsExplicitVisibleDeviceMatching:
- def test_all_digits(self):
- assert supports_explicit_visible_device_matching(["0", "1", "2"]) is True
-
- def test_gpu_prefix(self):
- assert supports_explicit_visible_device_matching(["GPU-abc123"]) is True
-
- def test_none(self):
- assert supports_explicit_visible_device_matching(None) is False
-
- def test_empty(self):
- assert supports_explicit_visible_device_matching([]) is False
-
- def test_mixed_invalid(self):
- assert supports_explicit_visible_device_matching(["0", "MIG-device"]) is False
-
-
-# ===========================================================================
-# E. select_visible_gpu_rows
-# ===========================================================================
-
-
-class TestSelectVisibleGpuRows:
- ROWS = [
- ("0", "GPU-aaa", "8.6"),
- ("1", "GPU-bbb", "7.5"),
- ("2", "GPU-ccc", "8.9"),
- ]
-
- def test_none_returns_all(self):
- assert select_visible_gpu_rows(self.ROWS, None) == list(self.ROWS)
-
- def test_empty_returns_empty(self):
- assert select_visible_gpu_rows(self.ROWS, []) == []
-
- def test_filter_by_index(self):
- result = select_visible_gpu_rows(self.ROWS, ["0", "2"])
- assert result == [("0", "GPU-aaa", "8.6"), ("2", "GPU-ccc", "8.9")]
-
- def test_filter_by_uuid_case_insensitive(self):
- result = select_visible_gpu_rows(self.ROWS, ["gpu-bbb"])
- assert result == [("1", "GPU-bbb", "7.5")]
-
- def test_dedup_same_device(self):
- result = select_visible_gpu_rows(self.ROWS, ["0", "0"])
- assert result == [("0", "GPU-aaa", "8.6")]
-
- def test_missing_token(self):
- result = select_visible_gpu_rows(self.ROWS, ["99"])
- assert result == []
-
-
-# ===========================================================================
-# F. compatible_linux_runtime_lines
-# ===========================================================================
-
-
-class TestCompatibleLinuxRuntimeLines:
- def test_no_driver(self):
- host = make_host(driver_cuda_version = None)
- assert compatible_linux_runtime_lines(host) == []
-
- def test_driver_11_8(self):
- host = make_host(driver_cuda_version = (11, 8))
- assert compatible_linux_runtime_lines(host) == []
-
- def test_driver_12_4(self):
- host = make_host(driver_cuda_version = (12, 4))
- assert compatible_linux_runtime_lines(host) == ["cuda12"]
-
- def test_driver_13_0(self):
- host = make_host(driver_cuda_version = (13, 0))
- assert compatible_linux_runtime_lines(host) == ["cuda13", "cuda12"]
-
- def test_future_major_derives_lines(self):
- host = make_host(driver_cuda_version = (14, 0))
- assert compatible_linux_runtime_lines(host) == ["cuda14", "cuda13", "cuda12"]
+def test_core_helper_aliases_bound_to_prebuilt_core():
+ import prebuilt_core as _core
+ for name in (
+ "normalize_compute_cap",
+ "normalize_compute_caps",
+ "parse_cuda_visible_devices",
+ "supports_explicit_visible_device_matching",
+ "select_visible_gpu_rows",
+ "compatible_linux_runtime_lines",
+ "runtime_line_from_cuda_version",
+ ):
+ assert getattr(INSTALL_LLAMA_PREBUILT, name) is getattr(_core, name), name
# ===========================================================================
@@ -669,28 +520,6 @@ class TestCompatibleWindowsRuntimeLines:
assert compatible_windows_runtime_lines(host) == ["cuda14", "cuda13", "cuda12"]
-# ===========================================================================
-# H. runtime_line_from_cuda_version
-# ===========================================================================
-
-
-class TestRuntimeLineFromCudaVersion:
- def test_cuda_12(self):
- assert runtime_line_from_cuda_version("12.6") == "cuda12"
-
- def test_cuda_13(self):
- assert runtime_line_from_cuda_version("13.0") == "cuda13"
-
- def test_cuda_11(self):
- assert runtime_line_from_cuda_version("11.8") is None
-
- def test_none(self):
- assert runtime_line_from_cuda_version(None) is None
-
- def test_empty(self):
- assert runtime_line_from_cuda_version("") is None
-
-
# ===========================================================================
# I. apply_approved_hashes
# ===========================================================================
diff --git a/tests/studio/install/test_setup_whisper_status.py b/tests/studio/install/test_setup_whisper_status.py
new file mode 100644
index 00000000000..fd3bd825079
--- /dev/null
+++ b/tests/studio/install/test_setup_whisper_status.py
@@ -0,0 +1,29 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+"""Contract checks for actionable whisper prebuilt setup outcomes."""
+
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[3]
+
+
+def test_shell_setup_distinguishes_release_skew_from_install_failure():
+ script = (ROOT / "studio" / "setup.sh").read_text(encoding = "utf-8")
+ assert 'if [ "$_WHISPER_STATUS" -eq 2 ]' in script
+ assert "installed llama.cpp ${_WHISPER_INSTALLED_TAG:-unknown}" in script
+ assert "whisper requires ${_WHISPER_REQUIRED_TAG:-unknown}" in script
+ assert "prebuilt install failed" in script
+ assert "retry setup or inspect verbose output" in script
+ assert "curated whisper.cpp dictation is unavailable" in script
+ assert "browser and Transformers dictation remain available" in script
+
+
+def test_powershell_setup_distinguishes_release_skew_from_install_failure():
+ script = (ROOT / "studio" / "setup.ps1").read_text(encoding = "utf-8")
+ assert "elseif ($whisperExit -eq 2)" in script
+ assert "installed llama.cpp $installedWhisperLlamaTag" in script
+ assert "whisper requires $requiredWhisperLlamaTag" in script
+ assert "prebuilt install failed" in script
+ assert "retry setup or inspect verbose output" in script
+ assert "curated whisper.cpp dictation is unavailable" in script
+ assert "browser and Transformers dictation remain available" in script
diff --git a/tests/studio/playwright_extra_ui.py b/tests/studio/playwright_extra_ui.py
index dde6c5d6351..0da028a28c3 100644
--- a/tests/studio/playwright_extra_ui.py
+++ b/tests/studio/playwright_extra_ui.py
@@ -482,6 +482,14 @@ with sync_playwright() as p:
step("Settings dialog: cycle through tabs")
page.goto(f"{BASE}/chat")
composer.wait_for(state = "visible", timeout = 60_000)
+ dictate = page.get_by_role("button", name = "Dictate").first
+ if dictate.count() == 0:
+ fail("Chat Dictate button not found")
+ elif dictate.get_attribute("type") != "button":
+ fail("Chat Dictate control must use type=button, not submit the composer")
+ else:
+ info("OK Chat Dictate control is type=button")
+
page.keyboard.press("Control+,")
page.wait_for_timeout(800)
settings = page.get_by_role("dialog").first
@@ -501,6 +509,7 @@ with sync_playwright() as p:
"Appearance",
"Chat",
"Developer",
+ "Voice",
"About",
)
seen_tabs = []
@@ -528,6 +537,39 @@ with sync_playwright() as p:
soft_fail(f"Settings tab '{tab_name}' body suspiciously short: {body_text}")
except Exception as exc:
soft_fail(f"Settings tab '{tab_name}' click failed: {exc!r}")
+ step("Voice model picker: real mouse-wheel scrolling")
+ voice_tab = page.get_by_role(
+ "button", name = re.compile(r"^\s*Voice(?:\s+New)?\s*$", re.I)
+ ).first
+ if voice_tab.count() == 0:
+ fail("Voice settings tab not found")
+ else:
+ voice_tab.click()
+ page.get_by_label("Dictation engine").click()
+ page.get_by_role("option", name = "Local transcription").click()
+ page.get_by_label("Speech recognition model").click()
+ page.get_by_placeholder("Search model").fill("whisper")
+ results = page.get_by_test_id("stt-model-results")
+ try:
+ page.wait_for_function(
+ """() => {
+ const node = document.querySelector('[data-testid="stt-model-results"]');
+ return !!node && node.scrollHeight > node.clientHeight;
+ }""",
+ timeout = 30_000,
+ )
+ results.hover()
+ page.mouse.wheel(0, 700)
+ page.wait_for_function(
+ """() => {
+ const node = document.querySelector('[data-testid="stt-model-results"]');
+ return !!node && node.scrollTop > 0;
+ }""",
+ timeout = 5_000,
+ )
+ info("OK Voice model picker mouse wheel changed scrollTop")
+ except Exception as exc:
+ fail(f"Voice model picker did not wheel-scroll: {exc!r}")
shoot("10-settings-tabs-visited")
page.keyboard.press("Escape")
page.wait_for_timeout(300)
diff --git a/tests/test_studio_install_workspace_guard.py b/tests/test_studio_install_workspace_guard.py
index ea5b34672c2..18678a9b4a3 100644
--- a/tests/test_studio_install_workspace_guard.py
+++ b/tests/test_studio_install_workspace_guard.py
@@ -254,6 +254,14 @@ def test_setup_ps1_prebuilt_llama_cpp_has_ownership_guard():
), "Assert-StudioOwnedOrAbsent must precede the install_llama_prebuilt.py call"
+def test_setup_ps1_adopts_existing_whisper_prebuilt_marker():
+ text = SETUP_PS1.read_text(encoding = "utf-8")
+ helper_start = text.index("function Test-StudioOwnedAdoptable")
+ helper_end = text.index("function Assert-StudioOwnedOrAbsent", helper_start)
+ helper = text[helper_start:helper_end]
+ assert "UNSLOTH_WHISPER_PREBUILT_INFO.json" in helper
+
+
def test_env_mode_passes_when_venv_marker_present(tmp_path):
"""install.sh env-mode guard must accept the in-VENV .unsloth-studio-owned marker as a sentinel."""
studio_home = tmp_path / "ws"