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: add custom stt connections (#9349)
Maheswar Kumarcb8e20620452
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.pyindex e3189c505a4..c77a48937b9 100644--- a/studio/backend/core/inference/external_provider.py+++ b/studio/backend/core/inference/external_provider.py@@ -862,7 +862,7 @@ def _build_kimi_tool_end(class ExternalProviderClient:- """Async proxy for OpenAI-compatible external LLM APIs."""+ """Async proxy for OpenAI-compatible external APIs."""def __init__(self,@@ -6278,6 +6278,37 @@ class ExternalProviderClient:response.raise_for_status()return response.json()+ async def create_transcription(+ self,+ audio: bytes,+ filename: str,+ content_type: str,+ model: str,+ language: Optional[str] = None,+ response_format: str = "json",+ ) -> tuple[bytes, str]:+ """Post audio to an OpenAI-compatible transcription endpoint."""+ data = {+ "model": model,+ "response_format": response_format,+ }+ if language:+ data["language"] = language+ headers = self._auth_headers()+ headers.pop("Content-Type", None)+ response = await _http_client.post(+ f"{self.base_url}/audio/transcriptions",+ headers = headers,+ files = {"file": (filename, audio, content_type)},+ data = data,+ timeout = self._timeout,+ )+ response.raise_for_status()+ media_type = (response.headers.get("content-type") or "").split(";", 1)[0].strip()+ if not media_type:+ media_type = "text/plain" if response_format == "text" else "application/json"+ return response.content, media_type+async def list_models(self) -> list[dict[str, Any]]:"""GET /models to discover available models.diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex ab3475ac9f6..63678b5c8d9 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -3510,6 +3510,16 @@ async def _await_disconnect_then_cancel(request, cancel_event) -> None:return+async def _await_disconnect_then_cancel_task(request, task: asyncio.Task) -> None:+ """Cancel one outbound request when its client disconnects."""+ try:+ while not await request.is_disconnected():+ await asyncio.sleep(0.1)+ task.cancel()+ except asyncio.CancelledError:+ return++async def _await_stt_disconnect_then_cancel(request, sidecar, cancel_event) -> None:"""Cancel this sidecar request, including a model load still starting."""try:@@ -12124,6 +12134,108 @@ async def openai_audio_speech(return Response(content = wav_bytes, media_type = "audio/wav")+async def _external_stt_transcription(+ *,+ provider_id: str,+ raw: bytes,+ filename: str,+ content_type: str,+ model: Optional[str],+ language: Optional[str],+ response_format: str,+ encrypted_api_key: Optional[str],+ request: Request,+) -> Response:+ provider_id = provider_id.strip()+ if not provider_id:+ raise HTTPException(status_code = 400, detail = "provider_id cannot be empty.")+ if not raw:+ raise HTTPException(status_code = 400, detail = "Audio is empty.")+ if len(raw) > _MAX_AUDIO_RAW_BYTES:+ raise HTTPException(status_code = 413, detail = "Audio is too large.")+ external_model = (model or "").strip()+ if not external_model:+ raise HTTPException(+ status_code = 400,+ detail = "model is required when using an external STT 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.")+ 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.",+ )+ api_key = await asyncio.to_thread(+ resolve_provider_api_key_or_400,+ provider_id,+ encrypted_api_key,+ allow_saved_key = not _request_has_api_key(request),+ )++ client = ExternalProviderClient(+ provider_type = config["provider_type"],+ base_url = base_url,+ api_key = api_key,+ )+ transcription_task = asyncio.create_task(+ client.create_transcription(+ audio = raw,+ filename = filename,+ content_type = content_type,+ model = external_model,+ language = language,+ response_format = response_format,+ )+ )+ disconnect_watcher = asyncio.create_task(+ _await_disconnect_then_cancel_task(request, transcription_task)+ )+ try:+ body, media_type = await transcription_task+ except httpx.HTTPStatusError as exc:+ detail = exc.response.text[:300] if exc.response is not None else str(exc)+ raise HTTPException(+ status_code = 502,+ detail = (+ f"STT endpoint returned HTTP {exc.response.status_code}: {detail}"+ if exc.response is not None+ else f"STT endpoint rejected the request: {detail}"+ ),+ ) from exc+ except httpx.HTTPError as exc:+ raise log_and_http_error(+ exc,+ 502,+ "Could not reach the STT endpoint.",+ event = "external_stt.transport_error",+ log = logger,+ ) from exc+ finally:+ await _stop_local_disconnect_cancel_watcher(disconnect_watcher)+ return Response(content = body, media_type = media_type)++# openai-compatible transcription api, dual-mounted like /audio/speech; runs on the stt sidecar, not the main gpu slot@router.post("/audio/transcriptions")async def openai_audio_transcriptions(@@ -12132,12 +12244,15 @@ async def openai_audio_transcriptions(model: Optional[str] = Form(None),language: Optional[str] = Form(None),response_format: str = Form("json"),+ provider_id: Optional[str] = Form(None),+ encrypted_api_key: Optional[str] = Form(None),current_subject: str = Depends(get_current_subject),):"""OpenAI-compatible speech-to-text (POST /v1/audio/transcriptions).- ``model`` maps to a sidecar model id, with ``whisper-1`` or nothing selecting the- default. ``response_format`` supports ``json`` and ``text``."""+ With ``provider_id`` set, the request is proxied to that saved connection.+ Otherwise ``model`` maps to a sidecar model id, with ``whisper-1`` or nothing+ selecting the default. ``response_format`` supports ``json`` and ``text``."""fmt = (response_format or "json").strip().lower()if fmt not in ("json", "text"):raise HTTPException(@@ -12147,6 +12262,18 @@ async def openai_audio_transcriptions(# UploadFile spools to disk, but an unbounded read materializes the whole upload in# memory before the shared size check. One byte past the limit is enough to reject it.raw = await file.read(_MAX_AUDIO_RAW_BYTES + 1)+ if isinstance(provider_id, str):+ return await _external_stt_transcription(+ provider_id = provider_id,+ raw = raw,+ filename = file.filename or "audio",+ content_type = file.content_type or "application/octet-stream",+ model = model,+ language = language,+ response_format = fmt,+ encrypted_api_key = encrypted_api_key,+ request = request,+ )# openai's whisper-1 placeholder means the default transcription model, not a sidecar idsidecar_model = None if model in (None, "", "whisper-1") else modelresult = await _transcribe_audio_result(diff --git a/studio/backend/tests/test_openai_audio_transcriptions_route.py b/studio/backend/tests/test_openai_audio_transcriptions_route.pyindex c3fbc625112..1f2e4aa262f 100644--- a/studio/backend/tests/test_openai_audio_transcriptions_route.py+++ b/studio/backend/tests/test_openai_audio_transcriptions_route.py@@ -57,10 +57,11 @@ def _post(data = None,filename = "clip.wav",content = b"RIFFfake",+ content_type = "audio/wav",):return cli.post("/v1/audio/transcriptions",- files = {"file": (filename, content, "audio/wav")},+ files = {"file": (filename, content, content_type)},data = data or {},)@@ -169,3 +170,310 @@ def test_the_studio_json_route_also_forwards_the_request(monkeypatch):assert resp.status_code == 200assert calls[0]["raw"] == b"RIFFfake"assert calls[0]["request"] is not None+++def _install_external(+ monkeypatch,+ *,+ enabled = True,+ media_type = "application/json",+):+ client_args = []+ transcription_calls = []+ credential_calls = []+ config = {+ "provider_type": "custom",+ "display_name": "Whisper Box",+ "base_url": "http://stt.local:8000/v1",+ "is_enabled": enabled,+ }++ monkeypatch.setattr(+ routes_module.providers_db,+ "get_provider",+ lambda provider_id: dict(config) if provider_id == "conn-1" else None,+ )+ monkeypatch.setattr(routes_module, "validate_provider_base_url", lambda url: url)++ def _resolve_api_key(+ provider_id,+ encrypted_api_key,+ *,+ allow_saved_key = True,+ ):+ credential_calls.append(+ {+ "provider_id": provider_id,+ "encrypted_api_key": encrypted_api_key,+ "allow_saved_key": allow_saved_key,+ }+ )+ return "sk-test" if allow_saved_key else ""++ monkeypatch.setattr(routes_module, "resolve_provider_api_key_or_400", _resolve_api_key)++ class _FakeClient:+ def __init__(self, provider_type, base_url, api_key):+ client_args.append(+ {+ "provider_type": provider_type,+ "base_url": base_url,+ "api_key": api_key,+ }+ )++ async def create_transcription(self, **kwargs):+ transcription_calls.append(kwargs)+ body = b"remote words" if media_type == "text/plain" else b'{"text":"remote words"}'+ return body, media_type++ monkeypatch.setattr(routes_module, "ExternalProviderClient", _FakeClient)+ return client_args, transcription_calls, credential_calls+++def test_provider_id_routes_to_external_endpoint_without_loading_the_sidecar(monkeypatch):+ cli, sidecar_calls = _make_client(monkeypatch)+ client_args, transcription_calls, credential_calls = _install_external(monkeypatch)+ resp = _post(+ cli,+ data = {+ "provider_id": "conn-1",+ "model": "Systran/faster-distil-whisper-large-v3",+ "language": "en",+ },+ filename = "dictation.webm",+ content = b"webm-audio",+ content_type = "audio/webm",+ )++ assert resp.status_code == 200+ assert resp.json() == {"text": "remote words"}+ assert sidecar_calls == []+ assert client_args == [+ {+ "provider_type": "custom",+ "base_url": "http://stt.local:8000/v1",+ "api_key": "sk-test",+ }+ ]+ assert transcription_calls == [+ {+ "audio": b"webm-audio",+ "filename": "dictation.webm",+ "content_type": "audio/webm",+ "model": "Systran/faster-distil-whisper-large-v3",+ "language": "en",+ "response_format": "json",+ }+ ]+ assert credential_calls[0]["allow_saved_key"] is True+++def test_external_text_response_keeps_plain_text_shape(monkeypatch):+ cli, sidecar_calls = _make_client(monkeypatch)+ _install_external(monkeypatch, media_type = "text/plain")+ resp = _post(+ cli,+ data = {+ "provider_id": "conn-1",+ "model": "whisper-1",+ "response_format": "text",+ },+ )++ assert resp.status_code == 200+ assert resp.text == "remote words"+ assert resp.headers["content-type"].startswith("text/plain")+ assert sidecar_calls == []+++def test_external_connection_requires_a_model(monkeypatch):+ cli, sidecar_calls = _make_client(monkeypatch)+ client_args, _, _ = _install_external(monkeypatch)+ resp = _post(cli, data = {"provider_id": "conn-1"})++ assert resp.status_code == 400+ assert "model is required" in resp.json()["error"]["message"]+ assert client_args == []+ assert sidecar_calls == []+++ ("provider_id", "enabled", "status"),+ [("missing", True, 404), ("conn-1", False, 400)],+)+def test_external_connection_must_exist_and_be_enabled(monkeypatch, provider_id, enabled, status):+ cli, sidecar_calls = _make_client(monkeypatch)+ client_args, _, _ = _install_external(monkeypatch, enabled = enabled)+ resp = _post(+ cli,+ data = {"provider_id": provider_id, "model": "whisper-1"},+ )++ assert resp.status_code == status+ assert client_args == []+ assert sidecar_calls == []+++def test_external_connection_validates_the_url_before_reading_its_key(monkeypatch):+ cli, sidecar_calls = _make_client(monkeypatch)+ _, _, credential_calls = _install_external(monkeypatch)++ def _reject_url(_url):+ raise ValueError("refused target")++ monkeypatch.setattr(routes_module, "validate_provider_base_url", _reject_url)+ resp = _post(+ cli,+ data = {"provider_id": "conn-1", "model": "whisper-1"},+ )++ assert resp.status_code == 400+ assert credential_calls == []+ assert sidecar_calls == []+++def test_api_key_callers_cannot_spend_a_saved_external_stt_key(monkeypatch):+ cli, sidecar_calls = _make_client(monkeypatch)+ client_args, _, credential_calls = _install_external(monkeypatch)+ resp = cli.post(+ "/v1/audio/transcriptions",+ files = {"file": ("clip.wav", b"RIFFfake", "audio/wav")},+ data = {"provider_id": "conn-1", "model": "whisper-1"},+ headers = {"Authorization": "Bearer sk-unsloth-test"},+ )++ assert resp.status_code == 200+ assert credential_calls[0]["allow_saved_key"] is False+ assert client_args[0]["api_key"] == ""+ assert sidecar_calls == []+++def test_external_connection_accepts_a_legacy_encrypted_key(monkeypatch):+ cli, sidecar_calls = _make_client(monkeypatch)+ _, _, credential_calls = _install_external(monkeypatch)+ resp = _post(+ cli,+ data = {+ "provider_id": "conn-1",+ "model": "whisper-1",+ "encrypted_api_key": "sealed-key",+ },+ )++ assert resp.status_code == 200+ assert credential_calls[0]["encrypted_api_key"] == "sealed-key"+ assert sidecar_calls == []+++def test_external_upstream_errors_are_502(monkeypatch):+ import httpx++ cli, sidecar_calls = _make_client(monkeypatch)+ _install_external(monkeypatch)++ async def _reject(self, **kwargs):+ request = httpx.Request("POST", "http://stt.local:8000/v1/audio/transcriptions")+ response = httpx.Response(503, text = "not ready", request = request)+ raise httpx.HTTPStatusError("rejected", request = request, response = response)++ monkeypatch.setattr(routes_module.ExternalProviderClient, "create_transcription", _reject)+ resp = _post(+ cli,+ data = {"provider_id": "conn-1", "model": "whisper-1"},+ )++ assert resp.status_code == 502+ assert "HTTP 503" in resp.json()["error"]["message"]+ assert sidecar_calls == []+++def test_external_disconnect_cancels_the_upstream_request(monkeypatch):+ import asyncio++ _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_transcription(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_stt_transcription(+ provider_id = "conn-1",+ raw = b"RIFFfake",+ filename = "clip.wav",+ content_type = "audio/wav",+ model = "whisper-1",+ language = None,+ response_format = "json",+ encrypted_api_key = None,+ request = _DisconnectingRequest(),+ )++ asyncio.run(_run())+ assert upstream_cancelled.is_set()+++def test_external_client_sends_openai_compatible_multipart(monkeypatch):+ import asyncio+ import httpx++ import core.inference.external_provider as provider_module++ captured = {}++ class _HttpClient:+ async def post(self, url, **kwargs):+ captured.update(url = url, **kwargs)+ request = httpx.Request("POST", url)+ return httpx.Response(+ 200,+ content = b'{"text":"hello"}',+ headers = {"content-type": "application/json; charset=utf-8"},+ request = request,+ )++ monkeypatch.setattr(provider_module, "_http_client", _HttpClient())+ client = provider_module.ExternalProviderClient(+ provider_type = "custom",+ base_url = "https://stt.example.com/v1",+ api_key = "sk-test",+ )+ body, media_type = asyncio.run(+ client.create_transcription(+ audio = b"webm-audio",+ filename = "dictation.webm",+ content_type = "audio/webm",+ model = "whisper-1",+ language = "en",+ )+ )++ assert body == b'{"text":"hello"}'+ assert media_type == "application/json"+ assert captured["url"] == "https://stt.example.com/v1/audio/transcriptions"+ assert "Content-Type" not in captured["headers"]+ assert captured["headers"]["Authorization"] == "Bearer sk-test"+ assert captured["files"] == {"file": ("dictation.webm", b"webm-audio", "audio/webm")}+ assert captured["data"] == {+ "model": "whisper-1",+ "response_format": "json",+ "language": "en",+ }diff --git a/studio/frontend/src/features/chat/adapters/studio-dictation-adapter.tsx b/studio/frontend/src/features/chat/adapters/studio-dictation-adapter.tsxindex 037db816d05..42d24932727 100644--- a/studio/frontend/src/features/chat/adapters/studio-dictation-adapter.tsx+++ b/studio/frontend/src/features/chat/adapters/studio-dictation-adapter.tsx@@ -8,6 +8,7 @@ import {} from "@/features/settings/stores/voice-settings-store";import { toast } from "@/lib/toast";import type { DictationAdapter } from "@assistant-ui/react";+import { useExternalProvidersStore } from "../stores/external-providers-store";import {StudioModelDictationAdapter,fetchSttStatus,@@ -34,9 +35,22 @@ export function cancelActiveStudioDictation(): void {* Routes dictation to the engine chosen in Voice settings, resolved at listen()* time so switching engines applies without reloading the chat runtime.*/-/** Both local engines (Transformers and GGUF) record via MediaRecorder. */-function usesModelRecording(dictationEngine: DictationEngine): boolean {- return dictationEngine === "model";+/** local and custom transcription record through the media recorder. */+function usesRecordedAudio(dictationEngine: DictationEngine): boolean {+ return dictationEngine !== "browser";+}++function customSttConfigured(): boolean {+ const { sttProviderId, sttProviderModel } = useVoiceSettingsStore.getState();+ const { connectionsEnabled, providers } =+ useExternalProvidersStore.getState();+ const providerId = sttProviderId.trim();+ return Boolean(+ connectionsEnabled &&+ providerId &&+ sttProviderModel.trim() &&+ providers.some((provider) => provider.id === providerId),+ );}export class StudioDictationAdapter implements DictationAdapter {@@ -52,7 +66,10 @@ export class StudioDictationAdapter implements DictationAdapter {dictationEngine: DictationEngine = useVoiceSettingsStore.getState().dictationEngine,): boolean {- return usesModelRecording(dictationEngine)+ if (dictationEngine === "custom" && !customSttConfigured()) {+ return false;+ }+ return usesRecordedAudio(dictationEngine)? StudioModelDictationAdapter.isSupported(): StudioWebSpeechDictationAdapter.isSupported();}@@ -77,12 +94,19 @@ export class StudioDictationAdapter implements DictationAdapter {private createSession(): StudioDictationSession {const { dictationEngine } = useVoiceSettingsStore.getState();- if (usesModelRecording(dictationEngine)) {+ if (usesRecordedAudio(dictationEngine)) {+ if (dictationEngine === "custom" && !customSttConfigured()) {+ throw new Error(+ "Custom transcription is not configured. Pick a connection and model in Settings → Voice.",+ );+ }if (StudioModelDictationAdapter.isSupported()) {return new StudioModelDictationAdapter({ chatId: this.chatId }).listen();}throw new Error(- "Local model dictation is not supported in this browser.",+ dictationEngine === "custom"+ ? "Voice recording is not supported in this browser."+ : "Local model dictation is not supported in this browser.",);}if (StudioWebSpeechDictationAdapter.isSupported()) {@@ -113,8 +137,14 @@ export function notifyStudioDictationUnavailable(});return;}- if (usesModelRecording(dictationEngine)) {- // Defensive: MediaRecorder is effectively always present here.+ if (dictationEngine === "custom" && !customSttConfigured()) {+ toast.error("Custom transcription isn't configured.", {+ description: "Pick a connection and model in Voice settings.",+ });+ return;+ }+ if (usesRecordedAudio(dictationEngine)) {+ // defensive: media recording is effectively always present here.toast.error("Voice recording isn't available in this browser.");return;}diff --git a/studio/frontend/src/features/chat/adapters/studio-model-dictation-adapter.ts b/studio/frontend/src/features/chat/adapters/studio-model-dictation-adapter.tsindex f25c027ee26..584514dc1a7 100644--- a/studio/frontend/src/features/chat/adapters/studio-model-dictation-adapter.ts+++ b/studio/frontend/src/features/chat/adapters/studio-model-dictation-adapter.ts@@ -16,6 +16,9 @@ import {} from "@/features/settings/stores/voice-settings-store";import type { DictationAdapter } from "@assistant-ui/react";import { toast } from "sonner";+import { encryptProviderApiKey } from "../api/providers-api";+import { getExternalProviderApiKey } from "../external-providers";+import { useExternalProvidersStore } from "../stores/external-providers-store";import { startDictationLevelMeter } from "./dictation-level";import { SttModelNotDownloadedError, sttRequestError } from "./stt-errors";// Re-exported so the one public entry point for dictation is unchanged.@@ -76,22 +79,104 @@ export function sttEngineFor(model: string): SttEngine {return isCuratedSttModel(model) ? "gguf" : "transformers";}-/** POST audio to the STT sidecar and return the transcript. */+function externalSttLanguage(language: string): string | undefined {+ const normalized = language.trim().replaceAll("_", "-").toLowerCase();+ if (!normalized || normalized === "auto") {+ return undefined;+ }+ return normalized.split("-", 1)[0] || undefined;+}++function dictationFilename(contentType: string): string {+ if (contentType.includes("ogg")) {+ return "dictation.ogg";+ }+ if (contentType.includes("mp4")) {+ return "dictation.m4a";+ }+ if (contentType.includes("wav")) {+ return "dictation.wav";+ }+ return "dictation.webm";+}++async function sttErrorDetail(response: Response): Promise<string> {+ const body = (await response.json().catch(() => null)) as {+ detail?: string;+ error?: { message?: string };+ } | null;+ return body?.detail ?? body?.error?.message ?? `HTTP ${response.status}`;+}++/** post recorded audio to the selected STT backend and return its transcript. */export async function transcribeAudioBlob(blob: Blob,options: {model?: string;language?: string;engine?: SttEngine;+ providerId?: string;signal?: AbortSignal;} = {},): Promise<string> {const settings = useVoiceSettingsStore.getState();- const model = options.model ?? settings.sttModel;- const language = resolveModelDictationLanguage(- model,- options.language ?? settings.dictationLanguage,- );+ const usesExternalEndpoint = options.providerId !== undefined;+ const providerId = options.providerId?.trim() ?? "";+ const model = (+ options.model ??+ (usesExternalEndpoint ? settings.sttProviderModel : settings.sttModel)+ ).trim();+ const languageSetting = options.language ?? settings.dictationLanguage;++ if (usesExternalEndpoint) {+ const providersState = useExternalProvidersStore.getState();+ if (!providersState.connectionsEnabled) {+ throw new Error(+ "Connections are disabled. Enable connections before using custom transcription.",+ );+ }+ if (!providerId || !model) {+ throw new Error(+ "Custom transcription is not configured. Pick a connection and model in Settings → Voice.",+ );+ }+ const form = new FormData();+ form.set("file", blob, dictationFilename(blob.type));+ form.set("provider_id", providerId);+ form.set("model", model);+ form.set("response_format", "json");+ const provider = providersState.providers.find(+ (candidate) => candidate.id === providerId,+ );+ const legacyApiKey = provider?.hasApiKey+ ? ""+ : getExternalProviderApiKey(providerId).trim();+ if (legacyApiKey) {+ form.set(+ "encrypted_api_key",+ await encryptProviderApiKey(legacyApiKey),+ );+ }+ const language = externalSttLanguage(languageSetting);+ if (language) {+ form.set("language", language);+ }+ const response = await authFetch("/api/inference/audio/transcriptions", {+ method: "POST",+ body: form,+ signal: options.signal,+ });+ if (!response.ok) {+ throw sttRequestError(response.status, await sttErrorDetail(response));+ }+ const data = (await response.json()) as { text?: string };+ if (typeof data.text !== "string") {+ throw new Error("The transcription endpoint returned no text.");+ }+ return data.text.trim();+ }++ const language = resolveModelDictationLanguage(model, languageSetting);const engine = options.engine ?? sttEngineFor(model);const params = new URLSearchParams({ model, fast: "true", engine });if (language) params.set("language", language);@@ -105,10 +190,7 @@ export async function transcribeAudioBlob(},);if (!response.ok) {- const body = (await response.json().catch(() => null)) as {- detail?: string;- } | null;- const detail = body?.detail ?? `HTTP ${response.status}`;+ const detail = await sttErrorDetail(response);if (response.status === 501) {throw new Error("Speech-to-text is not available on this server. Run `unsloth studio update` to install it.",@@ -317,8 +399,8 @@ export function unloadSttModel(}/**- * Local model dictation. Short recordings use one pass; long ones split near- * Whisper's 30s window. Confirm keeps text, discard removes it, and either+ * recorded-audio dictation. short recordings use one pass; long ones split near+ * whisper's 30s window. confirm keeps text, discard removes it, and either* releases the microphone immediately.*/export class StudioModelDictationAdapter implements DictationAdapter {@@ -341,18 +423,30 @@ export class StudioModelDictationAdapter implements DictationAdapter {if (!StudioModelDictationAdapter.isSupported()) {throw new Error("Recording is not supported in this browser.");}- beginDictationSession();// Pin the model, language, and linked chat chosen when recording began, so a// mid-session settings change or thread switch cannot affect later segments// or relink the saved transcript.- const { sttModel: sessionModel, dictationLanguage } =- useVoiceSettingsStore.getState();- const sessionLanguage = resolveModelDictationLanguage(- sessionModel,- dictationLanguage,- );- const sessionEngine = sttEngineFor(sessionModel);+ const settings = useVoiceSettingsStore.getState();+ const usesExternalEndpoint = settings.dictationEngine === "custom";+ const sessionProviderId = usesExternalEndpoint+ ? settings.sttProviderId.trim()+ : undefined;+ const sessionModel = usesExternalEndpoint+ ? settings.sttProviderModel.trim()+ : settings.sttModel;+ if (usesExternalEndpoint && (!sessionProviderId || !sessionModel)) {+ throw new Error(+ "Custom transcription is not configured. Pick a connection and model in Settings → Voice.",+ );+ }+ beginDictationSession();+ const sessionLanguage = usesExternalEndpoint+ ? settings.dictationLanguage+ : resolveModelDictationLanguage(sessionModel, settings.dictationLanguage);+ const sessionEngine = usesExternalEndpoint+ ? undefined+ : sttEngineFor(sessionModel);const sessionChatId = resolveDictationChatId(this.chatId);const speechStartCallbacks = new Set<() => void>();@@ -412,7 +506,10 @@ export class StudioModelDictationAdapter implements DictationAdapter {console.error("STT transcription error:", error);// An undownloaded model is the ordinary first-run state, not a failure.// Point at the download; never start it here.- if (error instanceof SttModelNotDownloadedError) {+ if (+ !usesExternalEndpoint &&+ error instanceof SttModelNotDownloadedError+ ) {requestSttDownload(sessionModel);finishSession("cancelled");return;@@ -495,6 +592,7 @@ export class StudioModelDictationAdapter implements DictationAdapter {model: sessionModel,language: sessionLanguage,engine: sessionEngine,+ providerId: sessionProviderId,signal: abortController.signal,});if (!cancelled) results[item.index] = text;@@ -712,11 +810,12 @@ export class StudioModelDictationAdapter implements DictationAdapter {stream = null;return;}- // Warm the model only after mic access. The backend loads cache-only- // and never downloads here.- void loadSttModel(sessionModel, sessionEngine).catch((error: unknown) =>- reportTranscriptionError(error, "preload"),- );+ if (!usesExternalEndpoint && sessionEngine) {+ // warm the model only after mic access; the backend never downloads here.+ void loadSttModel(sessionModel, sessionEngine).catch(+ (error: unknown) => reportTranscriptionError(error, "preload"),+ );+ }stopLevelMeter = startDictationLevelMeter(stream, (rawRms, now) => {onAudioFrame(rawRms, now);});diff --git a/studio/frontend/src/features/settings/stores/voice-settings-store.ts b/studio/frontend/src/features/settings/stores/voice-settings-store.tsindex 57e27983f77..d467496ef7c 100644--- a/studio/frontend/src/features/settings/stores/voice-settings-store.ts+++ b/studio/frontend/src/features/settings/stores/voice-settings-store.ts@@ -78,7 +78,7 @@ export function isSttModelLanguageCompatible(return normalized === "auto" || normalized.split("-", 1)[0] === "en";}-export type DictationEngine = "browser" | "model";+export type DictationEngine = "browser" | "model" | "custom";/*** Whether a model id is curated. Whisper ids run GGML through whisper.cpp,@@ -105,7 +105,12 @@ export interface VoiceSettingsState {sttModel: SttModel;setSttModel: (value: SttModel) => void;- /** BCP 47 tag for speech recognition, or "auto" for the browser locale. */+ sttProviderId: string;+ setSttProviderId: (value: string) => void;+ sttProviderModel: string;+ setSttProviderModel: (value: string) => void;++ /** bcp 47 tag for speech recognition, or "auto" for engine-specific detection. */dictationLanguage: string;setDictationLanguage: (value: string) => void;@@ -207,6 +212,11 @@ export const useVoiceSettingsStore = create<VoiceSettingsState>()(};}),+ sttProviderId: "",+ setSttProviderId: (sttProviderId) => set({ sttProviderId }),+ sttProviderModel: "",+ setSttProviderModel: (sttProviderModel) => set({ sttProviderModel }),+dictationLanguage: "auto",setDictationLanguage: (dictationLanguage) =>set((state) => ({@@ -314,11 +324,12 @@ export const useVoiceSettingsStore = create<VoiceSettingsState>()(// "gguf" was a short-lived separate engine choice; both local// backends now live under "model".const savedEngine = saved?.dictationEngine as string | undefined;- // Desktop has no browser speech engine, so always resolve to "model".const dictationEngine: DictationEngine =- isTauri || savedEngine === "model" || savedEngine === "gguf"- ? "model"- : "browser";+ savedEngine === "custom"+ ? "custom"+ : isTauri || savedEngine === "model" || savedEngine === "gguf"+ ? "model"+ : "browser";const savedSttModel = normalizeSttModel(saved?.sttModel);const sttModel = isSttModelLanguageCompatible(savedSttModel,@@ -331,6 +342,8 @@ export const useVoiceSettingsStore = create<VoiceSettingsState>()(micDeviceId: asString(saved?.micDeviceId, "default"),dictationEngine,sttModel,+ sttProviderId: asString(saved?.sttProviderId, ""),+ sttProviderModel: asString(saved?.sttProviderModel, ""),dictationLanguage,dictionary: Array.isArray(saved?.dictionary)? saved.dictionarydiff --git a/studio/frontend/src/features/settings/tabs/voice-tab.tsx b/studio/frontend/src/features/settings/tabs/voice-tab.tsxindex 6c611dbedeb..8d58fddb70e 100644--- a/studio/frontend/src/features/settings/tabs/voice-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/voice-tab.tsx@@ -30,6 +30,7 @@ import {loadSttModel,startSttDownload,unloadSttModel,+ useExternalProvidersStore,validateSttModel,} from "@/features/chat";import {@@ -404,6 +405,12 @@ export function VoiceTab() {const setDictationEngine = useVoiceSettingsStore((s) => s.setDictationEngine);const sttModel = useVoiceSettingsStore((s) => s.sttModel);const setSttModel = useVoiceSettingsStore((s) => s.setSttModel);+ const sttProviderId = useVoiceSettingsStore((s) => s.sttProviderId);+ const setSttProviderId = useVoiceSettingsStore((s) => s.setSttProviderId);+ const sttProviderModel = useVoiceSettingsStore((s) => s.sttProviderModel);+ const setSttProviderModel = useVoiceSettingsStore(+ (s) => s.setSttProviderModel,+ );const dictationLanguage = useVoiceSettingsStore((s) => s.dictationLanguage);const setDictationLanguage = useVoiceSettingsStore((s) => s.setDictationLanguage,@@ -420,6 +427,14 @@ export function VoiceTab() {const setTtsPitch = useVoiceSettingsStore((s) => s.setTtsPitch);const ttsVolume = useVoiceSettingsStore((s) => s.ttsVolume);const setTtsVolume = useVoiceSettingsStore((s) => s.setTtsVolume);+ const sttConnections = useExternalProvidersStore((s) => s.providers);+ const connectionsEnabled = useExternalProvidersStore(+ (s) => s.connectionsEnabled,+ );+ const hasSttConnections = sttConnections.length > 0;+ const hasSelectedSttConnection = sttConnections.some(+ (connection) => connection.id === sttProviderId,+ );const navigate = useNavigate();const { devices, hasLabels, requestAccess } = useAudioInputDevices();@@ -439,6 +454,12 @@ export function VoiceTab() {null,);+ useEffect(() => {+ if (sttProviderId && !hasSelectedSttConnection) {+ setSttProviderId("");+ }+ }, [hasSelectedSttConnection, setSttProviderId, sttProviderId]);+const modelSttSupported = StudioModelDictationAdapter.isSupported();const ttsSupported = StudioSpeechSynthesisAdapter.isSupported();const systemTtsSupported =@@ -465,6 +486,7 @@ export function VoiceTab() {const [sttDownloadCancelling, setSttDownloadCancelling] = useState(false);const [sttUnloading, setSttUnloading] = useState(false);const isLocalEngine = dictationEngine === "model";+ const isCustomEngine = dictationEngine === "custom";// The model decides the backend: curated ids run GGML through whisper.cpp,// custom repos run through Transformers.const isMtmdModel = MTMD_STT_MODELS.has(sttModel);@@ -886,50 +908,109 @@ export function VoiceTab() {description={dictationEngine === "model"? t("settings.voice.dictation.engineModelDescription")- : t("settings.voice.dictation.engineBrowserDescription")+ : dictationEngine === "custom"+ ? t("settings.voice.dictation.engineCustomDescription")+ : t("settings.voice.dictation.engineBrowserDescription")}>- {isTauri ? (- <span className="text-sm text-muted-foreground">- {t("settings.voice.dictation.engineModel")}- </span>- ) : (- <Select- value={dictationEngine}- onValueChange={(value) => {- const next = value === "model" ? "model" : "browser";- if (next !== dictationEngine) {- // Unload whichever backend was resident for the old engine.+ <Select+ value={dictationEngine}+ onValueChange={(value) => {+ const next =+ value === "model"+ ? "model"+ : value === "custom"+ ? "custom"+ : "browser";+ if (next !== dictationEngine) {+ if (dictationEngine === "model") {void unloadSttModel().catch(() => {});- if (next === "model") {- setSttPhase("checking");- setSttDevice(null);- setSttDownload(null);- }}- setDictationEngine(next);- }}+ if (next === "model") {+ setSttPhase("checking");+ setSttDevice(null);+ setSttDownload(null);+ }+ }+ setDictationEngine(next);+ }}+ >+ <SelectTrigger+ data-testid="dictation-engine-trigger"+ aria-label={t("settings.voice.dictation.engineLabel")}+ className="w-56"+ size="sm">- <SelectTrigger- data-testid="dictation-engine-trigger"- aria-label={t("settings.voice.dictation.engineLabel")}- className="w-56"- size="sm"- >- <SelectValue />- </SelectTrigger>- <SelectContent>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {isTauri ? null : (<SelectItem value="browser">{t("settings.voice.dictation.engineBrowser")}</SelectItem>- <SelectItem value="model" data-testid="dictation-engine-model">- {t("settings.voice.dictation.engineModel")}- </SelectItem>- </SelectContent>- </Select>- )}+ )}+ <SelectItem value="model" data-testid="dictation-engine-model">+ {t("settings.voice.dictation.engineModel")}+ </SelectItem>+ <SelectItem+ value="custom"+ data-testid="dictation-engine-custom"+ disabled={!connectionsEnabled}+ >+ {t("settings.voice.dictation.engineCustom")}+ </SelectItem>+ </SelectContent>+ </Select></SettingsRow>+ {isCustomEngine ? (+ <>+ <SettingsRow+ label={t("settings.voice.dictation.connectionLabel")}+ description={t("settings.voice.dictation.connectionDescription")}+ >+ <Select+ value={hasSelectedSttConnection ? sttProviderId : undefined}+ onValueChange={setSttProviderId}+ disabled={!connectionsEnabled || !hasSttConnections}+ >+ <SelectTrigger+ aria-label={t("settings.voice.dictation.connectionLabel")}+ className="w-56"+ size="sm"+ >+ <SelectValue+ placeholder={t(+ hasSttConnections+ ? "settings.voice.dictation.connectionPlaceholder"+ : "settings.voice.dictation.connectionEmpty",+ )}+ />+ </SelectTrigger>+ <SelectContent>+ {sttConnections.map((connection) => (+ <SelectItem key={connection.id} value={connection.id}>+ {connection.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </SettingsRow>+ <SettingsRow+ label={t("settings.voice.dictation.customModelLabel")}+ description={t("settings.voice.dictation.customModelDescription")}+ >+ <Input+ value={sttProviderModel}+ onChange={(event) => setSttProviderModel(event.target.value)}+ placeholder="whisper-1"+ aria-label={t("settings.voice.dictation.customModelLabel")}+ className="w-56"+ />+ </SettingsRow>+ </>+ ) : null}+{isLocalEngine ? (modelSttSupported ? (<SettingsRow@@ -1151,7 +1232,11 @@ export function VoiceTab() {{DICTATION_LANGUAGES.map(({ value, label }) => (<SelectItem key={value} value={value}>{value === "auto"- ? t("settings.voice.dictation.languageAuto")+ ? t(+ isCustomEngine+ ? "settings.voice.dictation.languageAutoDetect"+ : "settings.voice.dictation.languageAuto",+ ): label}</SelectItem>))}diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex f1116767382..72184097aed 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -280,6 +280,16 @@ export const ar = {engineModel: "التفريغ النصي المحلي",engineModelDescription:"يشغّل نموذج تحويل الكلام إلى نص (STT) محليًا ويعمل دون اتصال. نزّله ثم حمّله، ويُفرَغ من الذاكرة بعد فترة من عدم الاستخدام.",+ engineCustom: "نقطة نهاية مخصصة",+ engineCustomDescription:+ "يرسل الصوت المسجّل إلى خادم STT متوافق مع OpenAI من الاتصالات.",+ connectionLabel: "الاتصال",+ connectionDescription:+ "أضف خادمًا متوافقًا مع OpenAI ومفتاح API اختياريًا في الاتصالات.",+ connectionPlaceholder: "اختر اتصالًا",+ connectionEmpty: "لا توجد اتصالات متاحة",+ customModelLabel: "النموذج",+ customModelDescription: "اسم النموذج المرسل إلى /v1/audio/transcriptions.",sttModelLabel: "نموذج التعرّف على الكلام",sttModelDescription: "اختر نموذج STT أو ابحث عنه لتشغيله محليًا.",sttModelSearchPlaceholder: "ابحث عن نموذج",@@ -338,6 +348,7 @@ export const ar = {languageLabel: "لغة الإملاء",languageDescription: "اللغة المراد التعرّف عليها",languageAuto: "تلقائي (لغة المتصفح)",+ languageAutoDetect: "تلقائي (اكتشاف اللغة)",},dictionary: {sectionTitle: "قاموس الإملاء",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 4e9bc2db4b0..3c81df32d97 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -284,6 +284,17 @@ export const de = {engineModel: "Lokale Transkription",engineModelDescription:"Führt ein Spracherkennungsmodell (STT) lokal aus und funktioniert offline. Zuerst herunterladen und laden; nach einer Zeit ohne Nutzung wird es automatisch wieder entladen.",+ engineCustom: "Benutzerdefinierter Endpunkt",+ engineCustomDescription:+ "Sendet Audioaufnahmen an einen OpenAI-kompatiblen STT-Server aus Ihren Verbindungen.",+ connectionLabel: "Verbindung",+ connectionDescription:+ "Fügen Sie unter Verbindungen einen OpenAI-kompatiblen Server und optional einen API-Schlüssel hinzu.",+ connectionPlaceholder: "Verbindung auswählen",+ connectionEmpty: "Keine Verbindungen verfügbar",+ customModelLabel: "Modell",+ customModelDescription:+ "Modellname, der an /v1/audio/transcriptions gesendet wird.",sttModelLabel: "Spracherkennungsmodell",sttModelDescription:"Wählen oder suchen Sie ein STT-Modell für die lokale Ausführung.",@@ -347,6 +358,7 @@ export const de = {languageLabel: "Diktatsprache",languageDescription: "Zu erkennende Sprache",languageAuto: "Automatisch (Browsersprache)",+ languageAutoDetect: "Automatisch (Sprache erkennen)",},dictionary: {sectionTitle: "Diktatwörterbuch",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 2f97a5c0064..085887b3f77 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -282,6 +282,16 @@ export const en = {engineModel: "Local transcription",engineModelDescription:"Runs a speech-to-text (STT) model locally and works offline. Download, load, then unloads after inactivity.",+ engineCustom: "Custom endpoint",+ engineCustomDescription:+ "Sends recorded audio to an OpenAI-compatible STT server from your Connections.",+ connectionLabel: "Connection",+ connectionDescription:+ "Add an OpenAI-compatible server and optional API key in Connections.",+ connectionPlaceholder: "Select a connection",+ connectionEmpty: "No connections available",+ customModelLabel: "Model",+ customModelDescription: "Model name sent to /v1/audio/transcriptions.",sttModelLabel: "Speech recognition model",sttModelDescription: "Choose or search a STT model to run locally.",sttModelSearchPlaceholder: "Search any model on HF",@@ -339,6 +349,7 @@ export const en = {languageLabel: "Dictation language",languageDescription: "Language to recognize",languageAuto: "Auto (browser language)",+ languageAutoDetect: "Auto (detect language)",},dictionary: {sectionTitle: "Dictation dictionary",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex c9d1ebe6d72..3832321cddc 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -283,6 +283,17 @@ export const es = {engineModel: "Transcripción local",engineModelDescription:"Ejecuta un modelo de voz a texto (STT) en local y funciona sin conexión. Descárgalo, cárgalo y se liberará de la memoria tras un tiempo de inactividad.",+ engineCustom: "Endpoint personalizado",+ engineCustomDescription:+ "Envía el audio grabado a un servidor STT compatible con OpenAI desde tus conexiones.",+ connectionLabel: "Conexión",+ connectionDescription:+ "Añade un servidor compatible con OpenAI y una clave API opcional en Conexiones.",+ connectionPlaceholder: "Selecciona una conexión",+ connectionEmpty: "No hay conexiones disponibles",+ customModelLabel: "Modelo",+ customModelDescription:+ "Nombre del modelo enviado a /v1/audio/transcriptions.",sttModelLabel: "Modelo de reconocimiento de voz",sttModelDescription:"Elige o busca un modelo STT para ejecutarlo en local.",@@ -344,6 +355,7 @@ export const es = {languageLabel: "Idioma del dictado",languageDescription: "Idioma que se reconocerá",languageAuto: "Automático (idioma del navegador)",+ languageAutoDetect: "Automático (detectar idioma)",},dictionary: {sectionTitle: "Diccionario de dictado",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex ef8800d481d..c2fb603de8f 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -284,6 +284,17 @@ export const fr = {engineModel: "Transcription locale",engineModelDescription:"Exécute un modèle de reconnaissance vocale (STT) en local et fonctionne hors ligne. Téléchargez-le, chargez-le ; il se décharge après une période d'inactivité.",+ engineCustom: "Point de terminaison personnalisé",+ engineCustomDescription:+ "Envoie l'audio enregistré à un serveur STT compatible avec OpenAI depuis vos connexions.",+ connectionLabel: "Connexion",+ connectionDescription:+ "Ajoutez un serveur compatible avec OpenAI et éventuellement une clé API dans Connexions.",+ connectionPlaceholder: "Sélectionner une connexion",+ connectionEmpty: "Aucune connexion disponible",+ customModelLabel: "Modèle",+ customModelDescription:+ "Nom du modèle envoyé à /v1/audio/transcriptions.",sttModelLabel: "Modèle de reconnaissance vocale",sttModelDescription:"Choisissez ou recherchez un modèle STT à exécuter en local.",@@ -346,6 +357,7 @@ export const fr = {languageLabel: "Langue de la dictée",languageDescription: "Langue à reconnaître",languageAuto: "Auto (langue du navigateur)",+ languageAutoDetect: "Auto (détecter la langue)",},dictionary: {sectionTitle: "Dictionnaire de dictée",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 4b3ef5626fc..db197b1aec8 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -283,6 +283,17 @@ export const hi = {engineModel: "लोकल ट्रांसक्रिप्शन",engineModelDescription:"स्पीच-टू-टेक्स्ट (STT) मॉडल लोकली चलाता है और ऑफ़लाइन काम करता है। डाउनलोड करें, लोड करें; कुछ देर उपयोग न होने पर यह अनलोड हो जाता है।",+ engineCustom: "कस्टम एंडपॉइंट",+ engineCustomDescription:+ "आपके कनेक्शन से रिकॉर्ड किया गया ऑडियो OpenAI-संगत STT सर्वर को भेजता है।",+ connectionLabel: "कनेक्शन",+ connectionDescription:+ "कनेक्शन में OpenAI-संगत सर्वर और वैकल्पिक API कुंजी जोड़ें।",+ connectionPlaceholder: "कनेक्शन चुनें",+ connectionEmpty: "कोई कनेक्शन उपलब्ध नहीं है",+ customModelLabel: "मॉडल",+ customModelDescription:+ "/v1/audio/transcriptions को भेजा जाने वाला मॉडल नाम।",sttModelLabel: "स्पीच रिकग्निशन मॉडल",sttModelDescription: "लोकली चलाने के लिए STT मॉडल चुनें या खोजें।",sttModelSearchPlaceholder: "मॉडल खोजें",@@ -341,6 +352,7 @@ export const hi = {languageLabel: "डिक्टेशन की भाषा",languageDescription: "पहचानी जाने वाली भाषा",languageAuto: "स्वतः (ब्राउज़र की भाषा)",+ languageAutoDetect: "स्वतः (भाषा पहचानें)",},dictionary: {sectionTitle: "डिक्टेशन शब्दकोश",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex 6919b626051..6b30f8167a9 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -249,6 +249,17 @@ export const it = {engineModel: "Trascrizione locale",engineModelDescription:"Esegue un modello speech-to-text (STT) in locale e funziona offline. Puoi scaricare e caricare il modello, che verrà poi rimosso dalla memoria dopo un periodo di inattività.",+ engineCustom: "Endpoint personalizzato",+ engineCustomDescription:+ "Invia l'audio registrato a un server STT compatibile con OpenAI dalle tue connessioni.",+ connectionLabel: "Connessione",+ connectionDescription:+ "Aggiungi un server compatibile con OpenAI e una chiave API facoltativa in Connessioni.",+ connectionPlaceholder: "Seleziona una connessione",+ connectionEmpty: "Nessuna connessione disponibile",+ customModelLabel: "Modello",+ customModelDescription:+ "Nome del modello inviato a /v1/audio/transcriptions.",sttModelLabel: "Modello di riconoscimento vocale",sttModelDescription:"Scegli o cerca un modello STT da eseguire in locale.",@@ -311,6 +322,7 @@ export const it = {languageLabel: "Lingua di dettatura",languageDescription: "Lingua da riconoscere",languageAuto: "Automatica (lingua del browser)",+ languageAutoDetect: "Automatica (rileva lingua)",},dictionary: {sectionTitle: "Dizionario di dettatura",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 8739aba03c5..7a2ce508036 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -282,6 +282,17 @@ export const ja = {engineModel: "ローカル文字起こし",engineModelDescription:"音声認識 (STT) モデルをローカルで実行し、オフラインでも動作します。ダウンロードして読み込むと、一定時間使わなければアンロードされます。",+ engineCustom: "カスタムエンドポイント",+ engineCustomDescription:+ "接続に登録した OpenAI 互換 STT サーバーへ録音音声を送信します。",+ connectionLabel: "接続",+ connectionDescription:+ "接続で OpenAI 互換サーバーと任意の API キーを追加してください。",+ connectionPlaceholder: "接続を選択",+ connectionEmpty: "利用可能な接続はありません",+ customModelLabel: "モデル",+ customModelDescription:+ "/v1/audio/transcriptions に送信するモデル名です。",sttModelLabel: "音声認識モデル",sttModelDescription:"ローカルで実行する STT モデルを選択または検索します。",@@ -341,6 +352,7 @@ export const ja = {languageLabel: "音声入力の言語",languageDescription: "認識する言語",languageAuto: "自動 (ブラウザーの言語)",+ languageAutoDetect: "自動 (言語を検出)",},dictionary: {sectionTitle: "音声入力辞書",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 102d9c155c8..537ac5294eb 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -280,6 +280,17 @@ export const ko = {engineModel: "로컬 음성 인식",engineModelDescription:"음성 인식(STT) 모델을 로컬에서 실행하며 오프라인으로 동작합니다. 다운로드 후 로드하고, 일정 시간 사용하지 않으면 자동으로 해제됩니다.",+ engineCustom: "사용자 지정 엔드포인트",+ engineCustomDescription:+ "연결에 등록된 OpenAI 호환 STT 서버로 녹음된 오디오를 전송합니다.",+ connectionLabel: "연결",+ connectionDescription:+ "연결에서 OpenAI 호환 서버와 선택적 API 키를 추가하세요.",+ connectionPlaceholder: "연결 선택",+ connectionEmpty: "사용 가능한 연결이 없습니다",+ customModelLabel: "모델",+ customModelDescription:+ "/v1/audio/transcriptions에 전송할 모델 이름입니다.",sttModelLabel: "음성 인식 모델",sttModelDescription: "로컬에서 실행할 STT 모델을 선택하거나 검색하세요.",sttModelSearchPlaceholder: "모델 검색",@@ -338,6 +349,7 @@ export const ko = {languageLabel: "받아쓰기 언어",languageDescription: "인식할 언어",languageAuto: "자동(브라우저 언어)",+ languageAutoDetect: "자동(언어 감지)",},dictionary: {sectionTitle: "받아쓰기 사전",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex f7e0d39c80f..f0ab159f736 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -282,6 +282,17 @@ export const ptBR = {engineModel: "Transcrição local",engineModelDescription:"Executa um modelo de conversão de fala em texto (STT) localmente e funciona offline. Baixe e carregue o modelo; ele é descarregado após um período sem uso.",+ engineCustom: "Endpoint personalizado",+ engineCustomDescription:+ "Envia o áudio gravado a um servidor STT compatível com OpenAI das suas conexões.",+ connectionLabel: "Conexão",+ connectionDescription:+ "Adicione um servidor compatível com OpenAI e uma chave de API opcional em Conexões.",+ connectionPlaceholder: "Selecione uma conexão",+ connectionEmpty: "Nenhuma conexão disponível",+ customModelLabel: "Modelo",+ customModelDescription:+ "Nome do modelo enviado para /v1/audio/transcriptions.",sttModelLabel: "Modelo de reconhecimento de fala",sttModelDescription:"Escolha ou busque um modelo STT para executar localmente.",@@ -342,6 +353,7 @@ export const ptBR = {languageLabel: "Idioma do ditado",languageDescription: "Idioma a ser reconhecido",languageAuto: "Automático (idioma do navegador)",+ languageAutoDetect: "Automático (detectar idioma)",},dictionary: {sectionTitle: "Dicionário de ditado",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 5897fe2b258..7907e373502 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -282,6 +282,17 @@ export const ru = {engineModel: "Локальное распознавание",engineModelDescription:"Запускает модель распознавания речи (STT) локально и работает офлайн. Скачайте модель, затем загрузите её; после простоя она выгружается.",+ engineCustom: "Пользовательский эндпоинт",+ engineCustomDescription:+ "Отправляет записанный звук на OpenAI-совместимый сервер STT из ваших подключений.",+ connectionLabel: "Подключение",+ connectionDescription:+ "Добавьте OpenAI-совместимый сервер и при необходимости ключ API в разделе «Подключения».",+ connectionPlaceholder: "Выберите подключение",+ connectionEmpty: "Нет доступных подключений",+ customModelLabel: "Модель",+ customModelDescription:+ "Имя модели, отправляемое в /v1/audio/transcriptions.",sttModelLabel: "Модель распознавания речи",sttModelDescription:"Выберите или найдите модель STT для локального запуска.",@@ -341,6 +352,7 @@ export const ru = {languageLabel: "Язык диктовки",languageDescription: "Язык для распознавания",languageAuto: "Автоматически (язык браузера)",+ languageAutoDetect: "Автоматически (определить язык)",},dictionary: {sectionTitle: "Словарь диктовки",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 5f440b418cd..d6fb6d61819 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -278,6 +278,17 @@ export const zhCN = {engineModel: "本地转写",engineModelDescription:"在本地运行语音转文字(STT)模型,可离线使用。下载并加载后,闲置一段时间会自动卸载。",+ engineCustom: "自定义端点",+ engineCustomDescription:+ "将录制的音频发送到“连接”中的 OpenAI 兼容 STT 服务器。",+ connectionLabel: "连接",+ connectionDescription:+ "在“连接”中添加 OpenAI 兼容服务器和可选的 API 密钥。",+ connectionPlaceholder: "选择连接",+ connectionEmpty: "没有可用的连接",+ customModelLabel: "模型",+ customModelDescription:+ "发送到 /v1/audio/transcriptions 的模型名称。",sttModelLabel: "语音识别模型",sttModelDescription: "选择或搜索要在本地运行的 STT 模型。",sttModelSearchPlaceholder: "搜索模型",@@ -334,6 +345,7 @@ export const zhCN = {languageLabel: "语音输入语言",languageDescription: "要识别的语言",languageAuto: "自动(浏览器语言)",+ languageAutoDetect: "自动(检测语言)",},dictionary: {sectionTitle: "语音输入词典",diff --git a/studio/frontend/tests/voice-settings-stt-migration.test.ts b/studio/frontend/tests/voice-settings-stt-migration.test.tsindex cf8e4a3731b..5577914457a 100644--- a/studio/frontend/tests/voice-settings-stt-migration.test.ts+++ b/studio/frontend/tests/voice-settings-stt-migration.test.ts@@ -2,6 +2,7 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";+import { readFileSync } from "node:fs";import test from "node:test";import {@@ -11,6 +12,16 @@ import {migrateVoiceSettings,} from "../src/features/settings/stores/stt-model-catalog.ts";+const CUSTOM_ENGINE_BEFORE_TAURI =+ /savedEngine === "custom"\s*\? "custom"\s*:\s*isTauri/;+const EXTERNAL_PROVIDER_FORM_FIELD = /form\.set\("provider_id", providerId\)/;+const EXTERNAL_PRELOAD_GUARD =+ /if \(!usesExternalEndpoint && sessionEngine\) \{[\s\S]*loadSttModel/;+const CONNECTIONS_ENABLED_SEND_GUARD =+ /if \(!providersState\.connectionsEnabled\) \{[\s\S]*form\.set\("provider_id", providerId\)/;+const LEGACY_KEY_FALLBACK =+ /getExternalProviderApiKey\(providerId\)[\s\S]*encryptProviderApiKey\(legacyApiKey\)/;+test("the default dictation model is a recommended one", () => {assert.ok(RECOMMENDED_STT_MODELS.has(DEFAULT_STT_MODEL));});@@ -48,3 +59,57 @@ test("migration keeps the rest of the save intact", () => {);assert.equal(migrated?.dictationLanguage, "ja-JP");});++test("custom transcription uses a saved connection without loading local STT", () => {+ const storeSource = readFileSync(+ new URL(+ "../src/features/settings/stores/voice-settings-store.ts",+ import.meta.url,+ ),+ "utf8",+ );+ const adapterSource = readFileSync(+ new URL(+ "../src/features/chat/adapters/studio-model-dictation-adapter.ts",+ import.meta.url,+ ),+ "utf8",+ );++ assert.match(storeSource, CUSTOM_ENGINE_BEFORE_TAURI);+ assert.match(adapterSource, EXTERNAL_PROVIDER_FORM_FIELD);+ assert.match(adapterSource, EXTERNAL_PRELOAD_GUARD);+ assert.match(adapterSource, CONNECTIONS_ENABLED_SEND_GUARD);+ assert.match(adapterSource, LEGACY_KEY_FALLBACK);+});++test("the custom dictation connection picker handles deleted and empty connections", () => {+ const voiceTabSource = readFileSync(+ new URL(+ "../src/features/settings/tabs/voice-tab.tsx",+ import.meta.url,+ ),+ "utf8",+ );++ assert.match(+ voiceTabSource,+ /if \(sttProviderId && !hasSelectedSttConnection\) \{\s*setSttProviderId\(""\);/,+ );+ assert.match(+ voiceTabSource,+ /value=\{hasSelectedSttConnection \? sttProviderId : undefined\}/,+ );+ assert.match(+ voiceTabSource,+ /disabled=\{!connectionsEnabled \|\| !hasSttConnections\}/,+ );+ assert.match(+ voiceTabSource,+ /"settings\.voice\.dictation\.connectionEmpty"/,+ );+ assert.doesNotMatch(+ voiceTabSource,+ /<SelectItem value=\{sttProviderId\}/,+ );+});