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.

Allow removing missing images from the gallery (#10781)

Michael Han9e67af75094a
diff --git a/studio/backend/core/inference/image_gallery.py b/studio/backend/core/inference/image_gallery.py
index 337ccd42d24..29a72b08a7e 100644
--- a/studio/backend/core/inference/image_gallery.py
+++ b/studio/backend/core/inference/image_gallery.py
@@ -11,6 +11,7 @@ so a downloaded PNG carries its own settings. The route owns the schema; this on
from __future__ import annotations
import base64
+import errno
import json
import os
import re
@@ -126,12 +127,16 @@ def image_b64(image_id: str) -> Optional[str]:
_REQUIRED_META = ("prompt", "width", "height", "steps", "guidance", "seed", "created_at")
-def _read_meta(path: Path) -> Optional[dict[str, Any]]:
+def _read_meta(path: Path, *, strict_io: bool = False) -> Optional[dict[str, Any]]:
from PIL import Image
try:
with Image.open(path) as im:
raw = im.text.get(_META_KEY) # type: ignore[attr-defined]
+ except OSError as exc:
+ if strict_io and exc.errno not in (None, errno.ENOENT):
+ raise
+ return None
except Exception:
return None
if not raw:
@@ -235,19 +240,27 @@ def set_flags(
def delete(image_id: str) -> bool:
path = image_path(image_id)
- if path is None:
- return False
# a hand-dropped foreign PNG is invisible to list_images, so a guessed id must not destroy it
- if _read_meta(path) is None:
+ if path is None or _read_meta(path, strict_io = True) is None:
+ if _ID_RE.fullmatch(image_id):
+ # Only prune absent files, preserving foreign files and symlinks.
+ try:
+ (gallery_dir() / f"{image_id}.png").lstat()
+ except FileNotFoundError:
+ gallery_flags.forget(gallery_dir(), [image_id])
return False
+ removed = True
try:
path.unlink()
+ except FileNotFoundError:
+ removed = False
except OSError as exc:
logger.warning("image_gallery.delete_failed: %s", exc)
- return False
+ # Propagate I/O failures instead of reporting a missing image.
+ raise
# drop the flags with the file, so the id cannot hand out a stale pin and the store cannot grow forever
gallery_flags.forget(gallery_dir(), [image_id])
- return True
+ return removed
def clear(include_archived: bool = False) -> int:
diff --git a/studio/backend/tests/test_image_gallery.py b/studio/backend/tests/test_image_gallery.py
index 21c25279ece..17ccbe4b6ae 100644
--- a/studio/backend/tests/test_image_gallery.py
+++ b/studio/backend/tests/test_image_gallery.py
@@ -7,6 +7,7 @@ listing order, safe id handling, and delete/clear."""
from __future__ import annotations
import base64
+import errno
import io
import os
@@ -105,6 +106,23 @@ def test_delete_and_clear():
assert gallery.list_images() == []
[email protected]("stage", ["read", "unlink"])
+def test_delete_does_not_report_an_io_failure_as_a_missing_image(monkeypatch, stage):
+ record = gallery.save(_img(), _meta())
+ path = gallery.image_path(record["id"])
+
+ def refuse(*args, **kwargs):
+ raise PermissionError(errno.EACCES, "read-only gallery")
+
+ if stage == "read":
+ monkeypatch.setattr(Image, "open", refuse)
+ else:
+ monkeypatch.setattr(type(path), "unlink", refuse)
+ with pytest.raises(PermissionError, match = "read-only gallery"):
+ gallery.delete(record["id"])
+ assert path.exists()
+
+
def test_clear_preserves_foreign_png():
# A hand-dropped PNG with no recipe chunk is invisible to list_images; clear must not destroy it.
foreign = gallery.gallery_dir() / "family-photo.png"
@@ -301,11 +319,35 @@ def test_set_flags_refuses_a_foreign_or_unknown_id():
assert gallery.set_flags("foreign", pinned = True) is None
-def test_delete_prunes_the_flag_entry():
[email protected]("missing_at", [None, "lookup", "read", "unlink"])
+def test_delete_prunes_the_flag_entry(monkeypatch, missing_at):
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()) == {}
+ other = _save_with_mtime("keep", 200.0)
+ gallery.set_flags(record["id"], pinned = True, archived = True)
+ gallery.set_flags(other["id"], archived = True)
+ path = gallery.image_path(record["id"])
+ if missing_at == "lookup":
+ path.unlink()
+ elif missing_at == "read":
+ read_meta = gallery._read_meta
+
+ def disappear_before_read(candidate, **kwargs):
+ candidate.unlink()
+ return read_meta(candidate, **kwargs)
+
+ monkeypatch.setattr(gallery, "_read_meta", disappear_before_read)
+ elif missing_at == "unlink":
+ unlink = type(path).unlink
+
+ def disappear_before_unlink(candidate, **kwargs):
+ if candidate == path:
+ unlink(candidate)
+ return unlink(candidate, **kwargs)
+
+ monkeypatch.setattr(type(path), "unlink", disappear_before_unlink)
+ assert gallery.delete(record["id"]) is (missing_at is None)
+ assert gallery_flags.read(gallery.gallery_dir()) == {other["id"]: {"archived": True}}
+ assert gallery.image_path(other["id"]) is not None
def test_clear_spares_archived_images():
diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.ts
index 5d5c73353f6..a85e25f7910 100644
--- a/studio/frontend/src/features/images/api.ts
+++ b/studio/frontend/src/features/images/api.ts
@@ -441,7 +441,8 @@ export async function setGalleryImageFlags(
export async function deleteGalleryImage(id: string): Promise<void> {
const res = await authFetch(`/api/inference/images/gallery/${id}`, { method: "DELETE" });
- if (!res.ok) throw new Error(await readFastApiError(res));
+ // Already absent: let the caller remove the cached entry.
+ if (!res.ok && res.status !== 404) throw new Error(await readFastApiError(res));
}
export async function clearGallery(): Promise<void> {
diff --git a/studio/frontend/tests/image-gallery-delete.test.ts b/studio/frontend/tests/image-gallery-delete.test.ts
new file mode 100644
index 00000000000..ac4ca143279
--- /dev/null
+++ b/studio/frontend/tests/image-gallery-delete.test.ts
@@ -0,0 +1,37 @@
+// 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 { runInNewContext } from "node:vm";
+import ts from "typescript";
+import { readSrc } from "./helpers/kit.ts";
+
+test("gallery delete accepts an externally removed image but still reports real failures", async () => {
+ const source = readSrc("features/images/api.ts");
+ const start = source.indexOf("export async function deleteGalleryImage(");
+ const end = source.indexOf("export async function clearGallery(", start);
+ assert.ok(start >= 0 && end > start);
+ const code = ts.transpileModule(source.slice(start, end), {
+ compilerOptions: { module: ts.ModuleKind.CommonJS },
+ }).outputText;
+
+ for (const status of [200, 404, 401, 403, 500]) {
+ const context = {
+ exports: {} as { deleteGalleryImage: (id: string) => Promise<void> },
+ authFetch: async (url: string, init: RequestInit) => {
+ assert.equal(url, "/api/inference/images/gallery/missing-png");
+ assert.equal(init.method, "DELETE");
+ return new Response(null, { status });
+ },
+ readFastApiError: async () => `HTTP ${status}`,
+ };
+ runInNewContext(code, context);
+ const deletion = context.exports.deleteGalleryImage("missing-png");
+ if (status === 200 || status === 404) {
+ await assert.doesNotReject(deletion);
+ } else {
+ await assert.rejects(deletion, new RegExp(`HTTP ${status}`));
+ }
+ }
+});