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: archive audio clips (#9637)

Nilay448b17e2fc1c
diff --git a/studio/backend/core/inference/audio_gallery.py b/studio/backend/core/inference/audio_gallery.py
index d51a12aae62..77b5088445e 100644
--- a/studio/backend/core/inference/audio_gallery.py
+++ b/studio/backend/core/inference/audio_gallery.py
@@ -18,6 +18,7 @@ from collections.abc import Callable
from pathlib import Path
from typing import Any, Optional
+from core.inference import gallery_flags
from loggers import get_logger
from utils.paths import ensure_dir, studio_root
@@ -106,39 +107,66 @@ def _clip_bytes(audio_id: str) -> int:
def _prune_to_cap() -> int:
"""Drop the oldest owned pairs beyond the count or byte cap; return the count removed.
- Best-effort: a save must not fail because housekeeping did. Only Unsloth-owned pairs are
- considered, so a foreign or orphan wav is never destroyed.
+ Best-effort, so a save never fails on housekeeping. Only Unsloth-owned pairs are eligible,
+ archived clips are exempt, and an unreadable flag store skips the prune rather than guess.
"""
cap = _max_clips()
byte_cap = _max_bytes()
if cap <= 0 and byte_cap <= 0:
return 0
+ directory = gallery_dir()
+ removed = 0
try:
- entries = _list_audio_entries()
- except Exception: # noqa: BLE001 - never fail the save that triggered this
- return 0
-
- # Newest first, so the index where either budget runs out is the cut point. The newest
- # clip is always kept: it is the one the caller just generated, and dropping it would
- # make a single oversized request look like a silent failure.
- keep = len(entries) if cap <= 0 else min(cap, len(entries))
- if byte_cap > 0:
- running = 0
- for index, (record, _cursor) in enumerate(entries[:keep]):
- running += _clip_bytes(record["id"])
- if running > byte_cap and index > 0:
- keep = index
- break
- if keep >= len(entries):
+ # Select AND delete under one lock, as clear() does. Choosing victims from a snapshot and
+ # unlinking after it leaves a window where an archive lands and is deleted anyway.
+ with gallery_flags.exclusive(directory, require_file_lock = True):
+ entries = _list_audio_entries()
+
+ # Newest first, so the index where either budget runs out is the cut point. The newest
+ # is always kept: dropping what the caller just generated looks like a silent failure.
+ keep = len(entries) if cap <= 0 else min(cap, len(entries))
+ if byte_cap > 0:
+ running = 0
+ for index, (record, _cursor) in enumerate(entries[:keep]):
+ running += _clip_bytes(record["id"])
+ if running > byte_cap and index > 0:
+ keep = index
+ break
+ if keep >= len(entries):
+ return 0
+
+ # Re-read TRUSTED immediately before deleting: read() answers "nothing is archived"
+ # for a store it cannot parse, which here would drop the clips the shelf exists to
+ # keep. It also covers filesystems where the cross-process lock degrades to a no-op.
+ flags = gallery_flags.read_trusted(directory)
+ pruned: list[str] = []
+ for record, _cursor in entries[keep:]:
+ audio_id = record["id"]
+ if gallery_flags.is_archived(flags, audio_id):
+ continue
+ # Not delete(): it takes the flag lock on a second descriptor and would block here.
+ path = audio_path(audio_id)
+ if path is None or _read_meta(_sidecar_path(audio_id)) is None:
+ continue
+ try:
+ path.unlink()
+ except OSError as exc:
+ logger.warning("audio_gallery.delete_failed: %s", exc)
+ continue
+ removed += 1
+ pruned.append(audio_id)
+ try:
+ _sidecar_path(audio_id).unlink()
+ except OSError:
+ pass
+ if pruned:
+ gallery_flags.forget_locked(directory, pruned)
+ except gallery_flags.FlagsUnavailable:
+ logger.warning("audio_gallery.prune_skipped: the archive flags could not be read")
return 0
+ except Exception: # noqa: BLE001 - never fail the save that triggered this
+ return removed
- removed = 0
- for record, _cursor in entries[keep:]:
- try:
- if delete(record["id"]):
- removed += 1
- except Exception: # noqa: BLE001
- continue
if removed:
logger.info(
"audio_gallery.pruned: removed %d clip(s) over the %d clip / %d byte cap",
@@ -149,11 +177,18 @@ def _prune_to_cap() -> int:
return removed
-def _record(audio_id: str, meta: dict[str, Any]) -> dict[str, Any]:
+def _record(
+ audio_id: str,
+ meta: dict[str, Any],
+ flags: Optional[dict[str, dict[str, Any]]] = None,
+) -> dict[str, Any]:
+ if flags is None:
+ flags = gallery_flags.read(gallery_dir())
return {
**meta,
"id": audio_id,
"url": f"/api/inference/audio/gallery/{audio_id}/file",
+ "archived": gallery_flags.is_archived(flags, audio_id),
}
@@ -227,11 +262,14 @@ def _list_audio_entries(
*,
before: Optional[GalleryCursor] = None,
valid: Optional[Callable[[dict[str, Any]], bool]] = None,
+ archived: bool = False,
) -> list[tuple[dict[str, Any], GalleryCursor]]:
try:
paths = list(gallery_dir().glob("*.wav"))
except OSError:
return []
+ flags = gallery_flags.read(gallery_dir())
+ paths = [p for p in paths if gallery_flags.is_archived(flags, p.stem) == archived]
keyed_paths = [((_mtime(path), path.stem), path) for path in paths]
keyed_paths.sort(key = lambda item: item[0], reverse = True)
want = None if limit is None else offset + limit
@@ -242,7 +280,7 @@ def _list_audio_entries(
meta = _read_meta(_sidecar_path(path.stem))
if meta is None:
continue
- record = _record(path.stem, meta)
+ record = _record(path.stem, meta, flags)
if valid is not None and not valid(record):
continue
entries.append((record, cursor))
@@ -257,14 +295,20 @@ def list_audio(
*,
before: Optional[GalleryCursor] = None,
valid: Optional[Callable[[dict[str, Any]], bool]] = None,
+ archived: bool = False,
) -> list[dict[str, Any]]:
"""A newest-first window of clips for infinite scroll.
- Ordered by WAV mtime; only the window's sidecars are read, and a file without its
- pair is skipped. ``valid`` filters BEFORE pagination, so offset, limit and has_more
- all count over the accepted-record domain. ``before`` is an exclusive, stable cursor
- for callers that must tolerate deletions between pages."""
- return [record for record, _ in _list_audio_entries(limit, offset, before = before, valid = valid)]
+ Ordered by WAV mtime; a file without its pair is skipped. ``valid`` filters BEFORE pagination,
+ so offset, limit and has_more count over the accepted records. ``before`` is an exclusive,
+ stable cursor for callers that must tolerate deletions between pages, and ``archived`` picks
+ the shelf."""
+ return [
+ record
+ for record, _ in _list_audio_entries(
+ limit, offset, before = before, valid = valid, archived = archived
+ )
+ ]
def list_audio_page(
@@ -273,9 +317,22 @@ def list_audio_page(
*,
before: Optional[GalleryCursor] = None,
valid: Optional[Callable[[dict[str, Any]], bool]] = None,
+ archived: bool = False,
) -> list[tuple[dict[str, Any], GalleryCursor]]:
"""Return records with their stable pagination keys for the HTTP route."""
- return _list_audio_entries(limit, offset, before = before, valid = valid)
+ return _list_audio_entries(limit, offset, before = before, valid = valid, archived = archived)
+
+
+def set_flags(audio_id: str, *, archived: Optional[bool] = None) -> Optional[dict[str, Any]]:
+ """Archive or restore one owned clip; None when the id is not an Unsloth-owned clip."""
+ with gallery_flags.exclusive(gallery_dir()):
+ if owned_audio_path(audio_id) is None:
+ return None
+ gallery_flags.set_flags_locked(gallery_dir(), audio_id, archived = archived)
+ meta = _read_meta(_sidecar_path(audio_id))
+ if meta is None:
+ return None
+ return _record(audio_id, meta)
def delete(audio_id: str) -> bool:
@@ -298,28 +355,43 @@ def delete(audio_id: str) -> bool:
_sidecar_path(audio_id).unlink()
except OSError:
pass
+ gallery_flags.forget(gallery_dir(), [audio_id])
return True
-def clear() -> int:
- """Delete every Unsloth-owned pair (readable sidecar); return the count removed.
- Foreign and orphan WAVs are preserved, since list_audio already hides them."""
+def clear(include_archived: bool = False) -> int:
+ """Delete every Unsloth-owned pair (readable sidecar); return the count removed. Foreign and
+ orphan WAVs are preserved, since list_audio already hides them.
+
+ Archived clips are spared unless ``include_archived``, and sparing them raises
+ FlagsUnavailable when the flag store cannot be read."""
removed = 0
- try:
- paths = list(gallery_dir().glob("*.wav"))
- except OSError:
- return 0
- for path in paths:
- if _read_meta(_sidecar_path(path.stem)) is None:
- continue
- # wav first; if it cannot be unlinked, leave the sidecar so the clip stays listable
- try:
- path.unlink()
- except OSError:
- continue
- removed += 1
+ directory = gallery_dir()
+ with gallery_flags.exclusive(directory, require_file_lock = not include_archived):
+ flags = {} if include_archived else gallery_flags.read_trusted(directory)
try:
- _sidecar_path(path.stem).unlink()
+ paths = list(directory.glob("*.wav"))
except OSError:
- pass
+ return 0
+ cleared: list[str] = []
+ for path in paths:
+ if _read_meta(_sidecar_path(path.stem)) is None:
+ continue
+ if not include_archived and gallery_flags.is_archived(flags, path.stem):
+ continue
+ # wav first; if it cannot be unlinked, leave the sidecar so the clip stays listable
+ try:
+ path.unlink()
+ except OSError:
+ continue
+ removed += 1
+ cleared.append(path.stem)
+ try:
+ _sidecar_path(path.stem).unlink()
+ except OSError:
+ pass
+ if include_archived and not gallery_flags.is_trusted(directory):
+ gallery_flags.reset_locked(directory)
+ else:
+ gallery_flags.forget_locked(directory, cleared)
return removed
diff --git a/studio/backend/core/inference/gallery_flags.py b/studio/backend/core/inference/gallery_flags.py
index 69be6cc0148..c08ac6eb09d 100644
--- a/studio/backend/core/inference/gallery_flags.py
+++ b/studio/backend/core/inference/gallery_flags.py
@@ -171,13 +171,12 @@ def _save(directory: Path, data: dict[str, Any]) -> None:
@contextlib.contextmanager
def _file_lock(directory: Path):
"""Best-effort cross-process exclusive lock over one directory's store. Generation runs in
- subprocesses, so the in-process RLock alone would let two processes read the same JSON and
- clobber each other on ``os.replace``. Degrades to a no-op where OS locking is unavailable
- (the consequence is only a lost flag toggle)."""
+ subprocesses, so the in-process RLock alone would let two of them clobber each other on
+ ``os.replace``. Yields whether the OS lock was taken, so destructive callers can fail closed."""
try:
fd = os.open(str(directory / f"{_STORE_NAME}.lock"), os.O_CREAT | os.O_RDWR, 0o600)
except Exception:
- yield
+ yield False
return
locked = False
try:
@@ -191,7 +190,7 @@ def _file_lock(directory: Path):
locked = True
except Exception:
pass # locking unavailable; the thread lock still applies
- yield
+ yield locked
finally:
# Release only what was taken, and never let the release be the thing that fails the call.
# A filesystem that cannot lock usually cannot unlock either, and by this point the body
@@ -211,7 +210,7 @@ def _file_lock(directory: Path):
@contextlib.contextmanager
-def exclusive(directory: Path):
+def exclusive(directory: Path, *, require_file_lock: bool = False):
"""Hold the store's write lock across a read-then-act sequence.
``clear`` decides what to delete from a snapshot of the flags and then unlinks files, so an
@@ -219,7 +218,9 @@ def exclusive(directory: Path):
anyway -- after the PATCH had already told the user it was archived. Taking the same lock
``set_flags`` takes serializes the two.
"""
- with _lock, _file_lock(directory):
+ with _lock, _file_lock(directory) as file_locked:
+ if require_file_lock and not file_locked:
+ raise FlagsUnavailable(f"{_store_path(directory)} could not be locked")
yield
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 1f73bf47b48..c9551572d40 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -4297,6 +4297,11 @@ class AudioGalleryItem(BaseModel):
sample_rate: int
duration_s: float
created_at: str
+ archived: bool = Field(False, description = "Moved to the archived shelf, hidden from history")
+
+
+class AudioGalleryFlagsPatch(BaseModel):
+ archived: Optional[bool] = Field(None, description = "Archive (True) or restore (False) the clip")
class AudioGalleryListResponse(BaseModel):
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 7c8b7122d82..6111e0fc211 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -2721,6 +2721,7 @@ from models.inference import (
ImageGenerationData,
ImageGenerationResponse,
AudioSpeechRequest,
+ AudioGalleryFlagsPatch,
AudioGalleryItem,
AudioGalleryListResponse,
LoadResponse,
@@ -32322,6 +32323,7 @@ async def list_gallery_audio(
offset: int = 0,
before_mtime: Optional[float] = None,
before_id: Optional[str] = None,
+ archived: bool = False,
current_subject: str = Depends(get_current_subject),
):
from pydantic import ValidationError
@@ -32351,6 +32353,7 @@ async def list_gallery_audio(
offset,
before = before,
valid = _valid_gallery_audio,
+ archived = archived,
)
has_more = len(entries) > limit
visible = entries[:limit]
@@ -32384,6 +32387,24 @@ async def get_gallery_audio_file(
)
+@studio_router.patch("/audio/gallery/{audio_id}", response_model = AudioGalleryItem)
+async def update_gallery_audio_flags(
+ audio_id: str,
+ patch: AudioGalleryFlagsPatch,
+ current_subject: str = Depends(get_current_subject),
+):
+ from core.inference import audio_gallery
+
+ try:
+ record = await asyncio.to_thread(audio_gallery.set_flags, audio_id, archived = patch.archived)
+ except OSError as exc:
+ logger.warning("audio_gallery.set_flags_failed: %s", exc)
+ raise HTTPException(status_code = 500, detail = "Could not save the change to this clip.")
+ if record is None:
+ raise HTTPException(status_code = 404, detail = "Audio not found.")
+ return AudioGalleryItem(**record)
+
+
@studio_router.delete("/audio/gallery/{audio_id}")
async def delete_gallery_audio(audio_id: str, current_subject: str = Depends(get_current_subject)):
from core.inference import audio_gallery
@@ -32397,7 +32418,17 @@ async def delete_gallery_audio(audio_id: str, current_subject: str = Depends(get
@studio_router.delete("/audio/gallery")
async def clear_gallery_audio(current_subject: str = Depends(get_current_subject)):
from core.inference import audio_gallery
- removed = await asyncio.to_thread(audio_gallery.clear)
+ from core.inference.gallery_flags import FlagsUnavailable
+
+ try:
+ removed = await asyncio.to_thread(audio_gallery.clear)
+ except FlagsUnavailable as exc:
+ logger.warning("audio_gallery.clear_blocked: %s", exc)
+ raise HTTPException(
+ status_code = 503,
+ detail = "Could not read the gallery's archive data, so clearing was stopped to "
+ "avoid deleting archived clips.",
+ )
return {"removed": removed}
diff --git a/studio/backend/tests/test_audio_gallery.py b/studio/backend/tests/test_audio_gallery.py
index eff48fedb34..1eaed93d94f 100644
--- a/studio/backend/tests/test_audio_gallery.py
+++ b/studio/backend/tests/test_audio_gallery.py
@@ -319,3 +319,242 @@ def test_a_nonnumeric_cap_disables_pruning(monkeypatch):
assert audio_gallery._max_clips() == 5
monkeypatch.delenv("UNSLOTH_AUDIO_GALLERY_MAX_CLIPS")
assert audio_gallery._max_clips() == audio_gallery._DEFAULT_MAX_CLIPS
+
+
+# --- archive flags -----------------------------------------------------------------------
+
+
+def test_records_carry_default_archived_flag():
+ _save_with_mtime("a", 100.0)
+ assert gallery.list_audio()[0]["archived"] is False
+
+
+def test_archived_clips_leave_the_default_listing():
+ keep = _save_with_mtime("keep", 100.0)
+ shelved = _save_with_mtime("shelved", 200.0)
+ assert gallery.set_flags(shelved["id"], archived = True)["archived"] is True
+ assert [r["id"] for r in gallery.list_audio()] == [keep["id"]]
+ archived = gallery.list_audio(archived = True)
+ assert [r["id"] for r in archived] == [shelved["id"]]
+ assert archived[0]["archived"] is True
+
+
+def test_restoring_puts_a_clip_back_in_history():
+ record = _save_with_mtime("a", 100.0)
+ gallery.set_flags(record["id"], archived = True)
+ gallery.set_flags(record["id"], archived = False)
+ assert [r["id"] for r in gallery.list_audio()] == [record["id"]]
+ assert gallery.list_audio(archived = True) == []
+
+
+def test_archived_clips_do_not_consume_a_page_slot():
+ for i in range(4):
+ record = _save_with_mtime(f"a{i}", 100.0 + i)
+ if i % 2 == 0:
+ gallery.set_flags(record["id"], archived = True)
+ assert [r["prompt"] for r in gallery.list_audio(limit = 2)] == ["a3", "a1"]
+ assert [r["prompt"] for r in gallery.list_audio(archived = True)] == ["a2", "a0"]
+
+
+def test_archived_shelf_paginates_by_cursor():
+ records = [_save_with_mtime(prompt, float(i)) for i, prompt in enumerate("DCBA", 1)]
+ for record in records:
+ gallery.set_flags(record["id"], archived = True)
+ page1 = gallery.list_audio_page(limit = 2, archived = True)
+ assert [record["prompt"] for record, _ in page1] == ["A", "B"]
+ page2 = gallery.list_audio(limit = 2, before = page1[-1][1], archived = True)
+ assert [record["prompt"] for record in page2] == ["C", "D"]
+
+
+def test_set_flags_refuses_unowned_ids():
+ (gallery.gallery_dir() / "foreign.wav").write_bytes(_wav())
+ assert gallery.set_flags("foreign", archived = True) is None
+ assert gallery.set_flags("../../etc/passwd", archived = True) is None
+ assert gallery.set_flags("missing", archived = True) is None
+
+
+def test_delete_prunes_the_flag_entry():
+ from core.inference import gallery_flags
+
+ record = _save_with_mtime("a", 100.0)
+ gallery.set_flags(record["id"], archived = True)
+ assert gallery.delete(record["id"]) is True
+ assert gallery_flags.read(gallery.gallery_dir()) == {}
+
+
+def test_clear_spares_archived_clips():
+ active = _save_with_mtime("active", 100.0)
+ shelved = _save_with_mtime("shelved", 200.0)
+ gallery.set_flags(shelved["id"], archived = True)
+ assert gallery.clear() == 1
+ assert [r["id"] for r in gallery.list_audio(archived = True)] == [shelved["id"]]
+ assert gallery.audio_path(active["id"]) is None
+
+
+def test_clear_can_include_archived_clips():
+ from core.inference import gallery_flags
+
+ record = _save_with_mtime("shelved", 100.0)
+ gallery.set_flags(record["id"], archived = True)
+ assert gallery.clear(include_archived = True) == 1
+ assert gallery.list_audio(archived = True) == []
+ assert gallery_flags.read(gallery.gallery_dir()) == {}
+
+
+def test_clear_refuses_when_the_flag_store_cannot_be_read():
+ from core.inference import gallery_flags
+
+ record = _save_with_mtime("shelved", 100.0)
+ gallery.set_flags(record["id"], archived = True)
+ (gallery.gallery_dir() / ".flags.json").write_text("corrupt", encoding = "utf-8")
+ with pytest.raises(gallery_flags.FlagsUnavailable):
+ gallery.clear()
+ assert gallery.audio_path(record["id"]) is not None
+
+
+def test_clear_all_replaces_an_unreadable_store():
+ _save_with_mtime("a", 100.0)
+ (gallery.gallery_dir() / ".flags.json").write_text("corrupt", encoding = "utf-8")
+ assert gallery.clear(include_archived = True) == 1
+ _save_with_mtime("b", 200.0)
+ assert gallery.clear() == 1
+
+
+def test_prune_spares_archived_clips(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_AUDIO_GALLERY_MAX_CLIPS", "2")
+ shelved = _save_with_mtime("shelved", 100.0)
+ gallery.set_flags(shelved["id"], archived = True)
+ _save_with_mtime("b", 200.0)
+ _save_with_mtime("c", 300.0)
+ newest = gallery.save(_wav(), _meta(prompt = "d"))
+ assert gallery.audio_path(shelved["id"]) is not None
+ assert [r["prompt"] for r in gallery.list_audio()] == ["d", "c"]
+ assert gallery.audio_path(newest["id"]) is not None
+
+
+def test_flags_route_archives_and_restores():
+ from fastapi import HTTPException
+ from models.inference import AudioGalleryFlagsPatch
+ from routes.inference import update_gallery_audio_flags
+
+ record = gallery.save(_wav(), _meta())
+ archived = asyncio.run(
+ update_gallery_audio_flags(
+ record["id"], AudioGalleryFlagsPatch(archived = True), current_subject = "tester"
+ )
+ )
+ assert archived.archived is True
+ assert gallery.list_audio() == []
+ restored = asyncio.run(
+ update_gallery_audio_flags(
+ record["id"], AudioGalleryFlagsPatch(archived = False), current_subject = "tester"
+ )
+ )
+ assert restored.archived is False
+ with pytest.raises(HTTPException) as excinfo:
+ asyncio.run(
+ update_gallery_audio_flags(
+ "missing", AudioGalleryFlagsPatch(archived = True), current_subject = "tester"
+ )
+ )
+ assert excinfo.value.status_code == 404
+
+
+def test_clear_route_refuses_with_an_unreadable_store():
+ from fastapi import HTTPException
+ from routes.inference import clear_gallery_audio
+
+ record = gallery.save(_wav(), _meta())
+ gallery.set_flags(record["id"], archived = True)
+ (gallery.gallery_dir() / ".flags.json").write_text("corrupt", encoding = "utf-8")
+ with pytest.raises(HTTPException) as excinfo:
+ asyncio.run(clear_gallery_audio(current_subject = "tester"))
+ assert excinfo.value.status_code == 503
+ assert gallery.audio_path(record["id"]) is not None
+
+
+def test_prune_skips_when_the_flag_store_cannot_be_read(monkeypatch):
+ # The prune deletes on "not archived", so an unreadable store must stop it as it stops clear().
+ monkeypatch.setenv("UNSLOTH_AUDIO_GALLERY_MAX_CLIPS", "2")
+ shelved = _save_with_mtime("shelved", 100.0)
+ gallery.set_flags(shelved["id"], archived = True)
+ _save_with_mtime("b", 200.0)
+ _save_with_mtime("c", 300.0)
+ (gallery.gallery_dir() / ".flags.json").write_text("corrupt", encoding = "utf-8")
+ gallery.save(_wav(), _meta(prompt = "d"))
+ assert gallery.audio_path(shelved["id"]) is not None
+ # Nothing was pruned at all: the clips over the cap wait for a save that can read the store.
+ assert len(list(gallery.gallery_dir().glob("*.wav"))) == 4
+
+
+def test_prune_spares_a_clip_archived_after_its_snapshot(monkeypatch):
+ # The prune once picked victims from a listing and unlinked afterwards, so an archive landing
+ # in that window read as active from the stale snapshot and the clip was deleted anyway.
+ from core.inference import gallery_flags
+
+ doomed = _save_with_mtime("doomed", 100.0)
+ _save_with_mtime("b", 200.0)
+ _save_with_mtime("c", 300.0)
+
+ real = gallery._list_audio_entries
+ fired = []
+
+ def racing(*args, **kwargs):
+ entries = real(*args, **kwargs)
+ if not fired:
+ fired.append(True)
+ gallery_flags.set_flags_locked(gallery.gallery_dir(), doomed["id"], archived = True)
+ return entries
+
+ monkeypatch.setattr(gallery, "_list_audio_entries", racing)
+ # Capped only now, so the seeding saves do not prune `doomed` before the hook is in place.
+ monkeypatch.setenv("UNSLOTH_AUDIO_GALLERY_MAX_CLIPS", "2")
+ gallery.save(_wav(), _meta(prompt = "d"))
+
+ assert gallery.audio_path(doomed["id"]) is not None
+ assert [r["prompt"] for r in gallery.list_audio(archived = True)] == ["doomed"]
+
+
+def test_prune_stops_when_the_cross_process_lock_is_unavailable(monkeypatch):
+ import contextlib
+
+ from core.inference import gallery_flags
+
+ doomed = _save_with_mtime("doomed", 100.0)
+ _save_with_mtime("b", 200.0)
+ _save_with_mtime("c", 300.0)
+
+ @contextlib.contextmanager
+ def unlocked(_directory):
+ yield False
+
+ real_read = gallery_flags.read_trusted
+
+ def racing_read(directory):
+ flags = real_read(directory)
+ gallery_flags.set_flags_locked(directory, doomed["id"], archived = True)
+ return flags
+
+ monkeypatch.setattr(gallery_flags, "_file_lock", unlocked)
+ monkeypatch.setattr(gallery_flags, "read_trusted", racing_read)
+ monkeypatch.setenv("UNSLOTH_AUDIO_GALLERY_MAX_CLIPS", "2")
+ gallery.save(_wav(), _meta(prompt = "d"))
+
+ assert gallery.audio_path(doomed["id"]) is not None
+
+
+def test_clear_stops_when_the_cross_process_lock_is_unavailable(monkeypatch):
+ import contextlib
+
+ from core.inference import gallery_flags
+
+ record = _save_with_mtime("active", 100.0)
+
+ @contextlib.contextmanager
+ def unlocked(_directory):
+ yield False
+
+ monkeypatch.setattr(gallery_flags, "_file_lock", unlocked)
+ with pytest.raises(gallery_flags.FlagsUnavailable):
+ gallery.clear()
+ assert gallery.audio_path(record["id"]) is not None
diff --git a/studio/frontend/src/features/audio/api.ts b/studio/frontend/src/features/audio/api.ts
index 0920fa45294..52f55fda264 100644
--- a/studio/frontend/src/features/audio/api.ts
+++ b/studio/frontend/src/features/audio/api.ts
@@ -85,6 +85,7 @@ export interface AudioGalleryClip {
sample_rate: number;
duration_s: number;
created_at: string;
+ archived?: boolean;
}
export interface AudioGalleryListResponse {
@@ -98,16 +99,32 @@ export async function listAudioGallery(
offset: number,
limit: number,
before?: { mtime: number; id: string } | null,
+ archived = false,
): Promise<AudioGalleryListResponse> {
const cursor = before
? `&before_mtime=${encodeURIComponent(before.mtime)}&before_id=${encodeURIComponent(before.id)}`
: "";
const response = await authFetch(
- `/api/inference/audio/gallery?offset=${offset}&limit=${limit}${cursor}`,
+ `/api/inference/audio/gallery?offset=${offset}&limit=${limit}&archived=${archived}${cursor}`,
);
return parseJson<AudioGalleryListResponse>(response);
}
+export async function setAudioClipFlags(
+ id: string,
+ flags: { archived?: boolean },
+): Promise<AudioGalleryClip> {
+ const response = await authFetch(
+ `/api/inference/audio/gallery/${encodeURIComponent(id)}`,
+ {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(flags),
+ },
+ );
+ return parseJson<AudioGalleryClip>(response);
+}
+
export async function deleteAudioClip(id: string): Promise<void> {
const response = await authFetch(
`/api/inference/audio/gallery/${encodeURIComponent(id)}`,
diff --git a/studio/frontend/src/features/audio/audio-page-policy.ts b/studio/frontend/src/features/audio/audio-page-policy.ts
index 56984a3512c..8bfcba93178 100644
--- a/studio/frontend/src/features/audio/audio-page-policy.ts
+++ b/studio/frontend/src/features/audio/audio-page-policy.ts
@@ -303,11 +303,10 @@ export function mergeGalleryPage<T extends { id: string }>(
const oldestInPage = cached.findIndex(
(clip) => clip.id === page[page.length - 1].id,
);
- // No overlap with a non-empty cache means the page has moved past everything held, so
- // stitching would render a gap as contiguous and no cursor could ever reach it.
- if (oldestInPage === -1) {
- const overlaps = cached.some((clip) => inPage.has(clip.id));
- if (!overlaps && cached.length > 0) return { clips: [...page], stitched: false };
+ // Without that boundary the cache cannot prove where safe scrollback begins: an external archive
+ // can shift one unseen row into the page while every earlier row still overlaps.
+ if (oldestInPage === -1 && cached.length > 0) {
+ return { clips: [...page], stitched: false };
}
const scrollback = oldestInPage === -1 ? cached : cached.slice(oldestInPage + 1);
const tail = scrollback.filter(
diff --git a/studio/frontend/src/features/audio/audio-page.tsx b/studio/frontend/src/features/audio/audio-page.tsx
index 510a7476d52..d4f21fc8107 100644
--- a/studio/frontend/src/features/audio/audio-page.tsx
+++ b/studio/frontend/src/features/audio/audio-page.tsx
@@ -8,6 +8,7 @@
import { TestTubeOutlineIcon } from "@/lib/hugeicons-derived";
import {
+ Archive02Icon,
AudioWave01Icon,
Copy01Icon,
Delete02Icon,
@@ -84,9 +85,11 @@ import {
} from "@/features/settings/lib/stt-download-mirror";
import { sttModelSize } from "@/features/settings/stores/stt-model-catalog";
import { usePersistedToggle } from "@/hooks/use-persisted-toggle";
+import { useSettingsDialogStore } from "@/features/settings";
import { useScrollFades } from "@/hooks/use-scroll-fades";
import { fetchSystemInfo } from "@/hooks/use-system";
import { BlobUrlCache } from "@/lib/blob-url-cache";
+import { subscribeGalleryChanged } from "@/lib/gallery-flags";
import { subscribeModelLifecycle } from "@/lib/model-lifecycle-events";
import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
@@ -100,6 +103,7 @@ import {
getAudioDownloadPlan,
generateAudio,
listAudioGallery,
+ setAudioClipFlags,
} from "./api";
import {
type AudioBusy,
@@ -172,6 +176,8 @@ const HUB_TASKS_BY_MODE = {
} as const;
const PAGE_SIZE = 50;
+// The list route clamps a page to 200, so asking for more silently gets 200 back.
+const MAX_PAGE_SIZE = 200;
// Mirrors the STT sidecar's own limits (_MAX_AUDIO_SECONDS, STT_AUDIO_B64_MAX_CHARS), so a
// recording is stopped at the boundary rather than uploaded and refused.
const RECORDING_MAX_SECONDS = 30 * 60;
@@ -245,12 +251,14 @@ function ClipRowMenu({
onDownload,
onCopyPrompt,
onUseAsText,
+ onArchive,
onDelete,
}: {
clip: AudioGalleryClip;
onDownload: () => void;
onCopyPrompt: () => void;
onUseAsText: () => void;
+ onArchive: () => void;
onDelete: () => void;
}) {
return (
@@ -284,6 +292,10 @@ function ClipRowMenu({
<HugeiconsIcon icon={Download01Icon} className="size-4" />
Download WAV
</DropdownMenuItem>
+ <DropdownMenuItem onSelect={onArchive}>
+ <HugeiconsIcon icon={Archive02Icon} className="size-4" />
+ Archive
+ </DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive" onSelect={onDelete}>
<HugeiconsIcon icon={Delete02Icon} className="size-4" />
@@ -662,18 +674,29 @@ export function AudioPage({
}, []);
const refreshGallery = useCallback(
- async (removedId?: string): Promise<AudioGalleryClip[]> => {
+ async (
+ removedId?: string,
+ windowSize = PAGE_SIZE,
+ ): Promise<AudioGalleryClip[]> => {
const generation = ++galleryRefreshGeneration.current;
+ const wanted = Math.max(PAGE_SIZE, windowSize);
+ const asked = Math.min(wanted, MAX_PAGE_SIZE);
try {
- const page = await listAudioGallery(0, PAGE_SIZE);
+ const page = await listAudioGallery(0, asked);
// The caller's own fetch: a generation whose clip persisted must not be told otherwise.
if (generation !== galleryRefreshGeneration.current) return page.audio;
- const { clips: merged, stitched } = mergeGalleryPage(
- page.audio,
- galleryCache.clips,
- removedId,
- page.has_more,
- );
+ // A window past the route's cap cannot be covered in one page, and stitching the old
+ // scrollback back on keeps a cursor that starts BELOW it, stranding whatever was restored
+ // into the gap. Reset to what was fetched: shorter scrollback, nothing unreachable.
+ const { clips: merged, stitched } =
+ wanted > asked
+ ? { clips: [...page.audio], stitched: false }
+ : mergeGalleryPage(
+ page.audio,
+ galleryCache.clips,
+ removedId,
+ page.has_more,
+ );
galleryCache.clips = merged;
// A clip record carries no mtime, so kept scrollback has no cursor; keep the deeper one.
if (!stitched) {
@@ -729,13 +752,14 @@ export function AudioPage({
if (loadingMoreRef.current) return;
loadingMoreRef.current = true;
const refreshGeneration = galleryRefreshGeneration.current;
+ const cursor = galleryCache.nextCursor;
try {
- const page = await listAudioGallery(
- 0,
- PAGE_SIZE,
- galleryCache.nextCursor,
- );
- if (refreshGeneration !== galleryRefreshGeneration.current) return;
+ const page = await listAudioGallery(0, PAGE_SIZE, cursor);
+ if (
+ refreshGeneration !== galleryRefreshGeneration.current ||
+ cursor !== galleryCache.nextCursor
+ )
+ return;
galleryCache.nextCursor =
page.next_before_mtime !== null && page.next_before_id !== null
? { mtime: page.next_before_mtime, id: page.next_before_id }
@@ -761,7 +785,7 @@ export function AudioPage({
if (initialReadySent.current) {
void refreshStatus();
void refreshSttStatus();
- void refreshGallery();
+ void refreshGallery(undefined, galleryCache.clips.length);
return;
}
let cancelled = false;
@@ -803,6 +827,20 @@ export function AudioPage({
});
}, [active, refreshStatus, refreshSttStatus]);
+ useEffect(() => {
+ if (!active) return;
+ const refreshWhenVisible = () => {
+ if (document.hidden) return;
+ void refreshGallery(undefined, galleryCache.clips.length);
+ };
+ window.addEventListener("focus", refreshWhenVisible);
+ document.addEventListener("visibilitychange", refreshWhenVisible);
+ return () => {
+ window.removeEventListener("focus", refreshWhenVisible);
+ document.removeEventListener("visibilitychange", refreshWhenVisible);
+ };
+ }, [active, refreshGallery]);
+
// The selected clip needs its bytes before the player can play it.
useEffect(() => {
const clip = clips.find((c) => c.id === selectedId);
@@ -2126,23 +2164,24 @@ export function AudioPage({
// --- Gallery actions ----------------------------------------------------
+ const dropClip = useCallback((id: string) => {
+ galleryCache.srcById.delete(id);
+ setSrcById(galleryCache.srcById.toRecord());
+ // Drop the row now, as the clear-all path does: refreshGallery swallows a failed GET and
+ // returns the cache without setClips, leaving the row up against an already-revoked URL.
+ galleryCache.clips = galleryCache.clips.filter((clip) => clip.id !== id);
+ setClips(galleryCache.clips);
+ if (galleryCache.selectedId === id) {
+ galleryCache.selectedId = null;
+ setSelectedId(null);
+ }
+ }, []);
+
const handleDeleteClip = useCallback(
async (id: string) => {
try {
await deleteAudioClip(id);
- galleryCache.srcById.delete(id);
- setSrcById(galleryCache.srcById.toRecord());
- // Drop the row now, as the clear-all path does: refreshGallery swallows a failed
- // GET and returns the cache without calling setClips, which left the deleted clip
- // on screen against an object URL that has already been revoked.
- galleryCache.clips = galleryCache.clips.filter(
- (clip) => clip.id !== id,
- );
- setClips(galleryCache.clips);
- if (galleryCache.selectedId === id) {
- galleryCache.selectedId = null;
- setSelectedId(null);
- }
+ dropClip(id);
await refreshGallery(id);
} catch (error) {
toast.error(
@@ -2150,6 +2189,46 @@ export function AudioPage({
);
}
},
+ [dropClip, refreshGallery],
+ );
+
+ const handleArchiveClip = useCallback(
+ async (id: string) => {
+ try {
+ await setAudioClipFlags(id, { archived: true });
+ } catch (error) {
+ toast.error(
+ error instanceof Error ? error.message : "Could not archive the clip.",
+ );
+ return;
+ }
+ dropClip(id);
+ await refreshGallery(id);
+ const toastId = toast(
+ <button
+ type="button"
+ onClick={() => {
+ toast.dismiss(toastId);
+ useSettingsDialogStore.getState().openArchivedMedia("audio");
+ }}
+ className="w-full cursor-pointer text-left"
+ >
+ You can view archived audio in Settings
+ </button>,
+ { closeButton: true },
+ );
+ },
+ [dropClip, refreshGallery],
+ );
+
+ // This page stays mounted across route changes, so a restore from the Settings archive would not
+ // reach History until a reload. Refresh the loaded window, not just the first page: a clip
+ // re-enters at its own age, and the kept cursor already starts past anything below that page.
+ useEffect(
+ () =>
+ subscribeGalleryChanged("audio", () => {
+ void refreshGallery(undefined, galleryCache.clips.length);
+ }),
[refreshGallery],
);
@@ -2883,6 +2962,7 @@ export function AudioPage({
onUseAsText={() => {
if (transitionMode("speak")) setPrompt(clip.prompt);
}}
+ onArchive={() => void handleArchiveClip(clip.id)}
onDelete={() => void handleDeleteClip(clip.id)}
/>
</div>
diff --git a/studio/frontend/src/features/settings/components/archived-media-dialog.tsx b/studio/frontend/src/features/settings/components/archived-media-dialog.tsx
index b5436beef07..f3704b82965 100644
--- a/studio/frontend/src/features/settings/components/archived-media-dialog.tsx
+++ b/studio/frontend/src/features/settings/components/archived-media-dialog.tsx
@@ -1,12 +1,21 @@
// 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 { ArchiveRestoreIcon, Delete02Icon } from "@hugeicons/core-free-icons";
+import {
+ ArchiveRestoreIcon,
+ AudioWave01Icon,
+ Delete02Icon,
+} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { useCallback, useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
+import {
+ deleteAudioClip,
+ listAudioGallery,
+ setAudioClipFlags,
+} from "@/features/audio/api";
import {
deleteGalleryImage,
fetchGalleryObjectUrl,
@@ -35,7 +44,13 @@ const ARCHIVED_THUMB_BUDGET_BYTES = 32 * 1024 * 1024;
const THUMB_RETRY_LIMIT = 2;
const THUMB_RETRY_DELAY_MS = 750;
-export type ArchivedMediaKind = "images" | "videos";
+export type ArchivedMediaKind = "images" | "videos" | "audio";
+
+const NOUN: Record<ArchivedMediaKind, string> = {
+ images: "image",
+ videos: "video",
+ audio: "clip",
+};
/** The shape both galleries share, once flattened for this list. */
interface ArchivedRow {
@@ -47,6 +62,17 @@ interface ArchivedRow {
url: string;
}
+interface AudioCursor {
+ mtime: number;
+ id: string;
+}
+
+interface ArchivedPage {
+ rows: ArchivedRow[];
+ hasMore: boolean;
+ nextAudioCursor: AudioCursor | null;
+}
+
function formatCreatedAt(ms: number): string {
if (!Number.isFinite(ms)) return "";
return new Date(ms).toLocaleDateString(undefined, {
@@ -63,13 +89,16 @@ function formatCreatedAt(ms: number): string {
*/
export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
const isImages = kind === "images";
- const noun = isImages ? "image" : "video";
+ const isAudio = kind === "audio";
+ const noun = NOUN[kind];
+ const Noun = noun[0].toUpperCase() + noun.slice(1);
const [rows, setRows] = useState<ArchivedRow[]>([]);
// `showMore` reads the row count and the drop count from refs, not state: both can change while
// its request is in flight, and a stale closure is exactly what makes it skip a row. The ref is
// written with every list change rather than during render, so it is current the moment a drop
// lands instead of one render later.
const rowsRef = useRef<ArchivedRow[]>([]);
+ const audioCursor = useRef<AudioCursor | null>(null);
const mutations = useRef(0);
// Restores and deletes in flight. The counter above is an EDGE, so a page starting after it moves
// and landing before the row is dropped sees it hold still. A page applies only while this is zero.
@@ -92,7 +121,7 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
const [visible, setVisible] = useState<ReadonlySet<string>>(new Set());
const loadPage = useCallback(
- async (offset: number) => {
+ async (offset: number, before: AudioCursor | null = null): Promise<ArchivedPage> => {
if (isImages) {
const page = await getGallery(offset, ARCHIVED_PAGE_SIZE, true);
return {
@@ -103,6 +132,23 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
url: i.url,
})),
hasMore: page.has_more,
+ nextAudioCursor: null,
+ };
+ }
+ if (isAudio) {
+ const page = await listAudioGallery(0, ARCHIVED_PAGE_SIZE, before, true);
+ return {
+ rows: page.audio.map((a) => ({
+ id: a.id,
+ prompt: a.prompt,
+ createdAtMs: Date.parse(a.created_at),
+ url: a.url,
+ })),
+ hasMore: page.has_more,
+ nextAudioCursor:
+ page.next_before_mtime !== null && page.next_before_id !== null
+ ? { mtime: page.next_before_mtime, id: page.next_before_id }
+ : null,
};
}
const page = await getVideoGallery(offset, ARCHIVED_PAGE_SIZE, true);
@@ -114,9 +160,10 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
url: v.url,
})),
hasMore: page.has_more,
+ nextAudioCursor: null,
};
},
- [isImages],
+ [isImages, isAudio],
);
useEffect(() => {
@@ -127,6 +174,7 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
const page = await loadPage(0);
if (cancelled) return;
putRows(page.rows);
+ audioCursor.current = page.nextAudioCursor;
setHasMore(page.hasMore);
} catch (err) {
if (!cancelled) {
@@ -219,6 +267,7 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
};
}, []);
useEffect(() => {
+ if (isAudio) return;
let cancelled = false;
void (async () => {
for (const row of rows) {
@@ -285,7 +334,7 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
return () => {
cancelled = true;
};
- }, [rows, isImages, visible, retryTick]);
+ }, [rows, isImages, isAudio, visible, retryTick]);
// Drop a row, then top the page back up if that emptied it while more remain, so the list never
// dead-ends with rows still unreachable behind a hidden "Show more".
@@ -328,10 +377,11 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
pendingMutations.current += 1;
try {
if (isImages) await setGalleryImageFlags(row.id, { archived: false });
+ else if (isAudio) await setAudioClipFlags(row.id, { archived: false });
else await setGalleryVideoFlags(row.id, { archived: false });
dropRow(row.id, true);
pendingMutations.current -= 1;
- toast.success(`${isImages ? "Image" : "Video"} restored`);
+ toast.success(`${Noun} restored`);
} catch (err) {
pendingMutations.current -= 1;
toast.error(`Failed to restore ${noun}`, {
@@ -347,10 +397,11 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
pendingMutations.current += 1;
try {
if (isImages) await deleteGalleryImage(row.id);
+ else if (isAudio) await deleteAudioClip(row.id);
else await deleteGalleryVideo(row.id);
dropRow(row.id, false);
pendingMutations.current -= 1;
- toast.success(`${isImages ? "Image" : "Video"} deleted`);
+ toast.success(`${Noun} deleted`);
} catch (err) {
pendingMutations.current -= 1;
toast.error(`Failed to delete ${noun}`, {
@@ -363,16 +414,15 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
if (loadingMore.current) return;
loadingMore.current = true;
try {
- // Offset paging over a list the user can shorten. A restore or delete landing while this
- // request is in flight pulls every later row up by one, so the row at the old offset is
- // never returned by any page and becomes unreachable. Retry at the corrected offset when
- // that happens; the bound is only there so a burst of clicks cannot spin here.
+ // Images and videos page by offset over a shelf the user can shorten; audio uses its stable
+ // cursor. The same retry fence keeps locally mutated responses off every shelf.
for (let attempt = 0; attempt < 4; attempt += 1) {
const before = mutations.current;
- const page = await loadPage(rowsRef.current.length);
+ const page = await loadPage(rowsRef.current.length, audioCursor.current);
if (mutations.current !== before || pendingMutations.current > 0) continue;
const seen = new Set(rowsRef.current.map((r) => r.id));
putRows([...rowsRef.current, ...page.rows.filter((r) => !seen.has(r.id))]);
+ audioCursor.current = page.nextAudioCursor;
setHasMore(page.hasMore);
return;
}
@@ -418,8 +468,13 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
data-archived-id={row.id}
className="group flex items-center gap-4 border-b border-border/40 px-1 py-2.5 text-sm last:border-0"
>
- <span className="size-10 shrink-0 overflow-hidden rounded-md bg-muted/40">
- {thumbs[row.id] ? (
+ <span className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-md bg-muted/40">
+ {isAudio ? (
+ <HugeiconsIcon
+ icon={AudioWave01Icon}
+ className="size-4 text-muted-foreground"
+ />
+ ) : thumbs[row.id] ? (
isImages ? (
<img src={thumbs[row.id]} alt="" className="size-full object-cover" />
) : (
diff --git a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts b/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
index 17ec1772f98..776b76907f8 100644
--- a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
+++ b/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
@@ -32,7 +32,7 @@ export type SettingsScrollTarget =
| "chat-canvas-network";
/** Which archive the Data tab should open straight into. */
-export type ArchivedShelf = "chats" | "images" | "videos";
+export type ArchivedShelf = "chats" | "images" | "videos" | "audio";
interface OpenDialogOptions {
scrollTarget?: SettingsScrollTarget;
@@ -55,7 +55,7 @@ interface SettingsDialogState {
archivedRequested: ArchivedShelf | null;
openDialog: (tab?: SettingsTab, options?: OpenDialogOptions) => void;
openArchivedChats: () => void;
- openArchivedMedia: (shelf: "images" | "videos") => void;
+ openArchivedMedia: (shelf: Exclude<ArchivedShelf, "chats">) => void;
consumeArchivedChatsRequest: () => void;
consumeScrollTarget: (target: SettingsScrollTarget) => void;
closeDialog: () => void;
diff --git a/studio/frontend/src/features/settings/tabs/data-tab.tsx b/studio/frontend/src/features/settings/tabs/data-tab.tsx
index bf3af3333ef..8b9af949dad 100644
--- a/studio/frontend/src/features/settings/tabs/data-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/data-tab.tsx
@@ -70,7 +70,10 @@ import { HugeiconsIcon } from "@hugeicons/react";
import { useNavigate, useRouterState } from "@tanstack/react-router";
import { useEffect, useRef, useState } from "react";
import { ArchivedChatsView } from "../components/archived-chats-dialog";
-import { ArchivedMediaView } from "../components/archived-media-dialog";
+import {
+ type ArchivedMediaKind,
+ ArchivedMediaView,
+} from "../components/archived-media-dialog";
import { ManageChatsView } from "../components/manage-chats-view";
import { DocumentsRagSection } from "../components/documents-rag-section";
import { SettingsRow } from "../components/settings-row";
@@ -90,6 +93,7 @@ const SUBPAGE_FOR_SHELF = {
chats: "archived",
images: "archived-images",
videos: "archived-videos",
+ audio: "archived-audio",
} as const;
export function DataTab() {
@@ -106,7 +110,13 @@ export function DataTab() {
const [archiveConfirmOpen, setArchiveConfirmOpen] = useState(false);
// Subpages swap the Data tab body instead of opening nested dialogs.
const [subpage, setSubpage] = useState<
- "main" | "manage" | "archived" | "archived-images" | "archived-videos" | "files"
+ | "main"
+ | "manage"
+ | "archived"
+ | "archived-images"
+ | "archived-videos"
+ | "archived-audio"
+ | "files"
>(archivedRequested ? SUBPAGE_FOR_SHELF[archivedRequested] : "main");
const [count, setCount] = useState<number | null>(null);
const [exporting, setExporting] = useState(false);
@@ -559,8 +569,27 @@ export function DataTab() {
);
}
- if (subpage === "archived-images" || subpage === "archived-videos") {
- const isImages = subpage === "archived-images";
+ if (
+ subpage === "archived-images" ||
+ subpage === "archived-videos" ||
+ subpage === "archived-audio"
+ ) {
+ const kind: ArchivedMediaKind =
+ subpage === "archived-images"
+ ? "images"
+ : subpage === "archived-videos"
+ ? "videos"
+ : "audio";
+ const heading = {
+ images: t("settings.data.archivedImages"),
+ videos: t("settings.data.archivedVideos"),
+ audio: t("settings.data.archivedAudio"),
+ }[kind];
+ const description = {
+ images: t("settings.data.archivedImagesDescription"),
+ videos: t("settings.data.archivedVideosDescription"),
+ audio: t("settings.data.archivedAudioDescription"),
+ }[kind];
return (
<div className="flex flex-col gap-6">
<header className="flex items-center gap-2">
@@ -577,24 +606,13 @@ export function DataTab() {
</h1>
</header>
<div className="flex flex-col gap-1">
- <h2 className="text-sm font-semibold">
- {isImages
- ? t("settings.data.archivedImages")
- : t("settings.data.archivedVideos")}
- </h2>
- <p className="text-xs text-muted-foreground">
- {isImages
- ? t("settings.data.archivedImagesDescription")
- : t("settings.data.archivedVideosDescription")}
- </p>
+ <h2 className="text-sm font-semibold">{heading}</h2>
+ <p className="text-xs text-muted-foreground">{description}</p>
</div>
{/* Keyed by kind: switching shelves on an already-mounted tab otherwise keeps the
instance, and a showMore still awaiting the old shelf appends its rows to the new one,
which then drives restore and delete through the wrong media API. */}
- <ArchivedMediaView
- key={subpage}
- kind={isImages ? "images" : "videos"}
- />
+ <ArchivedMediaView key={subpage} kind={kind} />
</div>
);
}
@@ -754,6 +772,19 @@ export function DataTab() {
</Button>
</SettingsRow>
+ <SettingsRow
+ label={t("settings.data.archivedAudio")}
+ description={t("settings.data.archivedAudioDescription")}
+ >
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setSubpage("archived-audio")}
+ >
+ {t("settings.data.manageAction")}
+ </Button>
+ </SettingsRow>
+
<SettingsRow
label={t("settings.data.archiveAllChats")}
description={t("settings.data.archiveAllChatsDescription")}
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 02cd6374f4f..65361275383 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -1486,6 +1486,8 @@ export const ar = {
archivedImagesDescription: "اعرض الصور التي أرشفتها وأدرها.",
archivedVideos: "الفيديوهات المؤرشفة",
archivedVideosDescription: "اعرض الفيديوهات التي أرشفتها وأدرها.",
+ archivedAudio: "الصوتيات المؤرشفة",
+ archivedAudioDescription: "اعرض المقاطع الصوتية التي أرشفتها وأدرها.",
manageAction: "إدارة",
manageChats: "إدارة المحادثات",
manageChatsDescription:
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index a31da84298d..b3a17b8e380 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -1529,6 +1529,8 @@ export const de = {
archivedImagesDescription: "Bilder anzeigen und verwalten, die du archiviert hast.",
archivedVideos: "Archivierte Videos",
archivedVideosDescription: "Videos anzeigen und verwalten, die du archiviert hast.",
+ archivedAudio: "Archivierte Audioclips",
+ archivedAudioDescription: "Audioclips anzeigen und verwalten, die du archiviert hast.",
manageAction: "Verwalten",
manageChats: "Chats verwalten",
manageChatsDescription:
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index b7e1d657ae2..1715543fe07 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -1477,6 +1477,8 @@ export const en = {
archivedImagesDescription: "View and manage images you have archived.",
archivedVideos: "Archived videos",
archivedVideosDescription: "View and manage videos you have archived.",
+ archivedAudio: "Archived audio",
+ archivedAudioDescription: "View and manage audio clips you have archived.",
manageAction: "Manage",
manageChats: "Manage chats",
manageChatsDescription:
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 9ae3d2baf90..f7320158a07 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -1519,6 +1519,8 @@ export const es = {
archivedImagesDescription: "Consulta y gestiona las imágenes que has archivado.",
archivedVideos: "Vídeos archivados",
archivedVideosDescription: "Consulta y gestiona los vídeos que has archivado.",
+ archivedAudio: "Audio archivado",
+ archivedAudioDescription: "Consulta y gestiona los clips de audio que has archivado.",
manageAction: "Gestionar",
manageChats: "Gestionar chats",
manageChatsDescription:
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 8677a2d843d..a10d7ac6d6a 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -1527,6 +1527,8 @@ export const fr = {
archivedImagesDescription: "Consultez et gérez les images que vous avez archivées.",
archivedVideos: "Vidéos archivées",
archivedVideosDescription: "Consultez et gérez les vidéos que vous avez archivées.",
+ archivedAudio: "Audio archivé",
+ archivedAudioDescription: "Consultez et gérez les clips audio que vous avez archivés.",
manageAction: "Gérer",
manageChats: "Gérer les discussions",
manageChatsDescription:
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 86300226262..fc72c8106f5 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -1492,6 +1492,8 @@ export const hi = {
archivedImagesDescription: "आपके द्वारा संग्रहित की गई छवियाँ देखें और प्रबंधित करें।",
archivedVideos: "संग्रहित वीडियो",
archivedVideosDescription: "आपके द्वारा संग्रहित किए गए वीडियो देखें और प्रबंधित करें।",
+ archivedAudio: "संग्रहित ऑडियो",
+ archivedAudioDescription: "आपके द्वारा संग्रहित किए गए ऑडियो क्लिप देखें और प्रबंधित करें।",
manageAction: "प्रबंधित करें",
manageChats: "चैट प्रबंधित करें",
manageChatsDescription:
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 4001e1b88d5..c16df90eb32 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -1492,6 +1492,8 @@ export const it = {
archivedImagesDescription: "Visualizza e gestisci le immagini che hai archiviato.",
archivedVideos: "Video archiviati",
archivedVideosDescription: "Visualizza e gestisci i video che hai archiviato.",
+ archivedAudio: "Audio archiviati",
+ archivedAudioDescription: "Visualizza e gestisci le clip audio che hai archiviato.",
manageAction: "Gestisci",
manageChats: "Gestisci chat",
manageChatsDescription:
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index be6bd67e8f2..623d793cc6b 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -1461,6 +1461,8 @@ export const ja = {
archivedImagesDescription: "アーカイブした画像を表示・管理します。",
archivedVideos: "アーカイブ済み動画",
archivedVideosDescription: "アーカイブした動画を表示・管理します。",
+ archivedAudio: "アーカイブした音声",
+ archivedAudioDescription: "アーカイブした音声クリップを表示・管理します。",
manageAction: "管理",
manageChats: "チャットを管理",
manageChatsDescription:
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 1439bd4618f..b2e81f482e2 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -1483,6 +1483,8 @@ export const ko = {
archivedImagesDescription: "보관한 이미지를 확인하고 관리합니다.",
archivedVideos: "보관된 동영상",
archivedVideosDescription: "보관한 동영상을 확인하고 관리합니다.",
+ archivedAudio: "보관된 오디오",
+ archivedAudioDescription: "보관한 오디오 클립을 확인하고 관리합니다.",
manageAction: "관리",
manageChats: "채팅 관리",
manageChatsDescription:
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 220e0ffdc2a..c5d07a4a457 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -1504,6 +1504,8 @@ export const ptBR = {
archivedImagesDescription: "Veja e gerencie as imagens que você arquivou.",
archivedVideos: "Vídeos arquivados",
archivedVideosDescription: "Veja e gerencie os vídeos que você arquivou.",
+ archivedAudio: "Áudios arquivados",
+ archivedAudioDescription: "Veja e gerencie os clipes de áudio que você arquivou.",
manageAction: "Gerenciar",
manageChats: "Gerenciar chats",
manageChatsDescription:
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index eb0b4fda471..e3e3be3f37b 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -1501,6 +1501,8 @@ export const ru = {
archivedImagesDescription: "Просмотр и управление изображениями, которые вы архивировали.",
archivedVideos: "Архивные видео",
archivedVideosDescription: "Просмотр и управление видео, которые вы архивировали.",
+ archivedAudio: "Архивированные аудио",
+ archivedAudioDescription: "Просмотр и управление аудиоклипами, которые вы архивировали.",
manageAction: "Управлять",
manageChats: "Управление чатами",
manageChatsDescription:
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 851bcf2f540..dcacd0fb1bb 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -1452,6 +1452,8 @@ export const zhCN = {
archivedImagesDescription: "查看和管理你归档的图片。",
archivedVideos: "已归档的视频",
archivedVideosDescription: "查看和管理你归档的视频。",
+ archivedAudio: "已归档的音频",
+ archivedAudioDescription: "查看和管理你归档的音频片段。",
manageAction: "管理",
manageChats: "管理聊天",
manageChatsDescription: "选择多个聊天进行移动、置顶、归档、导出或删除。",
diff --git a/studio/frontend/src/lib/gallery-flags.ts b/studio/frontend/src/lib/gallery-flags.ts
index 1bebcb7879c..6c33345217d 100644
--- a/studio/frontend/src/lib/gallery-flags.ts
+++ b/studio/frontend/src/lib/gallery-flags.ts
@@ -12,7 +12,7 @@
export const GALLERY_CHANGED_EVENT = "unsloth:gallery-changed";
/** Which gallery a change landed in. */
-export type GalleryKind = "images" | "videos";
+export type GalleryKind = "images" | "videos" | "audio";
/**
* Announce that a gallery changed from OUTSIDE the page that owns it. Both pages are mounted
diff --git a/studio/frontend/tests/audio-generation-stop.test.ts b/studio/frontend/tests/audio-generation-stop.test.ts
index 77e451eee0a..8ee8bca4b00 100644
--- a/studio/frontend/tests/audio-generation-stop.test.ts
+++ b/studio/frontend/tests/audio-generation-stop.test.ts
@@ -86,7 +86,20 @@ test("deleting a clip drops the row without waiting on the refresh", () => {
// the deleted row on screen against an already-revoked object URL.
assert.match(
source,
- /await deleteAudioClip\(id\);[\s\S]*galleryCache\.clips = galleryCache\.clips\.filter\([\s\S]*setClips\(galleryCache\.clips\);/,
+ /const dropClip = useCallback\(\(id: string\) => \{[\s\S]*galleryCache\.clips = galleryCache\.clips\.filter\([\s\S]*setClips\(galleryCache\.clips\);/,
+ );
+ assert.match(
+ source,
+ /await deleteAudioClip\(id\);\s*dropClip\(id\);\s*await refreshGallery\(id\);/,
+ );
+});
+
+test("archiving a clip drops the row the same way a delete does", () => {
+ // Same revoked-object-URL trap: the clip is gone server-side, so a row left up until a refresh
+ // that may fail renders a tile that can no longer play.
+ assert.match(
+ source,
+ /await setAudioClipFlags\(id, \{ archived: true \}\);[\s\S]*?dropClip\(id\);\s*await refreshGallery\(id\);/,
);
});
diff --git a/studio/frontend/tests/audio-page-policy.test.ts b/studio/frontend/tests/audio-page-policy.test.ts
index a3aeaf1cd16..5861c7ce532 100644
--- a/studio/frontend/tests/audio-page-policy.test.ts
+++ b/studio/frontend/tests/audio-page-policy.test.ts
@@ -330,7 +330,7 @@ test("file transcription cannot overlap a pending microphone permission", () =>
test("gallery refresh preserves fallback selection and pagination identity", () => {
assert.match(
audioPageSource,
- /const generation = \+\+galleryRefreshGeneration\.current;[\s\S]*listAudioGallery\(0, PAGE_SIZE\);[\s\S]*if \(generation !== galleryRefreshGeneration\.current\) return/,
+ /const generation = \+\+galleryRefreshGeneration\.current;[\s\S]*listAudioGallery\(\s*0,[\s\S]*if \(generation !== galleryRefreshGeneration\.current\) return/,
);
assert.match(
audioPageSource,
@@ -420,7 +420,7 @@ test("a clip this client deleted leaves the merged gallery", () => {
test("the selection only moves when its clip left the merged gallery", () => {
assert.match(
audioPageSource,
- /const \{ clips: merged, stitched \} = mergeGalleryPage\([\s\S]*!merged\.some\(\(c\) => c\.id === galleryCache\.selectedId\)/,
+ /const \{ clips: merged, stitched \} =[\s\S]*mergeGalleryPage\([\s\S]*!merged\.some\(\(c\) => c\.id === galleryCache\.selectedId\)/,
);
// Play an older clip, delete another, and the player must not jump to the newest.
assert.doesNotMatch(
@@ -460,6 +460,15 @@ test("a cache with nothing in common with the page is dropped, not stitched", ()
assert.deepEqual(merged, { clips: [{ id: "z" }, { id: "y" }], stitched: false });
});
+test("a refresh resets when an external archive moves the page boundary", () => {
+ const cached = Array.from({ length: 50 }, (_, i) => ({ id: `c${i}` }));
+ const page = [...cached.slice(0, 5), ...cached.slice(6), { id: "c50" }];
+ assert.deepEqual(mergeGalleryPage(page, cached, undefined, true), {
+ clips: page,
+ stitched: false,
+ });
+});
+
test("the recorder is gated on the same capability check the composer uses", () => {
// Safari ships no MediaRecorder, and an http LAN origin (-H 0.0.0.0) is not a
// secure context, so navigator.mediaDevices is undefined there. Without this
@@ -609,3 +618,78 @@ test("generation is claimed before the transcribe release is awaited", () => {
/if \(releaseInFlight && !\(await releaseInFlight\)\) \{\s*busyRef\.current = null;\s*setBusy\(null\);\s*setMode\("transcribe"\);/,
);
});
+
+test("a restore refreshes the loaded window, not just the first page", () => {
+ // A restored clip re-enters History at its own age, so past the first page it lands below it.
+ // Refreshing only that page left it out of the strip AND unreachable, since the kept cursor
+ // starts below the loaded window.
+ const shelf = Array.from({ length: 120 }, (_, i) => ({ id: `c${i}` }));
+ const loaded = shelf.slice(0, 100);
+ const restored = { id: "restored" };
+ const afterRestore = [...shelf.slice(0, 70), restored, ...shelf.slice(70)];
+
+ const firstPageOnly = mergeGalleryPage(afterRestore.slice(0, 50), loaded, undefined, true);
+ assert.equal(
+ firstPageOnly.clips.some((clip) => clip.id === "restored"),
+ false,
+ );
+
+ const wholeWindow = mergeGalleryPage(
+ afterRestore.slice(0, loaded.length),
+ loaded,
+ undefined,
+ true,
+ );
+ assert.equal(
+ wholeWindow.clips.some((clip) => clip.id === "restored"),
+ true,
+ );
+ // Still contiguous: the row the longer page pushed out is stitched back on, not dropped.
+ assert.deepEqual(wholeWindow.clips, [...afterRestore.slice(0, 100), shelf[99]]);
+});
+
+test("the gallery-changed subscription asks for the window that is loaded", () => {
+ assert.match(
+ audioPageSource,
+ /subscribeGalleryChanged\("audio", \(\) => \{\s*void refreshGallery\(undefined, galleryCache\.clips\.length\);/,
+ );
+ assert.match(
+ audioPageSource,
+ /const wanted = Math\.max\(PAGE_SIZE, windowSize\);\s*const asked = Math\.min\(wanted, MAX_PAGE_SIZE\);/,
+ );
+});
+
+test("reactivating audio asks for the window that is loaded", () => {
+ assert.match(
+ audioPageSource,
+ /if \(initialReadySent\.current\) \{\s*void refreshStatus\(\);\s*void refreshSttStatus\(\);\s*void refreshGallery\(undefined, galleryCache\.clips\.length\);\s*return;\s*\}/,
+ );
+});
+
+test("returning to a visible audio tab refreshes the loaded window", () => {
+ assert.match(
+ audioPageSource,
+ /const refreshWhenVisible = \(\) => \{\s*if \(document\.hidden\) return;\s*void refreshGallery\(undefined, galleryCache\.clips\.length\);\s*\};\s*window\.addEventListener\("focus", refreshWhenVisible\);\s*document\.addEventListener\("visibilitychange", refreshWhenVisible\);/,
+ );
+ assert.match(
+ audioPageSource,
+ /window\.removeEventListener\("focus", refreshWhenVisible\);\s*document\.removeEventListener\("visibilitychange", refreshWhenVisible\);/,
+ );
+});
+
+test("a window past the route cap resets the strip instead of stranding the restore", () => {
+ // Asking for more than the route returns leaves the middle of the window unfetched, and keeping
+ // the old scrollback keeps a cursor starting BELOW that middle, so a clip restored into it is
+ // in neither the merged list nor any page still reachable.
+ assert.match(
+ audioPageSource,
+ /wanted > asked\s*\?\s*\{ clips: \[\.\.\.page\.audio\], stitched: false \}\s*:\s*mergeGalleryPage\(/,
+ );
+});
+
+test("a capped restore refresh invalidates a page fetched from the older cursor", () => {
+ assert.match(
+ audioPageSource,
+ /const cursor = galleryCache\.nextCursor;\s*try\s*{\s*const page = await listAudioGallery\(\s*0,\s*PAGE_SIZE,\s*cursor,?\s*\);\s*if \(\s*refreshGeneration !== galleryRefreshGeneration\.current \|\|\s*cursor !== galleryCache\.nextCursor\s*\)\s*return;/,
+ );
+});
diff --git a/studio/frontend/tests/gallery-flags.test.ts b/studio/frontend/tests/gallery-flags.test.ts
index 3f3a0721045..a3ba71eda0c 100644
--- a/studio/frontend/tests/gallery-flags.test.ts
+++ b/studio/frontend/tests/gallery-flags.test.ts
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
import test from "node:test";
import {
@@ -28,6 +29,14 @@ const item = (id: string, created_at: number | string, pinned = false) => ({
const ids = (items: { id: string }[]) => items.map((i) => i.id);
+const archivedMediaSource = readFileSync(
+ new URL(
+ "../src/features/settings/components/archived-media-dialog.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+);
+
test("unpinned items sort newest first", () => {
const items = [item("old", 1), item("new", 3), item("mid", 2)];
assert.deepEqual(ids(sortGalleryItems(items)), ["new", "mid", "old"]);
@@ -474,3 +483,14 @@ test("a page fetch is refused while a shelf mutation is still pending", async ()
assert.ok(result);
assert.deepEqual(result.page, ["c", "b"], "the retry, once nothing is pending, recovers it");
});
+
+test("archived audio pages from the stable server cursor", () => {
+ assert.match(
+ archivedMediaSource,
+ /listAudioGallery\(\s*0,\s*ARCHIVED_PAGE_SIZE,\s*before,\s*true,?\s*\)/,
+ );
+ assert.match(
+ archivedMediaSource,
+ /const page = await loadPage\(\s*rowsRef\.current\.length,\s*audioCursor\.current,?\s*\);[\s\S]*audioCursor\.current = page\.nextAudioCursor;/,
+ );
+});
diff --git a/studio/frontend/tests/reload-snapshot.test.ts b/studio/frontend/tests/reload-snapshot.test.ts
index 7f9b2dd73a3..e4cfb945f35 100644
--- a/studio/frontend/tests/reload-snapshot.test.ts
+++ b/studio/frontend/tests/reload-snapshot.test.ts
@@ -915,7 +915,8 @@ test("media pages retire the shell only after gallery and preview hydration", ()
);
assert.match(
audioPageSource,
- /if \(initialReadySent\.current\) \{\s*void refreshStatus\(\);\s*void refreshSttStatus\(\);\s*void refreshGallery\(\)/,
+ // audio-page-policy.test.ts pins the argument list: reactivation asks for the loaded window.
+ /if \(initialReadySent\.current\) \{\s*void refreshStatus\(\);\s*void refreshSttStatus\(\);\s*void refreshGallery\(/,
);
assert.match(
audioPageSource,
diff --git a/studio/frontend/tests/settings-deep-open-requests.test.ts b/studio/frontend/tests/settings-deep-open-requests.test.ts
index b066229cf08..019aa1da18a 100644
--- a/studio/frontend/tests/settings-deep-open-requests.test.ts
+++ b/studio/frontend/tests/settings-deep-open-requests.test.ts
@@ -70,6 +70,14 @@ test("reopening on Data does not drop a deep-open still in flight", () => {
assert.equal(store.getState().archivedRequested, "images");
});
+test("the audio shelf deep-opens like the other media shelves", () => {
+ reset();
+ store.getState().openArchivedMedia("audio");
+ assert.equal(store.getState().open, true);
+ assert.equal(store.getState().activeTab, "data");
+ assert.equal(store.getState().archivedRequested, "audio");
+});
+
test("consuming it clears it, so a later visit to Data is an ordinary one", () => {
reset();
store.getState().openArchivedChats();