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.

Unsloth Desktop/Studio audio: follow-ups from testing the Clone, Transcribe, Edit, Separate and Convert pages (#12706)

Leo Borcherding0108742f1ec5
diff --git a/studio/backend/core/inference/audio_cpp_backend.py b/studio/backend/core/inference/audio_cpp_backend.py
index 27567b1e152..d1485798395 100644
--- a/studio/backend/core/inference/audio_cpp_backend.py
+++ b/studio/backend/core/inference/audio_cpp_backend.py
@@ -67,6 +67,38 @@ def _raise_if_cancelled(cancel_event) -> None:
raise AudioGenerationCancelledError("Audio generation cancelled")
+_inflight_lock = threading.Lock()
+_inflight: dict[tuple[str, str, str], tuple[threading.Event, list]] = {}
+
+
+def _download_or_cancel(key, download, cancel_event) -> None:
+ """hf_hub_download has no cancel hook: it runs on its own thread and the caller stops waiting on
+ cancel. The thread still finishes into the Hub cache; a retry meanwhile joins it."""
+ with _inflight_lock:
+ flight = _inflight.get(key)
+ if flight is None:
+ flight = _inflight[key] = (threading.Event(), [])
+ done, failure = flight
+
+ def run():
+ try:
+ download()
+ except BaseException as exc: # noqa: BLE001 - re-raised on the caller's thread
+ failure.append(exc)
+ finally:
+ with _inflight_lock:
+ _inflight.pop(key, None)
+ done.set()
+
+ threading.Thread(target = run, name = "audio-cpp-download", daemon = True).start()
+ done, failure = flight
+ while not done.wait(0.2):
+ if cancel_event.is_set():
+ raise AudioCppRequestCancelledError("Request cancelled.")
+ if failure:
+ raise failure[0]
+
+
def _wav_seconds(path: str) -> float:
with wave.open(str(path)) as w:
rate = w.getframerate()
@@ -352,7 +384,11 @@ class AudioCppBackend:
forget(companion.id)
@staticmethod
- def _download_missing(model: AudioCppModel, hf_token: Optional[str]) -> bool:
+ def _download_missing(
+ model: AudioCppModel,
+ hf_token: Optional[str],
+ cancel_event = None,
+ ) -> bool:
missing = audio_cpp_files.missing_files(model)
if not missing:
return False
@@ -362,13 +398,23 @@ class AudioCppBackend:
cache_dir = str(active_hf_hub_cache())
for path, _size in missing:
+ if cancel_event is not None and cancel_event.is_set():
+ raise AudioCppRequestCancelledError("Request cancelled.")
logger.info("audio.cpp: downloading %s from %s", path, model.repo_id)
- hf_hub_download(
- model.repo_id,
- path,
- token = hf_token or None,
- cache_dir = cache_dir,
- )
+
+ def fetch(path = path):
+ hf_hub_download(
+ model.repo_id,
+ path,
+ token = hf_token or None,
+ cache_dir = cache_dir,
+ )
+
+ if cancel_event is None:
+ fetch()
+ else:
+ # Cache root in the key: a retry after the cache moved must not join the old transfer.
+ _download_or_cancel((cache_dir, model.repo_id, path), fetch, cancel_event)
return True
def _start_server(
diff --git a/studio/backend/core/inference/audio_cpp_outputs.py b/studio/backend/core/inference/audio_cpp_outputs.py
index bebef68ba30..46aefbfbe7a 100644
--- a/studio/backend/core/inference/audio_cpp_outputs.py
+++ b/studio/backend/core/inference/audio_cpp_outputs.py
@@ -106,11 +106,13 @@ def _span_index(item: dict) -> Optional[int]:
def safe_stem_id(raw: Any, taken: set[str]) -> str:
- """A file-safe id (``[A-Za-z0-9_-]{1,64}``), unique among ``taken`` by a ``_2`` style suffix."""
+ """A file-safe id (``[A-Za-z0-9_-]{1,64}``), unique among ``taken`` by a ``_2`` style suffix,
+ ignoring case (Windows and macOS read ``Vocals.wav`` as ``vocals.wav``)."""
base = _ID_UNSAFE_RE.sub("_", str(raw or "").strip())[:64] or "stem"
+ seen = {item.casefold() for item in taken}
stem_id = base
n = 2
- while stem_id in taken:
+ while stem_id.casefold() in seen:
suffix = f"_{n}"
stem_id = base[: 64 - len(suffix)] + suffix
n += 1
diff --git a/studio/backend/core/inference/audio_edit.py b/studio/backend/core/inference/audio_edit.py
index 6fcfadeaadb..f7220cbe4e1 100644
--- a/studio/backend/core/inference/audio_edit.py
+++ b/studio/backend/core/inference/audio_edit.py
@@ -11,6 +11,7 @@ from __future__ import annotations
import re
import time
+from collections import Counter
from pathlib import Path
from typing import Any, Optional, Sequence
@@ -23,6 +24,7 @@ EDIT_SOURCE_MAX_SECONDS = 30.0
TOO_LONG = "Edit works on recordings up to 30 s. Record or upload a shorter take."
NO_CHANGE = "Change at least one word."
+EMPTY_TARGET = "Keep at least one word."
MISMATCH = "The changes do not match the transcript. Check ① and ② again."
UNKNOWN_INSTRUCTION = "That change is not one FireRedAudio understands."
NEEDS_DELIVERY_MODEL = "Delivery changes need FireRedAudio."
@@ -93,7 +95,8 @@ def check_instructions(
label: str = "FireRedAudio",
) -> Optional[str]:
"""Why FireRedAudio ``instructions`` are refused; None when each is a known form whose old words
- (or anchor) are in ``original`` and new words in ``edited``."""
+ (or anchor) are in ``original`` and new words in ``edited``, and the words they remove and add
+ turn the one transcript into the other."""
items = list(instructions or ())
if not items:
return NO_CHANGE
@@ -103,21 +106,35 @@ def check_instructions(
"Make fewer changes, or use DotTTS Edit."
)
before, after = _collapse(original), _collapse(edited)
+ # Runtime gets the instructions, history gets ``edited``: they must agree as bags of words
+ # (which occurrence of a repeated word is meant is the runtime's call).
+ words = Counter(before.split())
for instruction in items:
match = INSTRUCTION_RE.match(str(instruction))
if match is None:
return UNKNOWN_INSTRUCTION
old, new, deleted, inserted, anchor = match.groups()
if old is not None:
- olds, news = [old], [new]
+ olds, news, removed = [old], [new], [old]
elif deleted is not None:
- olds, news = [deleted], []
+ olds, news, removed = [deleted], [], [deleted]
else:
- olds, news = [anchor], [inserted]
+ olds, news, removed = [anchor], [inserted], []
if not all(_collapse(o) and _collapse(o) in before for o in olds):
return MISMATCH
if not all(_collapse(n) and _collapse(n) in after for n in news):
return MISMATCH
+ # Running bag, not the transcript: a word an earlier instruction removed is gone.
+ if not all(words[token] > 0 for o in olds for token in o.split()):
+ return MISMATCH
+ for phrase in removed:
+ words.subtract(phrase.split())
+ if any(count < 0 for count in words.values()):
+ return MISMATCH
+ for phrase in news:
+ words.update(phrase.split())
+ if +words != Counter(after.split()):
+ return MISMATCH
return None
@@ -159,11 +176,15 @@ def request_problem(
if not delivery_instructions(edit.get("speed"), edit.get("pitch_steps")):
return NO_DELIVERY
return None
+ # Before the per-style checks: a no-op such as <sub targ="x">x</sub> passes them.
+ if style in ("markup", "instructions", "sentence"):
+ if not _collapse(text):
+ return EMPTY_TARGET
+ if _collapse(text) == _collapse(original):
+ return NO_CHANGE
if style == "markup":
markup = edit.get("markup")
if not markup:
- if _collapse(text) == _collapse(original):
- return NO_CHANGE
return f"{label} needs the marked-up changes."
return check_markup(markup, original, text)
if style == "instructions":
@@ -171,8 +192,6 @@ def request_problem(
edit.get("instructions") or (), original, text, rules.get("max_changes"), label
)
if style == "sentence":
- if original.strip() and _collapse(text) == _collapse(original):
- return NO_CHANGE
return None
return "Load a model that can edit speech."
diff --git a/studio/backend/core/inference/stt_audiocpp_sidecar.py b/studio/backend/core/inference/stt_audiocpp_sidecar.py
index 17c5f207596..0ebdb566363 100644
--- a/studio/backend/core/inference/stt_audiocpp_sidecar.py
+++ b/studio/backend/core/inference/stt_audiocpp_sidecar.py
@@ -727,6 +727,7 @@ class AudioCppSttSidecar:
self,
entry: AudioCppModel,
on_phase: Optional[Callable[[str], None]] = None,
+ cancel_event: Optional[threading.Event] = None,
) -> None:
from core.inference import audio_cpp_backend
@@ -739,7 +740,9 @@ class AudioCppSttSidecar:
_notify(on_phase, "downloading_aligner")
try:
aligner = audio_cpp_backend._resolve_companion(entry, QWEN3_ALIGNER, network = True)
- audio_cpp_backend.AudioCppBackend._download_missing(aligner, None)
+ audio_cpp_backend.AudioCppBackend._download_missing(aligner, None, cancel_event)
+ except AudioCppRequestCancelledError:
+ raise SttTranscriptionCancelledError("Transcription cancelled.") from None
except Exception as exc: # noqa: BLE001 - every failure reads the same to the user
reason = sanitize_runtime_detail(str(exc)) or type(exc).__name__
logger.warning("audio.cpp: timestamp aligner download failed: %s", reason)
@@ -808,7 +811,7 @@ class AudioCppSttSidecar:
model_path = self._ensure_model_downloaded(entry)
served = entry
if aligned:
- self._ensure_aligner_downloaded(entry, on_phase)
+ self._ensure_aligner_downloaded(entry, on_phase, request_cancel_event)
served = self._with_aligner(entry)
cancel_event = (
request_cancel_event if request_cancel_event is not None else threading.Event()
@@ -887,11 +890,13 @@ class AudioCppSttSidecar:
self,
model: Optional[str],
on_phase: Optional[Callable[[str], None]] = None,
+ cancel_event: Optional[threading.Event] = None,
) -> None:
- """Runs before the load so a 1.1 GB download holds neither the load lock nor dictation."""
+ """Runs before the load so a 1.1 GB download holds neither the load lock nor dictation.
+ Takes the request's cancel event: this is the call that does the first download."""
entry = resolve_audio_cpp_stt_model(self.keep_loaded_variant(model))
if entry.family in _ALIGNED_FAMILIES:
- self._ensure_aligner_downloaded(entry, on_phase)
+ self._ensure_aligner_downloaded(entry, on_phase, cancel_event)
def transcribe_path(
self,
diff --git a/studio/backend/core/inference/stt_details.py b/studio/backend/core/inference/stt_details.py
index 8c044892152..bdbcda15d6b 100644
--- a/studio/backend/core/inference/stt_details.py
+++ b/studio/backend/core/inference/stt_details.py
@@ -231,6 +231,10 @@ def normalize(payload: dict, family: str, sent_rate: int) -> dict:
turns = _turns(payload.get("speaker_turns"), rate)
if not segments and turns:
segments = _segments(payload.get("speaker_turns"), rate)
+ # Diarized answers can come grouped per speaker; the player assumes time order.
+ _by_time = lambda span: (span["start"], span["end"]) # noqa: E731
+ words.sort(key = _by_time)
+ segments.sort(key = _by_time)
native_segments = bool(segments)
if turns:
_assign_speakers(segments, turns)
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index d67eb9b5cbf..370abd48bb9 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -22411,6 +22411,19 @@ def _audio_source_error(exc) -> HTTPException:
return HTTPException(status_code = exc.status, detail = exc.detail)
+CONVERT_EXPIRED_DETAIL = {
+ "source": "This recording expired. Add it again.",
+ "target": "This target voice expired. Add it again.",
+}
+
+
+def _convert_role_error(exc, role: str):
+ from core.inference.audio_inputs import AudioInputError
+ if exc.status == 404 and exc.detail == "This reference expired. Add it again.":
+ return AudioInputError(404, CONVERT_EXPIRED_DETAIL[role])
+ return exc
+
+
def _audio_run_settings(body: AudioRunRequest, reference_text_used: bool) -> dict[str, Any]:
"""The run's recipe for history: scalar options only."""
options = {
@@ -22895,14 +22908,16 @@ async def _run_audio_convert(
if refs["source"] is None:
raise HTTPException(status_code = 400, detail = "Add the recording to convert.")
resolved: dict[str, Any] = {}
- try:
- for role, ref in refs.items():
- if ref is not None:
- resolved[role] = await asyncio.to_thread(
- audio_inputs.resolve_source, ref.model_dump(exclude_none = True)
- )
- except audio_inputs.AudioInputError as exc:
- raise _audio_source_error(exc) from None
+ for role, ref in refs.items():
+ if ref is None:
+ continue
+ try:
+ resolved[role] = await asyncio.to_thread(
+ audio_inputs.resolve_source, ref.model_dump(exclude_none = True)
+ )
+ except audio_inputs.AudioInputError as exc:
+ # Names the side so the page marks only the card that expired.
+ raise _audio_source_error(_convert_role_error(exc, role)) from None
source, target = resolved["source"], resolved.get("target")
max_seconds = {"source": CONVERT_SOURCE_MAX_SECONDS, "target": CONVERT_TARGET_MAX_SECONDS}
seen: dict[str, Any] = {}
@@ -24516,7 +24531,7 @@ async def _transcribe_audio_result(
)
load_options = {"on_phase": on_phase} if on_phase is not None else {}
if source_path is not None and timestamps:
- await asyncio.to_thread(sidecar.ensure_aligner, model, on_phase)
+ await asyncio.to_thread(sidecar.ensure_aligner, model, on_phase, cancel_event)
# Started with its aligner now, or transcribe_path would restart it.
load_options["timestamps"] = True
await asyncio.to_thread(
diff --git a/studio/backend/tests/test_audio_cpp_outputs.py b/studio/backend/tests/test_audio_cpp_outputs.py
index 807035c6dce..6633b02e55c 100644
--- a/studio/backend/tests/test_audio_cpp_outputs.py
+++ b/studio/backend/tests/test_audio_cpp_outputs.py
@@ -59,6 +59,13 @@ def _stems(ids):
return [{"id": i, "audio": _b64(_wav()), "sample_rate": RATE, "channels": 2} for i in ids]
+def test_stem_ids_differing_only_by_case_get_their_own_files(tmp_path):
+ path, out = _answer(tmp_path, {"named_audio_outputs": _stems(["Vocals", "vocals", "VOCALS"])})
+ outputs = extract_named_outputs(path, out)
+ assert [o["id"] for o in outputs] == ["Vocals", "vocals_2", "VOCALS_3"]
+ assert len({o["path"].lower() for o in outputs}) == 3
+
+
@pytest.mark.parametrize(
"ids",
[
diff --git a/studio/backend/tests/test_audio_edit_requests.py b/studio/backend/tests/test_audio_edit_requests.py
index 4365869dd99..28a0b30a356 100644
--- a/studio/backend/tests/test_audio_edit_requests.py
+++ b/studio/backend/tests/test_audio_edit_requests.py
@@ -281,6 +281,13 @@ def test_check_instructions():
# Words that are not in the transcripts.
(["Replace 'alien' with 'robot'."], EDITED, mismatch),
(["Replace 'human' with 'cat'."], EDITED, mismatch),
+ (["Replace 'Cemo' with 'human'."],
+ ORIGINAL.replace("Cemo", "human").replace("a human voice", "a Cemo voice"), mismatch),
+ (["Replace 'human' with 'robot'."], EDITED, mismatch),
+ (["Delete 'Okay,'."], ORIGINAL.replace("Okay, I'm", "I'm Okay,"), mismatch),
+ (["Replace 'human' with 'robot'."], ORIGINAL.replace("human", "robot"), None),
+ (["Delete 'human'.", "Delete 'human'."], ORIGINAL.replace("a human voice", "a voice"), mismatch),
+ (["Delete 'human'.", "Insert 'robot' before 'human'."], ORIGINAL.replace("human", "robot"), mismatch),
):
check = audio_edit.check_instructions(instructions, ORIGINAL, edited, 5, "FireRedAudio")
assert check == problem, instructions
@@ -309,6 +316,11 @@ def test_request_problem_per_style():
(firered, {"mode": "delivery", "speed": 1.0}, EDITED, ORIGINAL, "Pick a speed or a pitch change."),
(firered, {"mode": "delivery", "pitch_steps": 3}, ORIGINAL, ORIGINAL, None),
(firered, words, EDITED, ORIGINAL, no_change),
+ (dots, {"mode": "words", "markup": "<del>" + ORIGINAL + "</del>"}, " ", ORIGINAL, audio_edit.EMPTY_TARGET),
+ (vevo, words, "", ORIGINAL, audio_edit.EMPTY_TARGET),
+ (firered, {"mode": "words", "instructions": ["Delete 'a'."]}, " ", ORIGINAL, audio_edit.EMPTY_TARGET),
+ (dots, {"mode": "words", "markup": ORIGINAL.replace("Cemo", '<sub targ="Cemo">Cemo</sub>')}, ORIGINAL, ORIGINAL, no_change),
+ (firered, {"mode": "words", "instructions": ["Replace 'Cemo' with 'Cemo'."]}, ORIGINAL, ORIGINAL, no_change),
):
assert audio_edit.request_problem(rules, edit, text, reference, "DotTTS-Edit") == problem
# fmt: on
diff --git a/studio/backend/tests/test_audio_run_route.py b/studio/backend/tests/test_audio_run_route.py
index 071358632db..69cd178037e 100644
--- a/studio/backend/tests/test_audio_run_route.py
+++ b/studio/backend/tests/test_audio_run_route.py
@@ -1797,3 +1797,15 @@ def test_a_repaint_past_the_end_sizes_its_work_to_the_range_end(stub):
assert short.status_code == 200 and long.status_code == 200, long.text
first, second = backend.calls
assert second["music"]["timeout_s"] > first["music"]["timeout_s"]
+
+
+def test_a_convert_expiry_names_the_side_that_expired():
+ """Both uploads shared "This reference expired", so the page marked both cards when one went."""
+ from core.inference.audio_inputs import AudioInputError
+ from routes.inference import CONVERT_EXPIRED_DETAIL, _convert_role_error
+
+ gone = AudioInputError(404, "This reference expired. Add it again.")
+ assert _convert_role_error(gone, "source").detail == CONVERT_EXPIRED_DETAIL["source"]
+ assert _convert_role_error(gone, "target").detail == CONVERT_EXPIRED_DETAIL["target"]
+ other = AudioInputError(404, "That clip is gone.")
+ assert _convert_role_error(other, "target") is other
diff --git a/studio/backend/tests/test_stt_audiocpp_details.py b/studio/backend/tests/test_stt_audiocpp_details.py
index 99875f379a6..1ef33ee75a3 100644
--- a/studio/backend/tests/test_stt_audiocpp_details.py
+++ b/studio/backend/tests/test_stt_audiocpp_details.py
@@ -201,7 +201,9 @@ def test_qwen3_aligner_is_downloaded_loaded_once_and_kept(fake, side, source, hu
return real_resolve(model, companion, hf_token, network = False)
monkeypatch.setattr(audio_cpp_backend, "_resolve_companion", resolve)
- download = staticmethod(lambda model, token: downloads.append(model.id) or True)
+ download = staticmethod(
+ lambda model, token, cancel_event = None: downloads.append(model.id) or True
+ )
monkeypatch.setattr(audio_cpp_backend.AudioCppBackend, "_download_missing", download)
def run(**kwargs):
@@ -236,6 +238,199 @@ def test_qwen3_aligner_is_downloaded_loaded_once_and_kept(fake, side, source, hu
assert len(fake.starts) == 2 and all("options" not in b for b in fake.bodies[-2:])
+def test_stop_during_the_aligner_download_cancels_it(fake, side, source, hub, monkeypatch):
+ """Stop while "Downloading the timing aligner" only cancelled the transcription that never
+ started; the download itself read no cancel event and kept streaming."""
+ import threading
+
+ from core.inference.audio_cpp_backend import AudioCppRequestCancelledError
+ from core.inference.audio_cpp_backend import AudioCppBackend as backend_cls
+
+ import inspect
+
+ assert "cancel_event.is_set()" in inspect.getsource(backend_cls._download_missing)
+ real_resolve = audio_cpp_backend._resolve_companion
+
+ def resolve(
+ model,
+ companion,
+ hf_token = None,
+ *,
+ network = True,
+ ):
+ if network:
+ _add(hub, ALIGNER_FILE, "qwen3_forced_aligner")
+ return real_resolve(model, companion, hf_token, network = False)
+
+ monkeypatch.setattr(audio_cpp_backend, "_resolve_companion", resolve)
+ seen = []
+
+ def download(
+ model,
+ token,
+ cancel_event = None,
+ ):
+ seen.append(cancel_event)
+ cancel_event.set()
+ raise AudioCppRequestCancelledError("Request cancelled.")
+
+ monkeypatch.setattr(backend_cls, "_download_missing", staticmethod(download))
+ cancel = threading.Event()
+ with pytest.raises(stt.SttTranscriptionCancelledError):
+ side.transcribe_path(source, QWEN3, None, timestamps = True, cancel_event = cancel)
+ assert seen == [cancel]
+
+
+def test_the_aligner_preflight_carries_the_request_cancel(fake, side, source, hub, monkeypatch):
+ """The route's preflight (``ensure_aligner``) is the call that does the first 1.1 GB download;
+ without the event it ran uncancellable and the forwarding in ``load`` came too late."""
+ import threading
+
+ from core.inference.audio_cpp_backend import AudioCppBackend as backend_cls
+
+ real_resolve = audio_cpp_backend._resolve_companion
+
+ def resolve(
+ model,
+ companion,
+ hf_token = None,
+ *,
+ network = True,
+ ):
+ if network:
+ _add(hub, ALIGNER_FILE, "qwen3_forced_aligner")
+ return real_resolve(model, companion, hf_token, network = False)
+
+ monkeypatch.setattr(audio_cpp_backend, "_resolve_companion", resolve)
+ seen = []
+ monkeypatch.setattr(
+ backend_cls,
+ "_download_missing",
+ staticmethod(lambda model, token, cancel_event = None: seen.append(cancel_event)),
+ )
+ cancel = threading.Event()
+ side.ensure_aligner(QWEN3, None, cancel)
+ assert seen == [cancel]
+
+
+def test_stop_mid_file_returns_before_the_download_finishes(monkeypatch):
+ """The aligner is one 1.1 GB file, so a check between files never fires while it streams. The
+ download runs on its own thread and the caller returns on Stop while the file is still coming."""
+ import threading
+ from types import SimpleNamespace
+
+ from core.inference.audio_cpp_backend import AudioCppRequestCancelledError
+ from core.inference.audio_cpp_backend import AudioCppBackend as backend_cls
+
+ entered, release = threading.Event(), threading.Event()
+
+ def streaming(*_args, **_kwargs):
+ entered.set()
+ release.wait(10)
+
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", streaming)
+ monkeypatch.setattr(
+ audio_cpp_backend.audio_cpp_files, "missing_files", lambda model: [("aligner.gguf", 1)]
+ )
+ cancel = threading.Event()
+ threading.Timer(0.3, cancel.set).start()
+ with pytest.raises(AudioCppRequestCancelledError):
+ backend_cls._download_missing(SimpleNamespace(repo_id = "org/aligner"), None, cancel)
+ assert entered.is_set() and not release.is_set()
+ release.set()
+
+
+def test_a_retry_joins_the_download_that_stop_left_running(monkeypatch):
+ """Stop then retry: the file is still missing, so without sharing the retry would start a second
+ transfer of the same 1.1 GB and each cycle would leave another thread behind."""
+ import threading
+ from types import SimpleNamespace
+
+ from core.inference.audio_cpp_backend import AudioCppRequestCancelledError
+ from core.inference.audio_cpp_backend import AudioCppBackend as backend_cls
+
+ release, calls = threading.Event(), []
+
+ def streaming(*_args, **_kwargs):
+ calls.append(1)
+ release.wait(10)
+
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", streaming)
+ monkeypatch.setattr(
+ audio_cpp_backend.audio_cpp_files, "missing_files", lambda model: [("aligner.gguf", 1)]
+ )
+ model = SimpleNamespace(repo_id = "org/aligner")
+ stopped = threading.Event()
+ threading.Timer(0.3, stopped.set).start()
+ with pytest.raises(AudioCppRequestCancelledError):
+ backend_cls._download_missing(model, None, stopped)
+ outcome = []
+ retry = threading.Thread(
+ target = lambda: outcome.append(backend_cls._download_missing(model, None, threading.Event()))
+ )
+ retry.start()
+ threading.Timer(0.3, release.set).start()
+ retry.join(10)
+ assert outcome == [True]
+ assert calls == [1]
+ assert audio_cpp_backend._inflight == {}
+
+
+def test_a_retry_into_a_relocated_cache_starts_its_own_download(monkeypatch):
+ """Joining is keyed by cache root too: after Stop, a retry with the Hub cache moved in Settings
+ would otherwise wait on a transfer writing into the old cache and report the new one filled."""
+ import threading
+ from pathlib import Path
+ from types import SimpleNamespace
+
+ from core.inference.audio_cpp_backend import AudioCppRequestCancelledError
+ from core.inference.audio_cpp_backend import AudioCppBackend as backend_cls
+ from utils import hf_cache_settings
+
+ release, cache_dirs = threading.Event(), []
+
+ def streaming(*_args, cache_dir, **_kwargs):
+ cache_dirs.append(cache_dir)
+ release.wait(10)
+
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", streaming)
+ monkeypatch.setattr(
+ audio_cpp_backend.audio_cpp_files, "missing_files", lambda model: [("aligner.gguf", 1)]
+ )
+ monkeypatch.setattr(hf_cache_settings, "active_hf_hub_cache", lambda: Path("/cache/old"))
+ model = SimpleNamespace(repo_id = "org/aligner")
+ stopped = threading.Event()
+ threading.Timer(0.3, stopped.set).start()
+ with pytest.raises(AudioCppRequestCancelledError):
+ backend_cls._download_missing(model, None, stopped)
+ monkeypatch.setattr(hf_cache_settings, "active_hf_hub_cache", lambda: Path("/cache/new"))
+ stopped = threading.Event()
+ threading.Timer(0.3, stopped.set).start()
+ with pytest.raises(AudioCppRequestCancelledError):
+ backend_cls._download_missing(model, None, stopped)
+ assert [Path(c).name for c in cache_dirs] == ["old", "new"]
+ release.set()
+
+
+def test_a_download_error_still_reaches_the_caller_with_a_cancel_event(monkeypatch):
+ import threading
+ from types import SimpleNamespace
+
+ from core.inference.audio_cpp_backend import AudioCppBackend as backend_cls
+
+ def failing(*_args, **_kwargs):
+ raise OSError("disk full")
+
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", failing)
+ monkeypatch.setattr(
+ audio_cpp_backend.audio_cpp_files, "missing_files", lambda model: [("aligner.gguf", 1)]
+ )
+ with pytest.raises(OSError, match = "disk full"):
+ backend_cls._download_missing(
+ SimpleNamespace(repo_id = "org/aligner"), None, threading.Event()
+ )
+
+
def test_an_aligner_download_failure_says_how_to_go_on(fake, side, source, monkeypatch):
def offline(*_args, **_kwargs):
raise RuntimeError(
diff --git a/studio/backend/tests/test_stt_details.py b/studio/backend/tests/test_stt_details.py
index a4f25759b42..0d8c1bc6c0d 100644
--- a/studio/backend/tests/test_stt_details.py
+++ b/studio/backend/tests/test_stt_details.py
@@ -182,3 +182,24 @@ def test_cjk_text_keeps_its_punctuation_through_alignment(split):
# Qwen3-ASR's punctuated Chinese has no spaces; the aligner splits it into words.
result = stt_details.normalize(_payload(_seq(split, 0.3), "你好,世界。"), "qwen3_asr", 16000)
assert result["text"] == "你好,世界。" and result["segments"][0]["text"] == "你好,世界。"
+
+
+def test_spans_come_back_in_time_order_whatever_order_the_runtime_used():
+ """A diarized answer grouped per speaker left segments out of order, and the player's binary
+ search and paragraph merge both assume time order."""
+ payload = {
+ "text": "a b c",
+ "sample_rate": 16000,
+ "segments": [
+ {"start_sample": 80000, "end_sample": 96000, "text": "c"},
+ {"start_sample": 0, "end_sample": 16000, "text": "a"},
+ {"start_sample": 32000, "end_sample": 48000, "text": "b"},
+ ],
+ "words": [
+ {"start_sample": 32000, "end_sample": 48000, "word": "b"},
+ {"start_sample": 0, "end_sample": 16000, "word": "a"},
+ ],
+ }
+ result = stt_details.normalize(payload, "moss_transcribe_diarize", 16000)
+ assert [s["start"] for s in result["segments"]] == [0.0, 2.0, 5.0]
+ assert [w["word"] for w in result["words"]] == ["a", "b"]
diff --git a/studio/backend/tests/test_transcribe_source_route.py b/studio/backend/tests/test_transcribe_source_route.py
index 579f9b13dfe..1a7fc7681aa 100644
--- a/studio/backend/tests/test_transcribe_source_route.py
+++ b/studio/backend/tests/test_transcribe_source_route.py
@@ -40,8 +40,14 @@ class _Sidecar:
self.result.update(segments = SEGMENTS, speakers = ["S01", "S02"])
self.paths, self.bytes, self.events, self.loads = [], [], [], []
- def ensure_aligner(self, model, on_phase):
+ def ensure_aligner(
+ self,
+ model,
+ on_phase,
+ cancel_event = None,
+ ):
self.events.append(("aligner", model))
+ self.aligner_cancel = cancel_event
def transcribe_path(self, path, model, language, *, timestamps, cancel_event, on_phase):
on_phase("transcribing")
@@ -159,6 +165,7 @@ def test_qwen3_timestamps_are_asked_of_the_sidecar(stub):
assert stub.paths[0][2] is True
# The aligner is fetched first and the server starts with it: one load, not two.
assert stub.events == [("aligner", QWEN3), ("load", True)]
+ assert stub.aligner_cancel is not None
assert complete["timestamps"] is False and "segments" not in complete
diff --git a/studio/frontend/src/features/audio/api.ts b/studio/frontend/src/features/audio/api.ts
index 22b05a615fb..08ea23954ff 100644
--- a/studio/frontend/src/features/audio/api.ts
+++ b/studio/frontend/src/features/audio/api.ts
@@ -396,6 +396,21 @@ export async function uploadAudioInput(
return parseAudioJson<AudioInputRecord>(response);
}
+/** Whether an upload is still on the server; anything but a 404 counts as alive.
+ * GET, not HEAD: the FastAPI route answers HEAD with 405, which would read as alive. */
+export async function audioInputAlive(inputId: string): Promise<boolean> {
+ try {
+ const response = await authFetch(
+ `/api/inference/audio/inputs/${encodeURIComponent(inputId)}/file`,
+ { headers: { Range: "bytes=0-0" } },
+ );
+ void response.body?.cancel().catch(() => undefined);
+ return response.status !== 404;
+ } catch {
+ return true;
+ }
+}
+
export async function fetchAudioBlob(
url: string,
signal?: AbortSignal,
diff --git a/studio/frontend/src/features/audio/audio-cpp-catalog.ts b/studio/frontend/src/features/audio/audio-cpp-catalog.ts
index 16bcce7063e..536e4ae161c 100644
--- a/studio/frontend/src/features/audio/audio-cpp-catalog.ts
+++ b/studio/frontend/src/features/audio/audio-cpp-catalog.ts
@@ -131,6 +131,19 @@ export function isSpeakAndCloneFamilyId(id: string | null | undefined): boolean
return SPEAK_AND_CLONE_FAMILY_HINT.test(id ?? "");
}
+// Families that clone and convert (chatterbox, vevo2) and the convert-only ones (rvc, seed_vc,
+// meanvc2), by repo name the way the backend's family_from_names reads it.
+const CLONE_AND_CONVERT_FAMILY_HINT = /vevo[-_]?2|chatterbox(?![-_]?turbo)/i;
+const CONVERT_ONLY_FAMILY_HINT = /rvc|seed[-_]?vc|meanvc[-_]?2/i;
+
+export function isCloneAndConvertFamilyId(id: string | null | undefined): boolean {
+ return CLONE_AND_CONVERT_FAMILY_HINT.test(id ?? "");
+}
+
+export function isConvertOnlyFamilyId(id: string | null | undefined): boolean {
+ return CONVERT_ONLY_FAMILY_HINT.test(id ?? "");
+}
+
/** Legacy Settings > Voice keys; the backend still maps each to its folder id (and variant). */
export interface AudioCppDictationModel {
key: string;
diff --git a/studio/frontend/src/features/audio/audio-page.tsx b/studio/frontend/src/features/audio/audio-page.tsx
index d7d3e30b371..ffb7cc7b8c4 100644
--- a/studio/frontend/src/features/audio/audio-page.tsx
+++ b/studio/frontend/src/features/audio/audio-page.tsx
@@ -33,6 +33,7 @@ import { useShallow } from "zustand/react/shallow";
import {
type AudioGalleryClip,
+ audioInputAlive,
fetchAudioBlob,
uploadAudioInput,
} from "./api";
@@ -134,37 +135,56 @@ const HUB_TASKS_BY_MODE = {
transcribe: ["automatic-speech-recognition"],
} as const;
+let reuseSeq = 0;
+const EXPIRED_AT = new Date(0).toISOString();
+
const RECOMMENDED_MUSIC_MODELS = ["ACE-Step1.5-GGUF", "Stable-Audio-3-Small-Music-GGUF"];
function reuseConvertInputs(clip: AudioGalleryClip) {
const store = useAudioConvertStore.getState();
const sourceId = clip.source_clip_id ?? clip.source_input_id ?? null;
const name = clip.source_name ?? "Recording";
- if (sourceId) {
- store.setSource({
- kind: clip.source_clip_id ? "clip" : "input",
- id: sourceId,
- name,
- durationS: null,
- });
- }
+ const kept = sourceId
+ ? {
+ kind: clip.source_clip_id ? ("clip" as const) : ("input" as const),
+ id: sourceId,
+ name,
+ durationS: null,
+ }
+ : null;
// An upload expires within a day; the clip kept what it converted, so upload that copy again.
- if (!clip.source_clip_id && clip.source_saved) {
+ // Empty until the live id lands (the old id let Generate race the upload); expired on failure.
+ reuseSeq += 1;
+ if (!clip.source_clip_id && clip.source_saved && sourceId) {
+ const seq = reuseSeq;
+ const untouched = () => seq === reuseSeq && useAudioConvertStore.getState().source === null;
+ store.setSource(null);
void fetchAudioBlob(
`/api/inference/audio/gallery/${encodeURIComponent(clip.id)}/source/file`,
)
.then((blob) => uploadAudioInput(blob, name))
- .then((record) => {
- if (useAudioConvertStore.getState().source?.id !== sourceId) return;
- store.setSource({
- kind: "input",
- id: record.id,
- name,
- durationS: record.duration_s,
- expiresAt: record.expires_at,
- });
- })
- .catch(() => undefined);
+ .then(
+ (record) => {
+ if (!untouched()) return;
+ store.setSource({
+ kind: "input",
+ id: record.id,
+ name,
+ durationS: record.duration_s,
+ expiresAt: record.expires_at,
+ });
+ },
+ () => {
+ // The re-upload can fail for a transient reason: the kept id is expired only on a 404.
+ if (!untouched() || !kept) return;
+ void audioInputAlive(kept.id).then((alive) => {
+ if (untouched())
+ store.setSource(alive ? kept : { ...kept, expiresAt: EXPIRED_AT });
+ });
+ },
+ );
+ } else if (kept) {
+ store.setSource(kept);
}
const target = clip.voice_id
? { kind: "voice" as const, id: clip.voice_id }
@@ -173,7 +193,16 @@ function reuseConvertInputs(clip: AudioGalleryClip) {
: clip.target_input_id
? { kind: "input" as const, id: clip.target_input_id }
: null;
- if (target) {
+ if (target?.kind === "input") {
+ // No kept copy to re-upload: check it still exists, else it reads as ready until a 404.
+ const seq = reuseSeq;
+ const named = { ...target, name: clip.reference_name ?? "Target voice", durationS: null };
+ store.setTarget(null);
+ void audioInputAlive(target.id).then((alive) => {
+ if (seq !== reuseSeq || useAudioConvertStore.getState().target !== null) return;
+ store.setTarget(alive ? named : { ...named, expiresAt: EXPIRED_AT });
+ });
+ } else if (target) {
store.setTarget({
...target,
name: clip.reference_name ?? "Target voice",
diff --git a/studio/frontend/src/features/audio/edit-adapters.ts b/studio/frontend/src/features/audio/edit-adapters.ts
index 715c021f9ad..b6846551df8 100644
--- a/studio/frontend/src/features/audio/edit-adapters.ts
+++ b/studio/frontend/src/features/audio/edit-adapters.ts
@@ -31,6 +31,10 @@ export const DOTS_BAD_CHARACTERS =
"Remove quotes and angle brackets from the changed words for DotTTS Edit.";
export const DOTS_ANGLE_BRACKETS =
"Remove angle brackets from the transcript for DotTTS Edit.";
+/** Mirrors `AudioRunEdit.markup` (max_length = 8000) so the cap is a hint here, not a 422. */
+export const DOTS_MARKUP_MAX_CHARS = 8000;
+export const DOTS_MARKUP_TOO_LONG =
+ "Make fewer changes at once for DotTTS Edit, or shorten the transcript.";
export const DELIVERY_NEEDS_FIRERED = "Delivery changes need FireRedAudio.";
export type EditMode = "words" | "delivery";
@@ -169,6 +173,8 @@ export const EDIT_ADAPTERS: Readonly<Record<string, EditAdapter>> = {
return DOTS_BAD_CHARACTERS;
if (/[<>]/.test(original) || /[<>]/.test(edited))
return DOTS_ANGLE_BRACKETS;
+ if ((markupFor(original, edited)?.length ?? 0) > DOTS_MARKUP_MAX_CHARS)
+ return DOTS_MARKUP_TOO_LONG;
return null;
},
buildEdit: ({ transcript, edited }) => {
diff --git a/studio/frontend/src/features/audio/hooks/audio-source-state.ts b/studio/frontend/src/features/audio/hooks/audio-source-state.ts
index 347d2f4a019..a852c6d4fbf 100644
--- a/studio/frontend/src/features/audio/hooks/audio-source-state.ts
+++ b/studio/frontend/src/features/audio/hooks/audio-source-state.ts
@@ -60,6 +60,11 @@ export const INITIAL_AUDIO_SOURCE_STATE: AudioSourceState = {
preview: EMPTY_PREVIEW,
};
+/** Mirrors `CONVERT_EXPIRED_DETAIL` on the server: which Convert side's upload expired. */
+export const CONVERT_EXPIRED_MESSAGE = {
+ source: "This recording expired. Add it again.",
+ target: "This target voice expired. Add it again.",
+} as const;
export const REFERENCE_EXPIRED_MESSAGE =
"This reference expired. Add it again.";
diff --git a/studio/frontend/src/features/audio/hooks/use-clone-generation.ts b/studio/frontend/src/features/audio/hooks/use-clone-generation.ts
index 89d94bc0b46..bd291c80cf0 100644
--- a/studio/frontend/src/features/audio/hooks/use-clone-generation.ts
+++ b/studio/frontend/src/features/audio/hooks/use-clone-generation.ts
@@ -61,7 +61,10 @@ export async function showRunResult({
"refreshGallery" | "selectClip" | "setFallbackClip" | "setSelectedId"
>): Promise<void> {
// An edit whose output was not saved returns only its source clip: play the inline audio.
- const clip = response.clips.find((item) => item.role === "output");
+ // Other runs name their clips by role (variation, edit, a stem): the first one is the result.
+ const clip =
+ response.clips.find((item) => item.role === "output") ??
+ (workflow === "edit" ? undefined : response.clips[0]);
const refreshed = await refreshGallery();
if (clip) {
const listed = persistedClipForGeneration(clip.id, refreshed);
diff --git a/studio/frontend/src/features/audio/hooks/use-convert-generation.ts b/studio/frontend/src/features/audio/hooks/use-convert-generation.ts
index 5cc075bf893..9b015eae725 100644
--- a/studio/frontend/src/features/audio/hooks/use-convert-generation.ts
+++ b/studio/frontend/src/features/audio/hooks/use-convert-generation.ts
@@ -39,7 +39,10 @@ import {
} from "../tools/select";
import type { AudioHostState } from "./audio-host-state";
import type { AudioSourceStatus } from "./audio-source-state";
-import { REFERENCE_EXPIRED_MESSAGE } from "./audio-source-state";
+import {
+ CONVERT_EXPIRED_MESSAGE,
+ REFERENCE_EXPIRED_MESSAGE,
+} from "./audio-source-state";
import type { AudioGallery } from "./use-audio-gallery";
import type { AudioModelSlot } from "./use-audio-model-slot";
import { showRunResult } from "./use-clone-generation";
@@ -404,6 +407,8 @@ export function useConvertGeneration({
controller.signal,
);
updateGenerationPhase("finishing");
+ // The side is remembered across runs; a new result is what the user asked for.
+ useAudioConvertStore.getState().setCompareSide("converted");
await showRunResult({
response,
text: `${sourceSelection.name} → ${
@@ -420,14 +425,25 @@ export function useConvertGeneration({
if (!controller.signal.aborted) {
updateGenerationPhase("finishing");
// Only the expired-upload 404: a deleted clip or voice says otherwise and leaves uploads alone.
+ const expiredRole =
+ error instanceof AudioApiError && error.status === 404
+ ? error.message === CONVERT_EXPIRED_MESSAGE.source
+ ? "source"
+ : error.message === CONVERT_EXPIRED_MESSAGE.target
+ ? "target"
+ : error.message === REFERENCE_EXPIRED_MESSAGE
+ ? "both"
+ : null
+ : null;
const gone =
- error instanceof AudioApiError &&
- error.status === 404 &&
- error.message === REFERENCE_EXPIRED_MESSAGE
- ? [sourceSelection, targetSelection].filter(
+ expiredRole === null
+ ? []
+ : [
+ ...(expiredRole !== "target" ? [sourceSelection] : []),
+ ...(expiredRole !== "source" ? [targetSelection] : []),
+ ].filter(
(item): item is AudioSourceSelection => item?.kind === "input",
- )
- : [];
+ );
if (gone.length > 0) {
setExpiredIds((previous) => {
const next = new Set(previous);
diff --git a/studio/frontend/src/features/audio/pages/convert-page.tsx b/studio/frontend/src/features/audio/pages/convert-page.tsx
index 57dce72e37a..4be745b35ea 100644
--- a/studio/frontend/src/features/audio/pages/convert-page.tsx
+++ b/studio/frontend/src/features/audio/pages/convert-page.tsx
@@ -390,10 +390,18 @@ function useSourceSide(clip: AudioGalleryClip | null): {
let url: string | null = null;
let cancelled = false;
setSide({});
- fetchAudioBlob(
- savedUrl ??
- sourceFileUrl({ kind, id: sourceId ?? "", name: "", durationS: null }),
- )
+ // The saved copy is the prepared (mono, resampled, capped) input: prefer the live recording.
+ const original = sourceId
+ ? sourceFileUrl({ kind, id: sourceId, name: "", durationS: null })
+ : null;
+ const fetchSide = (): Promise<Blob> =>
+ original
+ ? fetchAudioBlob(original).catch((error) => {
+ if (savedUrl) return fetchAudioBlob(savedUrl);
+ throw error;
+ })
+ : fetchAudioBlob(savedUrl as string);
+ fetchSide()
.then((blob) => {
if (cancelled) return;
url = URL.createObjectURL(blob);
diff --git a/studio/frontend/src/features/audio/picker-filter.ts b/studio/frontend/src/features/audio/picker-filter.ts
index bba3c464533..c439cee5a40 100644
--- a/studio/frontend/src/features/audio/picker-filter.ts
+++ b/studio/frontend/src/features/audio/picker-filter.ts
@@ -6,7 +6,9 @@
import {
AUDIO_CPP_SEP_AUDIO_TYPE,
audioCppModelFor,
+ isCloneAndConvertFamilyId,
isCloneOnlyFamilyId,
+ isConvertOnlyFamilyId,
isSpeakAndCloneFamilyId,
} from "./audio-cpp-catalog";
import { isMusicGenerationModel } from "./catalog";
@@ -43,7 +45,14 @@ export function audioRowMatchesWorkflow(
if (catalogModel?.workflows) {
return catalogModel.workflows.includes(workflow);
}
- // Hub search rows carry no backend workflows before download: name the clone-only families.
+ // Hub search rows carry no backend workflows before download: name the families by repo.
+ // Convert first: chatterbox and vevo2 are in the clone-only hint too.
+ if (isCloneAndConvertFamilyId(row.id)) {
+ return workflow === "clone" || workflow === "convert";
+ }
+ if (isConvertOnlyFamilyId(row.id)) {
+ return workflow === "convert";
+ }
if (isCloneOnlyFamilyId(row.id)) {
return workflow === "clone";
}
diff --git a/studio/frontend/src/features/audio/transcript-model.ts b/studio/frontend/src/features/audio/transcript-model.ts
index ff026ef0580..ea1da7405cd 100644
--- a/studio/frontend/src/features/audio/transcript-model.ts
+++ b/studio/frontend/src/features/audio/transcript-model.ts
@@ -131,6 +131,11 @@ export function detailsFrom(
else segments.push({ start, end, text: item.text });
}
}
+ // Records saved before the server sorted spans can carry diarized rows grouped per speaker.
+ const byTime = (a: { start: number; end: number }, b: typeof a) =>
+ a.start - b.start || a.end - b.end;
+ segments.sort(byTime);
+ words.sort(byTime);
const speakers: TranscriptSpeaker[] = (
Array.isArray(value.speakers) ? value.speakers : []
)
diff --git a/studio/frontend/tests/audio-clone-panels.test.ts b/studio/frontend/tests/audio-clone-panels.test.ts
index a2f0b970f7c..e4a7ea3db96 100644
--- a/studio/frontend/tests/audio-clone-panels.test.ts
+++ b/studio/frontend/tests/audio-clone-panels.test.ts
@@ -479,6 +479,15 @@ test("reference transcription sends no language hint", () => {
assert.doesNotMatch(hook, /\blanguage\s*[:,}]/);
});
+test("a run whose clips carry no output role still selects its first clip, except an edit", () => {
+ const clone = readSrc("features/audio/hooks/use-clone-generation.ts");
+ const body = clone.slice(clone.indexOf("export async function showRunResult("));
+ assert.match(
+ body,
+ /response\.clips\.find\(\(item\) => item\.role === "output"\) \?\?\s*\(workflow === "edit" \? undefined : response\.clips\[0\]\)/,
+ );
+});
+
test("a run's inline fallback clip stays on the page that started it", () => {
const clone = readSrc("features/audio/hooks/use-clone-generation.ts");
const body = clone.slice(clone.indexOf("export async function showRunResult("));
diff --git a/studio/frontend/tests/audio-convert-policy.test.ts b/studio/frontend/tests/audio-convert-policy.test.ts
index b1220ea6ee1..6cd016ef022 100644
--- a/studio/frontend/tests/audio-convert-policy.test.ts
+++ b/studio/frontend/tests/audio-convert-policy.test.ts
@@ -285,7 +285,7 @@ test("only the expired-upload 404 expires uploads, and a re-upload clears it", (
const hook = readSrc("features/audio/hooks/use-convert-generation.ts");
assert.match(
hook,
- /error\.status === 404 &&\s*error\.message === REFERENCE_EXPIRED_MESSAGE/,
+ /error instanceof AudioApiError && error\.status === 404\s*\?\s*error\.message === CONVERT_EXPIRED_MESSAGE\.source/,
);
assert.match(
hook,
@@ -344,11 +344,30 @@ test("the Convert source card states Convert's own length cap", () => {
test("Use again re-uploads a conversion's kept source instead of its expiring upload id", () => {
const page = readSrc("features/audio/audio-page.tsx");
- assert.match(page, /if \(!clip\.source_clip_id && clip\.source_saved\) \{/);
+ assert.match(page, /if \(!clip\.source_clip_id && clip\.source_saved && sourceId\) \{/);
assert.match(
page,
/\/source\/file`,\s*\)\s*\.then\(\(blob\) => uploadAudioInput\(blob, name\)\)/,
);
+ assert.match(page, /store\.setSource\(null\);\s*void fetchAudioBlob\(/);
+ assert.match(
+ page,
+ /if \(!untouched\(\) \|\| !kept\) return;\s*void audioInputAlive\(kept\.id\)\.then\(\(alive\) => \{\s*if \(untouched\(\)\)\s*store\.setSource\(alive \? kept : \{ \.\.\.kept, expiresAt: EXPIRED_AT \}\);/,
+ );
+ assert.match(
+ page,
+ /if \(target\?\.kind === "input"\) \{[\s\S]{0,400}?store\.setTarget\(null\);/,
+ );
+ assert.match(
+ page,
+ /audioInputAlive\(target\.id\)\.then\(\(alive\) => \{[\s\S]{0,200}?store\.setTarget\(alive \? named : \{ \.\.\.named, expiresAt: EXPIRED_AT \}\);/,
+ );
+ const api = readSrc("features/audio/api.ts");
+ assert.match(
+ api,
+ /export async function audioInputAlive\(inputId: string\)[\s\S]{0,300}?headers: \{ Range: "bytes=0-0" \} \}[\s\S]{0,160}?return response\.status !== 404;/,
+ );
+ assert.doesNotMatch(api, /method: "HEAD"/);
});
const SEND_TO_HAS_CONVERT = /convert: \(\) => handleSendToConvert\(clip\),/;
@@ -369,3 +388,13 @@ test("a fresh Convert clip focuses its player, not the Source tab", () => {
const page = readSrc("features/audio/pages/convert-page.tsx");
assert.match(page, /playerRef=\{focusRef\}/);
});
+
+test("an expired upload marks only its own side, the result opens on Converted, and Source plays the recording", () => {
+ const hook = readSrc("features/audio/hooks/use-convert-generation.ts");
+ assert.match(hook, /error\.message === CONVERT_EXPIRED_MESSAGE\.source\s*\?\s*"source"/);
+ assert.match(hook, /error\.message === CONVERT_EXPIRED_MESSAGE\.target\s*\?\s*"target"/);
+ assert.match(hook, /error\.message === REFERENCE_EXPIRED_MESSAGE\s*\?\s*"both"/);
+ assert.match(hook, /setCompareSide\("converted"\);\s*await showRunResult\(/);
+ const page = readSrc("features/audio/pages/convert-page.tsx");
+ assert.match(page, /fetchAudioBlob\(original\)\.catch\([\s\S]*return fetchAudioBlob\(savedUrl\)/);
+});
diff --git a/studio/frontend/tests/audio-edit-adapters.test.ts b/studio/frontend/tests/audio-edit-adapters.test.ts
index 825f49ee341..6308d6064c3 100644
--- a/studio/frontend/tests/audio-edit-adapters.test.ts
+++ b/studio/frontend/tests/audio-edit-adapters.test.ts
@@ -205,3 +205,17 @@ test("segments carry the inserted and deleted labels for screen readers", () =>
{ kind: "insert", text: "really", srLabel: "inserted " },
]);
});
+
+test("DotTTS says so before its markup would outgrow the backend cap", () => {
+ const words = Array.from({ length: 400 }, (_, i) => `word${i}`);
+ const original = words.join(" ");
+ const edited = words.map((w, i) => (i % 2 ? `${w}x` : w)).join(" ");
+ assert.equal(
+ EDIT_ADAPTERS.dots_tts.validateWords(original, edited),
+ A.DOTS_MARKUP_TOO_LONG,
+ );
+ assert.equal(
+ EDIT_ADAPTERS.dots_tts.validateWords(original, original.replace("word1 ", "word1x ")),
+ null,
+ );
+});
diff --git a/studio/frontend/tests/audio-picker-filter.test.ts b/studio/frontend/tests/audio-picker-filter.test.ts
index 0f271e54fdf..56701d59771 100644
--- a/studio/frontend/tests/audio-picker-filter.test.ts
+++ b/studio/frontend/tests/audio-picker-filter.test.ts
@@ -291,6 +291,28 @@ test("the clone-only name hint follows the backend's speaks=False families", asy
}
});
+test("Hub search rows for conversion families outside the catalog list on Convert", () => {
+ for (const id of ["someone/RVC-v2-GGUF", "x/Seed-VC-GGUF", "x/MeanVC2-GGUF"]) {
+ const row = { id, task: "text-to-speech" };
+ assert.equal(audioRowMatchesWorkflow(row, "convert"), true, id);
+ assert.equal(audioRowMatchesWorkflow(row, "clone"), false, id);
+ assert.equal(audioRowMatchesWorkflow(row, "speak"), false, id);
+ }
+ for (const id of ["ResembleAI/chatterbox", "x/Vevo2-GGUF"]) {
+ const row = { id, task: "text-to-speech" };
+ assert.equal(audioRowMatchesWorkflow(row, "convert"), true, id);
+ assert.equal(audioRowMatchesWorkflow(row, "clone"), true, id);
+ assert.equal(audioRowMatchesWorkflow(row, "speak"), false, id);
+ }
+ const turbo = { id: "x/Chatterbox-Turbo-GGUF", task: "text-to-speech" };
+ assert.equal(audioRowMatchesWorkflow(turbo, "convert"), false);
+ assert.equal(audioRowMatchesWorkflow(turbo, "speak"), true);
+ const turboUnderscore = { id: "x/chatterbox_turbo-GGUF", task: "text-to-speech" };
+ assert.equal(audioRowMatchesWorkflow(turboUnderscore, "convert"), false);
+ const vevoUnderscore = { id: "x/vevo_2-GGUF", task: "text-to-speech" };
+ assert.equal(audioRowMatchesWorkflow(vevoUnderscore, "convert"), true);
+});
+
test("a Fish Audio Hub row lists on both Speak and Clone before download", () => {
const row = { id: "fishaudio/fish-speech-1.5-GGUF", task: "text-to-speech" };
assert.equal(audioRowMatchesWorkflow(row, "speak"), true);
diff --git a/studio/frontend/tests/transcript-model.test.ts b/studio/frontend/tests/transcript-model.test.ts
index 79695c13f6a..65d5a9b7c19 100644
--- a/studio/frontend/tests/transcript-model.test.ts
+++ b/studio/frontend/tests/transcript-model.test.ts
@@ -83,3 +83,25 @@ test("details drop malformed entries, server paths and unknown source kinds", ()
);
assert.deepEqual(detailsFrom({}), EMPTY_TRANSCRIPT_DETAILS);
});
+
+test("details come back in time order, whatever order the record kept", () => {
+ const details = detailsFrom({
+ segments: [
+ { start: 5, end: 6, text: "c", speaker: "S02" },
+ { start: 0, end: 1, text: "a", speaker: "S01" },
+ { start: 2, end: 3, text: "b", speaker: "S01" },
+ ],
+ words: [
+ { start: 2, end: 3, word: "b" },
+ { start: 0, end: 1, word: "a" },
+ ],
+ });
+ assert.deepEqual(
+ details.segments.map((s) => s.text),
+ ["a", "b", "c"],
+ );
+ assert.deepEqual(
+ details.words.map((w) => w.word),
+ ["a", "b"],
+ );
+});