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: info stamp on image downloads, recipe in every format, load settings from an image (#13444)

Daniel Han2470977d4306
diff --git a/studio/backend/core/inference/image_gallery.py b/studio/backend/core/inference/image_gallery.py
index dfd57d12d6c..03f4f627496 100644
--- a/studio/backend/core/inference/image_gallery.py
+++ b/studio/backend/core/inference/image_gallery.py
@@ -12,9 +12,11 @@ from __future__ import annotations
import base64
import errno
+import functools
import json
import os
import re
+import sys
import uuid
from collections.abc import Callable
from pathlib import Path
@@ -43,6 +45,9 @@ def gallery_dir() -> Path:
return ensure_account_dir(account_path("images"))
+_IMG2IMG_WORKFLOWS = ("img2img", "inpaint", "outpaint", "edit", "upscale")
+
+
def _params_text(meta: dict[str, Any]) -> str:
"""Automatic1111-style ``parameters`` string for cross-tool interop."""
lines = [str(meta.get("prompt", ""))]
@@ -58,7 +63,7 @@ def _params_text(meta: dict[str, Any]) -> str:
return "\n".join(lines)
sampler = sampler_label(meta.get("sampler"))
schedule = schedule_label(meta.get("schedule_type"))
- lines.append(
+ fields = (
f"Steps: {meta.get('steps')}, "
+ (f"Sampler: {sampler}, " if sampler else "")
+ (f"Schedule type: {schedule}, " if schedule else "")
@@ -66,6 +71,11 @@ def _params_text(meta: dict[str, Any]) -> str:
f"Seed: {meta.get('seed')}, Size: {meta.get('width')}x{meta.get('height')}, "
f"Model: {meta.get('model', '')}"
)
+ if meta.get("workflow") in _IMG2IMG_WORKFLOWS and meta.get("strength") is not None:
+ fields += f", Denoising strength: {meta['strength']}"
+ if meta.get("generator"):
+ fields += f", Version: {meta['generator']}"
+ lines.append(fields)
return "\n".join(lines)
@@ -96,10 +106,35 @@ def _png_bytes(image: Any, meta: dict[str, Any]) -> bytes:
return buf.getvalue()
[email protected]_cache(maxsize = 1)
+def _generator() -> str:
+ try:
+ from utils.studio_version import get_studio_version
+ return f"Unsloth {get_studio_version()}"
+ except Exception:
+ return "Unsloth"
+
+
+def _engine() -> Optional[str]:
+ # Read only when a generation already loaded the router: diffusers and the native engine draw
+ # different pixels from the same seed, so a replay needs to know which one ran.
+ router = sys.modules.get("core.inference.diffusion_engine_router")
+ try:
+ return router.active_engine_name() if router is not None else None
+ except Exception:
+ return None
+
+
def save(image: Any, meta: dict[str, Any]) -> dict[str, Any]:
"""Persist a PIL image with its recipe embedded; return the gallery record."""
image_id = uuid.uuid4().hex
- meta = {**meta, "schema_version": RECIPE_SCHEMA_VERSION}
+ meta = {
+ # A Connection run never touched the local engine.
+ "engine": None if meta.get("model_kind") == "connection" else _engine(),
+ "generator": _generator(),
+ **meta,
+ "schema_version": RECIPE_SCHEMA_VERSION,
+ }
# Encoded before the folder is looked up: a Settings move during the encode would otherwise
# finish first, and the image land in the folder it left.
data = _png_bytes(image, meta)
diff --git a/studio/backend/tests/test_image_gallery.py b/studio/backend/tests/test_image_gallery.py
index eacd9ef23f0..d1a913dad41 100644
--- a/studio/backend/tests/test_image_gallery.py
+++ b/studio/backend/tests/test_image_gallery.py
@@ -112,6 +112,20 @@ def test_negative_prompt_recorded_in_parameters():
assert "Negative prompt: blurry" in im.text["parameters"]
+def test_parameters_carry_strength_version_and_the_recipe_the_engine():
+ # Upscale's strength is its denoise, like the img2img workflows; plain txt2img has none.
+ for workflow, expected in (("upscale", True), ("edit", True), ("txt2img", False)):
+ record = gallery.save(_img(), _meta(workflow = workflow, strength = 0.35))
+ raw = base64.b64decode(gallery.image_b64(record["id"]))
+ with Image.open(io.BytesIO(raw)) as im:
+ params = im.text["parameters"]
+ recipe = _json.loads(im.text["unsloth"])
+ assert ("Denoising strength: 0.35" in params) is expected, (workflow, params)
+ assert ", Version: Unsloth " in params
+ assert recipe["generator"].startswith("Unsloth")
+ assert "engine" in recipe
+
+
def test_delete_and_clear():
a = gallery.save(_img(), _meta(prompt = "a"))
gallery.save(_img(), _meta(prompt = "b"))
@@ -592,3 +606,103 @@ def test_gallery_png_is_lossless_at_any_level(monkeypatch, level):
with Image.open(io.BytesIO(raw)) as im:
assert im.convert("RGB").tobytes() == image.tobytes()
assert _json.loads(im.text["unsloth"])["seed"] == 7
+
+
+def _recipe_keys_written() -> set[str]:
+ """Every key a generation route puts in an image's recipe, read from the routes' source."""
+ import ast
+ from pathlib import Path
+
+ tree = ast.parse(
+ (Path(__file__).resolve().parents[1] / "routes" / "inference.py").read_text(
+ encoding = "utf-8"
+ )
+ )
+ keys: set[str] = set()
+ for fn in ast.walk(tree):
+ if not isinstance(fn, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ continue
+ local_dicts = {
+ t.id: node.value
+ for node in ast.walk(fn)
+ if isinstance(node, ast.Assign) and isinstance(node.value, ast.Dict)
+ for t in node.targets
+ if isinstance(t, ast.Name)
+ }
+ for call in ast.walk(fn):
+ if not (
+ isinstance(call, ast.Call)
+ and isinstance(call.func, ast.Attribute)
+ and call.func.attr == "save"
+ and isinstance(call.func.value, ast.Name)
+ and call.func.value.id == "image_gallery"
+ and len(call.args) > 1
+ and isinstance(call.args[1], ast.Dict)
+ ):
+ continue
+ pending = [call.args[1]]
+ while pending:
+ d = pending.pop()
+ for k, v in zip(d.keys, d.values):
+ if k is None and isinstance(v, ast.Name) and v.id in local_dicts:
+ pending.append(local_dicts[v.id])
+ elif isinstance(k, ast.Constant) and isinstance(k.value, str):
+ keys.add(k.value)
+ return keys
+
+
+def test_every_recipe_key_is_known_to_the_image_import():
+ # Adding a setting to the recipe without teaching "Load settings from an image" about it would
+ # make the import report a current image's own setting as unsupported.
+ import re
+ from pathlib import Path
+
+ written = _recipe_keys_written()
+ assert {"prompt", "seed", "sampler", "strength"} <= written, written
+ meta = gallery.save(
+ _img(),
+ {
+ "prompt": "p",
+ "width": 8,
+ "height": 8,
+ "steps": 1,
+ "guidance": 0,
+ "seed": 1,
+ "created_at": 1.0,
+ },
+ )
+ written |= set(gallery._read_meta(gallery.gallery_dir() / f"{meta['id']}.png"))
+ ts = (
+ Path(__file__).resolve().parents[2]
+ / "frontend"
+ / "src"
+ / "features"
+ / "images"
+ / "lib"
+ / "image-metadata.ts"
+ ).read_text(encoding = "utf-8")
+ known: set[str] = set()
+ for name in ("APPLIED_RECIPE_KEYS", "INFO_RECIPE_KEYS"):
+ body = re.search(rf"export const {name} = \[(.*?)\] as const;", ts, re.S)
+ assert body, name
+ known |= set(re.findall(r'"([a-z_]+)"', body.group(1)))
+ assert sorted(written - known) == []
+ version = re.search(r"export const RECIPE_SCHEMA_VERSION = (\d+);", ts)
+ assert version and int(version.group(1)) == gallery.RECIPE_SCHEMA_VERSION
+
+
+def test_connection_images_record_no_local_engine(monkeypatch):
+ monkeypatch.setattr(gallery, "_engine", lambda: "diffusers")
+ base = {
+ "prompt": "p",
+ "width": 8,
+ "height": 8,
+ "steps": 1,
+ "guidance": 0,
+ "seed": 1,
+ "created_at": 1.0,
+ }
+ local = gallery.save(_img(), dict(base))
+ remote = gallery.save(_img(), {**base, "model_kind": "connection"})
+ assert local["engine"] == "diffusers"
+ assert remote["engine"] is None
diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.ts
index eb2d53f4260..ab58f449b1a 100644
--- a/studio/frontend/scripts/check-bundle-budget.ts
+++ b/studio/frontend/scripts/check-bundle-budget.ts
@@ -156,8 +156,12 @@ export const BUDGET = {
// the previous limits there, so they are set to the measured build.
// The downloads panel's "Starting…" row (#13738) adds 1,404 B raw / 353 B transfer (6,778,788 -> 6,780,192 B raw,
// 2,038,337 -> 2,038,690 B transfer against 7c235de6f, one machine and build, Node 24, 95 chunks). Raised by that growth.
- transferBytes: 2_039_209,
- rawBytes: 6_782_008,
+ // The Image downloads > Info stamp row in Settings > Library, its search entry and strings (#13444) add 348 B
+ // raw / 83 B transfer to the eager settings and English locale chunks (6,780,553 -> 6,780,901 B raw,
+ // 2,038,848 -> 2,038,931 B transfer against 9f5b133254, one machine and build, Node 24, chunk count unchanged
+ // at 95). Raised by that growth.
+ transferBytes: 2_039_292,
+ rawBytes: 6_782_356,
};
// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering the
diff --git a/studio/frontend/src/features/generation-presets/media-generation-preset-control.tsx b/studio/frontend/src/features/generation-presets/media-generation-preset-control.tsx
index b7792f76fb5..eb47c1f3f90 100644
--- a/studio/frontend/src/features/generation-presets/media-generation-preset-control.tsx
+++ b/studio/frontend/src/features/generation-presets/media-generation-preset-control.tsx
@@ -9,7 +9,7 @@ import {
PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
-import { Bookmark, Check, ChevronDown, Trash2 } from "lucide-react";
+import { Bookmark, Check, ChevronDown, ImageUp, Trash2 } from "lucide-react";
import { Fragment, useState } from "react";
import { DEFAULT_PRESET_NAME } from "./preset-policy";
@@ -22,6 +22,7 @@ interface MediaGenerationPresetControlProps {
onSelect: (name: string) => void;
onSave: (name: string) => Promise<string | null>;
onDelete: () => Promise<boolean>;
+ onImportFromImage?: () => void;
}
export function MediaGenerationPresetControl({
@@ -33,6 +34,7 @@ export function MediaGenerationPresetControl({
onSelect,
onSave,
onDelete,
+ onImportFromImage,
}: MediaGenerationPresetControlProps) {
const [open, setOpen] = useState(false);
const [draftName, setDraftName] = useState<string | null>(null);
@@ -214,6 +216,20 @@ export function MediaGenerationPresetControl({
{saveLabel}
</Button>
</div>
+ {onImportFromImage ? (
+ <button
+ type="button"
+ disabled={saving}
+ onClick={() => {
+ changeOpen(false);
+ onImportFromImage();
+ }}
+ className="mt-3 flex h-8 w-full items-center justify-center gap-1.5 rounded-lg text-xs text-muted-foreground transition-colors hover:bg-muted/70 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
+ >
+ <ImageUp className="size-3.5" />
+ Load settings from an image
+ </button>
+ ) : null}
{activeIsCustom ? (
<button
type="button"
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index a5fd76f58aa..25b83a45a91 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -5,6 +5,7 @@ import { generationFailureLogsAction } from "@/features/settings/lib/view-logs-a
import { readImageModel, rememberImageModel, matchesRememberedModel, componentFilesMatch, type RememberedImageModel } from "./image-model-recall";
import { componentFileFields, splitComponentFileList } from "./component-files";
import {
+ type DragEvent,
type ReactNode,
type SetStateAction,
useCallback,
@@ -33,6 +34,11 @@ import { MediaViewer } from "@/components/media-viewer";
import { shortPrompt } from "@/lib/prompt-text";
import { ImageDropzone } from "@/components/image-dropzone";
+import {
+ readNativeAttachmentFile,
+ registerNativeAttachmentPath,
+ useNativeDropTarget,
+} from "@/features/native-intents";
import { useImageCrop } from "@/hooks/use-image-crop";
import { GuidedTour, useGuidedTourController } from "@/features/tour";
import { buildImagesTourSteps } from "./tour";
@@ -41,6 +47,7 @@ import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
+ DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
@@ -273,6 +280,19 @@ import {
shouldReportGenerateError,
stopButtonLabel,
} from "./lib/generation-stop";
+import { drawInfoStamp, infoStampText } from "./lib/info-stamp";
+import {
+ copyPngTextChunks,
+ importedRecipe,
+ newerRecipeSchema,
+ pngRecipe,
+ readEmbeddedRecipe,
+ recipeSettings,
+ unknownRecipeKeys,
+ withJpegExif,
+ withWebpExif,
+} from "./lib/image-metadata";
+import { useLibrarySettingsStore } from "@/features/library/settings-store";
import {
ALLOW_OVERSIZED_HINT,
ALLOW_OVERSIZED_LABEL,
@@ -290,6 +310,7 @@ import {
type SamplerChoice,
samplerRecipeLabel,
samplerRequestFields,
+ SAMPLER_LABELS,
SCHEDULE_LABELS,
withSamplerChoice,
} from "./lib/sampler-choice";
@@ -341,6 +362,10 @@ function useImageModels(
// support; null = always. Each conditioned workflow names the images it consumed for the restore
// toast, since a recipe keeps the scalar settings but not the uploads. Keys are the backend's own
// workflow strings; txt2img is absent because it restores completely.
+// Own keys only: an imported id like "constructor" must not read Object.prototype.
+const labelOf = (labels: Record<string, string>, id: string) =>
+ Object.hasOwn(labels, id) ? labels[id] : id;
+
const CONDITIONED_WORKFLOW_INPUTS: Record<string, string> = {
img2img: "the source image",
inpaint: "the source image and mask",
@@ -529,11 +554,14 @@ function exportFilename(image: GalleryImage, format: ImageExportFormat = "png"):
return `Unsloth_${stamp}_${image.seed}${suffix}.${ext}`;
}
-// PNG saves the stored bytes verbatim, keeping the embedded recipe; JPEG / WebP re-encode
-// client-side, JPEG flattened onto white.
-async function reencodeImage(
+// Re-encoded client-side (JPEG flattened onto white), with the info stamp when it is on. Every
+// format carries the stored recipe: PNG keeps its text chunks, JPEG / WebP get it as EXIF.
+async function encodeExport(
src: string,
- format: Exclude<ImageExportFormat, "png">,
+ original: Uint8Array,
+ image: GalleryImage,
+ format: ImageExportFormat,
+ stamp: boolean,
): Promise<Blob> {
const el = new Image();
el.decoding = "async";
@@ -551,6 +579,9 @@ async function reencodeImage(
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
ctx.drawImage(el, 0, 0);
+ if (stamp) {
+ drawInfoStamp(ctx, canvas.width, canvas.height, infoStampText(image));
+ }
const blob = await new Promise<Blob | null>((resolve) =>
canvas.toBlob(resolve, `image/${format}`, 0.95),
);
@@ -562,39 +593,54 @@ async function reencodeImage(
// failed conversion and use a matching .png name.
throw new Error(`${format} encoding is unavailable`);
}
- return blob;
+ const bytes = new Uint8Array(await blob.arrayBuffer());
+ const recipe = pngRecipe(original);
+ const out =
+ format === "png"
+ ? copyPngTextChunks(original, bytes)
+ : format === "jpeg"
+ ? withJpegExif(bytes, recipe)
+ : withWebpExif(bytes, recipe, canvas.width, canvas.height);
+ return new Blob([out], { type: `image/${format}` });
}
async function downloadImage(
- src: string,
image: GalleryImage,
format: ImageExportFormat = "png",
+ src?: string,
) {
- let outputFormat = format;
- let outputBlob: Blob | null = null;
-
- if (format !== "png") {
- try {
- outputBlob = await reencodeImage(src, format);
- } catch {
- // Conversion failed, so preserve the original PNG instead.
- outputFormat = "png";
- outputBlob = null;
- }
- }
-
- const filename = exportFilename(image, outputFormat);
+ const stamp = useLibrarySettingsStore.getState().imageInfoStamp;
+ let ownedUrl: string | null = null;
try {
- if (outputBlob) {
- await downloadFile(outputBlob, filename, outputBlob.type);
- } else if (isTauri) {
- // WebKit can display the cached object URL but fail to fetch it again, so re-fetch the
- // authenticated original for the native save.
- const originalBlob = await fetchGalleryBlob(image.url);
- await downloadFile(originalBlob, filename, originalBlob.type);
+ let output: Blob;
+ let outputFormat = format;
+ if (format === "png" && !stamp) {
+ // The stored bytes verbatim. WebKit can display the cached object URL but fail to fetch it
+ // again, so the native save re-fetches the authenticated original.
+ if (src && !isTauri) {
+ const filename = exportFilename(image, "png");
+ await downloadUrl(src, filename);
+ return;
+ }
+ output = await fetchGalleryBlob(image.url);
} else {
- await downloadUrl(src, filename);
+ const original = await fetchGalleryBlob(image.url);
+ const source = src ?? (ownedUrl = URL.createObjectURL(original));
+ try {
+ output = await encodeExport(
+ source,
+ new Uint8Array(await original.arrayBuffer()),
+ image,
+ format,
+ stamp,
+ );
+ } catch {
+ outputFormat = "png";
+ output = original;
+ }
}
+ const filename = exportFilename(image, outputFormat);
+ await downloadFile(output, filename, output.type || "image/png");
if (isTauri) {
toast.success("Image saved", { description: filename });
}
@@ -605,6 +651,10 @@ async function downloadImage(
toast.error("Could not save image", {
description: error instanceof Error ? error.message : undefined,
});
+ } finally {
+ if (ownedUrl) {
+ URL.revokeObjectURL(ownedUrl);
+ }
}
}
@@ -1461,6 +1511,7 @@ export function ImagesPage({
}) {
const t = useT();
const initialReadySent = useRef(false);
+ const imageInfoStamp = useLibrarySettingsStore((state) => state.imageInfoStamp);
const [rememberedModel, setRememberedModel] = useState(readImageModel);
const pendingRecalledGeneration = useRef<{ model: RememberedImageModel; load: number; workflow: WorkflowId; allowOversized?: boolean } | null>(null);
const { isMobile, pinned } = useSidebar();
@@ -2478,24 +2529,8 @@ export function ImagesPage({
},
[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,
- });
- }
- },
+ (image: GalleryImage) => downloadImage(image, "png", srcById[image.id]),
[srcById],
);
const stripReorder = useStripReorder((id, afterId) => void handleMove(id, afterId));
@@ -2614,6 +2649,144 @@ export function ImagesPage({
}
}, [changeSamplerChoice, samplerOptions.length, setPromptFor, setWorkflow, sizeLimits]);
+ // Like dropping an image on ComfyUI: Unsloth's recipe first, else AUTOMATIC1111 / ComfyUI metadata.
+ const importFileRef = useRef<HTMLInputElement>(null);
+ const importSettingsFromFile = useCallback(
+ async (file: File | Uint8Array) => {
+ let recipe = null;
+ try {
+ const bytes = file instanceof Uint8Array ? file : new Uint8Array(await file.arrayBuffer());
+ recipe = importedRecipe(readEmbeddedRecipe(bytes));
+ } catch {
+ recipe = null;
+ }
+ if (!recipe) {
+ toast.error("No generation settings found in this image", {
+ description: "Images saved by Unsloth, ComfyUI, or tools that write a parameters block can be loaded.",
+ });
+ return;
+ }
+ const settings = recipeSettings(recipe, { width, height, steps, guidance });
+ const localized = settings.localized_edit;
+ restoreSettings({
+ ...settings,
+ id: "",
+ url: "",
+ seed: settings.seed ?? 0,
+ batch_index: 0,
+ created_at: 0,
+ localized_edit:
+ localized === "annotate" || localized === "paint" || localized === "mask" ? localized : null,
+ });
+ if (settings.seed === null && settings.model_kind !== "connection") setSeed("");
+ const loaded = status?.display_repo_id ?? status?.repo_id ?? null;
+ const quant = typeof recipe.gguf_filename === "string" ? recipe.gguf_filename : null;
+ if (settings.model && settings.model !== loaded) {
+ toast(`Made with ${settings.model}${quant ? ` (${quant})` : ""}`, {
+ // Loading a model applies its own default steps and guidance.
+ description: "Load that model, then load settings from this image again to reproduce it.",
+ });
+ } else if (settings.model && status?.loaded) {
+ // Same model, another build: null on either side means dense / no quant.
+ const differs = (["gguf_filename", "transformer_quant", "text_encoder_quant", "transformer_cache", "attention_backend"] as const).filter(
+ (key) =>
+ Object.hasOwn(recipe, key) &&
+ status[key] !== undefined &&
+ (recipe[key] ?? null) !== (status[key] ?? null),
+ );
+ if (differs.length > 0) {
+ toast(
+ `Made with ${differs.map((key) => (key === "gguf_filename" ? String(recipe[key] ?? "the dense model") : `${key.replace(/_/g, " ")} ${String(recipe[key] ?? "off")}`)).join(", ")}`,
+ { description: "Reload the model with that build to reproduce this image exactly." },
+ );
+ }
+ }
+ const notApplied = unknownRecipeKeys(recipe);
+ const baked = Array.isArray(recipe.baked_loras)
+ ? recipe.baked_loras.filter((x): x is string => typeof x === "string")
+ : [];
+ if (baked.length > 0) notApplied.unshift(`baked LoRAs ${baked.join(", ")} (load-time)`);
+ if (typeof recipe.controlnet === "string" && recipe.controlnet) {
+ notApplied.unshift(`ControlNet ${recipe.controlnet}`);
+ }
+ if (status?.loaded && status.supports_lora === false && settings.loras.length > 0) {
+ notApplied.unshift("LoRAs");
+ }
+ if (status?.supports_negative_prompt === false && settings.negative_prompt && settings.guidance > 0) {
+ notApplied.unshift("negative prompt");
+ }
+ if (status?.loaded && samplerOptions.length === 0) {
+ if (settings.schedule_type && settings.schedule_type !== AUTOMATIC_SCHEDULE) {
+ notApplied.unshift(`schedule ${labelOf(SCHEDULE_LABELS, settings.schedule_type)}`);
+ }
+ if (settings.sampler && settings.sampler !== DEFAULT_SAMPLER) {
+ notApplied.unshift(`sampler ${labelOf(SAMPLER_LABELS, settings.sampler)}`);
+ }
+ } else if (samplerOptions.length > 0) {
+ const offered = samplerOptions.find((o) => o.id === (settings.sampler ?? DEFAULT_SAMPLER));
+ if (!offered) {
+ notApplied.unshift(`sampler ${labelOf(SAMPLER_LABELS, settings.sampler ?? DEFAULT_SAMPLER)}`);
+ } else if (
+ settings.schedule_type &&
+ !offered.schedule_types.includes(settings.schedule_type)
+ ) {
+ notApplied.unshift(`schedule ${labelOf(SCHEDULE_LABELS, settings.schedule_type)}`);
+ }
+ }
+ if (notApplied.length > 0 || newerRecipeSchema(recipe)) {
+ toast.warning("Some settings in this image were not applied", {
+ description:
+ (notApplied.length > 0 ? `Not applied: ${notApplied.join(", ")}. ` : "") +
+ (newerRecipeSchema(recipe)
+ ? "It was made with a newer Unsloth; update to use every setting."
+ : "This model or build does not support them."),
+ });
+ }
+ },
+ [restoreSettings, width, height, steps, guidance, status, samplerOptions],
+ );
+ // Desktop: Tauri delivers OS drops as paths and suppresses the DOM drop event.
+ const importNativePath = useCallback(
+ async (path: string | undefined) => {
+ if (!path) return;
+ if (!["png", "jpg", "jpeg", "webp"].includes(path.split(".").pop()?.toLowerCase() ?? "")) {
+ toast.error("Drop a PNG, JPEG or WebP image to load its settings");
+ return;
+ }
+ try {
+ const intent = await registerNativeAttachmentPath(path);
+ const file = await readNativeAttachmentFile(intent.path.token);
+ await importSettingsFromFile(Uint8Array.from(atob(file.base64), (c) => c.charCodeAt(0)));
+ } catch (error) {
+ toast.error("Could not read the image", {
+ description: error instanceof Error ? error.message : String(error),
+ });
+ }
+ },
+ [importSettingsFromFile],
+ );
+ const previewDropRef = useNativeDropTarget({ onDrop: (paths) => void importNativePath(paths[0]) });
+ const onImportDragOver = useCallback((event: DragEvent<HTMLDivElement>) => {
+ if (event.dataTransfer.types.includes("Files")) {
+ event.preventDefault();
+ event.dataTransfer.dropEffect = "copy";
+ }
+ }, []);
+ const onImportDrop = useCallback(
+ (event: DragEvent<HTMLDivElement>) => {
+ if (!event.dataTransfer.types.includes("Files")) return;
+ // Claimed even for a file this cannot read, or the browser navigates away to it.
+ event.preventDefault();
+ const file = Array.from(event.dataTransfer.files).find((f) => f.type.startsWith("image/"));
+ if (file) {
+ void importSettingsFromFile(file);
+ } else {
+ toast.error("Drop a PNG, JPEG or WebP image to load its settings");
+ }
+ },
+ [importSettingsFromFile],
+ );
+
// A locked ratio keeps the paired dimension in step; "custom" frees both, Flip swaps W/H. ratioHW is h/w for [a,b].
const ratioHW = (a: number, b: number) => (portrait ? a / b : b / a);
const changeAspect = (key: string) => {
@@ -5180,6 +5353,7 @@ export function ImagesPage({
onSelect={imagePresets.selectPreset}
onSave={imagePresets.savePreset}
onDelete={imagePresets.deletePreset}
+ onImportFromImage={() => importFileRef.current?.click()}
/>
)}
</div>
@@ -5920,9 +6094,24 @@ export function ImagesPage({
</div>
<div
+ ref={previewDropRef}
data-tour="images-preview"
className="relative flex min-h-[60dvh] min-w-0 flex-1 flex-col overflow-hidden @[50rem]:min-h-0"
+ onDragOver={onImportDragOver}
+ onDrop={onImportDrop}
>
+ <input
+ ref={importFileRef}
+ type="file"
+ accept="image/png,image/jpeg,image/webp"
+ className="hidden"
+ data-testid="images-import-settings-input"
+ onChange={(event) => {
+ const file = event.target.files?.[0];
+ event.target.value = "";
+ if (file) void importSettingsFromFile(file);
+ }}
+ />
{viewerImage && viewerSrc && (
<MediaViewer
open={true}
@@ -6016,20 +6205,28 @@ export function ImagesPage({
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
- onClick={() => void downloadImage(selectedSrc, selected, "png")}
+ onClick={() => void downloadImage(selected, "png", selectedSrc)}
>
- PNG (original, keeps recipe)
+ PNG (lossless)
</DropdownMenuItem>
<DropdownMenuItem
- onClick={() => void downloadImage(selectedSrc, selected, "jpeg")}
+ onClick={() => void downloadImage(selected, "jpeg", selectedSrc)}
>
JPEG (smaller)
</DropdownMenuItem>
<DropdownMenuItem
- onClick={() => void downloadImage(selectedSrc, selected, "webp")}
+ onClick={() => void downloadImage(selected, "webp", selectedSrc)}
>
WebP
</DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={() => useSettingsDialogStore.getState().openDialog("library")}
+ className="justify-between gap-4 text-muted-foreground"
+ >
+ Info stamp
+ <span className="text-xs">{imageInfoStamp ? "On" : "Off"}</span>
+ </DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<GalleryItemMenu
diff --git a/studio/frontend/src/features/images/lib/image-metadata.ts b/studio/frontend/src/features/images/lib/image-metadata.ts
new file mode 100644
index 00000000000..755f03ba2b4
--- /dev/null
+++ b/studio/frontend/src/features/images/lib/image-metadata.ts
@@ -0,0 +1,937 @@
+// 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 { SAMPLER_LABELS, SCHEDULE_LABELS } from "./sampler-choice.ts";
+
+/** Generation settings in exported images, read back from dropped ones. PNG: `unsloth` + `parameters` text chunks;
+ * JPEG / WebP: EXIF UserComment (`parameters`, read by AUTOMATIC1111 / Forge / Civitai) + MakerNote (recipe). */
+
+export interface EmbeddedRecipe {
+ recipe?: string;
+ parameters?: string;
+ // ComfyUI's API-format graph (its `prompt` PNG chunk), read on import only.
+ comfyPrompt?: string;
+}
+
+type Bytes = Uint8Array<ArrayBuffer>;
+
+const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
+const TEXT_CHUNKS = new Set(["tEXt", "iTXt", "zTXt"]);
+const RECIPE_KEY = "unsloth";
+const PARAMETERS_KEY = "parameters";
+const MAKER_NOTE_PREFIX = "Unsloth\0";
+const SOFTWARE = "Unsloth";
+const COMFY_EXIF_PREFIX = "prompt:";
+
+interface Chunk {
+ type: string;
+ start: number;
+ end: number;
+ data: number;
+}
+
+function concat(parts: Uint8Array[]): Bytes {
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
+ let at = 0;
+ for (const p of parts) {
+ out.set(p, at);
+ at += p.length;
+ }
+ return out;
+}
+
+function ascii(bytes: Uint8Array, start: number, end: number): string {
+ return String.fromCharCode(...bytes.subarray(start, end));
+}
+
+function isPng(bytes: Uint8Array): boolean {
+ return bytes.length >= 8 && PNG_SIGNATURE.every((b, i) => bytes[i] === b);
+}
+
+function pngChunks(bytes: Uint8Array): Chunk[] | null {
+ if (!isPng(bytes)) {
+ return null;
+ }
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ const chunks: Chunk[] = [];
+ let offset = 8;
+ while (offset + 12 <= bytes.length) {
+ const end = offset + 12 + view.getUint32(offset);
+ if (end > bytes.length) {
+ return null;
+ }
+ const type = ascii(bytes, offset + 4, offset + 8);
+ chunks.push({ type, start: offset, end, data: offset + 8 });
+ offset = end;
+ if (type === "IEND") {
+ return chunks;
+ }
+ }
+ return null;
+}
+
+/** tEXt (Latin-1) and uncompressed iTXt (UTF-8) chunks by keyword. Compressed chunks are skipped. */
+export function pngTextChunks(bytes: Uint8Array): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const c of pngChunks(bytes) ?? []) {
+ const data = bytes.subarray(c.data, c.end - 4);
+ const nul = data.indexOf(0);
+ if (nul <= 0 || (c.type !== "tEXt" && c.type !== "iTXt")) {
+ continue;
+ }
+ const key = ascii(data, 0, nul);
+ if (c.type === "tEXt") {
+ out[key] = new TextDecoder("latin1").decode(data.subarray(nul + 1));
+ continue;
+ }
+ if (data[nul + 1] !== 0) {
+ continue;
+ }
+ const lang = data.indexOf(0, nul + 3);
+ const translated = lang < 0 ? -1 : data.indexOf(0, lang + 1);
+ if (translated >= 0) {
+ out[key] = new TextDecoder().decode(data.subarray(translated + 1));
+ }
+ }
+ return out;
+}
+
+/** `target` with its text chunks replaced by `source`'s (copied verbatim, CRCs intact) right after
+ * IHDR. Either side unparsable: `target` unchanged. */
+export function copyPngTextChunks(source: Uint8Array, target: Bytes): Bytes {
+ const from = pngChunks(source);
+ const into = pngChunks(target);
+ if (!from || !into || into[0]?.type !== "IHDR") {
+ return target;
+ }
+ const parts: Uint8Array[] = [target.subarray(0, into[0].end)];
+ for (const c of from) {
+ if (TEXT_CHUNKS.has(c.type)) parts.push(source.subarray(c.start, c.end));
+ }
+ for (const c of into.slice(1)) {
+ if (!TEXT_CHUNKS.has(c.type)) parts.push(target.subarray(c.start, c.end));
+ }
+ return concat(parts);
+}
+
+export function pngRecipe(bytes: Uint8Array): EmbeddedRecipe {
+ const text = pngTextChunks(bytes);
+ const out: EmbeddedRecipe = {
+ recipe: text[RECIPE_KEY],
+ parameters: text[PARAMETERS_KEY],
+ };
+ if (text.prompt?.trimStart().startsWith("{")) {
+ out.comfyPrompt = text.prompt;
+ }
+ return out;
+}
+
+// EXIF is big-endian TIFF, the layout piexif writes, so AUTOMATIC1111 reads it back.
+
+interface IfdEntry {
+ tag: number;
+ type: number;
+ count: number;
+ value: Uint8Array;
+}
+
+const ASCII = 2;
+const LONG = 4;
+const UNDEFINED = 7;
+
+function asciiValue(text: string): Uint8Array {
+ return new Uint8Array([...text].map((c) => c.charCodeAt(0) & 0x7f).concat(0));
+}
+
+function userComment(text: string): Uint8Array {
+ const out = new Uint8Array(8 + text.length * 2);
+ out.set([0x55, 0x4e, 0x49, 0x43, 0x4f, 0x44, 0x45, 0]); // "UNICODE\0", then UTF-16BE
+ const view = new DataView(out.buffer);
+ for (let i = 0; i < text.length; i++)
+ view.setUint16(8 + i * 2, text.charCodeAt(i));
+ return out;
+}
+
+function ifdSize(entries: IfdEntry[]): number {
+ const external = entries.reduce(
+ (n, e) =>
+ n + (e.value.length > 4 ? e.value.length + (e.value.length & 1) : 0),
+ 0,
+ );
+ return 2 + entries.length * 12 + 4 + external;
+}
+
+function writeIfd(out: Uint8Array, at: number, entries: IfdEntry[]): void {
+ const view = new DataView(out.buffer);
+ view.setUint16(at, entries.length);
+ let data = at + 2 + entries.length * 12 + 4;
+ entries.forEach((e, i) => {
+ const slot = at + 2 + i * 12;
+ view.setUint16(slot, e.tag);
+ view.setUint16(slot + 2, e.type);
+ view.setUint32(slot + 4, e.count);
+ if (e.value.length <= 4) {
+ out.set(e.value, slot + 8);
+ } else {
+ view.setUint32(slot + 8, data);
+ out.set(e.value, data);
+ data += e.value.length + (e.value.length & 1);
+ }
+ });
+ view.setUint32(at + 2 + entries.length * 12, 0);
+}
+
+export function buildExif(meta: EmbeddedRecipe): Bytes | null {
+ const exifEntries: IfdEntry[] = [];
+ if (meta.parameters) {
+ const v = userComment(meta.parameters);
+ exifEntries.push({
+ tag: 0x9286,
+ type: UNDEFINED,
+ count: v.length,
+ value: v,
+ });
+ }
+ if (meta.recipe) {
+ const v = concat([
+ new TextEncoder().encode(MAKER_NOTE_PREFIX),
+ new TextEncoder().encode(meta.recipe),
+ ]);
+ exifEntries.push({
+ tag: 0x927c,
+ type: UNDEFINED,
+ count: v.length,
+ value: v,
+ });
+ }
+ if (exifEntries.length === 0) {
+ return null;
+ }
+ exifEntries.sort((a, b) => a.tag - b.tag);
+ const software = asciiValue(SOFTWARE);
+ const ifd0: IfdEntry[] = [
+ { tag: 0x0131, type: ASCII, count: software.length, value: software },
+ { tag: 0x8769, type: LONG, count: 1, value: new Uint8Array(4) },
+ ];
+ const exifAt = 8 + ifdSize(ifd0);
+ new DataView(ifd0[1].value.buffer).setUint32(0, exifAt);
+ const out = new Uint8Array(exifAt + ifdSize(exifEntries));
+ out.set([0x4d, 0x4d, 0, 0x2a, 0, 0, 0, 8]);
+ writeIfd(out, 8, ifd0);
+ writeIfd(out, exifAt, exifEntries);
+ return out;
+}
+
+const EXIF_HEADER = [0x45, 0x78, 0x69, 0x66, 0, 0];
+const JPEG_SEGMENT_MAX = 0xffff - 2;
+
+/** `jpeg` with one EXIF APP1 segment (any existing one replaced) after SOI / APP0. A segment too
+ * large for JPEG falls back to the parameters text alone, then to no EXIF. */
+export function withJpegExif(jpeg: Bytes, meta: EmbeddedRecipe): Bytes {
+ if (jpeg[0] !== 0xff || jpeg[1] !== 0xd8) {
+ return jpeg;
+ }
+ let tiff = buildExif(meta);
+ if (tiff && tiff.length + EXIF_HEADER.length > JPEG_SEGMENT_MAX) {
+ tiff = buildExif({ parameters: meta.parameters });
+ }
+ if (tiff && tiff.length + EXIF_HEADER.length > JPEG_SEGMENT_MAX) {
+ tiff = null;
+ }
+ const kept: Uint8Array[] = [];
+ let insertAt = 2;
+ let at = 2;
+ while (at + 4 <= jpeg.length && jpeg[at] === 0xff) {
+ const marker = jpeg[at + 1];
+ if (marker === 0xda || marker < 0xe0 || marker > 0xef) {
+ break;
+ }
+ const end = at + 2 + ((jpeg[at + 2] << 8) | jpeg[at + 3]);
+ const isExif =
+ marker === 0xe1 && EXIF_HEADER.every((b, i) => jpeg[at + 4 + i] === b);
+ if (!isExif) kept.push(jpeg.subarray(at, end));
+ if (marker === 0xe0 && insertAt === at) insertAt = end;
+ at = end;
+ }
+ const head = jpeg.subarray(0, 2);
+ const app0 = insertAt > 2 ? [kept.shift() as Uint8Array] : [];
+ if (!tiff) {
+ return concat([head, ...app0, ...kept, jpeg.subarray(at)]);
+ }
+ const length = 2 + EXIF_HEADER.length + tiff.length;
+ const segment = concat([
+ new Uint8Array([0xff, 0xe1, length >> 8, length & 0xff, ...EXIF_HEADER]),
+ tiff,
+ ]);
+ return concat([head, ...app0, segment, ...kept, jpeg.subarray(at)]);
+}
+
+function riffChunks(webp: Uint8Array): Chunk[] | null {
+ if (
+ webp.length < 12 ||
+ ascii(webp, 0, 4) !== "RIFF" ||
+ ascii(webp, 8, 12) !== "WEBP"
+ ) {
+ return null;
+ }
+ const view = new DataView(webp.buffer, webp.byteOffset, webp.byteLength);
+ const chunks: Chunk[] = [];
+ let at = 12;
+ while (at + 8 <= webp.length) {
+ const size = view.getUint32(at + 4, true);
+ const end = at + 8 + size + (size & 1);
+ if (at + 8 + size > webp.length) {
+ return null;
+ }
+ chunks.push({
+ type: ascii(webp, at, at + 4),
+ start: at,
+ end: Math.min(end, webp.length),
+ data: at + 8,
+ });
+ at = end;
+ }
+ return chunks;
+}
+
+function riffChunk(type: string, payload: Uint8Array): Uint8Array {
+ const out = new Uint8Array(8 + payload.length + (payload.length & 1));
+ out.set([...type].map((c) => c.charCodeAt(0)));
+ new DataView(out.buffer).setUint32(4, payload.length, true);
+ out.set(payload, 8);
+ return out;
+}
+
+export function withWebpExif(
+ webp: Bytes,
+ meta: EmbeddedRecipe,
+ width: number,
+ height: number,
+): Bytes {
+ const chunks = riffChunks(webp);
+ const tiff = buildExif(meta);
+ if (!chunks || chunks.length === 0 || !tiff) {
+ return webp;
+ }
+ const body = chunks.filter((c) => c.type !== "EXIF" && c.type !== "VP8X");
+ let vp8x: Uint8Array;
+ const existing = chunks.find((c) => c.type === "VP8X");
+ if (existing) {
+ vp8x = webp.slice(existing.start, existing.end);
+ vp8x[8] |= 0x08;
+ } else {
+ const payload = new Uint8Array(10);
+ const lossless = body.find((c) => c.type === "VP8L");
+ // VP8L header: signature byte, then 14 + 14 bits of size, then the alpha_is_used bit.
+ const alpha = lossless ? (webp[lossless.data + 4] >> 4) & 1 : 0;
+ payload[0] = 0x08 | (alpha ? 0x10 : 0);
+ const w = width - 1;
+ const h = height - 1;
+ payload.set(
+ [
+ w & 0xff,
+ (w >> 8) & 0xff,
+ (w >> 16) & 0xff,
+ h & 0xff,
+ (h >> 8) & 0xff,
+ (h >> 16) & 0xff,
+ ],
+ 4,
+ );
+ vp8x = riffChunk("VP8X", payload);
+ }
+ const parts = [
+ vp8x,
+ ...body.map((c) => webp.subarray(c.start, c.end)),
+ riffChunk("EXIF", tiff),
+ ];
+ const size = 4 + parts.reduce((n, p) => n + p.length, 0);
+ const header = new Uint8Array(12);
+ header.set([0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50]);
+ new DataView(header.buffer).setUint32(4, size, true);
+ return concat([header, ...parts]);
+}
+
+function readTiff(tiff: Uint8Array): EmbeddedRecipe {
+ if (tiff.length < 8) {
+ return {};
+ }
+ const little = tiff[0] === 0x49;
+ const view = new DataView(tiff.buffer, tiff.byteOffset, tiff.byteLength);
+ const u16 = (at: number) => view.getUint16(at, little);
+ const u32 = (at: number) => view.getUint32(at, little);
+ const entries = (at: number) => {
+ const out = new Map<number, Uint8Array>();
+ if (at + 2 > tiff.length) return out;
+ const n = u16(at);
+ for (let i = 0; i < n; i++) {
+ const slot = at + 2 + i * 12;
+ if (slot + 12 > tiff.length) break;
+ const type = u16(slot + 2);
+ const count = u32(slot + 4);
+ const unit = type === 3 ? 2 : type === LONG ? 4 : 1;
+ const len = count * unit;
+ const start = len <= 4 ? slot + 8 : u32(slot + 8);
+ if (start + len <= tiff.length)
+ out.set(u16(slot), tiff.subarray(start, start + len));
+ }
+ return out;
+ };
+ const ifd0 = entries(u32(4));
+ const out: EmbeddedRecipe = {};
+ // ComfyUI's WebP / AVIF writers put its API graph in IFD0 Model as `prompt:{...}`.
+ const model = ifd0.get(0x0110);
+ if (model) {
+ const text = new TextDecoder().decode(model).replace(/\0+$/, "");
+ if (text.startsWith(COMFY_EXIF_PREFIX)) {
+ out.comfyPrompt = text.slice(COMFY_EXIF_PREFIX.length);
+ }
+ }
+ const pointer = ifd0.get(0x8769);
+ if (!pointer || pointer.length < 4) {
+ return out;
+ }
+ const exif = entries(
+ new DataView(pointer.buffer, pointer.byteOffset, 4).getUint32(0, little),
+ );
+ const comment = exif.get(0x9286);
+ if (comment && comment.length > 8) {
+ const prefix = ascii(comment, 0, 8);
+ const body = comment.subarray(8);
+ if (prefix === "UNICODE\0") {
+ const cv = new DataView(body.buffer, body.byteOffset, body.byteLength);
+ // piexif writes UTF-16BE, others the TIFF order: BOM, else where ASCII's zero bytes sit over the
+ // whole text (one leading U+4E00 must not decide), else TIFF order.
+ let start = 0;
+ let be: boolean;
+ if (body[0] === 0xfe && body[1] === 0xff) {
+ be = true;
+ start = 2;
+ } else if (body[0] === 0xff && body[1] === 0xfe) {
+ be = false;
+ start = 2;
+ } else {
+ let evenZeros = 0;
+ let oddZeros = 0;
+ for (let i = 0; i + 1 < body.length; i += 2) {
+ if (body[i] === 0 && body[i + 1] !== 0) evenZeros++;
+ else if (body[i + 1] === 0 && body[i] !== 0) oddZeros++;
+ }
+ be = evenZeros === oddZeros ? !little : evenZeros > oddZeros;
+ }
+ let s = "";
+ for (let i = start; i + 1 < body.length; i += 2)
+ s += String.fromCharCode(cv.getUint16(i, !be));
+ out.parameters = s.replace(/\0+$/, "");
+ } else {
+ out.parameters = new TextDecoder().decode(body).replace(/\0+$/, "");
+ }
+ }
+ const note = exif.get(0x927c);
+ if (note && ascii(note, 0, MAKER_NOTE_PREFIX.length) === MAKER_NOTE_PREFIX) {
+ out.recipe = new TextDecoder().decode(
+ note.subarray(MAKER_NOTE_PREFIX.length),
+ );
+ }
+ return out;
+}
+
+function jpegTiff(jpeg: Uint8Array): Uint8Array | null {
+ let at = 2;
+ while (at + 4 <= jpeg.length && jpeg[at] === 0xff) {
+ const marker = jpeg[at + 1];
+ if (marker === 0xda) break;
+ const end = at + 2 + ((jpeg[at + 2] << 8) | jpeg[at + 3]);
+ if (
+ marker === 0xe1 &&
+ EXIF_HEADER.every((b, i) => jpeg[at + 4 + i] === b)
+ ) {
+ return jpeg.subarray(
+ at + 4 + EXIF_HEADER.length,
+ Math.min(end, jpeg.length),
+ );
+ }
+ at = end;
+ }
+ return null;
+}
+
+function webpTiff(webp: Uint8Array): Uint8Array | null {
+ const chunk = riffChunks(webp)?.find((c) => c.type === "EXIF");
+ if (!chunk) return null;
+ const size = new DataView(webp.buffer, webp.byteOffset).getUint32(
+ chunk.start + 4,
+ true,
+ );
+ const data = webp.subarray(chunk.data, chunk.data + size);
+ return EXIF_HEADER.every((b, i) => data[i] === b)
+ ? data.subarray(EXIF_HEADER.length)
+ : data;
+}
+
+export function readEmbeddedRecipe(bytes: Uint8Array): EmbeddedRecipe {
+ if (isPng(bytes)) {
+ return pngRecipe(bytes);
+ }
+ const tiff =
+ bytes[0] === 0xff && bytes[1] === 0xd8 ? jpegTiff(bytes) : webpTiff(bytes);
+ return tiff ? readTiff(tiff) : {};
+}
+
+/** Settings read from a file: untrusted, so every field but the prompt stays `unknown` until
+ * `recipeSettings` checks it. */
+export interface ImportedRecipe {
+ prompt: string;
+ [key: string]: unknown;
+}
+
+const A1111_FIELD =
+ /\s*([A-Za-z][A-Za-z0-9 _-]*):\s*("(?:\\.|[^"\\])*"|[^,]*)(?:,|$)/g;
+const SIZE = /^(\d+)\s*x\s*(\d+)$/i;
+// An unknown label stays as written, so the import can name what it could not apply.
+const labelId = (labels: Record<string, string>, label: string) =>
+ Object.keys(labels).find((id) => labels[id] === label) ?? label;
+
+/** AUTOMATIC1111 `parameters` text: prompt, optional `Negative prompt:` line, then `Key: value, ...`. */
+export function parseA1111Parameters(text: string): ImportedRecipe | null {
+ const lines = text.replace(/\r\n/g, "\n").trim().split("\n");
+ if (lines.length === 0) {
+ return null;
+ }
+ const last = lines[lines.length - 1];
+ const hasSettings = /(^|,\s*)Steps:\s*\d+/.test(last);
+ const settingsLine = hasSettings ? (lines.pop() ?? "") : "";
+ const negativeAt = lines.findIndex((l) => l.startsWith("Negative prompt:"));
+ const promptLines = negativeAt >= 0 ? lines.slice(0, negativeAt) : lines;
+ const negative =
+ negativeAt >= 0
+ ? lines
+ .slice(negativeAt)
+ .join("\n")
+ .replace(/^Negative prompt:\s*/, "")
+ : null;
+ const out: ImportedRecipe = {
+ prompt: promptLines.join("\n").trim(),
+ negative_prompt: negative,
+ };
+ let legacySchedule: string | undefined;
+ let hires = false;
+ for (const m of settingsLine.matchAll(A1111_FIELD)) {
+ const key = m[1].trim().toLowerCase();
+ const value = m[2].trim();
+ const num = Number(value);
+ if (key === "steps" && Number.isInteger(num)) out.steps = num;
+ else if (key === "cfg scale" && Number.isFinite(num)) out.guidance = num;
+ else if (key === "seed" && Number.isSafeInteger(num)) out.seed = num;
+ else if (key === "model" && value) out.model = value;
+ else if (key === "denoising strength" && Number.isFinite(num))
+ out.strength = num;
+ else if (key.startsWith("hires")) hires = true;
+ else if (key === "sampler") {
+ out.sampler = labelId(SAMPLER_LABELS, value);
+ // Before AUTOMATIC1111 1.9 the schedule rode on the sampler name: `DPM++ 2M Karras`.
+ const suffix = Object.keys(SCHEDULE_LABELS).find(
+ (id) => id !== "automatic" && value.endsWith(` ${SCHEDULE_LABELS[id]}`),
+ );
+ if (out.sampler === value && suffix) {
+ out.sampler = labelId(
+ SAMPLER_LABELS,
+ value.slice(0, -SCHEDULE_LABELS[suffix].length - 1),
+ );
+ legacySchedule = suffix;
+ }
+ } else if (key === "schedule type")
+ out.schedule_type = labelId(SCHEDULE_LABELS, value);
+ else if (key === "size") {
+ const size = SIZE.exec(value);
+ if (size) {
+ out.width = Number(size[1]);
+ out.height = Number(size[2]);
+ }
+ }
+ }
+ out.schedule_type ??= legacySchedule;
+ // txt2img hires fix also writes a denoising strength; without it the strength means img2img.
+ if (out.strength !== undefined) {
+ if (hires) delete out.strength;
+ else out.workflow ??= "img2img";
+ }
+ return out.prompt || hasSettings ? out : null;
+}
+
+function recipeJson(text: string | undefined): ImportedRecipe | null {
+ if (!text) {
+ return null;
+ }
+ try {
+ const parsed: unknown = JSON.parse(text);
+ if (
+ typeof parsed !== "object" ||
+ parsed === null ||
+ Array.isArray(parsed)
+ ) {
+ return null;
+ }
+ const r = parsed as Record<string, unknown>;
+ return typeof r.prompt === "string" ? (r as ImportedRecipe) : null;
+ } catch {
+ return null;
+ }
+}
+
+/** The richest settings the file carries: Unsloth's recipe first, else the AUTOMATIC1111 text. */
+export function importedRecipe(
+ embedded: EmbeddedRecipe,
+): ImportedRecipe | null {
+ return (
+ recipeJson(embedded.recipe) ??
+ (embedded.parameters ? parseA1111Parameters(embedded.parameters) : null) ??
+ (embedded.comfyPrompt ? parseComfyPrompt(embedded.comfyPrompt) : null)
+ );
+}
+
+export interface RecipeDefaults {
+ width: number;
+ height: number;
+ steps: number;
+ guidance: number;
+}
+
+/** Type-checked form fields (a dropped file is untrusted); a missing seed stays null, i.e. random. */
+export interface RestorableRecipe {
+ prompt: string;
+ negative_prompt: string | null;
+ width: number;
+ height: number;
+ steps: number;
+ guidance: number;
+ seed: number | null;
+ batch_seed: number | null;
+ batch_size: number;
+ model: string | null;
+ workflow?: string;
+ loras: string[];
+ strength?: number;
+ upscale?: number;
+ reference_image_count?: number;
+ reference_resolution?: number;
+ localized_edit?: string | null;
+ // Only "connection" matters here: those runs never sent steps, guidance or a seed.
+ model_kind?: string;
+ sampler?: string;
+ schedule_type?: string;
+}
+
+export const APPLIED_RECIPE_KEYS = [
+ "prompt",
+ "negative_prompt",
+ "width",
+ "height",
+ "steps",
+ "guidance",
+ "seed",
+ "batch_seed",
+ "batch_size",
+ "loras",
+ "workflow",
+ "strength",
+ "upscale",
+ "reference_image_count",
+ "reference_resolution",
+ "localized_edit",
+ "sampler",
+ "schedule_type",
+] as const;
+
+/** Known but not applied: loading a model or a ControlNet image stays the user's call. */
+export const INFO_RECIPE_KEYS = [
+ "model",
+ "model_kind",
+ "gguf_filename",
+ "transformer_quant",
+ "text_encoder_quant",
+ "memory_mode",
+ "offload_policy",
+ "speed_mode",
+ "attention_backend",
+ "transformer_cache",
+ "cpu_offload",
+ "baked_loras",
+ "controlnet",
+ "controlnet_guidance",
+ "batch_index",
+ "created_at",
+ "engine",
+ "generator",
+ "schema_version",
+] as const;
+
+/** Matches RECIPE_SCHEMA_VERSION in core/inference/image_gallery.py. */
+export const RECIPE_SCHEMA_VERSION = 1;
+
+const KNOWN_RECIPE_KEYS = new Set<string>([
+ ...APPLIED_RECIPE_KEYS,
+ ...INFO_RECIPE_KEYS,
+]);
+
+/** Non-empty keys this build does not know (newer Unsloth, other tools), named instead of dropped. */
+export function unknownRecipeKeys(r: ImportedRecipe): string[] {
+ return Object.keys(r).filter((key) => {
+ if (KNOWN_RECIPE_KEYS.has(key)) {
+ return false;
+ }
+ const v = r[key];
+ return !(
+ v === null ||
+ v === undefined ||
+ v === "" ||
+ (Array.isArray(v) && v.length === 0)
+ );
+ });
+}
+
+export function newerRecipeSchema(r: ImportedRecipe): boolean {
+ return (
+ typeof r.schema_version === "number" &&
+ r.schema_version > RECIPE_SCHEMA_VERSION
+ );
+}
+
+const clamp = (
+ n: number | undefined,
+ lo: number,
+ hi: number,
+): number | undefined =>
+ n === undefined ? undefined : Math.min(hi, Math.max(lo, n));
+const num = (v: unknown): number | undefined =>
+ typeof v === "number" && Number.isFinite(v) ? v : undefined;
+const int = (v: unknown): number | undefined => {
+ const n = num(v);
+ return n !== undefined && Number.isSafeInteger(n) ? n : undefined;
+};
+const positive = (n: number | undefined): number | undefined =>
+ n !== undefined && n > 0 ? n : undefined;
+// The request takes seeds in [0, 2^53 - 1]; anything else leaves the seed random.
+const seedOf = (v: unknown): number | null => {
+ const n = int(v);
+ return n !== undefined && n >= 0 ? n : null;
+};
+// `id:weight` within the request's LoraSpec bounds (id 1-512 chars, weight 0-2), else dropped.
+const loraOf = (v: unknown): string[] => {
+ if (typeof v !== "string") return [];
+ const at = v.lastIndexOf(":");
+ const id = v.slice(0, at).trim();
+ const weight = Number(v.slice(at + 1));
+ if (at <= 0 || id.length > 512 || !Number.isFinite(weight)) return [];
+ return [`${id}:${Math.min(2, Math.max(0, weight))}`];
+};
+// The request rejects a repeated id: the first entry wins.
+const uniqueLoras = (loras: string[]): string[] => {
+ const seen = new Set<string>();
+ return loras.filter((l) => {
+ const id = l.slice(0, l.lastIndexOf(":"));
+ return !seen.has(id) && seen.add(id);
+ });
+};
+const str = (v: unknown): string | undefined =>
+ typeof v === "string" ? v : undefined;
+
+export function recipeSettings(
+ r: ImportedRecipe,
+ d: RecipeDefaults,
+): RestorableRecipe {
+ const width = int(r.width);
+ const height = int(r.height);
+ return {
+ prompt: str(r.prompt) ?? "",
+ negative_prompt: str(r.negative_prompt) ?? null,
+ width: width && width > 0 ? width : d.width,
+ height: height && height > 0 ? height : d.height,
+ // Clamped to the request's bounds: other tools allow more (AUTOMATIC1111 goes to 150 steps).
+ steps: clamp(int(r.steps), 1, 100) ?? d.steps,
+ guidance: clamp(num(r.guidance), 0, 20) ?? d.guidance,
+ seed: seedOf(r.seed),
+ batch_seed: seedOf(r.batch_seed),
+ batch_size: clamp(int(r.batch_size), 1, 32) ?? 1,
+ model: str(r.model) ?? null,
+ workflow: str(r.workflow),
+ loras: Array.isArray(r.loras)
+ ? uniqueLoras(r.loras.flatMap(loraOf)).slice(0, 8)
+ : [],
+ // The request takes strength in (0, 1]: 0 leaves no denoising steps, so it is not restored.
+ strength: positive(clamp(num(r.strength), 0, 1)),
+ upscale: clamp(num(r.upscale), 1, 4),
+ // The request caps reference images at 9; restore builds an array of this length.
+ reference_image_count: clamp(int(r.reference_image_count), 0, 9),
+ reference_resolution: clamp(int(r.reference_resolution), 256, 2048),
+ localized_edit: str(r.localized_edit) ?? null,
+ model_kind: r.model_kind === "connection" ? "connection" : undefined,
+ sampler: str(r.sampler),
+ schedule_type: str(r.schedule_type),
+ };
+}
+
+type ComfyGraph = Record<
+ string,
+ { class_type?: unknown; inputs?: Record<string, unknown> }
+>;
+
+const COMFY_SAMPLERS = new Set([
+ "KSampler",
+ "KSamplerAdvanced",
+ "SamplerCustomAdvanced",
+]);
+const COMFY_MODEL_INPUTS = ["ckpt_name", "unet_name", "model_name"];
+// ComfyUI core text-encoder prompt inputs (nodes_clip_sdxl.py, nodes_sd3.py, nodes_flux.py, ...), richest first.
+const COMFY_TEXT_INPUTS = [
+ "text",
+ "text_g",
+ "t5xxl",
+ "clip_g",
+ "clip_l",
+ "text_l",
+ "mt5xl",
+ "bert",
+];
+// ComfyUI sampler / scheduler names (comfy/samplers.py) that have a Studio equivalent.
+const COMFY_SAMPLER_IDS: Record<string, string> = {
+ euler: "euler",
+ euler_ancestral: "euler_a",
+ dpmpp_2m: "dpmpp_2m",
+ dpmpp_2m_sde: "dpmpp_2m_sde",
+};
+const COMFY_SCHEDULE_IDS: Record<string, string> = {
+ karras: "karras",
+ exponential: "exponential",
+};
+
+/** Settings from a ComfyUI API graph; wired inputs (`[id, slot]`) are followed a few hops. */
+export function parseComfyPrompt(text: string): ImportedRecipe | null {
+ let graph: ComfyGraph;
+ try {
+ const parsed: unknown = JSON.parse(text);
+ if (
+ typeof parsed !== "object" ||
+ parsed === null ||
+ Array.isArray(parsed)
+ ) {
+ return null;
+ }
+ graph = parsed as ComfyGraph;
+ } catch {
+ return null;
+ }
+ const node = (link: unknown) =>
+ Array.isArray(link) &&
+ (typeof link[0] === "string" || typeof link[0] === "number")
+ ? graph[String(link[0])]
+ : undefined;
+ const value = (v: unknown, keys: string[], depth = 0): unknown => {
+ const linked = node(v);
+ if (!linked) {
+ return v;
+ }
+ if (depth > 4) {
+ return undefined;
+ }
+ for (const key of keys) {
+ if (linked.inputs && key in linked.inputs) {
+ return value(linked.inputs[key], keys, depth + 1);
+ }
+ }
+ return undefined;
+ };
+ // Flux graphs put FluxGuidance between the text encoder and the sampler.
+ let fluxGuidance: unknown;
+ const textOf = (link: unknown): string | undefined => {
+ let n = node(link);
+ for (let hop = 0; n?.class_type === "FluxGuidance" && hop < 4; hop++) {
+ fluxGuidance ??= value(n.inputs?.guidance, ["guidance", "value"]);
+ n = node(n.inputs?.conditioning);
+ }
+ if (n?.class_type === "CLIPTextEncodeFlux") {
+ fluxGuidance ??= value(n.inputs?.guidance, ["guidance", "value"]);
+ }
+ for (const key of COMFY_TEXT_INPUTS) {
+ const v = value(n?.inputs?.[key], [key, "text", "value", "string"]);
+ if (typeof v === "string" && v.trim()) return v;
+ }
+ const v = value(n?.inputs?.text, ["text", "value", "string"]);
+ return typeof v === "string" ? v : undefined;
+ };
+ const sampler = Object.values(graph).find(
+ (n) =>
+ typeof n?.class_type === "string" && COMFY_SAMPLERS.has(n.class_type),
+ );
+ if (!sampler?.inputs) {
+ return null;
+ }
+ let inputs = sampler.inputs;
+ if (sampler.class_type === "SamplerCustomAdvanced") {
+ const guider = node(inputs.guider)?.inputs ?? {};
+ const sigmas = node(inputs.sigmas)?.inputs ?? {};
+ inputs = {
+ positive: guider.positive ?? guider.conditioning,
+ negative: guider.negative,
+ cfg: guider.cfg,
+ model: guider.model,
+ noise_seed: node(inputs.noise)?.inputs?.noise_seed,
+ steps: sigmas.steps,
+ scheduler: sigmas.scheduler,
+ denoise: sigmas.denoise,
+ sampler_name: node(inputs.sampler)?.inputs?.sampler_name,
+ latent_image: inputs.latent_image,
+ };
+ }
+ const out: ImportedRecipe = { prompt: textOf(inputs.positive) ?? "" };
+ const negative = textOf(inputs.negative);
+ if (negative !== undefined) out.negative_prompt = negative;
+ const seed = value(inputs.seed ?? inputs.noise_seed, [
+ "seed",
+ "noise_seed",
+ "value",
+ ]);
+ if (typeof seed === "number") out.seed = seed;
+ const steps = value(inputs.steps, ["steps", "value"]);
+ if (typeof steps === "number") out.steps = steps;
+ const cfg = value(inputs.cfg, ["cfg", "value"]);
+ if (typeof fluxGuidance === "number") out.guidance = fluxGuidance;
+ else if (typeof cfg === "number") out.guidance = cfg;
+ // denoise < 1 re-noises an encoded source: img2img at that strength.
+ const denoise = value(inputs.denoise, ["denoise", "value"]);
+ if (typeof denoise === "number" && denoise > 0 && denoise < 1) {
+ out.strength = denoise;
+ out.workflow = "img2img";
+ }
+ const samplerName = value(inputs.sampler_name, ["sampler_name", "value"]);
+ const scheduler = value(inputs.scheduler, ["scheduler", "value"]);
+ // Unmapped samplers stay named; normal / simple have no exact Studio schedule, so stay automatic.
+ if (typeof samplerName === "string" && samplerName)
+ out.sampler = Object.hasOwn(COMFY_SAMPLER_IDS, samplerName)
+ ? COMFY_SAMPLER_IDS[samplerName]
+ : samplerName;
+ if (
+ typeof scheduler === "string" &&
+ Object.hasOwn(COMFY_SCHEDULE_IDS, scheduler)
+ )
+ out.schedule_type = COMFY_SCHEDULE_IDS[scheduler];
+ const latent = node(inputs.latent_image)?.inputs;
+ const width = value(latent?.width, ["width", "value"]);
+ const height = value(latent?.height, ["height", "value"]);
+ if (typeof width === "number" && typeof height === "number") {
+ out.width = width;
+ out.height = height;
+ }
+ let link: unknown = inputs.model;
+ for (let hop = 0; hop < 8; hop++) {
+ const n = node(link);
+ const name = COMFY_MODEL_INPUTS.map((k) => n?.inputs?.[k]).find(
+ (v) => typeof v === "string",
+ );
+ if (typeof name === "string") {
+ out.model = name;
+ break;
+ }
+ link = n?.inputs?.model;
+ }
+ return out;
+}
diff --git a/studio/frontend/src/features/images/lib/info-stamp.ts b/studio/frontend/src/features/images/lib/info-stamp.ts
new file mode 100644
index 00000000000..bd4531f3588
--- /dev/null
+++ b/studio/frontend/src/features/images/lib/info-stamp.ts
@@ -0,0 +1,129 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/** `Model | date time | Seed: N` bar on the exported copy only, so the stored file stays clean and
+ * re-exporting never stacks. */
+
+export interface StampSource {
+ model: string | null;
+ seed: number;
+ created_at: number;
+ // A Connection run sends no seed to its provider, so none is stamped.
+ model_kind?: string | null;
+}
+
+const BRAND = "Unsloth";
+const PATH_SEP = /[\\/]/;
+const GGUF_SUFFIX = /(\.gguf|-gguf)$/i;
+const FONT_FAMILY =
+ 'ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace';
+
+/** Repo or file basename without a trailing -GGUF: `unsloth/FLUX.2-klein-4B-GGUF` -> `FLUX.2-klein-4B`. */
+export function stampModelName(model: string | null | undefined): string {
+ const base = (model ?? "").trim().split(PATH_SEP).filter(Boolean).pop() ?? "";
+ return base.replace(GGUF_SUFFIX, "");
+}
+
+export function stampDateTime(epochSeconds: number): string {
+ const d = new Date(epochSeconds * 1000);
+ const p = (n: number) => String(n).padStart(2, "0");
+ return (
+ `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ` +
+ `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`
+ );
+}
+
+export function infoStampText(image: StampSource): string {
+ const parts = [
+ stampModelName(image.model),
+ stampDateTime(image.created_at),
+ image.model_kind === "connection" ? "" : `Seed: ${image.seed}`,
+ ];
+ return parts.filter(Boolean).join(" | ");
+}
+
+export interface StampContext {
+ font: string;
+ fillStyle: string | CanvasGradient | CanvasPattern;
+ textBaseline: CanvasTextBaseline;
+ textAlign: CanvasTextAlign;
+ fillRect(x: number, y: number, w: number, h: number): void;
+ fillText(text: string, x: number, y: number): void;
+ measureText(text: string): { width: number };
+}
+
+export interface StampLayout {
+ /** Shortened from the model, then the date, so the seed is never clipped. */
+ text: string;
+ fontPx: number;
+ barHeight: number;
+ padX: number;
+ showBrand: boolean;
+}
+
+/** Font scales with the short side; a long line shrinks to fit, dropping the brand first. */
+export function layoutInfoStamp(
+ ctx: StampContext,
+ width: number,
+ height: number,
+ text: string,
+): StampLayout {
+ let fontPx = Math.max(10, Math.round(Math.min(width, height) / 48));
+ const padX = Math.round(fontPx * 0.75);
+ const widthAt = (s: string, px: number) => {
+ ctx.font = `${px}px ${FONT_FAMILY}`;
+ return ctx.measureText(s).width;
+ };
+ const room = width - padX * 2;
+ const textWidth = widthAt(text, fontPx);
+ const showBrand = textWidth + fontPx * 2 + widthAt(BRAND, fontPx) <= room;
+ if (textWidth > room) {
+ fontPx = Math.max(6, Math.floor((fontPx * room) / textWidth));
+ }
+ let fitted = text;
+ if (widthAt(fitted, fontPx) > room) {
+ const parts = text.split(" | ");
+ const seed = parts.pop() ?? "";
+ while (parts.length > 0 && widthAt(fitted, fontPx) > room) {
+ const first = parts[0];
+ if (parts.length > 1 && first.length > 1) {
+ parts[0] = `${first.replace(/\u2026$/, "").slice(0, -1)}\u2026`;
+ if (parts[0] === "\u2026") parts.shift();
+ } else {
+ parts.shift();
+ }
+ fitted = [...parts, seed].join(" | ");
+ }
+ }
+ return {
+ text: fitted,
+ fontPx,
+ barHeight: Math.round(fontPx * 1.9),
+ padX,
+ showBrand,
+ };
+}
+
+export function drawInfoStamp(
+ ctx: StampContext,
+ width: number,
+ height: number,
+ text: string,
+): StampLayout {
+ const layout = layoutInfoStamp(ctx, width, height, text);
+ const top = height - layout.barHeight;
+ const mid = top + layout.barHeight / 2;
+ ctx.fillStyle = "rgba(0, 0, 0, 0.55)";
+ ctx.fillRect(0, top, width, layout.barHeight);
+ ctx.font = `${layout.fontPx}px ${FONT_FAMILY}`;
+ ctx.textBaseline = "middle";
+ ctx.fillStyle = "rgba(255, 255, 255, 0.92)";
+ ctx.textAlign = "left";
+ ctx.fillText(layout.text, layout.padX, mid);
+ if (layout.showBrand) {
+ ctx.fillStyle = "rgba(255, 255, 255, 0.7)";
+ ctx.textAlign = "right";
+ ctx.fillText(BRAND, width - layout.padX, mid);
+ }
+ return layout;
+}
diff --git a/studio/frontend/src/features/images/lib/sampler-choice.ts b/studio/frontend/src/features/images/lib/sampler-choice.ts
index b0ef28b3bfa..f0b59b87117 100644
--- a/studio/frontend/src/features/images/lib/sampler-choice.ts
+++ b/studio/frontend/src/features/images/lib/sampler-choice.ts
@@ -5,7 +5,7 @@
export const DEFAULT_SAMPLER = "default";
export const AUTOMATIC_SCHEDULE = "automatic";
-const SAMPLER_LABELS: Record<string, string> = {
+export const SAMPLER_LABELS: Record<string, string> = {
default: "Model default",
euler: "Euler",
euler_a: "Euler a",
diff --git a/studio/frontend/src/features/library/settings-store.ts b/studio/frontend/src/features/library/settings-store.ts
index 9e99576f67c..ee963fdc0e1 100644
--- a/studio/frontend/src/features/library/settings-store.ts
+++ b/studio/frontend/src/features/library/settings-store.ts
@@ -25,6 +25,7 @@ export interface LibrarySettings {
showGeneratedMedia: boolean;
showFineTunes: boolean;
confirmDelete: boolean;
+ imageInfoStamp: boolean;
}
export const DEFAULT_LIBRARY_SETTINGS: LibrarySettings = {
@@ -51,6 +52,7 @@ export const DEFAULT_LIBRARY_SETTINGS: LibrarySettings = {
showGeneratedMedia: true,
showFineTunes: true,
confirmDelete: true,
+ imageInfoStamp: true,
};
export const SUGGESTED_LIMITS = [20, 40, 80] as const;
diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.ts
index 667824637ee..90b6f78f5da 100644
--- a/studio/frontend/src/features/settings/settings-search.ts
+++ b/studio/frontend/src/features/settings/settings-search.ts
@@ -189,6 +189,7 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {
"settings.library.cardSize",
"settings.library.imageLayout",
"settings.library.showCardDates",
+ "settings.library.imageInfoStamp",
"settings.library.startTab",
"settings.library.sort",
"settings.library.suggestedLimit",
diff --git a/studio/frontend/src/features/settings/tabs/library-tab.tsx b/studio/frontend/src/features/settings/tabs/library-tab.tsx
index 947ba030956..062386d0bdb 100644
--- a/studio/frontend/src/features/settings/tabs/library-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/library-tab.tsx
@@ -430,6 +430,10 @@ export function LibraryTab() {
{toggle("showCardDates", "settings.library.showCardDates", "settings.library.showCardDatesDescription")}
</SettingsSection>
+ <SettingsSection title={t("settings.library.downloadsSection")}>
+ {toggle("imageInfoStamp", "settings.library.imageInfoStamp", "settings.library.imageInfoStampDescription")}
+ </SettingsSection>
+
<SettingsSection title={t("settings.library.browsingSection")}>
{choice("startTab", "settings.library.startTab", "settings.library.startTabDescription")}
{choice("sort", "settings.library.sort", "settings.library.sortDescription")}
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 8312391b8c9..43aa3ecba7c 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -1002,6 +1002,9 @@ export const ar = {
resetButton: "إعادة ضبط",
resetDone: "تمت إعادة ضبط إعدادات المكتبة",
storageSection: "التخزين",
+ downloadsSection: "تنزيلات الصور",
+ imageInfoStamp: "ختم المعلومات",
+ imageInfoStampDescription: "عرض النموذج والتاريخ والبذرة أسفل الصور التي تنزّلها من صفحة الصور. تُحفظ إعدادات التوليد داخل الملف في كلتا الحالتين.",
storageDescription: "افتح فئة لرؤية ملفاتها من الأكبر حجمًا، واحذف ما لم تعد تحتاجه.",
storageUsed: "تستخدم المكتبة {size}",
storageDisk: "{free} متاحة من {total} على هذا القرص",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index f7030d34d85..005650dce83 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -1007,6 +1007,9 @@ export const de = {
resetButton: "Zurücksetzen",
resetDone: "Bibliothekseinstellungen zurückgesetzt",
storageSection: "Speicher",
+ downloadsSection: "Bild-Downloads",
+ imageInfoStamp: "Info-Stempel",
+ imageInfoStampDescription: "Zeigt Modell, Datum und Seed am unteren Rand von Bildern, die Sie auf der Seite Bilder herunterladen. Die Generierungseinstellungen werden in jedem Fall in der Datei gespeichert.",
storageDescription: "Öffne eine Kategorie, um ihre Dateien nach Größe zu sehen, und lösche, was du nicht mehr brauchst.",
storageUsed: "{size} von der Bibliothek belegt",
storageDisk: "{free} frei von {total} auf diesem Laufwerk",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 3cf7dba1f0e..89315b3084d 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -1060,6 +1060,9 @@ export const en = {
resetButton: "Reset",
resetDone: "Library settings reset",
storageSection: "Storage",
+ downloadsSection: "Image downloads",
+ imageInfoStamp: "Info stamp",
+ imageInfoStampDescription: "Show the model, date and seed along the bottom of images you download from the Images page. The generation settings are saved inside the file either way.",
storageDescription: "Open a category to see its files largest first, and delete what you no longer need.",
storageUsed: "{size} used by the Library",
storageDisk: "{free} free of {total} on this disk",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index f5cf1a8ca44..51770b85475 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -1006,6 +1006,9 @@ export const es = {
resetButton: "Restablecer",
resetDone: "Ajustes de la Biblioteca restablecidos",
storageSection: "Almacenamiento",
+ downloadsSection: "Descargas de imágenes",
+ imageInfoStamp: "Sello de información",
+ imageInfoStampDescription: "Muestra el modelo, la fecha y la semilla en la parte inferior de las imágenes que descargas desde la página Imágenes. Los ajustes de generación se guardan dentro del archivo en cualquier caso.",
storageDescription: "Abre una categoría para ver sus archivos de mayor a menor y elimina lo que ya no necesites.",
storageUsed: "{size} usados por la Biblioteca",
storageDisk: "{free} libres de {total} en este disco",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index b5fc6e6740b..a4124dfe2c0 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -1007,6 +1007,9 @@ export const fr = {
resetButton: "Réinitialiser",
resetDone: "Réglages de la Bibliothèque réinitialisés",
storageSection: "Stockage",
+ downloadsSection: "Téléchargements d'images",
+ imageInfoStamp: "Tampon d'informations",
+ imageInfoStampDescription: "Affiche le modèle, la date et la graine en bas des images téléchargées depuis la page Images. Les paramètres de génération sont enregistrés dans le fichier dans tous les cas.",
storageDescription: "Ouvrez une catégorie pour voir ses fichiers du plus lourd au plus léger et supprimez ce dont vous n'avez plus besoin.",
storageUsed: "{size} utilisés par la Bibliothèque",
storageDisk: "{free} libres sur {total} sur ce disque",
diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.ts
index bc04d40be61..4093b713e9b 100644
--- a/studio/frontend/src/i18n/locales/he.ts
+++ b/studio/frontend/src/i18n/locales/he.ts
@@ -1086,6 +1086,9 @@ export const he = {
resetButton: "איפוס",
resetDone: "הגדרות הספרייה אופסו",
storageSection: "אחסון",
+ downloadsSection: "הורדות תמונות",
+ imageInfoStamp: "חותמת מידע",
+ imageInfoStampDescription: "הצגת המודל, התאריך וה-seed בתחתית התמונות שמורידים מדף התמונות. הגדרות היצירה נשמרות בתוך הקובץ בכל מקרה.",
storageDescription:
"פתח קטגוריה כדי לראות את הקבצים שלה מהגדול לקטן, ומחק את מה שאינך צריך עוד.",
storageUsed: "{size} בשימוש הספרייה",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 0e4b1a8bdfb..c7bb29c1ac3 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -1006,6 +1006,9 @@ export const hi = {
resetButton: "रीसेट",
resetDone: "लाइब्रेरी सेटिंग्स रीसेट हो गईं",
storageSection: "स्टोरेज",
+ downloadsSection: "इमेज डाउनलोड",
+ imageInfoStamp: "जानकारी स्टैम्प",
+ imageInfoStampDescription: "Images पेज से डाउनलोड की गई इमेज के नीचे मॉडल, तारीख और सीड दिखाएँ। जनरेशन सेटिंग्स हर हाल में फ़ाइल के अंदर सहेजी जाती हैं।",
storageDescription: "किसी श्रेणी को खोलकर उसकी फ़ाइलें सबसे बड़ी से देखें, और जो ज़रूरी नहीं है उसे हटाएं।",
storageUsed: "लाइब्रेरी {size} इस्तेमाल कर रही है",
storageDisk: "इस डिस्क पर {total} में से {free} खाली",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index e5db6ec894e..b178da831bd 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -910,6 +910,9 @@ export const it = {
resetButton: "Reimposta",
resetDone: "Impostazioni della Libreria reimpostate",
storageSection: "Spazio",
+ downloadsSection: "Download delle immagini",
+ imageInfoStamp: "Timbro informativo",
+ imageInfoStampDescription: "Mostra modello, data e seed in fondo alle immagini scaricate dalla pagina Immagini. Le impostazioni di generazione vengono salvate nel file in ogni caso.",
storageDescription: "Apri una categoria per vedere i file dal più grande e elimina ciò che non ti serve più.",
storageUsed: "{size} usati dalla Libreria",
storageDisk: "{free} liberi su {total} in questo disco",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 2a356dc051c..6711b4ad3c3 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -1004,6 +1004,9 @@ export const ja = {
resetButton: "リセット",
resetDone: "ライブラリ設定をリセットしました",
storageSection: "ストレージ",
+ downloadsSection: "画像のダウンロード",
+ imageInfoStamp: "情報スタンプ",
+ imageInfoStampDescription: "画像ページからダウンロードした画像の下部にモデル、日時、シードを表示します。生成設定はどちらの場合もファイル内に保存されます。",
storageDescription: "カテゴリを開くとファイルがサイズの大きい順に表示されます。不要なものを削除できます。",
storageUsed: "ライブラリの使用量 {size}",
storageDisk: "このディスクの空き容量 {free} / {total}",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 0c107c6b205..4a5df53d164 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -1002,6 +1002,9 @@ export const ko = {
resetButton: "초기화",
resetDone: "라이브러리 설정을 초기화했습니다",
storageSection: "저장 공간",
+ downloadsSection: "이미지 다운로드",
+ imageInfoStamp: "정보 스탬프",
+ imageInfoStampDescription: "이미지 페이지에서 다운로드한 이미지 하단에 모델, 날짜, 시드를 표시합니다. 생성 설정은 어느 경우든 파일 안에 저장됩니다.",
storageDescription: "카테고리를 열면 파일이 큰 순서로 표시되며, 필요 없는 파일을 삭제할 수 있습니다.",
storageUsed: "라이브러리 사용량 {size}",
storageDisk: "이 디스크의 여유 공간 {free} / {total}",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 6a127e59aff..bc055725be6 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -1005,6 +1005,9 @@ export const ptBR = {
resetButton: "Redefinir",
resetDone: "Configurações da Biblioteca redefinidas",
storageSection: "Armazenamento",
+ downloadsSection: "Downloads de imagens",
+ imageInfoStamp: "Selo de informações",
+ imageInfoStampDescription: "Mostra o modelo, a data e a seed na parte inferior das imagens baixadas pela página Imagens. As configurações de geração são salvas dentro do arquivo de qualquer forma.",
storageDescription: "Abra uma categoria para ver os arquivos do maior para o menor e exclua o que não precisa mais.",
storageUsed: "{size} usados pela Biblioteca",
storageDisk: "{free} livres de {total} neste disco",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 56a4bd04ac7..b3319bb31fa 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -1005,6 +1005,9 @@ export const ru = {
resetButton: "Сбросить",
resetDone: "Настройки Библиотеки сброшены",
storageSection: "Хранилище",
+ downloadsSection: "Загрузка изображений",
+ imageInfoStamp: "Информационный штамп",
+ imageInfoStampDescription: "Показывать модель, дату и сид внизу изображений, скачанных на странице «Изображения». Параметры генерации в любом случае сохраняются внутри файла.",
storageDescription: "Откройте категорию, чтобы увидеть файлы от самых больших, и удалите ненужное.",
storageUsed: "Библиотека занимает {size}",
storageDisk: "Свободно {free} из {total} на этом диске",
diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.ts
index 676e90315f6..caebe3164d6 100644
--- a/studio/frontend/src/i18n/locales/sv.ts
+++ b/studio/frontend/src/i18n/locales/sv.ts
@@ -1112,6 +1112,9 @@ export const sv = {
resetButton: "Återställ",
resetDone: "Biblioteksinställningarna har återställts",
storageSection: "Lagring",
+ downloadsSection: "Bildnedladdningar",
+ imageInfoStamp: "Infostämpel",
+ imageInfoStampDescription: "Visa modell, datum och seed längst ned på bilder du laddar ned från sidan Bilder. Genereringsinställningarna sparas i filen oavsett.",
storageDescription:
"Öppna en kategori för att se dess filer med de största först och ta bort det du inte längre behöver.",
storageUsed: "{size} används av biblioteket",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index d8fafac444d..159dea2cc40 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -1000,6 +1000,9 @@ export const zhCN = {
resetButton: "重置",
resetDone: "资料库设置已重置",
storageSection: "存储空间",
+ downloadsSection: "图片下载",
+ imageInfoStamp: "信息水印",
+ imageInfoStampDescription: "在从图片页面下载的图片底部显示模型、日期和种子。无论是否开启,生成设置都会保存在文件中。",
storageDescription: "打开一个类别即可按大小从大到小查看文件,并删除不再需要的内容。",
storageUsed: "资料库已使用 {size}",
storageDisk: "此磁盘可用 {free},共 {total}",
diff --git a/studio/frontend/tests/image-info-stamp.test.ts b/studio/frontend/tests/image-info-stamp.test.ts
new file mode 100644
index 00000000000..2fe4930fc85
--- /dev/null
+++ b/studio/frontend/tests/image-info-stamp.test.ts
@@ -0,0 +1,109 @@
+// 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 {
+ drawInfoStamp,
+ infoStampText,
+ layoutInfoStamp,
+ stampModelName,
+ type StampContext,
+} from "../src/features/images/lib/info-stamp.ts";
+
+function fakeContext() {
+ const calls: { op: string; args: unknown[] }[] = [];
+ const ctx: StampContext = {
+ font: "",
+ fillStyle: "",
+ textBaseline: "alphabetic",
+ textAlign: "start",
+ fillRect: (...args) => calls.push({ op: "fillRect", args }),
+ fillText: (...args) => calls.push({ op: "fillText", args }),
+ // Monospace-ish: 0.6 em per character.
+ measureText(text: string) {
+ const px = Number.parseFloat(this.font);
+ return { width: text.length * px * 0.6 };
+ },
+ };
+ return { ctx, calls };
+}
+
+test("model name is the repo basename without the GGUF suffix", () => {
+ assert.equal(
+ stampModelName("unsloth/FLUX.2-klein-4B-GGUF"),
+ "FLUX.2-klein-4B",
+ );
+ assert.equal(stampModelName("Tongyi-MAI/Z-Image-Turbo"), "Z-Image-Turbo");
+ assert.equal(
+ stampModelName("C:\\models\\z-image-Q4_K_M.gguf"),
+ "z-image-Q4_K_M",
+ );
+ assert.equal(stampModelName(null), "");
+});
+
+test("stamp text is model, local date time and seed", () => {
+ const created = new Date(2026, 7, 9, 13, 1, 25).getTime() / 1000;
+ assert.equal(
+ infoStampText({
+ model: "unsloth/FLUX.2-klein-4B-GGUF",
+ seed: 6630007,
+ created_at: created,
+ }),
+ "FLUX.2-klein-4B | 2026-08-09 13:01:25 | Seed: 6630007",
+ );
+ assert.equal(
+ infoStampText({ model: null, seed: 7, created_at: created }),
+ "2026-08-09 13:01:25 | Seed: 7",
+ );
+});
+
+test("a typical 1024 image gets the full line plus the brand on a bottom bar", () => {
+ const { ctx, calls } = fakeContext();
+ const text = "FLUX.2-klein-4B | 2026-08-09 13:01:25 | Seed: 6630007";
+ const layout = drawInfoStamp(ctx, 1024, 1024, text);
+ assert.equal(layout.showBrand, true);
+ const bar = calls.find((c) => c.op === "fillRect");
+ assert.deepEqual(bar?.args, [
+ 0,
+ 1024 - layout.barHeight,
+ 1024,
+ layout.barHeight,
+ ]);
+ const texts = calls.filter((c) => c.op === "fillText").map((c) => c.args[0]);
+ assert.deepEqual(texts, [text, "Unsloth"]);
+});
+
+test("a narrow image drops the brand and shrinks the line to fit", () => {
+ const { ctx } = fakeContext();
+ const text = "Qwen-Image-Edit-2509 | 2026-08-09 13:01:25 | Seed: 1234567890";
+ const layout = layoutInfoStamp(ctx, 256, 256, text);
+ assert.equal(layout.showBrand, false);
+ ctx.font = `${layout.fontPx}px monospace`;
+ assert.ok(ctx.measureText(text).width <= 256 - layout.padX * 2);
+});
+
+test("a stamp too long for a narrow image shortens the model, then the date, never the seed", () => {
+ const { ctx, calls } = fakeContext();
+ const text = "Qwen-Image-Edit-2511-a-very-long-community-merge-name | 2026-10-15 03:15:47 | Seed: 156680208700286";
+ const layout = drawInfoStamp(ctx, 256, 256, text);
+ assert.equal(layout.fontPx, 6);
+ const room = 256 - layout.padX * 2;
+ assert.ok(layout.text.length * 6 * 0.6 <= room, layout.text);
+ assert.ok(layout.text.endsWith("Seed: 156680208700286"), layout.text);
+ assert.ok(layout.text.includes("…") || !layout.text.includes("Qwen"), layout.text);
+ const drawn = calls.find((c) => c.op === "fillText");
+ assert.equal(drawn?.args[0], layout.text);
+ // Narrower still: the date goes too, the seed stays.
+ const tiny = layoutInfoStamp(ctx, 120, 120, text);
+ assert.ok(tiny.text.endsWith("Seed: 156680208700286"), tiny.text);
+ // A stamp that fits is drawn unchanged.
+ assert.equal(layoutInfoStamp(ctx, 1024, 1024, "m | 2026-10-15 03:15:47 | Seed: 1").text, "m | 2026-10-15 03:15:47 | Seed: 1");
+});
+
+test("a Connection image is stamped without a seed", () => {
+ const text = infoStampText({ model: "openai/gpt-image-1", seed: 42, created_at: 0, model_kind: "connection" });
+ assert.ok(!text.includes("Seed"), text);
+ assert.ok(infoStampText({ model: "m", seed: 42, created_at: 0 }).endsWith("Seed: 42"));
+});
diff --git a/studio/frontend/tests/image-metadata.test.ts b/studio/frontend/tests/image-metadata.test.ts
new file mode 100644
index 00000000000..f232ea3c2da
--- /dev/null
+++ b/studio/frontend/tests/image-metadata.test.ts
@@ -0,0 +1,862 @@
+// 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 {
+ buildExif,
+ copyPngTextChunks,
+ importedRecipe,
+ parseA1111Parameters,
+ parseComfyPrompt,
+ pngTextChunks,
+ APPLIED_RECIPE_KEYS,
+ INFO_RECIPE_KEYS,
+ newerRecipeSchema,
+ readEmbeddedRecipe,
+ recipeSettings,
+ unknownRecipeKeys,
+ withJpegExif,
+ withWebpExif,
+} from "../src/features/images/lib/image-metadata.ts";
+import { readSrc } from "./helpers/kit.ts";
+
+// 8x8 files written by Pillow: a JFIF JPEG, a simple lossy WebP and a lossless WebP.
+const JPEG_B64 =
+ "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAIAAgDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwCzRRRXwR9sf//Z";
+const WEBP_LOSSY_B64 =
+ "UklGRjoAAABXRUJQVlA4IC4AAADQAQCdASoIAAgAAUAmJaACdLoB+AADsAD+pNf/TSPGkeNI+Yt/84ljqd3aAAAA";
+const WEBP_LOSSLESS_B64 =
+ "UklGRh4AAABXRUJQVlA4TBEAAAAvB8ABAAdQvCIXpf+BiOh/AAA=";
+
+const bytes = (b64: string) => new Uint8Array(Buffer.from(b64, "base64"));
+
+const RECIPE = JSON.stringify({
+ prompt: "a sloth hiking, 日本語 ok",
+ negative_prompt: "blurry",
+ width: 1024,
+ height: 768,
+ steps: 4,
+ guidance: 1,
+ seed: 6630007,
+ batch_seed: 6630007,
+ batch_size: 1,
+ model: "unsloth/FLUX.2-klein-4B-GGUF",
+ workflow: "txt2img",
+ loras: ["sloth-style:0.8"],
+});
+const PARAMETERS =
+ "a sloth hiking, 日本語 ok\nNegative prompt: blurry\nSteps: 4, CFG scale: 1.0, Seed: 6630007, Size: 1024x768, Model: unsloth/FLUX.2-klein-4B-GGUF";
+
+function chunk(type: string, data: number[] = []): number[] {
+ const len = data.length;
+ return [
+ len >>> 24,
+ (len >>> 16) & 255,
+ (len >>> 8) & 255,
+ len & 255,
+ ...[...type].map((c) => c.charCodeAt(0)),
+ ...data,
+ 1,
+ 2,
+ 3,
+ 4,
+ ];
+}
+const latin1 = (s: string) => [...s].map((c) => c.charCodeAt(0));
+const utf8 = (s: string) => [...new TextEncoder().encode(s)];
+function png(...chunks: number[][]): Uint8Array<ArrayBuffer> {
+ return new Uint8Array([
+ 0x89,
+ 0x50,
+ 0x4e,
+ 0x47,
+ 0x0d,
+ 0x0a,
+ 0x1a,
+ 0x0a,
+ ...chunks.flat(),
+ ]);
+}
+function chunkTypes(p: Uint8Array): string[] {
+ const types: string[] = [];
+ let at = 8;
+ while (at < p.length) {
+ const len =
+ (p[at] << 24) | (p[at + 1] << 16) | (p[at + 2] << 8) | p[at + 3];
+ types.push(String.fromCharCode(...p.subarray(at + 4, at + 8)));
+ at += 12 + len;
+ }
+ return types;
+}
+
+// Pillow writes tEXt for Latin-1 text and an uncompressed iTXt for anything else.
+const galleryPng = () =>
+ png(
+ chunk("IHDR", [0, 0, 0, 1]),
+ chunk("iTXt", [...latin1("unsloth\0\0\0\0\0"), ...utf8(RECIPE)]),
+ chunk("iTXt", [...latin1("parameters\0\0\0\0\0"), ...utf8(PARAMETERS)]),
+ chunk("IDAT", [9]),
+ chunk("IEND"),
+ );
+
+test("PNG text chunks read back, tEXt and uncompressed iTXt", () => {
+ const p = png(
+ chunk("IHDR"),
+ chunk("tEXt", latin1("parameters\0a sloth")),
+ chunk("IEND"),
+ );
+ assert.deepEqual(pngTextChunks(p), { parameters: "a sloth" });
+ assert.deepEqual(readEmbeddedRecipe(galleryPng()), {
+ recipe: RECIPE,
+ parameters: PARAMETERS,
+ });
+});
+
+test("a re-encoded PNG keeps the original's recipe chunks, once", () => {
+ const canvasPng = png(
+ chunk("IHDR", [0, 0, 0, 2]),
+ chunk("IDAT", [7]),
+ chunk("IEND"),
+ );
+ const once = copyPngTextChunks(galleryPng(), canvasPng);
+ assert.deepEqual(chunkTypes(once), ["IHDR", "iTXt", "iTXt", "IDAT", "IEND"]);
+ assert.deepEqual(readEmbeddedRecipe(once), {
+ recipe: RECIPE,
+ parameters: PARAMETERS,
+ });
+ assert.deepEqual(copyPngTextChunks(galleryPng(), once), once);
+ assert.equal(
+ copyPngTextChunks(new Uint8Array([1, 2, 3]), canvasPng),
+ canvasPng,
+ );
+});
+
+test("JPEG export carries the recipe as EXIF after the JFIF header, idempotently", () => {
+ const jpeg = bytes(JPEG_B64);
+ const out = withJpegExif(jpeg, { recipe: RECIPE, parameters: PARAMETERS });
+ assert.deepEqual(
+ [...out.subarray(0, 4)],
+ [0xff, 0xd8, 0xff, 0xe0],
+ "SOI then APP0",
+ );
+ const app0End = 4 + ((out[4] << 8) | out[5]);
+ assert.deepEqual(
+ [...out.subarray(app0End, app0End + 2)],
+ [0xff, 0xe1],
+ "EXIF right after APP0",
+ );
+ assert.deepEqual(readEmbeddedRecipe(out), {
+ recipe: RECIPE,
+ parameters: PARAMETERS,
+ });
+ assert.ok(
+ Buffer.from(out).subarray(-200).equals(Buffer.from(jpeg).subarray(-200)),
+ );
+ assert.deepEqual(
+ withJpegExif(out, { recipe: RECIPE, parameters: PARAMETERS }),
+ out,
+ );
+});
+
+test("a recipe too big for one JPEG segment keeps the parameters text", () => {
+ const huge = JSON.stringify({ prompt: "x".repeat(70_000) });
+ const out = withJpegExif(bytes(JPEG_B64), {
+ recipe: huge,
+ parameters: PARAMETERS,
+ });
+ assert.deepEqual(readEmbeddedRecipe(out), { parameters: PARAMETERS });
+});
+
+for (const [name, b64] of [
+ ["lossy", WEBP_LOSSY_B64],
+ ["lossless", WEBP_LOSSLESS_B64],
+] as const) {
+ test(`WebP (${name}) export becomes VP8X with an EXIF chunk`, () => {
+ const out = withWebpExif(
+ bytes(b64),
+ { recipe: RECIPE, parameters: PARAMETERS },
+ 8,
+ 8,
+ );
+ const text = Buffer.from(out).toString("latin1");
+ assert.equal(text.slice(12, 16), "VP8X");
+ assert.equal(out[20] & 0x08, 0x08, "EXIF flag");
+ assert.equal(
+ new DataView(out.buffer).getUint32(4, true),
+ out.length - 8,
+ "RIFF size",
+ );
+ assert.equal(
+ (out[24] | (out[25] << 8) | (out[26] << 16)) + 1,
+ 8,
+ "canvas width",
+ );
+ assert.deepEqual(readEmbeddedRecipe(out), {
+ recipe: RECIPE,
+ parameters: PARAMETERS,
+ });
+ assert.deepEqual(
+ withWebpExif(out, { recipe: RECIPE, parameters: PARAMETERS }, 8, 8),
+ out,
+ );
+ });
+}
+
+test("EXIF is big-endian with UNICODE UserComment, as piexif writes it", () => {
+ const tiff = buildExif({ parameters: "hi" });
+ assert.ok(tiff);
+ assert.deepEqual([...tiff.subarray(0, 4)], [0x4d, 0x4d, 0, 0x2a]);
+ const text = Buffer.from(tiff).toString("latin1");
+ assert.ok(text.includes("UNICODE\0\0h\0i"));
+ assert.equal(buildExif({}), null);
+});
+
+test("AUTOMATIC1111 parameters parse into settings", () => {
+ const parsed = parseA1111Parameters(
+ 'masterpiece, a cat\nwearing a hat\nNegative prompt: lowres, bad hands\nSteps: 28, Sampler: DPM++ 2M, Schedule type: Karras, CFG scale: 6.5, Seed: 1234567890, Size: 832x1216, Model hash: abc, Model: sdxl_base, Lora hashes: "a: 1, b: 2", Version: v1.10.1',
+ );
+ assert.deepEqual(parsed, {
+ prompt: "masterpiece, a cat\nwearing a hat",
+ negative_prompt: "lowres, bad hands",
+ steps: 28,
+ guidance: 6.5,
+ seed: 1234567890,
+ width: 832,
+ height: 1216,
+ model: "sdxl_base",
+ sampler: "dpmpp_2m",
+ schedule_type: "karras",
+ });
+ assert.equal(
+ parseA1111Parameters("just a caption")?.prompt,
+ "just a caption",
+ );
+});
+
+test("Unsloth's recipe wins over the parameters text; neither gives null", () => {
+ assert.equal(
+ importedRecipe({ recipe: RECIPE, parameters: "other\nSteps: 1" })?.prompt,
+ "a sloth hiking, 日本語 ok",
+ );
+ assert.equal(
+ importedRecipe({ recipe: "{not json", parameters: PARAMETERS })?.steps,
+ 4,
+ );
+ assert.equal(importedRecipe({}), null);
+ assert.equal(importedRecipe({ recipe: "[1,2]" }), null);
+});
+
+test("restorable settings are type-checked and fall back to the form's values", () => {
+ const defaults = { width: 1024, height: 1024, steps: 8, guidance: 3.5 };
+ const hostile = recipeSettings(
+ {
+ prompt: "p",
+ width: "9999",
+ steps: 2.5,
+ guidance: Number.NaN,
+ seed: "1",
+ loras: [1, "a:1"],
+ batch_size: 0,
+ },
+ defaults,
+ );
+ assert.equal(hostile.width, 1024);
+ assert.equal(hostile.steps, 8);
+ assert.equal(hostile.guidance, 3.5);
+ assert.equal(hostile.seed, null);
+ assert.deepEqual(hostile.loras, ["a:1"]);
+ assert.equal(hostile.batch_size, 1);
+ const full = recipeSettings(JSON.parse(RECIPE), defaults);
+ assert.equal(full.seed, 6630007);
+ assert.equal(full.height, 768);
+ assert.deepEqual(full.loras, ["sloth-style:0.8"]);
+});
+
+test("the Images page wires downloads, the stamp setting and import", () => {
+ const page = readSrc("features/images/images-page.tsx");
+ for (const format of ["png", "jpeg", "webp"]) {
+ assert.ok(
+ page.includes(`downloadImage(selected, "${format}", selectedSrc)`),
+ format,
+ );
+ }
+ assert.match(page, /useLibrarySettingsStore\.getState\(\)\.imageInfoStamp/);
+ assert.match(
+ page,
+ /\(image: GalleryImage\) => downloadImage\(image, "png", srcById\[image\.id\]\)/,
+ );
+ assert.match(
+ page,
+ /onImportFromImage=\{\(\) => importFileRef\.current\?\.click\(\)\}/,
+ );
+ assert.match(page, /onDrop=\{onImportDrop\}/);
+ const store = readSrc("features/library/settings-store.ts");
+ assert.match(store, /imageInfoStamp: true,/);
+});
+
+// ComfyUI's default text-to-image graph from its `prompt` chunk, seed wired through a primitive.
+const COMFY_PROMPT = JSON.stringify({
+ "3": {
+ class_type: "KSampler",
+ inputs: {
+ seed: ["10", 0],
+ steps: 20,
+ cfg: 8,
+ sampler_name: "euler",
+ scheduler: "normal",
+ denoise: 1,
+ model: ["4", 0],
+ positive: ["6", 0],
+ negative: ["7", 0],
+ latent_image: ["5", 0],
+ },
+ },
+ "4": {
+ class_type: "CheckpointLoaderSimple",
+ inputs: { ckpt_name: "v1-5-pruned-emaonly.safetensors" },
+ },
+ "5": {
+ class_type: "EmptyLatentImage",
+ inputs: { width: 512, height: 768, batch_size: 1 },
+ },
+ "6": {
+ class_type: "CLIPTextEncode",
+ inputs: { text: "beautiful scenery nature glass bottle", clip: ["4", 1] },
+ },
+ "7": {
+ class_type: "CLIPTextEncode",
+ inputs: { text: "text, watermark", clip: ["4", 1] },
+ },
+ "8": {
+ class_type: "VAEDecode",
+ inputs: { samples: ["3", 0], vae: ["4", 2] },
+ },
+ "9": {
+ class_type: "SaveImage",
+ inputs: { filename_prefix: "ComfyUI", images: ["8", 0] },
+ },
+ "10": { class_type: "PrimitiveInt", inputs: { value: 156680208700286 } },
+});
+
+test("a ComfyUI PNG imports its prompt, seed, steps, CFG, size and checkpoint", () => {
+ const comfyPng = png(
+ chunk("IHDR"),
+ chunk("tEXt", latin1(`prompt\0${COMFY_PROMPT}`)),
+ chunk("tEXt", latin1('workflow\0{"nodes":[]}')),
+ chunk("IEND"),
+ );
+ const embedded = readEmbeddedRecipe(comfyPng);
+ assert.equal(embedded.comfyPrompt, COMFY_PROMPT);
+ assert.deepEqual(importedRecipe(embedded), {
+ prompt: "beautiful scenery nature glass bottle",
+ negative_prompt: "text, watermark",
+ seed: 156680208700286,
+ steps: 20,
+ guidance: 8,
+ sampler: "euler",
+ width: 512,
+ height: 768,
+ model: "v1-5-pruned-emaonly.safetensors",
+ });
+ assert.equal(
+ parseComfyPrompt('{"1":{"class_type":"SaveImage","inputs":{}}}'),
+ null,
+ );
+ assert.equal(parseComfyPrompt("not json"), null);
+ assert.equal(
+ importedRecipe({ recipe: RECIPE, comfyPrompt: COMFY_PROMPT })?.steps,
+ 4,
+ );
+});
+
+// Written by Pillow the way ComfyUI's WebP save nodes do (comfy_api/latest/_ui.py
+// _create_webp_metadata): IFD0 Model = `prompt:{graph}`, Make = `workflow:{...}`, no Exif IFD.
+const COMFY_WEBP_B64 =
+ "UklGRvACAABXRUJQVlA4WAoAAAAIAAAABwAABwAAVlA4TBEAAAAvB8ABAAdQniKXov+BiOh/AABFWElGuAIAAE1NAC" +
+ "oAAAAIAAIBDwACAAAAFwAAACYBEAACAAACeQAAAD4AAAAAd29ya2Zsb3c6eyJub2RlcyI6IFtdfQAAcHJvbXB0Onsi" +
+ "MyI6IHsiY2xhc3NfdHlwZSI6ICJLU2FtcGxlciIsICJpbnB1dHMiOiB7InNlZWQiOiA0MiwgInN0ZXBzIjogMjUsIC" +
+ "JjZmciOiA3LjAsICJzYW1wbGVyX25hbWUiOiAiZXVsZXJfYW5jZXN0cmFsIiwgInNjaGVkdWxlciI6ICJrYXJyYXMi" +
+ "LCAiZGVub2lzZSI6IDEuMCwgIm1vZGVsIjogWyI0IiwgMF0sICJwb3NpdGl2ZSI6IFsiNiIsIDBdLCAibmVnYXRpdm" +
+ "UiOiBbIjciLCAwXSwgImxhdGVudF9pbWFnZSI6IFsiNSIsIDBdfX0sICI0IjogeyJjbGFzc190eXBlIjogIkNoZWNr" +
+ "cG9pbnRMb2FkZXJTaW1wbGUiLCAiaW5wdXRzIjogeyJja3B0X25hbWUiOiAic2RfeGxfYmFzZV8xLjAuc2FmZXRlbn" +
+ "NvcnMifX0sICI1IjogeyJjbGFzc190eXBlIjogIkVtcHR5TGF0ZW50SW1hZ2UiLCAiaW5wdXRzIjogeyJ3aWR0aCI6" +
+ "IDEwMjQsICJoZWlnaHQiOiAxMDI0LCAiYmF0Y2hfc2l6ZSI6IDF9fSwgIjYiOiB7ImNsYXNzX3R5cGUiOiAiQ0xJUF" +
+ "RleHRFbmNvZGUiLCAiaW5wdXRzIjogeyJ0ZXh0IjogImEgcmVkIGZveCIsICJjbGlwIjogWyI0IiwgMV19fSwgIjci" +
+ "OiB7ImNsYXNzX3R5cGUiOiAiQ0xJUFRleHRFbmNvZGUiLCAiaW5wdXRzIjogeyJ0ZXh0IjogImJsdXJyeSIsICJjbG" +
+ "lwIjogWyI0IiwgMV19fX0AAA==";
+
+test("a ComfyUI WebP imports its graph from EXIF Model, with sampler and schedule", () => {
+ const embedded = readEmbeddedRecipe(bytes(COMFY_WEBP_B64));
+ assert.ok(embedded.comfyPrompt?.startsWith("{"));
+ assert.deepEqual(importedRecipe(embedded), {
+ prompt: "a red fox",
+ negative_prompt: "blurry",
+ seed: 42,
+ steps: 25,
+ guidance: 7,
+ sampler: "euler_a",
+ schedule_type: "karras",
+ width: 1024,
+ height: 1024,
+ model: "sd_xl_base_1.0.safetensors",
+ });
+});
+
+// ComfyUI's Flux dev example: SamplerCustomAdvanced, guidance on FluxGuidance, size on
+// EmptySD3LatentImage, model through ModelSamplingFlux.
+const COMFY_FLUX_PROMPT = JSON.stringify({
+ "13": {
+ class_type: "SamplerCustomAdvanced",
+ inputs: {
+ noise: ["25", 0],
+ guider: ["22", 0],
+ sampler: ["16", 0],
+ sigmas: ["17", 0],
+ latent_image: ["27", 0],
+ },
+ },
+ "25": { class_type: "RandomNoise", inputs: { noise_seed: 219670278747233 } },
+ "22": {
+ class_type: "BasicGuider",
+ inputs: { model: ["30", 0], conditioning: ["26", 0] },
+ },
+ "26": {
+ class_type: "FluxGuidance",
+ inputs: { guidance: 3.5, conditioning: ["6", 0] },
+ },
+ "6": {
+ class_type: "CLIPTextEncode",
+ inputs: { text: "a fennec fox", clip: ["11", 0] },
+ },
+ "12": {
+ class_type: "UNETLoader",
+ inputs: { unet_name: "flux1-dev.safetensors", weight_dtype: "default" },
+ },
+ "30": {
+ class_type: "ModelSamplingFlux",
+ inputs: {
+ max_shift: 1.15,
+ base_shift: 0.5,
+ width: 1024,
+ height: 1024,
+ model: ["12", 0],
+ },
+ },
+ "16": { class_type: "KSamplerSelect", inputs: { sampler_name: "euler" } },
+ "17": {
+ class_type: "BasicScheduler",
+ inputs: { scheduler: "simple", steps: 20, denoise: 1, model: ["30", 0] },
+ },
+ "27": {
+ class_type: "EmptySD3LatentImage",
+ inputs: { width: 1024, height: 768, batch_size: 1 },
+ },
+});
+
+test("a ComfyUI Flux graph imports through SamplerCustomAdvanced and FluxGuidance", () => {
+ assert.deepEqual(parseComfyPrompt(COMFY_FLUX_PROMPT), {
+ prompt: "a fennec fox",
+ seed: 219670278747233,
+ steps: 20,
+ guidance: 3.5,
+ sampler: "euler",
+ width: 1024,
+ height: 768,
+ model: "flux1-dev.safetensors",
+ });
+ // Flux checkpoint example: KSampler at cfg 1, the real guidance on FluxGuidance.
+ const ksampler = JSON.parse(COMFY_PROMPT);
+ ksampler["3"].inputs.positive = ["26", 0];
+ ksampler["3"].inputs.cfg = 1;
+ ksampler["26"] = {
+ class_type: "FluxGuidance",
+ inputs: { guidance: 3.5, conditioning: ["6", 0] },
+ };
+ const flux = parseComfyPrompt(JSON.stringify(ksampler));
+ assert.equal(flux?.prompt, "beautiful scenery nature glass bottle");
+ assert.equal(flux?.guidance, 3.5);
+});
+
+// A little-endian EXIF block holding one UserComment, as a non-piexif writer lays it out.
+function littleEndianExifJpeg(comment: Uint8Array): Uint8Array<ArrayBuffer> {
+ const tiff = new Uint8Array(8 + 18 + 18 + comment.length);
+ const v = new DataView(tiff.buffer);
+ tiff.set([0x49, 0x49, 0x2a, 0]);
+ v.setUint32(4, 8, true);
+ v.setUint16(8, 1, true);
+ v.setUint16(10, 0x8769, true);
+ v.setUint16(12, 4, true);
+ v.setUint32(14, 1, true);
+ v.setUint32(18, 26, true);
+ v.setUint16(26, 1, true);
+ v.setUint16(28, 0x9286, true);
+ v.setUint16(30, 7, true);
+ v.setUint32(32, comment.length, true);
+ v.setUint32(36, 44, true);
+ tiff.set(comment, 44);
+ const length = 2 + 6 + tiff.length;
+ return new Uint8Array([
+ 0xff,
+ 0xd8,
+ 0xff,
+ 0xe1,
+ length >> 8,
+ length & 0xff,
+ 0x45,
+ 0x78,
+ 0x69,
+ 0x66,
+ 0,
+ 0,
+ ...tiff,
+ 0xff,
+ 0xd9,
+ ]);
+}
+
+function utf16(text: string, bigEndian: boolean): Uint8Array {
+ const out = new Uint8Array(8 + text.length * 2);
+ out.set(latin1("UNICODE\0"));
+ const v = new DataView(out.buffer);
+ for (let i = 0; i < text.length; i++)
+ v.setUint16(8 + i * 2, text.charCodeAt(i), !bigEndian);
+ return out;
+}
+
+test("a UNICODE UserComment decodes in either byte order inside a little-endian EXIF", () => {
+ for (const bigEndian of [true, false]) {
+ const read = readEmbeddedRecipe(
+ littleEndianExifJpeg(utf16(PARAMETERS, bigEndian)),
+ );
+ assert.equal(
+ read.parameters,
+ PARAMETERS,
+ bigEndian ? "piexif-style UTF-16BE" : "byte-order UTF-16LE",
+ );
+ }
+});
+
+test("an imported reference count is capped at the request limit", () => {
+ const defaults = { width: 1024, height: 1024, steps: 8, guidance: 3.5 };
+ const capped = recipeSettings(
+ { prompt: "p", workflow: "reference", reference_image_count: 1e9 },
+ defaults,
+ );
+ assert.equal(capped.reference_image_count, 9);
+ assert.equal(
+ recipeSettings({ prompt: "p", reference_image_count: 3 }, defaults)
+ .reference_image_count,
+ 3,
+ );
+});
+
+test("the ComfyUI model is the loader feeding the sampler, through a LoRA loader", () => {
+ const graph = JSON.parse(COMFY_PROMPT);
+ // An unused checkpoint listed first, and the sampler fed by a LoRA on another UNet.
+ const reordered = {
+ "1": {
+ class_type: "CheckpointLoaderSimple",
+ inputs: { ckpt_name: "unused.safetensors" },
+ },
+ ...graph,
+ "11": {
+ class_type: "UNETLoader",
+ inputs: { unet_name: "flux1-dev.safetensors" },
+ },
+ "12": {
+ class_type: "LoraLoaderModelOnly",
+ inputs: { model: ["11", 0], lora_name: "x.safetensors" },
+ },
+ };
+ reordered["3"] = {
+ ...graph["3"],
+ inputs: { ...graph["3"].inputs, model: ["12", 0] },
+ };
+ assert.equal(
+ parseComfyPrompt(JSON.stringify(reordered))?.model,
+ "flux1-dev.safetensors",
+ );
+});
+
+test("a file drop on the preview is always claimed before the image filter", () => {
+ const page = readSrc("features/images/images-page.tsx");
+ const start = page.indexOf("const onImportDrop");
+ const drop = page.slice(
+ start,
+ page.indexOf("[importSettingsFromFile],", start),
+ );
+ assert.ok(
+ drop.indexOf("event.preventDefault()") <
+ drop.indexOf('f.type.startsWith("image/")'),
+ );
+ assert.match(drop, /toast\.error\(/);
+ // Desktop: Tauri hands drops over as paths, so the preview is a native drop target too.
+ assert.match(page, /ref=\{previewDropRef\}/);
+ assert.match(
+ page,
+ /useNativeDropTarget\(\{ onDrop: \(paths\) => void importNativePath\(paths\[0\]\) \}\)/,
+ );
+});
+
+test("imported steps, CFG and strength land inside the request bounds; A1111 strength is read", () => {
+ const defaults = { width: 1024, height: 1024, steps: 8, guidance: 3.5 };
+ const parsed = parseA1111Parameters(
+ "a cat\nSteps: 150, CFG scale: 30, Seed: 5, Size: 512x512, Denoising strength: 0.45",
+ );
+ assert.equal(parsed?.strength, 0.45);
+ const settings = recipeSettings(parsed ?? { prompt: "" }, defaults);
+ assert.equal(settings.steps, 100);
+ assert.equal(settings.guidance, 20);
+ assert.equal(settings.strength, 0.45);
+ assert.equal(
+ recipeSettings({ prompt: "p", strength: 3 }, defaults).strength,
+ 1,
+ );
+});
+
+test("sampler and schedule come back from the recipe and from A1111 labels", () => {
+ const defaults = { width: 1024, height: 1024, steps: 8, guidance: 3.5 };
+ const fromRecipe = recipeSettings(
+ { prompt: "p", sampler: "euler_a", schedule_type: "karras" },
+ defaults,
+ );
+ assert.equal(fromRecipe.sampler, "euler_a");
+ assert.equal(fromRecipe.schedule_type, "karras");
+ assert.equal(recipeSettings({ prompt: "p", sampler: 3 }, defaults).sampler, undefined);
+ const parsed = parseA1111Parameters(
+ "a cat\nSteps: 20, Sampler: Euler a, Schedule type: Exponential, CFG scale: 7, Seed: 1",
+ );
+ assert.equal(parsed?.sampler, "euler_a");
+ assert.equal(parsed?.schedule_type, "exponential");
+ // Unknown labels stay as written so the import can say it did not apply them.
+ assert.equal(
+ parseA1111Parameters("a cat\nSteps: 20, Sampler: UniPC")?.sampler,
+ "UniPC",
+ );
+});
+
+test("an older recipe without the newer fields still loads with the form's values", () => {
+ const defaults = { width: 1024, height: 1024, steps: 8, guidance: 3.5 };
+ // A recipe from before batch_seed, sampler, generator and schema_version existed.
+ const old = { prompt: "old", width: 512, height: 512, steps: 4, guidance: 0, seed: 7, created_at: 1 };
+ const settings = recipeSettings(old, defaults);
+ assert.equal(settings.seed, 7);
+ assert.equal(settings.batch_seed, null);
+ assert.equal(settings.sampler, undefined);
+ assert.equal(settings.batch_size, 1);
+ assert.deepEqual(unknownRecipeKeys(old), []);
+ assert.equal(newerRecipeSchema(old), false);
+ assert.equal(importedRecipe({ recipe: JSON.stringify(old) })?.prompt, "old");
+});
+
+test("a newer recipe loads what this build knows and names what it does not", () => {
+ const defaults = { width: 1024, height: 1024, steps: 8, guidance: 3.5 };
+ const future = {
+ ...JSON.parse(RECIPE),
+ schema_version: 2,
+ cfg_rescale: 0.7,
+ tiling: false,
+ empty_list: [],
+ unset: null,
+ };
+ const recipe = importedRecipe({ recipe: JSON.stringify(future) });
+ assert.ok(recipe);
+ const settings = recipeSettings(recipe, defaults);
+ assert.equal(settings.seed, 6630007);
+ assert.deepEqual(unknownRecipeKeys(recipe), ["cfg_rescale", "tiling"]);
+ assert.equal(newerRecipeSchema(recipe), true);
+ // Every key today's recipe writes is known, so a current image reports nothing.
+ assert.deepEqual(unknownRecipeKeys(JSON.parse(RECIPE)), []);
+ assert.equal(
+ new Set([...APPLIED_RECIPE_KEYS, ...INFO_RECIPE_KEYS]).size,
+ APPLIED_RECIPE_KEYS.length + INFO_RECIPE_KEYS.length,
+ );
+});
+
+test("an unmapped ComfyUI sampler is kept by name; prototype names map to nothing", () => {
+ const graph = (sampler_name: string, scheduler: string) =>
+ JSON.stringify({
+ "1": { class_type: "CLIPTextEncode", inputs: { text: "a fox" } },
+ "2": {
+ class_type: "KSampler",
+ inputs: { positive: ["1", 0], seed: 3, steps: 9, cfg: 4, sampler_name, scheduler },
+ },
+ });
+ assert.equal(parseComfyPrompt(graph("uni_pc", "normal"))?.sampler, "uni_pc");
+ assert.equal(parseComfyPrompt(graph("uni_pc", "normal"))?.schedule_type, undefined);
+ const hostile = parseComfyPrompt(graph("constructor", "toString"));
+ assert.equal(hostile?.sampler, "constructor");
+ assert.equal(hostile?.schedule_type, undefined);
+});
+
+test("the import names a sampler or schedule the loaded model does not offer", () => {
+ const page = readSrc("features/images/images-page.tsx");
+ const start = page.indexOf("const notApplied = unknownRecipeKeys(recipe);");
+ assert.ok(start > 0);
+ const block = page.slice(start, page.indexOf("[restoreSettings,", start));
+ assert.match(block, /notApplied\.unshift\(`sampler \$\{labelOf\(SAMPLER_LABELS, settings\.sampler\)\}`\)/);
+ assert.match(block, /notApplied\.unshift\(`schedule \$\{labelOf\(SCHEDULE_LABELS, settings\.schedule_type\)\}`\)/);
+ assert.match(page, /Object\.hasOwn\(labels, id\)/);
+ assert.match(block, /offered\.schedule_types\.includes\(settings\.schedule_type\)/);
+ assert.match(block, /newerRecipeSchema\(recipe\)/);
+ // A loaded model with no sampler choice still names a recorded sampler.
+ assert.match(block, /status\?\.loaded && samplerOptions\.length === 0/);
+});
+
+test("imported numbers land inside the generation request's bounds", () => {
+ const defaults = { width: 1024, height: 1024, steps: 8, guidance: 3.5 };
+ const s = recipeSettings(
+ {
+ prompt: "p",
+ seed: -5,
+ batch_seed: -1,
+ batch_size: 500,
+ strength: 0,
+ upscale: 9,
+ reference_resolution: 100000,
+ },
+ defaults,
+ );
+ assert.equal(s.seed, null);
+ assert.equal(s.batch_seed, null);
+ assert.equal(s.batch_size, 32);
+ assert.equal(s.strength, undefined);
+ assert.equal(s.upscale, 4);
+ assert.equal(s.reference_resolution, 2048);
+ const low = recipeSettings({ prompt: "p", upscale: 0.5, reference_resolution: 8, strength: 0.3 }, defaults);
+ assert.equal(low.upscale, 1);
+ assert.equal(low.reference_resolution, 256);
+ assert.equal(low.strength, 0.3);
+});
+
+test("UNICODE UserComment byte order is read from the whole text, not its first character", () => {
+ const text = "一只猫, sitting on a mat\nSteps: 7, CFG scale: 4, Seed: 99, Size: 8x8";
+ // UTF-16LE inside a big-endian TIFF (first character U+4E00 looks big-endian on its own).
+ const le = bytes("/9j/4AAQSkZJRgABAQAAAQABAAD/4QC+RXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAZKGAAEAAACKAAAALAAAAABVTklDT0RFAABO6lMrcywAIABzAGkAdAB0AGkAbgBnACAAbwBuACAAYQAgAG0AYQB0AAoAUwB0AGUAcABzADoAIAA3ACwAIABDAEYARwAgAHMAYwBhAGwAZQA6ACAANAAsACAAUwBlAGUAZAA6ACAAOQA5ACwAIABTAGkAegBlADoAIAA4AHgAOAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAIAAgDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDwGiiimI//2Q==");
+ assert.equal(readEmbeddedRecipe(le).parameters, text);
+ assert.equal(importedRecipe(readEmbeddedRecipe(le))?.seed, 99);
+ // Our own big-endian writer with the same first character.
+ const be = withJpegExif(bytes(JPEG_B64), { parameters: text });
+ assert.equal(readEmbeddedRecipe(be).parameters, text);
+});
+
+test("ComfyUI's SDXL, SD3 and Flux text encoders import their prompt", () => {
+ const graph = (encoder: Record<string, unknown>) =>
+ JSON.stringify({
+ "1": encoder,
+ "2": { class_type: "CLIPTextEncodeSDXL", inputs: { text_g: "lowres", text_l: "lowres" } },
+ "3": {
+ class_type: "KSampler",
+ inputs: { positive: ["1", 0], negative: ["2", 0], seed: 5, steps: 20, cfg: 6, sampler_name: "euler", scheduler: "normal" },
+ },
+ });
+ const sdxl = parseComfyPrompt(
+ graph({ class_type: "CLIPTextEncodeSDXL", inputs: { text_g: "a castle on a hill", text_l: "castle", width: 1024 } }),
+ );
+ assert.equal(sdxl?.prompt, "a castle on a hill");
+ assert.equal(sdxl?.negative_prompt, "lowres");
+ const sd3 = parseComfyPrompt(
+ graph({ class_type: "CLIPTextEncodeSD3", inputs: { clip_l: "c", clip_g: "c", t5xxl: "a detailed castle" } }),
+ );
+ assert.equal(sd3?.prompt, "a detailed castle");
+ const flux = parseComfyPrompt(
+ graph({ class_type: "CLIPTextEncodeFlux", inputs: { clip_l: "castle", t5xxl: "a castle at dawn", guidance: 4 } }),
+ );
+ assert.equal(flux?.prompt, "a castle at dawn");
+ assert.equal(flux?.guidance, 4);
+});
+
+test("pre-1.9 AUTOMATIC1111 sampler names carry their schedule; denoising strength means img2img", () => {
+ const legacy = parseA1111Parameters("a cat\nSteps: 20, Sampler: DPM++ 2M Karras, CFG scale: 7, Seed: 1, Size: 512x512");
+ assert.equal(legacy?.sampler, "dpmpp_2m");
+ assert.equal(legacy?.schedule_type, "karras");
+ // An explicit Schedule type wins over the suffix.
+ const both = parseA1111Parameters("a cat\nSteps: 20, Sampler: Euler a, Schedule type: Uniform, CFG scale: 7");
+ assert.equal(both?.sampler, "euler_a");
+ assert.equal(both?.schedule_type, "uniform");
+ assert.equal(parseA1111Parameters("a cat\nSteps: 20, Sampler: UniPC Karras")?.sampler, "UniPC");
+ const img2img = parseA1111Parameters("a cat\nSteps: 20, CFG scale: 7, Seed: 1, Denoising strength: 0.4");
+ assert.equal(img2img?.workflow, "img2img");
+ assert.equal(img2img?.strength, 0.4);
+ // txt2img hires fix: the strength belongs to the hires pass, so it is not restored.
+ const hires = parseA1111Parameters(
+ "a cat\nSteps: 20, CFG scale: 7, Seed: 1, Denoising strength: 0.7, Hires upscale: 2, Hires upscaler: Latent",
+ );
+ assert.equal(hires?.workflow, undefined);
+ assert.equal(hires?.strength, undefined);
+});
+
+test("ComfyUI denoise below 1 imports as img2img at that strength", () => {
+ const graph = (denoise: number) =>
+ JSON.stringify({
+ "1": { class_type: "CLIPTextEncode", inputs: { text: "a fox" } },
+ "2": { class_type: "KSampler", inputs: { positive: ["1", 0], seed: 3, steps: 9, cfg: 4, denoise } },
+ });
+ assert.equal(parseComfyPrompt(graph(0.6))?.strength, 0.6);
+ assert.equal(parseComfyPrompt(graph(0.6))?.workflow, "img2img");
+ assert.equal(parseComfyPrompt(graph(1))?.workflow, undefined);
+ assert.equal(parseComfyPrompt(graph(1))?.strength, undefined);
+ const sca = JSON.stringify({
+ "1": { class_type: "CLIPTextEncode", inputs: { text: "a fox" } },
+ "2": { class_type: "BasicGuider", inputs: { conditioning: ["1", 0] } },
+ "3": { class_type: "BasicScheduler", inputs: { steps: 20, scheduler: "simple", denoise: 0.5 } },
+ "4": { class_type: "SamplerCustomAdvanced", inputs: { guider: ["2", 0], sigmas: ["3", 0] } },
+ });
+ assert.equal(parseComfyPrompt(sca)?.strength, 0.5);
+ assert.equal(parseComfyPrompt(sca)?.workflow, "img2img");
+});
+
+test("the import warns when the loaded model runs at another precision than the recipe", () => {
+ const page = readSrc("features/images/images-page.tsx");
+ assert.match(page, /"transformer_quant", "text_encoder_quant", "transformer_cache", "attention_backend"\] as const\)\.filter/);
+ assert.match(page, /\(recipe\[key\] \?\? null\) !== \(status\[key\] \?\? null\)/);
+});
+
+test("imported LoRAs stay within the request's count, id and weight bounds", () => {
+ const defaults = { width: 1024, height: 1024, steps: 8, guidance: 3.5 };
+ const many = Array.from({ length: 12 }, (_, i) => `lora${i}:1`);
+ assert.equal(recipeSettings({ prompt: "p", loras: many }, defaults).loras.length, 8);
+ assert.deepEqual(
+ recipeSettings(
+ { prompt: "p", loras: ["a:5", "b:-1", "org/c:d:0.5", `${"x".repeat(513)}:1`, ":1", "noweight", "e:NaN"] },
+ defaults,
+ ).loras,
+ ["a:2", "b:0", "org/c:d:0.5"],
+ );
+});
+
+test("imported LoRA ids are trimmed and deduplicated like the request does", () => {
+ const defaults = { width: 1024, height: 1024, steps: 8, guidance: 3.5 };
+ assert.deepEqual(
+ recipeSettings({ prompt: "p", loras: ["a:1", " a :0.5", "b:1", "b:2"] }, defaults).loras,
+ ["a:1", "b:1"],
+ );
+});
+
+test("the import names LoRAs and a negative prompt the loaded model cannot apply", () => {
+ const page = readSrc("features/images/images-page.tsx");
+ assert.match(page, /status\.supports_lora === false && settings\.loras\.length > 0/);
+ assert.match(page, /status\?\.supports_negative_prompt === false && settings\.negative_prompt && settings\.guidance > 0/);
+});
+
+test("the import compares the whole build and names baked LoRAs; ComfyUI's GPU SDE sampler stays distinct", () => {
+ const page = readSrc("features/images/images-page.tsx");
+ assert.match(page, /\(\["gguf_filename", "transformer_quant", "text_encoder_quant", "transformer_cache", "attention_backend"\] as const\)\.filter/);
+ assert.match(page, /notApplied\.unshift\(`baked LoRAs \$\{baked\.join\(", "\)\} \(load-time\)`\)/);
+ const graph = JSON.stringify({
+ "1": { class_type: "CLIPTextEncode", inputs: { text: "a fox" } },
+ "2": { class_type: "KSampler", inputs: { positive: ["1", 0], seed: 3, steps: 9, cfg: 4, sampler_name: "dpmpp_2m_sde_gpu" } },
+ });
+ assert.equal(parseComfyPrompt(graph)?.sampler, "dpmpp_2m_sde_gpu");
+});
+
+test("a Connection recipe keeps its marker; a ControlNet recipe is named as not applied", () => {
+ const defaults = { width: 1024, height: 1024, steps: 8, guidance: 3.5 };
+ assert.equal(recipeSettings({ prompt: "p", model_kind: "connection" }, defaults).model_kind, "connection");
+ assert.equal(recipeSettings({ prompt: "p", model_kind: "gguf" }, defaults).model_kind, undefined);
+ const page = readSrc("features/images/images-page.tsx");
+ assert.match(page, /settings\.seed === null && settings\.model_kind !== "connection"/);
+ assert.match(page, /notApplied\.unshift\(`ControlNet \$\{recipe\.controlnet\}`\)/);
+});
diff --git a/studio/frontend/tests/images-gallery-thumbnails.test.ts b/studio/frontend/tests/images-gallery-thumbnails.test.ts
index d119945195d..8fa0fa4fe23 100644
--- a/studio/frontend/tests/images-gallery-thumbnails.test.ts
+++ b/studio/frontend/tests/images-gallery-thumbnails.test.ts
@@ -55,15 +55,18 @@ test("the canvas, viewer and downloads read only the original", () => {
const canvas = between(page, ") : selected && selectedSrc ? (", ") : selected ? (");
assert.ok(canvas.includes("src={selectedSrc}"));
for (const format of ["png", "jpeg", "webp"]) {
- assert.ok(canvas.includes(`downloadImage(selectedSrc, selected, "${format}")`));
+ assert.ok(canvas.includes(`downloadImage(selected, "${format}", selectedSrc)`));
}
assert.ok(!canvas.includes("thumbById"));
assert.ok(!canvas.includes("selectedThumb"));
const quickDownload = between(page, "const handleQuickDownload = useCallback(", "const stripReorder");
assert.ok(quickDownload.includes("srcById[image.id]"));
- assert.ok(quickDownload.includes("fetchGalleryBlob(image.url)"));
assert.ok(!quickDownload.includes("thumbById"));
+ // Without a cached original, the download fetches the full PNG, never a thumbnail.
+ const download = between(page, "async function downloadImage(", "\n}\n");
+ assert.ok(download.includes("fetchGalleryBlob(image.url)"));
+ assert.ok(!download.includes("thumb"));
});
test("the thumbnail placeholder offers no action that needs the original", () => {
diff --git a/tests/studio/test_desktop_reliability_frontend_contract.py b/tests/studio/test_desktop_reliability_frontend_contract.py
index 55925d5e8b3..5cc912a13cb 100644
--- a/tests/studio/test_desktop_reliability_frontend_contract.py
+++ b/tests/studio/test_desktop_reliability_frontend_contract.py
@@ -250,7 +250,7 @@ def test_file_actions_route_through_native_commands_only_in_tauri():
def test_media_galleries_save_natively_with_feedback():
images_page = _ui_source(IMAGES_PAGE)
video_page = _ui_source(VIDEO_PAGE)
- reencode = images_page.split("async function reencodeImage(", 1)[1].split(
+ reencode = images_page.split("async function encodeExport(", 1)[1].split(
"\n}\n\nasync function downloadImage", 1
)[0]
download = images_page.split("async function downloadImage(", 1)[1].split(
@@ -261,9 +261,10 @@ def test_media_galleries_save_natively_with_feedback():
)[0]
assert "await downloadUrl(src, filename);" in download
- assert "await downloadFile(outputBlob, filename, outputBlob.type);" in download
- assert "const originalBlob = await fetchGalleryBlob(image.url);" in download
- assert "await downloadFile(originalBlob, filename, originalBlob.type);" in download
+ # WebKit cannot refetch the cached object URL, so only the unstamped browser PNG reuses src.
+ assert 'await downloadFile(output, filename, output.type || "image/png");' in download
+ assert "await fetchGalleryBlob(image.url)" in download
+ assert "if (src && !isTauri)" in download
assert "blob.type !== `image/${format}`" in reencode
assert "isDownloadCancelled(error)" in download
assert "if (isTauri)" in download