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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Layers: projects, versions and tool jobs (server + API)
Claudee2c2a31b3409
diff --git a/src/app/api/layers/[id]/jobs/[jobId]/route.ts b/src/app/api/layers/[id]/jobs/[jobId]/route.tsnew file mode 100644index 00000000..807c428f--- /dev/null+++ b/src/app/api/layers/[id]/jobs/[jobId]/route.ts@@ -0,0 +1,20 @@+import { z } from "zod";+import { endJob } from "@/server/layers";++const Patch = z.object({ state: z.enum(["dismissed", "applied"]) });++/** Dismiss a finished job (a failure you've read, a text detection you've used). */+export async function PATCH(request: Request, ctx: RouteContext<"/api/layers/[id]/jobs/[jobId]">) {+ const { id, jobId } = await ctx.params;+ const parsed = Patch.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: "Invalid change" }, { status: 400 });+ const job = await endJob(id, jobId, { state: parsed.data.state });+ return job ? Response.json(job) : Response.json({ error: "Not found" }, { status: 404 });+}++/** Cancel a job that's still running (its generations are canceled too). */+export async function DELETE(_req: Request, ctx: RouteContext<"/api/layers/[id]/jobs/[jobId]">) {+ const { id, jobId } = await ctx.params;+ const job = await endJob(id, jobId, { cancel: true });+ return job ? Response.json(job) : Response.json({ error: "Not found" }, { status: 404 });+}diff --git a/src/app/api/layers/[id]/jobs/route.ts b/src/app/api/layers/[id]/jobs/route.tsnew file mode 100644index 00000000..5bb43b4b--- /dev/null+++ b/src/app/api/layers/[id]/jobs/route.ts@@ -0,0 +1,17 @@+import { JobInputSchema, LayersError, startJob } from "@/server/layers";++/**+ * Start a tool (decompose, separate a layer, edit text, remove background, a regional edit, upscale,+ * relight, angles, expand, generate a layer): its generations run on the chosen engine; the editor+ * applies the result when it lands. 422 with the reason when it can't start.+ */+export async function POST(request: Request, ctx: RouteContext<"/api/layers/[id]/jobs">) {+ const { id } = await ctx.params;+ const parsed = JobInputSchema.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: "Could not start the tool: the request was incomplete" }, { status: 400 });+ try {+ return Response.json(startJob(id, parsed.data), { status: 201 });+ } catch (e) {+ return Response.json({ error: (e as Error).message }, { status: e instanceof LayersError ? e.status : 422 });+ }+}diff --git a/src/app/api/layers/[id]/route.ts b/src/app/api/layers/[id]/route.tsnew file mode 100644index 00000000..4dd45d42--- /dev/null+++ b/src/app/api/layers/[id]/route.ts@@ -0,0 +1,39 @@+import { connection } from "next/server";+import { z } from "zod";+import { deleteProject, LayersError, parseDoc, projectView, updateProject } from "@/server/layers";++const Patch = z.object({+ name: z.string().max(200).optional(),+ /** Autosave: the document as the editor shows it, written into the head version. */+ doc: z.unknown().optional(),+ /** The head version the editor started from (a mismatch means another tab saved a version). */+ versionId: z.string().max(40).optional(),+});++/** The project, its versions, the head document and its tools' jobs (with their results). */+export async function GET(_req: Request, ctx: RouteContext<"/api/layers/[id]">) {+ await connection();+ const { id } = await ctx.params;+ const view = projectView(id);+ return view ? Response.json(view) : Response.json({ error: "Not found" }, { status: 404 });+}++export async function PATCH(request: Request, ctx: RouteContext<"/api/layers/[id]">) {+ const { id } = await ctx.params;+ const parsed = Patch.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: "Invalid change" }, { status: 400 });+ const doc = parsed.data.doc === undefined ? undefined : parseDoc(parsed.data.doc);+ if (doc === null) return Response.json({ error: "Those layers couldn't be saved" }, { status: 400 });+ try {+ const p = updateProject(id, { name: parsed.data.name, doc, versionId: parsed.data.versionId });+ return p ? Response.json(p) : Response.json({ error: "Not found" }, { status: 404 });+ } catch (e) {+ return Response.json({ error: (e as Error).message }, { status: e instanceof LayersError ? e.status : 422 });+ }+}++/** Delete the project and all of its versions; its images stay in the library. */+export async function DELETE(_req: Request, ctx: RouteContext<"/api/layers/[id]">) {+ const { id } = await ctx.params;+ return deleteProject(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });+}diff --git a/src/app/api/layers/[id]/versions/route.ts b/src/app/api/layers/[id]/versions/route.tsnew file mode 100644index 00000000..2824f60f--- /dev/null+++ b/src/app/api/layers/[id]/versions/route.ts@@ -0,0 +1,25 @@+import { z } from "zod";+import { createVersion, LayersError, parseDoc } from "@/server/layers";++const Body = z.object({+ doc: z.unknown().optional(),+ label: z.string().max(120).optional(),+ /** The tool job whose result this version holds (marked applied in the same step). */+ jobId: z.string().max(40).optional(),+ /** Restore: copy this older version into a new head. */+ from: z.string().max(40).optional(),+});++/** Save a version (a tool's result, or a restored older version); it becomes the head. */+export async function POST(request: Request, ctx: RouteContext<"/api/layers/[id]/versions">) {+ const { id } = await ctx.params;+ const parsed = Body.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: "Invalid version" }, { status: 400 });+ const doc = parsed.data.doc === undefined ? undefined : parseDoc(parsed.data.doc);+ if (doc === null) return Response.json({ error: "Those layers couldn't be saved" }, { status: 400 });+ try {+ return Response.json(createVersion(id, { ...parsed.data, doc }), { status: 201 });+ } catch (e) {+ return Response.json({ error: (e as Error).message }, { status: e instanceof LayersError ? e.status : 422 });+ }+}diff --git a/src/app/api/layers/route.ts b/src/app/api/layers/route.tsnew file mode 100644index 00000000..224154fc--- /dev/null+++ b/src/app/api/layers/route.ts@@ -0,0 +1,32 @@+import { connection } from "next/server";+import { z } from "zod";+import { createProject, LayersError, listProjects } from "@/server/layers";++const Body = z.object({+ /** The image to open: an upload or a result (an /api/files/ URL). */+ source: z.string().max(2000).startsWith("/api/files/"),+ /** Its pixel size, read by the browser that loaded it. */+ width: z.number().positive().max(20_000),+ height: z.number().positive().max(20_000),+ name: z.string().max(200).optional(),+ /** A finished layers result to open as this project's layers. */+ generationId: z.string().max(40).optional(),+});++/** Your Layers projects, most recently edited first. */+export async function GET() {+ await connection();+ return Response.json({ items: listProjects() });+}++/** Open an image in Layers: a new project with the image as its only layer. */+export async function POST(request: Request) {+ const parsed = Body.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: "Only images can be edited here. Pick an image or upload one." }, { status: 400 });+ try {+ return Response.json(createProject(parsed.data), { status: 201 });+ } catch (e) {+ const status = e instanceof LayersError ? e.status : 422;+ return Response.json({ error: (e as Error).message }, { status });+ }+}diff --git a/src/lib/layers.ts b/src/lib/layers.tsindex 13900d70..5674ee59 100644--- a/src/lib/layers.ts+++ b/src/lib/layers.ts@@ -191,6 +191,41 @@ export const TOOL_MODELS: Record<LayerTool, { cloud: string[]; open: string[] }>expand: { cloud: ["nano-banana-pro"], open: ["oss-flux-fill"] },};+/** Relight looks (the Relight app's), as [label, prompt]. */+export const RELIGHT_LIGHTS: [string, string][] = [+ ["Golden hour", "warm golden hour sunlight"],+ ["Neon night", "pink and blue neon lights at night"],+ ["Studio softbox", "soft, even studio softbox lighting"],+ ["Dramatic", "dramatic low-key lighting with a single hard light and deep shadows"],+ ["Overcast", "soft overcast daylight"],+ ["Candlelight", "warm flickering candlelight"],+ ["Silhouette", "strong backlight that turns the subject into a near-silhouette"],+ ["Window", "soft directional window light"],+];++export const RELIGHT_DIRECTIONS: [string, string][] = [+ ["Auto", ""],+ ["Left", "coming from the left"],+ ["Right", "coming from the right"],+ ["Front", "coming from the front"],+ ["Above", "coming from above"],+ ["Behind", "coming from behind the subject as a rim light"],+];++/** Camera angles (the Angles app's), as [label, prompt]. */+export const ANGLES: [string, string][] = [+ ["Left 45°", "rotated 45 degrees to the left around the subject"],+ ["Right 45°", "rotated 45 degrees to the right around the subject"],+ ["Left profile", "a full left side profile view"],+ ["Right profile", "a full right side profile view"],+ ["Back", "a view from directly behind"],+ ["High angle", "a high-angle view looking down at the subject"],+ ["Low angle", "a low-angle view looking up at the subject"],+ ["Bird's eye", "a top-down bird's-eye view from directly above"],+ ["Close-up", "a tight close-up"],+ ["Wide", "a wide shot showing the full environment"],+];+/** Cuts the background back out after an edit model repaints a transparent layer. */export const CUTOUT_MODELS = { cloud: "birefnet-cloud", open: "oss-rmbg" } as const;diff --git a/src/server/db.ts b/src/server/db.tsindex 73575c8d..08d5e570 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -175,6 +175,29 @@ const MIGRATIONS: string[] = [edited_at INTEGER);CREATE INDEX IF NOT EXISTS canvases_updated ON canvases(updated_at DESC);`,+ // Layers projects: one source image, saved versions of its layer document, and the AI jobs its tools started.+ `CREATE TABLE IF NOT EXISTS layer_projects (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ source_url TEXT NOT NULL,+ cover_url TEXT,+ width INTEGER NOT NULL,+ height INTEGER NOT NULL,+ head_version_id TEXT,+ jobs_json TEXT NOT NULL DEFAULT '[]',+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ );+ CREATE INDEX IF NOT EXISTS layer_projects_updated ON layer_projects(updated_at DESC);+ CREATE TABLE IF NOT EXISTS layer_versions (+ id TEXT PRIMARY KEY,+ project_id TEXT NOT NULL,+ label TEXT NOT NULL,+ doc_json TEXT NOT NULL,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ );+ CREATE INDEX IF NOT EXISTS layer_versions_project ON layer_versions(project_id, created_at DESC);`,];declare global {diff --git a/src/server/generations.ts b/src/server/generations.tsindex e5034312..3e0e2944 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -208,6 +208,8 @@ const ASSET_REFS: { table: string; cols: string[]; except?: string }[] = [{ table: "cinema_projects", cols: ["cover_url", "palettes_json", "director_json", "chat_json", "brief_body"] },{ table: "cinema_items", cols: ["meta_json"], except: "generation_id" },{ table: "canvases", cols: ["graph_json"] },+ { table: "layer_projects", cols: ["source_url", "cover_url"] },+ { table: "layer_versions", cols: ["doc_json"] },];/** Whether anything still refers to this stored file (see ASSET_REFS). */diff --git a/src/server/layers.ts b/src/server/layers.tsnew file mode 100644index 00000000..00bd42c6--- /dev/null+++ b/src/server/layers.ts@@ -0,0 +1,596 @@+import "server-only";+import { nanoid } from "nanoid";+import { z } from "zod";+import { getModel } from "@/lib/catalog";+import type { Engine, Generation, GenerationRequest, ModelDef } from "@/lib/catalog/types";+import {+ ANGLES,+ APPLIES_TO_DOC,+ clampLayers,+ CUTOUT_MODELS,+ initialDoc,+ RELIGHT_DIRECTIONS,+ RELIGHT_LIGHTS,+ textChanges,+ textEditPrompt,+ TOOL_MODELS,+ type Box,+ type LayerDoc,+ type LayerJob,+ type LayerJobInput,+ type LayerJobResult,+ type LayerProject,+ type LayerProjectView,+ type LayerTool,+ type LayerVersion,+} from "@/lib/layers";+import { createPipeline, type PipelineStep } from "./chains";+import { db } from "./db";+import { cancelGeneration, getGeneration } from "./generations";++/**+ * Layers studio (Higgsfield Layers): projects, saved versions of their layer document, and the AI+ * jobs their tools start. A job is ordinary generations (so results survive restarts, show in the+ * Library and run on either engine); the editor applies a finished job to its document and saves a+ * version, which marks the job applied (src/lib/layers.ts has the document model).+ */++interface ProjectRow {+ id: string;+ name: string;+ source_url: string;+ cover_url: string | null;+ width: number;+ height: number;+ head_version_id: string | null;+ jobs_json: string;+ created_at: number;+ updated_at: number;+}++interface VersionRow {+ id: string;+ project_id: string;+ label: string;+ doc_json: string;+ created_at: number;+ updated_at: number;+}++/** A user-facing refusal with its HTTP status (the route returns `{ error }`). */+export class LayersError extends Error {+ constructor(+ message: string,+ public status = 422,+ ) {+ super(message);+ }+}++// ---------------------------------------------------------------------------+// Validation of documents and job requests coming from the browser++/** Files the document may point at: stored assets only. */+const FileUrl = z.string().max(2000).startsWith("/api/files/");+const num = z.number().finite();+const BoxSchema = z.tuple([num, num, num, num]);+const clamped = (max: number) => z.string().transform((s) => s.slice(0, max));++const Revision = z.object({+ src: FileUrl,+ crop: BoxSchema.nullable().optional(),+ natural: z.tuple([z.number().int().positive(), z.number().int().positive()]).optional(),+ label: clamped(80),+ prompt: clamped(2000).optional(),+ at: z.number().int().nonnegative(),+});++const Node = z.object({+ id: z.string().min(1).max(40),+ name: clamped(80),+ z: z.number().int().min(0).max(1000),+ x: num.min(-100_000).max(100_000),+ y: num.min(-100_000).max(100_000),+ w: num.positive().max(100_000),+ h: num.positive().max(100_000),+ rotation: num.min(-3600).max(3600),+ src: FileUrl,+ crop: BoxSchema.nullable().optional(),+ natural: z.tuple([z.number().int().positive(), z.number().int().positive()]).optional(),+ hidden: z.boolean().optional(),+ opacity: num.min(0).max(1).optional(),+ maskSrc: FileUrl.optional(),+ feather: num.min(0).max(2000).optional(),+ prompt: clamped(2000).optional(),+ refSrc: FileUrl.optional(),+ revisions: z.array(Revision).max(60),+ revision: z.number().int().min(0),+ role: z.enum(["original", "new"]).optional(),+});++const DocSchema = z.object({+ v: z.literal(1),+ width: z.number().int().min(1).max(20_000),+ height: z.number().int().min(1).max(20_000),+ source: FileUrl,+ decomposed: z.boolean(),+ nodes: z.array(Node).max(200),+});++/** A document the browser sent, cleaned (null when it can't be read). */+export function parseDoc(v: unknown): LayerDoc | null {+ const r = DocSchema.safeParse(v);+ if (!r.success) return null;+ const doc = r.data as LayerDoc;+ // Keep the revision index inside the list.+ doc.nodes = doc.nodes.map((n) => (n.revision < Math.max(1, n.revisions.length) ? n : { ...n, revision: Math.max(0, n.revisions.length - 1) }));+ return doc;+}++const TOOLS = ["decompose", "split", "regenerate", "generate-layer", "text-detect", "text-edit", "bg-remove", "regional", "upscale", "relight", "angles", "expand"] as const satisfies readonly LayerTool[];++export const JobInputSchema = z.object({+ tool: z.enum(TOOLS),+ engine: z.enum(["cloud", "open"]),+ modelId: z.string().max(80).optional(),+ image: FileUrl.optional(),+ refs: z.array(FileUrl).max(3).optional(),+ prompt: clamped(2000).optional(),+ nodeId: z.string().max(40).optional(),+ frame: BoxSchema,+ label: clamped(120).optional(),+ settings: z+ .object({+ resolution: z.enum(["1K", "1.5K", "2K"]).optional(),+ mode: z.enum(["standard", "fast"]).optional(),+ layers: z.number().int().min(1).max(16).optional(),+ keepAlpha: z.boolean().optional(),+ light: z.string().max(40).optional(),+ direction: z.string().max(40).optional(),+ angle: z.string().max(40).optional(),+ rotate: num.min(0).max(360).optional(),+ tilt: num.min(-30).max(90).optional(),+ zoom: num.min(0).max(10).optional(),+ rows: z.array(z.object({ from: clamped(500), to: clamped(500) })).max(500).optional(),+ pads: z.object({ left: z.number().int().min(0).max(4096), top: z.number().int().min(0).max(4096), right: z.number().int().min(0).max(4096), bottom: z.number().int().min(0).max(4096) }).optional(),+ feather: num.min(0).max(500).optional(),+ aspect: z.string().regex(/^\d+(\.\d+)?:\d+(\.\d+)?$/).max(20).optional(),+ })+ .optional(),+});++// ---------------------------------------------------------------------------+// Jobs → generation requests (pure: no database)++const TOOL_LABELS: Record<LayerTool, string> = {+ decompose: "Layer decomposition",+ split: "Separate layer",+ regenerate: "Layer edit",+ "generate-layer": "Generate layer",+ "text-detect": "Detect text",+ "text-edit": "Edit text",+ "bg-remove": "Remove background",+ regional: "Regional edit",+ upscale: "Upscale",+ relight: "Relight",+ angles: "Angles",+ expand: "Expand",+};++/** The tool's model on this engine: the one asked for (when the tool offers it) or its default. */+export function toolModel(tool: LayerTool, engine: Engine, modelId?: string): ModelDef {+ const list = TOOL_MODELS[tool][engine];+ if (!list.length) {+ throw new LayersError(+ tool === "text-detect" ? "Text detection runs on the cloud engine (Ideogram). On open source, type the lines you want to change." : `${TOOL_LABELS[tool]} has no ${engine === "open" ? "open-source" : "cloud"} model yet`,+ );+ }+ if (modelId && !list.includes(modelId)) throw new LayersError("That model can't run this tool", 400);+ const m = getModel(modelId ?? list[0]);+ if (!m) throw new LayersError("That model isn't in the catalog", 400);+ return m;+}++const RES_TIER = { "1K": "auto_1K", "1.5K": "auto_1.5K", "2K": "auto_2K" } as const;+/** Qwen-Image-Layered's longest side per tier (640 is the trained bucket; larger is slower). */+const OPEN_MAX_SIZE = { "1K": 640, "1.5K": 832, "2K": 1024 } as const;++const pick = (list: [string, string][], label: string | undefined) => list.find(([l]) => l === label)?.[1] ?? list[0][1];++/**+ * The generation steps for one tool run: the model step, then (for edits of a transparent layer and+ * new layers) a background cut-out that gives the result its alpha back.+ */+export function jobSteps(input: LayerJobInput, opts: { batchTitle?: string } = {}): PipelineStep[] {+ const { tool, engine } = input;+ const s = input.settings ?? {};+ const prompt = input.prompt?.trim() ?? "";+ const label = input.label?.trim() || TOOL_LABELS[tool];+ const needImage = () => {+ if (!input.image) throw new LayersError("Pick a layer or the image to work on", 400);+ return input.image;+ };+ const base = (model: ModelDef, request: Partial<GenerationRequest>, stepLabel = label): GenerationRequest => ({+ feature: "layers",+ modelId: model.id,+ ...request,+ ...(opts.batchTitle ? { batchTitle: opts.batchTitle } : {}),+ step: { label: `Layers · ${stepLabel}`, index: 0, of: 1 },+ });+ const steps: PipelineStep[] = [];+ const add = (key: string, request: GenerationRequest, after?: string) => steps.push(after ? { key, request, after, chain: [{ slot: "images" }] } : { key, request });+ const cutout = (after: string) => {+ const m = getModel(CUTOUT_MODELS[engine])!;+ add("cutout", base(m, { op: "bg-remove", params: aspectFor(m) }, `${label} · cut-out`), after);+ };+ /**+ * The input's shape, for models that take any ratio or list this one: the demo provider and+ * ratio-aware models then answer in the layer's shape. Never sent where the API would refuse it.+ */+ const aspectFor = (m: ModelDef): GenerationRequest["params"] => (s.aspect && (!m.options.aspectRatios || m.options.aspectRatios.includes(s.aspect)) ? { aspectRatio: s.aspect } : {});++ switch (tool) {+ case "decompose":+ case "split": {+ // Open: a named element goes to the prompt-guided Layered-Control model.+ const wantsControl = tool === "split" && engine === "open" && !!prompt && !input.modelId;+ const model = toolModel(tool, engine, wantsControl ? "oss-qwen-layered-control" : input.modelId);+ const layers = clampLayers(model.id, s.layers ?? (model.id === "oss-qwen-layered-control" ? 2 : tool === "split" ? 3 : 8));+ const res = s.resolution ?? "1K";+ const params: GenerationRequest["params"] = { ...aspectFor(model) };+ let p: string | undefined;+ if (model.id.startsWith("seedream")) {+ params.resolution = RES_TIER[res];+ if (model.id === "seedream-5-layers") params.extra = { enhance_prompt_mode: s.mode ?? "standard" };+ // Seedream picks how many layers it returns; the instruction steers it.+ p = prompt+ ? `Separate ${prompt} onto its own layer, and the rest into up to ${layers - 1} layers. Return name and description in English.`+ : `Separate the major elements into up to ${layers} layers. Return name and description in English.`;+ } else if (model.engine === "open") {+ params.numLayers = layers;+ params.extra = { steps: s.mode === "fast" ? 10 : 20, maxSize: OPEN_MAX_SIZE[res] };+ p = prompt || undefined;+ } else {+ params.numLayers = layers;+ p = prompt || undefined;+ }+ add("layers", base(model, { op: "layers", prompt: p, inputs: { images: [needImage()] }, params }));+ break;+ }+ case "regenerate": {+ if (!prompt) throw new LayersError("Describe the change in the layer edit prompt", 400);+ const model = toolModel(tool, engine, input.modelId);+ const refs = input.refs ?? [];+ const ask = refs.length ? `${prompt} Use image ${refs.length > 1 ? "2 and 3" : "2"} as the reference.` : prompt;+ add("edit", base(model, { op: "edit", prompt: s.keepAlpha ? `${ask} Keep the subject on a plain, even background.` : ask, inputs: { images: [needImage(), ...refs] }, params: aspectFor(model) }));+ if (s.keepAlpha) cutout("edit");+ break;+ }+ case "generate-layer": {+ if (!prompt) throw new LayersError("Describe the layer to generate", 400);+ const refs = input.refs ?? [];+ const ask = `${prompt}. A single element, isolated and centred on a plain white background, nothing else in the frame.`;+ if (refs.length) {+ const model = toolModel("regenerate", engine, undefined);+ add("make", base(model, { op: "edit", prompt: `${ask} Base it on image 1.`, inputs: { images: refs } }));+ } else {+ const model = toolModel(tool, engine, input.modelId);+ add("make", base(model, { op: "t2i", prompt: ask, params: { aspectRatio: "1:1", numOutputs: 1 } }));+ }+ cutout("make");+ break;+ }+ case "text-detect": {+ const model = toolModel(tool, engine, input.modelId);+ add("detect", base(model, { op: "text-layers", inputs: { images: [needImage()] }, params: aspectFor(model) }));+ break;+ }+ case "text-edit": {+ const rows = textChanges(s.rows ?? []);+ if (!rows.length) throw new LayersError("Change a line of text first", 400);+ const model = toolModel(tool, engine, input.modelId);+ add("edit", base(model, { op: "edit", prompt: textEditPrompt(rows), inputs: { images: [needImage()] }, params: aspectFor(model) }));+ if (s.keepAlpha) cutout("edit");+ break;+ }+ case "bg-remove": {+ const model = toolModel(tool, engine, input.modelId);+ add("cut", base(model, { op: "bg-remove", inputs: { images: [needImage()] }, params: aspectFor(model) }));+ break;+ }+ case "regional": {+ if (!prompt) throw new LayersError("Describe your changes for the selected area", 400);+ const model = toolModel(tool, engine, input.modelId);+ add("edit", base(model, { op: "edit", prompt: `${prompt}. Keep everything else in this crop the same, with the same framing, light and grain.`, inputs: { images: [needImage()] }, params: aspectFor(model) }));+ break;+ }+ case "upscale": {+ const model = toolModel(tool, engine, input.modelId);+ add("upscale", base(model, { op: "upscale-image", inputs: { images: [needImage()] }, params: aspectFor(model) }));+ break;+ }+ case "relight": {+ const model = toolModel(tool, engine, input.modelId);+ const light = pick(RELIGHT_LIGHTS, s.light);+ const dir = pick(RELIGHT_DIRECTIONS, s.direction);+ const p =+ model.engine === "open"+ ? `${light}${dir ? `, ${dir}` : ""}`+ : `Relight the image with ${light}${dir ? ` ${dir}` : ""}. Keep the subject, composition and all details identical; only the light, shadows, reflections and color temperature change.`;+ add("relight", base(model, { op: "edit", prompt: prompt ? `${p} ${prompt}` : p, inputs: { images: [needImage()] }, params: aspectFor(model) }));+ if (s.keepAlpha) cutout("relight");+ break;+ }+ case "angles": {+ const model = toolModel(tool, engine, input.modelId);+ const keep = "Keep identity, outfit, props, lighting direction and colours consistent; reveal plausible unseen sides.";+ const request =+ model.id === "qwen-multiple-angles"+ ? base(model, {+ op: "edit",+ prompt: prompt || "The same subject from a new camera angle.",+ inputs: { images: [needImage()] },+ params: { ...aspectFor(model), numOutputs: 1, extra: { horizontal_angle: Math.round(s.rotate ?? 45), vertical_angle: Math.round(s.tilt ?? 0), zoom: Math.round(s.zoom ?? 5) } },+ })+ : base(model, { op: "edit", prompt: `Show the exact same subject from ${pick(ANGLES, s.angle)}, as if the camera physically moved. ${keep}${prompt ? ` ${prompt}` : ""}`, inputs: { images: [needImage()] }, params: aspectFor(model) });+ add("angle", request);+ if (s.keepAlpha) cutout("angle");+ break;+ }+ case "expand": {+ const model = toolModel(tool, engine, input.modelId);+ const fill = "Continue the scene naturally beyond every edge with matching perspective, lighting, textures and grain. Keep the original picture untouched and add no new people or text.";+ if (model.engine === "open") {+ const pads = s.pads;+ if (!pads || pads.left + pads.top + pads.right + pads.bottom === 0) throw new LayersError("Drag an edge outward to make room to fill", 400);+ add("expand", base(model, { op: "outpaint", prompt: prompt || fill, inputs: { images: [needImage()] }, params: { extra: { padLeft: pads.left, padTop: pads.top, padRight: pads.right, padBottom: pads.bottom } } }));+ } else {+ add("expand", base(model, { op: "edit", prompt: `Fill the empty grey margins around the picture. ${fill}${prompt ? ` ${prompt}` : ""}`, inputs: { images: [needImage()] }, params: aspectFor(model) }));+ }+ break;+ }+ }+ const n = steps.length;+ return steps.map((st, i) => ({ ...st, request: { ...st.request, step: { ...st.request.step!, index: i, of: n } } }));+}++// ---------------------------------------------------------------------------+// Projects++const parseJobs = (s: string): LayerJob[] => {+ try {+ const v = JSON.parse(s);+ return Array.isArray(v) ? (v as LayerJob[]) : [];+ } catch {+ return [];+ }+};++/** The result generation of a job, trimmed to what the editor needs. */+function resultOf(job: LayerJob): LayerJobResult | null {+ const g: Generation | null = getGeneration(job.generationIds[job.generationIds.length - 1], { includeDeleted: true });+ if (!g) return null;+ return {+ status: g.status,+ progress: g.progress,+ message: g.message,+ error: g.error,+ provider: g.provider,+ outputs: g.outputs.map((o) => ({ url: o.url, kind: o.kind, ...(o.meta ? { meta: o.meta } : {}), ...(o.width ? { width: o.width } : {}), ...(o.height ? { height: o.height } : {}) })),+ };+}++const ACTIVE = new Set(["queued", "running"]);++function statusOf(row: ProjectRow, doc: LayerDoc | null): LayerProject["status"] {+ const dec = parseJobs(row.jobs_json).filter((j) => j.tool === "decompose" && j.state !== "dismissed");+ const last = dec[dec.length - 1];+ if (!last || last.state === "applied") return "ready";+ const r = resultOf(last);+ if (r && ACTIVE.has(r.status)) return "processing";+ if (r?.status === "succeeded") return "processing"; // finished, waiting for the editor to lay it out+ return doc?.decomposed ? "ready" : "failed";+}++function headDoc(row: ProjectRow): LayerDoc | null {+ if (!row.head_version_id) return null;+ const v = db().prepare("SELECT doc_json FROM layer_versions WHERE id = ?").get(row.head_version_id) as { doc_json: string } | undefined;+ return v ? (JSON.parse(v.doc_json) as LayerDoc) : null;+}++function toProject(row: ProjectRow, doc = headDoc(row)): LayerProject {+ return {+ id: row.id,+ name: row.name,+ sourceUrl: row.source_url,+ coverUrl: row.cover_url ?? row.source_url,+ width: doc?.width ?? row.width,+ height: doc?.height ?? row.height,+ layers: doc?.nodes.length ?? 1,+ status: statusOf(row, doc),+ createdAt: row.created_at,+ updatedAt: row.updated_at,+ };+}++const getRow = (id: string) => db().prepare("SELECT * FROM layer_projects WHERE id = ?").get(id) as ProjectRow | undefined;++export function listProjects(): LayerProject[] {+ return (db().prepare("SELECT * FROM layer_projects ORDER BY updated_at DESC, id DESC").all() as ProjectRow[]).map((r) => toProject(r));+}++export function projectView(id: string): LayerProjectView | null {+ const row = getRow(id);+ if (!row) return null;+ const doc = headDoc(row);+ if (!doc || !row.head_version_id) return null;+ const versions = (db().prepare("SELECT id, label, created_at, updated_at FROM layer_versions WHERE project_id = ? ORDER BY created_at DESC, id DESC").all(id) as Omit<VersionRow, "project_id" | "doc_json">[]).map(+ (v): LayerVersion => ({ id: v.id, label: v.label, createdAt: v.created_at, updatedAt: v.updated_at }),+ );+ const jobs = parseJobs(row.jobs_json).map((j) => ({ ...j, result: resultOf(j) }));+ return { project: toProject(row, doc), versions, headVersionId: row.head_version_id, doc, jobs };+}++function insertVersion(projectId: string, label: string, doc: LayerDoc, now: number): string {+ const id = nanoid(10);+ db()+ .prepare("INSERT INTO layer_versions (id, project_id, label, doc_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)")+ .run(id, projectId, label.slice(0, 80), JSON.stringify(doc), now, now);+ return id;+}++/**+ * A new project on an image (an upload or a result): the image is its first layer. With+ * `generationId` (a finished layers result), its layers arrive like a decomposition that just finished.+ */+export function createProject(input: { source: string; width: number; height: number; name?: string; generationId?: string }): LayerProjectView {+ const width = Math.round(input.width);+ const height = Math.round(input.height);+ if (!(width > 0 && height > 0 && width <= 20_000 && height <= 20_000)) throw new LayersError("That image's size couldn't be read", 400);+ const jobs: LayerJob[] = [];+ const now = Date.now();+ if (input.generationId) {+ const g = getGeneration(input.generationId);+ if (!g || g.op !== "layers" || g.status !== "succeeded") throw new LayersError("That result isn't a finished set of layers", 400);+ jobs.push({ id: nanoid(8), tool: "decompose", label: "Layers from your result", frame: [0, 0, width, height], generationIds: [g.id], state: "pending", createdAt: now });+ }+ const id = nanoid(10);+ const name = input.name?.trim().slice(0, 80) || "Untitled project";+ db().transaction(() => {+ db()+ .prepare("INSERT INTO layer_projects (id, name, source_url, cover_url, width, height, head_version_id, jobs_json, created_at, updated_at) VALUES (?, ?, ?, NULL, ?, ?, NULL, ?, ?, ?)")+ .run(id, name, input.source, width, height, JSON.stringify(jobs), now, now);+ const v = insertVersion(id, "Original", initialDoc(input.source, width, height, now), now);+ db().prepare("UPDATE layer_projects SET head_version_id = ? WHERE id = ?").run(v, id);+ })();+ return projectView(id)!;+}++/** Rename, and/or autosave the document into the head version (409 when another tab moved the head). */+export function updateProject(id: string, patch: { name?: string; doc?: LayerDoc; versionId?: string }): LayerProject | null {+ const row = getRow(id);+ if (!row) return null;+ const now = Date.now();+ db().transaction(() => {+ if (patch.name !== undefined) db().prepare("UPDATE layer_projects SET name = ?, updated_at = ? WHERE id = ?").run(patch.name.trim().slice(0, 80) || "Untitled project", now, id);+ if (patch.doc) {+ if (patch.versionId && patch.versionId !== row.head_version_id) throw new LayersError("This project changed in another tab. Reload to see the latest version.", 409);+ if (patch.doc.source !== row.source_url) throw new LayersError("That document belongs to another image", 400);+ db().prepare("UPDATE layer_versions SET doc_json = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(patch.doc), now, row.head_version_id);+ db().prepare("UPDATE layer_projects SET updated_at = ? WHERE id = ?").run(now, id);+ }+ })();+ return toProject(getRow(id)!);+}++/** Delete the project and its versions; the images and the generations it made stay in the library. */+export function deleteProject(id: string): boolean {+ let gone = false;+ db().transaction(() => {+ gone = db().prepare("DELETE FROM layer_projects WHERE id = ?").run(id).changes > 0;+ db().prepare("DELETE FROM layer_versions WHERE project_id = ?").run(id);+ })();+ return gone;+}++/**+ * Save a version: a milestone (`doc` + `label`, e.g. after a tool's result landed, marking `jobId`+ * applied in the same step) or a restore of an older one (`from`). It becomes the head.+ */+export function createVersion(id: string, input: { doc?: LayerDoc; label?: string; jobId?: string; from?: string }): LayerProjectView {+ const row = getRow(id);+ if (!row) throw new LayersError("Not found", 404);+ const now = Date.now();+ db().transaction(() => {+ let doc = input.doc;+ let label = input.label?.trim() || "Edit";+ if (input.from) {+ const v = db().prepare("SELECT * FROM layer_versions WHERE id = ? AND project_id = ?").get(input.from, id) as VersionRow | undefined;+ if (!v) throw new LayersError("Layer project version is unavailable", 404);+ doc = JSON.parse(v.doc_json) as LayerDoc;+ label = `Restored “${v.label}”`;+ }+ if (!doc) throw new LayersError("Nothing to save", 400);+ if (doc.source !== row.source_url) throw new LayersError("That document belongs to another image", 400);+ let jobs = parseJobs(row.jobs_json);+ if (input.jobId) {+ const job = jobs.find((j) => j.id === input.jobId);+ if (!job) throw new LayersError("That job is gone", 404);+ if (job.state !== "pending") throw new LayersError("That result is already in your layers", 409);+ jobs = jobs.map((j) => (j.id === input.jobId ? { ...j, state: "applied" as const } : j));+ }+ const v = insertVersion(id, label, doc, now);+ db().prepare("UPDATE layer_projects SET head_version_id = ?, jobs_json = ?, updated_at = ? WHERE id = ?").run(v, JSON.stringify(jobs), now, id);+ })();+ return projectView(id)!;+}++/** Jobs kept per project: every pending one, plus the latest finished ones (the last text detection among them). */+const KEEP_JOBS = 40;++function saveJobs(id: string, jobs: LayerJob[], now = Date.now()) {+ const pending = jobs.filter((j) => j.state === "pending");+ const done = jobs.filter((j) => j.state !== "pending").slice(-Math.max(0, KEEP_JOBS - pending.length));+ const keep = jobs.filter((j) => pending.includes(j) || done.includes(j)).map((j) => {+ const { result: _drop, ...rest } = j;+ void _drop;+ return rest;+ });+ db().prepare("UPDATE layer_projects SET jobs_json = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(keep), now, id);+}++/** Start a tool: its generations run in the background; the editor applies the result when it lands. */+export function startJob(id: string, input: LayerJobInput): LayerJob {+ const row = getRow(id);+ if (!row) throw new LayersError("Not found", 404);+ const jobs = parseJobs(row.jobs_json);+ const running = (j: LayerJob) => {+ if (j.state !== "pending") return false;+ const r = resultOf(j);+ return !r || ACTIVE.has(r.status) || (r.status === "succeeded" && APPLIES_TO_DOC.has(j.tool));+ };+ if (input.tool === "decompose") {+ if (headDoc(row)?.decomposed) throw new LayersError("An image can only be decomposed once. Pick a layer and use Separate layer to split it further.", 409);+ if (jobs.some((j) => j.tool === "decompose" && running(j))) throw new LayersError("This image is already being decomposed", 409);+ }+ if (input.nodeId && jobs.some((j) => j.nodeId === input.nodeId && j.tool !== "text-detect" && running(j))) {+ throw new LayersError("A generation is already running on this layer", 409);+ }+ const steps = jobSteps(input, { batchTitle: `Layers · ${row.name}` });+ let ids: string[];+ try {+ ids = createPipeline(steps, { batchId: `layers-${id}` }).items.map((g) => g.id);+ } catch (e) {+ if (e instanceof LayersError) throw e;+ throw new LayersError((e as Error).message || "Could not start the split");+ }+ const job: LayerJob = {+ id: nanoid(8),+ tool: input.tool,+ label: input.label?.trim() || TOOL_LABELS[input.tool],+ ...(input.nodeId ? { nodeId: input.nodeId } : {}),+ frame: input.frame as Box,+ settings: { ...(input.settings ?? {}), ...(input.prompt ? { prompt: input.prompt } : {}), ...(input.modelId ? { modelId: input.modelId } : {}) },+ generationIds: ids,+ state: "pending",+ createdAt: Date.now(),+ };+ saveJobs(id, [...jobs, job]);+ return { ...job, result: resultOf(job) };+}++/** Dismiss a job (a failure the user has seen, a detection that's been read) or cancel one still running. */+export async function endJob(id: string, jobId: string, opts: { cancel?: boolean; state?: "dismissed" | "applied" } = {}): Promise<LayerJob | null> {+ const row = getRow(id);+ if (!row) return null;+ const jobs = parseJobs(row.jobs_json);+ const job = jobs.find((j) => j.id === jobId);+ if (!job) return null;+ if (opts.cancel) for (const g of job.generationIds) await cancelGeneration(g);+ const next = { ...job, state: opts.state ?? ("dismissed" as const) };+ saveJobs(+ id,+ jobs.map((j) => (j.id === jobId ? next : j)),+ );+ return { ...next, result: resultOf(next) };+}diff --git a/tests/layers-api.test.ts b/tests/layers-api.test.tsnew file mode 100644index 00000000..71bedf11--- /dev/null+++ b/tests/layers-api.test.ts@@ -0,0 +1,302 @@+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 { Generation } from "@/lib/catalog/types";+import { initialDoc, nodesFromOutputs, placeOutput, type LayerDoc, type LayerJob, type LayerJobInput, type LayerProject, type LayerProjectView } from "@/lib/layers";++// Route handlers are called directly, outside a Next request: connection() has nothing to wait for.+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-layers-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9";++const { setSetting } = await import("@/server/settings");+const gens = await import("@/server/generations");+const { saveFile } = await import("@/server/storage");+const layers = await import("@/server/layers");+const list = await import("@/app/api/layers/route");+const one = await import("@/app/api/layers/[id]/route");+const versions = await import("@/app/api/layers/[id]/versions/route");+const jobs = await import("@/app/api/layers/[id]/jobs/route");+const job = await import("@/app/api/layers/[id]/jobs/[jobId]/route");++beforeAll(() => setSetting("demoMode", "auto"));+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++// eslint-disable-next-line @typescript-eslint/no-explicit-any+const ctx = (params: Record<string, string>) => ({ params: Promise.resolve(params) }) as any;+const req = (method: string, body?: unknown) =>+ new Request("http://localhost/api/layers", { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });++async function settle(id: string, ms = 40_000): Promise<Generation> {+ const until = Date.now() + ms;+ for (;;) {+ const g = gens.getGeneration(id, { includeDeleted: true })!;+ if (["succeeded", "failed", "canceled"].includes(g.status)) return g;+ if (Date.now() > until) throw new Error(`timed out: ${g.status} ${g.message}`);+ await new Promise((r) => setTimeout(r, 300));+ }+}++/** A tiny real PNG (1×1) saved as an upload. */+const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==", "base64");+const upload = () => saveFile({ data: PNG, contentType: "image/png", name: "poster.png", source: "upload" }).url;++describe("job steps", () => {+ const frame: [number, number, number, number] = [0, 0, 1920, 1080];+ const steps = (i: Partial<LayerJobInput>) => layers.jobSteps({ tool: "decompose", engine: "cloud", frame, image: "/api/files/a.png", ...i } as LayerJobInput);++ it("decomposes with Seedream on cloud: resolution tier, mode and the layer count in the instruction", () => {+ const [s] = steps({ settings: { resolution: "2K", mode: "fast", layers: 8, aspect: "16:9" } });+ expect(s.request).toMatchObject({+ feature: "layers",+ modelId: "seedream-5-layers",+ op: "layers",+ inputs: { images: ["/api/files/a.png"] },+ params: { resolution: "auto_2K", extra: { enhance_prompt_mode: "fast" }, aspectRatio: "16:9" },+ step: { label: "Layers · Layer decomposition", index: 0, of: 1 },+ });+ expect(s.request.prompt).toContain("up to 8 layers");+ // Flash has no mode field; Qwen takes the count itself (8 at most across its hosts).+ expect(steps({ modelId: "seedream-5-flash-layers", settings: { mode: "fast" } })[0].request.params?.extra).toBeUndefined();+ expect(steps({ modelId: "qwen-image-layered-cloud", settings: { layers: 16 } })[0].request.params).toMatchObject({ numLayers: 8 });+ });++ it("decomposes with Qwen-Image-Layered on the open engine", () => {+ const [s] = steps({ engine: "open", settings: { resolution: "1.5K", mode: "fast", layers: 12 } });+ expect(s.request).toMatchObject({ modelId: "oss-qwen-layered", params: { numLayers: 10, extra: { steps: 10, maxSize: 832 } } });+ expect(s.request.prompt).toBeUndefined();+ });++ it("separates a layer by name with Layered-Control on the open engine", () => {+ const [s] = steps({ tool: "split", engine: "open", prompt: "the guitar" });+ expect(s.request).toMatchObject({ modelId: "oss-qwen-layered-control", prompt: "the guitar", params: { numLayers: 2 } });+ expect(steps({ tool: "split", engine: "open" })[0].request.modelId).toBe("oss-qwen-layered");+ expect(steps({ tool: "split", prompt: "the guitar" })[0].request.prompt).toMatch(/^Separate the guitar onto its own layer/);+ });++ it("cuts the background back out after editing a transparent layer", () => {+ const s = steps({ tool: "regenerate", prompt: "Make it gold", refs: ["/api/files/ref.png"], settings: { keepAlpha: true } });+ expect(s.map((x) => [x.key, x.request.modelId, x.request.op, x.after])).toEqual([+ ["edit", "nano-banana-pro", "edit", undefined],+ ["cutout", "birefnet-cloud", "bg-remove", "edit"],+ ]);+ expect(s[0].request.inputs?.images).toEqual(["/api/files/a.png", "/api/files/ref.png"]);+ expect(s[0].request.prompt).toMatch(/^Make it gold Use image 2 as the reference\. Keep the subject/);+ expect(s[1].chain).toEqual([{ slot: "images" }]);+ expect(s.map((x) => x.request.step)).toEqual([+ { label: "Layers · Layer edit", index: 0, of: 2 },+ { label: "Layers · Layer edit · cut-out", index: 1, of: 2 },+ ]);+ const open = steps({ tool: "regenerate", engine: "open", prompt: "Make it gold", settings: { keepAlpha: true } });+ expect(open.map((x) => x.request.modelId)).toEqual(["oss-qwen-edit", "oss-rmbg"]);+ expect(() => steps({ tool: "regenerate" })).toThrow(/layer edit prompt/);+ });++ it("generates a new transparent layer from text or a reference", () => {+ const t = steps({ tool: "generate-layer", engine: "open", image: undefined, prompt: "a red balloon" });+ expect(t.map((x) => [x.request.modelId, x.request.op])).toEqual([+ ["oss-z-image-turbo", "t2i"],+ ["oss-rmbg", "bg-remove"],+ ]);+ expect(t[0].request.prompt).toMatch(/^a red balloon\. A single element, isolated/);+ const r = steps({ tool: "generate-layer", image: undefined, prompt: "this mug in blue", refs: ["/api/files/mug.png"] });+ expect(r[0].request).toMatchObject({ modelId: "nano-banana-pro", op: "edit", inputs: { images: ["/api/files/mug.png"] } });+ });++ it("edits text with the fixed instruction on both engines; detection is cloud only", () => {+ const rows = [{ from: "SALE", to: "OPEN" }];+ expect(steps({ tool: "text-edit", settings: { rows } })[0].request).toMatchObject({+ modelId: "nano-banana-pro",+ op: "edit",+ prompt: "Preserve the original design and change only the requested text. Change “SALE” to “OPEN”.",+ });+ expect(steps({ tool: "text-edit", engine: "open", settings: { rows } })[0].request.modelId).toBe("oss-qwen-edit");+ expect(() => steps({ tool: "text-edit", settings: { rows: [{ from: "SALE", to: "SALE" }] } })).toThrow(/Change a line/);+ expect(steps({ tool: "text-detect" })[0].request).toMatchObject({ modelId: "ideogram-3-text-layers", op: "text-layers" });+ expect(() => steps({ tool: "text-detect", engine: "open" })).toThrow(/cloud engine/);+ });++ it("hands layers to the existing upscale, relight, angles, background and expand models", () => {+ expect(steps({ tool: "upscale", engine: "open" })[0].request).toMatchObject({ modelId: "oss-upscale-image", op: "upscale-image" });+ expect(steps({ tool: "bg-remove" })[0].request).toMatchObject({ modelId: "birefnet-cloud", op: "bg-remove" });+ const relight = steps({ tool: "relight", engine: "open", settings: { light: "Neon night", direction: "Left" } })[0].request;+ expect(relight).toMatchObject({ modelId: "oss-qwen-relight", op: "edit", prompt: "pink and blue neon lights at night, coming from the left" });+ const angles = steps({ tool: "angles", settings: { rotate: 90, tilt: 10, zoom: 4 } })[0].request;+ expect(angles).toMatchObject({ modelId: "qwen-multiple-angles", params: { extra: { horizontal_angle: 90, vertical_angle: 10, zoom: 4 } } });+ expect(steps({ tool: "angles", engine: "open", settings: { angle: "Back" } })[0].request.prompt).toContain("a view from directly behind");+ const expand = steps({ tool: "expand", engine: "open", settings: { pads: { left: 64, top: 0, right: 64, bottom: 8 } } })[0].request;+ expect(expand).toMatchObject({ modelId: "oss-flux-fill", op: "outpaint", params: { extra: { padLeft: 64, padTop: 0, padRight: 64, padBottom: 8 } } });+ expect(() => steps({ tool: "expand", engine: "open", settings: { pads: { left: 0, top: 0, right: 0, bottom: 0 } } })).toThrow(/Drag an edge/);+ expect(steps({ tool: "expand" })[0].request.prompt).toMatch(/^Fill the empty grey margins/);+ expect(steps({ tool: "regional", prompt: "add a hat" })[0].request).toMatchObject({ modelId: "seedream-5-pro", op: "edit" });+ });++ it("only sends a shape the model accepts", () => {+ // Nano Banana Pro lists 16:9 but not an odd crop's shape.+ expect(steps({ tool: "regional", modelId: "nano-banana-pro", prompt: "x", settings: { aspect: "16:9" } })[0].request.params?.aspectRatio).toBe("16:9");+ expect(steps({ tool: "regional", modelId: "nano-banana-pro", prompt: "x", settings: { aspect: "317:211" } })[0].request.params?.aspectRatio).toBeUndefined();+ expect(() => steps({ modelId: "nano-banana-pro" })).toThrow(/can't run this tool/);+ });+});++describe("layers API", () => {+ let source = "";+ let id = "";+ let view: LayerProjectView;++ it("opens an image as a project and lists it", async () => {+ source = upload();+ let res = await list.POST(req("POST", { source, width: 1920, height: 1080, name: "Summer poster" }));+ expect(res.status).toBe(201);+ view = (await res.json()) as LayerProjectView;+ id = view.project.id;+ expect(view.project).toMatchObject({ name: "Summer poster", sourceUrl: source, coverUrl: source, width: 1920, height: 1080, layers: 1, status: "ready" });+ expect(view.versions.map((v) => v.label)).toEqual(["Original"]);+ expect(view.doc).toMatchObject({ width: 1920, height: 1080, decomposed: false, source });+ expect(view.jobs).toEqual([]);++ res = await list.GET();+ const items = ((await res.json()) as { items: LayerProject[] }).items;+ expect(items.map((p) => p.id)).toEqual([id]);++ // Only stored images open here.+ res = await list.POST(req("POST", { source: "http://example.com/a.png", width: 10, height: 10 }));+ expect(res.status).toBe(400);+ expect(((await res.json()) as { error: string }).error).toMatch(/Only images can be edited here/);+ });++ it("decomposes in demo mode, then the editor's version marks the job applied", async () => {+ let res = await jobs.POST(req("POST", { tool: "decompose", engine: "cloud", image: source, frame: [0, 0, 1920, 1080], settings: { layers: 4, aspect: "16:9" } }), ctx({ id }));+ expect(res.status).toBe(201);+ const started = (await res.json()) as LayerJob;+ expect(started).toMatchObject({ tool: "decompose", state: "pending", label: "Layer decomposition" });+ expect(started.generationIds).toHaveLength(1);++ // The card says it's processing; a second decomposition is refused while it runs.+ res = await list.GET();+ expect(((await res.json()) as { items: LayerProject[] }).items[0].status).toBe("processing");+ res = await jobs.POST(req("POST", { tool: "decompose", engine: "cloud", image: source, frame: [0, 0, 1920, 1080] }), ctx({ id }));+ expect(res.status).toBe(409);++ const g = await settle(started.generationIds[0]);+ expect(g.status).toBe("succeeded");+ expect(g.feature).toBe("layers");+ expect(g.batchId).toBe(`layers-${id}`);+ res = await one.GET(req("GET"), ctx({ id }));+ view = (await res.json()) as LayerProjectView;+ const j = view.jobs[0];+ expect(j.result?.status).toBe("succeeded");+ expect(j.result?.outputs.length).toBeGreaterThanOrEqual(3);+ expect(j.result?.outputs[1].meta).toMatchObject({ name: "Subject", z: 1 });++ // What the editor does: place each layer (demo layers are 1024×576 full canvases with pixel boxes).+ let n = 0;+ const nodes = nodesFromOutputs(+ j.result!.outputs.map((o) => ({ url: o.url, meta: o.meta, natural: [1024, 576] as [number, number], placement: placeOutput(j.frame, [1024, 576], o.meta) })),+ { id: () => `L${++n}`, label: "Decomposed", at: Date.now() },+ );+ const doc: LayerDoc = { ...view.doc, decomposed: true, nodes };+ res = await versions.POST(req("POST", { doc, label: "Decomposed", jobId: j.id }), ctx({ id }));+ expect(res.status).toBe(201);+ view = (await res.json()) as LayerProjectView;+ expect(view.versions.map((v) => v.label)).toEqual(["Decomposed", "Original"]);+ expect(view.headVersionId).toBe(view.versions[0].id);+ expect(view.doc.nodes.map((x) => x.name)).toEqual(nodes.map((x) => x.name));+ expect(view.jobs[0].state).toBe("applied");+ expect(view.project).toMatchObject({ status: "ready", layers: nodes.length });++ // Applying twice is refused; decomposing again too.+ res = await versions.POST(req("POST", { doc, label: "Decomposed", jobId: j.id }), ctx({ id }));+ expect(res.status).toBe(409);+ res = await jobs.POST(req("POST", { tool: "decompose", engine: "cloud", image: source, frame: [0, 0, 1920, 1080] }), ctx({ id }));+ expect(res.status).toBe(409);+ expect(((await res.json()) as { error: string }).error).toMatch(/can only be decomposed once/);+ });++ it("autosaves into the head version and refuses stale or foreign documents", async () => {+ const moved: LayerDoc = { ...view.doc, nodes: view.doc.nodes.map((x, i) => (i === 1 ? { ...x, x: x.x + 40, name: "Hero" } : x)) };+ let res = await one.PATCH(req("PATCH", { doc: moved, versionId: view.headVersionId, name: "Summer poster v2" }), ctx({ id }));+ expect(res.status).toBe(200);+ expect(((await res.json()) as LayerProject).name).toBe("Summer poster v2");+ res = await one.GET(req("GET"), ctx({ id }));+ const after = (await res.json()) as LayerProjectView;+ expect(after.doc.nodes[1].name).toBe("Hero");+ expect(after.versions).toHaveLength(2);++ // Another tab saved a version since: this one's head is stale.+ res = await one.PATCH(req("PATCH", { doc: moved, versionId: after.versions[1].id }), ctx({ id }));+ expect(res.status).toBe(409);+ // Files from elsewhere are refused.+ res = await one.PATCH(req("PATCH", { doc: { ...moved, nodes: [{ ...moved.nodes[0], src: "http://evil.example/x.png" }] } }), ctx({ id }));+ expect(res.status).toBe(400);+ res = await one.PATCH(req("PATCH", { doc: { ...initialDoc("/api/files/other.png", 10, 10) } }), ctx({ id }));+ expect(res.status).toBe(400);+ });++ it("runs one job per layer at a time, and cancels on request", async () => {+ const layer = view.doc.nodes[1];+ const body = { tool: "regenerate", engine: "open", image: source, nodeId: layer.id, frame: [layer.x, layer.y, layer.w, layer.h], prompt: "Make it gold", settings: { keepAlpha: true } };+ let res = await jobs.POST(req("POST", body), ctx({ id }));+ expect(res.status).toBe(201);+ const started = (await res.json()) as LayerJob;+ expect(started.generationIds).toHaveLength(2);+ res = await jobs.POST(req("POST", body), ctx({ id }));+ expect(res.status).toBe(409);+ expect(((await res.json()) as { error: string }).error).toBe("A generation is already running on this layer");++ res = await job.DELETE(req("DELETE"), ctx({ id, jobId: started.id }));+ expect(res.status).toBe(200);+ expect(((await res.json()) as LayerJob).state).toBe("dismissed");+ for (const g of started.generationIds) expect(gens.getGeneration(g)?.status).toBe("canceled");+ // Free again.+ res = await jobs.POST(req("POST", { ...body, settings: {} }), ctx({ id }));+ expect(res.status).toBe(201);+ const second = (await res.json()) as LayerJob;+ res = await job.PATCH(req("PATCH", { state: "dismissed" }), ctx({ id, jobId: second.id }));+ expect(((await res.json()) as LayerJob).state).toBe("dismissed");+ // Validation errors come back as 400 with a reason.+ res = await jobs.POST(req("POST", { tool: "regional", engine: "cloud", image: source, frame: [0, 0, 10, 10] }), ctx({ id }));+ expect(res.status).toBe(400);+ expect(((await res.json()) as { error: string }).error).toMatch(/Describe your changes/);+ });++ it("restores an older version as a new head", async () => {+ const original = view.versions[view.versions.length - 1];+ const res = await versions.POST(req("POST", { from: original.id }), ctx({ id }));+ expect(res.status).toBe(201);+ const v = (await res.json()) as LayerProjectView;+ expect(v.versions[0].label).toBe("Restored “Original”");+ expect(v.doc.nodes).toHaveLength(1);+ expect(v.doc.decomposed).toBe(false);+ });++ it("opens a finished layers result as a project", async () => {+ const g = gens.createGenerations({ feature: "image", modelId: "seedream-5-layers", op: "layers", inputs: { images: [source] }, params: { aspectRatio: "1:1" } })[0];+ await settle(g.id);+ const res = await list.POST(req("POST", { source, width: 512, height: 512, generationId: g.id }));+ expect(res.status).toBe(201);+ const v = (await res.json()) as LayerProjectView;+ expect(v.jobs).toHaveLength(1);+ expect(v.jobs[0]).toMatchObject({ tool: "decompose", state: "pending", generationIds: [g.id], frame: [0, 0, 512, 512] });+ expect(v.jobs[0].result?.status).toBe("succeeded");+ const bad = await list.POST(req("POST", { source, width: 512, height: 512, generationId: "nope" }));+ expect(bad.status).toBe(400);+ });++ it("keeps the files a project uses, and deletes only the project", async () => {+ const asset = source.split("/").pop()!.split(".")[0];+ expect(gens.assetInUse(asset)).toBe(true);+ const made = view.jobs[0].generationIds[0];+ let res = await one.DELETE(req("DELETE"), ctx({ id }));+ expect(res.status).toBe(204);+ res = await one.GET(req("GET"), ctx({ id }));+ expect(res.status).toBe(404);+ // The generations it made stay in the library.+ expect(gens.getGeneration(made)?.status).toBe("succeeded");+ res = await one.DELETE(req("DELETE"), ctx({ id }));+ expect(res.status).toBe(404);+ });+});