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
Studio: support external OpenAI-compatible TTS endpoints for Read Aloud (#9214)
Nilaya39638feb46c
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.pyindex 08a8ac6c48a..bfc1bb63923 100644--- a/studio/backend/core/inference/external_provider.py+++ b/studio/backend/core/inference/external_provider.py@@ -14,7 +14,7 @@ import mimetypesimport reimport timefrom typing import Any, AsyncGenerator, Literal, NamedTuple, Optional, Union-from urllib.parse import urlparse+from urllib.parse import urlparse, urlsplit, urlunsplitimport httpximport structlog@@ -54,6 +54,13 @@ _USAGE_STREAM_OPTION_PROVIDERS = frozenset({"vllm", "openrouter", "kimi"})logger = structlog.get_logger(__name__)+def _append_provider_path(base_url: str, endpoint: str) -> str:+ """Append an API path without moving it behind a base URL's query string."""+ parts = urlsplit(base_url)+ path = f"{parts.path.rstrip('/')}/{endpoint.lstrip('/')}"+ return urlunsplit((parts.scheme, parts.netloc, path, parts.query, parts.fragment))++def _is_openai_family_cloud(base_url: Optional[str]) -> bool:"""True iff ``base_url`` points at OpenAI cloud or Azure OpenAI Foundry.@@ -6278,6 +6285,34 @@ class ExternalProviderClient:response.raise_for_status()return response.json()+ async def create_speech(+ self,+ text: str,+ model: str,+ voice: Optional[str] = None,+ response_format: str = "wav",+ speed: Optional[float] = None,+ ) -> tuple[bytes, str]:+ """POST /audio/speech (OpenAI CreateSpeech). Returns (audio_bytes, media_type)."""+ body: dict[str, Any] = {+ "model": model,+ "input": text,+ "response_format": response_format,+ }+ if voice:+ body["voice"] = voice+ if speed is not None:+ body["speed"] = speed+ response = await _http_client.post(+ _append_provider_path(self.base_url, "/audio/speech"),+ headers = self._auth_headers(),+ json = body,+ timeout = self._timeout,+ )+ response.raise_for_status()+ media_type = (response.headers.get("content-type") or "").split(";")[0].strip()+ return response.content, media_type or f"audio/{response_format}"+async def create_transcription(self,audio: bytes,diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex be57f7d0212..c9c70556fc1 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -3843,6 +3843,21 @@ class AudioSpeechRequest(BaseModel):"wav", description = "Output container. Only 'wav' is supported.")speed: Optional[float] = Field(None, description = "Speech rate (accepted, unused).")+ provider_id: Optional[str] = Field(+ None,+ description = "[x-unsloth] Saved connection ID. When set, synthesis is proxied to that "+ "provider's /audio/speech and model/voice/speed are forwarded as sent.",+ )+ provider_base_url: Optional[str] = Field(+ None,+ description = "[x-unsloth] Browser-snapshotted connection base URL. Required with a "+ "legacy encrypted_api_key so an edit cannot route that key to another endpoint.",+ )+ encrypted_api_key: Optional[str] = Field(+ None,+ description = "[x-unsloth] Per-request key for a browser still holding a legacy "+ "provider key, used when the connection has none saved server side.",+ )@field_validator("response_format", mode = "before")@classmethoddiff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex b76fbe739fa..c44febb8916 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -12318,6 +12318,109 @@ async def generate_audio()+async def _external_tts_speech(body: AudioSpeechRequest, request: Request) -> Response:+ """Proxy CreateSpeech to a saved connection, so read-aloud skips the local model slot."""+ provider_id = (body.provider_id or "").strip()+ external_model = (body.model or "").strip()+ external_voice = (body.voice or "").strip()+ if not provider_id:+ raise HTTPException(status_code = 400, detail = "provider_id cannot be empty.")+ if not external_model:+ raise HTTPException(+ status_code = 400, detail = "model is required when using an external TTS connection."+ )+ if not external_voice:+ raise HTTPException(+ status_code = 400, detail = "voice is required when using an external TTS connection."+ )++ config = await asyncio.to_thread(providers_db.get_provider, provider_id)+ if config is None:+ raise HTTPException(status_code = 404, detail = f"Provider config not found: {provider_id}")+ if not config["is_enabled"]:+ raise HTTPException(+ status_code = 400, detail = f"Provider '{config['display_name']}' is disabled."+ )+ base_url = config["base_url"] or get_base_url(config["provider_type"])+ if not base_url:+ raise HTTPException(status_code = 400, detail = "The connection has no base URL.")+ # Validate the destination before decrypting the key: a refused target sees no credential.+ try:+ base_url = validate_provider_base_url(base_url)+ except ValueError as exc:+ raise HTTPException(status_code = 400, detail = str(exc)) from None+ async with provider_config_guard(provider_id):+ current = await asyncio.to_thread(providers_db.get_provider, provider_id)+ routing_fields = ("provider_type", "base_url", "is_enabled")+ if current is None or any(+ current.get(field) != config.get(field) for field in routing_fields+ ):+ raise HTTPException(+ status_code = 409,+ detail = "Provider changed while the request was starting; retry.",+ )+ if body.encrypted_api_key and body.provider_base_url != current.get("base_url"):+ # The browser encrypted a legacy key for the connection it rendered. A+ # same-id edit may have replaced both its destination and saved key while+ # encryption yielded; never attach that captured key to the new endpoint.+ raise HTTPException(+ status_code = 409,+ detail = "Provider changed while the request was starting; retry.",+ )+ api_key = await asyncio.to_thread(+ resolve_provider_api_key_or_400,+ provider_id,+ body.encrypted_api_key,+ allow_saved_key = not _request_has_api_key(request),+ prefer_saved_key = True,+ )+ # The guard coordinates this process, while Studio can also be edited by+ # another backend process. Provider updates write routing metadata before+ # the replacement secret, so a final row check prevents an old URL from+ # being paired with the newly written key.+ latest = await asyncio.to_thread(providers_db.get_provider, provider_id)+ if latest is None or any(+ latest.get(field) != current.get(field) for field in routing_fields+ ):+ raise HTTPException(+ status_code = 409,+ detail = "Provider changed while the request was starting; retry.",+ )+ client = ExternalProviderClient(+ provider_type = config["provider_type"],+ base_url = base_url,+ api_key = api_key,+ )+ # FastAPI does not cancel a non-streaming handler on disconnect, so stopping+ # read-aloud would leave the paid synthesis running. Same pair as transcription.+ speech_task = asyncio.create_task(+ client.create_speech(+ text = body.input,+ model = external_model,+ voice = external_voice,+ response_format = (body.response_format or "wav").strip().lower(),+ speed = body.speed,+ )+ )+ disconnect_watcher = asyncio.create_task(+ _await_disconnect_then_cancel_task(request, speech_task)+ )+ try:+ audio_bytes, media_type = await speech_task+ except httpx.HTTPStatusError as exc:+ raise HTTPException(+ status_code = 502,+ detail = (+ f"TTS endpoint returned HTTP {exc.response.status_code}: {exc.response.text[:300]}"+ ),+ )+ except httpx.HTTPError as exc:+ raise HTTPException(status_code = 502, detail = f"Could not reach the TTS endpoint: {exc}")+ finally:+ await _stop_local_disconnect_cancel_watcher(disconnect_watcher)+ return Response(content = audio_bytes, media_type = media_type)++# openai-compatible speech api: the router's dual mount also answers /v1/audio/speech@router.post("/audio/speech")async def openai_audio_speech(@@ -12327,9 +12430,26 @@ async def openai_audio_speech() -> Response:"""OpenAI-compatible text-to-speech (POST /v1/audio/speech).- ``model`` is informational (the loaded audio model is used); ``voice`` and ``speed``- are ignored. Only WAV exists, so another ``response_format`` is a 400 rather than a- silent container mismatch."""+ With ``provider_id`` the request is proxied to that connection, forwarding+ model/voice/speed. Otherwise the loaded model is used: ``model`` is informational,+ ``voice``/``speed`` ignored, and only WAV exists, so another ``response_format`` is+ a 400 rather than a silent container mismatch."""+ if body.provider_id:+ # This branch never touches the local GGUF. Drop it before any monitor or+ # upstream await so slow external speech cannot block a local swap/training+ # start or reset the local model's idle timer.+ from core.inference.llama_keepwarm import untrack_current_request+ untrack_current_request(request.scope)+ # A saved TTS connection is still media traffic through this server,+ # just like the proxied STT path below. Keep it visible in the monitor+ # and close the row consistently on upstream failure or cancellation.+ async with _monitored_media_request(+ request,+ model = public_model_id(body.model) or body.model,+ prompt = body.input,+ subject = current_subject,+ ):+ return await _external_tts_speech(body, request)fmt = (body.response_format or "wav").strip().lower()if fmt != "wav":raise HTTPException(diff --git a/studio/backend/routes/provider_credentials.py b/studio/backend/routes/provider_credentials.pyindex 1bb7565f042..164f6fc4279 100644--- a/studio/backend/routes/provider_credentials.py+++ b/studio/backend/routes/provider_credentials.py@@ -67,11 +67,16 @@ def resolve_provider_api_key_or_400(encrypted_api_key: str | None,*,allow_saved_key: bool = True,+ prefer_saved_key: bool = False,) -> str:"""Resolve an explicit key, or a saved key only for an interactive UI session."""try:saved_provider_id = provider_id if allow_saved_key else None+ if prefer_saved_key and saved_provider_id:+ saved_key = credential_secrets.get_provider_api_key(saved_provider_id)+ if saved_key is not None:+ return saved_keyreturn credential_secrets.resolve_provider_api_key(saved_provider_id, encrypted_api_key)except Exception as exc:logger.warning(diff --git a/studio/backend/routes/providers.py b/studio/backend/routes/providers.pyindex bb0459913da..f580d35f4bc 100644--- a/studio/backend/routes/providers.py+++ b/studio/backend/routes/providers.py@@ -452,16 +452,30 @@ async def update_provider_config(logger.exception("provider.update_metadata_rollback_failed", provider_id = provider_id)with current_credential_write(credential):- if metadata_requested:- providers_db.update_provider(**metadata_updates)- try:+ credential_requested = replacement_api_key is not None or payload.clear_api_key+ if metadata_requested and credential_requested:+ # Metadata and the saved key share studio.db. Commit them together so+ # another process can never route to the new endpoint with the old key.+ with providers_db.provider_bundle_transaction() as connection:+ providers_db.update_provider(**metadata_updates, connection = connection)+ if replacement_api_key is not None:+ credential_secrets.save_provider_api_key(+ provider_id,+ replacement_api_key,+ connection = connection,+ )+ else:+ credential_secrets.delete_provider_api_key(+ provider_id,+ connection = connection,+ )+ else:+ if metadata_requested:+ providers_db.update_provider(**metadata_updates)if replacement_api_key is not None:credential_secrets.save_provider_api_key(provider_id, replacement_api_key)elif payload.clear_api_key:credential_secrets.delete_provider_api_key(provider_id)- except Exception:- _restore_metadata()- raiseif not metadata_requested and not payload.encrypted_api_key and not payload.clear_api_key:raise HTTPException(status_code = 400, detail = "No fields to update")diff --git a/studio/backend/storage/credential_secrets.py b/studio/backend/storage/credential_secrets.pyindex 62de4acd4ec..da49836586d 100644--- a/studio/backend/storage/credential_secrets.py+++ b/studio/backend/storage/credential_secrets.py@@ -85,6 +85,12 @@ def get_connection() -> sqlite3.Connection:return conn+def ensure_schema() -> None:+ """Ensure the credential table exists before a shared transaction starts."""+ conn = get_connection()+ conn.close()++def _encrypted_secret(credential_kind: str, scope_id: str, plaintext: str) -> tuple[bytes, bytes, str]:@@ -102,10 +108,17 @@ def _encrypted_secret(return nonce, ciphertext, datetime.now(timezone.utc).isoformat()-def upsert_secret(credential_kind: str, scope_id: str, plaintext: str) -> None:+def upsert_secret(+ credential_kind: str,+ scope_id: str,+ plaintext: str,+ *,+ connection: sqlite3.Connection | None = None,+) -> None:"""Encrypt and atomically insert or replace one installation credential."""nonce, ciphertext, now = _encrypted_secret(credential_kind, scope_id, plaintext)- conn = get_connection()+ owns_connection = connection is None+ conn = connection or get_connection()try:conn.execute("""@@ -121,9 +134,11 @@ def upsert_secret(credential_kind: str, scope_id: str, plaintext: str) -> None:""",(credential_kind, scope_id, _FORMAT_VERSION, nonce, ciphertext, now, now),)- conn.commit()+ if owns_connection:+ conn.commit()finally:- conn.close()+ if owns_connection:+ conn.close()def insert_secret_if_absent(credential_kind: str, scope_id: str, plaintext: str) -> bool:@@ -181,18 +196,26 @@ def has_secret(credential_kind: str, scope_id: str) -> bool:return get_secret(credential_kind, scope_id) is not None-def delete_secret(credential_kind: str, scope_id: str) -> bool:+def delete_secret(+ credential_kind: str,+ scope_id: str,+ *,+ connection: sqlite3.Connection | None = None,+) -> bool:"""Idempotently delete one credential; return whether a row existed."""- conn = get_connection()+ owns_connection = connection is None+ conn = connection or get_connection()try:cursor = conn.execute("DELETE FROM credential_secrets WHERE credential_kind = ? AND scope_id = ?",(credential_kind, scope_id),)- conn.commit()+ if owns_connection:+ conn.commit()return cursor.rowcount > 0finally:- conn.close()+ if owns_connection:+ conn.close()def get_hf_token() -> Optional[str]:@@ -215,16 +238,23 @@ def get_provider_api_key(provider_id: str) -> Optional[str]:return get_secret(PROVIDER_API_KEY_KIND, provider_id)-def save_provider_api_key(provider_id: str, api_key: str) -> None:- upsert_secret(PROVIDER_API_KEY_KIND, provider_id, api_key)+def save_provider_api_key(+ provider_id: str,+ api_key: str,+ *,+ connection: sqlite3.Connection | None = None,+) -> None:+ upsert_secret(PROVIDER_API_KEY_KIND, provider_id, api_key, connection = connection)def save_provider_api_key_if_absent(provider_id: str, api_key: str) -> bool:return insert_secret_if_absent(PROVIDER_API_KEY_KIND, provider_id, api_key)-def delete_provider_api_key(provider_id: str) -> bool:- return delete_secret(PROVIDER_API_KEY_KIND, provider_id)+def delete_provider_api_key(+ provider_id: str, *, connection: sqlite3.Connection | None = None+) -> bool:+ return delete_secret(PROVIDER_API_KEY_KIND, provider_id, connection = connection)def resolve_provider_api_key(provider_id: Optional[str], encrypted_api_key: Optional[str]) -> str:diff --git a/studio/backend/storage/providers_db.py b/studio/backend/storage/providers_db.pyindex a1cf506716d..df000473df9 100644--- a/studio/backend/storage/providers_db.py+++ b/studio/backend/storage/providers_db.py@@ -17,6 +17,8 @@ import jsonimport loggingimport sqlite3import threading+from collections.abc import Iterator+from contextlib import contextmanagerfrom datetime import datetime, timezonefrom typing import Optional@@ -102,6 +104,34 @@ def get_connection() -> sqlite3.Connection:return conn+@contextmanager+def provider_bundle_transaction() -> Iterator[sqlite3.Connection]:+ """Atomically mutate a provider row and its saved credentials.++ Provider metadata and encrypted credentials share ``studio.db``. A single+ SQLite write transaction therefore prevents other processes from observing+ a new endpoint with the previous key (or the inverse) while a provider edit+ is in progress.+ """+ # Ensure both tables exist before opening the transaction. The credential+ # module commits schema initialization on its own connection.+ from storage import credential_secrets++ credential_secrets.ensure_schema()+ conn = get_connection()+ try:+ conn.commit()+ conn.execute("PRAGMA busy_timeout=5000")+ conn.execute("BEGIN IMMEDIATE")+ yield conn+ conn.commit()+ except Exception:+ conn.rollback()+ raise+ finally:+ conn.close()++def create_provider(id: str,provider_type: str,@@ -149,6 +179,8 @@ def update_provider(models: Optional[list[str]] = None,available_models: Optional[list[str]] = None,max_output_tokens: int | None | object = _UNSET,+ *,+ connection: sqlite3.Connection | None = None,) -> bool:"""Update fields on an existing provider. Returns True if a row was updated."""updates = []@@ -177,16 +209,19 @@ def update_provider(params.append(datetime.now(timezone.utc).isoformat())params.append(id)- conn = get_connection()+ owns_connection = connection is None+ conn = connection or get_connection()try:cursor = conn.execute(f"UPDATE llm_providers SET {', '.join(updates)} WHERE id = ?",params,)- conn.commit()+ if owns_connection:+ conn.commit()return cursor.rowcount > 0finally:- conn.close()+ if owns_connection:+ conn.close()def delete_provider(id: str) -> bool:diff --git a/studio/backend/tests/test_credential_routes.py b/studio/backend/tests/test_credential_routes.pyindex 1b62f1c08a4..0cf3c3517a5 100644--- a/studio/backend/tests/test_credential_routes.py+++ b/studio/backend/tests/test_credential_routes.py@@ -8,6 +8,7 @@ from contextlib import contextmanagerimport asyncioimport importlib.utilimport sys+import threadingimport timeimport typesfrom pathlib import Path@@ -150,6 +151,87 @@ def test_provider_create_preserve_replace_clear_and_delete(monkeypatch):assert providers_db.get_provider(created.id) is None+def test_endpoint_and_saved_key_update_is_atomic_for_independent_readers(monkeypatch):+ """A reader on another connection sees one complete provider bundle.++ The writer is paused after changing the endpoint but before replacing the+ encrypted key. This is the inverse interleaving that previously exposed the+ new route with the old key. The reader uses normal storage calls, each with+ its own SQLite connection, so process-local route locks cannot make it pass.+ """+ provider_id = "atomic-provider"+ old_base_url = "http://127.0.0.1:7770/v1"+ new_base_url = "http://127.0.0.1:8880/v1"+ providers_db.create_provider(+ id = provider_id,+ provider_type = "custom",+ display_name = "Atomic TTS",+ base_url = old_base_url,+ models = ["kokoro"],+ )+ credential_secrets.save_provider_api_key(provider_id, "old-secret")+ monkeypatch.setattr(+ providers_route,+ "resolve_provider_api_key_or_400",+ lambda *_args, **_kwargs: "new-secret",+ )++ between_row_and_key = threading.Event()+ finish_key_write = threading.Event()+ original_save = credential_secrets.save_provider_api_key++ def _paused_save(+ saved_provider_id: str,+ api_key: str,+ *,+ connection = None,+ ) -> None:+ assert connection is not None+ between_row_and_key.set()+ assert finish_key_write.wait(timeout = 5)+ original_save(saved_provider_id, api_key, connection = connection)++ monkeypatch.setattr(credential_secrets, "save_provider_api_key", _paused_save)+ failures: list[BaseException] = []++ def _update() -> None:+ try:+ asyncio.run(+ providers_route.update_provider_config(+ provider_id,+ ProviderUpdate(+ base_url = new_base_url,+ encrypted_api_key = "replacement-envelope",+ ),+ credential = ("alice", None),+ via_api_key = False,+ )+ )+ except BaseException as exc:+ failures.append(exc)++ writer = threading.Thread(target = _update)+ writer.start()+ try:+ assert between_row_and_key.wait(timeout = 5)+ observed_during_write = (+ providers_db.get_provider(provider_id)["base_url"],+ credential_secrets.get_provider_api_key(provider_id),+ )+ finally:+ finish_key_write.set()+ writer.join(timeout = 5)++ assert not writer.is_alive()+ assert failures == []+ observed_after_commit = (+ providers_db.get_provider(provider_id)["base_url"],+ credential_secrets.get_provider_api_key(provider_id),+ )+ assert observed_during_write == (old_base_url, "old-secret")+ assert observed_after_commit == (new_base_url, "new-secret")++def test_custom_max_output_tokens_create_update_and_clear():created = asyncio.run(providers_route.create_provider_config(@@ -359,10 +441,10 @@ def test_provider_update_validates_before_writes_and_rolls_back_metadata(monkeyp)original_save = credential_secrets.save_provider_api_key- def fail_replacement(provider_id: str, api_key: str):+ def fail_replacement(provider_id: str, api_key: str, **kwargs):if api_key == "sk-replacement":raise RuntimeError("simulated credential write failure")- original_save(provider_id, api_key)+ original_save(provider_id, api_key, **kwargs)monkeypatch.setattr(credential_secrets, "save_provider_api_key", fail_replacement)with pytest.raises(RuntimeError, match = "credential write failure"):@@ -459,6 +541,21 @@ def test_shared_provider_resolver_uses_saved_and_explicit_precedence(monkeypatchproviders_route.resolve_provider_api_key_or_400("provider-1", "ciphertext")== "explicit:ciphertext")+ assert (+ providers_route.resolve_provider_api_key_or_400(+ "provider-1", "ciphertext", prefer_saved_key = True+ )+ == "saved"+ )+ assert (+ providers_route.resolve_provider_api_key_or_400(+ "provider-1",+ "ciphertext",+ allow_saved_key = False,+ prefer_saved_key = True,+ )+ == "explicit:ciphertext"+ )monkeypatch.setattr(key_exchange,diff --git a/studio/backend/tests/test_openai_audio_speech_route.py b/studio/backend/tests/test_openai_audio_speech_route.pyindex 8ca3b02aa2c..5b98f85b696 100644--- a/studio/backend/tests/test_openai_audio_speech_route.py+++ b/studio/backend/tests/test_openai_audio_speech_route.py@@ -9,9 +9,10 @@ gallery persistence and the raw-WAV response without torch, weights or a GPU."""from __future__ import annotationsimport json+from contextlib import asynccontextmanagerimport pytest-from fastapi import FastAPI, HTTPException+from fastapi import FastAPI, HTTPException, Requestfrom fastapi.testclient import TestClientimport core.inference.audio_gallery as gallery_module@@ -313,6 +314,448 @@ def test_non_latin_prompts_are_not_billed_at_the_latin_rate():assert estimate("你好世界" * 50) >= 200+# ── External connection proxying (provider_id) ───────────────────+++def _install_external(+ monkeypatch,+ *,+ enabled = True,+ media_type = "audio/wav",+):+ created = []+ speech_calls = []++ monkeypatch.setattr(+ routes_module.providers_db,+ "get_provider",+ lambda pid: (+ {+ "provider_type": "custom",+ "display_name": "Kokoro Box",+ "base_url": "http://tts.local:8880/v1",+ "is_enabled": enabled,+ }+ if pid == "conn-1"+ else None+ ),+ )+ monkeypatch.setattr(routes_module, "validate_provider_base_url", lambda url: url)+ monkeypatch.setattr(routes_module, "resolve_provider_api_key_or_400", lambda *a, **k: "sk-test")++ class _FakeClient:+ def __init__(self, provider_type, base_url, api_key):+ created.append(+ {"provider_type": provider_type, "base_url": base_url, "api_key": api_key}+ )++ async def create_speech(self, **kwargs):+ speech_calls.append(kwargs)+ return b"external-audio", media_type++ monkeypatch.setattr(routes_module, "ExternalProviderClient", _FakeClient)+ return created, speech_calls+++def test_provider_id_routes_to_external_endpoint(monkeypatch):+ cli, calls, saved = _make_client(monkeypatch)+ created, speech_calls = _install_external(monkeypatch)+ api_monitor.clear()+ resp = cli.post(+ "/v1/audio/speech",+ json = {+ "input": "hi",+ "provider_id": "conn-1",+ "model": "kokoro",+ "voice": "af_heart",+ },+ )+ assert resp.status_code == 200+ assert resp.content == b"external-audio"+ assert resp.headers["content-type"].startswith("audio/wav")+ assert calls == [] # the local TTS core never runs+ assert saved == [] # external clips skip the gallery+ assert created[0]["base_url"] == "http://tts.local:8880/v1"+ assert created[0]["provider_type"] == "custom"+ assert speech_calls[0]["model"] == "kokoro"+ assert speech_calls[0]["voice"] == "af_heart"+ rows = api_monitor.snapshot(include_details = False)+ assert len(rows) == 1+ assert rows[0]["endpoint"] == "/v1/audio/speech"+ assert rows[0]["status"] == "completed"+ assert rows[0]["model"] == "kokoro"+ assert rows[0]["prompt_preview"] == "hi"+++def test_external_passes_response_format_through(monkeypatch):+ # The wav-only rule is a local-codec limit; an external server may emit mp3.+ cli, calls, saved = _make_client(monkeypatch)+ created, speech_calls = _install_external(monkeypatch, media_type = "audio/mpeg")+ resp = cli.post(+ "/v1/audio/speech",+ json = {+ "input": "hi",+ "provider_id": "conn-1",+ "model": "kokoro",+ "voice": "alloy",+ "response_format": "mp3",+ },+ )+ assert resp.status_code == 200+ assert resp.headers["content-type"].startswith("audio/mpeg")+ assert speech_calls[0]["response_format"] == "mp3"+++def test_external_missing_model_is_400(monkeypatch):+ cli, calls, saved = _make_client(monkeypatch)+ _install_external(monkeypatch)+ resp = cli.post("/v1/audio/speech", json = {"input": "hi", "provider_id": "conn-1"})+ assert resp.status_code == 400+++def test_external_missing_voice_is_400(monkeypatch):+ cli, _calls, _saved = _make_client(monkeypatch)+ _install_external(monkeypatch)+ resp = cli.post(+ "/v1/audio/speech",+ json = {"input": "hi", "provider_id": "conn-1", "model": "kokoro"},+ )+ assert resp.status_code == 400+ assert "voice" in resp.json()["error"]["message"].lower()+++def test_external_unknown_provider_is_404(monkeypatch):+ cli, calls, saved = _make_client(monkeypatch)+ _install_external(monkeypatch)+ resp = cli.post(+ "/v1/audio/speech",+ json = {+ "input": "hi",+ "provider_id": "missing",+ "model": "kokoro",+ "voice": "alloy",+ },+ )+ assert resp.status_code == 404+++def test_external_disabled_provider_is_400(monkeypatch):+ cli, calls, saved = _make_client(monkeypatch)+ _install_external(monkeypatch, enabled = False)+ resp = cli.post(+ "/v1/audio/speech",+ json = {+ "input": "hi",+ "provider_id": "conn-1",+ "model": "kokoro",+ "voice": "alloy",+ },+ )+ assert resp.status_code == 400+++def test_external_upstream_error_is_502(monkeypatch):+ import httpx++ cli, calls, saved = _make_client(monkeypatch)+ created, speech_calls = _install_external(monkeypatch)+ api_monitor.clear()++ async def _boom(self, **kwargs):+ request = httpx.Request("POST", "http://tts.local:8880/v1/audio/speech")+ raise httpx.HTTPStatusError(+ "boom",+ request = request,+ response = httpx.Response(500, text = "upstream broke", request = request),+ )++ monkeypatch.setattr(routes_module.ExternalProviderClient, "create_speech", _boom)+ resp = cli.post(+ "/v1/audio/speech",+ json = {+ "input": "hi",+ "provider_id": "conn-1",+ "model": "kokoro",+ "voice": "alloy",+ },+ )+ assert resp.status_code == 502+ assert "upstream broke" in resp.json()["error"]["message"]+ rows = api_monitor.snapshot(include_details = False)+ assert len(rows) == 1+ assert rows[0]["status"] == "error"+ assert "TTS endpoint returned HTTP 500" in rows[0]["error"]+++def test_external_disconnect_cancels_the_upstream_request(monkeypatch):+ import asyncio++ from models.inference import AudioSpeechRequest++ _install_external(monkeypatch)+ upstream_cancelled = asyncio.Event()++ class _DisconnectingRequest:+ headers = {}++ async def is_disconnected(self):+ return True++ class _BlockingClient:+ def __init__(self, **_kwargs):+ pass++ async def create_speech(self, **_kwargs):+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ upstream_cancelled.set()+ raise++ monkeypatch.setattr(routes_module, "ExternalProviderClient", _BlockingClient)++ async def _run():+ with pytest.raises(asyncio.CancelledError):+ await routes_module._external_tts_speech(+ AudioSpeechRequest(input = "hi", provider_id = "conn-1", model = "kokoro", voice = "alloy"),+ _DisconnectingRequest(),+ )++ asyncio.run(_run())+ assert upstream_cancelled.is_set()+++def test_external_forwards_a_legacy_browser_key(monkeypatch):+ cli, _calls, _saved = _make_client(monkeypatch)+ created, _speech_calls = _install_external(monkeypatch)+ seen = {}++ def _resolve(provider_id, encrypted_api_key, **_kwargs):+ seen["provider_id"] = provider_id+ seen["encrypted_api_key"] = encrypted_api_key+ return "sk-from-legacy"++ monkeypatch.setattr(routes_module, "resolve_provider_api_key_or_400", _resolve)+ resp = cli.post(+ "/v1/audio/speech",+ json = {+ "input": "hi",+ "provider_id": "conn-1",+ "model": "kokoro",+ "voice": "alloy",+ "provider_base_url": "http://tts.local:8880/v1",+ "encrypted_api_key": "enc-legacy",+ },+ )+ assert resp.status_code == 200+ assert seen["encrypted_api_key"] == "enc-legacy"+ assert created[0]["api_key"] == "sk-from-legacy"+++def test_external_rejects_a_legacy_key_snapshotted_for_another_base_url(monkeypatch):+ cli, _calls, _saved = _make_client(monkeypatch)+ _install_external(monkeypatch)++ def _must_not_resolve(*_args, **_kwargs):+ pytest.fail("the stale legacy key was decrypted")++ monkeypatch.setattr(routes_module, "resolve_provider_api_key_or_400", _must_not_resolve)+ resp = cli.post(+ "/v1/audio/speech",+ json = {+ "input": "hi",+ "provider_id": "conn-1",+ "provider_base_url": "http://old-tts.local:8880/v1",+ "model": "kokoro",+ "voice": "alloy",+ "encrypted_api_key": "enc-old-key",+ },+ )+ assert resp.status_code == 409+ assert "changed" in resp.json()["error"]["message"].lower()+++def test_external_tts_drops_the_local_keepwarm_count_before_proxy(monkeypatch):+ from core.inference import llama_keepwarm+ from models.inference import AudioSpeechRequest++ monkeypatch.setattr(llama_keepwarm, "_inflight", 1)+ monkeypatch.setattr(llama_keepwarm, "_pending", 0)+ observed_counts = []++ @asynccontextmanager+ async def _monitor(*_args, **_kwargs):+ yield "monitor-1"++ async def _proxy(_body, _request):+ observed_counts.append(+ llama_keepwarm.other_inference_request_count(current_request_counted = False)+ )+ return routes_module.Response(content = b"external-audio", media_type = "audio/wav")++ monkeypatch.setattr(routes_module, "_monitored_media_request", _monitor)+ monkeypatch.setattr(routes_module, "_external_tts_speech", _proxy)+ request = Request(+ {+ "type": "http",+ "method": "POST",+ "path": "/v1/audio/speech",+ "headers": [],+ "query_string": b"",+ "scheme": "http",+ "server": ("testserver", 80),+ "client": ("testclient", 123),+ }+ )++ import asyncio++ asyncio.run(+ routes_module.openai_audio_speech(+ AudioSpeechRequest(+ input = "hi",+ provider_id = "conn-1",+ model = "kokoro",+ voice = "alloy",+ ),+ request,+ "test-user",+ )+ )+ assert observed_counts == [0]+++def test_provider_client_appends_speech_path_before_the_base_query(monkeypatch):+ import asyncio++ from core.inference.external_provider import ExternalProviderClient+ import core.inference.external_provider as provider_module++ sent = {}++ class _Response:+ content = b"audio"+ headers = {"content-type": "audio/wav"}++ def raise_for_status(self):+ return None++ async def _post(url, **_kwargs):+ sent["url"] = url+ return _Response()++ monkeypatch.setattr(provider_module._http_client, "post", _post)+ client = ExternalProviderClient(+ "custom",+ "http://127.0.0.1:8880/v1?api-version=2026-08-24",+ "sk-test",+ )+ asyncio.run(client.create_speech(text = "hi", model = "kokoro"))+ assert sent["url"] == ("http://127.0.0.1:8880/v1/audio/speech?api-version=2026-08-24")+++def test_external_provider_reads_do_not_block_the_event_loop(monkeypatch):+ import asyncio+ import threading++ from models.inference import AudioSpeechRequest++ _install_external(monkeypatch)+ original_get_provider = routes_module.providers_db.get_provider+ read_started = threading.Event()+ release_read = threading.Event()+ heartbeat_seen = threading.Event()+ event_loop_blocked = []++ def _slow_get_provider(provider_id):+ read_started.set()+ release_read.wait()+ return original_get_provider(provider_id)++ monkeypatch.setattr(routes_module.providers_db, "get_provider", _slow_get_provider)++ class _ConnectedRequest:+ headers = {}++ async def is_disconnected(self):+ return False++ def _watchdog():+ if not read_started.wait(timeout = 1):+ event_loop_blocked.append(True)+ release_read.set()+ return+ if not heartbeat_seen.wait(timeout = 1):+ event_loop_blocked.append(True)+ release_read.set()++ async def _run():+ watchdog = threading.Thread(target = _watchdog)+ watchdog.start()+ speech = asyncio.create_task(+ routes_module._external_tts_speech(+ AudioSpeechRequest(input = "hi", provider_id = "conn-1", model = "kokoro", voice = "alloy"),+ _ConnectedRequest(),+ )+ )+ await asyncio.sleep(0)+ heartbeat_seen.set()+ release_read.set()+ await speech+ watchdog.join()++ asyncio.run(_run())+ assert event_loop_blocked == []+++def test_external_rejects_a_cross_process_provider_edit_after_resolving_its_key(monkeypatch):+ import asyncio++ from models.inference import AudioSpeechRequest++ old_config = {+ "provider_type": "custom",+ "display_name": "Old TTS",+ "base_url": "http://old-tts.local:8880/v1",+ "is_enabled": True,+ }+ new_config = {+ **old_config,+ "display_name": "New TTS",+ "base_url": "http://new-tts.local:8880/v1",+ }+ # A second process is not covered by provider_config_guard. It can update+ # the row and then the secret while this process is resolving that secret.+ snapshots = iter((old_config, old_config, new_config))+ monkeypatch.setattr(routes_module.providers_db, "get_provider", lambda _pid: next(snapshots))+ monkeypatch.setattr(routes_module, "validate_provider_base_url", lambda url: url)+ key_resolved = False++ def _resolve(*_args, **_kwargs):+ nonlocal key_resolved+ key_resolved = True+ return "new-key"++ monkeypatch.setattr(routes_module, "resolve_provider_api_key_or_400", _resolve)++ class _ConnectedRequest:+ headers = {}++ async def is_disconnected(self):+ return False++ async def _run():+ with pytest.raises(HTTPException) as excinfo:+ await routes_module._external_tts_speech(+ AudioSpeechRequest(input = "hi", provider_id = "conn-1", model = "kokoro", voice = "alloy"),+ _ConnectedRequest(),+ )+ assert excinfo.value.status_code == 409++ asyncio.run(_run())+ assert key_resolved++def test_speech_opens_a_monitor_row(monkeypatch):cli, calls, saved = _make_client(monkeypatch)api_monitor.clear()diff --git a/studio/backend/tests/test_provider_max_output_tokens_contract.py b/studio/backend/tests/test_provider_max_output_tokens_contract.pyindex 4e252efdb6e..fe43bb9190a 100644--- a/studio/backend/tests/test_provider_max_output_tokens_contract.py+++ b/studio/backend/tests/test_provider_max_output_tokens_contract.py@@ -398,7 +398,7 @@ def test_the_largest_accepted_value_round_trips_exactly(provider_routes: Path):def test_a_failed_credential_write_restores_the_previous_override(provider_routes: Path, monkeypatch: pytest.MonkeyPatch):- """Metadata is written before the key, so the rollback has to carry the column."""+ """A failed key write rolls the metadata update back in the shared transaction."""created = _create(ProviderCreate(provider_type = "custom",diff --git a/studio/frontend/src/features/auth/api.ts b/studio/frontend/src/features/auth/api.tsindex 8b22b48f319..64eae3de36b 100644--- a/studio/frontend/src/features/auth/api.ts+++ b/studio/frontend/src/features/auth/api.ts@@ -17,6 +17,12 @@ type RefreshResponse = {must_change_password: boolean;};+type AuthFetchOptions = {+ retryNetworkErrors?: boolean;+ /** Synchronous policy check run immediately before any retry sends bytes. */+ beforeRetry?: () => void;+};+let isRedirecting = false;let refreshInflight: Promise<boolean> | null = null;let refreshInflightToken: string | null = null;@@ -36,6 +42,7 @@ async function fetchWithTauriNetworkRetry(input: RequestInfo | URL,init?: RequestInit,retryNetworkErrors = true,+ beforeRetry?: () => void,): Promise<Response> {for (let attempt = 0; ; attempt++) {try {@@ -50,11 +57,14 @@ async function fetchWithTauriNetworkRetry(throw error;}await wait(TAURI_FETCH_RETRY_DELAYS_MS[attempt]);+ beforeRetry?.();}}}-async function isPasswordChangeRequiredResponse(response: Response): Promise<boolean> {+async function isPasswordChangeRequiredResponse(+ response: Response,+): Promise<boolean> {if (response.status !== 403) return false;try {@@ -95,7 +105,11 @@ function asTransportFailure(err: unknown): unknown {// fetch TypeError = offline | backend down | CORS/DNS. Tagged so callers tell "never reached"// from "rejected"; Tauri is always backend-down, the web build distinguishes offline.if (!(err instanceof TypeError)) return err;- if (!isTauri && typeof navigator !== "undefined" && navigator.onLine === false) {+ if (+ !isTauri &&+ typeof navigator !== "undefined" &&+ navigator.onLine === false+ ) {return Object.assign(new Error("You appear to be offline. Check your network connection and try again.",@@ -113,7 +127,9 @@ async function retryWithCurrentToken(input: RequestInfo | URL,init?: RequestInit,retryNetworkErrors = true,+ beforeRetry?: () => void,): Promise<Response> {+ beforeRetry?.();const retryHeaders = new Headers(init?.headers);const token = getAuthToken();if (token) retryHeaders.set("Authorization", `Bearer ${token}`);@@ -123,6 +139,7 @@ async function retryWithCurrentToken(input,{ ...init, headers: retryHeaders },retryNetworkErrors,+ beforeRetry,);} catch (err) {throw asTransportFailure(err);@@ -133,11 +150,12 @@ async function retryWithTauriAutoAuth(input: RequestInfo | URL,init?: RequestInit,retryNetworkErrors = true,+ beforeRetry?: () => void,): Promise<Response | null> {clearAuthTokens();const { tauriAutoAuth } = await import("./tauri-auto-auth");if (await tauriAutoAuth()) {- return retryWithCurrentToken(input, init, retryNetworkErrors);+ return retryWithCurrentToken(input, init, retryNetworkErrors, beforeRetry);}return null;}@@ -189,9 +207,9 @@ export async function refreshSession(): Promise<boolean> {export async function authFetch(input: RequestInfo | URL,init?: RequestInit,- options?: { retryNetworkErrors?: boolean },+ options?: AuthFetchOptions,): Promise<Response> {- const resolvedInput = typeof input === 'string' ? apiUrl(input) : input;+ const resolvedInput = typeof input === "string" ? apiUrl(input) : input;const headers = new Headers(init?.headers);const accessToken = getAuthToken();if (accessToken) {@@ -207,6 +225,7 @@ export async function authFetch(headers,},options?.retryNetworkErrors ?? true,+ options?.beforeRetry,);} catch (err) {throw asTransportFailure(err);@@ -219,6 +238,7 @@ export async function authFetch(resolvedInput,init,options?.retryNetworkErrors ?? true,+ options?.beforeRetry,)) ?? response);}@@ -236,6 +256,7 @@ export async function authFetch(resolvedInput,init,options?.retryNetworkErrors ?? true,+ options?.beforeRetry,)) ?? response);}@@ -251,6 +272,7 @@ export async function authFetch(resolvedInput,init,options?.retryNetworkErrors ?? true,+ options?.beforeRetry,)) ?? response);}@@ -263,10 +285,13 @@ export async function authFetch(resolvedInput,init,options?.retryNetworkErrors ?? true,+ options?.beforeRetry,);}-async function postLogout(accessToken: string | null): Promise<Response | null> {+async function postLogout(+ accessToken: string | null,+): Promise<Response | null> {try {return await fetchWithTauriNetworkRetry(apiUrl("/api/auth/logout"), {method: "POST",diff --git a/studio/frontend/src/features/chat/adapters/studio-speech-synthesis-adapter.ts b/studio/frontend/src/features/chat/adapters/studio-speech-synthesis-adapter.tsindex 91024e1793e..4052549b2f6 100644--- a/studio/frontend/src/features/chat/adapters/studio-speech-synthesis-adapter.ts+++ b/studio/frontend/src/features/chat/adapters/studio-speech-synthesis-adapter.ts@@ -2,10 +2,13 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { authFetch } from "@/features/auth";-import { stripSearchImageTokens } from "../search-images/search-images";import { useVoiceSettingsStore } from "@/features/settings/stores/voice-settings-store";import { toast } from "@/lib/toast";import type { SpeechSynthesisAdapter } from "@assistant-ui/react";+import { encryptProviderApiKey } from "../api/providers-api";+import { getExternalProviderApiKey } from "../external-providers";+import { stripSearchImageTokens } from "../search-images/search-images";+import { useExternalProvidersStore } from "../stores/external-providers-store";/** Voice for a stored voiceURI. "default" resolves to the voice the platform* marks as its default, so the "System default" choice means what it says@@ -252,7 +255,109 @@ export async function generateStudioTtsAudio(return `data:audio/wav;base64,${data.audio.data}`;}-function speakWithStudioModel(+/** Speech via a saved connection's /audio/speech. Returns an object URL to release. */+export async function generateCustomTtsAudio(+ text: string,+ signal?: AbortSignal,+): Promise<string> {+ const providersState = useExternalProvidersStore.getState();+ if (!providersState.connectionsEnabled) {+ throw new Error(+ "Connections are disabled. Turn on Enable connections in Settings → Connections to use a custom TTS endpoint.",+ );+ }+ const { ttsProviderId, ttsProviderModel, ttsProviderVoice } =+ useVoiceSettingsStore.getState();+ const model = ttsProviderModel.trim();+ const voice = ttsProviderVoice.trim() || "alloy";+ if (!ttsProviderId || !model) {+ throw new Error(+ "Custom TTS is not configured. Pick a connection and model in Settings → Voice.",+ );+ }+ // A browser whose key migration failed keeps the connection selectable on a+ // retained legacy key; send it like chat and STT do, or this call is unauthenticated.+ const provider = providersState.providers.find(+ (candidate) => candidate.id === ttsProviderId,+ );+ if (!provider) {+ useVoiceSettingsStore.getState().setTtsProviderId("");+ throw new Error(+ "The custom TTS connection no longer exists. Pick another connection in Settings → Voice.",+ );+ }+ const legacyApiKey = provider.hasApiKey+ ? ""+ : getExternalProviderApiKey(ttsProviderId).trim();+ const encryptedApiKey = legacyApiKey+ ? await encryptProviderApiKey(legacyApiKey)+ : "";++ // Encryption and auth refresh both yield. Reuse this check before the first+ // request and every authFetch retry so neither path can release assistant text+ // or a retained key after the frontend-only connection policy changes.+ const assertConnectionSnapshot = () => {+ const currentProvidersState = useExternalProvidersStore.getState();+ if (!currentProvidersState.connectionsEnabled) {+ throw new Error(+ "Connections are disabled. Turn on Enable connections in Settings → Connections to use a custom TTS endpoint.",+ );+ }+ const currentProvider = currentProvidersState.providers.find(+ (candidate) => candidate.id === ttsProviderId,+ );+ if (!currentProvider) {+ useVoiceSettingsStore.getState().setTtsProviderId("");+ throw new Error(+ "The custom TTS connection no longer exists. Pick another connection in Settings → Voice.",+ );+ }+ if (+ currentProvider.baseUrl !== provider.baseUrl ||+ currentProvider.providerType !== provider.providerType ||+ currentProvider.backendProviderType !== provider.backendProviderType ||+ currentProvider.hasApiKey !== provider.hasApiKey ||+ currentProvider.updatedAt !== provider.updatedAt+ ) {+ throw new Error(+ "The custom TTS connection changed while the request was starting. Try again.",+ );+ }+ };+ assertConnectionSnapshot();+ const response = await authFetch(+ "/api/inference/audio/speech",+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ input: text,+ provider_id: ttsProviderId,+ provider_base_url: provider.baseUrl,+ model,+ voice,+ ...(encryptedApiKey ? { encrypted_api_key: encryptedApiKey } : {}),+ }),+ signal,+ },+ { beforeRetry: assertConnectionSnapshot },+ );+ if (!response.ok) {+ const body = (await response.json().catch(() => null)) as {+ detail?: string;+ } | null;+ throw new Error(body?.detail ?? `HTTP ${response.status}`);+ }+ return URL.createObjectURL(await response.blob());+}++/** Release a URL returned by the generate helpers (data URLs need nothing). */+export function releaseTtsAudioUrl(url: string): void {+ if (url.startsWith("blob:")) URL.revokeObjectURL(url);+}++function speakWithBackendAudio(+ generate: (text: string, signal?: AbortSignal) => Promise<string>,text: string,handleEnd: (reason: "finished" | "error" | "cancelled",@@ -263,6 +368,7 @@ function speakWithStudioModel(const { ttsRate, ttsVolume } = useVoiceSettingsStore.getState();const controller = new AbortController();let audio: HTMLAudioElement | null = null;+ let audioUrl: string | null = null;let cancelled = false;// Release the element and its multi-MB WAV data URL as soon as playback ends.@@ -272,12 +378,20 @@ function speakWithStudioModel(audio.removeAttribute("src");audio = null;}+ if (audioUrl) {+ releaseTtsAudioUrl(audioUrl);+ audioUrl = null;+ }};void (async () => {try {- const url = await generateStudioTtsAudio(text, controller.signal);- if (cancelled) return;+ const url = await generate(text, controller.signal);+ if (cancelled) {+ releaseTtsAudioUrl(url);+ return;+ }+ audioUrl = url;audio = new Audio(url);audio.playbackRate = ttsRate;audio.volume = ttsVolume;@@ -316,7 +430,7 @@ function speakWithStudioModel(/*** Text-to-speech for assistant messages. Reads Voice settings at speak time.- * Engines: "system" (speechSynthesis) or "studio" (loaded TTS audio model).+ * Engines: "system" (speechSynthesis), "studio" (local TTS model), "custom" (a connection).*/export class StudioSpeechSynthesisAdapter implements SpeechSynthesisAdapter {/** Web Speech synthesis, used by the "system" engine. */@@ -388,10 +502,14 @@ export class StudioSpeechSynthesisAdapter implements SpeechSynthesisAdapter {// Fall back to the backend model when the runtime lacks Web Speech// synthesis (e.g. an audio-only WebView), so read-aloud still works.if (- ttsEngine === "studio" ||+ ttsEngine !== "system" ||!StudioSpeechSynthesisAdapter.systemVoicesSupported()) {- const session = speakWithStudioModel(text, handleEnd, () => {+ const generate =+ ttsEngine === "custom"+ ? generateCustomTtsAudio+ : generateStudioTtsAudio;+ const session = speakWithBackendAudio(generate, text, handleEnd, () => {if (res.status.type === "ended") return;// Notify subscribers of the async starting -> running transition;// the adapter contract drives UI state off these subscribe callbacks.diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex bd75f8126bd..d535ed73a99 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -342,5 +342,7 @@ export {StudioSpeechSynthesisAdapter,createConfiguredUtterance,curateSystemVoices,+ generateCustomTtsAudio,generateStudioTtsAudio,+ releaseTtsAudioUrl,} from "./adapters/studio-speech-synthesis-adapter";diff --git a/studio/frontend/src/features/settings/stores/voice-settings-store.ts b/studio/frontend/src/features/settings/stores/voice-settings-store.tsindex d467496ef7c..3e1845d0d20 100644--- a/studio/frontend/src/features/settings/stores/voice-settings-store.ts+++ b/studio/frontend/src/features/settings/stores/voice-settings-store.ts@@ -80,6 +80,8 @@ export function isSttModelLanguageCompatible(export type DictationEngine = "browser" | "model" | "custom";+export type TtsEngine = "system" | "studio" | "custom";+/*** Whether a model id is curated. Whisper ids run GGML through whisper.cpp,* mtmd ids run through llama.cpp, and custom repos are safetensors on@@ -132,9 +134,20 @@ export interface VoiceSettingsState {ttsEnabled: boolean;setTtsEnabled: (value: boolean) => void;- /** "system": speechSynthesis voices. "studio": the loaded TTS audio model. */- ttsEngine: "system" | "studio";- setTtsEngine: (value: "system" | "studio") => void;+ /** "system": speechSynthesis voices. "studio": the loaded TTS audio model.+ * "custom": a saved connection's /audio/speech endpoint. */+ ttsEngine: TtsEngine;+ setTtsEngine: (value: TtsEngine) => void;++ /** Saved connection id used by the "custom" engine. */+ ttsProviderId: string;+ setTtsProviderId: (value: string) => void;+ /** Model id sent to the custom endpoint (e.g. "kokoro"). */+ ttsProviderModel: string;+ setTtsProviderModel: (value: string) => void;+ /** Voice name sent to the custom endpoint; blank input defaults to alloy. */+ ttsProviderVoice: string;+ setTtsProviderVoice: (value: string) => void;/** speechSynthesis voiceURI, or "default" for the system voice. */ttsVoiceURI: string;@@ -303,6 +316,13 @@ export const useVoiceSettingsStore = create<VoiceSettingsState>()(ttsEngine: "system",setTtsEngine: (ttsEngine) => set({ ttsEngine }),+ ttsProviderId: "",+ setTtsProviderId: (ttsProviderId) => set({ ttsProviderId }),+ ttsProviderModel: "",+ setTtsProviderModel: (ttsProviderModel) => set({ ttsProviderModel }),+ ttsProviderVoice: "",+ setTtsProviderVoice: (ttsProviderVoice) => set({ ttsProviderVoice }),+ttsVoiceURI: "default",setTtsVoiceURI: (ttsVoiceURI) => set({ ttsVoiceURI }),@@ -354,7 +374,13 @@ export const useVoiceSettingsStore = create<VoiceSettingsState>()(recentDictations: normalizeRecentDictations(saved?.recentDictations),ttsEnabled:typeof saved?.ttsEnabled === "boolean" ? saved.ttsEnabled : true,- ttsEngine: saved?.ttsEngine === "studio" ? "studio" : "system",+ ttsEngine:+ saved?.ttsEngine === "studio" || saved?.ttsEngine === "custom"+ ? saved.ttsEngine+ : "system",+ ttsProviderId: asString(saved?.ttsProviderId, ""),+ ttsProviderModel: asString(saved?.ttsProviderModel, ""),+ ttsProviderVoice: asString(saved?.ttsProviderVoice, ""),ttsVoiceURI: asString(saved?.ttsVoiceURI, "default"),ttsRate: clampNumber(saved?.ttsRate, 0.5, 2, 1),ttsPitch: clampNumber(saved?.ttsPitch, 0, 2, 1),diff --git a/studio/frontend/src/features/settings/tabs/voice-tab.tsx b/studio/frontend/src/features/settings/tabs/voice-tab.tsxindex e1197e4e8d9..6583d3f45ea 100644--- a/studio/frontend/src/features/settings/tabs/voice-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/voice-tab.tsx@@ -26,8 +26,10 @@ import {createConfiguredUtterance,curateSystemVoices,fetchSttStatus,+ generateCustomTtsAudio,generateStudioTtsAudio,loadSttModel,+ releaseTtsAudioUrl,startSttDownload,unloadSttModel,useExternalProvidersStore,@@ -80,6 +82,7 @@ import {isSttModelLanguageCompatible,sttModelName,sttModelSize,+ type TtsEngine,useVoiceSettingsStore,} from "../stores/voice-settings-store";@@ -426,6 +429,20 @@ export function VoiceTab() {const setTtsEngine = useVoiceSettingsStore((s) => s.setTtsEngine);const ttsVoiceURI = useVoiceSettingsStore((s) => s.ttsVoiceURI);const setTtsVoiceURI = useVoiceSettingsStore((s) => s.setTtsVoiceURI);+ const ttsProviderId = useVoiceSettingsStore((s) => s.ttsProviderId);+ const setTtsProviderId = useVoiceSettingsStore((s) => s.setTtsProviderId);+ const ttsProviderModel = useVoiceSettingsStore((s) => s.ttsProviderModel);+ const setTtsProviderModel = useVoiceSettingsStore(+ (s) => s.setTtsProviderModel,+ );+ const ttsProviderVoice = useVoiceSettingsStore((s) => s.ttsProviderVoice);+ const setTtsProviderVoice = useVoiceSettingsStore(+ (s) => s.setTtsProviderVoice,+ );+ const ttsConnections = useExternalProvidersStore((s) => s.providers);+ const hasSelectedTtsConnection = ttsConnections.some(+ (connection) => connection.id === ttsProviderId,+ );const ttsRate = useVoiceSettingsStore((s) => s.ttsRate);const setTtsRate = useVoiceSettingsStore((s) => s.setTtsRate);const ttsPitch = useVoiceSettingsStore((s) => s.ttsPitch);@@ -465,11 +482,20 @@ export function VoiceTab() {}}, [hasSelectedSttConnection, setSttProviderId, sttProviderId]);+ // A deleted connection would otherwise stay selected and every read aloud would+ // post the stale id, so drop it the way the dictation selection does.+ useEffect(() => {+ if (ttsProviderId && !hasSelectedTtsConnection) {+ setTtsProviderId("");+ }+ }, [hasSelectedTtsConnection, setTtsProviderId, ttsProviderId]);+const modelSttSupported = StudioModelDictationAdapter.isSupported();const ttsSupported = StudioSpeechSynthesisAdapter.isSupported();const systemTtsSupported =StudioSpeechSynthesisAdapter.systemVoicesSupported();- const effectiveTtsEngine = systemTtsSupported ? ttsEngine : "studio";+ const effectiveTtsEngine: TtsEngine =+ ttsEngine === "system" && !systemTtsSupported ? "studio" : ttsEngine;// Local STT stays on-demand. Track its phase without fetching model weights.type SttPhase =@@ -803,7 +829,9 @@ export function VoiceTab() {const releasePreviewAudio = useCallback(() => {if (previewAudioRef.current) {previewAudioRef.current.pause();- previewAudioRef.current.src = "";+ releaseTtsAudioUrl(previewAudioRef.current.src);+ // removeAttribute, not `src = ""`: an empty src fires a media error toasting "preview failed".+ previewAudioRef.current.removeAttribute("src");previewAudioRef.current = null;}}, []);@@ -828,18 +856,22 @@ export function VoiceTab() {stopPreview();return;}- if (effectiveTtsEngine === "studio") {+ if (effectiveTtsEngine !== "system") {const controller = new AbortController();previewAbortRef.current = controller;ownsSystemPreviewRef.current = false;markPreviewing(true);setPreparingPreview(true);try {- const url = await generateStudioTtsAudio(- TTS_PREVIEW_TEXT,- controller.signal,- );- if (controller.signal.aborted) return;+ const generate =+ effectiveTtsEngine === "custom"+ ? generateCustomTtsAudio+ : generateStudioTtsAudio;+ const url = await generate(TTS_PREVIEW_TEXT, controller.signal);+ if (controller.signal.aborted) {+ releaseTtsAudioUrl(url);+ return;+ }setPreparingPreview(false);const audio = new Audio(url);audio.playbackRate = ttsRate;@@ -1310,13 +1342,19 @@ export function VoiceTab() {description={effectiveTtsEngine === "studio"? t("settings.voice.readAloud.engineStudioDescription")- : t("settings.voice.readAloud.engineSystemDescription")+ : effectiveTtsEngine === "custom"+ ? t("settings.voice.readAloud.engineCustomDescription")+ : t("settings.voice.readAloud.engineSystemDescription")}><Selectvalue={effectiveTtsEngine}onValueChange={(value) =>- setTtsEngine(value === "studio" ? "studio" : "system")+ setTtsEngine(+ value === "studio" || value === "custom"+ ? value+ : "system",+ )}><SelectTrigger@@ -1335,11 +1373,73 @@ export function VoiceTab() {<SelectItem value="studio">{t("settings.voice.readAloud.engineStudio")}</SelectItem>+ <SelectItem value="custom">+ {t("settings.voice.readAloud.engineCustom")}+ </SelectItem></SelectContent></Select></SettingsRow>- {effectiveTtsEngine === "studio" ? (+ {effectiveTtsEngine === "custom" ? (+ <>+ <SettingsRow+ label={t("settings.voice.readAloud.connectionLabel")}+ description={t(+ "settings.voice.readAloud.connectionDescription",+ )}+ >+ <Select+ value={hasSelectedTtsConnection ? ttsProviderId : ""}+ onValueChange={setTtsProviderId}+ disabled={ttsConnections.length === 0}+ >+ <SelectTrigger+ aria-label={t("settings.voice.readAloud.connectionLabel")}+ className="min-w-56 max-w-72"+ size="sm"+ >+ <SelectValue+ placeholder={t(+ "settings.voice.readAloud.connectionPlaceholder",+ )}+ />+ </SelectTrigger>+ <SelectContent>+ {ttsConnections.map((connection) => (+ <SelectItem key={connection.id} value={connection.id}>+ {connection.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </SettingsRow>+ <SettingsRow+ label={t("settings.voice.readAloud.customModelLabel")}+ >+ <Input+ value={ttsProviderModel}+ onChange={(e) => setTtsProviderModel(e.target.value)}+ placeholder="kokoro"+ className="h-8 w-56 max-w-72"+ aria-label={t("settings.voice.readAloud.customModelLabel")}+ />+ </SettingsRow>+ <SettingsRow+ label={t("settings.voice.readAloud.voiceLabel")}+ description={t(+ "settings.voice.readAloud.customVoiceDescription",+ )}+ >+ <Input+ value={ttsProviderVoice}+ onChange={(e) => setTtsProviderVoice(e.target.value)}+ placeholder="alloy"+ className="h-8 w-56 max-w-72"+ aria-label={t("settings.voice.readAloud.voiceLabel")}+ />+ </SettingsRow>+ </>+ ) : effectiveTtsEngine === "studio" ? (<SettingsRowlabel={t("settings.voice.readAloud.modelLabel")}description={t("settings.voice.readAloud.modelDescription")}diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex c80ed9b1211..af4ee8b5315 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -411,6 +411,16 @@ export const ar = {"يستخدم النموذج الصوتي المُحمَّل (مثل Orpheus)",engineSystem: "أصوات النظام",engineStudio: "تحميل نموذج TTS",+ engineCustom: "نقطة نهاية مخصصة",+ engineCustomDescription:+ "خادم TTS متوافق مع OpenAI من اتصالاتك (مثل Kokoro)",+ connectionLabel: "الاتصال",+ connectionDescription:+ "أضف خادمًا متوافقًا مع OpenAI من علامة تبويب الاتصالات",+ connectionPlaceholder: "اختر اتصالًا",+ customModelLabel: "النموذج",+ customVoiceDescription:+ "اسم الصوت الذي تتوقعه نقطة النهاية؛ القيمة الافتراضية alloy",modelLabel: "نموذج TTS",modelDescription:"حمّل نموذجًا صوتيًا من محدّد النماذج (مثل Orpheus TTS)",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 6ab7fd36ad9..516a3831dd6 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -423,6 +423,16 @@ export const de = {"Verwendet das geladene Audiomodell (z. B. Orpheus)",engineSystem: "Systemstimmen",engineStudio: "TTS-Modell laden",+ engineCustom: "Eigener Endpunkt",+ engineCustomDescription:+ "Ein OpenAI-kompatibler TTS-Server aus deinen Verbindungen (z. B. Kokoro)",+ connectionLabel: "Verbindung",+ connectionDescription:+ "Einen OpenAI-kompatiblen Server im Tab „Verbindungen“ hinzufügen",+ connectionPlaceholder: "Verbindung auswählen",+ customModelLabel: "Modell",+ customVoiceDescription:+ "Vom Endpunkt erwarteter Stimmenname; Standard ist alloy",modelLabel: "TTS-Modell",modelDescription:"Laden Sie ein Audiomodell über die Modellauswahl (z. B. Orpheus TTS)",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 1258f9cad72..3c883dba2d1 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -412,6 +412,15 @@ export const en = {engineStudioDescription: "Uses the loaded audio model (e.g. Orpheus)",engineSystem: "System voices",engineStudio: "Load TTS model",+ engineCustom: "Custom endpoint",+ engineCustomDescription:+ "An OpenAI-compatible TTS server from your connections (e.g. Kokoro)",+ connectionLabel: "Connection",+ connectionDescription:+ "Add an OpenAI-compatible server in the Connections tab",+ connectionPlaceholder: "Select a connection",+ customModelLabel: "Model",+ customVoiceDescription: "Voice name the endpoint expects; defaults to alloy",modelLabel: "TTS model",modelDescription:"Load an audio model from the model selector (e.g. Orpheus TTS)",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex cdb1f1fc023..aa110dfe5ad 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -420,6 +420,16 @@ export const es = {"Usa el modelo de audio cargado (por ejemplo, Orpheus)",engineSystem: "Voces del sistema",engineStudio: "Cargar un modelo de TTS",+ engineCustom: "Endpoint personalizado",+ engineCustomDescription:+ "Un servidor TTS compatible con OpenAI de tus conexiones (p. ej., Kokoro)",+ connectionLabel: "Conexión",+ connectionDescription:+ "Añade un servidor compatible con OpenAI en la pestaña Conexiones",+ connectionPlaceholder: "Selecciona una conexión",+ customModelLabel: "Modelo",+ customVoiceDescription:+ "Nombre de la voz que espera el endpoint; el valor predeterminado es alloy",modelLabel: "Modelo de TTS",modelDescription:"Carga un modelo de audio desde el selector de modelos (por ejemplo, Orpheus TTS)",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex a9660160c10..9e0d48e42bb 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -422,6 +422,16 @@ export const fr = {"Utilise le modèle audio chargé (par exemple Orpheus)",engineSystem: "Voix du système",engineStudio: "Charger un modèle TTS",+ engineCustom: "Endpoint personnalisé",+ engineCustomDescription:+ "Un serveur TTS compatible OpenAI parmi vos connexions (p. ex. Kokoro)",+ connectionLabel: "Connexion",+ connectionDescription:+ "Ajoutez un serveur compatible OpenAI dans l'onglet Connexions",+ connectionPlaceholder: "Sélectionner une connexion",+ customModelLabel: "Modèle",+ customVoiceDescription:+ "Nom de la voix attendu par l'endpoint ; alloy par défaut",modelLabel: "Modèle TTS",modelDescription:"Chargez un modèle audio depuis le sélecteur de modèles (par exemple Orpheus TTS)",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 545cefac584..2ee6330a5fc 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -417,6 +417,15 @@ export const hi = {"लोड किए गए ऑडियो मॉडल का उपयोग करता है (जैसे Orpheus)",engineSystem: "सिस्टम की आवाज़ें",engineStudio: "TTS मॉडल लोड करें",+ engineCustom: "कस्टम एंडपॉइंट",+ engineCustomDescription:+ "आपके कनेक्शनों में से एक OpenAI-संगत TTS सर्वर (जैसे Kokoro)",+ connectionLabel: "कनेक्शन",+ connectionDescription: "कनेक्शन टैब में OpenAI-संगत सर्वर जोड़ें",+ connectionPlaceholder: "कनेक्शन चुनें",+ customModelLabel: "मॉडल",+ customVoiceDescription:+ "एंडपॉइंट द्वारा अपेक्षित वॉइस नाम; डिफ़ॉल्ट alloy है",modelLabel: "TTS मॉडल",modelDescription:"मॉडल सिलेक्टर से एक ऑडियो मॉडल लोड करें (जैसे Orpheus TTS)",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex d7a42996c43..073f679b05b 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -386,6 +386,16 @@ export const it = {engineStudioDescription: "Usa il modello audio caricato (es. Orpheus)",engineSystem: "Voci di sistema",engineStudio: "Carica un modello TTS",+ engineCustom: "Endpoint personalizzato",+ engineCustomDescription:+ "Un server TTS compatibile con OpenAI dalle tue connessioni (ad es. Kokoro)",+ connectionLabel: "Connessione",+ connectionDescription:+ "Aggiungi un server compatibile con OpenAI nella scheda Connessioni",+ connectionPlaceholder: "Seleziona una connessione",+ customModelLabel: "Modello",+ customVoiceDescription:+ "Nome della voce atteso dall'endpoint; il valore predefinito è alloy",modelLabel: "Modello TTS",modelDescription:"Carica un modello audio dal selettore dei modelli (es. Orpheus TTS)",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex cd2f994376e..74b8c42df8a 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -416,6 +416,15 @@ export const ja = {"読み込み済みの音声モデルを使用します (例: Orpheus)",engineSystem: "システムの音声",engineStudio: "TTS モデルを読み込む",+ engineCustom: "カスタムエンドポイント",+ engineCustomDescription:+ "接続に登録した OpenAI 互換の TTS サーバー(例: Kokoro)",+ connectionLabel: "接続",+ connectionDescription:+ "OpenAI 互換サーバーは「接続」タブで追加できます",+ connectionPlaceholder: "接続を選択",+ customModelLabel: "モデル",+ customVoiceDescription: "エンドポイントが期待する音声名(デフォルトは alloy)",modelLabel: "TTS モデル",modelDescription:"モデルセレクターから音声モデルを読み込んでください (例: Orpheus TTS)",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 6b1fcb040de..2556b70a6f3 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -412,6 +412,15 @@ export const ko = {engineStudioDescription: "로드된 오디오 모델을 사용합니다(예: Orpheus)",engineSystem: "시스템 음성",engineStudio: "TTS 모델 로드",+ engineCustom: "사용자 지정 엔드포인트",+ engineCustomDescription:+ "연결에 저장된 OpenAI 호환 TTS 서버 (예: Kokoro)",+ connectionLabel: "연결",+ connectionDescription:+ "OpenAI 호환 서버는 연결 탭에서 추가할 수 있습니다",+ connectionPlaceholder: "연결 선택",+ customModelLabel: "모델",+ customVoiceDescription: "엔드포인트가 기대하는 음성 이름 (기본값: alloy)",modelLabel: "TTS 모델",modelDescription:"모델 선택기에서 오디오 모델을 로드하세요(예: Orpheus TTS)",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 4d2e1bf48f5..f353439a241 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -418,6 +418,16 @@ export const ptBR = {"Usa o modelo de áudio carregado (por exemplo, Orpheus)",engineSystem: "Vozes do sistema",engineStudio: "Carregar modelo de TTS",+ engineCustom: "Endpoint personalizado",+ engineCustomDescription:+ "Um servidor TTS compatível com OpenAI das suas conexões (ex.: Kokoro)",+ connectionLabel: "Conexão",+ connectionDescription:+ "Adicione um servidor compatível com OpenAI na aba Conexões",+ connectionPlaceholder: "Selecione uma conexão",+ customModelLabel: "Modelo",+ customVoiceDescription:+ "Nome da voz esperado pelo endpoint; o padrão é alloy",modelLabel: "Modelo de TTS",modelDescription:"Carregue um modelo de áudio pelo seletor de modelos (por exemplo, Orpheus TTS)",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 5195bdb96a9..428ae670b34 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -417,6 +417,16 @@ export const ru = {"Использует загруженную аудиомодель (например, Orpheus)",engineSystem: "Системные голоса",engineStudio: "Загрузить модель TTS",+ engineCustom: "Пользовательский эндпоинт",+ engineCustomDescription:+ "OpenAI-совместимый TTS-сервер из ваших подключений (например, Kokoro)",+ connectionLabel: "Подключение",+ connectionDescription:+ "Добавьте OpenAI-совместимый сервер на вкладке «Подключения»",+ connectionPlaceholder: "Выберите подключение",+ customModelLabel: "Модель",+ customVoiceDescription:+ "Имя голоса, которое ожидает эндпоинт; по умолчанию alloy",modelLabel: "Модель TTS",modelDescription:"Загрузите аудиомодель из списка моделей (например, Orpheus TTS)",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex a5b4b91d0b6..f2fe139ef1f 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -405,6 +405,14 @@ export const zhCN = {engineStudioDescription: "使用已加载的音频模型(例如 Orpheus)",engineSystem: "系统语音",engineStudio: "加载 TTS 模型",+ engineCustom: "自定义端点",+ engineCustomDescription:+ "来自连接的 OpenAI 兼容 TTS 服务器(例如 Kokoro)",+ connectionLabel: "连接",+ connectionDescription: "在“连接”标签页中添加 OpenAI 兼容服务器",+ connectionPlaceholder: "选择连接",+ customModelLabel: "模型",+ customVoiceDescription: "端点所需的语音名称(默认为 alloy)",modelLabel: "TTS 模型",modelDescription: "从模型选择器加载音频模型(例如 Orpheus TTS)",openAudioAction: "打开音频",diff --git a/studio/frontend/tests/read-aloud-tts-model-row.test.ts b/studio/frontend/tests/read-aloud-tts-model-row.test.tsindex e263404e995..e8ad0df6cef 100644--- a/studio/frontend/tests/read-aloud-tts-model-row.test.ts+++ b/studio/frontend/tests/read-aloud-tts-model-row.test.ts@@ -46,15 +46,23 @@ test("the row lands on the TTS selector, not the mode Audio was left in", () =>);});+test("custom TTS explains the strict voice default", () => {+ assert.match(+ en,+ /customVoiceDescription: "Voice name the endpoint expects; defaults to alloy",/,+ );+ assert.doesNotMatch(en, /customVoiceDescription: .*optional/i);+});+test("a studio preview shows the generate wait instead of an idle button", () => {// Stop during the generate wait read as idle, and extra clicks orphaned requests.assert.match(source,- /markPreviewing\(true\);\s*setPreparingPreview\(true\);\s*try \{\s*const url = await generateStudioTtsAudio\(/,+ /markPreviewing\(true\);\s*setPreparingPreview\(true\);\s*try \{\s*const generate =[\s\S]*?const url = await generate\(/,);assert.match(source,- /if \(controller\.signal\.aborted\) return;\s*setPreparingPreview\(false\);/,+ /if \(controller\.signal\.aborted\) \{\s*releaseTtsAudioUrl\(url\);\s*return;\s*\}\s*setPreparingPreview\(false\);/,);// Every other exit goes through markPreviewing, so clearing there covers them all.assert.match(diff --git a/studio/frontend/tests/tts-custom-connections-disabled.test.ts b/studio/frontend/tests/tts-custom-connections-disabled.test.tsnew file mode 100644index 00000000000..1767286ecf5--- /dev/null+++ b/studio/frontend/tests/tts-custom-connections-disabled.test.ts@@ -0,0 +1,354 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// #9214: "Enable connections" is a frontend-only flag, so the request guard is the+// whole enforcement; custom TTS posted assistant text with connections switched off.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++import { loadWithStubs } from "./helpers/module-stubs.ts";++type Adapter = {+ generateCustomTtsAudio: (+ text: string,+ signal?: AbortSignal,+ ) => Promise<string>;+};++type AuthApi = {+ authFetch: (+ input: string,+ init?: RequestInit,+ options?: { beforeRetry?: () => void },+ ) => Promise<Response>;+};++type StubProvider = {+ id: string;+ hasApiKey: boolean;+ baseUrl?: string;+ providerType?: string;+ backendProviderType?: string;+ updatedAt?: number;+};++/** The adapter with both stores faked and a fetch that only logs. */+function load(+ connectionsEnabled: boolean,+ {+ providers = [{ id: "conn-1", hasApiKey: true }],+ legacyKey = "",+ voice = "af_sky",+ encrypt = async (key: string) => `enc(${key})`,+ beforeAuthenticatedRetry,+ }: {+ providers?: StubProvider[];+ legacyKey?: string;+ voice?: string;+ encrypt?: (key: string) => Promise<string>;+ beforeAuthenticatedRetry?: () => void;+ } = {},+): {+ adapter: Adapter;+ posted: string[];+ clearedProviderIds: string[];+ setConnectionsEnabled: (enabled: boolean) => void;+ setProviders: (providers: StubProvider[]) => void;+} {+ const posted: string[] = [];+ const clearedProviderIds: string[] = [];+ let currentConnectionsEnabled = connectionsEnabled;+ let currentProviders = providers;+ const adapter = loadWithStubs<Adapter>(+ new URL(+ "../src/features/chat/adapters/studio-speech-synthesis-adapter.ts",+ import.meta.url,+ ),+ {+ "@/features/auth": {+ authFetch: async (+ _input: string,+ init: { body: string },+ options?: { beforeRetry?: () => void },+ ) => {+ if (beforeAuthenticatedRetry) {+ beforeAuthenticatedRetry();+ options?.beforeRetry?.();+ }+ posted.push(init.body);+ return {+ ok: true,+ blob: async () => "audio-blob",+ };+ },+ },+ "../search-images/search-images": {+ stripSearchImageTokens: (text: string) => text,+ },+ "../stores/external-providers-store": {+ useExternalProvidersStore: {+ getState: () => ({+ connectionsEnabled: currentConnectionsEnabled,+ providers: currentProviders,+ }),+ },+ },+ "../api/providers-api": {+ encryptProviderApiKey: encrypt,+ },+ "../external-providers": {+ getExternalProviderApiKey: () => legacyKey,+ },+ "@/features/settings/stores/voice-settings-store": {+ useVoiceSettingsStore: {+ getState: () => ({+ ttsProviderId: "conn-1",+ ttsProviderModel: "kokoro",+ ttsProviderVoice: voice,+ setTtsProviderId: (value: string) => clearedProviderIds.push(value),+ }),+ },+ },+ "@/lib/toast": { toast: { error: () => {} } },+ },+ );+ return {+ adapter,+ posted,+ clearedProviderIds,+ setConnectionsEnabled: (enabled) => {+ currentConnectionsEnabled = enabled;+ },+ setProviders: (nextProviders) => {+ currentProviders = nextProviders;+ },+ };+}++Object.assign(globalThis, {+ URL: Object.assign(URL, { createObjectURL: () => "blob:tts" }),+});++test("custom TTS sends nothing once connections are switched off", async () => {+ const { adapter, posted } = load(false);+ await assert.rejects(+ adapter.generateCustomTtsAudio("secret assistant reply"),+ /Connections are disabled/,+ );+ assert.deepEqual(posted, []);+});++test("custom TTS still reaches the saved connection while connections are on", async () => {+ const { adapter, posted } = load(true);+ assert.equal(await adapter.generateCustomTtsAudio("hello"), "blob:tts");+ assert.equal(posted.length, 1);+ assert.deepEqual(JSON.parse(posted[0]), {+ input: "hello",+ provider_id: "conn-1",+ model: "kokoro",+ voice: "af_sky",+ });+});++test("custom TTS defaults a blank voice for strict OpenAI-compatible endpoints", async () => {+ const { adapter, posted } = load(true, { voice: " " });+ await adapter.generateCustomTtsAudio("hello");+ assert.equal(JSON.parse(posted[0]).voice, "alloy");+});++test("custom TTS rejects a deleted provider even when Voice settings is unmounted", async () => {+ const { adapter, posted, clearedProviderIds } = load(true, { providers: [] });+ await assert.rejects(+ adapter.generateCustomTtsAudio("must stay local"),+ /connection.*no longer exists/i,+ );+ assert.deepEqual(posted, []);+ assert.deepEqual(clearedProviderIds, [""]);+});++test("custom TTS rechecks the global switch after legacy-key encryption", async () => {+ let releaseEncryption: ((value: string) => void) | undefined;+ const encryption = new Promise<string>((resolve) => {+ releaseEncryption = resolve;+ });+ const { adapter, posted, setConnectionsEnabled } = load(true, {+ providers: [{ id: "conn-1", hasApiKey: false }],+ legacyKey: "sk-legacy",+ encrypt: async () => encryption,+ });++ const pending = adapter.generateCustomTtsAudio("secret assistant reply");+ await Promise.resolve();+ setConnectionsEnabled(false);+ releaseEncryption?.("enc(sk-legacy)");++ await assert.rejects(pending, /Connections are disabled/);+ assert.deepEqual(posted, []);+});++test("custom TTS does not send a captured legacy key after the connection changes", async () => {+ let releaseEncryption: ((value: string) => void) | undefined;+ const encryption = new Promise<string>((resolve) => {+ releaseEncryption = resolve;+ });+ const { adapter, posted, setProviders } = load(true, {+ providers: [+ {+ id: "conn-1",+ hasApiKey: false,+ baseUrl: "https://old-tts.example/v1",+ providerType: "custom",+ backendProviderType: "custom",+ updatedAt: 1,+ },+ ],+ legacyKey: "sk-legacy",+ encrypt: async () => encryption,+ });++ const pending = adapter.generateCustomTtsAudio("secret assistant reply");+ await Promise.resolve();+ setProviders([+ {+ id: "conn-1",+ hasApiKey: true,+ baseUrl: "https://new-tts.example/v1",+ providerType: "custom",+ backendProviderType: "custom",+ updatedAt: 2,+ },+ ]);+ releaseEncryption?.("enc(sk-legacy)");++ await assert.rejects(pending, /connection changed/i);+ assert.deepEqual(posted, []);+});++test("custom TTS rechecks the connection switch before an authenticated retry", async () => {+ let disableConnections = () => {};+ const loaded = load(true, {+ beforeAuthenticatedRetry: () => disableConnections(),+ });+ disableConnections = () => loaded.setConnectionsEnabled(false);++ await assert.rejects(+ loaded.adapter.generateCustomTtsAudio("secret assistant reply"),+ /Connections are disabled/,+ );+ assert.deepEqual(loaded.posted, []);+});++test("authFetch invokes its policy guard after refresh and before retry", async () => {+ let accessToken: string | null = "expired-access";+ let refreshToken: string | null = "refresh-token";+ const fetched: string[] = [];+ const originalFetch = globalThis.fetch;+ globalThis.fetch = async (input) => {+ const url = String(input);+ fetched.push(url);+ if (url === "/api/auth/refresh") {+ return new Response(+ JSON.stringify({+ access_token: "fresh-access",+ refresh_token: "fresh-refresh",+ must_change_password: false,+ }),+ { status: 200, headers: { "content-type": "application/json" } },+ );+ }+ return new Response(null, { status: fetched.length === 1 ? 401 : 200 });+ };++ try {+ const authApi = loadWithStubs<AuthApi>(+ new URL("../src/features/auth/api.ts", import.meta.url),+ {+ "@/lib/api-base": { apiUrl: (path: string) => path, isTauri: false },+ "./session": {+ clearAuthTokens: () => {+ accessToken = null;+ refreshToken = null;+ },+ getAuthToken: () => accessToken,+ getRefreshToken: () => refreshToken,+ mustChangePassword: () => false,+ setMustChangePassword: () => {},+ storeAuthTokens: (access: string, refresh: string) => {+ accessToken = access;+ refreshToken = refresh;+ },+ },+ },+ );++ await assert.rejects(+ authApi.authFetch(+ "/api/inference/audio/speech",+ { method: "POST" },+ {+ beforeRetry: () => {+ throw new Error("Connections are disabled");+ },+ },+ ),+ /Connections are disabled/,+ );+ assert.deepEqual(fetched, [+ "/api/inference/audio/speech",+ "/api/auth/refresh",+ ]);+ } finally {+ globalThis.fetch = originalFetch;+ }+});++// #9214: a failed key migration leaves the connection selectable on the retained key.+test("custom TTS forwards a retained legacy key when the connection has none saved", async () => {+ const { adapter, posted } = load(true, {+ providers: [+ {+ id: "conn-1",+ hasApiKey: false,+ baseUrl: "https://tts.example/v1",+ },+ ],+ legacyKey: "sk-legacy",+ });+ await adapter.generateCustomTtsAudio("hello");+ assert.deepEqual(JSON.parse(posted[0]), {+ input: "hello",+ provider_id: "conn-1",+ provider_base_url: "https://tts.example/v1",+ model: "kokoro",+ voice: "af_sky",+ encrypted_api_key: "enc(sk-legacy)",+ });+});++test("custom TTS sends no key when the connection already has one saved", async () => {+ const { adapter, posted } = load(true, {+ providers: [{ id: "conn-1", hasApiKey: true }],+ legacyKey: "sk-legacy",+ });+ await adapter.generateCustomTtsAudio("hello");+ assert.equal("encrypted_api_key" in JSON.parse(posted[0]), false);+});++// #9214: a deleted connection left ttsProviderId persisted, so the select pointed at a+// missing item and every read aloud posted the stale id. Mirrors the dictation guard.+test("the custom TTS selection is dropped when its connection disappears", () => {+ const voiceTab = readFileSync(+ new URL("../src/features/settings/tabs/voice-tab.tsx", import.meta.url),+ "utf8",+ );+ assert.match(+ voiceTab,+ /if \(ttsProviderId && !hasSelectedTtsConnection\) \{\s*setTtsProviderId\(""\);/,+ );+ assert.match(+ voiceTab,+ /value=\{hasSelectedTtsConnection \? ttsProviderId : ""\}/,+ );+});diff --git a/tests/studio/test_voice_settings_select_width.py b/tests/studio/test_voice_settings_select_width.pyindex 2f657b851e0..6a305e7f029 100644--- a/tests/studio/test_voice_settings_select_width.py+++ b/tests/studio/test_voice_settings_select_width.py@@ -10,7 +10,7 @@ SELECT = REPO / "studio/frontend/src/components/ui/select.tsx"def test_voice_selects_grow_without_overflowing_the_dialog():source = VOICE_TAB.read_text(encoding = "utf-8")- assert source.count('className="min-w-56 max-w-72"') == 4+ assert source.count('className="min-w-56 max-w-72"') == 5select_source = SELECT.read_text(encoding = "utf-8")assert "*:data-[slot=select-value]:line-clamp-1" in select_source