Skip to content

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

studio: scope speech download cancellation to its attempt (#12925)

Maheswar Kumar319be470f268
diff --git a/studio/backend/core/inference/stt_audiocpp_sidecar.py b/studio/backend/core/inference/stt_audiocpp_sidecar.py
index a727f51bec1..111864367cd 100644
--- a/studio/backend/core/inference/stt_audiocpp_sidecar.py
+++ b/studio/backend/core/inference/stt_audiocpp_sidecar.py
@@ -18,6 +18,7 @@ import json
import subprocess
import tempfile
import threading
+import uuid
import wave
from contextlib import contextmanager
from dataclasses import replace
@@ -65,6 +66,7 @@ from core.inference.stt_sidecar import (
_downloaded_file_bytes,
_HF_COMMIT_SHA,
_prepare_stt_cache_for_http,
+ _remember_completed_download,
_training_active,
normalize_whisper_language,
)
@@ -307,6 +309,8 @@ class _AudioCppDownloadState:
self._thread: Optional[threading.Thread] = None
self._process: Optional[subprocess.Popen] = None
self._model_id: Optional[str] = None
+ self._download_id: Optional[str] = None
+ self._completed_download_ids: list[str] = []
self._error: Optional[str] = None
self._total_bytes: Optional[int] = None
self._etag: Optional[str] = None
@@ -320,10 +324,16 @@ class _AudioCppDownloadState:
with self._lock:
downloading = self._thread is not None and self._thread.is_alive()
# Callers track the row they picked; a variant pick arrives folded in as ``row:variant``.
- row = split_variant_ref(self._model_id)[0] if self._model_id else None
+ base, variant = split_variant_ref(self._model_id) if self._model_id else (None, None)
+ ref = parse_identifier(base)
+ row = base
+ variant = variant or (ref.variant_hint if ref is not None else None)
snapshot = {
"downloading": downloading,
"model": row if downloading else None,
+ "download_id": self._download_id,
+ "completed_download_ids": list(self._completed_download_ids),
+ "variant": variant if downloading else None,
"error": self._error,
"cancelled": self._cancelled,
"cancelled_model": row if self._cancelled else None,
@@ -340,10 +350,36 @@ class _AudioCppDownloadState:
snapshot["bytes_done"] = self._downloaded_bytes(*captured) if downloading else None
return snapshot
- def cancel(self) -> bool:
+ def cancel(
+ self,
+ model_id: Optional[str] = None,
+ download_id: Optional[str] = None,
+ ) -> bool:
with self._lock:
if self._thread is None or not self._thread.is_alive():
return False
+ if self._download_id in self._completed_download_ids:
+ return False
+ if download_id is not None:
+ if self._download_id != download_id:
+ return False
+ elif model_id is not None:
+ active_base, active_variant = split_variant_ref(self._model_id or "")
+ expected_base, expected_variant = split_variant_ref(model_id)
+ active_ref = parse_identifier(active_base)
+ expected_ref = parse_identifier(expected_base)
+ active_row = active_ref.id if active_ref is not None else ""
+ expected_row = expected_ref.id if expected_ref is not None else ""
+ active_variant = active_variant or (
+ active_ref.variant_hint if active_ref is not None else None
+ )
+ expected_variant = expected_variant or (
+ expected_ref.variant_hint if expected_ref is not None else None
+ )
+ if active_row.lower() != expected_row.lower() or (
+ expected_variant is not None and active_variant != expected_variant
+ ):
+ return False
self._cancelled = True
process = self._process
if process is not None and process.poll() is None:
@@ -371,7 +407,7 @@ class _AudioCppDownloadState:
self,
model_id: str,
hf_token: Optional[str] = None,
- ) -> None:
+ ) -> str:
model_id = str(model_id or DEFAULT_AUDIO_CPP_STT_MODEL).strip()
resolve_audio_cpp_stt_model_id(model_id)
hub_cache = _capture_stt_hub_cache()
@@ -379,7 +415,7 @@ class _AudioCppDownloadState:
if self._thread is not None and self._thread.is_alive():
if self._model_id == model_id:
if not self._cancelled:
- return
+ return str(self._download_id)
raise SttModelIdError(
f"'{model_id}' is still cancelling; try again in a moment."
)
@@ -388,6 +424,7 @@ class _AudioCppDownloadState:
"wait for it to finish."
)
self._model_id = model_id
+ self._download_id = uuid.uuid4().hex
self._error = None
self._total_bytes = None
self._etag = None
@@ -402,6 +439,7 @@ class _AudioCppDownloadState:
)
self._thread = thread
thread.start()
+ return str(self._download_id)
def _run(self, model_id: str, hf_token: Optional[str], hub_cache: Path) -> None:
registry = None
@@ -470,6 +508,12 @@ class _AudioCppDownloadState:
from core.inference.audio_cpp_models import forget
forget(model.id)
+ with self._lock:
+ _remember_completed_download(
+ self._completed_download_ids,
+ self._download_id,
+ cancelled = self._cancelled,
+ )
return
with self._lock:
if cancelled or process.returncode < 0:
@@ -495,17 +539,18 @@ class _AudioCppDownloadState:
_download_state = _AudioCppDownloadState()
-def start_model_download(model: Optional[str], hf_token: Optional[str] = None) -> None:
+def start_model_download(model: Optional[str], hf_token: Optional[str] = None) -> str:
model = get_audio_cpp_stt_sidecar().keep_loaded_variant(model)
- _download_state.start(str(model or DEFAULT_AUDIO_CPP_STT_MODEL).strip(), hf_token)
+ return _download_state.start(str(model or DEFAULT_AUDIO_CPP_STT_MODEL).strip(), hf_token)
def download_status() -> dict:
return _download_state.status()
-def cancel_model_download() -> bool:
- return _download_state.cancel()
+def cancel_model_download(model: Optional[str] = None, download_id: Optional[str] = None) -> bool:
+ requested = str(model).strip() if model is not None else None
+ return _download_state.cancel(requested, download_id)
def _launches_on_cpu(entry: AudioCppModel, force_cpu: bool) -> bool:
diff --git a/studio/backend/core/inference/stt_ggml_sidecar.py b/studio/backend/core/inference/stt_ggml_sidecar.py
index 50b2e7a50b9..e7873f1944e 100644
--- a/studio/backend/core/inference/stt_ggml_sidecar.py
+++ b/studio/backend/core/inference/stt_ggml_sidecar.py
@@ -64,6 +64,7 @@ from core.inference.stt_sidecar import (
_known_whisper_languages,
_prepare_stt_cache_for_http,
_read_revision_record,
+ _remember_completed_download,
_TARGET_SAMPLE_RATE,
_training_active,
_write_revision_record,
@@ -462,6 +463,8 @@ class _GgmlDownloadState:
self._thread: Optional[threading.Thread] = None
self._process: Optional[subprocess.Popen] = None
self._model_id: Optional[str] = None
+ self._download_id: Optional[str] = None
+ self._completed_download_ids: list[str] = []
self._error: Optional[str] = None
self._total_bytes: Optional[int] = None
self._etag: Optional[str] = None
@@ -475,6 +478,8 @@ class _GgmlDownloadState:
snapshot = {
"downloading": downloading,
"model": self._model_id if downloading else None,
+ "download_id": self._download_id,
+ "completed_download_ids": list(self._completed_download_ids),
"error": self._error,
"cancelled": self._cancelled,
# Which model the cancel applies to. "model" goes None once the worker thread stops, so a settled
@@ -494,7 +499,11 @@ class _GgmlDownloadState:
snapshot["bytes_done"] = self._downloaded_bytes(*captured) if downloading else None
return snapshot
- def cancel(self) -> bool:
+ def cancel(
+ self,
+ model_id: Optional[str] = None,
+ download_id: Optional[str] = None,
+ ) -> bool:
"""Stop an in-flight download. False when none was running.
The partial blob stays cached, so a restart resumes from it.
@@ -502,6 +511,13 @@ class _GgmlDownloadState:
with self._lock:
if self._thread is None or not self._thread.is_alive():
return False
+ if self._download_id in self._completed_download_ids:
+ return False
+ if download_id is not None:
+ if self._download_id != download_id:
+ return False
+ elif model_id is not None and self._model_id != model_id:
+ return False
self._cancelled = True
process = self._process
if process is not None and process.poll() is None:
@@ -546,14 +562,14 @@ class _GgmlDownloadState:
self,
model_id: str,
hf_token: Optional[str] = None,
- ) -> None:
+ ) -> str:
model_id = resolve_ggml_model_id(model_id)
hub_cache = _capture_stt_hub_cache()
with self._lock:
if self._thread is not None and self._thread.is_alive():
if self._model_id == model_id:
if not self._cancelled:
- return
+ return str(self._download_id)
raise SttModelIdError(
f"'{model_id}' is still cancelling; try again in a moment."
)
@@ -562,6 +578,7 @@ class _GgmlDownloadState:
"downloading; wait for it to finish."
)
self._model_id = model_id
+ self._download_id = uuid.uuid4().hex
self._error = None
self._total_bytes = None
self._etag = None
@@ -576,6 +593,7 @@ class _GgmlDownloadState:
)
self._thread = thread
thread.start()
+ return str(self._download_id)
def _run(
self,
@@ -664,6 +682,12 @@ class _GgmlDownloadState:
):
raise RuntimeError("downloaded file is missing from the captured cache")
_write_revision_record(repo_id, revision)
+ with self._lock:
+ _remember_completed_download(
+ self._completed_download_ids,
+ self._download_id,
+ cancelled = self._cancelled,
+ )
return
with self._lock:
if cancelled or process.returncode < 0:
@@ -686,16 +710,20 @@ class _GgmlDownloadState:
_download_state = _GgmlDownloadState()
-def start_model_download(model: Optional[str], hf_token: Optional[str] = None) -> None:
- _download_state.start(resolve_ggml_model_id(model), hf_token)
+def start_model_download(model: Optional[str], hf_token: Optional[str] = None) -> str:
+ return _download_state.start(resolve_ggml_model_id(model), hf_token)
def download_status() -> dict:
return _download_state.status()
-def cancel_model_download() -> bool:
- return _download_state.cancel()
+def cancel_model_download(model: Optional[str] = None, download_id: Optional[str] = None) -> bool:
+ try:
+ model_id = resolve_ggml_model_id(model) if model is not None else None
+ except SttModelIdError:
+ return False
+ return _download_state.cancel(model_id, download_id)
def _pcm_to_wav_bytes(decoded_audio) -> bytes:
diff --git a/studio/backend/core/inference/stt_mtmd_sidecar.py b/studio/backend/core/inference/stt_mtmd_sidecar.py
index 44366ec07d3..4bea1c0ac27 100644
--- a/studio/backend/core/inference/stt_mtmd_sidecar.py
+++ b/studio/backend/core/inference/stt_mtmd_sidecar.py
@@ -22,6 +22,7 @@ import subprocess
import threading
import time
import urllib.request
+import uuid
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
@@ -57,6 +58,7 @@ from core.inference.stt_sidecar import (
_HF_COMMIT_SHA,
_prepare_stt_cache_for_http,
_read_revision_record,
+ _remember_completed_download,
_TARGET_SAMPLE_RATE,
_training_active,
_write_revision_record,
@@ -318,6 +320,8 @@ class _MtmdDownloadState:
self._thread: Optional[threading.Thread] = None
self._process: Optional[subprocess.Popen] = None
self._model_id: Optional[str] = None
+ self._download_id: Optional[str] = None
+ self._completed_download_ids: list[str] = []
self._error: Optional[str] = None
self._total_bytes: Optional[int] = None
self._selected_files: tuple[_SelectedHubFile, ...] = ()
@@ -332,6 +336,8 @@ class _MtmdDownloadState:
snapshot = {
"downloading": downloading,
"model": model_id if downloading else None,
+ "download_id": self._download_id,
+ "completed_download_ids": list(self._completed_download_ids),
"error": self._error,
"cancelled": self._cancelled,
# Which model the cancel applies to. "model" goes None once the worker thread stops, so a settled
@@ -351,11 +357,22 @@ class _MtmdDownloadState:
snapshot["bytes_done"] = self._downloaded_bytes(*captured) if downloading else None
return snapshot
- def cancel(self) -> bool:
+ def cancel(
+ self,
+ model_id: Optional[str] = None,
+ download_id: Optional[str] = None,
+ ) -> bool:
"""Stop an in-flight download. False when none was running."""
with self._lock:
if self._thread is None or not self._thread.is_alive():
return False
+ if self._download_id in self._completed_download_ids:
+ return False
+ if download_id is not None:
+ if self._download_id != download_id:
+ return False
+ elif model_id is not None and self._model_id != model_id:
+ return False
self._cancelled = True
process = self._process
if process is not None and process.poll() is None:
@@ -405,14 +422,14 @@ class _MtmdDownloadState:
self,
model_id: str,
hf_token: Optional[str] = None,
- ) -> None:
+ ) -> str:
model_id = resolve_mtmd_model_id(model_id)
hub_cache = _capture_stt_hub_cache()
with self._lock:
if self._thread is not None and self._thread.is_alive():
if self._model_id == model_id:
if not self._cancelled:
- return
+ return str(self._download_id)
raise SttModelIdError(
f"'{model_id}' is still cancelling; try again in a moment."
)
@@ -421,6 +438,7 @@ class _MtmdDownloadState:
"downloading; wait for it to finish."
)
self._model_id = model_id
+ self._download_id = uuid.uuid4().hex
self._error = None
self._total_bytes = None
self._selected_files = ()
@@ -435,6 +453,7 @@ class _MtmdDownloadState:
)
self._thread = thread
thread.start()
+ return str(self._download_id)
def _run(
self,
@@ -516,6 +535,12 @@ class _MtmdDownloadState:
):
raise RuntimeError("downloaded mtmd files are missing from the captured cache")
_write_revision_record(spec.repo, revision)
+ with self._lock:
+ _remember_completed_download(
+ self._completed_download_ids,
+ self._download_id,
+ cancelled = self._cancelled,
+ )
return
with self._lock:
if cancelled or process.returncode < 0:
@@ -541,16 +566,20 @@ class _MtmdDownloadState:
_download_state = _MtmdDownloadState()
-def start_model_download(model: Optional[str], hf_token: Optional[str] = None) -> None:
- _download_state.start(resolve_mtmd_model_id(model), hf_token)
+def start_model_download(model: Optional[str], hf_token: Optional[str] = None) -> str:
+ return _download_state.start(resolve_mtmd_model_id(model), hf_token)
def download_status() -> dict:
return _download_state.status()
-def cancel_model_download() -> bool:
- return _download_state.cancel()
+def cancel_model_download(model: Optional[str] = None, download_id: Optional[str] = None) -> bool:
+ try:
+ model_id = resolve_mtmd_model_id(model) if model is not None else None
+ except SttModelIdError:
+ return False
+ return _download_state.cancel(model_id, download_id)
class MtmdSttSidecar:
diff --git a/studio/backend/core/inference/stt_sidecar.py b/studio/backend/core/inference/stt_sidecar.py
index 2682910464f..b90f56a45ef 100644
--- a/studio/backend/core/inference/stt_sidecar.py
+++ b/studio/backend/core/inference/stt_sidecar.py
@@ -682,6 +682,17 @@ def is_model_downloaded(model: Optional[str]) -> bool:
return False
+def _remember_completed_download(
+ completed_download_ids: list[str], download_id: Optional[str], *, cancelled: bool
+) -> bool:
+ """Keep enough successful attempt ids for delayed UI pollers to settle."""
+ if cancelled or download_id is None:
+ return False
+ completed_download_ids.append(download_id)
+ del completed_download_ids[:-8]
+ return True
+
+
class _SnapshotDownloadState:
"""Tracks one background snapshot_download of a dictation repository.
@@ -694,6 +705,8 @@ class _SnapshotDownloadState:
self._thread: Optional[threading.Thread] = None
self._process: Optional[subprocess.Popen] = None
self._model_id: Optional[str] = None
+ self._download_id: Optional[str] = None
+ self._completed_download_ids: list[str] = []
self._repo: Optional[str] = None
self._revision: Optional[str] = None
self._hub_cache: Optional[Path] = None
@@ -710,6 +723,8 @@ class _SnapshotDownloadState:
snapshot = {
"downloading": downloading,
"model": self._model_id if downloading else None,
+ "download_id": self._download_id,
+ "completed_download_ids": list(self._completed_download_ids),
"error": self._error,
"cancelled": self._cancelled,
# Which model the cancel applies to. "model" goes None once the worker thread stops, so a settled
@@ -729,7 +744,11 @@ class _SnapshotDownloadState:
snapshot["bytes_done"] = self._downloaded_bytes(*captured) if show_progress else None
return snapshot
- def cancel(self) -> bool:
+ def cancel(
+ self,
+ model_id: Optional[str] = None,
+ download_id: Optional[str] = None,
+ ) -> bool:
"""Stop an in-flight download. False when none was running.
Partial blobs stay cached, so a restart resumes from them.
@@ -737,6 +756,13 @@ class _SnapshotDownloadState:
with self._lock:
if self._thread is None or not self._thread.is_alive():
return False
+ if self._download_id in self._completed_download_ids:
+ return False
+ if download_id is not None:
+ if self._download_id != download_id:
+ return False
+ elif model_id is not None and self._model_id != model_id:
+ return False
self._cancelled = True
process = self._process
if process is not None and process.poll() is None:
@@ -814,14 +840,14 @@ class _SnapshotDownloadState:
model_id: str,
hf_token: Optional[str] = None,
revision: Optional[str] = None,
- ) -> None:
+ ) -> str:
model_id = resolve_model_id(model_id)
hub_cache = _capture_stt_hub_cache()
with self._lock:
if self._thread is not None and self._thread.is_alive():
if self._model_id == model_id:
if not self._cancelled:
- return
+ return str(self._download_id)
raise SttModelIdError(
f"'{model_id}' is still cancelling; try again in a moment."
)
@@ -830,6 +856,7 @@ class _SnapshotDownloadState:
"downloading; wait for it to finish."
)
self._model_id = model_id
+ self._download_id = uuid.uuid4().hex
self._repo = resolve_model_repo(model_id)
self._revision = None
self._hub_cache = hub_cache
@@ -846,6 +873,7 @@ class _SnapshotDownloadState:
)
self._thread = thread
thread.start()
+ return str(self._download_id)
def _run(
self,
@@ -921,7 +949,11 @@ class _SnapshotDownloadState:
)
_write_revision_record(repo, revision)
with self._lock:
- self._complete = True
+ self._complete = _remember_completed_download(
+ self._completed_download_ids,
+ self._download_id,
+ cancelled = self._cancelled,
+ )
except Exception as exc:
with self._lock:
if not self._cancelled:
@@ -939,16 +971,20 @@ def start_model_download(
model: Optional[str],
hf_token: Optional[str] = None,
revision: Optional[str] = None,
-) -> None:
- _download_state.start(resolve_model_id(model), hf_token, revision = revision)
+) -> str:
+ return _download_state.start(resolve_model_id(model), hf_token, revision = revision)
def download_status() -> dict:
return _download_state.status()
-def cancel_model_download() -> bool:
- return _download_state.cancel()
+def cancel_model_download(model: Optional[str] = None, download_id: Optional[str] = None) -> bool:
+ try:
+ model_id = resolve_model_id(model) if model is not None else None
+ except SttModelIdError:
+ return False
+ return _download_state.cancel(model_id, download_id)
def _training_active() -> bool:
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index e9d7f8fc994..79b4a2eea8b 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -548,6 +548,10 @@ class SttLoadRequest(BaseModel):
"sub-variant such as 'tiny'. Omitted picks the model's default."
),
)
+ download_id: Optional[str] = Field(
+ None,
+ description = "Opaque identity of the download attempt being cancelled",
+ )
@model_validator(mode = "after")
def _fold_audio_gguf_variant(self):
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index afcc9bab83c..fb7c4c6fdb8 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -24465,6 +24465,7 @@ def _stt_lifecycle() -> tuple:
_stt_download_accounts: dict[str, str] = {}
+_stt_download_id_accounts: dict[str, dict[str, str]] = {}
_stt_download_lock = threading.Lock()
_stt_grant_pending: dict[str, threading.Event] = {}
@@ -24498,9 +24499,14 @@ def _start_account_stt_download(
)
repo = _stt_repo_reference(model, engine)
account_access.authorize_download(repo, "model", hf_token)
- module.start_model_download(*args)
+ download_id = module.start_model_download(*args)
_stt_download_accounts[engine] = current_account_id()
account = current_account_id()
+ if download_id is not None:
+ attempts = _stt_download_id_accounts.setdefault(engine, {})
+ attempts[str(download_id)] = account
+ while len(attempts) > 64:
+ attempts.pop(next(iter(attempts)))
settled = _stt_grant_pending[engine] = threading.Event()
def watch():
@@ -24528,6 +24534,7 @@ def _start_account_stt_download(
settled.set()
account_thread(target = watch, name = f"stt-grant-{engine}", daemon = True).start()
+ return download_id
def retire_stt_downloads() -> None:
@@ -24562,14 +24569,24 @@ def retire_stt_downloads() -> None:
)
-def _cancel_account_stt_download(module, engine):
+def _cancel_account_stt_download(
+ module,
+ engine,
+ model = None,
+ download_id = None,
+):
with _stt_download_lock:
if (
account_access.account_scope() is not None
and _stt_download_accounts.get(engine, OWNER_ACCOUNT_ID) != current_account_id()
):
return {"downloading": False, "cancelled": False}
- cancelled = module.cancel_model_download()
+ if download_id is not None:
+ cancelled = module.cancel_model_download(model, download_id)
+ elif model is not None:
+ cancelled = module.cancel_model_download(model)
+ else:
+ cancelled = module.cancel_model_download()
return {**module.download_status(), "cancelled": cancelled}
@@ -24620,8 +24637,22 @@ def _account_stt_status(status):
for model in section.get("downloaded_models", [])
if account_access.model_visible(_stt_repo_reference(model, engine))
]
+ download = section.get("download", {})
+ attempt_accounts = _stt_download_id_accounts.get(engine, {})
+ completed_download_ids = [
+ download_id
+ for download_id in download.get("completed_download_ids", [])
+ if attempt_accounts.get(download_id) == current_account_id()
+ ]
if _stt_download_accounts.get(engine, OWNER_ACCOUNT_ID) != current_account_id():
- section["download"] = {"downloading": False}
+ # Opaque ids tell stale trackers the engine moved on; no other account's model leaks.
+ section["download"] = {
+ "downloading": False,
+ "download_id": download.get("download_id"),
+ "completed_download_ids": completed_download_ids,
+ }
+ else:
+ download["completed_download_ids"] = completed_download_ids
return status
@@ -24843,7 +24874,7 @@ async def stt_download(
validated = await asyncio.to_thread(validate_remote_model, payload.model, hf_token)
# Pin the download to the commit that was just validated so the
# repo cannot be swapped between validation and snapshot_download.
- await asyncio.to_thread(
+ download_id = await asyncio.to_thread(
_start_account_stt_download,
module,
engine,
@@ -24852,14 +24883,14 @@ async def stt_download(
validated.get("revision"),
)
else:
- await asyncio.to_thread(
+ download_id = await asyncio.to_thread(
_start_account_stt_download, module, engine, payload.model, hf_token
)
except SttModelIdError as e:
raise HTTPException(status_code = 422, detail = str(e))
except SttModelCompatibilityError as e:
raise HTTPException(status_code = 422, detail = str(e))
- return JSONResponse(content = module.download_status())
+ return JSONResponse(content = {**module.download_status(), "download_id": download_id})
@studio_router.post("/audio/stt/download/cancel")
@@ -24875,7 +24906,13 @@ async def stt_download_cancel(
engine = _resolve_serving_stt_engine(payload.engine if payload else None)
module = _stt_download_module(engine)
- status = await asyncio.to_thread(_cancel_account_stt_download, module, engine)
+ status = await asyncio.to_thread(
+ _cancel_account_stt_download,
+ module,
+ engine,
+ payload.model if payload else None,
+ payload.download_id if payload else None,
+ )
return JSONResponse(content = status)
diff --git a/studio/backend/tests/test_account_inference_isolation.py b/studio/backend/tests/test_account_inference_isolation.py
index e933d7d3724..6bcd6563c5c 100644
--- a/studio/backend/tests/test_account_inference_isolation.py
+++ b/studio/backend/tests/test_account_inference_isolation.py
@@ -338,6 +338,7 @@ def test_cpu_resident_provenance_does_not_depend_on_a_gpu_lease(monkeypatch):
def test_stt_private_status_and_download_state_are_filtered(monkeypatch):
monkeypatch.setattr(inference, "_stt_download_accounts", {"transformers": ALICE.account_id})
+ monkeypatch.setattr(inference, "_stt_download_id_accounts", {})
monkeypatch.setattr(access, "_resident_accounts", {})
monkeypatch.setattr(inference, "_stt_repo_reference", lambda model, engine: model)
run_as(ALICE, access.note_resident_account, "stt:transformers", "org/private")
@@ -354,14 +355,56 @@ def test_stt_private_status_and_download_state_are_filtered(monkeypatch):
assert "private error" not in str(result)
+def test_stt_filtered_status_preserves_only_caller_relevant_attempt_identity(monkeypatch):
+ monkeypatch.setattr(inference, "_stt_download_accounts", {"audiocpp": BOB.account_id})
+ monkeypatch.setattr(
+ inference,
+ "_stt_download_id_accounts",
+ {
+ "audiocpp": {
+ "alice-complete": ALICE.account_id,
+ "bob-complete": BOB.account_id,
+ "bob-active": BOB.account_id,
+ }
+ },
+ )
+ monkeypatch.setattr(inference, "_stt_repo_reference", lambda model, engine: model)
+ monkeypatch.setattr(access, "model_visible", lambda model: True)
+ status = {"loaded_model": None}
+ for engine in ["transformers", "gguf", "mtmd", "audiocpp"]:
+ status[engine] = {
+ "loaded_model": None,
+ "downloaded_models": [],
+ "download": {"downloading": False, "completed_download_ids": []},
+ }
+ status["audiocpp"]["download"] = {
+ "downloading": True,
+ "model": "bob/private-model",
+ "download_id": "bob-active",
+ "completed_download_ids": ["alice-complete", "bob-complete"],
+ "error": "bob private error",
+ }
+
+ result = run_as(ALICE, inference._account_stt_status, status)
+
+ assert result["audiocpp"]["download"] == {
+ "downloading": False,
+ "download_id": "bob-active",
+ "completed_download_ids": ["alice-complete"],
+ }
+ assert "private-model" not in str(result)
+ assert "private error" not in str(result)
+
+
def test_stt_downloads_grant_only_the_initiator_and_cancel_is_scoped(monkeypatch):
monkeypatch.setattr(inference, "_stt_download_accounts", {})
+ monkeypatch.setattr(inference, "_stt_download_id_accounts", {})
monkeypatch.setattr(inference, "_stt_grant_pending", {})
monkeypatch.setattr(inference, "_stt_repo_reference", lambda model, engine: model)
monkeypatch.setattr(access, "authorize_download", lambda *a: None)
calls = []
module = SimpleNamespace(
- start_model_download = lambda *a: calls.append(a),
+ start_model_download = lambda *a: calls.append(a) or "alice-attempt",
download_status = lambda: {"downloading": False},
is_model_downloaded = lambda model: True,
cancel_model_download = lambda: calls.append("cancel") or True,
@@ -375,6 +418,9 @@ def test_stt_downloads_grant_only_the_initiator_and_cancel_is_scoped(monkeypatch
"alice-token",
)
assert inference._stt_grant_pending["transformers"].wait(5)
+ assert inference._stt_download_id_accounts == {
+ "transformers": {"alice-attempt": ALICE.account_id}
+ }
assert run_as(ALICE, access.repo_visible, "org/private")
assert not run_as(BOB, access.repo_visible, "org/private")
assert run_as(BOB, inference._cancel_account_stt_download, module, "transformers") == {
diff --git a/studio/backend/tests/test_job_accounts.py b/studio/backend/tests/test_job_accounts.py
index 32cecf274db..4601aed1769 100644
--- a/studio/backend/tests/test_job_accounts.py
+++ b/studio/backend/tests/test_job_accounts.py
@@ -1612,6 +1612,7 @@ def test_retirement_reaps_stt_downloads_and_fences_a_parked_start(tmp_path, monk
monkeypatch.setattr(dataset_downloads, "retire_account_downloads", lambda: None)
monkeypatch.setattr(model_downloads, "retire_account_downloads", lambda: None)
monkeypatch.setattr(inference, "_stt_download_accounts", {})
+ monkeypatch.setattr(inference, "_stt_download_id_accounts", {})
monkeypatch.setattr(inference, "_stt_grant_pending", {})
monkeypatch.setattr(inference, "_stt_repo_reference", lambda model, engine: model)
monkeypatch.setattr(access, "authorize_download", lambda *a: None)
diff --git a/studio/backend/tests/test_stt_download_followups.py b/studio/backend/tests/test_stt_download_followups.py
index 9ab09cf4f26..718e7578c06 100644
--- a/studio/backend/tests/test_stt_download_followups.py
+++ b/studio/backend/tests/test_stt_download_followups.py
@@ -18,6 +18,7 @@ from types import SimpleNamespace
import pytest
from core.inference import stt_download_worker as worker_mod
+from core.inference import stt_audiocpp_sidecar as audiocpp_mod
from core.inference import stt_ggml_sidecar as ggml_mod
from core.inference import stt_mtmd_sidecar as mtmd_mod
from core.inference import stt_sidecar as snapshot_mod
@@ -152,6 +153,178 @@ def test_restarting_a_cancelling_download_is_not_a_silent_no_op(state_factory, m
state._thread.join(timeout = 5)
+ "state_factory, active_model, stale_model",
+ [
+ (snapshot_mod._SnapshotDownloadState, "unsloth/whisper-small", "unsloth/whisper-tiny"),
+ (ggml_mod._GgmlDownloadState, "small", "tiny"),
+ (mtmd_mod._MtmdDownloadState, "qwen3-asr-1.7b", "qwen3-asr-0.6b"),
+ (
+ audiocpp_mod._AudioCppDownloadState,
+ "homebrew/repo:new-quant",
+ "homebrew/repo:old-quant",
+ ),
+ (
+ audiocpp_mod._AudioCppDownloadState,
+ "audiocpp-moonshine-small",
+ "audiocpp-moonshine-tiny",
+ ),
+ ],
+)
+def test_a_stale_cancel_cannot_stop_a_newer_download(
+ state_factory, active_model, stale_model, monkeypatch
+):
+ state = state_factory()
+ release = threading.Event()
+ process = SimpleNamespace(poll = lambda: None)
+ stopped = []
+ monkeypatch.setattr(worker_mod, "terminate_download", stopped.append)
+ state._model_id = active_model
+ state._download_id = "new-download"
+ state._process = process
+ state._thread = threading.Thread(target = release.wait, daemon = True)
+ state._thread.start()
+ try:
+ assert state.status()["download_id"] == "new-download"
+ assert state.cancel(active_model, "old-download") is False
+ assert state.cancel(stale_model) is False
+ assert state._cancelled is False
+ assert stopped == []
+ assert state.cancel(active_model, "new-download") is True
+ assert state._cancelled is True
+ assert stopped == [process]
+ finally:
+ release.set()
+ state._thread.join(timeout = 5)
+
+
+ "state_factory, model_id",
+ [
+ (snapshot_mod._SnapshotDownloadState, "unsloth/whisper-tiny"),
+ (ggml_mod._GgmlDownloadState, "tiny"),
+ (mtmd_mod._MtmdDownloadState, "qwen3-asr-0.6b"),
+ (audiocpp_mod._AudioCppDownloadState, "homebrew/repo:Q4_K_M"),
+ ],
+)
+def test_a_completed_attempt_cannot_be_cancelled_during_thread_teardown(
+ state_factory, model_id, monkeypatch
+):
+ state = state_factory()
+ release = threading.Event()
+ process = SimpleNamespace(poll = lambda: None)
+ stopped = []
+ monkeypatch.setattr(worker_mod, "terminate_download", stopped.append)
+ state._model_id = model_id
+ state._download_id = "completed-download"
+ state._completed_download_ids.append("completed-download")
+ state._process = process
+ state._thread = threading.Thread(target = release.wait, daemon = True)
+ state._thread.start()
+ try:
+ assert state.cancel(model_id, "completed-download") is False
+ assert state._cancelled is False
+ assert stopped == []
+ finally:
+ release.set()
+ state._thread.join(timeout = 5)
+
+
+def test_the_download_identity_is_authoritative_for_an_audio_variant(monkeypatch):
+ state = audiocpp_mod._AudioCppDownloadState()
+ release = threading.Event()
+ process = SimpleNamespace(poll = lambda: None)
+ stopped = []
+ monkeypatch.setattr(worker_mod, "terminate_download", stopped.append)
+ state._model_id = "homebrew/repo:new-quant"
+ state._download_id = "new-download"
+ state._process = process
+ state._thread = threading.Thread(target = release.wait, daemon = True)
+ state._thread.start()
+ try:
+ assert state.status()["variant"] == "new-quant"
+ assert state.cancel("homebrew/repo", "new-download") is True
+ assert stopped == [process]
+ finally:
+ release.set()
+ state._thread.join(timeout = 5)
+
+
+def test_completed_download_history_is_bounded_and_ignores_missing_identity():
+ history = [f"attempt-{index}" for index in range(8)]
+
+ assert snapshot_mod._remember_completed_download(history, None, cancelled = False) is False
+ assert snapshot_mod._remember_completed_download(history, "cancelled", cancelled = True) is False
+ assert snapshot_mod._remember_completed_download(history, "attempt-8", cancelled = False) is True
+
+ assert history == [f"attempt-{index}" for index in range(1, 9)]
+
+
+ "state_factory",
+ [
+ snapshot_mod._SnapshotDownloadState,
+ ggml_mod._GgmlDownloadState,
+ mtmd_mod._MtmdDownloadState,
+ audiocpp_mod._AudioCppDownloadState,
+ ],
+)
+def test_download_status_copies_completed_attempt_history(state_factory):
+ state = state_factory()
+ state._completed_download_ids.append("attempt-a")
+
+ status = state.status()
+ status["completed_download_ids"].append("caller-mutation")
+
+ assert state.status()["completed_download_ids"] == ["attempt-a"]
+
+
+def test_a_bare_audio_row_remains_a_legacy_cancel_target(monkeypatch):
+ state = audiocpp_mod._AudioCppDownloadState()
+ release = threading.Event()
+ process = SimpleNamespace(poll = lambda: None)
+ stopped = []
+ monkeypatch.setattr(worker_mod, "terminate_download", stopped.append)
+ state._model_id = "homebrew/repo:new-quant"
+ state._process = process
+ state._thread = threading.Thread(target = release.wait, daemon = True)
+ state._thread.start()
+ try:
+ assert state.cancel("homebrew/repo") is True
+ assert stopped == [process]
+ finally:
+ release.set()
+ state._thread.join(timeout = 5)
+
+
+def test_cancel_route_forwards_the_request_identity():
+ from routes import inference
+
+ cancelled = []
+ module = SimpleNamespace(
+ cancel_model_download = lambda model, download_id: cancelled.append((model, download_id))
+ or False,
+ download_status = lambda: {"downloading": True, "model": "new"},
+ )
+
+ result = inference._cancel_account_stt_download(module, "transformers", "old", "old-download")
+
+ assert cancelled == [("old", "old-download")]
+ assert result["cancelled"] is False
+
+
+def test_start_account_download_returns_the_attempt_identity(monkeypatch):
+ from routes import inference
+
+ monkeypatch.setattr(inference.account_access, "account_scope", lambda: None)
+ module = SimpleNamespace(start_model_download = lambda *args: "attempt-a")
+
+ assert (
+ inference._start_account_stt_download(module, "transformers", "small", None, "a" * 40)
+ == "attempt-a"
+ )
+
+
def test_a_worker_that_ignores_sigterm_is_killed():
"""The canceller holds the repository reservation until the reap returns."""
process = subprocess.Popen(
diff --git a/studio/backend/tests/test_stt_sidecar.py b/studio/backend/tests/test_stt_sidecar.py
index 688d4f4a29a..b808c989e00 100644
--- a/studio/backend/tests/test_stt_sidecar.py
+++ b/studio/backend/tests/test_stt_sidecar.py
@@ -1942,6 +1942,8 @@ def test_download_status_is_idle_before_any_download():
assert status == {
"downloading": False,
"model": None,
+ "download_id": None,
+ "completed_download_ids": [],
"error": None,
"cancelled": False,
# Only set alongside cancelled: "model" goes None once the download thread stops, so
diff --git a/studio/frontend/src/features/audio/hooks/use-stt-sidecar.ts b/studio/frontend/src/features/audio/hooks/use-stt-sidecar.ts
index 5827b43b0cd..c8cb82388b7 100644
--- a/studio/frontend/src/features/audio/hooks/use-stt-sidecar.ts
+++ b/studio/frontend/src/features/audio/hooks/use-stt-sidecar.ts
@@ -12,7 +12,6 @@ import {
} from "@/features/chat/adapters/studio-model-dictation-adapter";
import { getHfToken, hfApiToken } from "@/features/hub/stores/hf-token-store";
import {
- isTrackingSttDownload,
trackSttDownload,
} from "@/features/settings/lib/stt-download-mirror";
import { usePersistedChoice } from "@/hooks/use-persisted-choice";
@@ -221,19 +220,19 @@ export function useSttSidecar({
} catch (error) {
if (!(error instanceof SttModelNotDownloadedError)) throw error;
if (!isCurrent()) return;
- await startSttDownload(
+ const download = await startSttDownload(
sidecarKey,
hfApiToken(getHfToken()),
engine,
ggufVariant,
);
- if (!isTrackingSttDownload(sidecarKey, engine)) {
- trackSttDownload(sidecarKey, {
- warmSelectedVoiceModelOnComplete: false,
- engine,
- repoId,
- });
- }
+ trackSttDownload(sidecarKey, {
+ warmSelectedVoiceModelOnComplete: false,
+ engine,
+ repoId,
+ ggufVariant,
+ downloadId: download.download_id,
+ });
toast.dismiss(toastId);
// Re-check ownership around every await: an old pick could replace a newer sidecar.
for (;;) {
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 e530f5b6e05..01fdcfd2e06 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
@@ -239,6 +239,12 @@ export async function transcribeAudioBlob(
export interface SttDownloadStatus {
downloading: boolean;
model: string | null;
+ /** opaque identity of this download attempt */
+ download_id?: string | null;
+ /** bounded history of attempts that completed successfully */
+ completed_download_ids?: string[];
+ /** active audiocpp quant; absent for other engines */
+ variant?: string | null;
error: string | null;
/** whether the user stopped the last download */
cancelled?: boolean;
@@ -408,7 +414,7 @@ export async function startSttDownload(
hfToken?: string,
engine?: SttEngine,
ggufVariant?: string | null,
-): Promise<void> {
+): Promise<SttDownloadStatus> {
const resolvedEngine = engine ?? sttEngineFor(model);
const response = await authFetch("/api/inference/audio/stt/download", {
method: "POST",
@@ -428,6 +434,7 @@ export async function startSttDownload(
} | null;
throw new Error(body?.detail ?? `HTTP ${response.status}`);
}
+ return (await response.json()) as SttDownloadStatus;
}
/** Stop an in-flight model download. Partial files stay cached, so starting the same download
@@ -435,18 +442,29 @@ export async function startSttDownload(
export async function cancelSttDownload(
model: string,
engine?: SttEngine,
+ ggufVariant?: string | null,
+ downloadId?: string | null,
): Promise<void> {
+ const resolvedEngine = engine ?? sttEngineFor(model);
const response = await authFetch("/api/inference/audio/stt/download/cancel", {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ model, engine: engine ?? sttEngineFor(model) }),
+ body: JSON.stringify({
+ model,
+ engine: resolvedEngine,
+ ...sttVariantBody(resolvedEngine, ggufVariant),
+ ...(downloadId ? { download_id: downloadId } : {}),
+ }),
});
+ const body = (await response.json().catch(() => null)) as
+ | (Partial<SttDownloadStatus> & { detail?: string })
+ | null;
if (!response.ok) {
- const body = (await response.json().catch(() => null)) as {
- detail?: string;
- } | null;
throw new Error(body?.detail ?? `HTTP ${response.status}`);
}
+ if (body?.downloading && body.cancelled === false) {
+ throw new Error("The download changed before cancellation completed.");
+ }
}
/** Release the local STT model and its RAM/VRAM allocations. */
diff --git a/studio/frontend/src/features/settings/components/stt-download-prompt.tsx b/studio/frontend/src/features/settings/components/stt-download-prompt.tsx
index b13aab555ac..61bafd2503f 100644
--- a/studio/frontend/src/features/settings/components/stt-download-prompt.tsx
+++ b/studio/frontend/src/features/settings/components/stt-download-prompt.tsx
@@ -85,7 +85,7 @@ export function SttDownloadPrompt() {
useVoiceSettingsStore.getState().setDictationEngine("model");
}
try {
- await startSttDownload(
+ const download = await startSttDownload(
request.model,
hfApiToken(hfToken),
undefined,
@@ -94,6 +94,7 @@ export function SttDownloadPrompt() {
// progress uses the shared download panel; the model loads when the download finishes
trackSttDownload(request.model, {
ggufVariant: request.ggufVariant ?? null,
+ downloadId: download.download_id,
});
} catch (error) {
toast.error(t("settings.voice.dictation.sttDownloadFailed"), {
diff --git a/studio/frontend/src/features/settings/lib/stt-download-mirror.ts b/studio/frontend/src/features/settings/lib/stt-download-mirror.ts
index 290ed5eb6c8..3f8f8082773 100644
--- a/studio/frontend/src/features/settings/lib/stt-download-mirror.ts
+++ b/studio/frontend/src/features/settings/lib/stt-download-mirror.ts
@@ -25,7 +25,12 @@ import {
sttModelVariant,
useVoiceSettingsStore,
} from "../stores/voice-settings-store";
-import { SttDownloadTrackers } from "./stt-download-trackers";
+import {
+ isSameSttAttempt,
+ shouldRecheckSttReplacement,
+ SttDownloadTrackers,
+ sttReplacementAction,
+} from "./stt-download-trackers";
/**
* Shows a dictation model download in the shared download panel, and loads the
@@ -42,6 +47,19 @@ const trackers = new SttDownloadTrackers();
const warmSelectedVoiceModelOnComplete = new Map<string, boolean>();
// The quant each tracked download fetches, when its starter knew it.
const trackedVariants = new Map<string, string | null>();
+const trackedDownloadIds = new Map<string, string | null>();
+const trackedStartedAt = new Map<string, number>();
+const replacementChecks = new Map<string, string>();
+
+interface TrackSttDownloadOptions {
+ warmSelectedVoiceModelOnComplete?: boolean;
+ engine?: SttEngine;
+ repoId?: string;
+ /** The quant this download fetches, so a quant picked meanwhile is not warmed. */
+ ggufVariant?: string | null;
+ /** The backend attempt this row may cancel. */
+ downloadId?: string | null;
+}
function trackerKey(model: SttModel, engine?: SttEngine): string {
return engine && engine !== "transformers" ? `${engine}:${model}` : model;
@@ -90,6 +108,8 @@ function settle(
warmSelectedVoiceModelOnComplete.delete(key);
const tracked = trackedVariants.get(key);
trackedVariants.delete(key);
+ trackedDownloadIds.delete(key);
+ trackedStartedAt.delete(key);
// Only warm what the user is still pointed at. Selecting another model or
// quant, or leaving local dictation, during the download means this one is
// not wanted and loading it would undo the unload that switch performed.
@@ -113,6 +133,8 @@ async function poll(
startedAt: number,
engine?: SttEngine,
): Promise<void> {
+ const key = trackerKey(model, engine);
+ const requestedDownloadId = trackedDownloadIds.get(key);
let status: Awaited<ReturnType<typeof fetchSttStatus>>;
try {
status = await fetchSttStatus(
@@ -123,11 +145,32 @@ async function poll(
// A dropped poll is not a failed download; the next one decides.
return;
}
- const key = trackerKey(model, engine);
if (!trackers.has(key)) return;
+ if (trackedDownloadIds.get(key) !== requestedDownloadId) return;
const engineStatus = sttEngineStatusFor(status, model, engine);
const download = engineStatus?.download;
+ if (
+ requestedDownloadId &&
+ download?.download_id &&
+ requestedDownloadId !== download.download_id
+ ) {
+ // Attempt history, not row-level downloaded_models (could be an older quant), decides.
+ if (download.completed_download_ids?.includes(requestedDownloadId)) {
+ settle(model, "complete", undefined, engine);
+ return;
+ }
+ const elapsed = Date.now() - (trackedStartedAt.get(key) ?? startedAt);
+ if (elapsed > START_GRACE_MS) {
+ settle(
+ model,
+ "error",
+ translate("settings.voice.dictation.sttDownloadFailed"),
+ engine,
+ );
+ }
+ return;
+ }
if (download?.downloading && download.model === model) {
updateExternalJob(jobKey(model, engine), {
@@ -151,7 +194,7 @@ async function poll(
settle(model, "complete", undefined, engine);
return;
}
- if (Date.now() - startedAt > START_GRACE_MS) {
+ if (Date.now() - (trackedStartedAt.get(key) ?? startedAt) > START_GRACE_MS) {
settle(
model,
"error",
@@ -161,34 +204,45 @@ async function poll(
}
}
-/** Whether a download is already mirrored, so a poller can adopt one that
- * started before this page load without duplicating the row. */
+/** Adopting an already tracked attempt must not take over its starter's completion policy. */
export function isTrackingSttDownload(
model: SttModel,
engine?: SttEngine,
+ downloadId?: string | null,
): boolean {
- return trackers.has(trackerKey(model, engine ?? sttEngineFor(model)));
+ const key = trackerKey(model, engine ?? sttEngineFor(model));
+ return isSameSttAttempt(
+ trackers.has(key),
+ trackedDownloadIds.get(key),
+ downloadId,
+ );
}
/**
* Mirror an already-started download of `model` into the panel. Any other
* model's download keeps its own row: switching models does not stop it.
*/
-export function trackSttDownload(
+function trackSttDownloadNow(
model: SttModel,
- options: {
- warmSelectedVoiceModelOnComplete?: boolean;
- engine?: SttEngine;
- repoId?: string;
- /** The quant this download fetches, so a quant picked meanwhile is not warmed. */
- ggufVariant?: string | null;
- } = {},
+ options: TrackSttDownloadOptions,
): void {
const resolvedEngine = options.engine ?? sttEngineFor(model);
const key = trackerKey(model, resolvedEngine);
- // Starting/adopting the same transfer from another surface must not reset
- // its visible progress or replace its poller/completion policy.
- if (trackers.has(key)) {
+ const wasTracking = trackers.has(key);
+ const previousDownloadId = trackedDownloadIds.get(key);
+ const changedAttempt =
+ options.downloadId !== undefined &&
+ previousDownloadId !== options.downloadId;
+ if (options.ggufVariant !== undefined) {
+ trackedVariants.set(key, options.ggufVariant);
+ }
+ if (options.downloadId !== undefined) {
+ if (trackedDownloadIds.get(key) !== options.downloadId) {
+ trackedStartedAt.set(key, Date.now());
+ }
+ trackedDownloadIds.set(key, options.downloadId);
+ }
+ if (wasTracking && !changedAttempt) {
if (options.warmSelectedVoiceModelOnComplete !== false)
warmSelectedVoiceModelOnComplete.set(key, true);
return;
@@ -197,9 +251,7 @@ export function trackSttDownload(
key,
options.warmSelectedVoiceModelOnComplete ?? true,
);
- if (options.ggufVariant !== undefined) {
- trackedVariants.set(key, options.ggufVariant);
- }
+ if (!trackedStartedAt.has(key)) trackedStartedAt.set(key, Date.now());
startExternalJob({
key: jobKey(model, resolvedEngine),
repoId: options.repoId ?? getSttModelRepo(model),
@@ -207,7 +259,12 @@ export function trackSttDownload(
expectedBytes: 0,
cancel: async () => {
try {
- await cancelSttDownload(model, resolvedEngine);
+ await cancelSttDownload(
+ model,
+ resolvedEngine,
+ trackedVariants.get(key),
+ trackedDownloadIds.get(key),
+ );
} catch (error) {
toast.error(
translate("settings.voice.dictation.sttCancelDownloadFailed"),
@@ -219,6 +276,7 @@ export function trackSttDownload(
}
},
});
+ if (wasTracking) return;
const startedAt = Date.now();
const timer = window.setInterval(() => {
void poll(model, startedAt, resolvedEngine);
@@ -226,3 +284,85 @@ export function trackSttDownload(
trackers.start(key, () => window.clearInterval(timer));
void poll(model, startedAt, resolvedEngine);
}
+
+async function confirmSttDownloadReplacement(
+ model: SttModel,
+ options: TrackSttDownloadOptions,
+ resolvedEngine: SttEngine,
+ key: string,
+ previousDownloadId: string,
+): Promise<void> {
+ const candidate = options.downloadId;
+ if (!candidate || replacementChecks.get(key) === candidate) return;
+ replacementChecks.set(key, candidate);
+ let retry = false;
+ try {
+ const status = await fetchSttStatus(
+ undefined,
+ resolvedEngine === "transformers" ? model : undefined,
+ );
+ const download = sttEngineStatusFor(status, model, resolvedEngine)?.download;
+ const candidateCompleted =
+ download?.completed_download_ids?.includes(candidate) ?? false;
+ if (download?.download_id === candidate || candidateCompleted) {
+ const current = trackedDownloadIds.get(key);
+ const action = sttReplacementAction(
+ trackers.has(key),
+ current,
+ previousDownloadId,
+ candidate,
+ download?.download_id,
+ candidateCompleted,
+ );
+ if (action === "track") {
+ trackSttDownloadNow(model, options);
+ } else if (action === "retry") {
+ retry = true;
+ }
+ }
+ } catch {
+ retry = true;
+ } finally {
+ if (replacementChecks.get(key) === candidate) replacementChecks.delete(key);
+ }
+ if (retry) {
+ window.setTimeout(() => {
+ if (
+ shouldRecheckSttReplacement(trackedDownloadIds.get(key), candidate)
+ ) {
+ void confirmSttDownloadReplacement(
+ model,
+ options,
+ resolvedEngine,
+ key,
+ previousDownloadId,
+ );
+ }
+ }, POLL_MS);
+ }
+}
+
+export function trackSttDownload(
+ model: SttModel,
+ options: TrackSttDownloadOptions = {},
+): void {
+ const resolvedEngine = options.engine ?? sttEngineFor(model);
+ const key = trackerKey(model, resolvedEngine);
+ const previousDownloadId = trackedDownloadIds.get(key);
+ if (
+ trackers.has(key) &&
+ previousDownloadId &&
+ options.downloadId &&
+ previousDownloadId !== options.downloadId
+ ) {
+ void confirmSttDownloadReplacement(
+ model,
+ options,
+ resolvedEngine,
+ key,
+ previousDownloadId,
+ );
+ return;
+ }
+ trackSttDownloadNow(model, options);
+}
diff --git a/studio/frontend/src/features/settings/lib/stt-download-trackers.ts b/studio/frontend/src/features/settings/lib/stt-download-trackers.ts
index 479a3f85a66..0790e6b76fc 100644
--- a/studio/frontend/src/features/settings/lib/stt-download-trackers.ts
+++ b/studio/frontend/src/features/settings/lib/stt-download-trackers.ts
@@ -25,3 +25,43 @@ export class SttDownloadTrackers {
stop?.();
}
}
+
+export type SttReplacementAction = "track" | "retry" | "ignore";
+
+/** Decide a confirmed replacement without letting an older response displace a newer one. */
+export function sttReplacementAction(
+ hasTracker: boolean,
+ currentDownloadId: string | null | undefined,
+ previousDownloadId: string,
+ candidateDownloadId: string,
+ backendDownloadId: string | null | undefined,
+ candidateCompleted: boolean,
+): SttReplacementAction {
+ if (
+ candidateCompleted &&
+ currentDownloadId &&
+ currentDownloadId === backendDownloadId &&
+ currentDownloadId !== candidateDownloadId
+ )
+ return "ignore";
+ if (!hasTracker || currentDownloadId === previousDownloadId) return "track";
+ if (currentDownloadId === candidateDownloadId || candidateCompleted)
+ return "ignore";
+ return "retry";
+}
+
+export function shouldRecheckSttReplacement(
+ currentDownloadId: string | null | undefined,
+ candidateDownloadId: string,
+): boolean {
+ return currentDownloadId !== candidateDownloadId;
+}
+
+/** An adopter's attempt is already tracked; a missing id (older backend) matches by row. */
+export function isSameSttAttempt(
+ hasTracker: boolean,
+ trackedDownloadId: string | null | undefined,
+ downloadId: string | null | undefined,
+): boolean {
+ return hasTracker && (!downloadId || trackedDownloadId === downloadId);
+}
diff --git a/studio/frontend/src/features/settings/tabs/voice-tab.tsx b/studio/frontend/src/features/settings/tabs/voice-tab.tsx
index 8375c9ad50b..da875b97335 100644
--- a/studio/frontend/src/features/settings/tabs/voice-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/voice-tab.tsx
@@ -770,8 +770,22 @@ export function VoiceTab() {
if (download.downloading) {
// Adopt a transfer that outlived the page that started it, so it
// still shows in the download panel.
- if (download.model && !isTrackingSttDownload(download.model)) {
- trackSttDownload(download.model);
+ if (
+ download.model &&
+ !isTrackingSttDownload(
+ download.model,
+ undefined,
+ download.download_id,
+ )
+ ) {
+ trackSttDownload(download.model, {
+ // Saved keys already encode their quant; only folder rows carry one.
+ ggufVariant: sttModelVariant(
+ download.model,
+ download.variant ?? "",
+ ),
+ downloadId: download.download_id,
+ });
}
watchedDownloadRef.current = download.model;
// Keep the status line fresh.
@@ -910,13 +924,16 @@ export function VoiceTab() {
const beginSttDownload = async () => {
setSttDownloadStarting(true);
try {
- await startSttDownload(
+ const download = await startSttDownload(
sttModel,
hfApiToken(hfToken),
undefined,
sttVariant,
);
- trackSttDownload(sttModel, { ggufVariant: sttVariant });
+ trackSttDownload(sttModel, {
+ ggufVariant: sttVariant,
+ downloadId: download.download_id,
+ });
startedDownloadRef.current = { model: sttModel, variant: sttVariant };
// The status effect only re-polls while it can see a download. Its last read was before this
// one existed, and the on-demand branch schedules nothing, so without a nudge the tab shows
diff --git a/studio/frontend/tests/audio-cpp-catalog.test.ts b/studio/frontend/tests/audio-cpp-catalog.test.ts
index e78760ed4a2..083b89c6942 100644
--- a/studio/frontend/tests/audio-cpp-catalog.test.ts
+++ b/studio/frontend/tests/audio-cpp-catalog.test.ts
@@ -516,7 +516,11 @@ test("an Audio-page ASR pick sends its quant; other engines and saved keys send
adapter,
/return engine === "audiocpp" && ggufVariant\s*\?[\s\S]*\{ gguf_variant: ggufVariant \}\s*:\s*\{\};/,
);
- assert.equal(adapter.match(/\.\.\.sttVariantBody\(resolvedEngine, ggufVariant\)/g)?.length, 2);
+ assert.equal(adapter.match(/\.\.\.sttVariantBody\(resolvedEngine, ggufVariant\)/g)?.length, 3);
+ assert.match(
+ adapter,
+ /body\?\.downloading && body\.cancelled === false[\s\S]*download changed before cancellation completed/,
+ );
const page = readAudioWorkspaceSource();
assert.match(page, /sttGgufVariants\.current\.set\(id\.toLowerCase\(\), meta\.ggufVariant\)/);
assert.match(
@@ -527,6 +531,10 @@ test("an Audio-page ASR pick sends its quant; other engines and saved keys send
page.match(/controller\.signal,\s*undefined,\s*ggufVariant,/g)?.length,
2,
);
+ assert.match(
+ page,
+ /trackSttDownload\(sidecarKey, \{[\s\S]*ggufVariant,[\s\S]*downloadId: download\.download_id,[\s\S]*\}\)/,
+ );
// Settings > Voice sends its saved quant only for package folders.
const voiceTab = readSrc("features/settings/tabs/voice-tab.tsx");
assert.match(
@@ -534,6 +542,10 @@ test("an Audio-page ASR pick sends its quant; other engines and saved keys send
/await startSttDownload\(\s*sttModel,\s*hfApiToken\(hfToken\),\s*undefined,\s*sttVariant,\s*\);/,
);
assert.match(voiceTab, /const sttVariant = sttModelVariant\(sttModel, sttGgufVariant\);/);
+ assert.match(
+ voiceTab,
+ /trackSttDownload\(download\.model, \{[\s\S]*ggufVariant: sttModelVariant\(\s*download\.model,\s*download\.variant \?\? "",\s*\),[\s\S]*downloadId: download\.download_id/,
+ );
});
const GIGAAM = `${AUDIO_CPP_REPO}/GigaAM-ASR-GGUF`;
@@ -613,7 +625,10 @@ test("every Settings dictation path carries the saved quant", () => {
mirror,
/\(tracked === undefined \? variant === null : tracked === variant\)/,
);
- assert.match(voiceTab, /trackSttDownload\(sttModel, \{ ggufVariant: sttVariant \}\)/);
+ assert.match(
+ voiceTab,
+ /trackSttDownload\(sttModel, \{\s*ggufVariant: sttVariant,\s*downloadId: download\.download_id,/,
+ );
// The tab's own watcher loads a landed download only when it is still the pinned quant.
assert.match(voiceTab, /startedDownloadRef\.current = \{ model: sttModel, variant: sttVariant \};/);
assert.match(
@@ -621,7 +636,10 @@ test("every Settings dictation path carries the saved quant", () => {
/started\?\.model === finished\s*\?\s*started\.variant === sttVariant\s*:\s*sttVariant === null;/,
);
assert.match(voiceTab, /!loaded &&\s*landedPinned\s*\)/);
- assert.match(prompt, /trackSttDownload\(request\.model, \{\s*ggufVariant: request\.ggufVariant \?\? null,\s*\}\)/);
+ assert.match(
+ prompt,
+ /trackSttDownload\(request\.model, \{\s*ggufVariant: request\.ggufVariant \?\? null,\s*downloadId: download\.download_id,/,
+ );
assert.match(mirror, /sttModelVariant\(model, sttGgufVariant\)/);
assert.match(mirror, /outcome === "complete" && isAudioCppFolderId\(model\)[\s\S]*invalidateGgufVariantsCache\(model\)/);
@@ -942,3 +960,11 @@ test("only the pinned quant's own listing row can say it is not on disk", () =>
assert.equal(sttListedQuantDownloaded(offline, "v3-ctc/F16"), true);
assert.equal(sttListedQuantDownloaded({ variants: [] }, "small/Q8_0"), true);
});
+
+test("adopting a saved-key audio download keeps it warmable", async () => {
+ const { sttModelVariant } = await import(
+ "../src/features/settings/stores/stt-model-catalog.ts"
+ );
+ assert.equal(sttModelVariant("audiocpp-moonshine-tiny", "tiny/Q8_0"), null);
+ assert.equal(sttModelVariant("audiocpp-moonshine-tiny", ""), null);
+});
diff --git a/studio/frontend/tests/audio-stt-download-fallback.test.ts b/studio/frontend/tests/audio-stt-download-fallback.test.ts
index ebf768322d5..1788c2f5e57 100644
--- a/studio/frontend/tests/audio-stt-download-fallback.test.ts
+++ b/studio/frontend/tests/audio-stt-download-fallback.test.ts
@@ -24,7 +24,7 @@ test("STT download polling uses the available engine fallback", () => {
test("Audio mirrors an STT transfer into Downloads without resetting an adopted job", () => {
assert.match(
source,
- /await startSttDownload\(\s*sidecarKey,[\s\S]*engine,\s*ggufVariant,\s*\);[\s\S]*if \(!isTrackingSttDownload\(sidecarKey, engine\)\) \{[\s\S]*trackSttDownload\(sidecarKey, \{[\s\S]*warmSelectedVoiceModelOnComplete: false,[\s\S]*engine,[\s\S]*repoId,[\s\S]*\}\);[\s\S]*\}[\s\S]*for \(;;\)/,
+ /const download = await startSttDownload\(\s*sidecarKey,[\s\S]*engine,\s*ggufVariant,\s*\);[\s\S]*trackSttDownload\(sidecarKey, \{[\s\S]*warmSelectedVoiceModelOnComplete: false,[\s\S]*engine,[\s\S]*repoId,[\s\S]*ggufVariant,[\s\S]*downloadId: download\.download_id,[\s\S]*\}\);[\s\S]*for \(;;\)/,
);
assert.doesNotMatch(source, /`Downloading \$\{sidecarKey\}:/);
});
@@ -58,7 +58,7 @@ test("resolved Transformers transfers share one tracker identity", () => {
);
assert.match(
mirrorSource,
- /if \(trackers\.has\(key\)\)[\s\S]*warmSelectedVoiceModelOnComplete\.set\(key, true\)/,
+ /if \(wasTracking && !changedAttempt\)[\s\S]*warmSelectedVoiceModelOnComplete\.set\(key, true\)/,
);
});
diff --git a/studio/frontend/tests/stt-download-mirror-policy.test.ts b/studio/frontend/tests/stt-download-mirror-policy.test.ts
index c50cb52183d..a7199fd163a 100644
--- a/studio/frontend/tests/stt-download-mirror-policy.test.ts
+++ b/studio/frontend/tests/stt-download-mirror-policy.test.ts
@@ -11,7 +11,34 @@ const source = readSrc("features/settings/lib/stt-download-mirror.ts");
test("an adopted STT transfer keeps progress and merges its Voice owner", () => {
assert.match(
source,
- /const resolvedEngine = options\.engine \?\? sttEngineFor\(model\);[\s\S]*const key = trackerKey\(model, resolvedEngine\);[\s\S]*if \(trackers\.has\(key\)\) \{[\s\S]*warmSelectedVoiceModelOnComplete\.set\(key, true\);[\s\S]*return;[\s\S]*\}/,
+ /trackedDownloadIds\.set\(key, options\.downloadId\);[\s\S]*if \(wasTracking && !changedAttempt\) \{[\s\S]*warmSelectedVoiceModelOnComplete\.set\(key, true\);[\s\S]*return;/,
+ );
+ assert.match(source, /trackedVariants\.set\(key, options\.ggufVariant\);/);
+ assert.match(source, /startExternalJob\([\s\S]*if \(wasTracking\) return;/);
+ assert.match(
+ source,
+ /const requestedDownloadId = trackedDownloadIds\.get\(key\);[\s\S]*if \(trackedDownloadIds\.get\(key\) !== requestedDownloadId\) return;/,
+ );
+ assert.match(
+ source,
+ /requestedDownloadId !== download\.download_id[\s\S]*elapsed > START_GRACE_MS[\s\S]*settle\(/,
+ );
+ assert.match(
+ source,
+ /completed_download_ids\?\.includes\(requestedDownloadId\)[\s\S]*settle\(model, "complete"/,
+ );
+ assert.match(
+ source,
+ /completed_download_ids\?\.includes\(candidate\)[\s\S]*download\?\.download_id === candidate \|\| candidateCompleted[\s\S]*sttReplacementAction\([\s\S]*action === "track"[\s\S]*trackSttDownloadNow\(model, options\)/,
+ );
+ assert.match(source, /action === "retry"[\s\S]*retry = true/);
+ assert.match(
+ source,
+ /shouldRecheckSttReplacement\(trackedDownloadIds\.get\(key\), candidate\)[\s\S]*confirmSttDownloadReplacement\(/,
+ );
+ assert.match(
+ source,
+ /previousDownloadId !== options\.downloadId[\s\S]*confirmSttDownloadReplacement\(/,
);
});
@@ -27,7 +54,10 @@ test("non-default STT engines have independent jobs", () => {
source,
/engine && engine !== "transformers" \? `\$\{engine\}:\$\{model\}` : model/,
);
- assert.match(source, /cancelSttDownload\(model, resolvedEngine\)/);
+ assert.match(
+ source,
+ /cancelSttDownload\([\s\S]*model,[\s\S]*resolvedEngine,[\s\S]*trackedVariants\.get\(key\),[\s\S]*trackedDownloadIds\.get\(key\),[\s\S]*\)/,
+ );
assert.match(
source,
/engine === undefined \|\| engine === "transformers" \? model : undefined/,
@@ -40,7 +70,10 @@ test("an explicit Transformers transfer keeps its serving engine", () => {
source,
/const resolvedEngine = options\.engine \?\? sttEngineFor\(model\)/,
);
- assert.match(source, /cancelSttDownload\(model, resolvedEngine\)/);
+ assert.match(
+ source,
+ /cancelSttDownload\([\s\S]*model,[\s\S]*resolvedEngine,[\s\S]*trackedVariants\.get\(key\),[\s\S]*trackedDownloadIds\.get\(key\),[\s\S]*\)/,
+ );
assert.match(source, /poll\(model, startedAt, resolvedEngine\)/);
assert.doesNotMatch(
source,
diff --git a/studio/frontend/tests/stt-download-trackers.test.ts b/studio/frontend/tests/stt-download-trackers.test.ts
index b689ed8d0e7..e2a798fc366 100644
--- a/studio/frontend/tests/stt-download-trackers.test.ts
+++ b/studio/frontend/tests/stt-download-trackers.test.ts
@@ -4,7 +4,12 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { SttDownloadTrackers } from "../src/features/settings/lib/stt-download-trackers.ts";
+import {
+ isSameSttAttempt,
+ shouldRecheckSttReplacement,
+ SttDownloadTrackers,
+ sttReplacementAction,
+} from "../src/features/settings/lib/stt-download-trackers.ts";
test("a second model's download does not stop the first", () => {
const trackers = new SttDownloadTrackers();
@@ -48,3 +53,97 @@ test("stopping an untracked model is a no-op", () => {
trackers.stop("whisper-small");
assert.equal(trackers.has("whisper-small"), false);
});
+
+test("an authoritative replacement survives its previous tracker settling", () => {
+ assert.equal(
+ sttReplacementAction(
+ false,
+ undefined,
+ "attempt-x",
+ "attempt-y",
+ "attempt-y",
+ false,
+ ),
+ "track",
+ );
+});
+
+test("replacement confirmation cannot displace a newer local attempt", () => {
+ assert.equal(
+ sttReplacementAction(
+ true,
+ "attempt-z",
+ "attempt-x",
+ "attempt-y",
+ "attempt-y",
+ false,
+ ),
+ "retry",
+ );
+ assert.equal(
+ sttReplacementAction(
+ true,
+ "attempt-y",
+ "attempt-x",
+ "attempt-y",
+ "attempt-y",
+ false,
+ ),
+ "ignore",
+ );
+});
+
+test("a completed candidate settles unless a newer local attempt already owns the row", () => {
+ assert.equal(
+ sttReplacementAction(
+ false,
+ undefined,
+ "attempt-a",
+ "attempt-b",
+ "attempt-c",
+ true,
+ ),
+ "track",
+ );
+ assert.equal(
+ sttReplacementAction(
+ true,
+ "attempt-c",
+ "attempt-a",
+ "attempt-b",
+ "attempt-c",
+ true,
+ ),
+ "ignore",
+ );
+ assert.equal(
+ sttReplacementAction(
+ true,
+ "attempt-c",
+ "attempt-c",
+ "attempt-b",
+ "attempt-c",
+ true,
+ ),
+ "ignore",
+ );
+});
+
+test("a transient confirmation failure retries after the prior tracker settles", () => {
+ assert.equal(shouldRecheckSttReplacement(undefined, "attempt-y"), true);
+ assert.equal(
+ shouldRecheckSttReplacement("attempt-x", "attempt-y"),
+ true,
+ );
+ assert.equal(
+ shouldRecheckSttReplacement("attempt-y", "attempt-y"),
+ false,
+ );
+});
+
+test("adopting an already tracked attempt leaves its owner's policy alone", () => {
+ assert.equal(isSameSttAttempt(true, "a", "a"), true);
+ assert.equal(isSameSttAttempt(true, "a", undefined), true);
+ assert.equal(isSameSttAttempt(true, "a", "b"), false);
+ assert.equal(isSameSttAttempt(false, undefined, "a"), false);
+});