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: pin, reorder and add to project for Audio history (#11774)

Michael Hanb5100c1d9cb9
diff --git a/studio/backend/core/inference/audio_gallery.py b/studio/backend/core/inference/audio_gallery.py
index 0ee9e0cae1a..a5e58c46607 100644
--- a/studio/backend/core/inference/audio_gallery.py
+++ b/studio/backend/core/inference/audio_gallery.py
@@ -110,7 +110,7 @@ def _prune_to_cap() -> int:
"""Drop the oldest owned pairs beyond the count or byte cap; return the count removed.
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.
+ archived and pinned clips are exempt, and an unreadable flag store skips the prune rather than guess.
"""
cap = _max_clips()
byte_cap = _max_bytes()
@@ -122,7 +122,9 @@ def _prune_to_cap() -> int:
# 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()
+ # By age, not display order: a clip dragged down is not older. Pinned clips are exempt.
+ entries = [e for e in _list_audio_entries() if not e[0].get("pinned")]
+ entries.sort(key = lambda e: _mtime(gallery_dir() / f"{e[0]['id']}.wav"), reverse = True)
# 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.
@@ -144,7 +146,9 @@ def _prune_to_cap() -> int:
pruned: list[str] = []
for record, _cursor in entries[keep:]:
audio_id = record["id"]
- if gallery_flags.is_archived(flags, audio_id):
+ if gallery_flags.is_archived(flags, audio_id) or gallery_flags.pin_rank(
+ flags, audio_id
+ ) > float("-inf"):
continue
path = audio_path(audio_id)
if path is None or _read_meta(_sidecar_path(audio_id)) is None:
@@ -189,7 +193,11 @@ def _record(
**meta,
"id": audio_id,
"url": f"/api/inference/audio/gallery/{audio_id}/file",
- "archived": gallery_flags.is_archived(flags, audio_id),
+ **gallery_flags.flags_for(flags, audio_id),
+ # The listing's own sort key, so a client re-sort agrees with it.
+ "order_at": gallery_flags.order_rank(
+ flags, audio_id, _mtime(gallery_dir() / f"{audio_id}.wav")
+ ),
}
@@ -253,7 +261,21 @@ def _mtime(path: Path) -> float:
return 0.0
-GalleryCursor = tuple[float, str]
+# (pin rank, order key, id), newest first; an unpinned clip's pin rank is -inf.
+GalleryCursor = tuple[float, float, str]
+
+
+def pin_rank(audio_id: str) -> float:
+ """The clip's current pin rank (-inf if unpinned), for a cursor sent without one."""
+ return gallery_flags.pin_rank(gallery_flags.read(gallery_dir()), audio_id)
+
+
+def _sort_key(flags: dict[str, dict[str, Any]], path: Path) -> GalleryCursor:
+ return (
+ gallery_flags.pin_rank(flags, path.stem),
+ gallery_flags.order_rank(flags, path.stem, _mtime(path)),
+ path.stem,
+ )
def _list_audio_entries(
@@ -270,7 +292,7 @@ def _list_audio_entries(
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(flags, path), path) for path in paths]
keyed_paths.sort(key = lambda item: item[0], reverse = True)
want = None if limit is None else offset + limit
entries = []
@@ -297,9 +319,9 @@ def list_audio(
valid: Optional[Callable[[dict[str, Any]], bool]] = None,
archived: bool = False,
) -> list[dict[str, Any]]:
- """A newest-first window of clips for infinite scroll.
+ """A window of clips for infinite scroll: pinned first, then newest first.
- Ordered by WAV mtime; a file without its pair is skipped. ``valid`` filters BEFORE pagination,
+ Ordered by pin, then the drag key or 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."""
@@ -323,12 +345,45 @@ def list_audio_page(
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."""
+def set_flags(
+ audio_id: str,
+ *,
+ pinned: Optional[bool] = None,
+ archived: Optional[bool] = None,
+) -> Optional[dict[str, Any]]:
+ """Pin or archive 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, pinned = pinned, archived = archived)
+ meta = _read_meta(_sidecar_path(audio_id))
+ if meta is None:
+ return None
+ return _record(audio_id, meta)
+
+
+def move(audio_id: str, after_id: Optional[str]) -> Optional[dict[str, Any]]:
+ """Move an active clip to just after ``after_id`` (None = front) and return its record.
+
+ None if the id is not an owned, active clip. Raises KeyError if ``after_id`` is not in history."""
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)
+ flags = gallery_flags.read(gallery_dir())
+ if gallery_flags.is_archived(flags, audio_id):
+ return None
+ # The whole shelf in listing order, so neighbours past the client's loaded window are known.
+ try:
+ paths = [
+ p
+ for p in gallery_dir().glob("*.wav")
+ if not gallery_flags.is_archived(flags, p.stem)
+ ]
+ except OSError:
+ paths = []
+ paths.sort(key = lambda p: _sort_key(flags, p), reverse = True)
+ keyed = [(p.stem, _mtime(p)) for p in paths]
+ gallery_flags.place_locked(gallery_dir(), audio_id, keyed, after_id = after_id)
meta = _read_meta(_sidecar_path(audio_id))
if meta is None:
return None
diff --git a/studio/backend/core/inference/gallery_projects.py b/studio/backend/core/inference/gallery_projects.py
index 39a24061ebc..e7efd1bc709 100644
--- a/studio/backend/core/inference/gallery_projects.py
+++ b/studio/backend/core/inference/gallery_projects.py
@@ -3,7 +3,7 @@
"""Copy a gallery image or clip into a chat project's folder.
-Files land in ``<project root>/sandbox/{images,videos}``, where the project's chats run their
+Files land in ``<project root>/sandbox/{images,videos,audio}``, where the project's chats run their
tools. It is a copy, so the gallery keeps its item.
"""
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 25d66f47c58..4473b6c5f04 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -4698,20 +4698,28 @@ class AudioGalleryItem(BaseModel):
sample_rate: int
duration_s: float
created_at: str
+ pinned: bool = Field(False, description = "Pinned to the top of history")
archived: bool = Field(False, description = "Moved to the archived shelf, hidden from history")
+ order_at: Optional[float] = Field(
+ None,
+ description = "Unpinned sort key (epoch-second scale): the manual key once dragged, else the file mtime",
+ )
class AudioGalleryFlagsPatch(BaseModel):
+ pinned: Optional[bool] = Field(None, description = "Pin (True) or unpin (False) the clip")
archived: Optional[bool] = Field(None, description = "Archive (True) or restore (False) the clip")
class AudioGalleryListResponse(BaseModel):
- """A newest-first window of the audio gallery for infinite scroll."""
+ """A window of the audio gallery for infinite scroll: pinned first, then newest first."""
audio: List[AudioGalleryItem] = Field(default_factory = list)
has_more: bool = False
+ # Cursor: the last clip's order key (mtime unless dragged), id, and pin rank (None if unpinned).
next_before_mtime: Optional[float] = None
next_before_id: Optional[str] = None
+ next_before_pin: Optional[float] = None
class VideoJobCreateRequest(BaseModel):
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index a60ba7809dd..dee15877cfb 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -39789,6 +39789,7 @@ async def list_gallery_audio(
offset: int = 0,
before_mtime: Optional[float] = None,
before_id: Optional[str] = None,
+ before_pin: Optional[float] = None,
archived: bool = False,
current_subject: str = Depends(get_current_subject),
):
@@ -39800,9 +39801,12 @@ async def list_gallery_audio(
offset = max(0, offset)
if (before_mtime is None) != (before_id is None):
raise HTTPException(status_code = 400, detail = "Incomplete audio gallery cursor.")
- before = (
- (before_mtime, before_id) if before_mtime is not None and before_id is not None else None
- )
+ before = None
+ if before_mtime is not None and before_id is not None:
+ # A cursor without before_pin (older clients, or an unpinned clip) takes the clip's own rank.
+ if before_pin is None:
+ before_pin = await asyncio.to_thread(audio_gallery.pin_rank, before_id)
+ before = (before_pin, before_mtime, before_id)
# validate inside the pager so offset, limit and has_more count over the accepted domain
def _valid_gallery_audio(record: dict) -> bool:
@@ -39828,8 +39832,9 @@ async def list_gallery_audio(
return AudioGalleryListResponse(
audio = audio,
has_more = has_more,
- next_before_mtime = next_cursor[0] if next_cursor else None,
- next_before_id = next_cursor[1] if next_cursor else None,
+ next_before_mtime = next_cursor[1] if next_cursor else None,
+ next_before_id = next_cursor[2] if next_cursor else None,
+ next_before_pin = next_cursor[0] if next_cursor and next_cursor[0] > float("-inf") else None,
)
@@ -39862,7 +39867,9 @@ async def update_gallery_audio_flags(
from core.inference import audio_gallery
try:
- record = await asyncio.to_thread(audio_gallery.set_flags, audio_id, archived = patch.archived)
+ record = await asyncio.to_thread(
+ audio_gallery.set_flags, audio_id, pinned = patch.pinned, 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.")
@@ -39871,6 +39878,51 @@ async def update_gallery_audio_flags(
return AudioGalleryItem(**record)
+@studio_router.post("/audio/gallery/{audio_id}/move", response_model = AudioGalleryItem)
+async def move_gallery_audio(
+ audio_id: str,
+ body: GalleryMoveRequest,
+ current_subject: str = Depends(get_current_subject),
+):
+ """Move one clip to just after ``after_id``. Dropping among pins pins it, elsewhere unpins it."""
+ from core.inference import audio_gallery
+
+ try:
+ record = await asyncio.to_thread(audio_gallery.move, audio_id, body.after_id)
+ except KeyError:
+ # The neighbour left history; the client resyncs.
+ raise HTTPException(status_code = 409, detail = "The gallery changed; try the move again.")
+ except OSError as exc:
+ logger.warning("audio_gallery.move_failed: %s", exc)
+ raise HTTPException(status_code = 500, detail = "Could not save the new order.")
+ if record is None:
+ raise HTTPException(status_code = 404, detail = "Audio not found.")
+ return AudioGalleryItem(**record)
+
+
+@studio_router.post("/audio/gallery/{audio_id}/project", response_model = GalleryProjectResponse)
+async def add_gallery_audio_to_project(
+ audio_id: str,
+ body: GalleryProjectRequest,
+ current_subject: str = Depends(get_current_subject),
+):
+ """Copy one clip into a chat project's folder."""
+ from core.inference import audio_gallery
+ from core.inference.gallery_projects import ProjectNotFound, copy_into_project
+
+ path = await asyncio.to_thread(audio_gallery.owned_audio_path, audio_id)
+ if path is None:
+ raise HTTPException(status_code = 404, detail = "Audio not found.")
+ try:
+ result = await asyncio.to_thread(copy_into_project, path, body.project_id, "audio")
+ except ProjectNotFound:
+ raise HTTPException(status_code = 404, detail = "Project not found.")
+ except OSError as exc:
+ logger.warning("audio_gallery.add_to_project_failed: %s", exc)
+ raise HTTPException(status_code = 500, detail = "Could not copy the clip into the project.")
+ return GalleryProjectResponse(**result)
+
+
@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
diff --git a/studio/backend/tests/test_audio_gallery.py b/studio/backend/tests/test_audio_gallery.py
index 1eaed93d94f..d6f6addb511 100644
--- a/studio/backend/tests/test_audio_gallery.py
+++ b/studio/backend/tests/test_audio_gallery.py
@@ -558,3 +558,141 @@ def test_clear_stops_when_the_cross_process_lock_is_unavailable(monkeypatch):
with pytest.raises(gallery_flags.FlagsUnavailable):
gallery.clear()
assert gallery.audio_path(record["id"]) is not None
+
+
+# --- pins and manual order ---------------------------------------------------------------
+
+
+def test_pinned_clips_lead_history():
+ old = _save_with_mtime("old", 100.0)
+ new = _save_with_mtime("new", 200.0)
+ assert gallery.set_flags(old["id"], pinned = True)["pinned"] is True
+ assert [r["id"] for r in gallery.list_audio()] == [old["id"], new["id"]]
+ gallery.set_flags(old["id"], pinned = False)
+ assert [r["id"] for r in gallery.list_audio()] == [new["id"], old["id"]]
+
+
+def test_records_carry_the_listing_sort_key():
+ record = _save_with_mtime("a", 150.0)
+ assert gallery.list_audio()[0]["order_at"] == 150.0
+ assert record["pinned"] is False
+
+
+def test_move_places_a_clip_after_its_new_neighbour():
+ a, b, c = (_save_with_mtime(p, t) for p, t in (("a", 300.0), ("b", 200.0), ("c", 100.0)))
+ gallery.move(c["id"], a["id"])
+ assert [r["prompt"] for r in gallery.list_audio()] == ["a", "c", "b"]
+ gallery.move(b["id"], None)
+ assert [r["prompt"] for r in gallery.list_audio()] == ["b", "a", "c"]
+
+
+def test_move_among_pins_pins_the_clip():
+ a, b, c = (_save_with_mtime(p, t) for p, t in (("a", 300.0), ("b", 200.0), ("c", 100.0)))
+ gallery.set_flags(a["id"], pinned = True)
+ gallery.set_flags(b["id"], pinned = True)
+ moved = gallery.move(c["id"], None)
+ assert moved["pinned"] is True
+ assert [r["prompt"] for r in gallery.list_audio()][0] == "c"
+
+
+def test_move_refuses_unknown_or_archived_clips():
+ a = _save_with_mtime("a", 100.0)
+ b = _save_with_mtime("b", 200.0)
+ assert gallery.move("missing", None) is None
+ gallery.set_flags(a["id"], archived = True)
+ assert gallery.move(a["id"], None) is None
+ with pytest.raises(KeyError):
+ gallery.move(b["id"], "not-on-the-shelf")
+
+
+def test_cursor_pages_through_pins_and_dragged_clips():
+ clips = [_save_with_mtime(f"p{i}", float(i)) for i in range(1, 6)]
+ gallery.set_flags(clips[0]["id"], pinned = True)
+ gallery.move(clips[1]["id"], clips[3]["id"])
+ full = [r["id"] for r in gallery.list_audio()]
+ seen, before = [], None
+ while True:
+ page = gallery.list_audio_page(limit = 2, before = before)
+ seen += [r["id"] for r, _ in page]
+ if len(page) < 2:
+ break
+ before = page[-1][1]
+ assert seen == full
+
+
+def test_prune_goes_by_age_and_spares_pins(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_AUDIO_GALLERY_MAX_CLIPS", "2")
+ oldest = _save_with_mtime("oldest", 100.0)
+ gallery.set_flags(oldest["id"], pinned = True)
+ b = _save_with_mtime("b", 200.0)
+ c = _save_with_mtime("c", 300.0)
+ # Dragged to the bottom, but still newer than b.
+ gallery.move(c["id"], b["id"])
+ gallery.save(_wav(), _meta(prompt = "d"))
+ assert gallery.audio_path(oldest["id"]) is not None
+ assert gallery.audio_path(c["id"]) is not None
+ assert gallery.audio_path(b["id"]) is None
+
+
+def test_list_route_round_trips_a_pinned_cursor():
+ from routes.inference import list_gallery_audio
+
+ clips = [_save_with_mtime(f"p{i}", float(i)) for i in range(1, 4)]
+ for clip in clips:
+ gallery.set_flags(clip["id"], pinned = True)
+ page1 = asyncio.run(list_gallery_audio(limit = 2, current_subject = "tester"))
+ assert page1.has_more and page1.next_before_pin is not None
+ page2 = asyncio.run(
+ list_gallery_audio(
+ limit = 2,
+ before_mtime = page1.next_before_mtime,
+ before_id = page1.next_before_id,
+ before_pin = page1.next_before_pin,
+ current_subject = "tester",
+ )
+ )
+ ids = [c.id for c in page1.audio] + [c.id for c in page2.audio]
+ assert sorted(ids) == sorted(c["id"] for c in clips) and len(set(ids)) == 3
+
+
+def test_project_route_copies_the_wav(monkeypatch, tmp_path):
+ import storage.studio_db as studio_db
+ from models.inference import GalleryProjectRequest
+ from routes.inference import add_gallery_audio_to_project
+
+ root = tmp_path / "Projects" / "demo"
+ (root / "sandbox").mkdir(parents = True)
+ monkeypatch.setattr(
+ studio_db,
+ "ensure_chat_project_workspace",
+ lambda pid: {"id": pid, "rootPath": str(root), "sandboxPath": str(root / "sandbox")},
+ )
+ record = gallery.save(_wav(), _meta())
+ result = asyncio.run(
+ add_gallery_audio_to_project(
+ record["id"], GalleryProjectRequest(project_id = "p1"), current_subject = "tester"
+ )
+ )
+ dest = root / "sandbox" / "audio" / f"{record['id']}.wav"
+ assert result.path == str(dest) and result.already is False
+ assert dest.read_bytes() == _wav()
+
+
+def test_list_route_resolves_a_cursor_sent_without_its_pin_rank():
+ # Older clients send only before_mtime and before_id.
+ from routes.inference import list_gallery_audio
+
+ clips = [_save_with_mtime(f"p{i}", float(i)) for i in range(1, 5)]
+ for clip in clips[:3]:
+ gallery.set_flags(clip["id"], pinned = True)
+ page1 = asyncio.run(list_gallery_audio(limit = 2, current_subject = "tester"))
+ page2 = asyncio.run(
+ list_gallery_audio(
+ limit = 2,
+ before_mtime = page1.next_before_mtime,
+ before_id = page1.next_before_id,
+ current_subject = "tester",
+ )
+ )
+ ids = [c.id for c in page1.audio] + [c.id for c in page2.audio]
+ assert sorted(ids) == sorted(c["id"] for c in clips)
diff --git a/studio/frontend/src/components/gallery-item-menu.tsx b/studio/frontend/src/components/gallery-item-menu.tsx
index abf952b2ed8..21d5180886c 100644
--- a/studio/frontend/src/components/gallery-item-menu.tsx
+++ b/studio/frontend/src/components/gallery-item-menu.tsx
@@ -14,7 +14,7 @@ import {
PinOffIcon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import { useEffect, useState } from "react";
+import { type ReactNode, useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import {
@@ -33,13 +33,14 @@ import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
/**
- * Actions for one gallery item, shared by the Images and Video pages. Matches a chat row's menu.
+ * Actions for one gallery item, shared by the Images, Video and Audio pages. Matches a chat row's menu.
*
* "toolbar" sits in the glass toolbar over the preview; "overlay" is the badge that appears on a
- * filmstrip tile on hover. A tile is itself a <button>, so the overlay must be rendered as its
- * SIBLING, never a child -- nested buttons are invalid and break keyboard activation.
+ * filmstrip tile on hover; "row" is the quiet trigger at the end of a list row. A tile is itself a
+ * <button>, so the menu must be rendered as its SIBLING, never a child -- nested buttons are invalid
+ * and break keyboard activation.
*/
-export type GalleryItemMenuVariant = "toolbar" | "overlay";
+export type GalleryItemMenuVariant = "toolbar" | "overlay" | "row";
export function GalleryItemMenu({
pinned,
@@ -49,6 +50,7 @@ export function GalleryItemMenu({
onDelete,
onDownload,
onAddToProject,
+ leadingItems,
variant = "toolbar",
noun,
active = true,
@@ -63,6 +65,8 @@ export function GalleryItemMenu({
onDownload?: () => void;
/** Copies the item into a project's folder. */
onAddToProject?: (projectId: string) => Promise<{ already: boolean }>;
+ /** Page-specific items shown first, above a separator. */
+ leadingItems?: ReactNode;
variant?: GalleryItemMenuVariant;
/** Used in the aria-label and messages, e.g. "image" or "video". */
noun: string;
@@ -95,23 +99,28 @@ export function GalleryItemMenu({
}
const overlay = variant === "overlay";
+ const row = variant === "row";
const menu = (
<DropdownMenu open={active && open} onOpenChange={(o) => setOpen(active && o)}>
<DropdownMenuTrigger asChild={true}>
<Button
- size={overlay ? "icon-xs" : "icon-sm"}
+ size={overlay || row ? "icon-xs" : "icon-sm"}
variant="ghost"
aria-label={`More actions for this ${noun}`}
className={cn(
- // Circular hover.
- "rounded-full",
+ // Circular hover, no border: focus returning on close would draw one. Keyboard focus tints instead.
+ "rounded-full border-0 focus-visible:bg-muted dark:focus-visible:bg-muted/50",
// Reads over any thumbnail, whatever its colours.
overlay &&
- "bg-background/80 text-foreground shadow-sm ring-1 ring-border backdrop-blur hover:bg-background",
+ "bg-background/80 text-foreground shadow-sm backdrop-blur hover:bg-background focus-visible:bg-background dark:focus-visible:bg-background",
+ row && "text-muted-foreground hover:text-foreground",
className,
)}
>
- <HugeiconsIcon icon={MoreVerticalIcon} className={overlay ? "size-3.5" : "size-4"} />
+ <HugeiconsIcon
+ icon={MoreVerticalIcon}
+ className={overlay || row ? "size-3.5" : "size-4"}
+ />
</Button>
</DropdownMenuTrigger>
{/* Same styling as a chat row's menu. */}
@@ -119,6 +128,12 @@ export function GalleryItemMenu({
align="end"
className="unsloth-plus-menu sidebar-row-menu menu-flat-destructive w-52"
>
+ {leadingItems ? (
+ <>
+ {leadingItems}
+ <DropdownMenuSeparator />
+ </>
+ ) : null}
<DropdownMenuItem onClick={onTogglePin}>
<HugeiconsIcon icon={pinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-icon" />
{pinned ? "Unpin" : "Pin"}
@@ -186,7 +201,7 @@ export function GalleryItemMenu({
/>
) : null;
- if (!overlay) {
+ if (!overlay && !row) {
return (
<>
{menu}
diff --git a/studio/frontend/src/components/gallery-strip-reorder.tsx b/studio/frontend/src/components/gallery-strip-reorder.tsx
index a534b801f87..5951087fc7c 100644
--- a/studio/frontend/src/components/gallery-strip-reorder.tsx
+++ b/studio/frontend/src/components/gallery-strip-reorder.tsx
@@ -4,16 +4,32 @@
import type { StripDropCue } from "@/hooks/use-strip-reorder";
import { cn } from "@/lib/utils";
-/** Insertion line beside a tile, centred in the strip's gap. */
-export function StripDropLine({ edge }: { edge: StripDropCue["edge"] }) {
+/** Insertion line beside a tile, centred in the strip's gap. `axis="y"` draws it across a list row. */
+export function StripDropLine({
+ edge,
+ axis = "x",
+}: {
+ edge: StripDropCue["edge"];
+ axis?: "x" | "y";
+}) {
return (
<span
aria-hidden={true}
className={cn(
- "pointer-events-none absolute inset-y-1 z-40 w-0.5 rounded-full bg-primary",
- edge === "before"
- ? "-left-[calc(5px*var(--ui-space-scale,1))]"
- : "-right-[calc(5px*var(--ui-space-scale,1))]",
+ "pointer-events-none absolute z-40 rounded-full bg-primary",
+ axis === "x"
+ ? cn(
+ "inset-y-1 w-0.5",
+ edge === "before"
+ ? "-left-[calc(5px*var(--ui-space-scale,1))]"
+ : "-right-[calc(5px*var(--ui-space-scale,1))]",
+ )
+ : cn(
+ "inset-x-1 h-0.5",
+ edge === "before"
+ ? "-top-[calc(3px*var(--ui-space-scale,1))]"
+ : "-bottom-[calc(3px*var(--ui-space-scale,1))]",
+ ),
)}
/>
);
diff --git a/studio/frontend/src/features/audio/api.ts b/studio/frontend/src/features/audio/api.ts
index fd0ba5f3dfe..18ef188d24d 100644
--- a/studio/frontend/src/features/audio/api.ts
+++ b/studio/frontend/src/features/audio/api.ts
@@ -85,7 +85,10 @@ export interface AudioGalleryClip {
sample_rate: number;
duration_s: number;
created_at: string;
+ pinned?: boolean;
archived?: boolean;
+ /** The server's unpinned sort key: the drag key, else the file mtime. */
+ order_at?: number | null;
}
export interface AudioGalleryListResponse {
@@ -93,16 +96,40 @@ export interface AudioGalleryListResponse {
has_more: boolean;
next_before_mtime: number | null;
next_before_id: string | null;
+ next_before_pin?: number | null;
+}
+
+/** Where the next page starts: the last clip's order key, id and pin rank (null if unpinned). */
+export interface AudioGalleryCursor {
+ mtime: number;
+ id: string;
+ pin?: number | null;
+}
+
+export function audioGalleryCursor(
+ page: AudioGalleryListResponse,
+): AudioGalleryCursor | null {
+ return page.next_before_mtime !== null && page.next_before_id !== null
+ ? {
+ mtime: page.next_before_mtime,
+ id: page.next_before_id,
+ pin: page.next_before_pin ?? null,
+ }
+ : null;
}
export async function listAudioGallery(
offset: number,
limit: number,
- before?: { mtime: number; id: string } | null,
+ before?: AudioGalleryCursor | null,
archived = false,
): Promise<AudioGalleryListResponse> {
+ const pin =
+ before?.pin !== null && before?.pin !== undefined
+ ? `&before_pin=${encodeURIComponent(before.pin)}`
+ : "";
const cursor = before
- ? `&before_mtime=${encodeURIComponent(before.mtime)}&before_id=${encodeURIComponent(before.id)}`
+ ? `&before_mtime=${encodeURIComponent(before.mtime)}&before_id=${encodeURIComponent(before.id)}${pin}`
: "";
const response = await authFetch(
`/api/inference/audio/gallery?offset=${offset}&limit=${limit}&archived=${archived}${cursor}`,
@@ -112,7 +139,7 @@ export async function listAudioGallery(
export async function setAudioClipFlags(
id: string,
- flags: { archived?: boolean },
+ flags: { pinned?: boolean; archived?: boolean },
): Promise<AudioGalleryClip> {
const response = await authFetch(
`/api/inference/audio/gallery/${encodeURIComponent(id)}`,
@@ -125,6 +152,38 @@ export async function setAudioClipFlags(
return parseJson<AudioGalleryClip>(response);
}
+/** Move one clip to just after `afterId` (null = top). */
+export async function moveAudioClip(
+ id: string,
+ afterId: string | null,
+): Promise<AudioGalleryClip> {
+ const response = await authFetch(
+ `/api/inference/audio/gallery/${encodeURIComponent(id)}/move`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ after_id: afterId }),
+ },
+ );
+ return parseJson<AudioGalleryClip>(response);
+}
+
+/** Copy one clip into a chat project's folder. */
+export async function addAudioClipToProject(
+ id: string,
+ projectId: string,
+): Promise<{ path: string; already: boolean }> {
+ const response = await authFetch(
+ `/api/inference/audio/gallery/${encodeURIComponent(id)}/project`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ project_id: projectId }),
+ },
+ );
+ return parseJson<{ path: string; already: boolean }>(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.tsx b/studio/frontend/src/features/audio/audio-page.tsx
index 7f29655e121..eb758fc773a 100644
--- a/studio/frontend/src/features/audio/audio-page.tsx
+++ b/studio/frontend/src/features/audio/audio-page.tsx
@@ -7,13 +7,11 @@
import { TestTubeOutlineIcon } from "@/lib/hugeicons-derived";
import {
- Archive02Icon,
AudioWave01Icon,
Copy01Icon,
Delete02Icon,
Download01Icon,
Mic01Icon,
- MoreVerticalIcon,
SparklesIcon,
StopIcon,
} from "@hugeicons/core-free-icons";
@@ -28,18 +26,15 @@ import {
} from "react";
import { AdvancedDisclosure } from "@/components/advanced-disclosure";
+import { GalleryItemMenu, GalleryPinBadge } from "@/components/gallery-item-menu";
+import { StripDropLine } from "@/components/gallery-strip-reorder";
+import { useStripReorder } from "@/hooks/use-strip-reorder";
import { MediaRailResizeHandle } from "@/components/media-rail-resize-handle";
import { MEDIA_RAIL_ROOT_ATTR, useMediaRailWidth } from "@/hooks/use-media-rail-width";
import { GuidedTour, useGuidedTourController } from "@/features/tour";
import { buildAudioTourSteps } from "./tour";
import { Button } from "@/components/ui/button";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Progress } from "@/components/ui/progress";
import { Textarea } from "@/components/ui/textarea";
@@ -104,7 +99,15 @@ import { fetchSystemInfo } from "@/hooks/use-system";
import { isTauri } from "@/lib/api-base";
import { BlobUrlCache } from "@/lib/blob-url-cache";
import { copyToClipboard } from "@/lib/copy-to-clipboard";
-import { subscribeGalleryChanged } from "@/lib/gallery-flags";
+import {
+ applyPin,
+ moveGalleryItem,
+ pinnedOrder,
+ restorePinOrder,
+ serializeById,
+ sortGalleryItems,
+ subscribeGalleryChanged,
+} from "@/lib/gallery-flags";
import { subscribeModelLifecycle } from "@/lib/model-lifecycle-events";
import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
@@ -113,12 +116,16 @@ import { useNavigate, useSearch } from "@tanstack/react-router";
import {
type AudioGalleryClip,
+ type AudioGalleryCursor,
+ addAudioClipToProject,
+ audioGalleryCursor,
clearAudioGallery,
deleteAudioClip,
fetchClipObjectUrl,
generateAudio,
getAudioDownloadPlan,
listAudioGallery,
+ moveAudioClip,
setAudioClipFlags,
transcribeWithProgress,
} from "./api";
@@ -216,7 +223,7 @@ const CLIP_BLOB_BUDGET_BYTES = 64 * 1024 * 1024;
const galleryCache: {
clips: AudioGalleryClip[];
hasMore: boolean;
- nextCursor: { mtime: number; id: string } | null;
+ nextCursor: AudioGalleryCursor | null;
selectedId: string | null;
srcById: BlobUrlCache;
} = {
@@ -262,68 +269,6 @@ function Field({
);
}
-/** Per-row actions for a history clip, in a dots menu so rows keep one line. Mirrors the model
- * rows' MoreVertical pattern. */
-function ClipRowMenu({
- clip,
- onDownload,
- onCopyPrompt,
- onUseAsText,
- onArchive,
- onDelete,
-}: {
- clip: AudioGalleryClip;
- onDownload: () => void;
- onCopyPrompt: () => void;
- onUseAsText: () => void;
- onArchive: () => void;
- onDelete: () => void;
-}) {
- return (
- <DropdownMenu>
- <DropdownMenuTrigger asChild={true}>
- <button
- type="button"
- onClick={(event) => event.stopPropagation()}
- aria-label={`Actions for ${clip.prompt || "clip"}`}
- // Hidden until the row is hovered or the menu is open, so a long list stays quiet; keyboard
- // focus reveals it too.
- className="flex size-5 shrink-0 items-center justify-center rounded-md text-muted-foreground/60 opacity-0 any-pointer-coarse:opacity-100 transition-colors hover:bg-[rgb(0_0_0_/_calc(0.05*var(--contrast-wash-gain,1)))] hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100 data-[state=open]:opacity-100 dark:hover:bg-[rgb(255_255_255_/_calc(0.1*var(--contrast-wash-gain,1)))]"
- >
- <HugeiconsIcon
- icon={MoreVerticalIcon}
- strokeWidth={1.75}
- className="size-3.5"
- />
- </button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-48">
- <DropdownMenuItem onSelect={onUseAsText}>
- <HugeiconsIcon icon={SparklesIcon} className="size-4" />
- Use text again
- </DropdownMenuItem>
- <DropdownMenuItem onSelect={onCopyPrompt}>
- <HugeiconsIcon icon={Copy01Icon} className="size-4" />
- Copy text
- </DropdownMenuItem>
- <DropdownMenuItem onSelect={onDownload}>
- <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" />
- Delete
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- );
-}
-
function formatClipDuration(seconds: number): string {
if (!Number.isFinite(seconds) || seconds <= 0) return "0:00";
const whole = Math.round(seconds);
@@ -457,6 +402,8 @@ export function AudioPage({
fallbackClipRef.current = fallbackClip;
const loadingMoreRef = useRef(false);
const galleryRefreshGeneration = useRef(0);
+ // Pins and moves in flight. A refresh that overlaps one read the old order, so it is dropped and rerun after.
+ const orderWrites = useRef({ inFlight: 0, epoch: 0, deferred: false });
const recorderRef = useRef<SegmentRecorder | null>(null);
const recordStreamRef = useRef<MediaStream | null>(null);
const discardRecordingRef = useRef(false);
@@ -790,12 +737,17 @@ export function AudioPage({
windowSize = PAGE_SIZE,
): Promise<AudioGalleryClip[]> => {
const generation = ++galleryRefreshGeneration.current;
+ const writeEpoch = orderWrites.current.epoch;
const wanted = Math.max(PAGE_SIZE, windowSize);
const asked = Math.min(wanted, MAX_PAGE_SIZE);
try {
const page = await listAudioGallery(0, asked);
// The caller's own fetch: a generation whose clip persisted must not be told otherwise.
if (generation !== galleryRefreshGeneration.current) return page.audio;
+ if (orderWrites.current.inFlight > 0 || orderWrites.current.epoch !== writeEpoch) {
+ orderWrites.current.deferred = true;
+ return page.audio;
+ }
// A window past the route's cap cannot be covered in one page, and stitching the old scrollback
// back on keeps a cursor that starts BELOW it, stranding whatever was restored.
const { clips: merged, stitched } =
@@ -811,10 +763,7 @@ export function AudioPage({
// A clip record carries no mtime, so kept scrollback has no cursor; keep the deeper one.
if (!stitched) {
galleryCache.hasMore = page.has_more;
- galleryCache.nextCursor =
- page.next_before_mtime !== null && page.next_before_id !== null
- ? { mtime: page.next_before_mtime, id: page.next_before_id }
- : null;
+ galleryCache.nextCursor = audioGalleryCursor(page);
}
setClips(merged);
setHasMore(galleryCache.hasMore);
@@ -869,10 +818,7 @@ export function AudioPage({
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 }
- : null;
+ galleryCache.nextCursor = audioGalleryCursor(page);
const known = new Set(galleryCache.clips.map((clip) => clip.id));
galleryCache.clips = [
...galleryCache.clips,
@@ -2384,6 +2330,101 @@ export function AudioPage({
[dropClip, refreshGallery],
);
+ // The pin state each id was last clicked or dragged into, so a stale response cannot undo a later one.
+ const pinAttempt = useRef(new Map<string, number>());
+ const pinSeq = useRef(0);
+
+ const beginOrderWrite = useCallback(() => {
+ orderWrites.current.inFlight += 1;
+ orderWrites.current.epoch += 1;
+ }, []);
+ const endOrderWrite = useCallback(() => {
+ const writes = orderWrites.current;
+ writes.inFlight -= 1;
+ writes.epoch += 1;
+ if (writes.inFlight === 0 && writes.deferred) {
+ writes.deferred = false;
+ void refreshGallery(undefined, galleryCache.clips.length);
+ }
+ }, [refreshGallery]);
+
+ const handleTogglePin = useCallback(async (id: string, pinned: boolean) => {
+ // The pinned order before the click, so a failed unpin goes back where it was.
+ const orderBefore = pinnedOrder(galleryCache.clips);
+ const attempt = (pinSeq.current += 1);
+ pinAttempt.current.set(id, attempt);
+ // Optimistic. Records carry the server's sort key, so the local re-sort matches it.
+ galleryCache.clips = applyPin(galleryCache.clips, id, pinned);
+ setClips(galleryCache.clips);
+ beginOrderWrite();
+ try {
+ // One queue for pins and moves: the server stamps pins in the order it runs them.
+ await serializeById("audio-pin", () => setAudioClipFlags(id, { pinned }));
+ // An unpinned clip can belong below the loaded window, so resync it once writes settle.
+ if (!pinned && galleryCache.hasMore) orderWrites.current.deferred = true;
+ } catch (error) {
+ toast.error(
+ error instanceof Error ? error.message : "Could not pin the clip.",
+ );
+ if (pinAttempt.current.get(id) === attempt) {
+ galleryCache.clips = pinned
+ ? applyPin(galleryCache.clips, id, false)
+ : restorePinOrder(galleryCache.clips, id, orderBefore);
+ setClips(galleryCache.clips);
+ }
+ } finally {
+ if (pinAttempt.current.get(id) === attempt) pinAttempt.current.delete(id);
+ endOrderWrite();
+ }
+ }, [beginOrderWrite, endOrderWrite]);
+
+ // Drag to reorder: applied optimistically, then the server's record (key and pin) is adopted.
+ const handleMoveClip = useCallback(
+ async (id: string, afterId: string | null) => {
+ const next = moveGalleryItem(galleryCache.clips, id, afterId);
+ if (next === galleryCache.clips) return;
+ const guessedPinned = Boolean(next.find((c) => c.id === id)?.pinned);
+ // Takes a pin token too: a pin clicked after this drop must not be undone by its response.
+ const attempt = (pinSeq.current += 1);
+ pinAttempt.current.set(id, attempt);
+ galleryCache.clips = next;
+ setClips(next);
+ beginOrderWrite();
+ try {
+ const record = await serializeById("audio-pin", () =>
+ moveAudioClip(id, afterId),
+ );
+ if (pinAttempt.current.get(id) !== attempt) return;
+ pinAttempt.current.delete(id);
+ const patched = galleryCache.clips.map((c) =>
+ c.id === id
+ ? { ...c, pinned: record.pinned, order_at: record.order_at }
+ : c,
+ );
+ // Re-sort only if the local pin guess was wrong.
+ galleryCache.clips =
+ Boolean(record.pinned) === guessedPinned
+ ? patched
+ : sortGalleryItems(patched);
+ setClips(galleryCache.clips);
+ } catch (error) {
+ toast.error(
+ error instanceof Error ? error.message : "Could not move the clip.",
+ );
+ if (pinAttempt.current.get(id) === attempt) pinAttempt.current.delete(id);
+ // Put the server's order back once no other write is in flight.
+ orderWrites.current.deferred = true;
+ } finally {
+ endOrderWrite();
+ }
+ },
+ [beginOrderWrite, endOrderWrite],
+ );
+ const historyReorder = useStripReorder(
+ (id, afterId) => void handleMoveClip(id, afterId),
+ { axis: "y" },
+ );
+
// This page stays mounted across route changes, so a restore from the Settings archive would not reach
// History until a reload. Refresh the loaded window, not just the first page: a clip re-enters at its own age.
useEffect(
@@ -3193,7 +3234,9 @@ export function AudioPage({
</Button>
</div>
<div
- className="hover-scrollbar flex max-h-40 flex-col gap-1 overflow-y-auto"
+ {...historyReorder.stripProps}
+ // py-1 keeps the first and last drop lines inside the scroller.
+ className="hover-scrollbar flex max-h-40 flex-col gap-1 overflow-y-auto py-1"
onScroll={(event) => {
const el = event.currentTarget;
if (
@@ -3205,14 +3248,22 @@ export function AudioPage({
}}
>
{clips.map((clip) => (
- // Shell, not a button: the dots menu is a button and cannot nest.
+ // Shell, not a button: the pin badge and dots menu are buttons and cannot nest.
<div
key={clip.id}
+ {...historyReorder.tileProps(clip.id)}
className={cn(
- "group flex items-center rounded-md pr-1 transition-colors hover:bg-muted",
+ "group relative flex items-center gap-1 rounded-md pr-1 transition-colors hover:bg-muted",
clip.id === selectedId && "bg-muted",
+ historyReorder.draggingId === clip.id && "opacity-40",
)}
>
+ {historyReorder.cue?.id === clip.id && (
+ <StripDropLine
+ axis="y"
+ edge={historyReorder.cue.edge}
+ />
+ )}
<button
type="button"
onClick={() => selectClip(clip.id)}
@@ -3232,17 +3283,54 @@ export function AudioPage({
{formatClipDuration(clip.duration_s)}
</span>
</button>
- <ClipRowMenu
- clip={clip}
- onDownload={() => void handleDownloadClipById(clip)}
- onCopyPrompt={() =>
- void handleCopyPrompt(clip.prompt)
+ {clip.pinned && (
+ <GalleryPinBadge
+ noun="clip"
+ className="static shrink-0"
+ onUnpin={() => void handleTogglePin(clip.id, false)}
+ />
+ )}
+ <GalleryItemMenu
+ variant="row"
+ noun="clip"
+ active={active}
+ pinned={Boolean(clip.pinned)}
+ archived={false}
+ onTogglePin={() =>
+ void handleTogglePin(clip.id, !clip.pinned)
}
- onUseAsText={() => {
- if (transitionMode("speak")) setPrompt(clip.prompt);
- }}
- onArchive={() => void handleArchiveClip(clip.id)}
+ onToggleArchive={() => void handleArchiveClip(clip.id)}
onDelete={() => void handleDeleteClip(clip.id)}
+ onDownload={() => void handleDownloadClipById(clip)}
+ onAddToProject={(projectId) =>
+ addAudioClipToProject(clip.id, projectId)
+ }
+ leadingItems={
+ <>
+ <DropdownMenuItem
+ onClick={() => {
+ if (transitionMode("speak")) setPrompt(clip.prompt);
+ }}
+ >
+ <HugeiconsIcon
+ icon={SparklesIcon}
+ strokeWidth={1.75}
+ className="size-icon"
+ />
+ Use text again
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => void handleCopyPrompt(clip.prompt)}
+ >
+ <HugeiconsIcon
+ icon={Copy01Icon}
+ strokeWidth={1.75}
+ className="size-icon"
+ />
+ Copy text
+ </DropdownMenuItem>
+ </>
+ }
/>
</div>
))}
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index bc824b5f1d1..453308af0ff 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -5194,7 +5194,8 @@ export function ImagesPage({
/>
{/* Actions grouped in one glass toolbar so they stay legible over any image. Size and seed
live in the Recipe popover. */}
- <div className="absolute bottom-4 right-4 flex items-center gap-0.5 rounded-xl bg-background/80 p-1 shadow-lg ring-1 ring-border backdrop-blur">
+ {/* No button borders: focus returning from a menu would draw one. Keyboard focus tints instead. */}
+ <div className="absolute bottom-4 right-4 flex items-center gap-0.5 rounded-xl bg-background/80 p-1 shadow-lg ring-1 ring-border backdrop-blur [&_[data-slot=button]]:border-0 [&_[data-slot=button]:focus-visible]:bg-muted">
<RecipePopover image={selected} onRestore={restoreSettings} active={active} />
<DropdownMenu>
<DropdownMenuTrigger asChild={true}>
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 9d172ad565f..c89b5be00d8 100644
--- a/studio/frontend/src/features/settings/components/archived-media-dialog.tsx
+++ b/studio/frontend/src/features/settings/components/archived-media-dialog.tsx
@@ -29,6 +29,8 @@ import {
import { LibraryRow, LibraryToolbar } from "./data-library-controls";
import { Spinner } from "@/components/ui/spinner";
import {
+ type AudioGalleryCursor,
+ audioGalleryCursor,
deleteAudioClip,
listAudioGallery,
setAudioClipFlags,
@@ -76,15 +78,10 @@ interface ArchivedRow {
url: string;
}
-interface AudioCursor {
- mtime: number;
- id: string;
-}
-
interface ArchivedPage {
rows: ArchivedRow[];
hasMore: boolean;
- nextAudioCursor: AudioCursor | null;
+ nextAudioCursor: AudioGalleryCursor | null;
}
/**
@@ -103,7 +100,7 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
// 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 audioCursor = useRef<AudioGalleryCursor | 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.
@@ -162,7 +159,7 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
const loadPage = useCallback(
async (
offset: number,
- before: AudioCursor | null = null,
+ before: AudioGalleryCursor | null = null,
pageSize = ARCHIVED_PAGE_SIZE,
): Promise<ArchivedPage> => {
if (isImages) {
@@ -188,10 +185,7 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
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,
+ nextAudioCursor: audioGalleryCursor(page),
};
}
const page = await getVideoGallery(offset, pageSize, true);
diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsx
index 2e0ed0ba7bc..f2f70e4ff78 100644
--- a/studio/frontend/src/features/video/video-page.tsx
+++ b/studio/frontend/src/features/video/video-page.tsx
@@ -4226,7 +4226,8 @@ function VideoGenerator({
</div>
)}
{/* Actions grouped in one glass toolbar so they stay legible over any clip. */}
- <div className="absolute bottom-4 right-4 flex items-center gap-0.5 rounded-xl bg-background/80 p-1 shadow-lg ring-1 ring-border backdrop-blur">
+ {/* No button borders: focus returning from a menu would draw one. Keyboard focus tints instead. */}
+ <div className="absolute bottom-4 right-4 flex items-center gap-0.5 rounded-xl bg-background/80 p-1 shadow-lg ring-1 ring-border backdrop-blur [&_[data-slot=button]]:border-0 [&_[data-slot=button]:focus-visible]:bg-muted">
<RecipePopover video={selected} onRestore={restoreSettings} active={active} />
<DropdownMenu>
<DropdownMenuTrigger asChild={true}>
diff --git a/studio/frontend/src/hooks/use-strip-reorder.ts b/studio/frontend/src/hooks/use-strip-reorder.ts
index 5880775272b..7285fd5e75e 100644
--- a/studio/frontend/src/hooks/use-strip-reorder.ts
+++ b/studio/frontend/src/hooks/use-strip-reorder.ts
@@ -19,13 +19,20 @@ function fromTile(event: React.SyntheticEvent<HTMLElement>): boolean {
}
/**
- * Drag-to-reorder for a horizontal gallery strip (Images and Video).
+ * Drag-to-reorder for a gallery strip: horizontal (Images, Video) or, with `axis: "y"`, a vertical
+ * list (Audio history).
*
* Tracked on the strip so gaps and ends are drop targets. Tiles carry `data-reorder-id` in display
- * order. A drop reports the id the tile now follows (null = front). Alt + Left / Right moves the
- * focused tile one slot. Drags that did not start on a tile are ignored.
+ * order. A drop reports the id the tile now follows (null = front). Alt + Left / Right (Up / Down
+ * on a list) moves the focused tile one slot. Drags that did not start on a tile are ignored.
*/
-export function useStripReorder(onMove: (id: string, afterId: string | null) => void) {
+export function useStripReorder(
+ onMove: (id: string, afterId: string | null) => void,
+ { axis = "x" }: { axis?: "x" | "y" } = {},
+) {
+ const vertical = axis === "y";
+ const backKey = vertical ? "ArrowUp" : "ArrowLeft";
+ const forwardKey = vertical ? "ArrowDown" : "ArrowRight";
const dragIdRef = useRef<string | null>(null);
const [draggingId, setDraggingId] = useState<string | null>(null);
const [cue, setCue] = useState<StripDropCue | null>(null);
@@ -36,10 +43,10 @@ export function useStripReorder(onMove: (id: string, afterId: string | null) =>
setCue(null);
}, []);
- /** The drop at `clientX`, or null if the tile would not move. */
+ /** The drop at pointer position `at` along the axis, or null if the tile would not move. */
function resolve(
strip: HTMLElement,
- clientX: number,
+ at: number,
): { afterId: string | null; cue: StripDropCue } | null {
const dragged = dragIdRef.current;
if (!dragged) return null;
@@ -47,7 +54,7 @@ export function useStripReorder(onMove: (id: string, afterId: string | null) =>
const order = tiles.map((tile) => tile.dataset.reorderId ?? "");
let index = tiles.findIndex((tile) => {
const rect = tile.getBoundingClientRect();
- return clientX < rect.left + rect.width / 2;
+ return vertical ? at < rect.top + rect.height / 2 : at < rect.left + rect.width / 2;
});
if (index < 0) index = tiles.length;
const from = order.indexOf(dragged);
@@ -67,7 +74,7 @@ export function useStripReorder(onMove: (id: string, afterId: string | null) =>
if (!dragIdRef.current) return;
event.preventDefault();
event.dataTransfer.dropEffect = "move";
- const next = resolve(event.currentTarget, event.clientX)?.cue ?? null;
+ const next = resolve(event.currentTarget, vertical ? event.clientY : event.clientX)?.cue ?? null;
setCue((prev) =>
prev?.id === next?.id && prev?.edge === next?.edge ? prev : next,
);
@@ -81,7 +88,7 @@ export function useStripReorder(onMove: (id: string, afterId: string | null) =>
const dragged = dragIdRef.current;
if (!dragged) return;
event.preventDefault();
- const drop = resolve(event.currentTarget, event.clientX);
+ const drop = resolve(event.currentTarget, vertical ? event.clientY : event.clientX);
end();
if (drop) onMove(dragged, drop.afterId);
},
@@ -103,7 +110,7 @@ export function useStripReorder(onMove: (id: string, afterId: string | null) =>
if (
!fromTile(event) ||
!event.altKey ||
- (event.key !== "ArrowLeft" && event.key !== "ArrowRight")
+ (event.key !== backKey && event.key !== forwardKey)
) {
return;
}
@@ -114,9 +121,9 @@ export function useStripReorder(onMove: (id: string, afterId: string | null) =>
].map((tile) => tile.dataset.reorderId ?? "");
const from = order.indexOf(id);
event.preventDefault();
- if (event.key === "ArrowLeft" && from > 0) {
+ if (event.key === backKey && from > 0) {
onMove(id, from > 1 ? order[from - 2] : null);
- } else if (event.key === "ArrowRight" && from >= 0 && from < order.length - 1) {
+ } else if (event.key === forwardKey && from >= 0 && from < order.length - 1) {
onMove(id, order[from + 1]);
}
},
diff --git a/studio/frontend/tests/audio-page-policy.test.ts b/studio/frontend/tests/audio-page-policy.test.ts
index 48ccc3852e5..d6590b6a50d 100644
--- a/studio/frontend/tests/audio-page-policy.test.ts
+++ b/studio/frontend/tests/audio-page-policy.test.ts
@@ -376,10 +376,32 @@ test("gallery refresh preserves fallback selection and pagination identity", ()
);
assert.match(
audioPageSource,
- /listAudioGallery\([\s\S]*galleryCache\.nextCursor[\s\S]*galleryCache\.nextCursor =[\s\S]*page\.next_before_mtime[\s\S]*new Set\(galleryCache\.clips\.map[\s\S]*filter\(\(clip\) => !known\.has\(clip\.id\)\)/,
+ /listAudioGallery\([\s\S]*galleryCache\.nextCursor[\s\S]*galleryCache\.nextCursor = audioGalleryCursor\(page\)[\s\S]*new Set\(galleryCache\.clips\.map[\s\S]*filter\(\(clip\) => !known\.has\(clip\.id\)\)/,
);
});
+test("a refresh that overlaps a pin or move is dropped and rerun after it", () => {
+ assert.match(
+ audioPageSource,
+ /const writeEpoch = orderWrites\.current\.epoch;[\s\S]*listAudioGallery\(\s*0,[\s\S]*orderWrites\.current\.inFlight > 0 \|\| orderWrites\.current\.epoch !== writeEpoch[\s\S]*orderWrites\.current\.deferred = true;\s*return page\.audio;/,
+ );
+ assert.match(
+ audioPageSource,
+ /writes\.inFlight === 0 && writes\.deferred\) \{\s*writes\.deferred = false;\s*void refreshGallery\(/,
+ );
+ // A successful unpin with more pages unloaded resyncs the window.
+ assert.match(
+ audioPageSource,
+ /setAudioClipFlags\(id, \{ pinned \}\)\);\s*\/\/[^\n]*\n\s*if \(!pinned && galleryCache\.hasMore\) orderWrites\.current\.deferred = true;/,
+ );
+ for (const call of ["setAudioClipFlags(id, { pinned })", "moveAudioClip(id, afterId)"]) {
+ const at = audioPageSource.indexOf(call);
+ const before = audioPageSource.lastIndexOf("beginOrderWrite();", at);
+ const after = audioPageSource.indexOf("endOrderWrite();", at);
+ assert.ok(before > 0 && at - before < 400 && after > at, call);
+ }
+});
+
test("Audio transcription uses backend language auto-detection", () => {
const api = readSrc("features/audio/api.ts");
const transcription = api.slice(api.indexOf("export async function transcribeWithProgress"), api.indexOf("export async function listTranscripts"));