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.

Add configurable voice context to reduce Qwen3-ASR memory (#15810)

Lee Jackson90929002741b
diff --git a/studio/backend/core/inference/stt_mtmd_sidecar.py b/studio/backend/core/inference/stt_mtmd_sidecar.py
index 0c3c3ca7774..6e0f54a07ec 100644
--- a/studio/backend/core/inference/stt_mtmd_sidecar.py
+++ b/studio/backend/core/inference/stt_mtmd_sidecar.py
@@ -34,6 +34,8 @@ from utils.process_lifetime import (
from core.inference.stt_ggml_sidecar import _pcm_to_wav_bytes
from core.inference.stt_sidecar import (
STT_KEEP_ALIVE_SECONDS,
+ SttContextSizeError,
+ SttIncompleteTranscriptionError,
SttLoadCancelledError,
SttModelBusyError,
SttModelIdError,
@@ -97,8 +99,31 @@ _TRANSCRIBE_PROMPT = "Transcribe the audio."
# Generous cap; it only stops a looping model before the request timeout.
_TRANSCRIPT_TOKENS_PER_SECOND = 30
_MIN_TRANSCRIPT_TOKENS = 512
-# Well under trained context, which must also hold the audio; llama-server keeps its default.
+# Output allowance is reserved alongside the measured audio/prompt tokens in Auto mode.
_MAX_TRANSCRIPT_TOKENS = 16384
+_AUTO_CONTEXT_MIN = 4096
+_MAX_CONTEXT_LENGTH = 65536
+_CONTEXT_MARGIN = 64
+
+
+def _validate_context_length(value: Optional[int]) -> Optional[int]:
+ if value is not None and (
+ type(value) is not int
+ or (value != 0 and not (1024 <= value <= _MAX_CONTEXT_LENGTH and value % 256 == 0))
+ ):
+ raise SttContextSizeError(
+ "Voice context must be Auto (0) or a multiple of 256 from 1024 to 65536 tokens."
+ )
+ return value
+
+
+def _auto_context_length(input_tokens: int, output_tokens: int) -> int:
+ required = input_tokens + output_tokens + _CONTEXT_MARGIN
+ if required > _MAX_CONTEXT_LENGTH:
+ raise SttContextSizeError(
+ "This recording needs more than the model's 64K context. Split it into shorter recordings."
+ )
+ return max(_AUTO_CONTEXT_MIN, ((required + 4095) // 4096) * 4096)
def _transcript_token_budget(audio_seconds: Optional[float]) -> int:
@@ -658,6 +683,8 @@ class MtmdSttSidecar:
self._generation = 0
# Transcription runs outside _lock; the idle timer stays disarmed while requests are in flight.
self._active_requests = 0
+ self._context_length = 0
+ self._context_preference = 0 # 0 is Auto; a positive value is a hard limit.
@property
def loaded_model(self) -> Optional[str]:
@@ -669,6 +696,14 @@ class MtmdSttSidecar:
# derived, not a second probe: two probes can straddle the publish and report a device with no model
return "llama.cpp" if self.loaded_model else None
+ @property
+ def context_length(self) -> Optional[int]:
+ return self._context_length if self.loaded_model else None
+
+ @property
+ def context_length_preference(self) -> int:
+ return self._context_preference
+
def is_loading(self) -> bool:
# Bare bool read, for the same reason as loaded_model.
return self._loading
@@ -698,7 +733,7 @@ class MtmdSttSidecar:
def _idle_unload(self, generation: int) -> None:
with self._lock:
- if generation != self._generation:
+ if generation != self._generation or self._active_requests:
return
self._release_locked()
@@ -715,6 +750,8 @@ class MtmdSttSidecar:
self._api_key = None
self._model_id = None
self._binary_path_revision = None
+ self._context_length = 0
+ self._context_preference = 0
def _drain_active_requests(self, deadline: float) -> None:
"""Must not hold _lock: transcribe claims _active_requests under it, so the wait would block
@@ -850,11 +887,12 @@ class MtmdSttSidecar:
model: Optional[str] = None,
request_cancel_event: Optional[threading.Event] = None,
device: Optional[str] = None,
+ *,
+ context_length: Optional[int] = None,
) -> None:
"""``device`` is the user's audio device preference; ``cpu`` starts
llama-server at ``-ngl 0``, the same offload training already forces."""
- from core.inference.audio_device import audio_device_forces_cpu
-
+ _validate_context_length(context_length)
if request_cancel_event is not None and request_cancel_event.is_set():
raise SttTranscriptionCancelledError("Transcription cancelled.")
self._raise_if_update_in_progress()
@@ -874,6 +912,7 @@ class MtmdSttSidecar:
request_cancel_event,
path_revision = path_revision,
device = device,
+ context_length = context_length,
)
def _load_locked(
@@ -884,6 +923,9 @@ class MtmdSttSidecar:
*,
path_revision: Optional[int] = None,
device: Optional[str] = None,
+ context_length: Optional[int] = None,
+ _context_size: Optional[int] = None,
+ _active_request: bool = False,
) -> None:
from core.inference.audio_device import stt_device_forces_cpu
@@ -891,6 +933,24 @@ class MtmdSttSidecar:
from utils.llama_cpp_path_settings import custom_llama_cpp_path_revision
path_revision = custom_llama_cpp_path_revision()
with self._lock:
+ preference = (
+ self._context_preference
+ if context_length is None and self._process_alive()
+ else (context_length or 0)
+ )
+ # A preload in Auto keeps the warm window. The actual recording sizes it after counting.
+ context_size = (
+ _context_size
+ or preference
+ or (
+ self._context_length
+ if self._process_alive()
+ and self._model_id == model_id
+ and self._context_preference == 0
+ else _AUTO_CONTEXT_MIN
+ )
+ )
+ other_requests = self._active_requests - int(_active_request)
# None is no opinion: a caller sending none cannot move the server.
if device is None:
forced_cpu = (
@@ -905,8 +965,16 @@ class MtmdSttSidecar:
and self._model_id == model_id
and self._binary_path_revision == path_revision
):
+ if other_requests > 0 and preference != self._context_preference:
+ raise SttModelBusyError(
+ "A transcription is using the current voice context. "
+ "Retry after it finishes to change the context setting."
+ )
# Never restart a busy server just to move it back to the GPU; the next idle load does it.
- if self._gpu_disabled == training or self._active_requests:
+ if self._context_length == context_size and (
+ self._gpu_disabled == training or other_requests > 0
+ ):
+ self._context_preference = preference
# Recorded though nothing restarts: dropping it sends the next device-less load to the GPU.
self._forced_cpu = forced_cpu
self._schedule_idle_unload_locked()
@@ -925,7 +993,7 @@ class MtmdSttSidecar:
# Before the release: a 409 for an undownloaded model must not cost the current server.
model_path, mmproj_path = self._ensure_model_downloaded(model_id)
# Only guard a live server: a request against one that already died must not block recovery.
- if self._active_requests and self._process_alive():
+ if other_requests > 0 and self._process_alive():
raise SttModelBusyError(
"A transcription is still running on the current dictation model. "
"Try again in a moment."
@@ -955,6 +1023,9 @@ class MtmdSttSidecar:
# one short request at a time, so one slot keeps the footprint down next to a loaded chat model
"--parallel",
"1",
+ # Explicit so the voice model cannot inherit a chat-sized cache.
+ "--ctx-size",
+ str(context_size),
# keep off the accelerator during training so a dictation load cannot reclaim VRAM training just freed
"-ngl",
"0" if training else "99",
@@ -1023,11 +1094,27 @@ class MtmdSttSidecar:
"Dictation model loading was cancelled so training could start."
)
raise SttUnavailableError(f"llama-server did not become ready for '{model_id}'.")
+ try:
+ actual_context = self._read_server_context(port, api_key, cancel_event = cancel_event)
+ if actual_context != context_size:
+ raise SttContextSizeError(
+ f"The voice runtime loaded {actual_context} context tokens instead of "
+ f"{context_size}. Choose a supported context size or update the runtime."
+ )
+ if cancel_event.is_set():
+ raise SttLoadCancelledError("Dictation model loading was cancelled.")
+ except Exception as exc:
+ _reap(process)
+ if cancel_event.is_set():
+ raise SttLoadCancelledError("Dictation model loading was cancelled.") from exc
+ raise
with self._lock:
self._process = process
self._port = port
self._api_key = api_key
self._model_id = model_id
+ self._context_length = actual_context
+ self._context_preference = preference
self._binary_path_revision = path_revision
self._gpu_disabled = training
self._forced_cpu = forced_cpu
@@ -1073,6 +1160,8 @@ class MtmdSttSidecar:
fast: bool = False,
cancel_event: Optional[threading.Event] = None,
on_progress = None,
+ *,
+ context_length: Optional[int] = None,
) -> dict:
"""Transcribe encoded audio bytes, as the other sidecars do.
@@ -1090,7 +1179,11 @@ class MtmdSttSidecar:
raise SttTranscriptionCancelledError("Transcription cancelled.")
wav_bytes = _pcm_to_wav_bytes(decoded_audio)
audio_seconds = (len(decoded_audio) / _TARGET_SAMPLE_RATE) if len(decoded_audio) else None
- self.load(model_id, request_cancel_event = cancel_event)
+ self.load(
+ model_id,
+ request_cancel_event = cancel_event,
+ **({"context_length": context_length} if context_length is not None else {}),
+ )
with self._lock:
port = self._port
api_key = self._api_key
@@ -1102,11 +1195,52 @@ class MtmdSttSidecar:
"The dictation model changed while this recording was being "
"prepared. Try again."
)
- # Disarm the idle timer: long audio can outlast the keep-alive.
+ if context_length is not None and self._context_preference != context_length:
+ raise SttModelBusyError(
+ "The voice context changed while this recording was being prepared. Try again."
+ )
+ preference = self._context_preference if context_length is None else context_length
+ generation = self._generation
+ # Counting is part of the request: it must also keep the process resident.
self._active_requests += 1
self._cancel_idle_unload_locked()
try:
- # Outside the lock so unload (including training's) is not blocked for the whole request.
+ payload, _ = _transcription_payload(wav_bytes, audio_seconds, language)
+ input_tokens = self._count_prompt_tokens(
+ port, payload, cancel_event = cancel_event, api_key = api_key
+ )
+ with self._lock:
+ self._check_request_server(model_id, generation)
+ if preference == 0:
+ # Older supported runtimes cannot measure audio tokens. Preserve their full
+ # context rather than guess a smaller window or break default API requests.
+ required_context = (
+ _MAX_CONTEXT_LENGTH
+ if input_tokens is None
+ else _auto_context_length(input_tokens, payload["max_tokens"])
+ )
+ if input_tokens is None and self.context_length != required_context:
+ logger.info(
+ "Voice runtime has no audio token counter; Auto uses the full 64K context. "
+ "Choose a fixed voice context to reduce memory, or update llama.cpp."
+ )
+ self._resize_for_request(model_id, generation, required_context, cancel_event)
+ with self._lock:
+ # A resize changes both the port and its per-launch key.
+ if self._model_id != model_id or not self._process_alive():
+ raise SttModelBusyError("The voice model changed. Try this recording again.")
+ port, api_key = self._port, self._api_key
+ capacity = self._context_length
+ if preference and capacity != preference:
+ raise SttModelBusyError("The voice context changed. Try this recording again.")
+ available = capacity - (input_tokens or 0) - _CONTEXT_MARGIN
+ if available <= 0:
+ raise SttContextSizeError(
+ f"This recording does not fit the selected {capacity}-token voice context. "
+ "Choose Auto or a larger context, or use a shorter recording."
+ )
+ payload["max_tokens"] = min(payload["max_tokens"], available)
+ # Outside the lock so unload (including training's) remains bounded.
text = self._post_transcribe(
port,
model_id,
@@ -1114,6 +1248,7 @@ class MtmdSttSidecar:
audio_seconds,
language = language,
cancel_event = cancel_event,
+ payload = payload,
**({"api_key": api_key} if api_key else {}),
**({"on_progress": on_progress} if on_progress is not None else {}),
)
@@ -1134,6 +1269,132 @@ class MtmdSttSidecar:
"model": model_id,
}
+ def _check_request_server(self, model_id: str, generation: int) -> None:
+ if (
+ not self._process_alive()
+ or self._model_id != model_id
+ or self._generation != generation
+ ):
+ raise SttModelBusyError(
+ "The voice model changed while preparing this recording. Try again."
+ )
+
+ def _resize_for_request(
+ self,
+ model_id: str,
+ generation: int,
+ context_size: int,
+ cancel_event: Optional[threading.Event],
+ ) -> None:
+ # Only the preparing request may replace its own server. Other transcriptions
+ # can keep using a large enough window, but must never be killed by a resize.
+ while not self._start_lock.acquire(timeout = 0.05):
+ if cancel_event is not None and cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
+ try:
+ if cancel_event is not None and cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
+ self._raise_if_update_in_progress()
+ with self._lock:
+ self._check_request_server(model_id, generation)
+ if self._context_length == context_size:
+ return
+ if self._active_requests > 1:
+ if self._context_length >= context_size:
+ return
+ raise SttModelBusyError(
+ "Another transcription is using the voice model. Retry when it finishes "
+ "so this recording can load a larger context."
+ )
+ self._load_locked(
+ model_id,
+ ensure_engine_available(),
+ cancel_event,
+ context_length = 0,
+ _context_size = context_size,
+ _active_request = True,
+ )
+ finally:
+ self._start_lock.release()
+
+ @staticmethod
+ def _server_json(
+ port: int,
+ path: str,
+ payload: Optional[dict] = None,
+ *,
+ api_key: Optional[str] = None,
+ cancel_event: Optional[threading.Event] = None,
+ ) -> tuple[int, dict]:
+ connection = http.client.HTTPConnection("127.0.0.1", port, timeout = 60)
+ done = threading.Event()
+ if cancel_event is not None:
+ threading.Thread(
+ target = _close_connection_on_cancel,
+ args = (connection, cancel_event, done),
+ daemon = True,
+ ).start()
+ try:
+ if cancel_event is not None and cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
+ connection.request(
+ "GET" if payload is None else "POST",
+ path,
+ body = None if payload is None else json.dumps(payload).encode("utf-8"),
+ headers = {
+ "Content-Type": "application/json",
+ **({"Authorization": f"Bearer {api_key}"} if api_key else {}),
+ },
+ )
+ with connection.getresponse() as response:
+ raw = response.read()
+ try:
+ body = json.loads(raw)
+ except (ValueError, UnicodeError):
+ body = {}
+ return response.status, body if isinstance(body, dict) else {}
+ finally:
+ done.set()
+ connection.close()
+
+ @classmethod
+ def _read_server_context(
+ cls,
+ port: int,
+ api_key: Optional[str] = None,
+ *,
+ cancel_event: Optional[threading.Event] = None,
+ ) -> int:
+ status, body = cls._server_json(port, "/props", api_key = api_key, cancel_event = cancel_event)
+ settings = body.get("default_generation_settings") or {}
+ value = settings.get("n_ctx") if isinstance(settings, dict) else None
+ if status != 200 or type(value) is not int or value <= 0:
+ raise SttUnavailableError("Could not verify the voice runtime's context size.")
+ return value
+
+ @classmethod
+ def _count_prompt_tokens(
+ cls,
+ port: int,
+ payload: dict,
+ *,
+ cancel_event: Optional[threading.Event] = None,
+ api_key: Optional[str] = None,
+ ) -> Optional[int]:
+ status, body = cls._server_json(
+ port,
+ "/v1/chat/completions/input_tokens",
+ payload,
+ api_key = api_key,
+ cancel_event = cancel_event,
+ )
+ if status in (404, 405, 501):
+ return None
+ count = body.get("input_tokens")
+ if status != 200 or type(count) is not int or count <= 0:
+ raise SttUnavailableError("The voice runtime could not count this recording's tokens.")
+ return count
+
def cancel_transcription(self, cancel_event: threading.Event) -> bool:
already_cancelled = cancel_event.is_set()
cancel_event.set()
@@ -1150,35 +1411,15 @@ class MtmdSttSidecar:
cancel_event: Optional[threading.Event] = None,
on_progress = None,
api_key: Optional[str] = None,
+ payload: Optional[dict] = None,
) -> str:
spec = MTMD_STT_MODELS[model_id]
- payload = {
- "messages": [
- {
- "role": "user",
- "content": [
- {
- "type": "input_audio",
- "input_audio": {
- "data": base64.b64encode(wav_bytes).decode("ascii"),
- "format": "wav",
- },
- },
- {"type": "text", "text": _TRANSCRIBE_PROMPT},
- ],
- }
- ],
- # Greedy: a transcript, not a sampled paraphrase.
- "temperature": 0,
- "max_tokens": _transcript_token_budget(audio_seconds),
- }
- forced_language = QWEN3_ASR_LANGUAGE_NAMES.get(normalize_whisper_language(language) or "")
- assistant_prefix = ""
- if forced_language:
- assistant_prefix = f"language {forced_language}<asr_text>"
- payload["messages"].append({"role": "assistant", "content": assistant_prefix})
- # Explicit, so a server-wide --no-prefill-assistant cannot close the prefix as a finished turn.
- payload.update({"continue_final_message": True, "add_generation_prompt": False})
+ if payload is None:
+ payload, assistant_prefix = _transcription_payload(wav_bytes, audio_seconds, language)
+ else:
+ payload = dict(payload)
+ last = payload["messages"][-1]
+ assistant_prefix = last["content"] if last["role"] == "assistant" else ""
if on_progress is not None:
payload["stream"] = True
connection = http.client.HTTPConnection(
@@ -1224,6 +1465,7 @@ class MtmdSttSidecar:
)
choices = event.get("choices") or []
if choices:
+ _check_transcription_finish(choices[0].get("finish_reason"))
finished = finished or choices[0].get("finish_reason") is not None
text += choices[0].get("delta", {}).get("content") or ""
if not spec.transcript_marker or spec.transcript_marker in text:
@@ -1237,6 +1479,15 @@ class MtmdSttSidecar:
return _clean_transcript(text, spec.transcript_marker)
response_body = response.read()
if not 200 <= response.status < 300:
+ try:
+ error = json.loads(response_body).get("error", {})
+ except (ValueError, AttributeError):
+ error = {}
+ if isinstance(error, dict) and error.get("type") == "exceed_context_size_error":
+ raise SttContextSizeError(
+ "This recording exceeds the selected voice context. "
+ "Choose Auto or a larger context, or use a shorter recording."
+ )
raise RuntimeError(
f"MTMD transcription server returned HTTP {response.status}."
)
@@ -1245,10 +1496,53 @@ class MtmdSttSidecar:
cancel_done.set()
connection.close()
choices = body.get("choices") or []
+ if choices:
+ _check_transcription_finish(choices[0].get("finish_reason"))
text = (choices[0].get("message", {}).get("content") or "") if choices else ""
return _clean_transcript(text, spec.transcript_marker)
+def _transcription_payload(
+ wav_bytes: bytes, audio_seconds: Optional[float], language: Optional[str]
+) -> tuple[dict, str]:
+ payload = {
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "input_audio",
+ "input_audio": {
+ "data": base64.b64encode(wav_bytes).decode("ascii"),
+ "format": "wav",
+ },
+ },
+ {"type": "text", "text": _TRANSCRIBE_PROMPT},
+ ],
+ }
+ ],
+ # Greedy: a transcript, not a sampled paraphrase.
+ "temperature": 0,
+ "max_tokens": _transcript_token_budget(audio_seconds),
+ }
+ forced_language = QWEN3_ASR_LANGUAGE_NAMES.get(normalize_whisper_language(language) or "")
+ assistant_prefix = ""
+ if forced_language:
+ assistant_prefix = f"language {forced_language}<asr_text>"
+ payload["messages"].append({"role": "assistant", "content": assistant_prefix})
+ # Explicit, so a server-wide --no-prefill-assistant cannot close the prefix as a finished turn.
+ payload.update({"continue_final_message": True, "add_generation_prompt": False})
+ return payload, assistant_prefix
+
+
+def _check_transcription_finish(reason: Optional[str]) -> None:
+ if reason == "length":
+ raise SttIncompleteTranscriptionError(
+ "Transcription stopped at a token limit and is incomplete. "
+ "Try a shorter recording, or Auto/a larger voice context if you selected a fixed size."
+ )
+
+
def _clean_transcript(text: str, marker: Optional[str]) -> str:
"""Drop the model's leading metadata, keeping only the transcript."""
if marker and marker in text:
diff --git a/studio/backend/core/inference/stt_registry.py b/studio/backend/core/inference/stt_registry.py
index 4317c80c2c3..860491e2666 100644
--- a/studio/backend/core/inference/stt_registry.py
+++ b/studio/backend/core/inference/stt_registry.py
@@ -51,6 +51,8 @@ def load(
engine: str,
request_cancel_event: Optional[threading.Event] = None,
device: Optional[str] = None,
+ *,
+ context_length: Optional[int] = None,
**options,
) -> None:
"""Make ``model`` resident on ``engine``, then release every idle other engine.
@@ -65,6 +67,9 @@ def load(
sidecar raises, before anything is released: a 409 for a model that is not
downloaded must not cost the user the engine they were already using.
"""
+ # This option belongs to the llama.cpp ASR sidecar; other engines do not accept it.
+ if engine == "mtmd" and context_length is not None:
+ options["context_length"] = context_length
others = [name for name in STT_ENGINES if name != engine]
with _load_lock:
# Release other engines before allocating only once the checkpoint is on disk, so a switch
diff --git a/studio/backend/core/inference/stt_sidecar.py b/studio/backend/core/inference/stt_sidecar.py
index 3879bbce0f8..3fe147401dc 100644
--- a/studio/backend/core/inference/stt_sidecar.py
+++ b/studio/backend/core/inference/stt_sidecar.py
@@ -213,6 +213,14 @@ class SttAudioTooLongError(ValueError):
"""The decoded audio exceeds the bounded transcription duration."""
+class SttContextSizeError(ValueError):
+ """A recording cannot fit the selected context, or Auto cannot size it reliably."""
+
+
+class SttIncompleteTranscriptionError(ValueError):
+ """The server stopped at a limit instead of completing the transcription."""
+
+
class SttLanguageError(ValueError):
"""The requested language is not supported by the selected STT model."""
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index adf33153dce..4c1c81f0746 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -587,7 +587,32 @@ class SearchImagesLookupRequest(BaseModel):
)
-class TranscribeRequest(BaseModel):
+def validate_stt_context_length(value: Any) -> int:
+ """A zero selects Auto; fixed lengths are multiples of 256, since llama-server pads n_ctx to that."""
+ if type(value) is not int or (value != 0 and not (1024 <= value <= 65536 and value % 256 == 0)):
+ raise ValueError(
+ "Voice context length must be 0 (Auto) or a multiple of 256 from 1024 to 65536."
+ )
+ return value
+
+
+class SttContextSettings(BaseModel):
+ context_length: int = Field(
+ 0,
+ ge = 0,
+ le = 65536,
+ description = (
+ "Qwen3-ASR on llama.cpp only: 0 (Auto) sizes context for the recording; "
+ "a multiple of 256 from 1024 to 65536 fixes the context limit. Ignored by other STT engines."
+ ),
+ )
+
+ _validate_context_length = field_validator("context_length", mode = "before")(
+ validate_stt_context_length
+ )
+
+
+class TranscribeRequest(SttContextSettings):
"""Speech-to-text request for the dictation STT sidecar."""
audio: str = Field(..., description = "Base64-encoded audio (any common format)")
@@ -612,7 +637,7 @@ class TranscribeRequest(BaseModel):
)
-class SttLoadRequest(BaseModel):
+class SttLoadRequest(SttContextSettings):
"""Warm the STT sidecar with a model without transcribing."""
model: Optional[str] = Field(None, description = "STT model id; defaults server-side")
@@ -7011,7 +7036,7 @@ class AudioInputRecord(BaseModel):
expires_at: str
-class AudioInputTranscribeRequest(BaseModel):
+class AudioInputTranscribeRequest(SttContextSettings):
model_config = ConfigDict(extra = "forbid")
model: str = Field(..., min_length = 1, max_length = 512)
@@ -7044,7 +7069,7 @@ class TranscribeSourceRef(BaseModel):
return self
-class TranscribeSourceRequest(BaseModel):
+class TranscribeSourceRequest(SttContextSettings):
"""``POST /audio/transcribe/source``: Audio page audio named by id, transcribed and saved."""
model_config = ConfigDict(extra = "forbid")
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index e53d2a1329d..02322d2a33b 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -30,6 +30,7 @@ from fastapi.encoders import jsonable_encoder
from fastapi.responses import StreamingResponse, JSONResponse, PlainTextResponse, Response
from starlette.requests import ClientDisconnect
from typing import (
+ Annotated,
Any,
Callable,
Collection,
@@ -84,7 +85,7 @@ from dataclasses import dataclass, fields as dataclass_fields, replace
import re as _re
-from pydantic import BaseModel
+from pydantic import BaseModel, BeforeValidator
from urllib.parse import quote as _urlquote, unquote as _urlunquote
# Model size extraction (shared with core/inference/llama_cpp.py)
@@ -3429,6 +3430,7 @@ from models.inference import (
SearchImagesLookupRequest,
TranscribeRequest,
SttLoadRequest,
+ validate_stt_context_length,
GenerateRequest,
DiffusionLoadRequest,
MediaUnloadOutcome,
@@ -26045,6 +26047,7 @@ async def stt_load(
account_access.require_model_access, _stt_repo_reference(payload.model, payload.engine)
)
from core.inference.stt_sidecar import (
+ SttContextSizeError,
SttLoadCancelledError,
SttModelBusyError,
SttModelCompatibilityError,
@@ -26070,7 +26073,14 @@ async def stt_load(
)
try:
await asyncio.to_thread(
- functools.partial(load_stt, payload.model, engine, cancel_event, device = payload.device)
+ functools.partial(
+ load_stt,
+ payload.model,
+ engine,
+ cancel_event,
+ device = payload.device,
+ **({"context_length": payload.context_length} if engine == "mtmd" else {}),
+ )
)
except SttModelNotDownloadedError as e:
raise HTTPException(status_code = 409, detail = str(e))
@@ -26080,6 +26090,8 @@ async def stt_load(
raise HTTPException(status_code = 409, detail = str(e))
except SttModelBusyError as e:
raise HTTPException(status_code = 409, detail = str(e))
+ except SttContextSizeError as e:
+ raise HTTPException(status_code = 422, detail = str(e))
except SttModelIdError as e:
raise HTTPException(status_code = 422, detail = str(e))
except SttModelCompatibilityError as e:
@@ -26184,10 +26196,14 @@ async def _transcribe_audio_bytes(
engine: Optional[str] = None,
request: Optional[Request] = None,
device: Optional[str] = None,
+ *,
+ context_length: int = 0,
) -> JSONResponse:
"""Run STT for already-decoded request bytes."""
return JSONResponse(
- content = await _transcribe_audio_result(raw, model, language, fast, engine, request, device)
+ content = await _transcribe_audio_result(
+ raw, model, language, fast, engine, request, device, context_length = context_length
+ )
)
@@ -26205,6 +26221,7 @@ async def _transcribe_audio_result(
source_path: Optional[Path] = None,
timestamps: bool = False,
translate: bool = False,
+ context_length: int = 0,
) -> dict:
"""source_path is read in place by audio.cpp; translate is honoured only by the Transformers sidecar."""
if account_access.managed_account():
@@ -26212,6 +26229,8 @@ async def _transcribe_audio_result(
account_access.require_model_access, _stt_repo_reference(model, engine)
)
from core.inference.stt_sidecar import (
+ SttContextSizeError,
+ SttIncompleteTranscriptionError,
SttAudioDecodeError,
SttAudioTooLongError,
SttLanguageError,
@@ -26247,6 +26266,8 @@ async def _transcribe_audio_result(
transcribe = (
functools.partial(sidecar.transcribe, task = "translate") if translate else sidecar.transcribe
)
+ if serving_engine == "mtmd":
+ transcribe = functools.partial(transcribe, context_length = context_length)
cancel_event = threading.Event() if request is not None or on_progress is not None else None
disconnect_watcher = (
asyncio.create_task(_await_stt_disconnect_then_cancel(request, sidecar, cancel_event))
@@ -26262,6 +26283,8 @@ async def _transcribe_audio_result(
else None
)
load_options = {"on_phase": on_phase} if on_phase is not None else {}
+ if serving_engine == "mtmd":
+ load_options["context_length"] = context_length
if source_path is not None and timestamps:
await asyncio.to_thread(
holds_inference(sidecar.ensure_aligner), model, on_phase, cancel_event
@@ -26335,6 +26358,8 @@ async def _transcribe_audio_result(
except SttModelBusyError as e:
# Another client switching the dictation model is normal concurrency; say retry, not a failure.
raise HTTPException(status_code = 409, detail = str(e))
+ except (SttContextSizeError, SttIncompleteTranscriptionError) as e:
+ raise HTTPException(status_code = 422, detail = str(e))
except SttModelIdError as e:
raise HTTPException(status_code = 422, detail = str(e))
except SttModelCompatibilityError as e:
@@ -26387,9 +26412,17 @@ async def transcribe_audio(
payload.engine,
request,
payload.device,
+ context_length = payload.context_length,
)
+def _parse_stt_context_length_query(value: Any) -> int:
+ # Query parameters arrive as strings. Do not let Pydantic coerce "4096.0" or a boolean.
+ if isinstance(value, str) and re.fullmatch(r"[0-9]+", value):
+ value = int(value)
+ return validate_stt_context_length(value)
+
+
@studio_router.post("/audio/transcribe/raw")
async def transcribe_audio_raw(
request: Request,
@@ -26402,6 +26435,7 @@ async def transcribe_audio_raw(
current_subject: str = Depends(get_current_subject),
stream: bool = False,
title: str = Query("Recording", max_length = 255),
+ context_length: Annotated[int, BeforeValidator(_parse_stt_context_length_query)] = 0,
):
"""Transcribe a raw audio body without base64 or JSON conversion overhead."""
chunks: list[bytes] = []
@@ -26417,7 +26451,15 @@ async def transcribe_audio_raw(
return StreamingResponse(
stream_transcript(
lambda on_progress: _transcribe_audio_result(
- raw, model, language, fast, engine, None, device, on_progress
+ raw,
+ model,
+ language,
+ fast,
+ engine,
+ None,
+ device,
+ on_progress,
+ context_length = context_length,
),
title,
),
@@ -26426,7 +26468,14 @@ async def transcribe_audio_raw(
)
return JSONResponse(
content = await _transcribe_audio_result(
- b"".join(chunks), model, language, fast, engine, request, device
+ b"".join(chunks),
+ model,
+ language,
+ fast,
+ engine,
+ request,
+ device,
+ context_length = context_length,
)
)
@@ -26619,6 +26668,7 @@ async def transcribe_audio_source(
on_progress,
source_path = path,
timestamps = body.timestamps,
+ context_length = body.context_length,
)
return _source_transcript(result, source, body.speakers)
@@ -50822,7 +50872,14 @@ async def transcribe_audio_input(
except audio_inputs.AudioInputError as exc:
raise _audio_source_error(exc) from None
result = await _transcribe_audio_result(
- raw, body.model, body.language, False, body.engine, request, body.device
+ raw,
+ body.model,
+ body.language,
+ False,
+ body.engine,
+ request,
+ body.device,
+ context_length = body.context_length,
)
return AudioInputTranscript(
text = str(result.get("text") or "").strip(),
diff --git a/studio/backend/tests/test_audio_device_preference.py b/studio/backend/tests/test_audio_device_preference.py
index ad3e56b05fa..81a5ec53b3d 100644
--- a/studio/backend/tests/test_audio_device_preference.py
+++ b/studio/backend/tests/test_audio_device_preference.py
@@ -347,6 +347,8 @@ def test_the_mtmd_reuse_branch_still_records_the_choice(monkeypatch):
sidecar._model_id = "m"
sidecar._binary_path_revision = 1
sidecar._active_requests = 0
+ sidecar._context_preference = 0
+ sidecar._context_length = 4096
monkeypatch.setattr(sidecar, "_process_alive", lambda: True)
monkeypatch.setattr(sidecar, "_schedule_idle_unload_locked", lambda: None)
monkeypatch.setattr(stt_mtmd_sidecar, "_training_active", lambda: True)
diff --git a/studio/backend/tests/test_audio_inputs.py b/studio/backend/tests/test_audio_inputs.py
index a4ae66e166e..eb573e1ac81 100644
--- a/studio/backend/tests/test_audio_inputs.py
+++ b/studio/backend/tests/test_audio_inputs.py
@@ -419,17 +419,37 @@ def test_transcribe_sends_a_16k_mono_copy_and_saves_nothing(client, monkeypatch)
calls, model = [], "audio-cpp/audio.cpp-gguf/Qwen3-ASR-0.6B-GGUF"
- async def fake_transcribe(raw, model, language, fast, engine, request, device):
+ async def fake_transcribe(
+ raw,
+ model,
+ language,
+ fast,
+ engine,
+ request,
+ device,
+ *,
+ context_length = 0,
+ ):
with wave.open(io.BytesIO(raw)) as w:
- calls.append((w.getframerate(), w.getnchannels(), model, language, engine, device))
+ calls.append(
+ (
+ w.getframerate(),
+ w.getnchannels(),
+ model,
+ language,
+ engine,
+ device,
+ context_length,
+ )
+ )
return {"text": " Okay, I'm Cemo. ", "language": "English"}
monkeypatch.setattr(inference, "_transcribe_audio_result", fake_transcribe)
record = _upload(client, encode("webm", "libopus", 48000, "stereo", 1.0), "r.webm").json()
url = f"{INPUTS}/{record['id']}/transcribe"
- response = client.post(url, json = {"model": model, "device": "cpu"})
+ response = client.post(url, json = {"model": model, "device": "cpu", "context_length": 4096})
assert response.json() == {"text": "Okay, I'm Cemo.", "language": "English", "model": model}
- assert calls == [(16000, 1, model, None, None, "cpu")]
+ assert calls == [(16000, 1, model, None, None, "cpu", 4096)]
source, clip_q = f"{INPUTS}/source/transcribe", {"clip_id": _clip()["id"]}
assert client.post(source, params = clip_q, json = {"model": "m"}).status_code == 200
assert client.post(url, params = clip_q, json = {"model": "m"}).status_code == 400
diff --git a/studio/backend/tests/test_stt_context_compatibility.py b/studio/backend/tests/test_stt_context_compatibility.py
new file mode 100644
index 00000000000..3f90097293c
--- /dev/null
+++ b/studio/backend/tests/test_stt_context_compatibility.py
@@ -0,0 +1,52 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The public transcription API remains usable with supported pre-counting runtimes."""
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from auth.authentication import get_current_subject
+from routes import inference as ri
+from .test_stt_mtmd_context import MODEL, runtime # noqa: F401 - shared protocol fixture
+
+
[email protected]("preloaded_manual", [False, True])
+def test_public_transcription_without_native_count_keeps_legacy_capacity(
+ runtime, monkeypatch, preloaded_manual
+):
+ # The supported upstream b9415 macOS fallback can transcribe Qwen3-ASR and has /props,
+ # but predates /v1/chat/completions/input_tokens. Public clients cannot send a UI setting.
+ runtime.wire.count_status = 404
+ if preloaded_manual:
+ runtime.sidecar.load(MODEL, context_length = 4096)
+ monkeypatch.setattr(ri.account_access, "managed_account", lambda: False)
+ monkeypatch.setattr(ri, "_stt_engine_for_model", lambda model: "mtmd")
+ monkeypatch.setattr(ri, "_resolve_serving_stt_engine", lambda engine: "mtmd")
+ monkeypatch.setattr(ri, "_prepare_runtime_fallback_checkpoint", lambda *args: None)
+ monkeypatch.setattr(ri, "_stt_sidecar_for", lambda engine: runtime.sidecar)
+
+ def load(
+ model,
+ engine,
+ cancel_event = None,
+ **kwargs,
+ ):
+ runtime.sidecar.load(model, request_cancel_event = cancel_event, **kwargs)
+
+ monkeypatch.setattr(ri, "_stt_lifecycle", lambda: (load, lambda *args: []))
+ app = FastAPI()
+ app.include_router(ri.router, prefix = "/v1")
+ app.dependency_overrides[get_current_subject] = lambda: "test-user"
+ with TestClient(app) as client:
+ response = client.post(
+ "/v1/audio/transcriptions",
+ data = {"model": MODEL},
+ files = {"file": ("clip.wav", b"encoded", "audio/wav")},
+ )
+ assert response.status_code == 200, response.text
+ assert response.json()["text"] == "Complete sentence."
+ assert runtime.sidecar.context_length == 65536
+ assert runtime.sidecar.context_length_preference == 0
+ assert runtime.wire.generation_requests()
diff --git a/studio/backend/tests/test_stt_context_settings.py b/studio/backend/tests/test_stt_context_settings.py
new file mode 100644
index 00000000000..717b38ee6b6
--- /dev/null
+++ b/studio/backend/tests/test_stt_context_settings.py
@@ -0,0 +1,201 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Voice context preferences are validated and reach only the llama.cpp ASR sidecar."""
+
+import asyncio
+import json
+from types import SimpleNamespace
+
+import pytest
+from fastapi import FastAPI, HTTPException
+from fastapi.testclient import TestClient
+from pydantic import ValidationError
+
+from auth.authentication import get_current_subject
+from models.inference import (
+ AudioInputTranscribeRequest,
+ SttLoadRequest,
+ TranscribeRequest,
+ TranscribeSourceRequest,
+)
+from routes import inference as ri
+
+
+ "model, fields",
+ [
+ (SttLoadRequest, {}),
+ (TranscribeRequest, {"audio": "YQ=="}),
+ (AudioInputTranscribeRequest, {"model": "qwen3-asr-0.6b"}),
+ (TranscribeSourceRequest, {"model": "qwen3-asr-0.6b", "source": {"input_id": "a" * 32}}),
+ ],
+)
+def test_context_settings_are_strict_and_default_to_auto(model, fields):
+ assert model(**fields).context_length == 0
+ for value in (0, 1024, 4096, 5120, 65536):
+ assert model(**fields, context_length = value).context_length == value
+ for value in (True, False, None, "4096", 4096.0, 4096.5, -1, 1, 1023, 5000, 65537):
+ with pytest.raises(ValidationError, match = "Voice context length"):
+ model(**fields, context_length = value)
+
+
+def sidecar_calls(monkeypatch):
+ loads, transcriptions = [], []
+
+ def transcribe(*args, **kwargs):
+ transcriptions.append((args, kwargs))
+ return {"text": "hello", "model": "qwen3-asr-0.6b"}
+
+ sidecar = SimpleNamespace(loaded_model = None, device = None, transcribe = transcribe)
+ monkeypatch.setattr(ri.account_access, "managed_account", lambda: False)
+ monkeypatch.setattr(ri, "_resolve_serving_stt_engine", lambda engine: engine or "mtmd")
+ monkeypatch.setattr(ri, "_prepare_runtime_fallback_checkpoint", lambda *args: None)
+ monkeypatch.setattr(ri, "_stt_sidecar_for", lambda engine: sidecar)
+ monkeypatch.setattr(
+ ri,
+ "_stt_lifecycle",
+ lambda: (lambda *args, **kwargs: loads.append((args, kwargs)), lambda *args: []),
+ )
+ return loads, transcriptions
+
+
[email protected]("engine", ["mtmd", "gguf", "transformers", "audiocpp"])
[email protected]("streaming", [False, True])
+def test_only_mtmd_receives_context_on_implicit_load_and_transcription(
+ sidecar_calls, engine, streaming
+):
+ loads, transcriptions = sidecar_calls
+ result = asyncio.run(
+ ri._transcribe_audio_result(
+ b"audio",
+ "qwen3-asr-0.6b",
+ None,
+ False,
+ engine,
+ on_progress = (lambda event: None) if streaming else None,
+ context_length = 4096,
+ )
+ )
+ assert result["text"] == "hello"
+ for kwargs in (loads[0][1], transcriptions[0][1]):
+ if engine == "mtmd":
+ assert kwargs["context_length"] == 4096
+ else:
+ assert "context_length" not in kwargs
+
+
+def test_an_omitted_api_preference_requests_auto(sidecar_calls):
+ loads, transcriptions = sidecar_calls
+ asyncio.run(ri._transcribe_audio_result(b"audio", "qwen3-asr-0.6b", None, False, "mtmd"))
+ assert loads[0][1]["context_length"] == 0
+ assert transcriptions[0][1]["context_length"] == 0
+
+
[email protected]("error_name", ["SttContextSizeError", "SttIncompleteTranscriptionError"])
+def test_context_failures_are_actionable_422_errors(sidecar_calls, monkeypatch, error_name):
+ from core.inference import stt_sidecar
+
+ def fail(*args, **kwargs):
+ raise getattr(stt_sidecar, error_name)(
+ "Choose a larger voice context or a shorter recording."
+ )
+
+ monkeypatch.setattr(ri._stt_sidecar_for("mtmd"), "transcribe", fail)
+ with pytest.raises(HTTPException) as exc:
+ asyncio.run(ri._transcribe_audio_result(b"audio", "qwen3-asr-0.6b", None, False, "mtmd"))
+ assert exc.value.status_code == 422
+ assert "larger voice context" in exc.value.detail
+
+
+def client(monkeypatch):
+ app = FastAPI()
+ app.add_api_route("/load", ri.stt_load, methods = ["POST"])
+ app.add_api_route("/transcribe", ri.transcribe_audio, methods = ["POST"])
+ app.add_api_route("/raw", ri.transcribe_audio_raw, methods = ["POST"])
+ app.dependency_overrides[get_current_subject] = lambda: "test-user"
+ return TestClient(app)
+
+
[email protected]("engine", ["mtmd", "gguf"])
+def test_explicit_load_forwards_context_only_to_mtmd(client, sidecar_calls, engine):
+ response = client.post(
+ "/load",
+ json = {
+ "model": "qwen3-asr-0.6b",
+ "engine": engine,
+ "context_length": 8192,
+ },
+ )
+ assert response.status_code == 200, response.text
+ kwargs = sidecar_calls[0][0][1]
+ assert kwargs.get("context_length") == (8192 if engine == "mtmd" else None)
+
+
+def test_load_context_failure_is_422(client, sidecar_calls, monkeypatch):
+ from core.inference.stt_sidecar import SttContextSizeError
+
+ def fail(*args, **kwargs):
+ raise SttContextSizeError("The requested context is unavailable.")
+
+ monkeypatch.setattr(ri, "_stt_lifecycle", lambda: (fail, lambda *args: []))
+ response = client.post("/load", json = {"model": "qwen3-asr-0.6b", "engine": "mtmd"})
+ assert response.status_code == 422
+ assert response.json()["detail"] == "The requested context is unavailable."
+
+
+ "value", ["true", "false", "4096.0", "4096.5", "1e4", "-1", "1023", "5000", "65537"]
+)
+def test_raw_query_rejects_invalid_context_before_transcribing(client, monkeypatch, value):
+ async def unexpected(*args, **kwargs):
+ pytest.fail("invalid context reached transcription")
+
+ monkeypatch.setattr(ri, "_transcribe_audio_result", unexpected)
+ response = client.post("/raw", params = {"context_length": value}, content = b"audio")
+ assert response.status_code == 422, response.text
+
+
[email protected]("endpoint", ["json", "raw", "stream"])
+def test_request_preference_reaches_transcription(client, monkeypatch, endpoint):
+ calls = []
+
+ async def transcribe(*args, **kwargs):
+ calls.append(kwargs)
+ return {"text": "hello", "model": "qwen3-asr-0.6b", "duration": 1.0}
+
+ monkeypatch.setattr(ri, "_transcribe_audio_result", transcribe)
+ if endpoint == "json":
+ response = client.post("/transcribe", json = {"audio": "YQ==", "context_length": 8192})
+ else:
+ response = client.post(
+ "/raw",
+ params = {
+ "context_length": "8192",
+ "stream": endpoint == "stream",
+ },
+ content = b"audio",
+ )
+ assert response.status_code == 200, response.text
+ assert calls[0]["context_length"] == 8192
+
+
[email protected]("error_name", ["SttContextSizeError", "SttIncompleteTranscriptionError"])
+def test_streamed_context_failures_preserve_detail_without_completing(
+ client, sidecar_calls, monkeypatch, error_name
+):
+ from core.inference import stt_sidecar
+
+ message = "Choose a larger voice context or a shorter recording."
+
+ def fail(*args, **kwargs):
+ raise getattr(stt_sidecar, error_name)(message)
+
+ monkeypatch.setattr(ri._stt_sidecar_for("mtmd"), "transcribe", fail)
+ response = client.post("/raw", params = {"engine": "mtmd", "stream": True}, content = b"audio")
+ assert response.status_code == 200
+ events = [json.loads(line) for line in response.text.splitlines()]
+ assert events[-1] == {"type": "error", "message": message}
+ assert not any(event["type"] == "complete" for event in events)
diff --git a/studio/backend/tests/test_stt_mtmd_context.py b/studio/backend/tests/test_stt_mtmd_context.py
new file mode 100644
index 00000000000..08ad1cdea0d
--- /dev/null
+++ b/studio/backend/tests/test_stt_mtmd_context.py
@@ -0,0 +1,572 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Regression coverage for audio context allocation and incomplete transcriptions."""
+
+import json
+import threading
+from types import SimpleNamespace
+
+import pytest
+
+from core.inference import stt_mtmd_sidecar as mtmd
+from core.inference.stt_sidecar import SttContextSizeError, SttIncompleteTranscriptionError
+
+
+MODEL = "qwen3-asr-0.6b"
+
+
+class _Process:
+ _next_pid = 81000
+
+ def __init__(self, command):
+ type(self)._next_pid += 1
+ self.pid = type(self)._next_pid
+ self.command = list(command)
+ self.returncode = None
+
+ def poll(self):
+ return self.returncode
+
+ def terminate(self):
+ self.returncode = -15
+
+ def kill(self):
+ self.returncode = -9
+
+ def wait(self, timeout = None):
+ return self.returncode
+
+
+class _Wire:
+ """A local server protocol double, including the separate audio token-count endpoint."""
+
+ def __init__(self):
+ self.requests = []
+ self.input_tokens = 200
+ self.count_status = 200
+ self.finish_reason = "stop"
+ self.before_count = None
+ self.before_generate = None
+ self.context_by_port = {}
+
+ def connection(self, *args, **kwargs):
+ wire = self
+ port = args[1]
+
+ class Connection:
+ sock = None
+
+ def request(
+ self,
+ method,
+ path,
+ body = None,
+ headers = None,
+ ):
+ self.path = path
+ self.payload = json.loads(body) if body is not None else None
+ wire.requests.append((path, self.payload, headers))
+
+ def getresponse(self):
+ if self.path == "/props":
+ return Response(
+ 200, {"default_generation_settings": {"n_ctx": wire.context_by_port[port]}}
+ )
+ is_count = self.path.endswith("/input_tokens")
+ callback = wire.before_count if is_count else wire.before_generate
+ if callback is not None:
+ callback()
+ if is_count:
+ body = (
+ {"input_tokens": wire.input_tokens, "object": "response.input_tokens"}
+ if wire.count_status == 200
+ else {"error": {"message": "not found"}}
+ )
+ return Response(wire.count_status, body)
+ return Response(
+ 200,
+ {
+ "choices": [
+ {
+ "message": {
+ "content": "language English<asr_text>Complete sentence."
+ },
+ "finish_reason": wire.finish_reason,
+ }
+ ]
+ },
+ )
+
+ def close(self):
+ pass
+
+ class Response:
+ def __init__(self, status, body):
+ self.status, self.body = status, body
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return False
+
+ def read(self):
+ return json.dumps(self.body).encode()
+
+ def __iter__(self):
+ yield b'data: {"choices":[{"delta":{"content":"language English<asr_text>Complete sentence."},"finish_reason":null}]}\n'
+ event = {"choices": [{"delta": {}, "finish_reason": wire.finish_reason}]}
+ yield b"data: " + json.dumps(event).encode() + b"\n"
+ yield b"data: [DONE]\n"
+
+ return Connection()
+
+ def count_requests(self):
+ return [request for request in self.requests if request[0].endswith("/input_tokens")]
+
+ def generation_requests(self):
+ return [request for request in self.requests if request[0] == "/v1/chat/completions"]
+
+
+def runtime(monkeypatch):
+ from core.inference import llama_cpp
+
+ wire, processes = _Wire(), []
+
+ def spawn(command, **kwargs):
+ process = _Process(command)
+ processes.append(process)
+ wire.context_by_port[int(command[command.index("--port") + 1])] = _context(process)
+ return process
+
+ monkeypatch.setattr(mtmd.subprocess, "Popen", spawn)
+ monkeypatch.setattr(mtmd, "adopt_pid", lambda _pid: None)
+ monkeypatch.setattr(mtmd, "forget_pid", lambda _pid: None)
+ monkeypatch.setattr(mtmd, "ensure_engine_available", lambda: "/fake/llama-server")
+ monkeypatch.setattr(mtmd, "_llama_server_child_env", lambda _binary: {})
+ monkeypatch.setattr(mtmd, "_training_active", lambda: False)
+ monkeypatch.setattr(llama_cpp, "_llama_server_api_key_enabled", lambda: False)
+ monkeypatch.setattr(
+ mtmd.MtmdSttSidecar, "_ensure_model_downloaded", lambda *_args: ("m.gguf", "p.gguf")
+ )
+ monkeypatch.setattr(
+ mtmd.MtmdSttSidecar, "_wait_for_server", staticmethod(lambda *_args, **_kwargs: True)
+ )
+ monkeypatch.setattr(mtmd, "_decode_audio_bounded", lambda *_args: b"x" * 16000)
+ monkeypatch.setattr(mtmd, "_pcm_to_wav_bytes", lambda _audio: b"RIFFwav")
+ monkeypatch.setattr(mtmd.http.client, "HTTPConnection", wire.connection)
+ sidecar = mtmd.MtmdSttSidecar(keep_alive_seconds = 0)
+ yield SimpleNamespace(sidecar = sidecar, wire = wire, processes = processes)
+ sidecar.unload(wait = False)
+
+
+def _context(process):
+ return int(process.command[process.command.index("--ctx-size") + 1])
+
+
[email protected]("stream", [False, True])
+def test_length_finish_never_reports_a_successful_transcript(monkeypatch, stream):
+ """A server can return HTTP 200 and useful partial text despite exhausting the token budget."""
+ wire = _Wire()
+ wire.finish_reason = "length"
+ monkeypatch.setattr(mtmd.http.client, "HTTPConnection", wire.connection)
+ sidecar = mtmd.MtmdSttSidecar(keep_alive_seconds = 0)
+ progress = []
+ with pytest.raises(
+ SttIncompleteTranscriptionError, match = "(?i)context|limit|incomplete|truncat"
+ ):
+ sidecar._post_transcribe(
+ 12345,
+ MODEL,
+ b"RIFFwav",
+ 1.0,
+ on_progress = progress.append if stream else None,
+ )
+
+
[email protected]("stream", [False, True])
+def test_normal_stop_still_returns_complete_transcript(monkeypatch, stream):
+ wire = _Wire()
+ monkeypatch.setattr(mtmd.http.client, "HTTPConnection", wire.connection)
+ progress = []
+ assert (
+ mtmd.MtmdSttSidecar(keep_alive_seconds = 0)._post_transcribe(
+ 12345,
+ MODEL,
+ b"RIFFwav",
+ 1.0,
+ on_progress = progress.append if stream else None,
+ )
+ == "Complete sentence."
+ )
+
+
+ "input_tokens, expected_context", [(200, 4096), (3520, 4096), (3521, 8192)]
+)
+def test_auto_reserves_audio_output_and_margin(runtime, input_tokens, expected_context):
+ runtime.wire.input_tokens = input_tokens
+ result = runtime.sidecar.transcribe(b"encoded", model = MODEL, context_length = 0)
+ assert result["text"] == "Complete sentence."
+ assert runtime.wire.count_requests(), "Auto must count the actual prepared audio prompt"
+ assert _context(runtime.processes[-1]) == expected_context
+ assert runtime.wire.generation_requests()[-1][1]["max_tokens"] == 512
+
+
+def test_device_less_warm_load_preserves_selected_context(runtime):
+ runtime.sidecar.load(MODEL, context_length = 8192)
+ process = runtime.processes[-1]
+ runtime.sidecar.load(MODEL, context_length = None)
+ assert runtime.processes == [process]
+ assert _context(process) == 8192
+
+
+def test_manual_context_bounds_output_without_reloading_larger(runtime):
+ runtime.wire.input_tokens = 900
+ result = runtime.sidecar.transcribe(b"encoded", model = MODEL, context_length = 1024)
+ assert result["text"] == "Complete sentence."
+ assert all(_context(process) == 1024 for process in runtime.processes)
+ assert runtime.wire.generation_requests()[-1][1]["max_tokens"] == 60
+
+
+def test_count_and_generation_share_language_prefill_and_authentication(runtime):
+ runtime.sidecar.load(MODEL, context_length = 4096)
+ runtime.sidecar._api_key = "test-launch-key"
+ runtime.sidecar.transcribe(b"encoded", model = MODEL, context_length = 4096, language = "en-GB")
+ count = runtime.wire.count_requests()[-1]
+ generation = runtime.wire.generation_requests()[-1]
+ assert count[1]["messages"] == generation[1]["messages"]
+ assert count[1]["messages"][-1] == {
+ "role": "assistant",
+ "content": "language English<asr_text>",
+ }
+ for request in (count, generation):
+ assert request[1]["continue_final_message"] is True
+ assert request[1]["add_generation_prompt"] is False
+ assert request[2]["Authorization"] == "Bearer test-launch-key"
+
+
+def test_manual_context_can_use_an_older_server_without_token_counting(runtime):
+ runtime.wire.count_status = 404
+ result = runtime.sidecar.transcribe(b"encoded", model = MODEL, context_length = 4096)
+ assert result["text"] == "Complete sentence."
+ assert runtime.wire.generation_requests()
+ assert all(_context(process) == 4096 for process in runtime.processes)
+
+
[email protected]("status", [404, 405, 501])
+def test_auto_keeps_legacy_capacity_when_runtime_cannot_count_audio(runtime, status):
+ runtime.wire.count_status = status
+ result = runtime.sidecar.transcribe(b"encoded", model = MODEL, context_length = 0)
+ assert result["text"] == "Complete sentence."
+ assert runtime.wire.generation_requests()
+ assert runtime.sidecar.context_length == 65536
+ assert runtime.sidecar.context_length_preference == 0
+ assert _context(runtime.processes[-1]) == 65536
+ assert runtime.sidecar._active_requests == 0
+
+
+def test_manual_context_rejects_input_that_leaves_no_output_room(runtime):
+ runtime.wire.input_tokens = 960
+ with pytest.raises(SttContextSizeError, match = "(?i)does not fit"):
+ runtime.sidecar.transcribe(b"encoded", model = MODEL, context_length = 1024)
+ assert not runtime.wire.generation_requests()
+ assert [_context(process) for process in runtime.processes] == [1024]
+ assert runtime.sidecar._active_requests == 0
+
+
+def test_auto_rejects_recordings_beyond_model_capacity(runtime):
+ runtime.wire.input_tokens = 64961 # Input + 512 output + 64 margin exceeds 64K by one.
+ with pytest.raises(SttContextSizeError, match = "(?i)64K|65536"):
+ runtime.sidecar.transcribe(b"encoded", model = MODEL, context_length = 0)
+ assert not runtime.wire.generation_requests()
+ assert [_context(process) for process in runtime.processes] == [4096]
+
+
+def test_auto_accepts_exact_model_capacity(runtime):
+ runtime.wire.input_tokens = 64960
+ assert (
+ runtime.sidecar.transcribe(b"encoded", model = MODEL, context_length = 0)["text"]
+ == "Complete sentence."
+ )
+ assert _context(runtime.processes[-1]) == 65536
+ assert runtime.wire.generation_requests()[-1][1]["max_tokens"] == 512
+
+
+def test_auto_resize_uses_the_new_servers_authentication_key(runtime, monkeypatch):
+ from core.inference import llama_cpp
+
+ monkeypatch.setattr(llama_cpp, "_llama_server_api_key_enabled", lambda: True)
+ monkeypatch.setattr(
+ llama_cpp.LlamaCppBackend,
+ "probe_server_capabilities",
+ lambda _binary: {"supports_api_key_file": True},
+ )
+ monkeypatch.setattr(llama_cpp, "_llama_server_key_launch", lambda _key: ([], {}, None))
+ keys = iter(("initial-launch-key", "resized-launch-key"))
+ monkeypatch.setattr(mtmd.secrets, "token_urlsafe", lambda _length: next(keys))
+ runtime.wire.input_tokens = 3521
+ runtime.sidecar.transcribe(b"encoded", model = MODEL, context_length = 0)
+ assert runtime.wire.count_requests()[0][2]["Authorization"] == "Bearer initial-launch-key"
+ assert runtime.wire.generation_requests()[0][2]["Authorization"] == "Bearer resized-launch-key"
+ assert [_context(process) for process in runtime.processes] == [4096, 8192]
+ assert runtime.processes[0].poll() is not None
+
+
+def test_manual_setting_cannot_replace_auto_preference_during_count(runtime):
+ runtime.wire.input_tokens = 3521
+ runtime.wire.before_count = lambda: runtime.sidecar.load(MODEL, context_length = 4096)
+ with pytest.raises(mtmd.SttModelBusyError):
+ runtime.sidecar.transcribe(b"encoded", model = MODEL, context_length = 0)
+ assert not runtime.wire.generation_requests()
+ assert [_context(process) for process in runtime.processes] == [4096]
+ assert runtime.sidecar.context_length_preference == 0
+
+
+def test_an_idle_timer_cannot_unload_a_request_while_it_counts(runtime):
+ runtime.wire.before_count = lambda: runtime.sidecar._idle_unload(runtime.sidecar._generation)
+ result = runtime.sidecar.transcribe(b"encoded", model = MODEL, context_length = 0)
+ assert result["text"] == "Complete sentence."
+ assert len(runtime.processes) == 1
+ assert runtime.processes[0].poll() is None
+
+
+def test_forced_unload_during_count_does_not_send_audio_to_a_stale_port(runtime, monkeypatch):
+ monkeypatch.setattr(mtmd, "_ACTIVE_REQUEST_DRAIN_TIMEOUT", 0)
+ runtime.wire.before_count = lambda: runtime.sidecar.unload(wait = True)
+ with pytest.raises(mtmd.SttModelBusyError):
+ runtime.sidecar.transcribe(b"encoded", model = MODEL, context_length = 0)
+ assert not runtime.wire.generation_requests()
+ assert runtime.processes[0].poll() is not None
+ assert runtime.sidecar._active_requests == 0
+
+
+def test_cancelled_resize_wait_releases_its_request_without_killing_the_server(
+ runtime, monkeypatch
+):
+ runtime.wire.input_tokens = 3521
+ counting, return_count, resizing = threading.Event(), threading.Event(), threading.Event()
+ cancelled = threading.Event()
+ errors = []
+ original_resize = runtime.sidecar._resize_for_request
+
+ def count():
+ counting.set()
+ assert return_count.wait(3)
+
+ def resize(*args, **kwargs):
+ resizing.set()
+ return original_resize(*args, **kwargs)
+
+ runtime.wire.before_count = count
+ monkeypatch.setattr(runtime.sidecar, "_resize_for_request", resize)
+
+ def transcribe():
+ try:
+ runtime.sidecar.transcribe(
+ b"encoded", model = MODEL, context_length = 0, cancel_event = cancelled
+ )
+ except Exception as exc:
+ errors.append(exc)
+
+ worker = threading.Thread(target = transcribe, daemon = True)
+ worker.start()
+ acquired = False
+ try:
+ assert counting.wait(3)
+ acquired = runtime.sidecar._start_lock.acquire(timeout = 2)
+ assert acquired
+ return_count.set()
+ assert resizing.wait(3)
+ runtime.sidecar.cancel_transcription(cancelled)
+ worker.join(timeout = 2)
+ assert not worker.is_alive(), "cancellation remained blocked behind another startup"
+ finally:
+ return_count.set()
+ if acquired:
+ runtime.sidecar._start_lock.release()
+ worker.join(timeout = 3)
+ assert len(errors) == 1 and isinstance(errors[0], mtmd.SttTranscriptionCancelledError)
+ assert runtime.sidecar._active_requests == 0
+ assert not runtime.wire.generation_requests()
+ assert len(runtime.processes) == 1 and runtime.processes[0].poll() is None
+
+
[email protected]("second_input_tokens, second_succeeds", [(8000, False), (200, True)])
+def test_context_resize_does_not_interrupt_a_sibling_transcription(
+ runtime, second_input_tokens, second_succeeds
+):
+ first_started, release_first = threading.Event(), threading.Event()
+ first_results, first_errors = [], []
+
+ def count():
+ runtime.wire.input_tokens = (
+ 3521 if threading.current_thread().name == "first-recording" else second_input_tokens
+ )
+
+ def generate():
+ if threading.current_thread().name == "first-recording":
+ first_started.set()
+ assert release_first.wait(5)
+
+ runtime.wire.before_count = count
+ runtime.wire.before_generate = generate
+
+ def first_request():
+ try:
+ first_results.append(
+ runtime.sidecar.transcribe(b"first", model = MODEL, context_length = 0)
+ )
+ except Exception as exc:
+ first_errors.append(exc)
+
+ worker = threading.Thread(target = first_request, name = "first-recording", daemon = True)
+ worker.start()
+ try:
+ assert first_started.wait(3)
+ resident = runtime.processes[-1]
+ assert _context(resident) == 8192
+ if second_succeeds:
+ assert (
+ runtime.sidecar.transcribe(b"second", model = MODEL, context_length = 0)["text"]
+ == "Complete sentence."
+ )
+ else:
+ # This case needs a genuinely larger window than the first recording's 8K.
+ with pytest.raises(mtmd.SttModelBusyError):
+ runtime.sidecar.transcribe(b"second", model = MODEL, context_length = 0)
+ assert runtime.processes[-1] is resident and resident.poll() is None
+ finally:
+ release_first.set()
+ worker.join(timeout = 5)
+ assert not worker.is_alive()
+ assert not first_errors
+ assert first_results[0]["text"] == "Complete sentence."
+ assert [_context(process) for process in runtime.processes] == [4096, 8192]
+ assert runtime.sidecar._active_requests == 0
+
+
+def test_setting_changed_between_load_and_request_claim_is_not_overwritten(runtime, monkeypatch):
+ """A same-model setting change need not replace the process or bump its generation."""
+ original_load = runtime.sidecar.load
+ runtime.wire.input_tokens = 3521
+
+ def load_then_select_manual(*args, **kwargs):
+ original_load(*args, **kwargs)
+ original_load(MODEL, context_length = 4096)
+
+ monkeypatch.setattr(runtime.sidecar, "load", load_then_select_manual)
+ with pytest.raises(mtmd.SttModelBusyError):
+ runtime.sidecar.transcribe(b"encoded", model = MODEL, context_length = 0)
+ assert not runtime.wire.generation_requests()
+ assert [_context(process) for process in runtime.processes] == [4096]
+ assert runtime.sidecar.context_length_preference == 4096
+
+
[email protected]("context_length", [1000, 5000, 65537])
+def test_a_size_llama_server_would_pad_is_refused_before_launch(runtime, context_length):
+ with pytest.raises(SttContextSizeError, match = "multiple of 256"):
+ runtime.sidecar.load(MODEL, context_length = context_length)
+ assert runtime.processes == []
+
+
+def test_server_cannot_silently_exceed_the_requested_manual_context(runtime, monkeypatch):
+ monkeypatch.setattr(runtime.sidecar, "_read_server_context", lambda *_args, **_kwargs: 8192)
+ with pytest.raises(SttContextSizeError, match = "8192.*4096"):
+ runtime.sidecar.load(MODEL, context_length = 4096)
+ assert runtime.sidecar.loaded_model is None
+ assert len(runtime.processes) == 1 and runtime.processes[0].poll() is not None
+ assert runtime.sidecar.is_loading() is False
+
+
+ "failure",
+ [ConnectionResetError("connection reset"), mtmd.SttUnavailableError("props unavailable")],
+)
+def test_preemption_during_context_verification_stays_retryable(runtime, monkeypatch, failure):
+ """Training can terminate a healthy child while the new /props probe is in flight."""
+
+ def preempt_during_props(*_args, **_kwargs):
+ assert runtime.sidecar.cancel_pending_load()
+ raise failure
+
+ monkeypatch.setattr(runtime.sidecar, "_read_server_context", preempt_during_props)
+ with pytest.raises(mtmd.SttLoadCancelledError):
+ runtime.sidecar.load(MODEL, context_length = 4096)
+ assert runtime.sidecar.loaded_model is None
+ assert runtime.sidecar.is_loading() is False
+ assert runtime.processes[0].poll() is not None
+
+
+def test_cancelling_context_verification_interrupts_a_stalled_http_read(runtime, monkeypatch):
+ """An unresponsive child must not turn cancellation into a sixty-second /props timeout."""
+ import subprocess
+
+ reading, unblock = threading.Event(), threading.Event()
+ cancelled = threading.Event()
+ errors = []
+
+ class Socket:
+ def shutdown(self, _how):
+ unblock.set()
+
+ class Response:
+ status = 200
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return False
+
+ def read(self):
+ reading.set()
+ assert unblock.wait(5), "the test did not clean up its blocked HTTP read"
+ raise OSError("connection interrupted")
+
+ class Connection:
+ def __init__(self, *_args, **_kwargs):
+ self.sock = Socket()
+
+ def request(self, method, path, **_kwargs):
+ assert method == "GET" and path == "/props"
+
+ def getresponse(self):
+ return Response()
+
+ def close(self):
+ pass
+
+ monkeypatch.setattr(mtmd.http.client, "HTTPConnection", Connection)
+
+ def load():
+ try:
+ runtime.sidecar.load(MODEL, context_length = 4096, request_cancel_event = cancelled)
+ except Exception as exc:
+ errors.append(exc)
+
+ loader = threading.Thread(target = load, daemon = True)
+ loader.start()
+ try:
+ assert reading.wait(3)
+ process = runtime.processes[0]
+ # Match an actual native child that ignores graceful shutdown until it is killed.
+ monkeypatch.setattr(process, "terminate", lambda: None)
+
+ def wait(timeout = None):
+ if process.poll() is None:
+ raise subprocess.TimeoutExpired("llama-server", timeout)
+ return process.returncode
+
+ monkeypatch.setattr(process, "wait", wait)
+ runtime.sidecar.cancel_transcription(cancelled)
+ loader.join(timeout = 1)
+ assert not loader.is_alive(), "cancelled load is still waiting on the /props HTTP timeout"
+ finally:
+ unblock.set()
+ loader.join(timeout = 3)
+ assert len(errors) == 1 and isinstance(errors[0], mtmd.SttLoadCancelledError)
+ assert process.poll() is not None
+ assert runtime.sidecar.is_loading() is False
diff --git a/studio/backend/tests/test_stt_mtmd_sidecar.py b/studio/backend/tests/test_stt_mtmd_sidecar.py
index 3665d25bd44..ff90aaf159f 100644
--- a/studio/backend/tests/test_stt_mtmd_sidecar.py
+++ b/studio/backend/tests/test_stt_mtmd_sidecar.py
@@ -24,6 +24,7 @@ def _shared_setup_2(monkeypatch):
mtmd_mod, "_decode_audio_bounded", lambda audio, cancel_event = None: b"\x00\x00" * 16000
)
monkeypatch.setattr(mtmd_mod, "_pcm_to_wav_bytes", lambda pcm: b"RIFFwav")
+ monkeypatch.setattr(MtmdSttSidecar, "_count_prompt_tokens", staticmethod(lambda *a, **k: 20))
class _FakeProcess:
@@ -79,6 +80,7 @@ def spawned(monkeypatch):
monkeypatch.setattr(
MtmdSttSidecar, "_ensure_model_downloaded", lambda self, model_id: ("m.gguf", "p.gguf")
)
+ monkeypatch.setattr(MtmdSttSidecar, "_read_server_context", staticmethod(lambda *a, **k: 4096))
return made, adopted, forgotten
@@ -555,6 +557,7 @@ def test_disconnecting_one_mtmd_request_does_not_kill_its_sibling(monkeypatch):
sidecar._process = process
sidecar._port = 65000
sidecar._model_id = "qwen3-asr-0.6b"
+ sidecar._context_length = 4096
monkeypatch.setattr(sidecar, "load", lambda model, **kwargs: None)
first_cancel = threading.Event()
@@ -572,6 +575,7 @@ def test_disconnecting_one_mtmd_request_does_not_kill_its_sibling(monkeypatch):
*,
language = None,
cancel_event = None,
+ payload = None,
):
nonlocal started
with started_lock:
diff --git a/studio/backend/tests/test_stt_registry.py b/studio/backend/tests/test_stt_registry.py
index fccd43c6f66..b4ed9ca529d 100644
--- a/studio/backend/tests/test_stt_registry.py
+++ b/studio/backend/tests/test_stt_registry.py
@@ -437,7 +437,9 @@ def test_an_implicit_transcribe_load_releases_the_other_engines(monkeypatch):
ri,
"_stt_lifecycle",
lambda: (
- lambda model, engine, cancel = None, device = None: loaded.append((model, engine)),
+ lambda model, engine, cancel = None, device = None, **options: loaded.append(
+ (model, engine)
+ ),
lambda *a: [],
),
)
@@ -654,3 +656,18 @@ def test_no_stt_sidecar_points_at_a_settings_path_for_downloads():
"stt_sidecar.py",
):
assert "Settings, then Voice" not in (inference / name).read_text(encoding = "utf-8"), name
+
+
[email protected]("engine", stt_registry.STT_ENGINES)
+def test_registry_forwards_voice_context_only_to_mtmd(monkeypatch, engine):
+ calls = []
+ sidecar = _Sidecar(engine)
+ sidecar.load = lambda *args, **kwargs: calls.append(kwargs)
+ monkeypatch.setattr(stt_registry, "sidecar_for", lambda name: sidecar)
+ monkeypatch.setattr(stt_registry, "_model_is_downloaded", lambda *args: True)
+ monkeypatch.setattr(stt_registry, "unload", lambda *args, **kwargs: [])
+ stt_registry.load("qwen3-asr-0.6b", engine, context_length = 4096)
+ if engine == "mtmd":
+ assert calls[0]["context_length"] == 4096
+ else:
+ assert "context_length" not in calls[0]
diff --git a/studio/backend/tests/test_transcribe_source_route.py b/studio/backend/tests/test_transcribe_source_route.py
index 22aee186878..628feeb59fb 100644
--- a/studio/backend/tests/test_transcribe_source_route.py
+++ b/studio/backend/tests/test_transcribe_source_route.py
@@ -305,6 +305,28 @@ def test_a_source_past_the_connection_limit_is_refused_before_upload(stub, conne
assert not connection and not stub.bytes
+def test_mtmd_source_keeps_its_context_preference_through_streaming(stub, monkeypatch):
+ calls = []
+ original = stub.transcribe
+
+ def transcribe(*args, **kwargs):
+ calls.append(kwargs)
+ return original(*args, **kwargs)
+
+ monkeypatch.setattr(stub, "transcribe", transcribe)
+ with _client(ALICE) as client:
+ response, events = _post(
+ client,
+ model = "qwen3-asr-0.6b",
+ engine = "mtmd",
+ source = {"input_id": _input(ALICE)},
+ context_length = 8192,
+ )
+ assert response.status_code == 200, response.text
+ assert events[-1]["type"] == "complete", events
+ assert calls[0]["context_length"] == 8192
+
+
def _long_input(account, seconds = 3.0) -> str:
save = audio_inputs.save_stream(_chunks([wav_bytes(seconds)]), "long.wav")
return run_as(account, lambda: asyncio.run(save)[0]["id"])
diff --git a/studio/frontend/src/features/audio/api.ts b/studio/frontend/src/features/audio/api.ts
index d4ff064cff6..627041b8fbb 100644
--- a/studio/frontend/src/features/audio/api.ts
+++ b/studio/frontend/src/features/audio/api.ts
@@ -493,6 +493,7 @@ export async function transcribeAudioInput(
model: string;
engine?: string;
device?: string;
+ context_length?: number;
language?: string;
purpose?: "reference" | "convert";
},
diff --git a/studio/frontend/src/features/audio/hooks/use-reference-transcribe.ts b/studio/frontend/src/features/audio/hooks/use-reference-transcribe.ts
index 91eb71474c6..340b1a093f0 100644
--- a/studio/frontend/src/features/audio/hooks/use-reference-transcribe.ts
+++ b/studio/frontend/src/features/audio/hooks/use-reference-transcribe.ts
@@ -3,6 +3,7 @@
import { sttEngineFor } from "@/features/chat/adapters/studio-model-dictation-adapter";
import { useVoiceSettingsStore, withSttVariant } from "@/features/settings";
+import { sttContextBody } from "@/features/settings/stores/stt-context";
import { useCallback, useEffect, useRef, useState } from "react";
import { transcribeAudioInput } from "../api";
import { type AudioSourceSelection, sourceRefOf } from "../audio-run-request";
@@ -37,6 +38,7 @@ export function useReferenceTranscribe({
try {
const voice = useVoiceSettingsStore.getState();
const model = sttRepo ? sttSidecarKeyFor(sttRepo) : voice.sttModel;
+ const engine = sttRepo ? sttEngineForRepoId(sttRepo) : sttEngineFor(model);
const result = await transcribeAudioInput(
sourceRefOf(reference),
{
@@ -44,9 +46,10 @@ export function useReferenceTranscribe({
model: sttRepo
? model
: withSttVariant(model, voice.sttGgufVariant),
- engine: sttRepo ? sttEngineForRepoId(sttRepo) : sttEngineFor(model),
+ engine,
device: voice.sttDevice,
purpose,
+ ...sttContextBody(model, engine, voice.sttContextLength),
},
controller.signal,
);
diff --git a/studio/frontend/src/features/audio/transcribe-api.ts b/studio/frontend/src/features/audio/transcribe-api.ts
index 45226bacb58..e5647807f83 100644
--- a/studio/frontend/src/features/audio/transcribe-api.ts
+++ b/studio/frontend/src/features/audio/transcribe-api.ts
@@ -2,6 +2,10 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { authFetch } from "@/features/auth";
+import {
+ sttContextBody,
+ useVoiceSettingsStore,
+} from "@/features/settings/stores/voice-settings-store";
import { readFastApiError } from "@/lib/format-fastapi-error";
import { AudioApiError } from "./api";
import type { AudioSourceRef } from "./audio-run-request";
@@ -31,6 +35,7 @@ export async function transcribeSourceWithProgress(
model: string;
engine: string;
device: string;
+ contextLength?: number;
language: string;
timestamps: boolean;
speakers: boolean;
@@ -47,6 +52,12 @@ export async function transcribeSourceWithProgress(
model: options.model,
engine: options.engine || null,
device: options.device || null,
+ ...(!options.providerId &&
+ sttContextBody(
+ options.model,
+ options.engine,
+ options.contextLength ?? useVoiceSettingsStore.getState().sttContextLength,
+ )),
language: options.language || null,
timestamps: options.timestamps,
speakers: options.speakers,
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.ts
index 3bad393705c..a8ae7a2d4cd 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
@@ -20,6 +20,7 @@ import {
isCuratedSttModel,
recordRecentDictation,
resolveModelDictationLanguage,
+ sttContextBody,
sttListedQuantDownloaded,
sttModelVariant,
useVoiceSettingsStore,
@@ -131,6 +132,7 @@ export async function transcribeAudioBlob(
language?: string;
engine?: SttEngine;
device?: SttDevice;
+ contextLength?: number;
/** package-folder quant; defaults to the saved quant when `model` is also omitted */
ggufVariant?: string | null;
providerId?: string;
@@ -211,6 +213,14 @@ export async function transcribeAudioBlob(
});
if (language) params.set("language", language);
params.set("device", options.device ?? settings.sttDevice);
+ const context = sttContextBody(
+ model,
+ engine,
+ options.contextLength ?? settings.sttContextLength,
+ );
+ if (context.context_length !== undefined) {
+ params.set("context_length", String(context.context_length));
+ }
const response = await authFetch(
`/api/inference/audio/transcribe/raw?${params.toString()}`,
{
@@ -373,9 +383,16 @@ export function loadSttModel(
signal?: AbortSignal,
device?: SttDevice,
ggufVariant?: string | null,
+ contextLength?: number,
): Promise<void> {
const resolvedEngine = engine ?? sttEngineFor(model);
- const resolvedDevice = device ?? useVoiceSettingsStore.getState().sttDevice;
+ const settings = useVoiceSettingsStore.getState();
+ const resolvedDevice = device ?? settings.sttDevice;
+ const context = sttContextBody(
+ model,
+ resolvedEngine,
+ contextLength ?? settings.sttContextLength,
+ );
// Announced so the indicator shows the load immediately, as the toast does.
return queueSttLifecycle(() =>
withModelLoadNotice("stt", model, async () => {
@@ -386,6 +403,7 @@ export function loadSttModel(
model,
engine: resolvedEngine,
device: resolvedDevice,
+ ...context,
...sttVariantBody(resolvedEngine, ggufVariant),
}),
signal,
diff --git a/studio/frontend/src/features/settings/stores/stt-context.ts b/studio/frontend/src/features/settings/stores/stt-context.ts
new file mode 100644
index 00000000000..1bf99aefaf1
--- /dev/null
+++ b/studio/frontend/src/features/settings/stores/stt-context.ts
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { MTMD_STT_MODELS } from "./stt-model-catalog.ts";
+
+/** Zero lets the backend fit the context to each recording. */
+export const DEFAULT_STT_CONTEXT_LENGTH = 0;
+export const STT_CONTEXT_LENGTHS = [
+ 1024, 2048, 4096, 8192, 16384, 32768, 65536,
+] as const;
+
+export function normalizeSttContextLength(value: unknown): number {
+ return typeof value === "number" &&
+ Number.isInteger(value) &&
+ (value === 0 || (value >= 1024 && value <= 65536 && value % 256 === 0))
+ ? value
+ : DEFAULT_STT_CONTEXT_LENGTH;
+}
+
+/** Other engines and custom models have different memory controls. */
+export function sttContextBody(
+ model: string,
+ engine: string,
+ contextLength: unknown,
+): { context_length?: number } {
+ return engine === "mtmd" && MTMD_STT_MODELS.has(model.trim())
+ ? { context_length: normalizeSttContextLength(contextLength) }
+ : {};
+}
diff --git a/studio/frontend/src/features/settings/stores/voice-settings-store.ts b/studio/frontend/src/features/settings/stores/voice-settings-store.ts
index bff4a50a41e..967b84459f0 100644
--- a/studio/frontend/src/features/settings/stores/voice-settings-store.ts
+++ b/studio/frontend/src/features/settings/stores/voice-settings-store.ts
@@ -5,6 +5,10 @@ import { isTauri } from "@/lib/api-base";
import { isAudioCppFolderId } from "../../audio/audio-cpp-catalog";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
+import {
+ DEFAULT_STT_CONTEXT_LENGTH,
+ normalizeSttContextLength,
+} from "./stt-context";
import {
DEFAULT_STT_MODEL,
type DefaultSttModel,
@@ -17,6 +21,7 @@ import {
import { syncSttDevicePreference } from "../api/stt-device";
export * from "./stt-model-catalog";
+export * from "./stt-context";
// Adapters read these at call time, so changes apply without reloading the chat runtime.
@@ -114,6 +119,10 @@ export interface VoiceSettingsState {
sttDevice: SttDevice;
setSttDevice: (value: SttDevice) => void;
+ /** Qwen3-ASR context: zero fits each recording; a positive value is a fixed limit. */
+ sttContextLength: number;
+ setSttContextLength: (value: number) => void;
+
sttProviderId: string;
setSttProviderId: (value: string) => void;
sttProviderModel: string;
@@ -244,6 +253,10 @@ export const useVoiceSettingsStore = create<VoiceSettingsState>()(
syncSttDevicePreference(sttDevice);
},
+ sttContextLength: DEFAULT_STT_CONTEXT_LENGTH,
+ setSttContextLength: (value) =>
+ set({ sttContextLength: normalizeSttContextLength(value) }),
+
sttProviderId: "",
setSttProviderId: (sttProviderId) => set({ sttProviderId }),
sttProviderModel: "",
@@ -390,6 +403,7 @@ export const useVoiceSettingsStore = create<VoiceSettingsState>()(
? asString(saved?.sttGgufVariant, "")
: "",
sttDevice: normalizeSttDevice(saved?.sttDevice),
+ sttContextLength: normalizeSttContextLength(saved?.sttContextLength),
sttProviderId: asString(saved?.sttProviderId, ""),
sttProviderModel: asString(saved?.sttProviderModel, ""),
dictationLanguage,
diff --git a/studio/frontend/src/features/settings/tabs/voice-tab.tsx b/studio/frontend/src/features/settings/tabs/voice-tab.tsx
index 791cb54a6a5..fd6998cea17 100644
--- a/studio/frontend/src/features/settings/tabs/voice-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/voice-tab.tsx
@@ -96,12 +96,14 @@ import {
AUDIO_CPP_STT_MODELS,
MTMD_STT_MODELS,
RECOMMENDED_STT_MODELS,
+ STT_CONTEXT_LENGTHS,
STT_PICKER_MODELS,
type SttModel,
getSttModelRepo,
isCuratedSttModel,
isSttModelId,
isSttModelLanguageCompatible,
+ normalizeSttContextLength,
sttModelName,
sttModelSize,
sttListedQuantDownloaded,
@@ -495,6 +497,8 @@ export function VoiceTab() {
// Named apart from the `sttDevice` state below, which the sidecar reports back.
const sttDevicePreference = useVoiceSettingsStore((s) => s.sttDevice);
const setSttDevicePreference = useVoiceSettingsStore((s) => s.setSttDevice);
+ const sttContextLength = useVoiceSettingsStore((s) => s.sttContextLength);
+ const setSttContextLength = useVoiceSettingsStore((s) => s.setSttContextLength);
const sttProviderId = useVoiceSettingsStore((s) => s.sttProviderId);
const setSttProviderId = useVoiceSettingsStore((s) => s.setSttProviderId);
const sttProviderModel = useVoiceSettingsStore((s) => s.sttProviderModel);
@@ -1500,6 +1504,61 @@ export function VoiceTab() {
</SettingsRow>
) : null}
+ {isLocalEngine && modelSttSupported && MTMD_STT_MODELS.has(sttModel) ? (
+ <SettingsRow
+ label={t("settings.voice.dictation.sttContextLabel")}
+ description={
+ sttContextLength === 0
+ ? t("settings.voice.dictation.sttContextAutoDescription")
+ : t("settings.voice.dictation.sttContextFixedDescription")
+ }
+ >
+ <Select
+ value={String(sttContextLength)}
+ onValueChange={(value) => {
+ const next = normalizeSttContextLength(Number(value));
+ if (next === sttContextLength) return;
+ // Keep an active transcription; the next request applies the new preference.
+ void unloadSttModel(sttEngineFor(sttModel), sttModel, {
+ wait: false,
+ }).catch(() => {});
+ setSttPhase("on-demand");
+ setSttDevice(null);
+ setSttContextLength(next);
+ }}
+ >
+ <SelectTrigger
+ data-testid="stt-context-trigger"
+ aria-label={t("settings.voice.dictation.sttContextLabel")}
+ className="w-56"
+ size="sm"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="0" data-testid="stt-context-auto">
+ {t("settings.voice.dictation.sttContextAuto")}
+ </SelectItem>
+ {STT_CONTEXT_LENGTHS.map((length) => (
+ <SelectItem key={length} value={String(length)}>
+ {t("settings.voice.dictation.sttContextTokens", {
+ count: length.toLocaleString(),
+ })}
+ </SelectItem>
+ ))}
+ {sttContextLength > 0 &&
+ !STT_CONTEXT_LENGTHS.some((length) => length === sttContextLength) ? (
+ <SelectItem value={String(sttContextLength)}>
+ {t("settings.voice.dictation.sttContextTokens", {
+ count: sttContextLength.toLocaleString(),
+ })}
+ </SelectItem>
+ ) : null}
+ </SelectContent>
+ </Select>
+ </SettingsRow>
+ ) : null}
+
<SettingsRow
label={t("settings.voice.dictation.microphoneLabel")}
description={
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 2745d2804aa..7c0a42cd4c2 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -1684,6 +1684,13 @@ export const ar = {
sttQuantDescription:
"اختر نموذج STT أو ابحث عنه لتشغيله محليًا، ثم اختر التكميم.",
sttDeviceLabel: "التحميل إلى",
+ sttContextLabel: "سياق الصوت",
+ sttContextAuto: "تلقائي (موصى به)",
+ sttContextAutoDescription:
+ "يضبط حجم السياق حسب كل تسجيل، ويستخدم ذاكرة أكثر للتسجيلات الأطول. قد تحتاج بيئات التشغيل القديمة إلى حجم ثابت لتقليل استخدام الذاكرة. ينطبق على Qwen3-ASR في «الصوت» و«تفريغ نصي».",
+ sttContextFixedDescription:
+ "تستهلك الحدود الأصغر ذاكرة أقل. تحتاج التسجيلات التي تتجاوز الحد إلى حد أعلى أو الوضع التلقائي. ينطبق على Qwen3-ASR في «الصوت» و«تفريغ نصي».",
+ sttContextTokens: "{count} توكن",
sttDeviceAuto: "وحدة معالجة الرسومات عند توفرها",
sttDeviceCpu: "ذاكرة المعالج",
sttDeviceAutoDescription:
diff --git a/studio/frontend/src/i18n/locales/cs.ts b/studio/frontend/src/i18n/locales/cs.ts
index b0ddd210535..90cd157a369 100644
--- a/studio/frontend/src/i18n/locales/cs.ts
+++ b/studio/frontend/src/i18n/locales/cs.ts
@@ -1859,6 +1859,13 @@ export const cs = {
sttQuantDescription:
"Vyberte nebo vyhledejte model STT, který se má spouštět místně, a potom jeho kvantizaci.",
sttDeviceLabel: "Načíst do",
+ sttContextLabel: "Kontext hlasu",
+ sttContextAuto: "Automaticky (doporučeno)",
+ sttContextAutoDescription:
+ "Přizpůsobí se každé nahrávce a pro delší zvuk použije více paměti. Starší běhová prostředí mohou ke snížení paměti potřebovat pevnou velikost. Platí pro Qwen3-ASR v sekcích Hlas a Přepis.",
+ sttContextFixedDescription:
+ "Menší limity používají méně paměti. Nahrávky, které se nevejdou, potřebují vyšší limit nebo Automaticky. Platí pro Qwen3-ASR v sekcích Hlas a Přepis.",
+ sttContextTokens: "tokeny: {count}",
sttDeviceAuto: "GPU, pokud je k dispozici",
sttDeviceCpu: "RAM procesoru",
sttDeviceAutoDescription:
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 2a0b4d9ce6f..9f1cb20d1e3 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -1690,6 +1690,13 @@ export const de = {
sttQuantDescription:
"Wählen oder suchen Sie ein STT-Modell für die lokale Ausführung, dann seine Quantisierung.",
sttDeviceLabel: "Laden in",
+ sttContextLabel: "Sprachkontext",
+ sttContextAuto: "Auto (empfohlen)",
+ sttContextAutoDescription:
+ "Passt sich jeder Aufnahme an und verwendet mehr Speicher für längere Audiodateien. Bei älteren Laufzeitumgebungen kann eine feste Größe nötig sein, um den Speicherverbrauch zu senken. Gilt für Qwen3-ASR unter „Sprachfunktionen“ und „Transkribieren“.",
+ sttContextFixedDescription:
+ "Kleinere Grenzen benötigen weniger Speicher. Für Aufnahmen, die nicht hineinpassen, ist eine höhere Grenze oder Auto nötig. Gilt für Qwen3-ASR unter „Sprachfunktionen“ und „Transkribieren“.",
+ sttContextTokens: "{count} Token",
sttDeviceAuto: "GPU, wenn verfügbar",
sttDeviceCpu: "CPU-RAM",
sttDeviceAutoDescription:
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 6dccc9d941f..61fc02c810c 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -1693,6 +1693,13 @@ export const en = {
sttQuantDescription:
"Choose or search a STT model to run locally, then its quantization.",
sttDeviceLabel: "Load into",
+ sttContextLabel: "Voice context",
+ sttContextAuto: "Auto (recommended)",
+ sttContextAutoDescription:
+ "Fits each recording, with more memory for longer audio. Older runtimes may need a fixed size to reduce memory. Applies to Qwen3-ASR in Voice and Transcribe.",
+ sttContextFixedDescription:
+ "Smaller limits use less memory. Recordings that do not fit need a higher limit or Auto. Applies to Qwen3-ASR in Voice and Transcribe.",
+ sttContextTokens: "{count} tokens",
sttDeviceAuto: "GPU when available",
sttDeviceCpu: "CPU RAM",
sttDeviceAutoDescription:
diff --git a/studio/frontend/src/i18n/locales/es-419.ts b/studio/frontend/src/i18n/locales/es-419.ts
index 53f44957247..b9a82a4284e 100644
--- a/studio/frontend/src/i18n/locales/es-419.ts
+++ b/studio/frontend/src/i18n/locales/es-419.ts
@@ -1870,6 +1870,13 @@ export const es419 = {
sttQuantDescription:
"Elige o busca un modelo STT para ejecutarlo de forma local y luego su cuantización.",
sttDeviceLabel: "Cargar en",
+ sttContextLabel: "Contexto de voz",
+ sttContextAuto: "Automático (recomendado)",
+ sttContextAutoDescription:
+ "Se ajusta a cada grabación y usa más memoria para audios más largos. Los entornos de ejecución más antiguos pueden necesitar un tamaño fijo para reducir la memoria. Se aplica a Qwen3-ASR en Voz y Transcribir.",
+ sttContextFixedDescription:
+ "Los límites más pequeños usan menos memoria. Las grabaciones que no caben necesitan un límite mayor o Automático. Se aplica a Qwen3-ASR en Voz y Transcribir.",
+ sttContextTokens: "{count} tokens",
sttDeviceAuto: "GPU cuando esté disponible",
sttDeviceCpu: "RAM de la CPU",
sttDeviceAutoDescription:
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 64f47f7a032..24b3cb76632 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -1689,6 +1689,13 @@ export const es = {
sttQuantDescription:
"Elige o busca un modelo STT para ejecutarlo en local y luego su cuantización.",
sttDeviceLabel: "Cargar en",
+ sttContextLabel: "Contexto de voz",
+ sttContextAuto: "Auto (recomendado)",
+ sttContextAutoDescription:
+ "Se adapta a cada grabación y usa más memoria para audios más largos. Los entornos de ejecución antiguos pueden necesitar un tamaño fijo para reducir el uso de memoria. Se aplica a Qwen3-ASR en Voz y Transcribir.",
+ sttContextFixedDescription:
+ "Los límites más pequeños usan menos memoria. Las grabaciones que no quepan necesitan un límite mayor o Auto. Se aplica a Qwen3-ASR en Voz y Transcribir.",
+ sttContextTokens: "{count} tokens",
sttDeviceAuto: "GPU cuando esté disponible",
sttDeviceCpu: "RAM de la CPU",
sttDeviceAutoDescription:
diff --git a/studio/frontend/src/i18n/locales/fa.ts b/studio/frontend/src/i18n/locales/fa.ts
index f065fb5ca33..86a286a6895 100644
--- a/studio/frontend/src/i18n/locales/fa.ts
+++ b/studio/frontend/src/i18n/locales/fa.ts
@@ -1844,6 +1844,13 @@ export const fa = {
sttQuantDescription:
"یک مدل STT را برای اجرای محلی انتخاب یا جستجو کنید، سپس کوانتیزه‌سازی آن را.",
sttDeviceLabel: "بارگذاری در",
+ sttContextLabel: "زمینهٔ صدا",
+ sttContextAuto: "خودکار (پیشنهادی)",
+ sttContextAutoDescription:
+ "با هر ضبط تنظیم می‌شود و برای صدای طولانی‌تر حافظهٔ بیشتری مصرف می‌کند. محیط‌های اجرای قدیمی‌تر ممکن است برای کاهش حافظه به اندازهٔ ثابت نیاز داشته باشند. برای Qwen3-ASR در صدا و رونویسی اعمال می‌شود.",
+ sttContextFixedDescription:
+ "محدودیت‌های کوچک‌تر حافظهٔ کمتری مصرف می‌کنند. ضبط‌هایی که جا نمی‌شوند به محدودیت بالاتر یا خودکار نیاز دارند. برای Qwen3-ASR در صدا و رونویسی اعمال می‌شود.",
+ sttContextTokens: "{count} توکن",
sttDeviceAuto: "GPU در صورت وجود",
sttDeviceCpu: "RAM پردازنده (CPU)",
sttDeviceAutoDescription:
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 9e90ed90be4..1131a626847 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -1690,6 +1690,13 @@ export const fr = {
sttQuantDescription:
"Choisissez ou recherchez un modèle STT à exécuter en local, puis sa quantification.",
sttDeviceLabel: "Charger dans",
+ sttContextLabel: "Contexte vocal",
+ sttContextAuto: "Auto (recommandé)",
+ sttContextAutoDescription:
+ "S’adapte à chaque enregistrement et utilise davantage de mémoire pour les fichiers audio plus longs. Les anciens environnements d’exécution peuvent nécessiter une taille fixe pour réduire l’utilisation de mémoire. S’applique à Qwen3-ASR dans Voix et Transcrire.",
+ sttContextFixedDescription:
+ "Les limites plus petites utilisent moins de mémoire. Les enregistrements qui dépassent la limite nécessitent une limite plus élevée ou le mode Auto. S’applique à Qwen3-ASR dans Voix et Transcrire.",
+ sttContextTokens: "{count} tokens",
sttDeviceAuto: "GPU si disponible",
sttDeviceCpu: "RAM du CPU",
sttDeviceAutoDescription:
diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.ts
index b005c2373ff..84675c1f3b3 100644
--- a/studio/frontend/src/i18n/locales/he.ts
+++ b/studio/frontend/src/i18n/locales/he.ts
@@ -1753,6 +1753,13 @@ export const he = {
sttQuantDescription:
"בחר או חפש מודל STT להרצה מקומית, ואז את הקוונטיזציה שלו.",
sttDeviceLabel: "טען אל",
+ sttContextLabel: "הקשר קולי",
+ sttContextAuto: "אוטומטי (מומלץ)",
+ sttContextAutoDescription:
+ "מתאים את גודל ההקשר לכל הקלטה, ומשתמש ביותר זיכרון להקלטות ארוכות יותר. בסביבות ריצה ישנות ייתכן שיהיה צורך בגודל קבוע כדי להפחית את השימוש בזיכרון. חל על Qwen3-ASR ב״קול״ וב״תמלול״.",
+ sttContextFixedDescription:
+ "מגבלות קטנות יותר צורכות פחות זיכרון. להקלטות שחורגות מהמגבלה יש לבחור מגבלה גבוהה יותר או מצב אוטומטי. חל על Qwen3-ASR ב״קול״ וב״תמלול״.",
+ sttContextTokens: "{count} טוקנים",
sttDeviceAuto: "GPU כאשר זמין",
sttDeviceCpu: "זיכרון RAM של ה-CPU",
sttDeviceAutoDescription: "השתמש ב-GPU כאשר קיים, וב-CPU במקרים אחרים.",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index d68db33ec53..b70510fed7e 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -1689,6 +1689,13 @@ export const hi = {
sttQuantDescription:
"लोकली चलाने के लिए STT मॉडल चुनें या खोजें, फिर उसका क्वांटाइज़ेशन चुनें।",
sttDeviceLabel: "इसमें लोड करें",
+ sttContextLabel: "आवज क कनक",
+ sttContextAuto: "सचलत (अनशसत)",
+ sttContextAutoDescription:
+ "हर रकरग क अनसर आकर समयजत करत ह। लब ऑडय क लए अधक ममर इसमल हत ह। परन रनटइम म ममर उपयग घटन क लए आकर तय करन पड सकत ह। “आवज” और “टसकइब” म Qwen3-ASR पर लग हत ह।",
+ sttContextFixedDescription:
+ "छट सम कम ममर इसमल करत ह। सम म न समन वल रकरग क लए सम बढए य “सचलत” चन। “आवज” और “टसकइब” म Qwen3-ASR पर लग हत ह।",
+ sttContextTokens: "{count} टकन",
sttDeviceAuto: "उपलब्ध होने पर GPU",
sttDeviceCpu: "CPU RAM",
sttDeviceAutoDescription:
diff --git a/studio/frontend/src/i18n/locales/id.ts b/studio/frontend/src/i18n/locales/id.ts
index 62d575f3892..d3ec1b6718c 100644
--- a/studio/frontend/src/i18n/locales/id.ts
+++ b/studio/frontend/src/i18n/locales/id.ts
@@ -1855,6 +1855,13 @@ export const id = {
sttQuantDescription:
"Pilih atau cari model STT untuk dijalankan secara lokal, lalu kuantisasinya.",
sttDeviceLabel: "Muat ke",
+ sttContextLabel: "Konteks suara",
+ sttContextAuto: "Otomatis (disarankan)",
+ sttContextAutoDescription:
+ "Menyesuaikan dengan setiap rekaman, dengan lebih banyak memori untuk audio yang lebih panjang. Runtime lama mungkin memerlukan ukuran tetap untuk mengurangi memori. Berlaku untuk Qwen3-ASR di Suara dan Transkripsikan.",
+ sttContextFixedDescription:
+ "Batas yang lebih kecil menggunakan lebih sedikit memori. Rekaman yang tidak muat memerlukan batas lebih tinggi atau Otomatis. Berlaku untuk Qwen3-ASR di Suara dan Transkripsikan.",
+ sttContextTokens: "{count} token",
sttDeviceAuto: "GPU jika tersedia",
sttDeviceCpu: "RAM CPU",
sttDeviceAutoDescription: "Gunakan GPU jika ada, dan CPU jika tidak.",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 384ce70855f..35029ef3165 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -1588,6 +1588,13 @@ export const it = {
sttQuantDescription:
"Scegli o cerca un modello STT da eseguire in locale, poi la sua quantizzazione.",
sttDeviceLabel: "Carica in",
+ sttContextLabel: "Contesto vocale",
+ sttContextAuto: "Auto (consigliato)",
+ sttContextAutoDescription:
+ "Si adatta a ogni registrazione, usando più memoria per gli audio più lunghi. Gli ambienti di esecuzione meno recenti potrebbero richiedere una dimensione fissa per ridurre l’uso della memoria. Si applica a Qwen3-ASR in Voce e Trascrivi.",
+ sttContextFixedDescription:
+ "Limiti più piccoli usano meno memoria. Le registrazioni che superano il limite richiedono un limite più alto o la modalità Auto. Si applica a Qwen3-ASR in Voce e Trascrivi.",
+ sttContextTokens: "{count} token",
sttDeviceAuto: "GPU quando disponibile",
sttDeviceCpu: "RAM della CPU",
sttDeviceAutoDescription:
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 3b769475eaf..004c71576ad 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -1688,6 +1688,13 @@ export const ja = {
sttQuantDescription:
"ローカルで実行する STT モデルを選択または検索し、量子化を選びます。",
sttDeviceLabel: "読み込み先",
+ sttContextLabel: "音声コンテキスト",
+ sttContextAuto: "自動(推奨)",
+ sttContextAutoDescription:
+ "録音ごとにコンテキスト長を調整します。長い音声ほど多くのメモリを使用します。古いランタイムでは、メモリ使用量を減らすために固定サイズの指定が必要な場合があります。「音声」と「文字起こし」の Qwen3-ASR に適用されます。",
+ sttContextFixedDescription:
+ "上限が小さいほどメモリ使用量を抑えられます。録音が上限に収まらない場合は、上限を増やすか「自動」を選択してください。「音声」と「文字起こし」の Qwen3-ASR に適用されます。",
+ sttContextTokens: "{count} トークン",
sttDeviceAuto: "GPU(利用できる場合)",
sttDeviceCpu: "CPU メモリ",
sttDeviceAutoDescription:
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 5db75ddcb61..382fd19dbec 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -1685,6 +1685,13 @@ export const ko = {
sttQuantDescription:
"로컬에서 실행할 STT 모델을 선택하거나 검색한 다음 양자화를 고르세요.",
sttDeviceLabel: "로드 위치",
+ sttContextLabel: "음성 컨텍스트",
+ sttContextAuto: "자동 (권장)",
+ sttContextAutoDescription:
+ "녹음마다 컨텍스트 크기를 맞추며, 오디오가 길수록 더 많은 메모리를 사용합니다. 이전 런타임에서는 메모리 사용량을 줄이려면 고정 크기를 지정해야 할 수 있습니다. ‘음성’과 ‘받아쓰기’에서 사용하는 Qwen3-ASR에 적용됩니다.",
+ sttContextFixedDescription:
+ "한도가 작을수록 메모리를 적게 사용합니다. 한도를 초과하는 녹음은 한도를 높이거나 ‘자동’을 선택해야 합니다. ‘음성’과 ‘받아쓰기’에서 사용하는 Qwen3-ASR에 적용됩니다.",
+ sttContextTokens: "{count} 토큰",
sttDeviceAuto: "GPU(사용 가능할 때)",
sttDeviceCpu: "CPU RAM",
sttDeviceAutoDescription:
diff --git a/studio/frontend/src/i18n/locales/nl.ts b/studio/frontend/src/i18n/locales/nl.ts
index 442d6033b3b..5d7a7f24c83 100644
--- a/studio/frontend/src/i18n/locales/nl.ts
+++ b/studio/frontend/src/i18n/locales/nl.ts
@@ -1876,6 +1876,13 @@ export const nl = {
sttQuantDescription:
"Kies of zoek een STT-model om lokaal uit te voeren en kies daarna de kwantisatie.",
sttDeviceLabel: "Laden in",
+ sttContextLabel: "Spraakcontext",
+ sttContextAuto: "Automatisch (aanbevolen)",
+ sttContextAutoDescription:
+ "Past zich aan elke opname aan en gebruikt meer geheugen voor langere audio. Oudere runtimes hebben mogelijk een vaste grootte nodig om geheugen te besparen. Geldt voor Qwen3-ASR in Spraak en Transcriberen.",
+ sttContextFixedDescription:
+ "Kleinere limieten gebruiken minder geheugen. Opnamen die niet passen hebben een hogere limiet of Automatisch nodig. Geldt voor Qwen3-ASR in Spraak en Transcriberen.",
+ sttContextTokens: "{count} tokens",
sttDeviceAuto: "GPU indien beschikbaar",
sttDeviceCpu: "CPU-RAM",
sttDeviceAutoDescription:
diff --git a/studio/frontend/src/i18n/locales/pl.ts b/studio/frontend/src/i18n/locales/pl.ts
index 34b9977fed3..031d5bdac25 100644
--- a/studio/frontend/src/i18n/locales/pl.ts
+++ b/studio/frontend/src/i18n/locales/pl.ts
@@ -1870,6 +1870,13 @@ export const pl = {
sttQuantDescription:
"Wybierz lub wyszukaj model STT do uruchomienia lokalnie, a następnie jego kwantyzację.",
sttDeviceLabel: "Wczytaj do",
+ sttContextLabel: "Kontekst głosu",
+ sttContextAuto: "Automatycznie (zalecane)",
+ sttContextAutoDescription:
+ "Dopasowuje się do każdego nagrania, używając więcej pamięci przy dłuższym dźwięku. Starsze środowiska uruchomieniowe mogą wymagać stałego rozmiaru, aby ograniczyć użycie pamięci. Dotyczy Qwen3-ASR w sekcjach Głos i Transkrypcja.",
+ sttContextFixedDescription:
+ "Mniejsze limity zużywają mniej pamięci. Nagrania, które się nie mieszczą, wymagają wyższego limitu lub trybu Automatycznie. Dotyczy Qwen3-ASR w sekcjach Głos i Transkrypcja.",
+ sttContextTokens: "tokeny: {count}",
sttDeviceAuto: "GPU, gdy jest dostępny",
sttDeviceCpu: "RAM procesora CPU",
sttDeviceAutoDescription:
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 15216135df9..a5510828682 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -1688,6 +1688,13 @@ export const ptBR = {
sttQuantDescription:
"Escolha ou busque um modelo STT para executar localmente e depois sua quantização.",
sttDeviceLabel: "Carregar em",
+ sttContextLabel: "Contexto de voz",
+ sttContextAuto: "Auto (recomendado)",
+ sttContextAutoDescription:
+ "Adapta-se a cada gravação, usando mais memória para áudios mais longos. Ambientes de execução antigos podem precisar de um tamanho fixo para reduzir o uso de memória. Aplica-se ao Qwen3-ASR em Voz e Transcrever.",
+ sttContextFixedDescription:
+ "Limites menores usam menos memória. Gravações que ultrapassam o limite precisam de um limite maior ou do modo Auto. Aplica-se ao Qwen3-ASR em Voz e Transcrever.",
+ sttContextTokens: "{count} tokens",
sttDeviceAuto: "GPU quando disponível",
sttDeviceCpu: "RAM da CPU",
sttDeviceAutoDescription:
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index e061a3daff4..a42f1ea092d 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -1688,6 +1688,13 @@ export const ru = {
sttQuantDescription:
"Выберите или найдите модель STT для локального запуска, затем её квантизацию.",
sttDeviceLabel: "Загружать в",
+ sttContextLabel: "Голосовой контекст",
+ sttContextAuto: "Авто (рекомендуется)",
+ sttContextAutoDescription:
+ "Подбирает размер для каждой записи: чем длиннее аудио, тем больше памяти требуется. В старых версиях среды выполнения для снижения расхода памяти может потребоваться фиксированный размер. Применяется к Qwen3-ASR в разделах «Голос» и «Транскрибировать».",
+ sttContextFixedDescription:
+ "Чем меньше лимит, тем меньше расход памяти. Для записей, которые не укладываются в лимит, увеличьте его или выберите «Авто». Применяется к Qwen3-ASR в разделах «Голос» и «Транскрибировать».",
+ sttContextTokens: "Токенов: {count}",
sttDeviceAuto: "GPU, если доступен",
sttDeviceCpu: "ОЗУ процессора",
sttDeviceAutoDescription:
diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.ts
index 5be43cb3188..57574b9e1dc 100644
--- a/studio/frontend/src/i18n/locales/sv.ts
+++ b/studio/frontend/src/i18n/locales/sv.ts
@@ -1791,6 +1791,13 @@ export const sv = {
sttQuantDescription:
"Välj eller sök efter en STT-modell som ska köras lokalt och sedan dess kvantisering.",
sttDeviceLabel: "Läs in i",
+ sttContextLabel: "Röstkontext",
+ sttContextAuto: "Auto (rekommenderas)",
+ sttContextAutoDescription:
+ "Anpassas till varje inspelning och använder mer minne för längre ljud. Äldre körmiljöer kan behöva en fast storlek för att minska minnesanvändningen. Gäller Qwen3-ASR i Röst och Transkribera.",
+ sttContextFixedDescription:
+ "Lägre gränser använder mindre minne. Inspelningar som inte ryms behöver en högre gräns eller Auto. Gäller Qwen3-ASR i Röst och Transkribera.",
+ sttContextTokens: "{count} token",
sttDeviceAuto: "GPU när tillgänglig",
sttDeviceCpu: "CPU-RAM",
sttDeviceAutoDescription: "Använd GPU:n om det finns en, annars CPU:n.",
diff --git a/studio/frontend/src/i18n/locales/th.ts b/studio/frontend/src/i18n/locales/th.ts
index 6506a196d62..75ed6f51117 100644
--- a/studio/frontend/src/i18n/locales/th.ts
+++ b/studio/frontend/src/i18n/locales/th.ts
@@ -1771,6 +1771,13 @@ export const th = {
sttQuantDescription:
"เลือกหรือค้นหาโมเดล STT เพื่อรันภายในเครื่อง แล้วเลือกการควอนไทซ์",
sttDeviceLabel: "โหลดลงใน",
+ sttContextLabel: "บริบทเสียง",
+ sttContextAuto: "อัตโนมัติ (แนะนำ)",
+ sttContextAutoDescription:
+ "ปรับตามการบันทึกแต่ละครั้ง โดยใช้หน่วยความจำมากขึ้นสำหรับเสียงที่ยาวขึ้น รันไทม์รุ่นเก่าอาจต้องใช้ขนาดคงที่เพื่อลดการใช้หน่วยความจำ ใช้กับ Qwen3-ASR ในเสียงพูดและถอดเสียง",
+ sttContextFixedDescription:
+ "ขีดจำกัดที่เล็กลงจะใช้หน่วยความจำน้อยลง การบันทึกที่ใส่ไม่พอต้องใช้ขีดจำกัดที่สูงขึ้นหรืออัตโนมัติ ใช้กับ Qwen3-ASR ในเสียงพูดและถอดเสียง",
+ sttContextTokens: "{count} โทเค็น",
sttDeviceAuto: "GPU เมื่อพร้อมใช้งาน",
sttDeviceCpu: "RAM ของ CPU",
sttDeviceAutoDescription: "ใช้ GPU เมื่อมี หากไม่มีให้ใช้ CPU",
diff --git a/studio/frontend/src/i18n/locales/tr.ts b/studio/frontend/src/i18n/locales/tr.ts
index 82a3448b143..3bad8ca43f4 100644
--- a/studio/frontend/src/i18n/locales/tr.ts
+++ b/studio/frontend/src/i18n/locales/tr.ts
@@ -1850,6 +1850,13 @@ export const tr = {
sttQuantDescription:
"Yerel olarak çalıştırılacak bir STT modeli seçin veya arayın, ardından nicelemesini seçin.",
sttDeviceLabel: "Yükleneceği yer",
+ sttContextLabel: "Ses bağlamı",
+ sttContextAuto: "Otomatik (önerilen)",
+ sttContextAutoDescription:
+ "Her kayda uyum sağlar, daha uzun seslerde daha fazla bellek kullanır. Eski çalışma ortamları belleği azaltmak için sabit bir boyut gerektirebilir. Ses ve Yazıya dök bölümlerindeki Qwen3-ASR için geçerlidir.",
+ sttContextFixedDescription:
+ "Daha küçük sınırlar daha az bellek kullanır. Sığmayan kayıtlar daha yüksek bir sınır veya Otomatik gerektirir. Ses ve Yazıya dök bölümlerindeki Qwen3-ASR için geçerlidir.",
+ sttContextTokens: "{count} token",
sttDeviceAuto: "Varsa GPU",
sttDeviceCpu: "CPU RAM",
sttDeviceAutoDescription: "Varsa GPU'yu, yoksa CPU'yu kullanın.",
diff --git a/studio/frontend/src/i18n/locales/uk.ts b/studio/frontend/src/i18n/locales/uk.ts
index 89d600801c1..ae479bb6bc2 100644
--- a/studio/frontend/src/i18n/locales/uk.ts
+++ b/studio/frontend/src/i18n/locales/uk.ts
@@ -1865,6 +1865,13 @@ export const uk = {
sttQuantDescription:
"Виберіть або знайдіть модель STT для локального запуску, а потім її квантування.",
sttDeviceLabel: "Завантажувати в",
+ sttContextLabel: "Контекст голосу",
+ sttContextAuto: "Авто (рекомендовано)",
+ sttContextAutoDescription:
+ "Підлаштовується під кожен запис і використовує більше пам'яті для довшого аудіо. Старішим середовищам виконання може знадобитися фіксований розмір, щоб зменшити використання пам'яті. Стосується Qwen3-ASR у розділах Голос і Транскрибувати.",
+ sttContextFixedDescription:
+ "Менші ліміти використовують менше пам'яті. Записам, які не вміщуються, потрібен вищий ліміт або Авто. Стосується Qwen3-ASR у розділах Голос і Транскрибувати.",
+ sttContextTokens: "токени: {count}",
sttDeviceAuto: "GPU, якщо доступний",
sttDeviceCpu: "RAM CPU",
sttDeviceAutoDescription:
diff --git a/studio/frontend/src/i18n/locales/vi.ts b/studio/frontend/src/i18n/locales/vi.ts
index 41f54c9c15c..2d4177b32b9 100644
--- a/studio/frontend/src/i18n/locales/vi.ts
+++ b/studio/frontend/src/i18n/locales/vi.ts
@@ -1860,6 +1860,13 @@ export const vi = {
sttQuantDescription:
"Chọn hoặc tìm kiếm một mô hình STT để chạy cục bộ, sau đó chọn mức lượng tử hóa.",
sttDeviceLabel: "Nạp vào",
+ sttContextLabel: "Ngữ cảnh giọng nói",
+ sttContextAuto: "Tự động (khuyên dùng)",
+ sttContextAutoDescription:
+ "Tự điều chỉnh theo từng bản ghi, dùng nhiều bộ nhớ hơn cho âm thanh dài hơn. Các runtime cũ có thể cần kích thước cố định để giảm bộ nhớ. Áp dụng cho Qwen3-ASR trong Giọng nói và Chép lời.",
+ sttContextFixedDescription:
+ "Giới hạn nhỏ hơn dùng ít bộ nhớ hơn. Bản ghi không vừa cần giới hạn cao hơn hoặc Tự động. Áp dụng cho Qwen3-ASR trong Giọng nói và Chép lời.",
+ sttContextTokens: "{count} token",
sttDeviceAuto: "GPU khi có sẵn",
sttDeviceCpu: "RAM của CPU",
sttDeviceAutoDescription: "Dùng GPU nếu có, nếu không thì dùng CPU.",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index bbe0e3ade89..fbd02e46bf9 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -1682,6 +1682,13 @@ export const zhCN = {
sttQuantDescription:
"选择或搜索要在本地运行的 STT 模型,再选择其量化。",
sttDeviceLabel: "加载到",
+ sttContextLabel: "语音上下文",
+ sttContextAuto: "自动(推荐)",
+ sttContextAutoDescription:
+ "根据每段录音调整大小,音频越长,使用的内存越多。旧版运行时可能需要设置固定大小才能减少内存占用。适用于“语音”和“转写”中的 Qwen3-ASR。",
+ sttContextFixedDescription:
+ "上限越小,内存占用越少。如果录音超出上限,请提高上限或选择“自动”。适用于“语音”和“转写”中的 Qwen3-ASR。",
+ sttContextTokens: "{count} 个 token",
sttDeviceAuto: "有 GPU 时使用 GPU",
sttDeviceCpu: "CPU 内存",
sttDeviceAutoDescription: "有 GPU 时使用 GPU,否则使用 CPU。",
diff --git a/studio/frontend/src/i18n/locales/zh-TW.ts b/studio/frontend/src/i18n/locales/zh-TW.ts
index 265bbb45d68..b17e34dfe89 100644
--- a/studio/frontend/src/i18n/locales/zh-TW.ts
+++ b/studio/frontend/src/i18n/locales/zh-TW.ts
@@ -1763,6 +1763,13 @@ export const zhTW = {
sttQuantDescription:
"選擇或搜尋要在本機執行的 STT 模型,再選擇其量化版本。",
sttDeviceLabel: "載入至",
+ sttContextLabel: "語音上下文",
+ sttContextAuto: "自動(建議)",
+ sttContextAutoDescription:
+ "依每段錄音調整,較長的音訊會使用較多記憶體。較舊的執行環境可能需要固定大小以減少記憶體用量。適用於「語音」與「轉錄」中的 Qwen3-ASR。",
+ sttContextFixedDescription:
+ "較小的上限使用較少記憶體。無法容納的錄音需要較高的上限或自動。適用於「語音」與「轉錄」中的 Qwen3-ASR。",
+ sttContextTokens: "{count} 個 token",
sttDeviceAuto: "有 GPU 時使用 GPU",
sttDeviceCpu: "CPU RAM",
sttDeviceAutoDescription: "有 GPU 時使用 GPU,否則使用 CPU。",
diff --git a/studio/frontend/tests/voice-settings-storage-sync.test.ts b/studio/frontend/tests/voice-settings-storage-sync.test.ts
index 987d2e463dc..ac870f7b001 100644
--- a/studio/frontend/tests/voice-settings-storage-sync.test.ts
+++ b/studio/frontend/tests/voice-settings-storage-sync.test.ts
@@ -7,6 +7,7 @@ import * as zustand from "zustand";
import * as zustandMiddleware from "zustand/middleware";
import * as audioCppCatalog from "../src/features/audio/audio-cpp-catalog.ts";
+import * as sttContext from "../src/features/settings/stores/stt-context.ts";
import * as sttModelCatalog from "../src/features/settings/stores/stt-model-catalog.ts";
import { installLocalStorageFake } from "./helpers/kit.ts";
import { loadWithStubs } from "./helpers/module-stubs.ts";
@@ -24,6 +25,7 @@ const { useVoiceSettingsStore } = loadWithStubs<
zustand,
"zustand/middleware": zustandMiddleware,
"./stt-model-catalog": sttModelCatalog,
+ "./stt-context": sttContext,
"../api/stt-device": { syncSttDevicePreference: () => undefined },
},
);
diff --git a/studio/frontend/tests/voice-stt-context.test.ts b/studio/frontend/tests/voice-stt-context.test.ts
new file mode 100644
index 00000000000..215f24c51ee
--- /dev/null
+++ b/studio/frontend/tests/voice-stt-context.test.ts
@@ -0,0 +1,329 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { stripTypeScriptTypes } from "node:module";
+import test from "node:test";
+
+import type { transcribeAudioInput } from "../src/features/audio/api.ts";
+import { sourceRefOf } from "../src/features/audio/audio-run-request.ts";
+import type { useReferenceTranscribe } from "../src/features/audio/hooks/use-reference-transcribe.ts";
+import {
+ sttEngineForRepoId,
+ sttSidecarKeyFor,
+} from "../src/features/audio/stt-artifacts.ts";
+import type { transcribeSourceWithProgress } from "../src/features/audio/transcribe-api.ts";
+import { readTranscriptStream } from "../src/features/audio/transcript-stream.ts";
+import { sttRequestError } from "../src/features/chat/adapters/stt-errors.ts";
+import type {
+ loadSttModel,
+ transcribeAudioBlob,
+} from "../src/features/chat/adapters/studio-model-dictation-adapter.ts";
+import { completeChatAudioUpload } from "../src/features/chat/utils/chat-audio-upload.ts";
+
+import {
+ DEFAULT_STT_CONTEXT_LENGTH,
+ STT_CONTEXT_LENGTHS,
+ normalizeSttContextLength,
+ sttContextBody,
+} from "../src/features/settings/stores/stt-context.ts";
+import {
+ installLocalStorageFake,
+ readSrc,
+ registerBundlerResolver,
+} from "./helpers/kit.ts";
+import { loadWithStubs } from "./helpers/module-stubs.ts";
+
+registerBundlerResolver();
+const { store: storage } = installLocalStorageFake();
+const { useVoiceSettingsStore } = await import(
+ "../src/features/settings/stores/voice-settings-store.ts"
+);
+
+test("old or invalid preferences use Auto; valid fixed limits survive", () => {
+ assert.equal(DEFAULT_STT_CONTEXT_LENGTH, 0);
+ for (const value of [
+ undefined,
+ null,
+ "4096",
+ Number.NaN,
+ Number.POSITIVE_INFINITY,
+ -1,
+ 1,
+ 1023,
+ 65537,
+ 4096.5,
+ 5000,
+ ]) {
+ assert.equal(normalizeSttContextLength(value), 0);
+ }
+ for (const value of [0, ...STT_CONTEXT_LENGTHS, 5120]) {
+ assert.equal(normalizeSttContextLength(value), value);
+ }
+});
+
+test("only curated Qwen3-ASR on mtmd receives a context preference", () => {
+ for (const model of ["qwen3-asr-0.6b", "qwen3-asr-1.7b"]) {
+ assert.deepEqual(sttContextBody(model, "mtmd", 0), { context_length: 0 });
+ assert.deepEqual(sttContextBody(model, "mtmd", 4096), {
+ context_length: 4096,
+ });
+ for (const engine of ["audiocpp", "gguf", "transformers", ""]) {
+ assert.deepEqual(sttContextBody(model, engine, 4096), {});
+ }
+ }
+ assert.deepEqual(sttContextBody("small", "mtmd", 4096), {});
+ assert.deepEqual(sttContextBody("owner/custom-model", "mtmd", 4096), {});
+});
+
+test("existing saves default to Auto and a fixed choice persists across hydration", async () => {
+ storage.set(
+ "unsloth_voice_settings",
+ JSON.stringify({
+ version: 1,
+ state: { sttModel: "qwen3-asr-0.6b", sttDevice: "cpu" },
+ }),
+ );
+ await useVoiceSettingsStore.persist.rehydrate();
+ assert.equal(useVoiceSettingsStore.getState().sttContextLength, 0);
+ assert.equal(useVoiceSettingsStore.getState().sttDevice, "cpu");
+
+ useVoiceSettingsStore.getState().setSttContextLength(8192);
+ const saved = storage.get("unsloth_voice_settings");
+ assert.ok(saved);
+ assert.equal(JSON.parse(saved).state.sttContextLength, 8192);
+ await useVoiceSettingsStore.persist.rehydrate();
+ assert.equal(useVoiceSettingsStore.getState().sttContextLength, 8192);
+ useVoiceSettingsStore.getState().setSttContextLength(0);
+ await useVoiceSettingsStore.persist.rehydrate();
+ assert.equal(useVoiceSettingsStore.getState().sttContextLength, 0);
+});
+
+// Run the actual request builders with a fake transport, avoiding the browser runtime
+// imported by the full dictation adapter. This checks the emitted requests, including Auto=0.
+function requestFunction<T>(
+ path: string,
+ name: string,
+ next: string,
+ scope: Record<string, unknown>,
+): T {
+ const source = readSrc(path);
+ const start = source.search(
+ new RegExp(`export (?:async )?function ${name}\\(`),
+ );
+ const end = source.indexOf(next, start);
+ assert.ok(start >= 0 && end > start);
+ const fn = source.slice(start, end).replace(/^export /, "");
+ return new Function(
+ ...Object.keys(scope),
+ `${stripTypeScriptTypes(fn)}\nreturn ${name};`,
+ )(...Object.values(scope)) as T;
+}
+
+test("loads, microphone/upload audio, sources and reference clips send the saved context", async () => {
+ const requests: { url: string; init: RequestInit }[] = [];
+ const scope = {
+ useVoiceSettingsStore,
+ sttContextBody,
+ authFetch: async (url: string, init: RequestInit) => {
+ requests.push({ url, init });
+ return new Response(JSON.stringify({ text: "hello" }));
+ },
+ sttEngineFor: (model: string) => (model === "small" ? "gguf" : "mtmd"),
+ resolveModelDictationLanguage: () => undefined,
+ sttModelVariant: () => null,
+ sttVariantBody: () => ({}),
+ queueSttLifecycle: (fn: () => Promise<void>) => fn(),
+ withModelLoadNotice: (
+ _kind: string,
+ _model: string,
+ fn: () => Promise<void>,
+ ) => fn(),
+ JSON_HEADERS: { "Content-Type": "application/json" },
+ readTranscriptStream: async () => ({ text: "hello" }),
+ parseAudioJson: async (response: Response) => response.json(),
+ transcribeUrl: () => "/api/inference/audio/inputs/input-1/transcribe",
+ };
+ const adapter = "features/chat/adapters/studio-model-dictation-adapter.ts";
+ const load = requestFunction<typeof loadSttModel>(
+ adapter,
+ "loadSttModel",
+ "export async function startSttDownload",
+ scope,
+ );
+ const raw = requestFunction<typeof transcribeAudioBlob>(
+ adapter,
+ "transcribeAudioBlob",
+ "export interface SttDownloadStatus",
+ scope,
+ );
+ const source = requestFunction<typeof transcribeSourceWithProgress>(
+ "features/audio/transcribe-api.ts",
+ "transcribeSourceWithProgress",
+ "export function fetchSttCapabilities",
+ scope,
+ );
+ const reference = requestFunction<typeof transcribeAudioInput>(
+ "features/audio/api.ts",
+ "transcribeAudioInput",
+ "export interface AudioRunResponse",
+ scope,
+ );
+ const { useReferenceTranscribe: referenceHook } = loadWithStubs<{
+ useReferenceTranscribe: typeof useReferenceTranscribe;
+ }>(
+ new URL(
+ "../src/features/audio/hooks/use-reference-transcribe.ts",
+ import.meta.url,
+ ),
+ {
+ "@/features/chat/adapters/studio-model-dictation-adapter": {
+ sttEngineFor: scope.sttEngineFor,
+ },
+ "@/features/settings": {
+ useVoiceSettingsStore,
+ withSttVariant: (model: string) => model,
+ },
+ "@/features/settings/stores/stt-context": { sttContextBody },
+ react: {
+ useCallback: (callback: unknown) => callback,
+ useEffect: () => undefined,
+ useRef: (current: unknown) => ({ current }),
+ useState: (value: unknown) => [value, () => undefined],
+ },
+ "../api": { transcribeAudioInput: reference },
+ "../audio-run-request": { sourceRefOf },
+ "../catalog": { sttEngineForRepoId, sttSidecarKeyFor },
+ },
+ );
+
+ for (const contextLength of [0, 4096]) {
+ useVoiceSettingsStore.getState().setSttContextLength(contextLength);
+ for (const [model, engine] of [
+ ["qwen3-asr-0.6b", "mtmd"],
+ ["qwen3-asr-1.7b", "mtmd"],
+ ["small", "gguf"],
+ ] as const) {
+ requests.length = 0;
+ await load(model, engine);
+ await raw(new Blob(["audio"]), { model, engine });
+ const sourceOptions = {
+ model,
+ engine,
+ device: "auto",
+ language: "",
+ timestamps: false,
+ speakers: false,
+ signal: new AbortController().signal,
+ };
+ await source({ input_id: "input-1" }, "clip", sourceOptions, () => {});
+ useVoiceSettingsStore.getState().setSttModel(model);
+ const hook = referenceHook({ sttRepo: null, onText: () => undefined });
+ await hook.transcribe({
+ kind: "input",
+ id: "input-1",
+ name: "clip",
+ durationS: 1,
+ });
+ const expected = engine === "mtmd" ? contextLength : undefined;
+ for (const index of [0, 2, 3]) {
+ assert.equal(
+ JSON.parse(String(requests[index].init.body)).context_length,
+ expected,
+ );
+ }
+ assert.equal(
+ new URL(requests[1].url, "http://localhost").searchParams.get(
+ "context_length",
+ ),
+ expected === undefined ? null : String(expected),
+ );
+ await source(
+ { input_id: "input-1" },
+ "clip",
+ {
+ ...sourceOptions,
+ providerId: "external-provider",
+ },
+ () => {},
+ );
+ assert.equal(
+ JSON.parse(String(requests[4].init.body)).context_length,
+ undefined,
+ );
+ }
+ }
+});
+
+test("context changes spare active transcriptions and scope the unload to the selected model", () => {
+ const source = readSrc("features/settings/tabs/voice-tab.tsx");
+ const start = source.indexOf(
+ "const next = normalizeSttContextLength(Number(value))",
+ );
+ const end = source.indexOf("setSttContextLength(next)", start);
+ assert.ok(start >= 0 && end > start);
+ assert.match(
+ source.slice(start, end),
+ /unloadSttModel\(sttEngineFor\(sttModel\), sttModel, \{\s*wait: false,/,
+ );
+});
+
+test("an incomplete raw transcription preserves its error without committing partial text", async () => {
+ const detail =
+ "Transcription stopped at a token limit and is incomplete. Choose Auto or a larger voice context.";
+ const raw = requestFunction<typeof transcribeAudioBlob>(
+ "features/chat/adapters/studio-model-dictation-adapter.ts",
+ "transcribeAudioBlob",
+ "export interface SttDownloadStatus",
+ {
+ useVoiceSettingsStore,
+ sttContextBody,
+ resolveModelDictationLanguage: () => undefined,
+ sttModelVariant: () => null,
+ sttRequestError,
+ sttErrorDetail: async (response: Response) =>
+ (await response.json()).detail,
+ authFetch: () =>
+ Promise.resolve(
+ new Response(JSON.stringify({ detail, text: "partial words" }), {
+ status: 422,
+ }),
+ ),
+ },
+ );
+ const fence = { generation: 1, owner: "thread-a", authSessionEpoch: 1 };
+ const committed: string[] = [];
+ await assert.rejects(
+ completeChatAudioUpload({
+ started: fence,
+ current: () => fence,
+ signal: new AbortController().signal,
+ blocked: () => false,
+ transcribe: () =>
+ raw(new Blob(["audio"]), { model: "qwen3-asr-0.6b", engine: "mtmd" }),
+ commit: (text) => committed.push(text),
+ }),
+ (error) => error instanceof Error && error.message === detail,
+ );
+ assert.deepEqual(committed, []);
+});
+
+test("a context error after streamed progress never becomes a completed transcript", async () => {
+ const message = "Transcription stopped at a token limit and is incomplete.";
+ const events = [
+ { type: "progress", text: "partial words" },
+ { type: "error", message },
+ ]
+ .map((event) => JSON.stringify(event))
+ .join("\n");
+ const updates: string[] = [];
+ const response = new Response(events);
+ assert.ok(response.body);
+ await assert.rejects(
+ readTranscriptStream(response.body, (progress) =>
+ updates.push(progress.text),
+ ),
+ (error) => error instanceof Error && error.message === message,
+ );
+ assert.deepEqual(updates, ["partial words"]);
+});