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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Honor Voice Settings device preference for STT API loads (#15284)
Indrajit swain2099086d8598
diff --git a/studio/backend/core/inference/audio_device.py b/studio/backend/core/inference/audio_device.pyindex 8bc831fbfe4..f2064989c5b 100644--- a/studio/backend/core/inference/audio_device.py+++ b/studio/backend/core/inference/audio_device.py@@ -13,9 +13,12 @@ from typing import Optional__all__ = ["AUDIO_DEVICE_CHOICES","audio_device_default",+ "audio_device_env_locked","audio_device_forces_cpu","mask_accelerators_for_cpu_audio","normalize_audio_device",+ "stt_device_default",+ "stt_device_forces_cpu",]AUDIO_DEVICE_CHOICES = ("auto", "cpu", "gpu")@@ -46,6 +49,29 @@ def audio_device_default() -> str:return normalize_audio_device(os.environ.get("UNSLOTH_AUDIO_DEVICE"))+def audio_device_env_locked() -> bool:+ """Whether ``UNSLOTH_AUDIO_DEVICE`` names a device, which Settings then cannot override."""+ return bool(str(os.environ.get("UNSLOTH_AUDIO_DEVICE") or "").strip())+++def stt_device_default() -> str:+ """Use the saved STT choice unless the environment overrides it; TTS is unaffected."""+ if audio_device_env_locked():+ return audio_device_default()+ try:+ from utils.stt_device_settings import get_stored_stt_device+ return get_stored_stt_device()+ except Exception: # noqa: BLE001 - store unavailable: detect as before+ return "auto"+++def stt_device_forces_cpu(value: Optional[str]) -> bool:+ """``audio_device_forces_cpu`` with ``None`` read through ``stt_device_default``."""+ if value is None:+ return stt_device_default() == "cpu"+ return normalize_audio_device(value) == "cpu"++def audio_device_forces_cpu(value: Optional[str]) -> bool:"""None falls back to the environment default, so older callers still honour a server-wide setting."""if value is None:diff --git a/studio/backend/core/inference/stt_audiocpp_sidecar.py b/studio/backend/core/inference/stt_audiocpp_sidecar.pyindex a980bd9af4c..7d2ef87dc82 100644--- a/studio/backend/core/inference/stt_audiocpp_sidecar.py+++ b/studio/backend/core/inference/stt_audiocpp_sidecar.py@@ -885,7 +885,7 @@ class AudioCppSttSidecar:on_phase: Optional[Callable[[str], None]] = None,) -> None:"""A server already holding the aligner keeps it for untimestamped requests (no restart)."""- from core.inference.audio_device import audio_device_forces_cpu+ from core.inference.audio_device import stt_device_forces_cpuif request_cancel_event is not None and request_cancel_event.is_set():raise SttTranscriptionCancelledError("Transcription cancelled.")@@ -900,7 +900,7 @@ class AudioCppSttSidecar:force_cpu = (self._forced_cpuif device is None and self._server_alive()- else audio_device_forces_cpu(device)+ else stt_device_forces_cpu(device))if (self._server_alive()diff --git a/studio/backend/core/inference/stt_ggml_sidecar.py b/studio/backend/core/inference/stt_ggml_sidecar.pyindex 1e086818eed..1219bc8365a 100644--- a/studio/backend/core/inference/stt_ggml_sidecar.py+++ b/studio/backend/core/inference/stt_ggml_sidecar.py@@ -923,7 +923,7 @@ class GgmlSttSidecar:) -> None:"""A None device keeps the running server's placement, so a caller that sends none cannotmove it."""- from core.inference.audio_device import audio_device_forces_cpu+ from core.inference.audio_device import stt_device_forces_cpuif request_cancel_event is not None and request_cancel_event.is_set():raise SttTranscriptionCancelledError("Transcription cancelled.")@@ -937,7 +937,7 @@ class GgmlSttSidecar:force_cpu = (self._forced_cpuif device is None and self._process_alive()- else audio_device_forces_cpu(device)+ else stt_device_forces_cpu(device))if (self._process_alive()diff --git a/studio/backend/core/inference/stt_mtmd_sidecar.py b/studio/backend/core/inference/stt_mtmd_sidecar.pyindex da282497c31..0c3c3ca7774 100644--- a/studio/backend/core/inference/stt_mtmd_sidecar.py+++ b/studio/backend/core/inference/stt_mtmd_sidecar.py@@ -885,7 +885,7 @@ class MtmdSttSidecar:path_revision: Optional[int] = None,device: Optional[str] = None,) -> None:- from core.inference.audio_device import audio_device_forces_cpu+ from core.inference.audio_device import stt_device_forces_cpuif path_revision is None:from utils.llama_cpp_path_settings import custom_llama_cpp_path_revision@@ -894,10 +894,10 @@ class MtmdSttSidecar:# None is no opinion: a caller sending none cannot move the server.if device is None:forced_cpu = (- self._forced_cpu if self._process_alive() else audio_device_forces_cpu(None)+ self._forced_cpu if self._process_alive() else stt_device_forces_cpu(None))else:- forced_cpu = audio_device_forces_cpu(device)+ forced_cpu = stt_device_forces_cpu(device)# Both mean "no offload", which _gpu_disabled already tracks.training = _training_active() or forced_cpuif (diff --git a/studio/backend/core/inference/stt_sidecar.py b/studio/backend/core/inference/stt_sidecar.pyindex 0a67c304108..3879bbce0f8 100644--- a/studio/backend/core/inference/stt_sidecar.py+++ b/studio/backend/core/inference/stt_sidecar.py@@ -1460,14 +1460,14 @@ class WhisperSttSidecar:):"""An explicit device differing from the resident one reloads the model; None keeps what isresident."""- from core.inference.audio_device import audio_device_default, normalize_audio_device+ from core.inference.audio_device import normalize_audio_device, stt_device_defaultif request_cancel_event is not None and request_cancel_event.is_set():raise SttTranscriptionCancelledError("Transcription cancelled.")model_id = resolve_model_id(model)# None means no opinion, not auto: do not move a model another surface placed.requested = None if device is None else normalize_audio_device(device)- preference = audio_device_default() if requested is None else requested+ preference = stt_device_default() if requested is None else requestedwith self._lock:if request_cancel_event is not None and request_cancel_event.is_set():raise SttTranscriptionCancelledError("Transcription cancelled.")diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 5f04c56e0d1..7e84b2e53e1 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -24710,6 +24710,7 @@ async def openai_audio_transcriptions(provider_id: Optional[str] = Form(None),encrypted_api_key: Optional[str] = Form(None),timestamp_granularities: Optional[list[str]] = Form(None, alias = "timestamp_granularities[]"),+ device: Optional[Literal["auto", "cpu", "gpu"]] = Form(None),current_subject: str = Depends(get_current_subject),):"""OpenAI-compatible speech-to-text (POST /v1/audio/transcriptions).@@ -24718,7 +24719,8 @@ async def openai_audio_transcriptions(Otherwise ``model`` maps to a sidecar model id, with ``whisper-1`` or nothingselecting the default. ``response_format`` supports ``json``, ``text`` and``verbose_json``; an audio.cpp model also gives segments, words (``timestamp_granularities``)- and ``diarized_json``."""+ and ``diarized_json``. Optional ``device`` (``auto``/``cpu``/``gpu``) places a cold+ load; when omitted, Voice Settings "Load into" / ``UNSLOTH_AUDIO_DEVICE`` apply (#15280)."""fmt = (response_format or "json").strip().lower()if fmt not in ("json", "text", "verbose_json", "diarized_json"):raise HTTPException(@@ -24827,6 +24829,7 @@ async def openai_audio_transcriptions(fast = False,engine = engine,request = request,+ device = device,source_path = path,timestamps = bool(granularities),)@@ -24908,13 +24911,15 @@ async def openai_audio_translations(model: Optional[str] = Form(None),response_format: str = Form("json"),provider_id: Optional[str] = Form(None),+ device: Optional[Literal["auto", "cpu", "gpu"]] = Form(None),current_subject: str = Depends(get_current_subject),):"""OpenAI-compatible speech translation to English (POST /v1/audio/translations).Runs on the local Whisper sidecar; ``whisper-1`` or nothing selects the default model.``response_format`` supports ``json``, ``text`` and ``verbose_json``. ``prompt`` and- ``temperature`` are accepted and ignored."""+ ``temperature`` are accepted and ignored. Optional ``device`` (``auto``/``cpu``/``gpu``)+ matches Voice Settings "Load into" on a cold load (#15280)."""fmt = (response_format or "json").strip().lower()if fmt not in ("json", "text", "verbose_json"):_raise_unsupported_openai_parameter(@@ -24949,7 +24954,13 @@ async def openai_audio_translations(subject = current_subject,) as monitor_id:result = await _transcribe_audio_result(- raw, sidecar_model, None, fast = False, request = request, translate = True+ raw,+ sidecar_model,+ None,+ fast = False,+ request = request,+ device = device,+ translate = True,)text = str(result.get("text", ""))_served_model = str(result.get("model") or "")diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex 590510caf1d..1d2b6fabc36 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -210,6 +210,7 @@ from utils.embedding_model_settings import (set_rag_embedding_model,validate_embedding_model,)+from utils.stt_device_settings import set_stt_devicefrom utils.hf_cache_settings import cache_status, get_hf_cache_paths, set_hf_cache_homefrom utils.llama_cpp_path_settings import (MAX_CUSTOM_LLAMA_CPP_PATH_LENGTH,@@ -3040,6 +3041,31 @@ class EmbeddingDevicePayload(BaseModel):device: Literal["auto", "cpu", "gpu"]+class SttDevicePayload(BaseModel):+ device: Literal["auto", "cpu", "gpu"]+ only_if_unset: bool = False+++class SttDeviceResponse(BaseModel):+ device: Literal["auto", "cpu", "gpu"] = "auto"+ locked: bool = False+ # Distinguishes an unset preference from a saved Auto choice.+ saved: bool = False+++def _stt_device_response() -> SttDeviceResponse:+ from core.inference.audio_device import audio_device_env_locked, stt_device_default+ from utils.stt_device_settings import stt_device_is_saved+ try:+ return SttDeviceResponse(+ device = stt_device_default(), # type: ignore[arg-type]+ locked = audio_device_env_locked(),+ saved = stt_device_is_saved(),+ )+ except Exception: # noqa: BLE001 - probe must never block reading settings+ return SttDeviceResponse()++def _embedding_device_state() -> tuple[str, bool]:from core.rag import config as rag_configtry:@@ -3981,6 +4007,34 @@ def update_embedding_device(return _embedding_model_response()+@_owner_settings_router.get("/stt-device", response_model = SttDeviceResponse)+def get_stt_device_setting(+ current_subject: str = Depends(get_current_subject),+) -> SttDeviceResponse:+ """Voice Settings "Load into": where a cold STT API load places the model (#15280)."""+ return _stt_device_response()+++@_owner_settings_router.put("/stt-device", response_model = SttDeviceResponse)+def update_stt_device_setting(+ payload: SttDevicePayload, current_subject: str = Depends(get_current_subject)+) -> SttDeviceResponse:+ """Persist Voice Settings "Load into" so ``/v1/audio/transcriptions`` honours it on a cold load.++ ``UNSLOTH_AUDIO_DEVICE`` still wins when set. An already-resident model is not moved;+ the next cold load (or an explicit ``device`` on ``/audio/stt/load``) applies the choice.+ """+ from core.inference.audio_device import audio_device_env_locked++ if audio_device_env_locked():+ raise HTTPException(+ status_code = 409, detail = "The STT device is set by UNSLOTH_AUDIO_DEVICE."+ )+ set_stt_device(payload.device, only_if_unset = payload.only_if_unset)+ logger.info("settings.stt_device_updated subject=%s device=%s", current_subject, payload.device)+ return _stt_device_response()++@_owner_settings_router.delete("/embedding-model", response_model = EmbeddingModelResponse)def reset_embedding_model(current_subject: str = Depends(get_current_subject),diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.pyindex 529bb40d658..b7dec809c27 100644--- a/studio/backend/tests/conftest.py+++ b/studio/backend/tests/conftest.py@@ -235,6 +235,18 @@ def _forget_embedding_device_setting():_forget()[email protected](autouse = True)+def _forget_stt_device_setting():+ def _forget():+ settings = sys.modules.get("utils.stt_device_settings")+ if settings is not None:+ settings.forget_cached_stt_device()++ _forget()+ yield+ _forget()++@pytest.fixture(autouse = True)def _no_background_sandbox_probes(monkeypatch):monkeypatch.setenv("UNSLOTH_DISABLE_SANDBOX_WARMUP", "1")diff --git a/studio/backend/tests/test_audio_device_preference.py b/studio/backend/tests/test_audio_device_preference.pyindex cb13f91760e..ad3e56b05fa 100644--- a/studio/backend/tests/test_audio_device_preference.py+++ b/studio/backend/tests/test_audio_device_preference.py@@ -68,6 +68,32 @@ def test_without_the_environment_variable_nothing_is_forced_to_cpu(monkeypatch):assert not audio_device_forces_cpu(None)+def test_saved_voice_settings_device_is_the_stt_default_when_env_is_unset(monkeypatch, tmp_path):+ """Cold /v1/audio/transcriptions must honour Voice Settings "Load into" (#15280)."""+ from core.inference.audio_device import stt_device_default, stt_device_forces_cpu+ from storage import studio_db+ from utils import stt_device_settings as sds++ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(studio_db, "_schema_ready", set())+ monkeypatch.delenv("UNSLOTH_AUDIO_DEVICE", raising = False)+ sds.forget_cached_stt_device()++ assert stt_device_default() == "auto"+ sds.set_stt_device("cpu")+ assert stt_device_default() == "cpu"+ assert stt_device_forces_cpu(None)+ assert not stt_device_forces_cpu("gpu")+ # The STT choice does not move TTS / native audio, which read the env-only default.+ assert audio_device_default() == "auto"+ assert not audio_device_forces_cpu(None)++ # Env still outranks the saved choice (headless/CLI).+ monkeypatch.setenv("UNSLOTH_AUDIO_DEVICE", "auto")+ assert stt_device_default() == "auto"+ assert not stt_device_forces_cpu(None)++def _torch_with_cuda(monkeypatch):"""A torch whose CUDA is available, so anything but CPU is a real choice."""torch = types.SimpleNamespace(diff --git a/studio/backend/tests/test_stt_audiocpp_details.py b/studio/backend/tests/test_stt_audiocpp_details.pyindex 33dc25c3074..1f502454bdd 100644--- a/studio/backend/tests/test_stt_audiocpp_details.py+++ b/studio/backend/tests/test_stt_audiocpp_details.py@@ -598,3 +598,18 @@ def test_training_moves_the_server_only_when_its_placement_changes(training[0] = activeside.transcribe(wav_bytes(), QWEN3, "en")assert len(fake.starts) == (3 if gpu_visible else 1)+++def test_a_device_less_load_follows_the_saved_voice_setting(fake, side, monkeypatch, tmp_path):+ from storage import studio_db++ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))+ monkeypatch.setattr(studio_db, "_schema_ready", set())+ monkeypatch.delenv("UNSLOTH_AUDIO_DEVICE", raising = False)+ studio_db.upsert_app_settings({"stt_device": "cpu"}, read_back = False)+ side.transcribe(wav_bytes(), QWEN3, "en")+ assert side.device == "cpu"+ # None keeps the running server: saving Auto later does not restart it under a caller.+ studio_db.upsert_app_settings({"stt_device": "auto"}, read_back = False)+ side.transcribe(wav_bytes(), QWEN3, "en")+ assert side.device == "cpu" and len(fake.starts) == 1diff --git a/studio/backend/tests/test_stt_device_setting.py b/studio/backend/tests/test_stt_device_setting.pynew file mode 100644index 00000000000..86e6f212806--- /dev/null+++ b/studio/backend/tests/test_stt_device_setting.py@@ -0,0 +1,87 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Voice Settings "Load into" persisted for cold STT API loads (#15280)."""++from pathlib import Path+import sys++import pytest+from fastapi import HTTPException++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++from core.inference import audio_device+from routes import settings as settings_routes+from storage import studio_db+from utils import stt_device_settings as sds++[email protected](autouse = True)+def isolated_home(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(studio_db, "_schema_ready", set())+ monkeypatch.delenv("UNSLOTH_AUDIO_DEVICE", raising = False)+ sds.forget_cached_stt_device()+ yield+ sds.forget_cached_stt_device()+++def _put(device):+ return settings_routes.update_stt_device_setting(+ settings_routes.SttDevicePayload(device = device), current_subject = "owner"+ )+++def test_unset_defaults_to_auto():+ response = settings_routes.get_stt_device_setting(current_subject = "owner")+ assert response.device == "auto"+ assert response.locked is False+ assert response.saved is False+++def test_saving_cpu_is_what_a_device_less_cold_load_uses():+ response = _put("cpu")+ assert response.device == "cpu"+ assert audio_device.stt_device_default() == "cpu"+ assert audio_device.stt_device_forces_cpu(None)+ assert audio_device.audio_device_default() == "auto"+++def test_env_locks_settings(monkeypatch):+ _put("cpu")+ monkeypatch.setenv("UNSLOTH_AUDIO_DEVICE", "gpu")+ with pytest.raises(HTTPException) as raised:+ _put("auto")+ assert raised.value.status_code == 409+ assert audio_device.stt_device_default() == "gpu"+ assert audio_device.audio_device_env_locked() is True+++def test_an_explicit_auto_is_saved_so_another_browser_adopts_it():+ """Unset and a chosen Auto both read as auto, but only a choice stops a browser migrating its own."""+ assert _put("auto").saved is True+ assert settings_routes.get_stt_device_setting(current_subject = "owner").device == "auto"+ assert _put("cpu").saved is True+++def test_delayed_browser_migration_keeps_a_newer_explicit_choice():+ assert settings_routes.get_stt_device_setting(current_subject = "owner").saved is False+ _put("auto")+ response = settings_routes.update_stt_device_setting(+ settings_routes.SttDevicePayload(device = "cpu", only_if_unset = True),+ current_subject = "owner",+ )+ assert response.device == "auto"+ assert audio_device.stt_device_default() == "auto"+++def test_initial_browser_migration_saves_cpu():+ response = settings_routes.update_stt_device_setting(+ settings_routes.SttDevicePayload(device = "cpu", only_if_unset = True),+ current_subject = "owner",+ )+ assert response.device == "cpu"+ assert response.saved is Truediff --git a/studio/backend/utils/stt_device_settings.py b/studio/backend/utils/stt_device_settings.pynew file mode 100644index 00000000000..90f663ecfe1--- /dev/null+++ b/studio/backend/utils/stt_device_settings.py@@ -0,0 +1,79 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Persist STT placement for device-less API loads (#15280)."""++from __future__ import annotations++import threading+import time+from typing import Optional++STT_DEVICE_SETTING_KEY = "stt_device"+STT_DEVICE_CHOICES = ("auto", "cpu", "gpu")++_CACHE_TTL_S = 2.0+_device_cached: list = [] # [(monotonic time, value)]+_device_generation = 0+_lock = threading.Lock()+++def _stored_stt_device() -> Optional[str]:+ now = time.monotonic()+ with _lock:+ if _device_cached and now - _device_cached[0][0] < _CACHE_TTL_S:+ return _device_cached[0][1]+ gen = _device_generation+ from utils.account_context import OWNER, bind_account, reset_account++ token = bind_account(OWNER)+ try:+ from storage.studio_db import get_app_setting+ value = get_app_setting(STT_DEVICE_SETTING_KEY, None)+ except Exception: # noqa: BLE001 - store unavailable: hardware default+ value = None+ finally:+ reset_account(token)+ device = value if value in STT_DEVICE_CHOICES else None+ with _lock:+ if _device_generation == gen:+ _device_cached[:] = [(now, device)]+ return device+++def get_stored_stt_device() -> str:+ """Voice Settings placement: ``auto`` when unset, unreadable or unrecognized."""+ return _stored_stt_device() or "auto"+++def stt_device_is_saved() -> bool:+ """Whether a choice was ever saved, so a browser knows to adopt it rather than migrate its own."""+ return _stored_stt_device() is not None+++def forget_cached_stt_device() -> None:+ global _device_generation+ with _lock:+ _device_cached.clear()+ _device_generation += 1+++def set_stt_device(device: str, *, only_if_unset: bool = False) -> bool:+ """Persist placement; returns whether it changed."""+ if device not in STT_DEVICE_CHOICES:+ raise ValueError("Device must be auto, cpu or gpu.")+ forget_cached_stt_device()+ if _stored_stt_device() == device:+ return False+ from storage.studio_db import compare_and_set_app_setting, upsert_app_settings+ from utils.account_context import OWNER, bind_account, reset_account++ token = bind_account(OWNER)+ try:+ if only_if_unset:+ return compare_and_set_app_setting(STT_DEVICE_SETTING_KEY, None, device)+ upsert_app_settings({STT_DEVICE_SETTING_KEY: device}, read_back = False)+ finally:+ reset_account(token)+ forget_cached_stt_device()+ return Truediff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsxindex 8ecd286bf02..ed7f015896a 100644--- a/studio/frontend/src/app/routes/__root.tsx+++ b/studio/frontend/src/app/routes/__root.tsx@@ -58,7 +58,9 @@ import {useSettingsDialogStore,useShortcut,useShortcutAvailable,+ useVoiceSettingsStore,} from "@/features/settings";+import { reconcileSttDevicePreference } from "@/features/settings/api/stt-device";import { useLowDiskNotice } from "@/features/settings/hooks/use-low-disk-notice";import { useTrainingUnloadGuard } from "@/features/training";import { TransformersUpgradeDialog } from "@/features/transformers-upgrade";@@ -245,6 +247,21 @@ function PersonalizationSyncMount() {return null;}+// Voice Settings "Load into" kept in step with the server copy that device-less STT API loads read (#15280). Here,+// not on store rehydrate: the store loads at startup, before the desktop backend port is known and before sign-in.+function SttDeviceSyncMount() {+ useRouterState({ select: (s) => s.location.pathname });+ const settled = hasSettledAuthSession();+ useEffect(() => {+ if (!settled) return;+ void reconcileSttDevicePreference(+ useVoiceSettingsStore.getState().sttDevice,+ (sttDevice) => useVoiceSettingsStore.setState({ sttDevice }),+ );+ }, [settled]);+ return null;+}+// A full disk is not a training problem, so the warning cannot live on the// training route: it belongs to whichever route the user happens to be on when// space runs out. Mounted here it subscribes once for the session, and stays@@ -703,6 +720,7 @@ function RootLayout() {const content = (<><PersonalizationSyncMount />+ <SttDeviceSyncMount /><InterfaceZoom /><WindowMaterialMount /><ReloadSnapshotPrivacy />diff --git a/studio/frontend/src/features/settings/api/stt-device.ts b/studio/frontend/src/features/settings/api/stt-device.tsnew file mode 100644index 00000000000..a30ba195bc6--- /dev/null+++ b/studio/frontend/src/features/settings/api/stt-device.ts@@ -0,0 +1,65 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// The module, not the barrel: the barrel pulls in page components the store tests cannot load.+import { authFetch } from "@/features/auth/api";+import type { SttDevice } from "../stores/voice-settings-store";++type SttDeviceState = { device: SttDevice | "gpu"; saved?: boolean };++// Serialize saves so the last choice lands last.+let pending: Promise<unknown> = Promise.resolve();+// Bumped per save, so a read that started before one is not applied after it.+let revision = 0;++export function syncSttDevicePreference(+ device: SttDevice,+ onlyIfUnset = false,+ adopt?: (device: SttDevice) => void,+): void {+ const saving = ++revision;+ pending = pending+ .then(async () => {+ const response = await authFetch("/api/settings/stt-device", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ device,+ ...(onlyIfUnset ? { only_if_unset: true } : {}),+ }),+ });+ if (onlyIfUnset && response.ok) {+ const state = (await response.json()) as SttDeviceState;+ if (revision === saving && state.device !== device) {+ adopt?.(state.device === "cpu" ? "cpu" : "auto");+ }+ }+ })+ .catch(() => undefined);+}++// Adopt a saved server choice; otherwise migrate the local choice.+export async function reconcileSttDevicePreference(+ local: SttDevice,+ adopt: (device: SttDevice) => void,+): Promise<void> {+ const started = revision;+ try {+ await pending;+ const response = await authFetch("/api/settings/stt-device");+ if (!response.ok) {+ return;+ }+ const state = (await response.json()) as SttDeviceState;+ if (revision !== started) {+ return;+ }+ if (state.saved) {+ adopt(state.device === "cpu" ? "cpu" : "auto");+ } else if (local !== "auto") {+ syncSttDevicePreference(local, true, adopt);+ }+ } catch {+ // Offline or not the owner: the local choice still drives this browser's own loads.+ }+}diff --git a/studio/frontend/src/features/settings/stores/voice-settings-store.ts b/studio/frontend/src/features/settings/stores/voice-settings-store.tsindex f34d435f6ee..56b45e715b9 100644--- a/studio/frontend/src/features/settings/stores/voice-settings-store.ts+++ b/studio/frontend/src/features/settings/stores/voice-settings-store.ts@@ -14,6 +14,7 @@ import {type SttModel,migrateVoiceSettings,} from "./stt-model-catalog";+import { syncSttDevicePreference } from "../api/stt-device";export * from "./stt-model-catalog";@@ -236,7 +237,12 @@ export const useVoiceSettingsStore = create<VoiceSettingsState>()(setSttGgufVariant: (sttGgufVariant) => set({ sttGgufVariant }),sttDevice: DEFAULT_STT_DEVICE,- setSttDevice: (value) => set({ sttDevice: normalizeSttDevice(value) }),+ setSttDevice: (value) => {+ const sttDevice = normalizeSttDevice(value);+ set({ sttDevice });+ // Server default for cold /v1/audio/transcriptions loads (#15280).+ syncSttDevicePreference(sttDevice);+ },sttProviderId: "",setSttProviderId: (sttProviderId) => set({ sttProviderId }),diff --git a/studio/frontend/tests/stt-device-reconcile.test.ts b/studio/frontend/tests/stt-device-reconcile.test.tsnew file mode 100644index 00000000000..aa0a05d7319--- /dev/null+++ b/studio/frontend/tests/stt-device-reconcile.test.ts@@ -0,0 +1,153 @@+// 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 { register } from "node:module";+import test from "node:test";++register("./helpers/settings-api-resolver.mjs", import.meta.url);+// stt-device.ts takes authFetch from the module, not the barrel the shared resolver stubs.+const STUB = new URL("./helpers/auth-stub.mjs", import.meta.url).href;+register(+ `data:text/javascript,export function resolve(s, c, n) { return n(s === "@/features/auth/api" ? ${JSON.stringify(STUB)} : s, c); }`,+);++type Call = { method: string; device?: string };++function fakeServer(state: { device: string; saved: boolean }) {+ const calls: Call[] = [];+ globalThis.fetch = (async (_url: string, init?: RequestInit) => {+ const method = init?.method ?? "GET";+ if (method === "PUT") {+ const { device } = JSON.parse(String(init?.body));+ calls.push({ method, device });+ Object.assign(state, { device, saved: true });+ } else {+ calls.push({ method });+ }+ return new Response(JSON.stringify(state), { status: 200 });+ }) as typeof fetch;+ return calls;+}++const { reconcileSttDevicePreference, syncSttDevicePreference } = await import(+ "../src/features/settings/api/stt-device.ts"+);++async function settle() {+ for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0));+}++test("a saved server choice wins over this browser's and is not sent back", async () => {+ for (const [server, local] of [+ ["cpu", "auto"],+ ["auto", "cpu"],+ ] as const) {+ const calls = fakeServer({ device: server, saved: true });+ let adopted: string | null = null;+ await reconcileSttDevicePreference(local, (d) => {+ adopted = d;+ });+ await settle();+ assert.equal(adopted, server);+ assert.deepEqual(calls, [{ method: "GET" }]);+ }+});++test("with nothing saved, a non-default local choice migrates and Auto sends nothing", async () => {+ let calls = fakeServer({ device: "auto", saved: false });+ await reconcileSttDevicePreference("cpu", () => assert.fail("nothing to adopt"));+ await settle();+ assert.deepEqual(calls, [{ method: "GET" }, { method: "PUT", device: "cpu" }]);++ calls = fakeServer({ device: "auto", saved: false });+ await reconcileSttDevicePreference("auto", () => assert.fail("nothing to adopt"));+ await settle();+ assert.deepEqual(calls, [{ method: "GET" }]);+});++test("quick changes reach the server in order", async () => {+ const state = { device: "cpu", saved: true };+ const calls: Call[] = [];+ const resolvers: (() => void)[] = [];+ globalThis.fetch = (async (_url: string, init?: RequestInit) => {+ const { device } = JSON.parse(String(init?.body));+ calls.push({ method: "PUT", device });+ if (calls.length === 1) await new Promise<void>((r) => resolvers.push(r));+ state.device = device;+ return new Response(JSON.stringify(state), { status: 200 });+ }) as typeof fetch;+ syncSttDevicePreference("auto");+ syncSttDevicePreference("cpu");+ await settle();+ assert.equal(calls.length, 1);+ resolvers[0]();+ await settle();+ assert.deepEqual(calls.map((c) => c.device), ["auto", "cpu"]);+ assert.equal(state.device, "cpu");+});++test("a choice made while the sign-in read is in flight is not undone", async () => {+ for (const saved of [true, false]) {+ const state = { device: "auto", saved };+ const calls: Call[] = [];+ let release: () => void = () => {};+ globalThis.fetch = (async (_url: string, init?: RequestInit) => {+ const method = init?.method ?? "GET";+ if (method === "GET") {+ const snapshot = JSON.stringify(state);+ calls.push({ method });+ await new Promise<void>((r) => {+ release = r;+ });+ return new Response(snapshot, { status: 200 });+ }+ const { device } = JSON.parse(String(init?.body));+ calls.push({ method, device });+ Object.assign(state, { device, saved: true });+ return new Response(JSON.stringify(state), { status: 200 });+ }) as typeof fetch;+ let adopted: string | null = null;+ const done = reconcileSttDevicePreference("cpu", (d) => {+ adopted = d;+ });+ await settle();+ syncSttDevicePreference(saved ? "cpu" : "auto");+ await settle();+ release();+ await done;+ await settle();+ assert.equal(adopted, null);+ assert.equal(state.device, saved ? "cpu" : "auto");+ }+});++test("a delayed migration adopts a newer choice saved by another browser", async () => {+ const state = { device: "auto", saved: false };+ let release: () => void = () => {};+ let adopted: string | null = null;+ globalThis.fetch = (async (_url: string, init?: RequestInit) => {+ if ((init?.method ?? "GET") === "GET") {+ const snapshot = JSON.stringify(state);+ await new Promise<void>((resolve) => {+ release = resolve;+ });+ return new Response(snapshot, { status: 200 });+ }+ const { device, only_if_unset } = JSON.parse(String(init?.body));+ if (!only_if_unset || !state.saved) {+ Object.assign(state, { device, saved: true });+ }+ return new Response(JSON.stringify(state), { status: 200 });+ }) as typeof fetch;+ const migration = reconcileSttDevicePreference("cpu", (device) => {+ adopted = device;+ });+ await settle();+ Object.assign(state, { device: "auto", saved: true });+ release();+ await migration;+ await settle();+ assert.equal(state.device, "auto");+ assert.equal(adopted, "auto");+});diff --git a/studio/frontend/tests/voice-stt-device-control.test.ts b/studio/frontend/tests/voice-stt-device-control.test.tsindex 305f3326822..c83ff11d004 100644--- a/studio/frontend/tests/voice-stt-device-control.test.ts+++ b/studio/frontend/tests/voice-stt-device-control.test.ts@@ -8,6 +8,9 @@ import { readSrc } from "./helpers/kit.ts";const voiceTab = readSrc("features/settings/tabs/voice-tab.tsx");const adapter = readSrc("features/chat/adapters/studio-model-dictation-adapter.ts");+const voiceStore = readSrc("features/settings/stores/voice-settings-store.ts");+const sttDeviceApi = readSrc("features/settings/api/stt-device.ts");+const root = readSrc("app/routes/__root.tsx");test("changing the dictation device releases only this tab's model", () => {// Unscoped, the unload can tear down a model this tab never owned.@@ -39,3 +42,24 @@ test("the device preference travels with every load and transcribe", () => {/params\.set\("device", options\.device \?\? settings\.sttDevice\)/,);});++test("Load into is synced to the server for cold API STT loads", () => {+ assert.match(sttDeviceApi, /\/api\/settings\/stt-device/);+ assert.match(sttDeviceApi, /from "@\/features\/auth\/api"/);+ assert.match(sttDeviceApi, /pending = pending\s*\.then\(/);+ assert.match(+ voiceStore,+ /set\(\{ sttDevice \}\);\s*\/\/[^\n]*\n\s*syncSttDevicePreference\(sttDevice\)/,+ );+ assert.doesNotMatch(voiceStore, /onRehydrateStorage/);+ assert.match(+ root,+ /function SttDeviceSyncMount[\s\S]*?hasSettledAuthSession\(\)[\s\S]*?if \(!settled\) return;[\s\S]*?reconcileSttDevicePreference\(/,+ );+ assert.match(root, /useVoiceSettingsStore\.setState\(\{ sttDevice \}\)/);+ assert.match(+ sttDeviceApi,+ /if \(state\.saved\) \{\s*adopt\([\s\S]*?else if \(local !== "auto"\) \{\s*syncSttDevicePreference\(local[,)]/,+ );+ assert.match(root, /<SttDeviceSyncMount \/>/);+});