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, archive and delete for generated images and clips (#8349)

Michael Han467eb5f8777c
diff --git a/studio/backend/core/inference/gallery_flags.py b/studio/backend/core/inference/gallery_flags.py
new file mode 100644
index 00000000000..69be6cc0148
--- /dev/null
+++ b/studio/backend/core/inference/gallery_flags.py
@@ -0,0 +1,404 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Pin / archive flags for the image and video galleries.
+
+Library state, NOT part of a generation recipe: a PNG's text chunk and a clip's sidecar
+describe how the media was made, while "I pinned this" describes how the user files it. So
+flags live in their own ``.flags.json`` beside the media rather than in the recipe, and a
+record missing from the store simply has no flags.
+
+One store per gallery directory, keyed by the same id the gallery uses (the file stem):
+
+ {"version": 1, "items": {"<id>": {"pinned_at": 1712345678.0, "archived": true}}}
+
+The filename is skipped by the galleries' ``*.png`` / ``*.mp4`` globs, so a store sitting in
+the directory is invisible to listing. Every read fails safe: a corrupt, hand-edited or
+unreadable store degrades to "no flags", never to an error, because losing a pin is a far
+better outcome than a gallery that will not list.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import json
+import math
+import os
+import threading
+from pathlib import Path
+from typing import Any, Optional
+
+from loggers import get_logger
+
+logger = get_logger(__name__)
+
+_SCHEMA_VERSION = 1
+_STORE_NAME = ".flags.json"
+# Marks a store written over one whose ITEMS MAP was illegible: the old flags could not be carried
+# forward, so the new file is no proof that nothing is archived. See ``_carry_taint``.
+_TAINT_KEY = "unreadable"
+_lock = threading.RLock()
+
+
+def _store_path(directory: Path) -> Path:
+ return directory / _STORE_NAME
+
+
+def _empty() -> dict[str, Any]:
+ return {"version": _SCHEMA_VERSION, "items": {}}
+
+
+class FlagsUnavailable(RuntimeError):
+ """The store exists but could not be trusted (unparseable, wrong shape, unreadable).
+
+ Distinct from "no store yet", which legitimately means no flags. Callers that only order or
+ display flags ignore this and fall back to no flags; callers that DELETE on the strength of a
+ flag must fail closed instead, or a corrupt store silently reads every archived item as active.
+ """
+
+
+def _valid_entry(entry: Any) -> bool:
+ """Whether an entry is exactly the shape this module writes.
+
+ The container being a dict is not enough. ``{"archived": null}`` is a dict, and every reader
+ turns it into "not archived", which is what ``clear`` deletes on. Nothing here ever writes a
+ non-bool ``archived`` or an unusable ``pinned_at``, so either one means the file was edited or
+ damaged and no field in it can be taken at face value."""
+ if not isinstance(entry, dict):
+ return False
+ if "archived" in entry and not isinstance(entry["archived"], bool):
+ return False
+ if "pinned_at" in entry and _pinned_at(entry) is None:
+ return False
+ return True
+
+
+def _sanitize_entry(entry: Any) -> Optional[dict[str, Any]]:
+ """The entry rewritten into a shape this module can read, or None when it held nothing.
+
+ Damage to ``archived`` is RESOLVED to True, never dropped. Dropping it would turn "we cannot
+ tell whether this was archived" into "this is active", and active is what ``clear`` deletes;
+ an item wrongly moved to the archive shelf is one click to undo, an item wrongly deleted is
+ gone. An ABSENT ``archived`` is not damage: unarchiving removes the key, so absent genuinely
+ means active. A non-dict entry has no readable field at all and only exists because something
+ was flagged, so it resolves the same safe way.
+
+ ``pinned_at`` is dropped instead, since losing a pin costs the user an ordering, not a file."""
+ if not isinstance(entry, dict):
+ return {"archived": True}
+ clean = dict(entry)
+ if "archived" in clean and not isinstance(clean["archived"], bool):
+ clean["archived"] = True
+ if "pinned_at" in clean and _pinned_at(clean) is None:
+ clean.pop("pinned_at")
+ return clean or None
+
+
+def _load(directory: Path) -> tuple[dict[str, Any], bool]:
+ """``(data, trusted)``. ``trusted`` is False when a store is present but unusable, so a caller
+ can tell "nothing is flagged" apart from "we cannot say what is flagged"."""
+ try:
+ with open(_store_path(directory), encoding = "utf-8-sig") as f:
+ data = json.load(f)
+ # Validate the shape, not just the version: a hand-edited ``items`` that is not a dict
+ # (e.g. ``[]``) would otherwise crash every lookup instead of failing safe.
+ if (
+ isinstance(data, dict)
+ and data.get("version") == _SCHEMA_VERSION
+ and isinstance(data.get("items"), dict)
+ ):
+ # Written over an illegible store, so what it does NOT say is not evidence.
+ if data.get(_TAINT_KEY):
+ return data, False
+ # Every ENTRY has to be readable too, not just the container. A malformed value is
+ # dropped by the readers below, which reads as "this id is not archived" -- enough for
+ # clear() to delete an archived file. So one bad entry costs the store its trust, but
+ # the surviving entries are still returned: listing should keep the flags it can read,
+ # and only destructive callers need to refuse.
+ if all(_valid_entry(v) for v in data["items"].values()):
+ return data, True
+ logger.warning(
+ "gallery_flags.unreadable: %s has a malformed entry", _store_path(directory)
+ )
+ return data, False
+ logger.warning(
+ "gallery_flags.unreadable: %s has an unrecognised shape", _store_path(directory)
+ )
+ return _empty(), False
+ except FileNotFoundError:
+ return _empty(), True # no store yet is a legitimate "nothing is flagged"
+ except Exception as exc:
+ logger.warning("gallery_flags.read_failed: %s", exc)
+ return _empty(), False
+
+
+def _carry_taint(data: dict[str, Any], trusted: bool) -> dict[str, Any]:
+ """``data`` prepared for a rewrite, marked when the old contents were illegible.
+
+ Entry-level damage is repaired by ``_sanitize_entry``, so readable flags survive and the store
+ earns its trust back. CONTAINER damage (truncated JSON, a non-dict ``items``, an unknown
+ version) leaves nothing to carry: ``_load`` substitutes an empty map, and writing that plainly
+ turns "we cannot say what was archived" into "nothing is", which is what ``clear()`` deletes on.
+ So the replacement is marked and destructive callers keep failing closed. Listing, pinning,
+ archiving and restoring still work; ``clear(include_archived = True)`` is the way out, since it
+ spares nothing and so needs no flags.
+ """
+ if not trusted and not data.get("items"):
+ data[_TAINT_KEY] = True
+ return data
+
+
+def _save(directory: Path, data: dict[str, Any]) -> None:
+ """Atomic write (tmp + os.replace), so a crash mid-write never leaves a truncated store.
+
+ Raises on failure. A silent miss would let the API report a pin or archive it never stored,
+ which the UI has already applied optimistically, so the action would quietly undo on reload."""
+ path = _store_path(directory)
+ tmp = directory / f".{_STORE_NAME}.tmp-{os.getpid()}"
+ try:
+ with open(tmp, "w", encoding = "utf-8") as f:
+ json.dump(data, f, indent = 2)
+ os.replace(tmp, path)
+ except Exception as exc:
+ logger.warning("gallery_flags.write_failed: %s", exc)
+ try:
+ tmp.unlink(missing_ok = True)
+ except OSError:
+ pass
+ raise
+
+
+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)."""
+ try:
+ fd = os.open(str(directory / f"{_STORE_NAME}.lock"), os.O_CREAT | os.O_RDWR, 0o600)
+ except Exception:
+ yield
+ return
+ locked = False
+ try:
+ try:
+ if os.name == "nt":
+ import msvcrt
+ msvcrt.locking(fd, msvcrt.LK_LOCK, 1)
+ else:
+ import fcntl
+ fcntl.flock(fd, fcntl.LOCK_EX)
+ locked = True
+ except Exception:
+ pass # locking unavailable; the thread lock still applies
+ yield
+ 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
+ # has already written the flags or deleted the media, so raising here reports a failure for
+ # work that landed.
+ try:
+ if locked:
+ with contextlib.suppress(Exception):
+ if os.name == "nt":
+ import msvcrt
+ msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
+ else:
+ import fcntl
+ fcntl.flock(fd, fcntl.LOCK_UN)
+ finally:
+ os.close(fd)
+
+
+def exclusive(directory: Path):
+ """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
+ archive landing in that window would be classified active from the stale snapshot and deleted
+ 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):
+ yield
+
+
+def _entry(items: dict[str, Any], item_id: str) -> dict[str, Any]:
+ """One id's entry, normalized. A non-dict entry (hand-edited) reads as no flags."""
+ entry = items.get(item_id)
+ return entry if isinstance(entry, dict) else {}
+
+
+def read(directory: Path) -> dict[str, dict[str, Any]]:
+ """Every id's flags for one gallery, read once so a listing pass can sort without
+ re-opening the store per file. Fail-safe: an untrusted store reads as no flags, because a
+ lost pin beats a gallery that will not list. Use ``read_trusted`` before destructive work."""
+ with _lock:
+ items = _load(directory)[0].get("items", {})
+ return {k: v for k, v in items.items() if isinstance(v, dict)}
+
+
+def is_trusted(directory: Path) -> bool:
+ """Whether the store can be believed about what is NOT flagged."""
+ with _lock:
+ return _load(directory)[1]
+
+
+def reset_locked(directory: Path) -> None:
+ """Replace the store with an empty, trusted one. For a caller already inside ``exclusive()``.
+
+ Only ``clear(include_archived = True)`` does this, and only after removing every item we own:
+ the taint protects files from a delete that cannot prove them active, and none are left. Without
+ it the escape hatch is not one, since the corrupt file survives the wipe and every later clear
+ still refuses, new media included."""
+ _save(directory, _empty())
+
+
+def read_trusted(directory: Path) -> dict[str, dict[str, Any]]:
+ """``read``, but raises FlagsUnavailable instead of pretending nothing is flagged. For callers
+ that delete based on a flag, where guessing "not archived" destroys the archive."""
+ with _lock:
+ data, trusted = _load(directory)
+ if not trusted:
+ raise FlagsUnavailable(f"{_store_path(directory)} could not be read")
+ items = data.get("items", {})
+ return {k: v for k, v in items.items() if isinstance(v, dict)}
+
+
+def _pinned_at(entry: dict[str, Any]) -> Optional[float]:
+ """The entry's pin time as a usable float, or None when it is absent or unusable.
+
+ JSON integers are unbounded, so a hand-edited ``pinned_at`` of a few hundred digits overflows
+ ``float()``. That is read at listing time, from a store whose whole contract is to degrade to
+ "no flags" rather than raise, so an unconvertible value must read as unpinned instead of
+ turning every gallery request into a 500. NaN / infinity are refused for the same reason: they
+ would poison the sort rather than fail it."""
+ value = entry.get("pinned_at")
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ return None
+ try:
+ pinned_at = float(value)
+ except (OverflowError, ValueError):
+ return None
+ return pinned_at if math.isfinite(pinned_at) else None
+
+
+def flags_for(items: dict[str, dict[str, Any]], item_id: str) -> dict[str, Any]:
+ """The public record fields for one id, from an already-read ``items`` map."""
+ entry = _entry(items, item_id)
+ return {
+ # Reported through the same conversion the sort uses, so a value the ordering cannot use
+ # never shows as a pin the user then cannot explain.
+ "pinned": _pinned_at(entry) is not None,
+ "archived": bool(entry.get("archived")),
+ }
+
+
+def pin_rank(items: dict[str, dict[str, Any]], item_id: str) -> float:
+ """Sort key for the pinned group: most recently pinned first. Unpinned sorts last."""
+ pinned_at = _pinned_at(_entry(items, item_id))
+ return pinned_at if pinned_at is not None else float("-inf")
+
+
+def is_archived(items: dict[str, dict[str, Any]], item_id: str) -> bool:
+ return bool(_entry(items, item_id).get("archived"))
+
+
+def set_flags(
+ directory: Path,
+ item_id: str,
+ *,
+ pinned: Optional[bool] = None,
+ archived: Optional[bool] = None,
+) -> dict[str, Any]:
+ """Patch one id's flags; ``None`` leaves that flag alone. Returns the resulting flags.
+
+ Pinning stamps ``pinned_at`` (wall clock) so the pinned group can sort most-recent-first;
+ unpinning drops the key rather than storing False, keeping the store to only what is set.
+ An id whose flags all end up default is removed entirely, so toggling something on and off
+ again leaves no residue."""
+ with _lock, _file_lock(directory):
+ return set_flags_locked(directory, item_id, pinned = pinned, archived = archived)
+
+
+def set_flags_locked(
+ directory: Path,
+ item_id: str,
+ *,
+ pinned: Optional[bool] = None,
+ archived: Optional[bool] = None,
+) -> dict[str, Any]:
+ """``set_flags`` for a caller already inside ``exclusive()``, so the ownership check and the
+ write land as one step. Separate for the same per-descriptor lock reason as ``forget_locked``."""
+ import time
+
+ # A write REPAIRS the store rather than preserving what made it untrusted. Merging the bad
+ # entry straight back would leave every later clear() refused until someone fixed the file by
+ # hand, and refusing here instead would leave the user unable to pin anything at all. Dropping
+ # only the unreadable entries keeps the flags that still mean something.
+ data = _carry_taint(*_load(directory))
+ items: dict[str, Any] = {}
+ for key, value in data.get("items", {}).items():
+ clean = _sanitize_entry(value)
+ if clean is not None:
+ items[key] = clean
+ data["items"] = items
+ entry = dict(_entry(items, item_id))
+ if pinned is not None:
+ if pinned:
+ # Strictly ahead of every stamp stored, not just the wall clock: Windows advances
+ # time.time() in ~16 ms steps, so two pins a click apart landed on the same value and
+ # "most recently pinned leads" stopped holding for exactly the case the client
+ # serializes its PATCHes to preserve.
+ latest = max(
+ (_pinned_at(v) for v in items.values() if _pinned_at(v) is not None),
+ default = float("-inf"),
+ )
+ now = time.time()
+ nudged = math.nextafter(latest, math.inf) if latest != float("-inf") else now
+ # A store holding the largest finite float nudges to infinity, which json writes and
+ # _pinned_at then refuses, so the pin just reported would read back unset AND take the
+ # store's trust with it. Tie instead: those two fall back to mtime, which costs an
+ # ordering rather than the store.
+ entry["pinned_at"] = (
+ now if now > latest else (nudged if math.isfinite(nudged) else latest)
+ )
+ else:
+ entry.pop("pinned_at", None)
+ if archived is not None:
+ if archived:
+ entry["archived"] = True
+ else:
+ entry.pop("archived", None)
+ if entry:
+ items[item_id] = entry
+ else:
+ items.pop(item_id, None)
+ _save(directory, data)
+ return {"pinned": entry.get("pinned_at") is not None, "archived": bool(entry.get("archived"))}
+
+
+def forget(directory: Path, item_ids) -> None:
+ """Drop flags for ids that no longer exist, so a deleted image cannot hand its pin to a
+ future id and the store cannot grow without bound. No-op when nothing is stored."""
+ with _lock, _file_lock(directory):
+ forget_locked(directory, item_ids)
+
+
+def forget_locked(directory: Path, item_ids) -> None:
+ """``forget`` for a caller already inside ``exclusive()``. Separate because the cross-process
+ lock is per file descriptor: re-taking it on a second descriptor in the same process blocks
+ against the one already held, so the nested call would deadlock rather than recurse."""
+ ids = {i for i in item_ids if i}
+ if not ids:
+ return
+ data = _load(directory)[0]
+ items = data.get("items", {})
+ if not any(i in items for i in ids):
+ return # nothing stored for these ids: skip the write entirely
+ for item_id in ids:
+ items.pop(item_id, None)
+ try:
+ _save(directory, data)
+ except Exception as exc: # noqa: BLE001 -- the media is already gone; a stale row is harmless
+ logger.warning("gallery_flags.prune_failed: %s", exc)
diff --git a/studio/backend/core/inference/image_gallery.py b/studio/backend/core/inference/image_gallery.py
index 193b9be2f5d..3750db95414 100644
--- a/studio/backend/core/inference/image_gallery.py
+++ b/studio/backend/core/inference/image_gallery.py
@@ -22,6 +22,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
@@ -83,11 +84,19 @@ def save(image: Any, meta: dict[str, Any]) -> dict[str, Any]:
return _record(image_id, meta)
-def _record(image_id: str, meta: dict[str, Any]) -> dict[str, Any]:
+def _record(
+ image_id: str,
+ meta: dict[str, Any],
+ flags: Optional[dict[str, dict[str, Any]]] = None,
+) -> dict[str, Any]:
+ # Flags are library state, not recipe: they come from the sidecar store, never the PNG chunk.
return {
**meta,
"id": image_id,
"url": f"/api/inference/images/gallery/{image_id}/file",
+ **gallery_flags.flags_for(
+ flags if flags is not None else gallery_flags.read(gallery_dir()), image_id
+ ),
}
@@ -157,12 +166,17 @@ def list_images(
offset: int = 0,
*,
valid: Optional[Callable[[dict[str, Any]], bool]] = None,
+ archived: bool = False,
) -> list[dict[str, Any]]:
- """A newest-first window of images for infinite scroll.
+ """A window of images for infinite scroll: pinned first (most recently pinned leading), then
+ newest-first by file mtime.
- Ordered by file mtime (a cheap stat ~= generation order), so a large gallery isn't opened in
- full just to sort; only the window's recipes are read. limit=None returns everything from
- ``offset`` on.
+ mtime is a cheap stat ~= generation order, so a large gallery isn't opened in full just to
+ sort; only the window's recipes are read. limit=None returns everything from ``offset`` on.
+
+ ``archived`` selects WHICH shelf to page over, it does not widen one: False lists only active
+ images, True lists only archived ones. The archived section needs its own scrollable page, so
+ a chat-style "include archived" flag would not do.
``valid`` (optional) filters records BEFORE pagination, so ``offset`` / ``limit`` and has_more
all count over the accepted-record domain. Pass the route's schema validator: a record with
@@ -172,7 +186,11 @@ def list_images(
paths = list(gallery_dir().glob("*.png"))
except OSError:
return []
- paths.sort(key = _mtime, reverse = True)
+ flags = gallery_flags.read(gallery_dir())
+ # Both the shelf split and the pin sort run on file stems, BEFORE any recipe is read, so they
+ # cost one dict lookup per file and leave the early break below intact.
+ paths = [p for p in paths if gallery_flags.is_archived(flags, p.stem) == archived]
+ paths.sort(key = lambda p: (gallery_flags.pin_rank(flags, p.stem), _mtime(p)), reverse = True)
# Page over READABLE records, not raw files: filtering a foreign PNG out of an already-sliced window would drop valid images and make has_more
# wrong. Known limit: this re-reads headers from newest down to `offset+limit` per page, so a deep scroll is O(offset) header-opens.
want = None if limit is None else offset + limit
@@ -181,7 +199,7 @@ def list_images(
meta = _read_meta(path)
if meta is None: # not one of ours (no recipe chunk)
continue
- record = _record(path.stem, meta)
+ record = _record(path.stem, meta, flags)
if valid is not None and not valid(record): # present but schema-invalid
continue
records.append(record)
@@ -190,6 +208,28 @@ def list_images(
return records[offset:] if limit is None else records[offset : offset + limit]
+def set_flags(
+ image_id: str,
+ *,
+ pinned: Optional[bool] = None,
+ archived: Optional[bool] = None,
+) -> Optional[dict[str, Any]]:
+ """Patch one image's pin/archive flags and return its updated record, or None when the id is
+ not a Studio-owned image. Ownership-gated like delete: a guessed stem for a hand-dropped
+ foreign PNG must not become flaggable (and so listable under a shelf we own)."""
+ # Ownership check and write under one lock, so a concurrent clear cannot delete the file
+ # between them and leave this reporting success for an image that is already gone.
+ with gallery_flags.exclusive(gallery_dir()):
+ path = owned_image_path(image_id)
+ if path is None:
+ return None
+ gallery_flags.set_flags_locked(gallery_dir(), image_id, pinned = pinned, archived = archived)
+ meta = _read_meta(path)
+ if meta is None: # raced a delete between the guard and the read
+ return None
+ return _record(image_id, meta)
+
+
def delete(image_id: str) -> bool:
path = image_path(image_id)
if path is None:
@@ -199,27 +239,55 @@ def delete(image_id: str) -> bool:
return False
try:
path.unlink()
- return True
except OSError as exc:
logger.warning("image_gallery.delete_failed: %s", exc)
return False
+ # Drop the flags with the file, so the id cannot hand a stale pin to anything and the store
+ # cannot grow forever.
+ gallery_flags.forget(gallery_dir(), [image_id])
+ return True
+
+def clear(include_archived: bool = False) -> int:
+ """Delete Studio-owned gallery PNGs (readable recipe chunk); return how many were removed.
-def clear() -> int:
- """Delete every Studio-owned gallery PNG (readable recipe chunk); return how many were removed.
+ Archived images are SPARED by default: archiving is how a user sets something aside, so a
+ "clear the gallery" action that destroyed the archive would defeat it. Pass
+ include_archived=True to remove those too.
+
+ Raises FlagsUnavailable when the archive has to be spared but the flag store cannot be read.
+ Fail CLOSED: read() answers "nothing is archived" for an unreadable store, which here would
+ quietly delete the very archive this promises to keep.
Foreign PNGs are preserved: list_images already hides them, so clear must not destroy them."""
removed = 0
- try:
- paths = list(gallery_dir().glob("*.png"))
- except OSError:
- return 0
- for path in paths:
- if _read_meta(path) is None: # foreign / not ours
- continue
+ directory = gallery_dir()
+ # Hold the flag lock across the whole read-then-delete: an archive landing mid-loop would
+ # otherwise be judged active from the stale snapshot and deleted, after its PATCH had already
+ # reported success.
+ with gallery_flags.exclusive(directory):
+ # Read flags BEFORE listing: nothing is unlinked if the store turns out to be untrusted.
+ flags = {} if include_archived else gallery_flags.read_trusted(directory)
try:
- path.unlink()
- removed += 1
+ paths = list(directory.glob("*.png"))
except OSError:
- continue
+ return 0
+ cleared: list[str] = []
+ for path in paths:
+ if _read_meta(path) is None: # foreign / not ours
+ continue
+ if not include_archived and gallery_flags.is_archived(flags, path.stem):
+ continue
+ try:
+ path.unlink()
+ removed += 1
+ cleared.append(path.stem)
+ except OSError:
+ continue
+ # Nothing left for an unreadable store to protect once every image we own is gone, so this is
+ # where the escape hatch escapes: replace it, or every later default clear still refuses.
+ 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/video_gallery.py b/studio/backend/core/inference/video_gallery.py
index a2b7f7b4b20..1bbf1b79e2d 100644
--- a/studio/backend/core/inference/video_gallery.py
+++ b/studio/backend/core/inference/video_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
@@ -56,11 +57,19 @@ def save(mp4_bytes: bytes, meta: dict[str, Any]) -> dict[str, Any]:
return _record(video_id, meta)
-def _record(video_id: str, meta: dict[str, Any]) -> dict[str, Any]:
+def _record(
+ video_id: str,
+ meta: dict[str, Any],
+ flags: Optional[dict[str, dict[str, Any]]] = None,
+) -> dict[str, Any]:
+ # Flags are library state, not recipe: they come from the .flags.json store, never the sidecar.
return {
**meta,
"id": video_id,
"url": f"/api/inference/video/gallery/{video_id}/file",
+ **gallery_flags.flags_for(
+ flags if flags is not None else gallery_flags.read(gallery_dir()), video_id
+ ),
}
@@ -314,11 +323,16 @@ def list_videos(
offset: int = 0,
*,
valid: Optional[Callable[[dict[str, Any]], bool]] = None,
+ archived: bool = False,
) -> list[dict[str, Any]]:
- """A newest-first window of videos for infinite scroll.
+ """A window of videos for infinite scroll: pinned first (most recently pinned leading), then
+ newest-first by MP4 mtime.
- Ordered by MP4 mtime (a cheap stat ~= generation order); only the window's sidecars are read.
- limit=None returns everything from ``offset`` on. A file without its pair is skipped.
+ mtime is a cheap stat ~= generation order; only the window's sidecars are read. limit=None
+ returns everything from ``offset`` on. A file without its pair is skipped.
+
+ ``archived`` selects WHICH shelf to page over, it does not widen one: False lists only active
+ clips, True lists only archived ones. The archived section needs its own scrollable page.
``valid`` (optional) filters records BEFORE pagination, so ``offset`` / ``limit`` and has_more
all count over the accepted-record domain. Pass the route's schema validator: a sidecar that
@@ -328,7 +342,11 @@ def list_videos(
paths = list(gallery_dir().glob("*.mp4"))
except OSError:
return []
- paths.sort(key = _mtime, reverse = True)
+ flags = gallery_flags.read(gallery_dir())
+ # Shelf split and pin sort run on file stems, BEFORE any sidecar is read, so they cost one
+ # dict lookup per file and leave the early break below intact.
+ paths = [p for p in paths if gallery_flags.is_archived(flags, p.stem) == archived]
+ paths.sort(key = lambda p: (gallery_flags.pin_rank(flags, p.stem), _mtime(p)), reverse = True)
# Page over READABLE records, not raw files: filtering an orphan MP4 out of an already-sliced window would drop valid videos and make has_more wrong.
want = None if limit is None else offset + limit
records = []
@@ -336,7 +354,7 @@ def list_videos(
meta = _read_meta(_sidecar_path(path.stem))
if meta is None: # orphan mp4 (no readable sidecar)
continue
- record = _record(path.stem, meta)
+ record = _record(path.stem, meta, flags)
if valid is not None and not valid(record): # parses but schema-invalid
continue
records.append(record)
@@ -345,6 +363,27 @@ def list_videos(
return records[offset:] if limit is None else records[offset : offset + limit]
+def set_flags(
+ video_id: str,
+ *,
+ pinned: Optional[bool] = None,
+ archived: Optional[bool] = None,
+) -> Optional[dict[str, Any]]:
+ """Patch one clip's pin/archive flags and return its updated record, or None when the id is
+ not a Studio-owned clip. Ownership-gated like delete: a guessed stem for a hand-dropped or
+ orphan MP4 must not become flaggable."""
+ # Ownership check and write under one lock, so a concurrent clear cannot delete the pair
+ # between them and leave this reporting success for a clip that is already gone.
+ with gallery_flags.exclusive(gallery_dir()):
+ if owned_video_path(video_id) is None:
+ return None
+ gallery_flags.set_flags_locked(gallery_dir(), video_id, pinned = pinned, archived = archived)
+ meta = _read_meta(_sidecar_path(video_id))
+ if meta is None: # raced a delete between the guard and the read
+ return None
+ return _record(video_id, meta)
+
+
def delete(video_id: str) -> bool:
"""Remove both files of an owned pair; True if the MP4 existed and was ours."""
path = video_path(video_id)
@@ -365,29 +404,56 @@ def delete(video_id: str) -> bool:
_sidecar_path(video_id).unlink()
except OSError:
pass
+ # Drop the flags with the pair, so the id cannot hand a stale pin to anything.
+ gallery_flags.forget(gallery_dir(), [video_id])
return True
-def clear() -> int:
- """Delete every Studio-owned gallery pair (readable sidecar); return how many were removed.
+def clear(include_archived: bool = False) -> int:
+ """Delete Studio-owned gallery pairs (readable sidecar); return how many were removed.
+
+ Archived clips are SPARED by default: archiving is how a user sets something aside, so a
+ "clear the gallery" action that destroyed the archive would defeat it. Pass
+ include_archived=True to remove those too.
+
+ Raises FlagsUnavailable when the archive has to be spared but the flag store cannot be read.
+ Fail CLOSED: read() answers "nothing is archived" for an unreadable store, which here would
+ quietly delete the very archive this promises to keep.
Foreign/orphan MP4s are preserved: list_videos already hides them, so clear must not destroy them."""
removed = 0
- try:
- paths = list(gallery_dir().glob("*.mp4"))
- except OSError:
- return 0
- for path in paths:
- if _read_meta(_sidecar_path(path.stem)) is None: # orphan / not ours
- continue
- # mp4 first; if it can't be unlinked, leave the sidecar so the video stays listable.
- try:
- path.unlink()
- except OSError:
- continue
- removed += 1
+ directory = gallery_dir()
+ # Hold the flag lock across the whole read-then-delete: an archive landing mid-loop would
+ # otherwise be judged active from the stale snapshot and deleted, after its PATCH had already
+ # reported success.
+ with gallery_flags.exclusive(directory):
+ # Read flags BEFORE listing: nothing is unlinked if the store turns out to be untrusted.
+ flags = {} if include_archived else gallery_flags.read_trusted(directory)
try:
- _sidecar_path(path.stem).unlink()
+ paths = list(directory.glob("*.mp4"))
except OSError:
- pass
+ return 0
+ cleared: list[str] = []
+ for path in paths:
+ if _read_meta(_sidecar_path(path.stem)) is None: # orphan / not ours
+ continue
+ if not include_archived and gallery_flags.is_archived(flags, path.stem):
+ continue
+ # mp4 first; if it can't be unlinked, leave the sidecar so the video stays listable.
+ try:
+ path.unlink()
+ except OSError:
+ continue
+ removed += 1
+ cleared.append(path.stem)
+ try:
+ _sidecar_path(path.stem).unlink()
+ except OSError:
+ pass
+ # Nothing left for an unreadable store to protect once every clip we own is gone, so this is
+ # where the escape hatch escapes: replace it, or every later default clear still refuses.
+ 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/models/inference.py b/studio/backend/models/inference.py
index 9674437a6c8..59cc7a30110 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -2895,6 +2895,16 @@ class GalleryImage(BaseModel):
None, description = "How many reference images the reference workflow used"
)
created_at: float = Field(..., description = "Creation time (epoch seconds)")
+ # Library state, not recipe: stored beside the PNG, so older files simply read as unset.
+ pinned: bool = Field(False, description = "Pinned to the front of the gallery")
+ archived: bool = Field(False, description = "Moved to the archived shelf, hidden from the strip")
+
+
+class GalleryFlagsPatch(BaseModel):
+ """Partial update of one gallery item's pin/archive flags; omitted fields are left alone."""
+
+ pinned: Optional[bool] = Field(None, description = "Pin (True) or unpin (False) the item")
+ archived: Optional[bool] = Field(None, description = "Archive (True) or restore (False) the item")
class DiffusionGenerateResponse(BaseModel):
@@ -3584,6 +3594,9 @@ class GalleryVideo(BaseModel):
None, description = "Offload policy actually engaged: none | group | model | sequential"
)
created_at: str = Field(..., description = "Creation time (ISO 8601 timestamp)")
+ # Library state, not recipe: stored beside the clip, so older sidecars simply read as unset.
+ pinned: bool = Field(False, description = "Pinned to the front of the gallery")
+ archived: bool = Field(False, description = "Moved to the archived shelf, hidden from the strip")
class VideoGenerateResponse(BaseModel):
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index d33f51b7e47..903f320844f 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -2174,6 +2174,7 @@ from models.inference import (
DiffusionDownloadPlanResponse,
DiffusionInferenceInfoResponse,
DiffusionLoadProgressResponse,
+ GalleryFlagsPatch,
GalleryImage,
GalleryListResponse,
ImageGenerationRequest,
@@ -21678,6 +21679,7 @@ async def generate_diffusion_image(
async def list_gallery_images(
limit: int = 50,
offset: int = 0,
+ archived: bool = False,
current_subject: str = Depends(get_current_subject),
):
from pydantic import ValidationError
@@ -21698,7 +21700,11 @@ async def list_gallery_images(
# Fetch one extra to learn whether more remain, without a second scan.
records = await asyncio.to_thread(
- image_gallery.list_images, limit + 1, offset, valid = _valid_gallery_image
+ image_gallery.list_images,
+ limit + 1,
+ offset,
+ valid = _valid_gallery_image,
+ archived = archived,
)
has_more = len(records) > limit
images = [GalleryImage(**r) for r in records[:limit]]
@@ -21724,6 +21730,29 @@ async def get_gallery_image_file(
)
+@studio_router.patch("/images/gallery/{image_id}", response_model = GalleryImage)
+async def update_gallery_image_flags(
+ image_id: str,
+ patch: GalleryFlagsPatch,
+ current_subject: str = Depends(get_current_subject),
+):
+ """Pin/unpin or archive/restore one image. Omitted fields are left alone."""
+ from core.inference import image_gallery
+
+ try:
+ record = await asyncio.to_thread(
+ image_gallery.set_flags, image_id, pinned = patch.pinned, archived = patch.archived
+ )
+ except OSError as exc:
+ # The client already applied this optimistically, so a silent miss would look like it stuck
+ # and then quietly undo on reload.
+ logger.warning("image_gallery.set_flags_failed: %s", exc)
+ raise HTTPException(status_code = 500, detail = "Could not save the change to this image.")
+ if record is None:
+ raise HTTPException(status_code = 404, detail = "Image not found.")
+ return GalleryImage(**record)
+
+
@studio_router.delete("/images/gallery/{image_id}")
async def delete_gallery_image(image_id: str, current_subject: str = Depends(get_current_subject)):
from core.inference import image_gallery
@@ -21737,7 +21766,18 @@ async def delete_gallery_image(image_id: str, current_subject: str = Depends(get
@studio_router.delete("/images/gallery")
async def clear_gallery_images(current_subject: str = Depends(get_current_subject)):
from core.inference import image_gallery
- removed = await asyncio.to_thread(image_gallery.clear)
+ from core.inference.gallery_flags import FlagsUnavailable
+
+ try:
+ removed = await asyncio.to_thread(image_gallery.clear)
+ except FlagsUnavailable as exc:
+ # Refuse rather than delete the archive we cannot prove is archived.
+ logger.warning("image_gallery.clear_blocked: %s", exc)
+ raise HTTPException(
+ status_code = 503,
+ detail = "Could not read the gallery's pin/archive data, so clearing was stopped to "
+ "avoid deleting archived images.",
+ )
return {"removed": removed}
diff --git a/studio/backend/routes/video.py b/studio/backend/routes/video.py
index 1886f650523..9e55083392b 100644
--- a/studio/backend/routes/video.py
+++ b/studio/backend/routes/video.py
@@ -31,6 +31,7 @@ from auth.authentication import get_current_subject
from loggers import get_logger
from models.inference import (
DiffusionDownloadPlanResponse,
+ GalleryFlagsPatch,
GalleryVideo,
VideoGalleryListResponse,
VideoGenerateProgressResponse,
@@ -374,6 +375,7 @@ async def unload_video_model(current_subject: str = Depends(get_current_subject)
async def list_gallery_videos(
limit: int = 50,
offset: int = 0,
+ archived: bool = False,
current_subject: str = Depends(get_current_subject),
):
from core.inference import video_gallery
@@ -391,7 +393,11 @@ async def list_gallery_videos(
# Fetch one extra to learn whether more remain, without a second scan.
records = await asyncio.to_thread(
- video_gallery.list_videos, limit + 1, offset, valid = _valid_gallery_video
+ video_gallery.list_videos,
+ limit + 1,
+ offset,
+ valid = _valid_gallery_video,
+ archived = archived,
)
has_more = len(records) > limit
videos = [GalleryVideo(**r) for r in records[:limit]]
@@ -539,6 +545,33 @@ def _forget_terminal_video(video_id: Optional[str]) -> None:
logger.debug(f"Could not clear the terminal video record for {video_id!r}: {e}")
[email protected]("/video/gallery/{video_id}", response_model = GalleryVideo)
+async def update_gallery_video_flags(
+ video_id: str,
+ patch: GalleryFlagsPatch,
+ current_subject: str = Depends(get_current_subject),
+):
+ """Pin/unpin or archive/restore one clip. Omitted fields are left alone."""
+ from core.inference import video_gallery
+
+ try:
+ record = await asyncio.to_thread(
+ video_gallery.set_flags, video_id, pinned = patch.pinned, archived = patch.archived
+ )
+ except OSError as exc:
+ # The client already applied this optimistically, so a silent miss would look like it stuck
+ # and then quietly undo on reload.
+ logger.warning("video_gallery.set_flags_failed: %s", exc)
+ raise HTTPException(status_code = 500, detail = "Could not save the change to this video.")
+ if record is None:
+ raise HTTPException(status_code = 404, detail = "Video not found.")
+ # Archiving takes the clip off the strip, so the completed-job record must go with it: the page
+ # merges that snapshot on mount, which would keep resurrecting the clip it just archived.
+ if patch.archived:
+ _forget_terminal_video(video_id)
+ return GalleryVideo(**record)
+
+
@router.delete("/video/gallery/{video_id}")
async def delete_gallery_video(video_id: str, current_subject: str = Depends(get_current_subject)):
from core.inference import video_gallery
@@ -553,8 +586,18 @@ async def delete_gallery_video(video_id: str, current_subject: str = Depends(get
@router.delete("/video/gallery")
async def clear_gallery_videos(current_subject: str = Depends(get_current_subject)):
from core.inference import video_gallery
+ from core.inference.gallery_flags import FlagsUnavailable
- removed = await asyncio.to_thread(video_gallery.clear)
+ try:
+ removed = await asyncio.to_thread(video_gallery.clear)
+ except FlagsUnavailable as exc:
+ # Refuse rather than delete the archive we cannot prove is archived.
+ logger.warning("video_gallery.clear_blocked: %s", exc)
+ raise HTTPException(
+ status_code = 503,
+ detail = "Could not read the gallery's pin/archive data, so clearing was stopped to "
+ "avoid deleting archived videos.",
+ )
# Clear-all takes the terminal record's clip with it whatever its id.
_forget_terminal_video(None)
return {"removed": removed}
diff --git a/studio/backend/tests/test_diffusion_routes.py b/studio/backend/tests/test_diffusion_routes.py
index 243fb2ca711..95a19bda228 100644
--- a/studio/backend/tests/test_diffusion_routes.py
+++ b/studio/backend/tests/test_diffusion_routes.py
@@ -229,8 +229,12 @@ def client(monkeypatch, tmp_path):
offset = 0,
*,
valid = None,
+ archived = False,
):
- ordered = sorted(store.values(), key = lambda r: r.get("created_at", 0.0), reverse = True)
+ # Model the real shelf split and pinned-first order, not just the signature: a double that
+ # ignored them would pass while the route paged the wrong set.
+ ordered = [r for r in store.values() if bool(r.get("archived")) == archived]
+ ordered.sort(key = lambda r: (bool(r.get("pinned")), r.get("created_at", 0.0)), reverse = True)
if valid is not None:
ordered = [r for r in ordered if valid(r)]
return ordered[offset:] if limit is None else ordered[offset : offset + limit]
diff --git a/studio/backend/tests/test_gallery_flags.py b/studio/backend/tests/test_gallery_flags.py
new file mode 100644
index 00000000000..6729f1228d5
--- /dev/null
+++ b/studio/backend/tests/test_gallery_flags.py
@@ -0,0 +1,382 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Unit tests for the gallery pin/archive flag store: patch semantics, the fail-safe read,
+atomic writes and orphan pruning."""
+
+from __future__ import annotations
+
+import json
+import math
+import os
+
+import pytest
+
+import core.inference.gallery_flags as flags
+
+
+def gdir(tmp_path):
+ d = tmp_path / "images"
+ d.mkdir()
+ return d
+
+
+def _store(directory):
+ return directory / ".flags.json"
+
+
+def test_unknown_id_reads_as_no_flags(gdir):
+ items = flags.read(gdir)
+ assert items == {}
+ assert flags.flags_for(items, "nope") == {"pinned": False, "archived": False}
+ assert flags.is_archived(items, "nope") is False
+
+
+def test_missing_store_is_not_created_by_reading(gdir):
+ flags.read(gdir)
+ assert not _store(gdir).exists()
+
+
+def test_set_and_read_back_each_flag(gdir):
+ assert flags.set_flags(gdir, "a", pinned = True) == {"pinned": True, "archived": False}
+ assert flags.set_flags(gdir, "b", archived = True) == {"pinned": False, "archived": True}
+ items = flags.read(gdir)
+ assert flags.flags_for(items, "a") == {"pinned": True, "archived": False}
+ assert flags.is_archived(items, "b") is True
+
+
+def test_none_leaves_the_other_flag_alone(gdir):
+ flags.set_flags(gdir, "a", pinned = True, archived = True)
+ # Patch only `archived`; the pin must survive.
+ assert flags.set_flags(gdir, "a", archived = False) == {"pinned": True, "archived": False}
+
+
+def test_toggling_everything_off_removes_the_entry(gdir):
+ flags.set_flags(gdir, "a", pinned = True)
+ flags.set_flags(gdir, "a", pinned = False)
+ # No residue: an id back at its defaults should not keep a row.
+ assert flags.read(gdir) == {}
+
+
+def test_pin_rank_orders_most_recently_pinned_first(gdir):
+ flags.set_flags(gdir, "first", pinned = True)
+ flags.set_flags(gdir, "second", pinned = True)
+ items = flags.read(gdir)
+ assert flags.pin_rank(items, "second") > flags.pin_rank(items, "first")
+ # An unpinned id must sort behind every pinned one.
+ assert flags.pin_rank(items, "unpinned") == float("-inf")
+
+
+def test_a_coarse_clock_still_orders_two_pins(gdir, monkeypatch):
+ # Windows advances time.time() in ~16 ms steps, so two pins a click apart read the same clock
+ # and the group loses the order the client serializes its PATCHes to preserve.
+ import time as _time
+
+ monkeypatch.setattr(_time, "time", lambda: 1000.0)
+ flags.set_flags(gdir, "first", pinned = True)
+ flags.set_flags(gdir, "second", pinned = True)
+ flags.set_flags(gdir, "third", pinned = True)
+ items = flags.read(gdir)
+ ranks = [flags.pin_rank(items, i) for i in ("first", "second", "third")]
+ assert ranks[0] < ranks[1] < ranks[2], ranks
+ # Re-pinning an already pinned id still moves it to the front of the group.
+ flags.set_flags(gdir, "first", pinned = True)
+ items = flags.read(gdir)
+ assert flags.pin_rank(items, "first") > flags.pin_rank(items, "third")
+
+
+def test_a_pin_never_stores_a_non_finite_timestamp(gdir):
+ # The nudge must not manufacture the value _pinned_at refuses: the largest finite float nudges
+ # to infinity, which reads back unpinned and leaves the store untrusted after a 200.
+ import sys
+
+ _store(gdir).write_text(
+ json.dumps({"version": 1, "items": {"huge": {"pinned_at": sys.float_info.max}}}),
+ encoding = "utf-8",
+ )
+ assert flags.set_flags(gdir, "a", pinned = True) == {"pinned": True, "archived": False}
+ items = flags.read_trusted(gdir) # must not raise: the store is still readable
+ assert flags.flags_for(items, "a")["pinned"] is True
+ assert math.isfinite(flags.pin_rank(items, "a"))
+
+
+ "raw",
+ [
+ "not json at all",
+ "[]", # right type, wrong shape
+ '{"version": 1, "items": []}', # items must be a mapping
+ '{"version": 99, "items": {"a": {}}}', # unknown schema version
+ ],
+)
+def test_a_corrupt_store_degrades_to_no_flags(gdir, raw):
+ # Losing a pin beats refusing to list the gallery, so every unreadable store reads empty.
+ _store(gdir).write_text(raw, encoding = "utf-8")
+ assert flags.read(gdir) == {}
+
+
+def test_a_corrupt_store_is_overwritten_by_the_next_write(gdir):
+ _store(gdir).write_text("garbage", encoding = "utf-8")
+ flags.set_flags(gdir, "a", pinned = True)
+ items = flags.read(gdir)
+ assert set(items) == {"a"}
+ assert flags.flags_for(items, "a") == {"pinned": True, "archived": False}
+
+
+def test_a_non_dict_entry_reads_as_no_flags(gdir):
+ _store(gdir).write_text(
+ json.dumps({"version": 1, "items": {"a": "hand edited"}}), encoding = "utf-8"
+ )
+ items = flags.read(gdir)
+ assert flags.flags_for(items, "a") == {"pinned": False, "archived": False}
+
+
+def test_forget_prunes_only_the_named_ids(gdir):
+ flags.set_flags(gdir, "keep", pinned = True)
+ flags.set_flags(gdir, "drop", archived = True)
+ flags.forget(gdir, ["drop", "never-existed"])
+ items = flags.read(gdir)
+ assert set(items) == {"keep"}
+
+
+def test_forget_on_an_empty_store_writes_nothing(gdir):
+ flags.forget(gdir, ["a"])
+ assert not _store(gdir).exists()
+
+
+def test_writes_leave_no_temp_files_behind(gdir):
+ flags.set_flags(gdir, "a", pinned = True)
+ flags.forget(gdir, ["a"])
+ # The tmp is renamed into place, so only the store (and its lock) may remain.
+ leftovers = {p.name for p in gdir.iterdir()} - {".flags.json", ".flags.json.lock"}
+ assert leftovers == set()
+
+
+def test_read_trusted_raises_on_a_corrupt_store(gdir):
+ _store(gdir).write_text("garbage", encoding = "utf-8")
+ with pytest.raises(flags.FlagsUnavailable):
+ flags.read_trusted(gdir)
+
+
+def test_read_trusted_accepts_a_missing_store(gdir):
+ # No store yet genuinely means nothing is flagged, which is safe to act on.
+ assert flags.read_trusted(gdir) == {}
+
+
+def test_set_flags_raises_when_the_store_cannot_be_written(gdir, monkeypatch):
+ def _boom(*a, **k):
+ raise OSError("read-only filesystem")
+
+ monkeypatch.setattr(flags.os, "replace", _boom)
+ with pytest.raises(OSError):
+ flags.set_flags(gdir, "a", pinned = True)
+ # The failed write leaves no temp behind.
+ assert [p.name for p in gdir.iterdir() if p.name.startswith(".flags.json.tmp")] == []
+
+
+def test_forget_stays_best_effort_when_the_store_cannot_be_written(gdir, monkeypatch):
+ flags.set_flags(gdir, "a", pinned = True)
+ real = flags.os.replace
+ monkeypatch.setattr(flags.os, "replace", lambda *a, **k: (_ for _ in ()).throw(OSError("nope")))
+ # The media is already deleted by this point, so a stale row must not raise into the caller.
+ flags.forget(gdir, ["a"])
+ monkeypatch.setattr(flags.os, "replace", real)
+
+
+def test_a_corrupt_store_is_replaced_rather_than_blocking_new_flags(gdir):
+ # Refusing here would leave the user unable to pin anything until they hand-fixed the file.
+ _store(gdir).write_text("[]", encoding = "utf-8")
+ flags.set_flags(gdir, "a", archived = True)
+ assert flags.is_archived(flags.read(gdir), "a") is True
+
+
+def test_a_store_rebuilt_from_illegible_contents_stays_untrusted(gdir):
+ # The write must not be blocked, but the file it leaves is not evidence: the old contents were
+ # never read. Trusting it let an unrelated pin hand every archived image to the next clear().
+ _store(gdir).write_text("[]", encoding = "utf-8")
+ flags.set_flags(gdir, "a", archived = True)
+ with pytest.raises(flags.FlagsUnavailable):
+ flags.read_trusted(gdir)
+ # And it stays that way across further writes, rather than being laundered clean by the next one.
+ flags.set_flags(gdir, "b", pinned = True)
+ with pytest.raises(flags.FlagsUnavailable):
+ flags.read_trusted(gdir)
+
+
+def test_a_malformed_entry_taints_the_whole_store_for_trusted_reads(gdir):
+ # One bad value would otherwise be filtered out silently, reading as "this id is not archived",
+ # which is enough for clear() to delete an archived file.
+ _store(gdir).write_text(
+ json.dumps({"version": 1, "items": {"ok": {"archived": True}, "bad": "corrupt"}}),
+ encoding = "utf-8",
+ )
+ with pytest.raises(flags.FlagsUnavailable):
+ flags.read_trusted(gdir)
+ # The fail-safe reader still degrades quietly, so listing keeps working.
+ assert flags.read(gdir) == {"ok": {"archived": True}}
+
+
+def test_exclusive_serializes_against_set_flags(gdir):
+ # clear() decides from a snapshot then unlinks; an archive landing in that window must wait,
+ # not slip in and leave the file deleted after its PATCH reported success.
+ import threading
+
+ started = threading.Event()
+ landed = threading.Event()
+
+ def _archive():
+ started.set()
+ flags.set_flags(gdir, "a", archived = True)
+ landed.set()
+
+ with flags.exclusive(gdir):
+ worker = threading.Thread(target = _archive)
+ worker.start()
+ started.wait(timeout = 5)
+ # Held: the writer cannot land while the section is open.
+ assert not landed.wait(timeout = 0.5)
+ worker.join(timeout = 5)
+ assert landed.is_set()
+ assert flags.is_archived(flags.read(gdir), "a") is True
+
+
+def test_forget_locked_does_not_deadlock_inside_exclusive(gdir):
+ # The cross-process lock is per descriptor, so a nested forget() would block on the lock its
+ # own caller holds. clear() uses forget_locked for exactly this reason.
+ flags.set_flags(gdir, "a", pinned = True)
+ with flags.exclusive(gdir):
+ flags.forget_locked(gdir, ["a"])
+ assert flags.read(gdir) == {}
+
+
+ "pinned_at",
+ [
+ 10**400, # JSON ints are unbounded; this overflows float()
+ -(10**400),
+ float("nan"),
+ float("inf"),
+ "2026-01-01", # wrong type entirely
+ True, # bool is an int subclass, but not a timestamp
+ ],
+)
+def test_an_unusable_pin_time_reads_as_unpinned_instead_of_raising(gdir, pinned_at):
+ # These are read on every listing, and the store's contract is to degrade rather than raise.
+ _store(gdir).write_text(
+ json.dumps({"version": 1, "items": {"a": {"pinned_at": pinned_at}}}), encoding = "utf-8"
+ )
+ items = flags.read(gdir)
+ assert flags.pin_rank(items, "a") == float("-inf")
+ assert flags.flags_for(items, "a")["pinned"] is False
+
+
+def test_an_unusable_pin_time_does_not_hide_the_archived_flag(gdir):
+ _store(gdir).write_text(
+ json.dumps({"version": 1, "items": {"a": {"pinned_at": 10**400, "archived": True}}}),
+ encoding = "utf-8",
+ )
+ assert flags.is_archived(flags.read(gdir), "a") is True
+
+
+def test_a_write_repairs_a_store_with_a_malformed_entry(gdir):
+ # Merging the bad entry back would leave every later clear() refused until someone fixed the
+ # file by hand, which is the opposite of what a pin action should cost the user.
+ _store(gdir).write_text(
+ json.dumps({"version": 1, "items": {"good": {"archived": True}, "bad": "corrupt"}}),
+ encoding = "utf-8",
+ )
+ flags.set_flags(gdir, "new", pinned = True)
+ # Trusted again, so a default clear is no longer blocked.
+ items = flags.read_trusted(gdir)
+ assert set(items) == {"good", "bad", "new"}
+ # The readable flags survived the repair.
+ assert flags.is_archived(items, "good") is True
+ assert flags.flags_for(items, "new")["pinned"] is True
+ # The unreadable one is kept on the archive shelf rather than handed to the next clear().
+ assert flags.is_archived(items, "bad") is True
+
+
[email protected]("archived", [None, 1, "yes", []])
+def test_a_non_bool_archived_is_refused_rather_than_read_as_active(gdir, archived):
+ # Every reader turns a non-bool into "not archived", which is what clear() deletes on, so the
+ # store has to refuse instead of handing the file over.
+ _store(gdir).write_text(
+ json.dumps({"version": 1, "items": {"a": {"archived": archived}}}), encoding = "utf-8"
+ )
+ with pytest.raises(flags.FlagsUnavailable):
+ flags.read_trusted(gdir)
+
+
+def test_an_unusable_pin_time_also_costs_the_store_its_trust(gdir):
+ _store(gdir).write_text(
+ json.dumps({"version": 1, "items": {"a": {"pinned_at": 10**400}}}), encoding = "utf-8"
+ )
+ with pytest.raises(flags.FlagsUnavailable):
+ flags.read_trusted(gdir)
+
+
+def test_a_write_repairs_a_bad_field_without_dropping_the_archive(gdir):
+ # Dropping the whole entry over its pin time would hand an archived item to the next clear().
+ _store(gdir).write_text(
+ json.dumps({"version": 1, "items": {"a": {"pinned_at": 10**400, "archived": True}}}),
+ encoding = "utf-8",
+ )
+ flags.set_flags(gdir, "b", pinned = True)
+ items = flags.read_trusted(gdir)
+ assert flags.is_archived(items, "a") is True
+ assert flags.flags_for(items, "a")["pinned"] is False
+
+
+def test_a_write_never_repairs_an_archive_into_an_active_item(gdir):
+ # Dropping the unreadable flag would leave the store trusted and the item active, so the next
+ # default clear() would delete a file that was on the archive shelf. Resolve it the safe way.
+ _store(gdir).write_text(
+ json.dumps({"version": 1, "items": {"a": {"archived": None}}}), encoding = "utf-8"
+ )
+ flags.set_flags(gdir, "b", pinned = True)
+ items = flags.read_trusted(gdir)
+ assert flags.is_archived(items, "a") is True
+ assert flags.flags_for(items, "b")["pinned"] is True
+
+
+def test_an_absent_archived_key_is_not_treated_as_damage(gdir):
+ # Unarchiving removes the key, so absent means active and must stay active through a repair.
+ _store(gdir).write_text(
+ json.dumps({"version": 1, "items": {"a": {"pinned_at": 10**400}}}), encoding = "utf-8"
+ )
+ flags.set_flags(gdir, "b", pinned = True)
+ assert flags.is_archived(flags.read_trusted(gdir), "a") is False
+
+
+def test_archived_false_is_a_shape_we_write_and_stays_trusted(gdir):
+ _store(gdir).write_text(
+ json.dumps({"version": 1, "items": {"a": {"archived": False, "pinned_at": 1.0}}}),
+ encoding = "utf-8",
+ )
+ items = flags.read_trusted(gdir)
+ assert flags.flags_for(items, "a") == {"pinned": True, "archived": False}
+
+
+def test_a_filesystem_that_cannot_lock_still_completes_the_write(gdir, monkeypatch):
+ # Some network filesystems refuse to lock. Acquisition already tolerated that, but the matching
+ # unlock did not, so the store was written and the call still raised, failing a PATCH whose
+ # work had landed (and, through clear(), one that had already deleted files).
+ # Whichever primitive this platform uses: fcntl does not exist on Windows, and importing it
+ # unconditionally failed the test there rather than exercising the branch that runs.
+ if os.name == "nt":
+ import msvcrt as locking
+ primitive = "locking"
+ else:
+ import fcntl as locking
+ primitive = "flock"
+
+ def _unsupported(*_args):
+ raise OSError(45, "Operation not supported")
+
+ monkeypatch.setattr(locking, primitive, _unsupported)
+ assert flags.set_flags(gdir, "a", pinned = True) == {"pinned": True, "archived": False}
+ flags.forget(gdir, ["a"])
+ with flags.exclusive(gdir):
+ pass
+ assert flags.read(gdir) == {}
diff --git a/studio/backend/tests/test_image_gallery.py b/studio/backend/tests/test_image_gallery.py
index 8c9d47309ba..c499ca1d002 100644
--- a/studio/backend/tests/test_image_gallery.py
+++ b/studio/backend/tests/test_image_gallery.py
@@ -12,6 +12,7 @@ import os
import pytest
+import core.inference.gallery_flags as gallery_flags
import core.inference.image_gallery as gallery
PIL = pytest.importorskip("PIL")
@@ -218,3 +219,239 @@ def test_save_is_atomic_no_partial_png_on_publish_failure(monkeypatch):
# No final PNG surfaced, and the hidden temp was cleaned up.
assert list(gallery.gallery_dir().glob("*.png")) == []
assert list(gallery.gallery_dir().iterdir()) == []
+
+
+# --- pin / archive flags ---------------------------------------------------------------------
+
+
+def test_records_carry_default_flags():
+ _save_with_mtime("a", 100.0)
+ record = gallery.list_images()[0]
+ assert record["pinned"] is False and record["archived"] is False
+
+
+def test_pinned_images_sort_ahead_of_newer_ones():
+ old = _save_with_mtime("old", 100.0)
+ _save_with_mtime("new", 200.0)
+ gallery.set_flags(old["id"], pinned = True)
+ assert [r["prompt"] for r in gallery.list_images()] == ["old", "new"]
+ assert gallery.list_images()[0]["pinned"] is True
+
+
+def test_most_recently_pinned_leads_the_pinned_group():
+ first = _save_with_mtime("first", 100.0)
+ second = _save_with_mtime("second", 200.0)
+ gallery.set_flags(second["id"], pinned = True)
+ gallery.set_flags(first["id"], pinned = True) # pinned later, so it leads
+ assert [r["prompt"] for r in gallery.list_images()] == ["first", "second"]
+
+
+def test_unpinning_returns_an_image_to_newest_first_order():
+ old = _save_with_mtime("old", 100.0)
+ _save_with_mtime("new", 200.0)
+ gallery.set_flags(old["id"], pinned = True)
+ gallery.set_flags(old["id"], pinned = False)
+ assert [r["prompt"] for r in gallery.list_images()] == ["new", "old"]
+
+
+def test_archived_images_leave_the_default_listing():
+ keep = _save_with_mtime("keep", 100.0)
+ shelved = _save_with_mtime("shelved", 200.0)
+ gallery.set_flags(shelved["id"], archived = True)
+ assert [r["id"] for r in gallery.list_images()] == [keep["id"]]
+ # The archived shelf is its own listing, not a superset of the active one.
+ archived = gallery.list_images(archived = True)
+ assert [r["id"] for r in archived] == [shelved["id"]]
+ assert archived[0]["archived"] is True
+
+
+def test_restoring_puts_an_image_back_on_the_strip():
+ 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_images()] == [record["id"]]
+
+
+def test_archived_images_do_not_consume_a_page_slot():
+ # Pagination counts over the shelf being listed, so has_more probes stay truthful.
+ 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_images(limit = 2)] == ["a3", "a1"]
+ # Only two active records exist, so a limit+1 probe must not invent a third.
+ assert len(gallery.list_images(limit = 3)) == 2
+ assert [r["prompt"] for r in gallery.list_images(archived = True)] == ["a2", "a0"]
+
+
+def test_pinning_survives_pagination():
+ oldest = _save_with_mtime("oldest", 100.0)
+ for i in range(1, 4):
+ _save_with_mtime(f"a{i}", 100.0 + i)
+ gallery.set_flags(oldest["id"], pinned = True)
+ # The pin must reach page 0 rather than waiting for the page its mtime belongs to.
+ assert gallery.list_images(limit = 1, offset = 0)[0]["prompt"] == "oldest"
+
+
+def test_set_flags_refuses_a_foreign_or_unknown_id():
+ assert gallery.set_flags("does-not-exist", pinned = True) is None
+ foreign = gallery.gallery_dir() / "foreign.png"
+ _img().save(foreign, format = "PNG") # no recipe chunk, so not ours
+ assert gallery.set_flags("foreign", pinned = True) is None
+
+
+def test_delete_prunes_the_flag_entry():
+ record = _save_with_mtime("a", 100.0)
+ gallery.set_flags(record["id"], pinned = True)
+ assert gallery.delete(record["id"]) is True
+ assert gallery_flags.read(gallery.gallery_dir()) == {}
+
+
+def test_clear_spares_archived_images():
+ 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_images(archived = True)] == [shelved["id"]]
+ # The cleared image's flags go with it; the archived one keeps its own.
+ assert set(gallery_flags.read(gallery.gallery_dir())) == {shelved["id"]}
+ assert gallery.image_path(active["id"]) is None
+
+
+def test_clear_can_include_archived_images():
+ record = _save_with_mtime("shelved", 100.0)
+ gallery.set_flags(record["id"], archived = True)
+ assert gallery.clear(include_archived = True) == 1
+ assert gallery.list_images(archived = True) == []
+ assert gallery_flags.read(gallery.gallery_dir()) == {}
+
+
+def test_flags_are_not_required_recipe_keys():
+ # Flags live beside the PNG, so an image written before they existed must still list.
+ record = _save_with_mtime("older-schema", 100.0)
+ assert "pinned" not in gallery._read_meta(gallery.image_path(record["id"]))
+ assert [r["id"] for r in gallery.list_images()] == [record["id"]]
+
+
+def test_clear_refuses_when_the_flag_store_cannot_be_read():
+ # Fail CLOSED: an unreadable store reads as "nothing archived", which would delete the archive.
+ 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()
+ # Nothing was unlinked before the refusal.
+ assert gallery.image_path(record["id"]) is not None
+
+
+def test_clear_all_still_works_with_an_unreadable_store():
+ # include_archived spares nothing, so it needs no flags and must not be blocked by them.
+ record = _save_with_mtime("a", 100.0)
+ (gallery.gallery_dir() / ".flags.json").write_text("corrupt", encoding = "utf-8")
+ assert gallery.clear(include_archived = True) == 1
+ assert gallery.image_path(record["id"]) is None
+
+
+def test_clear_refuses_when_a_single_flag_entry_is_malformed():
+ # The whole-file corruption case is not the only risk: one bad VALUE reads as "not archived",
+ # which is enough to delete an archived image, so it must block the clear too.
+ import json as _json
+
+ record = _save_with_mtime("shelved", 100.0)
+ gallery.set_flags(record["id"], archived = True)
+ (gallery.gallery_dir() / ".flags.json").write_text(
+ _json.dumps({"version": 1, "items": {record["id"]: "hand edited"}}), encoding = "utf-8"
+ )
+ with pytest.raises(gallery_flags.FlagsUnavailable):
+ gallery.clear()
+ assert gallery.image_path(record["id"]) is not None
+
+
+def test_clear_refuses_when_an_archived_flag_is_not_a_boolean():
+ # `{"archived": null}` is still a dict, so a container-only check trusted it, and every reader
+ # turns it into "not archived" -- enough for the default clear to delete the archived image.
+ import json as _json
+
+ record = _save_with_mtime("shelved", 100.0)
+ gallery.set_flags(record["id"], archived = True)
+ (gallery.gallery_dir() / ".flags.json").write_text(
+ _json.dumps({"version": 1, "items": {record["id"]: {"archived": None}}}), encoding = "utf-8"
+ )
+ with pytest.raises(gallery_flags.FlagsUnavailable):
+ gallery.clear()
+ assert gallery.image_path(record["id"]) is not None
+
+
+def test_a_repair_never_makes_a_damaged_archive_deletable():
+ # An unrelated pin rewrites the store. If that repair dropped the unreadable archived flag, the
+ # store would come back trusted with the image active, and the next default clear() removes it.
+ import json as _json
+
+ shelved = _save_with_mtime("shelved", 100.0)
+ other = _save_with_mtime("other", 200.0)
+ gallery.set_flags(shelved["id"], archived = True)
+ (gallery.gallery_dir() / ".flags.json").write_text(
+ _json.dumps({"version": 1, "items": {shelved["id"]: {"archived": None}}}),
+ encoding = "utf-8",
+ )
+ gallery.set_flags(other["id"], pinned = True)
+ assert gallery.clear() == 1
+ assert gallery.image_path(shelved["id"]) is not None
+ assert gallery.image_path(other["id"]) is None
+
+
+def test_a_repair_of_an_illegible_store_never_makes_the_archive_deletable():
+ # The sibling of the test above: with the CONTAINER unreadable there is nothing to repair from,
+ # so an unrelated pin wrote a clean, trusted store saying nothing was archived, and the next
+ # default clear() deleted the shelved image.
+ shelved = _save_with_mtime("shelved", 100.0)
+ other = _save_with_mtime("other", 200.0)
+ gallery.set_flags(shelved["id"], archived = True)
+ (gallery.gallery_dir() / ".flags.json").write_text(
+ '{"version": 1, "items": {"shel', encoding = "utf-8"
+ )
+ gallery.set_flags(other["id"], pinned = True)
+ with pytest.raises(gallery_flags.FlagsUnavailable):
+ gallery.clear()
+ assert gallery.image_path(shelved["id"]) is not None
+ assert gallery.image_path(other["id"]) is not None
+ # The escape hatch still works, since it spares nothing and so needs no flags.
+ assert gallery.clear(include_archived = True) == 2
+
+
+def test_clear_all_replaces_an_unreadable_store_so_the_gallery_recovers():
+ # The escape hatch has to escape: include_archived spares nothing, so no file is left for the
+ # taint to protect, and leaving the corrupt store behind kept every later clear refusing.
+ _save_with_mtime("a", 100.0)
+ _save_with_mtime("b", 200.0)
+ (gallery.gallery_dir() / ".flags.json").write_text(
+ '{"version": 1, "items": {"a": {"archi', encoding = "utf-8"
+ )
+ assert gallery.clear(include_archived = True) == 2
+ later = _save_with_mtime("c", 300.0)
+ assert gallery.clear() == 1
+ assert gallery.image_path(later["id"]) is None
+
+
+def test_archiving_during_a_clear_never_leaves_a_deleted_image_reported_as_archived():
+ # clear() decides from a flag snapshot and then unlinks. Without a shared lock an archive
+ # landing in that window returned success for a file the same clear went on to delete.
+ import threading
+
+ records = [_save_with_mtime(f"i{i}", float(i)) for i in range(30)]
+ target = records[15]["id"]
+ out = {}
+
+ def _archive():
+ out["result"] = gallery.set_flags(target, archived = True)
+
+ worker = threading.Thread(target = _archive)
+ worker.start()
+ gallery.clear()
+ worker.join(timeout = 10)
+
+ said_ok = out.get("result") is not None
+ survived = gallery.image_path(target) is not None
+ # Either the archive won (reported success, file kept) or the clear won (reported gone, file
+ # deleted). "Reported success but deleted" is the outcome this must never produce.
+ assert said_ok == survived
diff --git a/studio/backend/tests/test_video_gallery.py b/studio/backend/tests/test_video_gallery.py
index adf7ffadb06..a29ca3e67b5 100644
--- a/studio/backend/tests/test_video_gallery.py
+++ b/studio/backend/tests/test_video_gallery.py
@@ -10,6 +10,7 @@ import json
import os
from pathlib import Path
+import core.inference.gallery_flags as gallery_flags
import core.inference.video_gallery as gallery
@@ -540,3 +541,141 @@ def test_gif_export_bounds_frames_and_edge(monkeypatch):
except EOFError:
pass
assert frames <= 4, frames
+
+
+# --- pin / archive flags ---------------------------------------------------------------------
+
+
+def test_records_carry_default_flags():
+ _save_with_mtime("a", 100.0)
+ record = gallery.list_videos()[0]
+ assert record["pinned"] is False and record["archived"] is False
+
+
+def test_pinned_videos_sort_ahead_of_newer_ones():
+ old = _save_with_mtime("old", 100.0)
+ _save_with_mtime("new", 200.0)
+ gallery.set_flags(old["id"], pinned = True)
+ assert [r["prompt"] for r in gallery.list_videos()] == ["old", "new"]
+ assert gallery.list_videos()[0]["pinned"] is True
+
+
+def test_most_recently_pinned_leads_the_pinned_group():
+ first = _save_with_mtime("first", 100.0)
+ second = _save_with_mtime("second", 200.0)
+ gallery.set_flags(second["id"], pinned = True)
+ gallery.set_flags(first["id"], pinned = True) # pinned later, so it leads
+ assert [r["prompt"] for r in gallery.list_videos()] == ["first", "second"]
+
+
+def test_unpinning_returns_a_video_to_newest_first_order():
+ old = _save_with_mtime("old", 100.0)
+ _save_with_mtime("new", 200.0)
+ gallery.set_flags(old["id"], pinned = True)
+ gallery.set_flags(old["id"], pinned = False)
+ assert [r["prompt"] for r in gallery.list_videos()] == ["new", "old"]
+
+
+def test_archived_videos_leave_the_default_listing():
+ keep = _save_with_mtime("keep", 100.0)
+ shelved = _save_with_mtime("shelved", 200.0)
+ gallery.set_flags(shelved["id"], archived = True)
+ assert [r["id"] for r in gallery.list_videos()] == [keep["id"]]
+ archived = gallery.list_videos(archived = True)
+ assert [r["id"] for r in archived] == [shelved["id"]]
+ assert archived[0]["archived"] is True
+
+
+def test_restoring_puts_a_video_back_on_the_strip():
+ 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_videos()] == [record["id"]]
+
+
+def test_archived_videos_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_videos(limit = 2)] == ["a3", "a1"]
+ assert len(gallery.list_videos(limit = 3)) == 2
+ assert [r["prompt"] for r in gallery.list_videos(archived = True)] == ["a2", "a0"]
+
+
+def test_pinning_survives_pagination():
+ oldest = _save_with_mtime("oldest", 100.0)
+ for i in range(1, 4):
+ _save_with_mtime(f"a{i}", 100.0 + i)
+ gallery.set_flags(oldest["id"], pinned = True)
+ assert gallery.list_videos(limit = 1, offset = 0)[0]["prompt"] == "oldest"
+
+
+def test_set_flags_refuses_a_foreign_or_unknown_id():
+ assert gallery.set_flags("does-not-exist", pinned = True) is None
+ orphan = gallery.gallery_dir() / "orphan.mp4"
+ orphan.write_bytes(_mp4()) # no sidecar, so not ours
+ assert gallery.set_flags("orphan", pinned = True) is None
+
+
+def test_delete_prunes_the_flag_entry():
+ record = _save_with_mtime("a", 100.0)
+ gallery.set_flags(record["id"], pinned = True)
+ assert gallery.delete(record["id"]) is True
+ assert gallery_flags.read(gallery.gallery_dir()) == {}
+
+
+def test_clear_spares_archived_videos():
+ 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_videos(archived = True)] == [shelved["id"]]
+ assert set(gallery_flags.read(gallery.gallery_dir())) == {shelved["id"]}
+ assert gallery.video_path(active["id"]) is None
+
+
+def test_clear_can_include_archived_videos():
+ record = _save_with_mtime("shelved", 100.0)
+ gallery.set_flags(record["id"], archived = True)
+ assert gallery.clear(include_archived = True) == 1
+ assert gallery.list_videos(archived = True) == []
+ assert gallery_flags.read(gallery.gallery_dir()) == {}
+
+
+def test_flags_are_not_required_sidecar_keys():
+ # Flags live in their own store, so a clip written before they existed must still list.
+ record = _save_with_mtime("older-schema", 100.0)
+ sidecar = gallery.gallery_dir() / f"{record['id']}.json"
+ assert "pinned" not in json.loads(sidecar.read_text(encoding = "utf-8"))
+ assert [r["id"] for r in gallery.list_videos()] == [record["id"]]
+
+
+def test_clear_refuses_when_the_flag_store_cannot_be_read():
+ # Fail CLOSED: an unreadable store reads as "nothing archived", which would delete the archive.
+ 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.video_path(record["id"]) is not None
+
+
+def test_clear_all_still_works_with_an_unreadable_store():
+ record = _save_with_mtime("a", 100.0)
+ (gallery.gallery_dir() / ".flags.json").write_text("corrupt", encoding = "utf-8")
+ assert gallery.clear(include_archived = True) == 1
+ assert gallery.video_path(record["id"]) is None
+
+
+def test_clear_all_replaces_an_unreadable_store_so_the_gallery_recovers():
+ # Same escape hatch as the image gallery: a corrupt store surviving the wipe would leave every
+ # later default clear refusing, for clips generated long afterwards.
+ _save_with_mtime("a", 100.0)
+ _save_with_mtime("b", 200.0)
+ (gallery.gallery_dir() / ".flags.json").write_text(
+ '{"version": 1, "items": {"a": {"archi', encoding = "utf-8"
+ )
+ assert gallery.clear(include_archived = True) == 2
+ _save_with_mtime("c", 300.0)
+ assert gallery.clear() == 1
diff --git a/studio/frontend/src/components/gallery-item-menu.tsx b/studio/frontend/src/components/gallery-item-menu.tsx
new file mode 100644
index 00000000000..64d69a2c124
--- /dev/null
+++ b/studio/frontend/src/components/gallery-item-menu.tsx
@@ -0,0 +1,99 @@
+// 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 {
+ Archive02Icon,
+ ArchiveRestoreIcon,
+ Delete02Icon,
+ MoreHorizontalIcon,
+ PinIcon,
+ PinOffIcon,
+} from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useEffect, useState } from "react";
+
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { cn } from "@/lib/utils";
+
+/**
+ * Pin / archive / delete for one gallery item, shared by the Images and Video pages.
+ *
+ * "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.
+ */
+export type GalleryItemMenuVariant = "toolbar" | "overlay";
+
+export function GalleryItemMenu({
+ pinned,
+ archived,
+ onTogglePin,
+ onToggleArchive,
+ onDelete,
+ variant = "toolbar",
+ noun,
+ active = true,
+ className,
+}: {
+ pinned: boolean;
+ archived: boolean;
+ onTogglePin: () => void;
+ onToggleArchive: () => void;
+ onDelete: () => void;
+ variant?: GalleryItemMenuVariant;
+ /** Used in the aria-label, e.g. "image" or "video". */
+ noun: string;
+ /** False while the page is off-tab; forces the menu shut so a portalled popup cannot outlive it. */
+ active?: boolean;
+ className?: string;
+}) {
+ // Controlled like RecipePopover: DropdownMenuContent portals to body, so the inert page wrapper
+ // cannot contain it when the tab goes away.
+ const [open, setOpen] = useState(false);
+ useEffect(() => {
+ if (!active) setOpen(false);
+ }, [active]);
+
+ const overlay = variant === "overlay";
+ return (
+ <DropdownMenu open={active && open} onOpenChange={(o) => setOpen(active && o)}>
+ <DropdownMenuTrigger asChild={true}>
+ <Button
+ size={overlay ? "icon-xs" : "sm"}
+ variant="ghost"
+ aria-label={`More actions for this ${noun}`}
+ className={cn(
+ // Reads over any thumbnail, whatever its colours.
+ overlay &&
+ "bg-background/80 text-foreground shadow-sm ring-1 ring-border backdrop-blur hover:bg-background",
+ className,
+ )}
+ >
+ <HugeiconsIcon icon={MoreHorizontalIcon} className={overlay ? "size-3.5" : "size-4"} />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={onTogglePin}>
+ <HugeiconsIcon icon={pinned ? PinOffIcon : PinIcon} />
+ {pinned ? "Unpin" : "Pin to front"}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={onToggleArchive}>
+ <HugeiconsIcon icon={archived ? ArchiveRestoreIcon : Archive02Icon} />
+ {archived ? "Restore from archive" : "Archive"}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="destructive" onClick={onDelete}>
+ <HugeiconsIcon icon={Delete02Icon} />
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.ts
index a522d64697c..7864618ea58 100644
--- a/studio/frontend/src/features/images/api.ts
+++ b/studio/frontend/src/features/images/api.ts
@@ -202,6 +202,9 @@ export interface GalleryImage {
controlnet_guidance?: string | null;
reference_image_count?: number | null;
created_at: number;
+ // Library state, not recipe: stored beside the PNG, absent on records written before this existed.
+ pinned?: boolean;
+ archived?: boolean;
}
export interface DiffusionGenerateResponse {
@@ -396,9 +399,26 @@ export interface GalleryPage {
has_more: boolean;
}
-export async function getGallery(offset = 0, limit = 50): Promise<GalleryPage> {
+/** `archived` picks WHICH shelf to page over: false is the strip, true is the archive. */
+export async function getGallery(offset = 0, limit = 50, archived = false): Promise<GalleryPage> {
return parseJson(
- await authFetch(`/api/inference/images/gallery?offset=${offset}&limit=${limit}`),
+ await authFetch(
+ `/api/inference/images/gallery?offset=${offset}&limit=${limit}&archived=${archived}`,
+ ),
+ );
+}
+
+/** Pin/unpin or archive/restore one image; omitted flags are left alone. Returns the new record. */
+export async function setGalleryImageFlags(
+ id: string,
+ flags: { pinned?: boolean; archived?: boolean },
+): Promise<GalleryImage> {
+ return parseJson(
+ await authFetch(`/api/inference/images/gallery/${id}`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(flags),
+ }),
);
}
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index 5f2bafded6e..0b5ef37dad0 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -12,6 +12,7 @@ import {
Image03Icon,
ImageAdd02Icon,
InformationCircleIcon,
+ PinIcon,
SparklesIcon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon, type IconSvgElement } from "@hugeicons/react";
@@ -63,7 +64,25 @@ import type {
ModelSelectorChangeMeta,
} from "@/features/model-picker/components/model-selector/types";
import { AdvancedDisclosure } from "@/components/advanced-disclosure";
+import { GalleryItemMenu } from "@/components/gallery-item-menu";
import { MediaPageLink } from "@/components/media-page-link";
+import { useSettingsDialogStore } from "@/features/settings/stores/settings-dialog-store";
+import {
+ type NewRecordProbeBaseline,
+ applyPin,
+ fetchNextPage,
+ fetchWhileStable,
+ hasUnknownRecord,
+ mergeGenerated,
+ newRecordProbeBaseline,
+ nextSelectedId,
+ pinnedOrder,
+ removeGalleryItem,
+ restorePinOrder,
+ serializeById,
+ sortGalleryItems,
+ subscribeGalleryChanged,
+} from "@/lib/gallery-flags";
import { usePersistedToggle } from "@/hooks/use-persisted-toggle";
import { useImageWorkflowStore } from "./stores/image-workflow-store";
import { WORKFLOW_TABS } from "./workflows";
@@ -121,6 +140,7 @@ import {
getGenerateProgress,
listDiffusionControlNets,
listDiffusionLoras,
+ setGalleryImageFlags,
getDiffusionDownloadPlan,
loadDiffusionModel,
unloadDiffusionModel,
@@ -306,6 +326,10 @@ const galleryCache: {
// Images loaded per infinite-scroll page.
const PAGE_SIZE = 50;
+// Passes a window resync may make before giving up. Each extra pass only happens when pagination
+// moved while it was fetching, which cannot repeat indefinitely without the user scrolling along.
+const RESYNC_MAX_ATTEMPTS = 3;
+
// Export filename, e.g. Unsloth_20260624-143005_123.png. Batch siblings share seed + timestamp, so they get a "_<n>" suffix.
type ImageExportFormat = "png" | "jpeg" | "webp";
@@ -390,7 +414,7 @@ const SETTLE_MAX_FAILS = 5; // consecutive progress failures before calling the
/** Wait out a generation that outlived its POST. Idle progress alone is ambiguous, so success needs evidence (progress seen active, or a gallery record that was not there when the POST went out); otherwise report a failed submission. Throws past SETTLE_MAX_MS, or if the backend stays unreachable, so a wedged generation surfaces. */
async function settleLostGeneration(
isCurrent: () => boolean,
- knownIds: ReadonlySet<string>,
+ baseline: NewRecordProbeBaseline,
): Promise<void> {
const start = Date.now();
let fails = 0;
@@ -412,8 +436,15 @@ async function settleLostGeneration(
if (sawActive) return;
// Idle on the very first look: the run may already have finished or never started. A gallery record we had not seen is the proof.
try {
- const page = await getGallery(0, 1);
- if (page.images.some((image) => !knownIds.has(image.id))) return;
+ const sawNew = await hasUnknownRecord(
+ baseline,
+ async (offset) => {
+ const p = await getGallery(offset, PAGE_SIZE);
+ return { items: p.images, hasMore: p.has_more };
+ },
+ PAGE_SIZE,
+ );
+ if (sawNew) return;
} catch {
fails += 1;
if (fails >= SETTLE_MAX_FAILS) throw new Error("Lost connection to the image server.");
@@ -1455,9 +1486,29 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
}
}, []);
+ // Bumped by every LOCAL change to the strip (pin, archive, delete, merged generation). A resync
+ // started before one holds a snapshot the listing cannot reconcile with what the user just did.
+ const stripEpoch = useRef(0);
+ // Bumped by the window growing from the server (a load, an appended page). Not a conflict: the
+ // resync just sized itself against a smaller window, so it refetches.
+ const pageEpoch = useRef(0);
+ // Only the newest resync may apply: two restores in a row would otherwise let the older snapshot
+ // land last and drop what the newer one showed.
+ const resyncSeq = useRef(0);
+ // Shelf mutations in flight. The epoch is an EDGE, so a page starting after the bump and landing
+ // before the row is dropped sees it hold still. A page is only trusted while this is zero.
+ const pendingShelfMutations = useRef(0);
+
const loadGallery = useCallback(async () => {
try {
- const page = await getGallery(0, PAGE_SIZE);
+ // Fenced: this page renders from the module cache while the load runs, so its tiles are
+ // actionable, and a pre-pin snapshot would undo the action with nothing to correct it.
+ const page = await fetchWhileStable(
+ () => stripEpoch.current,
+ () => getGallery(0, PAGE_SIZE),
+ );
+ if (!page) return;
+ pageEpoch.current += 1;
galleryCache.images = page.images;
galleryCache.hasMore = page.has_more;
setImages(page.images);
@@ -1476,7 +1527,17 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
if (loadingMore.current || !galleryCache.hasMore) return;
loadingMore.current = true;
try {
- const page = await getGallery(galleryCache.images.length, PAGE_SIZE);
+ // Guarded on all three counters: an archive landing anywhere across this GET shortens the
+ // shelf, and the record that shifts over the page boundary is returned by no page at all.
+ const result = await fetchNextPage(
+ () => galleryCache.images.length,
+ () => stripEpoch.current,
+ () => pendingShelfMutations.current,
+ (offset) => getGallery(offset, PAGE_SIZE),
+ );
+ if (!result) return;
+ const page = result.page;
+ pageEpoch.current += 1;
setImages((prev) => {
const seen = new Set(prev.map((i) => i.id));
const next = [...prev, ...page.images.filter((i) => !seen.has(i.id))];
@@ -1535,26 +1596,218 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
void loadGallery();
}, [loadGallery]);
- const handleDelete = useCallback(async (id: string) => {
- try {
- await deleteGalleryImage(id);
- } catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to delete image");
- return;
+
+ // Drop an image from the strip. `discardBlob` is for a real delete: the bytes are gone, so the
+ // cached object URL must be revoked and any in-flight fetch told to throw its blob away. An
+ // archived image keeps both, since the archived view shows the same thumbnail.
+ const dropFromStrip = useCallback((id: string, discardBlob: boolean) => {
+ if (discardBlob) {
+ galleryCache.srcById.delete(id); // revokes the URL with the entry
+ galleryCache.deleted.add(id);
+ setSrcById((prev) => {
+ const next = { ...prev };
+ delete next[id];
+ return next;
+ });
}
- galleryCache.srcById.delete(id); // revokes the URL with the entry
visibleIds.current.delete(id);
- // A fetch still in flight for this id must discard its blob rather than cache it.
- galleryCache.deleted.add(id);
- setSrcById((prev) => {
- const next = { ...prev };
- delete next[id];
- return next;
- });
- setImages((prev) => prev.filter((i) => i.id !== id));
- setSelectedId((cur) => (cur === id ? null : cur));
+ stripEpoch.current += 1;
+ // Read the list from the cache (kept in sync with state every render) rather than nesting a
+ // setSelectedId inside a setImages updater, which would run a side effect during dispatch.
+ const at = galleryCache.images.findIndex((i) => i.id === id);
+ const next = removeGalleryItem(galleryCache.images, id);
+ galleryCache.images = next;
+ setImages(next);
+ setSelectedId((cur) => nextSelectedId(next, id, cur, at));
}, []);
+ const handleDelete = useCallback(
+ async (id: string) => {
+ // Held for the whole round trip: the server shortens the shelf when it processes this, and a
+ // page read inside that window sees the shortened list at an offset nothing contradicts.
+ stripEpoch.current += 1;
+ pendingShelfMutations.current += 1;
+ try {
+ await deleteGalleryImage(id);
+ } catch (err) {
+ pendingShelfMutations.current -= 1;
+ toast.error(err instanceof Error ? err.message : "Failed to delete image");
+ return;
+ }
+ dropFromStrip(id, true);
+ pendingShelfMutations.current -= 1;
+ },
+ [dropFromStrip],
+ );
+
+ /**
+ * Refetch the loaded window from offset 0.
+ *
+ * Unpinning can drop an image past the end of the loaded window and promote a previously
+ * unloaded one into it. The local reorder cannot know about the promoted image, and the next
+ * loadMore still pages from the unchanged length, so that image would be skipped entirely until
+ * a reload. Re-reading the window is the only way to see it.
+ */
+ const resyncWindow = useCallback(
+ async (count: number, stillFresh?: () => boolean) => {
+ const ticket = (resyncSeq.current += 1);
+ for (let attempt = 0; attempt < RESYNC_MAX_ATTEMPTS; attempt += 1) {
+ const paged = pageEpoch.current;
+ // Sized against the live window, so a page appended while this ran is covered rather than
+ // cut back off the bottom of the strip when the snapshot lands.
+ const wanted = Math.max(count, galleryCache.images.length, PAGE_SIZE);
+ const collected: GalleryImage[] = [];
+ let more = false;
+ while (collected.length < wanted) {
+ // The REMAINDER, not a whole page: a window of 51 (a page plus one new generation) would
+ // otherwise ask for 100 and grow the strip to match, reading 49 recipes off disk and
+ // rendering their tiles for a one-row shortfall.
+ const page = await getGallery(
+ collected.length,
+ Math.min(PAGE_SIZE, wanted - collected.length),
+ );
+ collected.push(...page.images);
+ more = page.has_more;
+ if (!page.has_more || page.images.length === 0) break;
+ }
+ // Checked here, not by the caller: by the time this returns the window is already applied,
+ // so a stale snapshot has to be dropped before it overwrites a newer local change.
+ if (stillFresh && !stillFresh()) return;
+ if (resyncSeq.current !== ticket) return;
+ // Pagination moved under this pass. That is only server data, so cover it with another
+ // pass instead of giving up: giving up is what left an unpin's promoted image missing.
+ if (pageEpoch.current !== paged) continue;
+ galleryCache.images = collected;
+ galleryCache.hasMore = more;
+ setImages(collected);
+ setHasMore(more);
+ if (typeof IntersectionObserver === "undefined") {
+ collected.forEach((image) => void ensureSrc(image));
+ }
+ return;
+ }
+ },
+ [ensureSrc],
+ );
+
+ // This page stays mounted across route changes, so a restore from the Settings archive would
+ // otherwise not reach the strip until a full reload. Resync the window that is actually loaded:
+ // loadGallery would cut it back to the first page and throw away everything scrolled to.
+ useEffect(
+ () =>
+ subscribeGalleryChanged("images", () => {
+ // Bumped FIRST: a restore changes the shelf, so reads already in flight must be discarded.
+ // Capturing without advancing let them pass their own checks and land on the new window.
+ stripEpoch.current += 1;
+ // Fenced like the unpin resync: a generation or a new page landing while this GET runs
+ // would otherwise be overwritten by a snapshot taken before it.
+ const epoch = stripEpoch.current;
+ void resyncWindow(
+ galleryCache.images.length,
+ () => stripEpoch.current === epoch,
+ ).catch(() => void loadGallery());
+ }),
+ [loadGallery, resyncWindow],
+ );
+
+ // The pin state each id was last CLICKED into, so a failing request can tell whether it is still
+ // the current intent. Without it, a slow first click failing after a later click succeeded would
+ // roll the strip back onto the state the user has since moved off.
+ const pinAttempt = useRef(new Map<string, number>());
+ const pinSeq = useRef(0);
+
+ const handleTogglePin = useCallback(
+ async (id: string, pinned: boolean) => {
+ const loadedCount = galleryCache.images.length;
+ // The pinned order as it stands BEFORE the click, so a failed unpin can put the image back
+ // where it was instead of at the front of the pins.
+ const orderBefore = pinnedOrder(galleryCache.images);
+ // A per-attempt token, not the target boolean: pin, unpin, pin stores true twice, so the FIRST
+ // attempt's failure would roll back the THIRD attempt's pin and leave the two disagreeing.
+ const attempt = (pinSeq.current += 1);
+ pinAttempt.current.set(id, attempt);
+ stripEpoch.current += 1;
+ const epoch = stripEpoch.current;
+ // Optimistic: the reorder should land on the click, not a round trip later.
+ setImages((prev) => {
+ const next = applyPin(prev, id, pinned);
+ galleryCache.images = next;
+ return next;
+ });
+ try {
+ // One queue for the whole gallery, not one per image. The server stamps `pinned_at` when
+ // it runs the PATCH and orders pins by that stamp, so two requests in flight together can
+ // be stamped in either order and the strip disagrees with the next load. Issuing them one
+ // at a time makes the stamps follow the clicks.
+ await serializeById("image-pin", () => setGalleryImageFlags(id, { pinned }));
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "Failed to pin image");
+ // Put the old order back rather than leave the strip lying about server state, but only
+ // while this is still what the user last asked for.
+ if (pinAttempt.current.get(id) === attempt) {
+ pinAttempt.current.delete(id);
+ stripEpoch.current += 1;
+ setImages((prev) => {
+ // A failed pin simply goes back to unpinned; a failed unpin has to be restored to its
+ // old position among the pins, which applyPin cannot do (it means "freshly pinned").
+ const next = pinned
+ ? applyPin(prev, id, false)
+ : restorePinOrder(prev, id, orderBefore);
+ galleryCache.images = next;
+ return next;
+ });
+ }
+ return;
+ }
+ if (pinAttempt.current.get(id) !== attempt) return; // superseded by a later click
+ pinAttempt.current.delete(id);
+ // Pinning keeps the same set in the window (it only moves an already-loaded image to the
+ // front), so only unpinning can open a gap.
+ if (!pinned && loadedCount > 0) {
+ try {
+ // Fenced: a pin clicked while this GET is in flight would otherwise be overwritten by a
+ // snapshot taken before it, leaving the strip unpinned while the server is pinned.
+ await resyncWindow(loadedCount, () => stripEpoch.current === epoch);
+ } catch {
+ // Best-effort: the strip is still usable, just possibly short one image until a reload.
+ }
+ }
+ },
+ [resyncWindow],
+ );
+
+ const handleArchive = useCallback(
+ async (id: string) => {
+ // Held for the whole round trip: the server shortens the shelf when it processes this, and a
+ // page read inside that window sees the shortened list at an offset nothing contradicts.
+ stripEpoch.current += 1;
+ pendingShelfMutations.current += 1;
+ try {
+ await setGalleryImageFlags(id, { archived: true });
+ } catch (err) {
+ pendingShelfMutations.current -= 1;
+ toast.error(err instanceof Error ? err.message : "Failed to archive image");
+ return;
+ }
+ dropFromStrip(id, false);
+ pendingShelfMutations.current -= 1;
+ const toastId = toast(
+ <button
+ type="button"
+ onClick={() => {
+ toast.dismiss(toastId);
+ useSettingsDialogStore.getState().openArchivedMedia("images");
+ }}
+ className="w-full cursor-pointer text-left"
+ >
+ You can view archived images in Settings
+ </button>,
+ { closeButton: true },
+ );
+ },
+ [dropFromStrip],
+ );
+
// Load an image's recipe back into the form inputs.
const restoreSettings = useCallback((image: GalleryImage) => {
setPrompt(image.prompt);
@@ -2841,6 +3094,18 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
})
)
break;
+ // Frozen BEFORE the POST goes out, because both halves of it have to describe the same
+ // moment. `knownIds` is from before the request, so deriving the window half in the catch
+ // mixes the two: scrolling while the request is in flight pages in historical unpinned
+ // records, and a window that was all pinned (which refuses to judge) then looks like one
+ // that can, with the newest historical row reading as proof the generation landed.
+ // Sharing the `knownIds` set is deliberate: it only ever grows, and a larger set can only
+ // make the probe more conservative.
+ const probeBaseline = newRecordProbeBaseline(
+ galleryCache.images,
+ galleryCache.hasMore,
+ knownIds,
+ );
let res: DiffusionGenerateResponse;
try {
res = await generateDiffusionImage({
@@ -2884,8 +3149,9 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
// The POST response was lost while the backend kept generating (the secure-mode tunnel caps the response near 100s).
// Retrying would duplicate the work, so wait the run out and read its images off the gallery.
if (!(err instanceof GenerateResponseLostError)) throw err;
- // The ids known before the POST went out: a record outside them proves the request reached the backend.
- await settleLostGeneration(() => isMounted.current, knownIds);
+ // A record outside the baseline proves the request reached the backend. Taken per
+ // attempt, so it reflects what the client could see when THIS post went out.
+ await settleLostGeneration(() => isMounted.current, probeBaseline);
if (!isMounted.current) break;
await loadGallery();
// loadGallery refreshes the module cache synchronously, so this run's records are folded in before the next run.
@@ -2894,8 +3160,13 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
continue;
}
if (!isMounted.current) break;
- // Prepend this run's records (newest first) and load their blobs.
- setImages((prev) => [...res.images, ...prev]);
+ // Merge this run's records and load their blobs. Sorted, not prepended: a new image is
+ // unpinned, so the server puts it after the pinned group, and a bare prepend would show it
+ // ahead of pins until the next reload.
+ stripEpoch.current += 1;
+ // Deduplicated: a resync in flight can fetch the saved record first, and prepending it
+ // again duplicates a React key and inflates the next page's offset, skipping a record.
+ setImages((prev) => mergeGenerated(prev, res.images));
res.images.forEach((image) => knownIds.add(image.id));
if (res.images[0]) setSelectedId(res.images[0].id);
res.images.forEach((image) => void ensureSrc(image));
@@ -3828,20 +4099,17 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
- <Tooltip>
- <TooltipTrigger asChild={true}>
- <Button
- size="sm"
- variant="ghost"
- aria-label="Delete image"
- className="text-muted-foreground hover:text-destructive"
- onClick={() => void handleDelete(selected.id)}
- >
- <HugeiconsIcon icon={Delete02Icon} className="size-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>Delete</TooltipContent>
- </Tooltip>
+ <GalleryItemMenu
+ noun="image"
+ active={active}
+ pinned={Boolean(selected.pinned)}
+ archived={Boolean(selected.archived)}
+ onTogglePin={() =>
+ void handleTogglePin(selected.id, !selected.pinned)
+ }
+ onToggleArchive={() => void handleArchive(selected.id)}
+ onDelete={() => void handleDelete(selected.id)}
+ />
</div>
</>
) : selected ? (
@@ -3905,30 +4173,55 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
<Spinner className="size-5 text-muted-foreground" />
</div>
)}
+ {/* The tile is a wrapper, not a button: the actions menu has to be the select
+ button's SIBLING, since a button inside a button is invalid and would swallow
+ its own clicks. data-image-id rides the wrapper so the observer still sees it. */}
{images.map((image) => (
- <button
+ <div
key={image.id}
- type="button"
data-image-id={image.id}
- onClick={() => setSelectedId(image.id)}
- className="relative size-16 shrink-0 overflow-hidden rounded-[10px] bg-muted/40 outline-none ring-1 ring-transparent transition-shadow hover:ring-border focus-visible:ring-2 focus-visible:ring-ring"
+ className="group relative size-16 shrink-0"
>
- {srcById[image.id] ? (
- <img
- src={srcById[image.id]}
- alt={image.prompt}
- className="size-full object-cover"
- />
- ) : (
- <span className="flex size-full items-center justify-center">
- <Spinner className="size-4 text-muted-foreground" />
+ <button
+ type="button"
+ onClick={() => setSelectedId(image.id)}
+ className="relative size-full overflow-hidden rounded-[10px] bg-muted/40 outline-none ring-1 ring-transparent transition-shadow hover:ring-border focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {srcById[image.id] ? (
+ <img
+ src={srcById[image.id]}
+ alt={image.prompt}
+ className="size-full object-cover"
+ />
+ ) : (
+ <span className="flex size-full items-center justify-center">
+ <Spinner className="size-4 text-muted-foreground" />
+ </span>
+ )}
+ {/* Selection marker on a non-focusable overlay, so the button own focus state can never mask it. */}
+ {image.id === selected?.id && (
+ <span className="pointer-events-none absolute inset-0 rounded-[10px] border border-border bg-white/35 dark:border-white/25 dark:bg-white/20" />
+ )}
+ </button>
+ {/* Pin marker, bottom-left so it never sits under the menu. */}
+ {image.pinned && (
+ <span className="pointer-events-none absolute bottom-0.5 left-0.5 rounded-full bg-background/80 p-0.5 text-foreground shadow-sm ring-1 ring-border backdrop-blur">
+ <HugeiconsIcon icon={PinIcon} className="size-3" />
</span>
)}
- {/* Selection marker on a non-focusable overlay, so the button own focus state can never mask it. */}
- {image.id === selected?.id && (
- <span className="pointer-events-none absolute inset-0 rounded-[10px] border border-border bg-white/35 dark:border-white/25 dark:bg-white/20" />
- )}
- </button>
+ <div className="absolute right-0.5 top-0.5 opacity-0 transition-opacity focus-within:opacity-100 group-hover:opacity-100">
+ <GalleryItemMenu
+ variant="overlay"
+ noun="image"
+ active={active}
+ pinned={Boolean(image.pinned)}
+ archived={Boolean(image.archived)}
+ onTogglePin={() => void handleTogglePin(image.id, !image.pinned)}
+ onToggleArchive={() => void handleArchive(image.id)}
+ onDelete={() => void handleDelete(image.id)}
+ />
+ </div>
+ </div>
))}
{/* Tail spinner while older pages stream in on scroll. */}
{hasMore && (
diff --git a/studio/frontend/src/features/settings/components/archived-media-dialog.tsx b/studio/frontend/src/features/settings/components/archived-media-dialog.tsx
new file mode 100644
index 00000000000..b5436beef07
--- /dev/null
+++ b/studio/frontend/src/features/settings/components/archived-media-dialog.tsx
@@ -0,0 +1,475 @@
+// 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 { HugeiconsIcon } from "@hugeicons/react";
+import { useCallback, useEffect, useRef, useState } from "react";
+
+import { Button } from "@/components/ui/button";
+import { Spinner } from "@/components/ui/spinner";
+import {
+ deleteGalleryImage,
+ fetchGalleryObjectUrl,
+ getGallery,
+ setGalleryImageFlags,
+} from "@/features/images/api";
+import {
+ deleteGalleryVideo,
+ fetchGalleryVideoSignedUrl,
+ getVideoGallery,
+ setGalleryVideoFlags,
+} from "@/features/video/api";
+import { BlobUrlCache } from "@/lib/blob-url-cache";
+import { notifyGalleryChanged } from "@/lib/gallery-flags";
+import { toast } from "@/lib/toast";
+
+/** Archived items shown per page; "Show more" pulls the next page. Matches ArchivedChatsView. */
+const ARCHIVED_PAGE_SIZE = 20;
+
+// Blob budget for archived thumbnails. Far smaller than the gallery strip's 192 MB: these are 40px
+// rows in a settings list, and only the loaded pages are ever on screen.
+const ARCHIVED_THUMB_BUDGET_BYTES = 32 * 1024 * 1024;
+
+// Retries for a thumbnail that failed to load, and the step between them. Capped so a row whose
+// file is genuinely gone stops asking instead of retrying for as long as the dialog is open.
+const THUMB_RETRY_LIMIT = 2;
+const THUMB_RETRY_DELAY_MS = 750;
+
+export type ArchivedMediaKind = "images" | "videos";
+
+/** The shape both galleries share, once flattened for this list. */
+interface ArchivedRow {
+ id: string;
+ prompt: string;
+ /** Epoch ms, so images (epoch seconds) and videos (ISO 8601) render the same way. */
+ createdAtMs: number;
+ /** Relative, auth-protected URL of the underlying file. */
+ url: string;
+}
+
+function formatCreatedAt(ms: number): string {
+ if (!Number.isFinite(ms)) return "";
+ return new Date(ms).toLocaleDateString(undefined, {
+ year: "numeric",
+ month: "long",
+ day: "numeric",
+ });
+}
+
+/**
+ * The archived shelf for one media gallery, modelled on ArchivedChatsView: rows with restore and
+ * delete, revealed a page at a time. Unlike chats there is nothing readable to identify a result
+ * by, so each row carries a thumbnail alongside its prompt.
+ */
+export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
+ const isImages = kind === "images";
+ const noun = isImages ? "image" : "video";
+ 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 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.
+ const pendingMutations = useRef(0);
+ const loadingMore = useRef(false);
+ const putRows = useCallback((next: ArchivedRow[]) => {
+ rowsRef.current = next;
+ setRows(next);
+ }, []);
+ const [hasMore, setHasMore] = useState(false);
+ const [loading, setLoading] = useState(true);
+ const [thumbs, setThumbs] = useState<Record<string, string>>({});
+ // Archived PNGs are full-size generated images, so "Show more" a few times would pin hundreds of
+ // MB if every blob were held to unmount. Budget them like the main gallery does. Images only: a
+ // clip uses a signed link, which is not an object URL and must not be revoked.
+ const blobs = useRef(new BlobUrlCache(ARCHIVED_THUMB_BUDGET_BYTES));
+ // Only rows on screen fetch a thumbnail, and only rows off screen are evicted. Together those
+ // two rules keep memory bounded without ever blanking a row the user is looking at.
+ const listRef = useRef<HTMLDivElement | null>(null);
+ const [visible, setVisible] = useState<ReadonlySet<string>>(new Set());
+
+ const loadPage = useCallback(
+ async (offset: number) => {
+ if (isImages) {
+ const page = await getGallery(offset, ARCHIVED_PAGE_SIZE, true);
+ return {
+ rows: page.images.map((i) => ({
+ id: i.id,
+ prompt: i.prompt,
+ createdAtMs: i.created_at * 1000,
+ url: i.url,
+ })),
+ hasMore: page.has_more,
+ };
+ }
+ const page = await getVideoGallery(offset, ARCHIVED_PAGE_SIZE, true);
+ return {
+ rows: page.videos.map((v) => ({
+ id: v.id,
+ prompt: v.prompt,
+ createdAtMs: Date.parse(v.created_at),
+ url: v.url,
+ })),
+ hasMore: page.has_more,
+ };
+ },
+ [isImages],
+ );
+
+ useEffect(() => {
+ let cancelled = false;
+ setLoading(true);
+ void (async () => {
+ try {
+ const page = await loadPage(0);
+ if (cancelled) return;
+ putRows(page.rows);
+ setHasMore(page.hasMore);
+ } catch (err) {
+ if (!cancelled) {
+ toast.error(`Failed to load archived ${kind}`, {
+ description: err instanceof Error ? err.message : undefined,
+ });
+ }
+ } finally {
+ if (!cancelled) setLoading(false);
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [loadPage, kind, putRows]);
+
+ // Revoke everything still cached, once, on unmount.
+ useEffect(() => {
+ const cache = blobs.current;
+ return () => cache.clear();
+ }, []);
+
+ // Track which rows are actually on screen. Without a visibility signal (jsdom, old webviews)
+ // every row counts as visible, which is the old eager behaviour rather than a blank list.
+ useEffect(() => {
+ const root = listRef.current;
+ if (!root) return;
+ if (typeof IntersectionObserver === "undefined") {
+ setVisible(new Set(rows.map((r) => r.id)));
+ return;
+ }
+ const io = new IntersectionObserver(
+ (entries) => {
+ setVisible((prev) => {
+ const next = new Set(prev);
+ for (const entry of entries) {
+ const id = (entry.target as HTMLElement).dataset.archivedId;
+ if (!id) continue;
+ if (entry.isIntersecting) next.add(id);
+ else next.delete(id);
+ }
+ return next;
+ });
+ },
+ // A little margin so a row is fetched just before it scrolls into view.
+ { rootMargin: "200px 0px" },
+ );
+ for (const el of root.querySelectorAll("[data-archived-id]")) io.observe(el);
+ return () => io.disconnect();
+ }, [rows]);
+
+ // Thumbnails for VISIBLE rows that do not have one yet. `requested` is a ref, not state, so a
+ // landing thumbnail cannot re-enter this effect and refetch the rest.
+ const requested = useRef<Set<string>>(new Set());
+ // The latest visibility set. A fetch that lands after the user scrolled would otherwise prune
+ // against the set its own effect run closed over, protecting a row that has since gone off
+ // screen and evicting one that is on it.
+ const visibleRef = useRef<ReadonlySet<string>>(visible);
+ useEffect(() => {
+ visibleRef.current = visible;
+ }, [visible]);
+ // Prune on VISIBILITY, not only after a fetch. Rows leaving the viewport are what makes their
+ // blobs evictable, and at the end of a shelf nothing fetches again, so the budget stopped binding.
+ useEffect(() => {
+ const evicted = blobs.current.prune(visible);
+ if (evicted.length === 0) return;
+ for (const id of evicted) requested.current.delete(id);
+ setThumbs((prev) => {
+ const next = { ...prev };
+ for (const id of evicted) delete next[id];
+ return next;
+ });
+ }, [visible]);
+ // Failed attempts per row. Clearing `requested` on a failure changes nothing this effect
+ // watches, so a visible row would stay blank until the user happened to scroll it away and
+ // back. The tick schedules the retry; the count stops a permanently broken row from looping.
+ const failures = useRef(new Map<string, number>());
+ const [retryTick, setRetryTick] = useState(0);
+ // Only an unmount has to discard a fetch that already completed. A plain effect re-run (a
+ // scroll, another page) leaves that work perfectly usable, and throwing it away is what left
+ // rows blank: `requested` outlives the effect, so nothing would ever fetch them again.
+ const alive = useRef(true);
+ useEffect(() => {
+ // Set on the way in, not just cleared on the way out: StrictMode runs setup, cleanup, setup in
+ // development, so a flag only cleared by the cleanup would stay false for the rest of the
+ // dialog's life and discard every thumbnail that landed.
+ alive.current = true;
+ return () => {
+ alive.current = false;
+ };
+ }, []);
+ useEffect(() => {
+ let cancelled = false;
+ void (async () => {
+ for (const row of rows) {
+ if (cancelled) return;
+ if (!visible.has(row.id)) continue;
+ if (requested.current.has(row.id)) continue;
+ // Checked here too, not only where the retry is scheduled: a failure clears `requested`, so
+ // any later run of this effect would refetch a permanently missing file without limit.
+ if ((failures.current.get(row.id) ?? 0) > THUMB_RETRY_LIMIT) continue;
+ requested.current.add(row.id);
+ try {
+ if (isImages) {
+ const { url, bytes } = await fetchGalleryObjectUrl(row.url);
+ // Dropped from the list, or the dialog closed: there is no row left to show it on,
+ // and caching it after the unmount sweep would leak the blob.
+ if (!alive.current || !rowsRef.current.some((r) => r.id === row.id)) {
+ URL.revokeObjectURL(url);
+ requested.current.delete(row.id);
+ return;
+ }
+ blobs.current.set(row.id, url, bytes);
+ // Successful load: forget the earlier failures, or a single transient one after an
+ // eviction would land past the cap and leave the row blank with no retry scheduled.
+ failures.current.delete(row.id);
+ // Evict the coldest thumbnails back within budget, never one that is on screen. Since
+ // only visible rows are fetched, an evicted row is off screen by definition; clearing
+ // it from `requested` lets it fetch again when it scrolls back and this effect re-runs.
+ const evicted = blobs.current.prune(visibleRef.current);
+ setThumbs((prev) => {
+ const next = { ...prev, [row.id]: url };
+ for (const id of evicted) {
+ delete next[id];
+ requested.current.delete(id);
+ }
+ return next;
+ });
+ // Stale generation: stop iterating, but keep what this fetch already paid for.
+ if (cancelled) return;
+ continue;
+ }
+ // A clip is a short-lived signed link, not a blob: nothing to budget or revoke.
+ const src = await fetchGalleryVideoSignedUrl(row.id);
+ if (!alive.current || !rowsRef.current.some((r) => r.id === row.id)) {
+ requested.current.delete(row.id);
+ return;
+ }
+ failures.current.delete(row.id);
+ setThumbs((prev) => ({ ...prev, [row.id]: src }));
+ if (cancelled) return;
+ } catch {
+ // A missing thumbnail still leaves a usable, actionable row, so a failure is not fatal.
+ // Schedule the retry rather than only clearing the flag, which nothing would act on.
+ requested.current.delete(row.id);
+ const attempts = (failures.current.get(row.id) ?? 0) + 1;
+ failures.current.set(row.id, attempts);
+ if (attempts <= THUMB_RETRY_LIMIT) {
+ setTimeout(() => {
+ if (alive.current) setRetryTick((tick) => tick + 1);
+ }, THUMB_RETRY_DELAY_MS * attempts);
+ }
+ }
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [rows, isImages, 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".
+ const dropRow = useCallback(
+ (id: string, backToGallery: boolean) => {
+ putRows(rowsRef.current.filter((r) => r.id !== id));
+ // Every drop shifts the rows behind it up by one, so an offset taken before this point is
+ // now short. `showMore` uses the counter to notice and re-page instead of skipping a row.
+ mutations.current += 1;
+ // Release the thumbnail with the row. Its element unmounts without the observer reporting it,
+ // so the id would sit in `visible` forever and permanently protect its blob from eviction,
+ // walking the cache past its budget one restore at a time.
+ blobs.current.delete(id);
+ requested.current.delete(id);
+ setVisible((prev) => {
+ if (!prev.has(id)) return prev;
+ const next = new Set(prev);
+ next.delete(id);
+ return next;
+ });
+ setThumbs((prev) => {
+ if (!(id in prev)) return prev;
+ const next = { ...prev };
+ delete next[id];
+ return next;
+ });
+ // The page that owns this gallery is mounted persistently and only loads on mount, so a
+ // restore has to be announced or the strip stays stale until a reload. A delete does not:
+ // the item was archived, so it was never on that strip, and refetching would only cost the
+ // user the pages they had scrolled to.
+ if (backToGallery) notifyGalleryChanged(kind);
+ },
+ [kind, putRows],
+ );
+
+ async function handleRestore(row: ArchivedRow) {
+ // Held for the whole round trip: the server shortens the shelf when it processes this, so a
+ // page read inside that window sees it at the offset it captured with nothing to notice.
+ mutations.current += 1;
+ pendingMutations.current += 1;
+ try {
+ if (isImages) await setGalleryImageFlags(row.id, { archived: false });
+ else await setGalleryVideoFlags(row.id, { archived: false });
+ dropRow(row.id, true);
+ pendingMutations.current -= 1;
+ toast.success(`${isImages ? "Image" : "Video"} restored`);
+ } catch (err) {
+ pendingMutations.current -= 1;
+ toast.error(`Failed to restore ${noun}`, {
+ description: err instanceof Error ? err.message : undefined,
+ });
+ }
+ }
+
+ async function handleDelete(row: ArchivedRow) {
+ // Held for the whole round trip: the server shortens the shelf when it processes this, so a
+ // page read inside that window sees it at the offset it captured with nothing to notice.
+ mutations.current += 1;
+ pendingMutations.current += 1;
+ try {
+ if (isImages) await deleteGalleryImage(row.id);
+ else await deleteGalleryVideo(row.id);
+ dropRow(row.id, false);
+ pendingMutations.current -= 1;
+ toast.success(`${isImages ? "Image" : "Video"} deleted`);
+ } catch (err) {
+ pendingMutations.current -= 1;
+ toast.error(`Failed to delete ${noun}`, {
+ description: err instanceof Error ? err.message : undefined,
+ });
+ }
+ }
+
+ async function showMore() {
+ 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.
+ for (let attempt = 0; attempt < 4; attempt += 1) {
+ const before = mutations.current;
+ const page = await loadPage(rowsRef.current.length);
+ 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))]);
+ setHasMore(page.hasMore);
+ return;
+ }
+ } catch (err) {
+ toast.error(`Failed to load more archived ${kind}`, {
+ description: err instanceof Error ? err.message : undefined,
+ });
+ } finally {
+ loadingMore.current = false;
+ }
+ }
+
+ if (loading) {
+ return (
+ <div className="flex justify-center py-8">
+ <Spinner className="size-5 text-muted-foreground" />
+ </div>
+ );
+ }
+
+ // Only a genuinely empty shelf ends here. Emptying the LOADED page while more remain keeps the
+ // list rendered so "Show more" survives, else the rest become unreachable without reopening.
+ if (rows.length === 0 && !hasMore) {
+ return (
+ <p className="py-8 text-center text-sm text-muted-foreground">
+ No archived {kind}.
+ </p>
+ );
+ }
+
+ return (
+ <div className="flex flex-col gap-4">
+ <div ref={listRef}>
+ <div className="flex items-center gap-4 border-b border-border/60 px-1 pb-2 text-xs font-semibold text-foreground">
+ <span className="w-10 shrink-0" />
+ <span className="flex-1">Prompt</span>
+ <span className="w-32 shrink-0">Date created</span>
+ <span className="w-16 shrink-0" />
+ </div>
+ {rows.map((row) => (
+ <div
+ key={row.id}
+ 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] ? (
+ isImages ? (
+ <img src={thumbs[row.id]} alt="" className="size-full object-cover" />
+ ) : (
+ // Muted metadata-only poster, same treatment as the filmstrip cards.
+ <video
+ src={thumbs[row.id]}
+ muted={true}
+ playsInline={true}
+ preload="metadata"
+ className="size-full object-cover"
+ />
+ )
+ ) : null}
+ </span>
+ <span className="min-w-0 flex-1 truncate" title={row.prompt}>
+ {row.prompt}
+ </span>
+ <span className="w-32 shrink-0 text-muted-foreground tabular-nums">
+ {formatCreatedAt(row.createdAtMs)}
+ </span>
+ <span className="flex w-16 shrink-0 items-center justify-end gap-1">
+ <button
+ type="button"
+ onClick={() => void handleRestore(row)}
+ aria-label={`Restore ${noun}`}
+ title="Restore"
+ className="inline-flex size-7 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
+ >
+ <HugeiconsIcon icon={ArchiveRestoreIcon} strokeWidth={1.75} className="size-4" />
+ </button>
+ <button
+ type="button"
+ onClick={() => void handleDelete(row)}
+ aria-label={`Delete ${noun}`}
+ title="Delete"
+ className="inline-flex size-7 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive"
+ >
+ <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-4" />
+ </button>
+ </span>
+ </div>
+ ))}
+ {hasMore ? (
+ <div className="flex justify-center pt-3">
+ <Button variant="outline" size="sm" onClick={() => void showMore()}>
+ Show more
+ </Button>
+ </div>
+ ) : null}
+ </div>
+ </div>
+ );
+}
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 c3a201f060d..6f4e696b854 100644
--- a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
+++ b/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
@@ -18,6 +18,9 @@ export type SettingsTab =
export type SettingsScrollTarget = "about-updates" | "appearance-sidebar-nav";
+/** Which archive the Data tab should open straight into. */
+export type ArchivedShelf = "chats" | "images" | "videos";
+
interface OpenDialogOptions {
scrollTarget?: SettingsScrollTarget;
}
@@ -31,11 +34,12 @@ interface SettingsDialogState {
// previous-focus capture, leaving focus on <body> after close. We restore
// explicitly via onCloseAutoFocus.
opener: HTMLElement | null;
- // Set when something asks to jump straight to the archived chats list (the
- // archive toast). DataTab uses it as its initial subpage, then clears it.
- archivedChatsRequested: boolean;
+ // Set when something asks to jump straight to an archive listing (the archive
+ // toast). DataTab uses it as its initial subpage, then clears it.
+ archivedRequested: ArchivedShelf | null;
openDialog: (tab?: SettingsTab, options?: OpenDialogOptions) => void;
openArchivedChats: () => void;
+ openArchivedMedia: (shelf: "images" | "videos") => void;
consumeArchivedChatsRequest: () => void;
consumeScrollTarget: (target: SettingsScrollTarget) => void;
closeDialog: () => void;
@@ -83,7 +87,7 @@ export const useSettingsDialogStore = create<SettingsDialogState>((set) => ({
activeTab: loadInitialTab(),
scrollTarget: null,
opener: null,
- archivedChatsRequested: false,
+ archivedRequested: null,
openDialog: (tab, options) =>
set((state) => ({
open: true,
@@ -96,10 +100,18 @@ export const useSettingsDialogStore = create<SettingsDialogState>((set) => ({
open: true,
activeTab: "data",
scrollTarget: null,
- archivedChatsRequested: true,
+ archivedRequested: "chats",
+ opener: captureOpener(),
+ }),
+ openArchivedMedia: (shelf) =>
+ set({
+ open: true,
+ activeTab: "data",
+ scrollTarget: null,
+ archivedRequested: shelf,
opener: captureOpener(),
}),
- consumeArchivedChatsRequest: () => set({ archivedChatsRequested: false }),
+ consumeArchivedChatsRequest: () => set({ archivedRequested: null }),
consumeScrollTarget: (target) =>
set((state) => ({
scrollTarget: state.scrollTarget === target ? null : state.scrollTarget,
diff --git a/studio/frontend/src/features/settings/tabs/data-tab.tsx b/studio/frontend/src/features/settings/tabs/data-tab.tsx
index 2f8cb414608..93c8d956b72 100644
--- a/studio/frontend/src/features/settings/tabs/data-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/data-tab.tsx
@@ -65,6 +65,7 @@ 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 {
createFineTuneRecipeFromChats,
loadFineTuneDatasetInTrainTab,
@@ -81,21 +82,26 @@ import {
// display order, and the guard against a persisted action this build dropped.
const FINE_TUNE_ACTIONS: FineTuneAction[] = ["export", "train", "recipes"];
+// Which subpage an "open the archive" request lands on.
+const SUBPAGE_FOR_SHELF = {
+ chats: "archived",
+ images: "archived-images",
+ videos: "archived-videos",
+} as const;
+
export function DataTab() {
const t = useT();
const navigate = useNavigate();
- const archivedChatsRequested = useSettingsDialogStore(
- (s) => s.archivedChatsRequested,
- );
+ const archivedRequested = useSettingsDialogStore((s) => s.archivedRequested);
const consumeArchivedChatsRequest = useSettingsDialogStore(
(s) => s.consumeArchivedChatsRequest,
);
const [confirmOpen, setConfirmOpen] = useState(false);
const [archiveConfirmOpen, setArchiveConfirmOpen] = useState(false);
// Subpages swap the Data tab body instead of opening nested dialogs.
- const [subpage, setSubpage] = useState<"main" | "archived" | "files">(
- archivedChatsRequested ? "archived" : "main",
- );
+ const [subpage, setSubpage] = useState<
+ "main" | "archived" | "archived-images" | "archived-videos" | "files"
+ >(archivedRequested ? SUBPAGE_FOR_SHELF[archivedRequested] : "main");
const [count, setCount] = useState<number | null>(null);
const [exporting, setExporting] = useState(false);
const [archivedExporting, setArchivedExporting] = useState(false);
@@ -131,17 +137,17 @@ export function DataTab() {
// Requests can arrive after Data is already mounted (for example from the
// archive-all toast), so always switch before consuming the flag.
useEffect(() => {
- if (!archivedChatsRequested) return;
+ if (!archivedRequested) return;
let cancelled = false;
queueMicrotask(() => {
if (cancelled) return;
- setSubpage("archived");
+ setSubpage(SUBPAGE_FOR_SHELF[archivedRequested]);
consumeArchivedChatsRequest();
});
return () => {
cancelled = true;
};
- }, [archivedChatsRequested, consumeArchivedChatsRequest]);
+ }, [archivedRequested, consumeArchivedChatsRequest]);
useEffect(() => {
if (!ragAvailabilityUnknown) return;
@@ -460,6 +466,43 @@ export function DataTab() {
);
}
+ if (subpage === "archived-images" || subpage === "archived-videos") {
+ const isImages = subpage === "archived-images";
+ return (
+ <div className="flex flex-col gap-6">
+ <header className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={() => setSubpage("main")}
+ aria-label={t("settings.data.backToData")}
+ className="inline-flex size-7 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
+ >
+ <HugeiconsIcon icon={ArrowLeft01Icon} className="size-4" />
+ </button>
+ <h1 className="text-xl font-semibold font-heading">
+ {t("settings.data.title")}
+ </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>
+ </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"} />
+ </div>
+ );
+ }
+
if (subpage === "files") {
return (
<div className="flex flex-col gap-6">
@@ -576,6 +619,32 @@ export function DataTab() {
</Button>
</SettingsRow>
+ <SettingsRow
+ label={t("settings.data.archivedImages")}
+ description={t("settings.data.archivedImagesDescription")}
+ >
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setSubpage("archived-images")}
+ >
+ {t("settings.data.manageAction")}
+ </Button>
+ </SettingsRow>
+
+ <SettingsRow
+ label={t("settings.data.archivedVideos")}
+ description={t("settings.data.archivedVideosDescription")}
+ >
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setSubpage("archived-videos")}
+ >
+ {t("settings.data.manageAction")}
+ </Button>
+ </SettingsRow>
+
<SettingsRow
label={t("settings.data.archiveAllChats")}
description={t("settings.data.archiveAllChatsDescription")}
diff --git a/studio/frontend/src/features/video/api.ts b/studio/frontend/src/features/video/api.ts
index 2354bfa9d93..60f780d5f91 100644
--- a/studio/frontend/src/features/video/api.ts
+++ b/studio/frontend/src/features/video/api.ts
@@ -207,6 +207,9 @@ export interface GalleryVideo {
offload_policy?: string | null;
// Creation time (ISO 8601 timestamp).
created_at: string;
+ // Library state, not recipe: stored beside the clip, absent on sidecars written before this existed.
+ pinned?: boolean;
+ archived?: boolean;
}
// Acknowledgement that the job started; the saved record arrives via getVideoGenerateProgress at phase "completed".
@@ -301,9 +304,30 @@ export interface VideoGalleryPage {
has_more: boolean;
}
-export async function getVideoGallery(offset = 0, limit = 50): Promise<VideoGalleryPage> {
+/** `archived` picks WHICH shelf to page over: false is the strip, true is the archive. */
+export async function getVideoGallery(
+ offset = 0,
+ limit = 50,
+ archived = false,
+): Promise<VideoGalleryPage> {
return parseJson(
- await authFetch(`/api/inference/video/gallery?offset=${offset}&limit=${limit}`),
+ await authFetch(
+ `/api/inference/video/gallery?offset=${offset}&limit=${limit}&archived=${archived}`,
+ ),
+ );
+}
+
+/** Pin/unpin or archive/restore one clip; omitted flags are left alone. Returns the new record. */
+export async function setGalleryVideoFlags(
+ id: string,
+ flags: { pinned?: boolean; archived?: boolean },
+): Promise<GalleryVideo> {
+ return parseJson(
+ await authFetch(`/api/inference/video/gallery/${id}`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(flags),
+ }),
);
}
diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsx
index fb9639ff112..cf34e900b21 100644
--- a/studio/frontend/src/features/video/video-page.tsx
+++ b/studio/frontend/src/features/video/video-page.tsx
@@ -8,13 +8,28 @@ import {
FlimSlateIcon,
Image03Icon,
InformationCircleIcon,
+ PinIcon,
VolumeHighIcon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { AdvancedDisclosure } from "@/components/advanced-disclosure";
+import { GalleryItemMenu } from "@/components/gallery-item-menu";
import { ImageDropzone } from "@/components/image-dropzone";
import { MediaPageLink } from "@/components/media-page-link";
+import { useSettingsDialogStore } from "@/features/settings/stores/settings-dialog-store";
+import {
+ applyPin,
+ fetchNextPage,
+ fetchWhileStable,
+ nextSelectedId,
+ pinnedOrder,
+ removeGalleryItem,
+ restorePinOrder,
+ serializeById,
+ sortGalleryItems,
+ subscribeGalleryChanged,
+} from "@/lib/gallery-flags";
import { useHardwareInfo } from "@/hooks/use-hardware-info";
import { usePersistedToggle } from "@/hooks/use-persisted-toggle";
import { Button } from "@/components/ui/button";
@@ -106,6 +121,7 @@ import {
cancelVideoGeneration,
clearVideoGallery,
deleteGalleryVideo,
+ setGalleryVideoFlags,
fetchGalleryVideoExport,
fetchGalleryVideoSignedUrl,
generateVideo,
@@ -171,6 +187,9 @@ const galleryCache: {
inflight: Set<string>;
// Ids deleted while their link was still being minted, so a reply landing after the delete is not cached. Clear-all bumps the epoch instead.
deleted: Set<string>;
+ /** Clips archived locally: a terminal progress response snapshotted before the archive cannot be
+ * revoked, so the merges below must refuse it or the clip returns to the active strip. */
+ archived: Set<string>;
epoch: number;
} = {
videos: [],
@@ -181,6 +200,7 @@ const galleryCache: {
refreshed: new Set(),
inflight: new Set(),
deleted: new Set(),
+ archived: new Set(),
epoch: 0,
};
@@ -190,6 +210,10 @@ const VIDEO_LINK_REFRESH_MS = 6 * 60 * 60 * 1000;
// Videos loaded per infinite-scroll page.
const PAGE_SIZE = 50;
+// Passes a window resync may make before giving up. Each extra pass only happens when pagination
+// moved while it was fetching, which cannot repeat indefinitely without the user scrolling along.
+const RESYNC_MAX_ATTEMPTS = 3;
+
// Export filename, e.g. Unsloth_video_20260624-143005_123.mp4.
type VideoExportFormat = "mp4" | "webm" | "gif";
@@ -1208,9 +1232,30 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
})();
}, [selected, ensureSrc]);
+ // Bumped by every LOCAL change to the strip: a pin, an archive, a delete, a merged generation.
+ // A resync started before one of those holds a snapshot the server listing cannot reconcile with
+ // what the user just did, so it drops it rather than applying a window they have moved off.
+ const stripEpoch = useRef(0);
+ // Bumped by the window growing from the server instead: a load, an appended page. That is not a
+ // conflict, it just means the resync sized itself against a smaller window, so it refetches.
+ const pageEpoch = useRef(0);
+ // Only the most recently started resync may apply. Two restores in a row start two of them, and
+ // the older snapshot arriving last would drop whatever the newer one had already shown.
+ const resyncSeq = useRef(0);
+ // Shelf mutations in flight. The epoch is an EDGE, so a page starting after the bump and landing
+ // before the row is dropped sees it hold still. A page is only trusted while this is zero.
+ const pendingShelfMutations = useRef(0);
+
const loadGallery = useCallback(async () => {
try {
- const page = await getVideoGallery(0, PAGE_SIZE);
+ // Fenced: this page renders from the module cache while the load runs, so its tiles are
+ // actionable, and a pre-pin snapshot would undo the action with nothing to correct it.
+ const page = await fetchWhileStable(
+ () => stripEpoch.current,
+ () => getVideoGallery(0, PAGE_SIZE),
+ );
+ if (!page) return;
+ pageEpoch.current += 1;
galleryCache.videos = page.videos;
galleryCache.hasMore = page.has_more;
setVideos(page.videos);
@@ -1228,7 +1273,17 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
if (loadingMore.current || !galleryCache.hasMore) return;
loadingMore.current = true;
try {
- const page = await getVideoGallery(galleryCache.videos.length, PAGE_SIZE);
+ // Guarded on all three counters: an archive landing anywhere across this GET shortens the
+ // shelf, and the clip that shifts over the page boundary is returned by no page at all.
+ const result = await fetchNextPage(
+ () => galleryCache.videos.length,
+ () => stripEpoch.current,
+ () => pendingShelfMutations.current,
+ (offset) => getVideoGallery(offset, PAGE_SIZE),
+ );
+ if (!result) return;
+ const page = result.page;
+ pageEpoch.current += 1;
setVideos((prev) => {
const seen = new Set(prev.map((v) => v.id));
const next = [...prev, ...page.videos.filter((v) => !seen.has(v.id))];
@@ -1275,26 +1330,217 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
[],
);
- const handleDelete = useCallback(async (id: string) => {
- try {
- await deleteGalleryVideo(id);
- } catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to delete video");
- return;
+ // Drop a clip from the strip. `discardLink` is for a real delete: the bytes are gone, so the
+ // cached link must go and any mint in flight must throw its result away. An archived clip keeps
+ // both, since the archived view plays the same file.
+ const dropFromStrip = useCallback((id: string, discardLink: boolean) => {
+ if (discardLink) {
+ galleryCache.srcById.delete(id);
+ galleryCache.refreshed.delete(id);
+ galleryCache.deleted.add(id);
+ setSrcById((prev) => {
+ const next = { ...prev };
+ delete next[id];
+ return next;
+ });
}
- galleryCache.srcById.delete(id);
- galleryCache.refreshed.delete(id);
- // A mint still in flight for this id must throw its link away rather than cache it.
- galleryCache.deleted.add(id);
- setSrcById((prev) => {
- const next = { ...prev };
- delete next[id];
- return next;
- });
- setVideos((prev) => prev.filter((v) => v.id !== id));
- setSelectedId((cur) => (cur === id ? null : cur));
+ stripEpoch.current += 1;
+ // Read the list from the cache (kept in sync with state every render) rather than nesting a
+ // setSelectedId inside a setVideos updater, which would run a side effect during dispatch.
+ const at = galleryCache.videos.findIndex((v) => v.id === id);
+ const next = removeGalleryItem(galleryCache.videos, id);
+ galleryCache.videos = next;
+ setVideos(next);
+ setSelectedId((cur) => nextSelectedId(next, id, cur, at));
}, []);
+ const handleDelete = useCallback(
+ async (id: string) => {
+ // Held for the whole round trip: the server shortens the shelf when it processes this, and a
+ // page read inside that window sees the shortened list at an offset nothing contradicts.
+ stripEpoch.current += 1;
+ pendingShelfMutations.current += 1;
+ try {
+ await deleteGalleryVideo(id);
+ } catch (err) {
+ pendingShelfMutations.current -= 1;
+ toast.error(err instanceof Error ? err.message : "Failed to delete video");
+ return;
+ }
+ dropFromStrip(id, true);
+ pendingShelfMutations.current -= 1;
+ },
+ [dropFromStrip],
+ );
+
+ /**
+ * Refetch the loaded window from offset 0.
+ *
+ * Unpinning can drop a clip past the end of the loaded window and promote a previously unloaded
+ * one into it. The local reorder cannot know about the promoted clip, and the next loadMore
+ * still pages from the unchanged length, so that clip would be skipped until a reload.
+ */
+ const resyncWindow = useCallback(
+ async (count: number, stillFresh?: () => boolean) => {
+ const ticket = (resyncSeq.current += 1);
+ for (let attempt = 0; attempt < RESYNC_MAX_ATTEMPTS; attempt += 1) {
+ const paged = pageEpoch.current;
+ // Sized against the live window, so a page appended while this ran is covered rather than
+ // cut back off the bottom of the strip when the snapshot lands.
+ const wanted = Math.max(count, galleryCache.videos.length, PAGE_SIZE);
+ const collected: GalleryVideo[] = [];
+ let more = false;
+ while (collected.length < wanted) {
+ // The REMAINDER, not a whole page: a window of 51 (a page plus one new generation) would
+ // otherwise ask for 100 and grow the strip to match, reading 49 recipes off disk and
+ // rendering their tiles for a one-row shortfall.
+ const page = await getVideoGallery(
+ collected.length,
+ Math.min(PAGE_SIZE, wanted - collected.length),
+ );
+ collected.push(...page.videos);
+ more = page.has_more;
+ if (!page.has_more || page.videos.length === 0) break;
+ }
+ // Checked here, not by the caller: by the time this returns the window is already applied,
+ // so a stale snapshot has to be dropped before it overwrites a newer local change.
+ if (stillFresh && !stillFresh()) return;
+ if (resyncSeq.current !== ticket) return;
+ // Pagination moved under this pass. That is only server data, so cover it with another
+ // pass instead of giving up: giving up is what left an unpin's promoted clip missing.
+ if (pageEpoch.current !== paged) continue;
+ galleryCache.videos = collected;
+ galleryCache.hasMore = more;
+ setVideos(collected);
+ setHasMore(more);
+ if (typeof IntersectionObserver === "undefined") {
+ collected.forEach((video) => void ensureSrc(video));
+ }
+ return;
+ }
+ },
+ [ensureSrc],
+ );
+
+ // This page stays mounted across route changes, so a restore from the Settings archive would
+ // otherwise not reach the strip until a full reload. Resync the window that is actually loaded:
+ // loadGallery would cut it back to the first page and throw away everything scrolled to.
+ useEffect(
+ () =>
+ subscribeGalleryChanged("videos", () => {
+ // Bumped FIRST: a restore changes the shelf, so reads already in flight must be discarded.
+ // Capturing without advancing let them pass their own checks and land on the new window.
+ stripEpoch.current += 1;
+ // Fenced like the unpin resync: a generation or a new page landing while this GET runs
+ // would otherwise be overwritten by a snapshot taken before it.
+ const epoch = stripEpoch.current;
+ void resyncWindow(
+ galleryCache.videos.length,
+ () => stripEpoch.current === epoch,
+ ).catch(() => void loadGallery());
+ }),
+ [loadGallery, resyncWindow],
+ );
+
+ // The pin state each id was last CLICKED into, so a failing request can tell whether it is still
+ // the current intent. Without it, a slow first click failing after a later click succeeded would
+ // roll the strip back onto the state the user has since moved off.
+ const pinAttempt = useRef(new Map<string, number>());
+ const pinSeq = useRef(0);
+
+ const handleTogglePin = useCallback(
+ async (id: string, pinned: boolean) => {
+ const loadedCount = galleryCache.videos.length;
+ // The pinned order as it stands BEFORE the click, so a failed unpin can put the clip back
+ // where it was instead of at the front of the pins.
+ const orderBefore = pinnedOrder(galleryCache.videos);
+ // A per-attempt token, not the target boolean: pin, unpin, pin stores true twice, so the FIRST
+ // attempt's failure would roll back the THIRD attempt's pin and leave the two disagreeing.
+ const attempt = (pinSeq.current += 1);
+ pinAttempt.current.set(id, attempt);
+ stripEpoch.current += 1;
+ const epoch = stripEpoch.current;
+ // Optimistic: the reorder should land on the click, not a round trip later.
+ setVideos((prev) => {
+ const next = applyPin(prev, id, pinned);
+ galleryCache.videos = next;
+ return next;
+ });
+ try {
+ // One queue for the whole gallery, not one per clip. The server stamps `pinned_at` when
+ // it runs the PATCH and orders pins by that stamp, so two requests in flight together can
+ // be stamped in either order and the strip disagrees with the next load. Issuing them one
+ // at a time makes the stamps follow the clicks.
+ await serializeById("video-pin", () => setGalleryVideoFlags(id, { pinned }));
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "Failed to pin video");
+ // Put the old order back rather than leave the strip lying about server state, but only
+ // while this is still what the user last asked for.
+ if (pinAttempt.current.get(id) === attempt) {
+ pinAttempt.current.delete(id);
+ stripEpoch.current += 1;
+ setVideos((prev) => {
+ // A failed pin simply goes back to unpinned; a failed unpin has to be restored to its
+ // old position among the pins, which applyPin cannot do (it means "freshly pinned").
+ const next = pinned
+ ? applyPin(prev, id, false)
+ : restorePinOrder(prev, id, orderBefore);
+ galleryCache.videos = next;
+ return next;
+ });
+ }
+ return;
+ }
+ if (pinAttempt.current.get(id) !== attempt) return; // superseded by a later click
+ pinAttempt.current.delete(id);
+ // Pinning keeps the same set in the window (it only moves an already-loaded clip to the
+ // front), so only unpinning can open a gap.
+ if (!pinned && loadedCount > 0) {
+ try {
+ // Fenced: a pin clicked while this GET is in flight would otherwise be overwritten by a
+ // snapshot taken before it, leaving the strip unpinned while the server is pinned.
+ await resyncWindow(loadedCount, () => stripEpoch.current === epoch);
+ } catch {
+ // Best-effort: the strip is still usable, just possibly short one clip until a reload.
+ }
+ }
+ },
+ [resyncWindow],
+ );
+
+ const handleArchive = useCallback(
+ async (id: string) => {
+ // Held for the whole round trip: the server shortens the shelf when it processes this, and a
+ // page read inside that window sees the shortened list at an offset nothing contradicts.
+ stripEpoch.current += 1;
+ pendingShelfMutations.current += 1;
+ try {
+ await setGalleryVideoFlags(id, { archived: true });
+ } catch (err) {
+ pendingShelfMutations.current -= 1;
+ toast.error(err instanceof Error ? err.message : "Failed to archive video");
+ return;
+ }
+ galleryCache.archived.add(id);
+ dropFromStrip(id, false);
+ pendingShelfMutations.current -= 1;
+ const toastId = toast(
+ <button
+ type="button"
+ onClick={() => {
+ toast.dismiss(toastId);
+ useSettingsDialogStore.getState().openArchivedMedia("videos");
+ }}
+ className="w-full cursor-pointer text-left"
+ >
+ You can view archived videos in Settings
+ </button>,
+ { closeButton: true },
+ );
+ },
+ [dropFromStrip],
+ );
+
const handleClearAll = useCallback(async () => {
try {
await clearVideoGallery();
@@ -1306,6 +1552,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
galleryCache.refreshed.clear();
// Every mint in flight now belongs to a cleared gallery, so their links are discarded on arrival. The epoch covers unlisted ids too.
galleryCache.epoch += 1;
+ stripEpoch.current += 1;
galleryCache.videos = [];
galleryCache.hasMore = false;
galleryCache.selectedId = null;
@@ -1528,11 +1775,19 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
setBusy(null);
setGenStep(null);
if (p.phase === "completed" && p.video) {
- // Prepend the new clip (newest first) and mint its link.
+ // Merge the new clip and mint its link. Sorted, not prepended: a new clip is unpinned,
+ // so the server puts it after the pinned group.
const clip = p.video;
- setVideos((prev) => [clip, ...prev.filter((v) => v.id !== clip.id)]);
- setSelectedId(clip.id);
- void ensureSrc(clip);
+ // Refused if archived while this poll was in flight: forgetting the backend record
+ // cannot revoke a response already on the wire, and it still says archived: false.
+ if (!galleryCache.archived.has(clip.id) && !galleryCache.deleted.has(clip.id)) {
+ stripEpoch.current += 1;
+ setVideos((prev) =>
+ sortGalleryItems([clip, ...prev.filter((v) => v.id !== clip.id)]),
+ );
+ setSelectedId(clip.id);
+ void ensureSrc(clip);
+ }
} else if (p.phase === "failed") {
const msg = p.error || "Video generation failed";
// The user's own Cancel surfaces as the backend's cancelled sentinel; not an error.
@@ -1591,8 +1846,11 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
// The job finished while no page was mounted. The terminal record persists until the next job; merging here covers the race where it completed after the mount fetch.
const clip = g.video;
// Deleted this session: the backend clears its terminal record on delete, but a client racing that must not merge a record whose file is gone.
- if (!galleryCache.deleted.has(clip.id)) {
- setVideos((prev) => (prev.some((v) => v.id === clip.id) ? prev : [clip, ...prev]));
+ if (!galleryCache.deleted.has(clip.id) && !galleryCache.archived.has(clip.id)) {
+ stripEpoch.current += 1;
+ setVideos((prev) =>
+ prev.some((v) => v.id === clip.id) ? prev : sortGalleryItems([clip, ...prev]),
+ );
void ensureSrc(clip);
}
} else if (g.phase === "failed") {
@@ -3154,20 +3412,17 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
- <Tooltip>
- <TooltipTrigger asChild={true}>
- <Button
- size="sm"
- variant="ghost"
- aria-label="Delete video"
- className="text-muted-foreground hover:text-destructive"
- onClick={() => void handleDelete(selected.id)}
- >
- <HugeiconsIcon icon={Delete02Icon} className="size-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>Delete</TooltipContent>
- </Tooltip>
+ <GalleryItemMenu
+ noun="video"
+ active={active}
+ pinned={Boolean(selected.pinned)}
+ archived={Boolean(selected.archived)}
+ onTogglePin={() =>
+ void handleTogglePin(selected.id, !selected.pinned)
+ }
+ onToggleArchive={() => void handleArchive(selected.id)}
+ onDelete={() => void handleDelete(selected.id)}
+ />
</div>
</>
) : selected ? (
@@ -3229,14 +3484,21 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
<Spinner className="size-5 text-muted-foreground" />
</div>
)}
+ {/* The card is a wrapper, not a button: the actions menu has to be the select
+ button's SIBLING, since a button inside a button is invalid and would swallow
+ its own clicks. data-clip-id rides the wrapper so the observer still sees it. */}
{videos.map((video) => (
- <Tooltip key={video.id}>
+ <div
+ key={video.id}
+ data-clip-id={video.id}
+ className="group relative h-16 w-24 shrink-0"
+ >
+ <Tooltip>
<TooltipTrigger asChild={true}>
<button
type="button"
- data-clip-id={video.id}
onClick={() => setSelectedId(video.id)}
- className="relative flex h-16 w-24 shrink-0 flex-col justify-end overflow-hidden rounded-[10px] bg-muted/40 outline-none ring-1 ring-transparent transition-shadow hover:ring-border focus-visible:ring-2 focus-visible:ring-ring"
+ className="relative flex size-full flex-col justify-end overflow-hidden rounded-[10px] bg-muted/40 outline-none ring-1 ring-transparent transition-shadow hover:ring-border focus-visible:ring-2 focus-visible:ring-ring"
>
{srcById[video.id] ? (
// Muted, preload="metadata" so the first frame renders as a poster without playing every card at once.
@@ -3273,6 +3535,25 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
</span>
</TooltipContent>
</Tooltip>
+ {/* Pin marker, top-left so it clears both the caption and the menu. */}
+ {video.pinned && (
+ <span className="pointer-events-none absolute left-0.5 top-0.5 z-30 rounded-full bg-background/80 p-0.5 text-foreground shadow-sm ring-1 ring-border backdrop-blur">
+ <HugeiconsIcon icon={PinIcon} className="size-3" />
+ </span>
+ )}
+ <div className="absolute right-0.5 top-0.5 z-30 opacity-0 transition-opacity focus-within:opacity-100 group-hover:opacity-100">
+ <GalleryItemMenu
+ variant="overlay"
+ noun="video"
+ active={active}
+ pinned={Boolean(video.pinned)}
+ archived={Boolean(video.archived)}
+ onTogglePin={() => void handleTogglePin(video.id, !video.pinned)}
+ onToggleArchive={() => void handleArchive(video.id)}
+ onDelete={() => void handleDelete(video.id)}
+ />
+ </div>
+ </div>
))}
{/* Tail spinner while older pages stream in on scroll. */}
{hasMore && (
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index ab671afa667..a3b57cc98cd 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -979,6 +979,10 @@ export const ar = {
"أدر سجل المحادثات والملفات المرفوعة المخزّنة على هذا الجهاز.",
archivedChats: "المحادثات المؤرشفة",
archivedChatsDescription: "اعرض المحادثات التي أرشفتها وأدرها.",
+ archivedImages: "الصور المؤرشفة",
+ archivedImagesDescription: "اعرض الصور التي أرشفتها وأدرها.",
+ archivedVideos: "الفيديوهات المؤرشفة",
+ archivedVideosDescription: "اعرض الفيديوهات التي أرشفتها وأدرها.",
manageAction: "إدارة",
exportArchivedChats: "تصدير",
exportingArchivedChats: "جارٍ التصدير...",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 0ab0eaecede..6c2fa08ab1b 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -1015,6 +1015,10 @@ export const de = {
archivedChats: "Archivierte Chats",
archivedChatsDescription:
"Zeigen Sie die von Ihnen archivierten Chats an und verwalten Sie sie.",
+ archivedImages: "Archivierte Bilder",
+ archivedImagesDescription: "Bilder anzeigen und verwalten, die du archiviert hast.",
+ archivedVideos: "Archivierte Videos",
+ archivedVideosDescription: "Videos anzeigen und verwalten, die du archiviert hast.",
manageAction: "Verwalten",
exportArchivedChats: "Exportieren",
exportingArchivedChats: "Wird exportiert...",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 542042e3bbf..1fe7522c86c 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -971,6 +971,10 @@ export const en = {
"Manage chat history and uploaded files stored on this device.",
archivedChats: "Archived chats",
archivedChatsDescription: "View and manage chats you have archived.",
+ archivedImages: "Archived images",
+ archivedImagesDescription: "View and manage images you have archived.",
+ archivedVideos: "Archived videos",
+ archivedVideosDescription: "View and manage videos you have archived.",
manageAction: "Manage",
exportArchivedChats: "Export",
exportingArchivedChats: "Exporting...",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 1f32a3e3270..fdf917fbccc 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -1005,6 +1005,10 @@ export const es = {
archivedChats: "Chats archivados",
archivedChatsDescription:
"Consulta y gestiona los chats que has archivado.",
+ archivedImages: "Imágenes archivadas",
+ archivedImagesDescription: "Consulta y gestiona las imágenes que has archivado.",
+ archivedVideos: "Vídeos archivados",
+ archivedVideosDescription: "Consulta y gestiona los vídeos que has archivado.",
manageAction: "Gestionar",
exportArchivedChats: "Exportar",
exportingArchivedChats: "Exportando...",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 1bd751b3356..db6963ee3c1 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -1013,6 +1013,10 @@ export const fr = {
archivedChats: "Discussions archivées",
archivedChatsDescription:
"Consultez et gérez les discussions que vous avez archivées.",
+ archivedImages: "Images archivées",
+ 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.",
manageAction: "Gérer",
exportArchivedChats: "Exporter",
exportingArchivedChats: "Exportation...",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index ecbb898c30c..dda49846b66 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -985,6 +985,10 @@ export const hi = {
archivedChats: "संग्रहित चैट",
archivedChatsDescription:
"आपने जो चैट संग्रहित की हैं उन्हें देखें और प्रबंधित करें।",
+ archivedImages: "संग्रहित छवियाँ",
+ archivedImagesDescription: "आपके द्वारा संग्रहित की गई छवियाँ देखें और प्रबंधित करें।",
+ archivedVideos: "संग्रहित वीडियो",
+ archivedVideosDescription: "आपके द्वारा संग्रहित किए गए वीडियो देखें और प्रबंधित करें।",
manageAction: "प्रबंधित करें",
exportArchivedChats: "एक्सपोर्ट करें",
exportingArchivedChats: "एक्सपोर्ट हो रहा है...",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index ee15375ed1c..ddb11e3a67b 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -980,6 +980,10 @@ export const it = {
archivedChats: "Chat archiviate",
archivedChatsDescription:
"Visualizza e gestisci le chat che hai archiviato.",
+ archivedImages: "Immagini archiviate",
+ archivedImagesDescription: "Visualizza e gestisci le immagini che hai archiviato.",
+ archivedVideos: "Video archiviati",
+ archivedVideosDescription: "Visualizza e gestisci i video che hai archiviato.",
manageAction: "Gestisci",
exportArchivedChats: "Esporta",
exportingArchivedChats: "Esportazione...",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 3ed7fc790e1..9a27112d532 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -954,6 +954,10 @@ export const ja = {
"このデバイスに保存されているチャット履歴とアップロード済みファイルを管理します。",
archivedChats: "アーカイブ済みチャット",
archivedChatsDescription: "アーカイブしたチャットを表示・管理します。",
+ archivedImages: "アーカイブ済み画像",
+ archivedImagesDescription: "アーカイブした画像を表示・管理します。",
+ archivedVideos: "アーカイブ済み動画",
+ archivedVideosDescription: "アーカイブした動画を表示・管理します。",
manageAction: "管理",
exportArchivedChats: "エクスポート",
exportingArchivedChats: "エクスポート中...",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 36394c6dc28..c5938481228 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -977,6 +977,10 @@ export const ko = {
"이 기기에 저장된 채팅 기록과 업로드한 파일을 관리합니다.",
archivedChats: "보관된 채팅",
archivedChatsDescription: "보관한 채팅을 확인하고 관리합니다.",
+ archivedImages: "보관된 이미지",
+ archivedImagesDescription: "보관한 이미지를 확인하고 관리합니다.",
+ archivedVideos: "보관된 동영상",
+ archivedVideosDescription: "보관한 동영상을 확인하고 관리합니다.",
manageAction: "관리",
exportArchivedChats: "내보내기",
exportingArchivedChats: "내보내는 중...",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index b17607ff74d..3b8b0dbe82f 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -990,6 +990,10 @@ export const ptBR = {
"Gerencie o histórico de chats e os arquivos enviados que ficam armazenados neste dispositivo.",
archivedChats: "Chats arquivados",
archivedChatsDescription: "Veja e gerencie os chats que você arquivou.",
+ archivedImages: "Imagens arquivadas",
+ archivedImagesDescription: "Veja e gerencie as imagens que você arquivou.",
+ archivedVideos: "Vídeos arquivados",
+ archivedVideosDescription: "Veja e gerencie os vídeos que você arquivou.",
manageAction: "Gerenciar",
exportArchivedChats: "Exportar",
exportingArchivedChats: "Exportando...",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 48f6089e5ab..f5d057f60eb 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -988,6 +988,10 @@ export const ru = {
archivedChats: "Архивные чаты",
archivedChatsDescription:
"Просматривайте чаты, отправленные в архив, и управляйте ими.",
+ archivedImages: "Архивные изображения",
+ archivedImagesDescription: "Просмотр и управление изображениями, которые вы архивировали.",
+ archivedVideos: "Архивные видео",
+ archivedVideosDescription: "Просмотр и управление видео, которые вы архивировали.",
manageAction: "Управлять",
exportArchivedChats: "Экспорт",
exportingArchivedChats: "Экспорт…",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 4e4091e60d0..9da9bf5cf37 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -949,6 +949,10 @@ export const zhCN = {
description: "管理此设备上保存的聊天记录和上传的文件。",
archivedChats: "已归档的聊天",
archivedChatsDescription: "查看和管理你归档的聊天。",
+ archivedImages: "已归档的图片",
+ archivedImagesDescription: "查看和管理你归档的图片。",
+ archivedVideos: "已归档的视频",
+ archivedVideosDescription: "查看和管理你归档的视频。",
manageAction: "管理",
exportArchivedChats: "导出",
exportingArchivedChats: "正在导出...",
diff --git a/studio/frontend/src/lib/gallery-flags.ts b/studio/frontend/src/lib/gallery-flags.ts
new file mode 100644
index 00000000000..1bebcb7879c
--- /dev/null
+++ b/studio/frontend/src/lib/gallery-flags.ts
@@ -0,0 +1,263 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * Optimistic list maths for the Images and Video galleries, kept pure so both pages share one
+ * implementation and it can be tested without rendering either.
+ *
+ * The backend is the source of truth for order (pinned first, then newest first). These helpers
+ * only reproduce that ordering locally so a click lands instantly instead of waiting on a refetch.
+ */
+
+export const GALLERY_CHANGED_EVENT = "unsloth:gallery-changed";
+
+/** Which gallery a change landed in. */
+export type GalleryKind = "images" | "videos";
+
+/**
+ * Announce that a gallery changed from OUTSIDE the page that owns it. Both pages are mounted
+ * persistently and load only on mount, so a restore from Settings would otherwise leave the strip
+ * stale until a full reload. In lib/ because emitter and listeners are both features.
+ */
+export function notifyGalleryChanged(kind: GalleryKind): void {
+ if (typeof window === "undefined") return;
+ window.dispatchEvent(new CustomEvent(GALLERY_CHANGED_EVENT, { detail: { kind } }));
+}
+
+/** Calls back when `kind` changed elsewhere. Returns an unsubscriber. */
+export function subscribeGalleryChanged(kind: GalleryKind, onChanged: () => void): () => void {
+ if (typeof window === "undefined") return () => {};
+ const handler = (event: Event) => {
+ const detail = (event as CustomEvent<{ kind?: string }>).detail;
+ if (detail?.kind === kind) onChanged();
+ };
+ window.addEventListener(GALLERY_CHANGED_EVENT, handler);
+ return () => window.removeEventListener(GALLERY_CHANGED_EVENT, handler);
+}
+
+/** The two fields these helpers care about; both gallery record types structurally satisfy it. */
+export interface FlaggableItem {
+ id: string;
+ pinned?: boolean;
+ archived?: boolean;
+ created_at: number | string;
+}
+
+/** Newest first, matching the backend's mtime ordering closely enough for an optimistic reorder. */
+function newestFirst<T extends FlaggableItem>(a: T, b: T): number {
+ const at = typeof a.created_at === "number" ? a.created_at : Date.parse(a.created_at);
+ const bt = typeof b.created_at === "number" ? b.created_at : Date.parse(b.created_at);
+ return bt - at;
+}
+
+/**
+ * Re-sort one shelf: pinned lead, then newest first.
+ *
+ * The pinned group keeps ARRIVAL order, which is the server's. It sorts pins by pin time, which the
+ * client never learns, so re-sorting them by `created_at` would rearrange them on any unrelated
+ * merge. `justPinnedId` is the exception: a fresh pin leads, matching the backend.
+ */
+export function sortGalleryItems<T extends FlaggableItem>(items: T[], justPinnedId?: string): T[] {
+ const pinned = items.filter((i) => i.pinned);
+ const rest = items.filter((i) => !i.pinned);
+ rest.sort(newestFirst);
+ if (justPinnedId) {
+ const at = pinned.findIndex((i) => i.id === justPinnedId);
+ if (at > 0) pinned.unshift(...pinned.splice(at, 1));
+ }
+ return [...pinned, ...rest];
+}
+
+/**
+ * Apply a pin toggle in place and re-sort. Archiving is NOT handled here: an archived item leaves
+ * this shelf entirely, which is `removeGalleryItem`.
+ */
+export function applyPin<T extends FlaggableItem>(items: T[], id: string, pinned: boolean): T[] {
+ const next = items.map((i) => (i.id === id ? { ...i, pinned } : i));
+ return sortGalleryItems(next, pinned ? id : undefined);
+}
+
+/** The pinned ids in their current order, to hand back to `restorePinOrder` on a failed unpin. */
+export function pinnedOrder<T extends FlaggableItem>(items: T[]): string[] {
+ return items.filter((i) => i.pinned).map((i) => i.id);
+}
+
+/**
+ * Undo a failed unpin, back to where the item WAS. `applyPin(..., true)` means "freshly pinned" and
+ * would promote it to the head instead, disagreeing with a server order that never changed.
+ *
+ * `order` is the pinned ids from before the click. An id missing from it was pinned mid-request, and
+ * `indexOf` scoring those -1 is exactly right: the newest pin leads.
+ */
+export function restorePinOrder<T extends FlaggableItem>(
+ items: T[],
+ id: string,
+ order: readonly string[],
+): T[] {
+ const next = items.map((i) => (i.id === id ? { ...i, pinned: true } : i));
+ const pinned = next.filter((i) => i.pinned);
+ const rest = next.filter((i) => !i.pinned);
+ rest.sort(newestFirst);
+ pinned.sort((a, b) => order.indexOf(a.id) - order.indexOf(b.id));
+ return [...pinned, ...rest];
+}
+
+/** Prepend a finished run's records, dropping any a concurrent load already brought in. */
+export function mergeGenerated<T extends FlaggableItem>(items: T[], fresh: T[]): T[] {
+ const known = new Set(items.map((i) => i.id));
+ return sortGalleryItems([...fresh.filter((i) => !known.has(i.id)), ...items]);
+}
+
+/** Pages to walk looking for the newest unpinned record, so an absurd pin count cannot turn a
+ * recovery probe into a full gallery scan. One page is normally enough. */
+export const NEW_RECORD_PROBE_MAX_PAGES = 5;
+
+/**
+ * Whether the gallery holds a record absent from `knownIds`, proving a generation whose POST
+ * response was lost did reach the server. A saved record is unpinned and newest, so it is the first
+ * UNPINNED row; reading row 0 instead would find a pin we already knew and report the run as never
+ * submitted.
+ */
+export interface NewRecordProbeBaseline {
+ /** Every gallery id the client had loaded when the POST went out. */
+ knownIds: ReadonlySet<string>;
+ /**
+ * Whether the window can judge an unpinned row: it held one already, or it was the whole gallery.
+ * An all-pinned window with more pages behind it cannot, since every unpinned row is unfamiliar
+ * for never having been loaded, so "unknown" stops meaning "new".
+ */
+ canJudgeUnpinned: boolean;
+}
+
+/** Build the baseline from what the client currently has loaded. */
+export function newRecordProbeBaseline<T extends FlaggableItem>(
+ loaded: T[],
+ hasMore: boolean,
+ knownIds: ReadonlySet<string>,
+): NewRecordProbeBaseline {
+ return { knownIds, canJudgeUnpinned: loaded.some((i) => !i.pinned) || !hasMore };
+}
+
+export async function hasUnknownRecord<T extends FlaggableItem>(
+ baseline: NewRecordProbeBaseline,
+ fetchPage: (offset: number) => Promise<{ items: T[]; hasMore: boolean }>,
+ pageSize: number,
+ maxPages: number = NEW_RECORD_PROBE_MAX_PAGES,
+): Promise<boolean> {
+ // Nothing the listing can show would be conclusive, so refuse to claim proof. The caller then
+ // reports the submission error, which is the loud failure rather than a silent false success.
+ if (!baseline.canJudgeUnpinned) return false;
+ for (let page = 0; page < maxPages; page += 1) {
+ const { items, hasMore } = await fetchPage(page * pageSize);
+ for (const record of items) {
+ // A saved record is never pinned, so a pinned row is never the proof -- not even an unknown
+ // one. With more pins than the client had loaded, treating an unfamiliar pin as evidence
+ // would report a generation that never reached the server as finished.
+ if (record.pinned) continue;
+ // The first unpinned row is where a new record would be, so it alone decides.
+ return !baseline.knownIds.has(record.id);
+ }
+ if (!hasMore || items.length === 0) return false;
+ }
+ return false;
+}
+
+/** In-flight tail of each key's chain, dropped once that key goes idle so the map stays small. */
+const queues = new Map<string, Promise<unknown>>();
+
+/**
+ * Run `task` after everything already queued under `key`, so a burst of clicks reaches the server in
+ * click order. Different keys stay parallel. A rejection does not break the chain, and is still
+ * delivered to whoever awaited it.
+ */
+export function serializeById<T>(key: string, task: () => Promise<T>): Promise<T> {
+ const previous = queues.get(key);
+ const run = previous ? previous.then(task, task) : task();
+ const settled = run.then(
+ () => {},
+ () => {},
+ );
+ queues.set(key, settled);
+ void settled.then(() => {
+ // Only the last link clears the key; an earlier one finishing must not drop a live chain.
+ if (queues.get(key) === settled) queues.delete(key);
+ });
+ return run;
+}
+
+/** Drop an item that was archived or deleted; order among the rest is untouched. */
+export function removeGalleryItem<T extends FlaggableItem>(items: T[], id: string): T[] {
+ return items.filter((i) => i.id !== id);
+}
+
+/** Attempts a page fetch may make before giving up, so a burst of actions cannot spin it. */
+export const PAGE_MAX_ATTEMPTS = 4;
+
+/**
+ * Run `fetch`, and use its result only if `token` held still. For a GET whose response REPLACES the
+ * strip: the backend can snapshot flags before a pin or archive and answer after it, reverting an
+ * action the user was told had succeeded, with nothing scheduled to correct it. Both pages render
+ * from a module cache while this runs, so their tiles are actionable throughout.
+ *
+ * It retries rather than fails, since the server now agrees with the local change. Null after
+ * `maxAttempts` leaves the caller its optimistic state, which is what the server just confirmed.
+ */
+export async function fetchWhileStable<T>(
+ token: () => number,
+ fetch: () => Promise<T>,
+ maxAttempts: number = PAGE_MAX_ATTEMPTS,
+): Promise<T | null> {
+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
+ const before = token();
+ const result = await fetch();
+ if (token() === before) return result;
+ }
+ return null;
+}
+
+/**
+ * Fetch the next page at an offset that is still true when the response lands.
+ *
+ * Archiving or deleting shortens the server's shelf under an in-flight request: with 50 loaded,
+ * losing one moves the record at index 50 down to 49, so a page starting at 50 begins after it and
+ * no page ever returns it. A short final page can then set `hasMore` false, so nothing looks again.
+ *
+ * All three guards are needed, because each covers a different part of the round trip.
+ * `count()` catches the row being dropped DURING the fetch. `token()`, bumped when the request
+ * starts, catches a mutation beginning during it. `pending()` catches the gap between those two,
+ * where a page begins after the bump and ends before the drop and sees both hold still across a
+ * shelf the server has already shortened.
+ */
+export async function fetchNextPage<T>(
+ count: () => number,
+ token: () => number,
+ pending: () => number,
+ fetchPage: (offset: number) => Promise<T>,
+ maxAttempts: number = PAGE_MAX_ATTEMPTS,
+): Promise<{ page: T; offset: number } | null> {
+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
+ const offset = count();
+ const before = token();
+ const page = await fetchPage(offset);
+ if (pending() === 0 && count() === offset && token() === before) {
+ return { page, offset };
+ }
+ }
+ return null;
+}
+
+/**
+ * The selection after `removedId` left the strip: keep the current pick unless it was the one that
+ * left, in which case fall to its neighbour so the preview never blanks out with items still on
+ * screen. `remaining` must already have the item removed.
+ */
+export function nextSelectedId<T extends FlaggableItem>(
+ remaining: T[],
+ removedId: string,
+ selectedId: string | null,
+ removedIndex: number,
+): string | null {
+ if (selectedId !== removedId) return selectedId;
+ if (remaining.length === 0) return null;
+ return remaining[Math.min(Math.max(removedIndex, 0), remaining.length - 1)].id;
+}
diff --git a/studio/frontend/tests/archived-thumbnail-budget.test.ts b/studio/frontend/tests/archived-thumbnail-budget.test.ts
new file mode 100644
index 00000000000..69dd29d76a6
--- /dev/null
+++ b/studio/frontend/tests/archived-thumbnail-budget.test.ts
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Why the archived media view must release a thumbnail when its row goes away.
+//
+// Eviction there protects the ids currently on screen, so a row that is restored or deleted has to
+// be dropped from that protected set AND from the cache. Its element unmounts without the observer
+// reporting it, so a stale id would stay "visible" forever and shield its blob from every later
+// prune, walking the cache past its budget one restore at a time.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { BlobUrlCache } from "../src/lib/blob-url-cache.ts";
+
+// The cache revokes on eviction; node has no object-URL registry, so record the calls instead.
+const revoked: string[] = [];
+(globalThis as { URL: { revokeObjectURL: (url: string) => void } }).URL = {
+ ...URL,
+ revokeObjectURL: (url: string) => {
+ revoked.push(url);
+ },
+} as never;
+
+test("a protected id survives eviction, so a stale one would pin its bytes forever", () => {
+ const cache = new BlobUrlCache(100);
+ cache.set("stale", "blob:stale", 80);
+ cache.set("other", "blob:other", 80);
+
+ // "stale" is still in the protected set, so prune frees the other entry instead and the cache
+ // stays over budget. That is correct while the row is on screen, and a leak once it is gone.
+ assert.deepEqual(cache.prune(new Set(["stale"])), ["other"]);
+ assert.equal(cache.has("stale"), true);
+ assert.ok(revoked.includes("blob:other"));
+});
+
+test("deleting the dropped row's entry releases its blob and restores the budget", () => {
+ const cache = new BlobUrlCache(100);
+ cache.set("dropped", "blob:dropped", 80);
+ cache.set("kept", "blob:kept", 10);
+
+ // What dropRow now does: release the entry outright rather than leaving it protected.
+ assert.equal(cache.delete("dropped"), true);
+ assert.ok(revoked.includes("blob:dropped"));
+ // With those bytes back, a later prune has no reason to evict what is still on screen.
+ assert.deepEqual(cache.prune(new Set(["kept"])), []);
+ assert.equal(cache.has("kept"), true);
+});
+
+test("deleting an id that was never cached is a no-op", () => {
+ // dropRow runs for videos too, where the thumbnail is a signed link and never enters the cache.
+ const cache = new BlobUrlCache(100);
+ assert.equal(cache.delete("never-cached"), false);
+});
diff --git a/studio/frontend/tests/gallery-flags.test.ts b/studio/frontend/tests/gallery-flags.test.ts
new file mode 100644
index 00000000000..3f3a0721045
--- /dev/null
+++ b/studio/frontend/tests/gallery-flags.test.ts
@@ -0,0 +1,476 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ PAGE_MAX_ATTEMPTS,
+ applyPin,
+ fetchNextPage,
+ fetchWhileStable,
+ hasUnknownRecord,
+ mergeGenerated,
+ newRecordProbeBaseline,
+ nextSelectedId,
+ pinnedOrder,
+ removeGalleryItem,
+ restorePinOrder,
+ serializeById,
+ sortGalleryItems,
+} from "../src/lib/gallery-flags.ts";
+
+const item = (id: string, created_at: number | string, pinned = false) => ({
+ id,
+ created_at,
+ pinned,
+});
+
+const ids = (items: { id: string }[]) => items.map((i) => i.id);
+
+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"]);
+});
+
+test("pinned items lead, keeping the order they arrived in", () => {
+ const items = [item("new", 3), item("pinnedFirst", 1, true), item("pinnedSecond", 2, true)];
+ assert.deepEqual(ids(sortGalleryItems(items)), ["pinnedFirst", "pinnedSecond", "new"]);
+});
+
+test("an unrelated merge does not rearrange the pinned group", () => {
+ // The backend orders pins by PIN time, which the client never learns. Sorting them by created_at
+ // would flip this pair, since the older item was pinned more recently and so leads on the server.
+ const serverOrder = [item("pinnedRecentlyButOld", 1, true), item("pinnedLongAgoButNew", 9, true)];
+ const merged = sortGalleryItems([item("fresh", 10), ...serverOrder]);
+ assert.deepEqual(ids(merged), ["pinnedRecentlyButOld", "pinnedLongAgoButNew", "fresh"]);
+});
+
+test("the item just pinned goes to the very front of the pinned group", () => {
+ // The backend orders pinned by pin time, which the client cannot know, so the freshly pinned
+ // item leads even though an older pin has a newer created_at.
+ const items = [item("a", 5, true), item("b", 1)];
+ assert.deepEqual(ids(applyPin(items, "b", true)), ["b", "a"]);
+});
+
+test("unpinning drops the item back into the newest-first tail", () => {
+ const items = [item("pinned", 1, true), item("newer", 9), item("older", 2)];
+ assert.deepEqual(ids(applyPin(items, "pinned", false)), ["newer", "older", "pinned"]);
+});
+
+test("pinning is applied to the record, not just the order", () => {
+ const next = applyPin([item("a", 1), item("b", 2)], "a", true);
+ assert.equal(next.find((i) => i.id === "a")?.pinned, true);
+ assert.equal(next.find((i) => i.id === "b")?.pinned, false);
+});
+
+test("ISO timestamps sort alongside epoch seconds, so videos order like images", () => {
+ const items = [
+ item("older", "2026-01-01T00:00:00Z"),
+ item("newer", "2026-06-01T00:00:00Z"),
+ ];
+ assert.deepEqual(ids(sortGalleryItems(items)), ["newer", "older"]);
+});
+
+test("removing an item leaves the rest in order", () => {
+ const items = [item("a", 3), item("b", 2), item("c", 1)];
+ assert.deepEqual(ids(removeGalleryItem(items, "b")), ["a", "c"]);
+});
+
+test("selection is untouched when some other item leaves the strip", () => {
+ const remaining = [item("a", 2), item("c", 1)];
+ assert.equal(nextSelectedId(remaining, "b", "a", 1), "a");
+});
+
+test("removing the selected item falls to the neighbour that took its place", () => {
+ const remaining = [item("a", 3), item("c", 1)];
+ assert.equal(nextSelectedId(remaining, "b", "b", 1), "c");
+});
+
+test("removing the last item selects the new last, not an empty slot", () => {
+ const remaining = [item("a", 3), item("b", 2)];
+ assert.equal(nextSelectedId(remaining, "c", "c", 2), "b");
+});
+
+test("removing the only item clears the selection", () => {
+ assert.equal(nextSelectedId([], "a", "a", 0), null);
+});
+
+test("a merged generation lands after the pinned group, not at the very front", () => {
+ // The server sorts pinned first, so prepending a fresh record would disagree with it on reload.
+ const existing = [item("pin", 1, true), item("older", 2)];
+ const fresh = item("new", 9);
+ assert.deepEqual(ids(sortGalleryItems([fresh, ...existing])), ["pin", "new", "older"]);
+});
+
+test("with nothing pinned a merged generation still leads", () => {
+ const merged = sortGalleryItems([item("new", 9), item("older", 2)]);
+ assert.deepEqual(ids(merged), ["new", "older"]);
+});
+
+// --- lost-generation probe ---------------------------------------------------------------------
+
+/** A baseline whose loaded window is a sound basis for judging an unpinned row. */
+const judging = (knownIds: ReadonlySet<string>) => ({ knownIds, canJudgeUnpinned: true });
+
+/** A fake gallery listing, already in server order, served in pages. */
+const pager =
+ (all: ReturnType<typeof item>[], pageSize: number) => async (offset: number) => ({
+ items: all.slice(offset, offset + pageSize),
+ hasMore: offset + pageSize < all.length,
+ });
+
+test("a pinned first row does not mask a newly saved record", async () => {
+ // The regression: with a pin present, reading only row 0 saw the pin, which was already known,
+ // and reported a finished generation as never submitted.
+ const listing = [item("pin", 5, true), item("fresh", 9), item("old", 1)];
+ const known = new Set(["pin", "old"]);
+ assert.equal(await hasUnknownRecord(judging(known), pager(listing, 50), 50), true);
+});
+
+test("no new record is reported when the first unpinned row is already known", async () => {
+ const listing = [item("pin", 5, true), item("known", 9), item("old", 1)];
+ assert.equal(
+ await hasUnknownRecord(judging(new Set(["pin", "known", "old"])), pager(listing, 50), 50),
+ false,
+ );
+});
+
+test("the probe walks past a pinned group that spans more than one page", async () => {
+ const listing = [
+ item("p1", 5, true),
+ item("p2", 4, true),
+ item("p3", 3, true),
+ item("fresh", 9),
+ ];
+ const known = new Set(["p1", "p2", "p3"]);
+ // Page size 2, so the first unpinned row only appears on the second page.
+ assert.equal(await hasUnknownRecord(judging(known), pager(listing, 2), 2), true);
+});
+
+test("the probe stops at its page cap instead of scanning the whole gallery", async () => {
+ const listing = Array.from({ length: 100 }, (_, i) => item(`p${i}`, 100 - i, true));
+ let pages = 0;
+ const counted = async (offset: number) => {
+ pages += 1;
+ return pager(listing, 10)(offset);
+ };
+ assert.equal(await hasUnknownRecord(judging(new Set(listing.map((i) => i.id))), counted, 10, 3), false);
+ assert.equal(pages, 3);
+});
+
+test("an empty gallery reports no new record", async () => {
+ assert.equal(await hasUnknownRecord(judging(new Set()), pager([], 50), 50), false);
+});
+
+test("an unknown pinned row is not proof that a generation landed", async () => {
+ // With more pins than the client had loaded, knownIds omits the later ones. Treating such a pin
+ // as evidence reported a lost submission as a finished run that produced no image.
+ const listing = [item("loadedPin", 5, true), item("unloadedPin", 4, true), item("old", 1)];
+ const known = new Set(["loadedPin", "old"]);
+ assert.equal(await hasUnknownRecord(judging(known), pager(listing, 50), 50), false);
+});
+
+test("a new record is still found past an unknown pinned row", async () => {
+ const listing = [item("unloadedPin", 4, true), item("fresh", 9), item("old", 1)];
+ assert.equal(await hasUnknownRecord(judging(new Set(["old"])), pager(listing, 50), 50), true);
+});
+
+// --- what the loaded window is allowed to conclude -----------------------------------------------
+
+test("an all-pinned partial window cannot judge an unpinned row", () => {
+ // 50 pins loaded, more pages behind them: every unpinned row is unfamiliar just for being
+ // unloaded, so unknown stops meaning new.
+ const loaded = Array.from({ length: 50 }, (_, i) => item(`p${i}`, 100 - i, true));
+ const known = new Set(loaded.map((i) => i.id));
+ assert.equal(newRecordProbeBaseline(loaded, true, known).canJudgeUnpinned, false);
+});
+
+test("a window holding any unpinned record can judge", () => {
+ const loaded = [item("pin", 5, true), item("plain", 4)];
+ assert.equal(newRecordProbeBaseline(loaded, true, new Set()).canJudgeUnpinned, true);
+});
+
+test("a complete window can judge even with nothing unpinned in it", () => {
+ // hasMore false means the client has the whole gallery, so there is nothing it has not seen.
+ const loaded = [item("pin", 5, true)];
+ assert.equal(newRecordProbeBaseline(loaded, false, new Set()).canJudgeUnpinned, true);
+ // The empty gallery of a first-ever generation is the same case.
+ assert.equal(newRecordProbeBaseline([], false, new Set()).canJudgeUnpinned, true);
+});
+
+test("a window that cannot judge refuses to claim proof", async () => {
+ // The regression: with 50+ pins loaded, the first historical unpinned row is necessarily
+ // unknown, and treating it as proof suppressed a real submission failure.
+ const listing = [
+ item("p0", 9, true),
+ item("p1", 8, true),
+ item("historical", 1),
+ ];
+ const loaded = [item("p0", 9, true), item("p1", 8, true)];
+ const baseline = newRecordProbeBaseline(loaded, true, new Set(["p0", "p1"]));
+ assert.equal(await hasUnknownRecord(baseline, pager(listing, 50), 50), false);
+});
+
+test("a judging window still proves a genuinely new record", async () => {
+ const listing = [item("pin", 9, true), item("fresh", 10), item("older", 1)];
+ const loaded = [item("pin", 9, true), item("older", 1)];
+ const baseline = newRecordProbeBaseline(loaded, true, new Set(["pin", "older"]));
+ assert.equal(await hasUnknownRecord(baseline, pager(listing, 50), 50), true);
+});
+
+test("an empty gallery still proves its first generation", async () => {
+ const baseline = newRecordProbeBaseline([], false, new Set());
+ assert.equal(await hasUnknownRecord(baseline, pager([item("first", 1)], 50), 50), true);
+});
+
+// --- per-item serialization ----------------------------------------------------------------------
+
+test("two tasks on the same key run in call order, never overlapping", async () => {
+ const events: string[] = [];
+ const gate = (name: string, ms: number) => async () => {
+ events.push(`${name}:start`);
+ await new Promise((r) => setTimeout(r, ms));
+ events.push(`${name}:end`);
+ };
+ // The slow one is queued first, which is exactly the case a plain `await` gets wrong: the fast
+ // second PATCH would land first and the server would keep the earlier intent.
+ const first = serializeById("img:a", gate("first", 20));
+ const second = serializeById("img:a", gate("second", 0));
+ await Promise.all([first, second]);
+ assert.deepEqual(events, ["first:start", "first:end", "second:start", "second:end"]);
+});
+
+test("different keys are not serialized against each other", async () => {
+ const events: string[] = [];
+ const slow = serializeById("img:a", async () => {
+ await new Promise((r) => setTimeout(r, 20));
+ events.push("a");
+ });
+ const fast = serializeById("img:b", async () => {
+ events.push("b");
+ });
+ await Promise.all([slow, fast]);
+ assert.deepEqual(events, ["b", "a"]);
+});
+
+test("a failure does not break the key's chain", async () => {
+ const failed = serializeById("img:c", async () => {
+ throw new Error("nope");
+ });
+ await assert.rejects(failed, /nope/);
+ assert.equal(await serializeById("img:c", async () => "ran"), "ran");
+});
+
+test("the rejection reaches the caller that queued it", async () => {
+ await serializeById("img:d", async () => "ok");
+ await assert.rejects(
+ serializeById("img:d", async () => {
+ throw new Error("second failed");
+ }),
+ /second failed/,
+ );
+});
+
+test("per item keys let a later pin be stamped first, one key per gallery does not", async () => {
+ // The server stamps pinned_at when it RUNS the PATCH and orders pins by that stamp. Two requests
+ // in flight together can therefore be stamped in either order, which is what a per-item key
+ // allowed: the strip showed the click order and the next load showed the stamp order.
+ const stamped = async (keyFor: (id: string) => string) => {
+ const order: string[] = [];
+ const patch = (id: string, ms: number) => async () => {
+ await new Promise((r) => setTimeout(r, ms));
+ order.push(id);
+ };
+ // "a" is clicked first but is the slower request.
+ await Promise.all([
+ serializeById(keyFor("a"), patch("a", 20)),
+ serializeById(keyFor("b"), patch("b", 0)),
+ ]);
+ return order;
+ };
+ assert.deepEqual(await stamped((id) => `per-item:${id}`), ["b", "a"]);
+ assert.deepEqual(await stamped(() => "one-gallery"), ["a", "b"]);
+});
+
+test("a baseline frozen before the request is not softened by a page loaded during it", async () => {
+ // The regression: the ids came from before the POST but the window half was read in the catch.
+ // Scrolling while the request was in flight paged in historical unpinned rows, which turned a
+ // window that must refuse to judge into one that judged, and the newest historical row then read
+ // as proof of a generation that never reached the server.
+ const pins = [item("p0", 9, true), item("p1", 8, true)];
+ const baseline = newRecordProbeBaseline(pins, true, new Set(["p0", "p1"]));
+ // The window the user scrolled to, and the listing, both now hold that historical row.
+ const listing = [...pins, item("historical", 1)];
+ assert.equal(await hasUnknownRecord(baseline, pager(listing, 50), 50), false);
+ // Read after the scroll instead, the same moment claims proof, which is the bug.
+ const afterScroll = newRecordProbeBaseline(listing, true, new Set(["p0", "p1"]));
+ assert.equal(await hasUnknownRecord(afterScroll, pager(listing, 50), 50), true);
+});
+
+test("a page fetch re-reads its offset when the shelf shortens mid request", async () => {
+ // The server's list, newest first. The client has the first two loaded.
+ let shelf = ["e", "d", "c", "b", "a"];
+ let loaded = ["e", "d"];
+ let epoch = 0;
+ const requested: number[] = [];
+ const result = await fetchNextPage(
+ () => loaded.length,
+ () => epoch,
+ () => 0,
+ async (offset) => {
+ requested.push(offset);
+ // The archive lands while the first request is in flight: "d" leaves the shelf, so every
+ // record behind it shifts up by one on the server AND locally.
+ if (requested.length === 1) {
+ shelf = shelf.filter((id) => id !== "d");
+ loaded = loaded.filter((id) => id !== "d");
+ }
+ return shelf.slice(offset, offset + 2);
+ },
+ );
+ assert.ok(result);
+ // Without the re-read this asks for offset 2 against the shortened shelf and returns ["b", "a"],
+ // skipping "c" entirely -- the record that shifted across the boundary.
+ assert.deepEqual(requested, [2, 1]);
+ assert.deepEqual(result.page, ["c", "b"]);
+});
+
+test("a page fetch gives up rather than spinning when the shelf keeps moving", async () => {
+ let loaded = 10;
+ let calls = 0;
+ const result = await fetchNextPage(
+ () => loaded,
+ () => 0,
+ () => 0,
+ async () => {
+ calls += 1;
+ loaded -= 1; // something mutates the list on every single response
+ return [];
+ },
+ );
+ assert.equal(result, null);
+ assert.equal(calls, PAGE_MAX_ATTEMPTS);
+});
+
+test("a failed unpin puts the image back where it was, not at the front of the pins", () => {
+ // Pins are ordered by pin TIME, which the client never learns, so a rollback must replay the
+ // order it saw. applyPin(..., true) means "freshly pinned" and would promote this to the head.
+ const before = [item("first", 1, true), item("second", 2, true), item("third", 3, true)];
+ const order = pinnedOrder(before);
+ const optimistic = applyPin(before, "third", false);
+ assert.deepEqual(ids(optimistic), ["first", "second", "third"]);
+ assert.deepEqual(ids(restorePinOrder(optimistic, "third", order)), ["first", "second", "third"]);
+ assert.deepEqual(ids(applyPin(optimistic, "third", true)), ["third", "first", "second"]);
+});
+
+test("a rollback leaves an image pinned during the request at the front", () => {
+ // Absent from the snapshot means pinned since, and the newest pin leads.
+ const before = [item("a", 1, true), item("b", 2, true)];
+ const order = pinnedOrder(before);
+ const withNewPin = applyPin([...before, item("c", 3)], "c", true);
+ assert.deepEqual(ids(restorePinOrder(withNewPin, "a", order)), ["c", "a", "b"]);
+});
+
+test("a finished generation does not duplicate a record a resync already loaded", () => {
+ const fresh = item("new", 9);
+ const alreadyLoaded = [fresh, item("old", 1)];
+ const merged = mergeGenerated(alreadyLoaded, [fresh]);
+ assert.deepEqual(ids(merged), ["new", "old"]);
+ assert.equal(merged.length, 2);
+ // And it still merges a record nothing had seen.
+ assert.deepEqual(ids(mergeGenerated([item("old", 1)], [fresh])), ["new", "old"]);
+});
+
+test("a gallery load is discarded when a pin lands while it is in flight", async () => {
+ // The response was snapshotted before the PATCH, so applying it would show the image unpinned
+ // while the server has it pinned, with nothing scheduled to correct it.
+ let epoch = 0;
+ let fetches = 0;
+ const result = await fetchWhileStable(
+ () => epoch,
+ async () => {
+ fetches += 1;
+ if (fetches === 1) epoch += 1; // the user pins mid request
+ return [item("a", 1, fetches > 1)];
+ },
+ );
+ assert.equal(fetches, 2);
+ assert.ok(result);
+ assert.equal(result[0].pinned, true); // the retry sees the server after the pin
+});
+
+test("a gallery load gives up rather than overwriting a strip that keeps changing", async () => {
+ let epoch = 0;
+ let fetches = 0;
+ const result = await fetchWhileStable(
+ () => epoch,
+ async () => {
+ fetches += 1;
+ epoch += 1;
+ return "stale";
+ },
+ );
+ // Null, so the caller keeps its optimistic state, which is what the server already agreed to.
+ assert.equal(result, null);
+ assert.equal(fetches, PAGE_MAX_ATTEMPTS);
+});
+
+test("a page fetch is refused when an archive is merely IN FLIGHT", async () => {
+ // The gap the count cannot see: the server shortens the shelf when it PROCESSES the archive,
+ // while the count only moves when the response gets back, so only a token bumped at request
+ // START reveals a page read inside that round trip.
+ const full = ["e", "d", "c", "b", "a"];
+ const shortened = ["e", "c", "b", "a"]; // the server has already archived "d"
+ let loaded = 2;
+ let epoch = 0;
+ const seen: string[][] = [];
+ const result = await fetchNextPage(
+ () => loaded,
+ () => epoch,
+ () => 0,
+ async (offset) => {
+ if (seen.length === 0) {
+ epoch += 1; // the user clicks Archive while this request is in flight
+ const page = shortened.slice(offset, offset + 2);
+ seen.push(page);
+ return page; // ["b", "a"] -- "c" would be skipped for good
+ }
+ loaded = 1; // the archive has landed locally by now
+ const page = shortened.slice(offset, offset + 2);
+ seen.push(page);
+ return page;
+ },
+ );
+ assert.deepEqual(seen[0], ["b", "a"], "the first read did skip the boundary record");
+ assert.ok(result);
+ assert.deepEqual(result.page, ["c", "b"], "the retry picks the skipped record back up");
+ assert.equal(full.length, 5);
+});
+
+test("a page fetch is refused while a shelf mutation is still pending", async () => {
+ // The token is an EDGE, not a state: a page starting after the bump and landing before the row is
+ // dropped sees it and the count hold still, so only "is anything in flight" catches this.
+ const shortened = ["e", "c", "b", "a"]; // the server has already archived "d"
+ let loaded = 2;
+ let pending = 1; // the PATCH is in flight for the whole of the first read
+ const epoch = 7; // bumped before this page even started, so it never moves again
+ const seen: string[][] = [];
+ const result = await fetchNextPage(
+ () => loaded,
+ () => epoch,
+ () => pending,
+ async (offset) => {
+ const page = shortened.slice(offset, offset + 2);
+ seen.push(page);
+ if (seen.length === 1) {
+ pending = 0; // the archive lands, the row is dropped
+ loaded = 1;
+ }
+ return page;
+ },
+ );
+ assert.deepEqual(seen[0], ["b", "a"], "the first read did skip the boundary record");
+ assert.ok(result);
+ assert.deepEqual(result.page, ["c", "b"], "the retry, once nothing is pending, recovers it");
+});