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: fix Restore settings breaking preset saving (#10256)

Nilay17954a186e5c
diff --git a/studio/frontend/src/features/images/image-size.ts b/studio/frontend/src/features/images/image-size.ts
new file mode 100644
index 00000000000..5fc49cb99e6
--- /dev/null
+++ b/studio/frontend/src/features/images/image-size.ts
@@ -0,0 +1,42 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Z-Image's range, which ImageGenerationPresetParams also enforces on the persisted recipe.
+export const MIN_DIM = 256;
+export const MAX_DIM = 2048;
+
+export function snapDim(value: number): number {
+ if (!Number.isFinite(value)) return 1024;
+ return Math.min(MAX_DIM, Math.max(MIN_DIM, Math.round(value / 16) * 16));
+}
+
+/** A gallery record's size as the Create form can hold it. Scaled as a pair, so the recipe's
+ * aspect ratio survives; clamping each side alone would not.
+ *
+ * Transform is the exception. img2img treats the requested size as a BOX it fits the upload
+ * inside (_fit_within, which never enlarges) rather than as the output size, so a side that was
+ * already in range has to be left alone: growing it moves the box and the re-run produces a
+ * different image than the one being restored. Clamping only the offending side reproduces the
+ * record exactly there, and the shape is the upload's anyway, not the form's. */
+export function restorableSize(
+ width: number,
+ height: number,
+ workflow?: string | null,
+): { width: number; height: number } {
+ if (workflow === "img2img") {
+ return { width: snapDim(width), height: snapDim(height) };
+ }
+ if (
+ !Number.isFinite(width) ||
+ !Number.isFinite(height) ||
+ width <= 0 ||
+ height <= 0
+ ) {
+ return { width: snapDim(width), height: snapDim(height) };
+ }
+ const upTo = Math.max(MIN_DIM / width, MIN_DIM / height);
+ const downTo = Math.min(MAX_DIM / width, MAX_DIM / height);
+ // A ratio too extreme to fit both bounds at any scale falls back to per-side clamping.
+ const scale = upTo > downTo ? 1 : Math.min(Math.max(1, upTo), downTo);
+ return { width: snapDim(width * scale), height: snapDim(height * scale) };
+}
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index fee8ed8a75c..de60327fe1d 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -131,6 +131,7 @@ import {
import { toast } from "@/lib/toast";
import { subscribeModelEjected } from "@/lib/model-lifecycle-events";
import { DEFAULT_GEN, defaultsFor } from "./image-generation-defaults";
+import { MAX_DIM, MIN_DIM, restorableSize, snapDim } from "./image-size";
import {
type ControlNetSpecInput,
@@ -218,9 +219,6 @@ const CONTROL_TYPE_LABELS: Record<string, string> = {
pose: "Pose (map)",
};
-// Z-Image accepts 256-2048, in multiples of 16. Snap any value into range.
-const MIN_DIM = 256;
-const MAX_DIM = 2048;
// Convenient drag range for the Runs slider; the number box accepts higher typed values on purpose.
const RUNS_SLIDER_MAX = 128;
// Offered sizes; a locked ratio can derive one off-list, so the current value is added in.
@@ -229,11 +227,6 @@ const DIM_OPTIONS = [
1408, 1536, 1664, 1792, 1920, 2048,
];
-function snapDim(value: number): number {
- if (!Number.isFinite(value)) return 1024;
- return Math.min(MAX_DIM, Math.max(MIN_DIM, Math.round(value / 16) * 16));
-}
-
/** Compact size control: type a value, or pick one of the usual sizes from the menu. */
function DimensionSelect({
icon,
@@ -1962,11 +1955,12 @@ export function ImagesPage({
// Restore from the BASE batch seed, not this image's derived seed, or a replay with batch_size
// advances it again.
setSeed(String(image.batch_seed ?? image.seed));
- setWidth(image.width);
- setHeight(image.height);
+ const restored = restorableSize(image.width, image.height, image.workflow);
+ setWidth(restored.width);
+ setHeight(restored.height);
// The batch shared one base seed, so a batch_index>0 image only reproduces by replaying the whole batch.
setBatchSize(image.batch_size ?? 1);
- const m = matchAspect(image.width, image.height);
+ const m = matchAspect(restored.width, restored.height);
setAspect(m.key);
setPortrait(m.portrait);
// Restore LoRA adapters from the recipe ("id:weight"), splitting on the LAST colon so an id
@@ -1995,12 +1989,18 @@ export function ImagesPage({
// The control image is not persisted, so clear any stale ControlNet selection.
setControlnetId("");
setControlImage(null);
+ // The Recipe popover goes on showing the recorded size, so a restore that had to move it says
+ // so rather than leaving the two silently disagreeing.
+ const rescaled =
+ restored.width !== image.width || restored.height !== image.height
+ ? { description: `Size scaled to ${restored.width} × ${restored.height} to fit the ${MIN_DIM}-${MAX_DIM} range.` }
+ : undefined;
// Say so, rather than letting a conditioned image restore as a plain Create that generates something unrelated.
const conditioned = CONDITIONED_WORKFLOW_INPUTS[image.workflow ?? ""];
if (conditioned) {
- toast.success(`Settings restored. Add ${conditioned} again to reproduce this image.`);
+ toast.success(`Settings restored. Add ${conditioned} again to reproduce this image.`, rescaled);
} else {
- toast.success("Settings restored to inputs");
+ toast.success("Settings restored to inputs", rescaled);
}
}, [setWorkflow]);
diff --git a/studio/frontend/tests/image-restore-settings-size.test.ts b/studio/frontend/tests/image-restore-settings-size.test.ts
new file mode 100644
index 00000000000..3b81cadb464
--- /dev/null
+++ b/studio/frontend/tests/image-restore-settings-size.test.ts
@@ -0,0 +1,229 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Restore settings copied a gallery record's raw size into the Create form. Image-conditioned
+// workflows derive that size from the upload, so it could fall outside the 256..2048 that
+// ImageGenerationPresetParams forbids -- 422ing every debounced preset PUT for the rest of the session.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+import {
+ MAX_DIM,
+ MIN_DIM,
+ restorableSize,
+ snapDim,
+} from "../src/features/images/image-size.ts";
+
+const withinSchema = ({ width, height }: { width: number; height: number }) =>
+ width >= MIN_DIM &&
+ width <= MAX_DIM &&
+ height >= MIN_DIM &&
+ height <= MAX_DIM &&
+ width % 16 === 0 &&
+ height % 16 === 0;
+
+const ratio = ({ width, height }: { width: number; height: number }) =>
+ width / height;
+
+test("a size the gallery can record always restores inside the preset schema", () => {
+ const recorded = [
+ [4032, 3024], // Edit on a phone photo: no clamp, only _snap_to_multiple
+ [1024, 208], // Transform a 1920x400 source with the sliders at 1024
+ [4096, 4096], // decode_b64_image's ceiling
+ [2048, 256], // already legal
+ [1024, 1024],
+ ];
+ for (const [width, height] of recorded) {
+ const restored = restorableSize(width, height);
+ assert.ok(
+ withinSchema(restored),
+ `${width}x${height} restored to ${restored.width}x${restored.height}`,
+ );
+ }
+ assert.ok(!withinSchema({ width: 4032, height: 3024 }));
+ assert.ok(!withinSchema({ width: 1024, height: 208 }));
+});
+
+test("a legal size is restored unchanged", () => {
+ assert.deepEqual(restorableSize(2048, 256), { width: 2048, height: 256 });
+ assert.deepEqual(restorableSize(1024, 1024), { width: 1024, height: 1024 });
+});
+
+test("the recipe's aspect ratio survives the scale into range", () => {
+ for (const [width, height] of [
+ [4032, 3024],
+ [1024, 208],
+ [4096, 2048],
+ ]) {
+ const restored = restorableSize(width, height);
+ assert.ok(
+ Math.abs(ratio(restored) - width / height) < 0.05,
+ `${width}x${height} became ${restored.width}x${restored.height}`,
+ );
+ }
+});
+
+test("a degenerate record still produces a usable size", () => {
+ for (const [width, height] of [
+ [0, 0],
+ [Number.NaN, 512],
+ [-1024, 512],
+ ]) {
+ assert.ok(withinSchema(restorableSize(width, height)));
+ }
+});
+
+const restoreSettingsBody = () => {
+ const source = readFileSync(
+ new URL("../src/features/images/images-page.tsx", import.meta.url),
+ "utf8",
+ );
+ const start = source.indexOf("const restoreSettings = useCallback(");
+ assert.ok(start > 0, "restoreSettings not found");
+ return source.slice(start, source.indexOf("}, [", start));
+};
+
+test("restoreSettings puts the record through restorableSize", () => {
+ const body = restoreSettingsBody();
+ assert.match(
+ body,
+ /restorableSize\(image\.width, image\.height, image\.workflow\)/,
+ );
+ assert.doesNotMatch(
+ body,
+ /setWidth\(image\.width\)|setHeight\(image\.height\)/,
+ "the raw recorded size must not reach the form",
+ );
+});
+
+test("a restore that had to move the size says so", () => {
+ // The Recipe popover goes on showing the recorded size, so a silent scale leaves the two
+ // disagreeing with nothing to explain it.
+ const body = restoreSettingsBody();
+ assert.match(body, /restored\.width !== image\.width/);
+ assert.match(body, /Size scaled to \$\{restored\.width\}/);
+});
+
+// Transform bounds the upload by the requested size instead of taking it literally, so the
+// restored recipe only reproduces the record when the in-range side is left where it was.
+
+/** _fit_within + _snap_to_multiple from studio/backend/core/inference/diffusion.py. */
+const transform = (
+ source: [number, number],
+ reqW: number,
+ reqH: number,
+): [number, number] => {
+ const [w, h] = source;
+ const bw = Math.min(2048, reqW);
+ const bh = Math.min(2048, reqH);
+ const [fw, fh] =
+ w <= bw && h <= bh
+ ? [w, h]
+ : (() => {
+ const s = Math.min(bw / w, bh / h);
+ return [
+ Math.max(1, Math.round(w * s)),
+ Math.max(1, Math.round(h * s)),
+ ];
+ })();
+ return [
+ Math.max(16, Math.round(fw / 16) * 16),
+ Math.max(16, Math.round(fh / 16) * 16),
+ ];
+};
+
+test("restoring a Transform record reproduces it as exactly as an unscaled restore would", () => {
+ // The baseline is the unscaled restore: the raw record in the form, each side snapped by
+ // Generate on its own. Not an absolute round-trip assertion, because Transform is not perfectly
+ // self-reproducing either way -- _snap_to_multiple rounds a side and the tightened box changes
+ // the next run (3000x500 at 2048 records 2048x336 and re-runs to 2016x336, scaled or not). What
+ // the scale owes is that it never reproduces WORSE while making the recipe savable.
+ for (const source of [
+ [1920, 400],
+ [1920, 320],
+ [3000, 500],
+ [4000, 3000],
+ ] as Array<[number, number]>) {
+ for (const requested of [512, 768, 1024, 2048]) {
+ const recorded = transform(source, requested, requested);
+ const unscaled = transform(
+ source,
+ snapDim(recorded[0]),
+ snapDim(recorded[1]),
+ );
+ const restored = restorableSize(recorded[0], recorded[1], "img2img");
+ const reRun = transform(
+ source,
+ snapDim(restored.width),
+ snapDim(restored.height),
+ );
+ assert.ok(
+ withinSchema(restored),
+ `${recorded[0]}x${recorded[1]} restored to ${restored.width}x${restored.height}`,
+ );
+ assert.deepEqual(
+ reRun,
+ unscaled,
+ `source ${source[0]}x${source[1]} at ${requested}: recorded ${recorded[0]}x${recorded[1]}, ` +
+ `restored ${restored.width}x${restored.height}, re-ran to ${reRun[0]}x${reRun[1]} ` +
+ `where an unscaled restore re-ran to ${unscaled[0]}x${unscaled[1]}`,
+ );
+ }
+ }
+});
+
+test("scaling a Transform record as a pair would NOT reproduce it", () => {
+ // Guards the reason the img2img branch exists: the shared scale is right for every other
+ // workflow and wrong for this one, so a later simplification that drops it has to fail here.
+ const recorded = transform([1920, 400], 1024, 1024);
+ assert.deepEqual(recorded, [1024, 208]);
+ const asTransform = restorableSize(1024, 208, "img2img");
+ const asPair = restorableSize(1024, 208, "edit");
+ assert.deepEqual(asTransform, { width: 1024, height: 256 });
+ assert.deepEqual(asPair, { width: 1264, height: 256 });
+ assert.deepEqual(
+ transform([1920, 400], asTransform.width, asTransform.height),
+ recorded,
+ );
+ assert.notDeepEqual(
+ transform([1920, 400], asPair.width, asPair.height),
+ recorded,
+ );
+});
+
+test("every other workflow still keeps the recipe's shape", () => {
+ // The headline case: an Edit of a phone photo must not come back square.
+ for (const workflow of [
+ null,
+ undefined,
+ "edit",
+ "inpaint",
+ "upscale",
+ "reference",
+ ]) {
+ const restored = restorableSize(4032, 3024, workflow);
+ assert.deepEqual(
+ restored,
+ { width: 2048, height: 1536 },
+ `workflow ${String(workflow)} restored 4032x3024 to ${restored.width}x${restored.height}`,
+ );
+ }
+ // Per-side clamping, which img2img wants, would square this one up.
+ assert.deepEqual(restorableSize(4032, 3024, "img2img"), {
+ width: 2048,
+ height: 2048,
+ });
+});
+
+test("a Transform record already inside the schema is untouched", () => {
+ assert.deepEqual(restorableSize(1024, 512, "img2img"), {
+ width: 1024,
+ height: 512,
+ });
+ assert.deepEqual(restorableSize(2048, 256, "img2img"), {
+ width: 2048,
+ height: 256,
+ });
+});