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: the plan compiles a layout at the size the model renders, Edit layout reads it back

Claude25e493bb62a0
diff --git a/src/components/studio/result-actions.tsx b/src/components/studio/result-actions.tsx
index 8df4770b..8180cdb7 100644
--- a/src/components/studio/result-actions.tsx
+++ b/src/components/studio/result-actions.tsx
@@ -18,6 +18,7 @@ import {
Heart,
ImagePlus,
Layers2,
+ LayoutDashboard,
Mic2,
MoreHorizontal,
Pin,
@@ -79,6 +80,7 @@ export const ACTION_ICONS: Record<OutputActionId, LucideIcon> = {
reference: ImagePlus,
grade: SlidersHorizontal,
layers: Layers2,
+ "edit-layout": LayoutDashboard,
"save-character": UserRoundPlus,
extend: FastForward,
reframe: Crop,
diff --git a/src/lib/catalog/payload.ts b/src/lib/catalog/payload.ts
index 8726545d..3996944c 100644
--- a/src/lib/catalog/payload.ts
+++ b/src/lib/catalog/payload.ts
@@ -997,6 +997,14 @@ 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.
+ 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));
+ }
}
return out;
}
diff --git a/src/lib/catalog/plan.ts b/src/lib/catalog/plan.ts
index cc2e6361..ddadfe21 100644
--- a/src/lib/catalog/plan.ts
+++ b/src/lib/catalog/plan.ts
@@ -17,6 +17,8 @@ import { cloudPath, fitLoras, gated, localOnly, loraCapacity, needsToken, routeL
import { anglesPrompt, anglesWords, ANGLES_ORIGINAL } from "./open-tools";
import { askedSize, numFramesValue, sizeValue } from "./payload";
import { characterScale, CINEMA_CROP, soulKind, soulMegapixels, soulRecipe, soulSize, type SoulOverlay } from "./soul";
+import { computeDimensions, fitCanvas } from "@/lib/comfy";
+import { carriesLayout, layoutCompilerFor, LAYOUT_MAX_SIDE, LAYOUT_MULTIPLE, LAYOUT_PARAM, readLayout, validateLayout, type LayoutDraft, type LayoutFormat } from "@/lib/layout-prompt";
/** Infer the operation from what the user attached. */
export function inferOperation(model: ModelDef, req: Pick<GenerationRequest, "op" | "inputs" | "params">): Operation {
@@ -140,6 +142,11 @@ export interface Plan {
* generation (the grade, an overlay) that the result's meta carries.
*/
soul?: { look?: string; words: string; triggers: string[]; grade?: string; overlay?: SoulOverlay; crop?: "21:9" };
+ /**
+ * A layout run (params.extra.layout, src/lib/layout-prompt.ts): the form the model reads it in, how many boxes, and
+ * the canvas it was compiled at when the model reads pixels (MOSS-Image: the exact size it renders).
+ */
+ layout?: { format: LayoutFormat | "words"; boxes: number; width?: number; height?: number };
}
/** Operations that work from their inputs alone. */
@@ -332,6 +339,17 @@ export function planGeneration(
if (!routesFor(model, op).length) {
throw new Error(`${model.name} can't do ${op} — try another model`);
}
+ // A layout (the Image studio's Layout mode, Edit layout, an API caller's draft): compiled for this model at the size it
+ // renders, the prompt as its caption; nothing rewrites it afterwards (Fuobe's enhancer, the API's prompt expansion).
+ let layoutPlan: Plan["layout"];
+ if (carriesLayout(params.extra)) {
+ const drawn = readLayout(params.extra![LAYOUT_PARAM]);
+ if (!drawn) throw new Error("The layout couldn't be read: draw its boxes again");
+ const compiled = planLayout(model, op, prompt, drawn, params);
+ prompt = compiled.prompt;
+ params = compiled.params;
+ layoutPlan = compiled.layout;
+ }
if (op === "finalize" && !params.draftId) throw new Error("Pick a draft to finish");
if (op === "dialogue" && !params.dialogue?.some((l) => l.text.trim())) throw new Error("Write at least one line");
if (op === "dub" && !params.targetLanguage) throw new Error("Pick a language to translate into");
@@ -412,6 +430,80 @@ export function planGeneration(
perJobOutputs,
...(notes.length && { notes }),
...(soulPlan && { soul: soulPlan }),
+ ...(layoutPlan && { layout: layoutPlan }),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Layouts
+
+/** A layout's canvas on your GPU: the graph's 16 px grid, up to 2048 a side (moss-image-t2i's limits), fitted as the ComfyUI provider fits a canvas the request names. */
+const OPEN_CANVAS = { dimensionMultiple: LAYOUT_MULTIPLE, maxWidth: LAYOUT_MAX_SIDE, maxHeight: LAYOUT_MAX_SIDE };
+
+/** "4k" / "2K" / "1k" → the resolution tiers computeDimensions knows ("4K"); anything else as it is. */
+const tier = (res: string | undefined) => (res && /^\d(\.\d)?k$/i.test(res) ? res.toUpperCase() : res);
+
+export interface LayoutCanvas {
+ /** The size the model renders, the size a pixel layout (MOSS-Image) is compiled at. */
+ width: number;
+ height: number;
+ /** The size the aspect ratio and resolution ask for, before the model's limits (a side past 2048 is scaled down). */
+ asked: { width: number; height: number };
+ /** False when the size is a guess from the resolution's name (a cloud model that takes an aspect ratio and a tier). */
+ exact: boolean;
+}
+
+/**
+ * The canvas a layout is drawn for on this model. On your GPU: the aspect ratio and resolution on the 16 px grid
+ * (computeDimensions), up to 2048 a side (fitCanvas, as the ComfyUI provider fits it). In the cloud: the route's size
+ * field (sizeValue: fal's MOSS-Image 512–2048), else a guess from the resolution's name (FLUX.3's "4k"). The layout
+ * keeps its boxes as fractions, so it is compiled at this size whatever it was drawn on.
+ */
+export function layoutCanvas(model: ModelDef, params: GenParams, op?: Operation): LayoutCanvas {
+ const aspect = params.aspectRatio ?? model.defaults?.aspectRatio;
+ const res = params.resolution ?? model.defaults?.resolution;
+ if (model.engine !== "open") {
+ const route = op ? routesFor(model, op)[0] : model.routes[0];
+ const size = route?.map?.size ?? route?.preview?.size;
+ if (size) {
+ const sent = size.key ? askedSize(params.extra?.[size.key]) : undefined;
+ 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);
+ const fitted = model.engine === "open" ? fitCanvas(asked.width, asked.height, OPEN_CANVAS) : asked;
+ return { ...fitted, asked, exact: model.engine === "open" };
+}
+
+/**
+ * A layout compiled for this model: the person's words (or the draft's own caption) as its caption, every box checked
+ * (a text box needs its words), the model's compiler (src/lib/layout-prompt.ts layoutCompilerFor) at the canvas it
+ * renders. A pixel layout (MOSS-Image) also names that canvas, so both engines render the size it was compiled at:
+ * params.extra.width / height on your GPU, the route's size field (fal's image_size) in the cloud. Bria FIBO 2 gets its
+ * VGL beside the words. Prompt rewriting is off for the run.
+ */
+function planLayout(model: ModelDef, op: Operation, prompt: string, drawn: LayoutDraft, params: GenParams): { prompt: string; params: GenParams; layout: NonNullable<Plan["layout"]> } {
+ const draft: LayoutDraft = { ...drawn, summary: { ...drawn.summary, caption: prompt.trim() || drawn.summary.caption.trim() } };
+ const format = model.options.layout;
+ const pixels = format === "moss";
+ const canvas = layoutCanvas(model, params, op);
+ // Only a pixel layout depends on the canvas (its sides on MOSS's 16 px grid); the others place boxes on a 0-1000 grid or in words.
+ const checkedAt = pixels ? canvas : { width: 1024, height: 1024 };
+ const problem = validateLayout(draft, checkedAt.width, checkedAt.height, format ?? "words").find((i) => i.level === "error");
+ if (problem) throw new Error(problem.message);
+ const compiled = layoutCompilerFor(model)(draft, canvas.width, canvas.height);
+ const extra: Record<string, unknown> = { ...params.extra };
+ if (pixels && draft.items.length) {
+ const route = routesFor(model, op)[0];
+ const key = (route?.map?.size ?? route?.preview?.size)?.key;
+ if (model.engine === "open") Object.assign(extra, { width: canvas.width, height: canvas.height });
+ else if (key) extra[key] = { width: canvas.width, height: canvas.height };
+ }
+ if (compiled.vgl && draft.items.length) extra.vgl = compiled.vgl;
+ return {
+ prompt: compiled.prompt,
+ params: { ...params, enhancePrompt: false, extra },
+ layout: { format: compiled.format, boxes: draft.items.length, ...(pixels && { width: canvas.width, height: canvas.height }) },
};
}
@@ -716,7 +808,9 @@ function sentMegapixels(params: GenParams): number | undefined {
* payload sends it. fal's megapixel is 1024 × 1024 pixels. Undefined when the route sends no size.
*/
function routeMegapixels(model: ModelDef, params: GenParams, op?: Operation): number | undefined {
- const size = (op ? model.routes.find((r) => r.op === op) : model.routes[0])?.map?.size;
+ const route = op ? model.routes.find((r) => r.op === op) : model.routes[0];
+ // The browser's catalog keeps the size field as route.preview (slimModel).
+ const size = route?.map?.size ?? route?.preview?.size;
if (!size) return undefined;
const asked = size.key ? askedSize(params.extra?.[size.key]) : undefined;
const { width, height } = sizeValue(size, params.aspectRatio ?? model.defaults?.aspectRatio, params.resolution ?? model.defaults?.resolution, asked);
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index d1f39740..bf6e68c5 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -489,10 +489,10 @@ export interface ModelRoute {
endpoint: string;
map?: FieldMap;
/**
- * The parts of `map` the composer previews a result with ("1920×1080 → 2880×1620", an EXR frame count),
- * kept by slimModel when it drops the field maps for the browser. The server reads `map`.
+ * The parts of `map` the composer previews a result with ("1920×1080 → 2880×1620", an EXR frame count, the canvas a
+ * layout is compiled at), kept by slimModel when it drops the field maps for the browser. The server reads `map`.
*/
- preview?: Pick<FieldMap, "upscaleFactor" | "numFrames">;
+ preview?: Pick<FieldMap, "upscaleFactor" | "numFrames" | "size">;
/** Optional note shown in the UI (e.g. "uses Lightx2v 4-step LoRA"). */
note?: string;
/**
diff --git a/src/lib/composer.ts b/src/lib/composer.ts
index 25c1c0f0..d65ae57d 100644
--- a/src/lib/composer.ts
+++ b/src/lib/composer.ts
@@ -13,6 +13,7 @@ import { FACE_MOSAIC_MODELS } from "./catalog/open-tools";
import { soulPostStep } from "./catalog/soul";
import { COLORMAPS, type Engine, type GenParams, type InputSlot, type MatteOutput, type MediaKind, type ModelDef, type Operation, type Preset, type VideoFormat } from "./catalog/types";
import { spokenLanguageName } from "./speech-languages";
+import { LAYOUT_MAX_PIXELS, LAYOUT_MAX_SIDE, LAYOUT_PARAM, readLayout, readsBoxes, type LayoutDraft } from "./layout-prompt";
// ---------------------------------------------------------------------------
// Settings summary ("16:9 · 720p · 5s · ×1")
@@ -103,6 +104,11 @@ export function framesShape(shape: SettingsShape, chained: boolean): SettingsSha
return { ...shape, duration: null, multiShot: false, count: shape.count && !chained };
}
+/** Layout mode's settings: the boxes are compiled as drawn, so nothing rewrites the prompt (no Enhance). */
+export function layoutShape(shape: SettingsShape): SettingsShape {
+ return { ...shape, enhance: false };
+}
+
export const MATTE_OUTPUT_LABELS: Record<MatteOutput, string> = { cutout: "Cutout video", matte: "Alpha mask" };
export const colormapLabel = (v: string) => v.charAt(0).toUpperCase() + v.slice(1);
@@ -586,6 +592,69 @@ export function leaveFrames<T extends Attachment>(frames: FrameAttachment<T>[],
return { slots: { ...slots, image: frames[0]?.value ?? null, endImage: end, mask: null, sketch: null }, dropped: Math.max(0, frames.length - 2) };
}
+// ---------------------------------------------------------------------------
+// Layout mode (Image studio): boxes on the picture, one row per box (src/lib/layout-prompt.ts)
+
+/**
+ * Layout mode on: an empty layout on the picture's shape (the aspect ratio picked, else the model's). The prompt stays
+ * as it is: in Layout mode it is the whole picture's caption.
+ */
+export function enterLayout(params: GenParams, model?: Pick<ModelDef, "defaults">): LayoutDraft {
+ const aspect = params.aspectRatio ?? model?.defaults?.aspectRatio;
+ return { summary: { caption: "", meta: [], canvas: "single" }, items: [], ...(aspect && aspect !== "auto" && { aspect }) };
+}
+
+/**
+ * What Layout mode sends: the prompt as written, and the layout as params.extra.layout with the prompt as its caption,
+ * on the shape it is drawn on. The plan compiles it for the model at the size it renders (src/lib/catalog/plan.ts
+ * planLayout) and turns prompt rewriting off; the request keeps the draft for Reuse and Edit layout.
+ */
+export function layoutRequest(layout: LayoutDraft, prompt: string, params: GenParams): { prompt: string; params: GenParams } {
+ const aspect = params.aspectRatio && params.aspectRatio !== "auto" ? params.aspectRatio : layout.aspect;
+ const draft: LayoutDraft = { ...layout, summary: { ...layout.summary, caption: prompt.trim() }, ...(aspect && { aspect }) };
+ return { prompt, params: { ...params, extra: { ...params.extra, [LAYOUT_PARAM]: draft } } };
+}
+
+/**
+ * Layout mode off: the boxes go (`dropped` counts them, so the composer offers Undo) and any layout the params still
+ * carry with them; the prompt stays as written.
+ */
+export function leaveLayout(layout: LayoutDraft | undefined, params: GenParams): { params: GenParams; dropped: number } {
+ return { params: withoutLayout(params).params, dropped: layout?.items.length ?? 0 };
+}
+
+/**
+ * A request's params with its layout taken out (Reuse, Edit layout): the layout goes back to Layout mode, the rest to
+ * the settings. `layout` is undefined when there was none (or it can't be read).
+ */
+export function withoutLayout(params: GenParams): { params: GenParams; layout?: LayoutDraft } {
+ if (!params.extra || !(LAYOUT_PARAM in params.extra)) return { params };
+ const extra = { ...params.extra };
+ const layout = readLayout(extra[LAYOUT_PARAM]) ?? undefined;
+ delete extra[LAYOUT_PARAM];
+ return { params: { ...params, extra: Object.keys(extra).length ? extra : undefined }, ...(layout && { layout }) };
+}
+
+/** The one line under the boxes for a model that doesn't place them by their coordinates (none for one that does). */
+export function layoutModelNote(model: Pick<ModelDef, "options"> | undefined): string | null {
+ return !model || readsBoxes(model) ? null : "This model reads the layout as words, not exact positions.";
+}
+
+/**
+ * The warning when the picture asked for is past what box-reading models were made for (2048 px a side, 4 MP): said
+ * with the size the model renders instead, when it scales it down (the boxes keep their places), else that the boxes
+ * may drift. Null when the size is within range.
+ */
+export function layoutSizeWarning(canvas: { width: number; height: number; asked: { width: number; height: number }; exact: boolean }, modelName: string): string | null {
+ const { asked } = canvas;
+ if (Math.max(asked.width, asked.height) <= LAYOUT_MAX_SIDE && asked.width * asked.height <= LAYOUT_MAX_PIXELS) return null;
+ const size = `${canvas.exact ? "" : "about "}${asked.width} × ${asked.height}`;
+ const scaled = canvas.width !== asked.width || canvas.height !== asked.height;
+ return scaled
+ ? `${size} is past ${LAYOUT_MAX_SIDE} px a side, so ${modelName} renders ${canvas.width} × ${canvas.height}; the boxes keep their places`
+ : `${size} is past ${LAYOUT_MAX_SIDE} px a side or 4 megapixels: ${modelName} may place the boxes less exactly`;
+}
+
/**
* 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
@@ -892,7 +961,7 @@ export function bestForStudio(models: ModelDef[], engine: Engine, defaultId: str
}
export interface ModelGroup {
- id: "recent" | "starred" | "best" | "all" | "results";
+ id: "boxes" | "recent" | "starred" | "best" | "all" | "results";
label: string;
models: ModelDef[];
}
@@ -925,15 +994,17 @@ export function groupModels(input: {
recent: string[];
starred: string[];
best: string[];
+ /** Layout mode: the models that place boxes by their coordinates come first ("Reads your boxes"). */
+ boxes?: boolean;
}): { groups: ModelGroup[]; count: number } {
- const { models, engine, engines, query, recent, starred, best } = input;
+ const { models, engine, engines, query, recent, starred, best, boxes } = input;
const q = query.trim();
if (q) {
const hits = models
.filter((m) => engines.includes(m.engine))
.map((m, i) => ({ m, s: matchScore(m, q), i }))
.filter((x) => x.s >= 0)
- .sort((a, b) => a.s - b.s || Number(a.m.engine !== engine) - Number(b.m.engine !== engine) || a.i - b.i)
+ .sort((a, b) => a.s - b.s || (boxes ? Number(!readsBoxes(a.m)) - Number(!readsBoxes(b.m)) : 0) || Number(a.m.engine !== engine) - Number(b.m.engine !== engine) || a.i - b.i)
.map((x) => x.m);
return { groups: hits.length ? [{ id: "results", label: "Results", models: hits }] : [], count: hits.length };
}
@@ -951,6 +1022,7 @@ export function groupModels(input: {
return out;
};
const groups: ModelGroup[] = [
+ ...(boxes ? [{ id: "boxes" as const, label: "Reads your boxes", models: take(pool.filter((m) => readsBoxes(m)).map((m) => m.id), 50) }] : []),
{ id: "recent", label: "Recent", models: take(recent, 3) },
{ id: "starred", label: "Starred", models: take(starred, 50) },
{ id: "best", label: "Best for this studio", models: take(best, 4) },
diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.ts
index 381a860f..ad49d1c5 100644
--- a/src/lib/output-actions.ts
+++ b/src/lib/output-actions.ts
@@ -10,6 +10,7 @@ import { cueText, type Cue } from "./cues";
import { downloadHref, downloadName, extensionOf } from "./library";
import { PRESETS as GRADE_PRESETS } from "./grade";
import { storedPath } from "./share";
+import { decodeMoss, LAYOUT_PARAM, readLayout, type LayoutDraft } from "./layout-prompt";
export type OutputActionId =
| "animate"
@@ -18,6 +19,7 @@ export type OutputActionId =
| "reference"
| "grade"
| "layers"
+ | "edit-layout"
| "save-character"
| "extend"
| "reframe"
@@ -101,6 +103,8 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =
link("reference", "Use as reference", `/image?ref=${q(o.url)}`);
link("grade", "Color grade", `/color-grade?image=${q(o.url)}`);
link("layers", "Open in Layers", layersHref(g, o.url));
+ // A picture drawn from a layout (or one fal's MOSS-Image planned itself) reopens as boxes in the Image studio.
+ if (editableLayout(g, index)) link("edit-layout", "Edit layout", editLayoutHref(g, index));
link("genjutsu", "Animate with Genjutsu", `/genjutsu?mode=motion&image=${q(o.url)}`);
out.push({ id: "save-character", label: "Save as character", placement: "menu" });
break;
@@ -208,6 +212,52 @@ export function isVector(g: Pick<Generation, "provider" | "op">, o: Pick<OutputF
return svg && (g.provider !== "mock" || g.op === "vectorize");
}
+// ---------------------------------------------------------------------------
+// Edit layout: a picture's boxes, back in the Image studio's Layout mode
+
+/** The query param that opens the Image studio on a result's layout: `<generation id>` or `<id>.<output index>`. */
+export const EDIT_LAYOUT_PARAM = "layout";
+
+export const editLayoutHref = (g: Pick<Generation, "id">, index: number) => `/image?${EDIT_LAYOUT_PARAM}=${q(index ? `${g.id}.${index}` : g.id)}`;
+
+/** `<id>` or `<id>.<index>` → the generation and output it names (null for anything else). */
+export function readEditLayoutParam(v: string | null | undefined): { id: string; index: number } | null {
+ const m = /^([A-Za-z0-9_-]{4,64})(?:\.(\d{1,2}))?$/.exec(v ?? "");
+ return m ? { id: m[1], index: Number(m[2] ?? 0) } : null;
+}
+
+export interface EditableLayout {
+ draft: LayoutDraft;
+ /** The words for the whole picture (the composer's prompt in Layout mode). */
+ caption: string;
+ /** The seed this picture was drawn with, when it is known: the one its provider reported (meta.seed), else the request's. */
+ seed?: number;
+ /** Where the boxes came from: the layout the request carried, or the one fal's prompt expansion planned. */
+ from: "request" | "expansion";
+}
+
+/**
+ * The layout a picture can be reopened as (Edit layout): the request's own (params.extra.layout), else, for a picture
+ * fal's MOSS-Image planned itself (its actual_prompt), that plan decoded at the picture's own size, so even a plain
+ * prompt's render opens as boxes. Null when there is none to open (no layout, or a plan with no boxes).
+ */
+export function editableLayout(g: Pick<Generation, "status" | "request" | "outputs">, index: number): EditableLayout | null {
+ const o = g.outputs[index];
+ if (g.status !== "succeeded" || o?.kind !== "image") return null;
+ const params = g.request.params ?? {};
+ 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" };
+ 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);
+ if (!planned || !(width > 0 && height > 0)) return null;
+ const draft = decodeMoss(planned, width, height);
+ if (!draft?.items.length) return null;
+ return { draft, caption: draft.summary.caption.trim() || g.request.prompt?.trim() || "", ...(seed !== undefined && { seed }), from: "expansion" };
+}
+
/**
* Open an image in the Layers editor (/layers?image=…). A layers result opens with its layers
* already split, on the picture it was made from.
diff --git a/src/lib/studio-catalog.ts b/src/lib/studio-catalog.ts
index 02c5b42b..59b0491d 100644
--- a/src/lib/studio-catalog.ts
+++ b/src/lib/studio-catalog.ts
@@ -22,8 +22,8 @@ export function slimModel(m: ModelDef): ModelDef {
routes: m.routes.map((r) => {
const copy = { ...r };
delete copy.map;
- const { upscaleFactor, numFrames } = r.map ?? {};
- if (upscaleFactor || numFrames) copy.preview = { ...(upscaleFactor && { upscaleFactor }), ...(numFrames && { numFrames }) };
+ const { upscaleFactor, numFrames, size } = r.map ?? {};
+ if (upscaleFactor || numFrames || size) copy.preview = { ...(upscaleFactor && { upscaleFactor }), ...(numFrames && { numFrames }), ...(size && { size }) };
return copy;
}),
};
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 067d5fb2..1f763bc4 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -49,6 +49,7 @@ import { listElements } from "./elements";
import { pollTrainings } from "./training";
import { createExtendChain, createKeyframeFilm, createMosaicRun, createRelitClip, createShotFilm, createStillTo3d } from "./chains";
import { enhancePrompt, enhanceSoulWords } from "./enhance";
+import { carriesLayout } from "@/lib/layout-prompt";
import { setResolver, watchGenerations, type LiveEvent } from "./live";
import { provider, PROVIDERS, RETIRED_PROVIDER_ERROR } from "./providers";
import { comfyLoraFiles, probeComfy } from "./providers/comfyui";
@@ -1212,7 +1213,8 @@ async function submit(
return adapter.prepareFile(data, f.contentType, f.name, route);
};
let prompt = plan.prompt;
- if (req.params?.enhancePrompt && prompt) {
+ // A layout's prompt is compiled boxes (plan.layout): the enhancer would rewrite them, so it never runs on one.
+ if (req.params?.enhancePrompt && prompt && !plan.layout && !carriesLayout(req.params?.extra)) {
update(id, { message: "Enhancing prompt" });
const words = plan.soul?.words;
const at = words ? prompt.indexOf(words) : -1;
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index 6bbfb376..23507f9f 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -1277,7 +1277,8 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,
return {
manifest,
workflow: wf,
- meta: { workflowId: manifest.id, nodeCount: Object.keys(wf).length, prefix: `fuobe/${ctx.generationId}`, ...(metaBatch ? { metaBatch: true } : {}) },
+ // The seed the graph drew with (one Fuobe picked when none was asked): its pictures keep it, so Edit layout redraws the same one.
+ meta: { workflowId: manifest.id, nodeCount: Object.keys(wf).length, prefix: `fuobe/${ctx.generationId}`, ...(metaBatch ? { metaBatch: true } : {}), ...(b.seed && typeof values.seed === "number" ? { seed: values.seed } : {}) },
};
}
@@ -1491,6 +1492,8 @@ export const comfyProvider: ProviderAdapter = {
} catch (e) {
return { state: "failed" as const, error: (e as Error).message };
}
+ const seed = typeof meta.seed === "number" ? meta.seed : undefined;
+ if (seed !== undefined) outputs = outputs.map((o) => (o.kind === "image" ? { ...o, meta: { ...o.meta, seed } } : o));
return { state: "succeeded" as const, outputs: await withLayerBoxes(outputs) };
};
const isDone = (e: HistoryEntry | undefined): e is HistoryEntry => !!e && (!!e.status?.completed || e.status?.status_str === "success" || e.status?.status_str === "error");
diff --git a/tests/fixtures/moss-actual-prompt.json b/tests/fixtures/moss-actual-prompt.json
new file mode 100644
index 00000000..9153a0ed
--- /dev/null
+++ b/tests/fixtures/moss-actual-prompt.json
@@ -0,0 +1,7 @@
+{
+ "_note": "A hand-written fal-ai/moss-image response in the shape of its OpenAPI output (images[], seed, has_nsfw_concepts[], actual_prompt): the layout its prompt expansion planned, with bbox before text as fal's own sample orders it. Not copied from fal; written for Fuobe's Edit layout test.",
+ "images": [{ "url": "https://v3.fal.media/files/example/moss-poster.png", "content_type": "image/png", "width": 1360, "height": 768 }],
+ "seed": 418207,
+ "has_nsfw_concepts": [false],
+ "actual_prompt": "{\"summary\":{\"caption\":\"A warm autumn sale poster for a candle shop\",\"canvas\":\"single\",\"meta\":[\"poster\",\"flat design\"]},\"items\":[{\"label\":\"text\",\"caption\":\"Large cream serif headline\",\"bbox\":[-320,-560,-160,560],\"text\":\"秋季特卖 30% OFF\"},{\"label\":\"object\",\"caption\":\"Three lit amber candles on a wooden tray\",\"bbox\":[-96,-400,320,400],\"tags\":[\"warm light\"]}],\"bbox_coord_space\":\"abs_centralized\",\"bbox_format\":\"yxyx\"}"
+}
diff --git a/tests/layout-mode-server.test.ts b/tests/layout-mode-server.test.ts
new file mode 100644
index 00000000..707ab4dc
--- /dev/null
+++ b/tests/layout-mode-server.test.ts
@@ -0,0 +1,66 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import type { LayoutDraft } from "@/lib/layout-prompt";
+
+// N7-2: a layout run never goes through Fuobe's prompt enhancer (it would rewrite the boxes), even when the request asks
+// for it; a plain prompt still does. Demo mode (no keys, no GPU): the mock provider makes the picture.
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-layout-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+
+const enhanced = vi.hoisted(() => ({ calls: [] as string[] }));
+vi.mock("@/server/enhance", async (orig) => ({
+ ...(await orig<typeof import("@/server/enhance")>()),
+ enhancePrompt: async (p: string) => {
+ enhanced.calls.push(p);
+ return `${p}, cinematic, richly detailed`;
+ },
+}));
+
+const { setSetting } = await import("@/server/settings");
+const { createGenerations, getGeneration, previewGeneration } = await import("@/server/generations");
+
+beforeAll(() => setSetting("demoMode", "auto"));
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+const poster: LayoutDraft = {
+ summary: { caption: "A candle sale poster", meta: [], canvas: "single" },
+ items: [{ label: "text", caption: "Bold serif", text: "30% OFF", box: [0.1, 0.05, 0.9, 0.2] }],
+};
+
+const settled = async (id: string) => {
+ await vi.waitFor(() => expect(getGeneration(id)?.status).not.toBe("queued"), { timeout: 5000 });
+ return getGeneration(id)!;
+};
+
+describe("a layout request on the server", () => {
+ it("ignores enhancePrompt and keeps the compiled layout as the prompt", async () => {
+ enhanced.calls.length = 0;
+ const [g] = createGenerations({ feature: "image", modelId: "moss-image", prompt: "A candle sale poster", params: { aspectRatio: "1:1", enhancePrompt: true, extra: { layout: poster } } });
+ const done = await settled(g.id);
+ expect(enhanced.calls).toEqual([]);
+ expect(done.provider).toBe("mock");
+ expect(JSON.parse(done.prompt!)).toMatchObject({ summary: { caption: "A candle sale poster" }, items: [{ text: "30% OFF", bbox: [-461, -410, -307, 410] }], bbox_coord_space: "abs_centralized" });
+ // The stored request keeps the draft and the person's words, for Reuse and Edit layout.
+ expect(done.request.prompt).toBe("A candle sale poster");
+ expect(done.request.params?.extra?.layout).toEqual(poster);
+ });
+
+ it("still enhances a plain prompt that asks for it", async () => {
+ enhanced.calls.length = 0;
+ const [g] = createGenerations({ feature: "image", modelId: "moss-image", prompt: "a candle", params: { aspectRatio: "1:1", enhancePrompt: true } });
+ const done = await settled(g.id);
+ expect(enhanced.calls).toEqual(["a candle"]);
+ expect(done.prompt).toBe("a candle, cinematic, richly detailed");
+ });
+
+ it("previews the compiled prompt at the canvas both engines render", () => {
+ const cloud = previewGeneration({ feature: "image", modelId: "moss-image", prompt: "A candle sale poster", params: { aspectRatio: "16:9", extra: { layout: poster } } });
+ const open = previewGeneration({ feature: "image", modelId: "oss-moss-image", prompt: "A candle sale poster", params: { aspectRatio: "16:9", extra: { layout: poster } } });
+ expect(cloud.prompt).toBe(open.prompt);
+ expect(cloud.costUsd).toBe(0);
+ expect(() => previewGeneration({ feature: "image", modelId: "moss-image", prompt: "x", params: { extra: { layout: { ...poster, items: [{ ...poster.items[0], text: "" }] } } } })).toThrow("Type the words for box 1");
+ });
+});
diff --git a/tests/layout-mode.test.ts b/tests/layout-mode.test.ts
new file mode 100644
index 00000000..c8d2dd42
--- /dev/null
+++ b/tests/layout-mode.test.ts
@@ -0,0 +1,248 @@
+import fs from "node:fs";
+import { describe, expect, it } from "vitest";
+import { getModel, getPreset } from "@/lib/catalog";
+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 { compileFlux3, compileIdeogram, compileMoss, compileWords, type LayoutDraft } from "@/lib/layout-prompt";
+import { editableLayout, editLayoutHref, outputActions, readEditLayoutParam } from "@/lib/output-actions";
+import { slimModel } from "@/lib/studio-catalog";
+
+// N7-2 (docs/research/new-models-7.md §5.3): Layout mode in the Image studio. The composer sends the neutral draft
+// (params.extra.layout) with the prompt as its caption; the plan compiles it for the model at the exact size it renders;
+// results reopen as boxes (Edit layout), from the request's own draft or from fal's actual_prompt.
+
+const poster: LayoutDraft = {
+ summary: { caption: "", meta: ["poster"], canvas: "single" },
+ items: [
+ { label: "text", caption: "Bold cream serif", text: "30% OFF", box: [0.1, 0.05, 0.9, 0.2], color: "#ff3b30" },
+ { label: "object", caption: "Three lit candles", box: [0.25, 0.35, 0.75, 0.9] },
+ ],
+ aspect: "16:9",
+};
+
+const model = (id: string) => getModel(id)!;
+const plan = (modelId: string, params: GenerationRequest["params"], prompt = "A candle sale poster", lookup: (id: string) => ModelDef | undefined = getModel) =>
+ planGeneration({ feature: "image", op: "t2i", modelId, prompt, params } as GenerationRequest, lookup, getPreset);
+const sent = (layout: LayoutDraft, prompt: string, params: GenerationRequest["params"] = {}) => layoutRequest(layout, prompt, params ?? {});
+
+describe("the composer's Layout mode helpers", () => {
+ it("enters on the picture's shape with an empty layout, the prompt left as the caption", () => {
+ expect(enterLayout({ aspectRatio: "3:2" })).toEqual({ summary: { caption: "", meta: [], canvas: "single" }, items: [], aspect: "3:2" });
+ expect(enterLayout({}, { defaults: { aspectRatio: "1:1" } }).aspect).toBe("1:1");
+ expect(enterLayout({ aspectRatio: "auto" })).not.toHaveProperty("aspect");
+ });
+
+ it("sends the draft as params.extra.layout, captioned with the prompt, on the shape picked", () => {
+ const r = sent(poster, " A candle sale poster ", { aspectRatio: "1:1", seed: 7, extra: { quality: "quality" } });
+ expect(r.prompt).toBe(" A candle sale poster ");
+ expect(r.params).toMatchObject({ aspectRatio: "1:1", seed: 7, extra: { quality: "quality" } });
+ const layout = r.params.extra!.layout as LayoutDraft;
+ expect(layout.summary.caption).toBe("A candle sale poster");
+ expect(layout.aspect).toBe("1:1");
+ expect(layout.items).toEqual(poster.items);
+ // The draft in the composer is untouched.
+ expect(poster.summary.caption).toBe("");
+ });
+
+ it("leaves with the boxes counted (for Undo) and no layout in the params", () => {
+ expect(leaveLayout(poster, { aspectRatio: "16:9", extra: { layout: poster, quality: "fast" } })).toEqual({ params: { aspectRatio: "16:9", extra: { quality: "fast" } }, dropped: 2 });
+ expect(leaveLayout(undefined, { aspectRatio: "16:9" })).toEqual({ params: { aspectRatio: "16:9" }, dropped: 0 });
+ expect(leaveLayout(poster, { extra: { layout: poster } }).params).toEqual({ extra: undefined });
+ });
+
+ it("takes a request's layout back out of its params (Reuse), and drops one it can't read", () => {
+ const { params, layout } = withoutLayout(sent(poster, "A poster", { seed: 3 }).params);
+ expect(params).toEqual({ seed: 3, extra: undefined });
+ expect(layout?.items.map((i) => i.box)).toEqual(poster.items.map((i) => i.box));
+ expect(layout?.summary.caption).toBe("A poster");
+ expect(withoutLayout({ extra: { layout: "nonsense", quality: "fast" } })).toEqual({ params: { extra: { quality: "fast" } } });
+ expect(withoutLayout({ seed: 1 })).toEqual({ params: { seed: 1 } });
+ });
+
+ it("hides Enhance (nothing rewrites the boxes)", () => {
+ const shape = settingsShape(model("oss-moss-image"), "t2i", "image", true);
+ expect(shape.enhance).toBe(true);
+ expect(layoutShape(shape)).toEqual({ ...shape, enhance: false });
+ });
+
+ it("says once when a model reads the layout as words", () => {
+ for (const id of ["oss-moss-image", "moss-image", "flux-3", "ideogram-4-5"]) expect(layoutModelNote(model(id))).toBeNull();
+ expect(layoutModelNote(model("nano-banana-pro"))).toBe("This model reads the layout as words, not exact positions.");
+ // Bria FIBO 2 places boxes with location words, not coordinates.
+ expect(layoutModelNote(model("bria-fibo-2"))).toBe("This model reads the layout as words, not exact positions.");
+ });
+
+ 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(
+ "2352 × 1008 is past 2048 px a side, so MOSS-Image renders 2048 × 880; the boxes keep their places",
+ );
+ expect(layoutSizeWarning({ width: 4096, height: 4096, asked: { width: 4096, height: 4096 }, exact: false }, "FLUX.3")).toBe(
+ "about 4096 × 4096 is past 2048 px a side or 4 megapixels: FLUX.3 may place the boxes less exactly",
+ );
+ });
+
+ it("lists the models that read boxes first in the picker", () => {
+ const models = ["nano-banana-pro", "moss-image", "flux-3", "ideogram-4-5", "bria-fibo-2"].map(model);
+ const base = { models, engine: "cloud" as const, engines: ["cloud" as const], query: "", recent: ["nano-banana-pro"], starred: [], best: [] };
+ expect(groupModels(base).groups.map((g) => g.id)).toEqual(["recent", "all"]);
+ const laid = groupModels({ ...base, boxes: true }).groups;
+ expect(laid[0]).toMatchObject({ id: "boxes", label: "Reads your boxes" });
+ expect(laid[0].models.map((m) => m.id)).toEqual(["moss-image", "flux-3", "ideogram-4-5"]);
+ // A search ranks them first among equal matches too.
+ const hits = groupModels({ ...base, boxes: true, query: "image" }).groups[0].models.map((m) => m.id);
+ expect(hits.indexOf("moss-image")).toBeLessThan(hits.indexOf("nano-banana-pro"));
+ });
+});
+
+describe("the plan compiles the layout at the size the model renders", () => {
+ it("on your GPU: the aspect ratio and resolution on the 16 px grid, sent as the graph's width and height", () => {
+ const p = plan("oss-moss-image", { aspectRatio: "16:9", resolution: "1K", extra: { layout: poster } });
+ expect(p.params.extra).toMatchObject({ width: 1360, height: 768 });
+ expect(p.prompt).toBe(compileMoss({ ...poster, summary: { ...poster.summary, caption: "A candle sale poster" } }, 1360, 768));
+ expect(p.layout).toEqual({ format: "moss", boxes: 2, width: 1360, height: 768 });
+ expect(p.params.enhancePrompt).toBe(false);
+ expect(p.params.extra?.layout).toBeDefined();
+ expect(estimateCost(p.model, p.params)).toBe(0);
+ });
+
+ it("on your GPU: a side past 2048 is scaled down whole, as the ComfyUI provider fits a canvas the request names", () => {
+ const p = plan("oss-moss-image", { aspectRatio: "21:9", resolution: "1.5K", extra: { layout: poster } });
+ expect(p.params.extra).toMatchObject({ width: 2048, height: 880 });
+ // The provider fits params.extra.width / height with the manifest's limits: the same size, so the boxes land where drawn.
+ const manifest = JSON.parse(fs.readFileSync("workflows/comfyui/manifest.json", "utf8")) as { workflows: { id: string; limits: Record<string, number> }[] };
+ const limits = manifest.workflows.find((w) => w.id === "moss-image-t2i")!.limits;
+ expect(fitCanvas(2048, 880, limits)).toEqual({ width: 2048, height: 880 });
+ expect(layoutCanvas(model("oss-moss-image"), { aspectRatio: "21:9", resolution: "1.5K" })).toEqual({ width: 2048, height: 880, asked: { width: 2352, height: 1008 }, exact: true });
+ });
+
+ it("on fal: image_size equal to the canvas, prompt expansion off, priced for that size", () => {
+ const m = model("moss-image");
+ const p = plan("moss-image", { aspectRatio: "16:9", extra: { layout: poster } });
+ expect(p.params.extra?.image_size).toEqual({ width: 1360, height: 768 });
+ const out = buildPayload((m.routes[0] as ModelRoute).map!, { prompt: p.prompt, ...p.params });
+ expect(out).toMatchObject({ image_size: { width: 1360, height: 768 }, enable_prompt_expansion: false, output_format: "png" });
+ expect(out.prompt).toBe(compileMoss({ ...poster, summary: { ...poster.summary, caption: "A candle sale poster" } }, 1360, 768));
+ expect(out).not.toHaveProperty("layout");
+ expect(estimateCost(p.model, p.params, 1, p.op)).toBe(Math.round(0.05 * ((1360 * 768) / 1048576) * 1000) / 1000);
+ });
+
+ it("on fal: a canvas asked for is clamped to 512–2048 with the minimum respected", () => {
+ const p = plan("moss-image", { extra: { layout: poster, image_size: { width: 3000, height: 300 } } });
+ expect(p.params.extra?.image_size).toEqual({ width: 2048, height: 512 });
+ expect(p.layout).toMatchObject({ width: 2048, height: 512 });
+ const small = plan("moss-image", { extra: { layout: poster, image_size: { width: 300, height: 300 } } });
+ expect(small.params.extra?.image_size).toEqual({ width: 512, height: 512 });
+ });
+
+ it("compiles the same at the browser's slim catalog (route sizes kept as previews)", () => {
+ const slim = slimModel(model("moss-image"));
+ expect(slim.routes[0].map).toBeUndefined();
+ const p = plan("moss-image", { aspectRatio: "16:9", extra: { layout: poster } }, "A candle sale poster", (id) => (id === slim.id ? slim : getModel(id)));
+ expect(p.params.extra?.image_size).toEqual({ width: 1360, height: 768 });
+ expect(estimateCost(p.model, p.params, 1, p.op)).toBe(estimateCost(model("moss-image"), p.params, 1, p.op));
+ });
+
+ it("gives FLUX.3 and Ideogram 4.5 their own compilers, expansion off, and every other model plain sentences", () => {
+ const captioned = { ...poster, summary: { ...poster.summary, caption: "A candle sale poster" } };
+ const flux = plan("flux-3", { aspectRatio: "16:9", extra: { layout: poster } });
+ expect(flux.prompt).toBe(compileFlux3(captioned));
+ expect(buildPayload(model("flux-3").routes[0].map!, { prompt: flux.prompt, ...flux.params }).enable_prompt_expansion).toBe(false);
+ const ideo = plan("ideogram-4-5", { aspectRatio: "16:9", extra: { layout: poster } });
+ expect(ideo.prompt).toBe(compileIdeogram(captioned));
+ expect(buildPayload(model("ideogram-4-5").routes[0].map!, { prompt: ideo.prompt, ...ideo.params }).enable_prompt_expansion).toBe(false);
+ // Neither renders a size Fuobe names: no image_size of their own.
+ expect(flux.params.extra).not.toHaveProperty("image_size");
+ const nano = plan("nano-banana-pro", { aspectRatio: "16:9", extra: { layout: poster } });
+ expect(nano.prompt).toBe(compileWords(captioned));
+ expect(nano.layout).toEqual({ format: "words", boxes: 2 });
+ // Bria FIBO 2 gets its VGL beside the words.
+ const bria = plan("bria-fibo-2", { aspectRatio: "1:1", extra: { layout: poster } });
+ expect(bria.params.extra?.vgl).toMatchObject({ text_render: [{ text: "30% OFF" }] });
+ });
+
+ it("refuses a text box without its words, and an unreadable layout", () => {
+ const empty: LayoutDraft = { ...poster, items: [{ ...poster.items[0], text: " " }, poster.items[1]] };
+ expect(() => plan("moss-image", { extra: { layout: empty } })).toThrow("Type the words for box 1");
+ expect(() => plan("oss-moss-image", { extra: { layout: { items: "x" } } })).toThrow(/couldn't be read/);
+ });
+
+ it("is a plain prompt with no boxes, its caption the prompt", () => {
+ const p = plan("moss-image", { extra: { layout: { ...poster, items: [] } } });
+ expect(p.prompt).toBe("A candle sale poster");
+ expect(p.params.extra).not.toHaveProperty("image_size");
+ });
+});
+
+describe("Edit layout", () => {
+ const fixture = JSON.parse(fs.readFileSync("tests/fixtures/moss-actual-prompt.json", "utf8")) as Record<string, unknown>;
+ const gen = (over: Partial<Generation>): Generation =>
+ ({
+ id: "gen_abc123",
+ status: "succeeded",
+ kind: "image",
+ op: "t2i",
+ feature: "image",
+ modelId: "moss-image",
+ outputs: [{ url: "/api/files/outputs/a.png", kind: "image" }],
+ request: { feature: "image", modelId: "moss-image", prompt: "A candle sale poster", params: {} },
+ ...over,
+ }) as Generation;
+
+ it("reopens a layout run's own draft with its seed", () => {
+ const r = sent(poster, "A candle sale poster", { seed: 41 });
+ const g = gen({ request: { feature: "image", modelId: "moss-image", prompt: r.prompt, params: r.params } });
+ const e = editableLayout(g, 0)!;
+ expect(e).toMatchObject({ caption: "A candle sale poster", seed: 41, from: "request" });
+ expect(e.draft.items.map((i) => i.text ?? i.caption)).toEqual(["30% OFF", "Three lit candles"]);
+ // The seed the provider reported (ComfyUI's own pick, fal's) wins over the request's.
+ const reported = gen({ request: g.request, outputs: [{ url: "/api/files/outputs/a.png", kind: "image", meta: { seed: 99 } }] });
+ expect(editableLayout(reported, 0)?.seed).toBe(99);
+ expect(outputActions(g, 0).find((a) => a.id === "edit-layout")).toEqual({ id: "edit-layout", label: "Edit layout", placement: "menu", href: "/image?layout=gen_abc123" });
+ });
+
+ it("decodes fal's actual_prompt at the picture's own size, so a plain prompt's render opens as boxes", () => {
+ const outputs = extractOutputs(fixture, "t2i");
+ expect(outputs).toHaveLength(1);
+ expect(outputs[0].meta).toMatchObject({ seed: 418207, width: 1360, height: 768 });
+ const g = gen({ outputs: outputs.map((o) => ({ ...o, url: "/api/files/outputs/b.png" })), request: { feature: "image", modelId: "moss-image", prompt: "candle sale poster", params: {} } });
+ const e = editableLayout(g, 0)!;
+ expect(e.from).toBe("expansion");
+ expect(e.seed).toBe(418207);
+ expect(e.caption).toBe("A warm autumn sale poster for a candle shop");
+ expect(e.draft.summary.meta).toEqual(["poster", "flat design"]);
+ expect(e.draft.items.map((i) => [i.label, i.text ?? null])).toEqual([["text", "秋季特卖 30% OFF"], ["object", null]]);
+ // Compiled again at the same size, the boxes are the ones fal planned (y before x, from the centre).
+ const again = JSON.parse(compileMoss(e.draft, 1360, 768)) as { items: { bbox: number[] }[] };
+ expect(again.items.map((i) => i.bbox)).toEqual([
+ [-320, -560, -160, 560],
+ [-96, -400, 320, 400],
+ ]);
+ expect(outputActions(g, 0).some((a) => a.id === "edit-layout")).toBe(true);
+ });
+
+ it("is offered only when it can work", () => {
+ expect(editableLayout(gen({}), 0)).toBeNull();
+ expect(outputActions(gen({}), 0).some((a) => a.id === "edit-layout")).toBe(false);
+ // Still running, a video, a plan with no boxes, a plan without the picture's size.
+ const r = sent(poster, "A poster");
+ const laid = { feature: "image", modelId: "moss-image", prompt: "A poster", params: r.params } as GenerationRequest;
+ expect(editableLayout(gen({ status: "running", request: laid }), 0)).toBeNull();
+ 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");
+ });
+
+ it("links to the Image studio with the generation and the picture", () => {
+ expect(editLayoutHref({ id: "gen_abc123" }, 0)).toBe("/image?layout=gen_abc123");
+ expect(editLayoutHref({ id: "gen_abc123" }, 2)).toBe("/image?layout=gen_abc123.2");
+ expect(readEditLayoutParam("gen_abc123.2")).toEqual({ id: "gen_abc123", index: 2 });
+ expect(readEditLayoutParam("gen_abc123")).toEqual({ id: "gen_abc123", index: 0 });
+ for (const bad of ["", null, "../etc", "a.b", "x".repeat(80)]) expect(readEditLayoutParam(bad)).toBeNull();
+ });
+});
diff --git a/tests/moss-image.test.ts b/tests/moss-image.test.ts
index 646d8d36..4d4f179e 100644
--- a/tests/moss-image.test.ts
+++ b/tests/moss-image.test.ts
@@ -90,9 +90,11 @@ describe("moss-image on fal", () => {
expect(plain).not.toHaveProperty("enable_prompt_expansion");
const compiled = layoutCompilerFor(cloud)(poster, 1024, 1024);
expect(compiled.format).toBe("moss");
- const laid = payload({ extra: { layout: poster, image_size: { width: 1024, height: 1024 } } }, compiled.prompt);
+ // The plan compiles the draft (N7-2): the prompt is its caption.
+ const laid = payload({ aspectRatio: "1:1", extra: { layout: poster } }, poster.summary.caption);
expect(laid.enable_prompt_expansion).toBe(false);
expect(laid.prompt).toBe(compiled.prompt);
+ expect(laid.image_size).toEqual({ width: 1024, height: 1024 });
// The draft rides along for Reuse; it is never sent as a field.
expect(laid).not.toHaveProperty("layout");
});