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: fix the review's findings (results never overwrite edits, deep links, model routing, exports)
Claude7205ef74729d
diff --git a/src/app/api/layers/renders/route.ts b/src/app/api/layers/renders/route.tsnew file mode 100644index 00000000..84fa6f31--- /dev/null+++ b/src/app/api/layers/renders/route.ts@@ -0,0 +1,20 @@+import { saveFile } from "@/server/storage";++const MAX_BYTES = 64 * 1024 * 1024;+const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);++/**+ * A picture the editor rendered to hand to a model or to keep in a layer (a layer, a region, the+ * composite, a mask, a merged region, a colour grade). Stored like an upload but as "derived", so it+ * stays out of the Library's Uploads and the pickers; projects that use it keep it (ASSET_REFS).+ */+export async function POST(request: Request) {+ const form = await request.formData().catch(() => null);+ const file = form?.get("file");+ if (!(file instanceof File)) return Response.json({ error: "No file" }, { status: 400 });+ if (file.size > MAX_BYTES) return Response.json({ error: "That render is too large (64 MB max)" }, { status: 413 });+ const data = Buffer.from(await file.arrayBuffer());+ if (file.type !== "image/png" || !data.subarray(0, 8).equals(PNG_MAGIC)) return Response.json({ error: "Renders are PNG images" }, { status: 415 });+ const asset = saveFile({ data, contentType: "image/png", name: file.name.slice(0, 120), source: "derived" });+ return Response.json(asset, { status: 201 });+}diff --git a/src/components/layers/apply.ts b/src/components/layers/apply.tsindex 0e85b38c..6223a108 100644--- a/src/components/layers/apply.ts+++ b/src/components/layers/apply.ts@@ -1,5 +1,3 @@-"use client";-import {addNodes,addRevision,@@ -16,13 +14,17 @@ import {type LayerRevision,type MeasuredOutput,} from "@/lib/layers";-import { alphaBox, loadImage, sizeOf } from "./render";/*** What a finished tool job does to the document: decompositions and splits become layers (placed by* their boxes, or cropped to their alpha), edits become a new revision of their layer (or a new* layer on top for the whole image), a region edit becomes the Original / New pair, Expand grows the* canvas with the fill underneath.+ *+ * Two halves: measuring the result's images takes the browser (src/components/layers/measure.ts,+ * once per job), laying them out is pure ({@link applyMeasured}). The editor lays a result out on+ * the document as it is right before saving the version, and again on the newest document if the+ * user edited meanwhile, so no edit made while a result lands is lost.*/const NEW_LAYER_NAMES: Partial<Record<LayerJob["tool"], string>> = {@@ -34,6 +36,22 @@ const NEW_LAYER_NAMES: Partial<Record<LayerJob["tool"], string>> = {angles: "New angle",};+/** One image of a result, measured: its pixel size and the box of its opaque pixels. */+export interface MeasuredImage {+ url: string;+ meta?: Record<string, unknown>;+ natural: [number, number];+ /** Alpha box (image px); null when fully clear, undefined when not measured. */+ alpha?: Box | null;+}++export interface MeasuredJob {+ /** The result's images, in output order. */+ outputs: MeasuredImage[];+ /** A regional edit's region as it was (the Original half of the pair); null when it didn't load. */+ original?: MeasuredImage | null;+}+export interface Applied {doc: LayerDoc;/** Toast text. */@@ -42,9 +60,23 @@ export interface Applied {select?: string;}-async function measure(url: string) {- const img = await loadImage(url);- return { img, natural: sizeOf(img) };+export interface ApplyOptions {+ /** New layer ids: hand the same sequence to a second call (a rebase) to get the same ids. */+ newId: () => string;+ /** Revision time stamps. */+ at: number;+}++/** Ids from a pool: every function it hands out returns the same sequence. */+export function idPool(make: () => string): () => () => string {+ const pool: string[] = [];+ return () => {+ let i = 0;+ return () => {+ pool[i] ??= make();+ return pool[i++];+ };+ };}/** Keep the frame's centre and width; take the height from the image's shape. */@@ -58,27 +90,36 @@ function newNode(id: string, name: string, box: Box, src: string, natural: [numbreturn { id, name: name.slice(0, 80), z: 0, x: box[0], y: box[1], w: box[2], h: box[3], rotation: 0, src, crop, natural, revisions: [rev], revision: 0 };}-export async function applyJob(doc: LayerDoc, job: LayerJob, newId: () => string): Promise<Applied> {+/** The images of a job's result that need measuring, and whether their alpha box is needed. */+export function imagesToMeasure(job: LayerJob): { url: string; alpha: boolean }[] {const outputs = (job.result?.outputs ?? []).filter((o) => o.kind === "image");+ if (job.tool === "decompose" || job.tool === "split") return outputs.map((o) => ({ url: o.url, alpha: true }));+ const last = outputs[outputs.length - 1];+ return last ? [{ url: last.url, alpha: job.tool === "generate-layer" }] : [];+}++/** Lay a measured result out on `doc` (pure). Throws when there's nothing to add. */+export function applyMeasured(doc: LayerDoc, job: LayerJob, m: MeasuredJob, opts: ApplyOptions): Applied {+ const { newId, at } = opts;+ const outputs = m.outputs;if (!outputs.length) throw new Error("The model returned no image");- const at = Date.now();const prompt = typeof job.settings?.prompt === "string" ? job.settings.prompt : undefined;if (job.tool === "decompose" || job.tool === "split") {const target = job.tool === "split" ? getNode(doc, job.nodeId) : undefined;const frame: Box = target ? [target.x, target.y, target.w, target.h] : job.frame;- const measured = await Promise.all(outputs.map(async (o) => ({ o, ...(await measure(o.url)) })));// Seedream's pixel boxes are measured on its base layer (z 0).- const base = measured.find((m) => m.o.meta?.z === 0) ?? measured[0];+ const base = outputs.find((o) => o.meta?.z === 0) ?? outputs[0];const placed: MeasuredOutput[] = [];- for (const m of measured) {- let p = placeOutput(frame, m.natural, m.o.meta ?? {}, base.natural);+ for (const o of outputs) {+ let p = placeOutput(frame, o.natural, o.meta ?? {}, base.natural);if (p.needsAlpha) {- const t = tightenToAlpha(frame, m.natural, alphaBox(m.img));- if (!t) continue; // an empty layer+ // Unmeasured: the whole canvas (an empty layer measures null and is left out).+ const t = o.alpha === undefined ? { box: frame, crop: null, needsAlpha: false } : tightenToAlpha(frame, o.natural, o.alpha);+ if (!t) continue;p = t;}- placed.push({ url: m.o.url, meta: m.o.meta, natural: m.natural, placement: p });+ placed.push({ url: o.url, meta: o.meta, natural: o.natural, placement: p });}if (!placed.length) throw new Error("No layers came back from the split");const nodes = nodesFromOutputs(placed, {@@ -90,21 +131,19 @@ export async function applyJob(doc: LayerDoc, job: LayerJob, newId: () => stringif (job.tool === "decompose") {return { doc: { ...doc, decomposed: true, nodes }, message: `Decomposed into ${nodes.length} layers` };}- const next = target ? replaceNodes(doc, [target.id], nodes) : addNodes(doc, nodes);+ let next = target ? replaceNodes(doc, [target.id], nodes) : addNodes(doc, nodes);+ // Separating the original picture is its decomposition (“An image can only be decomposed once”).+ if (!next.decomposed && typeof job.settings?.image === "string" && job.settings.image === doc.source) next = { ...next, decomposed: true };return { doc: next, message: `${target?.name ?? "Layer"} split into ${nodes.length} layers`, select: nodes[nodes.length - 1]?.id };}const out = outputs[outputs.length - 1];- const { img, natural } = await measure(out.url);+ const natural = out.natural;if (job.tool === "regional") {- const original = typeof job.settings?.image === "string" ? job.settings.image : undefined;const rect = job.frame;const add: LayerNode[] = [];- if (original) {- const before = await measure(original).catch(() => null);- if (before) add.push({ ...newNode(newId(), "Original", rect, original, before.natural, "Original", at), role: "original" });- }+ if (m.original) add.push({ ...newNode(newId(), "Original", rect, m.original.url, m.original.natural, "Original", at), role: "original" });const feather = typeof job.settings?.feather === "number" ? job.settings.feather : 12;const edited = { ...newNode(newId(), "New", rect, out.url, natural, "Regional edit", at, null, prompt), role: "new" as const, feather };add.push(edited);@@ -118,8 +157,7 @@ export async function applyJob(doc: LayerDoc, job: LayerJob, newId: () => string}if (job.tool === "generate-layer") {- const alpha = alphaBox(img);- const crop = alpha ?? null;+ const crop = out.alpha ?? null;const [cw, ch] = crop ? [crop[2], crop[3]] : natural;const k = Math.min((doc.width * 0.5) / cw, (doc.height * 0.5) / ch);const w = cw * k;diff --git a/src/components/layers/editor-context.tsx b/src/components/layers/editor-context.tsxindex 4691ed3d..d7b188fe 100644--- a/src/components/layers/editor-context.tsx+++ b/src/components/layers/editor-context.tsx@@ -37,6 +37,12 @@ export interface EditorCtx {jobs: LayerJob[];/** The job still working on a layer (queued, running, or finished but not laid out yet). */busyJob: (nodeId: string) => LayerJob | undefined;+ /** The newest failed run on a layer the user hasn't dismissed yet. */+ failedJob: (nodeId: string) => LayerJob | undefined;+ /** Show a job's tool (and its layer): where its failure can be retried. */+ showJob: (job: LayerJob) => void;+ /** “An image can only be decomposed once”: the project's fact, whichever version is open. */+ decomposed: boolean;/** Start a tool; resolves to the job, or null when it couldn't start (the reason was shown). */run: (input: RunInput) => Promise<LayerJob | null>;/** Dismiss a failed job, cancel a running one, or mark one used (a text detection that filled Edit text). */@@ -62,6 +68,35 @@ export interface EditorCtx {export type ToolId = "decompose" | "edit-text" | "remove-bg" | "regional" | "upscale" | "relight" | "angles" | "expand" | "grade";+/** The tool form that started each kind of job (none: the layer card or the Generate layer dialog). */+export const TOOL_FOR_JOB: Record<LayerTool, ToolId | null> = {+ decompose: "decompose",+ split: "decompose",+ regenerate: null,+ "generate-layer": null,+ "text-detect": "edit-text",+ "text-edit": "edit-text",+ "bg-remove": "remove-bg",+ regional: "regional",+ upscale: "upscale",+ relight: "relight",+ angles: "angles",+ expand: "expand",+};++/**+ * A key press the editor's shortcuts should leave alone: already handled, typed into a field, or+ * pressed in a dialog, menu or list (a Delete in the Edit history sheet mustn't delete a layer).+ */+export function keysBelongElsewhere(e: KeyboardEvent): boolean {+ if (e.defaultPrevented) return true;+ const t = e.target;+ if (t instanceof HTMLElement && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))) return true;+ if (t instanceof Element && t.closest('[role="dialog"],[role="alertdialog"],[role="menu"],[role="listbox"]')) return true;+ // A modal is open (focus can sit on its overlay or the page behind for a moment).+ return !!document.querySelector('[role="dialog"][data-state="open"],[role="alertdialog"][data-state="open"],[role="menu"][data-state="open"]');+}+export const Ctx = createContext<EditorCtx | null>(null);export function useEditor(): EditorCtx {diff --git a/src/components/layers/layers-editor.tsx b/src/components/layers/layers-editor.tsxindex e05c3df5..faedd70e 100644--- a/src/components/layers/layers-editor.tsx+++ b/src/components/layers/layers-editor.tsx@@ -6,35 +6,43 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useReducer, useRef, uimport { toast } from "sonner";import { ErrorState, NotFoundState } from "@/components/empty-state";import { Button } from "@/components/ui/button";+import { useSidebar } from "@/components/ui/sidebar";import { Skeleton } from "@/components/ui/skeleton";import { CompareSlider } from "@/components/studio/compare-slider";import { useIsMobile } from "@/hooks/use-mobile";-import { uploadFile, useEngine, useStatus } from "@/lib/api";+import { useEngine, useStatus } from "@/lib/api";import {APPLIES_TO_DOC,+ decomposeCost,deleteNode,duplicateNode,getNode,historyReducer,+ LayerLimitError,nativeSize,+ roomFor,+ TOOL_LABELS,+ TOOL_MODELS,updateNode,type Box,type LayerDoc,+ type LayerJob,type LayerModelInfo,type LayerNode,type LayerProjectView,+ type LayerTool,} from "@/lib/layers";-import { applyJob } from "./apply";-import { Ctx, isFailed, isRunning, type EditorCtx, type MaskEdit, type RunInput, type StageMode, type ToolId } from "./editor-context";+import { applyMeasured, idPool, type Applied } from "./apply";+import { costLabel, Ctx, isFailed, isRunning, keysBelongElsewhere, latestJob, TOOL_FOR_JOB, type EditorCtx, type MaskEdit, type RunInput, type StageMode, type ToolId } from "./editor-context";import { LayersPanel } from "./layers-panel";+import { measureJob } from "./measure";import { MobileView } from "./mobile-view";-import { loadImage, ratioOf, renderDoc, renderNative, toBlob, uploadRender } from "./render";+import { loadImage, ratioOf, renderDoc, renderNative, renderSource, toBlob, uploadDerived, uploadRender } from "./render";import { Stage } from "./stage";import { ToolRail } from "./tools";import { TopBar, type SaveState } from "./top-bar";import { LayersRequestError, saveCover, saveDoc, useLayerActions, useLayerProject } from "./use-layers";-const typing = (t: EventTarget | null) => t instanceof HTMLElement && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName));/** Focus is on a control that uses the arrow keys itself. */const widget = (t: EventTarget | null) =>t instanceof HTMLElement && !!t.closest('[role="radio"],[role="slider"],[role="menuitem"],[role="menu"],[role="tab"],[role="option"],[role="dialog"],[data-reorder]');@@ -49,6 +57,12 @@ function pristine(doc: LayerDoc): boolean {/** A layer whose file is exactly what it shows. */const plain = (n: LayerNode) => !n.crop && !n.maskSrc && !n.feather;+/** Tools whose failures a layer row shows (a text detection's shows in Edit text). */+const NODE_TOOLS = (Object.keys(TOOL_FOR_JOB) as LayerTool[]).filter((t) => t !== "text-detect");++/** Autosave retries after a failure (then every 15 s). */+const RETRY_MS = [2000, 5000, 15000];+function EditorSkeleton() {return (<div className="flex h-svh min-w-0 flex-col overflow-hidden md:h-[calc(100svh-0.5rem)]">@@ -87,6 +101,24 @@ export function LayersEditor({ id, models }: { id: string; models: Record<stringreturn <EditorSkeleton />;}+/**+ * Below 1280 px the app's sidebar folds to icons while the editor is open, so the canvas keeps its+ * room next to a tool's form and the Layers panel; it opens again when you leave.+ */+function useRoomyCanvas() {+ const sidebar = useSidebar();+ const ref = useRef(sidebar);+ useLayoutEffect(() => {+ ref.current = sidebar;+ });+ useEffect(() => {+ const s = ref.current;+ if (s.isMobile || !s.open || window.innerWidth >= 1280) return;+ s.setOpen(false);+ return () => ref.current.setOpen(true);+ }, []);+}+function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: () => Promise<{ data?: LayerProjectView }>; models: Record<string, LayerModelInfo> }) {// The document is the editor's once loaded; later fetches bring jobs and versions.const [initial] = useState(view);@@ -95,13 +127,16 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()const isMobile = useIsMobile();const [engine, setEngine] = useEngine();const status = useStatus().data;+ useRoomyCanvas();const [hist, dispatch] = useReducer(historyReducer, initial.doc, (doc) => ({ past: [], present: doc, future: [] }));const doc = hist.present;const docRef = useRef(doc);+ const histRef = useRef(hist);useLayoutEffect(() => {docRef.current = doc;- }, [doc]);+ histRef.current = hist;+ }, [doc, hist]);const headRef = useRef(initial.headVersionId);const [head, setHeadState] = useState(initial.headVersionId);const setHead = useCallback((v: string) => {@@ -110,10 +145,13 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()}, []);const savedRef = useRef<LayerDoc>(initial.doc);const [save, setSave] = useState<SaveState>("saved");+ /** The document a tool's version was saved with: undoing past it saves a new version (the tool's keeps its result). */+ const milestone = useRef<LayerDoc | null>(null);const [selectedId, setSelectedId] = useState<string | null>(null);const selected = getNode(doc, selectedId);- const [tool, setTool] = useState<ToolId | null>(() => (!initial.doc.decomposed && initial.doc.nodes.length === 1 ? "decompose" : null));+ const decomposed = doc.decomposed || view.project.decomposed;+ const [tool, setTool] = useState<ToolId | null>(() => (!initial.doc.decomposed && !initial.project.decomposed && initial.doc.nodes.length === 1 ? "decompose" : null));const [splitTarget, setSplitTarget] = useState<string | null>(null);const [mode, setModeState] = useState<StageMode>("select");const [region, setRegion] = useState<Box | null>(null);@@ -124,58 +162,94 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()const [maskVersion, setMaskVersion] = useState(0);const [brushSize, setBrushSize] = useState(() => Math.round(Math.max(initial.doc.width, initial.doc.height) / 30));const [compare, setCompare] = useState(false);+ const toolRef = useRef(tool);+ const selectedRef = useRef(selectedId);+ useLayoutEffect(() => {+ toolRef.current = tool;+ selectedRef.current = selectedId;+ }, [tool, selectedId]);const commit = useCallback((d: LayerDoc, merge?: string) => dispatch({ type: "commit", doc: d, merge, at: Date.now() }), []);const resetTo = useCallback((v: LayerProjectView) => {setHead(v.headVersionId);savedRef.current = v.doc;+ docRef.current = v.doc;+ milestone.current = null;dispatch({ type: "reset", doc: v.doc });setSave("saved");},[setHead],);- // ---- Autosave into the head version (debounced; flushed with keepalive when leaving).- const pending = useRef<LayerDoc | null>(null);- /** The save in flight: a tool's version waits for it, so the two never cross. */- const saving = useRef<Promise<unknown>>(Promise.resolve());- useEffect(() => {- if (doc === savedRef.current) return;- pending.current = doc;- setSave("dirty");- const t = setTimeout(async () => {- setSave("saving");- const put = async (): Promise<void> => {- const sentHead = headRef.current;+ // ---- Writes to the server (autosaves, tool results, restores) run one at a time, so they never+ // cross: a result saved as a version can't be overwritten by an autosave started before it.+ const writes = useRef<Promise<unknown>>(Promise.resolve());+ const serial = useCallback(<T,>(fn: () => Promise<T>): Promise<T> => {+ const p = writes.current.then(fn);+ writes.current = p.catch(() => {});+ return p;+ }, []);++ // ---- Autosave into the head version (debounced; retried with backoff; flushed with keepalive when leaving).+ const failures = useRef(0);+ const retry = useRef<ReturnType<typeof setTimeout> | null>(null);+ /** The newest saveNow, for its own retries. */+ const saveAgain = useRef<() => Promise<void>>(() => Promise.resolve());+ const saveNow = useCallback(+ (): Promise<void> =>+ serial(async () => {+ if (retry.current) clearTimeout(retry.current);+ retry.current = null;+ const d = docRef.current;+ if (d === savedRef.current) {+ setSave((s) => (s === "conflict" ? s : "saved"));+ return;+ }+ setSave("saving");try {- await saveDoc(id, doc, sentHead);+ if (milestone.current && histRef.current.future.includes(milestone.current)) {+ // Undone past a tool's result: that version keeps the result; this becomes a new one.+ const v = await actions.version(id, { doc: d, label: "Edit" });+ setHead(v.headVersionId);+ milestone.current = null;+ } else {+ await saveDoc(id, d, headRef.current);+ }+ savedRef.current = d;+ if (failures.current) toast.dismiss("layers-save");+ failures.current = 0;+ setSave(docRef.current === d ? "saved" : "dirty");} catch (e) {- // A tool's result became the head meanwhile (this tab): save onto the new head.- if (e instanceof LayersRequestError && e.status === 409 && headRef.current !== sentHead) return put();- throw e;+ if (e instanceof LayersRequestError && e.status === 409) {+ setSave("conflict");+ toast.error(e.message, { id: "layers-conflict", action: { label: "Reload", onClick: () => void refetch().then((r) => r.data && resetTo(r.data)) } });+ return;+ }+ setSave("error");+ const n = failures.current++;+ if (n >= 2) toast.error("Your latest changes aren't saved yet", { id: "layers-save", description: `${(e as Error).message || "The server didn't answer"}. Fuobe keeps trying.`, duration: 10_000 });+ retry.current = setTimeout(() => void saveAgain.current(), RETRY_MS[Math.min(n, RETRY_MS.length - 1)]);}- };- const p = put();- saving.current = p.catch(() => {});- try {- await p;- savedRef.current = doc;- if (pending.current === doc) pending.current = null;- setSave("saved");- } catch (e) {- if (e instanceof LayersRequestError && e.status === 409) {- setSave("conflict");- toast.error(e.message, { id: "layers-conflict", action: { label: "Reload", onClick: () => void refetch().then((r) => r.data && resetTo(r.data)) } });- } else setSave("error");- }- }, 700);+ }),+ [serial, actions, id, setHead, refetch, resetTo],+ );+ useLayoutEffect(() => {+ saveAgain.current = saveNow;+ }, [saveNow]);+ useEffect(() => {+ if (doc === savedRef.current) {+ setSave((s) => (s === "dirty" ? "saved" : s));+ return;+ }+ setSave((s) => (s === "conflict" || s === "error" ? s : "dirty"));+ const t = setTimeout(() => void saveNow(), 700);return () => clearTimeout(t);- }, [doc, id, refetch, resetTo]);+ }, [doc, saveNow]);useEffect(() => {const flush = () => {- const d = pending.current;- if (d && d !== savedRef.current) void saveDoc(id, d, headRef.current, true).catch(() => {});+ const d = docRef.current;+ if (d !== savedRef.current) void saveDoc(id, d, headRef.current, true).catch(() => {});};const onHide = () => document.visibilityState === "hidden" && flush();document.addEventListener("visibilitychange", onHide);@@ -183,6 +257,7 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()return () => {document.removeEventListener("visibilitychange", onHide);window.removeEventListener("pagehide", flush);+ if (retry.current) clearTimeout(retry.current);flush();};}, [id]);@@ -205,11 +280,41 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()};}, [doc, id, initial.doc]);+ // ---- Selection changes end mask editing and per-layer previews.+ const select = useCallback((nid: string | null) => {+ setSelectedId(nid);+ setModeState((m) => (m === "brush" || m === "eraser" ? "select" : m));+ setMask((m) => (m && m.nodeId !== nid ? null : m));+ }, []);++ const openTool = useCallback((t: ToolId | null) => {+ setTool(t);+ if (t !== "decompose") setSplitTarget(null);+ }, []);+// ---- Jobs: start, and lay out their results as they land.const busyJob = useCallback((nodeId: string) => view.jobs.find((j) => j.nodeId === nodeId && j.tool !== "text-detect" && j.state === "pending" && !isFailed(j)),[view.jobs],);+ const failedJob = useCallback(+ (nodeId: string) => {+ const j = latestJob(view.jobs, NODE_TOOLS, nodeId);+ return j && isFailed(j) && j.result?.status === "failed" ? j : undefined;+ },+ [view.jobs],+ );+ const showJob = useCallback(+ (j: LayerJob) => {+ const node = getNode(docRef.current, j.nodeId);+ select(node ? node.id : null);+ const t = TOOL_FOR_JOB[j.tool];+ if (!t) return;+ setTool(t);+ setSplitTarget(j.tool === "split" && node ? node.id : null);+ },+ [select],+ );const run = useCallback<EditorCtx["run"]>(async (input: RunInput) => {@@ -259,45 +364,94 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()[actions, id],);+ // A finished result is measured (its images loaded) first, then laid out on the document as it is+ // right before its version is saved, and once more on the newest document if you edited meanwhile.const applying = useRef(new Set<string>());- const queue = useRef<Promise<void>>(Promise.resolve());useEffect(() => {for (const j of view.jobs) {if (j.state !== "pending" || j.result?.status !== "succeeded" || !APPLIES_TO_DOC.has(j.tool) || applying.current.has(j.id)) continue;applying.current.add(j.id);- queue.current = queue.current.then(async () => {- try {- await saving.current;- const res = await applyJob(docRef.current, j, () => nanoid(8));- const v = await actions.version(id, { doc: res.doc, label: j.label, jobId: j.id });- setHead(v.headVersionId);- savedRef.current = res.doc;- dispatch({ type: "commit", doc: res.doc });- if (res.select) setSelectedId(res.select);- if (j.tool === "split") setSplitTarget(null);- toast.success(res.message, { duration: 2500 });- } catch (e) {- if (e instanceof LayersRequestError && e.status === 409) {- // Another tab laid it out first: take the saved version.- const r = await refetch();- if (r.data) resetTo(r.data);- } else {- toast.error(`Couldn't add the result to your layers: ${(e as Error).message}`);- endJob(j.id, "dismiss");- }- }+ const fail = (e: unknown) => {+ toast.error(`Couldn't add the result to your layers: ${(e as Error).message}`);+ endJob(j.id, "dismiss");+ };+ void measureJob(j).then(+ (measured) =>+ serial(async () => {+ const ids = idPool(() => nanoid(8));+ const at = Date.now();+ const base = docRef.current;+ let res: Applied;+ try {+ res = applyMeasured(base, j, measured, { newId: ids(), at });+ } catch (e) {+ fail(e);+ return;+ }+ try {+ const v = await actions.version(id, { doc: res.doc, label: j.label, jobId: j.id });+ setHead(v.headVersionId);+ savedRef.current = res.doc;+ if (docRef.current !== base) {+ // Edited while the version saved: lay the result out on the newest document (the same+ // new layer ids); the autosave then puts it into the new version.+ try {+ res = applyMeasured(docRef.current, j, measured, { newId: ids(), at });+ } catch {+ // The newest document can't take it (e.g. the layer limit): keep the saved one.+ }+ }+ milestone.current = res.doc;+ docRef.current = res.doc;+ dispatch({ type: "commit", doc: res.doc });+ // Select the result unless you've moved on to another layer meanwhile.+ const sel = selectedRef.current;+ if (res.select && (!sel || sel === j.nodeId || !getNode(res.doc, sel))) setSelectedId(res.select);+ if (j.tool === "split") setSplitTarget(null);+ toast.success(res.message, { duration: 2500 });+ } catch (e) {+ if (e instanceof LayersRequestError && e.status === 409) {+ // Another tab laid it out first: take the saved version.+ const r = await refetch();+ if (r.data) resetTo(r.data);+ } else fail(e);+ }+ }),+ fail,+ );+ }+ }, [view.jobs, actions, id, refetch, resetTo, endJob, setHead, serial]);++ // ---- Failures are told once, wherever you are (the tool's form or the layer's card shows them too).+ const told = useRef<Set<string> | null>(null);+ useEffect(() => {+ if (!told.current) {+ // Failures from before this visit show on their layers and forms, without a toast each.+ told.current = new Set(view.jobs.filter(isFailed).map((j) => j.id));+ return;+ }+ for (const j of view.jobs) {+ if (!isFailed(j) || told.current.has(j.id)) continue;+ told.current.add(j.id);+ if (j.result?.status !== "failed") continue; // canceled: you asked for it+ const node = getNode(docRef.current, j.nodeId);+ const form = TOOL_FOR_JOB[j.tool];+ const scope = (j.nodeId ?? null) === selectedRef.current;+ // Already in view: the open form (or the selected layer's card) shows the failure.+ if (scope && (form ? toolRef.current === form : j.tool === "regenerate")) continue;+ toast.error(`${TOOL_LABELS[j.tool]} failed${node ? ` on ${node.name}` : ""}`, {+ id: `layers-failed-${j.id}`,+ description: j.result.error ?? "The model didn't finish.",+ ...(form || node ? { action: { label: "View", onClick: () => showJob(j) } } : {}),});}- }, [view.jobs, actions, id, refetch, resetTo, endJob, setHead]);+ }, [view.jobs, showJob]);// ---- Masks (brush paints the layer back, eraser hides it).- const setMode = useCallback(- (m: StageMode) => {- setModeState(m);- if (m !== "brush" && m !== "eraser") setMask(null);- },- [],- );+ const setMode = useCallback((m: StageMode) => {+ setModeState(m);+ if (m !== "brush" && m !== "eraser") setMask(null);+ }, []);useEffect(() => {if ((mode !== "brush" && mode !== "eraser") || !selected) return;if (mask?.nodeId === selected.id) return;@@ -331,9 +485,8 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()if (!mask) return;setSavingMask(true);try {- const blob = await toBlob(mask.canvas);- const asset = await uploadFile(new File([blob], "layer-mask.png", { type: "image/png" }));- commit(updateNode(docRef.current, mask.nodeId, { maskSrc: asset.url }));+ const url = await uploadDerived(await toBlob(mask.canvas), "layer-mask");+ commit(updateNode(docRef.current, mask.nodeId, { maskSrc: url }));toast.success("Mask saved", { duration: 1500 });setMode("select");} catch (e) {@@ -343,16 +496,6 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()}};- // ---- Selection changes end mask editing and per-layer previews.- const select = useCallback(- (nid: string | null) => {- setSelectedId(nid);- setModeState((m) => (m === "brush" || m === "eraser" ? "select" : m));- setMask((m) => (m && m.nodeId !== nid ? null : m));- },- [],- );-const setPreview = useCallback((pid: string, c: HTMLCanvasElement | null) => {setPreviews((old) => {if (!c && !old.has(pid)) return old;@@ -363,15 +506,10 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()});}, []);- const openTool = useCallback((t: ToolId | null) => {- setTool(t);- if (t !== "decompose") setSplitTarget(null);- }, []);-- // ---- Keyboard.+ // ---- Keyboard (never behind a dialog, a menu or in a field).useEffect(() => {const onKey = (e: KeyboardEvent) => {- if (typing(e.target)) return;+ if (keysBelongElsewhere(e)) return;const mod = e.metaKey || e.ctrlKey;if (mod && e.key.toLowerCase() === "z") {e.preventDefault();@@ -387,7 +525,9 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()const sel = getNode(d, selectedId);if (mod && e.key.toLowerCase() === "d" && sel) {e.preventDefault();- commit(duplicateNode(d, sel.id, nanoid(8)));+ if (e.repeat) return;+ if (!roomFor(d)) toast.error(new LayerLimitError().message, { id: "layers-limit" });+ else commit(duplicateNode(d, sel.id, nanoid(8)));return;}if (mod || e.altKey) return;@@ -423,24 +563,25 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()return () => window.removeEventListener("keydown", onKey);}, [selectedId, mode, commit, select, setMode, busyJob]);- // ---- Compare: the original against the current composite.- const [composite, setComposite] = useState<string | null>(null);+ // ---- Compare: the original, where it sits in the document now, against the current composite.+ const [pair, setPair] = useState<{ before: string; after: string } | null>(null);useEffect(() => {if (!compare) return;- let url: string | null = null;+ const urls: string[] = [];let gone = false;- void renderDoc(doc, { scale: Math.min(1, 1600 / Math.max(doc.width, doc.height)) })- .then((c) => toBlob(c))- .then((b) => {+ const scale = Math.min(1, 1600 / Math.max(doc.width, doc.height));+ void Promise.all([renderSource(doc, scale), renderDoc(doc, { scale })])+ .then((cs) => Promise.all(cs.map((c) => toBlob(c))))+ .then(([b, a]) => {if (gone) return;- url = URL.createObjectURL(b);- setComposite(url);+ urls.push(URL.createObjectURL(b), URL.createObjectURL(a));+ setPair({ before: urls[0], after: urls[1] });}).catch(() => toast.error("Couldn't render the comparison"));return () => {gone = true;- if (url) URL.revokeObjectURL(url);- setComposite(null);+ for (const u of urls) URL.revokeObjectURL(u);+ setPair(null);};}, [compare, doc]);@@ -481,6 +622,9 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()isDemo,jobs: view.jobs,busyJob,+ failedJob,+ showJob,+ decomposed,run,endJob,mode,@@ -498,7 +642,23 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()setSplitTarget,};- if (isMobile) return <MobileView project={view.project} doc={doc} jobs={view.jobs} />;+ if (isMobile) {+ const modelId = TOOL_MODELS.decompose[engine][0];+ const model = models[modelId];+ return (+ <MobileView+ project={view.project}+ doc={doc}+ jobs={view.jobs}+ decomposed={decomposed}+ separateCost={costLabel(model, isDemo(model), decomposeCost(modelId, 8))}+ onSeparate={async () => {+ await run({ tool: "decompose", target: { kind: "whole" }, settings: { resolution: "1K", mode: "standard", layers: 8 }, label: "Layer decomposition" });+ }}+ onDismiss={(jobId) => endJob(jobId, "dismiss")}+ />+ );+ }return (<Ctx.Provider value={ctx}>@@ -507,6 +667,7 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()name={view.project.name}onRename={(n) => void actions.rename(id, n).catch((e) => toast.error((e as Error).message))}save={save}+ onRetrySave={() => void saveNow()}canUndo={hist.past.length > 0}canRedo={hist.future.length > 0}onUndo={() => dispatch({ type: "undo" })}@@ -514,8 +675,10 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()versions={view.versions}headVersionId={head}onRestore={async (vid) => {+ // Unsaved edits go into the version they were made on first.+ void saveNow();try {- const v = await actions.version(id, { from: vid });+ const v = await serial(() => actions.version(id, { from: vid }));resetTo(v);select(null);toast.success("Version restored", { duration: 1500 });@@ -535,7 +698,7 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()<main className="relative flex min-w-0 flex-1 flex-col">{compare ? (<div className="checkerboard grid min-h-0 flex-1 place-items-center overflow-hidden p-6">- {composite ? <CompareSlider before={doc.source} after={composite} alt="Your layers" /> : <Loader2 className="size-5 animate-spin text-muted-foreground" />}+ {pair ? <CompareSlider before={pair.before} after={pair.after} alt="Your layers" /> : <Loader2 className="size-5 animate-spin text-muted-foreground" />}</div>) : (<Stagediff --git a/src/components/layers/layers-panel.tsx b/src/components/layers/layers-panel.tsxindex 6cb075fb..1f4bbf25 100644--- a/src/components/layers/layers-panel.tsx+++ b/src/components/layers/layers-panel.tsx@@ -21,7 +21,10 @@ import {Scissors,Sparkles,SplitSquareVertical,+ Link2,Trash2,+ TriangleAlert,+ Unlink2,Upload,X,} from "lucide-react";@@ -39,13 +42,30 @@ import { Switch } from "@/components/ui/switch";import { Textarea } from "@/components/ui/textarea";import { LibraryGrid } from "@/components/studio/media-slot";import { uploadFile } from "@/lib/api";-import { addNodes, deleteNode, duplicateNode, jobStatusText, moveNode, setRevision, TOOL_MODELS, updateNode, type LayerNode, type LayerRevision } from "@/lib/layers";+import {+ addNodes,+ deleteNode,+ duplicateNode,+ jobStatusText,+ LayerLimitError,+ moveNode,+ roomFor,+ setRevision,+ TOOL_LABELS,+ TOOL_MODELS,+ updateNode,+ type LayerNode,+ type LayerRevision,+} from "@/lib/layers";import { cn } from "@/lib/utils";import { Field } from "./bits";-import { costLabel, isFailed, latestJob, modelsFor, useEditor } from "./editor-context";+import { costLabel, modelsFor, TOOL_FOR_JOB, useEditor } from "./editor-context";import { downloadLayer, loadImage, sizeOf } from "./render";-/** A layer's thumbnail showing just the part of its image it uses (its crop), on a checkerboard. */+/**+ * A layer's thumbnail showing just the part of its image it uses (its crop), on a mid-grey+ * checkerboard so white-only layers (text) and black-only ones both stay visible in either theme.+ */export function LayerThumb({ node, className }: { node: Pick<LayerNode, "src" | "crop" | "natural" | "w" | "h">; className?: string }) {const crop = node.crop;const nat = node.natural;@@ -59,12 +79,18 @@ export function LayerThumb({ node, className }: { node: Pick<LayerNode, "src" |}: { backgroundImage: `url("${node.src}")`, backgroundSize: "100% 100%" };return (- <span className={cn("checkerboard grid size-10 shrink-0 place-items-center overflow-hidden rounded-md border", className)}>+ <span className={cn("grid size-10 shrink-0 place-items-center overflow-hidden rounded-md border", className)} style={THUMB_CHECKER}><span className="block max-h-full max-w-full bg-no-repeat" style={{ ...style, aspectRatio: `${aspect}`, width: aspect >= 1 ? "100%" : "auto", height: aspect >= 1 ? "auto" : "100%" }} /></span>);}+const THUMB_CHECKER: React.CSSProperties = {+ backgroundColor: "#8f8f8f",+ backgroundImage: "conic-gradient(#a6a6a6 25%, transparent 0 50%, #a6a6a6 0 75%, transparent 0)",+ backgroundSize: "10px 10px",+};+/** Add a layer from a file or the library: sized to fit 80% of the canvas, centred. */async function layerFromImage(url: string, name: string, doc: { width: number; height: number }): Promise<LayerNode> {const img = await loadImage(url);@@ -94,8 +120,8 @@ function AddLayer() {commit(addNodes(doc, [n]));select(n.id);toast.success("Layer added", { duration: 1500 });- } catch {- toast.error("Failed to add layer");+ } catch (e) {+ toast.error(e instanceof LayerLimitError ? e.message : "Failed to add layer");}};@@ -298,10 +324,12 @@ function LayerRow({onDragHandle: (e: React.PointerEvent, id: string) => void;dropBefore: boolean;}) {- const { doc, commit, select, busyJob, openTool, setSplitTarget, setMode, mode } = useEditor();+ const { doc, commit, select, busyJob, failedJob, openTool, setSplitTarget, setMode, mode } = useEditor();const [renaming, setRenaming] = useState(false);const [draft, setDraft] = useState(node.name);const job = busyJob(node.id);+ // A failed run stays on its row until it's dismissed (its layer card or tool form says why).+ const failed = busy ? undefined : failedJob(node.id);const move = (dz: number) => {const to = node.z + dz;if (to < 0 || to >= total) return;@@ -352,9 +380,15 @@ function LayerRow({<LayerThumb node={node} /><span className="min-w-0 flex-1">{renaming ? null : <span className={cn("block truncate text-[13px]", selected && "font-medium text-brand-text")}>{node.name}</span>}- <span className="block truncate text-[11px] text-muted-foreground">- {busy ?? (node.revisions.length > 1 ? `Version ${node.revision + 1} of ${node.revisions.length}` : node.maskSrc ? "Masked" : `Layer ${index}`)}- </span>+ {failed ? (+ <span className="flex items-center gap-1 truncate text-[11px] font-medium text-destructive">+ <TriangleAlert className="size-3 shrink-0" /> {TOOL_LABELS[failed.tool]} failed+ </span>+ ) : (+ <span className="block truncate text-[11px] text-muted-foreground">+ {busy ?? (node.revisions.length > 1 ? `Version ${node.revision + 1} of ${node.revisions.length}` : node.maskSrc ? "Masked" : `Layer ${index}`)}+ </span>+ )}</span></button>{renaming && (@@ -396,7 +430,7 @@ function LayerRow({<DropdownMenuItem onSelect={() => setTimeout(() => setRenaming(true), 50)}><Pencil /> Rename layer</DropdownMenuItem>- <DropdownMenuItem onSelect={() => commit(duplicateNode(doc, node.id, nanoid(8)))}>+ <DropdownMenuItem onSelect={() => (roomFor(doc) ? commit(duplicateNode(doc, node.id, nanoid(8))) : toast.error(new LayerLimitError().message, { id: "layers-limit" }))}><Copy /> Duplicate</DropdownMenuItem><DropdownMenuItem onSelect={() => void downloadLayer(doc, node).catch(() => toast.error("Could not download the layer."))}>@@ -446,7 +480,7 @@ function LayerRow({/** Per-layer AI: “Layer edit prompt” + reference → Generate / Regenerate, and the layer's revisions. */function SelectedLayer({ node }: { node: LayerNode }) {- const { doc, commit, run, engine, models, isDemo, jobs, endJob, busyJob } = useEditor();+ const { doc, commit, run, engine, models, isDemo, endJob, busyJob, failedJob, showJob, tool } = useEditor();const [prompt, setPrompt] = useState(node.prompt ?? "");const [ref, setRef] = useState<string | null>(node.refSrc ?? null);const options = modelsFor(models, TOOL_MODELS.regenerate[engine]);@@ -456,10 +490,9 @@ function SelectedLayer({ node }: { node: LayerNode }) {const [keepAlpha, setKeepAlpha] = useState(node.z > 0);const [starting, setStarting] = useState(false);const running = busyJob(node.id);- const failed = useMemo(() => {- const j = latestJob(jobs, ["regenerate"], node.id);- return j && isFailed(j) ? j : undefined;- }, [jobs, node.id]);+ // The newest failed run on this layer, whichever tool started it (its form can try again).+ const failed = failedJob(node.id);+ const failedForm = failed ? TOOL_FOR_JOB[failed.tool] : null;const edited = node.revisions.length > 1;const rev = node.revisions[node.revision];@@ -534,14 +567,20 @@ function SelectedLayer({ node }: { node: LayerNode }) {</Button></div>)}- {failed && (+ {failed && !(failedForm && tool === failedForm) && (<div role="alert" className="rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-[12px]">- <p className="font-medium text-destructive">Layer generation failed</p>+ <p className="font-medium text-destructive">{failed.tool === "regenerate" ? "Layer generation failed" : `${TOOL_LABELS[failed.tool]} failed`}</p><p className="text-muted-foreground">{failed.result?.error ?? "Try again."}</p><div className="mt-1.5 flex gap-3">- <button type="button" className="font-medium text-brand-text hover:underline" onClick={() => void go()}>- Try again- </button>+ {failed.tool === "regenerate" ? (+ <button type="button" className="font-medium text-brand-text hover:underline" onClick={() => void go()}>+ Try again+ </button>+ ) : failedForm ? (+ <button type="button" className="font-medium text-brand-text hover:underline" onClick={() => showJob(failed)}>+ Open {TOOL_LABELS[failed.tool]}+ </button>+ ) : null}<button type="button" className="text-muted-foreground hover:underline" onClick={() => endJob(failed.id, "dismiss")}>Dismiss</button>@@ -569,32 +608,88 @@ function SelectedLayer({ node }: { node: LayerNode }) {<Field label="Opacity" hint={`${Math.round((node.opacity ?? 1) * 100)}%`}><Slider aria-label="Opacity" min={0} max={100} step={1} value={[Math.round((node.opacity ?? 1) * 100)]} onValueChange={([v]) => commit(updateNode(doc, node.id, { opacity: v / 100 }), `opacity:${node.id}`)} /></Field>- <div className="grid grid-cols-5 gap-1.5">- {(- [- ["x", "X"],- ["y", "Y"],- ["w", "W"],- ["h", "H"],- ["rotation", "°"],- ] as const- ).map(([k, label]) => (- <label key={k} className="space-y-0.5">- <span className="block text-center text-[11px] text-muted-foreground">{label}</span>- <Input- type="number"- inputMode="decimal"- aria-label={k === "rotation" ? "Rotation in degrees" : `${label} in pixels`}- className="h-7 px-1 text-center font-mono text-[12px]"- value={Math.round(node[k])}- onChange={(e) => {- const v = Number(e.target.value);- if (!Number.isFinite(v) || ((k === "w" || k === "h") && v < 1)) return;- commit(updateNode(doc, node.id, { [k]: v }), `${k}:${node.id}`);- }}- />- </label>- ))}+ <Geometry node={node} />+ </div>+ );+}++/**+ * A number typed into a draft: committed on Enter, on leaving the field and on arrow-key steps+ * (Shift: 10), so clearing it or typing "-50" passes through no in-between values. Escape reverts.+ */+function NumberField({ label, name, value, min, onCommit }: { label: string; name: string; value: number; min?: number; onCommit: (v: number) => void }) {+ const shown = String(Math.round(value));+ const [draft, setDraft] = useState<string | null>(null);+ const commitDraft = (s: string) => {+ setDraft(null);+ const v = Number(s.trim().replace(",", "."));+ if (!s.trim() || !Number.isFinite(v) || (min !== undefined && v < min) || Math.round(v) === Math.round(value)) return;+ onCommit(v);+ };+ return (+ <label className="flex h-7 min-w-0 items-center rounded-md border bg-transparent pl-2 text-[12px] focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/50">+ <span className="w-3 shrink-0 text-[11px] text-muted-foreground" aria-hidden>+ {label}+ </span>+ <input+ type="text"+ inputMode="decimal"+ aria-label={name}+ className="h-full min-w-0 flex-1 bg-transparent px-1 text-right font-mono text-[12px] outline-none"+ value={draft ?? shown}+ onChange={(e) => {+ // Digits, one leading minus and a decimal point: "-" and "" are fine while typing.+ if (/^-?\d*([.,]\d*)?$/.test(e.target.value)) setDraft(e.target.value);+ }}+ onFocus={(e) => e.currentTarget.select()}+ onBlur={(e) => commitDraft(e.currentTarget.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ commitDraft(e.currentTarget.value);+ } else if (e.key === "Escape") {+ e.preventDefault();+ e.stopPropagation();+ setDraft(null);+ } else if (e.key === "ArrowUp" || e.key === "ArrowDown") {+ e.preventDefault();+ const step = (e.key === "ArrowUp" ? 1 : -1) * (e.shiftKey ? 10 : 1);+ const base = Number((draft ?? shown).replace(",", "."));+ const next = Math.round(Number.isFinite(base) ? base : value) + step;+ if (min !== undefined && next < min) return;+ setDraft(null);+ onCommit(next);+ }+ }}+ />+ </label>+ );+}++/** X / Y, W ⛓ H and rotation, two to a row; W and H keep the layer's shape while the link is on. */+function Geometry({ node }: { node: LayerNode }) {+ const { doc, commit } = useEditor();+ const [locked, setLocked] = useState(true);+ const set = (k: "x" | "y" | "w" | "h" | "rotation", v: number) => {+ let patch: Partial<LayerNode> = { [k]: v };+ if (locked && (k === "w" || k === "h") && node.w > 0 && node.h > 0) patch = k === "w" ? { w: v, h: (v * node.h) / node.w } : { h: v, w: (v * node.w) / node.h };+ commit(updateNode(doc, node.id, patch), `${k}:${node.id}`);+ };+ return (+ <div className="space-y-1.5" role="group" aria-label="Position and size">+ <div className="grid grid-cols-2 gap-1.5">+ <NumberField label="X" name="X in pixels" value={node.x} onCommit={(v) => set("x", v)} />+ <NumberField label="Y" name="Y in pixels" value={node.y} onCommit={(v) => set("y", v)} />+ </div>+ <div className="grid grid-cols-[1fr_auto_1fr] items-center gap-1">+ <NumberField label="W" name="Width in pixels" value={node.w} min={1} onCommit={(v) => set("w", v)} />+ <Button size="icon-xs" variant="ghost" aria-pressed={locked} aria-label="Keep the layer's shape when changing W or H" title={locked ? "W and H keep the shape" : "W and H change on their own"} onClick={() => setLocked(!locked)}>+ {locked ? <Link2 /> : <Unlink2 />}+ </Button>+ <NumberField label="H" name="Height in pixels" value={node.h} min={1} onCommit={(v) => set("h", v)} />+ </div>+ <div className="grid grid-cols-2 gap-1.5">+ <NumberField label="°" name="Rotation in degrees" value={node.rotation} onCommit={(v) => set("rotation", v)} /></div></div>);@@ -644,7 +739,7 @@ export function LayersPanel() {};return (- <aside className="flex min-h-0 w-[240px] shrink-0 flex-col border-l bg-background lg:w-[264px] xl:w-[300px]" aria-label="Layers panel">+ <aside className="flex min-h-0 w-[232px] shrink-0 flex-col border-l bg-background lg:w-[264px] xl:w-[300px]" aria-label="Layers panel"><div className="flex h-12 shrink-0 items-center gap-2 px-3"><h2 className="text-[13px] font-semibold">Layers</h2><span className="font-mono text-[12px] text-subtle-foreground">{doc.nodes.length}</span>diff --git a/src/components/layers/measure.ts b/src/components/layers/measure.tsnew file mode 100644index 00000000..6a323259--- /dev/null+++ b/src/components/layers/measure.ts@@ -0,0 +1,25 @@+"use client";++import type { LayerJob } from "@/lib/layers";+import { imagesToMeasure, type MeasuredImage, type MeasuredJob } from "./apply";+import { alphaBox, loadImage, sizeOf } from "./render";++/** Load a finished job's images and measure them (sizes, alpha boxes) for {@link applyMeasured}. */+export async function measureJob(job: LayerJob): Promise<MeasuredJob> {+ const byUrl = new Map((job.result?.outputs ?? []).map((o) => [o.url, o]));+ const outputs = await Promise.all(+ imagesToMeasure(job).map(async ({ url, alpha }): Promise<MeasuredImage> => {+ const img = await loadImage(url);+ return { url, meta: byUrl.get(url)?.meta, natural: sizeOf(img), ...(alpha ? { alpha: alphaBox(img) } : {}) };+ }),+ );+ let original: MeasuredImage | null | undefined;+ if (job.tool === "regional" && typeof job.settings?.image === "string") {+ const url = job.settings.image;+ original = await loadImage(url).then(+ (img) => ({ url, natural: sizeOf(img) }),+ () => null,+ );+ }+ return { outputs, ...(original !== undefined ? { original } : {}) };+}diff --git a/src/components/layers/mobile-view.tsx b/src/components/layers/mobile-view.tsxindex 232028d0..0537a656 100644--- a/src/components/layers/mobile-view.tsx+++ b/src/components/layers/mobile-view.tsx@@ -1,19 +1,42 @@"use client";-import { ArrowLeft, EyeOff, MonitorSmartphone } from "lucide-react";+import { ArrowLeft, EyeOff, Layers, Loader2, MonitorSmartphone, TriangleAlert } from "lucide-react";import Link from "next/link";import { useEffect, useState } from "react";import { Button } from "@/components/ui/button";+import { Progress } from "@/components/ui/progress";import { SidebarTrigger } from "@/components/ui/sidebar";import { Skeleton } from "@/components/ui/skeleton";-import type { LayerDoc, LayerJob, LayerProject } from "@/lib/layers";+import { DECOMPOSE_COPY, jobStatusText, type LayerDoc, type LayerJob, type LayerProject } from "@/lib/layers";+import { isFailed, isRunning, latestJob } from "./editor-context";import { LayerThumb } from "./layers-panel";import { renderDoc, toBlob } from "./render";import { DownloadMenu } from "./top-bar";-/** Phones: a friendly read-only view with the picture, its layers and the downloads. */-export function MobileView({ project, doc, jobs }: { project: LayerProject; doc: LayerDoc; jobs: LayerJob[] }) {+/**+ * Phones: a friendly read-only view with the picture, its layers and the downloads. An image that+ * isn't split yet can be separated with one tap (the default settings); everything else waits for a+ * larger screen.+ */+export function MobileView({+ project,+ doc,+ jobs,+ decomposed,+ separateCost,+ onSeparate,+ onDismiss,+}: {+ project: LayerProject;+ doc: LayerDoc;+ jobs: LayerJob[];+ decomposed: boolean;+ separateCost: string;+ onSeparate: () => Promise<void>;+ onDismiss: (jobId: string) => void;+}) {const [preview, setPreview] = useState<string | null>(null);+ const [starting, setStarting] = useState(false);useEffect(() => {let url: string | null = null;let gone = false;@@ -31,6 +54,10 @@ export function MobileView({ project, doc, jobs }: { project: LayerProject; doc:};}, [doc]);const rows = [...doc.nodes].sort((a, b) => b.z - a.z);+ const job = latestJob(jobs, ["decompose"]);+ const pending = job?.state === "pending" ? job : undefined;+ const running = pending && !isFailed(pending) ? pending : undefined;+ const failed = pending && isFailed(pending) ? pending : undefined;return (<div className="flex min-h-svh min-w-0 flex-col">@@ -45,15 +72,81 @@ export function MobileView({ project, doc, jobs }: { project: LayerProject; doc:<DownloadMenu doc={doc} name={project.name} jobs={jobs} compact /></header><main className="mx-auto w-full max-w-xl flex-1 space-y-5 px-4 pb-12">- <div className="flex items-start gap-3 rounded-xl border bg-card p-3">- <span className="grid size-9 shrink-0 place-items-center rounded-lg bg-brand-faint text-brand-text">- <MonitorSmartphone className="size-4" />- </span>- <div className="min-w-0">- <p className="text-[14px] font-medium">Layers works best on a larger screen</p>- <p className="text-[13px] text-pretty text-muted-foreground">Open this project on a computer to separate, move and edit layers. Here you can preview it and download the layers.</p>+ {!decomposed && !running && !failed ? (+ <div className="space-y-3 rounded-xl border bg-card p-4">+ <div className="flex items-start gap-3">+ <span className="grid size-9 shrink-0 place-items-center rounded-lg bg-brand-faint text-brand-text">+ <Layers className="size-4" />+ </span>+ <div className="min-w-0">+ <p className="text-[14px] font-medium">Separate this image into layers</p>+ <p className="text-[13px] text-pretty text-muted-foreground">One tap splits it into subject, background and details with the standard settings. Moving and editing the layers needs a larger screen.</p>+ </div>+ </div>+ <div className="flex items-center justify-between gap-2">+ <span className="font-mono text-[12px] text-muted-foreground">{separateCost}</span>+ <Button+ className="rounded-full"+ disabled={starting}+ onClick={async () => {+ setStarting(true);+ try {+ await onSeparate();+ } finally {+ setStarting(false);+ }+ }}+ >+ {starting ? <Loader2 className="animate-spin" /> : <Layers />} Separate layers+ </Button>+ </div></div>- </div>+ ) : running ? (+ <div className="space-y-2 rounded-xl border bg-card p-4 text-center" role="status" aria-live="polite">+ <Loader2 className="mx-auto size-5 animate-spin text-brand-text" />+ <p className="font-heading text-[19px]">{isRunning(running) ? DECOMPOSE_COPY.processing[0] : DECOMPOSE_COPY.ready[0]}</p>+ <p className="text-[12px] text-muted-foreground">{isRunning(running) ? jobStatusText(running.result) : "Laying the layers out…"}</p>+ {running.result?.progress ? <Progress value={running.result.progress * 100} className="h-1" aria-label="Progress" /> : null}+ </div>+ ) : failed ? (+ <div role="alert" className="space-y-2 rounded-xl border border-destructive/30 bg-destructive/5 p-4">+ <p className="flex items-center gap-1.5 text-[14px] font-medium text-destructive">+ <TriangleAlert className="size-4" /> {DECOMPOSE_COPY.failed[0]}+ </p>+ <p className="text-[13px] text-muted-foreground">{failed.result?.error ?? DECOMPOSE_COPY.failed[1]}</p>+ <div className="flex gap-2">+ <Button variant="outline" size="sm" className="rounded-full" onClick={() => onDismiss(failed.id)}>+ Dismiss+ </Button>+ <Button+ size="sm"+ className="rounded-full"+ disabled={starting}+ onClick={async () => {+ onDismiss(failed.id);+ setStarting(true);+ try {+ await onSeparate();+ } finally {+ setStarting(false);+ }+ }}+ >+ Try again+ </Button>+ </div>+ </div>+ ) : (+ <div className="flex items-start gap-3 rounded-xl border bg-card p-3">+ <span className="grid size-9 shrink-0 place-items-center rounded-lg bg-brand-faint text-brand-text">+ <MonitorSmartphone className="size-4" />+ </span>+ <div className="min-w-0">+ <p className="text-[14px] font-medium">Layers works best on a larger screen</p>+ <p className="text-[13px] text-pretty text-muted-foreground">Open this project on a computer to move and edit its layers. Here you can preview it and download the layers.</p>+ </div>+ </div>+ )}<div className="checkerboard overflow-hidden rounded-xl border" style={{ aspectRatio: `${doc.width} / ${doc.height}` }}>{/* eslint-disable-next-line @next/next/no-img-element */}{preview ? <img src={preview} alt={`${project.name}, all visible layers`} className="size-full object-contain" /> : <Skeleton className="size-full rounded-none" />}diff --git a/src/components/layers/projects-view.tsx b/src/components/layers/projects-view.tsxindex f756d06b..4638ae63 100644--- a/src/components/layers/projects-view.tsx+++ b/src/components/layers/projects-view.tsx@@ -3,7 +3,7 @@import { ChevronLeft, ChevronRight, ExternalLink, ImagePlus, Layers, Library, Loader2, MonitorSmartphone, MoreHorizontal, Pencil, RotateCcw, Sun, Trash2, Type, Upload, Wand2, Sparkles } from "lucide-react";import Link from "next/link";import { useRouter, useSearchParams } from "next/navigation";-import { Suspense, useEffect, useRef, useState } from "react";+import { Suspense, useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";import { toast } from "sonner";import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";import { Button } from "@/components/ui/button";@@ -32,39 +32,65 @@ const CAPABILITIES = [const IMAGE_TYPES = "image/png,image/jpeg,image/webp";-/** Upload or pick an image, read its size, create the project and open it. */-function useOpenImage() {+/**+ * Upload or pick an image, read its size, create the project and open it. The page stays alive in+ * the background once you're in the editor (Next keeps recent pages in an <Activity>), so the+ * “Preparing your project” cover is lifted as the page hides: coming back finds it usable.+ */+function useOpenImage(onLeft?: () => void) {const router = useRouter();const { create } = useLayerActions();const [busy, setBusy] = useState<string | null>(null);- const open = async (source: string, opts: { name?: string; generationId?: string; label?: string } = {}) => {- setBusy(opts.label ?? "Preparing your project");- try {- const img = await loadImage(source).catch(() => {- throw new Error("This image cannot be decomposed — Layer decomposition needs a generated or uploaded image.");- });- const [width, height] = sizeOf(img);- const v = await create({ source, width, height, name: opts.name, generationId: opts.generationId });- router.replace(`/layers/${v.project.id}`);- } catch (e) {- toast.error((e as Error).message || "Couldn't open the editor for this image. Please try again.");+ // Set right before opening the editor; the page hiding then resets (not React's strict-mode re-mount).+ const leaving = useRef(false);+ const left = useRef(onLeft);+ useLayoutEffect(() => {+ left.current = onLeft;+ });+ useLayoutEffect(+ () => () => {+ if (!leaving.current) return;+ leaving.current = false;setBusy(null);- }- };- const openFile = async (file: File) => {- if (!/^image\/(png|jpeg|webp)$/.test(file.type)) {- toast.error("Only images can be edited here. Pick an image or upload one.");- return;- }- setBusy("Uploading…");- try {- const asset = await uploadFile(file);- await open(asset.url, { name: file.name.replace(/\.[^.]+$/, "").slice(0, 80) });- } catch (e) {- toast.error((e as Error).message);- setBusy(null);- }- };+ left.current?.();+ },+ [],+ );+ const open = useCallback(+ async (source: string, opts: { name?: string; generationId?: string; label?: string } = {}) => {+ setBusy(opts.label ?? "Preparing your project");+ try {+ const img = await loadImage(source).catch(() => {+ throw new Error("This image cannot be decomposed — Layer decomposition needs a generated or uploaded image.");+ });+ const [width, height] = sizeOf(img);+ const v = await create({ source, width, height, name: opts.name, generationId: opts.generationId });+ leaving.current = true;+ router.replace(`/layers/${v.project.id}`);+ } catch (e) {+ toast.error((e as Error).message || "Couldn't open the editor for this image. Please try again.");+ setBusy(null);+ }+ },+ [create, router],+ );+ const openFile = useCallback(+ async (file: File) => {+ if (!/^image\/(png|jpeg|webp)$/.test(file.type)) {+ toast.error("Only images can be edited here. Pick an image or upload one.");+ return;+ }+ setBusy("Uploading…");+ try {+ const asset = await uploadFile(file);+ await open(asset.url, { name: file.name.replace(/\.[^.]+$/, "").slice(0, 80) });+ } catch (e) {+ toast.error((e as Error).message);+ setBusy(null);+ }+ },+ [open],+ );return { busy, open, openFile };}@@ -78,18 +104,18 @@ function ProjectCard({ p, onRename, onDelete }: { p: LayerProject; onRename: (){p.status !== "ready" && (<spanclassName={cn(- "absolute top-2 left-2 inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[12px] font-medium backdrop-blur",- p.status === "processing" ? "bg-background/85 text-foreground" : "bg-destructive/90 text-white",+ "absolute top-2 left-2 inline-flex max-w-[calc(100%-1rem)] items-center gap-1.5 rounded-full px-2.5 py-1 text-[12px] font-medium backdrop-blur",+ p.status === "processing" ? "bg-background/85 text-foreground" : p.status === "unopened" ? "bg-background/90 text-brand-text" : "bg-destructive/90 text-white",)}>- {p.status === "processing" ? <Loader2 className="size-3 animate-spin" /> : null}- {p.status === "processing" ? "Processing…" : "Couldn't be processed"}+ {p.status === "processing" ? <Loader2 className="size-3 shrink-0 animate-spin" /> : p.status === "unopened" ? <Layers className="size-3 shrink-0" /> : null}+ <span className="truncate">{p.status === "processing" ? "Processing…" : p.status === "unopened" ? "Layers ready — open to see them" : "Couldn't be processed"}</span></span>)}</div><h3 className="mt-2 truncate pr-9 text-[14px] font-medium">{p.name}</h3><p className="text-[12px] text-muted-foreground">- {timeAgo(p.updatedAt)} · {p.layers} layer{p.layers === 1 ? "" : "s"}+ {timeAgo(p.updatedAt)} · {p.status === "unopened" && p.pendingLayers ? `${p.pendingLayers} layers ready` : `${p.layers} layer${p.layers === 1 ? "" : "s"}`}</p></Link><DropdownMenu>@@ -129,12 +155,13 @@ function Capabilities() {<Button variant="ghost" size="icon-sm" className="rounded-full" aria-label="Previous capability" onClick={() => setAt((at + CAPABILITIES.length - 1) % CAPABILITIES.length)}><ChevronLeft /></Button>- <div className="scrollbar-none flex min-w-0 gap-1.5 overflow-x-auto" role="tablist" aria-label="What Layers can do">+ <div className="scrollbar-none flex min-w-0 gap-1.5 overflow-x-auto" role="group" aria-label="What Layers can do">{CAPABILITIES.map((x, i) => (<buttonkey={x.label}- role="tab"- aria-selected={i === at}+ type="button"+ aria-pressed={i === at}+ aria-controls="layers-capability"onClick={() => setAt(i)}className={cn("inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium transition-colors",@@ -149,7 +176,7 @@ function Capabilities() {<ChevronRight /></Button></div>- <p className="mt-2 text-center text-[13px] text-muted-foreground" aria-live="polite">+ <p id="layers-capability" className="mt-2 text-center text-[13px] text-muted-foreground" aria-live="polite">{c.text}</p></div>@@ -160,7 +187,11 @@ function ProjectsInner() {const params = useSearchParams();const projects = useLayerProjects();const { rename, remove } = useLayerActions();- const { busy, open, openFile } = useOpenImage();+ const { bfcacheId } = useRouter();+ const started = useRef<string | null>(null);+ const { busy, open, openFile } = useOpenImage(() => {+ started.current = null;+ });const file = useRef<HTMLInputElement>(null);const hydrated = useHydrated();const [picking, setPicking] = useState(false);@@ -169,18 +200,21 @@ function ProjectsInner() {const [deleting, setDeleting] = useState<LayerProject | null>(null);const [dragging, setDragging] = useState(false);- // Deep link: /layers?image=<url>[&generation=<id>&name=…] opens that image as a project.+ // Deep link: /layers?image=<url>[&generation=<id>&name=…] opens that image as a project. Each+ // link opens once per visit (the guard holds the navigation and link it handled, and is+ // forgotten once the editor opens), so every “Open in Layers”, of the same image or another,+ // opens a new project, and React's strict-mode re-mount doesn't open a second one.const deep = params.get("image");- const started = useRef(false);+ const link = deep ? `${bfcacheId}|${params.toString()}` : null;useEffect(() => {- if (!deep || started.current) return;- started.current = true;+ if (!deep || !link || started.current === link) return;+ started.current = link;if (!deep.startsWith("/api/files/")) {toast.error("Only images from your library can be edited here. Pick an image or upload one.");return;}void open(deep, { generationId: params.get("generation") ?? undefined, name: params.get("name") ?? undefined });- }, [deep, params, open]);+ }, [deep, link, params, open]);const items = projects.data ?? [];diff --git a/src/components/layers/render.ts b/src/components/layers/render.tsindex d645377f..52e21485 100644--- a/src/components/layers/render.ts+++ b/src/components/layers/render.ts@@ -5,8 +5,21 @@* pictures handed to models all go through drawNode, so what you download is what you see.*/-import { uploadFile } from "@/lib/api";-import { bboxFromAlpha, cropRect, nativeSize, slugify, sourceRect, storedZip, zipPlan, type Box, type LayerDoc, type LayerNode } from "@/lib/layers";+import {+ bboxFromAlpha,+ cropRect,+ exportScale,+ layerExportScale,+ nativeSize,+ slugify,+ sourceBoxOf,+ sourceRect,+ storedZip,+ zipPlan,+ type Box,+ type LayerDoc,+ type LayerNode,+} from "@/lib/layers";// ---------------------------------------------------------------------------// Images@@ -112,7 +125,8 @@ export function layerCanvas(node: LayerNode, w: number, h: number, src: Sourcesconst maskOverride = src.masks?.get(node.id);const mask = maskOverride ?? (node.maskSrc ? readyImage(node.maskSrc, onLoad) : undefined);if (node.maskSrc && !maskOverride && !mask) return null;- const key = cache && !preview ? `${node.src}|${node.crop?.join(",")}|${node.maskSrc}|${maskOverride ? src.maskVersion : ""}|${node.feather ?? 0}|${w}x${h}` : "";+ // Large copies (exports) aren't kept: the cache holds stage-sized ones.+ const key = cache && !preview && w * h <= 2048 * 2048 ? `${node.src}|${node.crop?.join(",")}|${node.maskSrc}|${maskOverride ? src.maskVersion : ""}|${node.feather ?? 0}|${w}x${h}` : "";const hit = key ? softCache.get(key) : undefined;if (hit) return hit;const c = document.createElement("canvas");@@ -139,10 +153,10 @@ export function layerCanvas(node: LayerNode, w: number, h: number, src: Sources/*** Draw a layer in document coordinates (the context's transform maps document px to the target).- * `pxPerDoc` is how many target pixels one document pixel covers (sizes the offscreen copy). Returns- * false while an image is still loading.+ * `pxPerDoc` is how many target pixels one document pixel covers (sizes the offscreen copy of a+ * masked or feathered layer, at most `softMax` px). Returns false while an image is still loading.*/-export function drawNode(ctx: CanvasRenderingContext2D, node: LayerNode, pxPerDoc: number, src: Sources = {}, onLoad?: () => void): boolean {+export function drawNode(ctx: CanvasRenderingContext2D, node: LayerNode, pxPerDoc: number, src: Sources = {}, onLoad?: () => void, softMax = 2048): boolean {const soft = !!(node.maskSrc || node.feather || src.masks?.has(node.id) || src.previews?.has(node.id));ctx.save();ctx.globalAlpha = node.opacity ?? 1;@@ -151,7 +165,7 @@ export function drawNode(ctx: CanvasRenderingContext2D, node: LayerNode, pxPerDolet ok = true;if (soft) {// Offscreen at the size it's shown, capped (a 4K layer on a small stage doesn't need 4K pixels).- const k = Math.min(1, 2048 / Math.max(node.w * pxPerDoc, node.h * pxPerDoc));+ const k = Math.min(1, softMax / Math.max(node.w * pxPerDoc, node.h * pxPerDoc));const c = layerCanvas(node, Math.ceil(node.w * pxPerDoc * k), Math.ceil(node.h * pxPerDoc * k), src, onLoad);if (c) ctx.drawImage(c, -node.w / 2, -node.h / 2, node.w, node.h);else ok = false;@@ -190,7 +204,31 @@ export async function renderDoc(doc: LayerDoc, opts: { rect?: Box; scale?: numbe}ctx.scale(scale, scale);ctx.translate(-rect[0], -rect[1]);- for (const n of nodes) drawNode(ctx, n, scale, opts.src);+ ctx.imageSmoothingQuality = "high";+ // Masked layers keep their detail in large exports (the stage caps them at 2048 px).+ for (const n of nodes) drawNode(ctx, n, scale, opts.src, undefined, 8192);+ return c;+}++/**+ * The image the project was opened on, where it sits in the document now (Expand & Crop moves it),+ * on a transparent canvas the document's size: Compare's “before”, lined up with the “after”.+ */+export async function renderSource(doc: LayerDoc, scale = 1): Promise<HTMLCanvasElement> {+ const img = await loadImage(doc.source);+ const [x, y, w, h] = sourceBoxOf(doc);+ const c = document.createElement("canvas");+ c.width = Math.max(1, Math.round(doc.width * scale));+ c.height = Math.max(1, Math.round(doc.height * scale));+ const ctx = c.getContext("2d")!;+ // Canvas the original didn't have (an expanded margin) reads as empty: a checkerboard.+ const cell = 12;+ ctx.fillStyle = "#e7e7e7";+ ctx.fillRect(0, 0, c.width, c.height);+ ctx.fillStyle = "#f7f7f7";+ for (let cy = 0; cy < c.height; cy += cell) for (let cx = (cy / cell) % 2 ? cell : 0; cx < c.width; cx += cell * 2) ctx.fillRect(cx, cy, cell, cell);+ ctx.imageSmoothingQuality = "high";+ ctx.drawImage(img, x * scale, y * scale, w * scale, h * scale);return c;}@@ -205,11 +243,22 @@ export function toBlob(c: HTMLCanvasElement, type = "image/png", quality?: numbereturn new Promise((resolve, reject) => c.toBlob((b) => (b ? resolve(b) : reject(new Error("Couldn't render the image"))), type, quality));}-/** Upload a render as a PNG and return its /api/files URL. */+/**+ * Store a render as a PNG and return its /api/files URL. Saved as a derived file: it stays out of+ * the Library's Uploads (the project that uses it keeps it).+ */export async function uploadRender(c: HTMLCanvasElement, name: string): Promise<string> {- const blob = await toBlob(c);- const asset = await uploadFile(new File([blob], `${slugify(name) || "layer"}.png`, { type: "image/png" }));- return asset.url;+ return uploadDerived(await toBlob(c), name);+}++/** Store a PNG the editor made (a render, a mask) as a derived file. */+export async function uploadDerived(blob: Blob, name: string): Promise<string> {+ const form = new FormData();+ form.append("file", new File([blob], `${slugify(name) || "layer"}.png`, { type: "image/png" }));+ const res = await fetch("/api/layers/renders", { method: "POST", body: form });+ const body = (await res.json().catch(() => ({}))) as { url?: string; error?: string };+ if (!res.ok || !body.url) throw new Error(body.error ?? "Couldn't save the picture for the model. Please try again.");+ return body.url;}/** The alpha box of an image in its own pixels (measured on a copy at most 1024 px wide). */@@ -283,33 +332,44 @@ function save(blob: Blob, name: string) {const bytes = async (c: HTMLCanvasElement) => new Uint8Array(await (await toBlob(c)).arrayBuffer());/**- * cropped-layers.zip (each layer alone, cut to its rotation-aware box) or positioned-layers.zip- * (each layer alone on a transparent canvas the size of the document), both with composite.png.+ * Export size: "full" keeps every layer's detail (an upscaled layer makes the export bigger, see+ * exportScale), "document" renders at the document's own pixels.+ */+export type ExportSize = "full" | "document";++const docScale = (doc: LayerDoc, size: ExportSize) => (size === "full" ? exportScale(doc) : 1);++/**+ * cropped-layers.zip (each layer alone, cut to its rotation-aware box, at its own detail) or+ * positioned-layers.zip (each layer alone on a transparent canvas the size of the export), both with+ * composite.png.*/-export async function downloadZip(doc: LayerDoc, kind: "cropped" | "positioned"): Promise<number> {+export async function downloadZip(doc: LayerDoc, kind: "cropped" | "positioned", size: ExportSize = "full"): Promise<number> {if (!doc.nodes.length) throw new Error("No layers to download");const byId = new Map(doc.nodes.map((n) => [n.id, n]));const files: { name: string; data: Uint8Array }[] = [];+ const scale = docScale(doc, size);for (const { nodeId, file } of zipPlan(doc)) {const n = byId.get(nodeId)!;const rect = kind === "cropped" ? cropRect(n, doc) : ([0, 0, doc.width, doc.height] as Box);if (!rect) continue; // entirely off the canvas- files.push({ name: file, data: await bytes(await renderDoc(doc, { rect, only: n.id })) });+ const s = kind === "cropped" && size === "full" ? layerExportScale(n, rect) : scale;+ files.push({ name: file, data: await bytes(await renderDoc(doc, { rect, only: n.id, scale: s })) });}- files.push({ name: "composite.png", data: await bytes(await renderDoc(doc)) });+ files.push({ name: "composite.png", data: await bytes(await renderDoc(doc, { scale })) });save(new Blob([storedZip(files) as BlobPart], { type: "application/zip" }), kind === "cropped" ? "cropped-layers.zip" : "positioned-layers.zip");return files.length - 1;}-export async function downloadPng(doc: LayerDoc, name: string): Promise<void> {- save(await toBlob(await renderDoc(doc)), `${slugify(name) || "image"}.png`);+export async function downloadPng(doc: LayerDoc, name: string, size: ExportSize = "full"): Promise<void> {+ save(await toBlob(await renderDoc(doc, { scale: docScale(doc, size) })), `${slugify(name) || "image"}.png`);}-/** One layer as you see it (cropped to its box). */+/** One layer as you see it (cropped to its box), at its own detail. */export async function downloadLayer(doc: LayerDoc, node: LayerNode): Promise<void> {const rect = cropRect(node, doc);if (!rect) throw new Error("This layer is outside the canvas");- save(await toBlob(await renderDoc(doc, { rect, only: node.id })), zipPlan(doc).find((e) => e.nodeId === node.id)?.file ?? "layer.png");+ save(await toBlob(await renderDoc(doc, { rect, only: node.id, scale: layerExportScale(node, rect) })), zipPlan(doc).find((e) => e.nodeId === node.id)?.file ?? "layer.png");}/** "16:9" for 1920×1080; a decimal ratio ("1.37:1") when the numbers don't reduce. */diff --git a/src/components/layers/stage.tsx b/src/components/layers/stage.tsxindex 38541e1e..955b2f4d 100644--- a/src/components/layers/stage.tsx+++ b/src/components/layers/stage.tsx@@ -7,7 +7,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltipimport { Kbd } from "@/components/ui/kbd";import { resizeBox, rotationTo, toLocal, type Box, type Handle, type LayerDoc, type LayerNode } from "@/lib/layers";import { cn } from "@/lib/utils";-import type { MaskEdit, StageMode } from "./editor-context";+import { keysBelongElsewhere, type MaskEdit, type StageMode } from "./editor-context";import { drawNode, opaqueAt, type Sources } from "./render";interface View {@@ -29,7 +29,6 @@ const HANDLES: Handle[] = ["nw", "n", "ne", "e", "se", "s", "sw", "w"];const HANDLE_POS: Record<Handle, [number, number]> = { nw: [0, 0], n: [0.5, 0], ne: [1, 0], e: [1, 0.5], se: [1, 1], s: [0.5, 1], sw: [0, 1], w: [0, 0.5] };const HANDLE_CURSOR: Record<Handle, string> = { nw: "nwse-resize", se: "nwse-resize", ne: "nesw-resize", sw: "nesw-resize", n: "ns-resize", s: "ns-resize", e: "ew-resize", w: "ew-resize" };-const typing = (t: EventTarget | null) => t instanceof HTMLElement && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName));export interface StageProps {doc: LayerDoc;@@ -172,7 +171,7 @@ export function Stage(p: StageProps) {}, [fit]);useEffect(() => {const down = (e: KeyboardEvent) => {- if (typing(e.target) || e.metaKey || e.ctrlKey || e.altKey) return;+ if (keysBelongElsewhere(e) || e.metaKey || e.ctrlKey || e.altKey) return;// Space presses a focused button; it pans only from the canvas or the page.if (e.code === "Space" && !e.repeat && !(e.target instanceof HTMLElement && e.target.closest("button, a, [role]"))) {setSpace(true);diff --git a/src/components/layers/tools.tsx b/src/components/layers/tools.tsxindex 2c418592..8c83b8fb 100644--- a/src/components/layers/tools.tsx+++ b/src/components/layers/tools.tsx@@ -37,10 +37,13 @@ import {clampLayers,DECOMPOSE_COPY,decomposeCost,+ defaultLayers,expandPads,getNode,jobStatusText,LAYER_PRICES,+ layersModelFor,+ minLayers,reframeDoc,RELIGHT_DIRECTIONS,RELIGHT_LIGHTS,@@ -57,6 +60,7 @@ import {type LayerTool,type TextBlock,} from "@/lib/layers";+import { radioKeys, radioTab } from "@/components/studio/radio-keys";import { cn } from "@/lib/utils";import { Field, Segmented } from "./bits";import { costLabel, isFailed, isRunning, latestJob, modelsFor, useEditor, type Target, type ToolId } from "./editor-context";@@ -125,15 +129,18 @@ function ModelSelect({ tool, value, onChange }: { tool: LayerTool; value?: strin);}-/** The model the tool will run (picked, or the engine's default). */+/** The model the tool will run (picked, or the engine's default); `picked` is what the user chose, if anything. */function useToolModel(tool: LayerTool) {const { engine, models } = useEditor();const [picked, setPicked] = useState<string | undefined>();const options = TOOL_MODELS[tool][engine];- const id = picked && options.includes(picked) ? picked : options[0];- return { modelId: id, model: id ? models[id] : undefined, setModelId: setPicked };+ const chosen = picked && options.includes(picked) ? picked : undefined;+ const id = chosen ?? options[0];+ return { modelId: id, model: id ? models[id] : undefined, setModelId: setPicked, picked: chosen };}+type ToolModel = ReturnType<typeof useToolModel>;+/** A running or failed job of this tool on this target. */function JobState({ job, onRetry, failedTitle = "That didn't work" }: { job?: LayerJob; onRetry?: () => void; failedTitle?: string }) {const { endJob } = useEditor();@@ -233,15 +240,21 @@ function useRun() {// Layer Decomposition (and Separate layer)function DecomposeTool() {- const { doc, engine, isDemo, jobs, splitTarget, setSplitTarget, selected, endJob } = useEditor();+ const { doc, engine, models, isDemo, jobs, splitTarget, setSplitTarget, selected, endJob, decomposed } = useEditor();// Separate layer: picked from a layer's menu, or with the button below once the image is decomposed.const splitNode = getNode(doc, splitTarget);- const tool: LayerTool = splitNode ? "split" : "decompose";- const { modelId, model, setModelId } = useToolModel(tool);+ const tool = splitNode ? "split" : "decompose";+ const picker = useToolModel(tool);const [resolution, setResolution] = useState<"1K" | "1.5K" | "2K">("1K");const [mode, setMode] = useState<"standard" | "fast">("standard");- const [layers, setLayers] = useState(8);+ /** The slider's value once moved (until then each model's own default). */+ const [layers, setLayers] = useState<number | null>(null);const [prompt, setPrompt] = useState("");+ const asked = splitNode ? prompt.trim() : "";+ // On the open engine a named element runs on Layered-Control, and only there.+ const auto = tool === "split" && engine === "open";+ const modelId = layersModelFor(tool, engine, picker.modelId, asked) ?? picker.modelId;+ const model = modelId ? models[modelId] : undefined;const { busy, go } = useRun();const [phase, setPhase] = useState<"setting-up" | "submitting" | null>(null);const job = splitNode ? latestJob(jobs, ["split"], splitNode.id) : latestJob(jobs, ["decompose"]);@@ -253,7 +266,8 @@ function DecomposeTool() {}, [job]);const max = LAYER_PRICES[modelId ?? ""]?.maxLayers ?? 10;- const n = clampLayers(modelId ?? "", Math.min(layers, max));+ const min = minLayers(modelId ?? "");+ const n = clampLayers(modelId ?? "", Math.min(layers ?? defaultLayers(tool, modelId), max));const hasRes = !!modelId && (modelId.startsWith("seedream") || modelId.startsWith("oss-"));const hasMode = modelId === "seedream-5-layers" || !!modelId?.startsWith("oss-");const usd = decomposeCost(modelId ?? "", n, resolution);@@ -266,8 +280,9 @@ function DecomposeTool() {await go({tool,target,- modelId,- prompt: prompt.trim() || undefined,+ // The model that runs, as the form shows it (a model picked by hand, Layered-Control for a named element).+ ...(picker.picked || modelId !== picker.modelId ? { modelId } : {}),+ prompt: asked || undefined,settings: { resolution, mode, layers: n },label: splitNode ? `Separating ${splitNode.name}` : "Layer decomposition",});@@ -284,7 +299,7 @@ function DecomposeTool() {: isFailed(job)? "failed": "ready"- : !splitNode && doc.decomposed+ : !splitNode && decomposed? "decomposed": null;@@ -324,7 +339,7 @@ function DecomposeTool() {);}- if (!splitNode && doc.decomposed) {+ if (!splitNode && decomposed) {const [title, body] = DECOMPOSE_COPY.decomposed;return (<div className="space-y-3">@@ -360,12 +375,18 @@ function DecomposeTool() {<Field label="What to pull out (optional)" htmlFor="split-prompt"><Input id="split-prompt" value={prompt} onChange={(e) => setPrompt(e.target.value)} maxLength={200} placeholder="e.g. “the guitar”" className="h-9" /></Field>- {engine === "open" && prompt.trim() && <p className="text-[11px] text-muted-foreground">A named element runs on Qwen-Image-Layered Control.</p>}</div>) : (<p className="text-[12px] text-pretty text-muted-foreground">Break the image into clean, editable layers — subject, background and details. An image can only be decomposed once; you can separate any layer again later.</p>)}- <ModelSelect tool={tool} value={modelId} onChange={setModelId} />+ {auto ? (+ <div className="space-y-0.5">+ <p className="text-[12px] text-muted-foreground">Model · {model?.name ?? modelId}</p>+ <p className="text-[11px] text-subtle-foreground">{asked ? "A named element runs on Qwen-Image-Layered Control." : "Name an element to pull it out with Qwen-Image-Layered Control."}</p>+ </div>+ ) : (+ <ModelSelect tool={tool} value={modelId} onChange={picker.setModelId} />+ )}{hasRes && (<Field label="Resolution"><Segmented@@ -394,7 +415,7 @@ function DecomposeTool() {</Field>)}<Field label="Layers" hint={modelId?.startsWith("seedream") ? `up to ${n}` : n}>- <Slider aria-label="Layers" min={modelId === "oss-qwen-layered-control" ? 2 : 3} max={Math.max(3, max)} step={1} value={[n]} onValueChange={([v]) => setLayers(v)} />+ <Slider aria-label="Layers" min={min} max={Math.max(min, max)} step={1} value={[n]} onValueChange={([v]) => setLayers(v)} /></Field>{modelId?.startsWith("seedream") && <p className="text-[11px] text-subtle-foreground">Seedream decides the final count (up to 16) and names each layer.</p>}{!model && <p className="text-[12px] text-muted-foreground">No {engine === "open" ? "open-source" : "cloud"} model can split layers yet.</p>}@@ -542,10 +563,30 @@ function EditTextTool() {// ---------------------------------------------------------------------------// Remove background, Upscale, Relight, Angles-function SimpleTool({ tool, verb, failedTitle, children, settings, prompt, disabled }: { tool: LayerTool; verb: string; failedTitle: string; children?: React.ReactNode; settings?: LayerJobInput["settings"]; prompt?: string; disabled?: boolean }) {+function SimpleTool({+ tool,+ verb,+ failedTitle,+ children,+ settings,+ prompt,+ disabled,+ picker,+}: {+ tool: LayerTool;+ verb: string;+ failedTitle: string;+ children?: React.ReactNode;+ settings?: LayerJobInput["settings"];+ prompt?: string;+ disabled?: boolean;+ /** The model state, when the form above depends on the model (Angles). */+ picker?: ToolModel;+}) {const { jobs, isDemo } = useEditor();const { target, node } = useTarget();- const { modelId, model, setModelId } = useToolModel(tool);+ const own = useToolModel(tool);+ const { modelId, model, setModelId } = picker ?? own;const { busy, go } = useRun();const job = latestJob(jobs, [tool], node?.id ?? null);const run = () => void go({ tool, target, modelId, prompt, settings, label: verb });@@ -571,22 +612,10 @@ function RelightTool() {return (<SimpleTool tool="relight" verb="Relight" failedTitle="Couldn't relight it" settings={{ light, direction, keepAlpha: !!selected && keepAlpha }} prompt={extra.trim() || undefined}><Field label="Lighting">- <div className="flex flex-wrap gap-1.5" role="radiogroup" aria-label="Lighting">- {RELIGHT_LIGHTS.map(([l]) => (- <Chip key={l} active={light === l} onClick={() => setLight(l)}>- {l}- </Chip>- ))}- </div>+ <Chips label="Lighting" value={light} options={RELIGHT_LIGHTS.map(([l]) => l)} onChange={setLight} /></Field><Field label="Direction">- <div className="flex flex-wrap gap-1.5" role="radiogroup" aria-label="Direction">- {RELIGHT_DIRECTIONS.map(([d]) => (- <Chip key={d} active={direction === d} onClick={() => setDirection(d)}>- {d}- </Chip>- ))}- </div>+ <Chips label="Direction" value={direction} options={RELIGHT_DIRECTIONS.map(([d]) => d)} onChange={setDirection} /></Field><Field label="Anything else (optional)" htmlFor="relight-extra"><Input id="relight-extra" value={extra} onChange={(e) => setExtra(e.target.value)} maxLength={300} placeholder="e.g. “a soft blue fill from the right”" className="h-9" />@@ -597,16 +626,18 @@ function RelightTool() {}function AnglesTool() {- const { selected, engine } = useEditor();- const { modelId } = useToolModel("angles");+ const { selected } = useEditor();+ // One model state for the form and its Model select: Qwen Multiple Angles takes sliders, the others a camera.+ const picker = useToolModel("angles");const [rotate, setRotate] = useState(45);const [tilt, setTilt] = useState(0);const [zoom, setZoom] = useState(5);const [angle, setAngle] = useState(ANGLES[0][0]);const [keepAlpha, setKeepAlpha] = useState(!!selected && selected.z > 0);- const sliders = modelId === "qwen-multiple-angles" && engine === "cloud";+ const sliders = picker.modelId === "qwen-multiple-angles";+ const keep = !!selected && keepAlpha;return (- <SimpleTool tool="angles" verb="New angle" failedTitle="Couldn't make the new angle" settings={{ rotate, tilt, zoom, angle, keepAlpha: !!selected && keepAlpha }}>+ <SimpleTool tool="angles" verb="New angle" failedTitle="Couldn't make the new angle" picker={picker} settings={sliders ? { rotate, tilt, zoom, keepAlpha: keep } : { angle, keepAlpha: keep }}>{sliders ? (<><Field label="Rotate" hint={`${rotate}°`}>@@ -621,13 +652,7 @@ function AnglesTool() {</>) : (<Field label="Camera">- <div className="flex flex-wrap gap-1.5" role="radiogroup" aria-label="Camera angle">- {ANGLES.map(([a]) => (- <Chip key={a} active={angle === a} onClick={() => setAngle(a)}>- {a}- </Chip>- ))}- </div>+ <Chips label="Camera angle" value={angle} options={ANGLES.map(([a]) => a)} onChange={setAngle} /></Field>)}<KeepAlpha node={selected} value={keepAlpha} onChange={setKeepAlpha} />@@ -635,20 +660,26 @@ function AnglesTool() {);}-function Chip({ active, onClick, children }: { active: boolean; onClick: () => void; children: React.ReactNode }) {+const chipClass = (active: boolean) =>+ cn(+ "inline-flex h-7 items-center rounded-full px-2.5 text-[12px] font-medium transition-colors outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50",+ active ? "bg-brand-faint text-brand-text hover:bg-brand-faint-hover" : "bg-secondary text-secondary-foreground hover:bg-accent",+ );++/**+ * A row of chips to pick one of (a radio group): one Tab stop, the arrow keys move the pick. With+ * nothing picked yet, the first chip takes the Tab stop.+ */+function Chips<T extends string>({ label, value, options, onChange, names }: { label: string; value: T | null; options: readonly T[]; onChange: (v: T) => void; names?: (v: T) => string }) {+ const stop = value !== null && options.includes(value) ? value : options[0];return (- <button- type="button"- role="radio"- aria-checked={active}- onClick={onClick}- className={cn(- "inline-flex h-7 items-center rounded-full px-2.5 text-[12px] font-medium transition-colors",- active ? "bg-brand-faint text-brand-text hover:bg-brand-faint-hover" : "bg-secondary text-secondary-foreground hover:bg-accent",- )}- >- {children}- </button>+ <div className="flex flex-wrap gap-1.5" role="radiogroup" aria-label={label} onKeyDown={radioKeys}>+ {options.map((o) => (+ <button key={o} type="button" role="radio" aria-checked={value === o} tabIndex={radioTab(o === stop)} onClick={() => onChange(o)} className={chipClass(value === o)}>+ {names ? names(o) : o}+ </button>+ ))}+ </div>);}@@ -790,8 +821,7 @@ function RegionalTool() {// ---------------------------------------------------------------------------// Expand & Crop-const FRAME_RATIOS: [string, number | null][] = [- ["Free", null],+const FRAME_RATIOS: [string, number][] = [["1:1", 1],["4:5", 4 / 5],["3:4", 3 / 4],@@ -863,12 +893,16 @@ function ExpandTool() {<div className="space-y-4"><p className="text-[12px] text-pretty text-muted-foreground">Drag the edges or corners. Crop keeps pixels on layers. Expand adds empty canvas, or turn on Fill with AI to generate it.</p><Field label="Shape">- <div className="flex flex-wrap gap-1.5" role="radiogroup" aria-label="Frame shape">- {FRAME_RATIOS.map(([label, r]) => (- <Chip key={label} active={r === null ? false : Math.abs(f[2] / f[3] - r) < 0.01} onClick={() => setFrame(r ? frameAround(doc.width, doc.height, r) : [0, 0, doc.width, doc.height])}>- {r === null ? "Reset" : label}- </Chip>- ))}+ <div className="flex flex-wrap items-center gap-1.5">+ <Chips+ label="Frame shape"+ value={FRAME_RATIOS.find(([, r]) => Math.abs(f[2] / f[3] - r) < 0.01)?.[0] ?? null}+ options={FRAME_RATIOS.map(([l]) => l)}+ onChange={(l) => setFrame(frameAround(doc.width, doc.height, FRAME_RATIOS.find(([x]) => x === l)![1]))}+ />+ <button type="button" className={chipClass(false)} onClick={() => setFrame([0, 0, doc.width, doc.height])} disabled={f[0] === 0 && f[1] === 0 && f[2] === doc.width && f[3] === doc.height}>+ Reset+ </button></div></Field><div className="grid grid-cols-2 gap-2 font-mono text-[12px] text-muted-foreground">@@ -979,20 +1013,17 @@ function GradeTool() {<div className="space-y-4"><Scope node={node} /><Field label="Looks">- <div className="flex flex-wrap gap-1.5" role="radiogroup" aria-label="Looks">- {PRESETS.map((p) => (- <Chip- key={p.id}- active={preset === p.id}- onClick={() => {- setPreset(p.id);- setGrade(applyPreset(p));- }}- >- {p.name}- </Chip>- ))}- </div>+ <Chips+ label="Looks"+ value={preset}+ options={PRESETS.map((p) => p.id)}+ names={(id) => PRESETS.find((p) => p.id === id)?.name ?? id}+ onChange={(id) => {+ const p = PRESETS.find((x) => x.id === id)!;+ setPreset(p.id);+ setGrade(applyPreset(p));+ }}+ /></Field>{groups.map((g) => (<fieldset key={g} className="space-y-2.5">@@ -1034,7 +1065,7 @@ export function ToolRail() {const running = jobs.filter(isRunning).length;return (// Below 1280 px the list folds to icons (tooltips name them) so the canvas keeps its room; a tool's form stays readable.- <aside className={cn("flex min-h-0 shrink-0 flex-col border-r bg-background", current ? "w-[256px] xl:w-[280px]" : "w-[60px] xl:w-[280px]")} aria-label="Tools">+ <aside className={cn("flex min-h-0 shrink-0 flex-col border-r bg-background", current ? "w-[240px] lg:w-[256px] xl:w-[280px]" : "w-[60px] xl:w-[280px]")} aria-label="Tools">{current ? (<><div className="flex h-12 shrink-0 items-center gap-1 px-2">@@ -1055,7 +1086,8 @@ export function ToolRail() {<div className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-contain"><div className="px-3 pt-1 pb-6">{tool === "decompose" && <DecomposeTool />}- {tool === "edit-text" && <EditTextTool />}+ {/* Its rows belong to one scope: picking another layer (or the whole image) starts afresh. */}+ {tool === "edit-text" && <EditTextTool key={selected?.id ?? "whole"} />}{tool === "remove-bg" && (<SimpleTool tool="bg-remove" verb="Remove background" failedTitle="Failed to load image. Please try again."><HowItWorks>Remove background finds the main subject of your image and cuts everything else away, giving you the subject on a transparent background.</HowItWorks>diff --git a/src/components/layers/top-bar.tsx b/src/components/layers/top-bar.tsxindex 0e910a89..db9332fa 100644--- a/src/components/layers/top-bar.tsx+++ b/src/components/layers/top-bar.tsx@@ -5,7 +5,16 @@ import Link from "next/link";import { useState } from "react";import { toast } from "sonner";import { Button } from "@/components/ui/button";-import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";import { Kbd } from "@/components/ui/kbd";import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";import { SidebarTrigger } from "@/components/ui/sidebar";@@ -13,16 +22,25 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltipimport { EngineSwitch } from "@/components/studio/engine-switch";import type { Engine } from "@/lib/catalog/types";import { timeAgo } from "@/lib/format";-import { docJson, type LayerDoc, type LayerJob, type LayerVersion } from "@/lib/layers";+import { docJson, exportScale, scaledSize, type LayerDoc, type LayerJob, type LayerVersion } from "@/lib/layers";import { cn } from "@/lib/utils";-import { downloadPng, downloadZip } from "./render";+import { downloadPng, downloadZip, type ExportSize } from "./render";export type SaveState = "saved" | "saving" | "dirty" | "error" | "conflict";-/** The download menu (shared with the phone view): the two zips and the flat PNG, built in the browser. */+/**+ * The download menu (shared with the phone view): the two zips and the flat PNG, built in the+ * browser. When a layer carries more detail than the document (an upscale), the export can keep it+ * (“Full detail”, the default) or stay at the document's size.+ */export function DownloadMenu({ doc, name, jobs, compact }: { doc: LayerDoc; name: string; jobs: LayerJob[]; compact?: boolean }) {const [busy, setBusy] = useState(false);+ const [size, setSize] = useState<ExportSize>("full");const splitting = jobs.some((j) => (j.tool === "decompose" || j.tool === "split") && j.state === "pending");+ const scale = exportScale(doc);+ const [dw, dh] = scaledSize(doc.width, doc.height, 1);+ const [fw, fh] = scaledSize(doc.width, doc.height, scale);+ const larger = fw > dw;const go = async (kind: "cropped" | "positioned" | "image") => {if (!doc.nodes.length) {toast.error("No layers to download");@@ -34,9 +52,10 @@ export function DownloadMenu({ doc, name, jobs, compact }: { doc: LayerDoc; name}setBusy(true);const t = toast.loading(kind === "image" ? "Rendering the image…" : "Packing the layers…");+ const at = larger ? size : "document";try {- if (kind === "image") await downloadPng(doc, name);- else await downloadZip(doc, kind);+ if (kind === "image") await downloadPng(doc, name, at);+ else await downloadZip(doc, kind, at);toast.success("Downloaded", { id: t, duration: 1500 });} catch (e) {toast.error((e as Error).message || "Couldn't download this version. Please try again.", { id: t });@@ -52,7 +71,7 @@ export function DownloadMenu({ doc, name, jobs, compact }: { doc: LayerDoc; name{!compact && <span className="hidden xl:inline">Download</span>}</Button></DropdownMenuTrigger>- <DropdownMenuContent align="end" className="w-56">+ <DropdownMenuContent align="end" className="w-60"><DropdownMenuItem onSelect={() => void go("cropped")}><FileArchive /> Cropped layers .zip</DropdownMenuItem>@@ -62,19 +81,61 @@ export function DownloadMenu({ doc, name, jobs, compact }: { doc: LayerDoc; name<DropdownMenuSeparator /><DropdownMenuItem onSelect={() => void go("image")}><ImageDown /> Image .png+ <span className="ml-auto font-mono text-[11px] text-muted-foreground">+ {larger && size === "full" ? fw : dw} × {larger && size === "full" ? fh : dh}+ </span></DropdownMenuItem>+ {larger && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuLabel className="text-[11px] font-medium text-muted-foreground">Size</DropdownMenuLabel>+ <DropdownMenuRadioGroup value={size} onValueChange={(v) => setSize(v as ExportSize)}>+ <DropdownMenuRadioItem value="full" onSelect={(e) => e.preventDefault()}>+ Full detail+ <span className="ml-auto font-mono text-[11px] text-muted-foreground">+ {fw} × {fh}+ </span>+ </DropdownMenuRadioItem>+ <DropdownMenuRadioItem value="document" onSelect={(e) => e.preventDefault()}>+ Canvas size+ <span className="ml-auto font-mono text-[11px] text-muted-foreground">+ {dw} × {dh}+ </span>+ </DropdownMenuRadioItem>+ </DropdownMenuRadioGroup>+ </>+ )}</DropdownMenuContent></DropdownMenu>);}-function SaveBadge({ state }: { state: SaveState }) {+/** The autosave state: an icon at every width, its words from 1280 px (and in its tooltip). A failed save can be retried now. */+function SaveBadge({ state, onRetry }: { state: SaveState; onRetry: () => void }) {const text = { saved: "Saved", saving: "Saving…", dirty: "Saving…", error: "Not saved — retrying", conflict: "Changed in another tab" }[state];+ const bad = state === "error" || state === "conflict";+ const body = (+ <>+ {state === "saved" ? <Check className="size-3.5 shrink-0" /> : bad ? <CloudOff className="size-3.5 shrink-0" /> : <Loader2 className="size-3.5 shrink-0 animate-spin" />}+ <span className="sr-only xl:not-sr-only">{text}</span>+ </>+ );+ const cls = cn("inline-flex h-7 shrink-0 items-center gap-1 rounded-md px-1 text-[12px] whitespace-nowrap", bad ? "text-warning" : "text-subtle-foreground");return (- <span className={cn("hidden items-center gap-1 text-[12px] whitespace-nowrap xl:inline-flex", state === "error" || state === "conflict" ? "text-warning" : "text-subtle-foreground")} role="status" aria-live="polite">- {state === "saved" ? <Check className="size-3.5" /> : state === "error" || state === "conflict" ? <CloudOff className="size-3.5" /> : <Loader2 className="size-3.5 animate-spin" />}- {text}- </span>+ <Tooltip>+ <TooltipTrigger asChild>+ {state === "error" ? (+ <button type="button" className={cn(cls, "hover:bg-accent")} onClick={onRetry} aria-label="Not saved. Retry now">+ {body}+ </button>+ ) : (+ <span className={cls} role="status" aria-live="polite">+ {body}+ </span>+ )}+ </TooltipTrigger>+ <TooltipContent>{state === "error" ? "Not saved yet — Fuobe keeps retrying. Click to retry now." : text}</TooltipContent>+ </Tooltip>);}@@ -82,6 +143,7 @@ export function TopBar(p: {name: string;onRename: (name: string) => void;save: SaveState;+ onRetrySave: () => void;canUndo: boolean;canRedo: boolean;onUndo: () => void;@@ -142,7 +204,7 @@ export function TopBar(p: {}}className="h-8 w-[clamp(6rem,16vw,16rem)] min-w-0 truncate rounded-md border border-transparent bg-transparent px-2 font-heading text-[19px] outline-none hover:border-border focus:border-primary focus:ring-4 focus:ring-brand-faint"/>- <SaveBadge state={p.save} />+ <SaveBadge state={p.save} onRetry={p.onRetrySave} /><div className="ml-auto flex items-center gap-1"><Tooltip>@@ -193,7 +255,14 @@ export function TopBar(p: {</div><Sheet open={historyOpen} onOpenChange={setHistoryOpen}>- <SheetContent className="w-[min(92vw,380px)]">+ <SheetContent+ className="w-[min(92vw,380px)]"+ // Focus the sheet itself, not its first Restore button (Enter mustn't restore a version by accident).+ onOpenAutoFocus={(e) => {+ e.preventDefault();+ (e.currentTarget as HTMLElement | null)?.focus();+ }}+ ><SheetHeader><SheetTitle>Edit history</SheetTitle><SheetDescription>Every tool result is saved as a version. Restoring one adds it on top — nothing is lost.</SheetDescription>diff --git a/src/lib/layers.ts b/src/lib/layers.tsindex 59f87c41..3d4a9707 100644--- a/src/lib/layers.ts+++ b/src/lib/layers.ts@@ -65,9 +65,23 @@ export interface LayerDoc {source: string;/** “An image can only be decomposed once”: set after the first decomposition lands. */decomposed: boolean;+ /** Where the source image sits in the document (doc px): Expand & Crop moves it. Unset = the whole canvas. */+ sourceBox?: Box;nodes: LayerNode[];}+/** Layers a project holds at most (the server refuses more). */+export const MAX_NODES = 200;+/** Revisions a layer keeps: its first one and the newest (the server refuses more than 60). */+export const MAX_REVISIONS = 50;++/** A document change that would go past {@link MAX_NODES}. */+export class LayerLimitError extends Error {+ constructor() {+ super(`A project can hold up to ${MAX_NODES} layers. Merge or delete some layers first.`);+ }+}+// ---------------------------------------------------------------------------// Projects, versions and jobs as the API returns them@@ -94,8 +108,15 @@ export interface LayerProject {height: number;/** Layers in the newest version. */layers: number;- /** "processing" while a decomposition runs, "failed" when the only one failed. */- status: "ready" | "processing" | "failed";+ /**+ * "processing" while a decomposition runs, "unopened" when it finished but the editor hasn't laid+ * the layers out yet (`pendingLayers` of them), "failed" when the only one failed.+ */+ status: "ready" | "processing" | "unopened" | "failed";+ /** Layers a finished decomposition holds, waiting for the editor to lay them out. */+ pendingLayers?: number;+ /** “An image can only be decomposed once”: true once a decomposition (or a split of the original picture) landed, whichever version is open. */+ decomposed: boolean;createdAt: number;updatedAt: number;}@@ -175,6 +196,22 @@ export interface LayerJobInput {};}+/** What each tool is called in job titles, toasts and the generations' step labels. */+export 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",+};+/** Models each tool offers, per engine (the first is the default). Checked against the catalog in tests. */export const TOOL_MODELS: Record<LayerTool, { cloud: string[]; open: string[] }> = {decompose: { cloud: ["seedream-5-layers", "seedream-5-flash-layers", "qwen-image-layered-cloud"], open: ["oss-qwen-layered"] },@@ -257,10 +294,35 @@ export function decomposeCost(modelId: string, layers: number, resolution: "1K"return Math.round(p.perLayer * n * (p.doubleAt2K && resolution === "2K" ? 2 : 1) * 1000) / 1000;}+/** Qwen-Image-Layered Control: pulls a named element out of a layer (it needs the name). */+export const LAYERED_CONTROL = "oss-qwen-layered-control";++/**+ * The model a decomposition or a split runs on. On the open engine a split with a named element+ * (a prompt) goes to Layered-Control and one without a name to plain Qwen-Image-Layered, whichever of+ * the two was asked for (the form says so). Elsewhere: the model asked for (unset = the default).+ */+export function layersModelFor(tool: "decompose" | "split", engine: "cloud" | "open", modelId: string | undefined, prompt: string | undefined): string | undefined {+ if (tool !== "split" || engine !== "open") return modelId;+ const plain = TOOL_MODELS.split.open[0];+ if (prompt?.trim()) return !modelId || modelId === plain ? LAYERED_CONTROL : modelId;+ return modelId === LAYERED_CONTROL ? plain : modelId;+}++/** The layer count a decomposition starts at: 8 for the image, 3 for a layer, 2 for a named element. */+export function defaultLayers(tool: "decompose" | "split", modelId: string | undefined): number {+ return modelId === LAYERED_CONTROL ? 2 : tool === "split" ? 3 : 8;+}++/** The fewest layers a model can be asked for (Layered-Control: the element and the rest). */+export function minLayers(modelId: string): number {+ return modelId === LAYERED_CONTROL ? 2 : 3;+}+/** The layer count a decomposition model can be asked for (Seedream picks its own, up to 16). */export function clampLayers(modelId: string, layers: number): number {const max = LAYER_PRICES[modelId]?.maxLayers ?? 10;- return Math.min(max, Math.max(modelId === "oss-qwen-layered-control" ? 2 : 3, Math.round(layers)));+ return Math.min(max, Math.max(minLayers(modelId), Math.round(layers)));}// ---------------------------------------------------------------------------@@ -429,6 +491,33 @@ export function nativeSize(node: Pick<LayerNode, "w" | "h" | "crop" | "natural">return [w, h];}+/** Exports stay at most this many pixels on their long side. */+export const EXPORT_MAX_PX = 8192;++/** Image pixels per document pixel a layer carries: 1 as placed, 4 after a 4× upscale. */+export function layerDensity(node: Pick<LayerNode, "w" | "crop" | "natural">): number {+ const src = sourceRect(node);+ return src && node.w > 0 && src[2] > 0 ? src[2] / node.w : 1;+}++/**+ * The scale an export renders at so no visible layer loses detail (an upscaled layer makes the+ * whole picture bigger): the densest layer's, never below 1, kept to `max` px on the long side.+ */+export function exportScale(doc: Pick<LayerDoc, "width" | "height" | "nodes">, max = EXPORT_MAX_PX): number {+ let d = 1;+ for (const n of doc.nodes) if (!n.hidden) d = Math.max(d, layerDensity(n));+ return Math.max(1, Math.min(d, max / Math.max(doc.width, doc.height)));+}++/** One layer's own scale for a cropped download (its density, ≥ 1, ≤ `max` px on the long side of `rect`). */+export function layerExportScale(node: Pick<LayerNode, "w" | "crop" | "natural">, rect: Box, max = EXPORT_MAX_PX): number {+ return Math.max(1, Math.min(layerDensity(node), max / Math.max(rect[2], rect[3])));+}++/** The pixel size of a render of `w × h` doc px at `scale`. */+export const scaledSize = (w: number, h: number, scale: number): [number, number] => [Math.max(1, Math.round(w * scale)), Math.max(1, Math.round(h * scale))];+export type Handle = "n" | "s" | "e" | "w" | "ne" | "nw" | "se" | "sw";/**@@ -597,6 +686,7 @@ export function initialDoc(source: string, width: number, height: number, at = Dheight,source,decomposed: false,+ sourceBox: [0, 0, width, height],nodes: [{ id, name: "Original image", z: 0, x: 0, y: 0, w: width, h: height, rotation: 0, src: source, crop: null, natural: [width, height], revisions: [rev], revision: 0 }],};}@@ -607,7 +697,13 @@ export function normalize(doc: LayerDoc): LayerDoc {return nodes.every((n, i) => n === doc.nodes[i]) ? doc : { ...doc, nodes };}-const withNodes = (doc: LayerDoc, nodes: LayerNode[]): LayerDoc => normalize({ ...doc, nodes: nodes.map((n, i) => (n.z === i ? n : { ...n, z: i })) });+const withNodes = (doc: LayerDoc, nodes: LayerNode[]): LayerDoc => {+ if (nodes.length > MAX_NODES && nodes.length > doc.nodes.length) throw new LayerLimitError();+ return normalize({ ...doc, nodes: nodes.map((n, i) => (n.z === i ? n : { ...n, z: i })) });+};++/** Whether `more` layers still fit in the document. */+export const roomFor = (doc: Pick<LayerDoc, "nodes">, more = 1): boolean => doc.nodes.length + more <= MAX_NODES;export function getNode(doc: LayerDoc, id: string | null | undefined): LayerNode | undefined {return id ? doc.nodes.find((n) => n.id === id) : undefined;@@ -677,9 +773,13 @@ function refit(node: LayerNode, rev: Pick<LayerRevision, "crop" | "natural">): Preturn { x: node.x, y: node.y + node.h / 2 - h / 2, w: node.w, h };}-/** Add a new version of a layer's pixels and switch to it. */+/**+ * Add a new version of a layer's pixels and switch to it. A layer keeps {@link MAX_REVISIONS}: its+ * first one (“Reset layer”) and the newest.+ */export function addRevision(node: LayerNode, rev: LayerRevision): LayerNode {- const revisions = node.revisions.length ? [...node.revisions, rev] : [{ src: node.src, crop: node.crop ?? null, natural: node.natural, label: "Before", at: rev.at - 1 }, rev];+ let revisions = node.revisions.length ? [...node.revisions, rev] : [{ src: node.src, crop: node.crop ?? null, natural: node.natural, label: "Before", at: rev.at - 1 }, rev];+ if (revisions.length > MAX_REVISIONS) revisions = [revisions[0], ...revisions.slice(revisions.length - (MAX_REVISIONS - 1))];return { ...node, ...refit(node, rev), src: rev.src, crop: rev.crop ?? null, natural: rev.natural, revisions, revision: revisions.length - 1 };}@@ -699,7 +799,13 @@ export function reframeDoc(doc: LayerDoc, rect: Box): LayerDoc {const [rx, ry, rw, rh] = rect.map(Math.round) as Box;if (rw < 8 || rh < 8 || !intersect([rx, ry, rw, rh], [0, 0, doc.width, doc.height])) throw new Error("The frame no longer overlaps the image. Move it back over the picture.");if (rx === 0 && ry === 0 && rw === doc.width && rh === doc.height) return doc;- return { ...doc, width: rw, height: rh, nodes: doc.nodes.map((n) => ({ ...n, x: n.x - rx, y: n.y - ry })) };+ const [sx, sy, sw, sh] = sourceBoxOf(doc);+ return { ...doc, width: rw, height: rh, sourceBox: [sx - rx, sy - ry, sw, sh], nodes: doc.nodes.map((n) => ({ ...n, x: n.x - rx, y: n.y - ry })) };+}++/** Where the source image sits in the document (the whole canvas for documents saved before this was kept). */+export function sourceBoxOf(doc: Pick<LayerDoc, "width" | "height" | "sourceBox">): Box {+ return asBox(doc.sourceBox) ?? [0, 0, doc.width, doc.height];}/** Outpaint padding for an expanded frame (whole pixels, multiples of 8 as the open workflow wants). */diff --git a/src/server/layers.ts b/src/server/layers.tsindex a8ec2e65..7a8ac5d2 100644--- a/src/server/layers.ts+++ b/src/server/layers.ts@@ -8,11 +8,15 @@ import {APPLIES_TO_DOC,clampLayers,CUTOUT_MODELS,+ defaultLayers,initialDoc,+ layersModelFor,+ MAX_NODES,RELIGHT_DIRECTIONS,RELIGHT_LIGHTS,textChanges,textEditPrompt,+ TOOL_LABELS,TOOL_MODELS,type Box,type LayerDoc,@@ -118,7 +122,8 @@ const DocSchema = z.object({height: z.number().int().min(1).max(20_000),source: FileUrl,decomposed: z.boolean(),- nodes: z.array(Node).max(200),+ sourceBox: BoxSchema.optional(),+ nodes: z.array(Node).max(MAX_NODES),});/** A document the browser sent, cleaned (null when it can't be read). */@@ -166,21 +171,6 @@ export const JobInputSchema = z.object({// ---------------------------------------------------------------------------// 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];@@ -236,10 +226,9 @@ export function jobSteps(input: LayerJobInput, opts: { batchTitle?: string } = {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));+ // Open: a named element goes to the prompt-guided Layered-Control model (the form says so).+ const model = toolModel(tool, engine, layersModelFor(tool, engine, input.modelId, prompt));+ const layers = clampLayers(model.id, s.layers ?? defaultLayers(tool, model.id));const res = s.resolution ?? "1K";const params: GenerationRequest["params"] = { ...aspectFor(model) };let p: string | undefined;@@ -386,14 +375,28 @@ function resultOf(job: LayerJob): LayerJobResult | null {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");+/**+ * “An image can only be decomposed once” as a fact of the project, not of the open version (an+ * older version can be restored): a decomposition landed, or a split of the original picture did.+ * saveJobs keeps these jobs for good.+ */+const decomposes = (j: LayerJob, sourceUrl: string) => j.state === "applied" && (j.tool === "decompose" || (j.tool === "split" && j.settings?.image === sourceUrl));++function isDecomposed(row: ProjectRow, jobs: LayerJob[], doc: LayerDoc | null): boolean {+ return !!doc?.decomposed || jobs.some((j) => decomposes(j, row.source_url));+}++function statusOf(row: ProjectRow, doc: LayerDoc | null): Pick<LayerProject, "status" | "pendingLayers" | "decomposed"> {+ const jobs = parseJobs(row.jobs_json);+ const decomposed = isDecomposed(row, jobs, doc);+ const dec = jobs.filter((j) => j.tool === "decompose" && j.state !== "dismissed");const last = dec[dec.length - 1];- if (!last || last.state === "applied") return "ready";+ if (!last || last.state === "applied") return { status: "ready", decomposed };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";+ if (r && ACTIVE.has(r.status)) return { status: "processing", decomposed };+ // Finished, waiting for the editor to lay the layers out.+ if (r?.status === "succeeded") return { status: "unopened", pendingLayers: r.outputs.filter((o) => o.kind === "image").length, decomposed };+ return { status: decomposed ? "ready" : "failed", decomposed };}function headDoc(row: ProjectRow): LayerDoc | null {@@ -411,7 +414,7 @@ function toProject(row: ProjectRow, doc = headDoc(row)): LayerProject {width: doc?.width ?? row.width,height: doc?.height ?? row.height,layers: doc?.nodes.length ?? 1,- status: statusOf(row, doc),+ ...statusOf(row, doc),createdAt: row.created_at,updatedAt: row.updated_at,};@@ -546,13 +549,18 @@ export function createVersion(id: string, input: { doc?: LayerDoc; label?: strinreturn projectView(id)!;}-/** Jobs kept per project: every pending one, plus the latest finished ones (the last text detection among them). */+/**+ * Jobs kept per project: every pending one, the one that decomposed the image (for good: it says+ * the image can't be decomposed again), 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 source = getRow(id)?.source_url ?? "";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 first = jobs.find((j) => decomposes(j, source));+ const done = jobs.filter((j) => j.state !== "pending" && j !== first).slice(-Math.max(0, KEEP_JOBS - pending.length - (first ? 1 : 0)));+ const keep = jobs.filter((j) => pending.includes(j) || done.includes(j) || j === first).map((j) => {const { result: _drop, ...rest } = j;void _drop;return rest;@@ -571,7 +579,7 @@ export function startJob(id: string, input: LayerJobInput): LayerJob {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 (isDecomposed(row, jobs, headDoc(row))) 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))) {diff --git a/src/server/storage.ts b/src/server/storage.tsindex ebdfc627..92af7cf8 100644--- a/src/server/storage.ts+++ b/src/server/storage.ts@@ -79,7 +79,8 @@ export interface Asset {relPath: string;contentType: string;size: number;- source: "upload" | "generation";+ /** "derived": a picture a tool rendered for a model (a layer, a region, a mask), not listed with your uploads. */+ source: "upload" | "generation" | "derived";generationId: string | null;createdAt: number;url: string;@@ -92,7 +93,7 @@ interface AssetRow {rel_path: string;content_type: string;size: number;- source: "upload" | "generation";+ source: Asset["source"];generation_id: string | null;created_at: number;}@@ -126,7 +127,7 @@ export function saveFile(opts: {const id = nanoid(12);const ext = EXT_BY_TYPE[opts.contentType.split(";")[0].trim()] ?? opts.name?.split(".").pop()?.toLowerCase() ?? "bin";const day = new Date().toISOString().slice(0, 10);- const relPath = path.join(/*turbopackIgnore: true*/ opts.source === "upload" ? "uploads" : "outputs", day, `${id}.${ext}`);+ const relPath = path.join(/*turbopackIgnore: true*/ opts.source === "generation" ? "outputs" : "uploads", day, `${id}.${ext}`);const abs = path.join(FILES_DIR, relPath);fs.mkdirSync(path.dirname(abs), { recursive: true });fs.writeFileSync(abs, opts.data);@@ -155,14 +156,14 @@ export function getAsset(id: string): Asset | null {return row ? toAsset(row) : null;}-/** Newest first; page with `before` (+ `beforeId`): the last asset of the previous page. */+/** Newest first; page with `before` (+ `beforeId`): the last asset of the previous page. Derived renders only when asked for. */export function listAssets(opts: { source?: Asset["source"]; kind?: MediaKind; limit?: number; before?: number; beforeId?: string }): Asset[] {const where: string[] = [];const args: unknown[] = [];if (opts.source) {where.push("source = ?");args.push(opts.source);- }+ } else where.push("source != 'derived'");if (opts.kind) {where.push("kind = ?");args.push(opts.kind);diff --git a/tests/e2e/layers.mjs b/tests/e2e/layers.mjsnew file mode 100644index 00000000..d2e55bef--- /dev/null+++ b/tests/e2e/layers.mjs@@ -0,0 +1,136 @@+// Layers studio regressions in a real browser (the app must be running; demo mode is fine).+// Usage: node tests/e2e/layers.mjs [appUrl]. Exits 1 on the first failure.+//+// 1. Open a project, then "All projects": the projects page is usable (no "Preparing your project" cover).+// 2. "Open in Layers" twice in one session (client-side navigations, the same image) opens two projects.+// 3. An edit made while a tool's result is being saved survives: the result lands on the newest document.+// 4. Delete in the Edit history sheet doesn't delete the selected layer, and Restore doesn't get the focus.+// 5. Open engine: separating a named element runs on Qwen-Image-Layered Control.+import assert from "node:assert/strict";+import path from "node:path";+import { DESKTOP, launch, root } from "./_browser.mjs";++const app = (process.argv.slice(2).find((a) => !a.startsWith("--")) ?? "http://localhost:3000").replace(/\/$/, "");+const SAMPLE = path.join(root, "public/samples/grade-sample.jpg");+const browser = await launch();+const step = (name) => console.log(`- ${name}`);+const projectUrl = /\/layers\/[\w-]+$/;++/** fetch() from the page, as the editor does. */+const api = (page, url, init) =>+ page.evaluate(+ async ([u, i]) => {+ const r = await fetch(u, i);+ return { status: r.status, body: await r.json().catch(() => null) };+ },+ [url, init],+ );+const toast = (page, re, timeout = 90_000) => page.locator("[data-sonner-toast]").filter({ hasText: re }).first().waitFor({ timeout });+const rows = (page) => page.getByRole("button", { name: /^Select layer / });++try {+ const ctx = await browser.newContext({ ...DESKTOP });+ await ctx.addInitScript(() => localStorage.setItem("fuobe.engine", "cloud"));+ const page = await ctx.newPage();+ const errors = [];+ page.on("pageerror", (e) => errors.push(e.message));++ step("upload an image on /layers: its project opens");+ await page.goto(`${app}/layers`, { waitUntil: "load", timeout: 120_000 });+ const chooser = page.waitForEvent("filechooser");+ await page.getByRole("button", { name: "Upload Media" }).first().click();+ await (await chooser).setFiles(SAMPLE);+ await page.waitForURL(projectUrl, { timeout: 60_000 });+ await page.getByRole("button", { name: "Separate layers" }).waitFor({ timeout: 60_000 });++ step("All projects: the projects page is usable again");+ await page.getByRole("link", { name: "All projects" }).click();+ await page.waitForURL((u) => new URL(u).pathname === "/layers", { timeout: 30_000 });+ await page.getByRole("heading", { name: "My projects" }).waitFor();+ await page.waitForTimeout(800);+ const cover = page.getByRole("status").filter({ hasText: "Preparing your project" });+ assert.equal(await cover.count(), 0, "no “Preparing your project” cover");+ assert.ok(await page.getByRole("button", { name: "Upload Media" }).first().isEnabled(), "Upload Media is enabled");+ await page.getByRole("link", { name: /^Open project/ }).first().click();+ await page.waitForURL(projectUrl, { timeout: 30_000 });++ step("Open in Layers twice in one session opens two projects");+ const image = (await api(page, "/api/assets?source=upload&kind=image")).body.items[0].url;+ const before = (await api(page, "/api/layers")).body.items.length;+ for (let k = 0; k < 2; k++) {+ const from = page.url();+ // A client-side navigation, as the result menus' “Open in Layers” links do.+ await page.evaluate((u) => window.next.router.push(u), `/layers?image=${encodeURIComponent(image)}`);+ await page.waitForURL((u) => projectUrl.test(new URL(u).pathname) && u.toString() !== from, { timeout: 30_000 });+ await page.getByRole("button", { name: "Separate layers" }).waitFor({ timeout: 60_000 });+ }+ assert.equal((await api(page, "/api/layers")).body.items.length - before, 2, "two new projects");+ const id = page.url().split("/").pop();++ step("an edit made while a result is being saved survives");+ await page.getByRole("button", { name: "Separate layers" }).click();+ await toast(page, /Decomposed into \d+ layers/);+ assert.ok((await rows(page).count()) >= 3, "decomposed into layers");+ const names = (await rows(page).evaluateAll((bs) => bs.map((b) => b.getAttribute("aria-label").replace(/^Select layer /, "")))).reverse(); // bottom to top+ const [edited, nudged] = [names[1], names[2]];+ const docOf = async () => (await api(page, `/api/layers/${id}`)).body.doc;+ const x0 = (await docOf()).nodes.find((n) => n.name === nudged).x;+ // Hold the result's version for 2.5 s, and move another layer meanwhile.+ await page.route("**/api/layers/*/versions", async (route) => {+ await new Promise((r) => setTimeout(r, 2500));+ await route.continue();+ });+ await page.getByRole("button", { name: `Select layer ${edited}`, exact: true }).click();+ const back = page.getByRole("button", { name: "Back to tools" });+ if (await back.isVisible()) await back.click();+ await page.getByRole("button", { name: /^Remove background/ }).first().click();+ await page.getByRole("button", { name: "Remove background", exact: true }).last().click();+ await page.getByText("Adding the result to your layers").waitFor({ timeout: 90_000 });+ await page.waitForTimeout(700);+ await page.getByRole("button", { name: `Select layer ${nudged}`, exact: true }).click();+ for (let k = 0; k < 4; k++) await page.keyboard.press("Shift+ArrowRight");+ await toast(page, /remove background done/i);+ await page.unroute("**/api/layers/*/versions");+ await page.waitForTimeout(2500); // the autosave+ const saved = await docOf();+ assert.equal(Math.round(saved.nodes.find((n) => n.name === nudged).x - x0), 40, "the nudge is saved");+ assert.equal(saved.nodes.find((n) => n.name === edited).revisions.length, 2, "the result is saved");+ const shown = await page.getByRole("textbox", { name: "X in pixels" }).inputValue();+ assert.equal(Math.round(Number(shown) - x0), 40, "the nudge is on screen");++ step("Delete in the Edit history sheet leaves the layer alone");+ const count = await rows(page).count();+ await page.getByRole("button", { name: "Edit history" }).click();+ const sheet = page.getByRole("dialog", { name: "Edit history" });+ await sheet.waitFor();+ assert.notEqual((await page.evaluate(() => document.activeElement?.textContent ?? "")).trim(), "Restore", "Restore doesn't take the focus");+ await sheet.getByRole("button", { name: /Restore/ }).first().focus();+ await page.keyboard.press("Delete");+ await page.keyboard.press("Backspace");+ await page.keyboard.press("Escape");+ await sheet.waitFor({ state: "detached" });+ assert.equal(await rows(page).count(), count, "no layer deleted");++ step("open engine: a named element runs on Qwen-Image-Layered Control");+ await page.getByRole("radiogroup", { name: "Engine" }).getByRole("radio", { name: "Open source" }).click();+ await page.getByRole("button", { name: `Actions for ${nudged}`, exact: true }).click();+ await page.getByRole("menuitem", { name: "Separate layer" }).click();+ await page.getByLabel("What to pull out (optional)").fill("the face");+ await page.getByText("Model · Qwen-Image-Layered Control").waitFor();+ const sent = page.waitForRequest((r) => r.method() === "POST" && /\/api\/layers\/[\w-]+\/jobs$/.test(new URL(r.url()).pathname));+ await page.getByRole("button", { name: "Separate layer", exact: true }).click();+ const body = JSON.parse((await sent).postData() ?? "{}");+ assert.equal(body.engine, "open");+ assert.equal(body.modelId, "oss-qwen-layered-control");+ assert.equal(body.prompt, "the face");+ await toast(page, /split into \d+ layers/);++ assert.deepEqual(errors, [], "no page errors");+ await ctx.close();+ console.log("\nLayers checks passed.");+} catch (e) {+ console.error(`\nFAILED: ${e.message}`);+ process.exitCode = 1;+} finally {+ await browser.close();+}diff --git a/tests/layers-api.test.ts b/tests/layers-api.test.tsindex 4cfec64f..36f5a2ff 100644--- a/tests/layers-api.test.ts+++ b/tests/layers-api.test.ts@@ -21,6 +21,7 @@ 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");+const renders = await import("@/app/api/layers/renders/route");beforeAll(() => setSetting("demoMode", "auto"));afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));@@ -77,6 +78,28 @@ describe("job steps", () => {expect(steps({ tool: "split", prompt: "the guitar" })[0].request.prompt).toMatch(/^Separate the guitar onto its own layer/);});+ it("routes what the Separate layer form sends: a named element on the open engine runs on Layered-Control", () => {+ // The form always sends the model it shows; the default is plain Qwen-Image-Layered.+ const [s] = steps({ tool: "split", engine: "open", modelId: "oss-qwen-layered", prompt: "the guitar", nodeId: "n1", settings: { resolution: "1K", mode: "standard", layers: 2 } });+ expect(s.request).toMatchObject({ modelId: "oss-qwen-layered-control", prompt: "the guitar", params: { numLayers: 2 } });+ expect(steps({ tool: "split", engine: "open", modelId: "oss-qwen-layered-control", prompt: "the face", settings: { layers: 3 } })[0].request).toMatchObject({ modelId: "oss-qwen-layered-control", params: { numLayers: 3 } });+ // Control needs a name: without one the plain model splits.+ expect(steps({ tool: "split", engine: "open", modelId: "oss-qwen-layered-control", settings: { layers: 4 } })[0].request).toMatchObject({ modelId: "oss-qwen-layered", params: { numLayers: 4 } });+ // A named element without a layer count: the element and the rest.+ expect(steps({ tool: "split", engine: "open", prompt: "the hat" })[0].request.params).toMatchObject({ numLayers: 2 });+ });++ it("sends Angles the camera the form shows for its model", () => {+ // Nano Banana Pro: a camera chip, no sliders.+ const nbp = steps({ tool: "angles", modelId: "nano-banana-pro", settings: { angle: "Back", keepAlpha: false } })[0].request;+ expect(nbp).toMatchObject({ modelId: "nano-banana-pro", op: "edit" });+ expect(nbp.prompt).toMatch(/^Show the exact same subject from a view from directly behind/);+ expect(nbp.params?.extra).toBeUndefined();+ // Qwen Multiple Angles: the sliders.+ const qwen = steps({ tool: "angles", modelId: "qwen-multiple-angles", settings: { rotate: 120, tilt: -10, zoom: 2 } })[0].request;+ expect(qwen.params?.extra).toEqual({ horizontal_angle: 120, vertical_angle: -10, zoom: 2 });+ });+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([@@ -294,6 +317,43 @@ describe("layers API", () => {expect(v.versions[0].label).toBe("Restored “Original”");expect(v.doc.nodes).toHaveLength(1);expect(v.doc.decomposed).toBe(false);+ // The image was decomposed all the same: that's the project's, not the version's.+ expect(v.project.decomposed).toBe(true);+ const again = await jobs.POST(req("POST", { tool: "decompose", engine: "cloud", image: source, frame: [0, 0, 1920, 1080] }), ctx({ id }));+ expect(again.status).toBe(409);+ expect(((await again.json()) as { error: string }).error).toMatch(/can only be decomposed once/);+ });++ it("counts separating the original picture as its decomposition", async () => {+ const src = upload();+ let res = await list.POST(req("POST", { source: src, width: 64, height: 48 }));+ const v0 = (await res.json()) as LayerProjectView;+ const pid = v0.project.id;+ expect(v0.project.decomposed).toBe(false);+ res = await jobs.POST(req("POST", { tool: "split", engine: "cloud", image: src, nodeId: "original", frame: [0, 0, 64, 48], prompt: "the cup" }), ctx({ id: pid }));+ expect(res.status).toBe(201);+ const split = (await res.json()) as LayerJob;+ await settle(split.generationIds[0]);+ res = await versions.POST(req("POST", { doc: { ...v0.doc, decomposed: true }, label: split.label, jobId: split.id }), ctx({ id: pid }));+ expect(((await res.json()) as LayerProjectView).project.decomposed).toBe(true);+ // Restoring the original version doesn't make it decomposable again.+ res = await versions.POST(req("POST", { from: v0.headVersionId }), ctx({ id: pid }));+ expect(((await res.json()) as LayerProjectView).doc.decomposed).toBe(false);+ res = await jobs.POST(req("POST", { tool: "decompose", engine: "cloud", image: src, frame: [0, 0, 64, 48] }), ctx({ id: pid }));+ expect(res.status).toBe(409);+ await one.DELETE(req("DELETE"), ctx({ id: pid }));+ });++ it("saves where the original sits in the document", async () => {+ const src = upload();+ const v0 = (await (await list.POST(req("POST", { source: src, width: 64, height: 48 }))).json()) as LayerProjectView;+ expect(v0.doc.sourceBox).toEqual([0, 0, 64, 48]);+ const grown: LayerDoc = { ...v0.doc, width: 96, sourceBox: [16, 0, 64, 48], nodes: v0.doc.nodes.map((x) => ({ ...x, x: 16 })) };+ const res = await one.PATCH(req("PATCH", { doc: grown, versionId: v0.headVersionId }), ctx({ id: v0.project.id }));+ expect(res.status).toBe(200);+ const after = (await (await one.GET(req("GET"), ctx({ id: v0.project.id }))).json()) as LayerProjectView;+ expect(after.doc.sourceBox).toEqual([16, 0, 64, 48]);+ await one.DELETE(req("DELETE"), ctx({ id: v0.project.id }));});it("opens a finished layers result as a project", async () => {@@ -305,6 +365,11 @@ describe("layers API", () => {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");+ // Until the editor lays the layers out, the card says they're ready to see (not “Processing…” for good).+ expect(v.project).toMatchObject({ status: "unopened", layers: 1 });+ expect(v.project.pendingLayers).toBe(v.jobs[0].result?.outputs.filter((o) => o.kind === "image").length);+ const card = ((await (await list.GET()).json()) as { items: LayerProject[] }).items.find((p) => p.id === v.project.id);+ expect(card?.status).toBe("unopened");const bad = await list.POST(req("POST", { source, width: 512, height: 512, generationId: "nope" }));expect(bad.status).toBe(400);});@@ -323,3 +388,33 @@ describe("layers API", () => {expect(res.status).toBe(404);});});++describe("pictures the editor renders for models", () => {+ const post = (file: File) => {+ const form = new FormData();+ form.append("file", file);+ return renders.POST(new Request("http://localhost/api/layers/renders", { method: "POST", body: form }));+ };++ it("are stored as derived files: kept out of Uploads and the pickers, still served", async () => {+ const res = await post(new File([PNG], "layers-subject.png", { type: "image/png" }));+ expect(res.status).toBe(201);+ const a = (await res.json()) as { id: string; url: string; source: string };+ expect(a).toMatchObject({ source: "derived" });+ expect(a.url).toMatch(/^\/api\/files\/uploads\/.+\.png$/);+ const { listAssets, getAsset } = await import("@/server/storage");+ expect(getAsset(a.id)?.source).toBe("derived");+ // The Library's Uploads tab (source=upload) and the pickers (every source) don't list it.+ expect(listAssets({ source: "upload" }).some((x) => x.id === a.id)).toBe(false);+ expect(listAssets({}).some((x) => x.id === a.id)).toBe(false);+ expect(listAssets({ source: "derived" }).some((x) => x.id === a.id)).toBe(true);+ // Uploads still list.+ const up = upload();+ expect(listAssets({ source: "upload" }).some((x) => x.url === up)).toBe(true);+ });++ it("only takes PNGs", async () => {+ expect((await post(new File([Buffer.from("<svg/>")], "x.png", { type: "image/png" }))).status).toBe(415);+ expect((await post(new File([PNG], "x.jpg", { type: "image/jpeg" }))).status).toBe(415);+ });+});diff --git a/tests/layers-apply.test.ts b/tests/layers-apply.test.tsnew file mode 100644index 00000000..bb0c9483--- /dev/null+++ b/tests/layers-apply.test.ts@@ -0,0 +1,230 @@+import { describe, expect, it } from "vitest";+import { applyMeasured, idPool, imagesToMeasure, type MeasuredJob } from "@/components/layers/apply";+import { initialDoc, sourceBoxOf, updateNode, type Box, type LayerDoc, type LayerJob, type LayerNode } from "@/lib/layers";++// What a finished tool job does to the document (the pure half of the editor's apply step): every+// tool's branch, and laying a result out on a document that was edited while it landed.++const node = (id: string, z: number, extra: Partial<LayerNode> = {}): LayerNode => ({+ id,+ name: id,+ z,+ x: 0,+ y: 0,+ w: 100,+ h: 50,+ rotation: 0,+ src: `/api/files/${id}.png`,+ natural: [100, 50],+ revisions: [{ src: `/api/files/${id}.png`, natural: [100, 50], label: "Original", at: 1 }],+ revision: 0,+ ...extra,+});++const doc = (nodes: LayerNode[], w = 400, h = 300, extra: Partial<LayerDoc> = {}): LayerDoc => ({ v: 1, width: w, height: h, source: "/api/files/src.png", decomposed: true, nodes, ...extra });++const job = (tool: LayerJob["tool"], extra: Partial<LayerJob> = {}): LayerJob => ({+ id: "j1",+ tool,+ label: "Upscale",+ frame: [0, 0, 400, 300],+ generationIds: ["g1"],+ state: "pending",+ createdAt: 1,+ result: { status: "succeeded", progress: 1, message: null, error: null, provider: "mock", outputs: [{ url: "/api/files/out.png", kind: "image" }] },+ ...extra,+});++let n = 0;+const opts = () => ({ newId: () => `n${++n}`, at: 5 });+const one = (url: string, natural: [number, number], extra: Partial<MeasuredJob["outputs"][number]> = {}): MeasuredJob => ({ outputs: [{ url, natural, ...extra }] });+const ids = (d: LayerDoc) => [...d.nodes].sort((a, b) => a.z - b.z).map((x) => x.id);++describe("laying out a decomposition", () => {+ it("crops full-canvas layers to their alpha and leaves empty ones out (Qwen)", () => {+ const d = initialDoc("/api/files/src.png", 400, 300, 1);+ const m: MeasuredJob = {+ outputs: [+ { url: "/api/files/bg.png", natural: [800, 600], alpha: [0, 0, 800, 600], meta: { name: "Background", z: 0 } },+ { url: "/api/files/subject.png", natural: [800, 600], alpha: [200, 100, 400, 300], meta: { name: "Subject", z: 1 } },+ { url: "/api/files/empty.png", natural: [800, 600], alpha: null, meta: { z: 2 } },+ ],+ };+ const r = applyMeasured(d, job("decompose", { label: "Layer decomposition" }), m, opts());+ expect(r.doc.decomposed).toBe(true);+ expect(r.doc.nodes.map((x) => x.name)).toEqual(["Background", "Subject"]);+ expect(r.doc.nodes[1]).toMatchObject({ x: 100, y: 50, w: 200, h: 150, crop: [200, 100, 400, 300], natural: [800, 600] });+ expect(r.message).toBe("Decomposed into 2 layers");+ });++ it("places Seedream's cut layers by their boxes in the base layer's pixels", () => {+ const d = initialDoc("/api/files/src.png", 400, 300, 1);+ const m: MeasuredJob = {+ outputs: [+ { url: "/api/files/base.png", natural: [800, 600], alpha: [0, 0, 800, 600], meta: { z: 0, bbox: [0, 0, 800, 600] } },+ { url: "/api/files/cup.png", natural: [200, 100], alpha: [0, 0, 200, 100], meta: { z: 1, name: "Cup", bbox: [400, 300, 200, 100] } },+ ],+ };+ const r = applyMeasured(d, job("decompose"), m, opts());+ expect(r.doc.nodes[1]).toMatchObject({ name: "Cup", x: 200, y: 150, w: 100, h: 50, crop: null });+ });++ it("splits a layer in its place, inside where the layer is now", () => {+ const d = doc([node("bg", 0, { w: 400, h: 300 }), node("subject", 1, { x: 100, y: 100, w: 200, h: 100 }), node("text", 2)]);+ const m: MeasuredJob = {+ outputs: [+ { url: "/api/files/p1.png", natural: [200, 100], alpha: [0, 0, 100, 100] },+ { url: "/api/files/p2.png", natural: [200, 100], alpha: [100, 0, 100, 100], meta: { name: "Guitar" } },+ ],+ };+ // The job started when the layer sat at 0,0; it was moved since.+ const r = applyMeasured(d, job("split", { nodeId: "subject", frame: [0, 0, 200, 100], label: "Separating subject" }), m, opts());+ expect(r.doc.nodes.map((x) => [x.name, x.z])).toEqual([+ ["bg", 0],+ ["subject · part 1", 1],+ ["Guitar", 2],+ ["text", 3],+ ]);+ expect(r.doc.nodes[1]).toMatchObject({ x: 100, y: 100, w: 100, h: 100 });+ expect(r.doc.nodes[2]).toMatchObject({ x: 200, y: 100, w: 100, h: 100 });+ expect(r.select).toBe(r.doc.nodes[2].id);+ });++ it("counts separating the original picture as its decomposition", () => {+ const d = initialDoc("/api/files/src.png", 400, 300, 1);+ const m = one("/api/files/p.png", [400, 300], { alpha: [0, 0, 200, 300] });+ const own = applyMeasured(d, job("split", { nodeId: "original", settings: { image: "/api/files/src.png" } }), m, opts());+ expect(own.doc.decomposed).toBe(true);+ // A render of an edited layer is another picture: no decomposition yet.+ const other = applyMeasured(d, job("split", { nodeId: "original", settings: { image: "/api/files/render.png" } }), m, opts());+ expect(other.doc.decomposed).toBe(false);+ });++ it("refuses a result without images", () => {+ expect(() => applyMeasured(initialDoc("/api/files/src.png", 4, 3), job("decompose"), { outputs: [] }, opts())).toThrow(/no image/);+ const blank: MeasuredJob = { outputs: [{ url: "/api/files/e.png", natural: [4, 3], alpha: null }] };+ expect(() => applyMeasured(initialDoc("/api/files/src.png", 4, 3), job("decompose"), blank, opts())).toThrow(/No layers came back/);+ });+});++describe("laying out the other tools", () => {+ it("adds a regional edit as the Original / New pair with its feather", () => {+ const d = doc([node("bg", 0, { w: 400, h: 300 })]);+ const rect: Box = [50, 60, 120, 80];+ const m: MeasuredJob = { ...one("/api/files/new.png", [240, 160]), original: { url: "/api/files/region.png", natural: [120, 80] } };+ const r = applyMeasured(d, job("regional", { frame: rect, settings: { feather: 7, prompt: "add a hat", image: "/api/files/region.png" } }), m, opts());+ const [, orig, edited] = r.doc.nodes;+ expect(orig).toMatchObject({ name: "Original", role: "original", x: 50, y: 60, w: 120, h: 80, src: "/api/files/region.png" });+ expect(edited).toMatchObject({ name: "New", role: "new", feather: 7, src: "/api/files/new.png", natural: [240, 160] });+ expect(edited.revisions[0].prompt).toBe("add a hat");+ // The region as it was didn't load: just the new one.+ const lone = applyMeasured(d, job("regional", { frame: rect }), { ...one("/api/files/new.png", [240, 160]), original: null }, opts());+ expect(lone.doc.nodes.map((x) => x.role)).toEqual([undefined, "new"]);+ });++ it("expands the canvas with the fill underneath, and moves where the original sits", () => {+ const d = { ...initialDoc("/api/files/src.png", 400, 300, 1) };+ const r = applyMeasured(d, job("expand", { frame: [-100, 0, 600, 300] }), one("/api/files/fill.png", [1200, 600]), opts());+ expect(r.doc).toMatchObject({ width: 600, height: 300 });+ expect(r.doc.nodes[0]).toMatchObject({ name: "Expanded fill", x: 0, y: 0, w: 600, h: 300, z: 0 });+ expect(r.doc.nodes[1]).toMatchObject({ name: "Original image", x: 100, z: 1 });+ expect(sourceBoxOf(r.doc)).toEqual([100, 0, 400, 300]);+ });++ it("places a generated layer in the middle, cropped to its alpha", () => {+ const d = doc([node("bg", 0, { w: 400, h: 300 })]);+ const r = applyMeasured(d, job("generate-layer", { settings: { prompt: "a red paper lantern with a gold tassel" } }), one("/api/files/lantern.png", [1024, 1024], { alpha: [256, 0, 512, 1024] }), opts());+ const lantern = r.doc.nodes[1];+ expect(lantern).toMatchObject({ name: "A red paper lantern", crop: [256, 0, 512, 1024], h: 150, w: 75, x: 162.5, y: 75 });+ expect(r.select).toBe(lantern.id);+ });++ it("makes an edit a new revision of its layer", () => {+ const d = doc([node("bg", 0), node("subject", 1, { x: 10, y: 10 })]);+ const r = applyMeasured(d, job("upscale", { nodeId: "subject", frame: [10, 10, 100, 50] }), one("/api/files/up.png", [400, 200]), opts());+ const s = r.doc.nodes[1];+ expect(s).toMatchObject({ src: "/api/files/up.png", natural: [400, 200], revision: 1, x: 10, y: 10, w: 100, h: 50 });+ expect(s.revisions.map((x) => x.label)).toEqual(["Original", "Upscale"]);+ expect(r.message).toBe("subject: upscale done");+ });++ it("puts the result where the layer was when it was deleted meanwhile", () => {+ const d = doc([node("bg", 0)]);+ const r = applyMeasured(d, job("relight", { nodeId: "gone", frame: [20, 30, 100, 50], label: "Relight" }), one("/api/files/lit.png", [200, 100]), opts());+ expect(r.doc.nodes[1]).toMatchObject({ name: "Relit", x: 20, y: 30, w: 100, h: 50 });+ });++ it("covers the picture as it is now with a whole-image result; a cut-out hides what's under it", () => {+ const d = doc([node("bg", 0, { w: 400, h: 300 }), node("subject", 1)], 400, 300);+ const up = applyMeasured(d, job("upscale"), one("/api/files/up.png", [1600, 1200]), opts());+ expect(up.doc.nodes[2]).toMatchObject({ name: "Upscaled", x: 0, y: 0, w: 400, h: 300 });+ expect(up.doc.nodes.some((x) => x.hidden)).toBe(false);+ const cut = applyMeasured(d, job("bg-remove", { label: "Remove background" }), one("/api/files/cut.png", [400, 300]), opts());+ expect(cut.doc.nodes.map((x) => [x.name, !!x.hidden])).toEqual([+ ["bg", true],+ ["subject", true],+ ["Cut-out", false],+ ]);+ });+});++describe("a result landing on a document edited meanwhile", () => {+ it("keeps the edit and the result, with the same new layer ids", () => {+ const before = doc([node("bg", 0, { w: 400, h: 300 }), node("subject", 1, { x: 10, y: 10 }), node("prop", 2, { x: 77 })]);+ const j = job("split", { nodeId: "subject", frame: [10, 10, 100, 50], label: "Separating subject" });+ const m: MeasuredJob = {+ outputs: [+ { url: "/api/files/p1.png", natural: [100, 50], alpha: [0, 0, 50, 50] },+ { url: "/api/files/p2.png", natural: [100, 50], alpha: [50, 0, 50, 50] },+ ],+ };+ const pool = idPool((() => {+ let k = 0;+ return () => `id${++k}`;+ })());+ // Laid out for the version on the document as it was...+ const saved = applyMeasured(before, j, m, { newId: pool(), at: 9 });+ // ...while the prop was nudged 40 px and the subject moved.+ const edited = updateNode(updateNode(before, "prop", { x: 117 }), "subject", { x: 200 });+ const rebased = applyMeasured(edited, j, m, { newId: pool(), at: 9 });+ expect(rebased.doc.nodes.find((x) => x.id === "prop")?.x).toBe(117);+ expect(ids(rebased.doc)).toEqual(ids(saved.doc));+ expect(ids(rebased.doc)).toEqual(["bg", "id1", "id2", "prop"]);+ // The parts land where the subject is now.+ expect(rebased.doc.nodes.find((x) => x.id === "id1")).toMatchObject({ x: 200, y: 10, w: 50, h: 50 });+ expect(saved.doc.nodes.find((x) => x.id === "id1")).toMatchObject({ x: 10 });+ });++ it("adds a revision on top of edits to the same layer", () => {+ const before = doc([node("bg", 0), node("subject", 1)]);+ const edited = updateNode(before, "subject", { opacity: 0.5, name: "Hero" });+ const r = applyMeasured(edited, job("relight", { nodeId: "subject", label: "Relight" }), one("/api/files/lit.png", [100, 50]), opts());+ expect(r.doc.nodes[1]).toMatchObject({ name: "Hero", opacity: 0.5, src: "/api/files/lit.png", revision: 1 });+ });+});++describe("measuring", () => {+ it("measures every layer of a decomposition (with alpha) and only the last image otherwise", () => {+ const outputs = [+ { url: "/a.png", kind: "image" },+ { url: "/b.json", kind: "text" },+ { url: "/c.png", kind: "image" },+ ];+ const r = (tool: LayerJob["tool"]) => imagesToMeasure(job(tool, { result: { status: "succeeded", progress: 1, message: null, error: null, provider: "mock", outputs } }));+ expect(r("decompose")).toEqual([+ { url: "/a.png", alpha: true },+ { url: "/c.png", alpha: true },+ ]);+ expect(r("upscale")).toEqual([{ url: "/c.png", alpha: false }]);+ expect(r("generate-layer")).toEqual([{ url: "/c.png", alpha: true }]);+ });++ it("hands out the same ids to every layout of one result", () => {+ let k = 0;+ const pool = idPool(() => `x${++k}`);+ const a = pool();+ const b = pool();+ expect([a(), a(), a()]).toEqual(["x1", "x2", "x3"]);+ expect([b(), b(), b(), b()]).toEqual(["x1", "x2", "x3", "x4"]);+ });+});diff --git a/tests/layers.test.ts b/tests/layers.test.tsindex 61f68921..231e6e62 100644--- a/tests/layers.test.ts+++ b/tests/layers.test.ts@@ -42,6 +42,19 @@ import {toLocal,TOOL_MODELS,zipPlan,+ defaultLayers,+ exportScale,+ layerDensity,+ layerExportScale,+ LayerLimitError,+ layersModelFor,+ MAX_NODES,+ MAX_REVISIONS,+ minLayers,+ roomFor,+ scaledSize,+ sourceBoxOf,+ updateNode,type Box,type History,type LayerDoc,@@ -470,4 +483,78 @@ describe("tools and prices", () => {expect(clampLayers("seedream-5-layers", 1)).toBe(3);expect(clampLayers("oss-qwen-layered-control", 2)).toBe(2);});++ it("sends a named element to Layered-Control on the open engine, as the form says", () => {+ // What the Separate layer form posts: the model it shows (the default, or the one picked).+ expect(layersModelFor("split", "open", "oss-qwen-layered", "the guitar")).toBe("oss-qwen-layered-control");+ expect(layersModelFor("split", "open", undefined, "the guitar")).toBe("oss-qwen-layered-control");+ expect(layersModelFor("split", "open", "oss-qwen-layered-control", "the face")).toBe("oss-qwen-layered-control");+ // Control needs a name; without one the plain model splits.+ expect(layersModelFor("split", "open", "oss-qwen-layered-control", " ")).toBe("oss-qwen-layered");+ expect(layersModelFor("split", "open", undefined, undefined)).toBeUndefined();+ // Cloud models and the decomposition take the prompt as an instruction.+ expect(layersModelFor("split", "cloud", "seedream-5-layers", "the guitar")).toBe("seedream-5-layers");+ expect(layersModelFor("decompose", "open", "oss-qwen-layered", "the guitar")).toBe("oss-qwen-layered");+ expect([defaultLayers("decompose", "seedream-5-layers"), defaultLayers("split", "oss-qwen-layered"), defaultLayers("split", "oss-qwen-layered-control")]).toEqual([8, 3, 2]);+ expect([minLayers("oss-qwen-layered-control"), minLayers("oss-qwen-layered")]).toEqual([2, 3]);+ });+});++describe("exports keep every layer's detail", () => {+ it("renders at the densest visible layer's scale, kept to 8192 px", () => {+ const d = doc([node("bg", 0, { w: 960, h: 720, natural: [960, 720] })], 960, 720);+ expect(exportScale(d)).toBe(1);+ // A 4× upscale of the whole picture, laid over it.+ const up = addNodes(d, [node("up", 0, { w: 960, h: 720, natural: [3840, 2880] })]);+ expect(exportScale(up)).toBe(4);+ expect(scaledSize(960, 720, exportScale(up))).toEqual([3840, 2880]);+ // Hidden layers don't count; a crop counts its own pixels.+ expect(exportScale(updateNode(up, "up", { hidden: true }))).toBe(1);+ expect(layerDensity(node("c", 0, { w: 100, crop: [0, 0, 300, 150], natural: [1000, 1000] }))).toBe(3);+ // Enlarged past its pixels: the document's own size, never smaller.+ expect(exportScale(doc([node("big", 0, { w: 400, natural: [100, 50] })]))).toBe(1);+ // Capped on the long side.+ const huge = addNodes(doc([], 4000, 3000), [node("x", 0, { w: 4000, h: 3000, natural: [16000, 12000] })]);+ expect(scaledSize(4000, 3000, exportScale(huge))[0]).toBe(8192);+ // A cropped download: the layer's own density, capped on its box.+ expect(layerExportScale(node("u", 0, { w: 100, natural: [400, 200] }), [0, 0, 100, 50])).toBe(4);+ expect(layerExportScale(node("u", 0, { w: 100, natural: [100000, 50000] }), [0, 0, 100, 50])).toBeCloseTo(81.92);+ });+});++describe("limits the server enforces", () => {+ it("keeps a layer's first revision and the newest ones", () => {+ let n = node("a", 0);+ for (let i = 1; i <= 70; i++) n = addRevision(n, { src: `/api/files/r${i}.png`, natural: [100, 50], label: `Edit ${i}`, at: i + 1 });+ expect(n.revisions).toHaveLength(MAX_REVISIONS);+ expect(n.revisions[0].label).toBe("Original");+ expect(n.revisions.at(-1)?.label).toBe("Edit 70");+ expect(n.revisions[1].label).toBe("Edit 22");+ expect(n.revision).toBe(MAX_REVISIONS - 1);+ expect(n.src).toBe("/api/files/r70.png");+ });++ it("refuses to grow a project past 200 layers", () => {+ const full = doc(Array.from({ length: MAX_NODES }, (_, i) => node(`n${i}`, i)));+ expect(roomFor(full)).toBe(false);+ expect(roomFor(deleteNode(full, "n0"))).toBe(true);+ expect(() => addNodes(full, [node("x", 0)])).toThrow(LayerLimitError);+ expect(() => duplicateNode(full, "n1", "dup")).toThrow(/up to 200 layers/);+ // Moving, deleting and merging still work at the limit.+ expect(moveNode(full, "n0", 5).nodes).toHaveLength(MAX_NODES);+ expect(replaceNodes(full, ["n0", "n1"], [node("m", 0)]).nodes).toHaveLength(MAX_NODES - 1);+ });+});++describe("where the original sits", () => {+ it("moves with Expand & Crop, so Compare's before lines up with the after", () => {+ const d = initialDoc("/api/files/x.png", 960, 720, 1);+ expect(sourceBoxOf(d)).toEqual([0, 0, 960, 720]);+ const wide = reframeDoc(d, [-160, 0, 1280, 720]);+ expect(sourceBoxOf(wide)).toEqual([160, 0, 960, 720]);+ const crop = reframeDoc(wide, [200, 100, 400, 300]);+ expect(sourceBoxOf(crop)).toEqual([-40, -100, 960, 720]);+ // Documents saved before this was kept: the whole canvas.+ expect(sourceBoxOf({ width: 10, height: 20 })).toEqual([0, 0, 10, 20]);+ });});