Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Layout N7-2: review fixes: the seed on cloud pictures, Edit layout twice, keyboard resize and readable box numbers

Claude15c5889d1767
diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsx
index a924b76a..bd1be573 100644
--- a/src/components/studio/composer.tsx
+++ b/src/components/studio/composer.tsx
@@ -54,10 +54,10 @@ import {
framesShape,
framesSlots,
framesUploading,
- layoutModelNote,
+ layoutBoxModel,
+ layoutNotes,
layoutRequest,
layoutShape,
- layoutSizeWarning,
leaveFrames,
leaveLayout,
namedImageSlots,
@@ -907,14 +907,8 @@ export function Composer({ docked }: { docked: boolean }) {
// The canvas the boxes are drawn on: the size this model renders (src/lib/catalog/plan.ts layoutCanvas).
const canvasFor = (aspect: string | undefined) => layoutCanvas(model!, { ...draft.params, aspectRatio: aspect }, studioOp ?? "t2i");
const layoutCanvasNow = layoutOn && model ? canvasFor(p.aspectRatio ?? model.defaults?.aspectRatio) : undefined;
- const boxModel = layoutOn && model && layoutModelNote(model) ? catalog.getModel(BOX_MODELS[model.engine]) : undefined;
- const layoutNotes: { text: string; tone: "info" | "warn" }[] = [];
- if (layoutOn && model) {
- const words = layoutModelNote(model);
- if (words) layoutNotes.push({ text: words, tone: "info" });
- const big = layoutCanvasNow && layoutSizeWarning(layoutCanvasNow, model.name);
- if (big) layoutNotes.push({ text: big, tone: "warn" });
- }
+ const boxModel = layoutOn && model ? layoutBoxModel(model, { id: BOX_MODELS[model.engine], getModel: catalog.getModel, offered: catalog.offered }) : undefined;
+ const layoutStripNotes = layoutOn ? layoutNotes(model, layoutCanvasNow) : [];
const layoutSummary = !model
? ""
: laid?.width
@@ -1104,8 +1098,8 @@ export function Composer({ docked }: { docked: boolean }) {
layout={draft.layout}
aspect={p.aspectRatio ?? model?.defaults?.aspectRatio}
summary={layoutSummary}
- notes={layoutNotes}
- action={boxModel && boxModel.id !== model?.id ? { label: `Use ${boxModel.name}`, onClick: () => pickModel(boxModel) } : undefined}
+ notes={layoutStripNotes}
+ action={boxModel ? { label: `Use ${boxModel.name}`, onClick: () => pickModel(boxModel) } : undefined}
onEdit={() => setLayoutEditing(true)}
onClose={toggleLayout}
/>
diff --git a/src/components/studio/layout-editor.tsx b/src/components/studio/layout-editor.tsx
index 2eb8e9ae..47def002 100644
--- a/src/components/studio/layout-editor.tsx
+++ b/src/components/studio/layout-editor.tsx
@@ -11,7 +11,7 @@ import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { copyWithToast } from "@/lib/clipboard";
import type { ModelDef } from "@/lib/catalog/types";
-import { boxesAt, drawnBox, movedBox, newBox, nudgedBox, pickBox, resizedBox, type Handle } from "@/lib/layout-edit";
+import { boxesAt, drawnBox, inkOn, keyResizedBox, KIND_COLOR, movedBox, newBox, nudgedBox, pickBox, resizedBox, type Handle } from "@/lib/layout-edit";
import { layoutCompilerFor, parseLayout, readsBoxes, type LayoutBox, type LayoutCanvas as CanvasType, type LayoutDraft, type LayoutItem, type LayoutLabel, type LayoutSource } from "@/lib/layout-prompt";
import { cn } from "@/lib/utils";
import { radioKeys, radioTab } from "./radio-keys";
@@ -49,7 +49,6 @@ const CANVASES: { value: CanvasType; label: string }[] = [
{ value: "collage", label: "Collage" },
];
/** Box outlines by kind when a box has no colour of its own. */
-const KIND_COLOR: Record<LayoutLabel, string> = { object: "#0a84ff", character: "#34c759", text: "#ff9f0a" };
const SOURCE_WORDS: Record<LayoutSource, string> = {
fuobe: "a Fuobe layout",
linxce: "a ComfyUI layout draft",
@@ -123,7 +122,7 @@ export function LayoutEditor(props: {
}
type Drag =
- | { mode: "draw"; x0: number; y0: number; x1: number; y1: number; id: number }
+ | { mode: "draw"; x0: number; y0: number; x1: number; y1: number; id: number; min: number }
| { mode: "move"; index: number; box: LayoutBox; sx: number; sy: number; moved: boolean; id: number; before: LayoutItem[] }
| { mode: "resize"; index: number; box: LayoutBox; handle: Handle; sx: number; sy: number; id: number; before: LayoutItem[] };
@@ -224,6 +223,9 @@ function LayoutBoard({
setSheetOpen(true);
};
+ /** The smallest box a drag draws, in canvas pixels: 8 px on screen (a tap's drift on a phone isn't a box). */
+ const minDrawn = () => (8 * size.width) / (board.current?.getBoundingClientRect().width || size.width);
+
/** Pointer position in canvas pixels. */
const at = (e: React.PointerEvent) => {
const r = board.current!.getBoundingClientRect();
@@ -255,7 +257,7 @@ function LayoutBoard({
if (picked === null) {
lastPress.current = null;
setSelected(null);
- setDrag({ mode: "draw", x0: p.x, y0: p.y, x1: p.x, y1: p.y, id: e.pointerId });
+ setDrag({ mode: "draw", x0: p.x, y0: p.y, x1: p.x, y1: p.y, id: e.pointerId, min: minDrawn() });
return;
}
setSelected(picked);
@@ -281,7 +283,7 @@ function LayoutBoard({
const onPointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
if (!drag || drag.id !== e.pointerId) return;
if (drag.mode === "draw") {
- const box = drawnBox(drag.x0, drag.y0, drag.x1, drag.y1, size.width, size.height);
+ const box = drawnBox(drag.x0, drag.y0, drag.x1, drag.y1, size.width, size.height, drag.min);
if (box) add(box);
}
// A drag isn't a press on the same spot: the next press there picks the top box again.
@@ -299,18 +301,21 @@ function LayoutBoard({
if (selected === null || !items[selected]) return;
if (e.key === "Delete" || e.key === "Backspace") {
e.preventDefault();
- return remove(selected);
+ remove(selected);
+ // The box's tab had focus and goes with it: the canvas keeps it, so the keys go on working.
+ board.current?.focus();
+ return;
}
- const box = nudgedBox(items[selected].box, e.key, e.shiftKey, size.width, size.height);
+ const box = e.altKey ? keyResizedBox(items[selected].box, e.key, e.shiftKey, size.width, size.height) : nudgedBox(items[selected].box, e.key, e.shiftKey, size.width, size.height);
if (box) {
e.preventDefault();
- // Undo takes back a nudge (a held key is one step).
+ // Undo takes back a nudge or a resize (a held key is one step).
if (!e.repeat) remember();
patch(selected, { box });
}
};
- const ghost = drag?.mode === "draw" ? drawnBox(drag.x0, drag.y0, drag.x1, drag.y1, size.width, size.height) : null;
+ const ghost = drag?.mode === "draw" ? drawnBox(drag.x0, drag.y0, drag.x1, drag.y1, size.width, size.height, drag.min) : null;
const compiled = () => layoutCompilerFor(model)(draft, size.width, size.height).prompt;
const textErrors = items.map((it) => it.label === "text" && !it.text?.trim());
const reads = !model || readsBoxes(model);
@@ -380,11 +385,14 @@ function LayoutBoard({
onChange={(e) => setAspect(e.target.value)}
className="h-8 rounded-full border bg-background px-2.5 text-[13px] focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none"
>
- {aspects.filter((a) => a !== "auto").map((a) => (
- <option key={a} value={a}>
- {a}
- </option>
- ))}
+ {/* Auto is a square canvas here; it stays listed only while it is the choice, so the select shows what is drawn. */}
+ {aspects
+ .filter((a) => a !== "auto" || aspect === "auto")
+ .map((a) => (
+ <option key={a} value={a}>
+ {a === "auto" ? "Auto (square canvas)" : a}
+ </option>
+ ))}
</select>
)}
<DropdownMenu modal={false}>
@@ -414,7 +422,7 @@ function LayoutBoard({
</Button>
</div>
<DialogDescription id="layout-editor-hint" className="w-full text-[12px] leading-snug text-muted-foreground max-sm:sr-only">
- Drag to draw a box, then say what goes in it; hold Shift to draw over another box. Layout prompts are experimental in MOSS-Image&apos;s own guide: boxes guide the picture, they don&apos;t pin it.
+ Drag to draw a box, then say what goes in it; hold Shift to draw over another box. With a box picked, arrow keys move it, Alt+arrows resize it (Shift for bigger steps) and Delete removes it. Layout prompts are experimental in MOSS-Image&apos;s own guide: boxes guide the picture, they don&apos;t pin it.
</DialogDescription>
</header>
@@ -425,7 +433,7 @@ function LayoutBoard({
<div
ref={board}
role="application"
- aria-label={`Layout canvas, ${size.width} by ${size.height}: drag to draw a box (Shift to draw over another). With a box picked, arrow keys move it and Delete removes it.`}
+ aria-label={`Layout canvas, ${size.width} by ${size.height}: drag to draw a box (Shift to draw over another). With a box picked, arrow keys move it, Alt with arrow keys resizes it and Delete removes it.`}
tabIndex={0}
data-layout-canvas
onPointerDown={onPointerDown}
@@ -450,8 +458,8 @@ function LayoutBoard({
onClick={() => setSelected(i)}
aria-label={`Box ${i + 1}: ${it.label === "text" ? `the words ${it.text || "(not typed yet)"}` : it.caption || it.label}`}
aria-pressed={selected === i}
- className="absolute bottom-full -left-0.5 flex h-5 min-w-5 items-center justify-center rounded-t-md px-1.5 text-[11px] leading-none font-semibold text-white focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none [@media(pointer:coarse)]:h-6 [@media(pointer:coarse)]:min-w-7"
- style={{ background: colorOf(it) }}
+ className="absolute bottom-full -left-0.5 flex h-5 min-w-5 items-center justify-center rounded-t-md px-1.5 text-[11px] leading-none font-semibold focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none [@media(pointer:coarse)]:h-6 [@media(pointer:coarse)]:min-w-7"
+ style={{ background: colorOf(it), color: inkOn(colorOf(it)) }}
>
{i + 1}
</button>
@@ -591,7 +599,7 @@ function BoxRow({
className={cn("space-y-2 rounded-xl border p-3 transition-colors", selected ? "border-primary bg-brand-faint/50" : "hover:border-border-strong")}
>
<div className="flex flex-wrap items-center gap-2">
- <span className="grid size-6 shrink-0 place-items-center rounded-md text-[12px] font-semibold text-white" style={{ background: colorOf(item) }} aria-hidden>
+ <span className="grid size-6 shrink-0 place-items-center rounded-md text-[12px] font-semibold" style={{ background: colorOf(item), color: inkOn(colorOf(item)) }} aria-hidden>
{n}
</span>
<Segmented label={`Box ${n} is`} options={LABELS} value={item.label} onChange={(label) => onChange({ label, ...(label === "text" ? { text: item.text ?? "" } : {}) })} />
diff --git a/src/components/studio/layout-strip.tsx b/src/components/studio/layout-strip.tsx
index 570229e2..0d57c0aa 100644
--- a/src/components/studio/layout-strip.tsx
+++ b/src/components/studio/layout-strip.tsx
@@ -2,11 +2,10 @@
import { FlaskConical, PencilRuler, X } from "lucide-react";
import { Button } from "@/components/ui/button";
+import { KIND_COLOR } from "@/lib/layout-edit";
import type { LayoutDraft } from "@/lib/layout-prompt";
import { cn } from "@/lib/utils";
-const KIND_COLOR = { object: "#0a84ff", character: "#34c759", text: "#ff9f0a" } as const;
-
const ratioOf = (aspect: string | undefined) => {
const m = /^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/.exec(aspect ?? "");
return m ? Number(m[1]) / Number(m[2]) : 1;
diff --git a/src/components/studio/studio-page.tsx b/src/components/studio/studio-page.tsx
index 3f7b81c1..f42f90c5 100644
--- a/src/components/studio/studio-page.tsx
+++ b/src/components/studio/studio-page.tsx
@@ -615,6 +615,8 @@ function LayoutHandoff() {
const opened = useRef<string | null>(null);
const ref = config.layout ? readEditLayoutParam(value) : null;
useEffect(() => {
+ // Once the address no longer holds it (read, then taken out), the same picture's Edit layout opens again next time.
+ if (!value) opened.current = null;
if (!ref || !value || opened.current === value || !catalog.ready) return;
opened.current = value;
void fetch(`/api/generations/${encodeURIComponent(ref.id)}`)
diff --git a/src/lib/catalog/payload.ts b/src/lib/catalog/payload.ts
index 3996944c..5e9807e1 100644
--- a/src/lib/catalog/payload.ts
+++ b/src/lib/catalog/payload.ts
@@ -997,14 +997,16 @@ export function extractOutputs(response: unknown, op?: Operation): ExtractedOutp
// cut-out (meta.mask) instead of landing in the feed as a second result.
const mask = fileOf(r.mask)?.url;
if (mask && out.some((o) => o.url !== mask)) out = out.filter((o) => o.url !== mask).map((o) => ({ ...o, meta: { ...o.meta, mask } }));
- // fal's MOSS-Image returns the layout its prompt expansion planned (actual_prompt) and the seed it drew with: kept on
- // each picture with the picture's own size, so Edit layout can reopen it as boxes (decodeMoss) and draw it again.
+ // The seed fal drew the pictures with is kept on each one, so Edit layout (and a layout's Reuse) draws it again with
+ // the same seed: a layout run turns the API's prompt expansion off, and FLUX.3 and Ideogram never return
+ // actual_prompt, so the seed can't wait for it. fal's MOSS-Image also returns the layout its expansion planned
+ // (actual_prompt): kept with the picture's own size, so Edit layout can reopen it as boxes (decodeMoss).
+ const seed = num(r.seed);
const actualPrompt = str(r.actual_prompt)?.trim();
if (actualPrompt) {
- const seed = num(r.seed);
const sizes = new Map((Array.isArray(r.images) ? r.images : []).filter(isObj).map((im) => [str(im.url), { width: num(im.width), height: num(im.height) }] as const));
out = out.map((o) => (o.kind === "image" ? { ...o, meta: { ...o.meta, ...compact({ actualPrompt, seed, ...sizes.get(o.url) }) } } : o));
- }
+ } else if (seed !== undefined) out = out.map((o) => (o.kind === "image" ? { ...o, meta: { ...o.meta, seed } } : o));
}
return out;
}
diff --git a/src/lib/catalog/plan.ts b/src/lib/catalog/plan.ts
index 77cf3cf0..4eeada8d 100644
--- a/src/lib/catalog/plan.ts
+++ b/src/lib/catalog/plan.ts
@@ -535,7 +535,10 @@ export function layoutCanvas(model: ModelDef, params: GenParams, op?: Operation)
return { ...sizeValue(size, aspect, res, sent), asked: sizeValue({ ...size, min: undefined, max: undefined }, aspect, res, sent), exact: true };
}
}
- const asked = computeDimensions(aspect, tier(res), { width: 1024, height: 1024 }, LAYOUT_MULTIPLE);
+ // A "<side>sq" tier (FLUX.3's 512sq / 768sq) is that square's area in the chosen aspect: a square of that side at 1:1.
+ const sq = /^(\d+)sq$/i.exec(res ?? "");
+ const side = sq ? Number(sq[1]) : 1024;
+ const asked = computeDimensions(aspect, sq ? undefined : tier(res), { width: side, height: side }, LAYOUT_MULTIPLE);
const fitted = model.engine === "open" ? fitCanvas(asked.width, asked.height, OPEN_CANVAS) : asked;
return { ...fitted, asked, exact: model.engine === "open" };
}
diff --git a/src/lib/composer.ts b/src/lib/composer.ts
index b310ed49..85be98ea 100644
--- a/src/lib/composer.ts
+++ b/src/lib/composer.ts
@@ -662,6 +662,31 @@ export function layoutSizeWarning(canvas: { width: number; height: number; asked
: `${size} is past ${LAYOUT_MAX_SIDE} px a side or 4 megapixels: ${modelName} may place the boxes less exactly`;
}
+/**
+ * The lines under the Layout strip: a model that reads the layout as words says so (its boxes are never placed by
+ * position, so it gets no size warning); a box reader past its range gets the size warning.
+ */
+export function layoutNotes(
+ model: Pick<ModelDef, "options" | "name"> | undefined,
+ canvas: Parameters<typeof layoutSizeWarning>[0] | undefined,
+): { text: string; tone: "info" | "warn" }[] {
+ if (!model) return [];
+ const words = layoutModelNote(model);
+ if (words) return [{ text: words, tone: "info" }];
+ const big = canvas && layoutSizeWarning(canvas, model.name);
+ return big ? [{ text: big, tone: "warn" }] : [];
+}
+
+/** The box reader the words-model line offers instead ("Use MOSS-Image"): only when Settings → Models & licences offers it. */
+export function layoutBoxModel(
+ model: Pick<ModelDef, "id" | "options" | "engine"> | undefined,
+ pick: { id: string; getModel: (id: string) => ModelDef | undefined; offered: (id: string, engine?: Engine) => boolean },
+): ModelDef | undefined {
+ if (!model || !layoutModelNote(model) || !pick.offered(pick.id, model.engine)) return undefined;
+ const m = pick.getModel(pick.id);
+ return m && m.id !== model.id ? m : undefined;
+}
+
/**
* Where a batch of files would land, before any of them uploads: each file's index goes to
* `placed` (it gets a slot or a reference tile) or `rejected` (no room: the references are full or
diff --git a/src/lib/layout-edit.ts b/src/lib/layout-edit.ts
index 9e5e4387..82821545 100644
--- a/src/lib/layout-edit.ts
+++ b/src/lib/layout-edit.ts
@@ -16,9 +16,12 @@ const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v
const snap = (v: number) => Math.round(v * 1e6) / 1e6;
const toBox = (x: number, y: number, w: number, h: number, width: number, height: number): LayoutBox => [snap(x / width), snap(y / height), snap((x + w) / width), snap((y + h) / height)];
-/** A box drawn from one corner to the other (canvas pixels), kept inside the canvas; null when smaller than MIN_BOX_PX. */
-export function drawnBox(x0: number, y0: number, x1: number, y1: number, width: number, height: number): LayoutBox | null {
- const r = rectFrom(x0, y0, x1, y1, { width, height }, MIN_BOX_PX);
+/**
+ * A box drawn from one corner to the other (canvas pixels), kept inside the canvas; null when a side is under `min`
+ * (MIN_BOX_PX, or more when the canvas is drawn small on screen: a tap's drift isn't a box).
+ */
+export function drawnBox(x0: number, y0: number, x1: number, y1: number, width: number, height: number, min = MIN_BOX_PX): LayoutBox | null {
+ const r = rectFrom(x0, y0, x1, y1, { width, height }, Math.max(MIN_BOX_PX, min));
return r ? toBox(r[0], r[1], r[2], r[3], width, height) : null;
}
@@ -82,8 +85,51 @@ export function nudgedBox(box: LayoutBox, key: string, shift: boolean, width: nu
return d ? movedBox(box, d[0], d[1], width, height) : null;
}
+/**
+ * Alt+arrow keys: resize from the right and bottom edges (Left / Right make it narrower / wider, Up / Down shorter /
+ * taller), one canvas pixel a press, ten with Shift; the same limits as a handle drag. Null for any other key.
+ */
+export function keyResizedBox(box: LayoutBox, key: string, shift: boolean, width: number, height: number): LayoutBox | null {
+ const step = shift ? 10 : 1;
+ const d = ({ ArrowLeft: ["e", -step, 0], ArrowRight: ["e", step, 0], ArrowUp: ["s", 0, -step], ArrowDown: ["s", 0, step] } as Record<string, [Handle, number, number]>)[key];
+ return d ? resizedBox(box, d[0], d[1], d[2], width, height) : null;
+}
+
/** A new box in the middle of the canvas, for the keyboard (Add box): a third of each side, nudged down for each one already there. */
export function newBox(count: number): LayoutBox {
const off = Math.min(0.3, (count % 6) * 0.05);
return [snap(1 / 3 + off / 2), snap(1 / 3 + off), snap(2 / 3 + off / 2), snap(2 / 3 + off)].map((v) => Math.min(1, v)) as LayoutBox;
}
+
+/**
+ * Each kind's box colour (the editor and the composer's strip). Object's blue is deep enough for white numbers at AA
+ * (4.7:1); Character's green and Text's orange take dark ones (inkOn).
+ */
+export const KIND_COLOR = { object: "#0071e3", character: "#34c759", text: "#ff9f0a" } as const;
+
+const DARK_INK = "#1d1d1f";
+const LIGHT_INK = "#ffffff";
+
+/** sRGB relative luminance of a #rgb / #rrggbb colour (WCAG 2), null when it isn't one. */
+function luminance(hex: string): number | null {
+ const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(hex.trim());
+ if (!m) return null;
+ const h = m[1].length === 3 ? [...m[1]].map((c) => c + c).join("") : m[1];
+ const [r, g, b] = [0, 2, 4].map((i) => {
+ const c = parseInt(h.slice(i, i + 2), 16) / 255;
+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
+ });
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
+}
+
+/** The contrast ratio of two colours (WCAG 2): 1 to 21. */
+export function contrastRatio(a: string, b: string): number {
+ const [la, lb] = [luminance(a) ?? 0, luminance(b) ?? 0];
+ return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);
+}
+
+/** The ink for a box's number on its colour: near-black on light colours (orange, green, a picked yellow), white on dark ones. */
+export function inkOn(color: string): string {
+ if (luminance(color) === null) return LIGHT_INK;
+ return contrastRatio(color, DARK_INK) >= contrastRatio(color, LIGHT_INK) ? DARK_INK : LIGHT_INK;
+}
diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.ts
index ad49d1c5..90fc17c6 100644
--- a/src/lib/output-actions.ts
+++ b/src/lib/output-actions.ts
@@ -248,7 +248,7 @@ export function editableLayout(g: Pick<Generation, "status" | "request" | "outpu
const reported = typeof o.meta?.seed === "number" ? o.meta.seed : undefined;
const seed = reported ?? (params.seed !== undefined && params.seed >= 0 ? params.seed : undefined);
const own = readLayout(params.extra?.[LAYOUT_PARAM]);
- if (own) return { draft: own, caption: g.request.prompt?.trim() || own.summary.caption, ...(seed !== undefined && { seed }), from: "request" };
+ if (own?.items.length) return { draft: own, caption: g.request.prompt?.trim() || own.summary.caption, ...(seed !== undefined && { seed }), from: "request" };
const planned = typeof o.meta?.actualPrompt === "string" ? o.meta.actualPrompt : undefined;
const width = Number(o.meta?.width ?? o.width);
const height = Number(o.meta?.height ?? o.height);
diff --git a/tests/comfy-provider.test.ts b/tests/comfy-provider.test.ts
index 6c23666f..2e4ab69e 100644
--- a/tests/comfy-provider.test.ts
+++ b/tests/comfy-provider.test.ts
@@ -97,6 +97,26 @@ describe("ComfyUI poll (S5)", () => {
expect(third).toMatchObject({ state: "failed", error: expect.stringMatching(/disappeared/) });
});
+ it("keeps the seed the graph drew with on each picture, so Edit layout draws it again (N7-2)", async () => {
+ // prepareWorkflow records the seed it put in the graph (one Fuobe picked when none was asked).
+ const ctx = { generationId: "g-seed", op: "t2i" as const, upload: async () => "x" };
+ expect((await prepareWorkflow("moss-image-t2i", { prompt: "p", seed: 4242 }, ctx)).meta.seed).toBe(4242);
+ const picked = (await prepareWorkflow("moss-image-t2i", { prompt: "p" }, ctx)).meta.seed;
+ expect(typeof picked).toBe("number");
+ handler = (url) =>
+ url.includes("/history/p-seed")
+ ? json({ "p-seed": done({ "3": { images: [{ filename: "fuobe_00001_.png", subfolder: "fuobe", type: "output" }, { filename: "fuobe_00002_.png", subfolder: "fuobe", type: "output" }] } }) })
+ : json({ queue_running: [], queue_pending: [] });
+ const res = await comfyProvider.poll(pollCtx("p-seed", { workflowId: "selftest-image", nodeCount: 3, seed: 4242 }));
+ expect(res.state).toBe("succeeded");
+ const outputs = (res as { outputs: { kind: string; meta?: Record<string, unknown> }[] }).outputs;
+ expect(outputs).toHaveLength(2);
+ expect(outputs.every((o) => o.kind === "image" && o.meta?.seed === 4242)).toBe(true);
+ // Without a recorded seed the pictures carry none.
+ const plain = await comfyProvider.poll(pollCtx("p-seed"));
+ expect((plain as { outputs: { meta?: Record<string, unknown> }[] }).outputs.some((o) => o.meta?.seed !== undefined)).toBe(false);
+ });
+
it("reports the queue position while pending", async () => {
handler = (url) => (url.includes("/history/") ? json({}) : json({ queue_running: [[0, "other"]], queue_pending: [[1, "x"], [2, "p-wait"]] }));
expect(await comfyProvider.poll(pollCtx("p-wait"))).toMatchObject({ state: "queued", message: "In ComfyUI queue · position 2" });
diff --git a/tests/e2e/composer-flows.mjs b/tests/e2e/composer-flows.mjs
index 609038b7..8bbea01e 100644
--- a/tests/e2e/composer-flows.mjs
+++ b/tests/e2e/composer-flows.mjs
@@ -279,12 +279,19 @@ async function ready(page, url) {
check("layout: Reuse brings the boxes and the caption back", /1 box/.test(reused) && (await page.locator("[data-composer] textarea").inputValue()) === "A candle sale poster");
await page.waitForFunction(() => document.querySelector("[data-gen-id] img, [data-gen-id] video"), null, { timeout: 60_000 }).catch(() => {});
const t = tile.locator(".group\\/tile").first();
- await t.hover();
- await t.getByRole("button", { name: "More actions" }).first().click();
- await page.getByRole("menuitem", { name: "Edit layout" }).click();
- await page.waitForFunction(() => !location.search.includes("layout="), null, { timeout: 30_000 }).catch(() => {});
- await page.locator("[data-layout-strip]").waitFor({ timeout: 30_000 }).catch(() => {});
- check("layout: Edit layout reopens the boxes", /1 box/.test(await page.locator("[data-layout-strip]").innerText().catch(() => "")));
+ // Edit layout from a state with no layout on screen (Reuse just put one there), twice on the same picture: the second
+ // time must open it again too.
+ for (const time of ["first", "second"]) {
+ await page.getByRole("button", { name: "Layout off" }).click();
+ const off = await page.locator("[data-layout-strip]").waitFor({ state: "detached", timeout: 10_000 }).then(() => true, () => false);
+ await t.hover();
+ await t.getByRole("button", { name: "More actions" }).first().click();
+ await page.getByRole("menuitem", { name: "Edit layout" }).click();
+ await page.locator("[data-layout-strip]").waitFor({ timeout: 30_000 }).catch(() => {});
+ const strip = await page.locator("[data-layout-strip]").innerText().catch(() => "");
+ check(`layout: Edit layout reopens the boxes (${time} time)`, off && /1 box/.test(strip), off ? strip.replace(/\n/g, " ") || "no strip" : "Layout off left the strip");
+ await page.waitForFunction(() => !location.search.includes("layout="), null, { timeout: 30_000 }).catch(() => {});
+ }
await page.close();
const ctx = await browser.newContext({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true });
diff --git a/tests/layout-mode.test.ts b/tests/layout-mode.test.ts
index 0a365808..2b3ff089 100644
--- a/tests/layout-mode.test.ts
+++ b/tests/layout-mode.test.ts
@@ -5,9 +5,9 @@ import { buildPayload, extractOutputs } from "@/lib/catalog/payload";
import { estimateCost, layoutCanvas, planGeneration } from "@/lib/catalog/plan";
import type { Generation, GenerationRequest, ModelDef, ModelRoute } from "@/lib/catalog/types";
import { fitCanvas } from "@/lib/comfy";
-import { enterLayout, groupModels, layoutModelNote, layoutRequest, layoutShape, layoutSizeWarning, leaveLayout, settingsShape, withoutLayout } from "@/lib/composer";
+import { enterLayout, groupModels, layoutBoxModel, layoutModelNote, layoutNotes, layoutRequest, layoutShape, layoutSizeWarning, leaveLayout, settingsShape, withoutLayout } from "@/lib/composer";
import { compileFlux3, compileIdeogram, compileMoss, compileWords, type LayoutDraft } from "@/lib/layout-prompt";
-import { boxesAt, drawnBox, movedBox, newBox, nudgedBox, pickBox, resizedBox } from "@/lib/layout-edit";
+import { boxesAt, contrastRatio, drawnBox, inkOn, keyResizedBox, KIND_COLOR, movedBox, newBox, nudgedBox, pickBox, resizedBox } from "@/lib/layout-edit";
import { editableLayout, editLayoutHref, outputActions, readEditLayoutParam } from "@/lib/output-actions";
import { slimModel } from "@/lib/studio-catalog";
@@ -76,6 +76,28 @@ describe("the composer's Layout mode helpers", () => {
expect(layoutModelNote(model("bria-fibo-2"))).toBe("This model reads the layout as words, not exact positions.");
});
+ it("gives a words model its one line (no size warning: it never places boxes by position), a box reader its warning", () => {
+ const big = { width: 4096, height: 4096, asked: { width: 4096, height: 4096 }, exact: false };
+ expect(layoutNotes(model("nano-banana-pro"), big)).toEqual([{ text: "This model reads the layout as words, not exact positions.", tone: "info" }]);
+ expect(layoutNotes(model("flux-3"), big)).toEqual([{ text: expect.stringContaining("FLUX.3 may place the boxes less exactly"), tone: "warn" }]);
+ expect(layoutNotes(model("flux-3"), { ...big, width: 1024, height: 1024, asked: { width: 1024, height: 1024 } })).toEqual([]);
+ });
+
+ it("offers Use MOSS-Image only when Settings → Models & licences offers it", () => {
+ const pick = (offered: boolean) => ({ id: "moss-image", getModel, offered: () => offered });
+ expect(layoutBoxModel(model("nano-banana-pro"), pick(true))?.id).toBe("moss-image");
+ expect(layoutBoxModel(model("nano-banana-pro"), pick(false))).toBeUndefined();
+ // A box reader needs no fix.
+ expect(layoutBoxModel(model("flux-3"), pick(true))).toBeUndefined();
+ });
+
+ it("reads FLUX.3's 512sq / 768sq tiers as that square's area, not the 1K guess", () => {
+ expect(layoutCanvas(model("flux-3"), { aspectRatio: "1:1", resolution: "512sq" })).toMatchObject({ width: 512, height: 512 });
+ const wide = layoutCanvas(model("flux-3"), { aspectRatio: "16:9", resolution: "768sq" });
+ expect(wide.width / wide.height).toBeCloseTo(16 / 9, 1);
+ expect(Math.abs(wide.width * wide.height - 768 * 768) / (768 * 768)).toBeLessThan(0.03);
+ });
+
it("warns past 2048 px a side or 4 MP, with the size the model renders instead", () => {
expect(layoutSizeWarning({ width: 1024, height: 1024, asked: { width: 1024, height: 1024 }, exact: true }, "MOSS-Image")).toBeNull();
expect(layoutSizeWarning({ width: 2048, height: 880, asked: { width: 2352, height: 1008 }, exact: true }, "MOSS-Image")).toBe(
@@ -235,8 +257,22 @@ describe("Edit layout", () => {
expect(editableLayout(gen({ request: laid, outputs: [{ url: "/a.mp4", kind: "video" }] }), 0)).toBeNull();
expect(editableLayout(gen({ outputs: [{ url: "/a.png", kind: "image", meta: { actualPrompt: "just words", width: 1024, height: 1024 } }] }), 0)).toBeNull();
expect(editableLayout(gen({ outputs: [{ url: "/a.png", kind: "image", meta: { actualPrompt: fixture.actual_prompt } }] }), 0)).toBeNull();
- // fal's other models' outputs never carry an actual_prompt.
- expect(extractOutputs({ images: [{ url: "https://x/a.png", width: 1, height: 1 }], seed: 3 }, "t2i")[0]).not.toHaveProperty("meta");
+ // fal's other models' outputs never carry an actual_prompt, only the seed.
+ expect(extractOutputs({ images: [{ url: "https://x/a.png", width: 1, height: 1 }], seed: 3 }, "t2i")[0]).toMatchObject({ meta: { seed: 3 } });
+ expect(extractOutputs({ images: [{ url: "https://x/a.png", width: 1, height: 1 }] }, "t2i")[0]).not.toHaveProperty("meta");
+ // A run with Layout on but no box drawn has nothing to reopen.
+ const empty = { feature: "image", modelId: "moss-image", prompt: "A poster", params: { extra: { layout: { ...poster, items: [] } } } } as GenerationRequest;
+ expect(editableLayout(gen({ request: empty }), 0)).toBeNull();
+ expect(outputActions(gen({ request: empty }), 0).some((a) => a.id === "edit-layout")).toBe(false);
+ });
+
+ it("reopens a cloud layout run (expansion off, no actual_prompt) with the seed fal drew it with", () => {
+ for (const modelId of ["moss-image", "flux-3", "ideogram-4-5"]) {
+ const r = sent(poster, "A candle sale poster");
+ const outputs = extractOutputs({ images: [{ url: "https://fal/x.png", width: 1360, height: 768, content_type: "image/png" }], seed: 918273 }, "t2i");
+ const g = gen({ modelId, outputs, request: { feature: "image", modelId, prompt: r.prompt, params: r.params } });
+ expect(editableLayout(g, 0)).toMatchObject({ seed: 918273, from: "request" });
+ }
});
it("links to the Image studio with the generation and the picture", () => {
@@ -276,6 +312,12 @@ describe("the editor's box maths", () => {
expect(drawnBox(500, 250, -50, -50, W, H)).toEqual([0, 0, 0.5, 0.5]);
expect(drawnBox(100.4, 50.4, 500.4, 250.4, W, H)).toEqual([0.1, 0.1, 0.5, 0.5]);
expect(drawnBox(100, 100, 108, 104, W, H)).toBeNull();
+ // A canvas drawn small on screen asks for more: a 20 px drift isn't a box when 8 screen px are 23 canvas px.
+ expect(drawnBox(100, 100, 120, 120, W, H)).not.toBeNull();
+ expect(drawnBox(100, 100, 120, 120, W, H, 23)).toBeNull();
+ expect(drawnBox(100, 100, 130, 130, W, H, 23)).not.toBeNull();
+ // Never below 16 px, whatever is asked.
+ expect(drawnBox(100, 100, 110, 110, W, H, 2)).toBeNull();
});
it("picks the top box, keeps a picked one under another, and cycles on the same spot", () => {
@@ -309,4 +351,28 @@ describe("the editor's box maths", () => {
expect(nudgedBox(box, "Enter", false, W, H)).toBeNull();
expect(newBox(0)).toEqual([0.333333, 0.333333, 0.666667, 0.666667]);
});
+
+ it("resizes from the keyboard: Alt+arrows move the right and bottom edges, Shift for ten", () => {
+ const box: [number, number, number, number] = [0.1, 0.1, 0.5, 0.5];
+ expect(keyResizedBox(box, "ArrowRight", false, W, H)).toEqual([0.1, 0.1, 0.501, 0.5]);
+ expect(keyResizedBox(box, "ArrowLeft", true, W, H)).toEqual([0.1, 0.1, 0.49, 0.5]);
+ expect(keyResizedBox(box, "ArrowDown", true, W, H)).toEqual([0.1, 0.1, 0.5, 0.52]);
+ expect(keyResizedBox(box, "ArrowUp", false, W, H)).toEqual([0.1, 0.1, 0.5, 0.498]);
+ // The same limits as a handle: held at the edge and at 16 px.
+ expect(keyResizedBox([0.1, 0.1, 0.995, 0.5], "ArrowRight", true, W, H)?.[2]).toBe(1);
+ const narrow = keyResizedBox([0.1, 0.1, 0.117, 0.5], "ArrowLeft", true, W, H)!;
+ expect(Math.round((narrow[2] - narrow[0]) * W)).toBe(16);
+ expect(keyResizedBox(box, "Enter", false, W, H)).toBeNull();
+ });
+
+ it("writes a box's number in the ink that reads on its colour (WCAG AA for the kind colours)", () => {
+ for (const c of Object.values(KIND_COLOR)) expect(contrastRatio(c, inkOn(c))).toBeGreaterThanOrEqual(4.5);
+ expect(inkOn(KIND_COLOR.object)).toBe("#ffffff");
+ expect(inkOn("#ff9f0a")).toBe("#1d1d1f");
+ expect(inkOn("#34c759")).toBe("#1d1d1f");
+ expect(inkOn("#ffff00")).toBe("#1d1d1f");
+ expect(inkOn("#ffffff")).toBe("#1d1d1f");
+ expect(inkOn("#1c1c80")).toBe("#ffffff");
+ expect(inkOn("not a colour")).toBe("#ffffff");
+ });
});