Skip to content

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

studio: preserve transcripts and recall audio and image models (#10993)

Maheswar Kumarf621d12a21ec
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 630ec0d0f4c..ef1a3f6bcdc 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -6644,6 +6644,7 @@ class DiffusionBackend:
"device": state.device,
"dtype": state.dtype,
"model_kind": state.kind,
+ "gguf_filename": state.gguf_filename,
"gguf_variant": (
extract_quant_token(state.gguf_filename)
if state.kind == "gguf" and state.gguf_filename
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index 22806e745bc..36d0be89773 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -2689,6 +2689,8 @@ class SdCppDiffusionBackend:
"base_repo": state.base_repo,
"device": state.device,
"dtype": "gguf",
+ "model_kind": "gguf",
+ "gguf_filename": state.gguf_filename,
"gguf_variant": extract_quant_token(state.gguf_filename)
if state.gguf_filename
else None,
diff --git a/studio/backend/core/inference/stt_mtmd_sidecar.py b/studio/backend/core/inference/stt_mtmd_sidecar.py
index 7b98c4645ec..63416d5007c 100644
--- a/studio/backend/core/inference/stt_mtmd_sidecar.py
+++ b/studio/backend/core/inference/stt_mtmd_sidecar.py
@@ -1022,6 +1022,7 @@ class MtmdSttSidecar:
language: Optional[str] = None,
fast: bool = False,
cancel_event: Optional[threading.Event] = None,
+ on_progress = None,
) -> dict:
"""Transcribe encoded audio bytes, as the other sidecars do.
@@ -1062,7 +1063,12 @@ class MtmdSttSidecar:
# outside the lock: a held lock would block unload, including a training run's, for the whole request
# timeout
text = self._post_transcribe(
- port, model_id, wav_bytes, audio_seconds, cancel_event = cancel_event
+ port,
+ model_id,
+ wav_bytes,
+ audio_seconds,
+ cancel_event = cancel_event,
+ **({"on_progress": on_progress} if on_progress is not None else {}),
)
if cancel_event is not None and cancel_event.is_set():
raise SttTranscriptionCancelledError("Transcription cancelled.")
@@ -1094,6 +1100,7 @@ class MtmdSttSidecar:
audio_seconds: Optional[float] = None,
*,
cancel_event: Optional[threading.Event] = None,
+ on_progress = None,
) -> str:
spec = MTMD_STT_MODELS[model_id]
payload = {
@@ -1116,6 +1123,8 @@ class MtmdSttSidecar:
"temperature": 0,
"max_tokens": _transcript_token_budget(audio_seconds),
}
+ if on_progress is not None:
+ payload["stream"] = True
connection = http.client.HTTPConnection(
"127.0.0.1", port, timeout = _TRANSCRIBE_TIMEOUT_SECONDS
)
@@ -1136,6 +1145,36 @@ class MtmdSttSidecar:
headers = {"Content-Type": "application/json"},
)
with connection.getresponse() as response:
+ if on_progress is not None and 200 <= response.status < 300:
+ text = ""
+ finished = False
+ for line in response:
+ if cancel_event is not None and cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
+ if not line.startswith(b"data:"):
+ continue
+ data = line[5:].strip()
+ if data == b"[DONE]":
+ finished = True
+ break
+ event = json.loads(data)
+ if event.get("error"):
+ raise RuntimeError(
+ "The transcription server could not complete this recording."
+ )
+ choices = event.get("choices") or []
+ if choices:
+ finished = finished or choices[0].get("finish_reason") is not None
+ text += choices[0].get("delta", {}).get("content") or ""
+ if not spec.transcript_marker or spec.transcript_marker in text:
+ on_progress(
+ {"text": _clean_transcript(text, spec.transcript_marker)}
+ )
+ if not finished:
+ raise RuntimeError(
+ "The transcription server disconnected before finishing."
+ )
+ return _clean_transcript(text, spec.transcript_marker)
response_body = response.read()
if not 200 <= response.status < 300:
raise RuntimeError(
diff --git a/studio/backend/core/inference/stt_sidecar.py b/studio/backend/core/inference/stt_sidecar.py
index e3acfbfa17f..ad6433986af 100644
--- a/studio/backend/core/inference/stt_sidecar.py
+++ b/studio/backend/core/inference/stt_sidecar.py
@@ -1609,6 +1609,7 @@ class WhisperSttSidecar:
decoded_audio,
generate_kwargs: dict,
cancel_event: Optional[threading.Event] = None,
+ on_progress = None,
) -> str:
"""Run Whisper on already-decoded 16 kHz mono PCM and return text.
@@ -1642,6 +1643,15 @@ class WhisperSttSidecar:
continue
pcm = np.ascontiguousarray(segment, dtype = np.float32).tobytes()
parts.append(engine.transcribe_window(pcm, effective_generate_kwargs, cancel_event))
+ if on_progress is not None:
+ on_progress(
+ {
+ "text": " ".join(part.strip() for part in parts if part.strip()),
+ "processed_seconds": min(start + window, len(decoded_audio))
+ / _TARGET_SAMPLE_RATE,
+ "duration": len(decoded_audio) / _TARGET_SAMPLE_RATE,
+ }
+ )
if cancel_event is not None and cancel_event.is_set():
raise SttTranscriptionCancelledError("Transcription cancelled.")
return " ".join(part.strip() for part in parts if part.strip()).strip()
@@ -1653,6 +1663,7 @@ class WhisperSttSidecar:
language: Optional[str] = None,
fast: bool = False,
cancel_event: Optional[threading.Event] = None,
+ on_progress = None,
) -> dict:
"""Transcribe encoded audio bytes to text.
@@ -1693,7 +1704,11 @@ class WhisperSttSidecar:
generate_kwargs["num_beams"] = 1
with self._lock:
try:
- if cancel_event is None:
+ if on_progress is not None:
+ text = self._transcribe_decoded(
+ model_id, decoded_audio, generate_kwargs, cancel_event, on_progress
+ )
+ elif cancel_event is None:
text = self._transcribe_decoded(model_id, decoded_audio, generate_kwargs)
else:
text = self._transcribe_decoded(
diff --git a/studio/backend/core/inference/transcript_gallery.py b/studio/backend/core/inference/transcript_gallery.py
new file mode 100644
index 00000000000..45ba16ee792
--- /dev/null
+++ b/studio/backend/core/inference/transcript_gallery.py
@@ -0,0 +1,139 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Account-scoped transcript history, stored independently of model residency."""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import uuid
+from datetime import datetime, timezone
+from pathlib import Path
+
+from core.inference import gallery_flags
+from utils.account_context import is_owner_context
+from utils.paths import ensure_account_dir, ensure_dir, studio_root
+from utils.paths.storage_roots import account_path
+
+_ID_RE = re.compile(r"^[a-f0-9]{32}$")
+
+
+def gallery_dir() -> Path:
+ if is_owner_context():
+ return ensure_dir(studio_root() / "transcripts")
+ return ensure_account_dir(account_path("transcripts"))
+
+
+def save(result: dict, title: str) -> dict:
+ transcript_id = uuid.uuid4().hex
+ record = {
+ "id": transcript_id,
+ "title": title.replace("\\", "/").rsplit("/", 1)[-1][:255] or "Recording",
+ "text": result["text"],
+ "model": result["model"],
+ "duration": result.get("duration"),
+ "language": result.get("language"),
+ "created_at": datetime.now(timezone.utc).isoformat(),
+ "archived": False,
+ }
+ directory = gallery_dir()
+ staged = directory / f".{transcript_id}.tmp"
+ try:
+ staged.write_text(json.dumps(record, ensure_ascii = False), encoding = "utf-8")
+ os.replace(staged, directory / f"{transcript_id}.json")
+ finally:
+ staged.unlink(missing_ok = True)
+ return record
+
+
+def _read(directory: Path, transcript_id: str) -> dict | None:
+ if not _ID_RE.fullmatch(transcript_id):
+ return None
+ path = directory / f"{transcript_id}.json"
+ if path.is_symlink():
+ return None
+ try:
+ record = json.loads(path.read_text(encoding = "utf-8"))
+ if not isinstance(record, dict) or record.get("id") != transcript_id:
+ return None
+ if not all(
+ isinstance(record.get(key), str) for key in ("text", "model", "title", "created_at")
+ ):
+ return None
+ return record
+ except (OSError, ValueError):
+ return None
+
+
+def get(transcript_id: str) -> dict | None:
+ directory = gallery_dir()
+ record = _read(directory, transcript_id)
+ if record is not None:
+ record["archived"] = gallery_flags.is_archived(gallery_flags.read(directory), transcript_id)
+ return record
+
+
+def list_transcripts(
+ limit: int = 50,
+ before: str | None = None,
+ archived: bool = False,
+) -> dict:
+ directory = gallery_dir()
+ flags = gallery_flags.read(directory)
+ records = []
+ for path in directory.glob("*.json"):
+ record = _read(directory, path.stem)
+ if record is None or gallery_flags.is_archived(flags, path.stem) != archived:
+ continue
+ cursor = f"{record['created_at']}|{record['id']}"
+ if before is not None and cursor >= before:
+ continue
+ record["archived"] = archived
+ records.append(record)
+ records.sort(key = lambda record: (record["created_at"], record["id"]), reverse = True)
+ visible = records[:limit]
+ return {
+ "transcripts": visible,
+ "next_cursor": (
+ f"{visible[-1]['created_at']}|{visible[-1]['id']}" if len(records) > limit else None
+ ),
+ }
+
+
+def set_archived(transcript_id: str, archived: bool) -> dict | None:
+ # No require_file_lock, as audio_gallery.set_flags: only clear(), which DELETES on a
+ # flag, has to fail closed when the lock is unavailable.
+ directory = gallery_dir()
+ with gallery_flags.exclusive(directory):
+ record = _read(directory, transcript_id)
+ if record is None:
+ return None
+ gallery_flags.set_flags_locked(directory, transcript_id, archived = archived)
+ record["archived"] = archived
+ return record
+
+
+def delete(transcript_id: str) -> bool:
+ directory = gallery_dir()
+ with gallery_flags.exclusive(directory):
+ if _read(directory, transcript_id) is None:
+ return False
+ (directory / f"{transcript_id}.json").unlink()
+ gallery_flags.forget_locked(directory, [transcript_id])
+ return True
+
+
+def clear() -> int:
+ directory = gallery_dir()
+ with gallery_flags.exclusive(directory, require_file_lock = True):
+ flags = gallery_flags.read_trusted(directory)
+ removed = []
+ for path in directory.glob("*.json"):
+ if gallery_flags.is_archived(flags, path.stem) or _read(directory, path.stem) is None:
+ continue
+ path.unlink()
+ removed.append(path.stem)
+ gallery_flags.forget_locked(directory, removed)
+ return len(removed)
diff --git a/studio/backend/core/inference/transcript_stream.py b/studio/backend/core/inference/transcript_stream.py
new file mode 100644
index 00000000000..15928dab231
--- /dev/null
+++ b/studio/backend/core/inference/transcript_stream.py
@@ -0,0 +1,77 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Progress and durable results for the Studio transcription screen."""
+
+import asyncio
+import contextlib
+import json
+import time
+
+from fastapi import HTTPException
+
+from core.inference import transcript_gallery
+from loggers import get_logger
+
+logger = get_logger(__name__)
+
+
+async def stream_transcript(transcribe, title: str):
+ loop = asyncio.get_running_loop()
+ updates = asyncio.Queue(maxsize = 1)
+ closed = False
+ last_update = 0.0
+
+ def publish(update):
+ if closed:
+ return
+ if updates.full():
+ updates.get_nowait()
+ updates.put_nowait({"type": "progress", **update})
+
+ def on_progress(update):
+ nonlocal last_update
+ if closed:
+ return
+ now = time.monotonic()
+ if now - last_update >= 0.25:
+ last_update = now
+ loop.call_soon_threadsafe(publish, update)
+
+ async def run():
+ result = await transcribe(on_progress)
+ record = None
+ if result.get("text", "").strip():
+ try:
+ record = await asyncio.to_thread(transcript_gallery.save, result, title)
+ except Exception as exc:
+ logger.warning("Could not save transcript to the gallery (%s)", type(exc).__name__)
+ return {"type": "complete", **result, "record": record}
+
+ task = asyncio.create_task(run())
+ pending = asyncio.create_task(updates.get())
+ try:
+ yield json.dumps({"type": "progress", "text": ""}) + "\n"
+ while not task.done():
+ done, _ = await asyncio.wait(
+ {task, pending}, timeout = 5, return_when = asyncio.FIRST_COMPLETED
+ )
+ if pending in done:
+ yield json.dumps(pending.result()) + "\n"
+ pending = asyncio.create_task(updates.get())
+ elif not done:
+ yield json.dumps({"type": "heartbeat"}) + "\n"
+ yield json.dumps(task.result()) + "\n"
+ except HTTPException as exc:
+ yield json.dumps({"type": "error", "message": exc.detail}) + "\n"
+ except Exception as exc:
+ logger.warning("Transcription stream failed (%s)", type(exc).__name__)
+ yield json.dumps({"type": "error", "message": "Transcription failed. Try again."}) + "\n"
+ finally:
+ closed = True
+ pending.cancel()
+ task.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await pending
+ with contextlib.suppress(asyncio.CancelledError, Exception):
+ await task
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index cc5d05ab2d5..b77bcbe6c43 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -4245,6 +4245,9 @@ class DiffusionStatusResponse(BaseModel):
model_kind: Optional[str] = Field(
None, description = "Resolved load kind: gguf | single_file | pipeline (gates GGUF-only UI)"
)
+ gguf_filename: Optional[str] = Field(
+ None, description = "Loaded single-file checkpoint filename, or null for a pipeline"
+ )
gguf_variant: Optional[str] = Field(
None, description = "Selected GGUF quantisation variant (for example Q8_0)"
)
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index a0745ddf8ba..ee169f95947 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -19860,6 +19860,7 @@ async def _transcribe_audio_result(
engine: Optional[str] = None,
request: Optional[Request] = None,
device: Optional[str] = None,
+ on_progress = None,
) -> dict:
"""STT for already-decoded bytes, sidecar errors mapped to HTTP statuses.
Returns the sidecar's result dict so callers own the response shape."""
@@ -19893,7 +19894,7 @@ async def _transcribe_audio_result(
model,
)
sidecar = _stt_sidecar_for(serving_engine)
- cancel_event = threading.Event() if request is not None else None
+ cancel_event = threading.Event() if request is not None or on_progress is not None else None
disconnect_watcher = (
asyncio.create_task(_await_stt_disconnect_then_cancel(request, sidecar, cancel_event))
if request is not None and cancel_event is not None
@@ -19913,7 +19914,17 @@ async def _transcribe_audio_result(
loaded = getattr(sidecar, "loaded_model", None)
if loaded is not None and loaded == _stt_resolved_model_id(model, serving_engine):
account_access.note_resident_account(f"stt:{serving_engine}", loaded)
- if cancel_event is None:
+ if on_progress is not None and serving_engine in ("transformers", "mtmd"):
+ result = await asyncio.to_thread(
+ sidecar.transcribe,
+ raw,
+ model,
+ language,
+ fast,
+ cancel_event,
+ on_progress = on_progress,
+ )
+ elif cancel_event is None:
result = await asyncio.to_thread(sidecar.transcribe, raw, model, language, fast)
else:
result = await asyncio.to_thread(
@@ -20008,6 +20019,8 @@ async def transcribe_audio_raw(
# would silently put the model back on the GPU. 422 instead.
device: Optional[Literal["auto", "cpu", "gpu"]] = None,
current_subject: str = Depends(get_current_subject),
+ stream: bool = False,
+ title: str = Query("Recording", max_length = 255),
):
"""Transcribe a raw audio body without base64 or JSON conversion overhead."""
chunks: list[bytes] = []
@@ -20017,6 +20030,19 @@ async def transcribe_audio_raw(
if size > _MAX_AUDIO_RAW_BYTES:
raise HTTPException(status_code = 413, detail = "Audio is too large.")
chunks.append(chunk)
+ if stream:
+ from core.inference.transcript_stream import stream_transcript
+ raw = b"".join(chunks)
+ return StreamingResponse(
+ stream_transcript(
+ lambda on_progress: _transcribe_audio_result(
+ raw, model, language, fast, engine, None, device, on_progress
+ ),
+ title,
+ ),
+ media_type = "application/x-ndjson",
+ headers = {"Cache-Control": "no-store", "X-Accel-Buffering": "no"},
+ )
return JSONResponse(
content = await _transcribe_audio_result(
b"".join(chunks), model, language, fast, engine, request, device
@@ -37905,6 +37931,60 @@ async def clear_gallery_audio(current_subject: str = Depends(get_current_subject
return {"removed": removed}
+@studio_router.get("/audio/transcripts")
+async def list_gallery_transcripts(
+ limit: int = Query(50, ge = 1, le = 200),
+ before: Optional[str] = Query(None, max_length = 100),
+ archived: bool = False,
+ current_subject: str = Depends(get_current_subject),
+):
+ from core.inference import transcript_gallery
+ return await asyncio.to_thread(transcript_gallery.list_transcripts, limit, before, archived)
+
+
+@studio_router.patch("/audio/transcripts/{transcript_id}")
+async def archive_gallery_transcript(
+ transcript_id: str,
+ patch: AudioGalleryFlagsPatch,
+ current_subject: str = Depends(get_current_subject),
+):
+ from core.inference import transcript_gallery
+
+ if patch.archived is None:
+ raise HTTPException(status_code = 422, detail = "Specify whether to archive this transcript.")
+ record = await asyncio.to_thread(transcript_gallery.set_archived, transcript_id, patch.archived)
+ if record is None:
+ raise HTTPException(status_code = 404, detail = "Transcript not found.")
+ return record
+
+
+@studio_router.delete("/audio/transcripts/{transcript_id}")
+async def delete_gallery_transcript(
+ transcript_id: str, current_subject: str = Depends(get_current_subject)
+):
+ from core.inference import transcript_gallery
+ if not await asyncio.to_thread(transcript_gallery.delete, transcript_id):
+ raise HTTPException(status_code = 404, detail = "Transcript not found.")
+ return {"deleted": True}
+
+
+@studio_router.delete("/audio/transcripts")
+async def clear_gallery_transcripts(current_subject: str = Depends(get_current_subject)):
+ from core.inference import transcript_gallery
+ from core.inference.gallery_flags import FlagsUnavailable
+
+ try:
+ removed = await asyncio.to_thread(transcript_gallery.clear)
+ except FlagsUnavailable as exc:
+ logger.warning("transcript_gallery.clear_blocked: %s", exc)
+ raise HTTPException(
+ status_code = 503,
+ detail = "Could not read the transcript archive data, so clearing was stopped "
+ "to avoid deleting archived transcripts.",
+ )
+ return {"removed": removed}
+
+
@studio_router.post("/images/unload", response_model = DiffusionStatusResponse)
@account_access.gpu_busy_route
async def unload_diffusion_model(current_subject: str = Depends(get_current_subject)):
diff --git a/studio/backend/tests/multi_account/factories_media.py b/studio/backend/tests/multi_account/factories_media.py
index 28416da54e7..aa9143f9c23 100644
--- a/studio/backend/tests/multi_account/factories_media.py
+++ b/studio/backend/tests/multi_account/factories_media.py
@@ -75,6 +75,20 @@ def seed_audio(account) -> dict[str, str]:
return {"audio_id": record["id"]}
+@seeder("media-transcript")
+def seed_transcript(account) -> dict[str, str]:
+ from core.inference import transcript_gallery
+ from utils.account_context import run_as
+
+ record = run_as(
+ account,
+ transcript_gallery.save,
+ {"text": SENTINEL, "model": "media/none"},
+ "Recording",
+ )
+ return {"transcript_id": record["id"]}
+
+
def _mp4_bytes() -> bytes:
import io
@@ -219,6 +233,10 @@ FACTORIES = {
"media-audio", {"archived": True}, fragment = SENTINEL
),
"routes.inference:DELETE:/audio/gallery/{audio_id}": Factory("media-audio"),
+ "routes.inference:PATCH:/audio/transcripts/{transcript_id}": Factory(
+ "media-transcript", {"archived": True}, fragment = SENTINEL
+ ),
+ "routes.inference:DELETE:/audio/transcripts/{transcript_id}": Factory("media-transcript"),
"routes.video:GET:/video/gallery/{video_id}/file": Factory("media-video"),
"routes.video:GET:/video/gallery/{video_id}/file-signed": Factory(
"media-video",
diff --git a/studio/backend/tests/test_transcript_gallery.py b/studio/backend/tests/test_transcript_gallery.py
new file mode 100644
index 00000000000..2d9e9114546
--- /dev/null
+++ b/studio/backend/tests/test_transcript_gallery.py
@@ -0,0 +1,123 @@
+# 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 json
+
+import pytest
+
+from core.inference import gallery_flags, transcript_gallery as gallery
+
+
[email protected](autouse = True)
+def isolated_gallery(monkeypatch, tmp_path):
+ monkeypatch.setattr(gallery, "studio_root", lambda: tmp_path)
+
+
+def save(title = "speech.wav"):
+ return gallery.save({"text": "Hello 世界", "model": "tiny", "duration": 3.5}, title)
+
+
+def test_round_trip_preserves_text_and_origin():
+ record = save("some/folder/speech.wav")
+ assert record["title"] == "speech.wav"
+ assert gallery.get(record["id"]) == record
+ assert gallery.list_transcripts()["transcripts"] == [record]
+
+
+def test_cursor_survives_new_records_and_deletion():
+ first, second = save(), save()
+ page = gallery.list_transcripts(limit = 1)
+ assert page["transcripts"] == [second]
+ gallery.delete(second["id"])
+ save()
+ assert gallery.list_transcripts(before = page["next_cursor"])["transcripts"] == [first]
+
+
+def test_clear_keeps_archived_transcripts():
+ keep, remove = save(), save()
+ gallery.set_archived(keep["id"], True)
+ assert gallery.clear() == 1
+ assert gallery.get(remove["id"]) is None
+ assert gallery.list_transcripts(archived = True)["transcripts"][0]["id"] == keep["id"]
+ gallery.set_archived(keep["id"], False)
+ assert gallery.list_transcripts()["transcripts"][0]["id"] == keep["id"]
+
+
+def test_clear_does_not_guess_when_archive_flags_are_corrupt():
+ record = save()
+ gallery.set_archived(record["id"], True)
+ flags_path = gallery_flags._store_path(gallery.gallery_dir())
+ flags_path.write_text("broken")
+ with pytest.raises(gallery_flags.FlagsUnavailable):
+ gallery.clear()
+ assert (gallery.gallery_dir() / f"{record['id']}.json").exists()
+
+
+ "contents",
+ ["broken", json.dumps({"version": 1, "items": {}, "unreadable": True})],
+)
+def test_listing_recovers_when_archive_flags_are_unavailable(contents):
+ record = save()
+ gallery_flags._store_path(gallery.gallery_dir()).write_text(contents)
+ assert gallery.list_transcripts()["transcripts"] == [record]
+ with pytest.raises(gallery_flags.FlagsUnavailable):
+ gallery.clear()
+ assert gallery.get(record["id"])["text"] == record["text"]
+
+
+def test_foreign_files_and_unsafe_ids_are_untouched(tmp_path):
+ directory = gallery.gallery_dir()
+ foreign = directory / ("a" * 32 + ".json")
+ foreign.write_text(json.dumps({"text": "foreign"}))
+ outside = tmp_path / "private.json"
+ outside.write_text("secret")
+ assert gallery.get("../private") is None
+ assert not gallery.delete("../private")
+ assert gallery.clear() == 0
+ assert foreign.exists() and outside.exists()
+
+
+def test_atomic_save_failure_does_not_leave_history_entry(monkeypatch):
+ def fail(*args):
+ raise OSError("disk full")
+
+ monkeypatch.setattr(gallery.os, "replace", fail)
+ with pytest.raises(OSError):
+ save()
+ assert gallery.list_transcripts()["transcripts"] == []
+ assert not list(gallery.gallery_dir().glob("*.tmp"))
+
+
+def test_account_roots_are_separate(monkeypatch, tmp_path):
+ owner = save()
+ monkeypatch.setattr(gallery, "is_owner_context", lambda: False)
+ monkeypatch.setattr(gallery, "account_path", lambda name: tmp_path / "account" / name)
+ monkeypatch.setattr(gallery, "ensure_account_dir", gallery.ensure_dir)
+ assert gallery.get(owner["id"]) is None
+ account = save()
+ monkeypatch.setattr(gallery, "is_owner_context", lambda: True)
+ assert gallery.get(account["id"]) is None
+
+
+def test_archive_and_delete_survive_a_filesystem_without_flock(monkeypatch):
+ """A lock we cannot take must not cost the user archiving, only clearing.
+
+ ``clear`` deletes on the strength of a flag, so it fails closed. Archiving and
+ deleting one named transcript do not, and audio_gallery.set_flags deliberately takes
+ the plain lock for exactly that reason. Taking require_file_lock here made both a 500
+ on any mount where flock is unavailable, while the same account's audio clips worked.
+ """
+ import contextlib
+
+ @contextlib.contextmanager
+ def unlockable(directory):
+ yield False
+
+ record = save()
+ monkeypatch.setattr(gallery_flags, "_file_lock", unlockable)
+
+ assert gallery.set_archived(record["id"], True)["archived"] is True
+ assert gallery.delete(record["id"]) is True
+ with pytest.raises(gallery_flags.FlagsUnavailable):
+ gallery.clear()
diff --git a/studio/backend/tests/test_transcript_stream.py b/studio/backend/tests/test_transcript_stream.py
new file mode 100644
index 00000000000..9675ccbdf97
--- /dev/null
+++ b/studio/backend/tests/test_transcript_stream.py
@@ -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 asyncio
+import json
+
+from core.inference import transcript_stream
+
+
+def test_progress_and_saved_result(monkeypatch):
+ async def scenario():
+ async def transcribe(progress):
+ progress({"text": "hello"})
+ await asyncio.sleep(0.01)
+ return {"text": "hello world", "model": "tiny", "duration": 2}
+
+ monkeypatch.setattr(
+ transcript_stream.transcript_gallery,
+ "save",
+ lambda result, title: {"id": "saved", **result},
+ )
+ events = [
+ json.loads(line)
+ async for line in transcript_stream.stream_transcript(transcribe, "clip")
+ ]
+ assert any(event.get("text") == "hello" for event in events)
+ assert events[-1]["record"]["id"] == "saved"
+ assert events[-1]["text"] == "hello world"
+
+ asyncio.run(scenario())
+
+
+def test_save_failure_returns_complete_text(monkeypatch):
+ async def transcribe(progress):
+ return {"text": "keep this", "model": "tiny"}
+
+ def fail(*args):
+ raise OSError("disk full")
+
+ monkeypatch.setattr(transcript_stream.transcript_gallery, "save", fail)
+
+ async def scenario():
+ events = [
+ json.loads(line)
+ async for line in transcript_stream.stream_transcript(transcribe, "clip")
+ ]
+ assert events[-1]["text"] == "keep this"
+ assert events[-1]["record"] is None
+
+ asyncio.run(scenario())
+
+
+def test_closing_stream_cancels_inference_without_saving(monkeypatch):
+ async def scenario():
+ started, cancelled = asyncio.Event(), asyncio.Event()
+
+ async def transcribe(progress):
+ started.set()
+ try:
+ await asyncio.Event().wait()
+ finally:
+ cancelled.set()
+
+ monkeypatch.setattr(
+ transcript_stream.transcript_gallery,
+ "save",
+ lambda *args: (_ for _ in ()).throw(AssertionError("saved cancelled request")),
+ )
+ stream = transcript_stream.stream_transcript(transcribe, "clip")
+ await anext(stream)
+ await started.wait()
+ await stream.aclose()
+ assert cancelled.is_set()
+
+ asyncio.run(scenario())
+
+
+def test_transformers_progress_uses_existing_audio_windows(monkeypatch):
+ import numpy as np
+ from core.inference.stt_sidecar import WhisperSttSidecar
+
+ class Worker:
+ generation_config = None
+ calls = 0
+
+ def transcribe_window(self, pcm, kwargs, cancel):
+ self.calls += 1
+ return f"part {self.calls}"
+
+ worker = Worker()
+ sidecar = WhisperSttSidecar()
+ monkeypatch.setattr(sidecar, "load", lambda model: worker)
+ updates = []
+ result = sidecar._transcribe_decoded(
+ "tiny", np.zeros(35 * 16000), {}, on_progress = updates.append
+ )
+ assert result == "part 1 part 2"
+ assert [event["processed_seconds"] for event in updates] == [30, 35]
+ assert updates[-1]["text"] == result
+
+
+def test_mtmd_stream_cleans_metadata_and_requires_completion(monkeypatch):
+ import io
+ import pytest
+ from core.inference import stt_mtmd_sidecar as mtmd
+
+ marker = mtmd.MTMD_STT_MODELS["qwen3-asr-0.6b"].transcript_marker
+ wire = [
+ {"choices": [{"delta": {"content": f"language English{marker}hello"}}]},
+ {"choices": [{"delta": {"content": " world"}}]},
+ ]
+ payloads = []
+
+ class Response(io.BytesIO):
+ status = 200
+
+ class Connection:
+ def __init__(self, *args, **kwargs):
+ pass
+
+ def request(self, *args, **kwargs):
+ payloads.append(json.loads(kwargs["body"]))
+
+ def getresponse(self):
+ return Response(
+ b"".join(b"data: " + json.dumps(event).encode() + b"\n\n" for event in wire)
+ )
+
+ def close(self):
+ pass
+
+ monkeypatch.setattr(mtmd.http.client, "HTTPConnection", Connection)
+ updates = []
+ sidecar = mtmd.MtmdSttSidecar()
+ with pytest.raises(RuntimeError, match = "before finishing"):
+ sidecar._post_transcribe(1234, "qwen3-asr-0.6b", b"wav", on_progress = updates.append)
+ assert updates[-1]["text"] == "hello world"
+ wire.append({"choices": [{"delta": {}, "finish_reason": "stop"}]})
+ assert (
+ sidecar._post_transcribe(1234, "qwen3-asr-0.6b", b"wav", on_progress = updates.append)
+ == "hello world"
+ )
+ assert payloads[-1]["stream"] is True
+
+
+def test_diffusion_status_retains_the_exact_checkpoint_filename():
+ from models.inference import DiffusionStatusResponse
+ status = DiffusionStatusResponse(
+ loaded = True, model_kind = "gguf", gguf_filename = "model-Q8_0.gguf"
+ ).model_dump()
+ assert status["gguf_filename"] == "model-Q8_0.gguf"
diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsx
index 233f4cb12a6..28cf3cc1f1e 100644
--- a/studio/frontend/src/components/app-sidebar.tsx
+++ b/studio/frontend/src/components/app-sidebar.tsx
@@ -201,7 +201,7 @@ import { useEffectiveProfile, UserAvatar } from "@/features/profile";
import { resolveNavRowState } from "@/components/nav-row-state";
import { fetchDeviceType, usePlatformStore } from "@/config/env";
import { videoNavHint } from "@/config/hardware-verdict";
-import { clearAuthTokens, logout } from "@/features/auth";
+import { AUTH_SESSION_ENDING_EVENT, clearAuthTokens, logout } from "@/features/auth";
import { TOUR_OPEN_EVENT } from "@/features/tour";
import {
deleteTrainingRun,
@@ -2829,6 +2829,7 @@ export function AppSidebar() {
// Desktop signs out through the OS account menu, not here.
if (isTauri) return;
void (async () => {
+ if (!window.dispatchEvent(new Event(AUTH_SESSION_ENDING_EVENT, { cancelable: true }))) return;
try {
await logout();
} catch {
@@ -4448,6 +4449,7 @@ export function AppSidebar() {
{!isTauri && (
<DropdownMenuItem
onSelect={async () => {
+ if (!window.dispatchEvent(new Event(AUTH_SESSION_ENDING_EVENT, { cancelable: true }))) return;
// Best-effort server revocation; ignore network errors so the local clear still runs.
try {
await logout();
diff --git a/studio/frontend/src/features/audio/api.ts b/studio/frontend/src/features/audio/api.ts
index 52f55fda264..fd0ba5f3dfe 100644
--- a/studio/frontend/src/features/audio/api.ts
+++ b/studio/frontend/src/features/audio/api.ts
@@ -149,3 +149,83 @@ export async function fetchClipObjectUrl(
const blob = await response.blob();
return { url: URL.createObjectURL(blob), bytes: blob.size };
}
+
+export async function transcribeWithProgress(
+ blob: Blob,
+ title: string,
+ options: {
+ model: string;
+ engine: string;
+ device: string;
+ signal: AbortSignal;
+ },
+ onProgress: (
+ progress: import("./transcript-stream").TranscriptProgress,
+ ) => void,
+): Promise<import("./transcript-stream").TranscriptResult> {
+ const { readTranscriptStream } = await import("./transcript-stream");
+ const params = new URLSearchParams({
+ model: options.model,
+ engine: options.engine,
+ device: options.device,
+ fast: "true",
+ stream: "true",
+ title: title.slice(0, 255),
+ });
+ const response = await authFetch(
+ `/api/inference/audio/transcribe/raw?${params}`,
+ {
+ method: "POST",
+ headers: { "Content-Type": blob.type || "application/octet-stream" },
+ body: blob,
+ signal: options.signal,
+ },
+ );
+ if (!response.ok) throw new Error(await readFastApiError(response));
+ if (!response.body) throw new Error("The transcription response was empty.");
+ return readTranscriptStream(response.body, onProgress);
+}
+
+export async function listTranscripts(
+ archived = false,
+ before?: string | null,
+): Promise<{
+ transcripts: import("./transcript-stream").TranscriptRecord[];
+ next_cursor: string | null;
+}> {
+ const params = new URLSearchParams({
+ archived: String(archived),
+ limit: "50",
+ });
+ if (before) params.set("before", before);
+ return parseJson(
+ await authFetch(`/api/inference/audio/transcripts?${params}`),
+ );
+}
+
+export async function archiveTranscript(
+ id: string,
+ archived: boolean,
+): Promise<void> {
+ await parseJson(
+ await authFetch(
+ `/api/inference/audio/transcripts/${encodeURIComponent(id)}`,
+ {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ archived }),
+ },
+ ),
+ );
+}
+
+export async function deleteTranscript(id?: string): Promise<void> {
+ await parseJson(
+ await authFetch(
+ `/api/inference/audio/transcripts${id ? `/${encodeURIComponent(id)}` : ""}`,
+ {
+ method: "DELETE",
+ },
+ ),
+ );
+}
diff --git a/studio/frontend/src/features/audio/audio-page.tsx b/studio/frontend/src/features/audio/audio-page.tsx
index 2d112316dc8..241345213e7 100644
--- a/studio/frontend/src/features/audio/audio-page.tsx
+++ b/studio/frontend/src/features/audio/audio-page.tsx
@@ -38,7 +38,6 @@ import {
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Progress } from "@/components/ui/progress";
-import { Spinner } from "@/components/ui/spinner";
import { Textarea } from "@/components/ui/textarea";
import { usePlatformStore } from "@/config/env";
import {
@@ -66,7 +65,6 @@ import {
loadSttModel,
startSttDownload,
sttEngineStatusFor,
- transcribeAudioBlob,
unloadSttModel,
} from "@/features/chat/adapters/studio-model-dictation-adapter";
import { useStagedDownload } from "@/features/hub/download-manager";
@@ -79,16 +77,27 @@ import type {
ModelSelectorChangeMeta,
} from "@/features/model-picker/components/model-selector/types";
import { confirmRemoteCodeIfNeeded } from "@/features/security";
-import { useSettingsDialogStore } from "@/features/settings";
+import { useSettingsDialogStore, useVoiceSettingsStore } from "@/features/settings";
import {
isTrackingSttDownload,
trackSttDownload,
} from "@/features/settings/lib/stt-download-mirror";
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 { subscribeGalleryChanged } from "@/lib/gallery-flags";
import { subscribeModelLifecycle } from "@/lib/model-lifecycle-events";
@@ -105,6 +114,7 @@ import {
getAudioDownloadPlan,
listAudioGallery,
setAudioClipFlags,
+ transcribeWithProgress,
} from "./api";
import {
type AudioBusy,
@@ -390,6 +400,7 @@ export function AudioPage({
requestStarted: boolean;
} | null>(null);
+ const [lastSttRepo, setLastSttRepo] = usePersistedChoice("unsloth:audio:last-stt-model", "");
const [selectedSttRepo, setSelectedSttRepo] = useState<string | null>(null);
const [sttLoadedModel, setSttLoadedModel] = useState<string | null>(null);
const [sttLoadedEngine, setSttLoadedEngine] = useState<
@@ -398,8 +409,18 @@ export function AudioPage({
const [downloadedSttArtifacts, setDownloadedSttArtifacts] = useState<
SttDownloadedArtifact[]
>([]);
- const [transcript, setTranscript] = useState("");
- const [transcribedName, setTranscribedName] = useState<string | null>(null);
+ 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);
@@ -537,11 +558,78 @@ 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 {
@@ -598,10 +686,6 @@ export function AudioPage({
repoIdForSidecarKey: sttRepoIdForSidecarKey,
engineForRepo: sttEngineForRepoId,
});
- // Shared sidecar: an adopted model strands the previous pick's transcript under it. null is the
- // 5-minute idle unload, which must not delete it.
- if (reconciled !== null && reconciled !== selectedSttRepoRef.current)
- clearTranscript();
selectedSttRepoRef.current = reconciled;
setSelectedSttRepo(reconciled);
} catch {
@@ -609,7 +693,7 @@ export function AudioPage({
setSttLoadedModel(null);
setSttLoadedEngine(null);
}
- }, [clearTranscript]);
+ }, []);
const sttSelected = selectedSttRepo !== null;
const sttReady = sttSelectionReady(
@@ -634,7 +718,6 @@ export function AudioPage({
selectedSttRepoRef.current = null;
sttLoadGeneration.current += 1;
sttLoadedByThisPage.current = null;
- clearTranscript();
setSelectedSttRepo(null);
};
if (!owned) {
@@ -647,7 +730,7 @@ export function AudioPage({
await unloadSttModel(sttEngineForRepoId(selected), claim);
forget();
await refreshSttStatus();
- }, [clearTranscript, refreshSttStatus, sttReady, sttLoadedModel]);
+ }, [refreshSttStatus, sttReady, sttLoadedModel]);
const ensureClipSrc = useCallback(async (clip: AudioGalleryClip) => {
const cached = galleryCache.srcById.get(clip.id);
@@ -1414,8 +1497,12 @@ export function AudioPage({
await loadSttModel(sidecarKey, engine, controller.signal);
sttLoadedByThisPage.current = sidecarKey;
}
- if (isCurrent())
+ if (isCurrent()) {
+ setLastSttRepo(repoId);
toast.success("Transcription model ready", { id: toastId });
+ return true;
+ }
+ return false;
} catch (error) {
if (isCurrent()) {
toast.error(
@@ -1426,6 +1513,7 @@ export function AudioPage({
);
}
} finally {
+ if (!isCurrent()) toast.dismiss(toastId);
if (sttLoadingGeneration.current === generation) {
sttLoadingGeneration.current = null;
await refreshSttStatus();
@@ -1441,7 +1529,7 @@ export function AudioPage({
if (sttLoadAbort.current === controller) sttLoadAbort.current = null;
}
},
- [refreshSttStatus],
+ [refreshSttStatus, setLastSttRepo],
);
// A hidden page may let the shared download continue, but it must not load the sidecar. Returning
@@ -1558,7 +1646,6 @@ export function AudioPage({
if (!transitionMode("transcribe")) return;
const sidecarKey = sttSidecarKeyFor(id);
const engine = sttEngineForRepoId(id);
- if (selectedSttRepoRef.current !== id) clearTranscript();
deferredSttLoad.current = null;
selectedSttRepoRef.current = id;
setSelectedSttRepo(id);
@@ -1659,7 +1746,6 @@ export function AudioPage({
await loadOrStageTtsModel(id, exactGguf, meta);
},
[
- clearTranscript,
ensureSttLoaded,
isMac,
loadOrStageTtsModel,
@@ -1974,41 +2060,87 @@ export function AudioPage({
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 runTranscription = useCallback(
- async (blob: Blob, name: string) => {
- if (!selectedSttRepo) return;
- const key = sttSidecarKeyFor(selectedSttRepo);
- const engine = sttEngineForRepoId(selectedSttRepo);
- if (sttLoadedModel !== key || sttLoadedEngine !== engine) {
- toast.info("Wait for the transcription model to finish loading.");
- return;
- }
- transcriptionAbort.current?.abort();
+ 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;
- setBusy("transcribing");
- // Or a failure reads as this file's transcript, exported under its name.
- clearTranscript();
- setTranscribedName(name);
try {
- const text = await transcribeAudioBlob(blob, {
- model: key,
- engine,
- language: "",
- signal: controller.signal,
- });
- if (controller.signal.aborted || !activeRef.current) return;
- setTranscript(text);
- if (!text) toast.info("The model heard no speech in that audio.");
- } catch (error) {
+ 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.";
- if (activeRef.current) setTranscriptError(message);
+ 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();
}
@@ -2016,9 +2148,8 @@ export function AudioPage({
},
[
clearTranscript,
- selectedSttRepo,
- sttLoadedModel,
- sttLoadedEngine,
+ confirmTranscriptReplacement,
+ prepareTranscriptionModel,
refreshSttStatus,
],
);
@@ -2029,11 +2160,18 @@ export function AudioPage({
if (recorder && recorder.state !== "inactive") recorder.stop();
return;
}
- if (micPendingGeneration.current !== null) 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 },
});
@@ -2102,7 +2240,8 @@ export function AudioPage({
const blob = new Blob(chunks, {
type: recorder.mimeType || "audio/webm",
});
- if (!discard && blob.size > 0) void runTranscription(blob, "Recording");
+ 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
@@ -2129,21 +2268,25 @@ export function AudioPage({
setMicRequestPending(false);
}
}
- }, [isRecording, runTranscription, stopRecordStream]);
+ }, [
+ 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();
- transcriptionAbort.current?.abort();
}
- return () => {
- stopAndDiscardRecording();
- transcriptionAbort.current?.abort();
- };
+ return stopAndDiscardRecording;
}, [active, stopAndDiscardRecording]);
+ useEffect(() => () => transcriptionAbort.current?.abort(), []);
+
const handleTranscribeFile = useCallback(
(file: File | undefined) => {
if (!file) return;
@@ -2159,19 +2302,15 @@ export function AudioPage({
);
}, [transcript]);
- const handleDownloadTranscript = useCallback(() => {
- const blob = new Blob([transcript], { type: "text/plain" });
- const url = URL.createObjectURL(blob);
- const anchor = document.createElement("a");
- anchor.href = url;
- anchor.download = `${(transcribedName ?? "transcript").replace(/\.[^.]+$/, "")}.txt`;
- anchor.click();
- // Deferred like the gallery download below: browsers that resolve the synthetic navigation
- // asynchronously were left with a revoked URL and no file.
- window.setTimeout(() => URL.revokeObjectURL(url), 0);
+ 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());
@@ -2713,7 +2852,7 @@ export function AudioPage({
variant={isRecording ? "destructive" : "secondary"}
disabled={
!recordingSupported ||
- (!isRecording && (!sttReady || busy !== null)) ||
+ (!isRecording && (!(sttSelected || lastSttRepo) || busy !== null)) ||
micRequestPending
}
onClick={handleRecordToggle}
@@ -2725,7 +2864,7 @@ export function AudioPage({
{isRecording
? "Stop recording"
: micRequestPending
- ? "Waiting for microphone…"
+ ? busy === "loading" ? "Loading model…" : "Waiting for microphone…"
: "Record"}
</Button>
</Field>
@@ -2739,7 +2878,7 @@ export function AudioPage({
type="file"
accept="audio/*"
disabled={
- !sttReady ||
+ !(sttSelected || lastSttRepo) ||
busy !== null ||
isRecording ||
micRequestPending
@@ -2751,7 +2890,7 @@ export function AudioPage({
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 ? null : (
+ {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.
@@ -2819,55 +2958,94 @@ export function AudioPage({
data-reload-snapshot-sensitive={
transcript || transcribedName ? "" : undefined
}
- className="hover-scrollbar flex flex-1 flex-col gap-3 overflow-auto p-6 px-10 @[50rem]:pt-[60px]"
+ className="flex min-h-0 flex-1 flex-col gap-3 p-6 px-10 @[50rem]:pt-[60px]"
>
- {busy === "transcribing" ? (
- <div className="flex items-center gap-2 text-ui-13 text-muted-foreground">
- <Spinner className="size-4" />
- Transcribing {transcribedName ?? "audio"}…
- </div>
- ) : null}
- {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 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>
- <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>
+ ) : busy !== "transcribing" ? (
<p className="text-ui-13 text-muted-foreground">
- {transcriptError}
+ Record or upload audio to transcribe. Completed transcripts are saved
+ to history.
</p>
- </div>
- ) : busy !== "transcribing" ? (
- <p className="text-ui-13 text-muted-foreground">
- The transcript appears here. It is not stored: copy or
- download what you want to keep.
- </p>
- ) : null}
+ ) : 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>
</div>
) : (
<div className="flex min-h-0 flex-1 flex-col gap-4 p-6 px-10 @[50rem]:pt-[60px]">
diff --git a/studio/frontend/src/features/audio/transcript-download.ts b/studio/frontend/src/features/audio/transcript-download.ts
new file mode 100644
index 00000000000..0672fca8f89
--- /dev/null
+++ b/studio/frontend/src/features/audio/transcript-download.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 { downloadFile, isDownloadCancelled } from "@/lib/native-files";
+import { toast } from "@/lib/toast";
+
+export async function downloadTranscript(
+ text: string,
+ title: string,
+): Promise<boolean> {
+ try {
+ await downloadFile(
+ text,
+ `${
+ title
+ .replace(/\.[^.]+$/, "")
+ .replace(/[<>:"/\\|?*]/g, "_")
+ .replace(/\p{Cc}/gu, "_") || "transcript"
+ }.txt`,
+ "text/plain;charset=utf-8",
+ );
+ return true;
+ } catch (error) {
+ if (!isDownloadCancelled(error))
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : "Could not download transcript.",
+ );
+ return false;
+ }
+}
diff --git a/studio/frontend/src/features/audio/transcript-draft.ts b/studio/frontend/src/features/audio/transcript-draft.ts
new file mode 100644
index 00000000000..3bbd43408b3
--- /dev/null
+++ b/studio/frontend/src/features/audio/transcript-draft.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 { accountDatabaseName } from "../../lib/account-transition.ts";
+
+export interface TranscriptDraft {
+ text: string;
+ title: string;
+ model: string;
+}
+
+export function transcriptDraftKey(): string {
+ return accountDatabaseName("unsloth:audio:unsaved-transcript");
+}
+
+export function readTranscriptDraft(key: string): TranscriptDraft | null {
+ try {
+ const draft = JSON.parse(sessionStorage.getItem(key) ?? "null");
+ if (
+ !draft ||
+ typeof draft.text !== "string" ||
+ !draft.text ||
+ typeof draft.title !== "string" ||
+ typeof draft.model !== "string"
+ ) {
+ return null;
+ }
+ return { text: draft.text, title: draft.title, model: draft.model };
+ } catch {
+ return null;
+ }
+}
+
+export function writeTranscriptDraft(
+ key: string,
+ draft: TranscriptDraft | null,
+): boolean {
+ try {
+ if (draft) sessionStorage.setItem(key, JSON.stringify(draft));
+ else sessionStorage.removeItem(key);
+ return true;
+ } catch {
+ return false;
+ }
+}
diff --git a/studio/frontend/src/features/audio/transcript-gallery.tsx b/studio/frontend/src/features/audio/transcript-gallery.tsx
new file mode 100644
index 00000000000..330db744942
--- /dev/null
+++ b/studio/frontend/src/features/audio/transcript-gallery.tsx
@@ -0,0 +1,296 @@
+// 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,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from "react";
+import { HugeiconsIcon } from "@hugeicons/react";
+import {
+ Archive02Icon,
+ Copy01Icon,
+ Delete02Icon,
+ Download01Icon,
+ MoreVerticalIcon,
+} from "@hugeicons/core-free-icons";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { downloadTranscript } from "./transcript-download";
+import { toast } from "@/lib/toast";
+import { cn } from "@/lib/utils";
+import { archiveTranscript, deleteTranscript, listTranscripts } from "./api";
+import type { TranscriptRecord } from "./transcript-stream";
+
+export function TranscriptGallery({
+ active,
+ currentId,
+ latest,
+ onSelect,
+ onDelete,
+ canSelect,
+ autoSelect,
+}: {
+ active: boolean;
+ autoSelect: boolean;
+ currentId: string | null;
+ latest: TranscriptRecord | null;
+ onSelect: (record: TranscriptRecord) => void;
+ onDelete: (ids: string[] | null) => void;
+ canSelect: () => boolean;
+}) {
+ const [records, setRecords] = useState<TranscriptRecord[]>([]);
+ const [archived, setArchived] = useState(false);
+ const [cursor, setCursor] = useState<string | null>(null);
+ const [loading, setLoading] = useState(true);
+ const generation = useRef(0);
+ const loadingRef = useRef(false);
+ const currentIdRef = useRef(currentId);
+ const selectionRef = useRef({ autoSelect, onSelect, onDelete });
+ useLayoutEffect(() => {
+ currentIdRef.current = currentId;
+ selectionRef.current = { autoSelect, onSelect, onDelete };
+ }, [currentId, autoSelect, onSelect, onDelete]);
+ const refresh = useCallback(() => {
+ const ticket = ++generation.current;
+ loadingRef.current = true;
+ return listTranscripts(archived)
+ .then((page) => {
+ if (ticket !== generation.current) return;
+ setRecords(page.transcripts);
+ setCursor(page.next_cursor);
+ if (
+ selectionRef.current.autoSelect &&
+ !currentIdRef.current &&
+ page.transcripts[0]
+ ) {
+ selectionRef.current.onSelect(page.transcripts[0]);
+ }
+ })
+ .catch((error: unknown) => {
+ if (ticket !== generation.current) return;
+ // Rows and cursor belong to the view we just left: keeping them renders History
+ // entries under the Archived heading and pages the wrong cursor onto them.
+ setRecords([]);
+ setCursor(null);
+ toast.error(
+ error instanceof Error ? error.message : "Could not load transcripts.",
+ );
+ })
+ .finally(() => {
+ if (ticket === generation.current) {
+ loadingRef.current = false;
+ setLoading(false);
+ }
+ });
+ }, [archived]);
+ const refreshRef = useRef(refresh);
+ useLayoutEffect(() => {
+ refreshRef.current = refresh;
+ }, [refresh]);
+ useEffect(() => {
+ if (active) void refresh();
+ return () => {
+ generation.current += 1;
+ };
+ }, [active, latest, refresh]);
+ const loadMore = async () => {
+ if (!cursor || loadingRef.current) return;
+ const ticket = generation.current;
+ loadingRef.current = true;
+ setLoading(true);
+ try {
+ const page = await listTranscripts(archived, cursor);
+ if (ticket !== generation.current) return;
+ setRecords((current) => [
+ ...current,
+ ...page.transcripts.filter(
+ (record) => !current.some((item) => item.id === record.id),
+ ),
+ ]);
+ setCursor(page.next_cursor);
+ } catch (error) {
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : "Could not load more transcripts.",
+ );
+ } finally {
+ if (ticket === generation.current) {
+ loadingRef.current = false;
+ setLoading(false);
+ }
+ }
+ };
+ const mutate = async (
+ action: () => Promise<void>,
+ removed: string[] | null,
+ ) => {
+ try {
+ await action();
+ if (removed === null || removed.includes(currentIdRef.current ?? ""))
+ selectionRef.current.onDelete(removed);
+ await refreshRef.current();
+ } catch (error) {
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : "Could not update transcript history.",
+ );
+ }
+ };
+ return (
+ <div className="flex shrink-0 flex-col gap-2">
+ <div className="flex items-center justify-between">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="px-0 text-ui-11p5 text-muted-foreground"
+ >
+ {archived ? "Archived transcripts" : "History"}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ <DropdownMenuItem onClick={() => setArchived(false)}>
+ History
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setArchived(true)}>
+ Archived transcripts
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {!archived && records.length > 0 && (
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => {
+ if (
+ window.confirm(
+ "Delete all transcripts in history? Archived transcripts will be kept.",
+ )
+ )
+ void mutate(() => deleteTranscript(), null);
+ }}
+ >
+ Clear all
+ </Button>
+ )}
+ </div>
+ <div
+ className="hover-scrollbar flex max-h-40 flex-col gap-1 overflow-y-auto"
+ onScroll={(event) => {
+ const el = event.currentTarget;
+ if (el.scrollTop + el.clientHeight >= el.scrollHeight - 40)
+ void loadMore();
+ }}
+ >
+ {records.map((record) => (
+ <div
+ key={record.id}
+ className={cn(
+ "group flex items-center rounded-md pr-1 transition-colors hover:bg-muted",
+ currentId === record.id && "bg-muted",
+ )}
+ >
+ <button
+ type="button"
+ aria-current={currentId === record.id ? "true" : undefined}
+ className="flex min-w-0 flex-1 items-center gap-2 px-2 py-1.5 text-left text-ui-13"
+ onClick={() => {
+ if (canSelect()) onSelect(record);
+ }}
+ >
+ <span className="min-w-0 flex-1 truncate">{record.title}</span>
+ <span className="shrink-0 text-ui-11p5 text-muted-foreground">
+ {new Date(record.created_at).toLocaleDateString()}
+ </span>
+ </button>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-5 text-muted-foreground/60 opacity-0 group-hover:opacity-100 focus-visible:opacity-100 data-[state=open]:opacity-100"
+ aria-label="Transcript actions"
+ >
+ <HugeiconsIcon icon={MoreVerticalIcon} className="size-3.5" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ onClick={() =>
+ void downloadTranscript(record.text, record.title)
+ }
+ >
+ <HugeiconsIcon icon={Download01Icon} />
+ Download .txt
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() =>
+ void navigator.clipboard.writeText(record.text).then(
+ () => toast.success("Transcript copied"),
+ () => toast.error("Could not copy transcript."),
+ )
+ }
+ >
+ <HugeiconsIcon icon={Copy01Icon} />
+ Copy
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={() =>
+ void mutate(
+ () => archiveTranscript(record.id, !record.archived),
+ [record.id],
+ )
+ }
+ >
+ <HugeiconsIcon icon={Archive02Icon} />
+ {record.archived ? "Unarchive" : "Archive"}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() =>
+ void mutate(() => deleteTranscript(record.id), [record.id])
+ }
+ >
+ <HugeiconsIcon icon={Delete02Icon} />
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ ))}
+ {!records.length && (
+ <p className="px-2 py-1.5 text-ui-13 text-muted-foreground">
+ {loading
+ ? "Loading transcripts…"
+ : archived
+ ? "No archived transcripts."
+ : "Completed transcripts are saved here."}
+ </p>
+ )}
+ {cursor && (
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={loading}
+ onClick={() => void loadMore()}
+ >
+ {loading ? "Loading…" : "Load more"}
+ </Button>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/audio/transcript-stream.ts b/studio/frontend/src/features/audio/transcript-stream.ts
new file mode 100644
index 00000000000..10b34173d90
--- /dev/null
+++ b/studio/frontend/src/features/audio/transcript-stream.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
+
+export interface TranscriptRecord {
+ id: string;
+ title: string;
+ text: string;
+ model: string;
+ language: string | null;
+ duration: number | null;
+ created_at: string;
+ archived: boolean;
+}
+
+export interface TranscriptProgress {
+ text: string;
+ processed_seconds?: number;
+ duration?: number;
+}
+
+export interface TranscriptResult {
+ text: string;
+ model: string;
+ duration: number | null;
+ record: TranscriptRecord | null;
+}
+
+export async function readTranscriptStream(
+ body: ReadableStream<Uint8Array>,
+ onProgress: (progress: TranscriptProgress) => void,
+): Promise<TranscriptResult> {
+ const reader = body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = "";
+ try {
+ for (;;) {
+ const { done, value } = await reader.read();
+ buffer += decoder.decode(value, { stream: !done });
+ const lines = buffer.split("\n");
+ buffer = lines.pop() ?? "";
+ if (done && buffer.trim()) lines.push(buffer);
+ for (const line of lines) {
+ if (!line.trim()) continue;
+ const event = JSON.parse(line);
+ if (event.type === "error") throw new Error(event.message);
+ if (event.type === "progress") onProgress(event);
+ if (event.type === "complete") return event as TranscriptResult;
+ }
+ if (done)
+ throw new Error(
+ "The transcription connection ended before the result arrived.",
+ );
+ }
+ } finally {
+ await reader.cancel().catch(() => undefined);
+ reader.releaseLock();
+ }
+}
diff --git a/studio/frontend/src/features/audio/transcription-progress.css b/studio/frontend/src/features/audio/transcription-progress.css
new file mode 100644
index 00000000000..b46eca2e49e
--- /dev/null
+++ b/studio/frontend/src/features/audio/transcription-progress.css
@@ -0,0 +1,23 @@
+/* SPDX-License-Identifier: AGPL-3.0-only */
+/* Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0 */
+
+@keyframes transcription-wave {
+ 0%, 100% { transform: scaleY(0.45); }
+ 50% { transform: scaleY(1); }
+}
+
+.transcription-wave > span {
+ animation: transcription-wave 1.6s ease-in-out infinite;
+}
+
+.transcription-wave[data-stopping="true"] > span {
+ animation-play-state: paused;
+}
+
+html.force-reduced-motion .transcription-wave > span {
+ animation: none;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ html:not(.force-motion) .transcription-wave > span { animation: none; }
+}
diff --git a/studio/frontend/src/features/audio/transcription-progress.tsx b/studio/frontend/src/features/audio/transcription-progress.tsx
new file mode 100644
index 00000000000..43146961fd2
--- /dev/null
+++ b/studio/frontend/src/features/audio/transcription-progress.tsx
@@ -0,0 +1,77 @@
+// 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, useState } from "react";
+import { Button } from "@/components/ui/button";
+import type { TranscriptProgress } from "./transcript-stream";
+import "./transcription-progress.css";
+
+export function TranscriptionProgress({
+ startedAt,
+ finishedAt,
+ stopping,
+ progress,
+ onCancel,
+}: {
+ startedAt: number;
+ finishedAt: number | null;
+ stopping: boolean;
+ progress: TranscriptProgress | null;
+ onCancel: () => void;
+}) {
+ const [now, setNow] = useState(Date.now);
+ useEffect(() => {
+ if (finishedAt !== null) return;
+ const timer = window.setInterval(() => setNow(Date.now()), 1000);
+ return () => window.clearInterval(timer);
+ }, [finishedAt]);
+ const seconds = Math.max(
+ 0,
+ Math.floor(((finishedAt ?? now) - startedAt) / 1000),
+ );
+ const elapsed = `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
+ const running = finishedAt === null;
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center gap-3 text-ui-13 text-muted-foreground">
+ {running && (
+ <span
+ className="transcription-wave flex h-5 items-center gap-[3px]"
+ aria-hidden="true"
+ data-stopping={stopping}
+ >
+ {[10, 16, 20, 14, 8].map((height, index) => (
+ <span
+ key={index}
+ className="w-[3px] rounded-full bg-current"
+ style={{ height, animationDelay: `${index * -230}ms` }}
+ />
+ ))}
+ </span>
+ )}
+ <span role="status">
+ {running ? (stopping ? "Stopping…" : "Transcribing…") : "Elapsed"}
+ </span>
+ <span className="tabular-nums" aria-label={`Elapsed time ${elapsed}`}>
+ {elapsed}
+ </span>
+ {running && (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="ml-auto"
+ onClick={onCancel}
+ disabled={stopping}
+ >
+ Cancel
+ </Button>
+ )}
+ </div>
+ {running && progress?.text && (
+ <p className="line-clamp-2 text-ui-13 leading-relaxed text-muted-foreground">
+ {progress.text.split(/\s+/).slice(-35).join(" ")}
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/auth/index.ts b/studio/frontend/src/features/auth/index.ts
index c5bcf16fe47..2e03d1c8ca3 100644
--- a/studio/frontend/src/features/auth/index.ts
+++ b/studio/frontend/src/features/auth/index.ts
@@ -4,6 +4,7 @@
export { LoginPage } from "./login-page";
export { ChangePasswordPage } from "./change-password-page";
export { authFetch, logout, refreshSession } from "./api";
+export { AUTH_SESSION_ENDING_EVENT } from "./session-events";
export {
AUTH_SESSION_CLEARED_EVENT,
AUTH_SESSION_MARK_KEY,
diff --git a/studio/frontend/src/features/auth/session-events.ts b/studio/frontend/src/features/auth/session-events.ts
index eee0e28ebad..51a8c92978d 100644
--- a/studio/frontend/src/features/auth/session-events.ts
+++ b/studio/frontend/src/features/auth/session-events.ts
@@ -3,3 +3,4 @@
export const AUTH_SESSION_CLEARED_EVENT = "unsloth:auth-session-cleared";
export const AUTH_SESSION_STORED_EVENT = "unsloth:auth-session-stored";
+export const AUTH_SESSION_ENDING_EVENT = "unsloth:auth-session-ending";
diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.ts
index cc949ef314d..f40d3917b0f 100644
--- a/studio/frontend/src/features/images/api.ts
+++ b/studio/frontend/src/features/images/api.ts
@@ -27,6 +27,7 @@ export interface DiffusionStatus {
dtype: string | null;
// Resolved load kind: "gguf" | "single_file" | "pipeline". Gates GGUF-only controls. Null when not loaded.
model_kind?: string | null;
+ gguf_filename?: string | null;
// Selected GGUF quant. Newer backends report this separately from the compute dtype.
gguf_variant?: string | null;
cpu_offload: boolean;
diff --git a/studio/frontend/src/features/images/image-model-recall.ts b/studio/frontend/src/features/images/image-model-recall.ts
new file mode 100644
index 00000000000..9d8ac97ce99
--- /dev/null
+++ b/studio/frontend/src/features/images/image-model-recall.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
+
+export interface RememberedImageModel {
+ repoId: string;
+ kind: "gguf" | "single_file" | "pipeline";
+ filename?: string;
+}
+
+const KEY = "unsloth:images:last-model";
+
+export function readImageModel(): RememberedImageModel | null {
+ try {
+ const value = JSON.parse(localStorage.getItem(KEY) ?? "null");
+ if (!value || typeof value.repoId !== "string" || !value.repoId.trim())
+ return null;
+ if (!["gguf", "single_file", "pipeline"].includes(value.kind)) return null;
+ if (
+ value.kind !== "pipeline" &&
+ (typeof value.filename !== "string" || !value.filename)
+ )
+ return null;
+ return {
+ repoId: value.repoId,
+ kind: value.kind,
+ ...(typeof value.filename === "string"
+ ? { filename: value.filename }
+ : {}),
+ };
+ } catch {
+ return null;
+ }
+}
+
+export function rememberImageModel(model: RememberedImageModel): void {
+ try {
+ localStorage.setItem(KEY, JSON.stringify(model));
+ } catch {
+ // storage can be unavailable in private browsing
+ }
+}
+
+export function matchesRememberedModel(
+ model: RememberedImageModel,
+ status: {
+ loaded: boolean;
+ repo_id?: string | null;
+ model_kind?: string | null;
+ gguf_filename?: string | null;
+ },
+): boolean {
+ return (
+ status.loaded &&
+ status.repo_id === model.repoId &&
+ status.model_kind === model.kind &&
+ (model.kind === "pipeline" || status.gguf_filename === model.filename)
+ );
+}
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index 54ef88fecd2..538d0a4414e 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -1,6 +1,7 @@
// 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 { readImageModel, rememberImageModel, matchesRememberedModel, type RememberedImageModel } from "./image-model-recall";
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import {
ArrowLeftRightIcon,
@@ -89,7 +90,7 @@ import {
} from "@/lib/gallery-flags";
import { usePersistedToggle } from "@/hooks/use-persisted-toggle";
import { useImageWorkflowStore } from "./stores/image-workflow-store";
-import { WORKFLOW_TABS } from "./workflows";
+import { WORKFLOW_TABS, type WorkflowId } from "./workflows";
import { ParamSlider } from "@/features/chat";
import { ModelLoadDescription } from "@/features/chat/components/model-load-status";
import {
@@ -1161,6 +1162,8 @@ export function ImagesPage({
onInitialReady?: () => void;
}) {
const initialReadySent = useRef(false);
+ const [rememberedModel, setRememberedModel] = useState(readImageModel);
+ const pendingRecalledGeneration = useRef<{ model: RememberedImageModel; load: number; workflow: WorkflowId } | null>(null);
const { isMobile, pinned } = useSidebar();
const hostClass = useHostClass();
const imageModels = useImageModels(hostClass);
@@ -2134,6 +2137,10 @@ export function ImagesPage({
}
setStatusIfNewest(ticket, loaded);
toast.success("Model loaded");
+ if (lastLoad.current && matchesRememberedModel(lastLoad.current, loaded)) {
+ rememberImageModel(lastLoad.current);
+ setRememberedModel(lastLoad.current);
+ }
setBusy(null);
// Load succeeded: the optimistic quant is now the real one, so drop the pending revert.
quantRevert.current?.commitRecipeClaim?.();
@@ -2145,6 +2152,7 @@ export function ImagesPage({
return;
}
if (p.phase === "error") {
+ pendingRecalledGeneration.current = null;
dismissLoadToast();
reportLoadFailure(p.error, "Failed to load model");
setBusy(null);
@@ -2165,6 +2173,7 @@ export function ImagesPage({
return;
}
if (p.phase === null) {
+ pendingRecalledGeneration.current = null;
// No load in flight and nothing loaded: the load was cancelled or evicted. Terminal, else this
// loop spins forever.
dismissLoadToast();
@@ -2356,9 +2365,9 @@ export function ImagesPage({
}, [resolvedKey]);
const bakedLorasFor = useCallback(
- (repoId: string): LoraSpecInput[] => {
+ (repoId: string, preserveSelection = false): LoraSpecInput[] => {
const sameTarget = repoId === (lastLoad.current?.repoId ?? status?.repo_id ?? null);
- if (!sameTarget) return [];
+ if (!sameTarget && !preserveSelection) return [];
return loras
.map((l) => ({ id: l.id.trim(), weight: l.weight }))
.filter((l) => l.id && l.weight > 0);
@@ -2368,8 +2377,8 @@ export function ImagesPage({
// One snapshot of every Advanced control a load sends, so a staged pick can pin the values it planned against.
const currentLoadAdvanced = useCallback(
- (repoId: string): LoadAdvanced => {
- const baked = bakedLorasFor(repoId);
+ (repoId: string, preserveSelection = false): LoadAdvanced => {
+ const baked = bakedLorasFor(repoId, preserveSelection);
return {
cpu_offload: cpuOffload,
speed_mode: speedMode === "auto" ? undefined : speedMode,
@@ -2811,6 +2820,7 @@ export function ImagesPage({
);
const beginPick = useCallback(() => {
+ pendingRecalledGeneration.current = null;
pickSeq.current += 1;
pendingStagedLoad.current = null;
pendingLoadEntries.current = null;
@@ -3211,6 +3221,7 @@ export function ImagesPage({
// Resolves true when the backend accepted the unload; handleCancelLoad reports the cancel only then.
const handleUnload = useCallback(async (): Promise<boolean> => {
+ pendingRecalledGeneration.current = null;
// Ejecting cancels any in-flight replacement load, so tear down its client-side tracking too
// or the toast leaks forever.
dropResidentState();
@@ -3563,6 +3574,82 @@ export function ImagesPage({
}
}, []);
+ const handleGenerateWithRecall = useCallback(async () => {
+ if (busy !== null || !imagePresets.hydrated) return;
+ if (status?.loaded) {
+ const kind = status.model_kind;
+ if (
+ status.repo_id &&
+ (kind === "pipeline" ||
+ ((kind === "gguf" || kind === "single_file") && status.gguf_filename))
+ ) {
+ const model: RememberedImageModel = {
+ repoId: status.repo_id,
+ kind,
+ filename: status.gguf_filename ?? undefined,
+ };
+ rememberImageModel(model);
+ setRememberedModel(model);
+ }
+ await handleGenerate();
+ return;
+ }
+ if (!rememberedModel || !prompt.trim()) {
+ toast.info(
+ rememberedModel
+ ? "Enter a prompt first."
+ : "Pick an image model first.",
+ );
+ return;
+ }
+ pendingRecalledGeneration.current = {
+ model: rememberedModel,
+ load: loadSeq.current + 1,
+ workflow,
+ };
+ const started = await handleLoad(
+ rememberedModel.repoId,
+ { kind: rememberedModel.kind, filename: rememberedModel.filename },
+ currentLoadAdvanced(rememberedModel.repoId, true),
+ );
+ if (!started) pendingRecalledGeneration.current = null;
+ }, [
+ busy,
+ currentLoadAdvanced,
+ handleGenerate,
+ handleLoad,
+ imagePresets.hydrated,
+ prompt,
+ rememberedModel,
+ status,
+ workflow,
+ ]);
+
+ useEffect(() => {
+ const pending = pendingRecalledGeneration.current;
+ if (!pending) return;
+ if (!active || pending.load !== loadSeq.current) {
+ pendingRecalledGeneration.current = null;
+ return;
+ }
+ if (busy !== null || !status?.loaded) return;
+ pendingRecalledGeneration.current = null;
+ const tab = WORKFLOW_TABS.find(
+ (candidate) => candidate.id === pending.workflow,
+ );
+ if (
+ pending.workflow !== workflow ||
+ !tab ||
+ !(status.workflows ?? []).includes(tab.requires ?? "txt2img")
+ ) {
+ toast.info(
+ "Choose a workflow supported by the loaded model before generating.",
+ );
+ return;
+ }
+ if (matchesRememberedModel(pending.model, status)) void handleGenerate();
+ }, [active, busy, handleGenerate, status, workflow]);
+
// Publish what the loaded model can do, so the sidebar submenu dims the rest. null while
// nothing is loaded, which leaves every workflow open to set up first.
useEffect(() => {
@@ -3617,8 +3704,11 @@ export function ImagesPage({
]}
/>
{/* The dense transformer_quant fast path engages only on the GGUF kind, so gate the control to
- GGUF (or nothing loaded) and otherwise say why it is unavailable. */}
- {!status?.loaded || status.model_kind === "gguf" ? (
+ GGUF (or nothing loaded) and otherwise say why it is unavailable. Native sd.cpp reports
+ model_kind "gguf" as well, to be recallable by exact checkpoint, but runs no torchao path:
+ gate it out by ENGINE or it offers FP8/INT8/NVFP4 with no badge and snaps back on load. */}
+ {!status?.loaded
+ || (status.model_kind === "gguf" && !isNativeEngineStatus(status)) ? (
<AdvancedSelect
label="Precision"
hint="How the model computes. Auto picks the fastest precision the hardware supports (at least INT8 on a capable GPU; FP8 on data-center cards) by loading the FULL base model and quantising its transformer onto low-precision tensor cores, and falls back to running the GGUF as-is when the device, VRAM or disk can't take it. Off always runs the GGUF as-is."
@@ -4442,8 +4532,8 @@ export function ImagesPage({
) : (
<Button
className="relative z-10 h-11 px-8 disabled:bg-muted disabled:text-muted-foreground disabled:opacity-100"
- onClick={handleGenerate}
- disabled={busy !== null || !status?.loaded}
+ onClick={handleGenerateWithRecall}
+ disabled={busy !== null || !imagePresets.hydrated || (!status?.loaded && !rememberedModel)}
>
Generate
</Button>
diff --git a/studio/frontend/src/features/settings/index.ts b/studio/frontend/src/features/settings/index.ts
index 42f5e7a3cd0..ddab0329ae6 100644
--- a/studio/frontend/src/features/settings/index.ts
+++ b/studio/frontend/src/features/settings/index.ts
@@ -91,4 +91,5 @@ export { useSettingsDialogStore } from "./stores/settings-dialog-store";
export type { SettingsTab } from "./stores/settings-dialog-store";
export type { Palette, ResolvedTheme, Theme } from "./stores/theme-store";
+export { useVoiceSettingsStore } from "./stores/voice-settings-store";
export { isMacPlatform } from "./lib/keyboard-shortcuts";
diff --git a/studio/frontend/src/lib/native-files.ts b/studio/frontend/src/lib/native-files.ts
index 70f16cb98a1..6518f21acb4 100644
--- a/studio/frontend/src/lib/native-files.ts
+++ b/studio/frontend/src/lib/native-files.ts
@@ -60,7 +60,7 @@ export function browserDownload(blob: Blob, filename: string): void {
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
- URL.revokeObjectURL(url);
+ window.setTimeout(() => URL.revokeObjectURL(url), 0);
}
function browserUrlDownload(url: string, filename: string): void {
diff --git a/studio/frontend/tests/account-transition.test.ts b/studio/frontend/tests/account-transition.test.ts
index 5eb9395652f..38ade3010ce 100644
--- a/studio/frontend/tests/account-transition.test.ts
+++ b/studio/frontend/tests/account-transition.test.ts
@@ -571,3 +571,37 @@ test("saved recipes live in a per-account store and are never purged", () => {
"unsloth-data-recipes:alice",
);
});
+
+test("transcript recovery survives reauthentication but is cleared on account changes", async () => {
+ const { readTranscriptDraft, transcriptDraftKey, writeTranscriptDraft } =
+ await import("../src/features/audio/transcript-draft.ts");
+ const b = browserWith({ [BROWSER_ACCOUNT_KEY]: "account:alice-id:alice" });
+ const originals = ["window", "sessionStorage"].map((name) => [
+ name, Object.getOwnPropertyDescriptor(globalThis, name),
+ ] as const);
+ Object.defineProperty(globalThis, "window", { configurable: true, value: b.browser });
+ Object.defineProperty(globalThis, "sessionStorage", {
+ configurable: true, value: b.browser.sessionStorage,
+ });
+ try {
+ const key = transcriptDraftKey();
+ const draft = { text: "keep this transcript", title: "speech.wav", model: "tiny" };
+ assert.equal(writeTranscriptDraft(key, draft), true);
+ b.data.delete("unsloth_auth_token");
+ await transitionBrowserAccount(
+ { username: "alice", accountId: "alice-id" }, "/chat", () => {}, b.browser,
+ );
+ assert.deepEqual(readTranscriptDraft(transcriptDraftKey()), draft);
+ await transitionBrowserAccount(
+ { username: "bob", accountId: "bob-id" }, "/chat", () => {}, b.browser,
+ );
+ assert.notEqual(transcriptDraftKey(), key);
+ assert.equal(readTranscriptDraft(key), null);
+ assert.equal(readTranscriptDraft(transcriptDraftKey()), null);
+ } finally {
+ for (const [name, descriptor] of originals) {
+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);
+ else Reflect.deleteProperty(globalThis, name);
+ }
+ }
+});
diff --git a/studio/frontend/tests/audio-generation-stop.test.ts b/studio/frontend/tests/audio-generation-stop.test.ts
index e305f27e219..e94ec1554b6 100644
--- a/studio/frontend/tests/audio-generation-stop.test.ts
+++ b/studio/frontend/tests/audio-generation-stop.test.ts
@@ -95,20 +95,25 @@ test("leaving the audio page does NOT abort an in-flight generation", () => {
);
});
-test("leaving the audio page aborts an in-flight transcription", () => {
+test("transcription survives page deactivation and aborts on unmount", () => {
assert.match(
source,
/const transcriptionAbort = useRef<AbortController \| null>\(null\)/,
);
assert.match(
source,
- /transcribeAudioBlob\(blob, \{[\s\S]*signal: controller\.signal/,
+ /transcribeWithProgress\(\s*blob,\s*name,\s*\{[\s\S]*signal: controller\.signal/,
);
- assert.match(
- source,
- /if \(!active\) \{[\s\S]*transcriptionAbort\.current\?\.abort\(\)/,
+ const lifecycle = source.slice(
+ source.indexOf("// Release the microphone"),
+ source.indexOf("const handleTranscribeFile"),
);
+ assert.match(lifecycle, /if \(!active\) \{\s*stopAndDiscardRecording\(\);\s*\}/);
assert.match(
+ lifecycle,
+ /useEffect\(\(\) => \(\) => transcriptionAbort\.current\?\.abort\(\), \[\]\)/,
+ );
+ assert.doesNotMatch(
source,
/if \(controller\.signal\.aborted \|\| !activeRef\.current\) return/,
);
diff --git a/studio/frontend/tests/audio-page-policy.test.ts b/studio/frontend/tests/audio-page-policy.test.ts
index c1e6029cf1f..48ccc3852e5 100644
--- a/studio/frontend/tests/audio-page-policy.test.ts
+++ b/studio/frontend/tests/audio-page-policy.test.ts
@@ -381,10 +381,10 @@ test("gallery refresh preserves fallback selection and pagination identity", ()
});
test("Audio transcription uses backend language auto-detection", () => {
- assert.match(
- audioPageSource,
- /transcribeAudioBlob\(blob, \{[\s\S]*model: key,[\s\S]*engine,[\s\S]*language: ""/,
- );
+ const api = readSrc("features/audio/api.ts");
+ const transcription = api.slice(api.indexOf("export async function transcribeWithProgress"), api.indexOf("export async function listTranscripts"));
+ assert.doesNotMatch(transcription, /dictationLanguage|language:/);
+ assert.match(transcription, /stream: "true"/);
});
test("older STT status requests cannot overwrite newer residency", () => {
@@ -559,12 +559,8 @@ test("the trained-model list applies the native-aware macOS policy", () => {
});
test("the transcript download revokes its URL only after the click is consumed", () => {
- // Immediate revocation raced browsers that resolve a synthetic download navigation
- // asynchronously, leaving the action with no file.
- assert.match(
- audioPageSource,
- /anchor\.download = `\$\{\(transcribedName[\s\S]*?anchor\.click\(\);[\s\S]*?window\.setTimeout\(\(\) => URL\.revokeObjectURL\(url\), 0\);/,
- );
+ assert.match(readSrc("features/audio/transcript-download.ts"), /await downloadFile\(\s*text,/);
+ assert.match(readSrc("lib/native-files.ts"), /anchor\.click\(\);[\s\S]*?window\.setTimeout\(\(\) => URL\.revokeObjectURL\(url\), 0\);/);
});
test("a complete first page drops cached rows the server no longer holds", () => {
diff --git a/studio/frontend/tests/audio-transcript-lifecycle.test.ts b/studio/frontend/tests/audio-transcript-lifecycle.test.ts
index 6ade4dc889f..3d82f695c43 100644
--- a/studio/frontend/tests/audio-transcript-lifecycle.test.ts
+++ b/studio/frontend/tests/audio-transcript-lifecycle.test.ts
@@ -3,57 +3,297 @@
import assert from "node:assert/strict";
import test from "node:test";
-
-import { readSrc } from "./helpers/kit.ts";
+import ts from "typescript";
+import { readSrc, readText } from "./helpers/kit.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");
-test("a transcription run clears the previous result before it awaits", () => {
- // Download .txt used to save A's words under B's name.
+test("macOS termination checks unsaved transcripts before allowing exit", () => {
+ const native = readText("../../src-tauri/src/main.rs");
+ const predicate = native.slice(
+ native.indexOf("fn quit_requires_confirmation"),
+ native.indexOf("fn cleanup_child_processes"),
+ );
+ assert.match(predicate, /\|\| renderer.unsaved_transcript/);
assert.match(
- source,
- /setBusy\("transcribing"\);[\s\S]*?clearTranscript\(\);\s*setTranscribedName\(name\);\s*try \{/,
+ native,
+ /begin_or_attach_termination\(quit_requires_confirmation\(app\)\)/,
);
+ assert.match(native, /&& confirm_quit_with_unsaved_transcript\(&app\)/);
});
-test("a failed transcription is reported in the pane, not only in a toast", () => {
- assert.match(
- source,
- /if \(activeRef\.current\) setTranscriptError\(message\);\s*toast\.error\(message\);/,
+function section(start: string, end: string): string {
+ return source.slice(
+ source.indexOf(start),
+ source.indexOf(end, source.indexOf(start)),
);
- assert.match(
+}
+
+function callback(name: string, scope: Record<string, unknown>) {
+ const tree = ts.createSourceFile(
+ "audio-page.tsx",
source,
- /\) : transcriptError \? \([\s\S]*?Could not transcribe \{transcribedName \?\? "that audio"\}/,
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX,
);
+ let expression: ts.Expression | undefined;
+ function visit(node: ts.Node) {
+ if (
+ ts.isVariableDeclaration(node) &&
+ node.name.getText(tree) === name &&
+ node.initializer &&
+ ts.isCallExpression(node.initializer)
+ ) {
+ expression = node.initializer.arguments[0];
+ }
+ ts.forEachChild(node, visit);
+ }
+ visit(tree);
+ assert.ok(expression, `missing callback ${name}`);
+ const { outputText } = ts.transpileModule(
+ `return (${expression.getText(tree)});`,
+ {
+ compilerOptions: { target: ts.ScriptTarget.ES2022 },
+ },
+ );
+ return new Function(...Object.keys(scope), outputText)(
+ ...Object.values(scope),
+ );
+}
+
+test("declining replacement prevents recording setup", async () => {
+ const events: string[] = [];
+ const start = callback("handleRecordToggle", {
+ isRecording: false,
+ micPendingGeneration: { current: null },
+ busyRef: { current: null },
+ micRequestGeneration: { current: 0 },
+ transcriptVersion: { current: 7 },
+ setMicRequestPending: () => {},
+ confirmTranscriptReplacement: () => {
+ events.push("confirm");
+ return false;
+ },
+ prepareTranscriptionModel: async () => {
+ events.push("prepare");
+ return null;
+ },
+ });
+ await start();
+ assert.deepEqual(events, ["confirm"]);
});
-test("clearing a transcript drops its name and error together", () => {
+test("recording approval applies once and only to the transcript it covered", async () => {
+ for (const approvedVersion of [7, 6, undefined]) {
+ const events: string[] = [];
+ const run = callback("runTranscription", {
+ transcriptionAbort: { current: null },
+ busyRef: { current: null },
+ transcriptVersion: { current: 7 },
+ activeRef: { current: false },
+ confirmTranscriptReplacement: () => {
+ events.push("confirm");
+ return false;
+ },
+ prepareTranscriptionModel: async () => {
+ events.push("prepare");
+ return null;
+ },
+ setBusy: () => {},
+ AbortController,
+ });
+ await run(new Blob(["recording"]), "Recording", approvedVersion);
+ assert.deepEqual(events, approvedVersion === 7 ? ["prepare"] : ["confirm"]);
+ }
+ const recording = section(
+ "const handleRecordToggle",
+ "// Release the microphone",
+ );
+ assert.match(recording, /const confirmedVersion = transcriptVersion.current/);
assert.match(
- source,
- /const clearTranscript = useCallback\(\(\) => \{\s*setTranscript\(""\);\s*setTranscribedName\(null\);\s*setTranscriptError\(null\);\s*\}, \[\]\);/,
+ recording,
+ /runTranscription\(blob, "Recording", confirmedVersion\)/,
);
});
-test("a transcript never outlives the selection that produced it", () => {
- assert.match(source, /const forget = \(\) => \{[\s\S]*?clearTranscript\(\);/);
- assert.match(
- source,
- /if \(selectedSttRepoRef\.current !== id\) clearTranscript\(\);/,
+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",
);
+ assert.doesNotMatch(refresh, /clearTranscript\(/);
+ assert.doesNotMatch(release, /clearTranscript\(/);
+ assert.match(source, /setTranscriptModel\(result.model\)/);
+ assert.match(source, /setTranscriptModel\(record.model\)/);
});
-test("a resync that adopts another surface's model clears the transcript too", () => {
- // Chat dictation shares the sidecar, so a resync can adopt an unpicked model.
- assert.match(
- source,
- /const reconciled = reconcileSttSelection\(\{[\s\S]*?\}\);[\s\S]*?if \(reconciled !== null && reconciled !== selectedSttRepoRef\.current\)\s*clearTranscript\(\);\s*selectedSttRepoRef\.current = reconciled;/,
+test("the previous result is replaced only after its replacement model is ready", () => {
+ const run = section("const runTranscription", "const handleRecordToggle");
+ assert.match(run, /confirmTranscriptReplacement\(\)/);
+ assert.ok(
+ run.indexOf("await prepareTranscriptionModel()") <
+ run.indexOf("clearTranscript()"),
+ );
+ assert.ok(
+ run.indexOf("clearTranscript()") <
+ run.indexOf("await transcribeWithProgress"),
);
});
-test("an idle sidecar unload leaves the transcript the user came back for", () => {
- // The 5-minute idle unload fires while hidden; clearing there loses the text.
+test("leaving the page stops microphone capture while transcription can finish into history", () => {
+ const lifecycle = section(
+ "// Release the microphone",
+ "const handleTranscribeFile",
+ );
+ assert.match(
+ lifecycle,
+ /if \(!active\) \{\s*stopAndDiscardRecording\(\);\s*\}/,
+ );
+ assert.match(
+ lifecycle,
+ /useEffect\(\(\) => \(\) => transcriptionAbort.current\?\.abort\(\), \[\]\)/,
+ );
+ const run = section("const runTranscription", "const handleRecordToggle");
assert.doesNotMatch(
- source,
- /if \(reconciled !== selectedSttRepoRef\.current\) clearTranscript\(\);/,
+ run.slice(run.indexOf("await transcribeWithProgress")),
+ /!activeRef.current/,
+ );
+});
+
+test("logout checks unsaved transcripts before revoking the session or navigating", async () => {
+ const eventName = AUTH_SESSION_ENDING_EVENT;
+ const sidebar = readSrc("components/app-sidebar.tsx");
+ const parse = (text: string) =>
+ ts.createSourceFile(
+ "component.tsx", text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX,
+ );
+ const audioTree = parse(source);
+ let protection: string | undefined;
+ function findProtection(node: ts.Node) {
+ if (
+ ts.isCallExpression(node) &&
+ node.expression.getText(audioTree) === "useEffect" &&
+ node.arguments[0]?.getText(audioTree).includes('"set_renderer_activity"')
+ ) {
+ protection = node.arguments[0].getText(audioTree);
+ }
+ ts.forEachChild(node, findProtection);
+ }
+ findProtection(audioTree);
+ assert.ok(protection);
+ const sidebarTree = parse(sidebar);
+ const handlers: string[] = [];
+ function findLogout(node: ts.Node) {
+ if (
+ ts.isArrowFunction(node) &&
+ node.modifiers?.some((item) => item.kind === ts.SyntaxKind.AsyncKeyword) &&
+ node.body.getText(sidebarTree).includes("await logout()")
+ ) {
+ handlers.push(node.getText(sidebarTree));
+ }
+ ts.forEachChild(node, findLogout);
+ }
+ findLogout(sidebarTree);
+ assert.equal(handlers.length, 2);
+ const execute = (expression: string, scope: Record<string, unknown>) => {
+ const { outputText } = ts.transpileModule(`return (${expression});`, {
+ compilerOptions: { target: ts.ScriptTarget.ES2022 },
+ });
+ return new Function(...Object.keys(scope), outputText)(
+ ...Object.values(scope),
+ );
+ };
+ for (const handler of handlers) {
+ for (const scenario of ["decline", "accept", "saved", "exported", "unmounted"]) {
+ const events: string[] = [];
+ const drafts = new Map<string, string>();
+ Object.defineProperty(globalThis, "sessionStorage", {
+ configurable: true,
+ value: {
+ getItem: (key: string) => drafts.get(key) ?? null,
+ setItem: (key: string, value: string) => drafts.set(key, value),
+ removeItem: (key: string) => drafts.delete(key),
+ },
+ });
+ const target = new EventTarget();
+ const window = Object.assign(target, {
+ confirm: () => {
+ events.push("confirm");
+ return scenario === "accept";
+ },
+ });
+ const cleanup = execute(protection, {
+ transcript: "unsaved text",
+ transcriptRecord: scenario === "saved" ? { id: "saved" } : null,
+ transcriptExported: scenario === "exported",
+ draftKey: "test-draft",
+ transcribedName: "speech.wav",
+ transcriptModel: "tiny",
+ writeTranscriptDraft,
+ isTauri: false,
+ window,
+ AUTH_SESSION_ENDING_EVENT: eventName,
+ })();
+ if (scenario === "unmounted") cleanup?.();
+ await execute(handler, {
+ window,
+ Event,
+ AUTH_SESSION_ENDING_EVENT: eventName,
+ logout: async () => {
+ events.push("logout");
+ },
+ clearAuthTokens: () => {
+ events.push("clear");
+ },
+ navigate: () => {
+ events.push("navigate");
+ },
+ })();
+ assert.deepEqual(
+ events,
+ scenario === "decline"
+ ? ["confirm"]
+ : scenario === "accept"
+ ? ["confirm", "logout", "navigate"]
+ : ["logout", "navigate"],
+ );
+ cleanup?.();
+ assert.deepEqual(
+ readTranscriptDraft("test-draft"),
+ scenario === "decline" || scenario === "unmounted"
+ ? { text: "unsaved text", title: "speech.wav", model: "tiny" }
+ : null,
+ );
+ }
+ }
+});
+
+test("remounting audio restores the unsaved transcript and its origin", () => {
+ const tree = ts.createSourceFile("audio-page.tsx", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+ const names = new Set(["draftKey", "recoveredTranscript", "transcript", "transcribedName", "transcriptModel"]);
+ const declarations: string[] = [];
+ function visit(node: ts.Node) {
+ if (ts.isVariableDeclaration(node) && ts.isArrayBindingPattern(node.name)) {
+ const name = node.name.elements[0]?.getText(tree);
+ if (name && names.has(name)) declarations.push(`const ${node.getText(tree)};`);
+ }
+ ts.forEachChild(node, visit);
+ }
+ visit(tree);
+ const draft = { text: "recovered speech", title: "speech.wav", model: "tiny" };
+ const { outputText } = ts.transpileModule(
+ declarations.join("\n") + "\nreturn {text: transcript, title: transcribedName, model: transcriptModel};",
+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } },
);
+ const scope = {
+ useState: (initial: unknown) => [typeof initial === "function" ? initial() : initial, () => {}],
+ transcriptDraftKey: () => "test-draft",
+ readTranscriptDraft: () => draft,
+ };
+ const restored = new Function(...Object.keys(scope), outputText)(...Object.values(scope));
+ assert.deepEqual(restored, draft);
});
diff --git a/studio/frontend/tests/image-model-recall.test.ts b/studio/frontend/tests/image-model-recall.test.ts
new file mode 100644
index 00000000000..a4bd43ca24d
--- /dev/null
+++ b/studio/frontend/tests/image-model-recall.test.ts
@@ -0,0 +1,190 @@
+// 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 ts from "typescript";
+import {
+ matchesRememberedModel,
+ readImageModel,
+ rememberImageModel,
+} from "../src/features/images/image-model-recall.ts";
+import { installLocalStorageFake, readSrc } from "./helpers/kit.ts";
+
+const { storage } = installLocalStorageFake();
+
+test("recalling a quantized model carries the selected adapters into its load", async () => {
+ const source = readSrc("features/images/images-page.tsx");
+ const tree = ts.createSourceFile(
+ "images-page.tsx",
+ source,
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX,
+ );
+ const names = new Set([
+ "bakedLorasFor",
+ "currentLoadAdvanced",
+ "handleGenerateWithRecall",
+ ]);
+ const declarations: string[] = [];
+ function visit(node: ts.Node) {
+ if (ts.isVariableDeclaration(node) && names.has(node.name.getText(tree)))
+ declarations.push(`const ${node.getText(tree)};`);
+ ts.forEachChild(node, visit);
+ }
+ visit(tree);
+ assert.equal(declarations.length, names.size);
+ const { outputText } = ts.transpileModule(
+ declarations.join("\n") +
+ "\nreturn { handleGenerateWithRecall, currentLoadAdvanced };",
+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } },
+ );
+ for (const quant of ["int8", "fp8"]) {
+ const model = {
+ repoId: "unsloth/model-GGUF",
+ kind: "gguf",
+ filename: "model-Q8_0.gguf",
+ };
+ const loads: unknown[][] = [];
+ const scope = {
+ useCallback: (fn: unknown) => fn,
+ lastLoad: { current: null },
+ status: { loaded: false, repo_id: null },
+ loras: [
+ { id: " org/style ", weight: 0.7 },
+ { id: "", weight: 1 },
+ { id: "org/off", weight: 0 },
+ ],
+ cpuOffload: false,
+ speedMode: "auto",
+ transformerQuant: quant,
+ textEncoderQuant: "int8",
+ attentionBackend: "auto",
+ memoryMode: "auto",
+ transformerCache: "auto",
+ selectedGpu: "auto",
+ gpuChoices: [],
+ busy: null,
+ imagePresets: { hydrated: true },
+ prompt: "a teapot",
+ rememberedModel: model,
+ pendingRecalledGeneration: { current: null },
+ loadSeq: { current: 3 },
+ workflow: "txt2img",
+ handleGenerate: () => {
+ throw new Error("generation must wait for the load");
+ },
+ handleLoad: async (...args: unknown[]) => {
+ loads.push(args);
+ return true;
+ },
+ };
+ const callbacks = new Function(...Object.keys(scope), outputText)(
+ ...Object.values(scope),
+ );
+ await callbacks.handleGenerateWithRecall();
+ assert.equal(loads.length, 1);
+ assert.equal(loads[0][0], model.repoId);
+ assert.deepEqual(loads[0][1], {
+ kind: model.kind,
+ filename: model.filename,
+ });
+ const advanced = loads[0][2] as
+ | {
+ loras?: unknown;
+ transformer_quant?: string;
+ text_encoder_quant?: string;
+ }
+ | undefined;
+ assert.deepEqual(advanced?.loras, [{ id: "org/style", weight: 0.7 }]);
+ assert.equal(advanced?.transformer_quant, quant);
+ assert.equal(advanced?.text_encoder_quant, "int8");
+ assert.equal(
+ callbacks.currentLoadAdvanced("org/different-model").loras,
+ undefined,
+ );
+ }
+});
+
+test("recall keeps the exact GGUF artifact", () => {
+ const model = {
+ repoId: "unsloth/model-GGUF",
+ kind: "gguf" as const,
+ filename: "model-Q4.gguf",
+ };
+ rememberImageModel(model);
+ assert.deepEqual(readImageModel(), model);
+ assert.equal(
+ matchesRememberedModel(model, {
+ loaded: true,
+ repo_id: model.repoId,
+ model_kind: "gguf",
+ gguf_filename: "model-Q8.gguf",
+ }),
+ false,
+ );
+ assert.equal(
+ matchesRememberedModel(model, {
+ loaded: true,
+ repo_id: model.repoId,
+ model_kind: "gguf",
+ gguf_filename: model.filename,
+ }),
+ true,
+ );
+});
+
+test("invalid or incomplete stored targets cannot trigger automatic loading", () => {
+ for (const value of [
+ "broken",
+ "null",
+ "{}",
+ '{"repoId":"org/model","kind":"gguf"}',
+ '{"repoId":"org/model","kind":"unknown"}',
+ ]) {
+ storage.setItem("unsloth:images:last-model", value);
+ assert.equal(readImageModel(), null);
+ }
+});
+
+test("a new model pick cancels recalled generation and retires the staged load", () => {
+ const source = readSrc("features/images/images-page.tsx");
+ const tree = ts.createSourceFile(
+ "images-page.tsx",
+ source,
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX,
+ );
+ let declaration: ts.VariableDeclaration | undefined;
+ function visit(node: ts.Node) {
+ if (ts.isVariableDeclaration(node) && node.name.getText(tree) === "beginPick") {
+ assert.equal(declaration, undefined, "beginPick must have one owner");
+ declaration = node;
+ }
+ ts.forEachChild(node, visit);
+ }
+ visit(tree);
+ assert.ok(declaration);
+ const { outputText } = ts.transpileModule(
+ `const ${declaration.getText(tree)}; beginPick();`,
+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } },
+ );
+ const scope = {
+ useCallback: (fn: unknown) => fn,
+ pendingRecalledGeneration: { current: { model: "previous" } },
+ pickSeq: { current: 4 },
+ pendingStagedLoad: { current: { token: 4 } },
+ pendingLoadEntries: { current: ["previous"] },
+ stagedLoadDeferred: { current: true },
+ stagedQuantRevert: { current: { prev: "Q8_0" } },
+ };
+ new Function(...Object.keys(scope), outputText)(...Object.values(scope));
+ assert.equal(scope.pendingRecalledGeneration.current, null);
+ assert.equal(scope.pickSeq.current, 5);
+ assert.equal(scope.pendingStagedLoad.current, null);
+ assert.equal(scope.pendingLoadEntries.current, null);
+ assert.equal(scope.stagedLoadDeferred.current, false);
+ assert.equal(scope.stagedQuantRevert.current, null);
+});
diff --git a/studio/frontend/tests/images-precision-gate-native.test.ts b/studio/frontend/tests/images-precision-gate-native.test.ts
new file mode 100644
index 00000000000..7192d69a25f
--- /dev/null
+++ b/studio/frontend/tests/images-precision-gate-native.test.ts
@@ -0,0 +1,79 @@
+// 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 ts from "typescript";
+
+import { isNativeEngineStatus } from "../src/lib/resolved-precision.ts";
+import { readSrc } from "./helpers/kit.ts";
+
+/** The Images page's Precision gate, evaluated the way the component evaluates it. */
+function precisionControlShown(status: {
+ loaded?: boolean;
+ model_kind?: string | null;
+ dtype?: string | null;
+ engine?: string | null;
+} | null): boolean {
+ return (
+ !status?.loaded
+ || (status.model_kind === "gguf" && !isNativeEngineStatus(status))
+ );
+}
+
+const DIFFUSERS_GGUF = {
+ loaded: true,
+ model_kind: "gguf",
+ dtype: "bfloat16",
+ engine: "diffusers",
+};
+// SdCppDiffusionBackend.status(): model_kind "gguf" to be recallable by exact checkpoint,
+// engine "sd_cpp" to say the torchao path is unavailable.
+const SD_CPP_NATIVE = {
+ loaded: true,
+ model_kind: "gguf",
+ dtype: "gguf",
+ engine: "sd_cpp",
+};
+
+test("the Precision control is offered for a diffusers GGUF and withheld from native sd.cpp", () => {
+ assert.equal(precisionControlShown(null), true, "nothing loaded: the control is free");
+ assert.equal(
+ precisionControlShown(DIFFUSERS_GGUF),
+ true,
+ "a diffusers GGUF load is exactly what transformer_quant is for",
+ );
+ assert.equal(
+ precisionControlShown({ ...DIFFUSERS_GGUF, model_kind: "pipeline" }),
+ false,
+ "a full pipeline has no GGUF to quantise",
+ );
+ // The regression this guards: sd.cpp reports transformer_quant null and no `resolved`
+ // map, so an offered control has no badge and snaps back on the next load.
+ assert.equal(
+ precisionControlShown(SD_CPP_NATIVE),
+ false,
+ "the native sd.cpp engine runs no torchao path, so Precision must stay withheld",
+ );
+});
+
+test("the Images page gates Precision on the engine, not on model_kind alone", () => {
+ // The component's own source, so the helper above cannot drift away from it.
+ const source = readSrc("features/images/images-page.tsx");
+ const tree = ts.createSourceFile(
+ "images-page.tsx",
+ source,
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX,
+ );
+ void tree;
+ const gate = source.includes(
+ 'status.model_kind === "gguf" && !isNativeEngineStatus(status)',
+ );
+ assert.ok(
+ gate,
+ "the Precision gate must exclude the native engine; a bare "
+ + 'status.model_kind === "gguf" offers FP8/INT8/NVFP4 to sd.cpp, which ignores them',
+ );
+});
diff --git a/studio/frontend/tests/transcript-gallery-mutation.test.ts b/studio/frontend/tests/transcript-gallery-mutation.test.ts
new file mode 100644
index 00000000000..e7b35b661ed
--- /dev/null
+++ b/studio/frontend/tests/transcript-gallery-mutation.test.ts
@@ -0,0 +1,190 @@
+// 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 ts from "typescript";
+import { readSrc } from "./helpers/kit.ts";
+
+test("pending transcript mutations use the current view and deletion callback", async () => {
+ const source = readSrc("features/audio/transcript-gallery.tsx");
+ const tree = ts.createSourceFile(
+ "transcript-gallery.tsx",
+ source,
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX,
+ );
+ const component = tree.statements.find(
+ (node): node is ts.FunctionDeclaration =>
+ ts.isFunctionDeclaration(node) && node.name?.text === "TranscriptGallery",
+ );
+ assert.ok(component?.body);
+ const statements = [];
+ for (const statement of component.body.statements) {
+ if (ts.isReturnStatement(statement)) break;
+ statements.push(statement.getText(tree));
+ }
+ const { outputText } = ts.transpileModule(
+ statements.join("\n") + "\nreturn { mutate, refresh, setArchived };",
+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } },
+ );
+ for (const { initialView, nextView, removed } of [
+ { initialView: false, nextView: true, removed: ["deleted"] },
+ { initialView: true, nextView: false, removed: ["deleted"] },
+ { initialView: false, nextView: false, removed: ["deleted"] },
+ { initialView: false, nextView: true, removed: null },
+ ]) {
+ const state: unknown[] = [];
+ const refs: { current: unknown }[] = [];
+ const requests: boolean[] = [];
+ const deletions: unknown[] = [];
+ let stateIndex = 0;
+ let refIndex = 0;
+ const scope = {
+ active: true,
+ currentId: "deleted",
+ latest: null,
+ autoSelect: false,
+ onSelect: () => {},
+ onDelete: (ids: unknown) => deletions.push(["stale", ids]),
+ useState: (initial: unknown) => {
+ const index = stateIndex++;
+ if (!(index in state)) state[index] = initial;
+ return [
+ state[index],
+ (value: unknown) => {
+ state[index] = value;
+ },
+ ];
+ },
+ useRef: (initial: unknown) => refs[refIndex++] ??= { current: initial },
+ useCallback: (callback: unknown) => callback,
+ useLayoutEffect: (effect: () => void) => effect(),
+ useEffect: () => {},
+ listTranscripts: async (archived: boolean) => {
+ requests.push(archived);
+ return { transcripts: [{ id: String(archived) }], next_cursor: null };
+ },
+ toast: { error: (message: string) => assert.fail(message) },
+ };
+ const render = () => {
+ stateIndex = 0;
+ refIndex = 0;
+ return new Function(...Object.keys(scope), outputText)(
+ ...Object.values(scope),
+ );
+ };
+ render().setArchived(initialView);
+ const before = render();
+ let finish!: () => void;
+ const request = new Promise<void>((resolve) => {
+ finish = resolve;
+ });
+ const mutation = before.mutate(() => request, removed);
+ before.setArchived(nextView);
+ scope.onDelete = (ids: unknown) => deletions.push(["current", ids]);
+ if (removed === null) scope.currentId = "retained-archived";
+ const after = render();
+ await after.refresh();
+ finish();
+ await mutation;
+ assert.deepEqual(requests, [nextView, nextView]);
+ assert.deepEqual(state[0], [{ id: String(nextView) }]);
+ assert.deepEqual(deletions, [["current", removed]]);
+ }
+});
+
+test("a failed view switch does not leave the other view's rows on screen", async () => {
+ // `records`/`cursor` are written only by refresh's success path, so a rejected refresh
+ // used to leave the previous view's rows under the new heading, with the wrong cursor.
+ const source = readSrc("features/audio/transcript-gallery.tsx");
+ const tree = ts.createSourceFile(
+ "transcript-gallery.tsx",
+ source,
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX,
+ );
+ const component = tree.statements.find(
+ (node): node is ts.FunctionDeclaration =>
+ ts.isFunctionDeclaration(node) && node.name?.text === "TranscriptGallery",
+ );
+ assert.ok(component?.body);
+ const statements = [];
+ for (const statement of component.body.statements) {
+ if (ts.isReturnStatement(statement)) break;
+ statements.push(statement.getText(tree));
+ }
+ const { outputText } = ts.transpileModule(
+ statements.join("\n") + "\nreturn { refresh, setArchived };",
+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } },
+ );
+
+ const state: unknown[] = [];
+ const refs: { current: unknown }[] = [];
+ let stateIndex = 0;
+ let refIndex = 0;
+ let failNext = false;
+ const errors: string[] = [];
+ const scope = {
+ active: true,
+ currentId: null,
+ latest: null,
+ autoSelect: false,
+ onSelect: () => {},
+ onDelete: () => {},
+ useState: (initial: unknown) => {
+ const index = stateIndex++;
+ if (!(index in state)) state[index] = initial;
+ return [
+ state[index],
+ (value: unknown) => {
+ state[index] = value;
+ },
+ ];
+ },
+ useRef: (initial: unknown) => refs[refIndex++] ??= { current: initial },
+ useCallback: (callback: unknown) => callback,
+ useLayoutEffect: (effect: () => void) => effect(),
+ useEffect: () => {},
+ listTranscripts: async (archived: boolean) => {
+ if (failNext) throw new Error("Could not load transcripts.");
+ return {
+ transcripts: [{ id: String(archived) }],
+ next_cursor: `cursor-${archived}`,
+ };
+ },
+ toast: { error: (message: string) => errors.push(message) },
+ };
+ const render = () => {
+ stateIndex = 0;
+ refIndex = 0;
+ return new Function(...Object.keys(scope), outputText)(
+ ...Object.values(scope),
+ );
+ };
+
+ // History loads normally.
+ render().setArchived(false);
+ await render().refresh();
+ assert.deepEqual(state[0], [{ id: "false" }], "History rows should be loaded");
+ assert.equal(state[2], "cursor-false");
+
+ // Switch to Archived; that refresh fails.
+ failNext = true;
+ render().setArchived(true);
+ await render().refresh();
+
+ assert.deepEqual(errors, ["Could not load transcripts."]);
+ assert.deepEqual(
+ state[0],
+ [],
+ "the Archived view must not render the History rows it failed to replace",
+ );
+ assert.equal(
+ state[2],
+ null,
+ "the History cursor must not survive into the Archived view, or Load more mixes them",
+ );
+});
diff --git a/studio/frontend/tests/transcript-stream.test.ts b/studio/frontend/tests/transcript-stream.test.ts
new file mode 100644
index 00000000000..98c681291db
--- /dev/null
+++ b/studio/frontend/tests/transcript-stream.test.ts
@@ -0,0 +1,72 @@
+// 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 { readTranscriptStream } from "../src/features/audio/transcript-stream.ts";
+
+function stream(text: string, chunkSize = 3) {
+ const bytes = new TextEncoder().encode(text);
+ return new ReadableStream<Uint8Array>({
+ start(controller) {
+ for (let offset = 0; offset < bytes.length; offset += chunkSize)
+ controller.enqueue(bytes.slice(offset, offset + chunkSize));
+ controller.close();
+ },
+ });
+}
+
+test("transcription stream handles fragmented Unicode and retains the saved result", async () => {
+ const updates: string[] = [];
+ const result = await readTranscriptStream(
+ stream(
+ [
+ { type: "progress", text: "你好" },
+ { type: "heartbeat" },
+ {
+ type: "complete",
+ text: "你好 world",
+ model: "tiny",
+ record: { id: "saved" },
+ },
+ ]
+ .map((event) => JSON.stringify(event))
+ .join("\n"),
+ ),
+ (update) => updates.push(update.text),
+ );
+ assert.deepEqual(updates, ["你好"]);
+ assert.equal(result.text, "你好 world");
+ assert.equal(result.record?.id, "saved");
+});
+
+test("a broken stream does not treat partial text as a completed transcript", async () => {
+ await assert.rejects(
+ readTranscriptStream(
+ stream('{"type":"progress","text":"partial"}\n'),
+ () => {},
+ ),
+ /before the result arrived/,
+ );
+});
+
+test("server failures reach the caller", async () => {
+ await assert.rejects(
+ readTranscriptStream(
+ stream('{"type":"error","message":"Model unavailable"}\n'),
+ () => {},
+ ),
+ /Model unavailable/,
+ );
+});
+
+test("a failed save still delivers the complete transcript", async () => {
+ const result = await readTranscriptStream(
+ stream(
+ '{"type":"complete","text":"keep me","model":"tiny","record":null}\n',
+ ),
+ () => {},
+ );
+ assert.equal(result.text, "keep me");
+ assert.equal(result.record, null);
+});
diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rs
index 8a1910c691e..cc5a8ff09b4 100644
--- a/studio/src-tauri/src/main.rs
+++ b/studio/src-tauri/src/main.rs
@@ -988,13 +988,12 @@ fn confirm_quit_during_training(app: &tauri::AppHandle) -> bool {
.blocking_show()
}
-/// Renderer-only activity, mirrored here for the same reason: Hub downloads, which the
-/// backend runs but only the frontend tracks, and the Tauri shell self-update, which
-/// `update::is_update_running` stops covering once `downloadAndInstall` takes over.
+/// renderer-owned downloads, shell updates and unsaved transcripts must also protect native quit.
#[derive(Default)]
pub struct RendererActivity {
pub downloads: bool,
pub shell_update: bool,
+ pub unsaved_transcript: bool,
}
pub type RendererActivityState = std::sync::Arc<std::sync::Mutex<RendererActivity>>;
@@ -1009,6 +1008,7 @@ fn apply_renderer_activity(state: &RendererActivityState, kind: &str, active: bo
match kind {
"downloads" => activity.downloads = active,
"shell_update" => activity.shell_update = active,
+ "unsaved_transcript" => activity.unsaved_transcript = active,
// An unknown kind is a renderer/Rust mismatch, never a reason to flip a flag.
_ => {}
}
@@ -1029,10 +1029,28 @@ fn current_renderer_activity(app: &tauri::AppHandle) -> RendererActivity {
.map(|activity| RendererActivity {
downloads: activity.downloads,
shell_update: activity.shell_update,
+ unsaved_transcript: activity.unsaved_transcript,
})
.unwrap_or_default()
}
+fn confirm_quit_with_unsaved_transcript(app: &tauri::AppHandle) -> bool {
+ use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind};
+
+ if !current_renderer_activity(app).unsaved_transcript {
+ return true;
+ }
+ app.dialog()
+ .message("A transcript could not be saved. Download a copy before quitting to keep it.")
+ .kind(MessageDialogKind::Warning)
+ .title("Unsaved transcript")
+ .buttons(MessageDialogButtons::OkCancelCustom(
+ "Quit anyway".to_string(),
+ "Keep open".to_string(),
+ ))
+ .blocking_show()
+}
+
/// Ask before quitting mid shell update (true to proceed). request_quit only, as below.
fn confirm_quit_during_shell_update(app: &tauri::AppHandle) -> bool {
use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind};
@@ -1147,6 +1165,7 @@ fn quit_requires_confirmation(app: &tauri::AppHandle) -> bool {
install_is_active(app)
|| update_active
|| renderer.shell_update
+ || renderer.unsaved_transcript
|| training_is_active(app)
|| renderer.downloads
}
@@ -1514,6 +1533,7 @@ where
&& confirm_quit_during_update(&app)
&& confirm_quit_during_shell_update(&app)
&& confirm_quit_during_training(&app)
+ && confirm_quit_with_unsaved_transcript(&app)
&& confirm_quit_during_downloads(&app)
},
|| {
@@ -3104,27 +3124,38 @@ media-src 'self' https:"
assert!(hardened.ends_with("\nTryExec=/plain/app"));
}
- fn renderer_activity(state: &RendererActivityState) -> (bool, bool) {
+ // One element per field of RendererActivity: a narrower tuple is how a kind ships
+ // untested while a test named "each kind" still passes.
+ fn renderer_activity(state: &RendererActivityState) -> (bool, bool, bool) {
let activity = state
.lock()
.expect("the activity mutex must not be poisoned");
- (activity.downloads, activity.shell_update)
+ (
+ activity.downloads,
+ activity.shell_update,
+ activity.unsaved_transcript,
+ )
}
#[test]
fn renderer_activity_starts_clear_and_round_trips_each_kind() {
let state = new_renderer_activity_state();
- assert_eq!(renderer_activity(&state), (false, false));
+ assert_eq!(renderer_activity(&state), (false, false, false));
apply_renderer_activity(&state, "downloads", true);
- assert_eq!(renderer_activity(&state), (true, false));
+ assert_eq!(renderer_activity(&state), (true, false, false));
apply_renderer_activity(&state, "downloads", false);
- assert_eq!(renderer_activity(&state), (false, false));
+ assert_eq!(renderer_activity(&state), (false, false, false));
apply_renderer_activity(&state, "shell_update", true);
- assert_eq!(renderer_activity(&state), (false, true));
+ assert_eq!(renderer_activity(&state), (false, true, false));
apply_renderer_activity(&state, "shell_update", false);
- assert_eq!(renderer_activity(&state), (false, false));
+ assert_eq!(renderer_activity(&state), (false, false, false));
+
+ apply_renderer_activity(&state, "unsaved_transcript", true);
+ assert_eq!(renderer_activity(&state), (false, false, true));
+ apply_renderer_activity(&state, "unsaved_transcript", false);
+ assert_eq!(renderer_activity(&state), (false, false, false));
}
#[test]
@@ -3133,11 +3164,16 @@ media-src 'self' https:"
apply_renderer_activity(&state, "downloads", true);
apply_renderer_activity(&state, "shell_update", true);
- assert_eq!(renderer_activity(&state), (true, true));
+ apply_renderer_activity(&state, "unsaved_transcript", true);
+ assert_eq!(renderer_activity(&state), (true, true, true));
// Downloads finishing must not clear an update that is still installing.
apply_renderer_activity(&state, "downloads", false);
- assert_eq!(renderer_activity(&state), (false, true));
+ assert_eq!(renderer_activity(&state), (false, true, true));
+
+ // Nor must a saved transcript clear either of the other two.
+ apply_renderer_activity(&state, "unsaved_transcript", false);
+ assert_eq!(renderer_activity(&state), (false, true, false));
}
#[test]
@@ -3149,7 +3185,8 @@ media-src 'self' https:"
apply_renderer_activity(&state, "training", true);
apply_renderer_activity(&state, "", false);
apply_renderer_activity(&state, "Downloads", true);
- assert_eq!(renderer_activity(&state), (false, true));
+ apply_renderer_activity(&state, "unsaved-transcript", true);
+ assert_eq!(renderer_activity(&state), (false, true, false));
}
/// The three states the tray-toggle-server listener in use-tauri-backend.ts acts