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: drag to reorder, add to project and quick download for the image and video galleries (#11758)

Michael Han83db6e07c5f9
diff --git a/studio/backend/core/inference/gallery_flags.py b/studio/backend/core/inference/gallery_flags.py
index 3a6deedf68f..002a0556efa 100644
--- a/studio/backend/core/inference/gallery_flags.py
+++ b/studio/backend/core/inference/gallery_flags.py
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Pin / archive flags for the image and video galleries.
+"""Pin / archive / manual-order 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
@@ -12,6 +12,9 @@ One store per gallery directory, keyed by the same id the gallery uses (the file
{"version": 1, "items": {"<id>": {"pinned_at": 1712345678.0, "archived": true}}}
+A dragged item also stores ``order_at``, a sort key on the mtime scale used in place of its mtime.
+Only moved items get one, and new media still lands first.
+
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
@@ -70,6 +73,8 @@ def _valid_entry(entry: Any) -> bool:
return False
if "pinned_at" in entry and _pinned_at(entry) is None:
return False
+ if "order_at" in entry and _finite(entry.get("order_at")) is None:
+ return False
return True
@@ -91,6 +96,8 @@ def _sanitize_entry(entry: Any) -> Optional[dict[str, Any]]:
clean["archived"] = True
if "pinned_at" in clean and _pinned_at(clean) is None:
clean.pop("pinned_at")
+ if "order_at" in clean and _finite(clean.get("order_at")) is None:
+ clean.pop("order_at")
return clean or None
@@ -262,22 +269,23 @@ def read_trusted(directory: Path) -> dict[str, dict[str, Any]]:
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")
+def _finite(value: Any) -> Optional[float]:
+ """A stored number as a finite float, or None when absent or unusable.
+
+ Read at listing time, so a huge JSON int, NaN or infinity must read as unset rather than raise
+ or poison the sort."""
if isinstance(value, bool) or not isinstance(value, (int, float)):
return None
try:
- pinned_at = float(value)
+ number = float(value)
except (OverflowError, ValueError):
return None
- return pinned_at if math.isfinite(pinned_at) else None
+ return number if math.isfinite(number) else None
+
+
+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."""
+ return _finite(entry.get("pinned_at"))
def flags_for(items: dict[str, dict[str, Any]], item_id: str) -> dict[str, Any]:
@@ -297,6 +305,17 @@ def pin_rank(items: dict[str, dict[str, Any]], item_id: str) -> float:
return pinned_at if pinned_at is not None else float("-inf")
+def order_at(items: dict[str, dict[str, Any]], item_id: str) -> Optional[float]:
+ """The id's manual sort key, or None if it was never dragged."""
+ return _finite(_entry(items, item_id).get("order_at"))
+
+
+def order_rank(items: dict[str, dict[str, Any]], item_id: str, mtime: float) -> float:
+ """Unpinned sort key (newest first): ``order_at`` if dragged, else mtime."""
+ manual = order_at(items, item_id)
+ return manual if manual is not None else mtime
+
+
def is_archived(items: dict[str, dict[str, Any]], item_id: str) -> bool:
return bool(_entry(items, item_id).get("archived"))
@@ -318,6 +337,18 @@ def set_flags(
return set_flags_locked(directory, item_id, pinned = pinned, archived = archived)
+def _load_repaired(directory: Path) -> dict[str, Any]:
+ """The store ready for a rewrite, with unreadable entries dropped."""
+ 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
+ return data
+
+
def set_flags_locked(
directory: Path,
item_id: str,
@@ -333,13 +364,8 @@ def set_flags_locked(
# 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
+ data = _load_repaired(directory)
+ items = data["items"]
entry = dict(_entry(items, item_id))
if pinned is not None:
if pinned:
@@ -397,3 +423,74 @@ def forget_locked(directory: Path, item_ids) -> None:
_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)
+
+
+def _between(high: Optional[float], low: Optional[float], *, top: float) -> Optional[float]:
+ """A key between ``high`` and ``low`` (descending), or None if both are None.
+
+ ``top`` is used at the head of the group, so new media created later still sorts first."""
+ if high is not None and low is not None:
+ mid = (high + low) / 2
+ # Out of float precision: tie with the upper neighbour.
+ return mid if low < mid < high else high
+ if high is not None:
+ return high - 1.0
+ if low is not None:
+ return top if top > low else math.nextafter(low, math.inf)
+ return None
+
+
+def place_locked(
+ directory: Path, item_id: str, ordered: list[tuple[str, float]], *, after_id: Optional[str]
+) -> dict[str, Any]:
+ """Move one id to just after ``after_id`` (None = front) and return its flags.
+
+ ``ordered`` is the shelf as listed, as ``(id, mtime)`` pairs. Only the moved item is rewritten,
+ with a key between its neighbours: ``pinned_at`` among pins, ``order_at`` otherwise. Dropping
+ between pins pins it, between unpinned items unpins it, and on the boundary keeps its state.
+ Call inside ``exclusive()``. Raises KeyError if ``after_id`` is not on the shelf."""
+ import time
+
+ data = _load_repaired(directory)
+ items = data["items"]
+ ids = [(i, m) for i, m in ordered if i != item_id]
+ position = 0
+ if after_id is not None:
+ position = next((n + 1 for n, (i, _) in enumerate(ids) if i == after_id), -1)
+ if position < 0:
+ raise KeyError(after_id)
+ above = ids[position - 1] if position > 0 else None
+ below = ids[position] if position < len(ids) else None
+
+ def is_pinned(pair):
+ return _pinned_at(_entry(items, pair[0])) is not None
+
+ entry = dict(_entry(items, item_id))
+ was_pinned = _pinned_at(entry) is not None
+ if above is not None and below is not None:
+ pinned = is_pinned(above) if is_pinned(above) == is_pinned(below) else was_pinned
+ elif above is not None or below is not None:
+ pinned = is_pinned(above or below)
+ else:
+ pinned = was_pinned
+
+ now = time.time()
+ if pinned:
+ high = _pinned_at(_entry(items, above[0])) if above and is_pinned(above) else None
+ low = _pinned_at(_entry(items, below[0])) if below and is_pinned(below) else None
+ entry["pinned_at"] = _between(high, low, top = now) if (high, low) != (None, None) else now
+ else:
+ entry.pop("pinned_at", None)
+ high = order_rank(items, above[0], above[1]) if above and not is_pinned(above) else None
+ low = order_rank(items, below[0], below[1]) if below and not is_pinned(below) else None
+ key = _between(high, low, top = now)
+ if key is None:
+ entry.pop("order_at", None)
+ else:
+ entry["order_at"] = key
+ 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"))}
diff --git a/studio/backend/core/inference/gallery_projects.py b/studio/backend/core/inference/gallery_projects.py
new file mode 100644
index 00000000000..a409613b751
--- /dev/null
+++ b/studio/backend/core/inference/gallery_projects.py
@@ -0,0 +1,143 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Copy a gallery image or clip into a chat project's folder.
+
+Files land in ``<project root>/sandbox/{images,videos}``, where the project's chats run their
+tools. It is a copy, so the gallery keeps its item.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import os
+import shutil
+import stat
+import uuid
+from pathlib import Path
+
+from loggers import get_logger
+
+logger = get_logger(__name__)
+
+
+class ProjectNotFound(LookupError):
+ """No live project has this id."""
+
+
+# POSIX: walk into the folder by descriptor so a symlink swapped in cannot redirect the write.
+_DIR_FLAGS = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0)
+_USE_DIR_FD = (
+ hasattr(os, "O_NOFOLLOW")
+ and {
+ os.open,
+ os.mkdir,
+ os.stat,
+ os.rename,
+ os.unlink,
+ }
+ <= os.supports_dir_fd
+)
+
+
+def _sandbox_dir(project_id: str) -> str:
+ from storage.studio_db import ensure_chat_project_workspace
+
+ project = ensure_chat_project_workspace(project_id)
+ if not project:
+ raise ProjectNotFound(project_id)
+ root_path = project.get("rootPath")
+ sandbox_path = project.get("sandboxPath")
+ if not root_path or not sandbox_path:
+ raise ProjectNotFound(project_id)
+ # Same containment check as the chat tools.
+ root_real = os.path.realpath(root_path)
+ sandbox_real = os.path.realpath(sandbox_path)
+ if sandbox_real != root_real and not sandbox_real.startswith(root_real + os.sep):
+ raise ProjectNotFound(project_id)
+ return sandbox_real
+
+
+def _tmp_name(name: str) -> str:
+ # Unique per call: two adds of one item can run at once in this process.
+ return f".{name}.tmp-{uuid.uuid4().hex}"
+
+
+def _copy_with_dir_fd(source: Path, sandbox: str, folder: str) -> bool:
+ """Copy into ``sandbox/folder`` by descriptor; returns whether it was already there."""
+ name = source.name
+ sandbox_fd = os.open(sandbox, _DIR_FLAGS)
+ try:
+ try:
+ os.mkdir(folder, 0o755, dir_fd = sandbox_fd)
+ except FileExistsError:
+ pass
+ # O_NOFOLLOW makes a symlinked folder fail here (ELOOP) instead of writing through it.
+ folder_fd = os.open(folder, _DIR_FLAGS, dir_fd = sandbox_fd)
+ finally:
+ os.close(sandbox_fd)
+ try:
+ try:
+ st = os.stat(name, dir_fd = folder_fd, follow_symlinks = False)
+ if stat.S_ISREG(st.st_mode) and st.st_size == source.stat().st_size:
+ return True
+ except FileNotFoundError:
+ pass
+ tmp = _tmp_name(name)
+ out = os.open(
+ tmp,
+ os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW,
+ 0o644,
+ dir_fd = folder_fd,
+ )
+ try:
+ with os.fdopen(out, "wb") as dst, open(source, "rb") as src:
+ shutil.copyfileobj(src, dst)
+ os.rename(tmp, name, src_dir_fd = folder_fd, dst_dir_fd = folder_fd)
+ except BaseException:
+ with contextlib.suppress(OSError):
+ os.unlink(tmp, dir_fd = folder_fd)
+ raise
+ finally:
+ os.close(folder_fd)
+ return False
+
+
+def _copy_by_path(source: Path, sandbox: str, folder: str) -> bool:
+ """Fallback without dir_fd support (Windows): resolve the folder and re-check containment."""
+ target = Path(sandbox) / folder
+ target.mkdir(exist_ok = True)
+ real = os.path.realpath(target)
+ if os.path.dirname(real) != sandbox:
+ raise PermissionError(f"{target} resolves outside the project sandbox")
+ dest = Path(real) / source.name
+ try:
+ if (
+ not dest.is_symlink()
+ and dest.is_file()
+ and dest.stat().st_size == source.stat().st_size
+ ):
+ return True
+ except OSError:
+ pass
+ tmp = Path(real) / _tmp_name(source.name)
+ try:
+ shutil.copyfile(source, tmp)
+ os.replace(tmp, dest)
+ except BaseException:
+ with contextlib.suppress(OSError):
+ tmp.unlink(missing_ok = True)
+ raise
+ return False
+
+
+def copy_into_project(source: Path, project_id: str, folder: str) -> dict[str, object]:
+ """Copy ``source`` into the project's ``folder`` and return ``{"path", "already"}``.
+
+ Keyed by the gallery id, so a second add is a no-op. Written via a temp file so a failed copy
+ leaves nothing behind. Refuses a ``folder`` that leads outside the sandbox. Raises
+ ProjectNotFound or OSError."""
+ sandbox = _sandbox_dir(project_id)
+ copy = _copy_with_dir_fd if _USE_DIR_FD else _copy_by_path
+ already = copy(source, sandbox, folder)
+ return {"path": str(Path(sandbox) / folder / source.name), "already": already}
diff --git a/studio/backend/core/inference/image_gallery.py b/studio/backend/core/inference/image_gallery.py
index 29a72b08a7e..b0434749430 100644
--- a/studio/backend/core/inference/image_gallery.py
+++ b/studio/backend/core/inference/image_gallery.py
@@ -93,13 +93,15 @@ def _record(
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
+ if flags is None:
+ flags = gallery_flags.read(gallery_dir())
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
- ),
+ **gallery_flags.flags_for(flags, image_id),
+ # Lets the client keep a dragged item in place when it re-sorts.
+ "order_at": gallery_flags.order_at(flags, image_id),
}
@@ -176,7 +178,7 @@ def list_images(
archived: bool = False,
) -> list[dict[str, Any]]:
"""A window of images for infinite scroll: pinned first (most recently pinned leading), then
- newest-first by file mtime.
+ newest-first by file mtime (or the manual key once dragged).
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.
@@ -197,7 +199,13 @@ def list_images(
# 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)
+ paths.sort(
+ key = lambda p: (
+ gallery_flags.pin_rank(flags, p.stem),
+ gallery_flags.order_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.
@@ -238,6 +246,41 @@ def set_flags(
return _record(image_id, meta)
+def move(image_id: str, after_id: Optional[str]) -> Optional[dict[str, Any]]:
+ """Move an active image to just after ``after_id`` (None = front) and return its record.
+
+ None if the id is not an owned, active image. Raises KeyError if ``after_id`` is not on the shelf."""
+ with gallery_flags.exclusive(gallery_dir()):
+ path = owned_image_path(image_id)
+ if path is None:
+ return None
+ flags = gallery_flags.read(gallery_dir())
+ if gallery_flags.is_archived(flags, image_id):
+ return None
+ # Full shelf in listing order, so neighbours past the client's loaded window are known.
+ try:
+ paths = [
+ p
+ for p in gallery_dir().glob("*.png")
+ if not gallery_flags.is_archived(flags, p.stem)
+ ]
+ except OSError:
+ paths = []
+ keyed = [(p.stem, _mtime(p)) for p in paths]
+ keyed.sort(
+ key = lambda pair: (
+ gallery_flags.pin_rank(flags, pair[0]),
+ gallery_flags.order_rank(flags, pair[0], pair[1]),
+ ),
+ reverse = True,
+ )
+ gallery_flags.place_locked(gallery_dir(), image_id, keyed, after_id = after_id)
+ 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)
# a hand-dropped foreign PNG is invisible to list_images, so a guessed id must not destroy it
diff --git a/studio/backend/core/inference/video_gallery.py b/studio/backend/core/inference/video_gallery.py
index 1b7b873d7e7..346b80c1836 100644
--- a/studio/backend/core/inference/video_gallery.py
+++ b/studio/backend/core/inference/video_gallery.py
@@ -167,13 +167,15 @@ def _record(
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
+ if flags is None:
+ flags = gallery_flags.read(gallery_dir())
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
- ),
+ **gallery_flags.flags_for(flags, video_id),
+ # Lets the client keep a dragged item in place when it re-sorts.
+ "order_at": gallery_flags.order_at(flags, video_id),
}
@@ -479,7 +481,7 @@ def list_videos(
archived: bool = False,
) -> list[dict[str, Any]]:
"""A window of videos for infinite scroll: pinned first (most recently pinned leading), then
- newest-first by MP4 mtime.
+ newest-first by MP4 mtime (or the manual key once dragged).
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.
@@ -499,7 +501,13 @@ def list_videos(
# 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)
+ paths.sort(
+ key = lambda p: (
+ gallery_flags.pin_rank(flags, p.stem),
+ gallery_flags.order_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
@@ -538,6 +546,40 @@ def set_flags(
return _record(video_id, meta)
+def move(video_id: str, after_id: Optional[str]) -> Optional[dict[str, Any]]:
+ """Move an active video to just after ``after_id`` (None = front) and return its record.
+
+ None if the id is not an owned, active video. Raises KeyError if ``after_id`` is not on the shelf."""
+ with gallery_flags.exclusive(gallery_dir()):
+ if owned_video_path(video_id) is None:
+ return None
+ flags = gallery_flags.read(gallery_dir())
+ if gallery_flags.is_archived(flags, video_id):
+ return None
+ # Full shelf in listing order, so neighbours past the client's loaded window are known.
+ try:
+ paths = [
+ p
+ for p in gallery_dir().glob("*.mp4")
+ if not gallery_flags.is_archived(flags, p.stem)
+ ]
+ except OSError:
+ paths = []
+ keyed = [(p.stem, _mtime(p)) for p in paths]
+ keyed.sort(
+ key = lambda pair: (
+ gallery_flags.pin_rank(flags, pair[0]),
+ gallery_flags.order_rank(flags, pair[0], pair[1]),
+ ),
+ reverse = True,
+ )
+ gallery_flags.place_locked(gallery_dir(), video_id, keyed, after_id = after_id)
+ 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)
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 11f8307f9c9..79a337f8ca6 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -4293,6 +4293,10 @@ class GalleryImage(BaseModel):
# 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")
+ order_at: Optional[float] = Field(
+ None,
+ description = "Manual sort key (epoch-second scale) once dragged; unset sorts by creation",
+ )
class GalleryFlagsPatch(BaseModel):
@@ -4302,6 +4306,27 @@ class GalleryFlagsPatch(BaseModel):
archived: Optional[bool] = Field(None, description = "Archive (True) or restore (False) the item")
+class GalleryMoveRequest(BaseModel):
+ """Drag one gallery item to a new place on the active shelf."""
+
+ after_id: Optional[str] = Field(
+ None, description = "Id the item now follows, as displayed; null moves it to the front"
+ )
+
+
+class GalleryProjectRequest(BaseModel):
+ """Copy one gallery item into a chat project's folder."""
+
+ project_id: str = Field(..., description = "Chat project to add the item to")
+
+
+class GalleryProjectResponse(BaseModel):
+ path: str = Field(..., description = "Where the copy now lives, inside the project's folder")
+ already: bool = Field(
+ False, description = "The project already held this item; nothing was copied"
+ )
+
+
class DiffusionGenerateResponse(BaseModel):
"""The persisted gallery records for one generation call (a batch)."""
@@ -5127,6 +5152,10 @@ class GalleryVideo(BaseModel):
# 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")
+ order_at: Optional[float] = Field(
+ None,
+ description = "Manual sort key (epoch-second scale) once dragged; unset sorts by creation",
+ )
class VideoGenerateResponse(BaseModel):
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 68a74868e01..a60ba7809dd 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -3397,6 +3397,9 @@ from models.inference import (
DiffusionInferenceInfoResponse,
DiffusionLoadProgressResponse,
GalleryFlagsPatch,
+ GalleryMoveRequest,
+ GalleryProjectRequest,
+ GalleryProjectResponse,
GalleryImage,
GalleryListResponse,
ImageGenerationRequest,
@@ -39684,6 +39687,51 @@ async def get_search_image_thumbnail(
)
+@studio_router.post("/images/gallery/{image_id}/move", response_model = GalleryImage)
+async def move_gallery_image(
+ image_id: str,
+ body: GalleryMoveRequest,
+ current_subject: str = Depends(get_current_subject),
+):
+ """Move one image to just after ``after_id``. Dropping among pins pins it, elsewhere unpins it."""
+ from core.inference import image_gallery
+
+ try:
+ record = await asyncio.to_thread(image_gallery.move, image_id, body.after_id)
+ except KeyError:
+ # The neighbour left the shelf; the client resyncs.
+ raise HTTPException(status_code = 409, detail = "The gallery changed; try the move again.")
+ except OSError as exc:
+ logger.warning("image_gallery.move_failed: %s", exc)
+ raise HTTPException(status_code = 500, detail = "Could not save the new order.")
+ if record is None:
+ raise HTTPException(status_code = 404, detail = "Image not found.")
+ return GalleryImage(**record)
+
+
+@studio_router.post("/images/gallery/{image_id}/project", response_model = GalleryProjectResponse)
+async def add_gallery_image_to_project(
+ image_id: str,
+ body: GalleryProjectRequest,
+ current_subject: str = Depends(get_current_subject),
+):
+ """Copy one image into a chat project's folder."""
+ from core.inference import image_gallery
+ from core.inference.gallery_projects import ProjectNotFound, copy_into_project
+
+ path = await asyncio.to_thread(image_gallery.owned_image_path, image_id)
+ if path is None:
+ raise HTTPException(status_code = 404, detail = "Image not found.")
+ try:
+ result = await asyncio.to_thread(copy_into_project, path, body.project_id, "images")
+ except ProjectNotFound:
+ raise HTTPException(status_code = 404, detail = "Project not found.")
+ except OSError as exc:
+ logger.warning("image_gallery.add_to_project_failed: %s", exc)
+ raise HTTPException(status_code = 500, detail = "Could not copy the image into the project.")
+ return GalleryProjectResponse(**result)
+
+
@studio_router.patch("/images/gallery/{image_id}", response_model = GalleryImage)
async def update_gallery_image_flags(
image_id: str,
diff --git a/studio/backend/routes/video.py b/studio/backend/routes/video.py
index 535afbf7569..a96ae605913 100644
--- a/studio/backend/routes/video.py
+++ b/studio/backend/routes/video.py
@@ -53,6 +53,9 @@ from loggers.media_progress import (
from models.inference import (
DiffusionDownloadPlanResponse,
GalleryFlagsPatch,
+ GalleryMoveRequest,
+ GalleryProjectRequest,
+ GalleryProjectResponse,
GalleryVideo,
VideoGalleryListResponse,
VideoGenerateProgressResponse,
@@ -957,6 +960,51 @@ 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}/move", response_model = GalleryVideo)
+async def move_gallery_video(
+ video_id: str,
+ body: GalleryMoveRequest,
+ current_subject: str = Depends(get_current_subject),
+):
+ """Move one video to just after ``after_id``. Dropping among pins pins it, elsewhere unpins it."""
+ from core.inference import video_gallery
+
+ try:
+ record = await asyncio.to_thread(video_gallery.move, video_id, body.after_id)
+ except KeyError:
+ # The neighbour left the shelf; the client resyncs.
+ raise HTTPException(status_code = 409, detail = "The gallery changed; try the move again.")
+ except OSError as exc:
+ logger.warning("video_gallery.move_failed: %s", exc)
+ raise HTTPException(status_code = 500, detail = "Could not save the new order.")
+ if record is None:
+ raise HTTPException(status_code = 404, detail = "Video not found.")
+ return GalleryVideo(**record)
+
+
[email protected]("/video/gallery/{video_id}/project", response_model = GalleryProjectResponse)
+async def add_gallery_video_to_project(
+ video_id: str,
+ body: GalleryProjectRequest,
+ current_subject: str = Depends(get_current_subject),
+):
+ """Copy one video into a chat project's folder."""
+ from core.inference import video_gallery
+ from core.inference.gallery_projects import ProjectNotFound, copy_into_project
+
+ path = await asyncio.to_thread(video_gallery.owned_video_path, video_id)
+ if path is None:
+ raise HTTPException(status_code = 404, detail = "Video not found.")
+ try:
+ result = await asyncio.to_thread(copy_into_project, path, body.project_id, "videos")
+ except ProjectNotFound:
+ raise HTTPException(status_code = 404, detail = "Project not found.")
+ except OSError as exc:
+ logger.warning("video_gallery.add_to_project_failed: %s", exc)
+ raise HTTPException(status_code = 500, detail = "Could not copy the video into the project.")
+ return GalleryProjectResponse(**result)
+
+
@router.patch("/video/gallery/{video_id}", response_model = GalleryVideo)
async def update_gallery_video_flags(
video_id: str,
diff --git a/studio/backend/tests/test_gallery_flags.py b/studio/backend/tests/test_gallery_flags.py
index 6729f1228d5..7f2336cc3ca 100644
--- a/studio/backend/tests/test_gallery_flags.py
+++ b/studio/backend/tests/test_gallery_flags.py
@@ -380,3 +380,122 @@ def test_a_filesystem_that_cannot_lock_still_completes_the_write(gdir, monkeypat
with flags.exclusive(gdir):
pass
assert flags.read(gdir) == {}
+
+
+# -- manual order (drag) --------------------------------------------------------------------------
+
+
+def _shelf(gdir, mtimes):
+ """The shelf in listing order, as the galleries sort it."""
+ items = flags.read(gdir)
+ pairs = list(mtimes.items())
+ pairs.sort(
+ key = lambda p: (flags.pin_rank(items, p[0]), flags.order_rank(items, p[0], p[1])),
+ reverse = True,
+ )
+ return [i for i, _ in pairs]
+
+
+def _move(gdir, mtimes, item_id, after_id):
+ with flags.exclusive(gdir):
+ items = flags.read(gdir)
+ ordered = sorted(
+ mtimes.items(),
+ key = lambda p: (flags.pin_rank(items, p[0]), flags.order_rank(items, p[0], p[1])),
+ reverse = True,
+ )
+ return flags.place_locked(gdir, item_id, ordered, after_id = after_id)
+
+
+MTIMES = {"a": 400.0, "b": 300.0, "c": 200.0, "d": 100.0}
+
+
+def test_an_undragged_shelf_sorts_newest_first(gdir):
+ assert _shelf(gdir, MTIMES) == ["a", "b", "c", "d"]
+
+
+ "item, after, expected",
+ [
+ ("d", None, ["d", "a", "b", "c"]),
+ ("a", "d", ["b", "c", "d", "a"]),
+ ("a", "b", ["b", "a", "c", "d"]),
+ ("d", "a", ["a", "d", "b", "c"]),
+ ("b", "c", ["a", "c", "b", "d"]),
+ ],
+)
+def test_a_drag_lands_after_its_neighbour(gdir, item, after, expected):
+ assert _move(gdir, MTIMES, item, after) == {"pinned": False, "archived": False}
+ assert _shelf(gdir, MTIMES) == expected
+
+
+def test_only_the_moved_item_is_rewritten(gdir):
+ _move(gdir, MTIMES, "d", "a")
+ items = flags.read(gdir)
+ assert set(items) == {"d"}
+ assert 300.0 < flags.order_at(items, "d") < 400.0
+
+
+def test_new_media_still_lands_first_after_a_drag_to_the_front(gdir):
+ _move(gdir, MTIMES, "d", None)
+ later = {**MTIMES, "new": flags.order_at(flags.read(gdir), "d") + 1}
+ assert _shelf(gdir, later)[:2] == ["new", "d"]
+
+
+def test_repeated_drops_in_one_gap_keep_their_order(gdir):
+ mtimes = dict(MTIMES)
+ for _ in range(5):
+ _move(gdir, mtimes, "d", "a")
+ _move(gdir, mtimes, "c", "a")
+ assert _shelf(gdir, mtimes) == ["a", "c", "d", "b"]
+
+
+def test_dropping_between_pins_pins_and_orders_it(gdir):
+ flags.set_flags(gdir, "c", pinned = True)
+ flags.set_flags(gdir, "a", pinned = True) # pinned group: a, c
+ assert _move(gdir, MTIMES, "d", "a")["pinned"] is True
+ assert _shelf(gdir, MTIMES) == ["a", "d", "c", "b"]
+
+
+def test_dropping_at_the_front_of_a_pinned_shelf_pins_it(gdir):
+ flags.set_flags(gdir, "c", pinned = True)
+ assert _move(gdir, MTIMES, "b", None)["pinned"] is True
+ assert _shelf(gdir, MTIMES)[:2] == ["b", "c"]
+
+
+def test_dropping_among_unpinned_items_unpins_it(gdir):
+ flags.set_flags(gdir, "a", pinned = True)
+ assert _move(gdir, MTIMES, "a", "c")["pinned"] is False
+ assert _shelf(gdir, MTIMES) == ["b", "c", "a", "d"]
+
+
[email protected]("item, pinned", [("a", True), ("c", False)])
+def test_the_seam_between_groups_keeps_the_items_state(gdir, item, pinned):
+ flags.set_flags(gdir, "b", pinned = True)
+ flags.set_flags(gdir, "a", pinned = True) # pinned group: a, b
+ # Right after the last pin: "a" stays pinned, "c" stays unpinned.
+ assert _move(gdir, MTIMES, item, "b")["pinned"] is pinned
+ shelf = _shelf(gdir, MTIMES)
+ assert shelf.index(item) == shelf.index("b") + 1
+
+
+def test_a_later_pin_still_leads_a_dragged_pin(gdir):
+ flags.set_flags(gdir, "c", pinned = True)
+ _move(gdir, MTIMES, "d", None)
+ flags.set_flags(gdir, "b", pinned = True)
+ assert _shelf(gdir, MTIMES)[:3] == ["b", "d", "c"]
+
+
+def test_an_unknown_neighbour_is_refused(gdir):
+ with pytest.raises(KeyError):
+ _move(gdir, MTIMES, "a", "gone")
+ assert not _store(gdir).exists()
+
+
[email protected]("order_at", ["x", True, None, 10**400])
+def test_an_unusable_order_key_reads_as_undragged_and_costs_trust(gdir, order_at):
+ _store(gdir).write_text(json.dumps({"version": 1, "items": {"d": {"order_at": order_at}}}))
+ items = flags.read(gdir)
+ assert flags.order_at(items, "d") is None
+ assert _shelf(gdir, MTIMES) == ["a", "b", "c", "d"]
+ assert flags.is_trusted(gdir) is False
diff --git a/studio/backend/tests/test_gallery_projects.py b/studio/backend/tests/test_gallery_projects.py
new file mode 100644
index 00000000000..e7f60fef050
--- /dev/null
+++ b/studio/backend/tests/test_gallery_projects.py
@@ -0,0 +1,108 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Copying a gallery item into a chat project's folder."""
+
+from __future__ import annotations
+
+import pytest
+
+import core.inference.gallery_projects as gp
+import storage.studio_db as studio_db
+
+
+def project(tmp_path, monkeypatch):
+ root = tmp_path / "Projects" / "demo-1234"
+ (root / "sandbox").mkdir(parents = True)
+ record = {"id": "p1", "rootPath": str(root), "sandboxPath": str(root / "sandbox")}
+ monkeypatch.setattr(
+ studio_db, "ensure_chat_project_workspace", lambda pid: record if pid == "p1" else None
+ )
+ return root
+
+
+def media(tmp_path):
+ path = tmp_path / "gallery" / "abc123.png"
+ path.parent.mkdir()
+ path.write_bytes(b"\x89PNG fake bytes")
+ return path
+
+
+def test_the_copy_lands_in_the_projects_sandbox_folder(project, media):
+ result = gp.copy_into_project(media, "p1", "images")
+ dest = project / "sandbox" / "images" / "abc123.png"
+ assert result == {"path": str(dest), "already": False}
+ assert dest.read_bytes() == media.read_bytes()
+ # A copy, not a move: the gallery keeps its item.
+ assert media.exists()
+
+
+def test_adding_the_same_item_twice_reports_it_is_already_there(project, media):
+ gp.copy_into_project(media, "p1", "images")
+ assert gp.copy_into_project(media, "p1", "images")["already"] is True
+ assert sorted(p.name for p in (project / "sandbox" / "images").iterdir()) == ["abc123.png"]
+
+
+def test_an_unknown_project_is_refused(project, media):
+ with pytest.raises(gp.ProjectNotFound):
+ gp.copy_into_project(media, "gone", "images")
+
+
+def test_a_sandbox_outside_the_project_root_is_refused(tmp_path, media, monkeypatch):
+ root = tmp_path / "root"
+ root.mkdir()
+ elsewhere = tmp_path / "elsewhere"
+ elsewhere.mkdir()
+ monkeypatch.setattr(
+ studio_db,
+ "ensure_chat_project_workspace",
+ lambda pid: {"id": pid, "rootPath": str(root), "sandboxPath": str(elsewhere)},
+ )
+ with pytest.raises(gp.ProjectNotFound):
+ gp.copy_into_project(media, "p1", "images")
+ assert not (elsewhere / "images").exists()
+
+
[email protected](params = [True, False], ids = ["dir_fd", "by_path"])
+def copy_mode(request, monkeypatch):
+ if request.param and not gp._USE_DIR_FD:
+ pytest.skip("no dir_fd support on this platform")
+ monkeypatch.setattr(gp, "_USE_DIR_FD", request.param)
+ return request.param
+
+
+def test_a_failed_copy_leaves_no_partial_file(project, media, copy_mode, monkeypatch):
+ def boom(*args, **kwargs):
+ raise OSError("disk full")
+
+ monkeypatch.setattr(gp.shutil, "copyfileobj", boom)
+ monkeypatch.setattr(gp.shutil, "copyfile", boom)
+ with pytest.raises(OSError):
+ gp.copy_into_project(media, "p1", "images")
+ assert list((project / "sandbox" / "images").iterdir()) == []
+
+
+def test_a_symlinked_media_folder_is_refused(project, media, tmp_path, copy_mode):
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ (project / "sandbox" / "images").symlink_to(outside, target_is_directory = True)
+ with pytest.raises(OSError):
+ gp.copy_into_project(media, "p1", "images")
+ assert list(outside.iterdir()) == []
+
+
+def test_concurrent_adds_of_one_item_all_succeed(project, media, copy_mode):
+ from concurrent.futures import ThreadPoolExecutor
+
+ with ThreadPoolExecutor(8) as pool:
+ results = list(pool.map(lambda _: gp.copy_into_project(media, "p1", "images"), range(8)))
+ assert all(r["path"].endswith("abc123.png") for r in results)
+ folder = project / "sandbox" / "images"
+ assert [p.name for p in folder.iterdir()] == ["abc123.png"]
+ assert (folder / "abc123.png").read_bytes() == media.read_bytes()
+
+
+def test_temp_names_are_unique_per_call():
+ assert gp._tmp_name("a.png") != gp._tmp_name("a.png")
diff --git a/studio/frontend/src/components/gallery-item-menu.tsx b/studio/frontend/src/components/gallery-item-menu.tsx
index 1722c55a8d3..abf952b2ed8 100644
--- a/studio/frontend/src/components/gallery-item-menu.tsx
+++ b/studio/frontend/src/components/gallery-item-menu.tsx
@@ -2,10 +2,14 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import {
- Archive02Icon,
+ Archive03Icon,
ArchiveRestoreIcon,
Delete02Icon,
- MoreHorizontalIcon,
+ Download01Icon,
+ Folder01Icon,
+ FolderAddIcon,
+ FolderExportIcon,
+ MoreVerticalIcon,
PinIcon,
PinOffIcon,
} from "@hugeicons/core-free-icons";
@@ -18,12 +22,18 @@ import {
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { NewProjectDialog, useChatProjects } from "@/features/chat";
+import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
/**
- * Pin / archive / delete for one gallery item, shared by the Images and Video pages.
+ * Actions for one gallery item, shared by the Images and Video pages. Matches a chat row's menu.
*
* "toolbar" sits in the glass toolbar over the preview; "overlay" is the badge that appears on a
* filmstrip tile on hover. A tile is itself a <button>, so the overlay must be rendered as its
@@ -37,6 +47,8 @@ export function GalleryItemMenu({
onTogglePin,
onToggleArchive,
onDelete,
+ onDownload,
+ onAddToProject,
variant = "toolbar",
noun,
active = true,
@@ -47,8 +59,12 @@ export function GalleryItemMenu({
onTogglePin: () => void;
onToggleArchive: () => void;
onDelete: () => void;
+ /** One-click download of the original file. */
+ onDownload?: () => void;
+ /** Copies the item into a project's folder. */
+ onAddToProject?: (projectId: string) => Promise<{ already: boolean }>;
variant?: GalleryItemMenuVariant;
- /** Used in the aria-label, e.g. "image" or "video". */
+ /** Used in the aria-label and messages, 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;
@@ -57,47 +73,127 @@ export function GalleryItemMenu({
// 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);
+ const [creatingProject, setCreatingProject] = useState(false);
useEffect(() => {
- if (!active) setOpen(false);
+ if (!active) {
+ setOpen(false);
+ setCreatingProject(false);
+ }
}, [active]);
+ const { projects } = useChatProjects();
+
+ async function addToProject(projectId: string, projectName: string) {
+ if (!onAddToProject) return;
+ try {
+ const { already } = await onAddToProject(projectId);
+ toast.success(already ? `Already in ${projectName}` : `Added to ${projectName}`);
+ } catch (err) {
+ toast.error(`Failed to add ${noun} to project`, {
+ description: err instanceof Error ? err.message : undefined,
+ });
+ }
+ }
const overlay = variant === "overlay";
const menu = (
<DropdownMenu open={active && open} onOpenChange={(o) => setOpen(active && o)}>
<DropdownMenuTrigger asChild={true}>
<Button
- size={overlay ? "icon-xs" : "sm"}
+ size={overlay ? "icon-xs" : "icon-sm"}
variant="ghost"
aria-label={`More actions for this ${noun}`}
className={cn(
+ // Circular hover.
+ "rounded-full",
// 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"} />
+ <HugeiconsIcon icon={MoreVerticalIcon} className={overlay ? "size-3.5" : "size-4"} />
</Button>
</DropdownMenuTrigger>
- <DropdownMenuContent align="end">
+ {/* Same styling as a chat row's menu. */}
+ <DropdownMenuContent
+ align="end"
+ className="unsloth-plus-menu sidebar-row-menu menu-flat-destructive w-52"
+ >
<DropdownMenuItem onClick={onTogglePin}>
- <HugeiconsIcon icon={pinned ? PinOffIcon : PinIcon} />
- {pinned ? "Unpin" : "Pin to front"}
+ <HugeiconsIcon icon={pinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-icon" />
+ {pinned ? "Unpin" : "Pin"}
</DropdownMenuItem>
+ {onDownload ? (
+ <DropdownMenuItem onClick={onDownload}>
+ <HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} className="size-icon" />
+ Download
+ </DropdownMenuItem>
+ ) : null}
+ {onAddToProject ? (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <HugeiconsIcon icon={FolderExportIcon} strokeWidth={1.75} className="size-icon" />
+ <span>Project</span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent
+ sideOffset={0}
+ alignOffset={-4}
+ className="unsloth-plus-menu sidebar-row-menu w-48"
+ >
+ {/* Actions above the rule, destinations below, as in a chat's Project menu. */}
+ <DropdownMenuItem onClick={() => setCreatingProject(true)}>
+ <HugeiconsIcon icon={FolderAddIcon} strokeWidth={1.75} className="size-icon" />
+ <span>New project</span>
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ {projects.length === 0 ? (
+ <DropdownMenuItem disabled={true}>No projects yet</DropdownMenuItem>
+ ) : (
+ projects.map((project) => (
+ <DropdownMenuItem
+ key={project.id}
+ onClick={() => void addToProject(project.id, project.name)}
+ >
+ <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />
+ <span className="truncate">{project.name}</span>
+ </DropdownMenuItem>
+ ))
+ )}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ ) : null}
<DropdownMenuItem onClick={onToggleArchive}>
- <HugeiconsIcon icon={archived ? ArchiveRestoreIcon : Archive02Icon} />
+ <HugeiconsIcon icon={archived ? ArchiveRestoreIcon : Archive03Icon} strokeWidth={1.75} className="size-icon" />
{archived ? "Restore from archive" : "Archive"}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive" onClick={onDelete}>
- <HugeiconsIcon icon={Delete02Icon} />
+ <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-icon" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
- if (!overlay) return menu;
+ // Mounted only while open, since the overlay renders once per tile.
+ const newProjectDialog = creatingProject ? (
+ <NewProjectDialog
+ open={true}
+ onOpenChange={setCreatingProject}
+ title={`Add ${noun} to new project`}
+ submitLabel="Create and add"
+ onCreated={(project) => addToProject(project.id, project.name)}
+ />
+ ) : null;
+
+ if (!overlay) {
+ return (
+ <>
+ {menu}
+ {newProjectDialog}
+ </>
+ );
+ }
return (
<span
className={cn(
@@ -108,6 +204,44 @@ export function GalleryItemMenu({
)}
>
{menu}
+ {newProjectDialog}
</span>
);
}
+
+/** A pinned tile's marker, which unpins on click. Shows the unpin icon on hover or focus. */
+export function GalleryPinBadge({
+ noun,
+ onUnpin,
+ className,
+}: {
+ noun: string;
+ onUnpin: () => void;
+ className?: string;
+}) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <button
+ type="button"
+ aria-label={`Unpin this ${noun}`}
+ onClick={onUnpin}
+ className={cn(
+ "group/pin absolute flex items-center justify-center rounded-full bg-background/80 p-0.5 text-foreground shadow-sm ring-1 ring-border backdrop-blur outline-none transition-colors hover:bg-background focus-visible:ring-2 focus-visible:ring-ring",
+ className,
+ )}
+ >
+ <HugeiconsIcon
+ icon={PinIcon}
+ className="size-3 group-hover/pin:hidden group-focus-visible/pin:hidden"
+ />
+ <HugeiconsIcon
+ icon={PinOffIcon}
+ className="hidden size-3 group-hover/pin:block group-focus-visible/pin:block"
+ />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent>Unpin</TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/studio/frontend/src/components/gallery-strip-reorder.tsx b/studio/frontend/src/components/gallery-strip-reorder.tsx
new file mode 100644
index 00000000000..a534b801f87
--- /dev/null
+++ b/studio/frontend/src/components/gallery-strip-reorder.tsx
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import type { StripDropCue } from "@/hooks/use-strip-reorder";
+import { cn } from "@/lib/utils";
+
+/** Insertion line beside a tile, centred in the strip's gap. */
+export function StripDropLine({ edge }: { edge: StripDropCue["edge"] }) {
+ return (
+ <span
+ aria-hidden={true}
+ className={cn(
+ "pointer-events-none absolute inset-y-1 z-40 w-0.5 rounded-full bg-primary",
+ edge === "before"
+ ? "-left-[calc(5px*var(--ui-space-scale,1))]"
+ : "-right-[calc(5px*var(--ui-space-scale,1))]",
+ )}
+ />
+ );
+}
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index d63ace3453b..01a3c736b04 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -267,6 +267,7 @@ export { ApiProviderLogo } from "./api-provider-logo";
export { useExternalProvidersStore } from "./stores/external-providers-store";
export { DeleteChatFilesSwitch } from "./components/delete-chat-files-switch";
export { ChatSearchDialog } from "./components/chat-search-dialog";
+export { NewProjectDialog } from "./components/new-project-dialog";
export { StopRunningChatsDialog } from "./components/stop-running-chats-dialog";
export { setTrainingCompareHandoff } from "./lib/training-compare-handoff";
export type { ProjectRecord } from "./types";
diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.ts
index 88de7ba3bf3..7aee460d804 100644
--- a/studio/frontend/src/features/images/api.ts
+++ b/studio/frontend/src/features/images/api.ts
@@ -253,6 +253,8 @@ export interface GalleryImage {
// Library state, not recipe: stored beside the PNG, absent on records written before this existed.
pinned?: boolean;
archived?: boolean;
+ /** Manual sort key once dragged; unset sorts by created_at. */
+ order_at?: number | null;
}
export interface DiffusionGenerateResponse {
@@ -465,6 +467,31 @@ export async function getGallery(offset = 0, limit = 50, archived = false): Prom
}
/** Pin/unpin or archive/restore one image; omitted flags are left alone. Returns the new record. */
+/** Move one image to just after `afterId` (null = front). The server also decides the pin. */
+export async function moveGalleryImage(id: string, afterId: string | null): Promise<GalleryImage> {
+ return parseJson(
+ await authFetch(`/api/inference/images/gallery/${id}/move`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ after_id: afterId }),
+ }),
+ );
+}
+
+/** Copy one image into a chat project's folder. */
+export async function addGalleryImageToProject(
+ id: string,
+ projectId: string,
+): Promise<{ path: string; already: boolean }> {
+ return parseJson(
+ await authFetch(`/api/inference/images/gallery/${id}/project`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ project_id: projectId }),
+ }),
+ );
+}
+
export async function setGalleryImageFlags(
id: string,
flags: { pinned?: boolean; archived?: boolean },
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index a514061d3d4..6ab9536f9c3 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -13,7 +13,6 @@ import {
Image03Icon,
ImageAdd02Icon,
InformationCircleIcon,
- PinIcon,
SparklesIcon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon, type IconSvgElement } from "@hugeicons/react";
@@ -75,7 +74,9 @@ 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 { GalleryItemMenu, GalleryPinBadge } from "@/components/gallery-item-menu";
+import { StripDropLine } from "@/components/gallery-strip-reorder";
+import { useStripReorder } from "@/hooks/use-strip-reorder";
import { MediaPageLink } from "@/components/media-page-link";
import { useSettingsDialogStore } from "@/features/settings/stores/settings-dialog-store";
import {
@@ -85,6 +86,7 @@ import {
fetchWhileStable,
hasUnknownRecord,
mergeGenerated,
+ moveGalleryItem,
newRecordProbeBaseline,
nextSelectedId,
pinnedOrder,
@@ -190,6 +192,8 @@ import {
getGenerateProgress,
listDiffusionControlNets,
listDiffusionLoras,
+ addGalleryImageToProject,
+ moveGalleryImage,
setGalleryImageFlags,
getDiffusionDownloadPlan,
loadDiffusionModel,
@@ -1046,12 +1050,18 @@ function RecipePopover({
Recipe
</Button>
</PopoverTrigger>
- <PopoverContent align="end" side="top" className="w-80 p-0">
- <div className="border-b border-border/60 px-4 py-2.5">
+ {/* Fits the viewport: only the settings scroll, and overflow-hidden keeps the corners round. */}
+ <PopoverContent
+ align="end"
+ side="top"
+ collisionPadding={12}
+ className="flex max-h-[var(--radix-popover-content-available-height)] w-80 flex-col gap-0 overflow-hidden p-0"
+ >
+ <div className="shrink-0 border-b border-border/60 px-4 py-2.5">
<p className="text-sm font-semibold">Generation settings</p>
<p className="text-ui-11 text-muted-foreground">{formatTimestamp(image.created_at)}</p>
</div>
- <div className="flex flex-col gap-2 px-4 py-3 text-xs">
+ <div className="flex min-h-0 flex-col gap-2 overflow-y-auto overscroll-contain px-4 py-3 text-xs">
<RecipeRow label="Prompt" value={image.prompt} wrap />
{image.negative_prompt ? (
<RecipeRow label="Negative" value={image.negative_prompt} wrap />
@@ -1086,7 +1096,7 @@ function RecipePopover({
<RecipeRow label="Guidance" value={String(image.guidance)} />
<RecipeRow label="Seed" value={String(image.seed)} mono />
</div>
- <div className="border-t border-border/60 px-3 py-2.5">
+ <div className="shrink-0 border-t border-border/60 px-3 py-2.5">
<Button size="sm" className="w-full gap-1.5" onClick={() => onRestore(image)}>
<HugeiconsIcon icon={ArrowReloadHorizontalIcon} className="size-4" />
Restore these settings
@@ -2006,6 +2016,64 @@ export function ImagesPage({
[resyncWindow],
);
+ // Drag-to-reorder: applied optimistically, then the server's record (key and pin) is adopted.
+ const handleMove = useCallback(
+ async (id: string, afterId: string | null) => {
+ const next = moveGalleryItem(galleryCache.images, id, afterId);
+ if (next === galleryCache.images) return;
+ const guessedPinned = Boolean(next.find((i) => i.id === id)?.pinned);
+ stripEpoch.current += 1;
+ galleryCache.images = next;
+ setImages(next);
+ try {
+ // Shares the pin queue, since both rewrite the order.
+ const record = await serializeById("image-pin", () => moveGalleryImage(id, afterId));
+ setImages((prev) => {
+ const patched = prev.map((i) =>
+ i.id === id ? { ...i, pinned: record.pinned, order_at: record.order_at } : i,
+ );
+ // Re-sort only if the local pin guess was wrong.
+ const out =
+ Boolean(record.pinned) === guessedPinned ? patched : sortGalleryItems(patched);
+ galleryCache.images = out;
+ return out;
+ });
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "Failed to move image");
+ // Restore the server's order.
+ stripEpoch.current += 1;
+ const epoch = stripEpoch.current;
+ try {
+ await resyncWindow(galleryCache.images.length, () => stripEpoch.current === epoch);
+ } catch {
+ void loadGallery();
+ }
+ }
+ },
+ [resyncWindow, loadGallery],
+ );
+ // One-click download of the original PNG.
+ const handleQuickDownload = useCallback(
+ async (image: GalleryImage) => {
+ const src = srcById[image.id];
+ if (src) {
+ await downloadImage(src, image, "png");
+ return;
+ }
+ try {
+ const blob = await fetchGalleryBlob(image.url);
+ await downloadFile(blob, exportFilename(image, "png"), blob.type);
+ } catch (error) {
+ if (isDownloadCancelled(error)) return;
+ toast.error("Could not save image", {
+ description: error instanceof Error ? error.message : undefined,
+ });
+ }
+ },
+ [srcById],
+ );
+ const stripReorder = useStripReorder((id, afterId) => void handleMove(id, afterId));
+
const handleArchive = useCallback(
async (id: string) => {
// Held for the whole round trip: the server shortens the shelf when it processes this, so a
@@ -5149,6 +5217,8 @@ export function ImagesPage({
}
onToggleArchive={() => void handleArchive(selected.id)}
onDelete={() => void handleDelete(selected.id)}
+ onDownload={() => void handleQuickDownload(selected)}
+ onAddToProject={(projectId) => addGalleryImageToProject(selected.id, projectId)}
/>
</div>
</>
@@ -5199,6 +5269,7 @@ export function ImagesPage({
{(images.length > 0 || busy === "generating") && (
<div
ref={stripRef}
+ {...stripReorder.stripProps}
// The rule spans the pane; only the thumbnail contents receive the 40px gutter.
className="hover-scrollbar flex shrink-0 gap-2 overflow-x-auto border-t border-[color-mix(in_oklab,var(--foreground)_calc(10%*var(--contrast-edge-gain,1)),transparent)] px-10 max-sm:px-5 py-3"
onScroll={(e) => {
@@ -5221,8 +5292,16 @@ export function ImagesPage({
<div
key={image.id}
data-image-id={image.id}
- className="group relative size-16 shrink-0"
+ {...stripReorder.tileProps(image.id)}
+ className={cn(
+ "group relative size-16 shrink-0",
+ // Fade the tile being dragged.
+ stripReorder.draggingId === image.id && "opacity-40",
+ )}
>
+ {stripReorder.cue?.id === image.id && (
+ <StripDropLine edge={stripReorder.cue.edge} />
+ )}
<button
type="button"
onClick={() => setSelectedId(image.id)}
@@ -5232,6 +5311,7 @@ export function ImagesPage({
<img
src={srcById[image.id]}
alt={image.prompt}
+ draggable={false}
className="size-full object-cover"
/>
) : (
@@ -5244,11 +5324,13 @@ export function ImagesPage({
<span className="pointer-events-none absolute inset-0 rounded-[10px] border border-border bg-white/35 dark:border-[rgb(255_255_255_/_calc(0.25*var(--contrast-edge-gain,1)))] dark:bg-white/20" />
)}
</button>
- {/* Pin marker, bottom-left so it never sits under the menu. */}
+ {/* Pin marker and Unpin button, bottom-left so it clears 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>
+ <GalleryPinBadge
+ noun="image"
+ className="bottom-0.5 left-0.5"
+ onUnpin={() => void handleTogglePin(image.id, false)}
+ />
)}
<div className="absolute right-0.5 top-0.5">
<GalleryItemMenu
@@ -5260,6 +5342,8 @@ export function ImagesPage({
onTogglePin={() => void handleTogglePin(image.id, !image.pinned)}
onToggleArchive={() => void handleArchive(image.id)}
onDelete={() => void handleDelete(image.id)}
+ onDownload={() => void handleQuickDownload(image)}
+ onAddToProject={(projectId) => addGalleryImageToProject(image.id, projectId)}
/>
</div>
</div>
diff --git a/studio/frontend/src/features/video/api.ts b/studio/frontend/src/features/video/api.ts
index b68ba7fce24..014ae8e46b1 100644
--- a/studio/frontend/src/features/video/api.ts
+++ b/studio/frontend/src/features/video/api.ts
@@ -224,6 +224,8 @@ export interface GalleryVideo {
// Library state, not recipe: stored beside the clip, absent on sidecars written before this existed.
pinned?: boolean;
archived?: boolean;
+ /** Manual sort key once dragged; unset sorts by created_at. */
+ order_at?: number | null;
}
// Acknowledgement that the job started; the saved record arrives via getVideoGenerateProgress at phase "completed".
@@ -334,6 +336,31 @@ export async function getVideoGallery(
}
/** Pin/unpin or archive/restore one clip; omitted flags are left alone. Returns the new record. */
+/** Move one video to just after `afterId` (null = front). The server also decides the pin. */
+export async function moveGalleryVideo(id: string, afterId: string | null): Promise<GalleryVideo> {
+ return parseJson(
+ await authFetch(`/api/inference/video/gallery/${id}/move`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ after_id: afterId }),
+ }),
+ );
+}
+
+/** Copy one video into a chat project's folder. */
+export async function addGalleryVideoToProject(
+ id: string,
+ projectId: string,
+): Promise<{ path: string; already: boolean }> {
+ return parseJson(
+ await authFetch(`/api/inference/video/gallery/${id}/project`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ project_id: projectId }),
+ }),
+ );
+}
+
export async function setGalleryVideoFlags(
id: string,
flags: { pinned?: boolean; archived?: boolean },
diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsx
index 82ff041efe6..0da7de31124 100644
--- a/studio/frontend/src/features/video/video-page.tsx
+++ b/studio/frontend/src/features/video/video-page.tsx
@@ -10,13 +10,14 @@ import {
ImageCropIcon,
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 { GalleryItemMenu, GalleryPinBadge } from "@/components/gallery-item-menu";
+import { StripDropLine } from "@/components/gallery-strip-reorder";
+import { useStripReorder } from "@/hooks/use-strip-reorder";
import { ImageDropzone } from "@/components/image-dropzone";
import { MediaPageLink } from "@/components/media-page-link";
import { GuidedTour, useGuidedTourController } from "@/features/tour";
@@ -26,6 +27,7 @@ import {
applyPin,
fetchNextPage,
fetchWhileStable,
+ moveGalleryItem,
nextSelectedId,
pinnedOrder,
removeGalleryItem,
@@ -171,6 +173,8 @@ import {
cancelVideoGeneration,
clearVideoGallery,
deleteGalleryVideo,
+ addGalleryVideoToProject,
+ moveGalleryVideo,
setGalleryVideoFlags,
fetchGalleryVideoExport,
fetchGalleryVideoSignedUrl,
@@ -675,12 +679,18 @@ function RecipePopover({
Recipe
</Button>
</PopoverTrigger>
- <PopoverContent align="end" side="top" className="w-80 p-0">
- <div className="border-b border-border/60 px-4 py-2.5">
+ {/* Fits the viewport: only the settings scroll, and overflow-hidden keeps the corners round. */}
+ <PopoverContent
+ align="end"
+ side="top"
+ collisionPadding={12}
+ className="flex max-h-[var(--radix-popover-content-available-height)] w-80 flex-col gap-0 overflow-hidden p-0"
+ >
+ <div className="shrink-0 border-b border-border/60 px-4 py-2.5">
<p className="text-sm font-semibold">Generation settings</p>
<p className="text-ui-11 text-muted-foreground">{formatTimestamp(video.created_at)}</p>
</div>
- <div className="flex flex-col gap-2 px-4 py-3 text-xs">
+ <div className="flex min-h-0 flex-col gap-2 overflow-y-auto overscroll-contain px-4 py-3 text-xs">
<RecipeRow label="Prompt" value={video.prompt} wrap />
{video.negative_prompt ? (
<RecipeRow label="Negative" value={video.negative_prompt} wrap />
@@ -730,7 +740,7 @@ function RecipePopover({
) : null}
<RecipeRow label="Seed" value={String(video.seed)} mono />
</div>
- <div className="border-t border-border/60 px-3 py-2.5">
+ <div className="shrink-0 border-t border-border/60 px-3 py-2.5">
<Button size="sm" className="w-full gap-1.5" onClick={() => onRestore(video)}>
Restore these settings
</Button>
@@ -1766,6 +1776,27 @@ function VideoGenerator({
[],
);
+ // One-click download of the original MP4.
+ const handleQuickDownload = useCallback(
+ async (video: GalleryVideo) => {
+ const cached = galleryCache.srcById.get(video.id);
+ let url =
+ cached && Date.now() - cached.mintedAt < VIDEO_LINK_REFRESH_MS ? cached.url : null;
+ if (!url) {
+ try {
+ url = await fetchGalleryVideoSignedUrl(video.id);
+ } catch (err) {
+ toast.error("Could not save video", {
+ description: err instanceof Error ? err.message : undefined,
+ });
+ return;
+ }
+ }
+ await handleDownload(url, video, "mp4");
+ },
+ [handleDownload],
+ );
+
// 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 discard. An archived clip keeps both.
const dropFromStrip = useCallback((id: string, discardLink: boolean) => {
@@ -1940,6 +1971,44 @@ function VideoGenerator({
[resyncWindow],
);
+ // Drag-to-reorder: applied optimistically, then the server's record (key and pin) is adopted.
+ const handleMove = useCallback(
+ async (id: string, afterId: string | null) => {
+ const next = moveGalleryItem(galleryCache.videos, id, afterId);
+ if (next === galleryCache.videos) return;
+ const guessedPinned = Boolean(next.find((i) => i.id === id)?.pinned);
+ stripEpoch.current += 1;
+ galleryCache.videos = next;
+ setVideos(next);
+ try {
+ // Shares the pin queue, since both rewrite the order.
+ const record = await serializeById("video-pin", () => moveGalleryVideo(id, afterId));
+ setVideos((prev) => {
+ const patched = prev.map((i) =>
+ i.id === id ? { ...i, pinned: record.pinned, order_at: record.order_at } : i,
+ );
+ // Re-sort only if the local pin guess was wrong.
+ const out =
+ Boolean(record.pinned) === guessedPinned ? patched : sortGalleryItems(patched);
+ galleryCache.videos = out;
+ return out;
+ });
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "Failed to move video");
+ // Restore the server's order.
+ stripEpoch.current += 1;
+ const epoch = stripEpoch.current;
+ try {
+ await resyncWindow(galleryCache.videos.length, () => stripEpoch.current === epoch);
+ } catch {
+ void loadGallery();
+ }
+ }
+ },
+ [resyncWindow, loadGallery],
+ );
+ const stripReorder = useStripReorder((id, afterId) => void handleMove(id, afterId));
+
const handleArchive = useCallback(
async (id: string) => {
// Held for the whole round trip: the server shortens the shelf when it processes this, so a
@@ -4181,6 +4250,8 @@ function VideoGenerator({
}
onToggleArchive={() => void handleArchive(selected.id)}
onDelete={() => void handleDelete(selected.id)}
+ onDownload={() => void handleQuickDownload(selected)}
+ onAddToProject={(projectId) => addGalleryVideoToProject(selected.id, projectId)}
/>
</div>
</>
@@ -4231,6 +4302,7 @@ function VideoGenerator({
{(videos.length > 0 || busy === "generating") && (
<div
ref={stripRef}
+ {...stripReorder.stripProps}
className="hover-scrollbar flex shrink-0 items-stretch gap-2 overflow-x-auto border-t border-[color-mix(in_oklab,var(--foreground)_calc(10%*var(--contrast-edge-gain,1)),transparent)] p-3"
onScroll={(e) => {
// Near the right edge: pull the next older page (infinite scroll).
@@ -4252,8 +4324,16 @@ function VideoGenerator({
<div
key={video.id}
data-clip-id={video.id}
- className="group relative h-16 w-24 shrink-0"
+ {...stripReorder.tileProps(video.id)}
+ className={cn(
+ "group relative h-16 w-24 shrink-0",
+ // Fade the tile being dragged.
+ stripReorder.draggingId === video.id && "opacity-40",
+ )}
>
+ {stripReorder.cue?.id === video.id && (
+ <StripDropLine edge={stripReorder.cue.edge} />
+ )}
<Tooltip>
<TooltipTrigger asChild={true}>
<button
@@ -4265,6 +4345,7 @@ function VideoGenerator({
<img
src={thumbnailById[video.id]}
alt=""
+ draggable={false}
onError={() => handlePosterError(video.id)}
className="absolute inset-0 size-full object-cover"
/>
@@ -4301,11 +4382,13 @@ function VideoGenerator({
</span>
</TooltipContent>
</Tooltip>
- {/* Pin marker, top-left so it clears both the caption and the menu. */}
+ {/* Pin marker and Unpin button, top-left so it clears the caption and 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>
+ <GalleryPinBadge
+ noun="video"
+ className="left-0.5 top-0.5 z-30"
+ onUnpin={() => void handleTogglePin(video.id, false)}
+ />
)}
<div className="absolute right-0.5 top-0.5 z-30">
<GalleryItemMenu
@@ -4317,6 +4400,8 @@ function VideoGenerator({
onTogglePin={() => void handleTogglePin(video.id, !video.pinned)}
onToggleArchive={() => void handleArchive(video.id)}
onDelete={() => void handleDelete(video.id)}
+ onDownload={() => void handleQuickDownload(video)}
+ onAddToProject={(projectId) => addGalleryVideoToProject(video.id, projectId)}
/>
</div>
</div>
diff --git a/studio/frontend/src/hooks/use-strip-reorder.ts b/studio/frontend/src/hooks/use-strip-reorder.ts
new file mode 100644
index 00000000000..5880775272b
--- /dev/null
+++ b/studio/frontend/src/hooks/use-strip-reorder.ts
@@ -0,0 +1,127 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import type React from "react";
+import { useCallback, useRef, useState } from "react";
+
+/** Where a drop would land: on one side of one tile. */
+export interface StripDropCue {
+ id: string;
+ edge: "before" | "after";
+}
+
+// Custom type so other drop targets do not read the drag as a file or link.
+const DRAG_TYPE = "application/x-unsloth-gallery-item";
+
+/** Whether the event came from the tile's own DOM, not a portalled menu or dialog inside it. */
+function fromTile(event: React.SyntheticEvent<HTMLElement>): boolean {
+ return event.currentTarget.contains(event.target as Node);
+}
+
+/**
+ * Drag-to-reorder for a horizontal gallery strip (Images and Video).
+ *
+ * Tracked on the strip so gaps and ends are drop targets. Tiles carry `data-reorder-id` in display
+ * order. A drop reports the id the tile now follows (null = front). Alt + Left / Right moves the
+ * focused tile one slot. Drags that did not start on a tile are ignored.
+ */
+export function useStripReorder(onMove: (id: string, afterId: string | null) => void) {
+ const dragIdRef = useRef<string | null>(null);
+ const [draggingId, setDraggingId] = useState<string | null>(null);
+ const [cue, setCue] = useState<StripDropCue | null>(null);
+
+ const end = useCallback(() => {
+ dragIdRef.current = null;
+ setDraggingId(null);
+ setCue(null);
+ }, []);
+
+ /** The drop at `clientX`, or null if the tile would not move. */
+ function resolve(
+ strip: HTMLElement,
+ clientX: number,
+ ): { afterId: string | null; cue: StripDropCue } | null {
+ const dragged = dragIdRef.current;
+ if (!dragged) return null;
+ const tiles = [...strip.querySelectorAll<HTMLElement>("[data-reorder-id]")];
+ const order = tiles.map((tile) => tile.dataset.reorderId ?? "");
+ let index = tiles.findIndex((tile) => {
+ const rect = tile.getBoundingClientRect();
+ return clientX < rect.left + rect.width / 2;
+ });
+ if (index < 0) index = tiles.length;
+ const from = order.indexOf(dragged);
+ // Either side of the dragged tile is a no-op.
+ if (from < 0 || index === from || index === from + 1) return null;
+ return {
+ afterId: index === 0 ? null : order[index - 1],
+ cue:
+ index < order.length
+ ? { id: order[index], edge: "before" }
+ : { id: order[order.length - 1], edge: "after" },
+ };
+ }
+
+ const stripProps = {
+ onDragOver: (event: React.DragEvent<HTMLElement>) => {
+ if (!dragIdRef.current) return;
+ event.preventDefault();
+ event.dataTransfer.dropEffect = "move";
+ const next = resolve(event.currentTarget, event.clientX)?.cue ?? null;
+ setCue((prev) =>
+ prev?.id === next?.id && prev?.edge === next?.edge ? prev : next,
+ );
+ },
+ onDragLeave: (event: React.DragEvent<HTMLElement>) => {
+ if (!event.currentTarget.contains(event.relatedTarget as Node | null)) {
+ setCue(null);
+ }
+ },
+ onDrop: (event: React.DragEvent<HTMLElement>) => {
+ const dragged = dragIdRef.current;
+ if (!dragged) return;
+ event.preventDefault();
+ const drop = resolve(event.currentTarget, event.clientX);
+ end();
+ if (drop) onMove(dragged, drop.afterId);
+ },
+ };
+
+ function tileProps(id: string) {
+ return {
+ "data-reorder-id": id,
+ draggable: true,
+ onDragStart: (event: React.DragEvent<HTMLElement>) => {
+ if (!fromTile(event)) return;
+ dragIdRef.current = id;
+ setDraggingId(id);
+ event.dataTransfer.effectAllowed = "move";
+ event.dataTransfer.setData(DRAG_TYPE, id);
+ },
+ onDragEnd: end,
+ onKeyDown: (event: React.KeyboardEvent<HTMLElement>) => {
+ if (
+ !fromTile(event) ||
+ !event.altKey ||
+ (event.key !== "ArrowLeft" && event.key !== "ArrowRight")
+ ) {
+ return;
+ }
+ const strip = event.currentTarget.parentElement;
+ if (!strip) return;
+ const order = [
+ ...strip.querySelectorAll<HTMLElement>("[data-reorder-id]"),
+ ].map((tile) => tile.dataset.reorderId ?? "");
+ const from = order.indexOf(id);
+ event.preventDefault();
+ if (event.key === "ArrowLeft" && from > 0) {
+ onMove(id, from > 1 ? order[from - 2] : null);
+ } else if (event.key === "ArrowRight" && from >= 0 && from < order.length - 1) {
+ onMove(id, order[from + 1]);
+ }
+ },
+ };
+ }
+
+ return { stripProps, tileProps, cue, draggingId };
+}
diff --git a/studio/frontend/src/lib/gallery-flags.ts b/studio/frontend/src/lib/gallery-flags.ts
index 6c33345217d..a901b4ce9ad 100644
--- a/studio/frontend/src/lib/gallery-flags.ts
+++ b/studio/frontend/src/lib/gallery-flags.ts
@@ -5,8 +5,9 @@
* 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.
+ * The backend is the source of truth for order (pinned first, then newest first, or by manual key
+ * once dragged). 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";
@@ -40,14 +41,22 @@ export interface FlaggableItem {
id: string;
pinned?: boolean;
archived?: boolean;
+ /** Manual sort key in epoch seconds, set once dragged; replaces created_at in the sort. */
+ order_at?: number | null;
created_at: number | string;
}
+/** Unpinned sort key in epoch seconds (images store seconds, videos an ISO string). */
+function orderKey(item: FlaggableItem): number {
+ if (typeof item.order_at === "number") return item.order_at;
+ return typeof item.created_at === "number"
+ ? item.created_at
+ : Date.parse(item.created_at) / 1000;
+}
+
/** 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;
+ return orderKey(b) - orderKey(a);
}
/**
@@ -77,6 +86,34 @@ export function applyPin<T extends FlaggableItem>(items: T[], id: string, pinned
return sortGalleryItems(next, pinned ? id : undefined);
}
+/**
+ * Move `id` to just after `afterId` (null = front), with the backend's pin rule: between pins pins
+ * it, between unpinned items unpins it, on the boundary keeps its state. Returns `items` unchanged
+ * for a no-op. The server's record is authoritative for the pin.
+ */
+export function moveGalleryItem<T extends FlaggableItem>(
+ items: T[],
+ id: string,
+ afterId: string | null,
+): T[] {
+ const from = items.findIndex((i) => i.id === id);
+ if (from < 0 || afterId === id) return items;
+ const rest = items.filter((i) => i.id !== id);
+ const at = afterId === null ? 0 : rest.findIndex((i) => i.id === afterId) + 1;
+ if (afterId !== null && at === 0) return items;
+ const moved = items[from];
+ const above = rest[at - 1];
+ const below = rest[at];
+ const pinned =
+ above && below
+ ? Boolean(above.pinned) === Boolean(below.pinned)
+ ? Boolean(above.pinned)
+ : Boolean(moved.pinned)
+ : Boolean((above ?? below ?? moved).pinned);
+ if (at === from && pinned === Boolean(moved.pinned)) return items;
+ return [...rest.slice(0, at), { ...moved, pinned }, ...rest.slice(at)];
+}
+
/** The pinned ids in their current order, to hand back to `restorePinOrder` on a failed unpin. */
export function pinnedOrder<T extends FlaggableItem>(items: T[]): string[] {
return items.filter((i) => i.pinned).map((i) => i.id);
diff --git a/studio/frontend/tests/gallery-flags.test.ts b/studio/frontend/tests/gallery-flags.test.ts
index 8b138ac3c3d..56548cfcc2c 100644
--- a/studio/frontend/tests/gallery-flags.test.ts
+++ b/studio/frontend/tests/gallery-flags.test.ts
@@ -11,6 +11,7 @@ import {
fetchWhileStable,
hasUnknownRecord,
mergeGenerated,
+ moveGalleryItem,
newRecordProbeBaseline,
nextSelectedId,
pinnedOrder,
@@ -489,3 +490,52 @@ test("archived audio pages from the stable server cursor", () => {
/const page = await loadPage\(\s*rowsRef\.current\.length,\s*audioCursor\.current,\s*scanAll \? SEARCH_PAGE_SIZE : ARCHIVED_PAGE_SIZE,?\s*\);[\s\S]*audioCursor\.current = page\.nextAudioCursor;/,
);
});
+
+// -- manual order (drag) --------------------------------------------------------------------------
+
+const shelf = () => [item("a", 4), item("b", 3), item("c", 2), item("d", 1)];
+
+test("a drag lands just after its neighbour, or at the front for null", () => {
+ assert.deepEqual(ids(moveGalleryItem(shelf(), "d", "a")), ["a", "d", "b", "c"]);
+ assert.deepEqual(ids(moveGalleryItem(shelf(), "c", null)), ["c", "a", "b", "d"]);
+ assert.deepEqual(ids(moveGalleryItem(shelf(), "a", "d")), ["b", "c", "d", "a"]);
+});
+
+test("a drop in place, onto itself or after an unknown id changes nothing", () => {
+ const items = shelf();
+ assert.equal(moveGalleryItem(items, "b", "a"), items);
+ assert.equal(moveGalleryItem(items, "b", "b"), items);
+ assert.equal(moveGalleryItem(items, "b", "gone"), items);
+ assert.equal(moveGalleryItem(items, "gone", "a"), items);
+});
+
+test("a drop between pins pins the item, and among unpinned items unpins it", () => {
+ const items = [item("p1", 1, true), item("p2", 2, true), item("a", 4), item("b", 3)];
+ const pinnedDrop = moveGalleryItem(items, "b", "p1");
+ assert.deepEqual(ids(pinnedDrop), ["p1", "b", "p2", "a"]);
+ assert.equal(pinnedDrop[1].pinned, true);
+ const unpinnedDrop = moveGalleryItem(items, "p1", "a");
+ assert.deepEqual(ids(unpinnedDrop), ["p2", "a", "p1", "b"]);
+ assert.equal(unpinnedDrop[2].pinned, false);
+});
+
+test("on the seam between pins and the rest an item keeps its pin state", () => {
+ const items = [item("p1", 1, true), item("p2", 2, true), item("a", 4), item("b", 3)];
+ assert.equal(moveGalleryItem(items, "b", "p2")[2].pinned, false);
+ assert.equal(moveGalleryItem(items, "p1", "p2")[1].pinned, true);
+});
+
+test("a dragged item keeps its manual place through a later merge", () => {
+ const moved = [item("a", 4), { ...item("d", 1), order_at: 3.5 }, item("b", 3), item("c", 2)];
+ const merged = mergeGenerated(moved, [item("new", 5)]);
+ assert.deepEqual(ids(merged), ["new", "a", "d", "b", "c"]);
+});
+
+test("a manual key compares in seconds against ISO timestamps too", () => {
+ const at = (iso: string) => Date.parse(iso) / 1000;
+ const items = [
+ item("newer", "2026-06-01T00:00:00Z"),
+ { ...item("dragged", "2026-01-01T00:00:00Z"), order_at: at("2026-07-01T00:00:00Z") },
+ ];
+ assert.deepEqual(ids(sortGalleryItems(items)), ["dragged", "newer"]);
+});