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
fix(studio): repair custom TTS endpoint test and playback (#9905)
Souravrajvi0aa2b91421b3e
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.pyindex 3be49c97e2d..22343fe5946 100644--- a/studio/backend/core/inference/external_provider.py+++ b/studio/backend/core/inference/external_provider.py@@ -8,11 +8,15 @@ Most providers use OpenAI-compatible /v1/chat/completions; Anthropic usesthe native Messages API, translated in this client."""+import asyncioimport base64+import ioimport json as _jsonimport mimetypesimport re+import threadingimport time+import wavefrom typing import Any, AsyncGenerator, Literal, NamedTuple, Optional, Unionfrom urllib.parse import urlparse, urlsplit, urlunsplit@@ -53,6 +57,83 @@ _USAGE_STREAM_OPTION_PROVIDERS = frozenset({"vllm", "openrouter", "kimi"})# existing printf-style positional args.logger = structlog.get_logger(__name__)+_MAX_CONCATENATED_WAV_BYTES = 64 * 1024 * 1024+_MAX_CONCATENATED_WAV_SEGMENTS = 1_024+++def _merge_concatenated_wav_segments(+ audio: bytes, cancelled: Optional[threading.Event] = None+) -> bytes:+ """Join a byte stream containing multiple complete WAV files into one WAV."""+ cancelled = cancelled or threading.Event()+ if len(audio) > _MAX_CONCATENATED_WAV_BYTES:+ return audio++ def _segment_offsets():+ offset = 0+ while offset < len(audio):+ if audio[offset : offset + 4] != b"RIFF" or audio[offset + 8 : offset + 12] != b"WAVE":+ raise ValueError("not a concatenated WAV stream")+ segment_end = offset + 8 + int.from_bytes(audio[offset + 4 : offset + 8], "little")+ if segment_end <= offset + 12 or segment_end > len(audio):+ raise ValueError("invalid RIFF segment length")+ yield offset, segment_end+ offset = segment_end++ try:+ params = None+ source = io.BytesIO(audio)+ segment_count = 0+ for segment_start, _segment_end in _segment_offsets():+ if cancelled.is_set():+ return audio+ segment_count += 1+ if segment_count > _MAX_CONCATENATED_WAV_SEGMENTS:+ return audio+ source.seek(segment_start)+ with wave.open(source, "rb") as reader:+ current = (+ reader.getnchannels(),+ reader.getsampwidth(),+ reader.getframerate(),+ reader.getcomptype(),+ reader.getcompname(),+ )+ if params is None:+ params = current+ elif current != params:+ return audio+ if segment_count < 2:+ return audio+ assert params is not None+ output = io.BytesIO()+ with wave.open(output, "wb") as writer:+ writer.setnchannels(params[0])+ writer.setsampwidth(params[1])+ writer.setframerate(params[2])+ writer.setcomptype(params[3], params[4])+ for segment_start, _segment_end in _segment_offsets():+ if cancelled.is_set():+ return audio+ source.seek(segment_start)+ with wave.open(source, "rb") as reader:+ expected_bytes = (+ reader.getnframes() * reader.getnchannels() * reader.getsampwidth()+ )+ observed_bytes = 0+ while frames := reader.readframes(65_536):+ if cancelled.is_set():+ return audio+ observed_bytes += len(frames)+ writer.writeframesraw(frames)+ if observed_bytes != expected_bytes:+ return audio+ return output.getvalue()+ except MemoryError:+ raise+ except Exception:+ return audio+def _append_provider_path(base_url: str, endpoint: str) -> str:"""Append an API path without moving it behind a base URL's query string."""@@ -6381,7 +6462,29 @@ class ExternalProviderClient:)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}"+ audio = response.content+ if response_format.strip().lower() == "wav":+ merge_cancelled = threading.Event()+ merge_task = asyncio.create_task(+ asyncio.to_thread(_merge_concatenated_wav_segments, audio, merge_cancelled)+ )+ try:+ audio = await asyncio.shield(merge_task)+ except asyncio.CancelledError:+ merge_cancelled.set()+ while not merge_task.done():+ try:+ await asyncio.shield(merge_task)+ except asyncio.CancelledError:+ continue+ except Exception:+ break+ try:+ merge_task.result()+ except BaseException:+ pass+ raise asyncio.CancelledError+ return audio, media_type or f"audio/{response_format}"async def create_transcription(self,diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 5a2bccfc577..197ebb90750 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -16486,10 +16486,20 @@ async def openai_audio_speech(``voice``/``speed`` ignored, and only WAV exists, so another ``response_format`` isa 400 rather than a silent container mismatch."""if body.provider_id:+ fmt = (body.response_format or "wav").strip().lower()+ if fmt != "wav":+ raise HTTPException(+ status_code = 400,+ detail = (+ f"Unsupported response_format '{body.response_format}' for an external "+ "TTS connection. Only 'wav' is supported."+ ),+ )# 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 monitordiff --git a/studio/backend/routes/providers.py b/studio/backend/routes/providers.pyindex f580d35f4bc..ce780dc1dda 100644--- a/studio/backend/routes/providers.py+++ b/studio/backend/routes/providers.py@@ -616,6 +616,69 @@ def _bind_saved_provider_target(payload):# ── Test connectivity ─────────────────────────────────────────────+async def _test_custom_provider_connectivity(client, model_id: str) -> ProviderTestResult:+ """Probe a custom OpenAI-compatible endpoint without assuming /chat/completions.++ TTS-only gateways such as Kokoro expose ``/models`` and ``/audio/speech`` but+ not ``/chat/completions``. Try those first, then fall back to a chat probe."""+ model_id = (model_id or "").strip()+ models_error: Exception | None = None+ try:+ models = await client.list_models()+ return ProviderTestResult(+ success = True,+ message = f"Connected successfully. Found {len(models)} model(s).",+ models_count = len(models),+ )+ except Exception as exc:+ models_error = exc++ if not model_id:+ return ProviderTestResult(+ success = False,+ message = (+ "Connection failed: could not reach /models and no model ID was "+ f"provided to test further. {safe_curated_detail(models_error)}"+ ),+ models_count = None,+ )++ try:+ await client.create_speech(+ text = ".",+ model = model_id,+ voice = "alloy",+ response_format = "wav",+ )+ return ProviderTestResult(+ success = True,+ message = "Connected successfully. Audio speech endpoint responded.",+ models_count = None,+ )+ except Exception:+ pass++ try:+ await client.chat_completion(+ messages = [{"role": "user", "content": "ping"}],+ model = model_id,+ temperature = 0.0,+ top_p = 1.0,+ max_tokens = 1,+ )+ return ProviderTestResult(+ success = True,+ message = "Connected successfully. Chat completions endpoint responded.",+ models_count = None,+ )+ except Exception as exc:+ return ProviderTestResult(+ success = False,+ message = f"Connection failed: {safe_curated_detail(exc)}",+ models_count = None,+ )++@router.post("/test", response_model = ProviderTestResult)async def test_provider(payload: ProviderTestRequest,@@ -625,9 +688,10 @@ async def test_provider("""Test connectivity to an external provider.- Makes a lightweight GET /models call to verify the API key works. Generic- custom endpoints use a chat-completions probe because /models is optional.- An explicit encrypted key takes precedence over the saved provider key.+ Makes a lightweight GET /models call to verify the API key works. Custom+ endpoints try /models first, then /audio/speech or /chat/completions when a+ model ID is available. An explicit encrypted key takes precedence over the+ saved provider key."""payload = _bind_saved_provider_target(payload)@@ -670,25 +734,7 @@ async def test_provider(try:if payload.provider_type == "custom":- model_id = (payload.model_id or "").strip()- if not model_id:- return ProviderTestResult(- success = False,- message = "Connection failed: add a model ID to test custom providers.",- models_count = None,- )- await client.chat_completion(- messages = [{"role": "user", "content": "ping"}],- model = model_id,- temperature = 0.0,- top_p = 1.0,- max_tokens = 1,- )- return ProviderTestResult(- success = True,- message = "Connected successfully. Chat completions endpoint responded.",- models_count = None,- )+ return await _test_custom_provider_connectivity(client, payload.model_id or "")if info.get("model_list_mode") == "curated":await client.verify_models_endpoint_lightweight()return ProviderTestResult(diff --git a/studio/backend/tests/test_external_provider_usage_chunk.py b/studio/backend/tests/test_external_provider_usage_chunk.pyindex f2bc3ff89a1..3ab2a09fd74 100644--- a/studio/backend/tests/test_external_provider_usage_chunk.py+++ b/studio/backend/tests/test_external_provider_usage_chunk.py@@ -248,7 +248,7 @@ def test_custom_provider_uses_chat_completions_without_auth_key(monkeypatch):assert any("ok" in line for line in lines)-def test_custom_provider_test_endpoint_probes_chat_completion(monkeypatch):+def test_custom_provider_test_endpoint_probes_models_before_chat(monkeypatch):import importlib.utilimport sysfrom pathlib import Path@@ -267,12 +267,19 @@ def test_custom_provider_test_endpoint_probes_chat_completion(monkeypatch):def __init__(self, **kwargs):captured["init"] = kwargs+ async def list_models(self):+ captured["list_models"] = True+ return [{"id": "kokoro"}, {"id": "tts-1"}]+async def chat_completion(self, **kwargs):- captured["chat_completion"] = kwargs- return {"choices": [{"message": {"content": "ok"}}]}+ raise AssertionError(+ "custom provider test must not call /chat/completions when /models works"+ )- async def list_models(self):- raise AssertionError("custom provider test must not call /models")+ async def create_speech(self, **_kwargs):+ raise AssertionError(+ "custom provider test must not call /audio/speech when /models works"+ )async def close(self):captured["closed"] = True@@ -292,8 +299,132 @@ def test_custom_provider_test_endpoint_probes_chat_completion(monkeypatch):result = _drive(run())assert result.success is True- assert result.models_count is None+ assert result.models_count == 2+ assert "Found 2 model(s)" in result.messageassert captured["init"]["provider_type"] == "custom"+ assert captured["closed"] is True+++def test_custom_provider_test_falls_back_to_speech_for_tts_only_gateways(monkeypatch):+ import importlib.util+ import sys+ from pathlib import Path++ module_path = Path(__file__).resolve().parents[1] / "routes" / "providers.py"+ spec = importlib.util.spec_from_file_location("_providers_route_under_test", module_path)+ assert spec is not None+ assert spec.loader is not None+ providers_route = importlib.util.module_from_spec(spec)+ sys.modules[spec.name] = providers_route+ spec.loader.exec_module(providers_route)++ captured: dict = {}++ class _FakeClient:+ def __init__(self, **kwargs):+ captured["init"] = kwargs++ async def list_models(self):+ raise httpx.HTTPStatusError(+ "not found",+ request = httpx.Request("GET", "http://custom.example/v1/models"),+ response = httpx.Response(+ 404, request = httpx.Request("GET", "http://custom.example/v1/models")+ ),+ )++ async def create_speech(self, **kwargs):+ captured["create_speech"] = kwargs+ return b"audio", "audio/wav"++ async def chat_completion(self, **_kwargs):+ raise AssertionError(+ "custom provider test must not call /chat/completions when /audio/speech works"+ )++ async def close(self):+ captured["closed"] = True++ monkeypatch.setattr(providers_route, "ExternalProviderClient", _FakeClient)++ async def run():+ return await providers_route.test_provider(+ providers_route.ProviderTestRequest(+ provider_type = "custom",+ base_url = "http://custom.example/v1",+ model_id = "kokoro",+ ),+ _current_subject = "unsloth",+ via_api_key = False,+ )++ result = _drive(run())+ assert result.success is True+ assert "Audio speech endpoint responded" in result.message+ assert captured["create_speech"]["model"] == "kokoro"+ assert captured["create_speech"]["voice"] == "alloy"+++def test_custom_provider_test_falls_back_to_chat_when_only_completions_exist(monkeypatch):+ import importlib.util+ import sys+ from pathlib import Path++ module_path = Path(__file__).resolve().parents[1] / "routes" / "providers.py"+ spec = importlib.util.spec_from_file_location("_providers_route_under_test", module_path)+ assert spec is not None+ assert spec.loader is not None+ providers_route = importlib.util.module_from_spec(spec)+ sys.modules[spec.name] = providers_route+ spec.loader.exec_module(providers_route)++ captured: dict = {}++ class _FakeClient:+ def __init__(self, **kwargs):+ captured["init"] = kwargs++ async def list_models(self):+ raise httpx.HTTPStatusError(+ "not found",+ request = httpx.Request("GET", "http://custom.example/v1/models"),+ response = httpx.Response(+ 404, request = httpx.Request("GET", "http://custom.example/v1/models")+ ),+ )++ async def create_speech(self, **_kwargs):+ raise httpx.HTTPStatusError(+ "not found",+ request = httpx.Request("POST", "http://custom.example/v1/audio/speech"),+ response = httpx.Response(+ 404, request = httpx.Request("POST", "http://custom.example/v1/audio/speech")+ ),+ )++ async def chat_completion(self, **kwargs):+ captured["chat_completion"] = kwargs+ return {"choices": [{"message": {"content": "ok"}}]}++ async def close(self):+ captured["closed"] = True++ monkeypatch.setattr(providers_route, "ExternalProviderClient", _FakeClient)++ async def run():+ return await providers_route.test_provider(+ providers_route.ProviderTestRequest(+ provider_type = "custom",+ base_url = "http://custom.example/v1",+ model_id = "Qwen/Qwen3-0.6B",+ ),+ _current_subject = "unsloth",+ via_api_key = False,+ )++ result = _drive(run())+ assert result.success is True+ assert "Chat completions endpoint responded" in result.messageassert captured["chat_completion"]["model"] == "Qwen/Qwen3-0.6B"assert captured["chat_completion"]["max_tokens"] == 1assert captured["closed"] is True@@ -316,6 +447,15 @@ def test_custom_provider_test_endpoint_requires_model_id(monkeypatch):def __init__(self, **kwargs):pass+ async def list_models(self):+ raise httpx.HTTPStatusError(+ "not found",+ request = httpx.Request("GET", "http://custom.example/v1/models"),+ response = httpx.Response(+ 404, request = httpx.Request("GET", "http://custom.example/v1/models")+ ),+ )+async def close(self):passdiff --git a/studio/backend/tests/test_openai_audio_speech_route.py b/studio/backend/tests/test_openai_audio_speech_route.pyindex 0bb0d725990..6203b3d8cc9 100644--- a/studio/backend/tests/test_openai_audio_speech_route.py+++ b/studio/backend/tests/test_openai_audio_speech_route.py@@ -380,9 +380,8 @@ def test_provider_id_routes_to_external_endpoint(monkeypatch):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)+def test_external_rejects_non_wav_response_format(monkeypatch):+ cli, _calls, _saved = _make_client(monkeypatch)created, speech_calls = _install_external(monkeypatch, media_type = "audio/mpeg")resp = cli.post("/v1/audio/speech",@@ -394,9 +393,10 @@ def test_external_passes_response_format_through(monkeypatch):"response_format": "mp3",},)- assert resp.status_code == 200- assert resp.headers["content-type"].startswith("audio/mpeg")- assert speech_calls[0]["response_format"] == "mp3"+ assert resp.status_code == 400+ assert "Only 'wav' is supported" in resp.json()["error"]["message"]+ assert created == []+ assert speech_calls == []def test_external_missing_model_is_400(monkeypatch):@@ -647,6 +647,173 @@ def test_provider_client_appends_speech_path_before_the_base_query(monkeypatch):asyncio.run(client.create_speech(text = "hi", model = "kokoro", instructions = "Speak warmly."))assert sent["url"] == ("http://127.0.0.1:8880/v1/audio/speech?api-version=2026-08-24")assert sent["json"]["instructions"] == "Speak warmly."+ assert "stream" not in sent["json"]+++def test_provider_client_merges_concatenated_wav_segments(monkeypatch):+ import asyncio+ import io+ import struct+ import wave++ from core.inference.external_provider import ExternalProviderClient+ import core.inference.external_provider as provider_module++ def _wav(frames, rate = 24_000):+ output = io.BytesIO()+ with wave.open(output, "wb") as writer:+ writer.setnchannels(1)+ writer.setsampwidth(2)+ writer.setframerate(rate)+ writer.writeframes(frames)+ return output.getvalue()++ first_frames = b"\x01\x00" * 2+ second_frames = b"\x02\x00" * 3++ class _Response:+ content = _wav(first_frames) + _wav(second_frames)+ headers = {"content-type": "audio/wav"}++ def raise_for_status(self):+ return None++ async def _post(_url, **_kwargs):+ return _Response()++ monkeypatch.setattr(provider_module._http_client, "post", _post)+ client = ExternalProviderClient("custom", "http://127.0.0.1:8880/v1", "")+ audio, media_type = asyncio.run(client.create_speech(text = "one. two.", model = "kokoro"))++ with wave.open(io.BytesIO(audio), "rb") as reader:+ assert reader.getnframes() == 5+ assert reader.readframes(5) == first_frames + second_frames+ assert media_type == "audio/wav"+ assert audio.count(b"RIFF") == 1+ single = _wav(first_frames)+ incompatible = single + _wav(second_frames, rate = 16_000)+ assert provider_module._merge_concatenated_wav_segments(single) == single+ assert provider_module._merge_concatenated_wav_segments(incompatible) == incompatible+ assert provider_module._merge_concatenated_wav_segments(b"not-a-wave") == b"not-a-wave"+ malformed = b"RIFF" + (12).to_bytes(4, "little") + b"WAVEJUNK" + (100).to_bytes(4, "little")+ assert provider_module._merge_concatenated_wav_segments(malformed * 2) == malformed * 2+ fmt = struct.pack("<HHIIHH", 1, 1, 8_000, 16_000, 2, 16)+ body = (+ b"WAVEfmt "+ + (16).to_bytes(4, "little")+ + fmt+ + b"data"+ + (100).to_bytes(4, "little")+ + b"\x01\x00"+ )+ truncated = b"RIFF" + len(body).to_bytes(4, "little") + body+ assert provider_module._merge_concatenated_wav_segments(truncated * 2) == truncated * 2+ tiny_pseudo_segment = b"RIFF" + (5).to_bytes(4, "little") + b"WAVE\x00"+ many_pseudo_segments = tiny_pseudo_segment * 10_000+ assert (+ provider_module._merge_concatenated_wav_segments(many_pseudo_segments)+ == many_pseudo_segments+ )+ too_many_valid_segments = _wav(b"") * (provider_module._MAX_CONCATENATED_WAV_SEGMENTS + 1)+ assert (+ provider_module._merge_concatenated_wav_segments(too_many_valid_segments)+ == too_many_valid_segments+ )+++def test_provider_client_merges_wav_off_the_event_loop(monkeypatch):+ import asyncio+ import threading++ from core.inference.external_provider import ExternalProviderClient+ import core.inference.external_provider as provider_module++ merge_started = threading.Event()+ release_merge = threading.Event()++ class _Response:+ content = b"audio"+ headers = {"content-type": "audio/wav"}++ def raise_for_status(self):+ return None++ async def _post(_url, **_kwargs):+ return _Response()++ def _blocking_merge(audio, _cancelled):+ merge_started.set()+ release_merge.wait()+ return audio++ monkeypatch.setattr(provider_module._http_client, "post", _post)+ monkeypatch.setattr(provider_module, "_merge_concatenated_wav_segments", _blocking_merge)++ async def _run():+ client = ExternalProviderClient("custom", "http://127.0.0.1:8880/v1", "")+ speech_task = asyncio.create_task(client.create_speech(text = "hi", model = "kokoro"))+ while not merge_started.is_set():+ await asyncio.sleep(0)+ heartbeat_seen = False+ await asyncio.sleep(0)+ heartbeat_seen = True+ release_merge.set()+ await speech_task+ return heartbeat_seen++ assert asyncio.run(_run()) is True+++def test_cancelling_provider_speech_stops_the_wav_worker(monkeypatch):+ import asyncio+ import threading++ from core.inference.external_provider import ExternalProviderClient+ import core.inference.external_provider as provider_module++ merge_started = threading.Event()+ merge_cancel_seen = threading.Event()+ merge_stopped = threading.Event()+ release_merge = threading.Event()++ class _Response:+ content = b"audio"+ headers = {"content-type": "audio/wav"}++ def raise_for_status(self):+ return None++ async def _post(_url, **_kwargs):+ return _Response()++ def _cancellable_merge(audio, cancelled):+ merge_started.set()+ cancelled.wait()+ merge_cancel_seen.set()+ release_merge.wait()+ merge_stopped.set()+ return audio++ monkeypatch.setattr(provider_module._http_client, "post", _post)+ monkeypatch.setattr(provider_module, "_merge_concatenated_wav_segments", _cancellable_merge)++ async def _run():+ client = ExternalProviderClient("custom", "http://127.0.0.1:8880/v1", "")+ speech_task = asyncio.create_task(client.create_speech(text = "hi", model = "kokoro"))+ while not merge_started.is_set():+ await asyncio.sleep(0)+ speech_task.cancel()+ while not merge_cancel_seen.is_set():+ await asyncio.sleep(0)+ speech_task.cancel()+ await asyncio.sleep(0)+ assert not speech_task.done()+ release_merge.set()+ with pytest.raises(asyncio.CancelledError):+ await speech_task+ assert merge_stopped.is_set()++ asyncio.run(_run())def test_external_provider_reads_do_not_block_the_event_loop(monkeypatch):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 4052549b2f6..be91a7d0630 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@@ -348,7 +348,10 @@ export async function generateCustomTtsAudio(} | null;throw new Error(body?.detail ?? `HTTP ${response.status}`);}- return URL.createObjectURL(await response.blob());+ const bytes = await response.arrayBuffer();+ const contentType =+ response.headers.get("content-type")?.split(";")[0]?.trim() || "audio/wav";+ return URL.createObjectURL(new Blob([bytes], { type: contentType }));}/** Release a URL returned by the generate helpers (data URLs need nothing). */diff --git a/studio/frontend/tests/tts-custom-connections-disabled.test.ts b/studio/frontend/tests/tts-custom-connections-disabled.test.tsindex 1767286ecf5..54c18208e20 100644--- a/studio/frontend/tests/tts-custom-connections-disabled.test.ts+++ b/studio/frontend/tests/tts-custom-connections-disabled.test.ts@@ -80,7 +80,8 @@ function load(posted.push(init.body);return {ok: true,- blob: async () => "audio-blob",+ headers: { get: () => "audio/wav" },+ arrayBuffer: async () => new Uint8Array([1, 2, 3]).buffer,};},},