Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: split Audio into Speak, Music and Transcribe workspaces (#12600)
Etherlc7544700020c
diff --git a/studio/backend/core/inference/audio_cpp_backend.py b/studio/backend/core/inference/audio_cpp_backend.pyindex 11feeed83ab..ac8a7eb6df4 100644--- a/studio/backend/core/inference/audio_cpp_backend.py+++ b/studio/backend/core/inference/audio_cpp_backend.py@@ -263,7 +263,10 @@ class AudioCppBackend:_raise_if_cancelled(cancel_event)raiseexcept AudioCppRequestError as exc:- raise RuntimeError(f"The audio runtime could not generate audio: {exc.detail}") from exc+ from core.inference.audio_errors import AudioRuntimeError+ raise AudioRuntimeError(+ f"The audio runtime could not generate audio: {exc.detail}", status = exc.status+ ) from exc_raise_if_cancelled(cancel_event)return wav, _wav_sample_rate(wav)diff --git a/studio/backend/core/inference/audio_cpp_models.py b/studio/backend/core/inference/audio_cpp_models.pyindex 8306cbbbeba..5f6e2555d95 100644--- a/studio/backend/core/inference/audio_cpp_models.py+++ b/studio/backend/core/inference/audio_cpp_models.py@@ -359,21 +359,39 @@ _TASK_NAMES = {"vad": "Voice activity detection","midi": "Music transcription","vc": "Voice conversion",- "svc": "Voice conversion",+ "svc": "Singing voice conversion","s2s": "Speech-to-speech","spk": "Speaker embedding",+ "turn": "Turn detection",+ "clon": "Voice cloning",+ "vdes": "Voice design",}-def _family_from_spec_tasks(family: str, spec: Optional[dict]) -> AudioCppFamily:- """Policy for a family Studio does not list, from the tasks its spec declares."""+def _family_from_spec_tasks(+ family: str,+ spec: Optional[dict],+ label: Optional[str] = None,+) -> AudioCppFamily:+ """Policy for a family Studio does not list, from the tasks its spec declares.++ The spec can be the one a GGUF embeds, newer than the installed runtime, so a family the+ runtime does not load is refused here rather than failing at load with "unsupported model+ family hint". ``label`` names the model in that refusal.+ """tasks = [str(t).lower() for t in (spec or {}).get("tasks") or [] if isinstance(t, str)]tokens = [_SPEC_TO_SERVER_TASK.get(t, t) for t in tasks]# Speech first, then music, then transcription: a model that speaks is most useful spoken.for token in ("tts", "vdes", "clon", "gen", "asr"):if token in tokens:if token == "clon":- break+ continue+ if runtime_knows_family(family) is False:+ return AudioCppFamily(+ family,+ "",+ unsupported = f"{label or family} needs a newer audio runtime than the one installed.",+ )studio = "tts" if token == "vdes" else _SERVER_TO_STUDIO_TASK[token]return AudioCppFamily(family, studio, server_task = token)if "clon" in tokens:@@ -383,9 +401,15 @@ def _family_from_spec_tasks(family: str, spec: Optional[dict]) -> AudioCppFamilyunsupported = "This model only clones a reference voice, which Studio does not send yet.",)if tokens:- what = _TASK_NAMES.get(tokens[0], tokens[0])+ what = _TASK_NAMES.get(tokens[0])return AudioCppFamily(- family, "", unsupported = f"{what} models are not supported in Studio yet."+ family,+ "",+ unsupported = (+ f"{what} models are not supported in Studio yet."+ if what+ else f"Studio does not support the '{tokens[0]}' task yet."+ ),)return AudioCppFamily(family,@@ -398,13 +422,14 @@ def family_policy(family: str,spec: Optional[dict] = None,names: Iterable[str] = (),+ label: Optional[str] = None,) -> AudioCppFamily:"""What Studio does with ``family``: the table entry, else what its spec says it does.``names`` (repo, folder and file names) pick the Qwen3-TTS package kind, which the familyalone does not say: CustomVoice needs a speaker, VoiceDesign designs one, Base only clones."""- policy = FAMILIES.get(family) or _family_from_spec_tasks(family, spec)+ policy = FAMILIES.get(family) or _family_from_spec_tasks(family, spec, label)if family == "qwen3_tts":text = " ".join(names).lower()if "voicedesign" in text or "voice-design" in text:@@ -1119,6 +1144,45 @@ def runtime_spec(family: str) -> Optional[dict]:return None+def runtime_knows_family(family: str) -> Optional[bool]:+ """Whether the installed runtime loads ``family``; None when Studio cannot tell.++ A runtime that ships ``model_specs/`` answers from it. The prebuilt bundles do not ship that+ folder, so for the pinned prebuilt the families its source tree specs are listed in+ ``audio_cpp_spec_families``. Any other runtime (no install, a custom build, another tag) is+ unknown, and the spec's own tasks decide as before.+ """+ if not family or not re.fullmatch(r"[a-z0-9_]+", family):+ return None+ try:+ from core.inference.audio_cpp_server import (+ find_audio_cpp_server_binary,+ read_install_record,+ )+ binary = find_audio_cpp_server_binary()+ except Exception: # noqa: BLE001 - no runtime, no answer+ return None+ if not binary:+ return None+ if runtime_spec(family) is not None:+ return True+ try:+ parents = list(Path(binary).resolve().parents)[:3]+ if any((parent / "model_specs").is_dir() for parent in parents):+ return False+ tag = read_install_record(binary).get("release_tag")+ except (OSError, ValueError):+ return None+ from core.inference.audio_cpp_spec_families import (+ AUDIO_CPP_SPEC_FAMILIES,+ AUDIO_CPP_SPEC_FAMILIES_TAG,+ )++ if tag != AUDIO_CPP_SPEC_FAMILIES_TAG:+ return None+ return family in AUDIO_CPP_SPEC_FAMILIES++def _clean_option(raw: Any) -> Optional[dict]:if not isinstance(raw, dict):return None@@ -1536,7 +1600,7 @@ def _resolve_uncached()spec = runtime_spec(family)embedded = header.spec if header is not None else None- policy = family_policy(family, spec or embedded, names)+ policy = family_policy(family, spec or embedded, names, ref.display_name)if policy.package:# In the package's own order: its first mix is the one the runtime defaults to.variants = _package_variants(policy, files, ref.folder)diff --git a/studio/backend/core/inference/audio_cpp_server.py b/studio/backend/core/inference/audio_cpp_server.pyindex 8389c468094..7190284f3d9 100644--- a/studio/backend/core/inference/audio_cpp_server.py+++ b/studio/backend/core/inference/audio_cpp_server.py@@ -31,6 +31,7 @@ from pathlib import Pathfrom typing import Any, Optionalfrom core.inference.audio_cpp_models import AudioCppModel+from core.inference.audio_errors import sanitize_runtime_tailfrom loggers import get_loggerfrom utils.prebuilt.child_env import isolate_home, scrub_envfrom utils.prebuilt.runtime_libs import dedupe_existing_dirs@@ -474,7 +475,12 @@ class AudioCppServer:data = (self._config_dir / "server.log").read_bytes()except OSError:return ""- return data[-limit:].decode("utf-8", "replace").strip()+ tail = data[-limit:]+ if len(data) > limit:+ # The cut can split a path or token; drop that partial first line (or word, or all of it).+ parts = tail.split(b"\n", 1) if b"\n" in tail else tail.split(None, 1)+ tail = parts[1] if len(parts) == 2 else b""+ return tail.decode("utf-8", "replace").strip()def alive(self) -> bool:return self.process.poll() is None@@ -490,7 +496,7 @@ class AudioCppServer:raise AudioCppUnavailableError("The audio runtime exited before becoming ready; the model file may be ""incomplete or unsupported by this build."- + (f" Last output: {tail[-400:]}" if tail else "")+ + (f" Last output: {sanitize_runtime_tail(tail)}" if tail else ""))if self._probe():return@@ -576,7 +582,11 @@ class AudioCppServer:if not self.alive():raise AudioCppUnavailableError("The audio runtime stopped while serving the request."- + (f" Last output: {self.log_tail()[-400:]}" if self.log_tail() else "")+ + (+ f" Last output: {sanitize_runtime_tail(self.log_tail())}"+ if self.log_tail()+ else ""+ )) from excraise AudioCppUnavailableError(f"The audio runtime did not answer: {exc}") from excfinally:diff --git a/studio/backend/core/inference/audio_cpp_spec_families.py b/studio/backend/core/inference/audio_cpp_spec_families.pynew file mode 100644index 00000000000..abeac93f2f3--- /dev/null+++ b/studio/backend/core/inference/audio_cpp_spec_families.py@@ -0,0 +1,120 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The model families the pinned audio.cpp runtime loads, for prebuilt bundles that ship no ``model_specs/``.++A family Studio does not list is offered from the tasks its GGUF's spec declares, and that spec can+be newer than the runtime. This set lets Studio refuse such a family up front instead of failing at+load with "unsupported model family hint". It holds only for the tag it was generated from.+"""++from __future__ import annotations++AUDIO_CPP_SPEC_FAMILIES_TAG = "v0.9.0-unsloth.1"++# Regenerate on a pin bump: the stems of model_specs/*.json in unslothai/audio.cpp at that tag.+AUDIO_CPP_SPEC_FAMILIES = frozenset(+ (+ "ace_step",+ "apollo",+ "audio8_asr",+ "audio8_tts",+ "audiosr",+ "auk",+ "breeze_tts",+ "bs_roformer",+ "builtin_audio_utils",+ "canary_asr",+ "chatterbox",+ "chatterbox_turbo",+ "citrinet_asr",+ "cohere_asr",+ "confucius4_r2t2",+ "confucius4_tts",+ "controlfoley",+ "cosyvoice3",+ "dots_tts",+ "dramabox",+ "echo_tts",+ "f5_tts",+ "firered_audio",+ "fireredtts3",+ "fish_audio",+ "fun_asr_nano",+ "gigaam_asr",+ "glm_tts",+ "granite5asr",+ "heartmula",+ "higgs_audio_stt",+ "higgs_audio_tts",+ "htdemucs",+ "htdemucs_6stems",+ "hviske_asr",+ "index_tts2",+ "inflect_v2",+ "irodori_tts",+ "kitten_tts",+ "kokoro_tts",+ "kroko_asr",+ "liveavatar",+ "magpie_tts",+ "maya1",+ "meanvc2",+ "mel_band_roformer",+ "midashenglm_gen",+ "minimax_h3",+ "minimax_music3",+ "miocodec",+ "miotts",+ "mira_tts",+ "mms_forced_aligner",+ "moonshine_asr",+ "moss_transcribe_diarize",+ "moss_tts_local",+ "moss_tts_nano",+ "moss_tts_v15",+ "moss_ttsd",+ "moss_voicegen",+ "muscriptor",+ "nemotron_3_diar",+ "nemotron_asr",+ "neutts",+ "niagara_asr",+ "omnivoice",+ "outetts",+ "parakeet_tdt",+ "personaplex",+ "piper_tts",+ "pocket_tts",+ "pulsevad",+ "qwen3_asr",+ "qwen3_forced_aligner",+ "qwen3_tts",+ "rvc",+ "sam_audio",+ "samsone",+ "sanotts",+ "seed_vc",+ "sense_asr",+ "sheetsage2",+ "soprano_tts",+ "sopro_tts",+ "sortformer_diar",+ "sortformer_diar_v2",+ "stable_audio",+ "supertonic",+ "tone_color_vc",+ "universr",+ "vevo2",+ "vibeasr",+ "vibevoice",+ "vibevoice_asr",+ "vibevoice_asr_streaming",+ "vieneu_v3_turbo",+ "voxcpm1",+ "voxcpm2",+ "voxtral_realtime",+ "yue2",+ "zipvoice",+ )+)diff --git a/studio/backend/core/inference/audio_errors.py b/studio/backend/core/inference/audio_errors.pyindex 2d8c246b74e..1848153715c 100644--- a/studio/backend/core/inference/audio_errors.py+++ b/studio/backend/core/inference/audio_errors.py@@ -10,9 +10,20 @@ carry no path or user input, so the route passes them straight through.from __future__ import annotations+import re+# Tagged on the worker's audio_error payload so the parent recognises the case without matching on prose.AUDIO_UNSUPPORTED_CODE = "audio_unsupported_backend"+AUDIO_RUNTIME_ERROR_CODE = "audio_runtime_error"++_MAX_RUNTIME_DETAIL_CHARS = 300+# A network URL (kept: its tokens are redact_log_text's job), else an absolute POSIX, drive-letter,+# UNC or file:// path, also after a ':' ("path:/home/..."). A "family:name" pair has no slash.+_ABSOLUTE_PATH_RE = re.compile(+ r"(?P<url>\b(?:https?|wss?|ftp)://[^\s\"'`,;]+)"+ r"|(?<![\w/])(?:file://)?(?:/|[A-Za-z]:[\\/]|\\\\)[^\s\"'`,;]+"+)class AudioGenerationCancelledError(RuntimeError):@@ -42,3 +53,73 @@ class AudioBackendUnsupportedError(RuntimeError):@propertydef message(self) -> str:return self.args[0] if self.args else self.detail+++class AudioRuntimeError(RuntimeError):+ """The audio runtime refused or failed a request and said why ("CosyVoice3 requires reference+ audio"). ``status`` is the runtime's HTTP status, when it answered with one.++ The text is the runtime's own, so it can name a path or echo a token: send it to a client only+ through ``audio_runtime_http_error``.+ """++ def __init__(+ self,+ detail: str,+ *,+ status: int | None = None,+ ):+ self.detail = detail+ self.status = status+ super().__init__(detail)+++def _redacted_line(text: str) -> str:+ from utils.log_redaction import redact_log_text++ cleaned = redact_log_text(str(text or ""))+ cleaned = _ABSOLUTE_PATH_RE.sub(_path_tail, cleaned)+ return " ".join(cleaned.split())+++def sanitize_runtime_detail(text: str) -> str:+ """One bounded line of runtime error text with credentials and filesystem paths removed."""+ cleaned = _redacted_line(text)+ if len(cleaned) > _MAX_RUNTIME_DETAIL_CHARS:+ cleaned = cleaned[: _MAX_RUNTIME_DETAIL_CHARS - 3].rstrip() + "..."+ return cleaned+++def sanitize_runtime_tail(text: str, limit: int = 280) -> str:+ """The last ``limit`` characters of a runtime log, redacted before the cut so a path or token+ straddling it is never shown half-redacted."""+ cleaned = _redacted_line(text)+ if len(cleaned) > limit:+ cleaned = "..." + cleaned[-(limit - 3) :].split(" ", 1)[-1]+ return cleaned+++def _path_tail(match: "re.Match[str]") -> str:+ if match.group("url"):+ return match.group("url")+ tail = match.group(0).replace("\\", "/").rstrip("/").rsplit("/", 1)[-1]+ return tail or "..."+++def audio_runtime_http_error(+ error: AudioRuntimeError, fallback: str = "An internal error occurred"+) -> tuple[int, str]:+ """The HTTP status and client-safe ``detail`` for a runtime error.++ A runtime 4xx (a refused input or option) is the request's fault and becomes 400, never a+ 401/403/404 the client would read as its own auth or routing; a busy runtime stays 503;+ everything else is 500, as before, but with the runtime's reason instead of the fallback.+ """+ status = error.status+ if status == 503:+ code = 503+ elif status is not None and 400 <= status < 500:+ code = 400+ else:+ code = 500+ return code, sanitize_runtime_detail(error.detail) or fallbackdiff --git a/studio/backend/core/inference/audio_gallery.py b/studio/backend/core/inference/audio_gallery.pyindex 54a201e1bd2..a8831e65c5d 100644--- a/studio/backend/core/inference/audio_gallery.py+++ b/studio/backend/core/inference/audio_gallery.py@@ -19,6 +19,7 @@ from pathlib import Pathfrom typing import Any, Optionalfrom core.inference import gallery_flags+from core.inference.audio_workflows import workflow_for_audio_typefrom loggers import get_loggerfrom utils.account_context import is_owner_contextfrom utils.paths import ensure_account_dir, studio_root@@ -193,6 +194,7 @@ def _record(flags = gallery_flags.read(gallery_dir())return {**meta,+ "workflow": _workflow(meta),"id": audio_id,"url": f"/api/inference/audio/gallery/{audio_id}/file",**gallery_flags.flags_for(flags, audio_id),@@ -203,6 +205,13 @@ def _record(}+def _workflow(meta: dict[str, Any]) -> str:+ workflow = meta.get("workflow")+ if workflow in ("speak", "music"):+ return workflow+ return workflow_for_audio_type(meta.get("audio_type"))++def audio_path(audio_id: str) -> Optional[Path]:"""Resolve an id to its on-disk WAV, or None if missing or unsafe."""if not _ID_RE.match(audio_id):@@ -416,12 +425,13 @@ def delete(audio_id: str) -> bool:return True-def clear(include_archived: bool = False) -> int:+def clear(include_archived: bool = False, workflow: Optional[str] = None) -> int:"""Delete every Unsloth-owned pair (readable sidecar); return the count removed. Foreign andorphan WAVs are preserved, since list_audio already hides them.Archived clips are spared unless ``include_archived``, and sparing them raises- FlagsUnavailable when the flag store cannot be read."""+ FlagsUnavailable when the flag store cannot be read. A ``workflow`` (speak or music) spares+ the other workflow's clips."""removed = 0directory = gallery_dir()with gallery_flags.exclusive(directory, require_file_lock = not include_archived):@@ -432,7 +442,10 @@ def clear(include_archived: bool = False) -> int:return 0cleared: list[str] = []for path in paths:- if _read_meta(_sidecar_path(path.stem)) is None:+ meta = _read_meta(_sidecar_path(path.stem))+ if meta is None:+ continue+ if workflow is not None and _workflow(meta) != workflow:continueif not include_archived and gallery_flags.is_archived(flags, path.stem):continue@@ -446,7 +459,7 @@ def clear(include_archived: bool = False) -> int:_sidecar_path(path.stem).unlink()except OSError:pass- if include_archived and not gallery_flags.is_trusted(directory):+ if include_archived and workflow is None and not gallery_flags.is_trusted(directory):gallery_flags.reset_locked(directory)else:gallery_flags.forget_locked(directory, cleared)diff --git a/studio/backend/core/inference/audio_workflows.py b/studio/backend/core/inference/audio_workflows.pynew file mode 100644index 00000000000..a3d3f1f02d5--- /dev/null+++ b/studio/backend/core/inference/audio_workflows.py@@ -0,0 +1,38 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Which Audio page workflows (Speak, Music, Transcribe) a model or a clip belongs to.++Mirrors ``studio/frontend/src/features/audio/workflows.ts``. This module reads the audio.cpp+constants; ``audio_cpp_models`` never imports it.+"""++from __future__ import annotations++from typing import Optional++from core.inference.audio_cpp_models import AUDIO_CPP_MUSIC_AUDIO_TYPE, HUB_TASKS++MUSIC_AUDIO_TYPES = frozenset(("minimax_music3", AUDIO_CPP_MUSIC_AUDIO_TYPE))+++def workflow_for_audio_type(audio_type: Optional[str]) -> str:+ """The generation workflow (``speak`` or ``music``) that a model or clip of this type serves."""+ return "music" if audio_type in MUSIC_AUDIO_TYPES else "speak"+++def inventory_audio_workflows(+ task: Optional[str], audio_type: Optional[str]+) -> Optional[list[str]]:+ """Workflows a cached or local model row serves, from its pipeline task first.++ audio.cpp music rows carry ``text-to-audio`` with no audio_type, so the task decides before+ the audio_type does. None for a row that is not an audio model.+ """+ if task == HUB_TASKS["music"]:+ return ["music"]+ if task == HUB_TASKS["asr"]:+ return ["transcribe"]+ if task == HUB_TASKS["tts"]:+ return [workflow_for_audio_type(audio_type)]+ return Nonediff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.pyindex 06fcaf69efa..cf0209b4373 100644--- a/studio/backend/core/inference/orchestrator.py+++ b/studio/backend/core/inference/orchestrator.py@@ -28,9 +28,11 @@ from core.inference.audio_device import audio_device_forces_cpu, audio_load_runsfrom core.inference.context_refusal import ContextBudgetExceededfrom core.inference.native_audio import NATIVE_AUDIO_TYPES, is_native_audio_modelfrom core.inference.audio_errors import (+ AUDIO_RUNTIME_ERROR_CODE,AUDIO_UNSUPPORTED_CODE,AudioBackendUnsupportedError,AudioGenerationCancelledError,+ AudioRuntimeError,)from core.inference.worker import PendingTeardowns, StopLedgerfrom utils.hardware import get_device, prepare_gpu_selection@@ -3488,6 +3490,11 @@ class InferenceOrchestrator:resp.get("error", "This backend cannot generate audio."),hint = resp.get("hint"),)+ if resp.get("code") == AUDIO_RUNTIME_ERROR_CODE:+ raise AudioRuntimeError(+ resp.get("error", "Audio generation failed"),+ status = resp.get("status"),+ )raise RuntimeError(resp.get("error", "Audio generation failed"))if rtype == "error":diff --git a/studio/backend/core/inference/stt_audiocpp_sidecar.py b/studio/backend/core/inference/stt_audiocpp_sidecar.pyindex 0bd79f7ac02..ce28b377f7b 100644--- a/studio/backend/core/inference/stt_audiocpp_sidecar.py+++ b/studio/backend/core/inference/stt_audiocpp_sidecar.py@@ -34,6 +34,7 @@ from core.inference.audio_cpp_models import (resolve,split_variant_ref,)+from core.inference.audio_errors import sanitize_runtime_detailfrom core.inference.audio_cpp_server import (AudioCppRequestCancelledError,AudioCppRequestError,@@ -821,11 +822,13 @@ class AudioCppSttSidecar:self._release_locked()raise SttTranscriptionCancelledError("Transcription cancelled.") from excexcept AudioCppRequestError as exc:+ # The runtime's own words reach the client, so strip paths and credentials first.+ detail = sanitize_runtime_detail(exc.detail) or "The audio runtime refused the request."if 400 <= exc.status < 500:# The server rejected this clip or option (e.g. an unsupported language), not a broken runtime.- raise SttAudioDecodeError(exc.detail) from exc+ raise SttAudioDecodeError(detail) from excnote_runtime_inference_failure(str(exc))- raise SttEngineUnavailableError(f"The audio runtime failed: {exc.detail}") from exc+ raise SttEngineUnavailableError(f"The audio runtime failed: {detail}") from excexcept (AudioCppUnavailableError, ValueError) as exc:if cancel_event is None or not cancel_event.is_set():note_runtime_inference_failure(f"{type(exc).__name__}: {exc}")diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.pyindex d286f57d273..6a7fa6bc0bb 100644--- a/studio/backend/core/inference/worker.py+++ b/studio/backend/core/inference/worker.py@@ -27,7 +27,11 @@ from pathlib import Pathfrom typing import Any, Optionallogger = get_logger(__name__)-from core.inference.audio_errors import AUDIO_UNSUPPORTED_CODE+from core.inference.audio_errors import (+ AUDIO_RUNTIME_ERROR_CODE,+ AUDIO_UNSUPPORTED_CODE,+ AudioRuntimeError,+)from core.inference.context_refusal import ContextBudgetExceededfrom utils.hardware import apply_gpu_ids, is_apple_silicon@@ -1624,20 +1628,18 @@ def _handle_generate_audio(backend, cmd: dict, resp_queue: Any, cancel_event) ->except Exception as exc:logger.error("Audio generation error: %s", exc, exc_info = True)- _send_response(- resp_queue,- {- "type": "audio_error",- "request_id": request_id,- "error": str(exc),- # The route's own cancel event is not set when the worker's shared event is- # (an unload, a training admission, the GPU arbiter), so without this flag the- # orchestrator reports a cancellation as HTTP 500. Matching on the message text- # is what AudioGenerationCancelledError exists to avoid.- "cancelled": bool(cancel_event is not None and cancel_event.is_set()),- "stack": traceback.format_exc(limit = 20),- },- )+ response = {+ "type": "audio_error",+ "request_id": request_id,+ "error": str(exc),+ # Flag a shared-event cancel (unload, training, arbiter) so the orchestrator does not report HTTP 500.+ "cancelled": bool(cancel_event is not None and cancel_event.is_set()),+ "stack": traceback.format_exc(limit = 20),+ }+ if isinstance(exc, AudioRuntimeError):+ response["code"] = AUDIO_RUNTIME_ERROR_CODE+ response["status"] = exc.status+ _send_response(resp_queue, response)def _handle_generate_audio_input(backend, cmd: dict, resp_queue: Any, cancel_event) -> None:diff --git a/studio/backend/hub/schemas/inventory.py b/studio/backend/hub/schemas/inventory.pyindex 292ba13afd0..a2959fa2c69 100644--- a/studio/backend/hub/schemas/inventory.py+++ b/studio/backend/hub/schemas/inventory.py@@ -6,9 +6,11 @@Kept independent from upstream models/models.py so the Hub module can shipwithout modifying any upstream schema."""-from pydantic import BaseModel, Field, PrivateAttr+from pydantic import BaseModel, Field, PrivateAttr, model_validatorfrom typing import List, Literal, Optional+from core.inference.audio_workflows import inventory_audio_workflows+ModelFormat = Literal["gguf", "safetensors", "adapter", "checkpoint", "unknown"]ModelRuntime = Literal["llama_cpp", "transformers", "adapter", "unknown"]@@ -205,6 +207,10 @@ class LocalModelInfo(BaseModel):None,description = "Detected output-audio architecture or codec used by Audio runtime policy",)+ audio_workflows: Optional[List[str]] = Field(+ None,+ description = "Audio page workflows (speak, music, transcribe) this row serves; null when not audio",+ )base_model: Optional[str] = Field(None,description = "Base model from adapter_config.json when this is an adapter",@@ -249,6 +255,12 @@ class LocalModelInfo(BaseModel):),)+ @model_validator(mode = "after")+ def derive_audio_workflows(self):+ if self.audio_workflows is None:+ self.audio_workflows = inventory_audio_workflows(self.task, self.audio_type)+ return self+class LocalModelListResponse(BaseModel):"""Response schema for listing local/cached models."""@@ -299,6 +311,14 @@ class CachedRepoBase(BaseModel):# diffusion pick by it, so a row without one is dropped from those lists.task: Optional[str] = Noneaudio_type: Optional[str] = None+ # Audio page workflows the row serves, from the task first: audio.cpp music rows carry no audio_type.+ audio_workflows: Optional[List[str]] = None++ @model_validator(mode = "after")+ def derive_audio_workflows(self):+ if self.audio_workflows is None:+ self.audio_workflows = inventory_audio_workflows(self.task, self.audio_type)+ return selfclass CachedGgufRepo(CachedRepoBase):diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 206cc8b6821..ae4e35840f6 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -5107,6 +5107,9 @@ class AudioGalleryItem(BaseModel):created_at: strpinned: bool = Field(False, description = "Pinned to the top of history")archived: bool = Field(False, description = "Moved to the archived shelf, hidden from history")+ workflow: Optional[str] = Field(+ None, description = "Audio page workflow that made the clip: speak or music"+ )order_at: Optional[float] = Field(None,description = "Unpinned sort key (epoch-second scale): the manual key once dragged, else the file mtime",diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 02a8cabbbb3..8573ddc6f9d 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -100,6 +100,8 @@ from hub.services.models.ollama import (from core.inference.audio_errors import (AudioBackendUnsupportedError,AudioGenerationCancelledError,+ AudioRuntimeError,+ audio_runtime_http_error,)from core.inference import context_refusalfrom core.inference.context_window import (@@ -22142,6 +22144,10 @@ async def _generate_tts_wav(if isinstance(e, AudioBackendUnsupportedError):logger.info("Audio generation unsupported on this backend: %s", e.detail)raise HTTPException(status_code = 501, detail = e.message)+ if isinstance(e, AudioRuntimeError):+ status_code, detail = audio_runtime_http_error(e)+ logger.warning("Audio generation refused by the runtime: %s", e)+ raise HTTPException(status_code = status_code, detail = detail)if audio_type == "minimax_music3" and _MINIMAX_PROMPT_OVERFLOW.fullmatch(str(e)):raise HTTPException(status_code = 400, detail = str(e))logger.error(f"Audio generation error: {e}", exc_info = True)@@ -22172,6 +22178,8 @@ def _persist_tts_clip("""Best-effort gallery save: persistence never fails the request that producedthe audio. Blocking, so callers run it off the event loop."""from core.inference import audio_gallery+ from core.inference.audio_workflows import workflow_for_audio_type+try:return audio_gallery.save(wav_bytes,@@ -22179,6 +22187,7 @@ def _persist_tts_clip("prompt": text,"model": model_name,"audio_type": audio_type or "unknown",+ "workflow": workflow_for_audio_type(audio_type),"sample_rate": sample_rate,"duration_s": _wav_duration_seconds(wav_bytes, sample_rate),"created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),@@ -44499,12 +44508,15 @@ async def delete_gallery_audio(audio_id: str, current_subject: str = Depends(get@studio_router.delete("/audio/gallery")-async def clear_gallery_audio(current_subject: str = Depends(get_current_subject)):+async def clear_gallery_audio(+ workflow: Optional[Literal["speak", "music"]] = None,+ current_subject: str = Depends(get_current_subject),+):from core.inference import audio_galleryfrom core.inference.gallery_flags import FlagsUnavailabletry:- removed = await asyncio.to_thread(audio_gallery.clear)+ removed = await asyncio.to_thread(audio_gallery.clear, workflow = workflow)except FlagsUnavailable as exc:logger.warning("audio_gallery.clear_blocked: %s", exc)raise HTTPException(diff --git a/studio/backend/tests/test_audio_cpp_models.py b/studio/backend/tests/test_audio_cpp_models.pyindex d04f799a335..3e43dca324f 100644--- a/studio/backend/tests/test_audio_cpp_models.py+++ b/studio/backend/tests/test_audio_cpp_models.py@@ -70,6 +70,7 @@ def hub(tmp_path, monkeypatch):monkeypatch.setattr(acm, "_hub_cache", lambda: root)monkeypatch.setattr(audio_cpp_files, "_hub_cache", lambda: root)monkeypatch.setattr(acm, "runtime_spec", lambda family: None)+ monkeypatch.setattr(acm, "runtime_knows_family", lambda family: None)monkeypatch.setenv("HF_HUB_OFFLINE", "1")acm.forget()with acm._resolve_lock:@@ -314,6 +315,9 @@ def test_an_unknown_family_follows_its_spec_tasks_or_is_refused(hub):for family, tasks, task, server in (("new_tts", ["tts", "clone"], "tts", "tts"),("new_music", ["music"], "music", "gen"),+ ("new_clone_music", ["clone", "music"], "music", "gen"),+ ("new_clone_asr", ["clone", "asr"], "asr", "asr"),+ ("new_clone_only", ["clone"], "", ""),("new_sep", ["sep"], "", ""),):repo = f"someone/{family}-GGUF"@@ -323,6 +327,122 @@ def test_an_unknown_family_follows_its_spec_tasks_or_is_refused(hub):assert (model.unsupported is None) == bool(task)sep = acm.resolve("someone/new_sep-GGUF", network = False)assert "Source separation" in sep.unsupported+ clone_only = acm.resolve("someone/new_clone_only-GGUF", network = False)+ assert "only clones a reference voice" in clone_only.unsupported+++def test_unsupported_task_tokens_are_refused_by_a_readable_name(hub):+ for family, tasks, message in (+ ("smart_turn", ["turn"], "Turn detection models are not supported in Studio yet."),+ ("new_svc", ["svc"], "Singing voice conversion models are not supported in Studio yet."),+ ("new_s2s", ["s2s"], "Speech-to-speech models are not supported in Studio yet."),+ ("new_odd", ["odd_task"], "Studio does not support the 'odd_task' task yet."),+ ):+ repo = f"someone/{family}-GGUF"+ _put(_snapshot(hub, repo), "m-q8_0.gguf", _gguf_bytes(family = family, spec = {"tasks": tasks}))+ assert acm.resolve(repo, network = False).unsupported == message+++_REAL_RUNTIME_KNOWS_FAMILY = acm.runtime_knows_family+++def _fake_runtime(+ monkeypatch,+ tmp_path,+ *,+ tag = None,+ specs = None,+):+ """An installed audiocpp_server with a prebuilt install record for ``tag``, and a+ ``model_specs/`` folder beside it when ``specs`` is given."""+ from core.inference import audio_cpp_server++ root = tmp_path / "audio.cpp"+ root.mkdir(parents = True)+ binary = root / "audiocpp_server"+ binary.write_bytes(b"\x7fELF")+ if tag is not None:+ (root / audio_cpp_server.INSTALL_RECORD).write_text(json.dumps({"release_tag": tag}))+ if specs is not None:+ (root / "model_specs").mkdir()+ for name in specs:+ (root / "model_specs" / f"{name}.json").write_text(json.dumps({"family": name}))+ monkeypatch.setattr(audio_cpp_server, "find_audio_cpp_server_binary", lambda: str(binary))+ return binary+++def test_the_spec_family_list_matches_the_pinned_runtime():+ import importlib.util++ from core.inference.audio_cpp_spec_families import (+ AUDIO_CPP_SPEC_FAMILIES,+ AUDIO_CPP_SPEC_FAMILIES_TAG,+ )++ installer = Path(__file__).resolve().parents[2] / "install_audio_cpp_prebuilt.py"+ spec = importlib.util.spec_from_file_location("_audio_cpp_installer", installer)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ assert AUDIO_CPP_SPEC_FAMILIES_TAG == module.DEFAULT_TAG+ for family in ("crisperwhisper", "index_echo", "audio_flamingo", "kugelaudio", "smart_turn"):+ assert family not in AUDIO_CPP_SPEC_FAMILIES+ for family in ("samsone", "gigaam_asr", "maya1"):+ assert family in AUDIO_CPP_SPEC_FAMILIES+ assert set(acm.FAMILIES) - AUDIO_CPP_SPEC_FAMILIES == {"marblenet_vad", "silero_vad"}+++def test_runtime_knows_a_family_from_its_specs_or_the_pinned_list(monkeypatch, tmp_path):+ from core.inference import audio_cpp_server+ from core.inference.audio_cpp_spec_families import AUDIO_CPP_SPEC_FAMILIES_TAG++ monkeypatch.setattr(audio_cpp_server, "find_audio_cpp_server_binary", lambda: None)+ assert acm.runtime_knows_family("samsone") is None+ _fake_runtime(monkeypatch, tmp_path / "pinned", tag = AUDIO_CPP_SPEC_FAMILIES_TAG)+ assert acm.runtime_knows_family("samsone") is True+ assert acm.runtime_knows_family("crisperwhisper") is False+ _fake_runtime(monkeypatch, tmp_path / "newer", tag = "v9.9.9-unsloth.1")+ assert acm.runtime_knows_family("crisperwhisper") is None+ _fake_runtime(monkeypatch, tmp_path / "custom")+ assert acm.runtime_knows_family("crisperwhisper") is None+ _fake_runtime(+ monkeypatch, tmp_path / "specs", tag = AUDIO_CPP_SPEC_FAMILIES_TAG, specs = ("crisperwhisper",)+ )+ assert acm.runtime_knows_family("crisperwhisper") is True+ assert acm.runtime_knows_family("samsone") is False+++def test_a_spec_fallback_family_the_runtime_lacks_is_refused(hub, monkeypatch, tmp_path):+ from core.inference.audio_cpp_spec_families import AUDIO_CPP_SPEC_FAMILIES_TAG++ # The hub fixture leaves the runtime out of reach; this test installs one.+ monkeypatch.setattr(acm, "runtime_knows_family", _REAL_RUNTIME_KNOWS_FAMILY)+ _fake_runtime(monkeypatch, tmp_path, tag = AUDIO_CPP_SPEC_FAMILIES_TAG)+ for family, folder, tasks in (+ ("samsone", "Samsone-GGUF", ["asr"]),+ ("crisperwhisper", "CrisperWhisper2.0-GGUF", ["asr"]),+ ("kugelaudio", "KugelAudio-0-Open-GGUF", ["tts"]),+ ):+ _put(+ _snapshot(hub),+ f"{folder}/m-q8_0.gguf",+ _gguf_bytes(family = family, spec = {"tasks": tasks}),+ )+ samsone = acm.resolve(f"{AUDIO_CPP_REPO}/Samsone-GGUF", network = False)+ assert (samsone.task, samsone.unsupported) == ("asr", None)+ crisper = acm.resolve(f"{AUDIO_CPP_REPO}/CrisperWhisper2.0-GGUF", network = False)+ assert crisper.task == ""+ assert crisper.unsupported == (+ "CrisperWhisper2.0-GGUF needs a newer audio runtime than the one installed."+ )+ kugel = acm.resolve(f"{AUDIO_CPP_REPO}/KugelAudio-0-Open-GGUF", network = False)+ assert "needs a newer audio runtime" in kugel.unsupported+ assert acm.family_policy("silero_vad").unsupported.startswith("Voice activity detection")+ assert acm.family_policy("kokoro_tts").task == "tts"+ assert acm.family_policy("crisperwhisper", {"tasks": ["asr"]}).unsupported == (+ "crisperwhisper needs a newer audio runtime than the one installed."+ )+ _fake_runtime(monkeypatch, tmp_path / "newer", tag = "v9.9.9-unsloth.1")+ assert acm.family_policy("crisperwhisper", {"tasks": ["asr"]}).task == "asr"def test_known_task_families_are_refused_with_a_reason(hub):diff --git a/studio/backend/tests/test_audio_gallery.py b/studio/backend/tests/test_audio_gallery.pyindex d6f6addb511..32691d01146 100644--- a/studio/backend/tests/test_audio_gallery.py+++ b/studio/backend/tests/test_audio_gallery.py@@ -696,3 +696,66 @@ def test_list_route_resolves_a_cursor_sent_without_its_pin_rank():)ids = [c.id for c in page1.audio] + [c.id for c in page2.audio]assert sorted(ids) == sorted(c["id"] for c in clips)+++def test_a_new_clip_records_its_workflow():+ from routes.inference import _persist_tts_clip++ speech = _persist_tts_clip(_wav(), 24000, "hi", "kokoro", "audiocpp_tts")+ song = _persist_tts_clip(_wav(), 44100, "a song", "ace-step", "audiocpp_music")+ sidecars = {+ clip["id"]: json.loads(+ (gallery.gallery_dir() / f"{clip['id']}.json").read_text(encoding = "utf-8")+ )+ for clip in (speech, song)+ }+ assert sidecars[speech["id"]]["workflow"] == "speak"+ assert sidecars[song["id"]]["workflow"] == "music"+ assert {r["id"]: r["workflow"] for r in gallery.list_audio()} == {+ speech["id"]: "speak",+ song["id"]: "music",+ }+++def test_an_old_clip_takes_its_workflow_from_its_audio_type():+ from models.inference import AudioGalleryItem++ speech = gallery.save(_wav(), _meta())+ song = gallery.save(_wav(), _meta(audio_type = "minimax_music3"))+ listed = {r["id"]: r for r in gallery.list_audio()}+ assert listed[speech["id"]]["workflow"] == "speak"+ assert listed[song["id"]]["workflow"] == "music"+ assert AudioGalleryItem(**listed[song["id"]]).workflow == "music"+ assert gallery.set_flags(song["id"], pinned = True)["workflow"] == "music"+++def test_a_scoped_clear_keeps_the_other_workflows_clips():+ speech = _save_with_mtime("speech", 100.0)+ song = gallery.save(_wav(), _meta(audio_type = "audiocpp_music"))+ gallery.set_flags(song["id"], pinned = True)+ assert gallery.clear(workflow = "speak") == 1+ assert gallery.audio_path(speech["id"]) is None+ remaining = gallery.list_audio()+ assert [r["id"] for r in remaining] == [song["id"]] and remaining[0]["pinned"] is True+ assert gallery.clear(workflow = "music") == 1+ assert gallery.list_audio() == []+++def test_a_scoped_clear_with_archived_keeps_the_other_workflows_flags():+ shelved_song = gallery.save(_wav(), _meta(audio_type = "audiocpp_music"))+ gallery.set_flags(shelved_song["id"], archived = True)+ _save_with_mtime("speech", 100.0)+ assert gallery.clear(include_archived = True, workflow = "speak") == 1+ assert [r["id"] for r in gallery.list_audio(archived = True)] == [shelved_song["id"]]+++def test_the_clear_route_scopes_to_a_workflow():+ from routes.inference import clear_gallery_audio++ gallery.save(_wav(), _meta())+ song = gallery.save(_wav(), _meta(audio_type = "audiocpp_music"))+ assert asyncio.run(clear_gallery_audio(workflow = "speak", current_subject = "tester")) == {+ "removed": 1+ }+ assert [r["id"] for r in gallery.list_audio()] == [song["id"]]+ assert asyncio.run(clear_gallery_audio(current_subject = "tester")) == {"removed": 1}diff --git a/studio/backend/tests/test_audio_runtime_errors.py b/studio/backend/tests/test_audio_runtime_errors.pynew file mode 100644index 00000000000..bc943d09fcc--- /dev/null+++ b/studio/backend/tests/test_audio_runtime_errors.py@@ -0,0 +1,333 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A request the audio runtime refuses reaches the client with the runtime's reason, sanitized.++CosyVoice3 without a reference clip answered "CosyVoice3 requires reference audio", and the+Audio page showed "An internal error occurred": the reason crossed the worker as a bare+RuntimeError and ``safe_error_detail`` flattened it. Paths and credentials in that text must+still never reach the client.+"""++from __future__ import annotations++import asyncio+import queue+import threading++import pytest++from core.inference.audio_errors import (+ AUDIO_RUNTIME_ERROR_CODE,+ AudioRuntimeError,+ audio_runtime_http_error,+ sanitize_runtime_detail,+)++_LEAKY = (+ "The audio runtime could not generate audio: CosyVoice3 requires reference audio\n"+ " while loading /home/alice/.unsloth/studio/cache/models--x/blobs/abc123 "+ "(token hf_AbCdEfGhIjKlMnOpQrStUvWxYz123456, C:\\Users\\alice\\voice.wav)"+)+++def test_runtime_text_is_one_bounded_line_without_paths_or_tokens():+ detail = sanitize_runtime_detail(_LEAKY)+ assert detail.startswith(+ "The audio runtime could not generate audio: CosyVoice3 requires reference audio"+ )+ assert "\n" not in detail+ assert "/home/alice" not in detail and "alice" not in detail.replace("abc123", "")+ assert "Users" not in detail and "voice.wav" in detail+ assert "hf_AbCdEf" not in detail and "<redacted>" in detail+ long = sanitize_runtime_detail("x " * 1000)+ assert len(long) <= 300 and long.endswith("...")+ assert (+ sanitize_runtime_detail("VibeVoice prompt has no valid Speaker N: lines")+ == "VibeVoice prompt has no valid Speaker N: lines"+ )+ assert sanitize_runtime_detail("see http://127.0.0.1:8080/v1/audio/speech") == (+ "see http://127.0.0.1:8080/v1/audio/speech"+ )+++ "status, expected",+ [(500, 500), (None, 500), (502, 500), (422, 400), (404, 400), (401, 400), (503, 503)],+)+def test_runtime_status_maps_to_a_status_the_client_reads_as_this_request(status, expected):+ code, detail = audio_runtime_http_error(+ AudioRuntimeError("Vevo2 requires target_voice", status = status)+ )+ assert (code, detail) == (expected, "Vevo2 requires target_voice")+++def test_an_empty_runtime_reason_falls_back_to_the_generic_message():+ assert audio_runtime_http_error(AudioRuntimeError(" \n ", status = 500)) == (+ 500,+ "An internal error occurred",+ )+++def _route_with_backend(monkeypatch, error):+ import routes.inference as inference_route+ from models.inference import ChatCompletionRequest++ class _Llama:+ is_loaded = False+ _is_audio = False++ class _Backend:+ active_model_name = "audio-cpp/audio.cpp-gguf/CosyVoice3-GGUF"+ models = {active_model_name: {"is_audio": True, "audio_type": "audiocpp_tts"}}++ def generate_audio_response(self, **_kwargs):+ raise error++ async def _noop_switch(*_args, **_kwargs):+ return None++ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: _Llama())+ monkeypatch.setattr(inference_route, "get_inference_backend", lambda: _Backend())+ monkeypatch.setattr(inference_route, "_maybe_auto_switch_model", _noop_switch)+ payload = ChatCompletionRequest(+ model = _Backend.active_model_name, messages = [{"role": "user", "content": "hello"}]+ )+ with pytest.raises(inference_route.HTTPException) as excinfo:+ asyncio.run(+ inference_route._generate_tts_wav("hello", payload, request = None, current_subject = "t")+ )+ return excinfo.value+++def test_the_generate_and_speech_core_shows_the_runtime_reason(monkeypatch):+ error = _route_with_backend(monkeypatch, AudioRuntimeError(_LEAKY, status = 500))+ assert error.status_code == 500+ assert "CosyVoice3 requires reference audio" in error.detail+ assert "/home/alice" not in error.detail and "hf_AbCdEf" not in error.detail+ refused = _route_with_backend(+ monkeypatch, AudioRuntimeError("unknown MiDashengLM-Gen request option: x", status = 400)+ )+ assert (refused.status_code, refused.detail) == (+ 400,+ "unknown MiDashengLM-Gen request option: x",+ )+++def test_any_other_failure_still_gets_the_generic_message(monkeypatch):+ error = _route_with_backend(monkeypatch, RuntimeError("boom in /home/alice/secret.py"))+ assert (error.status_code, error.detail) == (500, "An internal error occurred")+++def test_the_backend_raises_the_runtime_reason_typed():+ from core.inference import audio_cpp_backend+ from core.inference.audio_cpp_server import AudioCppRequestError++ class _Server:+ model_id = "studio-test"++ def alive(self):+ return True++ def post_json(self, path, payload, **kwargs):+ raise AudioCppRequestError(500, "CosyVoice3 requires reference audio")++ from core.inference.audio_cpp_models import FAMILIES, AudioCppModel, AudioCppVariant, RepoFile++ family = FAMILIES["cosyvoice3"]+ variant = AudioCppVariant("Q8_0", (RepoFile("m.gguf", 1),), "m.gguf")+ model = AudioCppModel(+ id = "x/CosyVoice3-GGUF",+ repo_id = "x/CosyVoice3-GGUF",+ folder = "",+ display_name = "CosyVoice3-GGUF",+ family = family.family,+ task = family.task,+ server_task = family.default_server_task,+ variant = variant,+ variants = (variant,),+ default_variant = "Q8_0",+ )+ backend = audio_cpp_backend.AudioCppBackend()+ backend._server = _Server()+ backend._server.model = model+ backend._model = model+ backend.models = {model.id: {"is_audio": True}}+ backend.active_model_name = model.id+ with pytest.raises(AudioRuntimeError) as excinfo:+ backend.generate_audio_response("hello")+ assert excinfo.value.status == 500+ assert str(excinfo.value) == (+ "The audio runtime could not generate audio: CosyVoice3 requires reference audio"+ )+++def test_the_worker_tags_a_runtime_error_and_the_parent_rebuilds_it():+ from core.inference.worker import _handle_generate_audio++ class _Backend:+ def generate_audio_response(self, **_kwargs):+ raise AudioRuntimeError("Vevo2 requires target_voice", status = 500)++ responses: queue.Queue = queue.Queue()+ _handle_generate_audio(+ _Backend(), {"request_id": "r1", "text": "hi"}, responses, threading.Event()+ )+ sent = responses.get_nowait()+ assert sent["type"] == "audio_error"+ assert (sent["code"], sent["status"], sent["error"]) == (+ AUDIO_RUNTIME_ERROR_CODE,+ 500,+ "Vevo2 requires target_voice",+ )++ class _Plain:+ def generate_audio_response(self, **_kwargs):+ raise RuntimeError("boom")++ _handle_generate_audio(+ _Plain(), {"request_id": "r2", "text": "hi"}, responses, threading.Event()+ )+ assert "code" not in responses.get_nowait()+++def test_the_orchestrator_raises_the_tagged_payload_typed(monkeypatch):+ from core.inference.orchestrator import InferenceOrchestrator++ orchestrator = InferenceOrchestrator.__new__(InferenceOrchestrator)+ sent = []+ payload = {+ "type": "audio_error",+ "error": "Vevo2 requires target_voice",+ "code": AUDIO_RUNTIME_ERROR_CODE,+ "status": 500,+ }++ def read_one(*, timeout):+ return {**payload, "request_id": sent[0]["request_id"]}++ for name, value in {+ "_ensure_subprocess_alive": lambda: True,+ "_send_cmd": lambda cmd: sent.append(cmd),+ "_direct_reader": lambda _rid, _cancel = None: (read_one, lambda **_k: None, lambda: None),+ "_reserve_worker": lambda _why: _Nullcontext(),+ "_wait_worker_idle": lambda **_k: True,+ "_claim_worker": lambda _cancel: None,+ "_release_worker": lambda *_a, **_k: None,+ }.items():+ monkeypatch.setattr(orchestrator, name, value, raising = False)+ orchestrator.active_model_name = "m"+ orchestrator.models = {"m": {}}+ orchestrator._gen_lock = threading.Lock()+ orchestrator._send_order_lock = threading.Lock()+ orchestrator._unload_pending = False+ with pytest.raises(AudioRuntimeError) as excinfo:+ orchestrator.generate_audio_response("hello")+ assert (excinfo.value.status, str(excinfo.value)) == (500, "Vevo2 requires target_voice")+++class _Nullcontext:+ def __enter__(self):+ return self++ def __exit__(self, *_exc):+ return False+++def test_a_transcription_error_is_sanitized_before_it_reaches_the_client():+ from core.inference import stt_audiocpp_sidecar as stt+ from core.inference.audio_cpp_server import AudioCppRequestError+ from core.inference.stt_sidecar import SttAudioDecodeError++ class _Server:+ model_id = "studio-test"+ model = type("M", (), {"family": "qwen3_asr"})()++ def __init__(self, status):+ self.status = status++ def post_multipart(self, *_args, **_kwargs):+ raise AudioCppRequestError(self.status, _LEAKY)++ sidecar = stt.AudioCppSttSidecar.__new__(stt.AudioCppSttSidecar)+ sidecar._server = _Server(500)+ with pytest.raises(stt.SttEngineUnavailableError) as failed:+ sidecar._post_transcription(b"RIFF", None, None)+ message = str(failed.value)+ assert message.startswith("The audio runtime failed: The audio runtime could not generate")+ assert "/home/alice" not in message and "hf_AbCdEf" not in message and "\n" not in message+ sidecar._server = _Server(400)+ with pytest.raises(SttAudioDecodeError) as refused:+ sidecar._post_transcription(b"RIFF", None, None)+ assert "/home/alice" not in str(refused.value)+ stt.clear_runtime_inference_failure()+++def test_a_runtime_that_dies_at_load_reports_its_last_line_sanitized(tmp_path):+ from core.inference.audio_cpp_server import AudioCppServer, AudioCppUnavailableError++ (tmp_path / "server.log").write_text(+ "ggml_cuda_init: found 1 CUDA devices\n"+ "loading /home/alice/.cache/huggingface/hub/models--x/blobs/0f3a token hf_AbCdEfGhIjKlMnOpQrStUv12\n"+ "audiocpp_server failed: unsupported model family hint: crisperwhisper\n"+ )+ exited = type("P", (), {"poll": lambda self: 1, "pid": 0})()+ server = AudioCppServer(exited, 0, None, "studio-test", "cuda", tmp_path)+ with pytest.raises(AudioCppUnavailableError) as excinfo:+ server._wait_until_ready(None)+ message = str(excinfo.value)+ assert message.endswith("audiocpp_server failed: unsupported model family hint: crisperwhisper")+ assert "/home/alice" not in message and "hf_AbCdEf" not in message and "\n" not in message+++def test_runtime_tail_redacts_before_the_cut():+ from core.inference.audio_errors import sanitize_runtime_tail++ secret = "/home/someone/private/models/voice.gguf"+ text = "x" * 400 + " failed to open " + secret + " " + "y" * 250+ out = sanitize_runtime_tail(text)+ assert len(out) <= 280+ assert "someone" not in out and "private" not in out+ # Cutting the raw text first left the path without its leading "/".+ raw = text[-280:]+ assert "private" in raw+++def test_log_tail_drops_the_partial_first_line(tmp_path):+ from core.inference.audio_cpp_server import AudioCppServer++ server = AudioCppServer.__new__(AudioCppServer)+ server._config_dir = tmp_path+ (tmp_path / "server.log").write_bytes(b"/home/someone/secret/path.gguf\n" * 100 + b"last line")+ tail = server.log_tail(limit = 50)+ assert tail.endswith("last line")+ assert tail.split("\n")[0] in ("/home/someone/secret/path.gguf", "last line")+++def test_file_urls_and_colon_prefixed_paths_are_redacted_but_network_urls_kept():+ from core.inference.audio_errors import sanitize_runtime_detail++ assert sanitize_runtime_detail("failed: file:///home/alice/private/m.gguf") == "failed: m.gguf"+ assert sanitize_runtime_detail("path:/home/alice/x.gguf bad") == "path:x.gguf bad"+ url = "see https://huggingface.co/a/b/resolve/main/x.gguf"+ assert sanitize_runtime_detail(url) == url+ assert sanitize_runtime_detail("family:cosyvoice3 needs ref") == "family:cosyvoice3 needs ref"+++def test_log_tail_without_a_newline_drops_the_partial_first_word(tmp_path):+ from core.inference.audio_cpp_server import AudioCppServer++ server = AudioCppServer.__new__(AudioCppServer)+ server._config_dir = tmp_path+ (tmp_path / "server.log").write_bytes(b"token=hf_secretvalue " * 20 + b"end")+ tail = server.log_tail(limit = 50)+ assert tail.split(" ")[0] in ("token=hf_secretvalue", "end")+++def test_log_tail_with_no_delimiter_is_dropped(tmp_path):+ from core.inference.audio_cpp_server import AudioCppServer++ server = AudioCppServer.__new__(AudioCppServer)+ server._config_dir = tmp_path+ (tmp_path / "server.log").write_bytes(b"x" * 200)+ assert server.log_tail(limit = 50) == ""diff --git a/studio/backend/tests/test_audio_workflows.py b/studio/backend/tests/test_audio_workflows.pynew file mode 100644index 00000000000..bbfdda052c5--- /dev/null+++ b/studio/backend/tests/test_audio_workflows.py@@ -0,0 +1,61 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Which Audio page workflows an inventory row or a gallery clip belongs to."""++from __future__ import annotations++import re+from pathlib import Path++import pytest++from core.inference import audio_workflows as aw+from core.inference.audio_cpp_models import AUDIO_CPP_MUSIC_AUDIO_TYPE, AUDIO_CPP_TTS_AUDIO_TYPE+from hub.schemas.inventory import CachedGgufRepo, CachedModelRepo, LocalModelInfo+++def test_music_audio_types_match_the_frontend_set():+ source = (+ Path(__file__).resolve().parents[2] / "frontend/src/features/audio/workflows.ts"+ ).read_text(encoding = "utf-8")+ block = re.search(r"MUSIC_AUDIO_TYPES[^=]*=\s*new Set\(\[(.*?)\]\)", source, re.S).group(1)+ names = {"AUDIO_CPP_MUSIC_AUDIO_TYPE": AUDIO_CPP_MUSIC_AUDIO_TYPE}+ frontend = {+ names.get(item.strip(), item.strip().strip('"'))+ for item in block.split(",")+ if item.strip()+ }+ assert frontend == set(aw.MUSIC_AUDIO_TYPES) == {"minimax_music3", "audiocpp_music"}+++ "task, audio_type, workflows",+ [+ ("text-to-audio", None, ["music"]),+ ("automatic-speech-recognition", None, ["transcribe"]),+ ("text-to-speech", AUDIO_CPP_TTS_AUDIO_TYPE, ["speak"]),+ ("text-to-speech", "minimax_music3", ["music"]),+ ("text-to-speech", AUDIO_CPP_MUSIC_AUDIO_TYPE, ["music"]),+ ("text-to-speech", None, ["speak"]),+ ("text-generation", None, None),+ (None, None, None),+ ],+)+def test_inventory_rows_derive_workflows_from_the_task_first(task, audio_type, workflows):+ assert aw.inventory_audio_workflows(task, audio_type) == workflows+ gguf = CachedGgufRepo(repo_id = "someone/m-GGUF", task = task, audio_type = audio_type)+ model = CachedModelRepo(repo_id = "someone/m", task = task, audio_type = audio_type)+ local = LocalModelInfo(+ id = "m", display_name = "m", path = "/x", source = "models_dir", task = task, audio_type = audio_type+ )+ assert gguf.audio_workflows == model.audio_workflows == local.audio_workflows == workflows+ assert gguf.model_dump()["audio_workflows"] == workflows+++def test_workflow_for_audio_type_is_speak_or_music():+ assert aw.workflow_for_audio_type(AUDIO_CPP_MUSIC_AUDIO_TYPE) == "music"+ assert aw.workflow_for_audio_type("minimax_music3") == "music"+ assert aw.workflow_for_audio_type("snac") == "speak"+ assert aw.workflow_for_audio_type("unknown") == "speak"+ assert aw.workflow_for_audio_type(None) == "speak"diff --git a/studio/frontend/src/app/routes/audio.tsx b/studio/frontend/src/app/routes/audio.tsxindex 66a8eab9887..9ed9711351e 100644--- a/studio/frontend/src/app/routes/audio.tsx+++ b/studio/frontend/src/app/routes/audio.tsx@@ -2,54 +2,16 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { createRoute } from "@tanstack/react-router";-import { AUDIO_CPP_AUDIO_TYPES } from "../../features/audio/audio-cpp-catalog.ts";+import { validateAudioSearch } from "../../features/audio/route-search.ts";import { requireAuth } from "../auth-guards";import { Route as rootRoute } from "./__root";-const NATIVE_AUDIO_TYPES = new Set([- "higgs_tts2",- "moss_tts_local",- "moss_tts_nano",- "higgs_tts3",- "minimax_music3",- ...AUDIO_CPP_AUDIO_TYPES,-]);-// RootLayout renders AudioPage persistently (so an in-flight generation is not cancelled when leaving the tab); this route only owns the URL + auth gate.export const Route = createRoute({getParentRoute: () => rootRoute,path: "/audio",staticData: { title: "Audio" },- // An audio pick made from the chat picker arrives here as ?model= (+ ?quant=, ?ggufQuant=, and task), which the page loads and then clears.- validateSearch: (- search: Record<string, unknown>,- ): {- model?: string;- quant?: string;- ggufQuant?: string;- task?: string;- audioType?: string;- loadId?: string;- item?: string;- } => ({- ...(typeof search.model === "string" ? { model: search.model } : {}),- ...(typeof search.quant === "string" ? { quant: search.quant } : {}),- ...(typeof search.ggufQuant === "string"- ? { ggufQuant: search.ggufQuant }- : {}),- ...(search.task === "automatic-speech-recognition" ||- search.task === "text-to-speech"- ? { task: search.task }- : {}),- ...(typeof search.audioType === "string" &&- NATIVE_AUDIO_TYPES.has(search.audioType)- ? { audioType: search.audioType }- : {}),- ...(typeof search.loadId === "string" && search.loadId.trim()- ? { loadId: search.loadId }- : {}),- ...(typeof search.item === "string" ? { item: search.item } : {}),- }),+ validateSearch: validateAudioSearch,beforeLoad: () => requireAuth(),component: () => null,});diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsxindex 9def173f2dc..9e3c78bc820 100644--- a/studio/frontend/src/components/app-sidebar.tsx+++ b/studio/frontend/src/components/app-sidebar.tsx@@ -78,6 +78,11 @@ import {useImageWorkflowStore,} from "@/features/images/stores/image-workflow-store";import { WORKFLOW_TABS, type WorkflowId } from "@/features/images/workflows";+import { useAudioWorkspaceStore } from "@/features/audio/stores/audio-workspace-store";+import {+ AUDIO_WORKFLOWS,+ type AudioWorkflowId,+} from "@/features/audio/workflows";/* eslint-enable no-restricted-imports */import { cn } from "@/lib/utils";import { createNavigationNonce } from "@/lib/navigation-nonce";@@ -266,6 +271,7 @@ import {useMemo,useRef,useState,+ type ComponentProps,type ComponentType,type ReactNode,} from "react";@@ -706,14 +712,13 @@ const INVENTORY_SENSITIVE_REASONS = new Set(["detection_failed",]);-/** One workflow in the list under the Images row. */function WorkflowChoice({tab,active,enabled,onSelect,}: {- tab: (typeof WORKFLOW_TABS)[number];+ tab: { icon: IconSvgElement; label: string };active: boolean;enabled: boolean;onSelect: () => void;@@ -743,10 +748,21 @@ function WorkflowChoice({);}-/** Expands the workflow list on rows that do not list it outright, i.e. off the Images page. */-function ImagesNavDisclosure() {- const expanded = useImageWorkflowStore((s) => s.navExpanded);- const setExpanded = useImageWorkflowStore((s) => s.setNavExpanded);+// Spelled out per media so Tailwind sees each group name.+const IMAGES_DISCLOSURE_REVEAL =+ "group-hover/images-item:opacity-100 group-hover/images-item:pointer-events-auto";+const AUDIO_DISCLOSURE_REVEAL =+ "group-hover/audio-item:opacity-100 group-hover/audio-item:pointer-events-auto";++function MediaNavDisclosure({+ expanded,+ setExpanded,+ revealClassName,+}: {+ expanded: boolean;+ setExpanded: (expanded: boolean) => void;+ revealClassName: string;+}) {return (// Row action, so it gets the shared hover circle. Shown on row hover, kept while open.<button@@ -758,7 +774,9 @@ function ImagesNavDisclosure() {setExpanded(!expanded);}}className={cn(- "sidebar-row-action group-hover/images-item:opacity-100 group-hover/images-item:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto",+ "sidebar-row-action",+ revealClassName,+ "focus-visible:opacity-100 focus-visible:pointer-events-auto",expanded && "is-disclosure-open",)}>@@ -774,6 +792,47 @@ function ImagesNavDisclosure() {);}+function MediaWorkflowList<Id extends string>({+ tabs,+ current,+ enabled,+ listed,+ onPick,+}: {+ tabs: ReadonlyArray<{ id: Id; icon: IconSvgElement; label: string }>;+ current: Id | null;+ enabled: (id: Id) => boolean;+ listed: boolean;+ onPick: (id: Id) => void;+}) {+ if (!listed) return null;+ return (+ <div className="mt-0.5 flex flex-col gap-px pl-5">+ {tabs.map((tab) => (+ <WorkflowChoice+ key={tab.id}+ tab={tab}+ active={current === tab.id}+ enabled={enabled(tab.id)}+ onSelect={() => onPick(tab.id)}+ />+ ))}+ </div>+ );+}++function ImagesNavDisclosure() {+ const expanded = useImageWorkflowStore((s) => s.navExpanded);+ const setExpanded = useImageWorkflowStore((s) => s.setNavExpanded);+ return (+ <MediaNavDisclosure+ expanded={expanded}+ setExpanded={setExpanded}+ revealClassName={IMAGES_DISCLOSURE_REVEAL}+ />+ );+}+/*** The Images workflows, listed under their nav row. Open by default on the Images page, since* they are that page's switcher; elsewhere they stay folded until the row's chevron asks.@@ -791,22 +850,54 @@ function ImagesWorkflowList({const supported = useImageWorkflowStore((s) => s.supported);const pageMode = useImageWorkflowStore((s) => s.pageMode);const expanded = useImageWorkflowStore((s) => s.navExpanded);- if (collapsed) return null;- if (active ? pageMode === "train" : !expanded) return null;// Nothing here is current unless the page is actually showing a workflow.const current = active && pageMode === "create" ? workflow : null;return (- <div className="mt-0.5 flex flex-col gap-px pl-5">- {WORKFLOW_TABS.map((tab) => (- <WorkflowChoice- key={tab.id}- tab={tab}- active={current === tab.id}- enabled={isWorkflowEnabled(tab.id, supported)}- onSelect={() => onPick(tab.id)}- />- ))}- </div>+ <MediaWorkflowList+ tabs={WORKFLOW_TABS}+ current={current}+ enabled={(id) => isWorkflowEnabled(id, supported)}+ listed={!collapsed && (active ? pageMode !== "train" : expanded)}+ onPick={onPick}+ />+ );+}++function AudioNavDisclosure() {+ const expanded = useAudioWorkspaceStore((s) => s.navExpanded);+ const setExpanded = useAudioWorkspaceStore((s) => s.setNavExpanded);+ return (+ <MediaNavDisclosure+ expanded={expanded}+ setExpanded={setExpanded}+ revealClassName={AUDIO_DISCLOSURE_REVEAL}+ />+ );+}++const audioWorkflowAlwaysEnabled = () => true;++function AudioWorkflowList({+ active,+ collapsed,+ onPick,+}: {+ active: boolean;+ collapsed: boolean;+ onPick: (id: AudioWorkflowId) => void;+}) {+ const workflow = useAudioWorkspaceStore((s) => s.workflow);+ const requested = useAudioWorkspaceStore((s) => s.requestedWorkflow);+ const expanded = useAudioWorkspaceStore((s) => s.navExpanded);+ const current = active ? (requested ?? workflow) : null;+ return (+ <MediaWorkflowList+ tabs={AUDIO_WORKFLOWS}+ current={current}+ enabled={audioWorkflowAlwaysEnabled}+ listed={!collapsed && (active || expanded)}+ onPick={onPick}+ />);}@@ -858,6 +949,64 @@ function MoreMenuItem({);}+function AudioMoreSubmenu({+ icon,+ label,+ active,+ disabled,+ tooltip,+ badge,+ spinner,+ onIntent,+ onPick,+ contentProps,+}: {+ icon: typeof ZapIcon;+ label: string;+ active: boolean;+ disabled?: boolean;+ tooltip?: string;+ badge?: string;+ spinner?: boolean;+ onIntent?: () => void;+ onPick: (id: AudioWorkflowId) => void;+ contentProps: ComponentProps<typeof DropdownMenuSubContent>;+}) {+ const workflow = useAudioWorkspaceStore((s) => s.workflow);+ const requested = useAudioWorkspaceStore((s) => s.requestedWorkflow);+ const current = active ? (requested ?? workflow) : null;+ return (+ <DropdownMenuSub>+ <DropdownMenuSubTrigger+ disabled={disabled}+ title={tooltip}+ onPointerEnter={disabled ? undefined : onIntent}+ onFocus={disabled ? undefined : onIntent}+ className={cn("gap-2.5", active && "bg-accent/60")}+ >+ <HugeiconsIcon icon={icon} strokeWidth={1.75} />+ <span className="min-w-0 flex-1 truncate">{label}</span>+ {badge && <NavBadge label={badge} />}+ {spinner && (+ <Spinner className="size-3.5 shrink-0 text-muted-foreground" />+ )}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent {...contentProps} className="w-44 p-1">+ {AUDIO_WORKFLOWS.map((tab) => (+ <DropdownMenuItem+ key={tab.id}+ onSelect={() => onPick(tab.id)}+ className={cn(current === tab.id && "bg-accent/60")}+ >+ <HugeiconsIcon icon={tab.icon} strokeWidth={1.75} />+ <span className="min-w-0 flex-1 truncate">{tab.label}</span>+ </DropdownMenuItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ );+}+export function AppSidebar() {const t = useT();const { isDark, toggleTheme, anchorRef } = useAnimatedThemeToggle();@@ -2733,6 +2882,13 @@ export function AppSidebar() {const imagesWorkflowsListed =sidebarRowsLabelled &&!(navRows.images.active && imagesPageMode === "train");+ const audioWorkflowsListed = sidebarRowsLabelled;+ // Sidebar and More-flyout picks only ask; the Audio page switches once it is free to.+ const pickAudioWorkflow = (workflowId: AudioWorkflowId) => {+ useAudioWorkspaceStore.getState().requestWorkflow(workflowId);+ navigate({ to: "/audio" });+ closeMobileIfOpen();+ };const showSidebarBrand = true;@@ -5227,9 +5383,11 @@ export function AppSidebar() {icon={row.icon}label={row.label}badge={row.badge}- // While the workflows are listed, the current one carries the highlight, not the Images row.active={- id === "images" && imagesWorkflowsListed ? false : row.active+ (id === "images" && imagesWorkflowsListed) ||+ (id === "audio" && audioWorkflowsListed)+ ? false+ : row.active}disabled={rowState.disabled}tooltip={rowState.tooltip}@@ -5241,6 +5399,7 @@ export function AppSidebar() {className={cn(row.className,id === "images" && "group/images-item",+ id === "audio" && "group/audio-item",)}// Off the Images page the list is folded, so the row offers a way to open it.overlay={@@ -5248,6 +5407,10 @@ export function AppSidebar() {!row.active &&sidebarRowsLabelled ? (<ImagesNavDisclosure />+ ) : id === "audio" &&+ !row.active &&+ sidebarRowsLabelled ? (+ <AudioNavDisclosure />) : undefined}>@@ -5264,6 +5427,12 @@ export function AppSidebar() {closeMobileIfOpen();}}/>+ ) : id === "audio" ? (+ <AudioWorkflowList+ active={row.active}+ collapsed={!sidebarRowsLabelled}+ onPick={pickAudioWorkflow}+ />) : (row.children)}@@ -5354,6 +5523,27 @@ export function AppSidebar() {const row = navRows[id];// Same pending handling as the inline rows above.const rowState = resolveNavRowState(row);+ if (id === "audio") {+ return (+ <AudioMoreSubmenu+ key={id}+ icon={row.icon}+ label={row.label}+ badge={row.badge}+ active={row.active}+ disabled={rowState.disabled}+ tooltip={rowState.tooltip}+ spinner={rowState.spinner}+ onIntent={row.onIntent}+ onPick={pickAudioWorkflow}+ contentProps={{+ ...sidebarSubmenuOffsets,+ // Portaled outside the flyout, so the flyout's hover grace has to cover it too.+ ...moreHover.content,+ }}+ />+ );+ }return (<MoreMenuItemkey={id}diff --git a/studio/frontend/src/features/audio/api.ts b/studio/frontend/src/features/audio/api.tsindex 59ca8119d8a..8f8e482ec6b 100644--- a/studio/frontend/src/features/audio/api.ts+++ b/studio/frontend/src/features/audio/api.ts@@ -92,6 +92,8 @@ export interface AudioGalleryClip {archived?: boolean;/** The server's unpinned sort key: the drag key, else the file mtime. */order_at?: number | null;+ /** The Audio workflow that made the clip. Older servers omit it; read it through clipWorkflow. */+ workflow?: string | null;}export interface AudioGalleryListResponse {@@ -195,21 +197,28 @@ export async function deleteAudioClip(id: string): Promise<void> {if (!response.ok) throw new Error(await readFastApiError(response));}-export async function clearAudioGallery(): Promise<number> {- const response = await authFetch("/api/inference/audio/gallery", {+export async function clearAudioGallery(+ workflow?: "speak" | "music",+): Promise<number> {+ const query = workflow ? `?workflow=${workflow}` : "";+ const response = await authFetch(`/api/inference/audio/gallery${query}`, {method: "DELETE",});const body = await parseJson<{ removed: number }>(response);return body.removed;}-export async function fetchClipObjectUrl(- url: string,-): Promise<{ url: string; bytes: number }> {+export async function fetchClipBlob(url: string): Promise<Blob> {const response = await authFetch(url);if (!response.ok) throw new Error(await readFastApiError(response));- const blob = await response.blob();- return { url: URL.createObjectURL(blob), bytes: blob.size };+ return response.blob();+}++export async function fetchClipObjectUrl(+ url: string,+): Promise<{ url: string; bytes: number; blob: Blob }> {+ const blob = await fetchClipBlob(url);+ return { url: URL.createObjectURL(blob), bytes: blob.size, blob };}export async function transcribeWithProgress(diff --git a/studio/frontend/src/features/audio/audio-page-policy.ts b/studio/frontend/src/features/audio/audio-page-policy.tsindex 01bcc355857..b88247fd233 100644--- a/studio/frontend/src/features/audio/audio-page-policy.ts+++ b/studio/frontend/src/features/audio/audio-page-policy.ts@@ -183,6 +183,15 @@ export function nativeAudioInstructionsKind(return null;}+export function instructionsFieldKind(+ workflow: "speak" | "music",+ audioType?: string | null,+): NativeAudioInstructionsKind | null {+ if (workflow === "music") return "music";+ const kind = nativeAudioInstructionsKind(audioType);+ return kind === "music" ? null : kind;+}+/** The music length range the loaded model honours. The GGUF runtime clamps tighter than the* MiniMax Music 3 pipeline; both take the same 25 frames per second. */export function musicDurationRange(requiresCuda: boolean): {@@ -450,6 +459,35 @@ export function expectedGgufDownloadBytes(variant: AutoGgufVariant): number {: variant.size_bytes;}+/** The first `wanted` gallery rows fetched in pages of at most `maxPage`, merged into one page. */+export async function fetchGalleryWindow<+ C extends { id: string },+ P extends { audio: C[]; has_more: boolean },+ K,+>(+ fetchPage: (limit: number, cursor: K | null) => Promise<P>,+ cursorOf: (page: P) => K | null,+ wanted: number,+ maxPage: number,+ cancelled: () => boolean = () => false,+): Promise<P> {+ let page = await fetchPage(Math.min(wanted, maxPage), null);+ const audio = [...page.audio];+ const seen = new Set(audio.map((clip) => clip.id));+ while (audio.length < wanted && page.has_more && !cancelled()) {+ const cursor = cursorOf(page);+ if (cursor === null) break;+ page = await fetchPage(Math.min(maxPage, wanted - audio.length), cursor);+ if (page.audio.length === 0) break;+ for (const clip of page.audio) {+ if (seen.has(clip.id)) continue;+ seen.add(clip.id);+ audio.push(clip);+ }+ }+ return { ...page, audio };+}+/** Fold a freshly fetched first page into the list already on screen. The page is authoritative* for the newest `page.length` clips and any scrollback below it is kept; replacing outright* collapsed a paginated History on every delete and reselected a different clip.@@ -622,3 +660,27 @@ export function micStreamRequestIsCurrent(): boolean {return active && requestGeneration === currentGeneration;}++/**+ * The line said above Generate when the run will load or switch the model first, so the wait is+ * expected: "Loads Kokoro for Speak, about 5 s". Null when nothing will load.+ */+export function modelLoadNote({+ model,+ page,+ seconds,+}: {+ model: string | null;+ page: string;+ seconds?: number | null;+}): string | null {+ if (!model) return null;+ const about =+ seconds !== null &&+ seconds !== undefined &&+ Number.isFinite(seconds) &&+ seconds > 0+ ? `, about ${Math.max(1, Math.round(seconds))} s`+ : "";+ return `Loads ${model} for ${page}${about}`;+}diff --git a/studio/frontend/src/features/audio/audio-page.tsx b/studio/frontend/src/features/audio/audio-page.tsxindex 72b78769349..e3d505cbeed 100644--- a/studio/frontend/src/features/audio/audio-page.tsx+++ b/studio/frontend/src/features/audio/audio-page.tsx@@ -1,323 +1,81 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-// The Audio page: Generate (TTS via the main inference slot) and Transcribe (STT via the dictation sidecar).-// The page stays mounted across tab switches (see __root.tsx), so `active` gates polling, popovers and the-// recorder rather than lifecycle.+// Stays mounted across tab switches (__root.tsx), so `active` gates polling, popovers and the recorder.import { TestTubeOutlineIcon } from "@/lib/hugeicons-derived";-import {- AudioWave01Icon,- Copy01Icon,- Delete02Icon,- Download01Icon,- Mic01Icon,- SparklesIcon,- StopIcon,-} from "@hugeicons/core-free-icons";+import { SparklesIcon } from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";import { LibraryPageLink } from "@/components/media-page-link";-import { translate } from "@/i18n";-import {- type ReactNode,- useCallback,- useEffect,- useMemo,- useRef,- useState,-} from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { AdvancedDisclosure } from "@/components/advanced-disclosure";-import { GalleryItemMenu, GalleryPinBadge } from "@/components/gallery-item-menu";-import { StripDropLine } from "@/components/gallery-strip-reorder";-import { useStripReorder } from "@/hooks/use-strip-reorder";import { MediaRailResizeHandle } from "@/components/media-rail-resize-handle";import { MEDIA_RAIL_ROOT_ATTR, useMediaRailWidth } from "@/hooks/use-media-rail-width";import { GuidedTour, useGuidedTourController } from "@/features/tour";import { buildAudioTourSteps } from "./tour";-import { Button } from "@/components/ui/button";-import { DropdownMenuItem } from "@/components/ui/dropdown-menu";-import { Input } from "@/components/ui/input";-import { Progress } from "@/components/ui/progress";import { useSidebar } from "@/components/ui/sidebar";-import { Textarea } from "@/components/ui/textarea";import { usePlatformStore } from "@/config/env";-import {- type InferenceStatusResponse,- ParamSlider,- cancelPreStreamRunReservations,- confirmStopRunningChatsIfNeeded,- getInferenceStatus,- listGgufVariants,- listLoras,- loadModel,- offloadCountsFrom,- offloadWarning,- requestLocalPromptQueueStop,- unloadModel,- useChatRuntimeStore,-} from "@/features/chat";-import {- PcmRecorder,- type SegmentRecorder,- createAudioRecorder,-} from "@/features/chat/adapters/pcm-recorder";-import {- SttModelNotDownloadedError,- StudioModelDictationAdapter,- fetchSttStatus,- loadSttModel,- startSttDownload,- sttEngineStatusFor,- unloadSttModel,-} from "@/features/chat/adapters/studio-model-dictation-adapter";-import { useStagedDownload } from "@/features/hub/download-manager";-import { getHfToken, hfApiToken } from "@/features/hub/stores/hf-token-store";+import { type InferenceStatusResponse, getInferenceStatus } from "@/features/chat";import { ModelSelector } from "@/features/model-picker/components/model-selector";import { AUDIO_CATALOG } from "@/features/model-picker/components/model-selector/model-catalog";import { PillTabs } from "@/features/model-picker/components/model-selector/pill-tabs";-import type {- ModelOption,- ModelSelectorChangeMeta,-} from "@/features/model-picker/components/model-selector/types";-import { confirmRemoteCodeIfNeeded } from "@/features/security";-import { useSettingsDialogStore, useVoiceSettingsStore } from "@/features/settings";-import {- isTrackingSttDownload,- trackSttDownload,-} from "@/features/settings/lib/stt-download-mirror";+import type { ModelOption } from "@/features/model-picker/components/model-selector/types";import { sttModelSize } from "@/features/settings/stores/stt-model-catalog";-import { TranscriptGallery } from "./transcript-gallery";-import { AUTH_SESSION_ENDING_EVENT } from "@/features/auth";-import {- readTranscriptDraft,- transcriptDraftKey,- writeTranscriptDraft,-} from "./transcript-draft";-import { downloadTranscript } from "./transcript-download";-import { TranscriptionProgress } from "./transcription-progress";-import type { TranscriptRecord, TranscriptProgress } from "./transcript-stream";import { usePersistedChoice } from "@/hooks/use-persisted-choice";import { usePersistedToggle } from "@/hooks/use-persisted-toggle";import { useScrollFades } from "@/hooks/use-scroll-fades";-import { fetchSystemInfo } from "@/hooks/use-system";import { isTauri } from "@/lib/api-base";-import { BlobUrlCache } from "@/lib/blob-url-cache";-import { copyToClipboard } from "@/lib/copy-to-clipboard";-import {- applyPin,- moveGalleryItem,- pinnedOrder,- restorePinOrder,- serializeById,- sortGalleryItems,- subscribeGalleryChanged,-} from "@/lib/gallery-flags";import { subscribeModelLifecycle } from "@/lib/model-lifecycle-events";import { toast } from "@/lib/toast";-import { loadGalleryUntil } from "@/lib/gallery-deep-link";-import { readLastPrompt, saveLastPrompt } from "@/lib/last-prompt";import { cn } from "@/lib/utils";import { useIsMobileShell } from "@/hooks/use-mobile";-import { useNavigate, useSearch } from "@tanstack/react-router";-import {- type AudioGalleryClip,- type AudioGalleryCursor,- addAudioClipToProject,- audioGalleryCursor,- clearAudioGallery,- deleteAudioClip,- fetchClipObjectUrl,- generateAudio,- getAudioDownloadPlan,- listAudioGallery,- moveAudioClip,- setAudioClipFlags,- transcribeWithProgress,-} from "./api";+import { type AudioGalleryClip, fetchClipBlob } from "./api";import {type AudioBusy,type AudioGenerationPhase,- MINIMAX_MUSIC_DEFAULT_SECONDS,- MINIMAX_MUSIC_FRAMES_PER_SECOND,- MOSS_TTS_DEFAULT_SECONDS,- MOSS_TTS_FRAMES_PER_SECOND,- MOSS_TTS_MAX_FRAMES,- type SttDownloadedArtifact,audioGenerationPresentation,- canTransitionAudioMode,- exactGgufLoadSelector,- expectedGgufDownloadBytes,- isGgufTtsTarget,- isTtsAudioType,- macTtsPickAction,- mergeGalleryPage,- micStreamRequestIsCurrent,- audioCppRuntimeProblem,- audioSamplingControlsApply,- minimaxMusicFramesForSeconds,- musicDurationRange,- musicLyricsOptional,- musicNeedsDescription as musicModelNeedsDescription,- mossTtsFramesForSeconds,- mossTtsMaxFrames,- nativeAudioInstructionsKind,- persistedClipForGeneration,- reconcileSttSelection,- resolveAudioPickTask,- resolveSttResidency,- selectAutoGgufVariant,- stagedTtsLoadIsOwned,- sttDownloadedArtifacts,- sttSelectionReady,- trainedTtsCheckpointIsLoadable,- trainedTtsCheckpointIsRunnableOnMac,+ instructionsFieldKind,} from "./audio-page-policy";-import {- AUDIO_CPP_MUSIC_AUDIO_TYPE,- AUDIO_CPP_TTS_AUDIO_TYPE,- type AudioCppRuntimeStatus,- audioCppDisplayName,- isAudioCppFolderId,-} from "./audio-cpp-catalog";-import { AudioOptionFields } from "./audio-options-fields";-import {- type AudioOptionValue,- type AudioOptionValues,- audioOptionLabel,- audioOptionsForRequest,- missingRequiredAudioOptions,- parseAudioOptions,- readAudioOptionValues,- saveAudioOptionValues,-} from "./audio-options";+import { type CreateMode, deviceSizeBytes } from "./audio-workspace-utils";import {audioCapabilityLine,- audioModelRequiresRemoteCode,audioModelsForTask,- audioTaskFor,- ggufSiblingFor,isMusicGenerationModel,- macTtsCatalogChoiceIsRunnable,- musicGenerationRequiresCuda,- sttEngineForRepoId,- sttRepoIdForSidecarKey,- sttSidecarKeyFor,- type AudioSttEngine,- usesNativeAudioRuntime,} from "./catalog";+import type { ClipSendHandlers } from "./components/clip-card";+import { WorkflowTitleMenu } from "./components/workflow-title-menu";+import { galleryCache, useAudioGallery, useWorkflowHistory } from "./hooks/use-audio-gallery";+import { useAudioHandoff } from "./hooks/use-audio-handoff";+import { useAudioModelSlot } from "./hooks/use-audio-model-slot";+import { useSpeechGeneration } from "./hooks/use-speech-generation";+import { useSttSidecar } from "./hooks/use-stt-sidecar";+import { useTranscription } from "./hooks/use-transcription";+import { MusicOutput, MusicRail, musicPageModels } from "./pages/music-page";+import { SpeakOutput, SpeakRail, speakPageModels } from "./pages/speak-page";+import { type GenerateBlocker, TtsFooter } from "./pages/tts-workspace";+import { TranscribeOutput, TranscribeRail } from "./pages/transcribe-page";+import { type AudioPickerRow, audioRowMatchesWorkflow } from "./picker-filter";+import { useAudioWorkspaceStore } from "./stores/audio-workspace-store";+import { InstructionsField, MossLanguageField } from "./components/instructions-fields";+import {+ type AudioWorkflowId,+ audioWorkflowTab,+ clipWorkflow,+ slotForWorkflow,+} from "./workflows";const MODELS_BY_MODE: Record<CreateMode, ModelOption[]> = {speak: audioModelsForTask("tts"),transcribe: audioModelsForTask("stt"),};-/** What to call a model on screen. A Hub repo is its id; a checkpoint trained here is an output- * directory, and the full path in a toast reads as a bug. */-function audioModelLabel(id: string): string {- // A package folder of the shared GGUF repo is known by its folder name, as the Hub shows it.- if (isAudioCppFolderId(id)) return audioCppDisplayName(id);- if (!/^(?:[a-zA-Z]:[\\/]|[\\/]|~)/.test(id)) return id;- const leaf = id.split(/[\\/]/).filter(Boolean).pop() ?? id;- // Training stamps the output directory with an epoch; it means nothing to a reader.- return leaf.replace(/_\d{10,}$/, "");-}--/** The load toast's kind: the codec or runtime name, except for the GGUF runtime's internal ones. */-function loadedAudioKind(audioType: string | null | undefined): string {- if (audioType === AUDIO_CPP_TTS_AUDIO_TYPE) return "speech";- if (audioType === AUDIO_CPP_MUSIC_AUDIO_TYPE) return "music";- return audioType ?? "audio";-}--function deviceSizeBytes(label: string): number {- const match = label.trim().match(/^(\d+(?:\.\d+)?)\s*(MB|GB)$/i);- if (!match) return 0;- const value = Number(match[1]);- return value * (match[2].toUpperCase() === "GB" ? 1024 ** 3 : 1024 ** 2);-}// Music GGUFs carry text-to-audio. The Hub rows it adds still pass the speech runtime gate.const HUB_TASKS_BY_MODE = {speak: ["text-to-speech", "text-to-audio"],transcribe: ["automatic-speech-recognition"],} as const;-const PAGE_SIZE = 50;-// The list route clamps a page to 200, so asking for more silently gets 200 back.-const MAX_PAGE_SIZE = 200;-// Mirrors the STT sidecar's own limits, so a recording is stopped at the boundary rather than uploaded and refused.-// The two it mirrors are _MAX_AUDIO_SECONDS and STT_AUDIO_B64_MAX_CHARS.-const RECORDING_MAX_SECONDS = 30 * 60;-// STT_AUDIO_RAW_MAX_BYTES in utils/upload_limits.py. A larger client cap let a dense codec build-// a recording the raw route then refused with 413.-const RECORDING_MAX_BYTES = 25 * 1024 * 1024;-const RECORDING_CHUNK_MS = 1000;-const TTS_MAX_TOKENS = 8192;-// Max tokens caps the OUTPUT and the prompt's own tokens sit in the same context window, so-// loading at exactly TTS_MAX_TOKENS made the advertised maximum unreachable.-const TTS_PROMPT_CONTEXT_RESERVE = 2048;-// WAV clips run a few MB a minute; 64 MB keeps a healthy scrollback resident.-const CLIP_BLOB_BUDGET_BYTES = 64 * 1024 * 1024;--// Module scope so a tab switch re-renders the gallery instantly.-const galleryCache: {- clips: AudioGalleryClip[];- hasMore: boolean;- nextCursor: AudioGalleryCursor | null;- selectedId: string | null;- srcById: BlobUrlCache;-} = {- clips: [],- hasMore: false,- nextCursor: null,- selectedId: null,- srcById: new BlobUrlCache(CLIP_BLOB_BUDGET_BYTES),-};--type CreateMode = "speak" | "transcribe";-type RemoteCodeApproval = {- trustRemoteCode: true;- approvedRemoteCodeFingerprint: string | null;-};--function Field({- label,- hint,- htmlFor,- children,-}: {- label: string;- hint?: string;- htmlFor: string;- children: ReactNode;-}) {- return (- <div className="grid gap-1.5">- <label- className="text-ui-13 font-medium text-foreground"- htmlFor={htmlFor}- >- {label}- </label>- {children}- {hint ? (- <p className="text-ui-11p5 leading-snug text-muted-foreground">- {hint}- </p>- ) : null}- </div>- );-}--function formatClipDuration(seconds: number): string {- if (!Number.isFinite(seconds) || seconds <= 0) return "0:00";- const whole = Math.round(seconds);- const minutes = Math.floor(whole / 60);- const rest = whole % 60;- return `${minutes}:${String(rest).padStart(2, "0")}`;-}-export function AudioPage({active = true,onInitialReady,@@ -330,8 +88,21 @@ export function AudioPage({const isMobileShell = useIsMobileShell();const { pinned } = useSidebar();const [mode, setMode] = useState<CreateMode>("speak");+ const workflow = useAudioWorkspaceStore((state) => state.workflow);+ const pageWorkflow: AudioWorkflowId =+ slotForWorkflow(workflow) === mode+ ? workflow+ : mode === "transcribe"+ ? "transcribe"+ : "speak";+ const ttsWorkflow: "speak" | "music" =+ pageWorkflow === "music" ? "music" : "speak";+ const workflowTab = audioWorkflowTab(pageWorkflow);const { rootStyle: railRootStyle } = useMediaRailWidth("audio");- const tourSteps = useMemo(() => buildAudioTourSteps({ mode }), [mode]);+ const tourSteps = useMemo(+ () => buildAudioTourSteps({ workflow: pageWorkflow }),+ [pageWorkflow],+ );const tour = useGuidedTourController({id: "audio",steps: tourSteps,@@ -354,26 +125,6 @@ export function AudioPage({const generationPresentation = audioGenerationPresentation(generationPhase);const [status, setStatus] = useState<InferenceStatusResponse | null>(null);- // Starts from the last text generated with.- const [prompt, setPrompt] = useState(() => readLastPrompt("audio"));- const [audioInstructions, setAudioInstructions] = useState("");- const [audioLanguage, setAudioLanguage] = useState("");- const [temperature, setTemperature] = useState(0.6);- // Sending temperature unconditionally puts it in the request's model_fields_set, which the backend reads as an- // explicit client override that beats the per-model recommendation (Spark-TTS wants 0.8, OuteTTS 0.4), so only- // send it once the user has moved the slider.- const [temperatureEdited, setTemperatureEdited] = useState(false);- const handleTemperatureChange = useCallback((value: number) => {- setTemperatureEdited(true);- setTemperature(value);- }, []);- const [maxTokens, setMaxTokens] = useState(2048);- const [mossMaxSeconds, setMossMaxSeconds] = useState(- MOSS_TTS_DEFAULT_SECONDS,- );- const [minimaxMaxSeconds, setMinimaxMaxSeconds] = useState(- MINIMAX_MUSIC_DEFAULT_SECONDS,- );const generateAbort = useRef<AbortController | null>(null);const handleStopGeneration = useCallback(() => {const controller = generateAbort.current;@@ -381,175 +132,11 @@ export function AudioPage({updateGenerationPhase("stopping");controller.abort();}, [updateGenerationPhase]);- const ttsLoadInFlight = useRef(false);- // A pick that lost the race with a load still settling. Replayed once it does.- const pendingRoutedTtsPick = useRef<{- repoId: string;- ggufFilename?: string | null;- loadId?: string | null;- audioType?: string | null;- remoteCodeApproval?: RemoteCodeApproval;- isGguf?: boolean | null;- } | null>(null);const ttsStatusRefreshGeneration = useRef(0);- const ttsLoadGeneration = useRef(0);- const pendingTtsLoad = useRef<{- generation: number;- repoId: string;- /** What the load request actually sent, which is what a cancel has to name. */- loadTarget: string;- loadRequestId: string;- controller: AbortController;- requestStarted: boolean;- } | null>(null);-- const [lastSttRepo, setLastSttRepoChoice] = usePersistedChoice("unsloth:audio:last-stt-model", "");- // The quant a package pick (Moonshine tiny or small) asked for, so a restart reloads that one, not the default.- const [lastSttVariant, setLastSttVariant] = usePersistedChoice("unsloth:audio:last-stt-variant", "");- const [selectedSttRepo, setSelectedSttRepo] = useState<string | null>(null);- const [sttLoadedModel, setSttLoadedModel] = useState<string | null>(null);- const [sttLoadedEngine, setSttLoadedEngine] = useState<- AudioSttEngine | null- >(null);- const [downloadedSttArtifacts, setDownloadedSttArtifacts] = useState<- SttDownloadedArtifact[]- >([]);- const [draftKey] = useState(transcriptDraftKey);- const [recoveredTranscript] = useState(() => readTranscriptDraft(draftKey));- const [transcript, setTranscript] = useState(recoveredTranscript?.text ?? "");- const [transcribedName, setTranscribedName] = useState<string | null>(recoveredTranscript?.title ?? null);- const [transcriptModel, setTranscriptModel] = useState(recoveredTranscript?.model ?? "");- const [transcriptRecord, setTranscriptRecord] = useState<TranscriptRecord | null>(null);- const [transcriptExported, setTranscriptExported] = useState(false);- const transcriptVersion = useRef(0);- const [transcriptionStartedAt, setTranscriptionStartedAt] = useState<number | null>(null);- const [transcriptionFinishedAt, setTranscriptionFinishedAt] = useState<number | null>(null);- const [transcriptionStopping, setTranscriptionStopping] = useState(false);- const [transcriptionProgress, setTranscriptionProgress] = useState<TranscriptProgress | null>(null);- const [transcriptError, setTranscriptError] = useState<string | null>(null);- const [isRecording, setIsRecording] = useState(false);- const [micRequestPending, setMicRequestPending] = useState(false);- /** Safari and other WebKit builds ship no MediaRecorder, and an http LAN origin is not a secure- * context, so navigator.mediaDevices is undefined. Same check the chat composer uses. */- const recordingSupported = useMemo(- () => StudioModelDictationAdapter.isSupported(),- [],- );- /** Audio the server produced that the gallery is not showing yet: either it could not be- * persisted, or this refresh missed it. Kept so the generation is playable either way. */- const [fallbackClip, setFallbackClip] = useState<{- url: string;- prompt: string;- model: string;- saved: boolean;- } | null>(null);- const fallbackClipRef = useRef(fallbackClip);- fallbackClipRef.current = fallbackClip;- const loadingMoreRef = useRef(false);- const galleryRefreshGeneration = useRef(0);- // Pins and moves in flight. A refresh that overlaps one read the old order, so it is dropped and rerun after.- const orderWrites = useRef({ inFlight: 0, epoch: 0, deferred: false });- const recorderRef = useRef<SegmentRecorder | null>(null);- const recordStreamRef = useRef<MediaStream | null>(null);- const discardRecordingRef = useRef(false);- const selectedSttRepoRef = useRef<string | null>(selectedSttRepo);- selectedSttRepoRef.current = selectedSttRepo;const activeRef = useRef(active);activeRef.current = active;const modeRef = useRef(mode);modeRef.current = mode;- const sttStatusRefreshGeneration = useRef(0);- // What the installed GGUF audio runtime can run, from the STT status poll. Null until it answers.- const audioCppRuntime = useRef<AudioCppRuntimeStatus | null>(null);- const sttLoadGeneration = useRef(0);- /** The GGUF quant each picked STT repo asked for, by lowercased repo id. */- const sttGgufVariants = useRef(- new Map<string, string>(- lastSttRepo && lastSttVariant ? [[lastSttRepo.toLowerCase(), lastSttVariant]] : [],- ),- );- const setLastSttRepo = useCallback(- (repo: string) => {- setLastSttRepoChoice(repo);- setLastSttVariant(sttGgufVariants.current.get(repo.toLowerCase()) ?? "");- },- [setLastSttRepoChoice, setLastSttVariant],- );- const sttLoadingGeneration = useRef<number | null>(null);- // Residency is not ownership: the activation resync adopts whatever a sidecar already holds, including a model- // chat dictation loaded. The identity, not a boolean, since another surface can replace the sidecar's model- // while Audio is inactive and a bare flag would claim that too. Keyed on the model alone, since a "gguf" pick- // without whisper-server comes back resident under the Transformers fallback.- const sttLoadedByThisPage = useRef<string | null>(null);- const sttLoadAbort = useRef<AbortController | null>(null);- const deferredSttLoad = useRef<{- repoId: string;- sidecarKey: string;- engine: AudioSttEngine;- } | null>(null);- const ttsPickGeneration = useRef(0);- const ttsInspectionGeneration = useRef<number | null>(null);- const stagedTtsGeneration = useRef(0);- const pendingStagedTtsLoad = useRef<{- repoId: string;- ggufFilename: string | null;- loadId?: string | null;- audioType?: string | null;- remoteCodeApproval?: RemoteCodeApproval;- isGguf?: boolean | null;- generation: number;- } | null>(null);- const stagedTtsLoadDeferred = useRef(false);- const micRequestGeneration = useRef(0);- const micPendingGeneration = useRef<number | null>(null);- const transcriptionAbort = useRef<AbortController | null>(null);-- const stopRecordStream = useCallback(() => {- for (const track of recordStreamRef.current?.getTracks() ?? [])- track.stop();- recordStreamRef.current = null;- }, []);- const stopAndDiscardRecording = useCallback(() => {- // Also invalidates a getUserMedia request that has not resolved yet; its eventual stream is- // stopped before a MediaRecorder can be created.- micRequestGeneration.current += 1;- micPendingGeneration.current = null;- setMicRequestPending(false);- const recorder = recorderRef.current;- if (recorder) {- discardRecordingRef.current = true;- if (recorder.state !== "inactive") recorder.stop();- recorderRef.current = null;- setIsRecording(false);- }- stopRecordStream();- }, [stopRecordStream]);-- const [clips, setClips] = useState<AudioGalleryClip[]>(galleryCache.clips);- const [hasMore, setHasMore] = useState(galleryCache.hasMore);- const [selectedId, setSelectedId] = useState<string | null>(- galleryCache.selectedId,- );- const [srcById, setSrcById] = useState<Record<string, string>>(- galleryCache.srcById.toRecord(),- );- const clipSrcLoads = useRef<Map<string, Promise<void>>>(new Map());- const mossFrameLimit = mossTtsMaxFrames(- status?.audio_type,- status?.context_length,- );- const mossMaxSecondsLimit =- (mossFrameLimit ?? MOSS_TTS_MAX_FRAMES) / MOSS_TTS_FRAMES_PER_SECOND;-- useEffect(() => {- setTemperature(mossFrameLimit !== null ? 1.7 : 0.6);- setTemperatureEdited(false);- if (mossFrameLimit !== null) {- setMossMaxSeconds((current) =>- Math.min(current, mossFrameLimit / MOSS_TTS_FRAMES_PER_SECOND),- );- }- }, [mossFrameLimit]);const {attach: attachSettingsScroll,@@ -579,321 +166,101 @@ export function AudioPage({}}, []);- const clearTranscript = useCallback(() => {- transcriptVersion.current += 1;- setTranscript("");- setTranscribedName(null);- setTranscriptError(null);- setTranscriptModel("");- setTranscriptRecord(null);- setTranscriptExported(false);- }, []);-- const confirmTranscriptReplacement = useCallback(() => {- if (busyRef.current !== null) return false;- return (- !transcript ||- transcriptRecord !== null ||- transcriptExported ||- window.confirm(- "This transcript could not be saved. Download it before continuing, or continue and discard it?",- )- );- }, [transcript, transcriptRecord, transcriptExported]);-- useEffect(() => {- const unsaved = Boolean(- transcript && transcriptRecord === null && !transcriptExported,- );- if (!writeTranscriptDraft(- draftKey,- unsaved ? {- text: transcript,- title: transcribedName ?? "Transcript",- model: transcriptModel,- } : null,- )) {- toast.error("Could not update transcript recovery. Download unsaved text before leaving.");- }- if (isTauri) {- void import("@tauri-apps/api/core")- .then(({ invoke }) =>- invoke("set_renderer_activity", {- kind: "unsaved_transcript",- active: unsaved,- }),- )- .catch(() =>- toast.error("Could not update transcript close protection."),- );- }- if (!unsaved) return;- const warn = (event: BeforeUnloadEvent) => {- event.preventDefault();- event.returnValue = "";- };- const confirmLogout = (event: Event) => {- if (- !window.confirm(- "This transcript could not be saved. Download it before logging out, or log out and discard it?",- )- ) {- event.preventDefault();- } else if (!writeTranscriptDraft(draftKey, null)) {- event.preventDefault();- toast.error("Could not discard the transcript recovery copy. Try again.");- }- };- window.addEventListener("beforeunload", warn);- window.addEventListener(AUTH_SESSION_ENDING_EVENT, confirmLogout);- return () => {- window.removeEventListener("beforeunload", warn);- window.removeEventListener(AUTH_SESSION_ENDING_EVENT, confirmLogout);- };- }, [draftKey, transcript, transcribedName, transcriptModel, transcriptRecord, transcriptExported]);-- const refreshSttStatus = useCallback(async () => {- const generation = ++sttStatusRefreshGeneration.current;- try {- const selectedRepo = selectedSttRepoRef.current;- const selectedKey = selectedRepo ? sttSidecarKeyFor(selectedRepo) : null;- const selectedEngine = selectedRepo- ? sttEngineForRepoId(selectedRepo)- : null;- const stt = await fetchSttStatus(- undefined,- selectedEngine === "transformers"- ? (selectedKey ?? undefined)- : undefined,- );- if (generation !== sttStatusRefreshGeneration.current) return;- audioCppRuntime.current = stt.audio_cpp_runtime ?? null;- const nextDownloadedArtifacts = sttDownloadedArtifacts(- stt,- sttRepoIdForSidecarKey,- );- setDownloadedSttArtifacts((current) =>- current.length === nextDownloadedArtifacts.length &&- current.every(- (artifact, index) =>- artifact.repoId === nextDownloadedArtifacts[index].repoId &&- artifact.sidecarKey === nextDownloadedArtifacts[index].sidecarKey &&- artifact.engine === nextDownloadedArtifacts[index].engine,- )- ? current- : nextDownloadedArtifacts,- );- const selectedBlock = selectedKey- ? (sttEngineStatusFor(stt, selectedKey, selectedEngine ?? undefined) ??- (selectedEngine === "transformers" ? stt : undefined))- : undefined;- const preservePending = Boolean(- selectedBlock?.loading ||- sttLoadingGeneration.current !== null ||- deferredSttLoad.current !== null,- );- const residency = resolveSttResidency(- stt,- selectedEngine,- preservePending,- );- const loadedModel = residency?.model ?? null;- setSttLoadedModel(loadedModel);- setSttLoadedEngine(residency?.engine ?? null);- const reconciled = reconcileSttSelection({- selectedRepo,- loadedModel,- loadedEngine: residency?.engine,- preservePending,- sidecarKeyFor: sttSidecarKeyFor,- repoIdForSidecarKey: sttRepoIdForSidecarKey,- engineForRepo: sttEngineForRepoId,- });- selectedSttRepoRef.current = reconciled;- setSelectedSttRepo(reconciled);- } catch {- if (generation !== sttStatusRefreshGeneration.current) return;- setSttLoadedModel(null);- setSttLoadedEngine(null);- }- }, []);+ const isMac = usePlatformStore((s) => s.deviceType) === "mac";- const sttSelected = selectedSttRepo !== null;- const sttReady = sttSelectionReady(+ const {+ lastSttRepo,selectedSttRepo,+ setSelectedSttRepo,sttLoadedModel,- sttSidecarKeyFor,- selectedSttRepo ? sttEngineForRepoId(selectedSttRepo) : null,sttLoadedEngine,- );-- /** Forget the Transcribe pick, releasing its sidecar when this page owns it. */- const releaseTranscribeSelection = useCallback(async () => {- const selected = selectedSttRepoRef.current;- const claim = sttLoadedByThisPage.current;- const owned =- sttReady &&- selected !== null &&- claim !== null &&- claim === sttLoadedModel;- const forget = () => {- deferredSttLoad.current = null;- selectedSttRepoRef.current = null;- sttLoadGeneration.current += 1;- sttLoadedByThisPage.current = null;- setSelectedSttRepo(null);- };- if (!owned) {- forget();- return;- }- // Forget only once the sidecar is actually released: clearing first left a failed unload with the model in- // VRAM and no Eject to retry with. Scoped to the model this page claimed, since another surface can switch the- // same engine before the request lands.- await unloadSttModel(sttEngineForRepoId(selected), claim);- forget();- await refreshSttStatus();- }, [refreshSttStatus, sttReady, sttLoadedModel]);-- const ensureClipSrc = useCallback(async (clip: AudioGalleryClip) => {- const cached = galleryCache.srcById.get(clip.id);- if (cached) {- galleryCache.srcById.touch(clip.id);- return;- }- const pending = clipSrcLoads.current.get(clip.id);- if (pending) return pending;- const load = (async () => {- try {- const fetched = await fetchClipObjectUrl(clip.url);- // A delete can finish while protected bytes are in flight. Do not revive its cache entry after- // the row is already gone.- if (!galleryCache.clips.some((candidate) => candidate.id === clip.id)) {- URL.revokeObjectURL(fetched.url);- return;- }- galleryCache.srcById.set(clip.id, fetched.url, fetched.bytes);- galleryCache.srcById.prune(- galleryCache.selectedId ? [galleryCache.selectedId] : [],- );- setSrcById(galleryCache.srcById.toRecord());- } catch {- // Clip may have been deleted server-side; the next gallery refresh drops it.- toast.error("Could not load this audio clip. Try selecting it again.");- }- })();- clipSrcLoads.current.set(clip.id, load);- try {- await load;- } finally {- if (clipSrcLoads.current.get(clip.id) === load) {- clipSrcLoads.current.delete(clip.id);- }- }- }, []);+ downloadedSttArtifacts,+ selectedSttRepoRef,+ sttStatusRefreshGeneration,+ audioCppRuntime,+ sttLoadGeneration,+ sttGgufVariants,+ setLastSttRepo,+ sttLoadingGeneration,+ sttLoadAbort,+ deferredSttLoad,+ refreshSttStatus,+ sttSelected,+ sttReady,+ releaseTranscribeSelection,+ ensureSttLoaded,+ } = useSttSidecar({ setBusy, activeRef });- const refreshGallery = useCallback(- async (- removedId?: string,- windowSize = PAGE_SIZE,- ): Promise<AudioGalleryClip[]> => {- const generation = ++galleryRefreshGeneration.current;- const writeEpoch = orderWrites.current.epoch;- const wanted = Math.max(PAGE_SIZE, windowSize);- const asked = Math.min(wanted, MAX_PAGE_SIZE);- try {- const page = await listAudioGallery(0, asked);- // The caller's own fetch: a generation whose clip persisted must not be told otherwise.- if (generation !== galleryRefreshGeneration.current) return page.audio;- if (orderWrites.current.inFlight > 0 || orderWrites.current.epoch !== writeEpoch) {- orderWrites.current.deferred = true;- return page.audio;- }- // A window past the route's cap cannot be covered in one page, and stitching the old scrollback- // back on keeps a cursor that starts BELOW it, stranding whatever was restored.- const { clips: merged, stitched } =- wanted > asked- ? { clips: [...page.audio], stitched: false }- : mergeGalleryPage(- page.audio,- galleryCache.clips,- removedId,- page.has_more,- );- galleryCache.clips = merged;- // A clip record carries no mtime, so kept scrollback has no cursor; keep the deeper one.- if (!stitched) {- galleryCache.hasMore = page.has_more;- galleryCache.nextCursor = audioGalleryCursor(page);- }- setClips(merged);- setHasMore(galleryCache.hasMore);- // The response audio was kept only until its record showed up: left mounted, deleting the- // now-visible clip made the "saved, waiting for the gallery" copy reappear.- if (- fallbackClipRef.current &&- galleryCache.selectedId &&- merged.some((c) => c.id === galleryCache.selectedId)- ) {- setFallbackClip(null);- }- if (- galleryCache.selectedId &&- !merged.some((c) => c.id === galleryCache.selectedId)- ) {- galleryCache.selectedId = merged[0]?.id ?? null;- setSelectedId(galleryCache.selectedId);- }- if (- !galleryCache.selectedId &&- !fallbackClipRef.current &&- merged.length > 0- ) {- galleryCache.selectedId = merged[0].id;- setSelectedId(galleryCache.selectedId);- }- const selected = merged.find(- (clip) => clip.id === galleryCache.selectedId,- );- if (selected) void ensureClipSrc(selected);- return merged;- } catch {- // Same recoverable-poll stance as status.- return galleryCache.clips;- }- },- [ensureClipSrc],- );+ const {+ transcript,+ setTranscript,+ transcribedName,+ setTranscribedName,+ transcriptModel,+ setTranscriptModel,+ transcriptRecord,+ setTranscriptRecord,+ transcriptExported,+ setTranscriptExported,+ transcriptVersion,+ transcriptionStartedAt,+ setTranscriptionStartedAt,+ transcriptionFinishedAt,+ transcriptionStopping,+ setTranscriptionStopping,+ transcriptionProgress,+ transcriptError,+ setTranscriptError,+ isRecording,+ micRequestPending,+ recordingSupported,+ transcriptionAbort,+ stopAndDiscardRecording,+ clearTranscript,+ confirmTranscriptReplacement,+ handleRecordToggle,+ handleTranscribeFile,+ handleCopyTranscript,+ handleDownloadTranscript,+ } = useTranscription({+ active,+ activeRef,+ busyRef,+ setBusy,+ lastSttRepo,+ selectedSttRepoRef,+ setSelectedSttRepo,+ sttLoadedModel,+ sttLoadedEngine,+ ensureSttLoaded,+ setLastSttRepo,+ refreshSttStatus,+ });- const loadMore = useCallback(async () => {- // Repeated scroll events near the bottom would otherwise each fire with the same offset and- // append the same page, duplicating clips and React keys.- if (loadingMoreRef.current) return;- loadingMoreRef.current = true;- const refreshGeneration = galleryRefreshGeneration.current;- const cursor = galleryCache.nextCursor;- try {- const page = await listAudioGallery(0, PAGE_SIZE, cursor);- if (- refreshGeneration !== galleryRefreshGeneration.current ||- cursor !== galleryCache.nextCursor- )- return;- galleryCache.nextCursor = audioGalleryCursor(page);- const known = new Set(galleryCache.clips.map((clip) => clip.id));- galleryCache.clips = [- ...galleryCache.clips,- ...page.audio.filter((clip) => !known.has(clip.id)),- ];- galleryCache.hasMore = page.has_more;- setClips(galleryCache.clips);- setHasMore(page.has_more);- } catch {- // Retry on the next scroll.- } finally {- loadingMoreRef.current = false;- }- }, []);+ const {+ fallbackClip,+ setFallbackClip,+ loadingMoreRef,+ clips,+ hasMore,+ selectedId,+ setSelectedId,+ srcById,+ peaksById,+ ensureClipSrc,+ refreshGallery,+ loadMore,+ selectClip,+ handleDeleteClip,+ handleArchiveClip,+ handleTogglePin,+ historyReorder,+ handleClearGallery,+ handleDownloadClip,+ handleDownloadFallbackClip,+ handleDownloadClipById,+ handleCopyPrompt,+ } = useAudioGallery({ active });// Resync on activation: another tab may have loaded/unloaded models meanwhile.useEffect(() => {@@ -942,1875 +309,337 @@ export function AudioPage({});}, [active, refreshStatus, refreshSttStatus]);- useEffect(() => {- if (!active) return;- const refreshWhenVisible = () => {- if (document.hidden) return;- void refreshGallery(undefined, galleryCache.clips.length);- };- window.addEventListener("focus", refreshWhenVisible);- document.addEventListener("visibilitychange", refreshWhenVisible);- return () => {- window.removeEventListener("focus", refreshWhenVisible);- document.removeEventListener("visibilitychange", refreshWhenVisible);- };- }, [active, refreshGallery]);-- useEffect(() => {- const clip = clips.find((c) => c.id === selectedId);- if (clip) void ensureClipSrc(clip);- }, [clips, selectedId, ensureClipSrc]);-- /** `keepFallback` is for the one case where the id is not in `clips` yet: the server persisted the- * clip but this refresh missed it, so the response audio has to stay mounted or the player- * falls through to the empty state. */- const selectClip = useCallback(- (id: string, keepFallback = false) => {- galleryCache.selectedId = id;- setSelectedId(id);- if (!keepFallback) setFallbackClip(null);- const clip = galleryCache.clips.find((candidate) => candidate.id === id);- if (clip) void ensureClipSrc(clip);- },- [ensureClipSrc],- );--- const loadTtsModel = useCallback(- async (- repoId: string,- ggufFilename?: string | null,- // Where the weights actually are: a row cached in a NON-ACTIVE HF cache is loadable only by its snapshot path,- // which the picker supplies as meta.loadId, and sending the display repo id instead failed offline or- // re-downloaded into the active cache. Chat threads the same field (chat-page.tsx).- loadId?: string | null,- audioType?: string | null,- remoteCodeApproval?: RemoteCodeApproval,- // The catalog's answer: the ids alone miss a GGUF repo that does not spell it.- isGguf?: boolean | null,- ) => {- // A routed pick arriving while a previous load is still tearing down would otherwise be dropped,- // and the route effect has already cleared ?model=, so replay it from the finally below.- if (ttsLoadInFlight.current || busyRef.current === "generating") {- pendingRoutedTtsPick.current = {- repoId,- ggufFilename,- loadId,- audioType,- remoteCodeApproval,- isGguf,- };- return;- }- // A load stops every chat on the shared llama-server, so ask the way Chat does instead of dead-ending on the- // backend's 409. Claimed before the await: a routed pick arriving while the dialog is open must queue.- ttsLoadInFlight.current = true;- // Chat's gate, held across the question and the load. Without it a queue can materialize while- // the dialog is open, outside the snapshot the answer was given for.- const lifecycleLease = useChatRuntimeStore.getState().beginModelLoading();- if (lifecycleLease === null) {- ttsLoadInFlight.current = false;- pendingRoutedTtsPick.current = null;- toast.info("Wait for the current model to finish loading.");- return;- }- const releaseLifecycle = () =>- useChatRuntimeStore.getState().endModelLoading(lifecycleLease);- const stopDecision = await confirmStopRunningChatsIfNeeded();- if (!stopDecision.proceed) {- releaseLifecycle();- ttsLoadInFlight.current = false;- // Declining refuses the swap, so a queued pick must not reopen the dialog.- pendingRoutedTtsPick.current = null;- return;- }- // The page can go away while the dialog is open, and pendingTtsLoad is still null then, so the- // deactivation effect has nothing to abort. Queue it for the activation replay.- if (!activeRef.current) {- releaseLifecycle();- ttsLoadInFlight.current = false;- pendingRoutedTtsPick.current = {- repoId,- ggufFilename,- loadId,- audioType,- remoteCodeApproval,- isGguf,- };- return;- }- const generation = ++ttsLoadGeneration.current;- const controller = new AbortController();- const loadRequestId = crypto.randomUUID();- const pending = {- generation,- repoId,- // What the request actually sent. Cancelling under the display id works only when the load target is a- // standard HF cache snapshot; a pinned directory elsewhere does not match and _cancel_scoped_load_attempt then- // refuses.- loadTarget: loadId || repoId,- loadRequestId,- controller,- requestStarted: false,- };- pendingTtsLoad.current = pending;- const isCurrent = () =>- generation === ttsLoadGeneration.current && activeRef.current;- ttsLoadInFlight.current = true;- busyRef.current = "loading";- setBusy("loading");- const toastId = toast.loading(`Loading ${audioModelLabel(repoId)}…`);- try {- const hfToken = hfApiToken(getHfToken()) ?? null;- let trustRemoteCode = remoteCodeApproval?.trustRemoteCode ?? false;- let approvedRemoteCodeFingerprint =- remoteCodeApproval?.approvedRemoteCodeFingerprint ?? null;- if (- audioModelRequiresRemoteCode(repoId, audioType) &&- !remoteCodeApproval- ) {- const approved = await confirmRemoteCodeIfNeeded({- modelName: loadId || repoId,- hfToken,- requiresTrustRemoteCode: true,- onApprove: (fingerprint) => {- trustRemoteCode = true;- approvedRemoteCodeFingerprint = fingerprint;- },- });- if (!approved)- throw new Error(- "Custom code approval is required to load this model.",- );- if (controller.signal.aborted || !isCurrent()) return;- }- const wantsCpu = audioDevice === "cpu";- const isGgufLoad = isGgufTtsTarget({ repoId, ggufFilename, loadId, isGguf });- const res = await loadModel(- {- model_path: loadId || repoId,- load_request_id: loadRequestId,- force_cancel_active: stopDecision.forceCancelActive,- hf_token: hfToken,- max_seq_length: TTS_MAX_TOKENS + TTS_PROMPT_CONTEXT_RESERVE,- load_in_4bit: false,- is_lora: false,- gguf_variant: ggufFilename ?? null,- trust_remote_code: trustRemoteCode,- approved_remote_code_fingerprint: approvedRemoteCodeFingerprint,- audio_device: wantsCpu ? "cpu" : "auto",- // GGUF ignores audio_device: llama.cpp offloads unless told not to. An absent speculative_type resolves to- // "auto", which may attach a GPU drafter, and the backend then evicts image/video for a CPU load.- ...(wantsCpu && isGgufLoad- ? // biome-ignore lint/style/useNamingConvention: API schema- {- gpu_memory_mode: "manual" as const,- gpu_layers: 0,- speculative_type: "off" as const,- }- : {}),- },- {- signal: controller.signal,- runtime: "tts",- onRequestStart: () => {- pending.requestStarted = true;- // Queued prompts would otherwise start on the model this load replaces. Only once /load is actually going- // out: loadModel returns without sending when a stored token is invalid, and cancelling earlier threw away- // accepted sends for a swap that never happened.- cancelPreStreamRunReservations(stopDecision.preStreamRunTokens);- requestLocalPromptQueueStop(stopDecision.promptQueueThreadIds);- },- },- );- if (!isCurrent()) return;- if (res.is_audio && isTtsAudioType(res.audio_type)) {- const offloadNotice = offloadWarning(offloadCountsFrom(res));- const showToast = offloadNotice ? toast.warning : toast.success;- showToast(- `Model loaded (${loadedAudioKind(res.audio_type)})${offloadNotice?.titleSuffix ?? ""}`,- {- id: toastId,- description: offloadNotice?.description,- duration: offloadNotice ? 8000 : undefined,- },- );- // Only the native runtime and GGUF can be held in RAM.- if (- wantsCpu &&- !isGgufLoad &&- !usesNativeAudioRuntime(repoId, res.audio_type)- ) {- toast.info(- "This model does not support CPU RAM yet, so it loaded on the GPU.",- { duration: 6000 },- );- }- } else {- toast.error(`${repoId} loaded but is not a supported TTS model.`, {- id: toastId,- });- }- } catch (error) {- if (isCurrent()) {- toast.error(- error instanceof Error ? error.message : "Model load failed.",- { id: toastId },- );- } else {- toast.dismiss(toastId);- }- } finally {- if (pendingTtsLoad.current?.generation === generation)- pendingTtsLoad.current = null;- if (activeRef.current) await refreshStatus();- ttsLoadInFlight.current = false;- // Before the replay below, which needs the gate for its own attempt.- releaseLifecycle();- busyRef.current = null;- setBusy(null);- // Only while Audio is visible: replaying unconditionally started a load with activeRef already false, which- // the deactivation effect never saw to cancel, so a hidden page could replace the model Chat had loaded.- if (activeRef.current) replayQueuedTtsPick();- }- },- [refreshStatus, audioDevice],- );-- // Stage uncached Hub GGUFs through the shared manager so Audio gets the same progress,- // cancellation, resume and disk preflight as Chat/Images/Video.- const loadTtsModelRef = useRef(loadTtsModel);- loadTtsModelRef.current = loadTtsModel;- /** Start a pick that lost the race with a load still settling. Visible pages only: a load started- * while hidden outlives the deactivation effect that would cancel it. */- const replayQueuedTtsPick = useCallback(() => {- const queued = pendingRoutedTtsPick.current;- if (!queued) return;- pendingRoutedTtsPick.current = null;- void loadTtsModelRef.current(- queued.repoId,- queued.ggufFilename,- queued.loadId,- queued.audioType,- queued.remoteCodeApproval,- queued.isGguf,- );- }, []);- const invalidatePendingStagedTts = useCallback(() => {- stagedTtsGeneration.current += 1;- pendingStagedTtsLoad.current = null;- stagedTtsLoadDeferred.current = false;- }, []);- const invalidatePendingTtsSelection = useCallback(() => {- ttsPickGeneration.current += 1;- pendingRoutedTtsPick.current = null;- invalidatePendingStagedTts();- }, [invalidatePendingStagedTts]);- const transitionMode = useCallback(- (nextMode: CreateMode) => {- if (nextMode === mode) {- if (nextMode === "transcribe") invalidatePendingTtsSelection();- return true;- }- if (- !canTransitionAudioMode(busyRef.current, generationPhaseRef.current)- ) {- toast.info(- "Wait for the active audio task to finish before switching modes.",- );- return false;- }-- if (nextMode === "transcribe") invalidatePendingTtsSelection();- if (busyRef.current === "generating") handleStopGeneration();- stopAndDiscardRecording();- setMode(nextMode);- // Held through Generate, the sidecar keeps a dictation model in VRAM beside the speech one.- if (mode === "transcribe") {- // Resolves to whether the sidecar is actually gone: swallowing the rejection made a failed unload- // look like a release, so the speech load went ahead with the dictation model and OOMed.- const release = releaseTranscribeSelection().then(- () => true,- (error) => {- toast.error(- error instanceof Error- ? error.message- : "Failed to release the transcription model.",- );- return false;- },- );- // Recorded so a TTS load can wait for the teardown: allocating while the sidecar still holds its- // model is what OOMs a device that fits either one alone.- pendingTranscribeRelease.current = release;- void release.then((released) => {- if (pendingTranscribeRelease.current !== release) return;- pendingTranscribeRelease.current = null;- // The sidecar is still holding its model, so the page must not sit in Speak claiming otherwise:- // back to Transcribe, where Eject can retry. Only if nothing has moved on since.- if (!released && modeRef.current === "speak") setMode("transcribe");- });- }- return true;- },- [- invalidatePendingTtsSelection,- handleStopGeneration,- mode,- releaseTranscribeSelection,- stopAndDiscardRecording,- ],- );- const { stage: stageTtsDownload } = useStagedDownload({- scopeId: "audio",- onReady: () => {- const pending = pendingStagedTtsLoad.current;- if (- !pending ||- !stagedTtsLoadIsOwned(- pending.generation,- stagedTtsGeneration.current,- modeRef.current,- )- ) {- pendingStagedTtsLoad.current = null;- stagedTtsLoadDeferred.current = false;- return;- }- // Audio stays mounted across tabs, so loading from a hidden page would evict the visible page's- // model; likewise, wait for an active generation to end.- if (!active || busyRef.current !== null) {- stagedTtsLoadDeferred.current = true;- return;- }- pendingStagedTtsLoad.current = null;- void loadTtsModelRef.current(- pending.repoId,- pending.ggufFilename,- pending.loadId,- pending.audioType,- pending.remoteCodeApproval,- pending.isGguf,- );- },- });-- useEffect(() => {- if (!active || busy !== null || !stagedTtsLoadDeferred.current) return;- stagedTtsLoadDeferred.current = false;- const pending = pendingStagedTtsLoad.current;- if (- !pending ||- !stagedTtsLoadIsOwned(- pending.generation,- stagedTtsGeneration.current,- modeRef.current,- )- ) {- pendingStagedTtsLoad.current = null;- return;- }- pendingStagedTtsLoad.current = null;- void loadTtsModelRef.current(- pending.repoId,- pending.ggufFilename,- pending.loadId,- pending.audioType,- pending.remoteCodeApproval,- pending.isGguf,- );- }, [active, busy]);-- const loadOrStageTtsModel = useCallback(- async (- repoId: string,- ggufFilename: string | null,- meta: ModelSelectorChangeMeta,- ) => {- const generation = ++stagedTtsGeneration.current;- pendingStagedTtsLoad.current = null;- stagedTtsLoadDeferred.current = false;- stageTtsDownload([]);-- let remoteCodeApproval: RemoteCodeApproval | undefined;- const hfToken = hfApiToken(getHfToken()) ?? null;- if (- meta.source === "hub" &&- !ggufFilename &&- audioModelRequiresRemoteCode(repoId, meta.audioType)- ) {- try {- const approved = await confirmRemoteCodeIfNeeded({- modelName: meta.loadId || repoId,- hfToken,- requiresTrustRemoteCode: true,- onApprove: (fingerprint) => {- remoteCodeApproval = {- trustRemoteCode: true,- approvedRemoteCodeFingerprint: fingerprint,- };- },- });- if (generation !== stagedTtsGeneration.current) return;- if (!approved) {- toast.error("Custom code approval is required to load this model.");- return;- }- } catch (error) {- if (generation !== stagedTtsGeneration.current) return;- toast.error(- error instanceof Error- ? error.message- : `Could not verify the code for ${repoId}.`,- );- return;- }- }-- // Hub TTS picks use the same managed path as Chat. Native models can also depend on a second codec- // repository, so the selected repo's downloaded badge is not enough: the cache-aware backend plan owns every- // missing file.- if (meta.source === "hub" && !ggufFilename) {- let plan;- try {- plan = await getAudioDownloadPlan(- meta.loadId || repoId,- hfToken ?? undefined,- );- } catch (error) {- if (generation !== stagedTtsGeneration.current) return;- if (meta.isDownloaded === true) {- void loadTtsModelRef.current(- repoId,- ggufFilename,- meta.loadId,- meta.audioType,- remoteCodeApproval,- meta.isGguf,- );- return;- }- toast.error(- error instanceof Error- ? error.message- : `Could not prepare the download for ${repoId}.`,- );- return;- }- if (generation !== stagedTtsGeneration.current) return;- const plannedEntries = plan.entries;- if (plannedEntries.length > 0) {- pendingStagedTtsLoad.current = {- repoId,- ggufFilename,- loadId: meta.loadId,- audioType: meta.audioType,- remoteCodeApproval,- isGguf: meta.isGguf,- generation,- };- stageTtsDownload(- plannedEntries.map((entry) => ({- repoId: entry.repo_id,- files: entry.files,- bytes: entry.bytes,- ggufFilename: entry.gguf_filename,- checkpoint: entry.checkpoint,- })),- );- return;- }- }-- if (- meta.source === "hub" &&- meta.isDownloaded === false &&- ggufFilename- ) {- pendingStagedTtsLoad.current = {- repoId,- ggufFilename,- loadId: meta.loadId,- audioType: meta.audioType,- remoteCodeApproval,- isGguf: meta.isGguf,- generation,- };- // A named quant is fetched as the standard variant download, as Chat does, so the backend's plan- // brings the files it needs beside the weights and the Downloads row reads "<repo> · <quant>".- stageTtsDownload([- meta.ggufVariant- ? {- repoId,- files: [],- bytes: meta.expectedBytes ?? 0,- ggufFilename,- ggufVariant: meta.ggufVariant,- }- : {- repoId,- files: [ggufFilename],- bytes: meta.expectedBytes ?? 0,- ggufFilename,- },- ]);- return;- }-- // A cached/local/direct pick supersedes any staged auto-load: the manager may keep downloading- // globally, but its old completion cannot load here.- void loadTtsModelRef.current(- repoId,- ggufFilename,- meta.loadId,- meta.audioType,- remoteCodeApproval,- meta.isGguf,- );- },- [stageTtsDownload],- );-- const ensureSttLoaded = useCallback(- async (- repoId: string,- sidecarKey: string,- engine: AudioSttEngine,- ) => {- const generation = ++sttLoadGeneration.current;- const controller = new AbortController();- sttLoadingGeneration.current = generation;- sttLoadAbort.current = controller;- const isCurrent = () =>- generation === sttLoadGeneration.current &&- activeRef.current &&- selectedSttRepoRef.current === repoId;-- setBusy("loading");- // Ownership is claimed only once the requested model is actually resident: claiming it up front meant a- // cancelled download left the flag set while the backend kept the previous model, so leaving Transcribe- // unloaded another surface's model.- const toastId = toast.loading(`Preparing ${audioModelLabel(sidecarKey)}…`);- // The quant picked for this repo (Moonshine tiny or small), sent to the audio runtime's sidecar.- const ggufVariant =- engine === "audiocpp"- ? (sttGgufVariants.current.get(repoId.toLowerCase()) ?? null)- : null;- try {- try {- await loadSttModel(- sidecarKey,- engine,- controller.signal,- undefined,- ggufVariant,- );- sttLoadedByThisPage.current = sidecarKey;- } catch (error) {- if (!(error instanceof SttModelNotDownloadedError)) throw error;- if (!isCurrent()) return;- await startSttDownload(- sidecarKey,- hfApiToken(getHfToken()),- engine,- ggufVariant,- );- // STT owns its specialized transfer, but the existing mirror gives it the same global Downloads- // row, progress and Cancel as every other model download. Do not reset an adopted row.- if (!isTrackingSttDownload(sidecarKey, engine)) {- trackSttDownload(sidecarKey, {- // Audio owns the final load through its active/selection generation guards, so the- // Voice-settings mirror must not warm a stale sidecar behind those guards.- warmSelectedVoiceModelOnComplete: false,- engine,- repoId,- });- }- // The shared Downloads panel now owns transfer progress; keep this toast for the short model-load- // phase after the bytes land.- toast.dismiss(toastId);- // A completed download may outlive this page or selection, so re-check ownership around every- // await or an old pick could replace a newer sidecar.- for (;;) {- await new Promise((resolve) => setTimeout(resolve, 1000));- if (!isCurrent()) return;- const stt = await fetchSttStatus(- undefined,- engine === "transformers" ? sidecarKey : undefined,- );- if (!isCurrent()) return;- const block = sttEngineStatusFor(stt, sidecarKey, engine);- const download = block?.download;- // Cancel comes from the shared Downloads row. It is terminal for this preparation attempt, not- // permission to load a partial checkpoint.- if (download?.cancelled) return;- if (download?.error) throw new Error(download.error);- if (!download?.downloading) break;- }- if (!isCurrent()) return;- toast.loading(`Loading ${audioModelLabel(sidecarKey)}…`, {- id: toastId,- });- await loadSttModel(- sidecarKey,- engine,- controller.signal,- undefined,- ggufVariant,- );- sttLoadedByThisPage.current = sidecarKey;- }- if (isCurrent()) {- setLastSttRepo(repoId);- toast.success("Transcription model ready", { id: toastId });- return true;- }- return false;- } catch (error) {- if (isCurrent()) {- toast.error(- error instanceof Error- ? error.message- : "Transcription model failed.",- { id: toastId },- );- }- } finally {- if (!isCurrent()) toast.dismiss(toastId);- if (sttLoadingGeneration.current === generation) {- sttLoadingGeneration.current = null;- await refreshSttStatus();- if (- generation === sttLoadGeneration.current &&- sttLoadingGeneration.current === null- ) {- setBusy(null);- }- } else {- toast.dismiss(toastId);- }- if (sttLoadAbort.current === controller) sttLoadAbort.current = null;- }- },- [refreshSttStatus, setLastSttRepo],- );-- // A hidden page may let the shared download continue, but it must not load the sidecar. Returning- // to the same still-selected repo resumes preparation once; a different selection clears it.- useEffect(() => {- if (!active) {- ttsPickGeneration.current += 1;- const pending = pendingTtsLoad.current;- if (pending) {- ttsLoadGeneration.current += 1;- pendingTtsLoad.current = null;- pending.controller.abort();- if (pending.requestStarted)- void unloadModel({- model_path: pending.loadTarget,- cancel_load_request_id: pending.loadRequestId,- }).catch(() => {});- }- if (ttsInspectionGeneration.current !== null) {- ttsInspectionGeneration.current = null;- busyRef.current = null;- setBusy(null);- }-- if (sttLoadingGeneration.current !== null) {- const repoId = selectedSttRepoRef.current;- deferredSttLoad.current = repoId- ? {- repoId,- sidecarKey: sttSidecarKeyFor(repoId),- engine: sttEngineForRepoId(repoId),- }- : null;- sttLoadGeneration.current += 1;- sttLoadingGeneration.current = null;- sttLoadAbort.current?.abort();- sttLoadAbort.current = null;- busyRef.current = null;- setBusy(null);- }- return;- }-- // A pick queued behind a settling load, held back because the page went away before the load- // finished. Now that Audio is visible again the attempt is cancellable.- replayQueuedTtsPick();-- const deferred = deferredSttLoad.current;- deferredSttLoad.current = null;- if (deferred && selectedSttRepoRef.current === deferred.repoId) {- void (async () => {- try {- const status = await fetchSttStatus(- undefined,- deferred.engine === "transformers"- ? deferred.sidecarKey- : undefined,- );- const download = sttEngineStatusFor(- status,- deferred.sidecarKey,- deferred.engine,- )?.download;- // `model` is null once the download thread has stopped, so a cancellation made while this page- // was hidden matched nothing here and the deferred load restarted the whole download.- if (- download?.cancelled &&- (download.model ?? download.cancelled_model) === deferred.sidecarKey- )- return;- } catch {- // Status is advisory here; the normal preparation path reports errors.- }- if (activeRef.current && selectedSttRepoRef.current === deferred.repoId)- void ensureSttLoaded(- deferred.repoId,- deferred.sidecarKey,- deferred.engine,- );- })();- }- }, [active, ensureSttLoaded]);-- const isMac = usePlatformStore((s) => s.deviceType) === "mac";- /** An in-flight Transcribe teardown a following TTS load has to wait behind. */- const pendingTranscribeRelease = useRef<Promise<boolean> | null>(null);-- const handleModelSelect = useCallback(- async (id: string, meta: ModelSelectorChangeMeta) => {- if (busyRef.current !== null) return;- // Catalog first; an uncurated Hub pick falls back to its pipeline tag, or every community ASR- // repo would load into the TTS slot.- const task = resolveAudioPickTask(audioTaskFor(id), meta.pipelineTag);- // A recommended GGUF speech or music row the installed audio runtime cannot run: say why- // instead of loading into a 501.- const runtimeProblem =- task === "stt" ? null : audioCppRuntimeProblem(id, audioCppRuntime.current);- if (runtimeProblem) {- toast.error(runtimeProblem, { duration: 7000 });- return;- }- const cudaMusicPick =- task !== "stt" && musicGenerationRequiresCuda(id, meta.audioType);- const selectionGeneration = ++ttsPickGeneration.current;- if (cudaMusicPick) {- const system = await fetchSystemInfo();- if (selectionGeneration !== ttsPickGeneration.current) return;- if (system?.device_backend !== "cuda") {- toast.error(- `${id} requires a verified NVIDIA CUDA GPU for local generation.`,- { duration: 7000 },- );- return;- }- }- // Selecting a different artifact while recording is a lifecycle change even in Transcribe mode;- // never let the old capture submit against a sidecar this pick is replacing.- stopAndDiscardRecording();- deferredSttLoad.current = null;- if (task === "stt") {- // An STT pick owns Transcribe: it runs on the sidecar, not the main slot.- if (!transitionMode("transcribe")) return;- const sidecarKey = sttSidecarKeyFor(id);- const engine = sttEngineForRepoId(id, meta.isGguf);- // Remembered per repo, so a deferred or on-demand load of this pick asks for the same quant.- if (meta.ggufVariant) {- sttGgufVariants.current.set(id.toLowerCase(), meta.ggufVariant);- } else {- sttGgufVariants.current.delete(id.toLowerCase());- }- deferredSttLoad.current = null;- selectedSttRepoRef.current = id;- setSelectedSttRepo(id);- void ensureSttLoaded(id, sidecarKey, engine);- return;- }- // TTS (or an uncurated repo the user pasted, which /load will validate).- if (!transitionMode("speak")) return;- // Serialize against a Transcribe release started by that transition.- const releaseInFlight = pendingTranscribeRelease.current;- // A release that failed leaves the sidecar resident, so do not stack a speech model on top of it: back to- // Transcribe, where Eject can retry. Claimed before the await below, not after: the button only disables on- // `busy`, so a slow release let several clicks through, each resuming into its own generateAudio while- // generateAbort tracked only the last.- if (releaseInFlight && !(await releaseInFlight)) {- setMode("transcribe");- return;- }- if (ttsPickGeneration.current !== selectionGeneration) return;- const exactGguf = exactGgufLoadSelector(meta);- const isGguf = isGgufTtsTarget({- repoId: id,- ggufFilename: exactGguf,- isGguf: meta.isGguf,- });- const ggufSibling = isGguf ? null : ggufSiblingFor(id);- const nativeRuntime =- usesNativeAudioRuntime(id, meta.audioType) && !cudaMusicPick;- const macAction = macTtsPickAction({- isMac,- isGguf,- ggufSibling,- nativeRuntime,- });- if (macAction === "reject") {- toast.error(- cudaMusicPick- ? `${id} currently requires an NVIDIA CUDA GPU and cannot run locally on this Mac.`- : `${id} has no runnable GGUF TTS build. MLX cannot generate text-to-speech from its safetensors checkpoint on this Mac.`,- { duration: 7000 },- );- return;- }- if (macAction === "use-gguf-sibling" && ggufSibling) {- toast.info(- `Loading the GGUF build of ${id}. MLX has no text-to-speech decoder, so the safetensors build cannot generate on this Mac.`,- { duration: 7000 },- );- // Resolving the sibling is part of the model load lifecycle. Reserve the slot so Generate cannot- // run the old resident model and then be evicted by this inspection's completion.- ttsInspectionGeneration.current = selectionGeneration;- busyRef.current = "loading";- setBusy("loading");- try {- const listing = await listGgufVariants(- ggufSibling,- hfApiToken(getHfToken()),- );- if (selectionGeneration !== ttsPickGeneration.current) return;- const variant = selectAutoGgufVariant(- listing.variants,- listing.default_variant,- );- if (!variant) {- toast.error(- `${ggufSibling} does not publish a runnable GGUF file.`,- );- return;- }- if (ttsInspectionGeneration.current === selectionGeneration) {- ttsInspectionGeneration.current = null;- busyRef.current = null;- setBusy(null);- }- await loadOrStageTtsModel(ggufSibling, variant.filename, {- ...meta,- source: "hub",- isGguf: true,- ggufFilename: variant.filename,- ggufVariant: variant.quant,- isDownloaded: variant.downloaded === true && !variant.partial,- expectedBytes: expectedGgufDownloadBytes(variant),- });- } catch (error) {- if (selectionGeneration !== ttsPickGeneration.current) return;- toast.error(- error instanceof Error- ? error.message- : `Could not inspect ${ggufSibling}.`,- );- } finally {- if (ttsInspectionGeneration.current === selectionGeneration) {- ttsInspectionGeneration.current = null;- busyRef.current = null;- setBusy(null);- }- }- return;- }- await loadOrStageTtsModel(id, exactGguf, meta);- },- [- ensureSttLoaded,- isMac,- loadOrStageTtsModel,- stopAndDiscardRecording,- transitionMode,- ],- );-- // A pick handed over from the chat model selector arrives as ?model= (+ ?quant= and task).- const navigateSelf = useNavigate();- const routeSearch = useSearch({ strict: false }) as {- model?: string;- quant?: string;- ggufQuant?: string;- task?: string;- audioType?: string;- loadId?: string;- item?: string;- };- const handledRouteModel = useRef<string | null>(null);- useEffect(() => {- if (!active) return;- const wanted = routeSearch.model;- if (!wanted) {- handledRouteModel.current = null;- // A task with no model is a mode intent from Settings; without it the page keeps whatever mode it was left in.- const task = routeSearch.task;- if (!task) return;- const intended =- task === "automatic-speech-recognition" ? "transcribe" : "speak";- // Left in the URL when the switch is refused, so it retries once busy releases.- if (intended !== mode && !transitionMode(intended)) return;- void navigateSelf({ to: "/audio", search: {}, replace: true });- return;- }- const key = `${wanted}|${routeSearch.quant ?? ""}|${routeSearch.ggufQuant ?? ""}|${routeSearch.task ?? ""}|${routeSearch.audioType ?? ""}|${routeSearch.loadId ?? ""}`;- if (handledRouteModel.current === key) return;- // The persistent Audio page may still be finishing hidden work, so keep the handoff in the URL- // and retry it when that work releases the lifecycle.- if (busyRef.current !== null) return;- handledRouteModel.current = key;- handleModelSelect(wanted, {- source: "hub",- isLora: false,- ggufFilename: routeSearch.quant ?? undefined,- ggufVariant: routeSearch.ggufQuant ?? undefined,- loadId: routeSearch.loadId ?? undefined,- audioType: routeSearch.audioType ?? undefined,- // Chat-to-Audio routing cannot preserve the inventory flag, so stage the exact forwarded GGUF.- // An already-cached job completes immediately.- isDownloaded: routeSearch.loadId- ? true- : routeSearch.quant- ? false- : undefined,- pipelineTag: routeSearch.task ?? null,- });- void navigateSelf({ to: "/audio", search: {}, replace: true });- }, [- active,- busy,- mode,- routeSearch.model,- routeSearch.quant,- routeSearch.ggufQuant,- routeSearch.task,- routeSearch.audioType,- routeSearch.loadId,- handleModelSelect,- navigateSelf,+ const {+ replayQueuedTtsPick,transitionMode,- ]);-- // A Library "View in Audio" link arrives as ?task=text-to-speech&item=: the task switches to Speak- // (and clears its part of the query), this selects the clip, paging back until it loads. A- // counter, not effect cleanup, retires a lookup: clearing the query must not cancel its own.- const routedItem = active ? routeSearch.item : undefined;- const routedLookup = useRef(0);- useEffect(() => {- if (!active) routedLookup.current += 1;- }, [active]);- useEffect(() => {- if (!routedItem) return;- const lookup = ++routedLookup.current;- void navigateSelf({- to: "/audio",- search: (prev) => ({ ...prev, item: undefined }),- replace: true,- });- void loadGalleryUntil({- has: () => galleryCache.clips.some((clip) => clip.id === routedItem),- count: () => galleryCache.clips.length,- hasMore: () => galleryCache.hasMore,- refresh: () => refreshGallery(undefined, galleryCache.clips.length),- loadMore,- busy: () => loadingMoreRef.current,- cancelled: () => lookup !== routedLookup.current,- }).then((found) => {- if (lookup !== routedLookup.current) return;- if (found) selectClip(routedItem);- else {- toast(translate("library.toast.clipNotFound"), {- description: translate("library.toast.notFoundDescription"),- });- }- });- }, [routedItem, navigateSelf, refreshGallery, loadMore, selectClip]);--- const ttsLoaded = Boolean(- status?.active_model &&- isTtsAudioType(status.audio_type, status.is_gguf === true),- );- const musicGeneration = isMusicGenerationModel(- status?.active_model,- status?.audio_type,- );- const cudaMusicGeneration = musicGenerationRequiresCuda(- status?.active_model,- status?.audio_type,- );- // Most GGUF music falls back to the lyrics as its prompt; MiniMax Music 3 and YuE2 need a- // description beside them.- const musicNeedsDescription =- cudaMusicGeneration ||- musicModelNeedsDescription(status?.audio_type, status?.audio_family);- const lyricsOptional = musicLyricsOptional(- status?.audio_type,- status?.audio_family,- );- const musicRange = musicDurationRange(cudaMusicGeneration);- // A length picked for the MiniMax pipeline can exceed what the GGUF runtime generates.- const musicSeconds = Math.min(- Math.max(minimaxMaxSeconds, musicRange.min),- musicRange.max,- );- const samplingControls = audioSamplingControlsApply(status?.audio_type);- const audioOptionSpecs = useMemo(- () => parseAudioOptions(status?.audio_options),- [status?.audio_options],- );- const audioOptionsModel = status?.active_model ?? null;- const [audioOptionValues, setAudioOptionValues] = useState<AudioOptionValues>(- () => readAudioOptionValues(audioOptionsModel),- );- const [audioOptionValuesModel, setAudioOptionValuesModel] = useState(- audioOptionsModel,- );- // Each model keeps its own values, read back when it becomes the loaded one.- if (audioOptionValuesModel !== audioOptionsModel) {- setAudioOptionValuesModel(audioOptionsModel);- setAudioOptionValues(readAudioOptionValues(audioOptionsModel));- }- const handleAudioOptionChange = useCallback(- (name: string, value: AudioOptionValue | undefined) => {- setAudioOptionValues((current) => {- const next = { ...current };- if (value === undefined) delete next[name];- else next[name] = value;- saveAudioOptionValues(audioOptionsModel, next);- return next;- });- },- [audioOptionsModel],- );- const handleAudioOptionsReset = useCallback(() => {- setAudioOptionValues({});- saveAudioOptionValues(audioOptionsModel, {});- }, [audioOptionsModel]);- const mossLocalGeneration = status?.audio_type === "moss_tts_local";- const instructionsKind = musicGeneration- ? "music"- : nativeAudioInstructionsKind(status?.audio_type);- const handleEject = useCallback(() => {- if (busy !== null || isRecording) {- toast.info("Stop the active audio task before ejecting its model.");- return;- }-- // Eject also owns unresolved permission requests. Invalidating here makes their eventual streams- // self-discard instead of recording for an old STT pick.- stopAndDiscardRecording();-- if (mode === "transcribe") {- if (!selectedSttRepo) return;- // A selection can exist before its sidecar is resident, so an unowned pick is only forgotten.- if (!sttReady) {- sttStatusRefreshGeneration.current += 1;- void releaseTranscribeSelection();- return;- }-- setBusy("unloading");- const toastId = toast.loading("Unloading transcription model…");- void (async () => {- try {- await releaseTranscribeSelection();- toast.success("Transcription model unloaded", {- id: toastId,- duration: 1200,- });- } catch (error) {- toast.error(- error instanceof Error- ? error.message- : "Failed to unload transcription model.",- { id: toastId },- );- } finally {- setBusy(null);- }- })();- return;- }-- const activeModel = status?.active_model;- if (!activeModel) return;-- // Chat's gate, taken before the question so a queue cannot materialize while the dialog is open- // and then be stopped by the blanket queue stop.- const lifecycleLease = useChatRuntimeStore.getState().beginModelLoading();- if (lifecycleLease === null) {- toast.info("Wait for the current model to finish loading.");- return;- }-- // Busy before the dialog, so a second eject cannot start behind the first.- setBusy("unloading");- void (async () => {- try {- // Ejecting stops every chat on the shared llama-server, and unforced the backend refused with a 409 the- // user could only read. Nothing is torn down until the answer is in, so declining leaves the page as it was.- const stopDecision = await confirmStopRunningChatsIfNeeded(- "Unloading the model",- "unload",- );- if (!stopDecision.proceed) {- setBusy(null);- return;- }-- // An old managed completion must not immediately replace the model the user just ejected. The- // global download may continue for later use.- invalidatePendingStagedTts();- stageTtsDownload([]);-- const toastId = toast.loading("Unloading model…");- try {- cancelPreStreamRunReservations(stopDecision.preStreamRunTokens);- requestLocalPromptQueueStop(stopDecision.promptQueueThreadIds);- await unloadModel({- model_path: activeModel,- force_cancel_active: stopDecision.forceCancelActive,- });- requestLocalPromptQueueStop();- await refreshStatus();- toast.success("Model unloaded", { id: toastId, duration: 1200 });- } catch (error) {- toast.error(- error instanceof Error ? error.message : "Failed to unload model.",- { id: toastId },- );- } finally {- setBusy(null);- }- } finally {- useChatRuntimeStore.getState().endModelLoading(lifecycleLease);- }- })();- }, [+ transitionWorkflow,+ pendingTranscribeRelease,+ handleModelSelect,+ handleEject,+ trainedTtsModels,+ } = useAudioModelSlot({+ active,+ activeRef,busy,- isRecording,+ busyRef,+ setBusy,mode,+ setMode,+ modeRef,+ generationPhaseRef,+ handleStopGeneration,refreshStatus,+ audioDevice,+ isMac,+ status,+ isRecording,+ stopAndDiscardRecording,releaseTranscribeSelection,+ ensureSttLoaded,+ sttGgufVariants,+ selectedSttRepoRef,+ setSelectedSttRepo,+ deferredSttLoad,+ sttLoadingGeneration,+ sttLoadGeneration,+ sttLoadAbort,+ audioCppRuntime,selectedSttRepo,- invalidatePendingStagedTts,- stageTtsDownload,- status?.active_model,sttReady,- stopAndDiscardRecording,- ]);+ sttStatusRefreshGeneration,+ });- const handleGenerate = useCallback(async () => {- const text = prompt.trim();- if (!text && !lyricsOptional) return;- // Same gate the TTS load path uses: switching straight from Transcribe with a speech model already resident- // needs no load, so nothing else waits for the sidecar teardown, and generating beside a dictation model OOMs a- // device that fits either alone. Claimed before the await below, since the button only disables on `busy` and a- // slow release let several clicks each resume into their own generateAudio.- if (busyRef.current) return;- busyRef.current = "generating";- setBusy("generating");- updateGenerationPhase("preparing");- const releaseInFlight = pendingTranscribeRelease.current;- if (releaseInFlight && !(await releaseInFlight)) {- updateGenerationPhase(null);- busyRef.current = null;- setBusy(null);- setMode("transcribe");- return;- }- const instructions = audioInstructions.trim();- if (musicNeedsDescription && !instructions) {- updateGenerationPhase(null);- busyRef.current = null;- setBusy(null);- toast.error("Add a music description. This model needs one beside the lyrics.");- return;- }- const missingOptions = missingRequiredAudioOptions(- audioOptionSpecs,- audioOptionValues,- );- if (missingOptions.length > 0) {- updateGenerationPhase(null);- busyRef.current = null;- setBusy(null);- setAdvancedOpen(true);- toast.error(- `Set ${missingOptions.map((spec) => audioOptionLabel(spec.name)).join(", ")} in Advanced before generating.`,- );- return;- }- const requestOptions = audioOptionsForRequest(- audioOptionSpecs,- audioOptionValues,- );- const language = audioLanguage.trim();- saveLastPrompt("audio", prompt);- const controller = new AbortController();- generateAbort.current = controller;- updateGenerationPhase("generating");- try {- const generated = await generateAudio(text, {- ...(!musicGeneration && samplingControls && temperatureEdited- ? { temperature }- : {}),- max_tokens: musicGeneration- ? minimaxMusicFramesForSeconds(musicSeconds)- : mossFrameLimit !== null- ? mossTtsFramesForSeconds(mossMaxSeconds, mossFrameLimit)- : maxTokens,- ...(instructionsKind !== null && instructions- ? { audio_instructions: instructions }- : {}),- ...(mossLocalGeneration && language- ? { audio_language: language }- : {}),- ...(Object.keys(requestOptions).length > 0- ? { audio_options: requestOptions }- : {}),- signal: controller.signal,- });- if (generated.choices[0]?.finish_reason === "length")- toast.warning(- maxTokens < TTS_MAX_TOKENS- ? "Speech stopped at the Max tokens limit before the end of the text. Raise Max tokens under Advanced to hear the rest."- : "Speech stopped at the Max tokens limit before the end of the text. Split the text into shorter parts to hear the rest.",- );- updateGenerationPhase("finishing");- const refreshed = await refreshGallery();- const generatedClip = persistedClipForGeneration(- generated.clip_id,- refreshed,- );- if (generatedClip) {- setFallbackClip(null);- selectClip(generatedClip.id);- } else if (generated.clip_id) {- // The server did persist it; only this refresh missed it. Select the id so a later refresh shows the real- // record, but keep the response audio too: selectedClip resolves against `clips`, so an id that is not there- // yet would render the empty state.- setFallbackClip({- url: `data:audio/wav;base64,${generated.audio.data}`,- prompt: text,- model: generated.model,- saved: true,- });- selectClip(generated.clip_id, true);- } else {- // Gallery persistence is best-effort server-side, so a full disk still returns the audio. Play it- // from the response rather than dropping an expensive generation.- galleryCache.selectedId = null;- setSelectedId(null);- setFallbackClip({- url: `data:audio/wav;base64,${generated.audio.data}`,- prompt: text,- model: generated.model,- saved: false,- });- }- } catch (error) {- if (!controller.signal.aborted) {- updateGenerationPhase("finishing");- toast.error(- error instanceof Error ? error.message : "Audio generation failed.",- );- await refreshStatus();- }- } finally {- generateAbort.current = null;- updateGenerationPhase(null);- busyRef.current = null;- setBusy(null);- if (activeRef.current && modeRef.current === "speak")- replayQueuedTtsPick();- }- }, [+ const [freshClipId, setFreshClipId] = useState<string | null>(null);+ const [announcement, setAnnouncement] = useState("");+ const selectGeneratedClip = useCallback(+ (id: string, keepFallback?: boolean) => {+ selectClip(id, keepFallback);+ setFreshClipId(id);+ setAnnouncement("New clip ready.");+ },+ [selectClip],+ );+ const clearFreshClip = useCallback(() => setFreshClipId(null), []);+ useEffect(() => {+ if (busy === "generating") setAnnouncement("");+ }, [busy]);++ const {prompt,+ setPrompt,audioInstructions,+ setAudioInstructions,audioLanguage,+ setAudioLanguage,+ temperature,+ handleTemperatureChange,+ maxTokens,+ setMaxTokens,+ mossMaxSeconds,+ setMossMaxSeconds,+ setMinimaxMaxSeconds,+ mossFrameLimit,+ mossMaxSecondsLimit,+ ttsLoaded,musicGeneration,+ cudaMusicGeneration,musicNeedsDescription,lyricsOptional,- audioOptionSpecs,- audioOptionValues,- setAdvancedOpen,- mossLocalGeneration,- mossFrameLimit,- mossMaxSeconds,+ musicRange,musicSeconds,samplingControls,- instructionsKind,- temperature,- temperatureEdited,+ audioOptionSpecs,+ audioOptionValues,+ handleAudioOptionChange,+ handleAudioOptionsReset,+ handleGenerate,+ generationError,+ setGenerationError,+ } = useSpeechGeneration({+ workflow: ttsWorkflow,+ status,+ busyRef,+ setBusy,updateGenerationPhase,- maxTokens,- refreshGallery,+ generateAbort,+ setMode,+ setAdvancedOpen,refreshStatus,+ activeRef,+ modeRef,+ refreshGallery,+ selectClip: selectGeneratedClip,+ setFallbackClip,+ setSelectedId,+ pendingTranscribeRelease,replayQueuedTtsPick,- selectClip,- ]);-- // Only unmount aborts. RootLayout keeps this page mounted precisely so leaving the tab does not- // cancel synthesis, and the clip is persisted server-side.- useEffect(() => () => generateAbort.current?.abort(), []);-+ });- const prepareTranscriptionModel = useCallback(async () => {- const repo = selectedSttRepoRef.current ?? lastSttRepo;- if (!repo) {- toast.info("Pick a speech-to-text model first.");- return null;- }- selectedSttRepoRef.current = repo;- setSelectedSttRepo(repo);- const model = sttSidecarKeyFor(repo);- const engine = sttEngineForRepoId(repo);- if (sttLoadedModel !== model || sttLoadedEngine !== engine) {- if (!(await ensureSttLoaded(repo, model, engine))) return null;- }- setLastSttRepo(repo);- return { model, engine };- }, [- lastSttRepo,- sttLoadedModel,- sttLoadedEngine,- ensureSttLoaded,- setLastSttRepo,- ]);+ const { navigateSelf } = useAudioHandoff({+ active,+ busy,+ busyRef,+ handleModelSelect,+ transitionWorkflow,+ refreshGallery,+ loadMore,+ loadingMoreRef,+ selectClip,+ });- const runTranscription = useCallback(- async (blob: Blob, name: string, confirmedVersion?: number) => {- if (- transcriptionAbort.current ||- busyRef.current !== null ||- (confirmedVersion !== transcriptVersion.current &&- !confirmTranscriptReplacement())- ) return;- let started = false;- const controller = new AbortController();- transcriptionAbort.current = controller;- try {- const target = await prepareTranscriptionModel();- if (!target || controller.signal.aborted || !activeRef.current) return;- setBusy("transcribing");- clearTranscript();- setTranscribedName(name);- setTranscriptModel(target.model);- started = true;- setTranscriptionStartedAt(Date.now());- setTranscriptionFinishedAt(null);- setTranscriptionStopping(false);- setTranscriptionProgress(null);- const result = await transcribeWithProgress(- blob,- name,- {- ...target,- device: useVoiceSettingsStore.getState().sttDevice,- signal: controller.signal,- },- (progress) => {- if (!controller.signal.aborted) setTranscriptionProgress(progress);- },- );- if (controller.signal.aborted) return;- setTranscript(result.text);- setTranscriptModel(result.model);- setTranscriptRecord(result.record);- if (!result.text)- toast.info("The model heard no speech in that audio.");- else if (!result.record)- toast.error(- "Transcript could not be saved. Download a copy to keep it.",- );- } catch (error) {- if (controller.signal.aborted) {- setTranscriptError("Transcription cancelled.");- return;- }- const message =- error instanceof Error ? error.message : "Transcription failed.";- setTranscriptError(message);- toast.error(message);- } finally {- if (transcriptionAbort.current === controller) {- transcriptionAbort.current = null;- if (started) setTranscriptionFinishedAt(Date.now());- setBusy(null);- if (activeRef.current) void refreshSttStatus();- }- }- },- [- clearTranscript,- confirmTranscriptReplacement,- prepareTranscriptionModel,- refreshSttStatus,- ],+ const requestedWorkflow = useAudioWorkspaceStore(+ (state) => state.requestedWorkflow,);-- const handleRecordToggle = useCallback(async () => {- if (isRecording) {- const recorder = recorderRef.current;- if (recorder && recorder.state !== "inactive") recorder.stop();- return;- }- if (micPendingGeneration.current !== null || busyRef.current !== null) return;- if (!confirmTranscriptReplacement()) return;- const confirmedVersion = transcriptVersion.current;- const requestGeneration = ++micRequestGeneration.current;- micPendingGeneration.current = requestGeneration;- setMicRequestPending(true);- try {- if (- !(await prepareTranscriptionModel()) ||- !activeRef.current ||- micRequestGeneration.current !== requestGeneration- ) return;- const stream = await navigator.mediaDevices.getUserMedia({- audio: { echoCancellation: true, noiseSuppression: true },- });- if (- !micStreamRequestIsCurrent(- requestGeneration,- micRequestGeneration.current,- activeRef.current,- )- ) {- for (const track of stream.getTracks()) track.stop();- return;- }- recordStreamRef.current = stream;- const recorder = createAudioRecorder(stream);- // WAV is uncompressed, so on the PCM path the byte cap is reached long before the 30 minute one.- // Express it as a duration the timer below already enforces.- const maxSeconds =- recorder instanceof PcmRecorder- ? Math.min(- RECORDING_MAX_SECONDS,- recorder.secondsWithin(RECORDING_MAX_BYTES),- )- : RECORDING_MAX_SECONDS;- const chunks: Blob[] = [];- let recordedBytes = 0;- let limitHit: "duration" | "size" | null = null;- // The sidecar rejects anything past 30 minutes, and a timeslice keeps the chunks in our array- // rather than inside the browser, so an over-long recording can be stopped at the limit.- const stopAtLimit = (reason: "duration" | "size") => {- if (limitHit) return;- limitHit = reason;- toast.warning(- reason === "duration"- ? `Recording stopped at the ${Math.floor(maxSeconds / 60)} minute limit.`- : "Recording stopped: it reached the maximum upload size.",- );- try {- recorder.stop();- } catch {- // Already stopping; the stop handler still runs.- }- };- const durationTimer = window.setTimeout(- () => stopAtLimit("duration"),- maxSeconds * 1000,- );- recorder.addEventListener("dataavailable", (event) => {- if (event.data.size > 0) {- // Stop before appending the chunk that crosses the limit, so what is uploaded is always inside it.- if (recordedBytes + event.data.size > RECORDING_MAX_BYTES) {- stopAtLimit("size");- return;- }- chunks.push(event.data);- recordedBytes += event.data.size;- }- });- recorder.addEventListener("stop", () => {- window.clearTimeout(durationTimer);- const discard = discardRecordingRef.current;- discardRecordingRef.current = false;- setIsRecording(false);- stopRecordStream();- recorderRef.current = null;- const blob = new Blob(chunks, {- type: recorder.mimeType || "audio/webm",- });- if (!discard && blob.size > 0)- void runTranscription(blob, "Recording", confirmedVersion);- });- recorderRef.current = recorder;- // A timeslice is what makes the byte cap observable: with none, some browsers hold the whole- // recording internally and only emit it on stop.- recorder.start(RECORDING_CHUNK_MS);- setIsRecording(true);- } catch {- // getUserMedia may have succeeded even if MediaRecorder construction failed, so release that- // stream instead of leaving the mic live with no recorder UI to stop it.- recorderRef.current = null;- setIsRecording(false);- stopRecordStream();- if (- micStreamRequestIsCurrent(- requestGeneration,- micRequestGeneration.current,- activeRef.current,- )- )- toast.error("Could not access the microphone.");- } finally {- if (micPendingGeneration.current === requestGeneration) {- micPendingGeneration.current = null;- setMicRequestPending(false);- }- }- }, [- isRecording,- runTranscription,- stopRecordStream,- prepareTranscriptionModel,- confirmTranscriptReplacement,- ]);-- // Release the microphone on unmount AND whenever the page goes inactive: the page stays mounted- // across tab switches, so unmount alone left a hidden recorder capturing.+ // A refused request stays pending (the commit clears it) and is retried when busy settles.useEffect(() => {- if (!active) {- stopAndDiscardRecording();- }- return stopAndDiscardRecording;- }, [active, stopAndDiscardRecording]);-- useEffect(() => () => transcriptionAbort.current?.abort(), []);+ if (!active || requestedWorkflow === null) return;+ transitionWorkflow(requestedWorkflow);+ }, [active, busy, requestedWorkflow, transitionWorkflow]);- const handleTranscribeFile = useCallback(- (file: File | undefined) => {- if (!file) return;- void runTranscription(file, file.name);- },- [runTranscription],- );-- const handleCopyTranscript = useCallback(() => {- void copyToClipboard(transcript).then((ok) =>- ok- ? toast.success("Transcript copied")- : toast.error("Could not copy the transcript."),+ // A failed Transcribe release puts `mode` back on Transcribe from inside the slot; the workflow follows.+ const syncedMode = useRef(mode);+ useEffect(() => {+ if (syncedMode.current === mode) return;+ syncedMode.current = mode;+ const store = useAudioWorkspaceStore.getState();+ if (slotForWorkflow(store.workflow) === mode) return;+ store.commitWorkflow(+ mode === "transcribe" ? "transcribe" : musicGeneration ? "music" : "speak",);- }, [transcript]);-- const handleDownloadTranscript = useCallback(async () => {- const version = transcriptVersion.current;- if (- (await downloadTranscript(transcript, transcribedName ?? "transcript")) &&- transcriptVersion.current === version- )- setTranscriptExported(true);- }, [transcript, transcribedName]);-- const dropClip = useCallback((id: string) => {- galleryCache.srcById.delete(id);- setSrcById(galleryCache.srcById.toRecord());- // Drop the row now, as the clear-all path does: refreshGallery swallows a failed GET and returns- // the cache without setClips, leaving the row up against an already-revoked URL.- galleryCache.clips = galleryCache.clips.filter((clip) => clip.id !== id);- setClips(galleryCache.clips);- if (galleryCache.selectedId === id) {- galleryCache.selectedId = null;- setSelectedId(null);- }- }, []);-- const handleDeleteClip = useCallback(- async (id: string) => {- try {- await deleteAudioClip(id);- dropClip(id);- await refreshGallery(id);- } catch (error) {- toast.error(- error instanceof Error ? error.message : "Could not delete the clip.",- );- }- },- [dropClip, refreshGallery],- );+ }, [mode, musicGeneration]);- const handleArchiveClip = useCallback(- async (id: string) => {- try {- await setAudioClipFlags(id, { archived: true });- } catch (error) {- toast.error(- error instanceof Error ? error.message : "Could not archive the clip.",- );- return;- }- dropClip(id);- await refreshGallery(id);- const toastId = toast(- <button- type="button"- onClick={() => {- toast.dismiss(toastId);- useSettingsDialogStore.getState().openArchivedMedia("audio");- }}- className="w-full cursor-pointer text-left"- >- You can view archived audio in Settings- </button>,- { closeButton: true },- );- },- [dropClip, refreshGallery],- );-- // The pin state each id was last clicked or dragged into, so a stale response cannot undo a later one.- const pinAttempt = useRef(new Map<string, number>());- const pinSeq = useRef(0);-- const beginOrderWrite = useCallback(() => {- orderWrites.current.inFlight += 1;- orderWrites.current.epoch += 1;- }, []);- const endOrderWrite = useCallback(() => {- const writes = orderWrites.current;- writes.inFlight -= 1;- writes.epoch += 1;- if (writes.inFlight === 0 && writes.deferred) {- writes.deferred = false;- void refreshGallery(undefined, galleryCache.clips.length);- }- }, [refreshGallery]);-- const handleTogglePin = useCallback(async (id: string, pinned: boolean) => {- // The pinned order before the click, so a failed unpin goes back where it was.- const orderBefore = pinnedOrder(galleryCache.clips);- const attempt = (pinSeq.current += 1);- pinAttempt.current.set(id, attempt);- // Optimistic. Records carry the server's sort key, so the local re-sort matches it.- galleryCache.clips = applyPin(galleryCache.clips, id, pinned);- setClips(galleryCache.clips);- beginOrderWrite();- try {- // One queue for pins and moves: the server stamps pins in the order it runs them.- await serializeById("audio-pin", () => setAudioClipFlags(id, { pinned }));- // An unpinned clip can belong below the loaded window, so resync it once writes settle.- if (!pinned && galleryCache.hasMore) orderWrites.current.deferred = true;- } catch (error) {- toast.error(- error instanceof Error ? error.message : "Could not pin the clip.",- );- if (pinAttempt.current.get(id) === attempt) {- galleryCache.clips = pinned- ? applyPin(galleryCache.clips, id, false)- : restorePinOrder(galleryCache.clips, id, orderBefore);- setClips(galleryCache.clips);- }- } finally {- if (pinAttempt.current.get(id) === attempt) pinAttempt.current.delete(id);- endOrderWrite();+ const adoptedLoadedModel = useRef(false);+ useEffect(() => {+ if (adoptedLoadedModel.current || status === null) return;+ adoptedLoadedModel.current = true;+ if (modeRef.current === "speak" && ttsLoaded && musicGeneration) {+ useAudioWorkspaceStore.getState().adoptWorkflow("music");}- }, [beginOrderWrite, endOrderWrite]);+ }, [status, ttsLoaded, musicGeneration]);- // Drag to reorder: applied optimistically, then the server's record (key and pin) is adopted.- const handleMoveClip = useCallback(- async (id: string, afterId: string | null) => {- const next = moveGalleryItem(galleryCache.clips, id, afterId);- if (next === galleryCache.clips) return;- const guessedPinned = Boolean(next.find((c) => c.id === id)?.pinned);- // Takes a pin token too: a pin clicked after this drop must not be undone by its response.- const attempt = (pinSeq.current += 1);- pinAttempt.current.set(id, attempt);- galleryCache.clips = next;- setClips(next);- beginOrderWrite();- try {- const record = await serializeById("audio-pin", () =>- moveAudioClip(id, afterId),- );- if (pinAttempt.current.get(id) !== attempt) return;- pinAttempt.current.delete(id);- const patched = galleryCache.clips.map((c) =>- c.id === id- ? { ...c, pinned: record.pinned, order_at: record.order_at }- : c,- );- // Re-sort only if the local pin guess was wrong.- galleryCache.clips =- Boolean(record.pinned) === guessedPinned- ? patched- : sortGalleryItems(patched);- setClips(galleryCache.clips);- } catch (error) {- toast.error(- error instanceof Error ? error.message : "Could not move the clip.",- );- if (pinAttempt.current.get(id) === attempt) pinAttempt.current.delete(id);- // Put the server's order back once no other write is in flight.- orderWrites.current.deferred = true;- } finally {- endOrderWrite();- }- },- [beginOrderWrite, endOrderWrite],- );- const historyReorder = useStripReorder(- (id, afterId) => void handleMoveClip(id, afterId),- { axis: "y" },+ const {+ visibleClips,+ selectedClip,+ selectedClipSrc,+ loadMoreVisible,+ fallbackClip: pageFallbackClip,+ } = useWorkflowHistory({+ workflow: ttsWorkflow,+ enabled: active && mode === "speak",+ clips,+ hasMore,+ selectedId,+ srcById,+ fallbackClip,+ loadMore,+ loadingMoreRef,+ selectClip,+ });+ const handleClearWorkflowGallery = useCallback(+ () => handleClearGallery(ttsWorkflow),+ [handleClearGallery, ttsWorkflow],);-- // This page stays mounted across route changes, so a restore from the Settings archive would not reach- // History until a reload. Refresh the loaded window, not just the first page: a clip re-enters at its own age.- useEffect(- () =>- subscribeGalleryChanged("audio", () => {- void refreshGallery(undefined, galleryCache.clips.length);- }),- [refreshGallery],+ // Send to: only pages that can take a finished clip today. Bytes first, so a failed fetch leaves the page.+ const sendHandlersFor = useCallback(+ (clip: AudioGalleryClip): ClipSendHandlers => ({+ transcribe: () => {+ // Switching mid-run stops the run, and the stopped run still holds the page busy, so the+ // transcription would be refused and the clip silently dropped.+ const busyNow = () => {+ if (busyRef.current === null) return false;+ toast.info("Wait for the current audio task to finish, then send the clip.");+ return true;+ };+ if (busyNow()) return;+ void (async () => {+ try {+ const blob = await fetchClipBlob(clip.url);+ // Checked again: a run started while the clip downloaded would be stopped the same way.+ if (busyNow()) return;+ if (!transitionWorkflow("transcribe")) return;+ const name = `${clip.prompt.trim().slice(0, 40) || "Audio clip"}.wav`;+ handleTranscribeFile(+ new File([blob], name, { type: blob.type || "audio/wav" }),+ );+ } catch (error) {+ toast.error(+ error instanceof Error+ ? error.message+ : "Could not load this clip for transcription.",+ );+ }+ })();+ },+ }),+ [transitionWorkflow, handleTranscribeFile, busyRef],);-- const handleClearGallery = useCallback(async () => {- try {- await clearAudioGallery();- galleryCache.srcById.clear();- galleryCache.selectedId = null;- // Drop the cached list first: refreshGallery merges the fetched page into it, so an empty page- // would leave every cleared row on screen.- galleryCache.clips = [];- // React state too, not just the cache: refreshGallery swallows a failed GET and returns the cache- // without calling setClips, which left cleared rows rendered against a revoked URL.- setClips([]);- setSrcById({});- setSelectedId(null);- await refreshGallery();- } catch (error) {- toast.error(- error instanceof Error ? error.message : "Could not clear the gallery.",- );- }- }, [refreshGallery]);-- const handleDownloadClip = useCallback(+ const handleUseTextAgain = useCallback((clip: AudioGalleryClip) => {- const src = srcById[clip.id];- if (!src) return;- const anchor = document.createElement("a");- anchor.href = src;- anchor.download = `${clip.id}.wav`;- anchor.click();+ if (transitionWorkflow(clipWorkflow(clip))) setPrompt(clip.prompt);},- [srcById],+ [transitionWorkflow, setPrompt],);- const handleDownloadFallbackClip = useCallback(() => {- if (!fallbackClip) return;- const anchor = document.createElement("a");- anchor.href = fallbackClip.url;- anchor.download = "generated-audio.wav";- anchor.click();- }, [fallbackClip]);-- /** Download from a history row, whose bytes are only fetched once selected. */- const handleDownloadClipById = useCallback(async (clip: AudioGalleryClip) => {- let temporaryUrl: string | null = null;- try {- let src = galleryCache.srcById.get(clip.id);- if (!src) {- const fetched = await fetchClipObjectUrl(clip.url);- src = fetched.url;- temporaryUrl = fetched.url;- }- const anchor = document.createElement("a");- anchor.href = src;- anchor.download = `${clip.id}.wav`;- anchor.click();- } catch {- toast.error("Could not download the clip.");- } finally {- // A history-row download does not need to become resident playback state, so revoke it after the- // browser has consumed the synthetic click rather than bypassing the 64 MB cache budget.- if (temporaryUrl) {- const url = temporaryUrl;- window.setTimeout(() => URL.revokeObjectURL(url), 0);+ const pageModelLoaded =+ ttsLoaded && (ttsWorkflow === "music") === musicGeneration;+ const openSelector = useCallback(() => setSelectorOpen(true), []);+ const chooseModelAction = { label: "Choose a model", onClick: openSelector };+ const generateBlocker: GenerateBlocker | null =+ busy === "loading"+ ? { reason: "Waiting for the model to finish loading." }+ : busy !== null+ ? null+ : !ttsLoaded+ ? {+ reason:+ ttsWorkflow === "music"+ ? "Load a music model to generate."+ : "Load a speech model to generate.",+ actions: [chooseModelAction],+ }+ : !pageModelLoaded+ ? musicGeneration+ ? {+ reason: "The loaded model makes music.",+ actions: [+ { label: "Choose a speech model", onClick: openSelector },+ {+ label: "open Music",+ onClick: () => transitionWorkflow("music"),+ },+ ],+ }+ : {+ reason: "The loaded model makes speech.",+ actions: [+ { label: "Choose a music model", onClick: openSelector },+ {+ label: "open Speak",+ onClick: () => transitionWorkflow("speak"),+ },+ ],+ }+ : !prompt.trim() && !lyricsOptional+ ? {+ reason:+ ttsWorkflow === "music"+ ? "Write the lyrics to generate."+ : "Type the text to speak.",+ }+ : musicNeedsDescription && !audioInstructions.trim()+ ? {+ reason:+ "Add a music description. This model needs one beside the lyrics.",+ }+ : null;+ const generateFailure: GenerateBlocker | null = generationError+ ? {+ reason: /[.!?]$/.test(generationError) ? generationError : `${generationError}.`,+ actions: [{ label: "Choose a different model", onClick: openSelector }],}+ : null;+ useEffect(() => {+ setGenerationError(null);+ }, [status?.active_model, setGenerationError]);+ useEffect(() => {+ if (busy === "generating") setGenerationError(null);+ }, [busy, setGenerationError]);+ const [elapsedSeconds, setElapsedSeconds] = useState<number | null>(null);+ useEffect(() => {+ if (busy !== "generating") {+ setElapsedSeconds(null);+ return;}- }, []);-- const handleCopyPrompt = useCallback(async (text: string) => {- if (await copyToClipboard(text)) {- toast.success("Text copied");- } else {- toast.error("Could not copy the text.");- }- }, []);-- // Trained TTS checkpoints. A scan row carries no modality until the backend tags it, so without- // this a checkpoint you just fine-tuned here is unreachable.- const [trainedTtsModels, setTrainedTtsModels] = useState<ModelOption[]>([]);+ const startedAt = Date.now();+ setElapsedSeconds(0);+ const timer = window.setInterval(+ () => setElapsedSeconds(Math.floor((Date.now() - startedAt) / 1000)),+ 1000,+ );+ return () => window.clearInterval(timer);+ }, [busy]);+ const canGenerate =+ mode === "speak" &&+ busy === null &&+ !generationPresentation &&+ pageModelLoaded &&+ generateBlocker === null;+ const shortcutLabel = isMac ? "⌘ Enter" : "Ctrl+Enter";+ const pageRootRef = useRef<HTMLDivElement | null>(null);+ const generateShortcut = useRef<() => void>(() => {});+ generateShortcut.current = () => {+ if (canGenerate) void handleGenerate();+ };useEffect(() => {if (!active) return;- let cancelled = false;- listLoras()- .then((res) => {- if (cancelled) return;- setTrainedTtsModels(- res.loras- // Merged native speech checkpoints bypass MLX through the portable audio worker. Other- // safetensors exports still need a GGUF build on Mac.- .filter(- (lora) =>- !isMac ||- trainedTtsCheckpointIsRunnableOnMac(- lora.audio_type,- lora.export_type,- ),- )- // The GGUF flag matters: GGUF_TTS_AUDIO_TYPES leaves csm out because llama.cpp has no CSM- // decoder, so a csm LoRA exported to GGUF fails at load.- .filter((lora) =>- isTtsAudioType(lora.audio_type, lora.export_type === "gguf"),- )- .filter((lora) =>- trainedTtsCheckpointIsLoadable(lora.audio_type, lora.export_type),- )- .map((lora) => ({- id: lora.adapter_path,- name: audioModelLabel(lora.adapter_path),- description:- lora.export_type === "merged"- ? `Fine-tuned - ${lora.base_model || "unknown base"}`- : `LoRA - ${lora.base_model || "unknown base"}`,- audioType: lora.audio_type ?? null,- })),- );- })- .catch(() => {- // Listing trained models is additive; the catalog rows still work without it.- if (!cancelled) setTrainedTtsModels([]);- });- return () => {- cancelled = true;+ const onKeyDown = (event: KeyboardEvent) => {+ if (+ event.key !== "Enter" ||+ !(event.metaKey || event.ctrlKey) ||+ event.isComposing ||+ !(event.target instanceof Node) ||+ !pageRootRef.current?.contains(event.target)+ )+ return;+ event.preventDefault();+ generateShortcut.current();};- }, [active, isMac]);-+ document.addEventListener("keydown", onKeyDown);+ return () => document.removeEventListener("keydown", onKeyDown);+ }, [active]);+ const instructionsKind = instructionsFieldKind(ttsWorkflow, status?.audio_type);- const selectedClip = clips.find((c) => c.id === selectedId) ?? null;- const selectedClipSrc = selectedClip ? srcById[selectedClip.id] : undefined;const selectorModels =- mode === "speak" && isMac- ? MODELS_BY_MODE.speak.filter((model) =>- macTtsCatalogChoiceIsRunnable(model.id),- )+ mode === "speak"+ ? ttsWorkflow === "music"+ ? musicPageModels(MODELS_BY_MODE.speak, isMac)+ : speakPageModels(MODELS_BY_MODE.speak, isMac): MODELS_BY_MODE[mode];+ const selectorRowFilter = useCallback(+ (row: AudioPickerRow) =>+ audioRowMatchesWorkflow(row, pageWorkflow),+ [pageWorkflow],+ );const sttOnDeviceModels = downloadedSttArtifacts.map((artifact) => {const catalogModel = MODELS_BY_MODE.transcribe.find((model) => model.id.toLowerCase() === artifact.repoId.toLowerCase(),@@ -2844,10 +673,16 @@ export function AudioPage({const capabilityLine =mode === "speak"? ttsLoaded- ? audioCapabilityLine(musicGeneration ? "music" : "tts", status?.audio_type)+ ? pageModelLoaded+ ? audioCapabilityLine(musicGeneration ? "music" : "tts", status?.audio_type)+ : musicGeneration+ ? "The loaded model makes music. Pick a speech model."+ : "The loaded model is not a music model.": status?.active_model? "The loaded model is not a TTS audio model."- : "No TTS model loaded."+ : ttsWorkflow === "music"+ ? "No music model loaded."+ : "No TTS model loaded.": sttSelected? audioCapabilityLine("stt", sttReady ? "ready" : "loading"): "No transcription model selected.";@@ -2856,6 +691,7 @@ export function AudioPage({<div{...{ [MEDIA_RAIL_ROOT_ATTR]: "" }}style={railRootStyle}+ ref={pageRootRef}className="@container relative flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-hidden pt-[var(--studio-content-top-inset,0px)]">{/* Page-level, so the handle covers the divider through the header too. */}@@ -2882,8 +718,15 @@ export function AudioPage({triggerDataTour="audio-model"models={selectorModels}additionalOnDeviceModels={- mode === "transcribe" ? sttOnDeviceModels : trainedTtsModels+ mode === "transcribe"+ ? sttOnDeviceModels+ : trainedTtsModels.filter(+ (model) =>+ isMusicGenerationModel(model.id, model.audioType) ===+ (ttsWorkflow === "music"),+ )}+ rowFilter={selectorRowFilter}loadedModelIdOverride={mode === "transcribe" && sttReady? (selectedSttRepo ?? undefined)@@ -2910,47 +753,51 @@ export function AudioPage({</div><div className="grid h-full min-w-0 grid-cols-[1fr_auto_auto] gap-2 @[50rem]:grid-cols-[1fr_auto_1fr] @[50rem]:gap-0"><div className="pointer-events-auto col-start-2 justify-self-end pt-[var(--studio-chat-header-padding-top,11px)] @[50rem]:justify-self-center">- <PillTabs- ariaLabel="Page mode"- // Always "create": Train navigates away, so the pill never latches.- value="create"- onValueChange={(v) => {- if (v !== "train") return;- toast.info(- "Audio fine-tuning lives on the Train page. Unsloth trains TTS and STT models there. Pick an audio model and appropriate dataset.",- { duration: 8000 },- );- void navigateSelf({ to: "/studio" });- }}- fit={true}- className="h-[calc(34px*var(--ui-space-scale,1))] [&>button]:h-[calc(34px*var(--ui-space-scale,1))] [&>button]:px-3 @[68rem]:[&>button]:px-11 @max-[30rem]:[&>button]:px-2.5 @max-[30rem]:[&>button>span]:sr-only"- tabs={[- {- value: "create",- label: "Create",- icon: (- <HugeiconsIcon icon={SparklesIcon} className="size-3.5" />- ),- },- {- value: "train",- label: "Train",- icon: (- <HugeiconsIcon- icon={TestTubeOutlineIcon}- className="size-3.5"- />- ),- },- ]}- />+ {workflowTab.createTrain ? (+ <PillTabs+ ariaLabel="Page mode"+ // Always "create": Train navigates away, so the pill never latches.+ value="create"+ onValueChange={(v) => {+ if (v !== "train") return;+ toast.info(+ "Audio fine-tuning lives on the Train page. Unsloth trains TTS and STT models there. Pick an audio model and appropriate dataset.",+ { duration: 8000 },+ );+ void navigateSelf({ to: "/studio" });+ }}+ fit={true}+ className="h-[calc(34px*var(--ui-space-scale,1))] [&>button]:h-[calc(34px*var(--ui-space-scale,1))] [&>button]:px-3 @[68rem]:[&>button]:px-11 @max-[30rem]:[&>button]:px-2.5 @max-[30rem]:[&>button>span]:sr-only"+ tabs={[+ {+ value: "create",+ label: "Create",+ icon: (+ <HugeiconsIcon icon={SparklesIcon} className="size-3.5" />+ ),+ },+ {+ value: "train",+ label: "Train",+ icon: (+ <HugeiconsIcon+ icon={TestTubeOutlineIcon}+ className="size-3.5"+ />+ ),+ },+ ]}+ />+ ) : null}</div>- <div className="pointer-events-none col-start-3 flex min-w-0 items-start justify-end pr-2 pt-[var(--studio-chat-header-padding-top,11px)]">+ {/* Its own container: at a large UI size the column is too narrow for the label, which then+ truncated to "Li…". The arrow drops first, then the label, leaving the named icon. */}+ <div className="@container pointer-events-none col-start-3 flex min-w-0 items-start justify-end pr-2 pt-[var(--studio-chat-header-padding-top,11px)]"><div className="pointer-events-auto flex min-w-0 items-center gap-2"><LibraryPageLinktab="audio"- labelClassName="hidden @[50rem]:inline"- arrowClassName="hidden @[50rem]:block"+ labelClassName="hidden @[8.5rem]:inline"+ arrowClassName="hidden @[10rem]:block"/></div></div>@@ -2974,354 +821,109 @@ export function AudioPage({settingsFadeClass,)}>- {/* Same heading treatment as the Images and Video Create panes, so the media panes stay level (#7986). */}- <div className="mb-2 grid gap-1.5">- <h2 className="flex items-center gap-2 font-heading text-xl font-medium leading-none text-foreground">- <HugeiconsIcon- icon={mode === "speak" ? AudioWave01Icon : Mic01Icon}- className="size-[calc(18px*var(--ui-space-scale,1))] shrink-0"+ {/* One child, so the scroll fades see the rail grow (they watch only the first child): with+ the heading first, opening Advanced left the bottom fade over the last controls. */}+ <div className="flex flex-col gap-4">+ {/* Same heading treatment as the Images and Video Create panes, so the media panes stay level (#7986). */}+ <div className="mb-2 grid gap-1.5">+ <WorkflowTitleMenu+ workflow={pageWorkflow}+ onSelect={transitionWorkflow}/>- {mode === "speak" ? "Generate audio" : "Transcribe"}- </h2>- {/* The always-on capability line: which task the selected model actually does. */}- <p className="text-xs leading-snug text-muted-foreground">- {capabilityLine}- </p>- </div>-- <PillTabs- dataTour="audio-mode"- ariaLabel="Create mode"- value={mode}- onValueChange={(v) => transitionMode(v as CreateMode)}- fit={true}- className="h-[calc(30px*var(--ui-space-scale,1))] self-start [&>button]:h-[calc(30px*var(--ui-space-scale,1))] [&>button]:px-6"- tabs={[- { value: "speak", label: "Generate" },- { value: "transcribe", label: "Transcribe" },- ]}- />+ <p className="text-ui-11p5 leading-snug text-muted-foreground">+ {workflowTab.hint}+ </p>+ <p className="text-xs leading-snug text-muted-foreground">+ {capabilityLine}+ </p>+ </div>- {mode === "speak" ? (- <>- <Field- label={musicGeneration ? "Lyrics" : "Text"}- htmlFor="audio-prompt"- hint={- musicGeneration- ? "Lyrics may use sections such as [verse] and [chorus]. The completed song lands in the gallery on the right."- : "What the model should say. Generation runs on the loaded TTS model and lands in the gallery on the right."- }- >- <Textarea- id="audio-prompt"- value={prompt}- onChange={(event) => setPrompt(event.target.value)}- placeholder={- musicGeneration- ? "[verse]\nMorning light through the pines…\n\n[chorus]\n…"- : "Type the sentence to speak…"- }- className="min-h-28"- />- </Field>- {instructionsKind !== null ? (- <Field- label={- instructionsKind === "music"- ? "Music description"- : instructionsKind === "scene"- ? "Scene description"- : instructionsKind === "voice"- ? "Voice or style description"- : "Style instructions"- }- hint={- instructionsKind === "music"- ? musicNeedsDescription- ? "Describe genre, tempo, mood, vocals, and arrangement. This model requires it separately from the lyrics."- : "Optional genre, tempo, mood, vocals, and arrangement. Without it, the text above is used as the prompt."- : instructionsKind === "scene"- ? "Optional Higgs TTS 2 scene guidance such as room acoustics, recording conditions, or background ambience."- : instructionsKind === "voice"- ? "Optional. Used by Qwen3-TTS VoiceDesign, Qwen3-TTS CustomVoice and VoxCPM2; other models ignore it."- : "Optional MOSS Local guidance such as speaking style, emotion, pace, or delivery."- }- htmlFor="audio-instructions"- >- <Textarea- id="audio-instructions"- value={audioInstructions}- onChange={(event) =>- setAudioInstructions(event.target.value)- }- placeholder={- instructionsKind === "music"- ? "Acoustic pop, 96 BPM, warm female lead, fingerpicked guitar and soft piano…"- : instructionsKind === "scene"- ? "Close-mic studio recording in a quiet, softly treated room…"- : instructionsKind === "voice"- ? "A warm, low female voice, speaking slowly and calmly…"- : "Warm, measured delivery with a calm conversational tone…"- }- className="min-h-24"- />- </Field>- ) : null}- {mossLocalGeneration ? (- <Field- label="Language"- htmlFor="audio-language"- hint="Optional, but MOSS Local v1.5 recommends a language tag when known (for example English, Arabic, or French)."- >- <Input- id="audio-language"- value={audioLanguage}- onChange={(event) => setAudioLanguage(event.target.value)}- placeholder="English"- />- </Field>- ) : null}- {/* Field inlined: its label needs a form control to point- at, and PillTabs is a tablist with its own name. */}- <div className="grid gap-1.5">- <span className="text-ui-13 font-medium text-foreground">- Load model into- </span>- <PillTabs- ariaLabel="Load model into"- value={audioDevice === "cpu" ? "cpu" : "auto"}- // The eject below applies the change and cannot interrupt a load.- disabled={busy !== null || isRecording}- onValueChange={(value) => {- const next = value === "cpu" ? "cpu" : "auto";- if (next === audioDevice) return;- // MiniMax needs CUDA, and the backend's refusal cannot save a- // model already ejected here.- if (next === "cpu" && status?.audio_type === "minimax_music3") {- toast.info(- "MiniMax Music 3 needs a GPU, so it cannot be held in CPU RAM.",- );- return;- }- setAudioDeviceState(next);- if (ttsLoaded) handleEject();- }}- fit={true}- className="h-[calc(30px*var(--ui-space-scale,1))] self-start [&>button]:h-[calc(30px*var(--ui-space-scale,1))] [&>button]:px-6"- tabs={[- { value: "auto", label: "GPU when available" },- { value: "cpu", label: "CPU RAM" },- ]}- />- {/* Phrased as what the next load will do, not as the resident- model's state: a model loaded by another tab or client can- be on the other device, and status does not report it. */}- <p className="text-ui-11p5 leading-snug text-muted-foreground">- {audioDevice === "cpu"- ? "New loads go into system RAM instead of the GPU. Slower to generate, and no GPU memory is used."- : "New loads use the GPU when there is one, and the CPU otherwise."}- </p>- </div>- {/* GGUF runtime speech keeps its own sampling and length; its options come from the model. */}- {musicGeneration ||- samplingControls ||- audioOptionSpecs.length > 0 ? (- <AdvancedDisclosure- open={advancedOpen}- onOpenChange={setAdvancedOpen}- description={- musicGeneration- ? "Generation length and model options. Changes apply to the next audio clip."- : samplingControls- ? "Generation sampling. Changes apply to the next audio clip."- : "Model options. Changes apply to the next audio clip."- }- >- {!musicGeneration && samplingControls ? (- <ParamSlider- label="Temperature"- value={temperature}- min={0}- max={mossFrameLimit !== null ? 2 : 1.5}- step={0.05}- onChange={handleTemperatureChange}- />- ) : null}- {musicGeneration ? (- <ParamSlider- label="Max duration (seconds)"- value={musicSeconds}- min={musicRange.min}- max={musicRange.max}- step={1 / MINIMAX_MUSIC_FRAMES_PER_SECOND}- onChange={setMinimaxMaxSeconds}- valueSize={8}- info={- cudaMusicGeneration- ? `Starts at ${MINIMAX_MUSIC_DEFAULT_SECONDS} seconds. MiniMax Music 3 generates ${MINIMAX_MUSIC_FRAMES_PER_SECOND} frames per second, up to ${musicRange.max} seconds.`- : `Starts at ${MINIMAX_MUSIC_DEFAULT_SECONDS} seconds. This model generates between ${musicRange.min} and ${musicRange.max} seconds.`- }- />- ) : mossFrameLimit !== null ? (- <ParamSlider- label="Max duration (seconds)"- value={mossMaxSeconds}- min={1}- max={mossMaxSecondsLimit}- step={1 / MOSS_TTS_FRAMES_PER_SECOND}- onChange={setMossMaxSeconds}- valueSize={8}- info={`Starts at ${MOSS_TTS_DEFAULT_SECONDS} seconds. This model reports ${mossFrameLimit?.toLocaleString()} frames (${mossMaxSecondsLimit.toLocaleString(undefined, { maximumFractionDigits: 2 })} seconds); the prompt uses part of that context.`}- />- ) : samplingControls ? (- <ParamSlider- label="Max tokens"- value={maxTokens}- min={256}- max={TTS_MAX_TOKENS}- step={256}- onChange={setMaxTokens}- />- ) : null}- {audioOptionSpecs.length > 0 ? (+ {mode === "speak" ? (+ (() => {+ const railProps = {+ prompt,+ setPrompt,+ toolPanels: instructionsKind ? (<>- <AudioOptionFields- specs={audioOptionSpecs}- values={audioOptionValues}- onChange={handleAudioOptionChange}- disabled={busy === "generating"}- family={status?.audio_family}+ <InstructionsField+ instructionsKind={instructionsKind}+ musicNeedsDescription={musicNeedsDescription}+ audioInstructions={audioInstructions}+ setAudioInstructions={setAudioInstructions}/>- {Object.keys(audioOptionValues).length > 0 ? (- <Button- type="button"- variant="ghost"- size="sm"- className="self-start"- onClick={handleAudioOptionsReset}- >- Reset model options- </Button>+ {instructionsKind === "style" ? (+ <MossLanguageField+ audioLanguage={audioLanguage}+ setAudioLanguage={setAudioLanguage}+ />) : null}</>- ) : null}- </AdvancedDisclosure>- ) : null}- </>- ) : (- <>- <Field- label="Microphone"- htmlFor="audio-record"- hint={- recordingSupported- ? "Record a clip and it is transcribed when you stop."- : "This browser cannot record. Open Unsloth over https or on localhost, or upload a file below."- }- >- <Button- data-tour="audio-record"- id="audio-record"- variant={isRecording ? "destructive" : "secondary"}- disabled={- !recordingSupported ||- (!isRecording && (!(sttSelected || lastSttRepo) || busy !== null)) ||- micRequestPending- }- onClick={handleRecordToggle}- >- <HugeiconsIcon- icon={isRecording ? StopIcon : Mic01Icon}- className="mr-2 size-4"- />- {isRecording- ? "Stop recording"- : micRequestPending- ? busy === "loading" ? "Loading model…" : "Waiting for microphone…"- : "Record"}- </Button>- </Field>- <Field- label="Audio file"- htmlFor="audio-file"- hint="Or transcribe an existing recording (wav, mp3, m4a, webm…)."- >- <input- id="audio-file"- type="file"- accept="audio/*"- disabled={- !(sttSelected || lastSttRepo) ||- busy !== null ||- isRecording ||- micRequestPending- }- onChange={(event) => {- handleTranscribeFile(event.target.files?.[0]);- event.target.value = "";- }}- className="text-ui-13 file:mr-3 file:rounded-md file:border-0 file:bg-muted file:px-3 file:py-1.5 file:text-ui-13 file:font-medium"- />- </Field>- {sttSelected || lastSttRepo ? null : (- <p className="text-ui-11p5 leading-snug text-muted-foreground">- Pick a speech-to-text model (Whisper or Qwen3-ASR) from the- selector above to transcribe.- </p>- )}- </>- )}+ ) : null,+ audioDevice,+ busy,+ isRecording,+ status,+ setAudioDeviceState,+ ttsLoaded,+ handleEject,+ samplingControls,+ audioOptionSpecs,+ advancedOpen,+ setAdvancedOpen,+ temperature,+ mossFrameLimit,+ handleTemperatureChange,+ musicSeconds,+ musicRange,+ setMinimaxMaxSeconds,+ cudaMusicGeneration,+ mossMaxSeconds,+ mossMaxSecondsLimit,+ setMossMaxSeconds,+ maxTokens,+ setMaxTokens,+ audioOptionValues,+ handleAudioOptionChange,+ handleAudioOptionsReset,+ };+ return ttsWorkflow === "music" ? (+ <MusicRail {...railProps} />+ ) : (+ <SpeakRail {...railProps} />+ );+ })()+ ) : (+ <TranscribeRail+ recordingSupported={recordingSupported}+ isRecording={isRecording}+ sttSelected={sttSelected}+ lastSttRepo={lastSttRepo}+ busy={busy}+ micRequestPending={micRequestPending}+ handleRecordToggle={handleRecordToggle}+ handleTranscribeFile={handleTranscribeFile}+ />+ )}+ </div></div>{mode === "speak" ? (/* The scroll mask provides the fade; leave the footer unpainted to avoid dark-mode banding. */<div className="relative z-10 flex shrink-0 justify-center px-10 pt-0.5 pb-4">- <div className="flex w-full max-w-sm flex-col gap-2">- {busy === "generating" && generationPresentation ? (- <>- <output- aria-live="polite"- aria-atomic="true"- className="text-center text-ui-12 text-muted-foreground"- >- {generationPresentation.status}- </output>- <Progress- indeterminate- aria-label="Audio task in progress"- className="h-1.5"- />- </>- ) : null}- <Button- className="relative z-10 mx-auto h-11 px-8 disabled:bg-muted disabled:text-muted-foreground disabled:opacity-100"- onClick={- generationPresentation?.canStop- ? handleStopGeneration- : handleGenerate- }- disabled={- generationPresentation- ? !generationPresentation.canStop- : busy !== null ||- !ttsLoaded ||- (!prompt.trim() && !lyricsOptional) ||- (musicNeedsDescription && !audioInstructions.trim())- }- variant={- generationPresentation?.canStop ? "destructive" : "default"- }- >- {generationPresentation?.canStop ? (- <>- <HugeiconsIcon icon={StopIcon} className="mr-2 size-4" />- Stop- </>- ) : (- (generationPresentation?.actionLabel ?? "Generate")- )}- </Button>- </div>+ <TtsFooter+ busy={busy}+ generationPresentation={generationPresentation}+ handleStopGeneration={handleStopGeneration}+ handleGenerate={handleGenerate}+ ttsLoaded={pageModelLoaded}+ prompt={prompt}+ lyricsOptional={lyricsOptional}+ musicNeedsDescription={musicNeedsDescription}+ audioInstructions={audioInstructions}+ blocker={generateBlocker}+ shortcutLabel={shortcutLabel}+ error={generateFailure}+ elapsedSeconds={elapsedSeconds}+ /></div>) : null}</div>@@ -3337,304 +939,86 @@ export function AudioPage({}className="flex min-h-0 flex-1 flex-col gap-3 p-6 px-10 @[50rem]:pt-[calc(60px*var(--ui-space-scale,1))]">- <div className="hover-scrollbar flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto">- {transcriptionStartedAt !== null && (- <TranscriptionProgress- startedAt={transcriptionStartedAt}- finishedAt={transcriptionFinishedAt}- stopping={transcriptionStopping}- progress={transcriptionProgress}- onCancel={() => {- setTranscriptionStopping(true);- transcriptionAbort.current?.abort();- }}- />- )}- {transcript ? (- <>- <div className="flex items-center gap-2">- <Button- variant="secondary"- size="sm"- onClick={handleCopyTranscript}- >- Copy- </Button>- <Button- variant="secondary"- size="sm"- onClick={handleDownloadTranscript}- >- <HugeiconsIcon icon={Download01Icon} className="mr-2 size-3.5" />- Download .txt- </Button>- </div>- <div className="flex items-center gap-2 text-ui-11p5 text-muted-foreground">- <span className="truncate">{transcribedName}</span>- <span>·</span>- <span className="truncate">{transcriptModel}</span>- {!transcriptRecord && !transcriptExported && (- <span>· Not saved</span>- )}- </div>- <p className="whitespace-pre-wrap text-sm leading-relaxed text-foreground">- {transcript}- </p>- </>- ) : transcriptError ? (- <div className="flex flex-col gap-1" role="alert">- <p className="text-ui-13 font-medium text-destructive">- Could not transcribe {transcribedName ?? "that audio"}.- </p>- <p className="text-ui-13 text-muted-foreground">{transcriptError}</p>- </div>- ) : busy !== "transcribing" ? (- <p className="text-ui-13 text-muted-foreground">- Record or upload audio to transcribe. Completed transcripts are saved- to history.- </p>- ) : null}- </div>- <div className="shrink-0 pt-4">- <TranscriptGallery- autoSelect={!transcript && !transcribedName && busy === null}- active={active && mode === "transcribe"}- currentId={transcriptRecord?.id ?? null}- latest={transcriptRecord}- canSelect={confirmTranscriptReplacement}- onSelect={(record) => {- transcriptVersion.current += 1;- setTranscript(record.text);- setTranscribedName(record.title);- setTranscriptModel(record.model);- setTranscriptRecord(record);- setTranscriptError(null);- setTranscriptExported(false);- setTranscriptionStartedAt(null);- }}- onDelete={(ids) => {- if (- transcriptRecord &&- (ids === null- ? !transcriptRecord.archived- : ids.includes(transcriptRecord.id))- )- clearTranscript();- }}- />- </div>+ <TranscribeOutput+ transcriptionStartedAt={transcriptionStartedAt}+ transcriptionFinishedAt={transcriptionFinishedAt}+ transcriptionStopping={transcriptionStopping}+ transcriptionProgress={transcriptionProgress}+ setTranscriptionStopping={setTranscriptionStopping}+ transcriptionAbort={transcriptionAbort}+ transcript={transcript}+ handleCopyTranscript={handleCopyTranscript}+ handleDownloadTranscript={handleDownloadTranscript}+ transcribedName={transcribedName}+ transcriptModel={transcriptModel}+ transcriptRecord={transcriptRecord}+ transcriptExported={transcriptExported}+ transcriptError={transcriptError}+ busy={busy}+ active={active}+ mode={mode}+ confirmTranscriptReplacement={confirmTranscriptReplacement}+ transcriptVersion={transcriptVersion}+ setTranscript={setTranscript}+ setTranscribedName={setTranscribedName}+ setTranscriptModel={setTranscriptModel}+ setTranscriptRecord={setTranscriptRecord}+ setTranscriptError={setTranscriptError}+ setTranscriptExported={setTranscriptExported}+ setTranscriptionStartedAt={setTranscriptionStartedAt}+ clearTranscript={clearTranscript}+ /></div>) : (<div className="flex min-h-0 flex-1 flex-col gap-4 p-6 px-10 @[50rem]:pt-[calc(60px*var(--ui-space-scale,1))]">- <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-4">- {selectedClip ? (- <div className="flex w-full max-w-xl flex-col gap-3">- <p className="line-clamp-2 text-ui-13 text-muted-foreground">- {selectedClip.prompt}- </p>- {/* Auth-protected bytes, so mount a fresh player only once this clip's object URL exists: reusing- one media element while src is changing left History switches showing broken controls. */}- {selectedClipSrc ? (- <audio- key={selectedClip.id}- controls={true}- src={selectedClipSrc}- className="w-full"- />- ) : (- <div- role="status"- className="flex h-12 w-full items-center justify-center rounded-md border border-border text-ui-12 text-muted-foreground"- >- Loading audio…- </div>- )}- <div className="flex items-center gap-2 text-ui-11p5 text-muted-foreground">- <span title={selectedClip.model}>{audioModelLabel(selectedClip.model)}</span>- <span>·</span>- <span>{formatClipDuration(selectedClip.duration_s)}</span>- <span className="flex-1" />- <Button- variant="ghost"- size="sm"- aria-label="Download audio clip"- disabled={!srcById[selectedClip.id]}- onClick={() => handleDownloadClip(selectedClip)}- >- <HugeiconsIcon- icon={Download01Icon}- className="size-3.5"- />- </Button>- <Button- variant="ghost"- size="sm"- aria-label="Delete audio clip"- onClick={() => void handleDeleteClip(selectedClip.id)}- >- <HugeiconsIcon- icon={Delete02Icon}- className="size-3.5"- />- </Button>- </div>- </div>- ) : fallbackClip ? (- <div className="flex w-full max-w-xl flex-col gap-3">- <p className="line-clamp-2 text-ui-13 text-muted-foreground">- {fallbackClip.prompt}- </p>- <audio- controls={true}- src={fallbackClip.url}- className="w-full"- />- <div className="flex items-center gap-2 text-ui-11p5 text-muted-foreground">- <span>- {audioModelLabel(fallbackClip.model)}- {fallbackClip.saved- ? " · saved, waiting for the gallery"- : " · not saved to the gallery"}- </span>- <span className="flex-1" />- <Button- variant="outline"- size="sm"- onClick={handleDownloadFallbackClip}- >- <HugeiconsIcon- icon={Download01Icon}- className="size-3.5"- />- Download WAV- </Button>- </div>- </div>+ {(() => {+ const outputProps = {+ workflow: ttsWorkflow,+ peaksById,+ sendHandlersFor,+ pending:+ busy === "generating" && generationPresentation+ ? {+ title:+ prompt.trim() ||+ audioInstructions.trim() ||+ (ttsWorkflow === "music" ? "New track" : "New clip"),+ status: generationPresentation.status,+ elapsedSeconds,+ canStop: generationPresentation.canStop,+ onStop: handleStopGeneration,+ }+ : null,+ clips: visibleClips,+ selectedClip,+ selectedClipSrc,+ srcById,+ handleDownloadClip,+ handleDeleteClip,+ fallbackClip: pageFallbackClip,+ handleDownloadFallbackClip,+ handleClearGallery: handleClearWorkflowGallery,+ historyReorder,+ hasMore,+ loadMore: loadMoreVisible,+ selectedId,+ selectClip,+ handleTogglePin,+ active,+ handleArchiveClip,+ handleDownloadClipById,+ onUseTextAgain: handleUseTextAgain,+ handleCopyPrompt,+ freshClipId,+ onFreshClipFocused: clearFreshClip,+ announcement,+ };+ return ttsWorkflow === "music" ? (+ <MusicOutput {...outputProps} modelReady={pageModelLoaded} />) : (- <p className="text-ui-13 text-muted-foreground">- Generated speech lands here. Load a TTS model, type a- sentence, and press Generate.- </p>- )}- </div>- {clips.length > 0 ? (- <div className="flex shrink-0 flex-col gap-2">- <div className="flex items-center justify-between">- <span className="text-ui-11p5 font-medium text-muted-foreground">- History- </span>- <Button- variant="ghost"- size="sm"- onClick={() => void handleClearGallery()}- >- Clear all- </Button>- </div>- <div- {...historyReorder.stripProps}- // py-1 keeps the first and last drop lines inside the scroller.- className="hover-scrollbar flex max-h-40 flex-col gap-1 overflow-y-auto py-1"- onScroll={(event) => {- const el = event.currentTarget;- if (- hasMore &&- el.scrollTop + el.clientHeight >= el.scrollHeight - 40- ) {- void loadMore();- }- }}- >- {clips.map((clip) => (- // Shell, not a button: the pin badge and dots menu are buttons and cannot nest.- <div- key={clip.id}- {...historyReorder.tileProps(clip.id)}- className={cn(- "group relative flex items-center gap-1 rounded-md pr-1 transition-colors hover:bg-muted",- clip.id === selectedId && "bg-muted",- historyReorder.draggingId === clip.id && "opacity-40",- )}- >- {historyReorder.cue?.id === clip.id && (- <StripDropLine- axis="y"- edge={historyReorder.cue.edge}- />- )}- <button- type="button"- onClick={() => selectClip(clip.id)}- aria-current={- clip.id === selectedId ? "true" : undefined- }- className="flex min-w-0 flex-1 items-center gap-2 px-2 py-1.5 text-left text-ui-13"- >- <HugeiconsIcon- icon={AudioWave01Icon}- className="size-3.5 shrink-0 text-muted-foreground"- />- <span className="min-w-0 flex-1 truncate">- {clip.prompt}- </span>- <span className="shrink-0 text-ui-11p5 text-muted-foreground">- {formatClipDuration(clip.duration_s)}- </span>- </button>- {clip.pinned && (- <GalleryPinBadge- noun="clip"- className="static shrink-0"- onUnpin={() => void handleTogglePin(clip.id, false)}- />- )}- <GalleryItemMenu- variant="row"- noun="clip"- active={active}- pinned={Boolean(clip.pinned)}- archived={false}- onTogglePin={() =>- void handleTogglePin(clip.id, !clip.pinned)- }- onToggleArchive={() => void handleArchiveClip(clip.id)}- onDelete={() => void handleDeleteClip(clip.id)}- onDownload={() => void handleDownloadClipById(clip)}- onAddToProject={(projectId) =>- addAudioClipToProject(clip.id, projectId)- }- leadingItems={- <>- <DropdownMenuItem- onClick={() => {- if (transitionMode("speak")) setPrompt(clip.prompt);- }}- >- <HugeiconsIcon- icon={SparklesIcon}- strokeWidth={1.75}- className="size-icon"- />- Use text again- </DropdownMenuItem>- <DropdownMenuItem- onClick={() => void handleCopyPrompt(clip.prompt)}- >- <HugeiconsIcon- icon={Copy01Icon}- strokeWidth={1.75}- className="size-icon"- />- Copy text- </DropdownMenuItem>- </>- }- />- </div>- ))}- </div>- </div>- ) : null}+ <SpeakOutput {...outputProps} modelReady={pageModelLoaded} />+ );+ })()}</div>)}</div>diff --git a/studio/frontend/src/features/audio/audio-workspace-constants.ts b/studio/frontend/src/features/audio/audio-workspace-constants.tsnew file mode 100644index 00000000000..5f473dd50cf--- /dev/null+++ b/studio/frontend/src/features/audio/audio-workspace-constants.ts@@ -0,0 +1,15 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export const PAGE_SIZE = 50;+// The list route clamps a page to 200, so asking for more silently gets 200 back.+export const MAX_PAGE_SIZE = 200;+// Mirrors the STT sidecar's _MAX_AUDIO_SECONDS and STT_AUDIO_B64_MAX_CHARS.+export const RECORDING_MAX_SECONDS = 30 * 60;+// STT_AUDIO_RAW_MAX_BYTES in utils/upload_limits.py. A larger client cap let a dense codec build+export const RECORDING_MAX_BYTES = 25 * 1024 * 1024;+export const RECORDING_CHUNK_MS = 1000;+export const TTS_MAX_TOKENS = 8192;+// Max tokens caps output only and the prompt shares the context, so TTS_MAX_TOKENS itself is unreachable.+export const TTS_PROMPT_CONTEXT_RESERVE = 2048;+export const CLIP_BLOB_BUDGET_BYTES = 64 * 1024 * 1024;diff --git a/studio/frontend/src/features/audio/audio-workspace-utils.ts b/studio/frontend/src/features/audio/audio-workspace-utils.tsnew file mode 100644index 00000000000..f001aa06c16--- /dev/null+++ b/studio/frontend/src/features/audio/audio-workspace-utils.ts@@ -0,0 +1,43 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import {+ AUDIO_CPP_MUSIC_AUDIO_TYPE,+ AUDIO_CPP_TTS_AUDIO_TYPE,+ audioCppDisplayName,+ isAudioCppFolderId,+} from "./audio-cpp-catalog";++export function audioModelLabel(id: string): string {+ if (isAudioCppFolderId(id)) return audioCppDisplayName(id);+ if (!/^(?:[a-zA-Z]:[\\/]|[\\/]|~)/.test(id)) return id;+ const leaf = id.split(/[\\/]/).filter(Boolean).pop() ?? id;+ return leaf.replace(/_\d{10,}$/, "");+}++export function loadedAudioKind(audioType: string | null | undefined): string {+ if (audioType === AUDIO_CPP_TTS_AUDIO_TYPE) return "speech";+ if (audioType === AUDIO_CPP_MUSIC_AUDIO_TYPE) return "music";+ return audioType ?? "audio";+}++export function deviceSizeBytes(label: string): number {+ const match = label.trim().match(/^(\d+(?:\.\d+)?)\s*(MB|GB)$/i);+ if (!match) return 0;+ const value = Number(match[1]);+ return value * (match[2].toUpperCase() === "GB" ? 1024 ** 3 : 1024 ** 2);+}++export type CreateMode = "speak" | "transcribe";+export type RemoteCodeApproval = {+ trustRemoteCode: true;+ approvedRemoteCodeFingerprint: string | null;+};++export function formatClipDuration(seconds: number): string {+ if (!Number.isFinite(seconds) || seconds <= 0) return "0:00";+ const whole = Math.round(seconds);+ const minutes = Math.floor(whole / 60);+ const rest = whole % 60;+ return `${minutes}:${String(rest).padStart(2, "0")}`;+}diff --git a/studio/frontend/src/features/audio/components/clip-card.tsx b/studio/frontend/src/features/audio/components/clip-card.tsxnew file mode 100644index 00000000000..afdbc53d547--- /dev/null+++ b/studio/frontend/src/features/audio/components/clip-card.tsx@@ -0,0 +1,177 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { Download01Icon, SentIcon, StopIcon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import type { ReactNode } from "react";+import { Button } from "@/components/ui/button";+import { Card } from "@/components/ui/card";+import {+ DropdownMenuItem,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+} from "@/components/ui/dropdown-menu";+import { formatRelativeShort } from "@/features/hub/lib/format";+import { audioModelLabel, formatClipDuration } from "../audio-workspace-utils";+import { AUDIO_WORKFLOWS, type AudioWorkflowId } from "../workflows";+import { Waveform } from "./waveform";++export type ClipSendHandlers = Partial<Record<AudioWorkflowId, () => void>>;++export function ClipSendToMenu({+ current,+ handlers,+}: {+ current: AudioWorkflowId;+ handlers: ClipSendHandlers;+}) {+ const targets = AUDIO_WORKFLOWS.filter(+ (tab) => tab.id !== current && handlers[tab.id],+ );+ if (targets.length === 0) return null;+ return (+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <HugeiconsIcon+ icon={SentIcon}+ strokeWidth={1.75}+ className="size-icon"+ />+ Send to+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent>+ {targets.map((tab) => (+ <DropdownMenuItem key={tab.id} onClick={handlers[tab.id]}>+ <HugeiconsIcon+ icon={tab.icon}+ strokeWidth={1.75}+ className="size-icon"+ />+ {tab.label}+ </DropdownMenuItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ );+}++const CARD_CLASS = "w-full max-w-xl gap-3 px-5 py-4";++/** Never autoplays; a clip a run just made takes focus on its play button once. */+export function ClipCard({+ title,+ model,+ createdAt,+ durationS,+ src,+ peaks,+ onDownload,+ menu,+ status,+ focusOnMount = false,+ onFocused,+}: {+ title: string;+ model: string;+ createdAt?: string;+ durationS: number | null;+ src: string | null;+ peaks: readonly number[] | null;+ onDownload: (() => void) | null;+ menu?: ReactNode;+ status?: string;+ focusOnMount?: boolean;+ onFocused?: () => void;+}) {+ const focusPlay = (element: HTMLDivElement | null) => {+ if (!(element && focusOnMount && src)) return;+ element.querySelector<HTMLButtonElement>("button")?.focus();+ onFocused?.();+ };+ return (+ <Card size="sm" className={CARD_CLASS}>+ <div className="flex items-start gap-2">+ <div className="grid min-w-0 flex-1 gap-1">+ <p className="line-clamp-2 text-ui-13 text-foreground">{title}</p>+ <p className="truncate text-ui-11p5 text-muted-foreground">+ <span title={model}>{audioModelLabel(model)}</span>+ {createdAt ? ` · ${formatRelativeShort(createdAt)}` : ""}+ {status ? ` · ${status}` : ""}+ </p>+ </div>+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label="Download audio clip"+ disabled={!onDownload}+ onClick={onDownload ?? undefined}+ className="shrink-0 rounded-full"+ >+ <HugeiconsIcon icon={Download01Icon} className="size-3.5" />+ </Button>+ {menu}+ </div>+ <div ref={focusPlay}>+ <Waveform+ peaks={peaks}+ durationS={durationS}+ src={src}+ label={title || "audio clip"}+ />+ </div>+ </Card>+ );+}++export function PendingClipCard({+ title,+ status,+ elapsedSeconds,+ canStop,+ onStop,+}: {+ title: string;+ status: string;+ elapsedSeconds: number | null;+ canStop: boolean;+ onStop: () => void;+}) {+ return (+ <Card size="sm" className={CARD_CLASS} aria-busy="true">+ <div className="flex items-start gap-2">+ <div className="grid min-w-0 flex-1 gap-1">+ <p className="line-clamp-2 text-ui-13 text-muted-foreground">+ {title}+ </p>+ {/* No live region: the footer already announces progress. */}+ <p className="text-ui-11p5 text-muted-foreground">+ {status}+ {elapsedSeconds !== null ? (+ <span className="ml-1.5 font-mono tabular-nums">+ {formatClipDuration(elapsedSeconds)}+ </span>+ ) : null}+ </p>+ </div>+ {canStop ? (+ <Button+ variant="outline"+ size="sm"+ onClick={onStop}+ className="shrink-0 hover:bg-muted"+ >+ <HugeiconsIcon icon={StopIcon} className="size-3.5" />+ Stop+ </Button>+ ) : null}+ </div>+ <Waveform+ peaks={null}+ durationS={null}+ src={null}+ label="clip in progress"+ />+ </Card>+ );+}diff --git a/studio/frontend/src/features/audio/components/field.tsx b/studio/frontend/src/features/audio/components/field.tsxnew file mode 100644index 00000000000..2c08bcee6af--- /dev/null+++ b/studio/frontend/src/features/audio/components/field.tsx@@ -0,0 +1,33 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import type { ReactNode } from "react";++export function Field({+ label,+ hint,+ htmlFor,+ children,+}: {+ label: string;+ hint?: string;+ htmlFor: string;+ children: ReactNode;+}) {+ return (+ <div className="grid gap-1.5">+ <label+ className="text-ui-13 font-medium text-foreground"+ htmlFor={htmlFor}+ >+ {label}+ </label>+ {children}+ {hint ? (+ <p className="text-ui-11p5 leading-snug text-muted-foreground">+ {hint}+ </p>+ ) : null}+ </div>+ );+}diff --git a/studio/frontend/src/features/audio/components/instructions-fields.tsx b/studio/frontend/src/features/audio/components/instructions-fields.tsxnew file mode 100644index 00000000000..525f2f5c7cc--- /dev/null+++ b/studio/frontend/src/features/audio/components/instructions-fields.tsx@@ -0,0 +1,86 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { Input } from "@/components/ui/input";+import { Textarea } from "@/components/ui/textarea";+import type { NativeAudioInstructionsKind } from "../audio-page-policy";+import { Field } from "./field";++export function InstructionsField({+ instructionsKind,+ musicNeedsDescription,+ audioInstructions,+ setAudioInstructions,+}: {+ instructionsKind: NativeAudioInstructionsKind;+ musicNeedsDescription: boolean;+ audioInstructions: string;+ setAudioInstructions: (value: string) => void;+}) {+ return (+ <Field+ label={+ instructionsKind === "music"+ ? "Music description"+ : instructionsKind === "scene"+ ? "Scene description"+ : instructionsKind === "voice"+ ? "Voice or style description"+ : "Style instructions"+ }+ hint={+ instructionsKind === "music"+ ? musicNeedsDescription+ ? "Describe genre, tempo, mood, vocals, and arrangement. This model requires it separately from the lyrics."+ : "Optional genre, tempo, mood, vocals, and arrangement. Without it, the text above is used as the prompt."+ : instructionsKind === "scene"+ ? "Optional Higgs TTS 2 scene guidance such as room acoustics, recording conditions, or background ambience."+ : instructionsKind === "voice"+ ? "Optional. Used by Qwen3-TTS VoiceDesign, Qwen3-TTS CustomVoice and VoxCPM2; other models ignore it."+ : "Optional MOSS Local guidance such as speaking style, emotion, pace, or delivery."+ }+ htmlFor="audio-instructions"+ >+ <Textarea+ id="audio-instructions"+ value={audioInstructions}+ onChange={(event) =>+ setAudioInstructions(event.target.value)+ }+ placeholder={+ instructionsKind === "music"+ ? "Acoustic pop, 96 BPM, warm female lead, fingerpicked guitar and soft piano…"+ : instructionsKind === "scene"+ ? "Close-mic studio recording in a quiet, softly treated room…"+ : instructionsKind === "voice"+ ? "A warm, low female voice, speaking slowly and calmly…"+ : "Warm, measured delivery with a calm conversational tone…"+ }+ className="min-h-24"+ />+ </Field>+ );+}++export function MossLanguageField({+ audioLanguage,+ setAudioLanguage,+}: {+ audioLanguage: string;+ setAudioLanguage: (value: string) => void;+}) {+ return (+ <Field+ label="Language"+ htmlFor="audio-language"+ hint="Optional, but MOSS Local v1.5 recommends a language tag when known (for example English, Arabic, or French)."+ >+ <Input+ id="audio-language"+ value={audioLanguage}+ onChange={(event) => setAudioLanguage(event.target.value)}+ placeholder="English"+ />+ </Field>+ );+}diff --git a/studio/frontend/src/features/audio/components/waveform-decode.ts b/studio/frontend/src/features/audio/components/waveform-decode.tsnew file mode 100644index 00000000000..c4d57c4b941--- /dev/null+++ b/studio/frontend/src/features/audio/components/waveform-decode.ts@@ -0,0 +1,32 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { computePeaks } from "./waveform-peaks";++const DECODE_MAX_BYTES = 60 * 1024 * 1024;++/** Decodes the Blob itself: fetching a blob: URL is blocked by the page's connect-src. */+export async function decodePeaks(+ blob: Blob,+): Promise<{ peaks: number[] | null; durationS: number | null }> {+ if (blob.size > DECODE_MAX_BYTES) return { peaks: null, durationS: null };+ const Offline =+ window.OfflineAudioContext ||+ (+ window as unknown as {+ webkitOfflineAudioContext?: typeof OfflineAudioContext;+ }+ ).webkitOfflineAudioContext;+ if (!Offline) return { peaks: null, durationS: null };+ try {+ const context = new Offline(1, 1, 22050);+ const buffer = await context.decodeAudioData(await blob.arrayBuffer());+ const channels = Array.from(+ { length: buffer.numberOfChannels },+ (_, index) => buffer.getChannelData(index),+ );+ return { peaks: computePeaks(channels), durationS: buffer.duration };+ } catch {+ return { peaks: null, durationS: null };+ }+}diff --git a/studio/frontend/src/features/audio/components/waveform-peaks.ts b/studio/frontend/src/features/audio/components/waveform-peaks.tsnew file mode 100644index 00000000000..b3db426f487--- /dev/null+++ b/studio/frontend/src/features/audio/components/waveform-peaks.ts@@ -0,0 +1,49 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Free of app imports so the node test runner can load it directly.++export const WAVEFORM_BARS = 72;++/** Per-bar peak across channels, normalised so the loudest bar is 1; silence stays 0. */+export function computePeaks(+ channels: readonly Float32Array[],+ bars: number = WAVEFORM_BARS,+): number[] {+ const count = Math.max(1, Math.floor(bars));+ const length = channels.reduce(+ (longest, channel) => Math.max(longest, channel.length),+ 0,+ );+ const peaks = new Array<number>(count).fill(0);+ if (length === 0) return peaks;+ for (let bar = 0; bar < count; bar += 1) {+ const start = Math.floor((bar * length) / count);+ const end = Math.max(start + 1, Math.floor(((bar + 1) * length) / count));+ let peak = 0;+ for (const channel of channels) {+ const stop = Math.min(end, channel.length);+ for (let index = start; index < stop; index += 1) {+ const value = Math.abs(channel[index]);+ if (value > peak) peak = value;+ }+ }+ peaks[bar] = Number.isFinite(peak) ? peak : 0;+ }+ const loudest = Math.max(...peaks);+ // Below about -60 dBFS everywhere: treat it as silence.+ if (loudest < 0.001) return peaks.map(() => 0);+ return peaks.map((peak) => Math.min(1, peak / loudest));+}++export function formatSeconds(seconds: number | null | undefined): string {+ if (seconds === null || seconds === undefined || !Number.isFinite(seconds))+ return "0:00";+ const whole = Math.max(0, Math.round(seconds));+ const hours = Math.floor(whole / 3600);+ const minutes = Math.floor((whole % 3600) / 60);+ const rest = String(whole % 60).padStart(2, "0");+ return hours > 0+ ? `${hours}:${String(minutes).padStart(2, "0")}:${rest}`+ : `${minutes}:${rest}`;+}diff --git a/studio/frontend/src/features/audio/components/waveform.tsx b/studio/frontend/src/features/audio/components/waveform.tsxnew file mode 100644index 00000000000..82b82c6d872--- /dev/null+++ b/studio/frontend/src/features/audio/components/waveform.tsx@@ -0,0 +1,170 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { Button } from "@/components/ui/button";+import { cn } from "@/lib/utils";+import { PauseIcon, PlayIcon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import { useCallback, useEffect, useRef, useState } from "react";+import { WAVEFORM_BARS, formatSeconds } from "./waveform-peaks";++const SEEK_STEP_SECONDS = 5;++/** The position is also spoken, so colour never carries it alone. */+export function Waveform({+ peaks,+ durationS,+ src,+ label,+ className,+}: {+ /** 0..1; null draws a flat placeholder while decoding. */+ peaks: readonly number[] | null;+ durationS: number | null;+ src: string | null;+ label: string;+ className?: string;+}) {+ const audioRef = useRef<HTMLAudioElement | null>(null);+ const [playing, setPlaying] = useState(false);+ const [position, setPosition] = useState(0);+ const [mediaDuration, setMediaDuration] = useState<number | null>(null);+ const duration =+ durationS && durationS > 0 ? durationS : (mediaDuration ?? 0);+ const fraction = duration > 0 ? Math.min(1, position / duration) : 0;+ const bars = peaks && peaks.length > 0 ? peaks : null;+ const count = bars?.length ?? WAVEFORM_BARS;++ useEffect(() => {+ setPlaying(false);+ setPosition(0);+ setMediaDuration(null);+ if (src === null) audioRef.current?.pause();+ }, [src]);++ const toggle = useCallback(() => {+ const audio = audioRef.current;+ if (!(audio && src)) return;+ if (audio.paused) {+ audio.play().catch(() => setPlaying(false));+ } else {+ audio.pause();+ }+ }, [src]);++ const seekTo = useCallback(+ (seconds: number) => {+ const audio = audioRef.current;+ if (!(audio && src) || duration <= 0) return;+ const next = Math.min(duration, Math.max(0, seconds));+ audio.currentTime = next;+ setPosition(next);+ },+ [src, duration],+ );++ return (+ <div className={cn("flex items-center gap-2", className)}>+ <Button+ type="button"+ variant="muted"+ size="icon"+ className="size-[calc(32px*var(--ui-space-scale,1))] shrink-0"+ aria-label={playing ? `Pause ${label}` : `Play ${label}`}+ disabled={!src}+ onClick={toggle}+ >+ <HugeiconsIcon+ icon={playing ? PauseIcon : PlayIcon}+ className="size-3.5"+ />+ </Button>+ <div+ role="slider"+ tabIndex={src ? 0 : -1}+ aria-label={`${label} playback position`}+ aria-valuemin={0}+ aria-valuemax={Math.round(duration)}+ aria-valuenow={Math.round(position)}+ aria-valuetext={`${formatSeconds(position)} of ${formatSeconds(duration)}`}+ aria-disabled={!src}+ className="relative h-[calc(32px*var(--ui-space-scale,1))] min-w-0 flex-1 cursor-pointer rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ onKeyDown={(event) => {+ if (event.key === " ") {+ event.preventDefault();+ toggle();+ } else if (event.key === "ArrowRight") {+ event.preventDefault();+ seekTo(position + SEEK_STEP_SECONDS);+ } else if (event.key === "ArrowLeft") {+ event.preventDefault();+ seekTo(position - SEEK_STEP_SECONDS);+ } else if (event.key === "Home") {+ event.preventDefault();+ seekTo(0);+ }+ }}+ onClick={(event) => {+ const box = event.currentTarget.getBoundingClientRect();+ if (box.width <= 0) return;+ seekTo(((event.clientX - box.left) / box.width) * duration);+ }}+ >+ <svg+ aria-hidden="true"+ className="size-full"+ viewBox={`0 0 ${count * 3} 32`}+ preserveAspectRatio="none"+ >+ {Array.from({ length: count }, (_, index) => {+ const peak = bars ? (bars[index] ?? 0) : 0;+ const height = Math.max(2, peak * 30);+ const played = (index + 0.5) / count <= fraction;+ return (+ <rect+ // biome-ignore lint/suspicious/noArrayIndexKey: bars are positional and never reorder.+ key={index}+ x={index * 3 + 0.5}+ y={(32 - height) / 2}+ width={2}+ height={height}+ rx={1}+ className={cn(+ "fill-current",+ played && position > 0+ ? "text-foreground"+ : "text-muted-foreground",+ bars ? "opacity-100" : "opacity-40",+ )}+ />+ );+ })}+ </svg>+ </div>+ <span className="shrink-0 font-mono text-ui-11p5 tabular-nums text-muted-foreground">+ {position > 0 ? `${formatSeconds(position)} / ` : ""}+ {formatSeconds(duration)}+ </span>+ {src ? (+ // biome-ignore lint/a11y/useMediaCaption: voice references have no caption track; the clip's text is shown beside it.+ <audio+ ref={audioRef}+ src={src}+ preload="metadata"+ className="hidden"+ onPlay={() => setPlaying(true)}+ onPause={() => setPlaying(false)}+ onEnded={() => {+ setPlaying(false);+ setPosition(0);+ }}+ onTimeUpdate={(event) => setPosition(event.currentTarget.currentTime)}+ onLoadedMetadata={(event) => {+ const value = event.currentTarget.duration;+ if (Number.isFinite(value)) setMediaDuration(value);+ }}+ />+ ) : null}+ </div>+ );+}diff --git a/studio/frontend/src/features/audio/components/workflow-title-menu.tsx b/studio/frontend/src/features/audio/components/workflow-title-menu.tsxnew file mode 100644index 00000000000..98a7bee9afe--- /dev/null+++ b/studio/frontend/src/features/audio/components/workflow-title-menu.tsx@@ -0,0 +1,84 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { HugeiconsIcon } from "@hugeicons/react";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { ChevronDownStandardIcon } from "@/lib/chevron-icons";+import {+ AUDIO_WORKFLOWS,+ type AudioWorkflowId,+ isAudioWorkflowId,+} from "../workflows";++export function WorkflowTitleMenu({+ workflow,+ onSelect,+}: {+ workflow: AudioWorkflowId;+ onSelect: (workflow: AudioWorkflowId) => void;+}) {+ const current =+ AUDIO_WORKFLOWS.find((tab) => tab.id === workflow) ?? AUDIO_WORKFLOWS[0];+ return (+ <h2 className="font-heading text-xl font-medium leading-none text-foreground">+ <DropdownMenu>+ <DropdownMenuTrigger+ data-tour="audio-mode"+ aria-label={`${current.heading}, switch Audio page`}+ className="-mx-2 -my-1 flex max-w-full items-center gap-2 rounded-full px-2 py-1 outline-none transition-colors duration-150 hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring data-[state=open]:bg-accent"+ >+ <HugeiconsIcon+ icon={current.icon}+ className="size-[calc(18px*var(--ui-space-scale,1))] shrink-0"+ />+ <span className="truncate">{current.heading}</span>+ <HugeiconsIcon+ icon={ChevronDownStandardIcon}+ strokeWidth={1.5}+ className="size-[calc(14px*var(--ui-space-scale,1))] shrink-0 text-muted-foreground"+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="start"+ sideOffset={6}+ className="w-[min(calc(320px*var(--ui-space-scale,1)),calc(100vw-32px))]"+ >+ <DropdownMenuRadioGroup+ value={current.id}+ onValueChange={(value) => {+ if (isAudioWorkflowId(value)) onSelect(value);+ }}+ >+ {AUDIO_WORKFLOWS.map((tab) => (+ <DropdownMenuRadioItem+ key={tab.id}+ value={tab.id}+ textValue={tab.label}+ className="items-start"+ >+ <HugeiconsIcon+ icon={tab.icon}+ className="mt-0.5 size-[calc(16px*var(--ui-space-scale,1))]"+ />+ <span className="grid min-w-0 gap-0.5">+ <span className="text-ui-13 font-medium text-foreground">+ {tab.label}+ </span>+ <span className="text-ui-11p5 leading-snug text-muted-foreground">+ {tab.hint}+ </span>+ </span>+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ </h2>+ );+}diff --git a/studio/frontend/src/features/audio/hooks/audio-host-state.ts b/studio/frontend/src/features/audio/hooks/audio-host-state.tsnew file mode 100644index 00000000000..e0a191c1e61--- /dev/null+++ b/studio/frontend/src/features/audio/hooks/audio-host-state.ts@@ -0,0 +1,27 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import type { Dispatch, RefObject, SetStateAction } from "react";+import type { InferenceStatusResponse } from "@/features/chat";+import type { AudioBusy, AudioGenerationPhase } from "../audio-page-policy";+import type { CreateMode } from "../audio-workspace-utils";++export interface AudioHostState {+ active: boolean;+ activeRef: RefObject<boolean>;+ busy: AudioBusy;+ busyRef: RefObject<AudioBusy>;+ setBusy: Dispatch<SetStateAction<AudioBusy>>;+ mode: CreateMode;+ setMode: Dispatch<SetStateAction<CreateMode>>;+ modeRef: RefObject<CreateMode>;+ generationPhaseRef: RefObject<AudioGenerationPhase>;+ updateGenerationPhase: (nextPhase: AudioGenerationPhase) => void;+ generateAbort: RefObject<AbortController | null>;+ handleStopGeneration: () => void;+ status: InferenceStatusResponse | null;+ refreshStatus: () => Promise<void>;+ audioDevice: string;+ isMac: boolean;+ setAdvancedOpen: (next: boolean) => void;+}diff --git a/studio/frontend/src/features/audio/hooks/use-audio-gallery.tsx b/studio/frontend/src/features/audio/hooks/use-audio-gallery.tsxnew file mode 100644index 00000000000..436a9a17886--- /dev/null+++ b/studio/frontend/src/features/audio/hooks/use-audio-gallery.tsx@@ -0,0 +1,630 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useSettingsDialogStore } from "@/features/settings";+import { useStripReorder } from "@/hooks/use-strip-reorder";+import { BlobUrlCache } from "@/lib/blob-url-cache";+import { copyToClipboard } from "@/lib/copy-to-clipboard";+import { loadGalleryUntil } from "@/lib/gallery-deep-link";+import {+ applyPin,+ moveGalleryItem,+ pinnedOrder,+ restorePinOrder,+ scopedMoveAfterId,+ serializeById,+ sortGalleryItems,+ subscribeGalleryChanged,+} from "@/lib/gallery-flags";+import { toast } from "@/lib/toast";+import {+ type AudioGalleryClip,+ audioGalleryCursor,+ type AudioGalleryCursor,+ clearAudioGallery,+ deleteAudioClip,+ fetchClipObjectUrl,+ listAudioGallery,+ moveAudioClip,+ setAudioClipFlags,+} from "../api";+import { fetchGalleryWindow, mergeGalleryPage } from "../audio-page-policy";+import {+ CLIP_BLOB_BUDGET_BYTES,+ MAX_PAGE_SIZE,+ PAGE_SIZE,+} from "../audio-workspace-constants";+import { decodePeaks } from "../components/waveform-decode";+import { clipWorkflow } from "../workflows";+import type { AudioHostState } from "./audio-host-state";++// Module scope so a tab switch re-renders the gallery instantly.+export const galleryCache: {+ clips: AudioGalleryClip[];+ hasMore: boolean;+ nextCursor: AudioGalleryCursor | null;+ selectedId: string | null;+ srcById: BlobUrlCache;+ peaksById: Map<string, number[] | null>;+} = {+ clips: [],+ hasMore: false,+ nextCursor: null,+ selectedId: null,+ srcById: new BlobUrlCache(CLIP_BLOB_BUDGET_BYTES),+ peaksById: new Map(),+};++export function useAudioGallery({+ active,+}: Pick<AudioHostState, "active">) {+ const [fallbackClip, setFallbackClip] = useState<{+ url: string;+ prompt: string;+ model: string;+ saved: boolean;+ workflow: "speak" | "music";+ } | null>(null);+ const fallbackClipRef = useRef(fallbackClip);+ fallbackClipRef.current = fallbackClip;+ const loadingMoreRef = useRef(false);+ const galleryRefreshGeneration = useRef(0);+ // Pins and moves in flight. A refresh that overlaps one read the old order, so it is dropped and rerun after.+ const orderWrites = useRef({ inFlight: 0, epoch: 0, deferred: false });+ const [clips, setClips] = useState<AudioGalleryClip[]>(galleryCache.clips);+ const [hasMore, setHasMore] = useState(galleryCache.hasMore);+ const [selectedId, setSelectedId] = useState<string | null>(+ galleryCache.selectedId,+ );+ const [srcById, setSrcById] = useState<Record<string, string>>(+ galleryCache.srcById.toRecord(),+ );+ const [peaksById, setPeaksById] = useState<+ ReadonlyMap<string, number[] | null>+ >(galleryCache.peaksById);+ const clipSrcLoads = useRef<Map<string, Promise<void>>>(new Map());++ const ensureClipSrc = useCallback(async (clip: AudioGalleryClip) => {+ const cached = galleryCache.srcById.get(clip.id);+ if (cached) {+ galleryCache.srcById.touch(clip.id);+ return;+ }+ const pending = clipSrcLoads.current.get(clip.id);+ if (pending) return pending;+ const load = (async () => {+ try {+ const fetched = await fetchClipObjectUrl(clip.url);+ // A delete can finish mid-fetch: do not revive its cache entry.+ if (!galleryCache.clips.some((candidate) => candidate.id === clip.id)) {+ URL.revokeObjectURL(fetched.url);+ return;+ }+ galleryCache.srcById.set(clip.id, fetched.url, fetched.bytes);+ galleryCache.srcById.prune(+ galleryCache.selectedId ? [galleryCache.selectedId] : [],+ );+ setSrcById(galleryCache.srcById.toRecord());+ if (!galleryCache.peaksById.has(clip.id)) {+ void decodePeaks(fetched.blob).then(({ peaks }) => {+ galleryCache.peaksById.set(clip.id, peaks);+ setPeaksById(new Map(galleryCache.peaksById));+ });+ }+ } catch {+ toast.error("Could not load this audio clip. Try selecting it again.");+ }+ })();+ clipSrcLoads.current.set(clip.id, load);+ try {+ await load;+ } finally {+ if (clipSrcLoads.current.get(clip.id) === load) {+ clipSrcLoads.current.delete(clip.id);+ }+ }+ }, []);++ const refreshGallery = useCallback(+ async (+ removedId?: string,+ windowSize = PAGE_SIZE,+ ): Promise<AudioGalleryClip[]> => {+ const generation = ++galleryRefreshGeneration.current;+ const writeEpoch = orderWrites.current.epoch;+ const wanted = Math.max(PAGE_SIZE, windowSize);+ try {+ // Capped pages: refetching only the first page shrank a topped-up history.+ const page = await fetchGalleryWindow(+ (limit, cursor) => listAudioGallery(0, limit, cursor),+ audioGalleryCursor,+ wanted,+ MAX_PAGE_SIZE,+ () => generation !== galleryRefreshGeneration.current,+ );+ // The caller's own fetch: a generation whose clip persisted must not be told otherwise.+ if (generation !== galleryRefreshGeneration.current) return page.audio;+ if (orderWrites.current.inFlight > 0 || orderWrites.current.epoch !== writeEpoch) {+ orderWrites.current.deferred = true;+ return page.audio;+ }+ const { clips: merged, stitched } = mergeGalleryPage(+ page.audio,+ galleryCache.clips,+ removedId,+ page.has_more,+ );+ galleryCache.clips = merged;+ if (!stitched) {+ galleryCache.hasMore = page.has_more;+ galleryCache.nextCursor = audioGalleryCursor(page);+ }+ setClips(merged);+ setHasMore(galleryCache.hasMore);+ // Only a saved fallback is the selected clip; an unsaved one is the only copy.+ if (+ fallbackClipRef.current?.saved &&+ galleryCache.selectedId &&+ merged.some((c) => c.id === galleryCache.selectedId)+ ) {+ setFallbackClip(null);+ }+ if (+ galleryCache.selectedId &&+ !merged.some((c) => c.id === galleryCache.selectedId)+ ) {+ galleryCache.selectedId = merged[0]?.id ?? null;+ setSelectedId(galleryCache.selectedId);+ }+ if (+ !galleryCache.selectedId &&+ !fallbackClipRef.current &&+ merged.length > 0+ ) {+ galleryCache.selectedId = merged[0].id;+ setSelectedId(galleryCache.selectedId);+ }+ const selected = merged.find(+ (clip) => clip.id === galleryCache.selectedId,+ );+ if (selected) void ensureClipSrc(selected);+ return merged;+ } catch {+ return galleryCache.clips;+ }+ },+ [ensureClipSrc],+ );++ const loadMore = useCallback(async () => {+ // Dedupe: repeated near-bottom scrolls would append the same page twice.+ if (loadingMoreRef.current) return;+ loadingMoreRef.current = true;+ const refreshGeneration = galleryRefreshGeneration.current;+ const cursor = galleryCache.nextCursor;+ try {+ const page = await listAudioGallery(0, PAGE_SIZE, cursor);+ if (+ refreshGeneration !== galleryRefreshGeneration.current ||+ cursor !== galleryCache.nextCursor+ )+ return;+ galleryCache.nextCursor = audioGalleryCursor(page);+ const known = new Set(galleryCache.clips.map((clip) => clip.id));+ galleryCache.clips = [+ ...galleryCache.clips,+ ...page.audio.filter((clip) => !known.has(clip.id)),+ ];+ galleryCache.hasMore = page.has_more;+ setClips(galleryCache.clips);+ setHasMore(page.has_more);+ } catch {+ } finally {+ loadingMoreRef.current = false;+ }+ }, []);+++ useEffect(() => {+ if (!active) return;+ const refreshWhenVisible = () => {+ if (document.hidden) return;+ void refreshGallery(undefined, galleryCache.clips.length);+ };+ window.addEventListener("focus", refreshWhenVisible);+ document.addEventListener("visibilitychange", refreshWhenVisible);+ return () => {+ window.removeEventListener("focus", refreshWhenVisible);+ document.removeEventListener("visibilitychange", refreshWhenVisible);+ };+ }, [active, refreshGallery]);++ useEffect(() => {+ const clip = clips.find((c) => c.id === selectedId);+ if (clip) void ensureClipSrc(clip);+ }, [clips, selectedId, ensureClipSrc]);++ const selectClip = useCallback(+ (id: string, keepFallback = false) => {+ galleryCache.selectedId = id;+ setSelectedId(id);+ const clip = galleryCache.clips.find((candidate) => candidate.id === id);+ // A clip picked on the other page leaves this page's unsaved clip alone: it may be the only copy.+ const otherPage =+ clip !== undefined &&+ fallbackClipRef.current !== null &&+ clipWorkflow(clip) !== fallbackClipRef.current.workflow;+ if (!keepFallback && !otherPage) setFallbackClip(null);+ if (clip) void ensureClipSrc(clip);+ },+ [ensureClipSrc],+ );++ const dropClip = useCallback((id: string) => {+ galleryCache.srcById.delete(id);+ setSrcById(galleryCache.srcById.toRecord());+ // Drop the row now: refreshGallery swallows a failed GET without setClips, leaving it on a revoked URL.+ galleryCache.clips = galleryCache.clips.filter((clip) => clip.id !== id);+ setClips(galleryCache.clips);+ if (galleryCache.selectedId === id) {+ galleryCache.selectedId = null;+ setSelectedId(null);+ }+ }, []);++ const handleDeleteClip = useCallback(+ async (id: string) => {+ try {+ await deleteAudioClip(id);+ dropClip(id);+ await refreshGallery(id);+ } catch (error) {+ toast.error(+ error instanceof Error ? error.message : "Could not delete the clip.",+ );+ }+ },+ [dropClip, refreshGallery],+ );++ const handleArchiveClip = useCallback(+ async (id: string) => {+ try {+ await setAudioClipFlags(id, { archived: true });+ } catch (error) {+ toast.error(+ error instanceof Error ? error.message : "Could not archive the clip.",+ );+ return;+ }+ dropClip(id);+ await refreshGallery(id);+ const toastId = toast(+ <button+ type="button"+ onClick={() => {+ toast.dismiss(toastId);+ useSettingsDialogStore.getState().openArchivedMedia("audio");+ }}+ className="w-full cursor-pointer text-left"+ >+ You can view archived audio in Settings+ </button>,+ { closeButton: true },+ );+ },+ [dropClip, refreshGallery],+ );++ // The pin state each id was last clicked or dragged into, so a stale response cannot undo a later one.+ const pinAttempt = useRef(new Map<string, number>());+ const pinSeq = useRef(0);++ const beginOrderWrite = useCallback(() => {+ orderWrites.current.inFlight += 1;+ orderWrites.current.epoch += 1;+ }, []);+ const endOrderWrite = useCallback(() => {+ const writes = orderWrites.current;+ writes.inFlight -= 1;+ writes.epoch += 1;+ if (writes.inFlight === 0 && writes.deferred) {+ writes.deferred = false;+ void refreshGallery(undefined, galleryCache.clips.length);+ }+ }, [refreshGallery]);++ const handleTogglePin = useCallback(async (id: string, pinned: boolean) => {+ const orderBefore = pinnedOrder(galleryCache.clips);+ const attempt = (pinSeq.current += 1);+ pinAttempt.current.set(id, attempt);+ galleryCache.clips = applyPin(galleryCache.clips, id, pinned);+ setClips(galleryCache.clips);+ beginOrderWrite();+ try {+ // One queue for pins and moves: the server stamps pins in the order it runs them.+ await serializeById("audio-pin", () => setAudioClipFlags(id, { pinned }));+ // An unpinned clip can belong below the loaded window, so resync it once writes settle.+ if (!pinned && galleryCache.hasMore) orderWrites.current.deferred = true;+ } catch (error) {+ toast.error(+ error instanceof Error ? error.message : "Could not pin the clip.",+ );+ if (pinAttempt.current.get(id) === attempt) {+ galleryCache.clips = pinned+ ? applyPin(galleryCache.clips, id, false)+ : restorePinOrder(galleryCache.clips, id, orderBefore);+ setClips(galleryCache.clips);+ }+ } finally {+ if (pinAttempt.current.get(id) === attempt) pinAttempt.current.delete(id);+ endOrderWrite();+ }+ }, [beginOrderWrite, endOrderWrite]);++ const handleMoveClip = useCallback(+ async (id: string, viewAfterId: string | null) => {+ const moving = galleryCache.clips.find((c) => c.id === id);+ if (!moving) return;+ const workflow = clipWorkflow(moving);+ const afterId = scopedMoveAfterId(+ galleryCache.clips,+ (c) => clipWorkflow(c) === workflow,+ id,+ viewAfterId,+ );+ const next = moveGalleryItem(galleryCache.clips, id, afterId);+ if (next === galleryCache.clips) return;+ const guessedPinned = Boolean(next.find((c) => c.id === id)?.pinned);+ // Takes a pin token too: a pin clicked after this drop must not be undone by its response.+ const attempt = (pinSeq.current += 1);+ pinAttempt.current.set(id, attempt);+ galleryCache.clips = next;+ setClips(next);+ beginOrderWrite();+ try {+ const record = await serializeById("audio-pin", () =>+ moveAudioClip(id, afterId),+ );+ if (pinAttempt.current.get(id) !== attempt) return;+ pinAttempt.current.delete(id);+ const patched = galleryCache.clips.map((c) =>+ c.id === id+ ? { ...c, pinned: record.pinned, order_at: record.order_at }+ : c,+ );+ galleryCache.clips =+ Boolean(record.pinned) === guessedPinned+ ? patched+ : sortGalleryItems(patched);+ setClips(galleryCache.clips);+ } catch (error) {+ toast.error(+ error instanceof Error ? error.message : "Could not move the clip.",+ );+ if (pinAttempt.current.get(id) === attempt) pinAttempt.current.delete(id);+ orderWrites.current.deferred = true;+ } finally {+ endOrderWrite();+ }+ },+ [beginOrderWrite, endOrderWrite],+ );+ const historyReorder = useStripReorder(+ (id, afterId) => void handleMoveClip(id, afterId),+ { axis: "y" },+ );++ // Stays mounted, so refresh the whole loaded window after a Settings archive restore.+ useEffect(+ () =>+ subscribeGalleryChanged("audio", () => {+ void refreshGallery(undefined, galleryCache.clips.length);+ }),+ [refreshGallery],+ );++ const handleClearGallery = useCallback(async (workflow?: "speak" | "music") => {+ try {+ await clearAudioGallery(workflow);+ if (workflow) {+ const cleared = new Set(+ galleryCache.clips+ .filter((clip) => clipWorkflow(clip) === workflow)+ .map((clip) => clip.id),+ );+ for (const id of cleared) galleryCache.srcById.delete(id);+ if (galleryCache.selectedId && cleared.has(galleryCache.selectedId)) {+ galleryCache.selectedId = null;+ }+ galleryCache.clips = galleryCache.clips.filter(+ (clip) => !cleared.has(clip.id),+ );+ setClips(galleryCache.clips);+ setSrcById(galleryCache.srcById.toRecord());+ setSelectedId(galleryCache.selectedId);+ await refreshGallery();+ return;+ }+ galleryCache.srcById.clear();+ galleryCache.selectedId = null;+ // Drop the cached list and state first: refreshGallery merges into the cache and swallows a failed GET.+ galleryCache.clips = [];+ setClips([]);+ setSrcById({});+ setSelectedId(null);+ await refreshGallery();+ } catch (error) {+ toast.error(+ error instanceof Error ? error.message : "Could not clear the gallery.",+ );+ }+ }, [refreshGallery]);++ const handleDownloadClip = useCallback(+ (clip: AudioGalleryClip) => {+ const src = srcById[clip.id];+ if (!src) return;+ const anchor = document.createElement("a");+ anchor.href = src;+ anchor.download = `${clip.id}.wav`;+ anchor.click();+ },+ [srcById],+ );++ const handleDownloadFallbackClip = useCallback(() => {+ if (!fallbackClip) return;+ const anchor = document.createElement("a");+ anchor.href = fallbackClip.url;+ anchor.download = "generated-audio.wav";+ anchor.click();+ }, [fallbackClip]);++ const handleDownloadClipById = useCallback(async (clip: AudioGalleryClip) => {+ let temporaryUrl: string | null = null;+ try {+ let src = galleryCache.srcById.get(clip.id);+ if (!src) {+ const fetched = await fetchClipObjectUrl(clip.url);+ src = fetched.url;+ temporaryUrl = fetched.url;+ }+ const anchor = document.createElement("a");+ anchor.href = src;+ anchor.download = `${clip.id}.wav`;+ anchor.click();+ } catch {+ toast.error("Could not download the clip.");+ } finally {+ if (temporaryUrl) {+ const url = temporaryUrl;+ window.setTimeout(() => URL.revokeObjectURL(url), 0);+ }+ }+ }, []);++ const handleCopyPrompt = useCallback(async (text: string) => {+ if (await copyToClipboard(text)) {+ toast.success("Text copied");+ } else {+ toast.error("Could not copy the text.");+ }+ }, []);++ return {+ fallbackClip,+ setFallbackClip,+ loadingMoreRef,+ clips,+ hasMore,+ selectedId,+ setSelectedId,+ srcById,+ peaksById,+ ensureClipSrc,+ refreshGallery,+ loadMore,+ selectClip,+ handleDeleteClip,+ handleArchiveClip,+ handleTogglePin,+ historyReorder,+ handleClearGallery,+ handleDownloadClip,+ handleDownloadFallbackClip,+ handleDownloadClipById,+ handleCopyPrompt,+ };+}++export type AudioGallery = ReturnType<typeof useAudioGallery>;++const HISTORY_MIN_VISIBLE = 8;++export function useWorkflowHistory({+ workflow,+ enabled,+ clips,+ hasMore,+ selectedId,+ srcById,+ fallbackClip,+ loadMore,+ loadingMoreRef,+ selectClip,+}: { workflow: "speak" | "music"; enabled: boolean } & Pick<+ AudioGallery,+ | "clips"+ | "hasMore"+ | "selectedId"+ | "srcById"+ | "fallbackClip"+ | "loadMore"+ | "loadingMoreRef"+ | "selectClip"+>) {+ const visibleClips = useMemo(+ () => clips.filter((clip) => clipWorkflow(clip) === workflow),+ [clips, workflow],+ );+ const selectedClip =+ visibleClips.find((clip) => clip.id === selectedId) ?? null;+ const selectedClipSrc = selectedClip ? srcById[selectedClip.id] : undefined;+ const pageFallbackClip =+ fallbackClip?.workflow === workflow ? fallbackClip : null;++ useEffect(() => {+ if (!enabled || selectedClip || pageFallbackClip) return;+ const first = visibleClips[0];+ // Keep another page's unsaved clip: it is the only copy.+ if (first) selectClip(first.id, fallbackClip !== null);+ }, [enabled, selectedClip, pageFallbackClip, fallbackClip, visibleClips, selectClip]);++ useEffect(() => {+ if (+ !enabled ||+ visibleClips.length >= HISTORY_MIN_VISIBLE ||+ !hasMore ||+ loadingMoreRef.current+ )+ return;+ void loadMore();+ }, [enabled, visibleClips, hasMore, loadMore, loadingMoreRef]);++ // Load until this page gains a row: an all-other-page batch adds no height, so no scroll fires again.+ const visibleLoad = useRef(false);+ const current = useRef({ workflow, enabled });+ current.current = { workflow, enabled };+ const loadMoreVisible = useCallback(async () => {+ if (visibleLoad.current) return;+ visibleLoad.current = true;+ const countVisible = () =>+ galleryCache.clips.filter((clip) => clipWorkflow(clip) === workflow)+ .length;+ const before = countVisible();+ try {+ await loadGalleryUntil({+ has: () => countVisible() > before,+ count: () => galleryCache.clips.length,+ hasMore: () => galleryCache.hasMore,+ refresh: async () => {},+ loadMore,+ busy: () => loadingMoreRef.current,+ cancelled: () =>+ !current.current.enabled || current.current.workflow !== workflow,+ });+ } finally {+ visibleLoad.current = false;+ }+ }, [workflow, loadMore, loadingMoreRef]);++ return {+ visibleClips,+ selectedClip,+ selectedClipSrc,+ loadMoreVisible,+ fallbackClip: pageFallbackClip,+ };+}diff --git a/studio/frontend/src/features/audio/hooks/use-audio-handoff.ts b/studio/frontend/src/features/audio/hooks/use-audio-handoff.tsnew file mode 100644index 00000000000..9fd2ad5aec0--- /dev/null+++ b/studio/frontend/src/features/audio/hooks/use-audio-handoff.ts@@ -0,0 +1,160 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { useEffect, useRef } from "react";+import { translate } from "@/i18n";+import { loadGalleryUntil } from "@/lib/gallery-deep-link";+import { toast } from "@/lib/toast";+import { useNavigate, useSearch } from "@tanstack/react-router";+import { audioRouteIntent, audioWorkflowForPick } from "../route-search";+import { clipWorkflow, isAudioWorkflowId } from "../workflows";+import type { AudioHostState } from "./audio-host-state";+import { type AudioGallery, galleryCache } from "./use-audio-gallery";+import type { AudioModelSlot } from "./use-audio-model-slot";++export function useAudioHandoff({+ active,+ busy,+ busyRef,+ handleModelSelect,+ transitionWorkflow,+ refreshGallery,+ loadMore,+ loadingMoreRef,+ selectClip,+}: Pick<AudioHostState, "active" | "busy" | "busyRef"> &+ Pick<AudioModelSlot, "handleModelSelect" | "transitionWorkflow"> &+ Pick<+ AudioGallery,+ "refreshGallery" | "loadMore" | "loadingMoreRef" | "selectClip"+ >) {+ const navigateSelf = useNavigate();+ const routeSearch = useSearch({ strict: false }) as {+ model?: string;+ quant?: string;+ ggufQuant?: string;+ task?: string;+ workflow?: string;+ audioType?: string;+ loadId?: string;+ item?: string;+ };+ const handledRouteModel = useRef<string | null>(null);+ useEffect(() => {+ if (!active) return;+ const wanted = routeSearch.model;+ if (!wanted) {+ handledRouteModel.current = null;+ // An explicit workflow, else the one the task names (text-to-audio is Music).+ const routedWorkflow = audioRouteIntent(routeSearch);+ if (routedWorkflow === null) return;+ // Left in the URL when refused, so it retries once busy releases.+ if (!transitionWorkflow(routedWorkflow)) return;+ void navigateSelf({ to: "/audio", search: {}, replace: true });+ return;+ }+ const key = `${wanted}|${routeSearch.quant ?? ""}|${routeSearch.ggufQuant ?? ""}|${routeSearch.task ?? ""}|${routeSearch.audioType ?? ""}|${routeSearch.loadId ?? ""}|${routeSearch.workflow ?? ""}`;+ if (handledRouteModel.current === key) return;+ if (busyRef.current !== null) return;+ // Open the named page first: a staged or failed load otherwise left the user on another page.+ // Without an explicit workflow, the task (and audio type) name the page the load is for.+ const routedWorkflow = isAudioWorkflowId(routeSearch.workflow)+ ? routeSearch.workflow+ : audioWorkflowForPick({+ id: wanted,+ task: routeSearch.task,+ audioType: routeSearch.audioType,+ });+ if (+ isAudioWorkflowId(routedWorkflow) &&+ !transitionWorkflow(routedWorkflow)+ ) {+ return;+ }+ handledRouteModel.current = key;+ handleModelSelect(wanted, {+ source: "hub",+ isLora: false,+ ggufFilename: routeSearch.quant ?? undefined,+ ggufVariant: routeSearch.ggufQuant ?? undefined,+ loadId: routeSearch.loadId ?? undefined,+ audioType: routeSearch.audioType ?? undefined,+ // Chat-to-Audio routing drops the inventory flag, so stage the exact forwarded GGUF.+ isDownloaded: routeSearch.loadId+ ? true+ : routeSearch.quant+ ? false+ : undefined,+ pipelineTag: routeSearch.task ?? null,+ });+ void navigateSelf({ to: "/audio", search: {}, replace: true });+ }, [+ active,+ busy,+ routeSearch.model,+ routeSearch.quant,+ routeSearch.ggufQuant,+ routeSearch.task,+ routeSearch.workflow,+ routeSearch.audioType,+ routeSearch.loadId,+ handleModelSelect,+ navigateSelf,+ transitionWorkflow,+ ]);++ // A counter, not effect cleanup, retires a lookup: clearing the query must not cancel its own.+ const routedItem = active ? routeSearch.item : undefined;+ const routedLookup = useRef(0);+ useEffect(() => {+ if (!active) routedLookup.current += 1;+ }, [active]);+ useEffect(() => {+ if (!routedItem) return;+ const lookup = ++routedLookup.current;+ void navigateSelf({+ to: "/audio",+ search: (prev) => ({ ...prev, item: undefined }),+ replace: true,+ });+ void loadGalleryUntil({+ has: () => galleryCache.clips.some((clip) => clip.id === routedItem),+ count: () => galleryCache.clips.length,+ hasMore: () => galleryCache.hasMore,+ refresh: () => refreshGallery(undefined, galleryCache.clips.length),+ loadMore,+ busy: () => loadingMoreRef.current,+ cancelled: () => lookup !== routedLookup.current,+ }).then((found) => {+ if (lookup !== routedLookup.current) return;+ if (found) {+ selectClip(routedItem);+ const clip = galleryCache.clips.find((c) => c.id === routedItem);+ // Through ?workflow=, so a switch refused while busy stays in the URL and retries.+ if (clip) {+ void navigateSelf({+ to: "/audio",+ search: (prev) => ({ ...prev, workflow: clipWorkflow(clip) }),+ replace: true,+ });+ }+ } else {+ toast(translate("library.toast.clipNotFound"), {+ description: translate("library.toast.notFoundDescription"),+ });+ }+ });+ }, [+ routedItem,+ navigateSelf,+ refreshGallery,+ loadMore,+ selectClip,+ ]);++ return {+ navigateSelf,+ };+}++export type AudioHandoff = ReturnType<typeof useAudioHandoff>;diff --git a/studio/frontend/src/features/audio/hooks/use-audio-model-slot.ts b/studio/frontend/src/features/audio/hooks/use-audio-model-slot.tsnew file mode 100644index 00000000000..23ce76a266a--- /dev/null+++ b/studio/frontend/src/features/audio/hooks/use-audio-model-slot.ts@@ -0,0 +1,1051 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { useCallback, useEffect, useRef, useState } from "react";+import {+ cancelPreStreamRunReservations,+ confirmStopRunningChatsIfNeeded,+ listGgufVariants,+ listLoras,+ loadModel,+ offloadCountsFrom,+ offloadWarning,+ requestLocalPromptQueueStop,+ unloadModel,+ useChatRuntimeStore,+} from "@/features/chat";+import {+ fetchSttStatus,+ sttEngineStatusFor,+} from "@/features/chat/adapters/studio-model-dictation-adapter";+import { useStagedDownload } from "@/features/hub/download-manager";+import { getHfToken, hfApiToken } from "@/features/hub/stores/hf-token-store";+import type {+ ModelOption,+ ModelSelectorChangeMeta,+} from "@/features/model-picker/components/model-selector/types";+import { confirmRemoteCodeIfNeeded } from "@/features/security";+import { fetchSystemInfo } from "@/hooks/use-system";+import { toast } from "@/lib/toast";+import { getAudioDownloadPlan } from "../api";+import {+ audioCppRuntimeProblem,+ canTransitionAudioMode,+ exactGgufLoadSelector,+ expectedGgufDownloadBytes,+ isGgufTtsTarget,+ isTtsAudioType,+ macTtsPickAction,+ resolveAudioPickTask,+ selectAutoGgufVariant,+ stagedTtsLoadIsOwned,+ trainedTtsCheckpointIsLoadable,+ trainedTtsCheckpointIsRunnableOnMac,+} from "../audio-page-policy";+import {+ TTS_MAX_TOKENS,+ TTS_PROMPT_CONTEXT_RESERVE,+} from "../audio-workspace-constants";+import {+ audioModelLabel,+ type CreateMode,+ loadedAudioKind,+ type RemoteCodeApproval,+} from "../audio-workspace-utils";+import {+ audioModelRequiresRemoteCode,+ audioTaskFor,+ ggufSiblingFor,+ isMusicGenerationModel,+ musicGenerationRequiresCuda,+ sttEngineForRepoId,+ sttSidecarKeyFor,+ usesNativeAudioRuntime,+} from "../catalog";+import { useAudioWorkspaceStore } from "../stores/audio-workspace-store";+import { type AudioWorkflowId, slotForWorkflow } from "../workflows";+import type { AudioHostState } from "./audio-host-state";+import type { SttSidecar } from "./use-stt-sidecar";+import type { Transcription } from "./use-transcription";++export function useAudioModelSlot({+ active,+ activeRef,+ busy,+ busyRef,+ setBusy,+ mode,+ setMode,+ modeRef,+ generationPhaseRef,+ handleStopGeneration,+ refreshStatus,+ audioDevice,+ isMac,+ status,+ isRecording,+ stopAndDiscardRecording,+ releaseTranscribeSelection,+ ensureSttLoaded,+ sttGgufVariants,+ selectedSttRepoRef,+ setSelectedSttRepo,+ deferredSttLoad,+ sttLoadingGeneration,+ sttLoadGeneration,+ sttLoadAbort,+ audioCppRuntime,+ selectedSttRepo,+ sttReady,+ sttStatusRefreshGeneration,+}: Pick<+ AudioHostState,+ | "active"+ | "activeRef"+ | "busy"+ | "busyRef"+ | "setBusy"+ | "mode"+ | "setMode"+ | "modeRef"+ | "generationPhaseRef"+ | "handleStopGeneration"+ | "refreshStatus"+ | "audioDevice"+ | "isMac"+ | "status"+> &+ Pick<Transcription, "isRecording" | "stopAndDiscardRecording"> &+ Pick<+ SttSidecar,+ | "releaseTranscribeSelection"+ | "ensureSttLoaded"+ | "sttGgufVariants"+ | "selectedSttRepoRef"+ | "setSelectedSttRepo"+ | "deferredSttLoad"+ | "sttLoadingGeneration"+ | "sttLoadGeneration"+ | "sttLoadAbort"+ | "audioCppRuntime"+ | "selectedSttRepo"+ | "sttReady"+ | "sttStatusRefreshGeneration"+ >) {+ const ttsLoadInFlight = useRef(false);+ const pendingRoutedTtsPick = useRef<{+ repoId: string;+ ggufFilename?: string | null;+ loadId?: string | null;+ audioType?: string | null;+ remoteCodeApproval?: RemoteCodeApproval;+ isGguf?: boolean | null;+ } | null>(null);+ const ttsLoadGeneration = useRef(0);+ const pendingTtsLoad = useRef<{+ generation: number;+ repoId: string;+ loadTarget: string;+ loadRequestId: string;+ controller: AbortController;+ requestStarted: boolean;+ } | null>(null);++ const ttsPickGeneration = useRef(0);+ const ttsInspectionGeneration = useRef<number | null>(null);+ const stagedTtsGeneration = useRef(0);+ const pendingStagedTtsLoad = useRef<{+ repoId: string;+ ggufFilename: string | null;+ loadId?: string | null;+ audioType?: string | null;+ remoteCodeApproval?: RemoteCodeApproval;+ isGguf?: boolean | null;+ generation: number;+ } | null>(null);+ const stagedTtsLoadDeferred = useRef(false);++ const loadTtsModel = useCallback(+ async (+ repoId: string,+ ggufFilename?: string | null,+ // Rows in a non-active HF cache load only by snapshot path (meta.loadId), as in chat-page.tsx.+ loadId?: string | null,+ audioType?: string | null,+ remoteCodeApproval?: RemoteCodeApproval,+ isGguf?: boolean | null,+ ) => {+ // ?model= is already cleared, so a pick arriving mid-teardown is replayed from the finally below.+ if (ttsLoadInFlight.current || busyRef.current === "generating") {+ pendingRoutedTtsPick.current = {+ repoId,+ ggufFilename,+ loadId,+ audioType,+ remoteCodeApproval,+ isGguf,+ };+ return;+ }+ // A load stops every chat on the shared llama-server: ask as Chat does, gate claimed before the await so picks queue.+ ttsLoadInFlight.current = true;+ const lifecycleLease = useChatRuntimeStore.getState().beginModelLoading();+ if (lifecycleLease === null) {+ ttsLoadInFlight.current = false;+ pendingRoutedTtsPick.current = null;+ toast.info("Wait for the current model to finish loading.");+ return;+ }+ const releaseLifecycle = () =>+ useChatRuntimeStore.getState().endModelLoading(lifecycleLease);+ const stopDecision = await confirmStopRunningChatsIfNeeded();+ if (!stopDecision.proceed) {+ releaseLifecycle();+ ttsLoadInFlight.current = false;+ // Declining refuses the swap, so a queued pick must not reopen the dialog.+ pendingRoutedTtsPick.current = null;+ return;+ }+ // Hidden while the dialog is open: nothing to abort yet, so queue for the activation replay.+ if (!activeRef.current) {+ releaseLifecycle();+ ttsLoadInFlight.current = false;+ pendingRoutedTtsPick.current = {+ repoId,+ ggufFilename,+ loadId,+ audioType,+ remoteCodeApproval,+ isGguf,+ };+ return;+ }+ const generation = ++ttsLoadGeneration.current;+ const controller = new AbortController();+ const loadRequestId = crypto.randomUUID();+ const pending = {+ generation,+ repoId,+ // Cancel must name what was sent: for a pinned dir the display id makes _cancel_scoped_load_attempt refuse.+ loadTarget: loadId || repoId,+ loadRequestId,+ controller,+ requestStarted: false,+ };+ pendingTtsLoad.current = pending;+ const isCurrent = () =>+ generation === ttsLoadGeneration.current && activeRef.current;+ ttsLoadInFlight.current = true;+ busyRef.current = "loading";+ setBusy("loading");+ const toastId = toast.loading(`Loading ${audioModelLabel(repoId)}…`);+ try {+ const hfToken = hfApiToken(getHfToken()) ?? null;+ let trustRemoteCode = remoteCodeApproval?.trustRemoteCode ?? false;+ let approvedRemoteCodeFingerprint =+ remoteCodeApproval?.approvedRemoteCodeFingerprint ?? null;+ if (+ audioModelRequiresRemoteCode(repoId, audioType) &&+ !remoteCodeApproval+ ) {+ const approved = await confirmRemoteCodeIfNeeded({+ modelName: loadId || repoId,+ hfToken,+ requiresTrustRemoteCode: true,+ onApprove: (fingerprint) => {+ trustRemoteCode = true;+ approvedRemoteCodeFingerprint = fingerprint;+ },+ });+ if (!approved)+ throw new Error(+ "Custom code approval is required to load this model.",+ );+ if (controller.signal.aborted || !isCurrent()) return;+ }+ const wantsCpu = audioDevice === "cpu";+ const isGgufLoad = isGgufTtsTarget({ repoId, ggufFilename, loadId, isGguf });+ const res = await loadModel(+ {+ model_path: loadId || repoId,+ load_request_id: loadRequestId,+ force_cancel_active: stopDecision.forceCancelActive,+ hf_token: hfToken,+ max_seq_length: TTS_MAX_TOKENS + TTS_PROMPT_CONTEXT_RESERVE,+ load_in_4bit: false,+ is_lora: false,+ gguf_variant: ggufFilename ?? null,+ trust_remote_code: trustRemoteCode,+ approved_remote_code_fingerprint: approvedRemoteCodeFingerprint,+ audio_device: wantsCpu ? "cpu" : "auto",+ // GGUF ignores audio_device; an absent speculative_type means auto, which may attach a GPU drafter.+ ...(wantsCpu && isGgufLoad+ ? // biome-ignore lint/style/useNamingConvention: API schema+ {+ gpu_memory_mode: "manual" as const,+ gpu_layers: 0,+ speculative_type: "off" as const,+ }+ : {}),+ },+ {+ signal: controller.signal,+ runtime: "tts",+ onRequestStart: () => {+ pending.requestStarted = true;+ // Cancel queued prompts only once /load is really sent: loadModel can return without sending.+ cancelPreStreamRunReservations(stopDecision.preStreamRunTokens);+ requestLocalPromptQueueStop(stopDecision.promptQueueThreadIds);+ },+ },+ );+ if (!isCurrent()) return;+ if (res.is_audio && isTtsAudioType(res.audio_type)) {+ const offloadNotice = offloadWarning(offloadCountsFrom(res));+ const showToast = offloadNotice ? toast.warning : toast.success;+ showToast(+ `Model loaded (${loadedAudioKind(res.audio_type)})${offloadNotice?.titleSuffix ?? ""}`,+ {+ id: toastId,+ description: offloadNotice?.description,+ duration: offloadNotice ? 8000 : undefined,+ },+ );+ const loadedWorkflow = isMusicGenerationModel(repoId, res.audio_type)+ ? "music"+ : "speak";+ if (modeRef.current === "speak") {+ useAudioWorkspaceStore.getState().commitWorkflow(loadedWorkflow);+ }+ if (+ wantsCpu &&+ !isGgufLoad &&+ !usesNativeAudioRuntime(repoId, res.audio_type)+ ) {+ toast.info(+ "This model does not support CPU RAM yet, so it loaded on the GPU.",+ { duration: 6000 },+ );+ }+ } else {+ toast.error(`${repoId} loaded but is not a supported TTS model.`, {+ id: toastId,+ });+ }+ } catch (error) {+ if (isCurrent()) {+ toast.error(+ error instanceof Error ? error.message : "Model load failed.",+ { id: toastId },+ );+ } else {+ toast.dismiss(toastId);+ }+ } finally {+ if (pendingTtsLoad.current?.generation === generation)+ pendingTtsLoad.current = null;+ if (activeRef.current) await refreshStatus();+ ttsLoadInFlight.current = false;+ releaseLifecycle();+ busyRef.current = null;+ setBusy(null);+ // Only while visible: a hidden replay escapes the deactivation cancel and can replace Chat's model.+ if (activeRef.current) replayQueuedTtsPick();+ }+ },+ [refreshStatus, audioDevice],+ );++ const loadTtsModelRef = useRef(loadTtsModel);+ loadTtsModelRef.current = loadTtsModel;+ /** Start a pick that lost the race with a load still settling. Visible pages only: a load started+ * while hidden outlives the deactivation effect that would cancel it. */+ const replayQueuedTtsPick = useCallback(() => {+ const queued = pendingRoutedTtsPick.current;+ if (!queued) return;+ pendingRoutedTtsPick.current = null;+ void loadTtsModelRef.current(+ queued.repoId,+ queued.ggufFilename,+ queued.loadId,+ queued.audioType,+ queued.remoteCodeApproval,+ queued.isGguf,+ );+ }, []);+ const invalidatePendingStagedTts = useCallback(() => {+ stagedTtsGeneration.current += 1;+ pendingStagedTtsLoad.current = null;+ stagedTtsLoadDeferred.current = false;+ }, []);+ const invalidatePendingTtsSelection = useCallback(() => {+ ttsPickGeneration.current += 1;+ pendingRoutedTtsPick.current = null;+ invalidatePendingStagedTts();+ }, [invalidatePendingStagedTts]);+ const transitionMode = useCallback(+ (nextMode: CreateMode) => {+ if (nextMode === mode) {+ if (nextMode === "transcribe") invalidatePendingTtsSelection();+ return true;+ }+ if (+ !canTransitionAudioMode(busyRef.current, generationPhaseRef.current)+ ) {+ toast.info(+ "Wait for the active audio task to finish before switching modes.",+ );+ return false;+ }++ if (nextMode === "transcribe") invalidatePendingTtsSelection();+ if (busyRef.current === "generating") handleStopGeneration();+ stopAndDiscardRecording();+ setMode(nextMode);+ if (mode === "transcribe") {+ // Resolves to whether the sidecar is gone: a swallowed failed unload let the speech load OOM.+ const release = releaseTranscribeSelection().then(+ () => true,+ (error) => {+ toast.error(+ error instanceof Error+ ? error.message+ : "Failed to release the transcription model.",+ );+ return false;+ },+ );+ pendingTranscribeRelease.current = release;+ void release.then((released) => {+ if (pendingTranscribeRelease.current !== release) return;+ pendingTranscribeRelease.current = null;+ // Sidecar still resident: back to Transcribe so Eject can retry, unless something moved on.+ if (!released && modeRef.current === "speak") setMode("transcribe");+ });+ }+ return true;+ },+ [+ invalidatePendingTtsSelection,+ handleStopGeneration,+ mode,+ releaseTranscribeSelection,+ stopAndDiscardRecording,+ ],+ );+ const transitionWorkflow = useCallback(+ (next: AudioWorkflowId) => {+ const store = useAudioWorkspaceStore.getState();+ // Speak and Music share the slot, so transitionMode would wave a switch between them through.+ if (+ next !== store.workflow &&+ mode === "speak" &&+ slotForWorkflow(next) === "speak"+ ) {+ if (+ !canTransitionAudioMode(busyRef.current, generationPhaseRef.current)+ ) {+ toast.info(+ "Wait for the active audio task to finish before switching modes.",+ );+ return false;+ }+ if (busyRef.current === "generating") handleStopGeneration();+ invalidatePendingTtsSelection();+ } else if (!transitionMode(slotForWorkflow(next))) {+ return false;+ }+ store.commitWorkflow(next);+ return true;+ },+ [+ transitionMode,+ mode,+ busyRef,+ generationPhaseRef,+ handleStopGeneration,+ invalidatePendingTtsSelection,+ ],+ );+ const { stage: stageTtsDownload } = useStagedDownload({+ scopeId: "audio",+ onReady: () => {+ const pending = pendingStagedTtsLoad.current;+ if (+ !pending ||+ !stagedTtsLoadIsOwned(+ pending.generation,+ stagedTtsGeneration.current,+ modeRef.current,+ )+ ) {+ pendingStagedTtsLoad.current = null;+ stagedTtsLoadDeferred.current = false;+ return;+ }+ // Stays mounted: a hidden load would evict the visible page's model; also wait out generation.+ if (!active || busyRef.current !== null) {+ stagedTtsLoadDeferred.current = true;+ return;+ }+ pendingStagedTtsLoad.current = null;+ void loadTtsModelRef.current(+ pending.repoId,+ pending.ggufFilename,+ pending.loadId,+ pending.audioType,+ pending.remoteCodeApproval,+ pending.isGguf,+ );+ },+ });++ useEffect(() => {+ if (!active || busy !== null || !stagedTtsLoadDeferred.current) return;+ stagedTtsLoadDeferred.current = false;+ const pending = pendingStagedTtsLoad.current;+ if (+ !pending ||+ !stagedTtsLoadIsOwned(+ pending.generation,+ stagedTtsGeneration.current,+ modeRef.current,+ )+ ) {+ pendingStagedTtsLoad.current = null;+ return;+ }+ pendingStagedTtsLoad.current = null;+ void loadTtsModelRef.current(+ pending.repoId,+ pending.ggufFilename,+ pending.loadId,+ pending.audioType,+ pending.remoteCodeApproval,+ pending.isGguf,+ );+ }, [active, busy]);++ const loadOrStageTtsModel = useCallback(+ async (+ repoId: string,+ ggufFilename: string | null,+ meta: ModelSelectorChangeMeta,+ ) => {+ const generation = ++stagedTtsGeneration.current;+ pendingStagedTtsLoad.current = null;+ stagedTtsLoadDeferred.current = false;+ stageTtsDownload([]);++ let remoteCodeApproval: RemoteCodeApproval | undefined;+ const hfToken = hfApiToken(getHfToken()) ?? null;+ if (+ meta.source === "hub" &&+ !ggufFilename &&+ audioModelRequiresRemoteCode(repoId, meta.audioType)+ ) {+ try {+ const approved = await confirmRemoteCodeIfNeeded({+ modelName: meta.loadId || repoId,+ hfToken,+ requiresTrustRemoteCode: true,+ onApprove: (fingerprint) => {+ remoteCodeApproval = {+ trustRemoteCode: true,+ approvedRemoteCodeFingerprint: fingerprint,+ };+ },+ });+ if (generation !== stagedTtsGeneration.current) return;+ if (!approved) {+ toast.error("Custom code approval is required to load this model.");+ return;+ }+ } catch (error) {+ if (generation !== stagedTtsGeneration.current) return;+ toast.error(+ error instanceof Error+ ? error.message+ : `Could not verify the code for ${repoId}.`,+ );+ return;+ }+ }++ // Native models can need a second codec repo, so the backend plan owns every missing file.+ if (meta.source === "hub" && !ggufFilename) {+ let plan;+ try {+ plan = await getAudioDownloadPlan(+ meta.loadId || repoId,+ hfToken ?? undefined,+ );+ } catch (error) {+ if (generation !== stagedTtsGeneration.current) return;+ if (meta.isDownloaded === true) {+ void loadTtsModelRef.current(+ repoId,+ ggufFilename,+ meta.loadId,+ meta.audioType,+ remoteCodeApproval,+ meta.isGguf,+ );+ return;+ }+ toast.error(+ error instanceof Error+ ? error.message+ : `Could not prepare the download for ${repoId}.`,+ );+ return;+ }+ if (generation !== stagedTtsGeneration.current) return;+ const plannedEntries = plan.entries;+ if (plannedEntries.length > 0) {+ pendingStagedTtsLoad.current = {+ repoId,+ ggufFilename,+ loadId: meta.loadId,+ audioType: meta.audioType,+ remoteCodeApproval,+ isGguf: meta.isGguf,+ generation,+ };+ stageTtsDownload(+ plannedEntries.map((entry) => ({+ repoId: entry.repo_id,+ files: entry.files,+ bytes: entry.bytes,+ ggufFilename: entry.gguf_filename,+ checkpoint: entry.checkpoint,+ })),+ );+ return;+ }+ }++ if (+ meta.source === "hub" &&+ meta.isDownloaded === false &&+ ggufFilename+ ) {+ pendingStagedTtsLoad.current = {+ repoId,+ ggufFilename,+ loadId: meta.loadId,+ audioType: meta.audioType,+ remoteCodeApproval,+ isGguf: meta.isGguf,+ generation,+ };+ stageTtsDownload([+ meta.ggufVariant+ ? {+ repoId,+ files: [],+ bytes: meta.expectedBytes ?? 0,+ ggufFilename,+ ggufVariant: meta.ggufVariant,+ }+ : {+ repoId,+ files: [ggufFilename],+ bytes: meta.expectedBytes ?? 0,+ ggufFilename,+ },+ ]);+ return;+ }++ void loadTtsModelRef.current(+ repoId,+ ggufFilename,+ meta.loadId,+ meta.audioType,+ remoteCodeApproval,+ meta.isGguf,+ );+ },+ [stageTtsDownload],+ );++ // A hidden page may let the shared download continue, but it must not load the sidecar. Returning+ // to the same still-selected repo resumes preparation once; a different selection clears it.+ useEffect(() => {+ if (!active) {+ ttsPickGeneration.current += 1;+ const pending = pendingTtsLoad.current;+ if (pending) {+ ttsLoadGeneration.current += 1;+ pendingTtsLoad.current = null;+ pending.controller.abort();+ if (pending.requestStarted)+ void unloadModel({+ model_path: pending.loadTarget,+ cancel_load_request_id: pending.loadRequestId,+ }).catch(() => {});+ }+ if (ttsInspectionGeneration.current !== null) {+ ttsInspectionGeneration.current = null;+ busyRef.current = null;+ setBusy(null);+ }++ if (sttLoadingGeneration.current !== null) {+ const repoId = selectedSttRepoRef.current;+ deferredSttLoad.current = repoId+ ? {+ repoId,+ sidecarKey: sttSidecarKeyFor(repoId),+ engine: sttEngineForRepoId(repoId),+ }+ : null;+ sttLoadGeneration.current += 1;+ sttLoadingGeneration.current = null;+ sttLoadAbort.current?.abort();+ sttLoadAbort.current = null;+ busyRef.current = null;+ setBusy(null);+ }+ return;+ }++ // A pick queued behind a settling load, held back because the page went away before the load+ // finished. Now that Audio is visible again the attempt is cancellable.+ replayQueuedTtsPick();++ const deferred = deferredSttLoad.current;+ deferredSttLoad.current = null;+ if (deferred && selectedSttRepoRef.current === deferred.repoId) {+ void (async () => {+ try {+ const status = await fetchSttStatus(+ undefined,+ deferred.engine === "transformers"+ ? deferred.sidecarKey+ : undefined,+ );+ const download = sttEngineStatusFor(+ status,+ deferred.sidecarKey,+ deferred.engine,+ )?.download;+ // `model` is null once the download thread has stopped, so a cancellation made while this page+ // was hidden matched nothing here and the deferred load restarted the whole download.+ if (+ download?.cancelled &&+ (download.model ?? download.cancelled_model) === deferred.sidecarKey+ )+ return;+ } catch {+ }+ if (activeRef.current && selectedSttRepoRef.current === deferred.repoId)+ void ensureSttLoaded(+ deferred.repoId,+ deferred.sidecarKey,+ deferred.engine,+ );+ })();+ }+ }, [active, ensureSttLoaded]);++ const pendingTranscribeRelease = useRef<Promise<boolean> | null>(null);++ const handleModelSelect = useCallback(+ async (id: string, meta: ModelSelectorChangeMeta) => {+ if (busyRef.current !== null) return;+ // Uncurated picks fall back to the pipeline tag, else community ASR repos load into the TTS slot.+ const task = resolveAudioPickTask(audioTaskFor(id), meta.pipelineTag);+ const runtimeProblem =+ task === "stt" ? null : audioCppRuntimeProblem(id, audioCppRuntime.current);+ if (runtimeProblem) {+ toast.error(runtimeProblem, { duration: 7000 });+ return;+ }+ const cudaMusicPick =+ task !== "stt" && musicGenerationRequiresCuda(id, meta.audioType);+ const selectionGeneration = ++ttsPickGeneration.current;+ if (cudaMusicPick) {+ const system = await fetchSystemInfo();+ if (selectionGeneration !== ttsPickGeneration.current) return;+ if (system?.device_backend !== "cuda") {+ toast.error(+ `${id} requires a verified NVIDIA CUDA GPU for local generation.`,+ { duration: 7000 },+ );+ return;+ }+ }+ stopAndDiscardRecording();+ deferredSttLoad.current = null;+ if (task === "stt") {+ if (!transitionMode("transcribe")) return;+ const sidecarKey = sttSidecarKeyFor(id);+ const engine = sttEngineForRepoId(id, meta.isGguf);+ if (meta.ggufVariant) {+ sttGgufVariants.current.set(id.toLowerCase(), meta.ggufVariant);+ } else {+ sttGgufVariants.current.delete(id.toLowerCase());+ }+ deferredSttLoad.current = null;+ selectedSttRepoRef.current = id;+ setSelectedSttRepo(id);+ void ensureSttLoaded(id, sidecarKey, engine);+ return;+ }+ if (!transitionMode("speak")) return;+ const releaseInFlight = pendingTranscribeRelease.current;+ // A failed release leaves the sidecar resident; claimed before the await since the button only disables on `busy`.+ if (releaseInFlight && !(await releaseInFlight)) {+ setMode("transcribe");+ return;+ }+ if (ttsPickGeneration.current !== selectionGeneration) return;+ const exactGguf = exactGgufLoadSelector(meta);+ const isGguf = isGgufTtsTarget({+ repoId: id,+ ggufFilename: exactGguf,+ isGguf: meta.isGguf,+ });+ const ggufSibling = isGguf ? null : ggufSiblingFor(id);+ const nativeRuntime =+ usesNativeAudioRuntime(id, meta.audioType) && !cudaMusicPick;+ const macAction = macTtsPickAction({+ isMac,+ isGguf,+ ggufSibling,+ nativeRuntime,+ });+ if (macAction === "reject") {+ toast.error(+ cudaMusicPick+ ? `${id} currently requires an NVIDIA CUDA GPU and cannot run locally on this Mac.`+ : `${id} has no runnable GGUF TTS build. MLX cannot generate text-to-speech from its safetensors checkpoint on this Mac.`,+ { duration: 7000 },+ );+ return;+ }+ if (macAction === "use-gguf-sibling" && ggufSibling) {+ toast.info(+ `Loading the GGUF build of ${id}. MLX has no text-to-speech decoder, so the safetensors build cannot generate on this Mac.`,+ { duration: 7000 },+ );+ ttsInspectionGeneration.current = selectionGeneration;+ busyRef.current = "loading";+ setBusy("loading");+ try {+ const listing = await listGgufVariants(+ ggufSibling,+ hfApiToken(getHfToken()),+ );+ if (selectionGeneration !== ttsPickGeneration.current) return;+ const variant = selectAutoGgufVariant(+ listing.variants,+ listing.default_variant,+ );+ if (!variant) {+ toast.error(+ `${ggufSibling} does not publish a runnable GGUF file.`,+ );+ return;+ }+ if (ttsInspectionGeneration.current === selectionGeneration) {+ ttsInspectionGeneration.current = null;+ busyRef.current = null;+ setBusy(null);+ }+ await loadOrStageTtsModel(ggufSibling, variant.filename, {+ ...meta,+ source: "hub",+ isGguf: true,+ ggufFilename: variant.filename,+ ggufVariant: variant.quant,+ isDownloaded: variant.downloaded === true && !variant.partial,+ expectedBytes: expectedGgufDownloadBytes(variant),+ });+ } catch (error) {+ if (selectionGeneration !== ttsPickGeneration.current) return;+ toast.error(+ error instanceof Error+ ? error.message+ : `Could not inspect ${ggufSibling}.`,+ );+ } finally {+ if (ttsInspectionGeneration.current === selectionGeneration) {+ ttsInspectionGeneration.current = null;+ busyRef.current = null;+ setBusy(null);+ }+ }+ return;+ }+ await loadOrStageTtsModel(id, exactGguf, meta);+ },+ [+ ensureSttLoaded,+ isMac,+ loadOrStageTtsModel,+ stopAndDiscardRecording,+ transitionMode,+ ],+ );++ const handleEject = useCallback(() => {+ if (busy !== null || isRecording) {+ toast.info("Stop the active audio task before ejecting its model.");+ return;+ }++ stopAndDiscardRecording();++ if (mode === "transcribe") {+ if (!selectedSttRepo) return;+ if (!sttReady) {+ sttStatusRefreshGeneration.current += 1;+ void releaseTranscribeSelection();+ return;+ }++ setBusy("unloading");+ const toastId = toast.loading("Unloading transcription model…");+ void (async () => {+ try {+ await releaseTranscribeSelection();+ toast.success("Transcription model unloaded", {+ id: toastId,+ duration: 1200,+ });+ } catch (error) {+ toast.error(+ error instanceof Error+ ? error.message+ : "Failed to unload transcription model.",+ { id: toastId },+ );+ } finally {+ setBusy(null);+ }+ })();+ return;+ }++ const activeModel = status?.active_model;+ if (!activeModel) return;++ const lifecycleLease = useChatRuntimeStore.getState().beginModelLoading();+ if (lifecycleLease === null) {+ toast.info("Wait for the current model to finish loading.");+ return;+ }++ setBusy("unloading");+ void (async () => {+ try {+ const stopDecision = await confirmStopRunningChatsIfNeeded(+ "Unloading the model",+ "unload",+ );+ if (!stopDecision.proceed) {+ setBusy(null);+ return;+ }++ // An old managed completion must not immediately replace the model the user just ejected. The+ // global download may continue for later use.+ invalidatePendingStagedTts();+ stageTtsDownload([]);++ const toastId = toast.loading("Unloading model…");+ try {+ cancelPreStreamRunReservations(stopDecision.preStreamRunTokens);+ requestLocalPromptQueueStop(stopDecision.promptQueueThreadIds);+ await unloadModel({+ model_path: activeModel,+ force_cancel_active: stopDecision.forceCancelActive,+ });+ requestLocalPromptQueueStop();+ await refreshStatus();+ toast.success("Model unloaded", { id: toastId, duration: 1200 });+ } catch (error) {+ toast.error(+ error instanceof Error ? error.message : "Failed to unload model.",+ { id: toastId },+ );+ } finally {+ setBusy(null);+ }+ } finally {+ useChatRuntimeStore.getState().endModelLoading(lifecycleLease);+ }+ })();+ }, [+ busy,+ isRecording,+ mode,+ refreshStatus,+ releaseTranscribeSelection,+ selectedSttRepo,+ invalidatePendingStagedTts,+ stageTtsDownload,+ status?.active_model,+ sttReady,+ stopAndDiscardRecording,+ ]);++ // Scan rows carry no modality until the backend tags them; without this trained checkpoints are unreachable.+ const [trainedTtsModels, setTrainedTtsModels] = useState<ModelOption[]>([]);+ useEffect(() => {+ if (!active) return;+ let cancelled = false;+ listLoras()+ .then((res) => {+ if (cancelled) return;+ setTrainedTtsModels(+ res.loras+ .filter(+ (lora) =>+ !isMac ||+ trainedTtsCheckpointIsRunnableOnMac(+ lora.audio_type,+ lora.export_type,+ ),+ )+ // GGUF_TTS_AUDIO_TYPES omits csm: llama.cpp has no CSM decoder.+ .filter((lora) =>+ isTtsAudioType(lora.audio_type, lora.export_type === "gguf"),+ )+ .filter((lora) =>+ trainedTtsCheckpointIsLoadable(lora.audio_type, lora.export_type),+ )+ .map((lora) => ({+ id: lora.adapter_path,+ name: audioModelLabel(lora.adapter_path),+ description:+ lora.export_type === "merged"+ ? `Fine-tuned - ${lora.base_model || "unknown base"}`+ : `LoRA - ${lora.base_model || "unknown base"}`,+ audioType: lora.audio_type ?? null,+ })),+ );+ })+ .catch(() => {+ if (!cancelled) setTrainedTtsModels([]);+ });+ return () => {+ cancelled = true;+ };+ }, [active, isMac]);++ return {+ replayQueuedTtsPick,+ transitionMode,+ transitionWorkflow,+ pendingTranscribeRelease,+ handleModelSelect,+ handleEject,+ trainedTtsModels,+ };+}++export type AudioModelSlot = ReturnType<typeof useAudioModelSlot>;diff --git a/studio/frontend/src/features/audio/hooks/use-speech-generation.ts b/studio/frontend/src/features/audio/hooks/use-speech-generation.tsnew file mode 100644index 00000000000..9bb6a0bb7eb--- /dev/null+++ b/studio/frontend/src/features/audio/hooks/use-speech-generation.ts@@ -0,0 +1,405 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { useCallback, useEffect, useMemo, useState } from "react";+import { readLastPrompt, saveLastPrompt } from "@/lib/last-prompt";+import { toast } from "@/lib/toast";+import { generateAudio } from "../api";+import {+ audioOptionLabel,+ audioOptionsForRequest,+ type AudioOptionValue,+ type AudioOptionValues,+ missingRequiredAudioOptions,+ parseAudioOptions,+ readAudioOptionValues,+ saveAudioOptionValues,+} from "../audio-options";+import {+ audioSamplingControlsApply,+ isTtsAudioType,+ MINIMAX_MUSIC_DEFAULT_SECONDS,+ minimaxMusicFramesForSeconds,+ MOSS_TTS_DEFAULT_SECONDS,+ MOSS_TTS_FRAMES_PER_SECOND,+ MOSS_TTS_MAX_FRAMES,+ mossTtsFramesForSeconds,+ mossTtsMaxFrames,+ musicDurationRange,+ musicLyricsOptional,+ musicNeedsDescription as musicModelNeedsDescription,+ nativeAudioInstructionsKind,+ persistedClipForGeneration,+} from "../audio-page-policy";+import {+ isMusicGenerationModel,+ musicGenerationRequiresCuda,+} from "../catalog";+import { TTS_MAX_TOKENS } from "../audio-workspace-constants";+import type { AudioHostState } from "./audio-host-state";+import { galleryCache } from "./use-audio-gallery";+import { useAudioWorkspaceStore } from "../stores/audio-workspace-store";+import type { AudioWorkflowId } from "../workflows";+import type { AudioGallery } from "./use-audio-gallery";+import type { AudioModelSlot } from "./use-audio-model-slot";++type TtsWorkflow = "speak" | "music";+type TtsDraftField = "prompt" | "instructions";++function ttsWorkflowOf(workflow: AudioWorkflowId): TtsWorkflow {+ return workflow === "music" ? "music" : "speak";+}++/** Speak's text keeps the pre-split key so existing drafts survive. */+function ttsDraftKey(field: TtsDraftField, workflow: TtsWorkflow): string {+ const base = workflow === "music" ? "audio:music" : "audio";+ return field === "prompt" ? base : `${base}:instructions`;+}++export function useSpeechGeneration({+ workflow,+ status,+ busyRef,+ setBusy,+ updateGenerationPhase,+ generateAbort,+ setMode,+ setAdvancedOpen,+ refreshStatus,+ activeRef,+ modeRef,+ refreshGallery,+ selectClip,+ setFallbackClip,+ setSelectedId,+ pendingTranscribeRelease,+ replayQueuedTtsPick,+}: { workflow: TtsWorkflow } & Pick<+ AudioHostState,+ | "status"+ | "busyRef"+ | "setBusy"+ | "updateGenerationPhase"+ | "generateAbort"+ | "setMode"+ | "setAdvancedOpen"+ | "refreshStatus"+ | "activeRef"+ | "modeRef"+> &+ Pick<AudioGallery, "refreshGallery" | "selectClip" | "setFallbackClip" | "setSelectedId"> &+ Pick<AudioModelSlot, "pendingTranscribeRelease" | "replayQueuedTtsPick">) {+ const [drafts, setDrafts] = useState<Record<TtsDraftField, Record<TtsWorkflow, string>>>(+ () => ({+ prompt: {+ speak: readLastPrompt(ttsDraftKey("prompt", "speak")),+ music: readLastPrompt(ttsDraftKey("prompt", "music")),+ },+ instructions: {+ speak: readLastPrompt(ttsDraftKey("instructions", "speak")),+ music: readLastPrompt(ttsDraftKey("instructions", "music")),+ },+ }),+ );+ const [generationError, setGenerationError] = useState<string | null>(null);+ const prompt = drafts.prompt[workflow];+ const audioInstructions = drafts.instructions[workflow];+ const setDraft = useCallback((field: TtsDraftField, next: string) => {+ const page = ttsWorkflowOf(useAudioWorkspaceStore.getState().workflow);+ saveLastPrompt(ttsDraftKey(field, page), next);+ setDrafts((current) => ({+ ...current,+ [field]: { ...current[field], [page]: next },+ }));+ }, []);+ const setPrompt = useCallback(+ (next: string) => setDraft("prompt", next),+ [setDraft],+ );+ const setAudioInstructions = useCallback(+ (next: string) => setDraft("instructions", next),+ [setDraft],+ );+ const [audioLanguage, setAudioLanguage] = useState("");+ const [temperature, setTemperature] = useState(0.6);+ // Only send temperature once moved: model_fields_set makes it override the per-model recommendation.+ const [temperatureEdited, setTemperatureEdited] = useState(false);+ const handleTemperatureChange = useCallback((value: number) => {+ setTemperatureEdited(true);+ setTemperature(value);+ }, []);+ const [maxTokens, setMaxTokens] = useState(2048);+ const [mossMaxSeconds, setMossMaxSeconds] = useState(+ MOSS_TTS_DEFAULT_SECONDS,+ );+ const [minimaxMaxSeconds, setMinimaxMaxSeconds] = useState(+ MINIMAX_MUSIC_DEFAULT_SECONDS,+ );+ const mossFrameLimit = mossTtsMaxFrames(+ status?.audio_type,+ status?.context_length,+ );+ const mossMaxSecondsLimit =+ (mossFrameLimit ?? MOSS_TTS_MAX_FRAMES) / MOSS_TTS_FRAMES_PER_SECOND;++ useEffect(() => {+ setTemperature(mossFrameLimit !== null ? 1.7 : 0.6);+ setTemperatureEdited(false);+ if (mossFrameLimit !== null) {+ setMossMaxSeconds((current) =>+ Math.min(current, mossFrameLimit / MOSS_TTS_FRAMES_PER_SECOND),+ );+ }+ }, [mossFrameLimit]);++ const ttsLoaded = Boolean(+ status?.active_model &&+ isTtsAudioType(status.audio_type, status.is_gguf === true),+ );+ const musicGeneration = isMusicGenerationModel(+ status?.active_model,+ status?.audio_type,+ );+ const cudaMusicGeneration = musicGenerationRequiresCuda(+ status?.active_model,+ status?.audio_type,+ );+ const musicNeedsDescription =+ cudaMusicGeneration ||+ musicModelNeedsDescription(status?.audio_type, status?.audio_family);+ const lyricsOptional = musicLyricsOptional(+ status?.audio_type,+ status?.audio_family,+ );+ const musicRange = musicDurationRange(cudaMusicGeneration);+ const musicSeconds = Math.min(+ Math.max(minimaxMaxSeconds, musicRange.min),+ musicRange.max,+ );+ const samplingControls = audioSamplingControlsApply(status?.audio_type);+ const audioOptionSpecs = useMemo(+ () => parseAudioOptions(status?.audio_options),+ [status?.audio_options],+ );+ const audioOptionsModel = status?.active_model ?? null;+ const [audioOptionValues, setAudioOptionValues] = useState<AudioOptionValues>(+ () => readAudioOptionValues(audioOptionsModel),+ );+ const [audioOptionValuesModel, setAudioOptionValuesModel] = useState(+ audioOptionsModel,+ );+ if (audioOptionValuesModel !== audioOptionsModel) {+ setAudioOptionValuesModel(audioOptionsModel);+ setAudioOptionValues(readAudioOptionValues(audioOptionsModel));+ }+ const handleAudioOptionChange = useCallback(+ (name: string, value: AudioOptionValue | undefined) => {+ setAudioOptionValues((current) => {+ const next = { ...current };+ if (value === undefined) delete next[name];+ else next[name] = value;+ saveAudioOptionValues(audioOptionsModel, next);+ return next;+ });+ },+ [audioOptionsModel],+ );+ const handleAudioOptionsReset = useCallback(() => {+ setAudioOptionValues({});+ saveAudioOptionValues(audioOptionsModel, {});+ }, [audioOptionsModel]);+ const mossLocalGeneration = status?.audio_type === "moss_tts_local";+ const instructionsKind = musicGeneration+ ? "music"+ : nativeAudioInstructionsKind(status?.audio_type);++ const handleGenerate = useCallback(async () => {+ const text = prompt.trim();+ if (!text && !lyricsOptional) return;+ // Same sidecar gate as the TTS load path, claimed before the await: generating beside a dictation model OOMs.+ if (busyRef.current) return;+ busyRef.current = "generating";+ setBusy("generating");+ updateGenerationPhase("preparing");+ const releaseInFlight = pendingTranscribeRelease.current;+ if (releaseInFlight && !(await releaseInFlight)) {+ updateGenerationPhase(null);+ busyRef.current = null;+ setBusy(null);+ setMode("transcribe");+ return;+ }+ const instructions = audioInstructions.trim();+ if (musicNeedsDescription && !instructions) {+ updateGenerationPhase(null);+ busyRef.current = null;+ setBusy(null);+ toast.error("Add a music description. This model needs one beside the lyrics.");+ return;+ }+ const missingOptions = missingRequiredAudioOptions(+ audioOptionSpecs,+ audioOptionValues,+ );+ if (missingOptions.length > 0) {+ updateGenerationPhase(null);+ busyRef.current = null;+ setBusy(null);+ setAdvancedOpen(true);+ toast.error(+ `Set ${missingOptions.map((spec) => audioOptionLabel(spec.name)).join(", ")} in Advanced before generating.`,+ );+ return;+ }+ const requestOptions = audioOptionsForRequest(+ audioOptionSpecs,+ audioOptionValues,+ );+ const language = audioLanguage.trim();+ saveLastPrompt(ttsDraftKey("prompt", workflow), prompt);+ const controller = new AbortController();+ generateAbort.current = controller;+ updateGenerationPhase("generating");+ try {+ const generated = await generateAudio(text, {+ ...(!musicGeneration && samplingControls && temperatureEdited+ ? { temperature }+ : {}),+ max_tokens: musicGeneration+ ? minimaxMusicFramesForSeconds(musicSeconds)+ : mossFrameLimit !== null+ ? mossTtsFramesForSeconds(mossMaxSeconds, mossFrameLimit)+ : maxTokens,+ ...(instructionsKind !== null && instructions+ ? { audio_instructions: instructions }+ : {}),+ ...(mossLocalGeneration && language+ ? { audio_language: language }+ : {}),+ ...(Object.keys(requestOptions).length > 0+ ? { audio_options: requestOptions }+ : {}),+ signal: controller.signal,+ });+ if (generated.choices[0]?.finish_reason === "length")+ toast.warning(+ maxTokens < TTS_MAX_TOKENS+ ? "Speech stopped at the Max tokens limit before the end of the text. Raise Max tokens under Advanced to hear the rest."+ : "Speech stopped at the Max tokens limit before the end of the text. Split the text into shorter parts to hear the rest.",+ );+ updateGenerationPhase("finishing");+ const refreshed = await refreshGallery();+ const generatedClip = persistedClipForGeneration(+ generated.clip_id,+ refreshed,+ );+ if (generatedClip) {+ setFallbackClip(null);+ selectClip(generatedClip.id);+ } else if (generated.clip_id) {+ // Persisted but missed by this refresh: keep the response audio, or selectedClip renders empty.+ setFallbackClip({+ url: `data:audio/wav;base64,${generated.audio.data}`,+ prompt: text,+ model: generated.model,+ saved: true,+ workflow,+ });+ selectClip(generated.clip_id, true);+ } else {+ galleryCache.selectedId = null;+ setSelectedId(null);+ setFallbackClip({+ url: `data:audio/wav;base64,${generated.audio.data}`,+ prompt: text,+ model: generated.model,+ saved: false,+ workflow,+ });+ }+ } catch (error) {+ if (!controller.signal.aborted) {+ updateGenerationPhase("finishing");+ setGenerationError(+ error instanceof Error ? error.message : "Audio generation failed.",+ );+ toast.error(+ error instanceof Error ? error.message : "Audio generation failed.",+ );+ await refreshStatus();+ }+ } finally {+ generateAbort.current = null;+ updateGenerationPhase(null);+ busyRef.current = null;+ setBusy(null);+ if (activeRef.current && modeRef.current === "speak")+ replayQueuedTtsPick();+ }+ }, [+ workflow,+ prompt,+ audioInstructions,+ audioLanguage,+ musicGeneration,+ musicNeedsDescription,+ lyricsOptional,+ audioOptionSpecs,+ audioOptionValues,+ setAdvancedOpen,+ mossLocalGeneration,+ mossFrameLimit,+ mossMaxSeconds,+ musicSeconds,+ samplingControls,+ instructionsKind,+ temperature,+ temperatureEdited,+ updateGenerationPhase,+ maxTokens,+ refreshGallery,+ refreshStatus,+ replayQueuedTtsPick,+ selectClip,+ ]);++ // Only unmount aborts: RootLayout keeps this page mounted so leaving the tab does not cancel synthesis.+ useEffect(() => () => generateAbort.current?.abort(), []);++ return {+ prompt,+ setPrompt,+ audioInstructions,+ setAudioInstructions,+ audioLanguage,+ setAudioLanguage,+ temperature,+ handleTemperatureChange,+ maxTokens,+ setMaxTokens,+ mossMaxSeconds,+ setMossMaxSeconds,+ setMinimaxMaxSeconds,+ mossFrameLimit,+ mossMaxSecondsLimit,+ ttsLoaded,+ musicGeneration,+ cudaMusicGeneration,+ musicNeedsDescription,+ lyricsOptional,+ musicRange,+ musicSeconds,+ samplingControls,+ audioOptionSpecs,+ audioOptionValues,+ handleAudioOptionChange,+ handleAudioOptionsReset,+ mossLocalGeneration,+ instructionsKind,+ handleGenerate,+ generationError,+ setGenerationError,+ };+}++export type SpeechGeneration = ReturnType<typeof useSpeechGeneration>;diff --git a/studio/frontend/src/features/audio/hooks/use-stt-sidecar.ts b/studio/frontend/src/features/audio/hooks/use-stt-sidecar.tsnew file mode 100644index 00000000000..a0be8df6a36--- /dev/null+++ b/studio/frontend/src/features/audio/hooks/use-stt-sidecar.ts@@ -0,0 +1,316 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { useCallback, useRef, useState } from "react";+import {+ fetchSttStatus,+ loadSttModel,+ startSttDownload,+ sttEngineStatusFor,+ SttModelNotDownloadedError,+ unloadSttModel,+} 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";+import { toast } from "@/lib/toast";+import type { AudioCppRuntimeStatus } from "../audio-cpp-catalog";+import {+ reconcileSttSelection,+ resolveSttResidency,+ type SttDownloadedArtifact,+ sttDownloadedArtifacts,+ sttSelectionReady,+} from "../audio-page-policy";+import { audioModelLabel } from "../audio-workspace-utils";+import {+ type AudioSttEngine,+ sttEngineForRepoId,+ sttRepoIdForSidecarKey,+ sttSidecarKeyFor,+} from "../catalog";+import type { AudioHostState } from "./audio-host-state";++export function useSttSidecar({+ setBusy,+ activeRef,+}: Pick<AudioHostState, "setBusy" | "activeRef">) {+ const [lastSttRepo, setLastSttRepoChoice] = usePersistedChoice("unsloth:audio:last-stt-model", "");+ const [lastSttVariant, setLastSttVariant] = usePersistedChoice("unsloth:audio:last-stt-variant", "");+ const [selectedSttRepo, setSelectedSttRepo] = useState<string | null>(null);+ const [sttLoadedModel, setSttLoadedModel] = useState<string | null>(null);+ const [sttLoadedEngine, setSttLoadedEngine] = useState<+ AudioSttEngine | null+ >(null);+ const [downloadedSttArtifacts, setDownloadedSttArtifacts] = useState<+ SttDownloadedArtifact[]+ >([]);+ const selectedSttRepoRef = useRef<string | null>(selectedSttRepo);+ selectedSttRepoRef.current = selectedSttRepo;+ const sttStatusRefreshGeneration = useRef(0);+ const audioCppRuntime = useRef<AudioCppRuntimeStatus | null>(null);+ const sttLoadGeneration = useRef(0);+ const sttGgufVariants = useRef(+ new Map<string, string>(+ lastSttRepo && lastSttVariant ? [[lastSttRepo.toLowerCase(), lastSttVariant]] : [],+ ),+ );+ const setLastSttRepo = useCallback(+ (repo: string) => {+ setLastSttRepoChoice(repo);+ setLastSttVariant(sttGgufVariants.current.get(repo.toLowerCase()) ?? "");+ },+ [setLastSttRepoChoice, setLastSttVariant],+ );+ const sttLoadingGeneration = useRef<number | null>(null);+ // Residency is not ownership: track the owned model identity, since other surfaces can swap the sidecar.+ const sttLoadedByThisPage = useRef<string | null>(null);+ const sttLoadAbort = useRef<AbortController | null>(null);+ const deferredSttLoad = useRef<{+ repoId: string;+ sidecarKey: string;+ engine: AudioSttEngine;+ } | null>(null);++ const refreshSttStatus = useCallback(async () => {+ const generation = ++sttStatusRefreshGeneration.current;+ try {+ const selectedRepo = selectedSttRepoRef.current;+ const selectedKey = selectedRepo ? sttSidecarKeyFor(selectedRepo) : null;+ const selectedEngine = selectedRepo+ ? sttEngineForRepoId(selectedRepo)+ : null;+ const stt = await fetchSttStatus(+ undefined,+ selectedEngine === "transformers"+ ? (selectedKey ?? undefined)+ : undefined,+ );+ if (generation !== sttStatusRefreshGeneration.current) return;+ audioCppRuntime.current = stt.audio_cpp_runtime ?? null;+ const nextDownloadedArtifacts = sttDownloadedArtifacts(+ stt,+ sttRepoIdForSidecarKey,+ );+ setDownloadedSttArtifacts((current) =>+ current.length === nextDownloadedArtifacts.length &&+ current.every(+ (artifact, index) =>+ artifact.repoId === nextDownloadedArtifacts[index].repoId &&+ artifact.sidecarKey === nextDownloadedArtifacts[index].sidecarKey &&+ artifact.engine === nextDownloadedArtifacts[index].engine,+ )+ ? current+ : nextDownloadedArtifacts,+ );+ const selectedBlock = selectedKey+ ? (sttEngineStatusFor(stt, selectedKey, selectedEngine ?? undefined) ??+ (selectedEngine === "transformers" ? stt : undefined))+ : undefined;+ const preservePending = Boolean(+ selectedBlock?.loading ||+ sttLoadingGeneration.current !== null ||+ deferredSttLoad.current !== null,+ );+ const residency = resolveSttResidency(+ stt,+ selectedEngine,+ preservePending,+ );+ const loadedModel = residency?.model ?? null;+ setSttLoadedModel(loadedModel);+ setSttLoadedEngine(residency?.engine ?? null);+ const reconciled = reconcileSttSelection({+ selectedRepo,+ loadedModel,+ loadedEngine: residency?.engine,+ preservePending,+ sidecarKeyFor: sttSidecarKeyFor,+ repoIdForSidecarKey: sttRepoIdForSidecarKey,+ engineForRepo: sttEngineForRepoId,+ });+ selectedSttRepoRef.current = reconciled;+ setSelectedSttRepo(reconciled);+ } catch {+ if (generation !== sttStatusRefreshGeneration.current) return;+ setSttLoadedModel(null);+ setSttLoadedEngine(null);+ }+ }, []);++ const sttSelected = selectedSttRepo !== null;+ const sttReady = sttSelectionReady(+ selectedSttRepo,+ sttLoadedModel,+ sttSidecarKeyFor,+ selectedSttRepo ? sttEngineForRepoId(selectedSttRepo) : null,+ sttLoadedEngine,+ );++ const releaseTranscribeSelection = useCallback(async () => {+ const selected = selectedSttRepoRef.current;+ const claim = sttLoadedByThisPage.current;+ const owned =+ sttReady &&+ selected !== null &&+ claim !== null &&+ claim === sttLoadedModel;+ const forget = () => {+ deferredSttLoad.current = null;+ selectedSttRepoRef.current = null;+ sttLoadGeneration.current += 1;+ sttLoadedByThisPage.current = null;+ setSelectedSttRepo(null);+ };+ if (!owned) {+ forget();+ return;+ }+ // Forget only once released, else a failed unload leaves the model in VRAM with no Eject.+ await unloadSttModel(sttEngineForRepoId(selected), claim);+ forget();+ await refreshSttStatus();+ }, [refreshSttStatus, sttReady, sttLoadedModel]);++ const ensureSttLoaded = useCallback(+ async (+ repoId: string,+ sidecarKey: string,+ engine: AudioSttEngine,+ ) => {+ const generation = ++sttLoadGeneration.current;+ const controller = new AbortController();+ sttLoadingGeneration.current = generation;+ sttLoadAbort.current = controller;+ const isCurrent = () =>+ generation === sttLoadGeneration.current &&+ activeRef.current &&+ selectedSttRepoRef.current === repoId;++ setBusy("loading");+ // Claim ownership only once resident: a cancelled download would otherwise unload another surface's model.+ const toastId = toast.loading(`Preparing ${audioModelLabel(sidecarKey)}…`);+ const ggufVariant =+ engine === "audiocpp"+ ? (sttGgufVariants.current.get(repoId.toLowerCase()) ?? null)+ : null;+ try {+ try {+ await loadSttModel(+ sidecarKey,+ engine,+ controller.signal,+ undefined,+ ggufVariant,+ );+ sttLoadedByThisPage.current = sidecarKey;+ } catch (error) {+ if (!(error instanceof SttModelNotDownloadedError)) throw error;+ if (!isCurrent()) return;+ await startSttDownload(+ sidecarKey,+ hfApiToken(getHfToken()),+ engine,+ ggufVariant,+ );+ if (!isTrackingSttDownload(sidecarKey, engine)) {+ trackSttDownload(sidecarKey, {+ warmSelectedVoiceModelOnComplete: false,+ engine,+ repoId,+ });+ }+ toast.dismiss(toastId);+ // Re-check ownership around every await: an old pick could replace a newer sidecar.+ for (;;) {+ await new Promise((resolve) => setTimeout(resolve, 1000));+ if (!isCurrent()) return;+ const stt = await fetchSttStatus(+ undefined,+ engine === "transformers" ? sidecarKey : undefined,+ );+ if (!isCurrent()) return;+ const block = sttEngineStatusFor(stt, sidecarKey, engine);+ const download = block?.download;+ // Cancel is terminal: never load a partial checkpoint.+ if (download?.cancelled) return;+ if (download?.error) throw new Error(download.error);+ if (!download?.downloading) break;+ }+ if (!isCurrent()) return;+ toast.loading(`Loading ${audioModelLabel(sidecarKey)}…`, {+ id: toastId,+ });+ await loadSttModel(+ sidecarKey,+ engine,+ controller.signal,+ undefined,+ ggufVariant,+ );+ sttLoadedByThisPage.current = sidecarKey;+ }+ if (isCurrent()) {+ setLastSttRepo(repoId);+ toast.success("Transcription model ready", { id: toastId });+ return true;+ }+ return false;+ } catch (error) {+ if (isCurrent()) {+ toast.error(+ error instanceof Error+ ? error.message+ : "Transcription model failed.",+ { id: toastId },+ );+ }+ } finally {+ if (!isCurrent()) toast.dismiss(toastId);+ if (sttLoadingGeneration.current === generation) {+ sttLoadingGeneration.current = null;+ await refreshSttStatus();+ if (+ generation === sttLoadGeneration.current &&+ sttLoadingGeneration.current === null+ ) {+ setBusy(null);+ }+ } else {+ toast.dismiss(toastId);+ }+ if (sttLoadAbort.current === controller) sttLoadAbort.current = null;+ }+ },+ [refreshSttStatus, setLastSttRepo],+ );++ return {+ lastSttRepo,+ selectedSttRepo,+ setSelectedSttRepo,+ sttLoadedModel,+ sttLoadedEngine,+ downloadedSttArtifacts,+ selectedSttRepoRef,+ sttStatusRefreshGeneration,+ audioCppRuntime,+ sttLoadGeneration,+ sttGgufVariants,+ setLastSttRepo,+ sttLoadingGeneration,+ sttLoadedByThisPage,+ sttLoadAbort,+ deferredSttLoad,+ refreshSttStatus,+ sttSelected,+ sttReady,+ releaseTranscribeSelection,+ ensureSttLoaded,+ };+}++export type SttSidecar = ReturnType<typeof useSttSidecar>;diff --git a/studio/frontend/src/features/audio/hooks/use-transcription.ts b/studio/frontend/src/features/audio/hooks/use-transcription.tsnew file mode 100644index 00000000000..5d8d1e05270--- /dev/null+++ b/studio/frontend/src/features/audio/hooks/use-transcription.ts@@ -0,0 +1,461 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { AUTH_SESSION_ENDING_EVENT } from "@/features/auth";+import {+ createAudioRecorder,+ PcmRecorder,+ type SegmentRecorder,+} from "@/features/chat/adapters/pcm-recorder";+import {+ StudioModelDictationAdapter,+} from "@/features/chat/adapters/studio-model-dictation-adapter";+import { useVoiceSettingsStore } from "@/features/settings";+import { isTauri } from "@/lib/api-base";+import { copyToClipboard } from "@/lib/copy-to-clipboard";+import { toast } from "@/lib/toast";+import { transcribeWithProgress } from "../api";+import { micStreamRequestIsCurrent } from "../audio-page-policy";+import {+ RECORDING_CHUNK_MS,+ RECORDING_MAX_BYTES,+ RECORDING_MAX_SECONDS,+} from "../audio-workspace-constants";+import { sttEngineForRepoId, sttSidecarKeyFor } from "../catalog";+import { downloadTranscript } from "../transcript-download";+import {+ readTranscriptDraft,+ transcriptDraftKey,+ writeTranscriptDraft,+} from "../transcript-draft";+import type {+ TranscriptProgress,+ TranscriptRecord,+} from "../transcript-stream";+import type { AudioHostState } from "./audio-host-state";+import type { SttSidecar } from "./use-stt-sidecar";++export function useTranscription({+ active,+ activeRef,+ busyRef,+ setBusy,+ lastSttRepo,+ selectedSttRepoRef,+ setSelectedSttRepo,+ sttLoadedModel,+ sttLoadedEngine,+ ensureSttLoaded,+ setLastSttRepo,+ refreshSttStatus,+}: Pick<AudioHostState, "active" | "activeRef" | "busyRef" | "setBusy"> &+ Pick<+ SttSidecar,+ | "lastSttRepo"+ | "selectedSttRepoRef"+ | "setSelectedSttRepo"+ | "sttLoadedModel"+ | "sttLoadedEngine"+ | "ensureSttLoaded"+ | "setLastSttRepo"+ | "refreshSttStatus"+ >) {+ const [draftKey] = useState(transcriptDraftKey);+ const [recoveredTranscript] = useState(() => readTranscriptDraft(draftKey));+ const [transcript, setTranscript] = useState(recoveredTranscript?.text ?? "");+ const [transcribedName, setTranscribedName] = useState<string | null>(recoveredTranscript?.title ?? null);+ const [transcriptModel, setTranscriptModel] = useState(recoveredTranscript?.model ?? "");+ const [transcriptRecord, setTranscriptRecord] = useState<TranscriptRecord | null>(null);+ const [transcriptExported, setTranscriptExported] = useState(false);+ const transcriptVersion = useRef(0);+ const [transcriptionStartedAt, setTranscriptionStartedAt] = useState<number | null>(null);+ const [transcriptionFinishedAt, setTranscriptionFinishedAt] = useState<number | null>(null);+ const [transcriptionStopping, setTranscriptionStopping] = useState(false);+ const [transcriptionProgress, setTranscriptionProgress] = useState<TranscriptProgress | null>(null);+ const [transcriptError, setTranscriptError] = useState<string | null>(null);+ const [isRecording, setIsRecording] = useState(false);+ const [micRequestPending, setMicRequestPending] = useState(false);+ /** WebKit lacks MediaRecorder, and http LAN origins have no navigator.mediaDevices. */+ const recordingSupported = useMemo(+ () => StudioModelDictationAdapter.isSupported(),+ [],+ );+ const recorderRef = useRef<SegmentRecorder | null>(null);+ const recordStreamRef = useRef<MediaStream | null>(null);+ const discardRecordingRef = useRef(false);+ const micRequestGeneration = useRef(0);+ const micPendingGeneration = useRef<number | null>(null);+ const transcriptionAbort = useRef<AbortController | null>(null);++ const stopRecordStream = useCallback(() => {+ for (const track of recordStreamRef.current?.getTracks() ?? [])+ track.stop();+ recordStreamRef.current = null;+ }, []);+ const stopAndDiscardRecording = useCallback(() => {+ micRequestGeneration.current += 1;+ micPendingGeneration.current = null;+ setMicRequestPending(false);+ const recorder = recorderRef.current;+ if (recorder) {+ discardRecordingRef.current = true;+ if (recorder.state !== "inactive") recorder.stop();+ recorderRef.current = null;+ setIsRecording(false);+ }+ stopRecordStream();+ }, [stopRecordStream]);++ const clearTranscript = useCallback(() => {+ transcriptVersion.current += 1;+ setTranscript("");+ setTranscribedName(null);+ setTranscriptError(null);+ setTranscriptModel("");+ setTranscriptRecord(null);+ setTranscriptExported(false);+ }, []);++ const confirmTranscriptReplacement = useCallback(() => {+ if (busyRef.current !== null) return false;+ return (+ !transcript ||+ transcriptRecord !== null ||+ transcriptExported ||+ window.confirm(+ "This transcript could not be saved. Download it before continuing, or continue and discard it?",+ )+ );+ }, [transcript, transcriptRecord, transcriptExported]);++ useEffect(() => {+ const unsaved = Boolean(+ transcript && transcriptRecord === null && !transcriptExported,+ );+ if (!writeTranscriptDraft(+ draftKey,+ unsaved ? {+ text: transcript,+ title: transcribedName ?? "Transcript",+ model: transcriptModel,+ } : null,+ )) {+ toast.error("Could not update transcript recovery. Download unsaved text before leaving.");+ }+ if (isTauri) {+ void import("@tauri-apps/api/core")+ .then(({ invoke }) =>+ invoke("set_renderer_activity", {+ kind: "unsaved_transcript",+ active: unsaved,+ }),+ )+ .catch(() =>+ toast.error("Could not update transcript close protection."),+ );+ }+ if (!unsaved) return;+ const warn = (event: BeforeUnloadEvent) => {+ event.preventDefault();+ event.returnValue = "";+ };+ const confirmLogout = (event: Event) => {+ if (+ !window.confirm(+ "This transcript could not be saved. Download it before logging out, or log out and discard it?",+ )+ ) {+ event.preventDefault();+ } else if (!writeTranscriptDraft(draftKey, null)) {+ event.preventDefault();+ toast.error("Could not discard the transcript recovery copy. Try again.");+ }+ };+ window.addEventListener("beforeunload", warn);+ window.addEventListener(AUTH_SESSION_ENDING_EVENT, confirmLogout);+ return () => {+ window.removeEventListener("beforeunload", warn);+ window.removeEventListener(AUTH_SESSION_ENDING_EVENT, confirmLogout);+ };+ }, [draftKey, transcript, transcribedName, transcriptModel, transcriptRecord, transcriptExported]);++ const prepareTranscriptionModel = useCallback(async () => {+ const repo = selectedSttRepoRef.current ?? lastSttRepo;+ if (!repo) {+ toast.info("Pick a speech-to-text model first.");+ return null;+ }+ selectedSttRepoRef.current = repo;+ setSelectedSttRepo(repo);+ const model = sttSidecarKeyFor(repo);+ const engine = sttEngineForRepoId(repo);+ if (sttLoadedModel !== model || sttLoadedEngine !== engine) {+ if (!(await ensureSttLoaded(repo, model, engine))) return null;+ }+ setLastSttRepo(repo);+ return { model, engine };+ }, [+ lastSttRepo,+ sttLoadedModel,+ sttLoadedEngine,+ ensureSttLoaded,+ setLastSttRepo,+ ]);++ const runTranscription = useCallback(+ async (blob: Blob, name: string, confirmedVersion?: number) => {+ if (+ transcriptionAbort.current ||+ busyRef.current !== null ||+ (confirmedVersion !== transcriptVersion.current &&+ !confirmTranscriptReplacement())+ ) return;+ let started = false;+ const controller = new AbortController();+ transcriptionAbort.current = controller;+ try {+ const target = await prepareTranscriptionModel();+ if (!target || controller.signal.aborted || !activeRef.current) return;+ setBusy("transcribing");+ clearTranscript();+ setTranscribedName(name);+ setTranscriptModel(target.model);+ started = true;+ setTranscriptionStartedAt(Date.now());+ setTranscriptionFinishedAt(null);+ setTranscriptionStopping(false);+ setTranscriptionProgress(null);+ const result = await transcribeWithProgress(+ blob,+ name,+ {+ ...target,+ device: useVoiceSettingsStore.getState().sttDevice,+ signal: controller.signal,+ },+ (progress) => {+ if (!controller.signal.aborted) setTranscriptionProgress(progress);+ },+ );+ if (controller.signal.aborted) return;+ setTranscript(result.text);+ setTranscriptModel(result.model);+ setTranscriptRecord(result.record);+ if (!result.text)+ toast.info("The model heard no speech in that audio.");+ else if (!result.record)+ toast.error(+ "Transcript could not be saved. Download a copy to keep it.",+ );+ } catch (error) {+ if (controller.signal.aborted) {+ setTranscriptError("Transcription cancelled.");+ return;+ }+ const message =+ error instanceof Error ? error.message : "Transcription failed.";+ setTranscriptError(message);+ toast.error(message);+ } finally {+ if (transcriptionAbort.current === controller) {+ transcriptionAbort.current = null;+ if (started) setTranscriptionFinishedAt(Date.now());+ setBusy(null);+ if (activeRef.current) void refreshSttStatus();+ }+ }+ },+ [+ clearTranscript,+ confirmTranscriptReplacement,+ prepareTranscriptionModel,+ refreshSttStatus,+ ],+ );++ const handleRecordToggle = useCallback(async () => {+ if (isRecording) {+ const recorder = recorderRef.current;+ if (recorder && recorder.state !== "inactive") recorder.stop();+ return;+ }+ if (micPendingGeneration.current !== null || busyRef.current !== null) return;+ if (!confirmTranscriptReplacement()) return;+ const confirmedVersion = transcriptVersion.current;+ const requestGeneration = ++micRequestGeneration.current;+ micPendingGeneration.current = requestGeneration;+ setMicRequestPending(true);+ try {+ if (+ !(await prepareTranscriptionModel()) ||+ !activeRef.current ||+ micRequestGeneration.current !== requestGeneration+ ) return;+ const stream = await navigator.mediaDevices.getUserMedia({+ audio: { echoCancellation: true, noiseSuppression: true },+ });+ if (+ !micStreamRequestIsCurrent(+ requestGeneration,+ micRequestGeneration.current,+ activeRef.current,+ )+ ) {+ for (const track of stream.getTracks()) track.stop();+ return;+ }+ recordStreamRef.current = stream;+ const recorder = createAudioRecorder(stream);+ const maxSeconds =+ recorder instanceof PcmRecorder+ ? Math.min(+ RECORDING_MAX_SECONDS,+ recorder.secondsWithin(RECORDING_MAX_BYTES),+ )+ : RECORDING_MAX_SECONDS;+ const chunks: Blob[] = [];+ let recordedBytes = 0;+ let limitHit: "duration" | "size" | null = null;+ const stopAtLimit = (reason: "duration" | "size") => {+ if (limitHit) return;+ limitHit = reason;+ toast.warning(+ reason === "duration"+ ? `Recording stopped at the ${Math.floor(maxSeconds / 60)} minute limit.`+ : "Recording stopped: it reached the maximum upload size.",+ );+ try {+ recorder.stop();+ } catch {+ }+ };+ const durationTimer = window.setTimeout(+ () => stopAtLimit("duration"),+ maxSeconds * 1000,+ );+ recorder.addEventListener("dataavailable", (event) => {+ if (event.data.size > 0) {+ if (recordedBytes + event.data.size > RECORDING_MAX_BYTES) {+ stopAtLimit("size");+ return;+ }+ chunks.push(event.data);+ recordedBytes += event.data.size;+ }+ });+ recorder.addEventListener("stop", () => {+ window.clearTimeout(durationTimer);+ const discard = discardRecordingRef.current;+ discardRecordingRef.current = false;+ setIsRecording(false);+ stopRecordStream();+ recorderRef.current = null;+ const blob = new Blob(chunks, {+ type: recorder.mimeType || "audio/webm",+ });+ if (!discard && blob.size > 0)+ void runTranscription(blob, "Recording", confirmedVersion);+ });+ recorderRef.current = recorder;+ // A timeslice makes the byte cap observable; without one some browsers emit only on stop.+ recorder.start(RECORDING_CHUNK_MS);+ setIsRecording(true);+ } catch {+ // Release the stream if MediaRecorder construction failed, or the mic stays live.+ recorderRef.current = null;+ setIsRecording(false);+ stopRecordStream();+ if (+ micStreamRequestIsCurrent(+ requestGeneration,+ micRequestGeneration.current,+ activeRef.current,+ )+ )+ toast.error("Could not access the microphone.");+ } finally {+ if (micPendingGeneration.current === requestGeneration) {+ micPendingGeneration.current = null;+ setMicRequestPending(false);+ }+ }+ }, [+ isRecording,+ runTranscription,+ stopRecordStream,+ prepareTranscriptionModel,+ confirmTranscriptReplacement,+ ]);++ // Release the microphone on unmount AND whenever the page goes inactive: the page stays mounted+ // across tab switches, so unmount alone left a hidden recorder capturing.+ useEffect(() => {+ if (!active) {+ stopAndDiscardRecording();+ }+ return stopAndDiscardRecording;+ }, [active, stopAndDiscardRecording]);++ useEffect(() => () => transcriptionAbort.current?.abort(), []);++ const handleTranscribeFile = useCallback(+ (file: File | undefined) => {+ if (!file) return;+ void runTranscription(file, file.name);+ },+ [runTranscription],+ );++ const handleCopyTranscript = useCallback(() => {+ void copyToClipboard(transcript).then((ok) =>+ ok+ ? toast.success("Transcript copied")+ : toast.error("Could not copy the transcript."),+ );+ }, [transcript]);++ const handleDownloadTranscript = useCallback(async () => {+ const version = transcriptVersion.current;+ if (+ (await downloadTranscript(transcript, transcribedName ?? "transcript")) &&+ transcriptVersion.current === version+ )+ setTranscriptExported(true);+ }, [transcript, transcribedName]);++ return {+ transcript,+ setTranscript,+ transcribedName,+ setTranscribedName,+ transcriptModel,+ setTranscriptModel,+ transcriptRecord,+ setTranscriptRecord,+ transcriptExported,+ setTranscriptExported,+ transcriptVersion,+ transcriptionStartedAt,+ setTranscriptionStartedAt,+ transcriptionFinishedAt,+ transcriptionStopping,+ setTranscriptionStopping,+ transcriptionProgress,+ transcriptError,+ setTranscriptError,+ isRecording,+ micRequestPending,+ recordingSupported,+ transcriptionAbort,+ stopAndDiscardRecording,+ clearTranscript,+ confirmTranscriptReplacement,+ handleRecordToggle,+ handleTranscribeFile,+ handleCopyTranscript,+ handleDownloadTranscript,+ };+}++export type Transcription = ReturnType<typeof useTranscription>;diff --git a/studio/frontend/src/features/audio/pages/music-page.tsx b/studio/frontend/src/features/audio/pages/music-page.tsxnew file mode 100644index 00000000000..ee859425faa--- /dev/null+++ b/studio/frontend/src/features/audio/pages/music-page.tsx@@ -0,0 +1,44 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import type { ComponentProps } from "react";+import type { ModelOption } from "@/features/model-picker/components/model-selector/types";+import { isMusicGenerationModel, macTtsCatalogChoiceIsRunnable } from "../catalog";+import { TtsOutput, TtsRailFields } from "./tts-workspace";++export function musicPageModels(+ models: ModelOption[],+ isMac: boolean,+): ModelOption[] {+ return models.filter(+ (model) =>+ isMusicGenerationModel(model.id, model.audioType) &&+ (!isMac || macTtsCatalogChoiceIsRunnable(model.id)),+ );+}++export function MusicRail(+ props: Omit<ComponentProps<typeof TtsRailFields>, "musicGeneration">,+) {+ return <TtsRailFields {...props} musicGeneration={true} />;+}++export function MusicOutput(+ {+ modelReady,+ ...props+ }: Omit<ComponentProps<typeof TtsOutput>, "emptyText"> & {+ modelReady: boolean;+ },+) {+ return (+ <TtsOutput+ {...props}+ emptyText={+ modelReady+ ? "Generated music lands here. Write lyrics or a description, then press Generate."+ : "Generated music lands here. Load a music model, write lyrics or a description, and press Generate."+ }+ />+ );+}diff --git a/studio/frontend/src/features/audio/pages/speak-page.tsx b/studio/frontend/src/features/audio/pages/speak-page.tsxnew file mode 100644index 00000000000..af0a9293414--- /dev/null+++ b/studio/frontend/src/features/audio/pages/speak-page.tsx@@ -0,0 +1,44 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import type { ComponentProps } from "react";+import type { ModelOption } from "@/features/model-picker/components/model-selector/types";+import { isMusicGenerationModel, macTtsCatalogChoiceIsRunnable } from "../catalog";+import { TtsOutput, TtsRailFields } from "./tts-workspace";++export function speakPageModels(+ models: ModelOption[],+ isMac: boolean,+): ModelOption[] {+ return models.filter(+ (model) =>+ !isMusicGenerationModel(model.id, model.audioType) &&+ (!isMac || macTtsCatalogChoiceIsRunnable(model.id)),+ );+}++export function SpeakRail(+ props: Omit<ComponentProps<typeof TtsRailFields>, "musicGeneration">,+) {+ return <TtsRailFields {...props} musicGeneration={false} />;+}++export function SpeakOutput(+ {+ modelReady,+ ...props+ }: Omit<ComponentProps<typeof TtsOutput>, "emptyText"> & {+ modelReady: boolean;+ },+) {+ return (+ <TtsOutput+ {...props}+ emptyText={+ modelReady+ ? "Generated speech lands here. Type a sentence and press Generate."+ : "Generated speech lands here. Load a TTS model, type a sentence, and press Generate."+ }+ />+ );+}diff --git a/studio/frontend/src/features/audio/pages/transcribe-page.tsx b/studio/frontend/src/features/audio/pages/transcribe-page.tsxnew file mode 100644index 00000000000..db6ce1acd74--- /dev/null+++ b/studio/frontend/src/features/audio/pages/transcribe-page.tsx@@ -0,0 +1,248 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { Button } from "@/components/ui/button";+import {+ Download01Icon,+ Mic01Icon,+ StopIcon,+} from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import { Field } from "../components/field";+import { TranscriptGallery } from "../transcript-gallery";+import { TranscriptionProgress } from "../transcription-progress";+import type { AudioHostState } from "../hooks/audio-host-state";+import type { SttSidecar } from "../hooks/use-stt-sidecar";+import type { Transcription } from "../hooks/use-transcription";++export function TranscribeRail({+ recordingSupported,+ isRecording,+ sttSelected,+ lastSttRepo,+ busy,+ micRequestPending,+ handleRecordToggle,+ handleTranscribeFile,+}: Pick<+ Transcription,+ | "recordingSupported"+ | "isRecording"+ | "micRequestPending"+ | "handleRecordToggle"+ | "handleTranscribeFile"+> &+ Pick<SttSidecar, "sttSelected" | "lastSttRepo"> &+ Pick<AudioHostState, "busy">) {+ return (+ <>+ <Field+ label="Microphone"+ htmlFor="audio-record"+ hint={+ recordingSupported+ ? "Record a clip and it is transcribed when you stop."+ : "This browser cannot record. Open Unsloth over https or on localhost, or upload a file below."+ }+ >+ <Button+ data-tour="audio-record"+ id="audio-record"+ variant={isRecording ? "destructive" : "secondary"}+ disabled={+ !recordingSupported ||+ (!isRecording && (!(sttSelected || lastSttRepo) || busy !== null)) ||+ micRequestPending+ }+ onClick={handleRecordToggle}+ >+ <HugeiconsIcon+ icon={isRecording ? StopIcon : Mic01Icon}+ className="mr-2 size-4"+ />+ {isRecording+ ? "Stop recording"+ : micRequestPending+ ? busy === "loading" ? "Loading model…" : "Waiting for microphone…"+ : "Record"}+ </Button>+ </Field>+ <Field+ label="Audio file"+ htmlFor="audio-file"+ hint="Or transcribe an existing recording (wav, mp3, m4a, webm…)."+ >+ <input+ id="audio-file"+ type="file"+ accept="audio/*"+ disabled={+ !(sttSelected || lastSttRepo) ||+ busy !== null ||+ isRecording ||+ micRequestPending+ }+ onChange={(event) => {+ handleTranscribeFile(event.target.files?.[0]);+ event.target.value = "";+ }}+ className="text-ui-13 file:mr-3 file:rounded-md file:border-0 file:bg-muted file:px-3 file:py-1.5 file:text-ui-13 file:font-medium"+ />+ </Field>+ {sttSelected || lastSttRepo ? null : (+ <p className="text-ui-11p5 leading-snug text-muted-foreground">+ Pick a speech-to-text model (Whisper or Qwen3-ASR) from the+ selector above to transcribe.+ </p>+ )}+ </>+ );+}++export function TranscribeOutput({+ transcriptionStartedAt,+ transcriptionFinishedAt,+ transcriptionStopping,+ transcriptionProgress,+ setTranscriptionStopping,+ transcriptionAbort,+ transcript,+ handleCopyTranscript,+ handleDownloadTranscript,+ transcribedName,+ transcriptModel,+ transcriptRecord,+ transcriptExported,+ transcriptError,+ busy,+ active,+ mode,+ confirmTranscriptReplacement,+ transcriptVersion,+ setTranscript,+ setTranscribedName,+ setTranscriptModel,+ setTranscriptRecord,+ setTranscriptError,+ setTranscriptExported,+ setTranscriptionStartedAt,+ clearTranscript,+}: Pick<+ Transcription,+ | "transcriptionStartedAt"+ | "transcriptionFinishedAt"+ | "transcriptionStopping"+ | "transcriptionProgress"+ | "setTranscriptionStopping"+ | "transcriptionAbort"+ | "transcript"+ | "handleCopyTranscript"+ | "handleDownloadTranscript"+ | "transcribedName"+ | "transcriptModel"+ | "transcriptRecord"+ | "transcriptExported"+ | "transcriptError"+ | "confirmTranscriptReplacement"+ | "transcriptVersion"+ | "setTranscript"+ | "setTranscribedName"+ | "setTranscriptModel"+ | "setTranscriptRecord"+ | "setTranscriptError"+ | "setTranscriptExported"+ | "setTranscriptionStartedAt"+ | "clearTranscript"+> &+ Pick<AudioHostState, "busy" | "active" | "mode">) {+ return (+ <>+ <div className="hover-scrollbar flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto">+ {transcriptionStartedAt !== null && (+ <TranscriptionProgress+ startedAt={transcriptionStartedAt}+ finishedAt={transcriptionFinishedAt}+ stopping={transcriptionStopping}+ progress={transcriptionProgress}+ onCancel={() => {+ setTranscriptionStopping(true);+ transcriptionAbort.current?.abort();+ }}+ />+ )}+ {transcript ? (+ <>+ <div className="flex items-center gap-2">+ <Button+ variant="secondary"+ size="sm"+ onClick={handleCopyTranscript}+ >+ Copy+ </Button>+ <Button+ variant="secondary"+ size="sm"+ onClick={handleDownloadTranscript}+ >+ <HugeiconsIcon icon={Download01Icon} className="mr-2 size-3.5" />+ Download .txt+ </Button>+ </div>+ <div className="flex items-center gap-2 text-ui-11p5 text-muted-foreground">+ <span className="truncate">{transcribedName}</span>+ <span>·</span>+ <span className="truncate">{transcriptModel}</span>+ {!transcriptRecord && !transcriptExported && (+ <span>· Not saved</span>+ )}+ </div>+ <p className="whitespace-pre-wrap text-sm leading-relaxed text-foreground">+ {transcript}+ </p>+ </>+ ) : transcriptError ? (+ <div className="flex flex-col gap-1" role="alert">+ <p className="text-ui-13 font-medium text-destructive">+ Could not transcribe {transcribedName ?? "that audio"}.+ </p>+ <p className="text-ui-13 text-muted-foreground">{transcriptError}</p>+ </div>+ ) : busy !== "transcribing" ? (+ <p className="text-ui-13 text-muted-foreground">+ Record or upload audio to transcribe. Completed transcripts are saved+ to history.+ </p>+ ) : null}+ </div>+ <div className="shrink-0 pt-4">+ <TranscriptGallery+ autoSelect={!transcript && !transcribedName && busy === null}+ active={active && mode === "transcribe"}+ currentId={transcriptRecord?.id ?? null}+ latest={transcriptRecord}+ canSelect={confirmTranscriptReplacement}+ onSelect={(record) => {+ transcriptVersion.current += 1;+ setTranscript(record.text);+ setTranscribedName(record.title);+ setTranscriptModel(record.model);+ setTranscriptRecord(record);+ setTranscriptError(null);+ setTranscriptExported(false);+ setTranscriptionStartedAt(null);+ }}+ onDelete={(ids) => {+ if (+ transcriptRecord &&+ (ids === null+ ? !transcriptRecord.archived+ : ids.includes(transcriptRecord.id))+ )+ clearTranscript();+ }}+ />+ </div>+ </>+ );+}diff --git a/studio/frontend/src/features/audio/pages/tts-workspace.tsx b/studio/frontend/src/features/audio/pages/tts-workspace.tsxnew file mode 100644index 00000000000..418d8d14b76--- /dev/null+++ b/studio/frontend/src/features/audio/pages/tts-workspace.tsx@@ -0,0 +1,637 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import type { ReactNode } from "react";+import { AdvancedDisclosure } from "@/components/advanced-disclosure";+import {+ GalleryItemMenu,+ GalleryPinBadge,+} from "@/components/gallery-item-menu";+import { StripDropLine } from "@/components/gallery-strip-reorder";+import { Button } from "@/components/ui/button";+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";+import { Progress } from "@/components/ui/progress";+import { Spinner } from "@/components/ui/spinner";+import { Textarea } from "@/components/ui/textarea";+import { ParamSlider } from "@/features/chat";+import { formatRelativeShort } from "@/features/hub/lib/format";+import { PillTabs } from "@/features/model-picker/components/model-selector/pill-tabs";+import { toast } from "@/lib/toast";+import { cn } from "@/lib/utils";+import {+ AudioWave01Icon,+ Copy01Icon,+ SparklesIcon,+ StopIcon,+} from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import { addAudioClipToProject, type AudioGalleryClip } from "../api";+import { AudioOptionFields } from "../audio-options-fields";+import {+ type audioGenerationPresentation,+ MINIMAX_MUSIC_DEFAULT_SECONDS,+ MINIMAX_MUSIC_FRAMES_PER_SECOND,+ MOSS_TTS_DEFAULT_SECONDS,+ MOSS_TTS_FRAMES_PER_SECOND,+} from "../audio-page-policy";+import { TTS_MAX_TOKENS } from "../audio-workspace-constants";+import { audioModelLabel, formatClipDuration } from "../audio-workspace-utils";+import {+ ClipCard,+ type ClipSendHandlers,+ ClipSendToMenu,+ PendingClipCard,+} from "../components/clip-card";+import { Field } from "../components/field";+import type { AudioHostState } from "../hooks/audio-host-state";+import type { AudioGallery } from "../hooks/use-audio-gallery";+import type { AudioModelSlot } from "../hooks/use-audio-model-slot";+import type { SpeechGeneration } from "../hooks/use-speech-generation";+import type { AudioWorkflowId } from "../workflows";++export interface GenerateAction {+ label: string;+ onClick: () => void;+}++export interface GenerateBlocker {+ reason: string;+ actions?: GenerateAction[];+}++function GenerateActions({ actions }: { actions?: GenerateAction[] }) {+ if (!actions?.length) return null;+ return (+ <>+ {actions.map((action, index) => (+ <span key={action.label}>+ {index === 0 ? " " : " or "}+ <Button+ type="button"+ variant="link"+ className="h-auto p-0 text-ui-11p5 font-medium text-foreground"+ onClick={action.onClick}+ >+ {action.label}+ </Button>+ </span>+ ))}+ </>+ );+}++export function TtsRailFields({+ musicGeneration,+ prompt,+ setPrompt,+ toolPanels,+ audioDevice,+ busy,+ isRecording,+ status,+ setAudioDeviceState,+ ttsLoaded,+ handleEject,+ samplingControls,+ audioOptionSpecs,+ advancedOpen,+ setAdvancedOpen,+ temperature,+ mossFrameLimit,+ handleTemperatureChange,+ musicSeconds,+ musicRange,+ setMinimaxMaxSeconds,+ cudaMusicGeneration,+ mossMaxSeconds,+ mossMaxSecondsLimit,+ setMossMaxSeconds,+ maxTokens,+ setMaxTokens,+ audioOptionValues,+ handleAudioOptionChange,+ handleAudioOptionsReset,+}: Pick<+ SpeechGeneration,+ | "prompt"+ | "setPrompt"+ | "samplingControls"+ | "audioOptionSpecs"+ | "temperature"+ | "mossFrameLimit"+ | "handleTemperatureChange"+ | "musicSeconds"+ | "musicRange"+ | "setMinimaxMaxSeconds"+ | "cudaMusicGeneration"+ | "mossMaxSeconds"+ | "mossMaxSecondsLimit"+ | "setMossMaxSeconds"+ | "maxTokens"+ | "setMaxTokens"+ | "audioOptionValues"+ | "handleAudioOptionChange"+ | "handleAudioOptionsReset"+ | "ttsLoaded"+> &+ Pick<AudioHostState, "audioDevice" | "busy" | "status" | "setAdvancedOpen"> &+ Pick<AudioModelSlot, "handleEject"> & {+ musicGeneration: boolean;+ toolPanels: ReactNode;+ isRecording: boolean;+ setAudioDeviceState: (next: string) => void;+ advancedOpen: boolean;+ }) {+ return (+ <>+ {/* Field inlined: its label needs a form control to point+ at, and PillTabs is a tablist with its own name. */}+ <div className="grid gap-1.5">+ <span className="text-ui-13 font-medium text-foreground">+ Load model into+ </span>+ <PillTabs+ ariaLabel="Load model into"+ value={audioDevice === "cpu" ? "cpu" : "auto"}+ disabled={busy !== null || isRecording}+ onValueChange={(value) => {+ const next = value === "cpu" ? "cpu" : "auto";+ if (next === audioDevice) return;+ // MiniMax needs CUDA; the backend refusal cannot save an already-ejected model.+ if (next === "cpu" && status?.audio_type === "minimax_music3") {+ toast.info(+ "MiniMax Music 3 needs a GPU, so it cannot be held in CPU RAM.",+ );+ return;+ }+ setAudioDeviceState(next);+ if (ttsLoaded) handleEject();+ }}+ fit={true}+ className="h-[calc(30px*var(--ui-space-scale,1))] self-start [&>button]:h-[calc(30px*var(--ui-space-scale,1))] [&>button]:px-6"+ tabs={[+ { value: "auto", label: "GPU when available" },+ { value: "cpu", label: "CPU RAM" },+ ]}+ />+ {/* Phrased as what the next load will do, not as the resident+ model's state: a model loaded by another tab or client can+ be on the other device, and status does not report it. */}+ <p className="text-ui-11p5 leading-snug text-muted-foreground">+ {audioDevice === "cpu"+ ? "New loads go into system RAM instead of the GPU. Slower to generate, and no GPU memory is used."+ : "New loads use the GPU when there is one, and the CPU otherwise."}+ </p>+ </div>+ <Field+ label={musicGeneration ? "Lyrics" : "Text"}+ htmlFor="audio-prompt"+ hint={+ musicGeneration+ ? "Lyrics may use sections such as [verse] and [chorus]. The completed song lands in the gallery."+ : "What the model should say. Generation runs on the loaded TTS model and lands in the gallery."+ }+ >+ <Textarea+ id="audio-prompt"+ value={prompt}+ onChange={(event) => setPrompt(event.target.value)}+ placeholder={+ musicGeneration+ ? "[verse]\nMorning light through the pines…\n\n[chorus]\n…"+ : "Type the sentence to speak…"+ }+ className="min-h-28"+ />+ </Field>+ {toolPanels}+ {musicGeneration || samplingControls || audioOptionSpecs.length > 0 ? (+ <AdvancedDisclosure+ open={advancedOpen}+ onOpenChange={setAdvancedOpen}+ description={+ musicGeneration+ ? "Generation length and model options. Changes apply to the next audio clip."+ : samplingControls+ ? "Generation sampling. Changes apply to the next audio clip."+ : "Model options. Changes apply to the next audio clip."+ }+ >+ {!musicGeneration && samplingControls ? (+ <ParamSlider+ label="Temperature"+ value={temperature}+ min={0}+ max={mossFrameLimit !== null ? 2 : 1.5}+ step={0.05}+ onChange={handleTemperatureChange}+ />+ ) : null}+ {musicGeneration ? (+ <ParamSlider+ label="Max duration (seconds)"+ value={musicSeconds}+ min={musicRange.min}+ max={musicRange.max}+ step={1 / MINIMAX_MUSIC_FRAMES_PER_SECOND}+ onChange={setMinimaxMaxSeconds}+ valueSize={8}+ info={+ cudaMusicGeneration+ ? `Starts at ${MINIMAX_MUSIC_DEFAULT_SECONDS} seconds. MiniMax Music 3 generates ${MINIMAX_MUSIC_FRAMES_PER_SECOND} frames per second, up to ${musicRange.max} seconds.`+ : `Starts at ${MINIMAX_MUSIC_DEFAULT_SECONDS} seconds. This model generates between ${musicRange.min} and ${musicRange.max} seconds.`+ }+ />+ ) : mossFrameLimit !== null ? (+ <ParamSlider+ label="Max duration (seconds)"+ value={mossMaxSeconds}+ min={1}+ max={mossMaxSecondsLimit}+ step={1 / MOSS_TTS_FRAMES_PER_SECOND}+ onChange={setMossMaxSeconds}+ valueSize={8}+ info={`Starts at ${MOSS_TTS_DEFAULT_SECONDS} seconds. This model reports ${mossFrameLimit?.toLocaleString()} frames (${mossMaxSecondsLimit.toLocaleString(undefined, { maximumFractionDigits: 2 })} seconds); the prompt uses part of that context.`}+ />+ ) : samplingControls ? (+ <ParamSlider+ label="Max tokens"+ value={maxTokens}+ min={256}+ max={TTS_MAX_TOKENS}+ step={256}+ onChange={setMaxTokens}+ />+ ) : null}+ {audioOptionSpecs.length > 0 ? (+ <>+ <AudioOptionFields+ specs={audioOptionSpecs}+ values={audioOptionValues}+ onChange={handleAudioOptionChange}+ disabled={busy === "generating"}+ family={status?.audio_family}+ />+ {Object.keys(audioOptionValues).length > 0 ? (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="self-start"+ onClick={handleAudioOptionsReset}+ >+ Reset model options+ </Button>+ ) : null}+ </>+ ) : null}+ </AdvancedDisclosure>+ ) : null}+ </>+ );+}++export function TtsFooter({+ busy,+ generationPresentation,+ handleStopGeneration,+ handleGenerate,+ ttsLoaded,+ prompt,+ lyricsOptional,+ musicNeedsDescription,+ audioInstructions,+ blocker,+ shortcutLabel,+ error,+ elapsedSeconds,+ loadNote = null,+}: Pick<+ SpeechGeneration,+ | "handleGenerate"+ | "ttsLoaded"+ | "prompt"+ | "lyricsOptional"+ | "musicNeedsDescription"+ | "audioInstructions"+> &+ Pick<AudioHostState, "busy" | "handleStopGeneration"> & {+ generationPresentation: ReturnType<typeof audioGenerationPresentation>;+ blocker: GenerateBlocker | null;+ shortcutLabel: string;+ error: GenerateBlocker | null;+ elapsedSeconds: number | null;+ loadNote?: string | null;+ }) {+ return (+ <div className="flex w-full max-w-sm flex-col gap-2">+ {busy === "generating" && generationPresentation ? (+ <>+ <output+ aria-live="polite"+ aria-atomic="true"+ className="text-center text-ui-12 text-muted-foreground"+ >+ {generationPresentation.status}+ {elapsedSeconds !== null ? (+ <span className="ml-1.5 font-mono tabular-nums">+ {formatClipDuration(elapsedSeconds)}+ </span>+ ) : null}+ </output>+ <Progress+ indeterminate+ aria-label="Audio task in progress"+ className="h-1.5"+ />+ </>+ ) : null}+ {loadNote && !generationPresentation ? (+ <p className="text-center text-ui-11p5 leading-snug text-muted-foreground">+ {loadNote}+ </p>+ ) : null}+ <Button+ className={cn(+ "relative z-10 mx-auto h-11 px-8 disabled:bg-muted disabled:text-muted-foreground disabled:opacity-100",+ // Same Stop as Images: outline, neutral hover. Destructive is for deleting, not for stopping.+ generationPresentation && "hover:bg-muted dark:hover:bg-muted",+ )}+ onClick={+ generationPresentation?.canStop+ ? handleStopGeneration+ : handleGenerate+ }+ disabled={+ generationPresentation+ ? !generationPresentation.canStop+ : busy !== null ||+ !ttsLoaded ||+ (!prompt.trim() && !lyricsOptional) ||+ (musicNeedsDescription && !audioInstructions.trim())+ }+ variant={generationPresentation ? "outline" : "default"}+ aria-describedby={blocker ? "audio-generate-blocker" : undefined}+ aria-keyshortcuts="Control+Enter Meta+Enter"+ title={+ generationPresentation ? undefined : `Generate (${shortcutLabel})`+ }+ >+ {generationPresentation?.canStop ? (+ <>+ <HugeiconsIcon icon={StopIcon} className="mr-2 size-4" />+ Stop+ </>+ ) : generationPresentation ? (+ <>+ <Spinner className="mr-2 size-4" />+ {generationPresentation.actionLabel}+ </>+ ) : (+ "Generate"+ )}+ </Button>+ {blocker && !generationPresentation ? (+ <p+ id="audio-generate-blocker"+ className="text-center text-ui-11p5 leading-snug text-muted-foreground"+ >+ {blocker.reason}+ <GenerateActions actions={blocker.actions} />+ </p>+ ) : error && !generationPresentation ? (+ <p+ role="alert"+ className="text-center text-ui-11p5 leading-snug text-destructive"+ >+ {error.reason}+ <GenerateActions actions={error.actions} />+ </p>+ ) : null}+ </div>+ );+}++export function TtsOutput({+ workflow,+ clips,+ selectedClip,+ selectedClipSrc,+ srcById,+ peaksById,+ handleDownloadClip,+ handleDeleteClip,+ fallbackClip,+ handleDownloadFallbackClip,+ emptyText,+ handleClearGallery,+ historyReorder,+ hasMore,+ loadMore,+ selectedId,+ selectClip,+ handleTogglePin,+ active,+ handleArchiveClip,+ handleDownloadClipById,+ onUseTextAgain,+ handleCopyPrompt,+ sendHandlersFor,+ pending,+ freshClipId,+ onFreshClipFocused,+ announcement,+}: Pick<+ AudioGallery,+ | "srcById"+ | "peaksById"+ | "handleDownloadClip"+ | "handleDeleteClip"+ | "fallbackClip"+ | "handleDownloadFallbackClip"+ | "historyReorder"+ | "hasMore"+ | "loadMore"+ | "selectedId"+ | "selectClip"+ | "handleTogglePin"+ | "handleArchiveClip"+ | "handleDownloadClipById"+ | "handleCopyPrompt"+> &+ Pick<AudioHostState, "active"> & {+ workflow: AudioWorkflowId;+ clips: AudioGalleryClip[];+ selectedClip: AudioGalleryClip | null;+ selectedClipSrc: string | undefined;+ handleClearGallery: () => Promise<void>;+ onUseTextAgain: (clip: AudioGalleryClip) => void;+ sendHandlersFor: (clip: AudioGalleryClip) => ClipSendHandlers;+ pending: {+ title: string;+ status: string;+ elapsedSeconds: number | null;+ canStop: boolean;+ onStop: () => void;+ } | null;+ emptyText: string;+ freshClipId: string | null;+ onFreshClipFocused: () => void;+ announcement: string;+ }) {+ const clipMenu = (clip: AudioGalleryClip, variant: "row" | "toolbar") => (+ <GalleryItemMenu+ variant={variant}+ noun="clip"+ active={active}+ pinned={Boolean(clip.pinned)}+ archived={false}+ onTogglePin={() => void handleTogglePin(clip.id, !clip.pinned)}+ onToggleArchive={() => void handleArchiveClip(clip.id)}+ onDelete={() => void handleDeleteClip(clip.id)}+ onDownload={() => void handleDownloadClipById(clip)}+ onAddToProject={(projectId) => addAudioClipToProject(clip.id, projectId)}+ leadingItems={+ <>+ <ClipSendToMenu current={workflow} handlers={sendHandlersFor(clip)} />+ <DropdownMenuItem onClick={() => onUseTextAgain(clip)}>+ <HugeiconsIcon+ icon={SparklesIcon}+ strokeWidth={1.75}+ className="size-icon"+ />+ Use text again+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => void handleCopyPrompt(clip.prompt)}>+ <HugeiconsIcon+ icon={Copy01Icon}+ strokeWidth={1.75}+ className="size-icon"+ />+ Copy text+ </DropdownMenuItem>+ </>+ }+ />+ );+ return (+ <>+ <output aria-live="polite" aria-atomic="true" className="sr-only">+ {announcement}+ </output>+ <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-4">+ {pending ? (+ <PendingClipCard {...pending} />+ ) : selectedClip ? (+ <ClipCard+ // Keyed per clip: a reused player kept the old clip's position.+ key={selectedClip.id}+ title={selectedClip.prompt}+ model={selectedClip.model}+ createdAt={selectedClip.created_at}+ durationS={selectedClip.duration_s}+ src={selectedClipSrc ?? null}+ peaks={peaksById.get(selectedClip.id) ?? null}+ onDownload={+ srcById[selectedClip.id]+ ? () => handleDownloadClip(selectedClip)+ : null+ }+ menu={clipMenu(selectedClip, "row")}+ focusOnMount={selectedClip.id === freshClipId}+ onFocused={onFreshClipFocused}+ />+ ) : fallbackClip ? (+ <ClipCard+ title={fallbackClip.prompt}+ model={fallbackClip.model}+ durationS={null}+ src={fallbackClip.url}+ peaks={null}+ onDownload={handleDownloadFallbackClip}+ status={+ fallbackClip.saved+ ? "saved, waiting for the gallery"+ : "not saved to the gallery"+ }+ />+ ) : (+ <p className="text-ui-13 text-muted-foreground">{emptyText}</p>+ )}+ </div>+ {clips.length > 0 ? (+ <div className="flex shrink-0 flex-col gap-2">+ <div className="flex items-center justify-between">+ <span className="text-ui-11p5 font-medium text-muted-foreground">+ History+ </span>+ <Button+ variant="ghost"+ size="sm"+ onClick={() => void handleClearGallery()}+ >+ Clear all+ </Button>+ </div>+ <div+ {...historyReorder.stripProps}+ className="hover-scrollbar flex max-h-40 flex-col gap-1 overflow-y-auto py-1"+ onScroll={(event) => {+ const el = event.currentTarget;+ if (+ hasMore &&+ el.scrollTop + el.clientHeight >= el.scrollHeight - 40+ ) {+ void loadMore();+ }+ }}+ >+ {clips.map((clip) => (+ // Shell, not a button: the pin badge and dots menu are buttons and cannot nest.+ <div+ key={clip.id}+ {...historyReorder.tileProps(clip.id)}+ className={cn(+ "group relative flex items-center gap-1 rounded-md pr-1 transition-colors hover:bg-muted",+ clip.id === selectedId && "bg-muted",+ historyReorder.draggingId === clip.id && "opacity-40",+ )}+ >+ {historyReorder.cue?.id === clip.id && (+ <StripDropLine axis="y" edge={historyReorder.cue.edge} />+ )}+ <button+ type="button"+ onClick={() => selectClip(clip.id)}+ aria-current={clip.id === selectedId ? "true" : undefined}+ className="flex min-w-0 flex-1 items-center gap-2 px-2 py-1.5 text-left text-ui-13"+ >+ <HugeiconsIcon+ icon={AudioWave01Icon}+ className="size-3.5 shrink-0 text-muted-foreground"+ />+ <span className="min-w-0 flex-1 truncate">{clip.prompt}</span>+ <span className="hidden min-w-0 max-w-[45%] shrink truncate text-ui-11p5 text-muted-foreground @[30rem]:block">+ {audioModelLabel(clip.model)} ·{" "}+ {formatRelativeShort(clip.created_at)}+ </span>+ <span className="shrink-0 font-mono text-ui-11p5 tabular-nums text-muted-foreground">+ {formatClipDuration(clip.duration_s)}+ </span>+ </button>+ {clip.pinned && (+ <GalleryPinBadge+ noun="clip"+ className="static shrink-0"+ onUnpin={() => void handleTogglePin(clip.id, false)}+ />+ )}+ {clipMenu(clip, "row")}+ </div>+ ))}+ </div>+ </div>+ ) : null}+ </>+ );+}diff --git a/studio/frontend/src/features/audio/picker-filter.ts b/studio/frontend/src/features/audio/picker-filter.tsnew file mode 100644index 00000000000..c7c586c86f7--- /dev/null+++ b/studio/frontend/src/features/audio/picker-filter.ts@@ -0,0 +1,45 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Free of app imports so the node test runner can load it directly.++import { audioCppModelFor } from "./audio-cpp-catalog";+import { isMusicGenerationModel } from "./catalog";+import {+ type AudioWorkflowId,+ audioWorkflowForAudioType,+ audioWorkflowForTask,+} from "./workflows";++export interface AudioPickerRow {+ id?: string | null;+ task?: string | null;+ audioType?: string | null;+ audioWorkflows?: readonly string[] | null;+}++export function audioRowMatchesWorkflow(+ row: AudioPickerRow,+ workflow: AudioWorkflowId,+): boolean {+ if (row.audioWorkflows && row.audioWorkflows.length > 0) {+ return row.audioWorkflows.includes(workflow);+ }+ // MiniMax Music 3 is tagged text-to-speech on the Hub.+ if (isMusicGenerationModel(row.id, row.audioType)) return workflow === "music";+ const byTask = audioWorkflowForTask(row.task);+ if (byTask === "transcribe" || byTask === "music") {+ return byTask === workflow;+ }+ const catalogTask = audioCppModelFor(row.id)?.task;+ if (catalogTask === "music") {+ return workflow === "music";+ }+ if (catalogTask === "asr") {+ return workflow === "transcribe";+ }+ if (byTask === "speak" || catalogTask === "tts" || row.audioType) {+ return audioWorkflowForAudioType(row.audioType) === workflow;+ }+ return true;+}diff --git a/studio/frontend/src/features/audio/route-search.ts b/studio/frontend/src/features/audio/route-search.tsnew file mode 100644index 00000000000..21c69073fe6--- /dev/null+++ b/studio/frontend/src/features/audio/route-search.ts@@ -0,0 +1,90 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Free of app imports so the node test runner can load it directly.++import { AUDIO_CPP_AUDIO_TYPES, audioCppModelFor } from "./audio-cpp-catalog";+import {+ type AudioWorkflowId,+ MUSIC_AUDIO_TYPES,+ audioWorkflowForTask,+ isAudioWorkflowId,+} from "./workflows";++const NATIVE_AUDIO_TYPES = new Set([+ "higgs_tts2",+ "moss_tts_local",+ "moss_tts_nano",+ "higgs_tts3",+ "minimax_music3",+ ...AUDIO_CPP_AUDIO_TYPES,+]);++const AUDIO_ROUTE_TASKS: ReadonlySet<string> = new Set([+ "text-to-speech",+ "automatic-speech-recognition",+ "text-to-audio",+]);++export interface AudioRouteSearch {+ model?: string;+ quant?: string;+ ggufQuant?: string;+ task?: string;+ audioType?: string;+ loadId?: string;+ item?: string;+ workflow?: AudioWorkflowId;+}++export function validateAudioSearch(+ search: Record<string, unknown>,+): AudioRouteSearch {+ return {+ ...(typeof search.model === "string" ? { model: search.model } : {}),+ ...(typeof search.quant === "string" ? { quant: search.quant } : {}),+ ...(typeof search.ggufQuant === "string"+ ? { ggufQuant: search.ggufQuant }+ : {}),+ ...(typeof search.task === "string" && AUDIO_ROUTE_TASKS.has(search.task)+ ? { task: search.task }+ : {}),+ ...(typeof search.audioType === "string" &&+ NATIVE_AUDIO_TYPES.has(search.audioType)+ ? { audioType: search.audioType }+ : {}),+ ...(typeof search.loadId === "string" && search.loadId.trim()+ ? { loadId: search.loadId }+ : {}),+ ...(typeof search.item === "string" ? { item: search.item } : {}),+ ...(isAudioWorkflowId(search.workflow)+ ? { workflow: search.workflow }+ : {}),+ };+}++export function audioRouteIntent(search: {+ task?: string | null;+ workflow?: string | null;+}): AudioWorkflowId | null {+ if (isAudioWorkflowId(search.workflow)) {+ return search.workflow;+ }+ return audioWorkflowForTask(search.task);+}++export function audioWorkflowForPick(pick: {+ id: string;+ task?: string | null;+ audioType?: string | null;+}): AudioWorkflowId | null {+ const workflow = audioWorkflowForTask(pick.task);+ if (workflow !== null && workflow !== "speak") {+ return workflow;+ }+ // No task (or a speech one): the audio type or catalog entry can still say it makes music.+ const music =+ MUSIC_AUDIO_TYPES.has(pick.audioType ?? "") ||+ audioCppModelFor(pick.id)?.task === "music";+ return music ? "music" : workflow;+}diff --git a/studio/frontend/src/features/audio/stores/audio-workspace-store.ts b/studio/frontend/src/features/audio/stores/audio-workspace-store.tsnew file mode 100644index 00000000000..fd701cf5355--- /dev/null+++ b/studio/frontend/src/features/audio/stores/audio-workspace-store.ts@@ -0,0 +1,34 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { create } from "zustand";+import type { AudioWorkflowId } from "../workflows";++/** Only the page commits `workflow`; the sidebar and deep links put a request in+ * `requestedWorkflow`, which the page takes once it is free to switch, like an in-page tab click. */+interface AudioWorkspaceState {+ workflow: AudioWorkflowId;+ workflowChosen: boolean;+ requestedWorkflow: AudioWorkflowId | null;+ navExpanded: boolean;+ commitWorkflow: (workflow: AudioWorkflowId) => void;+ adoptWorkflow: (workflow: AudioWorkflowId) => void;+ requestWorkflow: (workflow: AudioWorkflowId) => void;+ clearRequestedWorkflow: () => void;+ setNavExpanded: (expanded: boolean) => void;+}++export const useAudioWorkspaceStore = create<AudioWorkspaceState>()((set) => ({+ workflow: "speak",+ workflowChosen: false,+ requestedWorkflow: null,+ navExpanded: false,+ // Any committed switch settles a pending request, so a stale one never fires later.+ commitWorkflow: (workflow) =>+ set({ workflow, workflowChosen: true, requestedWorkflow: null }),+ adoptWorkflow: (workflow) =>+ set((state) => (state.workflowChosen ? state : { workflow })),+ requestWorkflow: (requestedWorkflow) => set({ requestedWorkflow }),+ clearRequestedWorkflow: () => set({ requestedWorkflow: null }),+ setNavExpanded: (navExpanded) => set({ navExpanded }),+}));diff --git a/studio/frontend/src/features/audio/tour/steps.tsx b/studio/frontend/src/features/audio/tour/steps.tsxindex 8d933959b82..db969633a18 100644--- a/studio/frontend/src/features/audio/tour/steps.tsx+++ b/studio/frontend/src/features/audio/tour/steps.tsx@@ -2,32 +2,39 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import type { TourStep } from "@/features/tour";+import type { AudioWorkflowId } from "../workflows";const modeStep: TourStep = {id: "mode",target: "audio-mode",- title: "Generate or Transcribe",+ title: "Speak, Music or Transcribe",body: (<>- Generate makes speech and music from text. Transcribe turns a recording- into text. They use different models, so the picker above follows the- mode.+ Open the page title to switch pages. Speak turns text into speech, Music+ makes songs and sound effects, and Transcribe turns a recording into text.+ Each lists only the models that can do it, so the picker above follows the+ page.</>),};-const modelStep: TourStep = {- id: "model",- target: "audio-model",- title: "Pick a model",- body: (- <>- TTS and music models for Generate, speech recognition for Transcribe.- Voices you fine-tuned show up under On Device.- </>- ),+const MODEL_STEP_BODY: Record<AudioWorkflowId, string> = {+ speak:+ "Text-to-speech models, including voices you fine-tuned under On Device.",+ music: "Music models. Loading one replaces the model in the main slot.",+ transcribe:+ "Speech recognition models. They run beside your chat model, not in its place.",};+function modelStep(workflow: AudioWorkflowId): TourStep {+ return {+ id: "model",+ target: "audio-model",+ title: "Pick a model",+ body: <>{MODEL_STEP_BODY[workflow]}</>,+ };+}+const outputStep: TourStep = {id: "output",target: "audio-output",@@ -40,16 +47,15 @@ const outputStep: TourStep = {),};-/** The two modes swap the settings body and the footer, so each gets its own middle step. */export function buildAudioTourSteps({- mode,+ workflow,}: {- mode: "speak" | "transcribe";+ workflow: AudioWorkflowId;}): TourStep[] {- if (mode === "transcribe") {+ if (workflow === "transcribe") {return [modeStep,- modelStep,+ modelStep(workflow),{id: "record",target: "audio-record",@@ -67,17 +73,23 @@ export function buildAudioTourSteps({return [modeStep,- modelStep,+ modelStep(workflow),{id: "settings",target: "audio-settings",title: "Settings",- body: (- <>- Your text or lyrics, plus voice and style where the model supports- them. Length and temperature sit under Advanced.- </>- ),+ body:+ workflow === "music" ? (+ <>+ Lyrics, plus a description of the style where the model takes one.+ Length sits under Advanced.+ </>+ ) : (+ <>+ Your text, plus voice and style where the model supports them.+ Length and temperature sit under Advanced.+ </>+ ),},outputStep,];diff --git a/studio/frontend/src/features/audio/workflows.ts b/studio/frontend/src/features/audio/workflows.tsnew file mode 100644index 00000000000..01aabd3527f--- /dev/null+++ b/studio/frontend/src/features/audio/workflows.ts@@ -0,0 +1,103 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Free of app imports so the node test runner and the sidebar can load it directly.++import {+ AiVoiceIcon,+ MusicNote03Icon,+ SpeechToTextIcon,+} from "@hugeicons/core-free-icons";+import type { IconSvgElement } from "@hugeicons/react";+import { AUDIO_CPP_MUSIC_AUDIO_TYPE } from "./audio-cpp-catalog";++export type AudioWorkflowId = "speak" | "music" | "transcribe";++export type AudioWorkflowSlot = "speak" | "transcribe";++export const AUDIO_WORKFLOWS: ReadonlyArray<{+ id: AudioWorkflowId;+ label: string;+ heading: string;+ icon: IconSvgElement;+ hint: string;+ slot: AudioWorkflowSlot;+ createTrain: boolean;+}> = [+ {+ id: "speak",+ label: "Speak",+ heading: "Text to speech",+ icon: AiVoiceIcon,+ hint: "Turn text into speech with a built-in or designed voice",+ slot: "speak",+ createTrain: true,+ },+ {+ id: "music",+ label: "Music",+ heading: "Create music",+ icon: MusicNote03Icon,+ hint: "Songs, instrumentals and sound effects",+ slot: "speak",+ createTrain: false,+ },+ {+ id: "transcribe",+ label: "Transcribe",+ heading: "Transcribe",+ icon: SpeechToTextIcon,+ hint: "Turn speech into text",+ slot: "transcribe",+ createTrain: true,+ },+];++/** Mirrors MUSIC_AUDIO_TYPES in studio/backend/core/inference/audio_workflows.py. */+export const MUSIC_AUDIO_TYPES: ReadonlySet<string> = new Set([+ "minimax_music3",+ AUDIO_CPP_MUSIC_AUDIO_TYPE,+]);++export function isAudioWorkflowId(value: unknown): value is AudioWorkflowId {+ return AUDIO_WORKFLOWS.some((tab) => tab.id === value);+}++export function audioWorkflowTab(id: AudioWorkflowId) {+ return AUDIO_WORKFLOWS.find((tab) => tab.id === id) ?? AUDIO_WORKFLOWS[0];+}++export function slotForWorkflow(id: AudioWorkflowId): AudioWorkflowSlot {+ return audioWorkflowTab(id).slot;+}++export function audioWorkflowForTask(+ task: string | null | undefined,+): AudioWorkflowId | null {+ switch (task) {+ case "text-to-speech":+ return "speak";+ case "automatic-speech-recognition":+ return "transcribe";+ case "text-to-audio":+ return "music";+ default:+ return null;+ }+}++export function audioWorkflowForAudioType(+ audioType: string | null | undefined,+): "speak" | "music" {+ return audioType && MUSIC_AUDIO_TYPES.has(audioType) ? "music" : "speak";+}++export function clipWorkflow(clip: {+ workflow?: string | null;+ audio_type?: string | null;+}): "speak" | "music" {+ if (clip.workflow === "speak" || clip.workflow === "music") {+ return clip.workflow;+ }+ return audioWorkflowForAudioType(clip.audio_type);+}diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex 40672059457..a1513b47db6 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -553,6 +553,7 @@ export interface CachedGgufRepo {* Images picker can show only diffusion GGUFs. */task?: string | null;audio_type?: string | null;+ audio_workflows?: string[] | null;/** True when some quant has a download manifest or cancel marker. Optional for older-backend compatibility. */has_variant_state?: boolean;partial?: boolean;@@ -662,6 +663,7 @@ export interface LocalModelInfo {task?: string | null;/** Detected output-audio architecture or codec used by Audio runtime policy. */audio_type?: string | null;+ audio_workflows?: string[] | null;}interface LocalModelListResponse {@@ -700,6 +702,7 @@ export interface CachedModelRepo {task?: string | null;/** Detected output-audio architecture or codec used by Audio runtime policy. */audio_type?: string | null;+ audio_workflows?: string[] | null;/** True when the snapshot is incomplete: such a repo must not count as downloaded, or a click* re-downloads the full weights. */partial?: boolean;diff --git a/studio/frontend/src/features/model-picker/components/model-selector.tsx b/studio/frontend/src/features/model-picker/components/model-selector.tsxindex 9f2aee1acc6..56415df7b1f 100644--- a/studio/frontend/src/features/model-picker/components/model-selector.tsx+++ b/studio/frontend/src/features/model-picker/components/model-selector.tsx@@ -61,7 +61,11 @@ import {artifactForRepoId,type CatalogGroup,} from "./model-selector/model-catalog";-import { HubModelPicker, hasDownloadedModels } from "./model-selector/pickers";+import {+ HubModelPicker,+ hasDownloadedModels,+ type ModelPickerRowFilter,+} from "./model-selector/pickers";import { PillTabs } from "./model-selector/pill-tabs";import { loraOptionLabel } from "./model-selector/row-meta";import { isFineTunedSource } from "./model-selector/source-tabs";@@ -83,6 +87,7 @@ export type {ModelSelectorChangeMeta,} from "./model-selector/types";export type { ExternalConnectionRef } from "./model-selector/missing-external-model";+export type { ModelPickerRowFilter } from "./model-selector/pickers";interface ModelSelectorProps {models: ModelOption[];@@ -139,6 +144,7 @@ interface ModelSelectorProps {communityModelPolicy?: CommunityModelPolicy;/** The one opaque on-device artifact kind this task runtime may load. */opaqueKind?: "diffusers_pipeline" | "diffusers_modular_pipeline";+ rowFilter?: ModelPickerRowFilter;/** Hub filter the Search Hub button opens with. Also shows Search Hub on curated task pickers. */hubCapability?: CapabilityKey;/** Trigger text when nothing is loaded. Defaults to "Select model"; task pages name what they@@ -369,6 +375,7 @@ function ModelSelectorContent({catalog,communityModelPolicy,opaqueKind,+ rowFilter,}: {open: boolean;models: ModelOption[];@@ -400,6 +407,7 @@ function ModelSelectorContent({catalog?: CatalogGroup[];communityModelPolicy?: CommunityModelPolicy;opaqueKind?: "diffusers_pipeline" | "diffusers_modular_pipeline";+ rowFilter?: ModelPickerRowFilter;}) {const t = useT();const hasSelection = Boolean(value);@@ -676,6 +684,7 @@ function ModelSelectorContent({catalog={catalog}communityModelPolicy={communityModelPolicy}opaqueKind={opaqueKind}+ rowFilter={rowFilter}npu={npu}section={effectiveHubSection}sectionToggle={@@ -739,6 +748,7 @@ export function ModelSelector({catalog,communityModelPolicy = "none",opaqueKind,+ rowFilter,hubCapability,placeholder,loaded,@@ -939,6 +949,7 @@ export function ModelSelector({catalog={catalog}communityModelPolicy={communityModelPolicy}opaqueKind={opaqueKind}+ rowFilter={rowFilter}/></Popover>);diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsxindex 5a0cdedadb0..aa46132f570 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx+++ b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx@@ -155,6 +155,7 @@ import {useState,useSyncExternalStore,} from "react";+import { audioWorkflowForPick } from "../../../audio/route-search.ts";import { useChatPickerInventory } from "../../inventory/use-chat-picker-inventory";import {type CommunityModelPolicy,@@ -2965,6 +2966,13 @@ function localModelMatchesFormat();}+export type ModelPickerRowFilter = (row: {+ id: string;+ task?: string | null;+ audioType?: string | null;+ audioWorkflows?: readonly string[] | null;+}) => boolean;+export function HubModelPicker({models,additionalOnDeviceModels = [],@@ -2989,6 +2997,7 @@ export function HubModelPicker({communityModelPolicy = "none",opaqueKind,npu,+ rowFilter,}: {models: ModelOption[];/** Task-runtime downloads using a cache layout the shared Hub inventory cannot represent (for@@ -3024,6 +3033,7 @@ export function HubModelPicker({communityModelPolicy?: CommunityModelPolicy;opaqueKind?: "diffusers_pipeline" | "diffusers_modular_pipeline";npu?: NpuPickerSource;+ rowFilter?: ModelPickerRowFilter;}) {const gpu = useGpuInfo();const inferenceGpu = useInferenceGpuInfo();@@ -4221,7 +4231,14 @@ export function HubModelPicker({// The task and codec both came from GGUF classification; codec provenance separates runnable// Orpheus from unsupported CSM.taskFromGgufArch: true,- }),+ }) &&+ (!rowFilter ||+ rowFilter({+ id: c.repo_id,+ task: c.task,+ audioType: c.audio_type,+ audioWorkflows: c.audio_workflows,+ })),),downloadedSort,loadTimes,@@ -4233,6 +4250,7 @@ export function HubModelPicker({task,catalog,activeCatalogArtifactIds,+ rowFilter,],);// Cached non-GGUF repos. In chat, passesTaskGate drops diffusers image repos; the Images@@ -4287,7 +4305,14 @@ export function HubModelPicker({? artifactForRepoId(c.repo_id, catalog) !== null: false) ||// A pinned snapshot admitted only by an explicit family.- (c.opaque === true && Boolean(c.load_id?.trim()) && c.load_id?.trim() !== c.repo_id.trim())),+ (c.opaque === true && Boolean(c.load_id?.trim()) && c.load_id?.trim() !== c.repo_id.trim())) &&+ (!rowFilter ||+ rowFilter({+ id: c.repo_id,+ task: c.task,+ audioType: c.audio_type,+ audioWorkflows: c.audio_workflows,+ })),),downloadedSort,loadTimes,@@ -4300,6 +4325,7 @@ export function HubModelPicker({catalog,activeCatalogArtifactIds,isMac,+ rowFilter,],);// Task-scoped loads put the whole pipeline on ONE device, so quant fit uses the device the@@ -4356,7 +4382,16 @@ export function HubModelPicker({m,) &&localModelMatchesFormat(m, formatFilter) &&- matchesLocalQuery(m),+ matchesLocalQuery(m) &&+ // A task page's own filter (the Audio page lists only its workflow's models) applies to local+ // and LM Studio rows too, not just the cached Hub rows above.+ (!rowFilter ||+ rowFilter({+ id: m.model_id ?? m.id,+ task: m.task,+ audioType: m.audio_type,+ audioWorkflows: m.audio_workflows,+ })),),downloadedSort,loadTimes,@@ -4371,6 +4406,7 @@ export function HubModelPicker({task,catalog,activeCatalogArtifactIds,+ rowFilter,],);// Local ./models entries. Chat-only Unsloth runs GGUF anywhere and MLX on Mac, so raw@@ -4407,7 +4443,16 @@ export function HubModelPicker({localModelIsGguf(m) ||(isMac && localModelIsMlx(m))) &&localModelMatchesFormat(m, formatFilter) &&- matchesLocalQuery(m),+ matchesLocalQuery(m) &&+ // A task page's own filter (the Audio page lists only its workflow's models) applies to local+ // and LM Studio rows too, not just the cached Hub rows above.+ (!rowFilter ||+ rowFilter({+ id: m.model_id ?? m.id,+ task: m.task,+ audioType: m.audio_type,+ audioWorkflows: m.audio_workflows,+ })),),downloadedSort,loadTimes,@@ -4424,6 +4469,7 @@ export function HubModelPicker({task,catalog,activeCatalogArtifactIds,+ rowFilter,],);const sortedCustomFolderModels = useMemo(@@ -4453,7 +4499,16 @@ export function HubModelPicker({m,) &&localModelMatchesFormat(m, formatFilter) &&- matchesLocalQuery(m),+ matchesLocalQuery(m) &&+ // A task page's own filter (the Audio page lists only its workflow's models) applies to local+ // and LM Studio rows too, not just the cached Hub rows above.+ (!rowFilter ||+ rowFilter({+ id: m.model_id ?? m.id,+ task: m.task,+ audioType: m.audio_type,+ audioWorkflows: m.audio_workflows,+ })),),customSort,loadTimes,@@ -4468,6 +4523,7 @@ export function HubModelPicker({task,catalog,activeCatalogArtifactIds,+ rowFilter,],);@@ -4559,6 +4615,12 @@ export function HubModelPicker({task: pickedTask ?? undefined,audioType: meta.audioType ?? undefined,loadId: meta.loadId ?? undefined,+ workflow:+ audioWorkflowForPick({+ id,+ task: pickedTask,+ audioType: meta.audioType,+ }) ?? undefined,}: diffusionRouteSearch(id, meta),});@@ -5158,6 +5220,7 @@ export function HubModelPicker({rows.filter(isChatSupported).filter(isTaskRuntimeSupported)+ .filter((r) => !rowFilter || rowFilter({ id: r.id, task: r.pipelineTag })).filter((r) =>!fitOnDeviceOnly ||@@ -5193,6 +5256,7 @@ export function HubModelPicker({searchRowFits,isMac,curatedOfferable,+ rowFilter,],);diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.cssindex 23137208ff5..0bc130cad4a 100644--- a/studio/frontend/src/index.css+++ b/studio/frontend/src/index.css@@ -2276,9 +2276,10 @@ html[data-chat-font] .aui-root {.group\/project-chat-item:hover:not(:has(.sidebar-row-action:hover)) .sidebar-nav-btn,.group\/projects-item:hover:not(:has(.sidebar-row-action:hover)) .sidebar-nav-btn,.group\/recent-item:hover:not(:has(.sidebar-row-action:hover)) .sidebar-nav-btn,- /* Images: the chevron discloses this row's own list, so the row stays lit while the+ /* Images and Audio: the chevron discloses this row's own list, so the row stays lit while thepointer is on it. Scoped to the row's wrapper, clear of the list below it. */.group\/images-item:hover > .relative > .sidebar-nav-btn,+ .group\/audio-item:hover > .relative > .sidebar-nav-btn,.group\/run-item:hover:not(:has(.sidebar-row-action:hover)) .sidebar-nav-btn {background-color: var(--nav-surface-hover) !important;color: #000 !important;@@ -2292,6 +2293,7 @@ html[data-chat-font] .aui-root {.dark .group\/projects-item:hover:not(:has(.sidebar-row-action:hover)) .sidebar-nav-btn,.dark .group\/recent-item:hover:not(:has(.sidebar-row-action:hover)) .sidebar-nav-btn,.dark .group\/images-item:hover > .relative > .sidebar-nav-btn,+ .dark .group\/audio-item:hover > .relative > .sidebar-nav-btn,.dark .group\/run-item:hover:not(:has(.sidebar-row-action:hover)) .sidebar-nav-btn {color: #fff !important;}diff --git a/studio/frontend/src/lib/gallery-flags.ts b/studio/frontend/src/lib/gallery-flags.tsindex b5ecf065178..f62342a6833 100644--- a/studio/frontend/src/lib/gallery-flags.ts+++ b/studio/frontend/src/lib/gallery-flags.ts@@ -114,6 +114,32 @@ export function moveGalleryItem<T extends FlaggableItem>(return [...rest.slice(0, at), { ...moved, pinned }, ...rest.slice(at)];}+/** The shelf `afterId` for a move in a filtered view, keeping the pin state the view showed: hidden+ * neighbours decide the pin, so a drop beside another page's pin used to pin the clip. */+export function scopedMoveAfterId<T extends FlaggableItem>(+ items: T[],+ inView: (item: T) => boolean,+ id: string,+ afterId: string | null,+): string | null {+ const view = items.filter(inView);+ const intended = moveGalleryItem(view, id, afterId);+ if (intended === view) return afterId;+ const at = intended.findIndex((i) => i.id === id);+ const wantPinned = Boolean(intended[at]?.pinned);+ const above = intended[at - 1];+ const below = intended[at + 1];+ const rest = items.filter((i) => i.id !== id);+ const first = above ? rest.findIndex((i) => i.id === above.id) : -1;+ const last = below ? rest.findIndex((i) => i.id === below.id) : rest.length;+ for (let gap = first; gap < last; gap++) {+ const candidate = gap < 0 ? null : rest[gap].id;+ const moved = moveGalleryItem(items, id, candidate).find((i) => i.id === id);+ if (Boolean(moved?.pinned) === wantPinned) return candidate;+ }+ return afterId;+}+/** The pinned ids in their current order, to hand back to `restorePinOrder` on a failed unpin. */export function pinnedOrder<T extends FlaggableItem>(items: T[]): string[] {return items.filter((i) => i.pinned).map((i) => i.id);diff --git a/studio/frontend/tests/audio-cpp-catalog.test.ts b/studio/frontend/tests/audio-cpp-catalog.test.tsindex 3be97669fb4..8b5325c6c38 100644--- a/studio/frontend/tests/audio-cpp-catalog.test.ts+++ b/studio/frontend/tests/audio-cpp-catalog.test.ts@@ -75,6 +75,7 @@ import {readText,registerBundlerResolver,} from "./helpers/kit.ts";+import { readAudioWorkspaceSource } from "./helpers/audio-workspace.ts";registerBundlerResolver();installLocalStorageFake();@@ -222,7 +223,7 @@ test("MiniMax Music 3 and YuE2 need a description beside the lyrics", () => {assert.equal(musicNeedsDescription("audiocpp_music", family), false, String(family));}assert.equal(musicNeedsDescription("audiocpp_tts", "yue2"), false);- const page = readSrc("features/audio/audio-page.tsx");+ const page = readAudioWorkspaceSource();assert.match(page,/musicModelNeedsDescription\(status\?\.audio_type, status\?\.audio_family\)/,@@ -290,7 +291,7 @@ test("Hub rows published for the audio runtime are runnable on the Audio page",audioType,);}- const page = readSrc("features/audio/audio-page.tsx");+ const page = readAudioWorkspaceSource();assert.match(page, /speak: \["text-to-speech", "text-to-audio"\]/);});@@ -365,7 +366,7 @@ test("an Audio-page ASR pick sends its quant; other engines and saved keys send/return engine === "audiocpp" && ggufVariant\s*\?[\s\S]*\{ gguf_variant: ggufVariant \}\s*:\s*\{\};/,);assert.equal(adapter.match(/\.\.\.sttVariantBody\(resolvedEngine, ggufVariant\)/g)?.length, 2);- const page = readSrc("features/audio/audio-page.tsx");+ const page = readAudioWorkspaceSource();assert.match(page, /sttGgufVariants\.current\.set\(id\.toLowerCase\(\), meta\.ggufVariant\)/);assert.match(page,@@ -422,7 +423,7 @@ test("GGUF music length follows the backend clamp; the MiniMax pipeline keeps it});assert.equal(AUDIO_CPP_MUSIC_MAX_SECONDS, 240);assert.deepEqual(musicDurationRange(true), { min: 1, max: MINIMAX_MUSIC_MAX_SECONDS });- const page = readSrc("features/audio/audio-page.tsx");+ const page = readAudioWorkspaceSource();assert.match(page, /musicDurationRange\(cudaMusicGeneration\)/);assert.match(page, /min=\{musicRange\.min\}\s*max=\{musicRange\.max\}/);assert.match(page, /minimaxMusicFramesForSeconds\(musicSeconds\)/);@@ -433,7 +434,7 @@ test("GGUF runtime speech trades sampling controls for the model's own options",for (const audioType of ["audiocpp_music", "snac", "moss_tts_local", null]) {assert.equal(audioSamplingControlsApply(audioType), true, String(audioType));}- const page = readSrc("features/audio/audio-page.tsx");+ const page = readAudioWorkspaceSource();assert.match(page,/\{musicGeneration \|\|\s*samplingControls \|\|\s*audioOptionSpecs\.length > 0 \? \(\s*<AdvancedDisclosure/,@@ -445,7 +446,7 @@ test("GGUF runtime speech trades sampling controls for the model's own options",});test("pickers, toasts, downloads and loaded models show no engine name", () => {- const page = readSrc("features/audio/audio-page.tsx");+ const page = readAudioWorkspaceSource();// Every user-visible string literal on the page, without comments.const withoutComments = page.replace(/\/\*[\s\S]*?\*\//g, "")@@ -467,7 +468,7 @@ test("pickers, toasts, downloads and loaded models show no engine name", () => {});test("an Audio GGUF pick downloads its quant as the standard variant job", () => {- const page = readSrc("features/audio/audio-page.tsx");+ const page = readAudioWorkspaceSource();assert.match(page, /ggufVariant: meta\.ggufVariant,/);const staged = readSrc("features/hub/download-manager/use-staged-download.ts");assert.match(staged, /current\.ggufVariant \?\? scopedVariant\(scopeId\)/);@@ -512,7 +513,7 @@ test("recommended speech and music picks are refused when the runtime cannot runassert.equal(audioCppRuntimeProblem(null, missing), null);const route = readText("../../backend/routes/inference.py");assert.match(route, /"audio_cpp_runtime": _audio_cpp_runtime_status\(\)/);- const page = readSrc("features/audio/audio-page.tsx");+ const page = readAudioWorkspaceSource();assert.match(page, /audioCppRuntime\.current = stt\.audio_cpp_runtime \?\? null;/);assert.match(page,@@ -533,7 +534,7 @@ test("YuE2 generates from a style description alone; other music still needs lyrassert.equal(musicLyricsOptional("audiocpp_music", family), false, String(family));}assert.equal(musicLyricsOptional("audiocpp_tts", "yue2"), false);- const page = readSrc("features/audio/audio-page.tsx");+ const page = readAudioWorkspaceSource();assert.match(page, /\(!prompt\.trim\(\) && !lyricsOptional\)/);assert.match(page, /if \(!text && !lyricsOptional\) return;/);});@@ -544,7 +545,7 @@ test("a custom GGUF dictation repo skips the Whisper-only validator", () => {});test("the picked STT quant is remembered with the repo across a restart", () => {- const page = readSrc("features/audio/audio-page.tsx");+ const page = readAudioWorkspaceSource();assert.match(page, /usePersistedChoice\("unsloth:audio:last-stt-variant", ""\)/);assert.match(page, /lastSttRepo && lastSttVariant \? \[\[lastSttRepo\.toLowerCase\(\), lastSttVariant\]\]/);assert.match(page, /setLastSttVariant\(sttGgufVariants\.current\.get\(repo\.toLowerCase\(\)\) \?\? ""\)/);diff --git a/studio/frontend/tests/audio-generation-stop.test.ts b/studio/frontend/tests/audio-generation-stop.test.tsindex e94ec1554b6..c778206ea76 100644--- a/studio/frontend/tests/audio-generation-stop.test.ts+++ b/studio/frontend/tests/audio-generation-stop.test.ts@@ -4,9 +4,9 @@import assert from "node:assert/strict";import test from "node:test";-import { readSrc } from "./helpers/kit.ts";+import { readAudioWorkspaceSource } from "./helpers/audio-workspace.ts";-const source = readSrc("features/audio/audio-page.tsx");+const source = readAudioWorkspaceSource();test("generation exposes Stop only while the request controller can abort", () => {assert.match(@@ -136,9 +136,9 @@ test("a saved clip the refresh missed keeps its response audio mounted", () => {// player rendered the empty state.assert.match(source,- /const selectClip = useCallback\(\s*\(id: string, keepFallback = false\) => \{[\s\S]*if \(!keepFallback\) setFallbackClip\(null\);/,+ /const selectClip = useCallback\(\s*\(id: string, keepFallback = false\) => \{[\s\S]*if \(!keepFallback && !otherPage\) setFallbackClip\(null\);/,);- assert.match(source, /saved: true,\s*\}\);\s*selectClip\(generated\.clip_id, true\);/);+ assert.match(source, /saved: true,\s*workflow,\s*\}\);\s*selectClip\(generated\.clip_id, true\);/);});test("deleting a clip drops the row without waiting on the refresh", () => {@@ -168,6 +168,6 @@ test("the response fallback is dropped once its gallery record arrives", () => {// stale data URL, labelled as saved, as though the delete had not happened.assert.match(source,- /fallbackClipRef\.current &&\s*galleryCache\.selectedId &&\s*merged\.some\(\(c\) => c\.id === galleryCache\.selectedId\)\s*\)\s*\{\s*setFallbackClip\(null\);/,+ /fallbackClipRef\.current\?\.saved &&\s*galleryCache\.selectedId &&\s*merged\.some\(\(c\) => c\.id === galleryCache\.selectedId\)\s*\)\s*\{\s*setFallbackClip\(null\);/,);});diff --git a/studio/frontend/tests/audio-handoff-intent.test.ts b/studio/frontend/tests/audio-handoff-intent.test.tsnew file mode 100644index 00000000000..2d6a55438f9--- /dev/null+++ b/studio/frontend/tests/audio-handoff-intent.test.ts@@ -0,0 +1,161 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import { readSrc, registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();+const { audioRouteIntent, audioWorkflowForPick, validateAudioSearch } =+ await import("../src/features/audio/route-search.ts");++test("every task Audio runs survives validation, including text-to-audio", () => {+ for (const task of [+ "text-to-speech",+ "automatic-speech-recognition",+ "text-to-audio",+ ]) {+ assert.deepEqual(validateAudioSearch({ task }), { task });+ }+});++test("unknown tasks, workflows and audio types are dropped", () => {+ assert.deepEqual(+ validateAudioSearch({+ task: "text-to-image",+ workflow: "clone",+ audioType: "not-a-type",+ loadId: " ",+ }),+ {},+ );+ assert.deepEqual(+ validateAudioSearch({ workflow: 3, task: ["text-to-speech"] }),+ {},+ );+});++test("the params the route accepted before pass through unchanged", () => {+ const search = {+ model: "unsloth/orpheus-3b-0.1-ft-GGUF",+ quant: "orpheus-3b-0.1-ft-Q4_K_M.gguf",+ ggufQuant: "Q4_K_M",+ task: "text-to-speech",+ audioType: "audiocpp_tts",+ loadId: "load-1",+ item: "clip-1",+ };+ assert.deepEqual(validateAudioSearch({ ...search, extra: "x" }), search);+ assert.deepEqual(validateAudioSearch({ audioType: "minimax_music3" }), {+ audioType: "minimax_music3",+ });+});++test("a workflow param is kept when it names a workflow", () => {+ for (const workflow of ["speak", "music", "transcribe"]) {+ assert.deepEqual(validateAudioSearch({ workflow }), { workflow });+ }+});++test("the task maps to its workflow", () => {+ assert.equal(audioRouteIntent({ task: "text-to-speech" }), "speak");+ assert.equal(+ audioRouteIntent({ task: "automatic-speech-recognition" }),+ "transcribe",+ );+ assert.equal(audioRouteIntent({ task: "text-to-audio" }), "music");+ assert.equal(audioRouteIntent({}), null);+ assert.equal(audioRouteIntent({ task: "text-to-image" }), null);+});++test("an explicit workflow beats the one the task implies", () => {+ assert.equal(+ audioRouteIntent({ task: "text-to-speech", workflow: "music" }),+ "music",+ );+ assert.equal(+ audioRouteIntent({ task: "text-to-audio", workflow: "bogus" }),+ "music",+ );+});++test("a chat pick opens on the workflow its model runs in", () => {+ assert.equal(+ audioWorkflowForPick({ id: "hexgrad/Kokoro-82M", task: "text-to-speech" }),+ "speak",+ );+ assert.equal(+ audioWorkflowForPick({+ id: "openai/whisper-small",+ task: "automatic-speech-recognition",+ }),+ "transcribe",+ );+ assert.equal(+ audioWorkflowForPick({+ id: "MiniMaxAI/MiniMax-Music3",+ task: "text-to-speech",+ audioType: "minimax_music3",+ }),+ "music",+ );+ assert.equal(+ audioWorkflowForPick({+ id: "audio-cpp/audio.cpp-gguf/ACE-Step1.5-GGUF",+ task: "text-to-speech",+ }),+ "music",+ );+ assert.equal(audioWorkflowForPick({ id: "x/y", task: null }), null);+});++test("the route validates through the shared helper", () => {+ const route = readSrc("app/routes/audio.tsx");+ assert.match(route, /validateSearch: validateAudioSearch,/);+});++test("the chat picker forwards the workflow and still routes no text-to-audio rows", () => {+ const pickers = readSrc(+ "features/model-picker/components/model-selector/pickers.tsx",+ );+ assert.match(+ pickers,+ /workflow:\s*audioWorkflowForPick\(\{\s*id,\s*task: pickedTask,\s*audioType: meta\.audioType,\s*\}\) \?\? undefined,/,+ );+ const tasks = pickers.match(/export const AUDIO_GEN_TASKS = \[([^\]]*)\]/);+ assert.ok(tasks);+ assert.doesNotMatch(tasks[1], /text-to-audio/);+});++test("a chat picker handoff opens its page before the load, not only after it succeeds", () => {+ const handoff = readSrc("features/audio/hooks/use-audio-handoff.ts");+ // The workflow is part of the dedupe key, so the same model sent for another page is handled again.+ assert.match(+ handoff,+ /const key = `\$\{wanted\}\|[^`]*\|\$\{routeSearch\.workflow \?\? ""\}`;/,+ );+ // Switch, then mark handled, then load: a refused switch leaves the handoff in the URL to retry.+ assert.match(+ handoff,+ /if \(busyRef\.current !== null\) return;[\s\S]*?if \(\s*isAudioWorkflowId\(routedWorkflow\) &&\s*!transitionWorkflow\(routedWorkflow\)\s*\) \{\s*return;\s*\}\s*handledRouteModel\.current = key;\s*handleModelSelect\(wanted,/,+ );+});++test("a model deep link without a workflow opens the page its task names before loading", () => {+ const handoff = readSrc("features/audio/hooks/use-audio-handoff.ts");+ assert.match(+ handoff,+ /const routedWorkflow = isAudioWorkflowId\(routeSearch\.workflow\)\s*\?\s*routeSearch\.workflow\s*:\s*audioWorkflowForPick\(\{\s*id: wanted,\s*task: routeSearch\.task,\s*audioType: routeSearch\.audioType,\s*\}\);/,+ );+ assert.equal(+ audioWorkflowForPick({ id: "some/model", task: "text-to-audio" }),+ "music",+ );+ assert.equal(audioWorkflowForPick({ id: "some/model" }), null);+ // Without a task, a music audio type still names Music.+ assert.equal(+ audioWorkflowForPick({ id: "some/model", audioType: "minimax_music3" }),+ "music",+ );+});diff --git a/studio/frontend/tests/audio-instructions-field.test.ts b/studio/frontend/tests/audio-instructions-field.test.tsnew file mode 100644index 00000000000..1b0836ca6c9--- /dev/null+++ b/studio/frontend/tests/audio-instructions-field.test.ts@@ -0,0 +1,32 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import { readSrc, registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();+const { instructionsFieldKind } = await import("../src/features/audio/audio-page-policy.ts");++const fields = readSrc("features/audio/components/instructions-fields.tsx");+const host = readSrc("features/audio/audio-page.tsx");++test("a model gets the instruction field it always got, on its own page", () => {+ assert.equal(instructionsFieldKind("speak", "audiocpp_tts"), "voice");+ assert.equal(instructionsFieldKind("speak", "higgs_tts2"), "scene");+ assert.equal(instructionsFieldKind("speak", "moss_tts_local"), "style");+ assert.equal(instructionsFieldKind("music", "minimax_music3"), "music");+ assert.equal(instructionsFieldKind("speak", "snac"), null);+ assert.equal(instructionsFieldKind("speak", "csm"), null);+ assert.equal(instructionsFieldKind("speak", "audiocpp_music"), null);+});++test("the fields keep the rail's exact copy", () => {+ assert.match(fields, /\? "Scene description"/);+ assert.match(fields, /"Voice or style description"/);+ assert.match(fields, /instructionsKind === "music"\s*\? musicNeedsDescription/);+ assert.match(fields, /id="audio-instructions"/);+ assert.match(fields, /id="audio-language"/);+ assert.match(host, /instructionsKind === "style" \? \(\s*<MossLanguageField/);+});diff --git a/studio/frontend/tests/audio-mode-task-filter.test.ts b/studio/frontend/tests/audio-mode-task-filter.test.tsindex af285770da1..76db9bbec00 100644--- a/studio/frontend/tests/audio-mode-task-filter.test.ts+++ b/studio/frontend/tests/audio-mode-task-filter.test.ts@@ -11,8 +11,9 @@ import {import { detectCapabilities } from "../src/features/model-picker/components/model-selector/model-capabilities.ts";import { readSrc } from "./helpers/kit.ts";+import { readAudioWorkspaceSource } from "./helpers/audio-workspace.ts";-const pageSource = readSrc("features/audio/audio-page.tsx");+const pageSource = readAudioWorkspaceSource();const catalogSource = readSrc("features/audio/catalog.ts");test("Hub discovery follows the active audio mode", () => {diff --git a/studio/frontend/tests/audio-model-eject.test.ts b/studio/frontend/tests/audio-model-eject.test.tsindex 6d728ebb887..6238c7cf593 100644--- a/studio/frontend/tests/audio-model-eject.test.ts+++ b/studio/frontend/tests/audio-model-eject.test.ts@@ -5,8 +5,9 @@ import assert from "node:assert/strict";import test from "node:test";import { readSrc } from "./helpers/kit.ts";+import { readAudioWorkspaceSource } from "./helpers/audio-workspace.ts";-const source = readSrc("features/audio/audio-page.tsx");+const source = readAudioWorkspaceSource();const adapterSource = readSrc("features/chat/adapters/studio-model-dictation-adapter.ts");test("Audio exposes the shared picker eject action only while idle", () => {@@ -175,15 +176,17 @@ test("leaving Transcribe releases the sidecar it loaded", () => {test("selected and fallback clip actions remain named and downloadable", () => {assert.match(source, /aria-label="Download audio clip"/);- assert.match(source, /aria-label="Delete audio clip"/);+ // Delete sits in the clip card's menu, the same one each history row uses.assert.match(source,- /const handleDownloadFallbackClip[\s\S]*anchor\.download = "generated-audio\.wav"/,+ /onDelete=\{\(\) => void handleDeleteClip\(clip\.id\)\}/,);+ assert.match(source, /menu=\{clipMenu\(selectedClip, "row"\)\}/);assert.match(source,- /onClick=\{handleDownloadFallbackClip\}[\s\S]*Download WAV/,+ /const handleDownloadFallbackClip[\s\S]*anchor\.download = "generated-audio\.wav"/,);+ assert.match(source, /onDownload=\{handleDownloadFallbackClip\}/);});test("a dictation model this page did not load survives a mode switch", () => {diff --git a/studio/frontend/tests/audio-page-policy.test.ts b/studio/frontend/tests/audio-page-policy.test.tsindex 1d3ebab30c1..37f7d172500 100644--- a/studio/frontend/tests/audio-page-policy.test.ts+++ b/studio/frontend/tests/audio-page-policy.test.ts@@ -13,12 +13,14 @@ import {canTransitionAudioMode,exactGgufLoadSelector,expectedGgufDownloadBytes,+ fetchGalleryWindow,isGgufTtsTarget,isTtsAudioType,macTtsPickAction,mergeGalleryPage,micStreamRequestIsCurrent,minimaxMusicFramesForSeconds,+ modelLoadNote,nativeAudioInstructionsKind,persistedClipForGeneration,reconcileSttSelection,@@ -30,8 +32,9 @@ import {} from "../src/features/audio/audio-page-policy.ts";import { readSrc } from "./helpers/kit.ts";+import { readAudioWorkspaceSource } from "./helpers/audio-workspace.ts";-const audioPageSource = readSrc("features/audio/audio-page.tsx");+const audioPageSource = readAudioWorkspaceSource();const chatApiSource = readSrc("features/chat/api/chat-api.ts");test("mode transitions cancel generation but wait for non-cancellable work", () => {@@ -712,7 +715,7 @@ test("the gallery-changed subscription asks for the window that is loaded", () =);assert.match(audioPageSource,- /const wanted = Math\.max\(PAGE_SIZE, windowSize\);\s*const asked = Math\.min\(wanted, MAX_PAGE_SIZE\);/,+ /const wanted = Math\.max\(PAGE_SIZE, windowSize\);[\s\S]*?fetchGalleryWindow\([\s\S]*?wanted,\s*MAX_PAGE_SIZE,/,);});@@ -734,14 +737,57 @@ test("returning to a visible audio tab refreshes the loaded window", () => {);});-test("a window past the route cap resets the strip instead of stranding the restore", () => {- // Asking for more than the route returns leaves the middle of the window unfetched, and keeping- // the old scrollback keeps a cursor starting BELOW that middle, so a clip restored into it is- // in neither the merged list nor any page still reachable.+type WindowClip = { id: string };+type WindowPage = { audio: WindowClip[]; has_more: boolean; next: number | null };+function windowShelf(size: number) {+ const shelf = Array.from({ length: size }, (_, n) => ({ id: `c${n}` }));+ const calls: { limit: number; cursor: number | null }[] = [];+ const fetchPage = async (limit: number, cursor: number | null): Promise<WindowPage> => {+ calls.push({ limit, cursor });+ const from = cursor ?? 0;+ const audio = shelf.slice(from, from + limit);+ const end = from + audio.length;+ return { audio, has_more: end < shelf.length, next: end < shelf.length ? end : null };+ };+ return { shelf, calls, fetchPage };+}++test("a window past the route cap is fetched in capped pages, not cut to the first one", async () => {+ // A history topped up past 200 clips was refreshed with only the first 200 on focus, which+ // dropped the selected clip below them and jumped the selection to the newest clip.+ const { shelf, calls, fetchPage } = windowShelf(303);+ const page = await fetchGalleryWindow(fetchPage, (p) => p.next, 250, 200);+ assert.deepEqual(calls, [{ limit: 200, cursor: null }, { limit: 50, cursor: 200 }]);+ assert.deepEqual(page.audio.map((c) => c.id), shelf.slice(0, 250).map((c) => c.id));+ // The cursor and has_more come from the last page, so scrolling continues below the window.+ assert.equal(page.has_more, true);+ assert.equal(page.next, 250);+});++test("a window fetch stops when the server runs out or the refresh is superseded", async () => {+ const short = windowShelf(230);+ const page = await fetchGalleryWindow(short.fetchPage, (p) => p.next, 400, 200);+ assert.equal(page.audio.length, 230);+ assert.equal(page.has_more, false);+ assert.equal(short.calls.length, 2);++ const one = windowShelf(30);+ const small = await fetchGalleryWindow(one.fetchPage, (p) => p.next, 50, 200);+ assert.equal(small.audio.length, 30);+ assert.equal(one.calls.length, 1);++ const big = windowShelf(600);+ const stopped = await fetchGalleryWindow(big.fetchPage, (p) => p.next, 500, 200, () => true);+ assert.equal(big.calls.length, 1);+ assert.equal(stopped.audio.length, 200);+});++test("the gallery refresh fetches its whole window before merging", () => {assert.match(audioPageSource,- /wanted > asked\s*\?\s*\{ clips: \[\.\.\.page\.audio\], stitched: false \}\s*:\s*mergeGalleryPage\(/,+ /const page = await fetchGalleryWindow\([\s\S]*?\);[\s\S]*?const \{ clips: merged, stitched \} = mergeGalleryPage\(\s*page\.audio,/,);+ assert.doesNotMatch(audioPageSource, /wanted > asked/);});test("a capped restore refresh invalidates a page fetched from the older cursor", () => {@@ -812,3 +858,23 @@ test("selecting CPU never ejects a resident MiniMax, which cannot load on CPU",assert.ok(guard < eject, "the guard must return before the eject");assert.match(handler.slice(guard, eject), /return;/);});++test("history scrolling loads until the page gains a row, not one gallery page", () => {+ // A gallery page holding only the other page's clips added no visible row, so the list kept its+ // height and no later scroll event could ask for more.+ assert.match(audioPageSource, /loadMore: loadMoreVisible,/);+ assert.match(+ audioPageSource,+ /const loadMoreVisible = useCallback\(async \(\) => \{[\s\S]*?await loadGalleryUntil\(\{\s*has: \(\) => countVisible\(\) > before,/,+ );+});++test("a run that loads a model first says so before it starts", () => {+ assert.equal(+ modelLoadNote({ model: "Kokoro", page: "Speak", seconds: 4.6 }),+ "Loads Kokoro for Speak, about 5 s",+ );+ assert.equal(modelLoadNote({ model: "Kokoro", page: "Speak" }), "Loads Kokoro for Speak");+ assert.equal(modelLoadNote({ model: "Kokoro", page: "Speak", seconds: 0.2 }), "Loads Kokoro for Speak, about 1 s");+ assert.equal(modelLoadNote({ model: null, page: "Speak", seconds: 5 }), null);+});diff --git a/studio/frontend/tests/audio-picker-filter.test.ts b/studio/frontend/tests/audio-picker-filter.test.tsnew file mode 100644index 00000000000..422af0fca47--- /dev/null+++ b/studio/frontend/tests/audio-picker-filter.test.ts@@ -0,0 +1,140 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import { readSrc, registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();+const { audioRowMatchesWorkflow } = await import(+ "../src/features/audio/picker-filter.ts"+);+const { audioModelsForTask, isMusicGenerationModel } = await import(+ "../src/features/audio/catalog.ts"+);++type Workflow = "speak" | "music" | "transcribe";+const WORKFLOWS: Workflow[] = ["speak", "music", "transcribe"];++function workflowsFor(row: Parameters<typeof audioRowMatchesWorkflow>[0]) {+ return WORKFLOWS.filter((workflow) => audioRowMatchesWorkflow(row, workflow));+}++test("the backend's audio_workflows decides when the row has it", () => {+ assert.deepEqual(+ workflowsFor({+ id: "x/y",+ task: "text-to-speech",+ audioWorkflows: ["music"],+ }),+ ["music"],+ );+});++test("a speech row lists only on Speak", () => {+ assert.deepEqual(+ workflowsFor({ id: "hexgrad/Kokoro-82M", task: "text-to-speech" }),+ ["speak"],+ );+ assert.deepEqual(+ workflowsFor({+ id: "audio-cpp/audio.cpp-gguf/Kokoro-82M-GGUF",+ task: "text-to-speech",+ audioType: "audiocpp_tts",+ }),+ ["speak"],+ );+});++test("a music GGUF (text-to-audio, no audio type) lists only on Music", () => {+ assert.deepEqual(+ workflowsFor({+ id: "audio-cpp/audio.cpp-gguf/Stable-Audio-3-Small-Music-GGUF",+ task: "text-to-audio",+ audioType: null,+ }),+ ["music"],+ );+});++test("MiniMax Music 3 is tagged text-to-speech but lists only on Music", () => {+ assert.deepEqual(+ workflowsFor({+ id: "MiniMaxAI/MiniMax-Music3",+ task: "text-to-speech",+ audioType: "minimax_music3",+ }),+ ["music"],+ );+});++test("an ASR row lists only on Transcribe", () => {+ assert.deepEqual(+ workflowsFor({+ id: "openai/whisper-small",+ task: "automatic-speech-recognition",+ }),+ ["transcribe"],+ );+});++test("a row with nothing to classify it stays listed", () => {+ assert.deepEqual(workflowsFor({ id: "someone/unknown" }), WORKFLOWS);+});++test("splitting the speech catalog on music leaves no model out and none twice", () => {+ const tts = audioModelsForTask("tts");+ const speak = tts.filter((model) => !isMusicGenerationModel(model.id));+ const music = tts.filter((model) => isMusicGenerationModel(model.id));+ assert.ok(speak.length > 0);+ assert.ok(music.length > 0);+ const speakIds = new Set(speak.map((model) => model.id));+ assert.equal(music.filter((model) => speakIds.has(model.id)).length, 0);+ assert.deepEqual(+ [...speak, ...music].map((model) => model.id).sort(),+ tts.map((model) => model.id).sort(),+ );+});++test("an undefined rowFilter leaves the picker rows untouched", () => {+ const pickers = readSrc(+ "features/model-picker/components/model-selector/pickers.tsx",+ );+ const guards = pickers.match(/\(!rowFilter \|\|\s*rowFilter\(\{/g) ?? [];+ // Cached GGUF, cached repos, LM Studio, ./models and custom folders; Hub search rows stay unfiltered.+ assert.equal(guards.length, 5);+ // Each On Device list applies it, so a custom-folder speech model is not offered on the Music page.+ for (const list of [+ "sortedCachedGguf",+ "sortedCachedModels",+ "sortedLmStudio",+ "sortedLocalDir",+ "sortedCustomFolderModels",+ ]) {+ const start = pickers.indexOf(`const ${list} = useMemo(`);+ assert.ok(start >= 0, list);+ const body = pickers.slice(start, pickers.indexOf("\n );\n", start));+ assert.match(body, /\(!rowFilter \|\|\s*rowFilter\(\{/, list);+ assert.match(body, /rowFilter,\n\s*\]/, `${list} deps`);+ }+ const selector = readSrc(+ "features/model-picker/components/model-selector.tsx",+ );+ assert.match(selector, /rowFilter=\{rowFilter\}/);+});++test("typed Hub search results are scoped to the page too", () => {+ const pickers = readSrc("features/model-picker/components/model-selector/pickers.tsx");+ const body = pickers.slice(pickers.indexOf("const searchIdsFrom = useCallback("));+ const block = body.slice(0, body.indexOf("\n ],") + 1);+ assert.match(block, /\.filter\(\(r\) => !rowFilter \|\| rowFilter\(\{ id: r\.id, task: r\.pipelineTag \}\)\)/);+ assert.match(block, /\n\s+rowFilter,\n/);+});++test("a Hub music model tagged text-to-speech stays on Music", () => {+ const row = { id: "MiniMaxAI/MiniMax-Music3", task: "text-to-speech" };+ assert.equal(audioRowMatchesWorkflow(row, "speak"), false);+ assert.equal(audioRowMatchesWorkflow(row, "music"), true);+ assert.equal(audioRowMatchesWorkflow({ id: "hexgrad/Kokoro-82M", task: "text-to-speech" }, "speak"), true);+});diff --git a/studio/frontend/tests/audio-picker-policy.test.ts b/studio/frontend/tests/audio-picker-policy.test.tsindex b41451f36bd..806a6801476 100644--- a/studio/frontend/tests/audio-picker-policy.test.ts+++ b/studio/frontend/tests/audio-picker-policy.test.ts@@ -118,6 +118,7 @@ import {} from "../src/features/model-picker/components/model-selector/model-catalog.ts";import { readSrc } from "./helpers/kit.ts";+import { readAudioWorkspaceSource } from "./helpers/audio-workspace.ts";const pickerSource = readSrc("features/model-picker/components/model-selector/pickers.tsx");@@ -770,7 +771,7 @@ test("the audio page asks the GGUF-aware TTS predicate for trained rows", () =>// GGUF_TTS_AUDIO_TYPES leaves csm out because llama.cpp has no CSM decoder. Calling// isTtsAudioType without the flag answered off the wider Transformers list and offered// a csm GGUF export that fails at load.- const source = readSrc("features/audio/audio-page.tsx");+ const source = readAudioWorkspaceSource();assert.match(source,/isTtsAudioType\(\s*lora\.audio_type,\s*lora\.export_type === "gguf",?\s*\)/,diff --git a/studio/frontend/tests/audio-sidebar-workflows.test.ts b/studio/frontend/tests/audio-sidebar-workflows.test.tsnew file mode 100644index 00000000000..9d7cbc2add0--- /dev/null+++ b/studio/frontend/tests/audio-sidebar-workflows.test.ts@@ -0,0 +1,151 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import { readSrc } from "./helpers/kit.ts";++const SIDEBAR = readSrc("components/app-sidebar.tsx");++function block(source: string, start: string, end: string): string {+ const from = source.indexOf(start);+ assert.notEqual(from, -1, `missing ${start}`);+ const to = source.indexOf(end, from + start.length);+ assert.notEqual(to, -1, `missing ${end} after ${start}`);+ return source.slice(from, to);+}++test("Images keeps its list and chevron, now thin wrappers over the shared media pieces", () => {+ const images = block(+ SIDEBAR,+ "function ImagesNavDisclosure()",+ "function AudioNavDisclosure()",+ );+ assert.match(+ images,+ /<MediaNavDisclosure[\s\S]*revealClassName=\{IMAGES_DISCLOSURE_REVEAL\}/,+ );+ assert.match(+ images,+ /function ImagesWorkflowList\(\{\s*active,\s*collapsed,\s*onPick,\s*\}/,+ );+ assert.match(images, /tabs=\{WORKFLOW_TABS\}/);+ assert.match(+ images,+ /enabled=\{\(id\) => isWorkflowEnabled\(id, supported\)\}/,+ );+ assert.match(+ images,+ /listed=\{!collapsed && \(active \? pageMode !== "train" : expanded\)\}/,+ );+ assert.match(+ images,+ /const current = active && pageMode === "create" \? workflow : null;/,+ );+ // The reveal classes keep their literal spelling so Tailwind still generates them.+ assert.match(+ SIDEBAR,+ /const IMAGES_DISCLOSURE_REVEAL =\s*"group-hover\/images-item:opacity-100 group-hover\/images-item:pointer-events-auto";/,+ );+ assert.match(+ SIDEBAR,+ /const AUDIO_DISCLOSURE_REVEAL =\s*"group-hover\/audio-item:opacity-100 group-hover\/audio-item:pointer-events-auto";/,+ );+});++test("the Audio list highlights the requested or committed workflow, and never disables a row", () => {+ const audio = block(+ SIDEBAR,+ "function AudioWorkflowList(",+ "// Hugeicons' three dots",+ );+ assert.match(+ audio,+ /useAudioWorkspaceStore\(\(s\) => s\.requestedWorkflow\)/,+ );+ assert.match(+ audio,+ /const current = active \? \(requested \?\? workflow\) : null;/,+ );+ assert.match(audio, /tabs=\{AUDIO_WORKFLOWS\}/);+ assert.match(audio, /enabled=\{audioWorkflowAlwaysEnabled\}/);+ assert.match(SIDEBAR, /const audioWorkflowAlwaysEnabled = \(\) => true;/);+ assert.match(audio, /listed=\{!collapsed && \(active \|\| expanded\)\}/);+});++test("a pinned Audio row lists its workflows and hands picks to the page as requests", () => {+ assert.match(SIDEBAR, /id === "audio" && "group\/audio-item"/);+ assert.match(SIDEBAR, /const audioWorkflowsListed = sidebarRowsLabelled;/);+ assert.match(+ SIDEBAR,+ /\(id === "images" && imagesWorkflowsListed\) \|\|\s*\(id === "audio" && audioWorkflowsListed\)\s*\? false\s*: row\.active/,+ );+ assert.match(+ SIDEBAR,+ /id === "audio" &&\s*!row\.active &&\s*sidebarRowsLabelled \? \(\s*<AudioNavDisclosure \/>/,+ );+ assert.match(+ SIDEBAR,+ /<AudioWorkflowList\s+active=\{row\.active\}\s+collapsed=\{!sidebarRowsLabelled\}\s+onPick=\{pickAudioWorkflow\}/,+ );+ const pick = block(SIDEBAR, "const pickAudioWorkflow =", "};");+ assert.match(+ pick,+ /useAudioWorkspaceStore\.getState\(\)\.requestWorkflow\(workflowId\);/,+ );+ assert.match(pick, /navigate\(\{ to: "\/audio" \}\);/);+ assert.match(pick, /closeMobileIfOpen\(\);/);+ assert.doesNotMatch(SIDEBAR, /commitWorkflow/);+});++test("More opens Audio's workflows in a submenu that keeps the flyout open on the way in", () => {+ const more = block(SIDEBAR, "{overflowNavIds.map((id) => {", "<MoreMenuItem");+ assert.match(+ more,+ /if \(id === "audio"\) \{\s*return \(\s*<AudioMoreSubmenu/,+ );+ assert.match(more, /disabled=\{rowState\.disabled\}/);+ assert.match(more, /\.\.\.sidebarSubmenuOffsets,/);+ assert.match(more, /\.\.\.moreHover\.content,/);+ assert.match(more, /onPick=\{pickAudioWorkflow\}/);+ const resolves =+ SIDEBAR.match(/const rowState = resolveNavRowState\(row\);/g) ?? [];+ assert.equal(resolves.length, 2);++ const submenu = block(+ SIDEBAR,+ "function AudioMoreSubmenu(",+ "export function AppSidebar()",+ );+ assert.match(submenu, /<DropdownMenuSubTrigger/);+ assert.match(+ submenu,+ /className=\{cn\("gap-2\.5", active && "bg-accent\/60"\)\}/,+ );+ assert.match(submenu, /<DropdownMenuSubContent \{\.\.\.contentProps\}/);+ assert.match(submenu, /AUDIO_WORKFLOWS\.map/);+ assert.match(submenu, /onSelect=\{\(\) => onPick\(tab\.id\)\}/);+ assert.match(submenu, /current === tab\.id && "bg-accent\/60"/);+ assert.doesNotMatch(submenu, /max-h/);+});++test("the Audio row stays lit while hovered, like Images", () => {+ const css = readSrc("index.css");+ assert.match(+ css,+ /\n\t\.group\\\/audio-item:hover > \.relative > \.sidebar-nav-btn,/,+ );+ assert.match(+ css,+ /\.dark \.group\\\/audio-item:hover > \.relative > \.sidebar-nav-btn,/,+ );+});++test("Audio is still unpinned by default", () => {+ const store = readSrc("features/settings/stores/appearance-custom-store.ts");+ assert.match(+ store,+ /SIDEBAR_NAV_DEFAULT_PINNED[^=]*= \{[^}]*\n\s*audio: false,/,+ );+});diff --git a/studio/frontend/tests/audio-stt-download-fallback.test.ts b/studio/frontend/tests/audio-stt-download-fallback.test.tsindex abe6b992e37..ebf768322d5 100644--- a/studio/frontend/tests/audio-stt-download-fallback.test.ts+++ b/studio/frontend/tests/audio-stt-download-fallback.test.ts@@ -5,8 +5,9 @@ import assert from "node:assert/strict";import test from "node:test";import { readSrc } from "./helpers/kit.ts";+import { readAudioWorkspaceSource } from "./helpers/audio-workspace.ts";-const source = readSrc("features/audio/audio-page.tsx");+const source = readAudioWorkspaceSource();const mirrorSource = readSrc("features/settings/lib/stt-download-mirror.ts");test("STT download polling uses the available engine fallback", () => {diff --git a/studio/frontend/tests/audio-transcript-lifecycle.test.ts b/studio/frontend/tests/audio-transcript-lifecycle.test.tsindex 3d82f695c43..ae0a078f359 100644--- a/studio/frontend/tests/audio-transcript-lifecycle.test.ts+++ b/studio/frontend/tests/audio-transcript-lifecycle.test.ts@@ -5,10 +5,11 @@ import assert from "node:assert/strict";import test from "node:test";import ts from "typescript";import { readSrc, readText } from "./helpers/kit.ts";+import { readAudioWorkspaceSource } from "./helpers/audio-workspace.ts";import { AUTH_SESSION_ENDING_EVENT } from "../src/features/auth/session-events.ts";import { readTranscriptDraft, writeTranscriptDraft } from "../src/features/audio/transcript-draft.ts";-const source = readSrc("features/audio/audio-page.tsx");+const source = readAudioWorkspaceSource();test("macOS termination checks unsaved transcripts before allowing exit", () => {const native = readText("../../src-tauri/src/main.rs");@@ -123,7 +124,7 @@ test("changing model residency preserves the transcript and its recorded origin"const refresh = section("const refreshSttStatus", "const sttSelected");const release = section("const releaseTranscribeSelection",- "const ensureClipSrc",+ "const ensureSttLoaded",);assert.doesNotMatch(refresh, /clearTranscript\(/);assert.doesNotMatch(release, /clearTranscript\(/);diff --git a/studio/frontend/tests/audio-tts-download-manager.test.ts b/studio/frontend/tests/audio-tts-download-manager.test.tsindex 8e1e95bfd94..d7930539502 100644--- a/studio/frontend/tests/audio-tts-download-manager.test.ts+++ b/studio/frontend/tests/audio-tts-download-manager.test.ts@@ -4,9 +4,9 @@import assert from "node:assert/strict";import test from "node:test";-import { readSrc } from "./helpers/kit.ts";+import { readAudioWorkspaceSource } from "./helpers/audio-workspace.ts";-const source = readSrc("features/audio/audio-page.tsx");+const source = readAudioWorkspaceSource();test("uncached remote TTS GGUFs stage the picked quant through the shared manager", () => {assert.match(source, /useStagedDownload\(\{\s*scopeId: "audio"/);@@ -27,7 +27,7 @@ test("uncached remote TTS GGUFs stage the picked quant through the shared managetest("remote code approval precedes native model staging and survives completion", () => {const start = source.indexOf("const loadOrStageTtsModel");- const end = source.indexOf("const ensureSttLoaded", start);+ const end = source.indexOf("// A hidden page may let the shared download continue", start);const stagedFlow = source.slice(start, end);assert.ok(start >= 0 && end > start);assert.ok(diff --git a/studio/frontend/tests/audio-waveform-peaks.test.ts b/studio/frontend/tests/audio-waveform-peaks.test.tsnew file mode 100644index 00000000000..7cb1b61bac8--- /dev/null+++ b/studio/frontend/tests/audio-waveform-peaks.test.ts@@ -0,0 +1,58 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import { readSrc } from "./helpers/kit.ts";++const { computePeaks, formatSeconds, WAVEFORM_BARS } = await import(+ "../src/features/audio/components/waveform-peaks.ts"+);++test("peaks use the bar count and stay within 0..1", () => {+ const samples = new Float32Array(10_000);+ for (let i = 0; i < samples.length; i += 1)+ samples[i] = Math.sin(i / 20) * (i / samples.length) * 3;+ const peaks = computePeaks([samples], 50);+ assert.equal(peaks.length, 50);+ assert.ok(peaks.every((peak) => peak >= 0 && peak <= 1));+ assert.equal(Math.max(...peaks), 1);+ // Louder towards the end, as the ramp is.+ assert.ok(peaks[49] > peaks[5]);+ assert.equal(computePeaks([samples]).length, WAVEFORM_BARS);+});++test("silence draws flat bars, not amplified noise", () => {+ assert.deepEqual(+ computePeaks([new Float32Array(4000)], 8),+ new Array(8).fill(0),+ );+ const hiss = new Float32Array(4000).fill(0.0001);+ assert.deepEqual(computePeaks([hiss], 8), new Array(8).fill(0));+ assert.deepEqual(computePeaks([], 4), [0, 0, 0, 0]);+});++test("every channel counts, and a clip shorter than the bar count still fills it", () => {+ const left = new Float32Array([0, 0, 0, 0]);+ const right = new Float32Array([0, 0.5, 0, 1]);+ assert.deepEqual(computePeaks([left, right], 4), [0, 0.5, 0, 1]);+ assert.equal(computePeaks([new Float32Array([0.5])], 6).length, 6);+});++test("durations read as m:ss", () => {+ assert.equal(formatSeconds(4.7), "0:05");+ assert.equal(formatSeconds(75), "1:15");+ assert.equal(formatSeconds(3725), "1:02:05");+ assert.equal(formatSeconds(null), "0:00");+});++test("the waveform is neutral, keyboard-playable and static", () => {+ const source = readSrc("features/audio/components/waveform.tsx");+ assert.match(source, /"text-foreground"/);+ assert.match(source, /"text-muted-foreground"/);+ assert.match(source, /event\.key === " "/);+ assert.match(source, /aria-valuetext/);+ // No animation, so reduced motion needs nothing extra.+ assert.doesNotMatch(source, /animate-|transition-/);+});diff --git a/studio/frontend/tests/audio-workflows.test.ts b/studio/frontend/tests/audio-workflows.test.tsnew file mode 100644index 00000000000..983e5f9ad1c--- /dev/null+++ b/studio/frontend/tests/audio-workflows.test.ts@@ -0,0 +1,73 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import { readText, registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();+const {+ AUDIO_WORKFLOWS,+ audioWorkflowForAudioType,+ audioWorkflowForTask,+ audioWorkflowTab,+ clipWorkflow,+ isAudioWorkflowId,+ MUSIC_AUDIO_TYPES,+ slotForWorkflow,+} = await import("../src/features/audio/workflows.ts");++test("the Audio page offers Speak, Music and Transcribe in that order", () => {+ assert.deepEqual(+ AUDIO_WORKFLOWS.map((tab) => tab.id),+ ["speak", "music", "transcribe"],+ );+ assert.equal(audioWorkflowTab("speak").heading, "Text to speech");+ assert.equal(audioWorkflowTab("music").heading, "Create music");+ assert.equal(audioWorkflowTab("transcribe").heading, "Transcribe");+});++test("Speak and Music share the main slot; only Transcribe uses the sidecar", () => {+ assert.equal(slotForWorkflow("speak"), "speak");+ assert.equal(slotForWorkflow("music"), "speak");+ assert.equal(slotForWorkflow("transcribe"), "transcribe");+});++test("Create|Train is offered on Speak and Transcribe, not Music", () => {+ assert.equal(audioWorkflowTab("speak").createTrain, true);+ assert.equal(audioWorkflowTab("music").createTrain, false);+ assert.equal(audioWorkflowTab("transcribe").createTrain, true);+});++test("pipeline tags map onto workflows and anything else is ignored", () => {+ assert.equal(audioWorkflowForTask("text-to-speech"), "speak");+ assert.equal(audioWorkflowForTask("automatic-speech-recognition"), "transcribe");+ assert.equal(audioWorkflowForTask("text-to-audio"), "music");+ assert.equal(audioWorkflowForTask("text-generation"), null);+ assert.equal(audioWorkflowForTask(undefined), null);+ assert.equal(isAudioWorkflowId("music"), true);+ assert.equal(isAudioWorkflowId("separate"), false);+});++test("a clip without a workflow falls back to its audio type", () => {+ assert.equal(clipWorkflow({ audio_type: "minimax_music3" }), "music");+ assert.equal(clipWorkflow({ audio_type: "audiocpp_music" }), "music");+ assert.equal(clipWorkflow({ audio_type: "audiocpp_tts" }), "speak");+ assert.equal(clipWorkflow({ audio_type: "snac" }), "speak");+ assert.equal(clipWorkflow({ workflow: "music", audio_type: "snac" }), "music");+ assert.equal(clipWorkflow({ workflow: "edit", audio_type: "audiocpp_music" }), "music");+ assert.equal(audioWorkflowForAudioType(null), "speak");+});++test("the music audio types match the backend's list", () => {+ const backend = readText("../../backend/core/inference/audio_workflows.py");+ const block = backend.match(/MUSIC_AUDIO_TYPES[^=]*=\s*frozenset\(\s*[({]([^)}]*)[)}]/);+ assert.ok(block, "MUSIC_AUDIO_TYPES literal not found in audio_workflows.py");+ const names = new Set(+ [...block[1].matchAll(/"([^"]+)"|([A-Z_]+_AUDIO_TYPE)/g)].map(+ (m) => m[1] ?? (m[2] === "AUDIO_CPP_MUSIC_AUDIO_TYPE" ? "audiocpp_music" : m[2]),+ ),+ );+ assert.deepEqual(names, new Set(MUSIC_AUDIO_TYPES));+});diff --git a/studio/frontend/tests/audio-workspace-split.test.ts b/studio/frontend/tests/audio-workspace-split.test.tsnew file mode 100644index 00000000000..c129df02a9a--- /dev/null+++ b/studio/frontend/tests/audio-workspace-split.test.ts@@ -0,0 +1,218 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import { readSrc } from "./helpers/kit.ts";++const host = readSrc("features/audio/audio-page.tsx");+const slot = readSrc("features/audio/hooks/use-audio-model-slot.ts");+const handoff = readSrc("features/audio/hooks/use-audio-handoff.ts");+const generation = readSrc("features/audio/hooks/use-speech-generation.ts");+const gallery = readSrc("features/audio/hooks/use-audio-gallery.tsx");+const tour = readSrc("features/audio/tour/steps.tsx");++test("the host calls its hooks in the order their effects ran in the single page", () => {+ const order = [+ "useSttSidecar(",+ "useTranscription(",+ "useAudioGallery(",+ "useAudioModelSlot(",+ "useSpeechGeneration(",+ "useAudioHandoff(",+ ].map((call) => host.indexOf(call));+ assert.ok(order.every((at) => at > 0), String(order));+ assert.deepEqual([...order].sort((a, b) => a - b), order);+ assert.ok(host.indexOf("// Resync on activation") < host.indexOf("useAudioModelSlot("));+});++test("only the page commits a workflow; the sidebar's request goes through the same gate", () => {+ // A refused request is kept and retried when busy settles; the commit is what clears it.+ assert.match(+ host,+ /if \(!active \|\| requestedWorkflow === null\) return;\s*transitionWorkflow\(requestedWorkflow\);\s*\}, \[active, busy, requestedWorkflow, transitionWorkflow\]\);/,+ );+ assert.doesNotMatch(host, /clearRequestedWorkflow\(\)/);+ assert.match(+ slot,+ /\} else if \(!transitionMode\(slotForWorkflow\(next\)\)\) \{\s*return false;\s*\}\s*store\.commitWorkflow\(next\);/,+ );+ assert.match(host, /mode === "transcribe" \? "transcribe" : musicGeneration \? "music" : "speak"/);+});++test("a loaded model opens the page that fits it", () => {+ assert.match(+ slot,+ /const loadedWorkflow = isMusicGenerationModel\(repoId, res\.audio_type\)\s*\? "music"\s*: "speak";[\s\S]{0,200}?if \(modeRef\.current === "speak"\) \{\s*useAudioWorkspaceStore\.getState\(\)\.commitWorkflow\(loadedWorkflow\);/,+ );+ assert.match(host, /adoptWorkflow\("music"\)/);+});++test("?workflow= names the page ahead of ?task=, and both go through the workflow gate", () => {+ // Task-only links take the same gate as ?workflow=, so a Speak/Music switch never skips the busy check.+ assert.match(+ handoff,+ /const routedWorkflow = audioRouteIntent\(routeSearch\);\s*if \(routedWorkflow === null\) return;[\s\S]{0,120}?if \(!transitionWorkflow\(routedWorkflow\)\) return;\s*void navigateSelf\(\{ to: "\/audio", search: \{\}, replace: true \}\);/,+ );+ assert.doesNotMatch(handoff, /commitWorkflow\(/);+ // A Library clip asks for its page through ?workflow=, so a busy page retries it later.+ assert.match(+ handoff,+ /search: \(prev\) => \(\{ \.\.\.prev, workflow: clipWorkflow\(clip\) \}\)/,+ );+});++test("Speak and Music keep separate drafts that survive a reload", () => {+ assert.match(generation, /readLastPrompt\(ttsDraftKey\("prompt", "speak"\)\)/);+ assert.match(generation, /readLastPrompt\(ttsDraftKey\("prompt", "music"\)\)/);+ assert.match(generation, /const base = workflow === "music" \? "audio:music" : "audio";/);+ assert.match(generation, /saveLastPrompt\(ttsDraftKey\(field, page\), next\);/);+});++test("history is per page, and Clear all clears only that page", () => {+ assert.match(+ gallery,+ /clips\.filter\(\(clip\) => clipWorkflow\(clip\) === workflow\)/,+ );+ assert.match(gallery, /await clearAudioGallery\(workflow\);/);+ assert.match(host, /\(\) => handleClearGallery\(ttsWorkflow\)/);+});++test("Create|Train shows only where the page trains", () => {+ assert.match(+ host,+ /\{workflowTab\.createTrain \? \(\s*<PillTabs\s*ariaLabel="Page mode"/,+ );+});++test("Generate says why it is off and runs from Mod+Enter anywhere on the page", () => {+ assert.match(host, /: "Type the text to speak\."/);+ assert.match(host, /const chooseModelAction = \{ label: "Choose a model", onClick: openSelector \};/);+ assert.match(host, /\{ label: "Choose a music model", onClick: openSelector \}/);+ assert.match(host, /if \(busy === "generating"\) setGenerationError\(null\);/);+ assert.match(host, /!pageRootRef\.current\?\.contains\(event\.target\)/);+ assert.match(host, /if \(canGenerate\) void handleGenerate\(\);/);+});++test("each page tours its own model and settings", () => {+ assert.match(tour, /workflow: AudioWorkflowId;/);+ assert.match(tour, /if \(workflow === "transcribe"\)/);+ assert.match(tour, /modelStep\(workflow\)/);+ assert.match(host, /buildAudioTourSteps\(\{ workflow: pageWorkflow \}\)/);+});++test("the rail heading switches pages from a menu of every workflow", () => {+ // A tab row of 5-7 pages truncated every label in the default rail; the title menu lists them all.+ const host = readSrc("features/audio/audio-page.tsx");+ assert.doesNotMatch(host, /ariaLabel="Audio workflow"/);+ assert.match(+ host,+ /<WorkflowTitleMenu\s+workflow=\{pageWorkflow\}\s+onSelect=\{transitionWorkflow\}/,+ );+ const menu = readSrc("features/audio/components/workflow-title-menu.tsx");+ assert.match(menu, /data-tour="audio-mode"/);+ assert.match(menu, /AUDIO_WORKFLOWS\.map\(\(tab\) =>/);+ assert.match(menu, /\{tab\.hint\}/);+ // Radio items: the current page is ticked and announced as checked.+ assert.match(menu, /<DropdownMenuRadioGroup\s+value=\{current\.id\}/);+});++test("results show as a clip card with a waveform, never autoplaying", () => {+ const output = readSrc("features/audio/pages/tts-workspace.tsx");+ const card = readSrc("features/audio/components/clip-card.tsx");+ assert.doesNotMatch(output, /<audio\b/);+ assert.doesNotMatch(output + card, /autoPlay/);+ assert.match(output, /<ClipCard\s+\/\/[^\n]*\n\s*key=\{selectedClip\.id\}/);+ assert.match(card, /<Waveform\s+peaks=\{peaks\}/);+ // A run in progress stands where its clip will appear, with Stop, and no second live region.+ assert.match(+ output,+ /\{pending \? \(\s*<PendingClipCard \{\.\.\.pending\} \/>/,+ );+ assert.match(+ host,+ /pending:\s*busy === "generating" && generationPresentation/,+ );+ assert.match(host, /onStop: handleStopGeneration,/);+ assert.doesNotMatch(card, /aria-live/);+});++test("Send to lists the other Audio pages from the shared workflow list", () => {+ const card = readSrc("features/audio/components/clip-card.tsx");+ assert.match(+ card,+ /AUDIO_WORKFLOWS\.filter\(\s*\(tab\) => tab\.id !== current && handlers\[tab\.id\],?\s*\)/,+ );+ // Bytes first: a failed fetch must not leave the user on another page.+ assert.match(+ host,+ /const blob = await fetchClipBlob\(clip\.url\);[\s\S]*?if \(!transitionWorkflow\("transcribe"\)\) return;/,+ );+});++test("an unlisted clip stays on the page that made it", () => {+ assert.equal((generation.match(/saved: (?:true|false),\s*workflow,/g) ?? []).length, 2);+ assert.match(gallery, /const pageFallbackClip =\s*fallbackClip\?\.workflow === workflow \? fallbackClip : null;/);+ assert.match(gallery, /if \(!enabled \|\| selectedClip \|\| pageFallbackClip\) return;/);+ assert.match(host, /fallbackClip: pageFallbackClip,\s*\} = useWorkflowHistory\(/);+ assert.match(host, /handleDeleteClip,\s*fallbackClip: pageFallbackClip,/);+});++test("switching between Speak and Music passes the same busy gate as a mode switch", () => {+ assert.match(+ slot,+ /next !== store\.workflow &&\s*mode === "speak" &&\s*slotForWorkflow\(next\) === "speak"\s*\) \{\s*if \(\s*!canTransitionAudioMode\(busyRef\.current, generationPhaseRef\.current\)\s*\) \{[\s\S]{0,200}?return false;\s*\}\s*if \(busyRef\.current === "generating"\) handleStopGeneration\(\);/,+ );+});++test("the Max tokens stop warning from main lives in the generation hook", () => {+ assert.match(+ generation,+ /if \(generated\.choices\[0\]\?\.finish_reason === "length"\)\s*toast\.warning\(\s*maxTokens < TTS_MAX_TOKENS/,+ );+});++test("auto-selecting a page's history keeps another page's unsaved clip", () => {+ assert.match(gallery, /if \(first\) selectClip\(first\.id, fallbackClip !== null\);/);+});++test("Send to waits for a running task instead of stopping it and dropping the clip", () => {+ // A switch mid-run stops the run, but the page stays busy until the stopped run settles, so the+ // transcription was refused and the clip silently dropped.+ assert.match(+ host,+ /transcribe: \(\) => \{[\s\S]*?const busyNow = \(\) => \{\s*if \(busyRef\.current === null\) return false;\s*toast\.info\([^)]*\);\s*return true;\s*\};\s*if \(busyNow\(\)\) return;/,+ );+});++test("switching between Speak and Music disowns a pending pick", () => {+ assert.match(+ slot,+ /if \(busyRef\.current === "generating"\) handleStopGeneration\(\);\s*invalidatePendingTtsSelection\(\);\s*\} else if \(!transitionMode/,+ );+});++test("trained checkpoints are split between Speak and Music like the catalog", () => {+ assert.match(+ host,+ /trainedTtsModels\.filter\(\s*\(model\) =>\s*isMusicGenerationModel\(model\.id, model\.audioType\) ===\s*\(ttsWorkflow === "music"\),\s*\)/,+ );+});++test("picking a clip on one page keeps the other page's unsaved clip", () => {+ // A clip that failed to save exists only as the fallback; clicking a History row on the other+ // page cleared it, so returning to its page lost the clip.+ assert.match(+ gallery,+ /const otherPage =\s*clip !== undefined &&\s*fallbackClipRef\.current !== null &&\s*clipWorkflow\(clip\) !== fallbackClipRef\.current\.workflow;\s*if \(!keepFallback && !otherPage\) setFallbackClip\(null\);/,+ );+});++test("Send to checks again after the clip downloads, before switching pages", () => {+ // Generate pressed while the clip downloaded was stopped by the switch, and the clip dropped.+ assert.match(+ host,+ /const blob = await fetchClipBlob\(clip\.url\);[\s\S]*?if \(busyNow\(\)\) return;\s*if \(!transitionWorkflow\("transcribe"\)\) return;/,+ );+});diff --git a/studio/frontend/tests/audio-workspace-store.test.ts b/studio/frontend/tests/audio-workspace-store.test.tsnew file mode 100644index 00000000000..4806f93b352--- /dev/null+++ b/studio/frontend/tests/audio-workspace-store.test.ts@@ -0,0 +1,45 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++const { useAudioWorkspaceStore } = await import(+ "../src/features/audio/stores/audio-workspace-store.ts"+);++test("the workspace opens on Speak with nothing requested", () => {+ const state = useAudioWorkspaceStore.getState();+ assert.equal(state.workflow, "speak");+ assert.equal(state.requestedWorkflow, null);+ assert.equal(state.navExpanded, false);+});++test("a first look at the loaded model opens its page only until something chooses one", () => {+ const store = useAudioWorkspaceStore;+ store.getState().adoptWorkflow("music");+ assert.equal(store.getState().workflow, "music");+ store.getState().commitWorkflow("speak");+ store.getState().adoptWorkflow("music");+ assert.equal(store.getState().workflow, "speak");+});++test("a request does not move the committed workflow until the page takes it", () => {+ const store = useAudioWorkspaceStore;+ store.getState().requestWorkflow("music");+ assert.equal(store.getState().workflow, "speak");+ assert.equal(store.getState().requestedWorkflow, "music");+ store.getState().commitWorkflow("music");+ store.getState().clearRequestedWorkflow();+ assert.equal(store.getState().workflow, "music");+ assert.equal(store.getState().requestedWorkflow, null);+ store.getState().commitWorkflow("speak");+});++test("any committed switch settles a pending request, so it never fires later", () => {+ const store = useAudioWorkspaceStore;+ store.getState().requestWorkflow("music");+ store.getState().commitWorkflow("transcribe");+ assert.equal(store.getState().requestedWorkflow, null);+ store.getState().commitWorkflow("speak");+});diff --git a/studio/frontend/tests/chat-speech-model-not-adopted.test.ts b/studio/frontend/tests/chat-speech-model-not-adopted.test.tsindex 9e6bff19b80..869f25a29db 100644--- a/studio/frontend/tests/chat-speech-model-not-adopted.test.ts+++ b/studio/frontend/tests/chat-speech-model-not-adopted.test.ts@@ -114,7 +114,7 @@ test("a TTS load announces its own runtime so chat re-reads the slot", () => {// Chat ignores its own loads when reconciling, so a TTS load announced as "chat" left// chat naming a model the Audio page had evicted.- const audio = readText("../src/features/audio/audio-page.tsx");+ const audio = readText("../src/features/audio/hooks/use-audio-model-slot.ts");assert.match(audio, /runtime: "tts",/);const hook = readText("../src/features/chat/hooks/use-chat-model-runtime.ts",diff --git a/studio/frontend/tests/gallery-flags.test.ts b/studio/frontend/tests/gallery-flags.test.tsindex 56548cfcc2c..56d48663346 100644--- a/studio/frontend/tests/gallery-flags.test.ts+++ b/studio/frontend/tests/gallery-flags.test.ts@@ -5,6 +5,7 @@ import assert from "node:assert/strict";import test from "node:test";import {+ type FlaggableItem,PAGE_MAX_ATTEMPTS,applyPin,fetchNextPage,@@ -17,6 +18,7 @@ import {pinnedOrder,removeGalleryItem,restorePinOrder,+ scopedMoveAfterId,serializeById,sortGalleryItems,} from "../src/lib/gallery-flags.ts";@@ -539,3 +541,51 @@ test("a manual key compares in seconds against ISO timestamps too", () => {];assert.deepEqual(ids(sortGalleryItems(items)), ["dragged", "newer"]);});++// Shelf rows tagged with the page that shows them; a page's history is the shelf filtered to its tag.+const row = (id: string, page: "s" | "m", pinned = false) => ({ id, created_at: 0, pinned, page });+const onPage =+ (page: "s" | "m") =>+ <T extends { page: string }>(i: T) =>+ i.page === page;+const placed = <T extends FlaggableItem & { page: string }>(+ shelf: T[],+ page: "s" | "m",+ id: string,+ viewAfterId: string | null,+) => {+ const afterId = scopedMoveAfterId(shelf, onPage(page), id, viewAfterId);+ const next = moveGalleryItem(shelf, id, afterId);+ return {+ view: next.filter(onPage(page)).map((i) => `${i.id}${i.pinned ? "*" : ""}`),+ afterId,+ };+};++test("a move in one page's view does not take its pin from another page's hidden rows", () => {+ // Music's pin leads the shared shelf; dragging a Speak clip to the top of Speak's unpinned+ // history used to drop it next to that pin and pin it.+ const shelf = [row("m1", "m", true), row("s1", "s"), row("s2", "s"), row("m2", "m")];+ assert.deepEqual(placed(shelf, "s", "s2", null).view, ["s2", "s1"]);+ assert.equal(placed(shelf, "s", "s2", null).afterId, "m1");+ // The unscoped id would have pinned it.+ assert.equal(moveGalleryItem(shelf, "s2", null).find((i) => i.id === "s2")?.pinned, true);+});++test("dropping below a page's last pin keeps the clip unpinned past hidden pins", () => {+ const shelf = [row("s1", "s", true), row("m1", "m", true), row("s2", "s"), row("s3", "s")];+ // After s1 in Speak's view: between a pin and an unpinned row, the moved clip keeps its own state.+ assert.deepEqual(placed(shelf, "s", "s3", "s1").view, ["s1*", "s3", "s2"]);+});++test("a move the page's own view would pin still pins", () => {+ // Pins sort first on a shelf, so a hidden pin can sit between two of this page's pins.+ const shelf = [row("s1", "s", true), row("m1", "m", true), row("s2", "s", true), row("s3", "s")];+ assert.deepEqual(placed(shelf, "s", "s3", "s1").view, ["s1*", "s3*", "s2*"]);+});++test("a scoped move with no hidden rows sends the view's own neighbour", () => {+ const shelf = [row("s1", "s", true), row("s2", "s"), row("s3", "s")];+ assert.equal(scopedMoveAfterId(shelf, onPage("s"), "s3", null), null);+ assert.equal(scopedMoveAfterId(shelf, onPage("s"), "s3", "s1"), "s1");+});diff --git a/studio/frontend/tests/helpers/audio-workspace.ts b/studio/frontend/tests/helpers/audio-workspace.tsnew file mode 100644index 00000000000..b1c47052cff--- /dev/null+++ b/studio/frontend/tests/helpers/audio-workspace.ts@@ -0,0 +1,32 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { readSrc } from "./kit.ts";++/** Host first, then hooks in call order, so a spanning pattern reads in source order. */+export const AUDIO_WORKSPACE_FILES = [+ "features/audio/audio-page.tsx",+ "features/audio/hooks/use-stt-sidecar.ts",+ "features/audio/hooks/use-transcription.ts",+ "features/audio/hooks/use-audio-gallery.tsx",+ "features/audio/hooks/use-audio-model-slot.ts",+ "features/audio/hooks/use-speech-generation.ts",+ "features/audio/hooks/use-audio-handoff.ts",+ "features/audio/pages/tts-workspace.tsx",+ "features/audio/pages/speak-page.tsx",+ "features/audio/pages/music-page.tsx",+ "features/audio/pages/transcribe-page.tsx",+ "features/audio/components/instructions-fields.tsx",+ "features/audio/audio-workspace-constants.ts",+ "features/audio/audio-workspace-utils.ts",+ "features/audio/components/field.tsx",+ "features/audio/components/workflow-title-menu.tsx",+ "features/audio/components/clip-card.tsx",+ "features/audio/components/waveform.tsx",+] as const;++export type AudioWorkspaceFile = (typeof AUDIO_WORKSPACE_FILES)[number];++export function readAudioWorkspaceSource(): string {+ return AUDIO_WORKSPACE_FILES.map((file) => readSrc(file)).join("\n");+}diff --git a/studio/frontend/tests/media-plan-failure-fallback.test.ts b/studio/frontend/tests/media-plan-failure-fallback.test.tsindex 2439a42b4a5..d3028a58336 100644--- a/studio/frontend/tests/media-plan-failure-fallback.test.ts+++ b/studio/frontend/tests/media-plan-failure-fallback.test.ts@@ -7,6 +7,7 @@ import assert from "node:assert/strict";import test from "node:test";import { readSrc } from "./helpers/kit.ts";+import { readAudioWorkspaceSource } from "./helpers/audio-workspace.ts";test("images: only a download-only pick refuses a plan_failed plan", () => {const source = readSrc("features/images/images-page.tsx");@@ -21,7 +22,7 @@ test("video: a failed plan falls back to the load", () => {});test("audio: a downloaded TTS model still loads when its plan errors", () => {- const source = readSrc("features/audio/audio-page.tsx");+ const source = readAudioWorkspaceSource();const start = source.indexOf("plan = await getAudioDownloadPlan(");const fallback = source.slice(start, source.indexOf("const plannedEntries = plan.entries;", start));assert.match(fallback, /if \(meta\.isDownloaded === true\) \{\s*void loadTtsModelRef\.current\(/);diff --git a/studio/frontend/tests/model-picker-partial-downloads.test.ts b/studio/frontend/tests/model-picker-partial-downloads.test.tsindex 6af7abb702b..0ce9d932309 100644--- a/studio/frontend/tests/model-picker-partial-downloads.test.ts+++ b/studio/frontend/tests/model-picker-partial-downloads.test.ts@@ -427,7 +427,7 @@ test("the partial repo delete says it removes the repo, because it does", () =>});test("a partial pick carries no load identity", () => {- // The Chat-to-Audio route has no isDownloaded field: audio-page.tsx infers it from the+ // The Chat-to-Audio route has no isDownloaded field: the Audio handoff infers it from the// forwarded loadId. A loadId names a revision already on disk, so sending one for a torn// snapshot told that page the weights were there and skipped the download.assert.equal(@@ -446,7 +446,7 @@ test("a partial pick carries no load identity", () => {"the variant select still drops it the same way",);// What made the omission load bearing, in the page that reads it.- const audio = read("../src/features/audio/audio-page.tsx");+ const audio = read("../src/features/audio/hooks/use-audio-handoff.ts");assert.match(audio,/isDownloaded: routeSearch\.loadId\n?\s*\? true/,diff --git a/studio/frontend/tests/offload-warning-load-paths.test.ts b/studio/frontend/tests/offload-warning-load-paths.test.tsindex 477ff7ff915..6616dfa613c 100644--- a/studio/frontend/tests/offload-warning-load-paths.test.ts+++ b/studio/frontend/tests/offload-warning-load-paths.test.ts@@ -12,7 +12,7 @@ const LOAD_PATHS = ["../src/features/chat/api/chat-adapter.ts","../src/features/chat/shared-composer.tsx","../src/features/recipe-studio/hooks/use-recipe-executions.ts",- "../src/features/audio/audio-page.tsx",+ "../src/features/audio/hooks/use-audio-model-slot.ts",];test("every user-facing load path consults the offload warning", () => {diff --git a/studio/frontend/tests/pcm-recorder.test.ts b/studio/frontend/tests/pcm-recorder.test.tsindex c46581908be..dc227d3a56a 100644--- a/studio/frontend/tests/pcm-recorder.test.ts+++ b/studio/frontend/tests/pcm-recorder.test.ts@@ -353,7 +353,7 @@ test("secondsWithin keeps a WAV inside the upload cap", () => {test("the recording call sites go through createAudioRecorder", () => {for (const path of ["../src/features/chat/adapters/studio-model-dictation-adapter.ts",- "../src/features/audio/audio-page.tsx",+ "../src/features/audio/hooks/use-transcription.ts",]) {const source = readFileSync(new URL(path, import.meta.url), "utf8");assert.equal(diff --git a/studio/frontend/tests/read-aloud-tts-model-row.test.ts b/studio/frontend/tests/read-aloud-tts-model-row.test.tsindex 431ac67d285..9cb46f3d822 100644--- a/studio/frontend/tests/read-aloud-tts-model-row.test.ts+++ b/studio/frontend/tests/read-aloud-tts-model-row.test.ts@@ -5,10 +5,11 @@ import assert from "node:assert/strict";import test from "node:test";import { readSrc } from "./helpers/kit.ts";+import { readAudioWorkspaceSource } from "./helpers/audio-workspace.ts";const source = readSrc("features/settings/tabs/voice-tab.tsx");const en = readSrc("i18n/locales/en.ts");-const audioSource = readSrc("features/audio/audio-page.tsx");+const audioSource = readAudioWorkspaceSource();test("the studio TTS row offers the Audio page it tells the user to use", () => {// Settings is a modal, so it must close or Audio opens behind it.@@ -26,15 +27,16 @@ test("the row lands on the TTS selector, not the mode Audio was left in", () =>source,/to: "\/audio",\s*search: \{ task: "text-to-speech" \},/,);- // Audio ignored a task without a model, so the intent needs handling at the other end.+ // Audio ignored a task without a model, so the intent needs handling at the other end:+ // the task names the page, through the same busy gate as ?workflow=.assert.match(audioSource,- /const task = routeSearch\.task;\s*if \(!task\) return;\s*const intended =\s*task === "automatic-speech-recognition" \? "transcribe" : "speak";/,+ /const routedWorkflow = audioRouteIntent\(routeSearch\);\s*if \(routedWorkflow === null\) return;/,);// A refused switch keeps the parameter, so the retry rides the effect's busy dep.assert.match(audioSource,- /if \(intended !== mode && !transitionMode\(intended\)\) return;\s*void navigateSelf\(\{ to: "\/audio", search: \{\}, replace: true \}\);/,+ /if \(!transitionWorkflow\(routedWorkflow\)\) return;\s*void navigateSelf\(\{ to: "\/audio", search: \{\}, replace: true \}\);/,);});diff --git a/studio/frontend/tests/reload-snapshot.test.ts b/studio/frontend/tests/reload-snapshot.test.tsindex 117688ae680..10ea31db0c7 100644--- a/studio/frontend/tests/reload-snapshot.test.ts+++ b/studio/frontend/tests/reload-snapshot.test.ts@@ -6,6 +6,7 @@ import test from "node:test";import vm from "node:vm";import { readSrc, readText } from "./helpers/kit.ts";+import { readAudioWorkspaceSource } from "./helpers/audio-workspace.ts";const script = readText("../public/reload-snapshot.js");const indexHtml = readText("../index.html");@@ -20,7 +21,7 @@ const attachmentPreviewSource = readSrc("components/assistant-ui/attachment-prevconst attachmentSource = readSrc("components/assistant-ui/attachment.tsx");const imagesPageSource = readSrc("features/images/images-page.tsx");const videoPageSource = readSrc("features/video/video-page.tsx");-const audioPageSource = readSrc("features/audio/audio-page.tsx");+const audioPageSource = readAudioWorkspaceSource();const hubPageSource = readSrc("features/hub/hub-page.tsx");const referencePickerSource = readSrc("features/video/reference-picker.tsx");