Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: serve whisper-server under a random per-launch request path (#13002)

Daniel Han8ff8ad417c22
diff --git a/studio/backend/core/inference/stt_ggml_sidecar.py b/studio/backend/core/inference/stt_ggml_sidecar.py
index e7873f1944e..14454f359ed 100644
--- a/studio/backend/core/inference/stt_ggml_sidecar.py
+++ b/studio/backend/core/inference/stt_ggml_sidecar.py
@@ -28,6 +28,7 @@ import io
import json
import os
import re
+import secrets
import shutil
import socket
import subprocess
@@ -79,6 +80,7 @@ from utils.process_lifetime import (
forget_pid,
is_process_shutting_down,
)
+from utils.subprocess_compat import windows_hidden_subprocess_kwargs
logger = get_logger(__name__)
@@ -726,6 +728,36 @@ def cancel_model_download(model: Optional[str] = None, download_id: Optional[str
return _download_state.cancel(model_id, download_id)
+_REQUEST_PATH_SUPPORT: dict[tuple[str, int], bool] = {}
+
+
+def _supports_request_path(binary: str) -> bool:
+ """Whether ``binary`` accepts ``--request-path``; an older user-supplied whisper-server exits on it."""
+ try:
+ key = (binary, os.stat(binary).st_mtime_ns)
+ except OSError:
+ return False
+ cached = _REQUEST_PATH_SUPPORT.get(key)
+ marker = _whisper_install_marker(binary) if cached is None else None
+ if marker is not None and marker.get("published_repo") == "unslothai/whisper.cpp":
+ # Every unslothai/whisper.cpp release has the flag: skip the ~0.6 s --help probe.
+ cached = _REQUEST_PATH_SUPPORT[key] = True
+ if cached is None:
+ try:
+ probe = subprocess.run(
+ [binary, "--help"],
+ capture_output = True,
+ timeout = 20,
+ env = _whisper_server_child_env(binary),
+ **windows_hidden_subprocess_kwargs(),
+ )
+ cached = b"--request-path" in probe.stdout + probe.stderr
+ except Exception: # noqa: BLE001 -- a probe failure only means no route
+ cached = False
+ _REQUEST_PATH_SUPPORT[key] = cached
+ return cached
+
+
def _pcm_to_wav_bytes(decoded_audio) -> bytes:
"""Wrap decoded float32 mono 16 kHz PCM into an in-memory 16-bit WAV."""
import numpy as np
@@ -749,6 +781,8 @@ class GgmlSttSidecar:
self._load_state_lock = threading.Lock()
self._process: Optional[subprocess.Popen] = None
self._port: Optional[int] = None
+ # Secret route prefix: a web page that finds the loopback port cannot reach whisper-server.
+ self._route = ""
self._model_id: Optional[str] = None
# --no-gpu at the user's request, tracked because it varies per request.
self._forced_cpu = False
@@ -821,6 +855,7 @@ class GgmlSttSidecar:
process = self._process
self._process = None
self._port = None
+ self._route = ""
self._model_id = None
self._forced_cpu = False
if process is not None and process.poll() is None:
@@ -996,6 +1031,15 @@ class GgmlSttSidecar:
model_path = self._ensure_model_downloaded(model_id)
reservation, port = self._reserve_free_port()
command = [binary, "-m", model_path, "--host", "127.0.0.1", "--port", str(port)]
+ route = ""
+ if _supports_request_path(binary):
+ route = "/" + secrets.token_hex(16)
+ command.extend(["--request-path", route])
+ else:
+ logger.warning(
+ "whisper-server at %s has no --request-path; its routes stay at the root path.",
+ binary,
+ )
marker = _whisper_install_marker(binary)
cancel_event = (
request_cancel_event if request_cancel_event is not None else threading.Event()
@@ -1064,7 +1108,7 @@ class GgmlSttSidecar:
"Unsloth is shutting down; not starting whisper-server."
)
try:
- self._wait_for_server(process, port, cancel_event)
+ self._wait_for_server(process, port, cancel_event, route = route)
except Exception:
if process.poll() is None:
process.kill()
@@ -1073,6 +1117,7 @@ class GgmlSttSidecar:
raise
self._process = process
self._port = port
+ self._route = route
self._model_id = model_id
self._forced_cpu = force_cpu
self._schedule_idle_unload_locked()
@@ -1089,6 +1134,7 @@ class GgmlSttSidecar:
process: subprocess.Popen,
port: int,
cancel_event: Optional[threading.Event] = None,
+ route: str = "",
) -> None:
deadline = time.monotonic() + _SERVER_START_TIMEOUT_SECONDS
while time.monotonic() < deadline:
@@ -1104,21 +1150,25 @@ class GgmlSttSidecar:
# Require a whisper-server-specific response twice, with the managed child alive around each probe. An
# arbitrary local process that won the bind race would otherwise be mistaken for the sidecar and receive the
# user's microphone audio.
- if GgmlSttSidecar._probe_is_whisper_server(process, port) and (
- GgmlSttSidecar._probe_is_whisper_server(process, port)
+ if GgmlSttSidecar._probe_is_whisper_server(process, port, route) and (
+ GgmlSttSidecar._probe_is_whisper_server(process, port, route)
):
return
time.sleep(0.2)
raise SttEngineUnavailableError("The local transcription runtime did not start in time.")
@staticmethod
- def _probe_is_whisper_server(process: subprocess.Popen, port: int) -> bool:
+ def _probe_is_whisper_server(
+ process: subprocess.Popen,
+ port: int,
+ route: str = "",
+ ) -> bool:
"""One readiness probe: our child is alive and the responder looks like
whisper.cpp's server (its index page and errors identify whisper)."""
if process.poll() is not None:
return False
try:
- req = urllib.request.Request(f"http://127.0.0.1:{port}/", method = "GET")
+ req = urllib.request.Request(f"http://127.0.0.1:{port}{route}/", method = "GET")
with urllib.request.urlopen(req, timeout = 2) as response:
body = response.read(65536)
except Exception:
@@ -1234,7 +1284,7 @@ class GgmlSttSidecar:
try:
connection.request(
"POST",
- "/inference",
+ f"{self._route}/inference",
body = body,
headers = {"Content-Type": f"multipart/form-data; boundary={boundary}"},
)
diff --git a/studio/backend/tests/test_stt_ggml_request_path.py b/studio/backend/tests/test_stt_ggml_request_path.py
new file mode 100644
index 00000000000..7380e24cc9f
--- /dev/null
+++ b/studio/backend/tests/test_stt_ggml_request_path.py
@@ -0,0 +1,207 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""whisper-server runs under a random per-launch path, so a web page that finds its loopback port cannot reach it."""
+
+import http.server
+import json
+import os
+import re
+import stat
+import sys
+import threading
+
+import numpy as np
+import pytest
+
+import core.inference.stt_ggml_sidecar as ggml_module
+from core.inference.stt_ggml_sidecar import GgmlSttSidecar
+
+
[email protected](autouse = True)
+def _isolate(monkeypatch, tmp_path):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))
+ monkeypatch.delenv("WHISPER_SERVER_PATH", raising = False)
+ monkeypatch.setattr(ggml_module, "find_whisper_server_binary", lambda: "/bin/echo")
+ monkeypatch.setattr(ggml_module, "_cached_model_path", lambda model_id: "/tmp/ggml.bin")
+ monkeypatch.setattr(
+ ggml_module,
+ "_decode_audio_bounded",
+ lambda audio, cancel_event = None: np.zeros(16000, dtype = np.float32),
+ )
+ ggml_module._REQUEST_PATH_SUPPORT.clear()
+
+
+def _fake_popen(monkeypatch, commands):
+ class FakeProcess:
+ pid = 4321
+
+ def __init__(self, command, *args, **kwargs):
+ commands.append(command)
+
+ def poll(self):
+ return None
+
+ def terminate(self):
+ pass
+
+ def wait(self, timeout = None):
+ return 0
+
+ monkeypatch.setattr(ggml_module.subprocess, "Popen", FakeProcess)
+ monkeypatch.setattr(ggml_module, "adopt_pid", lambda pid: None)
+ monkeypatch.setattr(ggml_module, "forget_pid", lambda pid: None)
+ monkeypatch.setattr(ggml_module, "_training_active", lambda: False)
+
+
+def test_each_launch_gets_a_random_request_path(monkeypatch):
+ commands, routes = [], []
+ _fake_popen(monkeypatch, commands)
+ monkeypatch.setattr(ggml_module, "_supports_request_path", lambda binary: True)
+ monkeypatch.setattr(
+ GgmlSttSidecar,
+ "_wait_for_server",
+ staticmethod(lambda process, port, cancel_event = None, route = "": routes.append(route)),
+ )
+ for _ in range(2):
+ sidecar = GgmlSttSidecar()
+ sidecar.load("small")
+ flag = commands[-1].index("--request-path")
+ route = commands[-1][flag + 1]
+ assert re.fullmatch(r"/[0-9a-f]{32}", route)
+ assert sidecar._route == route == routes[-1]
+ sidecar.unload()
+ assert sidecar._route == ""
+ assert commands[0][commands[0].index("--request-path") + 1] != route
+
+
+def test_binary_without_the_flag_still_launches(monkeypatch):
+ commands, routes = [], []
+ _fake_popen(monkeypatch, commands)
+ monkeypatch.setattr(ggml_module, "_supports_request_path", lambda binary: False)
+ monkeypatch.setattr(
+ GgmlSttSidecar,
+ "_wait_for_server",
+ staticmethod(lambda process, port, cancel_event = None, route = "": routes.append(route)),
+ )
+ sidecar = GgmlSttSidecar()
+ sidecar.load("small")
+ assert "--request-path" not in commands[0]
+ assert routes == [""] and sidecar._route == ""
+
+
+def _script(tmp_path, name, help_text):
+ if sys.platform == "win32":
+ pytest.skip(
+ reason = "the whisper-server stand-in is a POSIX sh script, which Windows cannot exec"
+ )
+ path = tmp_path / name
+ path.write_text(f"#!/bin/sh\necho '{help_text}' >&2\necho run >> '{tmp_path}/{name}.runs'\n")
+ path.chmod(path.stat().st_mode | stat.S_IEXEC)
+ return str(path)
+
+
+def test_help_probe_detects_the_flag_and_caches(tmp_path):
+ new = _script(tmp_path, "new-server", " --request-path PATH, Request path for all requests")
+ old = _script(tmp_path, "old-server", " --port N, Port number")
+ assert ggml_module._supports_request_path(new) is True
+ assert ggml_module._supports_request_path(new) is True
+ assert ggml_module._supports_request_path(old) is False
+ assert ggml_module._supports_request_path(str(tmp_path / "missing")) is False
+ assert (tmp_path / "new-server.runs").read_text().count("run") == 1
+
+
+def test_managed_install_skips_the_help_probe(tmp_path, monkeypatch):
+ old = _script(tmp_path, "managed-server", " --port N, Port number")
+ monkeypatch.setattr(
+ ggml_module,
+ "_whisper_install_marker",
+ lambda binary: {"component": "whisper.cpp", "published_repo": "unslothai/whisper.cpp"},
+ )
+ assert ggml_module._supports_request_path(old) is True
+ assert not (tmp_path / "managed-server.runs").exists()
+
+
+def test_custom_published_repo_is_still_probed(tmp_path, monkeypatch):
+ old = _script(tmp_path, "custom-server", " --port N, Port number")
+ monkeypatch.setattr(
+ ggml_module,
+ "_whisper_install_marker",
+ lambda binary: {"component": "whisper.cpp", "published_repo": "someone/whisper-fork"},
+ )
+ assert ggml_module._supports_request_path(old) is False
+ assert (tmp_path / "custom-server.runs").read_text().count("run") == 1
+
+
+class _RoutedHandler(http.server.BaseHTTPRequestHandler):
+ """Serves whisper-server's index and /inference only under ROUTE, 404 elsewhere, like --request-path."""
+
+ route = "/" + "ab" * 16
+ posts: list = []
+
+ def do_GET(self):
+ if self.path != f"{self.route}/":
+ self.send_error(404)
+ return
+ body = b"<html>whisper.cpp server</html>"
+ self.send_response(200)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_POST(self):
+ length = int(self.headers.get("Content-Length", "0"))
+ self.rfile.read(length)
+ if self.path != f"{self.route}/inference":
+ self.send_error(404)
+ return
+ type(self).posts.append(self.path)
+ body = json.dumps({"text": "routed"}).encode()
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *args):
+ pass
+
+
+def routed_server():
+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _RoutedHandler)
+ thread = threading.Thread(target = server.serve_forever, daemon = True)
+ thread.start()
+ yield server.server_address[1]
+ server.shutdown()
+
+
+class _Alive:
+ def poll(self):
+ return None
+
+
+def test_probe_and_inference_use_the_route(monkeypatch, routed_server):
+ route = _RoutedHandler.route
+ assert GgmlSttSidecar._probe_is_whisper_server(_Alive(), routed_server, route) is True
+ assert GgmlSttSidecar._probe_is_whisper_server(_Alive(), routed_server) is False
+
+ sidecar = GgmlSttSidecar()
+
+ def fake_load(model = None, request_cancel_event = None):
+ sidecar._port = routed_server
+ sidecar._route = route
+ sidecar._model_id = ggml_module.resolve_ggml_model_id(model)
+
+ monkeypatch.setattr(sidecar, "load", fake_load)
+ assert sidecar.transcribe(b"RIFF", model = "small")["text"] == "routed"
+ assert _RoutedHandler.posts[-1] == f"{route}/inference"
+
+ # A caller without the route (a web page that found the port) gets 404 from every endpoint.
+ def unrouted_load(model = None, request_cancel_event = None):
+ fake_load(model)
+ sidecar._route = ""
+
+ monkeypatch.setattr(sidecar, "load", unrouted_load)
+ with pytest.raises(ggml_module.SttEngineUnavailableError, match = "HTTP 404"):
+ sidecar.transcribe(b"RIFF", model = "small")
diff --git a/studio/backend/tests/test_stt_ggml_sidecar.py b/studio/backend/tests/test_stt_ggml_sidecar.py
index da5a07ad4c2..8cd28eddb43 100644
--- a/studio/backend/tests/test_stt_ggml_sidecar.py
+++ b/studio/backend/tests/test_stt_ggml_sidecar.py
@@ -39,7 +39,7 @@ def _shared_setup_1(monkeypatch):
monkeypatch.setattr(
GgmlSttSidecar,
"_wait_for_server",
- staticmethod(lambda process, port, cancel_event = None: None),
+ staticmethod(lambda process, port, cancel_event = None, route = "": None),
)
@@ -55,6 +55,7 @@ def isolate_runtime_and_stub_audio_decoder(monkeypatch, tmp_path):
"_decode_audio_bounded",
lambda audio, cancel_event = None: np.zeros(16000, dtype = np.float32),
)
+ monkeypatch.setattr(ggml_module, "_supports_request_path", lambda binary: True)
# ---------------------------------------------------------------------------