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: update the audio.cpp runtime from the in-app update (#12893)

Etherlfed9f4d332f6
diff --git a/studio/backend/core/inference/audio_cpp_server.py b/studio/backend/core/inference/audio_cpp_server.py
index a643fe1ed81..a14b68c8580 100644
--- a/studio/backend/core/inference/audio_cpp_server.py
+++ b/studio/backend/core/inference/audio_cpp_server.py
@@ -188,8 +188,14 @@ def binary_has_espeak(binary: Optional[str]) -> bool:
return any((bin_dir / name).exists() for name in _ESPEAK_DATA_NAMES)
+# Set by utils.audio_cpp_update while it replaces the managed tree.
+UPDATE_IN_PROGRESS = threading.Event()
+
+
def model_runtime_problem(model: AudioCppModel, binary: Optional[str] = None) -> Optional[str]:
"""Why ``model`` cannot run on the installed runtime, or None when it can."""
+ if UPDATE_IN_PROGRESS.is_set():
+ return "The audio runtime is being updated. Try again in a moment."
if model.unsupported:
return model.unsupported
binary = binary if binary is not None else find_audio_cpp_server_binary()
diff --git a/studio/backend/core/inference/model_slots.py b/studio/backend/core/inference/model_slots.py
index 29776937246..c1f85a103de 100644
--- a/studio/backend/core/inference/model_slots.py
+++ b/studio/backend/core/inference/model_slots.py
@@ -289,6 +289,30 @@ def unload_idle() -> int:
return len(evict_these(idle))
+def audio_cpp_model_names(orchestrator) -> list[str]:
+ """The audio.cpp models an orchestrator holds or is loading: their servers run from the managed tree."""
+ from core.inference.audio_cpp_models import AUDIO_CPP_AUDIO_TYPES, looks_like_audio_cpp
+
+ # Snapshot the loads first: one that publishes between the two reads moves from loading to held.
+ loading = list(getattr(orchestrator, "loading_models", None) or ())
+ held = [
+ name
+ for name, entry in list((getattr(orchestrator, "models", None) or {}).items())
+ if isinstance(entry, dict) and entry.get("audio_type") in AUDIO_CPP_AUDIO_TYPES
+ ]
+ return held + [name for name in loading if name not in held and looks_like_audio_cpp(name)]
+
+
+def unload_audio_cpp_slots(strict: bool = False) -> int:
+ """Drop every slot holding or loading an audio.cpp model, for the audio.cpp runtime swap."""
+ doomed = [slot for slot in list(slots) if audio_cpp_model_names(slot.orchestrator)]
+ for slot in doomed:
+ # drop() keeps the loading marker, so a load still ahead of its spawn would start a worker after it.
+ for name in list(slot.orchestrator.loading_models):
+ slot.orchestrator.cancel_load(name)
+ return _drop_where(lambda slot, filling: any(slot is held for held in doomed), strict)
+
+
def unload_llama_slots(strict: bool = False) -> int:
"""Drop every slot running or starting a llama-server, a GGUF load still filling one included."""
return _drop_where(
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.py
index 391d7e98e2d..72b6fdab7fb 100644
--- a/studio/backend/core/inference/orchestrator.py
+++ b/studio/backend/core/inference/orchestrator.py
@@ -2051,6 +2051,13 @@ class InferenceOrchestrator:
self.loading_models.discard(model_name)
logger.info("Load cancelled before worker start: %s", model_name)
return False
+ # The audio.cpp update sets this before it scans loading_models, so a load registering after
+ # the scan is refused here rather than started from the tree being replaced.
+ if getattr(config, "audio_cpp", None) is not None:
+ from core.inference.audio_cpp_server import UPDATE_IN_PROGRESS
+ if UPDATE_IN_PROGRESS.is_set():
+ self.loading_models.discard(model_name)
+ raise RuntimeError("The audio runtime is being updated. Try again in a moment.")
try:
needed_major = "5" if needs_transformers_5(model_name) else "4"
diff --git a/studio/backend/core/inference/stt_audiocpp_sidecar.py b/studio/backend/core/inference/stt_audiocpp_sidecar.py
index 111864367cd..e02699077d1 100644
--- a/studio/backend/core/inference/stt_audiocpp_sidecar.py
+++ b/studio/backend/core/inference/stt_audiocpp_sidecar.py
@@ -716,12 +716,7 @@ class AudioCppSttSidecar:
@contextmanager
def update_maintenance(self) -> Iterator[bool]:
- """Block new loads while the managed audio.cpp tree is replaced.
-
- The runtime is pinned in source and replaced only by setup, which runs while Studio is
- stopped, so nothing calls this today. It is kept so an in-app updater can reuse the
- whisper.cpp update flow unchanged.
- """
+ """Block new loads while utils.audio_cpp_update replaces the managed audio.cpp tree."""
self._update_in_progress = True
try:
with self._lock:
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index ca575bc0756..d4dd6dcb377 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -24672,15 +24672,6 @@ _AUDIO_CPP_RUNTIME_MISSING = {
}
-def _audio_cpp_release_ladder() -> list:
- studio_dir = str(Path(__file__).resolve().parents[2])
- if studio_dir not in sys.path:
- sys.path.insert(0, studio_dir)
- import install_audio_cpp_prebuilt
-
- return install_audio_cpp_prebuilt._release_ladder()
-
-
def _audio_cpp_runtime_status() -> dict:
try:
from core.inference import audio_cpp_server
@@ -24702,26 +24693,11 @@ def _audio_cpp_runtime_status() -> dict:
except Exception as exc: # noqa: BLE001 - a status poll must not fail on a probe
logger.debug("audio.cpp runtime probe failed: %s", exc)
return dict(_AUDIO_CPP_RUNTIME_MISSING)
- # only the managed tree is updatable; setup skips it under any of these, whatever the path.
- setup_skips = (
- os.environ.get("AUDIOCPP_SERVER_PATH")
- or os.environ.get("UNSLOTH_AUDIO_CPP_PATH")
- or os.environ.get("UNSLOTH_SKIP_AUDIO_CPP_INSTALL") == "1"
- )
try:
- managed_dir = audio_cpp_server.managed_audio_cpp_dir().resolve()
- managed = not setup_skips and (
- Path(binary).resolve().is_relative_to(managed_dir)
- and (managed_dir / ".unsloth-studio-owned").is_file()
- )
- ladder = _audio_cpp_release_ladder() if managed else []
+ from utils import audio_cpp_update
+ status.update(audio_cpp_update.release_status(binary, record))
except Exception as exc: # noqa: BLE001 - cannot tell is not outdated
logger.debug("audio.cpp release lookup failed: %s", exc)
- ladder = []
- # a None tag tracks the latest release, so an installed release cannot be compared.
- if status["release_tag"] and ladder and all(tag for _, tag in ladder):
- status["expected_tag"] = ladder[0][1]
- status["outdated"] = (record.get("published_repo"), release_tag) not in ladder
return status
diff --git a/studio/backend/routes/llama.py b/studio/backend/routes/llama.py
index 89ccfe1014b..45902d8e426 100644
--- a/studio/backend/routes/llama.py
+++ b/studio/backend/routes/llama.py
@@ -13,7 +13,8 @@ utils.llama_cpp_update. Both fail open so the UI never blocks on a missing marke
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.
+keep working unchanged. audio.cpp is the third chained phase, offered when the managed runtime is not the release
+this Studio pins, with its own sub-status.
"""
from __future__ import annotations
@@ -79,6 +80,10 @@ class WhisperSubStatus(BaseModel):
)
+class AudioCppSubStatus(WhisperSubStatus):
+ """The audio.cpp phase inside the llama update item; latest_tag is the release this Studio pins."""
+
+
class LlamaUpdateStatusResponse(BaseModel):
supported: bool = Field(
False,
@@ -88,13 +93,13 @@ class LlamaUpdateStatusResponse(BaseModel):
False,
description = (
"True when an update would do something: llama.cpp is behind OR the "
- "whisper piggyback is behind."
+ "whisper piggyback is behind OR audio.cpp is not the pinned release."
),
)
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(
+ update_component: Optional[Literal["llama", "whisper", "audio"]] = Field(
None,
description = "Component whose versions the combined update banner should display.",
)
@@ -129,6 +134,9 @@ class LlamaUpdateStatusResponse(BaseModel):
whisper: Optional[WhisperSubStatus] = Field(
None, description = "Whisper piggyback sub-status; None when the probe is unavailable."
)
+ audio: Optional[AudioCppSubStatus] = Field(
+ None, description = "audio.cpp phase sub-status; None when the probe is unavailable."
+ )
job: LlamaUpdateJob = Field(default_factory = LlamaUpdateJob)
diff --git a/studio/backend/tests/test_audio_cpp_runtime_status.py b/studio/backend/tests/test_audio_cpp_runtime_status.py
index d2546fd7ccd..89e4ea01cc8 100644
--- a/studio/backend/tests/test_audio_cpp_runtime_status.py
+++ b/studio/backend/tests/test_audio_cpp_runtime_status.py
@@ -10,6 +10,7 @@ import pytest
from core.inference import audio_cpp_server
from routes import inference
+from utils import audio_cpp_update
def _patch(
@@ -103,7 +104,7 @@ def _managed(
(tmp_path / ".unsloth-studio-owned").touch()
_patch(monkeypatch, binary = str(tmp_path / "audiocpp_server"), record = record, espeak = True)
monkeypatch.setattr(audio_cpp_server, "managed_audio_cpp_dir", lambda: tmp_path)
- monkeypatch.setattr(inference, "_audio_cpp_release_ladder", lambda: ladder)
+ monkeypatch.setattr(audio_cpp_update, "_release_ladder", lambda: ladder)
def test_managed_install_of_the_pinned_release_is_current(monkeypatch, tmp_path):
@@ -221,7 +222,7 @@ def test_release_lookup_error_is_not_outdated(monkeypatch, tmp_path):
def boom():
raise ImportError("installer missing")
- monkeypatch.setattr(inference, "_audio_cpp_release_ladder", boom)
+ monkeypatch.setattr(audio_cpp_update, "_release_ladder", boom)
status = inference._audio_cpp_runtime_status()
assert status["available"] is True and status["outdated"] is False
@@ -231,7 +232,7 @@ def test_release_ladder_comes_from_the_installer(monkeypatch):
monkeypatch.delenv("UNSLOTH_AUDIO_CPP_TAG", raising = False)
import install_audio_cpp_prebuilt as installer
- ladder = inference._audio_cpp_release_ladder()
+ ladder = audio_cpp_update._release_ladder()
assert ladder[0] == (installer.DEFAULT_REPO, installer.DEFAULT_TAG)
assert (installer.UPSTREAM_FALLBACK_REPO, installer.UPSTREAM_FALLBACK_TAG) in ladder
diff --git a/studio/backend/tests/test_audio_cpp_update.py b/studio/backend/tests/test_audio_cpp_update.py
new file mode 100644
index 00000000000..3085b5107c0
--- /dev/null
+++ b/studio/backend/tests/test_audio_cpp_update.py
@@ -0,0 +1,455 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The audio.cpp phase of the combined in-app update: what it offers, and how it swaps the runtime."""
+
+from __future__ import annotations
+
+import json
+import threading
+from contextlib import contextmanager
+from types import SimpleNamespace
+
+import pytest
+
+from core.inference import audio_cpp_server, model_slots
+from core.inference.audio_cpp_models import AUDIO_CPP_MUSIC_AUDIO_TYPE, AUDIO_CPP_TTS_AUDIO_TYPE
+from utils import audio_cpp_update as aupd
+from utils.prebuilt import update_flow
+
+# A Studio pinned one release past the installed one, so the tests do not depend on the real pin.
+_LADDER = [("unslothai/audio.cpp", "v0.9.1-unsloth.1"), ("0xShug0/audio.cpp", "v0.9.1")]
+_real_unload = aupd._unload_audio_cpp_models
+_SETUP_SKIPS = ("AUDIOCPP_SERVER_PATH", "UNSLOTH_AUDIO_CPP_PATH", "UNSLOTH_SKIP_AUDIO_CPP_INSTALL")
+
+
+def _write_record(tree, **fields):
+ record = {
+ "published_repo": "unslothai/audio.cpp",
+ "release_tag": "v0.9.0-unsloth.1",
+ "accelerator": "cpu",
+ "accelerator_request": "cpu",
+ **fields,
+ }
+ (tree / audio_cpp_server.INSTALL_RECORD).write_text(json.dumps(record))
+
+
+def managed(monkeypatch, tmp_path):
+ """A Studio-managed install of v0.9.0-unsloth.1 under a Studio that pins v0.9.1-unsloth.1."""
+ for name in (*_SETUP_SKIPS, "UNSLOTH_DISABLE_UPDATE_CHECK"):
+ monkeypatch.delenv(name, raising = False)
+ tree = tmp_path / "audio.cpp"
+ tree.mkdir()
+ (tree / ".unsloth-studio-owned").touch()
+ binary = tree / "audiocpp_server"
+ binary.write_text("stub")
+ _write_record(tree)
+ script = tmp_path / "install_audio_cpp_prebuilt.py"
+ script.write_text("stub")
+ monkeypatch.setattr(audio_cpp_server, "managed_audio_cpp_dir", lambda: tree)
+ monkeypatch.setattr(audio_cpp_server, "find_audio_cpp_server_binary", lambda: str(binary))
+ monkeypatch.setattr(aupd, "_release_ladder", lambda: list(_LADDER))
+ monkeypatch.setattr(aupd, "_installer_script", lambda: script)
+ return SimpleNamespace(tree = tree, binary = binary, script = script)
+
+
+# --- plan ---
+
+
+def test_an_old_managed_runtime_is_offered_the_pinned_release(managed):
+ plan = aupd.chained_phase_plan()
+ assert plan["update_available"] is True and plan["skip_reason"] is None
+ assert plan["status"] == {
+ "installed_tag": "v0.9.0-unsloth.1",
+ "latest_tag": "v0.9.1-unsloth.1",
+ "update_size_bytes": None,
+ }
+ assert plan["phase"] == {
+ "install_dir": managed.tree,
+ "script": managed.script,
+ "accelerator": "cpu",
+ "from_tag": "v0.9.0-unsloth.1",
+ "to_tag": "v0.9.1-unsloth.1",
+ }
+
+
+def test_an_automatic_install_keeps_detecting_the_host(managed):
+ _write_record(managed.tree, accelerator = "cuda", accelerator_request = "auto")
+ assert aupd.chained_phase_plan()["phase"]["accelerator"] == "auto"
+
+
[email protected]("name", _SETUP_SKIPS)
+def test_a_runtime_setup_skips_is_unmanaged(managed, monkeypatch, name):
+ monkeypatch.setenv(name, "1" if name == "UNSLOTH_SKIP_AUDIO_CPP_INSTALL" else "/elsewhere")
+ plan = aupd.chained_phase_plan()
+ assert plan["update_available"] is False and plan["skip_reason"] == "unmanaged"
+
+
+def test_a_tree_without_the_ownership_marker_is_unmanaged(managed):
+ (managed.tree / ".unsloth-studio-owned").unlink()
+ assert aupd.chained_phase_plan()["skip_reason"] == "unmanaged"
+
+
+def test_a_binary_outside_the_managed_tree_is_unmanaged(managed, monkeypatch, tmp_path):
+ custom = tmp_path / "custom" / "audiocpp_server"
+ custom.parent.mkdir()
+ custom.write_text("stub")
+ monkeypatch.setattr(audio_cpp_server, "find_audio_cpp_server_binary", lambda: str(custom))
+ assert aupd.chained_phase_plan()["skip_reason"] == "unmanaged"
+
+
+def test_no_runtime_is_not_installed(managed, monkeypatch):
+ monkeypatch.setattr(audio_cpp_server, "find_audio_cpp_server_binary", lambda: None)
+ plan = aupd.chained_phase_plan()
+ assert plan["skip_reason"] == "not_installed" and plan["status"] is None
+
+
[email protected]("repo, tag", _LADDER)
+def test_either_rung_is_up_to_date(managed, repo, tag):
+ _write_record(managed.tree, published_repo = repo, release_tag = tag)
+ plan = aupd.chained_phase_plan()
+ assert plan["update_available"] is False and plan["skip_reason"] == "up_to_date"
+
+
+def test_a_latest_tracking_ladder_cannot_compare(managed, monkeypatch):
+ monkeypatch.setattr(aupd, "_release_ladder", lambda: [("unslothai/audio.cpp", None)])
+ assert aupd.chained_phase_plan()["skip_reason"] == "tracks_latest"
+
+
+def test_disabled_update_checks_skip_the_offer(managed, monkeypatch):
+ # Without this skip the union would show a card that start_update refuses.
+ monkeypatch.setenv("UNSLOTH_DISABLE_UPDATE_CHECK", "1")
+ assert aupd.chained_phase_plan()["skip_reason"] == "update_checks_disabled"
+
+
+def test_a_host_no_pinned_bundle_covers_has_no_prebuilt(managed, monkeypatch):
+ installer = aupd._installer()
+ pins = {
+ repo: {tag: {f"audio-{tag}-bin-windows-x64-cpu.zip": "0" * 64}} for repo, tag in _LADDER
+ }
+ monkeypatch.setattr(installer, "load_pins", lambda path = None: pins)
+ monkeypatch.setattr(aupd.platform, "system", lambda: "Linux")
+ monkeypatch.setattr(aupd.platform, "machine", lambda: "x86_64")
+ assert aupd.chained_phase_plan()["skip_reason"] == "no_prebuilt"
+ # The same pins cover a Windows host.
+ monkeypatch.setattr(aupd.platform, "system", lambda: "Windows")
+ assert aupd.chained_phase_plan()["update_available"] is True
+
+
[email protected]("request_, offered", [("vulkan", False), ("auto", True)])
+def test_an_explicit_accelerator_is_not_offered_the_cpu_bundle(
+ managed, monkeypatch, request_, offered
+):
+ # The installer never downgrades an explicit request, so a CPU-only release cannot satisfy it.
+ installer = aupd._installer()
+ pins = {
+ repo: {tag: {f"audio-{tag}-bin-ubuntu-arm64-cpu.tar.gz": "0" * 64}} for repo, tag in _LADDER
+ }
+ monkeypatch.setattr(installer, "load_pins", lambda path = None: pins)
+ monkeypatch.setattr(aupd.platform, "system", lambda: "Linux")
+ monkeypatch.setattr(aupd.platform, "machine", lambda: "aarch64")
+ _write_record(managed.tree, accelerator = "vulkan", accelerator_request = request_)
+ plan = aupd.chained_phase_plan()
+ assert plan["update_available"] is offered
+ assert plan["skip_reason"] == (None if offered else "no_prebuilt")
+
+
+def test_a_missing_installer_skips_the_offer(managed, monkeypatch):
+ monkeypatch.setattr(aupd, "_installer_script", lambda: None)
+ assert aupd.chained_phase_plan()["skip_reason"] == "installer_missing"
+
+
+def test_a_probe_that_raises_is_a_skip(managed, monkeypatch):
+ def boom():
+ raise OSError("unreadable")
+
+ monkeypatch.setattr(aupd, "_release_ladder", boom)
+ plan = aupd.chained_phase_plan()
+ assert plan["update_available"] is False and plan["skip_reason"] == "unavailable"
+
+
+def test_the_pinned_ladder_comes_from_the_installer(monkeypatch):
+ monkeypatch.delenv("UNSLOTH_AUDIO_CPP_REPO", raising = False)
+ monkeypatch.delenv("UNSLOTH_AUDIO_CPP_TAG", raising = False)
+ installer = aupd._installer()
+ assert aupd._release_ladder()[0] == (installer.DEFAULT_REPO, installer.DEFAULT_TAG)
+
+
+# --- run ---
+
+
+class _Sidecar:
+ def __init__(self, events):
+ self.events = events
+
+ @contextmanager
+ def update_maintenance(self):
+ self.events.append("sidecar:enter")
+ try:
+ yield False
+ finally:
+ self.events.append("sidecar:exit")
+
+
+def run_env(managed, monkeypatch):
+ """The run path with the sidecar, slot unload and installer recorded."""
+ from core.inference import stt_audiocpp_sidecar
+
+ events: list = []
+ calls: dict = {}
+ monkeypatch.setattr(stt_audiocpp_sidecar, "get_audio_cpp_stt_sidecar", lambda: _Sidecar(events))
+ monkeypatch.setattr(aupd, "_unload_audio_cpp_models", lambda: events.append("unload") or False)
+
+ def _installer(new_tag = "v0.9.1-unsloth.1", error = None):
+ def _stream(cmd, env, *, set_progress, timeout_seconds):
+ events.append("install")
+ calls.update(cmd = cmd, env = env, flag = audio_cpp_server.UPDATE_IN_PROGRESS.is_set())
+ if error is not None:
+ raise error
+ set_progress(0.5)
+ _write_record(managed.tree, release_tag = new_tag)
+
+ monkeypatch.setattr(update_flow, "stream_installer", _stream)
+
+ _installer()
+ phase = aupd.chained_phase_plan()["phase"]
+ return SimpleNamespace(events = events, calls = calls, phase = phase, installer = _installer)
+
+
+def test_the_runtime_is_swapped_while_no_audio_cpp_server_can_start(run_env):
+ result = aupd.run_chained_phase(run_env.phase, lambda fraction: None)
+ assert run_env.events == ["sidecar:enter", "unload", "install", "sidecar:exit"]
+ assert run_env.calls["flag"] is True
+ assert not audio_cpp_server.UPDATE_IN_PROGRESS.is_set()
+ assert result == {
+ "to_tag": "v0.9.1-unsloth.1",
+ "reload_required": False,
+ "message": "Updated audio.cpp to v0.9.1-unsloth.1.",
+ }
+
+
+def test_the_installer_gets_the_managed_dir_and_recorded_accelerator(run_env, managed):
+ aupd.run_chained_phase(run_env.phase, lambda fraction: None)
+ cmd = run_env.calls["cmd"]
+ assert cmd[1:] == [
+ str(managed.script),
+ "--install-dir",
+ str(managed.tree),
+ "--accelerator",
+ "cpu",
+ ]
+ assert run_env.calls["env"]["UNSLOTH_PROGRESS_PERCENT_STEP"] == "5"
+
+
+def test_an_unloaded_model_asks_for_a_reload(run_env, monkeypatch):
+ monkeypatch.setattr(aupd, "_unload_audio_cpp_models", lambda: True)
+ result = aupd.run_chained_phase(run_env.phase, lambda fraction: None)
+ assert result["reload_required"] is True
+ assert (
+ result["message"] == "Updated audio.cpp to v0.9.1-unsloth.1. Reload your model to use it."
+ )
+
+
+def test_the_update_flag_clears_when_the_install_fails(run_env):
+ run_env.installer(error = RuntimeError("installer timed out after 1800s"))
+ with pytest.raises(RuntimeError, match = "timed out"):
+ aupd.run_chained_phase(run_env.phase, lambda fraction: None)
+ assert not audio_cpp_server.UPDATE_IN_PROGRESS.is_set()
+ assert run_env.events[-1] == "sidecar:exit"
+
+
+def test_new_loads_are_refused_while_the_runtime_is_replaced():
+ audio_cpp_server.UPDATE_IN_PROGRESS.set()
+ try:
+ problem = audio_cpp_server.model_runtime_problem(SimpleNamespace(unsupported = None))
+ finally:
+ audio_cpp_server.UPDATE_IN_PROGRESS.clear()
+ assert problem == "The audio runtime is being updated. Try again in a moment."
+
+
+def test_a_load_registering_after_the_unload_scan_is_refused():
+ # Preflight can pass just before the flag is set; the registration is what the scan races.
+ from core.inference.orchestrator import InferenceOrchestrator
+
+ orchestrator = InferenceOrchestrator.__new__(InferenceOrchestrator)
+ orchestrator.loading_models = set()
+ orchestrator._managed_engine = None
+ config = SimpleNamespace(identifier = "kokoro", audio_cpp = object())
+ audio_cpp_server.UPDATE_IN_PROGRESS.set()
+ try:
+ with pytest.raises(RuntimeError, match = "being updated"):
+ orchestrator.load_model(config)
+ finally:
+ audio_cpp_server.UPDATE_IN_PROGRESS.clear()
+ assert orchestrator.loading_models == set()
+
+
+def test_a_kept_tree_is_not_reported_as_updated(run_env):
+ # Exit 0 also means the release lookup could not answer and the intact tree was kept.
+ run_env.installer(new_tag = "v0.9.0-unsloth.1")
+ result = aupd.run_chained_phase(run_env.phase, lambda fraction: None)
+ assert result["message"] == (
+ "audio.cpp could not be updated right now, so the existing v0.9.0-unsloth.1 "
+ "install was kept. Try again later."
+ )
+
+
+def test_a_kept_tree_still_asks_for_a_reload_after_an_unload(run_env, monkeypatch):
+ monkeypatch.setattr(aupd, "_unload_audio_cpp_models", lambda: True)
+ run_env.installer(new_tag = "v0.9.0-unsloth.1")
+ result = aupd.run_chained_phase(run_env.phase, lambda fraction: None)
+ assert result["reload_required"] is True
+ assert result["message"].endswith("Try again later. Reload your model to use it.")
+
+
+def test_a_busy_install_says_the_runtime_is_in_use(run_env):
+ run_env.installer(error = update_flow.InstallerExit(3, "installer exited 3: error: busy"))
+ with pytest.raises(RuntimeError, match = "in use by another Unsloth Studio or setup run"):
+ aupd.run_chained_phase(run_env.phase, lambda fraction: None)
+
+
+def test_a_checksum_failure_reports_the_installer_verdict(run_env):
+ tail = (
+ "installer exited 1: audio.cpp: downloading audio-x.tar.gz\n"
+ " 50.0% (1 MiB/2 MiB)\n"
+ "error: audio-x.tar.gz: sha256 mismatch (expected aa, got bb)\n"
+ )
+ run_env.installer(error = update_flow.InstallerExit(1, tail))
+ with pytest.raises(RuntimeError) as info:
+ aupd.run_chained_phase(run_env.phase, lambda fraction: None)
+ assert str(info.value) == "audio-x.tar.gz: sha256 mismatch (expected aa, got bb)"
+
+
+def test_a_rate_limit_gets_token_advice(run_env, monkeypatch):
+ monkeypatch.delenv("GH_TOKEN", raising = False)
+ monkeypatch.delenv("GITHUB_TOKEN", raising = False)
+ tail = "installer exited 1: error: GitHub API is rate limiting release lookups\n"
+ run_env.installer(error = update_flow.InstallerExit(1, tail))
+ with pytest.raises(RuntimeError, match = "Set GH_TOKEN or GITHUB_TOKEN"):
+ aupd.run_chained_phase(run_env.phase, lambda fraction: None)
+
+
+def test_no_sidecar_coordination_fails_closed(run_env, monkeypatch):
+ from core.inference import stt_audiocpp_sidecar
+
+ def boom():
+ raise ImportError("sidecar unavailable")
+
+ monkeypatch.setattr(stt_audiocpp_sidecar, "get_audio_cpp_stt_sidecar", boom)
+ with pytest.raises(RuntimeError, match = "dictation sidecar"):
+ aupd.run_chained_phase(run_env.phase, lambda fraction: None)
+ assert "install" not in run_env.events
+ assert not audio_cpp_server.UPDATE_IN_PROGRESS.is_set()
+
+
+# --- unload ---
+
+
+class _Orchestrator:
+ def __init__(
+ self,
+ models = None,
+ loading = (),
+ ):
+ self.models = dict(models or {})
+ self.loading_models = set(loading)
+ self.unloaded: list = []
+
+ def unload_model(self, name):
+ self.unloaded.append(name)
+ self.models.pop(name, None)
+ self.loading_models.discard(name)
+ return True
+
+ def cancel_load(self, name):
+ self.loading_models.discard(name)
+ return True
+
+
+def slots(monkeypatch):
+ from routes import inference
+
+ dropped: list = []
+ state = SimpleNamespace(main = None, dropped = dropped)
+ monkeypatch.setattr(inference, "_peek_inference_backend", lambda: state.main)
+ monkeypatch.setattr(model_slots, "slots", [])
+ monkeypatch.setattr(model_slots, "stuck", [])
+ monkeypatch.setattr(model_slots, "drop", lambda slot: dropped.append(slot))
+ return state
+
+
+def test_a_main_slot_audio_cpp_model_is_unloaded(slots):
+ slots.main = _Orchestrator(
+ {"kokoro": {"audio_type": AUDIO_CPP_TTS_AUDIO_TYPE, "is_audio": True}}
+ )
+ assert aupd._unload_audio_cpp_models() is True
+ assert slots.main.unloaded == ["kokoro"]
+
+
+def test_a_failed_unload_stops_the_update_before_the_install(run_env, slots, monkeypatch):
+ # The run_env fixture stubs the unload; put the real one back to drive the orchestrator.
+ monkeypatch.setattr(aupd, "_unload_audio_cpp_models", _real_unload)
+ slots.main = _Orchestrator({"kokoro": {"audio_type": AUDIO_CPP_TTS_AUDIO_TYPE}})
+ slots.main.unload_model = lambda name: False
+ with pytest.raises(RuntimeError, match = "kokoro did not unload") as info:
+ aupd.run_chained_phase(run_env.phase, lambda fraction: None)
+ assert info.value.reload_required is True
+ assert "install" not in run_env.events
+
+
+def test_a_main_slot_chat_model_is_left_alone(slots):
+ slots.main = _Orchestrator({"qwen": {"audio_type": None}})
+ assert aupd._unload_audio_cpp_models() is False
+ assert slots.main.unloaded == []
+
+
+def test_an_audio_cpp_load_in_flight_is_cancelled(slots, monkeypatch):
+ from core.inference import audio_cpp_models
+
+ monkeypatch.setattr(audio_cpp_models, "looks_like_audio_cpp", lambda name: name == "kokoro")
+ slots.main = _Orchestrator(loading = {"kokoro"})
+ assert aupd._unload_audio_cpp_models() is True
+ assert slots.main.unloaded == ["kokoro"]
+
+
+def test_a_load_that_publishes_during_the_scan_is_still_found(monkeypatch):
+ from core.inference import audio_cpp_models
+
+ monkeypatch.setattr(audio_cpp_models, "looks_like_audio_cpp", lambda name: name == "kokoro")
+
+ class _Publishing:
+ loading_models = {"kokoro"}
+
+ @property
+ def models(self):
+ # The load finishes right after this read: it leaves loading_models for models.
+ self.loading_models = set()
+ return {}
+
+ assert model_slots.audio_cpp_model_names(_Publishing()) == ["kokoro"]
+
+
+def test_a_kept_slot_load_is_cancelled_before_its_slot_is_dropped(slots, monkeypatch):
+ from core.inference import audio_cpp_models
+
+ monkeypatch.setattr(audio_cpp_models, "looks_like_audio_cpp", lambda name: name == "kokoro")
+ chat = SimpleNamespace(orchestrator = _Orchestrator({"qwen": {"audio_type": None}}))
+ loading = SimpleNamespace(orchestrator = _Orchestrator(loading = {"kokoro"}))
+ model_slots.slots[:] = [chat, loading]
+ assert aupd._unload_audio_cpp_models() is True
+ # A marker left behind would let the load spawn its worker after the drop.
+ assert loading.orchestrator.loading_models == set()
+ assert slots.dropped == [loading]
+
+
+def test_a_kept_audio_cpp_slot_is_dropped(slots):
+ music = SimpleNamespace(
+ orchestrator = _Orchestrator({"ace": {"audio_type": AUDIO_CPP_MUSIC_AUDIO_TYPE}})
+ )
+ chat = SimpleNamespace(orchestrator = _Orchestrator({"qwen": {"audio_type": None}}))
+ model_slots.slots[:] = [music, chat]
+ assert aupd._unload_audio_cpp_models() is True
+ assert slots.dropped == [music]
diff --git a/studio/backend/tests/test_combined_update.py b/studio/backend/tests/test_combined_update.py
index dd38308f707..3aa88c61ba2 100644
--- a/studio/backend/tests/test_combined_update.py
+++ b/studio/backend/tests/test_combined_update.py
@@ -23,6 +23,7 @@ _BACKEND = Path(__file__).resolve().parents[1]
if str(_BACKEND) not in sys.path:
sys.path.insert(0, str(_BACKEND))
+import utils.audio_cpp_update as aupd # noqa: E402
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
@@ -176,6 +177,17 @@ def _clean_state(monkeypatch, tmp_path):
# 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)
+ # A dev box may hold a real managed audio.cpp; tests that want the phase opt in with _setup_audio.
+ monkeypatch.setattr(
+ aupd,
+ "chained_phase_plan",
+ lambda: {
+ "status": None,
+ "update_available": False,
+ "skip_reason": "not_installed",
+ "phase": None,
+ },
+ )
yield
freshness.reset_caches()
wfresh.reset_caches()
@@ -240,6 +252,48 @@ def _patch_whisper_phase(
monkeypatch.setattr(wupd, "run_chained_phase", _run)
+_AUDIO_STATUS = {
+ "installed_tag": "v0.8.2-audio8-perf-hotfix-unsloth.1",
+ "latest_tag": "v0.9.0-unsloth.1",
+ "update_size_bytes": None,
+}
+
+
+def _setup_audio(
+ monkeypatch,
+ events,
+ *,
+ error = None,
+ reload_required = False,
+):
+ """An offered audio.cpp phase whose runs are recorded instead of installing."""
+ plans = []
+
+ def _plan():
+ plans.append("audio")
+ return {
+ "status": dict(_AUDIO_STATUS),
+ "update_available": True,
+ "skip_reason": None,
+ "phase": {"to_tag": "v0.9.0-unsloth.1"},
+ }
+
+ def _run(phase, set_progress):
+ events.append("audio")
+ if error is not None:
+ raise RuntimeError(error)
+ set_progress(0.5)
+ return {
+ "to_tag": "v0.9.0-unsloth.1",
+ "reload_required": reload_required,
+ "message": "Updated audio.cpp to v0.9.0-unsloth.1.",
+ }
+
+ monkeypatch.setattr(aupd, "chained_phase_plan", _plan)
+ monkeypatch.setattr(aupd, "run_chained_phase", _run)
+ return plans
+
+
def _wait_for_job():
deadline = time.time() + 10
while time.time() < deadline:
@@ -989,3 +1043,176 @@ def test_an_incompatible_release_that_slips_past_the_pre_flight_still_errors(mon
with pytest.raises(wupd._flow.InstallerExit):
wupd.run_chained_phase_after_llama(_slim_phase(), lambda _f: None)
+
+
+# --- audio.cpp: the third phase ---
+
+
+def test_status_union_audio_only_surfaces_update(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")
+ _setup_audio(monkeypatch, [])
+ st = upd.get_update_status(force_refresh = True)
+ assert LEGACY_STATUS_FIELDS <= set(st)
+ assert st["update_available"] is True
+ assert st["llama_update_available"] is False
+ assert st["update_component"] == "audio"
+ assert st["audio"] == {**_AUDIO_STATUS, "update_available": True, "skip_reason": None}
+ # The top-level version fields keep their llama meaning.
+ assert st["installed_tag"] == "b9518"
+
+
+def test_status_llama_keeps_the_card_name_over_audio(monkeypatch, tmp_path):
+ _setup_llama(monkeypatch, tmp_path)
+ _setup_audio(monkeypatch, [])
+ st = upd.get_update_status(force_refresh = True)
+ assert st["update_component"] == "llama"
+ assert st["audio"]["update_available"] is True
+
+
+def test_status_whisper_keeps_the_card_name_over_audio(monkeypatch, tmp_path):
+ _setup_llama(monkeypatch, tmp_path, installed = "b9518", latest = "b9518")
+ _setup_whisper(monkeypatch, tmp_path)
+ _setup_audio(monkeypatch, [])
+ assert upd.get_update_status(force_refresh = True)["update_component"] == "whisper"
+
+
+def test_status_survives_audio_probe_failure(monkeypatch, tmp_path):
+ _setup_llama(monkeypatch, tmp_path)
+
+ def _boom():
+ raise RuntimeError("probe exploded")
+
+ monkeypatch.setattr(aupd, "chained_phase_plan", _boom)
+ st = upd.get_update_status(force_refresh = True)
+ assert st["audio"] is None
+ assert st["update_available"] is True
+ assert st["update_component"] == "llama"
+
+
+def test_status_skipped_audio_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["update_component"] is None
+ assert st["audio"]["skip_reason"] == "not_installed"
+
+
+def test_apply_audio_only_runs_only_the_audio_phase(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")
+ events = []
+ _patch_llama_installer(monkeypatch, on_start = lambda cmd: events.append("llama"))
+ _patch_whisper_phase(monkeypatch, events)
+ _setup_audio(monkeypatch, events)
+
+ res = upd.start_update()
+ assert res["started"] is True, res
+ assert "audio.cpp" in res["job"]["message"]
+ job = _wait_for_job()
+ assert job["state"] == "success", job
+ assert events == ["audio"]
+ assert job["phases"]["llama"]["state"] == "skipped"
+ assert job["phases"]["whisper"]["state"] == "skipped"
+ assert job["phases"]["audio"]["state"] == "success"
+ assert job["phases"]["audio"]["to_tag"] == "v0.9.0-unsloth.1"
+ # The job-level to_tag stays the llama.cpp build, as for a whisper-only round.
+ assert job["to_tag"] is None
+ assert "Updated audio.cpp to v0.9.0-unsloth.1." in job["message"]
+ assert job["progress"] == 1.0
+
+
+def test_apply_runs_llama_then_whisper_then_audio(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)
+ _setup_audio(monkeypatch, events)
+
+ assert upd.start_update()["started"] is True
+ job = _wait_for_job()
+ assert job["state"] == "success", job
+ assert events == ["llama", "whisper", "audio"]
+ # The legacy to_tag still names the llama build.
+ assert job["to_tag"] == "b9518"
+
+
+def test_apply_llama_failure_aborts_audio(monkeypatch, tmp_path):
+ _setup_llama(monkeypatch, tmp_path)
+ events = []
+ _patch_llama_installer(monkeypatch, returncode = 2, lines = ["boom: disk full\n"])
+ _setup_audio(monkeypatch, events)
+
+ assert upd.start_update()["started"] is True
+ job = _wait_for_job()
+ assert job["state"] == "error", job
+ assert events == []
+ assert job["phases"]["audio"]["state"] == "skipped"
+ assert job["phases"]["audio"]["reason"] == "aborted"
+
+
+def test_apply_audio_failure_keeps_llama_partial_success(monkeypatch, tmp_path):
+ llama_dir = _setup_llama(monkeypatch, tmp_path)
+ events = []
+ _patch_llama_installer(
+ monkeypatch,
+ on_start = lambda cmd: (events.append("llama"), _write_llama_install(llama_dir, "b9518")),
+ )
+ _setup_audio(monkeypatch, events, error = "sha256 mismatch")
+
+ assert upd.start_update()["started"] is True
+ job = _wait_for_job()
+ assert job["state"] == "error", job
+ assert events == ["llama", "audio"]
+ assert "Updated llama.cpp to b9518." in job["message"]
+ assert "audio.cpp update failed." in job["message"]
+ assert "sha256 mismatch" in (job["error"] or "")
+ assert job["phases"]["llama"]["state"] == "success"
+ assert job["phases"]["audio"]["state"] == "error"
+
+
+def test_audio_unload_raises_the_job_reload_flag(monkeypatch, tmp_path):
+ # Unlike the dictation sidecars, an audio.cpp model in the main slot is a server model change.
+ _setup_llama(monkeypatch, tmp_path, installed = "b9518", latest = "b9518")
+ _setup_audio(monkeypatch, [], reload_required = True)
+ assert upd.start_update()["started"] is True
+ job = _wait_for_job()
+ assert job["state"] == "success", job
+ assert job["reload_required"] is True
+
+
+def test_backend_switch_never_plans_audio(monkeypatch, tmp_path):
+ plans = _setup_audio(monkeypatch, [])
+ monkeypatch.setattr(
+ upd,
+ "_plan_llama_phase",
+ lambda backend_request = None: {
+ "skip_reason": "already_selected",
+ "refusal": {
+ "started": False,
+ "reason": "already_selected",
+ "message": "llama.cpp is already set to cpu.",
+ },
+ },
+ )
+ monkeypatch.setattr(upd, "_repair_pairing_plan_or_empty", lambda *a, **k: {})
+ monkeypatch.setattr(upd, "_env_backend_override", lambda: None)
+ res = upd.start_backend_switch("cpu")
+ assert res["started"] is False
+ assert res["reason"] == "already_selected"
+ assert plans == []
+
+
+def test_update_checks_disabled_refuses_before_planning_audio(monkeypatch, tmp_path):
+ plans = _setup_audio(monkeypatch, [])
+ monkeypatch.setenv("UNSLOTH_DISABLE_UPDATE_CHECK", "1")
+ res = upd.start_update()
+ assert res["started"] is False
+ assert res["reason"] == "update_checks_disabled"
+ assert plans == []
diff --git a/studio/backend/utils/audio_cpp_update.py b/studio/backend/utils/audio_cpp_update.py
new file mode 100644
index 00000000000..80416a641e1
--- /dev/null
+++ b/studio/backend/utils/audio_cpp_update.py
@@ -0,0 +1,276 @@
+# 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 audio.cpp runtime update: the third phase of the combined llama.cpp update item (utils.llama_cpp_update chains run_chained_phase after the whisper phase). Unlike llama.cpp and whisper.cpp, audio.cpp is pinned in source: the target is the release install_audio_cpp_prebuilt.py would install for this Studio (its release ladder and sha256 pins), never GitHub's latest, so the status needs no network call. Only the Studio-managed tree is offered, the same predicate the Audio page notice reads. The mechanics (the streamed installer run, the chained job) live in utils.prebuilt.update_flow; this module keeps the audio.cpp policy."""
+
+from __future__ import annotations
+
+import os
+import platform
+import sys
+from pathlib import Path
+from typing import Optional
+
+import structlog
+
+from utils.prebuilt import update_flow as _flow
+from utils.update_status import update_checks_disabled
+
+logger = structlog.get_logger(__name__)
+
+_INSTALL_TIMEOUT_SECONDS = 1800
+# setup.sh / setup.ps1 leave the managed tree alone when any of these is set, so an update would not take effect.
+_SETUP_SKIP_VARS = ("AUDIOCPP_SERVER_PATH", "UNSLOTH_AUDIO_CPP_PATH")
+_EXIT_BUSY = 3
+
+
+class _AudioPhaseError(RuntimeError):
+ """An audio phase failed after possibly unloading audio.cpp models."""
+
+ def __init__(self, message: str, *, reload_required: bool):
+ super().__init__(message)
+ self.reload_required = reload_required
+
+
+def _installer():
+ studio_dir = str(Path(__file__).resolve().parents[2])
+ if studio_dir not in sys.path:
+ sys.path.insert(0, studio_dir)
+ import install_audio_cpp_prebuilt
+
+ return install_audio_cpp_prebuilt
+
+
+def _release_ladder() -> list:
+ return _installer()._release_ladder()
+
+
+def _installer_script() -> Optional[Path]:
+ return _flow.find_installer_script(
+ env_var = "UNSLOTH_AUDIO_CPP_INSTALLER", script_name = "install_audio_cpp_prebuilt.py"
+ )
+
+
+def _is_managed(binary: str) -> bool:
+ """Whether ``binary`` is the Studio-owned tree setup would replace."""
+ from core.inference import audio_cpp_server
+
+ if any(os.environ.get(name) for name in _SETUP_SKIP_VARS):
+ return False
+ if os.environ.get("UNSLOTH_SKIP_AUDIO_CPP_INSTALL") == "1":
+ return False
+ managed_dir = audio_cpp_server.managed_audio_cpp_dir().resolve()
+ return (
+ Path(binary).resolve().is_relative_to(managed_dir)
+ and (managed_dir / ".unsloth-studio-owned").is_file()
+ )
+
+
+def _tag(record: dict) -> Optional[str]:
+ tag = record.get("release_tag")
+ return tag if isinstance(tag, str) and tag else None
+
+
+def release_status(binary: str, record: dict) -> dict:
+ """``expected_tag`` and ``outdated`` for an installed runtime: the release this Studio would install, and whether the record names neither rung of the ladder. Raises when the ladder cannot be read; callers treat that as current."""
+ status = {"expected_tag": None, "outdated": False}
+ if _tag(record) is None or not _is_managed(binary):
+ return status
+ ladder = _release_ladder()
+ # a None tag tracks the latest release, so an installed release cannot be compared.
+ if ladder and all(tag for _, tag in ladder):
+ status["expected_tag"] = ladder[0][1]
+ status["outdated"] = (record.get("published_repo"), _tag(record)) not in ladder
+ return status
+
+
+def _host_has_prebuilt(
+ ladder: list,
+ accelerator: Optional[str],
+ explicit: Optional[str] = None,
+) -> bool:
+ """Whether any pinned rung publishes a bundle for this host. Offline: the pins list every asset name. A rung without pins (a release the user picked) can only be answered by the online lookup, so it counts as available. An explicit request is never downgraded to CPU by the installer, so only it is checked."""
+ installer = _installer()
+ pins = installer.load_pins()
+ accels = (explicit,) if explicit else tuple(dict.fromkeys((accelerator or "cpu", "cpu")))
+ for repo, tag in ladder:
+ names = list((pins.get(repo) or {}).get(tag) or {})
+ if not names:
+ return True
+ for accel in accels:
+ if installer.resolve_release_asset(
+ names,
+ system = platform.system(),
+ machine = platform.machine(),
+ accelerator = accel,
+ ):
+ return True
+ return False
+
+
+def _plan() -> dict:
+ from core.inference import audio_cpp_server
+
+ plan: dict = {"status": None, "update_available": False, "skip_reason": None, "phase": None}
+ binary = audio_cpp_server.find_audio_cpp_server_binary()
+ if binary is None:
+ plan["skip_reason"] = "not_installed"
+ return plan
+ record = audio_cpp_server.read_install_record(binary)
+ status = {"installed_tag": _tag(record), "latest_tag": None, "update_size_bytes": None}
+ plan["status"] = status
+ if not _is_managed(binary):
+ plan["skip_reason"] = "unmanaged"
+ return plan
+ ladder = _release_ladder()
+ if not ladder or not all(tag for _, tag in ladder):
+ plan["skip_reason"] = "tracks_latest"
+ return plan
+ status["latest_tag"] = ladder[0][1]
+ if (
+ status["installed_tag"] is None
+ or (
+ record.get("published_repo"),
+ status["installed_tag"],
+ )
+ in ladder
+ ):
+ plan["skip_reason"] = "up_to_date"
+ return plan
+ if update_checks_disabled():
+ plan["skip_reason"] = "update_checks_disabled"
+ return plan
+ installer = _installer()
+ request = record.get("accelerator_request")
+ resolved = record.get("accelerator")
+ explicit = request if request in installer.ACCELERATORS and request != "auto" else None
+ if not _host_has_prebuilt(ladder, resolved if isinstance(resolved, str) else None, explicit):
+ plan["skip_reason"] = "no_prebuilt"
+ return plan
+ script = _installer_script()
+ if script is None:
+ plan["skip_reason"] = "installer_missing"
+ return plan
+ plan["update_available"] = True
+ plan["phase"] = {
+ "install_dir": audio_cpp_server.managed_audio_cpp_dir(),
+ "script": script,
+ # What setup asked for, so an automatic install keeps detecting the host.
+ "accelerator": request if request in installer.ACCELERATORS else None,
+ "from_tag": status["installed_tag"],
+ "to_tag": status["latest_tag"],
+ }
+ return plan
+
+
+def chained_phase_plan() -> dict:
+ """audio.cpp's side of the combined update item. Returns {status, update_available, skip_reason, phase} like whisper_cpp_update.chained_phase_plan. Never raises: a probe that fails is a skip, so audio.cpp can never break the llama status or apply."""
+ try:
+ return _plan()
+ except Exception as exc: # noqa: BLE001 - fail open
+ logger.debug("audio.cpp update: plan failed", error = str(exc))
+ return {
+ "status": None,
+ "update_available": False,
+ "skip_reason": "unavailable",
+ "phase": None,
+ }
+
+
+def _unload_audio_cpp_models() -> bool:
+ """Stop every audio.cpp model in the main and kept slots, a load in flight included. Returns whether one was unloaded."""
+ from core.inference import model_slots
+
+ unloaded = False
+ try:
+ from routes.inference import _peek_inference_backend
+ main = _peek_inference_backend()
+ except Exception as exc: # noqa: BLE001 - no orchestrator means nothing to unload
+ logger.debug("audio.cpp update: inference backend unavailable", error = str(exc))
+ main = None
+ if main is not None:
+ for name in model_slots.audio_cpp_model_names(main):
+ unloaded = True
+ # A failed unload can leave the worker's server running from the tree being replaced.
+ if not main.unload_model(name):
+ raise RuntimeError(f"{name} did not unload")
+ # A kept server that survived would run from, or lock, the tree being replaced.
+ if model_slots.unload_audio_cpp_slots(strict = True):
+ unloaded = True
+ return unloaded
+
+
+def _failure_message(exc: _flow.InstallerExit, env: dict) -> str:
+ if exc.returncode == _EXIT_BUSY:
+ return "The audio runtime is in use by another Unsloth Studio or setup run. Close it and try again."
+ text = str(exc)
+ if _flow.is_github_rate_limit_text(text):
+ advice = _flow.github_rate_limit_advice(_flow.github_token_present(env))
+ return f"Could not update audio.cpp: GitHub is rate-limiting release downloads. {advice}"
+ # The installer's own verdict is its last "error:" line; the rest of the tail is download progress.
+ errors = [line.strip() for line in text.splitlines() if line.strip().startswith("error: ")]
+ return errors[-1][len("error: ") :] if errors else text
+
+
+def _install(phase: dict, set_progress, unloaded: bool) -> dict:
+ from core.inference import audio_cpp_server
+
+ cmd = [sys.executable, str(phase["script"]), "--install-dir", str(phase["install_dir"])]
+ if phase.get("accelerator"):
+ cmd.extend(["--accelerator", phase["accelerator"]])
+ logger.info("audio.cpp update: installing", cmd = " ".join(cmd))
+ env = dict(os.environ, UNSLOTH_PROGRESS_PERCENT_STEP = "5")
+ try:
+ _flow.stream_installer(
+ cmd,
+ env,
+ set_progress = set_progress,
+ timeout_seconds = _INSTALL_TIMEOUT_SECONDS,
+ )
+ except _flow.InstallerExit as exc:
+ logger.warning("audio.cpp update: installer failed", error = str(exc)[-500:])
+ raise _AudioPhaseError(_failure_message(exc, env), reload_required = unloaded) from exc
+ except Exception as exc:
+ raise _AudioPhaseError(str(exc), reload_required = unloaded) from exc
+
+ binary = audio_cpp_server.find_audio_cpp_server_binary()
+ new_tag = _tag(audio_cpp_server.read_install_record(binary)) if binary else None
+ reload_hint = " Reload your model to use it." if unloaded else ""
+ if new_tag == phase["from_tag"]:
+ # Exit 0 also means the release lookup could not answer and the intact tree was kept.
+ message = (
+ f"audio.cpp could not be updated right now, so the existing {new_tag} "
+ f"install was kept. Try again later.{reload_hint}"
+ )
+ else:
+ message = f"Updated audio.cpp to {new_tag}.{reload_hint}"
+ logger.info("audio.cpp update: done", to_tag = new_tag)
+ return {"to_tag": new_tag, "reload_required": unloaded, "message": message}
+
+
+def run_chained_phase(phase: dict, set_progress) -> dict:
+ """Replace the managed audio.cpp tree while no audio.cpp server can run from it."""
+ from core.inference import audio_cpp_server
+
+ try:
+ from core.inference.stt_audiocpp_sidecar import get_audio_cpp_stt_sidecar
+ sidecar = get_audio_cpp_stt_sidecar()
+ except Exception as exc:
+ # Replacing the tree without the dictation guard would race a transcription starting from it. Fail closed.
+ raise RuntimeError("could not coordinate the audio.cpp dictation sidecar update") from exc
+
+ # Set first: a load that starts while the sidecar drains a transcription is refused, not unloaded later.
+ audio_cpp_server.UPDATE_IN_PROGRESS.set()
+ try:
+ with sidecar.update_maintenance():
+ try:
+ unloaded = _unload_audio_cpp_models()
+ except Exception as exc:
+ # Some model may already be gone, so the UI must resync either way.
+ raise _AudioPhaseError(
+ f"Could not stop the audio models before the update: {exc}",
+ reload_required = True,
+ ) from exc
+ return _install(phase, set_progress, unloaded)
+ finally:
+ audio_cpp_server.UPDATE_IN_PROGRESS.clear()
diff --git a/studio/backend/utils/llama_cpp_update.py b/studio/backend/utils/llama_cpp_update.py
index a147b37ed5d..aba43db4cbb 100644
--- a/studio/backend/utils/llama_cpp_update.py
+++ b/studio/backend/utils/llama_cpp_update.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
-"""In-app llama.cpp prebuilt update: the *apply* half over utils.llama_cpp_freshness, running install_llama_prebuilt.py to download the newest bundle for this host and atomically swap it in. ``update_available`` (installed_tag != latest_tag) is laxer than freshness' ``stale`` (which also requires the install to be >= 3 days old); the UI shows the update affordance on update_available. The install is slow, so it runs on a daemon thread and callers poll get_update_status(). Everything fails open: a missing marker, offline GitHub or a source build reports update_available=False and never blocks the app. 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. whisper.cpp piggybacks on this single update item: status folds in a whisper sub-status (update_available becomes the union) and apply chains a whisper phase when whisper is behind (update_flow.run_chained_update, whisper_cpp_update.chained_phase_plan)."""
+"""In-app llama.cpp prebuilt update: the *apply* half over utils.llama_cpp_freshness, running install_llama_prebuilt.py to download the newest bundle for this host and atomically swap it in. ``update_available`` (installed_tag != latest_tag) is laxer than freshness' ``stale`` (which also requires the install to be >= 3 days old); the UI shows the update affordance on update_available. The install is slow, so it runs on a daemon thread and callers poll get_update_status(). Everything fails open: a missing marker, offline GitHub or a source build reports update_available=False and never blocks the app. 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. whisper.cpp piggybacks on this single update item: status folds in a whisper sub-status (update_available becomes the union) and apply chains a whisper phase when whisper is behind (update_flow.run_chained_update, whisper_cpp_update.chained_phase_plan). audio.cpp rides along the same way as a third phase (audio_cpp_update.chained_phase_plan)."""
from __future__ import annotations
@@ -297,10 +297,43 @@ def _merge_whisper_status(status: dict, *, force_refresh: bool = False) -> dict:
return status
+def _audio_chain_status() -> Optional[dict]:
+ """audio.cpp's plan for the combined update item. None disables it: fail-open like the whisper probe."""
+ try:
+ from utils import audio_cpp_update
+ return audio_cpp_update.chained_phase_plan()
+ except Exception as exc: # pragma: no cover - defensive
+ logger.debug("llama update: audio.cpp probe failed", error = str(exc))
+ return None
+
+
+def _merge_audio_status(status: dict) -> dict:
+ """Fold the audio.cpp sub-status in after whisper's: it joins the update_available union and names the component only when neither llama.cpp nor whisper.cpp is pending."""
+ plan = _audio_chain_status()
+ if plan is None:
+ status["audio"] = None
+ return status
+ sub = plan.get("status") or {}
+ audio_update_available = bool(plan.get("update_available"))
+ status["audio"] = {
+ "update_available": audio_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"),
+ }
+ if audio_update_available:
+ status["update_available"] = True
+ if status.get("update_component") is None:
+ status["update_component"] = "audio"
+ return status
+
+
def get_update_status(*, force_refresh: bool = False) -> dict:
- """Report whether an update is available plus the job state. This is the single main update item: llama.cpp drives it and the whisper piggyback is folded in (_merge_whisper_status). force_refresh bypasses the 24h release cache for an explicit "check now"."""
+ """Report whether an update is available plus the job state. This is the single main update item: llama.cpp drives it and the whisper and audio.cpp phases are folded in (_merge_whisper_status, _merge_audio_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)
+ status = _merge_whisper_status(status, force_refresh = force_refresh)
+ return _merge_audio_status(status)
def get_update_changelog(
@@ -864,9 +897,10 @@ def _block_mtmd_sidecar(stack: ExitStack) -> bool:
return False
-# Combined-job progress split when both phases run (the llama bundle dwarfs the whisper one); normalized to 0..1 when a phase is skipped.
+# Combined-job progress split when every phase runs (the llama bundle dwarfs the others); normalized to 0..1 over the phases that run.
_LLAMA_PHASE_WEIGHT = 0.7
_WHISPER_PHASE_WEIGHT = 0.3
+_AUDIO_PHASE_WEIGHT = 0.3
def _plan_llama_phase(backend_request: Optional[str] = None) -> dict:
@@ -1030,7 +1064,7 @@ def _plan_llama_phase(backend_request: Optional[str] = None) -> dict:
def start_update() -> dict:
- """Kick off a background update job chaining the llama phase with a whisper phase that runs only when whisper is 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."""
+ """Kick off a background update job chaining the llama phase with whisper and audio.cpp phases that run only when their component is behind; each phase no-ops cleanly when its component is current or unmanaged. Idempotent: a second call while one is running returns the in-flight job."""
if update_checks_disabled():
with _job_lock:
job = dict(_job)
@@ -1245,7 +1279,10 @@ def _start_llama_job(backend_request: Optional[str] = None) -> dict:
migration = migration,
)
whisper_spec = (whisper_plan or {}).get("phase")
- if llama_spec is None and whisper_spec is None:
+ # audio.cpp ships its own ggml, so a backend switch never touches it.
+ audio_plan = (_audio_chain_status() or {}) if backend_request is None or migration else {}
+ audio_spec = audio_plan.get("phase")
+ if llama_spec is None and whisper_spec is None and audio_spec is None:
# Nothing to run: answer with the llama refusal so the existing reasons (local_link / up_to_date / already_selected / ...) keep their meaning.
refusal = llama_plan["refusal"]
return _finish_planning_refusal(refusal["reason"], refusal["message"])
@@ -1265,6 +1302,11 @@ def _start_llama_job(backend_request: Optional[str] = None) -> dict:
else (lambda set_progress: _whisper.run_chained_phase(whisper_spec, set_progress))
)
+ audio_run = None
+ if audio_spec is not None:
+ from utils import audio_cpp_update as _audio
+ audio_run = lambda set_progress: _audio.run_chained_phase(audio_spec, set_progress)
+
phases = [
{
"name": "llama",
@@ -1307,10 +1349,24 @@ def _start_llama_job(backend_request: Optional[str] = None) -> dict:
"skip_reason": (whisper_plan or {}).get("skip_reason") or "unavailable",
"run": whisper_run,
},
+ {
+ "name": "audio",
+ "weight": _AUDIO_PHASE_WEIGHT,
+ "failure_message": "audio.cpp update failed.",
+ # Unloading a main-slot audio.cpp model is a server model change the UI must resync on.
+ "affects_job_reload": True,
+ "reports_job_tag": False,
+ "skip_reason": audio_plan.get("skip_reason") or "unavailable",
+ "run": audio_run,
+ },
]
running = " + ".join(
name
- for name, spec in (("llama.cpp", llama_spec), ("whisper.cpp", whisper_spec))
+ for name, spec in (
+ ("llama.cpp", llama_spec),
+ ("whisper.cpp", whisper_spec),
+ ("audio.cpp", audio_spec),
+ )
if spec
)
if backend_request is not None and llama_spec is not None:
diff --git a/studio/backend/utils/prebuilt/update_flow.py b/studio/backend/utils/prebuilt/update_flow.py
index 7f4a6b6dc4a..62ba15fbf82 100644
--- a/studio/backend/utils/prebuilt/update_flow.py
+++ b/studio/backend/utils/prebuilt/update_flow.py
@@ -579,7 +579,7 @@ def run_chained_update(phases: list[dict], *, job: dict, job_lock: threading.Loc
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"
- if primary_to_tag is None:
+ if primary_to_tag is None and phase.get("reports_job_tag", True):
primary_to_tag = result.get("to_tag")
with job_lock:
diff --git a/studio/frontend/src/components/llama-update-banner.tsx b/studio/frontend/src/components/llama-update-banner.tsx
index fd9c8cd6453..833e35fde66 100644
--- a/studio/frontend/src/components/llama-update-banner.tsx
+++ b/studio/frontend/src/components/llama-update-banner.tsx
@@ -9,6 +9,7 @@ import {
useLlamaUpdateCheck,
} from "@/hooks/use-llama-update-check";
import {
+ useShowAudioCppUpdateBanner,
useShowLlamaUpdateBanner,
useShowWhisperUpdateBanner,
} from "@/hooks/use-llama-update-pref";
@@ -115,6 +116,7 @@ export function LlamaUpdateBanner({
}: LlamaUpdateBannerProps): ReactElement | null {
const showLlamaBannerPref = useShowLlamaUpdateBanner();
const showWhisperBannerPref = useShowWhisperUpdateBanner();
+ const showAudioCppBannerPref = useShowAudioCppUpdateBanner();
const [changelogVersion, setChangelogVersion] = useState<string | null>(null);
// Not gated on showBannerPref: this hook instance is the app-wide listener
// for a cross-tab reload_required resync (the settings-sheet's own instance
@@ -134,20 +136,30 @@ export function LlamaUpdateBanner({
{
llama: Boolean(status?.llama.update_available) || migrationPending,
whisper: Boolean(status?.whisper?.update_available),
+ audio: Boolean(status?.audio?.update_available),
+ },
+ {
+ llama: showLlamaBannerPref,
+ whisper: showWhisperBannerPref,
+ audio: showAudioCppBannerPref,
},
- { llama: showLlamaBannerPref, whisper: showWhisperBannerPref },
);
// Its own release pair and download size, not the ones the backend put at the
// top level: those are llama's whatever the card shows.
const offer =
- component === "whisper.cpp" ? status?.whisper : status?.llama;
+ component === "whisper.cpp"
+ ? status?.whisper
+ : component === "audio.cpp"
+ ? status?.audio
+ : status?.llama;
const sizeBytes = offer?.update_size_bytes ?? null;
const latestTag = offer?.latest_tag ?? null;
const installedTag = offer?.installed_tag ?? null;
async function handleUpdate() {
- // Read before applying: the status refreshes as the job runs.
- const migrating = migrationPending;
+ // Read before applying (the status refreshes mid-job). An audio.cpp update may keep
+ // the old runtime, so only the job's message says what happened, as for a migration.
+ const migrating = migrationPending || component === "audio.cpp";
const result = await apply();
if (result?.ok) {
const updatedTag =
@@ -162,15 +174,18 @@ export function LlamaUpdateBanner({
}),
);
} else if (result) {
- toast.error(
- `${component} update failed: ${result.error ?? "unknown error"}`,
- );
+ // The failing phase need not be the component the card names.
+ toast.error(`Update failed: ${result.error ?? "unknown error"}`);
}
}
// Muted by the component the card shows.
const livePref =
- component === "whisper.cpp" ? showWhisperBannerPref : showLlamaBannerPref;
+ component === "whisper.cpp"
+ ? showWhisperBannerPref
+ : component === "audio.cpp"
+ ? showAudioCppBannerPref
+ : showLlamaBannerPref;
// Held across a chained apply, which renames the card mid-job. An error counts
// as in flight so a failed phase keeps its retry on screen.
const jobState = status?.job.state;
diff --git a/studio/frontend/src/features/audio/audio-page-policy.ts b/studio/frontend/src/features/audio/audio-page-policy.ts
index 576d43d2478..8878be15971 100644
--- a/studio/frontend/src/features/audio/audio-page-policy.ts
+++ b/studio/frontend/src/features/audio/audio-page-policy.ts
@@ -45,6 +45,33 @@ export function audioCppRuntimeUpdate(
return { installed: runtime.release_tag, expected: runtime.expected_tag };
}
+export type AudioRuntimeNoticeMode =
+ | "update"
+ | "updating"
+ | "checking"
+ | "ask_owner"
+ | "cli";
+
+/** What the outdated-runtime notice offers. The in-app update is owner-only, and the backend
+ * offers it only for a runtime it can replace; otherwise the notice keeps the CLI route. */
+export function audioRuntimeNoticeMode({
+ isOwner,
+ offered,
+ applying,
+ checked,
+}: {
+ isOwner: boolean;
+ offered: boolean;
+ applying: boolean;
+ /** The update status has loaded; before that the offer is unknown, not absent. */
+ checked: boolean;
+}): AudioRuntimeNoticeMode {
+ if (!isOwner) return "ask_owner";
+ if (applying) return "updating";
+ if (!checked) return "checking";
+ return offered ? "update" : "cli";
+}
+
/** GGUF music families whose prompt needs a description beside the lyrics: MiniMax Music 3
* takes it as the caption and YuE2 as the style. The others fall back to the lyrics. */
const DESCRIBED_MUSIC_FAMILIES = new Set(["minimax_music3", "yue2"]);
@@ -526,7 +553,8 @@ export function mergeGalleryPage<T extends { id: string }>(
if (oldestInPage === -1 && cached.length > 0) {
return { clips: [...page], stitched: false };
}
- const scrollback = oldestInPage === -1 ? cached : cached.slice(oldestInPage + 1);
+ const scrollback =
+ oldestInPage === -1 ? cached : cached.slice(oldestInPage + 1);
const tail = scrollback.filter(
(clip) => !inPage.has(clip.id) && clip.id !== removedId,
);
diff --git a/studio/frontend/src/features/audio/audio-page.tsx b/studio/frontend/src/features/audio/audio-page.tsx
index f18e6144cf0..b9defd9fe18 100644
--- a/studio/frontend/src/features/audio/audio-page.tsx
+++ b/studio/frontend/src/features/audio/audio-page.tsx
@@ -4,7 +4,7 @@
// Stays mounted across tab switches (__root.tsx), so `active` gates polling, popovers and the recorder.
import { TestTubeOutlineIcon } from "@/lib/hugeicons-derived";
-import { Alert02Icon, SparklesIcon } from "@hugeicons/core-free-icons";
+import { SparklesIcon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { LibraryPageLink } from "@/components/media-page-link";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -43,6 +43,7 @@ import {
audioGenerationPresentation,
} from "./audio-page-policy";
import { clipReference } from "./audio-run-request";
+import { AudioRuntimeUpdateNotice } from "./components/audio-runtime-update-notice";
import { AudioActiveProvider } from "./components/audio-source-input";
import {
audioModelLabel,
@@ -1705,29 +1706,12 @@ export function AudioPage({
{capabilityLine}
</p>
{runtimeUpdate ? (
- <p
- role="status"
- className="mt-1 flex items-start gap-1.5 text-ui-12 leading-snug text-foreground"
- >
- <HugeiconsIcon
- icon={Alert02Icon}
- className="mt-0.5 size-3.5 shrink-0 text-muted-foreground"
- />
- <span>
- Your audio runtime is{" "}
- <span className="whitespace-nowrap">
- {runtimeUpdate.installed}
- </span>
- ; this Studio expects{" "}
- <span className="whitespace-nowrap">
- {runtimeUpdate.expected}
- </span>
- . Some models may not work until you update. Stop Studio,{" "}
- run{" "}
- <code className="font-mono">unsloth studio update</code>,
- then start Studio again.
- </span>
- </p>
+ <AudioRuntimeUpdateNotice
+ update={runtimeUpdate}
+ onUpdated={() =>
+ Promise.all([refreshStatus(), refreshSttStatus()])
+ }
+ />
) : null}
</div>
diff --git a/studio/frontend/src/features/audio/components/audio-runtime-update-notice.tsx b/studio/frontend/src/features/audio/components/audio-runtime-update-notice.tsx
new file mode 100644
index 00000000000..4ce31d850aa
--- /dev/null
+++ b/studio/frontend/src/features/audio/components/audio-runtime-update-notice.tsx
@@ -0,0 +1,108 @@
+// 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 { useIsAccountOwner } from "@/features/auth";
+import { useLlamaUpdateCheck } from "@/hooks/use-llama-update-check";
+import { toast } from "@/lib/toast";
+import { Alert02Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { type ReactElement, useEffect, useRef, useState } from "react";
+import { audioRuntimeNoticeMode } from "../audio-page-policy";
+
+/** The managed audio runtime is not the release this Studio pins. The owner updates it in place
+ * through the shared update job, which also installs any pending llama.cpp or whisper.cpp update;
+ * the app-wide update card follows that job and resyncs the loaded model. */
+export function AudioRuntimeUpdateNotice({
+ update,
+ onUpdated,
+}: {
+ update: { installed: string; expected: string };
+ onUpdated: () => Promise<unknown>;
+}): ReactElement {
+ const isOwner = useIsAccountOwner();
+ const { status, applying, apply } = useLlamaUpdateCheck({
+ enabled: isOwner,
+ });
+ const offered = Boolean(status?.audio?.update_available);
+ // Re-read the runtime after a followed job or a withdrawn offer (another tab updated), staying
+ // on "updating" until then: a stale notice would send the owner to the CLI.
+ const followedJob = useRef(false);
+ const wasOffered = useRef(false);
+ const [refreshing, setRefreshing] = useState(false);
+ useEffect(() => {
+ if (applying) {
+ followedJob.current = true;
+ return;
+ }
+ const offerWithdrawn = wasOffered.current && !offered;
+ wasOffered.current = offered;
+ if (followedJob.current || offerWithdrawn) {
+ followedJob.current = false;
+ setRefreshing(true);
+ void onUpdated().finally(() => setRefreshing(false));
+ }
+ }, [applying, offered, onUpdated]);
+ const mode = audioRuntimeNoticeMode({
+ isOwner,
+ offered,
+ applying: applying || refreshing,
+ checked: status !== null,
+ });
+
+ async function handleUpdate() {
+ const result = await apply();
+ if (result.ok) {
+ // The job says what each phase did, including a release lookup that kept the old tree.
+ toast.success(
+ result.message?.trim() || `audio.cpp updated to ${update.expected}.`,
+ );
+ } else {
+ // The shared job may have failed in its llama.cpp or whisper.cpp phase.
+ toast.error(`Update failed: ${result.error ?? "unknown error"}`);
+ }
+ }
+
+ return (
+ <div
+ role="status"
+ className="mt-1 flex items-start gap-1.5 text-ui-12 leading-snug text-foreground"
+ >
+ <HugeiconsIcon
+ icon={Alert02Icon}
+ className="mt-0.5 size-3.5 shrink-0 text-muted-foreground"
+ />
+ <div className="grid justify-items-start gap-1.5">
+ <span>
+ Your audio runtime is{" "}
+ <span className="whitespace-nowrap">{update.installed}</span>; Unsloth
+ expects <span className="whitespace-nowrap">{update.expected}</span>.{" "}
+ {mode === "ask_owner" ? (
+ <>
+ Some models may not work until it is updated. Ask the Unsloth
+ owner to update it.
+ </>
+ ) : mode === "updating" || mode === "checking" ? null : (
+ <>Some models may not work until you update. </>
+ )}
+ {mode === "cli" ? (
+ <>
+ Stop Unsloth, run{" "}
+ <code className="font-mono">unsloth studio update</code>, then
+ start it again.
+ </>
+ ) : null}
+ </span>
+ {mode === "update" || mode === "updating" ? (
+ <Button
+ size="xs"
+ onClick={handleUpdate}
+ disabled={mode === "updating"}
+ >
+ {mode === "updating" ? "Updating..." : "Update"}
+ </Button>
+ ) : null}
+ </div>
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/chat/chat-settings-sheet.tsx b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
index ddb5bdb562b..e8420da53a1 100644
--- a/studio/frontend/src/features/chat/chat-settings-sheet.tsx
+++ b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
@@ -626,9 +626,7 @@ export function ChatSettingsPanel({
`llama.cpp updated to ${result.tag ?? "the latest build"}.${reloadHint}`,
);
} else {
- toast.error(
- `llama.cpp update failed: ${result.error ?? "unknown error"}`,
- );
+ toast.error(`Update failed: ${result.error ?? "unknown error"}`);
}
}, [applyLlamaUpdate, speculativeDrafterLabel]);
const loadedEffectiveContext = customContextLength ?? loadedContextLength;
@@ -1165,10 +1163,10 @@ export function ChatSettingsPanel({
reason: specFallbackReason,
drafter: speculativeDrafterLabel,
isLocalGguf,
- updateAvailable: Boolean(llamaUpdateStatus?.update_available),
+ updateAvailable: Boolean(llamaUpdateStatus?.llama.update_available),
})}
</p>
- {mtpUpdatable && llamaUpdateStatus?.update_available && (
+ {mtpUpdatable && llamaUpdateStatus?.llama.update_available && (
<Button
size="sm"
className="corner-squircle mt-2 h-7 text-ui-12"
diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.ts
index e59d9796002..18dd3d47903 100644
--- a/studio/frontend/src/features/settings/settings-search.ts
+++ b/studio/frontend/src/features/settings/settings-search.ts
@@ -26,6 +26,7 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {
"settings.general.notifications.sectionTitle",
"settings.general.notifications.showLlamaUpdates",
"settings.general.notifications.showWhisperUpdates",
+ "settings.general.notifications.showAudioCppUpdates",
"settings.general.previewSharing.sectionTitle",
"settings.general.previewSharing.enableLabel",
"settings.general.previewSharing.revokeLabel",
diff --git a/studio/frontend/src/features/settings/tabs/general-tab.tsx b/studio/frontend/src/features/settings/tabs/general-tab.tsx
index bb928737bde..a28d6f885d8 100644
--- a/studio/frontend/src/features/settings/tabs/general-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/general-tab.tsx
@@ -29,8 +29,10 @@ import {
TRAINING_UI_PREFERENCE_KEYS,
} from "@/features/training";
import {
+ setShowAudioCppUpdateBanner,
setShowLlamaUpdateBanner,
setShowWhisperUpdateBanner,
+ useShowAudioCppUpdateBanner,
useShowLlamaUpdateBanner,
useShowWhisperUpdateBanner,
} from "@/hooks/use-llama-update-pref";
@@ -163,6 +165,7 @@ const PREFS_KEYS: string[] = [
// Update notifications
"unsloth_show_llama_update_banner",
"unsloth_show_whisper_update_banner",
+ "unsloth_show_audio_cpp_update_banner",
"unsloth_llama_update_offer_suppression",
"unsloth_monitor_overlay",
LOADED_MODELS_PREFERENCE_KEYS.show,
@@ -203,6 +206,7 @@ export function GeneralTab() {
const hfTokenIsPersisting = useHfTokenStore((s) => s.isPersisting);
const showLlamaUpdates = useShowLlamaUpdateBanner();
const showWhisperUpdates = useShowWhisperUpdateBanner();
+ const showAudioCppUpdates = useShowAudioCppUpdateBanner();
const showLoadedModels = useShowLoadedModels();
const [draftToken, setDraftToken] = useState(hfToken ?? "");
@@ -680,6 +684,17 @@ export function GeneralTab() {
onCheckedChange={setShowWhisperUpdateBanner}
/>
</SettingsRow>
+ <SettingsRow
+ label={t("settings.general.notifications.showAudioCppUpdates")}
+ description={t(
+ "settings.general.notifications.showAudioCppUpdatesDescription",
+ )}
+ >
+ <Switch
+ checked={showAudioCppUpdates}
+ onCheckedChange={setShowAudioCppUpdateBanner}
+ />
+ </SettingsRow>
</SettingsSection>
{/* Installation-wide settings: owner-only routes, so a managed account gets no dead controls. */}
diff --git a/studio/frontend/src/hooks/use-llama-update-check.ts b/studio/frontend/src/hooks/use-llama-update-check.ts
index 559c828bb6c..37772602afc 100644
--- a/studio/frontend/src/hooks/use-llama-update-check.ts
+++ b/studio/frontend/src/hooks/use-llama-update-check.ts
@@ -50,11 +50,13 @@ export interface LlamaUpdateStatus {
supported: boolean;
update_available: boolean;
source_build: boolean;
- component: "llama.cpp" | "whisper.cpp";
- // Carried per component whatever the card names: both can be behind at once,
+ component: "llama.cpp" | "whisper.cpp" | "audio.cpp";
+ // Carried per component whatever the card names: several can be behind at once,
// and the card shows whichever one the notification switches allow.
llama: ComponentOffer;
whisper: ComponentOffer | null;
+ // The release this Studio pins, when the managed audio.cpp runtime is another one.
+ audio: ComponentOffer | null;
installed_tag: string | null;
latest_tag: string | null;
// Prebuilt download size in bytes, if known.
@@ -101,19 +103,45 @@ function parseJob(value: unknown): LlamaUpdateJob {
};
}
+function parseOffer(offer: Record<string, unknown>): ComponentOffer {
+ return {
+ update_available: offer.update_available === true,
+ installed_tag:
+ typeof offer.installed_tag === "string" ? offer.installed_tag : null,
+ latest_tag: typeof offer.latest_tag === "string" ? offer.latest_tag : null,
+ update_size_bytes:
+ typeof offer.update_size_bytes === "number"
+ ? offer.update_size_bytes
+ : null,
+ };
+}
+
+function nestedOffer(value: unknown): Record<string, unknown> | null {
+ return value && typeof value === "object"
+ ? (value as Record<string, unknown>)
+ : null;
+}
+
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;
+ s.update_component === "whisper"
+ ? "whisper.cpp"
+ : s.update_component === "audio"
+ ? "audio.cpp"
+ : "llama.cpp";
+ const whisper = nestedOffer(s.whisper);
+ const audio = nestedOffer(s.audio);
// 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;
+ // A whisper-only or audio-only update must display the nested release instead
+ // of presenting equal llama tags as a new llama update.
+ const details =
+ component === "whisper.cpp" && whisper
+ ? whisper
+ : component === "audio.cpp" && audio
+ ? audio
+ : s;
return {
supported: s.supported === true,
update_available: s.update_available === true,
@@ -140,21 +168,8 @@ function parseStatus(value: unknown): LlamaUpdateStatus | null {
update_size_bytes:
typeof s.update_size_bytes === "number" ? s.update_size_bytes : null,
},
- whisper: whisper
- ? {
- update_available: whisper.update_available === true,
- installed_tag:
- typeof whisper.installed_tag === "string"
- ? whisper.installed_tag
- : null,
- latest_tag:
- typeof whisper.latest_tag === "string" ? whisper.latest_tag : null,
- update_size_bytes:
- typeof whisper.update_size_bytes === "number"
- ? whisper.update_size_bytes
- : null,
- }
- : null,
+ whisper: whisper ? parseOffer(whisper) : null,
+ audio: audio ? parseOffer(audio) : null,
// Always from the top level: the backend belongs to the llama.cpp install whatever
// component the version fields describe.
backend_migration_available: s.backend_migration_available === true,
@@ -181,7 +196,7 @@ let retainedSuppression: {
persisted: boolean;
} = { value: null, persisted: true };
-function offerKey(status: LlamaUpdateStatus): string {
+export function offerKey(status: LlamaUpdateStatus): string {
return JSON.stringify({
llama: status.llama.update_available
? [status.llama.installed_tag, status.llama.latest_tag]
@@ -197,6 +212,10 @@ function offerKey(status: LlamaUpdateStatus): string {
status.to_backend,
]
: null,
+ // Only when offered, so keys stored before audio.cpp joined the card still match.
+ ...(status.audio?.update_available
+ ? { audio: [status.audio.installed_tag, status.audio.latest_tag] }
+ : {}),
});
}
diff --git a/studio/frontend/src/hooks/use-llama-update-pref.ts b/studio/frontend/src/hooks/use-llama-update-pref.ts
index 0b3ec57af30..3749378f6a9 100644
--- a/studio/frontend/src/hooks/use-llama-update-pref.ts
+++ b/studio/frontend/src/hooks/use-llama-update-pref.ts
@@ -5,9 +5,10 @@ import { useSyncExternalStore } from "react";
// Whether an update banner may appear, per component. On by default; only an
// explicit "false" (Settings -> General -> Notifications) disables it. A switch
-// each: the two components ship on their own schedules.
+// each: the components ship on their own schedules.
const LLAMA_STORAGE_KEY = "unsloth_show_llama_update_banner";
const WHISPER_STORAGE_KEY = "unsloth_show_whisper_update_banner";
+const AUDIO_CPP_STORAGE_KEY = "unsloth_show_audio_cpp_update_banner";
const listeners = new Set<() => void>();
@@ -33,13 +34,17 @@ function writePref(key: string, show: boolean): void {
for (const listener of listeners) listener();
}
-// One listener set for both keys: a subscriber re-reads its own getter, so a
+// One listener set for every key: a subscriber re-reads its own getter, so a
// notification it did not need costs it a comparison.
function subscribe(listener: () => void): () => void {
listeners.add(listener);
// Sync toggles made in another tab.
const onStorage = (event: StorageEvent) => {
- if (event.key === LLAMA_STORAGE_KEY || event.key === WHISPER_STORAGE_KEY) {
+ if (
+ event.key === LLAMA_STORAGE_KEY ||
+ event.key === WHISPER_STORAGE_KEY ||
+ event.key === AUDIO_CPP_STORAGE_KEY
+ ) {
listener();
}
};
@@ -73,3 +78,15 @@ export function setShowWhisperUpdateBanner(show: boolean): void {
export function useShowWhisperUpdateBanner(): boolean {
return useSyncExternalStore(subscribe, getShowWhisperUpdateBanner);
}
+
+export function getShowAudioCppUpdateBanner(): boolean {
+ return readPref(AUDIO_CPP_STORAGE_KEY);
+}
+
+export function setShowAudioCppUpdateBanner(show: boolean): void {
+ writePref(AUDIO_CPP_STORAGE_KEY, show);
+}
+
+export function useShowAudioCppUpdateBanner(): boolean {
+ return useSyncExternalStore(subscribe, getShowAudioCppUpdateBanner);
+}
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 7583e11ecbd..483cddc5875 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -1610,6 +1610,9 @@ export const ar = {
showWhisperUpdates: "إشعارات تحديث whisper.cpp",
showWhisperUpdatesDescription:
"التنبيه عند توفر إصدار أحدث من whisper.cpp لنماذج تحويل الكلام إلى نص. أوقف التشغيل إذا كنت لا تفرّغ الصوت.",
+ showAudioCppUpdates: "إشعارات تحديث audio.cpp",
+ showAudioCppUpdatesDescription:
+ "التنبيه عندما تحتاج بيئة تشغيل audio.cpp إلى تحديث لتشغيل صفحات الصوت. أوقف التشغيل إذا كنت لا تستخدم الصوت أبدًا.",
},
startup: {
sectionTitle: "بدء التشغيل",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index c3c7b1747c3..2aa3de83a4d 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -1631,6 +1631,9 @@ export const de = {
showWhisperUpdates: "whisper.cpp-Update-Benachrichtigungen",
showWhisperUpdatesDescription:
"Benachrichtigt, wenn ein neuerer whisper.cpp-Build für Speech-to-Text-Modelle verfügbar ist. Deaktivieren Sie dies, wenn Sie nie Audio transkribieren.",
+ showAudioCppUpdates: "audio.cpp-Update-Benachrichtigungen",
+ showAudioCppUpdatesDescription:
+ "Benachrichtigt, wenn die audio.cpp-Laufzeit ein Update für die Audio-Seiten braucht. Deaktivieren Sie dies, wenn Sie Audio nie verwenden.",
},
startup: {
sectionTitle: "Autostart",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index cfd2b3bc978..35299a57bc3 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -1669,6 +1669,9 @@ export const en = {
showWhisperUpdates: "whisper.cpp update notifications",
showWhisperUpdatesDescription:
"Notify when a newer whisper.cpp build is available for speech-to-text models. Turn off if you never transcribe audio.",
+ showAudioCppUpdates: "audio.cpp update notifications",
+ showAudioCppUpdatesDescription:
+ "Notify when the audio.cpp runtime needs an update to run the Audio pages. Turn off if you never use Audio.",
},
startup: {
sectionTitle: "Startup",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 0cb85efa1fc..ce11e2aa862 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -1627,6 +1627,9 @@ export const es = {
showWhisperUpdates: "Notificaciones de actualización de whisper.cpp",
showWhisperUpdatesDescription:
"Avisa cuando haya una compilación más reciente de whisper.cpp para los modelos de voz a texto. Desactívalo si nunca transcribes audio.",
+ showAudioCppUpdates: "Notificaciones de actualización de audio.cpp",
+ showAudioCppUpdatesDescription:
+ "Avisa cuando el entorno de ejecución de audio.cpp necesite una actualización para las páginas de Audio. Desactívalo si nunca usas Audio.",
},
startup: {
sectionTitle: "Inicio",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 1809103e212..de51c244be2 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -1629,6 +1629,9 @@ export const fr = {
showWhisperUpdates: "Notifications de mise à jour de whisper.cpp",
showWhisperUpdatesDescription:
"Notifier lorsqu'une nouvelle version de whisper.cpp est disponible pour les modèles de transcription vocale. Désactivez si vous ne transcrivez jamais d'audio.",
+ showAudioCppUpdates: "Notifications de mise à jour d'audio.cpp",
+ showAudioCppUpdatesDescription:
+ "Notifier lorsque le moteur audio.cpp doit être mis à jour pour les pages Audio. Désactivez si vous n'utilisez jamais Audio.",
},
startup: {
sectionTitle: "Démarrage",
diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.ts
index 803799fc8a2..e2709a1a2a7 100644
--- a/studio/frontend/src/i18n/locales/he.ts
+++ b/studio/frontend/src/i18n/locales/he.ts
@@ -1710,6 +1710,9 @@ export const he = {
showWhisperUpdates: "התראות עדכון של whisper.cpp",
showWhisperUpdatesDescription:
"הודע כאשר גרסת build חדשה יותר של whisper.cpp זמינה עבור מודלים של המרת דיבור לטקסט. כבה אם אינך מתמלל אודיו אף פעם.",
+ showAudioCppUpdates: "התראות עדכון של audio.cpp",
+ showAudioCppUpdatesDescription:
+ "הודע כאשר סביבת הריצה של audio.cpp צריכה עדכון עבור דפי האודיו. כבה אם אינך משתמש באודיו אף פעם.",
},
startup: {
sectionTitle: "הפעלה",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index c15c6eb58cf..f2ced12e34f 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -1613,6 +1613,9 @@ export const hi = {
showWhisperUpdates: "whisper.cpp अपडेट सूचनाएं",
showWhisperUpdatesDescription:
"स्पीच-टू-टेक्स्ट मॉडल के लिए जब कोई नया whisper.cpp बिल्ड उपलब्ध हो तो सूचित करें। यदि आप ऑडियो ट्रांसक्राइब नहीं करते हैं तो बंद कर दें।",
+ showAudioCppUpdates: "audio.cpp अपडेट सूचनाएं",
+ showAudioCppUpdatesDescription:
+ "जब ऑडियो पेजों के लिए audio.cpp रनटाइम को अपडेट की ज़रूरत हो तो सूचित करें। यदि आप कभी ऑडियो का उपयोग नहीं करते हैं तो बंद कर दें।",
},
startup: {
sectionTitle: "स्टार्टअप",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index fedf5226cd0..20542ac7ff0 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -1608,6 +1608,9 @@ export const it = {
showWhisperUpdates: "Notifiche di aggiornamento di whisper.cpp",
showWhisperUpdatesDescription:
"Avvisa quando è disponibile una build più recente di whisper.cpp per i modelli di trascrizione vocale. Disattiva le notifiche se non trascrivi mai l'audio.",
+ showAudioCppUpdates: "Notifiche di aggiornamento di audio.cpp",
+ showAudioCppUpdatesDescription:
+ "Avvisa quando il runtime di audio.cpp deve essere aggiornato per le pagine Audio. Disattiva le notifiche se non usi mai Audio.",
},
startup: {
sectionTitle: "Avvio",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 2ef80e33f9f..8201d4f7ff7 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -1598,6 +1598,9 @@ export const ja = {
showLoadedModelsDescription: "現在メモリ上にあるすべてのモデル(チャット、音声、画像、動画)を一覧表示する小さなカードを右下に表示します。各モデルを解放するボタンが付いています。",
showWhisperUpdates: "whisper.cpp のアップデート通知",
showWhisperUpdatesDescription: "音声認識モデル向けの新しい whisper.cpp ビルドが利用可能になったときに通知します。音声を文字起こししない場合はオフにしてください。",
+ showAudioCppUpdates: "audio.cpp のアップデート通知",
+ showAudioCppUpdatesDescription:
+ "音声ページに必要な audio.cpp ランタイムの更新があるときに通知します。音声機能を使わない場合はオフにしてください。",
},
startup: {
sectionTitle: "起動",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index f32eb189e3d..947a3736b01 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -1607,6 +1607,9 @@ export const ko = {
showWhisperUpdates: "whisper.cpp 업데이트 알림",
showWhisperUpdatesDescription:
"음성 인식 모델을 위한 최신 whisper.cpp 빌드가 있으면 알립니다. 오디오를 전사하지 않는다면 끄세요.",
+ showAudioCppUpdates: "audio.cpp 업데이트 알림",
+ showAudioCppUpdatesDescription:
+ "오디오 페이지에 필요한 audio.cpp 런타임 업데이트가 있으면 알립니다. 오디오를 사용하지 않는다면 끄세요.",
},
startup: {
sectionTitle: "시작",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 4b9527de4fd..ffb2e473e6d 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -1618,6 +1618,9 @@ export const ptBR = {
showWhisperUpdates: "Notificações de atualização do whisper.cpp",
showWhisperUpdatesDescription:
"Notifica quando uma versão mais recente do whisper.cpp está disponível para modelos de fala para texto. Desative se você nunca transcreve áudio.",
+ showAudioCppUpdates: "Notificações de atualização do audio.cpp",
+ showAudioCppUpdatesDescription:
+ "Notifica quando o runtime do audio.cpp precisa de uma atualização para as páginas de Áudio. Desative se você nunca usa Áudio.",
},
startup: {
sectionTitle: "Inicialização",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 0111b0bf94d..c50ec49c2db 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -1614,6 +1614,9 @@ export const ru = {
showWhisperUpdates: "Уведомления об обновлениях whisper.cpp",
showWhisperUpdatesDescription:
"Уведомлять о доступности новой сборки whisper.cpp для моделей распознавания речи. Отключите, если вы не расшифровываете аудио.",
+ showAudioCppUpdates: "Уведомления об обновлениях audio.cpp",
+ showAudioCppUpdatesDescription:
+ "Уведомлять, когда среде выполнения audio.cpp нужно обновление для страниц «Аудио». Отключите, если вы не пользуетесь аудио.",
},
startup: {
sectionTitle: "Автозапуск",
diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.ts
index f7812b48324..10242022fb5 100644
--- a/studio/frontend/src/i18n/locales/sv.ts
+++ b/studio/frontend/src/i18n/locales/sv.ts
@@ -1773,6 +1773,9 @@ export const sv = {
showWhisperUpdates: "Aviseringar om whisper.cpp-uppdateringar",
showWhisperUpdatesDescription:
"Avisera när en nyare whisper.cpp-version finns för tal-till-text-modeller. Stäng av om du aldrig transkriberar ljud.",
+ showAudioCppUpdates: "Aviseringar om audio.cpp-uppdateringar",
+ showAudioCppUpdatesDescription:
+ "Avisera när audio.cpp-körmiljön behöver uppdateras för ljudsidorna. Stäng av om du aldrig använder ljud.",
},
startup: {
sectionTitle: "Start",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index dcf45dce26a..80b042f1310 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -1590,6 +1590,9 @@ export const zhCN = {
showWhisperUpdates: "whisper.cpp 更新通知",
showWhisperUpdatesDescription:
"当有可用于语音识别模型的新版 whisper.cpp 构建时通知你。如果不需要转写音频,可以关闭此项。",
+ showAudioCppUpdates: "audio.cpp 更新通知",
+ showAudioCppUpdatesDescription:
+ "当音频页面所需的 audio.cpp 运行时需要更新时通知你。如果从不使用音频功能,可以关闭此项。",
},
startup: {
sectionTitle: "启动",
diff --git a/studio/frontend/src/lib/llama-job-lifecycle.ts b/studio/frontend/src/lib/llama-job-lifecycle.ts
index 75d788edf76..ae4580d5801 100644
--- a/studio/frontend/src/lib/llama-job-lifecycle.ts
+++ b/studio/frontend/src/lib/llama-job-lifecycle.ts
@@ -68,49 +68,62 @@ export function llamaUpdatePresentation(
};
}
-export type UpdateComponent = "llama.cpp" | "whisper.cpp";
+export type UpdateComponent = "llama.cpp" | "whisper.cpp" | "audio.cpp";
export interface UpdateComponentFlags {
llama: boolean;
whisper: boolean;
+ audio: boolean;
}
+// In the order the backend names them, which is also the order the job installs them.
+const UPDATE_COMPONENT_KEYS: Record<
+ UpdateComponent,
+ keyof UpdateComponentFlags
+> = {
+ "llama.cpp": "llama",
+ "whisper.cpp": "whisper",
+ "audio.cpp": "audio",
+};
+
/**
* Which component's offer the single update card shows.
*
- * Both can be pending at once and the backend names only one: llama.cpp when its
- * release is behind, whisper.cpp otherwise, so a llama.cpp backend migration is
- * named whisper.cpp when whisper is stale too. If the named one's switch is off
- * and the other has an offer the user does allow, the card shows that one rather
- * than nothing. Update installs everything pending either way.
+ * Several can be pending at once and the backend names only one: llama.cpp when its
+ * release is behind, then whisper.cpp, then audio.cpp, so a llama.cpp backend
+ * migration is named whisper.cpp when whisper is stale too. If the named one's
+ * switch is off and another has an offer the user does allow, the card shows that
+ * one rather than nothing. Update installs everything pending either way.
*/
export function updateBannerComponent(
named: UpdateComponent,
pending: UpdateComponentFlags,
allow: UpdateComponentFlags,
): UpdateComponent {
- const key = named === "whisper.cpp" ? "whisper" : "llama";
- if (allow[key]) {
+ if (allow[UPDATE_COMPONENT_KEYS[named]]) {
return named;
}
- const other = key === "whisper" ? "llama" : "whisper";
- return allow[other] && pending[other]
- ? ((other === "whisper" ? "whisper.cpp" : "llama.cpp") as UpdateComponent)
- : named;
+ const other = (Object.keys(UPDATE_COMPONENT_KEYS) as UpdateComponent[]).find(
+ (component) =>
+ component !== named &&
+ allow[UPDATE_COMPONENT_KEYS[component]] &&
+ pending[UPDATE_COMPONENT_KEYS[component]],
+ );
+ return other ?? named;
}
/**
* The tag a finished update reports.
*
* The job's `to_tag` is the llama.cpp build by definition, so a card showing the
- * whisper.cpp offer reports the release it advertised instead of llama's.
+ * whisper.cpp or audio.cpp offer reports the release it advertised instead of llama's.
*/
export function updateToastTag(
component: UpdateComponent,
jobTag: string | null | undefined,
offerTag: string | null | undefined,
): string | null {
- const preferred = component === "whisper.cpp" ? offerTag : jobTag;
+ const preferred = component === "llama.cpp" ? jobTag : offerTag;
return preferred ?? offerTag ?? jobTag ?? null;
}
diff --git a/studio/frontend/tests/audio-cpp-catalog.test.ts b/studio/frontend/tests/audio-cpp-catalog.test.ts
index 083b89c6942..b731fd856a5 100644
--- a/studio/frontend/tests/audio-cpp-catalog.test.ts
+++ b/studio/frontend/tests/audio-cpp-catalog.test.ts
@@ -867,10 +867,12 @@ test("an outdated managed runtime names both releases; anything else shows no no
assert.match(route, /"expected_tag": None,\s*"outdated": False,/);
const page = readAudioWorkspaceSource();
assert.match(page, /const nextUpdate = audioCppRuntimeUpdate\(audioCppRuntime\.current\);/);
- assert.match(page, /\{runtimeUpdate \? \(/);
+ assert.match(page, /\{runtimeUpdate \? \(\s*<AudioRuntimeUpdateNotice\s+update=\{runtimeUpdate\}/);
+ // The CLI route stays for whoever the in-app update is not offered to.
+ const notice = readText("../src/features/audio/components/audio-runtime-update-notice.tsx");
assert.match(
- page,
- /Stop Studio,\{" "\}\s*run\{" "\}\s*<code className="font-mono">unsloth studio update<\/code>,\s*then start Studio again\./,
+ notice,
+ /Stop Unsloth, run\{" "\}\s*<code className="font-mono">unsloth studio update<\/code>, then\s*start it again\./,
);
});
diff --git a/studio/frontend/tests/audio-page-policy.test.ts b/studio/frontend/tests/audio-page-policy.test.ts
index 4b196a414bf..c837e9457a9 100644
--- a/studio/frontend/tests/audio-page-policy.test.ts
+++ b/studio/frontend/tests/audio-page-policy.test.ts
@@ -10,6 +10,7 @@ import {
MINIMAX_MUSIC_MAX_FRAMES,
MINIMAX_MUSIC_MAX_SECONDS,
audioGenerationPresentation,
+ audioRuntimeNoticeMode,
canTransitionAudioMode,
exactGgufLoadSelector,
expectedGgufDownloadBytes,
@@ -847,3 +848,34 @@ test("trained speech checkpoints are offered only on Speak and Music", () => {
/ttsWorkflow !== "speak" && ttsWorkflow !== "music"\s*\?\s*\[\]\s*:\s*trainedTtsModels\.filter\(/,
);
});
+
+test("the outdated-runtime notice offers the in-app update only to the owner", () => {
+ const mode = (isOwner: boolean, offered: boolean, applying = false, checked = true) =>
+ audioRuntimeNoticeMode({ isOwner, offered, applying, checked });
+ assert.equal(mode(true, true), "update");
+ // A running job, started here or from the update card.
+ assert.equal(mode(true, true, true), "updating");
+ assert.equal(mode(true, false, true), "updating");
+ // A skipped offer (checks disabled, no bundle, no installer) or an older backend.
+ assert.equal(mode(true, false), "cli");
+ // Before the status loads the offer is unknown: no CLI instruction yet.
+ assert.equal(mode(true, false, false, false), "checking");
+ assert.equal(mode(false, false, false, false), "ask_owner");
+ // POST /api/llama/update is owner-only.
+ assert.equal(mode(false, true), "ask_owner");
+ assert.equal(mode(false, false, true), "ask_owner");
+});
+
+// The card, or another tab, can run the update without this notice's own click,
+// so the page refreshes from the followed job or from the offer disappearing,
+// and stays on "updating" until that refresh has re-read the runtime.
+test("the outdated-runtime notice refreshes the page however the update ran", () => {
+ const notice = readSrc("features/audio/components/audio-runtime-update-notice.tsx");
+ assert.match(notice, /const offerWithdrawn = wasOffered\.current && !offered;/);
+ assert.match(
+ notice,
+ /if \(followedJob\.current \|\| offerWithdrawn\) \{\s*followedJob\.current = false;\s*setRefreshing\(true\);\s*void onUpdated\(\)\.finally\(\(\) => setRefreshing\(false\)\);/,
+ );
+ assert.match(notice, /applying: applying \|\| refreshing,/);
+ assert.doesNotMatch(notice, /toast\.success\([^;]*;\s*onUpdated\(\)/);
+});
diff --git a/studio/frontend/tests/llama-job-lifecycle.test.ts b/studio/frontend/tests/llama-job-lifecycle.test.ts
index cdd1d10d267..f4a2a09beed 100644
--- a/studio/frontend/tests/llama-job-lifecycle.test.ts
+++ b/studio/frontend/tests/llama-job-lifecycle.test.ts
@@ -226,33 +226,63 @@ test("a muted card stays muted for a job it never showed", () => {
// Both components can be pending at once and the backend names only one, so the
// switch of the one it did not name had nothing to answer for.
test("the card shows the offer the switches allow", () => {
- const on = { llama: true, whisper: true };
- const bothStale = { llama: true, whisper: true };
+ const on = { llama: true, whisper: true, audio: false };
+ const bothStale = { llama: true, whisper: true, audio: false };
assert.equal(updateBannerComponent("llama.cpp", bothStale, on), "llama.cpp");
assert.equal(updateBannerComponent("whisper.cpp", bothStale, on), "whisper.cpp");
// llama.cpp muted, whisper.cpp on, both pending: show the one asked for.
assert.equal(
- updateBannerComponent("llama.cpp", bothStale, { llama: false, whisper: true }),
+ updateBannerComponent("llama.cpp", bothStale, { llama: false, whisper: true, audio: false }),
"whisper.cpp",
);
// And the reverse: a llama.cpp backend migration is named whisper.cpp when
// whisper is stale as well, so it needs the same swap back.
assert.equal(
- updateBannerComponent("whisper.cpp", bothStale, { llama: true, whisper: false }),
+ updateBannerComponent("whisper.cpp", bothStale, { llama: true, whisper: false, audio: false }),
"llama.cpp",
);
// Nothing to swap to when the other component has no offer.
assert.equal(
updateBannerComponent(
"llama.cpp",
- { llama: true, whisper: false },
- { llama: false, whisper: true },
+ { llama: true, whisper: false, audio: false },
+ { llama: false, whisper: true, audio: false },
),
"llama.cpp",
);
// Both muted: the name the backend gave stands, and the card stays hidden.
assert.equal(
- updateBannerComponent("llama.cpp", bothStale, { llama: false, whisper: false }),
+ updateBannerComponent("llama.cpp", bothStale, { llama: false, whisper: false, audio: false }),
+ "llama.cpp",
+ );
+});
+
+// audio.cpp is named only when llama.cpp and whisper.cpp are not pending.
+test("an audio.cpp offer joins the switch fallback", () => {
+ const allOn = { llama: true, whisper: true, audio: true };
+ const audioOnly = { llama: false, whisper: false, audio: true };
+ assert.equal(updateBannerComponent("audio.cpp", audioOnly, allOn), "audio.cpp");
+ // Its own switch off and nothing else pending: the name stands, the card stays hidden.
+ assert.equal(
+ updateBannerComponent("audio.cpp", audioOnly, { llama: true, whisper: true, audio: false }),
+ "audio.cpp",
+ );
+ // whisper.cpp named and muted, audio.cpp pending and allowed: show audio.cpp.
+ assert.equal(
+ updateBannerComponent(
+ "whisper.cpp",
+ { llama: false, whisper: true, audio: true },
+ { llama: true, whisper: false, audio: true },
+ ),
+ "audio.cpp",
+ );
+ // llama.cpp is preferred over audio.cpp when both could stand in.
+ assert.equal(
+ updateBannerComponent(
+ "whisper.cpp",
+ { llama: true, whisper: true, audio: true },
+ { llama: true, whisper: false, audio: true },
+ ),
"llama.cpp",
);
});
@@ -265,8 +295,21 @@ test("a finished update reports the release its card advertised", () => {
"v1.9.4-unsloth.4",
);
assert.equal(updateToastTag("llama.cpp", "b11100", "b11100"), "b11100");
+ assert.equal(
+ updateToastTag("audio.cpp", "b11100", "v0.9.0-unsloth.1"),
+ "v0.9.0-unsloth.1",
+ );
// Either side falls back to the other rather than reporting nothing.
assert.equal(updateToastTag("whisper.cpp", "b11100", null), "b11100");
assert.equal(updateToastTag("llama.cpp", null, "b11100"), "b11100");
assert.equal(updateToastTag("llama.cpp", null, null), null);
});
+
+// The chat "Update llama.cpp" button rides the shared update item, whose
+// update_available is the union: a whisper.cpp or audio.cpp offer alone must not
+// show it for a llama.cpp build that is current.
+test("chat settings offer the llama.cpp update only for a llama.cpp release", () => {
+ const sheet = readSrc("features/chat/chat-settings-sheet.tsx");
+ assert.match(sheet, /mtpUpdatable && llamaUpdateStatus\?\.llama\.update_available/);
+ assert.doesNotMatch(sheet, /llamaUpdateStatus\?\.update_available/);
+});
diff --git a/studio/frontend/tests/llama-update-offer-key.test.ts b/studio/frontend/tests/llama-update-offer-key.test.ts
new file mode 100644
index 00000000000..a1f1f478791
--- /dev/null
+++ b/studio/frontend/tests/llama-update-offer-key.test.ts
@@ -0,0 +1,68 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import * as lifecycle from "../src/lib/llama-job-lifecycle.ts";
+import type * as HookModule from "../src/hooks/use-llama-update-check.ts";
+import { loadWithStubs } from "./helpers/module-stubs.ts";
+
+const { offerKey } = loadWithStubs<typeof HookModule>(
+ new URL("../src/hooks/use-llama-update-check.ts", import.meta.url),
+ {
+ react: {},
+ "@/features/auth": {
+ authFetch: async () => null,
+ getAuthToken: () => null,
+ },
+ "@/hooks/use-hardware-info": { refreshHardwareInfo: async () => {} },
+ "@/lib/llama-job-events": {
+ signalRunningLlamaJob() {},
+ subscribeToLlamaJobStarted: () => () => {},
+ },
+ "@/lib/llama-job-lifecycle": lifecycle,
+ },
+);
+
+const none: HookModule.ComponentOffer = {
+ update_available: false,
+ installed_tag: null,
+ latest_tag: null,
+ update_size_bytes: null,
+};
+
+function status(audio: HookModule.ComponentOffer | null) {
+ return {
+ llama: {
+ ...none,
+ update_available: true,
+ installed_tag: "b1",
+ latest_tag: "b2",
+ },
+ whisper: null,
+ audio,
+ backend_migration_available: false,
+ } as unknown as HookModule.LlamaUpdateStatus;
+}
+
+test("an audio.cpp offer changes the suppression key, so a dismissed llama offer does not hide it", () => {
+ const audio = {
+ ...none,
+ update_available: true,
+ installed_tag: "v0.8.2",
+ latest_tag: "v0.9.0",
+ };
+ assert.notEqual(offerKey(status(audio)), offerKey(status(null)));
+ assert.notEqual(
+ offerKey(status(audio)),
+ offerKey(status({ ...audio, latest_tag: "v0.9.1" })),
+ );
+});
+
+test("without an audio.cpp offer the key matches keys stored before audio joined the card", () => {
+ assert.equal(
+ offerKey(status(null)),
+ JSON.stringify({ llama: ["b1", "b2"], whisper: null, migration: null }),
+ );
+ assert.equal(offerKey(status({ ...none })), offerKey(status(null)));
+});
diff --git a/tests/studio/install/test_install_audio_cpp_prebuilt_logic.py b/tests/studio/install/test_install_audio_cpp_prebuilt_logic.py
index da1661f413a..8197ac035f9 100644
--- a/tests/studio/install/test_install_audio_cpp_prebuilt_logic.py
+++ b/tests/studio/install/test_install_audio_cpp_prebuilt_logic.py
@@ -672,6 +672,35 @@ def test_a_download_that_does_not_hash_to_the_pin_is_refused(monkeypatch, tmp_pa
assert not (tmp_path / "audio.cpp").exists()
+OLD_TAG = "v0.8.2-audio8-perf-hotfix-unsloth.1"
+
+
+def _installed_at_an_older_release(monkeypatch, tmp_path, pins):
+ """What the in-app update replaces: a Studio-managed tree of a release this Studio no longer pins."""
+ old = _release(tmp_path, f"audio-{OLD_TAG}-bin-windows-x64-cpu-portable.zip", tag = OLD_TAG)
+ _install(monkeypatch, tmp_path, old, pins)
+ return tmp_path / "audio.cpp"
+
+
+def test_an_older_release_is_replaced_by_the_pinned_one(monkeypatch, tmp_path, pins):
+ root = _installed_at_an_older_release(monkeypatch, tmp_path, pins)
+ server = _install(monkeypatch, tmp_path, _release(tmp_path, CPU_ZIP), pins)
+ record = json.loads((root / M.INSTALL_RECORD).read_text())
+ assert (record["release_tag"], record["asset"]) == (FORK_TAG, CPU_ZIP)
+ assert server.read_bytes() == b"binary " + CPU_ZIP.encode()
+
+
+def test_an_update_that_fails_its_pin_leaves_the_older_tree(monkeypatch, tmp_path, pins):
+ root = _installed_at_an_older_release(monkeypatch, tmp_path, pins)
+ before = _tree_digest(root)
+ release = _release(tmp_path, CPU_ZIP)
+ release["assets"][0]["digest"] = None
+ pins[(FORK, FORK_TAG, CPU_ZIP)] = "0" * 64
+ with pytest.raises(RuntimeError, match = "sha256 mismatch"):
+ _install(monkeypatch, tmp_path, release)
+ assert _tree_digest(root) == before
+
+
def test_the_pins_file_covers_both_default_releases():
table = M.load_pins()
for repo, tag in (