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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio Images: Compare grid (X/Y/Z plot) (#14624)
Daniel Hanfcc7660e92ab
diff --git a/studio/frontend/src/features/images/compare/compare-axes.ts b/studio/frontend/src/features/images/compare/compare-axes.tsnew file mode 100644index 00000000000..da82da422c6--- /dev/null+++ b/studio/frontend/src/features/images/compare/compare-axes.ts@@ -0,0 +1,495 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/** Compare grid (AUTOMATIC1111's X/Y/Z plot): which axes the loaded model can take, the cell plan, the order the+ * cells run in, and each cell's generate request. Pure, so tests drive it without a page. */++import type { DiffusionGenerateRequest, LoraSpecInput } from "../api.ts";+import {+ AUTOMATIC_SCHEDULE as AUTOMATIC,+ SCHEDULE_LABELS,+ type SamplerChoice,+ type SamplerOption,+} from "../lib/sampler-choice.ts";+import { SHIFT_MAX, type ShiftControl } from "../lib/shift-choice.ts";+import { parseAxisValues, roundValue, type AxisValueType } from "./compare-values.ts";++export const MAX_COMPARE_CELLS = 64;+const STEPS_MAX = 100;+const GUIDANCE_MAX = 20;+const LORA_WEIGHT_MAX = 2;+const SEED_MAX = Number.MAX_SAFE_INTEGER;++/** PR-gated SD controls, read structurally so axes appear once a backend reports them. */+export interface CompareSdControls {+ clip_skip?: { min: number; max: number } | null;+ cfg_rescale?: { min: number; max: number } | null;+ variation_seed?: boolean;+ vary_strength?: number;+}++/** What the page knows about the loaded model and the form. Compare runs only on a loaded local model. */+export interface CompareContext {+ prompt: string;+ negativePrompt: string;+ negativeCapable: boolean;+ // Guidance a negative prompt (and so the unconditional pass) needs; null = always engaged.+ negativeMinGuidance: number | null;+ guidanceFixed: boolean;+ // The form's effective guidance, which every cell runs at unless a CFG axis sets it.+ guidance: number;+ samplers: readonly SamplerOption[];+ samplerChoice: SamplerChoice;+ shift: ShiftControl | null;+ loraCapable: boolean;+ // The form's active LoRA rows, in order; a weight axis targets one of them.+ loras: ReadonlyArray<{ id: string; weight: number; label: string }>;+ sdControls?: CompareSdControls | null;+ controlnetEngaged: boolean;+}++type Value = number | string;++/** Everything a cell can override, folded into the request once every axis has applied. */+export interface CellState {+ seed?: number | "random";+ steps?: number;+ guidance?: number;+ sampler?: string;+ schedule?: string;+ shift?: number;+ baseShift?: number;+ maxShift?: number;+ loraWeights: Record<number, number>;+ replacements: Array<[string, string]>;+ extra: Record<string, number>;+}++export interface AxisDef {+ id: string;+ label: string;+ type: AxisValueType;+ placeholder: string;+ choices?: ReadonlyArray<{ value: string; label: string }>;+ // A1111 AxisOption.cost: costly axes run in the outer loop. Here cost = may change the denoiser's work shape.+ cost: number;+ resolve(value: Value): { ok: true; value: Value } | { ok: false; error: string };+ apply(cell: CellState, value: Value, values: readonly Value[]): void;+ format(value: Value): string;+ // Values with the same key run with the same tensor shapes; the plan keeps each key's cells together.+ shapeKey?(value: Value): string;+ // Keys that must run first, in this order; others follow in first-seen order.+ shapeOrder?: readonly string[];+}++export const NOTHING = "nothing";++const ok = (value: Value) => ({ ok: true as const, value });+const fail = (error: string) => ({ ok: false as const, error });++function numberAxis(+ id: string,+ label: string,+ type: "int" | "float",+ min: number,+ max: number,+ placeholder: string,+ apply: (cell: CellState, v: number) => void,+ extra: Partial<AxisDef> = {},+ minExclusive = false,+): AxisDef {+ return {+ id,+ label,+ type,+ placeholder,+ cost: 0,+ resolve: (v) => {+ const n = Number(v);+ if (!Number.isFinite(n)) return fail(`${label}: "${v}" is not a number`);+ if (minExclusive ? n <= min : n < min) return fail(`${label} ${n} is below ${minExclusive ? "or at " : ""}${min}`);+ if (n > max) return fail(`${label} ${n} is above ${max}`);+ return ok(type === "int" ? Math.trunc(n) : roundValue(n));+ },+ apply: (cell, v) => apply(cell, Number(v)),+ format: (v) => `${label}: ${v}`,+ ...extra,+ };+}++function choiceAxis(+ id: string,+ label: string,+ choices: ReadonlyArray<{ value: string; label: string }>,+ apply: (cell: CellState, v: string) => void,+): AxisDef {+ return {+ id,+ label,+ type: "str",+ placeholder: choices.slice(0, 3).map((c) => c.label).join(", "),+ choices,+ cost: 0,+ resolve: (v) => {+ const want = String(v).trim().toLowerCase();+ const hit = choices.find((c) => c.value.toLowerCase() === want || c.label.toLowerCase() === want);+ return hit ? ok(hit.value) : fail(`Unknown ${label.toLowerCase()}: ${v}`);+ },+ apply: (cell, v) => apply(cell, String(v)),+ format: (v) => choices.find((c) => c.value === v)?.label ?? String(v),+ };+}++/** The axes the loaded model can take, in menu order. "Nothing" first, as in A1111. */+export function availableAxes(ctx: CompareContext): AxisDef[] {+ const axes: AxisDef[] = [];+ axes.push({+ id: NOTHING,+ label: "Nothing",+ type: "str",+ placeholder: "",+ cost: 0,+ resolve: ok,+ apply: () => {},+ format: () => "",+ });+ axes.push(+ numberAxis("seed", "Seed", "int", -1, SEED_MAX, "-1, 11, 12 or 100-103", (c, v) => {+ c.seed = v < 0 ? "random" : v;+ }),+ );+ axes.push(numberAxis("steps", "Steps", "int", 1, STEPS_MAX, "10, 20, 30 or 10-30 (+10)", (c, v) => (c.steps = v)));+ if (!ctx.guidanceFixed) {+ const min = ctx.negativeMinGuidance;+ axes.push(+ numberAxis("guidance", "CFG", "float", 0, GUIDANCE_MAX, "3, 5, 7 or 3-7 [3]", (c, v) => (c.guidance = v), {+ // Crossing the threshold adds or drops the unconditional pass (a batch-size change), so those cells group.+ cost: 1,+ shapeKey: (v) => (min === null || Number(v) > min ? "cfg" : "nocfg"),+ }),+ );+ }+ if (ctx.samplers.length > 1) {+ axes.push(+ choiceAxis(+ "sampler",+ "Sampler",+ ctx.samplers.map((s) => ({ value: s.id, label: s.label })),+ (c, v) => (c.sampler = v),+ ),+ );+ const schedules = [...new Set(ctx.samplers.flatMap((s) => s.schedule_types))];+ if (schedules.length > 1) {+ axes.push(+ choiceAxis(+ "schedule",+ "Schedule type",+ schedules.map((t) => ({ value: t, label: SCHEDULE_LABELS[t] ?? t })),+ (c, v) => (c.schedule = v),+ ),+ );+ }+ }+ if (ctx.shift?.node === "sd3") {+ axes.push(numberAxis("shift", "Shift", "float", 0, SHIFT_MAX, "1, 3, 6", (c, v) => (c.shift = v), {}, true));+ } else if (ctx.shift?.node === "flux") {+ axes.push(numberAxis("base_shift", "Base shift", "float", 0, SHIFT_MAX, "0.25, 0.5, 1", (c, v) => (c.baseShift = v)));+ axes.push(numberAxis("max_shift", "Max shift", "float", 0, SHIFT_MAX, "0.75, 1.15, 1.5", (c, v) => (c.maxShift = v)));+ }+ if (ctx.loraCapable) {+ ctx.loras.forEach((lora, index) => {+ const name = ctx.loras.length > 1 ? `LoRA weight: ${lora.label}` : "LoRA weight";+ axes.push(+ numberAxis(`lora:${index}`, name, "float", 0, LORA_WEIGHT_MAX, "0, 0.5, 1", (c, v) => (c.loraWeights[index] = v), {+ // Weight 0 drops the adapter from the request. Every weighted cell runs before any of those, outermost+ // of all axes: Speed Auto compiles on an adapter-free run, and a compiled load refuses LoRA after that.+ cost: 4,+ shapeKey: (v) => (Number(v) === 0 ? "off" : "on"),+ shapeOrder: ["on", "off"],+ format: (v) => `${name}: ${v}`,+ }),+ );+ });+ }+ const sd = ctx.sdControls;+ if (sd?.clip_skip) {+ const { min, max } = sd.clip_skip;+ axes.push(numberAxis("clip_skip", "Clip skip", "int", min, max, "1, 2", (c, v) => (c.extra.clip_skip = v)));+ }+ if (sd?.cfg_rescale && !ctx.controlnetEngaged) {+ const { min, max } = sd.cfg_rescale;+ axes.push(numberAxis("cfg_rescale", "CFG rescale", "float", min, max, "0, 0.35, 0.7", (c, v) => (c.extra.cfg_rescale = v)));+ }+ if (sd?.variation_seed) {+ axes.push(+ numberAxis("variation_seed", "Var. seed", "int", 0, 2 ** 32 - 1, "1, 2, 3", (c, v) => (c.extra.variation_seed = v)),+ );+ axes.push(+ numberAxis("variation_strength", "Var. strength", "float", 0, 1, "0, 0.1, 0.3", (c, v) => (c.extra.variation_strength = v)),+ );+ }+ axes.push({+ id: "prompt_sr",+ label: "Prompt S/R",+ type: "str",+ placeholder: "red, blue, green (first value is searched for)",+ // A new text length can retrace a dynamic-shape denoiser: outermost, so each prompt is entered once.+ cost: 3,+ resolve: (v) => ok(String(v)),+ apply: (cell, v, values) => cell.replacements.push([String(values[0]), String(v)]),+ format: (v) => String(v),+ shapeKey: (v) => String(v),+ });+ return axes;+}++export interface AxisInput {+ axisId: string;+ text: string;+}++export interface ResolvedAxis {+ def: AxisDef;+ text: string;+ values: Value[];+ labels: string[];+}++export interface CompareGridPlan {+ axes: [ResolvedAxis, ResolvedAxis, ResolvedAxis];+ cellCount: number;+ // Linear cell indexes (ix + iy*nx + iz*nx*ny) in the order they run.+ order: number[];+}++export type PlanResult = { ok: true; plan: CompareGridPlan } | { ok: false; error: string; cellCount?: number };++const AXIS_NAMES = ["X", "Y", "Z"] as const;++export function cellCoords(plan: CompareGridPlan, index: number): [number, number, number] {+ const nx = plan.axes[0].values.length;+ const ny = plan.axes[1].values.length;+ return [index % nx, Math.floor(index / nx) % ny, Math.floor(index / (nx * ny))];+}++/** Costliest axis outermost (A1111), and a costly axis's values grouped by shape key so the model switches shape+ * at most once per key. Cells are placed by index, not run order. */+export function executionOrder(axes: readonly ResolvedAxis[]): number[] {+ const n = axes.map((a) => a.values.length);+ const total = n[0] * n[1] * n[2];+ const priority = [2, 1, 0].sort((a, b) => axes[b].def.cost - axes[a].def.cost);+ const rank = axes.map((axis) => {+ const keys: string[] = [...(axis.def.shapeOrder ?? [])];+ return axis.values.map((v) => {+ const key = axis.def.shapeKey ? axis.def.shapeKey(v) : "";+ let at = keys.indexOf(key);+ if (at < 0) at = keys.push(key) - 1;+ return at;+ });+ });+ const cells = Array.from({ length: total }, (_, i) => i);+ const coord = (i: number) => [i % n[0], Math.floor(i / n[0]) % n[1], Math.floor(i / (n[0] * n[1]))];+ // Shape keys of every axis first (outer to inner), then the nested-loop position.+ const key = (i: number) => {+ const c = coord(i);+ return [...priority.map((a) => rank[a][c[a]]), ...priority.map((a) => c[a])];+ };+ const keys = cells.map(key);+ return cells.sort((a, b) => {+ const ka = keys[a];+ const kb = keys[b];+ for (let j = 0; j < ka.length; j++) if (ka[j] !== kb[j]) return ka[j] - kb[j];+ return 0;+ });+}++/** Parse, validate and order the three axes. `rng` draws the fixed seeds for -1 seed values (A1111 fix_axis_seeds). */+export function planCompare(+ inputs: readonly AxisInput[],+ ctx: CompareContext,+ options: { keepRandomSeeds: boolean; maxCells?: number; rng?: () => number } = { keepRandomSeeds: false },+): PlanResult {+ const defs = availableAxes(ctx);+ const nothing = defs[0];+ const resolved: ResolvedAxis[] = [];+ const seen = new Map<string, string>();+ for (let a = 0; a < 3; a++) {+ const input = inputs[a] ?? { axisId: NOTHING, text: "" };+ const def = defs.find((d) => d.id === input.axisId);+ if (!def) return { ok: false, error: `${AXIS_NAMES[a]}: this model has no ${input.axisId.replace(/_/g, " ")} axis` };+ if (def.id === NOTHING) {+ resolved.push({ def: nothing, text: "", values: [""], labels: [""] });+ continue;+ }+ if (def.id !== "prompt_sr" && seen.has(def.id)) {+ return { ok: false, error: `${seen.get(def.id)} and ${AXIS_NAMES[a]} are both ${def.label}` };+ }+ seen.set(def.id, AXIS_NAMES[a]);+ const parsed = parseAxisValues(input.text, def.type, { keepEmpty: def.id === "prompt_sr" });+ if (!parsed.ok) return { ok: false, error: `${AXIS_NAMES[a]} (${def.label}): ${parsed.error}` };+ const values: Value[] = [];+ for (const raw of parsed.values) {+ const r = def.resolve(raw);+ if (!r.ok) return { ok: false, error: `${AXIS_NAMES[a]}: ${r.error}` };+ values.push(r.value);+ }+ if (def.id === "seed" && !options.keepRandomSeeds) {+ const rng = options.rng ?? Math.random;+ for (let i = 0; i < values.length; i++) if (values[i] === -1) values[i] = Math.floor(rng() * 2 ** 32);+ }+ resolved.push({+ def,+ text: input.text,+ values,+ labels: values.map((v) => (def.id === "seed" && v === -1 ? "Seed: random" : def.format(v))),+ });+ }+ const cellCount = resolved.reduce((n, a) => n * a.values.length, 1);+ const max = options.maxCells ?? MAX_COMPARE_CELLS;+ if (resolved.every((a) => a.def.id === NOTHING)) return { ok: false, error: "Pick at least one axis", cellCount: 1 };+ if (cellCount > max) {+ return {+ ok: false,+ error: `${cellCount} cells is over the limit of ${max}. Use fewer values or drop an axis.`,+ cellCount,+ };+ }+ const axes = resolved as [ResolvedAxis, ResolvedAxis, ResolvedAxis];+ const plan: CompareGridPlan = { axes, cellCount, order: executionOrder(axes) };+ const problem = cellProblem(plan, ctx);+ return problem ? { ok: false, error: problem } : { ok: true, plan };+}++/** Combinations no cell may run: a Prompt S/R term a cell's text lacks once the earlier axes' substitutions ran+ * (A1111 apply_prompt raises per cell; a negative prompt counts only where that cell's CFG engages it), or a+ * Schedule type, from an axis or the form, the cell's sampler does not take (the backend would run Automatic under a+ * Karras label). */+function cellProblem(plan: CompareGridPlan, ctx: CompareContext): string | null {+ const srAxes = plan.axes.flatMap((axis, a) => (axis.def.id === "prompt_sr" ? [a] : []));+ for (let i = 0; i < plan.cellCount; i++) {+ const cell = cellState(plan, i);+ let prompt = ctx.prompt;+ let negative = negativeEngaged(ctx, cell.guidance ?? ctx.guidance) ? ctx.negativePrompt : "";+ for (let k = 0; k < cell.replacements.length; k++) {+ const [search, replace] = cell.replacements[k];+ if (!prompt.includes(search) && !negative.includes(search)) {+ return `${AXIS_NAMES[srAxes[k]]}: Prompt S/R did not find "${search}" in cell "${cellTitle(plan, i)}" (its prompt after earlier substitutions, or a negative prompt its CFG uses)`;+ }+ prompt = prompt.split(search).join(replace);+ negative = negative.split(search).join(replace);+ }+ // The form's schedule counts too once a Sampler axis picks the sampler: falling back to Automatic for one cell+ // would vary the schedule along with the labelled sampler.+ const schedule = cell.schedule ?? (cell.sampler !== undefined ? ctx.samplerChoice.scheduleType : undefined);+ if (schedule !== undefined && schedule !== AUTOMATIC) {+ const sampler = cell.sampler ?? ctx.samplerChoice.sampler;+ const option = ctx.samplers.find((s) => s.id === sampler);+ if (!option?.schedule_types.includes(schedule)) {+ const label = SCHEDULE_LABELS[schedule] ?? schedule;+ return cell.schedule !== undefined+ ? `Schedule type ${label} is not available with ${option?.label ?? sampler}. Drop it, or compare only samplers that take it.`+ : `${option?.label ?? sampler} does not take the form's ${label} schedule. Set Schedule type to Automatic, or compare only samplers that take it.`;+ }+ }+ }+ return null;+}++function negativeEngaged(ctx: CompareContext, guidance: number): boolean {+ return ctx.negativeCapable && (ctx.negativeMinGuidance === null || guidance > ctx.negativeMinGuidance);+}++/** The negative prompt the grid's recipe records: the form's text when any cell runs with it engaged. */+export function gridNegativePrompt(plan: CompareGridPlan, ctx: CompareContext): string | undefined {+ const text = ctx.negativePrompt.trim();+ if (!text) return undefined;+ for (let i = 0; i < plan.cellCount; i++) {+ if (negativeEngaged(ctx, cellState(plan, i).guidance ?? ctx.guidance)) return text;+ }+ return undefined;+}++/** The cell's overrides, every axis applied in X, Y, Z order (so two Prompt S/R axes chain as in A1111). */+export function cellState(plan: CompareGridPlan, index: number): CellState {+ const cell: CellState = { loraWeights: {}, replacements: [], extra: {} };+ const c = cellCoords(plan, index);+ plan.axes.forEach((axis, a) => axis.def.apply(cell, axis.values[c[a]], axis.values));+ return cell;+}++export function cellTitle(plan: CompareGridPlan, index: number): string {+ const c = cellCoords(plan, index);+ return plan.axes+ .map((axis, a) => (axis.def.id === NOTHING ? "" : axis.labels[c[a]]))+ .filter(Boolean)+ .join(", ");+}++/** `base` is the request Generate would send for the form (text-to-image). The cell runs it at batch size 1 with+ * the prompt enhancer off (a rewrite per cell would change the thing being compared). */+export function buildCellRequest(+ plan: CompareGridPlan,+ index: number,+ base: DiffusionGenerateRequest,+ ctx: CompareContext,+ // `variation`: the run's one variation seed, for cells that set a strength without one.+ seeds: { base: number; keepRandom: boolean; seedFieldEmpty: boolean; rng?: () => number; variation?: number },+): DiffusionGenerateRequest {+ const cell = cellState(plan, index);+ const rng = seeds.rng ?? Math.random;+ const req: DiffusionGenerateRequest & Record<string, unknown> = { ...base, batch_size: 1 };+ if (req.enhance_prompt !== undefined) req.enhance_prompt = false;+ // Seed: the axis value, else one shared seed for every cell (A1111 fix_seed), unless "Keep -1 for seeds" with an+ // empty seed box, when every cell draws its own.+ if (cell.seed === "random") req.seed = Math.floor(rng() * 2 ** 32);+ else if (typeof cell.seed === "number") req.seed = cell.seed;+ else req.seed = seeds.keepRandom && seeds.seedFieldEmpty ? Math.floor(rng() * 2 ** 32) : seeds.base;+ if (cell.steps !== undefined) req.steps = cell.steps;+ if (cell.guidance !== undefined) {+ req.guidance = cell.guidance;+ const engaged =+ ctx.negativeCapable && (ctx.negativeMinGuidance === null || cell.guidance > ctx.negativeMinGuidance);+ req.negative_prompt = engaged ? ctx.negativePrompt.trim() || undefined : undefined;+ }+ if (cell.sampler !== undefined || cell.schedule !== undefined) {+ const sampler = cell.sampler ?? ctx.samplerChoice.sampler;+ const option = ctx.samplers.find((s) => s.id === sampler);+ const schedule = cell.schedule ?? ctx.samplerChoice.scheduleType;+ delete req.sampler;+ delete req.schedule_type;+ if (sampler !== "default") req.sampler = sampler;+ // planCompare refuses a Schedule axis value the sampler lacks; only the form's schedule can fall back here.+ if (schedule !== AUTOMATIC && option?.schedule_types.includes(schedule)) req.schedule_type = schedule;+ }+ if (cell.shift !== undefined) req.shift = cell.shift;+ if (cell.baseShift !== undefined) req.base_shift = cell.baseShift;+ if (cell.maxShift !== undefined) req.max_shift = cell.maxShift;+ if (Object.keys(cell.loraWeights).length > 0) {+ const loras: LoraSpecInput[] = ctx.loras+ .map((l, i) => ({ id: l.id.trim(), weight: cell.loraWeights[i] ?? l.weight }))+ .filter((l) => l.id && l.weight > 0);+ req.loras = loras.length ? loras : undefined;+ }+ if (cell.replacements.length > 0) {+ let prompt = req.prompt;+ let negative = req.negative_prompt;+ for (const [search, replace] of cell.replacements) {+ prompt = prompt.split(search).join(replace);+ if (negative !== undefined) negative = negative.split(search).join(replace);+ }+ req.prompt = prompt;+ req.negative_prompt = negative;+ }+ for (const [key, value] of Object.entries(cell.extra)) req[key] = value;+ // Variation seed without a strength means nothing to the backend: use the model's Vary strength.+ if (cell.extra.variation_seed !== undefined && cell.extra.variation_strength === undefined && !req.variation_strength) {+ req.variation_strength = ctx.sdControls?.vary_strength ?? 0.15;+ }+ // A strength with no variation seed draws a random one per request: fix one for the run (A1111 fix_seed on the+ // subseed), so a Var. strength axis compares strengths over one noise source.+ // Strength 0 cells get it too (the backend ignores it there), so the grid's recipe still shares one seed.+ if (typeof req.variation_strength === "number" && req.variation_seed === undefined && seeds.variation !== undefined) {+ req.variation_seed = seeds.variation;+ }+ return req;+}diff --git a/studio/frontend/src/features/images/compare/compare-panel.tsx b/studio/frontend/src/features/images/compare/compare-panel.tsxnew file mode 100644index 00000000000..d8fd633db1b--- /dev/null+++ b/studio/frontend/src/features/images/compare/compare-panel.tsx@@ -0,0 +1,378 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/** Compare grid controls and result. Lazily loaded by the Images page, so none of it is on the startup path. */++import { useEffect, useMemo, useRef, useState } from "react";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { InfoHint } from "@/components/ui/info-hint";+import { Input } from "@/components/ui/input";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { Switch } from "@/components/ui/switch";+import { downloadBlobStreaming, isDownloadCancelled } from "@/lib/native-files";+import { toast } from "@/lib/toast";+import { fetchGalleryBlob } from "../api";+import {+ availableAxes,+ MAX_COMPARE_CELLS,+ NOTHING,+ planCompare,+ type AxisInput,+ type CompareContext,+} from "./compare-axes";+import { createCompareRun, gridParameters, gridTitles, sliceCells, type CompareRun, type CompareRunState } from "./compare-run";+import { joinAxisList } from "./compare-values";+import { drawCellsInTurn, drawGrid, gridLayout, withPngText } from "./compose-grid";++export interface ComparePanelProps {+ context: CompareContext;+ busy: boolean;+ seedFieldEmpty: boolean;+ // The form's typed Variation seed, null when empty or the model has none.+ variationSeed: number | null;+ modelName: string | null;+ width: number;+ height: number;+ steps: number;+ guidance: number;+ onRun: (run: CompareRun) => Promise<void>;+}++interface GridResult {+ title: string;+ url: string;+ blob: Blob;+ width: number;+ height: number;+}++const AXIS_NAMES = ["X", "Y", "Z"] as const;+const EMPTY_AXES: AxisInput[] = [+ { axisId: "steps", text: "" },+ { axisId: NOTHING, text: "" },+ { axisId: NOTHING, text: "" },+];++const HINT =+ "Generate the same prompt across up to three settings and lay the results out as a labelled grid " ++ "(AUTOMATIC1111's X/Y/Z plot). Values are comma separated; number axes also take ranges: 1-5, 10-30 (+10), " ++ "1-10 [4] (four evenly spaced). Z makes one grid per value. Prompt S/R swaps its first value in the prompt for " ++ "each value in turn. Every cell runs at batch size 1 with one shared seed and is saved to the gallery with its own recipe.";++async function composeGrid(+ run: CompareRunState,+ iz: number,+ title: string,+ options: { legend: boolean; margin: number },+ infotext: string,+): Promise<GridResult | null> {+ const plan = run.plan;+ const records = sliceCells(plan, run.results, iz);+ const first = records.find(Boolean);+ if (!first) return null;+ const canvas = document.createElement("canvas");+ const ctx = canvas.getContext("2d");+ if (!ctx) return null;+ const measure = (text: string, size: number) => {+ ctx.font = `${size}px ui-sans-serif, system-ui, sans-serif`;+ return ctx.measureText(text).width;+ };+ const layout = gridLayout(+ {+ cols: plan.axes[0].values.length,+ rows: plan.axes[1].values.length,+ cellWidth: first.width,+ cellHeight: first.height,+ colLabels: plan.axes[0].labels,+ rowLabels: plan.axes[1].labels,+ title,+ legend: options.legend,+ margin: options.margin,+ },+ measure,+ );+ canvas.width = layout.width;+ canvas.height = layout.height;+ // Placeholders and labels first, then one cell at a time decoded straight to its drawn size: a 64-cell grid of+ // full-size decodes held at once would be gigabytes of RGBA.+ drawGrid(ctx, layout, records.map(() => null));+ await drawCellsInTurn(+ records,+ async (r, i) => {+ const rect = layout.cells[i];+ return createImageBitmap(await fetchGalleryBlob(r.url), {+ resizeWidth: rect.w,+ resizeHeight: rect.h,+ resizeQuality: "high",+ });+ },+ (bitmap, i) => {+ const rect = layout.cells[i];+ ctx.drawImage(bitmap, rect.x, rect.y, rect.w, rect.h);+ bitmap.close();+ },+ );+ const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, "image/png"));+ if (!blob) return null;+ const png = withPngText(new Uint8Array(await blob.arrayBuffer()), "parameters", infotext);+ const out = new Blob([Uint8Array.from(png).buffer], { type: "image/png" });+ return { title, blob: out, url: URL.createObjectURL(out), width: layout.width, height: layout.height };+}++export default function ComparePanel(props: ComparePanelProps) {+ const { context, busy } = props;+ const [enabled, setEnabled] = useState(false);+ const [axes, setAxes] = useState<AxisInput[]>(EMPTY_AXES);+ const [legend, setLegend] = useState(true);+ const [keepRandom, setKeepRandom] = useState(false);+ const [margin, setMargin] = useState(0);+ const [running, setRunning] = useState<CompareRunState | null>(null);+ const [progress, setProgress] = useState(0);+ const [grids, setGrids] = useState<GridResult[]>([]);+ const [open, setOpen] = useState(false);+ const mounted = useRef(true);+ const active = useRef(false);++ const defs = useMemo(() => availableAxes(context), [context]);+ const effective = axes.map((a) => (defs.some((d) => d.id === a.axisId) ? a : { axisId: NOTHING, text: "" }));+ // Cheap (at most 64 cells), so it runs every render; the real plan is drawn again on click for fresh seeds.+ const preview = planCompare(effective, context, { keepRandomSeeds: keepRandom, rng: () => 0 });++ useEffect(() => {+ mounted.current = true;+ return () => {+ mounted.current = false;+ };+ }, []);+ // Object URLs of replaced results are released; the last ones live as long as the page.+ useEffect(() => () => grids.forEach((g) => URL.revokeObjectURL(g.url)), [grids]);++ const setAxis = (i: number, next: Partial<AxisInput>) =>+ setAxes((prev) => prev.map((a, j) => (j === i ? { ...effective[j], ...next } : effective[j] ?? a)));+ const swap = (a: number, b: number) =>+ setAxes(() => {+ const next = [...effective];+ [next[a], next[b]] = [next[b], next[a]];+ return next;+ });++ const run = async () => {+ if (active.current) return;+ const result = planCompare(effective, context, { keepRandomSeeds: keepRandom });+ if (!result.ok) {+ toast.error(result.error);+ return;+ }+ const state = createCompareRun(result.plan, context, {+ keepRandomSeeds: keepRandom,+ seedFieldEmpty: props.seedFieldEmpty,+ variationSeed: props.variationSeed,+ });+ const tracked: CompareRunState = {+ ...state,+ onImages(i, images) {+ state.onImages(i, images);+ setProgress((n) => n + 1);+ },+ };+ active.current = true;+ setProgress(0);+ setRunning(tracked);+ // Busy until the grid is composed too: a second run composing alongside would multiply canvas memory and race+ // this one's result.+ try {+ await props.onRun(tracked);+ if (!mounted.current) return;+ const done = state.results.filter(Boolean).length;+ if (done === 0) return;+ const plan = result.plan;+ const infotext = gridParameters(plan, context, state.requests, {+ steps: props.steps,+ guidance: props.guidance,+ width: props.width,+ height: props.height,+ model: props.modelName,+ keepRandomSeeds: keepRandom,+ });+ try {+ // One Z slice at a time, for the same memory reason as the cells.+ const made: GridResult[] = [];+ const titles = gridTitles(plan);+ for (let iz = 0; iz < titles.length; iz++) {+ const grid = await composeGrid(state, iz, titles[iz], { legend, margin }, infotext);+ if (grid) made.push(grid);+ }+ if (!mounted.current) return;+ setGrids(made);+ if (made.length) setOpen(true);+ if (done < plan.cellCount) toast.info(`Grid made from ${done} of ${plan.cellCount} cells`);+ } catch (err) {+ toast.error(err instanceof Error ? `Could not build the grid: ${err.message}` : "Could not build the grid");+ }+ } finally {+ active.current = false;+ if (mounted.current) setRunning(null);+ }+ };++ const download = (g: GridResult, i: number) => {+ const stamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);+ void downloadBlobStreaming(g.blob, `compare-grid-${stamp}${grids.length > 1 ? `-${i + 1}` : ""}.png`).catch((err) => {+ // Cancelling the save dialog is not a failure; a native open / write / finalize error is.+ if (!isDownloadCancelled(err)) {+ toast.error(err instanceof Error ? `Could not save the grid: ${err.message}` : "Could not save the grid");+ }+ });+ };++ const count = preview.ok ? preview.plan.cellCount : preview.cellCount;+ const shape = preview.ok+ ? preview.plan.axes+ .filter((a) => a.def.id !== NOTHING)+ .map((a) => a.values.length)+ .join(" x ")+ : "";++ return (+ <div className="flex flex-col gap-1.5 pt-2">+ <div className="flex items-center gap-1">+ <label htmlFor="images-compare-toggle" className="text-xs font-medium text-muted-foreground">+ Compare grid+ </label>+ <InfoHint>{HINT}</InfoHint>+ <div className="ml-auto flex items-center gap-2">+ {grids.length > 0 && !running && (+ <Button type="button" variant="ghost" size="sm" className="h-6 px-2 text-xs" onClick={() => setOpen(true)}>+ Last grid+ </Button>+ )}+ <Switch id="images-compare-toggle" checked={enabled} onCheckedChange={setEnabled} aria-label="Compare grid" />+ </div>+ </div>+ {enabled && (+ <div className="space-y-2 rounded-lg border border-border bg-muted/30 p-2">+ {effective.map((axis, i) => {+ const def = defs.find((d) => d.id === axis.axisId);+ return (+ <div key={AXIS_NAMES[i]} className="flex items-center gap-1.5">+ <span className="w-3 shrink-0 text-xs font-medium text-muted-foreground">{AXIS_NAMES[i]}</span>+ <Select value={axis.axisId} onValueChange={(v) => setAxis(i, { axisId: v })}>+ <SelectTrigger className="h-8 w-32 shrink-0 text-xs" aria-label={`${AXIS_NAMES[i]} type`}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {defs.map((d) => (+ <SelectItem key={d.id} value={d.id}>+ {d.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <Input+ value={axis.axisId === NOTHING ? "" : axis.text}+ disabled={axis.axisId === NOTHING}+ placeholder={def?.placeholder}+ aria-label={`${AXIS_NAMES[i]} values`}+ onChange={(e) => setAxis(i, { text: e.target.value })}+ className="h-8 min-w-0 flex-1 text-xs"+ />+ {def?.choices && (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="h-8 shrink-0 px-2 text-xs"+ title={`Fill every ${def.label.toLowerCase()}`}+ onClick={() => setAxis(i, { text: joinAxisList(def.choices!.map((c) => c.label)) })}+ >+ All+ </Button>+ )}+ </div>+ );+ })}+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5 text-xs">+ <label className="flex items-center gap-1.5">+ <Switch size="sm" checked={legend} onCheckedChange={setLegend} />+ Draw legend+ </label>+ <label className="flex items-center gap-1.5" title="Every cell draws its own random seed when the Seed box is empty">+ <Switch size="sm" checked={keepRandom} onCheckedChange={setKeepRandom} />+ Keep -1 for seeds+ </label>+ <label className="flex items-center gap-1.5">+ Margin+ <Input+ type="number"+ min={0}+ max={200}+ step={2}+ value={margin}+ onChange={(e) => setMargin(Math.max(0, Math.min(200, Math.round(Number(e.target.value) || 0))))}+ className="h-7 w-16 text-xs"+ aria-label="Grid margin in pixels"+ />+ </label>+ <Button type="button" variant="ghost" size="sm" className="h-7 px-2 text-xs" onClick={() => swap(0, 1)}>+ Swap X/Y+ </Button>+ </div>+ <div className="flex items-center gap-2">+ <p+ className={preview.ok ? "flex-1 text-xs text-muted-foreground" : "flex-1 text-xs text-destructive"}+ role={preview.ok ? undefined : "alert"}+ >+ {running+ ? `${progress} of ${running.cellCount} cells done`+ : preview.ok+ ? `${shape} = ${count} cell${count === 1 ? "" : "s"} (limit ${MAX_COMPARE_CELLS})`+ : preview.error}+ </p>+ <Button type="button" size="sm" disabled={busy || running !== null || !preview.ok} onClick={() => void run()}>+ {preview.ok ? `Generate grid (${count})` : "Generate grid"}+ </Button>+ </div>+ </div>+ )}+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogContent className="corner-squircle dialog-soft-surface gap-4 sm:max-w-5xl">+ <DialogHeader>+ <DialogTitle>Compare grid</DialogTitle>+ <DialogDescription>+ Each cell is also in the gallery with its own recipe. The PNG carries the grid's parameters.+ </DialogDescription>+ </DialogHeader>+ <div className="max-h-[70dvh] space-y-4 overflow-auto">+ {grids.map((g, i) => (+ <figure key={g.url} className="space-y-2">+ <img src={g.url} alt={g.title || "Compare grid"} className="mx-auto max-w-full rounded-md" />+ <figcaption className="flex items-center justify-between gap-2 text-xs text-muted-foreground">+ <span>+ {g.title ? `${g.title}, ` : ""}+ {g.width} x {g.height}+ </span>+ <Button type="button" size="sm" variant="secondary" onClick={() => download(g, i)}>+ Download PNG+ </Button>+ </figcaption>+ </figure>+ ))}+ </div>+ </DialogContent>+ </Dialog>+ </div>+ );+}diff --git a/studio/frontend/src/features/images/compare/compare-run.ts b/studio/frontend/src/features/images/compare/compare-run.tsnew file mode 100644index 00000000000..30394367c22--- /dev/null+++ b/studio/frontend/src/features/images/compare/compare-run.ts@@ -0,0 +1,235 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/** One compare run as the page's Generate loop sees it: N runs, each with its own request, reporting its records+ * back. The page keeps owning progress polling, Stop, the gallery merge and error toasts. */++import type { ControlNetSpecInput, DiffusionGenerateRequest, GalleryImage } from "../api.ts";+import { SAMPLER_LABELS, SCHEDULE_LABELS } from "../lib/sampler-choice.ts";+import { gridInfotext } from "./compose-grid.ts";+import { joinAxisList } from "./compare-values.ts";+import {+ buildCellRequest,+ gridNegativePrompt,+ cellTitle,+ NOTHING,+ type CompareContext,+ type CompareGridPlan,+} from "./compare-axes.ts";++export interface CompareRun {+ readonly cellCount: number;+ request(run: number, base: DiffusionGenerateRequest, baseSeed: number): DiffusionGenerateRequest;+ title(done: number): string;+ onImages(run: number, images: readonly GalleryImage[]): void;+ // The seed run `run` was actually sent with (a Seed axis or Keep -1 replaces the form's).+ sentSeed(run: number): number | undefined;+}++export interface CompareRunState extends CompareRun {+ readonly plan: CompareGridPlan;+ // By cell index (ix + iy*nx + iz*nx*ny), null until that cell lands.+ readonly results: Array<GalleryImage | null>;+ readonly requests: Array<DiffusionGenerateRequest | null>;+}++export function createCompareRun(+ plan: CompareGridPlan,+ ctx: CompareContext,+ // `variationSeed`: the form's typed Variation seed (null = the field is empty), used even when the form's strength+ // is 0 because a Var. strength axis supplies it.+ options: { keepRandomSeeds: boolean; seedFieldEmpty: boolean; rng?: () => number; variationSeed?: number | null },+): CompareRunState {+ const results: Array<GalleryImage | null> = Array.from({ length: plan.cellCount }, () => null);+ const requests: Array<DiffusionGenerateRequest | null> = Array.from({ length: plan.cellCount }, () => null);+ // One variation seed per run: the typed one, else drawn up front; "Keep -1 for seeds" with an empty seed box keeps+ // it random per cell too.+ const variation =+ options.variationSeed ??+ (options.keepRandomSeeds && options.seedFieldEmpty ? undefined : Math.floor((options.rng ?? Math.random)() * 2 ** 32));+ return {+ plan,+ results,+ requests,+ cellCount: plan.cellCount,+ request(run, base, baseSeed) {+ const cell = plan.order[run];+ const req = buildCellRequest(plan, cell, base, ctx, {+ base: baseSeed,+ keepRandom: options.keepRandomSeeds,+ seedFieldEmpty: options.seedFieldEmpty,+ rng: options.rng,+ variation,+ });+ requests[cell] = req;+ return req;+ },+ title(done) {+ const cell = plan.order[Math.min(done, plan.cellCount - 1)];+ const label = cellTitle(plan, cell);+ return `Cell ${Math.min(done + 1, plan.cellCount)}/${plan.cellCount}${label ? `: ${label}` : ""}`;+ },+ sentSeed(run) {+ const cell = plan.order[run];+ return cell === undefined ? undefined : requests[cell]?.seed;+ },+ onImages(run, images) {+ const cell = plan.order[run];+ if (cell === undefined) return;+ // A lost-response recovery passes every record the gallery gained: the cell's own carries its seed.+ const seed = requests[cell]?.seed;+ const own = images.find((image) => image.seed === seed) ?? (images.length === 1 ? images[0] : undefined);+ if (own) results[cell] = own;+ },+ };+}++/** Cells of one Z slice, row-major (ix + iy * nx). */+export function sliceCells<T>(plan: CompareGridPlan, items: readonly T[], iz: number): T[] {+ const nx = plan.axes[0].values.length;+ const ny = plan.axes[1].values.length;+ return items.slice(iz * nx * ny, (iz + 1) * nx * ny);+}++export function gridTitles(plan: CompareGridPlan): string[] {+ const z = plan.axes[2];+ return z.def.id === NOTHING ? [""] : z.labels;+}++export function completedCells(run: CompareRunState): number {+ return run.results.filter(Boolean).length;+}++/** The value every sent cell agrees on for `key`, or none when an axis varies it or any two cells differ (a+ * schedule a sampler fell back from, a per-cell random seed, a Seed axis). `{ value: undefined }` = every cell+ * omitted it. Cells are compared through `same` (each cell's request is built afresh, so objects by content). */+function sharedValue(+ sent: ReadonlyArray<Readonly<Record<string, unknown>>>,+ varied: ReadonlySet<string>,+ key: string,+ axisId: string = key,+ same: (a: unknown, b: unknown) => boolean = Object.is,+): { value: unknown } | null {+ if (varied.has(axisId) || sent.length === 0) return null;+ const value = sent[0][key];+ return sent.every((r) => same(r[key], value)) ? { value } : null;+}++// A ControlNet unit by every field it is sent with, the control image included.+const sameControlNet = (a: unknown, b: unknown): boolean => {+ const x = a as ControlNetSpecInput | undefined;+ const y = b as ControlNetSpecInput | undefined;+ if (!x || !y) return x === y;+ return (+ x.id === y.id &&+ x.image === y.image &&+ x.control_type === y.control_type &&+ x.strength === y.strength &&+ x.guidance_start === y.guidance_start &&+ x.guidance_end === y.guidance_end+ );+};++const scalar = (value: unknown): string | number | undefined =>+ typeof value === "string" || typeof value === "number" ? value : undefined;++/** sd-webui-controlnet's `ControlNet 0` unit text, without the control image (supplied again on import). */+function controlNetUnit(value: unknown): string | undefined {+ const cn = value as ControlNetSpecInput | undefined;+ if (!cn?.id) return undefined;+ const parts = [`Module: ${cn.control_type}`, `Model: ${cn.id}`, `Weight: ${cn.strength}`];+ if (cn.guidance_start !== undefined) parts.push(`Guidance Start: ${cn.guidance_start}`);+ if (cn.guidance_end !== undefined) parts.push(`Guidance End: ${cn.guidance_end}`);+ return parts.join(", ");+}++/** The grid's shared recipe for its `parameters` chunk, from the requests the cells were sent with: a field is+ * written only when every cell ran the same value, so the PNG never claims one cell's setting for the grid. */+export function gridRecipeFields(+ plan: CompareGridPlan,+ requests: ReadonlyArray<DiffusionGenerateRequest | null | undefined>,+ form: { steps: number; guidance: number; width: number; height: number; model: string | null },+): Array<[string, string | number | null | undefined]> {+ const varied = new Set(plan.axes.map((a) => a.def.id));+ const sent = requests.filter((r): r is DiffusionGenerateRequest => Boolean(r)) as unknown as Array<+ Record<string, unknown>+ >;+ const shared = (key: string, axisId?: string) => scalar(sharedValue(sent, varied, key, axisId)?.value);+ const sampler = sharedValue(sent, varied, "sampler");+ const schedule = shared("schedule_type", "schedule");+ const width = shared("width");+ const height = shared("height");+ const fields: Array<[string, string | number | null | undefined]> = [+ ["Steps", sent.length ? shared("steps") : form.steps],+ ["Sampler", sampler ? (SAMPLER_LABELS[String(sampler.value ?? "default")] ?? scalar(sampler.value)) : undefined],+ ["Schedule type", schedule ? (SCHEDULE_LABELS[String(schedule)] ?? schedule) : undefined],+ ["Shift", shared("shift")],+ ["Base shift", shared("base_shift")],+ ["Max shift", shared("max_shift")],+ ["CFG scale", sent.length ? shared("guidance") : form.guidance],+ ["Seed", shared("seed")],+ ["Variation seed", shared("variation_seed")],+ ["Variation seed strength", shared("variation_strength")],+ // The backend's own infotext names (core/inference/image_gallery.py).+ ["Clip skip", shared("clip_skip")],+ ["CFG rescale", shared("cfg_rescale")],+ ["Emphasis", sharedValue(sent, varied, "prompt_weighting")?.value === false ? "None" : undefined],+ // The fitted size the cells ran at, not the form's (Generate may shrink it to the model's pixel limit).+ ["Size", sent.length ? (width && height ? `${width}x${height}` : undefined) : `${form.width}x${form.height}`],+ ["Model", form.model],+ // Every cell is conditioned the same way; the control image itself is not embedded.+ ["ControlNet 0", controlNetUnit(sharedValue(sent, varied, "controlnet", "controlnet", sameControlNet)?.value)],+ // Every cell runs with the prompt enhancer off (compare/ forces it), so a restore must not rewrite the prompt.+ ["Prompt enhancement", sharedValue(sent, varied, "enhance_prompt")?.value === false ? "off" : undefined],+ ];+ return fields.filter(([, value]) => value !== undefined);+}++/** The grid's active LoRAs as one `LoRAs: id: weight, ...` field at the first cell's weights. Studio ids, Hub ones+ * included, restore exactly from it; A1111 `<lora:...>` prompt tags would match local adapters only. */+export function gridLoraField(+ ctx: Pick<CompareContext, "loraCapable" | "loras">,+ first: DiffusionGenerateRequest | null | undefined,+): string | null {+ if (!ctx.loraCapable) return null;+ const items: string[] = [];+ for (const row of ctx.loras) {+ const id = row.id.trim();+ if (!id) continue;+ items.push(`${id}: ${first?.loras?.find((l) => l.id === id)?.weight ?? 0}`);+ }+ // CSV-quoted where an id holds a comma or quote, so every id splits back out exactly.+ return items.length ? joinAxisList(items) : null;+}++const AXIS_NAMES = ["X", "Y", "Z"] as const;++/** The grid PNG's A1111-style `parameters`: the prompt, the negative prompt when any+ * cell engages it (the first cell may not), the shared recipe, then the axes. */+export function gridParameters(+ plan: CompareGridPlan,+ ctx: CompareContext,+ requests: ReadonlyArray<DiffusionGenerateRequest | null | undefined>,+ form: { steps: number; guidance: number; width: number; height: number; model: string | null; keepRandomSeeds: boolean },+): string {+ const fields = gridRecipeFields(plan, requests, form);+ const first = requests.find(Boolean);+ const loras = gridLoraField(ctx, first);+ if (loras) fields.push(["LoRAs", loras]);+ const axes = plan.axes+ .map((a, i) => ({ a, name: AXIS_NAMES[i] }))+ .filter(({ a }) => a.def.id !== NOTHING)+ .map(({ a, name }) => ({+ name,+ type: a.def.label,+ text: a.text,+ fixed: a.def.id === "seed" && !form.keepRandomSeeds ? a.values : undefined,+ }));+ const prompt = ctx.prompt.trim();+ return gridInfotext({+ prompt,+ negativePrompt: gridNegativePrompt(plan, ctx),+ fields,+ axes,+ });+}diff --git a/studio/frontend/src/features/images/compare/compare-values.ts b/studio/frontend/src/features/images/compare/compare-values.tsnew file mode 100644index 00000000000..621e04d1fa4--- /dev/null+++ b/studio/frontend/src/features/images/compare/compare-values.ts@@ -0,0 +1,150 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/** Axis value syntax of AUTOMATIC1111's X/Y/Z plot (scripts/xyz_grid.py, process_axis):+ * - a comma (or newline) separated list, CSV quoting allowed: `euler, "a, b", dpmpp_2m`+ * - an integer or decimal range `1-5`, with a step `1-9 (+2)` or `10-1 (-3)`+ * - a range with a count `1-10 [4]`, evenly spaced (numpy.linspace), truncated for integer axes+ * Two deliberate differences: a descending range keeps its end (`5-1 (-1)` is 5..1, A1111 stops at 3), and a+ * decimal step may omit its sign (`0-1 (0.25)`). */++export type AxisValueType = "int" | "float" | "str";++export type ParsedValues =+ | { ok: true; values: Array<number | string> }+ | { ok: false; error: string };++// One more than A1111's own limit would never matter here: the grid is capped far below this.+const MAX_EXPANDED = 1000;++const NUM = String.raw`[+-]?\s*\d+(?:\.\d*)?`;+const INT = String.raw`[+-]?\s*\d+`;+const INT_RANGE = new RegExp(String.raw`^\s*(${INT})\s*-\s*(${INT})(?:\s*\(\s*([+-]?\s*\d+)\s*\))?\s*$`);+const INT_COUNT = new RegExp(String.raw`^\s*(${INT})\s*-\s*(${INT})\s*\[\s*(\d+)\s*\]\s*$`);+const FLOAT_RANGE = new RegExp(+ String.raw`^\s*(${NUM})\s*-\s*(${NUM})(?:\s*\(\s*([+-]?\s*\d+(?:\.\d*)?)\s*\))?\s*$`,+);+const FLOAT_COUNT = new RegExp(String.raw`^\s*(${NUM})\s*-\s*(${NUM})\s*\[\s*(\d+)\s*\]\s*$`);++// A space may follow a sign (A1111's `[+-]?\s*\d+`); anywhere else inside a number it is a typo (`1 2`, `1 e2`).+const literal = (text: string): string => text.trim().replace(/^([+-])\s+/, "$1");+const num = (text: string): number => {+ const t = literal(text);+ return /\s/.test(t) ? Number.NaN : Number(t);+};++/** Labels and requests use the same rounding as A1111's format_value (8 decimals), so 0.1+0.2 reads 0.3. */+export function roundValue(value: number): number {+ return Number(value.toFixed(8));+}++/** csv.reader(skipinitialspace=True) over every line, each field stripped; empty fields are kept here and dropped by+ * the typed expansion, as A1111 does for numbers. */+export function splitAxisList(text: string): string[] {+ const out: string[] = [];+ let field = "";+ let quoted = false;+ let atStart = true;+ // csv.reader yields no field for a blank line, so a trailing newline adds no empty item.+ let lineHasField = false;+ for (let i = 0; i < text.length; i++) {+ const ch = text[i];+ if (quoted) {+ if (ch === '"') {+ if (text[i + 1] === '"') {+ field += '"';+ i++;+ } else {+ quoted = false;+ }+ } else {+ field += ch;+ }+ continue;+ }+ if (ch === '"' && atStart) {+ lineHasField = true;+ quoted = true;+ atStart = false;+ continue;+ }+ if (ch === "," || ch === "\n" || ch === "\r") {+ if (ch === ",") lineHasField = true;+ if (ch === "," || lineHasField || field.trim()) out.push(field.trim());+ field = "";+ atStart = true;+ if (ch !== ",") lineHasField = false;+ continue;+ }+ if (atStart && (ch === " " || ch === "\t")) continue;+ atStart = false;+ field += ch;+ }+ if (lineHasField || field.trim()) out.push(field.trim());+ return out;+}++function linspace(start: number, end: number, count: number): number[] {+ if (count <= 0) return [];+ if (count === 1) return [start];+ const step = (end - start) / (count - 1);+ return Array.from({ length: count }, (_, i) => (i === count - 1 ? end : start + step * i));+}++function inclusiveRange(start: number, end: number, step: number): number[] | null {+ if (step === 0 || !Number.isFinite(step)) return null;+ if ((end - start) / step < 0) return [];+ const count = Math.floor((end - start) / step + 1e-9) + 1;+ if (count > MAX_EXPANDED) return null;+ return Array.from({ length: count }, (_, i) => start + step * i);+}++/** Parse one axis's text into typed values. `str` axes keep each list item as typed (no range expansion); empty+ * items are dropped unless `keepEmpty`. */+export function parseAxisValues(text: string, type: AxisValueType, options: { keepEmpty?: boolean } = {}): ParsedValues {+ const items = splitAxisList(text);+ if (type === "str") {+ // Prompt S/R keeps an empty replacement (A1111 csv_string_to_list_strip drops nothing): `red, ""` compares the+ // prompt with the search text removed. Its first value is what it searches for, so that one cannot be empty.+ if (options.keepEmpty) {+ if (items.length === 0 || !items[0]) return { ok: false, error: items.some(Boolean) ? "The first value (searched for) is empty" : "No values" };+ return { ok: true, values: items };+ }+ const values = items.filter((v) => v.length > 0);+ return values.length ? { ok: true, values } : { ok: false, error: "No values" };+ }+ const values: number[] = [];+ for (const item of items) {+ if (!item) continue;+ const isInt = type === "int";+ const range = (isInt ? INT_RANGE : FLOAT_RANGE).exec(item);+ const counted = range ? null : (isInt ? INT_COUNT : FLOAT_COUNT).exec(item);+ if (range) {+ const start = num(range[1]);+ const end = num(range[2]);+ const step = range[3] !== undefined ? num(range[3]) : end >= start ? 1 : -1;+ const expanded = inclusiveRange(start, end, step);+ if (expanded === null) return { ok: false, error: `Bad range step in "${item}"` };+ values.push(...expanded.map(isInt ? Math.trunc : roundValue));+ } else if (counted) {+ const count = Number(counted[3]);+ if (count > MAX_EXPANDED) return { ok: false, error: `Too many values in "${item}"` };+ const spaced = linspace(num(counted[1]), num(counted[2]), count);+ values.push(...spaced.map(isInt ? Math.trunc : roundValue));+ } else {+ const value = num(item);+ if (!Number.isFinite(value) || !/^[+-]?\d*\.?\d+(?:e[+-]?\d+)?$|^[+-]?\d+\.$/i.test(literal(item))) {+ return { ok: false, error: `"${item}" is not a number` };+ }+ if (isInt && !Number.isInteger(value)) return { ok: false, error: `"${item}" is not a whole number` };+ values.push(isInt ? value : roundValue(value));+ }+ if (values.length > MAX_EXPANDED) return { ok: false, error: "Too many values" };+ }+ return values.length ? { ok: true, values } : { ok: false, error: "No values" };+}++/** CSV-quote a list back into the box (A1111 list_to_csv_string), for the fill button and swaps. */+export function joinAxisList(values: readonly string[]): string {+ return values.map((v) => (/[",\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v)).join(", ");+}diff --git a/studio/frontend/src/features/images/compare/compose-grid.ts b/studio/frontend/src/features/images/compare/compose-grid.tsnew file mode 100644index 00000000000..adb4e4b2149--- /dev/null+++ b/studio/frontend/src/features/images/compare/compose-grid.ts@@ -0,0 +1,262 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/** The labelled grid image: layout after AUTOMATIC1111's images.draw_grid_annotations (font size (w + h) / 25,+ * row labels in a left band 3/4 of a cell wide, column labels above, margin between cells), plus the Z value as a+ * title band. Layout is pure (tests pass a fake text measure); drawing needs a 2D canvas. */++export type MeasureText = (text: string, fontSize: number) => number;++export interface GridLayoutInput {+ cols: number;+ rows: number;+ cellWidth: number;+ cellHeight: number;+ colLabels: readonly string[];+ rowLabels: readonly string[];+ title: string;+ legend: boolean;+ margin: number;+}++export interface TextBlock {+ x: number; // centre+ y: number; // top of the first line+ lines: string[];+}++export interface GridLayout {+ width: number;+ height: number;+ scale: number;+ fontSize: number;+ lineHeight: number;+ cellWidth: number;+ cellHeight: number;+ cells: Array<{ x: number; y: number; w: number; h: number }>; // index ix + iy * cols+ colText: TextBlock[];+ rowText: TextBlock[];+ title: TextBlock | null;+}++// Chromium / Safari refuse a canvas side above 16384 px. The area is held to a memory budget well under their 2^28+// ceiling: 32 Mpx is 128 MiB of RGBA backing store, before the PNG encode, which mobile browsers can still allocate.+export const MAX_CANVAS_SIDE = 16384;+export const MAX_CANVAS_PIXELS = 32 * 1024 * 1024;++export function wrapText(text: string, maxWidth: number, fontSize: number, measure: MeasureText): string[] {+ if (!text) return [];+ const lines: string[] = [];+ for (const paragraph of text.split("\n")) {+ let line = "";+ for (const word of paragraph.split(/\s+/).filter(Boolean)) {+ const next = line ? `${line} ${word}` : word;+ if (line && measure(next, fontSize) > maxWidth) {+ lines.push(line);+ line = word;+ } else {+ line = next;+ }+ }+ if (line) lines.push(line);+ }+ return lines;+}++function clampLines(lines: string[], max: number): string[] {+ return lines.length <= max ? lines : [...lines.slice(0, max - 1), `${lines[max - 1]}\u2026`];+}++function layoutAt(input: GridLayoutInput, cellWidth: number, cellHeight: number, measure: MeasureText, scale: number): GridLayout {+ const { cols, rows, legend } = input;+ const margin = Math.round(Math.max(0, input.margin) * scale);+ const fontSize = Math.max(10, Math.round((cellWidth + cellHeight) / 25));+ const lineHeight = Math.round(fontSize * 1.25);+ const gap = Math.round(fontSize / 2);+ const hasCol = legend && input.colLabels.some(Boolean);+ const hasRow = legend && input.rowLabels.some(Boolean);+ const hasTitle = legend && Boolean(input.title);+ const padLeft = hasRow ? Math.floor((cellWidth * 3) / 4) : 0;+ const gridWidth = cols * cellWidth + (cols - 1) * margin;+ // A label band is never taller than a cell, so shrinking the cells always shrinks the grid (an overlong label+ // is cut with an ellipsis instead of growing the canvas past its limits).+ const maxLines = Math.max(1, Math.floor(cellHeight / lineHeight));+ const colLines = hasCol ? input.colLabels.map((t) => clampLines(wrapText(t, cellWidth - gap, fontSize, measure), maxLines)) : [];+ const rowLines = hasRow ? input.rowLabels.map((t) => clampLines(wrapText(t, padLeft - gap, fontSize, measure), maxLines)) : [];+ const titleLines = hasTitle+ ? clampLines(wrapText(input.title, padLeft + gridWidth - 2 * gap, fontSize, measure), maxLines)+ : [];+ const padTop = hasCol ? Math.max(1, ...colLines.map((l) => l.length)) * lineHeight + gap * 2 : 0;+ const titleHeight = hasTitle ? titleLines.length * lineHeight + gap * 2 : 0;+ const top = titleHeight + padTop;+ const width = padLeft + gridWidth;+ const height = top + rows * cellHeight + (rows - 1) * margin;+ const cells = [];+ for (let iy = 0; iy < rows; iy++) {+ for (let ix = 0; ix < cols; ix++) {+ cells.push({ x: padLeft + ix * (cellWidth + margin), y: top + iy * (cellHeight + margin), w: cellWidth, h: cellHeight });+ }+ }+ const colText = colLines.map((lines, ix) => ({+ x: padLeft + ix * (cellWidth + margin) + cellWidth / 2,+ y: titleHeight + (padTop - lines.length * lineHeight) / 2,+ lines,+ }));+ const rowText = rowLines.map((lines, iy) => ({+ x: padLeft / 2,+ y: top + iy * (cellHeight + margin) + (cellHeight - lines.length * lineHeight) / 2,+ lines,+ }));+ const title = hasTitle ? { x: width / 2, y: gap, lines: titleLines } : null;+ return { width, height, scale, fontSize, lineHeight, cellWidth, cellHeight, cells, colText, rowText, title };+}++const fitScale = (layout: GridLayout): number =>+ Math.min(+ 1,+ MAX_CANVAS_SIDE / layout.width,+ MAX_CANVAS_SIDE / layout.height,+ Math.sqrt(MAX_CANVAS_PIXELS / (layout.width * layout.height)),+ );++/** Cells shrink (never grow) until the whole grid fits a browser canvas and the pixel budget. Narrower cells rewrap+ * their labels onto more lines, so each shrunk layout is checked again until it fits. */+export function gridLayout(input: GridLayoutInput, measure: MeasureText): GridLayout {+ let layout = layoutAt(input, input.cellWidth, input.cellHeight, measure, 1);+ let s = 1;+ for (let i = 0; i < 40 && fitScale(layout) < 1; i++) {+ // A little under, so the re-derived label bands are less likely to push it back over.+ s *= fitScale(layout) * 0.98;+ layout = layoutAt(+ input,+ Math.max(1, Math.floor(input.cellWidth * s)),+ Math.max(1, Math.floor(input.cellHeight * s)),+ measure,+ s,+ );+ }+ // Cannot happen with bounded label bands; refused here rather than failing inside canvas allocation.+ if (fitScale(layout) < 1) throw new Error(`the grid is too large to draw (${layout.width}x${layout.height})`);+ return layout;+}++const FONT = 'ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif';++/** Draw the grid; `images[i]` null = a cell that did not run (stopped or failed), drawn as a grey placeholder. */+export function drawGrid(+ ctx: CanvasRenderingContext2D,+ layout: GridLayout,+ images: ReadonlyArray<CanvasImageSource | null>,+): void {+ ctx.fillStyle = "#ffffff";+ ctx.fillRect(0, 0, layout.width, layout.height);+ layout.cells.forEach((cell, i) => {+ const image = images[i];+ if (image) {+ ctx.drawImage(image, cell.x, cell.y, cell.w, cell.h);+ return;+ }+ ctx.fillStyle = "#d4d4d4";+ ctx.fillRect(cell.x, cell.y, cell.w, cell.h);+ ctx.fillStyle = "#525252";+ ctx.font = `${layout.fontSize}px ${FONT}`;+ ctx.textAlign = "center";+ ctx.textBaseline = "middle";+ ctx.fillText("not generated", cell.x + cell.w / 2, cell.y + cell.h / 2);+ });+ ctx.fillStyle = "#000000";+ ctx.textAlign = "center";+ ctx.textBaseline = "top";+ ctx.font = `${layout.fontSize}px ${FONT}`;+ const blocks = [...layout.colText, ...layout.rowText];+ for (const block of blocks) {+ block.lines.forEach((line, j) => ctx.fillText(line, block.x, block.y + j * layout.lineHeight));+ }+ if (layout.title) {+ ctx.font = `bold ${layout.fontSize}px ${FONT}`;+ const t = layout.title;+ t.lines.forEach((line, j) => ctx.fillText(line, t.x, t.y + j * layout.lineHeight));+ }+}++/** Decode and draw cells strictly one after another, so at most one decoded cell exists at a time. A cell that is+ * missing or fails to decode keeps the placeholder already drawn. */+export async function drawCellsInTurn<R, B>(+ records: ReadonlyArray<R | null>,+ load: (record: R, index: number) => Promise<B>,+ draw: (bitmap: B, index: number) => void,+): Promise<number> {+ let drawn = 0;+ for (let i = 0; i < records.length; i++) {+ const record = records[i];+ if (!record) continue;+ let bitmap: B;+ try {+ bitmap = await load(record, i);+ } catch {+ continue;+ }+ draw(bitmap, i);+ drawn++;+ }+ return drawn;+}++const CRC_TABLE = (() => {+ const table = new Uint32Array(256);+ for (let n = 0; n < 256; n++) {+ let c = n;+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;+ table[n] = c >>> 0;+ }+ return table;+})();++function crc32(bytes: Uint8Array): number {+ let c = 0xffffffff;+ for (const b of bytes) c = CRC_TABLE[(c ^ b) & 0xff] ^ (c >>> 8);+ return (c ^ 0xffffffff) >>> 0;+}++/** `png` with an uncompressed iTXt chunk (UTF-8, so any prompt survives) right after IHDR. Not a PNG: unchanged. */+export function withPngText(png: Uint8Array, keyword: string, text: string): Uint8Array {+ const SIG = [137, 80, 78, 71, 13, 10, 26, 10];+ if (png.length < 33 || SIG.some((b, i) => png[i] !== b)) return png;+ const ihdrEnd = 8 + 12 + 13;+ const enc = new TextEncoder();+ const body = new Uint8Array([...enc.encode(keyword), 0, 0, 0, 0, 0, ...enc.encode(text)]);+ const chunk = new Uint8Array(12 + body.length);+ const view = new DataView(chunk.buffer);+ view.setUint32(0, body.length);+ chunk.set(enc.encode("iTXt"), 4);+ chunk.set(body, 8);+ view.setUint32(8 + body.length, crc32(chunk.subarray(4, 8 + body.length)));+ const out = new Uint8Array(png.length + chunk.length);+ out.set(png.subarray(0, ihdrEnd), 0);+ out.set(chunk, ihdrEnd);+ out.set(png.subarray(ihdrEnd), ihdrEnd + chunk.length);+ return out;+}++const quote = (v: string) => (/[,:"\n]/.test(v) ? JSON.stringify(v) : v);++/** A1111-style `parameters` for the grid: the shared recipe, then `Script: X/Y/Z plot` and each axis's type and+ * values (A1111 xyz_grid.py Script.run, the grid infotext). */+export function gridInfotext(input: {+ prompt: string;+ negativePrompt?: string;+ fields: ReadonlyArray<[string, string | number | null | undefined]>;+ axes: ReadonlyArray<{ name: string; type: string; text: string; fixed?: readonly (string | number)[] }>;+}): string {+ const parts: string[] = [];+ for (const [key, value] of input.fields) if (value !== null && value !== undefined && value !== "") parts.push(`${key}: ${quote(String(value))}`);+ parts.push("Script: X/Y/Z plot");+ for (const axis of input.axes) {+ parts.push(`${axis.name} Type: ${quote(axis.type)}`, `${axis.name} Values: ${quote(axis.text)}`);+ if (axis.fixed) parts.push(`Fixed ${axis.name} Values: ${quote(axis.fixed.join(", "))}`);+ }+ const lines = [input.prompt];+ if (input.negativePrompt) lines.push(`Negative prompt: ${input.negativePrompt}`);+ lines.push(parts.join(", "));+ return lines.join("\n");+}diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsxindex dd62e27a8d9..26ba6c4ea13 100644--- a/studio/frontend/src/features/images/images-page.tsx+++ b/studio/frontend/src/features/images/images-page.tsx@@ -4,6 +4,11 @@import { generationFailureLogsAction } from "@/features/settings/lib/view-logs-action";import { readImageModel, redirectRetiredImagePick, rememberImageModel, matchesRememberedModel, componentFilesMatch, type RememberedImageModel } from "./image-model-recall";import { componentFileFields, splitComponentFileList } from "./component-files";+import type { CompareContext } from "./compare/compare-axes";+import type { CompareRun } from "./compare/compare-run";+// Statically imported: this page is already its own lazy chunk, and a nested import() of the panel split modules+// the startup set shares out of their eager chunks (+3 startup chunks, measured with bundle:check).+import ComparePanel from "./compare/compare-panel";import {type DragEvent,type ReactNode,@@ -267,6 +272,7 @@ import {type ControlNetSpecInput,type DiffusionControlNetInfo,type DiffusionGenerateProgress,+ type DiffusionGenerateRequest,type DiffusionGenerateResponse,type DiffusionLoadProgress,type DiffusionLoadRequest,@@ -834,6 +840,17 @@ const IDLE_PROGRESS: DiffusionLoadProgress = {// What the load toast shows while the backend saves the chat model's context ahead of this load.const SAVING_PROGRESS: DiffusionLoadProgress = { ...IDLE_PROGRESS, phase: "saving_chat_context" };++// The request one Generate run sends: a compare cell's own, else the form's.+function compareRequest(+ run: CompareRun | null,+ i: number,+ baseSeed: number,+ body: DiffusionGenerateRequest,+): DiffusionGenerateRequest {+ return run ? run.request(i, body, baseSeed) : body;+}+// One row: label, track, value. The Images sliders are Chat ParamSlider, so both pages share one// control.function SliderField({@@ -1836,6 +1853,8 @@ export function ImagesPage({const [livePreviewOff, setLivePreviewOff] = usePersistedToggle("unsloth_images_live_preview_off");const livePreview = !livePreviewOff;const oversizedOnce = useRef(false);+ // The compare grid run handleGenerate is to send instead of the form's runs (compare/).+ const compareOnce = useRef<CompareRun | null>(null);const [sdChoice, setSdChoice] = useState<SdControlsChoice>(DEFAULT_SD_CONTROLS);// Set by Vary for the next Generate only: the seed to keep and the variation seed to slerp toward.const varyOnce = useRef<{ seed: number; variationSeed: number; strength: number } | null>(null);@@ -5310,7 +5329,9 @@ export function ImagesPage({? { ...sdChoice, variationSeed: String(vary.variationSeed), variationStrength: vary.strength }: sdChoice;const varying = Boolean(sdCaps?.variation_seed) && workflow === "create" && runChoice.variationStrength > 0;- if (varying && runChoice.variationSeed.trim() && parseVariationSeed(runChoice.variationSeed) === null) {+ // A compare grid checks it at any form strength: a Var. strength axis can engage it with the form's at 0.+ const checkVariation = varying || (compareOnce.current !== null && Boolean(sdCaps?.variation_seed));+ if (checkVariation && runChoice.variationSeed.trim() && parseVariationSeed(runChoice.variationSeed) === null) {toast.error("Variation seed must be an integer from 0 to 4294967295");return;}@@ -5330,10 +5351,14 @@ export function ImagesPage({// A large run count is legitimate, so no upper cap: floor at 1 and ignore non-numeric input.const runs = Number.isFinite(count) && count >= 1 ? Math.floor(count) : 1;if (runs !== count) setCount(runs);+ // A compare grid sends one request per cell, in the order compare/ chose.+ const compare = compareOnce.current;+ const runTotal = compare ? compare.cellCount : runs;// An explicit seed near the 2**53-1 backend cap can overflow once the per-run and in-batch- // offsets are added, 422ing a later run after earlier images generated. Fail before GPU work.- if (baseSeed > Number.MAX_SAFE_INTEGER - (runs * batchSize - 1)) {+ // offsets are added, 422ing a later run after earlier images generated. Fail before GPU work. A compare grid adds+ // no offset (every cell runs at batch size 1 on the base seed or its Seed axis value, both already in range).+ if (!compare && baseSeed > Number.MAX_SAFE_INTEGER - (runs * batchSize - 1)) {toast.error("Seed too large for this run count and batch size; use a smaller seed");return;}@@ -5386,7 +5411,7 @@ export function ImagesPage({// arrive: settleLostGeneration proves a lost POST landed by finding a record outside it.const knownIds = new Set(galleryCache.images.map((image) => image.id));try {- for (let i = 0; i < runs; i++) {+ for (let i = 0; i < runTotal; i++) {// Stop issuing more GPU generations once the page unmounted or Stop was pressed: the backend// cancel only reaches the denoise in flight, so a count > 1 request would run on.if (@@ -5409,7 +5434,7 @@ export function ImagesPage({const runBaseSeed = varying ? baseSeed : baseSeed + i * batchSize;let res: DiffusionGenerateResponse;try {- res = await generateDiffusionImage({+ res = await generateDiffusionImage(compareRequest(compare, i, baseSeed, {prompt: prompt.trim(),// Only send a negative prompt when guidance uses it, so the recipe does not record one the model ignored.negative_prompt: negativeEngaged ? negativePrompt.trim() || undefined : undefined,@@ -5434,7 +5459,9 @@ export function ImagesPage({...sdControlsRequestFields(sdCaps,runChoice,- baseVariationSeed !== null ? (baseVariationSeed + i * batchSize) % 2 ** 32 : null,+ // A compare grid keeps the form's variation seed for every cell (its axis, if any, replaces it), so+ // only the swept setting differs between cells.+ baseVariationSeed !== null ? (baseVariationSeed + (compare ? 0 : i * batchSize)) % 2 ** 32 : null,varying,!controlnetEngaged,),@@ -5461,7 +5488,7 @@ export function ImagesPage({}: undefined,...(external && { provider_id: external.providerId, model: external.modelId }),- });+ }));} catch (err) {// The POST response was lost while the backend kept generating (the secure-mode tunnel caps// the response near 100s). Retrying would duplicate the work, so wait the run out.@@ -5471,11 +5498,13 @@ export function ImagesPage({await settleLostGeneration(() => isMounted.current, probeBaseline);if (!isMounted.current) break;await loadGallery();+ // A compare cell takes its record from what the gallery gained (matched by seed in compare/).+ compare?.onImages(i, galleryCache.images.filter((image) => !knownIds.has(image.id)));// loadGallery refreshes the module cache synchronously, so this run's records are folded in// before the next run.galleryCache.images.forEach((image) => knownIds.add(image.id));// The run landed without its records, so Reuse last seed takes the seed it was sent.- if (!external) setSessionSeed(runBaseSeed);+ if (!external) setSessionSeed(compare?.sentSeed(i) ?? runBaseSeed);setGenDone(i + 1);continue;}@@ -5496,6 +5525,7 @@ export function ImagesPage({if (notice) toast.info(notice.title, { id: "prompt-enhancement-notice", description: notice.description });}res.images.forEach((image) => void ensureSrc(image));+ compare?.onImages(i, res.images);setGenDone(i + 1);}} catch (err) {@@ -5507,7 +5537,14 @@ export function ImagesPage({message: msg,stopRequested: cancelRequested.current && cancelAcked.current,});- if (report && shouldOfferGenerateAnyway({ error: err, allowOversizedSent })) {+ const offerAnyway = report && shouldOfferGenerateAnyway({ error: err, allowOversizedSent });+ // Not for a compare cell: the queued retry would run after the grid has ended, as a plain form generation.+ if (offerAnyway && compare) {+ toast.error(MEMORY_REFUSAL_TITLE, {+ description: `${msg} To run the grid anyway, turn on "${ALLOW_OVERSIZED_LABEL}" and generate it again.`,+ duration: 20_000,+ });+ } else if (offerAnyway) {toast.error(MEMORY_REFUSAL_TITLE, {description: msg,duration: 20_000,@@ -5574,6 +5611,54 @@ export function ImagesPage({}}, []);+ // Compare grid: handleGenerate reads the run from compareOnce, so a grid shares Stop, progress and the gallery+ // merge with Generate. Text-to-image on a loaded local model only.+ const [compareRun, setCompareRun] = useState<CompareRun | null>(null);+ const runCompare = useCallback(+ async (run: CompareRun) => {+ // Like Generate: the stored preset must replace the default steps / size before any request is sent.+ if (busy !== null || !imagePresets.hydrated) return;+ compareOnce.current = run;+ setCompareRun(run);+ try {+ await handleGenerate();+ } finally {+ compareOnce.current = null;+ setCompareRun(null);+ }+ },+ [busy, handleGenerate, imagePresets.hydrated],+ );+ const compareAvailable = !external && Boolean(status?.loaded) && workflow === "create";+ const compareSdControls = sdCaps;+ const compareContext = useMemo<CompareContext>(+ () => ({+ prompt,+ negativePrompt,+ negativeCapable,+ negativeMinGuidance,+ guidanceFixed,+ guidance: effectiveGuidance,+ samplers: samplerOptions,+ samplerChoice,+ shift: shiftControl,+ loraCapable,+ loras: loras+ .filter((l) => l.id.trim())+ .map((l) => ({+ id: l.id,+ weight: l.weight,+ label: availableLoras.find((a) => a.id === l.id)?.display_name ?? l.id.split(/[\\/]/).pop() ?? l.id,+ })),+ sdControls: compareSdControls,+ // The predicate the request uses (strength 0 runs plain text-to-image, where CFG rescale applies).+ controlnetEngaged,+ }),+ // samplerChoice is rebuilt every render; its two fields are what matter.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [prompt, negativePrompt, negativeCapable, negativeMinGuidance, guidanceFixed, effectiveGuidance, samplerOptions, samplerChoice.sampler, samplerChoice.scheduleType, shiftControl, loraCapable, loras, availableLoras, compareSdControls, controlnetEngaged],+ );+const handleGenerateWithRecall = useCallback(async () => {if (busy !== null || !imagePresets.hydrated) return;if (external) {@@ -7045,6 +7130,21 @@ export function ImagesPage({</div></Field>+ {compareAvailable && (+ <ComparePanel+ context={compareContext}+ busy={busy !== null || compareRun !== null || !imagePresets.hydrated}+ seedFieldEmpty={!seed.trim()}+ variationSeed={sdCaps?.variation_seed ? parseVariationSeed(sdChoice.variationSeed) : null}+ modelName={status?.repo_id ?? null}+ width={width}+ height={height}+ steps={steps}+ guidance={effectiveGuidance}+ onRun={runCompare}+ />+ )}+<AdvancedDisclosure open={advancedOpen} onOpenChange={setAdvancedOpen}>{advancedControls}</AdvancedDisclosure>@@ -7338,9 +7438,11 @@ export function ImagesPage({// Drop the chat min-height: this floating card has no layout to stabilise.className="min-h-0"title={- genDone != null && count > 1- ? `Run ${genDone + 1}/${count}`- : null+ compareRun && genDone != null+ ? compareRun.title(genDone)+ : genDone != null && count > 1+ ? `Run ${genDone + 1}/${count}`+ : null}message="Starting…"progressPercent={genStep ? genStep.fraction * 100 : null}diff --git a/studio/frontend/src/features/images/lib/image-metadata.ts b/studio/frontend/src/features/images/lib/image-metadata.tsindex 41157611162..4b789d21621 100644--- a/studio/frontend/src/features/images/lib/image-metadata.ts+++ b/studio/frontend/src/features/images/lib/image-metadata.ts@@ -796,6 +796,22 @@ export function parseA1111Parameters(text: string): ImportedRecipe | null {if (names.length > 0) out.textual_inversions = names;}else if (key === "shift" && n !== undefined) out.shift = n;+ // Studio's compare grid: its adapters by exact id (Hub ones too, which a prompt tag matches only locally) and+ // the prompt enhancer it forced off.+ else if (key === "loras" && value) {+ // CSV items: an entry whose id holds a comma or quote is written "id: weight" with "" for a quote.+ const items = [...value.matchAll(/\s*(?:"((?:[^"]|"")*)"|([^,]+))\s*(?:,|$)/g)].map((m) =>+ m[1] !== undefined ? m[1].replace(/""/g, '"') : (m[2] ?? "").trim(),+ );+ const loras = items.flatMap((item) => {+ const at = item.lastIndexOf(":");+ return at > 0 ? [`${item.slice(0, at).trim()}:${item.slice(at + 1).trim()}`] : [];+ });+ if (loras.length > 0) out.loras = loras;+ } else if (key === "prompt enhancement" && value.toLowerCase() === "off") out.prompt_enhancement = "off";+ // Flux's resolution-dependent shift, as Studio's compare grid writes it.+ else if (key === "base shift" && n !== undefined) out.base_shift = n;+ else if (key === "max shift" && n !== undefined) out.max_shift = n;// A1111 writes Emphasis only when it is not the default; "Original" is what Studio's prompt encoding does.// "None" skips the parser entirely (brackets are prompt text): Studio's prompt weighting off.else if (key === "emphasis") {diff --git a/studio/frontend/tests/image-prompt-enhance.test.ts b/studio/frontend/tests/image-prompt-enhance.test.tsindex d594f9ac678..94607c1f80d 100644--- a/studio/frontend/tests/image-prompt-enhance.test.ts+++ b/studio/frontend/tests/image-prompt-enhance.test.ts@@ -85,7 +85,7 @@ test("enhance_prompt is sent only when the loaded family supports it", () => {assert.deepEqual(enhancePromptRequestField(promptUpsamplerCapability(null), true), {});// Wired into the generate request.const page = readSrc("features/images/images-page.tsx");- const call = page.slice(page.indexOf("res = await generateDiffusionImage({"));+ const call = page.slice(page.indexOf("res = await generateDiffusionImage("));assert.match(call.slice(0, 4000), /\.\.\.enhancePromptRequestField\(upsamplerCapability, enhanceOn\)/);});diff --git a/studio/frontend/tests/image-seed-inpaint-steps.test.ts b/studio/frontend/tests/image-seed-inpaint-steps.test.tsindex f55743c13a3..295176b5c88 100644--- a/studio/frontend/tests/image-seed-inpaint-steps.test.ts+++ b/studio/frontend/tests/image-seed-inpaint-steps.test.ts@@ -180,7 +180,7 @@ test("a run whose response was lost still becomes the seed Reuse last seed picksassert.match(page, /seed: runBaseSeed,/);assert.match(page,- /if \(!\(err instanceof GenerateResponseLostError\)\) throw err;[\s\S]*?if \(!external\) setSessionSeed\(runBaseSeed\);\n\s+setGenDone\(i \+ 1\);\n\s+continue;/,+ /if \(!\(err instanceof GenerateResponseLostError\)\) throw err;[\s\S]*?if \(!external\) setSessionSeed\((?:compare\?\.sentSeed\(i\) \?\? )?runBaseSeed\);\n\s+setGenDone\(i \+ 1\);\n\s+continue;/,);});diff --git a/studio/frontend/tests/images-compare-grid.test.ts b/studio/frontend/tests/images-compare-grid.test.tsnew file mode 100644index 00000000000..893b552677a--- /dev/null+++ b/studio/frontend/tests/images-compare-grid.test.ts@@ -0,0 +1,946 @@+// 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 type { DiffusionGenerateRequest } from "../src/features/images/api.ts";+import {+ availableAxes,+ buildCellRequest,+ cellCoords,+ executionOrder,+ MAX_COMPARE_CELLS,+ planCompare,+ type CompareContext,+ type CompareGridPlan,+} from "../src/features/images/compare/compare-axes.ts";+import { createCompareRun, gridParameters, gridRecipeFields, gridTitles, sliceCells } from "../src/features/images/compare/compare-run.ts";+import { joinAxisList, parseAxisValues, splitAxisList } from "../src/features/images/compare/compare-values.ts";+import { drawCellsInTurn, gridInfotext, gridLayout, MAX_CANVAS_PIXELS, MAX_CANVAS_SIDE, withPngText, wrapText } from "../src/features/images/compare/compose-grid.ts";+import { parseA1111Parameters, pngTextChunks } from "../src/features/images/lib/image-metadata.ts";+import { readSrc } from "./helpers/kit.ts";++const values = (text: string, type: "int" | "float" | "str") => {+ const r = parseAxisValues(text, type);+ assert.ok(r.ok, `expected ${text} to parse: ${r.ok ? "" : r.error}`);+ return r.values;+};++test("A1111 list syntax: commas, newlines, CSV quoting, empty items dropped", () => {+ assert.deepEqual(splitAxisList('euler, "a, b",dpmpp_2m'), ["euler", "a, b", "dpmpp_2m"]);+ assert.deepEqual(splitAxisList('say ""hi""'), ['say ""hi""']);+ assert.deepEqual(splitAxisList('"say ""hi"""'), ['say "hi"']);+ assert.deepEqual(values("1,2\n3,,", "int"), [1, 2, 3]);+ assert.deepEqual(values(" red , blue ", "str"), ["red", "blue"]);+ assert.equal(joinAxisList(["DPM++ 2M", "a, b"]), 'DPM++ 2M, "a, b"');+});++test("integer ranges: a-b, a-b (+s), a-b (-s), a-b [n] (linspace then truncated)", () => {+ assert.deepEqual(values("1-5", "int"), [1, 2, 3, 4, 5]);+ assert.deepEqual(values("1-9 (+2)", "int"), [1, 3, 5, 7, 9]);+ assert.deepEqual(values("10-30 (+10)", "int"), [10, 20, 30]);+ assert.deepEqual(values("1-10(+4)", "int"), [1, 5, 9]);+ // A1111 stops a descending range one short (range(5, 2, -1)); this keeps the end the user typed.+ assert.deepEqual(values("5-1 (-1)", "int"), [5, 4, 3, 2, 1]);+ assert.deepEqual(values("5-1", "int"), [5, 4, 3, 2, 1]);+ // numpy.linspace(1, 10, 4) = 1, 4, 7, 10; linspace(0, 10, 4) = 0, 3.33, 6.67, 10 -> int() truncates.+ assert.deepEqual(values("1-10 [4]", "int"), [1, 4, 7, 10]);+ assert.deepEqual(values("0-10 [4]", "int"), [0, 3, 6, 10]);+ assert.deepEqual(values("-1, 7, 100-102", "int"), [-1, 7, 100, 101, 102]);+ assert.deepEqual(values("20, 1-3 [2]", "int"), [20, 1, 3]);+});++test("decimal ranges: a-b (+s) inclusive via arange, a-b [n] via linspace, 8-decimal rounding", () => {+ assert.deepEqual(values("1-2 (+0.5)", "float"), [1, 1.5, 2]);+ assert.deepEqual(values("0-0.3 (+0.1)", "float"), [0, 0.1, 0.2, 0.3]);+ assert.deepEqual(values("3-7 [3]", "float"), [3, 5, 7]);+ assert.deepEqual(values("0-1 (0.25)", "float"), [0, 0.25, 0.5, 0.75, 1]);+ assert.deepEqual(values("1.5, 2.25, 7", "float"), [1.5, 2.25, 7]);+ assert.deepEqual(values("1-2", "float"), [1, 2]);+});++test("bad values name the item", () => {+ const bad = (text: string, type: "int" | "float") => {+ const r = parseAxisValues(text, type);+ assert.equal(r.ok, false, text);+ return r.ok ? "" : r.error;+ };+ assert.match(bad("abc", "int"), /"abc" is not a number/);+ assert.match(bad("2.5", "int"), /not a whole number/);+ assert.match(bad("1-5 (+0)", "int"), /Bad range step/);+ assert.match(bad("", "int"), /No values/);+ assert.match(bad("0x10", "float"), /not a number/);+});++const SAMPLERS = [+ { id: "default", label: "Model default", schedule_types: ["automatic"] },+ { id: "euler", label: "Euler", schedule_types: ["automatic", "karras"] },+ { id: "euler_a", label: "Euler a", schedule_types: ["automatic"] },+ { id: "dpmpp_2m", label: "DPM++ 2M", schedule_types: ["automatic", "karras", "exponential"] },+];++function sdxl(over: Partial<CompareContext> = {}): CompareContext {+ return {+ prompt: "a red fox in the snow",+ negativePrompt: "blurry",+ negativeCapable: true,+ negativeMinGuidance: 1,+ guidanceFixed: false,+ guidance: 6,+ samplers: SAMPLERS,+ samplerChoice: { sampler: "default", scheduleType: "automatic" },+ shift: null,+ loraCapable: false,+ loras: [],+ sdControls: null,+ controlnetEngaged: false,+ ...over,+ };+}++const zimage = (over: Partial<CompareContext> = {}) =>+ sdxl({ samplers: [], guidanceFixed: true, shift: { node: "sd3", shift: 3 }, negativeCapable: false, ...over });++const ids = (ctx: CompareContext) => availableAxes(ctx).map((a) => a.id);++test("capability gating: the axis list follows what the loaded model exposes", () => {+ assert.deepEqual(ids(sdxl()), ["nothing", "seed", "steps", "guidance", "sampler", "schedule", "prompt_sr"]);+ // A distilled flow model: no sampler picker, guidance fixed, one static shift.+ assert.deepEqual(ids(zimage()), ["nothing", "seed", "steps", "shift", "prompt_sr"]);+ // ComfyUI ModelSamplingFlux: base and max shift.+ assert.ok(ids(zimage({ shift: { node: "flux", base_shift: 0.5, max_shift: 1.15 } })).includes("max_shift"));+ const loras = [+ { id: "a/style", weight: 1, label: "style" },+ { id: "b/detail", weight: 0.5, label: "detail" },+ ];+ assert.ok(!ids(sdxl({ loras })).includes("lora:0"));+ const withLoras = availableAxes(sdxl({ loras, loraCapable: true }));+ assert.deepEqual(+ withLoras.filter((a) => a.id.startsWith("lora:")).map((a) => a.label),+ ["LoRA weight: style", "LoRA weight: detail"],+ );+ // One sampler (the model default only) is no picker, so no axis.+ assert.ok(!ids(sdxl({ samplers: SAMPLERS.slice(0, 1) })).includes("sampler"));+});++test("SD controls axes appear only when status reports them (#14562), CFG rescale not with a ControlNet", () => {+ const sdControls = { clip_skip: { min: 1, max: 12 }, cfg_rescale: { min: 0, max: 1 }, variation_seed: true, vary_strength: 0.2 };+ const all = ids(sdxl({ sdControls }));+ for (const id of ["clip_skip", "cfg_rescale", "variation_seed", "variation_strength"]) assert.ok(all.includes(id), id);+ assert.ok(!ids(sdxl({ sdControls, controlnetEngaged: true })).includes("cfg_rescale"));+ const r = planCompare([{ axisId: "variation_seed", text: "1, 2" }], sdxl({ sdControls }));+ assert.ok(r.ok);+ const req = buildCellRequest(r.plan, 1, base(), sdxl({ sdControls }), { base: 5, keepRandom: false, seedFieldEmpty: false }) as unknown as Record<string, unknown>;+ assert.equal(req.variation_seed, 2);+ assert.equal(req.variation_strength, 0.2);+ const clip = planCompare([{ axisId: "clip_skip", text: "1-3" }], sdxl({ sdControls }));+ assert.ok(clip.ok);+ assert.equal((buildCellRequest(clip.plan, 2, base(), sdxl({ sdControls }), { base: 5, keepRandom: false, seedFieldEmpty: false }) as unknown as Record<string, unknown>).clip_skip, 3);+ assert.equal(planCompare([{ axisId: "clip_skip", text: "13" }], sdxl({ sdControls })).ok, false);+});++test("an axis the model lacks is refused by id, out-of-range values are refused", () => {+ const r = planCompare([{ axisId: "sampler", text: "euler" }], zimage());+ assert.equal(r.ok, false);+ assert.match(r.ok ? "" : r.error, /no sampler axis/);+ assert.equal(planCompare([{ axisId: "steps", text: "0, 5" }], sdxl()).ok, false);+ assert.equal(planCompare([{ axisId: "steps", text: "101" }], sdxl()).ok, false);+ assert.equal(planCompare([{ axisId: "guidance", text: "21" }], sdxl()).ok, false);+ assert.equal(planCompare([{ axisId: "shift", text: "0" }], zimage()).ok, false);+ const unknown = planCompare([{ axisId: "sampler", text: "euler, heun" }], sdxl());+ assert.match(unknown.ok ? "" : unknown.error, /Unknown sampler: heun/);+});++test("sampler values match the id or the A1111 label, case-insensitively", () => {+ const r = planCompare([{ axisId: "sampler", text: "Euler a, dpm++ 2m, euler" }], sdxl());+ assert.ok(r.ok);+ assert.deepEqual(r.plan.axes[0].values, ["euler_a", "dpmpp_2m", "euler"]);+ assert.deepEqual(r.plan.axes[0].labels, ["Euler a", "DPM++ 2M", "Euler"]);+});++test("cell cap: over the limit is refused with the count, at the limit is fine", () => {+ assert.equal(MAX_COMPARE_CELLS, 64);+ const over = planCompare(+ [+ { axisId: "steps", text: "1-5" },+ { axisId: "guidance", text: "1-4" },+ { axisId: "seed", text: "1-4" },+ ],+ sdxl(),+ );+ assert.equal(over.ok, false);+ assert.equal(over.ok ? 0 : over.cellCount, 80);+ assert.match(over.ok ? "" : over.error, /80 cells is over the limit of 64/);+ const at = planCompare(+ [+ { axisId: "steps", text: "1-4" },+ { axisId: "guidance", text: "1-4" },+ { axisId: "seed", text: "1-4" },+ ],+ sdxl(),+ );+ assert.ok(at.ok);+ assert.equal(at.plan.cellCount, 64);+ assert.equal(planCompare([{ axisId: "nothing", text: "" }], sdxl()).ok, false);+ const dup = planCompare([{ axisId: "steps", text: "1" }, { axisId: "steps", text: "2" }], sdxl());+ assert.match(dup.ok ? "" : dup.error, /X and Y are both Steps/);+});++function base(over: Partial<DiffusionGenerateRequest> = {}): DiffusionGenerateRequest {+ return {+ prompt: "a red fox in the snow",+ negative_prompt: "blurry",+ width: 1024,+ height: 1024,+ steps: 25,+ guidance: 6,+ seed: 999,+ batch_size: 4,+ live_preview: true,+ ...over,+ };+}++const plan = (inputs: Array<{ axisId: string; text: string }>, ctx = sdxl(), keepRandom = false) => {+ const r = planCompare(inputs, ctx, { keepRandomSeeds: keepRandom, rng: () => 0.5 });+ assert.ok(r.ok, r.ok ? "" : r.error);+ return r.plan;+};++test("cell requests: batch 1, one shared seed, the cell's steps / sampler / schedule", () => {+ const p = plan([+ { axisId: "sampler", text: "euler, euler_a, dpmpp_2m" },+ { axisId: "steps", text: "10, 20, 30" },+ ]);+ assert.equal(p.cellCount, 9);+ const ctx = sdxl({ samplerChoice: { sampler: "euler", scheduleType: "karras" } });+ const reqs = Array.from({ length: 9 }, (_, i) =>+ buildCellRequest(p, i, base(), ctx, { base: 42, keepRandom: false, seedFieldEmpty: true }),+ );+ assert.ok(reqs.every((r) => r.batch_size === 1 && r.seed === 42));+ // index = ix + iy*3: ix = sampler, iy = steps.+ assert.deepEqual(+ reqs.map((r) => [r.sampler, r.schedule_type, r.steps]),+ [+ ["euler", "karras", 10],+ // Euler a takes no Karras: the form's schedule falls back to automatic (omitted).+ ["euler_a", undefined, 10],+ ["dpmpp_2m", "karras", 10],+ ["euler", "karras", 20],+ ["euler_a", undefined, 20],+ ["dpmpp_2m", "karras", 20],+ ["euler", "karras", 30],+ ["euler_a", undefined, 30],+ ["dpmpp_2m", "karras", 30],+ ],+ );+ // "Model default" is the shipped scheduler: no sampler field at all, as the form sends it.+ const d = plan([{ axisId: "sampler", text: "Model default" }]);+ const dr = buildCellRequest(d, 0, base({ sampler: "euler" }), sdxl(), { base: 1, keepRandom: false, seedFieldEmpty: false });+ assert.equal("sampler" in dr, false);+});++test("seeds: axis values, -1 fixed once per value (A1111 fix_axis_seeds), Keep -1 draws per cell", () => {+ const p = plan([{ axisId: "seed", text: "-1, 7" }, { axisId: "steps", text: "4, 8" }]);+ assert.deepEqual(p.axes[0].values, [2 ** 31, 7]);+ const s = (pl: CompareGridPlan, i: number, keepRandom: boolean, empty: boolean, rng = () => 0.25) =>+ buildCellRequest(pl, i, base(), sdxl(), { base: 42, keepRandom, seedFieldEmpty: empty, rng }).seed;+ assert.deepEqual([0, 1, 2, 3].map((i) => s(p, i, false, true)), [2 ** 31, 7, 2 ** 31, 7]);+ const kept = plan([{ axisId: "seed", text: "-1, 7" }], sdxl(), true);+ assert.equal(kept.axes[0].labels[0], "Seed: random");+ assert.equal(s(kept, 0, true, true), 2 ** 30);+ const steps = plan([{ axisId: "steps", text: "4, 8" }]);+ assert.equal(s(steps, 1, false, true), 42);+ assert.equal(s(steps, 1, true, true), 2 ** 30);+ // A typed seed is not -1, so Keep -1 leaves it alone.+ assert.equal(s(steps, 1, true, false), 42);+});++test("guidance re-derives the negative prompt; Prompt S/R replaces in both prompts and needs a hit", () => {+ const g = plan([{ axisId: "guidance", text: "1, 7" }]);+ const lo = buildCellRequest(g, 0, base(), sdxl(), { base: 1, keepRandom: false, seedFieldEmpty: false });+ const hi = buildCellRequest(g, 1, base(), sdxl(), { base: 1, keepRandom: false, seedFieldEmpty: false });+ assert.equal(lo.negative_prompt, undefined);+ assert.equal(hi.negative_prompt, "blurry");+ const ctx = sdxl({ prompt: "a red fox, red scarf", negativePrompt: "red eyes" });+ const sr = plan([{ axisId: "prompt_sr", text: "red, blue, green" }], ctx);+ const req = (i: number) =>+ buildCellRequest(sr, i, base({ prompt: ctx.prompt, negative_prompt: ctx.negativePrompt }), ctx, { base: 1, keepRandom: false, seedFieldEmpty: false });+ assert.equal(req(0).prompt, "a red fox, red scarf");+ assert.equal(req(1).prompt, "a blue fox, blue scarf");+ assert.equal(req(2).negative_prompt, "green eyes");+ const miss = planCompare([{ axisId: "prompt_sr", text: "purple, blue" }], ctx);+ assert.match(miss.ok ? "" : miss.error, /did not find "purple"/);+});++test("LoRA weight targets one row; 0 drops it; the prompt enhancer is off for every cell", () => {+ const ctx = sdxl({+ loraCapable: true,+ loras: [+ { id: "a/style", weight: 1, label: "style" },+ { id: "b/detail", weight: 0.5, label: "detail" },+ ],+ });+ const p = plan([{ axisId: "lora:1", text: "0, 0.5, 1" }], ctx);+ const req = (i: number) =>+ buildCellRequest(p, i, base({ enhance_prompt: true }), ctx, { base: 1, keepRandom: false, seedFieldEmpty: false });+ assert.deepEqual(req(0).loras, [{ id: "a/style", weight: 1 }]);+ assert.deepEqual(req(2).loras, [+ { id: "a/style", weight: 1 },+ { id: "b/detail", weight: 1 },+ ]);+ assert.equal(req(0).enhance_prompt, false);+ const z = plan([{ axisId: "shift", text: "1, 3, 6" }], zimage());+ const zr = buildCellRequest(z, 2, base(), zimage(), { base: 1, keepRandom: false, seedFieldEmpty: false });+ assert.equal(zr.shift, 6);+ assert.equal("enhance_prompt" in zr, false);+});++test("run order: A1111's z, y, x nesting; costly axes outermost, grouped by shape class", () => {+ // No costly axis: row by row (x fastest), exactly A1111's default loop.+ const p = plan([{ axisId: "steps", text: "1, 2, 3" }, { axisId: "seed", text: "1, 2" }]);+ assert.deepEqual(p.order, [0, 1, 2, 3, 4, 5]);+ // CFG on X crosses the CFG threshold (1): it becomes the outer loop, the two CFG-off values (0, 1) run first+ // even though 7 sits between them, so the denoiser batch changes once, not three times.+ const g = plan([{ axisId: "guidance", text: "0, 7, 1" }, { axisId: "steps", text: "4, 8" }]);+ const ran = g.order.map((i) => {+ const [ix, iy] = cellCoords(g, i);+ return [g.axes[0].values[ix], g.axes[1].values[iy]];+ });+ assert.deepEqual(ran, [+ [0, 4],+ [0, 8],+ [1, 4],+ [1, 8],+ [7, 4],+ [7, 8],+ ]);+ let switches = 0;+ for (let k = 1; k < ran.length; k++) if ((Number(ran[k][0]) > 1) !== (Number(ran[k - 1][0]) > 1)) switches++;+ assert.equal(switches, 1);+ // Prompt S/R outranks guidance: each prompt is entered once.+ const sr = plan(+ [+ { axisId: "guidance", text: "1, 7" },+ { axisId: "prompt_sr", text: "red, blue" },+ { axisId: "steps", text: "4, 8" },+ ],+ );+ const prompts = sr.order.map((i) => cellCoords(sr, i)[1]);+ assert.deepEqual(prompts, [0, 0, 0, 0, 1, 1, 1, 1]);+ assert.deepEqual([...sr.order].sort((a, b) => a - b), [0, 1, 2, 3, 4, 5, 6, 7]);+ assert.deepEqual(executionOrder(sr.axes).length, 8);+});++test("the run object: execution order to cell index, titles, one image per cell, Z slices", () => {+ const p = plan([+ { axisId: "steps", text: "4, 8" },+ { axisId: "nothing", text: "" },+ { axisId: "seed", text: "1, 2" },+ ]);+ assert.deepEqual(gridTitles(p), ["Seed: 1", "Seed: 2"]);+ const run = createCompareRun(p, sdxl(), { keepRandomSeeds: false, seedFieldEmpty: true });+ assert.equal(run.cellCount, 4);+ assert.equal(run.title(0), "Cell 1/4: Steps: 4, Seed: 1");+ for (let i = 0; i < 4; i++) {+ const req = run.request(i, base(), 5);+ run.onImages(i, [{ id: `img${i}`, steps: req.steps, seed: req.seed } as never]);+ }+ assert.deepEqual(+ sliceCells(p, run.results, 1).map((r) => (r as unknown as { seed: number }).seed),+ [2, 2],+ );+ assert.equal(run.requests.filter(Boolean).length, 4);+});++const measure = (text: string, size: number) => text.length * size * 0.5;++test("grid layout: A1111 font size and bands, labels wrapped, cells placed row-major", () => {+ const layout = gridLayout(+ {+ cols: 3,+ rows: 2,+ cellWidth: 512,+ cellHeight: 512,+ colLabels: ["Euler", "Euler a", "DPM++ 2M"],+ rowLabels: ["Steps: 10", "Steps: 20"],+ title: "",+ legend: true,+ margin: 8,+ },+ measure,+ );+ assert.equal(layout.fontSize, Math.round(1024 / 25));+ const padLeft = Math.floor((512 * 3) / 4);+ assert.equal(layout.cells[0].x, padLeft);+ assert.equal(layout.cells[1].x, padLeft + 520);+ assert.equal(layout.cells[3].y, layout.cells[0].y + 520);+ assert.equal(layout.width, padLeft + 3 * 512 + 2 * 8);+ assert.equal(layout.height, layout.cells[0].y + 2 * 512 + 8);+ assert.ok(layout.cells[0].y > 0, "column labels take a band above the cells");+ assert.equal(layout.colText.length, 3);+ assert.equal(layout.rowText[1].x, padLeft / 2);+ assert.equal(layout.title, null);+ const bare = gridLayout({ cols: 2, rows: 1, cellWidth: 64, cellHeight: 32, colLabels: ["a", "b"], rowLabels: [""], title: "Z", legend: false, margin: 0 }, measure);+ assert.deepEqual([bare.width, bare.height, bare.cells[1].x, bare.cells[0].y], [128, 32, 64, 0]);+ const titled = gridLayout({ cols: 1, rows: 1, cellWidth: 256, cellHeight: 256, colLabels: ["x"], rowLabels: [""], title: "Seed: 1", legend: true, margin: 0 }, measure);+ assert.ok(titled.title && titled.colText[0].y > titled.title.y);+ assert.deepEqual(wrapText("one two three four", 40, 10, measure), ["one two", "three", "four"]);+});++test("grid layout shrinks cells to fit a browser canvas", () => {+ const big = gridLayout(+ { cols: 8, rows: 8, cellWidth: 2752, cellHeight: 2752, colLabels: [], rowLabels: [], title: "", legend: false, margin: 0 },+ measure,+ );+ assert.ok(big.scale < 1);+ assert.ok(big.width <= MAX_CANVAS_SIDE && big.height <= MAX_CANVAS_SIDE);+ // Bounded by memory, not just the browser's 2^28 ceiling: an 8x8 grid of 2752 px cells stays under 128 MiB RGBA.+ assert.ok(big.width * big.height <= MAX_CANVAS_PIXELS);+ assert.equal(big.cells.length, 64);+ const labelled = gridLayout(+ { cols: 8, rows: 8, cellWidth: 2752, cellHeight: 2752, colLabels: Array(8).fill("Steps: 20"), rowLabels: Array(8).fill("CFG: 7"), title: "Seed: 1", legend: true, margin: 16 },+ measure,+ );+ assert.ok(labelled.width * labelled.height <= MAX_CANVAS_PIXELS);+});++test("the grid PNG carries an A1111-style parameters chunk the metadata reader parses", () => {+ const png = Uint8Array.from(+ atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),+ (c) => c.charCodeAt(0),+ );+ const info = gridInfotext({+ prompt: "a red fox",+ negativePrompt: "blurry",+ fields: [["Steps", 20], ["Seed", 42], ["Model", null]],+ axes: [{ name: "X", type: "Sampler", text: "euler, dpmpp_2m" }],+ });+ assert.equal(info, 'a red fox\nNegative prompt: blurry\nSteps: 20, Seed: 42, Script: X/Y/Z plot, X Type: Sampler, X Values: "euler, dpmpp_2m"');+ const out = withPngText(png, "parameters", info);+ assert.equal(pngTextChunks(out).parameters, info);+ assert.equal(withPngText(new Uint8Array([1, 2, 3]), "k", "v").length, 3);+});++test("the Images page (its own lazy chunk) renders the panel and loops cells through its own Generate path", () => {+ const page = readSrc("features/images/images-page.tsx");+ assert.match(page, /^import ComparePanel from "\.\/compare\/compare-panel";$/m);+ // The panel and the rest of compare/ are reached only through the Images page, never from the startup graph.+ const root = readSrc("app/routes/__root.tsx");+ assert.match(root, /lazy\(\(\) =>\s*import\("@\/features\/images"\)/);+ assert.match(page, /for \(let i = 0; i < runTotal; i\+\+\)/);+ assert.match(page, /generateDiffusionImage\(compareRequest\(compare, i, baseSeed, \{/);+ assert.match(page, /compare\?\.onImages\(i, res\.images\)/);+ // The lost-response branch also reports the cell, from the records the gallery gained.+ assert.match(page, /compare\?\.onImages\(i, galleryCache\.images\.filter\(\(image\) => !knownIds\.has\(image\.id\)\)\)/);+ assert.match(page, /workflow === "create"/);+});++test("a Schedule type the cell's sampler does not take is refused, not silently run as Automatic", () => {+ const bad = planCompare(+ [+ { axisId: "sampler", text: "euler, euler_a" },+ { axisId: "schedule", text: "karras" },+ ],+ sdxl(),+ );+ assert.equal(bad.ok, false);+ assert.match(bad.ok ? "" : bad.error, /Karras is not available with Euler a/);+ // The form's Model default takes no schedule either.+ const onDefault = planCompare([{ axisId: "schedule", text: "automatic, karras" }], sdxl());+ assert.match(onDefault.ok ? "" : onDefault.error, /Karras is not available with Model default/);+ const good = plan([+ { axisId: "sampler", text: "euler, dpmpp_2m" },+ { axisId: "schedule", text: "automatic, karras" },+ ]);+ const reqs = [0, 1, 2, 3].map((i) =>+ buildCellRequest(good, i, base(), sdxl(), { base: 1, keepRandom: false, seedFieldEmpty: false }),+ );+ assert.deepEqual(+ reqs.map((r) => [r.sampler, r.schedule_type]),+ [+ ["euler", undefined],+ ["dpmpp_2m", undefined],+ ["euler", "karras"],+ ["dpmpp_2m", "karras"],+ ],+ );+});++test("Prompt S/R counts a negative-prompt match only where some cell's CFG engages the negative prompt", () => {+ const ctx = sdxl({ prompt: "a fox", negativePrompt: "red eyes", guidance: 1 });+ const off = planCompare([{ axisId: "prompt_sr", text: "red, blue" }], ctx);+ assert.equal(off.ok, false);+ assert.match(off.ok ? "" : off.error, /did not find "red" in cell "red"/);+ // A CFG axis that raises guidance over the threshold engages it for those cells.+ // Per cell: a CFG 1 cell would not use the negative prompt, so its substitution would do nothing.+ const mixed = planCompare([{ axisId: "prompt_sr", text: "red, blue" }, { axisId: "guidance", text: "1, 7" }], ctx);+ assert.match(mixed.ok ? "" : mixed.error, /did not find "red" in cell "red, CFG: 1"/);+ const withCfg = planCompare([{ axisId: "prompt_sr", text: "red, blue" }, { axisId: "guidance", text: "3, 7" }], ctx);+ assert.ok(withCfg.ok);+ const req = buildCellRequest(withCfg.ok ? withCfg.plan : (null as never), 3, base({ prompt: "a fox", negative_prompt: undefined, guidance: 1 }), ctx, {+ base: 1,+ keepRandom: false,+ seedFieldEmpty: false,+ });+ assert.equal(req.negative_prompt, "blue eyes");+ assert.equal(planCompare([{ axisId: "prompt_sr", text: "red, blue" }], sdxl({ ...ctx, guidance: 6, negativeCapable: false })).ok, false);+ assert.ok(planCompare([{ axisId: "prompt_sr", text: "red, blue" }], sdxl({ ...ctx, guidance: 6 })).ok);+});++test("LoRA weight cells: every weighted cell runs before any adapter-free one, across all axes", () => {+ const ctx = sdxl({ loraCapable: true, loras: [{ id: "a/style", weight: 1, label: "style" }], prompt: "a red fox" });+ const p = plan(+ [+ { axisId: "lora:0", text: "0, 0.5, 1" },+ { axisId: "prompt_sr", text: "red, blue" },+ { axisId: "steps", text: "4, 8" },+ ],+ ctx,+ );+ const hasLora = p.order.map((i) =>+ Boolean(buildCellRequest(p, i, base(), ctx, { base: 1, keepRandom: false, seedFieldEmpty: false }).loras),+ );+ const firstOff = hasLora.indexOf(false);+ assert.ok(firstOff > 0);+ assert.ok(hasLora.slice(firstOff).every((x) => !x), "a LoRA cell ran after an adapter-free one");+ // The backend's deferred compile rule: with LoRA-free runs back to back, a later LoRA request would be refused.+ let attached = true;+ let compiled = false;+ for (const lora of hasLora) {+ assert.ok(!(lora && compiled), "a LoRA cell would hit a compiled load");+ if (!lora && !attached) compiled = true;+ attached = lora;+ }+});++test("a lost-response recovery hands the cell its own record, matched by seed", () => {+ const p = plan([{ axisId: "seed", text: "11, 12" }]);+ const run = createCompareRun(p, sdxl(), { keepRandomSeeds: false, seedFieldEmpty: false });+ run.request(0, base(), 5);+ run.request(1, base(), 5);+ run.onImages(1, [{ id: "other", seed: 99 } as never, { id: "mine", seed: 12 } as never]);+ assert.equal((run.results[1] as unknown as { id: string }).id, "mine");+ run.onImages(0, [{ id: "a", seed: 1 } as never, { id: "b", seed: 2 } as never]);+ assert.equal(run.results[0], null, "an ambiguous set without the cell's seed is not guessed");+ run.onImages(0, [{ id: "only", seed: 11 } as never]);+ assert.equal((run.results[0] as unknown as { id: string }).id, "only");+});++test("grid metadata names the sampler and schedule whenever no axis varies them", () => {+ const steps = plan([{ axisId: "steps", text: "10, 20" }]);+ const first = base({ sampler: "dpmpp_2m", schedule_type: "karras" });+ const fields = Object.fromEntries(gridRecipeFields(steps, [first], { steps: 25, guidance: 6, width: 1024, height: 1024, model: "m" }));+ assert.equal(fields.Sampler, "DPM++ 2M");+ assert.equal(fields["Schedule type"], "Karras");+ const samplers = plan([{ axisId: "sampler", text: "euler, dpmpp_2m" }]);+ const varied = Object.fromEntries(gridRecipeFields(samplers, [first], { steps: 25, guidance: 6, width: 1024, height: 1024, model: "m" }));+ assert.equal("Sampler" in varied, false);+ assert.equal(varied["Schedule type"], "Karras");+ const plain = Object.fromEntries(gridRecipeFields(steps, [base()], { steps: 25, guidance: 6, width: 1024, height: 1024, model: "m" }));+ assert.equal(plain.Sampler, "Model default");+ assert.equal("Schedule type" in plain, false);+});++test("grid metadata writes a schedule or shift only when every cell ran it", () => {+ const form = { steps: 25, guidance: 6, width: 1024, height: 1024, model: "m" };+ // Euler a takes no Karras: its cell fell back to Automatic, so Karras is not the grid's schedule.+ const samplers = plan([{ axisId: "sampler", text: "euler, euler_a" }]);+ const mixed = Object.fromEntries(+ gridRecipeFields(samplers, [base({ sampler: "euler", schedule_type: "karras" }), base({ sampler: "euler_a" })], form),+ );+ assert.equal("Schedule type" in mixed, false);+ const same = Object.fromEntries(+ gridRecipeFields(samplers, [base({ sampler: "euler", schedule_type: "karras" }), null, base({ sampler: "euler_a", schedule_type: "karras" })], form),+ );+ assert.equal(same["Schedule type"], "Karras");+ // A custom static shift every cell shares survives; a Shift axis keeps it out of the shared fields.+ const steps = plan([{ axisId: "steps", text: "10, 20" }]);+ const shifted = Object.fromEntries(gridRecipeFields(steps, [base({ shift: 3 }), base({ shift: 3, steps: 20 })], form));+ assert.equal(shifted.Shift, 3);+ const none = Object.fromEntries(gridRecipeFields(steps, [base(), base({ steps: 20 })], form));+ assert.equal(none.Shift, undefined);+});++test("grid metadata: one every-cell-agrees rule for Flux shift, fitted size, seeds and variation strength", () => {+ const form = { steps: 25, guidance: 6, width: 2048, height: 2048, model: "m" };+ const steps = plan([{ axisId: "steps", text: "10, 20" }]);+ const fields = Object.fromEntries(+ gridRecipeFields(+ steps,+ [+ base({ steps: 10, width: 1024, height: 1024, base_shift: 0.5, max_shift: 1.15, ...({ variation_strength: 0.15 } as object) }),+ base({ steps: 20, width: 1024, height: 1024, base_shift: 0.5, max_shift: 1.15, ...({ variation_strength: 0.15 } as object) }),+ ],+ form,+ ),+ );+ assert.equal(fields["Base shift"], 0.5);+ assert.equal(fields["Max shift"], 1.15);+ // The size the cells were fitted to, not the 2048 form value.+ assert.equal(fields.Size, "1024x1024");+ assert.equal(fields.Seed, 999);+ assert.equal(fields["Variation seed strength"], 0.15);+ // A varied axis is never written as shared, even if only one cell ran.+ assert.equal(fields.Steps, undefined);+ // Keep -1 with an empty seed box: each cell drew its own seed, so none is shared.+ const random = Object.fromEntries(gridRecipeFields(steps, [base({ seed: 1 }), base({ seed: 2 })], form));+ assert.equal(random.Seed, undefined);+ // The implicit Vary strength a Variation seed axis adds reaches the grid's parameters and parses back.+ const ctx = sdxl({ sdControls: { variation_seed: true, vary_strength: 0.2 } as never });+ const vp = plan([{ axisId: "variation_seed", text: "1, 2" }], ctx);+ const reqs = vp.order.map((cell) => buildCellRequest(vp, cell, base(), ctx, { base: 5, keepRandom: false, seedFieldEmpty: false }));+ const info = gridParameters(vp, ctx, reqs, { ...form, keepRandomSeeds: false });+ assert.match(info, /Variation seed strength: 0\.2/);+ // The importer restores the Flux shift pair the grid writes.+ const recipe = parseA1111Parameters(gridInfotext({ prompt: "p", fields: [["Steps", 4], ["Base shift", 0.5], ["Max shift", 1.15]], axes: [] }));+ assert.equal(recipe?.base_shift, 0.5);+ assert.equal(recipe?.max_shift, 1.15);+});++test("grid cells are decoded and drawn one at a time; missing and failed cells keep the placeholder", async () => {+ let live = 0;+ let peak = 0;+ const drawn: number[] = [];+ const count = await drawCellsInTurn(+ ["a", null, "fail", "d"],+ async (r) => {+ live++;+ peak = Math.max(peak, live);+ await new Promise((resolve) => setTimeout(resolve, 2));+ if (r === "fail") {+ live--;+ throw new Error("decode");+ }+ return r;+ },+ (_bitmap, i) => {+ drawn.push(i);+ live--;+ },+ );+ assert.equal(peak, 1);+ assert.equal(count, 2);+ assert.deepEqual(drawn, [0, 3]);+ const panel = readSrc("features/images/compare/compare-panel.tsx");+ assert.doesNotMatch(panel, /Promise\.all/);+ assert.match(panel, /resizeWidth: rect\.w/);+});++test("Prompt S/R is validated per cell after the earlier axes' substitutions, in X, Y, Z order", () => {+ const ctx = sdxl({ prompt: "red fox" });+ // X=blue removes "red" before Y runs, so the Y=green cells would be mislabelled duplicates.+ const removed = planCompare([{ axisId: "prompt_sr", text: "red, blue" }, { axisId: "prompt_sr", text: "red, green" }], ctx);+ assert.match(removed.ok ? "" : removed.error, /Y: Prompt S\/R did not find "red" in cell "blue, red"/);+ // X introduces Y's term in every cell: accepted, and the chain applies in order.+ const added = plan([{ axisId: "prompt_sr", text: "fox, fox cub" }, { axisId: "prompt_sr", text: "fox, wolf" }], ctx);+ const req = (i: number) => buildCellRequest(added, i, base({ prompt: "red fox" }), ctx, { base: 1, keepRandom: false, seedFieldEmpty: false }).prompt;+ assert.deepEqual([0, 1, 2, 3].map(req), ["red fox", "red fox cub", "red wolf", "red wolf cub"]);+});++test("numbers reject whitespace inside a literal; a space after a sign is A1111 syntax", () => {+ for (const text of ["1 2", "1 e2", "2. 5", "1 0-20"]) {+ assert.equal(parseAxisValues(text, "float").ok, false, text);+ assert.equal(parseAxisValues(text, "int").ok, false, text);+ }+ assert.deepEqual(values(" 12 , - 3, 1 - 3", "int"), [12, -3, 1, 2, 3]);+ assert.deepEqual(values("1e2, + 0.5", "float"), [100, 0.5]);+});++test("grid parameters: every LoRA by exact id at the first cell's weights, negative prompt when any cell engages it", () => {+ const ctx = sdxl({+ loraCapable: true,+ loras: [+ { id: "krea/Krea-2-LoRA-retro", weight: 0.8, label: "retro" },+ { id: "hub:odd/id", weight: 1, label: "odd" },+ ],+ prompt: "a fox",+ negativePrompt: "blurry",+ guidance: 1,+ });+ const p = plan([{ axisId: "guidance", text: "1, 7" }, { axisId: "steps", text: "4, 8" }], ctx);+ const first = buildCellRequest(p, p.order[0], base({ prompt: "a fox", negative_prompt: undefined, guidance: 1, loras: [{ id: "krea/Krea-2-LoRA-retro", weight: 0.8 }, { id: "hub:odd/id", weight: 1 }] }), ctx, { base: 1, keepRandom: false, seedFieldEmpty: false });+ assert.equal(first.negative_prompt, undefined, "the first cell runs at CFG 1 without the negative prompt");+ const info = gridParameters(p, ctx, [first], { steps: 4, guidance: 1, width: 64, height: 64, model: "m", keepRandomSeeds: false });+ const lines = info.split("\n");+ assert.equal(lines[0], "a fox");+ assert.equal(lines[1], "Negative prompt: blurry");+ assert.match(lines[2], /LoRAs: "krea\/Krea-2-LoRA-retro: 0\.8, hub:odd\/id: 1"/);+ // Hub ids restore from the field, not through the local-only prompt-tag matcher.+ assert.deepEqual(parseA1111Parameters(info)?.loras, ["krea/Krea-2-LoRA-retro:0.8", "hub:odd/id:1"]);+ // No cell engages it: not recorded.+ const flat = plan([{ axisId: "steps", text: "4, 8" }], ctx);+ assert.doesNotMatch(gridParameters(flat, ctx, [first], { steps: 4, guidance: 1, width: 64, height: 64, model: "m", keepRandomSeeds: false }), /Negative prompt/);+});++test("a lost response keeps the seed the compare cell was sent for Reuse last seed", () => {+ const p = plan([{ axisId: "seed", text: "11, 12" }]);+ const run = createCompareRun(p, sdxl(), { keepRandomSeeds: false, seedFieldEmpty: false });+ run.request(1, base(), 5);+ assert.equal(run.sentSeed(1), 12);+ assert.equal(run.sentSeed(0), undefined);+ const page = readSrc("features/images/images-page.tsx");+ assert.match(page, /setSessionSeed\(compare\?\.sentSeed\(i\) \?\? runBaseSeed\)/);+});++test("compare wiring: busy through composition, gated on preset hydration, no batch offset seed guard", () => {+ const panel = readSrc("features/images/compare/compare-panel.tsx");+ // `running` clears only in the finally that also wraps composition, and the button honours it.+ const body = panel.slice(panel.indexOf("const run = async"), panel.indexOf("const download ="));+ assert.ok(body.indexOf("composeGrid(") < body.indexOf("setRunning(null)"));+ assert.match(panel, /disabled=\{busy \|\| running !== null \|\| !preview\.ok\}/);+ const page = readSrc("features/images/images-page.tsx");+ assert.match(page, /busy=\{busy !== null \|\| compareRun !== null \|\| !imagePresets\.hydrated\}/);+ assert.match(page, /if \(busy !== null \|\| !imagePresets\.hydrated\) return;\n\s*compareOnce\.current = run;/);+ assert.match(page, /if \(!compare && baseSeed > Number\.MAX_SAFE_INTEGER - \(runs \* batchSize - 1\)\)/);+});++test("grid metadata records a ControlNet every cell shares, without its image", () => {+ const form = { steps: 25, guidance: 6, width: 1024, height: 1024, model: "m" };+ const steps = plan([{ axisId: "steps", text: "10, 20" }]);+ const controlnet = { id: "xinsir/canny", image: "data:image/png;base64,AAAA", control_type: "canny", strength: 0.7 };+ const reqs = steps.order.map((cell) => buildCellRequest(steps, cell, base({ controlnet }), sdxl(), { base: 1, keepRandom: false, seedFieldEmpty: false }));+ const fields = Object.fromEntries(gridRecipeFields(steps, reqs, form));+ assert.equal(fields["ControlNet 0"], "Module: canny, Model: xinsir/canny, Weight: 0.7");+ const mixed = Object.fromEntries(gridRecipeFields(steps, [base({ controlnet }), base()], form));+ assert.equal("ControlNet 0" in mixed, false);+ const none = Object.fromEntries(gridRecipeFields(steps, [base(), base()], form));+ assert.equal("ControlNet 0" in none, false);+});++test("a compare cell refused by the memory estimate offers no Generate anyway retry", () => {+ const page = readSrc("features/images/images-page.tsx");+ // The queued retry would run after the grid ended, as a plain form generation.+ assert.match(page, /if \(offerAnyway && compare\) \{\n\s*toast\.error\(MEMORY_REFUSAL_TITLE, \{\n\s*description: [^\n]*ALLOW_OVERSIZED_LABEL/);+ const compareBranch = page.slice(page.indexOf("if (offerAnyway && compare)"), page.indexOf("} else if (offerAnyway)"));+ assert.doesNotMatch(compareBranch, /setOversizedRetryQueued/);+});++test("grid metadata, every field x shared / varied / axis / absent: written only when every cell agrees", () => {+ const form = { steps: 25, guidance: 6, width: 1024, height: 1024, model: "m" };+ const axesOf = (ids: string[]) => ({ axes: ids.map((id) => ({ def: { id } })) }) as unknown as CompareGridPlan;+ const cn = (strength: number) => ({ id: "xinsir/canny", image: "data:image/png;base64,AAAA", control_type: "canny", strength });+ // [request key, axis id, field, value a, value b, the field's text when every cell sent a, its text when absent]+ const table: Array<[string, string, string, unknown, unknown, string | number, string | number | undefined]> = [+ ["steps", "steps", "Steps", 20, 30, 20, undefined],+ ["sampler", "sampler", "Sampler", "euler", "dpmpp_2m", "Euler", "Model default"],+ ["schedule_type", "schedule", "Schedule type", "karras", "exponential", "Karras", undefined],+ ["shift", "shift", "Shift", 3, 6, 3, undefined],+ ["base_shift", "base_shift", "Base shift", 0.5, 0.75, 0.5, undefined],+ ["max_shift", "max_shift", "Max shift", 1.15, 1.5, 1.15, undefined],+ ["guidance", "guidance", "CFG scale", 6, 7, 6, undefined],+ ["seed", "seed", "Seed", 1, 2, 1, undefined],+ ["variation_seed", "variation_seed", "Variation seed", 5, 6, 5, undefined],+ ["variation_strength", "variation_strength", "Variation seed strength", 0.1, 0.3, 0.1, undefined],+ ["width", "width", "Size", 1024, 768, "1024x1024", undefined],+ ["clip_skip", "clip_skip", "Clip skip", 2, 3, 2, undefined],+ ["cfg_rescale", "cfg_rescale", "CFG rescale", 0.7, 0.35, 0.7, undefined],+ ["prompt_weighting", "prompt_weighting", "Emphasis", false, true, "None", undefined],+ ["enhance_prompt", "enhance_prompt", "Prompt enhancement", false, true, "off", undefined],+ // Each cell's unit is a fresh object: compared by content.+ ["controlnet", "controlnet", "ControlNet 0", cn(0.7), cn(0.5), "Module: canny, Model: xinsir/canny, Weight: 0.7", undefined],+ ];+ const cell = (key: string, value: unknown): DiffusionGenerateRequest => {+ const req: Record<string, unknown> = { prompt: "p", batch_size: 1, height: 1024, ...(key === "width" ? {} : { width: 1024 }) };+ if (value !== undefined) req[key] = key === "controlnet" ? { ...(value as object) } : value;+ return req as unknown as DiffusionGenerateRequest;+ };+ const fieldOf = (plan: CompareGridPlan, cells: DiffusionGenerateRequest[], name: string) =>+ Object.fromEntries(gridRecipeFields(plan, cells, form))[name];+ for (const [key, axisId, name, a, b, sharedText, absentText] of table) {+ const none = axesOf([]);+ assert.equal(fieldOf(none, [cell(key, a), cell(key, a), null as never, cell(key, a)], name), sharedText, `${name} shared`);+ assert.equal(fieldOf(none, [cell(key, a), cell(key, b)], name), undefined, `${name} varied across cells`);+ assert.equal(fieldOf(none, [cell(key, a), cell(key, undefined)], name), undefined, `${name} on some cells only`);+ assert.equal(fieldOf(axesOf([axisId]), [cell(key, a), cell(key, a)], name), undefined, `${name} on an axis`);+ assert.equal(fieldOf(none, [cell(key, undefined), cell(key, undefined)], name), absentText, `${name} absent`);+ }+});++test("a Var. strength axis runs every cell on one variation seed; the grid restores the enhancer off", () => {+ const sdControls = { clip_skip: null, cfg_rescale: null, variation_seed: true, vary_strength: 0.2 } as never;+ const ctx = sdxl({ sdControls });+ const p = plan([{ axisId: "variation_strength", text: "0.1, 0.3, 0.5" }], ctx);+ let draws = 0;+ const run = createCompareRun(p, ctx, { keepRandomSeeds: false, seedFieldEmpty: false, rng: () => (++draws, 0.25) });+ const seeds = p.order.map((_, i) => (run.request(i, base(), 7) as unknown as Record<string, unknown>).variation_seed);+ assert.deepEqual(seeds, [2 ** 30, 2 ** 30, 2 ** 30]);+ assert.equal(draws, 1, "drawn once per run, not per cell");+ // Keep -1 for seeds with an empty seed box: the variation seed stays random as well.+ const keep = createCompareRun(p, ctx, { keepRandomSeeds: true, seedFieldEmpty: true, rng: () => 0.25 });+ assert.equal((keep.request(0, base(), 7) as unknown as Record<string, unknown>).variation_seed, undefined);+ // The enhancer compare/ forces off is recorded and parsed back as off.+ const off = buildCellRequest(p, 0, base({ enhance_prompt: true }), ctx, { base: 1, keepRandom: false, seedFieldEmpty: false });+ assert.equal(off.enhance_prompt, false);+ const info = gridParameters(plan([{ axisId: "steps", text: "4, 8" }]), sdxl(), [off, off], { steps: 4, guidance: 1, width: 64, height: 64, model: "m", keepRandomSeeds: false });+ assert.match(info, /Prompt enhancement: off/);+ assert.equal(parseA1111Parameters(info)?.prompt_enhancement, "off");+});++test("the SD controls axes reach the backend's request fields, the form's variation seed unshifted per cell", async () => {+ const { readFileSync } = await import("node:fs");+ const backend = readFileSync(new URL("../../backend/models/inference.py", import.meta.url), "utf8");+ const sdControls = { clip_skip: { min: 1, max: 12 }, cfg_rescale: { min: 0, max: 1 }, variation_seed: true, vary_strength: 0.2 };+ const ctx = sdxl({ sdControls });+ for (const [axisId, text] of [["variation_seed", "1, 2"], ["variation_strength", "0.1, 0.3"], ["clip_skip", "1, 2"], ["cfg_rescale", "0, 0.7"]]) {+ const p = plan([{ axisId, text }], ctx);+ const run = createCompareRun(p, ctx, { keepRandomSeeds: false, seedFieldEmpty: false, rng: () => 0.5 });+ const req = run.request(1, base(), 7) as unknown as Record<string, unknown>;+ assert.notEqual(req[axisId], undefined, axisId);+ // Every key a cell sends is a field of the backend's generate request.+ for (const key of ["variation_seed", "variation_strength", "clip_skip", "cfg_rescale"]) {+ if (req[key] !== undefined) assert.match(backend, new RegExp(`^\\s+${key}: Optional\\[`, "m"), key);+ }+ }+ // A Var. seed axis cell carries the implicit strength the backend needs to apply it.+ const vs = plan([{ axisId: "variation_seed", text: "1, 2" }], ctx);+ const cell = createCompareRun(vs, ctx, { keepRandomSeeds: false, seedFieldEmpty: false }).request(0, base(), 7) as unknown as Record<string, unknown>;+ assert.equal(cell.variation_strength, 0.2);+ // The page sends a compare grid the form's variation seed without the per-run offset.+ const page = readSrc("features/images/images-page.tsx");+ assert.match(page, /baseVariationSeed !== null \? \(baseVariationSeed \+ \(compare \? 0 : i \* batchSize\)\) % 2 \*\* 32 : null/);+ assert.match(page, /const compareSdControls = sdCaps;/);+});++test("variation seed table: a Var. strength sweep shares one seed across every cell, 0 included", () => {+ const sdControls = { clip_skip: null, cfg_rescale: null, variation_seed: true, vary_strength: 0.2 } as never;+ const ctx = sdxl({ sdControls });+ const p = plan([{ axisId: "variation_strength", text: "0, 0.3, 0.6" }], ctx);+ // [typed Variation seed, Keep -1 for seeds, seed box empty, expected per-cell variation seeds]+ const rows: Array<[number | null, boolean, boolean, Array<number | undefined>]> = [+ [1234, false, false, [1234, 1234, 1234]], // typed with the form's strength at 0: the typed seed, not a fresh draw+ [1234, true, true, [1234, 1234, 1234]], // typed wins over Keep -1 too+ [null, false, false, [2 ** 30, 2 ** 30, 2 ** 30]], // empty: one draw for the run+ [null, true, true, [undefined, undefined, undefined]], // Keep -1 and an empty seed box: random per cell+ ];+ for (const [typed, keepRandomSeeds, seedFieldEmpty, expected] of rows) {+ const run = createCompareRun(p, ctx, { keepRandomSeeds, seedFieldEmpty, rng: () => 0.25, variationSeed: typed });+ const reqs = p.order.map((_, i) => run.request(i, base(), 7));+ const label = `typed ${typed}, keep ${keepRandomSeeds}, empty ${seedFieldEmpty}`;+ assert.deepEqual(reqs.map((r) => (r as unknown as Record<string, unknown>).variation_seed), expected, label);+ const fields = Object.fromEntries(gridRecipeFields(p, run.requests, { steps: 25, guidance: 6, width: 1024, height: 1024, model: "m" }));+ assert.equal(fields["Variation seed"], expected[0], label);+ }+ const panel = readSrc("features/images/compare/compare-panel.tsx");+ assert.match(panel, /variationSeed: props\.variationSeed,/);+ const page = readSrc("features/images/images-page.tsx");+ assert.match(page, /variationSeed=\{sdCaps\?\.variation_seed \? parseVariationSeed\(sdChoice\.variationSeed\) : null\}/);+});++test("canvas table: the final, reflowed layout fits the side and pixel limits", () => {+ const long = Array.from({ length: 400 }, (_, i) => `word${i}`).join(" ");+ const wordy = Array.from({ length: 1000 }, (_, i) => `${"x".repeat(11)}${i % 10}`).join(" ");+ const huge = Array.from({ length: 5000 }, (_, i) => `w${i}`).join(" ");+ // [cols, rows, cell side, column label, row label]+ const rows: Array<[number, number, number, string, string]> = [+ [8, 8, 2752, "", ""],+ [1, 64, 2752, long, ""],+ // Narrower cells rewrap labels onto more lines: one shrink pass leaves this at 97x19218 (over the side limit).+ [1, 64, 512, wordy, ""],+ [64, 1, 512, wordy, ""],+ // So long that even 1 px cells with 10 px text cannot hold it: cut with an ellipsis, not drawn past the limits.+ [5, 1, 1024, huge, ""],+ [1, 64, 2752, huge, huge],+ [64, 1, 2752, "", long],+ [8, 8, 2752, long, long],+ [2, 2, 512, "a", "b"], // under the limits: unscaled+ ];+ for (const [cols, rows_, side, col, row] of rows) {+ const layout = gridLayout(+ {+ cols,+ rows: rows_,+ cellWidth: side,+ cellHeight: side,+ colLabels: Array(cols).fill(col),+ rowLabels: Array(rows_).fill(row),+ title: "",+ legend: true,+ margin: 0,+ },+ measure,+ );+ const label = `${cols}x${rows_} ${col ? "col label" : ""} ${row ? "row label" : ""}`;+ assert.ok(layout.width <= MAX_CANVAS_SIDE && layout.height <= MAX_CANVAS_SIDE, `${label}: ${layout.width}x${layout.height}`);+ assert.ok(layout.width * layout.height <= MAX_CANVAS_PIXELS, label);+ assert.equal(layout.cells.length, cols * rows_);+ }+});++test("Prompt S/R table: empty replacements kept, an empty search value refused, other text axes drop empties", () => {+ // [input, Prompt S/R values or an error pattern]+ const rows: Array<[string, string[] | RegExp]> = [+ ['red, ""', ["red", ""]],+ ["red,", ["red", ""]],+ ['red, "", blue', ["red", "", "blue"]],+ ["red\nblue\n", ["red", "blue"]], // a trailing newline is a blank line, not an empty value+ ['"", red', /first value/],+ ["", /No values/],+ ];+ for (const [text, expected] of rows) {+ const parsed = parseAxisValues(text, "str", { keepEmpty: true });+ if (expected instanceof RegExp) assert.match(parsed.ok ? "" : parsed.error, expected, text);+ else assert.deepEqual(parsed.ok ? parsed.values : parsed.error, expected, text);+ }+ assert.deepEqual(values('euler, ""', "str"), ["euler"]);+ // End to end: the empty cell removes the searched text from the prompt.+ const ctx = sdxl({ prompt: "a red fox" });+ const p = plan([{ axisId: "prompt_sr", text: 'red, ""' }], ctx);+ assert.deepEqual(+ [0, 1].map((i) => buildCellRequest(p, i, base({ prompt: "a red fox" }), ctx, { base: 1, keepRandom: false, seedFieldEmpty: false }).prompt),+ ["a red fox", "a fox"],+ );+});++test("sampler x schedule table: every cell must take its effective schedule, the form's included", () => {+ // [form sampler, form schedule, axes, ok or an error pattern]+ const rows: Array<[string, string, Array<{ axisId: string; text: string }>, true | RegExp]> = [+ ["euler", "karras", [{ axisId: "sampler", text: "euler, euler_a" }], /Euler a does not take the form's Karras schedule/],+ ["euler", "karras", [{ axisId: "sampler", text: "euler, dpmpp_2m" }], true],+ ["euler", "automatic", [{ axisId: "sampler", text: "euler, euler_a" }], true],+ // No Sampler axis: the form's own pair, already valid in the form.+ ["euler", "karras", [{ axisId: "steps", text: "10, 20" }], true],+ ["euler", "karras", [{ axisId: "sampler", text: "euler, euler_a" }, { axisId: "schedule", text: "automatic" }], true],+ ["euler", "automatic", [{ axisId: "sampler", text: "euler_a" }, { axisId: "schedule", text: "automatic, karras" }], /Schedule type Karras is not available with Euler a/],+ ];+ for (const [sampler, scheduleType, axes, expected] of rows) {+ const r = planCompare(axes, sdxl({ samplerChoice: { sampler, scheduleType } }));+ const label = `${sampler}/${scheduleType} ${axes.map((a) => `${a.axisId}=${a.text}`).join(" ")}`;+ if (expected === true) assert.ok(r.ok, `${label}: ${r.ok ? "" : r.error}`);+ else assert.match(r.ok ? "" : r.error, expected, label);+ }+});++test("compare wiring: the request's ControlNet predicate gates CFG rescale; a failed save is reported", () => {+ const page = readSrc("features/images/images-page.tsx");+ assert.match(page, /\n\s+controlnetEngaged,\n\s+\}\),/);+ assert.doesNotMatch(page, /controlnetEngaged: Boolean\(controlnetCapable && controlnetId && controlImage\)/);+ // A strength-0 ControlNet is not engaged, so the axis stays (the axes only read the flag).+ const sdControls = { clip_skip: null, cfg_rescale: { min: 0, max: 1 }, variation_seed: false } as never;+ assert.ok(availableAxes(sdxl({ sdControls, controlnetEngaged: false })).some((d) => d.id === "cfg_rescale"));+ assert.ok(!availableAxes(sdxl({ sdControls, controlnetEngaged: true })).some((d) => d.id === "cfg_rescale"));+ const panel = readSrc("features/images/compare/compare-panel.tsx");+ assert.match(panel, /if \(!isDownloadCancelled\(err\)\) \{\n\s+toast\.error\(/);+ assert.doesNotMatch(panel, /\.catch\(\(\) => \{\}\)/);+});++test("LoRA ids with commas or quotes round-trip through the grid's LoRAs field", () => {+ // [ids, expected restored entries]+ const rows: Array<[string[], string[]]> = [+ [["style, blue"], ["style, blue:0.5"]],+ [['say "hi"', "plain"], ['say "hi":0.5', "plain:0.5"]],+ [["a, b", "hub:odd/id", "c"], ["a, b:0.5", "hub:odd/id:0.5", "c:0.5"]],+ ];+ for (const [ids, expected] of rows) {+ const ctx = sdxl({ loraCapable: true, loras: ids.map((id) => ({ id, weight: 0.5, label: id })) });+ const first = base({ loras: ids.map((id) => ({ id, weight: 0.5 })) });+ const info = gridParameters(plan([{ axisId: "steps", text: "4, 8" }], ctx), ctx, [first], { steps: 4, guidance: 1, width: 64, height: 64, model: "m", keepRandomSeeds: false });+ assert.deepEqual(parseA1111Parameters(info)?.loras, expected, ids.join(" | "));+ }+});++test("an invalid typed Variation seed is refused for a compare run at any form strength", () => {+ const page = readSrc("features/images/images-page.tsx");+ assert.match(page, /const checkVariation = varying \|\| \(compareOnce\.current !== null && Boolean\(sdCaps\?\.variation_seed\)\);\n\s+if \(checkVariation && runChoice\.variationSeed\.trim\(\) && parseVariationSeed\(runChoice\.variationSeed\) === null\) \{\n\s+toast\.error/);+});